Compare commits

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

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

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

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

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

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

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

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

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 11:17:25 +08:00
53 changed files with 3366 additions and 350 deletions

No files matched your search

+15 -1
View File
@@ -141,13 +141,27 @@ import clock:lib/time.mq.md
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; `ext/agent` — document-driven agents: **step** (default writeback) / **plan** workbook ([ext-agent.md](../../doc/design/ext-agent.md), [ext-agent-plan.md](../../doc/design/ext-agent-plan.md)); **`ext/web`** — dynamic sites (W0–W7 + P3 complete; see below); **`ext/quantum`** — circuits + Q7 density/viz + Q8 themed SVG (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
Stdlib map: [reference.md](reference.md).
## Official extension: `ext/agent` (document-driven)
Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --release -p marqdo_plugin_agent`.
**Constitution (do not dilute):**
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`). Inspect without LLM: `dump_step_context`. Inside `writeback=` / `写回=` branches use `host_writeback_record` (param name shadows the writeback import).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
## Official extension: `ext/web` (dynamic sites)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin first: `cargo build --release -p marqdo_plugin_web`.
+1 -1
View File
@@ -54,7 +54,7 @@ Import one file; use **that** file’s function names.
| `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot |
| `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks |
| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | agent **framework** (layout now; LLM orchestration roadmap in `ext-agent.md`) |
| `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 |
+12
View File
@@ -0,0 +1,12 @@
# Local LLM for Marqdo agent / ext/ai/llm development.
# Copy to `.env` in the repo root (gitignored) and fill secrets.
# Never commit real keys.
OPENAI_API_KEY=
OPENAI_BASE_URL=https://llm.cflmy.cn/v1
OPENAI_MODEL=cflmy
# Aliases also accepted by ext/ai/llm:
# MARQDO_LLM_API_KEY=
# MARQDO_LLM_BASE_URL=
# MARQDO_LLM_MODEL=
+4 -4
View File
@@ -92,10 +92,10 @@ jobs:
body: |
## Marqdo ${{ github.ref_name }}
### 亮点 / Highlights — v0.3.3
- **浏览器作者零业务 JS(D/E/F)**:bridge 自启;DOM/路由/storage/ws/文件/Canvas/音频/Observer/拖放;`lib/browser` + GFM
- **Browser author-zero-JS (routes D/E/F)**: host effects + `lib/browser`; examples `browser-hello` / `browser-app` / `browser-media`
- Skill: `marqdo-dev`(代码即文档 / 禁止 json.set 胶水)
### 亮点 / Highlights — v0.3.4
- **`ext/web` 定制 C0–C4**:admin 前缀可让出、段边界 gates、shell/layout、样式 strict、脚本 defer/version、条件导航 when/media
- **ext/web customization C0–C4**: configurable admin/gates/shell/layout/CSS strict/script lifecycle/conditional nav
- Agent Wave B0 demos + writeback shadow fix
- Install: `marqdo ext list` / `marqdo ext add llm|agent|web|quantum`
- Native plugins: `cargo build --release -p marqdo_plugin_*` then `ext add`
- Details: [CHANGELOG](https://github.com/cflmy/marqdo/blob/main/CHANGELOG.md) · [README](https://github.com/cflmy/marqdo/blob/main/README.md)
+1
View File
@@ -23,6 +23,7 @@
.DS_Store
.marqdo/
**/.marqdo/
.marqdo-ext/
.env
# Generated HTML beside tracked public/*.mq.md (sources stay in git)
+31
View File
@@ -8,6 +8,37 @@
### Changed
## v0.3.4 — 2026-09-04
### Highlights
**`ext/web` 定制波次 C0–C4 收口**:可配置 admin 前缀与登录回跳、段边界 gates、shell/layout、样式单元格 strict、脚本 defer/version/`asset_version`、条件导航 when/media。附智能体 Wave B0 示例与写回遮蔽修复。
```bash
git checkout v0.3.4
cargo build --release
cargo build --release -p marqdo_plugin_web
marqdo ext add web
# golds: tests/ext/web-c0-admin-prefix … web-c4-nav-when
```
### Added
- **智能体 Wave B0**:宪法优先示例 [agent-pong](examples/agent-pong/)(call_site/源码注入)· [agent-okf-flywheel](examples/agent-okf-flywheel/)(OKF `cache=hit`);调研 [agent-framework-2026-09.md](doc/research/agent-framework-2026-09.md);离线 harness [`scripts/agent-harness.sh`](scripts/agent-harness.sh);金样 `agent-constitution-b0`。
- **`.env.example`**:开发期 OpenAI 兼容网关变量模板(密钥仅本地 `.env`)。
### Fixed
- **`agent.step` / `plan` 写回**:参数名 `writeback` 遮蔽 `lib/writeback` import,导致 `writeback=True` 时 `method receiver must be an object map`;改为 `host_writeback_record`。金样 `agent-writeback-shadow`。
- **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。
- **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。
- **`ext/web` C2**:`shell_css=full|minimal|off`;`layout=sidebar|stacked|bare|rail`;full 壳含小屏单列 media;金样 `web-c2-shell-layout`。
- **`ext/web` C3**:样式装配对数字/布尔值单元格告警,`strict`/`strict_css_cells` 硬错误;`page.css` 作 raw CSS;head 表支持 `defer`/`async`/`version`,`asset_version` 统一 `?v=`;金样 `web-c3-style-head`。
- **`ext/web` C4**:导航表 `当`/`when`(`auth`/`guest`/`hide`)与 `媒体`/`media`(响应式显隐);listen 注入 `_logged_in`;金样 `web-c4-nav-when`。
### Changed
- `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。
- 中文 `构建单步上下文` 委托英文版(含预算 / READ);新增 `dump_step_context`;live 用例改用仓库根 `.env`。
- 文档:[ext-web 定制限制](doc/research/ext-web-customization-limits.md) + [解决设计 C0–C4](doc/design/ext-web-customization/)。
## v0.3.3 — 2026-09-04
### Highlights
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo"
version = "0.3.3"
version = "0.3.4"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo — Markdown markers as an interpreted programming language"
+5 -5
View File
@@ -99,7 +99,7 @@ marqdo catalog public -o .marqdo
---
## 现状(v0.3.3)
## 现状(v0.3.4)
- 映射与解释器:Phase I 树遍历 + 字节码后端可用;金样例在 `tests/`
- **对象**:`#` = 类型/构造,`##`+ = 函数/方法;见 [objects.md](doc/design/objects.md)
@@ -109,7 +109,7 @@ marqdo catalog public -o .marqdo
- **`marqdo version --check`**:与 GitHub 最新 release 对比
- 标准库:**内置于二进制**(v0.1.2+);磁盘 `lib/` 或 `MARQDO_LIB` 可覆盖。模块含文本、表、**浏览器效应**、文件、系统、时间、JSON、网络、数学、外联、插件、**自写回**、**子任务**
- **官方扩展库 `ext/`**(**非** stdlib,本版收口):
- **`web`**:W0–W7 + P3 + **W8**(favicon / Head 资源 / 图片装配,见 [web-assets-and-images.md](doc/design/web-assets-and-images.md));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)(反向代理 → 嵌入式 `listen`,非 Daphne/Uvicorn)
- **`web`**:W0–W7 + P3 + **W8**;**定制 C0–C4**(admin 前缀/gates/`shell_css`/`layout`/样式 strict/脚本 defer·version/条件导航,见 [ext-web-customization](doc/design/ext-web-customization/));示例 [marqdo-blog](examples/marqdo-blog/);生产路径见 [web-asgi-servers-and-marqdo.md](doc/design/web-asgi-servers-and-marqdo.md)
- **`quantum`**:Q0–Q7 + Q8a/b 主题 SVG;示例 [quantum-entanglement](examples/quantum-entanglement/)
- **`agent`**:A1–A4(OKF 复用、过程事件、上下文预算、RAG/MCP fixture);下一波缺口 [agent-framework-gaps-after-a4.md](doc/research/agent-framework-gaps-after-a4.md)
- **`llm`**:OpenAI 兼容对话
@@ -120,12 +120,12 @@ marqdo catalog public -o .marqdo
- **浏览器 Marqdo(WASM)**:`marqdo wasm build` + 官方 bridge 自启(作者零业务 JS;桥内可含列表/路由/storage/ws/文件/Canvas/音频/Observer/拖放);`lib/browser` + GFM;`web.client_embed`;示例 [browser-hello](examples/browser-hello/) · [browser-app](examples/browser-app/) · [browser-media](examples/browser-media/) · [web-client-site](examples/web-client-site/)([ADR 0002](doc/adr/0002-browser-marqdo-wasm.md) · [D](doc/roadmap/browser-wasm-d.md) · [E](doc/roadmap/browser-wasm-e.md) · [F](doc/roadmap/browser-wasm-f.md))
- 选型:[ADR 0001 — Rust](doc/adr/0001-implementation-language.md) · [ADR 0002 — 浏览器 WASM](doc/adr/0002-browser-marqdo-wasm.md)(C0–C5 完结,见 [roadmap/browser-wasm.md](doc/roadmap/browser-wasm.md))· [ADR 0003 — 异步效应](doc/adr/0003-browser-async-effects.md)
### 如何使用最新 Marqdo(v0.3.3)
### 如何使用最新 Marqdo(v0.3.4)
```bash
# 1) 源码安装(跟 tag 或 main)
git clone https://github.com/cflmy/marqdo.git && cd marqdo
git checkout v0.3.3 # 或留在 main
git checkout v0.3.4 # 或留在 main
cargo build --release
export PATH="$PWD/target/release:$PATH"
marqdo version
@@ -154,7 +154,7 @@ marqdo wasm build
# → dist/wasm/ … 见 examples/browser-hello/
# 6) Windows:也可从 GitHub Releases 下载 exe / zip / vsix
# https://github.com/cflmy/marqdo/releases/tag/v0.3.3
# https://github.com/cflmy/marqdo/releases/tag/v0.3.4
```
开发期也可用 `cargo run -- …` 代替已安装的 `marqdo`:
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "marqdo-wasm"
version = "0.3.3"
version = "0.3.4"
edition = "2021"
license = "Apache-2.0"
description = "Marqdo interpreter as WebAssembly (browser host bridge)"
+5 -2
View File
@@ -40,6 +40,8 @@
| [design/ext-agent-plan.md](design/ext-agent-plan.md) | **`## 多步` / `## plan` 锁定设计**(工作簿文件、subtask 执行、修订循环、`step` 默认写回) |
| [design/ext-cli.md](design/ext-cli.md) | **`marqdo ext list/add/remove` 官方扩展安装器** |
| [design/ext-web.md](design/ext-web.md) | **官方扩展 `ext/web`(页面/库表/绑定/后台;ABI + CLI;设计锁定)** |
| [research/ext-web-customization-limits.md](research/ext-web-customization-limits.md) | **`ext/web` 定制限制踩坑盘点**(路由/壳 CSS/鉴权/样式/部署) |
| [design/ext-web-customization/](design/ext-web-customization/) | **对应解决设计**(C0–C4:前缀可让出、shell_css、gate、布局…) |
| [design/web-assets-and-images.md](design/web-assets-and-images.md) | **W8:favicon / Head 资源表 / 图片装配**(一次补齐) |
| [design/web-asgi-servers-and-marqdo.md](design/web-asgi-servers-and-marqdo.md) | **Daphne/Uvicorn 等 vs Marqdo**:不能直接托管;反代 + axum `listen` |
| [design/call-arguments.md](design/call-arguments.md) | **调用:具名 + 位置实参** |
@@ -67,8 +69,9 @@
| [roadmap/ext-quantum.md](roadmap/ext-quantum.md) | **规划:`ext/quantum` 量子模拟**(基础门·电路·ABI·`ext add`) |
| [research/okf-and-marqdo.md](research/okf-and-marqdo.md) | OKF 调研 |
| [research/agent-frameworks-and-marqdo.md](research/agent-frameworks-and-marqdo.md) | 主流智能体框架 vs Marqdo 优势 |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点**(产品化 / 评测 / MCP / resume) |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` 深入优化 A0–A4**(已完成) |
| [research/agent-framework-gaps-after-a4.md](research/agent-framework-gaps-after-a4.md) | **`ext/agent` A0–A4 之后缺口盘点** |
| [research/agent-framework-2026-09.md](research/agent-framework-2026-09.md) | **2026-09 刷新:宪法优先 Wave B** |
| [roadmap/ext-agent-optimize.md](roadmap/ext-agent-optimize.md) | **`ext/agent` A0–A4 done · Wave B Active** |
金样例与集成测试:[`tests/`](../tests/)。面向访客的可执行文档:[`public/`](../public/)。Spike 存档:[`spike/`](../spike/)。
@@ -0,0 +1,74 @@
# 解决 1:路由与 `/admin` 前缀可让出
| | |
|---|---|
| 问题 | [研究 §1](../../research/ext-web-customization-limits.md#1-路由与路径被框架强占) |
| 优先级 | **P0** · 波次 **C0** |
| 触点 | `plugins/web/src/lib.rs`(`normalize_route_path`、`web_app_new`、redirect)· `plugins/web/src/http.rs`(admin 路由挂载、login redirect)· `ext/web/web.mq.md` / `网页.mq.md` |
---
## 1. 目标
1. 关闭内置后台后,**整段前缀可被站点路由占用**(含自研 `/admin`)。
2. 开启内置后台时,前缀**可配置**(默认仍 `/admin`),登录成功/登出落地页可配置。
3. `app.route` / `app.redirect` 只禁止**当前生效**的框架保留段,不再永久霸占 `/admin`。
---
## 2. 作者 API(草案)
```markdown
*应用 = > web.app page=`首页` db=`库` admin=False*
# 或:仍用内置 CRUD,但挂到旁路前缀 + 自定义回跳
*应用 = > web.app page=`首页` db=`库` admin=True*
*应用 = > `应用`.auth users=`用户表` admin_prefix="/desk" login_redirect="/desk" logout_redirect="/desk/login"*
```
| 参数 | 默认 | 含义 |
|------|------|------|
| `admin` / `后台` | `False` | `False`:**不注册**任何内置 admin HTTP 路由 |
| `admin_prefix` / `后台前缀` | `"/admin"` | 内置 CRUD + 登录页挂载根;仅 `admin=True` 时生效 |
| `login_redirect` / `登录回跳` | `{admin_prefix}` | 登录成功 303 目标 |
| `logout_redirect` / `登出回跳` | `{admin_prefix}/login` | 登出后目标 |
中文别名与英文一一对应,写进 `网页.mq.md`。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `normalize_route_path(app)` | reserved 列表改为:`/_form`、`/_part`、`/static` + **当前** `admin_prefix`(仅当 `admin=True`) |
| `listen` 路由表 | `admin=False` → **不** `.route("/admin…")`;为真则用 `admin_prefix` 拼路径 |
| `admin_login_post` / `admin_logout` | 使用配置的 redirect,禁止写死 `"/admin"` |
| `web_app_redirect` | 校验目标时用同一套动态 reserved,允许指向已让出的 `/admin` |
| disabled 文案路径 | 删除「挂路由但只显示 Admin is disabled」;无路由则 404 或落入站点自定义页 |
---
## 4. 兼容策略
- 缺省参数下:现有 `examples/web-site`、`web-net-site`、`marqdo-blog` 行为不变(仍 `/admin` + 跳 `/admin`)。
- 文档明确:`admin=False` 后若仍要登录能力,用 §3 的通用 `auth`/`gate`,不必再依赖内置 admin 壳。
---
## 5. 验收
| 金样 / 手工 | 期望 |
|-------------|------|
| `admin=False` + `route path="/admin/news"` | 注册成功;GET 渲染站点页,**不是** Admin is disabled |
| `admin_prefix="/desk"` | 内置登录在 `/desk/login`;成功跳 `login_redirect` |
| 默认 `admin=True` 无新参数 | 与现网一致 |
| `redirect` 到已让出的 `/admin` | 允许 |
---
## 6. 过渡期 → 已落地
~~继续用 `/desk` 旁路 + JS 调 `/admin/login`。~~
**C0 已落地(2026-09):** `admin=False` 可直接 `route path="/admin/…"`;或 `admin=True` + `admin_prefix="/desk"` + `login_redirect` / `logout_redirect`。见金样 `tests/ext/web-c0-admin-prefix.mq.md`。
@@ -0,0 +1,72 @@
# 解决 2:`SHELL_CSS` 可关 / 可分层
| | |
|---|---|
| 问题 | [研究 §2](../../research/ext-web-customization-limits.md#2-内置-shell_css-难以彻底覆盖) |
| 优先级 | **P1** · 波次 **C2** |
| 触点 | `plugins/web/src/render.rs`(`SHELL_CSS`、`<style>` 拼接)· page/app 元数据 · `ext/web` 样式装配 |
---
## 1. 目标
1. 站点主题可选择:**不要**框架栅格/卡片默认,或只要 reset 级变量。
2. 壳 CSS 与主题 CSS 的级联顺序**可声明、可文档化**。
3. 默认仍注入完整壳(兼容旧站);新主题显式 `shell_css=off` 即可干净起步。
---
## 2. 作者 API(草案)
```markdown
*应用 = > web.app page=`首页` … shell_css="minimal"*
# 或页面级覆盖
*页 = > `页`.meta …* # 或 page 选项 shell_css=
```
| 值 | 行为 |
|----|------|
| `full`(默认) | 现网 `SHELL_CSS` 全文 |
| `minimal` | 仅 `:root` 变量 + `body` margin/字体;**不含** `has-sidebar` 双列栅格与卡片表单皮肤 |
| `off` / `none` | 不注入框架壳样式;只输出站点 `style` / 外链 CSS |
级联顺序锁定为文档约定:
1. (可选)框架 `SHELL_CSS`
2. 站点全局 style 表 / `site.css`
3. 页面级 style
禁止再出现「主题写在 extra,却被同特异性壳规则在小屏打穿且无媒体查询」而无开关可关的情况。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| 拆分 `SHELL_CSS` | `SHELL_VARS` / `SHELL_LAYOUT` / `SHELL_WIDGETS` 三段;`full`=`all`,`minimal`=vars(+极简 layout) |
| `render` 读 `app.shell_css` / `page.shell_css` | 页面覆盖应用 |
| 为 `has-sidebar` 布局加基础媒体查询 | 即使 `full`,小屏改为单列(减轻幽灵双列);`minimal`/`off` 不负责响应式 |
---
## 4. 兼容策略
- 默认 `full`:视觉与现网一致。
- Tutorial 增加一节「品牌主题请用 `shell_css=minimal|off`」。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| `shell_css=off` + 站点只写单列 grid | 响应里**无** `grid-template-columns:14rem` |
| `minimal` | 有 CSS 变量;无 `.content.cards article` 边框默认(或等价皮肤段) |
| 默认示例站 | HTML 仍含完整壳 CSS |
---
## 6. 过渡期 → 已落地
**C2 已落地(2026-09):** `shell_css=full|minimal|off`;页面/应用可设;`full` 含 `@media (max-width:720px)` 单列。金样 `tests/ext/web-c2-shell-layout.mq.md`。
@@ -0,0 +1,72 @@
# 解决 3:鉴权 / 门禁可配置且行为一致
| | |
|---|---|
| 问题 | [研究 §3](../../research/ext-web-customization-limits.md#3-鉴权--门禁模型偏固定) |
| 优先级 | **P0** · 波次 **C1**(依赖 [01](01-routes-and-admin-prefix.md) 的 prefix) |
| 触点 | `plugins/web/src/http.rs`(`rbac_middleware`、`path_matches`、login 表单)· `lib.rs`(`web_app_auth` / `web_app_gate`)· `ext/web` |
---
## 1. 目标
1. **未登录策略一致**:可配置 `redirect`(303 登录)或 `forbid`(403),对任意 gate 路径生效,不再「仅 `/admin*` 会跳登录」。
2. **匹配语义清晰**:支持精确路径、前缀、以及排除列表;`/desk` 默认**不**误伤 `/desk/login`。
3. 默认 admin gate 使用 **路径段边界**(`/admin` 与 `/admin/…`),不匹配 `/admin-publish`。
4. 登录 URL、表单 `action`、成功/失败回跳均可配置(与 C0 对齐)。
---
## 2. 作者 API(草案)
```markdown
*应用 = > `应用`.auth users=`用户表` login_path="/desk/login" login_redirect="/desk"*
*应用 = > `应用`.gate path="/desk" roles="admin" match="prefix" on_deny="redirect" exclude="/desk/login"*
```
| 字段 | 说明 |
|------|------|
| `login_path` | 登录页 URL(GET 表单 + POST 处理);默认 `{admin_prefix}/login` |
| `match` | `exact` \| `prefix`(默认对自定义 gate 建议 `prefix` + `exclude`) |
| `on_deny` | `redirect` \| `forbid`;`redirect` 时跳 `login_path`(可带 `?next=`) |
| `exclude` | 逗号分隔或表列:匹配前缀时放行的路径 |
`auth` 注册默认 gate 时:
- 使用 `{admin_prefix}` + 段边界,**不要** `starts_with("/admin")` 裸前缀。
- 自动把 `login_path` 加入放行列表。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `path_matches` | 增加 `exact`;`prefix` 要求下一字符为 `/` 或结尾;可选 exclude |
| `rbac_middleware` | 按 gate 的 `on_deny` 分支;通用放行 `login_path`,不写死 `/admin/login` |
| 登录 HTML | `action={login_path}`;hidden `next` 可选 |
| Session/CSRF | 短期仍用框架实现;文档标明字段名;中期再开放 `login_form` 自定义字段映射(非本波次必做) |
---
## 4. 兼容策略
- 未传新字段:行为对齐现网(`/admin*` → redirect 登录;其它自定义 gate → 403)。
- 新增金样:`/desk` gate + `/desk/login` 可匿名打开。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| visitor 访问 `/desk`(`on_deny=redirect`) | 303 → `/desk/login`,不是 403 |
| visitor 访问 `/desk/login`(exclude) | 200 登录页 |
| `/admin-publish` 无显式 gate | **不**被默认 admin gate 拦住 |
| 旧站仅 `app.auth` | 仍保护 `/admin*` |
---
## 6. 过渡期 → 已落地
**C1 已落地(2026-09):** `auth` 默认段边界 prefix + `on_deny=redirect` + 排除 `login_path`;自定义 `gate` 可设 `match` / `on_deny` / `exclude`。金样 `tests/ext/web-c1-gates.mq.md`;单元测试 `http::gate_tests`。
@@ -0,0 +1,69 @@
# 解决 4:样式表作者体验
| | |
|---|---|
| 问题 | [研究 §4](../../research/ext-web-customization-limits.md#4-样式作者体验受限) |
| 优先级 | **P2** · 波次 **C3** |
| 触点 | 表单元格表达式(T5)· `ext/web` style 装配 · 教程 / Skill · 可选校验 |
---
## 1. 目标
1. 含 `/`、`,`、括号的 CSS 值**不易被静默算坏**。
2. 复杂选择器 / `@keyframes` / 多层 media 有**官方推荐写法**(表内 vs 外链 vs raw 块)。
3. 与壳 CSS 的层叠关系在文档中一句话写清(并链到 [02](02-shell-css.md))。
---
## 2. 作者 API / 约定(草案)
### 2.1 立即固化的文档约定(可不改代码)
| 规则 | 说明 |
|------|------|
| 含 `/` 的值必须引号 | `"1 / 5"`、`"image/png"`(已有;Skill/教程加醒目反例) |
| 复杂皮肤优先外链 | `static/theme.css` + `page.head` / `app.icons` 同类资源表 |
| `@keyframes` / 长 media | 放外链 CSS,不塞进 GFM 单元格 |
| 调试 | `shell_css=off` 后只看主题文件,避免同页双源 |
### 2.2 产品增强(C3)
| 能力 | 说明 |
|------|------|
| `style` 装配时对可疑单元格告警 | 未加引号且含 `/` → listen/assemble 警告或硬错误(可开关) |
| 可选 `##` raw CSS 块绑定 | 例如页面附属 ````css` 具名块,**不经**表表达式求值 |
| 文档示例 | `min-width` + `max-width` 外链表;引用 [table-cell-expressions.md](../table-cell-expressions.md) |
---
## 3. 插件 / 核心改动点
| 改动 | 说明 |
|------|------|
| web style 编译 | 可选 `strict_css_cells=True`:裸 `/` 报错 |
| (可选)`web_page_css_raw` | 把文本 CSS 追加到页面,跳过 T5 |
| Skill `marqdo` / tutorial 14 | 增加「样式踩坑」小节 |
---
## 4. 兼容策略
- 默认不硬错误(避免打碎旧表);新 scaffold 默认 `strict_css_cells` 或文档强制引号。
- 不把完整 CSS 语法塞进表格方言——复杂内容走文件。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 文档反例 `grid-column` 裸 `1 / 5` | 在 strict 模式下失败或警告 |
| 外链 `theme.css` + `shell_css=off` | 无壳栅格串扰 |
| 现有 web 示例 | 默认模式仍绿 |
---
## 6. 过渡期 workaround
全部敏感值加引号;响应式与 keyframes 只写在 `static/*.css`;小屏问题优先关壳([02](02-shell-css.md))再调主题。
@@ -0,0 +1,85 @@
# 解决 5:页面壳与插槽松绑
| | |
|---|---|
| 问题 | [研究 §5](../../research/ext-web-customization-limits.md#5-页面壳与插槽约定僵硬) |
| 优先级 | **P1** · 波次 **C2/C4** |
| 触点 | `plugins/web/src/render.rs`(body class、四区 HTML)· page 槽位装配 · nav 组件表 |
---
## 1. 目标
1. 作者可选**非侧栏栅格**布局,而不必用 CSS 硬怼掉 `has-sidebar`。
2. 侧栏存在 ≠ 强制桌面双列;提供 stacked / bare 等预设。
3. 为「条件导航」留扩展点(先文档 + 简单 hook,完整运行时条件可后置)。
---
## 2. 作者 API(草案)
```markdown
*首页 = > web.page … layout="stacked"*
*应用 = > web.app page=`首页` … layout="bare"*
```
| `layout` | DOM / class | 说明 |
|----------|-------------|------|
| `sidebar`(默认,有 side 槽时) | `body.has-sidebar` | 现网行为 |
| `stacked` | `body.layout-stacked`;side 在 main 上或折叠区 | 单列流式,适合杂志/营销 |
| `bare` | 无 top/side/foot 强制栅格;只渲染 `main`(+ 显式槽) | 登录页、落地页 |
| `rail`(可选) | 保留站点已有 `has-rail` 约定并文档化 | 避免「只有首页有 class」 |
规则:**有 side 组件但 `layout=stacked|bare` 时,不自动加 `has-sidebar`。**
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| `render` 读 `page.layout` / `app.layout` | 决定 body class 与 HTML 骨架 |
| `SHELL_LAYOUT`(见 [02](02-shell-css.md)) | 为 `layout-stacked` / `layout-bare` 提供最小样式;`shell_css=off` 时不注入 |
| Nav 表 | 短期保持声明式;文档说明「条件项用两套 nav 组件 + 媒体查询隐藏」 |
| 中期 hook(非阻断) | `navigate` 已有字段可扩展 `when`/`media` 列(单独 RFC) |
---
## 4. 兼容策略
- 未设 `layout`:有 side → 与现网 `has-sidebar` 相同。
- 金样增加 `layout=bare` 登录页(可与 C0 自研 `/desk/login` 共用)。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 有 side + `layout=stacked` | body **无** `has-sidebar`;无 `14rem` 双列(在 full 壳下用 stacked 规则) |
| `layout=bare` | 输出不含 `<aside class="side">`(或 empty 不占栅格) |
| 默认站 | 不变 |
---
## 6. 过渡期 → 已落地
**C2 已落地(2026-09):** `layout=sidebar|stacked|bare|rail`;有 side 时 `stacked`/`bare` 不再强制 `has-sidebar`。金样 `web-c2-shell-layout`。
**C4 已落地(2026-09):** 导航 / 侧栏 / 页脚绑定表可选列:
| 列 | 说明 |
|----|------|
| `媒体` / `media` | CSS media;不匹配时 `display:none`(生成 `nav-mq-*` + `@media not …`) |
| `当` / `when` | `hide` 省略;`auth` / `guest` 按登录态过滤;空 = 总是显示 |
```markdown
| 属性 | 值 | 样式 | 媒体 | 当 |
|------|-----|------|------|-----|
| Home | / | | | |
| Menu | /m | | (max-width: 720px) | |
| Admin | /admin | | | auth |
| Login | /login | | | guest |
```
Listen 渲染时写入 `_logged_in` / `_nav_user`(来自 session)。离线 `page.render` 可自行 `table.put` `_logged_in`。金样 `web-c4-nav-when`。
@@ -0,0 +1,67 @@
# 解决 6:后台 CRUD 与表单能力边界
| | |
|---|---|
| 问题 | [研究 §6](../../research/ext-web-customization-limits.md#6-后台-crud-与表单能力边界) |
| 优先级 | **P3** · 随 C0 文档化;增强可选 |
| 触点 | `plugins/web/src/http.rs` / `form.rs`(内置 admin)· 站点自研页 + `db.*` · `/_form` |
---
## 1. 目标
1. **产品叙事澄清**:内置 `/admin`(或可配置前缀)= 通用表浏览器,**不是** CMS;关则彻底让路(见 [01](01-routes-and-admin-prefix.md))。
2. 自研后台的推荐路径写清楚:`page` + `form` + `db` + gate,而不是改插件壳。
3. 对「链接前缀 / new / edit」给出约定或薄辅助,减少前端状态机拼装。
---
## 2. 作者 API / 文档(草案)
### 2.1 推荐架构(文档为主)
| 需求 | 做法 |
|------|------|
| 产品级编辑器、专栏联动 | 自研 `# page` + 组件;写库用 `db.insert`/`update`;鉴权用 `gate` |
| 简单表维护 | 开 `admin=True`(可换前缀) |
| 关内置仍要 CRUD | 自研列表/编辑页;**不要**依赖 disabled 壳 |
### 2.2 可选薄增强(非 CMS)
| 能力 | 说明 |
|------|------|
| `form` 支持 `mode=new\|edit` 查询参数约定 | 文档 + 示例;必要时 `web.form` 读 `id`/`new` |
| `list` 组件 `link_prefix` | 已有则补示例;缺失则加一列「详情路径模板」 |
| Markdown 字段 | 继续「存库 + 前台渲染」;分栏编辑器保持外挂 JS(明确不做进 ABI) |
---
## 3. 插件改动点
| 改动 | 优先级 |
|------|--------|
| C0:disabled 不占路径 | 必需(属 [01](01-routes-and-admin-prefix.md)) |
| 示例 `examples/web-custom-desk/` | 展示自研列表/编辑,零内置 admin |
| form 查询参数助手 | 可选 |
---
## 4. 兼容策略
- 不扩展内置 admin 成 CMS(避免范围爆炸)。
- Tutorial 增加「何时用内置 admin / 何时自研」。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 文档 + 示例 desk | 无 `/admin` 也能完成一文增删改 |
| 内置 admin 金样 | 仍绿 |
---
## 6. 过渡期 workaround
自研 `/desk` + 调用 `/_form` 或直接 DB API;复杂编辑器继续外挂 JS。
@@ -0,0 +1,71 @@
# 解决 7:静态资源与脚本生命周期
| | |
|---|---|
| 问题 | [研究 §7](../../research/ext-web-customization-limits.md#7-静态资源与脚本生命周期) |
| 优先级 | **P2** · 波次 **C3** |
| 触点 | `web_page_head` / `web_head` · `render.rs` head 输出 · static 挂载 · [web-assets-and-images.md](../web-assets-and-images.md) |
---
## 1. 目标
1. 默认脚本加载方式**不假设**作者手写 IIFE 抢在 DOM 前执行成功;提供 `defer` / `module` 一等约定。
2. 静态资源变更可发现:文档化 `?v=`,并提供可选自动指纹或 listen 时 mtime 查询参数。
---
## 2. 作者 API(草案)
Head 资源表扩展列(向后兼容):
| 列 | 说明 |
|----|------|
| `rel` / `关系` | 已有;`script` / `module` |
| `defer` / `推迟` | `真` → `<script defer>`(**建议默认对 script 为真**) |
| `async` / `异步` | 可选 |
| `version` / `版本` | 非空则自动追加 `?v=` |
```markdown
`头` =
| 关系 | 地址 | 推迟 | 版本 |
|------|------|------|------|
| script | /static/theme.js | 真 | 2026-09-04 |
| module | /static/desk.js | 真 | 3 |
```
全局:`app.asset_version="2026-09-04"` 为所有 static 链接统一 bump(可选)。
---
## 3. 插件改动点
| 改动 | 说明 |
|------|------|
| head 渲染 | 尊重 defer/async;`module` → `type="module"`(已有则核对) |
| 默认 | 新建 scaffold 的 script 行带 `defer` |
| (可选)`asset_version` | listen 时重写 head / 页面内 static URL |
| 文档 | 「禁止在同步 head 脚本里直接 `getElementById` 主节点;用 defer 或 `DOMContentLoaded`」 |
---
## 4. 兼容策略
- 旧表无 `defer` 列:保持现网同步行为(或仅对 scaffold/新文档默认 defer,避免静默改变旧站时序)。
- 更安全:缺省仍同步;**Skill 与 scaffold 默认写 defer=真**。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| defer 脚本读 DOM | 登录跳转逻辑在 DOM 就绪后执行 |
| `version` 列 | HTML 中出现 `theme.js?v=…` |
| 旧示例无新列 | 仍通过 |
---
## 6. 过渡期 workaround
脚本改 `type=module` 或放 body 末;手动 `?v=` bump;登录逻辑用 `DOMContentLoaded`。
@@ -0,0 +1,60 @@
# 解决 8:扩展与部署耦合
| | |
|---|---|
| 问题 | [研究 §8](../../research/ext-web-customization-limits.md#8-扩展与部署耦合) |
| 优先级 | **P3** · 文档 + 发布流程 |
| 触点 | `marqdo ext add web` · ABI 版本 · Docker/发布说明 · [ext-cli.md](../ext-cli.md) · [marqdo-release](../../../.cursor/skills/marqdo-release/SKILL.md) |
---
## 1. 目标
1. 站点作者**不必 fork 插件**才能完成 P0/P1 定制(把能力收进官方参数,见 01–05)。
2. 版本耦合可预期:changelog / 扩展清单标明「web 插件需 ≥ x.y.z」。
3. 升级路径文档化:二进制、`.marqdo-ext`、Docker 镜像三者对齐检查。
---
## 2. 作者 / 运维约定(草案)
| 约定 | 说明 |
|------|------|
| 定制优先走 `.mq.md` 开关 | `admin_prefix`、`shell_css`、`layout`、`gate`… 进官方 API 后,禁止文档再教「改 plugins/web」 |
| 兼容性矩阵 | 在 [web-net-capabilities.md](../web-net-capabilities.md) 或本目录维护「Marqdo ↔ libweb 最低版本」表 |
| `marqdo ext add web` | 安装后打印当前插件路径与版本;与 CLI 版本不符时警告 |
| Docker | 示例 Dockerfile 注释:升级需同时换 `marqdo` 与 `ext add` 产物 |
| 样式引号等行为变更 | 写入 CHANGELOG **Breaking / migration** 小节(如 0.3.2 T5) |
---
## 3. 工程改动点
| 改动 | 说明 |
|------|------|
| 插件/Crate 版本可见 | `web_listen` 或 `ext list` 显示 web ABI/包版本 |
| CI | 金样使用仓库内 `plugins/web`;发布技能检查 VSIX/CLI/插件三件套 |
| 研究→设计→路线图 | C0–C4 进 [ext-web roadmap](../../roadmap/ext-web.md),避免只活在私有 fork |
---
## 4. 兼容策略
- 不承诺插件源码级稳定 API;承诺 **`.mq.md` 作者 API** 在小版本尽量兼容,破坏性变更进 CHANGELOG。
- Fork 插件仅作为「官方尚未交付」的临时手段,并在 issue/路线图留归还项。
---
## 5. 验收
| 场景 | 期望 |
|------|------|
| 升级说明文档 | 运维按清单升级后 web 金样通过 |
| C0–C2 落地 | 自研后台场景**无需**改 `plugins/web` 源码 |
| `ext list` / 文档 | 能核对版本 |
---
## 6. 过渡期 workaround
锁定 Marqdo 与插件同版本镜像;本地 `MARQDO_EXT` 指向仓库构建产物;定制需求提 issue 对照本目录解决文,避免沉默 fork 漂移。
@@ -0,0 +1,50 @@
# `ext/web` 定制修复:解决文档索引
| | |
|---|---|
| 状态 | **C0–C4 done** |
| 日期 | 2026-09-04 |
| 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) |
| 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) |
对应研究文 §1–§8,每项一份解决文档:**目标 → 作者 API → 插件改动点 → 兼容策略 → 验收**。
实现时优先 **不破坏现有金样**(`tests/ext/web-*`、`examples/web-*`);新能力用显式 opt-in 参数打开。
---
## 文档一览
| # | 主题 | 文档 | 建议优先级 |
|---|------|------|------------|
| 1 | 路由与 `/admin` 前缀可让出 | [01-routes-and-admin-prefix.md](01-routes-and-admin-prefix.md) | P0 |
| 2 | `SHELL_CSS` 可关 / 可层 | [02-shell-css.md](02-shell-css.md) | P1 |
| 3 | 鉴权门禁可配置且行为一致 | [03-auth-gates.md](03-auth-gates.md) | P0 |
| 4 | 样式表作者体验 | [04-stylesheet-authoring.md](04-stylesheet-authoring.md) | P2 |
| 5 | 页面壳与插槽松绑 | [05-page-shell-slots.md](05-page-shell-slots.md) | P1 |
| 6 | 后台 CRUD / 表单边界 | [06-admin-crud-forms.md](06-admin-crud-forms.md) | P3 |
| 7 | 静态资源与脚本生命周期 | [07-assets-script-lifecycle.md](07-assets-script-lifecycle.md) | P2 |
| 8 | 扩展与部署耦合 | [08-ext-deploy-coupling.md](08-ext-deploy-coupling.md) | P3 |
---
## 波次建议(实现用)
| 波次 | 内容 | 依赖 |
|------|------|------|
| **C0** | 可配置 `admin_prefix`;`admin=False` 时不挂内置路由;`login_redirect` / `logout_redirect` | — |
| **C1** | gate:统一未登录策略;精确/前缀匹配;登录页自动放行;默认 gate 不再误伤 `/admin-*` | C0 |
| **C2** | `shell_css=off\|minimal\|full`;主题在壳前或隔离层;可选 `layout=bare` | — |
| **C3** | 样式:校验警告 / `strict`;`page.css` raw;脚本 `defer`/`async`/`version` + `asset_version` | **done** |
| **C4** | 壳:`layout` 预设(C2);条件导航 `when` / `media` | **done** |
路线图入口可在 [ext-web.md](../../roadmap/ext-web.md) 增补「定制波次 C0–C4」行,落地后再改状态。
---
## 产品原则(解法共同约束)
1. **`.mq.md` 仍是真相源** — 能声明的不进隐藏默认;新开关写在 `app` / `page` / `listen` 参数表。
2. **内置 admin 是可选产品**,不是不可替换的内核路由命名空间。
3. **默认行为保持兼容** — 现有 tutorial / 示例零改动仍能跑;新站显式打开定制。
4. **禁止**为单站需求永久硬编码第二套旁路(如永远推荐 `/desk` + JS fetch 登录)。
+5 -2
View File
@@ -121,13 +121,16 @@ url = /favicon.ico
| `媒体` | `media` | CSS media |
| `作为` | `as` | preload `as` |
| `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` |
| `推迟` | `defer` | 经典 `script` 为真时输出 `defer`(缺省同步,兼容旧站) |
| `异步` | `async` | 为真时输出 `async` |
| `版本` | `version` / `v` | 非空则自动追加 `?v=`;否则用页面/应用 `asset_version` |
**渲染规则**
| `rel` | 输出 |
|-------|------|
| `script` | `<script src="…"></script>`(`type` 非空则写出) |
| `module` | `<script type="module" src="…"></script>` |
| `script` | `<script … src="…"></script>`(可选 `defer`/`async`;`type` 非空则写出) |
| `module` | `<script type="module" src="…"></script>`(浏览器默认 defer 语义) |
| 其他 | `<link rel="…" href="…" …>`(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) |
空 `地址` 的行跳过。
+54
View File
@@ -0,0 +1,54 @@
# 调研刷新:2026-09 智能体框架与 Marqdo「代码即文档」
| | |
|---|---|
| 状态 | **Wave B1 Active**(B0/B0.5 已完成;宪法优先) |
| 日期 | 2026-09-04 |
| 前置 | [agent-frameworks-and-marqdo.md](agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](agent-framework-gaps-after-a4.md) |
| 路线 | [ext-agent-optimize.md](../roadmap/ext-agent-optimize.md) |
## 0. 结论
业界框架(LangGraph / Microsoft Agent Framework / CrewAI / OpenAI Agents SDK)在编排、工具、检查点、MCP、评测上继续收敛;**权威真相仍默认在对象图 + transcript + 外置 Store**。
Marqdo 的差异化不是「再做一个 loop」,而是:
1. **代码即文档** — 编排 `.mq.md` = 提示词工作面
2. **调用位置可见** — `agent_call_site`(路径 / 函数 / 行)是一等上下文
3. **文档即知识库(OKF)** — 写回 → promote / solidify → 二次命中 / `llm_free`
Wave B 的目标函数:**证明并硬化上述三点**;产品化示例与评测必须服务差异化,禁止做成无源码上下文的 chatbot demo。
## 1. 业界快照(2026)
| 模式 | 代表 | 状态记忆 | 对 Marqdo |
|------|------|----------|-----------|
| 图 + checkpointer | LangGraph | typed state 持久化 | 续跑应对齐**文件化工作簿**,不造 Python 图 DSL |
| Agent vs Workflow | Microsoft AF | 自主 + 确定性流 | 已有 step / plan,强化即可 |
| 角色班组 | CrewAI | Task 管道 | 多 Agent 低优先;父 CALL + 多工作簿 |
| Handoff + Guardrails | OpenAI Agents SDK | 显式交接 | 可借鉴语义;权威仍在 `.mq.md` |
## 2. 深远影响(开发硬约束)
| 约束 | 含义 |
|------|------|
| 提示不黑盒 | standing / 工具 / 任务写在文件;拼装可审查 |
| 位置感知 | 每次推理注入 call_site;示例与评测可断言 |
| 源码工作面 | `source_brief` + `READ:source\|skill`;禁止藏整份 Skill 进不可见提示 |
| 写回即记忆 | ok/error 槽 + view;非默认向量库 |
| OKF 飞轮 | promote / solidify / hit / llm_free |
| 外置工具 | corpus / MCP 仅证据,`authority=workbook` |
## 3. Wave B 范围
| 波次 | 主题 |
|------|------|
| **B0** | 宪法可见示例 + 上下文管道可读性 + Skill/文档 |
| **B0.5** | 本机 live(`.env` → cflmy)验证「模型用上了文档」 |
| **B1** | 评测锁住 call_site / OKF / 写回 / 预算 |
暂缓:真 MCP、resume/HITL view、kb stats、并行、A2A。
## 4. 开发期 LLM
仓库根目录 `.env`(gitignore):`OPENAI_*` 或 `MARQDO_LLM_*`。模板见 `.env.example`。
@@ -0,0 +1,154 @@
# `ext/web` 定制限制:开发者不易定制的问题盘点
| | |
|---|---|
| 状态 | **调研锁定(踩坑整理)** |
| 日期 | 2026-09-04 |
| 相关 | [ext-web.md](../design/ext-web.md) · [ext-web-net.md](../design/ext-web-net.md) · [web-net-capabilities.md](../design/web-net-capabilities.md) |
| 解决索引 | [../design/ext-web-customization/](../design/ext-web-customization/) |
结合自研后台、样式迁移与响应式改造中的实际踩坑,整理当前 `plugins/web` + `ext/web` 对站点作者的**强占与难定制点**。本文只陈述问题与证据;逐项解法见解决索引。
---
## 0. 一句话
内置 `/admin` 壳、固定鉴权路径、注入式 `SHELL_CSS` 与四区栅格,让「只写 `.mq.md`」的产品路径在**自研后台 / 品牌主题 / 移动端**上反复撞墙;作者被迫旁路前缀 + `!important` + 前端 JS 兜底。
---
## 1. 路由与路径被框架强占
**现象**
- `/admin` 及 `/admin/*` 整段保留,无法 `app.route` 注册自定义页(错误:`route path … is reserved`)。
- `app.重定向` / `redirect` 目标若落在 reserved 前缀,同样被校验拒绝。
- `后台=False`(`admin=False`)后,访问 `/admin/news` 等仍进内置壳,只显示 *Admin is disabled*,**不能**换成自研页。
- 登录/登出硬绑 `/admin/login`、`/admin/logout`;登录成功硬编码 `Redirect::to("/admin")`,无法配置回跳到 `/desk`。
**代码证据**
| 位置 | 行为 |
|------|------|
| `plugins/web/src/lib.rs` → `normalize_route_path` | `/admin`、`/_form`、`/_part`、`/static` 一律 reserved |
| `plugins/web/src/http.rs` | 始终挂 `/admin…` 路由;disabled 时仍 `admin_shell` + 文案 |
| 同文件 `admin_login_post` | 成功跳转写死 `/admin` |
**结果**
自研后台只能用 `/desk` 等旁路前缀;入口与鉴权路径分裂,还要靠前端 JS(`fetch('/admin/login')` 再 `replace('/desk')`)做跳转兜底。
→ 解决:[01-routes-and-admin-prefix.md](../design/ext-web-customization/01-routes-and-admin-prefix.md)
---
## 2. 内置 `SHELL_CSS` 难以彻底覆盖
**现象**
- 每个页面都会注入框架壳样式,例如 `body.has-sidebar { grid-template-columns:14rem 1fr; … }`、默认卡片/表单/侧栏色。
- 规则**无媒体查询**、选择器优先级不低;站点主题选择器不够强时,小屏双列、侧栏占位等「幽灵布局」反复出现。
- 首页有额外 class(如 `has-rail`)时碰巧盖住,其他页没有同类 class 就暴露——表现为「只修了首页」。
- 实务上经常要 `!important` + 更高选择器,与「干净主题层」冲突。
**代码证据**
| 位置 | 行为 |
|------|------|
| `plugins/web/src/render.rs` → `SHELL_CSS` | 常量内联进每个 HTML |
| 同文件壳渲染 | `<style>{SHELL_CSS}{extra}</style>`,主题只能接在后面 |
→ 解决:[02-shell-css.md](../design/ext-web-customization/02-shell-css.md)
---
## 3. 鉴权 / 门禁模型偏固定
**现象**
- 未登录访问受保护路径:对 `/admin*` 会 **303 → 登录页**;对 `/desk` 等自定义路径往往是 **403 HTML**,行为不一致。
- 门禁匹配偏宽:`path.starts_with` / `path_matches` 使 `/desk` 匹配 `/desk/login`,公开登录页易被误伤。
- 默认鉴权挂上 `/admin*` → `admin`;`/admin-publish` 这类名字也会被当成 admin 域(`starts_with("/admin")`)。
- 会话 cookie、CSRF、登录表单字段均固定在框架实现;难换登录 UI 或改成功落地页。
**代码证据**
| 位置 | 行为 |
|------|------|
| `http.rs` → `rbac_middleware` | visitor + `/admin*` → redirect;其它 gate → 403 |
| `http.rs` → `path_matches` | 前缀匹配,无「精确路径 + 子路径排除」DSL |
| `lib.rs` → `web_app_auth` | 默认塞入 `/admin*` gate |
→ 解决:[03-auth-gates.md](../design/ext-web-customization/03-auth-gates.md)
---
## 4. 样式作者体验受限
**现象**
- 样式表是 GFM 表格;含 `/` 的值必须加引号(如 `"1 / 5"`),否则单元格表达式把 `/` 当除法(曾出现 `grid-column` 变成 `0`)。
- `@keyframes`、复杂选择器、多层媒体查询(`min-width` and `max-width`)表达能力有限,装配顺序要小心。
- 主题 CSS 与 `SHELL_CSS` 同页串联,级联顺序不透明,调试成本高。
- 响应式不能指望框架;壳层几乎不提供移动端抽屉/折叠。
→ 解决:[04-stylesheet-authoring.md](../design/ext-web-customization/04-stylesheet-authoring.md)
---
## 5. 页面壳与插槽约定僵硬
**现象**
- 壳结构固定为 `topnav` / `side` / `main` / `foot` 栅格命名区。
- 侧栏一旦装配,`body` 即 `has-sidebar`,套上框架双列;杂志风单列、抽屉必须自己拆布局。
- 组件表驱动导航,难做运行时条件导航(小屏合并顶栏+侧栏),通常再补 `theme.js`。
→ 解决:[05-page-shell-slots.md](../design/ext-web-customization/05-page-shell-slots.md)
---
## 6. 后台 CRUD 与表单能力边界
**现象**
- 内置 admin 是通用表管理,不是产品级 CMS;**关了又占着 `/admin` 路径**(与 §1 叠加)。
- 表单以声明式字段表为主;Markdown 分栏、专栏元数据联动等只能外挂 JS。
- 列表「链接前缀」等约定简单;编辑/新建状态机常靠前端拼(`?id=`、`?new=1`)。
→ 解决:[06-admin-crud-forms.md](../design/ext-web-customization/06-admin-crud-forms.md)
---
## 7. 静态资源与脚本生命周期
**现象**
- 头资源脚本常在 `<head>` **同步**加载;若脚本假设 DOM 已就绪会直接失败(登录页曾因此不跳转)。
- 缓存靠 `?v=` 手动 bump;无构建管线时易出现「改了 JS 浏览器仍用旧文件」。
→ 解决:[07-assets-script-lifecycle.md](../design/ext-web-customization/07-assets-script-lifecycle.md)
---
## 8. 扩展与部署耦合
**现象**
- 能力依赖 web 插件 ABI / Marqdo 版本(如 0.3.2 起的样式引号约定);升级要同步 Docker / 本机二进制。
- 定制若依赖改插件源码(放宽 `/admin` reserved、可配置 login redirect),就脱离「只写 `.mq.md`」的产品路径,维护成本陡增。
→ 解决:[08-ext-deploy-coupling.md](../design/ext-web-customization/08-ext-deploy-coupling.md)
---
## 9. 优先级建议(给实现排期)
| 优先级 | 项 | 理由 |
|--------|-----|------|
| P0 | §1 路由/前缀 + §3 鉴权一致 | 阻塞自研后台产品路径 |
| P1 | §2 SHELL_CSS + §5 壳布局 | 阻塞品牌主题与响应式 |
| P2 | §4 样式作者体验 + §7 脚本生命周期 | 降低日常踩坑,不改架构也能缓解 |
| P3 | §6 CRUD 边界 + §8 部署耦合 | 文档/约定/可选增强为主 |
详细验收与实现切片见解决索引 README。
+23 -12
View File
@@ -2,9 +2,9 @@
| | |
|---|---|
| 状态 | **A0–A4 完成**(调研驱动优化闭环;A4:corpus/MCP 证据工具,权威仍是 `.mq.md`) |
| 日期 | 2026-08-28 |
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · **缺口盘点** [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) |
| 状态 | **A0–A4 完成**;**Wave B Active**(宪法优先:代码即文档 / call_site / OKF) |
| 日期 | 2026-09-04 |
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) · [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) · **[agent-framework-2026-09.md](../research/agent-framework-2026-09.md)** |
| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) |
| 邻近 | [agent-streaming.md](agent-streaming.md) · [okf-near-match.md](okf-near-match.md) |
@@ -13,21 +13,32 @@
## 1. 优化原则(来自调研)
1. **强化差异化,不向 LangChain 薄循环回退**(禁止隐藏 TOOL: 主路径、禁止整文件 LLM 重写工作簿)。
2. 把资源砸在:**工作簿质量、写回、固化、OKF 命中、过程可视**。
2. 把资源砸在:**工作簿质量、写回、固化、OKF 命中、过程可视、源码/调用位置注入**。
3. 外部 RAG/MCP 只作**工具**,不升为权威真相源。
自评四问见调研 §9。A0–A4 之后的缺口与建议分期 **B0–B5** 见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md)。
自评四问见调研 §9。A0–A4 之后的缺口见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md)。**2026-09 Wave B** 锁定见 [agent-framework-2026-09.md](../research/agent-framework-2026-09.md)。
---
## 2. 建议分期(摘要)
## 2. A0–A4(已完成)
| 波次 | 主题 | 验收线索 |
|------|------|----------|
| **A0** | 工作簿补丁 / 固化可靠性 | **done** — 整文件 FIND 护栏;`soft` 仅 miss;decompose `n` 检查;`workbook_solidify` 单测;金样 `agent-workbook-patch-a0`(双 CONTINUE + solidify) |
| **A1** | OKF 复用飞轮(lookup / near / soft_match UX) | **done** — `list_tasks` 含 description/aliases/status/llm_free/hits;`plan` 命中路径暴露 `match`/`score`;soft_match 策展行含 meta;view plan 卡显示 match;金样 `agent-kb-plan-hit`(exact hit + near soft-hit) |
| **A2** | 过程可见(stream + view 过程卡) | **done** — `plan_append_*` / `plan_finish_stream` 始终写入 `events`(SSE 仍仅 `stream=True`);OKF REUSE 记 `decision`;view `plan-card` 渲染过程时间线(跳过 delta);金样断言 `events-ok`;对齐 [agent-streaming.md](agent-streaming.md) |
| **A3** | 上下文预算(源码/Skill 渐进披露) | **done** — `source_brief` / 加深 `skill_brief`;`build_step_context` 默认预算 + `READ:source|skill`;`step max_reads`;父 `READ:skill`;金样 `agent-context-budget-a3` |
| **A4** | 可选:RAG/MCP 工具适配器 | **done** — `corpus_search`(本地语料关键词);`mcp_list_tools` / `mcp_call`(JSON fixture);`authority=workbook`;金样 `agent-tools-rag-a4` |
| **A0** | 工作簿补丁 / 固化可靠性 | **done** — 金样 `agent-workbook-patch-a0` |
| **A1** | OKF 复用飞轮 | **done** — 金样 `agent-kb-plan-hit` |
| **A2** | 过程可见 | **done** — events + view plan 卡 |
| **A3** | 上下文预算 | **done** — `source_brief` / `READ:`;金样 `agent-context-budget-a3` |
| **A4** | RAG/MCP 证据工具 | **done** — 金样 `agent-tools-rag-a4` |
细节与行业对照以调研正文为准;本文件只跟踪 **A0–A4** 实现分期。后续产品化 / 评测 / live MCP 等见 [agent-framework-gaps-after-a4.md](../research/agent-framework-gaps-after-a4.md) §5(草案 B0–B5)。
---
## 3. Wave B(Active — 宪法优先)
| 波次 | 主题 | 状态 |
|------|------|------|
| **B0** | 官方示例演示 call_site/源码/OKF;Skill/文档;上下文管道可读 | **done** |
| **B0.5** | 本机 live(`.env` → 开发模型)验证「模型用上了文档」 | **done**(`AGENT_LIVE` / `AGENT_HARNESS_LIVE`) |
| **B1** | 评测 harness 锁差异化指标(constitution / dump / writeback 遮蔽) | **Active** |
| **B2–B5** | 真 MCP / resume+HITL / stats / 并行 | 暂缓 |
示例:`examples/agent-pong/` · `examples/agent-okf-flywheel/`。
+12
View File
@@ -35,6 +35,18 @@
| **W7** | Cache-Control / 404·500 / 重定向 / sitemap·robots / init 唯一·索引 / HTTPS 反代说明 | **done** |
| **P3** | 审计时间戳 / 外键 / RBAC / 相册 / ETag | **done** |
### 定制波次(规划中)
自研后台 / 主题 / 响应式踩坑见 [ext-web-customization-limits.md](../research/ext-web-customization-limits.md);解法索引 [ext-web-customization/](../design/ext-web-customization/)。
| 波次 | 内容 | 状态 |
|------|------|------|
| **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** |
| **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **done** |
| **C2** | `shell_css` + `layout` 松绑 | **done** |
| **C3** | 样式 strict / 脚本 defer·version | **done** |
| **C4** | 条件导航 when/media(layout 见 C2) | **done** |
验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`tests/ext/web-w7-finish-smoke.mq.md`、`tests/ext/web-p3-smoke.mq.md`、`ext_cli_add_web`。
---
+13
View File
@@ -0,0 +1,13 @@
# agent-okf-flywheel(Wave B0)
演示 **文档即知识库(OKF)**:固化工作簿 promote 后,相同 goal 的 `plan` 走 `cache=hit`(`llm_free` 路径),无需再问模型。
```bash
cargo build --release -p marqdo -p marqdo_plugin_agent
export MARQDO_EXT="$PWD/.marqdo-ext"
./target/release/marqdo run examples/agent-okf-flywheel/index.mq.md
```
期望:`promoted` · `hit` · `flywheel-ok`。
见 [okf.md](../../doc/design/okf.md) · [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md)。
+60
View File
@@ -0,0 +1,60 @@
---
title: agent-okf-flywheel (Wave B0)
description: Promote solidified workbook; second plan is cache=hit — document as knowledge base (OKF).
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import fs:lib/fs.mq.md
import json:lib/json.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
# main
OKF flywheel offline: promote → plan same goal → `cache=hit` (no live LLM required for the hit path).
*p = > plugin.native_path name="agent"*
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
> sys.env_set name="OPENAI_API_KEY" value="offline-okf-dummy"
*model = > llm.llm*
*tools = > json.parse text=[]*
*助手 = > agent.agent model=`model` tools=`tools` standing="offline okf flywheel"*
*kb = ".marqdo/agent-kb-example-flywheel"*
*wb = ".marqdo/agent-runs/example-pong-solid.mq.md"*
*goal = "Reply with exactly the word pong and nothing else."*
*body = "---\ntitle: okf pong\n---\n\n# main\n\n*msg = \"pong\"*\n\n**msg**\n"*
1. > fs.exists path=`kb`
> fs.remove path=`kb`
2. *
---
> fs.write_text path=`wb` text=`body`
*prom = > agent_kb_promote kb_dir=`kb` goal=`goal` workbook=`wb`*
*okp = > json.get value=`prom` key="promoted"*
1. `okp`
> print text=promoted
2. *
> print text=promote-fail
> sys.exit code=1
*out = > `助手`.plan goal=`goal` max_rounds=2 writeback=False kb_dir=`kb` explore_n=0 promote=False*
*cache = > json.get value=`out` key="cache"*
> print text=`cache`
*match = > json.get value=`out` key="match"*
> print text=`match`
*val = > json.get value=`out` key="result"*
> print text=`val`
1. `cache` == "hit"
> print text=flywheel-ok
2. *
> print text=flywheel-miss
> sys.exit code=1
+16
View File
@@ -0,0 +1,16 @@
# agent-pong(Wave B0)
演示 Marqdo 智能体宪法:**代码即文档** — 模型上下文含 **call site** 与本文件 **source**;工具是同文件里的 `## 获取时间`。
```bash
# 仓库根目录
cargo build --release -p marqdo -p marqdo_plugin_agent
export MARQDO_EXT="$PWD/.marqdo-ext" # 或: marqdo ext add agent
# 可选 live:仓库根 `.env` + `AGENT_LIVE=1 marqdo run examples/agent-pong/index.mq.md`
./target/release/marqdo run examples/agent-pong/index.mq.md
```
期望离线输出含:`call-site-ok` · `source-ok` · `tool-in-source-ok`。
配置真实 `.env` 时还会跑一次 `step`(CALL 工具)。
见 [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md)。
+89
View File
@@ -0,0 +1,89 @@
---
title: agent-pong (Wave B0)
description: >-
Constitution demo — call_site + source in step context; optional live CALL via .env.
Code is documentation; tools are ## in this same file.
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
import time:lib/time.mq.md
---
## 获取时间
Return today's date string (tool visible in source to the model).
*u = > time.now_unix*
**> time.format unix=`u` pattern="%Y-%m-%d"**
# main
*p = > plugin.native_path name="agent"*
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
> llm.load_env path="../../.env"
`工具表` =
| 工具 |
|------|
| 获取时间 |
*model = > llm.llm*
*助手 = > agent.agent model=`model` tools=`工具表` standing="You are a Marqdo agent. Prefer CALL:获取时间 when the task needs today's date."*
Assert constitution markers in the assembled prompt (call site before how-to-act):
*ctx = > agent.build_step_context agent=`助手` task="What is today's date? Use the tool in this runbook."*
*parts = > split value=`ctx` sep="--- call site ---"*
*n = > len value=`parts`*
1. `n` > 1
> print text=call-site-ok
2. *
> print text=call-site-missing
> sys.exit code=1
*parts2 = > split value=`ctx` sep="--- source (.mq.md) ---"*
*n2 = > len value=`parts2`*
1. `n2` > 1
> print text=source-ok
2. *
> print text=source-missing
> sys.exit code=1
*parts3 = > split value=`ctx` sep="获取时间"*
*n3 = > len value=`parts3`*
1. `n3` > 1
> print text=tool-in-source-ok
2. *
> print text=tool-in-source-missing
> sys.exit code=1
*site = > agent_call_site*
*fn = > json.get value=`site` key="function"*
> print text=`fn`
Optional live step — set env AGENT_LIVE=1 and put keys in repo-root `.env`:
*live = > sys.env_get name="AGENT_LIVE"*
*key = > sys.env_get name="OPENAI_API_KEY"*
1. `live` == "1"
1. `key`
*out = > `助手`.step task="请调用获取时间工具,然后只回复日期字符串。" writeback=False*
*status = > json.get value=`out` key="status"*
> print text=`status`
*tool = > json.get value=`out` key="tool"*
> print text=`tool`
*result = > json.get value=`out` key="result"*
> print text=`result`
2. *
> print text=live-skipped-no-key
2. *
> print text=live-skipped
+45 -18
View File
@@ -17,8 +17,8 @@ import plugin:lib/plugin.mq.md
+ `source_depth`=default
+ `skill_depth`=default
Assemble a readable prompt: standing, task, tools, call site, **budgeted** source + skill, and the act protocol.
Default budgets keep long runbooks from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`.
Assemble a readable prompt: standing, task, **call site**, tools, **budgeted** source + skill, and the act protocol.
The runbook `.mq.md` is ground truth (code as documentation). Default budgets keep long files from exploding the window; emit `READ:source` / `READ:skill` (Chinese `读取:`) to deepen, then answer or `CALL:`.
*standing = > json.get value=`agent` key="standing"*
1. `standing`
@@ -43,12 +43,39 @@ Default budgets keep long runbooks from exploding the window; emit `READ:source`
*f = > json.get value=`esc` key="f"*
*g = > json.get value=`esc` key="g"*
*p = "You are a Marqdo agent. The runbook source is your ground truth — code is documentation."*
*p = p + a + up + b + task_s + c + tools_s + g + d + site_s + e + src + f + skill*
*p = "You are a Marqdo agent. Code is documentation: this runbook source and call site are your ground truth — not a hidden system prompt."*
*p = p + a + up + b + task_s + d + site_s + c + tools_s + e + src + f + skill + g*
**p**
---
## dump_step_context
+ `agent`
+ `task`=""
+ `source_depth`=default
+ `skill_depth`=default
Inspect what `build_step_context` would send — no LLM. Returns a map: `prompt`, `call_site`, `prompt_chars`, `truncated` (true when budget markers appear). Use for harness / debugging the code-as-doc pipeline.
*prompt = > build_step_context agent=`agent` task=`task` source_depth=`source_depth` skill_depth=`skill_depth`*
*site = > agent_call_site*
*chars = > len value=`prompt`*
*parts = > split value=`prompt` sep="[truncated"*
*n = > len value=`parts`*
*truncated = False*
1. `n` > 1
*truncated = True*
2. *
*_ = 1*
*out = > json.parse text={}*
*out = > json.set map=`out` key="prompt" value=`prompt`*
*out = > json.set map=`out` key="call_site" value=`site`*
*out = > json.set map=`out` key="prompt_chars" value=`chars`*
*out = > json.set map=`out` key="truncated" value=`truncated`*
**out**
---
## extract_tool_name
+ `reply`
@@ -168,9 +195,9 @@ Structured observation for the parent developer-agent: source, named writeback s
- [`slot`](`slots`)
*k = > json.get value=`slot` key="key"*
*body = > json.get value=`slot` key="body"*
1. `k` == ok
1. `k` == "ok"
*last_ok = body*
2. `k` == error
2. `k` == "error"
*last_error = body*
3. *
*_ = 1*
@@ -1436,7 +1463,7 @@ Always append `done` and attach `events` on the result map (process audit even w
1. `trace`
*body = > json.stringify value=`events`*
> writeback.record value=`body` key=trace
> host_writeback_record value=`body` key="trace"
2. *
*_ = 1*
@@ -1578,10 +1605,10 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
1. `writeback`
*body = > json.stringify value=`out`*
*st = > json.get value=`out` key="status"*
1. `st` == ok
> writeback.record value=`body` key=ok
1. `st` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> writeback.record value=`body` key=error
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
@@ -1684,7 +1711,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`*
@@ -1741,7 +1768,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`*
@@ -1805,7 +1832,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*events = > plan_append_round events=`events` round=1 workbook=`path` exit_code=`code` result=`child_val` stream=`stream` echo=`echo`*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace` result=`child_val`*
@@ -1883,7 +1910,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*out = > json.set map=`out` key="cache" value="bypass"*
1. `writeback`
*body = > json.stringify value=`out`*
> writeback.record value=`body` key=ok
> host_writeback_record value=`body` key="ok"
2. *
*_ = 1*
*out = > plan_finish_stream out=`out` events=`events` stream=`stream` trace=`trace`*
@@ -2022,7 +2049,7 @@ Deterministic success stop (loop engineering): when the child already returned a
*summary = last_reply*
*left = 0*
1. `status` == ok
1. `status` == "ok"
1. `promote`
*prom = > agent_kb_promote kb_dir=`kb_dir` goal=`goal` workbook=`path` tools=`tools`*
*cache = "refreshed"*
@@ -2063,10 +2090,10 @@ Deterministic success stop (loop engineering): when the child already returned a
1. `writeback`
*body = > json.stringify value=`out`*
1. `status` == ok
> writeback.record value=`body` key=ok
1. `status` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> writeback.record value=`body` key=error
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
+9 -30
View File
@@ -13,35 +13,14 @@ import json:lib/json.mq.md
## 构建单步上下文
+ `智能体`
+ `任务`
+ `源码深度`=default
+ `技能深度`=default
组装可读提示:站立提示、任务、工具、调用位置、源码、Skill,以及人可见的行动约定。
组装可读提示:站立提示、任务、**调用位置**、工具、**预算**源码 + Skill,以及人可见的行动约定。
编排 `.mq.md` 即真相源(代码即文档)。默认预算防爆窗;可先 `读取:source|skill` 加深再答或 `调用:`。
实现委托 `agent.build_step_context`(与英文版同源)。
*standing = > json.get value=`智能体` key="standing"*
1. `standing`
*up = standing*
2. *
*up = 空*
*tools = > json.get value=`智能体` key="tools"*
*tools_s = > agent_format_tools tools=`tools`*
*src = > agent_module_source*
*site = > agent_call_site*
*site_s = > json.stringify value=`site`*
*skill = > agent_marqdo_skill*
*task_s = > json.stringify value=`任务`*
*esc = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- task ---\n","c":"\n\n--- tools ---\n","d":"\n\n--- call site ---\n","e":"\n\n--- source (.mq.md) ---\n","f":"\n\n--- marqdo skill ---\n","g":"\n\n--- how to act ---\nTools are ## functions in the source above. To call one, reply with exactly one line: CALL:<name>\n(Chinese ok: 调用:<name>)\nOtherwise reply with the final answer only.\nTools run via Marqdo subtask (spawn fn / wait).\n"}*
*a = > json.get value=`esc` key="a"*
*b = > json.get value=`esc` key="b"*
*c = > json.get value=`esc` key="c"*
*d = > json.get value=`esc` key="d"*
*e = > json.get value=`esc` key="e"*
*f = > json.get value=`esc` key="f"*
*g = > json.get value=`esc` key="g"*
*p = "You are a Marqdo agent. The runbook source is your ground truth — code is documentation."*
*p = p + a + up + b + task_s + c + tools_s + g + d + site_s + e + src + f + skill*
**p**
**> agent.build_step_context agent=`智能体` task=`任务` source_depth=`源码深度` skill_depth=`技能深度`**
---
@@ -195,10 +174,10 @@ import json:lib/json.mq.md
1. `写回`
*body = > json.stringify value=`out`*
*st = > json.get value=`out` key="status"*
1. `st` == ok
> 自写回.写回 值=`body` 键=ok
1. `st` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> 自写回.写回 值=`body` 键=error
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
+61 -12
View File
@@ -21,6 +21,7 @@ Load the ABI v2 `web` plugin once.
## make_style
+ `name`=""
+ `table`
+ `strict`=False
Assemble a GFM style table into a CSS string. Two shapes are accepted:
`|选择器|属性|值|` rule rows (arbitrary selectors; rows sharing a selector are
@@ -28,11 +29,14 @@ merged, and a leading `|媒体|` column groups rows into `@media` blocks), or
`|属性|值|` property rows wrapped as `.name { … }`. Selectors starting with
`@keyframes name` emit keyframe blocks (`属性` = stop `from`/`to`/`N%`,
`值` = `prop: val` or use `@keyframes name from` + normal 属性/值). Quote CSS
values that contain `/` (e.g. `"16/9"`, `"1/5"`); bare `1/5` is integer division.
Styles stay as data tables, `make_style` turns them into CSS — 样式即数据、装配即函数.
values that contain `/` (e.g. `"16/9"`, `"1 / 5"`); bare `1 / 5` is integer
division and becomes a numeric cell — default mode warns, `strict=True` errors.
For complex themes prefer `page.css` (raw string, no table eval) or an external
`static/*.css` via `page.head`. Styles stay as data tables, `make_style` turns
them into CSS — 样式即数据、装配即函数.
> ensure_plugin
**> web_style name=`name` table=`table`**
**> web_style name=`name` table=`table` strict=`strict`**
## make_images
+ `table`
@@ -179,14 +183,43 @@ Build a `render_list` effect: `{ render_list: { sel: { tag, items } } }`.
# page
+ `title`="Marqdo Web"
+ `intro`=""
+ `shell_css`=None
+ `layout`=None
+ `asset_version`=None
> ensure_plugin
**> web_page_new title=`title` intro=`intro`**
**> web_page_new title=`title` intro=`intro` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`**
## shell_css
+ `mode`=full
Framework shell CSS mode for this page: `full` (default), `minimal` (vars only), or `off`/`none`.
*`out` = > table.put in=`self` at="shell_css" value=mode*
**out**
## layout
+ `layout`=sidebar
Page chrome layout: `sidebar` (default when a side slot exists), `stacked` (single column; no `has-sidebar` grid), `bare` (main only), or `rail`.
*`out` = > table.put in=`self` at="layout" value=layout*
**out**
## asset_version
+ `version`=""
Default `?v=` bump for head scripts/styles that omit a per-row `version` column.
*`out` = > table.put in=`self` at="asset_version" value=version*
**out**
## compose_components
+ `components`
Assemble nav / sidebar / footer from a page table (`|组件|样式|` or `|src|style|`).
Nav bind tables may include optional `媒体`/`media` (responsive show) and `当`/`when`
(`auth` / `guest` / `hide`) columns — see C4 conditional nav.
**> web_compose_components page=`self` components=`components`**
@@ -223,8 +256,9 @@ an `href`/`链接` field become `<a href="{prefix}{href}">`.
## css
+ `css`
Append a raw CSS string to the page's stylesheet (`styles_css`). Use it to ship
a hand-written theme alongside the assembled shell.
Append a **raw** CSS string to the page's stylesheet (`styles_css`). Skips table-cell
expression evaluation — use for themes with `/`, `@keyframes`, or long media queries.
Hand-written theme alongside the assembled shell; or link `static/theme.css` via `head`.
**> web_page_css page=`self` css=`css`**
@@ -246,7 +280,7 @@ SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`,
## head
+ `table`
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|` or ZH `|关系|地址|类型|…|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Merges with any existing `head` on the page.
Assemble `<head>` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|defer|async|version|` or ZH `|关系|地址|…|推迟|异步|版本|`). `rel=script` / `module` become `<script>`; other rows become `<link>`. Classic scripts emit `defer` / `async` only when those columns are true (compat: missing `defer` stays synchronous). Non-empty `version` appends `?v=`; else page/app `asset_version` is used. Merges with any existing `head` on the page.
**> web_page_head page=`self` table=`table`**
@@ -565,9 +599,17 @@ Field table + rules table; submit writes through `# db`.
+ `admin`=False
+ `host`=127.0.0.1
+ `port`=18081
+ `admin_prefix`=/admin
+ `login_redirect`=None
+ `logout_redirect`=None
+ `shell_css`=None
+ `layout`=None
+ `asset_version`=None
Construct an app. `admin=True` mounts the built-in CRUD UI under `admin_prefix` (default `/admin`). When `admin=False`, that prefix is **not** reserved — you may `route` your own pages there. Optional `login_redirect` / `logout_redirect` override post-auth landing. Optional `shell_css` / `layout` / `asset_version` become defaults for pages that do not set their own (see `page.shell_css` / `page.layout` / `page.asset_version`).
> ensure_plugin
**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port`**
**> web_app_new page=`page` db=`db` admin=`admin` host=`host` port=`port` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`**
## route
+ `path`
@@ -636,18 +678,25 @@ Register a WebSocket endpoint at `path` (e.g. `/live`). `mode` is `echo` (defaul
## auth
+ `users`
+ `session_ttl`=3600
+ `admin_prefix`=None
+ `login_redirect`=None
+ `logout_redirect`=None
+ `login_path`=None
Keep the app's `admin=True`, and gate `/admin*` behind a login page. `users` is an admin-users table (`|username|password|` / `|用户名|密码|`); optional `role` / `角色` column (`admin` / `author` / `visitor`). Unauthenticated requests redirect to `/admin/login`. Registers a default gate `/admin*` → `admin`.
Keep the app's `admin=True`, and gate `{admin_prefix}` (segment-boundary prefix) behind a login page (default `/admin`). Unauthenticated requests **redirect** to `login_path` (default `{admin_prefix}/login`, auto-excluded). Does **not** match `/admin-publish`-style siblings.
**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl`**
**> web_app_auth app=`self` users=`users` session_ttl=`session_ttl` admin_prefix=`admin_prefix` login_redirect=`login_redirect` logout_redirect=`logout_redirect` login_path=`login_path`**
## gate
+ `path`
+ `roles`=admin
+ `match`=prefix
+ `on_deny`=forbid
+ `exclude`=None
Require one of `roles` (CSV) for `path` (prefix or `path*`). Anonymous sessions count as `visitor`.
Require one of `roles` (CSV) for `path`. `match=prefix` uses segment boundaries; `exact` is equality. Trailing `*` on `path` means prefix. `on_deny=redirect` sends visitors to `login_path` (with `?next=`); `forbid` returns 403. `exclude` is CSV or list of open paths.
**> web_app_gate app=`self` path=`path` roles=`roles`**
**> web_app_gate app=`self` path=`path` roles=`roles` match=`match` on_deny=`on_deny` exclude=`exclude`**
## gallery
+ `path`=/gallery
+54 -10
View File
@@ -21,17 +21,19 @@ import table:lib/table.mq.md
## 样式装配
+ `名`=""
+ `表`
+ `严格`=False
把 GFM 样式表装配成一段 CSS 文本。支持两种表形:
`|选择器|属性|值|` 规则行(选择器任意,同一选择器多行合并成一条规则;
加 `|媒体|` 列即可分组进 `@media` 块),或 `|属性|值|` 属性行(按 `.名 { … }` 包裹)。
选择器以 `@keyframes 名` 开头时输出关键帧块(`属性` 为停点 `from`/`to`/`N%`,
`值` 写 `opacity: 0` 等声明;也可用 `@keyframes 名 from` + 普通属性/值)。
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1/5"`),否则按表达式除法求值。
含 `/` 的 CSS 值请加引号(如 `"16/9"`、`"1 / 5"`);裸 `1 / 5` 会按表达式除法变成数字单元格——默认告警,`严格=真` 时报错。
复杂主题优先 `页面.样式`(原始 CSS 字符串,不经表求值)或外链 `static/*.css` + `页面.头装配`。
样式即数据、装配即函数 —— 主题模块据此把样式表拼成完整样式表。
> 确保插件
**> web_style name=`名` table=`表`**
**> web_style name=`名` table=`表` strict=`严格`**
## 图片装配
+ `表`
@@ -174,9 +176,36 @@ import table:lib/table.mq.md
# 页面
+ `标题`="站点"
+ `引言`=""
+ `壳样式`=None
+ `布局`=None
+ `资源版本`=None
> 确保插件
**> web_page_new title=`标题` intro=`引言`**
**> web_page_new title=`标题` intro=`引言` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`**
## 壳样式
+ `模式`=full
框架壳 CSS:`full`(默认)/ `minimal`(仅变量)/ `off`。
*`out` = > table.put in=`自` at="shell_css" value=模式*
**out**
## 布局
+ `布局`=sidebar
页面壳:`sidebar`(有侧栏时默认双列)/ `stacked`(单列、不加 has-sidebar)/ `bare`(仅 main)/ `rail`。
*`out` = > table.put in=`自` at="layout" value=布局*
**out**
## 资源版本
+ `版本`=""
为未写 `版本` 列的 head 脚本/样式统一追加 `?v=`。
*`out` = > table.put in=`自` at="asset_version" value=版本*
**out**
## 组件装配
+ `组件`
@@ -212,7 +241,7 @@ import table:lib/table.mq.md
## 样式
+ `样式`
把一段手写 CSS 字符串追加到页面样式表(`styles_css`),用于在装配好的外壳上叠加自定义主题。
把一段**原始** CSS 字符串追加到页面样式表(`styles_css`),不经表单元格表达式求值——适合含 `/`、`@keyframes` 或长 media 的主题。也可外链 `static/theme.css` 再经 `头装配`。
**> web_page_css page=`self` css=`样式`**
@@ -233,7 +262,7 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
## 头装配
+ `表`
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。与已有 `head` 合并。
把 Head 资源表(`|关系|地址|类型|尺寸|媒体|作为|跨域|推迟|异步|版本|`)挂到页面的 `head`。`关系=script` / `module` 生成 `<script>`,其余生成 `<link>`。经典脚本仅在 `推迟`/`异步` 为真时输出对应属性(缺省仍同步,兼容旧站)。非空 `版本` 追加 `?v=`,否则用页面/应用的 `资源版本`。与已有 `head` 合并。
**> web_page_head page=`self` table=`表`**
@@ -545,9 +574,17 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
+ `后台`=False
+ `主机`=127.0.0.1
+ `端口`=18081
+ `后台前缀`=/admin
+ `登录回跳`=None
+ `登出回跳`=None
+ `壳样式`=None
+ `布局`=None
+ `资源版本`=None
构造应用。`后台=真` 时在 `后台前缀`(默认 `/admin`)挂载内置 CRUD。`后台=假` 时该前缀**不再保留**,可自行 `路由` 到 `/admin…`。可选 `登录回跳` / `登出回跳`。可选 `壳样式` / `布局` / `资源版本` 作为未自设页面的默认(见 `页面.壳样式` / `页面.布局` / `页面.资源版本`)。
> 确保插件
**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口`**
**> web_app_new page=`页面` db=`数据库` admin=`后台` host=`主机` port=`端口` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` shell_css=`壳样式` layout=`布局` asset_version=`资源版本`**
## 路由
+ `路径`
@@ -611,18 +648,25 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
## 鉴权
+ `用户表`
+ `会话时长`=3600
+ `后台前缀`=None
+ `登录回跳`=None
+ `登出回跳`=None
+ `登录路径`=None
在保持 `后台=真` 的同时,为 `/admin*` 加登录门禁。`用户表` 为 `|用户名|密码|`(可选 `角色`:`admin`/`author`/`visitor`);未登录重定向到 `/admin/login`。默认登记门禁 `/admin*` → `admin`。
在保持 `后台=真` 的同时,为 `{后台前缀}` 加**段边界**前缀门禁(默认 `/admin`)。未登录 **重定向** 到 `登录路径`(默认 `{前缀}/login`,自动排除)。不会匹配 `/admin-publish` 这类旁系路径。
**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长`**
**> web_app_auth app=`self` users=`用户表` session_ttl=`会话时长` admin_prefix=`后台前缀` login_redirect=`登录回跳` logout_redirect=`登出回跳` login_path=`登录路径`**
## 门禁
+ `路径`
+ `角色`=admin
+ `匹配`=prefix
+ `拒绝`=forbid
+ `排除`=None
要求会话角色落在 `角色`(CSV)之一才可访问 `路径`(前缀或 `路径*`)。匿名视为 `visitor`。
要求会话角色落在 `角色`(CSV)之一。`匹配=prefix` 为段边界前缀;`exact` 为精确路径。路径末尾 `*` 亦表示前缀。`拒绝=redirect` 时访客跳转登录页(带 `?next=`);`forbid` 返回 403。`排除` 为 CSV/列表(如登录页)。
**> web_app_gate app=`self` path=`路径` roles=`角色`**
**> web_app_gate app=`self` path=`路径` roles=`角色` match=`匹配` on_deny=`拒绝` exclude=`排除`**
## 相册
+ `路径`=/gallery
+122 -5
View File
@@ -15,6 +15,11 @@ pub struct HeadLink {
pub media: String,
pub as_: String,
pub crossorigin: String,
/// When `Some(true)`, emit `defer` on classic scripts (not modules).
pub defer: Option<bool>,
pub async_: bool,
/// Query `?v=` bump for cache busting.
pub version: String,
}
#[derive(Clone, Debug)]
@@ -38,6 +43,37 @@ fn pick<'a>(m: &'a Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
keys.iter().find_map(|k| m.get(*k))
}
fn cell_boolish(v: &Value) -> Option<bool> {
match v {
Value::Bool(b) => Some(*b),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
Value::String(s) => {
let s = s.trim();
if s.is_empty() {
return None;
}
if matches!(
s,
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
) {
Some(true)
} else if matches!(
s,
"0" | "false" | "False" | "no" | "off" | "假" | "否"
) {
Some(false)
} else {
None
}
}
_ => None,
}
}
fn row_bool(m: &Map<String, Value>, keys: &[&str]) -> Option<bool> {
pick(m, keys).and_then(cell_boolish)
}
fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
pick(m, keys)
.map(|v| normalize_ref(&cell_str(v)))
@@ -46,6 +82,19 @@ fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
.to_string()
}
/// Append `?v=` / `&v=` for cache busting.
pub fn href_with_version(href: &str, version: &str) -> String {
let version = version.trim();
if version.is_empty() {
return href.to_string();
}
if href.contains('?') {
format!("{href}&v={version}")
} else {
format!("{href}?v={version}")
}
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
@@ -142,6 +191,9 @@ pub fn as_head_links(table: &Value) -> Vec<HeadLink> {
media: row_str(&m, &["媒体", "media", "Media"]),
as_: row_str(&m, &["作为", "as", "As"]),
crossorigin: row_str(&m, &["跨域", "crossorigin", "crossOrigin"]),
defer: row_bool(&m, &["推迟", "defer", "Defer"]),
async_: row_bool(&m, &["异步", "async", "Async"]).unwrap_or(false),
version: row_str(&m, &["版本", "version", "Version", "v"]),
});
}
out
@@ -152,7 +204,7 @@ pub fn head_links_to_json(links: &[HeadLink]) -> Value {
links
.iter()
.map(|l| {
json!({
let mut o = json!({
"rel": l.rel,
"href": l.href,
"type": l.type_,
@@ -160,7 +212,15 @@ pub fn head_links_to_json(links: &[HeadLink]) -> Value {
"media": l.media,
"as": l.as_,
"crossorigin": l.crossorigin,
})
"async": l.async_,
"version": l.version,
});
if let Some(d) = l.defer {
o.as_object_mut()
.unwrap()
.insert("defer".into(), json!(d));
}
o
})
.collect(),
)
@@ -187,6 +247,9 @@ pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
media: row_str(m, &["media", "媒体"]),
as_: row_str(m, &["as", "作为"]),
crossorigin: row_str(m, &["crossorigin", "跨域"]),
defer: row_bool(m, &["defer", "推迟"]),
async_: row_bool(m, &["async", "异步"]).unwrap_or(false),
version: row_str(m, &["version", "版本", "v"]),
});
}
out
@@ -194,24 +257,42 @@ pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
/// Render HeadLink list to HTML (link / script tags).
pub fn render_head_links(links: &[HeadLink]) -> String {
render_head_links_with_version(links, "")
}
pub fn render_head_links_with_version(links: &[HeadLink], asset_version: &str) -> String {
let mut s = String::new();
for l in links {
let rel = l.rel.trim().to_ascii_lowercase();
let ver = if !l.version.trim().is_empty() {
l.version.as_str()
} else {
asset_version
};
let href = href_with_version(&l.href, ver);
if rel == "script" || rel == "module" {
let mut tag = String::from("<script");
if rel == "module" || l.type_ == "module" {
let is_module = rel == "module" || l.type_ == "module";
if is_module {
tag.push_str(" type=\"module\"");
} else if !l.type_.is_empty() {
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
}
// Modules are deferred by browsers; classic scripts honor explicit defer.
if !is_module && l.defer == Some(true) {
tag.push_str(" defer");
}
if l.async_ {
tag.push_str(" async");
}
if !l.crossorigin.is_empty() {
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
}
tag.push_str(&format!(" src=\"{}\"></script>", esc(&l.href)));
tag.push_str(&format!(" src=\"{}\"></script>", esc(&href)));
s.push_str(&tag);
continue;
}
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&l.href));
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&href));
if !l.type_.is_empty() {
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
}
@@ -295,6 +376,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>)
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
});
}
@@ -347,6 +431,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>)
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
},
);
}
@@ -369,6 +456,9 @@ pub fn convention_favicon(static_dir: &Path) -> Option<(Vec<HeadLink>, Vec<IconR
media: String::new(),
as_: String::new(),
crossorigin: String::new(),
defer: None,
async_: false,
version: String::new(),
}];
let routes = vec![IconRoute {
url: "/favicon.ico".into(),
@@ -486,5 +576,32 @@ mod tests {
let h = make_head_html(&t);
assert!(h.contains("rel=\"icon\""));
assert!(h.contains("<script src=\"/static/a.js\"></script>"));
assert!(!h.contains(" defer"), "{h}");
}
#[test]
fn head_script_defer_async_version() {
let t = json!([
{"关系": "script", "地址": "/static/a.js", "推迟": true, "版本": "3"},
{"关系": "module", "地址": "/static/b.js", "版本": "9"},
{"关系": "stylesheet", "地址": "/static/t.css", "版本": "1"},
]);
let h = make_head_html(&t);
assert!(h.contains("<script defer src=\"/static/a.js?v=3\"></script>"), "{h}");
assert!(h.contains("type=\"module\""), "{h}");
assert!(h.contains("src=\"/static/b.js?v=9\""), "{h}");
assert!(h.contains("href=\"/static/t.css?v=1\""), "{h}");
}
#[test]
fn head_asset_version_fallback() {
let links = as_head_links(&json!([
{"关系": "script", "地址": "/static/a.js", "推迟": "真"},
]));
let h = render_head_links_with_version(&links, "2026-09-04");
assert!(
h.contains("<script defer src=\"/static/a.js?v=2026-09-04\"></script>"),
"{h}"
);
}
}
+8 -4
View File
@@ -193,11 +193,13 @@ fn sql_type_to_input(sql_type: &str, name: &str) -> &'static str {
}
/// Build a form handle from live SQLite schema (admin new/edit).
/// `admin_prefix` is the mount root (default `/admin`), without trailing slash.
pub fn from_schema(
db_url: &str,
table: &str,
action: &str,
id: Option<&str>,
admin_prefix: &str,
) -> Result<Value, String> {
let action = match action {
"update" | "更新" => "update",
@@ -223,22 +225,24 @@ pub fn from_schema(
"pk": c.pk,
}));
}
let base = admin_prefix.trim_end_matches('/');
let table_href = format!("{base}/{table}");
let mut form = form_new(Some(table), action, id);
if let Some(obj) = form.as_object_mut() {
obj.insert("fields".into(), Value::Array(fields));
obj.insert("redirect".into(), json!(format!("/admin/{table}")));
obj.insert("redirect".into(), json!(&table_href));
if action == "insert" {
obj.insert("action_url".into(), json!(format!("/admin/{table}/new")));
obj.insert("action_url".into(), json!(format!("{table_href}/new")));
obj.insert("title".into(), json!(format!("New {table}")));
} else if let Some(i) = id {
obj.insert(
"action_url".into(),
json!(format!("/admin/{table}/{i}/edit")),
json!(format!("{table_href}/{i}/edit")),
);
obj.insert("title".into(), json!(format!("Edit {table} #{i}")));
obj.insert("id".into(), json!(i));
}
obj.insert("cancel_href".into(), json!(format!("/admin/{table}")));
obj.insert("cancel_href".into(), json!(&table_href));
}
Ok(form)
}
+316 -58
View File
@@ -32,6 +32,24 @@ fn with_site_head(base: &Value, site_head: &[crate::assets::HeadLink]) -> Value
page
}
/// Stamp session login state so nav `when=auth|guest` can filter at render time.
fn with_nav_auth(base: &Value, cookie: Option<&str>) -> Value {
let mut page = base.clone();
let Some(obj) = page.as_object_mut() else {
return page;
};
let user = session::session_id_from_cookie(cookie)
.and_then(|sid| session::session_get(&sid, "username"));
let logged_in = user.is_some();
obj.insert("_logged_in".into(), json!(logged_in));
if let Some(u) = user {
obj.insert("_nav_user".into(), u);
} else {
obj.remove("_nav_user");
}
page
}
fn serve_icon_file(path: PathBuf, content_type: String) -> Response {
match std::fs::read(&path) {
Ok(bytes) => {
@@ -69,11 +87,115 @@ pub struct DownloadRoute {
pub disposition: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GateMatch {
Exact,
/// Segment-boundary prefix: `/desk` matches `/desk` and `/desk/…`, not `/desk-x`.
Prefix,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OnDeny {
Redirect,
Forbid,
}
#[derive(Clone, Debug)]
pub struct Gate {
pub path: String,
pub roles: Vec<String>,
pub match_mode: GateMatch,
pub on_deny: OnDeny,
pub exclude: Vec<String>,
}
impl Gate {
pub fn from_json(g: &Value) -> Option<Self> {
let raw = g.get("path").and_then(|v| v.as_str())?.trim();
if raw.is_empty() {
return None;
}
let starred = raw.ends_with('*');
let mut path = raw.trim_end_matches('*').trim_end_matches('/').to_string();
if path.is_empty() {
path = "/".into();
} else if !path.starts_with('/') {
path = format!("/{path}");
}
let roles = match g.get("roles") {
Some(Value::Array(a)) => a
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_ascii_lowercase()))
.collect(),
Some(Value::String(s)) => session::parse_roles_csv(s),
_ => vec!["admin".into()],
};
let match_s = g
.get("match")
.or_else(|| g.get("匹配"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_ascii_lowercase();
let match_mode = match match_s.as_str() {
"exact" | "精确" => GateMatch::Exact,
"prefix" | "前缀" => GateMatch::Prefix,
_ if starred => GateMatch::Prefix,
_ => GateMatch::Prefix,
};
let deny_s = g
.get("on_deny")
.or_else(|| g.get("拒绝"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_ascii_lowercase();
let on_deny = match deny_s.as_str() {
"redirect" | "重定向" | "login" => OnDeny::Redirect,
"forbid" | "禁止" | "403" => OnDeny::Forbid,
_ => OnDeny::Forbid,
};
let mut exclude = Vec::new();
if let Some(Value::Array(a)) = g.get("exclude").or_else(|| g.get("排除")) {
for v in a {
if let Some(s) = v.as_str() {
let s = s.trim();
if !s.is_empty() {
exclude.push(s.to_string());
}
}
}
} else if let Some(s) = g
.get("exclude")
.or_else(|| g.get("排除"))
.and_then(|v| v.as_str())
{
for part in s.split(',') {
let part = part.trim();
if !part.is_empty() {
exclude.push(part.to_string());
}
}
}
Some(Gate {
path,
roles,
match_mode,
on_deny,
exclude,
})
}
}
#[derive(Clone)]
pub struct AppState {
page: Value,
pub db_url: Option<String>,
admin: bool,
/// Built-in admin mount root (e.g. `/admin` or `/desk`); unused when `admin` is false.
admin_prefix: String,
/// Login form URL (GET/POST); may differ from `{admin_prefix}/login`.
login_path: String,
login_redirect: String,
logout_redirect: String,
forms: HashMap<String, Value>,
/// Page that owns an embedded form (for re-render on validation errors).
form_owners: HashMap<String, Value>,
@@ -90,6 +212,22 @@ pub struct AppState {
site_head: Vec<crate::assets::HeadLink>,
}
impl AppState {
fn ap(&self) -> &str {
self.admin_prefix.trim_end_matches('/')
}
fn admin_href(&self, rest: &str) -> String {
let p = self.ap();
let rest = rest.trim().trim_start_matches('/');
if rest.is_empty() {
p.to_string()
} else {
format!("{p}/{rest}")
}
}
}
fn collect_page_forms(
page: &Value,
forms: &mut HashMap<String, Value>,
@@ -118,6 +256,10 @@ pub fn listen(
host: &str,
port: u16,
admin: bool,
admin_prefix: &str,
login_path: &str,
login_redirect: &str,
logout_redirect: &str,
mut forms: HashMap<String, Value>,
routes: HashMap<String, Value>,
static_dir: Option<PathBuf>,
@@ -134,7 +276,7 @@ pub fn listen(
robots_body: Option<String>,
page_404: Option<Value>,
page_500: Option<Value>,
gates: Vec<(String, Vec<String>)>,
gates: Vec<Gate>,
gallery_routes: HashMap<String, Value>,
middleware: &Middleware,
mut site_head: Vec<crate::assets::HeadLink>,
@@ -166,10 +308,31 @@ pub fn listen(
// Resolve relative icon paths: try as-is absolute, else leave for entry_dir resolve in lib.
// (Absolute paths preferred; relative already joined in web_listen.)
let admin_prefix = {
let mut p = admin_prefix.trim().to_string();
if !p.starts_with('/') {
p = format!("/{p}");
}
while p.len() > 1 && p.ends_with('/') {
p.pop();
}
p
};
let state = Arc::new(AppState {
page: page.clone(),
db_url: db_url.map(|s| s.to_string()),
admin,
admin_prefix: admin_prefix.clone(),
login_path: {
let lp = login_path.trim();
if lp.is_empty() {
format!("{}/login", admin_prefix.trim_end_matches('/'))
} else {
lp.to_string()
}
},
login_redirect: login_redirect.to_string(),
logout_redirect: logout_redirect.to_string(),
forms,
form_owners,
auth_users,
@@ -185,17 +348,23 @@ pub fn listen(
let mut app = Router::new()
.route("/", get(home))
.route("/_part/{id}", get(home_part))
.route("/_form/{id}", get(form_get).post(form_post))
.route("/admin", get(admin_home))
.route("/admin/login", get(admin_login_get).post(admin_login_post))
.route("/admin/logout", get(admin_logout))
.route("/admin/{table}", get(admin_table))
.route("/admin/{table}/new", get(admin_new_get).post(admin_new_post))
.route(
"/admin/{table}/{id}/edit",
get(admin_edit_get).post(admin_edit_post),
)
.route("/admin/{table}/{id}/delete", get(admin_delete));
.route("/_form/{id}", get(form_get).post(form_post));
// Built-in admin only when enabled — otherwise `/admin…` is free for author routes.
if admin {
let admin_routes = Router::new()
.route("/", get(admin_home))
.route("/login", get(admin_login_get).post(admin_login_post))
.route("/logout", get(admin_logout))
.route("/{table}", get(admin_table))
.route("/{table}/new", get(admin_new_get).post(admin_new_post))
.route(
"/{table}/{id}/edit",
get(admin_edit_get).post(admin_edit_post),
)
.route("/{table}/{id}/delete", get(admin_delete));
app = app.nest(&admin_prefix, admin_routes);
}
// Register each author route as an exact GET path + `{path}/_part/{id}`.
// Paths containing `{param}` become dynamic routes (e.g. `/post/{slug}`);
@@ -214,6 +383,8 @@ pub fn listen(
inject_params(&mut p, &params);
let p = with_site_head(&p, &st.site_head);
let (_, csrf, set_cookie) = resolve_session(&headers);
let cookie = cookie_from_headers(&headers);
let p = with_nav_auth(&p, cookie);
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))).into_response();
append_set_cookie(&mut resp, set_cookie);
resp
@@ -237,6 +408,7 @@ pub fn listen(
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap| {
let (_, csrf, set_cookie) = resolve_session(&headers);
let p = with_site_head(&page_for_render, &st.site_head);
let p = with_nav_auth(&p, cookie_from_headers(&headers));
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf)))
.into_response();
append_set_cookie(&mut resp, set_cookie);
@@ -434,10 +606,12 @@ pub fn listen(
let app = crate::middleware::apply(app, middleware);
let app = if !gates.is_empty() {
let gates_for_mw = gates.clone();
let login_path_for_mw = state.login_path.clone();
app.layer(axum::middleware::from_fn(
move |req: axum::http::Request<axum::body::Body>, next: axum::middleware::Next| {
let gates = gates_for_mw.clone();
async move { rbac_middleware(gates, req, next).await }
let login_path = login_path_for_mw.clone();
async move { rbac_middleware(gates, login_path, req, next).await }
},
))
} else {
@@ -515,6 +689,7 @@ fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> Response {
async fn home(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
let (_, csrf, set_cookie) = resolve_session(&headers);
let page = with_site_head(&st.page, &st.site_head);
let page = with_nav_auth(&page, cookie_from_headers(&headers));
let html = render::render_page(&page, st.db_url.as_deref(), Some(&csrf));
let mut resp = Html(html).into_response();
append_set_cookie(&mut resp, set_cookie);
@@ -902,17 +1077,34 @@ fn weak_etag(bytes: &[u8]) -> String {
format!("W/\"{h:x}-{}\"", bytes.len())
}
fn path_matches(path: &str, pattern: &str) -> bool {
let pat = pattern.trim_end_matches('*');
if pattern.ends_with('*') {
path == pat.trim_end_matches('/') || path.starts_with(pat)
} else {
path == pattern || path.starts_with(&format!("{pattern}/"))
fn gate_matches(path: &str, gate: &Gate) -> bool {
let pat = gate.path.trim_end_matches('*').trim_end_matches('/');
let pat = if pat.is_empty() { "/" } else { pat };
match gate.match_mode {
GateMatch::Exact => path == pat || path == gate.path,
GateMatch::Prefix => path == pat || path.starts_with(&format!("{pat}/")),
}
}
fn path_excluded(path: &str, exclude: &[String], login_path: &str) -> bool {
if path == login_path || path.starts_with(&format!("{login_path}?")) {
return true;
}
for ex in exclude {
let ex = ex.trim_end_matches('*').trim_end_matches('/');
if ex.is_empty() {
continue;
}
if path == ex || path.starts_with(&format!("{ex}/")) {
return true;
}
}
false
}
async fn rbac_middleware(
gates: Vec<(String, Vec<String>)>,
gates: Vec<Gate>,
login_path: String,
req: axum::http::Request<axum::body::Body>,
next: axum::middleware::Next,
) -> Response {
@@ -922,18 +1114,23 @@ async fn rbac_middleware(
.get(header::COOKIE)
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
for (prefix, roles) in &gates {
if !path_matches(&path, prefix) {
for gate in &gates {
if !gate_matches(&path, gate) {
continue;
}
// Login page itself must stay reachable.
if path == "/admin/login" || path.starts_with("/admin/login?") {
if path_excluded(&path, &gate.exclude, &login_path) {
break;
}
let role = session::session_role(cookie.as_deref());
if !session::role_allowed(&role, roles) {
if role == "visitor" && path.starts_with("/admin") {
return Redirect::to("/admin/login").into_response();
if !session::role_allowed(&role, &gate.roles) {
if role == "visitor" && gate.on_deny == OnDeny::Redirect {
let next_q = urlencoding_path(&path);
let dest = if next_q.is_empty() || path == login_path {
login_path.clone()
} else {
format!("{login_path}?next={next_q}")
};
return Redirect::to(&dest).into_response();
}
return (
StatusCode::FORBIDDEN,
@@ -948,6 +1145,19 @@ async fn rbac_middleware(
next.run(req).await
}
fn urlencoding_path(path: &str) -> String {
let mut out = String::new();
for b in path.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
fn gallery_page(_st: &AppState, cfg: &Value) -> Response {
let storage_url = cfg
.get("storage")
@@ -1044,18 +1254,15 @@ h1{{margin:0 0 1rem;font-size:1.5rem}}
}
fn admin_gate(st: &AppState, cookie_header: Option<&str>) -> Option<Response> {
// When admin=false the built-in routes are not mounted; defense-in-depth only.
if !st.admin {
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">Admin is disabled for this app.</p>")).into_response());
return Some((StatusCode::NOT_FOUND, "Not Found").into_response());
}
if st.db_url.is_none() {
return Some(Html(admin_shell(st, "Admin", None, "<p class=\"flash err\">No database bound to this app.</p>")).into_response());
}
// Login-gated admin: require a valid admin-role session.
if st.auth_users.is_some() && !admin_authed(st, cookie_header) {
return Some(
Redirect::to("/admin/login")
.into_response(),
);
return Some(Redirect::to(&st.login_path).into_response());
}
None
}
@@ -1074,10 +1281,10 @@ fn admin_authed(_st: &AppState, cookie_header: Option<&str>) -> bool {
async fn admin_login_get(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
if st.auth_users.is_none() {
return Redirect::to("/admin").into_response();
return Redirect::to(&st.login_redirect).into_response();
}
if admin_authed(&st, cookie_from_headers(&headers)) {
return Redirect::to("/admin").into_response();
return Redirect::to(&st.login_redirect).into_response();
}
let (_, csrf, set_cookie) = resolve_session(&headers);
let mut resp = Html(login_page(&st, None, Some(&csrf))).into_response();
@@ -1091,7 +1298,7 @@ async fn admin_login_post(
Form(posted): Form<HashMap<String, String>>,
) -> Response {
let Some(users) = &st.auth_users else {
return Redirect::to("/admin").into_response();
return Redirect::to(&st.login_redirect).into_response();
};
let (_, csrf, set_cookie, posted) = match validate_csrf_post(&headers, posted) {
Ok(v) => v,
@@ -1117,7 +1324,7 @@ async fn admin_login_post(
let sid = session::session_new(Some(st.session_ttl));
session::session_set(&sid, "username", json!(user));
session::session_set(&sid, "role", json!(role));
let mut resp = Redirect::to("/admin").into_response();
let mut resp = Redirect::to(&st.login_redirect).into_response();
let _ = resp.headers_mut().try_append(
axum::http::header::SET_COOKIE,
session::session_cookie(&sid, st.session_ttl, st.cookie_secure)
@@ -1128,7 +1335,7 @@ async fn admin_login_post(
resp
}
fn login_page(_st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String {
fn login_page(st: &AppState, error: Option<&str>, csrf: Option<&str>) -> String {
let err = match error {
Some(e) => format!("<p class=\"flash err\">{}</p>", esc(e)),
None => String::new(),
@@ -1163,7 +1370,7 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background
<h1>Admin</h1>
<p class="sub">Sign in to manage this site.</p>
{err}
<form method="post" action="/admin/login">
<form method="post" action="{login_action}">
{csrf_field}
<label>Username<input name="username" autocomplete="username" required autofocus/></label>
<label>Password<input name="password" type="password" autocomplete="current-password" required/></label>
@@ -1173,11 +1380,12 @@ body {{ margin:0; min-height:100vh; display:grid; place-items:center; background
</body></html>"#,
err = err,
csrf_field = csrf_field,
login_action = esc(&st.login_path),
)
}
async fn admin_logout(
State(_st): State<Arc<AppState>>,
State(st): State<Arc<AppState>>,
headers: axum::http::HeaderMap,
) -> Response {
if let Some(sid) = session::session_id_from_cookie(
@@ -1187,7 +1395,7 @@ async fn admin_logout(
) {
session::session_destroy(&sid);
}
let mut resp = Redirect::to("/admin/login").into_response();
let mut resp = Redirect::to(&st.logout_redirect).into_response();
if let Ok(h) = resp.headers_mut().try_append(
axum::http::header::SET_COOKIE,
"marqdo_sid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax"
@@ -1217,7 +1425,7 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) ->
.as_deref()
.and_then(|u| db::list_tables(u).ok())
.unwrap_or_default();
let mut side = String::from("<nav class=\"admin-nav\"><a class=\"brand\" href=\"/admin\">Admin</a>");
let mut side = format!("<nav class=\"admin-nav\"><a class=\"brand\" href=\"{}\">Admin</a>", esc(st.ap()));
if tables.is_empty() {
side.push_str("<p class=\"muted\">No tables yet.</p>");
} else {
@@ -1229,8 +1437,8 @@ fn admin_shell(st: &AppState, title: &str, active: Option<&str>, inner: &str) ->
""
};
side.push_str(&format!(
"<li><a{cls} href=\"/admin/{}\">{}</a></li>",
esc(t),
"<li><a{cls} href=\"{}\">{}</a></li>",
esc(&st.admin_href(t)),
esc(t)
));
}
@@ -1325,7 +1533,9 @@ fn admin_form_page(
csrf: Option<&str>,
) -> String {
let mut body = format!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / <a href=\"/admin/{t}\">{t}</a> / {kind}</p><h1>{kind} {t}</h1>",
"<p class=\"crumbs\"><a href=\"{home}\">Admin</a> / <a href=\"{table_href}\">{t}</a> / {kind}</p><h1>{kind} {t}</h1>",
home = esc(st.ap()),
table_href = esc(&st.admin_href(table)),
t = esc(table),
kind = esc(kind),
);
@@ -1358,7 +1568,9 @@ async fn admin_home(
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr><th>Table</th><th></th></tr></thead><tbody>");
for t in &tables {
inner.push_str(&format!(
"<tr><td><a href=\"/admin/{t}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"/admin/{t}/new\">New</a></td></tr>",
"<tr><td><a href=\"{href}\">{t}</a></td><td class=\"actions\"><a class=\"btn\" href=\"{new_href}\">New</a></td></tr>",
href = esc(&st.admin_href(t)),
new_href = esc(&st.admin_href(&format!("{t}/new"))),
t = esc(t)
));
}
@@ -1407,22 +1619,23 @@ async fn admin_table(
}
let mut inner = format!(
"<p class=\"crumbs\"><a href=\"/admin\">Admin</a> / {t}</p><h1>{t}</h1>",
"<p class=\"crumbs\"><a href=\"{home}\">Admin</a> / {t}</p><h1>{t}</h1>",
home = esc(st.ap()),
t = esc(&table)
);
inner.push_str(&flash_html(q.flash.as_deref()));
inner.push_str(&format!(
"<div class=\"toolbar\"><a class=\"btn\" href=\"/admin/{}/new\">New row</a><span class=\"meta\">{} row{}</span></div>",
esc(&table),
"<div class=\"toolbar\"><a class=\"btn\" href=\"{new_href}\">New row</a><span class=\"meta\">{} row{}</span></div>",
rows.len(),
if rows.len() == 1 { "" } else { "s" }
if rows.len() == 1 { "" } else { "s" },
new_href = esc(&st.admin_href(&format!("{table}/new"))),
));
if rows.is_empty() {
inner.push_str(&format!(
"<div class=\"empty\"><strong>No rows in {}</strong><a class=\"btn\" href=\"/admin/{}/new\">Create the first row</a></div>",
"<div class=\"empty\"><strong>No rows in {}</strong><a class=\"btn\" href=\"{new_href}\">Create the first row</a></div>",
esc(&table),
esc(&table)
new_href = esc(&st.admin_href(&format!("{table}/new"))),
));
} else {
inner.push_str("<div class=\"table-wrap\"><table class=\"data\"><thead><tr>");
@@ -1454,7 +1667,10 @@ async fn admin_table(
.unwrap_or_default();
if !id.is_empty() {
inner.push_str(&format!(
"<td class=\"actions\"><a href=\"/admin/{table}/{id}/edit\">Edit</a> · <a class=\"danger\" href=\"/admin/{table}/{id}/delete\" onclick=\"return confirm('Delete row #{id}?')\">Delete</a></td>"
"<td class=\"actions\"><a href=\"{edit}\">Edit</a> · <a class=\"danger\" href=\"{del}\" onclick=\"return confirm('Delete row #{id}?')\">Delete</a></td>",
edit = esc(&st.admin_href(&format!("{table}/{id}/edit"))),
del = esc(&st.admin_href(&format!("{table}/{id}/delete"))),
id = esc(&id),
));
} else {
inner.push_str("<td></td>");
@@ -1476,7 +1692,7 @@ async fn admin_new_get(
}
let url = st.db_url.as_deref().unwrap();
let (_, csrf, set_cookie) = resolve_session(&headers);
match form::from_schema(url, &table, "insert", None) {
match form::from_schema(url, &table, "insert", None, st.ap()) {
Ok(frm) => {
let mut resp = Html(admin_form_page(
&st,
@@ -1516,7 +1732,7 @@ async fn admin_new_post(
Ok(v) => v,
Err(r) => return r,
};
match form::from_schema(url, &table, "insert", None) {
match form::from_schema(url, &table, "insert", None, st.ap()) {
Ok(frm) => {
let mut resp = submit_and_respond(
&st,
@@ -1571,7 +1787,7 @@ async fn admin_edit_get(
}
};
let (_, csrf, set_cookie) = resolve_session(&headers);
match form::from_schema(url, &table, "update", Some(&id)) {
match form::from_schema(url, &table, "update", Some(&id), st.ap()) {
Ok(frm) => {
let mut resp = Html(admin_form_page(
&st,
@@ -1611,7 +1827,7 @@ async fn admin_edit_post(
Ok(v) => v,
Err(r) => return r,
};
match form::from_schema(url, &table, "update", Some(&id)) {
match form::from_schema(url, &table, "update", Some(&id), st.ap()) {
Ok(frm) => {
let mut resp = submit_and_respond(
&st,
@@ -1653,7 +1869,7 @@ async fn admin_delete(
))
.into_response();
}
Redirect::to(&with_flash(&format!("/admin/{table}"), "deleted")).into_response()
Redirect::to(&with_flash(&st.admin_href(&table), "deleted")).into_response()
}
fn esc(s: &str) -> String {
@@ -1809,3 +2025,45 @@ async fn ws_socket_loop(
}
}
}
#[cfg(test)]
mod gate_tests {
use super::*;
fn g(path: &str, mode: GateMatch) -> Gate {
Gate {
path: path.into(),
roles: vec!["admin".into()],
match_mode: mode,
on_deny: OnDeny::Forbid,
exclude: vec![],
}
}
#[test]
fn prefix_segment_boundary() {
let gate = g("/admin", GateMatch::Prefix);
assert!(gate_matches("/admin", &gate));
assert!(gate_matches("/admin/news", &gate));
assert!(!gate_matches("/admin-publish", &gate));
assert!(!gate_matches("/administrator", &gate));
}
#[test]
fn starred_json_becomes_prefix() {
let gate = Gate::from_json(&json!({"path": "/admin*", "roles": ["admin"]})).unwrap();
assert_eq!(gate.match_mode, GateMatch::Prefix);
assert!(gate_matches("/admin/x", &gate));
assert!(!gate_matches("/admin-publish", &gate));
}
#[test]
fn exclude_login() {
assert!(path_excluded(
"/desk/login",
&["/desk/login".into()],
"/desk/login"
));
assert!(!path_excluded("/desk", &["/desk/login".into()], "/desk/login"));
}
}
+324 -58
View File
@@ -22,7 +22,7 @@ mod upload;
mod ws;
mod ws_hub;
use crate::table::as_css_named;
use crate::table::as_css_named_checked;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_int, c_void};
@@ -273,10 +273,24 @@ macro_rules! web_ffi {
web_ffi!(web_page_new, |args: &Value| {
let title = arg_str_opt(args, "title").unwrap_or("Marqdo Web");
let intro = arg_str_opt(args, "intro").unwrap_or("");
Ok(json!({
let mut out = json!({
"title": title,
"intro": intro,
}))
});
if let Some(s) = arg_str_opt(args, "shell_css").or_else(|| arg_str_opt(args, "壳样式")) {
out.as_object_mut().unwrap().insert("shell_css".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) {
out.as_object_mut().unwrap().insert("layout".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "asset_version")
.or_else(|| arg_str_opt(args, "资源版本"))
{
out.as_object_mut()
.unwrap()
.insert("asset_version".into(), json!(s));
}
Ok(out)
});
web_ffi!(web_compose_components, |args: &Value| {
@@ -348,7 +362,21 @@ web_ffi!(web_page_css, |args: &Value| {
web_ffi!(web_style, |args: &Value| {
let name = arg_str_opt(args, "name").unwrap_or("").to_string();
let table = args.get("table").cloned().unwrap_or(json!([]));
Ok(Value::String(as_css_named(&name, &table)))
let strict = args
.get("strict")
.or_else(|| args.get("strict_css_cells"))
.or_else(|| args.get("严格"))
.map(|v| match v {
Value::Bool(b) => *b,
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
Value::String(s) => matches!(
s.trim(),
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
),
_ => false,
})
.unwrap_or(false);
as_css_named_checked(&name, &table, strict).map(Value::String)
});
web_ffi!(web_page_detail, |args: &Value| {
@@ -500,7 +528,7 @@ web_ffi!(web_rss_build, |args: &Value| {
web_ffi!(web_app_route_rss, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let path = normalize_route_path_in_app(arg_str(args, "path")?, &app)?;
let table = arg_str(args, "table")?.to_string();
let limit = args
.get("limit")
@@ -537,7 +565,7 @@ web_ffi!(web_app_route_rss, |args: &Value| {
web_ffi!(web_app_redirect, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let from = normalize_route_path(arg_str(args, "from").or_else(|_| arg_str(args, "path"))?)?;
let from = normalize_route_path_in_app(arg_str(args, "from").or_else(|_| arg_str(args, "path"))?, &app)?;
let to = arg_str(args, "to")?.to_string();
let permanent = match args
.get("permanent")
@@ -588,7 +616,7 @@ web_ffi!(web_app_error_page, |args: &Value| {
web_ffi!(web_app_sitemap, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path").unwrap_or("/sitemap.xml"))?;
let path = normalize_route_path_in_app(arg_str(args, "path").unwrap_or("/sitemap.xml"), &app)?;
let base = arg_str_opt(args, "base").unwrap_or("").to_string();
let table = arg_str_opt(args, "table").map(|s| s.to_string());
let loc = arg_str_opt(args, "loc").unwrap_or("path").to_string();
@@ -655,7 +683,7 @@ fn storage_url_arg(args: &Value, key: &str) -> Result<String, String> {
web_ffi!(web_app_upload, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path").unwrap_or("/_upload"))?;
let path = normalize_route_path_in_app(arg_str(args, "path").unwrap_or("/_upload"), &app)?;
let field = arg_str_opt(args, "field").unwrap_or("file").to_string();
let storage_url = storage_url_arg(args, "storage")?;
let prefix = arg_str_opt(args, "prefix").unwrap_or("uploads/").to_string();
@@ -1023,27 +1051,57 @@ web_ffi!(web_app_new, |args: &Value| {
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
_ => false,
};
Ok(json!({
let admin_prefix = arg_str_opt(args, "admin_prefix")
.or_else(|| arg_str_opt(args, "后台前缀"))
.map(normalize_admin_prefix)
.transpose()?
.unwrap_or_else(|| "/admin".into());
let login_redirect = arg_str_opt(args, "login_redirect")
.or_else(|| arg_str_opt(args, "登录回跳"))
.map(|s| s.to_string());
let logout_redirect = arg_str_opt(args, "logout_redirect")
.or_else(|| arg_str_opt(args, "登出回跳"))
.map(|s| s.to_string());
let mut out = json!({
"page": page,
"db": db,
"host": host,
"port": port,
"admin": admin,
"admin_prefix": admin_prefix,
"forms": {},
"routes": {},
"ws_routes": {},
"static_dir": null,
"static_mount": "/static",
}))
});
if let Some(v) = login_redirect {
out.as_object_mut().unwrap().insert("login_redirect".into(), json!(v));
}
if let Some(v) = logout_redirect {
out.as_object_mut().unwrap().insert("logout_redirect".into(), json!(v));
}
if let Some(s) = arg_str_opt(args, "shell_css").or_else(|| arg_str_opt(args, "壳样式")) {
out.as_object_mut().unwrap().insert("shell_css".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) {
out.as_object_mut().unwrap().insert("layout".into(), json!(s));
}
if let Some(s) = arg_str_opt(args, "asset_version")
.or_else(|| arg_str_opt(args, "资源版本"))
{
out.as_object_mut()
.unwrap()
.insert("asset_version".into(), json!(s));
}
Ok(out)
});
fn normalize_route_path(raw: &str) -> Result<String, String> {
/// Normalize a URL path: leading slash, no trailing slash (except never `/` here).
fn clean_mount_path(raw: &str) -> Result<String, String> {
let s = raw.trim();
if s.is_empty() {
return Err("route path is empty".into());
}
if s == "/" {
return Err("route path `/` is reserved for the home page".into());
return Err("path is empty".into());
}
let mut path = if s.starts_with('/') {
s.to_string()
@@ -1053,24 +1111,88 @@ fn normalize_route_path(raw: &str) -> Result<String, String> {
while path.len() > 1 && path.ends_with('/') {
path.pop();
}
// reserved prefixes
if path == "/admin"
|| path.starts_with("/admin/")
|| path == "/_form"
Ok(path)
}
fn normalize_admin_prefix(raw: &str) -> Result<String, String> {
let path = clean_mount_path(raw)?;
if path == "/" {
return Err("admin_prefix cannot be `/`".into());
}
if path == "/_form"
|| path.starts_with("/_form/")
|| path == "/_part"
|| path.starts_with("/_part/")
|| path == "/static"
|| path.starts_with("/static/")
{
return Err(format!("admin_prefix `{path}` collides with framework paths"));
}
Ok(path)
}
fn path_under_prefix(path: &str, prefix: &str) -> bool {
path == prefix || path.starts_with(&format!("{prefix}/"))
}
fn is_framework_reserved(path: &str, static_mount: &str) -> bool {
path == "/_form"
|| path.starts_with("/_form/")
|| path == "/_part"
|| path.starts_with("/_part/")
|| path_under_prefix(path, static_mount)
}
/// Reserved only while built-in admin is enabled, for the active prefix.
fn normalize_route_path_for(
raw: &str,
admin: bool,
admin_prefix: &str,
static_mount: &str,
) -> Result<String, String> {
let path = clean_mount_path(raw)?;
if path == "/" {
return Err("route path `/` is reserved for the home page".into());
}
if is_framework_reserved(&path, static_mount) {
return Err(format!("route path `{path}` is reserved"));
}
if admin && path_under_prefix(&path, admin_prefix) {
return Err(format!("route path `{path}` is reserved"));
}
Ok(path)
}
fn app_admin_flag(app: &Value) -> bool {
app.get("admin")
.and_then(|v| v.as_bool())
.unwrap_or(false)
}
fn app_admin_prefix(app: &Value) -> String {
app.get("admin_prefix")
.and_then(|v| v.as_str())
.and_then(|s| normalize_admin_prefix(s).ok())
.unwrap_or_else(|| "/admin".into())
}
fn app_static_mount(app: &Value) -> String {
app.get("static_mount")
.and_then(|v| v.as_str())
.map(http::normalize_static_mount)
.unwrap_or_else(|| "/static".into())
}
fn normalize_route_path_in_app(raw: &str, app: &Value) -> Result<String, String> {
normalize_route_path_for(
raw,
app_admin_flag(app),
&app_admin_prefix(app),
&app_static_mount(app),
)
}
web_ffi!(web_app_route, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let path = normalize_route_path_in_app(arg_str(args, "path")?, &app)?;
let mut page = args
.get("page")
.cloned()
@@ -1094,7 +1216,7 @@ web_ffi!(web_app_route, |args: &Value| {
web_ffi!(web_app_route_ws, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let path = normalize_route_path_in_app(arg_str(args, "path")?, &app)?;
let mode = if let Some(m) = args.get("mode").or_else(|| args.get("模式")) {
crate::ws_hub::WsMode::parse(m)
} else {
@@ -1179,26 +1301,62 @@ web_ffi!(web_app_auth, |args: &Value| {
.get("session_ttl")
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
.unwrap_or(3600);
if let Some(p) = arg_str_opt(args, "admin_prefix").or_else(|| arg_str_opt(args, "后台前缀")) {
let p = normalize_admin_prefix(p)?;
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("admin_prefix".into(), json!(p));
}
if let Some(v) = arg_str_opt(args, "login_redirect").or_else(|| arg_str_opt(args, "登录回跳")) {
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("login_redirect".into(), json!(v));
}
if let Some(v) = arg_str_opt(args, "logout_redirect").or_else(|| arg_str_opt(args, "登出回跳")) {
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("logout_redirect".into(), json!(v));
}
if let Some(v) = arg_str_opt(args, "login_path").or_else(|| arg_str_opt(args, "登录路径")) {
app.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?
.insert("login_path".into(), json!(v));
}
let prefix = app_admin_prefix(&app);
let login_path = app
.get("login_path")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{prefix}/login"));
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
obj.insert("login_path".into(), json!(&login_path));
obj.insert(
"auth".to_string(),
json!({ "users": users, "session_ttl": session_ttl }),
);
// Default RBAC: `/admin*` requires role `admin` when auth is configured.
// Default RBAC: segment-boundary prefix on admin_prefix; redirect visitors to login.
let mut gates = obj
.get("gates")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let has_admin_gate = gates.iter().any(|g| {
g.get("path")
.and_then(|v| v.as_str())
.is_some_and(|p| p == "/admin" || p == "/admin*")
g.get("path").and_then(|v| v.as_str()).is_some_and(|p| {
let cleaned = p.trim_end_matches('*').trim_end_matches('/');
cleaned == prefix.trim_end_matches('/')
})
});
if !has_admin_gate {
gates.push(json!({ "path": "/admin*", "roles": ["admin"] }));
gates.push(json!({
"path": prefix,
"roles": ["admin"],
"match": "prefix",
"on_deny": "redirect",
"exclude": [login_path],
}));
obj.insert("gates".into(), Value::Array(gates));
}
Ok(app)
@@ -1211,6 +1369,17 @@ web_ffi!(web_app_gate, |args: &Value| {
.or_else(|| arg_str_opt(args, "角色"))
.unwrap_or("admin");
let roles: Vec<String> = session::parse_roles_csv(roles_raw);
let match_mode = arg_str_opt(args, "match")
.or_else(|| arg_str_opt(args, "匹配"))
.unwrap_or("prefix");
let on_deny = arg_str_opt(args, "on_deny")
.or_else(|| arg_str_opt(args, "拒绝"))
.unwrap_or("forbid");
let exclude = args
.get("exclude")
.or_else(|| args.get("排除"))
.cloned()
.unwrap_or(Value::Null);
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
@@ -1219,17 +1388,30 @@ web_ffi!(web_app_gate, |args: &Value| {
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
gates.push(json!({ "path": path, "roles": roles }));
let mut entry = json!({
"path": path,
"roles": roles,
"match": match_mode,
"on_deny": on_deny,
});
if !matches!(exclude, Value::Null) {
entry
.as_object_mut()
.unwrap()
.insert("exclude".into(), exclude);
}
gates.push(entry);
obj.insert("gates".into(), Value::Array(gates));
Ok(app)
});
web_ffi!(web_app_gallery, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(
let path = normalize_route_path_in_app(
arg_str(args, "path")
.or_else(|_| arg_str(args, "路径"))
.unwrap_or("/gallery"),
&app,
)?;
let storage_url = storage_url_arg(args, "storage")
.or_else(|_| storage_url_arg(args, "存储"))?;
@@ -1293,16 +1475,16 @@ web_ffi!(web_app_static, |args: &Value| {
}
let mount = arg_str_opt(args, "mount").unwrap_or("/static");
let mount = http::normalize_static_mount(mount);
// Also reserve custom mounts against later routes.
if mount == "/admin"
|| mount.starts_with("/admin/")
|| mount == "/_form"
if mount == "/_form"
|| mount.starts_with("/_form/")
|| mount == "/_part"
|| mount.starts_with("/_part/")
{
return Err(format!("static mount `{mount}` is reserved"));
}
if app_admin_flag(&app) && path_under_prefix(&mount, &app_admin_prefix(&app)) {
return Err(format!("static mount `{mount}` is reserved"));
}
let obj = app
.as_object_mut()
.ok_or_else(|| "app must be a map".to_string())?;
@@ -1463,7 +1645,10 @@ web_ffi!(web_form_from_schema, |args: &Value| {
None | Some(Value::Null) => None,
Some(_) => Some(arg_text(args, "id")?),
};
form::from_schema(&url, &table, action, id.as_deref())
let admin_prefix = arg_str_opt(args, "admin_prefix")
.or_else(|| arg_str_opt(args, "后台前缀"))
.unwrap_or("/admin");
form::from_schema(&url, &table, action, id.as_deref(), admin_prefix)
});
web_ffi!(web_db_table_info, |args: &Value| {
@@ -1484,6 +1669,48 @@ web_ffi!(web_db_table_info, |args: &Value| {
Ok(json!({ "columns": arr }))
});
fn stamp_page_shell(
page: &mut Value,
shell_css: Option<&str>,
layout: Option<&str>,
asset_version: Option<&str>,
) {
let Some(obj) = page.as_object_mut() else {
return;
};
if let Some(s) = shell_css {
let empty = obj
.get("shell_css")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("shell_css".into(), json!(s));
}
}
if let Some(s) = layout {
let empty = obj
.get("layout")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("layout".into(), json!(s));
}
}
if let Some(s) = asset_version {
let empty = obj
.get("asset_version")
.and_then(|v| v.as_str())
.unwrap_or("")
.is_empty();
if empty {
obj.insert("asset_version".into(), json!(s));
}
}
}
web_ffi!(web_listen, |args: &Value| {
use std::collections::HashMap;
use std::path::PathBuf;
@@ -1564,7 +1791,7 @@ web_ffi!(web_listen, |args: &Value| {
None,
None,
None,
Vec::<(String, Vec<String>)>::new(),
Vec::<http::Gate>::new(),
HashMap::new(),
middleware::Middleware::default(),
cookie_secure,
@@ -1702,26 +1929,12 @@ web_ffi!(web_listen, |args: &Value| {
.map(|s| s.to_string());
let page_404 = app.get("page_404").cloned().filter(|v| !v.is_null());
let page_500 = app.get("page_500").cloned().filter(|v| !v.is_null());
let mut gates: Vec<(String, Vec<String>)> = Vec::new();
let mut gates: Vec<http::Gate> = Vec::new();
if let Some(arr) = app.get("gates").and_then(|v| v.as_array()) {
for g in arr {
let path = g
.get("path")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
if path.is_empty() {
continue;
if let Some(gate) = http::Gate::from_json(g) {
gates.push(gate);
}
let roles = match g.get("roles") {
Some(Value::Array(a)) => a
.iter()
.filter_map(|v| v.as_str().map(|s| s.to_ascii_lowercase()))
.collect(),
Some(Value::String(s)) => session::parse_roles_csv(s),
_ => vec!["admin".into()],
};
gates.push((path, roles));
}
}
let mut gallery_routes = HashMap::new();
@@ -1852,12 +2065,61 @@ web_ffi!(web_listen, |args: &Value| {
r
})
.collect();
let admin_cfg_app = args.get("app").cloned().unwrap_or_else(|| {
json!({
"admin": admin,
"admin_prefix": arg_str_opt(args, "admin_prefix").unwrap_or("/admin"),
"login_redirect": args.get("login_redirect").cloned().unwrap_or(Value::Null),
"logout_redirect": args.get("logout_redirect").cloned().unwrap_or(Value::Null),
})
});
let admin_prefix = app_admin_prefix(&admin_cfg_app);
let login_path = admin_cfg_app
.get("login_path")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| format!("{admin_prefix}/login"));
let login_redirect = admin_cfg_app
.get("login_redirect")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| admin_prefix.clone());
let logout_redirect = admin_cfg_app
.get("logout_redirect")
.and_then(|v| v.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
.unwrap_or_else(|| login_path.clone());
let app_shell = admin_cfg_app
.get("shell_css")
.or_else(|| admin_cfg_app.get("壳样式"))
.and_then(|v| v.as_str());
let app_layout = admin_cfg_app
.get("layout")
.or_else(|| admin_cfg_app.get("布局"))
.and_then(|v| v.as_str());
let app_asset_version = admin_cfg_app
.get("asset_version")
.or_else(|| admin_cfg_app.get("资源版本"))
.and_then(|v| v.as_str());
let mut page = page;
let mut routes = routes;
stamp_page_shell(&mut page, app_shell, app_layout, app_asset_version);
for (_k, p) in routes.iter_mut() {
stamp_page_shell(p, app_shell, app_layout, app_asset_version);
}
http::listen(
&page,
db_url.as_deref(),
&host,
port,
admin,
&admin_prefix,
&login_path,
&login_redirect,
&logout_redirect,
forms,
routes,
static_dir,
@@ -1915,7 +2177,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
}
let regs = [
("web_page_new", "title,intro", web_page_new as PluginFn),
(
"web_page_new",
"title,intro,shell_css,layout,asset_version",
web_page_new as PluginFn,
),
(
"web_compose_components",
"page,components",
@@ -2024,7 +2290,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_media_new", "storage", web_media_new as PluginFn),
(
"web_style",
"name,table",
"name,table,strict",
web_style as PluginFn,
),
(
@@ -2087,7 +2353,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_db_list_tables", "url", web_db_list_tables as PluginFn),
(
"web_app_new",
"page,db,admin,host,port",
"page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout,asset_version",
web_app_new as PluginFn,
),
("web_app_route", "app,path,page", web_app_route as PluginFn),
@@ -2136,8 +2402,8 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_auth_logout", "session_id", web_auth_logout as PluginFn),
("web_password_hash", "password", web_password_hash as PluginFn),
("web_auth_new", "users,session_ttl", web_auth_new as PluginFn),
("web_app_auth", "app,users,session_ttl", web_app_auth as PluginFn),
("web_app_gate", "app,path,roles", web_app_gate as PluginFn),
("web_app_auth", "app,users,session_ttl,admin_prefix,login_redirect,logout_redirect,login_path", web_app_auth as PluginFn),
("web_app_gate", "app,path,roles,match,on_deny,exclude", web_app_gate as PluginFn),
(
"web_app_gallery",
"app,path,storage,prefix,title,download_base",
+515 -95
View File
@@ -4,7 +4,10 @@ use serde_json::{json, Map, Value};
use crate::db;
use crate::markdown;
use crate::table::{as_bind, normalize_ref, normalize_slot, parse_site_path, project_rows, SitePath};
use crate::table::{
as_bind, as_nav_rows, nav_label_href, nav_media_when_class, normalize_ref, normalize_slot,
parse_site_path, project_rows, SitePath,
};
fn esc(s: &str) -> String {
s.replace('&', "&amp;")
@@ -58,71 +61,244 @@ fn is_db_bind_back(back: &str) -> bool {
}
}
fn resolve_links(raw: Option<&Value>, db_url: Option<&str>) -> Vec<(String, String)> {
#[derive(Clone, Debug)]
struct NavLink {
label: String,
href: String,
class: String,
media: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NavWhen {
Always,
Hide,
Auth,
Guest,
}
fn parse_nav_when(raw: &str) -> NavWhen {
let t = raw.trim();
if t.is_empty()
|| matches!(
t,
"*" | "always" | "Always" | "真" | "yes" | "on" | "show" | "all"
)
{
return NavWhen::Always;
}
if matches!(
t,
"hide" | "never" | "off" | "no" | "假" | "否" | "0" | "false" | "False"
) {
return NavWhen::Hide;
}
if matches!(
t,
"auth" | "user" | "登录" | "已登录" | "logged_in" | "logged-in"
) {
return NavWhen::Auth;
}
if matches!(
t,
"guest" | "anon" | "anonymous" | "访客" | "匿名" | "未登录"
) {
return NavWhen::Guest;
}
// Unknown token: keep visible (forward-compatible).
NavWhen::Always
}
/// `Some(true)` logged in, `Some(false)` guest, `None` unknown (do not filter auth/guest).
fn page_auth_state(page: Option<&Value>) -> Option<bool> {
let page = page?;
if let Some(v) = page
.get("_nav_user")
.or_else(|| page.get("user"))
.or_else(|| page.get("username"))
.or_else(|| page.get("_user"))
{
match v {
Value::Null => Some(false),
Value::Bool(b) => Some(*b),
Value::String(s) => Some(!s.trim().is_empty()),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
_ => Some(true),
}
} else if let Some(v) = page.get("_logged_in").or_else(|| page.get("logged_in")) {
match v {
Value::Bool(b) => Some(*b),
Value::String(s) => Some(matches!(
s.trim(),
"1" | "true" | "True" | "yes" | "on" | "真" | "是"
)),
Value::Number(n) => Some(n.as_i64().unwrap_or(0) != 0),
_ => None,
}
} else {
None
}
}
fn nav_when_visible(when: NavWhen, auth: Option<bool>) -> bool {
match when {
NavWhen::Always => true,
NavWhen::Hide => false,
NavWhen::Auth => auth.unwrap_or(true), // unknown → keep (compat)
NavWhen::Guest => match auth {
Some(logged_in) => !logged_in,
None => true,
},
}
}
fn resolve_links(raw: Option<&Value>, db_url: Option<&str>, page: Option<&Value>) -> Vec<NavLink> {
let Some(raw) = raw else {
return Vec::new();
};
let auth = page_auth_state(page);
let binds = as_bind(raw);
let arr = binds.as_array().cloned().unwrap_or_default();
if arr.is_empty() {
return Vec::new();
}
let has_db = arr
.iter()
.any(|b| b.get("back").and_then(|v| v.as_str()).is_some_and(is_db_bind_back));
if has_db {
let Some(url) = db_url else {
return Vec::new();
};
let table = crate::table::bind_table_name(&arr);
let Some(table) = table else {
return Vec::new();
};
let data = select_page_data(url, &table, raw, 200, 0);
let rows = data
.get("rows")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default();
let projected = project_rows(&arr, &rows);
let mut out = Vec::new();
for it in projected.as_array().cloned().unwrap_or_default() {
let m = it.as_object().cloned().unwrap_or_default();
let label = m
.get("title")
.or_else(|| m.get("label"))
.map(text)
.unwrap_or_default();
let href = m
.get("href")
.or_else(|| m.get("path"))
.map(text)
.unwrap_or_else(|| "#".into());
if !label.is_empty() {
out.push((label, href));
}
let rows: Vec<Map<String, Value>> = if !arr.is_empty() {
let has_db = arr
.iter()
.any(|b| b.get("back").and_then(|v| v.as_str()).is_some_and(is_db_bind_back));
if has_db {
let Some(url) = db_url else {
return Vec::new();
};
let table = crate::table::bind_table_name(&arr);
let Some(table) = table else {
return Vec::new();
};
let data = select_page_data(url, &table, raw, 200, 0);
let projected = project_rows(
&arr,
&data
.get("rows")
.and_then(|v| v.as_array())
.cloned()
.unwrap_or_default(),
);
projected
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.filter_map(|it| it.as_object().cloned())
.collect()
} else {
arr.into_iter()
.filter_map(|b| b.as_object().cloned())
.collect()
}
return out;
} else {
as_nav_rows(raw)
};
let mut out = Vec::new();
for m in rows {
let (label, href) = nav_label_href(&m);
if label.is_empty() {
continue;
}
let (media, when_raw, class) = nav_media_when_class(&m);
// DB-projected rows may use title/href without media keys on bind.
let when_raw = if when_raw.is_empty() {
m.get("when")
.or_else(|| m.get("当"))
.map(text)
.unwrap_or_default()
} else {
when_raw
};
let media = if media.is_empty() {
m.get("media")
.or_else(|| m.get("媒体"))
.map(text)
.unwrap_or_default()
} else {
media
};
let when = parse_nav_when(&when_raw);
if !nav_when_visible(when, auth) {
continue;
}
out.push(NavLink {
label,
href,
class,
media,
});
}
// static: front=label back=href (URLs with `.` must stay here)
arr.into_iter()
.map(|b| {
let label = b.get("front").map(text).unwrap_or_default();
let href = b.get("back").map(text).unwrap_or_else(|| "#".into());
(label, href)
})
.filter(|(l, _)| !l.is_empty())
.collect()
out
}
fn render_ul(links: &[(String, String)], class: &str) -> String {
fn nav_media_class_map(links: &[NavLink]) -> (String, Vec<(String, String)>) {
nav_media_class_map_many(&[links])
}
fn nav_media_class_map_many(groups: &[&[NavLink]]) -> (String, Vec<(String, String)>) {
let mut pairs: Vec<(String, String)> = Vec::new();
let mut css = String::new();
for links in groups {
for link in *links {
let media = link.media.trim();
if media.is_empty() || pairs.iter().any(|(m, _)| m == media) {
continue;
}
let class = format!("nav-mq-{}", pairs.len());
css.push_str(&format!(
"@media not {media} {{ li.{class} {{ display:none !important; }} }}\n"
));
pairs.push((media.to_string(), class));
}
}
(css, pairs)
}
fn render_ul(links: &[NavLink], class: &str) -> String {
let (_css, mq_pairs) = nav_media_class_map(links);
render_ul_with_mq(links, class, &mq_pairs)
}
fn render_ul_with_mq(links: &[NavLink], class: &str, mq_pairs: &[(String, String)]) -> String {
let mut s = format!("<ul class=\"{}\">", esc(class));
for (label, href) in links {
s.push_str(&format!(
"<li><a href=\"{}\">{}</a></li>",
esc(href),
esc(label)
));
for link in links {
let mq = link.media.trim();
let mq_class = if mq.is_empty() {
""
} else {
mq_pairs
.iter()
.find(|(m, _)| m == mq)
.map(|(_, c)| c.as_str())
.unwrap_or("")
};
let mut li_class = String::new();
if !link.class.is_empty() {
li_class.push_str(&link.class);
}
if !mq_class.is_empty() {
if !li_class.is_empty() {
li_class.push(' ');
}
li_class.push_str(mq_class);
}
if li_class.is_empty() {
s.push_str(&format!(
"<li><a href=\"{}\">{}</a></li>",
esc(&link.href),
esc(&link.label)
));
} else {
s.push_str(&format!(
"<li class=\"{}\"><a href=\"{}\">{}</a></li>",
esc(&li_class),
esc(&link.href),
esc(&link.label)
));
}
}
s.push_str("</ul>");
s
@@ -307,19 +483,35 @@ fn slot_class(args: &Value, slot: &str, base: &str) -> String {
}
}
const SHELL_CSS: &str = r#"
const SHELL_VARS: &str = r#"
:root { --ink:#1c1917; --muted:#57534e; --paper:#fafaf9; --line:#e7e5e4; --accent:#0f766e; }
body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; }
body { margin:0; font-family: "IBM Plex Sans", "Noto Sans SC", sans-serif; background:var(--paper); color:var(--ink); }
a { color:var(--ink); text-decoration:none; }
a:hover { color:var(--accent); }
"#;
const SHELL_LAYOUT: &str = r#"
body { display:grid; min-height:100vh; grid-template-rows:auto 1fr auto; }
body.has-sidebar { grid-template-columns:14rem 1fr; grid-template-areas:"top top" "side main" "foot foot"; }
body.no-sidebar { grid-template-areas:"top" "main" "foot"; }
@media (max-width:720px) {
body.has-sidebar { grid-template-columns:1fr; grid-template-areas:"top" "main" "foot" "side"; }
body.has-sidebar aside.side { border-right:0; border-top:1px solid var(--line); }
}
body.layout-stacked { display:flex; flex-direction:column; min-height:100vh; }
body.layout-stacked header.topnav, body.layout-stacked aside.side, body.layout-stacked main.main, body.layout-stacked footer.foot { width:100%; }
body.layout-stacked aside.side { border-right:0; border-bottom:1px solid var(--line); }
body.layout-bare { display:block; min-height:100vh; }
body.layout-bare main.main { padding:1.5rem 1.25rem 2rem; }
header.topnav { grid-area:top; border-bottom:1px solid var(--line); padding:.85rem 1.25rem; background:#fff; }
aside.side { grid-area:side; border-right:1px solid var(--line); padding:1.25rem 1rem; background:#f5f5f4; }
main.main { grid-area:main; padding:1.5rem 1.25rem 2rem; }
footer.foot { grid-area:foot; border-top:1px solid var(--line); padding:.85rem 1.25rem; color:var(--muted); background:#fff; }
ul.nav, ul.side-nav, ul.foot-nav { list-style:none; margin:0; padding:0; display:flex; flex-wrap:wrap; gap:.35rem 1rem; }
ul.side-nav { flex-direction:column; }
a { color:var(--ink); text-decoration:none; }
a:hover { color:var(--accent); }
"#;
const SHELL_WIDGETS: &str = r#"
.content.cards { display:grid; gap:1rem; margin-top:1.25rem; grid-template-columns:repeat(auto-fill,minmax(16rem,1fr)); }
.content.cards article { background:#fff; border:1px solid var(--line); border-radius:6px; padding:1rem; }
.main-intro h1 { margin:0 0 .75rem; font-size:2rem; }
@@ -349,6 +541,52 @@ a:hover { color:var(--accent); }
.pagination .page-status { color:var(--muted); }
"#;
fn normalize_shell_css(raw: &str) -> &'static str {
match raw.trim().to_ascii_lowercase().as_str() {
"" | "full" | "default" => "full",
"minimal" | "min" | "vars" => "minimal",
"off" | "none" | "false" | "0" => "off",
_ => "full",
}
}
fn shell_css_for(mode: &str) -> String {
match normalize_shell_css(mode) {
"off" => String::new(),
"minimal" => SHELL_VARS.to_string(),
_ => format!("{SHELL_VARS}{SHELL_LAYOUT}{SHELL_WIDGETS}"),
}
}
fn normalize_layout(raw: &str) -> String {
match raw.trim().to_ascii_lowercase().as_str() {
"" | "auto" | "default" => String::new(),
"sidebar" | "side" => "sidebar".into(),
"stacked" | "stack" | "column" => "stacked".into(),
"bare" | "main" | "none" => "bare".into(),
"rail" => "rail".into(),
other => other.to_string(),
}
}
fn resolve_shell_css(args: &Value) -> String {
let raw = args
.get("shell_css")
.or_else(|| args.get("壳样式"))
.and_then(|v| v.as_str())
.unwrap_or("full");
shell_css_for(raw)
}
fn resolve_layout(args: &Value) -> String {
let raw = args
.get("layout")
.or_else(|| args.get("布局"))
.and_then(|v| v.as_str())
.unwrap_or("");
normalize_layout(raw)
}
fn head_html(args: &Value, default_title: &str) -> String {
let meta = args.get("meta").and_then(|v| v.as_object());
let page_title = meta
@@ -407,7 +645,15 @@ fn head_html(args: &Value, default_title: &str) -> String {
}
if let Some(head) = args.get("head") {
let links = crate::assets::head_links_from_json(head);
s.push_str(&crate::assets::render_head_links(&links));
let asset_version = args
.get("asset_version")
.or_else(|| args.get("资源版本"))
.and_then(|v| v.as_str())
.unwrap_or("");
s.push_str(&crate::assets::render_head_links_with_version(
&links,
asset_version,
));
}
s
}
@@ -469,26 +715,58 @@ pub fn render_page_ex(
.get("title")
.and_then(|v| v.as_str())
.unwrap_or("Marqdo Web");
let extra = args
.get("styles_css")
.and_then(|v| v.as_str())
.unwrap_or("");
let shell = resolve_shell_css(args);
let layout = resolve_layout(args);
let parts = args
.get("parts")
.and_then(|v| v.as_object())
.cloned()
.unwrap_or_default();
let nav = resolve_links(args.get("nav"), db_url);
let side = resolve_links(args.get("sidebar"), db_url);
let foot = resolve_links(args.get("footer"), db_url);
let nav = resolve_links(args.get("nav"), db_url, Some(args));
let side = resolve_links(args.get("sidebar"), db_url, Some(args));
let foot = resolve_links(args.get("footer"), db_url, Some(args));
let (intro, items, total) = resolve_main(args, db_url);
let (nav_css, mq_pairs) = nav_media_class_map_many(&[&nav, &side, &foot]);
let extra_owned = {
let base = args
.get("styles_css")
.and_then(|v| v.as_str())
.unwrap_or("");
if nav_css.is_empty() {
base.to_string()
} else {
format!("{base}\n{nav_css}")
}
};
let extra = extra_owned.as_str();
let has_side = args.get("sidebar").is_some() || !side.is_empty();
let body_class = if has_side {
"has-sidebar"
} else {
"no-sidebar"
let bare = layout == "bare";
let body_class = match layout.as_str() {
"bare" => "layout-bare".to_string(),
"stacked" => "layout-stacked".to_string(),
"rail" => {
if has_side {
"has-rail has-sidebar".into()
} else {
"has-rail no-sidebar".into()
}
}
"sidebar" => {
if has_side {
"has-sidebar".into()
} else {
"no-sidebar".into()
}
}
"" => {
if has_side {
"has-sidebar".into()
} else {
"no-sidebar".into()
}
}
other => other.to_string(),
};
let mut main_html = String::new();
@@ -532,39 +810,61 @@ pub fn render_page_ex(
}
}
let style_block = if shell.is_empty() && extra.is_empty() {
String::new()
} else {
format!("<style>{shell}{extra}</style>")
};
let show_chrome = !bare;
let side_html = if show_chrome && has_side {
format!(
"<aside class=\"{}\"{}><span class=\"side-label\">侧栏</span>{}</aside>",
slot_class(args, "sidebar", "side"),
slot_attrs("sidebar", &parts, args),
render_ul_with_mq(&side, "side-nav", &mq_pairs)
)
} else {
String::new()
};
let header_html = if show_chrome {
format!(
"<header class=\"{}\"{}>{}</header>",
slot_class(args, "nav", "topnav"),
slot_attrs("nav", &parts, args),
render_ul_with_mq(&nav, "nav", &mq_pairs)
)
} else {
String::new()
};
let footer_html = if show_chrome {
format!(
"<footer class=\"{}\"{}>{}</footer>",
slot_class(args, "footer", "foot"),
slot_attrs("footer", &parts, args),
render_ul_with_mq(&foot, "foot-nav", &mq_pairs)
)
} else {
String::new()
};
format!(
r#"<!DOCTYPE html>
<html lang="zh-CN"><head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
{head}
<style>{SHELL_CSS}{extra}</style>
{style_block}
</head>
<body class="{body_class}">
<header class="{nav_class}"{nav_attrs}>{nav_ul}</header>
{header_html}
{side_html}
<main class="{main_class}"{main_attrs}>{main_html}</main>
<footer class="{foot_class}"{foot_attrs}>{foot_ul}</footer>
{footer_html}
</body></html>"#,
head = head_html(args, title),
nav_class = slot_class(args, "nav", "topnav"),
nav_attrs = slot_attrs("nav", &parts, args),
nav_ul = render_ul(&nav, "nav"),
side_html = if has_side {
format!(
"<aside class=\"{}\"{}><span class=\"side-label\">侧栏</span>{}</aside>",
slot_class(args, "sidebar", "side"),
slot_attrs("sidebar", &parts, args),
render_ul(&side, "side-nav")
)
} else {
String::new()
},
main_class = slot_class(args, "main", "main"),
main_attrs = slot_attrs("main", &parts, args),
foot_class = slot_class(args, "footer", "foot"),
foot_attrs = slot_attrs("footer", &parts, args),
foot_ul = render_ul(&foot, "foot-nav"),
)
}
@@ -577,21 +877,21 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
.unwrap_or_else(|| "main".into());
match slot.as_str() {
"nav" => {
let links = resolve_links(args.get("nav"), db_url);
let links = resolve_links(args.get("nav"), db_url, Some(args));
format!(
"<header class=\"topnav\" data-slot=\"nav\">{}</header>",
render_ul(&links, "nav")
)
}
"sidebar" => {
let links = resolve_links(args.get("sidebar"), db_url);
let links = resolve_links(args.get("sidebar"), db_url, Some(args));
format!(
"<aside class=\"side\" data-slot=\"sidebar\"><span class=\"side-label\">侧栏</span>{}</aside>",
render_ul(&links, "side-nav")
)
}
"footer" => {
let links = resolve_links(args.get("footer"), db_url);
let links = resolve_links(args.get("footer"), db_url, Some(args));
format!(
"<footer class=\"foot\" data-slot=\"footer\">{}</footer>",
render_ul(&links, "foot-nav")
@@ -704,3 +1004,123 @@ fn render_article(it: &Map<String, Value>) -> String {
s.push_str("</article>");
s
}
#[cfg(test)]
mod shell_tests {
use super::*;
use serde_json::json;
#[test]
fn shell_off_omits_sidebar_grid() {
let page = json!({
"title": "t",
"shell_css": "off",
"layout": "stacked",
"sidebar": [{"label": "A", "href": "/a"}],
});
let html = render_page(&page, None, None);
assert!(html.contains("layout-stacked"));
assert!(!html.contains("has-sidebar"));
assert!(!html.contains("grid-template-columns:14rem"));
}
#[test]
fn shell_minimal_keeps_vars_not_cards() {
let page = json!({ "title": "t", "shell_css": "minimal" });
let html = render_page(&page, None, None);
assert!(html.contains("--ink:"));
assert!(!html.contains(".content.cards article"));
assert!(!html.contains("grid-template-columns:14rem"));
}
#[test]
fn layout_bare_skips_aside() {
let page = json!({
"title": "t",
"layout": "bare",
"sidebar": [{"label": "A", "href": "/a"}],
"nav": [{"label": "Home", "href": "/"}],
});
let html = render_page(&page, None, None);
assert!(html.contains("layout-bare"));
assert!(!html.contains("<aside"));
assert!(!html.contains("<header"));
}
#[test]
fn default_full_keeps_sidebar_grid() {
let page = json!({
"title": "t",
"sidebar": [{"label": "A", "href": "/a"}],
});
let html = render_page(&page, None, None);
assert!(html.contains("has-sidebar"));
assert!(html.contains("grid-template-columns:14rem"));
}
}
#[cfg(test)]
mod nav_tests {
use super::*;
use serde_json::json;
#[test]
fn when_hide_omits_item() {
let page = json!({
"title": "t",
"shell_css": "off",
"nav": [
{"label": "Home", "href": "/"},
{"label": "Secret", "href": "/x", "when": "hide"},
],
});
let html = render_page(&page, None, None);
assert!(html.contains(">Home<"), "{html}");
assert!(!html.contains("/x"), "{html}");
}
#[test]
fn when_auth_guest_respects_logged_in() {
let nav = json!([
{"front": "Public", "back": "/"},
{"front": "Admin", "back": "/admin", "when": "auth"},
{"front": "Login", "back": "/login", "when": "guest"},
]);
let guest = json!({
"title": "t",
"shell_css": "off",
"_logged_in": false,
"nav": nav,
});
let g = render_page(&guest, None, None);
assert!(g.contains("/login"), "{g}");
assert!(!g.contains("/admin"), "{g}");
let user = json!({
"title": "t",
"shell_css": "off",
"_logged_in": true,
"_nav_user": "alice",
"nav": nav,
});
let u = render_page(&user, None, None);
assert!(u.contains("/admin"), "{u}");
assert!(!u.contains("/login"), "{u}");
}
#[test]
fn media_emits_class_and_css() {
let page = json!({
"title": "t",
"shell_css": "off",
"nav": [
{"label": "Wide", "href": "/w", "media": "(min-width: 900px)"},
{"label": "Home", "href": "/"},
],
});
let html = render_page(&page, None, None);
assert!(html.contains("nav-mq-0"), "{html}");
assert!(html.contains("@media not (min-width: 900px)"), "{html}");
assert!(html.contains(">Home<"), "{html}");
}
}
+174 -20
View File
@@ -14,6 +14,10 @@ const PROP_KEYS: &[&str] = &["属性", "property", "prop", "名", "name"];
const VAL_KEYS: &[&str] = &["值", "value"];
const SEL_KEYS: &[&str] = &["选择器", "selector", "sel"];
const MEDIA_KEYS: &[&str] = &["媒体", "media", "mq", "@media"];
const WHEN_KEYS: &[&str] = &["当", "when", "if", "条件", "visible"];
const NAV_LABEL_KEYS: &[&str] = &["标签", "label", "title", "text", "名"];
const NAV_HREF_KEYS: &[&str] = &["链接", "href", "url", "path", "地址"];
pub fn normalize_ref(s: &str) -> String {
let s = s.trim();
@@ -214,7 +218,7 @@ pub fn as_rows(table: &Value) -> Value {
}
}
/// Bind table → `[{front,back,css}, …]`
/// Bind table → `[{front,back,css,media,when}, …]`
pub fn as_bind(table: &Value) -> Value {
match table {
Value::Array(rows) => {
@@ -224,8 +228,17 @@ pub fn as_bind(table: &Value) -> Value {
let front = normalize_ref(&pick(m, FRONT_KEYS).map(cell_str).unwrap_or_default());
let back = normalize_ref(&pick(m, BACK_KEYS).map(cell_str).unwrap_or_default());
let css = normalize_ref(&pick(m, CSS_KEYS).map(cell_str).unwrap_or_default());
let media =
normalize_ref(&pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default());
let when = normalize_ref(&pick(m, WHEN_KEYS).map(cell_str).unwrap_or_default());
if !front.is_empty() || !back.is_empty() {
out.push(json!({ "front": front, "back": back, "css": css }));
out.push(json!({
"front": front,
"back": back,
"css": css,
"media": media,
"when": when,
}));
}
}
}
@@ -235,14 +248,24 @@ pub fn as_bind(table: &Value) -> Value {
let fronts = pick(m, FRONT_KEYS).map(as_str_list).unwrap_or_default();
let backs = pick(m, BACK_KEYS).map(as_str_list).unwrap_or_default();
let csses = pick(m, CSS_KEYS).map(as_str_list).unwrap_or_default();
let medias = pick(m, MEDIA_KEYS).map(as_str_list).unwrap_or_default();
let whens = pick(m, WHEN_KEYS).map(as_str_list).unwrap_or_default();
let n = fronts.len().max(backs.len());
let mut out = Vec::new();
for i in 0..n {
let front = normalize_ref(&fronts.get(i).cloned().unwrap_or_default());
let back = normalize_ref(&backs.get(i).cloned().unwrap_or_default());
let css = normalize_ref(&csses.get(i).cloned().unwrap_or_default());
let media = normalize_ref(&medias.get(i).cloned().unwrap_or_default());
let when = normalize_ref(&whens.get(i).cloned().unwrap_or_default());
if !front.is_empty() || !back.is_empty() {
out.push(json!({ "front": front, "back": back, "css": css }));
out.push(json!({
"front": front,
"back": back,
"css": css,
"media": media,
"when": when,
}));
}
}
Value::Array(out)
@@ -251,6 +274,61 @@ pub fn as_bind(table: &Value) -> Value {
}
}
/// Nav / link table → row maps with label/href (and optional media/when/class).
/// Accepts bind rows (`front`/`back`) or author tables (`标签`/`链接`).
pub fn as_nav_rows(table: &Value) -> Vec<Map<String, Value>> {
let binds = as_bind(table);
let bind_arr = binds.as_array().cloned().unwrap_or_default();
if !bind_arr.is_empty() {
return bind_arr
.into_iter()
.filter_map(|v| v.as_object().cloned())
.collect();
}
as_rows(table)
.as_array()
.cloned()
.unwrap_or_default()
.into_iter()
.filter_map(|v| v.as_object().cloned())
.collect()
}
/// Pick label/href from a nav row (bind or 标签/链接 shape).
pub fn nav_label_href(m: &Map<String, Value>) -> (String, String) {
let label = pick(m, NAV_LABEL_KEYS)
.or_else(|| m.get("front"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
let href = pick(m, NAV_HREF_KEYS)
.or_else(|| m.get("back"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "#".into());
(label, href)
}
pub fn nav_media_when_class(m: &Map<String, Value>) -> (String, String, String) {
let media = pick(m, MEDIA_KEYS)
.or_else(|| m.get("media"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
let when = pick(m, WHEN_KEYS)
.or_else(|| m.get("when"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
let class = pick(m, CSS_KEYS)
.or_else(|| m.get("css"))
.map(cell_str)
.map(|s| normalize_ref(&s))
.unwrap_or_default();
(media, when, class)
}
/// Page table → `[{src,style,slot}, …]`
pub fn as_compose(table: &Value) -> Value {
match table {
@@ -335,20 +413,30 @@ pub fn normalize_slot(name: &str) -> String {
/// | @keyframes pulse from | opacity | 0 |
/// ```
pub fn as_css_named(name: &str, table: &Value) -> String {
as_css_named_checked(name, table, false).unwrap_or_default()
}
/// Like [`as_css_named`], but when `strict` is true, reject cells that look like
/// T5 evaluated a bare `/` (numeric/bool CSS values). Default mode warns on stderr.
pub fn as_css_named_checked(name: &str, table: &Value, strict: bool) -> Result<String, String> {
let name = normalize_ref(name);
if name.is_empty() {
return String::new();
return Ok(String::new());
}
let mut out = String::new();
match table {
Value::Object(m) => {
let sels = pick(m, SEL_KEYS).map(as_str_list).unwrap_or_default();
let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default();
let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default();
let vals_raw = pick(m, VAL_KEYS);
let vals = vals_raw.map(as_str_list).unwrap_or_default();
let medias = pick(m, MEDIA_KEYS).map(as_str_list).unwrap_or_default();
let n = props.len().max(sels.len()).max(vals.len());
if n == 0 {
return String::new();
return Ok(String::new());
}
if let Some(raw) = vals_raw {
check_css_value_cells(raw, &props, strict)?;
}
let rows: Vec<(String, String, String, String)> = (0..n)
.map(|i| {
@@ -363,23 +451,68 @@ pub fn as_css_named(name: &str, table: &Value) -> String {
emit_css_rows(&rows, &name, &mut out);
}
Value::Array(rows) => {
let rows: Vec<(String, String, String, String)> = rows
.iter()
.filter_map(|row| {
let m = row.as_object()?;
Some((
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(),
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
))
})
.collect();
emit_css_rows(&rows, &name, &mut out);
let mut collected = Vec::new();
for row in rows {
let Some(m) = row.as_object() else {
continue;
};
let prop = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default();
if let Some(v) = pick(m, VAL_KEYS) {
note_css_value_cell(&prop, v, strict)?;
}
collected.push((
pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(),
pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(),
prop,
pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(),
));
}
emit_css_rows(&collected, &name, &mut out);
}
_ => {}
}
out
Ok(out)
}
fn css_value_suspicious(v: &Value) -> Option<&'static str> {
match v {
Value::Number(_) => Some(
"numeric CSS value (likely bare `/` division such as `1 / 5`; quote the cell, e.g. `\"1 / 5\"`)",
),
Value::Bool(_) => Some("boolean CSS value (quote the cell if intentional)"),
_ => None,
}
}
fn note_css_value_cell(prop: &str, val: &Value, strict: bool) -> Result<(), String> {
let Some(why) = css_value_suspicious(val) else {
return Ok(());
};
let prop = if prop.trim().is_empty() {
"(value)"
} else {
prop.trim()
};
let msg = format!("ext/web style: suspicious cell for `{prop}`: {why}");
if strict {
Err(msg)
} else {
eprintln!("warning: {msg}");
Ok(())
}
}
fn check_css_value_cells(vals: &Value, props: &[String], strict: bool) -> Result<(), String> {
match vals {
Value::Array(a) => {
for (i, v) in a.iter().enumerate() {
let prop = props.get(i).map(|s| s.as_str()).unwrap_or("");
note_css_value_cell(prop, v, strict)?;
}
}
other => note_css_value_cell(props.first().map(|s| s.as_str()).unwrap_or(""), other, strict)?,
}
Ok(())
}
/// Parse `@keyframes name` or `@keyframes name stop` from a selector cell.
@@ -742,4 +875,25 @@ mod css_tests {
assert!(css.contains(".x {"), "{css}");
assert!(css.contains("color: red;"), "{css}");
}
#[test]
fn strict_rejects_numeric_css_value() {
let t = json!([
{"选择器": ".x", "属性": "grid-column", "值": 0},
]);
let err = as_css_named_checked("x", &t, true).unwrap_err();
assert!(err.contains("suspicious"), "{err}");
// Non-strict still emits (with warning on stderr).
let css = as_css_named_checked("x", &t, false).unwrap();
assert!(css.contains("grid-column: 0;"), "{css}");
}
#[test]
fn quoted_string_ok_in_strict() {
let t = json!([
{"选择器": ".x", "属性": "grid-column", "值": "1 / 5"},
]);
let css = as_css_named_checked("x", &t, true).unwrap();
assert!(css.contains("grid-column: 1 / 5;"), "{css}");
}
}
+1 -1
View File
@@ -34,7 +34,7 @@ ext/llm — OpenAI-compatible chat. Design: doc/design/ext-llm.md
ext/agent — agent framework + native plugin. Design: doc/design/ext-agent.md
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 + W8**. **Browser embed (routes D/E/F, v0.3.3)**: `web.client_embed` auto-mounts WASM — zero author JS; `lib/browser` + GFM tables; build with `marqdo wasm build`; examples: browser-hello · browser-app · browser-media · web-client-site. Design: doc/design/ext-web.md · WASM: doc/adr/0002-browser-marqdo-wasm.md · roadmaps D/E/F.
ext/web — HTTP / SQLite·Postgres site helpers + native plugin. **W0–W7 + P3 + W8** + **customization C0–C4**. **Browser embed (routes D/E/F, v0.3.4)**: `web.client_embed` auto-mounts WASM — zero author JS; `lib/browser` + GFM tables; build with `marqdo wasm build`; examples: browser-hello · browser-app · browser-media · web-client-site. Design: doc/design/ext-web.md · WASM: doc/adr/0002-browser-marqdo-wasm.md · roadmaps D/E/F.
ext/quantum — circuits, draw, noise, formula matrix custom gates, Q7 density/viz, Q8 themed SVG (`theme=dark|light|bw`). Design: doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
+1 -1
View File
@@ -34,7 +34,7 @@ ext/llm(大模型)— OpenAI 兼容聊天。设计:doc/design/ext-llm.md
ext/agent(智能体)— 智能体框架 + 原生插件。设计:doc/design/ext-agent.md
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。**W0–W7 + P3 + W8**。**浏览器挂载(路线 D/E/F,v0.3.3)**:`网页.客户端挂载` / `web.client_embed` 自动 mount(作者零业务 JS);`lib/浏览器` + GFM;先 `marqdo wasm build`;示例 examples/browser-hello/ · examples/browser-app/ · examples/browser-media/ · examples/web-client-site/。设计:doc/design/ext-web.md · WASM:doc/adr/0002-browser-marqdo-wasm.md · 路线 D/E/F:doc/roadmap/browser-wasm-*.md
ext/web(网页)— HTTP / SQLite 站点助手 + 原生插件。**W0–W7 + P3 + W8** + **定制 C0–C4**。**浏览器挂载(路线 D/E/F,v0.3.4)**:`网页.客户端挂载` / `web.client_embed` 自动 mount(作者零业务 JS);`lib/浏览器` + GFM;先 `marqdo wasm build`;示例 examples/browser-hello/ · examples/browser-app/ · examples/browser-media/ · examples/web-client-site/。设计:doc/design/ext-web.md · WASM:doc/adr/0002-browser-marqdo-wasm.md · 路线 D/E/F:doc/roadmap/browser-wasm-*.md
ext/quantum(量子)— 电路、绘图、噪声、公式矩阵自定义门、Q7 密度/高级图、Q8 主题 SVG(`主题=dark|light|bw`)。设计:doc/design/ext-quantum.md · doc/design/ext-quantum-viz-style.md
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Wave B1 — offline constitution / OKF harness (no network required).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
MQ="${MARQDO_BIN:-$ROOT/target/release/marqdo}"
export MARQDO_EXT="${MARQDO_EXT:-$ROOT/.marqdo-ext}"
export MARQDO_AGENT_PLUGIN="${MARQDO_AGENT_PLUGIN:-$ROOT/.marqdo-ext/native/libagent.so}"
if [[ ! -x "$MQ" ]]; then
echo "missing $MQ — run: cargo build --release -p marqdo -p marqdo_plugin_agent" >&2
exit 1
fi
fail=0
run() {
local f="$1"
echo "==> $f"
if ! "$MQ" run "$f"; then
echo "FAIL $f" >&2
fail=1
fi
}
run tests/ext/agent-constitution-b0.mq.md
run tests/ext/agent-dump-context.mq.md
run tests/ext/agent-writeback-shadow.mq.md
run tests/ext/agent-kb-plan-hit.mq.md
run tests/ext/agent-context-budget-a3.mq.md
run tests/ext/agent-workbook-patch-a0.mq.md
run examples/agent-okf-flywheel/index.mq.md
run examples/agent-pong/index.mq.md
if [[ "${AGENT_HARNESS_LIVE:-}" == "1" ]]; then
export AGENT_LIVE=1
if [[ ! -f "$ROOT/.env" ]]; then
echo "AGENT_HARNESS_LIVE=1 needs repo-root .env (see .env.example)" >&2
exit 1
fi
run examples/agent-pong/index.mq.md
run tests/ext/agent-run-live.mq.md
fi
if [[ "$fail" -ne 0 ]]; then
echo "agent harness: FAILED" >&2
exit 1
fi
echo "agent harness: OK"
+19 -5
View File
@@ -16,9 +16,9 @@ Marqdo = **Markdown markers as syntax**. A `.mq.md` file is both documentation a
Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.md`. Deeper tables: [reference.md](reference.md). Copy-paste patterns: [examples.md](examples.md).
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[`.cursor/skills/marqdo-dev/SKILL.md`](../../.cursor/skills/marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Authoring / library craft** (GFM-first, no json glue, how to develop Marqdo): use **[marqdo-dev](../marqdo-dev/SKILL.md)** whenever writing or refactoring `.mq.md`, `lib/*`, or `ext/*`.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [`.cursor/skills/marqdo-release/SKILL.md`](../../.cursor/skills/marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
**Product release** (tag, CHANGELOG, README, public docs, VSIX, GitHub assets): use [marqdo-release](../marqdo-release/SKILL.md) — detect latest version, **ask the user for the next SemVer**, then follow that playbook. Do not invent a version number.
## Hard rules (do not violate)
@@ -31,7 +31,7 @@ Canonical design (repo): `doc/design/markdown-mapping.md`, `doc/design/keywords.
7. **Paths:** In bare *expressions* `/` is division. In **call args / param defaults / table cells**, unspaced `a/b` and quoted `".marqdo/agent-kb"` are path text — no `json.parse` needed. Numeric ratios that must stay text use quotes (`"1/5"`, `"16/9"`); bare `1/5` is division.
8. Prefer ending side-effect-only function bodies with a lone `---` or `***` line (or `****` empty return) so later siblings are not swallowed.
9. **`ext/**` never calls `host_*`.** Agent/OKF helpers are plugin names (`agent_kb_*`, …) after `plugin.load`. Do **not** add agent/OKF domain code to `src/host/` (core bloat). See `doc/design/ext-agent.md` §4.
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([`.cursor/skills/marqdo-dev/SKILL.md`](../../.cursor/skills/marqdo-dev/SKILL.md)).
10. **Browser (route C/D/E/F):** client logic is Marqdo on WASM; official bridge is host glue and **may** implement lists, routing, storage, WebSocket, canvas, file read, observers — authors **must not hand-write business JS**. Use `web.client_embed` / `data-mq-source-url` auto-mount. Client effects: prefer **GFM tables + `lib/browser`** ([marqdo-dev](../marqdo-dev/SKILL.md)).
11. **Code-as-documentation / no bag glue:** Prefer **GFM tables** for maps, lists, wire, commands. Prefer **`table.put` / named helpers** over `json.set` / `json.append` chains. `lib/json` is for parse/stringify/quote only — not a dict builder. Unreadable json pipelines are a style bug.
@@ -141,13 +141,27 @@ import clock:lib/time.mq.md
- Instance methods stay `` > `obj`.method `` (backticks on the receiver only).
- `lib/…` resolves via `MARQDO_LIB`, cwd `lib/`, or `lib/` next to the `marqdo` binary.
- Design: [module-namespace.md](../../doc/design/module-namespace.md).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; `ext/agent` — document-driven agents: **step** (default writeback) / **plan** workbook ([ext-agent.md](../../doc/design/ext-agent.md), [ext-agent-plan.md](../../doc/design/ext-agent-plan.md)); **`ext/web`** — dynamic sites (W0–W7 + P3 complete; see below); **`ext/quantum`** — circuits + Q7 density/viz + Q8 themed SVG (see below).
- Official optional extensions (`ext/`, not stdlib): install with `marqdo ext add llm|agent|web|quantum` (see `doc/design/ext-cli.md`). `ext/llm` — chat; **`ext/agent`** — document-driven agents (see **ext/agent** below); **`ext/web`** — dynamic sites (see below); **`ext/quantum`** — circuits + Q7/Q8 (see below).
- Native plugins: `lib/plugin` — `## load` / `unload` / `list`. C ABI: `include/marqdo_abi.h`.
- Prefer `table.put` / `表.改` for list/map element updates; keep `json` for parse/stringify/quote (see `doc/design/stdlib-table.md`).
- Builtins (no import): `print`/`打印`, `input`/`输入`, `len`/`长度`, `str`/`文本`, `int`/`整数`; literals `True`/`真`, `False`/`假`, `None`/`空`; logic `and`/`且`, `or`/`或`, `not`/`非`.
Stdlib map: [reference.md](reference.md).
## Official extension: `ext/agent` (document-driven)
Install: `marqdo ext add agent` (ZH: `智能体`). Native: `cargo build --release -p marqdo_plugin_agent`.
**Constitution (do not dilute):**
1. **Code is documentation** — the runbook `.mq.md` is the model’s ground truth, not a hidden system prompt bag.
2. **Call site is first-class** — `build_step_context` injects path/function/line so the model knows where it is in the program.
3. **Document is the knowledge base (OKF)** — writeback → promote/solidify → reuse / `llm_free`; MCP/corpus are evidence only.
APIs: `# agent` / `# 智能体` → `## step` / `## plan`. Context: standing + task + **call site** + tools + budgeted source/skill + act protocol (`CALL:` / `READ:`).
Examples: [agent-pong](../../examples/agent-pong/) · [agent-okf-flywheel](../../examples/agent-okf-flywheel/). Harness: `scripts/agent-harness.sh`. Design: [ext-agent.md](../../doc/design/ext-agent.md) · Wave B: [agent-framework-2026-09.md](../../doc/research/agent-framework-2026-09.md). Dev LLM: copy [.env.example](../../.env.example) → `.env` (gitignored).
## Official extension: `ext/web` (dynamic sites)
Install: `marqdo ext add web` (ZH id: `网页`). Build native plugin first: `cargo build --release -p marqdo_plugin_web`.
@@ -234,7 +248,7 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
| Import `lib/text` then call `拆分` | Match file language (`text.split`, not 文本) |
| `json.set` / `json.append` to build maps or lists | GFM tables; sparse `table.put`; named helpers (`browser.*`, `web.*`) |
| `json.set` to build page parts | GFM tables + `page.compose_*` / `web.page` methods |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([`.cursor/skills/marqdo-dev/SKILL.md`](../../.cursor/skills/marqdo-dev/SKILL.md)) |
| Import `json` for every browser handler | `import browser:lib/browser.mq.md` + tables ([marqdo-dev](../marqdo-dev/SKILL.md)) |
| Mix `web.page` and `网页.页面` in one file | One import language per `.mq.md` |
| Call `host_web_*` from `ext/web` | Use `# app` / `# db` methods; plugin ABI only |
| Call `host_*` from `ext/quantum` | Use `# circuit` / `# density` methods; plugin ABI only |
+1 -1
View File
@@ -54,7 +54,7 @@ Import one file; use **that** file’s function names.
| `lib/math.mq.md` | `lib/数学.mq.md` | num, trig, random, formula, plot |
| `lib/foreign.mq.md` | `lib/外联.mq.md` | run foreign fenced blocks |
| `ext/llm.mq.md` | `ext/大模型.mq.md` | `# llm` / `# 大模型` object + chat methods |
| `ext/agent.mq.md` | `ext/智能体.mq.md` | agent **framework** (layout now; LLM orchestration roadmap in `ext-agent.md`) |
| `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 |
+68
View File
@@ -0,0 +1,68 @@
---
title: agent constitution markers (Wave B1 offline)
description: Assert call_site / source / protocol order in build_step_context.
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
## probe_tool
**"probe-ok"**
# main
*p = > plugin.native_path name="agent"*
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
> sys.env_set name="OPENAI_API_KEY" value="offline-constitution-dummy"
*model = > llm.llm*
`工具表` =
| 工具 |
|------|
| probe_tool |
*助手 = > agent.agent model=`model` tools=`工具表` standing="constitution probe"*
*ctx = > agent.build_step_context agent=`助手` task="constitution-probe-task"*
*a = > split value=`ctx` sep="--- call site ---"*
*b = > split value=`ctx` sep="--- source (.mq.md) ---"*
*c = > split value=`ctx` sep="--- how to act ---"*
*d = > split value=`ctx` sep="Code is documentation"*
*na = > len value=`a`*
*nb = > len value=`b`*
*nc = > len value=`c`*
*nd = > len value=`d`*
1. `na` > 1
1. `nb` > 1
1. `nc` > 1
1. `nd` > 1
> print text=constitution-ok
2. *
> print text=motto-missing
> sys.exit code=1
2. *
> print text=act-missing
> sys.exit code=1
2. *
> print text=source-missing
> sys.exit code=1
2. *
> print text=call-site-missing
> sys.exit code=1
*site = > agent_call_site*
*path = > json.get value=`site` key="path"*
1. `path`
> print text=site-path-ok
2. *
> print text=site-path-missing
> sys.exit code=1
+54
View File
@@ -0,0 +1,54 @@
---
title: dump_step_context (Wave B1 offline)
description: Assert dump_step_context exposes call_site + prompt without LLM.
import llm:ext/ai/llm.mq.md
import agent:ext/ai/agent.mq.md
import json:lib/json.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
## probe_tool
**"probe-ok"**
# main
*p = > plugin.native_path name="agent"*
1. `p`
> plugin.load path=`p`
2. *
> print text=no-agent-plugin
> sys.exit code=1
> sys.env_set name="OPENAI_API_KEY" value="offline-dump-dummy"
*model = > llm.llm*
`工具表` =
| 工具 |
|------|
| probe_tool |
*助手 = > agent.agent model=`model` tools=`工具表` standing="dump probe"*
*dump = > agent.dump_step_context agent=`助手` task="dump-probe-task"*
*site = > json.get value=`dump` key="call_site"*
*path = > json.get value=`site` key="path"*
*chars = > json.get value=`dump` key="prompt_chars"*
*prompt = > json.get value=`dump` key="prompt"*
1. `path`
1. `chars` > 100
*parts = > split value=`prompt` sep="--- call site ---"*
*n = > len value=`parts`*
1. `n` > 1
> print text=dump-context-ok
2. *
> print text=dump-prompt-missing-site
> sys.exit code=1
2. *
> print text=dump-chars-too-small
> sys.exit code=1
2. *
> print text=dump-site-path-missing
> sys.exit code=1
+1 -1
View File
@@ -16,7 +16,7 @@ import agent:ext/ai/agent.mq.md
# main
> llm.load_env path=.env
> llm.load_env path="../../.env"
*模型 = > llm.llm*
+42
View File
@@ -0,0 +1,42 @@
---
title: writeback param must not shadow host_writeback_record
description: Regression — step/plan param writeback=True used to break > writeback.record (bool is not a map).
import writeback:lib/writeback.mq.md
import json:lib/json.mq.md
import sys:lib/sys.mq.md
---
# box
+ `writeback`=False
## go
+ `writeback`=False
Mimic agent.step: branch on param named writeback, then persist via host (not import bind).
*out = > json.parse text={"status":"ok","note":"shadow-probe"}*
1. `writeback`
*body = > json.stringify value=`out`*
*st = > json.get value=`out` key="status"*
1. `st` == "ok"
> host_writeback_record value=`body` key="ok"
2. *
> host_writeback_record value=`body` key="error"
2. *
*_ = 1*
****
# main
*b = > box*
> `b`.go writeback=True
<!-- marqdo-out ok
{"note":"shadow-probe","status":"ok"}
-->
*cached = > writeback.get key="ok"*
1. `cached`
> print text=writeback-shadow-ok
2. *
> print text=writeback-shadow-missing
> sys.exit code=1
+72
View File
@@ -0,0 +1,72 @@
---
title: web C0 admin prefix / route release
description: admin=False frees /admin; custom admin_prefix reserves only that mount.
import web:ext/web/web.mq.md
import json:lib/json.mq.md
import sys:lib/sys.mq.md
---
# main
*首页 = > web.page title="home"*
*页 = > web.page title="news"*
*应用 = > web.app page=`首页` admin=False*
*应用 = > `应用`.route path="/admin/news" page=`页`*
*routes = > json.get value=`应用` key="routes"*
*hit = > json.get value=`routes` key="/admin/news"*
1. `hit`
> print text=free-admin-ok
2. *
> print text=free-admin-fail
> sys.exit code=1
*应用3 = > web.app page=`首页` admin=True admin_prefix="/desk"*
*应用3 = > `应用3`.route path="/admin/news" page=`页`*
*routes3 = > json.get value=`应用3` key="routes"*
*hit3 = > json.get value=`routes3` key="/admin/news"*
1. `hit3`
> print text=prefix-frees-admin-ok
2. *
> print text=prefix-frees-admin-fail
> sys.exit code=1
*prefix = > json.get value=`应用3` key="admin_prefix"*
1. `prefix` == "/desk"
> print text=prefix-stored-ok
2. *
> print text=prefix-stored-fail
> sys.exit code=1
`用户表` =
| 用户名 | 密码 | 角色 |
|--------|------|------|
| admin | secret | admin |
*应用4 = > web.app page=`首页` admin=True*
*应用4 = > `应用4`.auth users=`用户表` admin_prefix="/desk" login_redirect="/desk" logout_redirect="/desk/login"*
*prefix4 = > json.get value=`应用4` key="admin_prefix"*
*login4 = > json.get value=`应用4` key="login_redirect"*
*logout4 = > json.get value=`应用4` key="logout_redirect"*
*gates = > json.get value=`应用4` key="gates"*
*g0 = > at value=`gates` index=0*
*gpath = > json.get value=`g0` key="path"*
1. `prefix4` == "/desk"
1. `login4` == "/desk"
1. `logout4` == "/desk/login"
1. `gpath` == "/desk"
> print text=auth-prefix-ok
2. *
> print text=auth-gate-fail
> sys.exit code=1
2. *
> print text=auth-logout-fail
> sys.exit code=1
2. *
> print text=auth-login-fail
> sys.exit code=1
2. *
> print text=auth-prefix-fail
> sys.exit code=1
> print text=c0-admin-ok
+81
View File
@@ -0,0 +1,81 @@
---
title: web C1 gate match / on_deny / exclude
description: Segment-boundary prefix; auth default redirect; custom gate fields.
import web:ext/web/web.mq.md
import json:lib/json.mq.md
import sys:lib/sys.mq.md
---
# main
*首页 = > web.page title="home"*
`用户表` =
| 用户名 | 密码 | 角色 |
|--------|------|------|
| admin | secret | admin |
*应用 = > web.app page=`首页` admin=True*
*应用 = > `应用`.auth users=`用户表`*
*gates = > json.get value=`应用` key="gates"*
*g0 = > at value=`gates` index=0*
*path = > json.get value=`g0` key="path"*
*match = > json.get value=`g0` key="match"*
*deny = > json.get value=`g0` key="on_deny"*
*login = > json.get value=`应用` key="login_path"*
1. `path` == "/admin"
1. `match` == "prefix"
1. `deny` == "redirect"
1. `login` == "/admin/login"
> print text=auth-default-gate-ok
2. *
> print text=login-path-fail
> sys.exit code=1
2. *
> print text=on-deny-fail
> sys.exit code=1
2. *
> print text=match-fail
> sys.exit code=1
2. *
> print text=path-fail
> sys.exit code=1
*应用2 = > web.app page=`首页` admin=False*
*应用2 = > `应用2`.gate path="/desk" roles="admin" match="prefix" on_deny="redirect" exclude="/desk/login"*
*gates2 = > json.get value=`应用2` key="gates"*
*g1 = > at value=`gates2` index=0*
*p2 = > json.get value=`g1` key="path"*
*m2 = > json.get value=`g1` key="match"*
*d2 = > json.get value=`g1` key="on_deny"*
*ex = > json.get value=`g1` key="exclude"*
1. `p2` == "/desk"
1. `m2` == "prefix"
1. `d2` == "redirect"
1. `ex`
> print text=custom-gate-ok
2. *
> print text=exclude-fail
> sys.exit code=1
2. *
> print text=custom-deny-fail
> sys.exit code=1
2. *
> print text=custom-match-fail
> sys.exit code=1
2. *
> print text=custom-path-fail
> sys.exit code=1
*应用3 = > web.app page=`首页` admin=False*
*应用3 = > `应用3`.gate path="/write*" roles="admin,author"*
*gates3 = > json.get value=`应用3` key="gates"*
*g3 = > at value=`gates3` index=0*
*p3 = > json.get value=`g3` key="path"*
1. `p3`
> print text=star-gate-ok
2. *
> print text=star-gate-fail
> sys.exit code=1
> print text=c1-gate-ok
+60
View File
@@ -0,0 +1,60 @@
---
title: web C2 shell_css + layout
description: Offline render markers for shell modes and layouts.
import web:ext/web/web.mq.md
import json:lib/json.mq.md
import sys:lib/sys.mq.md
---
# main
`链` =
| 标签 | 链接 |
|------|------|
| Home | / |
| Desk | /desk |
*页 = > web.page title="c2" shell_css="off" layout="stacked"*
*页 = > json.set map=`页` key="nav" value=`链`*
*页 = > json.set map=`页` key="sidebar" value=`链`*
*html = > `页`.render*
*a = > split value=`html` sep="layout-stacked"*
*na = > len value=`a`*
*b = > split value=`html` sep="has-sidebar"*
*nb = > len value=`b`*
*c = > split value=`html` sep="grid-template-columns:14rem"*
*nc = > len value=`c`*
1. `na` > 1
1. `nb` == 1
1. `nc` == 1
> print text=stacked-off-ok
2. *
> print text=grid-still-present
> sys.exit code=1
2. *
> print text=has-sidebar-leak
> sys.exit code=1
2. *
> print text=stacked-missing
> sys.exit code=1
*裸 = > web.page title="bare" layout="bare" shell_css="minimal"*
*裸 = > json.set map=`裸` key="nav" value=`链`*
*裸 = > json.set map=`裸` key="sidebar" value=`链`*
*h2 = > `裸`.render*
*d = > split value=`h2` sep="<aside"*
*nd = > len value=`d`*
*e = > split value=`h2` sep="--ink:"*
*ne = > len value=`e`*
1. `nd` == 1
1. `ne` > 1
> print text=bare-minimal-ok
2. *
> print text=minimal-vars-missing
> sys.exit code=1
2. *
> print text=bare-aside-leak
> sys.exit code=1
> print text=c2-shell-ok
+91
View File
@@ -0,0 +1,91 @@
---
title: web C3 style strict + head defer/version
description: Offline markers for quoted CSS cells and head script lifecycle.
import web:ext/web/web.mq.md
import sys:lib/sys.mq.md
---
# main
`好` =
| 选择器 | 属性 | 值 |
|--------|------|-----|
| .box | grid-column | "1 / 5" |
*css = > web.make_style name="t" table=`好` strict=True*
*a = > split value=`css` sep="1 / 5"*
*na = > len value=`a`*
1. `na` > 1
> print text=quoted-css-ok
2. *
> print text=quoted-css-missing
> sys.exit code=1
`头` =
| 关系 | 地址 | 推迟 | 版本 |
|------|------|------|------|
| script | /static/a.js | 真 | 3 |
| stylesheet | /static/t.css | | 1 |
*页 = > web.page title="c3" asset_version="appv"*
*页 = > `页`.head table=`头`*
*html = > `页`.render*
*b = > split value=`html` sep="a.js?v=3"*
*nb = > len value=`b`*
*c = > split value=`html` sep="t.css?v=1"*
*nc = > len value=`c`*
*d0 = > split value=`html` sep="script defer"*
*nd0 = > len value=`d0`*
1. `nb` > 1
1. `nc` > 1
1. `nd0` > 1
> print text=defer-version-ok
2. *
> print text=defer-attr-missing
> sys.exit code=1
2. *
> print text=css-version-missing
> sys.exit code=1
2. *
> print text=defer-script-missing
> sys.exit code=1
`头2` =
| 关系 | 地址 | 推迟 |
|------|------|------|
| script | /static/b.js | 真 |
*页2 = > web.page title="c3b" asset_version="2026-09-04"*
*页2 = > `页2`.head table=`头2`*
*h2 = > `页2`.render*
*d = > split value=`h2` sep="b.js?v=2026-09-04"*
*nd = > len value=`d`*
1. `nd` > 1
> print text=asset-version-ok
2. *
> print text=asset-version-missing
> sys.exit code=1
`头3` =
| 关系 | 地址 |
|------|------|
| script | /static/sync.js |
*页3 = > web.page title="c3c"*
*页3 = > `页3`.head table=`头3`*
*h3 = > `页3`.render*
*e = > split value=`h3` sep="sync.js"*
*ne = > len value=`e`*
*f = > split value=`h3` sep="script defer"*
*nf = > len value=`f`*
1. `ne` > 1
1. `nf` == 1
> print text=sync-compat-ok
2. *
> print text=unexpected-defer
> sys.exit code=1
2. *
> print text=sync-script-missing
> sys.exit code=1
> print text=c3-style-head-ok
+75
View File
@@ -0,0 +1,75 @@
---
title: web C4 conditional nav when/media
description: Offline render markers for nav when= and media= columns.
import web:ext/web/web.mq.md
import table:lib/table.mq.md
import sys:lib/sys.mq.md
---
# main
`链` =
| 属性 | 值 | 样式 | 媒体 | 当 |
|------|-----|------|------|-----|
| Home | / | | | |
| Desk | /desk | | (max-width: 720px) | |
| Admin | /admin | | | auth |
| Login | /login | | | guest |
| Gone | /gone | | | hide |
*客 = > web.page title="c4-guest" shell_css="off"*
*`客` = > table.put in=`客` at="nav" value=`链`*
*`客` = > table.put in=`客` at="_logged_in" value=False*
*hg = > `客`.render*
*a = > split value=`hg` sep="/login"*
*na = > len value=`a`*
*b = > split value=`hg` sep="/admin"*
*nb = > len value=`b`*
*c = > split value=`hg` sep="/gone"*
*nc = > len value=`c`*
*d = > split value=`hg` sep="nav-mq-0"*
*nd = > len value=`d`*
*e = > split value=`hg` sep="@media not (max-width: 720px)"*
*ne = > len value=`e`*
1. `na` > 1
1. `nb` == 1
1. `nc` == 1
1. `nd` > 1
1. `ne` > 1
> print text=guest-media-ok
2. *
> print text=media-css-missing
> sys.exit code=1
2. *
> print text=media-class-missing
> sys.exit code=1
2. *
> print text=hide-leaked
> sys.exit code=1
2. *
> print text=auth-leaked-for-guest
> sys.exit code=1
2. *
> print text=guest-login-missing
> sys.exit code=1
*户 = > web.page title="c4-user" shell_css="off"*
*`户` = > table.put in=`户` at="nav" value=`链`*
*`户` = > table.put in=`户` at="_logged_in" value=True*
*hu = > `户`.render*
*f = > split value=`hu` sep="/admin"*
*nf = > len value=`f`*
*g = > split value=`hu` sep="/login"*
*ng = > len value=`g`*
1. `nf` > 1
1. `ng` == 1
> print text=auth-ok
2. *
> print text=guest-leaked-for-user
> sys.exit code=1
2. *
> print text=auth-admin-missing
> sys.exit code=1
> print text=c4-nav-ok
+2 -2
View File
@@ -11,8 +11,8 @@ import json:lib/json.mq.md
+ `value`
+ `line`
> writeback.ensure key=ok placeholder=pending line=`line`
> writeback.ensure key=error placeholder=pending line=`line`
> writeback.ensure key="ok" placeholder="pending" line=`line`
> writeback.ensure key="error" placeholder="pending" line=`line`
> writeback.record value=`value` key=`key` line=`line`
****