Compare commits

...
230 Commits
Author SHA1 Message Date
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
943 changed files with 132589 additions and 993 deletions

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
---
name: marqdo-dev
description: >-
Develop Marqdo programs and libraries the readable way: GFM tables as data,
code-as-documentation, table.put over json.set chains, lib/ext authoring.
Use when writing or refactoring .mq.md, creating lib/* or ext/*, reviewing
Marqdo style, fixing unreadable json glue, or when the user asks how to
develop Marqdo / 如何开发 marqdo.
---
# Marqdo development (author + library)
Read this **before** writing or expanding `.mq.md`. Syntax basics stay in [marqdo](../marqdo/SKILL.md); this skill is the **style and library craft** contract.
## Non-negotiable: code is documentation
A `.mq.md` file must stay readable as Markdown. If a human cannot skim the data and intent without decoding nested `json.set` / `json.append` chains, the code is wrong.
| Prefer | Avoid |
|--------|--------|
| GFM tables for maps, lists, records, wire, commands | Building the same with `json.set` / `json.append` |
| Named library helpers (`web.*`, `browser.*`, `table.*`) | Copy-paste effect-map glue in every handler |
| `table.put` for **one** dynamic key | Long `json.set` pipelines |
| `json.parse` / `json.stringify` / `json.quote` only | Using `json` as a general dict builder |
`lib/json` is for **parse / stringify / quote**. Collection edits use **GFM tables** and **`lib/table`** (`doc/design/stdlib-table.md`).
## How to shape data
### 1. GFM table geometry (memorize)
| Shape | Result |
|-------|--------|
| 1 column | list |
| ≥2 columns, **one** data row | map (headers = keys) |
| ≥2 columns, **many** rows | map of lists (column-oriented) |
| First header `@` / `行` / `row` | **list of maps** (row records) |
Cells are expressions (`doc/design/table-cell-expressions.md`): bare words = text, `` `var` `` = variable, quote paths/`/` ratios.
### 2. Good patterns
**Wire / steps / commands** — `@` record table:
```markdown
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
```
**Multi-key return / boot** — map table with variable cells:
```markdown
`boot` =
| wire | set_text |
|------|----------|
| `wire` | `set_text` |
```
**Single dynamic key** — one `table.put` (or a helper), not a json chain:
```markdown
**`set_text` = table.put in=None at="#log" value=msg**
**table.put in=None at="set_text" value=set_text**
```
Better still — call a named helper:
```markdown
**browser.set_text sel="#log" text=msg**
```
### 3. Bad pattern (do not write)
```markdown
**`ret` = json.set map=None key="set_text" value=…**
**`ret` = json.set map=ret key="canvas" value=…**
**`cmds` = json.append list=cmds item=c0**
```
## Writing application `.mq.md`
1. Frontmatter: title + imports (`table`, domain libs). **Do not import `json` unless parsing strings.**
2. `# main`: state binds, then **tables** for wire/config, return boot map via table or helper.
3. `##` handlers: short prose OK; data as tables; return via `browser.*` / `web.*` / one `table.put`.
4. Blank line between comment paragraphs and code.
5. Run `marqdo run path.mq.md` from repo root.
6. **Calls in narrative:** prefer `**结果 = 某函数 名=`x`**` (no `>` on the RHS). Bracket form `礼貌 [问候] "x"` / `**出 = [put] …**` is fine when modifiers help. Use `> …` for standalone step lists. See `examples/code-as-docs/`.
7. **Do not use `##` inside `# main` for document sectioning** — those become nested functions. Use paragraphs / `---` breaks instead.
8. **Index:** prefer `[键](集合)` / `` [`名`](集合) `` over footnote `` m[^k] ``.
Browser client programs: prefer `import browser:lib/browser.mq.md` (no native plugin). Server sites: `ext/web` + GFM page/style tables.
## Developing libraries (`lib/*`, `ext/*`)
Canonical thin-template + waves: [lib-code-as-docs.md](../../doc/design/lib-code-as-docs.md) · [roadmap/lib-ext-code-as-docs.md](../../doc/roadmap/lib-ext-code-as-docs.md).
### Goals
- **Authors** see tables and short calls; **library** may hide `table.put` / host calls.
- One concern per helper; name the effect (`set_text`, `canvas`, …), do not expose bag surgery.
- EN + ZH pair when shipping user-facing libs (`lib/browser.mq.md` ↔ `lib/浏览器.mq.md`, `ext/web` ↔ `ext/web/网页.mq.md`).
- `ext/**` never calls `host_*` — use plugins / public lib only (`doc/design/ext-agent.md`).
- Collection get: **`[key](coll)`** (no new footnote indexes). Calls in examples may use `修饰 [fn] …` or classic `>` / bold.
### Library checklist
- [ ] Purpose sentence + prose params + one example + short body
- [ ] Public examples use **tables + helpers**, not json glue
- [ ] Index with `[k](c)`; foreach `- [item](coll)`
- [ ] Helpers documented with a one-line purpose above `##`
- [ ] Defaults on params; omit `None` fields in merged maps
- [ ] No `json.set` chains in new code — use `table.put` / `table.merge` / GFM
- [ ] `marqdo run` on a tiny demo under `examples/` or inline smoke
### Where helpers live
| Need | Place |
|------|--------|
| Browser effect maps (WASM client) | `lib/browser.mq.md` |
| Site HTML / HTTP / DB | `ext/web` classes + compose from tables |
| List/map primitives | `lib/table.mq.md` |
| Parse JSON text | `lib/json.mq.md` only |
## Refactoring existing glue
When editing a file full of `json.set`:
1. Turn static structures into GFM tables.
2. Replace repeated effect shapes with `browser.*` / `web.text_patch` / `web.dom_patch`.
3. Leave at most sparse `table.put` for dynamic keys.
4. Drop `import json:…` if unused.
## Anti-patterns
| Wrong | Right |
|-------|-------|
| `json.set` × N to build boot | GFM map table or `browser`/`web` helper |
| `json.append` to build command list | `@` record table |
| Dummy column to force a 1-key map | `table.put` or helper |
| Importing `ext/web` only for `text_patch` in WASM | `lib/browser` (no native plugin) |
| Unreadable nested maps as “clever” | Flatten into tables humans can read |
## Related
- Syntax: [marqdo/SKILL.md](../marqdo/SKILL.md) · [examples.md](../marqdo/examples.md)
- Tables: `doc/design/stdlib-table.md` · `doc/design/table-cell-expressions.md`
- Browser effects: `doc/roadmap/browser-wasm-e.md` · `doc/roadmap/browser-wasm-f.md`
- Release: [marqdo-release](../marqdo-release/SKILL.md)
+184
View File
@@ -0,0 +1,184 @@
---
name: marqdo-release
description: >-
Run a full Marqdo product release: detect latest version and ask the user for
the next tag, update CHANGELOG/README/skills/public docs, bump Cargo versions,
sync VS Code extension on branch vscode-extension when needed, build or
trigger install assets (Windows CLI + **required Linux native/CLI zips**,
stdlib, ext, public zip, VSIX), push via origin or
https://proxy.cflmy.top/github.com/cflmy/marqdo.git, publish GitHub Release
with detailed notes, and recover from network failures via that proxy or HK
SSH jump (scripts/push-via-hk-jump.py). Use when the user asks to release,
cut a version, publish vX.Y.Z, ship a GitHub release, 发版, 发布新版本, or tag
marqdo.
---
# Marqdo release
Canonical release playbook for **cflmy/marqdo**. Read this skill **before** tagging or uploading assets. Details: [reference.md](reference.md).
## Hard rules
1. **Never invent the next version.** Detect current versions → **stop and ask the user** for the next SemVer (`X.Y.Z`). Do not proceed until they confirm.
2. **Never force-push** `main` / tags. **Never** `--no-verify` unless the user explicitly orders it.
3. **Never commit `vscode-extension/` on `main`** (gitignored). Extension source lives only on branch **`vscode-extension`**. See `doc/design/vscode-extension-commit.md`.
4. **Do not release from a dirty tree** (except intentional release commits you create in this flow).
5. **Tag format** is always `vX.Y.Z` matching root `Cargo.toml` `version = "X.Y.Z"`.
6. Prefer **tag push → GitHub Actions** (`.github/workflows/release.yml`) for **both** Windows and **Linux** install assets. Local packaging is fallback / verification.
7. After network errors: apply [reference.md § Proxy](reference.md). **First try** `https://proxy.cflmy.top/github.com/cflmy/marqdo.git` (this clone’s usual `origin`). Retry; do not silently skip uploads. If the reverse-proxy still drops long pushes, use **HK jump** (`hk.cflmy.de`) via `scripts/push-via-hk-jump.py` — see reference § **Proxy** / **HK SSH jump**.
8. **Do not ship a GitHub Release without the Linux extension/native zip.** Job `linux` must attach `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` (and the Linux CLI bundle). Missing Linux packages = release incomplete.
## Defaults (after version is confirmed)
Unless the user overrides, apply these automatically — **do not re-ask**:
| Setting | Default |
|---------|---------|
| Sync / bump `vscode-extension` to same `VER` | **yes** |
| Push `main`, create annotated tag, push tag immediately (trigger CI) | **yes** |
| Release notes language | **中英双语** (Chinese first, then English section, or paired ZH/EN under each heading) |
| Skip VSIX | **no** |
| Docs-only release | **no** (full asset pipeline via CI) |
| Deploy gh-pages after release | **no** (only if user asks) |
Phase 0 asks **only** for the next version (and optional overrides). Example ask:
> 当前最新是 **vA.B.C**。请指定下一个版本号(如 `0.3.2`)。其余按默认:同步扩展、立刻打 tag 发布、中英双语说明。
## Phase 0 — Detect versions (mandatory stop)
Run in repo root (parallel OK):
```bash
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
# or: rg / git tag / gh release list — see reference.md
```
Report briefly, then **ask only for the next SemVer** (defaults above). Wait for confirmation. Normalize to `VER=X.Y.Z` and `TAG=vX.Y.Z`.
## Phase 1 — Preflight
Copy and track:
```
Release progress:
- [ ] Phase 0: version confirmed by user (TAG=…)
- [ ] Phase 1: preflight green
- [ ] Phase 2: docs + version bumps committed
- [ ] Phase 3: extension branch (if needed)
- [ ] Phase 4: main pushed; tag created & pushed
- [ ] Phase 5: CI / assets / release notes verified
- [ ] Phase 6: post-release checks
```
Checks:
1. `git status` clean or only release WIP you control.
2. `git checkout main && git pull --ff-only origin main`.
3. Quick gate: `cargo test --test gold structure_hello` (and any release-critical tests the user named). Full gold suite if time allows.
4. `CHANGELOG.md` has meaningful **Unreleased** notes; if empty, draft from `git log vLAST..HEAD --oneline` and confirm with user.
5. Confirm no secrets in the commit (`*.env`, credentials).
## Phase 2 — Docs & version bumps (main)
Bump **in lockstep**:
| File | Change |
|------|--------|
| `Cargo.toml` | `version = "VER"` |
| `crates/marqdo-wasm/Cargo.toml` | same `VER` |
| `CHANGELOG.md` | Move `## Unreleased` → `## vVER — YYYY-MM-DD`; leave fresh empty `## Unreleased` |
| `README.md` | 「现状 / 如何使用最新」version strings, checkout tag, release URL |
| `.cursor/skills/marqdo/SKILL.md` | Version-sensitive bullets if any (WASM/web status); keep rules accurate |
| `public/**` | User-facing tutorials if features shipped (welcome, features/*, extensions). Prefer small factual updates over rewrites |
| `doc/roadmap/*.md` | Mark shipped waves done if this release closes them |
| `.github/workflows/release.yml` | Update **Highlights** body template to this release (CI still uses hardcoded blurb—keep in sync) |
Public HTML: regenerate before packaging / pages deploy:
```bash
./scripts/build-public.sh
# outputs under public/ (gitignored HTML); used by release zip / gh-pages
```
Commit on `main` (HEREDOC message), e.g.:
```text
release: vVER — <one-line highlight>
EOF
```
Push `main` (this repo’s `origin` is usually the reverse proxy):
```bash
# origin typically: https://proxy.cflmy.top/github.com/cflmy/marqdo.git
git push origin main
# one-shot if origin still points at github.com:
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git HEAD:main
```
If that times out: [reference § HK SSH jump](reference.md).
## Phase 3 — VS Code / Cursor extension
**Default: always** bump extension to `VER` on branch `vscode-extension` (skip only if user said so).
1. `git fetch origin vscode-extension`
2. Work on `vscode-extension` branch (not main):
- Bump `vscode-extension/package.json` `version` to `VER`.
- Update `engines` / CLI version hints in extension README if present.
- `npm ci && npm run compile`
3. Commit & `git push origin vscode-extension`.
4. Return to `main`. **Do not** add `vscode-extension/` to main.
## Phase 4 — Tag & trigger CI
```bash
git tag -a "TAG" -m "TAG"
git push origin "TAG"
```
This runs `.github/workflows/release.yml`:
- **windows** — CLI exe/zip, stdlib zip, ext zip, source zip, public zip, VSIX, Windows native zip
- **linux** (`needs: windows`) — **required** Linux native plugins zip + Linux CLI bundle (`ext/` + `native/*.so`)
If tag push fails: [reference.md § Proxy](reference.md) (`proxy.cflmy.top` first), retry once; then HK jump.
## Phase 5 — Release notes & assets
1. Wait for Actions success: `gh run list --workflow=Release --limit 3` / open the run URL. **Both** `windows` and `linux` jobs must be green.
2. Ensure GitHub Release for `TAG` exists with assets (workflow uses `softprops/action-gh-release`).
3. Confirm Linux assets exist: `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` and `marqdo-VER-x86_64-unknown-linux-gnu.zip`. If missing, do **not** call the release done — re-run / upload.
4. **Rewrite release body** (workflow body is a stub) with **中英双语** — see [reference.md § Notes template](reference.md). `gh release edit TAG --notes-file …`.
4. Include: Highlights, Breaking, Install (`ext add`, plugins build), Downloads table, WASM (`marqdo wasm build`), links to CHANGELOG/README, extension branch note.
5. Optional Linux local extras (not required if CI green): `marqdo wasm build` smoke; document in notes that wasm is built from source via CLI.
Local Windows fallback: `scripts/release-full.ps1 -Tag TAG -Upload` (see script header).
## Phase 6 — Post-release
1. `gh release view TAG` — confirm assets + notes.
2. `git status` clean; `main` synced.
3. Tell user: release URL `https://github.com/cflmy/marqdo/releases/tag/TAG`.
4. Optional: `./scripts/deploy-public.ps1` / pages workflow if user wants user-site refresh.
5. Open fresh `## Unreleased` already done in Phase 2.
## Failure matrix (short)
| Failure | Action |
|---------|--------|
| `gh` / git TLS or Clash `7890` refused | Unset bad proxy; `required_permissions: ["all"]`; see [reference § Proxy](reference.md) |
| GitHub blocked | **`origin` via proxy.cflmy.top** (see below), then HK jump |
| Tag exists | Stop; ask user to bump or delete tag (no force on shared tags without explicit order) |
| CI red | Fix on main, move tag only if user explicitly allows delete+re-push tag |
| VSIX missing | Fetch `vscode-extension`, build locally, `gh release upload TAG dist/*.vsix` |
| Linux native/CLI zip missing | Incomplete release — fix `linux` job or `gh release upload`; do not skip |
## Do not
- Ship without user-confirmed version.
- Hardcode release highlights only in Actions YAML and forget CHANGELOG.
- Commit `target/`, `dist/`, `*.wasm`, or `public/**/*.html` unless project policy changes.
- Merge extension tree into `main`.
+379
View File
@@ -0,0 +1,379 @@
# Marqdo release — reference
Companion to [SKILL.md](SKILL.md). Use during a release; keep SKILL short.
## Detect versions (commands)
```bash
# From repo root
python3 .cursor/skills/marqdo-release/scripts/detect_version.py
# or manually:
git fetch --tags origin 2>/dev/null || true
echo "Cargo: $(sed -n 's/^version = \"\(.*\)\"/\1/p' Cargo.toml | head -1)"
echo "wasm: $(sed -n 's/^version = \"\(.*\)\"/\1/p' crates/marqdo-wasm/Cargo.toml | head -1)"
echo "tags: $(git tag -l 'v*' --sort=-v:refname | head -3 | tr '\n' ' ')"
gh release list --limit 3 2>/dev/null || true
```
**SemVer guidance for the ask (do not choose for the user):**
| Kind | When |
|------|------|
| patch `x.y.(z+1)` | Fixes, docs, no public API / MQ surface break |
| minor `x.(y+1).0` | New features (WASM route C, new ext APIs) backward compatible |
| major `(x+1).0.0` | Breaking MQ / CLI / plugin ABI |
## Asset matrix (CI tag `v*`)
Produced by `.github/workflows/release.yml` on **windows-latest** (`windows` job) and **ubuntu-latest** (`linux` job, **required**, `needs: windows`):
| Asset | Role | Job |
|-------|------|-----|
| `marqdo-VER-x86_64-pc-windows-msvc.exe` | CLI (stdlib embedded) | windows |
| `marqdo-VER-x86_64-pc-windows-msvc.zip` | `marqdo.exe` + `lib/` + `ext/` + native DLL | windows |
| `marqdo-VER-stdlib.zip` | `lib/` only | windows |
| `marqdo-VER-ext.zip` | Official `ext/` L1 | windows |
| `marqdo-VER-native-x86_64-pc-windows-msvc.zip` | Prebuilt Windows plugins (`native/*.dll`) | windows |
| `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` | Prebuilt Linux plugins (`native/lib*.so`) — **must ship** | linux |
| `marqdo-VER-x86_64-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + native `.so` — **must ship** | linux |
| `marqdo-VER-source.zip` | `git archive` of tagged commit | windows |
| `marqdo-VER.vsix` | VS Code / Cursor (from branch `vscode-extension`) | windows |
| `marqdo-VER-public.zip` | Static user docs (`marqdo view output public`) | windows |
Not CI-uploaded (document in notes): macOS build from source; WASM via `marqdo wasm build` → `dist/wasm/`.
A release **without** the Linux native zip is incomplete (`marqdo ext add` on Linux cannot download prebuilts).
## Doc sync checklist (Phase 2 detail)
### CHANGELOG.md
1. Ensure `## Unreleased` lists everything shipping.
2. Rename to `## vVER — YYYY-MM-DD` (use release day in Asia/Shanghai unless user says otherwise).
3. Add a short **Highlights** subsection (install snippet + 3–6 bullets).
4. Insert empty:
```markdown
## Unreleased
### Added
### Fixed
### Changed
```
### README.md
Update every user-visible version pin, typically:
- Section title `## 现状(vVER)`
- `### 如何使用最新 Marqdo(vVER)`
- `git checkout vVER`
- Release URL `…/releases/tag/vVER`
Keep install / `ext add` / plugin build instructions accurate for this release.
### `.cursor/skills/marqdo/SKILL.md`
- Sync hard rules / feature bullets that this release changes (e.g. WASM, web).
- Do **not** dump full CHANGELOG into the skill.
- If release-only process changed, point to `.cursor/skills/marqdo-release/`.
### `public/` (author Markdown sources)
User tutorials under `public/` (not generated HTML). Update when:
- New CLI (`marqdo wasm …`, `ext add`, `version`)
- New tutorials (browser hello, web client embed)
- Version badges / “requires vVER” lines
Then regenerate HTML for zip/pages:
```bash
./scripts/build-public.sh
# Windows: powershell -File ./scripts/build-public.ps1
```
HTML under `public/**/*.html` is typically gitignored — zip still ships from CI `marqdo view output public`.
### Workflow stub
Edit `.github/workflows/release.yml` `body:` **Highlights** so the first auto body matches this tag (agent still replaces with full notes via `gh release edit`).
### Roadmaps / ADRs
If this release closes a wave: set status Completed in `doc/roadmap/*`; leave ADRs immutable (link from CHANGELOG).
## Extension checklist (Phase 3 detail)
Branch policy: `doc/design/vscode-extension-commit.md`.
```bash
git fetch origin vscode-extension
git checkout vscode-extension
# edit vscode-extension/package.json version → VER
# npm ci && npm run compile
git add vscode-extension/
git commit -m "$(cat <<'EOF'
vscode-extension: bump to VER for release
EOF
)"
git push origin vscode-extension
git checkout main
```
Local VSIX only (fallback):
```bash
git fetch origin vscode-extension
git checkout origin/vscode-extension -- vscode-extension
(cd vscode-extension && npm ci && npm run compile && npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-VER.vsix")
# cleanup ignored tree if desired
gh release upload "vVER" "dist/marqdo-VER.vsix" --clobber
```
## Defaults (mirror of SKILL)
| Setting | Default |
|---------|---------|
| Sync `vscode-extension` to `VER` | yes |
| Push main + annotated tag immediately | yes |
| Release notes | 中英双语 |
| Skip VSIX / docs-only / deploy pages | no |
Phase 0 asks **only** for the next version unless the user wants overrides.
## Notes template (中英双语 — default)
Save as `/tmp/marqdo-vVER-notes.md` then:
```bash
gh release edit "vVER" --notes-file /tmp/marqdo-vVER-notes.md
```
```markdown
## Marqdo vVER
### 亮点 / Highlights
- **中文** … / **EN** …
- …
### 安装 / Install
```bash
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout vVER
cargo build --release
./target/release/marqdo version
cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg
marqdo ext add web && marqdo ext add agent && marqdo ext add quantum
# 中文 id:网页 / 智能体 / 量子
```
**浏览器 WASM / Browser WASM**
```bash
marqdo wasm build
# → dist/wasm/marqdo_wasm_bg.wasm + marqdo-bridge.js
# examples: examples/browser-hello/
```
### 破坏性变更 / Breaking changes
- 无 / None
- …
### 下载 / Downloads
| Asset | 内容 / Contents |
|-------|-----------------|
| `marqdo-*-windows-msvc.exe` | CLI(内置 stdlib) |
| `marqdo-*-windows-msvc.zip` | exe + `lib/` + `ext/`(含 native) |
| `marqdo-*-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + `.so` |
| `marqdo-*-native-*.zip` | 预编译 `web`/`agent`/`quantum`/`linalg`(Win + **Linux 必出**) |
| `marqdo-*-stdlib.zip` | 仅 `lib/` |
| `marqdo-*-ext.zip` | 官方 `ext/` |
| `marqdo-*-source.zip` | 源码快照 |
| `marqdo-*.vsix` | VS Code / Cursor 扩展 |
| `marqdo-*-public.zip` | 用户文档站 |
扩展源码分支 / Extension branch: **`vscode-extension`** ([policy](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)).
### 链接 / Links
- [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md)
- [README](https://github.com/cflmy/marqdo/blob/main/README.md)
```
## Proxy & auth (network recovery)
Symptoms seen in this project: broken local Clash on `127.0.0.1:7890`, flaky GitHub TLS, `gh` needing token, Cursor agent sandbox with only `lo`.
### `proxy.cflmy.top` (try this first)
This machine’s `origin` is typically:
```
https://proxy.cflmy.top/github.com/cflmy/marqdo.git
```
Push / fetch / tag through that remote (HTTPS reverse proxy to GitHub):
```bash
git remote -v # confirm origin uses proxy.cflmy.top
git push origin main
git push origin vVER
git push origin vscode-extension
# one-shot if origin still points at github.com:
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git HEAD:main
git push https://proxy.cflmy.top/github.com/cflmy/marqdo.git vVER
```
Short GETs via the proxy often work; **long `git push` may still time out**. If push hangs or drops, skip Clash retries and go to **HK SSH jump** below.
`gh` against `api.github.com` may still need a direct path or HK jump (the reverse proxy is for `github.com` git, not always the API).
### Diagnose
```bash
env | grep -iE 'proxy|PROXY' || true
curl -sI --max-time 15 https://github.com | head -5
curl -sS --max-time 15 -o /dev/null -w 'proxy=%{http_code}\n' https://proxy.cflmy.top/ || true
gh auth status
ip -br addr | head -5 # agent may lack enp*; use required_permissions: ["all"]
```
### Fix order
1. **Unset bad proxy** if connection refused:
```bash
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy
# also clear for one git call: git -c http.proxy= -c https.proxy= …
```
2. **Set a working proxy** only if the user provides one (or known working):
```bash
export HTTPS_PROXY=http://HOST:PORT
export HTTP_PROXY=http://HOST:PORT
```
3. **Agent Shell**: retry `git push` / `gh` with `required_permissions: ["all"]` (and `full_network` if needed).
4. **`gh` auth**: if `gh auth status` fails, ask user to `gh auth login` or set `GH_TOKEN` / `GITHUB_TOKEN` for the session — **never commit tokens**. Fallback used in this repo: load password from `git credential fill` (`protocol=https` / `host=github.com`) into `GH_TOKEN` for the session only, then delete the temp env file.
5. **Git remote**: prefer `https://github.com/cflmy/marqdo.git`; SSH needs keys.
6. **HK SSH jump (preferred when GitHub is blocked but HK is reachable)** — see next subsection.
7. **Partial upload**:
```bash
gh release upload "vVER" dist/FILE --clobber
```
8. **Re-run CI** without retagging (if tag already correct):
```bash
gh workflow run Release --ref "vVER" # only if workflow_dispatch exists; else fix + new patch tag
```
Current Release workflow is **tag-push only**. Red CI after tag → fix on `main`, then either new patch tag or **user-approved** delete+recreate tag (dangerous; prefer patch).
### HK SSH jump (Paramiko CONNECT)
**When to use:** local → GitHub fails (timeout / TLS / Clash flaky / reverse-proxy `proxy.cflmy.top` connect drops), but this host can reach an overseas box that has stable GitHub (default `hk.cflmy.de`). Proven path for v0.3.9 push/tag/`gh`.
**Do not** rely on OpenSSH + `sshpass` here — password auth has hung; use **Paramiko** (`python3-paramiko`).
**Never** commit the HK root password or tokens. Ask the user for the password (or a key), put it in env / a `600` temp file, scrub after.
```bash
# one-shot password file (example — use the secret the user gave this session)
printf '%s' "$HK_PASSWORD_FROM_USER" > /tmp/.hk_ssh_pw && chmod 600 /tmp/.hk_ssh_pw
export HK_SSH_HOST=hk.cflmy.de # or 83.229.126.119
export HK_SSH_USER=root
export HK_SSH_PASSWORD_FILE=/tmp/.hk_ssh_pw
# optional: HK_JUMP_PORT=18081
SCRIPT=.cursor/skills/marqdo-release/scripts/push-via-hk-jump.py
# push / tag / extension (git gets CONNECT proxy + github.com askpass)
python3 "$SCRIPT" -- git push origin main
python3 "$SCRIPT" -- git push origin vscode-extension
python3 "$SCRIPT" -- git push origin vVER
# gh (sets GH_TOKEN from git credential fill if unset)
python3 "$SCRIPT" -- gh release edit vVER --notes-file /tmp/notes.md
python3 "$SCRIPT" -- gh run list --workflow=Release --limit 3
# leave proxy up for manual commands
python3 "$SCRIPT" --serve # then: export https_proxy=http://127.0.0.1:18081
rm -f /tmp/.hk_ssh_pw
```
Script behavior: SSH to HK → local `http://127.0.0.1:$HK_JUMP_PORT` HTTP CONNECT via `direct-tcpip` → run `git`/`gh`/`curl` with that proxy. Git auth uses local `git credential` via `http.extraHeader` (Basic) — **not** `GIT_ASKPASS` (askpass has hung under agent/no TTY). Tokens never go to the jump host disk.
Optional path reverse-proxy (`https://proxy.cflmy.top/github.com/…` `insteadOf`) may work for short GETs; treat long `git push` failures as a signal to use the HK jump instead of retrying Clash forever.
## Local Windows fallback
```powershell
powershell -File ./scripts/release-full.ps1 -Tag vVER -Upload
# -SkipVsix / -SkipPublic / -DeployPages as needed
```
Also: `scripts/release-windows.ps1`, `scripts/publish-release.py` if present.
## Commit message style
```text
release: vVER — <highlight>
```
Extension:
```text
vscode-extension: bump to VER for release
```
## Pre-tag test suggestions
Minimum:
```bash
cargo test --test gold structure_hello
./target/release/marqdo version # after cargo build --release
```
Stronger (time permitting):
```bash
cargo test --test gold
cargo test -p marqdo-wasm -- --nocapture # if wasm tests exist
# optional Node: node tests/wasm/smoke.mjs after marqdo wasm build
```
## Ask-user prompt (copy)
```text
版本探测结果:
- Cargo.toml: A.B.C
- crates/marqdo-wasm: …
- 最新 git tag: v…
- 最新 GitHub Release: v…
- CHANGELOG Unreleased: 有 / 无(摘要:…)
请指定下一个版本号(例如 0.3.2)。
默认(无需确认):同步 vscode-extension 同号、立刻 push tag 发版、发布说明中英双语。
若要改默认请一并说明。
```
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Detect Marqdo version sources for release Phase 0. Never invent next SemVer."""
from __future__ import annotations
import re
import subprocess
import sys
from pathlib import Path
# …/marqdo/.cursor/skills/marqdo-release/scripts/this.py → parents[4] = repo root
ROOT = Path(__file__).resolve().parents[4]
def cargo_version(path: Path) -> str | None:
if not path.is_file():
return None
m = re.search(r'^version\s*=\s*"([^"]+)"', path.read_text(encoding="utf-8"), re.M)
return m.group(1) if m else None
def run(cmd: list[str]) -> str:
try:
out = subprocess.check_output(cmd, cwd=ROOT, stderr=subprocess.DEVNULL, text=True)
return out.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return ""
def main() -> int:
cargo = cargo_version(ROOT / "Cargo.toml")
wasm = cargo_version(ROOT / "crates" / "marqdo-wasm" / "Cargo.toml")
tags = run(["git", "tag", "-l", "v*", "--sort=-v:refname"])
latest_tag = tags.splitlines()[0] if tags else "(none)"
gh_list = run(["gh", "release", "list", "--limit", "3"])
latest_gh = "(gh unavailable)"
if gh_list:
# first column is tag name for `gh release list`
latest_gh = gh_list.splitlines()[0].split("\t")[0].strip()
changelog = ROOT / "CHANGELOG.md"
unreleased = False
unreleased_preview = ""
if changelog.is_file():
text = changelog.read_text(encoding="utf-8")
m = re.search(r"^## Unreleased\s*\n(.*?)(?=^## |\Z)", text, re.M | re.S)
if m:
body = m.group(1).strip()
# nonempty if any bullet or non-heading content beyond empty section headers
content_lines = [
ln
for ln in body.splitlines()
if ln.strip() and not re.match(r"^###\s+", ln.strip())
]
unreleased = bool(content_lines)
unreleased_preview = " | ".join(content_lines[:3])[:200]
print("=== Marqdo version detect (do NOT invent next; ask the user) ===")
print(f"repo: {ROOT}")
print(f"Cargo.toml: {cargo or '(missing)'}")
print(f"marqdo-wasm: {wasm or '(missing)'}")
print(f"latest git tag: {latest_tag}")
print(f"latest gh release: {latest_gh}")
print(f"Unreleased notes: {'YES' if unreleased else 'NO/empty'}")
if unreleased_preview:
print(f"Unreleased peek: {unreleased_preview}")
if cargo and latest_tag.lstrip("v") != cargo:
print("WARN: Cargo version != latest tag (expected during pre-bump or lag)")
if cargo and wasm and cargo != wasm:
print("WARN: root Cargo.toml and marqdo-wasm versions differ — sync before release")
print()
print("ASK USER: next SemVer X.Y.Z (tag will be vX.Y.Z)")
return 0
if __name__ == "__main__":
sys.exit(main())
+284
View File
@@ -0,0 +1,284 @@
#!/usr/bin/env python3
"""Push / run git|gh through an HK SSH jump host (Paramiko HTTP CONNECT).
When this machine cannot reach GitHub reliably but can SSH to a host that can
(e.g. hk.cflmy.de), open a local HTTP CONNECT proxy over Paramiko and run the
remaining command with http(s).proxy pointed at it.
Why Paramiko: OpenSSH/`sshpass` has hung on password auth in this environment;
Paramiko password + direct-tcpip works.
Credentials (never commit):
HK_SSH_PASSWORD password string
HK_SSH_PASSWORD_FILE file containing password (mode 600 recommended)
or SSH key via Paramiko agent/keys if password unset and key works
Optional env:
HK_SSH_HOST default hk.cflmy.de
HK_SSH_USER default root
HK_JUMP_PORT default 18081 (local CONNECT listen)
Usage:
HK_SSH_PASSWORD_FILE=/tmp/hk.pw \\
python3 .cursor/skills/marqdo-release/scripts/push-via-hk-jump.py -- \\
git push origin main
# keep proxy only (Ctrl+C to stop)
... push-via-hk-jump.py --serve
# wrap gh
... push-via-hk-jump.py -- gh release view v0.3.9
"""
from __future__ import annotations
import os
import select
import socket
import socketserver
import subprocess
import sys
import threading
import time
from pathlib import Path
try:
import paramiko
except ImportError as e: # pragma: no cover
raise SystemExit(
"paramiko required: apt install python3-paramiko (or pip install paramiko)"
) from e
ROOT = Path(__file__).resolve().parents[4]
class _Server(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True
daemon_threads = True
def load_password() -> str | None:
path = os.environ.get("HK_SSH_PASSWORD_FILE")
if path:
return Path(path).read_text(encoding="utf-8").strip()
pw = os.environ.get("HK_SSH_PASSWORD")
return pw.strip() if pw else None
def connect_hk() -> paramiko.SSHClient:
host = os.environ.get("HK_SSH_HOST", "hk.cflmy.de")
user = os.environ.get("HK_SSH_USER", "root")
pw = load_password()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
kwargs: dict = {
"hostname": host,
"username": user,
"timeout": 20,
"auth_timeout": 25,
"banner_timeout": 25,
}
if pw:
kwargs.update(password=pw, allow_agent=False, look_for_keys=False)
else:
kwargs.update(allow_agent=True, look_for_keys=True)
print(f"== HK jump {user}@{host} ==", flush=True)
client.connect(**kwargs)
_, stdout, stderr = client.exec_command(
"hostname; curl -sS --max-time 20 -o /dev/null -w gh=%{http_code} https://github.com/; echo"
)
out = stdout.read().decode()
err = stderr.read().decode()
print(out, end="" if out.endswith("\n") else "\n", flush=True)
if err.strip():
print(err, file=sys.stderr, flush=True)
return client
def make_proxy(transport: paramiko.Transport, port: int) -> _Server:
class Handler(socketserver.StreamRequestHandler):
def handle(self) -> None:
try:
first = self.rfile.readline(65536)
if not first:
return
parts = first.decode("latin1", "replace").split()
if len(parts) < 2 or parts[0].upper() != "CONNECT":
self.wfile.write(b"HTTP/1.1 405 Method Not Allowed\r\n\r\n")
return
while True:
line = self.rfile.readline(65536)
if line in (b"\r\n", b"\n", b""):
break
host, _, port_s = parts[1].partition(":")
chan = transport.open_channel(
"direct-tcpip",
(host, int(port_s or "443")),
self.connection.getpeername(),
)
self.wfile.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
sock = self.connection
sock.setblocking(False)
chan.setblocking(False)
try:
while True:
r, _, x = select.select([sock, chan], [], [sock, chan], 120)
if x:
break
if sock in r:
data = sock.recv(65536)
if not data:
break
chan.sendall(data)
if chan in r:
data = chan.recv(65536)
if not data:
break
sock.sendall(data)
finally:
try:
chan.close()
except Exception:
pass
except Exception:
pass
return _Server(("127.0.0.1", port), Handler)
def github_basic_auth_header() -> str:
"""Authorization: Basic … from local git credential store (no askpass; askpass can hang)."""
import base64
out = subprocess.check_output(
["git", "credential", "fill"],
input=b"protocol=https\nhost=github.com\n\n",
).decode()
data = dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
user = data.get("username") or "x-access-token"
password = data.get("password") or ""
if not password:
raise SystemExit("no github.com credential in git credential store")
token = base64.b64encode(f"{user}:{password}".encode()).decode()
return f"Authorization: Basic {token}"
def github_token() -> str | None:
out = subprocess.check_output(
["git", "credential", "fill"],
input=b"protocol=https\nhost=github.com\n\n",
).decode()
data = dict(line.split("=", 1) for line in out.splitlines() if "=" in line)
return data.get("password") or None
def run_with_proxy(proxy: str, argv: list[str]) -> int:
env = os.environ.copy()
for k in (
"http_proxy",
"https_proxy",
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"all_proxy",
):
env.pop(k, None)
cmd = list(argv)
if cmd and cmd[0] == "git":
# Prefer http.extraHeader over GIT_ASKPASS (askpass has hung under agent/no TTY).
# Do not also set env http_proxy for git — only -c (avoids double-proxy quirks).
auth = github_basic_auth_header()
cmd = [
"git",
"-c",
f"http.proxy={proxy}",
"-c",
f"https.proxy={proxy}",
"-c",
"credential.helper=",
"-c",
f"http.extraHeader={auth}",
"-c",
"http.version=HTTP/1.1",
"-c",
"http.postBuffer=524288000",
*cmd[1:],
]
print(
"+",
" ".join(
c if not str(c).startswith("http.extraHeader=") else "http.extraHeader=<redacted>"
for c in cmd
),
flush=True,
)
return subprocess.call(cmd, cwd=ROOT, env=env)
env["http_proxy"] = proxy
env["https_proxy"] = proxy
env["HTTP_PROXY"] = proxy
env["HTTPS_PROXY"] = proxy
if cmd and cmd[0] == "gh" and not env.get("GH_TOKEN"):
tok = github_token()
if tok:
env["GH_TOKEN"] = tok
print("+", " ".join(cmd), flush=True)
return subprocess.call(cmd, cwd=ROOT, env=env)
def main(argv: list[str]) -> int:
args = argv[1:]
if not args or args[0] in ("-h", "--help"):
print(__doc__)
return 0 if args else 1
serve_only = args == ["--serve"]
if args[0] == "--":
args = args[1:]
if not serve_only and not args:
print("missing command after --", file=sys.stderr)
return 2
port = int(os.environ.get("HK_JUMP_PORT", "18081"))
client = connect_hk()
transport = client.get_transport()
assert transport is not None
server = make_proxy(transport, port)
threading.Thread(target=server.serve_forever, daemon=True).start()
proxy = f"http://127.0.0.1:{port}"
print(f"== CONNECT proxy {proxy} ==", flush=True)
# smoke
subprocess.call(
[
"curl",
"-sS",
"--connect-timeout",
"10",
"--max-time",
"25",
"--proxy",
proxy,
"-o",
"/dev/null",
"-w",
"github=%{http_code}\\n",
"https://github.com/",
]
)
try:
if serve_only:
print("serving; Ctrl+C to stop", flush=True)
while transport.is_active():
time.sleep(5)
return 1
return run_with_proxy(proxy, args)
finally:
server.shutdown()
client.close()
if __name__ == "__main__":
raise SystemExit(main(sys.argv))
+289
View File
@@ -0,0 +1,289 @@
---
name: marqdo
description: >-
Author and edit Marqdo programs (.mq.md): Markdown markers are executable
syntax (functions, calls, statements, returns, control flow). Use when writing
or modifying .mq.md files, teaching Marqdo, generating Marqdo from prose,
importing lib/* or ext/web or ext/quantum or ext/linalg, running marqdo CLI,
building dynamic sites with ext/web, quantum circuits with ext/quantum,
formula-first linear algebra with ext/linalg, or when the user mentions
Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, quantum/量子,
or linalg/线性代数 extension.
---
# Marqdo development
Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation and a runnable program. Read this skill **before** inventing syntax from Markdown habits or Python.
Canonical design (repo): [`markdown-mapping-v0.3.md`](../../doc/design/markdown-mapping-v0.3.md) (**v0.3 · runtime**), `doc/design/keywords.md`. Legacy v0.2 notes: `doc/design/markdown-mapping.md` (historical). Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
1. **File suffix** must be `.mq.md` (never plain `.md` for executable sources).
2. **`**…**` = code** (assign / call). **`*…*` = return value**. Output is **not** either marker — use `> print text=…` / `**print text="…"**` / `> 打印 内容=…`.
3. **Prose:** unmarked narrative may contain `` `名` `` (declare/ref), inline `**code**`, and `*return*`. Soft Markdown emphasis that is **not** code-shaped (`**说明**`, mid-line `*only*`) is ignored — see [code-as-docs-gaps.md](../../doc/design/code-as-docs-gaps.md). Dead `` `名` `` (never read) is OK and does not become a param.
4. **Do not invent keywords** `if` / `else` / `while` / `for` / `def` / `return`. Control flow is Markdown: **`1.` `2.` … branches**, **`-` loops**, arm `N. *` = else, `#` = **object/type**, `##`+ = **function/method**. Params: prefer prose `` `名` `` / `` `名`=默认 `` (inferred); `` + `名` `` still accepted.
5. **Identifiers:** `` `名` `` in prose; inside `*…*` / `**…**`, bare ids are **variables**. **Text literals must be quoted** in bold/italic: `**print text="hi"**`. Standalone `>` calls: bare words = text; vars need ticks: `` > str `n` ``.
6. **Structure lines** (`#` `>` `+` `-` `|` `1.`) need not be wrapped in bold.
7. **Paths:** In bare expressions `/` is division. In call args / defaults / table cells, unspaced `a/b` and quoted paths are text.
8. Prefer ending side-effect-only bodies with `*None*` / `*无*` / whole-line `**` / `****` when the next lines must belong to an outer function. Lone `---` / `***` are Markdown thematic breaks (skipped everywhere), not function end.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
12. **Bracket-marked calls:** Function name may be marked with `[函数名]`; bare words before `[` are boolean modifiers (`礼貌 [问候] x` → `礼貌=True`). `]` immediately followed by `(` is **index** `[key](coll)`, not a call. Prefer `[k](c)` over footnote index in new code. See [bracket-call-modifiers.md](../../doc/design/bracket-call-modifiers.md).
## Markup → meaning (v0.3)
| Marker | Meaning |
|--------|---------|
| `#` | **Object / type** (constructor body). `# main` = entry object. `# Child = > Parent` = inherit (**no** implicit parent constructor; call `` `self` = > Parent … `` explicitly when needed). |
| `##` … `######` | **Function / method** (nesting by heading depth). |
| `` + `name` `` under heading | Parameter (optional `` `name`=default ``) |
| `1.` `2.` … in body | Branch arm (condition or `N. *` else). **Same-indent restart at `1.` = new branch statement** (not more arms of the previous list). |
| `- …` inside body | Loop (`while` or `` [item](coll) `` / `` [`item`](`coll`) ``) |
| Line `N. *` | Else arm |
| `> fn args` | Call (named `k=v` or positional) |
| `修饰 [fn] args` | Bracket-marked call; leading words → `名=True` |
| `` > `obj`.method args `` | Method call (`obj` must be a map with `_type`) |
| Frontmatter `import bind:path.mq.md` / `导入` | Import file (bind library name) |
| Frontmatter `import bind:lib.member` / `导入` | Short name for a library member (same keyword; no separate `use`) |
| `> lib.member …` / `> lib.Type.member …` | Call via bare dotted path (instance methods need `` `var`.m ``) |
| `**…**` | **Code** (assign / call) — closing `**` touches last token; bare ids are variables; quote text literals |
| `*…*` | **Return value** — closing `*` touches last token; bare ids are variables |
| `****` / whole-line `**` / `*None*` | Return `None` and end function body |
| Lone `---` / `***` | Markdown thematic break (skip; not function end) |
| GFM table after empty RHS bind | Collection; get with `[key](coll)` (preferred) or legacy `` `m`[^key] `` |
| `- [item](coll)` | Foreach (unchanged) |
| `` ```lang `` | Foreign code block (via `lib/foreign`) |
| `` `"text"` `` | Quoted string (`\n` `\t` `\\` `\"`; `` `var` `` inside); bare tokens unescaped |
| Unmarked prose | Comment |
Entry: load file (often `index.mq.md`) → collect defs → run `# main`.
## Minimal program
```markdown
# main
> print text=Hello World!
```
Chinese builtins (same functions, no import):
```markdown
# main
> 打印 内容=你好
```
## Functions, calls, end-body
```markdown
# main
> greet who=Marqdo
## greet
+ `who`
> print text=Hello, `who`!
*None*
```
- Call: `> name key=value` or `> name value`.
- Nested helpers use deeper `#` (`##`, `###`, …).
- After a helper with only side effects, end with `*None*` / whole-line `**` / `****` when later lines must stay in the outer function. Lone `---` is only a thematic break (skipped).
- In bold assigns, prefer bare calls: `**摘要 = 结账摘要 …**` (omit `>`).
## Statements, returns, branches
```markdown
**x = 1**
**y = x + 2**
## add_one
+ `n`
*n + 1*
```
```markdown
**n = 0**
1. `n` > 0
> print text=positive
2. `n` < 0
> print text=negative
3. *
> print text=zero
```
## Frontmatter imports + stdlib
Imports use `import bind:target` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path:
```markdown
---
title: example
import text:lib/text.mq.md
import clock:lib/time.mq.md
---
# main
**xs = > text.str_split s="a,b,c" sep=","**
> print text=`xs`
**t = > clock.now_unix**
```
- Import **English** or **Chinese** library file; call that file’s API names via `lib.member` (do not mix languages).
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum|linalg` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below); **`ext/linalg`** — formula-first linear algebra (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
Stdlib map: [reference.md](reference.md).
## Official extension: `ext/agent` (document-driven)
Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --release -p marqdo_plugin_agent`.
**Constitution (do not dilute):**
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`). Inspect without LLM: `dump_step_context`. Inside `writeback=` / `写回=` branches use `host_writeback_record` (param name shadows the writeback import).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
## Official extension: `ext/web` (dynamic sites)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin first: `cargo build --release -p marqdo_plugin_web`.
Import **one language file** — never mix EN/ZH API names in the same `.mq.md`:
- EN: `import web:ext/web/web.mq.md`
- ZH: `导入 网页:ext/web/网页.mq.md`
**Hard rules (web):**
- Authors use **GFM tables + `#` classes** — no `json.parse` / `json.set` glue, no hand-built part JSON.
- Table cells stay **literal strings**; path text like `` `posts`.`title` `` is resolved by web classes.
- **Quote path/MIME cells** that contain `/` (T5 cell expressions treat bare `/` as division): `"/static/logo.svg"`, `"image/png"`.
- **`ext/**` never calls `host_*`** — hot path is native `plugins/web` ABI (default **Go `libweb`**, build via `scripts/build-web-plugin.sh`).
- HTTPS: terminate at reverse proxy; set `cookie_secure=True` on auth (no in-process TLS).
**Typical layout:**
```text
index.mq.md # entry + home page table + listen
pages/ # sub-pages
components/ # reusable |属性|值|样式| tables
styles/ # CSS modules
public/ # static + favicon.ico|png|svg
db/ # schema + open/init
data/ # sqlite runtime (gitignore)
```
**Core objects (EN / ZH):** `# page`/`页面`, `# style`/`样式`, `# db`/`数据库`, `# form`/`表单`, `# app`/`应用`, `# auth`/`鉴权`, `# cache`/`缓存`, `# storage`/`存储`.
**Typical flow:** `db.init` → `page.compose_*` → `app` + `static` / `listen`. Client: `marqdo wasm build -o static` + `web.client_embed source="/static/client.mq.md"` — **no author JS**; bridge may implement rich host effects ([browser-wasm-e.md](../../doc/roadmap/browser-wasm-e.md) · [browser-app](../../examples/browser-app/)).
**Shipped surface (W0–W7 + P3 + W8 + route D mount):** middleware + JSON API (`app.configure`); transactions, pagination, FTS search (`db.migrate`, `db.fts`, `db.search`); security (argon2, CSRF, SQLite sessions, login rate limit); SEO / RSS / Markdown (`page.meta`, `route_rss`, `lib/net.markdown_parse`); upload / download / gallery; sitemap / robots / error pages / redirects; RBAC (`app.gate`, user `role`); audit timestamps + FK in `db.init`; ETag on downloads; **W8** site icons (`app.icons` → `/favicon.ico`), head resource tables (`page.head`), image assembly (`make_images` / `page.images`); **D** `client_embed` auto-mount + DOM effect helpers (`text_patch` / `dom_patch`).
Design: [ext-web.md](../../doc/design/ext-web.md) · assets: [web-assets-and-images.md](../../doc/design/web-assets-and-images.md) · capability matrix: [web-net-capabilities.md](../../doc/design/web-net-capabilities.md) · example: [examples/marqdo-blog/](../../examples/marqdo-blog/) · client: [examples/web-client-site/](../../examples/web-client-site/).
Web patterns: [examples.md](examples.md) §13 · API index: [reference.md](reference.md).
## Official extension: `ext/quantum` (circuits + Q7/Q8)
Install: `marqdo ext add quantum` (ZH id: `量子`). Build: `cargo build --release -p marqdo_plugin_quantum`, then **`marqdo ext add quantum` again** so view loads the new `libquantum.so` (stale plugin = old black/white circuits).
- EN: `import quantum:ext/quantum/quantum.mq.md`
- ZH: `导入 量子:ext/quantum/量子.mq.md`
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; ≤12 qubits for statevector; density-matrix ops ≤6 qubits; one language file per program; quote draw string args (`kind="…"`, `theme="…"`).
**Core:** `# circuit` / `# gate` / `# density` — table `steps=` or method chain; `simulate` / `probabilities` / `run` / `draw`.
**Q7 linear algebra:** `density`, `partial_trace`, `eig`, `expect` (Pauli string, left=high bit), `purity`, `kron`, `schmidt`, `fidelity`.
**Draw kinds:** `circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`.
**Q8 themes (circuit / probs / bloch):** `theme="dark"|"light"|"bw"` (ZH `主题=`; **default `dark`** — slate lab look, gate-family colors, label chips so wires never cross `q0` text). View plot chrome follows `data-theme` on the SVG. Advanced kinds (hinton/…) still Q8c pending full re-skin.
```markdown
*_ = > `qc`.draw kind="circuit" theme="dark"*
*_ = > `qc`.draw kind="probs" theme="light"*
```
Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7.md](../../doc/design/ext-quantum-q7.md) · Q8 viz: [ext-quantum-viz-style.md](../../doc/design/ext-quantum-viz-style.md) · examples: [quantum-bell](../../examples/quantum-bell/) · [quantum-entanglement](../../examples/quantum-entanglement/).
## Official extension: `ext/linalg` (formula-first LA)
Install: `marqdo ext add linalg` (ZH id: `线性代数`). Build: `cargo build --release -p marqdo_plugin_linalg`, then **`marqdo ext add linalg` again** so view loads the new native lib.
- EN: `import la:ext/linalg/linalg.mq.md`
- ZH: `导入 la:ext/linalg/线性代数.mq.md`
**Hard rules:** `ext/**` never calls `host_*`; hot path is ABI plugin; prefer top-level `la.symbol` (not `matrix.symbol` without a receiver); quote `kind=` strings; dense `explicit` / factorize obey size guards.
APIs (EN): `symbol` → `# matrix`;中缀 `+`/`-`/`*`;方法 `` `A`.T `` / ``.simplify`` / ``.ascii`` · `from_formula` / `explicit` / `factorize` / `draw` · `lstsq` / `norm` / `cond` / `rank`.
Examples: [linalg-svd](../../examples/linalg-svd/) · [linalg-least-squares](../../examples/linalg-least-squares/). Design: [ext-linalg.md](../../doc/design/ext-linalg.md) · formula-doc: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md).
## AI authoring workflow
1. Decide language surface (English builtins + `lib/text.mq.md`, or Chinese + `lib/文本.mq.md`).
2. Write `.mq.md` with `# main`, blank lines around prose, correct markers.
3. Run: `marqdo run path/to/file.mq.md` (cwd = project root so `lib/` resolves).
4. On `path:line:col: message`, fix that span; re-run until exit 0.
5. Optional: `marqdo view .` / `marqdo debug .` for structure and breakpoints.
## Anti-patterns (common model mistakes)
| Wrong | Right |
|-------|-------|
| `**Hello**` to print | `> print text=Hello` |
| `# main` then prose then code with no blank line | Blank line before code |
| `if x > 0:` | `1. `x` > 0` |
| `* > print text=hi *` | `> print text=hi` |
| `` *`a` = 1 * `` (trailing space + backticks) | `*a = 1*` — bare bind, no trailing space before `*` / `**` |
| `*xs = > text.split value=a,b sep=,*` (bare text args) | `*xs = > text.split value="a,b" sep=","*` — quote text literals; bare words are variables |
| Forgetting empty return after nested `##` helper when outer continues | Add `*None*` / `**` / `****` (not `---`) |
| Import `lib/text` then call bare `split` | `> text.split …` (qualified) |
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
| `json.set` to build page parts | GFM tables + `page.compose_*` / `web.page` methods |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([marqdo-dev](../marqdo-dev/SKILL.md)) |
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
| Call `host_*` from `ext/linalg` | Use `la.*` L1 wrappers; plugin ABI only |
| Bare `kind=eig` inside `*…*` | `kind="eig"` — quote text literals |
| Bare `theme=dark` inside `*…*` | `theme="dark"` — quote; ZH `主题="dark"` |
| Rebuild plugin but skip `ext add` | `cargo build -p marqdo_plugin_quantum` then `marqdo ext add quantum` (or set `MARQDO_QUANTUM_PLUGIN`) |
## Checklist before finishing
- [ ] File ends with `.mq.md`
- [ ] Print via `print` / `打印`, not bold
- [ ] Blank lines separate comment paragraphs from code
- [ ] `# main` exists when the file is an entry program
- [ ] Nested side-effect helpers ended with `*None*` / `**` / `****` when the outer function continues
- [ ] Imports and call names share the same language file
- [ ] Data shaped as **GFM tables** (or short helpers) — no `json.set` / `json.append` glue
- [ ] Web sites: tables + web classes only (no JSON glue); `data/` gitignored
- [ ] Browser client: `lib/browser` + tables when returning effects
- [ ] Quantum draw: quote `kind=` / `theme=`; rebuild plugin → `ext add quantum` before view
- [ ] `marqdo run` succeeds (or errors addressed)
+419
View File
@@ -0,0 +1,419 @@
# Marqdo examples (AI)
v0.3: `**…**` = code (assign / call); `*…*` = return. Prefer `[key](coll)` over footnote get. Bracket calls: `礼貌 [问候] x`.
## 1. Hello (English)
```markdown
# main
> print text=Hello World!
```
## 2. Hello (Chinese builtins)
```markdown
# main
> 打印 内容=你好,世界!
```
## 3. Function + named call + empty return
```markdown
# main
Greeting via a nested function:
> greet who=Marqdo
## greet
+ `who`
> print text=Hello, `who`!
*None*
```
Or end with a whole-line empty bold return: `**` / `****`. Lone `---` is a thematic break (skipped), not function end.
## 4. Bindings and return
```markdown
# main
**a = 2**
**b = add_one n=`a`**
**打印 内容=`b`**
## add_one
+ `n`
*n + 1*
```
## 5. Branch with else
```markdown
# main
**n = 0**
1. `n` > 0
> print text=positive
2. `n` < 0
> print text=negative
3. *
> print text=zero
```
## 6. Foreach loop
```markdown
# main
`篮子` =
| 果 |
|----|
| 苹果 |
- [果](篮子)
> print text=`果`
```
## 6b. Map table + link-index get
```markdown
# main
`分类` =
| 苹果 | 黄瓜 |
|------|------|
| 水果 | 蔬菜 |
**种 = [苹果](分类)**
**打印 内容=`种`**
`篮子` =
| 果 |
|----|
| 苹果 |
**第一 = [1](篮子)**
**打印 内容=`第一`**
```
One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Prefer `[key](coll)` (lists are 1-based). Legacy `` coll[^key] `` still parses. Foreach on a map walks **keys**.
Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded):
```markdown
`订单` =
| 行 | 品名 | 数量 |
|----|------|------|
| 1 | 苹果 | 2 |
**名 = [品名]([1](订单))**
```
## 6c. Bracket-marked call + modifiers
```markdown
# main
**打印 内容=(礼貌 [问候] "Marqdo")**
## 问候
+ `谁`
+ `礼貌`=False
**出 = `礼貌` + ", " + `谁` + "!"**
*出*
```
`礼貌 [问候] …` → `礼貌=True`. `]` immediately followed by `(` is index, not a call.
## 6d. Browser effects — tables + lib/browser (not json.set)
```markdown
---
import browser:lib/browser.mq.md
---
# main
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
**`wire`**
## bump
**count = count + 1**
**label = str count**
**> browser.set_text sel="#count" text=label**
```
Do **not** build effect maps with `json.set` chains. See [marqdo-dev](../marqdo-dev/SKILL.md).
## 7. Import text stdlib
```markdown
---
title: split demo
import text:lib/text.mq.md
---
# main
**parts = [text.str_split] s="a,b,c" sep=","**
**打印 内容=`parts`**
```
## 7b. Mid M1 — regex + encoding (no plugin)
```markdown
---
import re:lib/re.mq.md
import enc:lib/encoding.mq.md
---
# main
**`ok` = [re.is_match] text="a@b.c" pattern="@"**
**`b64` = [enc.base64_encode] text="hi"**
**打印 内容=`ok`**
**打印 内容=`b64`**
```
## 7c. Mid M6 — log + uuid
```markdown
---
import log:lib/log.mq.md
import uuid:lib/uuid.mq.md
---
# main
> log.info text="start"
> log.set_level level="debug"
> log.debug text="detail"
**id = [uuid.v4]**
**打印 内容=`id`**
```
## 8. Comment paragraphs (blank-line rule)
```markdown
# main
This whole paragraph is a comment, including lines that look like code:
**not_executed = 1**
> print text=also still comment
After a blank line, code runs:
> print text=this runs
```
## 9. Frontmatter import only
```markdown
---
description: loads math
import math:lib/math.mq.md
---
# main
**t = > num value=3.5**
**打印 内容=`t`**
```
## 10. Object handle + method
See `tests/structure/object-handle.mq.md` and `ext/ai/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`.
## 10b. Object inheritance
```markdown
# Greeter
## hello
+ `who`
**msg = "Hello, `who`!"**
*msg*
# Loud = > Greeter
## hello
+ `who`
**msg = "HELLO, `who`!"**
*msg*
```
`_type` stays the most specific name (`Loud`). Methods walk the base chain; same-name `##` on the child overrides. **No implicit super** — if the child needs parent fields, call the parent explicitly:
```markdown
# Child = > Parent
+ `name`
**self = > Parent name=`name`**
**self = [table.put] in=`self` at="extra" value=1**
*self*
```
## 11. Agent layout (ABI)
```markdown
---
import agent:ext/agent.mq.md
---
# main
> load_native
**ws = > agent**
**n = > `ws`.ensure_layout**
**打印 内容=`n`**
```
Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`).
## 12. What not to emit
```markdown
# BAD — bare bold that is not code-shaped (decorative OK); do not use bold/italic as print
**Hello**
# BAD — Python control keywords
if x > 0:
print(x)
# BAD — wrapping a call in italics as if it were a statement
*> print text=hi*
# BAD — old branch syntax (removed)
+ `x` > 0
# GOOD — ordered list arms
1. `x` > 0
> print text=pos
2. *
> print text=other
# GOOD — another independent branch (restart at 1.)
1. `y` > 0
> print text=y-pos
2. *
> print text=y-other
# GOOD — print / return
**打印 内容="hi"**
*n + 1*
```
## 13. Dynamic site (ext/web, minimal)
```markdown
---
title: hello-site
import web:ext/web/web.mq.md
import db:db/index.mq.md
---
# main
`shell` =
| 组件 | 样式 |
|------|------|
| nav | |
`main` =
| 属性 | 值 | 样式 |
|------|-----|------|
| title | posts.title | |
| body | posts.summary | |
**store = > db.open**
**css = "body{font-family:sans-serif}"**
**page = > web.page title="Hello"**
**page = > page.compose_components components=`shell`**
**page = > page.compose_main main=`main`**
**page = > page.css css=`css`**
**app = > web.app page=`page` port=8080**
**app = > app.static prefix="/static" dir="static"**
> listen app=`app`
```
- Import `ext/web/web.mq.md` **or** `ext/web/网页.mq.md` — not both; match API language to the file.
- Full blog/CMS patterns: `examples/marqdo-blog/` (routes, SEO, RSS, auth, upload, WS).
- Run after `marqdo ext add web` and building `marqdo_plugin_web`.
## 14. Quantum entanglement lab (ext/quantum Q7/Q8)
```markdown
---
import quantum:ext/quantum/quantum.mq.md
---
# main
`steps` =
| step | gate | qubits |
|------|------|--------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
**qc = > quantum.circuit qubits=2 steps=`steps`**
**rho = > `qc`.density**
**red = > `rho`.partial_trace keep=0**
**sch = > `qc`.schmidt cut=1**
**_ = > `qc`.draw kind="circuit" theme="dark"**
**_ = > `qc`.draw kind="hinton"**
**打印 内容=`red`**
```
- Full lab: `examples/quantum-entanglement/`. Bell-only: `examples/quantum-bell/`.
- `theme="dark"|"light"|"bw"` (default dark) on `circuit` / `probs` / `bloch`. Quote `kind=` / `theme=`.
- After rebuilding the plugin: `marqdo ext add quantum` so view loads the new native lib.
## 15. Linear algebra (ext/linalg)
```markdown
---
import la:ext/linalg/linalg.mq.md
---
# main
**`A` = > la.symbol name="A" rows=2 cols=2**
**`B` = > la.symbol name="B" rows=2 cols=2**
**`C` = `A` + `B`**
**`P` = `A` * `B`**
```
Prefer:
```markdown
**`env` = > la.declare table=`shapes`**
**`P` = [A](env) * [B](env)**
**`t` = > `P`.T_ascii**
```
- Infix `+` / `-` / `*`;`ascii` / `T_ascii` 默认化简(`raw=True` 可关)。
- Formula-doc design: [ext-linalg-formula-doc.md](../../doc/design/ext-linalg-formula-doc.md).
- Examples: `examples/linalg-transpose/`, `examples/linalg-svd/`, `examples/linalg-least-squares/`.
+204
View File
@@ -0,0 +1,204 @@
# Marqdo reference (AI)
Load this when you need stdlib names, CLI, or edge cases. Core rules stay in [SKILL.md](SKILL.md).
## CLI
```text
marqdo --version
marqdo run FILE.mq.md
marqdo run FILE.mq.md --backend bytecode
marqdo view PATH # docs browser, default port 7429
marqdo debug PATH # debugger UI, default port 7430
marqdo catalog PATH -o .marqdo
marqdo ext list
marqdo ext add llm|agent|web|quantum|linalg
marqdo ext remove llm|agent|web|quantum|linalg
```
Diagnostics look like `path:line:col: message` (1-based line/col).
**v0.3 surface:** `**…**` = code; `*…*` = return; parameters `` + `name` `` (or prose-inferred); branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) ``; get `` [key](coll) ``; bracket calls `` mod [fn] args ``. See `doc/design/markdown-mapping-v0.3.md`.
Stdlib search order for `lib/…` imports: `MARQDO_LIB`, `./lib`, directory of the `marqdo` executable (and a few parents). Prefer the **bundle zip** (`marqdo.exe` + `lib/`) over a bare exe.
官方扩展(`ext/…`,非 stdlib):`marqdo ext add` 装到 `MARQDO_EXT` 或 `~/.marqdo/ext`;导入仍写 `import llm:ext/llm.mq.md`。解析还含 cwd `ext/`、二进制旁 `ext/`。对象:`doc/design/objects.md`。Agent:`doc/design/ext-agent.md` · 安装器:`doc/design/ext-cli.md`。
## Builtins (no import)
| EN | ZH | Role |
|----|----|------|
| `print` | `打印` | stdout; arg `text` / `内容` |
| `input` | `输入` | one line; arg `prompt` / `提示` |
| `len` | `长度` | length; arg `value` / `值` |
| `str` | `文本` | to text; arg `value` / `值` |
| `int` | `整数` | to int; arg `value` / `值` |
Keywords (not variable names): `True`/`真`, `False`/`假`, `None`/`空`, `and`/`且`, `or`/`或`, `not`/`非`.
## Standard library files
Import one file; use **that** file’s function names.
| EN import | ZH import | Typical APIs (EN / ZH) |
|-----------|-----------|-------------------------|
| `lib/text.mq.md` | `lib/文本.mq.md` | text helpers / 去空白·拆分·拼接… |
| `lib/table.mq.md` | `lib/表.mq.md` | `put`/`改` + list/map(见 `doc/design/stdlib-table.md`) |
| `lib/re.mq.md` | `lib/正则.mq.md` | Mid:`is_match`/`find`/`replace`/… |
| `lib/encoding.mq.md` | `lib/编码.mq.md` | Mid:base64/hex |
| `lib/path.mq.md` | `lib/路径.mq.md` | Mid:join/normalize/… |
| `lib/hash.mq.md` | `lib/哈希.mq.md` | Mid:sha256/hmac/… |
| `lib/secrets.mq.md` | `lib/机密.mq.md` | Mid:token_hex/urlsafe |
| `lib/csv.mq.md` | `lib/逗号表.mq.md` | Mid:parse/stringify |
| `lib/cli.mq.md` | `lib/命令行.mq.md` | Mid:`parse` flags |
| `lib/log.mq.md` | `lib/日志.mq.md` | Mid:level-filtered one-line logs |
| `lib/uuid.mq.md` | `lib/标识.mq.md` | Mid:UUID v4 |
| `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM client effect helpers(GFM + `set_text`/`canvas`/…;见 marqdo-dev) |
| `lib/fs.mq.md` | `lib/文件.mq.md` | filesystem |
| `lib/sys.mq.md` | `lib/系统.mq.md` | process / cwd / load_dotenv |
| `lib/plugin.mq.md` | `lib/插件.mq.md` | load native ABI plugins (`doc/design/ext-abi.md`) |
| `lib/time.mq.md` | `lib/时间.mq.md` | time/format |
| `lib/net.mq.md` | `lib/网络.mq.md` | HTTP(S) helpers (+ optional headers) |
| `lib/json.mq.md` | (see design) | **parse / stringify / quote only** — not a dict builder |
| `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot |
| `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks |
| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | document-driven **step** / **plan** + OKF;示例 `examples/agent-pong` · `agent-okf-flywheel`;Wave B:[agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md) |
| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | dynamic sites — see **ext/web** section below |
| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below |
| `ext/linalg/linalg.mq.md` | `ext/linalg/线性代数.mq.md` | formula MatExpr + factorize/draw — see **ext/linalg** below |
Open the imported `.mq.md` under `lib/` or `ext/` to see exact `##` / `#` names and parameters. Gold tests: `tests/lib/`, `tests/structure/`, `tests/ext/`.
## ext/web (dynamic sites)
Install: `marqdo ext add web` (`网页`). Native: `cargo build --release -p marqdo_plugin_web`.
| EN import | ZH import | Core types |
|-----------|-----------|------------|
| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | `# page` `# style` `# db` `# form` `# app` `# auth` `# cache` `# storage` |
| Area | EN methods (representative) | Notes |
|------|----------------------------|-------|
| Page | `compose_components`, `compose_main`, `render`, `meta`, `paginate` | GFM tables; cells are literal path strings |
| DB | `init`, `insert`, `select`, `paginate`, `get`, `update`, `delete`, `migrate`, `fts`, `search`, `count`, `事务`/`txn` | init supports `unique`/`index`/`fk`; auto `created_at`/`updated_at` |
| App | `route`, `static`, `configure`, `listen`, `auth`, `gate`, `upload`, `download`, `gallery`, `route_rss`, `redirect`, `error_page`, `sitemap`, `robots` | W0–W7 + P3 complete |
| Auth | `login`, `check`, `logout`, `hash_password` | argon2 + CSRF + SQLite sessions; `role` for RBAC |
Drivers (Postgres / Redis / S3): `db url=postgres://…`, `cache url=memory:`, `storage url=file:…` — see `doc/design/ext-web-drivers.md`.
Example project: `examples/marqdo-blog/`. Capability matrix: `doc/design/web-net-capabilities.md`.
## ext/quantum (circuits + Q7/Q8)
Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p marqdo_plugin_quantum`, then re-run `ext add` so view picks up the new `.so`.
| EN import | ZH import | Core types |
|-----------|-----------|------------|
| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | `# circuit` `# gate` `# density` |
| Area | EN APIs | Notes |
|------|---------|-------|
| Circuit | `h`/`cx`/…, `simulate`, `probabilities`, `run`, `draw`, `noise` | `steps=` GFM table; ≤12 qubits |
| Gate | `matrix`, `matches_matrix`, `draw` | named or `matrix=` custom unitary |
| Density (Q7) | `purity`, `partial_trace`, `eig`, `expect`, `draw` | ≤6 qubits for dense ρ |
| Free (Q7) | `kron`, `schmidt`, `fidelity` | top-level on import bind |
| Draw kinds | `circuit\|probs\|bloch\|hinton\|city\|density\|paulivec\|qsphere\|multibloch` | quote `kind="…"` |
| Themes (Q8) | `theme="dark"\|"light"\|"bw"` (ZH `主题=`) | default **dark**; circuit/probs/bloch themed; SVG `data-theme` |
Examples: `examples/quantum-bell/`, `examples/quantum-entanglement/`. Design: `doc/design/ext-quantum.md` · Q7: `doc/design/ext-quantum-q7.md` · Q8: `doc/design/ext-quantum-viz-style.md`.
## ext/linalg (formula-first linear algebra)
Install: `marqdo ext add linalg` (`线性代数`). Native: `cargo build --release -p marqdo_plugin_linalg`, then re-run `ext add`.
| EN import | ZH import | Notes |
|-----------|-----------|-------|
| `ext/linalg/linalg.mq.md` | `ext/linalg/线性代数.mq.md` | Top-level `symbol`/`mul`/`factorize`/`draw` |
Examples: `examples/linalg-svd/`, `examples/linalg-least-squares/`. Design: `doc/design/ext-linalg.md` · formula-doc: `doc/design/ext-linalg-formula-doc.md` · roadmap: `doc/roadmap/ext-linalg.md`.
## Formula + plot (math)
```markdown
---
import math:lib/math.mq.md
---
# main
`f` =
$$
x^2 - 2
$$
*_svg = > plot formula=`f` var=x min=-3 max=3*
```
Empty RHS assignment + following `$$…$$` binds a formula value. Narrative-only `$$` without binding is display, not assignment.
## Foreign (Python example)
```markdown
---
import foreign:lib/foreign.mq.md
---
# main
`hi` =
```python
print("hello-from-python")
```
```
Lines starting with `` ` `` can be code (binding). Keep a blank line before/after fences per comment rules.
## Function-end details
| Form | Effect |
|------|--------|
| Lone `---` or `***` (≥3 same chars) at function body top level | End function; no return value |
| `****` or empty bold | Return `None` and end body |
| `**expr**` | Return `expr`; does **not** by itself cut off later sibling statements — still use HR or shallower heading |
File-leading paired `---` is frontmatter only; body `---` is not frontmatter.
## Call arguments
- Named: `> greet who=World`
- Positional: `> greet World`
- Spaces in values: allowed in named forms as in docs (`who=marqdo user`)
- Inline call in statement: `` *`n` = > len value=`s`* ``
See `doc/design/call-arguments.md`.
## Identifiers
- Variables: `` `name` ``
- Comparisons: `==` `>` `<` `>=` `<=`
- Do not use keyword tokens as names
## Design docs (repo)
| Doc | Topic |
|-----|--------|
| `doc/design/markdown-mapping-v0.3.md` | Syntax constitution (runtime) |
| `doc/design/markdown-mapping.md` | Legacy v0.2 notes |
| `doc/design/objects.md` | `#` objects / `##` methods |
| `doc/design/keywords.md` | Builtins / keywords |
| `doc/design/return-hr-and-code-surface.md` | Function end / surfaces |
| `doc/design/stdlib-i18n.md` | EN/ZH lib files |
| `doc/design/stdlib-modules.md` | L1 modules including plugin |
| `doc/design/ext-abi.md` | Native C ABI v1 |
| `doc/design/ext-llm.md` | `ext/llm` |
| `doc/design/ext-agent.md` | `ext/agent` agent **framework** (layout shipped; LLM orchestration roadmap) |
| `doc/design/ext-cli.md` | `marqdo ext list/add/remove` |
| `doc/design/ext-web.md` | `ext/web` dynamic sites (author API) |
| `doc/design/web-net-capabilities.md` | ext/web capability matrix (W0–W7 + P3) |
| `doc/design/ext-quantum.md` | `ext/quantum` circuits |
| `doc/design/ext-quantum-q7.md` | Q7 density linear algebra + advanced SVG |
| `doc/design/ext-quantum-viz-style.md` | Q8 themed SVG (`dark`/`light`/`bw`; circuit/probs/bloch) |
| `doc/design/ext-linalg.md` | `ext/linalg` formula MatExpr + factorize/draw |
| `doc/design/ext-linalg-formula-doc.md` | 公式文档面:跑通即正确 · 代数/计算两面 |
| `doc/design/view-debug.md` | view / debug hosts |
+12
View File
@@ -0,0 +1,12 @@
# Local LLM for Marqdo agent / ext/ai/llm development.
# Copy to `.env` in the repo root (gitignored) and fill secrets.
# Never commit real keys.
OPENAI_API_KEY=
OPENAI_BASE_URL=https://llm.cflmy.cn/v1
OPENAI_MODEL=cflmy
# Aliases also accepted by ext/ai/llm:
# MARQDO_LLM_API_KEY=
# MARQDO_LLM_BASE_URL=
# MARQDO_LLM_MODEL=
+3 -5
View File
@@ -11,6 +11,7 @@ on:
- "Cargo.lock"
- ".github/workflows/pages.yml"
- "scripts/build-public.*"
- "scripts/run-public-pages.sh"
workflow_dispatch:
permissions:
@@ -26,11 +27,8 @@ jobs:
uses: dtolnay/rust-toolchain@stable
- name: Build & export site
run: |
cargo build --release
find public -name '*.mq.md' ! -name 'utils.mq.md' -print0 \
| xargs -0 -n1 ./target/release/marqdo run
./target/release/marqdo view output public -o public
shell: bash
run: bash scripts/run-public-pages.sh
- name: Verify site shape
run: |
+224
View File
@@ -0,0 +1,224 @@
# Build and attach release binaries when a version tag is pushed.
name: Release
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
windows:
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install Go (web plugin)
uses: actions/setup-go@v5
with:
go-version: "1.23.x"
- name: Install Node (VS Code extension)
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Install MinGW for cgo (web.dll)
run: choco install mingw -y
- name: Build release CLI + official plugins
shell: bash
run: |
export PATH="/c/ProgramData/mingw64/mingw64/bin:/c/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin:$PATH"
cargo build --release
cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg
bash ./scripts/build-web-plugin.sh
- name: Checkout extension sources (branch vscode-extension only)
run: git fetch origin vscode-extension && git checkout origin/vscode-extension -- vscode-extension
- name: Build VSIX
shell: pwsh
run: |
$ver = "${{ github.ref_name }}".TrimStart("v")
New-Item -ItemType Directory -Force -Path dist | Out-Null
Push-Location vscode-extension
npm ci
npm run compile
npx @vscode/vsce package --no-dependencies -o "../dist/marqdo-$ver.vsix"
Pop-Location
- name: Package
shell: pwsh
run: |
$ver = "${{ github.ref_name }}".TrimStart("v")
$target = "x86_64-pc-windows-msvc"
New-Item -ItemType Directory -Force -Path dist | Out-Null
$exe = "marqdo-$ver-$target.exe"
$zip = "marqdo-$ver-$target.zip"
$stdlib = "marqdo-$ver-stdlib.zip"
$source = "marqdo-$ver-source.zip"
$vsix = "marqdo-$ver.vsix"
$public = "marqdo-$ver-public.zip"
$extZip = "marqdo-$ver-ext.zip"
$nativeZip = "marqdo-$ver-native-$target.zip"
Copy-Item target/release/marqdo.exe "dist/$exe"
git archive --format=zip -o "dist/$source" HEAD
./target/release/marqdo view output public -o public
Compress-Archive -Path public/* -DestinationPath "dist/$public" -Force
$stageExt = "dist/stage-ext"
if (Test-Path $stageExt) { Remove-Item $stageExt -Recurse -Force }
New-Item -ItemType Directory -Force -Path $stageExt | Out-Null
Copy-Item ext "$stageExt/ext" -Recurse
if (Test-Path "dist/$extZip") { Remove-Item "dist/$extZip" -Force }
Compress-Archive -Path "$stageExt/*" -DestinationPath "dist/$extZip" -Force
# Prebuilt native plugins (no Rust required for `marqdo ext add`)
$stageNative = "dist/stage-native"
if (Test-Path $stageNative) { Remove-Item $stageNative -Recurse -Force }
New-Item -ItemType Directory -Force -Path "$stageNative/native" | Out-Null
Copy-Item target/release/web.dll "$stageNative/native/web.dll"
Copy-Item target/release/agent.dll "$stageNative/native/agent.dll"
Copy-Item target/release/quantum.dll "$stageNative/native/quantum.dll"
Copy-Item target/release/linalg.dll "$stageNative/native/linalg.dll"
if (Test-Path "dist/$nativeZip") { Remove-Item "dist/$nativeZip" -Force }
Compress-Archive -Path "$stageNative/*" -DestinationPath "dist/$nativeZip" -Force
$stage = "dist/stage-bundle"
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
New-Item -ItemType Directory -Force -Path $stage | Out-Null
Copy-Item target/release/marqdo.exe "$stage/marqdo.exe"
Copy-Item lib "$stage/lib" -Recurse
Copy-Item ext "$stage/ext" -Recurse
New-Item -ItemType Directory -Force -Path "$stage/ext/native" | Out-Null
Copy-Item target/release/web.dll "$stage/ext/native/web.dll"
Copy-Item target/release/agent.dll "$stage/ext/native/agent.dll"
Copy-Item target/release/quantum.dll "$stage/ext/native/quantum.dll"
Copy-Item target/release/linalg.dll "$stage/ext/native/linalg.dll"
if (Test-Path "dist/$zip") { Remove-Item "dist/$zip" -Force }
Compress-Archive -Path "$stage/*" -DestinationPath "dist/$zip" -Force
$stageLib = "dist/stage-stdlib"
if (Test-Path $stageLib) { Remove-Item $stageLib -Recurse -Force }
New-Item -ItemType Directory -Force -Path $stageLib | Out-Null
Copy-Item lib "$stageLib/lib" -Recurse
if (Test-Path "dist/$stdlib") { Remove-Item "dist/$stdlib" -Force }
Compress-Archive -Path "$stageLib/*" -DestinationPath "dist/$stdlib" -Force
echo "EXE=$exe" >> $env:GITHUB_ENV
echo "ZIP=$zip" >> $env:GITHUB_ENV
echo "STDLIB=$stdlib" >> $env:GITHUB_ENV
echo "VSIX=$vsix" >> $env:GITHUB_ENV
echo "SOURCE=$source" >> $env:GITHUB_ENV
echo "PUBLIC=$public" >> $env:GITHUB_ENV
echo "EXT=$extZip" >> $env:GITHUB_ENV
echo "NATIVE=$nativeZip" >> $env:GITHUB_ENV
- name: Upload release assets
uses: softprops/action-gh-release@v2
with:
body: |
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights
- **v1.0.1**:修复 Go `libweb` 动态路由 `{param}` 查询代入、详情 Markdown、CSS 数字误报、`/static/` ServeMux 冲突
- **v1.0.1**: fix Go `libweb` dynamic-route `{param}` query resolve, article Markdown, CSS numeric false positives, `/static/` ServeMux conflict
- **v1.0.0**:Markdown 语法映射 v0.3 为唯一运行时(`**` 代码 / `*` 返回 / 叙述 `` `名` ``)
- **Linux 包必出**:`*-native-x86_64-unknown-linux-gnu.zip` + Linux CLI bundle
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [mapping v0.3](https://github.com/cflmy/marqdo/blob/main/doc/design/markdown-mapping-v0.3.md)
### Downloads
| Asset | Contents |
|-------|----------|
| `marqdo-*-windows-msvc.exe` | CLI with **embedded** official stdlib |
| `marqdo-*-windows-msvc.zip` | `marqdo.exe` + `lib/` + `ext/`(含 native DLL) |
| `marqdo-*-native-*.zip` | 预编译 `web`/`agent`/`quantum`/`linalg`(Windows DLL + **Linux .so 必出**) |
| `marqdo-*-unknown-linux-gnu.zip` | Linux CLI + `lib/` + `ext/` + native `.so` |
| `marqdo-*-stdlib.zip` | `lib/` only |
| `marqdo-*-ext.zip` | Official `ext/` L1 sources |
| `marqdo-*-source.zip` | Source snapshot (`git archive`) |
| `marqdo-*.vsix` | VS Code / Cursor extension |
| `marqdo-*-public.zip` | Static user docs site |
Extension workflow: [vscode-extension-commit.md](https://github.com/cflmy/marqdo/blob/main/doc/design/vscode-extension-commit.md)
files: |
dist/${{ env.EXE }}
dist/${{ env.ZIP }}
dist/${{ env.STDLIB }}
dist/${{ env.EXT }}
dist/${{ env.NATIVE }}
dist/${{ env.VSIX }}
dist/${{ env.SOURCE }}
dist/${{ env.PUBLIC }}
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
linux:
runs-on: ubuntu-latest
# Wait until Windows has created the GitHub Release, then attach Linux zips
# (required: native plugins for `marqdo ext add` on Linux + CLI bundle).
needs: windows
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
- name: Install Go (web plugin)
uses: actions/setup-go@v5
with:
go-version: "1.23.x"
- name: Install zip + cgo toolchain
run: sudo apt-get update && sudo apt-get install -y zip gcc libc6-dev
- name: Build Linux CLI + official plugins
run: |
set -euo pipefail
cargo build --release
cargo build --release -p marqdo_plugin_agent -p marqdo_plugin_quantum -p marqdo_plugin_linalg
bash ./scripts/build-web-plugin.sh
- name: Package Linux native zip + CLI bundle
run: |
set -euo pipefail
VER="${GITHUB_REF_NAME#v}"
TARGET="x86_64-unknown-linux-gnu"
mkdir -p dist/stage-native/native
for lib in libweb.so libagent.so libquantum.so liblinalg.so; do
src="target/release/${lib}"
if [[ ! -f "$src" && "$lib" == libweb.so ]]; then
src="plugins/web/build/libweb.so"
fi
test -f "$src" || { echo "missing $src" >&2; exit 1; }
cp "$src" "dist/stage-native/native/${lib}"
done
(cd dist/stage-native && zip -r "../marqdo-${VER}-native-${TARGET}.zip" .)
echo "NATIVE=marqdo-${VER}-native-${TARGET}.zip" >> "$GITHUB_ENV"
stage="dist/stage-linux"
rm -rf "$stage"
mkdir -p "$stage/ext/native" "$stage/lib"
cp target/release/marqdo "$stage/marqdo"
chmod +x "$stage/marqdo"
cp -a lib/. "$stage/lib/"
cp -a ext/. "$stage/ext/"
cp dist/stage-native/native/*.so "$stage/ext/native/"
linux_zip="marqdo-${VER}-${TARGET}.zip"
(cd "$stage" && zip -r "../${linux_zip}" .)
echo "LINUX_ZIP=${linux_zip}" >> "$GITHUB_ENV"
- name: Upload Linux packages
uses: softprops/action-gh-release@v2
with:
files: |
dist/${{ env.NATIVE }}
dist/${{ env.LINUX_ZIP }}
fail_on_unmatched_files: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+63
View File
@@ -1,18 +1,81 @@
/target/
/dist/
# Copied by gold harness for ABI plugins
/tests/lib/demo.dll
/tests/lib/libdemo.so
/tests/lib/libdemo.dylib
/tests/ext/agent.dll
/tests/ext/libagent.so
/tests/ext/libagent.dylib
/tests/ext/skel.mq.md
/tests/ext/out-demo.mq.md
/tests/ext/ticket.txt
/tests/ext/ticket-stub.txt
/tests/ext/agents/
/tests/ext/runbooks/
/tests/ext/templates/
/tests/ext/reports/
**/*.rs.bk
.idea/
.vscode/
*.pdb
.DS_Store
.marqdo/
**/.marqdo/
.marqdo-ext/
.env
# Generated HTML beside tracked public/*.mq.md (sources stay in git)
/public/index.html
/public/pages/
# VS Code extension: source only on branch `vscode-extension` (see doc/design/vscode-extension-commit.md)
/vscode-extension/
# Python spike venv (local)
spike/.venv/
spike/__pycache__/
spike/.pytest_cache/
**/__pycache__/
*.pyc
# Built browser WASM (rebuild via crates/marqdo-wasm README)
/examples/browser-hello/marqdo_wasm.wasm
/examples/browser-hello/pkg/
/examples/web-client-site/static/marqdo_wasm.wasm
/examples/browser-app/marqdo_wasm.wasm
/examples/browser-media/marqdo_wasm.wasm
# Local sqlite / scratch
/data/
/tmp/
plugins/*/tmp/
# web smoke/example DBs (cwd-relative or fixture data dirs)
/web-fixtures/
/tests/ext/web-fixtures/data/
/tests/ext/entrydir-fixtures/data/
/examples/web-site/data/
/examples/web-site-zh/data/
/examples/web-net-site/data/
/examples/web-net-site-zh/data/
/examples/marqdo-blog/data/
/examples/anlian-mq/data/
# Quantum draw/SVG runtime outputs (sources & gold .mq.md stay tracked)
/tests/ext/quantum-*.svg
/tests/ext/linalg-*.svg
/examples/quantum-*/**/*.svg
/examples/quantum-*/*.svg
/examples/linalg-*/**/*.svg
/examples/linalg-*/*.svg
/examples/linalg-*.svg
# Local ABI plugin copies (use `marqdo ext add quantum` / cargo build)
/ext/native/
# Go web plugin c-shared build output (./scripts/build-web-plugin.sh)
/plugins/web/build/
# ephemeral sqlite / test artifacts
tests/ext/:memory:
+431
View File
@@ -0,0 +1,431 @@
# Changelog
## Unreleased
### Added
### Fixed
### Changed
## v1.0.1 — 2026-09-15
### Highlights
**ext/web(Go libweb)回归修复**:动态路由查询条件恢复 `{param}` 代入;详情 SSR + Markdown;样式表数字不再误报。
```bash
git checkout v1.0.1
cargo build --release
bash ./scripts/build-web-plugin.sh
# 或:解压 Release 的 marqdo-1.0.1-*-native-*.zip / Linux CLI zip
marqdo run examples/marqdo-blog/index.mq.md
```
### Added
- Go web plugin:详情页正文 Markdown(goldmark GFM),对齐 Rust `pulldown-cmark` 路径。
### Fixed
- **动态路由 `{param}` 未代入查询条件**(`ext/web` Go):`selectPageData` 递归展开 `query` 全部字符串叶子;`data-slot-src` / `_route` 同步替换。`examples/marqdo-blog` `/post/{slug}` 详情 SSR 恢复。
- **样式表数字单元格误报「可疑 `/` 除法」**:`cssValueSuspicious` 不再把合法 `z-index`/`opacity` 等 number 当警告。
- Go 1.22+ ServeMux:`/static/` 与 `/static/favicon.svg` 的 GET/HEAD 注册冲突导致博客启动 panic。
- Rust archive 同步:`resolve_placeholders` 递归 + CSS number 误报收窄(非默认构建路径)。
## v1.0.0 — 2026-09-14
### Highlights
**Markdown 语法映射 v0.3 成为 1.0 宪法**:`**粗体**` = 代码,`*斜体*` = 返回,叙述里的 `` `名` `` 声明并推断形参。这是相对 v0.4 / 旧 `*语句*`/`**返回**` 的破坏性对调。Linux 预编译拓展包与 CLI bundle 为 Release 必出资产。
```bash
git checkout v1.0.0
cargo build --release
# Linux:也可直接解压 Release 的 marqdo-1.0.0-x86_64-unknown-linux-gnu.zip
marqdo run tests/markup-v03/inc-prose.mq.md
```
### Added
- **Markup v0.3 运行时闭环**:粗体=`代码`、斜体=`返回`、叙述 `` `名` `` 声明与形参推断为唯一映射;金样 `tests/markup-v03/`。
- **方括号标记调用**与前置修饰语:`礼貌 [问候] x`;取元主语法 `[键](集合)`(脚注取元过渡保留)。
- **代码即文档叙述面 G1–G4**:模块级 `---` 跳过、装饰性强调、浮点面量、动态键。
- **粗体表达式语句** `**n + 1**`;`--dump-lines` 标注 `[decl]/[bold]/[italic]`;`--dump-ast` 显示 inferred 形参与死绑定。
- **Release Linux 包必出**:`linux` job 上传 `*-native-x86_64-unknown-linux-gnu.zip` 与 Linux CLI bundle。
### Fixed
- 行首 `` `名`… `` 叙述不再当语句(修复 pages CI:`public/features/16-fs-mid2.mq.md`)。
- 句中斜体强调(`*very important*` / `*foo.bar*`)不再误收束函数;Decl 名须为标识符;残缺粗体保持 GAP 恢复。
- 胶合 `` `名`=default …prose `` 为 Decl 而非赋值。
### Changed
- 教程 / Skill / `lib` / `ext` / `public` 对齐 v0.3 标记;view 推断形参 `chip inferred`。
## v0.4.0 — 2026-09-13
### Highlights
**Go `libweb` 默认落地(W-G0–W-G14)**:官方网页原生插件改为 Go C ABI;CLI / gold / Release 走 `scripts/build-web-plugin.sh`;Rust 源码归档。另附 **anlian-mq** 验收站与表单插槽 / `MARQDO_EXT` 提示修复。
```bash
git checkout v0.4.0
# 构建 web 原生插件(需 Go + cgo):
bash ./scripts/build-web-plugin.sh
marqdo ext add web
marqdo run examples/anlian-mq/index.mq.md
```
### Added
- **`plugins/web` Go 全量重写(W-G0–W-G13)**:C ABI 对等装配/DB/表单/listen/鉴权/上传/SEO/WS/驱动/proxy·invoke/定制壳;`scripts/build-web-plugin.sh` → `libweb.so` / `web.dll`;ADR [0004](doc/adr/0004-web-plugin-go.md) · 施工 [ext-web-go-rewrite.md](doc/design/ext-web-go-rewrite.md)。
- **W-G14 验收**:`examples/anlian-mq/`(暗恋见君风格论坛:路由/登录/粉玻璃主题/片段 API;SQLite 本地可跑)。
- **GAP-11**:`compose_form` / `表单装配` 支持 `target` / `表单插槽`(如 `#id`),把表单注入引言 HTML 内的挂载点。
### Fixed
- **GAP-12**:`ext/…` import 解析失败且未设置 `MARQDO_EXT` 时,错误附带 `hint: set MARQDO_EXT to the directory that contains web/`。
- **listen 会话 / CSRF**:登录后 `IssueCookie` 不再误设 `Max-Age=0`;页面 ABIs(`query`/`order`/`link_prefix`/`css`/`detail`)与 `web_page_chrome`、`invoke return=html` 对齐 anlian 需求。
### Changed
- **默认 `libweb` 为 Go**:Release / gold / `ext add web` 不再构建 Rust `marqdo_plugin_web`;旧 Rust 树移至 `plugins/web-rust-archive/`(非 workspace 成员)。作者面 `ext/web` ABI 名保持兼容。
## v0.3.9 — 2026-09-09
### Highlights
**业务联调缺口 GAP-06–10**:解析器不再吞掉嵌套反引号/`text=[…]` 后的函数体;`invoke` 的 `Null` 不再伪装成功;`sys.exec capture=` 可取 stdout;流式 proxy 反缓冲头。
```bash
git checkout v0.3.9
```
### Added
- **`sys.exec` / `系统.执行`**:可选 `capture=` / `捕获=`;为真时返回 `{code, stdout, stderr}`(GAP-09)。
### Fixed
- **GAP-06/07**:`*…*` 分类对反引号/字符串内的 `*` 不再误判;错误收尾的赋值行不再吞掉后续 `##` 体(`>` / 合法 `*…*` 可脱出注释段);命名参数边界尊重 `[…]`/`{…}`。
- **GAP-08**:`app.invoke` 对 `Null`/`None` 返回不再伪装成 `{"ok":true}`,改为 500 + `{"ok":false,"error":"null result"}`。
- **GAP-10**:`app.proxy` `stream=true` 响应补齐 `Cache-Control: no-cache, no-transform` 与 `X-Accel-Buffering: no`。
### Changed
## v0.3.8 — 2026-09-09
### Highlights
**中层标准库 Mid2(M7–M10)收口**:日历/时区、URL、TOML、HTML 转义、base32、实用 fs、薄统计与日志字段——日常脚本与工具配置不再依赖外联或插件。另修复嵌套插件调用后 `GLOBAL_HOST` 被清空导致 `invoke` 失败。
```bash
git checkout v0.3.8
# 或下载 Release 的 exe / zip
marqdo run public/features/14-datetime-url.mq.md
marqdo run public/features/17-stats-log.mq.md
```
### Added
- **中层标准库 Mid2 M10**:`lib/stats` / `统计`(mean/median/stdev)与 `log`/`日志` 可选 `fields=`;金样与 public `17-stats-log`。**Mid2 M7–M10 收口**(zip 跳过)。设计 [stdlib-stats-log.md](doc/design/stdlib-stats-log.md)。
- **中层标准库 Mid2 M9**:`fs.make_dirs` / `remove_tree` / `stat` / `walk`(中英);金样与 public `16-fs-mid2`。设计 [stdlib-fs-mid2.md](doc/design/stdlib-fs-mid2.md)。
- **中层标准库 Mid2 M8**:`lib/toml` / `配置表`(只读子集)、`lib/html` / `超文本`(escape/unescape)、`encoding` base32;金样与 public `15-toml-html-encoding`。设计 [stdlib-toml.md](doc/design/stdlib-toml.md) · [stdlib-html.md](doc/design/stdlib-html.md)。
- **中层标准库 Mid2 M7**:`lib/datetime` / `日期时间`(`{unix,zone,iso}` · parse/format/add/in_zone)与 `lib/url` / `地址`(parse · query_parse/stringify);金样与 public `14-datetime-url`。设计 [stdlib-datetime.md](doc/design/stdlib-datetime.md) · [stdlib-url.md](doc/design/stdlib-url.md)。
- **文档**:中层标准库 Mid 之后缺口盘点与 Mid2(M7–M10)设计/路线——[stdlib-gaps-after-mid.md](doc/research/stdlib-gaps-after-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md) · [stdlib-mid2.md](doc/roadmap/stdlib-mid2.md)。
### Fixed
- **`host_query` / GLOBAL_HOST**:嵌套 `call_registered` 结束后恢复外层宿主指针,不再清空;`web_listen` 多轮 `invoke`(中间再调插件)不再报 `no active host context`。
### Changed
## v0.3.7 — 2026-09-07
### Highlights
**宿主集成 H1–H4**:浏览器同域 SSE/HTTP 流式中继(`app.proxy`)、HTTP→用户 `##`(`app.invoke`)、跨模块 db 方法分发、`corpus_search` 可发现、MCP Server stdio——下游可去掉 Python 旁路。
```bash
git checkout v0.3.7
# 或下载 Release 的 exe / zip
marqdo ext add web && marqdo ext add agent
# *app*.proxy / *app*.invoke · agent.mcp_server
```
### Added
- **宿主集成 H1–H4**:`ext/web` `app.proxy`(同域 SSE/HTTP 流式中继)与 `app.invoke`(HTTP→`lib.member`);跨模块 `#` 对象方法查找;`agent.corpus_search` 自动加载插件;`agent.mcp_server` stdio。金样 `web-proxy-invoke-smoke` · `web-hosting-live` · `web-db-cross-module-smoke` · `agent-mcp-server-smoke`。设计 [ext-hosting-fill.md](doc/design/ext-hosting-fill.md) · [ext-hosting.md](doc/roadmap/ext-hosting.md)。
- **文档**:宿主集成缺口盘点——[ext-hosting-gaps.md](doc/research/ext-hosting-gaps.md)。
### Fixed
- **方法分发**:`find_object_type` 沿导入树传递查找,跨模块拿到的 `web.db` 等句柄可再调方法。
### Changed
## v0.3.6 — 2026-09-07
### Highlights
**中层标准库 Mid M1–M6 收口**:通用原语沉入 `lib/`(正则、编解码、路径、哈希、机密、CSV、加厚文本/集合、CLI、日志、UUID),写日常脚本与多数扩展库不再需要原生插件。另含 `ext/linalg` 公式文档面与 agent/llm 稳健性修复。
```bash
git checkout v0.3.6
# 或下载 Release 的 exe / zip
marqdo run public/features/13-log-uuid.mq.md
marqdo ext add linalg # 可选:公式文档 / 线性代数
```
### Added
- **中层标准库 M6**:`lib/log` / `日志`(级别过滤的一行日志)与 `lib/uuid` / `标识`(v4);金样与 public `13-log-uuid`。设计 [stdlib-log-uuid.md](doc/design/stdlib-log-uuid.md)。**Mid M1–M6 收口。**
- **中层标准库 M5**:`table`/`表` 加厚(sort/sort_by/unique/chunk/zip/flatten)与 `lib/cli`/`命令行`(parse);金样与 public `12-list-cli`。设计 [stdlib-list-cli.md](doc/design/stdlib-list-cli.md)。
- **中层标准库 M4**:`lib/csv` / `逗号表`(parse/stringify)与 `lib/text` / `文本` 加厚(contains/replace/case/pad/…);金样与 public `11-csv-text`。设计 [stdlib-csv.md](doc/design/stdlib-csv.md) · [stdlib-text-mid.md](doc/design/stdlib-text-mid.md)。
- **中层标准库 M3**:`lib/hash` / `哈希`(sha256/sha1/md5/hmac_sha256)与 `lib/secrets` / `机密`(token_hex/token_urlsafe);金样与 public `10-hash-secrets`。设计 [stdlib-hash.md](doc/design/stdlib-hash.md) · [stdlib-secrets.md](doc/design/stdlib-secrets.md)。
- **中层标准库 M2**:`lib/path` / `lib/路径`(join/split/normalize/…)与 `fs`/`文件` 加厚(`copy_file`/`move`/`make_temp`);金样与 public `09-path-fs`。设计 [stdlib-path.md](doc/design/stdlib-path.md) · [stdlib-fs-mid.md](doc/design/stdlib-fs-mid.md)。
- **中层标准库 M1**:`lib/re` / `lib/正则`(`is_match`/`find`/`find_all`/`replace`/`split`)与 `lib/encoding` / `lib/编码`(base64/hex);host `host_re_*` + `host_encoding_*`;金样与 public `08-re-encoding`。设计 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-re.md](doc/design/stdlib-re.md) · [stdlib-encoding.md](doc/design/stdlib-encoding.md)。
- **`ext/linalg`**:L0–L6 + 公式文档面 **F1–F3**(中缀、`declare`、展示/`explicit` 默认化简、`T_ascii`、public「如何写公式文档」);示例 `linalg-transpose` · `linalg-svd` · `linalg-least-squares`。设计:[ext-linalg-formula-doc.md](doc/design/ext-linalg-formula-doc.md)。
### Fixed
- **`ext/agent`**:写回改走 `wb.record`(避免 `writeback` 形参遮蔽模块名),不再直调 `host_*`。
- **`ext/llm`**:`stream_result` 忽略未知 SSE 类型(如 `reasoning`),不再因此退出。
### Changed
## v0.3.5 — 2026-09-04
### Highlights
**`marqdo ext add` 无需本机 Rust**:Release 发布预编译 native 插件;CLI 可自动下载 L1(`*-ext.zip`)与 `*-native-*.zip`。Windows 便携包内含 `ext/native/*.dll`。
```bash
git checkout v0.3.5
# 或下载 Release 的 exe / zip
marqdo ext add web
marqdo ext add agent
marqdo ext add quantum
```
### Added
- **预编译原生插件资产**:`marqdo-*-native-x86_64-pc-windows-msvc.zip`、`marqdo-*-native-x86_64-unknown-linux-gnu.zip`;Windows zip 捆绑 `ext/` + native DLL。
- **`ext add` 下载回退**:本地无 `target/` 时从 GitHub Release 拉取;`MARQDO_EXT_NO_DOWNLOAD=1` / `MARQDO_EXT_VERSION` 可配置。
### Changed
- 文档:[ext-cli.md](doc/design/ext-cli.md)、[08-ext-deploy-coupling](doc/design/ext-web-customization/08-ext-deploy-coupling.md)、README 安装步骤以预编译为默认路径。
- Release workflow:Windows 编插件并上传 native zip;新增 Linux native job。
## v0.3.4 — 2026-09-04
### Highlights
**`ext/web` 定制波次 C0–C4 收口**:可配置 admin 前缀与登录回跳、段边界 gates、shell/layout、样式单元格 strict、脚本 defer/version/`asset_version`、条件导航 when/media。附智能体 Wave B0 示例与写回遮蔽修复。
```bash
git checkout v0.3.4
cargo build --release
cargo build --release -p marqdo_plugin_web
marqdo ext add web
# golds: tests/ext/web-c0-admin-prefix … web-c4-nav-when
```
### Added
- **智能体 Wave B0**:宪法优先示例 [agent-pong](examples/agent-pong/)(call_site/源码注入)· [agent-okf-flywheel](examples/agent-okf-flywheel/)(OKF `cache=hit`);调研 [agent-framework-2026-09.md](doc/research/agent-framework-2026-09.md);离线 harness [`scripts/agent-harness.sh`](scripts/agent-harness.sh);金样 `agent-constitution-b0`。
- **`.env.example`**:开发期 OpenAI 兼容网关变量模板(密钥仅本地 `.env`)。
### Fixed
- **`agent.step` / `plan` 写回**:参数名 `writeback` 遮蔽 `lib/writeback` import,导致 `writeback=True` 时 `method receiver must be an object map`;改为 `host_writeback_record`。金样 `agent-writeback-shadow`。
- **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。
- **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。
- **`ext/web` C2**:`shell_css=full|minimal|off`;`layout=sidebar|stacked|bare|rail`;full 壳含小屏单列 media;金样 `web-c2-shell-layout`。
- **`ext/web` C3**:样式装配对数字/布尔值单元格告警,`strict`/`strict_css_cells` 硬错误;`page.css` 作 raw CSS;head 表支持 `defer`/`async`/`version`,`asset_version` 统一 `?v=`;金样 `web-c3-style-head`。
- **`ext/web` C4**:导航表 `当`/`when`(`auth`/`guest`/`hide`)与 `媒体`/`media`(响应式显隐);listen 注入 `_logged_in`;金样 `web-c4-nav-when`。
### Changed
- `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。
- 中文 `构建单步上下文` 委托英文版(含预算 / READ);新增 `dump_step_context`;live 用例改用仓库根 `.env`。
- 文档:[ext-web 定制限制](doc/research/ext-web-customization-limits.md) + [解决设计 C0–C4](doc/design/ext-web-customization/)。
## v0.3.3 — 2026-09-04
### Highlights
**浏览器作者零业务 JS(路线 D/E/F)**:官方 bridge 自启 + 宿主效应补齐(DOM/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM 表格写法;新增 [marqdo-dev](.cursor/skills/marqdo-dev/SKILL.md) 开发约定。
```bash
git checkout v0.3.3
cargo build --release
marqdo wasm build
# examples: browser-hello / browser-app / browser-media / web-client-site
```
### Added
- **路线 D(作者零 JS)**:[roadmap](doc/roadmap/browser-wasm-d.md) · 设计 §16。官方 bridge `mount` / `data-mq-*` 自启;`client_embed` 带 `wasm`/`source`/`boot`;DOM 效应;`examples/web-client-site/`。
- **路线 E(前端补齐)**:[browser-wasm-e.md](doc/roadmap/browser-wasm-e.md)。多节点 DOM、`add_class`/`remove_class`、cookie、clipboard/download、`fetch_all`/`ws`/`interval`;示例 [browser-app](examples/browser-app/)。
- **路线 F(媒体/文件,F1–F5)**:[browser-wasm-f.md](doc/roadmap/browser-wasm-f.md)。`read_file`、Canvas 2D、Audio beep、Intersection/ResizeObserver、drag/drop;示例 [browser-media](examples/browser-media/)。
- **`lib/browser` / `lib/浏览器`**:WASM 客户端效应助手(GFM 表格 + named helpers;勿用 `json.set` 链)。
- **Skill `marqdo-dev`**:代码即文档 / GFM-first / 库开发约定。
### Changed
- 浏览器示例(hello / app / media / web-client)改为表格 + `lib/browser`;`ext/web` 效应助手改用 `table.put`。
- 标准库模块表收录 `browser`;路线 F 收口 F1–F5(F6 Service Worker 仍可选)。
## v0.3.2 — 2026-09-01
### Highlights
**浏览器 Marqdo(路线 C)首版完备**:`wasm-core`、`marqdo wasm build`、会话 ABI、DOM/`fetch`/`after` 效应、官方 bridge、体积与冒烟;并修 Admin 长内容布局、`ext add` 原生插件预检、`@keyframes` 与样式表 `/` 比率约定。
```bash
git checkout v0.3.2
cargo build --release
marqdo wasm build
marqdo ext add web # 改插件后请重新 add
```
### Added
- **浏览器 Marqdo(路线 C)**: [ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [design](doc/design/browser-marqdo-wasm.md) · [roadmap C0–C5](doc/roadmap/browser-wasm.md)。
- **C0/C1**:`wasm-core` feature 门控;`run_source`;crate `crates/marqdo-wasm`(`mq_run` ABI);示例 [examples/browser-hello](examples/browser-hello/)。
- **C2/C3**:`marqdo wasm build`;会话 `mq_boot`/`mq_call`;GFM wire 表 + `set_text` DOM 回写;[interact.html](examples/browser-hello/interact.html) 计数器示例。
- **C4**:[ADR 0003](doc/adr/0003-browser-async-effects.md) 效应表(`fetch` / `after`)+ bridge 续体;[fetch.html](examples/browser-hello/fetch.html)。
- **C5**:`release-wasm` 体积配置;`marqdo wasm build` 报告 KiB 并可选 `wasm-opt`;`run_source` bytecode 单测;会话仍为 tree。
- **WASM 收口**:规范 `crates/marqdo-wasm/js/marqdo-bridge.js`;`wasm build` 同时拷贝 bridge;Node 冒烟 `tests/wasm`;`web.client_embed` / `网页.客户端挂载`;路线图标 Completed。
- **发版 Skill**:`.cursor/skills/marqdo-release/`(探测版本 → 用户确认 → 文档/资产/扩展/Release 说明)。
### Fixed
- **Admin UI**:主区取消 `max-width:56rem` 限制,表格外包可横向滚动的 `.table-wrap`,单元格完整展示并自动换行;表单加宽且 textarea 可随内容增高。
- **`marqdo ext add`**:安装含原生插件的扩展时**先**定位/自动 `cargo build` 再拷贝 `.mq.md`,避免只装上文稿、运行时报 `native plugin not found`;扩大 `.so` 搜索路径。
- **`web_style` / 样式装配**:正确输出 `@keyframes` 块(停点为嵌套规则,不再写成 `0%: opacity: 0`)。
- **样式表含 `/` 的值**:文档明确**引号优先**(`"16/9"`、`"1/5"`);不引入靠空格消歧的表单元格比率折叠。
## v0.3.1 — 2026-08-29
### Highlights
**W8 站点资源**:favicon / Head 资源表 / 图片装配一次补齐;并修复相对入口路径下 `entry_dir` 双重拼接导致的嵌套目录问题。
```bash
git checkout v0.3.1
cargo build --release
marqdo ext add web # 改插件后请重新 add
```
### Added
- **`ext/web` W8(站点图标 / Head / 图片装配)** ([web-assets-and-images.md](doc/design/web-assets-and-images.md)):`app.icons` / `应用.图标` 挂 `GET /favicon.ico`;`page.head` / `头装配`;`make_images` / `图片装配`;`meta` 认 `icon`/`favicon`/`apple-touch-icon`;`static` 约定 `favicon.*`;金样 `web-assets-smoke` / `web-assets-live`;[marqdo-blog](examples/marqdo-blog/) 接入。
### Fixed
- **`host_query("entry_dir")`**:相对入口脚本(如 `tests/ext/….mq.md`)时对进程 cwd 绝对化,避免与 `for_run` 已设的脚本目录 cwd 再次拼接成 `tests/ext/tests/ext/…`。
## v0.3.0 — 2026-08-29
### Highlights
本版把 **`ext/web` 网络能力(W0–W7 + P3)**、**`ext/quantum` Q7/Q8**、**`ext/agent` A1–A4** 一并收口到正式发布;并修了网页扩展叙述行误解析、补充 ASGI/生产部署说明与 agent 下一波(B0–B5)缺口调研。
**如何拿到本版**
```bash
# 从源码(推荐跟 main / 本 tag)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v0.3.0
cargo build --release
./target/release/marqdo version
# 或从 GitHub Releases 下载 Windows 包 / 源码 zip(见 Release 资产)
marqdo version --check
```
**扩展(非 stdlib)**
```bash
cargo build --release -p marqdo_plugin_web -p marqdo_plugin_agent -p marqdo_plugin_quantum
marqdo ext add web && marqdo ext add agent && marqdo ext add quantum
# 中文 id:网页 / 智能体 / 量子 / 大模型
```
### Added
- **调研:`ext/agent` A0–A4 之后缺口** ([agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)):产品化示例、评测 harness、真 MCP、plan resume/HITL、飞轮指标与建议分期 B0–B5;挂到 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md) 与 [doc/README.md](doc/README.md)。
- **生产部署调研(ASGI)** ([web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)):不能挂 Daphne/Uvicorn;路径为反向代理 → 嵌入式 `listen`(axum)。
- **`ext/agent` A4(RAG/MCP 证据工具)**: `corpus_search` 本地语料关键词检索;`mcp_list_tools` / `mcp_call` 读 JSON fixture;返回 `authority=workbook`。金样 `agent-tools-rag-a4`。
- **`ext/agent` A3(上下文预算)**: `source_brief` / 加深版 `skill_brief`;`build_step_context` 默认截断并提示 `READ:source|skill`;`step` 支持最多 `max_reads` 次加深;父 `READ:skill`。金样 `agent-context-budget-a3`。
- **`ext/agent` A2(过程可见)**: `plan` 过程事件默认写入返回 map 的 `events`(SSE 仍仅 `stream=True`);OKF 命中记 `REUSE` decision;view plan 卡渲染过程时间线。对齐 [agent-streaming.md](doc/roadmap/agent-streaming.md)。
- **`ext/agent` A1(OKF 复用飞轮)**: `agent_kb_list_tasks` 返回 description/aliases/status/llm_free/hits;`plan` 命中路径暴露 `match`/`score`(summary 含 match kind);soft_match 策展提示带 status/llm_free/description;view plan 卡显示 match。金样 `agent-kb-plan-hit`。路线 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md)。
- **`ext/web` 样式装配(`web_style` / `网页.样式装配`)**: 样式即数据表格 —— GFM 样式表(`|选择器|属性|值|`,可用 `|媒体|` 列分组进 `@media` 块)经 `样式装配` 函数转成 CSS 文本,再拼装成完整主题。替代"整段手写 CSS 字符串"的写法,贯彻 文档即代码。见 [marqdo-blog](examples/marqdo-blog/styles/theme.mq.md)。
- **网络能力调研(`doc/design/web-net-capabilities.md`)**: 盘点 `ext/web` + `plugins/web` + `lib/net` 现状,对照主流语言网络栈(FastAPI / Express / Flask / axum),给出「开发一个完整 Web 项目」所需能力的差距清单与分波次补强路线(W1–W7 + P3,**2026-08-28 已全部落地**)。
- **AI Skill + 文档(ext/web 完结复核)**: `skills/marqdo/` 与 `.cursor/skills/marqdo/` 增加 **ext/web 动态站** 专节(硬规则、API 摘要、§13 最小站点样例);`doc/design/web-net-capabilities.md` 结论/对照表与 W7+P3 实现对齐;`doc/design/ai-skill.md` 更新用途说明。
- **`ext/quantum` Q7(高阶线性代数 + 高级可视化)**: 密度矩阵 / 部分迹 / Hermitian 谱 / Schmidt / Pauli 期望 / 纯度;SVG:hinton、city、density、paulivec、qsphere、multibloch。全部经 `plugins/quantum` ABI。设计 [ext-quantum-q7.md](doc/design/ext-quantum-q7.md);金样 `quantum-linalg-smoke`、`quantum-viz-advanced-smoke`;示例 [quantum-entanglement](examples/quantum-entanglement/)。
- **`ext/quantum` Q8a/Q8b(可视化美学)**: `draw theme=dark|light|bw`(默认 dark);标签芯片 + gutter 消除线穿字;门族分色;probs/bloch 共用令牌;view 对 `data-theme` 换图框。设计 [ext-quantum-viz-style.md](doc/design/ext-quantum-viz-style.md)。改插件后须 `marqdo ext add quantum` 再开 view。
### Fixed
- **`ext/web` / `网页.mq.md`**:叙述行勿以反引号开头,避免被解析为语句(`examples/marqdo-blog` 可正常 `listen`)。
### Changed
- **Frontmatter import syntax**: `import bind:target` / `导入 bind:target` (file `.mq.md` or short name `lib.member`). Removed legacy `> path.mq.md` / `> use` imports. See [module-namespace.md](doc/design/module-namespace.md).
## v0.2.0 — 2026-08-12
### Highlights — official extension libraries
This release centers on **`ext/`**: optional packages that are **not** part of the embedded stdlib. Install them with the CLI; native plugins (`.so` / `.dll`) ship beside L1 Markdown APIs.
**How to get extensions**
```bash
# List what the installer knows about
marqdo ext list
# Install from the repo's ./ext (or MARQDO_EXT_SOURCE), into ~/.marqdo/ext (or MARQDO_EXT)
marqdo ext add llm
marqdo ext add agent
marqdo ext add web
marqdo ext add quantum
# Chinese ids work the same (大模型 / 智能体 / 网页 / 量子)
marqdo ext add 量子
marqdo ext remove quantum
```
Native plugins (agent / web / quantum) must be built once, then `ext add` copies them into `MARQDO_EXT/native/`:
```bash
cargo build --release -p marqdo_plugin_agent
cargo build --release -p marqdo_plugin_web
cargo build --release -p marqdo_plugin_quantum
marqdo ext add agent
marqdo ext add web
marqdo ext add quantum
```
Runtime also resolves plugins from `CARGO_TARGET_DIR`, `target/`, next to the `marqdo` binary, or `MARQDO_*_PLUGIN` env vars. Design: [ext-cli.md](doc/design/ext-cli.md) · [ext-abi.md](doc/design/ext-abi.md).
| Package | What you get |
|---------|----------------|
| **llm** | OpenAI-compatible chat — [ext-llm.md](doc/design/ext-llm.md) |
| **agent** | Agent layout / orchestration helpers + native plugin — [ext-agent.md](doc/design/ext-agent.md) |
| **web** | HTTP + SQLite site helpers + native plugin — [ext-web.md](doc/design/ext-web.md) |
| **quantum** | State-vector circuits, draw, noise, formula `matrix=` custom gates — [ext-quantum.md](doc/design/ext-quantum.md) |
User-facing intro: [`public/features/05-extensions.mq.md`](public/features/05-extensions.mq.md) / [`05-扩展.mq.md`](public/features/05-扩展.mq.md).
### Added
- Full **ext CLI** catalog: `llm`, `agent`, `web`, `quantum` (EN/ZH ids).
- **Quantum (Q0–Q6)**: gates, `run`/`steps`, draw (circuit/probs/bloch), heatmaps, teaching noise incl. amplitude damping, **custom gates from `$$` / `matrix=`**.
- **Web** extension (listen / render / SQLite) with L1 EN/ZH.
- **Agent** native plugin path + installer copy into `native/`.
- View **Variables** panel: previews + click-to-open rich modal (matrices / KaTeX).
- Formula matrix parse (`pmatrix` / `[[…]]`) for executable gate matrices.
### Changed
- Release notes and docs emphasize extensions vs embedded stdlib.
- Highlight.js CDN path for view pages; Variables panel script escaping fixed.
## v0.1.2 — 2026-08-07
### Added
- **Embedded standard library**: official `lib/*.mq.md` ships inside the `marqdo` binary; disk `lib/` and `MARQDO_LIB` still override.
- **`lib/writeback`** / **`lib/subtask`**: Jupyter-style writeback; concurrent subtasks (file / function / foreign).
- **Surface syntax v0.2**: `` + `param` `` parameters, `1.` ordered branches, backtick identifiers, quoted strings.
- **`marqdo version --check`**: compare installed CLI with latest GitHub release.
- **VS Code extension v0.0.6** (branch **`vscode-extension` only**): v0.2 grammar, update check — see [doc/design/vscode-extension-commit.md](doc/design/vscode-extension-commit.md)
### Changed
- Subtask `spawn` accepts `path=`, `fn=`, `code=`, or `lang=`+`source=` (not file-only).
- Release notes: standalone `.exe` includes stdlib; bundle/stdlib zips remain optional for overrides.
## v0.1.1
- v0.2 syntax migration, writeback/subtask v1 (file subprocess only), view input deferral, optional parameters.
## v0.1.0
- Initial public releases: tree + bytecode backends, `view` / `debug` / `catalog`, core stdlib, `ext/` installer.
Generated
+1074 -6
View File
File diff suppressed because it is too large. Load diff
+63 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "0.0.3"
version = "1.0.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
@@ -10,13 +10,73 @@ repository = "https://github.com/cflmy/marqdo"
[[bin]]
name = "marqdo"
path = "src/main.rs"
required-features = ["cli"]
[features]
default = ["native"]
native = ["cli", "view", "net-host", "plugin-host", "exec-host", "fs-host", "tty"]
cli = ["dep:clap"]
view = ["dep:tiny_http"]
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize", "dep:zip"]
plugin-host = ["dep:libloading"]
exec-host = []
fs-host = []
tty = ["dep:libc"]
wasm-core = []
[dependencies]
anyhow = "1"
clap = { version = "=4.4.18", features = ["derive"] }
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
clap = { version = "=4.4.18", features = ["derive"], optional = true }
pulldown-cmark = "0.12"
serde_json = "1"
thiserror = "1"
tiny_http = "0.12"
tiny_http = { version = "0.12", optional = true }
sha2 = { version = "=0.10.9", default-features = false }
sha1 = { version = "=0.10.6", default-features = false }
md-5 = { version = "=0.10.6", default-features = false }
hmac = { version = "=0.12.1", default-features = false }
getrandom = { version = "=0.2.17", default-features = false, features = ["std"] }
# Mid M1: Unicode regex for lib/re (no backrefs; RE2-like).
regex = { version = "=1.13.1", default-features = false, features = ["std", "unicode"] }
# Pin for Cargo/rustc 1.81 (newer rustls/idna/zeroize need edition2024).
ureq = { version = "=2.9.7", default-features = false, features = ["tls", "gzip"], optional = true }
idna_adapter = { version = "=1.1.0", optional = true }
zeroize = { version = "=1.8.1", optional = true }
# Extract GitHub Release ext/native zips (`marqdo ext add` without local Rust).
zip = { version = "=0.6.6", default-features = false, features = ["deflate"], optional = true }
libloading = { version = "=0.8.6", optional = true }
include_dir = "0.7"
libc = { version = "0.2", optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# No `wasmbind`: keeps cdylib free of wasm-bindgen imports (raw mq_* ABI).
chrono = { version = "0.4", default-features = false, features = ["alloc", "std"] }
[workspace]
members = [
"plugins/demo",
"plugins/agent",
"plugins/quantum",
"plugins/linalg",
"crates/marqdo-wasm",
]
# Official web plugin is Go (`plugins/web/`); Rust sources kept as
# `plugins/web-rust-archive/` for reference (not a workspace member).
resolver = "2"
[dev-dependencies]
assert_cmd = "=2.0.14"
predicates = "=3.1.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] }
tokio-tungstenite = "0.24"
futures-util = "0.3"
# Size-oriented profile for `marqdo-wasm` (C5). Use: cargo build -p marqdo-wasm --profile release-wasm --target wasm32-unknown-unknown
[profile.release-wasm]
inherits = "release"
lto = true
codegen-units = 1
opt-level = "z"
strip = true
panic = "abort"
+138 -30
View File
@@ -1,70 +1,178 @@
# Marqdo
**代码即文档。文档即代码。**
**代码即文档。文档即代码。文档即知识库。**
Marqdo:Markdown **标记即语法**。源文件 `.mq.md` 既是文稿也是程序。
Marqdo 把 Markdown **标记当作编程语法**:同一个 `.mq.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) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 金样例:[tests/](tests/) · 用户文档:[public/](public/)
欢迎访问 [marqdo 官方网站](https://www.marqdo.com/) 阅读更多特性与可执行文档。
语法宪法:[doc/design/markdown-mapping.md](doc/design/markdown-mapping.md) · 对象:[objects.md](doc/design/objects.md) · 调用实参:[call-arguments.md](doc/design/call-arguments.md) · 用户站:[user-site.md](doc/design/user-site.md) · 浏览:[view.md](doc/design/view.md) · 调试:[view-debug.md](doc/design/view-debug.md) · OKF 清单:[catalog-cli.md](doc/design/catalog-cli.md) · VS Code 扩展:[vscode-extension.md](doc/design/vscode-extension.md)(分支 **`vscode-extension`**;提交约定 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md)) · **AI Skill**:[skills/marqdo/](skills/marqdo/)(说明 [ai-skill.md](doc/design/ai-skill.md)) · 官方扩展:[ext-llm.md](doc/design/ext-llm.md)(`ext/llm`)· [ext-agent.md](doc/design/ext-agent.md)(智能体开发框架)· [ext-cli.md](doc/design/ext-cli.md)(`marqdo ext list/add/remove`) · 原生插件 ABI:[ext-abi.md](doc/design/ext-abi.md)(`lib/plugin`) · 金样例:[tests/](tests/) · 用户文档:[public/](public/) · 变更:[CHANGELOG.md](CHANGELOG.md)
---
## 语法速览(v0.1)
## 为什么重要
| 痛点 | Marqdo 的答案 |
|------|----------------|
| 文档过期、示例跑不通 | **一份源文件**:叙述、结构与执行结果同源 |
| 知识散落在 Wiki / 注释 / 脚本里 | **`.mq.md` 即知识单元**,可浏览、可运行、可检索 |
| 人写给人看,AI / 工具另起一套 | **人机同读同写同构**:标记语言对人类友好,对解释器确定 |
| 大仓里「文档站」与「代码仓」脱节 | `view` 文档站 + `debug` 调试面 + `catalog` 清单,同一棵树长大 |
这不是「再做一个 Markdown 渲染器」,而是:**把文档升格为可解释的程序与可生长的知识库**,让协作在大型项目里依然站得住。
---
## 语法速览(v0.3)
| 标记 | 含义 |
|------|------|
| 无标记行 | 注释 |
| `*…*` | 程序语句 |
| `**…**` | **返回值**(架构) |
| 无标记行 | 叙述(注释);行内 `` `名` `` 可声明 |
| `**…**` | **代码**(赋值 / 调用 / 表达式) |
| `*…*` | **返回值**(整行、`返回*n*`、或表达式形) |
| `****` / 整行 `**` / `*None*` | **空返回**(`None`),并结束本函数体 |
| `> print …` 等 | 输出等副作用 = **普通函数**,非架构标记 |
| `#` / `##` | 函数与作用域 |
| `+` / `1.` | 分支(臂头单独 `*` = else) |
| `-` | 循环(头下纯名则为形参) |
| 表格 | 集合 |
| `---` / `***` | 可选:框住分支/循环(不强制) |
| `#` | 对象 / 类型(构造体;`# main` = 入口) |
| `##` … | 函数 / 方法(按标题深度嵌套) |
| `` > `obj`.method … `` | 方法调用(`obj` 为带 `_type` 的 map) |
| 叙述 `` `名` `` / `` `名`=默认 `` | 形参由体推断(`` + `名` `` 仍可用) |
| `1.` … | 体内 `1.` `2.` … = 分支(`N. *` = else) |
| `-` | 循环(`` - `条件` `` 或 `` - [项](集合) ``) |
| 表格 | 集合;取元优先 `[键](集合)` |
| 单独一行 `---` / `***` | **叙述分隔**(跳过;不是函数收束) |
```markdown
# main
> print text=Hello World!
> 问候 谁=World
## 问候
向`谁`问好。
**print text="Hello " + 谁**
*None*
## 加一
- n
**`n` + 1**
对于输入变量`n`,执行**n=n+1**接着返回*n*。
```
完整约定:[markdown-mapping-v0.3.md](doc/design/markdown-mapping-v0.3.md)。
---
## 理念
1. 叙述默认安全(无标记 = 注释)。
2. 返回是架构;打印只是函数。
3. 依赖清单由工具生成(OKF 风格),不是手填配置。
4. **正经解释器(Rust)**:词法/行分类 → 递归下降语法 → 语义 → 树遍历 → 日后字节码;**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md) 与 [依赖说明](doc/design/dependencies.md)。
1. **叙述默认安全**(无标记 = 注释)。
2. **返回是架构;打印只是函数。**
3. **代码即文档即知识库**:文稿可执行,执行可回看结构,结构可导航与调试。
4. **对齐 [OKF](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md)(Open Knowledge Format)方向**:清单由工具从 `.mq.md` **自动生成**,不是手填配置——见下节与 [catalog-cli.md](doc/design/catalog-cli.md)。
5. **正经解释器(Rust)**:词法/行分类 → 语法 → 语义 → 树遍历(及字节码);**不用 Flex/Bison**。见 [路线图](doc/roadmap/interpreter.md)。
---
## 现状
## OKF 风格清单(自动生成)
- 映射 v0.1:[markdown-mapping.md](doc/design/markdown-mapping.md)
- 解释器路线图:[interpreter.md](doc/roadmap/interpreter.md)
- **Phase I(树遍历)已通**:`tests/structure/` 与 `tests/keywords/` 金样例均可 `marqdo run`
- **view**:`marqdo view public` 浏览用户文档;金样例用 `marqdo view tests`
- **用户静态站**:可执行文稿在 `public/`(无 errors);`view output` 生成 HTML(ignore),CI 发布到 `gh-pages` — 见 [user-site.md](doc/design/user-site.md)
- 依赖(Rust,无 Flex/Bison):[dependencies.md](doc/design/dependencies.md)
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md)
从源码派生 YAML / Markdown 知识包(勿手改生成物):
```bash
marqdo catalog [PATH] -o OUT_DIR
marqdo sync [PATH] -o OUT_DIR # catalog 的别名
```
| 参数 | 默认 | 说明 |
|------|------|------|
| `PATH` | `.` | 工程根或含 `.mq.md` 的目录 |
| `-o` / `--out` | `.marqdo` | 输出目录 |
产物示例:`catalog.yaml`、`index.md`、`modules/*.md`(`type: Marqdo Module` 等)。设计见 [generated-yaml-manifest.md](doc/design/generated-yaml-manifest.md) · 调研 [okf-and-marqdo.md](doc/research/okf-and-marqdo.md)。
智能体框架横向调研(LangGraph / CrewAI / 厂商 SDK 等 vs Marqdo 文档驱动优势):[agent-frameworks-and-marqdo.md](doc/research/agent-frameworks-and-marqdo.md) · 优化路线 [ext-agent-optimize.md](doc/roadmap/ext-agent-optimize.md)。
```bash
cargo run -- catalog public -o .marqdo
# 或已安装二进制时:
marqdo catalog public -o .marqdo
```
---
## 现状(v1.0.1)
- 映射与解释器:**v0.3 语法宪法**(`**` 代码 / `*` 返回 / 叙述声明);Phase I 树遍历 + 字节码后端;金样例在 `tests/` 与 `tests/markup-v03/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
- **`marqdo view`**:文档浏览器(Structure + 函数大纲/搜索 + Execution + Variables 浮窗)
- **`marqdo debug`**:独立调试页(断点 / 单步 / locals;默认端口 7430;页面 favicon / 品牌使用官方 Logo)
- **`marqdo catalog` / `sync`**:OKF 风格 YAML + 模块概念页
- **`marqdo version --check`**:与 GitHub 最新 release 对比
- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、表、**浏览器效应**、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**;**中层 Mid M1–M6** + **Mid2 M7–M10**(datetime/url/toml/html/fs++/stats/log.fields 等,见 [stdlib-mid.md](doc/design/stdlib-mid.md) · [stdlib-mid2.md](doc/design/stdlib-mid2.md))
- **官方扩展库 `ext/`**(**非** stdlib,本版收口):
- **`web`**:W0–W7 + P3 + **W8**;**定制 C0–C4**;**宿主 H1–H2**(`proxy`/`invoke`,见 [ext-hosting.md](doc/roadmap/ext-hosting.md));原生层默认 **Go `libweb`**([ADR 0004](doc/adr/0004-web-plugin-go.md),`scripts/build-web-plugin.sh`);示例 [marqdo-blog](examples/marqdo-blog/) · [anlian-mq](examples/anlian-mq/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
- **`linalg`**:L0–L6 + 公式文档面(中缀 / `declare` / 展示化简);示例 [linalg-transpose](examples/linalg-transpose/) · [linalg-svd](examples/linalg-svd/) · [linalg-least-squares](examples/linalg-least-squares/)
- **`agent`**:A1–A4 + **MCP Server stdio**(`mcp_server`);宿主缺口见 [ext-hosting.md](doc/roadmap/ext-hosting.md) · [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)
- **`llm`**:OpenAI 兼容对话
- 安装:`marqdo ext list` / `add …` / `remove`([ext-cli.md](doc/design/ext-cli.md);默认 `~/.marqdo/ext`)。原生插件先 `cargo build -p marqdo_plugin_*` 再 `ext add`
- **原生插件 ABI**:[`include/marqdo_abi.h`](include/marqdo_abi.h) · [ext-abi.md](doc/design/ext-abi.md);`plugins/{demo,agent,web,quantum,linalg}`(`web` 为 Go;其余为 Rust)
- **用户静态站**:`public/` → `view output` → CI 发布 [gh-pages](https://cflmy.github.io/marqdo/)
- **VS Code 扩展**:分支 **`vscode-extension`**(`main` 不跟踪源码;见 [vscode-extension-commit.md](doc/design/vscode-extension-commit.md));Release 附带 `.vsix`
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
### 如何使用最新 Marqdo(v1.0.1)
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v1.0.1 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
marqdo version --check
# 2) 跑解释器 / 文档站 / catalog
marqdo run tests/structure/hello.mq.md
marqdo run tests/structure/hello.mq.md --backend bytecode
marqdo view public --no-open
marqdo debug public --no-open
marqdo catalog public -o .marqdo
# 3) 安装官方扩展(Release 用户:无需本机 Rust/Go)
marqdo ext add web # 或:网页 — 自动下载 L1 + 预编译 native(Go libweb)
marqdo ext add agent # 或:智能体
marqdo ext add quantum # 或:量子
marqdo ext add linalg # 或:线性代数
marqdo ext add llm # 或:大模型(纯 .mq.md)
# 开发者:cargo build --release -p marqdo_plugin_{agent,quantum,linalg}
# bash ./scripts/build-web-plugin.sh # 需 Go + cgo → libweb
# 离线:解压 Windows zip(已含 ext/native)或手动放下 native zip;MARQDO_EXT_NO_DOWNLOAD=1
# 4) 动态站示例(扩展装好后)
marqdo run examples/marqdo-blog/index.mq.md
marqdo run examples/anlian-mq/index.mq.md # W-G14 验收站
# 浏览器打开终端打印的 listen 地址;/favicon.ico 与 logo 装配见 W8
# 5) 浏览器 WASM(可选)
marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 6) Releases:Windows exe/zip/vsix;Linux CLI zip + native `.so` zip
# https://github.com/cflmy/marqdo/releases/tag/v1.0.1
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
```bash
cargo run -- run tests/structure/hello.mq.md
cargo run -- run tests/structure/hello.mq.md --backend bytecode
cargo run -- view public --no-open
cargo run -- view output public -o public
powershell -File ./scripts/build-public.ps1
cargo run -- catalog tests -o .marqdo
```
文档:用户站见 [public/](public/) 与 [user-site.md](doc/design/user-site.md);设计文稿见 [doc/](doc/);`view` 皮肤见 [view.md](doc/design/view.md);OKF 清单见 [catalog-cli.md](doc/design/catalog-cli.md)。
**发布包(GitHub Releases)**:单独二进制 **已内置**官方 `lib/`(`import …:lib/…` 可直接导入)。仍提供带 `lib/` 的 zip 便于覆盖或离线分发。**扩展库**用 `marqdo ext add …` 安装(见 [CHANGELOG](CHANGELOG.md) 与 [ext-cli.md](doc/design/ext-cli.md));原生 `.so`/`.dll` 需本地编译或从带 `native/` 的安装目录解析。
文档:用户站 [public/](public/) · 设计 [doc/](doc/) · OKF / catalog [catalog-cli.md](doc/design/catalog-cli.md) · 调试 [view-debug.md](doc/design/view-debug.md) · 变更 [CHANGELOG.md](CHANGELOG.md)
---
## 命名
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "marqdo-wasm"
version = "1.0.1"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
repository = "https://github.com/cflmy/marqdo"
publish = false
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
marqdo = { path = "../..", default-features = false, features = ["wasm-core"] }
serde_json = "1"
+21
View File
@@ -0,0 +1,21 @@
# Marqdo browser WASM (route C)
Raw `cdylib` exports — no `wasm-bindgen` CLI required.
| Export | Role |
|--------|------|
| `mq_alloc` / `mq_dealloc` | linear memory |
| `mq_run` | one-shot `# main` (C1) |
| `mq_boot` / `mq_call` | session + handlers (C3) |
| `mq_version` | version C string |
```bash
# from repo root (C5 size profile)
marqdo wasm build -o examples/browser-hello
# or:
cargo build -p marqdo-wasm --target wasm32-unknown-unknown --profile release-wasm
```
Prints size in KiB; runs `wasm-opt -Oz` when Binaryen is on `PATH`.
See [doc/design/browser-marqdo-wasm.md](../../doc/design/browser-marqdo-wasm.md).
File diff suppressed because it is too large. Load diff
+201
View File
@@ -0,0 +1,201 @@
//! Browser export surface for Marqdo (ADR 0002 / C1–C3).
//!
//! Raw `cdylib` ABI (no wasm-bindgen CLI):
//! - `mq_alloc` / `mq_dealloc`
//! - `mq_run` — one-shot `# main` (C1)
//! - `mq_boot` — start session; return value often a `wire` table (C3)
//! - `mq_call` — `(name_ptr, name_len, args_ptr, args_len) ->` JSON result (C3)
//! - `mq_version`
//!
//! Packed results: little-endian `u32` length + UTF-8 JSON
//! `{ ok, stdout, error, value }`.
use std::alloc::{alloc, dealloc, Layout};
use std::cell::RefCell;
use std::ptr;
use std::slice;
use marqdo::{run_source, value_as_json, BrowserSession, RunOptions};
use serde_json::json;
thread_local! {
static SESSION: RefCell<Option<BrowserSession>> = const { RefCell::new(None) };
}
/// Allocate `size` bytes in WASM linear memory (alignment 1).
#[no_mangle]
pub extern "C" fn mq_alloc(size: usize) -> *mut u8 {
if size == 0 {
return ptr::null_mut();
}
let layout = match Layout::from_size_align(size, 1) {
Ok(l) => l,
Err(_) => return ptr::null_mut(),
};
unsafe { alloc(layout) }
}
/// Free a buffer previously returned by [`mq_alloc`], [`mq_run`], [`mq_boot`], or [`mq_call`].
#[no_mangle]
pub extern "C" fn mq_dealloc(ptr: *mut u8, size: usize) {
if ptr.is_null() || size == 0 {
return;
}
let layout = match Layout::from_size_align(size, 1) {
Ok(l) => l,
Err(_) => return,
};
unsafe { dealloc(ptr, layout) }
}
/// One-shot run (C1). Does not keep a session.
#[no_mangle]
pub extern "C" fn mq_run(ptr: *const u8, len: usize) -> *mut u8 {
let source = match read_utf8(ptr, len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
pack_json(&run_to_json(&source))
}
/// Boot a session: run `# main`, keep entry env. Replaces any prior session.
#[no_mangle]
pub extern "C" fn mq_boot(ptr: *const u8, len: usize) -> *mut u8 {
let source = match read_utf8(ptr, len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
match BrowserSession::boot(&source) {
Ok((sess, value)) => {
let stdout = String::new();
let value_json = match value_as_json(&value) {
Ok(j) => j,
Err(e) => return pack_json(&err_json(&e)),
};
SESSION.with(|s| *s.borrow_mut() = Some(sess));
pack_json(&json!({
"ok": true,
"stdout": stdout,
"error": null,
"value": value_json,
}))
}
Err(e) => {
SESSION.with(|s| *s.borrow_mut() = None);
pack_json(&err_json(&format!("{e:#}")))
}
}
}
/// Call a function in the current session.
/// `args` is UTF-8 JSON object of named arguments (may be `{}`).
#[no_mangle]
pub extern "C" fn mq_call(
name_ptr: *const u8,
name_len: usize,
args_ptr: *const u8,
args_len: usize,
) -> *mut u8 {
let name = match read_utf8(name_ptr, name_len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
let args = match read_utf8(args_ptr, args_len) {
Ok(s) => s,
Err(e) => return pack_json(&err_json(&e)),
};
SESSION.with(|cell| {
let mut guard = cell.borrow_mut();
let Some(sess) = guard.as_mut() else {
return pack_json(&err_json("no session — call mq_boot first"));
};
match sess.call(&name, &args) {
Ok(value) => {
let stdout = sess.take_stdout();
let value_json = match value_as_json(&value) {
Ok(j) => j,
Err(e) => return pack_json(&err_json(&e)),
};
pack_json(&json!({
"ok": true,
"stdout": stdout,
"error": null,
"value": value_json,
}))
}
Err(e) => pack_json(&err_json(&format!("{e:#}"))),
}
})
}
/// Package version (NUL-terminated C string in static memory — do not free).
#[no_mangle]
pub extern "C" fn mq_version() -> *const u8 {
concat!(env!("CARGO_PKG_VERSION"), "\0").as_ptr()
}
fn read_utf8(ptr: *const u8, len: usize) -> Result<String, String> {
if ptr.is_null() || len == 0 {
return Ok(String::new());
}
let bytes = unsafe { slice::from_raw_parts(ptr, len) };
String::from_utf8(bytes.to_vec()).map_err(|e| format!("not utf-8: {e}"))
}
fn run_to_json(source: &str) -> serde_json::Value {
let mut opts = RunOptions::default();
opts.allow_fs_write = false;
opts.allow_exec = false;
opts.allow_net = false;
opts.sleep_limit_ms = Some(0);
match run_source(source, &opts) {
Ok(cap) => match value_as_json(&cap.value) {
Ok(value) => json!({
"ok": true,
"stdout": cap.stdout,
"error": null,
"value": value,
}),
Err(e) => err_json(&e),
},
Err(e) => err_json(&format!("{e:#}")),
}
}
fn err_json(msg: &str) -> serde_json::Value {
json!({
"ok": false,
"stdout": "",
"error": msg,
"value": null,
})
}
fn pack_json(v: &serde_json::Value) -> *mut u8 {
let s = v.to_string();
let bytes = s.as_bytes();
let total = 4 + bytes.len();
let out = mq_alloc(total);
if out.is_null() {
return ptr::null_mut();
}
unsafe {
let len = bytes.len() as u32;
ptr::copy_nonoverlapping(len.to_le_bytes().as_ptr(), out, 4);
ptr::copy_nonoverlapping(bytes.as_ptr(), out.add(4), bytes.len());
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_hello_json() {
let v = run_to_json("# main\n\n> print text=Hello World!\n");
assert_eq!(v["ok"], true);
assert_eq!(v["stdout"], "Hello World!\n");
}
}
+62 -4
View File
@@ -15,24 +15,82 @@
| 文档 | 摘要 |
|------|------|
| [design/markdown-mapping.md](design/markdown-mapping.md) | **v0.1 语法宪法** |
| [design/markdown-mapping.md](design/markdown-mapping.md) | **v0.2 语法宪法(现行运行时)** |
| [design/markdown-mapping-v0.3.md](design/markdown-mapping-v0.3.md) | **v0.3 草案:叙述统一 · 粗体代码 · 斜体返回 · 形参体推断** |
| [adr/0005-prose-unified-markup.md](adr/0005-prose-unified-markup.md) | **Proposed:采纳 mapping v0.3** |
| [roadmap/markup-v0.3.md](roadmap/markup-v0.3.md) | **Markup v0.3 实现路线(M0–M5)** |
| [design/objects.md](design/objects.md) | **`#` 对象 / `##` 函数与方法** |
| [design/ai-skill.md](design/ai-skill.md) | **AI 接入 Skill**([`skills/marqdo/`](../skills/marqdo/)) |
| [design/code-vs-comment.md](design/code-vs-comment.md) | 叙述 / 可执行 / 外联 |
| [design/return-hr-and-code-surface.md](design/return-hr-and-code-surface.md) | 语句/返回/输出决议 |
| [design/generated-yaml-manifest.md](design/generated-yaml-manifest.md) | 生成式 OKF 清单 |
| [design/generated-yaml-manifest.md](design/generated-yaml-manifest.md) | 生成式 OKF 清单(早期方向) |
| [design/okf.md](design/okf.md) | **Marqdo OKF 实现规范**(catalog v0 + 任务知识包) |
| [design/catalog-cli.md](design/catalog-cli.md) | **`marqdo catalog` / `sync` OKF 清单命令** |
| [design/tech-stack.md](design/tech-stack.md) | 实现栈对比 |
| [adr/0001-implementation-language.md](adr/0001-implementation-language.md) | **Accepted:Rust 参考解释器;不用 Flex/Bison** |
| [design/dependencies.md](design/dependencies.md) | 依赖详单(无 Flex/Bison) |
| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置 `print` `input`** |
| [design/keywords.md](design/keywords.md) | **英文最小关键字 / 内置函数** |
| [design/keywords-i18n.md](design/keywords-i18n.md) | **内核中英双名(无需导入;少而精)** |
| [design/module-namespace.md](design/module-namespace.md) | **模块命名空间:导入绑定库名、`库.成员` / `use`(M1+M2 已落地)** |
| [design/stdlib.md](design/stdlib.md) | **标准库:内置 + `lib/` + 错误约定** |
| [design/stdlib-i18n.md](design/stdlib-i18n.md) | **标准库中英命名:靠库文件名区分,无 lang 开关** |
| [design/stdlib-modules.md](design/stdlib-modules.md) | **L1:文件/系统/时间/JSON/网络/数学/外联/插件** |
| [design/stdlib-mid.md](design/stdlib-mid.md) | **中层 Mid M1–M6(已落地)** |
| [design/stdlib-mid2.md](design/stdlib-mid2.md) | **中层 Mid2:datetime / url / toml / html / fs++** |
| [design/stdlib-datetime.md](design/stdlib-datetime.md) | **`lib/datetime`(Mid2 M7)** |
| [design/stdlib-url.md](design/stdlib-url.md) | **`lib/url`(Mid2 M7)** |
| [design/stdlib-toml.md](design/stdlib-toml.md) | **`lib/toml`(Mid2 M8)** |
| [design/stdlib-html.md](design/stdlib-html.md) | **`lib/html`(Mid2 M8)** |
| [design/stdlib-fs-mid2.md](design/stdlib-fs-mid2.md) | **`lib/fs` Mid2 M9 加厚** |
| [design/stdlib-stats-log.md](design/stdlib-stats-log.md) | **`lib/stats` + log.fields(Mid2 M10)** |
| [research/stdlib-gaps-after-mid.md](research/stdlib-gaps-after-mid.md) | **Mid 之后缺口盘点**(对照 Python/Go) |
| [roadmap/stdlib-mid.md](roadmap/stdlib-mid.md) | **Mid M1–M6 路线(done)** |
| [roadmap/stdlib-mid2.md](roadmap/stdlib-mid2.md) | **Mid2 M7–M10 路线(规划)** |
| [design/stdlib-math.md](design/stdlib-math.md) | **数学库(数值/随机/作图/轻量求解)** |
| [design/stdlib-foreign.md](design/stdlib-foreign.md) | **外联胶水(\`\`\`lang 具名块)— 已落地** |
| [design/ext-abi.md](design/ext-abi.md) | **原生插件 C ABI v1**(`lib/plugin`) |
| [design/ext-llm.md](design/ext-llm.md) | **官方扩展 `ext/llm`(OpenAI 兼容)** |
| [design/ext-agent.md](design/ext-agent.md) | **官方扩展 `ext/agent`(文档驱动:单步 / 多步工作簿 + 自写回;废弃 thin TOOL 循环)** |
| [design/ext-agent-plan.md](design/ext-agent-plan.md) | **`## 多步` / `## plan` 锁定设计**(工作簿文件、subtask 执行、修订循环、`step` 默认写回) |
| [design/ext-cli.md](design/ext-cli.md) | **`marqdo ext list/add/remove` 官方扩展安装器** |
| [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** |
| [design/ext-web-go-rewrite.md](design/ext-web-go-rewrite.md) | **`plugins/web` Go 全量重写**(多语言 ABI · 网页制备完备 · anlian 验收) |
| [adr/0004-web-plugin-go.md](adr/0004-web-plugin-go.md) | **Accepted:web 原生插件实现语言为 Go** |
| [research/ext-web-customization-limits.md](research/ext-web-customization-limits.md) | **`ext/web` 定制限制踩坑盘点**(路由/壳 CSS/鉴权/样式/部署) |
| [design/ext-web-customization/](design/ext-web-customization/) | **对应解决设计**(C0–C4:前缀可让出、shell_css、gate、布局…) |
| [design/web-assets-and-images.md](design/web-assets-and-images.md) | **W8:favicon / Head 资源表 / 图片装配**(一次补齐) |
| [design/web-asgi-servers-and-marqdo.md](design/web-asgi-servers-and-marqdo.md) | **Daphne/Uvicorn 等 vs Marqdo**:不能直接托管;反代 + axum `listen` |
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
| [design/examples-and-tests.md](design/examples-and-tests.md) | **tests/ 金样例目录布局** |
| [design/view.md](design/view.md) | **`marqdo view` / `view output` 黑白极简 + 静态文档** |
| [design/user-site.md](design/user-site.md) | **用户站:`public/` → `gh-pages`** |
| [design/catalog-cli.md](design/catalog-cli.md) | **`marqdo catalog` / `sync` OKF 清单命令** |
| [design/view-debug.md](design/view-debug.md) | **`marqdo debug` 独立调试页** |
| [design/vscode-extension.md](design/vscode-extension.md) | **VS Code 扩展:分支 `vscode-extension`(main 不跟踪源码)** |
| [design/vscode-extension-commit.md](design/vscode-extension-commit.md) | **扩展提交约定(禁止在 main 提交 `vscode-extension/`)** |
| [design/bytecode.md](design/bytecode.md) | **M5 字节码 / 双后端** |
| [design/pipeline-debug.md](design/pipeline-debug.md) | **流水线 `--dump-*` 可视调试** |
| [dev-setup.md](dev-setup.md) | 开发环境配置(Rust M0) |
| [roadmap/interpreter.md](roadmap/interpreter.md) | 正经解释器路线图 |
| [roadmap/next-phase.md](roadmap/next-phase.md) | **下一阶段:input / 诊断 / 标准库 / view 调试** |
| [roadmap/okf-near-match.md](roadmap/okf-near-match.md) | **规划:OKF 相近任务命中**(精确 sig 之外的可选软复用) |
| [roadmap/agent-streaming.md](roadmap/agent-streaming.md) | **流式输出**(SSE + `complete`/`step` stream;S0–S1 已落地) |
| [roadmap/object-inheritance.md](roadmap/object-inheritance.md) | **对象继承**(`# 子类 = > 父类`;I0–I2 已落地) |
| [roadmap/tables-maps-footnotes.md](roadmap/tables-maps-footnotes.md) | **表格语义**(竖表 / 横表字典 / 脚注取元 / 行向记录 / **单元格表达式 T5**) |
| [design/table-cell-expressions.md](design/table-cell-expressions.md) | **表数据单元格 = 表达式**(同调用实参值语法;Accepted) |
| [roadmap/browser-wasm.md](roadmap/browser-wasm.md) | **浏览器 WASM 路线 C(C0–C5 Completed)** |
| [roadmap/browser-wasm-d.md](roadmap/browser-wasm-d.md) | **路线 D:作者零 JS 前端(Completed)** |
| [roadmap/browser-wasm-e.md](roadmap/browser-wasm-e.md) | **路线 E:前端能力补齐(Completed)** |
| [roadmap/browser-wasm-f.md](roadmap/browser-wasm-f.md) | **路线 F:媒体/文件/Canvas 等(Completed,F1–F5;v0.3.3)** |
| [design/browser-marqdo-wasm.md](design/browser-marqdo-wasm.md) | **浏览器 Marqdo(WASM)设计** |
| [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) |
| [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 |
| [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** |
| [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** |
| [research/ext-hosting-gaps.md](research/ext-hosting-gaps.md) | **宿主集成缺口**:同域 SSE 中继 · HTTP→`##` · MCP Server · 副端口 · 跨模块 db/corpus |
| [design/ext-hosting-fill.md](design/ext-hosting-fill.md) | **宿主缺口补齐设计**(`ext/web` proxy/invoke · `ext/ai` mcp_server) |
| [roadmap/ext-hosting.md](roadmap/ext-hosting.md) | **宿主集成 H0–H4**(规划) |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** |
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
+57
View File
@@ -0,0 +1,57 @@
# ADR 0002:浏览器内 Marqdo = WASM 解释器(路线 C)
| | |
|---|---|
| 状态 | **Accepted** |
| 日期 | 2026-09-01 |
| 决策者 | chaungming + 协作 |
| 相关 | [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) · [interpreter.md](../roadmap/interpreter.md) · [0001](0001-implementation-language.md) |
---
## 背景
`ext/web` 已把站点装配成「源码以 `.mq.md` 为主、服务端 Rust 解释执行」。作者面仍缺**浏览器内**的同一语言:事件、局部状态、客户端 fetch/WS 回调今天要么手写 JS,要么完全不做。
候选路线:
| 代号 | 做法 |
|------|------|
| **A** | 服务端驱动 + 极薄固定增强(类 HTMX) |
| **B** | 把 Marqdo **编译/翻译成 JavaScript** |
| **C** | 把 **Rust 解释器/字节码 VM 编成 WASM**,浏览器跑同一套语义 |
产品叙事目标:**网络项目源码树可以只有 `.mq.md`**(JS/WASM 为生成或发行物,不是第二作者语言)。
---
## 决策
1. **选定路线 C**:浏览器内运行 **与主机同构的 Marqdo 语义**(parse → tree 和/或 bytecode VM),制品为 `marqdo.wasm` + 极薄 JS 宿主桥。
2. **不选定 B 作为主路径**:翻译到 JS 易语义漂移,长期要维护两套后端;B 至多作实验,不替代 C。
3. **A 不对立**:内容站 / SSR / 表单 POST 仍以服务端 `ext/web` 为主;C 负责「必须在客户端执行的 Marqdo」。
4. **同一内核、两套宿主**:`server`(今日 CLI + axum 插件)与 `browser`(DOM / `fetch` / 定时器 / storage);**不是**把 axum、`plugins/web`、SQLite 服务端塞进浏览器。
5. **另开设计与路线图**(见相关链接);实现按 **C0→C5** 切片,金样对齐主机行为。
6. **与「编译 mq.md → WASM 机器码」区分**:本 ADR 是 **解释器/VM 上 WASM**;把 `.mq.md` 直接编译成独立 wasm 模块仍属 `interpreter.md` Phase III 可选项,**另案**,不替代本决策。
---
## 后果
- 核心库必须可 **feature-gate** 掉 `libloading` / `ureq` / `tiny_http` / TTY `libc` 等,以便 `wasm32-unknown-unknown` 链接。
- 新增公共 API:`run_source`(内存源码 + 可选导入图),供 WASM 与测试共用。
- 浏览器侧宿主 API 以表驱动「交互装配」暴露(对称于 `样式装配`);`ext/**` 仍不直接调 `host_*`。
- 发行物可包含 `.wasm` / 生成的 loader;**作者仓库可不提交手写业务 JS**。
- view 断点 / 静态文档站调试可复用同一 WASM 解释器(与 `next-phase.md` 所述一致)。
---
## 否决 / 非目标(本 ADR)
| 方案 / 目标 | 原因 |
|-------------|------|
| 以 B(编译到 JS)为主交付 | 语义双轨;与「一种语言」冲突 |
| 浏览器内完整复刻 `plugins/web` 服务器 | 协议与权限模型不同;服务端仍 axum |
| 浏览器 `dlopen` 原生插件 | WASM 无 POSIX 动态库模型 |
| v1 消灭一切 JS 字节 | 胶水与发行 loader 允许存在;禁止的是**业务手写 JS** |
| 用 Daphne/ASGI 托管 Marqdo | 已否决,见 [web-asgi-servers-and-marqdo.md](../design/web-asgi-servers-and-marqdo.md) |
+48
View File
@@ -0,0 +1,48 @@
# ADR 0003:浏览器异步 I/O(fetch / 定时)— 效应表 + 续体回调
| | |
|---|---|
| 状态 | **Accepted** |
| 日期 | 2026-09-01 |
| 决策者 | chaungming + 协作 |
| 相关 | [0002-browser-marqdo-wasm.md](0002-browser-marqdo-wasm.md) · [browser-marqdo-wasm.md](../design/browser-marqdo-wasm.md) · [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
---
## 背景
Marqdo 调用面今日以**同步**为主。浏览器 `fetch` / `setTimeout` 是异步的;若在 WASM 里阻塞等待,会卡死 UI,且 `wasm32-unknown-unknown` 无真实阻塞 HTTP。
C3 已有:`mq_call` 返回 Map(如 `set_text`)由官方 bridge 执行。C4 在同一通道上扩展异步效应。
---
## 决策
1. **不**在语言内核引入 async/await 关键字或假同步 `fetch`。
2. 处理器返回值可含**效应字段**(与 `set_text` 并列),由 **JS bridge** 执行:
- `fetch`: `{ url, method?, then, headers?, body? }`
- `after`: `{ ms, then }`(定时续体)
3. 异步完成后 bridge 调用 `mq_call(then, payload)`:
- fetch 成功/失败:`{ ok, status, body, error? }`
- after:`{ ok: true }`
4. 能力默认关网络语义仍由**返回效应**显式开启(站点作者主动返回 `fetch`);CORS / 鉴权仍是浏览器与服务端责任。
5. 服务端 `lib/net` / `plugins/web` **不变**;本 ADR 仅浏览器 WASM 宿主。
---
## 后果
- 作者用表格/Map 声明「请求谁、完成后调谁」,无手写业务 JS。
- Bridge 必须串行处理效应(先 `set_text`,再调度 `fetch`/`after`)。
- 深层 Promise 链靠多次 `then` 回调;不在 C4 做通用 async 运行时。
---
## 否决
| 方案 | 原因 |
|------|------|
| WASM 内同步阻塞 `fetch` | 卡死主线程;平台不支持 |
| 编译期把 Marqdo 译成 async JS | 回到路线 B |
| 在核心加 `await` 关键字 | 违反 Markup-as-Syntax / 关键字纪律 |
+28
View File
@@ -0,0 +1,28 @@
# ADR 0004:网络拓展库原生实现改为 Go
| | |
|---|---|
| Status | **Accepted** |
| Date | 2026-09-10 |
| Related | [ext-web-go-rewrite.md](../design/ext-web-go-rewrite.md) · [ext-abi.md](../design/ext-abi.md) · [0001-implementation-language.md](0001-implementation-language.md) |
## Context
- Marqdo **宿主/解释器**仍为 Rust(ADR 0001 不变)。
- 官方插件契约是稳定 **C ABI**(`include/marqdo_abi.h`),不绑定 Rust ABI。
- `plugins/web`(Rust/axum)已具备 W0–W8 等能力,但迭代成本高;且需验证多语言插件生态。
- 产品目标:网络拓展库支撑完整网页制备,并以暗恋见君(外接 PostgreSQL + Redis)验收;应用层前后端均为 Marqdo 脚本。
## Decision
1. **重写** `plugins/web` 为 **Go** 共享库(`-buildmode=c-shared`),产物名仍为 `libweb.so` / `web.dll` / `libweb.dylib`。
2. **ABI 全量兼容**(函数名、参数、语义);`ext/web` 作者面默认不动。
3. 施工图:[ext-web-go-rewrite.md](../design/ext-web-go-rewrite.md)。禁止在旧 Rust 插件上继续打补丁演进(ext-web C5)。
4. 其它官方插件(agent / quantum / linalg)**暂不**强制改语言;Go web 作为多语言样板。
## Consequences
- 构建与发版需安装 Go;CI/`marqdo ext add web` 增加 `go build` 回退。
- 根 Cargo workspace 不再包含 `plugins/web` Rust crate(切换完成后)。
- cgo/共享库生命周期与 `shutdown` 需严格测试。
- 金样例 `tests/ext/web-*` 为门禁。
+53
View File
@@ -0,0 +1,53 @@
# ADR 0005:叙述统一的 Markup 映射(粗体即代码 · 斜体即返回 · 形参体推断)
| | |
|---|---|
| Status | **Accepted** |
| Date | 2026-09-13 |
| Related | [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md) · [markdown-mapping.md](../design/markdown-mapping.md) · [return-hr-and-code-surface.md](../design/return-hr-and-code-surface.md) · [roadmap/markup-v0.3.md](../roadmap/markup-v0.3.md) |
## Context
- Marqdo 的产品承诺是「代码即文档 / 文档即代码」:`.mq.md` 打开是文章,运行是程序。
- v0.2([markdown-mapping.md](../design/markdown-mapping.md))为消歧做了硬隔离:无标记 = 注释;`*…*` = 语句;`**…**` = 返回;调用必须 `>`;形参必须 `` + `名` ``。
- 该隔离使叙述与程序**视觉割裂**;且与 AI/Markdown 习惯相反(模型偏好用 `**` 强调「要做的事」)。
- 产品方重新审视后,希望合法化如下写法:
```markdown
## 加一函数
对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。
# main
> 加一函数 37
或者可以直接这么调用**加一函数 37**
```
## Decision
1. 采纳 **Markup 映射 v0.3** 为下一版语言宪法草案,全文见 [markdown-mapping-v0.3.md](../design/markdown-mapping-v0.3.md)。
2. **角色对调**:`**…**` = 代码段(含可省略 `>` 的调用);`*…*` = 返回值。
3. **叙述中的** `` `名` ``:**首次未赋值 = 声明变量**;未使用不报错;**仅当可执行面读取时升为形参**(见设计 §4.4 · §8.2)。不设「提及性」专用语法。
4. **形参默认由函数体/叙述推断**(升参);`` + `名` `` 仅作迁移兼容。
5. **`>` 调用面保留**(可选)。
6. **空返回**用标记而非关键字:推荐 `---` / `***`;显式 `*None*` / `*无*`;整行 `**`;兼容 `****`(设计 §7.2)。
7. **不做 v0.2 双模式兼容**(摸索阶段允许破坏性变更);旧 `.mq.md` 须改写。
8. 金样例门禁:`tests/markup-v03/`;存量 suite 随后迁移。
## Consequences
### Positive
- 叙述与代码共用 Markdown 习惯,文档可读性上升。
- 更贴合 AI 生成粗体「操作」的偏好,降低错用标记。
- 去掉形参表仪式,函数更像「带名字的说明段落」。
### Negative / Risks
- **破坏性**:与 v0.2 金样例、Skill、教程、大量 `lib/`/`ext/` 源码不兼容,必须分波迁移或双模式。
- 段内扫描与形参推断增加解析/语义复杂度——空返回与升参规则已在设计 §7.2 / §8.2 钉死;其余 §12 项用金样例收口。
- view/catalog/LSP 高亮规则需同步。
### Neutral
- `#` / `##` 对象体系、标准库、插件 ABI、关键字最小集不变。
- 输出仍是 `print` / `打印`,不是粗体/斜体。
+29
View File
@@ -0,0 +1,29 @@
# Marqdo AI Skill
| | |
|---|---|
| 状态 | 已提供 |
| 日期 | 2026-08-05(初版)· 2026-08-28(ext/web 完结复核 · ext/quantum Q8) |
| 路径 | [`skills/marqdo/`](../../skills/marqdo/)(权威);Cursor 镜像 [`.cursor/skills/marqdo/`](../../.cursor/skills/marqdo/) |
---
## 目的
让接入方(Cursor Agent、其它支持 Agent Skills 的模型宿主)在**加载本 skill 后**即可按 v0.2 语法正确编写 / 修改 `.mq.md`,并在使用 **`ext/web` 动态站** 或 **`ext/quantum` 电路/可视化** 时遵循官方作者面(不混中英 API、不写 JSON 袋胶水;量子绘图须引用 `kind=`/`theme=` 字符串)。
## 内容
| 文件 | 用途 |
|------|------|
| `SKILL.md` | 必读:硬规则、标记表、**ext/web**、**ext/quantum(Q7/Q8)**、工作流、反模式 |
| `reference.md` | 按需:CLI、stdlib/ext 索引、web/quantum API 摘要 |
| `examples.md` | 按需:可复制样例(§13 最小站点 · §14 纠缠实验) |
## 使用
- **本仓库 Cursor**:项目 skill 已在 `.cursor/skills/marqdo/`;描述含 `.mq.md` / Marqdo 触发词,可自动选用。
- **其它 AI**:将 `skills/marqdo/` 整目录作为 skill 包导入,或把 `SKILL.md` 贴进系统/项目说明并允许模型按需打开 `reference.md` / `examples.md`。
- **校验**:生成后执行 `marqdo run <file>.mq.md`,按 `path:line:col` 诊断迭代。
语法真相仍以 [markdown-mapping.md](markdown-mapping.md) 与 [keywords.md](keywords.md) 为准;skill 是面向模型的压缩操作手册。
+54
View File
@@ -0,0 +1,54 @@
# 方括号标记调用与前置修饰语
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-09-14 |
| 相关 | [call-arguments.md](call-arguments.md) · [collection-access-link.md](collection-access-link.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) |
---
## 1. 动机
无标记时,修饰语+函数名与函数名+实参都是词列,**无法消歧**。消歧标记必须来自 Marqdo 语法,**不能**依赖任一自然语言词法(「的」、形容词位置等)。
## 2. 形状
```text
修饰语… [函数名] 实参…
```
| 例子 | 含义 |
|------|------|
| `[问候] marqdo` | 调用 `问候`,位置实参 |
| `礼貌 [问候] marqdo` | 另加 `礼貌=True` |
| `正式 礼貌 [问候] marqdo` | `正式=True` `礼貌=True` |
| `[结账摘要] 品名="拿铁" 杯数=2` | 仅具名实参 |
| `[问候] ([格式化] `名字`)` | 嵌套:内层整段用 `()` |
旧形保留:`> 问候 …`、`**问候 …**`、`礼貌=True` 显式具名。
## 3. 与取元 / foreach
| 形状 | 语义 |
|------|------|
| `[X](Y)`(`]` 后**紧邻** `(`) | 取元 |
| `[X]`(`]` 后不是 `(`) | 函数名标记 |
| `- [X](Y)` | foreach |
## 4. 修饰语绑定
- `[` 前按空白切开;每段为标识(可 `` `名` ``)。
- 降为 `Named(名, Bool(true))`,再与 `]` 后实参合并。
- 与显式同名具名冲突 → 诊断。
- **核心不剥语言词缀**;形参叫 `礼貌` 则写 `礼貌 [问候]`。
## 5. AST
`CallExpr.pre_modifiers: Vec<String>`;求值/字节码在绑参前展开。
## 6. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-09-14 | 初稿并落地 |
+397
View File
@@ -0,0 +1,397 @@
# 浏览器 Marqdo(WASM 解释器)设计
| | |
|---|---|
| 状态 | **Accepted(设计锁定)** · 实现见路线图 C0–C5 |
| 日期 | 2026-09-01 |
| ADR | [0002-browser-marqdo-wasm.md](../adr/0002-browser-marqdo-wasm.md) |
| 路线图 | [roadmap/browser-wasm.md](../roadmap/browser-wasm.md) |
| 相关 | [ext-web.md](ext-web.md) · [bytecode.md](bytecode.md) · [web-assets-and-images.md](web-assets-and-images.md) · [table-cell-expressions.md](table-cell-expressions.md) |
---
## 0. 一句话
**源码只有 `.mq.md`;浏览器跑与 CLI 同构的 Marqdo VM(WASM);JS 只做宿主桥与加载器,不做业务语言。**
---
## 1. 目标与非目标
### 1.1 目标
| # | 目标 |
|---|------|
| G1 | 浏览器内执行合法 `.mq.md`(至少 `# main` + 打印/绑定/分支/循环/表/调用) |
| G2 | 与主机 **tree**(及后续 **bytecode**)金样在共享子集上 stdout/返回值一致 |
| G3 | 作者用 GFM 表声明交互(选择器 / 事件 / 调用),对称于 `样式装配` |
| G4 | 仓库源码树可不含业务 `.js`;允许提交或由工具生成 `marqdo.wasm` + 官方 loader |
| G5 | `import lib/…` 在浏览器可用(嵌入式 `lib/` 或打包进 wasm) |
### 1.2 非目标(本波 / C0–C3)
| # | 非目标 |
|---|--------|
| N1 | 在浏览器复刻 axum、`web_listen`、SQLite 服务端、admin UI |
| N2 | `plugin.load` 加载原生 `.so` / 浏览器内 dlopen |
| N3 | 把整站 `plugins/web` ABI 原样搬进 WASM |
| N4 | 把 `.mq.md` 编译成独立机器码 WASM(异于「解释器上 WASM」) |
| N5 | 强制内容站必须加载 WASM(纯 SSR 站可继续零客户端逻辑) |
---
## 2. 架构
```
┌─────────────────────────────────────────────────────────┐
│ Page (HTML shell from ext/web SSR or static) │
│ ┌──────────────┐ ┌─────────────────────────────────┐ │
│ │ DOM / CSS │ │ Official JS loader (thin) │ │
│ └──────▲───────┘ │ - WebAssembly.instantiate │ │
│ │ bridge │ - marqdo_run_source / on_event │ │
│ │ └──────────────┬──────────────────┘ │
│ │ │ │
│ │ ┌──────────▼──────────┐ │
│ │ │ marqdo.wasm │ │
│ │ │ parse → load → │ │
│ └──────────────│ Interpreter | Vm │ │
│ host_dom_* │ HostContext(browser)│ │
│ host_fetch_* │ embedded lib/ │ │
│ └─────────────────────┘ │
└─────────────────────────────────────────────────────────┘
Server (unchanged):
marqdo run / plugins/web (axum) — SSR, DB, auth, full site
```
**原则:** 一套语言语义;**HostContext 分型**(`native` vs `browser`),不是两套语法。
---
## 3. 与现有流水线对齐
主机今日(见 `src/lib.rs`):
```
path → fs::read → load_module → Interpreter|Vm → HostContext(native)
```
浏览器目标:
```
source: &str (+ optional import map)
→ load_module_from_memory
→ Interpreter|Vm (capture stdout)
→ HostContext(browser caps)
→ { ok, stdout, value_json, error }
```
公共库 API(C0/C1 必须落地):
| API | 职责 |
|-----|------|
| `run_source(source, opts) -> Result<RunCapture>` | 无路径入口;cwd/fs_root 虚拟 |
| `RunOptions` 浏览器默认 | `allow_fs_write=false`, `allow_exec=false`, `allow_net=false`(net 经显式 bridge 再开) |
| `load` 导入 | `lib/**` → `embedded_lib`;用户模块 → JS 注入的 `HashMap<path, source>` |
后端优先级:
1. **C1:tree**(与默认 CLI 一致,调试简单)
2. **C2+:bytecode** 可选(体积/性能;金样双后端)
---
## 4. Cargo / 制品布局
### 4.1 Feature 门(核心 crate `marqdo`)
| Feature | 默认(native) | `wasm-core` | 作用 |
|---------|----------------|-------------|------|
| `cli` | on | off | `main` / clap 仅 bin |
| `view` | on | off | `tiny_http` 文档浏览器 |
| `net-host` | on | off | `ureq` HTTP 客户端 |
| `plugin-host` | on | off | `libloading` 原生插件 |
| `exec-host` | on | off | `std::process` / foreign |
| `fs-host` | on | off | 真实磁盘读写(可读可后续经 VFS 桥) |
| `wasm-core` | off | on | 浏览器子集编译开关 |
`wasm32-unknown-unknown` 构建:**不得**链接 `libloading`、`ureq`、`tiny_http`、TTY `libc`。
### 4.2 包
| 路径 | 角色 |
|------|------|
| `marqdo`(根) | 核心;feature-gate |
| `crates/marqdo-wasm` | `cdylib`:`mq_*` ABI + `js/marqdo-bridge.js` |
| `ext/web` 或 `web/browser` | L1:`浏览器.运行` / `交互装配`(C3+) |
| `examples/browser-hello/` | 静态页 + wasm 冒烟 |
| `tests/browser/` 或金样脚本 | Node/wasmtime 跑 `run_source` 对齐 |
发行:`marqdo wasm build`(C2 CLI 糖)或 `wasm-pack build crates/marqdo-wasm`。
---
## 5. 宿主能力矩阵
| 能力 | Native | Browser C1 | Browser C3+ |
|------|--------|------------|-------------|
| `print` / 捕获 stdout | ✓ | ✓ → 可镜像 `console` | ✓ |
| `input` | stdin / preset | **仅 preset / JS 喂入** | 可选 prompt 桥 |
| builtins / 表 / 算术 | ✓ | ✓ | ✓ |
| `lib/math` `lib/json` `lib/collection` | ✓ | ✓(embedded) | ✓ |
| `lib/fs` 真磁盘 | ✓ | ✗ 明确报错 | 可选 OPFS/VFS 桥 |
| `lib/net` ureq | ✓ | ✗ | `fetch` 桥(异步模型见 §7) |
| `plugin.load` | ✓ | ✗ | ✗(改 L1 浏览器专用) |
| `exec` / foreign | ✓ | ✗ | ✗ |
| DOM / 事件 | ✗ | stub | **交互装配** |
| `sleep` | thread | 0 或 JS timer(异步) | timer |
错误策略:**显式失败**(诊断字符串含 `unavailable in browser wasm`),禁止静默空成功。
---
## 6. 交互装配(C3,对称样式装配)
### 6.1 作者面(示例)
```markdown
---
import json:lib/json.mq.md
---
# main
*`count` = 0*
`wire` =
| @ | 选择器 | 事件 | 调用 |
|---|--------|------|------|
| 1 | "#bump" | click | bump |
**`wire`**
## bump
*`count` = count + 1*
*`label` = > str count*
*`patch` = > json.set map=None key="#count" value=label*
**> json.set map=None key="set_text" value=patch**
```
`# main` 的返回值是 **wire 表**(`@` 行向记录列表)。Loader 调用 `mq_boot`,再 `wireEvents`。
### 6.2 桥约定
| 步骤 | API |
|------|-----|
| 启动 | `mq_boot(source)` → `{ ok, value }`;`value` = wire 列表或 `{ wire: [...] }` |
| 事件 | Loader `addEventListener` → `mq_call(fn, {"event":"click"})` |
| 回写 | 返回 Map 可含 `set_text`: `{ "#sel": "text" }`(仅 `textContent`) |
行键名认:`选择器`/`selector`、`事件`/`event`、`调用`/`call`。
含 `/` 的 CSS 等单元格仍 **引号优先**(见 [table-cell-expressions.md](table-cell-expressions.md))。
L1 `浏览器.交互装配`(ext)可后置;C3 以 bridge + 返回 wire 表即可验收。
---
## 7. 异步模型(C4)
锁定:[ADR 0003](../adr/0003-browser-async-effects.md)。
处理器返回 Map 可含(与 `set_text` 并列):
| 字段 | 含义 | 完成后 `mq_call` 实参 |
|------|------|----------------------|
| `fetch` | `{ url, method?, then, headers?, body? }` | `{ ok, status, body, error? }` |
| `after` | `{ ms, then }` | `{ ok: true }` |
Bridge:`applyEffects(exports, value)` — 先 DOM,再调度异步;**不**在 WASM 内阻塞。
示例见 `examples/browser-hello/fetch.mq.md`。
---
## 8. 安全
| 项 | 规则 |
|----|------|
| 默认能力 | 无磁盘写、无 exec、无任意 net |
| 源码来源 | 同源或构建时嵌入;不默认 `eval` 远程不可信脚本除非站点显式开启 |
| DOM | 仅经装配表/白名单 API;不暴露任意 `innerHTML` 字符串执行第三方脚本 |
| CSRF / Cookie | 浏览器 Marqdo **不替代**服务端鉴权;cookie 仍走 HTTP |
---
## 9. 与 `ext/web` 分工
| 层 | 负责 |
|----|------|
| 服务端 `plugins/web` | 路由、DB、会话、SSR HTML、样式/头/图装配 |
| 页面壳 | `头装配` 挂 `module` → `marqdo-bridge.js`;`static` 提供 `.wasm` |
| 浏览器 L1 | `客户端挂载` / `client_embed`;效应约定见 ADR 0003 |
| 核心 / crate | `run_source`、`BrowserSession`、`marqdo-wasm` ABI |
挂载示例:
```markdown
`头` =
| 关系 | 地址 |
|------|------|
| module | /static/marqdo-bridge.js |
*p = > page.头装配 表=头*
```
```bash
marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
# app.static dir=static
```
业务页再 `boot` 自己的 `.mq.md`(见 `examples/browser-hello/`)。
---
## 10. 测试与验收
| 级 | 内容 |
|----|------|
| 单元 | `run_source("…# main\n> print…")` native 与 wasm 同测 |
| 金样子集 | `tests/structure/hello.mq.md` 等无 fs/net/plugin 的样例 |
| 浏览器冒烟 | `examples/browser-hello`:按钮点击 → Marqdo 函数 → 改 DOM 文本 |
| 回归 | CI:`cargo test` native;另 job `wasm-pack build` / `cargo check --target wasm32-unknown-unknown --no-default-features --features wasm-core` |
---
## 11. 文档与技能同步
- ADR 0002、本文、路线图 C0–C5。
- `.cursor/skills/marqdo/SKILL.md`:补充「浏览器 WASM / 交互装配 / 引号 CSS」。
- `CHANGELOG`:Unreleased 记录设计锁定与各 C 完成项。
---
## 12. 风险
| 风险 | 缓解 |
|------|------|
| wasm 体积过大 | `release-wasm` profile(`opt-level=z` + LTO + strip);`marqdo wasm build` 打印 KiB,有则跑 `wasm-opt -Oz` |
| 异步拖垮语言 | ADR 0003 效应表;不阻塞 WASM |
| Feature-gate 伤 native | 默认 features = 今日行为;CI 全绿再合 |
| 作者误以浏览器替代服务器安全 | 文档强调鉴权在服务端 |
| 会话要 bytecode | **未做**:`BrowserSession` 固定 tree(缺 entry-env invoke);`run_source` 已支持 bytecode |
---
## 14. C5 硬化(已落地)
| 项 | 状态 |
|----|------|
| `profile.release-wasm` + `marqdo wasm build` 体积报告 | done(~0.9 MiB) |
| 可选 `wasm-opt` | done |
| `run_source` bytecode 金样 | done |
| 规范 bridge + 构建拷贝 | done(`crates/marqdo-wasm/js/`) |
| Node ABI 冒烟 | done(`tests/wasm`) |
| 站点 `头装配` / L1 `client_embed` | done |
| 会话 bytecode / view 断点复用 | **非本版目标** |
---
## 16. 路线 D — 作者零 JS(Active)
路线图:[browser-wasm-d.md](../roadmap/browser-wasm-d.md)。
**原则:** 业务与交互 100% `.mq.md`;`marqdo-bridge.js` 仅宿主胶。作者仓库可不含自写 `.js`。
### 16.1 一键挂载
| API | 含义 |
|-----|------|
| `mount({ wasmUrl, source \| sourceUrl, … })` | `loadWasm` → `boot` → `wireEvents` → 初始效应 |
| `script[data-mq-source-url]` / `data-mq-wasm` | 模块脚本属性自启 |
| `#marqdo-boot` | `application/json` 配置块 |
| `data-mq-playground` | 官方 playground(`#src,#run,#out`),仍非业务 JS |
`ext/web`:`client_embed` / `客户端挂载` 参数 `bridge`、`wasm`、`source`、`boot`(默认 true)。
```bash
marqdo wasm build -o static # marqdo_wasm.wasm + marqdo-bridge.js
# app.static dir=static
# intro 或主区嵌入 > web.client_embed source="/static/client.mq.md"
```
### 16.2 DOM / 表单效应(D3)
与 `set_text` / `fetch` / `after` 并列(白名单;**默认无**任意脚本注入):
| 字段 | 作用 |
|------|------|
| `set_text` | `textContent` |
| `set_value` | input/textarea/select 的 `value` |
| `set_attr` | 属性;值为 `null`/`false` 则 `removeAttribute` |
| `set_class` | `className` 字符串 |
| `toggle_class` | `{ "#sel": "cls" }` 切换 class |
| `set_html` | **仅**键前缀 `#trusted` 的选择器才写 `innerHTML`;其它键忽略 |
Wire 行可选 `值选择器` / `value_from`:事件触发时把该节点内容写入实参 `value`。
事件实参默认含:`event`、`value`、`checked`、`id`(来自 event.target);`submit` 另含 `fields` 表单字典。
L1:`web.dom_patch` / `网页.DOM补丁` 合并效应键;`web.text_patch` / `网页.文本补丁` 快捷 `set_text`。
### 16.3 非目标(D)
| # | 非目标 |
|---|--------|
| D-N1 | 用 Marqdo 重写 bridge 自身 |
| D-N2 | 作者手写业务 JS / TS(官方桥内机制允许) |
| D-N3 | ~~开放无前缀的 set_html~~(E 已允许任意选择器;内容由 MQ 产出) |
---
## 17. 路线 E — 前端能力补齐(Active)
路线图:[browser-wasm-e.md](../roadmap/browser-wasm-e.md)。
**原则:** 唯一硬禁是**作者手写业务 JS**。官方 bridge 可实现列表装配、路由、storage、WebSocket、内部模板/轻量 VDOM 等;作者只写 `.mq.md` + 效应表。
| 波 | 要点 |
|----|------|
| E1 | `set_style` / `focus` / `blur` / `scroll_into`;wire `委托`;键盘事件 |
| E2 | `set_html` / `replace_children` / `render_list` |
| E3 | `navigate` + `popstate`(选择器 `window`) |
| E4 | `storage` `{ op, key, value?, scope?, then? }` |
| E5 | `ws` `{ op: open\|send\|close, … }` |
| E6 | `fetch_all` / `interval` / `clear_interval` / fetch `fields` |
### 17.1 效应速查(E)
| 字段 | 含义 |
|------|------|
| `set_style` | `{ "#sel": { color: "red" } }` 或 `{ "#sel": "color:red" }` |
| `focus` / `blur` | `"#sel"` 或选择器数组 |
| `scroll_into` | `"#sel"` |
| `set_html` / `append_html` / `replace_children` | 写/追加 HTML(MQ 产出;XSS 自负) |
| `render_list` | `{ "#sel": { tag, items } }` |
| `remove` | 选择器或数组,删除节点 |
| `add_class` / `remove_class` | classList |
| `navigate` | `{ url, replace?: bool }` |
| `storage` | `{ op, key, value?, scope?: local\|session\|cookie, days?, then? }` |
| `ws` | `{ op: open\|send\|close, … }` |
| `fetch_all` | `{ requests: []\|map, then }` |
| `interval` / `clear_interval` | 定时 |
| `clipboard` / `download` | 剪贴板 / 触发下载 |
| `fetch.fields` | → FormData |
Wire 列:`委托` / `delegate` = 在容器上监听,目标须 `closest(delegate)`;选择器 `window` 绑 `window`。
## 15. 决策摘要
| 问题 | 答案 |
|------|------|
| 路线? | **C**:解释器/VM → WASM |
| 作者语言? | 仅 `.mq.md` |
| JS 角色? | Loader + 宿主桥 |
| 服务端? | 保留;不塞进浏览器 |
| 第一步实现? | C0 门控可编译 + C1 `run_source` 打印闭环 |
+2 -1
View File
@@ -67,7 +67,8 @@
| `keywords/bool-logic` | ✅ | ✅ |
| `structure/nested-call` | ✅ | ✅ |
| `structure/positional-call` | ✅ | ✅ |
| `structure/import/*` | ✅ | ✅(load 合并 AST 后编译) |
| `structure/import/*` | ✅ | ✅(导入模块树后编译) |
| `structure/ns/*` | ✅ | ✅ |
| `tests/errors/*` | ✅(非零退出) | 同 tree 语义(编译期/运行期诊断) |
核心金样例双后端已对齐;后续可扩展 Op、优化与更好的调试信息。
+25 -12
View File
@@ -2,9 +2,9 @@
| | |
|---|---|
| 状态 | 已定(v0.1 增补) |
| 日期 | 2026-08-04 |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords.md](keywords.md) |
| 状态 | 已定(v0.1 增补;2026-09-14:方括号标记调用) |
| 日期 | 2026-08-07 |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords.md](keywords.md) · [module-namespace.md](module-namespace.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md) |
---
@@ -16,35 +16,48 @@
|------|------|------|
| **具名**(保留) | `> 问候 谁=Marqdo` | `名=值`;值可含空格(至下一 `名=`) |
| **位置**(新增) | `> 问候 Marqdo` | 按形参声明顺序绑定 |
| **方括号标记**(增补) | `礼貌 [问候] Marqdo` | `[函数名]` 消歧;`[` 前裸词 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md) |
二者可混用:位置实参按「尚未被具名绑定的形参」从左到右填充。具名不可绑定同一形参两次;位置实参不得出现在「已出现具名实参」之后(对齐常见「位置在前、关键字在后」习惯)。
二者可混用:位置实参按「尚未被具名绑定的形参」从左到右填充。具名不可绑定同一形参两次;位置实参不得出现在「已出现具名实参」之后(对齐常见「位置在前、关键字在后」习惯)。前置修饰语与显式同名具名冲突则报错。
---
## 2. 文法(调用尾部)
```
call_tail ::= callee arg*
call_tail ::= bracket_call | classic_call
bracket_call ::= modifier* '[' callee ']' arg*
classic_call ::= callee arg*
arg ::= named | positional
named ::= ident '=' value
positional ::= value_token
positional ::= value_token | '(' call_tail ')'
modifier ::= ident # 展开为 ident=True;核心不剥语言词缀
```
- `]` 后**紧邻** `(` → **取元** `[key](collection)`,不是 callee 标记(见 [collection-access-link.md](collection-access-link.md))。
- 嵌套调用:把内层整段放进 `()`,例如 `[问候] ([格式化] "x")`。
- `value`(具名右侧):可含空格与 `` `var` `` 插值,直到下一个 `ident=` 边界。
- `value_token`(位置):空白分隔的一个词法单元——数字、`` `名` ``、标识/文本词;**不含空格**。多词字符串请用具名,例如 `> print text=Hello World!`。
- 内置 `print` 形参名为 `text`:`> print Hi` 与 `> print text=Hi` 等价。
- 实参值中 `` `变量` `` 后**紧跟** `[^…]` 时按**脚注取元**解析(可链式),而非文本:`> print text=苹果单价:`水果价格`[^苹果]`、`> print text=`订单`[^2][^品名]`。
- **独立 `>` 调用**:裸词 = 文本字面量。
- **`*…*` / `**…**` 段内的调用**(如 `*x = > text.split value=src sep=","*`):裸词 = **变量**(Python 统一命名空间),文本字面量必须加引号(`value="a,b"`);`` `名` `` 变量形式仍合法。
- 内置 `print` / `打印` 形参:`text` ≡ `内容`。
- `input` / `输入`:`prompt` ≡ `提示`。
- `len` / `长度`、`str` / `文本`、`int` / `整数`:`value` ≡ `值`。
- 完整中英双名见 [keywords-i18n.md](keywords-i18n.md)。
---
## 3. 绑定算法
1. 收集具名 → 映射;冲突则报错。
2. 按函数形参表顺序:若具名已提供则用之,否则取下一个位置实参。
3. 位置实参有余、或必填形参仍缺 → 报错(内置 `input` 的 `prompt` 可缺省)。
4. 用户函数:额外具名键仍写入调用环境(便于扩展);位置实参不可超过形参数目。
1. 将前置修饰语展开为 `名=True` 具名(与显式具名冲突则报错)。
2. 收集具名 → 映射;冲突则报错。
3. 按函数形参表顺序:若具名已提供则用之,否则取下一个位置实参。
4. 位置实参有余、或必填形参仍缺 → 报错(内置 `input` 的 `prompt` 可缺省)。
5. 用户函数:额外具名键仍写入调用环境(便于扩展);位置实参不可超过形参数目。
---
## 4. 金样例
见 `tests/structure/positional-call.mq.md` 与更新后的 `tests/structure/import/`。
见 `tests/structure/positional-call.mq.md`、`tests/structure/bracket-call.mq.md`、`tests/structure/ns/`(点号路径 / `use`)与 `tests/structure/import/`(导入解析)。
+32 -33
View File
@@ -2,18 +2,18 @@
| | |
|---|---|
| 状态 | 已定(v0 命令落地) |
| 日期 | 2026-08-04 |
| 状态 | 已定(O1 + O3:工程目录包 + agent-kb 概念并入) |
| 日期 | 2026-08-07 |
| 取代 | [generated-yaml-manifest.md](generated-yaml-manifest.md) 中「待决:sync/doc 命令」的命令名部分 |
| 相关 | [generated-yaml-manifest.md](generated-yaml-manifest.md) · [view.md](view.md) · [okf-and-marqdo.md](../research/okf-and-marqdo.md) |
| 相关 | [okf.md](okf.md)(**实现规范总览**)· [generated-yaml-manifest.md](generated-yaml-manifest.md) · [view.md](view.md) · [okf-and-marqdo.md](../research/okf-and-marqdo.md) |
---
## 1. 决策(重申)
YAML / OKF 风格清单是**从 `.mq.md` 派生的生成物**,不是手写配置。详见 [generated-yaml-manifest.md](generated-yaml-manifest.md)。
YAML / OKF 风格清单是**从 `.mq.md` 派生的生成物**,不是手写配置。完整词汇、任务知识包与路线图见 [**okf.md**](okf.md)。生成式方向见 [generated-yaml-manifest.md](generated-yaml-manifest.md)。
本文件规定 **CLI 与 v0 落盘格式**。
本文件规定 **CLI 与工程目录包落盘格式**(含 O3:扫入本地 `agent-kb` 概念,供人与工具同览)。
---
@@ -28,26 +28,31 @@ marqdo sync [PATH] -o OUT_DIR
| 参数 | 默认 | 说明 |
|------|------|------|
| `PATH` | `.` | 工程根或含 `.mq.md` 的目录(递归扫描) |
| `-o` / `--out` | `.marqdo` | 生成目录(写入前创建;**覆盖**同名生成文件) |
| `-o` / `--out` | `.marqdo` | 生成目录(写入前创建;**覆盖**同名生成文件;扫描时跳过该目录) |
退出码:成功 0;无可扫描文件或 IO/解析失败非 0(单文件解析失败时写入 `diagnostics` 并继续其余文件,最终若有失败则非 0)。
---
## 3. 生成物(v0)
## 3. 生成物
```
OUT_DIR/
catalog.yaml # 机器向总清单(OKF 风格字段)
index.md # 人/Agent 可读总览(含 YAML frontmatter)
index.md # 人可读总览:Modules + Agent knowledge
modules/
<stem>.md # 每个 .mq.md 一个概念页(frontmatter + 摘要)
<stem>.md # 每个工程 .mq.md 一个 Module 页
concepts/ # 从 **/.marqdo/agent-kb/concepts/ 复制(O3)
tasks/…
skills/…
```
路径中的目录层级拍扁为文件名时用 `__` 连接,例如:
`structure/import/main.mq.md` → `modules/structure__import__main.md`
`.marqdo/agent-kb/` 下的可执行 `.mq.md` **不**进 Module 表(由 Task/Skill 概念页的 `resource` 指向)。
### 3.1 `catalog.yaml`(示意)
```yaml
@@ -55,12 +60,11 @@ OUT_DIR/
type: Marqdo Catalog
title: marqdo-project
generated:
by: marqdo/0.0.1
# at: 可选 ISO8601;CI 比对时可忽略
by: marqdo/0.1.2
modules:
- id: structure/hello
resource: structure/hello.mq.md
title: Hello World # 来自源 frontmatter title,缺省用文件名
title: Hello World
imports: []
exports:
- name: Hello World
@@ -72,35 +76,28 @@ modules:
exports:
- name: main
kind: fn
concepts: [] # 有 agent-kb 时为 Task/Skill 条目列表
```
字段约定(v0 最小集):
| 字段 | 含义 |
|------|------|
| `type` | 固定 `Marqdo Catalog`(OKF:未知 type 可降级) |
| `modules[].resource` | 相对 `PATH` 的源路径 |
| `modules[].imports` | 源 frontmatter 中的 `> *.mq.md` |
| `modules[].exports` | 顶层 `#` 函数名(`kind: fn`);嵌套 `##` 列入 `children`(可选,v0 可扁平只列顶层) |
| `modules[].exports` | 顶层 `#` 函数名(`kind: fn`) |
| `modules[].verified` / `sources` | 源 frontmatter 有则透传(O3) |
| `concepts[]` | 本地 agent-kb 概念摘要(`id`/`type`/`page`/…) |
| `generated.by` | `marqdo/<crate version>` |
不在 v0:版本锁定哈希、跨仓 URL、完整符号类型。
不在现行范围:版本锁定哈希、跨仓 URL、完整符号类型、`log.md`(见 okf O4)。
### 3.2 模块概念页 frontmatter
### 3.2 模块概念页
```yaml
---
type: Marqdo Module
title: …
resource: structure/hello.mq.md
depends: [] # imports 列表
exports: [Hello World]
generated:
by: marqdo/0.0.1
---
```
Frontmatter 仍用 `depends` 字符串列表(机器可读);**正文 Dependencies** 链到同包其它 Module 页(人可点)。源若带 `verified` / `sources` 则写入页头。
正文含「请勿手改」提示、依赖列表、导出列表;可链到同包其它模块页。
### 3.3 Agent knowledge
`index.md` 的 **Agent knowledge** 节列出扫到的 Task/Skill,链到 `concepts/…`。概念页内容从本地 `agent-kb` **复制**,与 Agent 运行时包同源,便于人审阅晋升结果。
---
@@ -109,7 +106,7 @@ generated:
| 命令 | 产物 | 受众 |
|------|------|------|
| `marqdo view output` | 静态 HTML(结构 + 运行结果) | 人类读程序文档站 |
| `marqdo catalog` | OKF 风格 YAML + Markdown 索引 | 工具 / Agent / 依赖总览 |
| `marqdo catalog` | OKF 风格 YAML + Markdown 索引(含 agent-kb) | 人浏览依赖/技能 · 工具 / Agent |
二者都从同一源树生成,互不替代。发布用户文档时可同时:
@@ -122,7 +119,9 @@ marqdo catalog tests -o .marqdo
## 5. 验收
1. `marqdo catalog tests -o /tmp/mq-cat` 写出 `catalog.yaml` 与 `modules/`。
1. `marqdo catalog tests -o /tmp/mq-cat` 写出 `catalog.yaml`、`modules/`、`concepts:` 键。
2. `catalog.yaml` 含 `structure/hello` 与 import 模块的 `imports: [utils.mq.md]`。
3. 文件头或 `generated` 标明 GENERATED;文档声明勿手改。
4. `marqdo sync` 与 `catalog` 行为一致。
3. 模块页 Dependencies 对已解析导入为 Markdown 链接。
4. 若扫描根下有 `.marqdo/agent-kb/concepts/`,则复制进 `OUT_DIR/concepts/` 且 `index.md` 有 Agent knowledge 条目。
5. 文件头或 `generated` 标明 GENERATED;文档声明勿手改。
6. `marqdo sync` 与 `catalog` 行为一致。
+119
View File
@@ -0,0 +1,119 @@
# 代码即文档 · 叙述面摩擦(v0.3 实测)
| | |
|---|---|
| 状态 | **Done** |
| 日期 | 2026-09-14 |
| 触发 | `examples/code-as-docs/index.mq.md` 试跑 |
| 宪法 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) |
| 路线 | [code-as-docs-gaps.md](../roadmap/code-as-docs-gaps.md) |
---
## 0. 原则
修复必须同时服务:
1. **代码即文档**:人读 Markdown 时自然段落、分隔线、强调不应被误伤。
2. **适配 LLM 输出**:模型习惯写 `---` 分段、`**加粗强调**`、`0.85` 小数、`` map[^`key`] `` 动态键——运行时应尽量「写出来就能跑」。
3. **可执行标记仍清晰**:真正的赋值 / 调用 / 返回不被误判成装饰。
---
## 1. 四个问题(实测)
### G1 — 模块级 `---` 被当成结构错误
| | |
|---|---|
| 现象 | 文件标题段落后写 Markdown 分隔线 `---`,报 `expected heading … got: ---` |
| 根因 | 词法上整行 `-`/`*` 为 Code;旧实现把函数体内 `---` 当收束,模块顶却当非法。现统一为叙述跳过 |
| 人/LLM 期望 | 任意处 `---` = GFM thematic break = **叙述噪音** |
| 决议 | **处处** frame 行 skip;副作用收束用 `*None*` / `**` / `****`(返回即结束函数体解析) |
### G2 — 叙述里的 `**强调**` / `*斜体强调*` 被当成代码/返回
| | |
|---|---|
| 现象 | 「本文件既是**说明**也是**程序**」→ 粗体 `说明` 不是赋值/调用,解析失败;`*only*` 类英文强调升成返回/`only` 变量 |
| 根因 | v0.3 叙述扫描凡 `**…**` / `*…*` 一律可执行([prose.rs](../../src/parse/prose.rs));Skill 曾禁止强调,但与 LLM/Markdown 习惯冲突 |
| 人/LLM 期望 | 装饰性强调可出现;**像代码的**粗体/斜体仍执行 |
| 决议 | **形状启发式**(见 §2):像代码则执行,否则当作叙述装饰(不产生 Stmt,不升参) |
### G3 — 小数面量 `0.85` 不可用
| | |
|---|---|
| 现象 | `**x = 0.85**` → `trailing input: ".85"`;`28 * 0.85` 解析错乱;即便进到求值,`*` 仍只接受 int |
| 根因 | 表达式主词只吃整数字面量(`Literal` 无 `Num`);运行时已有 `Value::Num`,二元运算未接浮点 |
| 人/LLM 期望 | `0.85`、`3.14`、`折扣=0.85` 可写可算 |
| 决议 | 解析 `数字.数字` → `Literal::Num`;`*` `/` `+` `-` 及比较在 `Int`/`Num` 间提升(与已有 `cmp_ord` 一致) |
### G4 — 动态脚注键 `` 菜单[^`名`] ``
| | |
|---|---|
| 现象 | `` 菜单[^`名`] `` → `missing map key ``名`` `(把字面 `` `名` `` 当键,或解析失败) |
| 根因 | `[^label]` 的 label 仅为**静态字符串**;AST `Expr::Index { label: String }` 无变量槽 |
| 人/LLM 期望 | 表/映射按变量取键:`` `菜单`[^`品名`] `` 或 `菜单[^`品名`]` |
| 决议 | 支持 `` [^`ident`] `` → 运行时用变量值作键(文本化后走现有 footnote get);静态 `[^拿铁]` 不变 |
---
## 2. 粗体/斜体「像代码」启发式
### 粗体 `**inner**` → 可执行,当且仅当
满足任一:
- 含 `=`(赋值 / 命名参数调用);或
- 以 `>` 开头(显式调用);或
- 含运算符 / 索引 / 调用形:`+ - * / ( ) [ ]`;或
- 空白分词 ≥2 段,且其后段含数字面量、引号串、或 `=`(如 `**加一 37**`、`**print text="hi"**`)
否则(如 `**说明**`、`**代码即文档**`)→ **装饰,忽略**。
### 斜体 `*inner*` → 返回,当且仅当
满足任一:
- 空 / `None` / `无` / `空` / bool 字面;或
- 以 `>` 开头;或
- 含 `=` 或运算符 / 索引;或
- **整行**仅为 `*…*`(含缩进)——整行返回 `*总额*` / `*n*`;或
- 行内且前方紧邻「返回」二字(叙述「接着返回*n*」)
否则行内简单词(如 `*only*`、`*named*`)→ **装饰,忽略**。
> 整行 `*n*` 仍是返回;行内「返回*n*。」仍是返回。英文强调词在句中被忽略。
---
## 3. 非目标
- 不恢复 v0.2 双模式
- 不引入 `if`/`return` 关键字
- 不把任意 `**任意自然语言句子**` 都当代码(必须过 §2)
- 动态键第一期只做 `` [^`ident`] ``,不做完整表达式 `[^a+b]`
---
## 4. 验收
| 用例 | 期望 |
|------|------|
| 顶层段落之间的 `---` | 可解析、可运行 |
| 「既是**说明**也是**程序**」 | 可解析;无 Stmt |
| `**应付 = 原价 * 0.85**` / `折扣`=0.85 | 数值正确(浮点) |
| `` **价 = 菜单[^`名`]** ``(`名` 已绑定) | 取到对应价 |
| `examples/code-as-docs/index.mq.md` | 用回浮点折扣与动态键后仍绿 |
| 既有 `tests/markup-v03/*` 与 gold | 不回归 |
---
## 5. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-09-14 | 初稿:四缝 + 启发式 + 验收 |
| 2026-09-14 | 落地:G1–G4 实现 + 金样;顶层 Comment 引言 skip |
+16 -12
View File
@@ -2,8 +2,12 @@
| | |
|---|---|
| 状态 | 与 mapping v0.1 / keywords 对齐(成段注释) |
| 日期 | 2026-08-04 |
| 状态 | 与 mapping **v0.3** 对齐(现行运行时) |
| 日期 | 2026-09-14 |
| 取代 | 本文曾按 v0.2(`*语句*` / `**返回**`)叙述;旧对照见 [markdown-mapping.md](markdown-mapping.md) |
| 相关 | [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) §4 |
「Markup」在此仓库 = Marqdo **把 Markdown 标记映射成语法** 的那一层,不是另一个语言。
---
@@ -11,18 +15,18 @@
| 层 | 形态 | 角色 |
|----|------|------|
| **叙述面** | 成段注释(空行分段) | 注释;段内任意标记无语义 |
| **Marqdo 可执行面** | 结构标记 + `*语句*` + `**返回**` | 本语言程序 |
| **叙述面** | 普通段落 | 注释;行内 `` `名` `` 可声明/引用;装饰性 `**强调**` / `*斜体*` 不执行 |
| **Marqdo 可执行面** | 结构标记 + **`**代码**`** + **`*返回*`** | 本语言程序 |
| **外联面** | ` ```lang ` | 其它语言(FFI) |
输出属于可执行面里的**函数调用**(`> print …`),见 [keywords.md](keywords.md)。
输出属于可执行面里的**函数调用**(`> print …` / `**print …**`),见 [keywords.md](keywords.md)。
### 成段注释
- 以**空行**划分段落。
- 段首行:首字符非标记 → 注释。
- 段内续行:一律注释(即使以 `` ` `` / `-` 等开头)。
- 叙述段与可执行代码之间**必须空一行**,否则 `> print` 等会被吞进注释段。
- 段首行:首字符非标记 → 注释段;段内续行一律叙述(即使以 `` ` `` / `-` 开头)。
- 段内仍扫描行内可执行位:`` `名` ``、代码形 `**…**`、返回形 `*…*`。
- 叙述段与独立结构行(`>` `#`)之间**建议空一行**,否则 `> print` 可能被吞进注释段。
---
@@ -30,8 +34,8 @@
| 标记/形式 | 角色 | 是否架构级 |
|-----------|------|------------|
| `*…*` | 程序语句 | 是 |
| `**…**` | 返回值 | 是 |
| `****` / 空粗体 | 空返回 + 结束函数体 | 是 |
| `**…**` | 代码(赋值 / 调用 / 表达式语句) | 是 |
| `*…*` | 返回值(整行、`返回*n*`、或表达式形) | 是 |
| `****` / 整行 `**` / `*None*` | 空返回 + 结束函数体 | 是 |
| `> print …` | 打印副作用 | 否(内置函数) |
| 函数体 `---` / `***` | 结束函数体 | 是(边界) |
| 函数体 `---` / `***` | 叙述分隔(跳过,**不**结束函数体) | 否 |
+64
View File
@@ -0,0 +1,64 @@
# 集合取元:GFM 链接形
| | |
|---|---|
| 状态 | **Active(运行时)** |
| 日期 | 2026-09-14 |
| 相关 | [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) · [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) · [code-as-docs-gaps.md](code-as-docs-gaps.md) |
---
## 1. 决议
表达式取元的**主语法**为 Markdown 链接外形,与 foreach 同构:
| 角色 | 写法 |
|------|------|
| **取元(表达式)** | `[键](集合)` |
| **遍历(语句)** | `- [项](集合)`(不变) |
| **脚注取元(过渡)** | `` 集合[^键] `` 仍解析,新代码勿写 |
心智:**方括号 = 取出的名字,圆括号 = 从哪取。**
```markdown
**价 = [拿铁](菜单)**
**价 = [`名`](菜单)**
**第一 = [1](篮子)**
- [行](今日订单)
**名 = [品名](行)**
```
## 2. 细则
| 写法 | 语义 |
|------|------|
| `[拿铁](菜单)` | 静态键;`菜单` 为变量(粗体/斜体内) |
| `` [`名`](菜单) `` | 动态键(求值 `名` 再作键) |
| `[1](篮子)` | List **1-based** 下标(同脚注约定) |
| `[1]([苹果](货架))` | 嵌套链式 |
与 `- [项](集合)` 消歧:仅 **表达式位置** 的 `[…](…)` 为取元;`-` 行头仍为 foreach。
## 3. 迁移
`` `菜单`[^拿铁] `` / `菜单[^拿铁]` → `[拿铁](菜单)`(**基与键左右对调**)。
| 区域 | 约定 |
|------|------|
| 新代码 / examples / public | **只用**链接形 |
| `tests/structure/footnote*` · `interp-footnote*` | 脚注兼容门禁(保留) |
| 其余 structure / ext / lib 金样 | 已迁链接形 |
脚注路径保留至另行决定移除之日;Skill / 教程 / 新示例只用链接形。
## 4. 非目标
- 点号 map 访问、`在`、箭头取元、`(键)[集合]`
- 循环语法糖(`←` / `in` / 自然语言)
## 5. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-09-14 | 初稿并落地主语法 |
+6 -2
View File
@@ -41,7 +41,7 @@ Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这
│
├─① 行分类(自研) 无标记 → 注释;有标记 → 代码行
├─② GFM 块/行内(库) 标题、表、强调、列表结构
├─③ 行扫描补强(自研) 保留 '-' / '+';frontmatter `> file.mq.md`
├─③ 行扫描补强(自研) 保留 '-' / '+';frontmatter `import file:file.mq.md`
└─④ Marqdo 语法(自研) 递归下降:Module/Fun/Stmt/Expr → AST
└─ 表达式子语言 可手写,或仅对 Expr 用 pest/nom
```
@@ -80,7 +80,11 @@ Marqdo 换 **Rust 或 C++** 都不改变「主前端不该是 Flex/Bison」这
| **pulldown-cmark** *或* **comrak** | GFM 事件/AST | 标题、列表、表格、emphasis/strong;Spike 已证明「库 + 行扫描」可行。二选一做 Spike 对比后钉死 |
| **thiserror** / **anyhow** | 错误类型 | 诊断与 CLI 报错 |
| **clap** | CLI | `marqdo run [path]` |
| **serde** + **serde_yaml** | 元信息 | 仅解析 frontmatter 中的 YAML **键值**;`> x.mq.md` 仍按**行**抽取(见 Spike) |
| **serde** + **serde_yaml** | 元信息 | 仅解析 frontmatter 中的 YAML **键值**;`import x:x.mq.md` 仍按**行**抽取(见 Spike) |
| **ureq** (=2.9.7) | HTTP(S) | `lib/net`;为 Cargo 1.81 另钉 `idna_adapter`/`zeroize`(见根 `Cargo.toml`) |
| **regex** (=1.13.1) | 正则 | Mid M1 `lib/re`;`default-features=false` + `std`/`unicode`;无回溯引用 |
| **sha2** (=0.10.9) / **sha1** (=0.10.6) / **md-5** (=0.10.6) / **hmac** (=0.12.1) | 摘要 | Mid M3 `lib/hash` |
| **getrandom** (=0.2.17) | OS 熵 | Mid M3 `lib/secrets` |
#### 强烈建议
+14 -15
View File
@@ -3,7 +3,7 @@
| | |
|---|---|
| 状态 | 已定 |
| 日期 | 2026-08-04 |
| 日期 | 2026-08-07 |
| 原则 | **夹具即金样例**:`tests/{structure,keywords,errors}/**/*.mq.md` 由 `cargo test` / CI 跑通;`marqdo view tests` 也可浏览 |
---
@@ -16,19 +16,16 @@
tests/
README.md
gold.rs # 集成测试入口
structure/ # 代码基础结构(Markup 架构)
hello.mq.md
nested-call.mq.md
positional-call.mq.md
branch.mq.md
loop.mq.md
collection.mq.md
import/
main.mq.md
utils.mq.md
structure/ # 代码基础结构(Markup 架构 · v0.2)
…
keywords/ # 关键字与内置名
print.mq.md
bool-logic.mq.md
…
markup-v03/ # Markup 映射 v0.3 草案金样例(实现前 ignore)
README.md
inc-prose.mq.md
…
ext/
…
errors/ # 期望失败(诊断文案稳定后再加金样例)
…
```
@@ -42,8 +39,9 @@ tests/
| 类别 | 测什么 | 不测什么 |
|------|--------|----------|
| **structure** | `#`/`##`、形参、`>` 调用、`*`/`**`、`+`/`-`、表、导入、位置/具名实参 | 关键字边角 |
| **structure** | `#`/`##`、形参 `+`、`1.` 分支、`-` 循环、表、导入、点号路径 / `use`、位置/具名实参 | 关键字边角 |
| **keywords** | `True`/`False`/`None`、`and`/`or`/`not`、`print`/`input` 约定 | 复杂控制流(可极简) |
| **markup-v03** | v0.3:叙述声明、粗体代码、斜体返回、升参、空返回、双调用面(见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)) | 在 `--markup v0.3` 落地前 `#[ignore]` |
| **errors** | 未定义名、实参错误、语法错误的诊断 | 成功路径 |
未单独建夹、但应覆盖的其它测试(`src/**` 单测或日后 `tests/runtime/`):
@@ -51,7 +49,8 @@ tests/
- **流水线调试**:`--dump-lines` / `--dump-ast` / `--trace-eval`
- **CLI**:默认 `index.mq.md`、退出码
- **view**:目录扫描、单文件页、执行区(见 [view.md](view.md))
- **模块图**:循环导入拒绝
- **模块图**:循环导入拒绝;`errors/ns-instance-method`(实例方法路径)
- **ext live**:`ext/agent-run-live`(需 `.env` + `libagent`)
---
+105
View File
@@ -0,0 +1,105 @@
# Native plugin ABI (v2)
| | |
|---|---|
| Status | Accepted |
| Date | 2026-08-07 |
| Header | [`include/marqdo_abi.h`](../../include/marqdo_abi.h) |
| Related | [ext-agent.md](ext-agent.md) · [stdlib-modules.md](stdlib-modules.md) |
## Goals
- Optional **native** extensions as shared libraries (`.dll` / `.so` / `.dylib`).
- **Not** linked into the `marqdo` binary; load at runtime.
- Stable **C** ABI only (no cross-compiler Rust ABI for plugins).
- Official / local paths only — **no** third-party package registry.
- **v2**: allowlisted `host_query` so plugins can read entry source / call site / skill without baking agent logic into the core.
## Contract
`MARQDO_ABI_VERSION = 2` (host accepts plugins with version `1..=2`).
Every plugin exports:
| Symbol | Role |
|--------|------|
| `marqdo_plugin_abi_version` | `1` or `2` |
| `marqdo_plugin_init` | Register functions via `MarqdoHostApi` |
| `marqdo_plugin_shutdown` | Teardown |
Host provides `register_fn`, `alloc`, `free`, and (v2) `host_query`.
### Wire format
Arguments and results are **UTF-8 JSON**:
- Args: JSON object keyed by parameter names (from `params` CSV at registration).
- Result: any JSON value mappable to Marqdo `Value` (same rules as `lib/json`).
Plugin fn returns `0` + `*out_json` on success; non-zero + optional `*err_msg` on failure. Host frees both strings with the host `free`.
### `host_query` allowlist (v2)
| name | Result JSON | Notes |
|------|-------------|--------|
| `module_source` | string | Entry `.mq.md` text |
| `call_site` | `{path,function,line}` | Active call site |
| `marqdo_skill` | string | Skill pack text |
| `cwd` | string | Host `cwd` (entry file directory) for path resolution |
| `record_plot` | `{ok:true}` | Args `{svg}` + optional `path`; push SVG into host plots (view embed / CLI auto-write), same channel as math plots |
Unknown names fail. Queries are only valid during a plugin function call (host sets thread-local context).
## Marqdo surface (`lib/plugin` / `lib/插件`)
| English | Chinese | Host |
|---------|---------|------|
| `## load` (`path`) | `## 加载` (`路径`) | `host_plugin_load` |
| `## unload` | `## 卸载` | `host_plugin_unload` |
| `## list` | `## 列出` | `host_plugin_list` |
| `## native_path` (`name`) | `## 原生路径` (`名`) | `host_ext_native_path` |
```markdown
---
import plugin:lib/plugin.mq.md
---
# main
> load path=demo.dll
*`sum` = > demo_add a=1 b=2 *
> print text=`sum`
```
After `load`, registered names are callable like other functions (plugin registry lookup after fixed host fns, before user `#`/`##` defs).
**Path sandbox:** `path` resolves under the program’s cwd / `fs_root` (same as `lib/fs`). Absolute paths outside the root are rejected unless trusted (`MARQDO_EXT` / `MARQDO_AGENT_PLUGIN` / built `libagent.*`). Prefer `native_path name=agent` for the official agent plugin.
## Demo / agent
```bash
cargo build -p marqdo_plugin_demo
cargo build -p marqdo_plugin_agent
```
- Demo (ABI v1): `demo_add`, `demo_echo` — [`tests/lib/plugin-demo.mq.md`](../../tests/lib/plugin-demo.mq.md).
- Agent (ABI v2): … **OKF agent-kb** …
- Web (ABI v2): HTTP listen + SQLite/Postgres + page render (`web_listen`, `web_render`, `web_db_*`, …) — [`plugins/web`](../../plugins/web)(**Go 全量重写**,见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md) · [ADR 0004](../adr/0004-web-plugin-go.md));作者面 [`ext/web/web.mq.md`](../../ext/web/web.mq.md)。Lookup: `plugin.native_path name=web` / `MARQDO_WEB_PLUGIN` / `marqdo ext add web`.
## Layering
| Layer | May call `host_*` |
|-------|-------------------|
| `lib/*` | Yes (only L1 wrappers of generic L0.5) |
| `ext/*` | **No** — compose `lib/*` or ABI plugin names via `lib/plugin` |
| Application `.mq.md` | Prefer same as ext; do not add agent/OKF originals to `src/host` |
**Hard rule:** agent / OKF domain primitives live in `plugins/agent`, never in `HostFn` / `src/host/kb.rs`.
## Non-goals
- Embedding plugins in the release exe by default
- Callbacks from plugin into arbitrary Marqdo evaluation
- Arbitrary HostFn passthrough via `host_query`
- **Third-party** plugin / package registry
+150
View File
@@ -0,0 +1,150 @@
# 父智能体 Plan-and-Move(`## plan` 行动面)
| | |
|---|---|
| 状态 | **Accepted** |
| 日期 | 2026-08-11 |
| 父文档 | [ext-agent-plan.md](ext-agent-plan.md) · [ext-agent.md](ext-agent.md) |
| 相关 | [stdlib-subtask.md](stdlib-subtask.md) · [okf.md](okf.md) · [ai-skill.md](ai-skill.md) |
---
## 1. 一句话
**父智能体 = Plan-and-Move 控制器**:观察工作簿与子任务结果 → 规划下一步 → 行动(读 / 调工具 / 补丁 / 再跑 / 停);Marqdo「文档即代码」让工具、记忆与程序都落在 `.mq.md` 上。
---
## 2. 为何需要强化
单靠 `DECISION: DONE|CONTINUE|RUN` 时,父侧几乎没有「手」:
| 缺口 | 后果 |
|------|------|
| 看不到子源码 / 报错 / stdout | 空想 FIND/REPLACE,输出又臭又长 |
| 标准库未进入行动表 | 无法在规划环内用 `fs` / `json` / `subtask` 等 |
| 不能用 Marqdo 造工具 | 无法把可复用步骤沉淀为 `##` |
| 提示词过长且互相打架 | 模型「继续帮忙」而不停机 |
业界对 agent 回环的共识:成功标准、停机动作、**确定性行动面**三者必须写清;停机最终靠代码护栏,不只靠 prompt。
---
## 3. Marqdo 赋予的特性(相对通用 Plan-and-Move)
| 特性 | 含义 |
|------|------|
| 工作簿即程序 | 子执行物是可 `spawn path=` 的 `.mq.md`,不是隐式任务图 |
| 固化即记忆 | `DECISION: DONE` → `agent_workbook_solidify` + OKF 晋升 |
| `lib/*` 即工具 | 标准库是父可调度能力;经父 helper 或写入工作簿/`tools/` 后调用 |
| 补丁即改代码 | `CONTINUE` + 精确 FIND/REPLACE;禁止整文件 LLM 重写 |
| 文档即提示 | 站立提示、Skill 摘要、观察切片都是可读 Markdown,而非黑盒 system blob |
---
## 4. 循环形状(锁定)
```text
┌──────────────┐
│ Plan (LLM) │
└──────┬───────┘
│ 协议回复
┌─────────────┼─────────────┐
▼ ▼ ▼
READ:/CALL: DECISION: (无效 → error)
│ DONE/RUN/
│ CONTINUE
▼ ▼
Act 工具 Move(固化/补丁/spawn)
│ │
└──────┬──────┘
▼
Observe(有界)
│
└──► 回到 Plan 或终止
```
优先级(解析父回复时):
1. **`CALL:<name>` / `调用:`** — 跑父侧工具,结果并入 observation,再 Plan
2. **`READ:<kind>` / `读取:`** — 加深某一观察切片,再 Plan
3. **`DECISION:`** — Move(含运行时 solidify / apply_patch / spawn)
---
## 5. 观察面(有界、可加深)
`inspect_workbook` / `await_workbook` 在磁盘上可持有全文;**注入父 prompt 的默认紧凑观察**必须可行动且短:
| 字段 | 默认 | `READ:` 加深 |
|------|------|----------------|
| `source_excerpt` | 去 `<!-- … -->` 后的结构摘录,硬顶 ~4KiB / ~80 行 | `READ:source` → 更大但仍有硬顶的摘录 |
| `stderr_tail` / `stdout_tail` | 子任务捕获尾部 ~2KiB | `READ:stderr` / `READ:stdout` |
| `value` | ≤200 字;否则 `value_preview` + `value_len` | (一般不必加深) |
| `slots` | `{key,line,body_len}`;`error` 槽可带短预览 | `READ:slots` |
| `skill_brief`(父 / 子) | ~1.2KiB(`skill_brief`) | `READ:skill` → ~4KiB |
| `has_worker_step` / `solidify_on_done` | 布尔提示 | — |
`## step` 同样默认注入 **预算后的** `source_brief` + `skill_brief`(非全文);截断处带 `[truncated …; emit READ:…]` 标记,子轮最多 `max_reads` 次加深后再 CALL/作答。
`quiet=True` **只表示不污染父 TTY**;file `wait` 仍返回截断后的 `stdout` / `stderr` 供父观察。
---
## 6. 工具面
### 6.1 父侧内建 helper(`CALL:` 首批)
写在 `ext/ai/agent.mq.md`,由 plan 循环直接调度(**不用** OpenAI function calling):
| 名称 | 作用 |
|------|------|
| `workbook_read` | 按 depth 读工作簿摘录 |
| `workbook_excerpt` | 结构摘录(默认观察同源) |
| `lib_catalog` | 枚举 `lib/*.mq.md` 能力摘要 |
| `scratch_tool_write` | 写入 `.marqdo/agent-runs/tools/<name>.mq.md` |
| `corpus_search` | 本地语料关键词检索(RAG-lite;`ARGS.query` / `root`) |
| `mcp_list_tools` / `mcp_call` | MCP 形 JSON fixture 列工具 / 调用(离线证据) |
以上 **corpus / mcp** 返回一律带 `authority=workbook`:检索与外置工具只是证据,**可跑的 `.mq.md` 工作簿 / OKF 技能仍是权威真相**。
### 6.2 标准库与造工具
- **标准库直调(白名单)**:`CALL:lib.fs.read_text`(及 `exists` / `list_dir` / `json.parse` / `json.stringify` / `sys.cwd`)+ 可选 `ARGS:{…}` JSON 行;拒绝 `net.*` / `sys.exec` / 写删类。
- **目录**:`lib_catalog` 列出可 CALL 的 dotted 名。
- **造工具**:优先 `CONTINUE` + 短 PATCH 在工作簿内新增 `##`;或 `CALL:scratch_tool_write` 沉淀独立工具文件。
- **流式**:父 CALL/READ 发 `tool_start` / `tool_end`(view Tool 卡)。
- **非目标**:全量 `lib/*` JSON schema 反射;OpenAI function calling。
---
## 7. 输出纪律(停机规则)
父回复**只允许**协议行 + 一行 `SUMMARY` + 短 PATCH(`<20` 行)。禁止长独白 / 行程散文 / 把 observation 粘进 REPLACE。
修订阶段硬规则(自上而下):
1. `exit_code==0` 且 `has_value` → **立刻** `DECISION: DONE`(运行时 solidify);`has_worker_step` **不是** CONTINUE 的理由。
2. 仅失败 / 无值 / 明确未达目标时才 `CONTINUE`。
3. 代码护栏:非 `improve` 时,子已返回值则 **跳过父 LLM**,直接 solidify + DONE。
---
## 8. 与 `## step` 的关系
| | `step`(子) | `plan`(父) |
|---|-------------|-------------|
| 协议 | `CALL:` 或最终答案 | `CALL:` / `READ:` / `DECISION:` |
| 工具来源 | 工作簿 / 调用方 allowlist | 父 helper + 写入的 Marqdo `##` |
| 成功出口 | 返回答案文本 | `DONE` + solidify / promote |
---
## 9. 实现落点
| 组件 | 路径 |
|------|------|
| 设计(本文) | `doc/design/ext-agent-parent.md` |
| 多步总设计增量 | `doc/design/ext-agent-plan.md` §4.1 / 协议 |
| 子任务 I/O | `src/host/subtask.rs`、`lib/subtask.mq.md` |
| 父循环 / 观察 / 提示 | `ext/ai/agent.mq.md` |
+356
View File
@@ -0,0 +1,356 @@
# 智能体多步(`## 多步` / `## plan`)
| | |
|---|---|
| 状态 | **Accepted;D2a–D2f 已落地;父 Plan-and-Move / OKF 软命中见配套文档** |
| 日期 | 2026-08-11 |
| 父文档 | [ext-agent.md](ext-agent.md) |
| 相关 | [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move 行动面**) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [module-namespace.md](module-namespace.md) · [ai-skill.md](ai-skill.md) · [objects.md](objects.md) · [调研:主流框架与 Marqdo](../research/agent-frameworks-and-marqdo.md) |
---
## 1. 动机
单步(`## 单步` / `## step`)适合原子任务。复杂目标需要:
1. **把分解与执行过程落成一份可运行的 `.mq.md`**(工作簿),而不是藏在进程内的任务图。
2. **用子任务真正跑这份工作簿**,与主推理隔离。
3. **父智能体作为「智能体开发大师」**:结构化读取执行结果与写回,再二次规划;用**精确补丁**改工作簿代码,并把确定步骤**固化为普通 Marqdo `##`**。
4. **允许工作簿演化**——代码与 `<!-- marqdo-out … -->` 均可更新,但**禁止**以整文件 LLM 重写作为修订主路径。
5. 子智能体只做不确定的 `单步`;能写成代码的就不要再问模型。
本文锁定 **`## 多步` / `## plan`** 的语义。总览与分层见 [ext-agent.md](ext-agent.md);实现以 D2 为准。
---
## 2. 一句话
**多步 = 父智能体(开发大师)生成并演进一份子 Marqdo 程序:经 `lib/subtask` 运行它,结构化观察写回与源码,再二次规划并精确打补丁;子 `# 智能体` 只跑 `单步`,确定步骤固化为代码。**
---
## 3. 角色与产物
| 角色 | 职责 |
|------|------|
| **父智能体** | 持有目标;创建 / 改写工作簿;`spawn path=` 运行工作簿;读执行结果与写回块;决定改代码还是改提示;汇总并写回父文档 |
| **工作簿 `.mq.md`** | 任务实现的**详细步骤文档兼程序**:导入、工具、一个或多个子智能体、可固化的普通函数与 `# main` 编排 |
| **子智能体** | 工作簿内的 `# 智能体` / `# agent`;走 `单步`(默认);工具表白名单可收窄 |
| **子任务通道** | `lib/subtask`:`spawn path=<工作簿>` → `wait`;与工具 `spawn fn=` 同一套能力 |
| 产物 | 说明 |
|------|------|
| 工作簿路径 | 默认目录 `.marqdo/agent-runs/`(可参数覆盖);文件名含时间 / 短 id |
| 父侧返回值 | 结构化 map:`status`、`goal`、`workbook`(路径)、`result`(子 `# main` 返回值优先)、`summary` / `error`;可选 `observation` |
| 写回 | 工作簿内各 `单步` 默认落盘;父 `多步` 调用行亦可汇总写回 |
---
## 4. 调用流水线(锁定)
```text
父:`助手`.多步 目标=…
▼
① 解析参数(目录、深度、是否确认分解、是否覆盖已有工作簿…)
▼
② 创建(或打开)工作簿 .mq.md
- frontmatter:导入 ext/ai/llm|agent、json、writeback、subtask…
- **大模型配置与父智能体一致**(见 §5)
- 正文:总目标叙述 + 子智能体骨架 / 或父模型生成的首版步骤
▼
③ 父模型「分解」(非 OKF 命中路径必跑):`phase=decompose`,尚未 spawn;可 `DECISION: RUN` / `CONTINUE`+补丁 / 固化后 `DONE`
▼
④ lib/subtask:spawn path=<工作簿绝对或相对路径>
▼
⑤ wait → 收集 `{code, value}`(`# main` 返回)+ 工作簿内写回块;TTY 默认静默
▼
⑥ 父智能体 **结构化观察**(工作簿最新源码 + 写回槽 + 退出码 + `value`)
- 充分 → 汇总,写回父文档,返回
- 不足 / 失败 → **二次规划** → 对工作簿打**精确补丁**(禁止整文件重写)→ 回到 ④
▼
⑦ 触达最大修订轮次或深度 → 以 error / 部分摘要返回
```
要点:
- **创建文件发生在 `多步` 内**,不是调用方手写脚手架(调用方可传已有 `工作簿=` 路径以续跑)。
- **执行工作簿 = 子任务跑整文件**(入口 `# main`),不是父进程内嵌解释子 AST。
- **父是智能体开发大师**:读真实执行结果再规划;修订靠精确补丁与代码固化,不靠整文件重生。
- **修订循环属于父智能体职责**:同一 `多步` 调用内可多轮「观察 → 规划 → 补丁 → 再 spawn」。
---
## 4.1 观察面与补丁(锁定)
父每次二次规划前必须拿到观察 map(`inspect_workbook` / `await_workbook`)。磁盘可持全文;**注入父 LLM 的默认观察为有界紧凑面**(摘录 + I/O 尾部)。完整语义与 `READ:` / `CALL:` 行动面见 [ext-agent-parent.md](ext-agent-parent.md)。
| 字段 | 含义 |
|------|------|
| `path` | 工作簿路径 |
| `source` | 最新全文(磁盘);prompt 默认用 `source_excerpt` |
| `exit_code` | 上一轮子任务退出码 |
| `value` | 子 `# main` 返回值(经 `await_workbook` / `wait.value`) |
| `stdout` / `stderr` | 子任务捕获(`quiet` 仅静音 TTY,不丢弃数据) |
| `slots` | 命名写回列表(`key` + `body`) |
| `last_ok` / `last_error` | 便捷字段 |
二次规划输出协议(机器可解析;**禁止**只输出整份 `.mq.md`;**禁止**长独白):
```text
CALL:<parent-tool>
READ:source|stderr|stdout|slots
DECISION: DONE
SUMMARY: <一行>
DECISION: RUN
DECISION: CONTINUE
PATCH:
<<<
FIND
<确切旧片段>
===
REPLACE
<新片段>
>>>
```
解析优先级:`CALL` → `READ` → `DECISION`。应用器对文件做**精确** FIND→REPLACE;找不到则报错。`DONE` 时运行时 `agent_workbook_solidify` 固化答案(不必靠长 REPLACE 粘贴子散文)。
---
## 4.2 多轮哲学:仅子智能体接力(模式 C)
复杂 / 多轮目标 = **多份可执行 `.mq.md` 接力**,经 OKF 索引与复用;父 `plan` 聚合各子 `wait.value` 为 `result`。
| 做 | 不做 |
|----|------|
| 每主题 / 子目标一份工作簿(`resources/` / `explore/`) | 单文件无限追加「对话日志」 |
| OKF task/skill 做索引与命中 | 单文件状态机表冒充流程 UI |
| `# main` **返回**答案;`quiet` 只管 TTY | 依赖子 `print` 把答案刷到父终端 |
---
## 5. 大模型配置与父保持一致
工作簿内构造子智能体时:
| 从父继承 | 说明 |
|----------|------|
| `model` / `大模型` 句柄字段 | `api_key`、`base_url`、`model`、`suffix`、`bearer` 及拼装前缀等与父相同 |
| 默认站立提示基调 | 可追加「只负责本工作簿内子任务」等收窄句;不得更换供应商端点 |
实现约定(D2):
1. 父把当前 llm 句柄 **序列化进工作簿**(例如构造段直接写 `> llm.llm` 前先 `load_env`,或写入由父生成的配置表 / 环境约定)。
2. 优先:**工作簿与父共享同一套 `OPENAI_*` / `.env` 加载路径**,子文件内 `> llm.load_env` + `> llm.llm`(或中文面),避免把密钥明文写进工作簿。
3. 若父句柄来自非默认 env,父须在生成工作簿时写出等价构造(仍禁止把密钥写进 git 跟踪路径;工作簿目录应默认被 ignore)。
**禁止**:子工作簿默默改用另一 `base_url` / 另一模型名,除非调用方显式参数允许覆盖(v1 不提供覆盖;一律继承)。
---
## 6. 工作簿内容形态
### 6.1 推荐:多个子智能体
面对多种情形时,**多个 `# 智能体`(或一个类型多次构造)** 优于单一巨型提示:
```markdown
---
title: agent-run-…
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
import writeback:lib/writeback.mq.md
import subtask:lib/subtask.mq.md
---
# 总目标
(父写入的目标叙述)
## 工具甲
…
# main
> llm.load_env path=…
*`模型` = > llm.llm *
*`调研` = > agent.agent model=`模型` tools=`表甲` standing=… *
*`撰写` = > agent.agent model=`模型` tools=`表乙` standing=… *
*`a` = > `调研`.step task=… *
*`b` = > `撰写`.step task=… *
```
### 6.2 也可:一个智能体多次单步
适合线性流水线;每次 `step` 仍默认写回,便于中断续跑。
### 6.3 固化为代码(强烈推荐)
一旦某步输入输出稳定(例如「取今日日期」「解析固定 JSON」),父智能体应把该步 **改写成普通 `##` 函数 + 直接调用**,不再经子智能体推理:
| 不确定 | 已确定 |
|--------|--------|
| `` > `子`.step task=… `` | `` *`x` = > 本地函数 … `` |
| 宽工具表 + 长 standing | 窄函数、表驱动、分支 `1.` / `2.` |
**多步的价值之一就是把「试出来的正确步骤」沉淀成工作簿里的代码**,而不仅是 chat 痕迹。
### 6.4 持续更新的两类内容
| 更新 | 含义 |
|------|------|
| **代码更新** | 增删 `##`、改 `# main` 编排、改工具表、把 step 换成固化调用、修分支 |
| **写回注释更新** | `<!-- marqdo-out ok|error -->` 被单步 / 父汇总刷新;替换时**不得累积空行**(见 writeback 实现约定) |
工作簿是活文档:子任务跑完后磁盘上的 `.mq.md` 应比创建时更「像最终报告」。
---
## 7. 单步自动写回(服务多步)
### 7.1 决议
| | |
|---|---|
| **默认** | `单步` / `step` **自动写回** 本步结果(命名槽) |
| **开关** | 参数 `写回` / `writeback`(布尔,默认 `真` / `True`) |
| **槽** | 成功 → `key=ok`;失败 → `key=error`;正文为结构化 map 的 JSON(或与现 live 样例一致的 stringify) |
| **锚点** | 本步调用行(与现 `writeback.record` 锚点规则一致) |
这样:
- 父 / 工作簿**不必**靠提示词强迫模型「请记得写回」。
- 编排方仍可 `写回=假` 拿到纯 map,自行 `writeback.record`(测试、嵌套去重时有用)。
### 7.2 与父写回的分工
| 层级 | 写什么 |
|------|--------|
| 子 `step`(默认开) | 该步 decision / tool / result 或 error |
| 父 `plan` | 工作簿路径、轮次、汇总摘要;可选把关键子 ok 块索引写在父调用行下 |
**推荐**:载荷以子 `# main` 返回值(`wait.value` → `plan.result`)为准;写回作审计与 step 缓存。避免只靠 stdout(默认静默会丢弃)。
### 7.3 返回值
`step` 仍返回结构化 map(与现 D1 一致)。自动写回是**附加副作用**,不取代返回值。
---
## 8. 父智能体上下文(每次修订 / 汇总前)
父在多步循环中每次「想下一步」时,注入不得弱于单步,且额外包含工作簿:
| 片段 | 来源 |
|------|------|
| 站立提示 | 父构造 |
| 总目标 | `多步` 实参 |
| **父文件源码** | `agent_module_source` |
| **调用位置** | `agent_call_site` |
| **Marqdo Skill** | `agent_marqdo_skill` |
| 工作簿全文 / 写回 / 子返回 | `inspect_workbook`(源码 + slots + 退出码 + `value`) |
| 子任务退出码 | `subtask.wait` |
| 对话 / 历史 | 父 session;真相以写回为准 |
父模型输出必须是 **DONE / CONTINUE+精确补丁** 协议(见 §4.1),禁止整文件重写。
---
## 9. 公开 API(D2 契约)
### 9.1 `## 多步` / `## plan`
| 参数 | 中 / 英 | 默认 | 说明 |
|------|---------|------|------|
| 目标 | `目标` / `goal` | 必填 | 复杂任务描述 |
| 工作簿目录 | `工作簿目录` / `workbook_dir` | `.marqdo/agent-runs` | 新建文件所在目录 |
| 工作簿 | `工作簿` / `workbook` | 空 | 若给路径则**续跑 / 修订**该文件,跳过空白创建 |
| 最大深度 | `最大深度` / `max_depth` | `2` | 工作簿内再调 `多步` 的嵌套上限;叶强制单步 |
| 最大轮次 | `最大轮次` / `max_rounds` | 实现选定(如 `4`) | 父「改文件 → 再执行」循环上限 |
| 确认分解 | `确认分解` / `confirm` | `假` | `真` 时首版工作簿生成后暂停(返回 pending + 路径),不自动 spawn |
| 写回 | `写回` / `writeback` | `真` | 父侧汇总写回 |
| 骨架 | `骨架` / `skeleton` | `single` | `single` 单 worker;`dual` 为 research→writer 两子智能体 |
返回 map(字段名英文字段,中文面可读同一结构):
| 字段 | 含义 |
|------|------|
| `status` | `ok` / `error` / `pending`(待确认) |
| `goal` | 回显目标 |
| `workbook` | 工作簿路径 |
| `rounds` | 实际执行轮次 |
| `summary` | 成功时的汇总 |
| `error` | 失败信息 |
### 9.2 `## 单步` / `## step`(修订)
在 D1 参数上增加:
| 参数 | 默认 | 说明 |
|------|------|------|
| `写回` / `writeback` | `真` | 是否自动 `record` 到 ok/error 槽 |
### 9.3 内部辅助(非稳定对外)
工作簿模板渲染、从父句柄生成子文件 frontmatter、解析子写回摘要等——可随实现调整。
---
## 10. 安全与边界
| 风险 | 对策 |
|------|------|
| 无限修订 / 嵌套 | `最大轮次`、`最大深度`;叶任务禁止再 `plan` |
| 工作簿写爆仓库 | 默认目录 `.marqdo/agent-runs/` + gitignore;禁止默认写到 `lib/` / `ext/` |
| 密钥进工作簿 | 继承 env / load_dotenv,不写明文 key |
| 子文件乱改父仓 | 子任务 cwd / fs_root 落到工作簿目录;工具表白名单 |
| 写回空行膨胀 | 替换跨度含 `-->` 行尾换行(已实现) |
| 并发写同一工作簿 | writeback 全局锁;同一 plan 内串行 spawn 为 v1 默认 |
---
## 11. 与旧 §3.2 叙述的差异(显式)
| 旧粗述 | 本文锁定 |
|--------|----------|
| 分解表 + 每行一个子智能体实例 | **整文件工作簿**可含多智能体与固化代码;表只是可选骨架 |
| 子任务默认单步,写回在流水线步骤里点到为止 | **单步默认自动写回**;父负责修订循环与汇总 |
| 缓存命中略写 | **以 OKF 任务知识包为准**([okf.md §7](okf.md)):Task→Skill→resource 命中则跳过父模型;D2 + O2 已落地;人读目录见 O3 `marqdo catalog` |
| 父上下文未强调工作簿全文 | 父每次修订前必须能读**最新工作簿 + 写回** |
---
## 12. 实现路线(D2)
| 项 | 内容 |
|----|------|
| D2a | `step` 增加 `writeback=`(默认真);金样例改默认行为并保留 `writeback=False` 测例 | **done** |
| D2b | 工作簿模板 + 创建路径 + 父 llm 继承;`inspect_workbook` 观察面 | **done** |
| D2c | `plan`:生成 → `spawn path` → wait → **观察** → 返回;`confirm` | **done** |
| D2d | 二次规划 + **精确补丁**循环(`max_rounds`);禁止整文件重写 | **done**(主路径) |
| D2e | 多子智能体模板与固化提示 | **done**(`skeleton=dual` + Solidify 段 + 父规划优先级) |
| D2f | 离线骨架金样例 + 可选 live 多步 | **done**(decision 离线 + `agent-plan-live`) |
---
## 13. 决议摘要
1. **`多步` 自动创建(或续跑)工作簿 `.mq.md`**,内容为任务的详细可执行步骤。
2. **子文件大模型配置与父一致**(共享 env / 等价句柄;v1 无静默换模)。
3. **经 `lib/subtask` 启动该文件**;可多轮执行。
4. **工作簿内推荐多个智能体**;也允许单智能体多 `step`;**确定步骤固化为代码**。
5. **工作簿持续更新**:代码 + `marqdo-out`。
6. **`单步` 默认自动写回**(`写回=` 可关);父维护汇总写回。
7. **父具备源码、Skill、位置、历史与工作簿观察面**,二次规划后以**精确补丁**修改再执行(禁止整文件重写主路径)。
---
## 14. 一句话
**多步不是更长的聊天,而是父智能体编写、运行、修订一份子 Marqdo 程序——程序里的智能体可多可少,写回默认打开,能写成代码的就不要再问模型。**
+349
View File
@@ -0,0 +1,349 @@
# Official agent development framework (`ext/ai/agent`)
| | |
|---|---|
| Status | **Accepted · redesign**(取代「thin TOOL: loop」方案) |
| Date | 2026-08-07 |
| Related | [ext-llm.md](ext-llm.md) · [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md) · [**ext-agent-plan.md**](ext-agent-plan.md)(**多步锁定设计**) · [**ext-agent-parent.md**](ext-agent-parent.md)(**父 Plan-and-Move**) · [**okf.md**](okf.md)(**OKF / 任务知识包**) · [**调研:主流框架与 Marqdo 优势**](../research/agent-frameworks-and-marqdo.md) · [**缺口:A0–A4 之后**](../research/agent-framework-gaps-after-a4.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md) · [markdown-mapping.md](markdown-mapping.md) |
## 0. 为什么要改掉旧方案
旧版把智能体做成「黑盒对话循环」:隐藏提示拼装、`TOOL:<name>` 协议、host 历史袋、一次(或几次)模型往返。这是对 LangChain 类框架的平移,**背离了 Marqdo 的初衷**。
Marqdo 的宪法是 **代码即文档、文档即知识库**:
| 旧方案的问题 | Marqdo 应有的形态 |
|--------------|-------------------|
| 提示词藏在框架字符串里,与编排源码分离 | 提示、工具、任务、结果都在 `.mq.md` 里,人与模型同读同写 |
| 执行过程是不透明的 chat transcript | 思考与行动写回文档;`view` / `debug` 可跟可审 |
| 复杂任务与简单任务同一套循环 | **单步**与**多步(工作簿)**两级模型 |
| 成功经验留在进程内存 | **自写回**做成果缓存与失败知识;同类任务可复用 |
本文件锁定新方向。仓库里现有的 `ext/ai/agent.mq.md` / `智能体.mq.md`(TOOL: 薄循环)视为 **待替换实现**,以本文为准。
---
## 1. 我们在建什么
一个 **文档驱动的智能体开发框架**:编排本身就是可读的 `.mq.md`;模型吃的是这份文档与调用位置;写回让思考过程可控、可调试、可沉淀。
**不是** 外挂任务队列、**不是** 官方捆绑领域工具、**不是** 第二套聊天栈(模型 I/O 仍用 `ext/ai/llm`)。
| 在范围内 | 在范围外(应用 / runbook) |
|----------|---------------------------|
| `# 智能体` / `# agent` 构造 | 领域工具:`## 查天气`、`## 分配任务` … |
| `## 单步` / `## step` | 业务表格、队列、工单流程 |
| `## 多步` / `## plan`(生成并驱动工作簿) | 具体分解策略模板库(可放用户仓) |
| 上下文:源码、调用位置、工作簿路径、Skill | 第二套 HTTP / 聊天协议 |
| 与 `lib/writeback`、**`lib/subtask`(工具执行通道)**、**`lib/plugin` + ABI v2 `plugins/agent`** 协作 | 把领域技能塞进官方 `ext/ai/`;在 `ext` 内直调 `host_*` |
---
## 2. 核心理念:编排可读,过程可写回
1. **提示词与代码不分离**
站立提示、工具表、任务叙述都写在 `.mq.md` 里。框架把**当前模块源码**与**调用位置**交给模型,而不是另起一套 system prompt 黑盒。
2. **把 Marqdo 源码交给智能体**
每次推理可注入:入口 / 工作簿 `.mq.md` 全文(或相关切片)、`host_call_site`(路径、函数、行)、`skills/marqdo`(写 / 读 `.mq.md` 的语法纪律)。模型输出应优先是 **可解释的决策** 与 **对文档的结构化改动意图**,而不是私有 JSON 协议。
3. **自写回 = 思考轨迹 + 成果缓存**
成功或失败都写回文档(见 [stdlib-writeback.md](stdlib-writeback.md))。成功块可被后续同类任务命中,避免重复失败;失败块成为可读的「避坑记录」。`marqdo view` 在语句下展示 output-card,调试面可对齐同一份真相。
4. **相对其他框架的优势**
无需外挂向量库 / 状态机才能「记住」某次子任务已成功:记忆就是仓库里的 Markdown。审计、合规、复盘 = `git log` + 打开工作簿。
---
## 3. 两级执行模型
### 3.1 模式 A — 单步(原子任务)
| | |
|---|---|
| **输入** | 小任务描述 + 必要上下文(工具表、站立提示、源码切片) |
| **过程** | 一次(或有限次)推理;可选调用 **runbook 内** 的工具函数;结果写回 |
| **输出** | 原子结果(文本 / 表 / 句柄字段) |
| **适用** | 问答、单一工具、确定性一步 |
公开方法(中 / 英):`## 单步` / `## step`。
示意(语法外形;实现以落地代码为准):
```markdown
---
导入 智能体:ext/ai/智能体.mq.md
导入 大模型:ext/ai/大模型.mq.md
导入 自写回:lib/自写回.mq.md
导入 时间:lib/时间.mq.md
---
## 获取时间
*`u` = > 时间.此刻秒 *
**> 时间.格式化 秒=`u` 格式=%Y-%m-%d**
# main
*`模型` = > 大模型.大模型 *
`工具表` =
| 工具 |
|------|
| 获取时间 |
*`助手` = > 智能体 大模型=`模型` 工具=`工具表` 站立提示=你是可调试的 Marqdo 助手。 *
*`结果` = > `助手`.单步 任务=今天日期是什么?请在需要时调用工具。 *
> 打印 内容=`结果`
```
单步约定:
- 模型看到的上下文 **包含本文件源码与调用位置**,因此「有哪些 `##` 工具」对模型是可见的;行动约定写在提示里(人可读),例如单独一行 `CALL:<工具名>` / `调用:<工具名>`,最终答案则直接正文回复。
- 工具仍是 **runbook 里的 `##` 函数**(v1 以零参为主;可经 `args=` 扩展)。
- **调用工具走 [`lib/subtask`](stdlib-subtask.md)**:白名单校验通过后 `spawn fn=<名>`(中文面 `启动 函数=`)→ `wait` / `等待`,而不是进程内直接 `call_fn`。这样工具与主推理隔离在子任务语义下,并可与并行、超时、探测同一套主机能力对齐。
- 结束后用自写回记录:任务摘要、选用工具、结果或错误。
### 3.2 模式 B — 多步 / 复杂执行(工作簿)
> **完整锁定设计**见 [**ext-agent-plan.md**](ext-agent-plan.md)。以下为摘要。
| | |
|---|---|
| **输入** | 复杂目标 |
| **过程** | 父智能体**创建(或续跑)工作簿** →(非命中)**父先分解** → **`lib/subtask` spawn** 跑子文件 → 观察写回 → **父修订补丁后再执行**(有轮次上限) |
| **输出** | 汇总 map(含 `result`)+ 磁盘上的工作簿(代码与 `marqdo-out` 均可演化) |
| **适用** | 需分解、多情形、可固化步骤、可复用子成果的任务 |
公开方法:`## 多步` / `## plan`。
流水线要点:
1. **创建工作簿** — 默认 `.marqdo/agent-runs/`;内容为任务的详细可执行步骤(导入、工具、`# main`、子智能体)。
2. **模型配置继承父智能体** — 共享 env / 等价 llm 句柄;v1 不静默换模。
3. **子任务执行整文件** — 不是父进程内嵌解释。
4. **工作簿内推荐多个 `# 智能体`**;也允许一个智能体多次 `单步`;**已确定步骤应固化为返回答案的普通代码**(多轮 = 多文件接力 + OKF,见 [ext-agent-plan.md §4.2](ext-agent-plan.md))。
5. **持续更新** — 代码修订 + 写回注释刷新(替换不累积空行)。
6. **`单步` 默认自动写回**(`写回=` / `writeback=` 可关),父侧再汇总写回。
7. **父上下文** — 与单步同级的源码 / Skill / 调用位置 / 历史,外加工作簿全文与子写回。
示意:
```markdown
*`报告` = > `编排`.多步 目标=调研并汇总三篇资料的要点 *
> 打印 内容=`报告`
```
工作簿概念形状与修订循环细节 → [ext-agent-plan.md](ext-agent-plan.md)。
## 4. 分层与仓库布局
```text
ext/
ai/
llm.mq.md / 大模型.mq.md # 模型 I/O
agent.mq.md / 智能体.mq.md # 本框架(按本文重写)
```
| 层 | 职责 |
|----|------|
| **应用 runbook** | 领域 `##` 工具、任务表、是否人工确认分解 |
| **`ext/ai/agent`** | 单步 / 多步、工作簿生成、子智能体编排、写回约定 |
| **`ext/ai/llm`** | 补全 / 聊天 |
| **`lib/writeback`** | 持久化输出块 |
| **`lib/subtask`** | **工具调用与(多步时)子智能体并行的执行通道**;见 [stdlib-subtask.md](stdlib-subtask.md) |
安装:[`ext-cli.md`](ext-cli.md) — `marqdo ext add agent` / `add llm`(`.mq.md` + `native/libagent.so`)。导入:`导入 智能体:ext/ai/智能体.mq.md`。
**原生插件(ABI v2)**:`ext/ai/agent` 经 `lib/plugin` 加载;优先 `> plugin.native_path name=agent`,否则按序查找:
1. `MARQDO_AGENT_PLUGIN`(显式 `.so` / `.dylib` 路径)
2. `CARGO_TARGET_DIR/{debug,release}/libagent.so`(或 `.dylib`)
3. cwd `target/{debug,release}/`
4. 可执行文件旁 `libagent.*` 或 `target/debug/`
5. `MARQDO_EXT/native/libagent.*`(`marqdo ext add agent` 安装)
本地开发须先 `cargo build -p marqdo_plugin_agent`(或 `ext add agent` / 设 `MARQDO_AGENT_PLUGIN`)。详见 [ext-cli.md](ext-cli.md) · [ext-abi.md](ext-abi.md)。
**分层纪律(硬规则,勿破)**:
1. `ext/**/*.mq.md` **禁止**出现任何 `host_*` / `host_` 调用。
2. Agent 专属能力(含 OKF agent-kb:`agent_goal_sig` / `agent_kb_lookup` / `agent_kb_promote` / …)只进 **`plugins/agent` 注册名**,由 `ext/ai/agent` 在 `plugin.load` 后调用。
3. **禁止**向 `src/host/`(`HostFn` 表)添加 agent / OKF 领域原语,以免核心包体膨胀。通用 L0.5 仅保留 fs/json/subtask 等标准库底层。
4. 进程退出用 `sys.exit` / `系统.退出`,不用裸 `exit`。
官方 `ext/ai/` 用 `lib/*` 包装或插件注册名;见 [module-namespace.md](module-namespace.md) §8 · [ext-abi.md](ext-abi.md)。
---
## 5. 公开 API(目标契约)
| 中文 | 英文 | 角色 |
|------|------|------|
| `# 智能体` | `# agent` | 构造:`大模型`/`model`,`工具`/`tools`,可选 `站立提示`/`standing` |
| `## 单步` | `## step` | 原子执行;注入源码 + 位置;可选工具;返回结构化 map;**默认自动写回**(`写回=` / `writeback=` 可关) |
| `## 多步` | `## plan` | 建/续工作簿 → subtask 跑文件 → 修订循环 → 汇总(见 [ext-agent-plan.md](ext-agent-plan.md)) |
| `## 分解` | `## decompose` |(可公开或内部)目标 → 子任务表 |
| `## 清空历史` | `## clear_history` | 若仍保留会话式辅助状态则清空;**不以隐藏 chat 袋为真相源**——真相在文档写回 |
构造参数(v1):
| 参数 | 说明 |
|------|------|
| `大模型` / `model` | `ext/ai/llm` 句柄 |
| `工具` / `tools` | 工具名表(单列文本,或多列且含 `工具`/`tools`/`name`) |
| `站立提示` / `standing` | 写在文档里的常驻说明(可空) |
`## 单步` 参数:`任务` / `task`;可选 `写回` / `writeback`(默认真)、深度、是否强制不用缓存等。
`## 多步` 参数:`目标` / `goal`;可选 `工作簿目录`、`工作簿`(续跑路径)、`最大深度`、`最大轮次`、`确认分解` —— 详见 [ext-agent-plan.md §9](ext-agent-plan.md)。
模块内辅助函数(组装上下文、解析模型回复、匹配写回缓存)**不是**稳定对外契约,可随实现调整。
---
## 6. 工具表与子任务调用
工具 **不是** 框架内置能力。在 runbook 定义 `##`,再用表登记名称:
```markdown
`工具表` =
| 工具 |
|------|
| 获取时间 |
| 读取摘要 |
```
- 单列表 → 名称列表。
- 多列表 → 从列 `工具` / `tools` / `name` 取名。
- 名称须对应当前模块(或导入可见)的 `##`。
- **不要** 用 `parse text=["fn"]` 列工具(未加引号的标识符会被当成调用)。
### 6.1 调用路径(锁定)
```text
模型回复含 CALL:<名> / 调用:<名>
▼
host_tool_allowed(工具表白名单)
▼
lib/subtask:spawn fn=<名> → wait
▼
工具返回值写回上下文 / 自写回
```
| | |
|---|---|
| 英文面 | `> spawn fn=`名`` → `> wait id=`…`` |
| 中文面 | `> 启动 函数=`名`` → `> 等待 id=`…`` |
| 可选 | `args=` / `参数=` 传给带形参的工具;多工具并行时多次 `spawn` 再 `wait_all` / `等待全部` |
**非目标:** 以裸 `call_fn` 作为框架默认工具通道(应用仍可直接 `call_fn`,但官方智能体走子任务库)。
领域逻辑永远留在应用文件,不进官方 `ext/ai/`。
---
## 7. 上下文注入(每次单步 / 子步)
必须可注入(实现可切片,但不得默默丢掉「代码即文档」):
| 片段 | 来源 |
|------|------|
| 站立提示 | 构造参数 / 文档正文 |
| 任务 / 目标 | 方法实参 |
| 工具表(人可读) | 构造参数 |
| **当前 `.mq.md` 源码** | 插件 `agent_module_source`(经 ABI v2 `host_query`) |
| **调用位置** | 插件 `agent_call_site` |
| **Marqdo skill** | 插件 `agent_marqdo_skill` |
| Marqdo Skill | `skills/marqdo/`(`MARQDO_SKILL` 可覆盖) |
| 相关写回块 | `lib/writeback` 的 `get` / `list` |
禁止:把整份 Skill + 全文源码藏进不可审查的二进制提示且不在文档中留迹。框架拼装的提示应能在调试时落盘或写回(至少摘要)。
---
## 8. 自写回与缓存语义
依赖 [stdlib-writeback.md](stdlib-writeback.md):`record` / `写回` → `<!-- marqdo-out … -->`。
### 8.1 单步返回值与默认写回
`单步` / `step` 返回结构化 map,并在 **`写回` / `writeback` 默认真** 时自动 `record` 到命名槽(成功 `ok` / 失败 `error`)。关闭写回则行为与早期「纯返回值」一致,由编排方自行 `writeback.record`。
| 字段 | 何时 | 含义 |
|------|------|------|
| `status` | 总是 | `ok` / `error` |
| `task` | 总是 | 本步任务 |
| `decision` | 总是 | 模型首轮输出(含 CALL 行等) |
| `tool` / `tool_result` | 成功且调了工具 | 工具名与子任务返回 |
| `result` | 成功 | 最终答复 |
| `error` | 失败 | 错误信息 |
```markdown
*`out` = > `助手`.step task=… *
*`回复` = > json.get value=`out` key=result *
# 默认已写回;若 writeback=False 则需自行 record:
# > writeback.record value=`body` key=ok
```
命名槽 `ok` / `error` 互不覆盖;锚点为调用行。多步工作簿内依赖此默认写回,避免靠提示词强制落盘 —— 见 [ext-agent-plan.md §7](ext-agent-plan.md)。
**命中规则(后续缓存)**:读 `key=ok` 且非占位时可复用。失败知识读 `key=error`。
用户可 `clear key=ok` / `clear key=error` 强制重跑。
复杂执行中,子结果写回优先落在 **工作簿** 文件;父 `多步` 维护汇总写回。
### 8.2 Live 金样例
[`tests/ext/agent-run-live.mq.md`](../../tests/ext/agent-run-live.mq.md):`agent.step`(**默认写回** `ok`/`error`)+ 子任务工具。凭证:`tests/ext/.env`;`> llm.load_env path=.env` 相对**源文件目录**。需已构建 agent 原生库(见 §4)。
---
## 9. 安全与边界
| 风险 | 对策 |
|------|------|
| 无限多步递归 | `最大深度`(默认小,如 2);叶任务强制单步 |
| 工具越权 | 仅工具表白名单;子智能体可传更窄的表 |
| 工作簿爆炸 | 统一目录、命名含时间 / id;可选总超时 |
| 缓存过期 | 签名 + 时间戳;手动清块 |
| 模型乱改仓库 | 写回 API 约束写入形态;多步生成文件限于工作簿目录 |
---
## 10. 相对旧 API 的迁移
| 旧(废弃方向) | 新 |
|----------------|----|
| 唯一的 `## 执行` / `## run` + 隐藏 TOOL: 循环 | `## 单步` / `## 多步` |
| host 历史袋为真相 | 文档写回 + 工作簿为真相;历史袋至多辅助 |
| 提示全在框架字符串 | 站立提示与任务在 `.mq.md`;源码注入 |
| `tests/ext/agent-smoke` 测 TOOL 上下文拼接 | 重写为单步离线 / 写回 / 工作簿骨架测试 |
兼容:可短期保留 `## 执行` 作为 `## 单步` 的别名,但文档与金样例迁到新名后删除别名。
---
## 11. 实现路线(文档锁定后)
| 阶段 | 内容 | 状态 |
|------|------|------|
| D0 | 本文 Accepted;废弃 thin TOOL 设计叙述 | **本文件** |
| D1 | 重写 `ext/ai/agent.mq.md` / `智能体.mq.md`:`单步` + 源码/位置注入 + **子任务调工具** + **结构化返回值**;运行时经 **ABI v2 agent 插件**(禁 ext 直调 host) | **done** |
| D2 | `多步`:按 [ext-agent-plan.md](ext-agent-plan.md)(观察→精确补丁;禁止整文件重写);**D2a–D2f 主路径已落地** | **done** |
| D3 | 金样例:离线单步 / 写回;**live 单步**(`tests/ext/agent-run-live.mq.md`);多步骨架(可不打网) | **live done** |
| D4 | `view` / `debug` 对工作簿与写回块的导航体验 | done(workbook 链到 `/file?path=`;写回槽 `ok`/`error`/`trace` 徽章 + `#wb-{line}`;plan 结果卡) |
| O2 | OKF 任务知识包:`plan` reuse/promote([okf.md §7](okf.md)) | **done** |
### 非目标
- 在官方 `ext/ai/` 捆绑领域工具或工单技能
- 在 `ext/` 根目录摊平 `.mq.md`
- 平行再造一套 LLM HTTP 栈
- 以不可读的私有二进制协议作为编排主界面
---
## 12. 一句话
**智能体框架必须让编排看起来像文档、跑起来像程序、留痕像知识库。**
单步解决原子问题(默认写回);多步让父智能体编写并修订子 Marqdo 工作簿、经子任务执行、把确定步骤固化为代码——详见 [ext-agent-plan.md](ext-agent-plan.md)。
流式:`## step` / `## plan` 支持 `stream=True` / `echo=True`(SSE 增量;返回 map 不变;`plan` 另附 `events`,可选 `trace` 写回)。非命中时先流式父分解再 spawn 子任务。见 [agent-streaming.md](../roadmap/agent-streaming.md)。
+112
View File
@@ -0,0 +1,112 @@
# Official extension installer (`marqdo ext`)
| | |
|---|---|
| Status | **Accepted (v0.3.5 prep)** — prebuilt native download |
| Date | 2026-09-04 |
| Related | [ext-llm.md](ext-llm.md) · [ext-agent.md](ext-agent.md) · [ext-abi.md](ext-abi.md) · [08-ext-deploy-coupling.md](ext-web-customization/08-ext-deploy-coupling.md) |
## Commands
```text
marqdo ext list
marqdo ext add llm
marqdo ext add agent
marqdo ext add web
marqdo ext remove llm
```
## Install root
1. `MARQDO_EXT` if set
2. Else `~/.marqdo/ext`
Imports use paths like `import llm:ext/ai/llm.mq.md` (see [`load.rs`](../../src/load.rs)).
## Goal: no local Rust required
End users who install Marqdo from **GitHub Releases** should run:
```bash
marqdo ext add web
```
and get both L1 `.mq.md` **and** the matching native plugin (`.dll` / `.so`) **without** `cargo build`.
### Resolution order (`add` with native crate)
1. Local artifact (`MARQDO_*_PLUGIN`, `plugins/web/build` for **web**, `target/{debug,release}`, beside `marqdo`, `MARQDO_EXT_SOURCE/native`, …)
2. **Download** `marqdo-{VER}-native-{target}.zip` from the GitHub Release for this CLI version → cache under `~/.marqdo/cache/`
3. Local rebuild fallback:
- **web** → `./scripts/build-web-plugin.sh` (Go c-shared `libweb`; requires Go 1.22+ / cgo)
- other plugins → `cargo build -p marqdo_plugin_*` when Rust/`cargo` is available
4. Else fail with a clear message pointing at the Release assets
L1 sources:
1. `MARQDO_EXT_SOURCE` / repo `./ext` / beside binary
2. Else download `marqdo-{VER}-ext.zip` into `~/.marqdo/cache/ext-src-v{VER}/`
### Env knobs
| Variable | Meaning |
|----------|---------|
| `MARQDO_EXT_VERSION` | Override SemVer used for Release asset names (default: CLI `CARGO_PKG_VERSION`) |
| `MARQDO_EXT_NO_DOWNLOAD=1` | Never hit the network (CI / air-gap); local/cargo only |
| `MARQDO_WEB_PLUGIN` / `MARQDO_AGENT_PLUGIN` / `MARQDO_QUANTUM_PLUGIN` | Explicit native path |
Windows Release **zip** also ships `ext/` + `ext/native/*.dll` next to `marqdo.exe` so a portable unzip works offline after one download.
## Source for `add` (developers)
1. `MARQDO_EXT_SOURCE` — directory containing `ai/llm.mq.md` …
2. Else repo `./ext` near cwd / binary
3. Else Release `marqdo-*-ext.zip` (see above)
## Layout (`ext/`)
```text
ext/
ai/ # llm + agent L1
web/
quantum/
```
Installed tree (`~/.marqdo/ext` or `MARQDO_EXT`):
```text
web/web.mq.md
web/网页.mq.md
native/libweb.so # or web.dll / libweb.dylib
web.plugin # absolute path hint
```
## Catalog
| Id | Installs under `MARQDO_EXT` |
|----|-----------------------------|
| `llm` | `ai/llm.mq.md`, `ai/大模型.mq.md` |
| `agent` | `ai/agent.mq.md`, `ai/智能体.mq.md`, **native `agent`** |
| `web` | `web/web.mq.md`, `web/网页.mq.md`, **native `web`** |
| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **native `quantum`** |
## Release assets (native)
| Asset | Platform |
|-------|----------|
| `marqdo-VER-native-x86_64-pc-windows-msvc.zip` | Windows x64 (`native/*.dll`) |
| `marqdo-VER-native-x86_64-unknown-linux-gnu.zip` | Linux x64 (`native/lib*.so`) |
macOS: use local `cargo build` until CI adds Darwin natives (same zip naming pattern reserved).
## Tests
`tests/gold.rs`: `ext_cli_add_list_remove_llm`, `ext_cli_add_agent`, `ext_cli_add_web` (local build path; set `MARQDO_EXT_NO_DOWNLOAD=1` in sandboxes if needed).
Unit: `ext_fetch` URL / triple tests.
## Non-goals
- Third-party registry
- Merging domain helpers into `lib/`
- Guaranteeing plugin **source** ABI stability (author `.mq.md` API is the contract)
+306
View File
@@ -0,0 +1,306 @@
# 设计:宿主集成缺口补齐(`ext/web` · `ext/ai`)
| | |
|---|---|
| 状态 | **Accepted · H1–H4 stdio 已落地**(H4b HTTP 可选) |
| 日期 | 2026-09-07 |
| 缺口盘点 | [ext-hosting-gaps.md](../research/ext-hosting-gaps.md) |
| 路线图 | [ext-hosting.md](../roadmap/ext-hosting.md) |
| 边界 | [ext-web-net.md](ext-web-net.md) · [ext-abi.md](ext-abi.md) · [ext-agent.md](ext-agent.md) |
| 目标 | 用**扩展库一等 API**关闭 GAP-01–05,取代下游 Python 旁路 |
---
## 0. 一句话
**服务器中继与「请求→`##`」进 `ext/web`;MCP Server 与 corpus 可发现进 `ext/ai`;标准库只保留已有客户端 SSE。** 作者用 GFM 表声明路由/工具,不写 JS、不启第二语言运行时。
---
## 1. 分层与禁止项
| 层 | 职责 | 落点 |
|----|------|------|
| 作者面 | 声明路径、上游、函数名、工具表 | `ext/web/web.mq.md` · `ext/ai/agent.mq.md`(+ 中文对偶) |
| ABI | axum 流式代理、每请求 interp 调用、MCP 传输 | `plugins/web` · `plugins/agent` |
| 标准库 | 不变:缓冲客户端 SSE / 解析 | `lib/net`(**不**加中继) |
| 核心 host | **禁止**新增 agent/web 领域 `host_*` | 见 Skill 硬规则 9 |
**禁止:**
1. 为中继在浏览器手写业务 JS。
2. `json=` 继续塞「任意 `##`」语义(保持 DB-only;新能力用独立装配名)。
3. MCP Server 把向量库升为权威真相(工具结果可带 `authority=workbook`)。
4. 无白名单的「任意文件系统路径 + 任意 `##`」远程触发。
---
## 2. GAP-01 · `app.proxy` 流式反向代理
### 2.1 作者 API
```markdown
*应用 = > `应用`.proxy path="/v1/chat/completions" upstream=$OPENAI_BASE_URL*
*应用 = > `应用`.proxy path="/llm/stream" upstream="https://api.example.com" strip_prefix="/llm" stream=True*
```
或装配表(一次挂多条):
```markdown
*应用 = > `应用`.configure proxy=`代理表`*
| path | upstream | stream | strip_prefix | headers_from_env |
|------|----------|--------|--------------|------------------|
| /proxy/chat | $OPENAI_BASE_URL | True | | OPENAI_API_KEY=Authorization |
```
| 参数 | 默认 | 含义 |
|------|------|------|
| `path` | 必填 | 浏览器同域路径 |
| `upstream` | 必填 | 上游根或完整 URL;支持 `$ENV` |
| `stream` | `True` | `True`:响应按上游 `Content-Type` 管道转发(含 `text/event-stream`) |
| `strip_prefix` | 空 | 转发前去掉本站前缀 |
| `methods` | `POST` | 允许方法 |
| `headers_from_env` | 空 | `ENV=Header-Name` 注入(密钥不进前端) |
| `timeout_ms` | 插件默认 | 上游超时 |
中文:`## 代理` / `流式=` / `上游=` / `去前缀=`。
### 2.2 ABI / 插件行为
| 步骤 | 行为 |
|------|------|
| 注册 | `web_app_proxy` 写入 `AppState` 路由表 |
| 请求 | 读 body + 过滤危险 hop-by-hop 头;合并 env 注入头 |
| 上游 | `reqwest`/`hyper` 流式客户端(插件内,不进核心) |
| 响应 | 复制状态码与 `content-type`;`body` 为 stream;SSE 不整段缓冲 |
| CORS | 仍走既有 `configure cors=`(同域调用时浏览器不依赖上游 CORS) |
### 2.3 与 `lib/net.http_post_sse` 关系
| API | 角色 |
|-----|------|
| `http_post_sse` | **出站消费者**(CLI/agent 侧收齐 events) |
| `app.proxy` | **入站中继**(浏览器 ← Marqdo ← 上游) |
二者互补,不互相替代。
### 2.4 验收
- 金样:mock 上游发两帧 SSE,浏览器侧(或 `curl -N`)收到两帧且中间无全缓冲延迟门槛。
- 密钥仅出现在服务端 env 注入头。
- 金样名建议:`tests/ext/web-proxy-sse-smoke.mq.md`。
---
## 3. GAP-02 · `app.invoke` / `configure invoke=`(HTTP → `##`)
### 3.1 作者 API
```markdown
*应用 = > `应用`.invoke path="/api/沉淀" method=POST fn="run.沉淀"*
```
表形式:
```markdown
*应用 = > `应用`.configure invoke=`调用表`*
| path | method | fn | body | return |
|------|--------|-----|------|--------|
| /api/note | POST | run.写出 | json | json |
| /api/search | GET | db.recent | query | json |
```
| 列 / 参数 | 含义 |
|-----------|------|
| `path` / `method` | HTTP 路由 |
| `fn` | `库.成员`(入口模块已 `import`)或 `模块路径##标题`(白名单前缀内) |
| `body` | `json` \| `form` \| `query` \| `raw` → 映射到 `##` 形参(同名优先;其余进 `payload` 袋) |
| `return` | `json`(默认)\| `text` \| `status` |
中文:`## 调用` / `函数=` / `正文=` / `返回=`。
### 3.2 安全默认(锁定)
1. **仅**解析入口 workbook 已导入的 `bind` 路径,或 `invoke_allow=` 显式前缀列表。
2. 单请求超时 + 可选并发上限(防 listen 线程饿死)。
3. 默认不启;作者显式 `invoke` / `configure invoke=`。
4. 错误:`{ok:false, error}` + HTTP 4xx/5xx;不把内部路径栈默认回传生产模式。
### 3.3 ABI / 插件行为
| 步骤 | 行为 |
|------|------|
| 注册 | `web_app_invoke` 存 `(path, method, FnRef)` |
| 命中 | 解析 body → Value 袋;`call_lib_path` / 等价「同步调用已加载模块的 `##`」 |
| 返回 | Value → JSON(复用现有 host JSON 通路);侧效(写盘)在同一解释器事务语义内尽最大努力 |
**不**把 `json=` DB 路由改语义;`invoke` 是平行装配。
### 3.4 与 compose 期 `call_lib_path` 关系
| 时机 | API |
|------|-----|
| 装配页 | 现有 compose / `call_lib_path` |
| **每个 HTTP 请求** | 本设计 `invoke` |
### 3.5 验收
- `POST` JSON → 用户 `##` 写入临时文件 + 返回 `{ok:true,…}`。
- 未导入路径 → 4xx,不执行。
- 金样:`tests/ext/web-invoke-smoke.mq.md`。
---
## 4. GAP-03 · MCP Server(`ext/ai`)
### 4.1 作者 API
```markdown
*服务 = > agent.mcp_server name="marqdo-qd"*
*服务 = > `服务`.tool name="qd_search" fn="求道.搜索" description="关键词检索"*
*服务 = > `服务`.tool name="qd_capture" fn="求道.捕捉"*
*服务 = > `服务`.serve transport=stdio*
# 或
*服务 = > `服务`.serve transport=http host=127.0.0.1 port=7433*
```
工具表:
| name | fn | description |
|------|-----|-------------|
| qd_search | 求道.搜索 | … |
| qd_list | 求道.列出 | … |
### 4.2 传输
| transport | 用途 |
|-----------|------|
| `stdio` | Cursor / Claude Desktop 拉起 |
| `http` | Streamable HTTP(与官方 MCP 演进对齐;首版可先 SSE+POST 子集) |
### 4.3 与 A4 fixture 客户端关系
| API | 方向 |
|-----|------|
| `mcp_list_tools` / `mcp_call` | **出站**(Agent 调外部 MCP;现 fixture) |
| `mcp_server` + `serve` | **入站**(外部调 Marqdo) |
客户端「真 MCP」仍见 agent 缺口文;本设计先交 Server,fixture 可保留测客户端。
### 4.4 ABI
- `plugins/agent`:`agent_mcp_server_*`(注册工具、stdio loop、可选 HTTP)。
- 工具实现:复用 GAP-02 同款「调用 `##`」内核(可抽共享 `invoke_fn`),避免两套分发。
- 返回包装:可含 `authority=workbook`。
### 4.5 验收
- 金样:stdio 夹具发 `tools/list` + `tools/call`,断言 JSON-RPC 形结果。
- 可选:`tests/ext/agent-mcp-server-smoke.mq.md`。
---
## 5. GAP-04 · 同寿副端口
### 5.1 关闭策略(优先)
GAP-01 + GAP-02 挂在**同一** `app.listen` → **不实现副端口**,文档宣布 GAP-04 关闭。
### 5.2 备选 API(仅当必须隔离)
```markdown
*应用 = > `应用`.listen host=127.0.0.1 port=18081 also_port=7432 also_routes=`中继表`*
```
`also_routes` 仅允许 `proxy` / `invoke` 已注册子集。实现成本高,**默认不做**。
---
## 6. GAP-05 · 跨模块 `db` 与 corpus 可发现
### 6.1 `db` 句柄(扩展约定 + 运行时)
**作者约定(立即文档化):**
1. 跨模块优先传 **`url` 字符串**,调用方 `*store = > web.db url=…*` 再 `select`。
2. 若传对象:必须保留 `_type` 为插件注册名(与 `web.db` 构造一致)。
**运行时修补(H 波次):**
| 选项 | 做法 | 选用 |
|------|------|------|
| A | 跨模块返回插件对象时规范 `_type` + 全局方法表查找 | **首选**(一次修好所有插件对象) |
| B | `db.open` 只返回 `{url}` 朴素 map,禁止「裸 select」跨文件 | 文档契约;体验较差 |
金样:模块 A `open` → 返回 → 模块 B `select` 成功。
`tests/ext/web-db-cross-module-smoke.mq.md`。
### 6.2 `corpus_search` 可发现
```markdown
## corpus_search
+ `query`
+ `root`=".marqdo/agent-kb"
* > plugin.load name=agent *
** > agent_corpus_search query=`query` root=`root` **
```
或在 `# agent` / `## corpus_search` 入口统一 `ensure_plugin`(与现 `agent` 构造对齐),保证 **纯 `marqdo run` + import agent** 即可用。
**不**把 `agent_corpus_search` 搬进 `src/host/`。
### 6.3 验收
- 无显式手工 ABI 名的情况下,`marqdo run` 金样调用 `agent.corpus_search` 成功。
- 跨模块 `db.select` 金样绿。
---
## 7. 扩展库表面清单(落地时改这些文件)
| 文件 | 增补 |
|------|------|
| `ext/web/web.mq.md` · `网页.mq.md` | `## proxy` / `## invoke`;`configure` 增 `proxy`/`invoke` 列 |
| `plugins/web/src/http.rs` · `middleware.rs` · 新 `proxy.rs` / `invoke.rs` | 路由注册与流式/调用 |
| `ext/ai/agent.mq.md` · `智能体.mq.md` | `# mcp_server` · `## tool` · `## serve`;`corpus_search` ensure_plugin |
| `plugins/agent/` | MCP Server 传输 + 共享 invoke |
| `tests/ext/web-proxy-sse-smoke.mq.md` 等 | 见上 |
| `doc/roadmap/ext-web.md` | 链到 H 波次(不重开 W0–W7) |
| `public/` / Skill | 发版时补「同域 LLM 代理 / HTTP 调用 ##」短节 |
**不**新增 `lib/run` 作为核心依赖:用户业务 `##` 仍在其自己的 `lib/*.mq.md`;Marqdo 只提供 **invoke 管道**。
---
## 8. 迁移:下游旁路 → 扩展 API
| 旁路(下游) | 替换为 |
|--------------|--------|
| `llm_proxy.py` `/proxy/stream` | `app.proxy` / `configure proxy=` |
| `llm_proxy.py` `/store/*` + `marqdo run` | `app.invoke` → 用户 `##` |
| `mq_bridge.py` 仅过滤 | 用户 `##` 内 `table`/`re` 过滤,或修复后的 `corpus_search` |
| `qdagent_mcp.py` | `agent.mcp_server` + `serve` |
| `mq.sh` 双进程 | 单 `marqdo run index.mq.md`(proxy+invoke 同端口) |
---
## 9. 开放点(实现前拍板)
| # | 问题 | 默认倾向 |
|---|------|----------|
| 1 | `invoke` 的 `fn` 是否允许 `path.mq.md##标题` 字面量 | 允许但必须 `invoke_allow` 前缀 |
| 2 | MCP HTTP 首版范围 | stdio 先交;HTTP 跟一波 |
| 3 | 代理是否缓冲「非 SSE」大 body | 非流式可限长缓冲;SSE 禁止整段缓冲 |
| 4 | GAP-05 选项 A vs B | **A** |
---
## 10. 完成定义(整包)
1. 无 Python 旁路即可:浏览器同域 SSE 对话 + HTTP 触发沉淀 `##` +(可选)MCP stdio 暴露同一批 `##`。
2. 金样覆盖 proxy / invoke / cross-db / corpus / mcp-server(stdio)。
3. `doc/research/ext-hosting-gaps.md` 各 GAP 标为关闭或降级为「备选副端口不做」。
4. 发版说明指向 `ext/web` · `ext/ai` 新作者面,不指向 `scripts/*.py`。
+235
View File
@@ -0,0 +1,235 @@
# `ext/linalg` — 公式文档面(跑通即正确)
| | |
|---|---|
| 状态 | **Draft · 锁定作者面哲学与分期** |
| 日期 | 2026-09-07 |
| 父设计 | [ext-linalg.md](ext-linalg.md) |
| 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) |
| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) |
| 对照 | [stdlib-math.md](stdlib-math.md)(高中标量公式) |
---
## 0. 一句话
**`.mq.md` 里的线性代数应当读起来像一份可运行的公式讲义**:式子能跑通,就在库承诺的规则与维数下代表正确;`lib/math` 守高中边界,大学符号矩阵与更深层计算由 **`ext/linalg` 正当承担**。
---
## 1. 产品哲学
### 1.1 与 Marqdo 总原则对齐
| Marqdo | 在线性代数上的含义 |
|--------|-------------------|
| 代码即文档 | 矩阵代数段落用数学式书写,而不是 API 调用清单 |
| 标记即语法 | `$$`、中缀、`# matrix` 方法都是可读标记,不是「库胶水」 |
| 跑通可验收 | 金样 / 课堂作业:文件 exit 0 + 断言化简结果 = 式子合法 |
### 1.2 「跑通即正确」的精确定义
**不是**「任意高深定理自动证明」。
**是**在声明的能力边界内,下列任一成立则文档该段视为正确:
1. **形状层**:不相容维数的乘加在构造时硬错误(写不出可运行的坏式)。
2. **恒等式层**:文档断言的规范形(如 `(AB)^\top → B^\top A^\top`)经规则集得到。
3. **数值核对层**(可选):小 `$$` 数值阵 `explicit` 后与手算一致——验算,不是符号证明。
更高深主题(矩阵微积分、表示、特殊函数矩阵等)通过**扩展同一公式面的规则表**分期加入,而不是另起一套函数库叙事。
### 1.3 与 `lib/math` 的边界(再次锁定)
| | `lib/math` | `ext/linalg` |
|--|------------|--------------|
| 教育边界 | 高中标量公式 | 大学经典线性代数及更深(官方 ext) |
| 值类型 | `Value::Formula`(标量 AST) | `_type=matrix` / `矩阵`(MatExpr + 稠密) |
| 作者感觉 | `$$sin(x)+x$$` + `diff` / `plot` | `A*B`、`(AB)^T`、分块、分解图 |
| 是否「数学库」 | 是(stdlib) | **是数学库的官方扩展**,不是旁路工具箱 |
把大学 LA 塞进 `lib/math` ❌;在 `ext/linalg` 做大学符号计算乃至更深 ✅。
---
## 2. 两面模型:代数面 vs 计算面
文档里应能一眼分清「推导」与「动手算」。
### 2.1 代数面(默认;公式文档)
| 意图 | 写法(目标) | 语义 |
|------|--------------|------|
| 引入符号阵 | 见 §3 | 惰性 `MatrixSymbol` |
| 加减乘 | `` `C` = `A` + `B` `` · `` `P` = `A` * `B` `` | 建树 + 形状检查 |
| 转置 / 逆 | `` `At` = > `A`.T `` · `` `Ai` = > `A`.inv `` | 惰性节点 |
| 化简 / 展示 | 见 §4(默认化简策略) | 规则不动点 → ASCII / KaTeX |
| 分块 / Kronecker | 表或 `block` / `kron`(可保留具名,但结果仍是公式) | 惰性 |
**读者感受**:像在抄黑板,而不是在调 `la.mul`。
### 2.2 计算面(显式步骤;可单独成段)
| 意图 | 写法 | 语义 |
|------|------|------|
| 稠密求值 | `` `E` = > `A`.explicit `` / `la.explicit` | 展开数值 |
| 分解 | `` `f` = > la.factorize matrix=`A` kind="svd" `` | `linalg_factor` |
| 求解 / 最小二乘 | `solve` / `lstsq` | 数值解 |
| 度量 | `norm` / `cond` / `rank` / `det`(数值路径) | 标量或条件对象 |
| 作图 | `draw` / `show` | SVG / 公式卡 |
**读者感受**:「于是我们计算 / 画出…」——与纯代数叙述分段书写。
---
## 3. 目标作者语法(公式文档优先)
### 3.1 已落地(v1 中缀 / 方法)
```markdown
*`A` = > la.symbol name="A" rows=2 cols=2*
*`B` = > la.symbol name="B" rows=2 cols=2*
*`C` = `A` + `B`*
*`P` = `A` * `B`*
*`Pt` = > `P`.T*
*`s` = > `Pt`.simplify*
*`t` = > `s`.ascii*
```
数值 `$$` 矩阵可直接参与 `+` / `*`(经插件吸收为稠密叶)。
### 3.2 目标形态(文档感更强;分期实现)
**叙事理想(不必一次做完):**
```markdown
# 正规方程
令 \(A\) 为 \(m\times n\) 设计矩阵,\(b\) 为观测。
*`AtA` = > `A`.T * `A`* # 或未来更紧凑的 postfix / 混合写法
*`xty` = > `A`.T * `b`*
*`xhat` = > `AtA`.solve b=`xty`* # 计算面
```
**符号引入(减少 `la.symbol` 噪音)——候选(F2 选定一种):**
| 候选 | 例 | 利 | 弊 |
|------|----|----|-----|
| A. 构造糖 | `` `A` = > la.matrix name=A rows=m cols=n `` | 已有 `# matrix` | 仍是调用 |
| B. 维数表 | GFM 表声明符号与形状,一行绑定 | 很「文档」 | 需新约定 |
| C. `$$` 符号方言 | `$$A_{m\times n}$$` → MatExpr | 最像讲义 | 解析歧义;勿污染标量 formula |
| D. 保持 `symbol` + 短别名 | `` `A` = > la.A rows=m cols=n `` | 实现便宜 | 文档感一般 |
**锁定倾向:** 短期 **A + 默认化简(F1)**;**F2 采用 B(GFM `@` 表 + `la.declare`)**;受限 C(`$$` 符号方言)仍待评估且不得污染核心 formula。
### 3.3 明确不做(本波语法)
- 把符号 MatExpr 塞进核心 `formula::Expr`
- 发明与 Markdown 列表冲突的行首 `+` 矩阵语法
- 用未定义的 `$$矩阵A$$` 伪方言冒充已实现语义
---
## 4. 默认化简与「写出即规范」
### 4.1 策略
| 操作 | 是否自动 `simplify` | 理由 |
|------|---------------------|------|
| `ascii` / `latex` / `show` | **是(F1 done)** | 展示面应接近讲义规范形;`raw=True` 可关 |
| 中缀 `+` `*` `-` 的构造结果 | **否** | 保留用户书写结构;需要时再化简 |
| `.simplify` | 显式不动点 | 文档断言 / 金样 |
| `explicit` 前 | 可选先 simplify(F1.1) | 减少无效稠密路径 |
### 4.2 验收句式(金样)
```markdown
*`P` = `A` * `B`*
*`Pt` = > `P`.T*
*`t` = > `Pt`.ascii* # F1:无需再 .simplify 即得 B^T*A^T
1. `t` == "B^T*A^T"
> print text=ok
```
「跑通 + 断言」= 这段公式文档正确。
---
## 5. 正确性分层与错误体验
| 层 | 失败时 | 作者应看到 |
|----|--------|------------|
| 形状 | `A*B` 列行不配 | 含双方 shape 的硬错误,指向调用点 |
| 规则 | 无法化到文档期望形 | 金样失败;或 `ascii` 仍为未化简形(需补规则) |
| 插件未加载 | 中缀矩阵运算 | 提示 `ext add linalg` / `ensure_plugin` |
| 超维 | `explicit` / 分解 | 护栏错误,建议保持符号 |
---
## 6. 与实现现状的对照
| 能力 | 状态 |
|------|------|
| MatExpr 惰性树 + R1–R5 / 分块 / kron | done(L1–L3) |
| 稠密 / 分解 / 度量 / draw theme | done(L2–L6) |
| 中缀 `+` `-` `*` + `# matrix` 方法 | done(v1) |
| `ascii`/`latex`/`show` 默认 simplify | **done(F1)** |
| 更少噪音的符号引入 | **done(F2:`declare` + 表)** |
| 更紧凑转置 / 混合公式书写 | **done(F3:`T_ascii`)** |
| `explicit` 前可选 auto-simplify | **done(F3,默认开)** |
| public「如何写公式文档」 | **done(F3)** |
| 矩阵微积分等 | L7+ / 规则表扩展 |
---
## 7. 分期(公式文档面)
| 阶段 | 内容 | 出口 |
|------|------|------|
| **F1** | 展示路径默认 simplify;金样「`.T` + `ascii` → 规范形」;设计本文落地 | **done** |
| **F2** | 符号引入降噪(选定 §3.2 候选);更新 examples 使其读起来像讲义 | **done**(`declare` + `linalg-transpose`) |
| **F3** | 可选 postfix / 链式糖;`explicit` 前可选 auto-simplify;public 短文「如何写公式文档」 | **done** |
| **F4+** | 新规则(伴随、多项式矩阵…);矩阵微积分仅当明确需要 | 规则表可测 |
---
## 8. 示例叙事(目标文档骨架)
````markdown
---
import la:ext/linalg/linalg.mq.md
---
# 转置反序
*`A` = > la.symbol name="A" rows=2 cols=3*
*`B` = > la.symbol name="B" rows=3 cols=2*
*`P` = `A` * `B`*
*`Pt` = > `P`.T*
叙述:\((AB)^\top = B^\top A^\top\)。
*`t` = > `Pt`.ascii*
1. `t` == "B^T*A^T"
> print text=identity-ok
2. *
> print text=identity-fail
````
计算面示例保持 `examples/linalg-least-squares/`(`lstsq` + heatmap),与代数面示例分目录或分章节。
---
## 9. 开放问题
1. **自动 simplify 是否改变 `ascii` 金样**——凡依赖「未化简乘积串」的测试需改期望或改调 `repr_raw`(若提供)。
2. **中文 `_type=矩阵` 与展示**——方法链已 retag;view 是否统一显示英文 kind。
3. **`$$` 符号方言**——若做,必须经 `from_formula` 扩展,禁止改核心高中 formula 语义。
---
## 10. 收束
`ext/linalg` 的北极星不是「功能最多的矩阵库」,而是:
> **让大学线性代数(及更深)以可运行公式文档的形式存在于 Marqdo;跑通即在规则集内正确;计算与作图是显式步骤,不淹没代数叙述。**
+345
View File
@@ -0,0 +1,345 @@
# `ext/linalg` — 公式优先的线性代数扩展
| | |
|---|---|
| 状态 | **Draft · L0–L6 + 中缀 v1 · 公式文档面见专文** |
| 日期 | 2026-09-07 |
| 调研 | [research/ext-linalg-formula.md](../research/ext-linalg-formula.md) |
| **公式文档面** | [ext-linalg-formula-doc.md](ext-linalg-formula-doc.md)(跑通即正确 · 代数面/计算面) |
| 路线图 | [roadmap/ext-linalg.md](../roadmap/ext-linalg.md) |
| 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [view.md](view.md) · [ext-quantum-q7.md](ext-quantum-q7.md) |
| 安装(规划) | `marqdo ext add linalg`(`linalg` / `线性代数`) |
---
## 0. 一句话
**经典线性代数以「矩阵公式」为一等公民**:抽象表达式可化简、可展示、可选求值;稠密数值与分解图走 ABI 插件——**不**并入 `lib/math`,**不**挂在 `ext/quantum` 作者面。
作者面北极星见 **[ext-linalg-formula-doc.md](ext-linalg-formula-doc.md)**:跑通即正确;代数面像讲义,计算面是显式步骤。
---
## 1. 目标与非目标
### 1.1 目标
1. **公式类扩展**:在现有标量 `formula` 之上,引入 **矩阵表达式(MatExpr)**——`MatrixSymbol`、乘加、转置、逆、迹、行列式、分块、Kronecker——默认**不展开**。
2. **大规模优化**:形状检查 + 重写规则 + 惰性求值 + 分解对象复用(见 §5)。
3. **易于展示**:KaTeX 公式卡、结构 SVG(SVD/QR/消元/特征)、数值热力图;CLI 可断言的 ASCII。
4. **文档即实验**:GFM 表声明矩阵 / 步骤;`.mq.md` 可读可跑。
### 1.2 非目标(首版)
| 不做 | 原因 |
|------|------|
| 塞进 `lib/math` | 高中标量范围已锁定;大学 LA 属官方 ext |
| 复用 `quantum.*` 作者 API | 领域混淆;量子 Q7 保持量子语义 |
| 完整 SymPy / Mathematica | 规则表可控子集即可 |
| 稀疏格式 / GPU / 分布式 | 超出文档语言定位 |
| 矩阵微积分闭式(Jacobian 积木) | 记入路线图远期 |
| 在 `ext/**` 调 `host_*` | 硬约束;数值走插件名 |
---
## 2. 分层架构
```text
作者 .mq.md
│ import la:ext/linalg/linalg.mq.md
▼
L1 官方 ext(GFM + ## 包装,中英分文件)
│ plugin.load name=linalg
▼
plugins/linalg(ABI v2)
├── matexpr:符号树构造 / 重写 / latex
├── dense:稠密 f64(可选复数)运算与分解
└── draw:结构 SVG / heatmap
│
▼(可选)
核心 Value::Formula 仅保留「数值矩阵字面量」现状;
符号 MatExpr 以 **map `_type=matrix`(中文构造为 `矩阵`)** 承载,避免撑爆高中 formula AST;遗留标签 `linalg_expr` / `linalg_dense` 仍可解析。
```
### 2.1 为何 MatExpr 不直接塞进 `formula::Expr`
| 方案 | 利 | 弊 | 决策 |
|------|----|----|------|
| 扩展 `formula::Expr` | 与 `$$` 一体 | 核心膨胀;高中/大学边界糊 | ❌ |
| 插件侧表达式 + L1 对象 | 核心干净;可独立发版 | 需稳定 `_type` 与 latex 桥 | ✅ **采用** |
| 仅 list-of-list 数值 | 简单 | 无法公式优化与符号展示 | ❌ 仅作 `explicit` 结果 |
**既有** `formula::Expr::Matrix`(数值 `$$`)继续服务量子门 / 小例子;`ext/linalg` 通过 `la.matrix` / `la.from_formula` 吸收为稠密叶子。
### 2.2 与量子的边界
| | `ext/linalg` | `ext/quantum` Q7 |
|--|--------------|------------------|
| 域 | 经典实/复矩阵 | 态 / 密度 / Pauli |
| Kronecker | 经典 ⊗ | 复合量子系统 |
| 图 | SVD/QR/GE/heatmap | hinton/city/qsphere/… |
| 复用 | 插件**私有**可共享 Jacobi/SVD 代码 | 作者面 API **分离** |
---
## 3. 运行时对象(锁定草案)
全部经插件构造,L1 返回 **map**(`_type` 稳定,金样可断言):
| `_type`(英) | 中文标签 | 字段(最小) | 含义 |
|---------------|----------|--------------|------|
| `linalg_expr` | `线性式` | `repr`(S-expr 或内部 id)、`shape`=`[m,n]` 或符号维、`latex`、`ascii` | 抽象矩阵公式 |
| `linalg_dense` | `稠密阵` | `rows`, `cols`, `data`(行主 list[list])、`dtype`=`real`\|`complex` | 显式数值 |
| `linalg_factor` | `分解` | `kind`=`lu`\|`qr`\|`svd`\|`eig`\|`chol`,因子字段,`latex`,可选 `svg` | 分解结果 |
| `linalg_svg` | — | `kind`, `svg` 文本 | 与 quantum_svg 同构展示约定 |
| `linalg_solve` | `求解` | `x`, `residual`, `method` | 线性系 / 最小二乘 |
形状:`shape` 允许整数或符号维名(字符串 `"n"`);不相容 → 硬错误。
---
## 4. 作者面 API(英文 `ext/linalg/linalg.mq.md`)
中文镜像:`ext/linalg/线性代数.mq.md`(`矩阵` / `化简` / `求值` / `绘图`…)。
### 4.1 构造
```markdown
# matrix
## symbol
+ `name`
+ `rows`
+ `cols`
# → linalg_expr MatrixSymbol
## eye / zeros / ones / diag
+ …
## from_list
+ `data` # list[list] 或 table
## from_formula
+ `formula` # 吸收 Value::Formula Matrix 字面量
## block
+ `blocks` # 表或嵌套 list of expr
```
文档写法偏好:
````markdown
`A` = > la.symbol name=A rows=n cols=n
`b` =
$$
\begin{pmatrix}1\\0\\0\end{pmatrix}
$$
*`b` = > la.from_formula formula=`b` *
````
作者面优先顶层 `la.symbol` / `la.mul`(`la.matrix.symbol` 无接收者会硬错误,见 [module-namespace.md](module-namespace.md) §4.3)。
### 4.2 公式代数(返回 `linalg_expr`,惰性)
| 英文 | 中文 | 语义 |
|------|------|------|
| `mul` / `add` / `sub` | `乘` / `加` / `减` | 形状检查后建树 |
| `transpose` / `T` | `转置` | |
| `inv` | `逆` | 符号逆;不立即求数值 |
| `pow` | `幂` | 整数幂 |
| `trace` / `det` | `迹` / `行列式` | 可得到标量 expr 或数值 |
| `kron` | `克罗内克` | **禁止**默认 expand |
| `simplify` | `化简` | 应用 §5 规则集 |
| `collapse` | `分块化简` | 对标 `block_collapse` |
| `latex` / `ascii` | `乳胶` / `文本` | 展示字符串 |
| `shape` | `形状` | |
链式 / 中缀(v1 已落地):
```markdown
*`C` = `A` + `B`*
*`P` = `A` * `B`*
*`Pt` = > `P`.T*
*`s` = > `Pt`.simplify*
```
运行时对双方为 `matrix` / `矩阵` / 数值 `$$` 矩阵 / 遗留 `linalg_expr` 的 `+` `-` `*` 分派到插件;结果保留左操作数 `_type` 以便中英方法链。
### 4.3 求值与分解(热路径 → 稠密)
| 英文 | 说明 |
|------|------|
| `eval` / `explicit` | 符号树 + 绑定表 → `linalg_dense`;超维硬错误 |
| `factorize` | `kind=lu\|qr\|svd\|eig\|chol` → `linalg_factor` |
| `solve` | `A`,`b`;或 `factor` + `b` |
| `lstsq` | 最小二乘 |
| `rank` / `norm` / `cond` | 数值度量 |
| `matmul` | 稠密乘(已 explicit 时) |
维数上限(草案,可配置):
| 操作 | 默认上限 |
|------|----------|
| `explicit` 稠密元素总数 | \(n\cdot m \le 10^4\)(如 100×100) |
| SVD / eig 方阵边长 | \(\le 64\)(与 quantum 密度同级) |
| 结构 SVG(无元素) | 边长示意可达数百(只画框) |
| KaTeX 完整数字阵 | \(\le 8\times 8\);更大只出摘要 + 结构图 |
### 4.4 展示
| 英文 | `kind` | 说明 |
|------|--------|------|
| `show` | — | 写入 view:优先 `latex` 公式卡 |
| `draw` | `structure` | 形状/分块矩形(drawmatrix 风格) |
| `draw` | `heatmap` / `hinton` | 数值幅度 |
| `draw` | `svd` / `qr` / `ge` / `eig` | 分解结构图(对标 LAFigureSpecs) |
| `draw` | `path`= | 可选落盘 SVG |
`show` 应对符号式**始终可用**(无需 `eval`)。
### 4.5 最小可运行示例(设计验收叙事)
````markdown
---
import la:ext/linalg/linalg.mq.md
import table:lib/table.mq.md
---
# main
*`A` = > la.symbol name=A rows=3 cols=3 *
*`x` = > la.symbol name=x rows=3 cols=1 *
*`b` = > la.mul a=`A` b=`x` *
*`s` = > la.simplify expr=`b` *
> la.show expr=`s`
`M` =
$$
\begin{bmatrix}2&0\\0&3\end{bmatrix}
$$
*`M` = > la.from_list data=[[2,0],[0,3]] *
*`f` = > la.factorize matrix=`M` kind=eig *
> la.draw factor=`f` kind=eig path=eig.svg
````
---
## 5. 公式重写与「大规模优化」(核心)
### 5.1 原则
1. **构造便宜,展开昂贵**——乘加只分配节点。
2. **形状是类型系统**——`(m×k)·(k×n)` 合法;否则错误指向调用点。
3. **化简是规则不动点**——有限规则表,可测、可文档化。
4. **expand 显式开启**——`expand=True` 才对 Kronecker / 多项式矩阵做爆炸性展开。
5. **数值路径旁路符号**——已 `explicit` 的叶子用稠密核,不再走规则。
### 5.2 v1 规则集(最小够用)
| ID | 规则 | 例 |
|----|------|-----|
| R1 | 单位元 | `I*A → A`,`A*I → A`,`A+0 → A` |
| R2 | 双逆 | `(A^{-1})^{-1} → A` |
| R3 | 转置反序 | `(AB)^\top → B^\top A^\top`,`(A^\top)^\top → A` |
| R4 | 逆转置 | `(A^{-1})^\top → (A^\top)^{-1}` |
| R5 | 结合扁平 | `MatMul` 链扁平化 |
| R6 | 分块塌缩 | 对标 `block_collapse`(乘/加在块级分配) |
| R7 | Kronecker 结合 | `(A⊗B)⊗C → A⊗B⊗C`;**不**展开成元素 |
| R8 | 标量提出 | `c*(A+B) → c*A+c*B`(可选;默认关以免树变宽) |
### 5.3 数值侧优化
| 策略 | 说明 |
|------|------|
| `factorize` 一次 | 多 RHS `solve` 复用 |
| 小阵专用核 | 2×2 / 3×3 闭式逆 / det(教学友好、可对照公式) |
| 复杂度护栏 | 超限错误信息建议「保持符号 / 降维 / 分块」 |
| 禁止静默降精度 | 病态 `cond` 可警告(stderr 或结果字段) |
---
## 6. 展示设计(效果)
### 6.1 通道
| 通道 | 符号 MatExpr | 稠密 | 分解 |
|------|--------------|------|------|
| view Structure | KaTeX `latex` 卡 | 小阵 KaTeX;大阵摘要 | 公式 + 可选 SVG |
| view Execution plots | — | heatmap SVG | `kind=svd|…` SVG |
| CLI `print` | `ascii` | `[[…],…]` 或摘要 | `svd(U,S,V)` 摘要 |
| writeback | 可选记录 latex | 可选 | 可选 |
### 6.2 LaTeX 约定
- 符号:`A`,`A^{\top}`,`A^{-1}`,`AB`,`A \otimes B`
- 数值小阵:`\begin{bmatrix}…\end{bmatrix}`
- 分块:`\begin{bmatrix} A & B \\ C & D \end{bmatrix}`
- 喂给既有 view:与 `formula-card` / KaTeX 同源路径(L1 `show` → `host_query("record_plot")` 或扩展「record_math」若已有;无则复用 writeback + plot 列表)
### 6.3 结构 SVG(教学主视觉)
对标 LAFigureSpecs / drawmatrix,**不**依赖 Matplotlib:
| `kind` | 画什么 |
|--------|--------|
| `structure` | 矩形块 + 标签(零块灰色) |
| `svd` | \(U\Sigma V^{\top}\) 块布局 + 秩分隔 |
| `qr` | 瘦/胖 QR 示意 |
| `ge` | 消元后上三角高亮 |
| `eig` | \(A=PDP^{-1}\) 或谱列表 + 对角 |
| `heatmap` | 单元填色(实数蓝红;复数幅值) |
主题:`theme=light|dark|bw`(与 quantum Q8 令牌对齐;默认 `light`)。
---
## 7. L1 / 插件 / CLI 约定
1. **`ext/linalg/**` 禁止 `host_*`**;只调 `plugin.*` 注册名(如 `linalg_simplify`)。
2. **中英分文件**,CATALOG 双 id:`linalg` / `线性代数`。
3. **`marqdo ext add linalg`**:与 web/agent/quantum 相同——优先 Release 预编译 native zip。
4. **金样**:离线、确定性;SVG 断言含关键子串或稳定 hash 前缀。
5. **依赖**:插件内自研稠密核(或慎重引入单一 crate,如 `nalgebra`——**实现期再议**;设计默认「可自研小维 + 可选 crate」)。
---
## 8. 分期(摘要;细节见路线图)
| 阶段 | 交付 |
|------|------|
| **L0** | CATALOG + ping + L1 `ensure_plugin` |
| **L1** | `matrix.symbol` / dense 构造 / `mul`·`T`·`inv` 树 + `simplify` R1–R5 + `latex`/`show` |
| **L2** | `explicit` / 小阵运算 / `solve` / `det`·`trace` 数值 |
| **L3** | 分块 + `collapse`;Kronecker 惰性 |
| **L4** | `factorize` LU/QR/SVD/eig + 结构 SVG |
| **L5** | heatmap/hinton;examples + public 文档 + skill 摘要 |
| **L6+** | 矩阵微积分 / 更大 BLAS(仅当用户明确要求);复数全路径算子 |
---
## 9. 验收标准(设计级)
1. 符号式 `(AB)^\top` 经 `simplify` 得 `B^\top A^\top`,**不**产生稠密数据。
2. 不相容形状在符号 `mul` 即失败。
3. `$$` 数值阵 → `from_formula` → `factorize kind=eig` → view 含 SVG 或 latex。
4. Kronecker 默认不 expand;显式 `expand` 受维数护栏。
5. 中英 L1 金样各至少一条;`ext add linalg` 路径文档化。
6. 与 `ext/quantum` 无作者面符号冲突。
---
## 10. 风险与开放问题
| 项 | 备注 |
|----|------|
| MatExpr 序列化 | 金样 / write:倾向可打印 S-expr 或稳定 latex+shape,避免不透明指针跨进程 |
| 与标量 `formula` 混运算 | v1:标量只作 `c*A` 系数;`det` 结果若符号则另型或降为 `formula` 文本 |
| nalgebra 等依赖 | 实现 L2 时评估二进制体积与 ABI 体积 |
| record_math vs plot | 若仅 SVG/KaTeX 字符串,可先复用 plot/writeback |
---
## 11. 一句话(收束)
**`ext/linalg` 让线性代数公式保持可优化的表达式,用规则与结构图服务文档阅读,用受控稠密核服务验算——公式优先,数值可选,展示分层。**
+85
View File
@@ -0,0 +1,85 @@
# Official extensions (`ext/`) — LLM
| | |
|---|---|
| Status | Accepted (v0.1.x) |
| Date | 2026-08-06 |
| Related | [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-agent.md](ext-agent.md) · [ext-cli.md](ext-cli.md) |
## Scope
`ext/ai/` holds **official LLM + agent** extensions. Import paths:
```markdown
---
import llm:ext/ai/llm.mq.md
---
```
Resolution: `MARQDO_EXT/ai/…`, repo `ext/ai/…`, cwd `ext/ai/…` (see [ext-cli.md](ext-cli.md)).
Other official ext: [ext-agent.md](ext-agent.md) / [ext-agent-plan.md](ext-agent-plan.md) (**document-driven agent** — step with default writeback / plan workbook; thin `TOOL:` loop superseded). Installer: [ext-cli.md](ext-cli.md). Native plugins: [ext-abi.md](ext-abi.md).
Streaming: `complete stream=True` returns an event list (`reasoning` / `delta` / `done` / `error`); `echo=True` prints thinking (`reasoning_content`) and answer tokens as they arrive. See [agent-streaming.md](../roadmap/agent-streaming.md). Default (`stream=False`) is unchanged (answer string).
**Note:** Prefer `marqdo ext add llm`. Import `import llm:ext/ai/llm.mq.md` from repo or install root.
## Platform prerequisites
| Capability | Surface |
|------------|---------|
| HTTPS + headers | `lib/net` → `http_post` / `headers=` map |
| Dotenv | `## load_env` in ext (or `load_dotenv` / `lib/sys`) |
| JSON quote | `lib/json` → `quote` |
## `ext/ai/llm` / `ext/ai/大模型` (object handles)
| English | Chinese | Role |
|---------|---------|------|
| `## load_env` | `## 加载环境` | Free function: load `.env` |
| `## stream_result` | `## 流式结果` | Collapse event list → final text |
| `# llm` | `# 大模型` | Object ctor → handle map |
| `## complete` / `## chat` | `## 运行` / `## 聊天` | Methods; optional `stream` / `流式`, `echo` / `打印增量` |
```markdown
---
import llm:ext/ai/llm.mq.md
---
# main
> load_env
*`model` = > llm *
*`reply` = > `model`.complete prompt=Say hi in one word *
> print text=`reply`
*`events` = > `model`.complete prompt=Say hi stream=True *
- [`ev`](`events`)
*`t` = > json.get value=`ev` key=type *
1. `t` == "delta"
*`chunk` = > json.get value=`ev` key=text *
> print text=`chunk`
2. *
*`_` = 1*
```
Environment (create a **project-local** `.env`; do not commit secrets):
```env
OPENAI_API_KEY=sk-...
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_MODEL=gpt-4o-mini
```
Fallbacks: `MARQDO_LLM_API_KEY`, `MARQDO_LLM_BASE_URL`, `MARQDO_LLM_MODEL`.
## Tests
- Import smoke: `tests/ext/llm-import.mq.md`
- Offline stream: `tests/ext/llm-stream-offline.mq.md` + `tests/lib/net-openai-sse.mq.md`
- Live complete (local): `tests/ext/llm-complete.mq.md` + `tests/ext/.env`
- Live agent `## step`: `tests/ext/agent-run-live.mq.md` (DeepSeek; gold: `ext_agent_run_live`)
- Agent smoke (real `llm` handle): `tests/ext/agent-smoke.mq.md` (gold: `ext_agent_framework_smoke`)
- Live complete: `tests/ext/llm-complete.mq.md` (gold: `ext_llm_complete_live`)
+49
View File
@@ -0,0 +1,49 @@
# `ext/quantum` — 自定义酉门(公式矩阵 → 可施加)
| | |
|---|---|
| 状态 | **Accepted · 已落地** |
| 日期 | 2026-08-12 |
| 父设计 | [ext-quantum.md](ext-quantum.md) |
---
## 1. 目标
作者用 `$$…$$`(或嵌套 list)写出酉矩阵 → `quantum.gate matrix=…` 得到可复用门句柄 → `` `qc`.apply gate=… qubits=… `` 施加到电路。
---
## 2. 公式矩阵
`$$` 围栏若含 `[[…]]` 或 `\begin{pmatrix}` / `\begin{bmatrix}`,在**解析期**求值为嵌套数值 list(非整棵 `Formula` 标量树)。
支持:
- ASCII:`[[1,0],[0,-1]]`、`(1/sqrt(2))*[[1,1],[1,-1]]`
- LaTeX 子集:`\frac{…}{…}`、`\sqrt{…}`、`pmatrix` / `bmatrix`(`&` / `\\`)
复数:list 路径仍可用 `{re,im}` 或 `[re,im]`;公式路径本切片以实矩阵为主。
---
## 3. API
```markdown
*`U` = > quantum.gate matrix=`H_matrix` name=U *
# 或构造参数 matrix=;name 可选(默认 U)
*`qc` = > `qc`.apply gate=`U` qubits=0 *
# qubits= 标量或 list;矩阵维数须为 2^k
```
中文:`量子.门 矩阵=` / `` `qc`.施加 门= 比特= ``。
具名门仍可用 `name=H`;`matrix` / `matches_matrix` / `draw` 对自定义门同样有效。
---
## 4. 验收
- 公式(或 list)定义的 H 与内置 `H` 概率一致
- EN/ZH 金样
+48
View File
@@ -0,0 +1,48 @@
# `ext/quantum` Q5.5 — 振幅阻尼(教学轨迹)
| | |
|---|---|
| 状态 | **Accepted · 已落地** |
| 日期 | 2026-08-12 |
| 父设计 | [ext-quantum.md](ext-quantum.md) · [ext-quantum-q5.md](ext-quantum-q5.md) |
| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
---
## 1. 目标
在 Q5 的 `bitflip` / `depolarizing` 之外,补一种**耗散**教学噪声:`amplitude_damping`(中文 `振幅阻尼`),仍只影响 `run` 轨迹;`simulate` / `probabilities` 忽略。
**刻意不做:** 完整 Kraus 表 API、任意算符噪声、密度矩阵引擎、相位阻尼完整 Lindblad。
---
## 2. 作者面
```markdown
*`qc` = > `qc`.noise kind=amplitude_damping p=0.1 *
# 中文
*`qc` = > `qc`.噪声 种类=振幅阻尼 概率=0.1 *
```
别名:`amp_damp` / `amplitude-damping`。
---
## 3. 模拟语义
与 Q5 相同:每个改态门后,对涉及比特独立掷骰。
对每个比特,以概率 `p` 施加**跳跃**算符 \(E_1 = |0\rangle\langle 1|\)(只作用该比特),再归一化:
- 若态在该比特上几乎全为 `|0⟩`(范数 ≈ 0),跳跃无效,态不变。
- 否则振幅从 `|…1…⟩` 搬到对应 `|…0…⟩` 并归一化。
金样:`X` 后 `amplitude_damping p=1` → 全部 shot 落在 `|0⟩`。
---
## 4. 验收
- `tests/ext/quantum-amp-damp-smoke.mq.md`(+ 中文对称)
- L1 EN/ZH 文档列出第三种 `kind`
+69
View File
@@ -0,0 +1,69 @@
# `ext/quantum` Q5 — 最小噪声(教学用)
| | |
|---|---|
| 状态 | **Accepted · 最小实现已落地** |
| 日期 | 2026-08-12 |
| 父设计 | [ext-quantum.md](ext-quantum.md) |
| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
---
## 1. 目标
在 **不** 引入完整开放系统 / 云后端的前提下,让教学文档能写「带噪声的采样」,金样可复现。
**刻意不做(本 Q5 切片):** 任意 Kraus 组、振幅阻尼完整表、>12 qubits 张量网络、噪声参数学习。振幅阻尼教学轨迹见 [ext-quantum-q5.5.md](ext-quantum-q5.5.md)。
---
## 2. 作者面
电路上可选噪声字段(方法链设置,返回新句柄):
```markdown
*`qc` = > `qc`.noise kind=bitflip p=0.05 *
# 或
*`qc` = > `qc`.noise kind=depolarizing p=0.02 *
```
| 参数 | 含义 |
|------|------|
| `kind` | `bitflip` \| `depolarizing`(中文:`比特翻转` / `退极化`) |
| `p` | 每比特、每个非 `barrier`/`measure` 门后的错误概率,`0…1` |
`simulate` / `probabilities`:**忽略噪声**(仍为理想酉演化),避免概率图被蒙特卡洛抖动。
`run shots= seed=`:**启用噪声**(若 `p>0`):按轨迹采样,结果可复现。
---
## 3. 模拟语义(轨迹)
每个 shot:
1. 从 `|0…0⟩` 施电路门(跳过 `BARRIER`;`MEASURE` 不改变酉演化)。
2. 每施一个会改态的门后,对**该门涉及的每个比特**独立:
- `bitflip`:以概率 `p` 施 `X`;
- `depolarizing`:以概率 `p` 均匀随机施 `X`/`Y`/`Z` 之一。
3. 若电路含 `MEASURE` 标记:只对标记比特做计算基采样;否则测全部比特。
RNG:与现有 `run seed=` 同一 SplitMix64 流(门后噪声与最终采样共用)。
---
## 4. 与作者面补齐的关系
| API | 行为 |
|-----|------|
| `barrier` | 仅可视化;模拟跳过 |
| `measure` | 可视化测量符号;决定 `run` 读出哪些比特 |
| `append` | 追加另一 `circuit` 的 `ops`(或单门) |
| `state` | 等价于当前理想 `simulate` 结果(`quantum_state`) |
---
## 5. 验收
- 金样:理想 Bell `run` 不变;`noise kind=bitflip p=1` 在已知电路上计数偏离理想(`seed=` 固定)。
- `barrier`/`measure` 出现在 `draw kind=circuit` SVG。
- 中英 L1 对称;仍无 `host_*` 于 `ext/**`。
+230
View File
@@ -0,0 +1,230 @@
# `ext/quantum` Q7 — 高阶线性代数 + 高级可视化
| | |
|---|---|
| 状态 | **Accepted · Q7a/Q7b/Q7c 已落地** |
| 日期 | 2026-08-28 |
| 父设计 | [ext-quantum.md](ext-quantum.md) |
| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
| 对照 | [IBM Quantum state plots](https://quantum.cloud.ibm.com/docs/en/guides/plot-quantum-states) · [QuTiP visualization](https://qutip.readthedocs.io/en/latest/guide/guide-visualization.html) · Cirq `plot_density_matrix` |
---
## 0. 一句话
在 **Q0–Q6 态向量教学模拟**之上,补齐两块「教科书级」能力:
1. **高阶线性代数**(密度矩阵、Kronecker、部分迹、Hermitian 谱分解、Schmidt / SVD、Pauli 期望值)
2. **高级静态 SVG 展示**(Hinton / City / Pauli 向量 / QSphere 风格 / 多比特布洛赫)
全部经 **`plugins/quantum` ABI**;`ext/quantum/**` 只做 L1 表包装,**禁止** `host_*`。
---
## 1. 动机与业界对照(联网调研 2026-08)
### 1.1 为何现在做
| 已有(Q0–Q6) | 缺口 |
|---------------|------|
| 纯态态向量 + 施门 + 采样 | 混态 / 约化子系统无法一等公民表达 |
| `bloch` 单比特约化 | 纠缠与多比特关联只能猜 |
| `gate.draw kind=matrix` 热力图 | 无密度矩阵 / Pauli 分解 / 球面振幅布局 |
| 内部 `apply_unitary` / Kronecker | **未**暴露为作者面 API |
教学文档写「贝尔态纠缠」时,读者需要:**约化密度矩阵 → 纯度 < 1 → Schmidt 系数 → Hinton/QSphere 图**。这些正是 Qiskit / QuTiP / Cirq 的标配。
### 1.2 可视化对标(只取可静态 SVG 落地的子集)
| 业界 | 含义 | Q7 决策 |
|------|------|---------|
| Qiskit `plot_state_hinton` | 元大小表示幅值,色表示正负 | ✅ `kind=hinton` |
| Qiskit `plot_state_city` | Re/Im 三维条 | ✅ **2.5D 等轴测 SVG**(非 Matplotlib) |
| Qiskit `plot_state_paulivec` | Pauli 串期望值柱 | ✅ `kind=paulivec` |
| Qiskit `plot_state_qsphere` | 振幅点在球面上,色=相位 | ✅ `kind=qsphere`(教学投影) |
| Qiskit `plot_bloch_multivector` | 每比特一球 | ✅ `kind=multibloch` |
| Cirq density Argand 格 | 每元幅值圆 + 相位针 | ✅ 并入 `kind=density`(默认) |
| QuTiP Wigner / 过程层析 | 连续相空间 / χ 矩阵 | ❌ 本切片不做 |
### 1.3 线性代数对标(经典模拟侧,非量子算法)
| 能力 | 教学用途 | Q7 |
|------|----------|-----|
| ρ = \|ψ⟩⟨ψ\| | 纯→密度 | ✅ |
| Kronecker / 张量积 | 复合系统 | ✅ |
| 部分迹 | 约化、纠缠证据 | ✅ |
| Hermitian 本征分解 | 谱 / 测量可观测量 | ✅(小维) |
| Schmidt(纯态二分)= 整形 SVD | 纠缠熵入口 | ✅ |
| Pauli 期望 ⟨P⟩ | 布洛赫 / paulivec 数据源 | ✅ |
| 纯度 Tr(ρ²)、保真度 | 混态度量 | ✅ 最小 |
| 量子奇异值变换 / VQSVD / 云后端 | 算法研究 | ❌ |
---
## 2. 硬约束(沿用 + 本切片追加)
1. **仅 ABI**:新 FFI 全部注册在 `marqdo_plugin_init`;L1 经 `plugin.load`。
2. **`ext/**` 无 `host_*`**。
3. **中英分文件**,禁止混 API。
4. **维数上限**:
- 态向量模拟:仍 ≤ 12 qubits(既有)。
- **密度矩阵稠密运算**(部分迹结果展示、谱分解、Hinton/City):默认 **≤ 6 qubits**(dim ≤ 64);超限显式报错。
5. **无新核心依赖**:插件内手写复数矩阵 + Jacobi / 薄 SVD;**不**捆绑 BLAS / nalgebra(可后续再议)。
6. **view**:仍走 `host_query("record_plot")` + `quantum_svg`;无外链字体/CDN。
---
## 3. 新运行时类型
| `_type`(英) | 中文 | 字段(锁定) |
|---------------|------|----------------|
| `quantum_state` | `量子态` | 既有:`qubits`, `amplitudes:[{re,im}]` |
| `quantum_density` | `密度矩阵` | `qubits`, `dim`, `matrix`(dim×dim 嵌套 `{re,im}`) |
| `quantum_spectrum` | `谱` | `eigenvalues:[f64]`, `eigenvectors`(列向量嵌套 list) |
| `quantum_schmidt` | `施密特` | `coeffs:[f64]`, `ua`, `ub`(局域基),`entropy`(可选) |
| `quantum_svg` | — | 既有;`kind` 扩展见 §5 |
---
## 4. 作者面 API
### 4.1 英文(`ext/quantum/quantum.mq.md`)
在既有 `# circuit` / `# gate` 之外增加(或扩展方法):
```markdown
# density
+ `state`=None # quantum_state 或 circuit(先 simulate)
+ `matrix`=None # 直接给定 ρ
## matrix # → 嵌套 list
## purity # Tr(ρ²)
## expect
+ `obs` # Pauli 串 "ZI" / "XX" 或门矩阵
## partial_trace
+ `keep` # 保留的比特列表(LSB=0)
## eig # Hermitian 谱 → quantum_spectrum
## draw
+ `kind`=hinton # hinton|city|density|paulivec
+ `path`=None
# linop # 自由线性代数(也可挂在 quantum.* 模块函数)
## kron
+ `a`
+ `b` # 矩阵或态 → 张量积
## schmidt
+ `state`
+ `cut`=1 # 前 cut 个比特为 A,其余为 B
## fidelity
+ `a`
+ `b` # 两态或两密度(纯态公式优先)
```
**电路侧便捷方法**(返回新句柄,不改旧对象):
```markdown
## density # simulate 后 ρ=|ψ⟩⟨ψ|
## expect
+ `obs`
## schmidt
+ `cut`=1
## draw
+ `kind`=… # 扩展:hinton|city|density|paulivec|qsphere|multibloch
```
### 4.2 中文对称
| 英文 | 中文 |
|------|------|
| `density` | `密度` |
| `partial_trace` | `部分迹` |
| `purity` | `纯度` |
| `expect` | `期望` |
| `eig` | `本征` |
| `kron` | `张量积` |
| `schmidt` | `施密特` |
| `fidelity` | `保真度` |
| `hinton` / `city` / `paulivec` / `qsphere` / `multibloch` | 同音译或 `欣顿`/`城市`/`泡利向量`/`球`/`多布洛赫`(L1 锁定中英别名表) |
### 4.3 ABI 函数名(稳定英文)
| FFI | 作用 |
|-----|------|
| `quantum_density_from_state` | 态 / 电路 → `quantum_density` |
| `quantum_density_from_matrix` | 校验 Hermitian / 维数 → 句柄 |
| `quantum_density_matrix` | 取出嵌套矩阵 |
| `quantum_density_purity` | Tr(ρ²) |
| `quantum_density_partial_trace` | keep 列表 |
| `quantum_density_eig` | Jacobi Hermitian |
| `quantum_density_expect` | Pauli 串或矩阵 |
| `quantum_density_draw` | hinton/city/density/paulivec |
| `quantum_kron` | 两矩阵或两态振幅 |
| `quantum_schmidt` | 纯态二分 |
| `quantum_fidelity` | 两态 |
| `quantum_draw_circuit` | **扩展** kind 枚举(向后兼容) |
---
## 5. 高级绘图语义
| `kind` | 输入 | SVG 要点 |
|--------|------|----------|
| `hinton` | ρ | 网格方块;边长 ∝ √\|ρᵢⱼ\|;正 Re 浅 / 负深;小 dim 可标数值 |
| `city` | ρ | 等轴测「楼宇」:左 Re、右 Im 两城,或单城双色柱 |
| `density` | ρ | Cirq 风格:每格幅值圆 + 相位线段;对角概率矩形 |
| `paulivec` | 态或 ρ | 全 Pauli 基(n≤3)或用户 `ops=` 列表;柱高 = ⟨P⟩ |
| `qsphere` | 纯态 | 基矢点映射到球/圆;半径∝振幅,色相∝arg;n≤4 推荐 |
| `multibloch` | 纯态 | 每比特约化布洛赫并排 |
既有 `circuit|probs|bloch|gate|matrix` **不变**。
---
## 6. 数值语义(锁定)
| 项 | 规则 |
|----|------|
| 比特序 | **qubit 0 = LSB**(与既有概率标签一致) |
| `partial_trace keep=` | 保留比特升序组成新系统的 LSB…MSB |
| Pauli 串 | 左→右 = **高位→低位** 或文档写死「左=qubit n-1」——**锁定:字符串左端 = 最高比特(qubit n−1)**,与 Qiskit 习惯一致;文档 + 金样双锁 |
| Hermitian 检查 | ‖ρ−ρ†‖_F < 1e-8,否则报错 |
| 谱 | 实特征值降序;特征向量列归一 |
| Schmidt | 将 \|ψ⟩ 整形为 `2^cut × 2^(n-cut)` 复矩阵做薄 SVD;奇异值 = Schmidt 系数 |
| 纯度 | 纯态 ≈ 1;最大混态 = 1/dim |
---
## 7. 分期交付
| 子阶段 | 内容 | 验收 |
|--------|------|------|
| **Q7a** | density / kron / partial_trace / eig / schmidt / expect / purity / fidelity + L1 中英 | `tests/ext/quantum-linalg-smoke.mq.md`(+ zh) |
| **Q7b** | draw kinds:hinton, city, density, paulivec, qsphere, multibloch | `tests/ext/quantum-viz-advanced-smoke.mq.md`(SVG 含关键标记) |
| **Q7c** | 示例页 + 用户站短页 + skill/reference 摘要 | `examples/quantum-entanglement/` 或扩展 bell |
---
## 8. 刻意不做(本 Q7)
- 任意 Kraus / 完整 CPTP 通道库(仍用 Q5 轨迹噪声)
- >6 qubit 稠密 ρ 的谱 / Hinton(请用态向量 API)
- Matplotlib / WebGL / 交互拖拽
- 量子线性系统算法(HHL)、QSVT 电路构造
- 把线性代数并入 `lib/math`(经典公式优先的 LA 见规划 [ext-linalg.md](ext-linalg.md),作者面与 quantum 分离)
---
## 9. 评审清单
1. 密度矩阵上限 6 qubits 是否可接受?
2. Pauli 串左右端比特约定是否锁定为「左=高比特」?
3. City 用 2.5D SVG 而非真 3D 是否足够?
4. `# density` 独立类 vs 仅 `circuit.density` —— **两者都提供**(类用于给定矩阵;电路方法便捷)?
评审默认:**全部锁定为上文**;实现按 Q7a → Q7b → Q7c。
---
## 10. 一句话
**Q7 让 Marqdo 量子文档能「算清纠缠、画清态」:线性代数在 ABI 里跑,高级图用自绘 SVG 进 view——仍是代码即文档。**
+153
View File
@@ -0,0 +1,153 @@
# `ext/quantum` Q8 — 可视化美学升级(科技感电路图)
| | |
|---|---|
| 状态 | **Accepted · Q8a/Q8b landed · Q8c pending** |
| 日期 | 2026-08-28 |
| 父设计 | [ext-quantum.md](ext-quantum.md) · [ext-quantum-q7.md](ext-quantum-q7.md) |
| 路线图 | [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
| 对照 | [IBM Quantum Composer](https://quantum.cloud.ibm.com/docs/guides/composer) · [Qiskit `iqp` / `iqp-dark`](https://quantum.cloud.ibm.com/docs/api/qiskit/qiskit.visualization.circuit_drawer) · Cirq / Quirk 视觉习惯 |
---
## 0. 一句话
修复 view 内嵌量子 SVG 的**文字–导线粘连**,并把电路 / 概率 / 布洛赫 / 密度类图统一到一套**量子实验室科技感**视觉令牌(深底、门族分色、清晰留白)——仍只输出自包含 SVG,无外链字体/CDN。
---
## 1. 问题诊断(对照用户截图)
| 现象 | 根因(`plugins/quantum/src/draw.rs`) |
|------|----------------------------------------|
| `q0`/`q1` 与导线穿过文字 | 导线从 `x=8` 起画满宽;标签 `x=4` 且基线对齐导线中心 → 线穿字 |
| 「不好看 / 无科技感」 | 单色 `#1a1a1a` + 浅灰盒;无门族色、无背景板、无线宽层次 |
| 门盒贴线、略挤 | `COL_W=56`、盒 28×28、标签栏与第一列无独立 gutter |
| 测量/控点辨识弱 | 与单比特门同色同描边,缺少语义色 |
**不在本切片**:交互拖拽、WebGL、外链字体、第二套 view 皮肤。
---
## 2. 业界对照(联网 2026-08)
| 来源 | 可借鉴点 | 本仓取舍 |
|------|----------|----------|
| **Qiskit `iqp` / `iqp-dark`** | 门族 `displaycolor`(面色+字色);深色底;线色弱于门 | 移植**色板与分类**,不绑 matplotlib |
| **IBM Composer** | 经典门深蓝、相位门浅蓝、非酉灰;导出 light/dark | 默认 **dark tech**(view 卡片上更醒目);可选 `theme=light` |
| **Quirk** | 高对比栅格、测量仪表清晰 | 测量盒保留仪表符号,加强描边/填充对比 |
| **教科书 bw** | 印刷友好 | 保留为 `theme=bw` 后备,非默认 |
**刻意避开**:紫白渐变「AI 默认皮肤」;过重 glow 光晕(打印/浅底卡片会糊)。科技感靠:**深 slate 底 + 青/靛门色 + 清晰层级 + 留白**,而非堆霓虹。
---
## 3. 视觉令牌(锁定 `marqdo-iqp`)
### 3.1 主题
| `theme` | 用途 |
|---------|------|
| `dark`(**默认**) | view / 教学演示科技感 |
| `light` | 浅底文档打印 |
| `bw` | 无彩色、高对比 |
作者面:
```markdown
*`svg` = > `qc`.draw kind="circuit" theme="dark"*
*`svg` = > `qc`.draw kind="probs" theme="light"*
```
| 参数 | 默认 | 说明 |
|------|------|------|
| `kind` | `circuit` | 既有枚举不变 |
| `theme` | `dark` | 新增;非法值报错 |
| `path` | — | 既有 |
中文:`主题=dark|light|bw`。ABI:`quantum_draw_circuit` 增可选 `theme`(circuit/probs/bloch 已生效;gate/density 高级图见 Q8c)。
### 3.2 Dark 色板(默认)
| 令牌 | 色 | 用途 |
|------|-----|------|
| `bg` | `#0a0e14` → `#141c28` 渐变 | SVG 圆角底板 |
| `wire` | `#6b7f96` | 比特线(双层描边) |
| `label` / `chip` | `#e8eef6` / `#1e2a3a` | `q0` 芯片标签(线不穿字) |
| `gate.clifford` | 面 `#4c6fff` / 字 `#f2f6ff` | H、X、Y、CX、SWAP… |
| `gate.phase` | 面 `#2de2e6` / 字 `#042024` | S、T、Rz、CZ… |
| `gate.rotation` | 面 `#3dd6c6` / 字 `#041a18` | Rx、Ry |
| `gate.measure` | 面 `#8fa3b8` / 字 `#0a1018` | MEASURE |
| `barrier` | `#9aafc0` 虚线 | BARRIER |
| `ctrl` | `#f0f5ff` | 控制点 / ⊕ |
Light / bw 在实现里各给一套平行表;金样以 dark 主断言(SVG 含 `data-theme="dark"` 与背景色)。
### 3.3 布局(消灭粘连)
```text
| pad | label_col | gutter | col0 | … | colN | pad |
^q0 芯片标签 ^导线从此开始(不穿过文字)
```
| 常量 | 实现值 |
|------|--------|
| `LABEL_W` | 52 |
| `GUTTER` | 20 |
| `PAD_X` / `PAD_Y` | 24 / 36 |
| `COL_W` | 80 |
| `ROW_H` | 64 |
| 门盒 | 40×40,`rx=8` |
| 线宽 | 导线双层 3.2+1.8;门描边 ~1.1;控制竖线 2.25 |
标签:圆角芯片 + 居中文字;导线 `x1 = PAD_X + LABEL_W + GUTTER`。
### 3.4 门族映射
| 族 | 门名(归一化后) |
|----|------------------|
| clifford | I X Y Z H CX CNOT SWAP |
| phase | S T RZ CZ |
| rotation | RX RY |
| measure | MEASURE M |
| barrier | BARRIER |
| custom / U | clifford 色或中性 `#546e7a` |
---
## 4. 作者面(增量,向后兼容)
见 §3.1。字符串参数须加引号:`kind="circuit"`、`theme="dark"`(中文 `种类=` / `主题=`)。改插件后须 `marqdo ext add quantum` 再开 view,否则仍加载旧 `.so`。
---
## 5. 分期
| 子阶段 | 内容 | 验收 |
|--------|------|------|
| **Q8a** | 电路轨线:布局 gutter + dark/light/bw 令牌 + 门族分色 | 标签不与线相交;SVG 含 `data-theme`;更新 draw smoke |
| **Q8b** | probs / bloch / gate heatmap 共用令牌 | 柱/球/热力与电路同族色 |
| **Q8c** | hinton / city / qsphere / paulivec / multibloch 换肤 | 高级图不「脱节」;viz-advanced smoke 仍绿 |
---
## 6. 实现约束
1. 仅改 `plugins/quantum` 绘图 + L1 透传 `theme`;**不**改 Marqdo 核心。
2. SVG **内联**颜色与字体栈(`ui-sans-serif, system-ui, …`);无 `@import` / CDN。
3. view 仍走 `record_plot`;底板自带圆角矩形,避免白底卡片上「漂浮黑线」。
4. 金样:断言结构标记(`data-theme`、`data-gate-family`)+ 既有 kind;不像素比对。
---
## 7. 非目标
- 复制 Qiskit matplotlib 像素级一致
- 动画 / 3D 电路
- 用户自定义完整 JSON 主题文件(可 Q9)
---
## 8. 一句话
**先把字从线上挪开,再给门族涂上实验室色——默认 dark tech,打印用 light,论文用 bw。**
+408
View File
@@ -0,0 +1,408 @@
# 官方扩展:`ext/quantum` 量子计算模拟
| | |
|---|---|
| 状态 | **Accepted · Q0–Q7 完结 · Q8a/Q8b 完结**([ext-quantum-q7.md](ext-quantum-q7.md) · [ext-quantum-viz-style.md](ext-quantum-viz-style.md);Q8c 高级态图换肤待做) |
| 日期 | 2026-08-12(初版)· 2026-08-28(Q7 · Q8 viz) |
| 相关 | [stdlib-math.md](stdlib-math.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [ext-web.md](ext-web.md) · [view.md](view.md) · [stdlib-i18n.md](stdlib-i18n.md) · [roadmap/ext-quantum.md](../roadmap/ext-quantum.md) |
| 安装(目标) | `marqdo ext add quantum`(中英:`quantum` / `量子`) |
| 本文目的 | 锁定**作者面**、**模拟语义**、**view 可视化**与**分期**;指导 ABI 插件实现 |
---
## 0. 一句话
`ext/quantum` 用 **GFM 表格 + 类方法 +(可选)`$$` 狄拉克/矩阵公式** 描述量子门与电路;**经典状态向量模拟**给出概率与采样。
文档能跑通,公式与电路约定就成立——这是 Marqdo「代码即文档」在量子教学上的最强展示位。
**不改 Marqdo 核心语法**;热路径只在 ABI 插件;**禁止**把量子核链进 `marqdo` 主二进制或在 `ext/**` 里调用 `host_*`。
---
## 1. 为何做量子扩展(与 math 的关系)
### 1.1 与 `lib/math` 的相似处
| math | quantum |
|------|---------|
| `` `f` = `` + `$$…$$` → `formula` | 门矩阵 / 态矢量可用 `$$` **展示与核对** |
| 库函数对公式求值、求导、作图 | 类方法对电路施门、模拟、画图 |
| view 内嵌 SVG;CLI 可 `path=` | view 内嵌**电路图 / 概率条 / 布洛赫**;CLI 可落盘 |
| 金样例失败 = 文档/公式错 | 金样例失败 = 门定义或电路叙述错 |
math 是**高中符号与曲线**;quantum 是**离散希尔伯特空间上的可执行电路文档**。两者都是「写出公式 → 跑通 → 证明文档正确」。
### 1.2 与 math 的刻意分界
| 做 | 不做 |
|----|------|
| 量子在 **`ext/quantum`**,经 `plugin.load` | **不**并进 `lib/math`(避免 stdlib 膨胀) |
| 复数振幅用 `{re, im}` map(与现有 `Value` 兼容) | **不**为量子在核心新增 `Value::Complex`(可二期) |
| 角度可用 `math.pi` 等常量 | **不**在 quantum 插件内重写 CAS |
### 1.3 「代码即文档」在这里的作用
典型教学页:
```markdown
# 贝尔态 |Φ+⟩
对 qubit 0 施 H,再 CNOT(0→1)。理想测量:`00` 与 `11` 各约 1/2。
# main
`steps` =
| 步 | 门 | 比特 |
|----|----|------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
*`qc` = > quantum.circuit qubits=2 steps=`steps` *
*`p` = > `qc`.probabilities *
```
- 叙述与表格是**给人看的电路说明**;
- 同一文件是**可执行程序**;
- gold / CI 断言概率 → **文档与物理约定同步**,无需另维护「幻灯片公式」。
---
## 2. 硬约束(评审锁定)
1. **仅 ABI 插件接入**:`plugins/quantum` → `libquantum.so`;L1 在 `ext/quantum/*.mq.md`。
2. **`ext/quantum/**` 禁止 `host_*`**;经 `plugin.native_path` + `plugin.load`(同 web/agent)。
3. **中英分文件**:`quantum.mq.md` / `量子.mq.md`,**禁止**混排 API([stdlib-i18n.md](stdlib-i18n.md))。
4. **不改核心语法**;电路表单元格保持字面量;门名/比特下标由类方法解析。
5. **模拟器有硬上限**(默认 ≤ 12 qubits);超限报错,不静默截断。
6. **view 必须有专项展示**(结构卡 + 执行区 SVG),禁止只 dump JSON。
---
## 3. 布局与安装
```text
ext/quantum/
quantum.mq.md # 英文类 API
量子.mq.md # 中文类 API
plugins/quantum/
Cargo.toml
src/lib.rs # ABI v2:线性代数 / 施门 / 画 SVG
examples/quantum-bell/ # 规范示例(Q3)
tests/ext/quantum-*.mq.md
```
```bash
cargo build -p marqdo_plugin_quantum
marqdo ext add quantum
```
导入:
```markdown
---
import quantum:ext/quantum/quantum.mq.md
---
```
或中文:`导入 量子:ext/quantum/量子.mq.md`。
---
## 4. 核心模型
### 4.1 运行时句柄(JSON map + `_type`)
| `_type`(英) | 中文类名 | 含义 |
|---------------|----------|------|
| `quantum_gate` | `量子门` | 具名门或自定义酉矩阵 |
| `quantum_circuit` | `量子电路` | n qubits + 有序门列表 |
| `quantum_state` | `量子态` | 状态向量(振幅列表) |
| `quantum_result` | `量子结果` | 概率 / 采样 / 可选坍缩态 |
| `quantum_svg` | (产物) | 带 `svg` 字段的可视化结果 |
插件返回 map;Marqdo 对象系统挂 `_type` 后可用方法链。
### 4.2 状态表示
- **纯态**状态向量:长度 `2^n`,每元 `{re, im}`(f64)。
- 默认初态:`|0…0⟩`(仅 index 0 振幅为 1)。
- 门作用后可选重归一化(阈值误差阈值,默认开)。
### 4.3 公式面(对齐 math 精神,不抢 math 实现)
允许用 `` `G` = `` + `$$…$$` 书写门矩阵(**可执行**,见 [ext-quantum-custom-gate.md](ext-quantum-custom-gate.md)):
````markdown
`H_matrix` =
$$
\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix}
$$
*`U` = > quantum.gate matrix=`H_matrix` *
*`qc` = > `qc`.apply gate=`U` qubits=0 *
*`ok` = > `H`.matches_matrix matrix=`H_matrix` *
````
- v1:**具名门**以插件内置酉矩阵为准;`matrix=` 可从嵌套 list / `$$` 矩阵围栏构造自定义门。
- `$$` 含 `[[…]]` 或 `\begin{pmatrix}` 时解析期求值为数值 list;标量公式仍为 `Formula`。
- `matches_matrix` 仍可用于核对。
---
## 5. 作者面 API(锁定草图)
### 5.1 英文 `ext/quantum/quantum.mq.md`
```markdown
# gate
+ `name`=None # H X Y Z S T I CX CZ SWAP …
+ `theta`=None # Rx/Ry/Rz
## matrix # → 振幅表 / 嵌套 list(文档与调试)
## draw # → quantum_svg(`kind=gate|matrix` 符号 / 热力图)
## matches_matrix
+ `matrix`
+ `tol`=1e-9
# circuit
+ `qubits`
+ `steps`=None # 可选:GFM 门序列表
## h / x / y / z / s / t
+ `qubit`
## rx / ry / rz
+ `qubit`
+ `theta`
## cx / cz
+ `control`
+ `target`
## swap
+ `a`
+ `b`
## barrier # 仅可视化分隔,不改变态
## measure # 标记测量(模拟时按计算基)
+ `qubits`=None # 默认全部
## append # 追加另一电路或门
+ `op`
## simulate # → quantum_state(不坍缩)
## probabilities # → map 基矢标签 → 概率
## run
+ `shots`=1024
+ `seed`=None # → quantum_result(计数直方图)
## draw
+ `path`=None # SVG;无 path 时仍可进 view 产物
+ `kind`=circuit # circuit|probs|bloch|hinton|…(见 Q7)
+ `theme`=dark # dark|light|bw(Q8;电路/概率/布洛赫)
## state # 当前缓存态(若已 simulate)
```
门方法返回**更新后的 circuit 句柄**(与 web `compose_*` 相同:`` `qc` = > `qc`.h qubit=0 *``)。
### 5.2 中文 `ext/quantum/量子.mq.md`
| 英文 | 中文 |
|------|------|
| `gate` | `门` |
| `circuit` | `电路` |
| `h` | `哈达玛` |
| `x` / `y` / `z` | `泡利X` / `泡利Y` / `泡利Z` |
| `cx` | `控非` |
| `cz` | `控相` |
| `rx`/`ry`/`rz` | `绕X`/`绕Y`/`绕Z` |
| `simulate` | `模拟` |
| `probabilities` | `概率` |
| `run` | `运行` |
| `draw` | `绘图` |
| `kind` | `种类` |
| `theme` | `主题` |
| `measure` | `测量` |
| `qubits` | `比特数` |
| `steps` | `步骤` |
| `shots` / `seed` | `次数` / `种子` |
插件 FFI 名稳定英文:`quantum_circuit_new`、`quantum_h`、`quantum_cx`、`quantum_simulate`、`quantum_draw_circuit`…
### 5.3 电路表(文档优先写法)
```markdown
`steps` =
| 步 | 门 | 比特 | 参数 |
|----|----|------|------|
| 1 | H | 0 | |
| 2 | CX | 0,1 | |
| 3 | RZ | 1 | pi/4 |
```
列名中英兼容:`步|step`、`门|gate`、`比特|qubits|qubit`、`参数|theta|params`。
*`qc` = > quantum.circuit qubits=2 steps=`steps` *` 与方法链**等价**;表更适合「整页即电路说明书」。
### 5.4 返回值形态
| 方法 | 返回 |
|------|------|
| `simulate` | `{_type, qubits, dim, amplitudes:[{re,im},…]}` |
| `probabilities` | `{ "00": 0.5, "11": 0.5 }`(标签为小端比特串,文档写死) |
| `run` | `{ counts: {…}, shots, seed }` |
| `draw` | `{_type: quantum_svg, kind: circuit\|gate\|probs\|bloch, svg: "…" }` |
---
## 6. 模拟器语义
| 项 | 锁定 |
|----|------|
| 模型 | 封闭系统纯态;计算基测量 |
| 默认上限 | **12 qubits**;`MARQDO_QUANTUM_MAX_QUBITS` 可下调(不可暗中上调超过编译期硬顶,硬顶建议 16) |
| 超限 | 错误信息含当前 n 与上限 |
| `simulate` / `probabilities` | **无 RNG**、确定性 |
| `run` | 多项式采样;`seed=` 可复现(金样必用) |
| 数值 | f64;门后 ‖ψ‖ 偏离阈值则重归一化并可选 warning 字段 |
实现:插件内 Kronecker / 按比特作用稀疏更新;可用 `nalgebra` 或手写,**不**捆绑外部量子云。
---
## 7. view 模式支持(专项)
对齐 [view.md](view.md) 与 math 作图:**Structure / Execution / Source 共用渲染**;禁止第二套皮肤。
### 7.1 Structure(结构区)
| 源形态 | 展示 |
|--------|------|
| `` `qc` = `` + 电路表 | **circuit-card**:比特数、门序列时间线(文本/紧凑 SVG) |
| `` `G` = `` + `$$` 门矩阵 | 沿用 **formula-card**(KaTeX);徽章可标 `gate`(若绑定来自 quantum.gate) |
| 方法链语句 | 普通调用行;不强制每步展开 |
### 7.2 Execution(执行区)
| 产物 | 展示 |
|------|------|
| `quantum_svg` | 与 math `plots` 同级:**内嵌 SVG**(电路轨线图 / 概率直方图 / 单比特布洛赫) |
| `probabilities` / `counts` | 表格 + 可选自动条形 SVG |
| `quantum_state` | 默认折叠振幅表;小 n(≤3)可并排显示基矢 |
### 7.3 产物如何进入 view(实现锁定)
插件**不能**直接碰核心 `HostContext.plots`。采用其一(实现时二选一,优先 A):
| 方案 | 做法 |
|------|------|
| **A(推荐)** | ABI `host_query("record_plot")`:参数 JSON `{svg}`;写入与 math 相同的 plots 列表([ext-abi.md](ext-abi.md) allowlist 增补一条) |
| **B** | 仅返回 `quantum_svg`;view 在渲染执行值时识别 `_type`/`svg` 字段并内嵌(不扩 ABI) |
CLI:`draw path=bell.svg` 写沙箱文件;无 path 时不把整段 SVG 灌 stdout(同 math §5)。
### 7.4 可视化内容(v1 必须 / 可后)
| 图 | v1 | 说明 |
|----|----|------|
| 电路轨线(qubit 线 + 门盒 + 控点) | **必须** | `circuit.draw`;Q8 默认 `theme=dark`(标签芯片 + 门族分色) |
| 测量概率条形图 | **必须** | `probabilities` / `run` 后可 `draw kind=probs` |
| 单比特布洛赫球(SVG) | 应有 | 仅 n=1 或指定 qubit 约化(纯态投影) |
| 门矩阵热力图 | **必须** | `gate.draw kind=matrix`(幅值热图 + 小数标注) |
| 高级态图(hinton/city/…) | Q7 | 见 [ext-quantum-q7.md](ext-quantum-q7.md);换肤见 Q8c |
| 交互拖拽编辑电路 | **不做** | 静态文档足够 |
视觉:内联 SVG 色与字体栈;**无外链**字体/CDN(同 view 硬规则)。主题令牌与布局:[ext-quantum-viz-style.md](ext-quantum-viz-style.md)。view 对 `svg[data-theme=dark]` 使用深色图框。
---
## 8. 分期(开发计划)
```text
Q0 脚手架:CATALOG + plugins/quantum Hello + L1 ensure_plugin
Q1 态向量 + I/X/H/CX + simulate/probabilities;贝尔态 gold
Q2 Y/Z/S/T/Rx/Ry/Rz/CZ/SWAP + run(seed) + 中英 API 对齐
Q3 电路表 steps= + draw 电路 SVG + view record_plot/识别;examples/
Q5 教学噪声 + barrier/measure/append/state — 见 [ext-quantum-q5.md](ext-quantum-q5.md) ← **done(最小)**
```
| 阶段 | 交付物 | 验收 |
|------|--------|------|
| **Q0** | `marqdo_plugin_quantum` 注册 `quantum_ping`;L1 加载失败可读 | `ext add quantum` 路径通 |
| **Q1** | 贝尔态 `probabilities` ≈ 0.5/0.5 | `tests/ext/quantum-bell-smoke.mq.md` |
| **Q2** | 旋转门 + `run seed=` 计数稳定 | 中英双金样 |
| **Q3** | `steps=` 表;`draw` SVG 在 `view` HTML 含 `<svg` | 与 math-plot 同级断言 |
| **Q4** | 概率图 + 布洛赫;`matches_matrix`;用户文档页 | `quantum-draw-smoke` / `quantum-gate-matrix-smoke`;`view output` 可浏览示例 |
| **Q5** | `noise` 轨迹;`barrier`/`measure`/`append`/`state` | `quantum-noise-smoke` / `quantum-author-api-smoke` |
| **Q6** | 公式/`matrix=` 自定义门 | [ext-quantum-custom-gate.md](ext-quantum-custom-gate.md) |
| **Q7** | 密度矩阵线性代数 + Hinton/City/QSphere 等 SVG + 纠缠示例 | [ext-quantum-q7.md](ext-quantum-q7.md) ✅ |
| **Q8** | 可视化美学:`theme` + 标签 gutter + 门族分色 | [ext-quantum-viz-style.md](ext-quantum-viz-style.md) · Q8a/Q8b ✅ · Q8c 待做 |
实现路线图跟踪见 [roadmap/ext-quantum.md](../roadmap/ext-quantum.md)。
---
## 9. 规范示例(目标作者体验)
```markdown
---
title: Bell state
import quantum:ext/quantum/quantum.mq.md
---
# Bell |Φ+⟩
H on qubit 0, then CNOT. Expect |00⟩ and |11⟩ each with probability 1/2.
# main
`steps` =
| step | gate | qubits |
|------|------|--------|
| 1 | H | 0 |
| 2 | CX | 0,1 |
*`qc` = > quantum.circuit qubits=2 steps=`steps` *
*`p` = > `qc`.probabilities *
*`svg` = > `qc`.draw *
> print text=`p`
```
中文面对称:`量子.电路`、`哈达玛`、`控非`、`概率`、`绘图`。
---
## 10. 刻意不做(本 Accepted 范围)
- 真机 / 云后端(IBM、Braket…)
- 开放系统、完整噪声模型(可 Q5+)
- 符号电路编译优化器
- 交互式电路编辑器
- 把量子并入 `lib/math` 或核心 opcode
- 无上限比特的「生产级」模拟
---
## 11. 开放点(已收敛 / 剩余)
| 议题 | 结论 |
|------|------|
| 对象面 vs 自由函数 | **主推对象/方法链**;自由函数不平行提供 |
| 电路表 | **v1 纳入**(Q3),与方法链等价 |
| 振幅过大 | v1 全进 Value;n≤12 可接受;超限已挡 |
| view 产物 | **优先** `host_query("record_plot")` |
| 与 web | **不依赖** web 做可视化;SVG 自绘 |
---
## 12. 评审清单
1. ABI-only + 中英分文件是否认可?
2. 默认 12 qubits 上限是否合适?
3. 电路表列设计(步/门/比特/参数)是否够用?
4. view:电路轨线 + 概率条为 v1 必须,是否同意?
5. `$$` 矩阵核对放 Q4,是否同意先表驱动?
评审通过后:本文冻结为 Accepted → 按 §8 从 Q0 实现。
---
## 13. 一句话
**表格写出电路,类方法模拟与绘图;跑通金样即证明文档中的量子公式与步骤成立——math 管曲线,quantum 管希尔伯特空间上的可执行说明书。**
@@ -0,0 +1,74 @@
# 解决 1:路由与 `/admin` 前缀可让出
| | |
|---|---|
| 问题 | [研究 §1](../../research/ext-web-customization-limits.md#1-路由与路径被框架强占) |
| 优先级 | **P0** · 波次 **C0** |
| 触点 | `plugins/web/src/lib.rs`(`normalize_route_path`、`web_app_new`、redirect)· `plugins/web/src/http.rs`(admin 路由挂载、login redirect)· `ext/web/web.mq.md` / `网页.mq.md` |
---
## 1. 目标
1. 关闭内置后台后,**整段前缀可被站点路由占用**(含自研 `/admin`)。
2. 开启内置后台时,前缀**可配置**(默认仍 `/admin`),登录成功/登出落地页可配置。
3. `app.route` / `app.redirect` 只禁止**当前生效**的框架保留段,不再永久霸占 `/admin`。
---
## 2. 作者 API(草案)
```markdown
*应用 = > web.app page=`首页` db=`库` admin=False*
# 或:仍用内置 CRUD,但挂到旁路前缀 + 自定义回跳
*应用 = > web.app page=`首页` db=`库` admin=True*
*应用 = > `应用`.auth users=`用户表` admin_prefix="/desk" login_redirect="/desk" logout_redirect="/desk/login"*
```
| 参数 | 默认 | 含义 |
|------|------|------|
| `admin` / `后台` | `False` | `False`:**不注册**任何内置 admin HTTP 路由 |
| `admin_prefix` / `后台前缀` | `"/admin"` | 内置 CRUD + 登录页挂载根;仅 `admin=True` 时生效 |
| `login_redirect` / `登录回跳` | `{admin_prefix}` | 登录成功 303 目标 |
| `logout_redirect` / `登出回跳` | `{admin_prefix}/login` | 登出后目标 |
中文别名与英文一一对应,写进 `网页.mq.md`。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `normalize_route_path(app)` | reserved 列表改为:`/_form`、`/_part`、`/static` + **当前** `admin_prefix`(仅当 `admin=True`) |
| `listen` 路由表 | `admin=False` → **不** `.route("/admin…")`;为真则用 `admin_prefix` 拼路径 |
| `admin_login_post` / `admin_logout` | 使用配置的 redirect,禁止写死 `"/admin"` |
| `web_app_redirect` | 校验目标时用同一套动态 reserved,允许指向已让出的 `/admin` |
| disabled 文案路径 | 删除「挂路由但只显示 Admin is disabled」;无路由则 404 或落入站点自定义页 |
---
## 4. 兼容策略
- 缺省参数下:现有 `examples/web-site`、`web-net-site`、`marqdo-blog` 行为不变(仍 `/admin` + 跳 `/admin`)。
- 文档明确:`admin=False` 后若仍要登录能力,用 §3 的通用 `auth`/`gate`,不必再依赖内置 admin 壳。
---
## 5. 验收
| 金样 / 手工 | 期望 |
|-------------|------|
| `admin=False` + `route path="/admin/news"` | 注册成功;GET 渲染站点页,**不是** Admin is disabled |
| `admin_prefix="/desk"` | 内置登录在 `/desk/login`;成功跳 `login_redirect` |
| 默认 `admin=True` 无新参数 | 与现网一致 |
| `redirect` 到已让出的 `/admin` | 允许 |
---
## 6. 过渡期 → 已落地
~~继续用 `/desk` 旁路 + JS 调 `/admin/login`。~~
**C0 已落地(2026-09):** `admin=False` 可直接 `route path="/admin/…"`;或 `admin=True` + `admin_prefix="/desk"` + `login_redirect` / `logout_redirect`。见金样 `tests/ext/web-c0-admin-prefix.mq.md`。
@@ -0,0 +1,72 @@
# 解决 2:`SHELL_CSS` 可关 / 可分层
| | |
|---|---|
| 问题 | [研究 §2](../../research/ext-web-customization-limits.md#2-内置-shell_css-难以彻底覆盖) |
| 优先级 | **P1** · 波次 **C2** |
| 触点 | `plugins/web/src/render.rs`(`SHELL_CSS`、`<style>` 拼接)· page/app 元数据 · `ext/web` 样式装配 |
---
## 1. 目标
1. 站点主题可选择:**不要**框架栅格/卡片默认,或只要 reset 级变量。
2. 壳 CSS 与主题 CSS 的级联顺序**可声明、可文档化**。
3. 默认仍注入完整壳(兼容旧站);新主题显式 `shell_css=off` 即可干净起步。
---
## 2. 作者 API(草案)
```markdown
*应用 = > web.app page=`首页` … shell_css="minimal"*
# 或页面级覆盖
*页 = > `页`.meta …* # 或 page 选项 shell_css=
```
| 值 | 行为 |
|----|------|
| `full`(默认) | 现网 `SHELL_CSS` 全文 |
| `minimal` | 仅 `:root` 变量 + `body` margin/字体;**不含** `has-sidebar` 双列栅格与卡片表单皮肤 |
| `off` / `none` | 不注入框架壳样式;只输出站点 `style` / 外链 CSS |
级联顺序锁定为文档约定:
1. (可选)框架 `SHELL_CSS`
2. 站点全局 style 表 / `site.css`
3. 页面级 style
禁止再出现「主题写在 extra,却被同特异性壳规则在小屏打穿且无媒体查询」而无开关可关的情况。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| 拆分 `SHELL_CSS` | `SHELL_VARS` / `SHELL_LAYOUT` / `SHELL_WIDGETS` 三段;`full`=`all`,`minimal`=vars(+极简 layout) |
| `render` 读 `app.shell_css` / `page.shell_css` | 页面覆盖应用 |
| 为 `has-sidebar` 布局加基础媒体查询 | 即使 `full`,小屏改为单列(减轻幽灵双列);`minimal`/`off` 不负责响应式 |
---
## 4. 兼容策略
- 默认 `full`:视觉与现网一致。
- Tutorial 增加一节「品牌主题请用 `shell_css=minimal|off`」。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| `shell_css=off` + 站点只写单列 grid | 响应里**无** `grid-template-columns:14rem` |
| `minimal` | 有 CSS 变量;无 `.content.cards article` 边框默认(或等价皮肤段) |
| 默认示例站 | HTML 仍含完整壳 CSS |
---
## 6. 过渡期 → 已落地
**C2 已落地(2026-09):** `shell_css=full|minimal|off`;页面/应用可设;`full` 含 `@media (max-width:720px)` 单列。金样 `tests/ext/web-c2-shell-layout.mq.md`。
@@ -0,0 +1,72 @@
# 解决 3:鉴权 / 门禁可配置且行为一致
| | |
|---|---|
| 问题 | [研究 §3](../../research/ext-web-customization-limits.md#3-鉴权--门禁模型偏固定) |
| 优先级 | **P0** · 波次 **C1**(依赖 [01](01-routes-and-admin-prefix.md) 的 prefix) |
| 触点 | `plugins/web/src/http.rs`(`rbac_middleware`、`path_matches`、login 表单)· `lib.rs`(`web_app_auth` / `web_app_gate`)· `ext/web` |
---
## 1. 目标
1. **未登录策略一致**:可配置 `redirect`(303 登录)或 `forbid`(403),对任意 gate 路径生效,不再「仅 `/admin*` 会跳登录」。
2. **匹配语义清晰**:支持精确路径、前缀、以及排除列表;`/desk` 默认**不**误伤 `/desk/login`。
3. 默认 admin gate 使用 **路径段边界**(`/admin` 与 `/admin/…`),不匹配 `/admin-publish`。
4. 登录 URL、表单 `action`、成功/失败回跳均可配置(与 C0 对齐)。
---
## 2. 作者 API(草案)
```markdown
*应用 = > `应用`.auth users=`用户表` login_path="/desk/login" login_redirect="/desk"*
*应用 = > `应用`.gate path="/desk" roles="admin" match="prefix" on_deny="redirect" exclude="/desk/login"*
```
| 字段 | 说明 |
|------|------|
| `login_path` | 登录页 URL(GET 表单 + POST 处理);默认 `{admin_prefix}/login` |
| `match` | `exact` \| `prefix`(默认对自定义 gate 建议 `prefix` + `exclude`) |
| `on_deny` | `redirect` \| `forbid`;`redirect` 时跳 `login_path`(可带 `?next=`) |
| `exclude` | 逗号分隔或表列:匹配前缀时放行的路径 |
`auth` 注册默认 gate 时:
- 使用 `{admin_prefix}` + 段边界,**不要** `starts_with("/admin")` 裸前缀。
- 自动把 `login_path` 加入放行列表。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `path_matches` | 增加 `exact`;`prefix` 要求下一字符为 `/` 或结尾;可选 exclude |
| `rbac_middleware` | 按 gate 的 `on_deny` 分支;通用放行 `login_path`,不写死 `/admin/login` |
| 登录 HTML | `action={login_path}`;hidden `next` 可选 |
| Session/CSRF | 短期仍用框架实现;文档标明字段名;中期再开放 `login_form` 自定义字段映射(非本波次必做) |
---
## 4. 兼容策略
- 未传新字段:行为对齐现网(`/admin*` → redirect 登录;其它自定义 gate → 403)。
- 新增金样:`/desk` gate + `/desk/login` 可匿名打开。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| visitor 访问 `/desk`(`on_deny=redirect`) | 303 → `/desk/login`,不是 403 |
| visitor 访问 `/desk/login`(exclude) | 200 登录页 |
| `/admin-publish` 无显式 gate | **不**被默认 admin gate 拦住 |
| 旧站仅 `app.auth` | 仍保护 `/admin*` |
---
## 6. 过渡期 → 已落地
**C1 已落地(2026-09):** `auth` 默认段边界 prefix + `on_deny=redirect` + 排除 `login_path`;自定义 `gate` 可设 `match` / `on_deny` / `exclude`。金样 `tests/ext/web-c1-gates.mq.md`;单元测试 `http::gate_tests`。
@@ -0,0 +1,69 @@
# 解决 4:样式表作者体验
| | |
|---|---|
| 问题 | [研究 §4](../../research/ext-web-customization-limits.md#4-样式作者体验受限) |
| 优先级 | **P2** · 波次 **C3** |
| 触点 | 表单元格表达式(T5)· `ext/web` style 装配 · 教程 / Skill · 可选校验 |
---
## 1. 目标
1. 含 `/`、`,`、括号的 CSS 值**不易被静默算坏**。
2. 复杂选择器 / `@keyframes` / 多层 media 有**官方推荐写法**(表内 vs 外链 vs raw 块)。
3. 与壳 CSS 的层叠关系在文档中一句话写清(并链到 [02](02-shell-css.md))。
---
## 2. 作者 API / 约定(草案)
### 2.1 立即固化的文档约定(可不改代码)
| 规则 | 说明 |
|------|------|
| 含 `/` 的值必须引号 | `"1 / 5"`、`"image/png"`(已有;Skill/教程加醒目反例) |
| 复杂皮肤优先外链 | `static/theme.css` + `page.head` / `app.icons` 同类资源表 |
| `@keyframes` / 长 media | 放外链 CSS,不塞进 GFM 单元格 |
| 调试 | `shell_css=off` 后只看主题文件,避免同页双源 |
### 2.2 产品增强(C3)
| 能力 | 说明 |
|------|------|
| `style` 装配时对可疑单元格告警 | 未加引号且含 `/` → listen/assemble 警告或硬错误(可开关) |
| 可选 `##` raw CSS 块绑定 | 例如页面附属 ````css` 具名块,**不经**表表达式求值 |
| 文档示例 | `min-width` + `max-width` 外链表;引用 [table-cell-expressions.md](../table-cell-expressions.md) |
---
## 3. 插件 / 核心改动点
| 改动 | 说明 |
|------|------|
| web style 编译 | 可选 `strict_css_cells=True`:裸 `/` 报错 |
| (可选)`web_page_css_raw` | 把文本 CSS 追加到页面,跳过 T5 |
| Skill `marqdo` / tutorial 14 | 增加「样式踩坑」小节 |
---
## 4. 兼容策略
- 默认不硬错误(避免打碎旧表);新 scaffold 默认 `strict_css_cells` 或文档强制引号。
- 不把完整 CSS 语法塞进表格方言——复杂内容走文件。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 文档反例 `grid-column` 裸 `1 / 5` | 在 strict 模式下失败或警告 |
| 外链 `theme.css` + `shell_css=off` | 无壳栅格串扰 |
| 现有 web 示例 | 默认模式仍绿 |
---
## 6. 过渡期 workaround
全部敏感值加引号;响应式与 keyframes 只写在 `static/*.css`;小屏问题优先关壳([02](02-shell-css.md))再调主题。
@@ -0,0 +1,85 @@
# 解决 5:页面壳与插槽松绑
| | |
|---|---|
| 问题 | [研究 §5](../../research/ext-web-customization-limits.md#5-页面壳与插槽约定僵硬) |
| 优先级 | **P1** · 波次 **C2/C4** |
| 触点 | `plugins/web/src/render.rs`(body class、四区 HTML)· page 槽位装配 · nav 组件表 |
---
## 1. 目标
1. 作者可选**非侧栏栅格**布局,而不必用 CSS 硬怼掉 `has-sidebar`。
2. 侧栏存在 ≠ 强制桌面双列;提供 stacked / bare 等预设。
3. 为「条件导航」留扩展点(先文档 + 简单 hook,完整运行时条件可后置)。
---
## 2. 作者 API(草案)
```markdown
*首页 = > web.page … layout="stacked"*
*应用 = > web.app page=`首页` … layout="bare"*
```
| `layout` | DOM / class | 说明 |
|----------|-------------|------|
| `sidebar`(默认,有 side 槽时) | `body.has-sidebar` | 现网行为 |
| `stacked` | `body.layout-stacked`;side 在 main 上或折叠区 | 单列流式,适合杂志/营销 |
| `bare` | 无 top/side/foot 强制栅格;只渲染 `main`(+ 显式槽) | 登录页、落地页 |
| `rail`(可选) | 保留站点已有 `has-rail` 约定并文档化 | 避免「只有首页有 class」 |
规则:**有 side 组件但 `layout=stacked|bare` 时,不自动加 `has-sidebar`。**
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `render` 读 `page.layout` / `app.layout` | 决定 body class 与 HTML 骨架 |
| `SHELL_LAYOUT`(见 [02](02-shell-css.md)) | 为 `layout-stacked` / `layout-bare` 提供最小样式;`shell_css=off` 时不注入 |
| Nav 表 | 短期保持声明式;文档说明「条件项用两套 nav 组件 + 媒体查询隐藏」 |
| 中期 hook(非阻断) | `navigate` 已有字段可扩展 `when`/`media` 列(单独 RFC) |
---
## 4. 兼容策略
- 未设 `layout`:有 side → 与现网 `has-sidebar` 相同。
- 金样增加 `layout=bare` 登录页(可与 C0 自研 `/desk/login` 共用)。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 有 side + `layout=stacked` | body **无** `has-sidebar`;无 `14rem` 双列(在 full 壳下用 stacked 规则) |
| `layout=bare` | 输出不含 `<aside class="side">`(或 empty 不占栅格) |
| 默认站 | 不变 |
---
## 6. 过渡期 → 已落地
**C2 已落地(2026-09):** `layout=sidebar|stacked|bare|rail`;有 side 时 `stacked`/`bare` 不再强制 `has-sidebar`。金样 `web-c2-shell-layout`。
**C4 已落地(2026-09):** 导航 / 侧栏 / 页脚绑定表可选列:
| 列 | 说明 |
|----|------|
| `媒体` / `media` | CSS media;不匹配时 `display:none`(生成 `nav-mq-*` + `@media not …`) |
| `当` / `when` | `hide` 省略;`auth` / `guest` 按登录态过滤;空 = 总是显示 |
```markdown
| 属性 | 值 | 样式 | 媒体 | 当 |
|------|-----|------|------|-----|
| Home | / | | | |
| Menu | /m | | (max-width: 720px) | |
| Admin | /admin | | | auth |
| Login | /login | | | guest |
```
Listen 渲染时写入 `_logged_in` / `_nav_user`(来自 session)。离线 `page.render` 可自行 `table.put` `_logged_in`。金样 `web-c4-nav-when`。
@@ -0,0 +1,67 @@
# 解决 6:后台 CRUD 与表单能力边界
| | |
|---|---|
| 问题 | [研究 §6](../../research/ext-web-customization-limits.md#6-后台-crud-与表单能力边界) |
| 优先级 | **P3** · 随 C0 文档化;增强可选 |
| 触点 | `plugins/web/src/http.rs` / `form.rs`(内置 admin)· 站点自研页 + `db.*` · `/_form` |
---
## 1. 目标
1. **产品叙事澄清**:内置 `/admin`(或可配置前缀)= 通用表浏览器,**不是** CMS;关则彻底让路(见 [01](01-routes-and-admin-prefix.md))。
2. 自研后台的推荐路径写清楚:`page` + `form` + `db` + gate,而不是改插件壳。
3. 对「链接前缀 / new / edit」给出约定或薄辅助,减少前端状态机拼装。
---
## 2. 作者 API / 文档(草案)
### 2.1 推荐架构(文档为主)
| 需求 | 做法 |
|------|------|
| 产品级编辑器、专栏联动 | 自研 `# page` + 组件;写库用 `db.insert`/`update`;鉴权用 `gate` |
| 简单表维护 | 开 `admin=True`(可换前缀) |
| 关内置仍要 CRUD | 自研列表/编辑页;**不要**依赖 disabled 壳 |
### 2.2 可选薄增强(非 CMS)
| 能力 | 说明 |
|------|------|
| `form` 支持 `mode=new\|edit` 查询参数约定 | 文档 + 示例;必要时 `web.form` 读 `id`/`new` |
| `list` 组件 `link_prefix` | 已有则补示例;缺失则加一列「详情路径模板」 |
| Markdown 字段 | 继续「存库 + 前台渲染」;分栏编辑器保持外挂 JS(明确不做进 ABI) |
---
## 3. 插件改动点
| 改动 | 优先级 |
|------|--------|
| C0:disabled 不占路径 | 必需(属 [01](01-routes-and-admin-prefix.md)) |
| 示例 `examples/web-custom-desk/` | 展示自研列表/编辑,零内置 admin |
| form 查询参数助手 | 可选 |
---
## 4. 兼容策略
- 不扩展内置 admin 成 CMS(避免范围爆炸)。
- Tutorial 增加「何时用内置 admin / 何时自研」。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 文档 + 示例 desk | 无 `/admin` 也能完成一文增删改 |
| 内置 admin 金样 | 仍绿 |
---
## 6. 过渡期 workaround
自研 `/desk` + 调用 `/_form` 或直接 DB API;复杂编辑器继续外挂 JS。
@@ -0,0 +1,71 @@
# 解决 7:静态资源与脚本生命周期
| | |
|---|---|
| 问题 | [研究 §7](../../research/ext-web-customization-limits.md#7-静态资源与脚本生命周期) |
| 优先级 | **P2** · 波次 **C3** |
| 触点 | `web_page_head` / `web_head` · `render.rs` head 输出 · static 挂载 · [web-assets-and-images.md](../web-assets-and-images.md) |
---
## 1. 目标
1. 默认脚本加载方式**不假设**作者手写 IIFE 抢在 DOM 前执行成功;提供 `defer` / `module` 一等约定。
2. 静态资源变更可发现:文档化 `?v=`,并提供可选自动指纹或 listen 时 mtime 查询参数。
---
## 2. 作者 API(草案)
Head 资源表扩展列(向后兼容):
| 列 | 说明 |
|----|------|
| `rel` / `关系` | 已有;`script` / `module` |
| `defer` / `推迟` | `真` → `<script defer>`(**建议默认对 script 为真**) |
| `async` / `异步` | 可选 |
| `version` / `版本` | 非空则自动追加 `?v=` |
```markdown
`头` =
| 关系 | 地址 | 推迟 | 版本 |
|------|------|------|------|
| script | /static/theme.js | 真 | 2026-09-04 |
| module | /static/desk.js | 真 | 3 |
```
全局:`app.asset_version="2026-09-04"` 为所有 static 链接统一 bump(可选)。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| head 渲染 | 尊重 defer/async;`module` → `type="module"`(已有则核对) |
| 默认 | 新建 scaffold 的 script 行带 `defer` |
| (可选)`asset_version` | listen 时重写 head / 页面内 static URL |
| 文档 | 「禁止在同步 head 脚本里直接 `getElementById` 主节点;用 defer 或 `DOMContentLoaded`」 |
---
## 4. 兼容策略
- 旧表无 `defer` 列:保持现网同步行为(或仅对 scaffold/新文档默认 defer,避免静默改变旧站时序)。
- 更安全:缺省仍同步;**Skill 与 scaffold 默认写 defer=真**。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| defer 脚本读 DOM | 登录跳转逻辑在 DOM 就绪后执行 |
| `version` 列 | HTML 中出现 `theme.js?v=…` |
| 旧示例无新列 | 仍通过 |
---
## 6. 过渡期 workaround
脚本改 `type=module` 或放 body 末;手动 `?v=` bump;登录逻辑用 `DOMContentLoaded`。
@@ -0,0 +1,68 @@
# 解决 8:扩展与部署耦合
| | |
|---|---|
| 问题 | [研究 §8](../../research/ext-web-customization-limits.md#8-扩展与部署耦合) |
| 优先级 | **P3** · 文档 + 发布流程 |
| 触点 | `marqdo ext add web` · ABI 版本 · Docker/发布说明 · [ext-cli.md](../ext-cli.md) · [marqdo-release](../../../.cursor/skills/marqdo-release/SKILL.md) |
---
## 1. 目标
1. 站点作者**不必 fork 插件**才能完成 P0/P1 定制(把能力收进官方参数,见 01–05)。
2. 版本耦合可预期:changelog / 扩展清单标明「web 插件需 ≥ x.y.z」。
3. 升级路径文档化:二进制、`.marqdo-ext`、Docker 镜像三者对齐检查。
---
## 2. 作者 / 运维约定(草案)
| 约定 | 说明 |
|------|------|
| 定制优先走 `.mq.md` 开关 | `admin_prefix`、`shell_css`、`layout`、`gate`… 进官方 API 后,禁止文档再教「改 plugins/web」 |
| 兼容性矩阵 | 在 [web-net-capabilities.md](../web-net-capabilities.md) 或本目录维护「Marqdo ↔ libweb 最低版本」表 |
| `marqdo ext add web` | 安装后打印当前插件路径与版本;与 CLI 版本不符时警告 |
| Docker | 示例 Dockerfile 注释:升级需同时换 `marqdo` 与 `ext add` 产物 |
| 样式引号等行为变更 | 写入 CHANGELOG **Breaking / migration** 小节(如 0.3.2 T5) |
---
## 3. 工程改动点
| 改动 | 说明 |
|------|------|
| 插件/Crate 版本可见 | `web_listen` 或 `ext list` 显示 web ABI/包版本 |
| CI | 金样使用仓库内 `plugins/web`;发布技能检查 VSIX/CLI/插件三件套 |
| 研究→设计→路线图 | C0–C4 进 [ext-web roadmap](../../roadmap/ext-web.md),避免只活在私有 fork |
---
## 4. 兼容策略
- 不承诺插件源码级稳定 API;承诺 **`.mq.md` 作者 API** 在小版本尽量兼容,破坏性变更进 CHANGELOG。
- Fork 插件仅作为「官方尚未交付」的临时手段,并在 issue/路线图留归还项。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 升级说明文档 | 运维按清单升级后 web 金样通过 |
| C0–C2 落地 | 自研后台场景**无需**改 `plugins/web` 源码 |
| `ext list` / 文档 | 能核对版本 |
---
## 6. 过渡期 → 预编译路径(进行中)
**目标:** 用户 `marqdo ext add web` **不必**本机 Rust。
| 交付 | 说明 |
|------|------|
| Release `marqdo-*-native-*.zip` | Windows / Linux 预编译 `web`/`agent`/`quantum` |
| Windows portable zip | 内含 `ext/` + `ext/native/*.dll` |
| `ext add` 下载回退 | 本地无 `.so`/`.dll` 时从 GitHub Release 拉取(`MARQDO_EXT_NO_DOWNLOAD=1` 可关) |
仍保留开发者 `cargo build -p marqdo_plugin_*` 路径。详见 [ext-cli.md](../ext-cli.md)。
@@ -0,0 +1,50 @@
# `ext/web` 定制修复:解决文档索引
| | |
|---|---|
| 状态 | **C0–C4 done** |
| 日期 | 2026-09-04 |
| 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) |
| 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) |
对应研究文 §1–§8,每项一份解决文档:**目标 → 作者 API → 插件改动点 → 兼容策略 → 验收**。
实现时优先 **不破坏现有金样**(`tests/ext/web-*`、`examples/web-*`);新能力用显式 opt-in 参数打开。
---
## 文档一览
| # | 主题 | 文档 | 建议优先级 |
|---|------|------|------------|
| 1 | 路由与 `/admin` 前缀可让出 | [01-routes-and-admin-prefix.md](01-routes-and-admin-prefix.md) | P0 |
| 2 | `SHELL_CSS` 可关 / 可层 | [02-shell-css.md](02-shell-css.md) | P1 |
| 3 | 鉴权门禁可配置且行为一致 | [03-auth-gates.md](03-auth-gates.md) | P0 |
| 4 | 样式表作者体验 | [04-stylesheet-authoring.md](04-stylesheet-authoring.md) | P2 |
| 5 | 页面壳与插槽松绑 | [05-page-shell-slots.md](05-page-shell-slots.md) | P1 |
| 6 | 后台 CRUD / 表单边界 | [06-admin-crud-forms.md](06-admin-crud-forms.md) | P3 |
| 7 | 静态资源与脚本生命周期 | [07-assets-script-lifecycle.md](07-assets-script-lifecycle.md) | P2 |
| 8 | 扩展与部署耦合 | [08-ext-deploy-coupling.md](08-ext-deploy-coupling.md) | P3 |
---
## 波次建议(实现用)
| 波次 | 内容 | 依赖 |
|------|------|------|
| **C0** | 可配置 `admin_prefix`;`admin=False` 时不挂内置路由;`login_redirect` / `logout_redirect` | — |
| **C1** | gate:统一未登录策略;精确/前缀匹配;登录页自动放行;默认 gate 不再误伤 `/admin-*` | C0 |
| **C2** | `shell_css=off\|minimal\|full`;主题在壳前或隔离层;可选 `layout=bare` | — |
| **C3** | 样式:校验警告 / `strict`;`page.css` raw;脚本 `defer`/`async`/`version` + `asset_version` | **done** |
| **C4** | 壳:`layout` 预设(C2);条件导航 `when` / `media` | **done** |
路线图入口可在 [ext-web.md](../../roadmap/ext-web.md) 增补「定制波次 C0–C4」行,落地后再改状态。
---
## 产品原则(解法共同约束)
1. **`.mq.md` 仍是真相源** — 能声明的不进隐藏默认;新开关写在 `app` / `page` / `listen` 参数表。
2. **内置 admin 是可选产品**,不是不可替换的内核路由命名空间。
3. **默认行为保持兼容** — 现有 tutorial / 示例零改动仍能跑;新站显式打开定制。
4. **禁止**为单站需求永久硬编码第二套旁路(如永远推荐 `/desk` + JS fetch 登录)。
+124
View File
@@ -0,0 +1,124 @@
# `ext/web` 驱动:Postgres · Redis · S3
| | |
|---|---|
| 状态 | **Accepted · 已落地** |
| 日期 | 2026-08-28 |
| 相关 | [ext-web.md](ext-web.md) · [roadmap/ext-web.md](../roadmap/ext-web.md) · [ext-abi.md](ext-abi.md) |
| 目标 | 在**不改作者面 CRUD 心智**的前提下,用 URL 方案切换数据库;另增缓存与对象存储两类驱动。贯彻「表格 + 类方法」:配置即数据,装配即函数。 |
---
## 0. 一句话
**`# db` 的 `url=` 决定后端**:`sqlite:` 默认;`postgres://` / `postgresql://` 走 Postgres,作者面 API 不变。
**缓存**与**对象存储**是独立类(`# cache` / `# storage`),不塞进 `# db`。
---
## 1. 边界
| 能力 | 归属 | 理由 |
|------|------|------|
| SQLite / Postgres CRUD | `plugins/web` + `ext/web` `# db` | 同一套 `init/select/insert/…`;热路径 ABI |
| Redis 缓存 | `plugins/web` + `ext/web` `# cache` | 键值语义,不是表 CRUD |
| S3 / MinIO 对象 | `plugins/web` + `ext/web` `# storage` | 对象键 + 字节/路径,不是行 |
| 禁止 | 核心 `src/host/` | 驱动依赖重,只进 ABI 插件 |
---
## 2. URL 方案(锁定)
| 方案 | 含义 | 例 |
|------|------|-----|
| `sqlite:` / 裸路径 | SQLite 文件(既有) | `sqlite:data/site.db` |
| `postgres://` / `postgresql://` | Postgres | `postgres://user:pass@127.0.0.1:5432/app` |
| `redis://` / `rediss://` | Redis | `redis://127.0.0.1:6379/0` |
| `memory:` | **进程内** Redis 兼容后端(金样/离线) | `memory:` |
| `s3://bucket` + 查询参数 | S3 兼容(含 MinIO) | `s3://mybucket?endpoint=http://127.0.0.1:9000&region=us-east-1` |
| `file:` | **本地目录**对象存储(金样/离线) | `file:data/blobs` |
凭证:优先 URL 内嵌;S3 亦读环境变量 `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`(或 `S3_ACCESS_KEY` / `S3_SECRET_KEY`)。
---
## 3. 作者面(代码即文档)
### 3.1 数据库 — 只换 URL
英文:
```markdown
import web:ext/web/web.mq.md
# main
*store = > web.db url="postgres://marqdo:marqdo@127.0.0.1:5432/site"*
*store = > store.init name="posts" fields=`schema`*
```
中文:`网页.数据库` + `url=` 同形。`init` / `select` / `insert` / `paginate` / `事务` **API 不变**。
Postgres 差异(实现层消化,作者尽量无感):
- `id INTEGER PRIMARY KEY` → `SERIAL PRIMARY KEY`(或 `GENERATED …`)
- 占位符 `?` → `$1,$2,…`
- 标识符双引号规则对齐
### 3.2 缓存 `# cache` / `# 缓存`
```markdown
*c = > web.cache url="memory:"*
*c = > c.set key="k" value="v" ttl=60*
*v = > c.get key="k"*
*c = > c.del key="k"*
```
方法:`get` · `set`(可选 `ttl` 秒)· `del` · `exists` · `ttl`。
配置表可选(装配时合并进 url / 默认 TTL):
| 键 | 值 |
|----|-----|
| url | redis://127.0.0.1:6379/0 |
| ttl | 3600 |
### 3.3 对象存储 `# storage` / `# 存储`
```markdown
*blob = > web.storage url="file:data/blobs"*
> `blob`.put key="avatar/1.png" path="local.png" content_type="image/png"
*got = > `blob`.get key="avatar/1.png"*
> `blob`.delete key="avatar/1.png"
*keys = > `blob`.list prefix="avatar/"*
```
方法:`put`(`path=` 本地文件或 `body=` 文本)· `get`(返回 `{ok, body|path, content_type}`)· `delete` · `list`。
---
## 4. ABI 名
| ABI | 说明 |
|-----|------|
| 既有 `web_db_*` | 内部按 `url` 方案分发 SQLite / Postgres |
| `web_cache_new/get/set/del/exists/ttl` | 缓存 |
| `web_storage_new/put/get/delete/list` | 对象存储 |
---
## 5. 测试
| 金样 | 内容 |
|------|------|
| `tests/ext/web-drivers-smoke.mq.md` | `memory:` 缓存往返;`file:` 存储 put/get/list/delete;`web_db_new` 接受 `postgres://` 句柄形状(不要求本机有库) |
| 可选 live | `MARQDO_TEST_POSTGRES` / `MARQDO_TEST_REDIS` / `MARQDO_TEST_S3` 非空时跑真实连通(CI 默认关) |
---
## 6. 非本波次
- 连接池大小 / 读写分离配置表
- Redis 集群 / Sentinel
- S3 预签名 URL 作者面糖(可后续加方法)
- 把 session 默认改存 Redis(仍默认 SQLite 表;可选后续)
+454
View File
@@ -0,0 +1,454 @@
# `plugins/web` Go 全量重写(多语言 ABI 生态 · 网页制备完备)
| | |
|---|---|
| 状态 | **Completed(W-G0…W-G14 · v0.4.0)** |
| 日期 | 2026-09-10 |
| 相关 | [ext-web.md](ext-web.md) · [ext-web-net.md](ext-web-net.md) · [web-net-capabilities.md](web-net-capabilities.md) · [ext-web-drivers.md](ext-web-drivers.md) · [web-assets-and-images.md](web-assets-and-images.md) · [ext-hosting-fill.md](ext-hosting-fill.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md) |
| 实现目录 | `plugins/web/`(**Go module**;产物仍为 `libweb.so` / `web.dll` / `libweb.dylib`) |
| 作者面 | `ext/web/web.mq.md` · `ext/web/网页.mq.md`(**ABI 名与方法面保持兼容**;非另起一套 API) |
| 验收应用 | 工作区 `anlian`(暗恋见君):用 Marqdo 前后端脚本完整重写;**PostgreSQL + Redis 外接** |
---
## 0. 一句话
用 **Go** 重写官方网络拓展库原生层(`plugins/web`),在 **C ABI v2 全量兼容** 前提下提供「网页制备」所需的全部服务端能力;`ext/web` 继续用 GFM 表 + `#` 类做作者面;应用(含暗恋见君)的前后端脚本全部用 Marqdo 书写。此举同时验证 **多语言 ABI 插件生态**(首个非 Rust 官方插件)。
**不是**最小 hello 插件;**不是**在旧 Rust 代码上打补丁(对齐 [ext-web.md](ext-web.md) **C5**)。
---
## 1. 动机与目标
### 1.1 为何重写
| 动机 | 说明 |
|------|------|
| 开发/编译节奏 | Rust 插件迭代慢,网络域能力长期「半成品感」来自堆叠依赖与慢反馈,而非语言绝对性能 |
| 多语言生态 | ABI 已是稳定 C 契约;需要第一个 **Go** 官方插件证明「宿主 Rust ≠ 插件必须 Rust」 |
| 网页制备完备 | 目标是支持 **完整动态站点制备**(装配、CRUD、鉴权、实时、上传、SEO、代理、驱动…),并以真实论坛项目验收 |
| 性能与拉起 | Go `net/http` 生态成熟、单二进制友好;论坛级 IO 密集负载下足够「极致可用」 |
### 1.2 成功标准(全部满足才算完成)
1. **ABI 全量对等**:下文 §5 列出的每一个已注册 `web_*` 符号,参数 CSV、JSON 形、语义与现网 gold 一致(中英参数别名保留)。
2. **作者面可用**:现有 `ext/web` 示例与 `tests/ext/web-*`(含 live-server)在换 Go `.so` 后通过;无需作者改业务脚本(除非文档标明的 **G 增强**)。
3. **网页制备完备**:单站点可完成页面装配、样式/头/图、库表、表单、路由、中间件、鉴权/RBAC、上传下载、SEO/RSS/sitemap、WS、缓存、对象存储、反代、invoke——即 W0–W8 + P3 + C0–C4 + H1/H2 能力面。
4. **驱动外接**:`postgres://`、`redis://`、`s3://` 为正式一等能力(与 [ext-web-drivers.md](ext-web-drivers.md) 一致);SQLite / memory / file 仍支持本地与测试。
5. **暗恋见君可写完**:用 Marqdo 后端脚本 + 浏览器 WASM 前端脚本重写 anlian 核心模块(见 §8);运行时仅依赖 `marqdo` + `libweb` + **外接 PostgreSQL + Redis**(可选 S3/RustFS)。
6. **安装路径不变**:`marqdo ext add web`、`plugin.native_path name=web`、`MARQDO_WEB_PLUGIN`、产物文件名 `libweb.so` 等与 [ext-cli.md](ext-cli.md) 兼容。
### 1.3 非目标
| 非目标 | 说明 |
|--------|------|
| 改 Marqdo 核心语法 | 仍遵守 ext-web **C1** |
| 把服务器搬进浏览器 WASM | 仍遵守 ADR 0002 |
| 进程内 TLS | HTTPS 由反代;`cookie_secure` 保留 |
| 第三方插件市场 | 仍无 registry |
| 把论坛业务写进 Go 插件 | 帖子/新闻/聊天室规则在 `.mq.md`;插件只提供原语 |
| 强制嵌入式替代 PG/Redis | 本项目明确 **允许并依赖外接** PG/Redis |
---
## 2. 分层架构(锁定)
```text
┌──────────────────────────────────────────────────────────────────┐
│ 应用(anlian / 任意站点) │
│ · 后端 .mq.md:路由、业务、装配、invoke 处理函数 │
│ · 前端 .mq.md:WASM + lib/browser(作者零业务 JS) │
└────────────────────────────┬─────────────────────────────────────┘
│ import web / 网页
┌────────────────────────────▼─────────────────────────────────────┐
│ ext/web(L1 · Marqdo) │
│ # page # db # app # form # auth # cache # storage # media # ws │
│ make_style / make_head / make_images / client_embed … │
└────────────────────────────┬─────────────────────────────────────┘
│ lib/plugin → dlopen
┌────────────────────────────▼─────────────────────────────────────┐
│ plugins/web(L0 · Go · C ABI v2) ← 本文件重写对象 │
│ net/http + 驱动适配 + HTML 装配 + WS hub + 中间件 … │
└──────────┬─────────────────┬─────────────────┬───────────────────┘
│ │ │
PostgreSQL Redis S3/MinIO/RustFS
(外接) (外接) (可选外接)
```
| 层 | 语言 | 职责 |
|----|------|------|
| 应用脚本 | Marqdo | 前后端业务、页面表、领域模型 |
| `ext/web` | Marqdo | 双语作者 API;禁止直接 `host_*` |
| `plugins/web` | **Go** | 全部 `web_*` ABI;高性能网络与驱动 |
| `lib/net` | Marqdo + Rust host | **仅**客户端 HTTP / cookie / multipart / markdown **解析**;不进本重写范围(边界不变) |
| 宿主 | Rust | `dlopen`、JSON Value、`host_query`(`entry_dir` / `call_lib_path` …) |
---
## 3. 硬约束(继承 + 本重写追加)
### 3.1 继承 ext-web C1–C7
| ID | 约束 |
|----|------|
| C1 | 不为 web 改核心语法 |
| C2 | 作者面禁止 json 袋胶水拼装页面 |
| C3 | 中英 API 分文件;禁止混排 |
| C4 | 首页 `index.mq.md`;组件可拆 |
| C5 | **禁止在旧 Rust 插件上打补丁演进**;清空/替换后用 Go 重写 |
| C6 | `# db` 完整 CRUD;`select`/`查询`;admin 与表单共用写库 API |
| C7 | 表单字段+规则;**写库前服务端校验** |
### 3.2 本重写追加(G 系列)
| ID | 约束 |
|----|------|
| **G1** | 产物仍为 C ABI v2;`MARQDO_ABI_VERSION = 2`;导出符号名与 [include/marqdo_abi.h](../../include/marqdo_abi.h) 一致 |
| **G2** | **ABI 函数名与参数名向后兼容**:§5 清单中每个 `web_*` 必须注册;参数 CSV 与现 Rust 插件一致(含中文别名) |
| **G3** | Go 使用 `-buildmode=c-shared`;**禁止**把 Go runtime 假设成唯一线程——跨 FFI 调用必须可重入或明确串行化文档 |
| **G4** | `marqdo_plugin_shutdown` 必须停止 HTTP/WS、关闭 DB/Redis 连接、释放 hub |
| **G5** | 字符串跨界:成功时 `*out_json` / 失败时 `*err_msg` 必须用 **host `alloc`** 分配(与现插件相同),由宿主 `free` |
| **G6** | 相对路径(sqlite 文件、静态目录、上传根)一律相对 `host_query("entry_dir")` |
| **G7** | 多语言样板:仓库内保留可复用的 Go ABI 脚手架注释/包结构,供后续其它语言插件参考 |
| **G8** | 金样例不过 = 未完成;切换默认 `libweb` 到 Go 后,既有 `tests/ext/web-*` 必须绿 |
---
## 4. 技术选型(Go)
| 能力 | 选型 | 备注 |
|------|------|------|
| HTTP 服务器 | 标准库 `net/http` | 路由可用轻量自研 mux 或 `chi`/`http.ServeMux`(Go 1.22+ 模式) |
| 中间件 | 自研链式 `func(http.Handler) http.Handler` | 对等 CORS / 安全头 / gzip / body limit / access_log / cache-control |
| WebSocket | `gorilla/websocket` 或 `coder/websocket` | 对等 echo / broadcast / drain;**G 增强**:命名房间(§7) |
| SQLite | `modernc.org/sqlite`(纯 Go)或 `mattn/go-sqlite3`(cgo) | 优先纯 Go 以便交叉编译;FTS5/migrate 行为对齐 |
| PostgreSQL | `jackc/pgx/v5` | `postgres://` / `postgresql://` |
| Redis | `redis/go-redis/v9` | `# cache`;**G 增强**:可选 session/WS 后端 |
| S3 | `aws-sdk-go-v2` 或 MinIO SDK | `s3://`;兼容 RustFS |
| 密码 | `golang.org/x/crypto/argon2` | argon2id 参数对齐现实现 |
| Markdown | `goldmark`(GFM 扩展) | 对等 `pulldown-cmark` 用途(正文 HTML) |
| JSON | `encoding/json` | ABI 边界 |
| 构建 | `go build -buildmode=c-shared -o libweb.so` | 见 §9 |
**不引入**完整 Web 框架(Gin/Echo 业务层)以免作者面旁路;框架能力用 Marqdo `# app` 表达。
---
## 5. ABI 全量清单(必须注册 · 兼容)
> 参数列为注册时 `params` CSV(英;实现须同时接受设计中已有的中文键别名,与现 `lib.rs` 一致)。
> 状态列:`P0` = 首波必须与 gold 对齐;实现顺序见 §10。
### 5.1 Page / compose / assets / render
| ABI | params(摘要) | 域 |
|-----|----------------|-----|
| `web_page_new` | (空或 title 等,对齐现实现) | page |
| `web_compose_components` | page, components, … | compose |
| `web_compose_main` | page, main, … | compose |
| `web_page_query` | page, query | page |
| `web_page_order` | page, order | page |
| `web_page_link_prefix` | page, prefix | page |
| `web_page_css` | page, css | page |
| `web_page_detail` | page, … | page |
| `web_page_meta` | page, meta | SEO |
| `web_page_head` | page, head | W8 |
| `web_page_images` | page, images | W8 |
| `web_page_paginate` | page, … | content |
| `web_head` | table / … | W8 |
| `web_images` | table / … | W8 |
| `web_app_icons` | app, icons | W8 |
| `web_style` | table, strict? | CSS |
| `web_compose_form` | page, form, target? | form embed |
| `web_render` | page | HTML |
### 5.2 SEO / ops routes
| ABI | 域 |
|-----|-----|
| `web_rss_build` | RSS |
| `web_app_route_rss` | app |
| `web_app_redirect` | app |
| `web_app_error_page` | app |
| `web_app_sitemap` | app |
| `web_app_robots` | app |
| `web_sitemap_build` | sitemap |
### 5.3 Upload / media
| ABI | 域 |
|-----|-----|
| `web_app_upload` | app |
| `web_app_download` | app |
| `web_upload_validate` | media |
| `web_upload_save` | media |
| `web_media_new` | media |
| `web_app_gallery` | app |
### 5.4 Database
| ABI | 备注 |
|-----|------|
| `web_db_new` | `sqlite:` / `postgres://` |
| `web_db_init` | unique / index / fk / 审计时间戳 |
| `web_db_insert` / `select` / `get` / `update` / `delete` / `exec` | CRUD |
| `web_db_query` / `count` | 原生 / 计数 |
| `web_db_migrate` | **SQLite only**(对等) |
| `web_db_fts_create` / `web_db_search` | **SQLite only** |
| `web_db_begin` / `commit` / `rollback` | 事务句柄 |
| `web_db_list_tables` / `web_db_table_info` | admin 内部 |
Where 语义:等值 map、filter 表、OR / IN / BETWEEN、分页 offset/limit——行为对齐现 `db.rs` / `db_pg.rs`。
### 5.5 Cache / storage
| ABI | URL |
|-----|-----|
| `web_cache_new` / `get` / `set` / `del` / `exists` / `ttl` | `memory:` / `redis://` |
| `web_storage_new` / `put` / `get` / `delete` / `list` | `file:` / `s3://` |
### 5.6 App / HTTP / hosting
| ABI | 域 |
|-----|-----|
| `web_app_new` | app |
| `web_app_route` | 动态 `{param}` + `/_part` |
| `web_app_mount_form` | `/_form` |
| `web_app_static` | 静态目录 |
| `web_app_middleware` | `configure`:CORS、安全头、gzip、body_limit、JSON API、access_log、cache_control |
| `web_app_proxy` | 流式反代 / SSE(H1) |
| `web_app_invoke` | HTTP → `lib.member`(H2;经 `host_query call_lib_path`) |
| `web_listen` | 阻塞监听;组装全部路由 |
| `web_app_route_ws` | WS 端点 |
| `web_ws_connect` | 客户端单次请求-响应式 |
| `web_app_auth` | `/admin` 门禁 |
| `web_app_gate` | RBAC 段前缀 |
### 5.7 Form
| ABI |
|-----|
| `web_form_new` / `fields` / `rules` / `validate` / `render` / `submit` / `from_schema` |
规则:`required`、`min:N`、`max:N`、`email`、`url`、`match:field`、`in:a,b,c`。
### 5.8 Session / auth
| ABI |
|-----|
| `web_session_new` / `set` / `get` / `del` / `destroy` |
| `web_auth_new` / `login` / `check` / `logout` |
| `web_password_hash` |
安全对等:argon2id、CSRF、登录限速、CSPRNG session id、cookie Secure(配置)、滑动 TTL、持久化会话(默认 SQLite 会话表;见 §7 Redis 可选)。
### 5.9 HTTP 挂载面(`web_listen` 必须复现)
- `GET /`,`GET /_part/{id}`,`GET|POST /_form/{id}`
- 可选 admin:`{prefix}/`、`/login`、`/logout`、`/{table}`、`/new`、`/{id}/edit`、`/{id}/delete`(C0:`admin=False` 让出 `/admin`)
- 作者 `route` 页 + `{path}/_part/{id}`;动态路径参数
- WS;RSS;upload POST;download GET;gallery;sitemap;`/robots.txt`
- 301/307 重定向;自定义 404/500;proxy;invoke
- 静态与 icons;约定 `/favicon.ico`
- 保留名:`/_form`、`/_part`、静态挂载冲突检测
### 5.10 `host_query` 依赖
| name | 用途 |
|------|------|
| `entry_dir` | 路径沙箱根 |
| `call_lib_path` | invoke / 嵌套 lib 调用(含 `args`) |
| (其它已允许项) | 与 ABI v2 allowlist 一致;不得扩展任意 HostFn |
---
## 6. 作者面(保持 · 不另起炉灶)
英文 `ext/web/web.mq.md` / 中文 `ext/web/网页.mq.md` 现有 `#` 类与 `##` 方法 **保持**:
| 类 | 职责 |
|----|------|
| `# page` / `# 页面` | 装配、meta、head、images、paginate、render |
| `# db` / `# 数据库` + `# txn` | CRUD、事务、migrate/FTS(SQLite) |
| `# form` / `# 表单` | 字段、规则、校验、渲染、提交 |
| `# app` / `# 应用` | route、configure、listen、auth、gate、upload… |
| `# auth` / `# 鉴权` | login/check/logout/hash |
| `# cache` / `# 缓存` | memory/redis |
| `# storage` / `# 存储` | file/s3 |
| `# media` / `# 媒体` | validate/save |
| `# ws` / `# 实时` | connect |
| 模块函数 | `ensure_plugin`、`make_style`、`make_head`、`make_images`、`client_embed`、`text_patch`、`dom_patch`、`list_html` |
**重写默认策略**:先 **只换原生 `.so`**,L1 不动;仅当 §7 G 增强需要新方法时,再 **追加**(不破坏旧方法)。
---
## 7. G 增强(完备网页制备 + anlian;兼容之上增量)
> 以下为 **新增能力**,不替代 §5。作者面用新方法/新 configure 键;旧脚本不受影响。
| ID | 能力 | 动机 | 作者面草案 |
|----|------|------|------------|
| **G-WS1** | **命名房间** WS:`join`/`leave`/`publish`;组名 ASCII(如 `chat.room.{id}`) | anlian 公聊/私聊 | `app.route_ws` 增 `mode=room` + `room_key`;或 `ws.room_*` ABI |
| **G-WS2** | 房间消息钩子:先 `invoke`/落库再广播 | 「先写 PG 再推送」 | configure 或 route 表 `on_message=lib.member` |
| **G-SESS1** | Session 后端可选 `redis://` | 多进程/多实例 | `web_session_new` url 或 auth 配置 `session=redis://` |
| **G-CACHE1** | Redis pub/sub 可选作 WS 扇出后端 | 多进程 WS | `configure ws_backend=redis` |
| **G-API1** | Bearer API Key 校验原语(hash+pepper+scopes) | anlian `apikeys` | `web_api_key_check` + `# auth` 或独立小类;**业务 scopes 仍在 .mq.md** |
| **G-MAIL0** | (可选后续)SMTP 发送原语 | 邮箱验证码 | 不阻塞首版对等;列入 anlian 二期 |
**明确仍属应用层(不进插件)**:反垃圾策略、草稿定时发布约定、好友关系、专题 `topic_bundles` 静态交互内容(静态挂载 + 前端 Marqdo/既有 JS 资产)。
---
## 8. 暗恋见君验收矩阵(检测「能不能写完」)
外部依赖(允许):**PostgreSQL**、**Redis**;可选对象存储。
| 模块 | Marqdo 后端 | Marqdo 前端 | 插件依赖 | 验收 |
|------|-------------|-------------|----------|------|
| 站点壳 / 首页 | `# page` + db | 局部刷新可选 WASM | listen、static、cache | 首页可开 |
| posts 帖子/评论/板块 | route + form + db | 发帖表单 WASM 可选 | CRUD、CSRF、upload | CRUD+列表详情 |
| news | 同上 | 同上 | 同上 | 列表详情 |
| accounts | auth + session +(二期 mail) | 登录表单 | argon2、session、gate | 注册登录 |
| profiles | db + storage | 头像上传 | storage/upload | 资料页 |
| search | db.search 或 PG 查询 + cache | — | db/cache | 关键词搜索 |
| chat | route_ws + G-WS1/2 + db | WS 客户端脚本 | Redis + WS rooms | 公聊+私聊实时 |
| apikeys | G-API1 + db | 管理页 | — | Bearer 调 API |
| webmaster | sitemap/robots | — | 已有 ABI | `/sitemap.xml` |
| topics | `app.static` → bundles | 既有静态交互 | static | 专题可访问 |
**「写完」定义**:上述模块在 Marqdo 仓库或 `anlian` 旁路目录有可运行 `.mq.md` 站点;gold/手工脚本能走通主路径;不依赖 Django/Channels/Daphne/gunicorn。
---
## 9. 仓库布局与构建
### 9.1 目录(目标)
```text
plugins/web/ # Go module(替换原 Rust crate)
go.mod
go.sum
README.md
abi/
marqdo_abi.h # 从 include/ 拷贝或 cgo 引用
bridge.go # //export marqdo_plugin_* ;register;alloc/free
internal/
page/ compose/ render/ form/
db/ # sqlite + postgres driver
cache/ storage/ upload/
session/ auth/ password/ ratelimit/
httpx/ # listen、router、middleware、admin、proxy、invoke
ws/ # hub、rooms、client connect
assets/ rss/ sitemap/ markdown/
table/ # GFM 表 JSON 形态辅助
cmd/ # 可选:非 c-shared 的本地自测
scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
```
原 Rust 源码:`plugins/web-rust-archive/`(**已移出 Cargo workspace**;参考用,默认不构建)。
### 9.2 产物与解析
| 平台 | 文件名 |
|------|--------|
| Linux | `libweb.so` |
| macOS | `libweb.dylib` |
| Windows | `web.dll` |
解析顺序仍走 `installed_native_path` / `MARQDO_WEB_PLUGIN`;`find_native_plugin` 增加查找:
- `plugins/web/build/libweb.so`(Go 构建输出)
- `target/{debug,release}/libweb.so`(兼容旧路径,可选 copy)
### 9.3 宿主 / CI 变更要点
| 组件 | 变更 |
|------|------|
| 根 `Cargo.toml` workspace | 移除 `plugins/web` / `web-rust-archive` Rust member |
| `tests/gold.rs` | `ensure_web_plugin_built()` → `scripts/build-web-plugin.sh` |
| `marqdo ext add web` | 构建回退:`scripts/build-web-plugin.sh`(Go);Release 仍下发预编译 native zip |
| Release 脚本 | Go:`scripts/build-web-plugin.sh`;其它插件仍 `cargo build -p …` |
| [ext-cli.md](ext-cli.md) / [ext-abi.md](ext-abi.md) | 注明 web 插件实现语言为 Go |
### 9.4 cgo / runtime 注意
- `marqdo_plugin_init` 内 `register_fn` 注册全部符号;保存 host `alloc`/`free`/`host_query`。
- 长时间 `web_listen`:在独立 goroutine 跑 `http.Server`,ABI 调用阻塞至 shutdown 或按现语义阻塞(**对齐现 Rust:listen 阻塞当前插件调用**)。
- 禁止在 FFI 回调里长时间持有阻碍 GC 的错误模式;JSON 尽快拷贝到 Go string。
- Windows 导出需 `.def` 或 `//export` 完整三个符号。
---
## 10. 实现波次(按文档开发顺序)
| 波次 | 内容 | 退出条件 |
|------|------|----------|
| **W-G0** | 文档(本文)+ ADR + 目录骨架 + ABI bridge 能 `plugin.load` + `demo` 注册探测 | ✅ `tests/ext/web-go-abi-smoke.mq.md`;`web_go_ready` + `web_page_new`;`scripts/build-web-plugin.sh` → `libweb.so` |
| **W-G1** | table 辅助 + `web_style` + page new/compose/render(无 listen) | ✅ `web-smoke` / `web-zh-smoke`(含 compose_form / app_new / app_route 袋) |
| **W-G2** | SQLite db CRUD + where + txn + init | ✅ `web-db-w2-smoke` / `web-db-w6-smoke`(txn·migrate·FTS) |
| **W-G3** | form + mount_form + CSRF 基础 | ✅ `web-form-smoke`(validate/submit/render;CSRF 字段已接,listen 侧硬化见 W-G4/G5) |
| **W-G4** | `web_listen` + route + static + part + middleware + JSON API | ✅ offline:`web-route` / `web-static` / `web-middleware` / `web-part`;`web_listen` 已接线(live 随 W-G5+ hardening) |
| **W-G5** | session/auth/password/rate limit/gate/admin | ✅ offline:`web-security` / `web-c0` / `web-c1`;login rate limit 包已就位(HTTP 接线随 listen hardening) |
| **W-G6** | upload/download/gallery/ETag + assets W8 | ✅ `web-upload` / `web-assets` / `web-p3` |
| **W-G7** | SEO RSS sitemap robots redirect error paginate markdown | ✅ `web-content` / `web-w7-*` |
| **W-G8** | WS echo/broadcast + access_log | ✅ `web-ws-broadcast-*` |
| **W-G9** | Postgres + Redis cache + file/S3 storage | ✅ `web-drivers-smoke` |
| **W-G10** | proxy + invoke + nested plugin | ✅ `web-proxy-invoke` / hosting live |
| **W-G11** | 定制 C2–C4 shell/layout/style/nav | ✅ `web-c2`–`c4` |
| **W-G12** | G 增强 WS rooms + Redis session/pubsub + API key 原语 | ✅ 单测 + `web-g12-api-key-smoke` |
| **W-G13** | 默认切换 Go `libweb`;归档 Rust;更新发版与 ext CLI | ✅ 离线+live gold(7 个 `*_live`)对 Go 全绿;`ext add`/`gold`/`release` 走 `scripts/build-web-plugin.sh`;Rust 移出 workspace;gold 强制 `MARQDO_WEB_PLUGIN` 避免 `~/.marqdo` 旧 so |
| **W-G14** | anlian Marqdo 重写主路径(可分仓或 `examples/anlian-mq/`) | ✅ `examples/anlian-mq/`(本地 SQLite + 粉玻璃主题 + 主路由/登录/片段;外接 PG/Redis 仍为增强路径) |
每波次:**先补 Go 实现 → 跑对应 gold → 再进入下一波**。禁止跨波次留下「注册了但返回 stub 错误」的 ABI(除 W-G0 明确的未实现探测)。
---
## 11. 测试策略
| 类型 | 做法 |
|------|------|
| 单元 | Go `go test ./internal/...`(db where、form rules、middleware) |
| 金样例 | 现有 `tests/ext/web-*.mq.md`;构建脚本产出 `libweb.so` 后跑 |
| Live | 现有 `*-live-server.mq.md` + curl |
| 回归门禁 | CI:安装 Go → `scripts/build-web-plugin.sh` → `cargo test` 相关 web 项 |
| anlian | 独立 smoke:登录、发帖、WS 发言、API key |
---
## 12. 风险与缓解
| 风险 | 缓解 |
|------|------|
| cgo/共享库与宿主线程 | 文档化;listen 独立 goroutine;shutdown 明确 |
| JSON ABI 开销 | 热路径减少往返;装配结果缓存;不在此用「换语言」幻想消除 |
| 行为微差异(HTML/Markdown) | 用同一批 gold HTML 片段断言;差异列 changelog |
| 交叉编译 | 优先 `modernc.org/sqlite`;Release 矩阵 Linux/Windows 先 |
| 双实现并存混乱 | W-G13 前用 `MARQDO_WEB_PLUGIN` 显式指向;文档写清默认 |
---
## 13. 文档与索引更新清单
实现推进时同步:
- [x] 本文状态行随波次更新
- [x] [ext-abi.md](ext-abi.md) Demo/Web 节:实现语言 Go
- [x] [ext-cli.md](ext-cli.md):构建回退含 `go build` / `scripts/build-web-plugin.sh`
- [x] [ext-web.md](ext-web.md):链到本文;C5 落实说明
- [ ] [web-asgi-servers-and-marqdo.md](web-asgi-servers-and-marqdo.md):axum → Go `net/http`
- [ ] [doc/README.md](../README.md) 索引行(若尚未链到本文)
- [x] ADR:`doc/adr/0004-web-plugin-go.md`(Accepted)
- [x] `plugins/web/README.md` 开发者构建说明
---
## 14. 决议摘要
1. **全量重写** `plugins/web` 为 Go,**不是**最小闭环。
2. **既有网络拓展能力(§5)重写后必须仍可用**;作者面默认兼容。
3. **PostgreSQL / Redis 外接** 为一等公民;Marqdo 承担应用前后端脚本。
4. **暗恋见君** 为完备性验收,不是缩小插件范围的借口。
5. **多语言 ABI 生态** 以本插件为样板(G7)。
6. 开发严格按 **§10 波次** 推进;本文件为唯一施工图。
+285
View File
@@ -0,0 +1,285 @@
# 网络扩展波次:`ext/web` 鉴权 · WebSocket · 标准库网络原语
| | |
|---|---|
| 状态 | **Draft(本波次锁定设计)** |
| 日期 | 2026-08-24 |
| 相关 | [ext-web.md](ext-web.md) · [ext-abi.md](ext-abi.md) · [stdlib-modules.md](stdlib-modules.md) · [ext-cli.md](ext-cli.md) |
| 目标 | 补齐 `ext/web` 登录鉴权(session/cookie)、WebSocket 端点;为网络扩展所需的**基础设施解析原语**适当补强 `lib/net`(标准库)。 |
---
## 0. 一句话
**领域能力(鉴权、WebSocket 服务器)全部走 ABI 插件 `plugins/web`;纯解析基础设施(cookie / multipart 解析、WS 客户端)按需进入标准库 `lib/net`,因为标准库需要支撑扩展库开发。**
---
## 1. 边界判定:什么进标准库 `lib/net`,什么进扩展
### 1.1 跨语言调研结论
| 语言 | 标准库 | 扩展/生态 | 边界准则 |
|------|--------|----------|---------|
| Python | `urllib`(URL/基础 HTTP)、`http.cookies`(**cookie 解析器在标准库**) | `requests`/`httpx`(session/连接池/便利层) | 标准库 = 基础设施原语(解析器);便利层 = 第三方 |
| Node.js | `http`/`https`/`http2`(低层流式,不解析 body) | express、ws、formidable | 足够 fancy 就不进核心;核心只放几乎人人要用的低层原语;**先 userland 验证再拉进 core** |
| Go | `net/http`(服务器+客户端都在标准库)、`net/http/cookiejar`(**RFC 6265 cookie jar 在标准库**) | `golang.org/x/net`(publicsuffix 等演进性) | HTTP 是「与 stdin 同级」的核心能力;**cookie 解析/管理进标准库**;持久化等演进性能力在外 |
| Rust | 极小 std(无 HTTP) | `http`(词汇)→ `hyper`(传输)→ `reqwest`(便利) | 分层;HTTP 因生态多样不进 std |
**共识**:
1. **cookie 解析/管理(RFC 6265)**在 Python/Go 都是**标准库**(`http.cookies`、`net/http/cookiejar`)。
2. **multipart/form-data 解析**在 Go 是标准库(`net/http`),在 Python 是第三方 `multipart`。
3. **WebSocket** 几乎总在扩展/第三方(Node `ws`、Python `websockets`、Go `gorilla/websocket`),**很少进语言标准库**。
4. **session 是领域级便利**,几乎所有语言都在框架层(express-session、Django session),不在语言标准库。
### 1.2 Marqdo 判定(锁定)
| 能力 | 类型 | 归属 | 理由 |
|------|------|------|------|
| `cookie.parse` / `cookie.parse_response` | 基础设施解析 | **`lib/net`(标准库)** | 对齐 Go/Python 标准库;`ext/web` 鉴权依赖 |
| `multipart.parse` | 基础设施解析 | **`lib/net`(标准库)** | 对齐 Go 标准库;`ext/web` 文件上传依赖 |
| `ws.connect`(客户端) | 基础连接 | **`plugins/web`(ABI)+ `ext/web`** | WS 栈(tokio-tungstenite)已在 web 插件依赖链;核心 `Cargo.toml` 锁定 rustc 1.81 不宜再引入 WS 栈;符合「尽量只 ABI」 |
| `web.session_*`(session 管理) | 领域 | **`plugins/web`(ABI)+ `ext/web`** | session 是框架层便利,不进标准库 |
| `/admin` 登录鉴权 | 领域 | **`plugins/web`(ABI)+ `ext/web`** | 网站领域能力 |
| `web_ws`(服务器端点) | 领域 | **`plugins/web`(ABI)+ `ext/web`** | WebSocket 服务器是网站能力 |
**实现约束(用户要求)**:
- 标准库新增的**解析原语**(cookie/multipart)是纯函数、无网络 I/O,作为 L0.5 宿主原语进 `src/host/`(与 `url_encode` 同模式),由 `lib/net` 薄包装——这符合「标准库需要支持扩展库开发」。
- **涉及网络 I/O 的 WS 能力**(客户端 + 服务器端点)一律进 `plugins/web`(ABI v2),由 `ext/web` / `ext/web/网页.mq.md` 包装。核心运行时(rustc 1.81 锁定)**不再新增** WS 栈依赖。
- **网站领域能力**(session、鉴权中间件)一律进 `plugins/web`(ABI v2),由 `ext/web` 包装。
- **禁止**:为这些能力修改核心语法;禁止在 `src/host/` 塞领域逻辑。
---
## 2. 标准库 `lib/net` 新增(基础设施原语)
### 2.1 `cookie.parse` / `解析Cookie`
- 形参:`text`(`Cookie:` 请求头或 `Set-Cookie:` 响应头)
- 结果:`[{name, value, path, domain, expires, max_age, secure, http_only, same_site}]`
- 行为:RFC 6265 解析;`Set-Cookie` 多 cookie 分条;无属性则字段为空。
**英文(`lib/net.mq.md`):**
```markdown
## cookie_parse
+ `text`
**> host_cookie_parse text=`text`**
```
**中文(`lib/网络.mq.md`):**
```markdown
## 解析Cookie
+ `内容`
**> host_cookie_parse text=`内容`**
```
### 2.2 `multipart.parse` / `解析多部分`
- 形参:`body`(文本)、`boundary`
- 结果:`[{name, filename, content_type, value}]`(`value` 为字段值;文件字段用 `filename` + `content_type` + `value`(base64 或文本))
- 行为:解析 `multipart/form-data` 正文;字段名 → value;文件字段带 filename。
**英文:**
```markdown
## multipart_parse
+ `body`
+ `boundary`
**> host_multipart_parse body=`body` boundary=`boundary`**
```
**中文:**
```markdown
## 解析多部分
+ `正文`
+ `边界`
**> host_multipart_parse body=`正文` boundary=`边界`**
```
### 2.3 WebSocket 客户端 — 见 §3.4(`plugins/web` ABI)
WS 客户端为领域能力,放 `plugins/web`(ABI)而非标准库,理由见 §1.2。`lib/net` 不新增 WS 客户端包装,避免标准库依赖 ext 插件。
---
## 3. `plugins/web`(ABI v2)新增:领域能力
### 3.1 Session 存储(`web_session_*`)
插件进程内 `static` 内存存储(`HashMap<session_id, HashMap<String,Value>>`),与 `web_listen` 同生命周期。
| ABI 名 | 形参 | 结果 |
|--------|------|------|
| `web_session_new` | 可选 `ttl_sec` | `{id}`(新 session id) |
| `web_session_set` | `id`, `key`, `value` | `{ok:true}` |
| `web_session_get` | `id`, `key` | 值或 `{ok:false}` |
| `web_session_del` | `id`, `key` | `{ok:true}` |
| `web_session_destroy` | `id` | `{ok:true}` |
### 3.2 `/admin` 登录鉴权(`web_auth_*`)
- 作者面:`web.auth` 类(`网页.鉴权`),形参 `admin_users`(`|用户名|密码|` 表)、可选 `session_ttl`。
- `listen` 时若配置了 auth:`/admin*` 未登录 → 跳转 `/admin/login`;登录页 `POST` → 校验 `admin_users` 表 → 写 session cookie → 重定向。
- 登出:`/admin/logout` → 销毁 session。
| ABI 名 | 形参 | 结果 |
|--------|------|------|
| `web_auth_login` | `username`, `password`, `users`, `session_ttl` | `{ok:true, session_id}` 或 `{ok:false}` |
| `web_auth_check` | `session_id`, `users` | `{ok:true}` 或 `{ok:false}` |
| `web_auth_logout` | `session_id` | `{ok:true}` |
### 3.3 WebSocket 服务器端点(`web_ws_route`)
- 作者面:`app.route_ws` / `应用.路由实时`,形参 `path`、可选 `echo=True`。
- `listen` 时 `{path}` 升级为 WS:`echo=True` 回发原文;否则接收并丢弃(扩展点)。
| ABI 名 | 形参 | 结果 |
|--------|------|------|
| `web_app_route_ws` | `app`, `path`, `echo` | `{app}`(登记 WS 端点) |
### 3.4 WebSocket 客户端(`web_ws_connect`)
- 作者面:`web.ws` / `网页.实时`,形参 `url`、`message`、可选 `headers`、`timeout_sec`。
- 行为:客户端连接一次 WS,发 `message`,收**全部**服务器回文后关闭。**单请求-响应式**(非长驻),与 Marqdo 同步模型一致。
| ABI 名 | 形参 | 结果 |
|--------|------|------|
| `web_ws_connect` | `url`, `message`, `headers`(map), `timeout_sec` | `{ok:true, messages:[…]}` 或 `{ok:false, error}` |
**英文(`ext/web/web.mq.md`):**
```markdown
# ws
+ `timeout_sec`=30
## connect
+ `url`
+ `message`
+ `headers`=None
```
**中文(`ext/web/网页.mq.md`):**
```markdown
# 实时
+ `超时秒`=30
## 连接
+ `地址`
+ `消息`
+ `headers`=None
```
> `plugins/web` 用 `tokio-tungstenite`(与 axum WS 同栈,版本兼容 rustc 1.81)。
---
## 4. `ext/web` 作者面新增
### 4.1 英文面(`web.mq.md`)
```markdown
# auth
+ `users` # |用户名|密码| 表
+ `session_ttl`=3600
## login
+ `username`
+ `password`
## check
+ `session_id`
## logout
+ `session_id`
```
`# app` 新增 `## route_ws`:
```markdown
## route_ws
+ `path`
+ `echo`=True
```
### 4.2 中文面(`网页.mq.md`)
```markdown
# 鉴权
+ `用户表`
+ `会话时长`=3600
## 登录
+ `用户名`
+ `密码`
## 校验
+ `会话id`
## 登出
+ `会话id`
```
`# 应用` 新增 `## 路由实时`:
```markdown
## 路由实时
+ `路径`
+ `回显`=真
```
### 4.3 用法示例(英文)
```markdown
# main
`admins` =
| 用户名 | 密码 |
|--------|------|
| admin | secret |
*store = > db.open *
*page = > web.page title="Site" *
*app = > web.app page=`page` db=`store` admin=True host=127.0.0.1 port=18081 *
*app = > `app`.route_ws path="/live" echo=True *
*app = > web.auth users=`admins` *
> `app`.listen
*echo = > web.ws.connect url="ws://127.0.0.1:18081/live" message="hi" *
```
---
## 5. form 完善(现有功能验证 + 补测试)
现状已具备(无需改代码,需验证):
- `action=update`:hidden `id` + `db.update`(form.rs `from_schema`/`submit` 已实现)
- 校验失败页级回显:`submit_and_respond` → `render_page_ex`(http.rs 已实现)
本波次为 update 流程和页级回显补 gold 测试,确认端到端可用。
---
## 6. 测试与验收
| 测试 | 内容 |
|------|------|
| `tests/ext/web-net-smoke.mq.md` | session new/set/get/del + auth login/check/logout + `route_ws`/`app.auth` 登记 + ws 连接失败路径(离线) |
| `tests/lib/net-cookie.mq.md` | `cookie_parse` 解析 |
| `tests/lib/net-multipart.mq.md` | `multipart_parse` 解析 |
| `tests/ext/web-admin-smoke.mq.md` | form `action=update` 全流程 + 校验失败 `errors` 回显 |
| 现有 gold | 全量回归(树遍历 + 字节码) |
验收:`cargo test --test gold` 全绿(除网络 live),双后端一致。
### 6.1 字典操作约束(作者面)
Marqdo 原生字典操作:GFM 横表**构造**、脚注取元 `变量[^键]` **读取**。`ext/web` 作者面**不使用** `json.get` / `json.set` 做字典读取/改写——所有字段读取一律 `self[^键]`(或实例变量 `[^键]`),避免"用 json 标准库做字典操作"的反模式。`json.parse` / `json.stringify` 仅用于文本 ↔ 结构化数据的序列化转换(如 HTTP body 解析),不用于本地字典读写。
### 6.2 相对路径按入口脚本解析(host_query `entry_dir`)
`static_dir`(如 `public`)与相对 db 路径(如 `sqlite:data/site.db`)此前按**进程 cwd** 解析——从仓库根目录跑 `examples/*/index.mq.md` 时,`/static` 404、db 会建到根目录,这是错误行为。
本波次修复:宿主新增 `host_query("entry_dir")`(返回入口 `.mq.md` 所在目录的绝对路径,回退 cwd),`plugins/web` 的 `web_listen` 将相对 `static_dir`、`db_url_of` 将相对 db 路径统一 `entry_dir().join(...)` 到绝对路径。于是无论从仓库根目录还是示例目录运行,静态资源与数据库都落在**脚本目录**下。绝对路径不受影响;`host_query` 不可用时回退旧 cwd 行为。
---
## 7. 非本波次
- Postgres / Redis / S3 驱动(roadmap W4,另行)
- WS 广播房间、多客户端(先 echo 单连接)
- session 持久化到 SQLite / 文件(先内存)
- 复杂权限 / RBAC
+600
View File
@@ -0,0 +1,600 @@
# 官方扩展:`ext/web` 动态网站
| | |
|---|---|
| 状态 | **Accepted · W0–W7 + P3 + W8(站点图标/Head/图片装配)完结**(SQLite/Postgres 作者面:页面装配 / db CRUD+`where` / form / 嵌入主区 / `app.route` / 路由 `/_part` / admin UI / RBAC / 上传相册 / SEO·RSS·sitemap / **favicon·头资源·图片装配**;Postgres 等见 §9) |
| 日期 | 2026-08-11(W8:2026-08-29) |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [module-namespace.md](module-namespace.md) · [objects.md](objects.md) · [ext-abi.md](ext-abi.md) · [ext-cli.md](ext-cli.md) · [stdlib-i18n.md](stdlib-i18n.md) · [web-assets-and-images.md](web-assets-and-images.md) |
| 安装(目标) | `marqdo ext add web`(中英:`web` / `网页`) |
| 本文目的 | 锁定**作者面**与**类 API**;指导实现 |
---
## 0. 一句话
`ext/web` 用 **GFM 表格 + Marqdo 类方法** 描述动态网站:表仍是字典/列表嵌套;类方法把表装配成可渲染页面。
**不改 Marqdo 核心语法**;扩展库存在的理由,正是让「文档即代码」在网站场景下成立。
---
## 1. 为何要做网络扩展库
### 1.1 问题
若没有专用扩展,作者只能:
- 手写 JSON 袋、`json.set` 拼装组件/样式;或
- 要求改语言(让表格单元格求值、点号取值等)。
二者都破坏 Marqdo 的「代码即文档」。
### 1.2 答案
在 **`ext/web/web.mq.md`(英文)** 与 **`ext/web/网页.mq.md`(中文)** 中各提供一套 **`#` 类**:
- 作者只写**表** + **少量实例方法调用**;
- 表单元格保持**字面量**;
- **寻址字符串**由类方法解析;
- **导入英文文件 → 只用英文 API;导入中文文件 → 只用中文 API**(见 [stdlib-i18n.md](stdlib-i18n.md))。
### 1.3 硬约束(评审锁定)
| # | 约束 |
|---|------|
| C1 | **禁止**为 web 改动 Marqdo 核心:单元格求值、import、点号值读取等保持不变 |
| C2 | 作者面**禁止** `json.parse` / `json.set` 袋胶水、手写 part JSON、手写 assemble 袋 |
| C3 | 能力以 **`#` 类 + `##` 方法** 暴露;**英文库文件只用英文名,中文库文件只用中文名**(见 [stdlib-i18n.md](stdlib-i18n.md));同一 `.mq.md` 内禁止中英 API 混排 |
| C4 | 首页在 **`index.mq.md`**:页面表在此;可复用片段进 `components/`;主体可就地写 |
| C5 | **旧有网络扩展库全部废弃**:`plugins/web`、`ext/web/**`(含现网示例/gold 中依赖旧 API 者)评审通过后**删除或清空后重写**;禁止在旧代码上打补丁演进。**落实**:原生层 Go 全量重写见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md);作者面 ABI 名保持兼容 |
| C6 | `# db` / `# 数据库` 必须提供完整**增删改查**;列表查询英文方法名为 **`select`**(中文 **`查询`**);后台 `/admin` 与表单提交走同一套写库 API |
| C7 | 用户输入经 `# form` / `# 表单`:字段表 + 校验表;**服务端校验必须在写库前执行**(见 §5.5) |
---
## 2. 作者心智与目录
```text
myapp/
index.mq.md # 入口 + 首页:页面表 +(可选)就地主体表 + 类方法 + listen
pages/ # 子页:同形的页面表(导出布局表或由入口再装配)
components/ # 可复用组件:导出与路径同名的 ##,体为 |属性|值|样式|
styles/ # 样式模块:每个样式一个 ##,体为 |属性|值|
db/ # 库:schema 表 +(可选)open/种子
data/ # sqlite 等运行时数据(gitignore)
```
| 表种 | 列 | 一句话 |
|------|-----|--------|
| **页面表** | `组件` \| `样式` | 本页用哪些组件、各套哪套样式 |
| **组件 / 主体表** | `属性` \| `值` \| `样式` | 前端属性 ↔ 取值(库字段或字面量)↔ 样式名 |
| **样式表** | `属性` \| `值` | CSS 声明 |
| **库结构表** | `字段` \| `类型` \| `可空` | schema |
---
## 3. 表内寻址约定(单元格仍是字符串)
单元格**不求值**。下列写法是 **web 扩展约定的路径文本**,由 `# 页面` / `# 样式` / `# 数据库` 的方法解析。
### 3.1 反引号与裸名
| 含义 | 写法 | 例 |
|------|------|-----|
| 要「去导入树 / 定义里解析」的名字 | 反引号 `` `名` `` | `` `nav` ``、`` `title` ``、`` `topnav` ``、`` `articles` ``(表名) |
| 字面量(文案、URL、CSS 属性名/值、SQL 类型、**列名**) | **裸**或 `"…"` | `首页`、`/about`、`font-size`、`integer`、`title`(作为列名时) |
### 3.2 路径形态(锁定)
| 场景 | 形态 | 例 | 方法内语义 |
|------|------|-----|------------|
| 引用导入模块的导出 | `模块.`导出`` | `nav.`nav``、`shell.`topnav`` | 在**站点入口模块**的 import 树上调用 `模块.导出`(零参 `##`),取回表 Value |
| 引用库字段 | `模块.`表`.列` | `articles.`articles`.title` | 模块名 = 命名空间(对应导入的 db 文件);`` `表` `` = 库表名;**列名裸写**(列不是变量)→ 运行时绑定 `表.列` |
| 前端属性名 | `` `title` `` | 组件表「属性」列 | 解析为字段名 `title` |
| 样式引用 | 同「模块.导出」或纯样式名 | `shell.`card-title`` | 取回 `|属性|值|` 表并编译为 CSS 类 |
**刻意不做的事:**
- 不把「组件变量名」魔法等同于「库表名」;
- 不要求作者写 `json.set` 才能把 `nav` 放进袋;
- 不把 `articles.`articles`.title` 做成语言级表达式。
### 3.3 与模块命名空间的关系
- 库名来自 frontmatter 导入(茎名或 `as`),**裸名**,见 [module-namespace.md](module-namespace.md)。
- `nav.`nav`` 中:前段 `nav` = 导入库名;`` `nav` `` = 该库上的 `## nav` 导出。
- 组件/样式文件应导出 **与路径第二段同名的 `##`**,直接返回表(不要 `## bag` / `## bind` 袋)。
---
## 4. 规范示例:`index.mq.md`(作者面唯一样板)
**语言与导入绑定(锁定,纠正手写混用):**
| 导入 | 库名(默认茎) | 类 / 方法 / 形参 |
|------|----------------|------------------|
| `import web:ext/web/web.mq.md` | `web` | **仅英文**:`page` · `compose_components` · `db` · `app` · `components=` … |
| `导入 网页:ext/web/网页.mq.md` | `网页` | **仅中文**:`页面` · `组件装配` · `数据库` · `应用` · `组件=` … |
禁止:`import web:ext/web/web.mq.md` 后写 `web.页面` / `` `页`.组件装配 ``(英文库混中文成员)。
禁止:在 `web.mq.md` 文件内定义中文 `## 组件装配` 别名。中英对等靠**两个文件**,不靠同一文件双份导出。
### 4.1 英文面(导入 `web.mq.md`)
```markdown
---
title: web-site
description: Home = page table; main may be inline; class methods assemble.
import web:ext/web/web.mq.md
import shell:styles/shell.mq.md
import nav:components/nav.mq.md
import side:components/side.mq.md
import foot:components/foot.mq.md
import articles:db/articles.mq.md
import db:db/index.mq.md
---
# main
`home` =
| 组件 | 样式 |
|------|------|
| nav.`nav` | shell.`topnav` |
| side.`side` | shell.`side-panel` |
| foot.`foot` | |
Main content is not a reusable component, so it is authored here.
`index` =
| 属性 | 值 | 样式 |
|------|-----|------|
| `title` | articles.`articles`.title | shell.`card-title` |
| `body` | articles.`articles`.body | shell.`card-body` |
*`store` = > db.open *
*`page` = > web.page title="Marqdo Web Site" intro="<h1>Web Site</h1>" *
*`page` = > `page`.compose_components components=`home` *
*`page` = > `page`.compose_main main=`index` *
*`app` = > web.app page=`page` db=`store` admin=True host=127.0.0.1 port=18081 *
> `app`.listen
```
说明:表头列名可用中文(`组件`/`样式`/`属性`/`值`)——那是**表约定词汇**,不是库成员名;库成员必须与导入语言一致。
### 4.2 中文面(导入 `网页.mq.md`)
```markdown
---
title: 站点
导入 网页:ext/web/网页.mq.md
import shell:styles/shell.mq.md
import nav:components/nav.mq.md
import side:components/side.mq.md
import foot:components/foot.mq.md
import articles:db/articles.mq.md
import db:db/index.mq.md
---
# main
`首页` =
| 组件 | 样式 |
|------|------|
| nav.`nav` | shell.`topnav` |
| side.`side` | shell.`side-panel` |
| foot.`foot` | |
主体不是可复用组件,因此就地撰写。
`index` =
| 属性 | 值 | 样式 |
|------|-----|------|
| `title` | articles.`articles`.title | shell.`card-title` |
| `body` | articles.`articles`.body | shell.`card-body` |
*`库` = > db.open *
*`页` = > 网页.页面 标题="站点" 引言="<h1>站点</h1>" *
*`页` = > `页`.组件装配 组件=`首页` *
*`页` = > `页`.主体装配 主体=`index` *
*`应用` = > 网页.应用 页面=`页` 数据库=`库` 后台=True 主机=127.0.0.1 端口=18081 *
> `应用`.监听
```
**允许出现在 index 的非表内容:** frontmatter 导入、开库一行、构造页面/应用并装配、`listen` / `监听`。
**不允许:** `json.*` 袋、手写 `/_part` 注册、中英 API 混用。
---
## 5. 类 API(分文件 · 分语言)
依据 [stdlib-i18n.md](stdlib-i18n.md):**导入哪个文件,就用哪套名字。**
`ext/web/web.mq.md` = 全英文;`ext/web/网页.mq.md` = 全中文。中文实现可委托插件同一套原语,或薄封装英文库,但**对外导出的 `#` / `##` / 形参名必须是中文**。
### 5.1 页面 · `page` / `页面`
**英文(`web.mq.md`):**
```markdown
# page
+ `title`=…
+ `intro`=…
## compose_components
+ `components` # page table |组件|样式|
## compose_main
+ `main` # bind table |属性|值|样式|
```
**中文(`网页.mq.md`):**
```markdown
# 页面
+ `标题`=…
+ `引言`=…
## 组件装配
+ `组件`
## 主体装配
+ `主体`
```
| 行为 | 说明 |
|------|------|
| compose_components / 组件装配 | 解析组件·样式路径 → 填 nav/sidebar/footer → CSS → 登记 part |
| compose_main / 主体装配 | 解析库字段与样式路径 → 填 main → 登记 part(如 id=`index`) |
**槽位推断:** 由组件导出名决定(`nav`→顶栏,`side`→侧栏,`foot`→底栏;其余→main)。
### 5.2 样式 · `style` / `样式`
**英文:** `# style` · `## process` · `+ style=` / `name=` / `path=`
**中文:** `# 样式` · `## 样式处理` · `+ 样式=` / `名=` / `路径=`
页面装配可内部调用;作者一般不必在 index 显式调。
### 5.3 数据库 · `db` / `数据库`
完整**增删改查**;页面绑定、种子、`/admin`、表单提交共用。
**英文(`web.mq.md`):**
```markdown
# db
+ `url`=…
## init
+ `name`
+ `fields` # or table= schema
## insert
+ `table`
+ `rows`
## select
+ `table`
+ `where`=None # optional simple filters
+ `limit`=200
## get
+ `table`
+ `id`
## update
+ `table`
+ `id`
+ `row`
## delete
+ `table`
+ `id`
## exec
+ `sql`
+ `args`=None # escape hatch: raw SQL (not everyday authoring)
```
**中文(`网页.mq.md`):**
```markdown
# 数据库
+ `地址`=…
## 初始化
+ `数据库表` # 或 名= + 字段=
## 插入
+ `表`
+ `行` # 或 多行=
## 查询
+ `表`
+ `条件`=None
+ `上限`=200
## 获取
+ `表`
+ `id`
## 更新
+ `表`
+ `id`
+ `行`
## 删除
+ `表`
+ `id`
## 执行
+ `sql`
+ `参数`=None
```
| 中文 | 英文 | 职责 |
|------|------|------|
| 初始化 | `init` | 建表;登记表名 |
| 插入 | `insert` | 增 |
| 查询 | `select` | 查列表(可带简单条件 / limit) |
| 获取 | `get` | 按主键一行 |
| 更新 | `update` | 改 |
| 删除 | `delete` | 删 |
| 执行 | `exec` | 可选原始 SQL(进阶) |
`table=` / `表=` 接受表名或句柄;行数据优先 GFM 表。
**命名锁定:** 列表查询用 `select` / `查询`,**不用** `all`;原始 SQL 用 `exec` / `执行`,避免与 `select` 混淆。
### 5.4 应用 · `app` / `应用`
**英文:** `# app` · `## route` · `## static` · `## listen` · 形参 `page` `db` `admin` `host` `port`
**中文:** `# 应用` · `## 路由` · `## 静态` · `## 监听` · 形参 `页面` `数据库` `后台` `主机` `端口`
`listen` / `监听`:加载插件、注入 `db_url`、按页面 part 提供 `/_part/{id}`(首页)与 `{path}/_part/{id}`(`app.route` 页)、可选 `static` 目录挂载、启动 HTTP。作者不必手写 part 注册。
`static` / `静态`:`dir=`(或 `目录=`)+ 可选 `mount=`(默认 `/static`);`listen` 时用 `tower-http` 提供只读文件服务。
### 5.5 表单 · `form` / `表单`(规划锁定)
用户输入也走「表 + 类方法」,与页面/库同一心智;**提交最终调用 `# db` 的 insert/update**,不另开旁路。
**英文(`web.mq.md`):**
```markdown
# form
+ `table`=None # bound db table name (optional until submit)
+ `action`=insert # insert | update
+ `id`=None # required when action=update
## fields
+ `fields` # |字段|标签|类型|必填|默认|…
## validate
+ `rules`=None # |字段|规则|消息|… (optional extra rules)
+ `data` # submitted row / map
## render
# → HTML form (or form descriptor for page slot)
## submit
+ `data`
+ `db` # db handle
```
**中文(`网页.mq.md`):**
```markdown
# 表单
+ `表`=None
+ `动作`=插入 # 插入 | 更新
+ `id`=None
## 字段
+ `字段`
## 校验
+ `规则`=None
+ `数据`
## 渲染
## 提交
+ `数据`
+ `数据库`
```
#### 5.5.1 字段表(作者面)
```markdown
`文章表单` =
| 字段 | 标签 | 类型 | 必填 | 默认 |
|------|------|------|------|------|
| title | 标题 | text | true | |
| body | 正文 | textarea | false | |
```
| 列 | 含义 |
|----|------|
| `字段` | 对应库列名(裸名或 `` `列` ``,与 schema 对齐) |
| `标签` | 展示文案(字面量) |
| `类型` | 控件/值类型:`text` `textarea` `number` `email` `url` `checkbox` `select` … |
| `必填` | 是否必填 |
| `默认` | 可选默认值 |
#### 5.5.2 校验表(作者面)
```markdown
`文章校验` =
| 字段 | 规则 | 消息 |
|------|------|------|
| title | required | 标题不能为空 |
| title | max:120 | 标题过长 |
| body | max:8000 | 正文过长 |
```
| 规则(初版) | 含义 |
|--------------|------|
| `required` | 非空 |
| `min:N` / `max:N` | 字符串长度或数值范围 |
| `email` / `url` | 格式 |
| `match:字段` | 与另一字段相等(如确认密码) |
| `in:a,b,c` | 枚举 |
schema 上的「可空 / 类型」在 **submit 时自动并入校验**(不必重复写 `required`,但校验表可覆盖消息)。
#### 5.5.3 行为流程
```text
render → 按字段表出 HTML(或嵌入 page 主区)
用户填写 → POST /_form/{id} 或同页提交
validate → 合并 schema + 校验表;失败则带回字段级错误、不写库
submit → action=insert → db.insert;action=update → db.update
→ 成功后刷新槽位或跳转(由 form 选项约定)
```
| 层 | 校验 |
|----|------|
| **服务端(必须)** | `validate` 在写库前执行;唯一可信边界 |
| **浏览器(可选增强)** | 同源规则可生成 `required`/`maxlength` 等 HTML 属性;**不能**替代服务端 |
`/admin` 的新建/编辑页 = 内置 form:字段来自 schema,校验来自类型/可空;与站点自定义 form **同一套** `validate` + `db.insert`/`update`。
#### 5.5.4 与页面的关系
- 表单可以是独立路由页,或页面表里的一个「组件」导出(仍用 `|属性|值|样式|` 描述展示,提交走 form 类)。
- **`page.compose_form id=… form=…`**:把 form 嵌入该页主区;`listen` 从首页与路由页收集表单并挂载 `/_form/{id}`(`app.mount_form` 仍可用)。校验失败时若表单有所属页,则带回该页壳重渲染。
### 5.6 文件职责
| 文件 | 内容 |
|------|------|
| `ext/web/web.mq.md` | 英文 `# page` `# style` `# db` `# form` `# app` |
| `ext/web/网页.mq.md` | 中文 `# 页面` `# 样式` `# 数据库` `# 表单` `# 应用`(可包装英文实现,**不得**把中文名写进 `web.mq.md`) |
---
## 6. 模块导出形状(配合寻址)
### 6.1 组件 `components/nav.mq.md`
```markdown
## nav
`nav` =
| 属性 | 值 | 样式 |
|------|-----|------|
| `title` | `nav`.`title` | |
| `href` | `nav`.`href` | |
**`nav`**
```
说明:组件**内部**绑定仍可用 `` `表`.`列` ``(表名+列名皆引用)。与 index 主体里「模块命名空间 + 裸列名」的 `articles.`articles`.title` 分工:
- **跨文件、带导入命名空间** → `模块.`表`.列`;
- **组件文件内、表已明确** → `` `表`.`列` `` 即可。
(若评审希望全站统一为一种形态,可在评审意见中二选一;默认允许上述两种。)
### 6.2 样式 `styles/shell.mq.md`
每个样式一个 `##`,**禁止** `## bag` + `json.set`:
```markdown
## topnav
… |属性|值| …
**`topnav`**
## card-title
…
```
### 6.3 库 `db/articles.mq.md` / `db/index.mq.md`
- `articles`:`## schema`(或同名导出)返回结构表;
- `index`:`## open` → 确保插件、建库、init、幂等种子,返回 `# 数据库` 句柄。
---
## 7. 运行时职责划分
```text
作者 .mq.md 表(字面量单元格)
│
▼
ext/web 类方法(Marqdo)
│ 解析路径;需要时经 ABI host_query
│ 调用入口模块 import 树上的 lib.member
▼
plugins/web(HTTP / SQL / HTML 壳)
│
▼
浏览器:四区布局 + /_part 局部刷新 + /admin(可选)
```
| 层 | 做 | 不做 |
|----|----|------|
| Marqdo 核心 | 表→Value、类/方法、import | 不识别 web 路径语法 |
| `ext/web/*.mq.md` | 作者 API、中英面、委托插件 | 不直接 `host_*` |
| `plugins/web` | **Go** `libweb`(HTTP / SQL / HTML 壳;见 [ext-web-go-rewrite.md](ext-web-go-rewrite.md)) | 不要求作者写袋 |
**实现要点(评审通过后再做):**
1. ABI `host_query("call_lib_path")`:在**站点入口模块**上执行 `lib.member`;
2. 插件函数由类方法调用(如 compose_components / compose_main);
3. `listen` 合并页面内 part,注入 `db_url`。
---
## 8. 全部废弃 · 从头开发(锁定)
**旧有网络扩展库内容一律作废**,包括但不限于:
| 范围 | 处理 |
|------|------|
| [`plugins/web/`](../../plugins/web/) | 评审通过后**删除或清空**,按本文重写 cdylib |
| [`ext/web/`](../../ext/web/)(`web.mq.md` / `网页.mq.md` / templates) | 同上,**不**在旧 L1 上打补丁 |
| 依赖旧 API 的示例(如当前 `examples/web-site`、`web-demo`、`man-write-site` 可跑胶水版) | 按 §4 规范重写或暂时移除 |
| 依赖旧 API 的 gold / 单测 | 删除后按新 API 重写 |
| 本文之前的袋式 / assemble / wire / `## bag` 等作者面 | 永久移出正典 |
**禁止**:在遗留代码上「修到能跑」再文档化。
**允许**:实现时参考旧代码中的 HTTP/SQLite 技术经验,但**新树另起**,不以 ABI 表面或作者面兼容为目标。
历史摸索中明确不再回归的作者面模式:
- `json.parse` / `json.set` 拼 components/styles 袋;
- 手写 `web.assemble` + 袋参数;
- 手写 part JSON + `` `app`.part ``;
- `|前端变量|后端数据库|` 填路由;
- 「变量名即表名」魔法默认表;
- 样式 `## bag`;掏空 index 只留 `wire.boot`。
---
## 9. 非本波次(可记入路线图)
- Postgres / Redis / S3 驱动细节(SQLite 已落地);
- 复杂权限与多租户;
- 子页路由糖的更多约定(`# 应用.route` 已够用)。
---
## 10. 评审清单
请确认或批注:
1. **§3 路径**:`模块.`导出`` 与 `模块.`表`.列`(列裸名)是否定为唯一正典?组件内 `` `表`.`列` `` 是否保留?
2. **§4 index**:开库是否允许单独一行 `` db.open ``,还是必须进一步藏进 `web.应用`?
3. **§5 分文件**:英文 `web.mq.md` / 中文 `网页.mq.md` 是否严格分语言、禁止混排?
4. **§5.3**:列表查询用 `select` / `查询`、原始 SQL 用 `exec` / `执行` 是否认可?
5. **§5.5 表单/校验**:字段表、校验表、服务端必校、admin 共用是否认可?
6. **§5 槽位**:仅由组件导出名推断,是否足够?
7. **§8 废弃**:是否确认**全部推倒重来**、不兼容旧实现?
评审通过后:冻结本文为 Accepted → **清空旧 web 扩展代码** → 按本文从零实现(骨架 → db CRUD/`select` → form/validate → 页面装配 → app listen → 规范示例 → gold)。
+3 -3
View File
@@ -4,9 +4,9 @@
|---|---|
| 状态 | 草案(已采纳方向;修正「配置文件」误解) |
| 日期 | 2026-08-04 |
| 相关 | [OKF 调研](../research/okf-and-marqdo.md) |
| 相关 | [OKF 调研](../research/okf-and-marqdo.md) · **实现规范 [okf.md](okf.md)** |
| 取代 | 此前「YAML = 人手写的编译器配置 / frontmatter 契约」的表述 |
| 说明 | 原则仍有效;**类型表、任务知识包、路线图以 [okf.md](okf.md) 为准** |
---
## 决策
@@ -28,7 +28,7 @@ Marqdo 项目中的 **YAML(及由其组成的 OKF 风格知识包)是工具
**唯一手写真相**仍是 `.mq.md` 源文件正文。YAML 清单是派生工件;过时则重新生成,禁止当成第二套权威配置去手改(除非工具链明确支持的「生成后微调」流程,且须可复现)。
**与源 frontmatter 的分工**(见 [markdown-mapping.md](markdown-mapping.md)):源文件 `---` 块可含 `title` 等元信息,以及人手声明的跨文件导入行 `> other.mq.md`。那是**源上的导入声明**,不是工程依赖锁。工具仍应据此(及正文 `>` 调用)**生成** OKF 风格依赖/模块目录;不要把生成目录手改成权威。
**与源 frontmatter 的分工**(见 [markdown-mapping.md](markdown-mapping.md)):源文件 `---` 块可含 `title` 等元信息,以及人手声明的跨文件导入行 `import other:other.mq.md`。那是**源上的导入声明**,不是工程依赖锁。工具仍应据此(及正文 `>` 调用)**生成** OKF 风格依赖/模块目录;不要把生成目录手改成权威。
---
+137
View File
@@ -0,0 +1,137 @@
# 内置关键字 / 函数:中英双名(草案)
| | |
|---|---|
| 状态 | **已定(已实现)** |
| 日期 | 2026-08-05 |
| 原则 | **无需导入**;中英为**同一语义的别名**,不是语言模式开关 |
| 相关 | [keywords.md](keywords.md) · [stdlib-i18n.md](stdlib-i18n.md) · [call-arguments.md](call-arguments.md) |
---
## 1. 动机
Marqdo 要中英文都能自然书写。标准库已约定「**库文件名区分语言**」(见 [stdlib-i18n.md](stdlib-i18n.md));对**不必导入**的一层——字面量关键字与极少内置函数——也要对等提供中文名。
正因为每增加一个内置名,就要同时维护中英(及日后更多语言)别名,所以:
> **关键字 / 内置必须少而精**——体积在「名字 × 语言」上放大,而不是在功能清单上堆满。
更多能力进可导入的 `lib/`,用中英**不同库文件、不同函数名**扩展,不膨胀解释器内核。
---
## 2. 分层(与标准库对齐)
| 层 | 是否导入 | 中英怎么区分 |
|----|----------|--------------|
| **L0 内核** | 否 | **同一文件内双名**:`print` ≡ `打印`;`True` ≡ `真` |
| **L1 标准库** | 是(`import …:lib/…`) | **不同文件**:`text.mq.md` vs `文本.mq.md`(见 i18n 草案) |
L0 **不做** `lang:`、不做「当前语言模式」;写英文名就用英文,写中文名就用中文,可在同一程序里混用。
---
## 3. 范围:哪些要双名
### 3.1 字面量 / 逻辑关键字(词法保留)
控制流仍靠 Markdown(`#` `1.` `-` `*` `**`),**不**为 `if`/`while`/`def` 做中英关键字。形参用 `+`。
| 英文 | 中文(提案) | 备注 |
|------|--------------|------|
| `True` | `真` | 布尔真 |
| `False` | `假` | 布尔假 |
| `None` | `空` | 空值 |
| `and` | `且` | 逻辑与 |
| `or` | `或` | 逻辑或 |
| `not` | `非` | 逻辑非 |
中英文名均**不可作变量名**(同一保留集)。
### 3.2 内置函数(可调用、无需导入)
**仅**下列核心五项做中英双名(与「少而精」一致):
| 英文 | 中文(提案) | 作用 |
|------|--------------|------|
| `print` | `打印` | 写 stdout |
| `input` | `输入` | 读一行 |
| `len` | `长度` | 文本/表长度 |
| `str` | `文本` | 转为显示文本 |
| `int` | `整数` | 转为整数 |
形参名也提供中英别名(便于纯中文调用):
| 英文形参 | 中文形参 | 用于 |
|----------|----------|------|
| `text` | `内容` | `print` / `打印` |
| `prompt` | `提示` | `input` / `输入` |
| `value` | `值` | `len`/`str`/`int` 及对应中文名 |
示例(等价):
```markdown
> print text=Hello
> 打印 内容=你好
*`n` = > len `s`*
*`n` = > 长度 值=`s`*
```
### 3.3 明确不进 L0 双名表
下列若已在解释器中实现,视为**宿主原语 / 过渡 API**,**不**再批中文内核别名;应迁入或仅通过标准库暴露(中英分文件):
| 英文名 | 去向 |
|--------|------|
| `type` | L1 或维持实现细节,不进「关键字最少集」宣传 |
| `trim` `split` `join` | L1:`lib/text.mq.md` / `lib/文本.mq.md` |
| `at` | L1:`lib/table.mq.md` / `lib/表.mq.md` |
这样 L0 公开面 ≈ **6 个关键字词 ×2 + 5 个函数 ×2**,而不是「每个工具函数都 ×2」。
---
## 4. 语义规则
1. **别名等价**:中英文名绑定同一实现;诊断文案可用英文稳定串(金样例已有),用户文档中英均可举例。
2. **可混用**:同一文件可同时出现 `print` 与 `打印`、`True` 与 `真`。
3. **遮蔽**:用户 `# 打印` 与 `# print` 均会遮蔽对应内置名(实现阶段应警告)。
4. **大小写**:英文关键字保持 Python 风格(`True`/`False`/`None`);中文无名感大小写问题。
5. **扩语言**:日后日文等 → 再为 L0 增加第三个别名列;仍无「名字表」而非语言开关。标准库继续用**文件名**区分(见 i18n 草案)。
---
## 5. 与旧决议的关系
- 旧文「中文 `print` 废弃、统一为 `print`」:**废止**;改为正式双名 `print` / `打印`。
- [keywords.md](keywords.md) 原则条「英文标识」改为「**内核双名;标准库分文件**」——实现阶段改正文。
- 不引入中文控制流关键字(`如果`/`循环` 等);分支用 `1.` …,循环用 `-`。
---
## 6. 文档与金样例义务(实现时)
| 项 | 要求 |
|----|------|
| `keywords.md` | L0 表改为中英并列;砍掉对 `trim`/`split`/… 的「内核关键字」宣传 |
| `public/` | 英 / 中文件同目录并列(拉丁名 vs 中文名) |
| `tests/` | 中文关键字 / `打印`·`长度` 等金样例;与英文样例对等 |
| 诊断 | 位置格式不变;message 可暂维持英文,或中英均可接受(另开小节) |
---
## 7. 实现备忘(暂不开发)
1. 词法 / 解析:字面量与 `and`/`or`/`not` 识别中文别名。
2. 调用解析:内置表按别名归一到同一 `BuiltinId`。
3. 形参绑定:`text`≡`内容`,`prompt`≡`提示`,`value`≡`值`。
4. **不要**加 `lang:` 或全局「中文模式」。
5. 与 [stdlib-i18n.md](stdlib-i18n.md) 一并落地时:先收束 L0 公开面,再铺 `lib/text` ↔ `lib/文本`。
---
## 8. 一句话
**内核:中英别名、无需导入、必须少;标准库:中英分文件、靠导入路径选择——这样 Marqdo 才能中英文通用而不把解释器撑爆。**
+51 -38
View File
@@ -2,51 +2,65 @@
| | |
|---|---|
| 状态 | 已定(前期够用) |
| 日期 | 2026-08-04 |
| 原则 | **英文**;参考 [Python](https://realpython.com/python-keywords/) 但远更少;控制流仍靠 Markdown 标记,不引入 `if`/`while`/`def` |
| 相关 | [markdown-mapping.md](markdown-mapping.md) |
| 状态 | 已定(中英双名) |
| 日期 | 2026-08-05 |
| 原则 | **少而精**;控制流靠 Markdown;内核中英**别名等价**(见 [keywords-i18n.md](keywords-i18n.md)) |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [keywords-i18n.md](keywords-i18n.md) · [stdlib-i18n.md](stdlib-i18n.md) |
---
## 1. 设计原则
1. **标记承担架构**:函数=`#`,分支=`+`,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。
2. **英文标识**:内置与字面量用英文,便于工具高亮与国际协作。
3. **学 Python 的边界**:Python 3 里 [`print` / `input` 是内置函数,不是关键字](https://realpython.com/python-keywords/);布尔与空值是字面量关键字。Marqdo 同样区分 **关键字** vs **内置函数名**。
4. **宁少勿多**:前期只列执行金样例所需;要加再进 ADR。
1. **标记承担架构**:函数=`#`,**形参=`+`**,**分支=`1.`…**,循环=`-`,返回=`**…**`,语句=`*…*`。因此 **不**把 `def`/`if`/`else`/`while`/`for`/`return` 做成关键字。
2. **内核双名**:字面量 / 逻辑词 / 五个核心内置函数均有中英别名,**无需导入**,可混用。
3. **学 Python 的边界**:区分 **关键字** vs **内置函数名**。
4. **宁少勿多**:扩展能力进可导入标准库(中英分文件,见 [stdlib-i18n.md](stdlib-i18n.md))。
---
## 2. 关键字(词法保留,不可作变量名)
| 关键字 | 含义 | 备注 |
|--------|------|------|
| `True` | 布尔真 | 对齐 Python 大小写 |
| `False` | 布尔假 | |
| `None` | 空值 | |
| `and` | 逻辑与 | 表达式内 |
| `or` | 逻辑或 | |
| `not` | 逻辑非 | |
| 英文 | 中文 | 含义 |
|------|------|------|
| `True` | `真` | 布尔真 |
| `False` | `假` | 布尔假 |
| `None` | `空` | 空值 |
| `and` | `且` | 逻辑与 |
| `or` | `或` | 逻辑或 |
| `not` | `非` | 逻辑非 |
**本期不引入:** `if` `else` `elif` `while` `for` `def` `class` `return` `import` `pass` `break` `continue` `in` `is` `lambda` …
(`else` 分支臂仍用臂头单独的 `*` 标记,不是单词 `else`。)
**不引入:** `if` `else` `while` `for` `def` `return` …(分支臂 `*` 不是单词 `else`。)
---
## 3. 内置函数(可调用名,建议勿遮蔽)
## 3. 内置函数(可调用,无需导入)
| 名称 | 作用 | 调用示例 |
|------|------|----------|
| `print` | 写到 stdout(副作用) | `> print text=Hello` 或 `> print Hello`(位置实参,见 [call-arguments.md](call-arguments.md)) |
| `input` | 从 stdin 读一行(返回文本) | `*`name` = > input prompt=Name: *` |
| 英文 | 中文 | 作用 |
|------|------|------|
| `print` | `打印` | 写 stdout |
| `input` | `输入` | 读一行;capture / view 用 frontmatter `stdin:` / `输入:`、表单或 `--stdin-file` 预置 |
| `len` | `长度` | 文本/表长度 |
| `str` | `文本` | 转为显示文本 |
| `int` | `整数` | 转为整数 |
参数约定(v0):
**文本**:裸 token 按字面量;需 `\n` 等转义时用 `"..."`(见 [markdown-mapping.md](markdown-mapping.md) §7)。
- `print`:具名实参 `text`(必填);日后可扩展 `end` 等。
- `input`:可选 `prompt`;返回用户输入字符串(不含换行)。
形参别名:
旧文档中的中文 `print` **废弃**,统一为 `print`。
| 英文 | 中文 | 用于 |
|------|------|------|
| `text` | `内容` | `print` / `打印` |
| `prompt` | `提示` | `input` / `输入` |
| `value` | `值` | `len`/`str`/`int` 及其中文名 |
```markdown
> print text=Hello
> 打印 内容=你好
*`n` = > 长度 值=`s`*
```
宿主原语 `type` / `trim` / `split` / `join` / `at` **无**内核中文别名;文本/表扩展走标准库文件(见 [stdlib-i18n.md](stdlib-i18n.md))。转换错误见 [stdlib.md](stdlib.md)。
---
@@ -55,30 +69,29 @@
```markdown
# main
> print text=Hello World!
> 打印 内容=Hello World!
*`n` = 1*
+ `n` > 0
1. `n` > 0
> print text=positive
+ *
> print text=other
2. *
> 打印 内容=other
```
- `>` 是**调用标记**(架构)。
- `print` 是**被调名字**(内置库)。
- 用户自定义 `# print` 会遮蔽内置(实现应警告)。
- `>` 是调用标记;`print` / `打印` 是同一内置的别名。
- 用户 `# print` 或 `# 打印` 会遮蔽对应名字。
---
## 5. 标识符规则(摘要)
- 变量:行内 `` `name` ``;`name` 不可为上表关键字。
- 函数名:`#` 标题文本;建议 ASCII/英文,中文标题仍允许但内置名保持英文。
- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and` `or` `not`。
- 变量:`` `name` ``;不可为上表任一中英文关键字。
- 函数名:`#` 标题;中英文均可。
- 比较:`==` `>` `<` `>=` `<=`;逻辑:`and`/`且`、`or`/`或`、`not`/`非`。
---
## 6. 后续可增(未批准)
`len`、`str`、`int`、`float`、`range`;以及 `break`/`continue`(若循环需要)。增加前开短 ADR。
`float`、`range`;以及 `break`/`continue`。增加前开短 ADR,并同步考虑是否值得占用双名配额。
+55
View File
@@ -0,0 +1,55 @@
# 标准库 / 扩展库:代码即文档
| | |
|---|---|
| 状态 | **Active** |
| 日期 | 2026-09-14 |
| 相关 | [code-as-docs-gaps.md](code-as-docs-gaps.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md) · [collection-access-link.md](collection-access-link.md) · [stdlib.md](stdlib.md) · [marqdo-dev skill](../../.cursor/skills/marqdo-dev/SKILL.md) · [roadmap](../roadmap/lib-ext-code-as-docs.md) |
---
## 1. 目标
`lib/*` 与 `ext/*` 的 `.mq.md` 应**可当说明书读、可当程序跑**。薄库不写长文;厚领域库(web / quantum / …)仍用叙述承载意图,但数据与调用面与用户程序同一套标记。
## 2. 薄库模板(默认)
每个导出函数 / 方法尽量按此骨架(中英分文件锁步):
1. **目的句**(一句人话,无标记即可)。
2. **叙述形参**:正文里出现 `` `名` `` / `` `名`=默认 ``(推断签名);过渡期可保留 `` + `名` ``。
3. **一例**:粗体或 `>` 调用;优先可读表面。
4. **实现**:短;取元用 `[键](集合)`,**禁止新增**脚注取元 `` `m`[^k] ``(旧解析仍可用)。
调用示例(三种等价,试点期任选;新叙述优先括号标记或粗体):
```markdown
**出 = [put] 入=`表` 键="a" 值=1**
**出 = put 入=`表` 键="a" 值=1**
> put 入=`表` 键="a" 值=1
```
带布尔开关时可用前置修饰:`严格 [parse] text=`源`` → `严格=True`(形参名与修饰语字面一致;核心不剥「的」等词缀)。
## 3. 硬约束
| 要 | 不要 |
|----|------|
| GFM 表作数据;`table.put` / 具名助手 | `json.set` 链当字典构造器 |
| 作者程序用 `[k](c)` 取元;`- [项](集合)` foreach | 新代码写 `` m[^k] `` |
| 中英 API 对称(见 [stdlib-i18n.md](stdlib-i18n.md)) | 只改一侧 |
| 一例跑通即文档(public/stdlib 或 examples) | 另开第二套「文档站」手写说明 |
**库函数体内的叙述坑:** 函数体里的链接形 `[k](c)`、以及单独的 `**强调**` 会被当成可执行代码。库内说明用「链接取元 / link-index」等字面描述;可执行示例放在 `public/stdlib` 或 `examples/`,不要写在 `##` 体内当叙述。
## 4. 波次
见 [roadmap/lib-ext-code-as-docs.md](../roadmap/lib-ext-code-as-docs.md):先稳定调用表面,再 M1 试点 table/text/json,其后批次 lib → ext。
## 5. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-09-14 | 初稿(随括号调用落地) |
+618
View File
@@ -0,0 +1,618 @@
# Marqdo 语法映射 v0.3(叙述统一 · 粗体即代码)
| | |
|---|---|
| 状态 | **Accepted · 现行运行时目标(实现中)** |
| 日期 | 2026-09-13 |
| 取代 | [markdown-mapping.md](markdown-mapping.md) **v0.2(已废止为运行时宪法)** |
| ADR | [0005-prose-unified-markup.md](../adr/0005-prose-unified-markup.md) |
| 路线 | [markup-v0.3.md](../roadmap/markup-v0.3.md) |
| 相关 | [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) · [call-arguments.md](call-arguments.md) · [objects.md](objects.md) · [keywords.md](keywords.md) |
> **名词:** 本文「Markup」指 Marqdo **如何把 Markdown 标记映射成语法**(`**` 代码、`*` 返回、`` `名` `` 声明),不是另一个语言。产品仍是 Marqdo。
> **v0.3 为唯一映射。** 不做 v0.2 双模式 / `--markup` 版本身份。摸索阶段允许破坏性变更;旧 `.mq.md`(`*语句*` / `**返回**`)须改写。金样例见 `tests/markup-v03/`。
---
## 0. 一句话
让 **Markdown 叙述本身成为程序的一部分**:普通文字里用 `` `名` `` 出现变量(首次未赋值 = 声明);用 **`**…**` 粗体** 包裹可执行代码(含调用,不必再写 `>`);用 **`*…*` 斜体** 表示返回值。函数形参**不再手写 `+` 列表**,由函数体内的声明/赋值自行推断。
---
## 1. 动机(为何推翻 v0.2 的部分定论)
v0.2 为了「标记即语法」的清晰边界,做了这些硬隔离:
| v0.2 | 代价 |
|------|------|
| 无标记行 = 纯注释;变量只能写在 `*…*` / 结构行里 | 叙述与代码割裂,「文档即代码」读起来像两套语言叠在一起 |
| `*…*` = 语句,`**…**` = 返回 | 与常见 Markdown/AI 习惯相反:模型更爱用 `**` 强调「要执行的东西」,读者也更易看见粗体 |
| 调用必须 `>` | 行间调用要另起结构行,叙述中夹调用不自然 |
| 形参必须 `` + `名` `` | 仪式感强;函数头像「另一套签名语言」,与正文脱节 |
古早示例(当时不能跑,正是本文要合法化的目标面):
```markdown
## 加一函数
对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。
# main
我要调用加一函数可以采用这样的办法:
> 加一函数 37
或者可以直接这么调用**加一函数 37**
```
目标:上述文件在 v0.3 下应能解析、求值,且**读起来仍是一篇正常中文说明**。
---
## 2. 哲学(设计原则)
### P1 — 叙述统一(Prose-unified)
- Marqdo 注释采用 **Markdown 叙述**(段落、列表中的说明文字),不是第二种注释语法。
- **变量可以出现在正常文字之间**:用 Markdown 行内代码 `` `n` `` 标识标识符。
- **第一次出现且未赋值 = 声明变量**;之后的出现 = 引用。赋值发生在粗体代码段内(或兼容的结构赋值形)。
- **未使用的变量无害**(不报错、不升参);真正的输入由「可执行面读取」升为形参(§8)。
- 这样「说明文字」与「程序名字」共用同一套 Markdown 视觉习惯,整体更和谐。
### P2 — 粗体即代码(Bold-as-code)
- **`**…**` = 代码段**(可执行):赋值、表达式、函数/方法调用、可内联的短语句。
- 选择粗体的原因:
1. **AI 输出偏好**:模型天然爱用 `**` 强调「重要操作」;把粗体定为可执行,降低「模型写了强调却被当成返回」的错配。
2. **行间显眼**:在长段落里,粗体比斜体更容易被扫到。
- 粗体代码段内的调用 **允许不写 `>`**:`**加一函数 37**` 与 `> 加一函数 37` 语义等价(见 §6)。
- **`>` 保留为可选调用面**(blockquote 风格、独立行、兼容 v0.2 迁移与 AI 已学会的形态)。
### P3 — 斜体即返回(Italic-as-return)
- **`*…*` = 返回值**(架构级),与粗体代码形成对立、易读的一对:
- 做了什么 → 粗体
- 结果是什么 → 斜体
- **空返回 / 无值收束**(已决议,见 §7.2):推荐 `*None*` / `*无*`;整行 `**`;兼容 `****`。`---` / `***` 仅为叙述分隔(跳过),**不再**结束函数体。
- **输出仍不是返回**:打印继续用内置 `print` / `打印`(副作用函数),不把粗体或斜体当成「打印到终端」的语法。
### P4 — 形参由体推断(Body-inferred params)
- **不再要求**作者手写 `` + `名` `` 形参表(v0.3 默认关闭;过渡期可兼容,见 §8)。
- 函数体内:
- **只声明、未赋默认** → **必选形参**(调用时必须提供)。
- **声明同时赋值**(含默认值字面量)→ **可选形参**(带默认值)。
- 推断顺序与绑定规则见 §8;与位置/具名实参规则对齐 [call-arguments.md](call-arguments.md) 的精神(可修订附录)。
### P5 — 标记仍承载控制流(不变)
- **不引入** `if` / `else` / `while` / `for` / `def` / `return` 关键字。
- `#` = 对象/类型,`##`+ = 函数/方法([objects.md](objects.md) 不变)。
- 分支仍用 `1.` `2.` …;循环仍用 `-`;结构行不必再包粗体(见 §5)。
### P6 — 其它「代码即文档」补强(本版一并采纳)
| 思路 | 说明 |
|------|------|
| **渐进披露** | 读者可只读叙述;运行时只执行标记与推断出的声明。同一文件服务人与机器。 |
| **最小仪式** | 能从正文看出的签名,就不在函数头重复写一遍。 |
| **双调用面** | 独立行 `>` 适合「步骤清单」;行间 `**f …**` 适合「嵌在句子里的动作」。 |
| **标识符视觉统一** | 叙述、代码、形参一律优先 `` `名` ``;粗体/斜体内部允许裸名(与 v0.2 斜体/粗体内规则同类)。 |
| **段落仍可整段注释** | 不含任何可执行标记、且无「声明性 `` `名` ``」义务的纯说明段,行为与注释相同(见 §4 消歧)。 |
| **迁移可观测** | `--dump-lines` / `--dump-ast` 必须能区分「叙述中的声明」与「粗体代码」与「斜体返回」。 |
---
## 3. 与 v0.2 对照(角色对调摘要)
| 概念 | v0.2 | v0.3 |
|------|------|------|
| 程序语句 / 代码段 | `*…*` | `**…**` |
| 返回值 | `**…**` | `*…*` |
| 独立调用 | 必须 `>` | `>` **或** `**callee …**` |
| 形参 | 标题下 `` + `名` `` | **体推断**(`+` 过渡兼容) |
| 叙述中的变量 | 一般为注释,不可声明 | `` `名` `` 可声明/引用 |
| 无标记纯文字 | 成段注释 | 仍为叙述;**若含声明性反引号则参与绑定图**(见 §4) |
这是一次 **架构级标记对调**,不是局部糖。金样例、教程、Skill、扩展库需按路线图分波迁移。
---
## 4. 叙述、声明与注释
### 4.1 三层模型(修订)
| 层 | 形态 | 角色 |
|----|------|------|
| **叙述面** | 普通 Markdown 段落、列表说明 | 给人读;其中的 `` `名` `` 可进入**绑定图** |
| **可执行面** | 结构标记(`#` `>` `+` `-` `1.` 表…)+ **`**代码**`** + **`*返回*`** | 求值 |
| **外联面** | ` ```lang ` | FFI(不变) |
### 4.2 变量在叙述中的出现
语法:Markdown **行内代码** `` `标识符` ``。
| 出现形态 | 语义 |
|----------|------|
| 全文(当前函数/对象作用域)**首次**出现 `` `n` ``,且此前/同句无对 `n` 的赋值 | **声明变量**(进入绑定图;是否升为形参见 §8) |
| 已声明之后再次 `` `n` `` | **引用**(不生成新绑定) |
| 粗体内 `**n = …**` / `**n=n+1**` | **赋值**(若首次赋值且未见声明,则声明+赋值一并发生) |
| 叙述中 `` `n`=1 ``(反引号名紧贴 `=`,无粗体) | **带初值的声明**(形参默认或局部初值;见 §8) |
推荐作者写法(与动机示例一致):
```markdown
对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。
```
- `` `n` `` → 声明变量;因随后在代码中**读取**未先由局部独力定义 → 升为必选形参(§8)
- `**n=n+1**` → 代码段(赋值)
- `*n*` → 返回
### 4.3 何为「纯注释」
满足下列**全部**条件的段落,不产生绑定、不求值:
1. 不含结构标记行;
2. 不含 `**…**` / 作为返回的 `*…*`(见 §7);
3. 不含任何 `` `标识符` ``。
仍建议:**叙述段与独立结构代码行之间空一行**,降低人读与差分时的视觉粘连(解析器在 v0.3 下不再依赖「空行分段注释升级」作为唯一边界,但空行仍是作者卫生习惯)。
### 4.4 提及性反引号:一律视作变量(已决议)
**不另设「仅提及、不声明」语法。** 叙述里凡出现合法标识符 code span `` `名` ``,一律按 **变量** 处理(首次 = 声明,其后 = 引用)。
| 情况 | 处理 |
|------|------|
| 谈到某名但可执行代码**从未读写**它 | 仍是绑定图中的变量;**对求值无影响**(死绑定) |
| 与其它语言对照 | 类似 Python 写了未用局部、JS 未用 `let`——默认可忽略;实现可对「从未读写」发**可选 lint**,**不得**因此报错或拒绝运行 |
| 是否变成函数形参 | **否**(仅声明、从未在可执行面被读取)——见 §8.2「升参条件」 |
| 是否需要 `` 提及`n` `` 等前缀 | **不需要**;避免第二套反引号方言 |
例(合法、无副作用):
```markdown
## 说明性函数
本文顺便提到`Markdown`与`GFM`,但真正的输入只有`题干`。
**print text=题干**
---
```
- `` `Markdown` `` / `` `GFM` `` → 变量声明,未使用 → 不进形参表、不改行为
- `` `题干` `` → 声明且在粗体中读取 → 必选形参
**否决**:为「提及」单独做转义/前缀(曾列于开放点);若将来作者强烈需要「叙述中的等宽字但不进绑定图」,另开增强案,不阻塞 v0.3 核心。
### 4.5 成段规则相对 v0.2 的变化
v0.2:「段首无标记 → 整段注释,续行永不升级」。
v0.3:
- 叙述段落**可以**内含可执行粗体/斜体返回;解析器做**段内扫描**,抽出 `` `名` ``、`**…**`、`*…*`。
- 独立结构行(行首 `#` `>` `-` `1.` `|` 等)仍整行分类为代码。
- **否决维持**:「整行无标记 = 默认可执行代码」。无标记且无反引号声明的文字永不单独变成语句。
---
## 5. 映射总表(v0.3)
| 标记 | 语义 |
|------|------|
| `#` … `######` | `#` = 对象/类型;`##`+ = 函数/方法(同 [objects.md](objects.md)) |
| 叙述中 `` `名` `` | 声明或引用(§4) |
| `**…**` | **代码段**(赋值、表达式、调用) |
| `*…*` | **返回值**(含显式空值,见 §7.2) |
| `>` 行 | **调用**(可选面,与粗体内调用等价) |
| `` + `名` `` | **过渡兼容**:显式形参;新代码不推荐 |
| 体内 `1.` `2.` … | 分支 |
| 体内 `-` | 循环 |
| `N. *` | else 臂(此处 `*` 仍是「空条件」标记,**不是**返回值;见 §7.3) |
| GFM 表格 | 集合(不变) |
| 表达式 `[键](集合)` | **取元**(与 foreach 同形;见 [collection-access-link.md](collection-access-link.md)) |
| `修饰… [函数名] 实参…` | **方括号标记调用**(前置修饰 → `名=True`;见 [bracket-call-modifiers.md](bracket-call-modifiers.md)) |
| `` 集合[^键] `` | **过渡**:旧脚注取元(仍可用) |
| ` ```lang ` | 外联(不变) |
| 单独一行 `---` / `***` | **叙述分隔**(跳过;模块顶与函数体内相同) |
| 整行恰 `**` 或 `****` / `*None*` / `*无*` | **空返回**并结束本函数体(见 §7.2) |
### 结构行与粗体
行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包 `**…**`。
粗体用于:**嵌在叙述中的代码**,以及「我想把这一小段标成可执行」的行间片段。
---
## 6. 调用
### 6.1 调用表面
```markdown
> 加一函数 37
**加一函数 37**
礼貌 [问候] marqdo
```
前两种解析为对 `加一函数` 的调用;第三种为**方括号标记调用**(`[` `]` 标出函数名,前置裸词展开为 `名=True`)。实参位置或具名绑定;详见 [call-arguments.md](call-arguments.md) · [bracket-call-modifiers.md](bracket-call-modifiers.md)。
| 形式 | 典型用途 |
|------|----------|
| `> …` | 步骤列表、独立可执行行、与 v0.2/AI 习惯兼容 |
| `**…**` | 嵌在句子中:「或者可以直接这么调用**加一函数 37**」 |
| `**x = 加一 37**` | 粗体赋值右侧为调用时**可省略 `>`**(代码即文档首选;`> 加一 37` 仍合法) |
| `修饰… [函数] 实参…` | 叙述里需要「形容词 + 动词」时消歧;与 `[键](集合)` 取元靠 `]` 后是否紧邻 `(` 区分 |
### 6.2 粗体内调用的判别
粗体内容在去掉外层 `**` 后,按下列优先级分类:
1. 含 `=` 且左侧为可赋值目标(标识符 / 脚注左值等)→ **赋值语句**(可含右侧调用)。
2. 否则,若首词为已知函数/方法/内置/导入成员(Pass 名表可见)→ **调用**。
3. 否则 → **表达式语句**(求值后丢弃,或在语句位置非法则诊断)。
示例:
| 粗体内容 | 分类 |
|----------|------|
| `n=n+1` | 赋值 |
| `加一函数 37` | 调用 |
| `加一函数 n=37` | 调用(具名) |
| `n + 1` | 表达式(单独出现时;作返回应写 `*n + 1*`) |
| `print text=hi` / `打印 内容=你好` | 调用(内置) |
### 6.3 方法调用
- 独立行:`` > `对象`.方法 … ``(兼容)或 `> 对象.方法 …`(若接收者规则允许)。
- 粗体内:`**对象.方法 …**` / `**p = page.主体装配 组件=home**`。
- 粗体/斜体内裸名 = 变量(延续 v0.2「段内统一命名空间」精神)。
### 6.4 实参
具名 + 位置混用规则继承 [call-arguments.md](call-arguments.md);v0.3 仅把「形参列表来源」从 `+` 行改为**推断签名**(§8)。独立 `>` 行上裸词仍为文本字面量;粗体内调用的裸词为变量(与 v0.2「段内调用」一致)。
---
## 7. 返回
### 7.1 斜体返回
```markdown
*n*
*n + 1*
*"ok"*
```
斜体内部值语法与 v0.2 粗体返回内部相同(裸词 = 变量;文本须引号)。
### 7.2 空返回与收束(已决议)
Marqdo **不引入** `return` 关键字;「无值结束」用标记表达。对照常见语言:
| 语言 | 无值 / 空返回 | Marqdo v0.3 对应 |
|------|----------------|------------------|
| Python | `return` / `return None` | 显式 `*None*`·`*无*` |
| Go | 无结果函数里的 `return` | `*None*` / 整行 `**` / `****` |
| Rust | `()` 或函数末尾隐式 unit | 同上;或下一标题 / EOF 自然结束 |
| JavaScript | `return;` → `undefined` | 同上 → 运行时 `None` |
| Marqdo 历史 | `---` 收束;`****` | `---` 已改为叙述跳过;`****` 仍兼容 |
#### 形式层级(推荐自上而下)
| 优先级 | 形式 | 语义 | 说明 |
|--------|------|------|------|
| **1. 显式空值** | `*None*` 或 `*无*`(整段或行内返回位) | 返回 `None` **并结束本函数体解析** | 对齐 Python `return None`;副作用函数首选;外层续写依赖此收束 |
| **2. 空斜体标记** | **整行** trim 后恰为两个星号:`**` | 同上 | 词法钉死:`^\s*\*\*\s*$` → **空斜体返回**,**不得**当成粗体开闭 |
| **3. 兼容** | 整行 `****`(四个星号) | 同空返回 | 迁移期识别 |
| **(非收束)** | 整行 `---` / `***` | **仅叙述分隔**,跳过 | 不再结束函数;见 [code-as-docs-gaps.md](code-as-docs-gaps.md) |
```markdown
## 只打印
**print text=hi**
*None*
## 空斜体行
**print text=hi**
**
## 分割线不收束(下一标题才结束)
**print text=hi**
---
```
#### 词法消歧(空斜体 vs 粗体)
1. **整行恰好 `**`(两个 `*`)** → 空返回(规则 2),不是未闭合粗体。
2. **粗体代码**至少包住一个非空内容:`**x**`、`**n=1**`;不允许「空粗体代码段」作为语句。
3. **四个星号整行 `****`** → 兼容空返回(规则 3),不解释为「空粗体代码」。
4. 行内出现的 `**…**`(两侧还有叙述文字)按正常粗体代码扫描,不走「整行空返回」。
#### 与「有返回值」的关系
- 需要把值交回调用方 → 用非空斜体:`*n*`、`*n + 1*`(返回即结束本函数体解析)。
- 只做副作用、不要值 → 优先 `*None*` / `*无*` / 整行 `**`。
- 下一标题或 EOF 也可结束体;**不要**再靠 `---` 收束。
### 7.3 与 else 臂 `N. *` 的消歧
有序列表臂头 `2. *` 中的 `*` 表示 **else**,不是返回。判别:行匹配 `^\s*\d+\.\s+\*\s*$`(可带尾注)→ 分支 else;不进入返回扫描。
### 7.4 输出
```markdown
**print text=Hello**
> print text=Hello
```
打印是调用,不是返回。禁止把 `*Hello*` / `**Hello**` 解释为「打印 Hello」(延续 v0.2 决议精神,仅对调标记)。
---
## 8. 形参推断
### 8.1 目标签名
对每个 `## 函数`(及方法),在 Pass1 收集体之后得到:
```text
params: Vec<{ name, default: Option<Expr>, span }>
```
### 8.2 收集规则(函数作用域)
扫描该函数标题之下、下一同级/更高级标题之前的所有节点,维护**绑定图**与**形参表**(二者分离):
#### A. 绑定图(所有变量)
1. **声明事件**:叙述或代码中的首次 `` `名` ``,或粗体内首次对 `名` 的赋值左值。
2. **默认/初值事件**:叙述 `` `名`=默认表达式 ``;或符合 §8.3 的「形参默认」赋值。
3. **排除出绑定图**(不建变量):
- 循环变量 `` - [项](集合) `` 中的 `项`(循环自有绑定);
- `self` / `自`(方法自动注入)。
凡进入绑定图的名字都是**变量**——包括「只在叙述里出现、可执行代码从未读写」的名字(§4.4)。未使用 → **不报错**。
#### B. 升为形参的条件(升参)
名字已在绑定图中,且满足下列之一,才进入 `params`:
| 升参种类 | 条件 |
|----------|------|
| **必选形参** | 在可执行面(`**…**` / `*…*` / `>` / 结构语句)中存在对 `名` 的**读取**,且该读取无法单靠「不依赖外部输入的局部赋值」满足——典型:先声明、后 `n=n+1` / `*n*` / `**print text=n**` 等读到未先行赋成纯局部常量 |
| **可选形参** | 有默认/初值事件(`` `名`=… `` 或 §8.3 默认赋值),供调用方覆盖 |
**不升参**:仅叙述声明、可执行面零读取(死绑定)→ 留在绑定图,**不进** `params`,调用签名不变。
**顺序**:按升参名字的**首次声明事件**在源码中的出现序。
**仍排除**:分支/块内纯局部(金样例钉启发式);显式 `+` 合并见 §8.4。
### 8.3 「形参默认」与「函数体赋值」的区分
```markdown
## 问候
对`谁`打招呼,默认`礼貌`=False。
**print text=谁**
```
- `` `谁` `` → 必选
- `` `礼貌`=False `` → 可选,默认 `False`
- 体里的 `**print …**` 不是给 `谁` 赋默认值
```markdown
## 加一函数
输入`n`。**n=n+1**返回*n*。
```
- `` `n` `` 先声明 → 必选
- `**n=n+1**` 是**体语句**(对已声明形参赋值),**不是**默认值
判别启发式(实现契约):
- 若赋值右值**依赖同名左值**(如 `n=n+1`)→ 体语句。
- 若赋值出现在「该名被当作输入读取」之前,且右值不依赖未绑定的同名 → 可作为默认值候选。
- 叙述形 `` `名`=字面量 `` 优先视为默认值声明。
### 8.4 显式 `+` 形参(过渡)
- 若函数标题下仍有 `` + `名` `` 行:与推断结果**合并**;冲突时 **显式 `+` 胜出**并诊断警告。
- 迁移完成后(路线图 M4)可改为:存在 `+` 则关闭推断,或直接废弃 `+`。
### 8.5 调用绑定
与现有一致:具名优先,位置按「尚未绑定的形参」从左到右填充。缺必选形参 → 语义错误。
---
## 9. 完整示例(规范金样意向)
### 9.1 加一(动机例)
```markdown
## 加一函数
对于输入变量`n`,我们执行操作**n=n+1**接着返回*n*。
# main
我要调用加一函数可以采用这样的办法:
> 加一函数 37
或者可以直接这么调用**加一函数 37**
```
期望:
- 签名:`加一函数(n)`
- `# main` 两次调用均返回 `38`(第二次若未绑定到打印,至少 AST/求值结果为 38;可用 `**print text=…**` 观测)。
### 9.2 带默认值
```markdown
## 问候
向`谁`问好;`礼貌`=False 时用短句。
1. 礼貌
**print text=您好,**
**print text=谁**
2. *
**print text=嗨,**
**print text=谁**
---
# main
**问候 谁=Marqdo 礼貌=True**
> 问候 Marqdo
```
### 9.3 对象方法(不变骨架)
```markdown
# 计数器
## 加
将`self`的`值`增加`delta`(`delta`=1)。
**值 = 值 + delta**
*self*
# main
*c = > 计数器*
**c.加 3**
```
(方法形参推断含 `delta`;`self` 自动。)
---
## 10. AST / 管线变更要点(设计约束)
详细里程碑见 [markup-v0.3.md](../roadmap/markup-v0.3.md)。此处只钉**语义 → 树**的约束,供实现对照:
### 10.1 行分类(lex / line-class)
新增或调整类别:
| 类别 | 说明 |
|------|------|
| `Prose` | 叙述行;需**内联扫描** |
| `BoldCode` | 整行或片段 `**…**` |
| `ItalicReturn` | 整行或片段 `*…*`(非 else 臂) |
| `CallLine` | `>` 调用(保留) |
| … | 原有 Heading / List / Table / Fence / Hr |
**内联扫描**产出 `InlineBit`:`Text` | `IdentDecl/Ref` | `BoldCode` | `ItalicReturn`。
### 10.2 AST 节点调整(建议)
```text
Param { name, default?, inferred: bool, span } // inferred=true 表示来自体推断
Stmt::
Assign { … } // 多由 BoldCode 解析
Call { … } // CallLine 或 BoldCode 判别为调用
Return { value } // 由 ItalicReturn 解析(原由 Bold)
ExprStmt { … } // 可选:纯表达式粗体
Prose { bits } // 可选:保留叙述结构供 view/catalog;求值阶段只消费 Decl
FnDef.params:
由 InferParams(body + prose bits) 填充,再合并显式 +
```
`Stmt::Return` 的**语法来源**从粗体改为斜体;dump 文本应写 `return←italic`。
### 10.3 Pass1 / Pass2
- Pass1:收集 `#`/`##` 结构;建绑定图;跑 **ParamInfer(升参)**;登记名表。
- Pass2:粗体内调用名解析;叙述 Decl 不重复建参。
- 诊断:**必选缺失**、`+` 与推断冲突、空返回词法歧义(非整行 `**` 的残缺粗体)。
- Lint(可选、默认关或降级为 hint):绑定图中「从未读写」的死变量——**不得**当错误。
### 10.4 双后端
树遍历与字节码均消费同一 AST;字节码发射仅跟随 `Stmt`/`Expr` 变化,不感知 Markdown 标记。
---
## 11. 破坏性切换(无双模式)
**产品决定(2026-09-13):** 直接以 v0.3 为唯一运行时映射;**不**保留 `--markup v0.2` / 双 edition。旧语法金样例与库文件在迁移完成前可能失败——可接受。
| 阶段 | 行为 |
|------|------|
| 现在 | 解析器切到 v0.3;`tests/markup-v03/` 为门禁 |
| 随后 | 批量改写 `tests/structure|keywords`、`lib/`、`ext/`、Skill、`public/` |
| 文档 | `markdown-mapping.md` 改为指向本文;ADR 0005 → Accepted |
**机械改写:**
- 语句 `*a = 1*` → `**a = 1**`
- 返回 `**x**` → `*x*`
- 粗体内文本字面量须引号:`**print text="hi"**`(裸词 = 变量)
- 调用可保留 `>` 或改为粗体
- `` + `n` `` 可删,改为叙述 `` `n` `` + 升参
---
## 12. 开放问题 / 已决议
| # | 议题 | 状态 | 决议摘要 |
|---|------|------|----------|
| 1 | 空返回词法 | **已决议** | §7.2:推荐 `*None*`/`*无*`;整行 `**`;兼容 `****`;`---` 仅叙述跳过 |
| 2 | 提及性反引号 | **已决议** | §4.4:一律视作变量;未使用不报错、不升参;不设提及前缀 |
| 3 | 粗体内调用 vs 赋值 | **已落地** | §6.2:可赋值左值 → 赋值;否则表达式优先、再裸调用;`**n + 1**` = ExprStmt |
| 4 | `` `n`+1 `` 误声明 | **已落地** | Decl 名须为标识符;`` `n+1` `` 不升 Decl |
| 5 | 叙述强调斜体 vs 返回 | **已落地** | 整行 / `返回*…*` / 表达式形才当返回;`*only*` `*very important*` `*foo.bar*` 为叙述 |
| 6 | 一行多 `**…**` | **已落地** | 允许,按出现序执行(`tests/markup-v03/multi-bold.mq.md`) |
| 7 | view 展示 prose Decl | **已落地** | Structure / Functions 大纲:`inferred` 形参标注(`chip inferred`) |
---
## 13. 非目标
- 不把整篇无标记 Markdown 变成可执行程序。
- 不引入 `def` / `return` 关键字(空返回用标记,见 §7.2)。
- 不改变 `#` / `##` 对象体系与 ext 插件 ABI。
- 不在本文阶段修改解释器代码(见路线图)。
- 不为「提及」另发明一套反引号方言(§4.4)。
---
## 14. 验收标准(设计完成 ≠ 实现完成)
设计稿验收:
- [x] 哲学 P1–P6 成文
- [x] 与 v0.2 对照表
- [x] 形参推断规则可实现(含升参 vs 死绑定)
- [x] 动机示例在语义上闭合
- [x] AST/管线约束与路线图挂接
- [x] ADR 记录决策意向
- [x] **空返回**对照其它语言并钉死词法
- [x] **提及/未使用变量**政策钉死
实现验收:
- [x] 金样例夹具 `tests/markup-v03/`(`gold.rs` `markup_v03_*`)
- [x] 动机示例金样例通过(`inc-prose.mq.md`)
- [x] `--dump-ast` 可见 inferred params 与死绑定;`--dump-lines` 标注 `[decl]` / `[bold]` / `[italic]`
- [x] 空返回四种形式金样例通过
- [x] 无 v0.2 双模式(默认即 v0.3)
---
## 15. 修订历史
| 日期 | 说明 |
|------|------|
| 2026-09-13 | 初稿:叙述统一、粗体代码、斜体返回、形参体推断;Proposed |
| 2026-09-13 | 决议空返回(§7.2)与提及性反引号(§4.4);形参改为「升参」与绑定图分离(§8.2) |
| 2026-09-14 | §7.2:`---` 不再收束;返回语句结束函数体解析;空返回首选 `*None*` |
| 2026-09-14 | 取元主语法改为 `[键](集合)`;脚注取元过渡保留 |
+188 -52
View File
@@ -1,11 +1,12 @@
# Marqdo 语法映射 v0.1(Markup-as-Syntax)
# Marqdo 语法映射 v0.2(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) |
| 状态 | **历史文档(v0.2 · 已废止为运行时)** — 现行见 **[markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)** |
| 日期 | 2026-08-07 |
| 取代 | v0.1 中「函数头 `-` 形参 / 裸名形参与遍历变量 / `+` 分支」 |
| 被取代 | **[markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)**(粗体即代码 · 斜体即返回 · 无双模式兼容) |
| 相关 | [objects.md](objects.md) · [code-vs-comment.md](code-vs-comment.md) · [return-hr-and-code-surface.md](return-hr-and-code-surface.md) · [module-namespace.md](module-namespace.md) |
Markdown **标记即语法**。输出**不是**语言架构原语,而是内置函数 **`print`**(英文;见 [keywords.md](keywords.md))。
@@ -15,8 +16,13 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
1. `.mq.md`:打开即文档,运行即程序。
2. **叙述注释**以空行分段:段首无标记 → 注释;段内续行一律注释(见 §2)。
3. **可执行**靠标记:结构标记(`#` `>` `+` `-` 表…)与 **斜体语句** / **粗体返回**。
4. 作用域 = `#` 层数;入口 = `index.mq.md`。函数体可用 `---` / `***` 或空返回收束(见 §11)。
3. **可执行**靠标记:结构标记(`#` `>` `+` `-` `1.` 表…)与 **斜体语句** / **粗体返回**。
4. **`#` = 对象/类型**,**`##`+ = 函数/方法**(嵌套按标题深度);入口优先 `# main`(见 [objects.md](objects.md))。函数体可用 `---` / `***` 或空返回收束(见 §11)。
5. **标识符默认反引号**:形参、绑定、引用写作 `` `名` ``,与 Markdown 无序列表/链接脱钩。
**豁免:**
- foreach 头 `` - [项](集合) `` 允许裸名或反引号(可混用),推荐裸名;循环体内引用仍用 `` `名` ``。
- 脚注取元 `` 名[^键] ``:基名在紧跟 `` [^…] `` 时可省略反引号(`` `名`[^键] `` 仍合法);链式同理。
- **斜体语句 / 粗体返回内部**:裸标识符默认是**变量**(含调用实参与方法接收者);文本字面量须 `"…"` 或 `'…'` 或引号实参(`key="文本"`);`` `名` `` 仍合法。这是 **Python 统一命名空间**:裸点号 `a.b` 在 `a` 为局部变量时为方法调用,否则为库路径。
---
@@ -29,38 +35,52 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
| 普通文字 / 空 | **注释** |
| 标记字符 | **代码** |
标记含:`#` `*` `>` `+` `-` `` ` `` `|`、有序数字、围栏 `` ` ``、以及函数体内的结束分割线 `---` / `***`(见 §11)。
标记含:`#` `*` `>` `+` `-` `` ` `` `|`、有序数字 `1.`、围栏 `` ` ``、以及函数体内的结束分割线 `---` / `***`(见 §11)。
**成段注释(空行分段)**:段首一旦判定为注释,则直至下一空行之前的所有非空行一律为注释——即使续行以 `` ` `` / `-` / `*` 等开头也不升级为代码。叙述与可执行代码之间**必须空一行**。例外:单独一行的 `---` / `***` / `****`(函数结束或 frontmatter 闭合)始终为代码,并打断注释段。
---
## 3. 映射总表(v0.1)
## 3. 映射总表(v0.2)
| 标记 | 语义 |
|------|------|
| `#` … `######` | 函数;层数 = 作用域 |
| 函数头下 `-` 纯名 | 形参 |
| 体内 `-` | 循环 |
| 体内 `+` 或 `1.` | 分支 |
| 分支臂头整行恰为 `*` | else |
| `#` … `######` | **`#` = 对象/类型**(可 `# Child = > Parent`);**`##`+ = 函数/方法**(层差=嵌套)。见 [objects.md](objects.md) |
| 函数头下 `+ `` `名` `` ` | 形参 / 构造参数(可选 `` `名`=默认值 ``) |
| 体内 `1.` `2.` … | **分支**(有序列表臂;条件行或 else) |
| 体内 `-` | **循环**(`while` 条件,或 `[项](集合)` / `` [`项`](`集合`) `` 遍历) |
| 分支臂头整行恰为 `*`(在 `N.` 后) | else,如 `2. *` |
| `> 函数 形参=实参` 或 `> 函数 实参` | 调用(具名 / 位置,见 [call-arguments.md](call-arguments.md)) |
| frontmatter `> path.mq.md` | 跨文件导入 |
| `` > `对象`.方法 … `` | 方法调用(独立 `>`;实例 map 须含 `_type`)。`*…*` 段内接收者裸名:`*x = > 对象.方法 …*` |
| frontmatter `import bind:path.mq.md` / `导入` | 导入文件并绑定库名 |
| frontmatter `import bind:lib.member` / `导入` | 将库路径成员绑为本地短名(与文件导入同形) |
| `> lib.member …` / `> lib.Type.member …` | 点号路径调用(路径段裸名、无反引号) |
| `*…*` | **程序语句**(绑定、表达式句、可写的调用句等) |
| `**…**` | **返回值**(架构级;函数结果) |
| `****` / `**` + 空白 + `**` | **空返回**(`None`),并结束本函数体 |
| 无标记行 / 成段续行 | 注释(空行分段,见 §2) |
| GFM 表格 | 集合 |
| 空 RHS 赋值 + 后随 `$$…$$`(或同行 `$$…$$`) | **公式赋值** → 运行时 `formula`(见 [stdlib-math.md](stdlib-math.md));叙述面无名 `$$` 仅展示 |
| ` ```lang ` | 外联异种代码 |
| 函数体内 `---` / `***` | **结束本函数体**(无返回值函数的收束;见 §11) |
### `+` / `-` / `1.` 消歧
| 位置 | `+` | `1.` … | `-` |
|------|-----|--------|-----|
| 函数标题后、**首条体语句前** | 形参:`` + `名` `` / `` + `名`=默认 `` | (非法) | (非法作形参) |
| 函数体内 | (非法作分支) | 分支臂:`1. `条件`` / `2. *` | 循环 |
**分支从未使用 `+`。** 自 v0 起即采用 GFM 有序列表;`+` 在 v0.2 专用于形参,与 `-` 循环彻底分离。
### 输出不是架构
| 错误(旧) | 正确(v0.1) |
| 错误(旧) | 正确(v0.2) |
|------------|--------------|
| `**Hello**` 表示打印 | `> print text=Hello` |
| 中文名 `输出`(已废弃) | 统一英文内置 `print` |
| 输出与返回抢粗体 | 粗体只表示 **返回** |
| `+ `x` > 0` 作分支 | `1. `x` > 0` |
| `- 谁` 作形参 | `` + `谁` `` |
| `[果](篮子)` 裸名遍历 | **仍合法**(foreach 豁免);亦可用 `` [`果`](`篮子`) `` |
`print` / `input` 为内置函数,完整表见 [keywords.md](keywords.md)。
@@ -71,22 +91,27 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
### 程序语句(斜体)
```markdown
*`x` = 1*
*`y` = `x` + 2*
*x = 1*
*y = x + 2*
*answer = ev[^message]*
*亦可用 = 1*
```
行首已是结构标记的构造(`#` `>` `+` `-` `|`)**不必**再包一层斜体;斜体用于「一般语句」槽位。
斜体内部:裸标识符 = 变量;字符串写 `"…"` / `'…'`。行首已是结构标记的构造(`#` `>` `+` `-` `|`、`1.`)**不必**再包一层斜体;斜体用于「一般语句」槽位。
### 返回值(粗体)
```markdown
# 加一
- n
## 加一
+ `n`
**n + 1**
**"ok"**
**`n` + 1**
```
粗体内部与斜体相同的值语法(裸词 = 变量;文本须引号)。
### 输出(内置函数 `print`)
```markdown
@@ -97,7 +122,7 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
### else 与斜体消歧
- 分支臂**第一行整行只有一个** `*` → else。
- 分支臂有序行 `N. *`(或 `N.` 后仅 `*`)→ else。
- `*中间有内容*` → 程序语句。
- `**…**` → 返回(与 else 无关)。
@@ -105,14 +130,18 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
## 5. Frontmatter 与跨文件
同 v0:文件头 `---` 对为元信息;其中 `> file.mq.md` 为导入。
文件头 `---` 对为元信息。其中 `import bind:path.mq.md` / `导入` 为**文件导入**;`import bind:lib.member` 为**短名**(废除独立 `use` 与 frontmatter `>` 导入)。调用经裸点号路径(`time.parse`、`agent.agent`);实例方法在独立 `>` 调用须 `` > `var`.method ``(`*…*` 段内接收者裸名)。详见 [module-namespace.md](module-namespace.md)。
**函数体内的** `---` / `***` 不解释为 frontmatter(见 §11)。
---
## 6. 函数、作用域、提升
## 6. 对象、函数、形参
规则同 v0。推荐:
- `# Name`:对象(构造体);`# main` 为入口对象。
- `# Child = > Parent`:单继承(基类须为已定义对象名;方法沿链查找,子类可覆盖)。见 [objects.md](objects.md) §5。
- `##` / `###` …:函数或方法;挂在对象下则为方法。
- 标准库顶层 API 使用自由函数 `## name`(见 [objects.md](objects.md))。
```markdown
# main
@@ -120,53 +149,166 @@ Markdown **标记即语法**。输出**不是**语言架构原语,而是内置
> print text=Hello World!
## 加问候
- 谁
+ `谁`
**你好,`谁`**
```
(需要打印时对返回值再 `> print`,或直接 `> print`。)
可选形参:
形参 `- 名` → 体内 `` `名` ``。
```markdown
## 问候
+ `谁`
+ `礼貌`=False
```
方法体内自动绑定 `` `自` `` / `` `self` ``。
---
## 7. 绑定与比较
## 7. 绑定、比较与字符串
| 写法 | 含义 |
|------|------|
| `*`x` = 1*` 或行首 `` `x` = 1 `` | 绑定(两种均允许;实现应统一) |
| `*`x` = 1*` 或行首 `` `x` = 1 `` | 绑定 |
| `` `x` == 1 `` | 相等比较 |
| `"text"` | **双引号字符串**(复杂文本;见下) |
| `hello` / `路径` | **裸 token**(无转义,按字面量) |
v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致;行首 `` ` `` 仍合法以便表格右值绑定。
### 双引号字符串(复杂文本)
需要转义或嵌入变量时用 `"..."`;**裸 token 不转义**,保持文档简洁:
```markdown
> input prompt="你叫什么名字\n"
*`msg` = "Hello, `name`!\n"*
```
| 转义 | 含义 |
|------|------|
| `\n` | 换行 |
| `\t` | 制表 |
| `\r` | 回车 |
| `\\` | `\` |
| `\"` | `"` |
| `\'` | `'` |
| `\xHH` | 十六进制字符(如 `\x22` → `"`) |
| `\u{...}` | Unicode 码点(如 `\u{4e2d}` → `中`) |
引号内仍可用 `` `变量` `` 插值。字面反斜杠+n 写 `\\n`(裸 token `\\n` 则就是两个字符)。未知转义(如 `\q`)按字面保留,不报错。
---
## 8. 分支与循环
分支(`+` / 有序),循环(`-`),语义同 v0。臂体内打印改为调用 `print`:
分支(**有序列表** `1.` `2.` …),循环(`-`):
```markdown
*`x` = 0*
+ `x` > 0
1. `x` > 0
> print text=正数
+ `x` < 0
2. `x` < 0
> print text=负数
+ *
3. *
> print text=零
```
```markdown
*`bool_value` = True*
1. `bool_value` == True
> print text=True
2. *
> print text=False
```
**一条分支语句 = 从 `1.` 起、序号递增的一段有序列表。** 同级缩进上**再次出现 `1.`**(无论中间有无空行)开启**下一条**独立分支语句,不得并入上一段的臂列表:
```markdown
1. `a`
> print text=A
2. *
> print text=not-A
1. `b`
> print text=B
2. *
> print text=not-B
```
上例为两次独立判断(先 `a` 再 `b`),不是「四个臂的一个分支」。臂序号在同一分支内递增(`1.` → `2.` → `3.` …);**不要**在同一分支中途把序号重置为 `1.`。
```markdown
- [果](篮子)
> print text=今天吃`果`
```
反引号形式等价:`` - [`果`](`篮子`) ``。两侧可混用。
`while`:
```markdown
- `n` > 0
> print text=`n`
*`n` = `n` - 1*
```
---
## 9. 集合(表格)
同 v0。`` `篮子` = `` 后接 GFM 表。
`` `名` = `` 后接 GFM 表;几何决定值类型(详见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md)):
| 形状 | 值 |
|------|-----|
| **1 列**(竖表) | `List`(表头 = foreach 元素名,不进入元素) |
| **≥2 列 + 1 行数据**(横表) | `Map`:键 = 表头,值 = 该列标量 |
| **≥2 列 + ≥2 行数据** | `Map`:键 = 表头,值 = 该列 `List`(列向) |
| **≥2 列 + 0 行数据** | `Map`:键存在,值为空列表 |
| **首列表头 `@` / `行` / `row`** | **行向** `List` of `Map`(标记列不进入字段;任意数据行数) |
| 重复表头 | 诊断错误 |
**数据单元格是表达式**(与调用实参值语法相同:裸词、数字、`` `var` ``、算术、引号串;URL / `gpt-4o-mini` 等按路径·连字符折叠为文本;含 `/` 的 CSS 比率等请用引号 `"1/5"`,裸 `1/5` 为除法)。表头仍是键名文本。细则:[table-cell-expressions.md](table-cell-expressions.md)。
```markdown
*`k` = secret *
`cfg` =
| api_key | model |
|---------|-------|
| `k` | gpt-4o-mini |
```
行向示例:
```markdown
`订单` =
| 行 | 品名 | 数量 |
|----|------|------|
| 1 | 苹果 | 2 |
| 2 | 梨 | 3 |
*`名` = `订单`[^1][^品名] *
```
**脚注取元**(表达式级;可链式):
```markdown
*`第一` = 篮子[^1] * # 基名可省略反引号(`[^` 已标明取元)
*`种` = 分类[^苹果] *
*`第一种苹果` = 货架[^苹果][^1] *
*`亦可用` = `分类`[^苹果] * # 反引号形式并存
```
- **List**:标签须为纯数字(1-based);`[^0]` / 越界 → 报错。
- **Map**:标签为键文本(含 `"00"` 这类数字串键);缺键 → 报错。同一外形按接收值类型分派,不把 map 上的 `[^1]` 当成「第 1 个条目」。
- 基名:`` `名`[^键] `` 与 `` 名[^键] `` 等价;无 `` [^ `` 时裸词仍是**文本字面量**(不是变量)。
- **插值中的取元**:在调用实参值 / 引号字符串里,`` `变量` `` 后**紧跟**(无空白)`` [^…] `` 时按取元解析,而不是字面文本:`> print text=苹果单价:`水果价格`[^苹果]`;链式 `` `货架`[^苹果][^1] `` 同理。`` `变量` [^…] ``(有空白)则 `` [^…] `` 仍是文本。
- 文末 `[^1]: …` 定义块仍是注释,与取元无关。
- foreach:`List` 遍历元素;`Map` 遍历**键**(值用脚注取)。
---
@@ -175,21 +317,19 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致
1. 加载 `index.mq.md` + 导入。
2. Pass1 收集定义。
3. Pass2 执行 `# main`。
4. `*` 语句、`**` 返回、`>` 调用、`+`/`-` 控制流、表绑定按语义执行;`> print` 写 stdout。
4. `*` 语句、`**` 返回、`>` 调用、`1.` 分支、`-` 循环、表绑定按语义执行;`> print` 写 stdout。
---
## 11. 函数体结束(`---` / `***` / 空返回)
无返回值(或已写完副作用)的函数,在体末用分割线收束,避免后续同级语句被吞进嵌套函数:
```markdown
# main
> 问候 谁=World
## 问候
- 谁
+ `谁`
> print text=Hello `谁`!
@@ -198,20 +338,16 @@ v0.1 **推荐**绑定写在斜体语句内,以保持「语句=斜体」一致
| 约定 | 说明 |
|------|------|
| `---` 或 `***` | 函数体**顶层**单独一行(长度 ≥ 3 且全为 `-` 或全为 `*`)→ **结束本函数**;后续语句属于外层 |
| `****` / 空粗体 | 空返回(值为 `None`),并同样结束本函数体 |
| 有值 `**expr**` | 普通返回;**不**自动截断后续兄弟句(仍可用分割线或下一同级/更浅标题收束) |
| Frontmatter | 仅**文件开头**成对 `---` = 元信息;与函数体内结束符消歧 |
| 分支/循环臂内 | 分割线仍可忽略(噪声),不截断外层函数 |
曾设想的「可选框住分支/循环」废止,分割线专用于函数收束。
| `---` 或 `***` | 函数体**顶层**单独一行 → **结束本函数** |
| `****` / 空粗体 | 空返回(`None`),并结束本函数体 |
| Frontmatter | 仅**文件开头**成对 `---` = 元信息 |
---
## 12. v0.1 非目标
## 12. v0.2 非目标
- break/continue、完整错误模型、静态类型、完整 FFI
- 用 `*` 作无序列表符
- `+` 作分支、`+`/`-` 作形参(**不保留**)
---
+220
View File
@@ -0,0 +1,220 @@
# 模块命名空间(import / 点号寻址)
| | |
|---|---|
| 状态 | **Accepted;统一 `import bind:target` 已锁定** |
| 日期 | 2026-08-13 |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [markdown-mapping.md](markdown-mapping.md) · [objects.md](objects.md) · [call-arguments.md](call-arguments.md) · [ext-agent.md](ext-agent.md) |
---
## 1. 动机
加载器曾把每个导入文件的顶层 `#` / `##` **扁平合并**进同一全局函数表;同名则**后导入静默覆盖**。
后果:
- `lib/json` 的 `parse` 与 `lib/time` 的 `parse` 不能共存。
- 官方 ext / 多库编排无法按大型语言习惯书写 `time.parse` / `json.parse`。
- 旧 frontmatter `import path:path.mq.md` 对 Markdown / 编辑器不友好,且与调用标记 `>` 抢外形。
**结论**:模块命名空间 + 点号寻址;frontmatter 导入统一为可读的 `import bind:target`。
---
## 2. 目标与非目标
### 2.1 目标
1. **导入绑定库名**:导入一个 `.mq.md` 得到一个**库(模块)绑定**,成员不倒进全局。
2. **点号寻址调用**:`库.成员`、`库.对象.成员`;`.` 表示定义树寻址。
3. **库名不是变量**:路径段为**裸标识符**,不加反引号。
4. **短名与文件导入同形**:`import fmt:time.format`,废除独立 `use` 关键字。
5. **中英对等**:`import` / `导入`。
### 2.2 非目标
- 第三方包管理 / 版本求解。
- 旧 `> path.mq.md` / `> use` 双轨兼容。
- `` `time`.parse ``(库名加反引号)。
- `import fmt:time.*` 通配。
---
## 3. 核心语义
### 3.1 模块 / 库
| 内容 | 归属 |
|------|------|
| 顶层 `##` 自由函数 | 库根下的**函数** |
| 顶层 `#` 对象 | 库根下的**类型(对象)** |
| 类型下的 `##` 方法 | 该对象节点下的**成员函数** |
| 被导入文件的 `# main` | **不**作为入口执行 |
### 3.2 导入句法(frontmatter)
仍只出现在文件头成对 `---` 内。**调用**仍用 `> print`(不变)。
| 含义 | 英文 | 中文 |
|------|------|------|
| 导入文件 | `import utils:utils.mq.md` | `导入 utils:utils.mq.md` |
| 标准库 | `import json:lib/json.mq.md` | `导入 json:lib/json.mq.md` |
| 短名(成员) | `import fmt:time.format` | `导入 fmt:时间.格式化` |
规则:
- **绑定名必填**,在 `:` 左侧(裸名,无反引号)。
- `:` 右侧 `target`:
- 以 `.mq.md` 结尾 → **文件导入**;
- 否则为 **点号路径**(≥2 段),把该成员绑为本地短名(须先有对应文件导入)。
- 同一文件内绑定名不得冲突(文件库名与短名共用命名空间)→ 硬错误。
- 旧写法 `> ….mq.md`、`> … as …`、`> use …`、`> 使用 …` → **硬错误**,并提示新句法。
### 3.3 废除的旧规则
不再支持:
- 省略绑定名时用文件名茎作库名;
- 导入侧 `as` / `作为`;
- 独立关键字 `use` / `使用`。
### 3.4 调用解析顺序
1. **点号路径 callee**(§4)→ 按段在导入库 / 类型树上寻址。
2. **当前文件**顶层 `#` / `##` 与 frontmatter **短名绑定**。
3. **L0 内置**。
4. **插件注册名**。
5. 否则 → 未知 callee。
---
## 4. 点号寻址(核心外形)
### 4.1 文法
```text
path_callee ::= ident ('.' ident)+
```
### 4.2 二段:`库.成员`
```markdown
---
import time:lib/time.mq.md
import json:lib/json.mq.md
---
# main
*t = > time.now_unix*
*s = > time.format unix=`t` pattern="%Y-%m-%d"*
*obj = > json.parse text={"a":1}*
*a = > json.get value=`obj` key="a"*
> print text=`s`
```
### 4.3 三段:`库.对象.成员`
```markdown
> agent.agent # 库 → 类型:构造
```
实例方法须 `` > `var`.method ``;无接收者的 `库.类型.方法` → 硬错误。
### 4.4 变量 / 实例 vs 库路径(Python 统一命名空间)
| 写法 | 含义 |
|------|------|
| `time.parse` | 库路径(裸名,第一段非变量) |
| `` > `助手`.step `` | 独立 `>` 调用:实例方法(接收者反引号) |
| `*回复 = > 助手.step …*` | `*…*` 段内:若 `助手` 是变量 → 实例方法;否则 → 库路径 |
**统一规则**(与 Python 一致):对裸点号 `a.b`,当 `a` 是当前作用域**局部变量**时解释为**方法调用**(`a` 为接收者);否则解释为**库路径**(`lib.a.b`)。此规则同时应用于树遍历与字节码两后端。
- 在**独立 `>` 调用**中裸词 = 文本,故方法接收者仍须反引号:`` > `助手`.step ``。
- 在 **`*…*` / `**…**` 段内**裸词 = 变量,接收者不加反引号:`*回复 = 助手.step …*`。
### 4.5 短名示例
```markdown
---
import time:lib/time.mq.md
import fmt:time.format
---
# main
*t = > time.now_unix*
*s = > fmt unix=`t` pattern="%Y-%m-%d"*
```
### 4.6 应用侧完整示例
```markdown
---
import time:lib/time.mq.md
import writeback:lib/writeback.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
---
# main
*`助手` = > agent.agent model=… tools=… *
*`out` = > `助手`.step task=… *
*`body` = > json.stringify value=`out` *
> writeback.record value=`body` key=ok
```
---
## 5. 导出面
默认:库内顶层 `#` / `##` 均可被路径访问。本版不引入 `private`。
---
## 6. 与旧行为的关系(破坏性变更)
| 旧 | 新 |
|----|----|
| `import time:lib/time.mq.md` | `import time:lib/time.mq.md` |
| `import t`:lib/time.mq.md | `import t:lib/time.mq.md` |
| `import fmt`:time.format
| 茎名默认库名 | 绑定名始终显式 |
| 扁平合并进全局 | 仅库绑定 + 可选短名 |
不提供旧 `>` 导入过渡开关。
---
## 7. 对分层与 ext 的影响
| 层 | 影响 |
|----|------|
| L0 内置 | 仍为全局短名 |
| L1 / 官方 ext | 经库路径调用;**`ext/**/*.mq.md` 严禁 `host_*`** |
| ABI 插件 | 插件注册表 |
---
## 8. 实现要点
1. frontmatter 只解析 `import` / `导入` 行;右侧分流文件 / 成员。
2. AST 仍用 `Import`(文件)与 `Use`(短名)存储,对外无 `use` 关键字。
3. 金样例:`tests/structure/import/`、`tests/structure/ns/`。
| 阶段 | 内容 |
|------|------|
| M1+M2 | 点号路径 + 短名 — 已落地 |
| **Import 句法** | 统一 `import bind:target` — **本波次** |
---
## 9. 决议摘要
1. 导入 = `import bind:target`(`导入` 等价)。
2. target = `.mq.md` 文件 **或** `库.成员` 点号路径。
3. 调用以裸名点号路径寻址;实例方法用反引号接收者(仅独立 `>` 调用;`*…*`/`**…**` 段内接收者不加反引号)。
4. 裸点号 `a.b`:`a` 为局部变量 → 方法调用,否则 → 库路径(Python 统一命名空间)。
+104
View File
@@ -0,0 +1,104 @@
# Objects(`#`)与函数(`##`+)
| | |
|---|---|
| 状态 | Accepted |
| 日期 | 2026-08-06 |
| 相关 | [markdown-mapping.md](markdown-mapping.md) · [ext-llm.md](ext-llm.md) |
## 1. 约定
| 标题层 | 含义 |
|--------|------|
| `#`(恰好一层) | **对象 / 类型**。正文 = 构造体;调用类型名 = 构造实例。 |
| `##` 及更深 | **函数**(自由函数或方法)。层数差表示嵌套,与 v0.1 相同。 |
`# main` 是**入口对象**:运行文件 = 执行其构造体。若无 `main`,且文件恰好只有一个无参顶层 `#` 对象(如 `# Hello World`),则把它当作入口。
## 2. 实例句柄
构造返回值若为 `map`,运行时写入 `_type`(文本,值为类型名),形成句柄。
方法调用通过 `_type` 找到定义对象,再解析其下的 `##` 方法。
方法体内自动绑定:
- `自`(中文)
- `self`(英文)
二者同一接收者。
## 3. 调用外形
```markdown
# 大模型
+ `模型名`
*自 = …配置 map…*
**自**
## 运行
+ `提示`
…使用 `自` …
**内容**
# main
*模型 = > 大模型 模型名="gpt-4o-mini"*
*回复 = > 模型.运行 提示="你好"*
> print text=`回复`
```
- `> 大模型 …` — 构造
- `` > `模型`.运行 … `` — 方法(接收者 + `.` + 方法名;**独立 `>` 调用**需反引号接收者 `` `模型` ``;**在 `*…*` / `**…**` 段内**接收者不加反引号:`*回复 = > 模型.运行 提示="你好"*`)
- `## 自由函数` 挂在模块顶层(非某对象子标题)— 与旧版顶层 `# http_get` 对等,现写为 `## http_get`
## 4. 标准库
官方 `lib/*.mq.md` 以**顶层自由函数**为主:全部为 `##`(不再使用 `#` 冒充类型)。
真正的类型化扩展(如 `ext/llm`)使用 `# 类型` + `##` 方法。
## 5. 继承(`# 子类 = > 父类`)
```markdown
# Greeter
## hello
+ `who`
*msg = "Hello, `who`!"*
**msg**
# Loud = > Greeter
## hello
+ `who`
*msg = "HELLO, `who`!"*
**msg**
```
| 规则 | 说明 |
|------|------|
| 语法 | `# Child = > Parent`(右侧必须是 `>` + 简单类型名;无路径) |
| `_type` | 构造后仍为**最具体子类名** |
| 方法查找 | 先子类 `##`,未命中再沿基类链;同名则子类覆盖 |
| 构造 | **不**隐式调用父构造(无 auto-super)。需要父字段时在子类正文首行显式 `` `self` = > Parent … ``,再改字段并 `**`self`**`;返回 map 的 `_type` 仍为子类名 |
| 多继承 | 不支持 |
| 诊断 | 未知基类、循环继承、非法 RHS(如 `# Foo = 1`) |
详见 [object-inheritance.md](../roadmap/object-inheritance.md)。
## 6. 非目标(本波)
- 接口 / 可见性 / 多继承
- 无 `_type` 的「鸭子」方法分发
- 用表格声明字段 schema(表格仍表示数据集合;见 [tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md))
## 7. 迁移摘要
| 旧 | 新 |
|----|----|
| 库顶层 `# http_get` | `## http_get` |
| `# main` + `## 嵌套` | 不变(main = 入口对象) |
| `ext` 顶层 `# complete` | `# llm` / `# 大模型` 构造 + `## complete` / `## 运行` |
+482
View File
@@ -0,0 +1,482 @@
# Marqdo 的 OKF 实现
| | |
|---|---|
| 状态 | **Accepted(规范);实现分层见 §10** |
| 日期 | 2026-08-07 |
| 调研 | [okf-and-marqdo.md](../research/okf-and-marqdo.md) |
| 命令现状 | [catalog-cli.md](catalog-cli.md)(v0 已落地) |
| 生成式清单方向 | [generated-yaml-manifest.md](generated-yaml-manifest.md) |
| 智能体消费面 | [ext-agent.md](ext-agent.md) · [ext-agent-plan.md](ext-agent-plan.md) · 任务知识包见本文 §7 |
| 外部规范 | [OKF SPEC v0.2](https://github.com/GoogleCloudPlatform/knowledge-catalog/blob/main/okf/SPEC.md) |
本文是 **Marqdo 语言侧 OKF 实现的详细设计**:界定我们借鉴什么、已经实现什么、下一阶段必须补什么。
**不把 Google OKF 整本照搬进语言语义**;Marqdo 的可执行真相永远是 `.mq.md` 源。
---
## 1. 定位
### 1.1 OKF 是什么(对我们)
[Open Knowledge Format](https://github.com/GoogleCloudPlatform/knowledge-catalog) 用 **目录中的 Markdown + YAML frontmatter** 表示可交换知识:概念一页一文、路径即 ID、链接成图、最小强制面(几乎只强制 `type`),并在 v0.2 加入信任信号。
Marqdo 对齐的判断是:
> 人类可读的 Markdown 可以成为人与 Agent 的一等交换面;**程序本身也应能投影成同一形态的知识包**。
### 1.2 Marqdo 多走的一步
| | OKF(通用知识) | Marqdo |
|--|-----------------|--------|
| 正文 | 自由散文 | **可执行语法**(`.mq.md`) |
| 成功标准 | 互通、可策展、可信任 | 能跑 + 能读 + 可被 Agent 索引 |
| 清单角色 | 知识本身 | **从源派生的投影**(非第二套权威配置) |
一句话:
**OKF 形、Marqdo 义 — 形态对齐 OKF;词汇与生命周期服务模块、依赖、任务技能与信任,而不是 BigQuery 业务概念表。**
### 1.3 三层文档(勿混)
| 层 | 谁写 | 是什么 |
|----|------|--------|
| **源** | 人 / 编码 Agent | `.mq.md`:唯一语义权威,打开即读、即可跑 |
| **工程目录包** | `marqdo catalog` | 模块依赖/导出总览(`Marqdo Module`) |
| **任务知识包** | `plan` 晋升等 | 任务↔技能↔可执行资源(`Marqdo Task` / `Marqdo Agent Skill`) |
`marqdo view output` 出 HTML 站点,与 OKF 包**分工**:人读程序站 vs Agent/工具读知识包。见 [view.md](view.md)、[catalog-cli.md](catalog-cli.md) §4。
---
## 2. 设计原则(锁定)
1. **源为唯一权威** — 依赖、导出、可执行行为以 `.mq.md` 为准;知识包是提取或晋升结果。
2. **生成、可复现** — 同一源树 + 同一工具版本 → 同一工程目录包(时间戳字段可规范化忽略)。
3. **勿手改生成物** — 文件头 / `generated` 标明 GENERATED;手改不被承认为权威。
4. **最小强制面** — 互通只要求:合法 frontmatter、`type` 字段、可解析的 `resource` / 链接;未知 `type` **必须优雅降级**(仍可读正文与已知字段)。
5. **格式而非平台** — 包可 `cat` / `git clone`;不绑定某一云或某一模型。
6. **清单可删可再生** — 无 catalog 时解释器仍能直接从源工作;catalog **不是**语言语义的一部分。
7. **可执行资源显式** — 凡声称「可跑」的概念必须有 `resource:` 指向 `.mq.md`(或等价路径),禁止只靠散文描述冒充程序。
---
## 3. 概念模型
### 3.1 Bundle(知识包)
一个 OKF 风格 bundle 是目录树:
```text
<bundle-root>/
index.md # 可选:人/Agent 总览
log.md # 可选:变更史(策展用)
catalog.yaml # 可选:机器向总清单
concepts/… # 或 modules/…:概念页(frontmatter + Markdown)
resources/… # 可选:被引用的可执行 .mq.md(任务包常用)
```
**Concept ID** = 相对 bundle 根、去掉扩展名的路径(OKF 惯例)。
例:`concepts/tasks/a1b2c3d4e5f6.md` → ID `concepts/tasks/a1b2c3d4e5f6`。
**联系** = frontmatter 中的路径字段 + 正文中的 Markdown 链接,形成可遍历图。
### 3.2 Marqdo 使用的两类 bundle
| Bundle | 默认根 | 生产者 | 消费者 |
|--------|--------|--------|--------|
| **工程目录包** | `.marqdo/`(`-o` 可改) | `marqdo catalog` / `sync` | 人、CI、未来编译加速、通用 Agent |
| **任务知识包** | `.marqdo/agent-kb/` | `ext/ai` 的 `plan` 晋升等 | 父智能体快路径、策展、复用 |
二者词汇共享(`type` / `generated` / `verified` / `status`),目录职责分离:
**不要**把探索用的 `agent-runs/` 时间戳文件当成稳定概念 ID。
---
## 4. Frontmatter 词汇表
### 4.1 所有概念页的公共字段
| 字段 | 必填 | 含义 |
|------|------|------|
| `type` | **是** | 概念类型字符串(见 §5) |
| `title` | 推荐 | 短标题 |
| `description` | 可选 | 一句话说明 |
| `tags` | 可选 | 字符串列表 |
| `resource` | 视类型 | 指向权威源或可执行 `.mq.md` 的相对路径 |
| `status` | 推荐 | `draft` \| `stable` \| `deprecated` |
| `generated` | 生成物必有 | `{ by, at? }` — 谁生成 |
| `verified` | 可选 | `{ by, at? }` — 谁核验(非 LLM 口述) |
| `sources` | 可选 | 出处列表(OKF v0.2) |
| `stale_after` | 可选 | 绝对日期,过期后消费者应降级信任 |
| 未知字段 | — | **保留、不拒绝** |
信任档位(推导,不必单独存字段):
| 条件 | 档位 |
|------|------|
| 无 `verified` | 未验证(机器生成草稿) |
| 有 `verified.by` 为确定性工具(如 `marqdo-agent/spawn`) | 机器确认 |
| 有人工审核约定(未来) | 人工审核 |
### 4.2 工程模块页额外字段(v0 已用)
| 字段 | 含义 |
|------|------|
| `depends` | 导入列表(从源 frontmatter `> path` 提取) |
| `exports` | 顶层 `#` 导出名列表 |
### 4.3 任务 / 技能页额外字段(目标词汇)
| 字段 | 所在 type | 含义 |
|------|-----------|------|
| `skill` | `Marqdo Task` | 指向 Skill 概念页的相对路径 |
| `goal` 或正文中的规范化 goal | `Marqdo Task` | 匹配材料(规范化规则见 §7.3) |
| `llm_free` | `Marqdo Agent Skill` | 资源是否仍含 `agent.step` / LLM 调用(机器启发) |
| `quality` | `Marqdo Agent Skill` | 整数启发分(长度、llm_free 等),**非**模型打分 |
---
## 5. `type` 注册表(Marqdo 义)
未知 type **不得**导致解析失败;工具可跳过专用逻辑,仍展示 title/正文/链接。
| `type` | 状态 | 含义 | 主要生产者 |
|--------|------|------|------------|
| `Marqdo Catalog` | **v0 已实现** | 包总览(`catalog.yaml` / `index.md`) | `marqdo catalog` |
| `Marqdo Module` | **v0 已实现** | 一个 `.mq.md` 模块的投影 | `marqdo catalog` |
| `Marqdo Task` | **规范已定;实现待做** | 一项可匹配的任务意图 | `plan` 晋升 |
| `Marqdo Agent Skill` | **规范已定;实现待做** | 指向可执行工作簿的技能 | `plan` 晋升 |
| 其他 | 开放 | 第三方/未来扩展 | — |
**不**引入 Google OKF 的 `Metric` / BigQuery 表类型作为 Marqdo 核心词汇;需要时可由用户包自行使用,运行时降级。
---
## 6. 工程目录包(v0 — 已实现)
### 6.1 CLI
```bash
marqdo catalog [PATH] -o OUT_DIR
marqdo sync [PATH] -o OUT_DIR # 别名
```
| 参数 | 默认 | 说明 |
|------|------|------|
| `PATH` | `.` | 工程根或单文件;目录则递归 `*.mq.md` |
| `-o` | `.marqdo` | 输出根;写入前创建,**覆盖**同名生成文件 |
实现:[`src/catalog.rs`](../../src/catalog.rs)。金样:`tests/gold.rs` → `catalog_writes_yaml`、`catalog_includes_agent_kb_concepts`。
### 6.2 生成物布局
```text
OUT_DIR/
catalog.yaml
index.md
modules/
<path-with-__>.md
concepts/ # O3:从 **/.marqdo/agent-kb/concepts/ 复制
tasks/…
skills/…
```
路径拍扁:`structure/import/main.mq.md` → `modules/structure__import__main.md`。
`agent-kb` 下的可执行 `.mq.md` **不**进 Module 表(避免与概念/资源重复);Task/Skill 概念页进 `concepts/` 与 `catalog.yaml` 的 `concepts:`。
### 6.3 `catalog.yaml`(现行字段)
```yaml
# GENERATED by marqdo — do not edit by hand
type: Marqdo Catalog
title: marqdo-project
generated:
by: marqdo/<crate-version>
modules:
- id: structure/hello # resource 去掉 .mq.md
resource: structure/hello.mq.md
title: … # 源 frontmatter title,否则用路径
imports: [] # 或 ["lib/x.mq.md as x", …]
exports:
- name: Hello World
kind: fn
# 可选(源 frontmatter 有则透传):
# verified: { by: … }
# sources: […]
concepts: [] # 或 Task/Skill 条目(O3)
# - id: concepts/tasks/<sig>
# type: Marqdo Task
# title: …
# status: …
# page: concepts/tasks/<sig>.md
# resource: …
# skill: …
```
提取规则:
- **imports**:源文件 YAML frontmatter 中以 `>` 开头的导入行(经 `parse_import_spec`)。
- **exports**:解析成功则用 AST 顶层函数名;否则回退扫描 `# ` 标题行。
- **verified / sources**:源 frontmatter 有则写入 module/concept 条目(O3)。
- **concepts**:扫描 `**/.marqdo/agent-kb/concepts/**/*.md`,复制到 `OUT_DIR/concepts/`。
- **不**提取正文 `>` 动态调用图、不写锁哈希、不写跨仓 URL。
### 6.4 模块概念页(现行)
```yaml
---
type: Marqdo Module
title: …
resource: path/to/file.mq.md
depends: […]
exports: […]
generated:
by: marqdo/<version>
# verified / sources:源有则透传
---
```
正文含「勿手改」、**可点击依赖链接**(解析到同包其它 Module 页)、导出表。`index.md` 含 Modules 表与 **Agent knowledge** 节(链到 `concepts/`)。
### 6.5 仍相对完整 OKF 愿景的缺口
| 缺口 | 说明 |
|------|------|
| 无通用 Concept ID 遍历 API | catalog 为生成物;无独立查询命令 |
| 无 `stale_after` / Attested 再现 | 信任信号仅可选 `verified`/`sources` |
| 无 `log.md` | 无策展历史(O4) |
| 运行时不读 catalog | 解释器不依赖生成物(有意为之) |
O2/O3 已补:Task/Skill 知识包、catalog 扫入 agent-kb、模块页可点依赖、可选信任字段。
---
## 7. 任务知识包(规范 — 实现路线 O2)
服务「父智能体优化过的工作簿,同任务应直接执行」:把子 Marqdo / 技能登记为 OKF 概念,用 ID 与链接匹配,而不是私有 `index.json`。
### 7.1 布局(锁定)
```text
.marqdo/
agent-runs/workbook-<slug>-<ts>.mq.md # 仅当显式 workbook_dir= 时(可 gc)
agent-kb/ # 任务知识包 bundle(默认首次 plan 就写这里)
index.md
log.md # 可选
catalog.yaml # 可选;可由 promote 或 catalog 刷新
concepts/
tasks/<slug>.md # type: Marqdo Task;sig 在 frontmatter
skills/<slug>.md # type: Marqdo Agent Skill
resources/
<slug>.mq.md # 默认可执行工作簿(探索与晋升同一路径)
```
默认根可通过 `plan` 参数 `kb_dir` / `知识库目录` 覆盖。`.gitignore` 已忽略 `**/.marqdo/`。
路径用可读 **slug**(由 goal 派生:拉丁小写、CJK 保留、其它变 `-`,最长约 48 字符)。**`sig` 仅写在 frontmatter**,用于精确匹配。同 slug 异 sig 时用 `slug-<sig前4位>`。旧包若仍以 `<sig>` 为文件名,lookup 会回退识别。
### 7.2 概念页模板
**Task**(匹配入口):
```yaml
---
type: Marqdo Task
title: <短摘要>
description: <规范化 goal>
sig: <12hex>
status: stable
tags: [agent-task]
skill: ../skills/<slug>.md
generated:
by: marqdo-agent/plan
verified:
by: marqdo-agent/spawn
at: <ISO8601>
---
# Task
See [skill](../skills/<slug>.md).
```
**Skill**(可执行绑定):
```yaml
---
type: Marqdo Agent Skill
title: <短名>
sig: <12hex>
resource: ../../resources/<slug>.mq.md
status: stable | candidate
llm_free: true | false
quality: <int>
hits: <int>
generated:
by: marqdo-agent/plan
at: <ISO8601>
verified:
by: marqdo-agent/spawn
at: <ISO8601>
---
# Skill
Prefer spawning `resource` over re-planning.
```
`status`:`llm_free` 的 resource 晋升为 **stable**(零父 LLM 快路径);否则为 **candidate**(可复用,但按 `improve_every` 偶发再优化,每轮最多 1 次改进)。失败运行不晋升;质量更差不覆盖。
### 7.3 任务签名 → Concept 路径
材料:
1. `goal`:Unicode NFC → trim → 连续空白折叠为单空格。
2. 若调用方工具表非空:工具名排序后追加进材料。
3. **不**把父 `standing` 计入签名(易变导致永不命中)。
输出:稳定短哈希 `sig`(`agent_goal_sig`)+ 可读 `slug`(`agent_goal_slug`)。路径:
- `concepts/tasks/<slug>.md`
- `concepts/skills/<slug>.md`
- `resources/<slug>.mq.md`
匹配顺序:
1. **精确**:slug 试探 + frontmatter `sig` → 扫目录 `sig:` → 旧 hex 文件名。
2. **别名(Accepted)**:精确 miss 后,扫 Task FM `aliases:`(YAML 列表或 `[a, b]`);`normalize_goal(query)` 与某条 alias **精确相等**则命中同一 Skill/resource。lookup 返回 `match: exact|alias`;`plan` 对 alias 写 `cache=soft-hit`。
3. **规范句(Accepted)**:仍 miss 时对 goal 做轻量 `agent_kb_canonicalize`(剥站立前缀、去尾标点),再精确/别名各试一次;命中返回 `match: canonical`,`cache=soft-hit`。
4. **近义(Accepted,默认开)**:仍 miss 且 `near_match=True` 时,对 Task `title|description|aliases` 做本地**字符 bigram 词袋 + 余弦**;`best.score >= near_threshold`(默认 `0.78`)则 `match: near` 并带 `score`,`cache=soft-hit`,并可 `agent_kb_add_alias`。这是稀疏词法近邻,**不是** embedding 模型。
5. **父裁决 soft_match(Accepted,默认关)**:仍 miss 且 `plan soft_match=True` 时,把 `agent_kb_near_match` 排序候选(含 score;空则退回 `list_tasks`)交给父模型:`DECISION: REUSE` + `SLUG:` 或 `DECISION: NEW`;REUSE 后可 `agent_kb_add_alias`。
6. **不做**默认 dense embedding / 远程向量库。远期 dense 仍见 [okf-near-match.md](../roadmap/okf-near-match.md) E。
`agent_kb_promote` 可选 `aliases=`(字符串或列表)写入 Task;再晋升时合并既有 aliases。
### 7.4 与 `## plan` 的契约
| 参数 | 默认 | 含义 |
|------|------|------|
| `reuse` / `复用` | `True` | 允许知识包快路径 |
| `optimize` / `优化` | `False` | 跳过知识包,强制再规划 |
| `force` / `强制` | `False` | 忽略知识包 |
| `soft_match` / `软命中` | `False` | miss 后父裁决 REUSE/NEW(须显式打开;候选为 near 排序列表) |
| `near_match` / `近义命中` | `True` | lookup 第四趟本地 n-gram;`False` 关闭 |
| `near_threshold` / `近义阈值` | `0.78` | near 自动命中最低余弦分 |
| `promote` / `晋升` | `True` | DONE 后固化并写入/更新概念与 resource |
| `kb_dir` / `知识库目录` | `.marqdo/agent-kb` | bundle 根 |
| `workbook_dir` / `工作簿目录` | `None` | 默认直接写 `kb_dir/resources/<slug>.mq.md`;显式传入则用该目录下的临时 `workbook-<slug>-<ts>.mq.md` |
| `improve_every` / `改进周期` | `3` | candidate 每 N 次命中触发 ≤1 轮改进 |
| `explore_n` / `探索次数` | `3` | 同任务已有文件数 `< N` 且非 `llm_free` 时,强制新建 `explore/<slug>/<k>.mq.md` 尝试不同路径(第 2 次默认 dual 骨架) |
调用示例(路径可直接写在参数里,无需 `json.parse`):
```markdown
> `助手`.plan goal=… max_rounds=3
> `助手`.plan goal=… workbook_dir=".marqdo/agent-runs"
> `助手`.plan goal=… explore_n=3
```
快路径:
1. lookup 命中且 resource **llm_free**(含现场检测已固化源)→ spawn → `cache=hit`,**父 LLM 不调用**。
2. 否则若任务相关文件数 `< explore_n` → 写入新的 explore 变体,父 LLM 被提示尝试不同路径;成功则固化并晋升。
3. 否则走 candidate 命中 / `improve_every` 改进逻辑。
`DECISION: DONE` 时先 `agent_workbook_solidify`(把仍含 `worker.step` 的簿固化为 `# main` **返回**答案,而非仅 `print`),再晋升并写 `verified`。
显式 `workbook=` 续跑优先于知识包查找。
质量启发(覆盖 skill 时,不调模型):`llm_free` 优先;源更短优先;同质取较新。更差 `quality` 不覆盖现 skill。
### 7.5 自我成长如何落在 OKF 上
| 能力 | 机制 |
|------|------|
| 优化 | 规划循环固化代码 → 更优 `resources/<slug>.mq.md` |
| 迭代 | 同 Concept slug/`sig` 覆盖 resource + 刷新 `generated`/`verified` |
| 成长 | 命中快路径;`candidate`/`hits`/`improve_every` 驱动再优化;`log.md` 可审计 |
| 分发 | 整包 `agent-kb/` 可复制(格式即契约) |
---
## 8. 运行时与工具职责
| 组件 | 读 OKF? | 写 OKF? | 备注 |
|------|----------|----------|------|
| 解释器 / 字节码 VM | 否(语义) | 否 | 只跑 `.mq.md` |
| `marqdo catalog` | — | 工程目录包 | v0 |
| `plugins/agent`(`agent_kb_*`)+ `ext/ai` `plan` | 任务包 | 晋升时写任务包 | O2;**不**进核心 `src/host` |
| `lib/fs` | 通用文件 | 通用文件 | L1 包装 |
| `marqdo view` | 否 | 否 | HTML 另一轨 |
| 未来 `marqdo kb query` | 是 | 否 | 可选:按 type/tag/链接查询 |
agent-kb 运行时实现归属 **agent 插件**(`agent_goal_sig` / `agent_kb_lookup` / `agent_kb_promote` / `agent_kb_record_hit` / `agent_workbook_solidify` / `agent_kb_task_files`),由 `ext/ai/agent` 调用;禁止把这些原语加回 `HostFn`。
解释器**不得**因缺少 catalog 而拒绝运行源文件。
---
## 9. 安全与边界
| 风险 | 对策 |
|------|------|
| 把生成物当配置手改 | 文档 + GENERATED 头;CI 可选校验 |
| 错误技能被复用 | 快路径必 spawn+inspect;失败标 `draft` 并重规划 |
| 签名过宽 | tools 指纹;文档强调 exact goal |
| 密钥进入知识包 | 继承 env;禁止把 key 写入 resource/概念正文 |
| 包膨胀 | runs 与 kb 分离;仅 DONE 晋升 |
| 与语言语义耦合 | catalog/kb 失败不影响 `marqdo run` 源文件 |
---
## 10. 实现路线
| 阶段 | 内容 | 状态 |
|------|------|------|
| **O0** | 调研 + 生成式清单方向 + `.mq.md` 后缀 | **done** |
| **O1** | `marqdo catalog` / `sync`:Module + Catalog YAML | **done**(v0) |
| **O2** | 本文锁定的任务知识包:`Marqdo Task` / `Agent Skill`;`plan` reuse/promote | **done**(host kb_* + plan 快路径) |
| **O3** | catalog 增强:`verified`/`sources` 可选;模块页可点击依赖;扫入 `agent-kb` 概念供人浏览 | **done** |
| **O4** | `log.md` 策展、可选 `kb query`、Attested-style「再现跑通」收据(非 BigQuery) | 远期 |
| **O5** | 相近任务软命中:aliases + canonicalize + 本地 n-gram `near` + `soft_match` 父裁决已落地;dense embedding 仍见 [okf-near-match.md](../roadmap/okf-near-match.md) E | **A/B/C/D-near done** |
O2 设计落盘后,智能体侧实现文档可薄化为指向本文 §7,避免两套真理。
---
## 11. 非目标
- 在 Marqdo 内核实现完整 OKF 验证器产品或云托管知识库。
- 用 OKF 清单替代模块命名空间 / 导入语义([module-namespace.md](module-namespace.md))。
- 强制用户提交 `.marqdo/` 进 git。
- **默认**语义相似检索 / 向量库(可选软命中见 O5 / [okf-near-match.md](../roadmap/okf-near-match.md);不进内核)。
- 跨仓技能市场(可后续在概念图上扩展)。
- 照搬 OKF `Attested Computation` 的 BigQuery executor 模型。
---
## 12. 与既有文档的关系
| 文档 | 关系 |
|------|------|
| [okf-and-marqdo.md](../research/okf-and-marqdo.md) | 调研;产业背景与借鉴边界 |
| [generated-yaml-manifest.md](generated-yaml-manifest.md) | 早期「生成式清单」方向;**词汇与原则并入本文,命令细节见 catalog-cli** |
| [catalog-cli.md](catalog-cli.md) | O1 CLI 与 v0 落盘的操作说明 |
| [ext-agent-plan.md](ext-agent-plan.md) | 多步执行;缓存/复用应引用本文 §7 |
| [ext-agent.md](ext-agent.md) | 框架总览;自写回 ≠ 跨调用 OKF 知识包 |
---
## 13. 决议摘要
1. Marqdo 的 OKF 实现 = **形态对齐 + Marqdo 类型词汇 + 生成/晋升管道**,不是语言换皮。
2. **O1–O3 已落地**(工程目录包、任务知识包、catalog 扫入 agent-kb + 人读链接图);**O4** 策展/查询为远期。
3. 可执行真相是 `.mq.md`;概念页负责**寻址、信任与联系**——人与 Agent 都是闭环里的一环。
4. 父智能体复用优化结果,应走 **Task → Skill → resource → spawn**,而不是私有 JSON 缓存主路径。
5. 未知 `type` 降级;无清单亦可运行源码。
---
## 14. 一句话
**Marqdo 用 OKF 风格的知识包索引程序与任务技能:源负责跑,概念负责找与信,catalog 与 agent-kb 分管工程目录与自我成长。**
+8 -6
View File
@@ -23,19 +23,21 @@ marqdo dump FILE --stage lines|tokens|ast|sema|all
| 标志 | 阶段 | 输出内容 |
|------|------|----------|
| `--dump-lines` | 行分类 | 每行:`LINE kind=Comment\|Code\|Blank` + 原文预览 |
| `--dump-lines` | 行分类 | 每行:`kind=Comment\|Code\|Blank` + 原文;v0.3 行内位 `[decl n]` / `[bold …]` / `[italic …]` |
| `--dump-tokens` | 词法 | Token 流:`type lexeme line:col` |
| `--dump-ast` | 语法 | S 表达式或缩进树(模块/函数/语句) |
| `--dump-ast` | 语法 | 模块/函数/语句;形参带 `inferred`;叙述死绑定 `dead=[…]` |
| `--dump-sema` | 语义 | 作用域、导入图、提升后的符号表 |
| `--trace-eval` | 求值 | 进入/离开函数、绑定、分支臂选择、`print` 调用 |
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(见 [bytecode.md](bytecode.md)) |
| `--trace-eval` | 求值 | **JSON 行**(stderr):语句级事件,含 `path` / `span`(`line:col`) |
| `--dump-bytecode` | 字节码 | 反汇编 `Program`(指令旁带 `@line:col`;见 [bytecode.md](bytecode.md)) |
| `--backend tree\|bytecode` | 执行后端 | 默认 `tree`;`bytecode` 走栈式 VM |
| `--dump-all` | 以上全部 | 按管道顺序打印,段之间用横幅分隔 |
格式约定:
- 人类可读优先;段首统一:`=== marqdo: <stage> ===`
- 可选 `--dump-format=text|json`(json 后置,text 先做)
- dump 人类可读优先;段首统一:`=== marqdo: <stage> ===`
- `--trace-eval`:每条事件一行 JSON,例如
`{"event":"stmt","path":"…","span":"5:1","kind":"call","callee":"print"}`
树遍历:`enter_fn` / `stmt` / `leave_fn`;字节码:`op`(`print`/`input`/`call`/`return`)。
- 有 dump 时:若求值未实现,仍打印已实现阶段再以非 0 退出(便于 M1 只测 lines)
---
+21 -3
View File
@@ -2,18 +2,36 @@
| | |
|---|---|
| 状态 | 已决议(并入 mapping v0.1 + keywords;2026-08-04 修订函数收束) |
| 状态 | **v0.2 已决议**(现行实现);**v0.3 拟对调 `*` / `**` 角色**(见下) |
| 日期 | 2026-08-04 |
| 修订 | 2026-09-13:挂接 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) |
---
## 决议
## 决议(v0.2 · 现行)
1. **`*…*` = 程序语句**。
2. **`**…**` = 返回值**(架构级);空粗体 `****` / `** **` = 空返回(`None`)并结束函数体。
3. **输出**用内置函数 **`print`**(英文),不是粗体,不是中文名。
4. **`---` / `***`(函数体顶层)**:结束本函数体(无返回值函数收束);**不是**分支/循环装饰框。
4. **`---` / `***`**:Markdown 叙述分隔(跳过);**不再**结束函数体。无值收束用 `*None*` / 整行 `**` / `****`(见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md) §7.2)。
5. **成段注释**:空行分段;段内续行不因首字符升级为代码。
6. **否决**:无标记行 = 默认代码。
详见 [keywords.md](keywords.md)、[markdown-mapping.md](markdown-mapping.md)、[code-vs-comment.md](code-vs-comment.md)。
---
## v0.3 意向(Proposed · 未实现)
产品方重新审视后,拟在 [ADR 0005](../adr/0005-prose-unified-markup.md) 下**对调**架构标记,并放宽叙述面:
| 概念 | v0.2 | v0.3 草案 |
|------|------|-----------|
| 代码段 / 语句 | `*…*` | `**…**` |
| 返回值 | `**…**` | `*…*` |
| 空返回 | `****` / 空粗体;或 `---` | **推荐 `*None*`/`*无*`**;整行 `**`;兼容 `****`;`---` 仅叙述 |
| 输出 | 仍为 `print` / `打印` | 不变 |
| 无标记 = 默认代码 | 否决 | **仍否决** |
| 叙述中 `` `名` `` | 通常无绑定义 | 一律变量;未使用 OK;升参需可执行面读取 |
完整规则与迁移见 [markdown-mapping-v0.3.md](markdown-mapping-v0.3.md)。**v0.3 已为运行时;本文件历史决议中「`---` 收束」已废止。**
+29
View File
@@ -0,0 +1,29 @@
# `lib/csv` — 逗号表(Mid M4)
| | |
|---|---|
| 状态 | **已落地(M4)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-text-mid.md](stdlib-text-mid.md) · [stdlib-mid.md](stdlib-mid.md) |
| 导入 | `lib/csv.mq.md` · `lib/逗号表.mq.md` |
| Host | `host_csv_*`(RFC4180 最小集,无第三方 crate) |
---
## 1. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `parse` | `解析` | `text` | **list of maps**:首行为表头 |
| `stringify` | `序列化` | `rows` | CSV 文本(表头 = 首行 map 的键顺序) |
## 2. 方言(v1)
- 分隔符 `,`;引号 `"`;`""` 转义。
- 换行 `\n` / `\r\n`;忽略末尾空行。
- 字段内可含逗号与换行(须加引号)。
- **不**支持自定义分隔符 / 无表头模式(可后续加)。
## 3. 刻意不做
流式大文件、类型推断、Excel 方言。
+40
View File
@@ -0,0 +1,40 @@
# 设计:`lib/datetime` / `lib/日期时间`(Mid2 M7)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §2.1 |
| 宿主 | `src/host/datetime.rs` · `host_datetime_*` |
---
## 1. 时刻形状
每次返回 **map**:
| 键 | 含义 |
|----|------|
| `unix` | 秒级 Unix 戳(int) |
| `zone` | 固定偏移文本,如 `+08:00` / `+00:00` |
| `iso` | RFC3339(秒精度) |
`to_unix` 也接受裸 int 或 ISO 文本。
## 2. API
| EN | ZH | 说明 |
|----|-----|------|
| `now` | `现在` | UTC 此刻(wasm 无时钟桥则失败) |
| `from_unix` | `自戳` | `unix` + 可选 `zone` |
| `to_unix` | `成戳` | |
| `parse` | `解析` | 默认 RFC3339 / `YYYY-MM-DD[ HH:MM:SS]`;`pattern=` |
| `format` | `格式化` | `rfc3339`/`date`/`time` 或 strftime |
| `add` | `加` | `days`/`hours`/`minutes`/`seconds` |
| `in_zone` | `时区` | 同瞬间换区 |
**区名**:`+HH:MM` / `UTC` / `Z`,以及少量固定偏移别名(如 `Asia/Shanghai`)。**不做**完整 tzdb / DST。
## 3. 与 `lib/time`
`lib/time` 保留极简 unix/format/parse/sleep。日历语义用本库。
+32
View File
@@ -0,0 +1,32 @@
# `lib/encoding` — 编解码(Mid M1)
| | |
|---|---|
| 状态 | **已落地(M1)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [stdlib-re.md](stdlib-re.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
| 导入 | `lib/encoding.mq.md` · `lib/编码.mq.md` |
| Host | `host_encoding_*`(无第三方 crate:标准 Base64 / hex) |
---
## 1. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `base64_encode` | `基64编码` | `text` | 文本(UTF-8 字节 → 标准 Base64,含 `=` 填充) |
| `base64_decode` | `基64解码` | `text` | 文本(解码后须为合法 UTF-8) |
| `hex_encode` | `十六进制编码` | `text` | 小写 hex |
| `hex_decode` | `十六进制解码` | `text` | 文本(偶数字节;合法 UTF-8) |
## 2. 与 `net.url_encode` 的边界
| 能力 | 归属 |
|------|------|
| `application/x-www-form-urlencoded` 风格 | `net.url_encode` |
| Base64 / hex | **本库** |
| 百分号编解码通用版 | 可日后加 `encoding.percent_*`;本波不做 |
## 3. 刻意不做(v1)
URL-safe Base64 变体开关、忽略空白的宽松解码、二进制 `bytes` 类型(仍经 UTF-8 文本往返)。
+49
View File
@@ -0,0 +1,49 @@
# 外联 / 胶水标准库
| | |
|---|---|
| 状态 | **已落地(v1)** |
| 日期 | 2026-08-06 |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-math.md](stdlib-math.md)(公式同构绑定) |
---
## 1. 原则
**导入即用**:`lib/foreign` / `lib/外联`。解释器来自用户本机(PATH / `set_cmd` / `MARQDO_FOREIGN_*`)。live view 可点 Run;静态导出展示源码,Run 禁用。
---
## 2. 绑定语法(与公式同构)
```markdown
`hi` =
```python
print("hello")
```
*`out` = > run code=`hi` *
```
得到运行时类型 **`code`**(`lang` + `source`)。未绑定的 \`\`\` 围栏仍是叙述注释。
曾用的 \`\`\`python name=hi **已移除**。
---
## 3. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `set_cmd` | `设置命令` | `lang`, `cmd` | None |
| `run` | `运行` | `code`(code 值) | 文本 stdout |
| `run_lang` | `按语言运行` | `lang`, `source` | 文本 |
| `langs` | `语言表` | | 列表 |
live view:Structure 中 code 卡片带命令框 + Run → `POST /api/foreign-run`。
---
## 4. 一句话
**`name` = + \`\`\`lang 围栏 → code 值;显式 run;本机解释器可配置。**
+24
View File
@@ -0,0 +1,24 @@
# `lib/fs` 加厚 — 复制 / 移动 / 临时文件(Mid M2)
| | |
|---|---|
| 状态 | **已落地(M2)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-path.md](stdlib-path.md) · [stdlib-mid.md](stdlib-mid.md) |
| 边界 | **文本与普通文件**;不引入 `bytes` 类型(`read_bytes` 延后) |
---
## 1. 新增 API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `copy_file` | `复制文件` | `src`, `dest` | `None`(覆盖已存在的目标文件) |
| `move` | `移动` | `src`, `dest` | `None`(rename;跨设备失败则报错) |
| `make_temp` | `建临时` | 可选 `prefix` | 相对 `cwd`/`fs_root` 的新空文件路径文本 |
均走现有 `resolve_path` 沙箱;写操作受 `fs_write` 策略约束。
## 2. 刻意不做
目录树 `copy_tree`、原子替换、`read_bytes`、权限 chmod。
+25
View File
@@ -0,0 +1,25 @@
# 设计:`lib/fs` Mid2 加厚(M9)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §4 · [stdlib-fs-mid.md](stdlib-fs-mid.md)(M2) |
| 宿主 | `src/host/fs.rs` · `host_make_dirs` / `host_remove_tree` / `host_stat` / `host_walk` |
---
## API
| EN | ZH | 行为 |
|----|-----|------|
| `make_dirs` | `建目录树` | 递归创建(与既有 `make_dir` 同为 `create_dir_all`;显式命名) |
| `remove_tree` | `删目录树` | 仅删目录树;路径为文件则报错 |
| `stat` | `状态` | `{size, mtime_unix, is_file, is_dir}` |
| `walk` | `遍历` | **深度优先**;相对路径列表(正斜杠);含目录项;同级按名排序 |
既有 `remove` 对目录仍递归删除;`remove_tree` 拒绝文件,语义更窄。
## 刻意不做
ACL、watch、硬链接、`copy_tree`、惰性迭代器协议。
+26
View File
@@ -0,0 +1,26 @@
# `lib/hash` — 摘要与 HMAC(Mid M3)
| | |
|---|---|
| 状态 | **已落地(M3)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [stdlib-secrets.md](stdlib-secrets.md) |
| 导入 | `lib/hash.mq.md` · `lib/哈希.mq.md` |
| Host | `host_hash_*`(`sha2` / `sha1` / `md-5` / `hmac`) |
---
## 1. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `sha256` | `哈希256` | `text` | 小写 hex |
| `sha1` | `哈希1` | `text` | 小写 hex |
| `md5` | `md5` | `text` | 小写 hex |
| `hmac_sha256` | `密钥哈希256` | `key`, `text` | 小写 hex |
输入按 **UTF-8 字节**摘要。文档标明:用于完整性标识 / 缓存键,**不是**密码存储(无 Argon2/bcrypt)。
## 2. 刻意不做
密码哈希、流式大文件哈希 API、非 UTF-8 二进制类型。
+19
View File
@@ -0,0 +1,19 @@
# 设计:`lib/html` / `lib/超文本`(Mid2 M8)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §3.2 |
| 宿主 | `src/host/html_ops.rs` · `host_html_escape` / `host_html_unescape` |
---
## API
| EN | ZH | 行为 |
|----|-----|------|
| `escape` | `转义` | `& < > " '` → 实体(`'` → `&#x27;`) |
| `unescape` | `还原` | 上述实体(含 `&#39;` / `&apos;`) |
**不做** DOM / 模板引擎。
+146
View File
@@ -0,0 +1,146 @@
# 标准库多语言命名(草案)
| | |
|---|---|
| 状态 | **草案(先文档、后实现)** |
| 日期 | 2026-08-04 |
| 原则 | **不指定语言**;靠**库文件名**区分中英(及日后其它语言) |
| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [keywords.md](keywords.md) · [keywords-i18n.md](keywords-i18n.md) · [user-site.md](user-site.md) |
---
## 1. 要解决什么
- 内置(解释器里的名字)必须**少而精**;更多能力放进可 `>` 导入的标准库。
- 标准库需要**中英两套 API**(函数名不同),并方便以后再加日文、西班牙文等。
- **不要**用 frontmatter `lang:`、环境变量默认语言、或「同一导入路径再解析语言」——那是负累,也不符合「文档即代码」的直观性。
---
## 2. 方案(采用)
**导入哪个库文件,就用哪套函数名。**
文件名本身表达语言;解释器只做路径解析,不做语言推断。
### 2.1 推荐:库名用目标语言书写
| 导入 | 库内函数名(示例) |
|------|-------------------|
| `import text:lib/text.mq.md` | `trim` · `split` · `join` |
| `导入 文本:lib/文本.mq.md` | `去空白` · `拆分` · `拼接` |
| `import table:lib/table.mq.md` | `put` · `rows` · `row_at` · list/map(见 [stdlib-table.md](stdlib-table.md)) |
| `导入 表:lib/表.mq.md` | `行数` · `取行` |
示例:
```markdown
---
import text:lib/text.mq.md
---
# main
*`xs` = > split value=a,b,c sep=,*
```
```markdown
---
导入 文本:lib/文本.mq.md
---
# main
*`xs` = > 拆分 s=a,b,c sep=,*
```
读者看到导入路径就能知道后面该用英文还是中文函数名——**无需再声明语言**。
### 2.2 可选:同概念用后缀区分(同目录、同「概念」)
若希望「同一概念」在文件名上仍共享拉丁词根,可用:
| 导入 | 含义 |
|------|------|
| `import text-en:lib/text-en.mq.md` | 英文 API |
| `import text-zh:lib/text-zh.mq.md` | 中文 API |
这与 §2.1 **等价可选**,不是第二套解析器:仍然是「写哪个路径就加载哪个文件」。
**优先推荐 §2.1**(`text` / `文本`),后缀形式留给需要 ASCII-only 路径的环境。
### 2.3 明确不做
| 不做 | 原因 |
|------|------|
| `lang: zh` / `MARQDO_LANG` | 隐式状态,难读、难测 |
| `> std/text` 再按语言展开 | 多一次魔法 |
| 同一文件内中英函数双份导出 | 遮蔽与文档混乱 |
| 强制用户只许用中文或只许用英文 | Marqdo 本就多语言友好 |
---
## 2.4 特例:JSON
`JSON` 为专有缩写,**不强求**中文库名或中文 API 翻译。官方只提供:
```text
lib/json.mq.md # 中英文档均 `import json:lib/json.mq.md`;函数 parse / stringify / get / keys
```
不设 `lib/数据.mq.md` 等平行文件。其余模块仍遵守 §2.1。详见 [stdlib-modules.md](stdlib-modules.md) §3.4。
---
## 3. 与「少而精内置」的边界
| 层 | 内容 | 如何获得 |
|----|------|----------|
| **内置(L0)** | 极少:`print` `input` `len` `str` `int`(及语言字面量关键字) | 直接调用,无需导入 |
| **标准库(L1)** | 文本/表等扩展 API;**通常**中英各一套文件、各一套函数名(**JSON 例外**:仅 `lib/json.mq.md`) | frontmatter `import …:lib/…` |
| **宿主原语(实现细节)** | 若 `trim`/`split` 等暂由解释器实现 | 仅供标准库包装调用;**文档与用户站引导走 L1**,不鼓励当「关键字」堆砌 |
日后若某能力足够「核心」,可再升格为 L0;升格前先留在 L1。
---
## 4. 目录与扩展约定
```text
lib/
text.mq.md / 文本.mq.md
table.mq.md / 表.mq.md
# 本波:fs/文件 · sys/系统 · time/时间 · json(中英同文件)· net/网络
# 暂缓:math/数学 · foreign/外联
# 其它语言:texte.mq.md / テキスト.mq.md …
```
扩展新语言时:
1. **新加一个库文件**(文件名用该语言或 `概念-xx`)。
2. 库内函数名用该语言习惯。
3. 文档表增加一行映射;**无需改解释器语言开关**。
导入解析仍沿用现有规则:相对路径 → 官方 `lib/` 根(`MARQDO_LIB` / 工作区 `lib/` 等),**不增加语言分支**。
---
## 5. 文档与示例义务
- 用户站:英/中库各一页(或同页两小节),导入路径与调用名并排;**JSON** 可共用一页、同一导入。
- 金样例:分文件模块中英导入至少各一条;JSON 测 `lib/json.mq.md` 即可。
- [keywords.md](keywords.md) 只列 L0;L1 指向本文 + [stdlib.md](stdlib.md) + [stdlib-modules.md](stdlib-modules.md)。
---
## 6. 实现备忘(暂不开发)
实现阶段仅需:
1. 落地 `lib/text.mq.md` 与 `lib/文本.mq.md`(及 table / 表)两套文件与函数名。
2. 更新导入示例与金样例;删除「仅中文库名」的单轨示例。
3. **不要**实现 `lang:`、默认语言、或 `std/text` 自动选语言。
若历史上加过 `Module.lang` / `lang:` 解析,应撤回,与本草案对齐。
---
## 7. 一句话
**标准库用文件名区分语言(导入即选择);JSON 为缩写特例,中英共用 `lib/json.mq.md`——无语言开关。**
+36
View File
@@ -0,0 +1,36 @@
# `lib/table` 集合加厚 + `lib/cli`(Mid M5)
| | |
|---|---|
| 状态 | **已落地(M5)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
| 集合 | 加厚现有 `lib/table` / `lib/表`(不另开 `listx`) |
| CLI | `lib/cli.mq.md` / `lib/命令行.mq.md` |
---
## 1. 集合新增
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `sort` | `排序` | `list` | 升序列表(int/num/text 优先;其它按显示文本) |
| `sort_by` | `按键排序` | `list`, `key` | 对 **map 列表**按键值排序 |
| `unique` | `去重` | `list` | 保序去重 |
| `chunk` | `分块` | `list`, `size` | 列表的列表 |
| `zip` | `拉链` | `a`, `b` | `[[a0,b0], …]`(取较短长度) |
| `flatten` | `展平` | `list` | 一层展平 |
`reverse` 已有。
## 2. CLI
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `parse` | `解析` | 可选 `args` | map:`--k v` / `--k=v` → 文本;裸 `--flag` → `True`;位置参 → 键 `_` 列表 |
`args` 缺省时用 `sys.args`(经宿主 `argv`)。
## 3. 刻意不做
稳定自定义比较器、惰性迭代器、完整 argparse 互斥组。
+30
View File
@@ -0,0 +1,30 @@
# `lib/log` + `lib/uuid`(Mid M6)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
---
## 1. 日志 `lib/log` / `lib/日志`
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `set_level` | `设级别` | `level`(`debug`/`info`/`warn`/`error`) | `None` |
| `debug` / `info` / `warn` / `error` | `调试` / `信息` / `警告` / `错误` | `text` | 达级别则 `print` 一行 `LEVEL message`;否则无输出 |
默认级别:`info`(隐藏 `debug`)。中文级别别名:`调试`/`信息`/`警告`/`错误`。
实现:宿主记最小级别;`host_log_line` 返回待打印文本或 `None`;L1 再 `print`(接入现有 stdout / capture)。
## 2. UUID `lib/uuid` / `lib/标识`
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `v4` | `版本4` | (无) | 标准 8-4-4-4-12 小写 hex(`getrandom`) |
## 3. 刻意不做
结构化 JSON 日志、远程 sink、UUID v1/v7、yaml。
+231
View File
@@ -0,0 +1,231 @@
# 数学标准库(方案)
| | |
|---|---|
| 状态 | **已实现(M1–M4)** |
| 日期 | 2026-08-05 |
| 相关 | [stdlib-modules.md](stdlib-modules.md) · [stdlib-i18n.md](stdlib-i18n.md) · [markdown-mapping.md](markdown-mapping.md) · [view.md](view.md) · 大学线性代数见规划 [ext-linalg.md](ext-linalg.md) |
| 导入 | `lib/math.mq.md`(英)· `lib/数学.mq.md`(中) |
| 范围 | **高中数学**(初等函数、导数、圆锥曲线、简单方程);非大学 CAS |
---
## 1. 目标
1. **公式类型**:解析 `$$…$$`(及行内 `$…$` 的可选支持),得到可绑定、可传递的 **`formula` 值**——语义上像「公式常量 / 公式变量」。
2. **数学库对 `formula`(及文本表达式)做操作**:求值、化简、求导、求解、作图等。
3. **数值 + 随机**:日常算术与可复现随机。
4. **作图**:view / 静态页内嵌 SVG;CLI 写本地文件(可指定 `path`)。
**难度自觉:** 只覆盖高中知识面,自研小型表达式 AST + 规则即可,**不**追求 Mathematica / SymPy 完备性。
---
## 2. 核心模型:`formula` 类型
### 2.1 运行时
| 类型 | `type` 标签 | 说明 |
|------|-------------|------|
| `Value::Num(f64)` | `num` | 浮点 |
| `Value::Formula(…)` | `formula` | 已解析的表达式树(或等价内部表示) |
`print` / `str` 对 `formula`:输出规范 ASCII(如 `2*x + 1`)或保留源 LaTeX 的一种(实现时写死并文档化;建议 **ASCII 规范式** 便于测试)。
### 2.2 文档中的 `$$` = 公式赋值(与表格同构)
在可执行面用 **空 RHS 赋值** 后跟展示数学块,把公式绑到变量(与 `` `xs` = `` 后跟表格一致):
````markdown
# main
`f` =
$$
sin(x) + x
$$
*`df` = > diff formula=`f` var=x *
> plot formula=`f` var=x min=-3 max=3 path=f.svg
````
也支持:
- 单行围栏:下一行 `$$x^2 - 2$$`
- 同行 compact:`*`f` = $$x^2 - 2$$ *`
**废除:** `$$:name` / `$$ name=…` 模块级具名块(不再产生绑定)。
**无名 `$$…$$`:** 仅在成段注释(叙述面)里作展示,**不**进入运行时。可执行区若出现未挂在赋值上的裸 `$$` 围栏 → 报错,提示使用 `` `name` = `` + 围栏。
**行内 `$…$`:** v1 不做绑定;需要时用 `> formula text=…` 显式构造。
### 2.3 从文本构造
| 英文 | 中文 | 说明 |
|------|------|------|
| `formula` | `公式` | `text=` 解析为 `formula`(ASCII 或简单 LaTeX 子集) |
数学库函数形参统一接受:**`formula` 值**,或能解析的 **文本**(内部先 `formula` 化)。
### 2.4 与叙述面的关系
- `` `f` = `` + `$$…$$`:代码面赋值,得到 `formula` 值。
- 成段注释里的 `$$`:仍是注释,不解析为公式。
- view:公式赋值在 Structure 中显示为绑定,不是 comment。
(见 [markdown-mapping.md](markdown-mapping.md):空 RHS + `$$` → 公式赋值。)
---
## 3. 知识范围(高中)
### 3.1 表达式与符号(S)
| 纳入 | 例子 |
|------|------|
| 多项式 | `x^2 - 3*x + 2` |
| 初等函数 | `sin` `cos` `tan` `ln` `exp` `sqrt` `abs` |
| 四则、幂 | `+ - * / ^` |
| 化简 / 展开 | 合并同类项、基本三角恒等(小集合) |
| 求导 | 单变元,初等函数求导法则 |
| 代入求值 | `subs` → `num` 或公式 |
| 求解 | 一元一次 / 二次闭式;其它用数值求根并标明 |
**不做(本波):** 多元方程组、极限 ε-δ、级数、积分保证、**大学线性代数**(符号矩阵表达式 / 分解 —— 见 [ext-linalg.md](ext-linalg.md))、复数完备、任意证明。数值小矩阵字面量可在 `$$` 中解析为 `formula::Matrix`,但符号 MatExpr 与分解不在 `lib/math`。
### 3.2 作图(P)
| 纳入 | 说明 |
|------|------|
| 显函数 `y=f(x)` | 采样折线 SVG |
| 导数曲线 | 对 `formula` 先 `diff` 再画,或 `plot` 选项 `derivative=true` |
| 圆锥曲线 | 标准形:圆、椭圆、双曲线、抛物线(参数方程或隐式采样) |
| 点列 | `plot_points` |
**不做:** 三维、隐函数通用求解器、交互缩放(静态 SVG 足够)。
### 3.3 数值与随机(N)
常数、四则、三角、对数、取整、`num` 转换、`random` / `random_int` / `seed`(同前稿)。
---
## 4. API 草图(对 `formula` 操作)
### 4.1 构造与数值
| 英文 | 中文 | 要点 |
|------|------|------|
| `formula` | `公式` | 文本 → formula |
| `pi` `e` | `圆周率` `自然底数` | → num |
| `add`… / `sin`… | `加`… / `正弦`… | 对 num;若传入 formula 则返回 formula(符号)或报错——**v1 建议:算术函数只接 num;符号用 simplify/diff/subs** |
| `eval` | `求值` | `formula` + 变量赋值 → num |
| `random` / `random_int` / `seed` | `随机` / `随机整数` / `设种子` | 见前 |
### 4.2 符号
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `simplify` | `化简` | `formula` | formula |
| `expand` | `展开` | `formula` | formula |
| `diff` | `求导` | `formula`, `var` | formula |
| `subs` | `代入` | `formula`, `var`, `value` | formula 或 num |
| `solve` | `求解` | `formula`, `var`,可选区间 | list(num 或公式根) |
### 4.3 作图
| 英文 | 中文 | 形参 |
|------|------|------|
| `plot` | `绘图` | **`formula`**(或 `expr` 文本), `var`, `min`, `max`;可选 `steps`, `path`, `derivative`, **`grid`**(默认开;`False`/`假` 关) |
| `plot_conic` | `绘圆锥` | `kind`(circle/ellipse/hyperbola/parabola)+ 系数;可选 `path`, `grid` |
| `plot_points` | `绘点列` | `xs`, `ys`;可选 `path`, `grid` |
返回 **SVG 文本**;坐标轴带箭头与刻度,默认网格;写文件与 view 嵌入规则同前(§5)。
`diff` / `simplify` / `expand` / 未完全数值化的 `subs` 返回 **`formula`**,可继续链式调用。
示例:
```markdown
# main
`f` =
$$
x^2 - 2
$$
*`roots` = > solve formula=`f` var=x *
> print text=`roots`
*`svg` = > plot formula=`f` var=x min=-3 max=3 path=parabola.svg *
```
---
## 5. 作图:CLI / view / 静态(不变精神)
| 场景 | 行为 |
|------|------|
| 带 `path=` | 写 SVG 到该路径(沙箱内) |
| CLI 无 path | 自动 `{stem}-plot-{n}.svg` + 一行 `plot: …` |
| view / 导出无 path | 不强制写盘;加入 **plots 产物列表**,Execution 内嵌 |
| view / 导出有 path | 写盘 + 内嵌 |
不把整段 SVG 默认灌进 CLI stdout。
---
## 6. 分期
| 期 | 交付 |
|----|------|
| **M1** | `Num` + 数值/随机;`Formula` AST + `` `name` = `` + `$$…$$` 赋值绑定 |
| **M2** | `simplify` / `diff` / `subs` / `eval` / 二次 `solve`(高中子集) |
| **M3** | `plot` / `plot_points` / `plot_conic` + view 内嵌 + path 写盘 |
| **M4** | 用户文档 `public/stdlib/math*` · 金样例 · mapping 文档补丁 |
M1–M3 可在同一发版列车上连续落地;验收以「公式赋值 → 求导 → 作图」一条龙为准。
---
## 7. 实现要点
```text
src/formula/ # 词法/AST/化简/求导/求值(高中规则表)
src/host/math.rs # 数值、随机、对 formula 的 host 入口
src/host/plot.rs # SVG
lex/parse:空 RHS 赋值 + $$ 围栏 → Expr::Formula
Value::Num / Value::Formula
Interpreter.plots: Vec<Stringimport math:lib/math.mq.md · lib/数学.mq.md
```
依赖:纯 Rust;不绑 SymPy。公式复杂度、采样点、SVG 大小设硬上限。
---
## 8. 刻意不做
- `$$:name` 模块级具名绑定(已废除)。
- 无名 `$$` 自动进运行时。
- 大学级数 / 完备积分 / 定理证明。
- **大学线性代数扩展**(见 [ext-linalg.md](ext-linalg.md);不在本库做符号 MatExpr)。
- 通用隐函数作图引擎。
- 3D、交互式图表库。
---
## 9. 验收
1. `` `f` = `` + `$$…$$` + `diff` / `solve` / `plot` 金样例(中英库)。
2. 固定 `seed` 的随机金样例。
3. `plot` + `path` 在 CLI 落盘;view HTML 含 `<svg`。
4. `type` 对公式为 `formula`,对浮点为 `num`。
5. view Structure 将公式赋值显示为绑定,而非 comment。
---
## 10. 一句话
**`` `f` = `` + `$$…$$` 产出 `formula` 值;数学库对它做高中范围的符号运算、求解与作图——数值与随机并行,图在 view 内嵌、在 CLI 写文件。**
+172
View File
@@ -0,0 +1,172 @@
# 中层标准库(Mid Stdlib)
| | |
|---|---|
| 状态 | **M1–M6 已落地** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [ext-abi.md](ext-abi.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) · **后续** [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) |
| 目标 | 在接下来数个发版周期内,把「通用编程」能力沉到 **L0.5 宿主 + L1 `.mq.md`**,减少「凡是稍有能力就必须 ABI 插件」的路径依赖 |
---
## 1. 为什么现在做
现状分层(已落地):
```text
L0 内置 print / len / split / …
L0.5 宿主原语 src/host/*(供 L1 包装,作者原则上不直调)
L1 官方库 lib/*.mq.md(嵌入二进制 / 可覆盖)
ext 官方扩展 .mq.md + 可选 cdylib(web / agent / quantum / linalg)
```
痛点:
1. **通用语言能力缺口**:`lib/text` 几乎只是 `trim/split/join`;无正则、无编解码、无哈希、无路径代数、无 CSV……日常脚本要么外联 Python,要么新开插件。
2. **插件路径过重**:ABI 插件适合**领域热路径**(量子核、公式矩阵、HTTP 服务+SQLite),不适合「再来一个 base64」。每加一个插件都要:crate、Release 资产、`ext add`、CI、WASM 缺口。
3. **扩展作者被逼进插件**:`ext/**` 禁止 `host_*`。若 L1 没有正则 / 哈希 / 路径,扩展只能 `plugin.load`,导致「库」与「原生模块」边界模糊。
4. **对照成熟语言**:Go 的 `strings` / `regexp` / `encoding/*` / `crypto` / `path/filepath`、Python 的「难写对才进 stdlib」标准——都把**通用原语**留在语言自带层,把**领域产品**留给第三方。Marqdo 的「通用」应对齐前者;`ext/` 对齐后者。
中层标准库 = **在现有 L1 之上、在官方 ext 之下**,专门补「写通用程序必备、又不该做成插件」的那一档。
---
## 2. 分层命名(本波约定)
| 名称 | 位置 | 用户导入 | 实现形态 |
|------|------|----------|----------|
| **核心 L1** | 已有 `lib/{fs,sys,time,json,net,math,…}` | 是 | 薄包装 → 已有 `host_*` |
| **中层 L1(Mid)** | 新增 / 加厚 `lib/{re,encoding,hash,path,…}` | 是(仍属 `lib/` / `std/`) | **优先**薄 `host_*` + L1;能纯 `.mq.md` 则纯库 |
| **官方 ext** | `ext/{web,agent,quantum,linalg,ai}` | 显式 `ext/` | `.mq.md`;**仅**领域热路径允许 ABI 插件 |
| **catalog / 用户库** | 发版外收录 | 各自约定 | 应能主要靠 Mid + 核心 L1 写成,**默认无插件** |
> **不**新开第三棵目录树。中层仍落在 `lib/`,用文档与路线图分期交付,避免 `lib/` vs `lib-mid/` 分裂。
---
## 3. 准入 / 不准入(宪法)
### 3.1 进入中层的条件(须同时满足多数)
| # | 条件 | 说明 |
|---|------|------|
| 1 | **跨领域高频** | 脚本、站点、智能体、教学示例都会用到 |
| 2 | **难写对或不可移植** | 正则、Unicode、密码学、路径跨平台——纯 Marqdo 成本过高 |
| 3 | **解锁「无插件写库」** | 有了它,更多 `ext/` / catalog 可用纯 `.mq.md` |
| 4 | **宿主面积极小** | 一个或少数 `host_*` + 稳定 crate;不把巨型框架链进主二进制 |
| 5 | **API 可长期冻住** | 宁可窄接口,也不提前做成第二个 Requests |
参考(外部):
- Python:[stdlib 准入](https://devguide.python.org/developer-workflow/stdlib/) 与 [Language Summit:stdlib 何用](https://blog.python.org/2023/05/the-python-language-summit-2023-what-is.html)——偏「启动器 / 新手脚本 / 难写对的协议」,而非「万物入 std」。
- Go:日常几乎离不开的 `strings`、`regexp`、`encoding/*`、`crypto`、`path/filepath`、`slices`——对标我们的 Mid 候选,而非 `database/sql` 驱动全家桶。
- 反面:PEP 594「死电池」——过窄协议、过时格式、与生态脱节的模块不要进 Mid。
### 3.2 明确不准入(继续走 ext + 可选插件)
| 领域 | 原因 |
|------|------|
| HTTP **服务端** / ASGI / 路由框架 | 产品面;已有 `ext/web` |
| SQLite / ORM / 管理后台 | 同上 |
| LLM / 智能体编排 / OKF | `ext/ai` · `ext/agent` |
| 量子线路 / 密度矩阵核 | `ext/quantum` |
| 大学线性代数 CAS / 分解可视化 | `ext/linalg`(公式文档面) |
| 完整图像 / 音视频 / ML | 体积与依赖爆炸 |
| 任意第三方云 SDK | 不属于语言 |
### 3.3 插件仍保留的边界
ABI 插件 **不废除**。规则收紧为:
```text
若能力可用「少量 host_* + lib/*.mq.md」表达 → 必须走中层,禁止新开官方插件。
若能力是领域数值核 / 长生命周期服务 / 可选重依赖 → 才允许官方插件。
```
`lib/plugin` 继续服务:本地实验、第三方原生、官方领域包。
---
## 4. 实现分工(怎么长)
```text
用户 / catalog / 官方 ext(纯 mq 优先)
│ import re:lib/re.mq.md
▼
中层 L1(.mq.md,中英分文件,除 json 类共用外)
│ **> host_re_find …**
▼
L0.5 宿主(Rust:regex / sha2 / …)
│
▼
OS / 算法库(精选 crate,默认 features 最小化)
```
| 规则 | 说明 |
|------|------|
| `ext/**` 仍禁止 `host_*` | 中层补齐后,ext 经 `lib/re` 等调用 |
| 每个新 `host_*` | 必须有 L1 包装 + 金样 + 中英对称(见 [stdlib-i18n.md](stdlib-i18n.md)) |
| 能纯 mq 的 | 例如在 `table` 上的 `sort_by` 若性能可接受,可先纯库;热路径再下沉 host |
| WASM | 新 host 须标注是否进浏览器构建;不能 WASM 的在文档标 `host-only` |
| 依赖 | 新增 crate 写进 [dependencies.md](dependencies.md) 动机;禁止「顺手」拉大型框架 |
---
## 5. 模块候选总表(按优先级波次)
完整排期与验收见 [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md)。摘要:
| 波次 | 模块(英 / 中) | 典型能力 | 主要形态 |
|------|-----------------|----------|----------|
| **M1** | `re` / `正则` · `encoding` / `编码` | match / find / replace;base64 / hex | **done** |
| **M2** | `path` / `路径` · `fs` 加厚 | join / normalize;copy / move / temp | **done** |
| **M3** | `hash` / `哈希` · `secrets` / `机密` | sha256 / hmac;token | **done** |
| **M4** | `csv` / `逗号表` · `text` 加厚 | parse / stringify;contains / replace | **done** |
| **M5** | `table` 加厚 · `cli` / `命令行` | sort / zip;flags | **done** |
| **M6** | `log` / `日志` · `uuid` / `标识` | level 日志;v4 | **done** |
| **可选(Mid1)** | `yaml` | 默认 **不做** | 见 Mid2:优先 TOML |
**Mid1 刻意延后、现已升格到 Mid2:** 日历/时区、URL 解析 —— 见 [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md)。
**仍不准入 Mid:** 连接池、异步 runtime、模板引擎、完整 `collections` 类型系统、HTTP 服务端 / SQLite(`ext/`)。
---
## 6. 与现有库的关系
| 现有 | 中层策略 |
|------|----------|
| `lib/text` | **加厚**,不另起 `strings` 英文名(保持 Marqdo 习惯);中文 `文本` |
| `lib/table` | Mid 集合算法优先挂这里或薄 `listx`;避免与 GFM 表语义打架 |
| `lib/net` | HTTP 客户端保留;编解码类能力与 `encoding` 边界写清(url 组件归谁) |
| `lib/math` | 保持**高中**;哈希 / 安全随机不进 math |
| `lib/json` | 仍只 parse/stringify/quote;CSV/YAML 另库 |
| `lib/plugin` | 不变;文档写明「通用能力请先查 Mid」 |
| `ext/*` | 逐步**改写依赖**:能改用 `lib/re` 的路由/校验,去掉不必要的原生 |
---
## 7. 文档与工程节奏
每个 Mid 波次固定流水线(与现有发版习惯对齐):
1. 本设计不变的前提下,在 roadmap 勾选该波次工作项。
2. `doc/design/stdlib-<module>.md`(可短)→ `host_*` → `lib/` 中英 → `tests/lib/*` 金样 → `public/features` 短文。
3. 更新 [stdlib-modules.md](stdlib-modules.md) 模块表。
4. **不**为 Mid 单开 SemVer 故事;随正常产品发版收进 CHANGELOG「标准库」小节。
5. 发版技能 / Release 资产:仅当新增 **必须** 随 CLI 分发的东西时改 release 脚本——Mid 默认已嵌入 stdlib,**无** native zip。
---
## 8. 成功标准(数个版本后)
1. 用 Mid + 核心 L1 **不加载任何插件**,能写:日志采集脚本、CSV 清洗、带正则的文本管线、带哈希校验的下载器、简单 CLI 工具。
2. 新的官方 **非领域** 能力默认进 `lib/`,评审时问:「能否不做成插件?」
3. `ext/web` / `ext/agent` 等仍可有插件,但依赖面写进文档:哪些能力已改走 Mid。
4. 主二进制体积与依赖可解释;WASM 可用性有清单。
---
## 9. 一句话
**中层标准库把「通用原语」沉回语言自带层,让插件专属于真正的领域引擎——这样 Marqdo 才像一门通用语言,而不是「Markdown + 一堆 .so」。**
+139
View File
@@ -0,0 +1,139 @@
# 设计:中层标准库第二波(Mid2 · M7–M10)
| | |
|---|---|
| 状态 | **Accepted · M7–M10 已落地(zip 跳过)** |
| 日期 | 2026-09-09 |
| 缺口盘点 | [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) |
| 路线图 | [stdlib-mid2.md](../roadmap/stdlib-mid2.md) |
| 宪法 | [stdlib-mid.md](stdlib-mid.md) §3(准入 / 不准入 **不变**) |
| 目标 | 在 M1–M6 之上补「日历 · URL · 配置 · HTML 安全 · fs 再厚」,仍保持宿主面积极小 |
---
## 0. 一句话
**Mid2 = 第二档通用原语,不是第二套 stdlib。** 仍落在 `lib/` + 薄 `host_*`;禁止借机引入 YAML 全家桶、HTTP 服务端、数据库。
---
## 1. 分层与禁止
| 允许 | 禁止 |
|------|------|
| 新 `lib/*.mq.md` 中英对偶 | 新开 `lib-mid2/` 目录树 |
| 少数 `host_datetime_*` / `host_url_*` / `host_toml_parse` | 为 Mid 新增 ABI 插件 |
| 加厚既有 `fs` / `encoding` / `net` / `text` | 把 `ext/web` 能力下沉进 `lib/net` 服务端 |
| TOML **只读** | 完整 YAML 1.2、任意对象反序列化 |
| HTML **转义** | 模板引擎 / CSS 选择器引擎 |
---
## 2. M7 — `datetime` + `url`
### 2.1 `lib/datetime.mq.md` / `lib/日期时间.mq.md`
| 函数(英) | 中文建议 | 行为 |
|------------|----------|------|
| `now` | `现在` | 返回结构化时刻(见下)或 ISO 文本(二选一,实现时锁定) |
| `from_unix` / `to_unix` | `自戳` / `成戳` | 秒级;可选 `ms` |
| `parse` | `解析` | 支持 RFC3339 / 常见 `YYYY-MM-DD[ HH:MM:SS]` |
| `format` | `格式化` | strftime 子集或命名样式 `rfc3339`/`date`/`time` |
| `add` | `加` | `days`/`hours`/`minutes`/`seconds` 具名 |
| `in_zone` | `时区` | IANA 名或 `+08:00`;失败 → 诊断 |
**结构化时刻(建议 map)**:`{unix, zone, iso}` 或宿主不透明柄 + `_type=datetime`。优先 **map + 稳定字段**,便于 GFM/table 协作。
**刻意不做**:农历、营业日、完整 tzdb 热更新 UI、闰秒政治。
### 2.2 `lib/url.mq.md` / `lib/地址.mq.md`(或并入 `net`)
| 函数 | 行为 |
|------|------|
| `parse` | → `{scheme, userinfo, host, port, path, query, fragment}` |
| `query_parse` | `a=1&b=2` → map(多值用列表) |
| `query_stringify` | map → query |
| `join` | base + relative(可选,可二期) |
既有 `net.url_encode` **保留**;文档写清:编码单段用 `net`/`encoding`,解析整 URL 用 `url`。
**验收**:金样解析带 query 的 HTTPS URL;往返 query。
---
## 3. M8 — `toml` + `html` + `encoding` 加厚
### 3.1 `lib/toml.mq.md` / `lib/Toml.mq.md`(或 `配置表`)
| 函数 | 行为 |
|------|------|
| `parse` | TOML 文本 → Marqdo map/list(只读) |
**不做** `stringify`(首版);需要写出时继续用 JSON。动机对齐 PEP 680:配置引导,而非通用文档格式战争。
### 3.2 HTML 转义
二选一(实现时定一):
- A:`lib/html.mq.md` · `escape` / `unescape`
- B:`text.html_escape` / `text.html_unescape`
推荐 **A**(安全语义独立可见)。
### 3.3 `encoding` 加厚
| 函数 | 行为 |
|------|------|
| `base32_encode` / `base32_decode` | RFC 4648 |
| (可选)`percent_decode` | 与 `url` 协作 |
---
## 4. M9 — `fs` 加厚
| 函数 | 行为 |
|------|------|
| `make_dirs` | 递归创建 |
| `remove_tree` | 递归删除(目录) |
| `stat` | `{size, mtime_unix, is_file, is_dir}` |
| `walk` | 返回路径列表(深度优先或广度;文档锁定) |
**不做**:权限 ACL、watch/inotify、硬链接全家桶。
---
## 5. M10 — 收口糖(可选)
| 项 | 说明 |
|----|------|
| `lib/stats` 或 `math.mean`/`median`/`stdev` | 极薄;非 pandas |
| `log` 结构化字段 | 可选 `fields=` map;非完整 slog 生态 |
| `zip` 读写 | **默认跳过**;有明确 Release 需求再开 |
---
## 6. 宿主与 WASM
| Host | WASM |
|------|------|
| `datetime` / `url` / `toml` / `html` / `fs.stat` | 尽量可进;IANA tz 数据体积需评估(可 host-only + 文档标注) |
| `fs.walk` / `remove_tree` | host-only 可接受 |
新 crate 写进 [dependencies.md](dependencies.md);禁止顺手拉大型框架。
---
## 7. 作者面风格
- 中英分文件;形参表声明全部可选并转发 `host_*`。
- 数据优先 GFM / `table`;`json` 仍只 parse/stringify/quote。
- 每波:设计短文 → host → lib → `tests/lib/*` → `public/features` 短页。
---
## 8. 完成定义(Mid2 整包)
1. 作者可用 `datetime` + `url` + `toml.parse` + `html.escape` 写配置驱动脚本,无需 foreign。
2. `fs.stat` / `make_dirs` 金样绿。
3. 研究文高优先级缺口标 closed;YAML/模板/sqlite 仍标明 won't。
4. [stdlib-modules.md](stdlib-modules.md) 总表更新;`stdlib.md` 状态改为 Mid2 进行中/完成。
+214
View File
@@ -0,0 +1,214 @@
# 标准库 L1 模块
| | |
|---|---|
| 状态 | **核心已落地**;**Mid M1–M6 已落地**;**Mid2 规划中** · [stdlib-mid2.md](stdlib-mid2.md) / [roadmap/stdlib-mid2.md](../roadmap/stdlib-mid2.md) |
| 日期 | 2026-09-08 |
| 原则 | 全部经 frontmatter **导入**;除 JSON 外中英分文件;内核保持少而精;**通用能力优先 Mid,插件留给领域核** |
| 相关 | [stdlib.md](stdlib.md) · [stdlib-i18n.md](stdlib-i18n.md) · [stdlib-mid.md](stdlib-mid.md) · [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-gaps-after-mid.md](../research/stdlib-gaps-after-mid.md) · [ext-abi.md](ext-abi.md) · [ext-llm.md](ext-llm.md) · [ext-agent.md](ext-agent.md) · [**module-namespace.md**](module-namespace.md)(导入命名空间;**M1/M2 已落地**:`库.成员` / `库.对象.成员` / `use`) |
---
## 1. 目标
在 `lib/text`·`lib/文本`、`lib/table`·`lib/表` 之上,把 Marqdo 推进到可写日常脚本与可选原生扩展。标准库**必须导入**才可用。
| 模块族 | 英文库 | 中文库 | 状态 |
|--------|--------|--------|------|
| 文本 | `lib/text.mq.md` | `lib/文本.mq.md` | 已有 + **Mid M4** 加厚 |
| **正则** | `lib/re.mq.md` | `lib/正则.mq.md` | **Mid M1** |
| **编解码** | `lib/encoding.mq.md` | `lib/编码.mq.md` | **Mid M1** + Mid2 M8 base32 |
| **路径** | `lib/path.mq.md` | `lib/路径.mq.md` | **Mid M2** |
| **哈希** | `lib/hash.mq.md` | `lib/哈希.mq.md` | **Mid M3** |
| **机密** | `lib/secrets.mq.md` | `lib/机密.mq.md` | **Mid M3** |
| **逗号表** | `lib/csv.mq.md` | `lib/逗号表.mq.md` | **Mid M4** |
| 表 | `lib/table.mq.md` | `lib/表.mq.md` | 已有 + Mid M4/M5:`sort`/`unique`/`zip`/… |
| **命令行** | `lib/cli.mq.md` | `lib/命令行.mq.md` | **Mid M5** |
| **日志** | `lib/log.mq.md` | `lib/日志.mq.md` | **Mid M6** + Mid2 M10 `fields=` |
| **标识** | `lib/uuid.mq.md` | `lib/标识.mq.md` | **Mid M6** |
| **日期时间** | `lib/datetime.mq.md` | `lib/日期时间.mq.md` | **Mid2 M7** |
| **地址** | `lib/url.mq.md` | `lib/地址.mq.md` | **Mid2 M7** |
| **配置表** | `lib/toml.mq.md` | `lib/配置表.mq.md` | **Mid2 M8** |
| **超文本** | `lib/html.mq.md` | `lib/超文本.mq.md` | **Mid2 M8** |
| **统计** | `lib/stats.mq.md` | `lib/统计.mq.md` | **Mid2 M10** |
| 浏览器效应 | `lib/browser.mq.md` | `lib/浏览器.mq.md` | WASM 客户端效应助手(GFM + helpers;勿用 `json.set` 链) |
| 文件 | `lib/fs.mq.md` | `lib/文件.mq.md` | 已有 + Mid M2 + **Mid2 M9**:`make_dirs` / `remove_tree` / `stat` / `walk` |
| 系统 | `lib/sys.mq.md` | `lib/系统.mq.md` | 已有(含 `load_dotenv`) |
| 时间 | `lib/time.mq.md` | `lib/时间.mq.md` | 已有 |
| JSON | `lib/json.mq.md` | **同文件** | **仅** parse / stringify / quote;集合请用 table / GFM |
| 网络 | `lib/net.mq.md` | `lib/网络.mq.md` | 已有(HTTPS + headers) |
| 数学 | `lib/math.mq.md` | `lib/数学.mq.md` | 已有 |
| 外联 | `lib/foreign.mq.md` | `lib/外联.mq.md` | 已有 |
| **插件** | `lib/plugin.mq.md` | `lib/插件.mq.md` | **已有**(加载 C ABI 共享库) |
| **自写回** | `lib/writeback.mq.md` | `lib/自写回.mq.md` | **已有**(Jupyter 式输出写回) |
| **子任务** | `lib/subtask.mq.md` | `lib/子任务.mq.md` | **已有**(OS 子进程 + KillOnDrop) |
官方可选扩展(**非** stdlib):`ext/llm` · `ext/agent` · `ext/web` · `ext/quantum` · `ext/linalg` — 见各 `ext-*.md`。
**中层已落地:** M1–M6(含 log / uuid)— 见 [stdlib-mid.md](stdlib-mid.md) · [stdlib-log-uuid.md](stdlib-log-uuid.md)。
**Mid2:** **M7–M10 done**(datetime / url / toml / html / base32 / fs++ / stats / log.fields;zip 跳过)— [stdlib-mid2.md](stdlib-mid2.md) · [stdlib-stats-log.md](stdlib-stats-log.md)。
设计细节:[stdlib-writeback.md](stdlib-writeback.md) · [stdlib-subtask.md](stdlib-subtask.md)。
---
## 2. 分层与实现分工
```text
用户 .mq.md
│ import fs:lib/fs.mq.md / import llm:ext/llm.mq.md
▼
L1 官方库 / 官方 ext(.mq.md)
│
▼
L0.5 宿主原语(Rust)或 原生插件(ABI v1)
│
▼
OS / HTTP / 时钟 / 共享库 …
```
| 层 | 谁实现 | 用户是否直接调用 |
|----|--------|------------------|
| **L0** | 解释器内置 | 是(`print`/`len`/…) |
| **L0.5 宿主原语** | Rust(`src/host/`) | **原则上否**;供 L1 包装;ABI v2 `host_query` 仅插件可调 |
| **L1 官方库** | `lib/*.mq.md` | **是** |
| **官方 ext** | `ext/*.mq.md`(+ 可选 ABI 插件) | **是**(需显式导入 `ext/`);**禁止** `host_*`,经 `lib/*` 或插件注册名 |
> **已变更(M1+M2)**:[module-namespace.md](module-namespace.md) — 取消跨文件扁平合并;L1/ext 经**裸名点号路径**调用(`time.parse`、`agent.agent`;M2:`库.对象.成员` + `use`),库名不加反引号;实例方法须 `` `var`.method ``;不再靠 import 顺序覆盖同名。
### 2.1 L1 薄包装 → 宿主(命名空间后必读)
点号路径 `net.http_post` / `json.stringify` 等解析到 **`lib/*.mq.md` 的 `##` 函数**,再转发 `host_*`。未在包装形参表声明的可选实参会被**静默丢弃**(曾导致 live agent 401:`Authorization` 等 `headers` 从未到达宿主)。
| 规则 | 说明 |
|------|------|
| 每个 `host_*` 包装 | 须在 `+` 形参表声明**全部**宿主可选参数,默认 `None`,并在 `**> host_…**` 中**原样转发** |
| `http_post` / `提交` | `content_type=None` 时宿主按默认 JSON charset 处理 |
| 已对齐(2026-08-07) | `net`/`网络`(headers、content_type、body)、`sys`/`系统`(load_dotenv、exec)、`ext/ai/llm`(load_env / 加载环境 path)、`json.stringify` indent、`foreign`/`外联` stdin、`math`/`数学` plot*/solve 可选项 |
**无**扁平合并回退;**无**裸名双轨兼容。
---
## 3. 核心模块 API(摘要)
文件 / 系统 / 时间 / JSON / 网络 API 见下文历史草图(已实现)。补充:
### 3.2 系统 — 已含 dotenv
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `load_dotenv` | `加载环境` | 可选 `path` | 新写入的键数量;缺文件 → `0`;不覆盖已有环境变量 |
### 3.4 JSON — 已含 `quote`
| 函数 | 形参 | 结果 |
|------|------|------|
| `quote` | `text` | JSON 字符串字面量(含引号) |
### 3.5 网络 — HTTPS
仅 **HTTP / HTTPS**(ureq);可选 `headers=`(map)、`content_type=`。
### 3.6 插件 — `plugin` / `插件`
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `load` | `加载` | `path` / `路径` | 注册函数个数 |
| `unload` | `卸载` | (无) | `None` |
| `list` | `列出` | (无) | 已注册名列表 |
契约:[ext-abi.md](ext-abi.md)。路径受 cwd/fs_root 沙箱约束。
### 3.1–3.5 历史 API 草图
#### 文件 — `fs` / `文件`
| 英文 | 中文 | 形参(英 / 中) | 结果 |
|------|------|-----------------|------|
| `read_text` | `读文本` | `path` / `路径` | 文本 |
| `write_text` | `写文本` | `path`, `text` / `路径`, `内容` | `None` |
| `append_text` | `追加文本` | 同上 | `None` |
| `exists` | `存在` | `path` / `路径` | 布尔 |
| `list_dir` | `列目录` | `path` / `路径` | 文本列表 |
| `make_dir` | `建目录` | `path` / `路径` | `None` |
| `remove` | `删除` | `path` / `路径` | `None` |
#### 系统 — `sys` / `系统`
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `env_get` | `取环境` | `name` / `名` | 文本或 `None` |
| `env_set` | `设环境` | `name`, `value` / `名`, `值` | `None` |
| `load_dotenv` | `加载环境` | 可选 `path` | 见上 |
| `args` | `参数表` | (无) | 文本列表 |
| `cwd` | `工作目录` | (无) | 文本 |
| `exit` | `退出` | `code` / `码` | 不返回 |
| `exec` | `执行` | `cmd`, 可选 `args` | 退出码 |
#### 时间 — `time` / `时间`
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `now_unix` | `此刻秒` | (无) | 整数(Unix 秒) |
| `now_ms` | `此刻毫秒` | (无) | 整数 |
| `format` | `格式化` | `unix`, `pattern` / `秒`, `格式` | 文本 |
| `sleep_ms` | `睡眠毫秒` | `ms` / `毫秒` | `None` |
| `parse` | `解析时间` | `text`, `pattern` / `内容`, `格式` | 整数秒或诊断失败 |
#### JSON — `json`
| 函数 | 形参 | 结果 |
|------|------|------|
| `parse` | `text` | 值 |
| `stringify` | `value`, 可选 `indent` | JSON 文本 |
| `get` | `value`, `key` | 值或 `None` |
| `keys` | `value` | 文本列表 |
| `quote` | `text` | JSON 字符串字面量 |
#### 网络 — `net` / `网络`
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `http_get` | `获取` | `url` / `地址` | 响应文本 |
| `http_post` | `提交` | `url`, `body`, 可选 `content_type` / `headers` | 同上 |
| `url_encode` | `编码地址` | `text` / `内容` | 文本 |
**路径字面量:** 具名实参里 `path=a/b` 会被解析成除法。请用无斜杠文件名,或先赋给变量再传入。
---
## 4. 中英路径总表
```text
lib/
text.mq.md / 文本.mq.md
table.mq.md / 表.mq.md
fs.mq.md / 文件.mq.md
sys.mq.md / 系统.mq.md
time.mq.md / 时间.mq.md
json.mq.md # 中英共用
net.mq.md / 网络.mq.md
math.mq.md / 数学.mq.md
foreign.mq.md / 外联.mq.md
plugin.mq.md / 插件.mq.md
ext/ # 非 stdlib
llm.mq.md / 大模型.mq.md
agent.mq.md / 智能体.mq.md
```
别名:`std/…` ≡ `lib/…`。扩展解析:`MARQDO_EXT` / `./ext` / 二进制旁 `ext/`。
---
## 5. 安全与 view / 静态导出
`marqdo run`、live `view`、`view output` 对标准库 **默认同一套能力**。差异仅在软退出 / sleep 钳制。相对路径落在源文件目录(或 view 根)下,防止 `..` 逃逸。插件路径同沙箱。
---
## 6. 一句话
**L1 含文件 / 系统 / 时间 / JSON / 网络 / 数学 / 外联 / 插件;`ext/` 为可选官方扩展(llm、agent)。**
+33
View File
@@ -0,0 +1,33 @@
# `lib/path` — 路径代数(Mid M2)
| | |
|---|---|
| 状态 | **已落地(M2)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
| 导入 | `lib/path.mq.md` · `lib/路径.mq.md` |
| Host | `host_path_*`(`std::path`;无 I/O、不经 `fs_root`) |
---
## 1. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `join` | `拼接` | `a`, `b` | 文本路径 |
| `split` | `拆分` | `path` | 组件文本列表(去空段) |
| `file_name` | `文件名` | `path` | 最后一段;根路径可为空文本 |
| `parent` | `父目录` | `path` | 父路径文本;无父则 `"."` |
| `extension` | `扩展名` | `path` | 不含点;无扩展名为 `""` |
| `normalize` | `规范化` | `path` | 清理 `.` / `..`(纯字符串,不访问磁盘) |
| `is_absolute` | `是绝对` | `path` | 布尔 |
## 2. 语义
- 分隔符与绝对路径判定跟随 **宿主 OS**(Linux CI 为 `/`)。
- **不做** I/O;逃逸检查仍由 `lib/fs` 在读写时执行。
- `join`:若 `b` 为绝对路径,结果为 `b`(同 `Path::join`)。
## 3. 刻意不做(v1)
`glob`、符号链接解析、`relative_to`、Windows UNC 专项文档。
+33
View File
@@ -0,0 +1,33 @@
# `lib/re` — 正则(Mid M1)
| | |
|---|---|
| 状态 | **已落地(M1)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-mid.md](stdlib-mid.md) · [roadmap/stdlib-mid.md](../roadmap/stdlib-mid.md) |
| 导入 | `lib/re.mq.md` · `lib/正则.mq.md` |
| Host | `host_re_*`(`regex` crate,默认 Unicode) |
---
## 1. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `is_match` | `匹配` | `text`, `pattern` | 布尔 |
| `find` | `查找` | `text`, `pattern` | 首个匹配文本,或 `None` |
| `find_all` | `查找全部` | `text`, `pattern` | 文本列表 |
| `replace` | `替换` | `text`, `pattern`, `with`, 可选 `count` | 文本(`count` 缺省 = 全部) |
| `split` | `拆分` | `text`, `pattern` | 文本列表 |
非法 pattern → 诊断失败(含 crate 错误信息)。
## 2. 语义
- 引擎:Rust [`regex`](https://docs.rs/regex)(无回溯引用;与 RE2 同族限制)。
- 按 **UTF-8 文本**匹配,不做字节模式。
- `find` / `find_all` 返回整段匹配(不含捕获组拆分;捕获组 v1 不做)。
## 3. 刻意不做(v1)
命名捕获、替换回调、`Regex` 对象缓存 API、字节模式。
+24
View File
@@ -0,0 +1,24 @@
# `lib/secrets` — 安全随机令牌(Mid M3)
| | |
|---|---|
| 状态 | **已落地(M3)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-hash.md](stdlib-hash.md) · [stdlib-mid.md](stdlib-mid.md) |
| 导入 | `lib/secrets.mq.md` · `lib/机密.mq.md` |
| Host | `host_secrets_*`(`getrandom`) |
---
## 1. API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `token_hex` | `十六进制令牌` | 可选 `n`(字节数,默认 16) | 小写 hex,长度 `2*n` |
| `token_urlsafe` | `网址安全令牌` | 可选 `n`(字节数,默认 16) | URL-safe Base64(无填充) |
**不要**用 `math.random` / `math.seed` 生成令牌。
## 2. 刻意不做
密钥派生、加密/解密、密码哈希。
+30
View File
@@ -0,0 +1,30 @@
# 设计:`lib/stats` / `lib/统计` 与 `log.fields`(Mid2 M10)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §5 |
| 宿主 | `src/host/stats.rs` · `host_stats_*`;`log::line` 可选 `fields` |
---
## 1. `lib/stats`
| EN | ZH | 行为 |
|----|-----|------|
| `mean` | `均值` | 算术平均 → Num |
| `median` | `中位数` | 排序后中位;偶数取两中点平均 |
| `stdev` | `标准差` | **样本**标准差(n≥2) |
**不做** dataframe、分位数全家桶、加权统计。
## 2. `log` `fields=`
各级别函数可选 `fields`(map)。宿主拼到行尾:`INFO msg key=val …`(map 插入序)。
**不做** 远程 sink、结构化 JSON 日志协议。
## 3. zip
按路线图 **默认跳过**。
+29
View File
@@ -0,0 +1,29 @@
# 子任务标准库(subtask)
| | |
|---|---|
| 状态 | v2 |
| 库 | `lib/subtask.mq.md` · `lib/子任务.mq.md` |
## 定位
**并发**执行单元。`spawn` 四选一:
| 参数 | 执行方式 | `join` / `wait` 返回值 |
|------|----------|------------------------|
| `path=` | `marqdo run <file> --emit-result <tmp>` 子进程 | map `{ code, value, stdout?, stderr? }`(`# main` 返回值;quiet 时 piped 捕获 I/O 尾部,不 inherit TTY) |
| `fn=` + 可选 `args=` | 当前入口模块中的函数(进程内线程) | 函数返回值 `Value` |
| `code=` | 外联代码块(`Value::Code`)子进程 | stdout `Text` |
| `lang=` + `source=` | 外联源码子进程 | stdout `Text` |
`args=`:文件子任务为 `List`(命令行参数);函数子任务为 `Map`(形参绑定)或 `List`(按 `arg0`… 命名)。
`quiet=` / `静默=`(默认 `True`):仅影响 **文件** 子任务的 **TTY**。默认 **piped 捕获** stdout/stderr(父终端不被污染,`wait` map 带截断后的 `stdout`/`stderr` 供父智能体观察);`False` 时继承父进程 stdout/stderr(map 中 I/O 字段为空)。**答案载荷仍以 `# main` 返回值为主**(经 `--emit-result` 旁路)。外联子任务仍经管道收集 stdout 供 `join` 返回,不受此参数影响。
**事件转发(文件子任务)**:spawn 时设置 `MARQDO_EVENT_FORWARD=<临时 ndjson>`;子进程内 `EventBus.publish` 追加写入该文件;父在 `wait` 阻塞期间 tail 并 republish(加 `source=child`)。这样子 LLM `stream=True` 的 token 能进 `marqdo view` SSE,而不破坏 quiet TTY 契约。函数子任务在同进程内,本来就共享 EventBus。
父进程结束(含 panic)时 **KillOnDrop** 终止所有文件/外联子进程;函数线程标记为 killed 并 detach(无法强杀 OS 线程)。
`poll` → `{ status: running | done | failed, … }`;函数 done 时含 `value`,进程/外联 failed 时含 `code` 或 `error`。
Host:`host_subtask_*`(`src/host/subtask.rs`)。
+83
View File
@@ -0,0 +1,83 @@
# `lib/table` / `lib/表` — 列表与字典
| | |
|---|---|
| 状态 | **已落地**(可用级集合 API) |
| 相关 | [stdlib.md](stdlib.md) · [stdlib-modules.md](stdlib-modules.md) · [table-cell-expressions.md](table-cell-expressions.md) · [roadmap/tables-maps-footnotes.md](../roadmap/tables-maps-footnotes.md) |
---
## 1. 读写对
| 读 | 写 |
|----|----|
| 链接取元 `[key](xs)` / `[key](m)` / 嵌套 `[1]([a](m))`(脚注 `` `m`[^k] `` 仍兼容) | **`table.put` / `表.改`** |
`put` / `改` 的 `at=`(`于=`)与取元同构:文本键、**1-based** 整数下标,或键/下标组成的路径列表。
```markdown
---
import table:lib/table.mq.md
---
# main
**`h` = [table.put] in=None at="Authorization" value="Bearer-x"**
`xs` =
| v |
|---|
| a |
| b |
**`xs` = [table.put] in=`xs` at=1 value="A"**
**打印 内容=[Authorization](h)**
```
`in=None` 且 `at=` 为单个文本键 → 新建单键字典。值一律不可变更新(返回新集合)。
---
## 2. 索引约定
| API | 基数 |
|-----|------|
| `put` / `改` 路径中的整数;脚注 `[^n]` | **1-based** |
| `at` / `row_at` / `set_at` / `insert` / `remove_at` / `slice` / `index_of` | **0-based** |
---
## 3. API 摘要(EN ↔ ZH)
| EN | ZH | 说明 |
|----|----|------|
| `put` | `改` | 按路径改一元(首选写入) |
| `len` / `rows` | `长度` / `行数` | 长度 |
| `at` / `row_at` | `取` / `取行` | 0-based 取元 |
| `append` / `prepend` / `concat` | `追加` / `前插` / `拼接` | 列表 |
| `insert` / `set_at` / `remove_at` / `pop` | `插入` / `改位` / `删位` / `弹出` | 列表位操作 |
| `first` / `last` / `slice` | `首` / `末` / `切片` | |
| `contains` / `index_of` / `reverse` | `含有` / `下标` / `反转` | |
| `clear` | `清空` | 列表或字典 |
| `get` / `set` / `delete` / `has` | `取键` / `设` / `删键` / `有键` | 浅层字典 |
| `keys` / `values` / `items` / `merge` / `size` | `键表` / `值表` / `项表` / `合并` / `键数` | |
| `empty_list` / `empty_map` | `空表` / `空字典` | |
嵌套改写优先 `put`/`改`;`set`/`set_at` 仅浅层。
---
## 4. 与 `lib/json`
| 用途 | 用 |
|------|----|
| 解析 / 序列化 / `quote` | `json.parse` · `json.stringify` · `json.quote` |
| 集合读写 | **`table.*` / `表.*`** |
| 兼容 | `json.set` / `json.append` / `json.get` / `json.keys` 仍为别名,新代码勿依赖 |
---
## 5. 宿主
`host_collection_put` + list/map 原语(见 `src/host/collection.rs`)。作者面经 `lib/table` / `lib/表` 调用,不直接写 `host_*`。
+30
View File
@@ -0,0 +1,30 @@
# `lib/text` 加厚(Mid M4)
| | |
|---|---|
| 状态 | **已落地(M4)** |
| 日期 | 2026-09-07 |
| 相关 | [stdlib-csv.md](stdlib-csv.md) · [stdlib-mid.md](stdlib-mid.md) |
| 导入 | `lib/text.mq.md` · `lib/文本.mq.md` |
| Host | `host_text_*`(Unicode 大小写 / 子串;非正则替换) |
---
## 1. 新增 API
| 英文 | 中文 | 形参 | 结果 |
|------|------|------|------|
| `contains` | `包含` | `text`, `sub` | 布尔 |
| `starts_with` | `开头是` | `text`, `prefix` | 布尔 |
| `ends_with` | `结尾是` | `text`, `suffix` | 布尔 |
| `replace` | `替换` | `text`, `old`, `new`, 可选 `count` | 文本(字面替换,非正则) |
| `to_upper` | `大写` | `text` | 文本(Unicode) |
| `to_lower` | `小写` | `text` | 文本 |
| `repeat` | `重复` | `text`, `n` | 文本 |
| `pad` | `填充` | `text`, `width`, 可选 `fill`=`" "`,可选 `align`=`left`/`right`/`center` | 文本 |
保留原有 `str_trim` / `str_split` / `str_join`(及中文去空白/拆分/拼接)。
## 2. 刻意不做
正则替换(用 `lib/re`)、完整 `format` 模板引擎。
+24
View File
@@ -0,0 +1,24 @@
# 设计:`lib/toml` / `lib/配置表`(Mid2 M8)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §3.1 |
| 宿主 | `src/host/toml_ops.rs` · `host_toml_parse`(手写子集,无 `toml` crate) |
---
## 1. API
| EN | ZH | 行为 |
|----|-----|------|
| `parse` | `解析` | TOML 文本 → map/list |
**不做** `stringify`;写出继续用 JSON。
## 2. 子集
支持:`#` 注释、基本/字面字符串、int/float/bool、标量数组、`[table]` 与 dotted key。
**不支持:** `[[array of tables]]`、内联表、TOML datetime、多行字符串。
+24
View File
@@ -0,0 +1,24 @@
# 设计:`lib/url` / `lib/地址`(Mid2 M7)
| | |
|---|---|
| 状态 | **已落地** |
| 日期 | 2026-09-09 |
| 父设计 | [stdlib-mid2.md](stdlib-mid2.md) §2.2 |
| 宿主 | `src/host/url_ops.rs` · `host_url_*`(手写子集,无 `url` crate) |
---
## 1. 与 `net.url_encode`
| API | 用途 |
|-----|------|
| `net.url_encode` | **单段** form 编码(空格→`+`) |
| `url.parse` | 整 URL → `{scheme,userinfo,host,port,path,query,fragment}` |
| `url.query_parse` / `query_stringify` | 查询串 ↔ map(重复键→列表;空格→`%20`) |
## 2. 解析子集
`scheme://[userinfo@]host[:port]/path[?query][#fragment]`,含 IPv6 `[addr]`。缺 path 时规范为 `/`。
**不做**:相对 URL join、完整 WHATWG 边角、IDNA 规范化(host 原样保留)。
+59
View File
@@ -0,0 +1,59 @@
# 自写回标准库(writeback)
| | |
|---|---|
| 状态 | v1 已落地 |
| 日期 | 2026-08-07 |
| 库 | `lib/writeback.mq.md` · `lib/自写回.mq.md` |
## 定位
**Jupyter 输出单元的 Marqdo 等价物**:执行得到结果 → `record` / `写回` 写入入口 `.mq.md` 的 `<!-- marqdo-out … -->` → `marqdo view` 在对应语句下显示 **output-card**。普通 Markdown 预览不显示该区域。
## 存储格式
```markdown
*`n` = > len value=`xs` *
<!-- marqdo-out
42
-->
```
命名槽(智能体成功/失败互不覆盖):
```markdown
<!-- marqdo-out ok
status=ok result=…
-->
<!-- marqdo-out error
pending
-->
```
- 注释内为 `marqdo-out`,可选后跟槽名(`ok` / `error` 等),**不存行号**
- 默认在**调用行下方**插入或替换紧邻**无键**块
- `at_end=true`:替换文件末尾的**无键**块
- `key=` / `键=`:在**当前调用锚点下方**创建或替换该命名槽(智能体单步用父调用行,即 `step` 语句下方);`ensure` 在缺失时写入占位且不覆盖已有正文。命名槽互不覆盖,也不使用文件末尾单块。
- `line=` / `行=`:显式锚点行号。子任务 / 异步写回必须带上,否则会锚到子任务内部调用行。主机侧有全局互斥锁,写前从磁盘重读入口源,避免并发写互相覆盖。
### 替换跨度与空行
替换 `<!-- marqdo-out … -->` 时,被替换跨度**包含**注释块结束 `-->` 后的**单个**换行符(不把该换行留在文件里)。这样多次 `record` **不会**在块下方累积多余空行。
命名槽仍锚在调用行(如 `step` / `写回`)下方;整簇结束后保留**一条**有意空行即可,且应稳定。
## API
| EN | ZH | 说明 |
|----|-----|------|
| `record` | `写回` | `value=`;可选 `at_end`、`key`、`line` |
| `get` | `取` | 可选 `at_end`、`key`、`line` |
| `clear` | `清除` | 可选 `at_end`、`key`、`line` |
| `ensure` | `确保` | `key=` + 可选 `placeholder=`、`line=`;槽已存在则不动 |
| `list` | `列出` | 全文所有输出块(命名槽含 `key` 字段) |
可选参数语法:`` + `参数名`=默认值 ``(与现有参数列表兼容)。
Host:`host_writeback_*`(`src/host/writeback.rs`);智能体侧经 `lib/subtask` 异步调用写回,避免阻塞推理主路径。
**与 `ext/ai/agent`:** `## step` / `## 单步` 在 D2 起 **默认自动** `record` 到 `ok`/`error` 槽(参数 `writeback=` / `写回=` 可关)。多步工作簿依赖此默认,见 [ext-agent-plan.md](ext-agent-plan.md) · [ext-agent.md](ext-agent.md)。
Loaded 100 of 943 files, more files were not shown because too many files have changed in this diff. Show more