From 0e389f34eccd0e91f98b4d0eda754ecd95676955 Mon Sep 17 00:00:00 2001 From: cflmy Date: Fri, 6 Nov 2026 17:29:37 +0800 Subject: [PATCH] Ship quantum skill=tools tree with call session and ZH package. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split ext/quantum into index + modules, add marqdo call --effects/--session/--toget, narrative-ratio checks, and a same-package 量子/ tree so agents can follow a decision path for Bell demos without inventing a second API. Co-authored-by: Cursor --- .cursor/skills/marqdo/SKILL.md | 14 +- .cursor/skills/marqdo/examples.md | 281 ++++---------- .cursor/skills/marqdo/reference.md | 61 +--- .gitignore | 2 + doc/design/ext-cli.md | 2 +- doc/design/ext-index-skill-tools.md | 88 +++++ doc/design/ext-quantum-q7.md | 2 +- doc/design/ext-quantum.md | 36 +- doc/next/012.md | 66 ++++ examples/oa2026-showcase/bell.mq.md | 2 +- examples/quantum-bell/index.mq.md | 2 +- examples/quantum-entanglement/index.mq.md | 2 +- examples/quantum-ghz/index.mq.md | 5 +- examples/quantum-skill-call/index.mq.md | 21 ++ ext/quantum/_capability/index.mq.md | 49 +++ ext/quantum/circuit/index.mq.md | 320 ++++++++++++++++ ext/quantum/density/index.mq.md | 172 +++++++++ ext/quantum/gate/index.mq.md | 150 ++++++++ ext/quantum/index.mq.md | 193 ++++++++++ ext/quantum/quantum.mq.md | 332 ----------------- ext/quantum/simulate/index.mq.md | 110 ++++++ ext/quantum/state/index.mq.md | 86 +++++ ext/quantum/viz/index.mq.md | 114 ++++++ ext/quantum/量子.mq.md | 332 ----------------- ext/quantum/量子/可视化/索引.mq.md | 104 ++++++ ext/quantum/量子/密度/索引.mq.md | 170 +++++++++ ext/quantum/量子/态/索引.mq.md | 70 ++++ ext/quantum/量子/模拟/索引.mq.md | 100 +++++ ext/quantum/量子/电路/索引.mq.md | 362 +++++++++++++++++++ ext/quantum/量子/索引.mq.md | 159 ++++++++ ext/quantum/量子/能力/索引.mq.md | 40 ++ ext/quantum/量子/门/索引.mq.md | 140 +++++++ lib/lint/narrative.mq.md | 41 +++ public/features/06-quantum.mq.md | 5 +- public/features/06-量子-plot-1.svg | 15 +- public/features/06-量子.mq.md | 7 +- public/features/22-call.mq.md | 2 +- skills/marqdo/SKILL.md | 10 +- skills/marqdo/examples.md | 2 +- skills/marqdo/reference.md | 4 +- src/call.rs | 281 +++++++++++--- src/call_session.rs | 286 +++++++++++++++ src/ext_cli.rs | 47 ++- src/lib.rs | 2 + src/main.rs | 64 +++- src/narrative_ratio.rs | 222 ++++++++++++ tests/call/nested.mq.md | 41 +++ tests/call_cli.rs | 88 +++++ tests/ext/quantum-amp-damp-smoke.mq.md | 2 +- tests/ext/quantum-amp-damp-zh-smoke.mq.md | 2 +- tests/ext/quantum-author-api-smoke.mq.md | 2 +- tests/ext/quantum-author-api-zh-smoke.mq.md | 2 +- tests/ext/quantum-bell-smoke.mq.md | 2 +- tests/ext/quantum-custom-gate-smoke.mq.md | 5 +- tests/ext/quantum-custom-gate-zh-smoke.mq.md | 5 +- tests/ext/quantum-draw-smoke.mq.md | 2 +- tests/ext/quantum-gate-heatmap-smoke.mq.md | 5 +- tests/ext/quantum-gate-matrix-smoke.mq.md | 5 +- tests/ext/quantum-gates-smoke.mq.md | 2 +- tests/ext/quantum-linalg-smoke.mq.md | 2 +- tests/ext/quantum-noise-smoke.mq.md | 2 +- tests/ext/quantum-noise-zh-smoke.mq.md | 2 +- tests/ext/quantum-steps-smoke.mq.md | 2 +- tests/ext/quantum-viz-advanced-smoke.mq.md | 2 +- tests/ext/quantum-zh-smoke.mq.md | 2 +- 65 files changed, 3714 insertions(+), 1036 deletions(-) create mode 100644 doc/design/ext-index-skill-tools.md create mode 100644 doc/next/012.md create mode 100644 examples/quantum-skill-call/index.mq.md create mode 100644 ext/quantum/_capability/index.mq.md create mode 100644 ext/quantum/circuit/index.mq.md create mode 100644 ext/quantum/density/index.mq.md create mode 100644 ext/quantum/gate/index.mq.md create mode 100644 ext/quantum/index.mq.md delete mode 100644 ext/quantum/quantum.mq.md create mode 100644 ext/quantum/simulate/index.mq.md create mode 100644 ext/quantum/state/index.mq.md create mode 100644 ext/quantum/viz/index.mq.md delete mode 100644 ext/quantum/量子.mq.md create mode 100644 ext/quantum/量子/可视化/索引.mq.md create mode 100644 ext/quantum/量子/密度/索引.mq.md create mode 100644 ext/quantum/量子/态/索引.mq.md create mode 100644 ext/quantum/量子/模拟/索引.mq.md create mode 100644 ext/quantum/量子/电路/索引.mq.md create mode 100644 ext/quantum/量子/索引.mq.md create mode 100644 ext/quantum/量子/能力/索引.mq.md create mode 100644 ext/quantum/量子/门/索引.mq.md create mode 100644 lib/lint/narrative.mq.md create mode 100644 src/call_session.rs create mode 100644 src/narrative_ratio.rs create mode 100644 tests/call/nested.mq.md diff --git a/.cursor/skills/marqdo/SKILL.md b/.cursor/skills/marqdo/SKILL.md index cf7a4bd..9529a3d 100644 --- a/.cursor/skills/marqdo/SKILL.md +++ b/.cursor/skills/marqdo/SKILL.md @@ -7,7 +7,7 @@ description: >- importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic sites with ext/web, quantum circuits with ext/quantum, or when the user mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or - quantum/量子 extension. + quantum/量子 extension (ZH under ext/quantum/量子/). --- # Marqdo development @@ -136,7 +136,7 @@ Chinese builtins (same functions, no import): ## Frontmatter imports + stdlib -Imports use nested YAML `import:` (`导入:` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path: +Imports use nested YAML `import:` (`导入` equivalent): file (`.mq.md`) or short name (`lib.member`). Members are **not** flattened into the caller. Call with a bare dotted path: ```markdown --- @@ -195,12 +195,14 @@ Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: 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` +- **Root skill (read first):** [`ext/quantum/index.mq.md`](../../ext/quantum/index.mq.md) — explains every module and exact `marqdo call` commands for agents with no other context. +- **Modules:** `circuit/` · `gate/` · `simulate/` · `state/` · `density/` · `viz/` · `_capability/` (each has `index.mq.md`). ZH package: `ext/quantum/量子/`(根 `索引.mq.md`,模块同名中文目录). +- **Agent:** `marqdo call ext/quantum//index.mq.md … --effects plugin` (`--toget` / `$name`). Narration: `marqdo check --narrative-ratio FILE`. +- **Author import example:** `circuit: ext/quantum/circuit/index.mq.md` then `circuit.circuit` / method chain. **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`. +**Core:** domain skills above (`# circuit` / `# gate` / `# density` on module files) — 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`. @@ -221,7 +223,7 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7 - `invoke` returns a record (`ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result`); pass `input` for JSON stdin and `output="json"` for a parsed result. - `call` is JSON-in / JSON-out; `call_many` fans out one program over a list with ordered results. -- `session_open` returns an opaque `handle` (not text; not JSON-serializable). `session_eval` / `set` / `get` borrow the handle; `session_close` consumes it (double-close / use-after-close fault). Prefer `foreign.replay_check` / language-level `foreign.oracle_journal` when comparing recordings (`replay_snapshot` only re-runs). JSON integers outside \(\pm(2^{53}-1)\) and ragged table columns are refused (`doc/design/v-safe-json.md`, `foreign-strong-correspondence.md`, `oracle-journal-values.md`). +- `session_open` starts a persistent Python/Node kernel; `session_eval` evaluates source; `session_set` / `session_get` bridge values explicitly as JSON. Close it with `session_close`. - A view document opts into kernel state with `会话 = > foreign.session kernels=... cells=...`; the table names are free. `view` consumes only the `会话` handle and never scans source lines or reserved table names. Without `会话`, cells are stateless one-shot runs; no kernel is created. Clearing outputs calls `/api/session/clear` and keeps persistent kernel state. There is no separate notebook CLI mode or command, and no new Markdown marker exists. - The same source remains the authority; state crossing kernels is explicit, never implicitly mirrored. diff --git a/.cursor/skills/marqdo/examples.md b/.cursor/skills/marqdo/examples.md index 4e7d753..0048837 100644 --- a/.cursor/skills/marqdo/examples.md +++ b/.cursor/skills/marqdo/examples.md @@ -1,7 +1,5 @@ # Marqdo examples (AI) -v0.3: `**…**` = code (assign / call); `*…*` = return. Prefer `[key](coll)` over footnote get. Bracket calls: `礼貌 [问候] x`. - ## 1. Hello (English) ```markdown @@ -18,7 +16,7 @@ v0.3: `**…**` = code (assign / call); `*…*` = return. Prefer `[key](coll)` o > 打印 内容=你好,世界! ``` -## 3. Function + named call + empty return +## 3. Function + named call + body end ```markdown # main @@ -32,24 +30,22 @@ Greeting via a nested function: > 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`** +*a = 2* +*b = > add_one n=`a`* +> print text=`b` ## add_one + `n` -*n + 1* +**n + 1** ``` ## 5. Branch with else @@ -57,7 +53,7 @@ Or end with a whole-line empty bold return: `**` / `****`. Lone `---` is a thema ```markdown # main -**n = 0** +*n = 0* 1. `n` > 0 > print text=positive @@ -82,7 +78,8 @@ Or end with a whole-line empty bold return: `**` / `****`. Lone `---` is a thema > print text=`果` ``` -## 6b. Map table + link-index get + +## 6b. Map table + footnote get ```markdown # main @@ -93,20 +90,13 @@ Or end with a whole-line empty bold return: `**` / `****`. Lone `---` is a thema |------|------| | 水果 | 蔬菜 | -**种 = [苹果](分类)** -**打印 内容=`种`** +*种 = 分类[^苹果]* +> print text=`种` -`篮子` = - -| 果 | -|----| -| 苹果 | - -**第一 = [1](篮子)** -**打印 内容=`第一`** +*第一 = 篮子[^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**. +One column → list; ≥2 columns + one data row → map; ≥2 columns + many rows → map of lists. Data cells are expressions (same as call-arg values): bare words, numbers, `` `var` ``, quoted strings; URLs and `gpt-4o-mini` stay text via path/hyphen folding. Footnotes: lists use 1-based digit indices; maps use key text (including digit keys like `[^00]`). Foreach on a map walks **keys**. Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of maps (marker column excluded): @@ -117,27 +107,10 @@ Row-oriented records (SQL-like): first header `@` / `行` / `row` → list of ma |----|------|------| | 1 | 苹果 | 2 | -**名 = [品名]([1](订单))** +*名 = 订单[^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) +## 6c. Browser effects — tables + lib/browser (not json.set) ```markdown --- @@ -156,64 +129,13 @@ import: **`wire`** ## bump -**count = count + 1** -**label = str count** +*`count` = count + 1* +*`label` = > str count* **> browser.set_text sel="#count" text=label** ``` Do **not** build effect maps with `json.set` chains. See [marqdo-dev](../marqdo-dev/SKILL.md). -## 6e. Agent / LLM result maps — GFM first (positive) - -Return and soft-error packs are **tables**, not `json.set` pipelines. Full style contract: [marqdo-dev](../marqdo-dev/SKILL.md) §2. - -```markdown ---- -import: - table: lib/table.mq.md ---- - -## step_ok - + `task` - + `reply` - -`out` = - -| status | task | result | -|--------|------|--------| -| ok | `task` | `reply` | - -*out* - -## step_err - + `task` - + `err` - -`out` = - -| status | task | error | -|--------|------|-------| -| error | `task` | `err` | - -*out* - -## soft_http_pack - + `msg` - + `usage0` - -**empty_tc = > table.empty_list** - -`pack` = - -| finish | text | error | usage | tool_calls | -|--------|------|-------|-------|------------| -| error | "" | `msg` | `usage0` | `empty_tc` | - -*pack* -``` - -Do **not** mirror legacy `ext/ai/agent.mq.md` `json.parse`+`json.set` chains when adding new arms — convert the shape to a table. - ## 7. Import text stdlib ```markdown @@ -225,43 +147,8 @@ import: # 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 - 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 - uuid: lib/uuid.mq.md ---- - -# main - -> log.info text="start" -> log.set_level level="debug" -> log.debug text="detail" -**id = [uuid.v4]** -**打印 内容=`id`** +*parts = > split value=a,b,c sep=,* +> print text=`parts` ``` ## 8. Comment paragraphs (blank-line rule) @@ -270,7 +157,7 @@ import: # main This whole paragraph is a comment, including lines that look like code: -**not_executed = 1** +*not_executed = 1* > print text=also still comment After a blank line, code runs: @@ -289,13 +176,13 @@ import: # main -**t = > num value=3.5** -**打印 内容=`t`** +*t = > num value=3.5* +> print text=`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` / `自`. +See `tests/structure/object-handle.mq.md` and `ext/llm.mq.md`: `# Type` constructs a map with `_type`; methods use `` > `obj`.method `` and read `self` / `自`. ## 10b. Object inheritance @@ -305,16 +192,16 @@ See `tests/structure/object-handle.mq.md` and `ext/ai/llm.mq.md`: `# Type` const ## hello + `who` -**msg = "Hello, `who`!"** -*msg* +*msg = "Hello, `who`!"* +**msg** # Loud = > Greeter ## hello + `who` -**msg = "HELLO, `who`!"** -*msg* +*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: @@ -323,9 +210,9 @@ See `tests/structure/object-handle.mq.md` and `ext/ai/llm.mq.md`: `# Type` const # Child = > Parent + `name` -**self = > Parent name=`name`** -**self = [table.put] in=`self` at="extra" value=1** -*self* +*self = > Parent name=`name`* +*self = > json.set map=`self` key=extra value=1* +**self** ``` ## 11. Agent layout (ABI) @@ -340,9 +227,9 @@ import: > load_native -**ws = > agent** -**n = > `ws`.ensure_layout** -**打印 内容=`n`** +*ws = > agent* +*n = > `ws`.ensure_layout* +> print text=`n` ``` Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see `doc/design/ext-agent.md`). @@ -350,14 +237,14 @@ Requires `MARQDO_AGENT_PLUGIN` pointing at the built `agent` shared library (see ## 12. What not to emit ```markdown -# BAD — bare bold that is not code-shaped (decorative OK); do not use bold/italic as print +# BAD — bold is return, not print **Hello** # BAD — Python control keywords if x > 0: print(x) -# BAD — wrapping a call in italics as if it were a statement +# BAD — wrapping a call in italics *> print text=hi* # BAD — old branch syntax (removed) @@ -374,58 +261,48 @@ if x > 0: > print text=y-pos 2. * > print text=y-other - -# GOOD — print / return -**打印 内容="hi"** -*n + 1* ``` -## 13. Dynamic site (ext/web, minimal) +## 13. Dynamic site (Web Artifact, minimal) + +`index.mq.md`: + +```markdown +--- +type: web +title: Hello +route: / +method: GET +--- + +# Hello + +Executable document as a page. +``` + +`serve.mq.md`: ```markdown --- -title: hello-site import: web: ext/web/web.mq.md - 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` +> web.serve root="." host="127.0.0.1" port=8080 ``` -- 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`. +- Import `ext/web/web.mq.md` **or** `ext/web/网页.mq.md` — not both. +- Full Artifact blog: `examples/marqdo-blog/` (`pages/` · `api/` · `db/` · `data_source`). +- Design: `doc/design/ext-web-artifact.md` · ADR 0007. No `compose_*` / `configure`. ## 14. Quantum entanglement lab (ext/quantum Q7/Q8) ```markdown --- import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main @@ -437,43 +314,15 @@ import: | 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`** +*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"* +> print text=`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/`. diff --git a/.cursor/skills/marqdo/reference.md b/.cursor/skills/marqdo/reference.md index 9a20a85..cae83c6 100644 --- a/.cursor/skills/marqdo/reference.md +++ b/.cursor/skills/marqdo/reference.md @@ -12,13 +12,13 @@ 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 +marqdo ext add llm|agent|web|quantum +marqdo ext remove llm|agent|web|quantum ``` 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`. +**v0.2 surface:** parameters `` + `name` ``; branches `` 1. `cond` `` / `` 2. * `` (same-indent restart at `1.` = **new** branch statement); loops `` - [item](coll) `` or `` - [`item`](`coll`) ``; identifiers in backticks (foreach header may omit ticks). See `doc/design/markdown-mapping.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. @@ -44,15 +44,6 @@ Import one file; use **that** file’s function names. |-----------|-----------|-------------------------| | `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 | @@ -65,29 +56,28 @@ Import one file; use **that** file’s function names. | `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 | +| `ext/quantum/index.mq.md` + modules | `ext/quantum/量子/索引.mq.md` + modules | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** 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) +## ext/web (Artifact sites · ADR 0007) -Install: `marqdo ext add web` (`网页`). Native: `cargo build --release -p marqdo_plugin_web`. +Install: `marqdo ext add web` (`网页`). Native: `bash scripts/build-web-plugin.sh`. -| EN import | ZH import | Core types | -|-----------|-----------|------------| -| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | `# page` `# style` `# db` `# form` `# app` `# auth` `# cache` `# storage` | +| EN import | ZH import | Surface | +|-----------|-----------|---------| +| `ext/web/web.mq.md` | `ext/web/网页.mq.md` | facade: `page` · `route` · `serve` · `render` · `inspect` · `use` | -| 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 | +| Kind | Metadata | Notes | +|------|----------|-------| +| Document | `type: web` / `类型: 网页` | `route` · `data_source` · `data_order` · `data_where` | +| Endpoint | `type: endpoint` / `类型: 端点` | `path` · `method` · `# main` handler · `request`/`response` | +| View | `|type|slot|value|attrs|style|` | `web.render nodes=` | +| Resource | `ext/data` · `ext/security` · `ext/net` | db/cache/storage · auth/rbac/oidc · websocket | -Drivers (Postgres / Redis / S3): `db url=postgres://…`, `cache url=memory:`, `storage url=file:…` — see `doc/design/ext-web-drivers.md`. +Do **not** use `compose_*` / `app.configure` / author `ensure_plugin`. -Example project: `examples/marqdo-blog/`. Capability matrix: `doc/design/web-net-capabilities.md`. +Example: `examples/marqdo-blog/`. Design: `doc/design/ext-web-artifact.md`. Historical matrix: `doc/design/web-net-capabilities.md`. ## ext/quantum (circuits + Q7/Q8) @@ -95,7 +85,7 @@ Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p | EN import | ZH import | Core types | |-----------|-----------|------------| -| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | `# circuit` `# gate` `# density` | +| `ext/quantum/circuit/index.mq.md` (etc.) | `ext/quantum/量子/电路/索引.mq.md` (etc.) | `# circuit` / `# 电路` · `# gate` / `# 门` · `# density` / `# 密度` + call tools | | Area | EN APIs | Notes | |------|---------|-------| @@ -108,16 +98,6 @@ Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p 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 @@ -185,8 +165,7 @@ See `doc/design/call-arguments.md`. | Doc | Topic | |-----|--------| -| `doc/design/markdown-mapping-v0.3.md` | Syntax constitution (runtime) | -| `doc/design/markdown-mapping.md` | Legacy v0.2 notes | +| `doc/design/markdown-mapping.md` | Syntax constitution | | `doc/design/objects.md` | `#` objects / `##` methods | | `doc/design/keywords.md` | Builtins / keywords | | `doc/design/return-hr-and-code-surface.md` | Function end / surfaces | @@ -201,6 +180,4 @@ See `doc/design/call-arguments.md`. | `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 | diff --git a/.gitignore b/.gitignore index 4597071..242b966 100644 --- a/.gitignore +++ b/.gitignore @@ -87,6 +87,8 @@ plugins/*/tmp/ # Local ABI plugin copies (use `marqdo ext add quantum` / cargo build) /ext/native/ +# Install-root path hints from `marqdo ext add` — never belong in the source tree +/ext/*.plugin # Go web plugin c-shared build output (./scripts/build-web-plugin.sh) /plugins/web/build/ diff --git a/doc/design/ext-cli.md b/doc/design/ext-cli.md index f1730e3..d0d9851 100644 --- a/doc/design/ext-cli.md +++ b/doc/design/ext-cli.md @@ -94,7 +94,7 @@ web.plugin # absolute path hint | `llm` | `ai/llm.mq.md`, `ai/大模型.mq.md` | | `agent` | `ai/agent.mq.md`, `ai/智能体.mq.md`, **native `agent`** | | `web` | `web/web.mq.md`, `web/网页.mq.md`, **native `web`** | -| `quantum` | `quantum/quantum.mq.md`, `quantum/量子.mq.md`, **native `quantum`** | +| `quantum` | `quantum/`(含 `量子/` 中文树), **native `quantum`** | ## Release assets (native) diff --git a/doc/design/ext-index-skill-tools.md b/doc/design/ext-index-skill-tools.md new file mode 100644 index 0000000..c85a103 --- /dev/null +++ b/doc/design/ext-index-skill-tools.md @@ -0,0 +1,88 @@ +# 扩展库:index 即代码 · 文档 · SKILL · tools + +| | | +|---|---| +| 状态 | **Active** | +| 日期 | 2026-11-06 | +| 愿景 | [doc/next/012.md](../next/012.md)(手写真相源,本文不修改它) | +| 试点 | `ext/quantum/` | +| 相关 | [ext-abi.md](ext-abi.md) · [ext-quantum.md](ext-quantum.md) · [lib-code-as-docs.md](lib-code-as-docs.md) · [function-as-table-semantics.md](function-as-table-semantics.md) | + +--- + +## 0. 一句话 + +扩展包里**每一份** `.mq.md` 同时是可执行代码、可读 SKILL、以及可 `marqdo call` 的 tools 面;**函数即工具**,`###` 即子工具;禁止第二套 catalog / OpenAPI 真相源。 + +--- + +## 1. 整包统一作者契约(无例外) + +适用于包内全部 `.mq.md`(含 `index`、子依赖、`_capability`、兼容层、中英镜像): + +| 要求 | 含义 | +|------|------| +| 代码 | 标记可执行;实现可薄委托 ABI / 兄弟模块 | +| SKILL | `#` 下写清领域、何时用、**For AI agents → `marqdo call` 本文件** | +| tools | `##` / `###` 即工具树;无旁路 schema | +| 版式 | **形参契约表紧贴标题下**;**返回契约表在体末**(返回标记前) | +| 叙述 | 每个函数单元叙述占比 **≥ 50%**;公式与约定写进人话 | +| 禁止 | `+` 清单当主表面;ABI 名罗列充文档;「内部文件免检」 | + +形参仍由叙述/体中的 `` `名` `` 推断 arity;`| 参数 | 类型 | 说明 |` 为契约表(见 `tests/contracts/`)。 + +--- + +## 2. 包布局(quantum 试点) + +```text +ext/quantum/ + index.mq.md # EN 根 SKILL:无上下文也能照抄 marqdo call + circuit/index.mq.md # call 工具 + 作者 # circuit + gate/ · simulate/ · state/ · density/ · viz/ + _capability/index.mq.md + 量子/ # ZH 同包(勿再把 量子/ 抬到 ext/ 顶层) + 索引.mq.md + 电路/ · 门/ · 模拟/ · 态/ · 密度/ · 可视化/ · 能力/ +``` + +`index` = 总图与编排,必须写明 FILE/FUNCTION/`--effects plugin`;每个子目录的 `index.mq.md` 单独拿到也要能执行。无单独「兼容层」文件。 + +--- + +## 3. `marqdo call` 与会话 + +```text +marqdo call [k=v…] + [--json] [--backend tree|bytecode] + [--effects none|plugin] # 默认 none + [--session ] + [--toget ] # 或尾部 toget +``` + +- 默认:仅纯函数(今日行为)。 +- `--effects plugin`:允许 `plugin.call`(及附属的 `output.write`);仍拒绝 fs.write / network / process.exec / llm 等。 +- `toget` + `--session`:绑定写入 `.marqdo/call-sessions/.json`;参数 `$name` 引用会话值;跨进程 **plugin 句柄经 journal 重放** 重建。 +- 嵌套子工具:`parent.child`(`###` 路径)。 + +值字面量:整数/小数/引号文本/True|False|None;以 `[` / `{` 开头时按 JSON 解析为 List/Map。 + +--- + +## 4. 叙述 ≥ 50% + +`marqdo check --narrative-ratio`(及 `lib/lint/narrative.mq.md` skill)按函数单元统计叙述字符占比;`ext/quantum/**/*.mq.md` **全量零豁免**。 + +--- + +## 5. 与 ADR 0007 + +作者程序与业务路径仍不写 `ensure_plugin` / `host_*`;插件经 `_capability` / facade 加载。Agent 用 `--effects plugin` 调用 facade,不把 capability 当日常工具(文件本身仍须达标 skill)。 + +--- + +## 6. 修订历史 + +| 日期 | 说明 | +|------|------| +| 2026-11-06 | 初稿:012 试点契约、call effects/toget、quantum 模块树 | diff --git a/doc/design/ext-quantum-q7.md b/doc/design/ext-quantum-q7.md index fe594a6..3042988 100644 --- a/doc/design/ext-quantum-q7.md +++ b/doc/design/ext-quantum-q7.md @@ -88,7 +88,7 @@ ## 4. 作者面 API -### 4.1 英文(`ext/quantum/quantum.mq.md`) +### 4.1 英文(`ext/quantum/circuit/index.mq.md`) 在既有 `# circuit` / `# gate` 之外增加(或扩展方法): diff --git a/doc/design/ext-quantum.md b/doc/design/ext-quantum.md index aba6da1..7479888 100644 --- a/doc/design/ext-quantum.md +++ b/doc/design/ext-quantum.md @@ -72,7 +72,7 @@ math 是**高中符号与曲线**;quantum 是**离散希尔伯特空间上的 1. **仅 ABI 插件接入**:`plugins/quantum` → `libquantum.so`;L1 在 `ext/quantum/*.mq.md`。 2. **`ext/quantum/**` 禁止 `host_*`**;经 `plugin.native_path` + `plugin.load`(同 web/agent)。 -3. **中英分文件**:`quantum.mq.md` / `量子.mq.md`,**禁止**混排 API([stdlib-i18n.md](stdlib-i18n.md))。 +3. **中英分文件**:同一包 `ext/quantum/` 内英文模块树 + `量子/` 中文树,**禁止**混排 API([stdlib-i18n.md](stdlib-i18n.md))。 4. **不改核心语法**;电路表单元格保持字面量;门名/比特下标由类方法解析。 5. **模拟器有硬上限**(默认 ≤ 12 qubits);超限报错,不静默截断。 6. **view 必须有专项展示**(结构卡 + 执行区 SVG),禁止只 dump JSON。 @@ -81,17 +81,31 @@ math 是**高中符号与曲线**;quantum 是**离散希尔伯特空间上的 ## 3. 布局与安装 +Skill / tools 树(012 试点,见 [ext-index-skill-tools.md](ext-index-skill-tools.md)): + ```text -ext/quantum/ - quantum.mq.md # 英文类 API - 量子.mq.md # 中文类 API +ext/quantum/ # 一个扩展包(同 web/ai:中英同目录) + index.mq.md # EN 根 SKILL + circuit/ · gate/ · simulate/ · state/ · density/ · viz/ + _capability/index.mq.md + 量子/ # ZH 根与模块(同等 skill 标准) + 索引.mq.md + 电路/ · 门/ · 模拟/ · 态/ · 密度/ · 可视化/ · 能力/ plugins/quantum/ Cargo.toml - src/lib.rs # ABI v2:线性代数 / 施门 / 画 SVG -examples/quantum-bell/ # 规范示例(Q3) + src/lib.rs # ABI v2 +examples/quantum-bell/ tests/ext/quantum-*.mq.md ``` +安装产物(`~/.marqdo/ext` 或 `MARQDO_EXT`,**不是**仓库 `ext/` 源码树): + +```text +quantum/... +native/libquantum.so +quantum.plugin # 绝对路径提示;勿提交 +``` + ```bash cargo build -p marqdo_plugin_quantum marqdo ext add quantum @@ -102,11 +116,11 @@ marqdo ext add quantum ```markdown --- import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- ``` -或中文:`导入 量子:ext/quantum/量子.mq.md`。 +或中文:`导入 量子:ext/quantum/量子/电路/索引.mq.md`(根 skill:`ext/quantum/量子/索引.mq.md`)。 --- @@ -152,7 +166,7 @@ $$ ## 5. 作者面 API(锁定草图) -### 5.1 英文 `ext/quantum/quantum.mq.md` +### 5.1 英文 `ext/quantum/circuit/index.mq.md` ```markdown # gate @@ -199,7 +213,7 @@ $$ 门方法返回**更新后的 circuit 句柄**(与 web `compose_*` 相同:`` `qc` = > `qc`.h qubit=0 *``)。 -### 5.2 中文 `ext/quantum/量子.mq.md` +### 5.2 中文 `ext/quantum/量子/`(根 `索引.mq.md`) | 英文 | 中文 | |------|------| @@ -343,7 +357,7 @@ Q5 教学噪声 + barrier/measure/append/state — 见 [ext-quantum-q5.md](ext- --- title: Bell state import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # Bell |Φ+⟩ diff --git a/doc/next/012.md b/doc/next/012.md new file mode 100644 index 0000000..1c868f3 --- /dev/null +++ b/doc/next/012.md @@ -0,0 +1,66 @@ +--- +title: 作者对于marqdo的价值认识 +author: cflmy +--- + +# main + +诚实的说,作者其实一直都很纠结说marqdo是否具有存在的必要,不过在逐渐的开发和了解中,marqdo +是有价值的,我此时此刻确信这一点。 + +在过去的很长时间中,我一直在思考,marqdo代码即文档,文档即知识库,知识库可执行有什么作用呢? + +## code as document,document as skill,skill is tools + +现在我给出的答案是,code as document,document as skill,skill is tools. + +试想一个.mq.md文件,只需要撰写下来,智能体只需要每次执行: +``` +marqdo call 文件名 函数名 函数参数 +``` +就能直接的得到执行结果,之后进行下一步的判断,更近一步,我们甚至可以在函数内写分支,但是让智能体决定走哪一个分支,让skill和tools不再强行分离。 + +甚至更近一步 + +``` +marqdo call 文件名 函数名 函数参数 toget 返回值 +``` + +得到返回值,在同一个会话进行多次的操作,之后记录下来,我们以后必定能够复现出来。 + +再进一步呢,智能体的输出就是marqdo脚本,只需要单步运行就能够得到结果。 + +## ABI插件 + +除此之外还有编程语言的特色,ABI插件,在deepseek harness中插件被证明是skill、mcp等的极好 +接入方式,那么有没有可能marqdo可以实现每一个插件都是通过ABI接入的? + +我想答案似乎是可以的。 + +这种情况下拓展库应该怎么设计呢? + +我觉得应该按照模块设计 + +index.mq.md + 依赖1 + …… + 依赖2 + …… + +其中index.mq.md就是这个拓展库的SKILL文档,AI只需要阅读这个文档就知道该怎么使用这个拓展库。 + +甚至更近一步的,index.mq.md本身就是一个可执行的文档,包含拓展库的全部功能。 + +## 叙述代码是否足够? + +我想叙述性文字在AI编程中是非常重要的,所以,我在这里提出一个编程规范: + +> 所有的函数叙述性文字必须和实际文字混合且超过50% + +进行**校验**如果通过则**通过**否则**不通过** + +这应该是我写的第一个SKILL即tools吧 + +所有的拓展库都要规划成为这样。 + +skill即tools有一个绝妙的地方那就是tools是函数,函数本身就对应一个操作,这个操作就是一个工具,所以每个skill都只需要调用本身就可以是tools了,同时marqdo的设计中包含有### 更深层的函数,这就是子工具了 \ No newline at end of file diff --git a/examples/oa2026-showcase/bell.mq.md b/examples/oa2026-showcase/bell.mq.md index b308d33..dc34002 100644 --- a/examples/oa2026-showcase/bell.mq.md +++ b/examples/oa2026-showcase/bell.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: 贝尔态:两个量子比特如何一起回答 description: 从一条假设开始,搭电路、看概率、画图,并用断言验收。 import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/examples/quantum-bell/index.mq.md b/examples/quantum-bell/index.mq.md index 69eeb16..5e145c2 100644 --- a/examples/quantum-bell/index.mq.md +++ b/examples/quantum-bell/index.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: Bell state description: H then CX; probabilities ≈ 1/2; circuit SVG. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md math: lib/math.mq.md json: lib/json.mq.md --- diff --git a/examples/quantum-entanglement/index.mq.md b/examples/quantum-entanglement/index.mq.md index c020da3..4112217 100644 --- a/examples/quantum-entanglement/index.mq.md +++ b/examples/quantum-entanglement/index.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: Entanglement lab description: Bell state — density, partial trace, Schmidt, themed SVG (Q7/Q8). import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md math: lib/math.mq.md --- diff --git a/examples/quantum-ghz/index.mq.md b/examples/quantum-ghz/index.mq.md index 7b5d023..121ac54 100644 --- a/examples/quantum-ghz/index.mq.md +++ b/examples/quantum-ghz/index.mq.md @@ -3,7 +3,8 @@ markup: occlusion title: GHZ state description: 3-qubit GHZ; |000⟩/|111⟩ ≈ 1/2; probs + H matrix heatmap. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md + gate: ext/quantum/gate/index.mq.md --- # GHZ @@ -24,7 +25,7 @@ H on qubit 0, CX(0→1), CX(0→2). Ideal: |000⟩ and |111⟩ each with probabi **p = > qc.probabilities** **_ = > qc.draw path="ghz.svg"** **_ = > qc.draw kind="probs" path="ghz-probs.svg"** -**H = > quantum.gate name="H"** +**H = > gate.gate name="H"** **_ = > H.draw kind="matrix" path="ghz-h-matrix.svg"** > print text=`p` diff --git a/examples/quantum-skill-call/index.mq.md b/examples/quantum-skill-call/index.mq.md new file mode 100644 index 0000000..fb3ae94 --- /dev/null +++ b/examples/quantum-skill-call/index.mq.md @@ -0,0 +1,21 @@ +--- +markup: occlusion +title: Quantum skill call demo +description: >- + Agent-style flow via ext/quantum index and domain modules (Bell probabilities). +import: + circuit: ext/quantum/circuit/index.mq.md + simulate: ext/quantum/simulate/index.mq.md +--- + +# main + +Build Phi-plus with domain skills, then print ideal probabilities. Prefer the +same steps via marqdo call with --effects plugin and toget when an agent drives +the session. + +**qc = > circuit.new qubits=2 steps=None** +**qc = > circuit.hadamard circuit=`qc` qubit=0** +**qc = > circuit.cnot circuit=`qc` control=0 target=1** +**p = > simulate.probabilities circuit=`qc`** +> print text=`p` diff --git a/ext/quantum/_capability/index.mq.md b/ext/quantum/_capability/index.mq.md new file mode 100644 index 0000000..bb45a1d --- /dev/null +++ b/ext/quantum/_capability/index.mq.md @@ -0,0 +1,49 @@ +--- +markup: occlusion +title: ext/quantum/_capability +description: >- + Quantum ABI load skill. Prefer domain modules; call load when diagnosing plugins. +import: + plugin: lib/plugin.mq.md + sys: lib/sys.mq.md +--- + +Capability + +This file is still a skill and a tool surface. It exists so the quantum package +can load the native ABI plugin once. Everyday author programs and agents should +call domain modules which invoke load for you. Reach for this page when checking +whether the plugin is installed, not when building a Bell state. + +## For AI agents + +If you were given only this file, use it only to check the plugin. Day-to-day work +should call circuit or simulate modules instead. + +Call example (plain text): + marqdo call ext/quantum/_capability/index.mq.md load --effects plugin --json + +*None* + +## load + +Locate the ABI v2 quantum shared library through plugin.native_path, then +plugin.load it. If the library is missing, print a short install hint and exit +non-zero so CI and agents fail loudly. After a successful load, later quantum +star names are available in this process. This is the only sanctioned place in +the package that talks to lib/plugin for quantum. Domain skills call load at the +start of each tool that needs the simulator. + +This tool takes no parameters. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | null after a successful load | + +**p = > plugin.native_path name="quantum"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum) + > sys.exit code=1 +**** diff --git a/ext/quantum/circuit/index.mq.md b/ext/quantum/circuit/index.mq.md new file mode 100644 index 0000000..05d249c --- /dev/null +++ b/ext/quantum/circuit/index.mq.md @@ -0,0 +1,320 @@ +--- +markup: occlusion +title: ext/quantum/circuit +description: >- + Quantum circuit skill — wires, step tables, and applying gates. +import: + cap: ext/quantum/_capability/index.mq.md + density: ext/quantum/density/index.mq.md +--- + +Circuit + +A circuit is an ordered list of gates on n wires, starting from the all-zero +ket. You can build it with method-style steps with author method chains on this file, or +call the tools here. A steps table is a readable program. Measurement rows mark +which bits simulate.run should report; they do not collapse the ideal state +vector used by probabilities. + +## For AI agents +If you were given only this file, you still know how to run it. Every ## heading +below is a tool. Execute with the shell. Always include --effects plugin. + +Create a two-qubit circuit and save it as qc: + +Call example (plain text): + marqdo call ext/quantum/circuit/index.mq.md new qubits=2 --effects plugin --session s --toget qc --json + +Apply Hadamard on qubit 0: + +Call example (plain text): + marqdo call ext/quantum/circuit/index.mq.md hadamard circuit=$qc qubit=0 --effects plugin --session s --toget qc --json + +Apply CNOT from 0 to 1: + +Call example (plain text): + marqdo call ext/quantum/circuit/index.mq.md cnot circuit=$qc control=0 target=1 --effects plugin --session s --toget qc --json + +Then open ext/quantum/simulate/index.mq.md for probabilities. Author programs may +import this file and construct the circuit object named circuit (method chain h, +cx, …). Agents should prefer marqdo call on the ## tools above. + +## new +Create a state-vector circuit of width `qubits`=1 by default. Optional +`steps`=None means no preloaded gates; when a table is provided it is parsed +like the author API. + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubits | number | wire count | +| steps | any | optional gate table or None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | new circuit handle | + +> cap.load +*> quantum_circuit_new qubits=`qubits` steps=`steps`* + +## hadamard +Apply Hadamard on wire `qubit`=0 of an existing `circuit` by default. Prefer +this when an agent already holds a circuit from new or toget. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | existing circuit | +| qubit | number | target wire | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | updated circuit | + +> cap.load +*> quantum_h circuit=`circuit` qubit=`qubit`* + +## cnot +Controlled-NOT on `circuit` from `control`=0 to `target`=1 by default. Together +with hadamard this prepares a Bell pair on two wires. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | existing circuit | +| control | number | control wire | +| target | number | target wire | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | updated circuit | + +> cap.load +*> quantum_cx circuit=`circuit` control=`control` target=`target`* + +## barrier +Insert a visual barrier on `circuit`. The state does not change; drawings show a +separator so lectures can mark logical layers. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | existing circuit | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | circuit with barrier recorded | + +> cap.load +*> quantum_barrier circuit=`circuit`* + +## measure_mark +Mark computational-basis readout on `circuit` for later simulate.run. This does +not collapse the ideal state used by probabilities. Pass `qubits`=None to mark +every wire. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | existing circuit | +| qubits | any | wire list or None for all | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | circuit with measure markers | + +> cap.load +*> quantum_measure circuit=`circuit` qubits=`qubits`* + +# circuit + + `qubits`=1 + + `steps`=None + +State-vector circuit on n wires (default all-zero ket). Optional steps= preloads a gate table. Methods append gates and return a fresh handle for chaining. Agents should prefer the ## call tools above; authors use this object for readable method chains in programs. + +> cap.load +*> quantum_circuit_new qubits=`qubits` steps=`steps`* + +## h + + `qubit`=0 + +Apply the Hadamard gate on the chosen wire. This creates equal superposition from computational basis states and is the first step of Bell and GHZ recipes. Returns an updated circuit handle so authors can chain without in-place mutation. + +*> quantum_h circuit=`self` qubit=`qubit`* + +## x + + `qubit`=0 + +Apply Pauli X (bit flip) on the chosen wire. Useful for preparing |1⟩ from |0⟩ or sandwiching phase gates. Returns the updated circuit handle for further chaining. + +*> quantum_x circuit=`self` qubit=`qubit`* + +## y + + `qubit`=0 + +Apply Pauli Y on the chosen wire. Combines bit and phase flip; returns the updated circuit handle for further chaining in author programs. + +*> quantum_y circuit=`self` qubit=`qubit`* + +## z + + `qubit`=0 + +Apply Pauli Z (phase flip) on the chosen wire. Often used in H–Z–H sandwiches that realize an effective X. Returns the updated circuit handle. + +*> quantum_z circuit=`self` qubit=`qubit`* + +## s + + `qubit`=0 + +Apply the phase gate S (√Z) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. + +*> quantum_s circuit=`self` qubit=`qubit`* + +## t + + `qubit`=0 + +Apply the phase gate T (π/8) on the chosen wire. Returns the updated circuit handle for further chaining in lecture circuits. + +*> quantum_t circuit=`self` qubit=`qubit`* + +## i + + `qubit`=0 + +Apply the identity on the chosen wire. Acts as a no-op spacer in step tables or noise experiments while keeping the wire explicit. Returns the updated handle. + +*> quantum_i circuit=`self` qubit=`qubit`* + +## rx + + `qubit`=0 + + `theta` + +Rotate the chosen wire about the X axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. + +*> quantum_rx circuit=`self` qubit=`qubit` theta=`theta`* + +## ry + + `qubit`=0 + + `theta` + +Rotate the chosen wire about the Y axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. + +*> quantum_ry circuit=`self` qubit=`qubit` theta=`theta`* + +## rz + + `qubit`=0 + + `theta` + +Rotate the chosen wire about the Z axis by angle theta in radians. Continuous single-qubit control for variational and teaching demos. Returns the updated circuit handle. + +*> quantum_rz circuit=`self` qubit=`qubit` theta=`theta`* + +## cx + + `control`=0 + + `target`=1 + +Apply CNOT from control to target. This is the standard entangling step in Bell and GHZ preparations. Returns the updated circuit handle for chaining. + +*> quantum_cx circuit=`self` control=`control` target=`target`* + +## cz + + `control`=0 + + `target`=1 + +Apply controlled-Z between control and target. Creates phase entanglement without flipping bits. Returns the updated circuit handle for chaining. + +*> quantum_cz circuit=`self` control=`control` target=`target`* + +## swap + + `a`=0 + + `b`=1 + +Exchange the two wires named by a and b. Useful when routing logical qubits in a teaching layout. Returns the updated circuit handle. + +*> quantum_swap circuit=`self` a=`a` b=`b`* + +## barrier + +Record a visual barrier only. The ideal state vector is unchanged; use barriers to separate lecture stages when drawing circuit rails. + +*> quantum_barrier circuit=`self`* + +## measure + + `qubits`=None + +Mark computational-basis readout wires for later run sampling. This does not collapse the ideal state used by probabilities. Pass qubits=None to mark every wire. + +*> quantum_measure circuit=`self` qubits=`qubits`* + +## append + + `op` + +Append another circuit’s operation list, or a gate/qubits record table, onto this circuit. Returns the combined circuit handle so programs can compose fragments. + +*> quantum_append circuit=`self` op=`op`* + +## apply + + `gate` + + `qubits`=0 + +Apply a gate handle (built-in name or custom unitary matrix) onto qubits given as an int or a list. Returns the updated circuit handle for further chaining. + +*> quantum_apply circuit=`self` gate=`gate` qubits=`qubits`* + +## noise + + `kind` + + `p` + +Attach teaching noise of the given kind and strength for run trajectories. Ideal simulate and probabilities paths ignore this channel by design. + +*> quantum_noise circuit=`self` kind=`kind` p=`p`* + +## simulate + +Return ideal state-vector amplitudes as re/im pairs for the current circuit. Teaching noise attached to the circuit is ignored on this ideal path. + +*> quantum_simulate circuit=`self`* + +## state + +Return the ideal state object with the same amplitudes as simulate. Prefer this when later fidelity or density tools expect a state handle rather than raw amplitudes. + +*> quantum_state circuit=`self`* + +## probabilities + +Map basis labels to ideal probabilities. Labels treat qubit 0 as the rightmost bit. Teaching noise is ignored so results match the pure statevector story. + +*> quantum_probabilities circuit=`self`* + +## run + + `shots`=1024 + + `seed`=1 + +Sample computational-basis shots from this circuit. Defaults are shots=1024 and seed=1 for reproducible replays. Applies teaching noise when a noise channel was attached. + +*> quantum_run circuit=`self` shots=`shots` seed=`seed`* + +## draw + + `path`=None + + `kind`=circuit + + `qubit`=0 + + `theme`=dark + +Render an SVG figure for circuit rails, probability bars, Bloch spheres, or advanced density kinds. Theme tokens are dark, light, and bw. Optional path writes the file for CLI or view embedding. + +*> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit` theme=`theme`* + +## density + +Build the pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulation of this circuit. Use density-module tools for mixed states and partial traces. + +*> quantum_density_from_state state=`self`* + +## expect + + `obs` + +Compute the expectation value of a Pauli string (left end = high bit) or an explicit matrix on this circuit’s ideal density. Teaching noise is ignored. + +*> quantum_density_expect density=`self` obs=`obs`* + +## schmidt + + `cut`=1 + +Perform a bipartite Schmidt decomposition of the ideal state. The cut argument is the number of qubits in subsystem A counted from the low bits. + +*> quantum_schmidt state=`self` cut=`cut`* diff --git a/ext/quantum/density/index.mq.md b/ext/quantum/density/index.mq.md new file mode 100644 index 0000000..fb7f115 --- /dev/null +++ b/ext/quantum/density/index.mq.md @@ -0,0 +1,172 @@ +--- +markup: occlusion +title: ext/quantum/density +description: >- + Density-operator skill — mixed states, partial trace, expectations. +import: + cap: ext/quantum/_capability/index.mq.md +--- + +Density + +A density operator describes pure and mixed states together. Pure states have +purity one; mixing lowers purity. Build rho from a circuit or state, or from an +explicit Hermitian matrix. Partial trace discards subsystems. Expectation values +take Pauli strings or matrices. + +## For AI agents +If you were given only this file, build or inspect density operators with marqdo +call and --effects plugin. + +Call example (plain text): + marqdo call ext/quantum/density/index.mq.md from_state state=$qc --effects plugin --toget rho --json + marqdo call ext/quantum/density/index.mq.md purity density=$rho --effects plugin --json + +Author programs may use the density object on this file. + +## from_state +Form rho as the outer product of a pure `state` (or the ideal state of a +circuit). Use this when you trust the pure-state picture and want mixed-state +tools without writing a matrix by hand. + +| 参数 | 类型 | 说明 | +|------|------|------| +| state | any | pure state or circuit | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | density handle | + +> cap.load +*> quantum_density_from_state state=`state`* + +## from_matrix +Build rho from an explicit Hermitian `matrix`. Pair with formula blocks in the +lecture so the matrix on the page is the matrix in the simulator. Size is +limited by the plugin. + +| 参数 | 类型 | 说明 | +|------|------|------| +| matrix | any | Hermitian matrix | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | density handle | + +> cap.load +*> quantum_density_from_matrix matrix=`matrix`* + +## purity +Compute the trace of rho squared for `density`. Values near one mean nearly +pure; lower values mean classical mixing or traced-out entanglement. + +| 参数 | 类型 | 说明 | +|------|------|------| +| density | any | density operator | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | purity | + +> cap.load +*> quantum_density_purity density=`density`* + +## partial_trace +Keep listed qubits in `keep` and trace out the rest of `density`. Indices use +LSB equals zero. The result is generally mixed even when the joint state was +pure. + +| 参数 | 类型 | 说明 | +|------|------|------| +| density | any | joint density | +| keep | any | qubit index list to keep | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | reduced density | + +> cap.load +*> quantum_density_partial_trace density=`density` keep=`keep`* + +## expect +Expectation of observable `obs` on `density`. Pauli strings use left equals +high bit. Pass a matrix when the observable is not a Pauli product. + +| 参数 | 类型 | 说明 | +|------|------|------| +| density | any | density operator | +| obs | any | Pauli string or matrix | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | expectation value | + +> cap.load +*> quantum_density_expect density=`density` obs=`obs`* + +## eig +Hermitian spectrum of `density` as eigenvalues and eigenvectors. Useful when a +lecture needs the eigenbasis of rho. + +| 参数 | 类型 | 说明 | +|------|------|------| +| density | any | Hermitian density | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | eigenvalues and eigenvectors | + +> cap.load +*> quantum_density_eig density=`density`* + +# density + + `state`=None + + `matrix`=None + +Construct a density operator from a pure state or circuit (state=) or from an explicit Hermitian matrix=. Density operations support at most six qubits. Pure and mixed states share this object surface for purity, partial trace, and expectation. + +> cap.load +1. `matrix` + *> quantum_density_from_matrix matrix=`matrix`* +2. * + *> quantum_density_from_state state=`state`* + +## matrix + +Return the explicit matrix of this density operator so authors can inspect entries or hand the array to further linear-algebra steps outside the quantum package. + +*> quantum_density_matrix density=`self`* + +## purity + +Compute Tr(ρ²). Values near one mean a pure state; mixed states are strictly less than one. Use this as a quick entanglement or decoherence check after a partial trace. + +*> quantum_density_purity density=`self`* + +## partial_trace + + `keep` + +Trace out every qubit except those listed in keep (LSB index 0). Returns the reduced density on the kept subsystem for entanglement lectures and purity checks. + +*> quantum_density_partial_trace density=`self` keep=`keep`* + +## eig + +Compute the Hermitian spectrum of this density operator as eigenvalues and eigenvectors. Handy for lecture plots and for verifying that a constructed rho is physical. + +*> quantum_density_eig density=`self`* + +## expect + + `obs` + +Expectation value of observable obs on this density. obs may be a Pauli string with the left end as the high bit, or an explicit matrix matching the density dimension. + +*> quantum_density_expect density=`self` obs=`obs`* + +## draw + + `path`=None + + `kind`=hinton + +Draw a Hinton diagram, city plot, density grid, or Pauli vector for this density. Optional path writes SVG; kind selects which visual metaphor the lecture uses. + +*> quantum_density_draw density=`self` path=`path` kind=`kind`* diff --git a/ext/quantum/gate/index.mq.md b/ext/quantum/gate/index.mq.md new file mode 100644 index 0000000..5991a77 --- /dev/null +++ b/ext/quantum/gate/index.mq.md @@ -0,0 +1,150 @@ +--- +markup: occlusion +title: ext/quantum/gate +description: >- + Quantum gate skill — unitaries as formulas, named gates, matrix checks. +import: + cap: ext/quantum/_capability/index.mq.md +--- + +Gate + +A gate is a unitary on one or more qubits. This skill writes the matrix in +lecture form, then builds a gate handle. Circuits apply gates; this page defines +what they are. Custom unitaries use the same path with a matrix argument from a +formula block or nested list. + +## For AI agents +If you were given only this file, run tools with marqdo call and --effects plugin. +FUNCTION is the ## name. Example Hadamard gate handle: + +Call example (plain text): + marqdo call ext/quantum/gate/index.mq.md hadamard --effects plugin --json + +Custom unitary: pass matrix= as JSON or a prior toget. matches checks a gate +against a matrix. Author programs may also use the gate object constructor on +this file. + +## hadamard +The Hadamard gate creates equal superposition from computational basis states. +Its matrix in the computational basis is one over square-root two times the +matrix with ones on the first row and one then minus one on the second row. +So H on ket-zero yields an equal plus combination, and H on ket-one yields an +equal minus combination. This tool returns a named gate handle for later apply. + +This tool takes no parameters. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Hadamard gate handle | + +> cap.load +*> quantum_gate_new name="H" theta=None matrix=None* + +## pauli_x +Pauli X is the bit-flip gate: a two-by-two matrix that swaps ket-zero and +ket-one. Use it when a lecture needs an explicit NOT on the computational basis. + +This tool takes no parameters. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Pauli X handle | + +> cap.load +*> quantum_gate_new name="X" theta=None matrix=None* + +## pauli_z +Pauli Z applies a phase of minus one to ket-one while leaving ket-zero alone. +Its diagonal matrix is the standard computational-basis Z. + +This tool takes no parameters. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | Pauli Z handle | + +> cap.load +*> quantum_gate_new name="Z" theta=None matrix=None* + +## cnot +The controlled-NOT on two qubits flips the target when the control is ket-one. +Wire order and bit-endianness follow the package convention where qubit 0 is the +rightmost label bit. Prefer applying via circuit tools with explicit control and +target indices when building lectures step by step. + +This tool takes no parameters. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | CNOT gate handle | + +> cap.load +*> quantum_gate_new name="CX" theta=None matrix=None* + +## custom +Build a gate from an explicit unitary given as `matrix`. Authors usually bind a +formula matrix first, then pass that binding. Optional label `name`="U" marks +drawings when the caller omits a name. + +| 参数 | 类型 | 说明 | +|------|------|------| +| matrix | any | unitary matrix formula or list | +| name | text | optional label defaulting to U | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | custom gate handle | + +> cap.load +*> quantum_gate_new name=`name` theta=None matrix=`matrix`* + +## matches +Teaching check: does `gate` match expected `matrix` within absolute tolerance +`tol`=0.000000001? Use after defining a formula so the lecture and the simulator +cannot drift apart. + +| 参数 | 类型 | 说明 | +|------|------|------| +| gate | any | gate handle to test | +| matrix | any | expected unitary | +| tol | number | absolute tolerance | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | bool | True when matrices match | + +> cap.load +*> quantum_gate_matches_matrix gate=`gate` matrix=`matrix` tol=`tol`* + +# gate + + `name`=None + + `theta`=None + + `matrix`=None + +Named built-in gate (name=H) or a custom unitary defined by matrix= (nested lists or a formula matrix fence). Custom gates may set name= (default U). Authors and call-style tools share this object surface. + +> cap.load +*> quantum_gate_new name=`name` theta=`theta` matrix=`matrix`* + +## matrix + +Return the explicit unitary matrix of this gate handle. Use it to inspect entries or to feed matches_matrix after constructing a gate from a formula. + +*> quantum_gate_matrix gate=`self`* + +## matches_matrix + + `matrix` + + `tol`=0.000000001 + +Check whether this gate matches the given matrix within absolute tolerance tol. Typical after building a custom gate from a Markdown formula fence in a lecture notebook. + +*> quantum_gate_matches_matrix gate=`self` matrix=`matrix` tol=`tol`* + +## draw + + `path`=None + + `kind`=gate + +Draw a gate symbol or a complex-matrix heatmap (kind=gate or matrix). Optional path writes SVG to disk; plots also enter view/CLI through record_plot for the session. + +*> quantum_gate_draw gate=`self` path=`path` kind=`kind`* diff --git a/ext/quantum/index.mq.md b/ext/quantum/index.mq.md new file mode 100644 index 0000000..910ba4c --- /dev/null +++ b/ext/quantum/index.mq.md @@ -0,0 +1,193 @@ +--- +markup: occlusion +title: ext/quantum +description: >- + Quantum package root skill. Read this file first. Every tool runs with marqdo call. +import: + state: ext/quantum/state/index.mq.md + gate: ext/quantum/gate/index.mq.md + circuit: ext/quantum/circuit/index.mq.md + simulate: ext/quantum/simulate/index.mq.md + density: ext/quantum/density/index.mq.md + viz: ext/quantum/viz/index.mq.md +--- + +This file is the root skill for the Marqdo quantum package. If you are an AI +agent (or any program) with no other Marqdo context, follow Choose a path, then +How to execute any tool. Do not invent MCP tools, Python wrappers, or a second +API. The Markdown ## headings in these files are the tools. + +## Choose a path + +Pick one row. Do not mix English and Chinese tool names or file trees. (Do not +write Marqdo branch lines here; this table is narration only.) + +| If you need | Do this | +|-------------|---------| +| Only a Bell result | Run `bell_phi_plus` on this file (command in the next section). Stop. | +| Circuit handles to continue (draw, noise, more gates) | Copy the stepwise circuit then simulate calls under circuit module below. Keep one `--session` and `--toget qc`. | +| Chinese tool names | Open `ext/quantum/量子/索引.mq.md` instead and stay in that tree. | + +English paths stay under `ext/quantum/` (this tree). Agents should use `##` +tools via `marqdo call`. The `# circuit` / `# gate` objects on module files are +for author programs that import the module, not the default agent path. + +*None* + +## How to execute any tool + +Marqdo runs one function from a Markdown file with this shell command shape. +Copy it literally. Replace FILE, FUNCTION, and arguments. + +Call example (plain text): + marqdo call FILE FUNCTION name=value name=value --effects plugin --json + +FILE is always a path under ext/quantum/, usually ending in index.mq.md. +FUNCTION is the exact ## heading name in that file (for example new, hadamard, +probabilities). Nested ### headings use a dotted path like parent.child. +Always pass --effects plugin because the simulator is a native plugin; without +this flag marqdo call refuses the tool. Pass --json when you need the envelope +with ok and result fields. To keep a return value for the next command, add +--session some-id and --toget name (or put toget name at the end). Later +arguments may use circuit=$name. Plugin handles are rebuilt from the session +journal. Argument values may be numbers, quoted text, True, False, None, JSON +starting with [ or {, or $name session refs. Do not call ensure_plugin or any +host-star API; domain files load the plugin themselves. + +Minimal first command to verify the package (no tool arguments): + +Call example (plain text): + marqdo call ext/quantum/index.mq.md bell_phi_plus --effects plugin --json + +*None* + +## Package layout + +Open only the module you need. Each module file is also a complete skill and +repeats how to marqdo call its tools. + +The path ext/quantum/index.mq.md is this root map and the Bell demo tool. +The path ext/quantum/circuit/index.mq.md builds wires, applies H and CNOT, and +defines the author object circuit. +The path ext/quantum/gate/index.mq.md holds gate matrices as formulas and named +or custom gates. +The path ext/quantum/simulate/index.mq.md returns amplitudes, probabilities, and +noisy shots. +The path ext/quantum/state/index.mq.md covers kron, fidelity, and Schmidt. +The path ext/quantum/density/index.mq.md covers density operators and partial +trace. +The path ext/quantum/viz/index.mq.md draws SVG figures. +The path ext/quantum/_capability/index.mq.md only loads the plugin for diagnostics. + +Author programs import the same paths in frontmatter, then call module.member. +Example: import circuit from ext/quantum/circuit/index.mq.md, then use +circuit.circuit for the object constructor, or circuit.new for the call-style +tool that agents use with marqdo call. + +*None* + +## circuit module + +File path: ext/quantum/circuit/index.mq.md + +Use this when you need a quantum circuit handle. Typical agent sequence for a +two-qubit Bell preparation (copy each line as its own shell command): + +Call example (plain text): + marqdo call ext/quantum/circuit/index.mq.md new qubits=2 --effects plugin --session s1 --toget qc --json + marqdo call ext/quantum/circuit/index.mq.md hadamard circuit=$qc qubit=0 --effects plugin --session s1 --toget qc --json + marqdo call ext/quantum/circuit/index.mq.md cnot circuit=$qc control=0 target=1 --effects plugin --session s1 --toget qc --json + +Main ## tools on that file: new, hadamard, cnot, barrier, measure_mark. The same +file also defines the author object circuit with methods such as h and cx. + +*None* + +## gate module + +File path: ext/quantum/gate/index.mq.md + +Use this when you need a gate handle or a formula matrix check. + +Call example (plain text): + marqdo call ext/quantum/gate/index.mq.md hadamard --effects plugin --json + marqdo call ext/quantum/gate/index.mq.md cnot --effects plugin --json + +Main ## tools: hadamard, pauli_x, pauli_z, cnot, custom, matches. + +*None* + +## simulate module + +File path: ext/quantum/simulate/index.mq.md + +Use this when you already have a circuit handle and want amplitudes, +probabilities, or sampled shots. + +Call example (plain text): + marqdo call ext/quantum/simulate/index.mq.md probabilities circuit=$qc --effects plugin --session s1 --json + +Main ## tools: simulate, state, probabilities, run, noise. Ideal probabilities +ignore teaching noise; run applies noise when set. + +*None* + +## state module + +File path: ext/quantum/state/index.mq.md + +Use this for Kronecker product, fidelity, and Schmidt decomposition. + +Call example (plain text): + marqdo call ext/quantum/state/index.mq.md fidelity a=$psi b=$phi --effects plugin --json + +Main ## tools: kron, fidelity, schmidt. + +*None* + +## density module + +File path: ext/quantum/density/index.mq.md + +Use this for mixed states. + +Call example (plain text): + marqdo call ext/quantum/density/index.mq.md from_state state=$qc --effects plugin --toget rho --json + marqdo call ext/quantum/density/index.mq.md purity density=$rho --effects plugin --json + +*None* + +## viz module + +File path: ext/quantum/viz/index.mq.md + +Use this to draw SVG. Pass a circuit or density handle and optional path. + +Call example (plain text): + marqdo call ext/quantum/viz/index.mq.md draw_circuit circuit=$qc path="bell.svg" --effects plugin --session s1 --json + +Main ## tools: draw_circuit, draw_probs, draw_bloch, draw_density, draw_gate. + +*None* + +## bell_phi_plus + +One-shot orchestration tool on this index file. It takes no parameters. It builds +the Bell Phi-plus state with Hadamard on qubit 0 and CNOT from 0 to 1, then +returns ideal basis probabilities. Use this when you only need the demo result. +Use the stepwise circuit and simulate calls above when you need intermediate +handles. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | map of basis label to probability | + +Exact command to run this tool: + +Call example (plain text): + marqdo call ext/quantum/index.mq.md bell_phi_plus --effects plugin --json + +**qc = > circuit.new qubits=2 steps=None** +**qc = > circuit.hadamard circuit=`qc` qubit=0** +**qc = > circuit.cnot circuit=`qc` control=0 target=1** +*> simulate.probabilities circuit=`qc`* diff --git a/ext/quantum/quantum.mq.md b/ext/quantum/quantum.mq.md deleted file mode 100644 index 292bb99..0000000 --- a/ext/quantum/quantum.mq.md +++ /dev/null @@ -1,332 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/quantum -description: Official quantum circuit simulator (English). Gates + circuits; ABI plugin. -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - json: lib/json.mq.md ---- - -Official quantum circuit simulator (English). Gates + circuits; ABI plugin. - -## ensure_plugin - -Load the ABI v2 `quantum` plugin once. - -**p = > plugin.native_path name="quantum"** -1. `p` - > plugin.load path=`p` -2. * - > print text=ext/quantum: native quantum plugin not found (build marqdo_plugin_quantum or marqdo ext add quantum) - > sys.exit code=1 -**** - -## kron - + `a` - + `b` - -Tensor product of two states or square matrices. - -> ensure_plugin -*> quantum_kron a=`a` b=`b`* - -## schmidt - + `state` - + `cut`=1 - -Schmidt decomposition of a pure state / circuit across `cut` (subsystem A = low qubits). - -> ensure_plugin -*> quantum_schmidt state=`state` cut=`cut`* - -## fidelity - + `a` - + `b` - -Pure-state fidelity |⟨a|b⟩|². - -> ensure_plugin -*> quantum_fidelity a=`a` b=`b`* - -# circuit - + `qubits`=1 - + `steps`=None - -State-vector circuit (default |0…0⟩). Optional `steps=` gate table (column or row records). Methods append gates and return an updated handle. - -> ensure_plugin -*> quantum_circuit_new qubits=`qubits` steps=`steps`* - -## h - + `qubit`=0 - -Hadamard on qubit (default 0). - -*> quantum_h circuit=`self` qubit=`qubit`* - -## x - + `qubit`=0 - -Pauli X on qubit. - -*> quantum_x circuit=`self` qubit=`qubit`* - -## y - + `qubit`=0 - -Pauli Y on qubit. - -*> quantum_y circuit=`self` qubit=`qubit`* - -## z - + `qubit`=0 - -Pauli Z on qubit. - -*> quantum_z circuit=`self` qubit=`qubit`* - -## s - + `qubit`=0 - -Phase S on qubit. - -*> quantum_s circuit=`self` qubit=`qubit`* - -## t - + `qubit`=0 - -Phase T on qubit. - -*> quantum_t circuit=`self` qubit=`qubit`* - -## i - + `qubit`=0 - -Identity on qubit. - -*> quantum_i circuit=`self` qubit=`qubit`* - -## rx - + `qubit`=0 - + `theta` - -Rotate about X by theta. - -*> quantum_rx circuit=`self` qubit=`qubit` theta=`theta`* - -## ry - + `qubit`=0 - + `theta` - -Rotate about Y by theta. - -*> quantum_ry circuit=`self` qubit=`qubit` theta=`theta`* - -## rz - + `qubit`=0 - + `theta` - -Rotate about Z by theta. - -*> quantum_rz circuit=`self` qubit=`qubit` theta=`theta`* - -## cx - + `control`=0 - + `target`=1 - -CNOT: control → target. - -*> quantum_cx circuit=`self` control=`control` target=`target`* - -## cz - + `control`=0 - + `target`=1 - -Controlled-Z. - -*> quantum_cz circuit=`self` control=`control` target=`target`* - -## swap - + `a`=0 - + `b`=1 - -Swap two qubits. - -*> quantum_swap circuit=`self` a=`a` b=`b`* - -## barrier - -Visual separator only (no state change). - -*> quantum_barrier circuit=`self`* - -## measure - + `qubits`=None - -Mark computational-basis readout (`None` / empty = all qubits). Affects which bits `run` reports. - -*> quantum_measure circuit=`self` qubits=`qubits`* - -## append - + `op` - -Append another circuit's ops or a `{gate,qubits}` op map. - -*> quantum_append circuit=`self` op=`op`* - -## apply - + `gate` - + `qubits`=0 - -Apply a gate handle (named or custom `matrix=`) on `qubits` (int or list). - -*> quantum_apply circuit=`self` gate=`gate` qubits=`qubits`* - -## noise - + `kind` - + `p` - -Teaching noise for `run` trajectories (`bitflip` / `depolarizing` / `amplitude_damping`). Ignored by `simulate` / `probabilities`. - -*> quantum_noise circuit=`self` kind=`kind` p=`p`* - -## simulate - -Return state vector amplitudes `{re,im}` (ideal; no noise). - -*> quantum_simulate circuit=`self`* - -## state - -Ideal state vector (same amplitudes as `simulate`). - -*> quantum_state circuit=`self`* - -## probabilities - -Return map of basis label → probability (qubit 0 = rightmost bit). Ideal; ignores noise. - -*> quantum_probabilities circuit=`self`* - -## run - + `shots`=1024 - + `seed`=1 - -Sample computational-basis shots (deterministic with `seed=`). Applies circuit `noise` if set. - -*> quantum_run circuit=`self` shots=`shots` seed=`seed`* - -## draw - + `path`=None - + `kind`=circuit - + `qubit`=0 - + `theme`=dark - -Circuit rail / probability bars / Bloch / advanced state plots (`kind=circuit|probs|bloch|hinton|city|density|paulivec|qsphere|multibloch`). Theme `dark` (default tech lab) / `light` / `bw`. Records into view/CLI plots via host `record_plot`. - -*> quantum_draw_circuit circuit=`self` path=`path` kind=`kind` qubit=`qubit` theme=`theme`* - -## density - -Pure-state density matrix ρ=|ψ⟩⟨ψ| after ideal simulate. - -*> density state=`self`* - -## expect - + `obs` - -Pauli string (left = high bit) or matrix expectation on the ideal state. - -*> quantum_density_expect density=`self` obs=`obs`* - -## schmidt - + `cut`=1 - -Schmidt / singular values across a bipartition (`cut` = qubits in subsystem A, low bits). - -*> quantum_schmidt state=`self` cut=`cut`* - -# gate - + `name`=None - + `theta`=None - + `matrix`=None - -Named built-in gate (`name=H`) or custom unitary from `matrix=` (nested list or formula matrix fence). Optional `name=` label for custom gates (default `U`). - -> ensure_plugin -*> quantum_gate_new name=`name` theta=`theta` matrix=`matrix`* - -## matrix - -Explicit matrix of this object. - -*> quantum_gate_matrix gate=`self`* - -## matches_matrix - + `matrix` - + `tol`=0.000000001 - -Whether this gate matches matrix (tol). - -*> quantum_gate_matches_matrix gate=`self` matrix=`matrix` tol=`tol`* - -## draw - + `path`=None - + `kind`=gate - -Gate glyph or complex-matrix heatmap (`kind=gate|matrix`). Records via host `record_plot`. - -*> quantum_gate_draw gate=`self` path=`path` kind=`kind`* - -# density - + `state`=None - + `matrix`=None - -Density matrix from a state/circuit (`state=`) or an explicit Hermitian `matrix=` (≤6 qubits). - -> ensure_plugin -1. `matrix` - *> quantum_density_from_matrix matrix=`matrix`* -2. * - *> quantum_density_from_state state=`state`* - -## matrix - -Explicit matrix of this object. - -*> quantum_density_matrix density=`self`* - -## purity - -Tr(ρ²). - -*> quantum_density_purity density=`self`* - -## partial_trace - + `keep` - -Keep listed qubits (LSB=0); trace out the rest. - -*> quantum_density_partial_trace density=`self` keep=`keep`* - -## eig - -Hermitian spectrum → `{eigenvalues, eigenvectors}`. - -*> quantum_density_eig density=`self`* - -## expect - + `obs` - -Expectation value of obs. - -*> quantum_density_expect density=`self` obs=`obs`* - -## draw - + `path`=None - + `kind`=hinton - -Hinton / city / density-cells / Pauli vector SVG (`kind=hinton` or city or density or paulivec). - -*> quantum_density_draw density=`self` path=`path` kind=`kind`* diff --git a/ext/quantum/simulate/index.mq.md b/ext/quantum/simulate/index.mq.md new file mode 100644 index 0000000..1a1b519 --- /dev/null +++ b/ext/quantum/simulate/index.mq.md @@ -0,0 +1,110 @@ +--- +markup: occlusion +title: ext/quantum/simulate +description: >- + Quantum simulation skill — amplitudes, probabilities, noisy shots. +import: + cap: ext/quantum/_capability/index.mq.md +--- + +Simulate + +Simulation answers what a circuit does. Ideal paths (simulate, state, +probabilities) ignore teaching noise. The run tool draws computational-basis +shots and applies circuit noise when noise was attached. The simulator refuses +circuits wider than the plugin limit instead of silently truncating. + +## For AI agents + +If you were given only this file, you need a circuit handle from +ext/quantum/circuit/index.mq.md (usually via --toget). Then: + +Call example (plain text): + marqdo call ext/quantum/simulate/index.mq.md probabilities circuit=$qc --effects plugin --session s --json + +Other tools: simulate, state, run, noise. Always --effects plugin. + +## simulate + +Return ideal state-vector amplitudes for `circuit` as re/im entries. Noise +channels attached to the circuit are ignored here. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to evolve | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | amplitude list | + +> cap.load +*> quantum_simulate circuit=`circuit`* + +## state + +Same ideal amplitudes as simulate for `circuit`, packaged as the plugin state +object. Prefer this when later fidelity or density tools expect a state handle. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to evolve | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | ideal state | + +> cap.load +*> quantum_state circuit=`circuit`* + +## probabilities + +Map basis label to probability for the ideal state of `circuit`. Labels use +qubit 0 as the rightmost bit. Noise is ignored. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to read | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | probability map | + +> cap.load +*> quantum_probabilities circuit=`circuit`* + +## run + +Sample computational-basis outcomes from `circuit`. Defaults are `shots`=1024 +and `seed`=1 so replays are deterministic. Teaching noise is applied when set. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to sample | +| shots | number | sample count | +| seed | number | RNG seed | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | counts or shot result | + +> cap.load +*> quantum_run circuit=`circuit` shots=`shots` seed=`seed`* + +## noise + +Attach teaching noise of kind `kind` with strength `p` on `circuit`. Ideal +simulate and probability tools ignore it. Keep p small unless demonstrating +decoherence. Supported kinds include bitflip, depolarizing, and amplitude_damping. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to annotate | +| kind | text | noise family name | +| p | number | strength in the unit interval | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | circuit with noise metadata | + +> cap.load +*> quantum_noise circuit=`circuit` kind=`kind` p=`p`* diff --git a/ext/quantum/state/index.mq.md b/ext/quantum/state/index.mq.md new file mode 100644 index 0000000..80358bc --- /dev/null +++ b/ext/quantum/state/index.mq.md @@ -0,0 +1,86 @@ +--- +markup: occlusion +title: ext/quantum/state +description: >- + Quantum state skill — amplitudes, Kronecker products, fidelity, Schmidt. +import: + cap: ext/quantum/_capability/index.mq.md +--- + +State + +A pure quantum state on n qubits is a unit vector in a complex space of size +two to the n. In this package each amplitude is a map with re and im fields. +Qubit 0 is the rightmost bit in basis labels. Ideal simulation ignores teaching +noise; sampled trajectories live under the simulate skill. + +States often arrive as the result of simulate tools on a circuit. This module +answers state-to-state questions: tensor products, fidelity, and Schmidt cuts. + +## For AI agents + +If you were given only this file, run state tools with marqdo call and --effects +plugin. Example fidelity: + +Call example (plain text): + marqdo call ext/quantum/state/index.mq.md fidelity a=$psi b=$phi --effects plugin --json + +Tools: kron, fidelity, schmidt. + +## kron + +The Kronecker product of `a` and `b` builds a larger space from two smaller +ones. For state vectors this writes product states; for matrices it enlarges +operators. + +| 参数 | 类型 | 说明 | +|------|------|------| +| a | any | left factor state or matrix | +| b | any | right factor state or matrix | + +Pass handles the plugin already understands. Circuit and density objects may +participate through their registered ABI shapes when the simulator accepts them. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | tensor product | + +> cap.load +*> quantum_kron a=`a` b=`b`* + +## fidelity + +Pure-state fidelity between `a` and `b` is the squared absolute overlap. It is +one when the states coincide and zero when they are orthogonal. You may pass a +circuit handle; the plugin uses the ideal simulated state. Teaching noise is +ignored. + +| 参数 | 类型 | 说明 | +|------|------|------| +| a | any | first pure state or circuit | +| b | any | second pure state or circuit | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | fidelity in the unit interval | + +> cap.load +*> quantum_fidelity a=`a` b=`b`* + +## schmidt + +Schmidt decomposition of `state` across a cut. Subsystem A owns the lowest +`cut`=1 qubits by default. Qubit 0 is the rightmost bit. Singular values show +entanglement across the bipartition. + +| 参数 | 类型 | 说明 | +|------|------|------| +| state | any | pure state or circuit | +| cut | number | qubits in subsystem A low bits | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | singular values and factors | + +> cap.load +*> quantum_schmidt state=`state` cut=`cut`* diff --git a/ext/quantum/viz/index.mq.md b/ext/quantum/viz/index.mq.md new file mode 100644 index 0000000..ebd3666 --- /dev/null +++ b/ext/quantum/viz/index.mq.md @@ -0,0 +1,114 @@ +--- +markup: occlusion +title: ext/quantum/viz +description: >- + Quantum visualization skill — circuit rails, probabilities, Bloch, density plots. +import: + cap: ext/quantum/_capability/index.mq.md +--- + +Visualization + +Drawings turn a circuit or density into SVG for view mode or a path on disk. +Pick a kind for the figure and a theme for colors. Themes dark (default), light, +and bw share geometry so lectures can switch style without rewriting the +circuit. Start with circuit and probs kinds when unsure. + +## For AI agents + +If you were given only this file, draw with marqdo call and --effects plugin. +You need a circuit or density handle from another module (toget). + +Call example (plain text): + marqdo call ext/quantum/viz/index.mq.md draw_probs circuit=$qc path="out.svg" --effects plugin --session s --json + +## draw_circuit + +Rail diagram of gates and barriers for `circuit`. Theme `theme`="dark" by +default. Optional `path` writes SVG for CLI or view embedding. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to render | +| path | any | optional output path or None | +| theme | text | dark light or bw | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | drawing result | + +> cap.load +*> quantum_draw_circuit circuit=`circuit` path=`path` kind="circuit" qubit=0 theme=`theme`* + +## draw_probs + +Probability bars for the ideal state of `circuit`. Same theme tokens as the +rail diagram. Uses `theme`="dark" when omitted. Optional `path` for file output. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit to render | +| path | any | optional output path or None | +| theme | text | dark light or bw | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | drawing result | + +> cap.load +*> quantum_draw_circuit circuit=`circuit` path=`path` kind="probs" qubit=0 theme=`theme`* + +## draw_bloch + +Bloch sphere for one wire of `circuit`. Default `qubit`=0. Optional `path` and +`theme`="dark". Multi-qubit circuits still render one qubit reduced picture. + +| 参数 | 类型 | 说明 | +|------|------|------| +| circuit | any | circuit source | +| path | any | optional output path or None | +| qubit | number | which wire | +| theme | text | dark light or bw | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | drawing result | + +> cap.load +*> quantum_draw_circuit circuit=`circuit` path=`path` kind="bloch" qubit=`qubit` theme=`theme`* + +## draw_density + +Plot density operator `density`. Default `kind`="hinton". Optional `path`. +Choose city, density, or paulivec when the lecture uses those metaphors. + +| 参数 | 类型 | 说明 | +|------|------|------| +| density | any | density operator | +| path | any | optional output path or None | +| kind | text | hinton city density or paulivec | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | drawing result | + +> cap.load +*> quantum_density_draw density=`density` path=`path` kind=`kind`* + +## draw_gate + +Glyph or matrix heatmap for `gate`. Use `kind`="gate" by default, or matrix +when checking a custom unitary. Optional `path`. + +| 参数 | 类型 | 说明 | +|------|------|------| +| gate | any | gate handle | +| path | any | optional output path or None | +| kind | text | gate or matrix | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | drawing result | + +> cap.load +*> quantum_gate_draw gate=`gate` path=`path` kind=`kind`* diff --git a/ext/quantum/量子.mq.md b/ext/quantum/量子.mq.md deleted file mode 100644 index ae11768..0000000 --- a/ext/quantum/量子.mq.md +++ /dev/null @@ -1,332 +0,0 @@ ---- -markup: occlusion -title: ext/quantum/量子 -description: 官方量子电路模拟(中文)。门 + 电路;ABI 插件。 -import: - plugin: lib/plugin.mq.md - sys: lib/sys.mq.md - json: lib/json.mq.md ---- - -官方量子电路模拟(中文)。门 + 电路;ABI 插件。 - -## 确保插件 - -加载 ABI v2 `quantum` 插件。 - -**p = > plugin.native_path name="quantum"** -1. `p` - > plugin.load path=`p` -2. * - > print text=ext/quantum: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum) - > sys.exit code=1 -**** - -## 张量积 - + `左` - + `右` - -两态或方阵的张量积。 - -> 确保插件 -*> quantum_kron a=`左` b=`右`* - -## 施密特分解 - + `态` - + `分割`=1 - -纯态 / 电路的施密特分解。 - -> 确保插件 -*> quantum_schmidt state=`态` cut=`分割`* - -## 保真度 - + `左` - + `右` - -纯态保真度 |⟨a|b⟩|²。 - -> 确保插件 -*> quantum_fidelity a=`左` b=`右`* - -# 电路 - + `比特数`=1 - + `步骤`=None - -状态向量电路(默认 |0…0⟩)。可选 `步骤=` 门序列表。方法追加门并返回更新后的句柄。 - -> 确保插件 -*> quantum_circuit_new qubits=`比特数` steps=`步骤`* - -## 哈达玛 - + `比特`=0 - -对比特施加哈达玛(默认 0)。 - -*> quantum_h circuit=`self` qubit=`比特`* - -## 泡利X - + `比特`=0 - -对比特施加泡利 X。 - -*> quantum_x circuit=`self` qubit=`比特`* - -## 泡利Y - + `比特`=0 - -对比特施加泡利 Y。 - -*> quantum_y circuit=`self` qubit=`比特`* - -## 泡利Z - + `比特`=0 - -对比特施加泡利 Z。 - -*> quantum_z circuit=`self` qubit=`比特`* - -## 相位S - + `比特`=0 - -对比特施加相位 S。 - -*> quantum_s circuit=`self` qubit=`比特`* - -## 相位T - + `比特`=0 - -对比特施加相位 T。 - -*> quantum_t circuit=`self` qubit=`比特`* - -## 单位 - + `比特`=0 - -对比特施加单位门 / 单位矩阵。 - -*> quantum_i circuit=`self` qubit=`比特`* - -## 绕X - + `比特`=0 - + `参数` - -绕 X 旋转参数角。 - -*> quantum_rx circuit=`self` qubit=`比特` theta=`参数`* - -## 绕Y - + `比特`=0 - + `参数` - -绕 Y 旋转参数角。 - -*> quantum_ry circuit=`self` qubit=`比特` theta=`参数`* - -## 绕Z - + `比特`=0 - + `参数` - -绕 Z 旋转参数角。 - -*> quantum_rz circuit=`self` qubit=`比特` theta=`参数`* - -## 控非 - + `控制`=0 - + `目标`=1 - -控非门:控制 → 目标。 - -*> quantum_cx circuit=`self` control=`控制` target=`目标`* - -## 控相 - + `控制`=0 - + `目标`=1 - -控制相位 Z。 - -*> quantum_cz circuit=`self` control=`控制` target=`目标`* - -## 交换 - + `比特甲`=0 - + `比特乙`=1 - -交换两比特。 - -*> quantum_swap circuit=`self` a=`比特甲` b=`比特乙`* - -## 屏障 - -仅可视化分隔(不改态)。 - -*> quantum_barrier circuit=`self`* - -## 测量 - + `比特`=None - -标记计算基读出(空 = 全部比特)。影响 `运行` 报告哪些位。 - -*> quantum_measure circuit=`self` qubits=`比特`* - -## 追加 - + `操作` - -追加另一电路的 ops,或 `{gate,qubits}` 操作表。 - -*> quantum_append circuit=`self` op=`操作`* - -## 施加 - + `门` - + `比特`=0 - -将门句柄(具名或 `矩阵=` 自定义)施加到 `比特`(整数或列表)。 - -*> quantum_apply circuit=`self` gate=`门` qubits=`比特`* - -## 噪声 - + `种类` - + `概率` - -教学噪声,供 `运行` 轨迹使用(`bitflip` / `depolarizing` / `amplitude_damping`,或中文:比特翻转 / 退极化 / 振幅阻尼)。`模拟` / `概率` 忽略。 - -*> quantum_noise circuit=`self` kind=`种类` p=`概率`* - -## 模拟 - -返回态矢量振幅 `{re,im}`(理想;无噪声)。 - -*> quantum_simulate circuit=`self`* - -## 态 - -理想态矢量(与 `模拟` 相同振幅)。 - -*> quantum_state circuit=`self`* - -## 概率 - -基矢标签 → 概率(qubit 0 为最右侧比特)。理想;忽略噪声。 - -*> quantum_probabilities circuit=`self`* - -## 运行 - + `次数`=1024 - + `种子`=1 - -计算基采样(`种子=` 可复现)。若设置了电路噪声则启用。 - -*> quantum_run circuit=`self` shots=`次数` seed=`种子`* - -## 绘图 - + `路径`=None - + `种类`=circuit - + `比特`=0 - + `主题`=dark - -电路轨线 / 概率条 / 布洛赫 / 高级态图(种类 circuit、probs、bloch、hinton、city、density、paulivec、qsphere、multibloch)。主题 dark(默认科技感)/ light / bw。经 record_plot 进入 view/CLI plots。 - -*> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特` theme=`主题`* - -## 密度 - -理想模拟后的纯态密度矩阵 ρ=|ψ⟩⟨ψ|。 - -*> 密度 态=`self`* - -## 期望 - + `可观测量` - -Pauli 串(左端=高比特)或矩阵期望值。 - -*> quantum_density_expect density=`self` obs=`可观测量`* - -## 施密特 - + `分割`=1 - -二分施密特分解(`分割`=子系统 A 的比特数,低位)。 - -*> quantum_schmidt state=`self` cut=`分割`* - -# 门 - + `名`=None - + `参数`=None - + `矩阵`=None - -具名内置门(`名=H`)或由 `矩阵=`(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选 `名=`(默认 `U`)。 - -> 确保插件 -*> quantum_gate_new name=`名` theta=`参数` matrix=`矩阵`* - -## 矩阵 - -本对象的显式矩阵。 - -*> quantum_gate_matrix gate=`self`* - -## 匹配矩阵 - + `矩阵` - + `容差`=0.000000001 - -门是否匹配给定矩阵(容差)。 - -*> quantum_gate_matches_matrix gate=`self` matrix=`矩阵` tol=`容差`* - -## 绘图 - + `路径`=None - + `种类`=gate - -门符号或复矩阵热力图(`种类=gate|matrix`)。经 `record_plot` 记录。 - -*> quantum_gate_draw gate=`self` path=`路径` kind=`种类`* - -# 密度 - + `态`=None - + `矩阵`=None - -由态/电路(`态=`)或显式厄米 `矩阵=` 构造密度矩阵(≤6 比特)。 - -> 确保插件 -1. `矩阵` - *> quantum_density_from_matrix matrix=`矩阵`* -2. * - *> quantum_density_from_state state=`态`* - -## 矩阵 - -本对象的显式矩阵。 - -*> quantum_density_matrix density=`self`* - -## 纯度 - -Tr(ρ²)。 - -*> quantum_density_purity density=`self`* - -## 部分迹 - + `保留` - -保留所列比特(LSB=0),对其余求迹。 - -*> quantum_density_partial_trace density=`self` keep=`保留`* - -## 本征 - -厄米谱 → `{eigenvalues, eigenvectors}`。 - -*> quantum_density_eig density=`self`* - -## 期望 - + `可观测量` - -可观测量的期望值。 - -*> quantum_density_expect density=`self` obs=`可观测量`* - -## 绘图 - + `路径`=None - + `种类`=hinton - -Hinton / 城市 / 密度格 / 泡利向量 SVG(`种类=hinton` 或 city / density / paulivec)。 - -*> quantum_density_draw density=`self` path=`路径` kind=`种类`* diff --git a/ext/quantum/量子/可视化/索引.mq.md b/ext/quantum/量子/可视化/索引.mq.md new file mode 100644 index 0000000..ce531f1 --- /dev/null +++ b/ext/quantum/量子/可视化/索引.mq.md @@ -0,0 +1,104 @@ +--- +markup: occlusion +title: ext/quantum/量子/可视化 +description: 量子可视化 skill — 电路轨、概率条、布洛赫、密度图。 +import: + 能力: ext/quantum/量子/能力/索引.mq.md +--- + +把电路或密度画成 SVG。选择 kind 与主题。主题 dark(默认)、light、bw 几何一致。 + +## 给智能体 + +若你只拿到本文件,需要其它模块给出的电路或密度句柄(toget)。 + +调用示例(纯文本): + marqdo call ext/quantum/量子/可视化/索引.mq.md 画概率 电路=$qc 路径="out.svg" --effects plugin --session s --json + +*None* + +## 画电路 + +`电路` 的轨线图。默认 `主题`="dark"。可选 `路径` 落盘。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路 | +| 路径 | any | 可选输出路径或 None | +| 主题 | text | dark light 或 bw | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 绘图结果 | + +> 能力.加载 +*> quantum_draw_circuit circuit=`电路` path=`路径` kind="circuit" qubit=0 theme=`主题`* + +## 画概率 + +`电路` 理想态概率条。默认 `主题`="dark"。可选 `路径` 落盘。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路 | +| 路径 | any | 可选路径或 None | +| 主题 | text | dark light 或 bw | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 绘图结果 | + +> 能力.加载 +*> quantum_draw_circuit circuit=`电路` path=`路径` kind="probs" qubit=0 theme=`主题`* + +## 画布洛赫 + +`电路` 上单线布洛赫球。默认 `比特`=0、`主题`="dark"。可选 `路径` 落盘。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路 | +| 路径 | any | 可选路径或 None | +| 比特 | number | 哪一根线 | +| 主题 | text | dark light 或 bw | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 绘图结果 | + +> 能力.加载 +*> quantum_draw_circuit circuit=`电路` path=`路径` kind="bloch" qubit=`比特` theme=`主题`* + +## 画密度 + +绘制密度算符 `密度`。默认 `种类`="hinton"。可选 `路径` 落盘。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 密度 | any | 密度算符 | +| 路径 | any | 可选路径或 None | +| 种类 | text | hinton city density 或 paulivec | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 绘图结果 | + +> 能力.加载 +*> quantum_density_draw density=`密度` path=`路径` kind=`种类`* + +## 画门 + +绘制单个 `门`。默认 `种类`="gate"。可选 `路径` 落盘。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 门 | any | 门句柄 | +| 路径 | any | 可选路径或 None | +| 种类 | text | gate 或 matrix | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 绘图结果 | + +> 能力.加载 +*> quantum_gate_draw gate=`门` path=`路径` kind=`种类`* diff --git a/ext/quantum/量子/密度/索引.mq.md b/ext/quantum/量子/密度/索引.mq.md new file mode 100644 index 0000000..071a299 --- /dev/null +++ b/ext/quantum/量子/密度/索引.mq.md @@ -0,0 +1,170 @@ +--- +markup: occlusion +title: ext/quantum/量子/密度 +description: 密度算符 skill — 混合态、部分迹、期望值。 +import: + 能力: ext/quantum/量子/能力/索引.mq.md +--- + +密度算符同时描述纯态与混合态。可从态/电路或显式厄米矩阵构造,再做纯度、 +部分迹与期望。 + +## 给智能体 +若你只拿到本文件: + +调用示例(纯文本): + marqdo call ext/quantum/量子/密度/索引.mq.md 从态 态=$qc --effects plugin --toget rho --json + marqdo call ext/quantum/量子/密度/索引.mq.md 纯度 密度=$rho --effects plugin --json + +*None* + +## 从态 +由纯态或电路句柄 `态` 的理想态构造 rho。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 态 | any | 纯态或电路 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 密度句柄 | + +> 能力.加载 +*> quantum_density_from_state state=`态`* + +## 从矩阵 +由显式厄米 `矩阵` 构造 rho。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 矩阵 | any | 厄米矩阵 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 密度句柄 | + +> 能力.加载 +*> quantum_density_from_matrix matrix=`矩阵`* + +## 纯度 +计算 `密度` 的 Tr(rho^2)。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 密度 | any | 密度算符 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 纯度 | + +> 能力.加载 +*> quantum_density_purity density=`密度`* + +## 部分迹 +对联合密度 `密度` 保留 `保留` 所列比特,对其余求迹。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 密度 | any | 联合密度 | +| 保留 | any | 保留的比特下标列表 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 约化密度 | + +> 能力.加载 +*> quantum_density_partial_trace density=`密度` keep=`保留`* + +## 期望 +`密度` 上可观测量 `可观测量` 的期望值。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 密度 | any | 密度算符 | +| 可观测量 | any | 泡利串或矩阵 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 期望值 | + +> 能力.加载 +*> quantum_density_expect density=`密度` obs=`可观测量`* + +## 本征 +`密度` 的厄米谱。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 密度 | any | 密度算符 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 本征值与本征矢 | + +> 能力.加载 +*> quantum_density_eig density=`密度`* + + +# 密度 + + `态`=None + + `矩阵`=None + +由态/电路(态=)或显式厄米矩阵=构造密度算符,宽度上限六比特。纯态与混合态共用本对象面,随后可做纯度、部分迹、本征与期望。智能体也可用同文件 ## 从态 / 从矩阵 工具逐步构造,再 toget 复用句柄。构造成功后返回密度句柄,供作者链式或 call 会话继续使用。若同时给出矩阵与态,以矩阵分支为准。 + +> 能力.加载 +1. `矩阵` + *> quantum_density_from_matrix matrix=`矩阵`* +2. * + *> quantum_density_from_state state=`态`* + +## 矩阵 + +返回本密度算符的显式矩阵,便于检查元素,或交给包外线性代数步骤继续处理。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_matrix density=`self`* + +## 纯度 + +计算 Tr(ρ²)。接近 1 表示纯态;混合态严格小于 1。部分迹后可用来快速检查纠缠或退相干。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_purity density=`self`* + +## 部分迹 + + `保留` + +保留所列比特(LSB=0),对其余求迹,得到约化密度。用于纠缠讲义与纯度检查。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_partial_trace density=`self` keep=`保留`* + +## 本征 + +计算本密度的厄米谱(本征值与本征矢)。便于讲义作图,并核对构造的 rho 是否物理。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_eig density=`self`* + +## 期望 + + `可观测量` + +可观测量在本密度上的期望值。可观测量可以是泡利串(左端=高比特),或与密度维数匹配的显式矩阵。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_expect density=`self` obs=`可观测量`* + +## 绘图 + + `路径`=None + + `种类`=hinton + +绘制 Hinton、城市、密度格或泡利向量图。可选路径落盘;种类选择讲义采用的视觉隐喻。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_draw density=`self` path=`路径` kind=`种类`* diff --git a/ext/quantum/量子/态/索引.mq.md b/ext/quantum/量子/态/索引.mq.md new file mode 100644 index 0000000..22970b9 --- /dev/null +++ b/ext/quantum/量子/态/索引.mq.md @@ -0,0 +1,70 @@ +--- +markup: occlusion +title: ext/quantum/量子/态 +description: 量子态 skill — 张量积、保真度、施密特分解。 +import: + 能力: ext/quantum/量子/能力/索引.mq.md +--- + +纯态是复空间中的单位向量。本包振幅用含 re、im 的映射表示。基矢标签里比特 0 在 +最右侧。理想模拟忽略教学噪声;采样轨迹见模拟模块。 + +## 给智能体 + +若你只拿到本文件,用 marqdo call 调用下面的 ## 工具,并务必加 --effects plugin。 + +调用示例(纯文本): + marqdo call ext/quantum/量子/态/索引.mq.md 保真度 a=$psi b=$phi --effects plugin --json + +工具名:张量积、保真度、施密特分解。 + +*None* + +## 张量积 + +将 `a` 与 `b` 做张量积,得到更大空间上的态或算符。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| a | any | 左因子 | +| b | any | 右因子 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 张量积结果 | + +> 能力.加载 +*> quantum_kron a=`a` b=`b`* + +## 保真度 + +纯态 `a` 与 `b` 的保真度为重叠绝对值的平方。可传入电路句柄(取理想模拟态)。 +教学噪声忽略。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| a | any | 第一态或电路 | +| b | any | 第二态或电路 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | number | 保真度 | + +> 能力.加载 +*> quantum_fidelity a=`a` b=`b`* + +## 施密特分解 + +对纯态或电路 `态` 做施密特分解。`分割`=1 表示子系统 A 的比特数(低位)。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 态 | any | 纯态或电路 | +| 分割 | number | 子系统 A 比特数 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 施密特数据 | + +> 能力.加载 +*> quantum_schmidt state=`态` cut=`分割`* diff --git a/ext/quantum/量子/模拟/索引.mq.md b/ext/quantum/量子/模拟/索引.mq.md new file mode 100644 index 0000000..03a4f2f --- /dev/null +++ b/ext/quantum/量子/模拟/索引.mq.md @@ -0,0 +1,100 @@ +--- +markup: occlusion +title: ext/quantum/量子/模拟 +description: 量子模拟 skill — 振幅、概率、含噪采样。 +import: + 能力: ext/quantum/量子/能力/索引.mq.md +--- + +模拟回答「这条电路会怎样」。理想路径(模拟、态、概率)忽略教学噪声。运行工具 +做计算基采样,并在已附着噪声时应用噪声。超宽电路会被插件拒绝,不会静默截断。 + +## 给智能体 + +若你只拿到本文件,需要先有电路句柄(通常来自电路模块的 toget)。然后: + +调用示例(纯文本): + marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 电路=$qc --effects plugin --session s --json + +其它工具:模拟、态、运行、噪声。一律 --effects plugin。 + +*None* + +## 模拟 + +返回 `电路` 的理想态矢量振幅。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 待演化电路 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 振幅列表 | + +> 能力.加载 +*> quantum_simulate circuit=`电路`* + +## 态 + +与模拟相同:取 `电路` 的理想振幅,打包为态对象,便于后续保真度或密度构造。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 待演化电路 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 理想态 | + +> 能力.加载 +*> quantum_state circuit=`电路`* + +## 概率 + +`电路` 理想态的基矢标签到概率映射。比特 0 为最右侧。忽略噪声。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 待读取电路 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 概率映射 | + +> 能力.加载 +*> quantum_probabilities circuit=`电路`* + +## 运行 + +对 `电路` 采样。默认 `次数`=1024、`种子`=1。若有教学噪声则轨迹含噪声。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 待采样电路 | +| 次数 | number | 采样次数 | +| 种子 | number | 随机种子 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 计数或采样结果 | + +> 能力.加载 +*> quantum_run circuit=`电路` shots=`次数` seed=`种子`* + +## 噪声 + +在 `电路` 上附着种类 `种类`、强度 `强度` 的教学噪声。理想概率工具忽略它。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路 | +| 种类 | text | 噪声族名 | +| 强度 | number | 单位区间强度 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 带噪声元数据的电路 | + +> 能力.加载 +*> quantum_noise circuit=`电路` kind=`种类` p=`强度`* diff --git a/ext/quantum/量子/电路/索引.mq.md b/ext/quantum/量子/电路/索引.mq.md new file mode 100644 index 0000000..18e1657 --- /dev/null +++ b/ext/quantum/量子/电路/索引.mq.md @@ -0,0 +1,362 @@ +--- +markup: occlusion +title: ext/quantum/量子/电路 +description: 量子电路 skill — 造线、施加门;含作者对象「电路」。 +import: + 能力: ext/quantum/量子/能力/索引.mq.md + 密度: ext/quantum/量子/密度/索引.mq.md +--- + +电路是 n 条线上的有序门列,初态为全零。可用本页 ## 工具逐步构造,或用对象 +「电路」的方法链。测量标记只影响采样,不坍缩理想概率所用的态矢量。 + +## 给智能体 +若你只拿到本文件,每个 ## 都是工具。一律加 --effects plugin。 + +创建两比特电路并保存为 qc: + +调用示例(纯文本): + marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=2 --effects plugin --session s --toget qc --json + +在比特 0 上施加哈达玛: + +调用示例(纯文本): + marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 电路=$qc 比特=0 --effects plugin --session s --toget qc --json + +控非 0→1: + +调用示例(纯文本): + marqdo call ext/quantum/量子/电路/索引.mq.md 控非 电路=$qc 控制=0 目标=1 --effects plugin --session s --toget qc --json + +随后打开 ext/quantum/量子/模拟/索引.mq.md 取概率。作者程序可导入本文件并使用对象电路 +(方法如哈达玛、控非)。智能体优先用上面的 marqdo call。 + +*None* + +## 新建 +创建宽度为 `比特数`=1 的态矢量电路。可选 `步骤`=None 表示不预载门表。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 比特数 | number | 线宽 | +| 步骤 | any | 可选门表或 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 新电路句柄 | + +> 能力.加载 +*> quantum_circuit_new qubits=`比特数` steps=`步骤`* + +## 哈达玛 +对已有 `电路` 的 `比特`=0 施加哈达玛。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路句柄 | +| 比特 | number | 目标线 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +> 能力.加载 +*> quantum_h circuit=`电路` qubit=`比特`* + +## 控非 +对 `电路` 从 `控制`=0 到 `目标`=1 施加控非。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路句柄 | +| 控制 | number | 控制位 | +| 目标 | number | 目标位 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 更新后的电路 | + +> 能力.加载 +*> quantum_cx circuit=`电路` control=`控制` target=`目标`* + +## 屏障 +在 `电路` 上记录可视化屏障(不改态)。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路句柄 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 带屏障的电路 | + +> 能力.加载 +*> quantum_barrier circuit=`电路`* + +## 测量标记 +为后续运行在 `电路` 上标记计算基读出。`比特`=None 表示全部线。不坍缩理想态。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 电路 | any | 电路句柄 | +| 比特 | any | 线列表或 None | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 带测量标记的电路 | + +> 能力.加载 +*> quantum_measure circuit=`电路` qubits=`比特`* + + +# 电路 + + `比特数`=1 + + `步骤`=None + +状态向量电路,初态为全零。可选步骤表预载门列。方法追加门并返回新句柄,供作者链式写法;智能体更宜用上方 ## 工具配合 marqdo call。测量标记只影响采样,不坍缩概率所用的理想态。 + +本构造返回可供链式调用的句柄,与同文件 ## 工具共用能力.加载 路径。作者程序写对象方法链;智能体优先 marqdo call 上方工具。 + +> 能力.加载 +*> quantum_circuit_new qubits=`比特数` steps=`步骤`* + +## 哈达玛 + + `比特`=0 + +对选定线施加哈达玛,把计算基变成等权叠加,是贝尔态与 GHZ 制备的第一步。返回更新后的电路句柄,便于继续链式写法而不原地突变。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_h circuit=`self` qubit=`比特`* + +## 泡利X + + `比特`=0 + +对选定线施加泡利 X(比特翻转)。常用于从 |0⟩ 制备 |1⟩,或与相位门组成三明治。返回更新后的电路句柄以便继续链式调用。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_x circuit=`self` qubit=`比特`* + +## 泡利Y + + `比特`=0 + +对选定线施加泡利 Y,同时含比特翻转与相位。返回更新后的电路句柄,供作者程序继续链式组合。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_y circuit=`self` qubit=`比特`* + +## 泡利Z + + `比特`=0 + +对选定线施加泡利 Z(相位翻转)。常见于 H–Z–H 三明治以等效实现 X。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_z circuit=`self` qubit=`比特`* + +## 相位S + + `比特`=0 + +对选定线施加相位门 S(√Z)。返回更新后的电路句柄,便于讲义电路继续链式写法。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_s circuit=`self` qubit=`比特`* + +## 相位T + + `比特`=0 + +对选定线施加相位门 T(π/8)。返回更新后的电路句柄,便于讲义电路继续链式写法。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_t circuit=`self` qubit=`比特`* + +## 单位 + + `比特`=0 + +对选定线施加单位门。在步骤表中作占位,或在噪声实验里作对照。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_i circuit=`self` qubit=`比特`* + +## 绕X + + `比特`=0 + + `参数` + +绕 X 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_rx circuit=`self` qubit=`比特` theta=`参数`* + +## 绕Y + + `比特`=0 + + `参数` + +绕 Y 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_ry circuit=`self` qubit=`比特` theta=`参数`* + +## 绕Z + + `比特`=0 + + `参数` + +绕 Z 轴按角参数(弧度)旋转选定线。用于变分线路与连续单比特教学。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_rz circuit=`self` qubit=`比特` theta=`参数`* + +## 控非 + + `控制`=0 + + `目标`=1 + +从控制位到目标位施加控非。贝尔态与 GHZ 制备中的标准纠缠步骤。返回更新后的电路句柄以便继续链式调用。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_cx circuit=`self` control=`控制` target=`目标`* + +## 控相 + + `控制`=0 + + `目标`=1 + +在控制位与目标位之间施加控制 Z。产生相位纠缠且不翻转比特。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_cz circuit=`self` control=`控制` target=`目标`* + +## 交换 + + `比特甲`=0 + + `比特乙`=1 + +交换比特甲与比特乙两根线。用于教学布局里重排逻辑比特。返回更新后的电路句柄。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_swap circuit=`self` a=`比特甲` b=`比特乙`* + +## 屏障 + +仅记录可视化分隔,不改变理想态矢量。画电路轨线时用来分开讲义阶段。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_barrier circuit=`self`* + +## 测量 + + `比特`=None + +为后续运行标记计算基读出线。不坍缩概率所用的理想态。比特=None 表示标记全部线。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_measure circuit=`self` qubits=`比特`* + +## 追加 + + `操作` + +把另一电路的操作列,或门/比特记录表,追加到本电路。返回合并后的句柄,便于组合电路片段。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_append circuit=`self` op=`操作`* + +## 施加 + + `门` + + `比特`=0 + +把门句柄(具名或自定义酉矩阵)施加到比特(整数或列表)。返回更新后的电路句柄以便继续链式调用。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_apply circuit=`self` gate=`门` qubits=`比特`* + +## 噪声 + + `种类` + + `概率` + +附着给定种类与强度的教学噪声,供运行轨迹使用。理想模拟与概率路径按设计会忽略该通道。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_noise circuit=`self` kind=`种类` p=`概率`* + +## 模拟 + +返回当前电路的理想态矢量振幅(re/im)。此路径忽略已附着的教学噪声。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_simulate circuit=`self`* + +## 态 + +返回与模拟相同振幅的理想态对象。后续保真度或密度工具若需要态句柄,优先用本方法。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_state circuit=`self`* + +## 概率 + +基矢标签到理想概率的映射;比特 0 在最右侧。忽略教学噪声,结果与纯态矢量叙述一致。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_probabilities circuit=`self`* + +## 运行 + + `次数`=1024 + + `种子`=1 + +对本电路做计算基采样。默认次数=1024、种子=1,便于复现。若已附着教学噪声则在轨迹中启用。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_run circuit=`self` shots=`次数` seed=`种子`* + +## 绘图 + + `路径`=None + + `种类`=circuit + + `比特`=0 + + `主题`=dark + +绘制电路轨线、概率条、布洛赫或高级密度图种的 SVG。主题为 dark、light、bw。可选路径落盘供 CLI 或 view 嵌入。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_draw_circuit circuit=`self` path=`路径` kind=`种类` qubit=`比特` theme=`主题`* + +## 密度 + +对本电路理想模拟后构造纯态密度矩阵 ρ=|ψ⟩⟨ψ|。混合态与部分迹请改用密度模块工具。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_from_state state=`self`* + +## 期望 + + `可观测量` + +在本电路理想密度上计算泡利串(左端=高比特)或矩阵的期望值。忽略教学噪声。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_density_expect density=`self` obs=`可观测量`* + +## 施密特 + + `分割`=1 + +对理想态做二分施密特分解。分割为子系统 A 的比特数,从低位起算。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_schmidt state=`self` cut=`分割`* diff --git a/ext/quantum/量子/索引.mq.md b/ext/quantum/量子/索引.mq.md new file mode 100644 index 0000000..0d33b68 --- /dev/null +++ b/ext/quantum/量子/索引.mq.md @@ -0,0 +1,159 @@ +--- +markup: occlusion +title: ext/quantum/量子 +description: 量子扩展根 skill。请先读本文件。每个工具用 marqdo call 执行。 +import: + 态: ext/quantum/量子/态/索引.mq.md + 门: ext/quantum/量子/门/索引.mq.md + 电路: ext/quantum/量子/电路/索引.mq.md + 模拟: ext/quantum/量子/模拟/索引.mq.md + 密度: ext/quantum/量子/密度/索引.mq.md + 可视化: ext/quantum/量子/可视化/索引.mq.md +--- + +本文件是 Marqdo 量子扩展的中文根 skill。若你是没有其它 Marqdo 上下文的智能体, +请先读「选哪条路」,再按「如何执行任意工具」操作。不要发明 MCP、Python 封装或 +第二套 API。这些文件里的 ## 标题就是工具。 + +## 选哪条路 + +只选一行。不要混用中英工具名或目录树。(下表是叙述,不要写成 Marqdo 分支行。) + +| 若你需要 | 这样做 | +|----------|--------| +| 只要贝尔态结果 | 对本文件调用 `贝尔态`(下节命令)。到此结束。 | +| 电路句柄以便继续(画图、噪声、再施门) | 照抄下方「电路模块」里的分步电路再模拟调用。全程同一 `--session`,并用 `--toget qc`。 | +| 英文工具名 | 改开 `ext/quantum/index.mq.md`,并留在英文树。 | + +中文路径留在 `ext/quantum/量子/`(本树)。智能体请用 `##` 工具配 +`marqdo call`。各模块文件里的 `# 电路` / `# 门` 对象面向作者程序导入,不是 +默认的智能体路径。 + +*None* + +## 如何执行任意工具 + +Marqdo 用下面的 shell 命令形状,从 Markdown 文件里运行一个函数。请原样复制, +再替换 FILE、FUNCTION 与参数。 + +调用示例(纯文本): + marqdo call FILE FUNCTION 名=值 名=值 --effects plugin --json + +FILE 总是 ext/quantum/量子/ 下的路径,通常以 索引.mq.md 结尾。FUNCTION 是该文件中 ## +标题的精确名字(例如 新建、哈达玛、概率)。嵌套的 ### 用 parent.child 路径。 +本包必须加 --effects plugin,因为模拟器是原生插件;不加会被拒绝。需要机器可读 +结果时加 --json。若要在下一步复用返回值,加 --session 某id 与 --toget 名字 +(或在命令末尾写 toget 名字)。之后参数可用 电路=$名字。插件句柄靠会话日志 +跨进程重建。参数值可以是数字、引号文本、True/False/None、以 [ 或 { 开头的 JSON、 +或 $名字。不要调用 确保插件 或任何 host 星号 API;领域文件会自行加载插件。 + +验证本包可用的最小命令(无工具参数): + +调用示例(纯文本): + marqdo call ext/quantum/量子/索引.mq.md 贝尔态 --effects plugin --json + +*None* + +## 包布局 + +只打开你需要的模块。每个模块文件本身也是完整 skill,并重复说明如何 marqdo call。 + +路径 ext/quantum/量子/索引.mq.md 是本根地图与贝尔演示工具。 +路径 ext/quantum/量子/电路/索引.mq.md 造线、施加哈达玛与控非,并定义作者对象「电路」。 +路径 ext/quantum/量子/门/索引.mq.md 用公式写酉门,并构造具名或自定义门。 +路径 ext/quantum/量子/模拟/索引.mq.md 给出振幅、概率与含噪采样。 +路径 ext/quantum/量子/态/索引.mq.md 做张量积、保真度、施密特分解。 +路径 ext/quantum/量子/密度/索引.mq.md 做密度算符与部分迹。 +路径 ext/quantum/量子/可视化/索引.mq.md 画 SVG。 +路径 ext/quantum/量子/能力/索引.mq.md 仅加载插件,供排查用。 + +作者程序在 frontmatter 用「导入」引入相同路径,再写 模块.成员。例如导入电路: +ext/quantum/量子/电路/索引.mq.md,然后用 电路.电路 构造对象,或用 电路.新建 供智能体 +marqdo call。 + +*None* + +## 电路模块 + +文件路径:ext/quantum/量子/电路/索引.mq.md + +需要电路句柄时用本模块。两比特贝尔态典型智能体序列(每行一条 shell 命令): + +调用示例(纯文本): + marqdo call ext/quantum/量子/电路/索引.mq.md 新建 比特数=2 --effects plugin --session s1 --toget qc --json + marqdo call ext/quantum/量子/电路/索引.mq.md 哈达玛 电路=$qc 比特=0 --effects plugin --session s1 --toget qc --json + marqdo call ext/quantum/量子/电路/索引.mq.md 控非 电路=$qc 控制=0 目标=1 --effects plugin --session s1 --toget qc --json + +该文件主要 ## 工具:新建、哈达玛、控非、屏障、测量标记。同文件还有作者对象电路。 + +*None* + +## 门模块 + +文件路径:ext/quantum/量子/门/索引.mq.md + +调用示例(纯文本): + marqdo call ext/quantum/量子/门/索引.mq.md 哈达玛 --effects plugin --json + +主要 ## 工具:哈达玛、泡利X、泡利Z、控非门、自定义、匹配。 + +*None* + +## 模拟模块 + +文件路径:ext/quantum/量子/模拟/索引.mq.md + +调用示例(纯文本): + marqdo call ext/quantum/量子/模拟/索引.mq.md 概率 电路=$qc --effects plugin --session s1 --json + +主要 ## 工具:模拟、态、概率、运行、噪声。 + +*None* + +## 态模块 + +文件路径:ext/quantum/量子/态/索引.mq.md + +调用示例(纯文本): + marqdo call ext/quantum/量子/态/索引.mq.md 保真度 a=$psi b=$phi --effects plugin --json + +主要 ## 工具:张量积、保真度、施密特分解。 + +*None* + +## 密度模块 + +文件路径:ext/quantum/量子/密度/索引.mq.md + +调用示例(纯文本): + marqdo call ext/quantum/量子/密度/索引.mq.md 从态 态=$qc --effects plugin --toget rho --json + +*None* + +## 可视化模块 + +文件路径:ext/quantum/量子/可视化/索引.mq.md + +调用示例(纯文本): + marqdo call ext/quantum/量子/可视化/索引.mq.md 画电路 电路=$qc 路径="bell.svg" --effects plugin --session s1 --json + +*None* + +## 贝尔态 + +本索引上的一键编排工具,无参数。在比特 0 上哈达玛再控非 0→1,返回理想基矢概率。 +只要演示结果时用本工具;需要中间句柄时用上面的分步 call。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 基矢标签到概率的映射 | + +精确命令: + +调用示例(纯文本): + marqdo call ext/quantum/量子/索引.mq.md 贝尔态 --effects plugin --json + +**qc = > 电路.新建 比特数=2 步骤=None** +**qc = > 电路.哈达玛 电路=`qc` 比特=0** +**qc = > 电路.控非 电路=`qc` 控制=0 目标=1** +*> 模拟.概率 电路=`qc`* diff --git a/ext/quantum/量子/能力/索引.mq.md b/ext/quantum/量子/能力/索引.mq.md new file mode 100644 index 0000000..4173cff --- /dev/null +++ b/ext/quantum/量子/能力/索引.mq.md @@ -0,0 +1,40 @@ +--- +markup: occlusion +title: ext/quantum/量子/能力 +description: 量子 ABI 加载 skill。日常请用电路/门/模拟等模块。 +import: + plugin: lib/plugin.mq.md + sys: lib/sys.mq.md +--- + +本文件仍是 skill 与工具面。它只负责加载原生 quantum 插件。日常作者程序与智能体 +应调用电路、门、模拟等模块(它们会替你加载)。仅在排查插件是否安装时打开本页。 + +## 给智能体 + +若你只拿到本文件,请用下面命令检查插件。日常工作请改调电路或模拟模块。 + +调用示例(纯文本): + marqdo call ext/quantum/量子/能力/索引.mq.md 加载 --effects plugin --json + +*None* + +## 加载 + +通过 plugin.native_path 找到 ABI v2 quantum 共享库,再 plugin.load。若缺失则打印 +安装提示并以非零退出。成功后本进程内可用 quantum_* 符号。本包中只有这里应直接 +接触 lib/plugin。领域模块在需要模拟器的工具开头调用加载。 + +本工具无参数。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 加载成功后为空 | + +**p = > plugin.native_path name="quantum"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/quantum/量子: 未找到原生 quantum 插件(请 build marqdo_plugin_quantum 或 marqdo ext add quantum) + > sys.exit code=1 +**** diff --git a/ext/quantum/量子/门/索引.mq.md b/ext/quantum/量子/门/索引.mq.md new file mode 100644 index 0000000..81a06f5 --- /dev/null +++ b/ext/quantum/量子/门/索引.mq.md @@ -0,0 +1,140 @@ +--- +markup: occlusion +title: ext/quantum/量子/门 +description: 量子门 skill — 公式酉矩阵、具名门、矩阵核对。 +import: + 能力: ext/quantum/量子/能力/索引.mq.md +--- + +门是作用在一个或多个比特上的酉变换。本 skill 先写矩阵含义,再构造门句柄。 +电路施加门;本页定义门是什么。 + +## 给智能体 +若你只拿到本文件,用 marqdo call 调用 ## 工具,必须加 --effects plugin。 + +调用示例(纯文本): + marqdo call ext/quantum/量子/门/索引.mq.md 哈达玛 --effects plugin --json + +作者程序也可使用本文件中的对象「门」。 + +*None* + +## 哈达玛 +哈达玛门把计算基变成等权叠加。本工具返回名为 H 的门句柄。 + +本工具无参数。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 哈达玛门句柄 | + +> 能力.加载 +*> quantum_gate_new name="H" theta=None matrix=None* + +## 泡利X +泡利 X 是比特翻转门。 + +本工具无参数。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 泡利 X 句柄 | + +> 能力.加载 +*> quantum_gate_new name="X" theta=None matrix=None* + +## 泡利Z +泡利 Z 给 ket-one 乘上负号相位。 + +本工具无参数。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 泡利 Z 句柄 | + +> 能力.加载 +*> quantum_gate_new name="Z" theta=None matrix=None* + +## 控非门 +两比特受控非门句柄。施到线路上时请用电路模块并写明控制位与目标位。 + +本工具无参数。 + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | CNOT 门句柄 | + +> 能力.加载 +*> quantum_gate_new name="CX" theta=None matrix=None* + +## 自定义 +用显式酉矩阵 `矩阵` 构造门。可选标签 `名`="U"。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 矩阵 | any | 酉矩阵公式或列表 | +| 名 | text | 可选标签,默认 U | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | 自定义门句柄 | + +> 能力.加载 +*> quantum_gate_new name=`名` theta=None matrix=`矩阵`* + +## 匹配 +检查 `门` 是否在容差 `容差`=0.000000001 内匹配 `矩阵`。 + +| 参数 | 类型 | 说明 | +|------|------|------| +| 门 | any | 门句柄 | +| 矩阵 | any | 期望酉矩阵 | +| 容差 | number | 绝对容差 | + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | bool | 匹配则为 True | + +> 能力.加载 +*> quantum_gate_matches_matrix gate=`门` matrix=`矩阵` tol=`容差`* + + +# 门 + + `名`=None + + `参数`=None + + `矩阵`=None + +具名内置门(名=H)或由矩阵=(嵌套 list 或公式矩阵围栏)定义的自定义酉门。自定义门可选名=(默认 U)。作者链式与智能体 ## 工具共用本对象面。 + +本构造返回可供链式调用的句柄,与同文件 ## 工具共用能力.加载 路径。作者程序写对象方法链;智能体优先 marqdo call 上方工具。 + +> 能力.加载 +*> quantum_gate_new name=`名` theta=`参数` matrix=`矩阵`* + +## 矩阵 + +返回本门句柄的显式酉矩阵,便于检查元素,或在公式构造自定义门后交给匹配矩阵验收。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_gate_matrix gate=`self`* + +## 匹配矩阵 + + `矩阵` + + `容差`=0.000000001 + +检查本门是否在绝对容差内容差内匹配给定矩阵。讲义里用公式围栏造门后,常用本方法做数值验收。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_gate_matches_matrix gate=`self` matrix=`矩阵` tol=`容差`* + +## 绘图 + + `路径`=None + + `种类`=gate + +绘制门符号或复矩阵热力图(种类=gate 或 matrix)。可选路径落盘;亦经 record_plot 进入本会话的 view/CLI 图面。 + +本方法把领域意图写进句柄并返回结果,便于作者程序继续组合;智能体若只需单步操作也可改调同文件上方对应的 ## 工具与 marqdo call。参数默认值写在 + 形参行;调用时只覆盖需要改的项即可。 + +*> quantum_gate_draw gate=`self` path=`路径` kind=`种类`* diff --git a/lib/lint/narrative.mq.md b/lib/lint/narrative.mq.md new file mode 100644 index 0000000..7434993 --- /dev/null +++ b/lib/lint/narrative.mq.md @@ -0,0 +1,41 @@ +--- +markup: occlusion +title: lib/lint/narrative +description: >- + Narration-ratio skill (≥50%). Canonical checker: marqdo check --narrative-ratio. +--- + +Narration ratio skill. Every authored function unit should mix narration with +code so narration is more than half the text. This is the first skill-as-tools +example called out in the author vision notes: the page is documentation, and +its headings are tools. The canonical path checker lives in the host as +marqdo check --narrative-ratio so directory dogfood does not need filesystem +effects inside a pure call. + +## For AI agents + +If you are an AI agent, run marqdo check --narrative-ratio on each extension +file you edit. Do not invent a second schema. Call remind on this file when you +need a short machine-readable reminder of the rule. Each double-hash heading is +a tool. + +*None* + +## remind + +Return a small map stating the narration threshold and the CLI to run. Takes no +parameters. Use this when an agent needs a tool-shaped reminder without opening +design docs. The threshold is one half. Contract tables count as narration; +call lines and bold statements count as code. + +| 返回 | 类型 | 说明 | +|------|------|------| +| result | any | rule reminder map | + +`out` = + +| threshold | cli | tables | +|-----------|-----|--------| +| 0.5 | marqdo check --narrative-ratio FILE | narration | + +*out* diff --git a/public/features/06-quantum.mq.md b/public/features/06-quantum.mq.md index 1d96764..de1d92d 100644 --- a/public/features/06-quantum.mq.md +++ b/public/features/06-quantum.mq.md @@ -3,7 +3,8 @@ markup: occlusion title: Quantum circuits (ext/quantum) description: Official quantum simulator — tables, gates, Q7 density, Q8 themed SVG import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md + gate: ext/quantum/gate/index.mq.md --- # main @@ -27,7 +28,7 @@ Q8: `draw theme="dark"|"light"|"bw"` (default dark lab look) on circuit / probs **`qc` = > quantum.circuit qubits=3 steps=`steps`** **`p` = > `qc`.probabilities** **`_` = > `qc`.draw kind="probs" theme="dark"** -**`H` = > quantum.gate name="H"** +**`H` = > gate.gate name="H"** **`__` = > `H`.draw kind="matrix"** > print text=`p` diff --git a/public/features/06-量子-plot-1.svg b/public/features/06-量子-plot-1.svg index 6409a88..fe619c4 100644 --- a/public/features/06-量子-plot-1.svg +++ b/public/features/06-量子-plot-1.svg @@ -1 +1,14 @@ -100000.501110.50 \ No newline at end of file + + + + + + + + + + + + + +100000.501110.50 \ No newline at end of file diff --git a/public/features/06-量子.mq.md b/public/features/06-量子.mq.md index b9e7399..71fc8ae 100644 --- a/public/features/06-量子.mq.md +++ b/public/features/06-量子.mq.md @@ -3,13 +3,16 @@ markup: occlusion title: 量子电路(ext/quantum) description: 官方量子模拟 — 表、门、Q7 密度与高级图、Q8 主题 SVG 导入: - 量子: ext/quantum/量子.mq.md + 量子: ext/quantum/量子/电路/索引.mq.md + 门: ext/quantum/量子/门/索引.mq.md --- # main 可选扩展(非 stdlib)。安装:`marqdo ext add quantum`(或编译 `marqdo_plugin_quantum`)。 +中文面在同包 `ext/quantum/量子/`(根 skill:`索引.mq.md`),与英文模块树并列、不混排 API。 + GHZ(3 比特):q0 哈达玛,再控非 0→1、0→2。理想 |000⟩ / |111⟩ 各约 1/2。 Q7:密度 / 部分迹 / Schmidt / `绘图 种类=hinton` 等 — `examples/quantum-entanglement/`。 @@ -27,7 +30,7 @@ Q8:`绘图 主题="dark"|"light"|"bw"`(默认 dark 科技感)作用于电 **`qc` = > 量子.电路 比特数=3 步骤=`步骤`** **`p` = > `qc`.概率** **`_` = > `qc`.绘图 种类="probs" 主题="dark"** -**`H` = > 量子.门 名="H"** +**`H` = > 门.门 名="H"** **`__` = > `H`.绘图 种类="matrix"** > 打印 内容=`p` diff --git a/public/features/22-call.mq.md b/public/features/22-call.mq.md index b1e63e6..dac6e41 100644 --- a/public/features/22-call.mq.md +++ b/public/features/22-call.mq.md @@ -34,7 +34,7 @@ Those four uses are one call. Knowledge becomes a tool because knowledge can alr The command keeps a boundary. -An external call runs a pure function. Writing files, starting a process, using the network or loading a plugin is refused before the function runs, so the side effect does not happen. Wider permission stays on the checks the project already has. An instance method needs its receiver; this command does not invent one. +An external call defaults to a pure function. Writing files, starting a process, using the network or loading a plugin is refused before the function runs. Pass `--effects plugin` when the tool needs an ABI plugin (for example `ext/quantum`). Session bindings use `--session` and `--toget name` (or trailing `toget name`); later calls may pass `$name`. Nested sub-tools use a dotted path such as `outer.helper`. An instance method needs its receiver; this command does not invent one. The function must resolve to exactly one declaration. No match, or one short name that hits two functions, is a structured error. The command does not pick the first hit. Arguments bind through the signature and contract that the function already has. Missing, unknown and ill-typed arguments are diagnostics. diff --git a/skills/marqdo/SKILL.md b/skills/marqdo/SKILL.md index 5a016ee..9529a3d 100644 --- a/skills/marqdo/SKILL.md +++ b/skills/marqdo/SKILL.md @@ -7,7 +7,7 @@ description: >- importing lib/* or ext/web or ext/quantum, running marqdo CLI, building dynamic sites with ext/web, quantum circuits with ext/quantum, or when the user mentions Marqdo, mq.md, markup-as-syntax, code-as-documentation, web/网页, or - quantum/量子 extension. + quantum/量子 extension (ZH under ext/quantum/量子/). --- # Marqdo development @@ -195,12 +195,14 @@ Design: [ext-web-artifact.md](../../doc/design/ext-web-artifact.md) · example: 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` +- **Root skill (read first):** [`ext/quantum/index.mq.md`](../../ext/quantum/index.mq.md) — explains every module and exact `marqdo call` commands for agents with no other context. +- **Modules:** `circuit/` · `gate/` · `simulate/` · `state/` · `density/` · `viz/` · `_capability/` (each has `index.mq.md`). ZH package: `ext/quantum/量子/`(根 `索引.mq.md`,模块同名中文目录). +- **Agent:** `marqdo call ext/quantum//index.mq.md … --effects plugin` (`--toget` / `$name`). Narration: `marqdo check --narrative-ratio FILE`. +- **Author import example:** `circuit: ext/quantum/circuit/index.mq.md` then `circuit.circuit` / method chain. **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`. +**Core:** domain skills above (`# circuit` / `# gate` / `# density` on module files) — 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`. diff --git a/skills/marqdo/examples.md b/skills/marqdo/examples.md index 7c3f37d..0048837 100644 --- a/skills/marqdo/examples.md +++ b/skills/marqdo/examples.md @@ -302,7 +302,7 @@ import: ```markdown --- import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/skills/marqdo/reference.md b/skills/marqdo/reference.md index 7d09c50..cae83c6 100644 --- a/skills/marqdo/reference.md +++ b/skills/marqdo/reference.md @@ -56,7 +56,7 @@ Import one file; use **that** file’s function names. | `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/quantum/index.mq.md` + modules | `ext/quantum/量子/索引.mq.md` + modules | circuits + Q7 density/viz + Q8 themes — see **ext/quantum** below | Open the imported `.mq.md` under `lib/` or `ext/` to see exact `##` / `#` names and parameters. Gold tests: `tests/lib/`, `tests/structure/`, `tests/ext/`. @@ -85,7 +85,7 @@ Install: `marqdo ext add quantum` (`量子`). Native: `cargo build --release -p | EN import | ZH import | Core types | |-----------|-----------|------------| -| `ext/quantum/quantum.mq.md` | `ext/quantum/量子.mq.md` | `# circuit` `# gate` `# density` | +| `ext/quantum/circuit/index.mq.md` (etc.) | `ext/quantum/量子/电路/索引.mq.md` (etc.) | `# circuit` / `# 电路` · `# gate` / `# 门` · `# density` / `# 密度` + call tools | | Area | EN APIs | Notes | |------|---------|-------| diff --git a/src/call.rs b/src/call.rs index 4eda12e..5d3dc19 100644 --- a/src/call.rs +++ b/src/call.rs @@ -11,6 +11,7 @@ use anyhow::Result; use crate::ast::Function; use crate::bytecode::{compile_for_call, Vm}; use crate::diagnostics::{Diagnostic, Span}; +use crate::host::json::json_to_value; use crate::host::{HostCaps, HostContext}; use crate::interp::Interpreter; use crate::load::load_module; @@ -18,40 +19,182 @@ use crate::sema::{compile_file_closure, SemanticArtifact, SemanticProject}; use crate::value::Value; use crate::Backend; -/// Call `function` in `path` with named arguments. -/// -/// Non-pure effects are refused before the function runs. Host write, exec, net, -/// and plugin capabilities stay off for the call. +/// Which host side effects `marqdo call` may perform. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CallEffects { + /// Refuse any non-pure artifact (historical default). + #[default] + None, + /// Allow `plugin.call` (and accompanying `output.write` from load helpers). + Plugin, +} + +impl CallEffects { + pub fn parse(s: &str) -> Result { + match s.trim().to_ascii_lowercase().as_str() { + "none" | "" => Ok(Self::None), + "plugin" => Ok(Self::Plugin), + other => Err(call_diag( + None, + 0, + "call.bad_effects", + format!("unknown --effects `{other}` (expected none|plugin)"), + )), + } + } + + pub fn as_str(self) -> &'static str { + match self { + Self::None => "none", + Self::Plugin => "plugin", + } + } + + fn host_caps(self) -> HostCaps { + match self { + Self::None => HostCaps { + fs_write: false, + exec: false, + net: false, + plugin: false, + }, + Self::Plugin => HostCaps { + fs_write: false, + exec: false, + net: false, + plugin: true, + }, + } + } + + fn allows(self, effect: &str) -> bool { + match self { + Self::None => effect == "pure", + Self::Plugin => matches!( + effect, + "pure" | "plugin.call" | "output.write" | "time.read" | "random.read" + ), + } + } +} + +/// Options for one external call. +#[derive(Debug, Clone, Default)] +pub struct CallOptions { + pub effects: CallEffects, + pub session: Option, + pub toget: Option, +} + +/// Call `function` in `path` with named arguments (pure-only, no session). pub fn call_file( path: &Path, function: &str, args: &[(String, Value)], backend: Backend, +) -> Result { + call_file_with(path, function, args, backend, CallOptions::default()) +} + +/// Call with effects / session / toget. +pub fn call_file_with( + path: &Path, + function: &str, + args: &[(String, Value)], + backend: Backend, + opts: CallOptions, ) -> Result { let path = path .canonicalize() - .map_err(|e| call_diag(None, 1, "call.compile", format!("failed to read {}: {e}", path.display())))?; + .map_err(|e| { + call_diag( + None, + 1, + "call.compile", + format!("failed to read {}: {e}", path.display()), + ) + })?; + + let mut session = if opts.session.is_some() || opts.toget.is_some() || args_need_session(args) + { + let id = opts + .session + .clone() + .unwrap_or_else(crate::call_session::default_session_id); + Some(crate::call_session::load_session(&id)?) + } else { + None + }; + + let resolved = if let Some(ref mut sess) = session { + crate::call_session::resolve_args(sess, args, backend)? + } else { + args.to_vec() + }; + + // Record uses original arg texts (with $refs) so replay can re-resolve. + let record_args = args.to_vec(); + + let value = call_file_raw(&path, function, &resolved, opts.effects, backend)?; + + if let Some(ref mut sess) = session { + crate::call_session::record_step( + sess, + &path, + function, + &record_args, + opts.effects, + opts.toget.as_deref(), + &value, + )?; + crate::call_session::save_session(sess)?; + } + + Ok(value) +} + +/// Execute without session bookkeeping (used by journal replay). +pub fn call_file_raw( + path: &Path, + function: &str, + args: &[(String, Value)], + effects: CallEffects, + backend: Backend, +) -> Result { + let path = if path.is_absolute() { + path.to_path_buf() + } else { + path.canonicalize().map_err(|e| { + call_diag( + None, + 1, + "call.compile", + format!("failed to read {}: {e}", path.display()), + ) + })? + }; let compilation = compile_file_closure(&path).map_err(|e| preserve_diag(&path, e))?; let artifact = locate_artifact(&compilation.semantics, &path, function)?; - deny_unsafe(&path, artifact)?; + deny_unsafe(&path, artifact, effects)?; execute_source_function( &path, artifact.source.line, &artifact.display_name, args, - tight_caps(), + effects.host_caps(), backend, true, ) .map(|(value, _stdout)| value) } +fn args_need_session(args: &[(String, Value)]) -> bool { + args.iter().any(|(_, v)| { + matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) + }) +} + /// Run the function declared at `line` in `path`. -/// -/// `display_name` is the declaration path (`计算器.加法`). The query the caller -/// typed is not used as a heading search and is not used as the bytecode path, -/// so a unique short name or SymbolId still executes that function. -/// `caps` are the host capabilities for this run. `call` passes them all off. pub(crate) fn execute_source_function( path: &Path, line: u32, @@ -70,22 +213,20 @@ pub(crate) fn execute_source_function( format!("无法在 {}:{} 定位函数 {display_name}", path.display(), line), ) })?; - let expected = display_name - .rsplit('.') - .next() - .unwrap_or(display_name); + let expected = display_name.rsplit('.').next().unwrap_or(display_name); if fun.name != expected { return Err(call_diag( Some(path), line, "artifact.unresolved", - format!("源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", fun.name), + format!( + "源码行 {line} 上的函数是 `{}`,与 `{display_name}` 不一致", + fun.name + ), )); } let mut interp = Interpreter::with_capture(Some(path), false) .with_host(HostContext::for_capture(Some(path), caps)); - // `call` checks the signature. `artifact.execute` keeps its previous - // environment injection so an input the body reads is not rejected as unknown. let bound; let invoke_args: &[(String, Value)] = if strict_args { bound = interp.bind_external_args(&module, fun, args)?; @@ -100,27 +241,53 @@ pub(crate) fn execute_source_function( } Backend::Bytecode => { let program = compile_for_call(Some(path), &module)?; - // Source binding is authoritative even when declaration paths repeat. - let idx = program.functions.iter().position(|chunk| - chunk.module_scope == 0 && chunk.declaration_span == fun.span - && chunk.name == fun.name && chunk.source.sha256 == module.source.sha256 - ).ok_or_else(|| { - call_diag( - Some(path), - line, - "artifact.unresolved", - format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"), - ) - })?; - let mut vm = Vm::with_capture(Some(path)) - .with_host(HostContext::for_capture(Some(path), caps)); + let idx = program + .functions + .iter() + .position(|chunk| { + chunk.module_scope == 0 + && chunk.declaration_span == fun.span + && chunk.name == fun.name + && chunk.source.sha256 == module.source.sha256 + }) + .ok_or_else(|| { + call_diag( + Some(path), + line, + "artifact.unresolved", + format!("bytecode 没有编译出 `{display_name}`;拒绝改去执行程序入口"), + ) + })?; + let mut vm = + Vm::with_capture(Some(path)).with_host(HostContext::for_capture(Some(path), caps)); let value = vm.call_function(&program, idx, invoke_args)?; Ok((value, vm.captured_stdout)) } } } -/// Parse `name=value` tokens. Values are integers, decimals, quoted text, or True/False/None. +/// Split trailing `toget ` from a clap `args` vector. +pub fn split_toget(tokens: &[String]) -> Result<(Vec, Option)> { + if tokens.len() >= 2 { + let n = tokens.len(); + if tokens[n - 2] == "toget" { + let name = tokens[n - 1].clone(); + if name.contains('=') { + return Err(call_diag( + None, + 0, + "call.bad_toget", + "toget 名字不能含 `=`".into(), + )); + } + return Ok((tokens[..n - 2].to_vec(), Some(name))); + } + } + Ok((tokens.to_vec(), None)) +} + +/// Parse `name=value` tokens. Values are integers, decimals, quoted text, True/False/None, +/// or JSON when the raw value starts with `[` or `{`. pub fn parse_call_args(tokens: &[String]) -> Result> { let mut out = Vec::new(); for token in tokens { @@ -148,15 +315,6 @@ pub fn parse_call_args(tokens: &[String]) -> Result> { Ok(out) } -fn tight_caps() -> HostCaps { - HostCaps { - fs_write: false, - exec: false, - net: false, - plugin: false, - } -} - fn locate_artifact<'a>( project: &'a SemanticProject, entry: &Path, @@ -191,7 +349,17 @@ fn locate_artifact<'a>( }) .collect() } else { - Vec::new() + // Nested sub-tools: `outer.helper` matches display path `main.outer.helper`. + let suffix = format!(".{query}"); + in_entry + .iter() + .copied() + .filter(|artifact| { + artifact.kind == "function" + && (artifact.display_name.ends_with(&suffix) + || artifact.display_name == query) + }) + .collect() }; match hits.len() { 1 => Ok(hits[0]), @@ -210,7 +378,7 @@ fn locate_artifact<'a>( } } -fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> { +fn deny_unsafe(path: &Path, artifact: &SemanticArtifact, effects: CallEffects) -> Result<()> { if artifact.kind != "function" || artifact.callable.as_deref() == Some("instance_method") { return Err(call_diag( Some(path), @@ -219,14 +387,21 @@ fn deny_unsafe(path: &Path, artifact: &SemanticArtifact) -> Result<()> { "只有非实例函数可由 call 直接执行".to_string(), )); } - if !artifact.effects.is_pure() { + let denied: Vec = artifact + .effects + .values() + .into_iter() + .filter(|e| !effects.allows(e)) + .collect(); + if !denied.is_empty() { return Err(call_diag( Some(path), artifact.source.line, "artifact.effect_denied", format!( - "call 默认只执行纯函数,拒绝效应 {}", - artifact.effects.values().join(", ") + "call --effects {} 拒绝效应 {}", + effects.as_str(), + denied.join(", ") ), )); } @@ -260,6 +435,9 @@ fn parse_literal(raw: &str) -> Result { "None" | "none" => return Ok(Value::None), _ => {} } + if raw.starts_with('$') || raw.starts_with('@') { + return Ok(Value::Text(raw.to_string())); + } if raw.len() >= 2 { let bytes = raw.as_bytes(); if (bytes[0] == b'"' && bytes[raw.len() - 1] == b'"') @@ -268,6 +446,11 @@ fn parse_literal(raw: &str) -> Result { return Ok(Value::Text(raw[1..raw.len() - 1].to_string())); } } + if raw.starts_with('[') || raw.starts_with('{') { + let json: serde_json::Value = + serde_json::from_str(raw).map_err(|e| format!("JSON 解析失败: {e}"))?; + return json_to_value(&json); + } if let Ok(n) = raw.parse::() { return Ok(Value::Int(n)); } @@ -277,7 +460,7 @@ fn parse_literal(raw: &str) -> Result { } } Err(format!( - "无法解析 `{raw}`(整数、小数、引号文本、True/False/None)" + "无法解析 `{raw}`(整数、小数、引号文本、True/False/None、JSON、`$name`)" )) } diff --git a/src/call_session.rs b/src/call_session.rs new file mode 100644 index 0000000..7e0f193 --- /dev/null +++ b/src/call_session.rs @@ -0,0 +1,286 @@ +//! Call-session journal for `marqdo call … toget` across process boundaries. +//! +//! Plugin handles do not survive a new OS process; replaying the journal rebuilds them. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; + +use crate::call::{self, CallEffects}; +use crate::host::json::{json_to_value, value_to_json}; +use crate::value::Value; +use crate::Backend; + +const SESSION_DIR: &str = ".marqdo/call-sessions"; + +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct CallSession { + pub session: String, + #[serde(default)] + pub steps: Vec, + /// JSON-serializable bindings from `toget` (when the result was V_safe JSON). + #[serde(default)] + pub bindings: BTreeMap, + /// Names whose live value must be rebuilt by replaying `steps` (plugin handles / opaque). + #[serde(default)] + pub journal_bindings: BTreeMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CallStep { + pub file: String, + pub function: String, + pub args: BTreeMap, + pub effects: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub toget: Option, +} + +fn sessions_root() -> PathBuf { + if let Ok(p) = std::env::var("MARQDO_CALL_SESSION_DIR") { + return PathBuf::from(p); + } + PathBuf::from(SESSION_DIR) +} + +pub fn session_path(id: &str) -> PathBuf { + let safe: String = id + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' || c == '_' { + c + } else { + '_' + } + }) + .collect(); + sessions_root().join(format!("{safe}.json")) +} + +pub fn load_session(id: &str) -> Result { + let path = session_path(id); + if !path.exists() { + return Ok(CallSession { + session: id.to_string(), + ..Default::default() + }); + } + let text = fs::read_to_string(&path) + .with_context(|| format!("read call session {}", path.display()))?; + let mut s: CallSession = serde_json::from_str(&text) + .with_context(|| format!("parse call session {}", path.display()))?; + s.session = id.to_string(); + Ok(s) +} + +pub fn save_session(session: &CallSession) -> Result<()> { + let path = session_path(&session.session); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let text = serde_json::to_string_pretty(session)?; + fs::write(&path, text)?; + Ok(()) +} + +/// Resolve `$name` / `@name` argument values from the session (replaying journal as needed). +pub fn resolve_args( + session: &mut CallSession, + args: &[(String, Value)], + backend: Backend, +) -> Result> { + let mut live: BTreeMap = BTreeMap::new(); + for (k, v) in &session.bindings { + live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?); + } + let needs_replay = args.iter().any(|(_, v)| { + matches!(v, Value::Text(t) if t.starts_with('$') || t.starts_with('@')) + && { + let name = v_text_ref(v); + session.journal_bindings.contains_key(name) + || (!session.bindings.contains_key(name) + && session.steps.iter().any(|s| s.toget.as_deref() == Some(name))) + } + }); + if needs_replay || args.iter().any(|(_, v)| { + matches!(v, Value::Text(t) if (t.starts_with('$') || t.starts_with('@')) + && session.journal_bindings.contains_key(&t[1..])) + }) { + live = replay_live(session, backend)?; + } + let mut out = Vec::with_capacity(args.len()); + for (name, value) in args { + out.push(( + name.clone(), + resolve_one(session, &live, value.clone(), backend)?, + )); + } + Ok(out) +} + +fn v_text_ref(v: &Value) -> &str { + match v { + Value::Text(t) if t.starts_with('$') || t.starts_with('@') => &t[1..], + Value::Text(t) => t.as_str(), + _ => "", + } +} + +fn resolve_one( + session: &CallSession, + live: &BTreeMap, + value: Value, + backend: Backend, +) -> Result { + let Value::Text(t) = &value else { + return Ok(value); + }; + if !(t.starts_with('$') || t.starts_with('@')) { + return Ok(value); + } + let key = &t[1..]; + if let Some(v) = live.get(key) { + return Ok(v.clone()); + } + if let Some(j) = session.bindings.get(key) { + return json_to_value(j).map_err(|e| anyhow::anyhow!(e)); + } + // Last resort: full replay + let live = replay_live(session, backend)?; + live.get(key) + .cloned() + .ok_or_else(|| anyhow::anyhow!("call.session_unbound: `${key}` not in session {}", session.session)) +} + +fn replay_live(session: &CallSession, backend: Backend) -> Result> { + let mut live: BTreeMap = BTreeMap::new(); + for (k, v) in &session.bindings { + // Prefer journal rebuild for names also in journal_bindings + if !session.journal_bindings.contains_key(k) { + live.insert(k.clone(), json_to_value(v).map_err(|e| anyhow::anyhow!(e))?); + } + } + for step in &session.steps { + let mut args = Vec::new(); + for (k, jv) in &step.args { + let mut val = json_to_value(jv).map_err(|e| anyhow::anyhow!(e))?; + if let Value::Text(t) = &val { + if t.starts_with('$') || t.starts_with('@') { + let key = &t[1..]; + val = live + .get(key) + .cloned() + .ok_or_else(|| anyhow::anyhow!("call.session_replay: missing `${key}`"))?; + } + } + args.push((k.clone(), val)); + } + let effects = CallEffects::parse(&step.effects)?; + let value = call::call_file_raw( + Path::new(&step.file), + &step.function, + &args, + effects, + backend, + )?; + if let Some(name) = &step.toget { + live.insert(name.clone(), value); + } + } + Ok(live) +} + +pub fn record_step( + session: &mut CallSession, + file: &Path, + function: &str, + args: &[(String, Value)], + effects: CallEffects, + toget: Option<&str>, + result: &Value, +) -> Result<()> { + let mut arg_map = BTreeMap::new(); + for (k, v) in args { + // Keep $ refs as text so replay can resolve them. + if let Value::Text(t) = v { + if t.starts_with('$') || t.starts_with('@') { + arg_map.insert(k.clone(), serde_json::Value::String(t.clone())); + continue; + } + } + match value_to_json(v) { + Ok(j) => { + arg_map.insert(k.clone(), j); + } + Err(_) => { + bail!("call.session: argument `{k}` is not JSON-serializable for the journal"); + } + } + } + let file_s = file + .canonicalize() + .unwrap_or_else(|_| file.to_path_buf()) + .display() + .to_string(); + let step = CallStep { + file: file_s, + function: function.to_string(), + args: arg_map, + effects: effects.as_str().to_string(), + toget: toget.map(|s| s.to_string()), + }; + session.steps.push(step); + if let Some(name) = toget { + match value_to_json(result) { + Ok(j) if is_json_friendly(result) => { + session.bindings.insert(name.to_string(), j); + session.journal_bindings.remove(name); + } + _ => { + session.bindings.remove(name); + session + .journal_bindings + .insert(name.to_string(), session.steps.len() - 1); + } + } + } + Ok(()) +} + +fn is_json_friendly(v: &Value) -> bool { + match v { + Value::None | Value::Bool(_) | Value::Int(_) | Value::Num(_) | Value::Text(_) => true, + Value::List(xs) => xs.iter().all(is_json_friendly), + Value::Map(pairs) => { + // Tagged quantum objects need journal replay across processes. + if pairs.iter().any(|(k, _)| k == "_type") { + return false; + } + pairs.iter().all(|(_, v)| is_json_friendly(v)) + } + Value::Handle(_) | Value::Formula(_) | Value::Code(_) | Value::Secret(_) => false, + } +} + +/// Dump journal steps as a minimal Marqdo script for later `marqdo run`. +pub fn dump_replay_script(session: &CallSession) -> String { + let mut out = String::from("# main\n\n# Replayed from call-session journal. Review before trusting.\n\n"); + for (i, step) in session.steps.iter().enumerate() { + out.push_str(&format!( + "> print text=\"step {i}: call {} {} effects={}\"\n", + step.file, step.function, step.effects + )); + } + if let Some(last) = session.steps.last().and_then(|s| s.toget.as_ref()) { + out.push_str(&format!("\n> print text=\"last toget was {last}\"\n")); + } + out.push_str("*None*\n"); + out +} + +pub fn default_session_id() -> String { + std::env::var("MARQDO_CALL_SESSION").unwrap_or_else(|_| "default".into()) +} diff --git a/src/ext_cli.rs b/src/ext_cli.rs index bd2d466..458772d 100644 --- a/src/ext_cli.rs +++ b/src/ext_cli.rs @@ -44,7 +44,24 @@ pub const CATALOG: &[ExtPackage] = &[ ExtPackage { id: "quantum", description: "Quantum circuit simulator (ext/quantum) — gates/state vector", - mq_files: &["quantum/quantum.mq.md", "quantum/量子.mq.md"], + mq_files: &[ + "quantum/index.mq.md", + "quantum/_capability/index.mq.md", + "quantum/circuit/index.mq.md", + "quantum/gate/index.mq.md", + "quantum/simulate/index.mq.md", + "quantum/state/index.mq.md", + "quantum/density/index.mq.md", + "quantum/viz/index.mq.md", + "quantum/量子/索引.mq.md", + "quantum/量子/能力/索引.mq.md", + "quantum/量子/电路/索引.mq.md", + "quantum/量子/门/索引.mq.md", + "quantum/量子/模拟/索引.mq.md", + "quantum/量子/态/索引.mq.md", + "quantum/量子/密度/索引.mq.md", + "quantum/量子/可视化/索引.mq.md", + ], native_crate: Some("marqdo_plugin_quantum"), }, ExtPackage { @@ -406,6 +423,20 @@ fn ensure_native_plugin(crate_name: &str) -> Result { ) } +fn same_path(a: &Path, b: &Path) -> bool { + match (a.canonicalize(), b.canonicalize()) { + (Ok(x), Ok(y)) => x == y, + _ => a == b, + } +} + +/// True when `install_root` is also a source `ext/` tree (dev layout). Copying +/// there truncates `.mq.md` on Linux (`fs::copy` same-file) and drops `.plugin` +/// junk into the repo. +fn install_root_is_source_tree(root: &Path) -> bool { + source_ext_roots().iter().any(|s| same_path(root, s)) +} + pub fn add_ext(id: &str) -> Result<()> { let pkg = find_package(id).with_context(|| { format!( @@ -418,6 +449,14 @@ pub fn add_ext(id: &str) -> Result<()> { ) })?; let root = install_root()?; + if install_root_is_source_tree(&root) { + bail!( + "refusing to install into extension *source* tree {} \ +(set MARQDO_EXT to an install directory such as ~/.marqdo/ext, \ +and use MARQDO_EXT_SOURCE for the repo ext/ when needed)", + root.display() + ); + } fs::create_dir_all(&root) .with_context(|| format!("create install root {}", root.display()))?; @@ -432,6 +471,12 @@ pub fn add_ext(id: &str) -> Result<()> { for f in pkg.mq_files { let src = find_source_file(f)?; let dest = root.join(f); + if same_path(&src, &dest) { + bail!( + "refusing same-file copy {} (install root overlaps source)", + src.display() + ); + } if let Some(parent) = dest.parent() { fs::create_dir_all(parent) .with_context(|| format!("create {}", parent.display()))?; diff --git a/src/lib.rs b/src/lib.rs index 3241128..e82f5ae 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,9 @@ pub mod browser_session; pub mod builtin; pub mod bytecode; pub mod call; +pub mod call_session; pub mod capture; +pub mod narrative_ratio; #[cfg(feature = "cli")] pub mod catalog; #[cfg(feature = "cli")] diff --git a/src/main.rs b/src/main.rs index 9277241..82efaaa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -142,11 +142,12 @@ enum Commands { /// Source file. file: PathBuf, - /// Function display path, for example `计算器.加法`. + /// Function display path, for example `计算器.加法` or nested `parent.child`. function: String, - /// Named arguments `name=value` (integer, decimal, quoted text, True/False/None). - /// A value may be negative (`a=-2`). `--json` and `--backend` remain flags. + /// Named arguments `name=value` (integer, decimal, quoted text, True/False/None, JSON, `$name`). + /// A value may be negative (`a=-2`). Trailing `toget ` stores the result in the session. + /// `--json` and `--backend` remain flags. args: Vec, /// Print one JSON object: `{"ok":true,"result":...}` or `{"ok":false,"error":...}`. @@ -156,6 +157,18 @@ enum Commands { /// Runtime. Both backends execute the named function. #[arg(long, value_enum, default_value_t = BackendCli::Tree)] backend: BackendCli, + + /// Side effects this call may perform (`none` = pure only; `plugin` allows ABI plugins). + #[arg(long, default_value = "none")] + effects: String, + + /// Call-session id for `toget` / `$name` (default: env `MARQDO_CALL_SESSION` or `default`). + #[arg(long)] + session: Option, + + /// Store the return value under this name in the call session (also: trailing `toget NAME`). + #[arg(long)] + toget: Option, }, /// Static contract cross-check (渐进式契约): drift, unknown types, misplaced tables Check { @@ -171,6 +184,10 @@ enum Commands { #[arg(long)] implicit_labels: bool, + /// Require narration ≥ 50% in each function unit (ext skill contract). + #[arg(long)] + narrative_ratio: bool, + /// Parse an unmarked file with the legacy grammar for migration review. #[arg(long)] legacy_markup: bool, @@ -810,10 +827,41 @@ fn try_main(cli: Cli) -> Result { args, json, backend, + effects, + session, + toget, } => { let outcome = (|| -> Result { - let parsed = marqdo::call::parse_call_args(&args)?; - marqdo::call::call_file(&file, &function, &parsed, backend.into()) + let effects = marqdo::call::CallEffects::parse(&effects)?; + let (arg_tokens, trailing_toget) = marqdo::call::split_toget(&args)?; + let toget = toget.or(trailing_toget); + let parsed = marqdo::call::parse_call_args(&arg_tokens)?; + let session = session.or_else(|| { + if toget.is_some() + || parsed.iter().any(|(_, v)| { + matches!( + v, + marqdo::value::Value::Text(t) + if t.starts_with('$') || t.starts_with('@') + ) + }) + { + Some(marqdo::call_session::default_session_id()) + } else { + None + } + }); + marqdo::call::call_file_with( + &file, + &function, + &parsed, + backend.into(), + marqdo::call::CallOptions { + effects, + session, + toget, + }, + ) })(); match outcome { Ok(value) => { @@ -849,15 +897,19 @@ fn try_main(cli: Cli) -> Result { file, json, implicit_labels, + narrative_ratio, legacy_markup, } => { - let diags = if legacy_markup { + let mut diags = if legacy_markup { marqdo::parse::expr::with_markup(marqdo::parse::expr::Markup::Classic, || { marqdo::check::check_path_opts(&file, implicit_labels) })? } else { marqdo::check::check_path_opts(&file, implicit_labels)? }; + if narrative_ratio { + diags.extend(marqdo::narrative_ratio::check_file(&file)?); + } let mut errors = 0i32; for d in &diags { if matches!(d.severity, marqdo::diagnostics::Severity::Error) { diff --git a/src/narrative_ratio.rs b/src/narrative_ratio.rs new file mode 100644 index 0000000..cdab534 --- /dev/null +++ b/src/narrative_ratio.rs @@ -0,0 +1,222 @@ +//! Narration ratio gate: each function unit should be ≥50% narrative text. +//! +//! Used by `marqdo check --narrative-ratio` and extension skill dogfood. + +use std::path::Path; + +use anyhow::Result; + +use crate::ast::Function; +use crate::diagnostics::{Diagnostic, Span}; +use crate::load::load_module; + +const MIN_RATIO: f64 = 0.5; + +#[derive(Debug, Clone)] +pub struct UnitReport { + pub name: String, + pub line: u32, + pub narrative: usize, + pub total: usize, + pub ratio: f64, + pub pass: bool, +} + +/// Check one `.mq.md` file; returns Error diagnostics for failing units. +pub fn check_file(path: &Path) -> Result> { + let reports = check_file_source(path)?; + Ok(reports + .iter() + .filter(|r| !r.pass) + .map(|r| { + Diagnostic::new( + Some(path), + Span::new(r.line, 1), + format!( + "narrative ratio {:.0}% < 50% for function `{}` (narrative={}, total={})", + r.ratio * 100.0, + r.name, + r.narrative, + r.total + ), + ) + .with_code("narrative.ratio") + }) + .collect()) +} + +/// Measure using original file text between this function's line and the next heading. +pub fn check_file_source(path: &Path) -> Result> { + let text = std::fs::read_to_string(path)?; + let module = load_module(path)?; + Ok(measure_source_units(&text, &module.functions)) +} + +pub fn measure_source_units(source: &str, functions: &[Function]) -> Vec { + let lines: Vec<&str> = source.lines().collect(); + let mut starts: Vec<(String, u32, usize)> = Vec::new(); + collect_starts(functions, &mut starts); + starts.sort_by_key(|(_, line, _)| *line); + + let mut out = Vec::new(); + for (i, (name, line, _)) in starts.iter().enumerate() { + let start = (*line as usize).saturating_sub(1); + let end = starts + .get(i + 1) + .map(|(_, l, _)| (*l as usize).saturating_sub(1)) + .unwrap_or(lines.len()); + let chunk = lines[start..end.min(lines.len())].join("\n"); + let (narrative, code) = split_narrative_code(&chunk); + let total = narrative + code; + let ratio = if total == 0 { + 1.0 + } else { + narrative as f64 / total as f64 + }; + out.push(UnitReport { + name: name.clone(), + line: *line, + narrative, + total, + ratio, + pass: total == 0 || ratio + f64::EPSILON >= MIN_RATIO, + }); + } + out +} + +fn collect_starts(fns: &[Function], out: &mut Vec<(String, u32, usize)>) { + for f in fns { + out.push((f.name.clone(), f.span.line, f.body.len())); + collect_starts(&f.children, out); + } +} + +/// Split a function unit's source into narrative vs code character counts. +/// +/// Code: lines that are primarily executable markers (`>`, `**`, `*…*`, `+`, tables with `|`, +/// fences, `#`/`##` headings themselves). Narrative: remaining prose (including formula fences +/// content is counted as narrative — formulas are documentation). +pub fn split_narrative_code(chunk: &str) -> (usize, usize) { + let mut narrative = 0usize; + let mut code = 0usize; + let mut in_fence = false; + let mut fence_is_formula = false; + for line in chunk.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("```") || trimmed.starts_with("~~~") { + in_fence = !in_fence; + fence_is_formula = trimmed.contains("$$") || trimmed == "$$"; + // Fence markers themselves are markup/code budget. + code += line.chars().count(); + continue; + } + if in_fence { + // Math/display fences count as narration; language fences as code. + if fence_is_formula { + narrative += line.chars().count(); + } else { + code += line.chars().count(); + } + continue; + } + if trimmed.is_empty() { + continue; + } + // Standalone $$ formula blocks (Marqdo formula assignment bodies). + if trimmed == "$$" || trimmed.starts_with("$$") { + narrative += line.chars().count(); + continue; + } + if is_code_line(trimmed) { + code += line.chars().count(); + } else { + narrative += line.chars().count(); + } + } + (narrative, code) +} + +fn is_code_line(trimmed: &str) -> bool { + if trimmed.starts_with('>') { + return true; + } + if trimmed.starts_with("**") && trimmed.ends_with("**") { + return true; + } + if trimmed.starts_with('*') && trimmed.ends_with('*') && !trimmed.starts_with("**") { + // Return line + return true; + } + if trimmed.starts_with("+ `") || trimmed.starts_with("+`") { + return true; + } + // Contract / documentation tables are narration surface (param and return + // tables under skill tools), not executable code budget. + if trimmed.starts_with('|') { + return false; + } + if trimmed.starts_with('#') { + return true; + } + if trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains(". ") { + // Branch list `1. …` — executable control + return true; + } + if trimmed.starts_with("- ") && (trimmed.contains('>') || trimmed.contains('`')) { + return true; + } + if trimmed.starts_with("---") { + return true; + } + if trimmed.starts_with("import:") || trimmed.starts_with("导入:") { + return true; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prose_heavy_unit_passes() { + let chunk = r#" +## hadamard + +The Hadamard gate creates equal superposition from the computational basis. +It is the unitary matrix shown below and is central to many algorithms. + +| 参数 | 类型 | 说明 | +|------|------|------| +| qubit | number | target | + +This paragraph keeps narration above half even with a small table. + +| 返回 | 类型 | 说明 | +|------|------|------| +| | handle | circuit | + +*None* +"#; + let (n, c) = split_narrative_code(chunk); + assert!( + (n as f64) / ((n + c) as f64) >= 0.5, + "n={n} c={c}" + ); + } + + #[test] + fn api_list_fails() { + let chunk = r#" +## h + + `qubit`=0 +*> quantum_h circuit=`self` qubit=`qubit`* +"#; + let (n, c) = split_narrative_code(chunk); + assert!( + (n as f64) / ((n + c) as f64) < 0.5, + "n={n} c={c}" + ); + } +} diff --git a/tests/call/nested.mq.md b/tests/call/nested.mq.md new file mode 100644 index 0000000..c26bd61 --- /dev/null +++ b/tests/call/nested.mq.md @@ -0,0 +1,41 @@ +--- +markup: occlusion +title: nested ### sub-tool call +--- + +# main + +*None* + +## outer + +Parent tool. Agents may call this path or the finer nested helper. + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | seed value | + +This paragraph is narration so the unit stays readable. The nested +`### helper` is the sub-tool that does the arithmetic. Call path +`outer.helper` selects the child without running the parent body. + +### helper + +| 参数 | 类型 | 说明 | +|------|------|------| +| n | number | value to double | + +Sub-tool under `outer`. Doubles `n` without side effects so default +`marqdo call` may run it. Prefer this when only the doubling step is needed. + +| 返回 | 类型 | 说明 | +|------|------|------| +| | number | two times n | + +*[result](n * 2)* + +| 返回 | 类型 | 说明 | +|------|------|------| +| | number | parent returns n unchanged | + +*n* diff --git a/tests/call_cli.rs b/tests/call_cli.rs index 19297e7..d19710a 100644 --- a/tests/call_cli.rs +++ b/tests/call_cli.rs @@ -217,3 +217,91 @@ fn impure_calls_do_not_run() { "denied write must not create sent.txt" ); } + +#[test] +fn nested_subtool_path_resolves() { + let file = root().join("tests/call/nested.mq.md"); + for backend in ["tree", "bytecode"] { + assert_value(&file, "outer.helper", &["n=3"], backend, "6"); + assert_value(&file, "helper", &["n=4"], backend, "8"); + } +} + +#[test] +fn plugin_effects_flag_allows_quantum_ensure() { + let file = root().join("ext/quantum/_capability/index.mq.md"); + let out = run(&[ + "call", + "--effects", + "plugin", + "--json", + file.to_str().unwrap(), + "load", + ]); + assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout)); + let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap(); + assert_eq!(body["ok"], true, "{body}"); +} + +#[test] +fn quantum_index_bell_via_call() { + let file = root().join("ext/quantum/index.mq.md"); + let out = run(&[ + "call", + "--effects", + "plugin", + "--json", + file.to_str().unwrap(), + "bell_phi_plus", + ]); + assert_eq!(out.status.code(), Some(0), "{}", text(&out.stdout)); + let body: serde_json::Value = serde_json::from_str(&text(&out.stdout)).unwrap(); + assert_eq!(body["ok"], true, "{body}"); + let p00 = body["result"]["00"].as_f64().unwrap(); + let p11 = body["result"]["11"].as_f64().unwrap(); + assert!((p00 - 0.5).abs() < 0.05, "{body}"); + assert!((p11 - 0.5).abs() < 0.05, "{body}"); +} + +#[test] +fn toget_persists_serializable_value() { + let dir = std::env::temp_dir().join(format!("mq-call-sess-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let file = root().join("tests/call/nested.mq.md"); + let sess = "toget-demo"; + let out1 = Command::new(bin()) + .env("MARQDO_CALL_SESSION_DIR", &dir) + .args([ + "call", + "--session", + sess, + "--toget", + "x", + "--json", + file.to_str().unwrap(), + "helper", + "n=5", + ]) + .current_dir(root()) + .output() + .unwrap(); + assert_eq!(out1.status.code(), Some(0), "{}", text(&out1.stdout)); + let out2 = Command::new(bin()) + .env("MARQDO_CALL_SESSION_DIR", &dir) + .args([ + "call", + "--session", + sess, + "--json", + file.to_str().unwrap(), + "helper", + "n=$x", + ]) + .current_dir(root()) + .output() + .unwrap(); + assert_eq!(out2.status.code(), Some(0), "{}", text(&out2.stdout)); + let body: serde_json::Value = serde_json::from_str(&text(&out2.stdout)).unwrap(); + assert_eq!(body["result"], 20, "{body}"); +} diff --git a/tests/ext/quantum-amp-damp-smoke.mq.md b/tests/ext/quantum-amp-damp-smoke.mq.md index 0af9620..3731611 100644 --- a/tests/ext/quantum-amp-damp-smoke.mq.md +++ b/tests/ext/quantum-amp-damp-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum amplitude damping smoke description: X then amplitude_damping p=1 returns all shots to |0>. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/tests/ext/quantum-amp-damp-zh-smoke.mq.md b/tests/ext/quantum-amp-damp-zh-smoke.mq.md index 18edc4f..227a9fe 100644 --- a/tests/ext/quantum-amp-damp-zh-smoke.mq.md +++ b/tests/ext/quantum-amp-damp-zh-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum amplitude damping zh smoke description: 泡利X 后 振幅阻尼 p=1 全部落回 |0⟩. 导入: - 量子: ext/quantum/量子.mq.md + 量子: ext/quantum/量子/电路/索引.mq.md --- # main diff --git a/tests/ext/quantum-author-api-smoke.mq.md b/tests/ext/quantum-author-api-smoke.mq.md index 7bc5f78..ede5b32 100644 --- a/tests/ext/quantum-author-api-smoke.mq.md +++ b/tests/ext/quantum-author-api-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum author API smoke description: barrier, measure, append, state, draw meters. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/tests/ext/quantum-author-api-zh-smoke.mq.md b/tests/ext/quantum-author-api-zh-smoke.mq.md index 49d0958..873184a 100644 --- a/tests/ext/quantum-author-api-zh-smoke.mq.md +++ b/tests/ext/quantum-author-api-zh-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum author API zh smoke description: 屏障 / 测量 / 追加 / 态 / 绘图. 导入: - 量子: ext/quantum/量子.mq.md + 量子: ext/quantum/量子/电路/索引.mq.md --- # main diff --git a/tests/ext/quantum-bell-smoke.mq.md b/tests/ext/quantum-bell-smoke.mq.md index 95da8ed..404ed7d 100644 --- a/tests/ext/quantum-bell-smoke.mq.md +++ b/tests/ext/quantum-bell-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum bell smoke description: H+CX Bell state probabilities ≈ 1/2 each. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md math: lib/math.mq.md --- diff --git a/tests/ext/quantum-custom-gate-smoke.mq.md b/tests/ext/quantum-custom-gate-smoke.mq.md index c707b16..aa22346 100644 --- a/tests/ext/quantum-custom-gate-smoke.mq.md +++ b/tests/ext/quantum-custom-gate-smoke.mq.md @@ -3,7 +3,8 @@ markup: occlusion title: quantum custom gate from formula matrix description: $$ H matrix $$ → gate matrix= → apply → probs match built-in H. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md + gate: ext/quantum/gate/index.mq.md math: lib/math.mq.md --- @@ -14,7 +15,7 @@ $$ \frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix} $$ -**U = > quantum.gate matrix=`H_matrix` name="U"** +**U = > gate.gate matrix=`H_matrix` name="U"** **qc = > quantum.circuit qubits=1** **qc = > `qc`.apply gate=`U` qubits=0** **p = > `qc`.probabilities** diff --git a/tests/ext/quantum-custom-gate-zh-smoke.mq.md b/tests/ext/quantum-custom-gate-zh-smoke.mq.md index 711e483..70ccbe6 100644 --- a/tests/ext/quantum-custom-gate-zh-smoke.mq.md +++ b/tests/ext/quantum-custom-gate-zh-smoke.mq.md @@ -3,7 +3,8 @@ markup: occlusion title: quantum custom gate zh from formula description: $$ 矩阵 $$ → 门 矩阵= → 施加. 导入: - 量子: ext/quantum/量子.mq.md + 量子: ext/quantum/量子/电路/索引.mq.md + 门: ext/quantum/量子/门/索引.mq.md math: lib/math.mq.md --- @@ -14,7 +15,7 @@ $$ \frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\1&-1\end{pmatrix} $$ -**U = > 量子.门 矩阵=`H矩阵` 名="U"** +**U = > 门.门 矩阵=`H矩阵` 名="U"** **qc = > 量子.电路 比特数=1** **qc = > `qc`.施加 门=`U` 比特=0** **p = > `qc`.概率** diff --git a/tests/ext/quantum-draw-smoke.mq.md b/tests/ext/quantum-draw-smoke.mq.md index 939d16c..fbeeddc 100644 --- a/tests/ext/quantum-draw-smoke.mq.md +++ b/tests/ext/quantum-draw-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum draw probs/bloch smoke description: draw kind=probs and kind=bloch return matching kind tags. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/tests/ext/quantum-gate-heatmap-smoke.mq.md b/tests/ext/quantum-gate-heatmap-smoke.mq.md index 794223d..e57d086 100644 --- a/tests/ext/quantum-gate-heatmap-smoke.mq.md +++ b/tests/ext/quantum-gate-heatmap-smoke.mq.md @@ -3,12 +3,13 @@ markup: occlusion title: quantum gate matrix heatmap smoke description: gate.draw kind=matrix writes SVG heatmap. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md + gate: ext/quantum/gate/index.mq.md --- # main -**H = > quantum.gate name="H"** +**H = > gate.gate name="H"** **img = > `H`.draw kind="matrix" path="quantum-gate-heatmap.svg"** **kind = [kind](access(img, "kind"))** diff --git a/tests/ext/quantum-gate-matrix-smoke.mq.md b/tests/ext/quantum-gate-matrix-smoke.mq.md index 6750dae..a779e36 100644 --- a/tests/ext/quantum-gate-matrix-smoke.mq.md +++ b/tests/ext/quantum-gate-matrix-smoke.mq.md @@ -3,14 +3,15 @@ markup: occlusion title: quantum gate matches_matrix smoke description: Named H matches an explicit 2x2 nested list. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md + gate: ext/quantum/gate/index.mq.md json: lib/json.mq.md --- # main **H_matrix = > json.parse text=[[0.7071067811865475,0.7071067811865475],[0.7071067811865475,-0.7071067811865475]]** -**H = > quantum.gate name="H"** +**H = > gate.gate name="H"** **ok = > `H`.matches_matrix matrix=`H_matrix`** 1. `ok` diff --git a/tests/ext/quantum-gates-smoke.mq.md b/tests/ext/quantum-gates-smoke.mq.md index caea173..04b887f 100644 --- a/tests/ext/quantum-gates-smoke.mq.md +++ b/tests/ext/quantum-gates-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum gates + run smoke description: Z sandwich, Ry(pi), seeded Bell run counts. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md math: lib/math.mq.md --- diff --git a/tests/ext/quantum-linalg-smoke.mq.md b/tests/ext/quantum-linalg-smoke.mq.md index 979a9ec..614931b 100644 --- a/tests/ext/quantum-linalg-smoke.mq.md +++ b/tests/ext/quantum-linalg-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum linalg smoke description: Q7a density / partial_trace / expect / schmidt / purity import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md math: lib/math.mq.md --- diff --git a/tests/ext/quantum-noise-smoke.mq.md b/tests/ext/quantum-noise-smoke.mq.md index c92f618..6c54f18 100644 --- a/tests/ext/quantum-noise-smoke.mq.md +++ b/tests/ext/quantum-noise-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum noise smoke description: bitflip p=1 after I flips |0> to |1| for all shots. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/tests/ext/quantum-noise-zh-smoke.mq.md b/tests/ext/quantum-noise-zh-smoke.mq.md index ed728fb..f151635 100644 --- a/tests/ext/quantum-noise-zh-smoke.mq.md +++ b/tests/ext/quantum-noise-zh-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum noise zh smoke description: 噪声 bitflip p=1 后 I 使全部射中 |1⟩. 导入: - 量子: ext/quantum/量子.mq.md + 量子: ext/quantum/量子/电路/索引.mq.md --- # main diff --git a/tests/ext/quantum-steps-smoke.mq.md b/tests/ext/quantum-steps-smoke.mq.md index 0957cc6..07fdcd8 100644 --- a/tests/ext/quantum-steps-smoke.mq.md +++ b/tests/ext/quantum-steps-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum steps + draw smoke description: steps= Bell table + draw SVG via record_plot. import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md math: lib/math.mq.md --- diff --git a/tests/ext/quantum-viz-advanced-smoke.mq.md b/tests/ext/quantum-viz-advanced-smoke.mq.md index 1aa9078..c26991c 100644 --- a/tests/ext/quantum-viz-advanced-smoke.mq.md +++ b/tests/ext/quantum-viz-advanced-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum viz advanced smoke description: Q7b hinton / qsphere / multibloch SVG markers import: - quantum: ext/quantum/quantum.mq.md + quantum: ext/quantum/circuit/index.mq.md --- # main diff --git a/tests/ext/quantum-zh-smoke.mq.md b/tests/ext/quantum-zh-smoke.mq.md index b4adc1a..3159db7 100644 --- a/tests/ext/quantum-zh-smoke.mq.md +++ b/tests/ext/quantum-zh-smoke.mq.md @@ -3,7 +3,7 @@ markup: occlusion title: quantum zh API smoke description: Chinese 量子.电路 泡利Z sandwich. 导入: - 量子: ext/quantum/量子.mq.md + 量子: ext/quantum/量子/电路/索引.mq.md math: lib/math.mq.md ---