Compare commits

..
Author SHA1 Message Date
cflmy f89b2dd81e feat: show release notes and official download in update check
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
Continue app-harness#16 goal 4: the application update check now displays the
trusted release metadata a user needs to decide.

- release/gitea.ts reads the trusted Gitea release body (truncated to 8 KiB)
  into the candidate alongside the already-validated manifest/asset.
- UpdateCandidate gains notes and release_url; UpdateState.latest persists both.
- mqdh update check text output adds published/download/release URL/known limits
  and release notes; JSON already carries the same fields.
- DISTRIBUTION documents the fields; RELEASING names the Gitea release body as
  the single source of release notes (no second list).
- updater.test.ts fake release carries a body and asserts notes/release_url.

Verified locally: updater tests 3/3, all downstream node tests 77 pass/3
skipped, typecheck 5/5. No release/tag; full ecosystem latest-version view and
E09 notification/reconciliation remain UNVERIFIED.
2026-11-30 21:57:22 +08:00
cflmy eceb13a70a Merge pull request #19 from codex/issue-16-status-view
ci/woodpecker/push/ci Pipeline was successful
feat: read-only mqdh status ecosystem view (#16 slice)
2026-11-30 20:44:29 +08:00
cflmy fd1d129e00 feat: add a read-only mqdh status ecosystem view
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
Start the app-harness#16 version-visibility slice with `mqdh status [--json]`:
one read-only report of the application version/home/workspace, platform and
Node, ecosystem candidate/version, Bundle version/modules/digest, installed tool
versions, market/knowledge counts and the privacy constants. JSON uses the
stable schema marqdo.mqdh.status.

The launcher product-command set and HELP include status; ARCHITECTURE records
the command. The CLI test covers JSON and text output for an empty install and
asserts the honest "not installed"/false values. This is not the full latest
version/release-notes/download view from #16; that remains UNVERIFIED.

Verified locally: all downstream node tests 77 pass/3 skipped; typecheck gates
5/5 pass.
2026-11-30 20:21:33 +08:00
cflmy a1517652c2 Merge pull request #18 from codex/issue-15-entry-polish
ci/woodpecker/push/ci Pipeline was successful
docs: wrap-standard polish for the product entry (#15)
2026-11-30 20:19:26 +08:00
cflmy 3e76e3df89 docs: satisfy the wrap standard for the product entry
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
Follow up the product entry (#15 P1/P2): make docs/mqdh/index.mq.md and its
evidence one physical line per paragraph, and record the real documentation-gate
baseline. pnpm run test:docs fails on this downstream fork for pre-existing
docs/mqdh files (missing bilingual counterparts, wrap rules); the entry is not
the only offender and doc-sync remains UNVERIFIED rather than claimed PASS.

Add STATUS S11 (PASS (this repo)) for the entry itself: it exists, the docs list
points at it, its 39 relative links were checked, and upstream isolation / the
STATUS authority / security invariants are visible. The S11 note keeps the
doc-gate baseline failure explicit.
2026-11-30 19:42:50 +08:00
cflmy 6c84ad4f1d Merge pull request #17 from codex/issue-15-product-entry
ci/woodpecker/push/ci Pipeline was successful
docs: product-level AI-readable entry (#15 P1/P2)
2026-11-30 19:19:51 +08:00
cflmy 240956ecae docs: add the product-level AI-readable entry
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
Implement the P1/P2 slice of marqdo-app-harness#15: create the single
product-level entry docs/mqdh/index.mq.md and point the docs list at it.

The entry states the product positioning and non-goals, the upstream
isolation rule (upstream DSH docs are not product spec; every upstream
modification goes to upstream-delta.md), the architecture and capability maps
with authoritative docs + real implementation directories, a task navigation
table with real verification commands, the security invariants (0600
credentials, single controlled egress, one-shot approval, no Marqdo source
copies, MQDH_HOME/install-tree separation), and the real acceptance entries.
It links STATUS.md as the only current-state matrix and does not copy domain
prose or add a second documentation system.

Evidence: docs/mqdh/evidence/2026-11-30-product-entry.md. Local verification:
all 39 relative links resolve; the downstream harness node --test suite passes
(0 fail, 2 skipped). No upstream file changed; no new metadata syntax.
2026-11-30 18:58:32 +08:00
cflmy 2aab24cccf docs: record the catalog empty-home negative
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/push/ci Pipeline was successful
2026-11-29 12:52:51 +08:00
cflmy 86c10416dd docs: record the five-group ecosystem catalog browser evidence
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
2026-11-29 12:39:44 +08:00
cflmy 56ff79cf01 docs: record reader candidate CI evidence
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was canceled
2026-11-29 12:33:40 +08:00
cflmy 01afaf2ce4 feat: embed the View read-only reader
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
Add a single bridge that runs the public View export --embed command, checks
the manifest, producer and package digests, caches the package by source,
View, CLI, theme and anchor identity, and serves it to a sandboxed same-origin
frame. Expose workspace and knowledge reading in the workbench and keep
execution, approval and evidence in the existing MQDH/CLI flow.
2026-11-29 12:21:48 +08:00
cflmy bc4bb48e61 fix: expose capability imports in the market projection
ci/woodpecker/pr/ci Pipeline was successful
ci/woodpecker/push/ci Pipeline was successful
The project view reads recorded imports from the capability projection; keep
that field in the public view and cover it in the import test. Record the real
browser import, lock and uninstall-refusal flow.
2026-11-29 10:48:59 +08:00
40 changed files with 1751 additions and 32 deletions

No files matched your search

+7 -2
View File
@@ -34,12 +34,13 @@ apps/harness/ # 独立应用仓库(父仓 gitlink:apps
│ ├── src/release/ # 应用发行清单、签名、Gitea 发现
│ ├── src/ecosystem/ # Runtime 信任来源、安装事务、环境、回退、Bootstrap Tool 兼容
│ ├── src/market/ # 市场来源/索引、用户级能力存储、启用作用域、项目导入门禁
│ ├── src/reader/ # View embed 桥、manifest/摘要校验、阅读包缓存与同源服务
│ ├── src/bootstrap/ # 首次启动状态机、doctor、repair
│ ├── src/distribution/ # 安装根、应用更新/回退/卸载
│ ├── src/diagnostics/ # 脱敏报告、去重、Gitea Issue 提交
│ ├── src/knowledge/ # 私人知识集合、导入、索引适配、检索
│ ├── src/execution/ # Analysis 3、CLI argv、审批、证据
│ ├── src/cli/ # 产品命令(bootstrap/doctor/repair/report/update/network)
│ ├── src/cli/ # 产品命令(bootstrap/status/doctor/repair/report/update/network)
│ ├── src/tools/ # 面向模型的六个操作
│ ├── src/web/ # /mqdh 页面与同源只读/受控写 API
│ └── tests/ # node:test 单元与真实 CLI/Release 集成
@@ -94,6 +95,9 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070
├── market/
│ ├── index.json # 可重建的来源聚合投影
│ └── events.jsonl # market.changed 变更事件
├── reader/
│ ├── packages/ # 按源/View/主题/锚点身份缓存的只读阅读包
│ └── staging/ # 未完成的 View 导出
├── capabilities/
│ ├── index.json # 权威:已安装版本/激活摘要/启用作用域/导入记录
│ ├── store/<source>-<kind>-<id>/ # 用户级能力载荷(按摘要分版本)
@@ -154,7 +158,7 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070
## 7. Web 工作台
`/mqdh` 是 DSH Web 内的真实服务器渲染工作台(同一 webserver、同一 loopback 绑定)。生态目录固定按 Runtime → Tool → Std → Ext → Knowledge 展示真实来源;打开/筛选无副作用,候选检查、市场刷新、安装/激活/启用、Runtime 切换、项目导入/锁检查与 Tool 移除由按钮显式发起。市场来源、索引与能力合同见 [MARKET.md](MARKET.md),目录分层见 [ECOSYSTEM.md](ECOSYSTEM.md)。Ext 的市场条目与项目文件分开显示,项目锁语义仍由 CLI `sync --locked --json`/`lock` 承担:
`/mqdh` 是 DSH Web 内的真实服务器渲染工作台(同一 webserver、同一 loopback 绑定)。生态目录固定按 Runtime → Tool → Std → Ext → Knowledge 展示真实来源;打开/筛选无副作用,候选检查、市场刷新、安装/激活/启用、Runtime 切换、项目导入/锁检查与 Tool 移除由按钮显式发起。市场来源、索引与能力合同见 [MARKET.md](MARKET.md),目录分层见 [ECOSYSTEM.md](ECOSYSTEM.md),View 阅读桥见 [READER.md](READER.md)。Ext 的市场条目与项目文件分开显示,项目锁语义仍由 CLI `sync --locked --json`/`lock` 承担:
- Runtime:CLI/Bundle/平台/环境 ID/遥测关闭状态;
- Knowledge:集合、导入(浏览器上传文本/文件)、搜索、删除、导出;
@@ -173,6 +177,7 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070
- Runtime 安装只接受 Gitea 权威 release 的不可变 tag、资产名、平台、大小与 SHA-256;市场条目按来源配置发现,下载/解包同样强制摘要、大小、路径与链接安全;失败保留旧组合。
- 市场不做可信/不可信中央裁决;来源标签不门禁,安装不等于对模型启用;项目导入只由 CLI 写声明与锁。
- 私人知识、完整会话、路径、环境变量、密钥和用户源码默认不进入诊断对外内容。
- View 阅读包同源服务只返回 manifest 列出的文件,iframe 仅 `allow-same-origin`,HTML 包 CSP 禁止脚本、表单、顶层导航与外部资源。
## 9. 出口、发行与引导边界
+1
View File
@@ -73,6 +73,7 @@ mqdh update rollback --confirm [--json]
- 失败关闭:摘要/平台/兼容/smoke 任一失败都不改指针,staging 清理。
- 更新不触碰 `MQDH_HOME/ecosystem`;Marqdo 运行时仍由 Bootstrap/生态中心独立管理。
- 应用仓库当前为私有开发仓时,匿名检查返回 403/404,状态显示 `update.unavailable`(不是伪造“已是最新”)。正式发行需公开仓库或显式配置凭据。
- `update check` 同时展示最新候选的 `published_at`、官方下载 URL(`latest.asset.url`)、Release 页面 URL(`latest.release_url`)、`known_limits` 与发布说明;发布说明来自可信 Gitea Release body(截断到 8 KiB),不是第二份清单。JSON 字段为 `latest.notes` 与 `latest.release_url`。
## 5. 构建与发布
+72
View File
@@ -0,0 +1,72 @@
# 文稿与知识只读阅读:复用 Marqdo View
本文件是 MQDH 阅读桥的唯一实现合同。正文渲染、主题、公式、表格、代码、锚点、受限媒体与静态包格式由 `marqdo-view` 的公开 `export --embed` 合同负责;MQDH 只负责选中文稿、外部布局、导航、审批/运行/证据入口和同源服务。实现位于 `packages/marqdo/harness/src/reader/`。
## 1. 上游公开合同
View 候选(PR `marqdo-view#18`,`tools/view` 分支 `b1f92548`)提供:
```sh
marqdo view export <doc.mq.md|doc.md> --out <dir> --embed \
--theme light|dark --anchor <heading-id> --expect-source-sha256 <raw-lower-hex>
```
`manifest.json` 的必核字段:
| 字段 | 要求 |
| --- | --- |
| `schema` / `schema_version` | `marqdo.view-export` / `1` |
| `mode` | `embedded` |
| `theme` | 与请求一致 |
| `executed` | 必须为 `false` |
| `requires` | `api_revision=1`、`analysis=3`、`observation=1`、`markdown_profile=marqdo.md.v1` |
| `producers.view.binary_sha256` | 等于已安装 View 可执行文件的 SHA-256 |
| `producers.cli.binary_sha256` | 等于当前 Runtime CLI 的 SHA-256(有值时) |
| `pages[0].source_sha256` | 等于所选源文件的原始 SHA-256 |
| `pages[0].source_status` | `static-ok` 或 `markdown-only` |
| `entry.href` / `entry.file` | 包内相对入口,通常 `index.html` 或 `index.html#<anchor>` |
| `entry.anchor` / `entry.heading_ids` | 与请求锚点一致;锚点必须在列表内 |
| `files[]` / `assets[]` | 包内相对路径与 SHA-256,不得包含 `.js`/脚本 |
`--embed` 包只含 `index.html`、`assets/`(CSS/字体/logo)与受限 `media/`;MQDH 不生成、不解析、不覆盖这些文件。
## 2. 桥接层
`ReaderService` 对每个请求:
1. 解析源:工作区文件经 `resolveDocument`(拒绝绝对路径、越界、符号链接);知识源经 collection + relPath 校验,读取 `MQDH_HOME/knowledge/sources/<collection>/<rel>`。
2. 读取已安装 Tool 的 `record.json`,定位 `bin/marqdo-view` 并计算 SHA-256;读取当前 Runtime CLI SHA-256。
3. 缓存键 = `workspace root + 源相对路径 + 源摘要 + View 二进制摘要 + CLI 二进制摘要 + theme + anchor` 的 SHA-256。
4. 缓存未命中时固定 argv 执行 `marqdo view export ...`,`cwd` 为工作区或知识 source root;`MARQDO_TOOL_HOME` 指向当前 Runtime 的隔离 Tool home。
5. 校验 manifest、全部包文件摘要、入口文件、主题、锚点、源摘要与生产者摘要。
6. 原子移动到 `MQDH_HOME/reader/packages/<id>/`,元数据写在 `<id>.json`;缓存命中不重新导出。
失败码:`reader.view_missing`、`reader.cli_missing`、`reader.source_invalid`、`reader.source_changed`、`reader.anchor_missing`、`reader.export_failed`、`reader.manifest_invalid`、`reader.package_missing`、`reader.package_invalid`、`reader.knowledge_source_missing`。
## 3. 同源服务与隔离
- `POST /mqdh/api/reader/open`:显式 `confirm:true`;只做静态检查与本地导出,不执行文稿。
- `GET /mqdh/api/reader/source`:只读源文本,最多 256 KiB,不调用 View。
- `GET /mqdh/api/reader/status`:View/CLI 可用性、版本与二进制摘要。
- `GET /mqdh/api/reader/package/<id>/<path>`:只服务 manifest 列出的文件;拒绝越界、符号链接、未列出文件与超过 16 MiB 的单个文件。
- HTML 包响应发送 `Content-Security-Policy: default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self' data:; media-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'`。
- 页面 iframe 固定 `sandbox="allow-same-origin"`,不开放脚本、表单或顶层导航;父页 CSP 只允许 `frame-src 'self'`。
## 4. 两处入口与降级
- **任务右侧文稿**:工作台“文稿阅读”页签输入工作区相对路径、主题与可选锚点;外层显示路径、View 版本/二进制摘要、manifest 摘要、源码切换与“运行记录”入口。运行、审批和证据仍走现有 `marqdo_program`/CLI 流程。
- **知识命中详情**:搜索结果“在 View 阅读”使用同一桥接层、同一 View 制品与同一 iframe;collection、relPath、anchor 由知识命中提供,普通 Markdown 显示 `markdown-only`。
- 缺 View / 缺 Runtime 时显示明确文字与恢复入口(生态中心安装 Tool);源变更、锚点缺失、manifest/摘要不匹配均返回结构化错误,不回退到第二套渲染器或静默显示旧包。
## 5. 不做的部分
- 不复制 View CSS、不写第二套 Markdown/公式/表格渲染器、不读取 View 私有文件路径。
- 不把知识文本、外部链接或未知媒体当作可执行内容;不因阅读自动执行、安装或授权。
- 不在 MQDH 内定义新的 View manifest 方言;只消费 `marqdo.view-export` 的公开字段。
- 不把“View 包已生成”等同于“运行验收通过”;运行事实仍由 CLI Observation 1 与 MQDH 证据绑定。
## 6. 验收与限制
真实证据见 [evidence/2026-11-29-reader.md](evidence/2026-11-29-reader.md):候选 View 二进制 `ab353d09…`、rc.6、真实工作区 `.mq.md` 与知识 `.md`,Playwright 验证主题、公式、表格/代码横向滚动、本地图片、锚点、源码切换、知识命中入口、0 外部请求、0 页面错误。
未验证:正式 View Release 尚未包含 `--embed`,发布后需用同资产复验;企业代理/离线安装组合;Windows/macOS 包路径;完整 screen-reader/像素级主题走查。
+4
View File
@@ -1,10 +1,14 @@
# Marqdo Harness 文档
产品级 AI 可读入口:[index.mq.md](index.mq.md)(定位、架构地图、能力地图、任务导航、关键不变量与真实验收入口;先读这里)。本列表只是文档索引;唯一现状仍是 [STATUS.md](STATUS.md),领域细节只在各自权威文档维护。
| 文档 | 内容 |
| --- | --- |
| [index.mq.md](index.mq.md) | **产品入口(AI 可读)**:定位/上游隔离/架构与能力地图/任务导航/关键不变量/验收入口 |
| [ARCHITECTURE.md](ARCHITECTURE.md) | 产品边界、包结构、数据布局、执行与安全模型 |
| [ECOSYSTEM.md](ECOSYSTEM.md) | 生态目录的发现、浏览与安装边界 |
| [MARKET.md](MARKET.md) | 动态来源、市场索引、用户级能力存储与项目导入合同 |
| [READER.md](READER.md) | 复用 Marqdo View 的文稿/知识只读阅读桥与隔离合同 |
| [NETWORK.md](NETWORK.md) | 默认出口、代理/镜像/离线、审计与拒绝码 |
| [BOOTSTRAP.md](BOOTSTRAP.md) | 首次启动状态机、`doctor`/`repair`、离线与失败处理 |
| [DIAGNOSTICS.md](DIAGNOSTICS.md) | 本地脱敏报告、去重/限额与显式 Issue 提交 |
+5 -1
View File
@@ -73,6 +73,10 @@ cd marqdo-harness-<version>-x86_64-unknown-linux-gnu
- 已发布版本有缺陷:发布更高版本;不删除或重写旧资产。用户侧可 `mqdh update rollback --confirm`。
- 签名错误:停止发布,轮换密钥并提升版本;不得重新上传同 tag。
## 7. 未验证
## 7. 发布说明
创建 Gitea Release 时填写的 body 是产品内 `mqdh update check` 展示的发布说明唯一来源(截断到 8 KiB);不要另建发布说明清单或第二份版本表。发布说明应包含用户可见变化、已知限制和升级注意项,且不得包含凭据、私有数据或未验证的 PASS 声明。
## 8. 未验证
生产签名证书/密钥托管、macOS/Windows 构建与公证、第二台干净主机、低于 2.39 glibc 的平台、真实断网更新与弱网大文件下载。以上保持 `UNVERIFIED`,不得写成 PASS。
+5 -4
View File
@@ -70,11 +70,12 @@
| S03 文件/进程/网络边界 | PARTIAL | 路径/符号链接/argv/进程组/超时/输出上限有测试;OS 级隔离依赖 DSH 沙箱,未声称强隔离。 |
| S04 插件/profile 旁路 | PASS | `plugin-manager` 服务关闭;插件 market/manager 工具不可用;不是仅隐藏 UI。 |
| S05 工作区隔离 | PARTIAL | 工作区显式且路径受控;未实现每任务独立目录与跨工作区审计。 |
| S06 浏览器真实交互 | PARTIAL | 市场工作台已用 Playwright 真实浏览器覆盖刷新/详情/安装/启用/撤销/窄窗口/暗色;知识导入检索、执行审批与完整生态安装仍未在浏览器中运行。 |
| S06 浏览器真实交互 | PARTIAL | 市场、View 阅读与五组生态目录已用 Playwright 真实浏览器覆盖刷新/详情/安装/启用/撤销/阅读/知识命中/键盘/窄窗口/暗色;知识导入与执行审批的完整浏览器流程仍未运行。 |
| S07 诊断脱敏 | PASS(本地/替身) | 捕获→脱敏→本地报告→显式提交全链路由 `tests/diagnostics.test.ts` 覆盖;真实公网 Gitea 权限与模板未验证,见 DIAG-03/05。 |
| S08 独立归档冷安装 | PASS(本机) | 归档内置 Node + `install.sh`;从归档冷安装后 `mqdh --version`、`doctor --json`、`--dump-config` 通过(见 m7 证据)。未在第二台干净主机验证。 |
| S09 CI/真实模型/发布 | PARTIAL | `scripts/ci.sh` 与 `.woodpecker/ci.yml` 已实现;父仓 PR#48 的 Woodpecker pipeline 已运行并暴露/修复 candidate manifest bug,最终通过证据以 PR 为准。真实模型两轮验收 UNVERIFIED。 |
| S10 父仓组合验收 | PASS(父仓) | 父仓 Node app lane 使用同一 CLI/Bundle 候选;app optional,不阻塞 CLI 独立发行。 |
| S11 产品级 AI 可读入口 | PASS(本仓) | `docs/mqdh/index.mq.md` 为产品层唯一入口,`docs/mqdh/README.md` 指向;39 个相对链接在提交前核对存在;上游隔离/STATUS 权威声明与关键不变量在入口可见。完整 `pnpm run doc-sync` 在本下游 fork 基线不通过(既有 `docs/mqdh/` 文档缺双语/单行段落规范),文档门禁保持 UNVERIFIED,不用入口 PASS 冒充文档 gate。 |
## 网络出口(NET)
@@ -120,16 +121,16 @@
| 门禁 | 状态 | 证据或限制 |
| --- | --- | --- |
| CAT-01 固定顺序 Runtime/Tool/Std/Ext/Knowledge 与真实来源 | PARTIAL | `/mqdh` 生态目录按固定顺序投影真实状态;Runtime 可显式切换,Tool 候选由市场来源驱动,Ext 市场/已安装/当前项目三段视图与 CLI 锁检查并存,Std 只随 Bundle。市场工作台浏览器/键盘/窄窗口/主题验收已通过;完整五组目录的浏览器遍历未运行。 |
| CAT-01 固定顺序 Runtime/Tool/Std/Ext/Knowledge 与真实来源 | PASS | 固定五组同工作台浏览器回归:真实 rc.6 Runtime + Bundle 17 模块 + View Tool + 锁定 Ext 项目 + 私人知识集合;组顺序、真实状态、Knowledge 同集合入口、市场行键盘 Enter、窄窗口/暗色均通过,0 外部请求、0 page error。见 [目录证据](evidence/2026-11-29-catalog.md)。浏览器态 Runtime 缺失负例已通过(空 home 五组仍可用、0 mutating request);下载中断/候选校验失败浏览器负例仍为 UNVERIFIED。 |
| CAT-02 打开、筛选、查看详情无自动安装/执行 | PASS | `/ecosystem` 只做本地状态与文件读取;候选检查、项目锁检查、Tool 移除均由按钮显式发起。 |
| CAT-03 Ext 锁语义(声明/锁差异/权限) | PARTIAL | 应用不解析第二套依赖图;显示 `marqdo.yaml`/`marqdo.lock` 存在性与摘要,显式按钮调用 CLI `sync --locked --json`/`lock`,错误原文展示;项目导入由 CLI `add` 写声明。 |
| CAT-04 真实浏览器与主题回归 | PASS(市场工作台) | Playwright Chromium 149 真实打开 `/mqdh`:无 page/console error、无外部请求、键盘焦点与 Enter 打开详情、420px 窄窗口、明/暗主题截图;证据见 [市场证据](evidence/2026-11-29-market.md#6-真实浏览器与主题回归)。完整五组目录的浏览器遍历仍属 CAT-01。 |
| CAT-05 动态市场来源、缓存/变更探测、离线目录 | PASS | `market.test.ts` 覆盖默认来源、目录发现、new/changed/stale、TTL、来源隔离、摘要/链接拒绝;真实 Gitea 通过 topic 发现 knowledge/lint/view,prove 无资产如实 warning;离线刷新保留官方旧条目并标记 `offline`,目录来源仍 `ok`。见 [市场证据](evidence/2026-11-29-market.md)。 |
| CAT-06 用户级能力存储、安装/激活、启用/撤销与模型可见性 | PASS | 能力载荷写入 `MQDH_HOME/capabilities/store`;Tool 注册到当前 Runtime 隔离 Tool home;未启用时 `visible=[]`,全局启用后出现,撤销后立即消失;安装/激活/导入/锁/卸载写审计。真实 rc.6 + view 0.3.0 已跑通。 |
| CAT-07 安装→项目导入门禁与 CLI 锁 | PASS | 未安装返回 `extension.not_installed`;已安装 ext 复制到 `marqdo-vendor/<alias>` 后由 CLI `add` 写声明、CLI `lock` 生成锁、`sync --locked` 通过;应用不写锁。 |
| CAT-07 安装→项目导入门禁与 CLI 锁 | PASS | 未安装返回 `extension.not_installed`;已安装 ext 复制到 `marqdo-vendor/<alias>` 后由 CLI `add` 写声明、CLI `lock` 生成锁、`sync --locked` 通过;应用不写锁。真实浏览器完成启用项目→导入→生成锁→卸载被引用拒绝。 |
| CAT-08 更新/卸载与项目引用 | PASS | 新版本安装后 `pending_activation=true`、旧版本保持激活,显式 `activate` 才切换;被 `marqdo.yaml`/`marqdo.lock` 引用时卸载返回 `extension.project_referenced`,强制卸载需显式 `force`;运行证据绑定锁摘要,重新锁后旧证据 stale。 |
| CAT-09 市场浏览器/键盘/窄窗口/暗色回归 | PASS | Playwright Chromium 149:刷新、详情、安装、启用当前项目、撤销、搜索无网络副作用;`market-refresh` 聚焦、行 Enter 打开详情;420px 窄窗口与 dark 媒体截图;0 external request、0 page error。 |
| READER-01 文稿/知识复用 Marqdo View 只读阅读 | UNVERIFIED(上游阻塞) | 等待 `marqdo-view#16` 公开只读嵌入与主题身份、`marqdo-view#15` 结果绑定;应用不实现第二套 Markdown/主题。 |
| READER-01 文稿/知识复用 Marqdo View 只读阅读 | PASS(候选 View) | 已接入 View PR #18 的公开 `export --embed`:静态包 manifest、View/CLI 二进制摘要、源摘要、锚点与包文件摘要全部校验;工作区 `.mq.md` 与知识 `.md` 共用同一桥接层/View 制品,iframe 仅 `allow-same-origin`,HTML CSP 禁止脚本/外部资源。Playwright 真实验证主题、公式、表格/代码滚动、本地图片、源码切换、知识命中入口、0 外部请求、0 页面错误;证据见 [reader 证据](evidence/2026-11-29-reader.md)。正式 View Release 尚未包含 `--embed`,发布后同资产复验仍待。 |
| SCOPE-01 局部调用、规则审阅与跨会话复用 | UNVERIFIED | 依赖真实模型/浏览器、E07 环境固定与主仓 #28 的独立规则/预期;应用现有 `marqdo_program` 已提供固定 argv/审批/证据基础,但未做真实模型验收。 |
## 明确边界
Binary file not shown.

After

Width:  |  Height:  |  Size: 533 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 544 KiB

@@ -0,0 +1,75 @@
{
"schema": "marqdo.mqdh.catalog-evidence",
"schema_version": 1,
"status": "PASS",
"application_sha": "01afaf2ce44effabdc8b45ebe575f580687dbb20",
"group_order": [
"Runtime",
"Tool",
"Std",
"Ext",
"Knowledge"
],
"runtime": {
"cli": "3.0.0-rc.6",
"environment": "cli-3.0.0-rc.6-8dc0b006302e",
"bundle": "0.2.0",
"bundle_digest": "sha256:db905508dde89763b9d43b47fc5d52c6a1d5445a91f3c86a550ced43e8aac9d7",
"modules": 17
},
"tool": {
"command": "view",
"version": "0.3.0",
"binary_sha256": "ab353d09868e651cddf4b7bd774c8a7d241855499b6d34d2c01233898631237c"
},
"ext": {
"capability": "local:ext:demo-ext",
"version": "0.2.0",
"manifest_digest": "sha256:1535a268f91b4707913e9c8cf812f7dac5e618297ed6027a51787c4233efa8b7",
"lock_digest": "sha256:090f0eb2bcaa97064929574224c739b8be75909eda76bce91acb528eb4bf2138"
},
"knowledge": {
"collection": "kc-ff2818c3b057",
"sources": 1,
"enabled": 1
},
"browser": {
"engine": "Playwright Chromium 149.0.7827.55 (Playwright 1.61.1)",
"external_requests": 0,
"page_errors": 0,
"keyboard": "row-button focus + Enter detail",
"viewports": [
"1280x900",
"420x900"
],
"themes": [
"light",
"dark"
],
"screenshots": [
"2026-11-29-catalog-wide-light.png",
"2026-11-29-catalog-narrow-light.png",
"2026-11-29-catalog-narrow-dark.png"
]
},
"unverified": [
"download-interruption/candidate-validation browser negatives",
"full tool/project mutation browser confirmation",
"keyboard-only traversal and screen-reader"
],
"empty_home_negative": {
"runtime_missing": true,
"groups_visible": [
"Runtime",
"Tool",
"Std",
"Ext",
"Knowledge"
],
"reader_status": "unavailable: installed View Tool is required",
"requests": 14,
"external_requests": 0,
"mutating_requests": 0,
"page_errors": 0
}
}
+38
View File
@@ -0,0 +1,38 @@
# 2026-11-29 生态目录五组组合证据
状态:固定五组同工作台浏览器回归 **PASS**;Runtime 缺失/下载中断/候选校验失败等浏览器态负例仍为 **UNVERIFIED**(由单元/HTTP 测试与 STATUS 覆盖)。应用身份与 CI 结果见 [2026-11-29-reader-ci.json](2026-11-29-reader-ci.json) 的同一候选提交。
## 输入
| 层 | 真实身份 |
| --- | --- |
| Runtime | CLI `3.0.0-rc.6`,环境 `cli-3.0.0-rc.6-8dc0b006302e`,Bundle `0.2.0` / `sha256:db905508…` / 17 个模块 |
| Tool | View 候选 `0.3.0`,二进制 SHA-256 `ab353d09…`,安装在当前 Runtime 隔离 Tool home |
| Std | 当前 Bundle 的 `std:clock`、`std:io`、`std:data/*` 等公开导入路径 |
| Ext | 当前工作区 `marqdo.yaml` + `marqdo.lock`;市场本地来源安装的 `local:ext:demo-ext@0.2.0` |
| Knowledge | 私人集合 `kc-ff2818c3b057` / `阅读知识`,1 份原文,已启用 |
## 浏览器结果
Playwright Chromium `149.0.7827.55` 真实打开 `/mqdh`:
- `#catalog .group h3` 顺序严格为 `Runtime|Tool|Std|Ext|Knowledge`。
- 每层都能回溯真实来源:Runtime 版本/平台/环境、Tool 版本与路径、Std 命名空间导入、Ext 项目文件摘要与市场条目、Knowledge 集合计数。
- 点击 Knowledge“打开集合”进入同一知识页;市场列表行可用键盘聚焦,`Enter` 打开 `Demo ext` 详情。
- 0 外部请求、0 page error;窄窗口 420px 与暗色主题截图如下。
![五组宽屏亮色](2026-11-29-catalog-wide-light.png)
![五组窄屏亮色](2026-11-29-catalog-narrow-light.png)
![五组窄屏暗色](2026-11-29-catalog-narrow-dark.png)
## Runtime 缺失负例
空 `MQDH_HOME`(无 Runtime、无 Tool、无知识集合)真实浏览器打开 `/mqdh`:五组仍按顺序显示;Runtime “未安装”、Std “随 Runtime”、Ext 文件“缺失”、Knowledge “0 个集合”;阅读页显示“阅读不可用:installed View Tool is required…”;14 个请求全部同源 GET,0 外部请求、0 mutating request、0 page error。原 DSH 对话入口仍由同一 `/mqdh` 外的页面保留。
## 未完成
- 下载中断、候选校验失败在真实浏览器中的目录态负例(命令/单元层已覆盖失败保留旧组合)。
- Tool 安装/移除、项目依赖变更的完整浏览器确认流程(命令层已由市场/导入测试覆盖)。
- 完整 keyboard-only 走查与 screen-reader。
+6 -2
View File
@@ -68,7 +68,10 @@
"install",
"enable project scope",
"local search",
"disable all"
"disable all",
"with real Runtime: import via CLI add",
"lock via CLI lock",
"uninstall refused by project reference"
],
"page_errors": 0,
"console_errors": 0,
@@ -85,7 +88,8 @@
"screenshots": [
"2026-11-29-market-wide-light.png",
"2026-11-29-market-narrow-light.png",
"2026-11-29-market-narrow-dark.png"
"2026-11-29-market-narrow-dark.png",
"2026-11-29-market-import-refusal.png"
],
"status": "PASS"
},
Binary file not shown.

After

Width:  |  Height:  |  Size: 658 KiB

+4
View File
@@ -92,6 +92,10 @@ Playwright Chromium `149.0.7827.55`(Playwright `1.61.1`)在 `http://127.0.0.
![市场窄屏暗色](2026-11-29-market-narrow-dark.png)
带真实 Runtime 的第二轮浏览器流程:在“已安装”启用当前项目 → “导入项目(CLI add)”写入 `marqdo.yaml` 的 `./marqdo-vendor/demo` → “当前项目”点击“生成项目锁(CLI lock)”生成 `marqdo.lock` → 点击卸载返回 `extension.project_referenced`,能力保持安装。项目内副本、锁文件与拒绝结果均从页面按钮触发并落盘。
![项目导入与卸载拒绝](2026-11-29-market-import-refusal.png)
## 7. 未验证
- 真实浏览器、键盘遍历、窄窗口、亮/暗主题截图与回归;
@@ -0,0 +1,53 @@
{
"schema": "marqdo.mqdh.ci-evidence",
"schema_version": 1,
"status": "PASS",
"application_sha": "01afaf2ce44effabdc8b45ebe575f580687dbb20",
"platform": "x86_64-unknown-linux-gnu",
"node": "v24.22.3",
"view": {
"candidate": "marqdo-view#18",
"source_sha": "b1f92548dc343435677747580806fbe58c5ab4ef",
"binary_sha256": "ab353d09868e651cddf4b7bd774c8a7d241855499b6d34d2c01233898631237c",
"command": "marqdo view export --embed --theme --anchor --expect-source-sha256"
},
"cli": {
"version": "3.0.0-rc.6",
"source_sha": "63776735e924ade279cdf59d5c733dc24bfdabbb",
"binary_sha256": "4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c"
},
"browser": {
"engine": "Playwright Chromium 149.0.7827.55 (Playwright 1.61.1)",
"theme": "dark/light",
"math": 1,
"image_natural_width": 1,
"code_scroll": {
"scrollWidth": 1716,
"clientWidth": 353
},
"iframe_sandbox": "allow-same-origin",
"external_requests": 0,
"page_errors": 0,
"knowledge_reader": "PASS",
"screenshots": [
"2026-11-29-reader-wide-dark.png",
"2026-11-29-reader-narrow-dark.png",
"2026-11-29-reader-narrow-light.png"
]
},
"unverified": [
"official View release with --embed",
"enterprise proxy/offline View install",
"Windows/macOS packaging",
"full screen-reader and pixel theme review"
],
"remote_ci": {
"push": "https://ci.cflmy.cn/repos/21/pipeline/21/1",
"pull_request": "https://ci.cflmy.cn/repos/21/pipeline/22/1"
},
"commands": [
"pnpm run typecheck",
"node --import tsx/esm --test packages/marqdo/harness/tests/*.test.ts",
"Playwright Chromium reader acceptance"
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

+50
View File
@@ -0,0 +1,50 @@
# 2026-11-29 View 只读阅读桥证据
状态:候选 View 真实阅读 **PASS**;正式 View Release 与跨平台 **UNVERIFIED**。应用身份与 CI 退出码见 [2026-11-29-reader-ci.json](2026-11-29-reader-ci.json)。
## 1. 输入与身份
| 输入 | 身份 |
| --- | --- |
| View 候选 | PR `marqdo-view#18`;`tools/view` 分支 `b1f92548dc343435677747580806fbe58c5ab4ef`;候选二进制 SHA-256 `ab353d09868e651cddf4b7bd774c8a7d241855499b6d34d2c01233898631237c` |
| View 命令 | `marqdo view export <doc> --out <dir> --embed --theme light|dark --anchor <id> --expect-source-sha256 <hex>` |
| CLI Runtime | `v3.0.0-rc.6`,source `63776735e924ade279cdf59d5c733dc24bfdabbb`,二进制 SHA-256 `4f12e6b8a2edb327c0d9ab6165f74e8e88a01b05350527e3aade6f52d4f7a06c` |
| 平台 | `x86_64-unknown-linux-gnu`,glibc 2.43,Node `v24.22.3` |
| 工作区文稿 | `reader.mq.md`:标题、宽表格、长代码块、公式、本地 1×1 PNG、`@exec main` |
| 知识源 | collection `kc-ff2818c3b057` / `knowledge.md`:标题、引用、表格、公式;普通 Markdown |
View 候选 manifest 实测 `mode=embedded`、`executed=false`、`theme=dark`、`source_status=static-ok`,`producers.view.binary_sha256` 与上述候选二进制一致,`pages[0].source_sha256` 与源文件一致。
## 2. 桥接与失败路径
命令/服务已验证:
- 工作区阅读:`POST /mqdh/api/reader/open` → 固定 argv `marqdo view export ... --embed --theme dark --expect-source-sha256 ...` → 校验 manifest/36 个包文件摘要 → 返回 `index.html` 包 URL;第二次打开 `cached=true`。
- 锚点:`anchor=表格` 返回 `index.html#%E8%A1%A8%E6%A0%BC`;`anchor=no-such-heading` 返回 `reader.anchor_missing`。
- 知识阅读:同一桥接层打开 collection/relPath,manifest `source_status=markdown-only`,标题 ID 为 `知识文章`、`细节`。
- 源切换:`GET /mqdh/api/reader/source` 返回原始文本与 `sha256:` 摘要,不调用 View。
- 包文件:只服务 manifest 列出的文件;`index.html` 与 CSS 返回正确 content-type;未列出路径/越界/脚本路径拒绝。
- 缺 View / 缺 Runtime / 源变更 / 摘要不符 / manifest 主题或生产者不符均有结构化错误,不回退第二套渲染器。
## 3. 真实浏览器
Playwright Chromium `149.0.7827.55`(Playwright `1.61.1`)真实打开 `/mqdh`:
- 工作区阅读 dark:`body[data-theme=dark]`,公式 `math` 1 个,本地图片 `naturalWidth=1`,420px 窄窗口下长代码块 `scrollWidth=1716 > clientWidth=353`,iframe `sandbox="allow-same-origin"`。
- 嵌入正文无 `script`/`button`/`.mq-topbar`/`.mq-dock`;0 外部请求、0 page error。
- 源码切换显示文稿原文;知识搜索命中“在 View 阅读”打开同一桥接层的知识包,正文包含“知识文章”。
- 宽屏 dark、窄屏 dark、窄屏 light 截图:
![阅读宽屏暗色](2026-11-29-reader-wide-dark.png)
![阅读窄屏暗色](2026-11-29-reader-narrow-dark.png)
![阅读窄屏亮色](2026-11-29-reader-narrow-light.png)
## 4. 未验证
- View 正式 Release 尚未包含 `--embed`;发布后必须用同资产复验并记录 tag/资产 SHA。
- 企业代理/离线包安装组合下的 View Tool 获取。
- Windows/macOS 路径与打包。
- 完整 screen-reader 与像素级主题走查。
- View 独立阅读器与嵌入正文的自动化样式对比目前复用 View 自身 `embedded.browser.cjs` 的证据;MQDH 侧只断言同一主题、同一包和关键渲染结果。
@@ -0,0 +1,18 @@
# 产品级 AI 可读入口证据(app-harness#15 P1)
Date: 2026-11-30. Branch: `codex/issue-15-product-entry`. Baseline: `2aab24cccf986141e0622d34391b9d012d8b9f98`(main)。
## 交付(P1/P2 的首个切片)
- 新增 `docs/mqdh/index.mq.md`:产品层唯一 AI 可读入口,包含上游隔离声明、定位与承担/不承担边界、架构地图与能力地图(每项指向权威文档 + 真实实现目录)、任务导航表(开发启动/Bootstrap/工作台/文稿执行/阅读桥/私人知识/生态/诊断/发行更新/上游同步 → 必读、实现位置、验证入口)、关键不变量(凭证 0600、默认出口、一次一授权、不复制 Marqdo 源码、`MQDH_HOME` 与安装树分离、上游修改登记)、真实验收入口(`pnpm run build`、`MQDH_TEST_INSTALL=1 ... scripts/ci.sh`、`node scripts/mqdh.mjs doctor --json`、tag 上 `scripts/package.sh`)、阅读顺序与“唯一现状是 STATUS.md”的权威性声明。
- `docs/mqdh/README.md` 顶部文档列表指向 `index.mq.md`,本入口不复制领域正文。
- `docs/mqdh/STATUS.md` 新增 S11(PASS(本仓)),记录入口存在、链接核对与文档 gate 基线不通过的边界。
## 真实性与边界
- 入口只导航,不复制 `docs/mqdh/` 领域正文;不新增 AI 专用语法/元数据。
- 未改上游文件:本次只新增/修改 `docs/mqdh/` 下游文档,不触发 `upstream-delta.md`;根 `README.md` 未改(其既有 downstream 段已指向 `docs/mqdh/`,本入口由该目录 README 指向)。
- 链接在提交前用脚本核对真实存在(39 个相对链接,0 个缺失)。
- 文档 gate:在本下游 fork 基线上运行 `pnpm run test:docs`(doc-quick)会失败,失败集合包含既有 `docs/mqdh/` 文档(缺双语 counterpart、单行段落格式等),并非本入口单独引入;完整 `pnpm run doc-sync` 因此保持 UNVERIFIED,不冒充 PASS。入口与证据文件已改为一行一段,减少新增 wrap 违例。
- 未运行完整文档 gate;`scripts/ci.sh` 不含文档 gate,组件 CI 结果以平台为准记录。
- `index.mq.md` 是导航级入口,不重复 STATUS 矩阵;STATUS 中 UNVERIFIED/PARTIAL 项保持原样。
@@ -0,0 +1,22 @@
# `mqdh status` 生态版本视图(app-harness#16 切片)
Date: 2026-11-30. Branch: `codex/issue-16-status-view`.
Baseline: `a1517652c29ac51357275661a59e7814b596efc8`(main)。
## 交付
- 新增只读产品命令 `mqdh status [--json]`:一次输出应用版本/home/workspace、平台与 Node、运行时候选版本、生态环境 id、Bundle 版本/模块数/摘要、已安装 Tool 版本、market/knowledge 计数与 privacy 常量;JSON schema `marqdo.mqdh.status`(`schema_version: 1`)。
- `scripts/mqdh.mjs` 的产品命令集合加入 `status`(避免落到 DSH 转发);HELP 更新。
- `docs/mqdh/ARCHITECTURE.md` 产品命令列表更新。
- 测试:`packages/marqdo/harness/tests/cli.test.ts` 新增 `status` JSON/文本断言(未安装生态时如实显示 not installed/false)。
## 验证(本机,Linux x86_64 / glibc 2.43)
```text
$ node --import tsx/esm --test packages/marqdo/harness/tests/cli.test.ts
6 pass, 0 fail
```
该命令只读现有 `MdhRuntime.status()` 状态,不触发安装/网络/更新;不是 #16 的
“最新版本/发布说明/下载入口”完整生态版本检查,那部分保持 UNVERIFIED。未运行
完整组件测试,组件 CI 结果以平台为准。
@@ -0,0 +1,28 @@
# 应用更新检查展示发布说明/官方下载/已知限制(app-harness#16 切片)
Date: 2026-11-30. Branch: `codex/issue-16-update-notes`.
Baseline: `eceb13a70a723d8623cbf7f4b1b6979bdc303680`(main)。
## 交付
- `release/gitea.ts`:可信 Gitea Release 的 `body` 进入候选(截断 8192 字节,空值 null);`AppReleaseCandidate.notes` 与 `browser_url` 明确。
- `distribution/updater.ts`:`UpdateCandidate` 新增 `notes` 与 `release_url`;持久化 `UpdateState.latest` 携带二者。
- CLI `mqdh update check` 文本输出新增 `published`/`download`(官方资产 URL)/`release`(Release 页面)/`known limits`/`release notes`;JSON 已直接包含这些字段。
- 文档:`DISTRIBUTION.md` §4 更新检查字段、`RELEASING.md` §7 发布说明唯一来源(Gitea Release body,不另建清单)。
- 测试:`updater.test.ts` 的 fake Gitea Release 带 body,断言 `latest.notes` 与 `latest.release_url`。
## 验证(本机,Linux x86_64 / glibc 2.43)
```text
node --import tsx/esm --test packages/marqdo/harness/tests/updater.test.ts
3 pass, 0 fail
node --import tsx/esm --test packages/marqdo/harness/tests/*.test.ts
77 pass, 0 fail, 3 skipped
pnpm run typecheck → 5 passed, 0 failed
```
## 边界
- 发布说明来自可信 Release body,显示为数据;不执行、不解析为指令,不冒充“更新说明已验证”。
- 仍不是完整生态(CLI/View/Tools/Bundle/Knowledge)的最新版本聚合;E09 通知/对账仍 UNVERIFIED。
- 未创建 release/tag;未运行浏览器/真实 Gitea 端到端。
+80
View File
@@ -0,0 +1,80 @@
# @knowledge MQDH 产品入口
Marqdo Harness(MQDH)是 Marqdo 生态的官方单用户应用:安装并校验 Marqdo 运行时与默认 Bundle/Tools,通过公开 CLI 契约执行 `.mq.md` 文稿,维护私人本地知识,并保存可复核的运行证据。本文件是**产品层唯一的 AI 可读入口**:只做定位、导航、关键不变量与验收入口,不复制领域正文。
## 上游隔离
本仓库是 DeepSeek Harness(DSH)的下游 fork。**上游 DSH 文档不是 MQDH 产品规范**:产品规范只在本仓 `docs/mqdh/` 与本文。上游远端、许可与同步规则见 [UPSTREAM.md](UPSTREAM.md);对上游文件的每一处修改都必须登记在 [upstream-delta.md](upstream-delta.md)。不得重建/复制上游文档,不得把上游文档改成第二套产品规范;产品特化优先通过 bundle patch 与公开 seam 完成。
## 产品定位与边界
- 用户:希望在本地运行 Marqdo 文稿、复用 View 阅读、保存私人知识的单用户。
- 本仓承担:应用壳与 `/mqdh` 工作台、首次启动 Bootstrap、生态安装/更新、文稿执行入口与审批、阅读桥、私人知识、诊断/反馈路由、发行打包、上游同步。
- 本仓不承担:CLI/语言语义、默认 Bundle 内容、扩展业务实现、知识检索实现、文稿渲染与静态包格式(由 `marqdo-cli`、标准库/扩展仓、`marqdo-knowledge`、`marqdo-view` 等按各自合同提供);不提供多用户账号、遥测或静默上传。
- 权威边界与包结构见 [ARCHITECTURE.md](ARCHITECTURE.md);生态安装边界见 [ECOSYSTEM.md](ECOSYSTEM.md)。
## 架构地图
- 唯一产品启动器:`scripts/mqdh.mjs`;唯一 profile `mqdh`(`packages/marqdo/bundle/`)。
- 产品插件与服务:`packages/marqdo/harness/src/`,按能力分为 `bootstrap/`、`cli/`、`core/`、`diagnostics/`、`distribution/`、`ecosystem/`、`execution/`、`knowledge/`、`market/`、`network/`、`platform/`、`reader/`、`release/`、`tools/`、`version/`、`web/`、`workspace.ts`。
- 首次启动状态机、`doctor`/`repair`:见 [BOOTSTRAP.md](BOOTSTRAP.md)。
- `/mqdh` 工作台在 DSH 同一 loopback listener 上注册(`ctx.webServer.register`)。
- 应用不携带 Marqdo CLI/Bundle/扩展/Tool 实现;它们从可信 Gitea 发布安装到 `MQDH_HOME`,安装布局与平台矩阵见 [DISTRIBUTION.md](DISTRIBUTION.md)。
## 能力地图(权威文档)
| 能力 | 权威文档 | 实现位置 |
| --- | --- | --- |
| 产品边界/数据布局/执行安全 | [ARCHITECTURE.md](ARCHITECTURE.md) | `packages/marqdo/harness/src/core/` |
| 生态目录、浏览与安装边界 | [ECOSYSTEM.md](ECOSYSTEM.md) | `src/ecosystem/`、`src/market/`、`src/tools/` |
| 阅读桥(复用 View 合同) | [READER.md](READER.md) | `src/reader/` |
| 默认网络出口/代理/离线/审计 | [NETWORK.md](NETWORK.md) | `src/network/` |
| 首次启动、离线与失败处理 | [BOOTSTRAP.md](BOOTSTRAP.md) | `src/bootstrap/` |
| 本地脱敏报告与显式 Issue 提交 | [DIAGNOSTICS.md](DIAGNOSTICS.md) | `src/diagnostics/` |
| 平台矩阵、安装布局、更新/回退 | [DISTRIBUTION.md](DISTRIBUTION.md) | `src/distribution/`、`src/release/` |
| 构建、签名、发布与发布后验证 | [RELEASING.md](RELEASING.md) | `scripts/release-manifest.ts`、`scripts/release.ts` |
| 上游远端、同步与许可 | [UPSTREAM.md](UPSTREAM.md) | `scripts/upstream.sh` |
| 唯一现状与门禁矩阵 | [STATUS.md](STATUS.md) | 本仓证据(`docs/mqdh/evidence/`) |
## 任务导航
| 任务 | 必读 | 实现位置 | 验证 |
| --- | --- | --- | --- |
| 本地启动产品 | 本文、[ARCHITECTURE.md](ARCHITECTURE.md) | `scripts/mqdh.mjs` | `pnpm install && pnpm run build`;`node scripts/mqdh.mjs --version` |
| 首次启动/Bootstrap | [BOOTSTRAP.md](BOOTSTRAP.md) | `src/bootstrap/`、`src/cli/` | `node scripts/mqdh.mjs bootstrap --json`、`doctor --json`、`repair --json` |
| Web `/mqdh` 工作台 | [ARCHITECTURE.md](ARCHITECTURE.md) | `src/web/` | `pnpm run build` 后打开 `/mqdh`;状态见 [STATUS.md](STATUS.md) S06 |
| 文稿执行与审批 | [ARCHITECTURE.md](ARCHITECTURE.md)、[STATUS.md](STATUS.md) P 组 | `src/execution/` | `scripts/ci.sh` 的下游测试;真实浏览器审批见 STATUS |
| 阅读桥 | [READER.md](READER.md) | `src/reader/` | `scripts/ci.sh`;View 导出合同回归按 STATUS P09 |
| 私人知识 | [ARCHITECTURE.md](ARCHITECTURE.md) | `src/knowledge/` | `scripts/ci.sh`;状态见 [STATUS.md](STATUS.md) K 组 |
| 生态目录/安装 | [ECOSYSTEM.md](ECOSYSTEM.md)、[MARKET.md](MARKET.md) | `src/ecosystem/`、`src/market/`、`src/tools/` | `node scripts/mqdh.mjs bootstrap --json`;`scripts/ci.sh` |
| 诊断与反馈 | [DIAGNOSTICS.md](DIAGNOSTICS.md) | `src/diagnostics/` | `node scripts/mqdh.mjs report list`;`report submit --confirm` 需显式同意 |
| 发行与更新 | [DISTRIBUTION.md](DISTRIBUTION.md)、[RELEASING.md](RELEASING.md) | `src/distribution/`、`src/release/` | `node scripts/mqdh.mjs update check --json`;tag 上 `bash scripts/package.sh` |
| 上游同步 | [UPSTREAM.md](UPSTREAM.md)、[upstream-delta.md](upstream-delta.md) | `scripts/upstream.sh` | `bash scripts/upstream.sh report`;`candidate <sha>` 仅在真实同步时使用 |
## 关键不变量(安全)
- 凭证只存 `MQDH_HOME/config/credentials.json`(0600);不得写入仓库、日志、诊断报告或模型上下文。诊断/反馈不含凭据、私有知识正文、用户文件或完整会话。
- 唯一默认网络出口:所有自有出站按 [NETWORK.md](NETWORK.md) 经受控代理/镜像/离线策略;运行时模块不得各自 `fetch`。
- 审批一次一授权:文稿执行与生态变更通过 `ctx.approval.request`,模型不能提供 URL/argv/安装根。
- 应用不复制 Marqdo 生产源码;运行时/Bundle/Tool 来自可信发布安装。
- `MQDH_HOME` 与安装树分离;更新只影响新任务,回退目标受保护。
- 对上游文件的修改必须记录在 [upstream-delta.md](upstream-delta.md),并优先使用公开 seam。
- 不建第二套产品规范、包管理、反馈后端或渲染器:正文只在权威文档维护,本文只导航。
## 真实验收入口
```sh
pnpm install --frozen-lockfile
pnpm run build
MQDH_TEST_INSTALL=1 MARQDO_CI_OUT=.ci bash scripts/ci.sh
node scripts/mqdh.mjs --version
node scripts/mqdh.mjs doctor --json
bash scripts/package.sh # tag/发行构建时;含冷安装与 package-evidence.json
```
- 仓库 CI:`.woodpecker/ci.yml`(install/build/test/package;package 仅 tag)。
- 状态与证据:唯一现状是 [STATUS.md](STATUS.md),逐项命令/SHA/摘要见 [evidence/](evidence/)。本入口不复制矩阵、不把 UNVERIFIED 写成 PASS。
## 阅读顺序
本入口 → [STATUS.md](STATUS.md)(现状)→ [ARCHITECTURE.md](ARCHITECTURE.md)(边界)→ 对应能力的权威文档 → `packages/marqdo/harness/src/` 实现 → 对应测试/`docs/mqdh/evidence/`。新增文档只加入 [README.md](README.md) 的列表,不在此复制正文。
+51
View File
@@ -146,6 +146,7 @@ Usage: mqdh <command> [options]
Commands:
bootstrap [--channel stable|beta] [--offline <dir>] [--force] [--json]
status [--json]
doctor [--json]
repair [--json]
report list|show|export|submit|delete|token [...]
@@ -187,6 +188,8 @@ export async function runProductCli(argv: readonly string[], options: CliOptions
switch (parsed.command) {
case 'bootstrap':
return await runBootstrap(parsed, io, runtime)
case 'status':
return await runStatus(parsed, io, runtime)
case 'doctor':
return await runDoctor(parsed, io, runtime)
case 'repair':
@@ -241,6 +244,46 @@ async function runBootstrap(parsed: ParsedCommand, io: CliIO, runtime: () => Pro
return state.status === 'failed' ? 1 : 0
}
/** `mqdh status`: one read-only ecosystem/app version view. */
async function runStatus(parsed: ParsedCommand, io: CliIO, runtime: () => Promise<MdhRuntime>): Promise<number> {
expectNoSubcommand(parsed)
allowFlags(parsed, ['json'])
const app = await runtime()
const status = await app.status()
if (booleanFlag(parsed, 'json')) {
io.stdout(json({
schema: 'marqdo.mqdh.status',
schema_version: 1,
app: { version: APP_VERSION, home: status.home, workspace: status.workspace },
platform: status.platform,
node: status.node,
ecosystem: status.ecosystem,
market: status.market,
knowledge: status.knowledge,
privacy: status.privacy,
}))
return 0
}
const environment = status.ecosystem.current
const version = environment ? `${environment.version} (${environment.id})` : 'not installed'
const tools = status.ecosystem.tools.length === 0
? 'none'
: status.ecosystem.tools.map(tool => `${tool.command} ${tool.version ?? 'unknown'}`).join(', ')
io.stdout([
`app: ${APP_VERSION} home: ${status.home}`,
`workspace: ${status.workspace}`,
`platform: ${status.platform} node: ${status.node}`,
`runtime: ${status.ecosystem.runtime.version ?? 'not installed'}`,
`environment: ${version}`,
`bundle: ${status.ecosystem.std.version ?? 'not installed'} modules=${status.ecosystem.std.modules.length} digest=${status.ecosystem.std.digest ?? 'n/a'}`,
`tools: ${tools}`,
`market: entries=${status.market.entries} installed=${status.market.installed} enabled=${status.market.enabled}`,
`knowledge: collections=${status.knowledge.collections} sources=${status.knowledge.sources} enabled=${status.knowledge.enabled}`,
`privacy: telemetry=${String(status.privacy.telemetry)} session_upload=${String(status.privacy.sessionUpload)} plugin_install=${String(status.privacy.pluginInstall)}`,
].join('\n') + '\n')
return 0
}
/** `mqdh doctor`. */
async function runDoctor(parsed: ParsedCommand, io: CliIO, runtime: () => Promise<MdhRuntime>): Promise<number> {
expectNoSubcommand(parsed)
@@ -389,6 +432,14 @@ async function runUpdate(parsed: ParsedCommand, io: CliIO, runtime: () => Promis
`channel: ${state.channel}`,
`latest: ${state.latest?.version ?? 'none'}${state.latest === null ? '' : ` (${state.latest.signature})`}`,
`update available: ${String(state.update_available)}`,
...(state.latest === null ? [] : [
`published: ${state.latest.published_at}`,
`download: ${state.latest.asset.url}`,
`release: ${state.latest.release_url}`,
...(state.latest.known_limits.length === 0 ? [] : ['known limits:']),
...state.latest.known_limits.map(limit => ` - ${limit}`),
...(state.latest.notes === null ? [] : ['release notes:', ...state.latest.notes.split('\n').map(line => ` ${line}`)]),
]),
...(state.last_error === null ? [] : [`error: ${state.last_error.code}: ${state.last_error.message}`]),
].join('\n') + '\n')
}
+10
View File
@@ -49,6 +49,10 @@ export interface MdhLayout {
readonly capabilityStore: string
readonly capabilityStaging: string
readonly capabilityAudit: string
/** Read-only View reader package cache. */
readonly reader: string
readonly readerPackages: string
readonly readerStaging: string
/** Private knowledge root. */
readonly knowledge: string
/** Imported original knowledge documents. */
@@ -101,6 +105,9 @@ export function layoutOf(home: string): MdhLayout {
capabilityStore: join(root, 'capabilities', 'store'),
capabilityStaging: join(root, 'capabilities', 'staging'),
capabilityAudit: join(root, 'capabilities', 'audit.jsonl'),
reader: join(root, 'reader'),
readerPackages: join(root, 'reader', 'packages'),
readerStaging: join(root, 'reader', 'staging'),
knowledge: join(root, 'knowledge'),
knowledgeSources: join(root, 'knowledge', 'sources'),
knowledgeIndex: join(root, 'knowledge', 'index'),
@@ -136,6 +143,9 @@ export async function ensureMdhHome(home: string): Promise<MdhLayout> {
layout.capabilities,
layout.capabilityStore,
layout.capabilityStaging,
layout.reader,
layout.readerPackages,
layout.readerStaging,
layout.knowledge,
layout.knowledgeSources,
layout.knowledgeIndex,
@@ -52,6 +52,10 @@ export interface UpdateCandidate {
readonly node: string
readonly signature: 'verified' | 'unsigned'
readonly known_limits: readonly string[]
/** Release notes from the trusted release body, or null. */
readonly notes: string | null
/** Official browser URL of the release page. */
readonly release_url: string
}
/** Persisted update state. */
@@ -135,6 +139,8 @@ function candidateOf(candidate: AppReleaseCandidate): UpdateCandidate {
node: candidate.manifest.app.node,
signature: candidate.signature.status,
known_limits: candidate.manifest.known_limits,
notes: candidate.notes,
release_url: candidate.browser_url,
}
}
@@ -185,11 +185,12 @@ export class KnowledgeManager {
if (text === undefined) {
return { schema: COLLECTIONS_SCHEMA, schema_version: 1, collections: [] }
}
const parsed = JSON.parse(text) as CollectionsFile
if (parsed.schema !== COLLECTIONS_SCHEMA || parsed.schema_version !== 1 || !Array.isArray(parsed.collections)) {
const parsed: unknown = JSON.parse(text)
const record = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined
if (record === undefined || record.schema !== COLLECTIONS_SCHEMA || record.schema_version !== 1 || !Array.isArray(record.collections)) {
throw new KnowledgeError('unsupported knowledge collections file')
}
return parsed
return parsed as CollectionsFile
}
/** Persist the collections file. */
@@ -261,6 +262,25 @@ export class KnowledgeManager {
return join(this.#layout.knowledgeSources, id)
}
/** Resolve one imported source to its absolute copy and recorded identity. */
async sourcePath(id: string, relPath: string): Promise<{
root: string
relative: string
absolute: string
digest: string
title: string
} | undefined> {
const collection = await this.collection(id)
if (collection === undefined) return undefined
const relativePath = normalizeSourcePath(relPath)
const known = collection.sources.find(source => source.relPath === relativePath)
if (known === undefined) return undefined
const root = this.sourceRoot(collection.id)
const absolute = join(root, relativePath)
assertWithin(root, absolute, 'knowledge source')
return { root, relative: relativePath, absolute, digest: known.digest, title: known.title }
}
/** Import files or directories. Nothing is written until all candidates pass. */
async import(input: {
collection: string
@@ -279,8 +299,8 @@ export class KnowledgeManager {
if (!info) { rejected.push({ path: selected, reason: 'not found' }); continue }
if (info.isSymbolicLink()) { rejected.push({ path: selected, reason: 'symbolic link is not allowed' }); continue }
const files = info.isDirectory()
? await listRegularFiles(selected, { maxFiles: IMPORT_LIMITS.maxFiles }).catch((error: Error) => {
rejected.push({ path: selected, reason: error.message })
? await listRegularFiles(selected, { maxFiles: IMPORT_LIMITS.maxFiles }).catch((error: unknown) => {
rejected.push({ path: selected, reason: error instanceof Error ? error.message : String(error) })
return []
})
: [{ relative: basename(selected), size: info.size }]
@@ -325,8 +345,8 @@ export class KnowledgeManager {
rejected.push({ path: candidate.relPath, reason: 'document declares an @exec region; import a reviewed static extract instead' })
continue
}
const semantic = await this.#checkExecutable(candidate.bytes, candidate.relPath).catch((error: Error) => {
rejected.push({ path: candidate.relPath, reason: error.message })
const semantic = await this.#checkExecutable(candidate.bytes, candidate.relPath).catch((error: unknown) => {
rejected.push({ path: candidate.relPath, reason: error instanceof Error ? error.message : String(error) })
return 'rejected' as const
})
if (semantic === 'rejected') continue
@@ -425,11 +445,12 @@ export class KnowledgeManager {
async indexState(id: string): Promise<IndexState | undefined> {
const text = await readText(join(this.#layout.knowledgeIndex, id, 'state.json'))
if (text === undefined) return undefined
const parsed = JSON.parse(text) as IndexState
if (parsed.schema !== 'marqdo.mqdh.knowledge-index' || parsed.schema_version !== 1) {
const parsed: unknown = JSON.parse(text)
const record = typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed as Record<string, unknown> : undefined
if (record === undefined || record.schema !== 'marqdo.mqdh.knowledge-index' || record.schema_version !== 1) {
throw new KnowledgeError('unsupported knowledge index state')
}
return parsed
return parsed as IndexState
}
/** Compute the current source-tree digest for one collection. */
@@ -453,8 +474,11 @@ export class KnowledgeManager {
const record = await readJson<Record<string, unknown>>(join(toolHome, 'knowledge', 'record.json'))
if (!record || record.command !== 'knowledge') return undefined
const manifest = await readJson<Record<string, unknown>>(join(toolHome, 'knowledge', 'tool.json'))
const requires = manifest?.requires as Record<string, unknown> | undefined
if (!manifest || requires?.api_revision !== 1 || requires?.analysis !== 3) return undefined
if (manifest === undefined) return undefined
const requires = manifest.requires
if (typeof requires !== 'object' || requires === null || Array.isArray(requires)) return undefined
const requirement = requires as Record<string, unknown>
if (requirement.api_revision !== 1 || requirement.analysis !== 3) return undefined
return { cli, toolHome }
}
@@ -62,6 +62,7 @@ export interface CapabilityView {
readonly tool_registered: boolean
}[]
readonly enabled: readonly CapabilityScope[]
readonly imports: readonly CapabilityImport[]
readonly project_references: readonly string[]
readonly update_available: boolean
readonly latest_version: string | null
@@ -335,6 +336,7 @@ export class CapabilityStore {
tool_registered: item.tool_registered,
})),
enabled: record.enabled,
imports: record.imports,
project_references: this.#references(record, texts),
update_available: isNewer(active?.version ?? null, latest),
latest_version: latest,
@@ -0,0 +1,333 @@
/**
* View embedded-export manifest validation.
*
* View is the only renderer and theme authority. MQDH checks the public
* `marqdo.view-export` manifest, its producer digests, the selected source
* digest and package file digests before serving the package in a sandboxed
* same-origin frame.
*
* @module @marqdo/mqdh-harness/reader/contract
*/
import { lstat } from 'node:fs/promises'
import { join } from 'node:path'
import { digestFile, isWithin } from '../core/fsx.ts'
import { READER_ERROR, ReaderError } from './errors.ts'
/** Reader theme selected by the user. */
export type ReaderTheme = 'light' | 'dark'
/** Source kind accepted by the bridge. */
export type ReaderSourceKind = 'workspace' | 'knowledge'
/** One requested reading surface. */
export interface ReaderRequest {
readonly kind: ReaderSourceKind
/** Workspace-relative path or knowledge source relative path. */
readonly path: string
/** Collection id for a knowledge source. */
readonly collection?: string | undefined
readonly theme?: ReaderTheme | undefined
readonly anchor?: string | undefined
readonly force?: boolean | undefined
}
/** Resolved source identity. */
export interface ReaderSource {
readonly kind: ReaderSourceKind
readonly collection: string | null
readonly root: string
readonly relative: string
readonly absolute: string
/** `sha256:<hex>` digest of the exact source bytes. */
readonly digest: string
readonly title: string | null
}
/** Installed View Tool identity from the active Runtime. */
export interface ReaderViewTool {
readonly command: 'view'
readonly version: string | null
readonly path: string
readonly entrypoint: string
readonly binaryPath: string
/** Bare lowercase hex SHA-256 of the View executable. */
readonly binarySha256: string
readonly sourceSha: string | null
}
/** One validated file of an embedded package. */
export interface ReaderPackageFile {
readonly path: string
readonly sha256: string
}
/** Cache metadata for one embedded package. */
export interface ReaderPackageMeta {
readonly schema: 'marqdo.mqdh.reader-package'
readonly schema_version: 1
readonly id: string
readonly created_at: string
readonly source: {
readonly kind: ReaderSourceKind
readonly collection: string | null
readonly relative: string
readonly digest: string
readonly title: string | null
}
readonly theme: ReaderTheme
readonly anchor: string | null
readonly entry: {
readonly href: string
readonly file: string
readonly heading_ids: readonly string[]
readonly relative_path: string
}
readonly view: {
readonly version: string | null
readonly binary_sha256: string
readonly source_sha: string | null
}
readonly cli: {
readonly version: string | null
readonly binary_sha256: string
}
readonly manifest_sha256: string
readonly files: readonly ReaderPackageFile[]
readonly assets: readonly ReaderPackageFile[]
}
/** Reader package returned to the workbench. */
export interface ReaderPackage {
readonly id: string
readonly source: ReaderPackageMeta['source']
readonly theme: ReaderTheme
readonly anchor: string | null
readonly entry_href: string
readonly heading_ids: readonly string[]
readonly view: ReaderPackageMeta['view']
readonly cli: ReaderPackageMeta['cli']
readonly manifest_sha256: string
readonly created_at: string
readonly cached: boolean
readonly package_url: string
}
/** Expected identities one manifest must match. */
export interface ViewManifestExpectation {
readonly sourceSha256: string
readonly viewBinarySha256: string
readonly cliBinarySha256: string
readonly theme: ReaderTheme
readonly anchor: string | null
readonly relativePath: string
}
/** Parsed View manifest values the bridge consumes. */
export interface ViewManifest {
readonly schemaVersion: number
readonly mode: string
readonly theme: ReaderTheme
readonly executed: boolean
readonly requires: Record<string, unknown>
readonly producers: Record<string, unknown>
readonly entry: {
readonly href: string
readonly file: string
readonly heading_ids: readonly string[]
readonly relative_path: string
readonly anchor: string | null
readonly sha256: string
}
readonly pages: readonly {
readonly source_sha256: string
readonly source_status: string
readonly relative_path: string
readonly sha256: string
}[]
readonly files: readonly ReaderPackageFile[]
readonly assets: readonly ReaderPackageFile[]
}
/** Read a plain object or throw a manifest error. */
function objectOf(value: unknown, label: string): Record<string, unknown> {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} must be an object`)
}
return value as Record<string, unknown>
}
/** Read a required string. */
function stringOf(record: Record<string, unknown>, key: string, label: string): string {
const value = record[key]
if (typeof value !== 'string' || value === '') throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a non-empty string`)
return value
}
/** Read an optional string. */
function optionalString(record: Record<string, unknown>, key: string, label: string): string | null {
const value = record[key]
if (value === undefined || value === null) return null
if (typeof value !== 'string') throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a string`)
return value
}
/** Read a required digest as bare lowercase hex. */
function digestOf(record: Record<string, unknown>, key: string, label: string): string {
const value = record[key]
if (typeof value !== 'string') throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a digest`)
const match = /^(?:sha256:)?([0-9a-f]{64})$/.exec(value)
if (match?.[1] === undefined) throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be a SHA-256 digest`)
return match[1]
}
/** Read one file list with path and digest. */
function fileList(record: Record<string, unknown>, key: string, label: string): ReaderPackageFile[] {
const value = record[key]
if (value === undefined || value === null) return []
if (!Array.isArray(value)) throw new ReaderError(READER_ERROR.manifestInvalid, `${label}.${key} must be an array`)
return value.map((item, index) => {
const file = objectOf(item, `${label}.${key}[${index}]`)
const path = stringOf(file, 'path', `${label}.${key}[${index}]`)
assertPackagePath(path, `${label}.${key}[${index}].path`)
return {
path,
sha256: digestOf(file, 'sha256', `${label}.${key}[${index}]`),
}
})
}
/** Reject a package-relative path that could escape or execute. */
export function assertPackagePath(path: string, label: string): void {
if (path === '' || path.startsWith('/') || /^[A-Za-z]:/.test(path) || path.includes('\\') || path.includes('\0')) {
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} is not a package-relative path: ${path}`)
}
const segments = path.split('/')
if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} is not a safe package path: ${path}`)
}
if (/\.(?:m?js|jsx|ts|tsx)$/i.test(path)) {
throw new ReaderError(READER_ERROR.manifestInvalid, `${label} must not contain scripts: ${path}`)
}
}
/** Parse one `marqdo.view-export` manifest. */
export function parseViewManifest(value: unknown): ViewManifest {
const record = objectOf(value, 'manifest')
const schemaVersion = record.schema_version
if (record.schema !== 'marqdo.view-export' || schemaVersion !== 1) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'unsupported View export schema')
}
const theme = stringOf(record, 'theme', 'manifest')
if (theme !== 'light' && theme !== 'dark') throw new ReaderError(READER_ERROR.manifestInvalid, `unknown View theme: ${theme}`)
const entry = objectOf(record.entry, 'manifest.entry')
const rawPages = record.pages
if (!Array.isArray(rawPages) || rawPages.length !== 1) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'embedded export must contain exactly one page')
}
const page = objectOf(rawPages[0], 'manifest.pages[0]')
const rawHeadingIds = entry.heading_ids
if (!Array.isArray(rawHeadingIds) || !rawHeadingIds.every(item => typeof item === 'string')) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'manifest.entry.heading_ids must be a string array')
}
return {
schemaVersion,
mode: stringOf(record, 'mode', 'manifest'),
theme,
executed: record.executed === true,
requires: objectOf(record.requires, 'manifest.requires'),
producers: objectOf(record.producers, 'manifest.producers'),
entry: {
href: stringOf(entry, 'href', 'manifest.entry'),
file: stringOf(entry, 'file', 'manifest.entry'),
heading_ids: rawHeadingIds,
relative_path: stringOf(entry, 'relative_path', 'manifest.entry'),
anchor: optionalString(entry, 'anchor', 'manifest.entry'),
sha256: digestOf(entry, 'sha256', 'manifest.entry'),
},
pages: [{
source_sha256: digestOf(page, 'source_sha256', 'manifest.pages[0]'),
source_status: stringOf(page, 'source_status', 'manifest.pages[0]'),
relative_path: stringOf(page, 'relative_path', 'manifest.pages[0]'),
sha256: digestOf(page, 'sha256', 'manifest.pages[0]'),
}],
files: fileList(record, 'files', 'manifest'),
assets: fileList(record, 'assets', 'manifest'),
}
}
/** Validate the manifest against the exact source, Tool and CLI identities. */
export function validateViewManifest(manifest: ViewManifest, expected: ViewManifestExpectation): void {
if (manifest.mode !== 'embedded') throw new ReaderError(READER_ERROR.manifestInvalid, `View export mode is ${manifest.mode}, expected embedded`)
if (manifest.executed) throw new ReaderError(READER_ERROR.manifestInvalid, 'View embed manifest claims execution')
if (manifest.theme !== expected.theme) throw new ReaderError(READER_ERROR.manifestInvalid, 'View theme does not match the request')
if (manifest.requires.api_revision !== 1 || manifest.requires.analysis !== 3 || manifest.requires.observation !== 1) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export requires an unsupported protocol revision')
}
if (manifest.requires.markdown_profile !== 'marqdo.md.v1') {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export markdown profile is not marqdo.md.v1')
}
const viewProducer = objectOf(manifest.producers.view, 'manifest.producers.view')
if (digestOf(viewProducer, 'binary_sha256', 'manifest.producers.view') !== expected.viewBinarySha256) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View producer digest does not match the installed Tool')
}
const cliProducer = manifest.producers.cli
if (cliProducer !== null && cliProducer !== undefined) {
const cli = objectOf(cliProducer, 'manifest.producers.cli')
if (digestOf(cli, 'binary_sha256', 'manifest.producers.cli') !== expected.cliBinarySha256) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'CLI producer digest does not match the active Runtime')
}
}
const page = manifest.pages[0]
if (page === undefined) throw new ReaderError(READER_ERROR.manifestInvalid, 'View export has no page')
if (page.source_sha256 !== expected.sourceSha256) {
throw new ReaderError(READER_ERROR.sourceChanged, 'View export source digest does not match the selected document')
}
if (page.source_status !== 'static-ok' && page.source_status !== 'markdown-only') {
throw new ReaderError(READER_ERROR.manifestInvalid, `unexpected View source status: ${page.source_status}`)
}
if (manifest.entry.relative_path !== expected.relativePath || page.relative_path !== expected.relativePath) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export entry path does not match the request')
}
assertPackagePath(manifest.entry.file, 'manifest.entry.file')
assertPackagePath(manifest.entry.href.split('#')[0] ?? '', 'manifest.entry.href')
if (manifest.entry.anchor !== expected.anchor) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export anchor does not match the request')
}
if (expected.anchor !== null && !manifest.entry.heading_ids.includes(expected.anchor)) {
throw new ReaderError(READER_ERROR.anchorMissing, `requested anchor does not exist: ${expected.anchor}`)
}
if (expected.anchor === null && manifest.entry.href !== manifest.entry.file) {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View export has an unexpected entry fragment')
}
}
/**
* Verify every package file digest and ensure the entry file is listed.
* @param packageRoot - extracted package directory.
* @param manifest - validated manifest.
* @returns the verified file list.
*/
export async function verifyPackageFiles(packageRoot: string, manifest: ViewManifest): Promise<ReaderPackageFile[]> {
const all = [...manifest.files, ...manifest.assets]
const seen = new Set<string>()
let total = 0
for (const file of all) {
assertPackagePath(file.path, 'package file')
if (seen.has(file.path)) throw new ReaderError(READER_ERROR.manifestInvalid, `duplicate package file: ${file.path}`)
seen.add(file.path)
const target = join(packageRoot, file.path)
if (!isWithin(packageRoot, target)) throw new ReaderError(READER_ERROR.packageInvalid, `package file escapes its root: ${file.path}`)
const info = await lstat(target).catch(() => undefined)
if (info === undefined || !info.isFile() || info.isSymbolicLink()) {
throw new ReaderError(READER_ERROR.packageInvalid, `package file is not a regular file: ${file.path}`)
}
if (info.size > 16 * 1024 * 1024) throw new ReaderError(READER_ERROR.packageInvalid, `package file exceeds its size limit: ${file.path}`)
total += info.size
if (total > 64 * 1024 * 1024) throw new ReaderError(READER_ERROR.packageInvalid, 'package exceeds its total size limit')
const actual = await digestFile(target)
if (actual !== `sha256:${file.sha256}`) throw new ReaderError(READER_ERROR.packageInvalid, `package file digest mismatch: ${file.path}`)
}
if (!seen.has(manifest.entry.file)) throw new ReaderError(READER_ERROR.manifestInvalid, 'entry file is not listed in the package')
return all
}
@@ -0,0 +1,38 @@
/**
* Reader bridge failure codes.
*
* Opening a reader package performs a static View export (a CLI `check` and
* local HTML write) but never executes the document. Failures keep their own
* code so the workbench can distinguish a missing Tool, a source change, an
* invalid anchor and an untrusted package.
*
* @module @marqdo/mqdh-harness/reader/errors
*/
/** Reader failure with a stable local code. */
export class ReaderError extends Error {
override name = 'ReaderError'
readonly code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
/** Canonical reader failure codes. */
export const READER_ERROR = {
viewMissing: 'reader.view_missing',
cliMissing: 'reader.cli_missing',
sourceInvalid: 'reader.source_invalid',
sourceChanged: 'reader.source_changed',
anchorMissing: 'reader.anchor_missing',
exportFailed: 'reader.export_failed',
manifestInvalid: 'reader.manifest_invalid',
packageMissing: 'reader.package_missing',
packageInvalid: 'reader.package_invalid',
knowledgeSourceMissing: 'reader.knowledge_source_missing',
} as const
/** One canonical reader failure code. */
export type ReaderErrorCode = (typeof READER_ERROR)[keyof typeof READER_ERROR]
@@ -0,0 +1,402 @@
/**
* Read-only View reader bridge.
*
* One bridge runs the installed View Tool's public `export --embed` command,
* validates the resulting package manifest and producer identities, caches the
* package by source/Tool/theme identity and serves package files for a
* sandboxed same-origin iframe. The bridge never renders Markdown, copies View
* CSS or executes the document.
*
* @module @marqdo/mqdh-harness/reader/service
*/
import { createHash, randomBytes } from 'node:crypto'
import { lstat, mkdir, readFile, realpath, rename, rm } from 'node:fs/promises'
import { dirname, extname, join, relative as relativePath } from 'node:path'
import { digestBytes, digestFile, isDirectory, isFile, isWithin, readJson, writeJsonAtomic } from '../core/fsx.ts'
import type { MdhLayout } from '../core/home.ts'
import { withLock } from '../core/lock.ts'
import { runProcess } from '../core/process.ts'
import type { MarqdoCli } from '../execution/cli.ts'
import { resolveDocument } from '../workspace.ts'
import {
assertPackagePath, parseViewManifest, validateViewManifest, verifyPackageFiles,
} from './contract.ts'
import type {
ReaderPackage, ReaderPackageFile, ReaderPackageMeta, ReaderRequest, ReaderSource, ReaderTheme,
ReaderViewTool, ViewManifest,
} from './contract.ts'
import { READER_ERROR, ReaderError } from './errors.ts'
/** Reader bridge dependencies. */
export interface ReaderServiceOptions {
readonly layout: MdhLayout
readonly cli: () => Promise<MarqdoCli | undefined>
readonly toolHome: () => Promise<string | undefined>
readonly viewTool: () => Promise<ReaderViewTool | undefined>
readonly workspace: () => string
readonly knowledgeSource: (collection: string, path: string) => Promise<ReaderSource | undefined>
}
/** Reader availability projection. */
export interface ReaderStatus {
readonly available: boolean
readonly view: {
readonly version: string | null
readonly path: string
readonly binary_sha256: string
readonly source_sha: string | null
} | null
readonly cli: { readonly version: string | null } | null
readonly error: string | null
}
/** Project source text result. */
export interface ReaderSourceText {
readonly kind: 'workspace' | 'knowledge'
readonly collection: string | null
readonly path: string
readonly digest: string
readonly text: string
readonly truncated: boolean
}
/** One served package file. */
export interface ReaderPackageFileBody {
readonly path: string
readonly contentType: string
readonly body: Buffer
}
/** The reader bridge. */
export class ReaderService {
readonly #layout: MdhLayout
readonly #cli: ReaderServiceOptions['cli']
readonly #toolHome: ReaderServiceOptions['toolHome']
readonly #viewTool: ReaderServiceOptions['viewTool']
readonly #workspace: ReaderServiceOptions['workspace']
readonly #knowledgeSource: ReaderServiceOptions['knowledgeSource']
constructor(options: ReaderServiceOptions) {
this.#layout = options.layout
this.#cli = options.cli
this.#toolHome = options.toolHome
this.#viewTool = options.viewTool
this.#workspace = options.workspace
this.#knowledgeSource = options.knowledgeSource
}
/** Read the current View/CLI availability without running either. */
async status(): Promise<ReaderStatus> {
const view = await this.#viewTool().catch(() => undefined)
if (view === undefined) {
return { available: false, view: null, cli: null, error: 'installed View Tool is required for the reader' }
}
const cli = await this.#cli().catch(() => undefined)
return {
available: cli !== undefined,
view: {
version: view.version,
path: view.binaryPath,
binary_sha256: view.binarySha256,
source_sha: view.sourceSha,
},
cli: cli === undefined ? null : { version: cli.version ?? null },
error: cli === undefined ? 'active Marqdo Runtime is required for the reader' : null,
}
}
/** Resolve one workspace or knowledge source to its exact bytes and root. */
async #source(request: ReaderRequest): Promise<ReaderSource> {
if (request.kind === 'workspace') {
const workspace = this.#workspace()
let absolute: string
try {
absolute = await resolveDocument(workspace, request.path)
} catch (error) {
throw new ReaderError(READER_ERROR.sourceInvalid, error instanceof Error ? error.message : String(error))
}
const digest = await digestFile(absolute)
return {
kind: 'workspace',
collection: null,
root: workspace,
relative: relativePath(workspace, absolute).split('\\').join('/'),
absolute,
digest,
title: null,
}
}
const collection = request.collection?.trim()
if (collection === undefined || collection === '') {
throw new ReaderError(READER_ERROR.sourceInvalid, 'knowledge reading requires a collection id')
}
const source = await this.#knowledgeSource(collection, request.path).catch(() => undefined)
if (source === undefined) throw new ReaderError(READER_ERROR.knowledgeSourceMissing, `unknown knowledge source: ${collection}/${request.path}`)
return source
}
/** Build the cache identity for one request. */
#cacheId(source: ReaderSource, view: ReaderViewTool, cliSha256: string, theme: ReaderTheme, anchor: string | null): string {
return createHash('sha256').update(JSON.stringify({
schema: 1,
kind: source.kind,
collection: source.collection,
root: source.root,
relative: source.relative,
source: source.digest,
view: view.binarySha256,
cli: cliSha256,
theme,
anchor,
})).digest('hex')
}
/** Read valid cache metadata or return undefined. */
async #cachedMeta(
id: string,
source: ReaderSource,
view: ReaderViewTool,
theme: ReaderTheme,
anchor: string | null,
): Promise<ReaderPackageMeta | undefined> {
const raw = await readJson<unknown>(join(this.#layout.readerPackages, `${id}.json`)).catch(() => undefined)
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
const record = raw as Record<string, unknown>
if (record.schema !== 'marqdo.mqdh.reader-package' || record.schema_version !== 1) return undefined
try {
const meta = raw as ReaderPackageMeta
if (meta.id !== id || meta.theme !== theme || meta.anchor !== anchor) return undefined
if (meta.source.digest !== source.digest || meta.source.relative !== source.relative) return undefined
if (meta.view.binary_sha256 !== view.binarySha256) return undefined
if (!(await isDirectory(join(this.#layout.readerPackages, id)))) return undefined
return meta
} catch (error) {
void error
return undefined
}
}
/** Render a cache hit. */
#packageFromMeta(meta: ReaderPackageMeta, cached: boolean): ReaderPackage {
return {
id: meta.id,
source: meta.source,
theme: meta.theme,
anchor: meta.anchor,
entry_href: meta.entry.href,
heading_ids: meta.entry.heading_ids,
view: meta.view,
cli: meta.cli,
manifest_sha256: meta.manifest_sha256,
created_at: meta.created_at,
cached,
package_url: `/mqdh/api/reader/package/${meta.id}/${meta.entry.href}`,
}
}
/** Expand a View failure into a stable reader error. */
#exportFailure(error: Error, anchor: string | null): ReaderError {
const message = error.message.slice(0, 600)
if (anchor !== null && /anchor|heading/i.test(message)) return new ReaderError(READER_ERROR.anchorMissing, message)
if (/source.*sha|expect-source|digest/i.test(message)) return new ReaderError(READER_ERROR.sourceChanged, message)
return new ReaderError(READER_ERROR.exportFailed, message)
}
/**
* Open one read-only package. A cache miss runs the installed View Tool with a
* fixed argv; the document is statically checked, never executed.
* @param request - source, theme and optional anchor.
* @returns the validated package and its same-origin URL.
*/
async open(request: ReaderRequest): Promise<ReaderPackage> {
const theme: ReaderTheme = request.theme ?? 'light'
const anchor = request.anchor?.trim() || null
const view = await this.#viewTool()
if (view === undefined) throw new ReaderError(READER_ERROR.viewMissing, 'install the View Tool to read documents')
const cli = await this.#cli()
if (cli === undefined) throw new ReaderError(READER_ERROR.cliMissing, 'install a Marqdo Runtime to read documents')
const toolHome = await this.#toolHome()
if (toolHome === undefined) throw new ReaderError(READER_ERROR.cliMissing, 'active Runtime has no Tool home')
const cliSha256 = (await digestFile(cli.bin)).slice('sha256:'.length)
const source = await this.#source(request)
const sourceSha256 = source.digest.slice('sha256:'.length)
const id = this.#cacheId(source, view, cliSha256, theme, anchor)
return await withLock(join(this.#layout.reader, 'open.lock'), async () => {
if (request.force !== true) {
const cached = await this.#cachedMeta(id, source, view, theme, anchor)
if (cached !== undefined) return this.#packageFromMeta(cached, true)
}
const output = join(this.#layout.readerStaging, `open-${id.slice(0, 12)}-${randomBytes(4).toString('hex')}`)
await mkdir(dirname(output), { recursive: true, mode: 0o700 })
try {
const args = [
'view', 'export', source.relative, '--out', output, '--embed',
'--theme', theme, '--expect-source-sha256', sourceSha256,
...(anchor === null ? [] : ['--anchor', anchor]),
]
const run = await runProcess(cli.bin, args, {
cwd: source.root,
env: { MARQDO_TOOL_HOME: toolHome },
limits: { timeoutMs: 120_000, maxOutputBytes: 2 * 1024 * 1024 },
})
if (run.exitCode !== 0) {
throw this.#exportFailure(new Error(run.stderr.trim() || run.stdout.trim() || `view export exited ${run.exitCode}`), anchor)
}
const manifestBytes = await readFile(join(output, 'manifest.json')).catch(() => undefined)
if (manifestBytes === undefined) throw new ReaderError(READER_ERROR.manifestInvalid, 'View export produced no manifest.json')
let raw: unknown
try {
raw = JSON.parse(manifestBytes.toString('utf8'))
} catch {
throw new ReaderError(READER_ERROR.manifestInvalid, 'View manifest is not valid JSON')
}
const manifest = parseViewManifest(raw)
validateViewManifest(manifest, {
sourceSha256,
viewBinarySha256: view.binarySha256,
cliBinarySha256: cliSha256,
theme,
anchor,
relativePath: source.relative,
})
const files = await verifyPackageFiles(output, manifest)
const packageRoot = join(this.#layout.readerPackages, id)
await rm(packageRoot, { recursive: true, force: true })
await rename(output, packageRoot)
const meta: ReaderPackageMeta = {
schema: 'marqdo.mqdh.reader-package',
schema_version: 1,
id,
created_at: new Date().toISOString(),
source: {
kind: source.kind,
collection: source.collection,
relative: source.relative,
digest: source.digest,
title: source.title,
},
theme,
anchor,
entry: {
href: manifest.entry.href,
file: manifest.entry.file,
heading_ids: manifest.entry.heading_ids,
relative_path: manifest.entry.relative_path,
},
view: {
version: view.version,
binary_sha256: view.binarySha256,
source_sha: view.sourceSha,
},
cli: { version: cli.version ?? null, binary_sha256: cliSha256 },
manifest_sha256: digestBytes(manifestBytes).slice('sha256:'.length),
files: files.filter(file => manifest.files.some(item => item.path === file.path)),
assets: files.filter(file => manifest.assets.some(item => item.path === file.path)),
}
await writeJsonAtomic(join(this.#layout.readerPackages, `${id}.json`), meta, 0o600)
return this.#packageFromMeta(meta, false)
} catch (error) {
await rm(output, { recursive: true, force: true }).catch(() => undefined)
if (error instanceof ReaderError) throw error
throw new ReaderError(READER_ERROR.exportFailed, error instanceof Error ? error.message : String(error))
}
})
}
/**
* Read the selected source text without invoking View.
* @param request - workspace or knowledge source.
* @returns bounded UTF-8 source text and its digest.
*/
async source(request: ReaderRequest): Promise<ReaderSourceText> {
const source = await this.#source(request)
const bytes = await readFile(source.absolute)
const max = 256 * 1024
const slice = bytes.byteLength > max ? bytes.subarray(0, max) : bytes
return {
kind: source.kind,
collection: source.collection,
path: source.relative,
digest: source.digest,
text: slice.toString('utf8'),
truncated: bytes.byteLength > max,
}
}
/**
* Resolve one file of a cached package for the same-origin route.
* @param id - package cache id.
* @param path - package-relative path.
* @returns the file body and content type.
*/
async packageFile(id: string, path: string): Promise<ReaderPackageFileBody> {
if (!/^[a-f0-9]{64}$/.test(id)) throw new ReaderError(READER_ERROR.packageInvalid, 'invalid reader package id')
assertPackagePath(path, 'reader package path')
const meta = await readJson<ReaderPackageMeta>(join(this.#layout.readerPackages, `${id}.json`))
if (meta === undefined) throw new ReaderError(READER_ERROR.packageMissing, 'reader package is missing')
const allowed = new Set([...meta.files.map(file => file.path), ...meta.assets.map(file => file.path), meta.entry.file])
if (!allowed.has(path)) throw new ReaderError(READER_ERROR.packageInvalid, `file is not listed in the package manifest: ${path}`)
const root = join(this.#layout.readerPackages, id)
const target = join(root, path)
if (!isWithin(root, target)) throw new ReaderError(READER_ERROR.packageInvalid, 'package path escapes its root')
const info = await lstat(target).catch(() => undefined)
if (info === undefined || !info.isFile() || info.isSymbolicLink()) throw new ReaderError(READER_ERROR.packageInvalid, 'package file is not a regular file')
if (info.size > 16 * 1024 * 1024) throw new ReaderError(READER_ERROR.packageInvalid, 'package file is too large')
const canonical = await realpath(target).catch(() => undefined)
if (canonical === undefined || !isWithin(await realpath(root), canonical)) throw new ReaderError(READER_ERROR.packageInvalid, 'package file resolves outside its root')
return { path, contentType: contentTypeOf(path), body: await readFile(canonical) }
}
/** Whether one package file identity is already cached. */
async cachedFile(id: string, path: string): Promise<ReaderPackageFile | undefined> {
const meta = await readJson<ReaderPackageMeta>(join(this.#layout.readerPackages, `${id}.json`)).catch(() => undefined)
return meta?.files.find(file => file.path === path) ?? meta?.assets.find(file => file.path === path)
}
/** Remove one cached package or all packages. */
async clear(id?: string): Promise<void> {
if (id === undefined) {
await rm(this.#layout.readerPackages, { recursive: true, force: true })
await mkdir(this.#layout.readerPackages, { recursive: true, mode: 0o700 })
return
}
if (!/^[a-f0-9]{64}$/.test(id)) throw new ReaderError(READER_ERROR.packageInvalid, 'invalid reader package id')
await rm(join(this.#layout.readerPackages, id), { recursive: true, force: true })
await rm(join(this.#layout.readerPackages, `${id}.json`), { force: true })
}
/** Whether a package directory exists (used by tests and diagnostics). */
async hasPackage(id: string): Promise<boolean> {
return await isFile(join(this.#layout.readerPackages, `${id}.json`)) && await isDirectory(join(this.#layout.readerPackages, id))
}
/** Read a package manifest for diagnostics. */
async manifest(id: string): Promise<ViewManifest | undefined> {
const path = join(this.#layout.readerPackages, id, 'manifest.json')
const parsed = await readJson<unknown>(path).catch(() => undefined)
if (parsed === undefined) return undefined
return parseViewManifest(parsed)
}
}
/** Map package file extensions to response content types. */
export function contentTypeOf(path: string): string {
switch (extname(path).toLowerCase()) {
case '.html': return 'text/html; charset=utf-8'
case '.css': return 'text/css; charset=utf-8'
case '.svg': return 'image/svg+xml'
case '.png': return 'image/png'
case '.jpg':
case '.jpeg': return 'image/jpeg'
case '.webp': return 'image/webp'
case '.gif': return 'image/gif'
case '.ttf': return 'font/ttf'
case '.otf': return 'font/otf'
case '.woff': return 'font/woff'
case '.woff2': return 'font/woff2'
case '.txt': return 'text/plain; charset=utf-8'
case '.md': return 'text/markdown; charset=utf-8'
default: return 'application/octet-stream'
}
}
@@ -38,6 +38,8 @@ export interface GiteaRelease {
readonly prerelease: boolean
readonly draft: boolean
readonly target_commitish: string | null
/** Release notes authored in the trusted Gitea release, truncated. */
readonly body: string | null
readonly assets: readonly GiteaAsset[]
}
@@ -72,11 +74,15 @@ function parseRelease(raw: unknown): GiteaRelease {
const record = raw as Record<string, unknown>
if (typeof record.tag_name !== 'string') throw new GiteaError('invalid_response', 'release has no tag_name')
const assets = Array.isArray(record.assets) ? record.assets.map(parseAsset) : []
const body = typeof record.body === 'string' && record.body.trim() !== ''
? record.body.slice(0, 8192)
: null
return {
tag_name: record.tag_name,
prerelease: record.prerelease === true,
draft: record.draft === true,
target_commitish: typeof record.target_commitish === 'string' ? record.target_commitish : null,
body,
assets,
}
}
@@ -131,6 +137,8 @@ export interface AppReleaseCandidate {
readonly asset: { readonly name: string; readonly url: string; readonly size: number; readonly sha256: string }
readonly manifest_url: string
readonly browser_url: string
/** Release notes from the release body, or null when absent. */
readonly notes: string | null
}
/** Read a detached signature asset when the release publishes one. */
@@ -258,6 +266,7 @@ async function inspectRelease(
},
manifest_url: manifestAsset.browser_download_url,
browser_url: `${authority}/${repository}/releases/tag/${release.tag_name}`,
notes: release.body,
}
}
+68 -2
View File
@@ -10,12 +10,15 @@
import { readFile, stat } from 'node:fs/promises'
import { isAbsolute, join, resolve } from 'node:path'
import { digestFile } from './core/fsx.ts'
import { digestFile, isWithin, readJson, readText } from './core/fsx.ts'
import { ensureMdhHome, resolveMdhHome } from './core/home.ts'
import type { MdhLayout } from './core/home.ts'
import { EcosystemManager } from './ecosystem/manager.ts'
import type { EcosystemStatus } from './ecosystem/manager.ts'
import { EvidenceStore } from './execution/evidence.ts'
import { ReaderService } from './reader/service.ts'
import type { ReaderSourceText, ReaderStatus } from './reader/service.ts'
import type { ReaderPackage, ReaderViewTool } from './reader/contract.ts'
import type { RunEvidence, RunRecord } from './execution/evidence.ts'
import { MarqdoCli } from './execution/cli.ts'
import type { CheckedDocument, ExecutedDocument, Grants, SandboxMode } from './execution/cli.ts'
@@ -109,6 +112,7 @@ export class MdhRuntime {
readonly bootstrap: BootstrapManager
readonly updater: AppUpdater
readonly knowledge: KnowledgeManager
readonly reader: ReaderService
readonly evidence: EvidenceStore
readonly #cliCache = new Map<string, { cli: MarqdoCli }>()
readonly #analysisCache = new Map<string, CheckedDocument>()
@@ -152,6 +156,29 @@ export class MdhRuntime {
return environment ? join(this.layout.environments, environment.id, environment.tool_home) : undefined
},
})
this.reader = new ReaderService({
layout,
cli: () => this.cli(),
toolHome: async () => {
const environment = await this.ecosystem.current()
return environment ? join(layout.environments, environment.id, environment.tool_home) : undefined
},
viewTool: () => this.#viewTool(),
workspace: () => this.workspace,
knowledgeSource: async (collection, path) => {
const source = await this.knowledge.sourcePath(collection, path)
if (source === undefined) return undefined
return {
kind: 'knowledge',
collection,
root: source.root,
relative: source.relative,
absolute: source.absolute,
digest: source.digest,
title: source.title,
}
},
})
}
/**
@@ -167,7 +194,7 @@ export class MdhRuntime {
}
/** Configured workspace override applied at runtime (Web settings). */
async setWorkspace(workspace: string): Promise<void> {
setWorkspace(workspace: string): void {
if (!isAbsolute(workspace)) throw new Error('workspace must be an absolute path')
this.workspace = resolve(workspace)
}
@@ -204,6 +231,45 @@ export class MdhRuntime {
return await readProjectDependencies(this.workspace)
}
/** Installed View Tool identity used by the reader bridge. */
async #viewTool(): Promise<ReaderViewTool | undefined> {
const status = await this.ecosystem.status()
const tool = status.tools.find(candidate => candidate.command === 'view')
if (tool === undefined) return undefined
const record = await readJson<Record<string, unknown>>(join(tool.path, 'record.json'))
if (record === undefined || typeof record.entrypoint !== 'string' || record.entrypoint === '') return undefined
const binaryPath = join(tool.path, record.entrypoint)
if (!isWithin(tool.path, binaryPath)) return undefined
const info = await stat(binaryPath).catch(() => undefined)
if (info === undefined || !info.isFile()) return undefined
const digest = await digestFile(binaryPath)
const sourceSha = (await readText(join(tool.path, 'SOURCE_SHA')))?.trim() || null
return {
command: 'view',
version: typeof record.version === 'string' ? record.version : tool.version,
path: tool.path,
entrypoint: record.entrypoint,
binaryPath,
binarySha256: digest.slice('sha256:'.length),
sourceSha,
}
}
/** Reader availability and installed View/CLI identity. */
async readerStatus(): Promise<ReaderStatus> {
return await this.reader.status()
}
/** Open one read-only View package for a workspace or knowledge source. */
async openReader(request: Parameters<ReaderService['open']>[0]): Promise<ReaderPackage> {
return await this.reader.open(request)
}
/** Read source text for the reader's source toggle. */
async readerSource(request: Parameters<ReaderService['source']>[0]): Promise<ReaderSourceText> {
return await this.reader.source(request)
}
/** Installed capabilities visible to one agent/session scope. */
async visibleCapabilities(sessionId: string | null): Promise<VisibleCapability[]> {
return await this.capabilities.visible(sessionId, this.workspace)
+109 -1
View File
@@ -45,6 +45,7 @@ export const APP_HTML = `<!doctype html>
<button role="tab" data-tab="knowledge" aria-selected="true">私人知识</button>
<button role="tab" data-tab="ecosystem">生态中心</button>
<button role="tab" data-tab="document">文稿检查</button>
<button role="tab" data-tab="reader">文稿阅读</button>
<button role="tab" data-tab="runs">运行记录</button>
<button role="tab" data-tab="bootstrap">首次启动</button>
<button role="tab" data-tab="update">更新与出口</button>
@@ -162,6 +163,27 @@ export const APP_HTML = `<!doctype html>
<div id="document-result" class="results"></div>
</section>
<section id="tab-reader" class="panel" role="tabpanel" hidden>
<h2>文稿阅读</h2>
<p class="muted">正文由已安装 View Tool 的公开 <code>export --embed</code> 生成;标题、公式、表格、主题与媒体来自同一 View 制品。打开只做静态检查与本地导出,不执行文稿,也不联网。</p>
<form id="reader-form" class="form inline">
<label>工作区相对路径<input name="path" placeholder="index.mq.md" required autocomplete="off"></label>
<label>主题<select name="theme"><option value="light">light</option><option value="dark">dark</option></select></label>
<label>锚点(可选)<input name="anchor" placeholder="heading-id" autocomplete="off"></label>
<button type="submit">只读打开</button>
</form>
<div id="reader-status" class="card" aria-live="polite">尚未打开文稿。</div>
<div class="reader-toolbar">
<button id="reader-source-toggle" class="ghost" type="button" disabled>查看源码</button>
<button id="reader-runs" class="ghost" type="button">查看运行记录</button>
<span id="reader-identity" class="muted"></span>
</div>
<div class="reader-frame">
<iframe id="reader-frame" title="View 只读阅读" sandbox="allow-same-origin" referrerpolicy="no-referrer"></iframe>
</div>
<pre id="reader-source-text" class="code" hidden></pre>
</section>
<section id="tab-runs" class="panel" role="tabpanel" hidden>
<h2>运行记录</h2>
<p class="muted">记录绑定源文稿摘要、Analysis、CLI/Bundle 身份与 Observation 终态;源变更后标记为过期。</p>
@@ -287,6 +309,9 @@ button:disabled { opacity: 0.55; cursor: progress; }
.code { background: #26241f; color: #f3efe5; border-radius: 0.6rem; padding: 0.9rem; overflow: auto; font-size: 0.8rem; max-height: 32rem; }
.error { color: var(--danger); min-height: 1.5rem; }
.foot { text-align: center; color: var(--muted); font-size: 0.8rem; padding: 1rem; border-top: 1px solid var(--line); }
.reader-toolbar { display: flex; gap: 0.6rem; align-items: center; flex-wrap: wrap; margin: 0.7rem 0; }
.reader-frame { border: 1px solid var(--line); border-radius: 0.6rem; overflow: hidden; background: #fff; }
.reader-frame iframe { display: block; width: 100%; min-height: 70vh; border: 0; background: #fff; }
.market { border: 1px solid var(--line); border-radius: 0.7rem; background: #fffdf8; padding: 0.9rem 1rem; margin: 1rem 0; }
.market-toolbar { display: flex; gap: 0.7rem; align-items: end; flex-wrap: wrap; margin: 0.6rem 0; }
.market-toolbar label { display: flex; flex-direction: column; gap: 0.2rem; font-size: 0.86rem; }
@@ -453,6 +478,7 @@ function renderSearch(data) {
el('h3', { text: hit.title || hit.rel_path }),
el('div', { class: 'src', text: hit.collection_name + ' / ' + hit.rel_path + ' · ' + hit.digest + (hit.stale ? ' · 源已变更(STALE)' : '') }),
el('pre', { text: hit.snippet || '' }),
el('button', { class: 'ghost', type: 'button', text: '在 View 阅读', onclick: () => openKnowledgeReader(hit) }),
));
}
}
@@ -902,7 +928,7 @@ function renderMarketProject() {
host.append(el('p', { text: 'marqdo.lock:' + (project.lock.present ? project.lock.digest : '缺失') }));
const imports = [];
for (const capability of data.capabilities) {
for (const item of capability.imports) imports.push(capability.name + ' -> ' + item.alias + ' (' + item.path + ')');
for (const item of capability.imports || []) imports.push(capability.name + ' -> ' + item.alias + ' (' + item.path + ')');
}
host.append(el('p', { class: 'muted', text: imports.length === 0 ? '尚无应用记录的导入。' : '应用记录的导入:' + imports.join(';') }));
host.append(el('p', { class: 'muted', text: '锁由 CLI 生成与校验;应用不解析第二套依赖图,也不把锁当作运行授权。' }));
@@ -929,6 +955,79 @@ function renderMarketProject() {
host.append(row);
}
const readerState = { kind: 'workspace', path: '', collection: null, theme: 'light', anchor: '', package: null };
async function loadReaderStatus() {
const status = $('#reader-status');
if (!status) return;
try {
const data = await api('/reader/status');
if (data.available) {
const view = data.view;
status.textContent = 'View ' + (view.version || 'unknown') + ' · ' + short(view.binary_sha256, 24) + ' · CLI ' + (data.cli?.version || 'unknown') + ' 可用。打开只读阅读不会执行文稿。';
$('#reader-form').querySelector('button').disabled = false;
} else {
status.textContent = '阅读不可用:' + (data.error || 'View Tool 未安装') + '。可到“生态中心 → Tool”安装 View。';
$('#reader-form').querySelector('button').disabled = true;
}
} catch (error) {
status.textContent = '读取 View 状态失败:' + error.message;
}
}
async function openReader(request) {
const status = $('#reader-status');
const identity = $('#reader-identity');
const frame = $('#reader-frame');
clear($('#reader-source-text'));
$('#reader-source-text').hidden = true;
if (status) status.textContent = '正在静态检查并导出 View 阅读包…';
if (identity) identity.textContent = '';
if (frame) frame.removeAttribute('src');
try {
const data = await api('/reader/open', { method: 'POST', body: JSON.stringify({
confirm: true,
kind: request.kind || 'workspace',
path: request.path,
collection: request.collection || undefined,
theme: request.theme || 'light',
anchor: request.anchor || undefined,
}) });
readerState.kind = data.source.kind;
readerState.path = data.source.relative;
readerState.collection = data.source.collection;
readerState.theme = data.theme;
readerState.anchor = data.anchor || '';
readerState.package = data;
if (frame) frame.setAttribute('src', data.package_url);
if (status) status.textContent = (data.cached ? '已复用缓存阅读包。' : '已生成并校验阅读包。') + ' 正文来自 View ' + (data.view.version || 'unknown') + ',未执行文稿。';
if (identity) identity.textContent = 'source ' + data.source.digest + ' · manifest ' + data.manifest_sha256 + (data.anchor ? ' · anchor ' + data.anchor : '');
$('#reader-source-toggle').disabled = false;
} catch (error) {
if (status) status.textContent = '打开阅读失败:' + error.message + (error.code === 'reader.view_missing' ? '。请先在生态中心安装 View Tool。' : '');
if (frame) frame.removeAttribute('src');
}
}
async function openKnowledgeReader(hit) {
const button = document.querySelector('[data-tab="reader"]');
if (button) button.click();
await openReader({ kind: 'knowledge', path: hit.rel_path, collection: hit.collection, theme: 'light', anchor: hit.anchor || '' });
}
async function loadReaderSource() {
const pkg = readerState.package;
if (!pkg) return;
try {
const query = new URLSearchParams({ kind: readerState.kind, path: readerState.path });
if (readerState.collection) query.set('collection', readerState.collection);
const data = await api('/reader/source?' + query.toString());
const node = $('#reader-source-text');
node.textContent = data.text + (data.truncated ? '\\n…(已截断)' : '');
node.hidden = false;
} catch (error) { showError('读取源码失败:' + error.message); }
}
async function loadRuns() {
try {
const data = await api('/runs');
@@ -1119,6 +1218,7 @@ function bind() {
});
const tab = button.dataset.tab;
if (tab === 'ecosystem') { loadEcosystem(); loadMarket(); }
if (tab === 'reader') loadReaderStatus();
if (tab === 'bootstrap') loadBootstrap();
if (tab === 'update') { loadUpdate(); loadNetwork(); }
if (tab === 'reports') loadReports();
@@ -1186,6 +1286,13 @@ function bind() {
await loadMarket();
} catch (error) { showError('添加来源失败:' + error.message); }
});
$('#reader-form').addEventListener('submit', async (event) => {
event.preventDefault();
const form = new FormData(event.target);
await openReader({ kind: 'workspace', path: String(form.get('path') || ''), theme: String(form.get('theme') || 'light'), anchor: String(form.get('anchor') || '') });
});
$('#reader-source-toggle').addEventListener('click', async () => { await loadReaderSource(); });
$('#reader-runs').addEventListener('click', () => { document.querySelector('[data-tab="runs"]').click(); });
$('#create-collection').addEventListener('submit', async (event) => {
event.preventDefault();
const form = new FormData(event.target);
@@ -1305,5 +1412,6 @@ loadStatus();
loadCollections();
loadEcosystem();
loadMarket();
loadReaderStatus();
loadRuns();
`
+73 -6
View File
@@ -19,6 +19,7 @@ import type { DiagnosticArea } from '../diagnostics/contract.ts'
import { discoverRelease } from '../ecosystem/sources.ts'
import { parseSourceConfig } from '../market/config.ts'
import { MarketError } from '../market/errors.ts'
import { ReaderError } from '../reader/errors.ts'
import { runProcess } from '../core/process.ts'
import { APP_CSS, APP_HTML, APP_JS } from './assets.ts'
import { isLoopbackAuthority, isTrustedAuthority } from './trust.ts'
@@ -53,7 +54,7 @@ class HttpError extends Error {
/** Read a bounded request body. */
async function readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {
const chunks: Buffer[] = []
const chunks: Uint8Array[] = []
let total = 0
for await (const chunk of req) {
const bytes = Buffer.from(chunk)
@@ -61,7 +62,7 @@ async function readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer>
if (total > maxBytes) throw new HttpError(413, 'request body exceeds its limit')
chunks.push(bytes)
}
return Buffer.concat(chunks)
return Buffer.concat(chunks.map(chunk => Buffer.from(chunk)))
}
/** Parse a JSON body. */
@@ -90,7 +91,7 @@ function registerRoutes(
runtime: MdhRuntime,
config: { trustedHosts: readonly string[]; bindHost?: string | undefined },
): void {
const webServer = ctx.get('webServer' as never) as {
const webServer = ctx.get('webServer') as {
register(route: {
kind: 'prefix'
path: string
@@ -128,7 +129,7 @@ function registerRoutes(
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
'content-length': Buffer.byteLength(html),
'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'",
'x-content-type-options': 'nosniff',
'referrer-policy': 'no-referrer',
'cache-control': 'no-store',
@@ -153,6 +154,7 @@ function registerRoutes(
} catch (error) {
if (error instanceof HttpError) { json(res, error.status, { error: error.message }); return }
if (error instanceof MarketError) { json(res, 409, { error: error.message, code: error.code }); return }
if (error instanceof ReaderError) { json(res, 409, { error: error.message, code: error.code }); return }
const message = error instanceof Error ? error.message : String(error)
const path = req.url ?? ''
const area: DiagnosticArea = path.startsWith('/mqdh/api/knowledge') ? 'knowledge'
@@ -302,6 +304,71 @@ async function handleApi(
})
return
}
if (path === '/reader/status' && method === 'GET') {
json(res, 200, await runtime.readerStatus())
return
}
if (path === '/reader/open' && method === 'POST') {
const body = await readJson(req)
if (body.confirm !== true) throw new HttpError(400, 'opening the reader requires explicit confirmation')
const kind = body.kind
if (kind !== 'workspace' && kind !== 'knowledge') throw new HttpError(400, 'kind must be workspace or knowledge')
const sourcePath = stringField(body, 'path')
let theme: 'light' | 'dark' | undefined
if (body.theme !== undefined) {
if (body.theme !== 'light' && body.theme !== 'dark') throw new HttpError(400, 'theme must be light or dark')
theme = body.theme
}
const collection = typeof body.collection === 'string' && body.collection.trim() !== '' ? body.collection.trim() : undefined
const anchor = typeof body.anchor === 'string' && body.anchor.trim() !== '' ? body.anchor.trim() : undefined
json(res, 200, await runtime.openReader({
kind,
path: sourcePath,
...(collection === undefined ? {} : { collection }),
...(theme === undefined ? {} : { theme }),
...(anchor === undefined ? {} : { anchor }),
...(body.force === true ? { force: true } : {}),
}))
return
}
if (path === '/reader/source' && method === 'GET') {
const kind = url.searchParams.get('kind') ?? 'workspace'
if (kind !== 'workspace' && kind !== 'knowledge') throw new HttpError(400, 'kind must be workspace or knowledge')
const sourcePath = url.searchParams.get('path') ?? ''
if (sourcePath === '') throw new HttpError(400, 'missing path')
const collection = url.searchParams.get('collection') ?? undefined
json(res, 200, await runtime.readerSource({
kind,
path: sourcePath,
...(collection === undefined || collection === '' ? {} : { collection }),
}))
return
}
const readerPackageMatch = /^\/reader\/package\/([a-f0-9]{64})\/(.+)$/.exec(path)
if (readerPackageMatch && method === 'GET') {
const id = readerPackageMatch[1]
const encodedPath = readerPackageMatch[2]
if (id === undefined || encodedPath === undefined) throw new HttpError(400, 'invalid reader package path')
let filePath: string
try {
filePath = decodeURIComponent(encodedPath)
} catch {
throw new HttpError(400, 'invalid reader package path')
}
const file = await runtime.reader.packageFile(id, filePath)
res.writeHead(200, {
'content-type': file.contentType,
'content-length': file.body.byteLength,
'cache-control': 'no-store',
'x-content-type-options': 'nosniff',
'referrer-policy': 'no-referrer',
...(file.contentType.startsWith('text/html')
? { 'content-security-policy': "default-src 'none'; style-src 'self'; font-src 'self'; img-src 'self' data:; media-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'" }
: {}),
})
res.end(file.body)
return
}
if (path === '/market' && method === 'GET') {
const config = await runtime.market.config()
json(res, 200, {
@@ -668,7 +735,7 @@ async function handleApi(
proxy_https: config.proxy.https !== null,
proxy_http: config.proxy.http !== null,
no_proxy_entries: config.proxy.noProxy.length,
mirrors: Object.entries(config.mirrors).map(([purpose, base]) => `${purpose}=${String(base)}`),
mirrors: Object.entries(config.mirrors).map(([purpose, base]) => `${purpose}=${base}`),
allowed_hosts: config.allowedHosts,
allow_loopback: config.allowLoopback,
allow_private: config.allowPrivate,
@@ -756,7 +823,7 @@ async function handleApi(
/** Register the workbench and its API over the DSH web server. */
export function apply(ctx: Context, config: { trustedHosts?: readonly string[] | undefined; bindHost?: string | undefined } = {}): void {
const runtime = ctx.get('mqdhRuntime' as never) as MdhRuntime | undefined
const runtime = ctx.get('mqdhRuntime') as MdhRuntime | undefined
if (!runtime) throw new Error('mqdh-web requires mqdhRuntime')
registerRoutes(ctx, runtime, { trustedHosts: config.trustedHosts ?? [], bindHost: config.bindHost })
}
+23
View File
@@ -80,3 +80,26 @@ test('a token is read from stdin and stored without appearing in output', async
assert.doesNotMatch(output.out.join(''), new RegExp(token))
assert.equal(await runtime.diagnostics.hasToken(), true)
})
test('status emits a read-only app and ecosystem version view', async () => {
const root = await mkdtemp(join(tmpdir(), 'mqdh-cli-'))
const runtime = await MdhRuntime.create({ home: join(root, 'home'), workspace: join(root, 'ws') })
const view = sink()
const code = await runProductCli(['status', '--json'], { io: view.io, runtime: async () => runtime })
assert.equal(code, 0)
const parsed = JSON.parse(view.out.join('')) as {
schema: string
app: { version: string; home: string }
ecosystem: { runtime: { installed: boolean }; std: { installed: boolean; modules: string[] } }
privacy: { telemetry: boolean; sessionUpload: boolean; pluginInstall: boolean }
}
assert.equal(parsed.schema, 'marqdo.mqdh.status')
assert.equal(parsed.app.version, APP_VERSION)
assert.equal(parsed.ecosystem.runtime.installed, false)
assert.equal(parsed.ecosystem.std.installed, false)
assert.deepEqual(parsed.privacy, { telemetry: false, sessionUpload: false, pluginInstall: false })
const text = sink()
assert.equal(await runProductCli(['status'], { io: text.io, runtime: async () => runtime }), 0)
assert.match(text.out.join(''), /^app: /)
assert.match(text.out.join(''), /privacy: telemetry=false/)
})
@@ -342,6 +342,9 @@ test('project import materializes a project-local copy and delegates add to the
assert.equal(imported.next, 'marqdo lock')
assert.match(await readFile(join(f.workspace, 'marqdo-vendor', 'demo', 'index.mq.md'), 'utf8'), /return 1/)
assert.match(await readFile(join(f.workspace, 'marqdo.yaml'), 'utf8'), /demo/)
const view = await store.capability(key)
assert.equal(view?.imports.length, 1)
assert.equal(view?.imports[0]?.project_path, 'marqdo-vendor/demo')
} finally {
await cleanup(join(f.home, '..'))
}
@@ -0,0 +1,114 @@
/** View embedded manifest validation and package file safety. */
import assert from 'node:assert/strict'
import { mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { test } from 'node:test'
import {
assertPackagePath, parseViewManifest, validateViewManifest, verifyPackageFiles,
} from '../src/reader/contract.ts'
import { contentTypeOf } from '../src/reader/service.ts'
import { READER_ERROR, ReaderError } from '../src/reader/errors.ts'
const hex = (char: string): string => char.repeat(64)
/** Build one valid View embedded manifest. */
function manifest(overrides: Record<string, unknown> = {}): Record<string, unknown> {
const base = {
schema: 'marqdo.view-export',
schema_version: 1,
mode: 'embedded',
theme: 'dark',
executed: false,
requires: { api_revision: 1, analysis: 3, observation: 1, markdown_profile: 'marqdo.md.v1' },
producers: {
view: { name: 'marqdo-view', version: '0.3.0', binary_sha256: hex('a') },
cli: { version: '3.0.0-rc.6', binary_sha256: hex('b') },
},
entry: {
href: 'index.html#detail',
file: 'index.html',
heading_ids: ['detail', 'intro'],
relative_path: 'doc.md',
anchor: 'detail',
sha256: hex('c'),
},
pages: [{
source_sha256: hex('d'),
source_status: 'static-ok',
relative_path: 'doc.md',
sha256: hex('c'),
}],
files: [{ path: 'index.html', sha256: hex('c') }],
assets: [],
}
return { ...base, ...overrides }
}
/** Expected identities for the valid manifest. */
const expected = {
sourceSha256: hex('d'),
viewBinarySha256: hex('a'),
cliBinarySha256: hex('b'),
theme: 'dark' as const,
anchor: 'detail',
relativePath: 'doc.md',
}
/** Assert one reader failure code. */
function rejectCode(run: () => unknown, code: string): void {
assert.throws(() => { run() }, (error: unknown) => error instanceof ReaderError && error.code === code)
}
void test('a View embedded manifest validates against exact source and producer identities', () => {
const parsed = parseViewManifest(manifest())
validateViewManifest(parsed, expected)
assert.equal(parsed.mode, 'embedded')
assert.equal(parsed.executed, false)
assert.equal(parsed.entry.heading_ids[0], 'detail')
})
void test('View manifest identity mismatches fail closed', () => {
const base = parseViewManifest(manifest())
rejectCode(() => { validateViewManifest(base, { ...expected, sourceSha256: hex('f') }) }, READER_ERROR.sourceChanged)
rejectCode(() => { validateViewManifest(base, { ...expected, viewBinarySha256: hex('f') }) }, READER_ERROR.manifestInvalid)
rejectCode(() => { validateViewManifest(base, { ...expected, theme: 'light' }) }, READER_ERROR.manifestInvalid)
rejectCode(() => { validateViewManifest(base, { ...expected, anchor: 'missing' }) }, READER_ERROR.manifestInvalid)
rejectCode(() => { validateViewManifest(parseViewManifest(manifest({ executed: true })), expected) }, READER_ERROR.manifestInvalid)
rejectCode(() => { validateViewManifest(parseViewManifest(manifest({ mode: 'site' })), expected) }, READER_ERROR.manifestInvalid)
})
void test('missing anchors and script assets in package manifests are rejected', () => {
const noAnchor = parseViewManifest(manifest({
entry: { href: 'index.html#detail', file: 'index.html', heading_ids: ['intro'], relative_path: 'doc.md', anchor: 'detail', sha256: hex('c') },
}))
rejectCode(() => { validateViewManifest(noAnchor, expected) }, READER_ERROR.anchorMissing)
assert.throws(() => { parseViewManifest(manifest({ files: [{ path: 'assets/app.js', sha256: hex('c') }] })) }, ReaderError)
assert.throws(() => { assertPackagePath('../escape', 'package file') }, ReaderError)
assert.throws(() => { assertPackagePath('assets/app.js', 'package file') }, ReaderError)
})
void test('package file digests are verified against the manifest', async () => {
const root = await mkdtemp(join(tmpdir(), 'mqdh-reader-'))
await writeFile(join(root, 'index.html'), '<p>reader</p>')
const parsed = parseViewManifest(manifest({
entry: {
href: 'index.html', file: 'index.html', heading_ids: [], relative_path: 'doc.md', anchor: null, sha256: hex('0'),
},
pages: [{ source_sha256: hex('d'), source_status: 'static-ok', relative_path: 'doc.md', sha256: hex('0') }],
files: [{ path: 'index.html', sha256: hex('0') }],
}))
await assert.rejects(verifyPackageFiles(root, parsed), (error: unknown) => (
error instanceof ReaderError && error.code === READER_ERROR.packageInvalid
))
})
void test('reader content types stay static-only', () => {
assert.equal(contentTypeOf('index.html'), 'text/html; charset=utf-8')
assert.equal(contentTypeOf('assets/reader.css'), 'text/css; charset=utf-8')
assert.equal(contentTypeOf('assets/noto-math.woff2'), 'font/woff2')
assert.equal(contentTypeOf('media/x.png'), 'image/png')
assert.equal(contentTypeOf('media/x.js'), 'application/octet-stream')
})
@@ -81,6 +81,7 @@ async function startReleaseServer(releases: readonly {
manifest: string
signature: string
size: number
body?: string
}[]): Promise<{ server: Server; authority: string; stop: () => void }> {
const server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
const url = req.url ?? ''
@@ -92,6 +93,7 @@ async function startReleaseServer(releases: readonly {
prerelease: false,
draft: false,
target_commitish: null,
body: release.body ?? null,
assets: [
{ name: 'mqdh-release.json', size: Buffer.byteLength(release.manifest), browser_download_url: `${authority}/assets/${release.tag}/mqdh-release.json` },
{ name: 'mqdh-release.json.sig', size: Buffer.byteLength(release.signature), browser_download_url: `${authority}/assets/${release.tag}/mqdh-release.json.sig` },
@@ -150,13 +152,15 @@ test('checks, verifies, activates and rolls back a signed application release',
const v3 = await buildRelease({ root, version: '0.3.0', target })
const server = await startReleaseServer([
{ tag: 'mqdh-v0.2.0', archive: v2.archive, manifest: v2.manifest, signature: v2.signature, size: v2.size },
{ tag: 'mqdh-v0.3.0', archive: v3.archive, manifest: v3.manifest, signature: v3.signature, size: v3.size },
{ tag: 'mqdh-v0.3.0', archive: v3.archive, manifest: v3.manifest, signature: v3.signature, size: v3.size, body: '修复启动问题并更新默认 Bundle。' },
])
const { updater, installRoot } = await makeUpdater(server.authority)
try {
const checked = await updater.check({ force: true })
assert.equal(checked.latest?.version, '0.3.0')
assert.equal(checked.latest?.signature, 'verified')
assert.equal(checked.latest?.notes, '修复启动问题并更新默认 Bundle。')
assert.match(checked.latest?.release_url ?? '', /releases\/tag\/mqdh-v0\.3\.0$/)
assert.equal(checked.update_available, true)
assert.equal(checked.current?.version, '0.1.0')
+1 -1
View File
@@ -19,7 +19,7 @@ import { spawn } from 'node:child_process'
const here = dirname(fileURLToPath(import.meta.url))
const root = resolve(here, '..')
const productCommands = new Set(['bootstrap', 'doctor', 'repair', 'report', 'update', 'network', 'uninstall', 'help'])
const productCommands = new Set(['bootstrap', 'status', 'doctor', 'repair', 'report', 'update', 'network', 'uninstall', 'help'])
/** Resolve the application home without touching the user's `~/.dsh`. */
function resolveHome() {