Compare commits

..
Author SHA1 Message Date
cflmy 6d6f580d24 docs: lead with Markdown-to-execution film and original View imagery 2026-11-13 12:06:30 +08:00
github-actions[bot] af05f19301 docs: publish cinematic Markdown-to-execution promotional film 2026-11-13 04:05:04 +00:00
cflmy 3201369470 docs: build cinematic 3-view Markdown execution promotion from original screenshots 2026-11-13 12:04:18 +08:00
cflmy 05197378b3 assets: add original procurement View screenshot and Markdown three-view concept art 2026-11-13 12:01:22 +08:00
github-actions[bot] f3b3152f07 docs: render Marqdo 2.7.1 promotional video from existing assets 2026-11-13 03:35:16 +00:00
cflmy 22364f2f1b feat(docs): add reproducible Marqdo v2.7.1 promotional video editor 2026-11-13 11:34:12 +08:00
cflmy b69a90501d docs: feature verified procurement GIF and real Marqdo View screenshot 2026-11-13 11:19:51 +08:00
github-actions[bot] 7ff881f506 docs: capture live procurement CLI GIF and View screenshot 2026-11-13 03:19:13 +00:00
cflmy 9acbe10986 build(docs): reproducibly capture real procurement CLI and View assets 2026-11-13 11:18:41 +08:00
cflmy 81989a26d7 fix(demo): bind numeric quote validity explicitly for contract checks 2026-11-13 11:08:48 +08:00
cflmy cf0ba6dccd docs: launch executable skills with procurement showcase and animated assets 2026-11-13 11:07:57 +08:00
cflmy 0de703f86a debian: include cached orig until its publication is confirmed 2026-11-11 01:04:18 +08:00
cflmy 4907f92d84 debian: stop reapplying the upstream engineering compatibility fix 2026-11-11 00:57:16 +08:00
cflmy eac6921524 view: preserve disclosure state and release CLI 2.7.1 2026-11-11 00:44:32 +08:00
cflmy c0dc18433b Fix 2.7.0 engineering release compatibility and preserve accepted Ubuntu orig 2026-11-10 17:53:08 +08:00
cflmy 7d9af11398 Release 2.7.0: invoke source packaging through its declared Bash runtime 2026-11-10 17:12:51 +08:00
cflmy d9aef957f7 Release 2.7.0: executable handbooks and native user-site workflows 2026-11-10 17:03:06 +08:00
cflmy aa0c4d0f55 release: v2.6.0 — executable library handbooks and readable actions 2026-11-08 23:30:17 +08:00
cflmy c50c515c4a Refactor executable library handbooks and improve document reading 2026-11-08 22:19:11 +08:00
cflmy 16c44588d5 Fix replay policy wire commands and register the agent smoke tool
Send complete op/steps/value records to the Lean decoder for every operation. Preserve companion exit status and a bounded stderr tail on transport failure. Register the smoke fixture read tool explicitly without weakening the allowlist or changing its output assertion.

