Compare commits

...
Author SHA1 Message Date
cflmy 328cc5c61b fix(impact): load the impact report before assembling the evidence record
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline is running
The candidate evidence heredoc referenced the report without reading it after the
rebase; define the report from <work>/impact.json (or None when no accepted ref
was available) before building the record.
2026-11-27 02:05:33 +08:00
cflmy 520931ca34 feat(impact): recursive candidate impact analysis over the union graph
Implement the ECO-02 impact contract: compare the recursively expanded
(global_id, parent, remote, SHA, state) identities of an accepted root commit
and a candidate, expand domain gitlink changes to child identities, close over
the reverse requires graph built from the union of both revisions, add parent
domains, then reach a fixed point over checks_with. An unexpandable domain is
reported UNVERIFIED and widens the affected set to the full candidate instead of
skipping (--fail-on-unverified makes it fatal).

integration.sh runs it against the accepted root ref (PR target branch or
origin/main) and records changed/affected/checks_with/fallback in the candidate
evidence JSON. Five contract tests build real temporary Git repositories,
including a domain gitlink change and the conservative fallback.

Refs cflmy/marqdo#7
2026-11-27 02:05:22 +08:00
cflmy f17e23aeec docs: record the promoted stdlib migration combination and M4 cold install
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
The root candidate is promoted: main pins CLI Phase B (no in-repo stdlib
sources) and the six migrated stdlib components; the root CI candidate passed
with one derived CLI/Worker/Bundle artifact and all consumers. Record the
promotion, the required check pipeline, the release-level offline cold install
result, the archive identity caveat (example binaries built locally differ from
the CI archive) and the remaining non-blocking follow-ups.

Also fix the integration evidence JSON: root_commit must name the root
candidate commit, with cli_source_sha separate.

Refs cflmy/marqdo#9
2026-11-27 01:51:06 +08:00
cflmy f4e292e7b0 fix(integration): scope the CLI target directory to the CLI build
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was canceled
The exported CARGO_TARGET_DIR leaked into the consumer repositories, so View's
package script built into the CLI target directory and then failed to find its
own release binary. Only the pinned CLI build names that target directory.
2026-11-27 01:40:57 +08:00
cflmy e7324edc0f candidate: pin the merged CLI Phase B commit
ci/woodpecker/push/eco Pipeline is pending
ci/woodpecker/pr/eco Pipeline failed
CLI PR #17 was fast-forward merged; the root candidate now pins the accepted
CLI Phase B commit (the earlier candidate commit plus the CI-only contract-lane
and Bundle-materialization fixes). Evidence updated with the merged identity.

Refs cflmy/marqdo#9, cflmy/marqdo-cli#11
2026-11-27 01:32:53 +08:00
cflmy c190ffb184 fix(integration): build the pinned CLI into its own target directory
ci/woodpecker/push/eco Pipeline failed
ci/woodpecker/pr/eco Pipeline was canceled
The release packager resolves both binaries from the CLI checkout's target
directory, so the candidate build must happen there; the previous external
CARGO_TARGET_DIR left the package step with no release binary. Keeps one build
and one artifact identity.
2026-11-27 01:22:13 +08:00
cflmy 380d4f95a3 candidate: pin CLI Phase B and derive every artifact from the root candidate
ci/woodpecker/push/eco Pipeline failed
ci/woodpecker/pr/eco Pipeline failed
M3 candidate for cflmy/marqdo#9: the root cli gitlink now points at the CLI
Phase B commit that removed the in-repo stdlib sources and pinned the accepted
ecosystem Bundle.

scripts/integration.sh no longer takes a CLI artifact from View's frozen RC.4
script. One candidate derives every input: the root-owned Bundle producer
assembles the Bundle from pinned gitlinks, the CLI and Worker are built from the
pinned cli commit, the release archive is packaged with --stdlib-dir, and
Conformance/View/Knowledge/Prove/Lint plus acceptance-stdlib all use that same
installed binary and adjacent Bundle. Evidence records the exact identities.

Composition gains the print-format equivalence fixture (moved from the CLI) and
a pure-mode Table case; the root acceptance compares stdout line pairs so the
official print/打印 aliases must produce identical formatting.

Refs cflmy/marqdo#9, cflmy/marqdo-cli#11
2026-11-27 01:07:31 +08:00
cflmy 48189243f7 fix(acceptance): pass the explicit negative-gate environment
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
The fail-closed gates must run with MARQDO_STDLIB_DIR explicitly pointed at a
missing or tampered Bundle; inheriting the caller environment let a CLI with an
adjacent valid Bundle fall back and made the missing-bundle negative pass.
Reproduced with an installed CLI that has stdlib/ next to the binary.

Refs cflmy/marqdo#9
2026-11-27 00:26:57 +08:00
cflmy 4fade3e981 candidate: pin the explicit-package extensions and gate their consumption
ci/woodpecker/push/eco Pipeline was canceled
ci/woodpecker/pr/eco Pipeline failed
Pin ext-http/ext-regex/ext-archive at the merged explicit-Package candidates
(they stay planned, never join the default Bundle) and extend the root
acceptance gate to run any extension checkout that publishes the current
package layout (marqdo.yaml + index.mq.md + scripts/test.sh). Record the actual
package-entry decision in the ledger and evidence: the three domain modules are
consumed through the public @alias import after marqdo lock, with the original
domain tests and baseline terminal values preserved.

Refs cflmy/marqdo#9
2026-11-27 00:10:11 +08:00
cflmy 0c7430ede0 docs: record the stdlib M2 candidate identity, gates and unverified scope
Evidence for the pinned six-component candidate: two byte-identical Bundle
builds (0.2.0, tree digest sha256:db9055...), both verified CLI identities,
component entries, cross-repository composition (including byte-equal Table
split), fail-closed negatives, adjacent offline install and deterministic CLI
packaging. The file explicitly keeps the unchanged main combination, the
existing consumer gates, CLI Phase B and the ext migrations as UNVERIFIED.

Refs cflmy/marqdo#9
2026-11-26 23:51:22 +08:00
cflmy 8fa728b302 candidate: pin the six migrated stdlib components and activate their entries
M2 candidate for cflmy/marqdo#9: pin std-text/std-system/std-io/std-fs/
std-data/std-collections at the exact receiving-repo candidate commits,
activate them in the root catalog with their own scripts/test.sh entry, and
extend integration.sh with the root acceptance-stdlib gate.

The previous requires arrays were design inputs, not real dependencies: the
migrated modules import only CLI language/host builtins and same-repository
siblings, so every active stdlib component now requires only cli (the Table
pair also declares the coordinated checks_with). core/encoding/net stay planned
and do not join the Bundle.
2026-11-26 23:47:57 +08:00
cflmy 7475c79cb2 migration: freeze the stdlib relocation ledger and add the unique Bundle producer
ci/woodpecker/pr/eco Pipeline was successful
ci/woodpecker/push/eco Pipeline was successful
M0 of cflmy/marqdo#9: the root ledger now records the verified baseline, the
151 public functions of the 20 pre-migration modules, the frozen Bundle-root
paths, the test/assertion ownership and the decisions that replace the earlier
path-plan (which would have changed public std: imports). Nine receiving-repo
sub-issues are linked.

One producer owns Bundle composition from the exact component gitlinks
(scripts/build-stdlib.py + scripts/stdlib-bundle.json): it publishes only
modules/**/*.mq.md of active stdlib components, rejects symlinks, submodules,
case/NFC collisions, tests/ and unsafe paths, generates the current
stdlib.json digest and requires an explicit version bump when content changes.

scripts/acceptance-stdlib.py is the root composition gate with explicit
--cli/--bundle inputs: it verifies the manifest independently, runs each active
component entry, runs the cross-repository composition fixtures (official
aliases, Table split, default-Bundle smoke), enforces fail-closed negatives and
optionally proves deterministic packaging with the CLI packer.

Contract tests build real temporary Git repositories and cover the gitlink
identity path, determinism, all rejection cases and the explicit version bump.

Refs cflmy/marqdo#9
2026-11-26 23:44:17 +08:00
cflmy 484cb10d66 Merge pull request '将组件占位目录替换为独立仓库的 Git 子模块' (#8) from codex/link-component-repositories into main
ci/woodpecker/push/eco Pipeline was successful
2026-11-26 19:12:51 +08:00
cflmy 8f842a7f08 ci: retry verified package indexes before ecosystem tests
ci/woodpecker/push/eco Pipeline was canceled
ci/woodpecker/pr/eco Pipeline was successful
2026-11-26 19:06:30 +08:00
cflmy 5798999691 fix: mount component directories as real Git submodules
ci/woodpecker/push/eco Pipeline is pending
ci/woodpecker/pr/eco Pipeline failed
2026-11-26 18:55:00 +08:00
cflmy 7aac052149 fix(layout): handle submodule sections whose name differs from path
ci/woodpecker/push/eco Pipeline was successful
The duplicate-settings guard compared the section field dict with a set
and could raise TypeError instead of reporting the real configuration
error. Compare sets and add a fixture accepting a section name that
differs from its path.
2026-11-26 17:28:13 +08:00
cflmy f08ec00dec feat(layout): validate domain aggregates and recursive governance
ci/woodpecker/push/eco Pipeline failed
Implement the G01/G02 governance checks of ADR 0001 section 4:

- accept the single `kind = "domain"` role (release none/base, empty
  requires, root-level extensions/<id> or stdlib path) while keeping the
  existing root-layer rules for direct components;
- with `--checkouts`, expand every active domain at its pinned gitlink,
  read that commit's own components.toml/.gitmodules, validate its
  gitlinks, remotes, HEAD/dirty state and entries, and refuse a third
  gitlink level or implementation files in aggregate layers;
- flatten the recursive tree into one in-memory global graph: unique
  ids/remotes, active-never-depends-on-planned, requires DAG acyclic,
  checks_with cycles allowed, stdlib/core/tool dependency boundaries and
  requires never targeting a domain;
- structured failures name the responsible label/path and never skip
  unverified layers silently. Existing six-component tree passes both
  modes; 44 integration tests cover positive and negative nested Git
  fixtures without network access.
2026-11-26 17:18:30 +08:00
cflmy 198b3acc86 docs: adopt hierarchical ecosystem governance and Web domain contract
Replace the flat, one-level submodule policy with the bounded tree
root -> domain aggregate -> component (at most two gitlink levels) and
introduce the single `kind = "domain"` governance role.

- Merge the approved architecture rules into ARCHITECTURE, DEVELOPMENT,
  MIGRATION, REPOSITORY-TASKS, AGENTS and components.toml; keep the full
  implementation spec as ADR 0001 (historical input, not a second
  current authority).
- Register `web` as a planned domain at extensions/web; child records
  live in marqdo-ext-web's own components.toml, never duplicated in the
  root catalog. No placeholder gitlink or fake active entry is created.
- Point the Web domain at the single authoritative contract
  marqdo-ext-web docs/WEB-DESIGN.md; Design and Preview stay planned
  until they have real entries and same-candidate evidence.
- Create the marqdo-ext-web, marqdo-web-design and marqdo-web-preview
  repositories (docs/contracts/issues only) and update the migration
  ledger, task list, extension index and issue/PR templates.
2026-11-26 17:18:14 +08:00
cflmy c5415d5bc5 Merge pull request '补齐 Marqdo 项目说明和独立仓库目录' (#5) from codex/readme-component-directory into main
ci/woodpecker/push/eco Pipeline was successful
2026-11-26 15:10:10 +08:00
cflmy 8c1ec4c91e docs: explain Marqdo and index independent component repositories
ci/woodpecker/push/eco Pipeline was canceled
ci/woodpecker/pr/eco Pipeline was successful
2026-11-26 14:54:11 +08:00
cflmy 451000e9ad Merge pull request '记录独立官网与 VS Code 仓库及维护边界' (#4) from codex/consumer-repositories into main
ci/woodpecker/push/eco Pipeline was successful
2026-11-26 14:08:33 +08:00
cflmy b4395416fd docs: route website and VS Code work to independent repositories
ci/woodpecker/push/eco Pipeline is pending
ci/woodpecker/pr/eco Pipeline was successful
2026-11-26 13:55:59 +08:00
cflmy cbbd819370 Merge pull request '重构 Marqdo 为生态集成主仓库' (#1) from codex/ecosystem-restructure into main
ci/woodpecker/push/eco Pipeline was canceled
2026-11-26 13:46:20 +08:00
cflmy ad52612355 ci: use existing runner images for ecosystem checks
ci/woodpecker/push/eco Pipeline was successful
ci/woodpecker/pr/eco Pipeline was successful
2026-11-26 13:29:02 +08:00
cflmy 024d803494 test: verify installed View execution and document migration work
ci/woodpecker/pr/eco Pipeline was canceled
ci/woodpecker/push/eco Pipeline was canceled
2026-11-26 13:25:35 +08:00
cflmy 4c5c102593 refactor: convert Marqdo into the ecosystem integration repository
ci/woodpecker/pr/eco Pipeline was canceled
ci/woodpecker/push/eco Pipeline was canceled
2026-11-26 13:19:26 +08:00
cflmy 1c55baabd5 docs: point new development at the split marqdo-cli repository
executable-knowledge / gate (push) Canceled after 0s
Marqdo functionality is developed across multiple repositories because the
language runtime/CLI, public protocols and independent tools have separate
architectures and version axes. This repository remains the historical v2 line;
the README now names cflmy/marqdo-cli as the current implementation, release
and developer entry point, states that the v2 syntax/package/plugin ABI is not
compatible with it (no legacy execution path), and links the independent
extension conformance repository.
2026-11-22 02:56:21 +08:00
cflmy ffe06d7afa release(2.9.1): keep knowledge in the core compiler
sema::ir always emits proof-index.json and proof-obligations.json through
knowledge, so gating that module on the cli feature broke library consumers
built with --no-default-features (E0433). knowledge is now part of the core
compiler; the CLI binary keeps required-features = ["cli"].

Add a feature-matrix CI gate for the no-feature, cli-only and default
configurations, retire the completed one-time v2.9.0 promotion workflow, and
record the reviewed bilingual 2.9.1 notes and version metadata.
2026-11-18 18:48:47 +08:00
cflmy 180a111799 feat: Marqdo v2.9.0 Verified Knowledge Compiler (full release candidate)
Unified source-verified contracts, accurate evidence grades and independently replayable Lean certificates; version sync, bilingual notes and guarded full release CI. Preserve native AI extension updates from main.
2026-11-18 17:12:07 +08:00
cflmy a3948dbe0d ci: remove temporary extension validation trigger 2026-11-18 14:53:54 +08:00
cflmy 24959a0ba8 fix: validate Windows extension packs with 7-Zip 2026-11-18 14:40:07 +08:00
cflmyandCursor afbb9f191c ci: retrigger EK for ext-v2.8.1 release gate
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:41:29 +08:00
cflmy 8db699191e release(ext-2.8.1): AI durable workflow pack with Windows packaging fixes 2026-11-18 13:37:02 +08:00
cflmy e5580d9640 release(ext-2.8.3): use Windows System32 tar for pack ZIP encoding 2026-11-18 13:25:09 +08:00
cflmy 9ce2ae1037 release(ext-2.8.2): fix Windows packs.ci root and ship AI durable workflow 2026-11-18 13:08:59 +08:00
cflmy 166b01c86b release(ext-2.8.1): AI native durable workflow pack notes and VERSION 2026-11-18 12:41:57 +08:00
cflmyandCursor 87cfe05095 docs(next): add 014 knowledge-anchor compilation direction
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 12:40:41 +08:00
cflmy b37387e6da Merge native AI flow workflow into main
Integrate the v2.8.0-based native agent workflow branch:
- durable open/next/inspect/list/commit/cancel step state with resume_dir isolation
- verified small-model choices, scoped context and bounded parallel recovery
- failed-only read-only retry through the Agent ABI plugin
- offline interpreter fixtures, contract checks and focused CI gates
2026-11-18 12:33:54 +08:00
cflmy 895752a1fd Merge v2.8.0 into native AI flow branch
- take the 2.8.0 crate versions, Cargo.lock dependency graph and release workflows
- keep the native workflow inspect/list, resume_dir isolation and repeatable fixtures
- satisfy the 2.8.0 library narrative gate for workflow.tick
- resolve CHANGELOG ordering with the v2.8.0 release entry
2026-11-18 12:14:03 +08:00
cflmy 38c07d9a0e feat(agent): add workflow inspection and durable isolation
- add agent_workflow_inspect/list primitives and ext/ai wrappers
- expose host-relative resume_dir on every workflow operation
- make offline workflow fixture repeatable with a timestamped run id
- fix flow.choose branch scoping contract diagnostic
- build the agent cdylib and drop the removed run --effects flag in CI
2026-11-18 11:57:12 +08:00
cflmy a7a5554c0f ci(proof): elan 钉 v4.35.0——lean-action 已移除 lean4-version,安装改走 elan-init
proof job 在 2.8.0 HEAD 因 Unexpected input lean4-version 立刻失败;
判定流水线只需 lean 二进制(底座内嵌),与 skill-proof/lean-toolchain 对齐。
2026-11-18 10:57:28 +08:00
cflmy 343504c7a8 release(2.8.0): local.bump — wasm 包版本与 debian/changelog 2.8.0 stanza,Cargo check 更新锁文件
按发版手册 cli 模式:两个 Cargo 包版本一致(marqdo/marqdo-wasm 2.8.0),
ext/VERSION 保持 2.7.0 不动;PPA stanza 保留原维护者、Asia/Shanghai 时间。
2026-11-18 10:29:26 +08:00
cflmy 3d9fa0da96 docs(public): 新增 23-prove 特性页——页面自身定理表经 Lean 全 proved
- 英文特性页(public/features/23-prove.mq.md):六段管线/状态阶梯/
  反例见证/单调性护栏/可证片段边界,示例即页面内的台账.记一笔;
- import result 模块使 result.ok 内联(轨迹语义与定理匹配:大额必经复核
  + 大额单次外呼 + 必有回执);
- 实测 marqdo prove 23-prove.mq.md → status proved,3 定理全部
  decided_by=lean;公开文档重建后 23-prove 页面入站。
2026-11-18 10:29:26 +08:00
cflmy bb8960c5eb fix(env): 重放测试可移植 shebang + dev-env 工具箱目录——全量 1105 测试零失败
- notebook_api.rs:replay 包装脚本 shebang /usr/bin/python3 →
  /usr/bin/env python3(本机 /usr/bin 只读无 python3,CI 与工具链均兼容);
- scripts/dev-env.sh:PATH 预置 target/toolchain/bin(本机 zip shim
  所在,gitignored;CI 用真实 zip),修复 release_handbook packs
  边界 cannot start zip 环境缺口;
- 全量 cargo test:1105 通过 / 0 失败(此前 2 个记录在案的环境基线
  失败——replay python 包装与 packs zip——均已消除)。
2026-11-18 10:29:26 +08:00
cflmy 9331af78e2 release(2.8.0): 合入 CHANGELOG/README/发版说明/skills prove 任务;CI 链接指向 doc/releases
- CHANGELOG.md:v2.8.0 条目(中英双语);
- README.md:版本行 2.7.1→2.8.0 + 愿景第 6 条(知识可证明);
- doc/releases/v2.8.0.md:双语发版说明(亮点/用法/已知限制);
- skills/marqdo-dev/index.mq.md:新增 prove 任务(路径/目录模式/
  require_lean/json;参数用 + 行声明升参,check 与 narrative-ratio 通过);
- 设计文档 §12.5 标记已合入;发版链接统一指向 doc/releases/v2.8.0.md。
2026-11-18 10:29:26 +08:00
cflmy 73bf574a55 ci: proof.yml Full sweep 接真任务——40 夹具单调性 + T4 一致性 + 分歧注入红线
- corpus monotonicity(offline_checked ⊆ lean_proved)与 T4 差分一致性
  进 CI(MARQDO_PROOF_REQUIRE_LEAN=1);
- Full sweep 改为分歧注入红线:--fault-inject offline-claim 必须触发
  error[proof.divergence] 且退 1,护栏失灵(静默落绿)即 CI 失败;
  本地实测 exit=1 + proof.divergence 诊断。
2026-11-18 10:28:18 +08:00
cflmy 4fae71342d prove: P3 — --all 目录模式、T4 差分一致性、库语义对齐、2.8.0 收口
- main.rs:prove --all/--max-files(递归收集,目录不带 --all 拒绝;
  聚合 JSON kind=prove-all,整体状态差者胜);--fault-inject offline-claim
  (调试分歧注入,A3 护栏验证入口)
- tests/conformance.rs:T4 差分一致性——5 例纯函数语料(算术/中文标识符/
  分支比较/字符串拼接/i64 边界)解释器求值 == Lean example(simp+try rfl);
  B4 result.ok 结构字段 access 两侧一致
- MarqdoProof.lean:mqAdd 补文本拼接与 num 混合(与解释器 eval_binary(Add)
  对齐——T4 实测抓出的真分歧);mqDisplay 显示串(标量精确,容器一层,
  有意简化并记录)
- 文档:design §12 P3 落地 + §12.4 延期理由(foreach/assume-guarantee/T3
  → 2.9)+ §12.5 权限受限待合入清单;roadmap 状态 → 已实施;
  教程 §13.8 prove 章节;skills/marqdo/reference.md 定理表;
  doc/verification/skill-proof-theory.md(库形式化说明);
  doc/roadmap/prove-release-2.8.0.md(双语发版说明 + CHANGELOG/README/
  skills/marqdo-dev prove 任务待合入原文)
- Cargo.toml/Cargo.lock:2.7.1 → 2.8.0

实测:全量 516 通过(仅 2 个已记录环境基线失败);prove 23 + prove_lean 10
+ corpus 40 夹具 + conformance 6 例全绿;biz 定理 proved、假定理反例、
--all 聚合与护栏目录模式同样生效。
2026-11-18 10:28:18 +08:00
cflmy 63d60e3ba1 prove: P2 — 离线符号执行(F1–F5)+ 单调性护栏 + 语料库
- offline.rs:SymVal 符号执行(Const/Struct/OpResult/Param/Unknown);
  If 分支克隆状态并接续后续语句(修复 Return-in-outer 编排丢结果);
  可行性检查(前提∩路径条件为空 → 空真关闭,Lean 假设矛盾同构);
  F2 轨迹包含/长度、F3 构造器结构求值、F4 自由原子二分、
  F5 区间:字面重述关闭 + 区间违反反例(区间端点见证,如 金额 = 10001);
  区间蕴含保守 unverified(当前 Lean 脚本无 Val 传递引理,先于 Lean
  关闭即触发 divergence——诚实优先)
- 判定编排:离线先行(毫秒级 checked ≠ proved)→ Lean 复核升级 proved;
  分歧护栏:checked 但 Lean 关不掉 / 反例被 Lean 证出 ⇒
  error[proof.divergence] 退 1 永不落绿;MARQDO_PROOF_INJECT_DIVERGENCE 验证
- emit:try split 按 if 嵌套深度重复(三路分支可达);simp 清单补
  mqResultError/mqValueOr/mqAnd/mqOr/mqNot(分歧护栏暴露)
- tests/prove_corpus.rs:8 类 × 5 = 40 夹具语料库,
  offline_checked ⊆ lean_proved 强制 + 无 Lean 禁 proved;
  f5_interval_closure_scope 单测锁定 F5 诚实范围
- 设计文档 §12 记录 P2 落地、修复与文法限制

实测:biz 3 定理离线 checked→Lean proved;假定理反例 金额 = 10001
指回定理表行;注入分歧 → error/divergence 退 1;全量 516 通过
(仅剩 2 个已记录环境基线失败)。
2026-11-18 10:28:18 +08:00
cflmy 44d2928c06 prove: P1 — Lean 判定接入 CLI(driver + 证书缓存 + CI)
- driver.rs:工具链发现(--lean → MARQDO_PROOF_LEAN → PATH;显式坏路径
  error[proof.lean_missing] 不回退);MarqdoProof 库内嵌进二进制,按内容
  哈希缓存、lean -o 直接构建(运行时零 lake/elan 依赖);lean 调用带超时
  (--timeout/--heartbeats);unsolved→unproved、error→error、
  sorry→unverified;-- mq: 注释 + 定理头注释 → 证据映射指回源行
- cache.rs:复合键证书(源码⊕plan⊕库sha256⊕lean版本⊕版本),
  命中跳判定(lean.cache: hit),--no-cache/MARQDO_PROOF_NO_CACHE 绕过
- mod.rs:per-claim 判定面(status/decided_by/evidence/source_line)、
  lean JSON 对象、proof.claim_failed 诊断;文件状态只聚合有定理与被拒函数
- main.rs:--lean/--timeout/--no-cache/--heartbeats 旗标;prove emit
  子命令只生成不判定;策略 none → sorry(绝不冒充 proved)
- tests/prove_lean.rs:A1/E1/E4/F2/F3/F4/G1/G2/G2b 矩阵,无工具链 SKIP、
  MARQDO_PROOF_REQUIRE_LEAN=1 硬性要求;实测抓出并修复错误行/列解析、
  逐定理记录缺失、含点函数名归因三处判定缺陷
- CI proof.yml:装 Lean 4.35.0 → 底座校验 → 判定矩阵(CI 不许静默降级)
- 设计文档 §12 记录 P1 落地与偏差(直接 lean -o,不经 lake)

实测:业务样例 3 定理 proved;假定理 unproved 退 1 指回定理表行;
缓存命中后跳判定(假 lean 计数器验证);全量 Rust 测试 508 通过
(仅剩 2 个已记录环境基线失败)。
2026-11-18 10:28:18 +08:00
cflmy fa832268b3 prove: fix issues found in Lean verification round
- p2_len fixture claim corrected: pure function's trace is always empty,
  so '长度(轨迹) = 2' was an authoring mistake -> '长度(轨迹) = 0'
  (Nat-path coverage unchanged); all 7 claim-bearing files now prove
- generated Lean headers set linter.unusedVariables/unusedSimpArgs off:
  machine-emitted artifacts should not trigger human-authoring lints
  (0 warnings now)
- verification driver script + updated results in design doc 12 and
  library README
2026-11-18 10:28:18 +08:00
cflmy 9576188a2e prove: real Lean 4.35.0 verification round
- MarqdoProof semantic base (Val + mq* helpers + branch-contradiction
  lemmas, no axiom/opaque), lake-built; sources under doc/verification/
- emitter: ASCII-only namespaces (uXXXX encoding), guillemet wrapping
  for all non-ASCII identifiers, ':' -> '_' inside op ctor names,
  ctor pattern arg binding, ASCII-safe rename forms, placeholder ctor
  via op_ctor, flipped run equation (outputs on the left), try-split
  for branchless bodies, validated proof script (simp_all + .elim
  contradiction + omega)
- business example: 3/3 theorems proved by real Lean; 5/6 claim
  fixtures proved, p2_len honestly unproved (false claim)
- design doc section 12: Lean round findings + results
2026-11-18 10:28:18 +08:00
cflmy 528a1f0dbc prove: fix 4 review defects (honesty + compilability) + business validation
Code review after the initial prove commit found and fixed:

1. Calls inside table/list literals were silently dropped — a function
   with side-effectful cells lowered to "no ops" and claimed purity in
   Lean. lower_expr's fallback now rejects with proof.unsupported
   (author must bind the call to a variable first).
2. Same-callee call sites with different arities (optional params)
   shared one Op whose ctor declared the first-seen arity, emitting
   uncompilable Lean. register_op now suffixes `/N` per arity.
3. proof.name_shadow fired once per walked function (N functions → N
   duplicates) and checked params of claim-free functions. Predicate
   check runs once per module; param check only for functions that
   carry claims.
4. 长度(轨迹) = 2 emitted mqEq (Nat) (Val) — type-mismatched Lean.
   Nat-context detection renders trace-length comparisons natively;
   untranslatable shapes become comments instead of broken Lean.

Hardening: lean_ident reserves 轨迹₀ / h_前提 (theorem binder
collision); emit_theorems dedups repeated claim ids.

Tests: +4 integration regressions (p2_a..p2_d), 23 prove tests total;
full suite green except the documented env-limited failures (one
host::foreign_session flake passes standalone).

Business validation (doc §12): e-commerce order-approval SKILL with 3
theorems cross-checked against the real interpreter — 5000 → auto
(1-step trace), 20000/60000 → manual ticket T-20000/T-60000
(需人工→创建, exactly 2 steps); corrupted claim tables hit
check --proof codes while staying default-off; double emit
byte-identical.
2026-11-18 10:28:18 +08:00
cflmy a11b347659 prove: add marqdo prove (P0 emit/audit + P1 claim tables & check --proof)
Language layer (ADR 0010):
- claim tables (定理|结论|前提|策略) parsed before first executable
  statement, extracted into Function.claims, removed from body
- check --proof (default off): proof.claim_malformed / claim_ambiguous /
  claim_misplaced / claim_duplicate / claim_unknown_symbol /
  claim_unsupported / name_shadow

Runtime layer (src/prove/):
- ir.rs: Plan IR with stable hand-rolled JSON (schema 1)
- lower.rs: subset acceptance (proof.while / proof.recursion /
  proof.dynamic_call), inlining for straight-line pure callees, opaque
  ops with effect labels, --allow-opaque whole-function downgrade
- types.rs: literal-driven inference + branch confluence
  (proof.type_mismatch, exit 1)
- emit.rs: deterministic Lean emission (Val × List Op, continuation
  style, -- mq: line:col anchors, «…» for dotted idents, theorem
  scaffolds from claims with unfold/split script)
- mod.rs: prove/emit/audit/clean commands, Verdict taxonomy
  (error > unproved > rejected > unverified > checked > proved),
  exit codes 0/1/2 per design §3.3

Tests: tests/prove.rs 19 integration cases (no Lean required) + module
unit tests; full suite stays green except the 3 documented
env-limited failures.

Docs: doc/design/prove-cli.md (§12 records deviations: result.ok/error
vs drafted success/failure, Val-based run at P1, op arity, opaque
effect label), doc/roadmap/prove.md, doc/adr/0010.

Env fixes carried in: scratch dirs in test helpers honor
CARGO_TARGET_DIR (needed on this machine's read-only target/debug).
2026-11-18 10:28:18 +08:00
cflmy 8e437e2cd3 ci(agent): permit native ABI loading in offline Agent integration tests 2026-11-18 10:17:47 +08:00
cflmy 23229a6ac9 ci(agent): permit native ABI loading in offline Agent integration tests 2026-11-18 10:17:44 +08:00
cflmy 58b65215a1 test(agent): show the failed native choice result in interpreter smoke diagnostics 2026-11-18 10:16:43 +08:00
cflmy 92c3f80055 fix(agent): compare branch labels using explicit text conversion 2026-11-18 09:59:27 +08:00
cflmy 8a66f803cb feat(agent): add validated forward-only branching from model choices to registered SKILL steps 2026-11-18 09:59:16 +08:00
cflmy 3ce59a4da8 test(ai): verify JSON-formatted small-model option parsing from Marqdo 2026-11-18 09:57:47 +08:00
cflmy 90688741c5 feat(agent): parse bounded JSON choice envelopes without relaxing skill allowlist 2026-11-18 09:57:37 +08:00
cflmy 70b88b3767 security(agent): require explicit read-only classification before automatic SKILL/parallel dispatch 2026-11-18 09:57:06 +08:00
cflmy f859e6eeea test(ai): include required short model prompt in workflow fixture 2026-11-18 09:56:55 +08:00
cflmy 6705e2e6b7 fix(agent): require explicit local prompt for model workflow steps 2026-11-18 09:56:49 +08:00
cflmy 6e8a62928b test(ai): verify plugin-only tick returns waiting input and commits final step 2026-11-18 09:56:39 +08:00
cflmy 398a0b7222 ci(agent): introduce focused plugin-only native workflow gate separate from long EK suite 2026-11-18 09:56:28 +08:00
cflmy e8f1a3e126 fix(agent): deduplicate equivalent numbered and labeled user replies 2026-11-18 09:56:16 +08:00
cflmy 8ea56cbe30 test(ai): exercise ABI failed-only recovery without executing already successful children 2026-11-18 09:55:42 +08:00
cflmy 8085d06124 feat(ai): expose failed-only read-only child recovery as a short Marqdo workflow 2026-11-18 09:55:30 +08:00
cflmy 6f929dc2da feat(agent): publish safe partial fan-out recovery through Agent ABI 2026-11-18 09:55:19 +08:00
cflmy dd22180269 feat(agent): recover failed read-only children only, preserving successful subtask results 2026-11-18 09:55:11 +08:00
cflmy cc48bf6d05 docs(agent): document plugin-only durable step state engine and safety boundaries 2026-11-18 09:54:45 +08:00
cflmy 19f986953a test(ai): prove successful parallel child outputs survive failed sibling and checkpoint reload 2026-11-18 09:54:21 +08:00
cflmy 770dee5199 fix(agent): prevent EffectLedger atomic temp collisions under parallel operations 2026-11-18 09:54:06 +08:00
cflmy f6612813e3 fix(agent): remove resume test global cwd races and make atomic temp names unique 2026-11-18 09:53:58 +08:00
cflmy 643ea06340 feat(ai): add one-step native workflow driver for model input and bounded child tasks 2026-11-18 09:53:17 +08:00
cflmy 0cd64a7450 fix(agent): persist partial child outcomes and require verified process success before workflow commit 2026-11-18 09:53:02 +08:00
cflmy 981faac022 ci(ai): test native workflow plugin through actual Marqdo interpreter 2026-11-18 09:52:42 +08:00
cflmy f818834ec1 test(ai): exercise ABI-only durable workflow in actual Marqdo interpreter 2026-11-18 09:52:35 +08:00
cflmy 8d47507d15 feat(ai): expose a concise ABI-backed durable workflow library 2026-11-18 09:52:13 +08:00
cflmy 1e1f05c087 feat(agent): register ABI workflow state transitions and cancellation 2026-11-18 09:51:59 +08:00
cflmy 06e61efc51 feat(agent): implement plugin-only durable step workflow with deterministic next/commit/cancel and tests 2026-11-18 09:51:51 +08:00
cflmy 2dfa0b2a5b fix(ai): do not mistake LLM transport errors for choices or trigger format repair 2026-11-18 09:46:24 +08:00
cflmy 629ad8ed39 feat(agent): tolerate short deterministic small-model selection phrases 2026-11-18 09:43:59 +08:00
cflmy ee677478be test(ai): verify file/class/function context composition in Marqdo interpreter 2026-11-18 09:43:30 +08:00
cflmy edbf241d99 feat(ai): compose current user and scoped file/class/function source into a bounded context pack 2026-11-18 09:43:24 +08:00
cflmy add6a7d32c docs(agent): record implemented contracts and precise VM/runtime completion gates 2026-11-18 09:42:07 +08:00
cflmy c64ec99115 feat(ai): expose minimal ask/start/wait on top of native LLM and subtask APIs 2026-11-18 09:41:28 +08:00
cflmy 60a3b84a84 test(ai): exercise durable input and reply from a real Marqdo program 2026-11-18 09:41:08 +08:00
cflmy 02a4f2d20d fix(agent): skip YAML setext lookalikes in document-scope parser 2026-11-18 09:40:50 +08:00
cflmy 88490e3092 ci(ai): execute real native choice and scoped-context Marqdo smoke 2026-11-18 09:40:15 +08:00
cflmy 9031c106a1 test(ai): add offline Marqdo interpreter smoke for native choice and scoped context 2026-11-18 09:40:08 +08:00
cflmy 633436e40f fix(agent): compare owned JSON values with dereferenced optional identity values 2026-11-18 09:39:53 +08:00
cflmy cf73fcf1ef feat(ai): add allowlisted SKILL enter via standard Marqdo subtasks 2026-11-18 09:39:37 +08:00
cflmy e48fd5b0f4 feat(ai): aggregate concurrent child status without losing successful siblings 2026-11-18 09:39:06 +08:00
cflmy b2f97e72c3 build(agent): lock pulldown-cmark dependency for native scoped context 2026-11-18 09:38:58 +08:00
cflmy c7c0f66d1f feat(agent): register typed concurrent task result aggregator 2026-11-18 09:38:33 +08:00
cflmy d5ab9daebb feat(agent): classify parallel child successes, failures and unknown outcomes 2026-11-18 09:38:26 +08:00
cflmy 5795236d1f feat(ai): expose durable step-boundary input/reply in flow SKILL 2026-11-18 09:37:56 +08:00
cflmy e8d6dc92fc feat(agent): register user-input pause/reply gate primitives 2026-11-18 09:37:44 +08:00
cflmy afe31cb2a8 feat(agent): durable user-input gate with idempotent reply, revision and session checks 2026-11-18 09:37:35 +08:00
cflmy 905a67df32 feat(ai): expose native Markdown scope selection to Marqdo authors 2026-11-18 09:37:18 +08:00
cflmy f63b7ef48d feat(agent): register scoped context projection in native plugin 2026-11-18 09:37:02 +08:00
cflmy 393558ca97 feat(agent): register scoped context projection in native plugin 2026-11-18 09:36:59 +08:00
cflmy 0d9bd99fc0 feat(agent): add Markdown heading-scoped bounded file/class/function prompt projection with tests 2026-11-18 09:36:52 +08:00
cflmy a0c779e022 fix(ai): declare function parameters in Marqdo prose syntax 2026-11-18 09:36:31 +08:00
cflmy a82b6fdde1 fix(ai): declare function parameters in Marqdo prose syntax 2026-11-18 09:36:28 +08:00
cflmy 3613ed7c4e fix(ai): declare function parameters in Marqdo prose syntax 2026-11-18 09:36:26 +08:00
cflmy 9564dff777 docs(ai): link the new native flow, context and recovery modules 2026-11-18 09:34:13 +08:00
cflmy f56deffefe test(agent): isolate EffectLedger tests without process-global cwd races 2026-11-18 09:33:28 +08:00
cflmy bdedf3ecd8 ci(ai): include scoped context pack in syntax gates 2026-11-18 09:32:55 +08:00
cflmy b0ee958fcf feat(ai): add explicit small-model file/class/function context pack 2026-11-18 09:32:48 +08:00
cflmy e64f6b23b4 fix(ai): use valid Marqdo branch expressions and literal main reference 2026-11-18 09:32:04 +08:00
cflmy eed4f05ea4 ci(agent): test native parser and check the new Marqdo flow modules 2026-11-18 09:31:14 +08:00
cflmy d88ed274ed feat(ai): expose short checkpoint and bounded recovery functions 2026-11-18 09:30:49 +08:00
cflmy 7fdd97f675 feat(agent): classify invalid model output and bound local recovery 2026-11-18 09:30:33 +08:00
cflmy c299efe589 feat(ai): add thin model-choice and parallel-document flow library 2026-11-18 09:30:22 +08:00
cflmy b3867c46db feat(agent): register native choice parser in plugin ABI 2026-11-18 09:30:10 +08:00
cflmy 1a39a53d93 feat(agent): add fail-closed small-model choice parser and tests 2026-11-18 09:30:03 +08:00
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
cflmyandCursor 1e61dca9d8 release: Marqdo 1.4.6
CLI and wasm only. Bare self-increment now promotes a required parameter, matching design §8.2. Extension pack stays 1.4.5.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 23:58:09 +08:00
cflmyandCursor ba675a4767 fix(parse): promote a bare self-increment to a required parameter.
Design §8.2 treats the first bold assignment as a declaration, but merging only walked backtick mentions, so n = n + 1 never entered the signature.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 23:55:30 +08:00
cflmyandCursor bfd468d5e3 release: Marqdo 1.4.5
Streamable HTTP MCP, web invoke Bearer/401, openai/agent json.get hardening.
Bump CLI/Ext/wasm and debian changelog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:36:07 +08:00
cflmyandCursor 8353ba38fe Add Streamable HTTP MCP and harden web /v1 invoke auth.
agent_mcp_serve gains http transport; invoke injects Bearer/X-Api-Key and maps
unauthorized to 401; openai/agent field access prefers json.get over footnotes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 17:33:24 +08:00
cflmyandCursor b43a08b2e2 release: Marqdo 1.4.4
Soft LLM transport errors and table-first ext/ai; CLI + Ext + wasm SemVer bump.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 14:38:16 +08:00
cflmyandCursor 1908bf1a53 fix(ai): soft LLM transport errors and strip ext/ai json glue
Host/plugin HTTP failures return structured finish|status=error instead of
aborting the VM; agent/llm/openai/智能体 result maps use GFM tables and
table.put. SKILL gains positive copy-paste examples so agents stop mirroring
legacy json.set chains.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 14:27:45 +08:00
cflmyandCursor c44ea38ae2 release: Ext pack 1.4.3 — agent.run cold EFI / resolve llm_free
Bump ext/VERSION only (CLI stays 1.4.2). Ships agent facade + native miss-field fix for qdagent cold OKF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:56:40 +08:00
cflmyandCursor d489f7c088 fix(ext/ai): cold agent.run EFI — self.preflight and resolve llm_free
Miss resolve omitted llm_free and run called bare preflight, which crashed
qdagent on empty OKF. Align miss fields, use self.preflight + json.get, add
regression gold and research note.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:54:00 +08:00
cflmyandCursor a993cfd76a chore: sync Cargo.lock package versions to 1.4.2
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 12:21:23 +08:00
cflmyandCursor d5f826a8c8 release: Marqdo 1.4.2
Bump CLI/wasm/ext to 1.4.2 for Agent/LLM optimize O1–O5 (sandbox trial,
promote proof, step_route/EFI, lint, quarantine).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:51:41 +08:00
cflmyandCursor 0f72173d08 feat(ext/ai): land Agent/LLM optimize waves O1–O5
Wire opt-in sandbox trial into agent, require sandbox proof before OKF
promote, add step_route/EFI/cost surfaces, style lint + quarantine, and
offline policy optimize script—keeping GFM tables over json glue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:47:28 +08:00
cflmyandCursor a707758d47 docs: research and plan Agent/LLM optimization with OKF and sandbox
Capture the 2026-10 landscape (skills, Skill Lift, routing, GEPA) against Marqdo’s code-as-docs assets and list feasible optimize directions without editing doc/next.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:13:48 +08:00
cflmyandCursor 63bcb882a6 feat(ext/ai): add CoW sandbox for Marqdo-only agent trials
Give agents a capability-capped run path that stages workspace edits until commit, so generated .mq.md can be verified without polluting the real tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-16 11:11:54 +08:00
cflmyandCursor 1bb16dd6db release: Marqdo 1.4.1
View annot leaders mid-to-mid SVG, frame chip id unify; bump CLI/wasm/ext.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 20:37:24 +08:00
cflmyandCursor 58ec2172d6 fix(view): mid-to-mid annot leaders and prose chip density
Unify frame chip ids with marks, reorder chips under anchors, and draw
SVG leaders from underline mid-bottom to chip mid-top so crowded bands
stay readable.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 20:36:12 +08:00
cflmyandCursor 66926e9e0a release: Marqdo 1.4.0
Prose-unified control flow, formula meta bind, image writeback, view
inferred params; sync CLI/wasm/ext/VERSION and install docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:54:45 +08:00
cflmyandCursor dcf4c05663 fix(ext/net): wrap url.encode via lib/net, not host_*
Gold rule bans host_* from ext/**; encode must go through stdlib.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:47:07 +08:00
cflmyandCursor f47a1e143a feat(writeback): image form ![marqdo-out](…) with view parity
Auto-persist image paths/URLs as Markdown images (validated extension);
keep HTML comment for text. View and static export share styled source
markers and output-card <img> rendering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:45:52 +08:00
cflmyandCursor 9cf98a98b5 feat: block formula meta bind and control-flow prose
Support $$ % marqdo: var= binding, arm/loop narrative (fix comment-paragraph
swallow of branch arms), foreach ZH/EN sugar, and condition-line narrative.
Welcome pages and gold samples updated; view skips meta formula fence bodies.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 15:28:46 +08:00
cflmyandCursor f99d552d87 feat(view): show inferred param values; migrate welcome to v0.3 prose
Param chips carry call-frame values (and refresh with the call picker).
Welcome pages and the marqdo skill prefer body-inferred, conversational markup.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:32:50 +08:00
cflmyandCursor 7d49c358c1 fix(view): nested-call welcome + clean formula/code cards
Welcome pages put greet calls in # main so CallFrames/pickers appear;
document surface skips fence body lines and Bind chips under formula/code cards.
Adds view-static-interactive design and entry-vs-method regression tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 14:13:42 +08:00
cflmyandCursor a32c0cd78f fix(ppa): skip cp when local orig already sits in build-area
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:42:37 +08:00
cflmyandCursor 0a8f76d9b4 release: v1.3.3 — view document-surface Structure
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:18:51 +08:00
cflmyandCursor 4e2419b598 feat(view): document-surface Structure with frame-aware annotations
Browse Structure keeps narration and surfaces post-stmt values, branch
arms, and call/loop pickers; static `view output` shares the same render
path so exported HTML matches live view.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-15 13:12:53 +08:00
cflmy f6374d1593 release: ext pack v1.3.2 trailing slash route fix 2026-10-13 15:37:42 +08:00
cflmy 9ede4bc63d fix(web): strip trailing slash so /post/foo/ matches /post/foo
Go ServeMux does exact-match routing; a trailing slash caused dynamic
routes like /post/{slug} to fall through to the 404 catch-all. Add
withStripTrailingSlash middleware as the outermost handler wrapper so
all downstream middleware (RBAC, tenant, mux) see the normalized path.

Tested: static routes, dynamic routes, root path, query-string preservation.
2026-10-13 15:24:26 +08:00
cflmyandCursor 3ae8f2c843 release: ext pack v1.3.1 OIDC path redirect_uri
Bump ext/VERSION only; CLI remains 1.3.0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:42:08 +08:00
cflmyandCursor e9c1a8a730 feat(web): resolve OIDC redirect_uri from request Host
Allow path-style redirect_uri (/oidc/callback) so apex/www and
proxied HTTPS share one config; persist the absolute URI for token exchange.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-08 11:35:12 +08:00
cflmyandCursor 5554b1642c feat(run): add --fs-root / MARQDO_FS_ROOT for subdirectory entries
marqdo run cli/… sandboxes to the entry directory by default; repo-root
sandbox+cwd lets qdagent keep thin CLI wrappers under cli/ without
escaping .marqdo or polluting cli/.marqdo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:17:24 +08:00
cflmyandCursor fe15603a91 fix(llm): hoist ask result fields out of the return table
Table cells shadowed self/column names (model, usage), so [model](self)
and [total_tokens](usage) raised "footnote index needs list or map" and
blocked live agent.step / qdagent BUILD.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:08:48 +08:00
cflmyandCursor 1418742655 Skip docker/data/.cursor when compiling engineering knowledge.
Packaging trees and runtime vaults were inflating EKC with duplicate noise; dogfood agents should index product sources only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 21:50:58 +08:00
cflmyandCursor ed31a2b31d release: v1.3.0 Engineering Knowledge Compiler (EKC)
Bump CLI/ext/wasm to 1.3.0; document L0–L4 catalog, reuse preflight, and
agent eng_* surfaces for AI-native engineering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 16:46:30 +08:00
cflmyandCursor 56ab52356f feat(knowledge): land Engineering Knowledge Compiler (EKC) from 008
Give agents Engineering First Information before codegen: L0–L4 catalog,
reuse/preflight (REUSE→ADAPT→CREATE), graph, and CLI surfaces so large
repos stop reinventing existing capabilities.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 16:44:39 +08:00
cflmyandCursor 2e425c3010 chore: sync Cargo.lock to 1.2.0 for PPA vendor
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:59:48 +08:00
cflmyandCursor 46a0263d7f release: v1.2.0 Web Artifact (ADR 0007) Document/Endpoint/Resource
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:39:25 +08:00
cflmyandCursor ff252fd469 feat(web): land Artifact serve/endpoint path and retire compose golds
Wire data_source into Document render, register Endpoint handlers via
run_artifact, restore marqdo-blog as an Artifact site, and replace old
compose_* web golds with ADR 0007 fixtures and docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:36:45 +08:00
cflmyandCursor 67bac1bf02 feat(web): Document/Endpoint/Resource artifact rewrite (ADR 0007)
Replace the monolithic compose_*/configure author surface with file-level
web|endpoint artifacts, split ext/{web,data,security,net}, and lock
no-degrade rules so the model cannot regress to God-object APIs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 11:06:38 +08:00
cflmyandCursor 33f8b94bb0 release: v1.1.1 AI stack (llm/agent/metadata) + ship plugins/llm
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 20:34:08 +08:00
cflmyandCursor 0ed57b6d54 feat(agent): ext APIs, goldens, and docs for MCP/resume/small-llm routing
Wire mcp_connect/list/call, resume_*, and demote Jev in author docs.
Offline goldens cover MCP client, resume, and small-llm/jev-alias route.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 20:26:55 +08:00
cflmyandCursor c29d48f38c feat(agent): MCP stdio client, resume checkpoints, small-llm router alias
Add agent_mcp_client and agent_resume_* plugin APIs. Treat jev as a
compat alias of small-llm; auto cascade no longer probes MARQDO_JEV.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 20:26:55 +08:00
cflmyandCursor f1e82ce4e5 feat(llm): optional plugins/llm Transport ABI for chat completions
OpenAI transport prefers llm_chat_completions when the native plugin is
resolvable, and falls back to lib/net HTTP/SSE so CI stays green without the .so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 20:26:55 +08:00
cflmyandCursor 2d412e3bba feat(llm): LLMResult.tool_calls from OpenAI-shaped responses
Parse choices[0].message.tool_calls into the ask Result; empty list when
absent. Offline gold covers tool_calls_from.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 20:07:59 +08:00
cflmyandCursor 46d78c6e15 feat(core): Phase 2 Metadata scope lift (no body ${})
Inject bound frontmatter keys into the entry env as ordinary variables.
Reject body ${env…}; bytecode entry prologue seeds the same locals.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 20:05:25 +08:00
cflmyandCursor 81a14f9b38 feat(llm): sys.module_source + entry prompt / meta offline paths
Expose entry source via sys.module_source; ask/stream fall back to
prompt_body of the entry document. Add meta-binding and entry-prompt golds.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 19:52:57 +08:00
cflmyandCursor 88dc6d5a54 feat(core): Artifact Metadata Binding (${env|arg|sys|secret})
Load-time resolve of frontmatter bindings into Module.metadata; Secret
masking; sys.meta / --bind; llm ctor prefers meta over env_get.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 19:51:24 +08:00
cflmyandCursor 4a2d89406b fix(agent): preserve llm_free resources under plan force
Stop plan from clobbering an existing resources workbook with an explore
skeleton. Add llm.prompt helpers and agent-plan-preserve gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 19:34:05 +08:00
cflmyandCursor d8d435fead feat(ai-stack): metrics, named handles, prompt docs, backends, zero-LLM
Finish ai-stack steps 1–5: model_turn usage, fast/reasoning, type:prompt
load, openai/ollama split, and agent-zero-llm gold. Fix compiled-skill
Marqdo syntax so llm_free await no longer falls through to plan+HTTP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 19:30:25 +08:00
cflmyandCursor 1f8e61f3bf feat(llm): semantic ask/stream/collect surface (005)
Lift ext/ai/llm from OpenAI HTTP client to an intelligence primitive;
keep complete as compat. Add unified ai-stack roadmap linking agent + llm.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 13:35:38 +08:00
cflmyandCursor a9ee858f53 feat(agent): Skill Compilation + Adaptive Routing (v2/P4)
Episode → maybe_learn → llm_free skills, plus abstract router backends
(marqdo/small-llm/jev?/llm/auto) via plugins/agent; no core host changes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-24 13:28:50 +08:00
cflmyandCursor 8489d90926 docs(public): 新增 feature 18 —— AI 原生闭环(契约 + MLSP)中英各一篇
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 13:46:03 +08:00
cflmyandCursor 5272acaea0 release: v1.1.0 —— 核心表面守卫 + 渐进式契约 + MLSP for AI
- Cargo.toml / marqdo-wasm / ext/VERSION → 1.1.0(CLI 与扩展同步)
- CHANGELOG v1.1.0(含核心表面 Δ = 无增删;诚实标注 P4(b) 盲测未达标)
- README 现状/安装/示例更新(新命令 check / --json / mlsp)
- debian/changelog 1.1.0-1ppa1;release.yml Highlights stub 更新
- 核心表面 Δ:无增删(19 构造不变;本版为 Runtime/Document 层变更)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 13:31:27 +08:00
cflmyandCursor cba51238b6 doc/next/002: 智能体框架「认知编译」构想(Learning → Compilation)
用户维护文档归档:每次执行沉淀 mq.md;>3 次调用自动总结优化出记忆文档;
完全学会后降能耗运行(少 LLM 思考 / Jev 决策模型 / 纯分支控制)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 13:19:56 +08:00
cflmyandCursor 5fffb800f9 P4(b) 收口:mimo-v2.6-pro 两跑均端点 infra 不可评估,判据以 deepseek-flash 为准
- perf-validation-report §3 记录重跑终局(12/12→11/12 infra),(b) 判据判定不改
- three-problems-plan Phase 4 落地记录同步

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 13:10:28 +08:00
cflmyandCursor 1a729eb9ec P4 验证执行:(a)锚点消融✅/(c)契约消融✅/(d)防漂移✅/(e)守卫演练✅;(b)盲测 deepseek-flash 完成未达标、mimo-v2.6-pro 重跑中
- perf-validation.md:五实验协议/判据/材料(2026-09-23 自设计)
- perf-validation-report-2026-09-23.md:汇总报告(判据逐项对照 + 诚实结论)
- tests/blind_experiment.rs + tests/blind/:盲测 harness(查询通道/修复回路/usage 计量)+ 冻结材料(6 任务书 + docs-bundle)
- tests/contract_ablation.rs:四边界×三情形消融(拦截 100%/误报 0%/零回归)
- tests/drift_drill.rs:9 漂移必报 + 2 负对照
- src/mlsp.rs:syntax 卡片自持化(semantics/rule/sample/doc_quote)
- three-problems.md §5.1 判据矩阵逐行判定(问题 1✅ 2✅ 3❌);three-problems-plan.md Phase 4 落地记录
- 全量干净回归零失败

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 05:06:30 +08:00
cflmyandCursor 00c763300e test(repair): mimo-v2.6-flash cross-check + measurement-side hardening
mimo-v2.6-flash 终测:anchor 臂一轮 20/20=100%、plain 90%(最终 95%);
三轮双臂一轮修复率全部 >=85%(目标 >=80%),护栏 0 越界。

'测试不稳定'定性为三类测量端问题并全部加固(与 Marqdo 语义无关):
- 网关空体抖动 -> curl --retry + 5s 退避(加固后 0 次失败)
- 推理模型 reasoning_content 吃光 token 预算 -> max_tokens 2000->8000
- 模型输出格式畸形 -> parse_edits 容错(数组/单对象/NDJSON 多对象流/
  字符串化元素/字符串型行号/围栏/数字后多余引号的确定性修补 unquote_line_nums)

报告按模型分文件(repair-experiment-<date>-<model>.md),cflmy/mimo 双报告并存;
计划记录更新为三轮对照表。干净环境 cargo test 444/444 全绿(零回归);
ext_llm_*/ext_agent_*_live 为环境开关型实况测试,与本期无关。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-23 01:27:01 +08:00
cflmyandCursor 224b3d4a66 test(repair): §5.2(a) 模型在环修复实验 —— 锚点消融:anchor 100%(20/20) vs plain 85%,≥80% 目标达成
- tests/repair_experiment.rs:真实消费 validate → repair_targets → 模型行编辑 → repair_apply(越界必拒)
  → 复验 的完整闭环(≤2 轮;容错重试;cflmy @ llm.cflmy.cn,.env 读取,#[ignore] 不进常规回归)
- 双臂消融:anchor(诊断带 doc_anchor/doc_quote/suggestion)vs plain(剥掉)——
  anchor 一轮修复 20/20=100%;plain 17/20=85%(3 例失败均为网络空体抖动)
- tests/common/mod.rs:golden 20 例与诊断/应用共享件抽出(repair_loop + experiment 同源)
- parse_edits 容错(数组/单对象/字符串化元素/围栏);越界必拒/abstain 由 repair_loop 硬断言覆盖
- 报告:doc/roadmap/repair-experiment-2026-09-22.md;.gitignore 补 .env(密钥不入库)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 21:10:03 +08:00
cflmyandCursor 81d26a265a docs(roadmap): 落地记录 —— T3.4 修复回路工程项完成(护栏 + golden 20 例);T3.3 编号归位
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 20:14:32 +08:00
cflmyandCursor 5b599125d1 feat(repair): T3.3 修复护栏 + golden 20 例 —— 机械护栏(有界行编辑·越界必拒·abstain)+ mlsp repair_apply
- src/repair.rs:行编辑有界应用(replace/delete/insert;触碰行必须落在靶点范围内,
  越界 ⇒ 整体拒绝 + 越界清单,源零字节不改 = abstain;表尾追加允许 end+1)
- mlsp repair_apply:护栏的 MLSP 出口(ranges + edits → 新源;越界报 mlsp.repair_out_of_scope)
- tests/repair_loop.rs:golden 20 例(10 骨架 × 2)走完整修复循环
  (诊断 → 靶点 → 金修复行编辑自动推导 → 范围自检 = 「易锚定」机器验证 → 应用 → 复验)
  + 护栏负例(越界必拒 + 源零字节不改 + 部分越界全拒)
- 待做:模型修复实验(把金修复换成模型编辑,测 ≥80% 修复率)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 20:13:41 +08:00
cflmyandCursor 18d89d6cf2 docs(roadmap): 落地记录更新 —— T3.4 完成;T3.3 golden 实验待做
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 19:47:19 +08:00
cflmyandCursor 199b5c532f docs(skill): T3.4 AI Skill 换骨 —— 背语法 → 查 MLSP;渐进式契约入语法面
- marqdo/SKILL.md: 置顶「查 MLSP」查询式工作流(五方法 + 行分隔 JSON 协议 + 修复护栏);
  渐进式契约三种表格形状/位置/四边界;工作流与 checklist 增加 validate/check 环节
- marqdo-dev/SKILL.md: 契约/MLSP/三层准入/错误出口唯一的开发戒律

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 19:46:25 +08:00
cflmyandCursor db5f0e830b feat(mlsp): Phase 3 MLSP for AI —— locate/syntax/validate/repair_targets/schema(T3.1/T3.2 + T2.6)
- src/mlsp.rs: 行分隔 JSON 协议 + 五 handler;语法唯一事实来源 = CORE_CONSTRUCTS(只加检索别名)
- repair_targets 带有界护栏策略(anchored-local / 越界必拒 abstain / max_attempts=2)
- schema 契约导出(T2.6):形参/返回/字段契约 + 升参清单 + 锚点
- marqdo mlsp 子命令:stdio 行分隔 JSON 服务
- tests/mlsp.rs 7 例全绿;全量回归零失败(含 262 gold)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 19:44:35 +08:00
cflmyandCursor 7a449c40b1 feat(contract): Phase 2 渐进式契约层 —— 契约表提取 + 四边界校验 + marqdo check 防漂移(T2.1–T2.5)
- src/contract.rs: 类型词汇(渐进标注)、参数/返回/字段三形状契约表解析、合并、四边界校验诊断
- src/parse/mod.rs: extract_function_contract —— 位置+形状双重判定,在升参推断之前提取;
  绑定表/普通文档表绝不吃(P1 零回归),契约表从 body 移除(元数据永不执行)
- src/interp.rs: 四边界校验 —— 调用实参(3 条调用路径)/返回/表绑定/字段访问
- src/check.rs + marqdo check [--json]: 漂移双向互查、未知类型名(附建议)、错位契约
- src/load.rs: label_error 保留结构化诊断(错误出口唯一,不拍平成字符串)
- T2.4: 全部契约诊断带 doc_anchor/doc_quote/contract_ref
- tests/contracts.rs 12 例全绿;全量回归零失败(含 262 gold)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 19:40:08 +08:00
cflmyandCursor 97fda7aa10 feat(core): Phase 1 —— 核心收口 + 诊断地基(core-surface 守卫 · 三层准入 · Diagnostic JSON)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 19:03:03 +08:00
cflmyandCursor a49592a3ba docs: 三大问题设计移出 doc/next/ → roadmap/three-problems.md;新增落地计划 three-problems-plan.md
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 17:46:09 +08:00
cflmyandCursor ed9ac03c0c docs: README 前置核心优势与愿景(Executable Knowledge 定位);doc/next 交流笔记入库
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 17:07:33 +08:00
cflmyandCursor cb46ad7abe fix(ppa): trim bundled Rust to build essentials; clean extract on failure
Launchpad builds only need rustc + cargo + rust-std (debian/rules PATH),
but install.sh was still shipping rust-docs-json-preview / rustfmt /
rls (~1G). Also drop the 1.5G extract dir via EXIT trap when install
fails — the leftover is what filled /tmp last run.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 16:40:39 +08:00
cflmyandCursor 586975090b release: v1.0.7 — WS/网络边界加固
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 15:40:48 +08:00
cflmyandCursor 544805266b fix(wasm): mark marqdo-bridge.js as ESM for Node consumers
The canonical bridge uses ESM exports but, with no package.json in scope,
Node loads untyped .js as CommonJS — tests/wasm/smoke.mjs could not see
applyDomPatch et al (Named export not found). Scope type=module to the js
dir only; marqdo wasm build copies just the single .js file, so nothing
ships differently.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 15:27:09 +08:00
cflmyandCursor f3051fb536 fix(test): align P3 gold with quiet-admin gate semantics
b752cd4 stopped auto-gating admin_prefix when admin=false but did not
update the P3 gold, which still expected the removed /admin auto gate
(ng >= 2). Assert the new intent instead: exactly one explicit gate
registered with the declared path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 15:20:48 +08:00
cflmyandCursor 86b183e2d7 fix(web): harden WebSocket and net host boundaries
- WS handshake: same-origin CheckOrigin instead of allow-all
- route_ws require_auth/需要登录: broadcast/room need a session by default,
  explicit opt-out for public feeds; unauthenticated handshakes get 401
- WS limits: 1 MiB per message, 256 replies per connect; transport errors
  return {ok:false, error} instead of an empty success; empty rooms GC'd
- net host: enforce the 8 MiB response cap while reading (incl. error and
  SSE error paths) so a peer cannot exhaust memory
- url_encode: %20 for space (URL segment semantics, not form +)
- docs: sync 网页 (route_ws 需要登录, connect caps) and CHANGELOG
- tests: gold expectations, live fixture opt-out, hub GC, ws auth gate

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-22 15:14:35 +08:00
cflmyandCursor 8e23a5395a release: ext pack 1.0.6 — OIDC, form delete, quiet admin
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 16:46:01 +08:00
cflmyandCursor cab609ee91 fix(web): logout to home instead of OIDC login bounce
Clear the session and land on / when logout_redirect is an OIDC entry
path; also exclude */logout from RBAC gates so exit always runs locally.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 16:13:06 +08:00
cflmyandCursor b752cd49b7 fix(web): keep admin and RBAC desk quiet until opted in
Skip auto-gating admin_prefix when admin=false, and mount /_rbac/* only
when enable_rbac sets desk/管理台 so custom desks are not interfered with.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 16:01:40 +08:00
cflmyandCursor 2c91b5cc7b feat(web): OIDC login, form delete, and route-param intros
Add authorization-code OIDC for site auth, treat form action delete as a
generic CRUD primitive, and resolve {param} placeholders in page intros so
custom admin desks can stay in .mq.md without site-specific plugin patches.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 15:57:33 +08:00
cflmyandCursor 453321c8c2 perf(web): cache static assets and defer wasm boot
Add long Cache-Control for /static, version client embed URLs from
asset_version, and delay WASM mount until after load so LCP images win.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 15:07:54 +08:00
cflmyandCursor 981d754133 feat(web): allow Redis session URL separate from app DB
Wire session_url through app.auth/listen so sites can store sessions in
Redis while keeping Postgres/SQLite for application data.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 14:59:50 +08:00
cflmyandCursor 410f36f719 feat(web): Postgres CRUD and fix stale-session CSRF login
Wire pgx for postgres:// DB URLs, dialect-aware RBAC/sessions, and replace dead marqdo_sid cookies so login forms always get a fresh CSRF token.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 14:53:16 +08:00
cflmyandCursor bd06aedb90 fix(browser): pass optional then= through store_set
Theme toggle wrote localStorage but never chained to apply_theme because store_set dropped then.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 14:22:54 +08:00
cflmyandCursor 42ddeb14e7 fix(wasm): custom getrandom so browser wasm loads without wbindgen
The js feature pulled __wbindgen_* imports that marqdo-bridge cannot satisfy, breaking theme toggle and all client WASM.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 13:46:49 +08:00
cflmyandCursor 6bd127a313 feat(web): live markdown preview via POST /_md host glue
Markdown form fields render a dual-pane shell; official boot posts textarea input to /_md for GFM HTML without author business JS.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 13:01:43 +08:00
cflmyandCursor 4b7643d833 fix(web): prefer form redirect and soft-default now_if_empty
Desk 文案 cancel links stamp redirect so POST leaves the compose page; empty date fields can opt into 空则现在 without blocking custom values.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 12:58:24 +08:00
cflmyandCursor 3f96592c99 feat(web): form_load SSR prefill and safe {id} desk routes
Edit pages can stamp compose_form_load to hydrate forms from DB by route id without author JS. Part slots use {part} so pathParamNames can inject {id} again.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 12:50:59 +08:00
cflmyandCursor 98018fc63b feat(web): SSR nav brand/client embed and form markdown labels
Replace author theme.js with framework chrome (nav brand, theme boot,
client mount) plus bridge scroll/observe helpers; add form submit copy
and type=markdown textareas so sites can drop business JS.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 12:42:50 +08:00
cflmyandCursor aeac4d6d20 feat(web): SSR news rail via list target=rail and KaTeX boot glue
List binds with 插槽=rail render aside.side-rail and set has-rail; cards honor pinned; pages that load KaTeX auto-render get an official deferred math boot so authors need no volume.js.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:41:52 +08:00
cflmyandCursor 9e9a80df31 feat(web): progressive-enhancement auth forms for branded login pages
Custom /login and /desk/login can POST natively: CSRF/next are injected server-side, failures re-render the same site page with localized flash, and compose_auth_form / 鉴权表单 removes the need for author JS.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:30:33 +08:00
cflmyandCursor 5f07b1c3b1 fix(web): preserve absolute URLs in card hrefs
News and other cards with http(s) or root-relative links were incorrectly prefixed with link_prefix, breaking SSR /news.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 11:03:15 +08:00
cflmyandCursor bfea2204eb fix(web): inject CSRF meta on custom login pages
Site-owned GET /login no longer serves the framework form; stamp
csrf-token + session cookie on page render so JS can still POST /login.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 10:49:56 +08:00
cflmyandCursor fb30cd3db3 release: ext pack 1.0.5 — request context and list binds
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 10:24:34 +08:00
cflmyandCursor 584cb9ac9d feat(web): request-context field sources and page list binds
Replace domain comment hacks with generic session/route/now stamps,
server-only form fields, compose_list for detail+child lists, and a live gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 10:17:39 +08:00
cflmy 428ee141e1 fix(ppa): keep vendor checksums and reuse published orig on debian bumps
dh_clean was stripping Cargo.toml.orig and breaking Launchpad offline
builds; debian-only uploads now reuse the PPA orig with debuild -sd.
2026-09-18 09:02:53 +08:00
cflmyandCursor ec9718466d release: ext pack 1.0.4 — RBAC, tenant, WS hooks, SPA, collab
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 21:10:50 +08:00
cflmyandCursor c5bb08022a feat(web): collaborative notepad MVP over WS rooms
Add LWW text sync demo (DOC\\t protocol + presence) on route_ws rooms,
with design note and bag smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 21:00:10 +08:00
cflmyandCursor b710745e88 feat(web): native SPA helpers, memory store, and demo
Add bridge scope=memory, lib/browser store_set/spa_goto, web-spa-app
list/detail/edit client routes demo, and helper smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 20:58:21 +08:00
cflmyandCursor 5cf84fe9b7 feat(web): RBAC, tenant scope, and WS room hooks
Add configurable role⊥permission (five tables, gate permissions, register,
/_rbac desk), multi-tenant path/header resolution with JSON tenant_scope,
and route_ws on_message/presence/dynamic room_key — with author surfaces,
demos, and smokes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 20:54:02 +08:00
cflmyandCursor 27991a7822 docs(release): fold unbound-table fix into v1.0.3 notes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:31:41 +08:00
cflmyandCursor d1e2f0ced0 fix(parse): allow unbound GFM tables as discarded values
Bare tables in a function body evaluate as collections without requiring
a name bind; restores welcome-page install tables.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:29:13 +08:00
cflmyandCursor e848306187 fix(public): drop bare GFM tables from welcome # main
Tables are collections in Marqdo; bare rows aborted pages CI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:26:12 +08:00
cflmyandCursor 2ee9d7e66d release: v1.0.3 — PPA, ext CDN, synced CLI+ext packs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:20:37 +08:00
cflmyandCursor e31585842d fix(ppa): bundle Rust toolchain for noble Cargo.lock v4 builds
Document install channels (PPA/GitHub/CDN); release skill supports
full/cli/ext modes with R2+GitHub ext uploads and manual PPA commands.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:18:50 +08:00
cflmyandCursor f068b4ab75 fix(packaging): skip cp when orig tarball already in build-area
Same-inode copy aborted ppa-build under set -e before dput.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:05:23 +08:00
cflmyandCursor 26e29409a9 docs(changelog): mention ppa-ship one-shot script
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:01:33 +08:00
cflmyandCursor 4923129d10 feat(packaging): add ppa-ship.sh one-shot build and dput
Installs apt deps with sudo, then builds/signs/uploads as the real user.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 10:01:22 +08:00
cflmyandCursor 8ab55e2193 docs(changelog): note Ubuntu PPA packaging scaffold
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 09:58:12 +08:00
cflmyandCursor 9bc7ef3b5a feat(packaging): scaffold Ubuntu PPA debian/ for marqdo CLI
Add control/rules/changelog and ppa-build-source.sh (cargo vendor + debuild -S).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 09:57:11 +08:00
cflmyandCursor 9431ad835c docs: link ext-cdn in doc/README
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 09:31:06 +08:00
cflmyandCursor 2984d7d4f8 feat(ext): prefer Cloudflare R2 CDN and allow separate ext pack versions
Download order is CDN (ext.marqdo.com) → GitHub → proxy; pack SemVer from
ext/VERSION / CDN latest; add upload-ext-r2.py and release-skill notes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 09:28:28 +08:00
cflmyandCursor 6324036e41 fix(ext): mirror fallback for Release downloads and default ~/.marqdo/ext
Try proxy.cflmy.top when github.com fails; honor MARQDO_EXT_DOWNLOAD_BASE;
resolve ext imports from the ext-add install root without exporting MARQDO_EXT.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 08:57:24 +08:00
cflmyandCursor 3287799959 docs(skill): note table-bound page.compose_intro for v1.0.2
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:06:30 +08:00
cflmyandCursor f95e5d3339 release: v1.0.2 — table-bound page intro (compose_intro)
Ship web_compose_intro / 引言装配 and web-site demo polish; bump Cargo and docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 21:05:49 +08:00
cflmyandCursor 52b4bae423 feat(web-site): harden sample desk, auth login, and form layout
Align nav/side/foot slots and shell CSS with table-driven admin desk;
add session login/logout mount and widen form fields for usable create UX.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 19:44:12 +08:00
cflmyandCursor 037592087c feat(web): table-bound intro and demo-grade web-site sample
Add compose_intro (属性/值/样式) so page heroes are not HTML strings, and polish examples/web-site for WWW Demo: literary shell, card→detail routes, richer seeds, particle atmosphere without author JS.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 17:34:49 +08:00
cflmyandCursor 3eb8e732ea release: v1.0.1 — fix Go libweb dynamic-route query, Markdown, CSS false positives
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-15 14:48:47 +08:00
cflmyandCursor 761b92afce docs(public): keep narrative emphasis from executing as v0.3 code
Unbold code-shaped prose and give log.fields a map so pages and
`view output` stay green under markup v0.3.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:15:47 +08:00
cflmyandCursor b5f43ee993 release: v1.0.0 — markup v0.3 as the 1.0 language surface
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:05:29 +08:00
cflmyandCursor 76da97f090 ci(release): require Linux native+CLI zips; document proxy.cflmy.top
Pages was failing on leading-backtick narrative (already fixed on main).
Linux job now waits for the Windows release, then uploads .so plugins and a
Linux CLI bundle. Release skill treats those assets as mandatory.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 16:03:02 +08:00
cflmyandCursor 7554e45f60 feat(debug): dump v0.3 prose bits, inferred params, and dead binds
--dump-lines tags [decl]/[bold]/[italic]; --dump-ast prints `inferred` params
and `dead=[…]`. Migrate leftover italic-assign unit fixtures to bold/return.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 15:33:45 +08:00
cflmyandCursor 6994acb91d fix(prose): mid-line italic emphasis is not a return
Skip *very important* / *foo.bar* / *code-as-docs* so narrative emphasis cannot end a function; keep whole-line *n* and 返回*n*.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 15:25:26 +08:00
cflmyandCursor bccfec86ba feat(parse): bold infix expressions are ExprStmt, not calls
`` **n + 1** `` evaluates and discards (design §6.2); keep assign-first and
bare-call fallback. Explicit `` **> …** `` uses standalone bare=text rules.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 15:12:00 +08:00
cflmyandCursor 114fd53cd1 fix(prose): Decl names are identifiers; skip non-decl tick spans
Reject `` `n+1` `` as Decl, and when skipping non-decl `` `…` `` advance past the closing tick so inner `*` cannot open italic (fixes `` `OPENAI_*` `` in ext/ai/llm).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 14:50:01 +08:00
cflmyandCursor c8f41164c5 fix(parse): keep GAP recovery for unclosed bold
Hard-erroring code-shaped `` **… `` broke tests/structure/gap-star-json-body.mq.md; unclosed bold stays Comment so later statements still run.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 14:41:51 +08:00
cflmyandCursor 6f303ff957 fix(parse): diagnose unclosed code-shaped bold
Treat `` **x = 1 `` as Code and error with a clear unclosed-`**` diagnostic instead of silently skipping it as a comment.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 14:39:58 +08:00
cflmyandCursor 95a49697f7 fix(lex): glued ` name=default …prose ` is Decl, not assign
Trailing text after a glued default (same terminators as prose Decl) keeps the line narrative so `` `礼貌`=False 时… `` no longer binds a mangled text value.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 14:31:12 +08:00
cflmyandCursor 8846f5f070 fix(lex): treat leading backtick decl lines as narrative
Only `` `name` = … `` binds stay Code; lines like `` `捕获=True` 时… `` are Comment Decl prose so they no longer raise unrecognized statement.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 14:22:19 +08:00
cflmyandCursor 4f09e515ee feat(view): mark prose-inferred params in Structure
Show inferred function parameters with a dashed chip and outline annotation so view surfaces v0.3 param elevation without changing the redundant call surfaces.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 14:04:45 +08:00
cflmyandCursor 551f4ff322 feat(view): preserve bracket-marked calls without modifiers
Track CallExpr.bracket_marked from `[callee]` parse so Structure display keeps `[fn] …` instead of falling back to `> fn …` when there are no pre-modifiers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 13:39:12 +08:00
cflmyandCursor d5a9301c7f docs(public): finish stdlib bracket-call demos and fix import returns
Prefer [lib.fn] in remaining public/stdlib samples, correct italic returns in structure import modules, and keep lib/系统 narration from starting with backticks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 13:32:17 +08:00
cflmyandCursor 34915e3b16 docs: align remaining tutorial chapters with markup v0.3
Teach bold-as-code, italic-as-return, link-index, and bracket-marked calls across chapters 1–8/10–14 and Skill reference so teaching matches the runtime.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 13:18:28 +08:00
cflmyandCursor c55aad775e docs: teach link-index and v0.3 markers in tutorial and Skill
Rewrite chapter 9 and Skill examples around [key](coll), bracket-marked
calls, and ** code / * return; keep footnote get as a transitional note.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 13:08:53 +08:00
cflmyandCursor ac3f0633cd refactor(tests): prefer link-index in structure collection golds
Move collection-* structure fixtures to [key](base), and modernize
public/stdlib table/fs/time demos with bracket-marked library calls.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 13:03:03 +08:00
cflmyandCursor d55567a634 chore: stop tracking ephemeral tests/ext/:memory:
Remove the accidental sqlite artifact from the tree and ignore it.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 12:54:51 +08:00
cflmyandCursor abcb141737 refactor: prefer link-index get across examples and tests
Migrate remaining footnote-style collection access in examples,
public/structure, and ext/lib smokes to [key](base); teach link-index in
structure pages and use bracket calls in the cafe journal example.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 12:54:38 +08:00
cflmyandCursor 8d97adc1dc docs(ext): narrate quantum/linalg and link-index public features
Add module intros and missing purpose lines for EN/ZH quantum and linalg
extensions; migrate remaining public/features footnote gets to [key](base).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 12:45:57 +08:00
cflmyandCursor 5c37d54070 refactor(ext): prefer link-index get in web and ai modules
Migrate footnote-style collection access to [key](base) (including nested
chains) in ext/web and ext/ai EN/ZH sources.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:55:09 +08:00
cflmyandCursor fecaacd5be docs(lib): narrate remaining stdlib modules (M2)
Add module intros and per-function purpose lines across EN/ZH libs, with
callable examples on the smaller modules; keep + params and host bodies intact.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:47:35 +08:00
cflmyandCursor 53bc3538da docs(lib): narrate table/text/json as code-as-docs pilot
Add purpose lines and bracket-call examples in EN/ZH libs and public/stdlib
demos; keep explicit + params so function-body prose cannot be mistaken for
link-index or bold code.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:38:24 +08:00
cflmyandCursor 0e0655b316 feat(markup): bracket-marked calls with pre_modifiers
Stabilize `mod… [callee] args` (modifiers → name=True) alongside link-index
disambiguation; expand in interp/bytecode, show in view, and document lib/view
code-as-docs waves before stdlib rewrite.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 11:33:11 +08:00
cflmyandCursor 5058f5ddcf docs(examples): make code-as-docs read as a cafe journal
Drop syntax-teaching asides, rename the tip helper to 印章加一, and keep
return phrasing that the italic heuristic recognizes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:52:30 +08:00
cflmyandCursor 4a1c9c48a2 feat(markup): prefer [key](collection) for map and list access
Add GFM link-shaped index as the primary get surface, keep footnote
index as transitional compatibility, and align the coffee example.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:44:18 +08:00
cflmyandCursor 5e74ff39f2 feat(markup): code-as-docs narration surface (G1–G4) and drop --- body end
Treat --- as Markdown HR everywhere, end side-effect helpers with empty returns,
and accept soft emphasis, float literals, and dynamic footnote keys so LLM-friendly
.mq.md stays runnable. Ship the weekend coffee example plus gold fixtures.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-14 10:16:48 +08:00
cflmyandCursor b5c07385e9 feat(markup): finish v0.3 stock migration and green gold
Migrate remaining .mq.md (tests/ext/public/examples), stop elevating local assigns to params, inject form_target in Go libweb, and skip live LLM gold without a real key.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 23:43:44 +08:00
cflmyandCursor bfb10d172b feat(markup): adopt v0.3 as sole mapping (** code, * return)
Make prose-unified Markup the only runtime: bold segments are executable,
italic is return, params can be inferred from body/prose, with no v0.2 dual
mode. Migrate lib and structure/keywords golds; gate on tests/markup-v03.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 20:38:53 +08:00
cflmyandCursor 00a77181ef docs(skill): note Go libweb default for v0.4.0
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 15:10:00 +08:00
cflmyandCursor e13468dc43 release: v0.4.0 — Go libweb default and anlian-mq
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-13 15:09:45 +08:00
cflmyandCursor d3b137c919 feat(anlian-mq): align site with Django anlian browse UX
Port original CSS/JS/assets, rebuild home as four sections with feed
fragments, expand schema (boards/notices/rooms/topics), and add
page.chrome HTML overrides plus invoke html returns so Marqdo can
render Django-class chrome without json glue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 22:46:55 +08:00
cflmyandCursor e292c8a7c7 feat(anlian-mq): port pink-glass theme, hero motion, and brand assets
Replace the warm-paper placeholder shell with GFM style tables that
mirror Django anlian (fixed bg, frosted nav, pulse logo, hero float,
glass cards). Ship original static assets and tighten smoke for visuals.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 21:32:46 +08:00
cflmyandCursor ce195998c1 feat(web): W-G14 anlian-mq acceptance and auth/session listen fixes
Add a GFM-first anlian rewrite under examples/anlian-mq to exercise Go
libweb (lists, detail, gates, login, WS). Wire RBAC/login into listen,
page query/order/detail ABIs, and stop issuing Max-Age=0 CSRF cookies so
browser login sessions stick.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 21:20:11 +08:00
cflmyandCursor e20cf8b386 feat(web): serve upload, WS, proxy, and gallery on Go listen
Mount media/ws/proxy/invoke routes in httpx, force gold onto Go via
MARQDO_WEB_PLUGIN, and case-fold middleware header checks so all seven
web live golds pass against libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 20:52:29 +08:00
cflmyandCursor c4a726397d feat(web): W-G13 default to Go libweb in CLI, gold, and release
Switch ext add / gold / release builds to scripts/build-web-plugin.sh,
drop the Rust archive from the Cargo workspace, and resolve libweb from
plugins/web/build (and target copies) without MARQDO_WEB_PLUGIN.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 20:18:41 +08:00
cflmyandCursor 7fab85b389 fix(web): expose web_db_table_info for admin schema forms
Wire existing db.TableInfo through the C ABI so offline admin smoke
can introspect columns before form_from_schema.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 20:12:32 +08:00
cflmyandCursor 12d2c7be69 feat(web): Go W-G12 rooms, Redis session, and API keys
Add mode=room with room_key hub APIs, optional redis:// session
backend, and web_api_key_check (sha256 pepper:key) for anlian primitives.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 20:10:43 +08:00
cflmyandCursor 26955f4f36 feat(web): Go W-G11 render head links for C2–C4
Emit page.head scripts/styles with defer and asset versioning so
shell/layout, style/head, and nav when/media offline smokes pass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 20:07:04 +08:00
cflmyandCursor 56df0736fa feat(web): Go W-G10 proxy and invoke route bags
Register web_app_proxy/invoke and merge configure tables into
proxy_routes/invoke_routes so offline proxy-invoke smoke passes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 20:02:46 +08:00
cflmyandCursor 695939ac74 feat(web): Go W-G9 memory/Redis cache drivers
Wire web_cache_* ABIs with an in-process memory backend and go-redis
ops so drivers smoke covers cache, file storage, postgres URL, and s3 open.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 19:41:10 +08:00
cflmyandCursor 4c06851e0e feat(web): Go W-G8 WebSocket routes and access_log
Register route_ws/ws_connect ABIs with an in-process broadcast hub
so offline WS broadcast and access_log smokes pass on libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 19:31:03 +08:00
cflmyandCursor 23e4bc406e feat(web): Go W-G7 RSS, sitemap, redirect, and SEO bags
Add paginate/meta wiring, RSS and sitemap builders, and app
redirect/error/sitemap/robots route bags so content and W7 offline
smokes pass on libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:51:50 +08:00
cflmyandCursor fe18c4d1d6 docs(web): mark W-G6 complete in rewrite plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:41:59 +08:00
cflmyandCursor e6fdeb0b31 feat(web): Go W-G6 storage, upload, gallery, and assets
Add file: storage, media validate/save, app upload/download/gallery
route bags, and head/images/icons assembly so offline upload, assets,
and P3 smokes pass on libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:41:59 +08:00
cflmyandCursor 5ec4b3c17d docs(web): mark W-G5 complete in rewrite plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:31:07 +08:00
cflmyandCursor 6e94d0a179 feat(web): Go W-G5 session, auth, password, and RBAC gates
Wire password hash, session CRUD, auth login/check/logout, and
app.auth/gate ABIs so security and C0/C1 offline smokes pass on libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 17:31:07 +08:00
cflmyandCursor 4357045904 docs(web): mark W-G4 complete in rewrite plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 16:50:30 +08:00
cflmyandCursor 1ef71d7492 feat(web): Go W-G4 listen, static, middleware, and JSON routes
Add app.static / configure middleware bags and blocking httpx.Listen
(home, routes, _part, static, forms, JSON API, CORS/gzip layers).
Pass route/static/middleware/part offline smokes against libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 16:41:59 +08:00
cflmyandCursor 1fc985db7e docs(web): mark W-G2/W-G3 complete in rewrite plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 16:03:53 +08:00
cflmyandCursor 364428ca1e feat(web): Go W-G2 txn/migrate/FTS and W-G3 form ABI
Wire begin/commit/rollback, migrations, FTS search, and form
rules/validate/render/submit/from_schema plus mount_form; pass
web-db-w2, web-db-w6, and web-form-smoke against libweb.so.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 16:01:17 +08:00
cflmyandCursor 09b549a862 docs(web): note W-G2 CRUD/where progress after select-smoke
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 15:34:42 +08:00
cflmyandCursor 2d238a8c36 feat(web): Go SQLite update/delete/query/count + where filters
Complete core CRUD beyond smoke: typed where (map + filter ops),
register web_db_update/delete/query/count, and pass web-select-smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 15:34:15 +08:00
cflmyandCursor 7a0309284a feat(web): Go plugin W-G1 assemble/render + SQLite smoke path
Port table/compose/style/render/db/form/app bags, register ABI symbols,
prefer MARQDO_WEB_PLUGIN over ~/.marqdo, and pass web-smoke + web-zh-smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 15:27:12 +08:00
cflmyandCursor fd3f1724e6 chore: ignore Go web plugin build/ artifacts
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 14:48:07 +08:00
cflmyandCursor ca40c698a2 refactor(web): start Go ABI rewrite of plugins/web (W-G0)
Archive the Rust web plugin and add a Go c-shared skeleton with ABI v2
bridge, build script, design doc/ADR, and smoke test so multi-language
plugins and full web parity can proceed wave by wave.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 14:47:43 +08:00
cflmyandCursor fb6254e501 fix: GAP-11 form slot mount and GAP-12 MARQDO_EXT import hint
compose_form/表单装配 can inject into intro via target/表单插槽; unresolved
ext/ imports hint to set MARQDO_EXT when unset.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 16:52:41 +08:00
cflmyandCursor cf9d96477b fix(release): avoid env http_proxy when git uses HK jump -c
Match the proven push path: clear env proxies and set only git -c http.proxy.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 16:15:23 +08:00
cflmyandCursor 493d0ad91a fix(release): use Basic auth in HK jump git push
GIT_ASKPASS hung under agent/no-TTY; prefer http.extraHeader from credential store.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 15:52:33 +08:00
cflmyandCursor a0e88919a6 docs(release): add HK Paramiko jump for GitHub push recovery
Document the proven hk.cflmy.de CONNECT path and ship push-via-hk-jump.py so flaky Clash/reverse-proxy no longer blocks releases.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 15:44:17 +08:00
cflmyandCursor 237962c3be release: v0.3.9 — GAP-06–10 parser, invoke, exec, SSE
Ship business-integration fixes: star/JSON body recovery, invoke Null,
sys.exec capture, and proxy anti-buffer headers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 14:12:43 +08:00
cflmyandCursor 1637acce6e fix: GAP-06–10 parser, invoke Null, exec capture, SSE headers
Recover ## bodies after bad *…* terminators; bracket-aware call args;
invoke Null is 500 not fake ok; sys.exec capture={code,stdout,stderr};
proxy stream sets anti-buffer headers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 13:58:02 +08:00
cflmyandCursor 68c4f8c822 release: v0.3.8 — Mid2 stdlib M7–M10
Ship calendar/URL/TOML/HTML/fs/stats plus GLOBAL_HOST restore;
bump Cargo, README, CHANGELOG, and release workflow highlights.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 10:08:59 +08:00
cflmyandCursor 784d5ec346 feat(stdlib): Mid2 M10 stats and log fields
Add thin mean/median/stdev and optional structured fields on log
lines; close Mid2 M7–M10 (zip skipped).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 09:42:13 +08:00
cflmyandCursor 955834e453 feat(stdlib): Mid2 M9 fs make_dirs, walk, and stat
Thicken lib/fs with recursive mkdir/rmdir-tree, metadata maps, and
depth-first walk; add gold tests and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 09:27:06 +08:00
cflmyandCursor 435f36b6e9 feat(stdlib): Mid2 M8 toml, html escape, and base32
Add read-only TOML subset parse, HTML escape/unescape, and RFC 4648
base32 on encoding; gold tests and public demos included.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 09:22:00 +08:00
cflmyandCursor 08c48f3acb feat(stdlib): Mid2 M7 datetime and url
Add calendar moments as {unix,zone,iso} maps and URL/query parse
helpers in lib/ with thin host_* forwards; gold and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 09:14:18 +08:00
cflmyandCursor ff1870cedc docs: Mid2 gap research and M7–M10 design/roadmap
Inventory stdlib gaps after Mid M1–M6 and lock Mid2 waves
(datetime/url, toml/html, fs++, optional stats).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 09:04:29 +08:00
cflmyandCursor 5e51ee1bb2 fix(host): restore GLOBAL_HOST after nested plugin calls
Nested call_registered was clearing the process-wide host pointer to null,
so web_listen lost context for later HTTP invoke rounds after an inner ABI call.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 10:40:27 +08:00
cflmyandCursor 55f1a37b3d chore: sync Cargo.lock package versions to 0.3.7
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 22:21:54 +08:00
cflmyandCursor 58dff0a1e9 release: v0.3.7 — Hosting H1–H4 (proxy, invoke, MCP stdio)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 22:18:43 +08:00
cflmyandCursor fc543f1ca5 feat(web,agent): hosting H1–H4 — proxy, invoke, MCP stdio, cross-module db
Close GAP-01–05 with ext/web streaming reverse proxy and HTTP→## invoke,
transitive object method lookup, corpus_search plugin ensure, and agent MCP
server stdio so downstream apps can drop Python side relays.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 22:14:51 +08:00
cflmyandCursor 2e068e66d4 release: v0.3.6 — Mid stdlib M1–M6
Ship mid-tier libraries through log/uuid, bump Cargo/README/CHANGELOG, and refresh the Release workflow highlights.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:55:26 +08:00
cflmyandCursor a4c346d4a2 fix(agent,llm): avoid host_* writeback and tolerate SSE reasoning
Alias writeback as wb so the writeback= param does not shadow lib calls; ignore unknown stream event types so live SSE models keep working.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:52:44 +08:00
cflmyandCursor fe14d1f7e3 fix(agent): route writeback through lib instead of host_*
ext/** must not call host_*; use writeback.record / 自写回.写回 so the host-boundary gold passes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:40:24 +08:00
cflmyandCursor f4b39dfe80 feat(stdlib): Mid M6 log levels and UUID v4
Close the mid-tier stdlib waves with filtered one-line logs and cryptographic UUID minting in lib/, plus golds and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:37:28 +08:00
cflmyandCursor 7d86ed1d9c feat(stdlib): Mid M5 list algorithms and cli.parse
Thicken table with sort/unique/chunk/zip/flatten and add lib/cli
flag parsing, with golds and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:32:58 +08:00
cflmyandCursor 506de65dae feat(stdlib): Mid M4 csv and thickened text helpers
Add lib/csv parse/stringify and expand lib/text with contains,
replace, case, pad, and related golds plus public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:27:19 +08:00
cflmyandCursor 08384c7540 feat(stdlib): Mid M3 hash digests and secure tokens
Add lib/hash and lib/secrets (EN/ZH) with known-vector golds,
getrandom-backed tokens, and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:15:36 +08:00
cflmyandCursor 94ae6713aa feat(stdlib): Mid M2 path algebra and fs copy/move/temp
Add lib/path (EN/ZH) and thicken fs with sandboxed copy_file, move,
and make_temp, with golds and public demos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:10:12 +08:00
cflmyandCursor 838a2b425a feat(stdlib): Mid M1 regex and encoding libraries
Add lib/re and lib/encoding (EN/ZH) backed by host_re_* and
host_encoding_*, with golds, public demos, and design docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 20:02:43 +08:00
cflmyandCursor 1a5ee57a6f docs(stdlib): plan mid-tier standard library waves M1–M6
Define mid-stdlib admission rules and a phased roadmap so general
primitives land in lib/ instead of ABI plugins.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 19:53:44 +08:00
cflmyandCursor d539e6b96b fix(pages): build linalg plugin for public site CI
public/features/07-linalg needs marqdo_plugin_linalg; pages only built quantum.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 19:35:52 +08:00
cflmyandCursor 3ade036d34 feat(linalg): F3 formula-doc public pages and T_ascii
Ship runnable public how-to pages, T_ascii/转置文本 one-step display,
explicit auto-simplify, and mark formula-doc F1–F3 complete.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 16:13:22 +08:00
cflmyandCursor f3c49e86ae feat(linalg): F2 declare from GFM table and lecture example
Add la.declare for batch MatrixSymbol from @-record tables, ship
examples/linalg-transpose, and mark formula-doc F2 done.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 15:52:46 +08:00
cflmyandCursor b2401b8458 docs(linalg): formula-doc design and F1 display auto-simplify
Lock the run-implies-correct authoring model, default-simplify ascii/latex/show
(with raw= escape), and add linalg-doc-smoke for (AB)^T identity.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 15:50:33 +08:00
cflmyandCursor 51bb8767e3 feat(linalg): matrix infix ops and # matrix methods
Dispatch +/−/* to the linalg plugin for matrix values, retag for EN/ZH
method chains, and expand # matrix with T/simplify/ascii-style methods.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 15:13:47 +08:00
cflmyandCursor c0fbe9b182 feat(linalg): L6 lstsq, norms, complex dtype, draw themes
Add QR/SVD least squares, norm/cond/rank, complex dense Frobenius
baseline, and light/dark/bw draw themes aligned with quantum Q8.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:47:30 +08:00
cflmyandCursor 01287d9e7e feat(linalg): L5 examples, public feature pages, and skill docs
Ship SVD / least-squares examples, heatmap-hinton draw paths, coerce
dense factors into MatExpr ops, and document ext/linalg in skill/README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:36:17 +08:00
cflmyandCursor 70fb2fbfb2 feat(linalg): L4 factorize and structure SVG draw
Add LU/QR/SVD/eig/chol dense factorizations, teaching structure SVGs,
LU reuse via solve(factor=), and linalg-factor-smoke gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:31:44 +08:00
cflmyandCursor b6f116108c feat(linalg): L3 block collapse and lazy Kronecker
Add Block/Kron MatExpr, collapse for Block*Block, R7 flatten,
explicit assembly/kronecker, and linalg-block-kron smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:22:08 +08:00
cflmyandCursor 03aca7cdac feat(linalg): L2 dense explicit, det, trace, and solve
Add dense kernels with element limits, from_formula for $$ matrices,
and linalg-basic-smoke covering 2×2 det/trace/solve/explicit.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:16:16 +08:00
cflmyandCursor 96da88e168 feat(linalg): L0–L1 formula-first MatExpr plugin
Add plugins/linalg with symbol/mul/transpose/inv simplify (R1–R5),
EN/ZH L1, CATALOG/ext add wiring, release native assets, and smokes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 14:10:54 +08:00
cflmyandCursor b6cceab218 docs(linalg): design formula-first linear algebra extension
Add research, design, and roadmap for ext/linalg; cross-link from
stdlib-math and quantum Q7 so classic MatExpr stays out of lib/math.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-07 10:53:56 +08:00
cflmyandCursor 95b16be714 release: v0.3.5 — prebuilt native plugins for ext add
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 17:08:19 +08:00
cflmyandCursor d31ad79bc0 feat(ext): prebuilt native plugins and ext add download
Ship Release native zips and let ext add fetch L1/native without a local Rust toolchain.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 16:57:43 +08:00
cflmyandCursor 5745805a5d docs: blank line before v0.3.3 in CHANGELOG
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 14:20:31 +08:00
cflmyandCursor 590f7a58fa release: v0.3.4 — ext/web customization C0–C4
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 14:16:41 +08:00
cflmyandCursor 027b19c5db feat(web): C4 conditional nav with when and media columns
Filter nav/sidebar/footer by auth/guest/hide and emit responsive media CSS; stamp _logged_in from session on listen.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 13:54:53 +08:00
cflmyandCursor 7670673a39 feat(web): C3 style cell strict checks and head defer/version
Warn or reject numeric CSS values from bare `/` division; support script defer/async/version and page/app asset_version for cache busting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 13:43:35 +08:00
cflmyandCursor 824b9bf607 docs(web): mark C1 auth-gates solution as landed
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:49:07 +08:00
cflmyandCursor 155183eb30 feat(web): C2 shell_css modes and page layout presets
Split injected shell CSS into vars/layout/widgets with full|minimal|off, add stacked/bare/rail layouts, and stop forcing has-sidebar when authors opt out.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:48:50 +08:00
cflmyandCursor b10a84466b feat(web): C1 segment-boundary gates with on_deny and exclude
Make auth/admin gates use path segment prefixes, configurable redirect vs 403, and login_path exclusion so /admin-publish and /desk/login are not mis-matched.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:38:44 +08:00
cflmyandCursor 0aa0f47a9d feat(web): C0 release /admin when disabled; configurable admin_prefix
Stop mounting reserved admin routes when admin=False, nest CRUD under a
configurable prefix, and honor login/logout redirects so custom desks need no JS bypass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:50:11 +08:00
cflmyandCursor 5f91be7c21 docs(web): catalog customization limits and C0–C4 fix designs
Capture route/shell/auth/theme pain points from real sites and lock per-item solution docs before plugin work.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:38:20 +08:00
cflmyandCursor e3e2cfa9d1 fix(agent): writeback param shadow + Wave B1 dump/harness
step/plan writeback=True shadowed lib/writeback; persist via host_writeback_record. Align ZH context builder, add dump_step_context, lock offline harness.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:24:50 +08:00
cflmyandCursor d1b4e62d4d feat(agent): Wave B0 constitution demos + harness
Lock code-as-doc / call_site / OKF as first-class: reorder step
context, ship agent-pong and okf-flywheel examples, offline harness,
and skill/docs refresh. Dev LLM template via .env.example only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:17:25 +08:00
cflmyandCursor ff1b846b73 release: v0.3.3 — browser author-zero-JS routes D/E/F
Ship host effects through media APIs, lib/browser + GFM authoring,
and marqdo-dev skill; bump crate versions and release docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 10:13:28 +08:00
cflmyandCursor ad47d4a0d2 chore: gitignore browser-media wasm build artifact
Keep the example source and bridge; rebuild wasm via marqdo wasm build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 10:06:03 +08:00
cflmyandCursor c080b79c5b feat(wasm): route F host media APIs + GFM-first browser authoring
Ship bridge effects for file/canvas/audio/observers/drag-drop with
browser-media demo; add lib/browser and marqdo-dev skill so clients
use tables/helpers instead of json.set glue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 10:05:46 +08:00
cflmyandCursor f19f614e0d feat(wasm): finish route E gaps — multi-DOM, cookies, app CRUD/net
querySelectorAll patches, add/remove_class, append_html, remove,
clipboard/download, cookie storage; browser-app list delete + fetch_all/ws
panel. Mark E completed; plan F for file/canvas/media.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 09:11:36 +08:00
cflmyandCursor 8fbf617e05 feat(wasm): route E host effects for author-zero-JS frontend
Expand the official bridge with style/focus/list/navigate/storage/ws/
fetch_all/interval effects; relax the design rule to forbid only
author-written JS. Add browser-app demo and L1 list_html/dom_patch keys.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 09:06:21 +08:00
cflmyandCursor a9d30cdf4a feat(wasm): route D zero-author-JS frontend + plan route E
Auto-mount via bridge mount/data-mq and client_embed; expand DOM/form
effects; drop hello loader JS; add web-client-site. Document that C+D
cover mid-size interactivity but not most JS apps—route E covers
routing, storage, lists, WebSocket, and richer DOM/timers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 08:46:05 +08:00
cflmyandCursor 4c27c8afeb docs(release-skill): note gh auth via git credential fill
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:26:21 +08:00
cflmyandCursor 9d591674aa chore: sync Cargo.lock versions for v0.3.2
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:18:29 +08:00
cflmyandCursor e40d21760a release: v0.3.2 — browser WASM route C + release skill
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:18:13 +08:00
cflmyandCursor 2445c290c9 feat(wasm): finish route C — bridge package, smoke, site embed L1
Canonical marqdo-bridge.js ships with wasm build, Node ABI smoke covers
boot/call, and ext/web gains client_embed for head/static mounting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 11:05:43 +08:00
cflmyandCursor 04890e0c73 feat(wasm): C5 release-wasm size profile and build reporting
Add opt-level=z/LTO strip profile, print KiB from marqdo wasm build,
optional wasm-opt, and document tree-only browser sessions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:58:42 +08:00
cflmyandCursor ab52db2037 feat(wasm): C4 async fetch/after effects with bridge continuations
Accept ADR 0003: handlers return fetch/after maps; the official bridge
runs Promise/timer work and resumes via mq_call. Add fetch.mq.md demo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:53:11 +08:00
cflmyandCursor aac896b044 feat(wasm): C2/C3 session boot, wire events, and interact demo
Add BrowserSession with shared entry env, mq_boot/mq_call exports,
marqdo wasm build, and a counter page driven only by counter.mq.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:48:46 +08:00
cflmyandCursor fb037022ba docs(wasm): document raw mq_* ABI for C1 exports
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:38:15 +08:00
cflmyandCursor a75b7a1c87 feat(wasm): C0/C1 browser Marqdo interpreter on wasm32
Feature-gate host/CLI deps for wasm-core, add run_source, and ship
crates/marqdo-wasm with a raw mq_run ABI plus examples/browser-hello.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:37:44 +08:00
cflmyandCursor f2fd4fb34e docs: lock browser Marqdo WASM plan (ADR 0002, C0–C5)
Accept route C: ship the interpreter/VM on wasm32 with a thin JS host
bridge, not transpile-to-JS. Add design, roadmap, and cross-links.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 10:06:56 +08:00
cflmyandCursor 2079577314 fix(web): admin layout, ext add native, keyframes; document quoted CSS ratios
Widen admin main/table display, ensure marqdo ext add builds/copies the
native plugin before mq install, and emit valid @keyframes from style
tables. Prefer quoted cells like "16/9" for CSS values that contain /.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 09:59:03 +08:00
cflmyandCursor 416914a346 release: v0.3.1 — W8 favicon/head/images + entry_dir fix
Ship site icons, head asset tables, and image assembly; absolutize
entry_dir for relative entry scripts so sqlite paths no longer nest.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-29 11:47:22 +08:00
cflmyandCursor 1e5e6f4891 release: v0.3.0 — web/agent/quantum wave + docs
Ship W0–W7+P3, agent A1–A4, quantum Q7/Q8; fix web prose parse;
document ASGI/proxy deploy; refresh README how-to for latest Marqdo.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-29 10:35:13 +08:00
cflmyandCursor 4c37e79dae docs(agent): record post-A4 framework gaps and next-wave B0–B5
Capture productization, eval, live MCP, resume/HITL, and metrics gaps after the A0–A4 optimize loop; link from roadmap and doc index.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 17:56:31 +08:00
cflmyandCursor 9a8545b725 feat(agent): A4 corpus search and MCP fixture evidence tools
Add local keyword corpus_search and offline MCP fixture adapters as parent CALL tools; keep authority on workbook .mq.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 17:47:59 +08:00
cflmyandCursor ee3116513b feat(agent): A3 context budget and progressive READ disclose
Budget source/skill in step prompts with truncation markers; allow READ:source|skill deepen; parent READ:skill.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 17:26:16 +08:00
cflmyandCursor 729357b7c0 feat(agent): A2 process visibility — events always on plan result
Record decision/round/done without requiring stream; render process timeline on view plan cards; keep SSE gated on stream=True.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 17:06:59 +08:00
cflmyandCursor 07ab7d52c6 feat(agent): A1 OKF reuse flywheel — list_tasks curation and plan match
Enrich list_tasks for soft_match curation; expose match/score on plan hits; add offline plan-hit gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:53:27 +08:00
cflmyandCursor d7be903297 test(agent): A0 gold for multi-CONTINUE patches and solidify
Offline coverage: two precise workbook patches then agent_workbook_solidify
freezes the step worker into a quoted return.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:41:44 +08:00
cflmyandCursor d0b184939f fix(agent): harden workbook patches against whole-file rewrites
Reject large whole-file FIND spans, narrow soft=True to miss-only, check
decompose CONTINUE patch counts, and unit-test workbook_solidify.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:22:39 +08:00
cflmyandCursor c36383bf28 docs(agent): research frameworks vs Marqdo document-driven advantages
Add detailed survey of LangGraph/CrewAI/SDK landscape, lock Marqdo
differentiators, and sketch A0–A4 optimize roadmap for ext/agent.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:06:11 +08:00
cflmyandCursor eba0d703c5 docs(quantum): document Q8 themes in skill and user-facing pages
Align SKILL/reference/examples, design docs, CHANGELOG, and feature demos
with theme=dark|light|bw and the rebuild → ext add reload note.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 15:54:47 +08:00
cflmyandCursor dfb27d41dc feat(quantum): Q8 circuit SVG themes and view plot chrome
Fix label/wire overlap with gutter + chip labels; default dark tech palette
with light/bw themes; restyle probs/bloch and darken view plot frames.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 15:46:02 +08:00
cflmyandCursor cf4dbdeade chore: gitignore quantum draw SVG runtime outputs
Keep gold/example .mq.md sources tracked; ignore generated circuit and
state-plot SVGs under tests/ext and examples/quantum-*.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 14:47:19 +08:00
cflmyandCursor f3fe7f268e docs(quantum): Q7c entanglement example and skill summary
Add examples/quantum-entanglement lab, update skill/reference/examples
and public feature page for Q7 density/viz APIs; mark roadmap Q7 complete.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 14:28:11 +08:00
cflmyandCursor 88fe076216 feat(quantum): Q7 density linear algebra and advanced SVG viz
Add density-matrix ops (partial trace, Hermitian eig, Schmidt, Pauli
expect, purity/fidelity, kron) and hinton/city/qsphere/paulivec/multibloch
draw kinds via plugins/quantum ABI, with EN/ZH L1 and gold smokes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 14:23:24 +08:00
cflmyandCursor 4956460773 docs: align skill and docs with ext/web W7+P3 completion
Update Marqdo AI skill (SKILL/reference/examples) with ext/web authoring
rules and API summary; reconcile web-net-capabilities conclusions and blog
checklist with shipped W0–W7+P3 surface.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 13:41:50 +08:00
cflmyandCursor eafa203205 fix(ci): build quantum plugin for public pages demos
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 13:29:05 +08:00
cflmyandCursor 7317a653c7 fix(ci): run public pages via bash script with per-file logging
Move the Build & export loop into scripts/run-public-pages.sh (explicit
bash, skip files without # main) so CI failures show which demo broke.
Also quote remaining time/json italic string args.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 12:27:57 +08:00
cflmyandCursor 0fddc3bf05 fix(ci): skip public mq.md files without # main
Avoid locale-sensitive find -name/?? matching for 工具.mq.md; only run
demos that define # main so import helpers are skipped on all runners.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 12:18:52 +08:00
cflmyandCursor 724a22e48d fix(ci): exclude import helpers with path-scoped ?? pattern
Literal 工具.mq.md in the workflow shell can fail to match on runners;
limit ?? to structure/import so utils/工具 are skipped without dropping
other two-character public docs (数学, 文本, …).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 12:15:20 +08:00
cflmyandCursor 6db3da1cc0 fix(public): quote italic call-arg string literals for pages CI
Bare identifiers inside *…* are variables; quote text args (and var="x")
so marqdo run on public/*.mq.md succeeds. Narrow pages.yml exclude to
utils.mq.md and 工具.mq.md instead of overly broad ??.mq.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:59:10 +08:00
cflmyandCursor 86bfb0648c fix(ci): exclude UTF-8 工具.mq.md from pages site build
The pages workflow used a mojibake exclude name, so import helper
工具.mq.md was executed and failed without a # main entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:44:11 +08:00
cflmyandCursor c6360adccb ext/web P3: RBAC, audit timestamps, FK, gallery, ETag
Complete the remaining network-extension gaps so media sites can
gate by role, auto-stamp rows, declare foreign keys, browse uploads,
and conditional-get downloads.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:37:02 +08:00
cflmyandCursor 2d51f29199 fix(web): restore sitemap_json helper used by ABI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:26:01 +08:00
cflmyandCursor 323449c2c3 ext/web W7: finish network extension polish
Ship Cache-Control, 301 redirects, custom 404/500, sitemap/robots, and
init unique/index so the web capability roadmap is complete for P0–P2.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:25:33 +08:00
cflmyandCursor 6808d56c9d ext/web W6b: WebSocket broadcast and access logging
Add route_ws mode=broadcast with a per-path hub, configure access_log
for stderr request lines, and cover both offline and live gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:13:24 +08:00
cflmyandCursor e3b0314382 ext/web W6: schema migrate and SQLite FTS5 search
Add db.migrate with _marqdo_migrations, db.fts/search (bm25), and gold
covering published filters plus a comments table convention.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:07:24 +08:00
cflmyandCursor a900fd550f ext/web W5: multipart upload receive and download
Add app.upload/download routes over # storage, offline media validate/save
helpers, form type=file + enctype, and curl live gold coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 11:01:18 +08:00
cflmy 034f52b7e7 ext/web W4: Postgres, Redis/memory cache, and S3/file storage drivers
URL-scheme backends keep the same # db CRUD author API; add # cache and

Co-authored-by: Cursor <cursoragent@cursor.com>
# storage with offline memory:/file: gold coverage.
2026-08-28 10:33:05 +08:00
cflmyandCursor e7c9c21a49 ext/web W4c: SEO meta, Markdown render, RSS, pagination UI
Add lib/net markdown_parse, page.meta/paginate and app.route_rss author
APIs, GFM Markdown article bodies, head SEO tags, list pagination nav, and
RSS 2.0 feed routes — keeping tables + class methods as the author surface.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 09:46:16 +08:00
cflmyandCursor be6223f1fb ext/web W1–W3: middleware, data layer, and security hardening
Deliver the interrupted network extension backlog: declarative middleware
(CORS, security headers, gzip, JSON API), SQLite pool/transactions/pagination,
and W3 security (argon2 passwords, CSRF on forms/login, persistent sessions,
CSPRNG ids, login rate limiting). Adds gold smokes and author-facing
hash_password on ext/web.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 09:35:39 +08:00
cflmyandCursor da9fc75b1e Add marqdo-blog example with GFM-table style assembly
Introduce web_style ABI (样式装配) so themes are GFM style tables
(|选择器|属性|值|, optional |媒体| column for @media) assembled by
functions instead of hand-written CSS strings — 文档即代码. The new
examples/marqdo-blog shows a full blog: card grid, dynamic /post/{slug},
tag archive, WebSocket live widget, and session-gated admin CRUD, plus a
smoke test (15 checks) and README.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-26 13:03:55 +08:00
cflmyandCursor 7645dd4c1f Extend network stack: session/auth, WebSocket, cookie/multipart primitives
Add the network-extension wave to lib/net and the web ABI plugin:
- lib/net cookie_parse / multipart_parse host primitives (EN/ZH)
- plugins/web session store + /admin login gate + WebSocket client/server
- ext/web author surface (EN/ZH) for session, auth, ws
- form update flow and page-level validation echo tests
- fix string escapes: \xHH, \u{...}, unknown escapes kept verbatim
- map Chinese component slots (导航/侧栏/页脚) so sidebar renders
- resolve relative static/db paths against the entry script dir (entry_dir)
- new tutorial chapter 14, EN/ZH example sites, and gold tests

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 14:58:46 +08:00
cflmyandCursor 7dfa161422 Document proxy-7890 push fallback for git network failures
Records the working one-shot command (proxy + larger postBuffer) used
when direct push fails with curl 35/56 connection resets.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 14:56:32 +08:00
cflmyandCursor b84e82eb56 Support footnote indexing inside interpolated call args and strings
Parse `` `var`[^key] `` in `` *…* `` segments and quoted strings as an
Index part (chained `` [^a][^b] `` folds into one part) in both the
tree-walk interpreter and the bytecode compiler, and render it back in
`view`. Also make bytecode `_type` stamping always overwrite like the
interpreter does, so child constructors yield the most specific type.

Adds gold/unit tests for interp footnote indexing and a bytecode
inherit-explicit-super case.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 14:45:56 +08:00
cflmyandCursor d7924ea8c7 Add Marqdo Chinese syntax tutorial under doc/tutorial/
13 chapters plus a README index covering syntax, variables, functions,
control flow, collections, objects/inheritance, modules and the CLI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-24 14:45:26 +08:00
cflmyandCursor bd5555afaa Unify bare-identifier semantics in *…* / **…** (Python namespace)
Inside italic/bold code segments every bare word is a variable — including
call arguments and method-call receivers — so text literals must be quoted
and receivers no longer need backticks. A bare dotted callee `a.b` resolves
as a method call when `a` is a local variable, otherwise as a library path
(Python-style unified namespace), in both the tree-walk and bytecode backends.

Migrate ~70 tests plus ext/web, ext/quantum, ext/ai and the example projects
to the new idiom; update SKILL.md and the design docs; fix the web/quantum
example data model (db/index.mq.md). Unit and gold suites pass; only the 3
network-live tests fail offline.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-18 11:20:46 +08:00
cflmyandCursor f275d1e030 Drop redundant backticks in *…* / **…** code segments
Value-expression variables inside *…* / **…** segments no longer need
backticks (the segment markers already mark code). Drop trailing spaces
and de-tick value-expression variable names in tests and skill docs;
keep backticks for string interpolation, call args, and method receivers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 17:22:45 +08:00
cflmyandCursor 1bf414c745 Harden plan parent: first DECISION, soft patches, and empty-tool step retry.
Stop import/fence prompt breakage, prefer modern workbook imports, accept
common patch shapes, and recover when workers CALL disallowed tools.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-16 12:07:17 +08:00
cflmyandCursor ecc92f473a Unify frontmatter imports as import bind:target and drop > imports.
`import json:lib/json.mq.md` binds file libraries; `import fmt:time.format`
binds member short names (replaces `> use`). Legacy `> path.mq.md` / `> use`
now hard-error with a hint. Migrates repo docs, skills, ext, lib, public, examples,
man-test and tests; adds a negative gold and updates view/catalog rendering.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-13 10:03:21 +08:00
cflmyandCursor 56b9bfa5a3 Fix subtask overview pages so tables are not parsed as statements.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 15:37:26 +08:00
cflmyandCursor 209dc4fc5d Fix public docs run errors and optional gate matrix binding.
Markdown list dashes were parsed as loops; quantum.gate name=H failed because plugin bind required matrix. Repair user-site pages and redeploy-ready sources.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 15:36:58 +08:00
cflmyandCursor db27f5c8d3 Fix release workflow VSIX output path by creating dist first.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 15:03:26 +08:00
cflmyandCursor 106e1d5136 Release Marqdo 0.2.0 with official extension libraries.
Document ext add for llm/agent/web/quantum, ship release notes and installer assets for the extension-focused release.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 14:52:13 +08:00
cflmyandCursor d269ccb7e7 Add formula-matrix custom gates and fix Variables modal in view.
Parse $$ pmatrix/[[…]] into executable matrices for quantum.gate matrix=, and make the vars panel open a rich modal without breaking the page script.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 14:40:55 +08:00
cflmyandCursor 505d478724 Add amplitude_damping teaching noise for quantum run trajectories.
Extends Q5 with a dissipative jump channel and EN/ZH golds so docs can show energy loss, not only Pauli flips.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 13:59:51 +08:00
cflmyandCursor b842644686 Add gate matrix heatmaps, GHZ example, and ZH quantum golds.
Completes the Q4 matrix-draw follow-up and mirrors author/noise APIs in Chinese smokes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 13:57:13 +08:00
cflmyandCursor 60d570756f Add quantum Q5 teaching noise and finish author-facing circuit APIs.
Barrier/measure/append/state plus bitflip/depolarizing run trajectories let docs show noisy sampling without a full open-system simulator.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 13:46:56 +08:00
cflmyandCursor eea6fe1a0e Land quantum Q4 visuals and gate Stream to LLM/agent imports.
Add probs/Bloch draw kinds and matches_matrix, plus feature docs; hide the view Stream panel unless llm/agent is imported, and stop rewriting method names like 绘图 through host_plot aliases.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 12:36:51 +08:00
cflmyandCursor 25b7be6739 Add usable table/map stdlib with put, and show run bindings in view.
Authors can update nested collections via table.put/表.改 instead of json.set chains; view’s right rail adds collapsible Variables from the entry env.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 11:49:48 +08:00
cflmyandCursor 91d51f3f0a Treat bare ids as variables in italic/bold, and land table/quantum follow-ups.
Prefer-var parsing in *…* / **…* (quoted strings for text), table cell expressions, digit map footnotes, and quantum steps/draw with updated golds and LLM sources.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 11:21:23 +08:00
cflmyandCursor ff6425e6c5 Add quantum Q2 gate set, seeded run, and EN/ZH L1 APIs.
Expand the simulator beyond H/CX with Y/Z/S/T/R*/CZ/SWAP and deterministic shot sampling so authors can write full circuits and reproducible measurement checks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 10:28:41 +08:00
cflmyandCursor e853b00fe2 Update Cargo.lock for marqdo_plugin_quantum workspace member.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 10:24:38 +08:00
cflmyandCursor 4a7a33e29a Add ext/quantum Q0–Q1: ABI simulator with H/CX and Bell smoke.
Register the quantum catalog package, English/Chinese circuit APIs, and a state-vector plugin that verifies Bell-state probabilities.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 10:24:33 +08:00
cflmyandCursor 25b6b86c26 Document ext/quantum design and implementation roadmap.
Lock author API, simulator bounds, view SVG plan, and Q0–Q5 phases before coding the ABI plugin.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 10:21:07 +08:00
cflmyandCursor e4be0b0492 Ignore local web SQLite fixture directories.
Keep smoke and example runtime databases out of the working tree status.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:29:14 +08:00
cflmyandCursor db6158e9e2 Polish admin UI and add app.static file serving.
Admin gets a sidebar shell, flash messages, empty states, and forms in-chrome; listen can nest a public directory under /static (or a custom mount).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:26:30 +08:00
cflmyandCursor a0c56fa352 Add Chinese web-site example and 网页.mq.md smoke.
Mirrors the English sample on port 18082 using only Chinese class APIs for page, db, form, and app.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:20:34 +08:00
cflmyandCursor c181b74a88 Implement db.select where= with simple map and filter-table ops.
Equality maps and |字段|操作|值| rows (including like) feed parameterized AND clauses; admin smoke resets the SQLite sequence for stable ids.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:16:03 +08:00
cflmyandCursor 02b3dfab48 Resolve /_part against home or routed pages.
Stamp _route on app.route pages and emit {path}/_part/{id} slot sources so partials refresh the correct page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:05:50 +08:00
cflmyandCursor b09538d242 Embed forms in page main via compose_form.
listen collects forms from home and routed pages so mount_form is optional; validation errors re-render the owning page shell.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:02:37 +08:00
cflmyandCursor 0dcd9e3d03 Add app.route for mounting extra pages by path.
Register GET routes from assembled pages; sample /about + offline smoke.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 08:57:07 +08:00
cflmyandCursor 897db76aa7 Add admin CRUD via schema-derived forms sharing validate/submit.
Infer fields from SQLite table_info; serve /admin/{table}/new|edit|delete.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 08:55:06 +08:00
cflmyandCursor ee019fb1c2 Add ext/web forms (design §5.5): fields, validate, submit, GET|POST /_form.
Also fix static links (URLs with dots) being misread as db fields.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 17:55:29 +08:00
cflmyandCursor 9599303c4c Rewrite ext/web around tables and class methods.
Drop bag/scaffold glue and rebuild the web plugin for compose, SQLite CRUD, and listen, with call_lib_path support and a §4 English site sample.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 15:06:39 +08:00
cflmyandCursor 8041a2274c Add ext/web with table-driven pages and polished admin CRUD.
Ship the web L1/plugin stack (bind tables, variable-named db.init, live render) and tighten the admin UI with sidebar, toolbar, forms, and activity log.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 11:42:17 +08:00
cflmyandCursor ab8ea8438f Add local n-gram near match for OKF agent-kb reuse.
Sparse bigram cosine closes near-duplicate goal fragmentation; soft_match parents now judge ranked scored candidates instead of a flat task list.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 10:07:03 +08:00
cflmyandCursor f240bdf156 Stream child agent events into view SSE without jumpy drip.
Forward quiet file-subtask EventBus frames while wait blocks, coalesce
DOM updates per rAF, and keep one SSE write per event so Stream stays
live during child work instead of freezing or dumping bursts.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 09:45:08 +08:00
cflmyandCursor ff84c43c10 Add OKF soft match, CALL tool streaming, and lib whitelist dispatch.
Canonicalize/alias lookup and optional soft_match parent REUSE cut kb
fragmentation; stream tool_start/end for Plan-and-Move visibility; allow
safe CALL:lib.* without FC.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 09:26:59 +08:00
cflmyandCursor dbb2765553 Add parent Plan-and-Move: CALL/READ tools and quiet I/O capture.
Give the plan loop actionable observation (source excerpts, stderr/stdout tails) and short stop rules so the parent can inspect children and use stdlib helpers instead of inventing long patches.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 09:11:15 +08:00
cflmyandCursor 7e3b193d49 Stop plan loops after child success; harden stream UX.
Prefer DONE + runtime solidify when the child already returned a value, compact parent observations, drop the SSE 8MiB raw-buffer abort, and drip-stream the view panel via POST /api/run.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 17:25:24 +08:00
cflmyandCursor 2a9fceb51c Land OKF aliases, view SSE, workbook nav, and explicit parent ctor.
Complete the core agent roadmap: soft KB hits via Task aliases, EventBus-backed view streaming, D4 writeback/workbook navigation, and I3 explicit-super without implicit auto-super.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 11:58:26 +08:00
cflmyandCursor d1ddb74235 Plan parent-first decompose, reasoning streaming, TTY input editing.
Reorder non-hit plan pipeline so the parent decomposes before spawning the child, stream DeepSeek thinking (reasoning_content) to TTY, and add Unicode-aware line editing for interactive input to fix CJK backspace corruption.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 11:45:58 +08:00
cflmyandCursor b6bb42e460 Implement streaming S0-S2: SSE complete, step/plan events.
Add net/llm SSE primitives and optional stream/echo/trace on step and plan so callers can watch deltas and rounds without changing final return values.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 11:03:04 +08:00
cflmyandCursor 5456d9ff83 Implement object inheritance: # Child = > Parent (I0-I2)
- Parse `# Child = > Parent` object decls (base must be a simple
  name after `>`; dotted bases and `# Foo = 1` are diagnostics).
- Validate in load: unknown base types and cyclic inheritance (A → B → A)
  fail with line/col.
- Method resolution walks the base chain (most specific first) on both
  tree and bytecode backends; `_type` stays the child name; same-name
  child ## overrides the parent.
- Add inherit.rs, wire Program.object_bases, gold fixtures
  (inherit-parent-method / inherit-override + cycle/unknown-base/bad-rhs)
  and public 09-inherit demo pages. Docs: objects.md, markdown-mapping,
  roadmap, skill.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 10:01:05 +08:00
cflmyandCursor a23fdedfa2 Implement table semantic T0-T4: map/records/footnote get
- 1-col table stays a List; >=2-col becomes a column-oriented Map
  (1 data row -> scalar values, >=2 -> Map of Lists).
- First header @ / 行 / row opts into row-oriented List of Maps
  (marker column excluded); missing field cols is a diagnostic.
- Footnote index: `xs`[^1] (1-based list), `m`[^key] (map key), chained.
  Errors for [^0], out-of-range, missing key, duplicate headers.
- foreach walks list items or map keys; Map values now display as {k: v}.
- Sync both tree and bytecode backends; new gold + error fixtures, docs
  (markdown-mapping, roadmap, skill, public), and public 07/08 pages.
- Fix subtask-spawn fixture return value to child_ok (child-ok parses as
  subtraction).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-10 09:50:21 +08:00
cflmyandCursor 3463628165 Document roadmap plans for soft OKF match, streaming, syntax, and new exts.
Capture near-match, agent streaming, inheritance, table/map footnotes, plus
planned web and quantum extensions with ABI and ext-cli install conventions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-09 10:29:18 +08:00
cflmyandCursor d1b33c78c6 Make file subtasks return #main value and expose it as plan.result.
Quiet spawn still hides child stdout; workbooks solidify to **returns**, agent-kb lives in the plugin, and multi-step follows OKF file relay rather than print-based answers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 17:53:14 +08:00
cflmyandCursor fbece725e1 Enable default writeback on agent step and lock the plan design.
Document multi-step workbooks in ext-agent-plan, and make step/单步 persist ok/error slots unless writeback is turned off.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:47:34 +08:00
cflmyandCursor 1f23e2ed93 Add module namespaces and harden L1/agent after the import redesign.
Bind imports to library names with bare path calls (and use), forward optional host args through mq wrappers, stabilize writeback replacement newlines, and document the M1/M2 decisions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 13:28:32 +08:00
cflmy 99132ac8fc update 2026-08-07 10:06:33 +08:00
cflmy 118448538c update 2026-08-07 09:50:03 +08:00
cflmyandCursor 2e65c055b8 Release v0.1.2: embedded stdlib, docs, and extension branch policy.
Embed lib/*.mq.md in binary; marqdo version --check; public writeback/subtask pages; restore /vscode-extension/ ignore. VSIX built from branch vscode-extension only (see doc/design/vscode-extension-commit.md).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 09:41:53 +08:00
cflmyandCursor 3da7b276d3 Extend subtask stdlib for file, function, and foreign concurrency.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 09:41:22 +08:00
cflmyandCursor 63e5be80ab Add v0.2 surface syntax, writeback/subtask stdlib, and view input deferral.
Use + for parameters, ordered-list branches, backtick identifiers, and quoted strings with escapes. Add writeback and subtask host libs, optional parameter defaults, narrative-bold comment fix, and defer view execution until preset stdin is submitted.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 17:52:33 +08:00
cflmyandCursor 92d88fe761 Move LLM and agent into ext/ai with host tool catalog and call_fn.
Consolidate official AI extensions under ext/ai/, add agent history/context host APIs, dynamic call_fn, and a first-pass TOOL:name loop so runbooks can list zero-arg tools in a table.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 15:28:39 +08:00
cflmyandCursor c4ffb9473f Extend ext/agent with skill match/assign and multi-column tables.
Compose ext/llm, add ABI match_skill/bump_load, map-valued GFM tables, and agent-assign gold coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 13:46:34 +08:00
cflmyandCursor 3a7e11c995 Add ext/agent layout framework, ext CLI, and docs catch-up.
Ship ABI agent plugin helpers, marqdo ext list/add/remove, and document the agent development roadmap (compose LLM, match/assign).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 13:31:25 +08:00
cflmyandCursor b0c777c480 Add versioned C ABI for optional native plugins.
Load .dll/.so/.dylib at runtime via libloading, register JSON-wired functions, and ship a Rust cdylib demo with lib/plugin wrappers and gold coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 12:45:18 +08:00
cflmyandCursor b00b018056 Add object primitives, official ext/llm, and HTTPS/dotenv platform.
Introduce # objects with ## methods (handles + ` x.method `), ship OpenAI-compatible ext/llm, and upgrade net/sys for HTTPS headers and dotenv loading.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-06 11:53:14 +08:00
cflmy b974f10c6e Add Marqdo AI skill for correct .mq.md authoring.
Ship a portable skills/marqdo package (and Cursor mirror) so agents follow markup-as-syntax rules, stdlib imports, and the run-fix loop.
2026-08-05 17:36:21 +08:00
cflmyandCursor 72777a8c74 Release v0.1.1: debug page Logo branding and packaging notes.
Bump crate version, use official Logo for marqdo debug favicon/brand, and document VS Code extension assets in the Windows release script.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 17:17:00 +08:00
cflmyandCursor e08cd839be Ignore vscode-extension on main and document the extension branch.
Point editors to the vscode-extension branch for host work, mirroring the public/gh-pages split.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 16:25:38 +08:00
cflmyandCursor 5309848292 Fix README syntax for function-end HR and document catalog CLI.
Correct ---/***/empty-return conventions and spell out marqdo catalog/sync for OKF-style YAML generation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 16:01:22 +08:00
cflmyandCursor 1271aafcdd Package release zips with stdlib and document bare-exe limits.
Ship recommended marqdo.exe+lib bundle, a separate stdlib zip, and clear release notes that the standalone exe does not include lib/.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 15:50:10 +08:00
cflmyandCursor 54a507d906 Ship v0.1.0: dedicated debug host, view outline, code-as-docs README.
Add marqdo debug (breakpoints/step/locals), restore view as docs with function search, and emphasize OKF-aligned knowledge-base direction.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 15:40:29 +08:00
cflmyandCursor ea17ae1074 Add Windows release packaging so tagged releases ship binaries.
Upload exe/zip via CI on v* tags and provide a local release-windows script.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 13:04:06 +08:00
cflmyandCursor fe9046cecf Sync Cargo.lock package version to 0.0.4.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 12:52:43 +08:00
cflmyandCursor b5e9d15391 Add foreign stdlib with code values and ship v0.0.4.
Bind `lang fences like formulas, run them via local interpreters, polish live-view code cards, and refresh bilingual welcome docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 12:50:01 +08:00
cflmyandCursor dcd0cdb8f7 Add math stdlib with formulas/plots and polish the docs view.
Ship Num/Formula runtime, bilingual math libs, SVG plots with axes/grid, and view UX for collapsible folders plus centered plots.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 11:30:47 +08:00
cflmyandCursor a53ebb65ee Add host stdlib modules and unify view/run capabilities.
Ship fs/time/sys/json/net L1 libs (plus existing text/table), default-on host caps with soft exit under view, bilingual public/stdlib docs, and design notes for deferred math/foreign.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 10:03:54 +08:00
cflmyandCursor a5d30c00b3 Add bilingual public docs, keyword aliases, and frontmatter stdin for view.
English/Chinese user pages sit side by side; L0 builtins and lib/ text|表 dual APIs land with gold coverage. Capture/view input demos use stdin:/输入: so static export and first page load succeed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 09:14:26 +08:00
cflmyandCursor fd36b92224 Emit structured JSON --trace-eval events with source spans.
Tree walk logs enter_fn/stmt/leave_fn; bytecode logs op events for print/input/call/return, paving the way for view debug pause hooks.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 17:37:45 +08:00
cflmyandCursor 30cd39fd8f Add diagnostics spans, CLI/view input feeding, and len/str/int builtins.
Unify bytecode errors with path:line:col, support --stdin-file and live view preset stdin, and ship the S0 standard library with gold coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 17:26:09 +08:00
cflmyandCursor 31a4b69bbd Render view comments as Markdown with pulldown-cmark.
Comment cards now turn links, code, and emphasis into real HTML instead of escaped source text.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 16:14:34 +08:00
cflmyandCursor 7848180454 Release v0.0.3: function end, paragraph comments, logo, and welcome polish.
End nested functions with ---/***/empty return; blank-line comment paragraphs in lex and view; brand favicon/logo; bump crate to 0.0.3.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 16:03:10 +08:00
cflmyandCursor 69fecaeaab Add script to publish GitHub releases with Windows binaries.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 15:11:12 +08:00
cflmyandCursor 04098db74c Release v0.0.2: bump crate version after public site and layout consolidation.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 15:08:32 +08:00
cflmyandCursor 96a7c6ce76 Consolidate layout: tests fixtures, public user docs, and view site.
Move gold samples under tests/, put executable user docs in public/, restyle view, and add catalog plus gh-pages publish workflow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 14:49:44 +08:00
132 changed files with 6454 additions and 7205 deletions

No files matched your search

Executable
+2
View File
@@ -0,0 +1,2 @@
* text=auto
*.sh text eol=lf
+34
View File
@@ -0,0 +1,34 @@
---
name: 功能、缺陷或迁移
about: 记录唯一负责仓库、可复现候选与验收
---
## 问题与所有权
- 责任组件(全局 ID / 仓库):
- 类型:bug | missing capability | contract change | migration
- 影响消费者(ID / 关联工单):
- 权威合同链接:
## 可复现的候选组合
- 根 / 领域 / 组件 SHA:
- CLI、Worker、Stdlib、依赖制品 SHA-256 与平台:
- 环境与工具链:
- 最小 fixture / 命令 / 实际结果:
- 预期结果:
## 修复范围
- 必须:
- 禁止:兼容旧协议、复制实现、无关重构、扩大权限等
- 上游阻塞:<工单链接或无>
## 验收
- 正例:
- 负例 / 授权与安全边界:
- 回归 / 性能条件:
- 组件 CI:
- 领域 / 消费者组合测试:
- 修复提交与制品证据:
+25
View File
@@ -0,0 +1,25 @@
## 工单与责任仓库
- 责任工单:
- 唯一责任仓库与组件 ID:
- 本次变更是否涉及 domain、gitlink、`planned → active` 或公共合同:<是/否,说明>
## 组合与证据
- 组件提交(C2)/ 领域组合(B2)/ 根组合(A2):
- C1/C2/C3 CI 链接:
- 可复现命令、平台、依赖制品摘要:
- 本次未运行 / UNVERIFIED 的项:
## 分层与边界检查
- [ ] 变更落在唯一责任仓库,聚合仓未引入生产实现
- [ ] 未创建占位 gitlink 或伪造 active `entry`;planned 不计入验收
- [ ] 公共合同变更与实际消费者配对候选,未引入旧协议 fallback
- [ ] 主仓库只更新精确 gitlink、治理文件与集成脚本,未借机重构无关组件
- [ ] 未在根或聚合脚本中加入 workaround、复制协议或绕开权限
## 发行与回滚
- 公共协议 / 制品影响:
- 旧基线或回滚方式(恢复上一组已接受 gitlink):
Regular → Executable
+8 -12
View File
@@ -1,13 +1,9 @@
/target/
**/*.rs.bk
.idea/
.vscode/
*.pdb
.DS_Store
# Python spike venv (local)
spike/.venv/
spike/__pycache__/
spike/.pytest_cache/
.env
.env.*
/.migration-work/
/.integration-work/
/__pycache__/
**/__pycache__/
*.pyc
# Local build/cache/scratch (DSH workspace tooling)
/.build/
+102
View File
@@ -0,0 +1,102 @@
[submodule "cli"]
path = cli
url = https://git.cflmy.cn/cflmy/marqdo-cli.git
[submodule "tests/conformance"]
path = tests/conformance
url = https://git.cflmy.cn/cflmy/marqdo-extension-conformance.git
[submodule "tools/view"]
path = tools/view
url = https://git.cflmy.cn/cflmy/marqdo-view.git
[submodule "tools/knowledge"]
path = tools/knowledge
url = https://git.cflmy.cn/cflmy/marqdo-knowledge.git
[submodule "tools/prove"]
path = tools/prove
url = https://git.cflmy.cn/cflmy/marqdo-prove.git
[submodule "tools/lint"]
path = tools/lint
url = https://git.cflmy.cn/cflmy/marqdo-lint.git
[submodule "extensions/ai"]
path = extensions/ai
url = https://git.cflmy.cn/cflmy/marqdo-ext-ai.git
[submodule "extensions/archive"]
path = extensions/archive
url = https://git.cflmy.cn/cflmy/marqdo-ext-archive.git
[submodule "extensions/browser"]
path = extensions/browser
url = https://git.cflmy.cn/cflmy/marqdo-ext-browser.git
[submodule "extensions/cache"]
path = extensions/cache
url = https://git.cflmy.cn/cflmy/marqdo-ext-cache.git
[submodule "extensions/crypto"]
path = extensions/crypto
url = https://git.cflmy.cn/cflmy/marqdo-ext-crypto.git
[submodule "extensions/database"]
path = extensions/database
url = https://git.cflmy.cn/cflmy/marqdo-ext-database.git
[submodule "extensions/datetime"]
path = extensions/datetime
url = https://git.cflmy.cn/cflmy/marqdo-ext-datetime.git
[submodule "extensions/document"]
path = extensions/document
url = https://git.cflmy.cn/cflmy/marqdo-ext-document.git
[submodule "extensions/engineering"]
path = extensions/engineering
url = https://git.cflmy.cn/cflmy/marqdo-ext-engineering.git
[submodule "extensions/http"]
path = extensions/http
url = https://git.cflmy.cn/cflmy/marqdo-ext-http.git
[submodule "extensions/linalg"]
path = extensions/linalg
url = https://git.cflmy.cn/cflmy/marqdo-ext-linalg.git
[submodule "extensions/math"]
path = extensions/math
url = https://git.cflmy.cn/cflmy/marqdo-ext-math.git
[submodule "extensions/mcp"]
path = extensions/mcp
url = https://git.cflmy.cn/cflmy/marqdo-ext-mcp.git
[submodule "extensions/quantum"]
path = extensions/quantum
url = https://git.cflmy.cn/cflmy/marqdo-ext-quantum.git
[submodule "extensions/regex"]
path = extensions/regex
url = https://git.cflmy.cn/cflmy/marqdo-ext-regex.git
[submodule "extensions/security"]
path = extensions/security
url = https://git.cflmy.cn/cflmy/marqdo-ext-security.git
[submodule "extensions/storage"]
path = extensions/storage
url = https://git.cflmy.cn/cflmy/marqdo-ext-storage.git
[submodule "extensions/web"]
path = extensions/web
url = https://git.cflmy.cn/cflmy/marqdo-ext-web.git
[submodule "extensions/websocket"]
path = extensions/websocket
url = https://git.cflmy.cn/cflmy/marqdo-ext-websocket.git
[submodule "stdlib/collections"]
path = stdlib/collections
url = https://git.cflmy.cn/cflmy/marqdo-std-collections.git
[submodule "stdlib/core"]
path = stdlib/core
url = https://git.cflmy.cn/cflmy/marqdo-std-core.git
[submodule "stdlib/data"]
path = stdlib/data
url = https://git.cflmy.cn/cflmy/marqdo-std-data.git
[submodule "stdlib/encoding"]
path = stdlib/encoding
url = https://git.cflmy.cn/cflmy/marqdo-std-encoding.git
[submodule "stdlib/fs"]
path = stdlib/fs
url = https://git.cflmy.cn/cflmy/marqdo-std-fs.git
[submodule "stdlib/io"]
path = stdlib/io
url = https://git.cflmy.cn/cflmy/marqdo-std-io.git
[submodule "stdlib/net"]
path = stdlib/net
url = https://git.cflmy.cn/cflmy/marqdo-std-net.git
[submodule "stdlib/system"]
path = stdlib/system
url = https://git.cflmy.cn/cflmy/marqdo-std-system.git
[submodule "stdlib/text"]
path = stdlib/text
url = https://git.cflmy.cn/cflmy/marqdo-std-text.git
+40
View File
@@ -0,0 +1,40 @@
when:
event: [push, pull_request, manual]
steps:
layout:
image: rust:1.100-bookworm
commands:
- apt-get update && apt-get install -y --no-install-recommends ca-certificates git python3
- python3 scripts/check-layout.py
- python3 -m unittest discover -s tests/integration
- git submodule update --init
- |
set -eu
domains="$(python3 scripts/check-layout.py --domain-paths)"
for domain in $domains; do
git -C "$domain" submodule update --init
done
- python3 scripts/check-layout.py --checkouts
candidate:
# Match the Linux/glibc environment already used by View for the RC.4 artifact.
image: mcr.microsoft.com/playwright:v1.49.0-noble
depends_on: [layout]
commands:
- |
set -eu
for attempt in 1 2 3; do
if apt-get -o Acquire::By-Hash=force -o Acquire::Retries=3 update --error-on=any; then
break
fi
if [ "$attempt" -eq 3 ]; then
exit 1
fi
sleep 15
done
apt-get -o Acquire::Retries=3 install -y --no-install-recommends ca-certificates curl git python3 python3-jsonschema build-essential
curl -fsSL --retry 3 https://sh.rustup.rs -o /tmp/marqdo-rustup.sh
sh /tmp/marqdo-rustup.sh -y --profile minimal --default-toolchain 1.100.0 --no-modify-path
export PATH="$HOME/.cargo/bin:$PATH"
bash scripts/integration.sh
+10
View File
@@ -0,0 +1,10 @@
# Marqdo 维护指引
1. 从 [各仓库任务](docs/REPOSITORY-TASKS.md)、[组件目录](components.toml) 与 [架构边界](docs/ARCHITECTURE.md) 确定**唯一**责任仓库:功能缺陷在功能仓库,领域合同/组合在领域聚合仓库,gitlink、跨领域集成、发行组合与治理在主仓库。主仓库和聚合仓库不实现子组件业务。
2. 治理树最多两级:根 → 领域聚合(`kind = "domain"`)→ 功能组件。每个组件只有一个父级,全局 ID 与权威远端唯一,领域聚合仓库只做治理、合同、示例和组合验收。已发布的 `planned` 仓库可以挂载真实 gitlink。激活时登记实际 `entry`,只有通过验收的 active 组件计入完成率。
3. 找到或建立责任仓库的工单,按 `.gitea/ISSUE_TEMPLATE/change.md` 记录目标、当前提交、最小复现、公共契约、影响消费者和验收命令。跨仓库阻塞在上游开关联工单,并在消费者记录回归条件。不要按错误最终显示的仓库定责,找第一个违反公开合同的所有者。
4. 在责任仓库独立修改、构建和测试。需要调整公共语义时,在 CLI 提交 ADR;调整 Web 作者面语义时,只在 `marqdo-ext-web` 的 [WEB-DESIGN 合同](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md) 走 ADR,并与实际消费者(Design/Preview)同候选验证;不得并列维护第二份现行规范或旧协议 fallback。
5. 逐层晋升:功能提交 C2 通过组件 CI → 领域 PR 更新 gitlink 至 C2 并通过领域 CI(B2)→ 主仓库 PR 更新领域 gitlink 至 B2 并通过根递归校验与受影响组合验收(A2)。先推送子仓库提交,再在主仓库提交精确 gitlink;区分组件 CI、公共契约 CI 和生态 CI 证据。以 [开发流程](docs/DEVELOPMENT.md) 为准。
6. 新接入组件先核对公开 API、直接依赖、独立入口和实际测试。空仓在 [迁移台账](docs/MIGRATION.md) 中保持 `planned`;Web 领域的 Design/Preview 子组件记录在 `marqdo-ext-web` 自己的 `components.toml`,根目录不登记其后代路径。
7. 记录 FAIL 和 UNVERIFIED 的具体环境、命令和日志。只有实际通过且匹配候选 SHA 的证据才可用于集成与发行;模拟、mock 或原型测试不能冒充生产验收。
8. Web 边界硬约束:不新增 CLI 核心语法或 Web 专属关键字;不复制 Markdown/语言解析器;默认不允许 HTML 注入、业务 JS 或真实网络/数据库/认证;预览是有限确定性解释,生产实现由成熟框架在目标应用仓库承担。
Generated
-447
View File
@@ -1,447 +0,0 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "anyhow"
version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ascii"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
[[package]]
name = "assert_cmd"
version = "2.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed72493ac66d5804837f480ab3766c72bdfab91a65e565fc54fa9e42db0073a8"
dependencies = [
"anstyle",
"bstr",
"doc-comment",
"predicates",
"predicates-core",
"predicates-tree",
"wait-timeout",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bstr"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"
dependencies = [
"memchr",
"regex-automata",
"serde_core",
]
[[package]]
name = "chunked_transfer"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
[[package]]
name = "clap"
version = "4.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "clap_lex"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "difflib"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
[[package]]
name = "doc-comment"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "780955b8b195a21ab8e4ac6b60dd1dbdcec1dc6c51c0617964b08c81785e12c9"
[[package]]
name = "float-cmp"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
dependencies = [
"num-traits",
]
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "log"
version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
[[package]]
name = "marqdo"
version = "0.1.0"
dependencies = [
"anyhow",
"assert_cmd",
"clap",
"predicates",
"thiserror",
"tiny_http",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "normalize-line-endings"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "predicates"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68b87bfd4605926cdfefc1c3b5f8fe560e3feca9d5552cf68c466d3d8236c7e8"
dependencies = [
"anstyle",
"difflib",
"float-cmp",
"normalize-line-endings",
"predicates-core",
"regex",
]
[[package]]
name = "predicates-core"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144"
[[package]]
name = "predicates-tree"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2"
dependencies = [
"predicates-core",
"termtree",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.3",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "termtree"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683"
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tiny_http"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
dependencies = [
"ascii",
"chunked_transfer",
"httpdate",
"log",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "wait-timeout"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11"
dependencies = [
"libc",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
-22
View File
@@ -1,22 +0,0 @@
[package]
name = "marqdo"
version = "0.0.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
readme = "README.md"
repository = "https://github.com/cflmy/marqdo"
[[bin]]
name = "marqdo"
path = "src/main.rs"
[dependencies]
anyhow = "1"
clap = { version = "=4.4.18", features = ["derive"] }
thiserror = "1"
tiny_http = "0.12"
[dev-dependencies]
assert_cmd = "=2.0.14"
predicates = "=3.1.0"
Regular → Executable
View File
File mode changed.
+113 -53
View File
@@ -1,73 +1,133 @@
# Marqdo
# Marqdo
**代码即文档。文档即代码。**
**Marqdo 是一门以 Markdown 为源文档的编程语言。** 用 `.mq.md` 可以把业务规则、公式、解释和可执行步骤写在同一份文档中。读者用 Markdown 阅读器查看正文,开发者用 Marqdo 检查、运行和验证其中的程序。这个仓库维护生态组件的集成、验收和发行入口。
Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程序。
生态治理采用有限分层:主仓库固定领域聚合仓库,领域聚合仓库固定本领域功能仓库,最多两级 Gitlink。主仓库和聚合仓库只做治理、组合与验收,不实现子组件业务;Web 领域把设计文档直接作为原型与工程交付的源材料,详见 [架构边界](docs/ARCHITECTURE.md)。
语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 示例布局:[examples-and-tests.md](doc/design/examples-and-tests.md) · 浏览:[view.md](doc/design/view.md) · 示例:[examples/](examples/)
## 为什么开发 Marqdo
---
规则通常写在说明文档里,实现放在脚本里,结果再写进报告。三份内容分开维护后,读者很难确认某个结果用了哪条规则,也很难重新验证。Marqdo 让解释和计算随同一份源文档修改、评审和运行。它适合写带示例的算法说明、可重跑的分析流程,以及需要交代验证过程的知识文档。
## 语法速览(v0.1)
## 主要特性
| 标记 | 含义 |
|------|------|
| 无标记行 | 注释 |
| `*…*` | 程序语句 |
| `**…**` | **返回值**(架构) |
| `> print …` 等 | 输出等副作用 = **普通函数**,非架构标记 |
| `#` / `##` | 函数与作用域 |
| `+` / `1.` | 分支(臂头单独 `*` = else) |
| `-` | 循环(头下纯名则为形参) |
| 表格 | 集合 |
| `---` / `***` | 可选:框住分支/循环(不强制) |
- **Markdown 原生**。文档保留 CommonMark/GFM 的结构,并支持公式。在 `.mq.md` 中,以 `@exec` 标明可执行区,以 `@knowledge` 标明说明与知识区。正文可以直接阅读。
- **先检查,再运行**。`marqdo check` 静态检查语法与调用,`--refs` 检查文档引用。Analysis 提供结构化分析结果,供编辑器和独立工具使用。
- **可观察的运行**。Rust 解释器显式运行文档代码,Observation 记录执行事件与结果。文件、网络、进程等外部操作受运行模式与能力授权约束。
- **可组合的生态**。基础发行包含标准库。程序可以通过锁文件固定包与领域扩展的来源和摘要。阅读、知识索引、证明和静态诊断由独立工具提供。
```markdown
# main
## 快速开始
> print text=Hello World!
从 [CLI 发行页](https://git.cflmy.cn/cflmy/marqdo-cli/releases) 下载适合平台的发行包。把解包目录加入 `PATH`,保持 CLI、Worker 和旁置 `stdlib/` 的目录结构。将下面的内容保存为 `hello.mq.md`。
## 加一
- n
````markdown
# 问候示例
**`n` + 1**
这一节说明程序的用途。下方函数由 CLI 执行。
## @exec main
`params()`
`打印("你好,Marqdo")`
````
```sh
marqdo check hello.mq.md
marqdo run hello.mq.md
```
---
## 理念
1. 叙述默认安全(无标记 = 注释)。
2. 返回是架构;打印只是函数。
3. 依赖清单由工具生成(OKF 风格),不是手填配置。
4. **正经解释器(Rust)**:词法/行分类 → 递归下降语法 → 语义 → 树遍历 → 日后字节码;**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md) 与 [依赖说明](doc/design/dependencies.md)。
---
## 现状
- 映射 v0.1:[markdown-mapping.md](doc/design/markdown-mapping.md)
- 解释器路线图:[interpreter.md](doc/roadmap/interpreter.md)
- **Phase I(树遍历)已通**:`examples/structure/` 与 `examples/keywords/` 金样例均可 `marqdo run`
- **view**:`marqdo view examples` 按 AST 浏览结构与输出
- 依赖(Rust,无 Flex/Bison):[dependencies.md](doc/design/dependencies.md)
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md)
```bash
cargo run -- run examples/structure/hello.mq.md
cargo run -- run examples/structure/hello.mq.md --backend bytecode
cargo run -- view examples --no-open
```text
你好,Marqdo
```
当前发布:**v0.0.1**(Phase I 树遍历 + `view` + M5 字节码原型)。M5 见 [bytecode.md](doc/design/bytecode.md);errors 见 `examples/errors/`。
[CLI 使用指南](https://git.cflmy.cn/cflmy/marqdo-cli) · [语言规范](https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/master/spec/mapping.md)
## 仓库与职责
---
### 已接入的核心和工具
## 命名
| 仓库 | 职责 |
| --- | --- |
| [marqdo](https://git.cflmy.cn/cflmy/marqdo) | 生态主仓库,维护仓库索引、固定提交组合、跨仓库验收与发行 |
| [marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) | 语言规范、Rust 解释器、CLI、运行权限和公开协议 |
| [marqdo-extension-conformance](https://git.cflmy.cn/cflmy/marqdo-extension-conformance) | 用冻结的真实 CLI 独立验收包、插件、Provider、Foreign 和 Tool |
| [marqdo-knowledge](https://git.cflmy.cn/cflmy/marqdo-knowledge) | 使用公开 Analysis 编译、索引和检索知识文档 |
| [marqdo-prove](https://git.cflmy.cn/cflmy/marqdo-prove) | 处理证明依赖、Lean 证书与独立重放 |
| [marqdo-view](https://git.cflmy.cn/cflmy/marqdo-view) | 阅读和预览文档、显示执行观察、静态导出 |
| [marqdo-lint](https://git.cflmy.cn/cflmy/marqdo-lint) | 静态规则、诊断定位与显式修复 |
**Marqdo** = Marq(Markdown)+ do(执行)
### 独立产品
## 许可
| 仓库 | 职责 |
| --- | --- |
| [marqdo-site](https://git.cflmy.cn/cflmy/marqdo-site) | 官网、入门文档、静态站点构建与托管 |
| [marqdo-vscode](https://git.cflmy.cn/cflmy/marqdo-vscode) | VS Code 文件关联、编辑体验、CLI 集成与 VSIX 发布 |
[Apache License 2.0](LICENSE)
### 标准库
标准库组件负责低层通用能力,验收后共同组成基础发行的标准库 Bundle。`stdlib/` 的子模块固定各独立仓库的开发提交,状态为 `planned`。 [标准库目录](stdlib/README.md)
| 仓库 | 职责 |
| --- | --- |
| [marqdo-std-core](https://git.cflmy.cn/cflmy/marqdo-std-core) | Result 与基础数值 |
| [marqdo-std-collections](https://git.cflmy.cn/cflmy/marqdo-std-collections) | List、Map 和 Table 值操作 |
| [marqdo-std-text](https://git.cflmy.cn/cflmy/marqdo-std-text) | Unicode 文本、字节值与 UTF-8 |
| [marqdo-std-encoding](https://git.cflmy.cn/cflmy/marqdo-std-encoding) | Base64、Base32 和 Hex |
| [marqdo-std-data](https://git.cflmy.cn/cflmy/marqdo-std-data) | JSON、CSV、TOML 与 GFM 数据转换 |
| [marqdo-std-io](https://git.cflmy.cn/cflmy/marqdo-std-io) | Console、Stream、格式化和官方 print 别名 |
| [marqdo-std-fs](https://git.cflmy.cn/cflmy/marqdo-std-fs) | 文件、目录与路径 |
| [marqdo-std-system](https://git.cflmy.cn/cflmy/marqdo-std-system) | 时钟、UTC、环境、进程与随机 |
| [marqdo-std-net](https://git.cflmy.cn/cflmy/marqdo-std-net) | TCP、UDP、TLS 和网络字节流 |
### 领域扩展
领域扩展负责按需安装的算法、协议和业务能力。`extensions/` 的子模块链接各独立仓库,功能从 `planned` 状态开始开发。 [领域扩展目录](extensions/README.md)
| 仓库 | 职责 |
| --- | --- |
| [marqdo-ext-math](https://git.cflmy.cn/cflmy/marqdo-ext-math) | 数值算法、统计、符号数学及绘图 |
| [marqdo-ext-linalg](https://git.cflmy.cn/cflmy/marqdo-ext-linalg) | 复数、矩阵、分解及数值线性代数 |
| [marqdo-ext-quantum](https://git.cflmy.cn/cflmy/marqdo-ext-quantum) | 量子电路、态向量、采样与模拟 |
| [marqdo-ext-http](https://git.cflmy.cn/cflmy/marqdo-ext-http) | HTTP、URL、SSE 与报文生命周期 |
| [marqdo-ext-websocket](https://git.cflmy.cn/cflmy/marqdo-ext-websocket) | WebSocket 握手、帧与连接语义 |
| [marqdo-ext-ai](https://git.cflmy.cn/cflmy/marqdo-ext-ai) | 模型协议、流式输出与工具调用数据 |
| [marqdo-ext-mcp](https://git.cflmy.cn/cflmy/marqdo-ext-mcp) | MCP 协议、传输、发现和调用 |
| [marqdo-ext-crypto](https://git.cflmy.cn/cflmy/marqdo-ext-crypto) | 成熟密码学实现的封装 |
| [marqdo-ext-database](https://git.cflmy.cn/cflmy/marqdo-ext-database) | SQL 参数绑定、事务和驱动连接 |
| [marqdo-ext-storage](https://git.cflmy.cn/cflmy/marqdo-ext-storage) | 本地和对象存储接口 |
| [marqdo-ext-cache](https://git.cflmy.cn/cflmy/marqdo-ext-cache) | TTL、缓存和失效 |
| [marqdo-ext-security](https://git.cflmy.cn/cflmy/marqdo-ext-security) | 应用身份、会话及权限模型 |
| [marqdo-ext-browser](https://git.cflmy.cn/cflmy/marqdo-ext-browser) | 浏览器宿主、WASM 适配、DOM 和事件 |
| [marqdo-ext-document](https://git.cflmy.cn/cflmy/marqdo-ext-document) | Markdown 结构与显式文档编辑 |
| [marqdo-ext-archive](https://git.cflmy.cn/cflmy/marqdo-ext-archive) | 压缩、安全归档和解包 |
| [marqdo-ext-engineering](https://git.cflmy.cn/cflmy/marqdo-ext-engineering) | 工程操作、文件补丁与产物 |
| [marqdo-ext-regex](https://git.cflmy.cn/cflmy/marqdo-ext-regex) | 正则匹配、捕获、扫描和替换 |
| [marqdo-ext-datetime](https://git.cflmy.cn/cflmy/marqdo-ext-datetime) | IANA 时区、DST 和高级日历 |
### Web 领域聚合
Web 领域以设计文档为源材料,面向可交互的原型预览与工程交付。HTTP、数据库、认证和浏览器运行时各自独立维护。`extensions/web` 链接 `planned` 的 Web 领域仓,Design 和 Preview 由该领域仓固定。 [WEB-DESIGN](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md)
| 仓库 | 职责 |
| --- | --- |
| [marqdo-ext-web](https://git.cflmy.cn/cflmy/marqdo-ext-web) | Web 领域聚合:唯一设计合同、示例、组合验收与交付协调,不含生产实现 |
| [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) | 设计文档解释、校验、组件/依赖图、诊断与 handoff(独立 Rust library) |
| [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview) | 通用离线预览渲染、有限状态交互与 `web` Tool 发行 |
## 参与开发
在负责的独立仓库提交实现和测试。主仓库用 Git 子模块按“根 → 领域 → 功能”最多两级固定提交,组件的发行状态由 catalog 独立记录。需要获取当前组合时,运行:
```sh
git clone https://git.cflmy.cn/cflmy/marqdo.git
cd marqdo
git submodule update --init --recursive
python3 scripts/check-layout.py --checkouts
python3 -m unittest discover -s tests/integration
```
`check-layout.py` 校验每层 catalog、gitlink、权威远端、全局 ID 和依赖图。`--checkouts` 同时核对递归检出的实际提交。`planned` 子模块提供固定开发快照,只有 `active` 组件进入发行验收。
[各仓库任务](docs/REPOSITORY-TASKS.md) · [组件目录](components.toml) · [架构边界](docs/ARCHITECTURE.md) · [开发流程](docs/DEVELOPMENT.md) · [迁移台账](docs/MIGRATION.md) · [架构决策记录](docs/adr/README.md) · [AGENTS](AGENTS.md)
旧版实现与文档可在历史标签查阅。 [v2.9.1 历史树](https://git.cflmy.cn/cflmy/marqdo/src/tag/v2.9.1)
Submodule
+1
Submodule cli added at deadf6edee.
+393
View File
@@ -0,0 +1,393 @@
# 生态组件职责与构建关系。精确提交由 Git tree 的 gitlink 锁定。
# 治理树最多两级:根 → 领域聚合(kind = "domain")→ 功能组件。每个聚合仓库只登记直属子组件,
# 递归展平后全局 ID 与权威远端唯一;禁止在根同时登记某个计划中聚合及其后代路径。
# kind = "domain" 是治理角色:requires = [],release 为 none(普通领域)或 base(Stdlib Bundle 聚合),
# 聚合仓自身不含生产实现;其子组件在领域仓库自己的 components.toml 登记。
# planned 的 requires 是设计输入,激活前须核对实际 imports 和发布依赖。
# 已发布的仓库提交可以作为 planned gitlink 固定,发行验收以 active 状态为准。
[[component]]
id = "cli"
path = "cli"
kind = "core"
state = "active"
owner = "cflmy"
scope = "语言语义、运行时、受控宿主和公共协议"
requires = []
checks_with = ["conformance"]
release = "base"
entry = "tools/release/smoke.py"
[[component]]
id = "conformance"
path = "tests/conformance"
kind = "test"
state = "active"
owner = "cflmy"
scope = "可执行的独立公共协议测试"
requires = ["cli"]
checks_with = []
release = "none"
entry = "scripts/build_all.sh"
[[component]]
id = "view"
path = "tools/view"
kind = "tool"
state = "active"
owner = "cflmy"
scope = "阅读、运行观察与静态导出"
requires = ["cli"]
checks_with = []
release = "optional"
entry = "scripts/acceptance.sh"
[[component]]
id = "knowledge"
path = "tools/knowledge"
kind = "tool"
state = "active"
owner = "cflmy"
scope = "静态知识编译与检索"
requires = ["cli"]
checks_with = []
release = "optional"
entry = "scripts/ci.sh"
[[component]]
id = "prove"
path = "tools/prove"
kind = "tool"
state = "active"
owner = "cflmy"
scope = "证明依赖、证书及 Lean 后端"
requires = ["cli"]
checks_with = []
release = "optional"
entry = "scripts/package-tool.sh"
[[component]]
id = "lint"
path = "tools/lint"
kind = "tool"
state = "active"
owner = "cflmy"
scope = "静态规则、诊断及显式修复"
requires = ["cli"]
checks_with = []
release = "optional"
entry = "scripts/package-tool.sh"
[[component]]
id = "std-core"
path = "stdlib/core"
kind = "stdlib"
state = "planned"
owner = "cflmy"
scope = "Result 与基础数值"
requires = ["cli"]
checks_with = []
release = "base"
[[component]]
id = "std-collections"
path = "stdlib/collections"
kind = "stdlib"
state = "active"
owner = "cflmy"
scope = "List、Map 和 Table 值操作"
requires = ["cli"]
checks_with = ["std-data"]
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-text"
path = "stdlib/text"
kind = "stdlib"
state = "active"
owner = "cflmy"
scope = "Unicode 文本、字节值与 UTF-8"
requires = ["cli"]
checks_with = []
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-encoding"
path = "stdlib/encoding"
kind = "stdlib"
state = "planned"
owner = "cflmy"
scope = "Base64、Base32 和 Hex"
requires = ["cli", "std-core", "std-text"]
checks_with = []
release = "base"
[[component]]
id = "std-data"
path = "stdlib/data"
kind = "stdlib"
state = "active"
owner = "cflmy"
scope = "JSON、CSV、TOML 与 GFM 数据转换"
requires = ["cli"]
checks_with = ["std-collections"]
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-io"
path = "stdlib/io"
kind = "stdlib"
state = "active"
owner = "cflmy"
scope = "Console、Stream、格式化和官方 print 别名"
requires = ["cli"]
checks_with = []
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-fs"
path = "stdlib/fs"
kind = "stdlib"
state = "active"
owner = "cflmy"
scope = "文件、目录与路径"
requires = ["cli"]
checks_with = []
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-system"
path = "stdlib/system"
kind = "stdlib"
state = "active"
owner = "cflmy"
scope = "时钟、UTC、环境、进程与随机"
requires = ["cli"]
checks_with = []
release = "base"
entry = "scripts/test.sh"
[[component]]
id = "std-net"
path = "stdlib/net"
kind = "stdlib"
state = "planned"
owner = "cflmy"
scope = "TCP、UDP、TLS 和网络字节流"
requires = ["cli", "std-io", "std-system"]
checks_with = []
release = "base"
[[component]]
id = "math"
path = "extensions/math"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "数值算法、统计、符号数学及绘图"
requires = ["cli", "std-core", "std-collections", "std-text"]
checks_with = []
release = "optional"
[[component]]
id = "linalg"
path = "extensions/linalg"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "复数、矩阵、分解及数值线性代数"
requires = ["cli", "math"]
checks_with = []
release = "optional"
[[component]]
id = "quantum"
path = "extensions/quantum"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "量子电路、态向量、采样与模拟"
requires = ["cli", "linalg"]
checks_with = []
release = "optional"
[[component]]
id = "http"
path = "extensions/http"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "HTTP、URL、SSE 与报文生命周期"
requires = ["cli", "std-net", "std-text", "std-encoding"]
checks_with = []
release = "optional"
[[component]]
id = "websocket"
path = "extensions/websocket"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "WebSocket 握手、帧与连接语义"
requires = ["cli", "http"]
checks_with = []
release = "optional"
[[component]]
id = "ai"
path = "extensions/ai"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "模型协议、流式输出与工具调用数据"
requires = ["cli", "http", "std-data"]
checks_with = []
release = "optional"
[[component]]
id = "mcp"
path = "extensions/mcp"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "MCP 协议、传输、发现和调用"
requires = ["cli", "http", "std-system"]
checks_with = []
release = "optional"
[[component]]
id = "crypto"
path = "extensions/crypto"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "成熟密码学实现的封装"
requires = ["cli", "std-encoding"]
checks_with = []
release = "optional"
[[component]]
id = "database"
path = "extensions/database"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "SQL 参数绑定、事务和驱动连接"
requires = ["cli", "std-data"]
checks_with = []
release = "optional"
[[component]]
id = "storage"
path = "extensions/storage"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "本地和对象存储接口"
requires = ["cli", "std-fs"]
checks_with = []
release = "optional"
[[component]]
id = "cache"
path = "extensions/cache"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "TTL、缓存和失效"
requires = ["cli", "std-system"]
checks_with = []
release = "optional"
[[component]]
id = "security"
path = "extensions/security"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "应用身份、会话及权限模型"
requires = ["cli", "crypto", "http"]
checks_with = []
release = "optional"
[[component]]
id = "web"
path = "extensions/web"
kind = "domain"
state = "planned"
owner = "cflmy"
scope = "Web 原型设计领域治理:唯一设计合同、组合验收与交付协调"
requires = []
checks_with = []
release = "none"
[[component]]
id = "browser"
path = "extensions/browser"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "浏览器宿主、WASM 适配、DOM 和事件"
requires = ["cli"]
checks_with = []
release = "optional"
[[component]]
id = "document"
path = "extensions/document"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "Markdown 结构与显式文档编辑"
requires = ["cli", "std-fs", "std-text"]
checks_with = []
release = "optional"
[[component]]
id = "archive"
path = "extensions/archive"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "压缩、安全归档和解包"
requires = ["cli", "std-text", "std-fs"]
checks_with = []
release = "optional"
[[component]]
id = "engineering"
path = "extensions/engineering"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "工程操作、文件补丁与产物"
requires = ["cli", "document", "archive"]
checks_with = []
release = "optional"
[[component]]
id = "regex"
path = "extensions/regex"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "正则匹配、捕获、扫描和替换"
requires = ["cli", "std-text"]
checks_with = []
release = "optional"
[[component]]
id = "datetime"
path = "extensions/datetime"
kind = "extension"
state = "planned"
owner = "cflmy"
scope = "IANA 时区、DST 和高级日历"
requires = ["cli", "std-system"]
checks_with = []
release = "optional"
-41
View File
@@ -1,41 +0,0 @@
# Marqdo 开发文档
本目录存放各阶段设计、选型与路线图。
## 目录约定
| 路径 | 用途 |
|------|------|
| [`research/`](research/) | 外部标准与调研 |
| [`design/`](design/) | 语言设计(语法映射等) |
| [`adr/`](adr/) | 架构决策记录 |
| [`roadmap/`](roadmap/) | 实现路线与里程碑 |
## 当前文档
| 文档 | 摘要 |
|------|------|
| [design/markdown-mapping.md](design/markdown-mapping.md) | **v0.1 语法宪法** |
| [design/code-vs-comment.md](design/code-vs-comment.md) | 叙述 / 可执行 / 外联 |
| [design/return-hr-and-code-surface.md](design/return-hr-and-code-surface.md) | 语句/返回/输出决议 |
| [design/generated-yaml-manifest.md](design/generated-yaml-manifest.md) | 生成式 OKF 清单 |
| [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 |
| [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** |
| [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) |
| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置 `print` `input`** |
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
| [design/examples-and-tests.md](design/examples-and-tests.md) | **示例即金样例目录布局** |
| [design/view.md](design/view.md) | **`marqdo view` 源结构浏览器** |
| [design/bytecode.md](design/bytecode.md) | **M5 字节码 / 双后端** |
| [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** |
| [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) |
| [roadmap/interpreter.md](roadmap/interpreter.md) | 正经解释器路线图 |
| [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 |
示例与验收集:[`examples/`](../examples/)。Spike 存档:[`spike/`](../spike/)。
## 写作原则
1. 先宪法与路线图,再实现。
2. 金样例不过 = 未完成。
3. 示例统一 `.mq.md`。
-53
View File
@@ -1,53 +0,0 @@
# ADR 0001:参考实现语言与前端工具
| | |
|---|---|
| 状态 | **Accepted**(修订:实现语言 = Rust) |
| 日期 | 2026-08-04 |
| 决策者 | chaungming + 协作 |
| 相关 | [dependencies.md](../design/dependencies.md) · [interpreter 路线图](../roadmap/interpreter.md) · [spike/REPORT.md](../../spike/REPORT.md) |
---
## 背景
语法宪法 v0.1 已定;Python Spike 已验证 GFM/行扫描风险。产品目标是正经**解释器**(`marqdo run index.mq.md`),实现语言需兼顾安全与可维护性。
---
## 决策
1. **参考解释器实现语言:Rust(stable)**
- 内存安全、单静态二进制、适合长期演进到字节码 VM。
- Python Spike **保留为算法原型/对照**,不是运行时依赖。
2. **词法 / 语法:不使用 Flex、Bison**
- **主因是 Marqdo 的 Markdown 语法形态**,不是「因为选了 Rust」。换成 C++ 同样不建议用 Flex/Bison 做整语言前端。
- 解释器需要词法·语法**阶段**;采用自研行分类 + GFM 库 + **手写递归下降** → AST。
- 详见 [dependencies.md](../design/dependencies.md)。
3. **架构分期不变**
- Phase I:树遍历解释器
- Phase II:字节码 + VM
- 见 [interpreter.md](../roadmap/interpreter.md)
4. **Markdown 库**
- `pulldown-cmark` 或 `comrak` 二选一(建包前短 Spike 钉死)。
---
## 后果
- 正式代码以 Cargo 工程生长;不把 Flex/Bison/LLVM 列入 v1 依赖。
- 金样例仍为 `examples/`;行为与宪法一致。
- 此前「Python 作参考实现」的倾向由本修订取代;Spike 结论(行扫描等)仍然有效并迁入 Rust。
---
## 否决
| 方案 | 原因 |
|------|------|
| Flex + Bison 作主前端 | 与 Markup-as-Syntax / Rust 栈错配;解释器非必需 |
| v1 上 LLVM | 产品是解释执行文档,不是机器后端 |
| 仅 Python 正则玩具 | 达不到安全与长期目标 |
-89
View File
@@ -1,89 +0,0 @@
# Marqdo 字节码(M5 原型)
| | |
|---|---|
| 状态 | 进行中(原型) |
| 日期 | 2026-08-04 |
| 相关 | [roadmap/interpreter.md](../roadmap/interpreter.md) · Phase I 树遍历 |
---
## 1. 目标
在保留树遍历后端(`--backend tree`,默认)的同时,提供栈式字节码 VM(`--backend bytecode`),使**核心金样例** stdout 与树遍历 bit 一致。
```
.mq.md → load/parse → Module AST
├─ tree-walk
└─ compile → Chunk → VM
```
---
## 2. 指令集(草案 / 原型已实现子集)
| Op | 栈效应 | 说明 |
|----|--------|------|
| `Constant i` | → v | 常量池 |
| `True` / `False` / `None` | → b | |
| `Pop` | v → | |
| `GetLocal i` / `SetLocal i` | | 当前帧槽 |
| `GetGlobal i` / `SetGlobal i` | | 名字在常量池(文本) |
| `Add` `Sub` `Mul` `Div` `Negate` `Not` | | |
| `Equal` `NotEqual` `Greater` `GreaterEqual` `Less` `LessEqual` | | |
| `Jump a` / `JumpIfFalse a` / `JumpBack a` | | 相对/绝对跳转(原型用绝对 u16) |
| `Print` | v → | 弹出并写 stdout |
| `BuildList n` | v… → list | |
| `GetIndex` | list, i → v | foreach 用 |
| `Call f argc` | args… → ret | 用户函数(按形参序压栈) |
| `Return` | | 返回 / 结束帧 |
| `Interp n` | parts… → text | n 个交错 Lit/Var 标记后的拼接(简化:编译期展开为常量+拼接) |
原型实现以 `src/bytecode/` 为准;未列出的 Op 不存在于当前构建。
---
## 3. 编译约定
- 每个 Marqdo `Function` → 一个 `FnChunk`(含 `name`、`params`、`code`、`constants`)。
- 模块级 `Program`:函数表 + 入口名(`main` 或唯一无参 level-1)。
- 局部变量:函数体内首次赋值/形参分配槽位。
- 嵌套 `##`:编入同一 `Program`,按名 `Call`;查找规则对齐树遍历(子树优先,再顶层)。
- `and` / `or`:短接跳转。
- 分支 / while:`JumpIfFalse` + `Jump` / `JumpBack`。
- foreach:`BuildList` 或已有 list 全局/局部 → 索引循环。
---
## 4. 覆盖表(M5 原型)
| 金样例 | tree | bytecode |
|--------|------|----------|
| `structure/hello` | ✅ | ✅ |
| `structure/branch` | ✅ | ✅ |
| `structure/loop` | ✅ | ✅ |
| `structure/collection` | ✅ | ✅ |
| `keywords/print` | ✅ | ✅ |
| `keywords/bool-logic` | ✅ | ✅ |
| `structure/nested-call` | ✅ | ✅ |
| `structure/positional-call` | ✅ | ✅ |
| `structure/import/*` | ✅ | ✅(load 合并 AST 后编译) |
| `examples/errors/*` | ✅(非零退出) | 同 tree 语义(编译期/运行期诊断) |
核心金样例双后端已对齐;后续可扩展 Op、优化与更好的调试信息。
---
## 5. CLI
```bash
marqdo run FILE --backend tree # 默认
marqdo run FILE --backend bytecode
marqdo run FILE --dump-bytecode # 反汇编后仍可按 backend 执行
```
---
## 6. 非目标(本原型)
优化、寄存器分配、GC、与树遍历指令级调试对齐、独立 sema IR。
-50
View File
@@ -1,50 +0,0 @@
# 调用实参:具名与位置
| | |
|---|---|
| 状态 | 已定(v0.1 增补) |
| 日期 | 2026-08-04 |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords.md](keywords.md) |
---
## 1. 目标
`>` 调用同时支持:
| 形式 | 示例 | 说明 |
|------|------|------|
| **具名**(保留) | `> 问候 谁=Marqdo` | `名=值`;值可含空格(至下一 `名=`) |
| **位置**(新增) | `> 问候 Marqdo` | 按形参声明顺序绑定 |
二者可混用:位置实参按「尚未被具名绑定的形参」从左到右填充。具名不可绑定同一形参两次;位置实参不得出现在「已出现具名实参」之后(对齐常见「位置在前、关键字在后」习惯)。
---
## 2. 文法(调用尾部)
```
call_tail ::= callee arg*
arg ::= named | positional
named ::= ident '=' value
positional ::= value_token
```
- `value`(具名右侧):可含空格与 `` `var` `` 插值,直到下一个 `ident=` 边界。
- `value_token`(位置):空白分隔的一个词法单元——数字、`` `名` ``、标识/文本词;**不含空格**。多词字符串请用具名,例如 `> print text=Hello World!`。
- 内置 `print` 形参名为 `text`:`> print Hi` 与 `> print text=Hi` 等价。
---
## 3. 绑定算法
1. 收集具名 → 映射;冲突则报错。
2. 按函数形参表顺序:若具名已提供则用之,否则取下一个位置实参。
3. 位置实参有余、或必填形参仍缺 → 报错(内置 `input` 的 `prompt` 可缺省)。
4. 用户函数:额外具名键仍写入调用环境(便于扩展);位置实参不可超过形参数目。
---
## 4. 金样例
见 `examples/structure/positional-call.mq.md` 与更新后的 `examples/structure/import/`。
-28
View File
@@ -1,28 +0,0 @@
# 可执行面与叙述面
| | |
|---|---|
| 状态 | 与 mapping v0.1 / keywords 对齐 |
| 日期 | 2026-08-04 |
---
## 三层
| 层 | 形态 | 角色 |
|----|------|------|
| **叙述面** | 无标记行 | 注释;内部标记无语义 |
| **Marqdo 可执行面** | 结构标记 + `*语句*` + `**返回**` | 本语言程序 |
| **外联面** | ` ```lang ` | 其它语言(FFI) |
输出属于可执行面里的**函数调用**(`> print …`),见 [keywords.md](keywords.md)。
---
## 语句 vs 返回 vs 输出
| 标记/形式 | 角色 | 是否架构级 |
|-----------|------|------------|
| `*…*` | 程序语句 | 是 |
| `**…**` | 返回值 | 是 |
| `> print …` | 打印副作用 | 否(内置函数) |
-174
View File
@@ -1,174 +0,0 @@
# Marqdo 实现依赖说明(Rust 参考解释器)
| | |
|---|---|
| 状态 | 已定 |
| 日期 | 2026-08-04 |
| 相关 | [ADR 0001](../adr/0001-implementation-language.md) · [interpreter 路线图](../roadmap/interpreter.md) |
---
## 1. 要不要 Flex / Bison?
### 结论:**不需要。** 主因不是「用了 Rust」,而是 **Marqdo 的语法形态 + 解释器并不绑定生成器。**
把两件事分开:
| 问题 | 答案 |
|------|------|
| 因为 Rust 才不用 Flex/Bison? | **否。** Flex/Bison 生成的是 C(也可接 C++)。若实现改成 **C++**,**仍然不建议**用它们做 Marqdo 主前端。 |
| 因为是解释器才不用? | **部分相关,但不是全部。** 解释器**需要**词法/语法阶段,但**不规定**必须用 Flex/Bison;手写递归下降是主流。即便将来做「编译到字节码/原生」,Marqdo 也因 Markdown 外壳而不适合整语言 Bison 化。 |
| 真正主因 | **Markup-as-Syntax**:源是 GFM 文档结构(标题/列表/强调/表格/行分类),不是 Cminusf 那种纯字符流文法。 |
| 工具 | 典型用途 | Marqdo 为何不用(与宿主语言无关) |
|------|----------|----------------------------------|
| **Flex** | 正则 → C 词法分析器 | 「词法」是 **行分类 + Markdown 标记**,不是经典 `id\|num\|op` 字符流 |
| **Bison** | Yacc 文法 → C LR 分析器 | 整体语法绑在 **GFM 块结构**上,硬写成单一 Bison 文法别扭且难与预览器对齐 |
[USTC 编译课 Lab1](https://ustc-compiler-2025.github.io/homepage/) 用 Flex/Bison,是因为对象语言是 **C 式源码的编译器**;换 C++ 写那个编译器也合理。
Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这一判断。
**解释型语言同样需要词法与语法分析**,要的是阶段,不是这两个具体程序。
---
## 2. Marqdo 前端应怎样做(替代 Flex/Bison)
拆成三层,比「一个大 lexer/parser」更贴合宪法:
```
.mq.md 文本
│
├─① 行分类(自研) 无标记 → 注释;有标记 → 代码行
├─② GFM 块/行内(库) 标题、表、强调、列表结构
├─③ 行扫描补强(自研) 保留 '-' / '+';frontmatter `> file.mq.md`
└─④ Marqdo 语法(自研) 递归下降:Module/Fun/Stmt/Expr → AST
└─ 表达式子语言 可手写,或仅对 Expr 用 pest/nom
```
| 阶段 | 做法 | 对应编译学 |
|------|------|------------|
| ①③ | Rust 手写扫描 | 词法 / 扫描器 |
| ② | `pulldown-cmark` 或 `comrak` | 复用 GFM,避免自研表格/强调 |
| ④ | **手写递归下降**(推荐主路径) | 语法分析 |
| Expr(可选) | `pest`(PEG)或 `nom`(组合子) | 仅迷你表达式,不是整门语言 |
**不推荐**整门语言上 LALRPOP / rusty_lr / Bison 等价物作为 v1 主前端:Markdown 外壳 + 行语义会让文法极度别扭。若将来有「纯文本 Marqdo 方言」,再另议生成器。
---
## 3. 详细依赖清单(Rust)
### 3.1 工具链(开发机)
| 依赖 | 用途 | 安装 |
|------|------|------|
| **Rust**(stable,建议 ≥ 1.75) | 编译实现 | [rustup](https://rustup.rs/):`rustup default stable` |
| **Cargo** | 包与构建 | 随 rustup |
| **rustfmt / clippy** | 格式与静态检查 | `rustup component add rustfmt clippy` |
| **Git** | 版本管理 | 已有 |
**不要安装:** Flex、Bison、LLVM(v1 解释器不需要)。
(日后若做原生后端再开 ADR;与当前解释器无关。)
### 3.2 Cargo crate(建议写入根 `Cargo.toml` / workspace)
#### 必选(Phase I 树遍历解释器)
| Crate | 角色 | 说明 |
|-------|------|------|
| **pulldown-cmark** *或* **comrak** | GFM 事件/AST | 标题、列表、表格、emphasis/strong;Spike 已证明「库 + 行扫描」可行。二选一做 Spike 对比后钉死 |
| **thiserror** / **anyhow** | 错误类型 | 诊断与 CLI 报错 |
| **clap** | CLI | `marqdo run [path]` |
| **serde** + **serde_yaml** | 元信息 | 仅解析 frontmatter 中的 YAML **键值**;`> x.mq.md` 仍按**行**抽取(见 Spike) |
#### 强烈建议
| Crate | 角色 |
|-------|------|
| **camino** 或标准 `PathBuf` | 路径 |
| **indexmap** | 保序 map(模块导出等) |
#### 测试
| Crate | 角色 |
|-------|------|
| **rust 自带** `#[test]` | 单元测试 |
| **insta** 或手写金文件 | examples 期望 stdout 快照(可选) |
| **assert_cmd** / **predicates** | CLI 集成测试(可选) |
#### Phase II(字节码 VM,后加)
无强制新依赖;VM 以自研为主。可选:
| Crate | 角色 |
|-------|------|
| **num_enum** 等 | opcode 枚举(可选) |
#### 明确不引入(v1)
| 东西 | 原因 |
|------|------|
| flex / bison / lemon | 见 §1 |
| lalrpop / rusty_lr 作**整语言**前端 | 与 MD 外壳冲突;递归下降更合适 |
| llvm-sys / inkwell | 非解释器 v1 |
| 完整 Python 运行时嵌入 | 参考实现已定为 Rust,避免双运行时 |
### 3.3 表达式子语言(可选增强)
若手写 Expr 递归下降过痛,**仅**对 `` `a` + 1 == `b` `` 这类表达式引入其一:
| 选项 | 类型 | 何时用 |
|------|------|--------|
| **手写递归下降** | 无新依赖 | 默认;与全书一致、错误信息最好控 |
| **pest** | PEG 生成器 | 文法清晰、想要 `.pest` 文件时 |
| **nom** | 解析组合子 | 要零拷贝/细控时 |
整文件 `.mq.md` **不要**整份丢给 pest/nom。
---
## 4. 仓库布局(与依赖对应)
```
Cargo.toml # workspace 或单包
crates/marqdo/ # 或根包 marqdo
src/
main.rs / lib.rs
lex/ # 行分类、Token(自研,无 flex)
parse/ # 递归下降(自研,无 bison)
ast/
sema/
interp/ # Phase I
bytecode/ # Phase II
runtime/
tests/
examples/ # 金样例(已有)
spike/ # Python 风险探测存档(可保留,非运行时依赖)
```
开发命令示例:
```bash
cargo build
cargo test
cargo run -- run examples/structure/nested-call.mq.md
```
---
## 5. 与 Python Spike 的关系
| | Python `spike/` | Rust 参考实现 |
|--|-----------------|---------------|
| 角色 | 已验证 S1–S5 风险 | **正式**词法/语法/语义/解释器 |
| 是否运行时依赖 | 否 | 是 |
| 算法可迁移 | 行扫描、`split_front_matter`、导入正则 | 用 Rust 重写同算法 |
---
## 6. 一句话对照
- **需要:** 词法(行分类+标记)、语法(递归下降→AST)、语义、解释器/日后 VM。
- **不需要:** Flex、Bison、LLVM(v1)。
- **外部库只需:** Rust 工具链 + GFM crate(pulldown-cmark/comrak)+ CLI/错误/测试若干;表达式可选 pest/nom。
-76
View File
@@ -1,76 +0,0 @@
# 示例与测试布局
| | |
|---|---|
| 状态 | 已定 |
| 日期 | 2026-08-04 |
| 原则 | **示例即金样例**:`examples/**/*.mq.md` 由 `cargo test` / CI 跑通;`marqdo view` 也可直接浏览 |
---
## 1. 目录
```
examples/
README.md # 本树说明
structure/ # 代码基础结构(Markup 架构)
hello.mq.md
nested-call.mq.md # 原 index:嵌套函数 + 调用
positional-call.mq.md # 位置实参
branch.mq.md
loop.mq.md
collection.mq.md
import/
main.mq.md # 原 with-import
utils.mq.md
keywords/ # 关键字与内置名
print.mq.md
bool-logic.mq.md # True/False/None、and/or/not
errors/ # 期望失败(诊断文案稳定后再加金样例)
.gitkeep
```
Rust 集成测试:`tests/gold.rs` 扫描约定路径,比对 stdout。
---
## 2. 分类职责
| 类别 | 测什么 | 不测什么 |
|------|--------|----------|
| **structure** | `#`/`##`、形参、`>` 调用、`*`/`**`、`+`/`-`、表、导入、位置/具名实参 | 关键字边角 |
| **keywords** | `True`/`False`/`None`、`and`/`or`/`not`、`print`/`input` 约定 | 复杂控制流(可极简) |
| **errors** | 未定义名、实参错误、语法错误的诊断 | 成功路径 |
未单独建夹、但应覆盖的其它测试(放 `tests/` 单测或日后 `examples/runtime/`):
- **流水线调试**:`--dump-lines` / `--dump-ast` / `--trace-eval`
- **CLI**:默认 `index.mq.md`、退出码
- **view**:目录扫描、单文件页、执行区(见 [view.md](view.md))
- **模块图**:循环导入拒绝
---
## 3. 金样例约定
每个可执行 `.mq.md` 在 `tests/gold.rs`(或旁路 `.out` 文件)登记期望 stdout。
`errors/` 内文件登记期望 stderr 子串与非零退出码。
Frontmatter 可写:
```yaml
---
title: …
expect_stdout: |
line1
line2
---
```
(可选;v0 先以测试代码内嵌期望为主。)
---
## 4. 与 `view` 的关系
`marqdo view examples` 按上述文件夹生成侧栏索引;`structure` / `keywords` 为一级分组。
-163
View File
@@ -1,163 +0,0 @@
# 设计草案:机器生成的 YAML 清单(OKF 风格)
| | |
|---|---|
| 状态 | 草案(已采纳方向;修正「配置文件」误解) |
| 日期 | 2026-08-04 |
| 相关 | [OKF 调研](../research/okf-and-marqdo.md) |
| 取代 | 此前「YAML = 人手写的编译器配置 / frontmatter 契约」的表述 |
---
## 决策
Marqdo 项目中的 **YAML(及由其组成的 OKF 风格知识包)是工具自动生成的产物,不是给人填的配置文件。**
它的角色接近其它语言里由工具维护的**依赖与包元数据**,例如:
| 生态 | 类比(职责相近,不是语法相同) |
|------|--------------------------------|
| Rust | `Cargo.toml` / 解析后的依赖图(由源与清单共同推导,工具可改写) |
| Python | `requirements.txt`(常由解析/冻结生成) |
| Go | `go.mod` + `go.sum`(`go mod tidy` 维护) |
我们选择 **OKF 的形态**(Markdown + YAML frontmatter 的概念目录)来承载这份生成结果,从而一举两得:
1. **给编译器 / 包管理**:依赖图、模块身份、导出符号、版本锁定等可查询元数据
2. **给本项目文档**:同一份生成物可直接渲染为「项目知识目录」——模块说明、依赖关系、API 索引等**自动生成本项目文档内容**
**唯一手写真相**仍是 `.mq.md` 源文件正文。YAML 清单是派生工件;过时则重新生成,禁止当成第二套权威配置去手改(除非工具链明确支持的「生成后微调」流程,且须可复现)。
**与源 frontmatter 的分工**(见 [markdown-mapping.md](markdown-mapping.md)):源文件 `---` 块可含 `title` 等元信息,以及人手声明的跨文件导入行 `> other.mq.md`。那是**源上的导入声明**,不是工程依赖锁。工具仍应据此(及正文 `>` 调用)**生成** OKF 风格依赖/模块目录;不要把生成目录手改成权威。
---
## 纠正:它不是什么
| ❌ 不是 | ✅ 是 |
|--------|------|
| 人手维护的 `run` / `target` / 路径配置 | 从源码 **推导** 出的依赖与模块元数据 |
| 编译器「怎么跑」的 ini/配置替代品 | 解析、链接、文档站共用的 **生成清单** |
| 与正文平行的第二套程序描述 | 正文的 **投影**(projection):结构化、可查询、可渲染 |
执行方式(解释 / 检查 / 编译到某后端)由 **CLI、子命令或工程约定** 决定,不塞进这份 YAML 让人配置。
---
## 数据流
```
手写 .mq.md 源
(叙事 + 类型 + 函数 + 正文中的引用/导入)
│
▼
marqdo 工具链
· 解析正文 AST
· 收集 import / 链接 / 导出
· 解析依赖、锁定版本
│
├──────────────────────────────┐
▼ ▼
生成 OKF 风格清单 编译 / 类型检查 / 运行
(YAML + 概念 Markdown) (消费清单加速解析)
│
▼
自动生成本项目文档
(模块索引、依赖图、API 目录……)
```
- **源 → 清单**:单向派生;清单不得反向成为「唯一写依赖的地方」。
- **清单 → 文档**:OKF 包本身即可浏览;也可再生成站点/目录页。
- **清单 → 编译**:编译器可读生成结果以跳过重复发现,但语义仍以源为准;清单缺失时应能从源重建。
---
## 生成物长什么样(示意)
工程在构建或 `marqdo sync` 类命令后,可得到类似 OKF bundle 的目录(路径未定):
```
.marqdo/ # 或 docs/catalog/ 等 — 待 ADR
index.md # 生成:项目总览
modules/
cart.md # 生成:每个模块一个概念文档
prelude-list.md
deps/
lock.yaml # 生成:依赖锁定(机器向)
```
单个生成的概念文件可呈 OKF 形:
```yaml
---
type: Marqdo Module # 生成
title: cart
description: 购物车:行项目与总额
resource: src/cart.mq.md # 指向源文件
depends:
- prelude/list
- math/sum
exports: [Line, total]
generated:
by: "marqdo/0.1"
at: 2026-08-04T01:00:00Z
---
# cart
> 本页由 Marqdo 工具链根据 [`src/cart.mq.md`](../../src/cart.mq.md) **自动生成**,请勿手改。
## 依赖
- [prelude/list](../modules/prelude-list.md)
- [math/sum](../modules/math-sum.md)
## 导出
| 符号 | 种类 |
|------|------|
| `Line` | type |
| `total` | fn |
```
人要改行为或说明 → 改 `src/cart.mq.md`;再生成,文档与依赖清单一起更新。
---
## 与「代码即文档」的关系
Marqdo 有两层「文档」,不要混为一谈:
| 层 | 谁写 | 是什么 |
|----|------|--------|
| **源文档** | 人(及协助编写的 Agent) | `.mq.md`:程序本身,打开即读、即可跑 |
| **项目目录文档** | 机器 | OKF 风格 YAML/Markdown:从全项目源 **汇总** 的依赖、模块图、索引 |
前者消灭「实现与说明漂移」;后者消灭「仓库级总览靠手维护 README 目录」——总览从源自动长出,格式还对 Agent / 搜索友好(OKF)。
---
## 原则
1. **源为唯一权威** — 依赖与导出以 `.mq.md` 正文中的语言构造为准;YAML 是提取结果。
2. **生成、可复现** — 同一源树 + 同一工具版本 → 同一清单(允许时间戳等字段除外或规范化)。
3. **勿手改生成物** — 生成文件应带头注释或 `generated` 字段;CI 可校验「未提交脏生成」或「提交的生成与源一致」。
4. **OKF 形、Marqdo 义** — 文件形态对齐 OKF(`type`、链接、目录),词汇服务模块/依赖/导出,而不是照搬 BigQuery 概念类型。
5. **清单可删可再生** — 没有清单时,编译器仍须能直接从源工作(可能更慢);清单是缓存与文档面,不是语言语义的一部分。
---
## 待决问题(后续 ADR)
- [ ] 生成物落盘路径(例如 `.marqdo/` vs `docs/catalog/`)及是否提交进 git
- [ ] 单文件是否仍写入「生成型 frontmatter」,还是全部集中在工程级 OKF 包
- [ ] 与 `Cargo.toml` 式「可手写包身份(name/version)」的边界:是否允许极少量非生成的包清单,与全自动 OKF 目录如何分工
- [ ] `marqdo sync` / `marqdo doc` 命令的具体行为
- [ ] 是否沿用 OKF v0.2 的 `generated` / `sources` 字段描述溯源
---
## 结论
**YAML(OKF 风格清单)= 机器从 `.mq.md` 自动生成的依赖与项目元数据,并可据此自动生成本项目文档;不是人手填写的配置文件。**
人写源,工具写清单与目录文档;编译器与文档站共同消费生成物,语义始终回到源。
-84
View File
@@ -1,84 +0,0 @@
# Marqdo 关键字与内置名(v0 最小集)
| | |
|---|---|
| 状态 | 已定(前期够用) |
| 日期 | 2026-08-04 |
| 原则 | **英文**;参考 [Python](https://realpython.com/python-keywords/) 但远更少;控制流仍靠 Markdown 标记,不引入 `if`/`while`/`def` |
| 相关 | [markdown-mapping.md](markdown-mapping.md) |
---
## 1. 设计原则
1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。
2. **英文标识**:内置与字面量用英文,便于工具高亮与国际协作。
3. **学 Python 的边界**:Python 3 里 [`print` / `input` 是内置函数,不是关键字](https://realpython.com/python-keywords/);布尔与空值是字面量关键字。Marqdo 同样区分 **关键字** vs **内置函数名**。
4. **宁少勿多**:前期只列执行 examples 所需;要加再进 ADR。
---
## 2. 关键字(词法保留,不可作变量名)
| 关键字 | 含义 | 备注 |
|--------|------|------|
| `True` | 布尔真 | 对齐 Python 大小写 |
| `False` | 布尔假 | |
| `None` | 空值 | |
| `and` | 逻辑与 | 表达式内 |
| `or` | 逻辑或 | |
| `not` | 逻辑非 | |
**本期不引入:** `if` `else` `elif` `while` `for` `def` `class` `return` `import` `pass` `break` `continue` `in` `is` `lambda` …
(`else` 分支臂仍用臂头单独的 `*` 标记,不是单词 `else`。)
---
## 3. 内置函数(可调用名,建议勿遮蔽)
| 名称 | 作用 | 调用示例 |
|------|------|----------|
| `print` | 写到 stdout(副作用) | `> print text=Hello` 或 `> print Hello`(位置实参,见 [call-arguments.md](call-arguments.md)) |
| `input` | 从 stdin 读一行(返回文本) | `*`name` = > input prompt=Name: *` |
参数约定(v0):
- `print`:具名实参 `text`(必填);日后可扩展 `end` 等。
- `input`:可选 `prompt`;返回用户输入字符串(不含换行)。
旧文档中的中文 `print` **废弃**,统一为 `print`。
---
## 4. 与 Markup 调用的关系
```markdown
# main
> print text=Hello World!
*`n` = 1*
+ `n` > 0
> print text=positive
+ *
> print text=other
```
- `>` 是**调用标记**(架构)。
- `print` 是**被调名字**(内置库)。
- 用户自定义 `# print` 会遮蔽内置(实现应警告)。
---
## 5. 标识符规则(摘要)
- 变量:行内 `` `name` ``;`name` 不可为上表关键字。
- 函数名:`#` 标题文本;建议 ASCII/英文,中文标题仍允许但内置名保持英文。
- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and` `or` `not`。
---
## 6. 后续可增(未批准)
`len`、`str`、`int`、`float`、`range`;以及 `break`/`continue`(若循环需要)。增加前开短 ADR。
-211
View File
@@ -1,211 +0,0 @@
# Marqdo 语法映射 v0.1(Markup-as-Syntax)
| | |
|---|---|
| 状态 | 已定论(修订:语句 / 返回 / 输出职责分离) |
| 日期 | 2026-08-04 |
| 取代 | v0 中「`**`=输出、`*`=返回」 |
| 相关 | [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) |
Markdown **标记即语法**。输出**不是**语言架构原语,而是内置函数 **`print`**(英文;见 [keywords.md](keywords.md))。
---
## 1. 哲学
1. `.mq.md`:打开即文档,运行即程序。
2. **无标记行 = 叙述注释**(内部任何标记无语义)。
3. **可执行**靠标记:结构标记(`#` `>` `+` `-` 表…)与 **斜体语句** / **粗体返回**。
4. 作用域 = `#` 层数;入口 = `index.mq.md`。
---
## 2. 行首判别
跳过前导空白后:
| 首字符 | 分类 |
|--------|------|
| 普通文字 / 空 | **注释** |
| 标记字符 | **代码** |
标记含:`#` `*` `>` `+` `-` `` ` `` `|`、有序数字、围栏 `` ` ``、以及函数体内的分割线 `---` / `***`(见 §11)。
---
## 3. 映射总表(v0.1)
| 标记 | 语义 |
|------|------|
| `#` … `######` | 函数;层数 = 作用域 |
| 函数头下 `-` 纯名 | 形参 |
| 体内 `-` | 循环 |
| 体内 `+` 或 `1.` | 分支 |
| 分支臂头整行恰为 `*` | else |
| `> 函数 形参=实参` 或 `> 函数 实参` | 调用(具名 / 位置,见 [call-arguments.md](call-arguments.md)) |
| frontmatter `> path.mq.md` | 跨文件导入 |
| `*…*` | **程序语句**(绑定、表达式句、可写的调用句等) |
| `**…**` | **返回值**(架构级;函数结果) |
| 无标记行 | 注释 |
| GFM 表格 | 集合 |
| ` ```lang ` | 外联异种代码 |
| `---` / `***` | **可选**:框住分支/循环块(美化/分组;v0.1 不强制,见 §11) |
### 输出不是架构
| 错误(旧) | 正确(v0.1) |
|------------|--------------|
| `**Hello**` 表示打印 | `> print text=Hello` |
| 中文名 `输出`(已废弃) | 统一英文内置 `print` |
| 输出与返回抢粗体 | 粗体只表示 **返回** |
`print` / `input` 为内置函数,完整表见 [keywords.md](keywords.md)。
---
## 4. 语句、返回、调用
### 程序语句(斜体)
```markdown
*`x` = 1*
*`y` = `x` + 2*
```
行首已是结构标记的构造(`#` `>` `+` `-` `|`)**不必**再包一层斜体;斜体用于「一般语句」槽位。
### 返回值(粗体)
```markdown
# 加一
- n
**`n` + 1**
```
### 输出(内置函数 `print`)
```markdown
# main
> print text=Hello World!
```
### else 与斜体消歧
- 分支臂**第一行整行只有一个** `*` → else。
- `*中间有内容*` → 程序语句。
- `**…**` → 返回(与 else 无关)。
---
## 5. Frontmatter 与跨文件
同 v0:文件头 `---` 对为元信息;其中 `> file.mq.md` 为导入。
**函数体内的** `---` / `***` 不解释为 frontmatter(见 §11)。
---
## 6. 函数、作用域、提升
规则同 v0。推荐:
```markdown
# main
> print text=Hello World!
## 加问候
- 谁
**你好,`谁`**
```
(需要打印时对返回值再 `> print`,或直接 `> print`。)
形参 `- 名` → 体内 `` `名` ``。
---
## 7. 绑定与比较
| 写法 | 含义 |
|------|------|
| `*`x` = 1*` 或行首 `` `x` = 1 `` | 绑定(两种均允许;实现应统一) |
| `` `x` == 1 `` | 相等比较 |
v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致;行首 `` ` `` 仍合法以便表格右值绑定。
---
## 8. 分支与循环
分支(`+` / 有序),循环(`-`),语义同 v0。臂体内打印改为调用 `print`:
```markdown
*`x` = 0*
+ `x` > 0
> print text=正数
+ `x` < 0
> print text=负数
+ *
> print text=零
```
```markdown
- [果](篮子)
> print text=今天吃`果`
```
---
## 9. 集合(表格)
同 v0。`` `篮子` = `` 后接 GFM 表。
---
## 10. 求值入口
1. 加载 `index.mq.md` + 导入。
2. Pass1 收集定义。
3. Pass2 执行 `# main`。
4. `*` 语句、`**` 返回、`>` 调用、`+`/`-` 控制流、表绑定按语义执行;`> print` 写 stdout。
---
## 11. 分割线框住分支/循环(可选、非强制)
允许用 `---` 或 `***` 将分支/循环块视觉框起来,便于阅读:
```markdown
---
+ `x` > 0
> print text=正
+ *
> print text=其它
---
```
| 约定 | 说明 |
|------|------|
| v0.1 | **不强制**;无框同样合法 |
| 语义 | 若使用,框内仍是原列表语义;分割线本身不产生控制流 |
| 保留 | 日后若缺「块」类关键语法,可升级分割线为强制块边界 |
| 消歧 | 仅文件开头的 `---` 对 = frontmatter;函数体内成对/成段的 `---`/`***` = 可选框 |
---
## 12. v0.1 非目标
- break/continue、完整错误模型、静态类型、完整 FFI
- 强制分割线框
- 用 `*` 作无序列表符
---
## 13. 示例索引
见 [`examples/`](../../examples/)。
-73
View File
@@ -1,73 +0,0 @@
# 解释器流水线可视调试
| | |
|---|---|
| 状态 | 已定(开发期强制友好) |
| 日期 | 2026-08-04 |
| 参考 | [Crafting Interpreters — Scanning](https://www.craftinginterpreters.com/scanning.html)(先打 token)· [AstPrinter](https://craftinginterpreters.com/representing-code.html) · CLI `--dump-ast` 类实践 |
---
## 1. 目标
开发 `marqdo` 时,对任意 `.mq.md` 应能**分阶段看见**中间结果,避免黑盒;正式 `run` 默认安静,仅输出程序 `print` 的内容。
---
## 2. CLI 开关
```bash
marqdo run FILE [dumps...]
marqdo dump FILE --stage lines|tokens|ast|sema|all
```
| 标志 | 阶段 | 输出内容 |
|------|------|----------|
| `--dump-lines` | 行分类 | 每行:`LINE kind=Comment\|Code\|Blank` + 原文预览 |
| `--dump-tokens` | 词法 | Token 流:`type lexeme line:col` |
| `--dump-ast` | 语法 | S 表达式或缩进树(模块/函数/语句) |
| `--dump-sema` | 语义 | 作用域、导入图、提升后的符号表 |
| `--trace-eval` | 求值 | 进入/离开函数、绑定、分支臂选择、`print` 调用 |
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(见 [bytecode.md](bytecode.md)) |
| `--backend tree\|bytecode` | 执行后端 | 默认 `tree`;`bytecode` 走栈式 VM |
| `--dump-all` | 以上全部 | 按管道顺序打印,段之间用横幅分隔 |
格式约定:
- 人类可读优先;段首统一:`=== marqdo: <stage> ===`
- 可选 `--dump-format=text|json`(json 后置,text 先做)
- 有 dump 时:若求值未实现,仍打印已实现阶段再以非 0 退出(便于 M1 只测 lines)
---
## 3. 横幅示例
```
=== marqdo: lines (examples/hello.mq.md) ===
1 Blank
2 Comment | # Hello World
3 Blank
4 Comment | 本程序调用...
5 Blank
6 Code | > print text=Hello World!
=== marqdo: end lines ===
```
---
## 4. 实现要点
- dump 逻辑放在 `src/debug/`(或各阶段 `fmt`),**不**与安静求值路径搅在一起。
- 每个阶段纯函数:`input → (artifacts, diagnostics)`,CLI 负责打印。
- 单测可断言 dump 字符串包含关键行(稳定子集),避免绑死全文格式。
---
## 5. 与里程碑
| 里程碑 | 必须可用的 dump |
|--------|-----------------|
| M1 | `--dump-lines`(及可选 tokens 雏形) |
| M2 | `--dump-ast` |
| M3–M4 | `--dump-sema`、`--trace-eval` |
| 全程 | `--dump-all` 随阶段增长自动变完整 |
-18
View File
@@ -1,18 +0,0 @@
# 记录:返回 / 语句 / 输出 / 分割线(决议)
| | |
|---|---|
| 状态 | 已决议(并入 mapping v0.1 + keywords) |
| 日期 | 2026-08-04 |
---
## 决议
1. **`*…*` = 程序语句**。
2. **`**…**` = 返回值**(架构级)。
3. **输出**用内置函数 **`print`**(英文),不是粗体,不是中文名。
4. **`---` / `***`**:可选框住分支/循环,不强制。
5. **否决**:无标记行 = 默认代码。
详见 [keywords.md](keywords.md)、[markdown-mapping.md](markdown-mapping.md)。
-152
View File
@@ -1,152 +0,0 @@
# 参考实现:技术选型分析(尚未拍板)
| | |
|---|---|
| 状态 | **分析中 — 未定案** |
| 日期 | 2026-08-04 |
| 说明 | 对比候选与约束;**不在本文直接开写实现仓库脚手架** |
上一版曾草率写「就用 TypeScript」——信息不足,已作废为定论。本文只做选型框架与对比,**最终实现语言须单开 ADR 确认后再动工。**
---
## 1. 我们在选什么
参考实现至少包含:
1. **读入** `.mq.md`(含 frontmatter 混合行)
2. **对齐 GFM** 的结构:标题、列表(`-`/`+`/`1.`)、强调、表格、围栏、链接
3. **Lower**:行首判别、标题树作用域、列表符语义、注释剥离
4. **两遍**:收集定义 + 导入 → 求值
5. **CLI** + **金样例测试**(`examples/`)
可选后期:字节码/编译、LSP、格式化。首版目标是**验证语法宪法**,不是上生产编译器。
---
## 2. 选型准则(按权重)
| 权重 | 准则 | 说明 |
|------|------|------|
| 高 | GFM 忠实度 | 表格、列表符、强调边界与 GitHub 预览一致,减少「能渲染不能跑 / 能跑不能渲染」 |
| 高 | 与宪法同构 | 易于表达「先 mdast/事件流,再 Marqdo AST」 |
| 高 | 测试与迭代速度 | 改语法宪法时能快速改测试 |
| 中 | 静态类型 / 可维护 AST | 长期改解释器不疼 |
| 中 | CLI 与打包 | 单二进制或 `npx`/等价体验 |
| 低 | 极致性能 | v0 样例很小 |
| 低 | 浏览器内运行 | 可后置 |
非准则:跟风、先写再选、与「生成 OKF」强绑某一云厂商。
---
## 3. 架构共性(与语言无关)
无论选哪门实现语言,流水线应一致:
```
.mq.md 文本
→ 前端:GFM 友好解析(或事件扫描)
→ Middle:Marqdo lower(行类、标题树、- / +、表、围栏)
→ Marqdo AST
→ 语义:导入图、提升、作用域
→ 后端:解释器(v0)/日后编译
→ 测试:examples → 期望 stdout
```
**前端可复用成熟 GFM 库,也可自研**;Middle/后端必须自研(这是语言本体)。
---
## 4. 候选对比
### A. TypeScript / Node + remark(mdast)
| 利 | 弊 |
|----|----|
| remark-gfm 与预览器语义接近;mdast 节点齐全 | 运行时依赖 Node;发行 CLI 需打包 |
| 迭代快、Vitest 方便 | 性能与「系统级编译器」形象偏软 |
| 与 Markdown 工具链同生态 | 需纪律:避免把业务写进插件泥潭 |
**适合:** 验证宪法、快速金样例。
**不自动等于最终生产编译器。**
### B. Rust + pulldown-cmark / comrak
| 利 | 弊 |
|----|----|
| 单静态二进制、性能好、适合日后正式编译器 | GFM 表格/细节与 GitHub 仍可能有差异,要对齐测试 |
| 类型与代数数据类型适合 AST | 前期迭代比 TS 慢 |
| 无 GC、可嵌入 | MD 生态碎片,选库要论证 |
**适合:** 中长期「真编译器」或与 TS 原型双轨。
**风险:** 首版就上 Rust 可能拖慢语法验证。
### C. Python + markdown-it-py / mistune
| 利 | 弊 |
|----|----|
| 原型极快 | 类型与工程化偏弱;双实现时易弃 |
| 文本处理友好 | 打包 CLI 体验一般 |
**适合:** 一次性语法实验。
**不推荐**作为唯一长期实现,除非团队强约束。
### D. Go + goldmark
| 利 | 弊 |
|----|----|
| 单二进制、部署简单 | 泛型/AST 表达力一般;MD 库选 goldmark 需 GFM 扩展评估 |
| 并发与工具链成熟 | 与 MD 研究生态联系弱于 JS |
**适合:** 工具型 CLI 优先的团队。
### E. 自研扫描器(任意语言)+ 仅用 GFM 做对照测试
| 利 | 弊 |
|----|----|
| 完全控制行首判别与 `+`/`-` 语义 | 重复实现表格/强调,易与渲染不一致 |
| 可强制「行分类优先于块解析」 | 工作量大 |
**适合:** 证明「行首判别」与 CommonMark 块结构冲突时的研究分支。
可与 A/B 组合:自研 lower,块结构仍喂给现成解析器。
---
## 5. 关键技术风险(与选语言正交)
1. **行首判别 vs 块解析器** — CommonMark 先成块再看内容;Marqdo 先看行类。可能需「行预分类再喂解析器」或「解析后按源位置重分类」。选型时要让候选语言/库能拿到**源行映射**。
2. **frontmatter 非纯 YAML** — `>` 导入行是扩展;不能整块丢给严格 YAML 解析器。
3. **`+` 与 `-` 列表** — 多数解析器都认,但 lower 必须保留**项目符字符**,不能只得「unordered list」。选库时验证 AST 是否保留 bullet type。
4. **`*` else vs `*返回*` vs 强调** — 依赖 inline 解析与「整行恰好一个 `*`」的行级规则并存。
以上 4 点应作为**选型验收用例**,写进 ADR:用最小样例在候选栈上 Spike,再定案。
---
## 6. 建议的决策流程(尚未执行)
1. **Spike(各 ≤0.5–1 日)**
- 候选 A:TS + remark-gfm — 能否区分 `-`/`+` bullet、解析单列表格、读 strong/emphasis。
- 候选 B:Rust + comrak/pulldown — 同上。
- (可选)C 或 D 若团队有偏好再做。
2. **对照验收用例**(固定):`examples/hello.mq.md`、`branch.mq.md`(`+`)、`collection.mq.md`(表)、含 `> x.mq.md` 的 frontmatter 行。
3. **出 ADR**:选定「验证期实现」与(可选)「生产目标实现」是否同一语言。
4. **再**建仓库脚手架与测试——禁止在 ADR 前默认生成 `package.json` / `Cargo.toml` 当既成事实。
---
## 7. 当前态度(非正式投票)
| 阶段 | 倾向(待 Spike 验证) |
|------|------------------------|
| 语法验证期 | 更可能是 **TypeScript + remark**(快、GFM 近) |
| 长期生产编译器 | **开放** Rust / Go,不与验证期绑定 |
**本文不授权开始实现。** 确认 Spike 计划或直接指定语言后,再写 `adr/0001-implementation-language.md`。
---
## 8. 与「无标记 = 注释」的关系
实现必须先做**行分类**(见 [code-vs-comment.md](code-vs-comment.md)),再谈用何种语言写分类器。选型不能假设「整文件都是可执行代码」。
-119
View File
@@ -1,119 +0,0 @@
# `marqdo view` — 源结构浏览器
| | |
|---|---|
| 状态 | 已定(实现中) |
| 日期 | 2026-08-04 |
| 相关 | [examples-and-tests.md](examples-and-tests.md) · [pipeline-debug.md](pipeline-debug.md) · AST(`src/ast.rs`) |
---
## 1. 动机
`.mq.md` 既是文档也是程序。需要一种**可读渲染**,而不仅是纯文本或 `run` 的 stdout:
- 按语法树展示函数、分支、循环、调用、返回;
- 同页展示**执行结果**;
- 支持打开**单个文件**或**文件夹**(扫描全部 `.mq.md` + 结构索引)。
---
## 2. CLI
```bash
marqdo view [PATH] [--port PORT] [--host HOST] [--no-open]
```
| 参数 | 默认 | 说明 |
|------|------|------|
| `PATH` | `.` | `.mq.md` 文件,或目录(递归扫描 `*.mq.md`) |
| `--port` | `7429` | HTTP 端口 |
| `--host` | `127.0.0.1` | 仅本地 |
| `--no-open` | 关 | 不尝试打开系统浏览器 |
示例:
```bash
marqdo view examples/structure/hello.mq.md
marqdo view examples
marqdo view examples/keywords --port 8080
```
启动后打印 `http://127.0.0.1:7429/`,阻塞直至 Ctrl+C。
---
## 3. 信息架构
### 3.1 目录模式
```
┌─────────────┬──────────────────────────────────┐
│ 索引 │ 选中文件 / 欢迎页 │
│ structure/ │ │
│ hello │ [源码结构] [执行结果] [原始文本] │
│ branch │ │
│ keywords/ │ │
└─────────────┴──────────────────────────────────┘
```
- 侧栏:相对 `PATH` 的目录树;只列出 `.mq.md`。
- 点击文件:主区切换为该文件的三栏/三节视图。
### 3.2 单文件模式
无侧栏列表(或仅当前文件);主区同「选中文件」视图。仍提供「执行」结果。
---
## 4. 主区三节
### 4.1 源码结构(AST 渲染)
不依赖浏览器 Markdown 猜测语义,而用服务端已解析的 AST:
| AST 节点 | 视觉 |
|----------|------|
| `Function` | 卡片:标题层级、形参芯片、子函数嵌套;**中间的注释行仍展示**(来自源行分类,不在 AST 内) |
| `Stmt::*` | 绑定 / 返回 / 调用 / 分支 / 循环;表达式用**表面语法**(如 `` `x` > 0 ``),不用 Debug |
样式:清晰分区,避免「通用仪表盘」堆砌;结构层级一眼可读。
### 4.2 执行结果
服务端对该文件跑与 `marqdo run` 相同的管线,**捕获 stdout/stderr** 与退出状态,展示在「输出」区。
含 `input` 的程序:view 中标注「需交互,未在 view 执行」或提供只读说明(v0:跳过/失败信息)。
### 4.3 原始文本
等宽展示源文件;可选行分类着色(Code / Comment / Blank),与 `--dump-lines` 一致。
---
## 5. HTTP API(实现细节)
| 方法 | 路径 | 含义 |
|------|------|------|
| `GET` | `/` | 索引 HTML |
| `GET` | `/file?path=…` | 单文件页(path 相对根,防 `..` 逃逸) |
| `GET` | `/api/tree` | JSON 文件树 |
| `GET` | `/api/file?path=…` | JSON:`{ source, ast_html 或 ast_json, stdout, stderr, ok }` |
v0 可全部服务端渲染 HTML,API 可选。
安全:根目录锁死为 CLI 给定的 `PATH`(若为文件则其父目录为根、仅一文件);拒绝根外路径。
---
## 6. 依赖
本地同步 HTTP 即可(如 `tiny_http`),无强制前端构建;HTML/CSS/少量 JS 内嵌于 Rust。
---
## 7. 验收
1. `marqdo view examples/structure/hello.mq.md` 显示结构 + `Hello World!` 输出。
2. `marqdo view examples` 侧栏含 `structure/` 与 `keywords/` 分组。
3. 分支/循环样例在结构区可区分臂与循环体。
4. 路径逃逸被拒绝。
-86
View File
@@ -1,86 +0,0 @@
# 开发环境配置(Rust 参考解释器)
| | |
|---|---|
| 状态 | M0 |
| 相关 | [dependencies.md](design/dependencies.md) · [interpreter.md](roadmap/interpreter.md) |
---
## 1. 必备软件
| 软件 | 要求 | 检查 |
|------|------|------|
| Rust + Cargo | stable,建议 ≥ 1.81(本机验证过 1.81) | `rustc --version` / `cargo --version` |
| Git | 任意近期版本 | `git --version` |
安装 Rust(若尚未安装):
- 官方:[https://rustup.rs/](https://rustup.rs/)
- Windows:下载 `rustup-init.exe`,按提示安装后**重新打开终端**
本仓库可选 `rust-toolchain.toml`(钉 1.81.0)。若本机无 `rustup`、但已有匹配的 `rustc`/`cargo`,也可直接开发。
**不需要:** Flex、Bison、LLVM、Node/npm(实现栈为 Rust)。
---
## 2. 获取代码与构建
```bash
git clone https://github.com/cflmy/marqdo.git
cd marqdo
cargo build
cargo test
cargo run -- run examples/structure/hello.mq.md
```
当前 M0:`run` 会读入文件并明确报错「evaluation not implemented」(脚手架,非静默假成功)。
> 若 `cargo build` 报 `edition2024` / 过新 crate:仓库已对 `clap` 等做兼容钉扎(见 `Cargo.toml`);请使用附带的 `Cargo.lock`,勿盲目 `cargo update` 到最新 major。
---
## 3. 推荐组件
```bash
rustup component add rustfmt clippy # 若使用 rustup
cargo fmt
cargo clippy --all-targets
```
代理下拉 crate(可选,与 git 推送类似):
```bash
# Windows PowerShell 示例
$env:HTTPS_PROXY="http://127.0.0.1:7897"
$env:HTTP_PROXY="http://127.0.0.1:7897"
cargo build
```
或配置 `%USERPROFILE%\.cargo\config.toml`:
```toml
[http]
proxy = "http://127.0.0.1:7897"
```
---
## 4. 目录约定
| 路径 | 含义 |
|------|------|
| `src/lex` | 行分类 / 词法(自研) |
| `src/parse` | 递归下降语法 |
| `src/diagnostics` | 诊断 |
| `examples/` | 金样例(宪法) |
| `spike/` | 旧 Python 风险探测,非运行时依赖 |
| `doc/` | 设计与路线图 |
---
## 5. 下一里程碑
见 [interpreter.md](roadmap/interpreter.md):M1 词法·行分类与最小 AST。
-215
View File
@@ -1,215 +0,0 @@
# 调研:Google Open Knowledge Format(OKF)与 Marqdo
| | |
|---|---|
| 状态 | 调研笔记 |
| 日期 | 2026-08-04 |
| 对象 | [OKF v0.2](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md) |
| 公告 | [v0.1 介绍](https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing) · [v0.2 trust signals](https://cloud.google.com/blog/products/data-analytics/okf-v0-2-adds-trust-signals) |
---
## 1. OKF 是什么
**Open Knowledge Format(开放知识格式)** 是 Google Cloud 于 2026 年 6 月发布的厂商中立开放规范(Apache 2.0)。它把「LLM Wiki」模式形式化为可移植格式:用**目录树中的 Markdown 文件 + YAML frontmatter** 表示组织知识(表结构、指标、API、操作手册等),供人类与 AI Agent 共同阅读、交换与维护。
一句话定位:
> 知识应活在**格式**里,而不是专有服务或散落的非结构化文本里。
### 核心形态
```
bundle/
index.md # 可选:目录索引(渐进披露)
log.md # 可选:变更历史
concepts/.../*.md # 每个概念一个 Markdown 文件
```
每个概念文件:
```yaml
---
type: Metric # 唯一必填
title: Monthly Active Users
description: ...
tags: [product, growth]
sources: [...] # v0.2:出处
generated: {...} # v0.2:谁生成的
verified: {...} # v0.2:谁验证的
status: stable # v0.2:生命周期
stale_after: 2026-12-01 # v0.2:过期日
---
# 正文(自由 Markdown)
指标定义为……
```
- **Concept ID** = 相对路径去掉 `.md`
- **链接** = 普通 Markdown 链接,形成可遍历关系图
- **无中心 schema registry**;未知 `type` 必须被优雅降级处理
### 设计三原则(官方表述)
1. **Minimally opinionated** — 只强制互通所需的最小公约;其余留给生产者。
2. **Producer / consumer independence** — 写知识的人(或 Agent)与读知识的 Agent/工具解耦;格式即契约。
3. **Format, not platform** — 不绑定云、数据库、模型或 Agent 框架;`cat` 能读,`git clone` 能分发。
### v0.2 新增:五类信任信号
当知识主要由 Agent **持续生成**时,纯 Markdown 不够。v0.2 把下列问题变成 frontmatter 一等字段:
| 问题 | 机制 |
|------|------|
| 从何而来? | `sources`(出处 + 可信度信号,不作统一打分) |
| 该信多少? | `generated` / `verified` → 推导 trust tier(未验证 / 机器确认 / 人工审核) |
| 是否仍真? | `stale_after`(绝对日期,非相对 TTL) |
| 是否现行? | `status`: `draft` → `stable` → `deprecated` |
| 数字是否按约定算出? | 概念类型 `Attested Computation`:executor 跑计算出 receipt,**非 LLM** 的 attester 核验 |
---
## 2. OKF 与 Marqdo:相邻,但不等同
| 维度 | OKF | Marqdo |
|------|-----|--------|
| 本质 | **知识交换格式** | **编程语言** |
| 文件角色 | 描述资产与概念的文档 | 可执行程序 = 可渲染文档 |
| 机器侧 | 解析 metadata、遍历链接、过滤信任 | 解析、类型检查、求值/编译 |
| Markdown 地位 | 载体与呈现层 | **语法表层的一部分**(源即 Markdown) |
| 成功标准 | 跨组织互通、Agent 可策展 | 严肃编程能力 + 阅读体验同时成立 |
OKF 回答:「人和 Agent 如何**共享与信任知识**?」
Marqdo 回答:「程序如何**本身就是知识**,且仍能运行?」
因此借鉴应落在**表示哲学与工程约束**,而不是照搬「知识目录」产品形态。
---
## 3. 值得借鉴的设计点
### 3.1 后缀与生态搭便车 — 已采纳
OKF 坚持「就是 Markdown」:GitHub 渲染、编辑器预览、静态站、搜索索引零摩擦。
**Marqdo 对应决策:源文件后缀为 `.mq.md`。**
- `.md` 确保通用 Markdown 渲染器开箱可用
- `.mq` 前缀声明这是 Marqdo 源,而非普通文档
- 与 OKF「格式优先于平台」一致:可读性不依赖自研 viewer
### 3.2 最小强制面(Minimally opinionated)
OKF 只强制 `type`;其余可选,未知字段保留不拒绝。
**对 Marqdo 的启发:**
- 语言的「文档面」与「程序面」之间,划清**硬语法**与**散文**
- 第一版语法宜小:标题层级、声明、表达式……先钉死互通/可执行最小集
- 扩展用约定或可选 frontmatter,避免一上来造完整注解宇宙
### 3.3 生成式 YAML / OKF 清单 — 已采纳方向(已修正)
OKF 用 YAML frontmatter 承载「可查询元数据」。Marqdo **借鉴其形态**,但职责不同:
**YAML(OKF 风格知识包)由工具从 `.mq.md` 自动生成,不是人手写的配置文件。**
详见 [`design/generated-yaml-manifest.md`](../design/generated-yaml-manifest.md)。
| | |
|--|--|
| 类比 | 其它语言中由工具维护的依赖描述(如 `Cargo.toml` / `requirements.txt` 所承担的那类角色) |
| 形态 | OKF:概念目录 + YAML frontmatter + Markdown 正文 |
| 用途 | ① 编译器/包管理消费依赖图与导出 ② **自动生成本项目文档**(模块索引、依赖关系等) |
| 权威 | 始终是手写 `.mq.md`;清单可删、可重建 |
```
.mq.md 源(人写)
→ marqdo 工具链
→ 生成 OKF 风格清单(YAML + 概念页)
→ 供编译解析,并渲染为项目目录文档
```
执行方式等运行参数不放进该 YAML 当配置;由 CLI / 子命令决定。
程序本体(类型、函数)只活在源正文里。
### 3.4 路径即身份,链接即关系
Concept ID = 路径;关系 = Markdown 链接;目录 = 渐进披露(`index.md`)。
**对模块系统的启发:**
- 文件路径可成为模块身份的一部分(类比 OKF concept ID)
- `import` / 交叉引用尽量与 Markdown 链接同构,使「读文档跳转」与「解析依赖」共用一种边
- 大型程序按「书的章节」组织目录,而不是扁平包名墙
### 3.5 生产者 / 消费者分离
同一 bundle:人手写、Agent 生成、管道导出,均可被另一 Agent 或 UI 消费。
**对 Marqdo 工具链:**
- 解析器、渲染器、求值器、LSP 都是**消费者**;源格式是唯一契约
- 允许 Agent 协助编写 `.mq.md`,但语言必须对「纯手写」同样友好
- 不把语义锁进某一 IDE 或云服务
### 3.6 信任与 attestation(中长期)
OKF v0.2 的 Attested Computation:批准的算法 + 确定性核验,防止 Agent「随口报数」。
**远期可借鉴(非 v0 范围):**
- 文档中嵌入的「可运行示例」是否经过核验执行?
- 渲染出的结果是否带来源与 receipt?
- Agent 生成的 Marqdo 模块如何标注 `generated` / `verified`?
这强化「文档中的数字/行为与真实执行一致」——与 Marqdo「同一份真相」高度同向。
### 3.7 规范本身的克制
OKF 规范强调:一页纸能讲清 v0.1 的互通面;v0.2 只**加词汇、不加强制规则**。
**对 Marqdo 文档文化:**
- ADR 记录否决项
- 语法草案保持短小、可验证的 conformance 描述
- 版本演进优先加法兼容,避免随意破坏「已是有效程序」的源文件
---
## 4. 不应照搬之处
1. **OKF 不是语言** — 其 body 是自由散文;Marqdo body 必须有严格可执行语义。不能停在「Markdown 知识库」。
2. **无中心 type 注册** 适合知识目录;编程语言的类型系统需要更强的一致性与检查规则。
3. **`Attested Computation` 的 executor/attester** 面向数据平台查询核验;Marqdo 若引入类似机制,应长在「测试 / 示例求值 / 再现构建」上,而不是 BigQuery 收据模型。
4. **保留文件名**(`index.md` / `log.md`)可参考,但是否占用需在模块设计里单独 ADR,避免与源文件约定冲突。
---
## 5. 建议纳入 Marqdo 设计议程的议题
来自本次调研、建议在 `design/` 或 `adr/` 中跟进:
1. **`.mq.md` 的双重解析模型** — Markdown CST 与 Marqdo AST 如何共享同一文本、何处分叉。
2. **生成式 OKF 清单的落盘与命令** — 路径、是否提交 git、`sync`/`doc` 行为(方向已采纳,见 [design/generated-yaml-manifest.md](../design/generated-yaml-manifest.md))。
3. **正文中的依赖声明语法** — import / 链接如何写出,供工具提取进生成清单。
4. **Agent 友好但不 Agent 绑定** — 源格式对 LLM 可写,语义对确定性工具可检。
5. **可渲染结果的 attestation(后期)** — 文档内求值结果的可验证性。
---
## 6. 参考链接
- 规范:[okf/SPEC.md](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)(v0.2)
- 仓库:[GoogleCloudPlatform/knowledge-catalog](https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf)
- 博客:[Introducing OKF](https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing)
- 博客:[OKF v0.2 trust signals](https://cloud.google.com/blog/products/data-analytics/okf-v0-2-adds-trust-signals)
---
## 7. 结论
OKF 证明了一条与 Marqdo 同向的产业判断:**人类可读的 Markdown 可以成为机器与 Agent 的一等交换面**,前提是约定足够小、足够稳,并把信任做成可查询字段而非口头保证。
Marqdo 比 OKF 多走一步:Markdown 不仅是知识的容器,更是**程序的表面语法**。我们借鉴 OKF 的形态,用作**从源自动生成的依赖清单与项目目录文档**(而非人手配置);同时借鉴「格式而非平台」、路径/链接身份、以及(远期)provenance。语言设计必须单独完成——**可渲染不等于可执行,可执行才是 Marqdo 的终点。**
-178
View File
@@ -1,178 +0,0 @@
# Marqdo 参考实现:正经解释器路线图
| | |
|---|---|
| 状态 | 已采纳方向 |
| 日期 | 2026-08-04 |
| 目标 | `marqdo run path/to/index.mq.md` 得到真实执行结果;非演示玩具 |
| 相关 | [markdown-mapping.md](../design/markdown-mapping.md) · [ADR 0001](../adr/0001-implementation-language.md) · [USTC 编译课 2025](https://ustc-compiler-2025.github.io/homepage/) |
---
## 1. 为何是解释器,而不是 USTC 式「编译到机器码」
[USTC《编译原理与技术》2025](https://ustc-compiler-2025.github.io/homepage/) 的实验链是经典**编译器**路径:
```
源码 → 词法(Flex) → 语法(Bison) → AST
→ 语义 / Light IR → 优化 → 后端(龙芯汇编等)
```
这条路适合 Cminusf 一类「最终变成机器指令」的语言。Marqdo 的产品形态是:
- 源即 Markdown 文档,**打开即读、运行即算**;
- 首要交付是 **从 `index.mq.md` 得到求值结果**(stdout、返回值、模块图),不是龙芯/ x86 二进制;
- 语法表面是 Markup-as-Syntax,前端与传统正则+Bison 不同,但**中后端的编译学知识仍然全部用得上**。
因此:
| USTC / 龙书阶段 | Marqdo 解释器中的对应 |
|-----------------|------------------------|
| 词法分析 | **行分类 + 标记词法**(无标记=注释;`#`/`*`/`**`/`>`/`+`/`-`/表…) |
| 语法分析 | **结构解析 → Marqdo AST**(可递归下降;不必上 Bison,除非日后自研纯文本方言) |
| 语义分析 | 作用域、提升、导入、形参绑定、类型(可后置) |
| 中间代码 | **可选**:先树遍历;第二期再降到**字节码** |
| 优化 / 目标代码 | **非 v1 目标**;日后若要可另开「编译后端」ADR |
**结论:做正经解释器 = 把编译前端做扎实 + 把运行时做完整;不是跳过词法语法,也不是一上来 LLVM。**
权威地图见 [Crafting Interpreters — A Map of the Territory](https://craftinginterpreters.com/a-map-of-the-territory.html):用户眼里的「解释器」内部往往仍含编译到字节码(如 CPython);树遍历是第一期,字节码 VM 是第二期。
---
## 2. 推荐总体架构
```
index.mq.md (+ 导入的 .mq.md)
│
▼
┌───────────────────┐
│ 0. 源加载 / 模块图 │ frontmatter `> a.mq.md` → 依赖图
└─────────┬─────────┘
▼
┌───────────────────┐
│ 1. 词法·行分类 │ 注释行丢弃语义;代码行 → Token 流
│ (+ MD 块辅助) │ pulldown-cmark/comrak;+/- 靠行扫描
└─────────┬─────────┘
▼
┌───────────────────┐
│ 2. 语法分析 │ Token/块 → Marqdo AST
│ (递归下降) │ Module / Fun / Stmt / Expr / Branch / Loop …
│ │ **不用 Flex/Bison**(见 dependencies.md)
└─────────┬─────────┘
▼
┌───────────────────┐
│ 3. 语义·绑定 │ Pass1: 收集函数(提升)+ 导入合并
│ │ 作用域链、形参、未定义名诊断
└─────────┬─────────┘
▼
┌───────────────────┐
│ 4a. 树遍历解释器 │ ← Phase I(必须先完成,跑通全部 examples)
│ 或 │
│ 4b. 字节码编译+VM │ ← Phase II(性能与「更像真语言实现」)
└─────────┬─────────┘
▼
stdout / 返回值 / 退出码
```
Phase I 对齐 Crafting Interpreters 的 **jlox(树遍历)**;Phase II 对齐 **clox(字节码 VM)**(见 [Chunks of Bytecode](https://craftinginterpreters.com/chunks-of-bytecode.html))。这是 Python/Ruby/Lua 主实现走过的正经路径,不是玩具捷径。
---
## 3. 各阶段「做满」的标准(反玩具清单)
### Phase 0 — 工程骨架(正式包,不是 `spike/`)
- 包名:`marqdo`(`src/marqdo/` 或 `marqdo/`)
- CLI:`marqdo run <file.mq.md>`,默认找目录下 `index.mq.md`
- 诊断:带文件名、行号、列号
- 测试:每个 `examples/*.mq.md` 有期望 stdout(金样例);CI 可跑
### Phase I — 可运行的语言核心(树遍历)
必须全部为真实现,禁止「正则特判 hello」:
1. **词法 / 行分类**:注释与代码严格分离。
2. **语法 → AST**:函数、形参、`*` 语句、`**` 返回、`>` 调用、`+` 分支、`-` 循环、表格集合、绑定与 `==`。
3. **语义**:提升、嵌套作用域、`##` 私有、frontmatter 导入公有顶层。
4. **运行时**:环境、调用栈、值(文/数/表/记录)、内置 `print`。
5. **验收**:`examples/structure/*` 与 `examples/keywords/*` 全部 `marqdo run` 通过。
### Phase II — 字节码 VM(正经化)
- AST → 线性字节码(栈式 VM 即可,与 clox / [GoAWK 经验](https://benhoyt.com/writings/goawk-compiler-vm/) 同类)
- 控制流用跳转指令实现分支/循环
- 同一套金样例必须 bit-同结果(回归)
- 性能与可调试性(反汇编、栈跟踪)优于 Phase I
### Phase III — 语言完备(按需)
- 更完整表达式文法、错误模型、外联围栏 FFI
- 生成 OKF 依赖目录
- (可选)另一后端:编译到 Python/WASM——**另开 ADR**,不替代自研语义
---
## 4. 与 USTC Lab 的知识复用(学什么、不搬什么)
| 课程内容(摘要) | Marqdo 用法 |
|------------------|-------------|
| Lab1 词法/语法/AST | **直接对标** Phase I 前端;工具可自研递归下降,不必 Flex/Bison |
| Lab2 IR / 访问者 | Phase II 字节码 ≈ 轻量 IR;访问者可用于 AST→字节码 |
| Lab3 后端汇编 | **v1 不做**;解释器 VM 代替机器后端 |
| Lab4 优化 | Phase II 之后可选;解释器也可做常量折叠等 |
教材仍可读:龙书、陈意云《编译原理》、课主页参考书;解释器专项读 **Crafting Interpreters**(免费:[craftinginterpreters.com](https://craftinginterpreters.com/))。
---
## 5. 实现语言(本路线图默认)
**参考解释器:Rust**([ADR 0001](../adr/0001-implementation-language.md))。
- 词法/语法:**自研 + GFM crate**,不用 Flex/Bison([dependencies.md](../design/dependencies.md))。
- Python `spike/` 仅作风险探测与算法草稿。
- Phase I 树遍历、Phase II 字节码 VM 均在 Rust 中实现。
---
## 6. 目录规划(正式代码,非 spike)
```
Cargo.toml
crates/marqdo/ # 或根包
src/lex/ parse/ ast/ sema/ interp/ bytecode/ runtime/
tests/
examples/
spike/ # Python 存档,非运行时依赖
```
---
## 7. 近期里程碑(可执行顺序)
| 周序 | 交付 | 完成定义 |
|------|------|----------|
| M0 | 正式包 + CLI 空壳 + 金样例框架 | `marqdo run` 可调用;测试发现「未实现」 | ✅ |
| M1 | 词法·行分类 + 最小 AST | 单测覆盖注释/代码行 | ✅ |
| M2 | 解析:函数、输出调用、返回 | `hello` + `index` 金样例绿 | ✅ |
| M3 | 分支、循环、表格、绑定 | `branch`/`loop`/`collection` 绿 | ✅ |
| M4 | 导入与提升 | `with-import` 绿;**宣称 Phase I 达标** | ✅ |
| M5 | 字节码设计文档 + 原型 opcode | 核心金样例双后端一致;覆盖表见 [bytecode.md](../design/bytecode.md) | ✅ 原型 |
**Phase I 完成前,不宣称「语言已实现」。**
**仅 hello 特判通过,不算完成。**
---
## 8. 成功判据(产品级)
在仓库根或任意含 `index.mq.md` 的目录:
```bash
marqdo run examples/structure/nested-call.mq.md
# 或
marqdo run examples/structure/import/main.mq.md
```
输出与金样例一致;错误带位置;新增语法必须加金样例与单测。这才是「一门解释型语言」的最低合格线。
+105
View File
@@ -0,0 +1,105 @@
# 架构与所有权
自建 Git `git.cflmy.cn/cflmy` 是代码、工单和合并的权威,`ci.cflmy.cn` 是 CI 权威,GitHub 仅作镜像或分发渠道。主仓库维护生态组件关系、精确组合、跨组件验收、发行与责任治理;领域聚合仓库维护本领域的合同与组合验收;功能仓库拥有唯一实现、测试和缺陷修复。
## 三种关系,不得混用
| 关系 | 表达载体 | 用途 | 约束 |
| --- | --- | --- | --- |
| 治理树 | `.gitmodules` + Git tree gitlink + 每层 `components.toml` | 源码归属、父级与提交身份 | 每个组件只有一个父级;全局 ID 与权威远端唯一;Gitlink 是提交身份唯一权威,`.gitmodules` 是权威远端唯一记录 |
| 构建/制品依赖 DAG | `requires` 与真实 package/Cargo/Tool/Bundle 依赖 | 编译、打包、发行装配顺序 | 可以跨治理树;必须有向无环;聚合节点不是可被程序 import 的包 |
| 协同验收关系 | `checks_with` | 跨组件测试与消费者回归 | 不是安装依赖;允许互相测试;调度固定点必须去重且不得互相等待形成死锁 |
组件关系不能由目录物理位置推导,也不能把兄弟仓库的源码路径当作公开依赖。`requires` 只表达真实直接构建或制品依赖,禁止把计划假想写成实际依赖。
## 治理树与分层
治理树最多两级 Gitlink:**根仓库 → 领域聚合仓库 → 功能仓库**(主仓库→领域→功能,深度 2)。新增三级 gitlink 需要生态 ADR 和真实跨仓维护收益,默认拒绝。目录层级不等于运行时依赖层级。
- **领域(`kind = "domain"`)**:工程治理角色,不是语言层也不是运行协议。领域仓库只登记直属子组件,可拥有 `components.toml`、`.gitmodules`、领域公共规范、跨组件集成测试、综合示例、发布装配脚本、ADR 与维护指南;禁止在其中建立 renderer、解析器、数据库驱动等生产实现,也禁止把子仓库源码复制进普通目录。领域 `requires = []`,`release` 为 `none`(普通领域)或 `base`(Stdlib Bundle 聚合)。
- **功能组件**:`kind` 仍为 `core/stdlib/extension/tool/test`,在责任仓库独立实现、测试和发版;`release` 与 `kind` 的对应关系不变(base/optional/none)。
- **唯一归属**:一个功能只有一个权威实现,一个组件只有一个治理归属,一个公共边界只有一套现行合同。已有仓库直接复用,不能因为命名不符创建重复实现。
- **`planned` 纪律**:已有仓库可以通过 gitlink 固定已发布的开发提交。尚无提交的仓库登记在 [迁移台账](MIGRATION.md)。组件通过联合验收后才晋升为 `active` 并登记实际 `entry`。将直属组件迁入领域时,在同一根候选转移清单和 gitlink,保证一个组件只有一个父级。
- **聚合准入**:功能拆分须至少有一种独立价值(独立维护责任、显著不同依赖/安全/平台边界、独立版本与制品、可重复独立验收)。若两个仓库几乎每个 PR 都必须一起改动且接口未稳定,应先收敛合同或合并,不能无限拆分。
- **工具目录**(`tools/`)暂不聚合,现有四个 Tool 保持原路径。
**当前状态**(以 [components.toml](../components.toml) 与 [迁移台账](MIGRATION.md) 为准):根仓库有六个核心/工具 active 组件(`cli`、`conformance`、`view`、`knowledge`、`prove`、`lint`)和六个已交付源码的 active 标准库组件(`std-collections/data/fs/io/system/text`)。`std-core/encoding/net` 与十八个独立扩展仍是根层 planned 子模块。`extensions/web` 是 planned 领域子模块,Design 和 Preview 由 Web 领域仓挂载。`marqdo-stdlib` 聚合和 `web-components` 仍在计划中。
## 语言与产品层(不因仓库变多而改变)
| 层 | 权威所有者 | 允许 | 禁止 |
| --- | --- | --- | --- |
| L0 语言核心 | CLI | Markdown 映射、AST、IR、Value、Memory、求值 | Web/AI/数据库专属关键字 |
| L1 平台能力 | CLI Capability Host | 权限、预算、通用资源/扩展机制 | 网页布局和业务协议 |
| L2 标准库 | Stdlib 各功能仓库 | 基础发行默认安装的通用低层算法及薄封装 | 依赖领域扩展或大型专业运行环境 |
| L3 扩展 | 各领域功能仓库 | 可选专业算法、协议和资源后端 | 修改或复制语言内核 |
| L4 应用 | 用户项目 | 使用已发布能力实现具体任务 | 作为默认基础发行依赖 |
| Tool(旁路) | 独立工具 | 通过公开 CLI 协议处理源码、分析及制品 | 伪装成 Runtime 插件,反向侵入核心 |
## 权威记录与递归校验
每个拥有子模块的聚合仓库只登记直接子组件;普通功能仓库不需要另建治理清单。配置与身份的唯一来源:
| 记录 | 权威内容 |
| --- | --- |
| `components.toml`(每层) | 组件 ID、父级路径、kind、state、owner、scope、`requires`、`checks_with`、release、active 入口 |
| `.gitmodules`(每层) | 直属子组件权威远端 |
| Git tree gitlink | 精确提交身份 |
| Cargo.lock / `marqdo.lock` / 现行 Bundle manifest | 相应依赖与制品身份 |
主仓库 `scripts/check-layout.py` 校验 catalog、gitlink、远端与文件白名单。`--checkouts` 递归读取每个已挂载领域的固定提交,逐层验证 gitlink、远端、工作树和活跃入口,并检查全局 ID、依赖边界和无环性。CI 用 `--domain-paths` 在检出子组件前校验领域远端。 [开发流程](DEVELOPMENT.md)
## 各领域排他边界
| 领域 / 功能 | 应拥有 | 不应拥有 |
| --- | --- | --- |
| Stdlib/Core、Collections、Text、Encoding、Data、IO、FS、System、Net | 默认安装的通用低层能力及薄封装 | 专业计算、外部服务、HTTP 协议 |
| Ext-Net(HTTP/WebSocket) | URL、HTTP 客户端/服务端协议、SSE、Cookie、Multipart、WebSocket 帧与生命周期 | Web 页面模型、应用实时协作状态 |
| Web 领域 | 设计模型、快速预览、交付清单与组件复用 | 生产级前端框架、HTTP/DB/认证协议、AI 调度 |
| Browser | 将来可选的真实浏览器执行宿主与平台桥 | 本期 Web 原型必需依赖、第二套解释器 |
| AI / MCP | 模型访问、流式结果、工具调用数据;MCP 发现/调用/传输 | 全量 Agent 调度、HTTP 实现、Agent 框架 |
| Database / Storage / Cache / Auth | 参数化查询与事务、存储接口、TTL 缓存、OIDC/会话/RBAC | Web 后台页面、文件系统原语、替代 Capability Host |
| Crypto / Datetime / Regex / Archive | 成熟密码学封装、IANA 时区、完整正则、安全归档 | 自制不安全加密、重复宿主基础原语 |
| Document / Engineering | 文档显式编辑、工程操作与产物 | 静态分析或编辑器全栈平台 |
| Quantum / Linalg / Math | 量子态/电路/模拟、矩阵/张量/分解、数值与符号数学 | 复制矩阵内核、通用前端框架 |
上表是规划边界,不是开发完成承诺。旧标准库中 `net/http.mq.md`、`regex.mq.md`、`compress.mq.md` 的迁移必须有真实替代实现与验收才能退出原归属,不得先删造成回归,也不得长期维护两个官方实现。
## Web 领域
Web 领域的产品定义是**文档原生、可交互的前端设计原型及工程交付**,不是新的通用前端框架。GFM 表描述组件关系,普通 Markdown 描述内容与意图,链接表达精确的组件引用与设计依赖,有限场景表达交互原型;生产级前端由成熟框架完成。HTTP、数据库、认证、浏览器运行时仍是独立通用能力,不是原型工具的强制依赖。
- **唯一作者合同**:[marqdo-ext-web 的 WEB-DESIGN](https://git.cflmy.cn/cflmy/marqdo-ext-web/src/branch/main/docs/WEB-DESIGN.md)。主仓库、组件仓库和作者文档都引用它,不并列维护第二份现行合同;合同变更在该领域走 ADR 并与 Design/Preview 同候选验证。
- **领域聚合** `marqdo-ext-web`(planned):治理、合同、示例、组合验收;无运行时入口,不实现 renderer/parser。
- **Web Design** `marqdo-web-design`(planned):独立 Rust library,唯一解释作者合同、消费真实 CLI Analysis、产出设计模型/诊断/handoff;不启动服务、不渲染 DOM、不复制 CLI parser。
- **Web Preview** `marqdo-web-preview`(planned):独立 executable + `tool.json`,注册唯一 `web` 命令;消费 Design 公开 API,生成离线安全预览与有限状态交互;不自行解释表格、不写任务专用 JS、不启动生产服务器。
- **组件模板** `web-components`:候选,只有至少两个独立真实复用模板及稳定合同后才准入,不阻塞首版。
- **边界**:首版不迁移 WASM、不重新实现语言、不要求旧 plugin 回调,不新增 CLI Web 关键字或 `@component` 语义;复杂视觉、真实登录/支付/数据库/网络和任意状态管理交给生产实现。Web 领域已通过 gitlink 固定开发提交,状态为 `planned`。 [开发流程](DEVELOPMENT.md)
## 新增能力与公共边界
先复用职责匹配的组件。需要独立维护、依赖、安全或发行边界时,为新仓库发起评审;加入标准库须证明基础发行默认需要、至少三个领域真实复用、依赖闭包受控,并说明错误、授权和预算语义。
需要新增 builtin、HostOp、值类型、语法或公共协议字段时,在 CLI 提交 ADR,写明现有机制为何不足、最小复现、三个领域用例、替换及正负例。Web 专属需求不得进入 CLI 核心;设计领域能自己解释的内容留在 Web 合同。公开接口破坏性更新按同一候选组合切换产生者和消费者,保留单套现行协议;历史行为通过固定版本的历史发行复现。
## 架构门禁
| 门禁 | 检查与拒绝条件 | 权威 |
| --- | --- | --- |
| 归属唯一 | Git tree/catalog 递归一致,一个全局 ID 与远端只出现一次,不允许同功能两个官方实现 | 根 |
| 聚合纯度 | 根与领域聚合不含生产实现;新增文件须落在治理/集成/示例职责 | 根/领域 |
| 深度 | 超过两级 Gitlink 拒绝,除非批准 ADR 先更新单一规则 | 根 |
| 真实依赖 | active 不依赖 planned;requires DAG 无环;无父 checkout 或跨仓私有源码依赖 | 根/组件 |
| 标准库准入 | 基础发行默认必需、低层、至少三类真实消费者、依赖与授权有界;新功能默认 extension | Stdlib/根 |
| 内核准入 | 新 builtin/HostOp/语法/协议字段须 ADR、最小复现、三个不相关领域用例;Web 专属需求不进入 CLI | CLI |
| Web 作者面 | 不新增核心语法、重复表头方言、隐式解析普通文档、HTML 注入默认通道 | Ext-Web/Design |
| 通用渲染 | 新普通组件由设计文档复用实现;不得新增任务/页面/业务专用 renderer 分支 | Preview |
| 原型诚实性 | 模拟明确标注;无真实后端、无假执行、无伪造生产测试 | Web |
| 独立产品 | 组件能独立构建;只有实际产品需要才创建新仓库 | 各级 |
| 现行合同唯一 | 不引入旧协议 fallback、版本数组、旧语法探测;配对候选一次切换 | 各级 |
| 默认安装规模 | 基础制品不引入可选 Tool/领域环境;体积、构建时间及依赖增长记录基线 | 根/Stdlib |
| 范围控制 | 每个 PR 关联责任工单、复现与验收;无关重构拆独立任务 | 各级 |
每次架构变更须回答:谁是唯一责任方?是否必须新增公开边界?如何证明现有机制不足?能否在单仓修复?新功能能否独立测试?删除或替代了什么?回答不明确则不进入开发。
跨组件测试以真实 CLI/Worker、独立消费者和现行权限配置验证。Native 后端与外部工具按 CLI 安全边界执行,权限、隔离和预算声明以可验证的实际行为为准。
+101
View File
@@ -0,0 +1,101 @@
# 开发、验收与发行
生态采用**逐层候选晋升**:功能仓库修实现,领域聚合仓库固定组合并做领域验收,主仓库固定整个递归树并做生态验收。任何一层失败都停在该层,不让未验证组合进入受保护的分支;回退根 gitlink 即可复现上一个已接受组合,不重写子仓库历史。
## 责任仓库与工单
1. 先确定唯一责任仓库:功能行为在功能仓库;领域合同、示例与组合在领域聚合仓库;gitlink、跨领域集成、发行组合与治理在主仓库。拿不准时按“第一个违反公开合同的所有者”定责,而不是按错误最后显示的仓库。
2. 在责任仓库找到或建立工单,按 `.gitea/ISSUE_TEMPLATE/change.md` 记录:责任组件与类型、影响消费者、根/领域/组件 SHA、CLI 与依赖制品摘要及平台、最小 fixture 与命令、实际与预期结果、权威合同链接、修复范围、验收命令。
3. 跨仓库阻塞在上游仓库开工单,并在消费者工单记录回归条件;不同问题拆分,重复发现追加证据。任何维护者或 AI 都可以读其它仓库定位,但修改必须进入对应责任仓库的独立提交。
## 分层候选流程
以 Web 领域为例,一般组件同理:
```text
功能提交 C2(功能仓库,通过组件 CI)
-> 领域 PR 将 gitlink 更新到 C2,通过领域 CI,形成 B2
-> 主仓库 PR 将领域 gitlink 更新到 B2,通过根递归校验与受影响组合验收,形成 A2
```
- 子模块的 detached HEAD 只用于复现与集成;开发应在子仓库独立创建分支后推送,禁止 `git submodule update --remote` 在发布/验收中追踪浮动分支。
- 同一份公共合同切换需要多个组件同步变化时,在一个候选组合中提交整组 gitlink,配对候选联调通过后再晋升;不允许主分支出现半套协议。
- 领域激活(planned → active)的门禁:两个功能仓具备真实 `entry` 与候选提交,领域 `components.toml` 与 gitlink 一致,领域 CI 和根递归校验通过,Design/Preview 等有依赖关系的组件获得同候选证据。已发布的开发提交可先作为 `planned` 子模块固定。
## 递归校验与组合检查
```sh
git submodule update --init --recursive
python3 scripts/check-layout.py # 根层:catalog/gitlink/远端/白名单
python3 scripts/check-layout.py --checkouts # 递归:各 active 领域固定提交、全局图与依赖
python3 -m unittest discover -s tests/integration
bash scripts/integration.sh # 生态候选:真实 CLI 制品 + 组件验收
```
- 校验器读取 Git tree 中固定提交的 catalog,不以工作区改动替代候选;`--checkouts` 需要子模块已初始化,缺失、错误 HEAD、脏工作区、错误入口都明确 FAIL/UNVERIFIED,不静默跳过。CI 先验证并检出直属子模块,再用 `--domain-paths` 校验领域的子模块远端,最后逐个领域检出直属子库。
- 没有 active 领域时,新校验规则同样接受合法的直属功能组件,这不是历史协议兼容。
- 未知的 active 入口、未声明的 gitlink、目录与 catalog 不一致都必须让候选失败。`planned` 不进入验收计数。
- 当前 CI 为 `layout` 与 `candidate` 两段;统一 CLI 制品准备、声明驱动调度与递归影响分析仍在推进(见 `.woodpecker/eco.yml` 与主仓库工单),不得以本文件描述当作已实现。
## 三层验收
| 层 | 责任与证据 |
| --- | --- |
| C1 组件 CI | 责任组件独立检出、独立构建与测试、授权负例、固定依赖、打包 smoke;由组件仓库维护 |
| C2 公共契约 | 真实 CLI 和 Worker、独立 Conformance 与消费者,覆盖当前协议、失败和正确身份 |
| C3 生态集成 | 递归结构校验、公开冷克隆、精确 gitlink、官方基础发行、CLI Tool 与契约消费回归 |
三层不是重复跑三次测试:同一候选、同一制品、同一环境的有效证据可以复用;身份不匹配必须重跑。每个 active 组件提供独立验收入口(建议 `scripts/ci.sh` 或 `scripts/integration.sh`),从显式传入的 `MARQDO_BIN`、Bundle/依赖制品位置和隔离输出目录读取输入,不自行拉取浮动 CLI 或其它组件 main。
## 统一 CLI 与制品输入
- 生态候选使用**固定、可验证**的 CLI/Worker/Stdlib 候选制品;输入必须绑定 CLI gitlink SHA、目标平台、归档/二进制/Bundle digest、工具链与锁。
- 标准库 Bundle 的唯一生产者是根仓库的 `scripts/build-stdlib.py`:它从根提交的精确组件 gitlink 读取各 active `kind = "stdlib"` 组件的 `modules/`,校验发布路径(只发布 `.mq.md`、拒绝 symlink/子模块/大小写与 NFC 冲突、`tests/` 不入库),生成现行 `stdlib.json`(tree digest + aliases digest),配置在 `scripts/stdlib-bundle.json`。版本变化必须显式(`--baseline-manifest` 拒绝同版本不同摘要)。组件仓继续拥有源码与测试,根不复制模块。
- 组合验收入口是根仓库的 `scripts/acceptance-stdlib.py`:只接受显式 `--cli` 与 `--bundle`(或按根 gitlink 构建),运行各 active 组件的 `entry`、跨仓组合 fixture(别名、Table 切分、默认 Bundle smoke)和必须失败的负例;提供 `--pack-tool` 时用 CLI 自己的打包器做两次确定性打包并核对摘要。CLI 自身打包请使用 Phase A 之后的 `--stdlib-dir` 输入,不再默认读取 CLI 源码树。
- 统一制品输入已落地(ECO-02 核心):`scripts/integration.sh` 不再从 View 的冻结脚本取 CLI 制品,而是由同一根候选派生全部输入——根唯一生产者 `scripts/build-stdlib.py` 按固定 gitlink 生成 Bundle;`cli/` 固定提交构建 CLI 与 Worker;`cli/tools/release/package.py --stdlib-dir <Bundle>` 生成发行归档;随后 Conformance、View、Knowledge、Prove、Lint 与根 `acceptance-stdlib.py` 全部使用同一安装后二进制与相邻 Bundle。任何消费者都不能决定 CLI 版本,也不再有浮动或隐式制品。
- 组件验收只读取传入制品,不自行下载未知版本;开发目录覆盖入口(如 `MARQDO_STDLIB_DIR`)不得当作发行行为。缺失、摘要不符或平台不符必须拒绝。
## 影响范围与调度
根 `scripts/impact.py` 比较已接受根提交与候选递归展开的 `(global_id, parent, remote, SHA, state)`:领域指针变化展开到子组件身份,不能只标记父节点;变更叶子加入集合后,取 `requires` 新旧图并集的反向传递依赖闭包,再加所在祖先领域及 `checks_with` 固定点(协同验收不是构建先决)。领域无法展开(缺对象/检出)时结果标 UNVERIFIED 并**全量**扩大范围,不静默跳过;`--fail-on-unverified` 可把该情形变成硬失败。`integration.sh` 将报告写入候选证据(changed/affected/checks_with/fallback),正式发行仍执行所有 active 组件与完整测试。
## 工单路由与状态
| 现象 | 责任归属 |
| --- | --- |
| 组件表头正确但 Design 未识别 | web-design(若 Analysis 的真实 AST 正确) |
| Link 中 `not_loaded` 错误处理 | web-design;若 CLI candidate 违反公开 resolver 合同则 CLI |
| 手机布局溢出、场景实例串扰 | web-preview |
| 特定设计模板不符合合同 | web-components(激活后)或作者项目,不修改核心 renderer 迎合坏模板 |
| Web 设计约定出现冲突 | marqdo-ext-web 协调,Design/Preview 各自提交 |
| 真实生产框架渲染/业务错误 | 目标应用仓库,不归 Web 原型 |
| SSE 或网络传输错误 | Ext-Net 的 HTTP/WS 或 CLI Resource 真正责任方 |
| 固定 SHA 组合构建失败 | 若各组件公开制品正确,由所属聚合/根修复装配,否则责任组件 |
状态流:`open → triaged → in-progress / blocked → component-verified → integrated`。可用现有 Git 平台标签与关联链接,不设计新工单数据库;阻塞项不能以 mock PASS 关闭。组件 PR 合并后可关闭组件修复工单,但消费者/领域或生态集成任务保留到真实候选组合通过。
## 自动化权限
先实现人工触发与 PR/CI 门禁,不开发自动 Agent 管理平台。Webhook 只作通知(记录仓库、完整 SHA、CI URL);上级通过 API 验证存在性、审批与权限后再创建候选 PR,不得自动合入或提升权限。外部不可信 PR、未批准 gitlink 或脚本不得在拥有跨仓库写权限/发版密钥的 runner 中运行;区分只读 checkout/test token、受限 issue/PR token、受保护发布权限。日志不得输出凭证、完整 Analysis 或生产 API key。
## 发行与回滚
- 组件可独立 SemVer 发布;领域可发布经过验证的组合制品;根生态 release 固定整个 gitlink 树。独立版本不代表维护多套现行协议。
- 每份证据记录根及递归组件 SHA、制品摘要、真实命令、退出码、环境/工具链、日志、测试范围与未验证项。复用现有 manifest/evidence 模式,不复制成新的权威锁。
- Git tree 是源码身份权威;Cargo.lock/`marqdo.lock`/现行 Bundle manifest 是对应依赖权威。记录不可变归档校验和、可信来源及获取方法;摘要校验不是发布者身份认证。
- 基础发行包含同源 CLI、必需 Worker 与单一标准库 Bundle;不使用浮动 branch/标签名作为发布依据。发布失败保留日志,使用新候选;已有标签和资产保持不可变。回滚用新集成提交恢复上一组通过的 gitlink。
## Web 领域开发约束
- 唯一作者合同是 `marqdo-ext-web` 的 `docs/WEB-DESIGN.md`;Design 是唯一解释实现,Preview 不另加解析规则。合同变更在该领域走 ADR,并让 Design/Preview 以配对候选一次切换。
- Design 只消费公开 CLI `check --emit` 的 Analysis 3,不复制 Markdown/语言解析器、不依赖 CLI 私有 Rust crate;Preview 只消费 Design 的公开 crate/固定 revision,`,...` 不通过 `../design` 长期路径依赖,最终发布以 `Cargo.lock` 固定真实依赖身份。
- 首版不迁移 WASM、不新增 CLI 语义、不要求旧 plugin 回调;模拟状态、原型标识与“未实现真实功能”必须对作者可见。
- 真实验收使用真实浏览器 `file://` 制品、真实 CLI 正负例与真实冷安装;原型测试 PASS 不能当作生产测试 PASS。
## 本地环境
需要 Linux x86_64/glibc ≥ 2.39、Python 3.11+、Git、Rust、C 编译器和 curl;`integration.sh` 另需 jsonschema 与冻结 CLI 归档。详细命令与组件验收入口见各仓库 `README.md` 与 [各仓库任务](REPOSITORY-TASKS.md)。
## 迁移台账
标准库与扩展的现状、历史归属和切换顺序以 [迁移台账](MIGRATION.md) 为准。当前 CLI 内置标准库仍是基础发行的现行权威;`marqdo-stdlib` 聚合与九个功能仓库的迁移完成前,不得声称 Stdlib 拆分完成,也不得先删旧实现造成产品回归。
+207
View File
@@ -0,0 +1,207 @@
# 迁移台账
## 权威盘点
历史主分支最后提交为 `1c55baabd570e18b9da8f9057cef2f848e176690`,v2.9.1 的发布提交为 `ffe06d7afab7acaed87be5ff16edddc37da536a2`。自建 Git 已核验旧标签和主分支。旧实现、文档、示例、测试与工作流以历史提交为迁移资料。[历史主分支末尾](https://git.cflmy.cn/cflmy/marqdo/src/commit/1c55baabd570e18b9da8f9057cef2f848e176690)
| 已有仓库 | 审计时默认分支 | 发行或证据 |
| --- | --- | --- |
| [marqdo-cli](https://git.cflmy.cn/cflmy/marqdo-cli) | `master` | v3.0.0-rc.4 |
| [marqdo-extension-conformance](https://git.cflmy.cn/cflmy/marqdo-extension-conformance) | `main` | 有独立固定 fixture |
| [marqdo-knowledge](https://git.cflmy.cn/cflmy/marqdo-knowledge) | `master` | v0.1.0-beta.3 |
| [marqdo-lint](https://git.cflmy.cn/cflmy/marqdo-lint) | `main` | v0.2.0 |
| [marqdo-prove](https://git.cflmy.cn/cflmy/marqdo-prove) | `master` | v0.1.0-beta.1 |
| [marqdo-view](https://git.cflmy.cn/cflmy/marqdo-view) | `master` | v0.3.0 |
| [marqdo-ext-web](https://git.cflmy.cn/cflmy/marqdo-ext-web) | `main` | Web 领域聚合,planned;唯一设计合同在 `docs/WEB-DESIGN.md` |
| [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) | `main` | Web Design 组件,planned;初始开发文档 |
| [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview) | `main` | Web Preview 组件,planned;初始开发文档 |
CLI gitlink 采用 RC.4 正式发布源码,以匹配冻结归档和现有 View/Lint 契约。
其文档后续提交曾用于 Knowledge 的独立 CI;生态候选以自身测试判定实际组合。
Conformance 使用 CLI 已固定的真实 fixture 提交。
## 标准库和扩展目录
主仓库的 [标准库目录](../stdlib/README.md) 和 [扩展目录](../extensions/README.md) 通过 Git 子模块固定独立仓库的开发提交。Web Design 和 Preview 从 Web 领域聚合仓递归获取。是否参加发行验收以 [组件目录](../components.toml) 与该组件所在层的 catalog 为准。
**标准库(planned,聚合仓库 marqdo-stdlib 尚未创建)** · [core](https://git.cflmy.cn/cflmy/marqdo-std-core) · [collections](https://git.cflmy.cn/cflmy/marqdo-std-collections) · [text](https://git.cflmy.cn/cflmy/marqdo-std-text) · [encoding](https://git.cflmy.cn/cflmy/marqdo-std-encoding) · [data](https://git.cflmy.cn/cflmy/marqdo-std-data) · [io](https://git.cflmy.cn/cflmy/marqdo-std-io) · [fs](https://git.cflmy.cn/cflmy/marqdo-std-fs) · [system](https://git.cflmy.cn/cflmy/marqdo-std-system) · [net](https://git.cflmy.cn/cflmy/marqdo-std-net)
**扩展(planned,独立组件)** · [math](https://git.cflmy.cn/cflmy/marqdo-ext-math) · [linalg](https://git.cflmy.cn/cflmy/marqdo-ext-linalg) · [quantum](https://git.cflmy.cn/cflmy/marqdo-ext-quantum) · [http](https://git.cflmy.cn/cflmy/marqdo-ext-http) · [websocket](https://git.cflmy.cn/cflmy/marqdo-ext-websocket) · [ai](https://git.cflmy.cn/cflmy/marqdo-ext-ai) · [mcp](https://git.cflmy.cn/cflmy/marqdo-ext-mcp) · [crypto](https://git.cflmy.cn/cflmy/marqdo-ext-crypto) · [database](https://git.cflmy.cn/cflmy/marqdo-ext-database) · [storage](https://git.cflmy.cn/cflmy/marqdo-ext-storage) · [cache](https://git.cflmy.cn/cflmy/marqdo-ext-cache) · [security](https://git.cflmy.cn/cflmy/marqdo-ext-security) · [browser](https://git.cflmy.cn/cflmy/marqdo-ext-browser) · [document](https://git.cflmy.cn/cflmy/marqdo-ext-document) · [archive](https://git.cflmy.cn/cflmy/marqdo-ext-archive) · [engineering](https://git.cflmy.cn/cflmy/marqdo-ext-engineering) · [regex](https://git.cflmy.cn/cflmy/marqdo-ext-regex) · [datetime](https://git.cflmy.cn/cflmy/marqdo-ext-datetime)
**Web 领域(planned domain)** · 聚合 [marqdo-ext-web](https://git.cflmy.cn/cflmy/marqdo-ext-web)(唯一合同 `docs/WEB-DESIGN.md`)· 子组件 [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design) · [marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview)
## 分层治理与领域聚合(2026-11-26 起)
根 catalog 支持唯一的新增类型 `kind = "domain"`(聚合治理角色),治理树最多两级:**根 → 领域聚合 → 功能组件**。规则要点:
- 每个拥有子模块的聚合仓库只登记直接子组件;全局 ID 与权威远端唯一;功能仓库仍只有一个父级。Gitlink 是提交身份唯一权威,`.gitmodules` 是权威远端唯一记录。
- 聚合仓库可拥有 `components.toml`、`.gitmodules`、领域公共规范、跨组件集成测试、综合示例、发布装配脚本、ADR 与维护指南;**禁止**生产实现与源码复制。
- 已有 `planned` 仓的 gitlink 固定真实开发提交。尚无提交的组件只登记计划,激活以后再填写真实 `entry` 并计入完成率。领域及其后代分别登记在各自父仓库。
- 领域激活门禁:子组件具备真实入口与候选提交、领域 catalog 与 gitlink 一致、领域 CI 通过、根 `check-layout.py --checkouts` 递归校验通过、存在依赖关系的组件以同候选证据验证。
- 主仓库 `scripts/check-layout.py` 已引入 domain 角色与递归校验;统一 CLI 制品准备、声明驱动调度、递归影响分析仍在推进,CI 证据以真实候选为准。
当前状态:**没有任何 active 领域**。Web 领域为 planned(`extensions/web`,聚合仓 marqdo-ext-web,子组件 design/preview 在其 catalog 登记);标准库聚合 marqdo-stdlib 尚未创建,九个 `std-*` 保持根 catalog 的 planned 直属记录;HTTP/WebSocket 等仍为独立 planned 扩展,等至少两个真实组件形成共同边界后再评估聚合。首批 Web 实施工单为 WEB-00(合同与真实 Analysis 风险探测)、WEB-01(Design)、WEB-02(Preview)、WEB-03(handoff/组件图)、WEB-04(组合案例与框架交付)、WEB-05(根接入与冷安装),WEB-06(components)为候选;工单在对应责任仓库创建。Web 合同语义冲突由 marqdo-ext-web 协调,不回流 CLI 核心。
## 阶段与阻塞
| 原分支 | 独立仓库与迁移状态 |
| --- | --- |
| `gh-pages` | 官网架构、v2.9.1 源内容和部署快照均已迁入 marqdo-site。原分支保留现有公共入口,部署切换以独立托管和路由验收为准。[托管切换工单](https://git.cflmy.cn/cflmy/marqdo-site/issues/1) |
| `vscode-extension` | 扩展目录历史归档到 marqdo-vscode 的 `legacy-v2.8.0`。现行 CLI 适配和新版 VSIX 由扩展仓独立开发和验收。[首版实现工单](https://git.cflmy.cn/cflmy/marqdo-vscode/issues/1) |
| 阶段 | 当前范围 | 后续验收 |
| --- | --- | --- |
| M0 盘点 | 自建 Git、历史标签、已有六组件和新仓位 | 通过真实远端候选持续维护台账 |
| M1 集成骨架 | 六个 active gitlink,另固定 28 个直属和 2 个 Web 子级的 planned 开发提交 | 查看候选 Woodpecker 运行及各组件独立 CI |
| M2 标准库切换 | planned,CLI RC.4 提供官方完整 Bundle | [CLI 外部 Bundle](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) 和 [九组件切换](https://git.cflmy.cn/cflmy/marqdo/issues/2),包括 HTTP、Regex、Archive 迁出与同步删除旧路径 |
| M3 跨仓闭环 | 工单、人工候选、同 SHA 门禁 | [跨仓库 CI](https://git.cflmy.cn/cflmy/marqdo/issues/3) 跟踪真实缺陷闭环、候选通知鉴权、去重和影响分析 |
| M4 领域接入 | Web 领域 planned:三仓文档与工单就绪;根 catalog 登记 planned domain | W-M0 真实 CLI 风险探测、WEB-01/02 实现、领域 gitlink、根递归校验与冷安装验收;Stdlib 聚合按 STD-01..04 独立推进 |
| 后续领域 | 空仓和预期职责 | 逐组件开展最小真实功能、独立 CI、制品与接入 |
### 标准库切换顺序
1. CLI 打包器与产品测试接受单一显式外部 Bundle 输入。内核独立编译;制品仍附带一个校验过的标准库。
2. 标准库在各组件维护唯一生产源码和自测。组装拒绝冲突、符号链接或测试污染,调用 CLI 权威打包器。std-io 维护 print/打印 的别名元数据。
3. HTTP、Regex、Archive 的真实替代和授权回归先行。候选同时移除 CLI 中旧领域宿主服务和旧导入。
4. 验证同输入两次组装结果、摘要及路径负例、C1/C2/C3、独立冷安装和真实工具集成后,再切换基础发行。当前状态为 UNVERIFIED。
## 标准库源码归位迁移(marqdo#9,2026-11-26 M0 冻结)
本节是标准库迁出的**唯一现行台账**,取代此前按未来目录规划起草的路径表(如 `system/clock.mq.md`、`io/index.mq.md`);旧路径方案会改变公开 `std:` 路径,与“迁移不改语言/库语义”冲突,已作废。详细实施与验收见父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),各接收仓子工单在对应仓库 issue #1。
### 基线与身份(M0)
| 对象 | 权威身份 |
| --- | --- |
| 根仓库 | `cflmy/marqdo@484cb10d66db9b92f0527499642ae6abddb3ef29` |
| CLI 标准库源 | `cflmy/marqdo-cli@452e9a32bd9e40dba427d4180691c58bab74449e`(RC.4 发行组合;`stdlib/` 自 `4bbefc9` 起未变) |
| 迁移前 Bundle | `marqdo-stdlib@0.1.0`,tree digest `sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`(含 `tests/`) |
| 公开函数台账 | 20 个模块、151 个 H2 函数,由基线 Bundle 上 `marqdo inspect --signature` 生成并记入各接收仓工单 |
| CLI 显式 Bundle 输入 | [marqdo-cli#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) Phase A(PR #12)已提供 `--stdlib-dir`/pin 校验;Phase B(删除仓内源树)以本台账根组合验收为前置 |
### 模块归属与冻结发布路径
接收仓库负责源码、测试和后续缺陷;根只做组合、锁定和验收。`modules/` 镜像 Bundle 根相对路径,只收模块不收 `tests/`;官方 manifest 由根唯一生产者生成。
| 原 CLI 路径(相对 `stdlib/`) | 接收仓 / 工单 | 冻结发布路径(Bundle 根相对) | 公开函数 |
| --- | --- | --- | --- |
| `clock.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `clock.mq.md` | 1 |
| `datetime.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `datetime.mq.md` | 14 |
| `env.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `env.mq.md` | 2 |
| `process.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `process.mq.md` | 1 |
| `random.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `random.mq.md` | 2 |
| `format.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `format.mq.md` | 8 |
| `io.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `io.mq.md` | 5 |
| `io/console.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `io/console.mq.md` | 4 |
| `io/stream.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `io/stream.mq.md` | 3 |
| `data/json.mq.md` | [std-data#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1) | `data/json.mq.md` | 22 |
| `data/csv.mq.md` | [std-data#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1) | `data/csv.mq.md` | 7 |
| `data/table.mq.md` | [std-collections#1](https://git.cflmy.cn/cflmy/marqdo-std-collections/issues/1) / [std-data#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1) | `collections/table.mq.md`(8 个值操作)/ `data/table.mq.md`(4 个序列化) | 12 |
| `fs/file.mq.md` | [std-fs#1](https://git.cflmy.cn/cflmy/marqdo-std-fs/issues/1) | `fs/file.mq.md` | 14 |
| `path.mq.md` | [std-fs#1](https://git.cflmy.cn/cflmy/marqdo-std-fs/issues/1) | `path.mq.md` | 8 |
| `text.mq.md` | [std-text#1](https://git.cflmy.cn/cflmy/marqdo-std-text/issues/1) | `text.mq.md`(`utf8编码` 薄封装) | 1 |
| `text/utf8.mq.md` | [std-text#1](https://git.cflmy.cn/cflmy/marqdo-std-text/issues/1) | `text/utf8.mq.md`(唯一编解码实现) | 10 |
| `net/http.mq.md` | [ext-http#1](https://git.cflmy.cn/cflmy/marqdo-ext-http/issues/1) | 显式 Package 入口 `index.mq.md`,**不进入默认 Bundle**,不再是 `std:` | 11 |
| `regex.mq.md` | [ext-regex#1](https://git.cflmy.cn/cflmy/marqdo-ext-regex/issues/1) | 显式 Package 入口 `index.mq.md`,**不进入默认 Bundle**,不再是 `std:` | 22 |
| `compress.mq.md` | [ext-archive#1](https://git.cflmy.cn/cflmy/marqdo-ext-archive/issues/1) | 显式 Package 入口 `index.mq.md`,**不进入默认 Bundle**,不再是 `std:` | 2 |
| `demo.mq.md` | 不设接收仓;根 Bundle 组合 fixture | 不作为公开安装模块 | 2 |
`std-core`、`std-encoding`、`std-net` 没有与之对应的旧模块:本轮不发空工单、不激活、不要求补齐未来规划;若已实现模块被本期 Bundle 实际依赖,再按真实依赖补充工单。
### 原测试断言归属
每项必须在新归属留下真实执行证据;跨模块断言归根 Bundle 组合测试。
| 原 `stdlib/tests/` 文件 | 接收仓 | 断言载体 |
| --- | --- | --- |
| `clock.mq.md`、`datetime.mq.md`、`env.mq.md`、`process.mq.md`、`random.mq.md` | std-system | 组件 case,覆盖原 Rust 断言 |
| `console.mq.md`、`format.mq.md`、`io.mq.md`、`stream.mq.md` | std-io | 组件 case + resource 端点事件检查 |
| `csv.mq.md`、`json.mq.md` | std-data | 组件 case,覆盖原 Rust 断言 |
| `table.mq.md` | std-collections(值操作)+ std-data(GFM)+ 根组合 | 切分后的组件 case 与根组合用例 |
| `fs.mq.md`、`path.mq.md` | std-fs | 组件 case,覆盖原 Rust 断言 |
| `text.mq.md`、`utf8.mq.md` | std-text | 组件 case,覆盖原 Rust 断言 |
| `http.mq.md` | ext-http | 领域回归(基线仅运行级覆盖,需补真实断言) |
| `regex.mq.md` | ext-regex | 领域回归,覆盖原 Rust 断言 |
| `compress.mq.md` | ext-archive | 领域回归,覆盖原 Rust 断言 |
| `demo.mq.md` | 根 Bundle 组合测试 | 组合运行证据 |
### 决策与取舍
1. **冻结路径**:以 Bundle 根相对路径为公开身份,迁移不改 `std:` 导入路径;被旧台账规划改名(如 `system/clock.mq.md`、`io/index.mq.md`)的条目按本表冻结。
2. **测试不随发行**:`tests/` 迁入组件仓并留在仓库外,默认 Bundle 只含模块;因此 Bundle 内容必然变化,版本与 digest 由 MIG-BUNDLE 唯一生产者显式更新,摘要算法不变。
3. **Table 切分**:值操作以 `std:collections/table` 为唯一权威,GFM 序列化以 `std:data/table` 为唯一权威;不保留旧 `std:data/table` 的值操作兼容转发,已知消费者在同一候选内更新。
4. **Text 去重**:UTF-8 编解码唯一实现在 `text/utf8.mq.md`,`text.mq.md#utf8编码` 为保留公开名称的薄封装。
5. **IO 别名**:`io.mq.md` 保持官方 `print`/`打印` 的别名目标 `写值`,签名与 effects 不变;别名元数据仍由 Bundle 生产者生成。
6. **三个领域模块**:HTTP/Regex/Archive 迁入既有扩展仓,按现行 Package 布局以 `index.mq.md` 为唯一公开入口(消费者经 `@alias` 显式依赖),退出默认 Bundle,不保留隐藏的 `std:` fallback;HTTP 的 bundle 内相对 import 改为公开 `std:text/utf8`。CLI 现有 `regex.*`/`compress.*` 宿主请求是历史例外,本轮不删除也不新增同类请求,彻底消除另开工单。
7. **`demo.mq.md`**:不作为公开库模块,转为根 Bundle 组合 fixture,避免为了放置文件创建无独立责任的新仓库。
8. **staging 不是发行**:迁移期为了隔离测试,允许用基线 Bundle 覆盖组件模块并重算 digest 的 staging 组合;它不是官方发布源,最终只有根唯一生产路径。
9. **CLI 侧最小修改**:Phase A 显式制品输入已落地;Phase B 删除仓内官方源树只在组件替代与根组合验收通过后执行,不同时进行核心重构。
10. **未创建的新仓**:不为缺失模块创建同名替代仓;`marqdo-stdlib` 聚合仓仍未建立,聚合治理按原独立计划推进,不阻塞本次源码归位。
### 迁移状态
| 项 | 状态 | 证据 |
| --- | --- | --- |
| M0 盘点与派单 | 完成 | 本节、9 个接收仓 issue #1、[marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9) 评论 |
| 组件接收(源码+断言) | 候选已推送(6 个 std 仓,同候选配对) | [std-text PR #2](https://git.cflmy.cn/cflmy/marqdo-std-text/pulls/2)、[std-system PR #2](https://git.cflmy.cn/cflmy/marqdo-std-system/pulls/2)、[std-io PR #2](https://git.cflmy.cn/cflmy/marqdo-std-io/pulls/2)、[std-fs PR #2](https://git.cflmy.cn/cflmy/marqdo-std-fs/pulls/2)、[std-data PR #2](https://git.cflmy.cn/cflmy/marqdo-std-data/pulls/2)、[std-collections PR #2](https://git.cflmy.cn/cflmy/marqdo-std-collections/pulls/2) |
| 领域模块(http/regex/archive) | 候选已合并为显式 Package | [ext-http PR #2](https://git.cflmy.cn/cflmy/marqdo-ext-http/pulls/2)、[ext-regex PR #2](https://git.cflmy.cn/cflmy/marqdo-ext-regex/pulls/2)、[ext-archive PR #2](https://git.cflmy.cn/cflmy/marqdo-ext-archive/pulls/2) |
| Bundle 唯一生产者 | 已实现,M2 候选真实构建两次逐字节一致 | `scripts/build-stdlib.py`、`scripts/stdlib-bundle.json`、`tests/integration/test_build_stdlib.py` |
| 组合验收入口 | M2 候选 PASS(组件 entry + 跨仓组合 + 负例 + 相邻离线安装 + CLI 确定性打包) | `scripts/acceptance-stdlib.py`、[M2 候选证据](evidence/2026-11-26-stdlib-m2-candidate.md)、[根 PR #11](https://git.cflmy.cn/cflmy/marqdo/pulls/11) |
| CLI 旧源树删除 | 候选完成:CLI 仓已无 `stdlib/` 源树、无编译期 fallback,pin 指向生态 Bundle | [marqdo-cli#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11)、[CLI PR #17](https://git.cflmy.cn/cflmy/marqdo-cli/pulls/17)、[Phase B 证据](https://git.cflmy.cn/cflmy/marqdo-cli/src/branch/migration/cli-stdlib-phase-b/docs/evidence/2026-11-27-issue-11-phase-b.md) |
| 统一 CLI/Worker/Bundle 制品输入(ECO-02 核心) | 已落地:integration.sh 由同一根候选派生全部输入,不再使用 View 冻结制品 | 根 `scripts/integration.sh`、[marqdo#7](https://git.cflmy.cn/cflmy/marqdo/issues/7) |
| 根组合与切换 | **已晋升**:`main` = `f4e292e`,固定 CLI Phase B `deadf6e` 与六个 std/三个 ext 组件;根生态 CI(pipeline 38)PASS | [M3 证据](evidence/2026-11-27-stdlib-m3-candidate.md)、[根 PR #12](https://git.cflmy.cn/cflmy/marqdo/pulls/12) |
| M4 发行级验收 | 离线冷安装 PASS(`ubuntu:24.04 --network none`,归档 `sha256:377d2787...`);多平台不在本线支持矩阵 | [M3 证据的晋升章节](evidence/2026-11-27-stdlib-m3-candidate.md#晋升与-m4-验收) |
## v2 功能历史索引
按表中的归属逐项拆分工单,记录来源路径、目标接口、正负例、状态和真实测试提交。
| 旧版 lib 模块 | 目标 | 迁移决策 / 主要缺口 |
|---|---|---|
| archive | archive | ZIP/TAR 等安全归档;现有 gzip 迁移,测试路径穿越 |
| browser | browser | 31 个 H2 所涉 DOM、存储、事件、fetch、WS、下载;不复制旧 WASM runtime |
| bytes | std-text / std-encoding | 字节值、slice、UTF-8 归 Text,base64 归 Encoding,单一 byte 表示 |
| cli | std-system | 应用参数 parse,非 CLI 自身 flag parser |
| csv | std-data | 已有 parse/format;补非法输入与多行测试 |
| datetime | std-system / datetime | UTC 基础已有;时区、DST 和高级日历明确拆分 |
| document | document | sections、tables、links、code blocks、replace;通过受支持静态事实与显式文件编辑 |
| encoding | std-encoding | Base64/Base32/Hex 编解码缺失 |
| foreign | CLI 现有 Foreign / 独立可选会话扩展(待 ADR) | one-shot run/call 已有;不恢复 set_cmd/register 等隐式动态机制;session/replay 需真实设计 |
| fs | std-fs / document / engineering | 40 个 H2 涵盖文件操作;新版14个 H2;二进制、递归、原子、临时、读写组合;文本 patch/工程 sync 归相应扩展 |
| hash | crypto | SHA/HMAC 等,密码学不进入内核 |
| html | web(合同见 WEB-DESIGN) | HTML escape/unescape 属渲染安全细节,按 WEB-DESIGN 与 Preview 安全合同处理;不恢复旧页面/模板插件模型 |
| json | std-data | parse/stringify 已有;get/keys/set 等可复用 collections;严格 Result |
| log | std-system | 结构化、level、输出门面,不引入服务框架 |
| math | std-core / math | abs/min/max/clamp 基础归 Core;数值、超越、公式、CAS、绘图归 Math;随机归 System |
| net | std-net / http / ai / document | TCP/TLS 基础归 Net;HTTP/SSE/cookie/multipart/download 归 HTTP;OpenAI 特定 SSE 归 AI;Markdown 解析归 Document 或公开静态事实 |
| path | std-fs | join/normalize 等已有;relative/with_extension 等补齐 |
| plugin | CLI 现行扩展选择机制 | 不迁移 load/unload 自动加载;使用显式 descriptors、lock、grant |
| re | regex | 查找/替换/分割/捕获和现有纯子集、成熟后端,取消宿主 convenience 重复 |
| result | std-core | ok/error/value_or,统一现行可恢复错误约定 |
| secrets | std-system / crypto | token 生成归 System,密钥/密码学安全操作归 Crypto;不泄漏 secret |
| stats | math | mean/median/stdev;定义样本与总体、空集合、精度 |
| subtask | CLI Structured Tasks(待开发) / std-system | spawn/join/cancel 等先验证通用语义;库只薄封装,不移植旧 scheduler |
| sys | std-system / CLI 公共事实 | env/args/process/clock;旧 stream_publish 和 meta 由现行 Observation/Analysis 或真正应用输出处理;不恢复隐式环境写入 |
| table | std-collections / std-data | 60 个 H2 入口(List/Map/Table 混合);值操作归 Collections,GFM/数据格式归 Data |
| text | std-text | trim/split/join、contains/replace、大小写、repeat/pad 等缺口 |
| time | std-system | now/UTC parse 已部分有;sleep 仅在受控原语可用后实现 |
| toml | std-data | parse/stringify/try_parse,实际支持标准及错误边界 |
| url | http | URL parse/query/percent 与同协议归属,std-net 不重复 |
| uuid | std-system | v4 使用 OS entropy;检查版本/variant |
| writeback | document / engineering | 显式有界编辑、来源摘要及冲突检查;不恢复隐式自修改/自动 oracle writeback |
| lint/narrative | lint Tool | 静态诊断与显式修复,不进 CLI runtime |
### 领域与插件
| 旧目录 | 目标及处理 |
|---|---|
| `ext/ai` + `plugins/llm` / `plugins/agent` | AI 模型协议、MCP 独立迁移;agent 97 个 H2 涉及 workflow/memory/工具/恢复等,按真实通用能力拆分,不整体复制。qdagent 应用管理其自己的最小工作流、记忆、意图和 SKILL,不作为通用标准库。知识检索、证明分别由对应 Tool;sandbox 用 CLI 的实际保证,不伪造 OS 隔离。 |
| `ext/linalg` + `plugins/linalg` | Linalg;迁移数值算法、复数及矩阵符号知识;重新适配 ABI,减少重复。 |
| `ext/quantum` + `plugins/quantum` | Quantum;gate/state/circuit/simulate/density/viz,移除与 Linalg 重复的实现或建立经测试的后端共享边界。 |
| `ext/net` | HTTP、WebSocket、URL,低层 TCP/TLS 归 Std Net。 |
| `ext/data` | Database/Cache/Storage;form/admin/api/view 的 Web 部分归 Web,数据验证及查询归唯一相应库。旧 Web Go plugin 的 DB、storage、cache 子模块分别迁移。 |
| `ext/security` | Security + Crypto;旧 Go plugin auth/OIDC/RBAC/tenant/password 按归属拆分,不混入 Host capability。 |
| `ext/web` + `plugins/web` | 拆为 Web 设计原型领域(唯一合同见 marqdo-ext-web `docs/WEB-DESIGN.md`:设计文档解释、递归组件、有限场景、离线预览与 handoff)与 HTTP/WebSocket/Browser/Database/Security 各自独立组件;删除 monolithic Go plugin 调度与旧页面模型,不恢复旧 Web Artifact 兼容层。 |
| `ext/engineering` + `plugins/engineering` | Engineering;Git 操作、文件、archive 分配给已有权威库,避免重复平台操作。 |
| `crates/marqdo-wasm`、旧 browser examples | Browser 组件参考;语言核心可移植性需要 CLI 工单,而非复制旧执行器。 |
| 旧 `src/knowledge`/proof/view/lint/对应历史 CI 与 examples | 独立 Tool,只迁移所需知识、算法和 fixture;当前公共 Analysis/Observation 优先;新旧协议不并存。 |
+76
View File
@@ -0,0 +1,76 @@
# Marqdo 各仓库任务
按仓库领取任务。标为 **大改** 的条目可涉及模块拆分、实现重写或发布切换。责任仓库应先限定本轮交付范围,涉及公共接口时与实际消费者一起验收。
生态治理采用“根 → 领域聚合 → 功能组件”最多两级 Gitlink:功能仓库实现与修复、领域聚合仓库维护合同与组合验收、主仓库固定 gitlink、治理与发行。`planned` 组件可以挂载真实开发提交,实际入口随验收登记。当前没有 active 领域;Web 领域为 planned(聚合仓 `marqdo-ext-web`,子组件 `marqdo-web-design`/`marqdo-web-preview` 在其 catalog 登记)。先推进 CLI 外部 Bundle、九个标准库,以及 HTTP、Regex、Archive 的迁出;这些改动在同一候选组合中验证后切换基础发行。官网和 VS Code 可独立推进。[迁移台账](MIGRATION.md) · [开发流程](DEVELOPMENT.md)
## 集成和语言
| 仓库 | 要完成的任务 |
| --- | --- |
| `marqdo` | 固定已验收的组件组合与领域 gitlink,完成跨仓库工单闭环、CI 和生态发行验证。推进递归治理校验(domain 角色与全局依赖 DAG)、声明驱动集成计划、统一 CLI 制品输入与递归影响分析;保留现有 conformance/View/Knowledge/Prove/Lint 真实门禁。 |
| `marqdo-cli` | **大改**。拆分内核构建和基础发行装配,接受显式外部标准库 Bundle。完成领域能力迁出后,移除旧标准库入口和被替代的专用宿主实现。 |
| `marqdo-extension-conformance` | 更新真实 CLI 的公共契约测试,覆盖 Bundle 切换、五类扩展机制及其权限边界。 |
## 领域聚合(planned)
领域聚合仓库只做治理、唯一合同、示例、跨组件验收与交付协调,不含生产实现。激活前保持 planned,子组件在其自身 `components.toml` 登记,根 catalog 不重复登记。
| 仓库 | 要完成的任务 |
| --- | --- |
| `marqdo-ext-web` | Web 领域聚合:维护唯一作者合同 `docs/WEB-DESIGN.md`、§8 组合示例与领域 CI;验证真实 Analysis 风险(WEB-00),协调设计合同变更与 Design/Preview 配对候选;在子组件通过 WEB-01..04 后以领域 gitlink 接入根(WEB-05)。 |
| `marqdo-web-design` | WEB-01:消费真实 CLI Analysis 3,解释精确组件引用、递归布局、有限场景与依赖,输出稳定诊断、组件图和源身份;WEB-03:handoff、单组件切片与漂移标识。独立 Rust library,禁止复制 parser/启动服务。 |
| `marqdo-web-preview` | WEB-02:通用离线预览渲染器与有限状态交互、响应式、安全负例、Tool 打包;作为唯一 `web` 命令入口消费 Design 公开 API,禁止任务专用 JS、第二套解析或生产服务器。 |
## 工具和产品
| 仓库 | 要完成的任务 |
| --- | --- |
| `marqdo-knowledge` | 基于公开 Analysis 完善可复现的知识编译、索引和检索,验证独立发行。 |
| `marqdo-prove` | 完善证明依赖、Lean 证书生成和独立重放,清楚展示各项证明的核验状态。 |
| `marqdo-view` | 维护文档阅读、显式运行、Observation 和静态导出,验证与现行 CLI 及官网构建的组合。 |
| `marqdo-lint` | 扩展静态规则和诊断定位,为可修复规则提供显式修复。 |
| `marqdo-site` | **大改**。用现行 CLI 和 View 重建官网与入门内容,验证新站和旧链接后切换托管。 |
| `marqdo-vscode` | **大改**。按现行 CLI 重做诊断和运行适配,先完成高亮、静态诊断、显式运行和可安装的 VSIX。 |
## 标准库
每个仓库交付可独立测试的模块,共同组成默认 Bundle。标准库源码归位已完成并晋升:六个交付源码的 `std-*` 在根 catalog 为 active,`std-core/encoding/net` 保持 planned 且不入 Bundle;CLI 已无内置标准库源树,唯一 Bundle 由根 `scripts/build-stdlib.py` 从固定 gitlink 生成,组合验收为 `scripts/acceptance-stdlib.py`。迁移基线、模块/函数与断言台账、冻结发布路径见 [迁移台账](MIGRATION.md) 的“标准库源码归位迁移”一节。`marqdo-stdlib` 聚合仓库仍未建立;发行级冷安装已通过,后续缺陷回各责任仓。
| 仓库 | 要完成的任务 |
| --- | --- |
| `marqdo-std-core` | 实现共用 Result 和基础数值操作。 |
| `marqdo-std-collections` | 实现 List、Map 和 Table 的通用集合操作,从数据格式处理中拆出表格算法。 |
| `marqdo-std-text` | 统一 Unicode 文本、字节值切片和 UTF-8 编解码。 |
| `marqdo-std-encoding` | 提供 Base64、Base32 和 Hex,并定义非法输入的行为。 |
| `marqdo-std-data` | 迁入 JSON、CSV 和表格格式转换,补齐 TOML 与 GFM。 |
| `marqdo-std-io` | 迁入 Console、Stream 和格式化,负责官方 `print` 与 `打印` 别名。 |
| `marqdo-std-fs` | 迁入文件、路径和目录操作,核验读写边界。 |
| `marqdo-std-system` | 迁入时钟、UTC、环境、进程和随机能力。 |
| `marqdo-std-net` | 提供有界 TCP、UDP、TLS 和字节流,供上层协议复用。 |
## 扩展
每个仓库先完成一个可安装、可验证的用例。历史实现可用于迁移取证,公开接口按现行契约验收。
| 仓库 | 要完成的任务 |
| --- | --- |
| `marqdo-ext-math` | 建立数值算法、统计、符号数学和绘图能力,先交付可验证的数值用例。 |
| `marqdo-ext-linalg` | 迁移复数、矩阵和分解,向量子组件提供可复用的线性代数接口。 |
| `marqdo-ext-quantum` | 迁移量子电路、态向量、采样与模拟,验证代表性电路结果。 |
| `marqdo-ext-http` | **大改**。把现有 HTTP 迁为基于 std-net 的独立包,覆盖 URL、消息编解码、请求生命周期和 SSE。 |
| `marqdo-ext-websocket` | 交付基于 HTTP 与网络流的 WebSocket 握手、帧和连接生命周期。 |
| `marqdo-ext-ai` | **大改**。从旧 AI 实现拆出模型协议、流式输出和工具调用数据。 |
| `marqdo-ext-mcp` | 交付 MCP 传输、能力发现和受控工具调用。 |
| `marqdo-ext-crypto` | 封装成熟密码学实现,先交付一种带标准测试向量的能力。 |
| `marqdo-ext-database` | 交付一个支持参数绑定和事务的数据库驱动。 |
| `marqdo-ext-storage` | 定义本地与对象存储接口,先验证一套读写和错误处理流程。 |
| `marqdo-ext-cache` | 交付带 TTL 和失效行为的缓存。 |
| `marqdo-ext-security` | 交付应用身份、会话与授权,复用加密扩展。 |
| `marqdo-ext-web` | 已改为 Web 领域聚合仓库,任务见「领域聚合」小节;不再作为 HTTP 页面/路由渲染实现。 |
| `marqdo-ext-browser` | **大改**。按现行运行时边界适配浏览器宿主、WASM、DOM 和事件。 |
| `marqdo-ext-document` | 交付 Markdown 结构查询与显式编辑接口。 |
| `marqdo-ext-archive` | 实现归档与安全解包,为 CLI 移除旧压缩入口提供可验证的替代。 |
| `marqdo-ext-engineering` | 拆分工程操作、文件补丁和产物处理,先交付一个独立工程用例。 |
| `marqdo-ext-regex` | 提供匹配、捕获、扫描与替换,为 CLI 移除旧正则入口提供可验证的替代。 |
| `marqdo-ext-datetime` | 交付 IANA 时区、夏令时和高级日历能力,与标准库 UTC 接口对接。 |
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
# 架构决策记录
按时间顺序保存影响生态边界、公共合同或发行方式的决策。现行规则以 `docs/ARCHITECTURE.md`、`docs/DEVELOPMENT.md`、`components.toml` 与各责任仓库的合同文档为准;ADR 是决策历史,不是第二套现行规范。
| ADR | 状态 | 主题 |
| --- | --- | --- |
| [0001](0001-hierarchical-ecosystem-and-web-domain.md) | 已采纳(实施记录) | 分层生态治理(根→领域→功能)与 Web 原型设计领域合同 |
@@ -0,0 +1,72 @@
# 标准库源码归位 M2 候选证据(2026-11-26)
父仓工单:[cflmy/marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9)。本文件记录 **M2 候选组合**的真实执行结果,是候选证据,不是已发布声明。根主分支仍保持迁移前组合(`484cb10`);本候选只有在 CLI Phase A 与六个接收仓 PR 合并、且完整生态门禁通过后才可晋升。
## 候选身份
| 对象 | 身份 |
| --- | --- |
| 根候选分支 | `migration/stdlib-m2-candidate`(本文档提交前树 `8fa728b302fa29caf8268a758eb4b0e90431d780`) |
| 根主分支基线 | `484cb10d66db9b92f0527499642ae6abddb3ef29`(未改动) |
| CLI gitlink(未变) | `cflmy/marqdo-cli@452e9a32bd9e40dba427d4180691c58bab74449e`(RC.4 组合) |
| CLI Phase A 候选(仅用于打包/验证,PR #12) | `cflmy/marqdo-cli@f8b82d414328d92b31865fed05e68223f7bee917` |
| std-text | `cflmy/marqdo-std-text@c2a7d327e5d1914db8952562614707c112a07da1`(PR #2) |
| std-system | `cflmy/marqdo-std-system@053ddb0e59dc016b9c7833f115d14fa04e721d48`(PR #2) |
| std-io | `cflmy/marqdo-std-io@e18b0b1b40fcc6adcb42b5ab9fe1c9c04e9b8263`(PR #2) |
| std-fs | `cflmy/marqdo-std-fs@63bceae58736f13770c7eead02535726d08c19d0`(PR #2) |
| std-data | `cflmy/marqdo-std-data@848af7a357ceda2cfc20721b93406cf4be705889`(PR #2) |
| std-collections | `cflmy/marqdo-std-collections@490765226866ac74b7365471c202e7638187bff8`(PR #2) |
| ext-http(显式 Package) | `cflmy/marqdo-ext-http@368b33d241`(PR #2,合并后精确 SHA 以根 gitlink 为准) |
| ext-regex(显式 Package) | `cflmy/marqdo-ext-regex@6e7e633798`(PR #2) |
| ext-archive(显式 Package) | `cflmy/marqdo-ext-archive@aba6b60934`(PR #2) |
`std-core`、`std-encoding`、`std-net` 保持 `planned`,不加入 Bundle。HTTP/Regex/Archive 已迁为显式 Package(`index.mq.md` + `marqdo.yaml`,消费者经 `@alias` 导入),不进入默认 Bundle;其源码候选已合并到各自仓库 main,根候选固定对应提交并执行显式 Package 消费门禁(`kind = "explicit-package"`)。
## 唯一 Bundle 制品
`scripts/build-stdlib.py` 从上述根 gitlink 组合,两次干净构建逐字节一致:
| 字段 | 值 |
| --- | --- |
| name / version | `marqdo-stdlib` / `0.2.0`(内容变化显式升版本;摘要算法不变) |
| tree digest | `sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7` |
| aliases digest | `sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`(与迁移前一致) |
| 模块数 | 17(仅模块;`tests/`、`demo.mq.md`、`net/http`、`regex`、`compress` 均不在默认 Bundle) |
| 打包归档 | `marqdo-stdlib-0.2.0.tar.gz`,`sha256:212cca32f10ecfa0cdedfa976f7726db5e01cdb0e664a41ae26d4b34a8fd7048`(CLI Phase A `tools/pack-stdlib.py` 两次输出逐字节一致) |
## 门禁结果
| 门禁 | 命令 | 结果 |
| --- | --- | --- |
| 根布局 | `python3 scripts/check-layout.py` | PASS |
| 递归布局 | `python3 scripts/check-layout.py --checkouts` | PASS(33 个固定子树;6 个 active stdlib entry 存在且工作区干净) |
| 根集成测试 | `python3 -m unittest discover -s tests/integration` | Ran 56 tests,OK(含 9 个 Bundle 生产者契约测试) |
| 组件独立验收 | `MARQDO_BIN=<RC.4 由 452e9a3 构建> MARQDO_STDLIB_DIR=<新 Bundle> scripts/test.sh`(各仓) | 6/6 PASS,共 17 个 case(collections 1、text 2、data 3、io 4、fs 2、system 5) |
| 跨仓组合 | `scripts/acceptance-stdlib.py --cli <CLI> --bundle <新 Bundle>` | PASS:官方 `print`/`打印` 别名、Table 值操作+GFM 跨模块、默认 Bundle smoke |
| Table 等价性 | 组合 fixture 终值与迁移前原 `stdlib/tests/table.mq.md` 终值 | 逐字节一致 |
| 显式 Package 消费 | `scripts/acceptance-stdlib.py` 内 http/regex/archive 各自 `scripts/test.sh`(临时消费者工程 + `marqdo lock` + `@alias` 导入) | PASS(原领域测试终值与迁移前基线一致) |
| 失败负例 | 缺显式 Bundle、篡改模块摘要 | 均按预期失败(exit 1),不静默回退 |
| 相邻安装离线运行 | 把新 Bundle 放到 CLI 二进制旁 `stdlib/`,不设 `MARQDO_STDLIB_DIR` | PASS(默认离线安装路径可用) |
| CLI 打包 | Phase A `pack-stdlib.py --stdlib-dir <新 Bundle>` ×2 + 篡改输入 | 确定性 PASS;篡改拒绝 |
CLI 身份(sha256):由 `452e9a3` 构建的 RC.4 二进制 `sha256:0377b855...`;Phase A 合并 master(`f8b82d4`)二进制 `sha256:6ede3b9e...`。两者对同一 Bundle 的组件与组合门禁结果一致。
## 未验证 / 待办
- 完整 `scripts/integration.sh` 的既有消费者门禁(Conformance/View/Knowledge/Prove/Lint)本轮**未执行**:该流程仍取冻结 RC.4 制品,本次未替换为统一制品输入(ECO-02,marqdo#7);不能把本次 PASS 当作生态发行验收。
- CLI Phase B(删除仓内官方标准库源树、pin 切换)未做,等待 CLI PR #12 合并与本候选组件 PR 合并。
- HTTP/Regex/Archive 已成为显式 Package 且组件内测试通过;本候选的根组合门禁只验证了独立 Package 行为,尚未验证真实应用项目的 `git` 依赖锁定/同步与发布分发,也尚未从默认 Bundle 删除后验证既有 `std:` 用户的迁移提示(按合同不保留 fallback)。
- 未做完整产品归档冷安装(新 Bundle + 新 CLI 发行归档)与多平台证据;Windows/macOS 未验证。
- 根主分支未改动,回退方式为放弃本候选分支,迁移前组合 `484cb10` 仍可检出。
## 复现
```sh
git checkout migration/stdlib-m2-candidate
git submodule update --init --recursive
python3 scripts/check-layout.py --checkouts
python3 -m unittest discover -s tests/integration
python3 scripts/build-stdlib.py --out build/stdlib
python3 scripts/acceptance-stdlib.py --cli <verified-marqdo> --work build/accept
# 可选:--pack-tool <cli>/tools/pack-stdlib.py(Phase A 之后)
```
@@ -0,0 +1,54 @@
# 标准库源码归位 M3 候选证据(2026-11-27)
父仓工单:[cflmy/marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9)。
本文件记录 **M3 候选组合**(源码所有权切换 + 统一制品输入)的候选证据,不是已完成发行声明。主分支仍保持迁移前组合 `484cb10`,根 PR #12 只有在 CI 通过且 CLI Phase B 合并后才晋升。
## 候选身份
| 对象 | 身份 |
| --- | --- |
| 根候选 | `migration/stdlib-m2-candidate`(CLI Phase B 合并提交 `deadf6e`) |
| CLI Phase B 合并 | `cflmy/marqdo-cli@deadf6edeea6dd0f5abf51c47e80204fd851baf0`(PR #17 fast-forward 合并;Phase B 代码提交 `72f57be`,另含 CI 脚本修复;`stdlib/` 已删除,pin 指向生态 Bundle) |
| 生态 Bundle | `marqdo-stdlib@0.2.0`,source `cflmy/marqdo@48189243f7`,tree digest `sha256:db905508...`,aliases digest `sha256:5f513c0f...`(17 模块 + manifest) |
| 组件固定 | 六个 std 与三个 ext 的已合并候选 SHA(M2 证据同一组) |
| 发行归档(本地候选) | `marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz`,`sha256:9a926010ffe8e7353ee18b65fc568ced8bbf4b09b7592713f1213e2f3e3d40f9`(CLI `72f57be` + 新 Bundle) |
## 统一制品输入(ECO-02 核心)
根 `scripts/integration.sh` 不再读取 View 的冻结 RC.4 脚本;一次候选内派生全部输入:
1. `scripts/build-stdlib.py --out <work>/stdlib` 由固定组件 gitlink 生成唯一 Bundle;
2. 从根固定的 `cli/` 提交构建 CLI 与 Provider Worker;
3. `cli/tools/release/package.py --source-sha <cli SHA> --version <workspace version> --stdlib-dir <Bundle>` 生成发行归档与 `RELEASE_INFO.json`;
4. `cli/tools/release/smoke.py` 验证归档、`SOURCE_SHA`、stdlib 摘要与语言-only 运行;
5. `scripts/acceptance-stdlib.py --cli <installed> --bundle <Bundle>` 跑组件 entry、显式 Package、组合 fixture 与失败负例;
6. Conformance、View、Knowledge、Prove、Lint 使用同一安装后二进制与相邻 Bundle。
## 本地候选验证
| 门禁 | 命令 | 结果 |
| --- | --- | --- |
| 根布局 | `python3 scripts/check-layout.py --checkouts` | PASS(含 6 个 active stdlib entry 与 9 个固定组件) |
| Bundle | `python3 scripts/build-stdlib.py --out <dir>` | 两次构建一致,digest `sha256:db9055...` |
| CLI Phase B | `cargo fmt` / `clippy -D warnings` / `cargo test --workspace`(显式 Bundle) | fmt/clippy PASS;72 个测试二进制 PASS |
| CLI 工具测试 | `MARQDO_TEST_STDLIB_BUNDLE=<bundle> python3 -m unittest discover -s tools/ci` | 75 tests OK |
| 独立构建 | `python3 tools/ci/independent_build.py` | PASS(无 stdlib 源树、无兄弟 Bundle,语言-only 运行成功,依赖 std 的程序 fail-closed) |
| 发行归档 | `package.py --stdlib-dir <Bundle>` + `smoke.py --archive` | PASS(stdlib 0.2.0 摘要校验、缺失 Bundle fail-closed、language-only 运行) |
| 验收脚本 | `scripts/acceptance-stdlib.py` 本地 M2 版 | PASS(6 组件 + 3 显式 Package + 4 组合 + 2 负例) |
## 未验证 / 待办
- 完整根 CI(`scripts/integration.sh` 含 View/Knowledge/Prove/Lint 消费者)在候选分支执行,结果记录在 PR #12/评论,不以本地部分运行替代。
- 根晋升(合并 CLI PR #17 与根 PR #12、climo gitlink 与制品同一候选)属 MIG-RELEASE。
- 完整产品归档冷安装(docker `--network none`)、多平台、ext-http loopback 领域测试仍待补;如需标记为发行门禁必须另行执行,不得以本文件冒充 PASS。
## 晋升与 M4 验收(2026-11-27)
- CLI Phase B [PR #17](https://git.cflmy.cn/cflmy/marqdo-cli/pulls/17) fast-forward 合并,`master` = `deadf6e`(contract/test/independent-build/minimum-rust/build 全绿)。
- 根 [PR #12](https://git.cflmy.cn/cflmy/marqdo/pulls/12) fast-forward 合并,`main` = `f4e292e7b09057c77e2a9293b40051be2666c4f8`;根树固定 CLI Phase B 与六个 std、三个 ext 提交,六个 stdlib 组件 active。
- 根生态 CI 必须门禁 `ci/woodpecker/pr/eco` PASS([pipeline 38](https://ci.cflmy.cn/repos/6/pipeline/38/1)):一次候选派生 Bundle(`sha256:db9055...`)→ 从 cli gitlink 构建 CLI/Worker → `package.py --stdlib-dir`(归档 `sha256:0827ba4b...`)→ smoke → 根 acceptance(组件 entry、显式 Package、组合、负例)→ Conformance/View/Knowledge/Prove/Lint 全部同一安装后二进制与相邻 Bundle。
- 发行级离线冷安装:在本机对同一晋升组合(根 `f4e292e`、CLI `deadf6e`、Bundle `db9055`)重新打包(归档 `sha256:377d2787...`)并执行 `cli/tools/release/cold-install.sh`(`ubuntu:24.04`、`--network none`、非 root 用户):PASS——安装后打印、`check`、示例运行、隐藏 Bundle 时 fail-closed、仅语言程序可运行均符合门禁。
- 两个归档 SHA 不同是因为示例插件二进制由本机构建产生,不是同一构建环境的确定性证据;确定性打包证据以 CI 同一环境两次构建为准。发行归档身份以 CI/发布记录为准,本文件只记录晋升组合与冷安装通过。
仍保留为后续(不阻塞本轮关闭):Windows/macOS 不在本线发行支持矩阵;`marqdo-ext-http` 的 HTTP-over-TCP loopback 领域测试;ECO-02 的递归影响分析自动化。
-15
View File
@@ -1,15 +0,0 @@
# Marqdo examples(金样例)
本目录即测试夹具,见 [doc/design/examples-and-tests.md](../doc/design/examples-and-tests.md)。
| 目录 | 内容 |
|------|------|
| [`structure/`](structure/) | 函数、调用、分支、循环、表、导入、位置实参 |
| [`keywords/`](keywords/) | `print`、布尔与 `and`/`or`/`not` |
| [`errors/`](errors/) | 期望失败(未定义名 / 未知函数 / 实参 / 语法) |
```bash
cargo test
marqdo run examples/structure/hello.mq.md
marqdo view examples
```
View File
Whitespace-only changes.
-12
View File
@@ -1,12 +0,0 @@
---
title: bad arity
---
# main
> needs_one
## needs_one
- x
> print text=`x`
-7
View File
@@ -1,7 +0,0 @@
---
title: unrecognized code line
---
# main
~not-valid-syntax
-7
View File
@@ -1,7 +0,0 @@
---
title: undefined variable
---
# main
> print text=`missing`
-7
View File
@@ -1,7 +0,0 @@
---
title: unknown function
---
# main
> no_such_fn x=1
-20
View File
@@ -1,20 +0,0 @@
---
title: 布尔与逻辑关键字
---
# main
*`a` = True*
*`b` = False*
+ `a` and not `b`
> print text=ok
+ *
> print text=fail
*`probe` = 1*
+ None
> print text=none-truthy
+ *
> print text=none-falsy
-9
View File
@@ -1,9 +0,0 @@
---
title: 内置 print
---
# main
> print text=named form
> print positional
-14
View File
@@ -1,14 +0,0 @@
---
title: 分支示例
---
# main
*`x` = 0*
+ `x` > 0
> print text=正数
+ `x` < 0
> print text=负数
+ *
> print text=零
-16
View File
@@ -1,16 +0,0 @@
---
title: 集合(表格)示例
---
# main
`篮子` =
| 果 |
|----|
| 苹果 |
| 梨 |
| 桃 |
- [果](篮子)
> print text=`果`
-5
View File
@@ -1,5 +0,0 @@
# Hello World
本程序调用内置函数 `print` 打印问候。注释里的 **粗体** 与 *斜体* 都不执行。
> print text=Hello World!
-14
View File
@@ -1,14 +0,0 @@
---
title: 跨文件导入示例
> utils.mq.md
---
# main
导入 `utils.mq.md` 后:用返回值绑定,再输出;并直接调用问候。
*`y` = > 加一 n=41*
> print text=`y`
> 问候 谁=Marqdo
-14
View File
@@ -1,14 +0,0 @@
---
title: 工具函数
description: 供 frontmatter > 导入;返回用粗体;副作用用输出函数
---
# 加一
- n
**`n` + 1**
# 问候
- 谁
> print text=你好,`谁`!
-25
View File
@@ -1,25 +0,0 @@
---
title: 循环示例
---
# main
倒数:
*`n` = 3*
- `n` > 0
> print text=`n`
*`n` = `n` - 1*
遍历篮子:
`篮子` =
| 果 |
|----|
| 苹果 |
| 梨 |
- [果](篮子)
> print text=今天吃`果`
-15
View File
@@ -1,15 +0,0 @@
---
title: Hello World
description: Recommended entry — nested fn; print builtin; bold return
---
# main
打印一句问候。`print` 是函数,不是语法架构;粗体只用于返回值。
> 问候 谁=World
## 问候
- 谁
> print text=Hello `谁`!
-19
View File
@@ -1,19 +0,0 @@
---
title: 位置实参
description: `> fn value` binds by parameter order; named form still works
---
# main
位置实参:
> 问候 Marqdo
具名实参(保留):
> 问候 谁=World
## 问候
- 谁
> print text=Hello `谁`!
+32
View File
@@ -0,0 +1,32 @@
# 领域扩展与领域聚合
本目录覆盖按需安装的领域能力。功能组件默认 `planned`,通过 Git 子模块固定独立仓库的开发提交,完成验收后晋升;聚合仓库不实现子组件业务,根 catalog 只登记 `kind = "domain"` 的聚合本身,不重复登记其后代路径。
## 领域聚合(planned)
| 路径 | 仓库 | 说明 |
| --- | --- | --- |
| `web/` | [marqdo-ext-web](https://git.cflmy.cn/cflmy/marqdo-ext-web) | Web 原型设计领域聚合:唯一设计合同、示例、组合验收与交付协调;子组件 [marqdo-web-design](https://git.cflmy.cn/cflmy/marqdo-web-design)、[marqdo-web-preview](https://git.cflmy.cn/cflmy/marqdo-web-preview) 在领域 `components.toml` 登记 |
## 独立组件(planned)
- [marqdo-ext-math](https://git.cflmy.cn/cflmy/marqdo-ext-math) · 数值算法、统计、符号数学及绘图
- [marqdo-ext-linalg](https://git.cflmy.cn/cflmy/marqdo-ext-linalg) · 复数、矩阵、分解及数值线性代数
- [marqdo-ext-quantum](https://git.cflmy.cn/cflmy/marqdo-ext-quantum) · 量子电路、态向量、采样与模拟
- [marqdo-ext-http](https://git.cflmy.cn/cflmy/marqdo-ext-http) · HTTP、URL、SSE 与报文生命周期
- [marqdo-ext-websocket](https://git.cflmy.cn/cflmy/marqdo-ext-websocket) · WebSocket 握手、帧与连接语义
- [marqdo-ext-ai](https://git.cflmy.cn/cflmy/marqdo-ext-ai) · 模型协议、流式输出与工具调用数据
- [marqdo-ext-mcp](https://git.cflmy.cn/cflmy/marqdo-ext-mcp) · MCP 协议、传输、发现和调用
- [marqdo-ext-crypto](https://git.cflmy.cn/cflmy/marqdo-ext-crypto) · 成熟密码学实现的封装
- [marqdo-ext-database](https://git.cflmy.cn/cflmy/marqdo-ext-database) · SQL 参数绑定、事务和驱动连接
- [marqdo-ext-storage](https://git.cflmy.cn/cflmy/marqdo-ext-storage) · 本地和对象存储接口
- [marqdo-ext-cache](https://git.cflmy.cn/cflmy/marqdo-ext-cache) · TTL、缓存和失效
- [marqdo-ext-security](https://git.cflmy.cn/cflmy/marqdo-ext-security) · 应用身份、会话及权限模型
- [marqdo-ext-browser](https://git.cflmy.cn/cflmy/marqdo-ext-browser) · 浏览器宿主、WASM 适配、DOM 和事件
- [marqdo-ext-document](https://git.cflmy.cn/cflmy/marqdo-ext-document) · Markdown 结构与显式文档编辑
- [marqdo-ext-archive](https://git.cflmy.cn/cflmy/marqdo-ext-archive) · 压缩、安全归档和解包
- [marqdo-ext-engineering](https://git.cflmy.cn/cflmy/marqdo-ext-engineering) · 工程操作、文件补丁与产物
- [marqdo-ext-regex](https://git.cflmy.cn/cflmy/marqdo-ext-regex) · 正则匹配、捕获、扫描和替换
- [marqdo-ext-datetime](https://git.cflmy.cn/cflmy/marqdo-ext-datetime) · IANA 时区、DST 和高级日历
[组件目录](../components.toml) · [各仓库任务](../docs/REPOSITORY-TASKS.md) · [架构边界](../docs/ARCHITECTURE.md)
Submodule
+1
Submodule extensions/ai added at 4d2c3e4f1a.
Submodule extensions/archive added at aba6b60934.
Submodule extensions/browser added at 35c1a75fd0.
+1
Submodule extensions/cache added at 0357907e1d.
+1
Submodule extensions/crypto added at 21529b8b25.
Submodule extensions/database added at e86a397c8e.
Submodule extensions/datetime added at 5e2e2a1b34.
Submodule extensions/document added at eb88be346a.
+1
Submodule extensions/http added at 368b33d241.
+1
Submodule extensions/linalg added at 773ba9ef2e.
+1
Submodule extensions/math added at f7ef25014a.
+1
Submodule extensions/mcp added at df477bceec.
Submodule extensions/quantum added at 33f4780e9e.
+1
Submodule extensions/regex added at 6e7e633798.
Submodule extensions/security added at 6939018249.
Submodule extensions/storage added at 6a798f099e.
+1
Submodule extensions/web added at f70095d60a.
Submodule extensions/websocket added at e79f2e78fa.
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""Accept the stdlib migration candidate with explicit, verified inputs.
This is the root-layer composition gate: it builds (or accepts) the one Bundle
produced by ``scripts/build-stdlib.py`` from the pinned component gitlinks, runs
each active stdlib component's own entry point against that Bundle, runs the
cross-repository composition fixtures, exercises the negative inputs that must
fail closed, and optionally packages the Bundle with the CLI's own packer twice
to prove determinism.
Every input is explicit: a real ``marqdo`` executable (``--cli``) and either a
Bundle (``--bundle``) or a checkout that can build one at its pinned gitlinks.
Nothing is downloaded and no sibling component is discovered implicitly.
Usage:
python3 scripts/acceptance-stdlib.py --cli build/marqdo --work build/accept
python3 scripts/acceptance-stdlib.py --cli build/marqdo --work build/accept \
--pack-tool /path/to/cli/tools/pack-stdlib.py --evidence build/accept/evidence.json
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CASES = ROOT / "tests" / "integration" / "composition" / "cases"
CASES_SCHEMA = "marqdo.stdlib-test-case"
FORBIDDEN = {
"net/http.mq.md",
"regex.mq.md",
"compress.mq.md",
"demo.mq.md",
"tests",
}
class AcceptanceError(Exception):
pass
def run(command, cwd=None, env=None, input_bytes=b""):
result = subprocess.run(
command, cwd=cwd, env=env, input=input_bytes, capture_output=True
)
return result
def sha256(path: Path) -> str:
return "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest()
def channel_text(events: list[dict], channel: str) -> str:
chunks = []
for event in events:
if event.get("kind") != channel:
continue
payload = event["payload"]
data = base64.b64decode(payload["data_base64"])
if len(data) != payload["byte_count"]:
raise AcceptanceError(f"{channel} byte_count mismatch")
chunks.append(data)
return b"".join(chunks).decode("utf-8")
def tree_digest(bundle: Path) -> str:
digest = hashlib.sha256()
for path in sorted(bundle.rglob("*.mq.md"), key=lambda p: p.relative_to(bundle).as_posix()):
digest.update(path.relative_to(bundle).as_posix().encode())
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
def aliases_digest(aliases: list[dict]) -> str:
digest = hashlib.sha256()
for alias in sorted(aliases, key=lambda a: (a["target_module"], a["target_function"])):
digest.update(alias["target_module"].encode()); digest.update(b"\0")
digest.update(alias["target_function"].encode()); digest.update(b"\0")
for name in sorted(alias["public_names"]):
digest.update(name.encode()); digest.update(b"\0")
return "sha256:" + digest.hexdigest()
def verify_bundle(bundle: Path) -> dict:
manifest_path = bundle / "stdlib.json"
if not manifest_path.is_file():
raise AcceptanceError(f"missing Bundle manifest: {manifest_path}")
manifest = json.loads(manifest_path.read_text())
for field in ("name", "version", "digest", "aliases_digest"):
if not isinstance(manifest.get(field), str) or not manifest[field]:
raise AcceptanceError(f"manifest has no {field}")
computed = tree_digest(bundle)
if computed != manifest["digest"]:
raise AcceptanceError(
f"manifest digest mismatch: {manifest['digest']} != {computed}"
)
aliases = manifest.get("public_aliases", [])
expected_alias = aliases_digest(aliases)
if expected_alias != manifest["aliases_digest"]:
raise AcceptanceError("aliases digest mismatch")
files = sorted(
path.relative_to(bundle).as_posix()
for path in bundle.rglob("*.mq.md")
)
for relative in files:
parts = relative.split("/")
if "tests" in parts or relative in FORBIDDEN:
raise AcceptanceError(f"forbidden module in Bundle: {relative}")
for alias in aliases:
if alias["target_module"] not in files:
raise AcceptanceError(
f"public alias targets missing module {alias['target_module']}"
)
if "io.mq.md" not in files:
raise AcceptanceError("Bundle lost the io.mq.md alias target")
return {
"manifest": manifest,
"files": files,
"tree_digest": computed,
}
def run_case(cli: str, bundle: Path, case: dict) -> dict:
source = ROOT / "tests" / "integration" / "composition" / case["file"]
command = [cli, "run", str(source), *case.get("args", []), "--output", "json"]
env = os.environ.copy()
env["MARQDO_STDLIB_DIR"] = str(bundle)
for key, value in case.get("env", {}).items():
env[key] = value.replace("$MARQDO_BIN", cli)
result = run(command, cwd=ROOT, env=env, input_bytes=case.get("stdin", "").encode())
if result.returncode != 0:
raise AcceptanceError(
f"composition case {case['name']} failed: "
f"{result.stderr.decode(errors='replace')}"
)
report = json.loads(result.stdout)
if report.get("run", {}).get("status") != "ok":
raise AcceptanceError(f"composition case {case['name']} run status not ok")
terminal = report["events"][-1]["payload"]
if terminal.get("value") != case["expected_terminal"]:
raise AcceptanceError(
f"composition case {case['name']} terminal value changed"
)
stdout = channel_text(report["events"], "stdout.chunk")
if stdout != case.get("expected_stdout", ""):
raise AcceptanceError(
f"composition case {case['name']} stdout changed: {stdout!r}"
)
lines = stdout.splitlines()
for left, right in case.get("stdout_line_pairs", []):
if left >= len(lines) or right >= len(lines):
raise AcceptanceError(
f"composition case {case['name']} has no line pair {left}/{right}"
)
if lines[left] != lines[right]:
raise AcceptanceError(
f"composition case {case['name']}: line {left} differs from line {right}: "
f"{lines[left]!r} != {lines[right]!r}"
)
return {"name": case["name"], "status": "PASS"}
def load_components() -> list[dict]:
catalog = tomllib.loads((ROOT / "components.toml").read_text())
return [
component
for component in catalog["component"]
if component.get("kind") == "stdlib" and component.get("state") == "active"
]
def load_explicit_packages() -> list[dict]:
"""Planned extensions that already publish an explicit Package entry.
A component is gated as an explicit package only when its pinned checkout
carries the current package layout (``marqdo.yaml`` + ``index.mq.md`` +
``scripts/test.sh``); it is never silently loaded into the default Bundle.
"""
catalog = tomllib.loads((ROOT / "components.toml").read_text())
packages = []
for component in catalog["component"]:
if component.get("kind") != "extension":
continue
checkout = ROOT / component["path"]
if (checkout / "marqdo.yaml").is_file() and (
checkout / "index.mq.md"
).is_file() and (checkout / "scripts" / "test.sh").is_file():
packages.append(component)
return packages
def component_gates(cli: str, bundle: Path) -> list[dict]:
results = []
for component in load_components():
entry = ROOT / component["path"] / component["entry"]
if not entry.is_file():
raise AcceptanceError(
f"active component {component['id']} has no entry {component['entry']}"
)
env = os.environ.copy()
env["MARQDO_BIN"] = cli
env["MARQDO_STDLIB_DIR"] = str(bundle)
result = run([str(entry)], cwd=entry.parent.parent, env=env)
output = (result.stdout + result.stderr).decode(errors="replace").strip()
if result.returncode != 0:
raise AcceptanceError(
f"component {component['id']} failed entry {component['entry']}:\n{output}"
)
results.append(
{
"id": component["id"],
"entry": component["entry"],
"status": "PASS",
"output": output,
}
)
for component in load_explicit_packages():
entry = ROOT / component["path"] / "scripts" / "test.sh"
env = os.environ.copy()
env["MARQDO_BIN"] = cli
env["MARQDO_STDLIB_DIR"] = str(bundle)
result = run([str(entry)], cwd=ROOT / component["path"], env=env)
output = (result.stdout + result.stderr).decode(errors="replace").strip()
if result.returncode != 0:
raise AcceptanceError(
f"explicit package {component['id']} failed: {output}"
)
results.append(
{
"id": component["id"],
"entry": "scripts/test.sh",
"kind": "explicit-package",
"status": "PASS",
"output": output,
}
)
return results
def negative_gates(cli: str, bundle: Path, work: Path) -> list[dict]:
results = []
def expect_failure(name, command, env_for_gate):
result = run(command, env=env_for_gate)
if result.returncode == 0:
raise AcceptanceError(f"negative gate {name} unexpectedly passed")
results.append(
{
"name": name,
"status": "PASS",
"exit": result.returncode,
"stderr": result.stderr.decode(errors="replace").strip()[:400],
}
)
missing = work / "missing-bundle"
env = os.environ.copy()
env["MARQDO_STDLIB_DIR"] = str(missing)
expect_failure(
"missing-explicit-bundle",
[cli, "run", str(ROOT / "tests/integration/composition/default-bundle.mq.md")],
env,
)
tampered = work / "tampered-bundle"
if tampered.exists():
shutil.rmtree(tampered)
shutil.copytree(bundle, tampered)
target = next(iter(sorted(tampered.rglob("*.mq.md"))))
target.write_bytes(target.read_bytes() + b"\n")
env["MARQDO_STDLIB_DIR"] = str(tampered)
expect_failure(
"tampered-module-digest",
[cli, "run", str(ROOT / "tests/integration/composition/default-bundle.mq.md")],
env,
)
return results
def packaging_gates(pack_tool: str, bundle: Path, work: Path) -> list[dict]:
results = []
archives = []
for attempt in (1, 2):
out_dir = work / f"pack-{attempt}"
if out_dir.exists():
shutil.rmtree(out_dir)
result = run(
[
sys.executable,
pack_tool,
"--stdlib-dir",
str(bundle),
"--out-dir",
str(out_dir),
]
)
if result.returncode != 0:
raise AcceptanceError(
"CLI packer rejected the Bundle: "
+ result.stderr.decode(errors="replace")
)
archives.append(sorted(out_dir.glob("*.tar.gz"))[0])
if archives[0].read_bytes() != archives[1].read_bytes():
raise AcceptanceError("two packaging runs are not byte-identical")
descriptor = json.loads(
sorted(archives[0].parent.glob("*.json"))[0].read_text()
)
results.append(
{
"status": "PASS",
"archive": archives[0].name,
"archive_sha256": sha256(archives[0]),
"tree_digest": descriptor.get("tree_digest"),
"aliases_digest": descriptor.get("aliases_digest"),
"deterministic": True,
}
)
return results
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cli", required=True)
parser.add_argument("--work", required=True)
parser.add_argument("--bundle")
parser.add_argument("--pack-tool")
parser.add_argument("--evidence")
parser.add_argument("--root-commit")
args = parser.parse_args(argv)
cli = str(Path(args.cli).resolve())
if not Path(cli).is_file():
raise SystemExit(f"acceptance-stdlib: error: no CLI executable at {cli}")
work = Path(args.work).resolve()
work.mkdir(parents=True, exist_ok=True)
try:
if args.bundle:
bundle = Path(args.bundle).resolve()
else:
bundle = work / "bundle"
if bundle.exists():
shutil.rmtree(bundle)
command = [
sys.executable,
str(ROOT / "scripts" / "build-stdlib.py"),
"--out",
str(bundle),
]
if args.root_commit:
command += ["--root-commit", args.root_commit]
result = run(command, cwd=ROOT)
if result.returncode != 0:
raise AcceptanceError(
"Bundle producer failed: "
+ result.stderr.decode(errors="replace")
)
bundle_record = verify_bundle(bundle)
version = run([cli, "--version"]).stdout.decode().strip()
cases = []
for path in sorted(CASES.glob("*.json")):
case = json.loads(path.read_text())
if case.get("schema") != CASES_SCHEMA:
raise AcceptanceError(f"unsupported case schema: {path}")
cases.append(run_case(cli, bundle, case))
components = component_gates(cli, bundle)
negatives = negative_gates(cli, bundle, work)
packaging = (
packaging_gates(args.pack_tool, bundle, work)
if args.pack_tool
else []
)
evidence = {
"schema": "marqdo.stdlib-acceptance",
"schema_version": 1,
"cli": {"path": cli, "version": version, "sha256": sha256(Path(cli))},
"root_commit": run(
["git", "-C", str(ROOT), "rev-parse", "HEAD"]
).stdout.decode().strip(),
"bundle": {
"name": bundle_record["manifest"]["name"],
"version": bundle_record["manifest"]["version"],
"tree_digest": bundle_record["tree_digest"],
"aliases_digest": bundle_record["manifest"]["aliases_digest"],
"files": bundle_record["files"],
},
"components": components,
"composition": cases,
"negatives": negatives,
"packaging": packaging,
"status": "PASS",
}
except AcceptanceError as error:
print(f"acceptance-stdlib: FAIL: {error}", file=sys.stderr)
return 1
text = json.dumps(evidence, ensure_ascii=False, indent=2) + "\n"
if args.evidence:
Path(args.evidence).write_text(text)
print(text)
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+397
View File
@@ -0,0 +1,397 @@
#!/usr/bin/env python3
"""Build the one official `marqdo-stdlib` Bundle from pinned component gitlinks.
The producer owns composition only: it collects the published `modules/` files
of every **active** `kind = "stdlib"` component at the exact commit pinned by
the root Gitlink, validates the published path set, generates the current
`stdlib.json` (tree digest + public aliases digest) and writes a deterministic
Bundle directory. Component repositories keep the module sources and tests; the
root repository does not copy or edit them. The CLI packages the resulting
Bundle with its existing `tools/pack-stdlib.py`.
Identity rules:
* release mode (default) reads `components.toml`, the Bundle config and the
gitlinks from the ``--root-commit`` tree, never from the working tree;
* `--worktree` is a development-only mode that reads each component's
``HEAD`` and requires a clean component checkout;
* only ``modules/**/*.mq.md`` is published. Other files under ``modules/``
(for example ``modules/README.md``) stay repository documentation and are
not packed. Symlinks, submodules and non-regular entries are refused;
* published paths must be NFC, case-insensitively unique and free of
``tests/``, ``.git`` or traversal segments;
* a version bump is explicit: with ``--baseline-manifest`` content digest
changes are refused unless ``version`` also changes.
Usage:
python3 scripts/build-stdlib.py --out build/stdlib
python3 scripts/build-stdlib.py --out build/stdlib --worktree
python3 scripts/build-stdlib.py --out build/stdlib \
--baseline-manifest previous/stdlib.json
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import tomllib
import unicodedata
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_CONFIG = Path("scripts") / "stdlib-bundle.json"
MANIFEST = "stdlib.json"
MODULES = "modules"
PUBLISHED_SUFFIX = ".mq.md"
class BundleError(Exception):
"""An input cannot become the official Bundle."""
def _git(repo: Path, *args: str) -> bytes:
result = subprocess.run(
["git", "-C", str(repo), *args], capture_output=True
)
if result.returncode != 0:
raise BundleError(
f"git failed in {repo}: {' '.join(args)}: "
f"{result.stderr.decode(errors='replace').strip()}"
)
return result.stdout
def _nfc(value: str) -> str:
return unicodedata.normalize("NFC", value)
def load_json(path: Path) -> dict:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise BundleError(f"cannot read {path}: {error}") from error
if not isinstance(data, dict):
raise BundleError(f"{path} must contain a JSON object")
return data
def read_blob(repo: Path, revision: str, path: str) -> bytes | None:
result = subprocess.run(
["git", "-C", str(repo), "show", f"{revision}:{path}"],
capture_output=True,
)
return result.stdout if result.returncode == 0 else None
def read_catalog(root: Path, revision: str | None) -> list[dict]:
if revision is None:
raw = (root / "components.toml").read_bytes()
else:
raw = read_blob(root, revision, "components.toml")
if raw is None:
raise BundleError(f"root commit {revision} has no components.toml")
try:
catalog = tomllib.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error:
raise BundleError(f"invalid components.toml: {error}") from error
components = catalog.get("component")
if not isinstance(components, list):
raise BundleError("components.toml has no [[component]] entries")
return components
def read_config(root: Path, revision: str | None, path: Path) -> dict:
if not path.is_absolute():
path = root / path
if revision is not None:
relative = path.resolve().relative_to(root.resolve()).as_posix()
raw = read_blob(root, revision, relative)
if raw is None:
raise BundleError(f"root commit {revision} has no {relative}")
try:
config = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise BundleError(f"invalid Bundle config {relative}: {error}") from error
else:
config = load_json(path)
for field in ("name", "version"):
value = config.get(field)
if not isinstance(value, str) or not value:
raise BundleError(f"Bundle config has no non-empty `{field}`")
aliases = config.get("public_aliases", [])
if not isinstance(aliases, list):
raise BundleError("Bundle config `public_aliases` must be a list")
return config
def pinned_gitlink(root: Path, revision: str, path: str) -> str:
result = _git(root, "ls-tree", revision, "--", path).decode().strip()
if not result:
raise BundleError(
f"root commit {revision} has no gitlink at {path}; only published "
"components may join the Bundle"
)
fields = result.split()
if len(fields) != 4:
raise BundleError(f"invalid gitlink record for {path}")
mode, kind, sha, _ = fields
if mode != "160000" or kind != "commit":
raise BundleError(f"{path} is not a gitlink in root commit {revision}")
return sha
def worktree_sha(component_dir: Path) -> str:
if not (component_dir / ".git").exists():
raise BundleError(f"missing component checkout: {component_dir}")
status = _git(component_dir, "status", "--porcelain").decode().strip()
if status:
raise BundleError(f"dirty component checkout: {component_dir}")
return _git(component_dir, "rev-parse", "HEAD").decode().strip()
def validate_published_path(relative: str, component_id: str) -> None:
if not relative or relative.startswith("/"):
raise BundleError(f"{component_id}: invalid published path {relative!r}")
parts = relative.split("/")
if any(part in ("", ".", "..") for part in parts):
raise BundleError(f"{component_id}: unsafe published path {relative!r}")
if any(part.startswith(".") for part in parts):
raise BundleError(f"{component_id}: hidden path segment in {relative!r}")
if "tests" in parts:
raise BundleError(f"{component_id}: tests must not enter the Bundle: {relative!r}")
if not relative.endswith(PUBLISHED_SUFFIX):
raise BundleError(
f"{component_id}: only {PUBLISHED_SUFFIX} files are published, got {relative!r}"
)
if _nfc(relative) != relative:
raise BundleError(
f"{component_id}: published path is not NFC normalised: {relative!r}"
)
def component_modules(component_dir: Path, revision: str, component_id: str) -> list[tuple[str, str]]:
output = _git(
component_dir, "ls-tree", "-r", "-z", revision, "--", MODULES
)
records = [record for record in output.split(b"\0") if record]
published: list[tuple[str, str]] = []
for record in records:
header, _, raw_path = record.partition(b"\t")
fields = header.decode().split()
if len(fields) != 3:
raise BundleError(f"{component_id}: invalid tree record {record!r}")
mode, kind, sha = fields
path = raw_path.decode()
if kind != "blob" or mode not in ("100644", "100755"):
raise BundleError(
f"{component_id}: only regular modules files are publishable, "
f"found {mode} {kind} at {path}"
)
relative = path[len(MODULES) + 1 :]
if not relative.endswith(PUBLISHED_SUFFIX):
continue
validate_published_path(relative, component_id)
published.append((relative, sha))
if not published:
raise BundleError(
f"{component_id}: active component publishes no {PUBLISHED_SUFFIX} modules"
)
return published
def collect(root: Path, components: list[dict], *, root_commit: str | None) -> tuple[dict[str, bytes], list[dict]]:
active = [
component
for component in components
if component.get("kind") == "stdlib" and component.get("state") == "active"
]
if not active:
raise BundleError("no active stdlib component; nothing to publish")
for component in active:
if component.get("release") != "base":
raise BundleError(
f'{component["id"]}: active stdlib component must have release = "base"'
)
files: dict[str, bytes] = {}
identities: list[dict] = []
owners: dict[str, str] = {}
folded: dict[str, str] = {}
for component in active:
component_id = component["id"]
path = component["path"]
component_dir = (root / path).resolve()
revision = (
pinned_gitlink(root, root_commit, path)
if root_commit is not None
else worktree_sha(component_dir)
)
modules = component_modules(component_dir, revision, component_id)
for relative, sha in modules:
key = _nfc(relative).casefold()
if relative in owners:
raise BundleError(
f"duplicate published path {relative!r}: "
f"{owners[relative]} and {component_id}"
)
if key in folded:
raise BundleError(
f"case/NFC collision on {relative!r}: "
f"{folded[key]} and {component_id}"
)
owners[relative] = component_id
folded[key] = component_id
files[relative] = _git(component_dir, "cat-file", "blob", sha)
identities.append(
{"id": component_id, "path": path, "revision": revision, "files": len(modules)}
)
return files, identities
def tree_digest(files: dict[str, bytes]) -> str:
digest = hashlib.sha256()
for relative in sorted(files):
digest.update(relative.encode())
digest.update(b"\0")
digest.update(files[relative])
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
def aliases_digest(aliases: list[dict]) -> str:
digest = hashlib.sha256()
for alias in sorted(
aliases, key=lambda item: (item["target_module"], item["target_function"])
):
digest.update(alias["target_module"].encode())
digest.update(b"\0")
digest.update(alias["target_function"].encode())
digest.update(b"\0")
for name in sorted(alias["public_names"]):
digest.update(name.encode())
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
def validate_aliases(aliases: list[dict], files: dict[str, bytes]) -> None:
seen: set[str] = set()
for alias in aliases:
if not isinstance(alias, dict):
raise BundleError("public alias entry must be an object")
module = alias.get("target_module")
function = alias.get("target_function")
names = alias.get("public_names")
if module not in files:
raise BundleError(f"public alias targets missing module: {module!r}")
if not isinstance(function, str) or not function:
raise BundleError(f"public alias for {module} has no target_function")
if not isinstance(names, list) or not names or not all(
isinstance(name, str) and name for name in names
):
raise BundleError(f"public alias for {module}.{function} has invalid names")
for name in names:
if name in seen:
raise BundleError(f"public alias name declared twice: {name!r}")
seen.add(name)
if alias.get("expected_signature") != "params(值)":
raise BundleError(
f"public alias {module}.{function} must keep expected_signature params(值)"
)
if alias.get("effects") != ["host"]:
raise BundleError(
f"public alias {module}.{function} must keep effects [host]"
)
def build_manifest(config: dict, files: dict[str, bytes]) -> dict:
aliases = config.get("public_aliases", [])
validate_aliases(aliases, files)
return {
"name": config["name"],
"version": config["version"],
"digest": tree_digest(files),
"public_aliases": aliases,
"aliases_digest": aliases_digest(aliases),
}
def check_baseline(manifest: dict, baseline_path: Path) -> None:
baseline = load_json(baseline_path)
if baseline.get("version") == manifest["version"] and baseline.get(
"digest"
) != manifest["digest"]:
raise BundleError(
f"Bundle content changed but version is still {manifest['version']}; "
"bump the version explicitly"
)
def write_bundle(out: Path, manifest: dict, files: dict[str, bytes], force: bool) -> None:
if out.exists():
if not force:
raise BundleError(f"output directory already exists: {out}")
shutil.rmtree(out)
out.parent.mkdir(parents=True, exist_ok=True)
staging = Path(tempfile.mkdtemp(prefix=".stdlib-build-", dir=str(out.parent)))
try:
for relative, data in files.items():
target = staging / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
(staging / MANIFEST).write_text(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
os.replace(staging, out)
except BaseException:
shutil.rmtree(staging, ignore_errors=True)
raise
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--out", required=True, help="Bundle output directory")
parser.add_argument("--root-commit", default=None)
parser.add_argument("--worktree", action="store_true")
parser.add_argument("--config", default=None)
parser.add_argument("--baseline-manifest", default=None)
parser.add_argument("--force", action="store_true")
parser.add_argument("--root", default=str(ROOT), help=argparse.SUPPRESS)
args = parser.parse_args(argv)
if args.worktree and args.root_commit:
parser.error("--worktree and --root-commit are mutually exclusive")
root = Path(args.root).resolve()
revision = None
if not args.worktree:
revision = args.root_commit or _git(root, "rev-parse", "HEAD").decode().strip()
try:
components = read_catalog(root, revision)
config = read_config(root, revision, Path(args.config) if args.config else DEFAULT_CONFIG)
files, identities = collect(root, components, root_commit=revision)
manifest = build_manifest(config, files)
if args.baseline_manifest:
check_baseline(manifest, Path(args.baseline_manifest))
except BundleError as error:
raise SystemExit(f"build-stdlib: error: {error}") from error
write_bundle(Path(args.out), manifest, files, args.force)
summary = {
"name": manifest["name"],
"version": manifest["version"],
"tree_digest": manifest["digest"],
"aliases_digest": manifest["aliases_digest"],
"root_commit": revision,
"components": identities,
"files": sorted(files),
}
print(json.dumps(summary, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+455
View File
@@ -0,0 +1,455 @@
#!/usr/bin/env python3
"""Validate a Marqdo ecosystem Git tree.
The checker follows the hierarchical governance rules of the Marqdo ecosystem
specification (sections 2-4, 13):
* the root catalog describes direct components and domain aggregates;
* a registered ``kind = "domain"`` gitlink is expanded at its exact pinned
commit for ``--checkouts`` or to validate URLs before updating its children;
* each aggregate layer has its own ``components.toml`` / ``.gitmodules`` and
registers only its direct children;
* governance depth is limited to two gitlink levels (root -> domain -> leaf);
* global ids and remotes are unique, dependency edges resolve globally and
``requires`` stays acyclic while ``checks_with`` may contain cycles.
Commit identity comes from the Git tree (gitlinks), the authority for remotes
is ``.gitmodules`` and the catalog never repeats SHAs. The checker never
fetches from a network remote, never runs ``git submodule update`` and only
reads objects already present in the local repositories.
"""
import argparse
import graphlib
import re
import subprocess
import sys
import tomllib
import unicodedata
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
NAME = r"[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
FIELDS = {"id", "path", "kind", "state", "owner", "scope", "requires", "checks_with", "release"}
ROOT_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
ROOT_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts"}
CATEGORY_READMES = {"stdlib/README.md", "extensions/README.md"}
RELEASE_ROLES = {"core": "base", "stdlib": "base", "extension": "optional", "tool": "optional", "test": "none"}
DOMAIN_RELEASE = {"none", "base"}
DOMAIN_FILES = {".gitattributes", ".gitignore", ".gitmodules", "AGENTS.md", "LICENSE", "README.md", "components.toml"}
DOMAIN_DIRS = {".gitea", ".woodpecker", "docs", "examples", "scripts", "tests"}
DOMAIN_CHILD_KINDS = {"stdlib", "extension", "tool"}
AUTHORITY = "https://git.cflmy.cn/cflmy"
ENTRY = r"(?:[a-zA-Z0-9_-]+/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*"
def git(*args, cwd=ROOT):
return subprocess.check_output(["git", "-C", str(cwd), *args]).decode()
def require(condition, message):
if not condition:
raise ValueError(message)
def nfc(value):
return unicodedata.normalize("NFC", value)
class Layer:
"""One governance level: the root tree or one expanded domain aggregate."""
def __init__(self, repo, revision, label, depth, order, components, gitlinks, linked, urls):
self.repo = Path(repo)
self.revision = revision
self.label = label
self.depth = depth
self.order = order
self.components = components
self.gitlinks = gitlinks
self.linked = linked
self.urls = urls
def read_blob(repo, revision, path, label):
try:
return git("show", f"{revision}:{path}", cwd=repo)
except subprocess.CalledProcessError:
return None
def check_relative_path(path, id, label):
require(isinstance(path, str) and path, f"{label}: invalid path for {id}: {path!r}")
require("\\" not in path and not path.startswith("/") and not path.endswith("/"),
f"{label}: invalid path for {id}: {path!r}")
segments = path.split("/")
require(all(segment and segment not in {".", ".."} for segment in segments),
f"{label}: invalid path for {id}: {path!r}")
require(all(re.fullmatch(NAME, segment) for segment in segments),
f"{label}: invalid path for {id}: {path!r}")
require(nfc(path) == path, f"{label}: non-NFC path for {id}: {path!r}")
return path
def expected_root_path(component):
kind = component["kind"]
id = component["id"]
if kind == "core":
return "cli" if id == "cli" else None
if kind == "test":
return "tests/conformance" if id == "conformance" else None
if kind == "stdlib":
return f"stdlib/{id.removeprefix('std-')}" if id.startswith("std-") else None
if kind == "extension":
return f"extensions/{id}"
if kind == "tool":
return f"tools/{id}"
if kind == "domain":
return "stdlib" if id == "stdlib" else f"extensions/{id}"
return None
def expected_remote(component, depth):
"""Derive the single approved self-hosted HTTPS remote for a component.
Root direct components keep their historical ``marqdo-<id>`` /
``marqdo-ext-<id>`` / ``marqdo-extension-conformance`` repository names.
Components registered by a domain aggregate are independently named
``marqdo-<id>`` (for example ``marqdo-web-design``).
"""
id = component["id"]
kind = component["kind"]
if depth == 0:
if kind == "test":
name = "extension-conformance"
elif kind == "extension":
name = f"ext-{id}"
elif kind == "domain":
name = "stdlib" if id == "stdlib" else f"ext-{id}"
else:
name = id
else:
name = id
return f"{AUTHORITY}/marqdo-{name}.git"
def check_component(raw, depth, label, by_id, paths, path_keys):
require(isinstance(raw, dict), f"{label}: invalid component entry: {raw!r}")
id = raw.get("id")
state = raw.get("state")
require(state in {"active", "planned"}, f"{label}: invalid state: {id!r}")
fields = FIELDS | ({"entry"} if state == "active" else set())
require(set(raw) == fields, f"{label}: invalid fields for {id!r}: {sorted(set(raw) ^ fields)}")
require(isinstance(id, str) and re.fullmatch(NAME, id), f"{label}: invalid id: {id!r}")
for key in ("requires", "checks_with"):
items = raw[key]
require(isinstance(items, list) and all(isinstance(item, str) for item in items),
f"{label}: invalid {key}: {id}")
require(id not in items and len(set(items)) == len(items), f"{label}: invalid {key}: {id}")
kind = raw["kind"]
require(kind in RELEASE_ROLES or kind == "domain", f"{label}: unknown kind: {id}: {kind!r}")
if kind == "domain":
require(depth == 0, f"{label}: domain kind is only allowed at the root layer: {id}")
require(raw["release"] in DOMAIN_RELEASE, f"{label}: invalid release role: {id}")
require(raw["requires"] == [], f"{label}: domain requires must be empty: {id}")
else:
require(depth == 0 or kind in DOMAIN_CHILD_KINDS,
f"{label}: component kind is not allowed inside a domain: {id} ({kind})")
require(raw["release"] == RELEASE_ROLES[kind], f"{label}: invalid release role: {id}")
path = check_relative_path(raw["path"], id, label)
if depth == 0:
expected = expected_root_path(raw)
require(expected is not None and path == expected,
f"{label}: invalid path: {id}: {path} (expected {expected})")
require(path not in paths, f"{label}: invalid or duplicate path: {path}")
key = nfc(path).casefold()
require(key not in path_keys, f"{label}: path case/NFC conflict: {id}: {path}")
for other in paths:
require(not path.startswith(other + "/") and not other.startswith(path + "/"),
f"{label}: overlapping component path: {path} / {other}")
for key in ("owner", "scope"):
require(isinstance(raw[key], str) and raw[key].strip(), f"{label}: missing {key}: {id}")
if state == "active":
require(isinstance(raw["entry"], str) and re.fullmatch(ENTRY, raw["entry"]),
f"{label}: unsafe entry: {id}")
paths.add(path)
path_keys.add(key)
by_id[id] = raw
return raw
def parse_catalog(repo, revision, label):
text = read_blob(repo, revision, "components.toml", label)
require(text is not None, f"{label}: missing components.toml at {revision}")
try:
data = tomllib.loads(text)
except tomllib.TOMLDecodeError as error:
raise ValueError(f"{label}: invalid components.toml: {error}") from None
require(set(data) == {"component"} and isinstance(data["component"], list), f"{label}: invalid catalog")
return data["component"]
def tree_entries(repo, revision, label):
try:
output = git("ls-tree", "-rz", "--full-tree", revision, cwd=repo)
except subprocess.CalledProcessError:
raise ValueError(f"{label}: missing Git tree at {revision}") from None
entries = {}
for record in output.split("\0"):
if record:
metadata, path = record.split("\t", 1)
mode, _, sha = metadata.split()
entries[path] = (mode, sha)
return entries
def check_root_tree(entries, linked, unlinked, label):
allowed_readmes = CATEGORY_READMES | {
f'{item["path"]}/README.md'
for item in unlinked
if item["kind"] in {"stdlib", "extension", "domain"}
}
for path, (mode, _) in entries.items():
root = path.split("/", 1)[0]
require(
path in linked or (mode == "100644" and path in allowed_readmes)
or (mode in {"100644", "100755"} and (
path in ROOT_FILES or root in ROOT_DIRS and "/" in path or path.startswith("tests/integration/")
)),
f"{label}: unexpected tracked path or mode: {path} ({mode})",
)
def check_domain_tree(entries, linked, unlinked, label):
"""Aggregate layers only carry governance, docs, examples and tests.
Production implementations stay in the child repositories: an aggregate
may not add a renderer, parser or driver under its own tree.
"""
allowed_readmes = {f'{item["path"]}/README.md' for item in unlinked}
for path, (mode, _) in entries.items():
if path in linked:
continue
if mode == "100644" and path in allowed_readmes:
continue
top = path.split("/", 1)[0]
top_level_doc = mode == "100644" and "/" not in path and path.endswith(".md")
require(
mode in {"100644", "100755"} and (
path in DOMAIN_FILES or top_level_doc or (top in DOMAIN_DIRS and "/" in path)
),
f"{label}: unexpected aggregate tracked path or mode: {path} ({mode})",
)
def read_submodules(repo, revision, label):
if read_blob(repo, revision, ".gitmodules", label) is None:
return {}
try:
output = git("config", "--null", "--blob", f"{revision}:.gitmodules", "--list", cwd=repo)
except subprocess.CalledProcessError:
raise ValueError(f"{label}: invalid .gitmodules") from None
config = {}
for record in output.split("\0"):
if record:
key, value = record.split("\n", 1)
require(key not in config, f"{label}: duplicate submodule setting: {key}")
config[key] = value
return config
def check_submodules(config, linked, depth, label, urls):
"""Match ``.gitmodules`` sections by ``path``, not by section name.
Git configuration keys are keyed by the submodule section name, which is
not required to equal the checked-out path. Path and URL remain the
authority for identity; any other setting (for example an ``update``
command or a relative override) is rejected as unexpected.
"""
sections = {}
extras = []
for key, value in config.items():
match = re.fullmatch(r"submodule\.(.+)\.(path|url)", key)
if not match:
extras.append(key)
continue
name, field = match.groups()
sections.setdefault(name, {})[field] = value
by_path = {}
for name, fields in sections.items():
require(set(fields) == {"path", "url"},
f"{label}: unexpected submodule settings: "
f"{sorted(f'submodule.{name}.{field}' for field in set(fields) ^ {'path', 'url'})}")
path = fields["path"]
require(path not in by_path, f"{label}: duplicate submodule path: {path}")
by_path[path] = fields["url"]
require(not extras, f"{label}: unexpected submodule settings: {sorted(extras)}")
for path, component in linked.items():
require(path in by_path, f"{label}: missing or invalid submodule path: {path}")
url = by_path.pop(path)
expected = expected_remote(component, depth)
require(url == expected, f"{label}: invalid submodule URL: {path}: {url!r}")
require(url not in urls, f"{label}: duplicate submodule remote: {path}: {url}")
urls[url] = path
require(not by_path, f"{label}: unexpected submodule settings: {sorted(by_path)}")
def read_layer(repo, revision, label, depth):
repo = Path(repo)
order = []
components = {}
paths = set()
path_keys = set()
for raw in parse_catalog(repo, revision, label):
order.append(check_component(raw, depth, label, components, paths, path_keys))
entries = tree_entries(repo, revision, label)
gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"}
active_paths = {item["path"] for item in order if item["state"] == "active"}
mismatch = (active_paths - gitlinks.keys()) | (gitlinks.keys() - paths)
require(not mismatch, f"{label}: gitlink/catalog mismatch: {sorted(mismatch)}")
linked = {item["path"]: item for item in order if item["path"] in gitlinks}
unlinked = [item for item in order if item["path"] not in gitlinks]
if depth == 0:
check_root_tree(entries, linked, unlinked, label)
else:
check_domain_tree(entries, linked, unlinked, label)
urls = {}
check_submodules(read_submodules(repo, revision, label), linked, depth, label, urls)
return Layer(repo, revision, label, depth, order, components, gitlinks, linked, urls)
def verify_checkout(layer, component):
path = component["path"]
checkout = layer.repo / path
sha = layer.gitlinks[path]
require(checkout.resolve() == checkout and (checkout / ".git").exists(),
f"{layer.label}: missing submodule checkout: {path}")
try:
git("cat-file", "-e", f"{sha}^{{commit}}", cwd=checkout)
except subprocess.CalledProcessError:
raise ValueError(f"{layer.label}: missing committed object: {path}@{sha}") from None
require(git("rev-parse", "HEAD", cwd=checkout).strip() == sha,
f"{layer.label}: wrong checked-out commit: {path}")
status = ["status", "--porcelain"]
if component["kind"] == "domain":
# Child dirt is the responsibility of the child checkout and is
# reported by its own leaf check, not by the aggregate repository.
status.append("--ignore-submodules=all")
require(not git(*status, cwd=checkout),
f"{layer.label}: dirty submodule: {path}")
if component["state"] == "active":
entry = checkout / component["entry"]
require(entry.is_file() and entry.resolve() == entry,
f"{layer.label}: missing or symbolic entry: {path}/{component['entry']}")
return checkout
def verify_leaf(layer, component):
checkout = verify_checkout(layer, component)
sha = layer.gitlinks[component["path"]]
label = f'{layer.label} leaf {component["id"]} ({component["path"]})'
nested = tree_entries(checkout, sha, label)
gitlinks = sorted(path for path, (mode, _) in nested.items() if mode == "160000")
require(not gitlinks, f"{label}: leaf must not register gitlinks: {gitlinks}")
def validate_graph(layers):
components = {}
for layer in layers:
for component in layer.order:
id = component["id"]
require(id not in components, f"{layer.label}: duplicate global id: {id}")
components[id] = (component, layer)
remotes = {}
for layer in layers:
for url, path in layer.urls.items():
require(url not in remotes, f"{layer.label}: duplicate global remote: {path}: {url}")
remotes[url] = path
for layer in layers:
for component in layer.order:
id = component["id"]
for field in ("requires", "checks_with"):
for dependency in component[field]:
require(dependency in components, f"{layer.label}: unknown dependency: {id} -> {dependency}")
target, _ = components[dependency]
require(component["state"] != "active" or target["state"] == "active",
f"{layer.label}: active depends on planned: {id} -> {dependency}")
if field != "requires":
continue
target_kind = target["kind"]
source_kind = component["kind"]
require(target_kind != "domain",
f"{layer.label}: requires must not target a domain: {id} -> {dependency}")
if source_kind in {"core", "domain"}:
require(False, f"{layer.label}: dependency violation: {id} must not require {dependency}")
if source_kind == "stdlib":
require(target_kind in {"core", "stdlib"},
f"{layer.label}: stdlib dependency violation: {id} -> {dependency}")
elif source_kind == "tool":
require(target_kind in {"core", "extension"},
f"{layer.label}: tool dependency violation: {id} -> {dependency}")
elif source_kind == "extension":
require(target_kind in {"core", "stdlib", "extension"},
f"{layer.label}: extension dependency violation: {id} -> {dependency}")
try:
graph = {id: list(item["requires"]) for id, (item, _) in components.items()}
tuple(graphlib.TopologicalSorter(graph).static_order())
except graphlib.CycleError as error:
raise ValueError(f"root: requires DAG cycle: {error}") from None
def validate(revision, checkouts, expand_domains=False):
layers = [read_layer(ROOT, revision, "root", 0)]
if checkouts or expand_domains:
root = layers[0]
for path, component in root.linked.items():
if component["kind"] != "domain":
if checkouts:
verify_leaf(root, component)
continue
domain_repo = verify_checkout(root, component)
domain = read_layer(domain_repo, root.gitlinks[path],
f"domain {component['id']} ({path})", 1)
layers.append(domain)
if checkouts:
for child in domain.linked.values():
verify_leaf(domain, child)
validate_graph(layers)
return layers
def main():
parser = argparse.ArgumentParser(description="Validate a Marqdo ecosystem Git tree")
parser.add_argument("revision", nargs="?", default="HEAD")
parser.add_argument("--checkouts", action="store_true")
paths = parser.add_mutually_exclusive_group()
paths.add_argument("--active-paths", action="store_true", help="print only direct active component paths")
paths.add_argument("--domain-paths", action="store_true", help="validate domain URLs and print domain paths")
args = parser.parse_args()
try:
revision = git("rev-parse", "--verify", args.revision + "^{commit}").strip()
layers = validate(revision, args.checkouts, expand_domains=args.domain_paths)
if args.active_paths:
for path, component in sorted(layers[0].linked.items()):
if component["state"] == "active":
print(path)
elif args.domain_paths:
for path, component in sorted(layers[0].linked.items()):
if component["kind"] == "domain":
print(path)
else:
for layer in layers:
for path, component in sorted(layer.linked.items()):
relative = (layer.repo / path).relative_to(ROOT).as_posix()
print(f'{component["id"]} {relative} {layer.gitlinks[path]} {component["state"]}')
except (AttributeError, KeyError, OSError, subprocess.CalledProcessError, TypeError, ValueError) as error:
sys.exit(f"layout: {error}")
if __name__ == "__main__":
main()
+333
View File
@@ -0,0 +1,333 @@
#!/usr/bin/env python3
"""Recursive impact analysis between an accepted root commit and a candidate.
Compares the recursively expanded governance tree of two root revisions. A
component identity is `(global_id, parent, remote, SHA, state)`; a domain
gitlink change is expanded to its child identities so leaf changes are visible
even when the parent pointer did not change as a string.
The affected set is computed in the order the development contract requires:
1. changed or removed leaves;
2. reverse transitive closure over `requires` edges from the union of both
graphs (removed edges cannot hide a consumer);
3. parent domains of affected components;
4. `checks_with` fixed point (co-validation is not a build prerequisite).
When a domain cannot be expanded (missing object/checkout) the result is marked
UNVERIFIED and the whole domain is treated as affected rather than silently
skipping it.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import tomllib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SCHEMA = "marqdo.impact"
SCHEMA_VERSION = 1
class ImpactError(Exception):
pass
def git(repo: Path, *args: str) -> bytes:
result = subprocess.run(["git", "-C", str(repo), *args], capture_output=True)
if result.returncode != 0:
raise ImpactError(
f"git {' '.join(args)} failed in {repo}: "
f"{result.stderr.decode(errors='replace').strip()}"
)
return result.stdout
def show(repo: Path, revision: str, path: str) -> bytes | None:
result = subprocess.run(
["git", "-C", str(repo), "show", f"{revision}:{path}"], capture_output=True
)
return result.stdout if result.returncode == 0 else None
def resolve(repo: Path, revision: str) -> str:
try:
return (
git(repo, "rev-parse", "--verify", revision + "^{commit}")
.decode()
.strip()
)
except ImpactError as error:
raise ImpactError(f"cannot resolve revision {revision!r}: {error}") from error
def tree_entries(repo: Path, revision: str) -> dict[str, tuple[str, str]]:
output = git(repo, "ls-tree", "-r", "-z", revision)
entries: dict[str, tuple[str, str]] = {}
for record in output.split(b"\0"):
if not record:
continue
header, _, raw_path = record.partition(b"\t")
fields = header.decode().split()
if len(fields) != 3:
raise ImpactError(f"invalid tree record in {repo}@{revision}")
mode, _kind, sha = fields
entries[raw_path.decode()] = (mode, sha)
return entries
def submodule_urls(repo: Path, revision: str) -> dict[str, str]:
"""Map `.gitmodules` path to URL at a revision (authority for remotes)."""
raw = show(repo, revision, ".gitmodules")
if raw is None:
return {}
config = git(
repo, "config", "--null", "--blob", f"{revision}:.gitmodules", "--list"
)
urls: dict[str, str] = {}
pending: dict[str, dict[str, str]] = {}
for record in config.split(b"\0"):
if not record:
continue
key, _, value = record.decode(errors="replace").partition("\n")
parts = key.split(".")
if len(parts) == 4 and parts[0] == "submodule" and parts[3] in ("path", "url"):
pending.setdefault(parts[1], {})[parts[3]] = value
for fields in pending.values():
if "path" in fields and "url" in fields:
urls[fields["path"]] = fields["url"]
return urls
def read_catalog(repo: Path, revision: str, label: str) -> list[dict]:
raw = show(repo, revision, "components.toml")
if raw is None:
raise ImpactError(f"{label}: revision {revision} has no components.toml")
try:
catalog = tomllib.loads(raw.decode())
except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error:
raise ImpactError(f"{label}: invalid components.toml: {error}") from error
components = catalog.get("component")
if not isinstance(components, list):
raise ImpactError(f"{label}: components.toml has no [[component]] entries")
return components
def load_graph(
repo: Path, revision: str, label: str, depth: int = 0
) -> tuple[dict[str, dict], list[str]]:
"""Expand one governance layer (root then domains) into global identities."""
components = read_catalog(repo, revision, label)
entries = tree_entries(repo, revision)
urls = submodule_urls(repo, revision)
gitlinks = {path: sha for path, (mode, sha) in entries.items() if mode == "160000"}
graph: dict[str, dict] = {}
unverified: list[str] = []
for component in components:
component_id = component.get("id")
path = component.get("path")
if not isinstance(component_id, str) or not isinstance(path, str):
raise ImpactError(f"{label}: component without id/path")
sha = gitlinks.get(path)
identity = {
"id": component_id,
"parent": None,
"path": path,
"remote": urls.get(path),
"sha": sha,
"state": component.get("state"),
"kind": component.get("kind"),
"requires": sorted(component.get("requires", [])),
"checks_with": sorted(component.get("checks_with", [])),
"layer": label,
}
graph[component_id] = identity
if component.get("kind") != "domain" or depth > 0:
continue
domain_repo = repo / path
if sha is None or not (domain_repo / ".git").exists():
unverified.append(
f"{label}: domain {component_id} ({path}) cannot be expanded: "
"missing gitlink or checkout"
)
continue
try:
children, child_unverified = load_graph(
domain_repo, sha, f"domain {component_id}", depth + 1
)
except ImpactError as error:
unverified.append(
f"{label}: domain {component_id} ({path})@{sha} cannot be expanded: {error}"
)
continue
unverified.extend(child_unverified)
for child_id, child in children.items():
if child_id in graph:
raise ImpactError(f"{label}: duplicate global id {child_id}")
child["parent"] = component_id
graph[child_id] = child
return graph, unverified
def identity_fields(component: dict) -> tuple:
return (
component.get("parent"),
component.get("remote"),
component.get("sha"),
component.get("state"),
tuple(component.get("requires", [])),
tuple(component.get("checks_with", [])),
)
def changed_components(
accepted: dict[str, dict], candidate: dict[str, dict]
) -> list[dict]:
changed = []
for component_id in sorted(set(accepted) | set(candidate)):
before = accepted.get(component_id)
after = candidate.get(component_id)
if before is None:
changed.append({"id": component_id, "reason": "added"})
continue
if after is None:
changed.append({"id": component_id, "reason": "removed"})
continue
if before.get("sha") != after.get("sha"):
changed.append({"id": component_id, "reason": "sha"})
elif before.get("state") != after.get("state"):
changed.append({"id": component_id, "reason": "state"})
elif before.get("remote") != after.get("remote"):
changed.append({"id": component_id, "reason": "remote"})
elif before.get("parent") != after.get("parent"):
changed.append({"id": component_id, "reason": "parent"})
elif before.get("requires") != after.get("requires") or before.get(
"checks_with"
) != after.get("checks_with"):
changed.append({"id": component_id, "reason": "dependencies"})
return changed
def affected_set(
accepted: dict[str, dict], candidate: dict[str, dict], changed: list[dict]
) -> tuple[list[str], list[str], list[str]]:
graph = {**accepted, **candidate}
dependents: dict[str, set[str]] = {component_id: set() for component_id in graph}
for component in graph.values():
for dependency in component.get("requires", []):
dependents.setdefault(dependency, set()).add(component["id"])
affected = {item["id"] for item in changed}
queue = list(affected)
while queue:
current = queue.pop()
for consumer in dependents.get(current, set()):
if consumer not in affected:
affected.add(consumer)
queue.append(consumer)
domains = set()
for component_id in list(affected):
parent = graph[component_id].get("parent")
while parent:
if parent not in affected:
domains.add(parent)
parent = graph[parent].get("parent") if parent in graph else None
co_validation: set[str] = set()
while True:
additions = set()
for component_id in affected:
for partner in graph[component_id].get("checks_with", []):
if partner not in affected:
additions.add(partner)
if not additions:
break
affected |= additions
co_validation |= additions
return sorted(affected), sorted(domains), sorted(co_validation)
def analyze(accepted_ref: str, candidate_ref: str) -> dict:
accepted_revision = resolve(ROOT, accepted_ref)
candidate_revision = resolve(ROOT, candidate_ref)
accepted, accepted_unverified = load_graph(ROOT, accepted_revision, "root")
candidate, candidate_unverified = load_graph(ROOT, candidate_revision, "root")
changed = changed_components(accepted, candidate)
affected, domains, co_validation = affected_set(accepted, candidate, changed)
unverified = accepted_unverified + candidate_unverified
fallback = None
if unverified:
# Undetermined scope must widen, never silently skip.
affected = sorted(set(accepted) | set(candidate))
domains = []
co_validation = []
fallback = "full"
return {
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"accepted": {"ref": accepted_ref, "revision": accepted_revision},
"candidate": {"ref": candidate_ref, "revision": candidate_revision},
"counts": {
"accepted_components": len(accepted),
"candidate_components": len(candidate),
"changed": len(changed),
"affected": len(affected),
},
"changed": changed,
"affected": affected,
"domain_ancestors": domains,
"checks_with": co_validation,
"fallback": fallback,
"unverified": unverified,
}
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--accepted", required=True, help="accepted root revision")
parser.add_argument("--candidate", default="HEAD", help="candidate root revision")
parser.add_argument("--out", default=None)
parser.add_argument("--json", action="store_true")
parser.add_argument(
"--fail-on-unverified",
action="store_true",
help="exit 2 when a domain cannot be expanded",
)
args = parser.parse_args(argv)
try:
report = analyze(args.accepted, args.candidate)
except ImpactError as error:
print(f"impact: error: {error}", file=sys.stderr)
return 1
text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
if args.out:
Path(args.out).write_text(text)
if args.json:
print(text, end="")
else:
print(
f"accepted {report['accepted']['revision'][:12]} "
f"candidate {report['candidate']['revision'][:12]}"
)
print(
f"changed={report['counts']['changed']} "
f"affected={report['counts']['affected']}"
)
for item in report["changed"]:
print(f" changed {item['id']}: {item['reason']}")
print("affected: " + ", ".join(report["affected"]))
if report["checks_with"]:
print("co-validation: " + ", ".join(report["checks_with"]))
if report["fallback"]:
print("fallback: full (impact scope undetermined)")
for note in report["unverified"]:
print(f"UNVERIFIED: {note}", file=sys.stderr)
if args.fail_on_unverified and report["unverified"]:
return 2
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+188
View File
@@ -0,0 +1,188 @@
#!/usr/bin/env bash
# Ecosystem integration for one exact candidate combination.
#
# Inputs are the pinned root gitlinks: the root-owned Bundle producer assembles
# the one stdlib Bundle, the CLI/Worker are built from the pinned `cli` commit,
# the release archive is packaged with that explicit Bundle, and every consumer
# runs against that same installed binary + adjacent Bundle. There is no
# implicit artifact from View, no floating branch and no network-selected CLI.
set -euo pipefail
cd "$(dirname "$0")/.."
root="$PWD"
active="$(python3 scripts/check-layout.py --checkouts --active-paths)"
expected=$'cli\nstdlib/collections\nstdlib/data\nstdlib/fs\nstdlib/io\nstdlib/system\nstdlib/text\ntests/conformance\ntools/knowledge\ntools/lint\ntools/prove\ntools/view'
if [[ "$active" != "$expected" ]]; then
echo "UNVERIFIED: update the integration plan for the changed active component set" >&2
exit 1
fi
mkdir -p .integration-work
work="$(mktemp -d "$root/.integration-work/run.XXXXXX")"
echo "integration evidence: $work"
exec > >(tee "$work/run.log") 2>&1
set -x
git rev-parse HEAD
git submodule status --recursive
uname -m
ldd --version
cargo --version
python3 --version
python3 -c 'import jsonschema'
python3 scripts/check-layout.py --checkouts > "$work/layout.txt"
cat "$work/layout.txt"
# Recursive impact analysis against the accepted root commit: the change set
# comes from the recursively expanded (global_id, parent, remote, SHA, state)
# identities, then reverse `requires` closure, parent domains and `checks_with`
# fixed point. An undetermined scope widens to the full candidate.
accepted_ref="${MARQDO_ACCEPTED_REF:-}"
if [[ -z "$accepted_ref" && -n "${CI_COMMIT_TARGET_BRANCH:-}" ]] \
&& git rev-parse --verify "origin/$CI_COMMIT_TARGET_BRANCH" >/dev/null 2>&1; then
accepted_ref="origin/$CI_COMMIT_TARGET_BRANCH"
elif [[ -z "$accepted_ref" ]] && git rev-parse --verify origin/main >/dev/null 2>&1; then
accepted_ref="origin/main"
fi
if [[ -n "$accepted_ref" ]]; then
python3 scripts/impact.py --accepted "$accepted_ref" --candidate HEAD \
--out "$work/impact.json"
fi
# 1. One Bundle, produced by the root-owned producer from the pinned gitlinks.
python3 scripts/build-stdlib.py --out "$work/stdlib" | tee "$work/bundle.json"
bundle_digest="$(python3 -c 'import json,sys; print(json.load(sys.stdin)["tree_digest"])' < "$work/bundle.json")"
bundle_aliases="$(python3 -c 'import json,sys; print(json.load(sys.stdin)["aliases_digest"])' < "$work/bundle.json")"
test -f "$work/stdlib/stdlib.json"
# 2. CLI and Worker from the exact pinned CLI gitlink.
source_sha="$(git -C cli rev-parse HEAD)"
# The CLI release packager resolves its binaries from the pinned CLI checkout's
# own target directory; keep this build there so the package step consumes the
# same artifacts without a second build. Do not export CARGO_TARGET_DIR: the
# consumer repositories build into their own target directories.
CARGO_TARGET_DIR="$root/cli/target" \
cargo build --manifest-path cli/Cargo.toml --locked --release \
-p marqdo-cli -p marqdo-provider-worker
version="$(python3 -c '
import pathlib, tomllib
data = tomllib.loads(pathlib.Path("cli/Cargo.toml").read_text())
print(data["workspace"]["package"]["version"])
')"
# 3. The release archive takes the Bundle as one explicit input.
python3 cli/tools/release/package.py \
--source-sha "$source_sha" --version "$version" \
--stdlib-dir "$work/stdlib" --out-dir "$work/dist" | tee "$work/package.json"
archive="$(find "$work/dist" -maxdepth 1 -name 'marqdo-*.tar.gz' -print -quit)"
python3 cli/tools/release/smoke.py --archive "$archive"
mkdir -p "$work/install"
tar -xzf "$archive" -C "$work/install"
installed="$(find "$work/install" -mindepth 1 -maxdepth 1 -type d -print -quit)"
MARQDO_BIN="$installed/marqdo"
export MARQDO_BIN
test "$(cat "$installed/SOURCE_SHA")" = "$source_sha"
test "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' "$installed/stdlib/stdlib.json")" = "$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' "$work/stdlib/stdlib.json")"
sha256sum "$archive" "$MARQDO_BIN" "$installed/marqdo-provider-worker"
# 4. Root stdlib acceptance: component entries, explicit Packages, composition
# fixtures and fail-closed negatives with the same installed CLI/Bundle.
python3 scripts/acceptance-stdlib.py \
--cli "$MARQDO_BIN" --bundle "$work/stdlib" \
--work "$work/stdlib-acceptance" --evidence "$work/stdlib-acceptance.json"
# 5. Frozen independent public-contract fixtures against the same CLI.
python3 cli/tools/ci/verify_extension_contracts.py \
--source-repo cli --tested-sha "$source_sha" --cli "$MARQDO_BIN" \
--release-info "$installed/RELEASE_INFO.json" \
--fixtures tests/conformance --out "$work/conformance.json"
# 6. Existing consumers, same installed binary and adjacent Bundle.
(
cd tools/view
export MARQDO_TOOL_HOME="$work/view-registry"
scripts/package.sh
"$MARQDO_BIN" tool install dist/marqdo-view/tool.json
"$MARQDO_BIN" view verify examples/mixed-modes/index.mq.md
"$MARQDO_BIN" view export examples/tables-math --out "$work/view-export"
setsid "$MARQDO_BIN" view examples/control-flow --port 0 --no-open >"$work/view-server.log" 2>&1 &
view_pid=$!
stop_view() {
kill -- "-$view_pid" 2>/dev/null || true
wait "$view_pid" 2>/dev/null || true
}
trap stop_view EXIT
view_url=""
for attempt in {1..100}; do
view_url="$(grep -m1 -o 'http://127\.0\.0\.1:[0-9]\+/' "$work/view-server.log" || true)"
if [[ -n "$view_url" ]] || ! kill -0 "$view_pid" 2>/dev/null; then
break
fi
sleep 0.1
done
if [[ -z "$view_url" ]]; then
cat "$work/view-server.log" >&2
exit 1
fi
python3 scripts/acceptance-run.py "$view_url"
stop_view
trap - EXIT
python3 scripts/check-observation.py stream-snapshot
"$MARQDO_BIN" tool remove view
if "$MARQDO_BIN" view --version; then
echo "view still dispatches after removal" >&2
exit 1
fi
)
(
cd tools/knowledge
MARQDO_TEST_BIN="$MARQDO_BIN" cargo test --locked --test core_cli --test compile
)
(
cd tools/prove
cargo test --locked --test analysis_document --test document_contract
)
(
cd tools/lint
export MARQDO_TOOL_HOME="$work/lint-registry"
scripts/package-tool.sh "$work/lint"
"$MARQDO_BIN" tool install "$work/lint/tool.json"
"$MARQDO_BIN" lint examples/nested/inventory.mq.md --format json
"$MARQDO_BIN" tool remove lint
)
# 7. Evidence identity for the accepted candidate.
root_commit="$(git rev-parse HEAD)"
python3 - "$work" "$root_commit" "$source_sha" "$bundle_digest" "$bundle_aliases" "$archive" <<'PY'
import hashlib, json, pathlib, sys
work = pathlib.Path(sys.argv[1])
archive = pathlib.Path(sys.argv[6])
impact_path = work / "impact.json"
impact = json.loads(impact_path.read_text()) if impact_path.is_file() else None
evidence = {
"schema": "marqdo.ecosystem-integration",
"schema_version": 1,
"root_commit": sys.argv[2],
"cli_source_sha": sys.argv[3],
"stdlib_tree_digest": sys.argv[4],
"stdlib_aliases_digest": sys.argv[5],
"archive": archive.name,
"archive_sha256": "sha256:" + hashlib.sha256(archive.read_bytes()).hexdigest(),
"impact": (
{
"changed": impact["changed"],
"affected": impact["affected"],
"checks_with": impact["checks_with"],
"fallback": impact["fallback"],
"unverified": impact["unverified"],
}
if impact
else None
),
"status": "PASS",
}
(work / "integration-evidence.json").write_text(json.dumps(evidence, indent=2) + "\n")
print(json.dumps(evidence, indent=2))
PY
echo "PASS: ecosystem candidate (single CLI/Worker/Bundle artifact, consumers green)"
+13
View File
@@ -0,0 +1,13 @@
{
"name": "marqdo-stdlib",
"version": "0.2.0",
"public_aliases": [
{
"public_names": ["print", "打印"],
"target_module": "io.mq.md",
"target_function": "写值",
"expected_signature": "params(值)",
"effects": ["host"]
}
]
}
-4
View File
@@ -1,4 +0,0 @@
.venv/
__pycache__/
*.pyc
.pytest_cache/
-14
View File
@@ -1,14 +0,0 @@
# Marqdo Spike(Python)
快速验收 ADR 0001 中的 S1–S5,**不是**完整解释器。
```bash
cd spike
python -m venv .venv
# Windows:
.\.venv\Scripts\activate
pip install -r requirements.txt
pytest -q
```
若需代理:`pip install -r requirements.txt --proxy http://127.0.0.1:7897`
-35
View File
@@ -1,35 +0,0 @@
# Spike 报告:Python + markdown-it-py(S1–S5)
| | |
|---|---|
| 日期 | 2026-08-04 |
| 状态 | **通过** |
| 命令 | `cd spike && pytest -q` → `6 passed` |
---
## 结果
| ID | 项 | 结果 | 备注 |
|----|----|------|------|
| S1 | `*` vs `**` | 通过 | `em_*` / `strong_*` 在 inline children 中 |
| S2 | `-` vs `+` | 通过 | **行扫描** `scan_bullets` 保留项目符;库只保证有 `bullet_list` |
| S3 | 单列表格 | 通过 | `table` 规则开启后可解析 |
| S4 | FM `---` vs 正文 `---` | 通过 | 自研 `split_front_matter` |
| S5 | FM 内 `> *.mq.md` | 通过 | 行正则抽取,不整块丢给严格 YAML |
---
## 对实现的含义
1. **行扫描是必需层**:`-`/`+` 消歧、frontmatter 导入、注释行分类,不宜只靠 MD 库 AST。
2. **markdown-it-py** 足够做块/inline 结构(标题、表、强调、列表);避免 `gfm-like` 默认 `linkify`(缺可选依赖会炸)。
3. Spike **不**等于选定长期实现语言;仅证明 Python 路径可验证宪法。参考实现可继续 Python,或再评 TS/Rust。
---
## 建议下一步
1. 将 ADR 0001 中 Spike 标为通过。
2. 拍板:参考实现是否 **继续 Python**(推荐,与 Spike 同栈)或换栈。
3. 再搭建正式包(`src/marqdo`)与 `marqdo run`,按 examples 金样例推进。
-78
View File
@@ -1,78 +0,0 @@
"""
Spike helpers: GFM parse via markdown-it-py + line-level bullet probe.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from markdown_it import MarkdownIt
from mdit_py_plugins.front_matter import front_matter_plugin
def make_md() -> MarkdownIt:
# Avoid gfm-like's linkify (needs optional linkify-it-py).
md = MarkdownIt("commonmark", {"html": False, "linkify": False})
md.enable(["table"])
md.use(front_matter_plugin)
return md
@dataclass
class BulletLine:
line_no: int
marker: str # "-" | "+" | "*" | "1."
text: str
_BULLET = re.compile(
r"^(?P<indent>\s*)(?P<marker>[-+*]|\d+\.)\s+(?P<text>.*)$"
)
def scan_bullets(source: str) -> list[BulletLine]:
"""Line-level scan: preserves '-' vs '+' regardless of MD library."""
out: list[BulletLine] = []
for i, line in enumerate(source.splitlines(), start=1):
m = _BULLET.match(line)
if not m:
continue
out.append(
BulletLine(line_no=i, marker=m.group("marker"), text=m.group("text"))
)
return out
def parse_tokens(source: str):
return make_md().parse(source)
def split_front_matter(source: str) -> tuple[str | None, str]:
"""
Split leading --- ... --- front matter from body.
Body-internal --- is left untouched.
"""
if not source.startswith("---"):
return None, source
lines = source.splitlines(keepends=True)
if not lines or lines[0].strip() != "---":
return None, source
for i in range(1, len(lines)):
if lines[i].strip() == "---":
fm = "".join(lines[1:i])
body = "".join(lines[i + 1 :])
return fm, body
return None, source
_IMPORT = re.compile(r"^>\s*(?P<path>\S+\.mq\.md)\s*$")
def front_matter_imports(fm: str) -> list[str]:
paths: list[str] = []
for line in fm.splitlines():
m = _IMPORT.match(line.strip())
if m:
paths.append(m.group("path"))
return paths
-3
View File
@@ -1,3 +0,0 @@
markdown-it-py>=3.0,<4
mdit-py-plugins>=0.4,<1
pytest>=8.0,<9
-104
View File
@@ -1,104 +0,0 @@
"""ADR 0001 Spike acceptance: S1–S5."""
from __future__ import annotations
from marqdo_spike import (
front_matter_imports,
parse_tokens,
scan_bullets,
split_front_matter,
)
def test_s1_emphasis_vs_strong():
"""S1: *a* vs **a** yield distinct inline marks."""
src = "hello *em* and **strong** end\n"
tokens = parse_tokens(src)
inlines = [t for t in tokens if t.type == "inline"]
assert inlines, "expected inline token"
children = inlines[0].children or []
types = [c.type for c in children]
assert "em_open" in types and "em_close" in types
assert "strong_open" in types and "strong_close" in types
assert any(c.type == "text" and c.content == "em" for c in children)
assert any(c.type == "text" and c.content == "strong" for c in children)
def test_s2_bullet_minus_vs_plus_line_scan():
"""S2: line scan distinguishes '-' (loop) vs '+' (branch)."""
src = """
# main
- loop item
+ branch item
"""
bullets = scan_bullets(src)
markers = [b.marker for b in bullets]
assert "-" in markers
assert "+" in markers
assert bullets[0].marker == "-"
assert bullets[1].marker == "+"
def test_s2_library_list_tokens_exist():
"""S2b: library at least parses both as lists (bullet char may need line scan)."""
src = "- a\n\n+ b\n"
tokens = parse_tokens(src)
assert any(t.type == "bullet_list_open" for t in tokens)
def test_s3_single_column_table():
"""S3: GFM single-column table."""
src = """
| 果 |
|----|
| 苹果 |
| 梨 |
"""
tokens = parse_tokens(src)
assert any(t.type == "table_open" for t in tokens)
texts = [t.content for t in tokens if t.type == "inline"]
flat = " ".join(texts)
assert "果" in flat
assert "苹果" in flat
assert "梨" in flat
def test_s4_front_matter_vs_body_hr():
"""S4: file-level --- front matter vs body --- frame."""
src = """---
title: demo
---
# main
---
+ `x` > 0
> 输出 内容=正
---
"""
fm, body = split_front_matter(src)
assert fm is not None
assert "title: demo" in fm
assert body.lstrip().startswith("# main")
assert "---" in body
assert "+ `x` > 0" in body
# Body still has its own ---; must not be eaten by FM splitter
assert body.count("---") >= 2
def test_s5_front_matter_mq_imports():
"""S5: `> file.mq.md` lines inside front matter."""
src = """---
title: main
> utils.mq.md
> lib/math.mq.md
---
# main
"""
fm, body = split_front_matter(src)
assert fm is not None
imports = front_matter_imports(fm)
assert imports == ["utils.mq.md", "lib/math.mq.md"]
assert "# main" in body
-208
View File
@@ -1,208 +0,0 @@
//! Marqdo AST (Phase I).
use crate::diagnostics::Span;
#[derive(Debug, Clone)]
pub struct Module {
pub imports: Vec<String>,
pub functions: Vec<Function>,
}
#[derive(Debug, Clone)]
pub struct Function {
pub name: String,
pub level: u8,
pub span: Span,
pub params: Vec<String>,
pub body: Vec<Stmt>,
pub children: Vec<Function>,
}
#[derive(Debug, Clone)]
pub enum Stmt {
Assign {
name: String,
value: Expr,
span: Span,
},
Return {
value: Expr,
span: Span,
},
/// Statement-form call (`> …`); return value discarded.
Call {
call: CallExpr,
span: Span,
},
Branch {
arms: Vec<BranchArm>,
span: Span,
},
While {
condition: Expr,
body: Vec<Stmt>,
span: Span,
},
ForEach {
item: String,
collection: String,
body: Vec<Stmt>,
span: Span,
},
}
#[derive(Debug, Clone)]
pub struct BranchArm {
pub condition: Option<Expr>, // None = else
pub body: Vec<Stmt>,
}
#[derive(Debug, Clone)]
pub struct CallExpr {
pub callee: String,
pub args: Vec<Arg>,
}
#[derive(Debug, Clone)]
pub enum Arg {
Positional(Expr),
Named { name: String, value: Expr },
}
#[derive(Debug, Clone)]
pub enum Expr {
Literal(Literal),
Var(String),
/// Text with embedded `` `var` `` segments.
Interp(Vec<InterpPart>),
Unary {
op: UnaryOp,
expr: Box<Expr>,
},
Binary {
op: BinaryOp,
left: Box<Expr>,
right: Box<Expr>,
},
Call(CallExpr),
List(Vec<Expr>),
}
#[derive(Debug, Clone)]
pub enum InterpPart {
Lit(String),
Var(String),
}
#[derive(Debug, Clone)]
pub enum Literal {
None,
Bool(bool),
Int(i64),
Text(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
Not,
Neg,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
And,
Or,
}
/// Pretty-print AST for `--dump-ast`.
pub fn format_ast_dump(path: &str, module: &Module) -> String {
let mut out = String::new();
out.push_str(&format!("=== marqdo: ast ({path}) ===\n"));
if !module.imports.is_empty() {
out.push_str(&format!("(imports {:?})\n", module.imports));
}
for fun in &module.functions {
dump_fun(&mut out, fun, 0);
}
out.push_str("=== marqdo: end ast ===\n");
out
}
fn dump_fun(out: &mut String, fun: &Function, depth: usize) {
let pad = " ".repeat(depth);
out.push_str(&format!(
"{pad}(fun level={} {:?} params={:?} @{}\n",
fun.level, fun.name, fun.params, fun.span
));
for stmt in &fun.body {
dump_stmt(out, stmt, depth + 1);
}
for child in &fun.children {
dump_fun(out, child, depth + 1);
}
out.push_str(&format!("{pad})\n"));
}
fn dump_stmt(out: &mut String, stmt: &Stmt, depth: usize) {
let pad = " ".repeat(depth);
match stmt {
Stmt::Assign { name, value, span } => {
out.push_str(&format!("{pad}(assign {name:?} {value:?} @{span})\n"));
}
Stmt::Return { value, span } => {
out.push_str(&format!("{pad}(return {value:?} @{span})\n"));
}
Stmt::Call { call, span } => {
out.push_str(&format!(
"{pad}(call {:?} {:?} @{span})\n",
call.callee, call.args
));
}
Stmt::Branch { arms, span } => {
out.push_str(&format!("{pad}(branch @{span}\n"));
for arm in arms {
out.push_str(&format!("{pad} (arm cond={:?}\n", arm.condition));
for s in &arm.body {
dump_stmt(out, s, depth + 2);
}
out.push_str(&format!("{pad} )\n"));
}
out.push_str(&format!("{pad})\n"));
}
Stmt::While {
condition,
body,
span,
} => {
out.push_str(&format!("{pad}(while {condition:?} @{span}\n"));
for s in body {
dump_stmt(out, s, depth + 1);
}
out.push_str(&format!("{pad})\n"));
}
Stmt::ForEach {
item,
collection,
body,
span,
} => {
out.push_str(&format!(
"{pad}(foreach {item:?} in {collection:?} @{span}\n"
));
for s in body {
dump_stmt(out, s, depth + 1);
}
out.push_str(&format!("{pad})\n"));
}
}
}
-453
View File
@@ -1,453 +0,0 @@
//! AST → bytecode Program.
use anyhow::{bail, Result};
use std::collections::HashMap;
use crate::ast::{
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
};
use crate::bytecode::{FnChunk, Op, Program};
use crate::value::Value;
struct FlatFun {
name: String,
parent: Option<usize>,
params: Vec<String>,
body: Vec<Stmt>,
children: Vec<usize>,
}
pub fn compile_module(module: &Module) -> Result<Program> {
let mut flat = Vec::new();
for fun in &module.functions {
collect_fun(fun, None, &mut flat);
}
if flat.is_empty() {
bail!("bytecode: no functions to compile");
}
let entry = flat
.iter()
.position(|f| f.name == "main" && f.parent.is_none())
.or_else(|| {
flat.iter()
.position(|f| f.parent.is_none() && f.params.is_empty())
})
.ok_or_else(|| anyhow::anyhow!("bytecode: no entry function"))?;
let mut functions = Vec::new();
for i in 0..flat.len() {
functions.push(compile_function(i, &flat)?);
}
Ok(Program { functions, entry })
}
fn collect_fun(fun: &Function, parent: Option<usize>, flat: &mut Vec<FlatFun>) -> usize {
let id = flat.len();
flat.push(FlatFun {
name: fun.name.clone(),
parent,
params: fun.params.clone(),
body: fun.body.clone(),
children: Vec::new(),
});
let mut child_ids = Vec::new();
for child in &fun.children {
child_ids.push(collect_fun(child, Some(id), flat));
}
flat[id].children = child_ids;
id
}
struct FnCompiler<'a> {
flat: &'a [FlatFun],
fn_id: usize,
chunk: FnChunk,
locals: HashMap<String, u8>,
}
fn compile_function(fn_id: usize, flat: &[FlatFun]) -> Result<FnChunk> {
let fun = &flat[fn_id];
let mut locals = HashMap::new();
for (i, p) in fun.params.iter().enumerate() {
locals.insert(p.clone(), i as u8);
}
let mut c = FnCompiler {
flat,
fn_id,
chunk: FnChunk {
name: fun.name.clone(),
params: fun.params.clone(),
code: Vec::new(),
constants: Vec::new(),
locals: fun.params.clone(),
},
locals,
};
for stmt in &fun.body {
c.compile_stmt(stmt)?;
}
c.emit(Op::None_);
c.emit(Op::Return);
let mut names = vec![String::new(); c.locals.len()];
for (name, slot) in &c.locals {
names[*slot as usize] = name.clone();
}
c.chunk.locals = names;
Ok(c.chunk)
}
impl<'a> FnCompiler<'a> {
fn emit(&mut self, op: Op) {
self.chunk.code.push(op);
}
fn here(&self) -> u16 {
self.chunk.code.len() as u16
}
fn patch(&mut self, at: u16, op: Op) {
self.chunk.code[at as usize] = op;
}
fn add_const(&mut self, v: Value) -> u16 {
if let Some(i) = self.chunk.constants.iter().position(|c| c == &v) {
return i as u16;
}
let i = self.chunk.constants.len() as u16;
self.chunk.constants.push(v);
i
}
fn local_slot(&mut self, name: &str) -> u8 {
if let Some(&s) = self.locals.get(name) {
return s;
}
let s = self.locals.len() as u8;
self.locals.insert(name.to_string(), s);
s
}
fn resolve_call(&self, name: &str) -> Result<usize> {
let fun = &self.flat[self.fn_id];
for &cid in &fun.children {
if self.flat[cid].name == name {
return Ok(cid);
}
}
let mut parent = fun.parent;
while let Some(pid) = parent {
for &cid in &self.flat[pid].children {
if self.flat[cid].name == name {
return Ok(cid);
}
}
parent = self.flat[pid].parent;
}
for (i, f) in self.flat.iter().enumerate() {
if f.parent.is_none() && f.name == name {
return Ok(i);
}
}
bail!("bytecode: unknown function `{name}`")
}
fn compile_stmt(&mut self, stmt: &Stmt) -> Result<()> {
match stmt {
Stmt::Assign { name, value, .. } => {
self.compile_expr(value)?;
let slot = self.local_slot(name);
self.emit(Op::SetLocal(slot));
self.emit(Op::Pop);
}
Stmt::Return { value, .. } => {
self.compile_expr(value)?;
self.emit(Op::Return);
}
Stmt::Call { call, .. } => self.compile_call(call, true)?,
Stmt::Branch { arms, .. } => {
let mut end_jumps = Vec::new();
for (i, arm) in arms.iter().enumerate() {
let is_last = i + 1 == arms.len();
let mut else_jump = None;
if let Some(cond) = &arm.condition {
self.compile_expr(cond)?;
let jf = self.here();
self.emit(Op::JumpIfFalse(0));
else_jump = Some(jf);
}
for st in &arm.body {
self.compile_stmt(st)?;
}
if !is_last {
let j = self.here();
self.emit(Op::Jump(0));
end_jumps.push(j);
}
if let Some(jf) = else_jump {
self.patch(jf, Op::JumpIfFalse(self.here()));
}
}
let end = self.here();
for j in end_jumps {
self.patch(j, Op::Jump(end));
}
}
Stmt::While {
condition, body, ..
} => {
let loop_start = self.here();
self.compile_expr(condition)?;
let exit_j = self.here();
self.emit(Op::JumpIfFalse(0));
for st in body {
self.compile_stmt(st)?;
}
self.emit(Op::Jump(loop_start));
self.patch(exit_j, Op::JumpIfFalse(self.here()));
}
Stmt::ForEach {
item,
collection,
body,
..
} => {
self.compile_expr(&Expr::Var(collection.clone()))?;
let coll_slot = self.local_slot(&format!("__coll_{collection}"));
self.emit(Op::SetLocal(coll_slot));
self.emit(Op::Pop);
let i_slot = self.local_slot(&format!("__i_{collection}"));
let zero = self.add_const(Value::Int(0));
self.emit(Op::Constant(zero));
self.emit(Op::SetLocal(i_slot));
self.emit(Op::Pop);
let item_slot = self.local_slot(item);
let loop_start = self.here();
self.emit(Op::GetLocal(i_slot));
self.emit(Op::GetLocal(coll_slot));
self.emit(Op::Len);
self.emit(Op::Less);
let exit_j = self.here();
self.emit(Op::JumpIfFalse(0));
self.emit(Op::GetLocal(coll_slot));
self.emit(Op::GetLocal(i_slot));
self.emit(Op::GetIndex);
self.emit(Op::SetLocal(item_slot));
self.emit(Op::Pop);
for st in body {
self.compile_stmt(st)?;
}
self.emit(Op::GetLocal(i_slot));
let one = self.add_const(Value::Int(1));
self.emit(Op::Constant(one));
self.emit(Op::Add);
self.emit(Op::SetLocal(i_slot));
self.emit(Op::Pop);
self.emit(Op::Jump(loop_start));
self.patch(exit_j, Op::JumpIfFalse(self.here()));
}
}
Ok(())
}
fn compile_call(&mut self, call: &CallExpr, as_stmt: bool) -> Result<()> {
match call.callee.as_str() {
"print" => {
let text_expr = call
.args
.iter()
.find_map(|a| match a {
Arg::Named { name, value } if name == "text" => Some(value),
_ => None,
})
.or_else(|| {
call.args.iter().find_map(|a| match a {
Arg::Positional(e) => Some(e),
_ => None,
})
})
.ok_or_else(|| anyhow::anyhow!("bytecode: print needs text"))?;
self.compile_expr(text_expr)?;
self.emit(Op::Print);
if !as_stmt {
self.emit(Op::None_);
}
return Ok(());
}
"input" => bail!("bytecode: input not supported"),
_ => {}
}
let fid = self.resolve_call(&call.callee)?;
let params = self.flat[fid].params.clone();
let mut named: HashMap<String, &Expr> = HashMap::new();
let mut positionals = Vec::new();
for a in &call.args {
match a {
Arg::Positional(e) => positionals.push(e),
Arg::Named { name, value } => {
named.insert(name.clone(), value);
}
}
}
let mut pos_i = 0;
for p in &params {
if let Some(e) = named.get(p) {
self.compile_expr(e)?;
} else if pos_i < positionals.len() {
self.compile_expr(positionals[pos_i])?;
pos_i += 1;
} else {
bail!("bytecode: missing argument for parameter `{p}`");
}
}
if pos_i < positionals.len() {
bail!("bytecode: too many positional arguments");
}
self.emit(Op::Call(fid as u16, params.len() as u8));
if as_stmt {
self.emit(Op::Pop);
}
Ok(())
}
fn compile_expr(&mut self, expr: &Expr) -> Result<()> {
match expr {
Expr::Literal(lit) => match lit {
Literal::None => self.emit(Op::None_),
Literal::Bool(true) => self.emit(Op::True),
Literal::Bool(false) => self.emit(Op::False),
Literal::Int(n) => {
let i = self.add_const(Value::Int(*n));
self.emit(Op::Constant(i));
}
Literal::Text(t) => {
let i = self.add_const(Value::Text(t.clone()));
self.emit(Op::Constant(i));
}
},
Expr::Var(name) => {
let slot = self
.locals
.get(name)
.copied()
.ok_or_else(|| anyhow::anyhow!("bytecode: undefined variable `{name}`"))?;
self.emit(Op::GetLocal(slot));
}
Expr::Interp(parts) => {
if parts.is_empty() {
let i = self.add_const(Value::Text(String::new()));
self.emit(Op::Constant(i));
return Ok(());
}
for (idx, part) in parts.iter().enumerate() {
match part {
InterpPart::Lit(t) => {
let i = self.add_const(Value::Text(t.clone()));
self.emit(Op::Constant(i));
}
InterpPart::Var(n) => {
let slot = self.locals.get(n).copied().ok_or_else(|| {
anyhow::anyhow!("bytecode: undefined variable `{n}`")
})?;
self.emit(Op::GetLocal(slot));
}
}
if idx > 0 {
self.emit(Op::Add);
}
}
}
Expr::Unary { op, expr } => {
self.compile_expr(expr)?;
match op {
UnaryOp::Not => self.emit(Op::Not),
UnaryOp::Neg => self.emit(Op::Negate),
}
}
Expr::Binary {
op: BinaryOp::And,
left,
right,
} => {
// JumpIfFalse always pops the tested value.
self.compile_expr(left)?;
let j_false = self.here();
self.emit(Op::JumpIfFalse(0));
self.compile_expr(right)?;
let j_false2 = self.here();
self.emit(Op::JumpIfFalse(0));
self.emit(Op::True);
let j_end = self.here();
self.emit(Op::Jump(0));
let f2 = self.here();
self.patch(j_false2, Op::JumpIfFalse(f2));
self.emit(Op::False);
let j_end2 = self.here();
self.emit(Op::Jump(0));
let f1 = self.here();
self.patch(j_false, Op::JumpIfFalse(f1));
self.emit(Op::False);
let end = self.here();
self.patch(j_end, Op::Jump(end));
self.patch(j_end2, Op::Jump(end));
}
Expr::Binary {
op: BinaryOp::Or,
left,
right,
} => {
self.compile_expr(left)?;
let j_else = self.here();
self.emit(Op::JumpIfFalse(0));
self.emit(Op::True);
let j_end = self.here();
self.emit(Op::Jump(0));
let else_ip = self.here();
self.patch(j_else, Op::JumpIfFalse(else_ip));
self.compile_expr(right)?;
let j_f = self.here();
self.emit(Op::JumpIfFalse(0));
self.emit(Op::True);
let j_end2 = self.here();
self.emit(Op::Jump(0));
let f = self.here();
self.patch(j_f, Op::JumpIfFalse(f));
self.emit(Op::False);
let end = self.here();
self.patch(j_end, Op::Jump(end));
self.patch(j_end2, Op::Jump(end));
}
Expr::Binary { op, left, right } => {
self.compile_expr(left)?;
self.compile_expr(right)?;
self.emit(match op {
BinaryOp::Add => Op::Add,
BinaryOp::Sub => Op::Sub,
BinaryOp::Mul => Op::Mul,
BinaryOp::Div => Op::Div,
BinaryOp::Eq => Op::Equal,
BinaryOp::Ne => Op::NotEqual,
BinaryOp::Lt => Op::Less,
BinaryOp::Le => Op::Lessequal,
BinaryOp::Gt => Op::Greater,
BinaryOp::Ge => Op::GreaterEqual,
BinaryOp::And | BinaryOp::Or => unreachable!(),
});
}
Expr::Call(call) => self.compile_call(call, false)?,
Expr::List(items) => {
for it in items {
self.compile_expr(it)?;
}
self.emit(Op::BuildList(items.len() as u16));
}
}
Ok(())
}
}
-80
View File
@@ -1,80 +0,0 @@
//! Bytecode chunk + opcodes (M5 prototype).
mod compile;
mod vm;
pub use compile::compile_module;
pub use vm::Vm;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Op {
Constant(u16),
True,
False,
None_,
Pop,
GetLocal(u8),
SetLocal(u8),
Add,
Sub,
Mul,
Div,
Negate,
Not,
Equal,
NotEqual,
Greater,
GreaterEqual,
Less,
Lessequal,
/// Absolute jump to instruction index.
Jump(u16),
JumpIfFalse(u16),
Print,
BuildList(u16),
Len,
GetIndex,
/// Call function by index; argc values are on the stack (param order).
Call(u16, u8),
Return,
}
#[derive(Debug, Clone)]
pub struct FnChunk {
pub name: String,
pub params: Vec<String>,
pub code: Vec<Op>,
pub constants: Vec<Value>,
/// Local slot names (params first).
pub locals: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct Program {
pub functions: Vec<FnChunk>,
pub entry: usize,
}
impl Program {
pub fn disassemble(&self) -> String {
let mut out = String::new();
out.push_str("=== marqdo: bytecode ===\n");
for (fi, fun) in self.functions.iter().enumerate() {
let entry = if fi == self.entry { " <entry>" } else { "" };
out.push_str(&format!(
"fn[{fi}] {} params={:?} locals={:?}{entry}\n",
fun.name, fun.params, fun.locals
));
for (i, c) in fun.constants.iter().enumerate() {
out.push_str(&format!(" const[{i}] = {c:?}\n"));
}
for (ip, op) in fun.code.iter().enumerate() {
out.push_str(&format!(" {ip:04} {op:?}\n"));
}
}
out.push_str("=== marqdo: end bytecode ===\n");
out
}
}
-236
View File
@@ -1,236 +0,0 @@
//! Stack VM for Marqdo bytecode.
use anyhow::{bail, Result};
use crate::bytecode::{Op, Program};
use crate::value::Value;
pub struct Vm {
capture: bool,
pub captured_stdout: String,
}
struct Frame {
fn_idx: usize,
ip: usize,
slots: Vec<Value>,
}
impl Vm {
pub fn new() -> Self {
Self {
capture: false,
captured_stdout: String::new(),
}
}
pub fn with_capture() -> Self {
Self {
capture: true,
captured_stdout: String::new(),
}
}
fn emit_line(&mut self, text: &str) {
if self.capture {
self.captured_stdout.push_str(text);
self.captured_stdout.push('\n');
} else {
println!("{text}");
}
}
pub fn run(&mut self, program: &Program) -> Result<Value> {
let mut stack: Vec<Value> = Vec::new();
let entry = program.entry;
let arity = program.functions[entry].params.len();
if arity != 0 {
bail!("bytecode: entry function needs arguments");
}
let mut frames = vec![Frame {
fn_idx: entry,
ip: 0,
slots: vec![Value::None; program.functions[entry].locals.len().max(1)],
}];
loop {
let frame = frames.last_mut().unwrap();
let fun = &program.functions[frame.fn_idx];
if frame.ip >= fun.code.len() {
bail!("bytecode: ip out of range in {}", fun.name);
}
let op = fun.code[frame.ip];
frame.ip += 1;
match op {
Op::Constant(i) => stack.push(fun.constants[i as usize].clone()),
Op::True => stack.push(Value::Bool(true)),
Op::False => stack.push(Value::Bool(false)),
Op::None_ => stack.push(Value::None),
Op::Pop => {
stack.pop();
}
Op::GetLocal(i) => {
let v = frames.last().unwrap().slots[i as usize].clone();
stack.push(v);
}
Op::SetLocal(i) => {
let v = stack.last().cloned().unwrap_or(Value::None);
let slot = i as usize;
let fr = frames.last_mut().unwrap();
if fr.slots.len() <= slot {
fr.slots.resize(slot + 1, Value::None);
}
fr.slots[slot] = v;
}
Op::Add => {
let b = pop(&mut stack)?;
let a = pop(&mut stack)?;
stack.push(add(a, b)?);
}
Op::Sub => bin_int(&mut stack, |a, b| a - b)?,
Op::Mul => bin_int(&mut stack, |a, b| a * b)?,
Op::Div => {
let b = pop(&mut stack)?;
let a = pop(&mut stack)?;
match (a, b) {
(Value::Int(_), Value::Int(0)) => bail!("division by zero"),
(Value::Int(x), Value::Int(y)) => stack.push(Value::Int(x / y)),
_ => bail!("`/` needs ints"),
}
}
Op::Negate => match pop(&mut stack)? {
Value::Int(n) => stack.push(Value::Int(-n)),
_ => bail!("unary `-` needs int"),
},
Op::Not => {
let v = pop(&mut stack)?;
stack.push(Value::Bool(!v.truthy()));
}
Op::Equal => {
let b = pop(&mut stack)?;
let a = pop(&mut stack)?;
stack.push(Value::Bool(a == b));
}
Op::NotEqual => {
let b = pop(&mut stack)?;
let a = pop(&mut stack)?;
stack.push(Value::Bool(a != b));
}
Op::Greater => cmp(&mut stack, |o| o.is_gt())?,
Op::GreaterEqual => cmp(&mut stack, |o| o.is_ge())?,
Op::Less => cmp(&mut stack, |o| o.is_lt())?,
Op::Lessequal => cmp(&mut stack, |o| o.is_le())?,
Op::Jump(t) => {
frames.last_mut().unwrap().ip = t as usize;
}
Op::JumpIfFalse(t) => {
let v = pop(&mut stack)?;
if !v.truthy() {
frames.last_mut().unwrap().ip = t as usize;
}
}
Op::Print => {
let v = pop(&mut stack)?;
self.emit_line(&v.as_display());
}
Op::BuildList(n) => {
let n = n as usize;
let mut items = Vec::with_capacity(n);
for _ in 0..n {
items.push(pop(&mut stack)?);
}
items.reverse();
stack.push(Value::List(items));
}
Op::Len => match pop(&mut stack)? {
Value::List(xs) => stack.push(Value::Int(xs.len() as i64)),
_ => bail!("len needs list"),
},
Op::GetIndex => {
let idx = pop(&mut stack)?;
let list = pop(&mut stack)?;
match (list, idx) {
(Value::List(xs), Value::Int(i)) if i >= 0 && (i as usize) < xs.len() => {
stack.push(xs[i as usize].clone());
}
(Value::List(_), Value::Int(_)) => stack.push(Value::None),
_ => bail!("GetIndex needs list and int"),
}
}
Op::Call(fid, argc) => {
let fid = fid as usize;
let argc = argc as usize;
let callee = &program.functions[fid];
if callee.params.len() != argc {
bail!("bytecode: call argc mismatch");
}
let mut slots = vec![Value::None; callee.locals.len().max(argc).max(1)];
for i in (0..argc).rev() {
slots[i] = pop(&mut stack)?;
}
// args were pushed in param order; we popped reverse so slots[0] is last param — fix:
// stack had p0, p1, p2 (top). pop → p2, p1, p0. So assign slots[argc-1-i] or pop into reverse.
// Actually we did: for i in (0..argc).rev() { slots[i] = pop() }
// first pop → slots[argc-1] = top = last param. Good if push order was p0..plast.
frames.push(Frame {
fn_idx: fid,
ip: 0,
slots,
});
}
Op::Return => {
let ret = pop(&mut stack).unwrap_or(Value::None);
frames.pop();
if frames.is_empty() {
return Ok(ret);
}
stack.push(ret);
}
}
}
}
}
fn pop(stack: &mut Vec<Value>) -> Result<Value> {
stack
.pop()
.ok_or_else(|| anyhow::anyhow!("bytecode: stack underflow"))
}
fn add(a: Value, b: Value) -> Result<Value> {
match (a, b) {
(Value::Int(x), Value::Int(y)) => Ok(Value::Int(x + y)),
(Value::Text(x), Value::Text(y)) => Ok(Value::Text(format!("{x}{y}"))),
(Value::Text(x), y) => Ok(Value::Text(format!("{x}{}", y.as_display()))),
(x, Value::Text(y)) => Ok(Value::Text(format!("{}{y}", x.as_display()))),
// Int + display for interp GetLocal Int + Lit text
(Value::Int(x), y) => Ok(Value::Text(format!("{}{}", x, y.as_display()))),
(x, Value::Int(y)) => Ok(Value::Text(format!("{}{y}", x.as_display()))),
_ => bail!("`+` needs ints or text"),
}
}
fn bin_int(stack: &mut Vec<Value>, f: impl Fn(i64, i64) -> i64) -> Result<()> {
let b = pop(stack)?;
let a = pop(stack)?;
match (a, b) {
(Value::Int(x), Value::Int(y)) => {
stack.push(Value::Int(f(x, y)));
Ok(())
}
_ => bail!("binary op needs ints"),
}
}
fn cmp(stack: &mut Vec<Value>, pred: impl Fn(std::cmp::Ordering) -> bool) -> Result<()> {
let b = pop(stack)?;
let a = pop(stack)?;
let ord = match (&a, &b) {
(Value::Int(x), Value::Int(y)) => x.cmp(y),
(Value::Text(x), Value::Text(y)) => x.cmp(y),
_ => bail!("comparison needs two ints or two texts"),
};
stack.push(Value::Bool(pred(ord)));
Ok(())
}
-9
View File
@@ -1,9 +0,0 @@
//! Captured program run (for tests and `view`).
use crate::value::Value;
#[derive(Debug, Clone)]
pub struct RunCapture {
pub stdout: String,
pub value: Value,
}
-3
View File
@@ -1,3 +0,0 @@
//! Pipeline dump helpers (see doc/design/pipeline-debug.md).
pub use crate::lex::format_lines_dump;
-59
View File
@@ -1,59 +0,0 @@
//! Diagnostics with file/line/column.
use std::fmt;
use std::path::{Path, PathBuf};
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
pub line: u32,
pub col: u32,
}
impl Span {
pub fn new(line: u32, col: u32) -> Self {
Self { line, col }
}
}
impl fmt::Display for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}:{}", self.line, self.col)
}
}
/// Unified diagnostic: `path:line:col: message` (path omitted if unknown).
#[derive(Debug, Error, Clone)]
#[error("{}", self.format_message())]
pub struct Diagnostic {
pub path: Option<PathBuf>,
pub span: Span,
pub message: String,
}
impl Diagnostic {
pub fn new(path: Option<&Path>, span: Span, message: impl Into<String>) -> Self {
Self {
path: path.map(|p| p.to_path_buf()),
span,
message: message.into(),
}
}
pub fn at(path: &Path, span: Span, message: impl Into<String>) -> Self {
Self::new(Some(path), span, message)
}
pub fn format_message(&self) -> String {
match &self.path {
Some(p) => format!("{}:{}: {}", p.display(), self.span, self.message),
None => format!("{}: {}", self.span, self.message),
}
}
}
/// Convenience for `anyhow` sites that already have a span.
pub fn bail_at(path: Option<&Path>, span: Span, message: impl Into<String>) -> anyhow::Error {
anyhow::Error::new(Diagnostic::new(path, span, message))
}
-509
View File
@@ -1,509 +0,0 @@
//! Tree-walk interpreter (Phase I).
use anyhow::{bail, Result};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use crate::ast::{
Arg, BinaryOp, CallExpr, Expr, Function, InterpPart, Literal, Module, Stmt, UnaryOp,
};
use crate::diagnostics::{bail_at, Span};
use crate::value::Value;
pub struct Interpreter {
pub path: Option<PathBuf>,
pub trace: bool,
capture: bool,
pub captured_stdout: String,
current_span: Span,
}
struct Env {
vars: HashMap<String, Value>,
}
impl Env {
fn new() -> Self {
Self {
vars: HashMap::new(),
}
}
fn get(&self, name: &str) -> Option<&Value> {
self.vars.get(name)
}
fn set(&mut self, name: String, value: Value) {
self.vars.insert(name, value);
}
}
enum EvArg {
Positional(Value),
Named(String, Value),
}
impl Interpreter {
pub fn new(path: Option<&Path>, trace: bool) -> Self {
Self {
path: path.map(|p| p.to_path_buf()),
trace,
capture: false,
captured_stdout: String::new(),
current_span: Span::new(1, 1),
}
}
pub fn with_capture(path: Option<&Path>, trace: bool) -> Self {
Self {
path: path.map(|p| p.to_path_buf()),
trace,
capture: true,
captured_stdout: String::new(),
current_span: Span::new(1, 1),
}
}
fn err(&self, message: impl Into<String>) -> anyhow::Error {
bail_at(self.path.as_deref(), self.current_span, message)
}
fn emit_line(&mut self, text: &str) {
if self.capture {
self.captured_stdout.push_str(text);
self.captured_stdout.push('\n');
} else {
println!("{text}");
}
}
pub fn run_module(&mut self, module: &Module) -> Result<Value> {
if let Some(main) = find_top(module, "main") {
return self.run_function(module, main, Env::new(), &[]);
}
let tops: Vec<&Function> = module.functions.iter().filter(|f| f.level == 1).collect();
if tops.is_empty() {
bail!("no `# main` and no level-1 function to run");
}
let mut last = Value::None;
for fun in tops {
if fun.params.is_empty() {
last = self.run_function(module, fun, Env::new(), &[])?;
}
}
Ok(last)
}
fn run_function(
&mut self,
module: &Module,
fun: &Function,
mut env: Env,
args: &[(String, Value)],
) -> Result<Value> {
if self.trace {
eprintln!("enter fun {:?}", fun.name);
}
for (k, v) in args {
env.set(k.clone(), v.clone());
}
for p in &fun.params {
if env.get(p).is_none() {
env.set(p.clone(), Value::None);
}
}
let mut ret = Value::None;
for stmt in &fun.body {
if let Some(v) = self.exec_stmt(module, fun, &mut env, stmt)? {
ret = v;
break;
}
}
if self.trace {
eprintln!("leave fun {:?} => {ret}", fun.name);
}
Ok(ret)
}
fn exec_stmt(
&mut self,
module: &Module,
fun: &Function,
env: &mut Env,
stmt: &Stmt,
) -> Result<Option<Value>> {
match stmt {
Stmt::Assign { name, value, span } => {
self.current_span = *span;
let v = self.eval_expr(module, fun, env, value)?;
if self.trace {
eprintln!(" assign {name} = {v:?} @{span}");
}
env.set(name.clone(), v);
Ok(None)
}
Stmt::Return { value, span } => {
self.current_span = *span;
let v = self.eval_expr(module, fun, env, value)?;
if self.trace {
eprintln!(" return {v:?} @{span}");
}
Ok(Some(v))
}
Stmt::Call { call, span } => {
self.current_span = *span;
if self.trace {
eprintln!(" call-stmt {} @{span}", call.callee);
}
let _ = self.eval_call(module, fun, env, call)?;
Ok(None)
}
Stmt::Branch { arms, span } => {
self.current_span = *span;
if self.trace {
eprintln!(" branch @{span}");
}
for arm in arms {
let take = match &arm.condition {
None => true,
Some(cond) => self.eval_expr(module, fun, env, cond)?.truthy(),
};
if take {
for s in &arm.body {
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
return Ok(Some(v));
}
}
break;
}
}
Ok(None)
}
Stmt::While {
condition,
body,
span,
} => {
self.current_span = *span;
if self.trace {
eprintln!(" while @{span}");
}
let mut guard = 0u32;
while self.eval_expr(module, fun, env, condition)?.truthy() {
guard += 1;
if guard > 1_000_000 {
return Err(self.err("while loop exceeded iteration limit"));
}
for s in body {
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
return Ok(Some(v));
}
}
}
Ok(None)
}
Stmt::ForEach {
item,
collection,
body,
span,
} => {
self.current_span = *span;
if self.trace {
eprintln!(" foreach {item} in {collection} @{span}");
}
let coll = env.get(collection).cloned().ok_or_else(|| {
self.err(format!("undefined collection `{collection}`"))
})?;
let items = match coll {
Value::List(xs) => xs,
other => {
return Err(self.err(format!("foreach needs a list, got {other:?}")));
}
};
for val in items {
env.set(item.clone(), val);
for s in body {
if let Some(v) = self.exec_stmt(module, fun, env, s)? {
return Ok(Some(v));
}
}
}
Ok(None)
}
}
}
fn eval_expr(
&mut self,
module: &Module,
fun: &Function,
env: &mut Env,
expr: &Expr,
) -> Result<Value> {
match expr {
Expr::Literal(lit) => Ok(lit_to_value(lit)),
Expr::Var(name) => env
.get(name)
.cloned()
.ok_or_else(|| self.err(format!("undefined variable `{name}`"))),
Expr::Interp(parts) => {
let mut s = String::new();
for part in parts {
match part {
InterpPart::Lit(t) => s.push_str(t),
InterpPart::Var(n) => {
let v = env
.get(n)
.ok_or_else(|| self.err(format!("undefined variable `{n}`")))?;
s.push_str(&v.as_display());
}
}
}
Ok(Value::Text(s))
}
Expr::Unary { op, expr } => {
let v = self.eval_expr(module, fun, env, expr)?;
match op {
UnaryOp::Not => Ok(Value::Bool(!v.truthy())),
UnaryOp::Neg => match v {
Value::Int(n) => Ok(Value::Int(-n)),
_ => Err(self.err("unary `-` needs int")),
},
}
}
Expr::Binary { op, left, right } => {
let l = self.eval_expr(module, fun, env, left)?;
match op {
BinaryOp::And => {
if !l.truthy() {
return Ok(Value::Bool(false));
}
let r = self.eval_expr(module, fun, env, right)?;
return Ok(Value::Bool(r.truthy()));
}
BinaryOp::Or => {
if l.truthy() {
return Ok(Value::Bool(true));
}
let r = self.eval_expr(module, fun, env, right)?;
return Ok(Value::Bool(r.truthy()));
}
_ => {}
}
let r = self.eval_expr(module, fun, env, right)?;
eval_binary(*op, &l, &r).map_err(|e| self.err(e.to_string()))
}
Expr::Call(call) => self.eval_call(module, fun, env, call),
Expr::List(items) => {
let mut out = Vec::new();
for it in items {
out.push(self.eval_expr(module, fun, env, it)?);
}
Ok(Value::List(out))
}
}
}
fn eval_call(
&mut self,
module: &Module,
fun: &Function,
env: &mut Env,
call: &CallExpr,
) -> Result<Value> {
let mut ev_args = Vec::new();
for arg in &call.args {
match arg {
Arg::Positional(e) => {
ev_args.push(EvArg::Positional(self.eval_expr(module, fun, env, e)?));
}
Arg::Named { name, value } => {
ev_args.push(EvArg::Named(
name.clone(),
self.eval_expr(module, fun, env, value)?,
));
}
}
}
match call.callee.as_str() {
"print" => {
let bound = bind_args(&["text".into()], &ev_args, false)
.map_err(|m| self.err(m))?;
let text = bound
.get("text")
.map(|v| v.as_display())
.ok_or_else(|| self.err("print requires text (named or positional)"))?;
self.emit_line(&text);
return Ok(Value::None);
}
"input" => {
if self.capture {
return Err(self.err("input is not available under capture / view"));
}
let bound = bind_args(&["prompt".into()], &ev_args, true)
.map_err(|m| self.err(m))?;
let prompt = bound
.get("prompt")
.map(|v| v.as_display())
.unwrap_or_default();
if !prompt.is_empty() {
print!("{prompt}");
use std::io::Write;
let _ = std::io::stdout().flush();
}
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
if line.ends_with('\n') {
line.pop();
if line.ends_with('\r') {
line.pop();
}
}
return Ok(Value::Text(line));
}
_ => {}
}
let target = lookup_function(module, fun, &call.callee)
.ok_or_else(|| self.err(format!("unknown function `{}`", call.callee)))?;
let bound = bind_args(&target.params, &ev_args, false).map_err(|m| self.err(m))?;
let mut call_env = Env::new();
for (k, v) in bound {
call_env.set(k, v);
}
self.run_function(module, target, call_env, &[])
}
}
/// Bind evaluated args onto parameter names. Err is a plain message (caller adds span/path).
fn bind_args(
params: &[String],
args: &[EvArg],
allow_missing: bool,
) -> std::result::Result<HashMap<String, Value>, String> {
let mut named: HashMap<String, Value> = HashMap::new();
let mut positionals = Vec::new();
for a in args {
match a {
EvArg::Positional(v) => positionals.push(v.clone()),
EvArg::Named(k, v) => {
if named.contains_key(k) {
return Err(format!("duplicate named argument `{k}`"));
}
named.insert(k.clone(), v.clone());
}
}
}
let mut out: HashMap<String, Value> = HashMap::new();
let mut used_named = HashSet::new();
let mut pos_i = 0usize;
for p in params {
if let Some(v) = named.get(p) {
out.insert(p.clone(), v.clone());
used_named.insert(p.clone());
} else if pos_i < positionals.len() {
out.insert(p.clone(), positionals[pos_i].clone());
pos_i += 1;
} else if !allow_missing {
return Err(format!("missing argument for parameter `{p}`"));
}
}
if pos_i < positionals.len() {
return Err(format!(
"too many positional arguments ({} extra)",
positionals.len() - pos_i
));
}
for (k, v) in named {
if !used_named.contains(&k) && !out.contains_key(&k) {
out.insert(k, v);
}
}
Ok(out)
}
fn find_top<'a>(module: &'a Module, name: &str) -> Option<&'a Function> {
module.functions.iter().find(|f| f.name == name)
}
fn lookup_function<'a>(
module: &'a Module,
current: &'a Function,
name: &str,
) -> Option<&'a Function> {
if let Some(f) = find_in_tree(current, name) {
return Some(f);
}
module.functions.iter().find(|f| f.name == name)
}
fn find_in_tree<'a>(fun: &'a Function, name: &str) -> Option<&'a Function> {
for child in &fun.children {
if child.name == name {
return Some(child);
}
if let Some(f) = find_in_tree(child, name) {
return Some(f);
}
}
None
}
fn lit_to_value(lit: &Literal) -> Value {
match lit {
Literal::None => Value::None,
Literal::Bool(b) => Value::Bool(*b),
Literal::Int(n) => Value::Int(*n),
Literal::Text(s) => Value::Text(s.clone()),
}
}
fn eval_binary(op: BinaryOp, l: &Value, r: &Value) -> Result<Value> {
match op {
BinaryOp::Add => match (l, r) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a + b)),
(Value::Text(a), Value::Text(b)) => Ok(Value::Text(format!("{a}{b}"))),
(Value::Text(a), b) => Ok(Value::Text(format!("{a}{}", b.as_display()))),
(a, Value::Text(b)) => Ok(Value::Text(format!("{}{b}", a.as_display()))),
_ => bail!("`+` needs ints or text"),
},
BinaryOp::Sub => match (l, r) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a - b)),
_ => bail!("`-` needs ints"),
},
BinaryOp::Mul => match (l, r) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a * b)),
_ => bail!("`*` needs ints"),
},
BinaryOp::Div => match (l, r) {
(Value::Int(_), Value::Int(0)) => bail!("division by zero"),
(Value::Int(a), Value::Int(b)) => Ok(Value::Int(a / b)),
_ => bail!("`/` needs ints"),
},
BinaryOp::Eq => Ok(Value::Bool(l == r)),
BinaryOp::Ne => Ok(Value::Bool(l != r)),
BinaryOp::Lt => cmp_ord(l, r, |o| o.is_lt()),
BinaryOp::Le => cmp_ord(l, r, |o| o.is_le()),
BinaryOp::Gt => cmp_ord(l, r, |o| o.is_gt()),
BinaryOp::Ge => cmp_ord(l, r, |o| o.is_ge()),
BinaryOp::And | BinaryOp::Or => unreachable!("handled above"),
}
}
fn cmp_ord(l: &Value, r: &Value, f: impl Fn(std::cmp::Ordering) -> bool) -> Result<Value> {
match (l, r) {
(Value::Int(a), Value::Int(b)) => Ok(Value::Bool(f(a.cmp(b)))),
(Value::Text(a), Value::Text(b)) => Ok(Value::Bool(f(a.cmp(b)))),
_ => bail!("comparison needs two ints or two texts"),
}
}
-130
View File
@@ -1,130 +0,0 @@
//! Line classification (M1) — no Flex.
//!
//! Unmarked lines are comments; lines whose first non-whitespace character
//! opens a Marqdo/Markdown marker are code.
use std::fmt;
/// Kind of a source line after skipping leading indentation for the test.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineKind {
Blank,
Comment,
Code,
}
impl fmt::Display for LineKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LineKind::Blank => write!(f, "Blank"),
LineKind::Comment => write!(f, "Comment"),
LineKind::Code => write!(f, "Code"),
}
}
}
/// One classified source line (1-based line number).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClassifiedLine {
pub line_no: u32,
pub kind: LineKind,
pub text: String,
}
/// Characters that start a code line when they appear as the first non-ws char.
fn is_code_starter(c: char) -> bool {
matches!(
c,
'#' | '*' | '>' | '+' | '-' | '`' | '|' | '~'
) || c.is_ascii_digit()
}
/// Classify a single logical line (no trailing newline required).
pub fn classify_line(text: &str) -> LineKind {
let trimmed = text.trim_end_matches(['\r', '\n']);
if trimmed.chars().all(|c| c.is_whitespace()) {
return LineKind::Blank;
}
let first = trimmed.chars().find(|c| !c.is_whitespace());
match first {
None => LineKind::Blank,
Some(c) if is_code_starter(c) => LineKind::Code,
Some(_) => LineKind::Comment,
}
}
/// Classify every line of a source file.
pub fn classify_source(source: &str) -> Vec<ClassifiedLine> {
let source = source.strip_prefix('\u{feff}').unwrap_or(source);
let lines: Vec<&str> = if source.is_empty() {
Vec::new()
} else {
source.lines().collect()
};
lines
.into_iter()
.enumerate()
.map(|(i, text)| ClassifiedLine {
line_no: (i + 1) as u32,
kind: classify_line(text),
text: text.to_string(),
})
.collect()
}
/// Human-readable dump for `--dump-lines`.
pub fn format_lines_dump(path: &str, lines: &[ClassifiedLine]) -> String {
let mut out = String::new();
out.push_str(&format!("=== marqdo: lines ({path}) ===\n"));
for line in lines {
let preview = if line.text.len() > 80 {
format!("{}…", &line.text.chars().take(80).collect::<String>())
} else {
line.text.clone()
};
match line.kind {
LineKind::Blank => {
out.push_str(&format!("{:4} {:7}\n", line.line_no, line.kind));
}
_ => {
out.push_str(&format!(
"{:4} {:7} | {}\n",
line.line_no, line.kind, preview
));
}
}
}
out.push_str("=== marqdo: end lines ===\n");
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn blank_and_comment_and_code() {
assert_eq!(classify_line(""), LineKind::Blank);
assert_eq!(classify_line(" "), LineKind::Blank);
assert_eq!(classify_line("hello world"), LineKind::Comment);
assert_eq!(classify_line(" 中文说明"), LineKind::Comment);
assert_eq!(classify_line("> print text=hi"), LineKind::Code);
assert_eq!(classify_line("# main"), LineKind::Code);
assert_eq!(classify_line("*`x` = 1*"), LineKind::Code);
assert_eq!(classify_line("**ret**"), LineKind::Code);
assert_eq!(classify_line("+ `x` > 0"), LineKind::Code);
assert_eq!(classify_line("- item"), LineKind::Code);
assert_eq!(classify_line("1. arm"), LineKind::Code);
assert_eq!(classify_line("| a |"), LineKind::Code);
assert_eq!(classify_line("`x` = 1"), LineKind::Code);
}
#[test]
fn classify_hello_fixture() {
let src = include_str!("../../examples/structure/hello.mq.md");
let lines = classify_source(src);
assert!(lines.iter().any(|l| l.kind == LineKind::Code && l.text.contains("print")));
assert!(lines.iter().any(|l| l.kind == LineKind::Comment));
}
}
-173
View File
@@ -1,173 +0,0 @@
//! Marqdo reference interpreter (Phase I + M5 bytecode prototype).
//!
//! Pipeline: load → line classify → parse → tree-walk eval | bytecode VM.
//! CLI also offers `view` for AST-backed browsing.
pub mod ast;
pub mod bytecode;
pub mod capture;
pub mod debug;
pub mod diagnostics;
pub mod interp;
pub mod lex;
pub mod load;
pub mod parse;
pub mod value;
pub mod view;
use std::path::Path;
use anyhow::{bail, Result};
use crate::ast::format_ast_dump;
use crate::bytecode::{compile_module, Vm};
use crate::capture::RunCapture;
use crate::interp::Interpreter;
use crate::lex::{classify_source, format_lines_dump};
use crate::load::load_module;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Backend {
#[default]
Tree,
Bytecode,
}
impl Backend {
pub fn parse(s: &str) -> Result<Self> {
match s {
"tree" => Ok(Self::Tree),
"bytecode" | "bc" => Ok(Self::Bytecode),
other => bail!("unknown backend `{other}` (expected tree|bytecode)"),
}
}
}
/// Options for a single `run` / dump invocation.
#[derive(Debug, Clone, Default)]
pub struct RunOptions {
pub dump_lines: bool,
pub dump_tokens: bool,
pub dump_ast: bool,
pub dump_sema: bool,
pub dump_bytecode: bool,
pub trace_eval: bool,
pub backend: Backend,
}
impl RunOptions {
pub fn dump_all() -> Self {
Self {
dump_lines: true,
dump_tokens: true,
dump_ast: true,
dump_sema: true,
dump_bytecode: true,
trace_eval: true,
backend: Backend::Tree,
}
}
pub fn any_dump(&self) -> bool {
self.dump_lines
|| self.dump_tokens
|| self.dump_ast
|| self.dump_sema
|| self.dump_bytecode
|| self.trace_eval
}
}
/// Run a `.mq.md` program (prints to real stdout).
pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
let source = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("failed to read {}: {e}", path.display()))?;
if source.trim().is_empty() {
bail!("{} is empty", path.display());
}
let path_label = path.display().to_string();
if opts.dump_lines {
let lines = classify_source(&source);
print!("{}", format_lines_dump(&path_label, &lines));
}
if opts.dump_tokens {
println!("=== marqdo: tokens ({path_label}) ===");
println!("(fine-grained tokens not implemented yet — use --dump-lines)");
println!("=== marqdo: end tokens ===");
}
let module = load_module(path)?;
if opts.dump_ast {
print!("{}", format_ast_dump(&path_label, &module));
}
if opts.dump_sema {
println!("=== marqdo: sema ({path_label}) ===");
println!(
"functions: {:?}",
module
.functions
.iter()
.map(|f| f.name.as_str())
.collect::<Vec<_>>()
);
println!("imports: {:?}", module.imports);
println!("=== marqdo: end sema ===");
}
match opts.backend {
Backend::Tree => {
let mut interp = Interpreter::new(Some(path), opts.trace_eval);
if opts.trace_eval {
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
}
interp.run_module(&module)?;
if opts.trace_eval {
eprintln!("=== marqdo: end trace-eval ===");
}
}
Backend::Bytecode => {
let program = compile_module(&module)?;
if opts.dump_bytecode {
print!("{}", program.disassemble());
}
let mut vm = Vm::new();
vm.run(&program)?;
}
}
// dump bytecode even on tree backend if requested
if opts.backend == Backend::Tree && opts.dump_bytecode {
let program = compile_module(&module)?;
print!("{}", program.disassemble());
}
Ok(0)
}
/// Run and capture stdout (used by `view` and tests).
pub fn run_file_capture(path: &Path, opts: &RunOptions) -> Result<RunCapture> {
let module = load_module(path)?;
match opts.backend {
Backend::Tree => {
let mut interp = Interpreter::with_capture(Some(path), false);
let value = interp.run_module(&module)?;
Ok(RunCapture {
stdout: interp.captured_stdout,
value,
})
}
Backend::Bytecode => {
let program = compile_module(&module)?;
let mut vm = Vm::with_capture();
let value = vm.run(&program)?;
Ok(RunCapture {
stdout: vm.captured_stdout,
value,
})
}
}
}
-68
View File
@@ -1,68 +0,0 @@
//! Load `.mq.md` files and merge frontmatter imports.
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use anyhow::{bail, Context, Result};
use crate::ast::{Function, Module};
use crate::diagnostics::Diagnostic;
use crate::parse::parse_source;
/// Load `path` and recursively merge imported modules' top-level functions.
pub fn load_module(path: &Path) -> Result<Module> {
let mut visited = HashSet::new();
load_module_inner(path, &mut visited)
}
fn load_module_inner(path: &Path, visited: &mut HashSet<PathBuf>) -> Result<Module> {
let canon = path
.canonicalize()
.unwrap_or_else(|_| path.to_path_buf());
if !visited.insert(canon.clone()) {
bail!("circular import involving {}", path.display());
}
let source = std::fs::read_to_string(path)
.with_context(|| format!("failed to read {}", path.display()))?;
let mut module = parse_source(&source).map_err(|e| attach_path(path, e))?;
let base = path.parent().unwrap_or_else(|| Path::new("."));
let imports = module.imports.clone();
for rel in imports {
let dep_path = base.join(&rel);
let dep = load_module_inner(&dep_path, visited)?;
for fun in dep.functions {
merge_top_level(&mut module.functions, fun);
}
}
Ok(module)
}
fn attach_path(path: &Path, err: anyhow::Error) -> anyhow::Error {
if let Some(d) = err.downcast_ref::<Diagnostic>() {
if d.path.is_none() {
return Diagnostic::at(path, d.span, d.message.clone()).into();
}
return err;
}
// Legacy `line:col: message` from parse bail!
let msg = err.to_string();
if let Some((loc, rest)) = msg.split_once(": ") {
if let Some((line_s, col_s)) = loc.split_once(':') {
if let (Ok(line), Ok(col)) = (line_s.parse::<u32>(), col_s.parse::<u32>()) {
return Diagnostic::at(path, crate::diagnostics::Span::new(line, col), rest).into();
}
}
}
err.context(format!("in {}", path.display()))
}
fn merge_top_level(into: &mut Vec<Function>, fun: Function) {
if let Some(existing) = into.iter_mut().find(|f| f.name == fun.name) {
*existing = fun;
} else {
into.push(fun);
}
}
-132
View File
@@ -1,132 +0,0 @@
use std::path::PathBuf;
use std::process::ExitCode;
use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use marqdo::view::{serve, ViewOptions};
use marqdo::{Backend, RunOptions};
#[derive(Parser, Debug)]
#[command(name = "marqdo", version, about = "Marqdo interpreter — run and view .mq.md programs")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Clone, Copy, Debug, ValueEnum)]
enum BackendCli {
Tree,
Bytecode,
}
impl From<BackendCli> for Backend {
fn from(b: BackendCli) -> Self {
match b {
BackendCli::Tree => Backend::Tree,
BackendCli::Bytecode => Backend::Bytecode,
}
}
}
#[derive(Subcommand, Debug)]
enum Commands {
/// Execute a Marqdo source file (defaults to ./index.mq.md)
Run {
#[arg(value_name = "FILE")]
file: Option<PathBuf>,
#[arg(long, value_enum, default_value_t = BackendCli::Tree)]
backend: BackendCli,
#[arg(long)]
dump_lines: bool,
#[arg(long)]
dump_tokens: bool,
#[arg(long)]
dump_ast: bool,
#[arg(long)]
dump_sema: bool,
#[arg(long)]
dump_bytecode: bool,
#[arg(long)]
trace_eval: bool,
#[arg(long)]
dump_all: bool,
},
/// Browse `.mq.md` structure + execution in a local webpage
View {
#[arg(value_name = "PATH")]
path: Option<PathBuf>,
#[arg(long, default_value = "127.0.0.1")]
host: String,
#[arg(long, default_value_t = 7429)]
port: u16,
#[arg(long)]
no_open: bool,
},
}
fn main() -> ExitCode {
match try_main() {
Ok(code) => ExitCode::from(code as u8),
Err(err) => {
eprintln!("error: {err:#}");
ExitCode::from(1)
}
}
}
fn try_main() -> Result<i32> {
let cli = Cli::parse();
match cli.command {
Commands::Run {
file,
backend,
dump_lines,
dump_tokens,
dump_ast,
dump_sema,
dump_bytecode,
trace_eval,
dump_all,
} => {
let path = file.unwrap_or_else(|| PathBuf::from("index.mq.md"));
let mut opts = if dump_all {
RunOptions::dump_all()
} else {
RunOptions {
dump_lines,
dump_tokens,
dump_ast,
dump_sema,
dump_bytecode,
trace_eval,
backend: backend.into(),
}
};
if dump_all {
opts.backend = backend.into();
}
marqdo::run_file(&path, &opts)?;
Ok(0)
}
Commands::View {
path,
host,
port,
no_open,
} => {
serve(ViewOptions {
path: path.unwrap_or_else(|| PathBuf::from(".")),
host,
port,
open_browser: !no_open,
})?;
Ok(0)
}
}
}
-492
View File
@@ -1,492 +0,0 @@
//! Expression parser (recursive descent over a single string).
use anyhow::{bail, Result};
use crate::ast::{BinaryOp, CallExpr, Expr, InterpPart, Literal, UnaryOp};
pub fn parse_expr(input: &str) -> Result<Expr> {
let mut p = Parser::new(input.trim());
let e = p.parse_or()?;
p.skip_ws();
if !p.rest().is_empty() {
bail!("trailing input in expression: {:?}", p.rest());
}
Ok(e)
}
/// Argument / template RHS: prefer a full expression; else interpolated text.
/// Hyphenated prose (`none-falsy`) is not parsed as subtraction.
pub fn parse_value_or_interp(input: &str) -> Result<Expr> {
let s = input.trim();
if s.is_empty() {
return Ok(Expr::Literal(Literal::Text(String::new())));
}
if has_hyphenated_prose(s) {
return Ok(parse_interp(s));
}
match parse_expr(s) {
Ok(e) => Ok(e),
Err(_) => Ok(parse_interp(s)),
}
}
fn has_hyphenated_prose(s: &str) -> bool {
let chars: Vec<char> = s.chars().collect();
for i in 1..chars.len().saturating_sub(1) {
if chars[i] != '-' {
continue;
}
let left = chars[i - 1];
let right = chars[i + 1];
if left.is_whitespace() || right.is_whitespace() || left == '`' || right == '`' {
continue;
}
// `none-falsy` / `Hello-World` — not `` `n` - 1 ``
if left.is_alphanumeric() || right.is_alphanumeric() || !left.is_ascii() || !right.is_ascii()
{
return true;
}
}
false
}
pub fn parse_interp(s: &str) -> Expr {
let mut parts = Vec::new();
let mut rest = s;
while !rest.is_empty() {
if let Some(start) = rest.find('`') {
if start > 0 {
parts.push(InterpPart::Lit(rest[..start].to_string()));
}
let after = &rest[start + 1..];
if let Some(end) = after.find('`') {
let name = after[..end].to_string();
parts.push(InterpPart::Var(name));
rest = &after[end + 1..];
} else {
parts.push(InterpPart::Lit(format!("`{after}")));
break;
}
} else {
parts.push(InterpPart::Lit(rest.to_string()));
break;
}
}
if parts.len() == 1 {
match &parts[0] {
InterpPart::Lit(t) => return Expr::Literal(Literal::Text(t.clone())),
InterpPart::Var(n) => return Expr::Var(n.clone()),
}
}
Expr::Interp(parts)
}
struct Parser<'a> {
src: &'a str,
i: usize,
}
impl<'a> Parser<'a> {
fn new(src: &'a str) -> Self {
Self { src, i: 0 }
}
fn rest(&self) -> &str {
&self.src[self.i..]
}
fn skip_ws(&mut self) {
while let Some(c) = self.peek_char() {
if c.is_whitespace() {
self.bump_char();
} else {
break;
}
}
}
fn peek_char(&self) -> Option<char> {
self.rest().chars().next()
}
fn bump_char(&mut self) -> Option<char> {
let mut chars = self.rest().chars();
let c = chars.next()?;
self.i += c.len_utf8();
Some(c)
}
fn starts_with(&self, s: &str) -> bool {
self.rest().starts_with(s)
}
fn eat(&mut self, s: &str) -> bool {
if self.starts_with(s) {
self.i += s.len();
true
} else {
false
}
}
fn parse_or(&mut self) -> Result<Expr> {
let mut left = self.parse_and()?;
loop {
self.skip_ws();
if self.eat("or") {
// ensure word boundary
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) {
self.i -= 2;
break;
}
let right = self.parse_and()?;
left = Expr::Binary {
op: BinaryOp::Or,
left: Box::new(left),
right: Box::new(right),
};
} else {
break;
}
}
Ok(left)
}
fn parse_and(&mut self) -> Result<Expr> {
let mut left = self.parse_cmp()?;
loop {
self.skip_ws();
if self.eat("and") {
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) {
self.i -= 3;
break;
}
let right = self.parse_cmp()?;
left = Expr::Binary {
op: BinaryOp::And,
left: Box::new(left),
right: Box::new(right),
};
} else {
break;
}
}
Ok(left)
}
fn parse_cmp(&mut self) -> Result<Expr> {
let mut left = self.parse_add()?;
self.skip_ws();
let op = if self.eat("==") {
Some(BinaryOp::Eq)
} else if self.eat("!=") {
Some(BinaryOp::Ne)
} else if self.eat("<=") {
Some(BinaryOp::Le)
} else if self.eat(">=") {
Some(BinaryOp::Ge)
} else if self.eat("<") {
Some(BinaryOp::Lt)
} else if self.eat(">") {
Some(BinaryOp::Gt)
} else {
None
};
if let Some(op) = op {
let right = self.parse_add()?;
left = Expr::Binary {
op,
left: Box::new(left),
right: Box::new(right),
};
}
Ok(left)
}
fn parse_add(&mut self) -> Result<Expr> {
let mut left = self.parse_mul()?;
loop {
self.skip_ws();
if self.eat("+") {
let right = self.parse_mul()?;
left = Expr::Binary {
op: BinaryOp::Add,
left: Box::new(left),
right: Box::new(right),
};
} else if self.eat("-") {
let right = self.parse_mul()?;
left = Expr::Binary {
op: BinaryOp::Sub,
left: Box::new(left),
right: Box::new(right),
};
} else {
break;
}
}
Ok(left)
}
fn parse_mul(&mut self) -> Result<Expr> {
let mut left = self.parse_unary()?;
loop {
self.skip_ws();
if self.eat("*") {
let right = self.parse_unary()?;
left = Expr::Binary {
op: BinaryOp::Mul,
left: Box::new(left),
right: Box::new(right),
};
} else if self.eat("/") {
let right = self.parse_unary()?;
left = Expr::Binary {
op: BinaryOp::Div,
left: Box::new(left),
right: Box::new(right),
};
} else {
break;
}
}
Ok(left)
}
fn parse_unary(&mut self) -> Result<Expr> {
self.skip_ws();
if self.eat("not") {
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false) {
self.i -= 3;
} else {
let expr = self.parse_unary()?;
return Ok(Expr::Unary {
op: UnaryOp::Not,
expr: Box::new(expr),
});
}
}
if self.eat("-") {
let expr = self.parse_unary()?;
return Ok(Expr::Unary {
op: UnaryOp::Neg,
expr: Box::new(expr),
});
}
self.parse_primary()
}
fn parse_primary(&mut self) -> Result<Expr> {
self.skip_ws();
if self.eat("(") {
let e = self.parse_or()?;
self.skip_ws();
if !self.eat(")") {
bail!("expected ')'");
}
return Ok(e);
}
if self.eat("`") {
let start = self.i;
while let Some(c) = self.peek_char() {
if c == '`' {
break;
}
self.bump_char();
}
let name = self.src[start..self.i].to_string();
if !self.eat("`") {
bail!("unterminated `name`");
}
return Ok(Expr::Var(name));
}
if self.eat(">") {
// Inline call: `> name k=v`
self.skip_ws();
return Ok(Expr::Call(parse_call_tail(self.rest()).map(|(c, consumed)| {
self.i += consumed;
c
})?));
}
if self.starts_with("True") && is_word_end(self.rest(), 4) {
self.i += 4;
return Ok(Expr::Literal(Literal::Bool(true)));
}
if self.starts_with("False") && is_word_end(self.rest(), 5) {
self.i += 5;
return Ok(Expr::Literal(Literal::Bool(false)));
}
if self.starts_with("None") && is_word_end(self.rest(), 4) {
self.i += 4;
return Ok(Expr::Literal(Literal::None));
}
if self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
let start = self.i;
while self.peek_char().map(|c| c.is_ascii_digit()).unwrap_or(false) {
self.bump_char();
}
let n: i64 = self.src[start..self.i].parse()?;
return Ok(Expr::Literal(Literal::Int(n)));
}
// Bare identifier / text word
if self.peek_char().map(|c| c.is_alphanumeric() || c == '_' || !c.is_ascii()).unwrap_or(false)
{
let start = self.i;
while let Some(c) = self.peek_char() {
if c.is_whitespace() || matches!(c, '=' | '+' | '-' | '*' | '/' | '<' | '>' | '(' | ')' | '`' | '|' | ',')
{
break;
}
self.bump_char();
}
let word = &self.src[start..self.i];
return Ok(Expr::Literal(Literal::Text(word.to_string())));
}
bail!("unexpected expression input: {:?}", self.rest());
}
}
fn is_word_end(s: &str, len: usize) -> bool {
match s[len..].chars().next() {
None => true,
Some(c) => !(c.is_alphanumeric() || c == '_'),
}
}
/// Parse `name key=val …` / positional args; returns call + bytes consumed.
pub fn parse_call_tail(s: &str) -> Result<(CallExpr, usize)> {
use crate::ast::Arg;
let s = s.trim_start();
let original_len = s.len();
let callee = {
let mut parts = s.split_whitespace();
parts
.next()
.ok_or_else(|| anyhow::anyhow!("missing callee"))?
.to_string()
};
let after_callee_offset = {
let idx = s.find(&callee).unwrap();
idx + callee.len()
};
let mut args_str = s[after_callee_offset..].trim_start();
let mut args = Vec::new();
let mut seen_named = false;
while !args_str.is_empty() {
if let Some((key, after_eq)) = try_named_arg(args_str) {
seen_named = true;
let val_end = find_next_arg_boundary(after_eq);
let val_raw = after_eq[..val_end].trim_end();
args.push(Arg::Named {
name: key,
value: parse_value_or_interp(val_raw)?,
});
args_str = after_eq[val_end..].trim_start();
} else {
if seen_named {
bail!("positional argument after named argument is not allowed");
}
let (tok, rest) = split_first_token(args_str);
if tok.is_empty() {
break;
}
args.push(Arg::Positional(parse_value_or_interp(tok)?));
args_str = rest.trim_start();
}
}
Ok((CallExpr { callee, args }, original_len))
}
/// If `s` begins with `ident=`, return (ident, rest_after_eq).
fn try_named_arg(s: &str) -> Option<(String, &str)> {
let s = s.trim_start();
for (i, c) in s.char_indices() {
if c == '=' {
if i == 0 {
return None;
}
let key = &s[..i];
if key.chars().any(|ch| ch.is_whitespace()) {
return None;
}
return Some((key.to_string(), &s[i + 1..]));
}
if c.is_whitespace() {
return None;
}
}
None
}
fn split_first_token(s: &str) -> (&str, &str) {
let s = s.trim_start();
if s.starts_with('`') {
// `` `name` `` as one token
if let Some(end) = s[1..].find('`') {
let end = end + 2; // include closing `
return (&s[..end], &s[end..]);
}
}
match s.find(char::is_whitespace) {
Some(i) => (&s[..i], &s[i..]),
None => (s, ""),
}
}
fn find_next_arg_boundary(after_eq: &str) -> usize {
// Look for ` <ident>=` pattern not inside backticks (UTF-8 safe).
let mut in_bt = false;
for (i, c) in after_eq.char_indices() {
if c == '`' {
in_bt = !in_bt;
continue;
}
if !in_bt && c.is_whitespace() {
let rest = &after_eq[i..];
let trimmed = rest.trim_start();
let skipped = rest.len() - trimmed.len();
if let Some(eq_at) = trimmed.find('=') {
let key = &trimmed[..eq_at];
if !key.is_empty()
&& !key.contains(char::is_whitespace)
&& key
.chars()
.all(|ch| ch.is_alphanumeric() || ch == '_' || !ch.is_ascii())
{
return i + skipped;
}
}
}
}
after_eq.len()
}
/// Parse `> callee args` call expression/statement text (without leading `>`).
pub fn parse_call_after_gt(after_gt: &str) -> Result<CallExpr> {
let (call, _) = parse_call_tail(after_gt.trim())?;
Ok(call)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cmp_and_arith() {
let e = parse_expr("`x` > 0").unwrap();
assert!(matches!(e, Expr::Binary { op: BinaryOp::Gt, .. }));
let e = parse_expr("`n` + 1").unwrap();
assert!(matches!(e, Expr::Binary { op: BinaryOp::Add, .. }));
}
#[test]
fn interp_hello() {
let e = parse_value_or_interp("Hello `谁`!").unwrap();
assert!(matches!(e, Expr::Interp(_)));
}
}
-554
View File
@@ -1,554 +0,0 @@
//! Line-oriented recursive descent → AST (no Bison).
mod expr;
pub use expr::{parse_call_after_gt, parse_expr, parse_value_or_interp};
use anyhow::{bail, Result};
use crate::ast::{
BranchArm, Expr, Function, Literal, Module, Stmt,
};
use crate::diagnostics::{Diagnostic, Span};
use crate::lex::{classify_source, ClassifiedLine, LineKind};
use crate::parse::expr::parse_call_after_gt as call_after_gt;
use crate::parse::expr::parse_expr as parse_expr_str;
/// Parse full source (with optional frontmatter) into a module AST.
pub fn parse_source(source: &str) -> Result<Module> {
let lines = classify_source(source);
parse_classified(&lines)
}
pub fn parse_classified(lines: &[ClassifiedLine]) -> Result<Module> {
let mut cur = Cursor::new(lines);
let imports = cur.parse_frontmatter()?;
let mut functions = Vec::new();
while cur.skip_noise() {
let Some(line) = cur.peek() else { break };
let trimmed = line.text.trim();
if is_heading(trimmed) {
functions.push(cur.parse_function(1)?);
} else {
bail!(
"{}:1: expected function heading `# …`, got: {trimmed}",
line.line_no
);
}
}
Ok(Module { imports, functions })
}
struct Cursor<'a> {
lines: &'a [ClassifiedLine],
i: usize,
}
impl<'a> Cursor<'a> {
fn new(lines: &'a [ClassifiedLine]) -> Self {
Self { lines, i: 0 }
}
fn peek(&self) -> Option<&'a ClassifiedLine> {
self.lines.get(self.i)
}
fn bump(&mut self) -> Option<&'a ClassifiedLine> {
let l = self.lines.get(self.i)?;
self.i += 1;
Some(l)
}
/// Skip blank + comment; return true if a line remains.
fn skip_noise(&mut self) -> bool {
while let Some(l) = self.peek() {
match l.kind {
LineKind::Blank | LineKind::Comment => {
self.i += 1;
}
LineKind::Code => return true,
}
}
false
}
fn parse_frontmatter(&mut self) -> Result<Vec<String>> {
let mut imports = Vec::new();
if !self.skip_noise() {
return Ok(imports);
}
let Some(first) = self.peek() else {
return Ok(imports);
};
if first.text.trim() != "---" {
return Ok(imports);
}
self.bump();
while let Some(line) = self.peek() {
let t = line.text.trim();
if t == "---" {
self.bump();
break;
}
if t.starts_with('>') {
let path = t[1..].trim();
if path.ends_with(".mq.md") {
imports.push(path.to_string());
}
}
self.bump();
}
Ok(imports)
}
fn parse_function(&mut self, min_level: u8) -> Result<Function> {
let line = self.bump().unwrap();
let (level, name) = parse_heading(line.text.trim())
.ok_or_else(|| anyhow::anyhow!("{}:1: expected heading", line.line_no))?;
if level < min_level {
bail!("{}:1: heading level {level} < expected {min_level}", line.line_no);
}
let mut fun = Function {
name: name.to_string(),
level,
span: Span {
line: line.line_no,
col: 1,
},
params: Vec::new(),
body: Vec::new(),
children: Vec::new(),
};
// Parameter zone: indented `- name` pure identifiers.
while self.skip_noise() {
let Some(l) = self.peek() else { break };
let trimmed = l.text.trim();
if is_heading(trimmed) {
let (nl, _) = parse_heading(trimmed).unwrap();
if nl > level {
fun.children.push(self.parse_function(level + 1)?);
continue;
}
break;
}
if let Some(param) = parse_param_line(trimmed) {
// Only accept as param before any body stmt (params first).
if fun.body.is_empty() {
fun.params.push(param);
self.bump();
continue;
}
}
break;
}
// Body until next heading at level <= ours.
while self.skip_noise() {
let Some(l) = self.peek() else { break };
let trimmed = l.text.trim();
if is_frame(trimmed) {
self.bump();
continue;
}
if is_heading(trimmed) {
let (nl, _) = parse_heading(trimmed).unwrap();
if nl > level {
fun.children.push(self.parse_function(level + 1)?);
continue;
}
break;
}
// Nested params mid-body shouldn't happen; treat `-` as control flow.
if trimmed.starts_with('+') || is_ordered_branch(trimmed) {
fun.body.push(self.parse_branch()?);
continue;
}
if trimmed.starts_with('-') {
fun.body.push(self.parse_loop_or_err()?);
continue;
}
fun.body.push(self.parse_simple_stmt()?);
}
Ok(fun)
}
fn parse_simple_stmt(&mut self) -> Result<Stmt> {
let line = self.bump().unwrap();
let span = Span {
line: line.line_no,
col: 1,
};
let trimmed = line.text.trim();
if is_frame(trimmed) {
bail!("{span}: unexpected frame line as statement");
}
// Bold return **…**
if trimmed.starts_with("**") && trimmed.ends_with("**") && trimmed.len() >= 4 {
let inner = &trimmed[2..trimmed.len() - 2];
let value = parse_expr_str(inner)?;
return Ok(Stmt::Return { value, span });
}
// Italic statement *…*
if trimmed.starts_with('*') && trimmed.ends_with('*') && !trimmed.starts_with("**") {
let inner = &trimmed[1..trimmed.len() - 1];
return parse_assign_or_expr_stmt(inner, span);
}
// Call >
if trimmed.starts_with('>') {
let call = call_after_gt(trimmed[1..].trim())?;
return Ok(Stmt::Call { call, span });
}
// Bare assign `` `x` = … `` possibly followed by table
if trimmed.starts_with('`') {
if let Some(stmt) = self.parse_backtick_assign(trimmed, span.clone())? {
return Ok(stmt);
}
}
Err(Diagnostic::new(None, span, format!("unrecognized statement: {trimmed}")).into())
}
fn parse_backtick_assign(&mut self, trimmed: &str, span: Span) -> Result<Option<Stmt>> {
// `name` = [rhs]
let Some(rest) = trimmed.strip_prefix('`') else {
return Ok(None);
};
let Some(end) = rest.find('`') else {
return Ok(None);
};
let name = rest[..end].to_string();
let after = rest[end + 1..].trim_start();
if !after.starts_with('=') {
return Ok(None);
}
let rhs = after[1..].trim();
if rhs.is_empty() {
// Consume following table if present.
let list = self.consume_table()?;
return Ok(Some(Stmt::Assign {
name,
value: Expr::List(list.into_iter().map(Expr::Literal).collect()),
span,
}));
}
Ok(Some(Stmt::Assign {
name,
value: parse_value_or_interp(rhs)?,
span,
}))
}
fn consume_table(&mut self) -> Result<Vec<Literal>> {
self.skip_noise();
let mut rows = Vec::new();
let mut header_done = false;
let mut sep_done = false;
while let Some(l) = self.peek() {
if l.kind != LineKind::Code {
break;
}
let t = l.text.trim();
if !t.starts_with('|') {
break;
}
self.bump();
let cells = split_table_row(t);
if !header_done {
header_done = true;
continue;
}
if !sep_done && cells.iter().all(|c| c.chars().all(|ch| ch == '-' || ch == ':' || ch.is_whitespace() || ch == '|'))
{
// separator row like |----|
sep_done = true;
continue;
}
// data row — single column examples: take first cell
if let Some(cell) = cells.first() {
rows.push(Literal::Text(cell.clone()));
}
sep_done = true;
}
if !header_done {
bail!("expected GFM table after empty assignment");
}
Ok(rows)
}
fn parse_branch(&mut self) -> Result<Stmt> {
let first = self.peek().unwrap();
let span = Span {
line: first.line_no,
col: 1,
};
let base_indent = indent_of(&first.text);
let mut arms = Vec::new();
while self.skip_noise() {
let Some(l) = self.peek() else { break };
let ind = indent_of(&l.text);
if ind < base_indent {
break;
}
let trimmed = l.text.trim();
let cond_src = if let Some(rest) = trimmed.strip_prefix('+') {
rest.trim()
} else if let Some(rest) = strip_ordered(trimmed) {
rest
} else {
break;
};
if ind != base_indent {
break;
}
self.bump();
let condition = if cond_src == "*" || cond_src.is_empty() {
None
} else {
Some(parse_expr_str(cond_src)?)
};
let body = self.parse_indented_body(base_indent)?;
arms.push(BranchArm { condition, body });
}
if arms.is_empty() {
bail!("{span}: empty branch");
}
Ok(Stmt::Branch { arms, span })
}
fn parse_loop_or_err(&mut self) -> Result<Stmt> {
let line = self.bump().unwrap();
let span = Span {
line: line.line_no,
col: 1,
};
let base_indent = indent_of(&line.text);
let trimmed = line.text.trim();
let rest = trimmed.strip_prefix('-').unwrap().trim();
// foreach: [item](collection)
if let Some((item, coll)) = parse_foreach_header(rest) {
let body = self.parse_indented_body(base_indent)?;
return Ok(Stmt::ForEach {
item,
collection: coll,
body,
span,
});
}
// while: expression
let condition = parse_expr_str(rest)?;
let body = self.parse_indented_body(base_indent)?;
Ok(Stmt::While {
condition,
body,
span,
})
}
fn parse_indented_body(&mut self, parent_indent: usize) -> Result<Vec<Stmt>> {
let mut body = Vec::new();
while self.skip_noise() {
let Some(l) = self.peek() else { break };
let ind = indent_of(&l.text);
if ind <= parent_indent {
// Same-indent `+`/`-` ends body (next arm / sibling).
break;
}
let trimmed = l.text.trim();
if is_frame(trimmed) {
self.bump();
continue;
}
if is_heading(trimmed) {
break;
}
if trimmed.starts_with('+') || is_ordered_branch(trimmed) {
// Nested branch inside body
body.push(self.parse_branch()?);
continue;
}
if trimmed.starts_with('-') {
body.push(self.parse_loop_or_err()?);
continue;
}
body.push(self.parse_simple_stmt()?);
}
Ok(body)
}
}
fn parse_assign_or_expr_stmt(inner: &str, span: Span) -> Result<Stmt> {
let inner = inner.trim();
// `` `name` = … ``
if let Some(rest) = inner.strip_prefix('`') {
if let Some(end) = rest.find('`') {
let name = rest[..end].to_string();
let after = rest[end + 1..].trim_start();
if let Some(rhs) = after.strip_prefix('=') {
let rhs = rhs.trim();
// Inline call assign: `> fn …`
let value = if rhs.starts_with('>') {
Expr::Call(call_after_gt(rhs[1..].trim())?)
} else {
parse_value_or_interp(rhs)?
};
return Ok(Stmt::Assign {
name,
value,
span,
});
}
}
}
bail!("{span}: italic statement must be an assignment (`name` = …)")
}
fn parse_param_line(trimmed: &str) -> Option<String> {
let rest = trimmed.strip_prefix('-')?.trim();
if rest.is_empty() || rest.contains('`') || rest.contains('[') || rest.contains('=') {
return None;
}
if rest.split_whitespace().count() != 1 {
return None;
}
// Reject if looks like comparison / operator expr
if rest.contains('>') || rest.contains('<') || rest.contains('+') || rest.contains('*') {
return None;
}
Some(rest.to_string())
}
fn parse_foreach_header(rest: &str) -> Option<(String, String)> {
// [item](collection)
let rest = rest.trim();
if !rest.starts_with('[') {
return None;
}
let end_item = rest.find(']')?;
let item = rest[1..end_item].to_string();
let after = rest[end_item + 1..].trim_start();
if !after.starts_with('(') || !after.ends_with(')') {
return None;
}
let coll = after[1..after.len() - 1].to_string();
Some((item, coll))
}
fn parse_heading(trimmed: &str) -> Option<(u8, &str)> {
if !trimmed.starts_with('#') {
return None;
}
let mut level = 0u8;
for c in trimmed.chars() {
if c == '#' {
level = level.saturating_add(1);
} else {
break;
}
}
if level == 0 || level > 6 {
return None;
}
let name = trimmed[level as usize..].trim();
if name.is_empty() {
return None;
}
Some((level, name))
}
fn is_heading(trimmed: &str) -> bool {
parse_heading(trimmed).is_some()
}
fn is_frame(trimmed: &str) -> bool {
if trimmed.len() < 3 {
return false;
}
trimmed.chars().all(|c| c == '-') || trimmed.chars().all(|c| c == '*')
}
fn is_ordered_branch(trimmed: &str) -> bool {
strip_ordered(trimmed).is_some()
}
fn strip_ordered(trimmed: &str) -> Option<&str> {
let mut chars = trimmed.chars();
let mut saw_digit = false;
while let Some(c) = chars.next() {
if c.is_ascii_digit() {
saw_digit = true;
continue;
}
if c == '.' && saw_digit {
return Some(chars.as_str().trim_start());
}
return None;
}
None
}
fn indent_of(text: &str) -> usize {
text.chars()
.take_while(|c| *c == ' ' || *c == '\t')
.map(|c| if c == '\t' { 4 } else { 1 })
.sum()
}
fn split_table_row(line: &str) -> Vec<String> {
let t = line.trim();
let t = t.strip_prefix('|').unwrap_or(t);
let t = t.strip_suffix('|').unwrap_or(t);
t.split('|').map(|c| c.trim().to_string()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::Stmt;
#[test]
fn parse_hello() {
let src = include_str!("../../examples/structure/hello.mq.md");
let m = parse_source(src).unwrap();
assert_eq!(m.functions.len(), 1);
assert_eq!(m.functions[0].name, "Hello World");
assert_eq!(m.functions[0].body.len(), 1);
assert!(matches!(m.functions[0].body[0], Stmt::Call { .. }));
}
#[test]
fn parse_index() {
let src = include_str!("../../examples/structure/nested-call.mq.md");
let m = parse_source(src).unwrap();
assert!(m.imports.is_empty());
let main = m.functions.iter().find(|f| f.name == "main").unwrap();
assert_eq!(main.children.len(), 1);
assert_eq!(main.children[0].name, "问候");
assert_eq!(main.children[0].params, vec!["谁".to_string()]);
}
#[test]
fn parse_branch() {
let src = include_str!("../../examples/structure/branch.mq.md");
let m = parse_source(src).unwrap();
let main = &m.functions[0];
assert!(main.body.iter().any(|s| matches!(s, Stmt::Branch { .. })));
}
}
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff. Show more