docs(public): showcase foreign v2, OKF and EKC

Rewrite the public foreign reference, add bilingual complex Python notebook and OKF/EKC pages, and expand both homepages with executable foreign, notebook, knowledge and preflight examples.
This commit is contained in:
cflmy committed 2026-10-18 03:15:34 +08:00
1 parent 81f9ea0072
commit e6f05c7748
12 files changed
+1015 -20

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
---
title: Foreign kernels v2 — a Python analysis notebook
description: A complete Python data walkthrough with probe, JSON calls, parallel fan-out, persistent state, an explicit bridge and document-native notebook cells
import foreign:lib/foreign.mq.md
---
# main
This page is both a readable document and a runnable program. It uses the same file to show the foreign-kernel features added in v2: language probing, structured records, JSON in/out, parallel fan-out, a persistent Python kernel, and an explicit state bridge.
The data is intentionally small and deterministic, so every number below can be reproduced by running the page.
---
The input.
`orders` =
| @ | region | amount |
|---|--------|--------|
| 1 | 华东 | 120 |
| 2 | 华东 | 300 |
| 3 | 华南 | 90 |
| 4 | 华南 | 140 |
| 5 | 华北 | 220 |
| 6 | 西部 | 80 |
---
Probe Python before using it.
**python = > foreign.probe lang="python"**
> print text=[ok](`python`)
> print text=[version](`python`)
The probe record also carries `cmd`, `path` and `error`, so a site can explain a missing interpreter instead of producing a blank cell.
---
A JSON call. Python reads the table as JSON, groups it, and writes one JSON result.
`analyze` =
```python
import json
import statistics
import sys
rows = json.load(sys.stdin)
by_region = {}
for row in rows:
by_region.setdefault(row["region"], []).append(float(row["amount"]))
summary = []
for region, values in sorted(by_region.items()):
mean = statistics.mean(values)
sd = statistics.pstdev(values) or 1.0
summary.append({
"region": region,
"orders": len(values),
"total": round(sum(values), 2),
"mean": round(mean, 2),
"z_span": round((max(values) - mean) / sd, 3),
})
print(json.dumps({
"regions": summary,
"total": round(sum(float(row["amount"]) for row in rows), 2),
"count": len(rows),
}, ensure_ascii=False))
```
**result = > foreign.call code=`analyze` input=`orders`**
> print text=[count](`result`)
> print text=[total](`result`)
> print text=[region]([1]([regions](`result`)))
> print text=[mean]([1]([regions](`result`)))
A call is JSON-in / JSON-out: the table is encoded on stdin, and the final stdout value is parsed into Marqdo values.
---
The same work as a structured record. `invoke` keeps stdout, stderr, exit code and timing even when the program fails.
**record = > foreign.invoke code=`analyze` input=`orders` output="json"**
> print text=[ok](`record`)
> print text=[code](`record`)
> print text=[ms](`record`)
Here `result` is already a parsed value, while `stdout` remains available for logging.
---
Persistent Python state. The first evaluation imports a module and creates a list; the second evaluation sees both.
**session = > foreign.session_open lang="python"**
**first = > foreign.session_eval id=`session` source="import math\nvalues = [3, 4, 5]"**
**second = > foreign.session_eval id=`session` source="round(math.sqrt(sum(value * value for value in values)), 3)"**
> print text=[result](`second`)
The kernel is strict and serial: evaluations do not interleave, and a timeout kills the process group.
---
The explicit state bridge. Values cross as JSON copies, never as shared object references.
**> foreign.session_set id=`session` name="threshold" value=2.5**
**threshold = > foreign.session_get id=`session` name="threshold"**
> print text=`threshold`
**> foreign.session_close id=`session`**
No implicit mirroring: if a variable is not pushed or pulled, the other side does not see it.
---
Parallel fan-out. Every input gets its own process; failures are isolated and order is preserved.
`increment` =
```python
import json
import sys
value = json.load(sys.stdin)
print(json.dumps(value + 1))
```
`numbers` =
| value |
|-------|
| 1 |
| 2 |
| 3 |
| 4 |
**bumped = > foreign.call_many code=`increment` inputs=`numbers` concurrency=4**
> print text=`bumped`
---
A document-native notebook. Named kernels and a session table are ordinary bound data tables, not fence metadata or YAML config.
```text
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | shared analysis |
| 复核 | python | | isolated review |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | generate orders |
| 计算指标 | 分析 | regions and totals |
| 独立复核 | 复核 | read the JSON report |
```
Live `view` renders these as cells with Run All, Step, per-cell kernel switching, a journal, dirty reload and a state panel. The same file still runs as a single program.
---
Why this stays readable.
| Layer | What the reader sees |
|---|---|
| Markdown | headings, prose, tables and fenced code |
| Program | assignments, calls and return values |
| Knowledge | frontmatter, links, task pages and generated catalog entries |
The foreign layer does not add syntax to the language. A fence is still a fence; a table is still a table.
For the lower-level API and safety defaults, read [`../../lib/foreign.mq.md`](../../lib/foreign.mq.md) and [`../../doc/design/foreign-kernel.md`](../../doc/design/foreign-kernel.md).
+183
View File
@@ -0,0 +1,183 @@
---
title: 外联内核 v2 — Python 分析 Notebook
description: 从 probe、JSON 调用、并行扇出、持久状态到显式桥与文档原生 notebook 单元的完整 Python 示例
导入 外联:lib/外联.mq.md
---
# main
这一页既是可读文档,也是可运行程序。它用同一份文件展示 v2 的外联内核能力:语言探测、结构化记录、JSON 进出、并行扇出、持久 Python 内核,以及显式状态桥。
数据故意保持小而确定,因此下面每个数字都可以通过运行本页复现。
---
输入数据。
`订单` =
| @ | 区域 | 金额 |
|---|------|------|
| 1 | 华东 | 120 |
| 2 | 华东 | 300 |
| 3 | 华南 | 90 |
| 4 | 华南 | 140 |
| 5 | 华北 | 220 |
| 6 | 西部 | 80 |
---
先探测 Python。
**python = > 外联.探测 语言="python"**
> 打印 内容=[ok](`python`)
> 打印 内容=[version](`python`)
探测记录还带 `cmd`、`path` 与 `error`,所以站点可以解释“解释器缺失”,而不是显示一个空白单元。
---
JSON 调用。Python 把表读成 JSON,按区域聚合,再写出一个 JSON 结果。
`分析` =
```python
import json
import statistics
import sys
rows = json.load(sys.stdin)
by_region = {}
for row in rows:
by_region.setdefault(row["区域"], []).append(float(row["金额"]))
summary = []
for region, values in sorted(by_region.items()):
mean = statistics.mean(values)
sd = statistics.pstdev(values) or 1.0
summary.append({
"region": region,
"orders": len(values),
"total": round(sum(values), 2),
"mean": round(mean, 2),
"z_span": round((max(values) - mean) / sd, 3),
})
print(json.dumps({
"regions": summary,
"total": round(sum(float(row["金额"]) for row in rows), 2),
"count": len(rows),
}, ensure_ascii=False))
```
**结果 = > 外联.调用 代码=`分析` 输入=`订单`**
> 打印 内容=[count](`结果`)
> 打印 内容=[total](`结果`)
> 打印 内容=[region]([1]([regions](`结果`)))
> 打印 内容=[mean]([1]([regions](`结果`)))
调用是 JSON 进 / JSON 出:表编码到 stdin,stdout 的最后一个值再解析成 Marqdo 值。
---
同样的工作也可以保留成结构化记录。`执行` 即使进程失败也保留 stdout、stderr、退出码与耗时。
**记录 = > 外联.执行 代码=`分析` 输入=`订单` 输出="json"**
> 打印 内容=[ok](`记录`)
> 打印 内容=[code](`记录`)
> 打印 内容=[ms](`记录`)
这里 `result` 已经是解析后的值,同时 `stdout` 仍可用于日志。
---
持久 Python 状态。第一次求值导入模块并创建列表;第二次求值仍能看到两者。
**会话 = > 外联.会话开启 语言="python"**
**第一次 = > 外联.会话求值 标识=`会话` 源码="import math\nvalues = [3, 4, 5]"**
**第二次 = > 外联.会话求值 标识=`会话` 源码="round(math.sqrt(sum(value * value for value in values)), 3)"**
> 打印 内容=[result](`第二次`)
内核严格串行:求值不会交错,超时会杀掉进程组。
---
显式状态桥。值以 JSON 拷贝跨越边界,永远不是共享对象引用。
**> 外联.会话设值 标识=`会话` 名称="threshold" 值=2.5**
**阈值 = > 外联.会话取值 标识=`会话` 名称="threshold"**
> 打印 内容=`阈值`
**> 外联.会话关闭 标识=`会话`**
没有隐式镜像:没有 push / pull 的变量,另一边看不到。
---
并行扇出。每个输入都有独立进程;失败互相隔离,顺序保持不变。
`加一` =
```python
import json
import sys
value = json.load(sys.stdin)
print(json.dumps(value + 1))
```
`数值` =
| value |
|-------|
| 1 |
| 2 |
| 3 |
| 4 |
**加一后 = > 外联.批量调用 代码=`加一` 输入表=`数值` 并发=4**
> 打印 内容=`加一后`
---
文档原生 Notebook。命名内核和会话表都是普通绑定数据表,不是 fence 元数据或 YAML 配置。
```text
`内核表` =
| 名称 | 语言 | 命令 | 说明 |
|------|------|------|------|
| 分析 | python | | 共享分析 |
| 复核 | python | | 独立复核 |
`会话表` =
| 单元 | 内核 | 说明 |
|------|------|------|
| 准备数据 | 分析 | 生成订单 |
| 计算指标 | 分析 | 区域与总额 |
| 独立复核 | 复核 | 读取 JSON 报告 |
```
live `view` 会把这些渲染成带 Run All、Step、切换内核、journal、dirty reload 和状态面板的单元。同一份文件仍可作为单个程序运行。
---
为什么它仍然可读。
| 层 | 读者看到什么 |
|---|---|
| Markdown | 标题、叙述、表格与围栏代码 |
| 程序 | 赋值、调用与返回值 |
| 知识 | frontmatter、链接、任务页与生成的 catalog 条目 |
外联层没有给语言新增语法。围栏还是围栏,表还是表。
底层 API 与安全默认值见 [`../../lib/外联.mq.md`](../../lib/外联.mq.md) 与 [`../../doc/design/foreign-kernel.md`](../../doc/design/foreign-kernel.md)。
+135
View File
@@ -0,0 +1,135 @@
---
title: 代码即文档,文档即知识 — OKF 与 EKC
description: Marqdo 如何以一份可执行源为唯一权威,把它投影成 OKF 风格知识与 Engineering Knowledge Compiler 制品
---
# main
Marqdo 的宪法是「代码即文档,文档即知识库」。`.mq.md` 不是程序截图:它同时是可读源码、可执行单元和知识页。
这个承诺只有在知识始终从源派生时才成立。OKF 提供可移植知识包的形态;EKC 提供工程化投影。二者都不成为第二份权威。
---
OKF 的形,Marqdo 的义。
OKF(Open Knowledge Format)用 Markdown + YAML frontmatter 表示知识:一页一概念、路径即身份、链接成图、强制面刻意保持很小。Marqdo 借用这个形态,但正文是可执行语法。
因此概念页可以直接指向证明它的文件:
```yaml
type: Capability
title: 持久外联内核
description: 在命名内核中运行 Python 或 Node 并保留状态
resource: public/features/19-外联Notebook.mq.md
status: stable
verified:
by: marqdo-knowledge/verify
tags:
- foreign
- notebook
```
同一页可以在编辑器里读、从 catalog 链接、被 Agent 查询,也可以直接运行。未知字段保留;未知类型降级为可读正文。概念页不是源文件的复制品。
---
哪些是生成的,哪些不是。
| 层 | 作者 | 职责 |
|---|---|---|
| 源 | 人或编码 Agent | .mq.md;唯一语义权威 |
| 目录包 | marqdo catalog | 模块、符号、能力与图投影 |
| 任务知识 | plan 晋升 | 任务、技能与可执行资源包 |
| 静态站 | marqdo view output | 人读 HTML,永远不是权威 |
生成物带 GENERATED 标记,可以删除重建;没有它们源树仍能运行。Catalog 是索引,不是语言特性。
---
EKC:Engineering Knowledge Compiler。
EKC 把仓库投影成工程知识系统,并在 Agent 写新代码前提供 preflight:
```text
.mq.md ──► EKC ──► catalog L0–L4
├─ graph
├─ context pack
└─ Agent preflight
```
| 层 | 知识 | 例子 |
|---|---|---|
| L0 Repository | 语言、规模、根目录 | 仓库总览 |
| L1 Module | imports、exports、职责 | 外联内核模块 |
| L2 Symbol | 签名、调用、指纹 | Python 分析函数 |
| L3 Capability | 工程能做什么 | 运行持久外联内核 |
| L4 Knowledge | 决策、约束、失败 | 为什么状态桥必须显式 |
图记录 implements、uses、depends_on、tested_by、documented_by、constrained_by、decided_by、supersedes、conflicts_with、deprecated_by 等关系。Agent 先沿图发现已有能力,而不是重新造轮子。
---
Engineering First Information:先发现,再创建。
复用协议是硬顺序:
```text
REUSE → ADAPT → CREATE
```
preflight 可以在实现开始前返回已有能力、API、约束、决策与失败经验。知识图缺失时返回明确的 missing_knowledge,而不是静默编造。
五条原则:
| # | 原则 |
|---|---|
| 1 | Discover before Create |
| 2 | Reuse before Adapt |
| 3 | Adapt before Duplicate |
| 4 | Verify before Promote |
| 5 | Code changes update knowledge |
---
命令。
```bash
# 把仓库投影成 catalog + EKC 制品
marqdo catalog .
# 写代码前先问:已经有了什么?
marqdo knowledge preflight "增加一个持久外联内核"
marqdo find "外联 会话"
marqdo reuse "实现 JSON 并行扇出"
# 看一次修改会影响什么
marqdo impact public/features/19-外联Notebook.mq.md
# 校验知识投影
marqdo knowledge verify
```
`marqdo catalog` 保留人读的 `index.md` 与模块页;EKC 在 `.marqdo/` 下增加 L0–L4。两者都从同一棵源树生成。
---
每个声称的能力都必须有可执行资源。
一个知识页说“这个工程能分析订单”,就必须指向一个真正能跑的 `.mq.md` 资源。这是 OKF 形态的笔记与可执行知识系统的区别。
在外联示例里,页面本身就是证明:Python 调用、持久内核和状态桥都从读者正在看的同一份 Markdown 源运行。没有另一个会漂移的演示项目。
---
继续阅读。
OKF 设计:[OKF 设计](../../doc/design/okf.md)
Engineering Knowledge Compiler:[Engineering Knowledge Compiler](../../doc/design/engineering-knowledge.md)
Catalog CLI:[Catalog CLI](../../doc/design/catalog-cli.md)
OKF 与 Marqdo 调研:[OKF 与 Marqdo 调研](../../doc/research/okf-and-marqdo.md)
外联 Notebook 示例:[外联 Notebook 示例](19-外联Notebook.mq.md)
+135
View File
@@ -0,0 +1,135 @@
---
title: Code as documentation, documentation as knowledge — OKF and EKC
description: How Marqdo keeps one executable source of truth while projecting it into OKF-style knowledge and Engineering Knowledge Compiler artifacts
---
# main
Marqdo's constitution is code as documentation and documentation as knowledge. A `.mq.md` file is not a screenshot of a program: it is the readable source, the executable unit and the knowledge page at the same time.
That claim matters only if the knowledge stays derived from the source. OKF gives us the shape of a portable knowledge bundle; EKC gives us the engineering projection. Neither becomes a second source of truth.
---
OKF shape, Marqdo meaning.
OKF (Open Knowledge Format) describes knowledge as Markdown pages with YAML frontmatter: one concept per page, path as identity, links as graph, a deliberately small required surface. Marqdo borrows that shape, but its body is executable.
A concept page can therefore point at the exact file that proves it:
```yaml
type: Capability
title: Persistent foreign kernels
description: Run Python or Node in a named, stateful kernel
resource: public/features/19-foreign-notebook.mq.md
status: stable
verified:
by: marqdo-knowledge/verify
tags:
- foreign
- notebook
```
The same page can be opened in an editor, linked from a catalog, queried by an agent, and executed. Unknown fields are preserved; unknown types degrade to readable prose. The page is a concept, not a copy of one.
---
What is generated, and what is not.
| Layer | Author | Role |
|---|---|---|
| Source | person or coding agent | .mq.md; the only semantic authority |
| Catalog | marqdo catalog | module, symbol, capability and graph projection |
| Task knowledge | plan promotion | task, skill and executable resource bundle |
| Static site | marqdo view output | human-readable HTML, never an authority |
Generated artifacts are marked GENERATED and can be deleted and rebuilt. The source tree still runs without them. A catalog is an index, not a language feature.
---
EKC: the Engineering Knowledge Compiler.
EKC projects the repository into an engineering knowledge system, then exposes it through a preflight before an agent writes new code:
```text
.mq.md ──► EKC ──► catalog L0–L4
├─ graph
├─ context pack
└─ Agent preflight
```
| Layer | Knowledge | Example |
|---|---|---|
| L0 Repository | language, size, roots | repository summary |
| L1 Module | imports, exports, responsibility | a foreign kernel module |
| L2 Symbol | signature, calls, fingerprint | a Python analysis function |
| L3 Capability | what the project can do | run a persistent foreign kernel |
| L4 Knowledge | decisions, constraints, failures | why the bridge is explicit |
The graph records relations such as implements, uses, depends_on, tested_by, documented_by, constrained_by, decided_by, supersedes, conflicts_with and deprecated_by. That graph is how an agent discovers existing capability before inventing a duplicate.
---
Engineering First Information: discover before create.
The reuse protocol is a hard order:
```text
REUSE → ADAPT → CREATE
```
A preflight can return existing capabilities, APIs, constraints, decisions and failure notes before a new implementation starts. If the knowledge graph is missing, the result is an explicit missing_knowledge state, not a silent fabrication.
The five principles are:
| # | Principle |
|---|---|
| 1 | Discover before Create |
| 2 | Reuse before Adapt |
| 3 | Adapt before Duplicate |
| 4 | Verify before Promote |
| 5 | Code changes update knowledge |
---
The commands.
```bash
# Project the repository into catalog + EKC artifacts
marqdo catalog .
# Ask what already exists before writing code
marqdo knowledge preflight "add a persistent foreign kernel"
marqdo find "foreign session"
marqdo reuse "implement JSON fan-out"
# See what a change would touch
marqdo impact public/features/19-foreign-notebook.mq.md
# Validate the knowledge projection
marqdo knowledge verify
```
`marqdo catalog` keeps the human-readable `index.md` and module pages; EKC adds L0–L4 files under `.marqdo/`. Both are generated from the same source tree.
---
Every claimed capability has an executable resource.
A knowledge page that says “this project can analyze orders” must point to a `.mq.md` resource that actually runs. That is the difference between an OKF-shaped note and an executable knowledge system.
In the foreign example, the page itself is the proof: the Python call, the persistent kernel and the state bridge all run from the same Markdown source that a reader is looking at. There is no separate demo project to drift out of sync.
---
Read more.
OKF design: [OKF design](../../doc/design/okf.md)
Engineering Knowledge Compiler: [Engineering Knowledge Compiler](../../doc/design/engineering-knowledge.md)
Catalog CLI: [Catalog CLI](../../doc/design/catalog-cli.md)
OKF and Marqdo research: [OKF and Marqdo research](../../doc/research/okf-and-marqdo.md)
Foreign notebook example: [Foreign notebook example](19-foreign-notebook.mq.md)