Validation: 462 library tests and 312 gold tests passed. The repository regression run passed 946 tests with two existing ignored experiments; the previously passed 1000-document scale test was not repeated.
2026-11-08 21:50:01 +08:00
cflmy 5080136d65 Make Web an executable handbook with recursive Markdown layouts 2026-11-08 21:50:01 +08:00
cflmy cc5277d2b5 Make Quantum an executable handbook with verified experiments 2026-11-08 21:50:01 +08:00
cflmyandCursor bb06dad134 Start web skill=tools migration with in-package layout law.
Add root/index and layout skills that force file-partitioned pages and ban
HTML/CSS injection as the default path; wire ext add, docs, and call coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 21:50:01 +08:00
cflmyandCursor 24dcb97354 Document the ext skill=tools development paradigm.
Capture the quantum pilot as a checklist-driven guide: layout, root skill
paths, call/session, narration, i18n, install hygiene, and rollout order.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 21:50:01 +08:00
cflmyandCursor 76aa02846a Clarify quantum agent paths for Bell preparation.
Root skills get a choose-a-path table; circuit modules spell the simulate
handoff; call_cli covers ZH bell and stepwise session probabilities.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 21:50:01 +08:00
cflmyandCursor 0e389f34ec Ship quantum skill=tools tree with call session and ZH package.
Split ext/quantum into index + modules, add marqdo call --effects/--session/--toget,
narrative-ratio checks, and a same-package 量子/ tree so agents can follow a
decision path for Bell demos without inventing a second API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-08 21:50:01 +08:00
cflmy 492790e985 release: v2.5.1 — flowing source annotations and labeled toolbar 2026-11-07 13:08:09 +08:00
cflmy ca434a8bab docs: keep 2.5.0 reader version prose out of branch syntax 2026-11-07 10:11:36 +08:00
cflmy 6195ad1d5d release: v2.5.0 — document reader redesign 2026-11-07 10:06:58 +08:00
cflmyandCursor a87c2154ff release: v2.4.0 oracle journal language values
Expose foreign.oracle_journal/replay_check as values, bump CLI/ext/wasm to
2.4.0, and fix notebook OnceLock wait for MSRV 1.81 so EK can compile.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 15:09:34 +08:00
cflmyandCursor 8f1010f967 Ship oracle journal values, bytecode/frontend hardening, and replay-policy Lean.
Host exposes oracle journals as language values with refuse/copy gates; bytecode and foreign session paths get modularized; applications and verification replay-policy sources land with Lake builds ignored.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-06 15:04:27 +08:00
cflmyandCursor e3d9021bb6 docs: align foreign Strong correspondence with mechanized Thm. corr
Record corr_fresh_functional and host discharge (foreign gold + R1–R3)
for the closed/fresh/functional fragment instead of conformance-only wording.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 20:03:44 +08:00
cflmyandCursor 142ab523d6 release: v2.3.0 Foreign Strong session/handle/replay/arity
Opaque session handles, affine close, replay_check vs oracle journal,
table arity refuse, and Ω∈V_safe gate for the Strong foreign narrative.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 14:46:08 +08:00
cflmyandCursor 82c8d78fd3 release: v2.2.2 V_safe JSON integer refuse on foreign bridge
Align host json encode/decode with Lean ForeignJSON: refuse OOD integers
instead of silent Node distortion; keep decimal-string BigInt author path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 09:43:51 +08:00
cflmyandCursor 58791fc7d9 release: v2.2.1 fix view outline rail under document
Occlusion left .doc-block open and mid-width CSS stacked the Functions/Variables rail below Structure; close the block and stack by panel container width instead.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-30 11:41:49 +08:00
cflmyandCursor 1730f26fc7 release: v2.2.0 call one function in any .mq.md
The same page is the document, the knowledge and the program. marqdo call runs that function with arguments, so reuse, tools and tests do not need a second skill system.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-30 09:07:23 +08:00
cflmyandCursor 4018e9928a fix(ai): stream usage events and accept free-form plan replies
Request stream_options.include_usage, emit usage SSE events for collect_usage,
propagate plan tokens through run, and treat unknown prose decisions as DONE.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-28 11:56:51 +08:00
cflmyandCursor 628e3b6e5d chore(ppa): bump 2.1.5 to 1ppa2 after Launchpad no-log failure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 17:38:04 +08:00
cflmyandCursor 5c6c612edd fix(test): coerce MARQDO_SITE_PORT for MR-01 isolated execute
Env port strings must be json.parsed to int; pin main site to 18220 so
inherited MARQDO_SITE_PORT cannot steal the fixture bind.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 16:05:24 +08:00
cflmyandCursor 41587f319e release: v2.1.5 agent reliability workbench
Bump CLI/wasm/ext to 2.1.5; document ResourceView, ToolSpec, CheckpointV2,
EffectLedger, EKC warm-load, and web short/read lane isolation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 15:39:36 +08:00
cflmyandCursor 298fbd51ea feat(workbench): expose CSV preview text for TablePreview
ResourceView csv render now includes bounded text alongside sanitized
HTML so clients can build interactive tables without re-parsing HTML.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 14:45:05 +08:00
cflmyandCursor 265dfdbcc4 feat(workbench): emit JSON source text and code line locators
ResourceView now carries render.text for JsonPreview/CodePreview and
honors locator.line with capped line locators for navigation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 14:23:00 +08:00
cflmyandCursor 42a43f5ffd feat(workbench): honor ResourceView locator.page as focus_locator
PDF blob views echo the requested page for client navigation without
claiming text extract or OCR.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 14:18:38 +08:00
cflmyandCursor 037a963547 feat(workbench): emit blob_ref for PDF and image ResourceView
Client visual preview consumes the blob; extract/OCR capabilities stay
false so QA-10 honesty holds without cutting the preview path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 14:14:17 +08:00
cflmyandCursor a32638e935 fix(workbench): drop trailing blank lines from CSV ResourceView
Avoid an empty last table row when files end with a newline.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 14:03:40 +08:00
cflmyandCursor 43eebe5671 feat(workbench): add bounded JSON and CSV ResourceView renderers
Serve static application/json and text/csv previews with outline/table
limits and flip extract_formats availability for those media types.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 13:55:35 +08:00
cflmyandCursor e833dc05e2 feat(agent): attach effect ledger watermark on CheckpointV2 save
Persist effects_watermark with resume checkpoints and pass resume_id into
step tool calls so mutating tools share a stable logical_run scope.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 13:48:45 +08:00
cflmyandCursor 11bb7ef277 feat(agent): wire EffectLedger through mutating run_tool
Prepare/start/commit write and execute tools with idempotent dedupe, and refuse
blind retry while ledger state is unknown or interrupted mid-flight (MA-T03).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 13:44:45 +08:00
cflmyandCursor 6bd90bb2d0 feat(agent): ship output channels, ContextPackV2, and effect ledger
Open AgentOutputV1/ContextPackV2 capability bits and add EffectLedgerRecordV1
so CheckpointV2 write auto-resume only unlocks on a safe watermark.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 13:28:03 +08:00
cflmyandCursor 4683f2e067 feat(agent): ToolSpec registry with authorize-before-call
Add ToolSpecV1 register/search/describe/prepare so CALL and native paths share one schema gate; unauthorized and invalid-arg prepares fail with zero executions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 13:18:55 +08:00
cflmyandCursor 5912164039 feat(agent): CheckpointV2 atomic resume and AgentErrorV1
Replace bare resume writes with temp/fsync/rename, mark legacy loads as manual_review, and expose bounded read-only retry decisions while keeping write auto-resume closed without a ledger.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 11:03:39 +08:00
cflmyandCursor 303c06f773 feat(workbench): freeze agent protocols and ship ResourceView v1
Lock M-A0 Error/Tool/Checkpoint/Output/Context fixtures with capability bits off, and land M-A3 static md/txt/code ResourceView (no-exec) behind resource.view.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 10:59:59 +08:00
cflmyandCursor a1086fd6c3 docs: plan cross-repo agent reliability delivery
Lock M-A*/Q-A* sequencing, F01–F20 mapping, and first-slice gates on top of the 2026-10-27 designs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 10:49:20 +08:00
cflmy 6ffe5ceb19 docs: expand executable knowledge design notes 2026-10-27 02:10:54 +00:00
cflmy 6b568aff3d docs: design reliable agent capabilities 2026-10-27 02:10:25 +00:00
cflmyandCursor 16f26d7d60 fix(knowledge): warm-load IR for preflight/find/reuse queries
Stop full recompile on every knowledge preflight by writing ekc/graph/ir.json
and loading it unless --refresh or missing projections, cutting chat预检 wall time.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 09:18:27 +08:00
cflmyandCursor b8265a92aa fix(web): stop short/read/control from filling execute slots
Isolating every short invoke on the 2-slot worker pool caused no_slot under
normal traffic; keep short paths on parent (execute already off-process) and
background-reap after observer disconnect so zombies release slots.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 08:56:56 +08:00
cflmyandCursor 9af929971c fix(web): disconnect≠cancel and isolate short/read/control lanes
Observer SSE close no longer cancels execute by default; short/read/control
bypass parent INVOKE_LOCK via isolated admission, with read_lane=1 and gold samples.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-27 08:44:07 +08:00
cflmyandCursor 2c4fa4bb05 fix(ppa): install only rustc/cargo/std and use disk TMPDIR
Repeated --without flags were ignored by install.sh (last wins), so
rust-docs still filled /tmp and hit quota; prefer --components= and
a home-cache work dir instead of tmpfs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 19:13:48 +08:00
cflmyandCursor 3cabe53da2 release: v2.1.4 isolated HTTP execute (ADR 0009)
Default execute/sse-live/stream to Supervisor worker pool; MR-01 gold;
/_runtime/*; bump CLI/wasm/ext to 2.1.4.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 18:33:33 +08:00
cflmy 58e13ee6d3 docs: add isolated web runtime development design 2026-10-26 05:53:02 +00:00
cflmyandCursor 1b11fe063a fix(web): fail-fast when invoke lock is busy; document single-interp limit
Long sse-live chats held INVOKE_LOCK indefinitely and starved short routes
(UI freeze). Timed try-lock returns interpreter busy → HTTP 503; ADR 0008
records that HTTP is multi-goroutine while Marqdo evaluation stays single-flight.
Also lands plan/delta streaming and soft map guards used by qdagent chat.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 13:27:53 +08:00
cflmyandCursor b792f44556 feat(web): auto sse-live when chat body has stream:true
Upgrade json invoke routes to the M02 EventBus forwarder for OpenAI-compatible
stream requests, and normalize LLM delta frames to message.delta.payload.delta
so tokens flush before run.completed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 09:47:05 +08:00
cflmyandCursor 9ea5bebfc3 chore(release): bump to 2.1.3 (workbench M00–M06)
Ship ModelSelection/RunContext/DocumentView contracts, LLM selection,
view document CLI, and live/F02 evidence. CLI, wasm, and ext pack aligned.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 23:13:27 +08:00
cflmyandCursor c7c329341b feat(workbench): live selection smoke, F02 agent e2e, DocumentView CLI
Hoist llm.ask prompt binding to avoid elevated `p`; prefer reasoning_content
when content is empty; point live/tests at in-tree MARQDO_EXT; add USTC live
gates and mock agent.step selection+resume evidence; view document --out for
read-only browser embed checks. Design stays Partial (not Verified).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 23:05:28 +08:00
cflmyandCursor 8cf5288481 feat(workbench): F14 coalesce, snapshot manifest, and sse drain evidence
Hold analysis locks across compile for concurrent same-snapshot reads,
emit SnapshotManifestV1 for app retention, and add Go drainForward tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 11:13:53 +08:00
cflmyandCursor 69c4e74872 feat(view): project KnowledgeStep kinds into DocumentView nodes
Strengthen F09 read-model coverage so observe/derive/call/iterate steps
appear alongside artifact cards without executing the document.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 11:03:01 +08:00
cflmyandCursor af0bda2e40 test(workbench): add F02 subtask/agent skeleton and cancel bridge evidence
Cover selection env propagation, agent skeleton without llm.llm, step-kinds
DocumentView read purity, and Go cancel-token bridge smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 11:02:25 +08:00
cflmyandCursor 090b026547 test(workbench): harden F-matrix evidence and demote Verified claim
Add dual-endpoint LLM isolation, usage revision replace, cancel/F08/F11
asserts, and mark the design status Partial until remaining F gaps close.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 11:01:02 +08:00
cflmyandCursor 03396afd02 feat(workbench): land M00–M06 runtime contracts and read-only view
Add capabilities/selection/usage/DocumentView/locator/RunContext with
honest probes, LLM messages+cancel, sse-live cancel bridge, and CI
workbench_contracts gate; record design evidence for verified slices.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 10:55:08 +08:00
cflmy 663a8ba2c0 docs: specify runtime and view workbench support 2026-10-24 16:27:08 +00:00
cflmyandCursor dc853fb580 release: bump to 2.1.2 (EK production chain + View V0–V3 bar)
Ship evidence/closure invalidation, verify/adjudicate, reuse_execute and
agent bind/publish gates, document.extract, KnowledgePresentation + SSE
page_token, and upload max_bytes with the 45-test offline gate.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-24 22:52:03 +08:00
cflmy 0b80ff8e50 docs: redesign view knowledge reading experience 2026-10-24 02:51:03 +00:00
cflmyandCursor b8a4ddd38f release: bump to 2.1.1 (executable-knowledge spine)
Ship BoundCall/NarrativeRef/generation CURRENT notes with Cargo, ext pack, README, debian, and release Highlights.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 23:40:35 +08:00
cflmyandCursor 352bc0d2c5 feat: finish remaining EK plan — bookstore chain, closure, 100-unit corpus
Make examples/executable-knowledge runnable on both backends, bind same-module
Type.member paths, add closure digests to locks/impact, and gate 100 corpus
units plus CLI smoke so S4–S6 leftover items have reviewable evidence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 23:34:21 +08:00
cflmyandCursor 8a6d09d582 feat: pure extract, bookstore story subset, and project scan caps
Add artifact.extract_pure for restricted expression lifting, a runnable
bookstore tax story fixture, and G12 discovery limits so oversized or deep
trees fail with explicit diagnostics instead of hanging.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 23:27:05 +08:00
cflmyandCursor dcd3d329d4 feat: land S1–S6 executable-knowledge slices (NarrativeRef through CI)
Add comment-line NarrativeRef steps, generation CURRENT snapshots, frontmatter
sources/applicability, digest-guarded artifact.patch, lock change classes, and
an offline CI gate so the documented S0–S6 path has reviewable evidence.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 23:24:18 +08:00
cflmyandCursor 0e1bfb3359 feat: complete BoundCall dual-backend and reuse bind gate (G02)
Share resolve_for_exec across Tree/Bytecode and semantic projections,
emit bound_calls/dynamic_calls, and require eng_reuse bind_targets before
execute so discovery scores cannot be treated as handles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 23:06:34 +08:00
cflmyandCursor e9ae7ff1ae fix: isolate bytecode bare-name resolve to module scope (G02)
Imported functions shared the flat call table, so bare same-named calls
could silently bind across imports. Scope tags keep path calls working
while rejecting ambiguous bare names on both backends.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 22:54:52 +08:00
cflmyandCursor ecbdd18303 feat: executable-knowledge S0–S1 gate plus effect and MLSP reuse subset
Establish author baseline fixtures and offline tests, make SemanticProject
the sole authority for graph edges, classify named steps, and tighten
local reuse so unknown effects are not pure and MLSP binds by SymbolId.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 22:52:06 +08:00
cflmy bedd53e212 docs: align executable knowledge roadmap with native workflow 2026-10-23 14:25:12 +00:00
cflmy 7674ebb869 docs: audit executable knowledge planning gaps 2026-10-23 13:54:08 +00:00
cflmy 434be9fd52 chore: ignore local release secrets 2026-10-23 13:37:54 +00:00
cflmy ae97891266 release: v2.1.0 — file-scoped occlusion 2026-10-23 12:59:28 +00:00
cflmy aea86746e7 feat: migrate corpus to file-scoped occlusion 2026-10-23 12:45:01 +00:00
cflmy c773503938 Merge branch 'main' of https://github.com/cflmy/marqdo
# Conflicts:
#	tests/migrate.rs
#	tests/occlusion/classic-index.mq.md
2026-10-23 12:11:58 +00:00
cflmy 939e23ee88 refactor: scope markup compatibility per invocation 2026-10-23 12:11:26 +00:00
cflmyandCursor 687c168014 feat(parse): use nested YAML import: maps instead of one-liner binds
Frontmatter imports are now valid YAML (`import:` / `导入:` with bind→target
entries), removing spaced keys. Add `marqdo migrate imports`, hard-error the
old one-liner form, and migrate lib/ext/examples/tests/docs accordingly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 19:33:58 +08:00
cflmy eac9b45263 feat: compile executable knowledge semantic artifacts 2026-10-23 09:16:52 +00:00
cflmy 74b298e80d build: add portable development toolchain setup 2026-10-23 09:00:56 +00:00
cflmy fc7097bae4 test: validate executable knowledge syntax across libraries 2026-10-23 08:47:49 +00:00
cflmy b624084745 feat: classify associated and instance symbols 2026-10-23 08:26:33 +00:00
cflmy 0bbe735c3c feat: add stable executable knowledge symbols 2026-10-23 08:24:10 +00:00
cflmy 92de46aca4 docs: define executable knowledge implementation baseline 2026-10-23 08:06:38 +00:00
cflmy 8bbe017a5e docs: define executable knowledge step architecture 2026-10-23 15:46:02 +08:00
cflmy 1a13989230 fix(ext/ai): 变量引用补反引号;prompt 缺失回退空串
- llm/agent 模板中的变量引用统一加反引号
- ask/stream 在 prompt/path 均缺失时回退空串,避免直接退出
- 修正 stream 分支返回缩进;agent workbook 模板改用 ** 代码块
2026-10-23 14:52:26 +08:00
cflmy 5ad1a07f5c docs(language): 链接语法与知识分层设计声明 + 示例
- []() 零新语法:描述 + 已有类/函数调用,不引入 ref/别名/开关
- # 是类、## 是函数;类.函数 是类调用;跨文档用项目类索引
- 知识分层:原始语料 / 本体 / 单体知识类 / 调用面;出处与还原验证
- 新增 link-syntax、knowledge-layers 设计声明与两组可运行/目标示例
2026-10-23 14:52:23 +08:00
cflmy bcfc763ba4 fix(parse): 孤立 * 行不再 panic(exit 101 → 干净诊断)
qdagent 全仓 labels 扫描期间实测:任何 .mq.md 里有一行只含单个 `*`
(markdown 强调残留)时,`*…* = 返回` 分支同时满足 starts_with/ends_with('*'),
切片 &trimmed[1..0] 越界,整条 labels 扫描被一个文件打死(exit 101)。

修复:斜体返回分支要求 len >= 2,裸 `*` 落回 "unrecognized statement"
干净错误而非崩溃。

实测:
- tests/errors/lone-asterisk.mq.md → check 报 "unrecognized statement: *",
  exit 1(不再 101)
- gold 回归 error_lone_asterisk_line 通过
- cargo test --release 全套件 0 failed
2026-10-22 19:04:25 +08:00
cflmy bf76e069ee release: v2.0.0 — 遮蔽语法落地([描述](实现) / 标签欠据 / 全仓迁移)
Bump CLI, wasm and plugin SDK to 2.0.0; sync ext/VERSION, Cargo.lock,
CHANGELOG (Highlights + 核心表面 Δ), README, release highlights stub,
skills and debian/changelog.
2026-10-22 16:26:29 +08:00
cflmy 9015de26e5 feat(view): M8 遮蔽呈现 — 描述为正文、实现为代码片、桩有徽章;并修复 view 解析模式回归
一、先修回归(用户看到"没渲染"的真因)
view 多处直接用 crate::parse::parse_source 重新解析文件,而 per-file markup:
是在 load 层生效的(M7)。于是任何带 markup: occlusion 的文档在结构区报
"parse/load error: expected ')' after link-index collection",退化成源码视图。
→ 新增 load::parse_source_auto(source):先读 frontmatter 的 markup:,用
  with_markup 包住解析;view 的 4 处解析点全部改用。

二、遮蔽呈现
浏览视图(document.rs / /file):
  <div class="doc-line doc-occl">
    <span class="occl-pre">留存 =</span>              ← 变量名 灰 等宽
    <span class="occl-label">客户留存率,模拟数据</span> ← 描述 正文
    <code class="occl-code">0.42</code>              ← 实现 代码片
  </div>
空载荷换成 <span class="occl-stub">桩</span> 琥珀徽章(title 说明未接通/待补返回值);
前缀的反引号与 ** 都剥掉,与其它行的 mq-anchor 一致。

卡片视图(render.rs / /debug):按 AST 匹配 Expr::Occluded(Assign/Expr/Return),
渲染 card occl-card:徽章「遮蔽」+ 变量名 + 描述 + 代码片/桩。

样式刻意不加虚线下划线(易读成链接):描述即正文,靠代码片边框区分。

验证:
- /file 页面 0 处 parse/load error;7 个遮蔽行全部渲染
  (6 代码片 + 1 桩),文本抽取为「留存 = 客户留存率,模拟数据 [0.42]」
- 4 个单测(裸赋值/粗体赋值/空载荷+嵌套/非遮蔽不误判)
- 全量 cargo test --release 613 passed / 0 failed

未能截图:本机无任何浏览器,puppeteer 的 Chromium 下载被网络阻断;
改为 DOM 断言 + /.preview/occlusion.html 方案对照页由作者目视确认。

文档:doc/design/change-m8-view-occlusion.md
2026-10-22 16:16:32 +08:00
cflmy 8c24d96626 docs(examples): 遮蔽改用裸赋值 名 = [描述](实现),不再包进粗体
用户指出:`**留存 = [客户留存率,模拟数据](0.42)**` 在阅读器/高亮里
描述被粗体吞成"代码味",人话反而不显眼。

改为裸赋值形式(与粗体形式语义完全等价,实测四项一致):
  `留存` = [客户留存率,模拟数据](0.42)
  `待接` = [搜索接入,接口未接,待开发]()
  `取第一` = [第一颗](access(`篮子`, "1"))
  `个数` = [篮子有几颗](table.len(`篮子`))
  `表取` = [用 table.get 读同一个键](table.get(`饮品价`, "美式"))
  `长度` = [名字长度](len(`名`))

等价性实测(b.mq.md):留存=0.42 / 待接=None / 取第一=苹果 / 个数=2,
check 只报同一条 label.empty_payload,labels 命中同样两处。

并在第 5 节补一句为什么这样写:粗体是给"表达式赋值"用的紧凑写法,
而遮蔽的前提是"描述给人读",所以描述不该被强调形式包住。

顺带说明(不是本次改动):view 的代码区展示的是**高亮后的源码**,
不是 Markdown 渲染,所以 `[..](..)` 在两种写法下都不是可点链接;
真正的呈现改进(描述为正文、实现为代码块)属于 M8 未做部分。
2026-10-22 16:03:59 +08:00
cflmy 4a2f5bf226 docs(examples): 新增 examples/syntax-tour — 一页跑通全部现行语法
十个板块,全部可执行(marqdo run 实测通过):
1 变量与插值  2 函数与契约  3 调用四种形态(> 前缀 / 括号位置 / 逗号 /
  嵌套 / 带空格函数名)  4 取值 access / table.len / table.get
5 遮蔽(普通 + 空载荷桩)  6 循环(遮蔽循环 + while 式递减)
7 分支  8 表格三态(竖表 List / 横表 Map / 行向 List[Map])
9 值类型  10 收尾

写作过程中踩到的真实约束(都已按现行语义修正):
- `##` 是函数定义,正文分节不能用 `##`(改用散文分隔行)
- 函数内看不到模块级变量,`计税` 改为自包含的分支查表
- 反引号插值只接受变量名,不能写 `len(`名`)`,需先算出变量
- `()` 内的 payload 是表达式,空格形调用要写成括号形
  (`table.get(表, 键)` 而非 `table.get map=… key=…`)

实测:run 输出 25 行符合预期;check 仅 1 条有意保留的
label.empty_payload(正是第 5 节要演示的空载荷规则);
labels 命中 2 个已申报桩。
2026-10-22 15:57:48 +08:00
cflmy 86e921e959 feat(migrate): 支持多路径;docs: 体量审计修正两条不成立的判断
- migrate labels 接受多个 PATH(与 labels 一致);全仓干跑幂等:
  lib/ext/cli/examples/public 均为 0,tests 仅剩刻意保留的 classic 样例 1 处
- 审计修正:
  * html.rs 皮肤"重复声明基础 CSS" —— 实测 312 vs 128 条规则、选择器零重叠,不成立
  * debug_page "复刻 shell" —— 仅 head/favicon 约 10 行相似,它没有 nav/topbar,不成立
  * HostFn 五表合一标记为已完成(−404 行)
- 结论:可机械消除的重复已清完;剩余体量全是特性实现

全仓校验:63 个文件 check 零诊断(label.* 全 0);
cargo test --release 609 passed / 0 failed。" && timeout 300 git push origin main 2>&1 | tail -1
2026-10-22 15:52:22 +08:00
cflmy b196a44685 refactor(host): HostFn 五张表合一 — HOST_FN_TABLE 单一来源(−404 行)
202 个宿主函数的元数据原本分散在 from_u16 / from_name / name /
required_params / optional_params 五个手写 match 里,必须同步维护,
审计已记录过 from_name 与 name() 的漂移。

改动:
- 新增 HostFnDef + HOST_FN_TABLE(203 项:id, 变体, 规范名, 必填, 可选)
- from_u16 按 id 查表;name / required_params / optional_params 按判别值查表
- call_host 的 202 个一行臂保持不变(只集中元数据,不动分派逻辑)
- from_name 保留:它是别名注册表(http_get/中文别名…),语义与规范名不同

等价性证明(快照比对):
1. 先在旧实现导出全部 203 项的 (id,name,required,optional) 到 TSV
2. 合并后用同一段代码再导出
3. diff 两份 → 完全一致;快照测试用后即删

长期守护(4 个不变量测试,上一轮已加):
id↔as_u16 往返、name→from_name 往返、规范名唯一、required/optional 不重叠。

验证:cargo build 零警告;cargo test --release 609 passed / 0 failed。
行数:dispatch.rs 2052 → 1648;src 合计 53,040 → 52,668。

文档:doc/design/change-hostfn-table.md
2026-10-22 15:51:26 +08:00
cflmy c8ed5bffb7 docs: 体量审计更新 — 插件 SDK 完成(净减 674 行),合计 67,786 2026-10-22 15:49:26 +08:00
cflmy fb135ae2f8 refactor(plugins): 抽出 marqdo-plugin-sdk — ABI 前言从 5 份变 1 份
新增工作区成员 crates/marqdo-plugin-sdk:ABI 类型、HOST_* 静态回调、
host_strdup/set_out/set_err/parse_args/reply/host_query_json(_with)/
take_host_string/init_plugin,以及生成四个 #[no_mangle] 导出的
marqdo_plugin! 宏。ABI 常量、符号名、结构体布局一律未变。

5 个插件改为依赖 SDK + 一行宏调用:
  agent  1237 → 929  (-308)
  quantum 1045 → 835 (-210)
  linalg  688 → 524  (-164)
  llm     405 → 278  (-127)
  demo    170 → 73   (-97)
  SDK 新增 232 行 → 净减约 674 行

迁移中发现并修正三次"编译通过但语义已变":
1. 注册项抽取漏 11 项 —— 正则 [a-z_0-9]+ 匹配不到 mcp_server::agent_mcp_serve、
   sandbox::* 这类路径限定函数名;改为允许 :: 后重抽。
   已用脚本逐项比对 (名称, 参数串, 函数) 三元组:agent 63/63、quantum 41/41、
   linalg 31/31、llm 2/2、demo 2/2,全部 0 差异。
2. mcp_client 被误判死模块(删 327 行后才发现 agent_mcp_client 正注册它)→ 恢复。
3. 量子插件两个"未使用"函数删除时连带吃掉 density_from_amps/flat_to_nested
   → 恢复原文件并改为 #[allow(dead_code)]。

验证:cargo build --release(含 5 个插件)零警告;
cargo test --release 609 passed / 0 failed;
量子金样实跑 p00-ok / p11-ok / ping-ok。

文档:doc/design/change-plugin-sdk.md
2026-10-22 15:49:13 +08:00
cflmy 69fcdd6227 docs: 代码体量审计 — 53k 行构成、已清 14.5k 冗余、剩余为特性面
把账算清楚,避免行数多=冗余多的误判:
- src 53,072(其中 5,220 是内联测试)+ plugins/crates 15,423
- 最大的 10 个文件逐一标注性质(html.rs 4,451 行里 3,861 是页面皮肤字符串)
- 已清除 14,235 + ~400 行,逐项列提交号
- 顺带修出的 4 个真实缺陷(Access 隐式判别值、escape_js_string 漏 U+2028/2029、
  view 双 handler 路由、HOST id 稀疏无测试守护)
- 剩余可精简项:插件 ABI SDK(~550)、html 皮肤(~250)、debug_page(~120)、
  HostFn 五表(~450),合计约总量 2%,标注风险
- 结论:继续压体量的正确方向是砍特性,而不是在特性内部找重复(已找完)
2026-10-22 15:44:37 +08:00
cflmy deac53d0f5 refactor(view): AST 遍历器合流 — walk_stmts / stmt_line 收进 ast
三处各自实现的「深度优先遍历函数体」合并为一个:
- ast::walk_stmts(fun, &mut |stmt| ...):body + 分支臂 + 循环体 + 子函数
- ast::stmt_line(stmt):语句行号(原 view::document 私有副本)

改造:view/annot.rs::fun_stmt_lines、view/document.rs::index_stmt_lines
(annot 的 collect_name_sites 保留自己的收集逻辑,只借遍历)

cargo build 零警告;cargo test --release 609 passed / 0 failed。
view/annot.rs -30 行、view/document.rs -41 行。
2026-10-22 15:44:20 +08:00
cflmy 932403237a test(host): HostFn id/name/params 一致性测试;refactor: 转义函数去重
一、先暴露问题:写 4 个一致性测试后发现——
- id 空间是**稀疏**的(10 个退役 id),不是连续的;测试按"每个已分配 id 都能还原"重写
- Access 变体只有隐式判别值,补 `= 212` 使之显式(避免重排时静默错位)
- 四个测试现在锁定:id→as_u16 往返、name→from_name 往返、名称唯一、
  required/optional 不重叠且无重复参数。审计提到的 from_name/name 漂移由此可被捕获。

二、转义去重
- urlencoding_encode 与 urlencoding_path 逐字相同 → 合并为 urlencoding_path(pub(crate))
- escape_js_string 两份:debug_page 的副本漏了 U+2028/2029 转义(真实缺陷)
  → 保留 html 的完整版并 pub(crate),debug_page 改为引用

cargo build 零警告;cargo test --release 609 passed / 0 failed(605 + 4 个新测试)。
2026-10-22 15:42:42 +08:00
cflmy a14a6e221d refactor: 删除无调用点的死代码(审计项)
- src/parse/mod.rs: parse_italic_assign(17 行,0 引用)
- src/host/sandbox_fs.rs: unavailable
- src/knowledge/extract.rs: stem_of
- src/knowledge/lifecycle.rs: _system_time_now
- src/debug/ctrl.rs: action_channel
- 连带清理 3 处随之失效的 import

cargo build 零警告;cargo test --release 605 passed / 0 failed。
src 行数 53,079 → 52,96x。
2026-10-22 15:40:31 +08:00
cflmy 8b0ea9ed7a refactor: 精简三处重复 — as_text×18、catalog 助手×4、view 路由 34 臂
按审计结论清理冗余(不改变行为):
1. as_text:17 个 host 模块各自复制同一函数(两种措辞),合并为
   crate::host::as_text(统一 "{label} needs text",无测试依赖旧措辞)
2. catalog.rs:extract_fm_field / extract_nested_by / extract_fm_list /
   yaml_escape 与 knowledge::util 逐字相同,改为直接引用
3. view/mod.rs:handle 29 臂 + handle_debug 5 臂折叠成两张路由表
   (Notebook/Debug/Action 三种处理器),每臂原本重复同一 api_debug_post 包装

实测:
- cargo build 零警告;cargo test --release 605 passed / 0 failed
- view 服务实测:GET / → 200;POST /api/debug/continue → 200(真实响应
  {"error":"unknown session"});POST /api/nope → 405

行数:view/mod.rs -99(168 删 69 增);src 合计由 53,276 降至约 53,000
(as_text 18 文件各约 6 行、catalog 4 函数约 70 行)

期间发现并修正一处真实风险:路由臂分布在两个 handler(handle / handle_debug),
首次只替换了一个导致 debug 路由 405;已按 handler 分别建表并由实测覆盖。
2026-10-22 15:39:18 +08:00
cflmy 6ae0d39e5a feat(labels): 兼容文档里的 labels pending / labels search 写法
设计文档写的是 `labels pending` / `labels search --grep`,CLI 是扁平参数。
把 pending/search 作为无意义位置词过滤掉,使两种写法都可用(不动参数语义)。
实测:labels pending --count → 2;labels search --grep 联调 --count → 1。
全量 605 passed / 0 failed。
2026-10-22 15:34:55 +08:00
cflmy 307c8efa81 feat(labels): 支持多路径扫描;docs: 里程碑全量完成状态与变更文档索引
- labels 接受多个 PATH(默认 .),合并去重后扫描
- occlusion-syntax.md §13.1 记录 M0–M10 全部完成,附 11 份变更文档索引
- 全仓校验:98 个文件 check 零诊断(label.* 全为 0,确认无噪音)
- cargo test --release 605 passed / 0 failed;0 编译警告
2026-10-22 15:34:29 +08:00
cflmy 34b0911218 feat(labels): M8 债务棘轮 — --baseline + --fail-on-increase
规则:未完成项只许减少,不许增加。
- 台账不存在 → 建立(写入当前计数)并提示,exit 0
- 当前 > 台账 → 失败并提示"未完成项增加了 K",exit 1
- 当前 ≤ 台账 → 通过;若减少则**收紧**台账(N → M)

为什么减少即收紧:否则债务可先降后升,棘轮形同虚设;
收紧后回退到旧数量同样失败(测试第 4 步验证)。

台账格式 {"count":N,"words":[…]},记录词集使"口径变更"可审计。

为什么用棘轮而非硬门禁:硬门禁(必须为 0)会让存量债立刻红一片、逼人关检查;
棘轮做到"老账不追、新账必拦",与防疲劳机制的结论一致。

呈现面复核:expr_display / view 把遮蔽渲染为 [描述](实现)、桩为 [描述](),
实测 view output 页面含 access(;未做桩徽章——桩已是显眼形状,再加装饰是噪音。

测试:四步集成用例(建账 → 增加失败 → 减少收紧 → 回退再次失败);
全量 605 passed / 0 failed(M7 后 604 + 1)。

文档:doc/design/change-m8-ratchet.md
2026-10-22 15:34:07 +08:00
cflmy 4488a3cb70 feat(migrate): M7 迁移与版本门 — per-file markup + migrate labels + 全仓迁移
原计划的"翻转默认 + 旧形硬报错"不可行:`[键](集合)` 与 `[描述](实现)` 外形相同,
翻转会让 506 处取元静默变义,硬报错又拿不到证据。改为**按文件声明**。

一、per-file markup
- frontmatter `markup: occlusion`(或 `标记: 遮蔽`)决定该文件模式
- load.rs 先取模式,用 parse::expr::with_markup(线程局部压栈)包住解析
- 同一进程可同时加载两种模式的文件(imports);MARQDO_MARKUP 仍作进程默认
- 好处:迁移逐文件、可增量、可回滚,不存在半迁移的静默错义

二、`marqdo migrate labels [--write|--json]`
改写规则:
  [键](集合)      → [键](access(集合, "键"))
  [`名`](集合)    → [名](access(集合, `名`))
  - [项](集合)    → - [项](遍历 集合 为 项)

安全模型:改写 → 重解析 → 证明等价 → 才写
- 原文件按 classic 解析得 AST-A;改写后按 occlusion 解析得 AST-B
- 反归一化 B(标签与键同名且 payload 为 access 的遮蔽还原成 Index)
- Debug(A) == Debug(反归一化(B))(抹掉行号)才写入,否则原文件一字不动

只改代码行(LineKind::Code);表格行只改 **…** 单元格,散文 markdown 链接不碰;
链式索引由内向外改写,已迁移的有守卫不二次改。

三、access 提升为宿主函数 HostFn::Access(u16 id 212)
与旧取元逐字一致(Map 按键 / List 1-based / 缺键 missing map key);
进 HostFn 是为了两个后端共用同一实现,interp 里的特例已删除。

四、顺带修的两处真实语义缺陷
1. payload 继承外层"文本模式":`f text=[k](access(c,k))` 中 access 不被当调用
   → `()` 内永远允许 callee(args)
2. 遮蔽形状判定过宽:`[问候] ([格式化] "Bo")` 误判为遮蔽
   → 要求 `]` 后紧跟 `(`,否则落回方括号调用

五、全仓迁移结果
migrate labels: 256 index, 23 loop, 80 file written;0 文件被等价性拒绝;
迁移后 cargo test --release → 604 passed / 0 failed;再跑迁移幂等。

等价性检查先后抓出 4 类改写 bug(表格散文链接、payload 文本模式、链式索引、
遮蔽与方括号调用混淆),每类都是先拦下再修工具,未污染文件。

测试:6 个单测 + 3 个集成(干跑不写盘 / 写入后运行输出不变且幂等 /
等价失败文件不动);全量 604 passed / 0 failed(M3 后 595 + 9);双后端一致。

文档:doc/design/change-m7-migration.md
2026-10-22 15:33:31 +08:00
cflmy 9dbcc728b6 docs(design): 记录里程碑进度 — M0/M1/M2/M2.5/M3/M4/M5/M6/M9/M10 已完成,M7/M8 待做 2026-10-22 15:23:54 +08:00
cflmy 0405a60d68 feat(lang): M3 access 内建与遮蔽循环 — 为 M7 迁移准备等价语义
access(集合, 键)(别名 取/取值):
- 复用 builtin_footnote_get,与旧 [键](集合) 语义完全一致
  (Map 按键 / List 1-based 下标 / 缺键报 missing map key,不静默 None)
- 不新增平行实现,避免两套索引语义漂移
- 用途:M7 把 506 处 [k](c) 机械改写成 access(c, k),语义零漂移

遮蔽循环:- [描述](遍历 集合 为 变量)
- 仅 occlusion 模式识别;接受 遍历/for 与 为/as/in
- 描述存入 Stmt::ForEach.label(Option<String>),供 M8 渲染/诊断

为什么先 M3 后 M7:迁移目标必须先存在且等价,否则就是"边迁移边发明语义"。

实测:
  access(`表`,"键") → 值;access(`列`,2) → 二;
  缺键 → missing map key(与旧取元同一错误)
  - [篮子里的每个果子](遍历 `列` 为 `果`) → 果=一 / 果=二

测试:2 个集成(含缺键错误保真);全量 595 passed / 0 failed(M5 后 593 + 2)

文档:doc/design/change-m3-access-and-loop.md
2026-10-22 15:23:36 +08:00
cflmy 409b8df2cb feat(check): M5 隐式遮蔽 — > 调用上方的叙述作为描述(默认关闭)
规则:`>` 调用上方的叙述段即其"描述";段内反引号实体必须被该调用用到,
或能解析到模块/内置,否则报 label.implicit_stale(warning)。
段落边界:紧邻上一行起,允许一个分隔空行(blockquote 前常空一行),
遇第二个空行/标题/代码行即止。

关键决策:**默认关闭(--implicit-labels 开启)**,依据是实测噪音:
- 初版(任何反引号都算断言):lib+ext/ai 上 6 条警告,**全为误报**
  (`## open`、`{ path, kind }`、`source=`、`exec`/`net`)
- 加"实体名形状"过滤后:2 条
- 再加默认关闭:**0 条**
理由:描述一个调用可以用任意措辞,机械校验必然模糊;
默认开启就制造疲劳(违背 warning-fatigue-control)。这与 L1 不同:
L1 是"能证明才报",隐式检查是"可疑就报",必须 opt-in。

实体名过滤:首字符字母/_/非ASCII,其余字母数字/_/./非ASCII非空白
→ 排除 `## open` / `{ path, kind }` / `source=` / `path=`。

用法:marqdo check 文件 --implicit-labels

测试:3 个集成(默认静默 / opt-in 报不一致 / opt-in 对一致描述仍静默,
后两条是反向验证"不乱响");全量 593 passed / 0 failed(M6 后 590 + 3)。

文档:doc/design/change-m5-implicit-occlusion.md
2026-10-22 15:21:23 +08:00
cflmy 6bba0be6d2 feat(mlsp): M6 T1 会话内陈旧检测 — repair_apply 前后对照 + session.summary
机制:repair_apply 内同一作用域已同时持有 source(改前) 与 new_source(改后),
所以「描述是否还成立」可纯内存判定,无需 git/台账/exec:
  stale ⟺ 标签文本未变 ∧ payload 指纹变了
按 (标签文本, 出现序号) 配对 → 移动代码不误报。

协议:
  请求加可选 check_labels(默认 false,零开销零噪音)
  响应加 labels.stale[{label,line,code_past,code_now}] + newly_seen
  新增 session.summary → {labels_stale_seen, labels_fixed, labels_outstanding, items},
  返回后清零(客户端收尾调用一次即闭合,不主动打屏)

取舍:
- 标签变了 → 不报(作者改描述即"已复核"信号)
- 新标签 → 不报(无历史可比)
- 指纹用 Debug:只需进程内一致;跨版本稳定指纹留给 T2/T3
- code_past/code_now 用 view::expr_display 渲染成人可读的表面语法

实测:
  改 payload 0.1→0.2、标签不变 → stale 且带 code_past="100 * 0.1" / code_now="100 * 0.2"
  同时改标签 → stale: []
  session.summary → stale_seen=1, outstanding=1, items=["按税率算总价"]

测试:3 个集成(含反向验证"改描述即复核不误报");
全量 cargo test --release:590 passed / 0 failed(M10 后 587 + 3)

文档:doc/design/change-m6-t1-session.md
2026-10-22 15:19:17 +08:00
cflmy 1c90312c02 feat(ai): M10 把「接不了就申报」写进 agent 提示词(standing + how-to-act)
两处:
1) how-to-act 协议段(每轮都带):无法真正接通的capability 不许静默伪造、不许声称完成,
   改写成带状态的遮蔽,例如 [按关键词检索,接口未接,待开发](None);
   桩必须能跑并写清返回值(None 亦可);收尾用 labels.search 自查。
2) 默认 standing(p):追加一句"接不了就在描述里申报(待开发/模拟),别假装成功"。

为什么两处:standing 定基调(每轮开头),how-to-act 定动作(每轮),
只写一处会被长上下文冲淡或缺动机。
设计要点:给范式而非规则(可直接抄)、给返回值要求(对应 label.empty_payload)、
给自查动作(labels.search)、用英文与既有协议一致。

验证:marqdo check ext/ai/agent.mq.md(occlusion 模式)通过;
grep 确认两处文本落地;全量回归 587 passed / 0 failed(不改逻辑)。

文档:doc/design/change-m10-engineering-habits.md
2026-10-22 15:17:43 +08:00
cflmy fd0cfcb566 feat(labels): M9 两级词表检索 — labels CLI + MLSP labels.search
第一级(内置,数据常量):六组关键词 —— 未完成/假数据/示例/实验/废弃/待校验,
pending = 未完成 ∪ 假数据。作用是默认查询、LLM 范例、跨项目可比。
第二级(参数):--grep 替换,--also-builtin 并集,--group 选组。
**词表是数据不是语法**:扩充它不改任何解析规则。

CLI:
  marqdo labels .                              # pending 口径
  marqdo labels . --grep "联调"                 # 自定义替换
  marqdo labels . --grep "联调" --also-builtin   # 并集
  marqdo labels . --group 示例,实验
  marqdo labels . --count / --json

MLSP:{"method":"labels.search","params":{path|source, grep?, also_builtin?, group?}}
→ {"ok":true,"words":[…],"count":N,"hits":[{line,unit,label,words,has_payload}]}
与 CLI 共用同一份 label::search。

检索语义 v1:子串匹配(CJK 无词边界)、多词 OR、英文大小写不敏感;
误判只影响计数,输出带描述原文可人工判断;不做否定语法(留 v1.1)。

测试:4 个集成(pending=2 / grep 替换=1 / also-builtin 并集=3 / MLSP 返回 hits);
全量 cargo test --release:587 passed / 0 failed(M4 后 583 + 4)。

实测:
  pending → 2 命中("待开发"、"模拟"两处)
  --grep 联调 → 1 命中
  --grep 联调 --also-builtin → 3 命中

文档:doc/design/change-m9-label-search.md
2026-10-22 15:16:39 +08:00
cflmy 6dd0ce47b1 feat(check): M4 L1 引用一致性 — 描述里的反引号实体必须可解析(label.ref_dangling)
规则:描述里的 `名字` = 断言,必须能解析 ——
要么 () 的实现用到它,要么文档定义了它(函数/参数/import 绑定/frontmatter 键),
要么是内置函数。否则报 label.ref_dangling(error)。

只认反引号(可证伪原则):普通汉字不参与判定,避免海量假阳性;
代价是作者不写反引号就得不到保护,这是刻意的——机器只校验它看得懂的断言。

实现:
- refs(label):扫描成对反引号取内部(未闭合/空串忽略,不 panic)
- payload_idents(payload):Var / callee / path 段 / receiver / [k] 变量键 / 插值变量
- module_symbols(module):函数与子函数、参数、import/use 绑定、frontmatter 键
- 内置函数用 crate::host::HostFn::from_name 判定
- OcclusionSite 增加 payload_idents,collect 阶段一次算好

实测:
  悬空 → "描述引用了不存在的实体:`税率` ..." 1 error, exit 1
  可解析(payload 变量 / len 内置 / `> 加 1 2` 行内调用)→ 零诊断

测试:3 个单测(抽取/多引用与散文混排/未闭合不 panic)
+ 2 个集成(悬空 exit 1;三类可解析零诊断)
全量 cargo test --release:583 passed / 0 failed(M2.5 后 578 + 5)

文档:doc/design/change-m4-label-refs.md
2026-10-22 15:14:50 +08:00
cflmy 1a94cc8490 feat(check): M2.5 遮蔽标签诊断 — label.missing(error) / label.empty_payload(warning)
新增 src/label.rs:
- OcclusionSite { label, has_payload, line, unit }
- collect(module):遍历函数/分支/循环/表达式收集遮蔽点(描述只读,不产生读引用)
- check(module, path):产出两条诊断

两条诊断:
- label.missing(error):[](...) 描述为空 —— 写一句人话,或改用不带遮蔽的写法
- label.empty_payload(warning):[描述]() 载荷为空 —— 写清桩返回什么(None/0),或补实现
warning 不影响退出码;JSON 出口自动继承既有 schema(含 doc_quote/span/suggestion)。

接入 check_module:walk 之后 extend(crate::label::check(..)),保持一行;
M4(引用一致性)与 M9(检索)都往 label 模块加,check 不再膨胀。

测试:
- 3 个集成(tests/occlusion.rs):空描述 exit 1、空载荷 exit 0、干净样例无诊断
- 全量 cargo test --release:578 passed / 0 failed(M2 后 575 + 3)
反向验证:干净样例必须零输出,证明不会误响。

实测:
  MARQDO_MARKUP=occlusion marqdo check empty-label.mq.md    # 1 error, exit 1
  MARQDO_MARKUP=occlusion marqdo check empty-payload.mq.md  # 1 warning, exit 0

文档:doc/design/change-m25-label-diagnostics.md
2026-10-22 15:13:33 +08:00
cflmy 11417c42e0 feat(lang): M2 遮蔽语法 [描述](实现) — 描述不执行,payload 是唯一执行体
新增 Expr::Occluded { label, payload: Option<Box<Expr>> }:
- [] 描述:自由文本,永不执行(仅用于检索/统计/过期校验)
- () 实现:唯一执行体;为空时值为 None(空载荷桩)
- 支持嵌套遮蔽、描述含空格与中文标点、\] 转义

关键决策:**模式开关,暂不切换语义**
[键](集合) 与 [描述](实现) 外形完全相同;M2 若直接改语义,全仓 506 处取元会
静默变成"遮蔽整个集合"(同形换义,文档点名的最坏一类)。
故 M2 只实现能力:
- 默认 Classic:MARQDO_MARKUP 未设 → [a](b) 仍是取元
- 纯度 Occlusion:MARQDO_MARKUP=occlusion/purity/1/on → 遮蔽
M7 才迁移语料、翻转默认、对旧形报 syntax.legacy_index 硬错误。

实现:
- ast.rs 新节点
- parse/expr.rs:Markup 枚举 + set_markup_default + parse_expr_markup(显式模式,
  避免测试依赖全局) + parse_occluded(描述扫描到 ]、\] 转义、必须紧跟 (、
  空载荷 → None)+ Parser.markup 字段
- interp.rs:有 payload 求值 payload,否则 None;collect_decl_reads 递归 payload
- bytecode/compile.rs:编译 payload(空则 Op::None_),双后端一致
- view/render.rs:expr_prec 渲染 [描述](payload) / [描述]()
- parse/mod.rs:pub mod expr
- main.rs:MARQDO_MARKUP 环境变量(init_markup_from_env)

测试:
- 8 个单元(值直通/空载荷/描述空格标点/转义/嵌套/classic 仍取元/缺括号报错)
- 3 个集成 tests/occlusion.rs + tests/occlusion/*.mq.md
- 全量 cargo test --release:575 passed / 0 failed(M1 后 565 + 10)
- tree 与 bytecode 双后端一致

文档:doc/design/change-m2-occlusion.md
2026-10-22 15:11:59 +08:00
cflmy 13012cac0e refactor: 精简 — 删除归档的 Rust web 插件(14,235 行)
审计结论:plugins/web-rust-archive/ 不是 Cargo workspace 成员、默认不构建、
无任何脚本/代码引用,官方 web 插件早已是 Go 版(plugins/web/ + libweb.so)。
仅作为"参考"留在树里,占 Rust 代码量约 18%。

删除内容:
- plugins/web-rust-archive/(31 个文件,14,235 行 Rust,528K)
- 更新三处指向:Cargo.toml 注释、plugins/web/README.md、ext-web-go-rewrite.md,
  说明历史保留在 git 中
- CHANGELOG Unreleased 记录此次精简

验证:cargo build --release 通过;cargo test --release 565 passed / 0 failed。

这是「不要让冗余代码毁坏 marqdo 设计」的第一步;后续按审计报告继续:
HostFn 元数据表合一(~400L)、plugin ABI 共用 SDK(~550L)、
catalog 复用 knowledge 助手(~140L)、view 路由表化(~130L)、
as_text 19→1(~90L)、view/html 字符串拆分与去重(~300L)。
2026-10-22 15:09:31 +08:00
cflmy 5a0f4ed747 refactor(parse): M1 收尾 — 删除重构后变成死代码的两个函数
- parse_call_arg_value_prefer_var:统一成 parse_call_arg_value_mode 后无调用点
- Parser::new_plain:改回 new(唯一构造点)

cargo build --release 警告清零;cargo test --lib 248 passed。
2026-10-22 15:08:55 +08:00
cflmy 05b8edc186 feat(parse): M1 ()内调用语法 — ) 终止 / 逗号 / 嵌套 / 带空格 callee
实现 M1(occlusion-syntax.md §13):把 `(…)` 变成一等调用外形。

四件事:
1. `)` 是参数终止符(历史缺陷:末个位置实参吞掉 `)`,导致 `加(31)` 报
   unknown function `加(31`)
2. 可选逗号分隔:`加(1, 2)` / `加(1 2)` 等价
3. 嵌套调用:`加(加(1 2), 10)` → 13
4. **callee 可含空格**:`加一 号(31)` → 32 —— 这是缺陷 D8 的结构性解法
   (`(` 是明确分隔符,空格不再参与切词)

实现要点:
- split_first_token / find_next_arg_boundary 重写为深度感知扫描器:
  跟踪 ()[]{} 嵌套 + 字符串 + 反引号;顶层 )/空白(括号形还含逗号)终止 token
  且不吞终止符;字符串内逗号不受影响。
- 新增 try_paren_call:callee = 第一个 '(' 之前的全部文本。
  护栏:callee 含 = [ ] ( ) " ' 即拒绝(避免把 `text=a(b)` 具名实参与
  `trim [stdout](…)` 方括号实参误判为调用);反引号允许(保留 `obj`.方法 写法)。
- 表达式级 postfix 调用(parse_primary 裸词分支,要求 `(` 紧跟)。
- is_bracket_callee_inner 允许空格:[加一 号] 31 亦可用。

关键决策(回归测试逼出来的):括号形与空格形的**参数值语义不同**——
括号形是表达式(允许嵌套调用),空格形仍是文本(`source=print(2+2)` 必须保持文本,
否则 foreign.run_lang 报 source must be text)。用 Parser.allow_paren_call +
parse_call_arg_value_mode(input, prefer_var, allow_call) 区分。

测试:新增 11 个单测(TDD:先 10 红后全绿);全量 cargo test --release
565 passed / 0 failed(基线 554 + 11);tree 与 bytecode 双后端输出一致;
端到端 marqdo run 六用例符合预期。

顺带:删除变成死代码的 end_of_quoted_string(编译警告清零)。

文档:doc/design/change-m1-paren-call.md(含决策依据、护栏表、边界)。
2026-10-22 15:08:02 +08:00
cflmy 8926f7bed6 docs(design): M0 语义冻结 — 遮蔽语法系列文档标记 Accepted
用户已批准:内置词表先按现方案(六组、两级检索),后续可调。
本提交只改文档状态,不动代码:

- occlusion-syntax.md:Proposed → Accepted · 实施中(M0 起)
- occlusion-description-and-search.md:Proposed → Accepted · 实施中
- warning-fatigue-control.md:Proposed → Accepted(机制基线:stale 是变更报告)
- staleness-providers.md:Proposed → Accepted · 修订
- t1-session-staleness.md:Proposed → Accepted · 机制说明
- label-freshness-and-repair.md:Proposed → Accepted

后续按 M1 → M2 → M2.5 → M4 → M9 → M10 → M6 → M5 → M3 → M7 → M8 逐步落地。
2026-10-22 15:03:26 +08:00
cflmy 18b0c655f7 docs: 两级词表定稿 + README 工程习惯 + M10 提示词落点
按用户决定:内置词表保留(作范例与默认检索集),检索语义仍由参数指定;
工程化写进 README;有提示词的更新提示词。

一、occlusion-description-and-search.md 改为「两级检索」
- 第一级 内置词表 = 范式 + 默认检索集 + 默认豁免集(零配置可用,跨项目可比,
  给 LLM 稳定范本,避免它每次发明措辞)。六组:未完成/假数据/演示/不稳/将删/待核;
  pending = 未完成 ∪ 假数据。
- 第二级 参数:--grep A,B 替换;--also-builtin 并集;--group 选内置组;MLSP 同构
  (labels.search { grep, also_builtin })。
- 明确:内置词表是数据不是语法;词表扩容不动语法;写别的措辞完全合法。
- 空载荷一律 warning(写 None 消除);「命中内置集则降为 hint」留作非默认旋钮。
- stale 豁免默认用内置 pending/将删组,--stub-words 可覆盖。
- 识别仍为纯子串、无位置/分隔符要求;识别不到不报错;误判只影响计数。

二、README.md 新增「工程习惯:允许申报未完成,但不允许假装完成」
- 示例:空载荷桩 / 假数据桩 + 桩契约
- 四条约定:桩必须能跑、必须写明返回值、申报有范例、接不了就申报别声称完成
- 盘点与门禁命令:labels pending / labels search --grep / --also-builtin /
  --count --baseline --fail-on-increase(棘轮)
- 指向两份设计文档

三、总纲增补 M10(工程化落点):README 一节 + ext/ai/agent.mq.md 提示词两处
(:48 默认 standing、:39 how-to-act 协议段)追加申报约定;顺序
M0→M1→M2→(M2.5)→M4→M9→M10→M6→M5→M3→M7→M8。

四、实现点明确分层:内置词表是常量数据、检索是纯函数、语法零依赖。

未改代码(README 为文档)。
2026-10-22 14:25:51 +08:00
cflmy 924885969f docs(design): 删除内置词表,检索改为调用方传词;空载荷一律 warning
用户质疑「关键词表其实不是很有必要,为什么不能允许 LLM 直接传入某个关键词做检索」——成立,
词表是冗余层。本文重写并改名 occlusion-description-and-search.md(原 occlusion-tags-and-stubs.md)。

一、编译器不再内置任何词表
只做两件事:原样保存描述字符串 + 提供参数化检索。
  marqdo labels search --grep 待开发,未实现,开发中   # OR 子串匹配
  marqdo labels search --grep 接口 --json            # 任意词
  marqdo labels search --grep 待开发 --count         # 只数数
MLSP 对应 labels.search。
删词表的理由:词表是语义偏见("什么算未完成"是项目判断);永远不全
(开发中/未接/待联调/占位/TODO 追不上真实语言);闭集要改编译器;分类应在查询期而非编译期;
LLM 更会挑词。**编译器保持哑,查询保持聪明。**

二、唯一代价与其解法
CI 需要"什么算欠债"的定义 → 不是把词表放回编译器,而是**在调用处声明**(通常写在 CI 脚本):
  marqdo labels search --grep "待开发,未实现,开发中,模拟,桩" --count \
    --baseline .marqdo/pending.json --fail-on-increase
词集在仓库里可读可改可评审,换项目只换词集,编译器一行不改。

三、空载荷改为**一律 warning**
原设计"已申报则不打扰"依赖词表;词表删掉后无法判定是否申报,故改为一律:
() 为空 → label.empty_payload。修法极简——写 None 或一个真实返回值。
实测确认 None 是合法表达式(json.stringify → null),所以 [功能开发中](None) 可用。
补充:遮蔽语法是新形式,今天仓库里一处都没有,**这条 warning 不可能产生历史债**。

四、stale 豁免也改为调用方决定
check --stub-words "待开发,模拟" / MLSP validate.stub_words;**不传则不豁免**。
与"参数化"一致:豁免也是调用方的判断,不在编译器里写死。

五、检索语义 v1:子串匹配(CJK 无词边界)+ OR + 英文忽略大小写;
输出含文件/行号/描述原文/() 代码/命中词;误判必然存在但只影响计数,且输出带原文可人工判断;
不做否定语法(留 v1.1「否定词窗口」可选项)。

六、工程化章节保留并简化:agent 提示词(写不了就申报、桩必须能跑、写清返回值、
收尾用 labels.search 自查)、四个工具面、四个指标(pending_count/unlabeled_empty/stub_ratio/stub_age)。

七、实现点:无任何词表常量;src/label.rs 为索引与检索器;
check 三条硬规则(label.missing error / label.ref_dangling error / label.empty_payload warning);
描述不影响求值;空载荷 → None。

同步 occlusion-syntax.md(空载荷说明改为一律 warning、M9 改为「描述检索与桩」、增补链接)
与 doc/README.md 索引;文档改名为 occlusion-description-and-search.md。未改代码。
2026-10-22 14:21:36 +08:00
cflmy 619271b8eb docs(design): 关键词改为纯子串检索(无分隔符)+ 空载荷 warning + 工程化实践
按用户两点修正:

一、关键词匹配不再有任何位置/分隔符规则 —— **纯子串检索**
[某某功能开发中]() 合法且可被统计;[搜索接入,待开发]、[【待开发】x] 同样命中。
关键词表扩为六组(未完成/假数据/演示/不稳/将删/待核),每组含同义词
(待开发·未开发·开发中·未实现·待接…;模拟·假数据·桩·占位·stub…)。
识别不到不报错不提示;最多取 3 组,最强者决定语义(未完成>假数据>示例>实验,将删正交)。
诚实写明子串必然误判([不属于待开发范围] 会命中):不影响执行,只让计数偏大;
stubs --list 显示描述原文可人工识别;否定词窗口留作 v1.1 可选。

二、空载荷必须提示,不得静默
() 为空 → label.empty_payload(**warning**);**若描述已含关键词(已申报)则不报**
——否则每个桩都报,正好制造要消灭的疲劳。
文案:「空载荷遮蔽:请补 (),或在描述里写明未完成状态」。

三、新增「工程化」一节(本设计的真正落点)
- §5.1 可直接放进 agent standing 的提示词片段:接不了就申报,别静默伪造、别声称已完成;
  桩必须能跑,返回值建议带 stub:true;收尾用 stubs 工具确认剩余项。
  要点:把"编造"变成"填表"——模型不必判断算不算伪造,只需写状态词。
- §5.2 三个 LLM 工具面:stubs --json(待办)/ --changed(本次改过的桩)/ labels --grep(任意词检索)
- §5.3 工程指标:pending_count、unlabeled_empty、stub_ratio、stub_age
- §5.4 CLI 示例

四、生命周期与防疲劳协同保持:桩(含空载荷、含未完成/假数据/将删)豁免 stale;
债务用棘轮;空载荷只在未申报时警告(说过的不再重复)。

实现点更新:src/label.rs 为检索器(label_text.contains(word)),
check 三条硬规则(label.missing / label.ref_dangling / label.empty_payload warning),
关键词不影响求值,空载荷→None。

同步 occlusion-syntax.md(文法允许空载荷 + 空载荷说明 + M9 改为「关键词与桩」+ 增补措辞)
与 doc/README.md 索引。未改代码。
2026-10-22 14:18:58 +08:00
cflmy 719b7a8d82 docs(design): 修正标签定位 — 描述是自由文本,内置词只做检索不做语法
按用户修正重写 occlusion-tags-and-stubs.md:
1. `[]` 里是**纯粹的描述文字,对执行零作用**;编译器不解析,只在其内**检索**
   (供统计、清单、LLM 待办)。写成 `[某个功能,没开发完成]()` 完全合法。
2. **标签不是语法**,是内置词;想被统计就顺手写上 `[某个功能,没开发完成。待开发]()`。
3. 标签的作用是"让人和模型多看一眼",不是审批、不是门禁——所以标在任何地方都无害。

识别规则改为检索语义:
- 结尾识别([搜索接入,待开发] / [搜索接入-待开发] / [功能待开发])
- 显式括号识别(【待开发】可出现在任意位置)
- 句中裸词不识别(避免误判)
- **识别不到不报错、不提示**(描述自由,机器只是"看见了就记一笔")

撤回上一版的错误判断:原把 `[税率-待开发](0.1)` 列为反例是错的。
标在已知常量上也无害——多四个字换来一次深入检查与阅读,按用户判断**收益优先**。
仅保留不报警的提醒:stubs --changed / --uncounted 展示债务构成,避免数字被撑大后失去参考。

空载荷语义调整:描述非空时 `()` 可空(返回 None),并**自动计入 `stubs --uncounted`**
(未标注的桩也会被看见),不再把"必须有内置词"作为语法门槛。

桩豁免 stale 保持(待开发/模拟/废弃,以及空载荷),并补"防忘去标签"的兜底:
stubs --changed + 会话汇总里的 stubs_touched(一次性,不催)。

实现点相应改为"检索层":parse 原样保存描述字符串;src/label.rs 为检索器;
Tag 为闭集枚举但词表可扩(后续支持 frontmatter 自定义),**不影响任何语法规则**;
check 只保留两条硬规则(label.missing 描述为空、label.ref_dangling 引用悬空)。

同步 occlusion-syntax.md(增补措辞 + M9 改为"检索层")与 doc/README.md 索引。未改代码。
2026-10-22 14:14:15 +08:00
cflmy dfe99a10b4 docs(design): 遮蔽标签与桩 — 把 LLM 的「假接通」改造成可结算的欠据
按用户提议新增:描述文字内可带尾标签([某某功能-示例-待开发](实现)),
编译器在描述里检索标签,从而让"未开发"变成可枚举、可统计、可门禁的债务。

核心框架:**遮蔽是承诺,承诺有三态** —— 兑现(fresh) / 过期(stale) / 尚未兑现(pending)。
前两态由新鲜度机制管,第三态由标签管。于是假接通从"无法追踪的谎言"变成"可结算的欠据"。

一、动机:LLM 假接通的三条路 —— 禁止(改隐蔽)、放任(静默撒谎)、**申报(本方案)**。
关键不是提高道德要求,而是改变激励:申报比伪造省力,且申报后代码照样能跑。

二、()` 内部语法定稿(用户授权自行制定)
- 取元:at(表, 键) / get(表, 键, 默认)
- 调用:callee(args),逗号可选;**callee = 第一个 '(' 之前的全部文本**(空格合法,解决 D8)
- 循环:- [描述](遍历 集合 为 变量),变量名搬进 ()
- 空载荷:() 仅在带桩标签时合法(返回 None),否则 label.empty_payload

三、标签规范
形态 [描述-标签[-标签]](实现);抽取规则:**从右往左**剥离已知标签(最多 3 个),
分隔符 - 或 -;剩余为描述;未知尾段不剥离([报表-2026] 描述不变);
疑似拼错报 label.tag_suspect;字面尾标签用 \- 转义。
词汇表 v1 闭集:待开发 / 模拟 / 示例 / 实验 / 废弃(闭集才可枚举、可统计、可门禁)。
多标签以最强者决定语义:待开发 > 模拟 > 示例 > 实验;废弃正交。
标签放 [] 里而不是 () 里:人必须看得见、与描述同处一室、不可执行(守住铁律)、可正则检索。

四、桩的语义:必须能跑(不得报错)、必须有标签、不得被当成已完成。
返回手段:空载荷 None / 常量占位 / 假数据 / **桩+契约=有类型的洞**(推荐)。
建议惯例:桩返回值显式带 stub:true,下游跑通也知道是假的。

五、生命周期(自愈):写桩 → 计数 → 开发 → T1 检测 → 复核去标签 → 债务-1。
**桩豁免 stale**(待开发/模拟/废弃):否则 12 个桩变 12 条常驻警告,正好制造要消灭的疲劳。
代价是"做完了忘去标签" → 用 stubs --changed 与会话汇总里的 stubs_touched 兜住(一次性,不催)。

六、与防疲劳机制协同:桩豁免 stale;债务用**棘轮**(stubs.json 基线,只在增加时失败);
stubs 是按需命令不进 check 人类输出;会话末汇总带 stubs_touched。

七、编译器实现点:parse 抽标签 → ast Expr::Occluded{label,tags,inner} → 新增 src/label.rs →
check 报 label.missing/empty_payload/tag_suspect → interp **标签绝不影响求值** →
mlsp stubs → main marqdo stubs → view 桩徽章。
**铁律守住:[] 永不执行,标签只影响诊断/统计/呈现。**

八、示例集(按 LLM 真实风格):假装接入搜索 / 假算指标 / 假接通 ERP / 已废弃旧实现 /
反例(税率不该标待开发——桩只用于"应存在但未实现的连接",不是懒得查的数据)。

九、实施增补:M2 抽标签、M2.5 空载荷与 label.missing、M4 L1(桩不影响引用校验)、
**M9(新)marqdo stubs(清单/--json/--check 棘轮/--changed)+ MLSP stubs**、M6 汇总加
stubs_touched、M8 view 徽章与教程。顺序 M2→M2.5→M4→M9→M6→M8。

十、风险:标签滥用(棘轮+评审约定)、桩腐化(--changed 提示,不靠常驻警告)、
假功能上生产(view 显著标记 + 知识库仓可 error)、词汇不够(后续可配但须可枚举)、
**LLM 伪造标签**(标签只增加可见性,不减少任何检查)。

同步更新 occlusion-syntax.md(增补引用 + M9 行 + 顺序)与 doc/README.md 索引。未改代码。
2026-10-22 14:08:54 +08:00
cflmy fac68e85ea docs(design): 遮蔽语法总纲(实施依据)— 示例先行 + M0–M8 实施计划
按用户定调:不把 []() 写成「循环/表格取元/函数调用」的语法,而是写成
**遮蔽语法(occlusion syntax)**:用叙述显示逻辑、用括号承载实现,
解决"刻意语法设计导致文档不可读",并依靠链接特性使知识过期可被检查。

一、示例先行(六个)
1 嵌套取值:三层 [1]([苹果]([水果类](货架))) → [水果类里苹果的第 1 项价格](at(at(at(货架,水果类),苹果),1))
2 长表达式打断叙述 → [应缴税额](...) 让句子完整
3 抽象层次混杂 → 论证留在叙述,算法退居括号
4 循环来源不可见 → - [从篮子里取出的每个果子](遍历 篮子 为 果)
5 **带空格函数名(已实测)**:> 加一 号 31 ❌ unknown function 加一;
   括号调用 加一 号(31 ) ✅ 32 —— 因为 callee = 第一个 '(' 之前的全部文本,空格不再是切词依据
6 反例:描述=实现时不该遮蔽

二、核心定理(本文档的理论支点)
**遮蔽创造信任负债**:把实现藏起来,读者就必须相信描述;
不遮蔽时描述过期无伤大雅,遮蔽后描述过期=文档变假。
所以「新鲜度校验」不是附加功能,而是遮蔽语法的**合法性来源**与代价。

三、场景按动机分类(不按语法分类)
A 不可读 / B 打断叙述 / C 层次混杂 / D 来源不明 / E 名称受限。
D 与 E 是遮蔽顺带解决的问题,不是目的;按动机写才能覆盖未来没想到的不可读情形。

四、语法规范:[] 永不执行、() 唯一执行;空标签 label.missing(error);
() 内用现有表达式文法,callee 允许空格;取元改为 at/get(纯度);
循环 - [描述](遍历 集合 为 变量),变量名从 [] 搬进 ()。

五、两种遮蔽关系,**都要查**
显式遮蔽([]())与**隐式遮蔽(叙述段 + 紧接 > 调用)**——
按用户要求把 > 调用也纳入过期检查:取上方紧邻叙述段为描述,
其反引号实体须出现在实参/callee;无叙述或无反引号则跳过(零噪音)。

六、新鲜度机制:L1 引用一致性(零依赖)+ T1 会话内(repair_apply 前后版对比)
+ **会话末一次性汇总(用户要求做)**:{labels_stale_seen, fixed, outstanding, items};
能力自述与无 git 降级(沙箱 exec=false / WASM 均可用)。

七、实施计划 M0–M8(每个里程碑含目标/改动文件/关键点/测试/验收/回滚)
M0 语义冻结 / M1 () 内调用增强() 终止·逗号·嵌套·空格 callee)/ M2 遮蔽语法 /
M3 at·get 与循环 / M4 L1 / M5 隐式遮蔽 / M6 T1+汇总 / M7 迁移与版本门 / M8 呈现与门禁。
**顺序建议 M0→M1→M2→M4→M6→M5→M3→M7→M8**:先让"断言+复核+修复"跑通,
再动 506 处迁移(中间态最痛)。

八、迁移实测规模:取元 506 处/136 文件,循环 44 处/24 文件,可执行方括号调用 0
(189 行是 lib/* 的 Caller 说明,不执行)。旧形必须 syntax.legacy_index 硬报错
(同形换义最危险),并用 label.provisional 承接机械迁移,避免 506 处全红。

九、测试计划与风险登记:单元/金样/回归 554/双后端/迁移差异/反向验证/环境矩阵/性能;
硬要求"每个新检查必须证明它会响"。

十、附环境前置(踩过的坑):scripts/dev-env.sh + build-web-plugin.sh;
$HOME 不可写 → zig 缓存重定向;/tmp 是 noexec → TMPDIR 必须可执行。
基线 cargo test 554/0;check 对 59 文件 0 warning/0 error,任何里程碑不得变差。

同步在 doc/README.md 登记 5 份新设计文档。未改代码。
2026-10-22 14:03:31 +08:00
cflmy 639b0ebcd1 docs(design): 讲清 T1「会话内陈旧检测」— 为什么模型在结构上收不到重复警告
回答:能不能在不改变的情况下让模型免于多次警告疲劳。能,且几乎不用改什么。

一、机制成立的根据(代码事实)
repair_apply(src/mlsp.rs:233)里 source(before)与 apply_edits 后的 new_source(after)
在同一个函数作用域内同时存在。所以"比较改动前后"不需要任何外部东西:
改动前 AST / 改动后 AST / 标签配对 / () 指纹 / [] 文本,全部在内存里算完。
零 git、零台账、零缓存文件、零环境依赖——这就是"agent 回路根本不需要 VCS"的确切含义。

二、时序:模型在自己这次编辑的响应里收到
validate → repair_targets → 模型产出 edits → repair_apply(source, ranges, edits)
→ 内部 before/after 对比 → 响应追加 labels.stale[{text, code_past, code_now, span}]。
模型只需回答一个问题:"你刚动了这段实现,描述还成立吗"。

三、重复为什么在结构上消失(三性质,缺一不可)
作用域=自己的 diff(旧债永不进上下文);投递=一次(后续 validate 不再出现);
自包含(下一轮 diff 是新的,没碰就不提)。刻意取舍:**宁可漏一次,也不反复骚扰**。
对比:20 处标签的文件 5 轮修复,扫描式累计上百条,T1 最多 0–2 条且每条一次。

四、关键重构:它在性质上不是 warning,而是**编辑期诊断**
对照 lint 警告 / 编译器错误 / T1 stale 的四个维度(时机、数量、是否重复、用户态度)。
没有人抱怨"编译器又报语法错了",因为那是一次性、可归因、改动驱动的。
**疲劳不是靠压制解决的,是把 stale 从 lint 类别搬到编译错误类别解决的。**

五、「不改变」到什么程度
文档内容不变(不嵌指纹、不加 noqa);工作流不变;不新增状态文件;不依赖 VCS;
纯内存计算。唯一改动:MLSP 加一个可选参数 check_labels + 一个响应字段 labels。
缺省关闭 = 零开销零噪音。

六、配对规则(按标签文本配,不按行号)
标签未变+() 变=stale;标签变了=作者在更新描述(不报);新增/删除不报;移动位置不报。
→ "挪位置"不误报,"改计算"必报警。

七、漏掉的三层兜底:循环预算(现有 max_attempts:2 直接可用)、可选阻塞
check_labels:"block"、会话末一次性汇总。建议默认 true + 循环预算。

八、边界:T1 保证"改动者当场被问一次",不保证"全仓库始终新鲜"(那是 T2/T3 的活,
可选、不进默认路径)。

附 §1.1 指纹可行性:Expr 目前只有 Debug 无 PartialEq;T1 只需进程内一致,
用 format!("{:?}", expr) 即可;更严谨可补 derive(PartialEq)(Literal 含 f64,只能 PartialEq)。
T2/T3 才需要跨版本稳定指纹,那时再用 knowledge/fingerprint.rs。

未改代码。附四项待确认。
2026-10-22 13:52:26 +08:00
cflmy 2c4dac005c docs(design): 修订 — 标签保鲜不该依赖 git,改为「前一状态」provider 分层
用户反驳成立:不是所有开发都用 git,依赖 git 不是好设计。三条理由:
1. 环境覆盖不到:沙箱 allow_exec=false(src/host/sandbox_fs.rs:378)文档内调不了 git;
   浏览器 WASM(wasm32)无进程能力;单文件/zip 工件无 .git;非 git 用户无从使用
2. 语言不该绑定 VCS:把语义正确性外包给"某工具目录是否存在"
3. 最要命的:最高价值场景(agent 修复回路)恰在不能调 git 的环境里

修订方案:保住 M5 的**原则**(变更驱动而非扫描驱动),把"前一状态"抽象为 provider:
判定逻辑只有一份 stale ⟺ fingerprint(()) 变 ∧ label 未变;变的只是 prev 从哪来。

四层能力:
- T0 引用一致性(零依赖,纯文档)——查引用腐烂
- T1 会话内前后对照(零依赖,最高性价比)——repair_apply / view 保存 / 编辑器钩子 / agent diff
- T2 外部历史源(可选,git/hg/svn 适配器)——跨会话漂移
- T3 台账(可选,.marqdo/labels.json)——无 VCS 时的持久化 + 确认状态

环境能力矩阵:CLI+git / CLI 无 VCS / agent 沙箱 / 浏览器 WASM / 单文件 / 对象存储,
**没有一行全 ❌**——T0+T1 在所有环境成立,足以支撑"agent 改动即时提醒"。

最关键一条:repair_apply 已同时持有 before(source) 与 after(应用 edits 后),
所以建议协议加一个可选 base_code / check_labels 字段,Marqdo 在同一次调用内即可算出
"哪些标签的 () 指纹变了而 [] 没变",返回带 code_past / code_now 的 stale 列表。
零外部状态、零依赖、零 git——而这正是模型改完代码别忘了改描述的场景。

provider 五条硬规则:核心不依赖 / 缺失即静默降级(不报错不提示)/ 能力必须自述
(labels status 显示启用层级,避免"没报=没问题"的误判)/ 判定单一定义 / 不写进文档。

被否:强制 git、文档内嵌指纹、零宽字符、mtime 启发式、# noqa、静音清单。

同步修订 warning-fatigue-control.md:M5a 由"核心"降级为可选 T2 适配器,
补一条验收指标"provider 缺失时标签相关输出也必须为 0"。其余结论不受影响。

未改代码。附五项待决策(是否接受分层、T1 是否够、能力自述、T2 适配范围、T3 是否推迟)。
2026-10-22 13:49:03 +08:00
cflmy 0ac661eef2 docs(design): 防警告疲劳机制 — stale 必须是「变更报告」而非「扫描报告」
触发:用户指出 []() 每次报 warning 会导致烦躁与忽略,机制必须先定再开工。

一、为什么标签检查特别容易被忽视
高频(标签密度≈每个取值/调用)、主观(自然语言断言,机器只能近似)、
持续(代码天天改)。且实测基线是**零噪音**:lib/ + ext/ai/ 共 59 文件跑 check,
warning=0、error=0 —— 标签校验会成为项目第一个持续警告源,一次就要做对。

二、疲劳的真正根因不是"报得多",而是「同一件已知的事被反复告知」。
目标改成三条硬约束:没有新信息就不说话 / 说了就能做点什么 / 说过的就不再重复。

三、六个机制评估
M1 分级(按证据强度:error=能证明断裂,warning=能证明变化但不知谁错,hint=弱信号)
M2 聚合(check 人类输出最多一行,细节进 --json / view / labels)
M3 基线(bootstrap 静默吸收,用于迁移后的存量)
M4 确认即静默(ack 台账,同指纹不再报)
M5 **结构化 diff(推荐核心)**:stale 只在「() 变了 ∧ [] 没变 ∧ 在本次变更集」时报
M6 文档内抑制 # noqa —— **否决**(污染文档、不可审计、会永久化;抑制只放台账/配置)

四、M5 的性质(这是把疲劳问题降级的关键)
零台账(git 即台账,无新文件/无合并冲突)、零基线(首次也安静)、
零重复(提交后 diff 清空报告即消失)、天生带 before/after(正好是 LLM 复核输入)、
格式化免疫(比 AST 指纹而非文本)。非 git 环境降级为 L1,仍安静。

五、推荐组合
默认:M5a + 默认 hint + check 最多一行 + 每条带定位/before-after/建议 + 变更集去重 + 非 git 降级
严格模式(知识库仓 opt-in):升 warning/error + 基线与确认台账 + **棘轮(允许存量、禁止新增)**
+ labels status 进 CI。棘轮是最值得抄的机制:老债不阻塞、新债立刻拦、债务数字可下降。

六、确认的三种语义:改标签 / 改代码 / 显式确认。
建议三者都提供,但显式确认留痕(confirmed_by + 次数)——**被反复确认的标签本身是坏味道**。

七、可证伪原则:只有能被证伪的断言才被检查。标签含反引号实体→参与 L1;纯口语→L1 不检查。
检查成本由书写具体程度决定,同时反向抑制"为凑数写废话"。

八、agent 节流:只对它自己刚改到的标签做检查,每轮一次,超 N 条只报前 N+汇总。
模型看到的是"你刚改的这处描述可能不成立",而不是"全仓库 200 处过期"。

九、防「用忽视解决」三道闸:债务可见(labels status 给数字)、可 gate(error)、
可审计抑制(labels audit + 过期抑制提示)。

十、验收指标(写进文档防走样):无变更时标签相关输出=0;单变更集提示≤3 或≤20%;
重复=0;可行动率 100%;误报≤10%;check 人类输出≤1 行;hint/warning 不影响退出码。

未改代码。附五项待决策(核心机制、默认级别、棘轮、确认留痕、check 聚合行是否常显)。
2026-10-22 13:44:36 +08:00
cflmy 1dd74578b5 docs(design): 纯度路线落地 + 标签过期检测(L1/L2/L3),对接 MLSP 修复回路
决策:取纯度(() 只装机器语句,取元搬进 ());标签可省略书写但编译器必须报错;
循环写法不追求统一。

一、纯度强制两件事(推论)
① 必须有不带标签的普通表达式写法(否则每个访问都被迫配人话 = 仪式感复辟)
② 带标签形式是「想做断言时的可选包装」——由此解决「标签凑数」退化:
   不想断言就别用这个形式。
普通取元四个候选:A 现有内建 at value= index=(零新语法、啰嗦)、
B 后置方括号 篮子[1](自然但引入第二种方括号角色)、C at(篮子, 1)(需逗号参数,
与之前想要的 f(args) 同一改动)、D 点号(与库路径/方法冲突)。建议 C,零风险选 A。
空标签 [](…) → label.missing 硬错误。
循环:- [从篮子取出的每个果子](foreach 篮子 为 果),变量名从 [] 搬进 (),不再让 [] 兼任标识符。

二、标签 = 可校验断言的载体(不是注释)
锚定 AST(有 span)/ 可机械核验 / 可进修复协议 / 变更可感知。

三、过期检测三层
L1 引用一致性(无状态):标签内反引号=实体断言,必须可解析且出现在 () 中。
   低假阳性(只有显式反引号才算),但查不出语义腐烂(乘改除)。
L2 指纹台账(有状态):.marqdo/labels.json 记 hash(())+code_quote。
   复用 knowledge/fingerprint.rs(collect_calls/ops_hint/fingerprint_hash)。
   键=规范化标签文本+序号,移动代码不误报。能查语义腐烂。
   存 code_quote = 「保留内容用于校验」的对称物:doc_quote 留 [],code_quote 留 ()。
L3 LLM 复核:诊断同时带 doc_quote / code_past / code_now,模型三选一
   (改标签 / 改代码 / 确认无害),走 repair_targets → repair_apply 越界必拒 → 复验 → 写回台账。

四、与现有设施对接(落地成本低的关键)
- diagnostics.rs to_json 已有 doc_anchor / doc_quote / contract_ref{declared} / suggestion
  → 无需新造字段;contract_ref.declared 就是「声明 vs 实际」的现成先例,只是从类型层下沉到散文层
- contract.rs:203 Contract::diagnostic 一次性装配同一组字段,标签诊断照抄,kind 换 "label"
- mlsp repair_apply 的 ranges 天然支持多区间 → 允许「标签行 ∪ 代码行」,护栏不变
- knowledge/lifecycle.rs 已有 find_stale/stale_json/verify → 标签过期走同一条 stale 通道,
  成为知识库健康指标(知识腐烂的新类型:文档断言 vs 实现)

五、诊断 schema 草案:code=label.stale,doc_quote=标签原文,
label_ref{text,refs,missing_refs,code_past,code_now,fingerprint_past/now,layer},
suggestion 给可执行建议,ranges=[[行,行]]。

六、反幻觉的精确表述:只解决「文档断言与实现不一致」这一类;
不解决模型编造、代码本身写错、标签含糊。价值 = 把文档可信度从「靠人自觉」
提升到「可机械复核 + 可被 LLM 裁决」。

七、风险诚实清单:误报疲劳(最危险,L1 只在能证明冲突时报、L2 同指纹只报一次)、
台账腐烂与合并冲突(视为可丢弃缓存、重算优先)、语义鸿沟(L1 边界)、
LLM 用幻觉修幻觉(护栏+双向信息+人工确认)、
**标签不得参与安全判定**(策略/沙箱/工具白名单只读 () 语义,永不读 [])、增量成本。

八、分阶段 P0 纯度语法 / P1 L1 / P2 schema+MLSP / P3 台账 / P4 L3+CI。
建议先做 P1(零状态、确定性、不依赖纯度迁移),先把「断言→复核→修复」链路跑通。

未改代码。附五项待决策。
2026-10-22 13:40:02 +08:00
cflmy 14114993c4 docs(design): 评定「[描述](语句)」提案 — 方括号=人话、圆括号=机器话
提案:`[]()` 不再读作"两个部分两个含义",而是 `[描述性显示文字](实际执行的简短语句)`;
表格取元的嵌套难描述也没关系——括号里可以写长,方括号只放人话。

一、为什么这个写法"美":三处真实同构
- 超链接 `<a>`:可见文本 ↔ 目标
- 文学编程 chunk 名(Knuth `<<name>>`)
- **Marqdo 自己的 `![marqdo-out](…)`**:方括号放指令、圆括号放负载
经验佐证:`[f] args` 可执行用量 **0**;189 处全是 lib/* 的 `Caller:` 用法说明(给人看)。
`[]` 在实践中的天性确实偏"描述"。

二、三个真实收益(本文最大的肯定)
1. 两条规则变一条:**解散 link-call 死结**。前几轮反复撞墙是因为默认 `()` 只能是集合;
   改成"任意语句"后,取元只是特例,不再独占外形。
2. 嵌套可读:`[1]([苹果](货架))` → `[货架里苹果的第一项](…)`,人读标签、机器读嵌套。
3. 循环来源可见 —— 但要精确限定:`view` 已把 foreach 渲染成带徽章的 loop-card
   (render.rs:1354),取元仍渲染为字面 `[键](集合)`(1502)。所以问题只在**通用 Markdown
   阅读器**里成立,而这恰是多数场合。由此升级为更强的论点:
   **语义正确性不该依赖读者是否用了 marqdo view。**
附:标签→锚点→点击跳转可行(view 已有 span),且 agent 用人话定位比行列号稳。

三、结构性弱点(代价最大、最易被忽略)
若 `[]` 只是标签,`(菜单)` 就只是"整个菜单",取元必须搬进 `()`:
点号 / 函数式 / 嵌套方括号 / 英文式,每种都有消歧问题。
→ **收益一能否兑现,取决于愿不愿新增一条取元规则**。用一条新规则换一条旧规则,不必然净简化。

四、描述漂移:不同意"不重要"
1. 它是注释的回归(贴在执行体上、必须短、可说谎的文本)
2. 一旦作为定位锚点,漂移就有操作后果(错误信息也撒谎)
3. agent 安全面:标签是模型会信任的自然语言,"标签写只读、代码做写入"从文档瑕疵升级为误导通道
缓释:①标签永不参与绑定 ②check 做词重叠校验(标签提到的名字全不在 () 中出现 → warn)
③trace 双输出 ④策略判定绝不读标签。**② 最划算,能抓住最恶劣的一类漂移。**

五、采用风险:可能重演 v0.3 废除 `+ 名` 的"仪式感"(原文理由:仪式感强、与正文脱节)。
两种可预测退化:凑数、噪音。矛盾在于"可省略 vs 歧义回归"必须在设计里正面解决。

六、迁移面实测:索引 506 处 / 136 文件;循环 44 处 / 24 文件;可执行方括号调用 0。
若 `[]` 改纯标签,506 处是**同形换义**(不报错就变义)——最坏一类,必须硬报错 + 版本门。

七、两条落地路线
- 路线一(推荐)双层:长形 `[描述](语句)` + 短形 `[键](集合)` 定义为长形缩写。零迁移、
  调用零成本收编、收益全拿;代价是短形两义仍在但可解释。
- 路线二(纯度):`()` 只装机器语句,取元搬进去;语义最纯但要新增取元规则 + 506 处迁移。

八、评定:本系列结构最强的提案(哲学自洽 ★★★★★,解决问题 ★★★★☆,
规则净简化 ★★★☆☆,迁移风险 ★★☆☆☆,漂移风险 ★★★☆☆)。
建议走双层 + 先把「词重叠校验」做出来,让标签从装饰变成可轻度核验的描述,
才配得上"AI 定位锚点"与"点击跳转"两个职责。

未改代码。附五项待决策。
2026-10-22 13:30:07 +08:00
cflmy e80c944c40 docs(design): 函数的水土不服与「命名/代入」重构 — 设计哲学层(含 1322 函数实测分类)
命题(来自用户):函数是预先抽象,自然语言是即席描述;正常人不会说「要算 37 的两倍
得先抽象一个函数」,而是直接说乘二。故函数在代码即文档里错位。

本文只谈语义表示与自然语言映射,不谈编译器与语法糖。

一、量化证据:Marqdo 的 ## 其实不是「过程」
1322 个函数:
- 纯返回式(零可执行语句,只有一个返回表达式)765(57.9%)
- 一行式 935(70.7%);可执行语句数中位数 0、平均 2.2
- 较长(≥10 行)仅 62(4.7%)
按语义功能分类:
- 纯命名式 754(57.0%)→ 对应「所谓 X,是指…」
- 条款式(有分支无副作用)103(7.8%)→ 对应「凡…则…」
- 遍历式 26(2.0%)、命令式(含 print)83(6.3%)、线性计算 356(26.9%)
结论:命名+条款 = 64.8%,真实副作用只有 6.3%。
即三分之二的 ## 落在「定义/条款」两种自然语言形态里,不需要过程语义。

二、复用经济学:为什么文档里抽象格外别扭
成本 = 定义 + 读者的跳转 + 维护;收益 = N 次复用省下的重复。
抽象值得做 ⟺ 复用次数×复杂度 > 定义成本 + N×跳转成本。
代码里 N 大、跳转便宜;文档里 N 常为 1、跳转昂贵(读者被打断)。
→ 大量文档中的「函数」是负收益:只用一次却强迫回头查定义。
这正是「正常人不会这么说话」的形式化解释:说话默认对方不知道你的定义,倾向就地展开。

三、自然语言复用的六种形态(程序语言只承认一种)
重复 / 指称(该金额)/ 命名(所谓 X)/ 条款(凡…则…)/ 范例(以 37 为例)/ 表格。
命名只是六分之一,却被程序语言变成唯一入口。

四、三个语义立场
甲 定义—代入:一段正文被命名,使用=按角色代入后重述。覆盖 58% 现状,与 ## 结构一致。
乙 条款—援引:条件→结论,援引条款给出适用事实。最贴中文说明文,1./2./3. 已有。
丙 配方—配料:用料表+做法,参数=配料行。最可读但表达力最弱、无法组合。
→ 推荐甲为主、乙为辅;丙作为甲的呈现(契约表)。

五、代入 vs 调用(为什么代入更贴人话)
心理动作、输入意义(一套名字 vs 两套)、结果意义、可嵌入叙述、一次性使用可取消。
关键:抽象必须能被「取消」——就地描述与命名代入是同一切换,提升/展开是编辑动作而非必经入口。

六、落到已有载体:只缺一环
命名(#/##)、正文(叙述+标记)、未定的量(体推断)、结论(*…*)、条款(1./2./3.)、
配料表(GFM+契约表)全部已有。**唯一缺的是「具名给值」**——问题因此缩小。

七、硬边界:自然性 vs 可判定性
角色具名(可判定,略啰嗦)/ 位置(实测叙述顺序一变绑定就翻转)/
语境隐式(130 个形参名撞车,不可判定)。
→ 只有「具名」同时可读且可判定。也解释了为何叙述式动词不可取:把判定交给未标记的词。

八、三个未决哲学难题:副作用(6.3% 需保留命令语义)、递归(代入=有限展开)、定义时序(能否前向引用)。

未改代码。附四项待裁决(含是否接受「不支持递归」、具名给值的最小形态)。
2026-10-22 13:14:03 +08:00
cflmy 30cd5a0833 docs(design): 在「只执行标记」原则下设计调用语法 — 含 3.8× 后端实测与叙述顺序实验
接受纠正:上一轮的「叙述式动词」L0 方案违背「叙述默认安全、只执行标记」的底层原则,
已否决。本文从该原则重新推导调用语法。

设计约束(硬):调用的每个语义成分(被调者、每个实参、绑定关系)必须落在标记内,
叙述词只能连接与解释,永不改变语义。

一、标记字母表:可承载调用的只有 `> 行`、`**…**`、`[callee]` 三种;
`[k](coll)` 已被取元独占(前几轮结论)。问题收敛为「在标记内如何连接函数名与槽赋值」。

二、三个候选
- A 括注具名 `**加一函数(n=31)**` —— 与通用函数调用同构,取元不冲突,具名可静态映射槽位
- B 箭头 `**n=31 → 加一函数**` —— 最贴汉语语序、链式可读,但优先级与返回值语义需增设计
- C 空格式 `**加一函数 n=31**` —— 今天就能跑(实测 **r = 加 1 2** 已可用),但参数边界靠空格

三、「不分实参形参」的编译器面(实测,结论意外)
| 路径 | 绑定方式 | 200k 次(1 int) | 2000 次(500 元素) |
| 树遍历(默认) | Env{HashMap},实参 k.clone()+v.clone() 深拷贝 | 167ms | 66ms |
| 字节码 | slots:Vec<Value>,pop 按位置移动,无克隆无哈希 | 44ms | 23ms |
即「变量始终在某个位置」已是字节码现实(vm.rs Op::Call),收益 3.8× 是真的。
但**它与语法无关**:槽位化只需编译期知道形参顺序,而体推断已给出顺序。
瓶颈是树遍历用名字哈希+深拷贝、以及默认后端是 Tree。
→ 不要用性能论证语义变更;省 IO 走「默认切字节码/解释器槽位化」这条正交工程路径。

四、真实耦合点:具名 vs 位置(决定性实验)
形参顺序 = 叙述里首次声明顺序(v0.3 §8.2),而叙述可自由改写。两文件只差语序:
| 调用 | 叙述 a,b | 叙述 b,a |
| a=10 b=3 | 7 | -7(随函数体改变,符合预期) |
| 位置 10 3 | 7(a=10,b=3) | **7(b=10,a=3)绑定翻转,不报错** |
→ 「实参形参不分」时位置传参等于把语义挂在可改写的叙述顺序上。
推论:调用应以具名为准;具名同时让编译期静态映射 slots[i],既稳又快。

五、建议
- 主形态 A:`**f(k=v)**`;单参允许 `f(31)`;多参要求具名,旧位置写法 check 期 warn
- B 箭头作后续可选项(定位为语句式组合子)
- 明确不做:未标记动词、[f](args)(撞取元,已实测 2 个真实冲突文件)、
  动态作用域(七条硬伤 + 130 个撞车形参名)、位置实参作主流

附优劣总表与待决策四项(含是否把默认后端切字节码)。未改代码。
2026-10-22 13:06:57 +08:00
cflmy e2068c2051 docs(design): 参数能否从上下文推断 — 拆成 L0/L1/L2 三层,附 1322 函数语料实测
回应「让函数参数从上下文推断,写成 对**n=31**执行**加一函数** 可能吗」。

核心结论:**用户示例其实不需要隐式推断** —— n=31 就写在句子里,
缺的是「叙述式调用」语法,不是新的作用域语义。拆成三层:
- L0 叙述式调用(绑定在句中)→ 纯语法糖,安全,建议做
- L1 就近绑定(上一行绑定,下一行只写函数)→ 段落级隐式,不建议
- L2 真隐式(动态作用域)→ 不建议,七条硬伤

实测(1.5.2,8 组):
1. 示例原样跑:无输出、无报错、exit 0 —— 静默 no-op
2. 拆开看:散文行里的 **n=31** **真的执行了**(main 的 n 变 31);
   而 **加一函数** 只被求值丢弃,从未被当作调用
3. `**n = 31**` + `> 加一函数`(不传参)→ missing argument for parameter n
   —— 函数看不见调用者作用域(严格分离,这是语义基石)
4. `> 加一函数 n=31` → 32,今天就能做
5. `# main` 读 frontmatter `税率` → 0.1 ✅;`## 函数` 读同一个 → undefined ❌

用户担心的「大项目变量名难用」有数据支撑(全仓库扫描 1322 个函数):
- 819 个不同形参名,其中 **130 个被 ≥5 个函数共用**
- 最严重:path 70、value 59、text 53、id 47、list 38、内容 38、路径 35
→ 若参数靠上下文推断,调用任何读 text 的函数都会捡到作用域里的 text,撞车是常态

L2 七条硬伤:同名捕获、递归自毁、无法复用、契约报废(call_arg_diag 没有校验点)、
指纹/arity 失真(隐式调用在 AST 上像零参)、沙箱隔离破坏、不可审计。

给出受控替代:**常量默认值** —— 形参未传入时取文件级常量(frontmatter),
静态可判定、不随调用者变化、契约与序列化都不受影响。

顺带发现并记录 **D11(高)**:函数可见环境随运行面不同。
- # main 走 Env::with_metadata(interp.rs:473)→ 能读 frontmatter
- 普通函数调用走 Env::new() → 读不到
- 浏览器 WASM 入口 invoke_in_entry(interp.rs:365)→ metadata + entry_bindings 都给
即同一份文档在 Web 能跑、在 CLI 报 undefined variable。已写入缺陷实录(含复现与两条修法,
倾向「统一为函数可见 metadata」,正好成为常量默认值的现成基础)。

未修改任何代码。
2026-10-22 13:00:01 +08:00
cflmy 9cda80ee7d docs(design): [函数名](参数) 与 f(参数) 调用写法评估 — 原型实测 554/0(已回退)
更正前两轮对用户意图的误读:用户问的是**调用写法**,不是表/函数即值。

核心结论:
- [函数名](参数) 技术上能做,但撞的是已定的取元语义
  「方括号=取出的名字,圆括号=从哪取」(collection-access-link.md §1;
  call-arguments.md §2 锁定 `]` 紧邻 `(` = 取元)
- 按名字消歧不可行(**实测证据**):全仓库 851 文件 / 2367 个 ## 名 /
  983 次 [k](c),键名与同文件函数名冲突 5 处、去重后 2 个真实文件:
    ext/data/db.mq.md:122        *[count](r)*        (## count + r 里的 count 列)
    examples/code-as-docs/index.mq.md:79  价=[单价](行)  (## 单价 + 行里的单价字段)
  函数名优先 → 打断这两处取元;数据优先 → 永远无法 [f](1) 调用。两条都走不通。
- 且存在不可消除的歧义子集:[f](1) 与 [1](篮子) 同形,单参调用永远无法表达;
  「多参能用、单参不能用」的语法不可教。

但去掉方括号的 函数名(参数) 是**完全空闲的语法**(实测原型前 加(1) 报
trailing input in expression),且原型验证可行:

原型(已回退,仅验证):
1. src/parse/expr.rs 新增 try_paren_call,紧随其后的 ( 视为参数列表
2. src/parse/mod.rs 两处「像调用」判定加 looks_like_paren_call,让单 token 也能进调用分支

原型实测:
- 加(1) / 加(1 2 ) / 加("1" "2") / txt.str_trim("  x  ") 均通过
- 加(1 2)、加(a=1 b=2)、加(1, 2)、嵌套 加(加(1 2) 3) 失败
- **全量 cargo test --release: 554 passed / 0 failed(零回归)**

关键判断:失败点不在语法而在**参数分词器**——加(1 2) 失败、加(1 2 ) 成功,
差别只是 ) 前多一个空格,说明 parse_call_args/split_first_token 把 ) 当成了
token 的一部分;修它要动所有调用共享的分词器。这解释了「看着 10 行、实为一次核心改动」。

另一个重要性质:f(args) 最终仍产出 CallExpr{callee,args},
EKC 指纹 collect_calls、契约校验、字节码 Op::Call(fid,argc) **全部自动兼容**——
它只换写法,不改调用模型(与一等函数方案本质不同)。

人读性:f(1 2) / f(a=1 b=2) 与数学记号同构、参数边界显式、渲染不成超链接,
优于 [f](1 2)(预览里会变成链接)。

建议:不做 [f](args);做 f(args),先具名后位置。
附工作量清单 9 项与三档实施选择(A 仅具名 / B 具名+位置 / C 全量)。未改代码。
2026-10-22 12:53:03 +08:00
cflmy eae4815fc7 docs(design): 函数能否解释为 GFM 表 — 11 组实验 + 史料考古(未改代码)
回应「代码函数(## 名 + 参数 + 体)从某种角度能否解释成 GFM 表,
这样的解释运行时有没有巨大风险、有没有实际收益、历史上出现过吗为什么放弃」。

核心答案:命题在 Marqdo 里**已经实现**,但实现的是「关于函数的表」(契约表),
不是「函数本身」。界:表能描述外延(输入→结果)与签名(元数据),
不能描述内涵(怎么算);而调用恰恰是内涵操作。
[k](集合) 是投影已有数据,f(x) 是计算新数据,只有 f 已是预先枚举的表函数才重合。

一、固定表格几何(实测)
- 1 列 N 行 → List;≥2 列 1 行 → Map 记录(实测 {"x":1,"y":2})
- ≥2 列 N 行 → **列向聚合** Map(实测 {"档位":[1,2],"税率":[...]})
- 行向记录必须显式标记(行/@/row),文档原话「不得与默认列向字典静默混用」
→ 「行 = 参数」在 Marqdo 里不是自然形态

二、命题已存在:契约表(tests/contracts/ok_contract.mq.md)
src/contract.rs:表头含 参数/返回/字段 + 必须有「类型」列 → 契约块。
契约表的首列标头正是 §3.5 那种「显式形态标记」的同类做法。

三、11 组实验(1.5.2 实跑)划定边界
- E1b 表列 n 但体不读 → > f 无参调用成功 → 表**不能声明**形参
- E3 叙述声明 n + 表 + 传"七" → 参数 n 期望 number,实际 text(契约校验)
- E4 无表 → 七1,不校验
- E5 + `n` 旧式形参行 + 表 → 契约生效(用户草图形态可用)
- E6 表写 2 行、体只读 1 个 → too many positional(**表 ≠ arity**)
- E7 单列参数表 → 七1,**契约静默失效**(1 列 = List,且 check 报"无契约问题")
- E8 重复行 → 取首行无诊断;E9 幽灵行 → 静默忽略
- E10 同一张表加 `tc` = 绑定 → 契约消失
→ 隐含规则:**未绑定的表 = 声明/元数据;绑定的表 = 数据**

四、若表成为定义(把静默漂移从"少个校验"升级为"少个参数")
漏类型列/表体漂移/重复行/调换行序都会变成绑定语义;
最致命的是行序携带语义——「把 b 行移到 a 上面」这个无害编辑会改变位置参数绑定。
而 [键](集合) 之所以安全是因为**键是显式的**,取元不依赖顺序。

五、链接式调用第三次论证(带史料)
collection-access-link.md §1「方括号 = 取出的名字,圆括号 = 从哪取」;
§4 非目标排除点号/在/箭头/(键)[集合];call-arguments.md 锁定 `]` 紧邻 `(` = 取元。
→ [f](args) 不是未决定,而是**已被明确分配给取元**。

六、史料:这条路是被反向走过的
- v0.2 要求手写 `+ 名` 形参表 → v0.3 列为**代价**(仪式感强、与正文脱节),
  P4 改为体推断,`+ 名` 标注「过渡兼容,新代码不推荐」
- objects.md §6 非目标:**用表格声明字段 schema**(表格仍表示数据集合)
- tables-maps-footnotes §3.3 行向记录「不默认」,§3.5 显式标记才开启
- collection-access-link §3 记录了取元语法的迁移与定稿

七、收益(诚实)
tool schema 最实:tools 已能写成记录行(tool_names 接受含 name/工具 的 Object),
但 agent_format_tools 只渲染 `- name`,说明与参数被丢弃——能力已在那儿,只差接上签名。

八、建议:表做声明不做定义,补三件事
① 消灭静默:契约表缺类型列/幽灵行/重复行/与 arity 不符 → check 应 warn(当前全静默)
② 反向生成:marqdo view 从签名生成契约表草案(单一真相仍是体,表是投影)
③ 签名可供机器消费:knowledge 能力条目带参数 schema → tool schema 自动生成
零语法改动。§9 给了「双写 + 一致性校验」的可试写法(E5 已验证可跑)。

未修改任何代码。
2026-10-22 12:46:13 +08:00
cflmy 3260494e5c docs(design): 评估「函数作为变量 / 函数即表」(未改代码)
回应「函数能不能是变量的一种,`函数名` = 参数|函数体 表,取元即调用」的提议。

核心结论:这个直觉在数学上成立,但一句话里混了四种不同的「函数」观,必须拆开:
- 外延观:函数是图 → 就是表,调用是查表(有限域才成立)
- 内涵观:函数是规则 → 调用是执行(定义域无穷,写不成表)
- 闭包观:函数 = 代码 + 环境
- 名字观:函数是命名空间一条(Marqdo 现状)
用户草图是「参数声明 + 函数体」的混合体,而「像表格取元」的直觉来自外延观。

现状实测(1.5.2,六组实验):
1. Value 枚举十种无函数;函数是 AST,挂 Module.functions
2. CallExpr.callee 是 String 不是 Expr → 语法上无法调用「计算出来的值」
3. 对象本来就是 Value::Map + _type 标签(对象是值,函数不是,这个不对称是关键)
4. 已存在 call_fn 按名字间接调用,但零参、限当前模块、只在运行期校验
5. 实验:`**f = > greet**` 报 missing argument(> 名字 是调用语法,无法引用函数本身)
6. 实验:表里存函数名 + [h](reg) + call_fn → 动态派发今天就能做

关键实测纠正(我最初写错、已改):
GFM 两列表绑定为「列映射」{"档位":[1,2],"税率":[...]},不是按首列键控的映射,
所以 [2](两列表) 报 missing map key 2。真正键→值查表需 Map(json.parse)
或用 table.index_of + table.at 显式索引(两条配方均已跑通)。

三条断裂点:表格有限 vs 函数常无限;函数体是代码不是数据(需 eval,静态检查/契约/
EKC 全失效);[k](x) 会被语义重载(与上一轮 [函数名](参数) 冲突同源)。

五条路径与代价对比(值模型改动/静态可索引/契约/EKC 指纹/序列化沙箱/成本),
并逐项分析对 Marqdo 特有机制的冲击:契约 T2.1/T2.2 依赖静态 target、
EKC 指纹 collect_calls 读静态 callee(src/knowledge/fingerprint.rs:76)、
value_to_json 对 Value 穷举(src/host/json.rs:98)、字节码 Op::Call(fid) 用编译期 id
(src/bytecode/compile.rs:709)。

建议分阶段:
- 立即:决策表(零改动),但补 table.lookup / table.by_column 库缺口
- 短期:扩展 call_fn(args=、跨模块、字面量静态校验)——不动值模型
- 中期:若要一等函数,走 ADR 并回答匿名函数如何进 EKC 索引
- 不建议:「函数即表」强主张(语义重载 + 削弱静态可索引性)

§9 给出折中:数据在表、逻辑在命名函数,兼顾表驱动直觉与可索引性。
未修改任何代码。
2026-10-22 12:35:40 +08:00
cflmy 3330a0fc66 chore: 还原 go.mod 被构建副产物改动的依赖分类
上一个提交误带入 plugins/web/go.mod 变更:构建 libweb 时用了 -mod=mod,
Go 把 jackc/pgx/v5 与 yuin/goldmark 从 indirect 提升为 direct。
这与本次文档提交无关,属于构建副产物,还原为提交前状态(内容与版本不变,
仅 require 块归类复原)。
2026-10-22 11:59:50 +08:00
cflmy 42a1a46383 docs: 链接式调用 [函数名](参数) 评估 + 开发环境脚本 dev-env.sh
两件事:

1. doc/design/link-style-call-evaluation.md(Proposed · 待决策)
   评估用户提议的 Markdown 链接式调用 [函数名](参数…)。

   结论:语法优雅,但与既有特性「链接索引 [key](map)」形状完全相同,无法可靠消歧。
   实测证据:
   - [a](m) → 链接索引,取成员,返回 1(既有特性,v0.3 明确推广)
   - [greet](alice) → 被当链接索引处理,报 undefined variable alice
   两者区别只在「greet 是函数还是键名」,需要符号表信息,而语法判定发生在
   解析期(跨模块时未知)。若靠「已知函数表」消歧,会把清晰的
   missing map key 变成误导性的 unknown function。

   给出四个受限方案并对比,推荐 L3:用「] 与 ( 之间是否有空格」消歧
   - [key](coll)  紧贴 → 链接索引,语义一字不动(零回归)
   - [callee] (args) 有空格 → 调用,参数显式成组,顺带解决 D8 空格函数名
   并附 8 条验证计划。未改任何代码。

2. scripts/dev-env.sh(新增,可 source 复用)
   本机测试环境缺失导致基线本来就有失败,本次装好并固化:
   - 约束1:$HOME 不可写 → zig/rust 缓存显式重定向
   - 约束2:/tmp 是 noexec tmpfs → TMPDIR 必须指向可写且可执行目录
     (这是 Go 链接报 "signal: aborted"、zig 报 AccessDenied 的真正原因)
   - 提供 rust 1.81 / go 1.25 / python 3.12 / gcc shim(zig, glibc 2.36)

   环境修复前后:
   - 无 python3:231 passed / 2 failed
   - 加 python3:233 / 0(lib)
   - 加 go + libweb:gold 284 / 0
   - 全量:554 passed / 0 failed

   libweb.so 构建要点:Go cgo 需要 gcc,用 zig cc 充当
   (/workspace/qdagent/.tools/zigcc/bin/gcc,过滤 Go 传入的
   -Qunused-arguments,该参数会让 zig 驱动 abort)。

变更文档同步追加 §8 记录环境安装过程与前后对比。
2026-10-22 11:59:14 +08:00
cflmy b6629e5450 fix(parse): D9 未闭合引号不再静默吞行(分类层 + 解析层双层修复)
缺陷:`**s = "abc`(引号未闭合)被静默当成叙述丢弃,退出码 0,
没有输出也没有报错,该行凭空消失。对「文档即程序」来说这是最危险的一类
错误——文档看起来完整、能跑、check 通过,实际少了一节。

根因在**分类层**而不是解析层:
parse_quoted_string 里 `unterminated " string` 的报错一直都在,
但 matching_bold_close 扫描时遇到未闭合的 '"' 后一直处于 in_str 状态,
再也找不到收尾 '**',于是 is_marqdo_star_line 返回 false,
该行被判为 LineKind::Comment 成为叙述,解析器根本看不到它。
解析层精心准备的报错不可达。

修复(两层,缺一不可):
1. src/lex/mod.rs
   - 新增 pub fn has_unterminated_string:统计未被 \ 转义的 '"',奇数即「开了没收」
   - is_marqdo_star_line:粗体起始且找不到收尾时,若引号未闭合则仍判 Code
     (判 Comment 会静默丢行;判 Code 才能让解析器说话)
2. src/parse/mod.rs
   - parse_simple_stmt 紧跟既有粗体分支之后,对「粗体起始 + 引号未闭合」
     给出精确报错,而不是笼统的 unrecognized statement

影响面(改前量化,避免凭直觉改核心解析):
- 全仓库 845 个 .mq.md、620 个含代码行文件
- 引号计数为奇数的代码行:**0**
- 结论:不改变任何现有文件的解析结果,只作用于畸形输入

测试(TDD,先写测试确认失败再修):
- 新增 4 个单测:未闭合→Code、闭合→Code、叙述含引号→Comment、
  叙述含孤立引号→Comment
- 修复前 unterminated_quote_inside_bold_is_code_not_comment 如期失败
- 修复后 lex 14/14;cargo test --lib 237 passed 0 failed(基线 233 + 新增 4)
- cargo test --test gold 276 passed 8 failed;git stash 验证基线同样 8 failed,
  失败全部是 ext_web_*(依赖 Go 插件 libweb,本机环境不具备),与本次无关

文档:
- doc/design/parser-diagnostics-d8-d9.md  设计依据、根因链路、候选方案评判、影响面
- doc/design/change-d9-unterminated-string.md  变更记录(现象/根因/改法/测试/边界)
- doc/design/spaced-function-names-d8.md  D8 方案评估(待审阅,未改代码)

已知边界:单引号 '...' 未闭合仍是旧行为,留作后续评估
(单引号兼作英文撇号,误判风险高于双引号)。
2026-10-22 11:52:27 +08:00
cflmy ecd7d5e433 examples: 新增 oa2026-showcase(2026 开源项目大赛作品介绍示例集)
五个可运行示例,覆盖 Marqdo 的核心能力面:

| 文件 | 展示 |
|------|------|
| add.mq.md | 叙述统一、粗体即代码、斜体即返回 |
| invoice.mq.md | 表格即数据、循环、分支、断言 |
| calculus.mq.md | 公式即变量、求导、求根、绘图 |
| bell.mq.md | 量子电路、概率、断言、SVG 派生物 |
| foreign-node.mq.md | 外联一次性执行、持久会话、显式传值 |

全部实测跑通(1.5.2),输出与 README「预期输出」一节一致:
- add → 42
- invoice → 960 / 912 / 966 / within-cap
- calculus → 3*x^2 - 3 / 9 / [-1.73, 0, 1.73] / plot-ok
- bell → {00: 0.5, 11: 0.5} / bell-00-ok / bell-11-ok / bell-draw-ok
- foreign-node → 区域汇总表 + 持久会话复读

仓库侧改动:
- examples/oa2026-showcase/*.svg 随示例入库(README 有说明,属固定产物)
- .gitignore 忽略根目录 bell-*.svg / calculus-*.svg —— 从仓库根运行示例时
  draw/plot 会把 SVG 写到 cwd,那是运行产物不是源文件
- examples/marqdo-blog/db/posts.mq.md 首行正文去掉了内嵌 `#` 标题写法
2026-10-22 10:41:41 +08:00
cflmy aeb5a2a43d docs(tutorial): 新增《常见陷阱手册》,并补 D8–D10、按实测收敛 D3
把 qdagent 重构期间踩到的坑整理成**使用向**手册 doc/tutorial/15-常见陷阱.md
(417 行,全部条目在 1.5.2 逐条实测,含现象/原因/改法三段式与提交前自查清单)。

手册要点:
- §1 写文档:行首数字必报错(2026 年 / 42 条 / 3 个要点 都中招);
  行首 + 报错;未闭合引号静默吞行(最危险)
- §2 变量作用域:模块级变量在 # main 与各 ## 之间不可见;
  顶层不许裸语句;table.put 不原地修改
- §3 函数:函数名含空格时定义成功但调用必崩
- §4 字符串:引号内 ** / | / # 实为安全,只有引号不配对才出事
- §5 导入:相对路径以当前文件为基准;标准库必须带库名前缀
- §6 易记错的函数签名(txt.contains 的 sub、table.put 的 in/at/value …)
- §7 结构:# main 体不被 ## 截断;1./2./3. 是 if/elif/else 链
- §8 自查清单(marqdo check + run 双跑)

同步修正缺陷实录 research/qdagent-refactor-defects-2026-10.md:
- D3 收敛:实测证明 - / > / | / [ 在叙述区**安全**,只有行首数字与 +
  会被当语句;判据是「该行能否被解析成完整语句」
- 新增 D8 函数名含空格:定义成功、调用必崩,check 却通过(不对称)
- 新增 D9 未闭合引号静默吞行,退出码 0(静默类最危险)
- 新增 D10 table.put 非原地,累积计数静默失效
- 同步复现清单与变更记录

索引:tutorial/README 增第 15 章;doc/README 增手册与缺陷实录两行。
手册内所有代码示例均实测跑通(含参数传递修法、if 链、标准库前缀)。
2026-10-22 09:46:17 +08:00
cflmy f2d651e063 docs(research): qdagent 重构期间发现的运行时缺陷实录(D1–D7)
在 qdagent 实现「智能体输出必须是可运行 .mq.md」的机械门禁
(提取 → 结构检查 → 沙箱试跑)时,暴露 Marqdo 1.5.2 的一批
行为与文档不一致、诊断不可用、静默降级问题,逐条记录并给出建议:

- D1 高 sandbox.profile 仅回显不生效:readonly 与 default 等价,
  RunOptions 硬编码 allow_fs_write=true(安全语义静默失效)
- D2 高 全角冒号 调用:<name> 无法解析,但提示文案推荐全角;
  extract_tool_name 用 split sep=":",与 READ/DECISION 的全半角支持不一致
- D3 中 叙述行行首执行标记(数字/-/>/|/[/**/*)导致中文文档解析失败;
  对 LLM 生成文档是高频陷阱,建议增强诊断与 check 规则
- D4 中 sandbox.run source= 报错丢上下文:文件名显示 <memory>,
  未提示「源文本必须含 # main」
- D5 中 [key](map) 键缺失硬崩:sandbox.run 成功形状无 error 键,
  按防御式写法在成功路径崩溃;建议统一形状
- D6 低 未绑定 GFM 表不可迭代,报错不指向根因
- D7 低 沙箱内 subtask spawn path= 设计性不可用,未在沙箱文档明示

附「确认正常的项」以避免误报,与逐条复现清单。
2026-10-22 09:03:07 +08:00
cflmyandCursor b020b9d218 Ignore PLDI harness scratch and test plot SVG leftovers.
Keep experiment temp trees and regenerated *-plot-*.svg out of the interpreter tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 12:56:51 +08:00
cflmy 33a14d272c release: v1.5.2 — foreign v3 P0/P1 (stdin, plan API, snapshot, capture, persist) 2026-10-18 14:57:15 +08:00
cflmy 6ed70fd8b8 docs(design): defer G7 and G8 from the v3 target
Keep the cross-document scope and non-Python/Node adapter designs in the document for future work, but remove them from the current implementation target and priorities.
2026-10-18 14:51:12 +08:00
cflmy 115d1f6c0b feat(view): explicit persist and nested-plan boundary
Add per-cell Persist backed by lib/writeback and /api/session/cell/persist. Reject nested foreign.session plans with a top-level diagnostic and tests.
2026-10-18 14:47:54 +08:00
cflmy 7dc5e56850 feat(foreign): reject nested view plans
Enforce the v3 plan boundary: foreign.session must be a top-level binding. Nested plans are diagnosed instead of silently becoming stateless. Tests cover the AST helper and DocumentSession open.
2026-10-18 14:46:57 +08:00
cflmy 514caa55ae docs(design): mark G9 snapshot capture implemented
view capture and view output --snapshot are implemented with source-hash validation; remaining gaps are G3/G7/G8/G10.
2026-10-18 14:46:20 +08:00
cflmy 74908ebf04 feat(view): capture live snapshots for static export
Add view capture to record per-cell outputs and session summary with source hashes. view output --snapshot consumes the capture without re-executing and rejects source drift. Includes snapshot parsing tests.
2026-10-18 14:45:26 +08:00
cflmy 0f852593bc docs(design): record foreign v3 P0/P1 implementation status
Mark stdin/per-cell inputs/interrupt and plan/snapshot APIs as implemented; keep G3/G7/G8/G9/G10 as pending design items.
2026-10-18 14:44:29 +08:00
cflmy 34e2fb4f74 feat(foreign): snapshot export, import and replay
Export JSON-safe kernel values, cells and journal; restore values into a matching plan; replay cells with recorded stdin. Add /api/session/snapshot/{export,import,replay}.
2026-10-18 14:43:53 +08:00
cflmy 0e407b2bd3 feat(foreign): runtime plan updates and generation
Add explicit add/remove cell and set-value operations with a plan generation counter. Expose /api/session/plan/{assign,add,remove,value}.
2026-10-18 14:43:26 +08:00
cflmy e5e532d83f fix(foreign): keep session_list arity empty
ForeignSessionList accepts no id; only ForeignSessionInterrupt takes id.
2026-10-18 14:38:27 +08:00
cflmy 064522a338 feat(foreign): raw stdin, per-cell inputs and interrupt
Persistent Python/Node kernels receive raw program stdin per eval; foreign.session accepts an inputs table and view exposes per-cell stdin. Add session interrupt host API and view control.
2026-10-18 14:37:45 +08:00
cflmy c85f1a2829 feat(foreign): support raw stdin and per-cell inputs
Session eval now carries raw stdin, and the Python/Node workers temporarily replace program stdin during evaluation. foreign.session accepts an inputs table; view exposes per-cell stdin and Run All sends a per-cell input map. Stateless and persistent cells share the same input semantics.
2026-10-18 14:36:47 +08:00
cflmy a7266185b2 docs(design): propose foreign v3 capability plan
Document the remaining foreign runtime gaps: persistent raw stdin, per-cell input, dynamic plan boundaries, runtime plan updates, interrupt, state export/replay, cross-document scope, non-Python/Node adapters, live-to-static snapshots and explicit writeback policy.
2026-10-18 14:31:44 +08:00
cflmy 4d7c0bea1b fix: sync Cargo.lock with v1.5.1 version bump 2026-10-18 14:23:20 +08:00
cflmy 53758ebd1c debian: changelog entry for 1.5.1-1ppa1 2026-10-18 14:20:24 +08:00
cflmy dff0b700ae release: v1.5.1 — view static/live unified + foreign value passing 2026-10-18 14:05:19 +08:00
cflmy 4da07c1b26 fix(view): do not turn documentation tables into call chips
Keep descriptive table labels non-callable and suppress call annotations on table blocks. This removes the collapsed call {步骤...} chip while preserving the table and the return 950 chips at the actual foreign/writeback calls.
2026-10-18 13:59:24 +08:00
cflmy 78922102e4 fix(view): anchor imported-function returns at their call site
Track the caller line on CallFrame and use it for return annotations instead of the callee library line. Return 950 stays visible on the actual foreign/writeback calls; the Markdown table remains intact and no longer receives stray return chips.
2026-10-18 13:56:50 +08:00
cflmy 064bae2c65 docs(view): keep writeback table labels as inline code
Wrap foreign.run/session and writeback.record table labels in code spans so the prose table is not traced as executable calls; this removes the stray return 950 chips.
2026-10-18 13:52:51 +08:00
cflmy 92b91ffc81 fix(view): group and theme writeback blocks
Render contiguous writeback comment lines as one block, and map output-card/writeback tokens to the View dark theme. Static and live pages no longer show three dashed fragments or light output cards on dark.
2026-10-18 13:51:11 +08:00
cflmy ab6648ae0e docs(view): make the writeback page itself the runnable example
Move the foreign + writeback demo into the user persistence page. The page runs a Python code fence, records a keyed total slot, and the slot is visible in both source and static rendering. Remove the separate example document.
2026-10-18 13:48:05 +08:00
cflmy 5acf026e0c docs(view): add a runnable foreign writeback example
Move persistence guidance out of the walkthrough into separate static pages. Add examples/foreign-writeback/index.mq.md, which executes a foreign code fence and writes a keyed total slot into its own source.
2026-10-18 13:45:27 +08:00
cflmy 8dcd69412f docs(view): recommend static snapshots and writeback persistence
Add a persistence recommendation to the user-facing foreign walkthrough: static export for published snapshots, and lib/writeback for opt-in result slots in the .mq.md source. Show a readable code-fence based writeback example.
2026-10-18 13:40:44 +08:00
cflmy 2a13e52981 docs(view): show low-level session evaluation as code fences
Replace inline source strings with readable Python code fences bound as Marqdo code values. The low-level session evaluates those values; no long escaped source argument remains.
2026-10-18 13:35:51 +08:00
cflmy 9b269f6447 feat(foreign): pass Marqdo values into multi-kernel view sessions
foreign.session accepts a values table and initializes each kernel from ordinary Marqdo values. The static walkthrough now uses two kernels and a shared 订单 value instead of redefining orders inside Python. Static pages embed the session summary so kernel controls and Clean stay visible.
2026-10-18 13:32:51 +08:00
cflmy 15362cb048 fix(view): restore per-cell kernel switch and Clean
Code cards again show a kernel selector and a Clean button. Clean calls /api/session/cell/clear for live sessions and clears local output in static snapshots, without restarting kernels.
2026-10-18 13:27:15 +08:00
cflmy 05d48f68a4 docs(view): show kernel state and Marqdo value passing
Rewrite the static foreign walkthrough without stdin-driven examples. It now demonstrates session_set from an ordinary Marqdo table, persistent kernel state across evaluations, and a foreign.session view plan sharing state across cells. Static export executes those cells and embeds the real outputs.
2026-10-18 13:23:03 +08:00
cflmy e4387259ba fix(view): make static examples self-contained
Foreign cell examples read stdin with a deterministic fallback, so static exports show real output without tracebacks. Low-level session bindings named 会话 are no longer mistaken for a view plan; static export runs all cells again.
2026-10-18 13:19:41 +08:00
cflmy 518f8e386b fix(view): avoid stdin tracebacks in static snapshots
Static export skips cells that read stdin when the document has no preset stdin, and shows a short explanation instead of a traceback. Preset stdin still executes normally.
2026-10-18 13:14:17 +08:00
cflmy 9da12c9093 feat(view): add cell stdin for live and static runs
View gets a Cell stdin/input field wired to cell Run, Step and Run All. Stateless cells receive raw stdin; persistent kernels receive marqdo_input. Static export uses the document preset stdin and the same run_all path.
2026-10-18 13:10:08 +08:00
cflmy e0d34669e0 fix(view): use the same run path for static and live cells
Run All now records per-cell failures and continues; static export uses the same foreign_doc run_all and injects those records. A cell that succeeds in view therefore succeeds in the static snapshot, and failures match.
2026-10-18 13:03:46 +08:00
cflmy 0ba4d3d2d7 feat(view): render real cell outputs in static exports
Static export opens the foreign document session, runs cells once, and injects stdout/stderr/error into the code cards. Failures are shown as real errors; --no-exec still skips execution.
2026-10-18 13:00:41 +08:00
cflmy ad3ebf243a fix(view): keep static buttons with a no-live notice
Static pages now render the same toolbar and Execution Clear button as live view. Clicking any execution control shows a static-export notice instead of hiding controls or pretending to run.
2026-10-18 12:55:07 +08:00
cflmy 142d30ce08 fix(view): share the same shell between static and live output
Static exports now include the View shell and dark theme; interactive toolbar and Execution Clear stay hidden, while dynamic pages show them.
2026-10-18 12:52:48 +08:00
cflmy 4757b82edd fix(view): run stateless documents and clear Execution output
No-session view Run All now runs the document and renders stdout into Execution; Clear outputs clears Execution output, plots and plan cards as well as cell outputs.
2026-10-18 12:51:13 +08:00
cflmy bff2f53e52 fix(view): clear Execution output from the view surface
Add an Execution Clear button and clear the Execution out/plots/plan card in addition to code-cell outputs. The same clearOutputs path calls /api/session/clear, so ordinary stateless pages and foreign sessions are both wired.
2026-10-18 12:47:56 +08:00
cflmy fb28eee62f feat(foreign): own view sessions and clear outputs
foreign.session returns a handle from ordinary kernel/cell tables; view consumes only the 会话 binding. Sessions live in host foreign_doc. Without 会话, view cells run stateless one-shot. Add /api/session/clear and a Clear outputs button for every view page; clearing keeps persistent kernel state.
2026-10-18 12:42:15 +08:00
cflmy 01468ad976 test(view): add foreign and non-foreign preview fixtures
Add a pure Marqdo control page and make the Python view-cells example explicitly import lib/foreign.
2026-10-18 12:22:36 +08:00
cflmy f3791d11b4 refactor(view): evaluate cell plans through the interpreter
Delete the source-line table scanner. 内核表/会话表 are now evaluated as ordinary Marqdo bindings (with simple assignment dependencies) via Interpreter::capture_declarations. Every view page uses the same cell toolbar; run/watch semantics are unchanged; no new CLI or Markdown marker.
2026-10-18 12:17:42 +08:00
cflmy 7fef690167 refactor(view): unify cells into the view surface
Cell controls now appear only when a document declares 内核表/会话表. Remove Notebook branding and Jupyter In/Out prompts; ordinary view pages stay classic. There is no new CLI command or second interactive mode; run remains canonical execution and view is the only interactive surface.
2026-10-18 12:03:17 +08:00
cflmy 024cdee82a debian: add 1.5.0 PPA changelog 2026-10-18 03:36:53 +08:00
cflmy f666eaaf40 release: v1.5.0
Foreign v2 + document-native notebooks, view contrast/themes/resize, public OKF/EKC and Python examples. Bump CLI/wasm/ext to 1.5.0; no core surface delta.
2026-10-18 03:17:53 +08:00
cflmy e6f05c7748 docs(public): showcase foreign v2, OKF and EKC
Rewrite the public foreign reference, add bilingual complex Python notebook and OKF/EKC pages, and expand both homepages with executable foreign, notebook, knowledge and preflight examples.
2026-10-18 03:15:34 +08:00
cflmy 81f9ea0072 fix(view): map document tokens to the active theme
Legacy view tokens (--ink, --fill, --line, --muted) now resolve from the notebook theme. This fixes dark text and white annotation chips on the dark STRUCTURE surface, including function names, binding labels, tables, and the right rail.
2026-10-18 03:05:29 +08:00
cflmy dbf3f3a14b fix(view): raise code contrast and unify syntax colors
Remove the two conflicting highlight.js stylesheets and define one high-contrast token palette. Dark code foreground is #f0f0f0 on #1e1e1e (14.6:1); light is #24292f on #f6f8fa (13.8:1). Keywords, strings, and comments stay above readable contrast, and base view code blocks are resizable too.
2026-10-18 03:03:08 +08:00
cflmy 654e89d98c style(view): make cell resize affordance visible
Style the native vertical resize grip and add a hover hint on code and output panes.
2026-10-18 02:59:36 +08:00
cflmy be20629496 feat(view): resizable cells and light/dark themes
Add native vertical resize to code and output panes; add a VS Code Light token set with Jupyter light syntax highlighting, a toolbar theme toggle, and localStorage persistence. Keep the restored three-column layout.
2026-10-18 02:59:21 +08:00
cflmy 3223295841 fix(view): restore notebook left nav and right rail
Keep the original three-column layout (file navigation, main structure, Functions/Variables rail) and execution/source sections; restyle them with the same VS Code dark surface tokens so the notebook remains readable and consistent.
2026-10-18 02:56:34 +08:00
cflmy beb5bdbe8c style(view): align notebook with VS Code dark and Jupyter cells
Flat VS Code Dark surfaces and borders, Jupyter In[n]/Out[] cell structure, unified top cell toolbar, consistent typography and spacing, removed gradients, glows, heavy shadows, and multi-color pills.
2026-10-18 02:51:28 +08:00
cflmy b8cb022018 style(view): redesign notebook layout and controls
Single-column notebook shell, sticky glass toolbar, card cells with language/kernel/status pills, output panel, dark-mode support, responsive layout, and hidden duplicate Execution/Source sections.
2026-10-18 02:45:10 +08:00
cflmy b9e331cb31 test(notebook): add Python business-insights example
Five-cell Python notebook sharing one kernel: deterministic order generation, regional/product metrics, z-score anomaly detection, ASCII report + JSON, and an isolated second Python kernel that validates the report through an explicit file bridge.
2026-10-18 02:38:48 +08:00
cflmy 476c2b607b fix(view): use relative API URLs for path-prefix reverse proxy
Notebook and debugger controls now call api/... and open debug?path=... relative to the page, so the same HTML works under a path prefix such as /marqdo-view/<token>/. This enables same-origin DSH preview without publishing another Docker port.
2026-10-18 02:33:50 +08:00
cflmy d99b275336 fix(parse): do not over-promote branch-local variables to params
If/else arms that all bind a local (e.g. # llm key/url/mdl/nm) no longer leak it into constructor params. This fixes the missing `key` error in llm.create and restores the agent/llm gold tests. Adds a regression test.
2026-10-18 02:09:16 +08:00
cflmy 1415aee08f docs(notebook): record D1–D3 implementation status 2026-10-18 01:45:41 +08:00
cflmy 0f2c12b636 feat(notebook): link statement debugger from view
Expose /debug and /api/debug/* on the live view server; add a notebook Debug button so Marqdo statement stepping is reachable from the same page/session as cell stepping.
2026-10-18 01:44:05 +08:00
cflmy 9873df7099 feat(notebook): reload, journal and state panel polish
D3 (partial): reload re-parses the document while preserving kernels, marks changed cells dirty; Journal and Reload view actions; filtered Node variable names for the state panel; per-session timeout parsing before spawn.
2026-10-18 01:41:36 +08:00
cflmy 3001ed7ba5 feat(notebook): document session with shared kernels and view controls
D1/D2: 内核表/会话表 parsing, DocumentSession cell index, named/default kernels, shared state + isolation, run_cell/step/run_all/restart/assign, state bridge, journal, POST /api/session/*, and a live-view notebook bar with status badges, per-cell kernel selector, step/run-all and push/pull state form.
2026-10-18 01:39:36 +08:00
cflmy 050d71927f feat(foreign): persistent Python/Node kernels and state bridge
F3/F3.5: session_open/eval/close/list, session_set/get/names, Python and Node bootstraps, strict serial protocol, per-session timeout, crash isolation, drop cleanup, and node/bash gold tests (python conditional).
2026-10-18 01:32:48 +08:00
cflmy 7859170aec feat(foreign): JSON call and parallel fan-out
F2: call/call_many JSON bridge, run_many ordered parallel execution with per-item isolation and concurrency cap, plus node gold tests for call and call_many.
2026-10-18 01:29:15 +08:00
cflmy e32ff8f6b3 feat(foreign): structured invoke, presets, probe and config
F0/F1: safe execution core (exec gate, bounded IO, process-group timeout), structured invoke records, run options, 15 language presets, register/unset/probe/config, view stderr/exit/ms, and node/bash gold tests.
2026-10-18 01:26:53 +08:00
cflmy c21a28c3bc docs(foreign): design kernel runtime and document session
Record the Jupyter-beyond discussion, decisions, and the document-native notebook syntax (内核表/会话表). Split the design into F (foreign kernel runtime) and D (document session) layers, with roadmaps, state bridge, stepping, journal, and security rules.
2026-10-18 00:43:31 +08:00
1489 changed files with 142267 additions and 44878 deletions

No files matched your search

+6 -213
View File
@@ -1,221 +1,14 @@
---
name: marqdo-dev
description: >-
Develop Marqdo programs and libraries the readable way: GFM tables as data,
code-as-documentation, table.put over json.set chains, lib/ext authoring.
Use when writing or refactoring .mq.md, creating lib/* or ext/*, reviewing
Marqdo style, fixing unreadable json glue, or when the user asks how to
develop Marqdo / 如何开发 marqdo.
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.
---
# Marqdo development (author + library)
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.
Read this **before** writing or expanding `.mq.md`. Syntax basics stay in [marqdo](../marqdo/SKILL.md); this skill is the **style and library craft** contract.
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.
## Non-negotiable: code is documentation
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.
A `.mq.md` file must stay readable as Markdown. If a human cannot skim the data and intent without decoding nested `json.set` / `json.append` chains, the code is wrong.
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.
| Prefer | Avoid |
|--------|--------|
| GFM tables for maps, lists, records, wire, commands | Building the same with `json.set` / `json.append` |
| Named library helpers (`web.*`, `browser.*`, `table.*`) | Copy-paste effect-map glue in every handler |
| `table.put` for **one** dynamic key | Long `json.set` pipelines |
| `json.parse` / `json.stringify` / `json.quote` only | Using `json` as a general dict builder |
`lib/json` is for **parse / stringify / quote**. Collection edits use **GFM tables** and **`lib/table`** (`doc/design/stdlib-table.md`).
## How to shape data
### 1. GFM table geometry (memorize)
| Shape | Result |
|-------|--------|
| 1 column | list |
| ≥2 columns, **one** data row | map (headers = keys) |
| ≥2 columns, **many** rows | map of lists (column-oriented) |
| First header `@` / `行` / `row` | **list of maps** (row records) |
Cells are expressions (`doc/design/table-cell-expressions.md`): bare words = text, `` `var` `` = variable, quote paths/`/` ratios.
### 2. Good patterns (copy these — not `json.set`)
**Wire / steps / commands** — `@` record table:
```markdown
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
```
**Multi-key return / boot** — map table with variable cells:
```markdown
`boot` =
| wire | set_text |
|------|----------|
| `wire` | `set_text` |
```
**Agent / LLM result map** — one readable row, not a `json.parse` + `json.set` chain:
```markdown
`out` =
| status | task | result | llm_calls | tokens |
|--------|------|--------|-----------|--------|
| ok | `task` | `reply` | `llm_calls` | `tokens` |
*out*
```
**Soft error pack** (transport / gate failure) — still a table humans can skim:
```markdown
`pack` =
| finish | text | error | usage | tool_calls |
|--------|------|-------|-------|------------|
| error | "" | `msg` | `usage0` | `empty_tc` |
*pack*
```
**Optional / conditional key** — sparse `table.put` after the static table (one dynamic key only):
```markdown
`out` =
| status | task |
|--------|------|
| error | `task` |
1. `err`
**out = > table.put in=`out` at="error" value=`err`**
2. *
**_ = 1**
```
**Empty list / empty map** — prefer stdlib seeds over `json.parse text=[]` / `{}`:
```markdown
**empty_tc = > table.empty_list**
**empty_map = > table.empty_map**
```
**Single dynamic key from scratch** — one `table.put` (or a helper), not a json chain:
```markdown
**`set_text` = table.put in=None at="#log" value=msg**
**table.put in=None at="set_text" value=set_text**
```
Better still — call a named helper:
```markdown
**browser.set_text sel="#log" text=msg**
```
**When `json.*` is OK:** `json.parse` / `json.stringify` / `json.quote` on **wire text**; `json.get` to read an opaque map. Never use `json.set` / `json.append` to *build* author-facing structures.
### 3. Bad pattern (do not write — and do not copy from old `ext/ai`)
```markdown
**`ret` = json.set map=None key="set_text" value=…**
**`ret` = json.set map=ret key="canvas" value=…**
**`cmds` = json.append list=cmds item=c0**
**`out` = json.parse text={"status":"ok"}**
**`out` = json.set map=out key="task" value=task**
```
Matching surrounding **legacy** `json.set` in `ext/ai/*.mq.md` is **not** compliance. Refactor the call site to tables / `table.put` instead of extending the glue.
## Writing application `.mq.md`
1. Frontmatter: title + imports (`table`, domain libs). **Do not import `json` unless parsing strings.**
2. `# main`: state binds, then **tables** for wire/config, return boot map via table or helper.
3. `##` handlers: short prose OK; data as tables; return via `browser.*` / `web.*` / one `table.put`.
4. Blank line between comment paragraphs and code.
5. Run `marqdo run path.mq.md` from repo root.
6. **Calls in narrative:** prefer `**结果 = 某函数 名=`x`**` (no `>` on the RHS). Bracket form `礼貌 [问候] "x"` / `**出 = [put] …**` is fine when modifiers help. Use `> …` for standalone step lists. See `examples/code-as-docs/`.
7. **Do not use `##` inside `# main` for document sectioning** — those become nested functions. Use paragraphs / `---` breaks instead.
8. **Index:** prefer `[键](集合)` / `` [`名`](集合) `` over footnote `` m[^k] ``.
Browser client programs: prefer `import browser:lib/browser.mq.md` (no native plugin). Server sites: Artifact Metadata (`type: web|endpoint`) + `ext/web` facade + `ext/data` / `ext/security` / `ext/net` — see [ext-web-artifact.md](../../doc/design/ext-web-artifact.md). **Never** restore `compose_*` / `app.configure`.
## Developing libraries (`lib/*`, `ext/*`)
Canonical thin-template + waves: [lib-code-as-docs.md](../../doc/design/lib-code-as-docs.md) · [roadmap/lib-ext-code-as-docs.md](../../doc/roadmap/lib-ext-code-as-docs.md).
### Goals
- **Authors** see tables and short calls; **library** may hide `table.put` / host calls.
- One concern per helper; name the effect (`set_text`, `canvas`, …), do not expose bag surgery.
- EN + ZH pair when shipping user-facing libs (`lib/browser.mq.md` ↔ `lib/浏览器.mq.md`, `ext/web` ↔ `ext/web/网页.mq.md`).
- `ext/**` never calls `host_*` — use plugins / public lib only (`doc/design/ext-agent.md`).
- Collection get: **`[key](coll)`** (no new footnote indexes). Calls in examples may use `修饰 [fn] …` or classic `>` / bold.
### Library checklist
- [ ] Purpose sentence + prose params + one example + short body
- [ ] Public examples use **tables + helpers**, not json glue
- [ ] Index with `[k](c)`; foreach `- [item](coll)`
- [ ] Helpers documented with a one-line purpose above `##`
- [ ] Defaults on params; omit `None` fields in merged maps
- [ ] No `json.set` chains in new code — use `table.put` / `table.merge` / GFM
- [ ] `marqdo run` on a tiny demo under `examples/` or inline smoke
### Where helpers live
| Need | Place |
|------|--------|
| Browser effect maps (WASM client) | `lib/browser.mq.md` |
| Site HTML / HTTP | `ext/web` Document/Endpoint + View tables |
| DB / cache / storage | `ext/data` |
| Auth / OIDC / RBAC | `ext/security` |
| List/map primitives | `lib/table.mq.md` |
| Parse JSON text | `lib/json.mq.md` only |
## Refactoring existing glue
When editing a file full of `json.set`:
1. Turn static structures into GFM tables.
2. Replace repeated effect shapes with `browser.*` / `web.text_patch` / `web.dom_patch`.
3. Leave at most sparse `table.put` for dynamic keys.
4. Drop `import json:…` if unused.
## Anti-patterns
| Wrong | Right |
|-------|-------|
| `json.set` × N to build boot | GFM map table or `browser`/`web` helper |
| `json.append` to build command list | `@` record table |
| Dummy column to force a 1-key map | `table.put` or helper |
| Importing `ext/web` only for `text_patch` in WASM | `lib/browser` (no native plugin) |
| Unreadable nested maps as “clever” | Flatten into tables humans can read |
## Related
- Syntax: [marqdo/SKILL.md](../marqdo/SKILL.md) · [examples.md](../marqdo/examples.md)
- Tables: `doc/design/stdlib-table.md` · `doc/design/table-cell-expressions.md`
- Browser effects: `doc/roadmap/browser-wasm-e.md` · `doc/roadmap/browser-wasm-f.md`
- Release: [marqdo-release](../marqdo-release/SKILL.md)
## 渐进式契约 + MLSP(Phase 2/3 落地后的开发戒律)
- **契约实现**:`src/contract.rs`(类型词汇 / 三形状契约表解析 / 合并 / 四边界校验诊断);
`src/parse/mod.rs::extract_function_contract`(位置 + 形状双重判定,**在升参推断之前**执行;
绑定表与普通文档表绝不吃 ⇒ 无契约文件零回归)。契约表从 body 移除——元数据永不执行。
- **静态互查**:`src/check.rs`(`marqdo check [--json]`)——契约行 vs 升参推断形参双向漂移、
未知类型名、错位契约;Error ⇒ 非零退出。
- **AI 工具面**:`src/mlsp.rs`(`marqdo mlsp`,行分隔 JSON)——`locate` / `syntax` / `validate` /
`repair_targets` / `schema`。语法唯一事实来源 = `parse::CORE_CONSTRUCTS`(CI 守卫与
`doc/design/core-surface.md` 同步);MLSP 只加检索别名,**不定义语法**。
- **准入戒律**:新特性先过 `doc/design/layers.md` 三层归属(Language 层改动须 ADR + core-surface);
新契约形状/类型词汇 = 文档层扩展,进 `src/contract.rs`,不进词法/语法。
- **错误出口唯一**:`src/load.rs::label_error` 已示范——装载层/任何新代码都**不许**把
`Diagnostic` 拍平成字符串;错误链里必须能 `Diagnostic::find` 找回结构化诊断(AI/MLSP 面)。
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.
+6 -201
View File
@@ -1,209 +1,14 @@
---
name: marqdo-release
description: >-
Run a Marqdo product release: detect latest version and ask the user for the
next tag (or confirm mode), update CHANGELOG/README/skills/public docs, bump
Cargo and/or ext/VERSION, sync VS Code extension when needed, publish GitHub
Release assets, upload extension packs to Cloudflare R2 (ext.marqdo.com) and
GitHub, ship Ubuntu CLI via PPA (scripts/ppa-ship.sh), and print manual
commands when sudo/GPG/network steps need the user. Use when the user asks to
release, cut a version, publish vX.Y.Z, ext-only pack, PPA, 发版, 发布新版本,
or tag marqdo.
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.
---
# Marqdo release
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.
Canonical release playbook for **cflmy/marqdo**. Read this skill **before** tagging or uploading assets. Details: [reference.md](reference.md).
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.
## Hard rules
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.
1. **Never invent the next version.** Detect current versions → **stop and ask the user** for the next SemVer (`X.Y.Z`) and **release mode** if unclear. Do not proceed until they confirm (unless they already stated both in the same message).
2. **Never force-push** `main` / tags. **Never** `--no-verify` unless the user explicitly orders it.
3. **Never commit `vscode-extension/` on `main`** (gitignored). Extension source lives only on branch **`vscode-extension`**. See `doc/design/vscode-extension-commit.md`.
4. **Do not release from a dirty tree** (except intentional release commits you create in this flow).
5. **Tag format:** CLI/full → `vX.Y.Z` matching root `Cargo.toml`. Ext-only → `ext-vX.Y.Z` matching `ext/VERSION` (Cargo may stay unchanged).
6. Prefer **tag push → GitHub Actions** (`.github/workflows/release.yml`) for Windows/Linux install assets. Local packaging is fallback / verification.
7. After network errors: apply [reference.md § Proxy](reference.md). **First try** `https://proxy.cflmy.top/github.com/cflmy/marqdo.git`. Retry; do not silently skip uploads. If needed: **HK jump** (`scripts/push-via-hk-jump.py`).
8. **Do not ship a full GitHub Release without the Linux extension/native zip** when the mode includes ext packs. Missing Linux packages = incomplete for that mode.
9. **Extension packs always publish to both** Cloudflare R2 (`https://ext.marqdo.com` via `scripts/upload-ext-r2.py`) **and** GitHub (Release assets / `ext-v*` tag). Credentials only in `~/.marqdo/r2.env` / CI — **never** commit. See [ext-cdn.md](../../../doc/design/ext-cdn.md).
10. **CLI Ubuntu package = PPA** (`ppa:cflmy/marqdo`) via `./scripts/ppa-ship.sh` / `ppa-build-source.sh`. GitHub zips remain for Windows and non-apt Linux.
11. **When a step needs the user** (sudo password, GPG passphrase, Launchpad UI, interactive `dput`): **stop, state what failed, and give the exact commands** to run in their terminal. Do not pretend the step succeeded.
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.
## Release modes
Ask (or take from user message) which mode:
| Mode | Bumps | Git tag | GitHub assets | R2 CDN | Ubuntu PPA |
|------|-------|---------|---------------|--------|------------|
| **full** (default) | `Cargo.toml` + `ext/VERSION` (same SemVer) | `vX.Y.Z` | CLI + ext + native + VSIX + … | yes | yes |
| **cli** | `Cargo.toml` only | `vX.Y.Z` | CLI (+ optional attach prior ext) | no (unless user asks) | yes |
| **ext** | `ext/VERSION` only | `ext-vX.Y.Z` (or attach to latest CLI release) | ext.zip + native-*.zip | **required** | no |
Defaults after version+mode confirmed — **do not re-ask**:
| Setting | Default |
|---------|---------|
| Sync / bump `vscode-extension` to same `VER` | **yes** for full/cli; **no** for ext-only |
| Push `main`, create annotated tag, push tag (trigger CI) | **yes** for full/cli |
| Ext packs → R2 **and** GitHub | **yes** whenever ext ships |
| Ubuntu PPA upload after CLI tag | **yes** for full/cli |
| Release notes language | **中英双语** |
| Deploy gh-pages after release | **no** (only if user asks) |
Phase 0 ask example:
> 当前最新 CLI **vA.B.C**,扩展包 **E.F.G**。请指定下一个版本号与模式(`full` / `cli` / `ext`,如 `1.0.3 full`)。
## Phase 0 — Detect versions (mandatory stop)
```bash
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
```
Report briefly, then **ask for SemVer + mode** (unless already given). Normalize `VER` / `TAG`.
## Phase 1 — Preflight
```
Release progress:
- [ ] Phase 0: version + mode confirmed
- [ ] Phase 1: preflight green
- [ ] Phase 2: docs + version bumps committed
- [ ] Phase 3: extension branch (full/cli)
- [ ] Phase 4: main pushed; tag created & pushed
- [ ] Phase 5: CI / GitHub assets / notes
- [ ] Phase 6: R2 upload (if ext ships)
- [ ] Phase 7: Ubuntu PPA (full/cli)
- [ ] Phase 8: post-release checks
```
Checks: clean tree; `main` ff-only; smoke tests; CHANGELOG Unreleased; no secrets.
## Phase 2 — Docs & version bumps (main)
| File | full | cli | ext |
|------|------|-----|-----|
| `Cargo.toml` + `crates/marqdo-wasm/Cargo.toml` | bump | bump | — |
| `ext/VERSION` | bump | — | bump |
| `CHANGELOG.md` | `## vVER`(含**核心表面 Δ**,见 `doc/design/layers.md`) | same | `## Ext pack vVER` |
| `README.md` / `public/**` install + download table | update | update | update ext notes |
| `.cursor/skills/marqdo/SKILL.md` | if surface changed | same | rare |
| `.github/workflows/release.yml` Highlights stub | yes | yes | — |
```bash
./scripts/build-public.sh # when public/ sources changed
```
Commit + push `main` (proxy origin). On push failure → reference § Proxy; if still blocked, **print** for the user:
```bash
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git HEAD:main
# or: python3 scripts/push-via-hk-jump.py
```
## Phase 3 — VS Code / Cursor extension (full/cli only)
Default: bump `vscode-extension` package.json to `VER`, compile, push branch `vscode-extension`, return to `main`.
## Phase 4 — Tag & trigger CI (full/cli)
```bash
git tag -a "vVER" -m "vVER"
git push origin "vVER"
```
Ext-only:
```bash
git tag -a "ext-vVER" -m "ext-vVER"
git push origin "ext-vVER"
```
(or build zips locally / via workflow and `gh release upload`).
If tag push needs the user:
```bash
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git vVER
```
## Phase 5 — GitHub Release notes & assets
1. Wait for Actions (full/cli): both `windows` and `linux` green when ext natives required.
2. Rewrite release body 中英双语 — [reference.md § Notes](reference.md).
3. Confirm Linux `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` when mode ships ext.
## Phase 6 — Extension CDN (R2) — required when ext ships
```bash
# credentials: ~/.marqdo/r2.env (never commit)
python3 scripts/upload-ext-r2.py --version VER --from-dir dist/
curl -fsS https://ext.marqdo.com/latest/VERSION
```
Also ensure the **same** zips are on GitHub (`vVER` or `ext-vVER`). If R2 credentials missing, **tell the user**:
```bash
# put keys in ~/.marqdo/r2.env then:
python3 scripts/upload-ext-r2.py --version VER --from-dir dist/
```
## Phase 7 — Ubuntu PPA (full/cli)
Linux CLI for apt users. After `Cargo.toml` is at `VER` and `debian/changelog` has a matching `VER-1ppaN` stanza:
```bash
./scripts/ppa-ship.sh noble
```
Packaging notes / noble Cargo.lock v4: [ubuntu-ppa.md](../../../doc/design/ubuntu-ppa.md).
**If the agent cannot sudo / sign / dput**, print exactly:
```bash
cd ~/work/marqdo
./scripts/ppa-ship.sh noble
# or build then upload:
./scripts/ppa-build-source.sh noble
dput ppa:cflmy/marqdo ../build-area/marqdo_*~noble_source.changes
```
Watch: https://launchpad.net/~cflmy/+archive/ubuntu/marqdo/+builds
On Launchpad failure: read the build log, fix `debian/` or bundle script, bump `1ppaN`, re-upload. Tell the user the new `dput` command.
## Phase 8 — Post-release
1. `gh release view TAG` — assets + notes.
2. CDN `https://ext.marqdo.com/vVER/` (if ext shipped).
3. PPA build green (if cli shipped).
4. Tell user URLs: GitHub release, CDN, PPA install one-liner.
5. Optional gh-pages only if asked.
## Extension-only release (mode=ext)
1. User confirms **ext** SemVer (may differ from CLI).
2. Bump `ext/VERSION`; CHANGELOG → `## Ext pack vVER`.
3. Build/package `marqdo-VER-ext.zip` + `marqdo-VER-native-*.zip` (CI or local).
4. Upload to **R2 and GitHub** (required both).
5. Do **not** retag CLI / do **not** PPA unless user also asked for cli.
## Failure matrix (short)
| Failure | Action |
|---------|--------|
| `gh` / git TLS or Clash `7890` refused | Unset bad proxy; see [reference § Proxy](reference.md) |
| GitHub blocked | proxy.cflmy.top, then HK jump; **print commands** if agent cannot push |
| Tag exists | Stop; ask user |
| CI red | Fix on main; retag only if user allows |
| R2 upload fails | Print `upload-ext-r2.py` command; do not skip silently |
| PPA / sudo / GPG | Print `./scripts/ppa-ship.sh noble` (or `dput …`); do not skip silently |
| Launchpad `Cargo.lock` v4 / old cargo | Ensure bundled `third_party/rust` via current `ppa-build-source.sh`; bump `1ppaN` |
| Linux native zip missing (full/ext) | Incomplete — fix linux job or upload |
## Do not
- Ship without user-confirmed version (and mode when ambiguous).
- Ship ext packs to only one of R2 / GitHub.
- Call a full/cli release done without attempting PPA **or** giving the user the PPA commands.
- Commit `target/`, `dist/`, `*.wasm`, `third_party/rust/`, or `public/**/*.html` unless policy changes.
- Merge extension tree into `main`.
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.
+2 -396
View File
@@ -1,397 +1,3 @@
# Marqdo release — reference
# Release task reference
Companion to [SKILL.md](SKILL.md). Use during a release; keep SKILL short.
## Detect versions (commands)
```bash
# From repo root
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
# or manually:
git fetch --tags origin 2>/dev/null || true
echo "Cargo: $(sed -n 's/^version = \"\(.*\)\"/\1/p' Cargo.toml | head -1)"
echo "wasm: $(sed -n 's/^version = \"\(.*\)\"/\1/p' crates/marqdo-wasm/Cargo.toml | head -1)"
echo "tags: $(git tag -l 'v*' --sort=-v:refname | head -3 | tr '\n' ' ')"
gh release list --limit 3 2>/dev/null || true
```
**SemVer guidance for the ask (do not choose for the user):**
| Kind | When |
|------|------|
| patch `x.y.(z+1)` | Fixes, docs, no public API / MQ surface break |
| minor `x.(y+1).0` | New features (WASM route C, new ext APIs) backward compatible |
| major `(x+1).0.0` | Breaking MQ / CLI / plugin ABI |
## Asset matrix (CI tag `v*`)
Produced by `.github/workflows/release.yml` on **windows-latest** (`windows` job) and **ubuntu-latest** (`linux` job, **required**, `needs: windows`):
| Asset | Role | Job |
|-------|------|-----|
| `marqdo-VER-x86_64-pc-windows-msvc.exe` | CLI (stdlib embedded) | windows |
| `marqdo-VER-x86_64-pc-windows-msvc.zip` | `marqdo.exe` + `lib/` + `ext/` + native DLL | windows |
| `marqdo-VER-stdlib.zip` | `lib/` only | windows |
| `marqdo-VER-ext.zip` | Official `ext/` L1 | windows |
| `marqdo-VER-native-x86_64-pc-windows-msvc.zip` | Prebuilt Windows plugins (`native/*.dll`) | windows |
| `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` | Prebuilt Linux plugins (`native/lib*.so`) — **must ship** | linux |
| `marqdo-VER-x86_64-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + native `.so` — **must ship** | linux |
| `marqdo-VER-source.zip` | `git archive` of tagged commit | windows |
| `marqdo-VER.vsix` | VS Code / Cursor (from branch `vscode-extension`) | windows |
| `marqdo-VER-public.zip` | Static user docs (`marqdo view output public`) | windows |
Not CI-uploaded (document in notes): macOS build from source; WASM via `marqdo wasm build` → `dist/wasm/`.
A release **without** the Linux native zip is incomplete (`marqdo ext add` on Linux cannot download prebuilts).
## Doc sync checklist (Phase 2 detail)
### CHANGELOG.md
1. Ensure `## Unreleased` lists everything shipping.
2. Rename to `## vVER — YYYY-MM-DD` (use release day in Asia/Shanghai unless user says otherwise).
3. Add a short **Highlights** subsection (install snippet + 3–6 bullets).
4. Insert empty:
```markdown
## Unreleased
### Added
### Fixed
### Changed
```
### README.md
Update every user-visible version pin, typically:
- Section title `## 现状(vVER)`
- `### 如何使用最新 Marqdo(vVER)`
- `git checkout vVER`
- Release URL `…/releases/tag/vVER`
Keep install / `ext add` / plugin build instructions accurate for this release.
### `.cursor/skills/marqdo/SKILL.md`
- Sync hard rules / feature bullets that this release changes (e.g. WASM, web).
- Do **not** dump full CHANGELOG into the skill.
- If release-only process changed, point to `.cursor/skills/marqdo-release/`.
### `public/` (author Markdown sources)
User tutorials under `public/` (not generated HTML). Update when:
- New CLI (`marqdo wasm …`, `ext add`, `version`)
- New tutorials (browser hello, web client embed)
- Version badges / “requires vVER” lines
Then regenerate HTML for zip/pages:
```bash
./scripts/build-public.sh
# Windows: powershell -File ./scripts/build-public.ps1
```
HTML under `public/**/*.html` is typically gitignored — zip still ships from CI `marqdo view output public`.
### Workflow stub
Edit `.github/workflows/release.yml` `body:` **Highlights** so the first auto body matches this tag (agent still replaces with full notes via `gh release edit`).
### Roadmaps / ADRs
If this release closes a wave: set status Completed in `doc/roadmap/*`; leave ADRs immutable (link from CHANGELOG).
## Extension checklist (Phase 3 detail)
Branch policy: `doc/design/vscode-extension-commit.md`.
```bash
git fetch origin vscode-extension
git checkout vscode-extension
# edit vscode-extension/package.json version → VER
# npm ci && npm run compile
git add vscode-extension/
git commit -m "$(cat <<'EOF'
vscode-extension: bump to VER for release
EOF
)"
git push origin vscode-extension
git checkout main
```
Local VSIX only (fallback):
```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 --no-dependencies -o "../dist/marqdo-VER.vsix")
# cleanup ignored tree if desired
gh release upload "vVER" "dist/marqdo-VER.vsix" --clobber
```
## Defaults (mirror of SKILL)
| Setting | Default |
|---------|---------|
| Sync `vscode-extension` to `VER` | yes |
| Push main + annotated tag immediately | yes |
| Release notes | 中英双语 |
| Skip VSIX / docs-only / deploy pages | no |
Phase 0 asks **only** for the next version unless the user wants overrides.
## Notes template (中英双语 — default)
Save as `/tmp/marqdo-vVER-notes.md` then:
```bash
gh release edit "vVER" --notes-file /tmp/marqdo-vVER-notes.md
```
```markdown
## Marqdo vVER
### 亮点 / Highlights
- **中文** … / **EN** …
- …
### 安装 / Install
```bash
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout vVER
cargo build --release
./target/release/marqdo version
cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg
marqdo ext add web && marqdo ext add agent && marqdo ext add quantum
# 中文 id:网页 / 智能体 / 量子
```
**浏览器 WASM / Browser WASM**
```bash
marqdo wasm build
# → dist/wasm/marqdo_wasm_bg.wasm + marqdo-bridge.js
# examples: examples/browser-hello/
```
### 破坏性变更 / Breaking changes
- 无 / None
- …
### 下载 / Downloads
| Asset | 内容 / Contents |
|-------|-----------------|
| `marqdo-*-windows-msvc.exe` | CLI(内置 stdlib) |
| `marqdo-*-windows-msvc.zip` | exe + `lib/` + `ext/`(含 native) |
| `marqdo-*-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + `.so` |
| `marqdo-*-native-*.zip` | 预编译 `web`/`agent`/`quantum`/`linalg`(Win + **Linux 必出**) |
| `marqdo-*-stdlib.zip` | 仅 `lib/` |
| `marqdo-*-ext.zip` | 官方 `ext/` |
| `marqdo-*-source.zip` | 源码快照 |
| `marqdo-*.vsix` | VS Code / Cursor 扩展 |
| `marqdo-*-public.zip` | 用户文档站 |
扩展源码分支 / Extension branch: **`vscode-extension`** ([policy](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)).
### 链接 / Links
- [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md)
- [README](https://github.com/cflmy/marqdo/blob/main/README.md)
```
## Proxy & auth (network recovery)
Symptoms seen in this project: broken local Clash on `127.0.0.1:7890`, flaky GitHub TLS, `gh` needing token, Cursor agent sandbox with only `lo`.
### `proxy.cflmy.top` (try this first)
This machine’s `origin` is typically:
```
https://proxy.cflmy.top/github.com/cflmy/marqdo.git
```
Push / fetch / tag through that remote (HTTPS reverse proxy to GitHub):
```bash
git remote -v # confirm origin uses proxy.cflmy.top
git push origin main
git push origin vVER
git push origin vscode-extension
# one-shot if origin still points at github.com:
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git HEAD:main
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git vVER
```
Short GETs via the proxy often work; **long `git push` may still time out**. If push hangs or drops, skip Clash retries and go to **HK SSH jump** below.
`gh` / Release API can use the same path reverse-proxy:
| Path prefix | Upstream |
|-------------|----------|
| `/github.com/` | `https://github.com/` |
| `/api.github.com/` | `https://api.github.com/` |
| `/uploads.github.com/` | `https://uploads.github.com/` (Release asset POST; OpenResty on HK) |
```bash
# Upload a Release asset through proxy.cflmy.top (Content-Type: application/octet-stream)
curl -X POST \
-H "Authorization: Bearer $GH_TOKEN" \
-H "Accept: application/vnd.github+json" \
-H "Content-Type: application/octet-stream" \
--data-binary @dist/FILE.zip \
"https://proxy.cflmy.top/uploads.github.com/repos/cflmy/marqdo/releases/RELEASE_ID/assets?name=FILE.zip"
```
Do **not** rewrite `Host: uploads.github.com` against `proxy.cflmy.top` without the `/uploads.github.com/` path prefix — that returns 404.
### Diagnose
```bash
env | grep -iE 'proxy|PROXY' || true
curl -sI --max-time 15 https://github.com | head -5
curl -sS --max-time 15 -o /dev/null -w 'proxy=%{http_code}\n' https://proxy.cflmy.top/ || true
gh auth status
ip -br addr | head -5 # agent may lack enp*; use required_permissions: ["all"]
```
### Fix order
1. **Unset bad proxy** if connection refused:
```bash
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy
# also clear for one git call: git -c http.proxy= -c https.proxy= …
```
2. **Set a working proxy** only if the user provides one (or known working):
```bash
export HTTPS_PROXY=http://HOST:PORT
export HTTP_PROXY=http://HOST:PORT
```
3. **Agent Shell**: retry `git push` / `gh` with `required_permissions: ["all"]` (and `full_network` if needed).
4. **`gh` auth**: if `gh auth status` fails, ask user to `gh auth login` or set `GH_TOKEN` / `GITHUB_TOKEN` for the session — **never commit tokens**. Fallback used in this repo: load password from `git credential fill` (`protocol=https` / `host=github.com`) into `GH_TOKEN` for the session only, then delete the temp env file.
5. **Git remote**: prefer `https://github.com/cflmy/marqdo.git`; SSH needs keys.
6. **HK SSH jump (preferred when GitHub is blocked but HK is reachable)** — see next subsection.
7. **Partial upload**:
```bash
gh release upload "vVER" dist/FILE --clobber
```
8. **Re-run CI** without retagging (if tag already correct):
```bash
gh workflow run Release --ref "vVER" # only if workflow_dispatch exists; else fix + new patch tag
```
Current Release workflow is **tag-push only**. Red CI after tag → fix on `main`, then either new patch tag or **user-approved** delete+recreate tag (dangerous; prefer patch).
### HK SSH jump (Paramiko CONNECT)
**When to use:** local → GitHub fails (timeout / TLS / Clash flaky / reverse-proxy `proxy.cflmy.top` connect drops), but this host can reach an overseas box that has stable GitHub (default `hk.cflmy.de`). Proven path for v0.3.9 push/tag/`gh`.
**Do not** rely on OpenSSH + `sshpass` here — password auth has hung; use **Paramiko** (`python3-paramiko`).
**Never** commit the HK root password or tokens. Ask the user for the password (or a key), put it in env / a `600` temp file, scrub after.
```bash
# one-shot password file (example — use the secret the user gave this session)
printf '%s' "$HK_PASSWORD_FROM_USER" > /tmp/.hk_ssh_pw && chmod 600 /tmp/.hk_ssh_pw
export HK_SSH_HOST=hk.cflmy.de # or 83.229.126.119
export HK_SSH_USER=root
export HK_SSH_PASSWORD_FILE=/tmp/.hk_ssh_pw
# optional: HK_JUMP_PORT=18081
SCRIPT=.cursor/skills/marqdo-release/scripts/push-via-hk-jump.py
# push / tag / extension (git gets CONNECT proxy + github.com askpass)
python3 "$SCRIPT" -- git push origin main
python3 "$SCRIPT" -- git push origin vscode-extension
python3 "$SCRIPT" -- git push origin vVER
# gh (sets GH_TOKEN from git credential fill if unset)
python3 "$SCRIPT" -- gh release edit vVER --notes-file /tmp/notes.md
python3 "$SCRIPT" -- gh run list --workflow=Release --limit 3
# leave proxy up for manual commands
python3 "$SCRIPT" --serve # then: export https_proxy=http://127.0.0.1:18081
rm -f /tmp/.hk_ssh_pw
```
Script behavior: SSH to HK → local `http://127.0.0.1:$HK_JUMP_PORT` HTTP CONNECT via `direct-tcpip` → run `git`/`gh`/`curl` with that proxy. Git auth uses local `git credential` via `http.extraHeader` (Basic) — **not** `GIT_ASKPASS` (askpass has hung under agent/no TTY). Tokens never go to the jump host disk.
Optional path reverse-proxy (`https://proxy.cflmy.top/github.com/…` `insteadOf`) may work for short GETs; treat long `git push` failures as a signal to use the HK jump instead of retrying Clash forever.
## Local Windows fallback
```powershell
powershell -File ./scripts/release-full.ps1 -Tag vVER -Upload
# -SkipVsix / -SkipPublic / -DeployPages as needed
```
Also: `scripts/release-windows.ps1`, `scripts/publish-release.py` if present.
## Commit message style
```text
release: vVER — <highlight>
```
Extension:
```text
vscode-extension: bump to VER for release
```
## Pre-tag test suggestions
Minimum:
```bash
cargo test --test gold structure_hello
./target/release/marqdo version # after cargo build --release
```
Stronger (time permitting):
```bash
cargo test --test gold
cargo test -p marqdo-wasm -- --nocapture # if wasm tests exist
# optional Node: node tests/wasm/smoke.mjs after marqdo wasm build
```
## Ask-user prompt (copy)
```text
版本探测结果:
- Cargo.toml: A.B.C
- crates/marqdo-wasm: …
- 最新 git tag: v…
- 最新 GitHub Release: v…
- CHANGELOG Unreleased: 有 / 无(摘要:…)
请指定下一个版本号(例如 0.3.2)。
默认(无需确认):同步 vscode-extension 同号、立刻 push tag 发版、发布说明中英双语。
若要改默认请一并说明。
```
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.
+48 -235
View File
@@ -1,249 +1,62 @@
---
name: marqdo
description: >-
Author and edit Marqdo programs (.mq.md): Markdown markers are executable
syntax (functions, calls, statements, returns, control flow). Use when writing
or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose,
importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic
sites with ext/web, quantum circuits with ext/quantum, or when the user
mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or
quantum/量子 extension.
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 development
# Marqdo
Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python.
<!-- CORE_SYNTAX_V2.1: keep this card within the first 1200 body characters -->
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
## CORE SYNTAX
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
2. **Output is not `**bold**`.** Print with `> print text=…` (or `> 打印 内容=…`). Bold `**…**` is **return value only**.
3. **Prose vs code:** after a blank line, an unmarked first line starts a **comment paragraph**; every following non-blank line stays comment until the next blank line. Put a **blank line** between narration and executable lines.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`+` params** (under heading), **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**, `**…**` = return.
5. **Identifiers use backticks** — params `` + `name` ``. **Exemptions:** foreach `` - [item](coll) ``; footnote `` name[^key] ``; **inside italic `*…*` / bold `**…**`**, bare ids are **variables** (Python-style unified namespace) and method-call receivers are bare too. **Drop the backticks on value-expression variable names and method receivers inside `*…*` / `**…**`** — they are redundant once the `*…*`/`**…**` markers mark the segment as code: `*分类 = 分类[^苹果]*`, `**n * 2**`, `*p = > page.主体装配 组件=home*`. **Text literals must be quoted**: `*a = > text.split value=src sep=","*`. Backticks **still required** where a bare word is *not* a variable in **standalone `>` calls** (bare = text there): `` > str `n` ``, `` > `obj`.method ``. **No trailing space** inside `*…*` / `**…**` wrapped code: the closing marker must touch the last token directly (`*a = 1*`, `**n**`), never `` *a = 1 * ``.
6. **Structure lines are not wrapped in italics.** `#` `>` `+` `-` `|` lines stand alone; use `*…*` only for general statements (bindings / expressions).
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with `*None*` / `*无*` / whole-line `**` / `****` when later lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug. Read collections with **`[key](map)`**, not footnote indexes for new code. **Positive copy-paste shapes** (result map, soft-error pack, sparse `table.put`): [marqdo-dev](../marqdo-dev/SKILL.md) §2 · [examples.md](examples.md) §6e. Do **not** extend legacy `json.set` in `ext/ai` — refactor to tables.
12. **One language per file:** Do not mix EN and ZH API names in the same `.mq.md` (imports, calls, params). Pick English *or* Chinese mirrors for the whole program.
13. **Sandbox trial habit (Agent / generated `.mq.md`):** Prefer `agent.trial` / `run sandbox=True` / `sandbox.open`→`run`→`diff`→`commit` before promoting to the host tree. Host files must stay unchanged until a successful commit. Caps live in `sandbox.profile` GFM tables — do not invent a second dialect.
## Markup → meaning (v0.2)
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 |
|--------|---------|
| `#` | **Object / type** (constructor body). `# main` = entry object. `# Child = > Parent` = inherit (**no** implicit parent constructor; call `` `self` = > Parent … `` explicitly when needed). |
| `##` … `######` | **Function / method** (nesting by heading depth). |
| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) |
| `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). |
| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) |
| `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) |
| Frontmatter `import bind:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) |
| `> lib.member …` / `> lib.Type.member …` | Call via bare dotted path (instance methods need `` `var`.m ``) |
| `*…*` | Statement (bind / expr) — closing `*` touches last token, **no trailing space**; bare ids are variables |
| `**…**` | Return value — closing `**` touches last token, **no trailing space**; bare ids are variables |
| `****` or `**` + spaces + `**` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `- [item](coll)` | Foreach (unchanged) |
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
| Unmarked prose | Comment |
|---|---|
| `**…**` | 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 |
Entry: load file (often `index.mq.md`) → collect defs → run `# main`.
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.
## Minimal program
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.
```markdown
# main
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.
> print text=Hello World!
```
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.
Chinese builtins (same functions, no import):
```markdown
# main
> 打印 内容=你好
```
## Functions, calls, end-body
```markdown
# main
> greet who=Marqdo
## greet
+ `who`
> print text=Hello, `who`!
*None*
```
- Call: `> name key=value` or `> name value`.
- Nested helpers use deeper `#` (`##`, `###`, …).
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
## Statements, returns, branches
```markdown
*x = 1*
*y = x + 2*
## add_one
+ `n`
**n + 1**
```
```markdown
*n = 0*
1. `n` > 0
> print text=positive
2. `n` < 0
> print text=negative
3. *
> print text=zero
```
## Frontmatter imports + stdlib
Imports use `import bind:target` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path:
```markdown
---
title: example
import text:lib/text.mq.md
import clock:lib/time.mq.md
---
# main
*xs = > text.split value="a,b,c" sep=","*
> print text=`xs`
*t = > clock.now_unix*
```
- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages).
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
Stdlib map: [reference.md](reference.md).
## Official extension: `ext/agent` (document-driven)
Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --release -p marqdo_plugin_agent`.
**Constitution (do not dilute):**
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/) · [agent-sandbox-okf](../../examples/agent-sandbox-okf/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · optimize O1–O5: [ext-ai-optimize.md](../../doc/roadmap/ext-ai-optimize.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
**Sandbox (O1):** `import sandbox:ext/ai/sandbox.mq.md` · `agent.trial` / `智能体.试跑` · `run`/`step` take `sandbox=` / `沙盒=` (default `False`). Profile caps are tables via `sandbox.profile`. Gold: `tests/ext/agent-sandbox-optin.mq.md`.
## Official extension: `ext/web` (Document / Endpoint / Resource)
Install: `marqdo ext add web` (ZH id: `网页`). See ADR 0007 · [ext-web-artifact.md](../../doc/design/ext-web-artifact.md).
**Do not degrade:** Document/Endpoint metadata; facade `web.page|route|serve|render|inspect`; View `|type|slot|value|attrs|style|` only; no `compose_*` / `configure` / author `ensure_plugin`. DB → `ext/data`; auth → `ext/security`; net → `ext/net`.
- EN: `import web:ext/web/web.mq.md`
- ZH: `导入 网页:ext/web/网页.mq.md`
Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/).
## Official extension: `ext/quantum` (circuits + Q7/Q8)
Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --release -p marqdo_plugin_quantum`, then **`marqdo ext add quantum` again** so view loads the new `libquantum.so` (stale plugin = old black/white circuits).
- EN: `import quantum:ext/quantum/quantum.mq.md`
- ZH: `导入 量子:ext/quantum/量子.mq.md`
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; ≤12 qubits for statevector; density-matrix ops ≤6 qubits; one language file per program; quote draw string args (`kind="…"`, `theme="…"`).
**Core:** `# circuit` / `# gate` / `# density` — table `steps=` or method chain; `simulate` / `probabilities` / `run` / `draw`.
**Q7 linear algebra:** `density`, `partial_trace`, `eig`, `expect` (Pauli string, left=high bit), `purity`, `kron`, `schmidt`, `fidelity`.
**Draw kinds:** `circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`.
**Q8 themes (circuit / probs / bloch):** `theme="dark"|"light"|"bw"` (ZH `主题=`; **default `dark`** — slate lab look, gate-family colors, label chips so wires never cross `q0` text). View plot chrome follows `data-theme` on the SVG. Advanced kinds (hinton/…) still Q8c pending full re-skin.
```markdown
*_ = > `qc`.draw kind="circuit" theme="dark"*
*_ = > `qc`.draw kind="probs" theme="light"*
```
Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/).
## AI authoring workflow
1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
2. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
4. On `path:line:col: message`, fix that span; re-run until exit 0.
5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
## Anti-patterns (common model mistakes)
| Wrong | Right |
|-------|-------|
| `**Hello**` to print | `> print text=Hello` |
| `# main` then prose then code with no blank line | Blank line before code |
| `if x > 0:` | `1. `x` > 0` |
| `* > print text=hi *` | `> print text=hi` |
| `` *`a` = 1 * `` (trailing space + backticks) | `*a = 1*` — bare bind, no trailing space before `*` / `**` |
| `*xs = > text.split value=a,b sep=,*` (bare text args) | `*xs = > text.split value="a,b" sep=","*` — quote text literals; bare words are variables |
| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) |
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
| `json.set` / `compose_*` page parts | `type: web` Document + View table / `web.render` / `web.serve` |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([marqdo-dev](../marqdo-dev/SKILL.md)) |
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
| Bare `kind=hinton` inside `*…*` | `kind="hinton"` — quote text literals |
| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` |
| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) |
## Checklist before finishing
- [ ] File ends with `.mq.md`
- [ ] Print via `print` / `打印`, not bold
- [ ] Blank lines separate comment paragraphs from code
- [ ] `# main` exists when the file is an entry program
- [ ] Nested side-effect helpers ended with `*None*` / `**` / `****` when the outer function continues
- [ ] Imports and call names share the same language file
- [ ] Data shaped as **GFM tables** (or short helpers) — no `json.set` / `json.append` glue
- [ ] Web sites: tables + web classes only (no JSON glue); `data/` gitignored
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
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.
+2 -468
View File
@@ -1,469 +1,3 @@
# Marqdo examples (AI)
# Marqdo executable examples
v0.3: `**…**` = code (assign / call); `*…*` = return. Prefer `[key](coll)` over footnote get. Bracket calls: `礼貌 [问候] x`.
## 1. Hello (English)
```markdown
# main
> print text=Hello World!
```
## 2. Hello (Chinese builtins)
```markdown
# main
> 打印 内容=你好,世界!
```
## 3. Function + named call + empty return
```markdown
# main
Greeting via a nested function:
> greet who=Marqdo
## greet
+ `who`
> print text=Hello, `who`!
*None*
```
Or end with a whole-line empty bold return: `**` / `****`. Lone `---` is a thematic break (skipped), not function end.
## 4. Bindings and return
```markdown
# main
**a = 2**
**b = add_one n=`a`**
**打印 内容=`b`**
## add_one
+ `n`
*n + 1*
```
## 5. Branch with else
```markdown
# main
**n = 0**
1. `n` > 0
> print text=positive
2. `n` < 0
> print text=negative
3. *
> print text=zero
```
## 6. Foreach loop
```markdown
# main
`篮子` =
| 果 |
|----|
| 苹果 |
- [果](篮子)
> print text=`果`
```
## 6b. Map table + link-index get
```markdown
# main
`分类` =
| 苹果 | 黄瓜 |
|------|------|
| 水果 | 蔬菜 |
**种 = [苹果](分类)**
**打印 内容=`种`**
`篮子` =
| 果 |
|----|
| 苹果 |
**第一 = [1](篮子)**
**打印 内容=`第一`**
```
One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Prefer `[key](coll)` (lists are 1-based). Legacy `` coll[^key] `` still parses. Foreach on a map walks **keys**.
Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded):
```markdown
`订单` =
| 行 | 品名 | 数量 |
|----|------|------|
| 1 | 苹果 | 2 |
**名 = [品名]([1](订单))**
```
## 6c. Bracket-marked call + modifiers
```markdown
# main
**打印 内容=(礼貌 [问候] "Marqdo")**
## 问候
+ `谁`
+ `礼貌`=False
**出 = `礼貌` + ", " + `谁` + "!"**
*出*
```
`礼貌 [问候] …` → `礼貌=True`. `]` immediately followed by `(` is index, not a call.
## 6d. Browser effects — tables + lib/browser (not json.set)
```markdown
---
import browser:lib/browser.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
**`wire`**
## bump
**count = count + 1**
**label = str count**
**> browser.set_text sel="#count" text=label**
```
Do **not** build effect maps with `json.set` chains. See [marqdo-dev](../marqdo-dev/SKILL.md).
## 6e. Agent / LLM result maps — GFM first (positive)
Return and soft-error packs are **tables**, not `json.set` pipelines. Full style contract: [marqdo-dev](../marqdo-dev/SKILL.md) §2.
```markdown
---
import table:lib/table.mq.md
---
## step_ok
+ `task`
+ `reply`
`out` =
| status | task | result |
|--------|------|--------|
| ok | `task` | `reply` |
*out*
## step_err
+ `task`
+ `err`
`out` =
| status | task | error |
|--------|------|-------|
| error | `task` | `err` |
*out*
## soft_http_pack
+ `msg`
+ `usage0`
**empty_tc = > table.empty_list**
`pack` =
| finish | text | error | usage | tool_calls |
|--------|------|-------|-------|------------|
| error | "" | `msg` | `usage0` | `empty_tc` |
*pack*
```
Do **not** mirror legacy `ext/ai/agent.mq.md` `json.parse`+`json.set` chains when adding new arms — convert the shape to a table.
## 7. Import text stdlib
```markdown
---
title: split demo
import text:lib/text.mq.md
---
# main
**parts = [text.str_split] s="a,b,c" sep=","**
**打印 内容=`parts`**
```
## 7b. Mid M1 — regex + encoding (no plugin)
```markdown
---
import re:lib/re.mq.md
import enc:lib/encoding.mq.md
---
# main
**`ok` = [re.is_match] text="a@b.c" pattern="@"**
**`b64` = [enc.base64_encode] text="hi"**
**打印 内容=`ok`**
**打印 内容=`b64`**
```
## 7c. Mid M6 — log + uuid
```markdown
---
import log:lib/log.mq.md
import uuid:lib/uuid.mq.md
---
# main
> log.info text="start"
> log.set_level level="debug"
> log.debug text="detail"
**id = [uuid.v4]**
**打印 内容=`id`**
```
## 8. Comment paragraphs (blank-line rule)
```markdown
# main
This whole paragraph is a comment, including lines that look like code:
**not_executed = 1**
> print text=also still comment
After a blank line, code runs:
> print text=this runs
```
## 9. Frontmatter import only
```markdown
---
description: loads math
import math:lib/math.mq.md
---
# main
**t = > num value=3.5**
**打印 内容=`t`**
```
## 10. Object handle + method
See `tests/structure/object-handle.mq.md` and `ext/ai/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`.
## 10b. Object inheritance
```markdown
# Greeter
## hello
+ `who`
**msg = "Hello, `who`!"**
*msg*
# Loud = > Greeter
## hello
+ `who`
**msg = "HELLO, `who`!"**
*msg*
```
`_type` stays the most specific name (`Loud`). Methods walk the base chain; same-name `##` on the child overrides. **No implicit super** — if the child needs parent fields, call the parent explicitly:
```markdown
# Child = > Parent
+ `name`
**self = > Parent name=`name`**
**self = [table.put] in=`self` at="extra" value=1**
*self*
```
## 11. Agent layout (ABI)
```markdown
---
import agent:ext/agent.mq.md
---
# main
> load_native
**ws = > agent**
**n = > `ws`.ensure_layout**
**打印 内容=`n`**
```
Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`).
## 12. What not to emit
```markdown
# BAD — bare bold that is not code-shaped (decorative OK); do not use bold/italic as print
**Hello**
# BAD — Python control keywords
if x > 0:
print(x)
# BAD — wrapping a call in italics as if it were a statement
*> print text=hi*
# BAD — old branch syntax (removed)
+ `x` > 0
# GOOD — ordered list arms
1. `x` > 0
> print text=pos
2. *
> print text=other
# GOOD — another independent branch (restart at 1.)
1. `y` > 0
> print text=y-pos
2. *
> print text=y-other
# GOOD — print / return
**打印 内容="hi"**
*n + 1*
```
## 13. Dynamic site (ext/web, minimal)
```markdown
---
title: hello-site
import web:ext/web/web.mq.md
import db:db/index.mq.md
---
# main
`shell` =
| 组件 | 样式 |
|------|------|
| nav | |
`main` =
| 属性 | 值 | 样式 |
|------|-----|------|
| title | posts.title | |
| body | posts.summary | |
**store = > db.open**
**css = "body{font-family:sans-serif}"**
**page = > web.page title="Hello"**
**page = > page.compose_components components=`shell`**
**page = > page.compose_main main=`main`**
**page = > page.css css=`css`**
**app = > web.app page=`page` port=8080**
**app = > app.static prefix="/static" dir="static"**
> listen app=`app`
```
- Import `ext/web/web.mq.md` **or** `ext/web/网页.mq.md` — not both; match API language to the file.
- Full blog/CMS patterns: `examples/marqdo-blog/` (routes, SEO, RSS, auth, upload, WS).
- Run after `marqdo ext add web` and building `marqdo_plugin_web`.
## 14. Quantum entanglement lab (ext/quantum Q7/Q8)
```markdown
---
import quantum:ext/quantum/quantum.mq.md
---
# main
`steps` =
| step | gate | qubits |
|------|------|--------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
**qc = > quantum.circuit qubits=2 steps=`steps`**
**rho = > `qc`.density**
**red = > `rho`.partial_trace keep=0**
**sch = > `qc`.schmidt cut=1**
**_ = > `qc`.draw kind="circuit" theme="dark"**
**_ = > `qc`.draw kind="hinton"**
**打印 内容=`red`**
```
- Full lab: `examples/quantum-entanglement/`. Bell-only: `examples/quantum-bell/`.
- `theme="dark"|"light"|"bw"` (default dark) on `circuit` / `probs` / `bloch`. Quote `kind=` / `theme=`.
- After rebuilding the plugin: `marqdo ext add quantum` so view loads the new native lib.
## 15. Linear algebra (ext/linalg)
```markdown
---
import la:ext/linalg/linalg.mq.md
---
# main
**`A` = > la.symbol name="A" rows=2 cols=2**
**`B` = > la.symbol name="B" rows=2 cols=2**
**`C` = `A` + `B`**
**`P` = `A` * `B`**
```
Prefer:
```markdown
**`env` = > la.declare table=`shapes`**
**`P` = [A](env) * [B](env)**
**`t` = > `P`.T_ascii**
```
- Infix `+` / `-` / `*`;`ascii` / `T_ascii` 默认化简(`raw=True` 可关)。
- Formula-doc design: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md).
- Examples: `examples/linalg-transpose/`, `examples/linalg-svd/`, `examples/linalg-least-squares/`.
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.
@@ -0,0 +1,3 @@
# 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).
+2 -203
View File
@@ -1,204 +1,3 @@
# Marqdo reference (AI)
# Marqdo executable reference
Load this when you need stdlib names, CLI, or edge cases. Core rules stay in [SKILL.md](SKILL.md).
## CLI
```text
marqdo --version
marqdo run FILE.mq.md
marqdo run FILE.mq.md --backend bytecode
marqdo view PATH # docs browser, default port 7429
marqdo debug PATH # debugger UI, default port 7430
marqdo catalog PATH -o .marqdo
marqdo ext list
marqdo ext add llm|agent|web|quantum|linalg
marqdo ext remove llm|agent|web|quantum|linalg
```
Diagnostics look like `path:line:col: message` (1-based line/col).
**v0.3 surface:** `**…**` = code; `*…*` = return; parameters `` + `name` `` (or prose-inferred); branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) ``; get `` [key](coll) ``; bracket calls `` mod [fn] args ``. See `doc/design/markdown-mapping-v0.3.md`.
Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe.
官方扩展(`ext/…`,非 stdlib):`marqdo ext add` 装到 `MARQDO_EXT` 或 `~/.marqdo/ext`;导入仍写 `import llm:ext/llm.mq.md`。解析还含 cwd `ext/`、二进制旁 `ext/`。对象:`doc/design/objects.md`。Agent:`doc/design/ext-agent.md` · 安装器:`doc/design/ext-cli.md`。
## Builtins (no import)
| EN | ZH | Role |
|----|----|------|
| `print` | `打印` | stdout; arg `text` / `内容` |
| `input` | `输入` | one line; arg `prompt` / `提示` |
| `len` | `长度` | length; arg `value` / `值` |
| `str` | `文本` | to text; arg `value` / `值` |
| `int` | `整数` | to int; arg `value` / `值` |
Keywords (not variable names): `True`/`真`, `False`/`假`, `None`/`空`, `and`/`且`, `or`/`或`, `not`/`非`.
## Standard library files
Import one file; use **that** file’s function names.
| EN import | ZH import | Typical APIs (EN / ZH) |
|-----------|-----------|-------------------------|
| `lib/text.mq.md` | `lib/文本.mq.md` | text helpers / 去空白·拆分·拼接… |
| `lib/table.mq.md` | `lib/表.mq.md` | `put`/`改` + list/map(见 `doc/design/stdlib-table.md`) |
| `lib/re.mq.md` | `lib/正则.mq.md` | Mid:`is_match`/`find`/`replace`/… |
| `lib/encoding.mq.md` | `lib/编码.mq.md` | Mid:base64/hex |
| `lib/path.mq.md` | `lib/路径.mq.md` | Mid:join/normalize/… |
| `lib/hash.mq.md` | `lib/哈希.mq.md` | Mid:sha256/hmac/… |
| `lib/secrets.mq.md` | `lib/机密.mq.md` | Mid:token_hex/urlsafe |
| `lib/csv.mq.md` | `lib/逗号表.mq.md` | Mid:parse/stringify |
| `lib/cli.mq.md` | `lib/命令行.mq.md` | Mid:`parse` flags |
| `lib/log.mq.md` | `lib/日志.mq.md` | Mid:level-filtered one-line logs |
| `lib/uuid.mq.md` | `lib/标识.mq.md` | Mid:UUID v4 |
| `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM client effect helpers(GFM + `set_text`/`canvas`/…;见 marqdo-dev) |
| `lib/fs.mq.md` | `lib/文件.mq.md` | filesystem |
| `lib/sys.mq.md` | `lib/系统.mq.md` | process / cwd / load_dotenv |
| `lib/plugin.mq.md` | `lib/插件.mq.md` | load native ABI plugins (`doc/design/ext-abi.md`) |
| `lib/time.mq.md` | `lib/时间.mq.md` | time/format |
| `lib/net.mq.md` | `lib/网络.mq.md` | HTTP(S) helpers (+ optional headers) |
| `lib/json.mq.md` | (see design) | **parse / stringify / quote only** — not a dict builder |
| `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot |
| `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks |
| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | document-driven **step** / **plan** + OKF;示例 `examples/agent-pong` · `agent-okf-flywheel`;Wave B:[agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md) |
| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | dynamic sites — see **ext/web** section below |
| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below |
| `ext/linalg/linalg.mq.md` | `ext/linalg/线性代数.mq.md` | formula MatExpr + factorize/draw — see **ext/linalg** below |
Open the imported `.mq.md` under `lib/` or `ext/` to see exact `##` / `#` names and parameters. Gold tests: `tests/lib/`, `tests/structure/`, `tests/ext/`.
## ext/web (dynamic sites)
Install: `marqdo ext add web` (`网页`). Native: `cargo build --release -p marqdo_plugin_web`.
| EN import | ZH import | Core types |
|-----------|-----------|------------|
| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | `# page` `# style` `# db` `# form` `# app` `# auth` `# cache` `# storage` |
| Area | EN methods (representative) | Notes |
|------|----------------------------|-------|
| Page | `compose_components`, `compose_main`, `render`, `meta`, `paginate` | GFM tables; cells are literal path strings |
| DB | `init`, `insert`, `select`, `paginate`, `get`, `update`, `delete`, `migrate`, `fts`, `search`, `count`, `事务`/`txn` | init supports `unique`/`index`/`fk`; auto `created_at`/`updated_at` |
| App | `route`, `static`, `configure`, `listen`, `auth`, `gate`, `upload`, `download`, `gallery`, `route_rss`, `redirect`, `error_page`, `sitemap`, `robots` | W0–W7 + P3 complete |
| Auth | `login`, `check`, `logout`, `hash_password` | argon2 + CSRF + SQLite sessions; `role` for RBAC |
Drivers (Postgres / Redis / S3): `db url=postgres://…`, `cache url=memory:`, `storage url=file:…` — see `doc/design/ext-web-drivers.md`.
Example project: `examples/marqdo-blog/`. Capability matrix: `doc/design/web-net-capabilities.md`.
## ext/quantum (circuits + Q7/Q8)
Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p marqdo_plugin_quantum`, then re-run `ext add` so view picks up the new `.so`.
| EN import | ZH import | Core types |
|-----------|-----------|------------|
| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | `# circuit` `# gate` `# density` |
| Area | EN APIs | Notes |
|------|---------|-------|
| Circuit | `h`/`cx`/…, `simulate`, `probabilities`, `run`, `draw`, `noise` | `steps=` GFM table; ≤12 qubits |
| Gate | `matrix`, `matches_matrix`, `draw` | named or `matrix=` custom unitary |
| Density (Q7) | `purity`, `partial_trace`, `eig`, `expect`, `draw` | ≤6 qubits for dense ρ |
| Free (Q7) | `kron`, `schmidt`, `fidelity` | top-level on import bind |
| Draw kinds | `circuit\|probs\|bloch\|hinton\|city\|density\|paulivec\|qsphere\|multibloch` | quote `kind="…"` |
| Themes (Q8) | `theme="dark"\|"light"\|"bw"` (ZH `主题=`) | default **dark**; circuit/probs/bloch themed; SVG `data-theme` |
Examples: `examples/quantum-bell/`, `examples/quantum-entanglement/`. Design: `doc/design/ext-quantum.md` · Q7: `doc/design/ext-quantum-q7.md` · Q8: `doc/design/ext-quantum-viz-style.md`.
## ext/linalg (formula-first linear algebra)
Install: `marqdo ext add linalg` (`线性代数`). Native: `cargo build --release -p marqdo_plugin_linalg`, then re-run `ext add`.
| EN import | ZH import | Notes |
|-----------|-----------|-------|
| `ext/linalg/linalg.mq.md` | `ext/linalg/线性代数.mq.md` | Top-level `symbol`/`mul`/`factorize`/`draw` |
Examples: `examples/linalg-svd/`, `examples/linalg-least-squares/`. Design: `doc/design/ext-linalg.md` · formula-doc: `doc/design/ext-linalg-formula-doc.md` · roadmap: `doc/roadmap/ext-linalg.md`.
## Formula + plot (math)
```markdown
---
import math:lib/math.mq.md
---
# main
`f` =
$$
x^2 - 2
$$
*_svg = > plot formula=`f` var=x min=-3 max=3*
```
Empty RHS assignment + following `$$…$$` binds a formula value. Narrative-only `$$` without binding is display, not assignment.
## Foreign (Python example)
```markdown
---
import foreign:lib/foreign.mq.md
---
# main
`hi` =
```python
print("hello-from-python")
```
```
Lines starting with `` ` `` can be code (binding). Keep a blank line before/after fences per comment rules.
## Function-end details
| Form | Effect |
|------|--------|
| Lone `---` or `***` (≥3 same chars) at function body top level | End function; no return value |
| `****` or empty bold | Return `None` and end body |
| `**expr**` | Return `expr`; does **not** by itself cut off later sibling statements — still use HR or shallower heading |
File-leading paired `---` is frontmatter only; body `---` is not frontmatter.
## Call arguments
- Named: `> greet who=World`
- Positional: `> greet World`
- Spaces in values: allowed in named forms as in docs (`who=marqdo user`)
- Inline call in statement: `` *`n` = > len value=`s`* ``
See `doc/design/call-arguments.md`.
## Identifiers
- Variables: `` `name` ``
- Comparisons: `==` `>` `<` `>=` `<=`
- Do not use keyword tokens as names
## Design docs (repo)
| Doc | Topic |
|-----|--------|
| `doc/design/markdown-mapping-v0.3.md` | Syntax constitution (runtime) |
| `doc/design/markdown-mapping.md` | Legacy v0.2 notes |
| `doc/design/objects.md` | `#` objects / `##` methods |
| `doc/design/keywords.md` | Builtins / keywords |
| `doc/design/return-hr-and-code-surface.md` | Function end / surfaces |
| `doc/design/stdlib-i18n.md` | EN/ZH lib files |
| `doc/design/stdlib-modules.md` | L1 modules including plugin |
| `doc/design/ext-abi.md` | Native C ABI v1 |
| `doc/design/ext-llm.md` | `ext/llm` |
| `doc/design/ext-agent.md` | `ext/agent` agent **framework** (layout shipped; LLM orchestration roadmap) |
| `doc/design/ext-cli.md` | `marqdo ext list/add/remove` |
| `doc/design/ext-web.md` | `ext/web` dynamic sites (author API) |
| `doc/design/web-net-capabilities.md` | ext/web capability matrix (W0–W7 + P3) |
| `doc/design/ext-quantum.md` | `ext/quantum` circuits |
| `doc/design/ext-quantum-q7.md` | Q7 density linear algebra + advanced SVG |
| `doc/design/ext-quantum-viz-style.md` | Q8 themed SVG (`dark`/`light`/`bw`; circuit/probs/bloch) |
| `doc/design/ext-linalg.md` | `ext/linalg` formula MatExpr + factorize/draw |
| `doc/design/ext-linalg-formula-doc.md` | 公式文档面:跑通即正确 · 代数/计算两面 |
| `doc/design/view-debug.md` | view / debug hosts |
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.
+3
View File
@@ -0,0 +1,3 @@
# 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
@@ -0,0 +1,46 @@
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
@@ -0,0 +1,48 @@
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
@@ -0,0 +1,34 @@
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: 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"
+64
View File
@@ -0,0 +1,64 @@
# 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: pwsh
run: ./target/release/marqdo.exe call skills/marqdo-release/packs.mq.md ci --effects plugin,fs.write,environment.read --fs-root . --require-ok --json
- name: Attach source and Windows native packs without replacement
shell: pwsh
run: ./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.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
+28
View File
@@ -0,0 +1,28 @@
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
+43
View File
@@ -0,0 +1,43 @@
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
+30 -44
View File
@@ -38,7 +38,7 @@ jobs:
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
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)
@@ -88,6 +88,7 @@ jobs:
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"
@@ -102,6 +103,7 @@ jobs:
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"
@@ -116,56 +118,18 @@ jobs:
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: |
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **v1.4.6**:裸自增升参——首次粗体赋值左值即声明;`n = n + 1` 无反引号也是必选形参
- **v1.4.6**: Bare self-increment is a required parameter — first bold assignment LHS is a declaration
- **v1.4.5**:Streamable HTTP MCP + web invoke Bearer/401 · openai/agent json.get 硬化
- **v1.4.5**: Streamable HTTP MCP + web invoke Bearer/401; openai/agent json.get hardening
- **v1.4.2**:Agent/LLM 优化 O1–O5——sandbox trial · promote proof · step_route/EFI/cost · lint · quarantine
- **v1.4.2**: Agent/LLM optimize O1–O5 — sandbox trial, promote proof, step_route/EFI/cost, lint, quarantine
- **v1.4.1**:view 标注连线——SVG mid→mid(underline 底中 → chip 顶中)· 帧 chip id 对齐 · L→R 密度
- **v1.4.1**: View annot leaders — SVG mid→mid (mark bottom-center → chip top-center), frame chip id unify, L→R density
- **v1.4.0**:叙述统一——`% marqdo: var=` · 臂/循环体叙述 · foreach 中英糖 · 图片自写回 · view 推断形参
- **v1.4.0**: Prose-unified control flow — formula meta bind, arm/loop narrative, foreach sugar, image writeback, inferred-param view
- **v1.3.3**:view 文档面 Structure——叙述保真 · 标记面 · 调用/循环帧 · `#mq-view-trace` · 静态站同源
- **v1.3.3**: Browse document-surface Structure — narration, markers, call/loop frames, `#mq-view-trace`, static site parity
- **v1.3.0**:Engineering Knowledge Compiler——L0–L4 · `reuse`/`find`/`duplicate` · Agent preflight(REUSE→ADAPT→CREATE)
- **v1.3.0**: Engineering Knowledge Compiler — L0–L4 catalog, reuse/find/duplicate, Agent preflight (REUSE→ADAPT→CREATE)
- **v1.2.0**:Web Artifact(ADR 0007)——Document/Endpoint · `web.serve`/`render`/`inspect` · `ext/data|security|net` · 移除 `compose_*`/`configure`
- **v1.2.0**: Web Artifact (ADR 0007) — Document/Endpoint, web.serve/render/inspect, ext/data|security|net, compose_*/configure removed
- **Linux 包必出**:`*-native-x86_64-unknown-linux-gnu.zip` + Linux CLI bundle
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [ext-ai-optimize](https://github.com/cflmy/marqdo/blob/main/doc/roadmap/ext-ai-optimize.md)
### Downloads
| Asset | Contents |
|-------|----------|
| `marqdo-*-windows-msvc.exe` | CLI with **embedded** official stdlib |
| `marqdo-*-windows-msvc.zip` | `marqdo.exe` + `lib/` + `ext/`(含 native DLL) |
| `marqdo-*-native-*.zip` | 预编译 `web`/`agent`/`quantum`/`linalg`/`llm`(Windows DLL + **Linux .so 必出**) |
| `marqdo-*-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + native `.so` |
| `marqdo-*-stdlib.zip` | `lib/` only |
| `marqdo-*-ext.zip` | Official `ext/` L1 sources |
| `marqdo-*-source.zip` | Source snapshot (`git archive`) |
| `marqdo-*.vsix` | VS Code / Cursor extension |
| `marqdo-*-public.zip` | Static user docs site |
Extension workflow: [vscode-extension-commit.md](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)
body_path: doc/releases/${{ github.ref_name }}.md
files: |
dist/${{ env.EXE }}
dist/${{ env.ZIP }}
dist/${{ env.STDLIB }}
dist/${{ env.EXT }}
dist/${{ env.NATIVE }}
dist/${{ env.VSIX }}
dist/${{ env.SOURCE }}
dist/${{ env.PUBLIC }}
@@ -173,6 +137,17 @@ jobs:
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
@@ -196,7 +171,7 @@ jobs:
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
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
@@ -204,8 +179,11 @@ jobs:
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; do
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"
@@ -232,8 +210,16 @@ jobs:
uses: softprops/action-gh-release@v2
with:
files: |
dist/${{ env.NATIVE }}
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 }}
+35 -5
View File
@@ -42,11 +42,7 @@ spike/.pytest_cache/
*.pyc
# Built browser WASM (rebuild via crates/marqdo-wasm README)
/examples/browser-hello/marqdo_wasm.wasm
/examples/browser-hello/pkg/
/examples/web-client-site/static/marqdo_wasm.wasm
/examples/browser-app/marqdo_wasm.wasm
/examples/browser-media/marqdo_wasm.wasm
# Local sqlite / scratch
/data/
@@ -61,7 +57,6 @@ plugins/*/tmp/
/examples/web-net-site/data/
/examples/web-net-site-zh/data/
/examples/marqdo-blog/data/
/examples/anlian-mq/data/
# Quantum draw/SVG runtime outputs (sources & gold .mq.md stay tracked)
/tests/ext/quantum-*.svg
@@ -71,9 +66,24 @@ plugins/*/tmp/
/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/
@@ -93,3 +103,23 @@ 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
+583
View File
@@ -2,12 +2,593 @@
## Unreleased
## 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/<id>/` + `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
@@ -611,6 +1192,8 @@ marqdo run tests/markup-v03/inc-prose.mq.md
### 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
Generated
+202 -15
View File
@@ -186,6 +186,27 @@ dependencies = [
"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"
@@ -264,9 +285,9 @@ dependencies = [
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "crypto-common"
@@ -307,6 +328,12 @@ 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"
@@ -414,6 +441,12 @@ dependencies = [
"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"
@@ -525,6 +558,16 @@ dependencies = [
"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"
@@ -539,9 +582,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.104"
version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a"
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
dependencies = [
"cfg-if",
"futures-util",
@@ -572,11 +615,12 @@ checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "1.4.6"
version = "2.7.1"
dependencies = [
"anyhow",
"assert_cmd",
"chrono",
"chrono-tz",
"clap",
"futures-util",
"getrandom",
@@ -589,6 +633,7 @@ dependencies = [
"predicates",
"pulldown-cmark",
"regex",
"serde",
"serde_json",
"sha1",
"sha2",
@@ -596,14 +641,22 @@ dependencies = [
"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 = "1.4.6"
version = "2.7.1"
dependencies = [
"marqdo",
"serde_json",
@@ -614,6 +667,7 @@ name = "marqdo_plugin_agent"
version = "0.1.0"
dependencies = [
"chrono",
"marqdo-plugin-sdk",
"serde_json",
]
@@ -621,13 +675,32 @@ dependencies = [
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",
]
@@ -637,6 +710,7 @@ name = "marqdo_plugin_llm"
version = "0.1.0"
dependencies = [
"idna_adapter",
"marqdo-plugin-sdk",
"serde_json",
"ureq",
"zeroize",
@@ -646,6 +720,7 @@ dependencies = [
name = "marqdo_plugin_quantum"
version = "0.1.0"
dependencies = [
"marqdo-plugin-sdk",
"serde",
"serde_json",
]
@@ -714,12 +789,59 @@ 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"
@@ -958,6 +1080,15 @@ dependencies = [
"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"
@@ -992,6 +1123,12 @@ 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"
@@ -1139,6 +1276,47 @@ dependencies = [
"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"
@@ -1278,9 +1456,9 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasm-bindgen"
version = "0.2.127"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70"
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
dependencies = [
"cfg-if",
"once_cell",
@@ -1291,9 +1469,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.127"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1"
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -1301,22 +1479,22 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.127"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284"
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 2.0.119",
"syn 3.0.3",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.127"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf"
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
@@ -1480,6 +1658,15 @@ 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"
+10 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "1.4.6"
version = "2.7.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
@@ -19,7 +19,7 @@ cli = ["dep:clap"]
view = ["dep:tiny_http"]
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize", "dep:zip"]
plugin-host = ["dep:libloading"]
exec-host = []
exec-host = ["dep:libc"]
fs-host = []
tty = ["dep:libc"]
wasm-core = []
@@ -29,7 +29,8 @@ 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_json = "1"
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 }
@@ -48,6 +49,8 @@ zip = { version = "=0.6.6", default-features = false, features = ["deflate"], op
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).
@@ -57,14 +60,16 @@ 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/`); Rust sources kept as
# `plugins/web-rust-archive/` for reference (not a workspace member).
# 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]
+292 -21
View File
@@ -1,15 +1,128 @@
# Marqdo
# Marqdo — Your SKILL is now a TOOL.
**代码即文档。文档即知识库。知识即可执行。**
<p align="center"><strong>Write it. Inspect it. Call it.</strong></p>
<p align="center"><em>让 SKILL 真正成为工具:文档即知识,知识即可执行。</em></p>
Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,既是给人读的文稿,也是给机器跑的程序。写文档的过程就是在写可执行逻辑——大型项目里,说明、示例与实现不再分叉成三份真相。它不是「又一个 Markdown 编程语言」,而是**文档原生的编程运行时(Document-native runtime)**——一门关于**可执行知识(Executable Knowledge)**的语言。
<p align="center">
<a href="https://github.com/cflmy/marqdo/releases/tag/v2.7.1"><img alt="release" src="https://img.shields.io/badge/release-v2.7.1-DDBA86?style=flat-square"></a>
<a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square"></a>
<img alt="Rust runtime" src="https://img.shields.io/badge/runtime-Rust-B38E68?style=flat-square">
<img alt="Pure by default" src="https://img.shields.io/badge/call-pure_by_default-467C83?style=flat-square">
</p>
欢迎访问 [marqdo 官方网站](https://www.marqdo.com/) 阅读更多特性与可执行文档。
**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.
语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 对象:[objects.md](doc/design/objects.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 调试:[view-debug.md](doc/design/view-debug.md) · OKF 清单:[catalog-cli.md](doc/design/catalog-cli.md) · Engineering Knowledge:[engineering-knowledge.md](doc/design/engineering-knowledge.md) · VS Code 扩展:[vscode-extension.md](doc/design/vscode-extension.md)(分支 **`vscode-extension`**;提交约定 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md)) · **AI Skill**:[skills/marqdo/](skills/marqdo/)(说明 [ai-skill.md](doc/design/ai-skill.md)) · 官方扩展:[ext-llm.md](doc/design/ext-llm.md)(`ext/llm`)· [ext-agent.md](doc/design/ext-agent.md)(智能体开发框架)· [ext-cli.md](doc/design/ext-cli.md)(`marqdo ext list/add/remove`) · 原生插件 ABI:[ext-abi.md](doc/design/ext-abi.md)(`lib/plugin`) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) · 变更:[CHANGELOG.md](CHANGELOG.md)
**Not a prompt wrapper.** The document is interpreted as a program by Marqdo; its tool functions are not merely natural-language instructions.
<p align="center">
<a href="#one-markdown-file-three-views-real-execution">56s film</a> ·
<a href="#quickstart--one-function-one-command">Quickstart</a> ·
<a href="#a-procurement-skill-with-a-600-budget">Procurement demo</a> ·
<a href="#explore-the-view">View</a> ·
<a href="doc/library-development.mq.md">Guide</a> ·
<a href="https://www.marqdo.com/">Website</a> ·
<a href="doc/releases/v2.7.1.md">Release notes</a>
</p>
## 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)
<sub>**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.</sub>
**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 [2.7.1 CLI release for Windows or Linux](https://github.com/cflmy/marqdo/releases/tag/v2.7.1), then run from this repository's root:
```bash
marqdo call examples/calculator.mq.md 计算器.加法 a=2 b=3
# => 5
```
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
[Read the complete executable procurement document](examples/procurement/index.mq.md) · [How to run and verify the example](examples/procurement/README.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)
<sub>**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).</sub>
```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)
<sub>**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).</sub>
## 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.7.1](https://github.com/cflmy/marqdo/releases/tag/v2.7.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 · 语言、设计与执行系统
## 核心优势:可执行知识(Executable Knowledge)
> **Knowledge That Can Run —— 知识即可执行。**
@@ -29,15 +142,97 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
| 真正的核心优势 | 说明 |
|------|------|
| **知识-代码一致性**<br>Knowledge-Code Coherence | 说明、数据、示例与实现**同一份源文件**:文档里的表格就是程序的数据,文档里的调用就是真实执行。「文档过期」不再是悄悄漂移,而是可被机器发现的**知识不一致**——知识陈述本身可以被测试。 |
| **函数即工具**<br>`marqdo call` | 最小可执行单位是文件中的函数,不只是整份文件。人阅读函数旁边的叙述;开发者、测试和 Agent 用 `marqdo call 文件 函数 名字=值` 执行它。知识复用、工具调用、函数级测试和局部改进是同一入口的四种用法。 |
| **默认安全,AI 友好** | 无标记文字默认是叙述(注释),只有显式标记才进入执行。AI 自由发挥**不会污染**文档与代码的边界——这比「自然语言编程」安全得多,是 AI 原生语言的重要前提。 |
| **multi-view artifact**<br>`.mq.md` 双后缀即开放接口 | `.mq` 告诉解释器「可执行」,`.md` 告诉整个 Markdown 生态「仍是文档」。GitHub 直接读、VS Code 直接改、搜索引擎直接索引、LLM 直接理解、Marqdo 直接运行。**Marqdo 不占有知识,只是给 Markdown 增加执行语义。** |
| **表格即数据结构** | 程序的数据结构直接就是文档的数据结构:单列竖表 → `List`;横表(1 数据行)→ `Map`;横表(多数据行)→ `Map` of `List`(列向聚合);首列写 `@` / `行` / `row` → 行向记录 `List` of `Map`。取元 `[键](集合)` 也是 Markdown 链接形。这是 literate programming 的下一步。 |
| **表格即数据结构** | 程序的数据结构直接就是文档的数据结构:单列竖表 → `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。 |
| **链接即调用**<br>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」**:
@@ -45,7 +240,7 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
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. **可执行知识图**:`.mq.md` 之间的 Markdown 链接天然长成文档图 + 知识图 + 程序图(Executable Knowledge Graph)。
4. **链接即调用 / 可执行知识图**:`[描述](类.函数)` 既是文档链接,也是类/函数调用;编译器解析目标、校验签名、返回 LinkInfo;`view` 显示调用点;`.mq.md` 之间的链接长成文档图 + 知识图 + 程序图(Executable Knowledge Graph)。
5. **知识可测试**:文档中的示例表自动执行;知识与执行结果不一致会被机器报告——Knowledge-Code Coherence 从理念变为日常。
6. **可靠性基准**:让同一个 AI 分别用 Python / TypeScript / Marqdo 完成真实任务,测量生成长度、语法 / 语义错误率、修复轮次、token 消耗与人类阅读 / 修改成本——用实验数据证明「文档型语法降低 LLM 生成熵」。
@@ -64,24 +259,30 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
---
## 语法速览(v0.3)
## 语法速览
| 标记 | 含义 |
|------|------|
| 无标记行 | 叙述(注释);行内 `` `名` `` 可声明 |
| `**…**` | **代码**(赋值 / 调用 / 表达式) |
| `[描述](表达式)` | **链接(本地)**:描述 + 代码;`()` 与 `**…**` 同权(默认语义) |
| `[描述](类.函数)` | **链接(跨文档/类调用)**:描述 + 已有类函数调用;可解析、可执行(v2.1 目标) |
| `[描述](url)` | 普通 Markdown 导航链接(惰性,不执行) |
| `*…*` | **返回值**(整行、`返回*n*`、或表达式形) |
| `****` / 整行 `**` / `*None*` | **空返回**(`None`),并结束本函数体 |
| `> print …` 等 | 输出等副作用 = **普通函数**,非架构标记 |
| `#` | 对象 / 类型(构造体;`# main` = 入口) |
| `##` … | 函数 / 方法(按标题深度嵌套) |
| `#` | **类 / 类型**(知识命名空间;`# 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
@@ -116,6 +317,51 @@ Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.md` 文件,
---
## 工程习惯:允许申报未完成,但不允许假装完成
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 知识包(勿手改生成物):
@@ -149,8 +395,31 @@ marqdo catalog public -o .marqdo
---
## 现状(v1.4.6)
## 现状(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)
@@ -172,7 +441,7 @@ marqdo catalog public -o .marqdo
- **`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/) · [anlian-mq](examples/anlian-mq/)
- **`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)
@@ -181,10 +450,10 @@ marqdo catalog public -o .marqdo
- **原生插件 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-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([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))
- **浏览器 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(v1.4.6)
### 如何使用最新 Marqdo(v2.7.0)
**安装解释器(任选其一)**
@@ -199,14 +468,16 @@ marqdo catalog public -o .marqdo
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v1.4.6 # 或留在 main
git checkout v2.7.0 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
marqdo version --check
# 2) 跑解释器 / 文档站 / catalog
# 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
@@ -230,15 +501,15 @@ marqdo ext add llm # 或:大模型(.mq.md + 可选 native llm)
# 4) 动态站示例(扩展装好后)
marqdo run examples/web-site-zh/index.mq.md # 表驱动引言 Demo
marqdo run examples/marqdo-blog/serve.mq.md
marqdo run examples/anlian-mq/index.mq.md # W-G14 验收站
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-hello/
# → dist/wasm/ … 实际工程见 examples/browser-app/
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
# https://github.com/cflmy/marqdo/releases/tag/v1.4.6
# https://github.com/cflmy/marqdo/releases/tag/v2.7.0
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

@@ -0,0 +1,35 @@
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
Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.
+29
View File
@@ -0,0 +1,29 @@
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
Binary file not shown.

After

Width:  |  Height:  |  Size: 161 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

+42
View File
@@ -0,0 +1,42 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1340" height="720" viewBox="0 0 1340 720" role="img" aria-label="Animated illustration of a procurement skill being called, including a budget denial">
<defs><linearGradient id="night" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#0b1324"/><stop offset="1" stop-color="#1a2335"/></linearGradient></defs>
<rect x="0" y="0" width="1340" height="720" rx="0" fill="url(#night)" stroke="none"/>
<text x="46" y="52" fill="#f6d39c" font-size="30" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">Marqdo</text>
<text x="207" y="50" fill="#9eacc1" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">/ EXECUTABLE SKILLS</text>
<rect x="1137" y="25" width="165" height="38" rx="19" fill="#283348" stroke="#4b5b6b"/>
<text x="1154" y="50" fill="#d3d9e4" font-size="15" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">2.7.1 · DEMO</text>
<text x="46" y="109" fill="#f6f5ee" font-size="37" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">Your SKILL is now a TOOL.</text>
<text x="47" y="141" fill="#a8b6c7" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">A human-readable document → callable business logic → structured results</text>
<rect x="43" y="168" width="608" height="493" rx="18" fill="#182235" stroke="#38485c"/>
<rect x="677" y="168" width="620" height="493" rx="18" fill="#111a2b" stroke="#38485c"/>
<rect x="43" y="168" width="608" height="57" rx="18" fill="#263349" stroke="none"/>
<rect x="677" y="168" width="620" height="57" rx="18" fill="#263349" stroke="none"/>
<text x="65" y="204" fill="#f5dba9" font-size="20" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">index.mq.md</text>
<text x="707" y="204" fill="#e5eaf4" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">$ marqdo call ... 向采购商发工单</text>
<text x="66" y="266" fill="#faf7f1" font-size="27" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">## 向采购商发工单</text>
<text x="66" y="307" fill="#a2b2ca" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">Read the rules. Call the function.</text>
<rect x="65" y="328" width="564" height="166" rx="9" fill="#101a2a" stroke="none"/>
<text x="86" y="365" fill="#abd6fa" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">报价 = 查询采购商价格(...)</text>
<text x="86" y="407" fill="#abd6fa" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">预算 = 查询余额(已花费=...)</text>
<text x="86" y="453" fill="#e9ba84" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">1. 剩余额度 &lt; 本单金额 → 拒绝</text>
<text x="65" y="552" fill="#d4e0ee" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">One file: prose + contracts + tables</text>
<text x="65" y="588" fill="#d4e0ee" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">+ executable functions + result records</text>
<text x="706" y="272" fill="#d7deef" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">SUP_JN 数量=8 单价=36</text>
<text x="706" y="311" fill="#98aec9" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">最高预算 = ¥600</text>
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.04;0.09;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="345" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="374" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">01 SUPPLIER</text><text x="920" y="374" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">SUP_JN · active</text></g>
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.19;0.24;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="399" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="428" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">02 QUOTE</text><text x="920" y="428" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">8 × ¥36 = ¥288</text></g>
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.35;0.39999999999999997;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="453" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="482" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">03 BALANCE</text><text x="920" y="482" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">¥600 - already spent</text></g>
<g opacity=".18"><animate attributeName="opacity" values="0.18;0.18;1;1;0.18" keyTimes="0;0.53;0.5800000000000001;0.91;1" dur="13s" repeatCount="indefinite"/><rect x="704" y="507" width="565" height="45" rx="9" fill="#233248" stroke="none"/><text x="719" y="536" fill="#9db5cf" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">04 DECISION</text><text x="920" y="536" fill="#f5d8aa" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">check requested amount</text></g>
<g opacity="0"><animate attributeName="opacity" values="0;0;1;1;0" keyTimes="0;0.62;0.66;0.85;1" dur="13s" repeatCount="indefinite"/>
<rect x="704" y="572" width="565" height="68" rx="10" fill="#193a34" stroke="#478a71"/>
<text x="718" y="600" fill="#b5ebcb" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">✓ 已花费=120 ¥480 ≥ ¥288</text>
<text x="718" y="625" fill="#d9f7e8" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">ok: true · 本地模拟,未发送</text>
</g>
<g opacity="0"><animate attributeName="opacity" values="0;0;0;1;1;0" keyTimes="0;0.78;0.84;0.88;0.95;1" dur="13s" repeatCount="indefinite"/>
<rect x="704" y="572" width="565" height="68" rx="10" fill="#42252d" stroke="#a45a67"/>
<text x="718" y="600" fill="#f8b1bc" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">✕ 已花费=360 ¥240 &lt; ¥288</text>
<text x="718" y="625" fill="#fde7ea" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">ok: false · 预算不足,拒绝工单</text>
</g>
<path d="M 652 430 C 665 429 674 429 688 430" fill="none" stroke="#f0c58c" stroke-width="3"/><circle cx="665" cy="429" r="4" fill="#f0c58c"><animate attributeName="cx" values="656;681;656" dur="2.5s" repeatCount="indefinite"/></circle>
<text x="44" y="698" fill="#7e90a7" font-size="14" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">ILLUSTRATED EXPECTED FLOW · NOT A TERMINAL CAPTURE · NO REAL PURCHASE</text>
</svg>

After

Width:  |  Height:  |  Size: 7.4 KiB

@@ -0,0 +1,35 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1340" height="740" viewBox="0 0 1340 740" role="img" aria-label="View-inspired editorial concept for the procurement function, not a real screenshot">
<rect x="0" y="0" width="1340" height="740" rx="0" fill="#f8f6f0" stroke="none"/>
<rect x="0" y="0" width="1340" height="68" rx="0" fill="#f2ede4" stroke="none"/>
<text x="69" y="45" fill="#8d7358" font-size="29" font-family="Georgia,serif" font-weight="600">marqdo</text>
<text x="577" y="43" fill="#665d53" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">文档 函数 执行 变量</text>
<text x="1030" y="44" fill="#998773" font-size="13" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">VIEW CONCEPT / NOT CAPTURE</text>
<line x1="325" y1="113" x2="325" y2="688" stroke="#e0d5c7"/><line x1="1032" y1="113" x2="1032" y2="688" stroke="#e0d5c7"/>
<text x="374" y="128" fill="#b0895e" font-size="16" font-family="Georgia,'Noto Serif CJK SC',serif" font-weight="400">采购智能体</text>
<text x="372" y="196" fill="#39352d" font-size="37" font-family="'Noto Serif CJK SC',Georgia,serif" font-weight="600">向采购商发工单</text>
<text x="374" y="238" fill="#5d5851" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">核对准入、价格、交付与预算之后,生成本地模拟工单。</text>
<line x1="374" y1="267" x2="993" y2="267" stroke="#b69b78"/>
<text x="375" y="309" fill="#514a41" font-size="21" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="600">参数</text>
<text x="375" y="348" fill="#5b5146" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">采购商标识符</text>
<text x="625" y="348" fill="#96754f" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">text</text>
<text x="811" y="348" fill="#8e8171" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">必填</text>
<line x1="374" y1="365" x2="994" y2="365" stroke="#ded6c9"/>
<text x="375" y="392" fill="#5b5146" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">数量 / 单价 / 已花费</text>
<text x="625" y="392" fill="#96754f" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">number</text>
<text x="811" y="392" fill="#8e8171" font-size="17" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">必填</text>
<line x1="374" y1="408" x2="994" y2="408" stroke="#ded6c9"/>
<text x="374" y="463" fill="#5e584f" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">发单前,必须再次查询并核对本轮的可用余额。</text>
<rect x="373" y="483" width="618" height="48" rx="8" fill="#ebe3d5" stroke="none"/>
<text x="391" y="513" fill="#805b35" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">预算 = [重新查询预算](查询余额(...))</text>
<text x="374" y="565" fill="#7b5b4b" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">1. 剩余额度 &lt; 本单金额</text>
<text x="374" y="612" fill="#a06b5f" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400"> 返回 [预算不足,拒绝模拟工单](...)</text>
<text x="375" y="682" fill="#8c8276" font-size="16" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">仅在全部检查通过时产生“本地模拟、未发送”的结果。</text>
<path d="M 408 503 C 295 503 278 339 146 339" stroke="#ba9a75" stroke-width="1.7" fill="none"/><circle cx="408" cy="503" r="4.3" fill="#ba9a75"/>
<text x="73" y="281" fill="#a78255" font-size="15" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">BUDGET CHECK</text>
<text x="73" y="315" fill="#756350" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">已花费 ¥360</text>
<text x="73" y="343" fill="#756350" font-size="18" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">剩余额度 ¥240</text>
<path d="M 823 602 C 1010 586 1026 396 1122 396" stroke="#b7837e" stroke-width="1.7" fill="none"/><circle cx="823" cy="602" r="4.3" fill="#b7837e"/>
<text x="1080" y="319" fill="#a67871" font-size="15" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">REJECTION</text>
<text x="1080" y="354" fill="#945e55" font-size="22" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="700">¥240 &lt; ¥288</text>
<text x="1080" y="393" fill="#945e55" font-size="19" font-family="ui-monospace,Consolas,'Noto Sans CJK SC',monospace" font-weight="400">拒绝工单</text>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 523 KiB

+7
View File
@@ -0,0 +1,7 @@
[package]
name = "marqdo-plugin-sdk"
version = "2.0.0"
edition = "2021"
[dependencies]
serde_json = "1"
+195
View File
@@ -0,0 +1,195 @@
//! Shared ABI plumbing for Marqdo native plugins (`<TAB>` 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<unsafe extern "C" fn(n: usize) -> *mut c_void>,
pub free: Option<unsafe extern "C" fn(p: *mut c_void)>,
pub host_query: Option<HostQueryFn>,
}
pub static mut HOST_FREE: Option<unsafe extern "C" fn(*mut c_void)> = None;
pub static mut HOST_ALLOC: Option<unsafe extern "C" fn(usize) -> *mut c_void> = None;
pub static mut HOST_QUERY: Option<HostQueryFn> = 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<Value, String> {
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<Value, String>) -> 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<Value, String> {
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<Value, String> {
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<String> {
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) ),* ])
}
};
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "1.4.6"
version = "2.7.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
@@ -12,4 +12,4 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
marqdo = { path = "../..", default-features = false, features = ["wasm-core"] }
serde_json = "1"
serde_json = "1"
+3 -1
View File
@@ -11,7 +11,7 @@ Raw `cdylib` exports — no `wasm-bindgen` CLI required.
```bash
# from repo root (C5 size profile)
marqdo wasm build -o examples/browser-hello
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
```
@@ -19,3 +19,5 @@ cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-was
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.
+43 -19
View File
@@ -228,28 +228,52 @@ function applyStyle(el, styleVal) {
}
export function renderListItems(spec) {
const tag = String(spec.tag || "li");
const rootTag = 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))}</${tag}>`;
}
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))}"`;
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))}"`;
}
const inner = it.html != null ? String(it.html) : escapeHtml(text ?? "");
return `<${tag}${cls}${attrs}>${inner}</${tag}>`;
})
.join("");
}
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}</${tag}>`;
};
return items.map(item => render(item, rootTag, 0)).join("");
}
function escapeHtml(s) {
+172
View File
@@ -1,3 +1,175 @@
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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <cflmy@users.noreply.github.com> 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 <noreply@marqdo.com> 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 <noreply@marqdo.com> 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 <noreply@marqdo.com> 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 <noreply@marqdo.com> 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 <noreply@marqdo.com> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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 <pingan@cflmy.cn> 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.
+18
View File
@@ -0,0 +1,18 @@
Description: Use stable Option map_or in the engineering release boundary
Author: Marqdo Maintainers <cflmy@users.noreply.github.com>
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<BTreeMap<String,String>,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)
}
+2
View File
@@ -0,0 +1,2 @@
# engineering-stable-option.patch
# The fix is already in upstream 2.7.1.
+44 -4
View File
@@ -13,10 +13,26 @@
## 当前文档
> **可执行知识下一阶段的阅读顺序**:[原始意图 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/markdown-mapping.md](design/markdown-mapping.md) | **v0.2 语法宪法(现行运行时)** |
| [design/markdown-mapping-v0.3.md](design/markdown-mapping-v0.3.md) | **v0.3 草案:叙述统一 · 粗体代码 · 斜体返回 · 形参体推断** |
| [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) | **`#` 对象 / `##` 函数与方法** |
@@ -33,6 +49,7 @@
| [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/网络/数学/外联/插件** |
@@ -48,7 +65,13 @@
| [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 具名块)— 已落地** |
| [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 循环)** |
@@ -57,7 +80,7 @@
| [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 · 网页制备完备 · anlian 验收) |
| [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、布局…) |
@@ -99,6 +122,23 @@
| [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/)。
+2
View File
@@ -1,5 +1,7 @@
# ADR 0004:网络拓展库原生实现改为 Go
历史说明(2026-11-10):下文业务站点仅记录当时决策背景,相关工程已移出本仓库;当前验收使用维护中的完整站点、网络站点及隔离测试,见 [当前工作流](../design/ext-web-go-rewrite.md#8-独立工作流与隔离验收)。
| | |
|---|---|
| Status | **Accepted** |
+68
View File
@@ -0,0 +1,68 @@
# 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) |
+33
View File
@@ -0,0 +1,33 @@
# 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。
@@ -0,0 +1,348 @@
# 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": "<p>正文</p>"},
"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 保持不可用,不阻塞已经完成的只读预览切片。
+252
View File
@@ -0,0 +1,252 @@
# 语义评估:参数能否从上下文推断(含叙述式调用)
> **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 的所有验证结论。
+2 -1
View File
@@ -36,7 +36,8 @@ 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
import:
sys: lib/sys.mq.md
---
```
+302
View File
@@ -0,0 +1,302 @@
# 评定:`[描述](语句)` —— 方括号读作「人话」,圆括号读作「机器话」
> **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 超链接:可见文本 ↔ 目标
`<a>` / `[可见文字](目标地址)` 的全部意义就是**给机器一个目标,给人类一个说法**。
这是人类最早、最成功的"双面文本"。
### 1.2 文学编程的 chunk 名(Knuth)
Knuth 的 `<<chunk name>>` 就是"可执行片段的人话名字"。
而**文学编程的整个出发点,正是你前面说的"代码要像文章"**——这个类比不是巧合。
### 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. 循环的新写法你倾向哪一种:
- `- [从篮子取出的每个果子](遍历 篮子 为 果)`
- `- [篮子里的果子](篮子 → 果)`
- 保留 `- [果](篮子)` 作短形
+9 -5
View File
@@ -1,5 +1,8 @@
# 浏览器 Marqdo(WASM 解释器)设计
> 2.7.0 维护说明:独立的 browser-hello 与 browser-media 演示已删除。下文保留既有能力设计与宿主边界,当前可运行工程使用 browser-app;底层计数器冒烟夹具位于 tests/wasm/counter.mq.md。Canvas、音频等仍是 lib/browser 的宿主能力,不宣称当前 browser-app 演示包含这些交互。
| | |
|---|---|
| 状态 | **Accepted(设计锁定)** · 实现见路线图 C0–C5 |
@@ -124,7 +127,7 @@ source: &str (+ optional import map)
| `marqdo`(根) | 核心;feature-gate |
| `crates/marqdo-wasm` | `cdylib`:`mq_*` ABI + `js/marqdo-bridge.js` |
| `ext/web` 或 `web/browser` | L1:`浏览器.运行` / `交互装配`(C3+) |
| `examples/browser-hello/` | 静态页 + wasm 冒烟 |
| `examples/browser-app/` | 静态页 + wasm 冒烟 |
| `tests/browser/` 或金样脚本 | Node/wasmtime 跑 `run_source` 对齐 |
发行:`marqdo wasm build`(C2 CLI 糖)或 `wasm-pack build crates/marqdo-wasm`。
@@ -156,7 +159,8 @@ source: &str (+ optional import map)
```markdown
---
import json:lib/json.mq.md
import:
json: lib/json.mq.md
---
# main
@@ -209,7 +213,7 @@ L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表
Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。
示例见 `examples/browser-hello/fetch.mq.md`。
示例见 `examples/browser-app/static/app.mq.md`。
---
@@ -250,7 +254,7 @@ marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
# app.static dir=static
```
业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-hello/`)。
业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-app/`)。
---
@@ -260,7 +264,7 @@ marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
|----|------|
| 单元 | `run_source("…# main\n> print…")` native 与 wasm 同测 |
| 金样子集 | `tests/structure/hello.mq.md` 等无 fs/net/plugin 的样例 |
| 浏览器冒烟 | `examples/browser-hello`:按钮点击 → Marqdo 函数 → 改 DOM 文本 |
| 浏览器冒烟 | `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` |
---
+2
View File
@@ -1,5 +1,7 @@
# 调用实参:具名与位置
> **2026-10-23 适用范围校正**:本文保留早期调用尾部规则和历史示例,不是 v2.1 全部调用语法。当前已有 `f(args)` 及具名实参;默认紧邻 `](` 是描述包裹 payload,不再是下文所述的 Classic 取元。语法审阅与开发取舍见[文档原生指导 §2](document-native-development-guide.md#2-语法审查的保留修正与暂缓),当前行为须由默认模式测试复核。
| | |
|---|---|
| 状态 | 已定(v0.1 增补;2026-09-14:方括号标记调用) |
+289
View File
@@ -0,0 +1,289 @@
# 语法设计:标记如何构成调用(在「只执行标记」原则下)
> **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<String, Value> }`,每个实参 `k.clone()` + `v.clone()`(**深拷贝**) | 167 ms | 66 ms |
| **字节码**(`--backend bytecode`) | `slots: Vec<Value>`,`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 回归 → 写变更文档。
+231
View File
@@ -0,0 +1,231 @@
# 变更记录: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** |
+99
View File
@@ -0,0 +1,99 @@
# 变更记录: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` | 本文件 |
+134
View File
@@ -0,0 +1,134 @@
# 变更记录: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` | 本文件 |
@@ -0,0 +1,73 @@
# 变更记录: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` | 本文件 |
+126
View File
@@ -0,0 +1,126 @@
# 变更记录: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<Box<Expr>>, // 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` | 本文件 |
@@ -0,0 +1,91 @@
# 变更记录: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` | 本文件 |
+89
View File
@@ -0,0 +1,89 @@
# 变更记录: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<String>`),供 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<String>` |
| `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` | 本文件 |
+84
View File
@@ -0,0 +1,84 @@
# 变更记录: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` | 本文件 |
+103
View File
@@ -0,0 +1,103 @@
# 变更记录: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` | 本文件 |
+109
View File
@@ -0,0 +1,109 @@
# 变更记录: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` | 本文件 |
+127
View File
@@ -0,0 +1,127 @@
# 变更记录: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` | 本文件 |
+81
View File
@@ -0,0 +1,81 @@
# 变更记录: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` | 本文件 |
+89
View File
@@ -0,0 +1,89 @@
# 变更记录: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)。结果:
```
<div class="structure"><div class="err">parse/load error: expected ')' after link-index collection</div></div>
```
任何带 `markup: occlusion` 的文档在 view 里**结构区直接报错**,只能退化成源码视图。
用户看到的"粗体里的 `[描述](实现)` 没渲染"其实是这个错误的表象。
**修法**:`load::parse_source_auto(source)` —— 先读 frontmatter 的 `markup:`,
用 `with_markup` 包住 `parse_source`,view 的五处解析点全部改用它。
## 2. 遮蔽呈现
### 2.1 浏览视图(`document.rs`,`/file`)
```html
<div class="doc-line doc-occl" data-line="81">
<span class="occl-pre">留存 =</span> <!-- 变量名:灰、等宽 -->
<span class="occl-label">客户留存率,模拟数据</span> <!-- 描述:正文 -->
<code class="occl-code">0.42</code> <!-- 实现:代码片 -->
</div>
```
- 空载荷 → `<span class="occl-stub">桩</span>`(琥珀色徽章,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` | 本文件 |
+113
View File
@@ -0,0 +1,113 @@
# 变更记录: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` | 本文件 |
+103
View File
@@ -0,0 +1,103 @@
# 变更记录:插件 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` | 本文件 |
+103
View File
@@ -0,0 +1,103 @@
# 代码体量审计: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` 引擎),
而不是继续在特性内部找"重复"——那已经找完了。
+9 -7
View File
@@ -3,22 +3,24 @@
| | |
|---|---|
| 状态 | **Accepted · 核心语法封闭集合(CI 守卫锁定)** |
| 日期 | 2026-09-22 |
| 日期 | 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` |
| `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` |
| `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` |
@@ -30,12 +32,12 @@
| id | 外形 | 语义 | 戒律 | 样例 |
|----|------|------|------|------|
| `ident` | `` `名` `` | 声明 / 引用 | 首次未赋值 = 声明;叙述与程序共用同一视觉习惯 | `tests/markup-v03/decl-ident-only.mq.md` |
| `bold-code` | `**…**` | 代码(赋值 / 调用 / 表达式) | 只有粗体进入执行;判别序:赋值 → 调用 → 表达式 | `tests/markup-v03/multi-bold.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` | `[键](集合)` | 取元 / foreach | **主取元语法**;与 bracket-call 靠 `]` 后是否紧邻 `(` 消歧 | `tests/lib/table-collections.mq.md` |
| `bracket-call` | `修饰… [函数] 实参…` | 方括号标记调用 | 前置修饰 → `名=True`;与 link-index 消歧同上 | `tests/structure/bracket-call.mq.md` |
| `footnote-index` | `集合[^键]` | 过渡取元 | **仅兼容**;新代码一律写 link-index | `tests/structure/footnote-index.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`)
+1 -1
View File
@@ -80,7 +80,7 @@ Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这
| **pulldown-cmark** *或* **comrak** | GFM 事件/AST | 标题、列表、表格、emphasis/strong;Spike 已证明「库 + 行扫描」可行。二选一做 Spike 对比后钉死 |
| **thiserror** / **anyhow** | 错误类型 | 诊断与 CLI 报错 |
| **clap** | CLI | `marqdo run [path]` |
| **serde** + **serde_yaml** | 元信息 | 仅解析 frontmatter 中的 YAML **键值**;`import x:x.mq.md` 仍按**行**抽取(见 Spike) |
| **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` |
@@ -0,0 +1,284 @@
# 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?
- 这是已实现、受限试点还是设计目标?文档和发布声明是否一致?
**准入原则**:内部可以使用成熟编译器、数据库和协议技术;外部必须减少知识在“说明、程序、索引、工具描述”之间的重复翻译。独特性由这条链的实际收益体现,不由新符号数量或与其他语言不同的程度体现。
+8 -5
View File
@@ -51,22 +51,25 @@ Marqdo 把仓库投影为 **可查询、可验证、可复用** 的工程知识
`implements` · `uses` · `depends_on` · `tested_by` · `documented_by` · `constrained_by` · `decided_by` · `supersedes` · `conflicts_with` · `deprecated_by` · `derived_from` · `failed_by` · `related_to`
落盘:`.marqdo/graph/graph.json` · `edges.json` · `index.json`。
落盘(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(默认)
marqdo knowledge preflight "task"
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"
marqdo find "authentication" # 同上:缺图才 compile;--refresh 强制
marqdo reuse "implement oauth login"
marqdo impact path/to/file.mq.md
marqdo conflicts | stale | duplicate [--fail] | verify
```
统一 `--json`。`duplicate` 默认阈值 `0.75`;`--fail` 作 CI Gate。
统一 `--json`。查询类命令(`preflight` / `find` / `reuse` / `impact` / `conflicts` / `stale` / `duplicate` / `verify`)默认 **读已编译投影**;CI 或源变更后应先 `marqdo knowledge` 或加 `--refresh`。`duplicate` 默认阈值 `0.75`;`--fail` 作 CI Gate。
## 6. Reuse 协议
+206
View File
@@ -0,0 +1,206 @@
# 可执行知识系统:`[]()` 的统一语法与跨文件闭环
| | |
|---|---|
| 状态 | **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<T>`
`[]()` 的正确抽象不是“链接调用”,而是泛型 AST 装饰器:
```text
Named<T> { 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<T>`。所以循环不会被误判成“返回一个事实”,取元也不会
被迫拥有来源表;但两者都能在图中被看见、被搜索、被影响分析。
### 1.1 每个节点都有角色,而不是两套语法
角色由既有 AST、类型、效果和依赖推导,必要时由所在 `#`/`##` 的契约约束:
| role | 如何识别 | `check` 应问什么 |
|---|---|---|
| `observe` | 取元、读取字段、读取表/文档 | 读什么、类型是什么、是否可用 |
| `derive` | 纯计算、聚合、映射 | 输入、输出、公式/依赖是否完整 |
| `reuse` | 调用已解析的 `##` / 模块能力 | 调用到哪个稳定符号、参数/返回是否匹配 |
| `iterate` | 已有遍历/循环载荷 | 遍历什么、绑定什么、循环体依赖什么 |
| `act` | 写入、请求、打印等副作用 | 权限、幂等性、影响目标 |
| `narrate` | 正文中的命名载荷 | 它在句中替代什么值、依赖是否可解析 |
一个节点可以有多个 role,例如 `[同步并记录](写入(...) + 记录(...))` 是 `act`,也依赖
若干 `observe`/`reuse` 节点。角色是编译结果,不是作者需要记忆的关键字。
---
## 2. 知识层不是目录隔离,而是同一图的不同投影
“几层知识”不应把语法和项目切断。它们是同一个 `Named<T>` 图中不同职责的节点;
同一份 `.mq.md` 可以同时有多层节点。
| 投影层 | 在统一图中的节点 | 由什么语法产生 | 它回答的问题 |
|---|---|---|---|
| **E 证据** | 原文、数据、文件/表读取节点 | Markdown 链接、`at(...)`、读取调用 | 事实从哪里来? |
| **C 概念** | 类型、字段、术语、约束 | `#`、字段/契约表 | 这些值是什么意思、能否组合? |
| **K 原子知识** | 命名个体、事实、规则 | `# 个体`、`##`、`Named<Expr>` | 哪个可调用单元给出什么知识? |
| **D 推导知识** | 聚合、计算、决策、工作流步骤 | 任意 `Named<Expr>` / `Named<LoopSpec>` | 如何从已有知识得到新结论/行动? |
| **N 叙述知识** | 段落与正文调用槽 | 正文 `Named<InlinePayload>` | 如何把结论说给人或 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<T>
│
├─ run:擦除 label,按原语义执行
├─ view:显示 label,可展开值、输入、步骤和来源
└─ check:解析所有依赖,编译统一知识图
│
catalog / lock / context pack
│
来源、规则、代码任一变化 ── impact / verify ──> 所有受影响 Named<T> 与叙述句子
│
作者或 agent 修复后重新 check/verify
```
### 5.1 命令边界
| 操作 | 做什么 | 不做什么 |
|---|---|---|
| `run` | 执行代码位置的原 payload | 不因为正文出现 `[]()` 而执行副作用 |
| `check` | 建图、解析类型/符号/依赖、检查 label 漂移 | 不求值、不伪造运行结果 |
| `view` | 呈现命名步骤及可选值/来源 | 静态模式不执行;live 模式遵守 effect 权限 |
| `verify` | 在沙箱中重算 pure 节点、核对来源/指纹 | 不执行 `act` 节点 |
| `impact` | 从变更节点反查依赖、函数、文档 span | 不按文本猜测关系 |
这样,任意通用代码一开始就属于知识图;只有在执行/验证权限上分级,而不是在语法上被分裂。
---
## 6. 实施顺序
1. 在表达式、遍历和正文三处统一保留 `Named<T>`;payload 复用各自现有 parser。
2. 为任意 `Named<T>` 提取 `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;让一次变更能回到具体的 `[]()` 和具体句子。
验收不是“能把一个类函数链接出来”,而是:**改一处表字段、来源、规则或函数,系统能列出受影响的
取元、循环、推导、调用和正文;其中每一步既可展开为代码,也可读成文档。**
+2 -1
View File
@@ -61,7 +61,8 @@ Unknown names fail. Queries are only valid during a plugin function call (host s
```markdown
---
import plugin:lib/plugin.mq.md
import:
plugin: lib/plugin.mq.md
---
# main
+6 -5
View File
@@ -159,11 +159,12 @@ REPLACE
```markdown
---
title: agent-run-…
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
import writeback:lib/writeback.mq.md
import subtask:lib/subtask.mq.md
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
---
# 总目标
+5 -4
View File
@@ -72,10 +72,11 @@ Marqdo 的宪法是 **代码即文档、文档即知识库**:
```markdown
---
导入 智能体:ext/ai/智能体.mq.md
导入 大模型:ext/ai/大模型.mq.md
导入 自写回:lib/自写回.mq.md
导入 时间:lib/时间.mq.md
导入:
智能体: ext/ai/智能体.mq.md
大模型: ext/ai/大模型.mq.md
自写回: lib/自写回.mq.md
时间: lib/时间.mq.md
---
## 获取时间
+29 -54
View File
@@ -1,66 +1,41 @@
# Extension CDN (Cloudflare R2 → https://ext.marqdo.com)
# 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 |
|---|---|
| Status | **Accepted** — download prefer CDN; upload via `scripts/upload-ext-r2.py` |
| Date | 2026-09-17 |
| Related | [ext-cli.md](ext-cli.md) · [marqdo-release](../../.cursor/skills/marqdo-release/SKILL.md) |
| 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 |
## Why
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.
CLI (语法解释器) and official **extension packs** (`ext/` L1 + native plugins) update on different cadences. Users behind unstable GitHub links should get packs from a stable object store first.
## Callable publication
## Public URL layout
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.
Bucket: `marqdo` · Custom domain: **https://ext.marqdo.com**
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
```
| Key | Meaning |
|-----|---------|
| `v{VER}/marqdo-{VER}-ext.zip` | L1 sources |
| `v{VER}/marqdo-{VER}-native-{triple}.zip` | Prebuilt plugins |
| `v{VER}/VERSION` | Pack SemVer echo |
| `latest/VERSION` | Recommended pack SemVer (plain text) |
| `latest/marqdo-…zip` | Same assets mirrored for convenience |
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.
`{VER}` is the **extension pack** version (`ext/VERSION`), which **may differ** from CLI `Cargo.toml` version.
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.
## Client download order (`marqdo ext add`)
## Explicit boundaries
1. `MARQDO_EXT_DOWNLOAD_BASE` (optional override)
2. **CDN** `https://ext.marqdo.com/v{VER}/…` (override host with `MARQDO_EXT_CDN`)
3. GitHub Releases
4. `https://proxy.cflmy.top/github.com/…`
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.
Pack SemVer resolution (`release_version()`):
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.
1. `MARQDO_EXT_VERSION`
2. CDN `GET …/latest/VERSION` (short timeout)
3. Embedded `ext/VERSION` at build time
4. CLI `CARGO_PKG_VERSION`
## Separate ext release (no CLI bump)
1. Bump `ext/VERSION` (e.g. `1.0.3`) — leave root `Cargo.toml` alone if CLI unchanged.
2. Build native zips (CI Linux/Windows jobs or local `scripts/build-web-plugin.sh` + cargo plugins).
3. Package `marqdo-{VER}-ext.zip` and `marqdo-{VER}-native-*.zip`.
4. Upload **both**:
- R2: `python3 scripts/upload-ext-r2.py --version VER --from-dir dist/`
- GitHub: attach to a GitHub Release (tag `ext-vVER` **or** reuse latest CLI release assets)
5. Confirm `https://ext.marqdo.com/latest/VERSION` and a sample zip URL return 200.
## Full product release (CLI + ext)
Keep `ext/VERSION` equal to (or compatible with) CLI SemVer unless documenting a deliberate skew. CI still publishes GitHub assets; **after** CI green, run `upload-ext-r2.py` so CDN is populated (or add a CI step with R2 secrets).
## Credentials
| Where | What |
|-------|------|
| Local | `~/.marqdo/r2.env` (`chmod 600`) — see `.env.r2.example` |
| CI (optional) | GitHub Actions secrets: `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`, `R2_ENDPOINT`, `R2_BUCKET` |
**Never** commit Account API tokens or S3 secret keys. If a token was pasted into chat, **rotate** it in the Cloudflare dashboard.
## Object ACL
Custom domain public reads require the bucket/objects to be publicly readable (R2 public bucket / r2.dev / custom domain). Uploads use S3 API credentials; downloads by `ext add` are anonymous HTTPS GETs.
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.
+2 -2
View File
@@ -93,8 +93,8 @@ web.plugin # absolute path hint
|----|-----------------------------|
| `llm` | `ai/llm.mq.md`, `ai/大模型.mq.md` |
| `agent` | `ai/agent.mq.md`, `ai/智能体.mq.md`, **native `agent`** |
| `web` | `web/web.mq.md`, `web/网页.mq.md`, **native `web`** |
| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **native `quantum`** |
| `web` | `web/index.mq.md` + facade/modules + `layout/` · `布局/` + `网页.mq.md`, **native `web`** |
| `quantum` | `quantum/`(含 `量子/` 中文树), **native `quantum`** |
## Release assets (native)
+91
View File
@@ -0,0 +1,91 @@
# 扩展库: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 <FILE> <FUNCTION> [k=v…]
[--json] [--backend tree|bytecode]
[--effects none|plugin] # 默认 none
[--session <id>]
[--toget <name>] # 或尾部 toget <name>
```
- 默认:仅纯函数(今日行为)。
- `--effects plugin`:允许 `plugin.call`(及附属的 `output.write`);仍拒绝 fs.write / network / process.exec / llm 等。
- `toget` + `--session`:绑定写入 `.marqdo/call-sessions/<id>.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) 作为开发范式长文 |
+2 -1
View File
@@ -197,7 +197,8 @@
````markdown
---
import la:ext/linalg/linalg.mq.md
import:
la: ext/linalg/linalg.mq.md
---
# 转置反序
+3 -2
View File
@@ -201,8 +201,9 @@ $$
````markdown
---
import la:ext/linalg/linalg.mq.md
import table:lib/table.mq.md
import:
la: ext/linalg/linalg.mq.md
table: lib/table.mq.md
---
# main
+2 -1
View File
@@ -20,7 +20,8 @@ Import:
```markdown
---
import llm:ext/ai/llm.mq.md
import:
llm: ext/ai/llm.mq.md
---
```
+71
View File
@@ -0,0 +1,71 @@
# 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 的具体物理工具或新的模板套到每个库。
+1 -1
View File
@@ -88,7 +88,7 @@
## 4. 作者面 API
### 4.1 英文(`ext/quantum/quantum.mq.md`)
### 4.1 英文(`ext/quantum/circuit/index.mq.md`)
在既有 `# circuit` / `# gate` 之外增加(或扩展方法):
+28 -11
View File
@@ -6,6 +6,7 @@
| 日期 | 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 插件实现 |
---
@@ -72,7 +73,7 @@ math 是**高中符号与曲线**;quantum 是**离散希尔伯特空间上的
1. **仅 ABI 插件接入**:`plugins/quantum` → `libquantum.so`;L1 在 `ext/quantum/*.mq.md`。
2. **`ext/quantum/**` 禁止 `host_*`**;经 `plugin.native_path` + `plugin.load`(同 web/agent)。
3. **中英分文件**:`quantum.mq.md` / `量子.mq.md`,**禁止**混排 API([stdlib-i18n.md](stdlib-i18n.md))。
3. **中英分文件**:同一包 `ext/quantum/` 内英文模块树 + `量子/` 中文树,**禁止**混排 API([stdlib-i18n.md](stdlib-i18n.md))。
4. **不改核心语法**;电路表单元格保持字面量;门名/比特下标由类方法解析。
5. **模拟器有硬上限**(默认 ≤ 12 qubits);超限报错,不静默截断。
6. **view 必须有专项展示**(结构卡 + 执行区 SVG),禁止只 dump JSON。
@@ -81,17 +82,31 @@ math 是**高中符号与曲线**;quantum 是**离散希尔伯特空间上的
## 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/
quantum.mq.md # 英文类 API
量子.mq.md # 中文类 API
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:线性代数 / 施门 / 画 SVG
examples/quantum-bell/ # 规范示例(Q3)
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
@@ -101,11 +116,12 @@ marqdo ext add quantum
```markdown
---
import quantum:ext/quantum/quantum.mq.md
import:
quantum: ext/quantum/circuit/index.mq.md
---
```
或中文:`导入 量子:ext/quantum/量子.mq.md`。
或中文:`导入 量子:ext/quantum/量子/电路/索引.mq.md`(根 skill:`ext/quantum/量子/索引.mq.md`)。
---
@@ -151,7 +167,7 @@ $$
## 5. 作者面 API(锁定草图)
### 5.1 英文 `ext/quantum/quantum.mq.md`
### 5.1 英文 `ext/quantum/circuit/index.mq.md`
```markdown
# gate
@@ -198,7 +214,7 @@ $$
门方法返回**更新后的 circuit 句柄**(与 web `compose_*` 相同:`` `qc` = > `qc`.h qubit=0 *``)。
### 5.2 中文 `ext/quantum/量子.mq.md`
### 5.2 中文 `ext/quantum/量子/`(根 `索引.mq.md`)
| 英文 | 中文 |
|------|------|
@@ -341,7 +357,8 @@ Q5 教学噪声 + barrier/measure/append/state — 见 [ext-quantum-q5.md](ext-
```markdown
---
title: Bell state
import quantum:ext/quantum/quantum.mq.md
import:
quantum: ext/quantum/circuit/index.mq.md
---
# Bell |Φ+⟩
+227
View File
@@ -0,0 +1,227 @@
# 扩展库开发范式: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/<id>/
index.mq.md # EN 根 SKILL(先读)
<module>/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 <FILE> <FUNCTION> [k=v…]
[--json]
[--effects none|plugin] # 默认 none;ABI 扩展必须 plugin
[--session <id>]
[--toget <name>] # 或尾部 toget <name>
```
| 机制 | 用途 |
|------|------|
| `--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/<id>/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/<id>/` 内放中文子树,勿 `ext/<中文包名>/` 顶层并列 |
| 作者导入 | `import: circuit: ext/quantum/circuit/index.mq.md` → `circuit.circuit` |
| 中文导入 | `导入 量子:ext/quantum/量子/电路/索引.mq.md` → `量子.电路` |
| 智能体 | 打开对应语言的根 skill,工具名与路径保持同语言 |
---
## 9. 安装与源码卫生
```bash
cargo build -p marqdo_plugin_<id> # 若有原生插件
MARQDO_EXT_SOURCE=/path/to/repo/ext \
marqdo ext add <id> # 装到 ~/.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/<id>/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 试点归纳的整包开发范式与验收清单 |
+17 -5
View File
@@ -7,7 +7,7 @@
| 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) · [stdlib-i18n.md](stdlib-i18n.md) · [layers.md](layers.md) |
| 相关 | [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) |
---
@@ -33,13 +33,17 @@
```text
ext/web/
web.mq.md · 网页.mq.md # facade: page route serve render inspect
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
@@ -62,8 +66,9 @@ route: /
method: GET
data_source: posts
data_order: -created_at
import web:ext/web/web.mq.md
import data:ext/data/db.mq.md
import:
web: ext/web/web.mq.md
data: ext/data/db.mq.md
---
# Marqdo
@@ -76,6 +81,7 @@ Welcome to the executable web.
| `type` | `类型` | `web` / `网页` |
| `route` | `路由` | 路径,可含 `{param}` |
| `method` | `方法` | 默认 `GET` |
| `view` | `视图` | 可选 main:启动时执行主程序,返回递归 View 节点;不与自动 data_source 绑定混用 |
| `title` | `标题` | 文档标题 / `<title>` |
| `data_source` | `数据源` | 表名 |
| `data_order` | `排序` | 如 `-created_at` |
@@ -92,6 +98,10 @@ Welcome to the executable web.
| 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。
---
@@ -106,7 +116,8 @@ path: /api/posts
request: json
response: json
auth: member
import data:ext/data/db.mq.md
import:
data: ext/data/db.mq.md
---
**post = > data.db.insert …**
@@ -189,6 +200,7 @@ Middleware 一等:`web.use` / `route.use`,表驱动;**禁止** `configure(
| A6 | 禁止恢复 `compose_*` / `app.configure` / god page 变异堆 |
| A7 | 能力只许迁移/提升;删除须本设计明示 + tests 同步 |
| A8 | 设计未锁定处停工提问,禁止自行发明 DSL |
| A9 | **文件划分布局**:页面拆到简单组件文件为止;默认禁止整页 HTML/CSS 注入(`dom.raw`/`page.css` 仅逃逸舱) |
---
+2 -1
View File
@@ -49,7 +49,8 @@
英文:
```markdown
import web:ext/web/web.mq.md
import:
web: ext/web/web.mq.md
# main
+25 -27
View File
@@ -7,13 +7,15 @@
| 相关 | [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) |
| 验收应用 | 工作区 `anlian`(暗恋见君):用 Marqdo 前后端脚本完整重写;**PostgreSQL + Redis 外接** |
| 当前验收 | 仓库内独立示例与临时夹具;完整站点、网络站点、浏览器与数据资源分别验证 |
本文件记录 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 官方插件)。
用 **Go** 重写官方网络拓展库原生层(`plugins/web`),在 **C ABI v2 全量兼容** 前提下提供「网页制备」所需的全部服务端能力;`ext/web` 继续用 GFM 表 + `#` 类做作者面;应用的前后端脚本全部用 Marqdo 书写。此举同时验证 **多语言 ABI 插件生态**(首个非 Rust 官方插件)。
**不是**最小 hello 插件;**不是**在旧 Rust 代码上打补丁(对齐 [ext-web.md](ext-web.md) **C5**)。
@@ -36,7 +38,7 @@
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. **暗恋见君可写完**:用 Marqdo 后端脚本 + 浏览器 WASM 前端脚本重写 anlian 核心模块(见 §8);运行时仅依赖 `marqdo` + `libweb` + **外接 PostgreSQL + Redis**(可选 S3/RustFS)。
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 非目标
@@ -56,7 +58,7 @@
```text
┌──────────────────────────────────────────────────────────────────┐
│ 应用(anlian / 任意站点) │
│ 应用(独立业务站点) │
│ · 后端 .mq.md:路由、业务、装配、invoke 处理函数 │
│ · 前端 .mq.md:WASM + lib/browser(作者零业务 JS) │
└────────────────────────────┬─────────────────────────────────────┘
@@ -284,41 +286,36 @@ Where 语义:等值 map、filter 表、OR / IN / BETWEEN、分页 offset/limit
---
## 7. G 增强(完备网页制备 + anlian;兼容之上增量)
## 7. G 增强(完备网页制备;兼容之上增量)
> 以下为 **新增能力**,不替代 §5。作者面用新方法/新 configure 键;旧脚本不受影响。
| ID | 能力 | 动机 | 作者面草案 |
|----|------|------|------------|
| **G-WS1** | **命名房间** WS:`join`/`leave`/`publish`;组名 ASCII(如 `chat.room.{id}`) | anlian 公聊/私聊 | `app.route_ws` 增 `mode=room` + `room_key`;或 `ws.room_*` ABI |
| **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) | anlian `apikeys` | `web_api_key_check` + `# auth` 或独立小类;**业务 scopes 仍在 .mq.md** |
| **G-MAIL0** | (可选后续)SMTP 发送原语 | 邮箱验证码 | 不阻塞首版对等;列入 anlian 二期 |
| **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. 暗恋见君验收矩阵(检测「能不能写完」)
## 8. 独立工作流与隔离验收
外部依赖(允许):**PostgreSQL**、**Redis**;可选对象存储。
仓库交付不依赖某个外部业务工程的源码或个人数据库。各能力保留在原生实现与领域资源中,通过维护中的独立示例验证;移出业务工程不构成删除通用功能的理由。
| 模块 | Marqdo 后端 | Marqdo 前端 | 插件依赖 | 验收 |
|------|-------------|-------------|----------|------|
| 站点壳 / 首页 | `# page` + db | 局部刷新可选 WASM | listen、static、cache | 首页可开 |
| posts 帖子/评论/板块 | route + form + db | 发帖表单 WASM 可选 | CRUD、CSRF、upload | CRUD+列表详情 |
| news | 同上 | 同上 | 同上 | 列表详情 |
| accounts | auth + session +(二期 mail) | 登录表单 | argon2、session、gate | 注册登录 |
| profiles | db + storage | 头像上传 | storage/upload | 资料页 |
| search | db.search 或 PG 查询 + cache | — | db/cache | 关键词搜索 |
| chat | route_ws + G-WS1/2 + db | WS 客户端脚本 | Redis + WS rooms | 公聊+私聊实时 |
| apikeys | G-API1 + db | 管理页 | — | Bearer 调 API |
| webmaster | sitemap/robots | — | 已有 ABI | `/sitemap.xml` |
| topics | `app.static` → bundles | 既有静态交互 | static | 专题可访问 |
| 工作流 | 当前来源 | 实际核对 |
|---|---|---|
| 完整动态站点 | 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 内部测试 | 独立夹具下验证数据库、会话、运输、资源及渲染边界 |
**「写完」定义**:上述模块在 Marqdo 仓库或 `anlian` 旁路目录有可运行 `.mq.md` 站点;gold/手工脚本能走通主路径;不依赖 Django/Channels/Daphne/gunicorn。
开发与验收由 skills/marqdo-dev/index.mq.md 编排,使用 marqdo call。完整示例的浏览器用例和 HTTP 用例不能替代 Postgres、Redis、OIDC 或外部服务的真实环境证据;未运行的边界仍需明确保留为未验证。
---
@@ -347,7 +344,8 @@ plugins/web/ # Go module(替换原 Rust crate)
scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
```
原 Rust 源码:`plugins/web-rust-archive/`(**已移出 Cargo workspace**;参考用,默认不构建)。
原 Rust 源码:曾置于 `plugins/web-rust-archive/`(已移出 Cargo workspace,参考用);
该目录已于 v1.6 精简时从工作树移除,历史保留在 git 中。
### 9.2 产物与解析
@@ -399,7 +397,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
| **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** | anlian Marqdo 重写主路径(可分仓或 `examples/anlian-mq/`) | ✅ `examples/anlian-mq/`(本地 SQLite + 粉玻璃主题 + 主路由/登录/片段;外接 PG/Redis 仍为增强路径) |
| **W-G14** | 历史业务站点主路径演示 | 历史演示工程已移出仓库;当前独立验收见 §8 |
每波次:**先补 Go 实现 → 跑对应 gold → 再进入下一波**。禁止跨波次留下「注册了但返回 stub 错误」的 ABI(除 W-G0 明确的未实现探测)。
@@ -413,7 +411,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
| 金样例 | 现有 `tests/ext/web-*.mq.md`;构建脚本产出 `libweb.so` 后跑 |
| Live | 现有 `*-live-server.mq.md` + curl |
| 回归门禁 | CI:安装 Go → `scripts/build-web-plugin.sh` → `cargo test` 相关 web 项 |
| anlian | 独立 smoke:登录、发帖、WS 发言、API key |
| 独立站点 | 登录、表单、WebSocket 与 API 使用可控夹具分别验收 |
---
@@ -449,6 +447,6 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
1. **全量重写** `plugins/web` 为 Go,**不是**最小闭环。
2. **既有网络拓展能力(§5)重写后必须仍可用**;作者面默认兼容。
3. **PostgreSQL / Redis 外接** 为一等公民;Marqdo 承担应用前后端脚本。
4. **暗恋见君** 为完备性验收,不是缩小插件范围的借口。
4. 完备性通过独立工作流和原生测试验证,不以外部业务工程缩小插件能力范围。
5. **多语言 ABI 生态** 以本插件为样板(G7)。
6. 开发严格按 **§10 波次** 推进;本文件为唯一施工图。
+71
View File
@@ -0,0 +1,71 @@
# 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 执行。
+65
View File
@@ -0,0 +1,65 @@
# 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)。
+16 -14
View File
@@ -128,13 +128,14 @@ myapp/
---
title: web-site
description: Home = page table; main may be inline; class methods assemble.
import web:ext/web/web.mq.md
import shell:styles/shell.mq.md
import nav:components/nav.mq.md
import side:components/side.mq.md
import foot:components/foot.mq.md
import articles:db/articles.mq.md
import db:db/index.mq.md
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
@@ -171,13 +172,14 @@ Main content is not a reusable component, so it is authored here.
```markdown
---
title: 站点
导入 网页:ext/web/网页.mq.md
import shell:styles/shell.mq.md
import nav:components/nav.mq.md
import side:components/side.mq.md
import foot:components/foot.mq.md
import articles:db/articles.mq.md
import db:db/index.mq.md
导入:
网页: 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
+453
View File
@@ -0,0 +1,453 @@
# 外联内核(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 外联。
@@ -0,0 +1,24 @@
# 外联库论文的研究方向
作者于 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/`。
@@ -0,0 +1,44 @@
# 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.
+654
View File
@@ -0,0 +1,654 @@
# 外联运行时 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 变成第二套解释器;
- 不把“未实现”伪装成支持。
@@ -0,0 +1,336 @@
# 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.
+306
View File
@@ -0,0 +1,306 @@
# 语法设计哲学:函数在「代码即文档」里为何水土不服,以及用什么语义取代
> **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 个函数**——
看有多少在"命名表达式"框架下会更自然、多少必须保留"过程"语义?
+337
View File
@@ -0,0 +1,337 @@
# 语义探析:代码函数能否解释为一张 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. 若你仍想推进「表即签名」,我可以做一次**限定实验**:
要求显式标记(如 `| 签名 | 参数 | 类型 |`)+ 与体推断不一致即报错,
在小范围金样里验证是否可控。要我做吗?
@@ -0,0 +1,471 @@
# 方案评估:函数能否作为变量的一种(函数即表)
> **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 需要回调)
若有真实用例,评估会完全不同——请给我场景,我按场景重新评估。
Loaded 100 of 1489 files, more files were not shown because too many files have changed in this diff. Show more