diff --git a/AGENTS.md b/AGENTS.md index 2692d2891d..1afc5fd93e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -205,6 +205,6 @@ This repository is `app-harness` in the Marqdo ecosystem (parent path `apps/harn - Upstream contract defects go to `marqdo-cli`, `marqdo-std-*`, `marqdo-ext-*`, `marqdo-knowledge` or `marqdo-view`; this repository only consumes their published contracts. - Run `scripts/ci.sh` before pushing; use `scripts/upstream.sh candidate ` for a synchronisation branch and never auto-merge upstream. - All product-owned egress goes through `packages/marqdo/harness/src/network/`; do not add direct `fetch` calls to product sources. The model transport remains upstream DSH. -- One bootstrap state machine (`src/bootstrap`), one platform table (`src/platform`), one application release manifest (`src/release`), one diagnostics store (`src/diagnostics`). Do not add a second installer, platform list, version table or log protocol. +- One bootstrap state machine (`src/bootstrap`), one platform table (`src/platform`), one application release manifest (`src/release`), one diagnostics store (`src/diagnostics`), one market index and capability store (`src/market`). Do not add a second installer, platform list, version table, dependency lock, market registry or log protocol. - Diagnostics are local-first: redact before writing, submit only with explicit user confirmation, and never expose token/report content to the model. - The application install tree (`MQDH_INSTALL_ROOT`) is separate from `MQDH_HOME`; updates must never change the ecosystem or user knowledge, and unverified platforms/signatures must not be published as supported. diff --git a/docs/mqdh/ARCHITECTURE.md b/docs/mqdh/ARCHITECTURE.md index f844d1b1a9..42c7b7d017 100644 --- a/docs/mqdh/ARCHITECTURE.md +++ b/docs/mqdh/ARCHITECTURE.md @@ -2,9 +2,8 @@ Marqdo Harness 是 Marqdo 生态的官方单用户应用:一个基于 [DeepSeek Harness](https://git.cflmy.cn/cflmy/deepseek-harness)(DSH)的下游 fork。 它复用 DSH 的模型接入、Agent Loop、会话、事件、工具审批和 Web 外壳,新增四类产品能力: -1. **生态管理**:发现、安装、验证、切换与回退 Marqdo CLI / Bundle / Tool / Ext; -2. **文稿原生程序化执行(Marqdo PTC)**:以完整 `.mq.md` 为程序化调用单元, -经官方 `check` / `run` / `call` 与 Observation 1 产生可核对结果; +1. **生态管理**:发现、安装、验证、切换与回退 Marqdo CLI / Bundle / Tool / Ext,并以动态来源市场管理用户级能力; +2. **文稿原生程序化执行(Marqdo PTC)**:以完整 `.mq.md` 为程序化调用单元,经官方 `check` / `run` / `call` 与 Observation 1 产生可核对结果; 3. **私人知识库**:本地静态知识集合的导入、编译、检索、引用与沉淀; 4. **成果复用**:运行证据、离线阅读、知识候选与再次执行。 @@ -33,7 +32,8 @@ apps/harness/ # 独立应用仓库(父仓 gitlink:apps │ ├── src/network/ # 唯一出口:用途策略、代理、镜像、离线、审计 │ ├── src/platform/ # 唯一平台探测与发布目标矩阵 │ ├── src/release/ # 应用发行清单、签名、Gitea 发现 -│ ├── src/ecosystem/ # 信任来源、安装事务、环境、回退、Tool 安装 +│ ├── src/ecosystem/ # Runtime 信任来源、安装事务、环境、回退、Bootstrap Tool 兼容 +│ ├── src/market/ # 市场来源/索引、用户级能力存储、启用作用域、项目导入门禁 │ ├── src/bootstrap/ # 首次启动状态机、doctor、repair │ ├── src/distribution/ # 安装根、应用更新/回退/卸载 │ ├── src/diagnostics/ # 脱敏报告、去重、Gitea Issue 提交 @@ -91,6 +91,14 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070 │ ├── environments/ # 一组 CLI + Bundle + Tool home │ ├── current.json # 原子活动指针 │ └── install.lock +├── market/ +│ ├── index.json # 可重建的来源聚合投影 +│ └── events.jsonl # market.changed 变更事件 +├── capabilities/ +│ ├── index.json # 权威:已安装版本/激活摘要/启用作用域/导入记录 +│ ├── store/--/ # 用户级能力载荷(按摘要分版本) +│ ├── staging/ # 未完成安装(失败清理) +│ └── audit.jsonl # 安装/激活/启用/撤销/导入/锁/卸载审计 ├── knowledge/ │ ├── sources// # 用户导入的原文副本 │ ├── collections.json # 集合元数据与 revision @@ -106,14 +114,14 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070 ├── product.json # 首次完成标记 ├── update.json # 应用更新缓存与历史 ├── network.json # 可选出口覆盖 + ├── market.json # 市场来源列表(0600) └── credentials.json # 用户提供的 Gitea token(0600) ``` 规则: - 不覆盖用户已有的 `~/.dsh`;DSH home 固定在 `MQDH_HOME/harness`。 -- 任务启动时固定环境 ID、CLI 绝对路径、Tool home、Bundle 与锁摘要;之后不从 -`current` 再解析。 +- 任务启动时固定环境 ID、CLI 绝对路径、Tool home、Bundle 与锁摘要;之后不从 `current` 再解析。 - 活动环境与回退目标不会被清理;staging 与未被引用的环境可受控清理。 - 运行证据只记录引用与摘要,不把完整私有知识或模型密钥写入日志。 @@ -138,18 +146,15 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070 ## 6. 私人知识 - 集合由用户创建;导入默认复制到 `knowledge/sources`,原文件不被修改。 -- 导入拒绝越界路径、符号链接、特殊文件、超限、大小写/NFC 冲突; -`.mq.md` 或含执行区域的内容不得作为静态知识导入。 -- 检索优先调用已安装的 `marqdo-knowledge` 公开命令 -(`compile` / `check` / `query --format json`),消费 `marqdo.knowledge.result` v1 的 `hits[].source` 身份;索引与源摘要不匹配即标记过期。 -- 没有 Knowledge Tool 时只提供明确披露的只读文件定位器(`mode: "locator"`, -`indexed: false`),不伪造编译/索引完成。 +- 导入拒绝越界路径、符号链接、特殊文件、超限、大小写/NFC 冲突;`.mq.md` 或含执行区域的内容不得作为静态知识导入。 +- 检索优先调用已安装的 `marqdo-knowledge` 公开命令(`compile` / `check` / `query --format json`),消费 `marqdo.knowledge.result` v1 的 `hits[].source` 身份;索引与源摘要不匹配即标记过期。 +- 没有 Knowledge Tool 时只提供明确披露的只读文件定位器(`mode: "locator"`, `indexed: false`),不伪造编译/索引完成。 - 搜索结果必须包含集合、源相对路径、摘要、标题/锚点和片段;模糊查询只返回候选。 - 知识文本是低信任输入,不作为系统级指令拼接;知识不授予执行、安装或网络权限。 ## 7. Web 工作台 -`/mqdh` 是 DSH Web 内的真实服务器渲染工作台(同一 webserver、同一 loopback 绑定)。生态目录固定按 Runtime → Tool → Std → Ext → Knowledge 展示真实来源;打开/筛选无副作用,候选检查、受信任 Tool 安装、Runtime 切换、项目锁检查与 Tool 移除由按钮显式发起。Std 只随 Bundle,Ext 只走项目依赖工作流,见 [ECOSYSTEM.md](ECOSYSTEM.md)。Ext 只显示项目文件摘要,语义检查由 CLI `sync --locked --json` 承担: +`/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` 承担: - Runtime:CLI/Bundle/平台/环境 ID/遥测关闭状态; - Knowledge:集合、导入(浏览器上传文本/文件)、搜索、删除、导出; @@ -164,15 +169,14 @@ MQDH_HOME/ # 默认 $XDG_DATA_HOME/marqdo-harness,070 - 默认只绑定 loopback;远程绑定需要显式配置并自行承担认证/隔离。 - 关闭上游默认会话上传、反馈会话日志、独立 DeepSeek session log 与遥测。 - 模型密钥只用于模型通信,不进入 Marqdo 子进程环境;子进程用 allowlist 环境。 -- 固定 argv、绝对可执行路径、进程组终止、超时/输出上限;不把 `project` 或 -worker 名称当成 OS 隔离证明。 -- 生态安装只接受 Gitea 权威 release 的不可变 tag、资产名、平台、大小与 SHA-256; -安全解包拒绝链接/特殊文件/越界;失败保留旧组合。 +- 固定 argv、绝对可执行路径、进程组终止、超时/输出上限;不把 `project` 或 worker 名称当成 OS 隔离证明。 +- Runtime 安装只接受 Gitea 权威 release 的不可变 tag、资产名、平台、大小与 SHA-256;市场条目按来源配置发现,下载/解包同样强制摘要、大小、路径与链接安全;失败保留旧组合。 +- 市场不做可信/不可信中央裁决;来源标签不门禁,安装不等于对模型启用;项目导入只由 CLI 写声明与锁。 - 私人知识、完整会话、路径、环境变量、密钥和用户源码默认不进入诊断对外内容。 ## 9. 出口、发行与引导边界 -- **唯一网络出口**:`src/network` 是产品自有出站的唯一实现;组件发现/下载、引导、应用更新、Issue 提交都走它。模型传输仍归上游 DSH,`model` 用途只做策略分类/探测/审计。 +- **唯一网络出口**:`src/network` 是产品自有出站的唯一实现;组件发现/下载、市场来源/资产、引导、应用更新、Issue 提交都走它。模型传输仍归上游 DSH,`model` 用途只做策略分类/探测/审计;`market` 的 URL 只来自用户配置的来源。 - **唯一平台表**:`src/platform/detect` 决定 target/glibc/Node/磁盘;Bootstrap、更新、doctor 共用,未发布平台明确拒绝。 - **唯一发行清单**:应用用 `src/release/manifest.ts` 的 `mqdh-release.json`;组件继续使用其既有 `RELEASE_INFO.json` 合同,二者不互相替代。 - **安装与数据分离**:应用安装树在 `MQDH_INSTALL_ROOT`(默认 `~/.local/opt/mqdh`),用户数据/运行时在 `MQDH_HOME`;更新不改变运行时,运行时升级不重装应用。 diff --git a/docs/mqdh/ECOSYSTEM.md b/docs/mqdh/ECOSYSTEM.md index 0c256604c2..1043ee232d 100644 --- a/docs/mqdh/ECOSYSTEM.md +++ b/docs/mqdh/ECOSYSTEM.md @@ -1,40 +1,75 @@ -# 生态目录:发现、浏览与安装边界 +# 生态目录:发现、市场与能力边界 -生态目录回答两个不同问题:**有什么可用**(发现)和 **是否允许现在安装**(授权)。前者应尽量开放,后者必须受信任来源、层语义与用户确认约束。把两者混成“任意下载”会破坏生态边界。 +生态目录回答两个不同问题:**有什么可用**(发现)和 **是否允许现在使用**(授权)。发现应尽量开放;授权必须由用户显式完成。市场是来源聚合视图,不是中心化商店,也不是第二套依赖解析器。 ## 1. 分层规则 | 层 | 未安装时可浏览 | 可执行动作 | 权威来源 | 禁止 | | --- | --- | --- | --- | --- | | Runtime | 是:受信任 CLI/Worker + 相邻单一 Bundle 候选 | 显式确认后安装/切换;失败保留当前组合 | 权威 Gitea Release 的 tag、资产名、平台、大小、SHA-256、`RELEASE_INFO`、Bundle digest、协议 | 任意 URL、模型提供版本/argv、静默升级 | -| Tool | 是:受信任 knowledge/view/lint/prove 候选 | 显式确认后安装/移除/更新;只写入当前环境 tool-home | CLI Tool Release 的资产与 `tool.json` | 第三方 Tool 市场、任意包名/URL、自动安装 | +| Tool | 是:市场来源中的 `tool` 条目 | 安装到用户级能力存储并注册到当前 Runtime 的隔离 Tool home;显式启用后才对模型可见 | 来源 Release 资产与 `tool.json`;条目元数据由市场投影 | 任意包名/URL、自动安装、静默启用 | | Std | 安装 Runtime 后按命名空间浏览;未安装时说明“随 Bundle” | 只随 Runtime Bundle 安装/升级 | 已验证 Bundle 的 manifest 与模块清单 | 单模块下载、单模块启停、第二套模块索引 | -| Ext | 只显示当前项目 `marqdo.yaml` / `marqdo.lock` 身份与锁定状态 | 显式按钮调用 CLI `sync --locked --json`;依赖变更走 `marqdo add`/`marqdo lock` | 项目声明与锁;语义由 CLI 校验 | 插件市场、任意扩展下载、第二套依赖锁/解析器 | +| Ext | 是:市场来源中的 `ext` 条目,以及当前项目 `marqdo.yaml`/`marqdo.lock` | 安装到用户级能力存储;显式启用;项目导入由 CLI `add` 写声明、CLI `lock` 生成锁 | 来源 Release/目录资产;项目声明与锁的语义由 CLI 校验 | 第二套依赖锁/解析器、应用直接写 `marqdo.lock`、把安装当运行授权 | | Knowledge | 只显示用户自己的集合、来源与索引状态 | 导入、重建、检索、删除 | 同一私人知识集合 | 公共知识商店、第二套集合/索引、执行授权 | “锁存在”不等于“运行授权”;实际调用仍由 CLI 的权限模型和 DSH 审批逐步决定。 -## 2. 为什么发现很重要 +## 2. 市场不是中央商店 -- 首次用户不知道 CLI、Bundle、Tool 的发行关系;只显示已安装项会让生态看起来是空的。 -- 候选必须带真实身份:tag、平台、资产名、SHA-256、source SHA、签名状态与兼容范围;否则用户无法判断风险。 -- 发现动作本身不应下载或执行;只有用户点“安装/更新”并确认后才进入现有事务(校验 → staging → smoke → 原子切换)。 -- 不可用不是空白:必须用文字说明原因(未安装、平台不符、无候选、锁未验证、离线)与恢复入口。 +- 市场索引是**可重建投影**,由 `MQDH_HOME/config/market.json` 中用户配置的来源聚合而成;产品源码不保存 owner、仓库或条目清单。 +- 来源可以是 Gitea(通过 topic、显式仓库或 owner 发现 Release)、本地/离线目录;新增来源、仓库、Release 或条目不需要修改 MQDH 源码。 +- 市场展示来源、版本、摘要、签名/`unsigned`、权限、effects、依赖与已知风险,但不做“可信/不可信”中央裁决;来源标签不构成浏览或安装门禁。 +- 完整性、路径安全与格式校验仍然强制:摘要、大小、归档链接/越界、清单字段、平台不兼容都会拒绝。技术安全不等于信任背书。 +- 不同来源的同名条目以 `source:kind:id` 区分,不自动合并或覆盖;已安装版本由摘要锁定。 -## 3. 当前实现 +完整合同见 [MARKET.md](MARKET.md)。 -- `GET /mqdh/api/ecosystem`:本地只读投影(Runtime/Tool/Std/Ext 文件身份/Knowledge 计数)。 -- `GET /mqdh/api/ecosystem/candidates`:显式“检查候选”时读取权威 Release 元数据;不下载资产。 -- `POST /mqdh/api/ecosystem/install`:Runtime 安装/切换(既有事务)。 -- `POST /mqdh/api/ecosystem/tool-install-release`:按受信任组件 id + 版本安装 Tool;只接受 knowledge/view/lint/prove。 -- `POST /mqdh/api/ecosystem/project-check`:显式调用 CLI `sync --locked --json`,回显真实结果。 -- 页面按钮只在这些显式动作后产生副作用;打开、筛选、查看详情不下载、不安装、不执行。 +## 3. 四个状态 -## 4. 证据 +| 状态 | 含义 | 所有者 | 进入下一状态的条件 | +| --- | --- | --- | --- | +| `listed` | 市场来源中可见的条目 | 市场索引(可重建) | 用户选择安装 | +| `installed` | 已解包到用户级能力存储,摘要、大小、路径与清单校验通过 | `MQDH_HOME/capabilities/` | 用户显式激活/启用 | +| `project-imported` | 已由 CLI `add` 写入项目声明并由 CLI `lock` 生成锁 | 项目 + CLI | 用户显式在会话中使用 | +| `agent-enabled` | 当前会话/项目可见并可被模型请求 | 应用能力授权 | 每次调用仍走 CLI 权限与 DSH 审批 | -- 候选:cli `v3.0.0-rc.6`、knowledge `v0.1.0-beta.3`、view `v0.3.0`、lint `v0.2.0`;prove 无候选时如实显示错误。 -- Tool 安装:从页面移除 view 后,通过 `tool-install-release` 重新安装 `v0.3.0`,`/ecosystem` 显示 knowledge + view。 -- Ext:真实 `marqdo.yaml`/`marqdo.lock` 摘要可回显;摘要不符时 CLI 返回 `root manifest changed since marqdo.lock`,页面原文展示。 -- Std:真实 Bundle 返回 17 个 `std:` 导入路径,按命名空间分组。 +- 未安装时项目导入返回 `extension.not_installed`,UI 同时给出“先安装”入口。 +- `agent-enabled` 默认关闭;启用是用户动作,可按全局、会话或项目收窄;撤销后能力立即从 `marqdo_find` 与 `marqdo_ecosystem capabilities` 消失。 +- 模型不能安装、启用、修改来源或写锁;市场变更 API 只由 `/mqdh` 页面的显式用户操作调用。 +- 卸载前做保守的项目引用检查;被引用时返回 `extension.project_referenced`,要求先移除依赖并重新锁,或由用户显式强制卸载。 -未验证:真实浏览器/键盘/窄窗口/主题回归;prove/lint Tool 的真实安装;企业代理下的候选检查。 +## 4. 安装、项目导入与执行 + +```text +listed + -> install(用户确认;下载/解包/摘要/路径/清单校验) + -> installed(用户级能力存储,模型不可见) + -> activate(选择版本;Tool 注册到当前 Runtime) + -> enable(全局/会话/项目作用域,模型可见) + -> project import(CLI add + 项目内副本;只有已安装才允许) + -> CLI lock(唯一锁写入者) + -> run/call(CLI 权限 + DSH 审批 + Observation 证据) +``` + +- 市场安装不修改项目;项目导入不绕过安装。 +- 项目导入把已安装载荷复制到 `marqdo-vendor/`,因为 CLI 清单只接受项目相对 `path`;规范副本仍在用户级能力存储,项目副本只是 CLI 可解析的导入材料。 +- 项目导入调用固定 argv `marqdo add --path ./marqdo-vendor/ --json`;锁生成调用 `marqdo lock --json`。应用不写 `marqdo.yaml`/`marqdo.lock`。 +- 运行证据绑定执行时的项目锁摘要;重新导入/重新锁后旧证据标记 `stale`,不会冒充当前依赖身份。 +- 更新先安装新版本到独立目录,**不自动切换**已启用版本;用户显式选择后再激活。Tool 激活会重新注册到当前 Runtime。 +- 能力启用是应用层可见性控制,不是 OS 隔离;实际执行仍由 CLI 的 mode/grants 与 DSH 审批决定。 + +## 5. 当前实现 + +- `GET /mqdh/api/market`:来源配置、最近索引、已安装能力、变更事件、当前项目状态。 +- `POST /mqdh/api/market/refresh`:显式刷新所有来源;缓存按 TTL 与来源配置摘要失效;失败保留上次条目并标记来源 `stale`,离线时 Gitea 来源标记 `offline`。 +- `POST /mqdh/api/market/install|activate|uninstall|enable|disable|import|lock`:均要求 `confirm: true`。 +- `POST /mqdh/api/market/sources` / `sources/remove`:增删来源;有已安装能力的来源必须先卸载能力才能移除。 +- `GET /mqdh/api/ecosystem/candidates`:Runtime 候选 + 市场 Tool 条目;不再遍历固定组件 id。 +- `POST /mqdh/api/ecosystem/tool-install-release`:按市场 entry key 安装 Tool,写入能力存储。 +- 页面打开、搜索、筛选、查看详情无下载/安装/执行副作用;刷新、安装、激活、启用、导入、锁、卸载只由按钮显式发起。 + +## 6. 证据与限制 + +真实证据见 [evidence/2026-11-29-market.md](evidence/2026-11-29-market.md):官方 topic 发现 knowledge/lint/view、`marqdo-view` 安装/启用/撤销、目录 ext 安装、CLI `add`+`lock`+`sync --locked`、更新待激活、离线目录刷新与来源 `offline`。 + +未验证:真实浏览器/键盘/窄窗口/暗色主题回归;企业内网 Gitea 与真实代理下的市场刷新;签名校验只有展示,没有中央信任裁决或强制签名;构建脚本只在用户显式同意后执行,未做真实构建扩展验收。 diff --git a/docs/mqdh/MARKET.md b/docs/mqdh/MARKET.md new file mode 100644 index 0000000000..2c1aade93f --- /dev/null +++ b/docs/mqdh/MARKET.md @@ -0,0 +1,149 @@ +# 扩展市场与用户级能力合同 + +本文件是 MQDH 市场的唯一实现合同。市场是来源聚合视图;项目依赖仍由 CLI 唯一负责。实现位于 `packages/marqdo/harness/src/market/`,页面与 API 位于 `src/web/`。 + +## 1. 目标与非目标 + +目标:动态发现 Ext/Tool;用户可配置 Gitea、自建 Gitea、本地/离线目录;安装到用户级能力存储;按全局/会话/项目启用或撤销;项目导入只在已安装后允许;来源隔离、变更探测、离线与审计。 + +非目标:中心化市场服务、账号体系、第二套包管理器/锁/解析器、复制 Extension manifest 解析、把安装当执行授权、模型自行安装/启用/改锁。 + +## 2. 来源配置 + +`MQDH_HOME/config/market.json`(0600)是唯一来源声明。缺失时默认一个 `official` 来源,base 取网络配置的发行源,topics 为 `["marqdo-ext","marqdo-tool"]`,owner 为权威 owner。 + +```json +{ + "schema": "marqdo.mqdh.market", + "schema_version": 1, + "sources": [ + { "id": "official", "kind": "gitea", "base": "https://git.cflmy.cn", "owners": ["cflmy"], "topics": ["marqdo-ext", "marqdo-tool"] }, + { "id": "team", "kind": "gitea", "base": "https://gitea.internal", "owners": ["platform"], "repositories": [] }, + { "id": "local", "kind": "directory", "path": "/srv/marqdo-market" } + ], + "cache_ttl_ms": 300000, + "offline": false +} +``` + +- `id` 匹配 `^[a-z][a-z0-9-]{0,31}$`,全局唯一;来源决定能力身份的一部分。 +- Gitea 来源至少配置 `owners`、`topics`、`repositories` 之一;topic 通过 Gitea `repos/search?q=&topic=true` 动态发现仓库,再按 owner 过滤。 +- `directory` 来源必须有绝对 `path`,读取 `/index.json` 与相对资产;离线可用。 +- `default_kind` 只用于没有 `marqdo-ext`/`marqdo-tool` topic 的显式仓库,可选 `ext`/`tool`。 +- 未知键、重复 id、目录来源与仓库字段混用都 fail-closed。 +- 每次刷新重新读取配置;新增/删除来源不需要重启。删除来源前必须卸载该来源的已安装能力(`market.source_in_use`)。 + +## 3. 发现与索引 + +### 3.1 Gitea + +- 仓库 topic 含 `marqdo-tool` 或 `marqdo-ext` 决定条目 kind;同时含两者且没有 `default_kind` 时跳过并记录 warning。 +- 每个仓库按版本降序检查 Release(最多 30),选择第一个满足当前平台 `.tar.gz` 资产的 Release;资产 URL 必须位于该来源 base 下。 +- 摘要求自 `.sha256` 或 `release-evidence.json` 的 `assets[].sha256`;没有摘要的 Release 不进入市场。 +- source SHA 取自 `target_commitish`(40 位十六进制)或 `release-evidence.json.source_sha`。 +- Tool 条目没有 `market-entry.json` 时,从仓库名派生命令(`marqdo-view` → `view`)并生成最小 display manifest;安装时仍以归档内 `tool.json` 为准。 +- 可选资产 `market-entry.json`/`marqdo-market.json` 提供 `kind/id/name/summary/description/version/publisher/source_sha/manifest/signature/known_limitations/risk`;`manifest` 字段与第 3.3 节一致。 + +### 3.2 目录 + +```json +{ + "schema": "marqdo.mqdh.market.directory", + "schema_version": 1, + "entries": [ + { + "kind": "ext", + "id": "quantum", + "name": "Quantum", + "summary": "quantum circuits", + "version": "0.1.0", + "asset": { "name": "quantum-0.1.0.tar.gz", "path": "quantum-0.1.0.tar.gz", "sha256": "…", "size": 1234 }, + "manifest": { "capabilities": ["quantum"], "permissions": ["read:data"], "effects": ["pure"] } + } + ] +} +``` + +- `asset.path` 必须是来源目录内的普通文件;符号链接、越界、大小/摘要不符拒绝。 +- 未声明 `sha256`/`size` 时刷新阶段计算并写入投影;声明时必须匹配。 +- 目录条目与在线条目拥有同一 `source:kind:id`、版本、摘要与安装/启用路径。 + +### 3.3 条目 manifest 字段 + +```json +{ + "mechanisms": ["plugin"], + "tools": ["view"], + "skills": [], + "capabilities": ["demo.run"], + "permissions": ["read:data"], + "effects": ["filesystem.read"], + "dependencies": [{ "id": "std-data", "version": ">=1" }], + "min_cli": "3.0.0-rc.6", + "min_protocol": "analysis:3,observation:1", + "build": { "required": true, "command": ["npm", "run", "build"], "instructions": "needs Node" } +} +``` + +Display-only;权威 extension/tool 清单仍由归档内的公开 manifest 与 CLI 校验。`build` 只在用户显式 `allow_build` 时执行固定 argv,不通过 shell,超时/输出有界;未同意时仅解包并标记未就绪。 + +### 3.4 索引、缓存与变更 + +- 索引文件 `MQDH_HOME/market/index.json`,包含 `config_digest`、来源状态与条目。它是可重建投影,不作为身份权威。 +- 非强制刷新在 `cache_ttl_ms` 内且来源配置摘要未变时复用缓存;显式刷新强制访问来源。 +- 比较 `(source,kind,id)` 的版本与摘要:新增 `new`、变化 `changed`、来源成功刷新后消失 `stale`。 +- 来源刷新失败保留上次条目,来源状态 `stale`;离线时 Gitea 来源 `offline`,目录来源仍为 `ok`。 +- 变更追加到 `MQDH_HOME/market/events.jsonl`(`market.changed`);不静默替换已安装能力。 + +## 4. 用户级能力存储 + +```text +MQDH_HOME/capabilities/ +├── index.json # 权威:版本、激活摘要、启用作用域、导入记录 +├── audit.jsonl # install/activate/enable/disable/uninstall/import/lock/build +├── store/--/-/ +└── staging/ # 未完成安装,失败清理 +``` + +- 一个能力记录以 `source:kind:id` 为 key,保留多个已安装版本;`active` 指向当前摘要。 +- 首次安装激活该版本;后续版本安装到独立目录,`active` 不自动改变。返回 `pending_activation: true`,用户显式 `activate` 后才切换。 +- Tool 安装/激活调用当前 Runtime 的 `marqdo tool install `,写入隔离 Tool home;卸载/切换调用 `tool remove`。应用不维护第二套 Tool registry。 +- 启用作用域:`global`、`session:`、`project:`;默认没有任何作用域。 +- 可见性要求:已激活、构建满足、Tool 已注册、至少一个作用域匹配当前会话/项目。`marqdo_find` 与 `marqdo_ecosystem capabilities` 使用同一投影。 +- 模型工具没有安装、激活、启用、来源编辑或锁写入动作。 + +## 5. 项目导入与锁 + +- 只有 `installed` 且已激活的 `ext` 才能导入;否则 `extension.not_installed`/`extension.import_unsupported`。 +- CLI 清单只接受项目相对 `path`,因此导入先把载荷复制到项目 `marqdo-vendor/`(拒绝链接/越界/超限),再执行固定 argv `marqdo add --path ./marqdo-vendor/ --json`。 +- 应用不写 `marqdo.yaml` 或 `marqdo.lock`;锁由显式 `POST /market/lock` 调用 `marqdo lock --json` 生成。 +- 项目导入记录保留规范载荷绝对路径与项目相对路径;卸载做保守字面引用检查,命中 `marqdo.yaml`/`marqdo.lock` 时拒绝,除非用户强制。 +- 激活新版本不会静默更新项目副本;需要重新导入/重新锁。运行证据绑定执行时的 `marqdo.lock` 摘要,重新锁后旧证据标记 `stale`。 + +## 6. 网络、完整性与审计 + +- 所有来源与资产请求走 `EgressClient` 的 `market` purpose。市场 URL 只来自用户配置,模型不能提供 URL;公共 HTTPS 来源由配置显式列出,私网/loopback 仍需 `allow_private`/`allow_loopback`。 +- 下载强制 SHA-256 与声明大小;解包复用 `extractTarGz` 的链接/特殊文件/越界/大小写/NFC/大小限制。 +- 签名可选展示;没有签名标记 `unsigned`,不因来源标签阻止安装。完整性失败必须拒绝。 +- 安装/激活/启用/撤销/导入/锁/卸载/构建写本地审计,不含私人内容。 + +## 7. API 与页面 + +| 方法与路径 | 作用 | +| --- | --- | +| `GET /mqdh/api/market` | 配置、索引、能力、事件、项目状态 | +| `POST /mqdh/api/market/refresh` | 显式刷新(`confirm:true`) | +| `POST /mqdh/api/market/install` | `key` + 可选 `allow_build` | +| `POST /mqdh/api/market/activate` | `key` + 可选 `sha256` | +| `POST /mqdh/api/market/uninstall` | `key` + 可选 `force` | +| `POST /mqdh/api/market/enable` / `disable` | `key` + `scope`(`global`/`session`/`project`) | +| `POST /mqdh/api/market/import` | `key` + 可选 `alias` | +| `POST /mqdh/api/market/lock` | 由 CLI 生成项目锁 | +| `POST /mqdh/api/market/sources` / `sources/remove` | 增删来源 | +| `GET /mqdh/api/market/events` | 最近变更事件 | + +页面在生态中心 Ext 组提供“市场 / 已安装 / 当前项目”三段视图;搜索、来源/类型筛选、详情、安装、激活、启用、导入、锁、卸载均无隐式副作用。窄窗口、键盘焦点、明暗主题使用 DSH 现有控件与本地 CSS,不引入外部字体/脚本/CDN。 + +## 8. 验收与限制 + +见 [STATUS.md](STATUS.md) 的 CAT-05–CAT-09 与 [evidence/2026-11-29-market.md](evidence/2026-11-29-market.md)。未验证:真实浏览器回归、企业内网/代理、签名强制、真实构建扩展、Windows/macOS 路径与打包。 diff --git a/docs/mqdh/NETWORK.md b/docs/mqdh/NETWORK.md index 58ada232bc..96d65378dc 100644 --- a/docs/mqdh/NETWORK.md +++ b/docs/mqdh/NETWORK.md @@ -12,6 +12,7 @@ | `bootstrap` | 同上 | 首次启动解析候选 | 允许(仅权威源或已配置镜像) | | `update` | 同上 | 应用发行清单/安装包 | 允许(仅权威源或已配置镜像) | | `issue` | 配置的 Gitea API | 用户确认后提交 Issue | 允许(仅确认时) | +| `market` | 用户 `market.json` 中的来源 | 显式刷新/安装市场条目 | 公共 HTTPS 来源由用户配置显式声明;私网仍需 `allow_private`/`allow_loopback` | | `model` | 用户配置的模型端点 | 出口探测/审计 | 仅显式 `allowed_hosts` | | `knowledge-embedding` | 用户配置的端点 | 可选 | 仅显式 `allowed_hosts` | @@ -19,6 +20,8 @@ 默认禁止:遥测、反馈上传、第三方 CDN/字体/脚本、任意 URL、内网扫描。云端 metadata 地址(`169.254.169.254`、`fd00:ec2::254`、`100.100.100.200`)使用独立拒绝码。 +`market` 的 URL 只来自用户拥有的 `MQDH_HOME/config/market.json`,模型不能提供来源或资产 URL。该用途允许配置中的公共 HTTPS 来源,因为来源列表本身是用户授权;私网/loopback 目标仍必须落在 `allow_private`/`allow_loopback`,DNS 解析后的私网地址同样拒绝。 + ## 2. 配置 默认值写在 `defaultNetworkConfig()`;用户配置为 `MQDH_HOME/config/network.json`(0600),未知键直接报错,避免拼写错误静默放宽策略。 diff --git a/docs/mqdh/README.md b/docs/mqdh/README.md index 51b2d4bb9f..1146eb9635 100644 --- a/docs/mqdh/README.md +++ b/docs/mqdh/README.md @@ -4,6 +4,7 @@ | --- | --- | | [ARCHITECTURE.md](ARCHITECTURE.md) | 产品边界、包结构、数据布局、执行与安全模型 | | [ECOSYSTEM.md](ECOSYSTEM.md) | 生态目录的发现、浏览与安装边界 | +| [MARKET.md](MARKET.md) | 动态来源、市场索引、用户级能力存储与项目导入合同 | | [NETWORK.md](NETWORK.md) | 默认出口、代理/镜像/离线、审计与拒绝码 | | [BOOTSTRAP.md](BOOTSTRAP.md) | 首次启动状态机、`doctor`/`repair`、离线与失败处理 | | [DIAGNOSTICS.md](DIAGNOSTICS.md) | 本地脱敏报告、去重/限额与显式 Issue 提交 | diff --git a/docs/mqdh/STATUS.md b/docs/mqdh/STATUS.md index 8083d371a5..8afb859cce 100644 --- a/docs/mqdh/STATUS.md +++ b/docs/mqdh/STATUS.md @@ -1,6 +1,6 @@ # Marqdo Harness 状态与门禁 -本文件是 MQDH 现状的唯一产品状态来源。日期:2026-11-28。应用提交以 `git rev-parse HEAD` 为准;上游基线为 DSH `4b399c39a6d1479cd84ca591b4d7c88e24d38a96`(标签 `dsh-v0.2.3-alpha.2`)。证据目录见 [evidence/](evidence/)。 +本文件是 MQDH 现状的唯一产品状态来源。日期:2026-11-29。应用提交以 `git rev-parse HEAD` 为准;上游基线为 DSH `4b399c39a6d1479cd84ca591b4d7c88e24d38a96`(标签 `dsh-v0.2.3-alpha.2`)。证据目录见 [evidence/](evidence/)。 状态定义:**PASS** 表示本仓库或本机真实命令已通过并记录;**PARTIAL** 表示实现存在且已覆盖主要路径,但门禁要求的一部分尚未验证;**UNVERIFIED** 表示未运行或环境不具备,不能当作通过;**FAIL** 表示真实失败。 @@ -70,7 +70,7 @@ | S03 文件/进程/网络边界 | PARTIAL | 路径/符号链接/argv/进程组/超时/输出上限有测试;OS 级隔离依赖 DSH 沙箱,未声称强隔离。 | | S04 插件/profile 旁路 | PASS | `plugin-manager` 服务关闭;插件 market/manager 工具不可用;不是仅隐藏 UI。 | | S05 工作区隔离 | PARTIAL | 工作区显式且路径受控;未实现每任务独立目录与跨工作区审计。 | -| S06 浏览器真实交互 | PARTIAL | HTTP 验证页面/状态/知识导入检索/生态安装/工具安装;未运行浏览器自动化。 | +| S06 浏览器真实交互 | PARTIAL | 市场工作台已用 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。 | @@ -120,10 +120,15 @@ | 门禁 | 状态 | 证据或限制 | | --- | --- | --- | -| CAT-01 固定顺序 Runtime/Tool/Std/Ext/Knowledge 与真实来源 | PARTIAL | `/mqdh` 生态目录按固定顺序投影真实状态;Tool 候选可显式安装,Runtime 可显式切换,Ext 只做文件摘要 + CLI 锁检查,Std 只随 Bundle。浏览器/键盘/窄窗口/主题验收未运行。 | +| CAT-01 固定顺序 Runtime/Tool/Std/Ext/Knowledge 与真实来源 | PARTIAL | `/mqdh` 生态目录按固定顺序投影真实状态;Runtime 可显式切换,Tool 候选由市场来源驱动,Ext 市场/已安装/当前项目三段视图与 CLI 锁检查并存,Std 只随 Bundle。市场工作台浏览器/键盘/窄窗口/主题验收已通过;完整五组目录的浏览器遍历未运行。 | | CAT-02 打开、筛选、查看详情无自动安装/执行 | PASS | `/ecosystem` 只做本地状态与文件读取;候选检查、项目锁检查、Tool 移除均由按钮显式发起。 | -| CAT-03 Ext 锁语义(声明/锁差异/权限) | PARTIAL | 应用不解析第二套依赖图;显示 `marqdo.yaml`/`marqdo.lock` 存在性与摘要,显式按钮调用 CLI `sync --locked --json`,错误原文展示。 | -| CAT-04 真实浏览器与主题回归 | UNVERIFIED | 本轮无浏览器自动化环境;未伪造截图或键盘证据。 | +| 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/` 后由 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/主题。 | | SCOPE-01 局部调用、规则审阅与跨会话复用 | UNVERIFIED | 依赖真实模型/浏览器、E07 环境固定与主仓 #28 的独立规则/预期;应用现有 `marqdo_program` 已提供固定 argv/审批/证据基础,但未做真实模型验收。 | diff --git a/docs/mqdh/evidence/2026-11-29-market-ci.json b/docs/mqdh/evidence/2026-11-29-market-ci.json new file mode 100644 index 0000000000..9ff9385bb8 --- /dev/null +++ b/docs/mqdh/evidence/2026-11-29-market-ci.json @@ -0,0 +1,104 @@ +{ + "schema": "marqdo.mqdh.ci-evidence", + "schema_version": 1, + "status": "PASS", + "started_at": "2026-11-29T02:21:39Z", + "finished_at": "2026-11-29T02:21:52Z", + "application_sha": "629cff0301b160278c060d883098b529cb9ba4ff", + "upstream_remote": "https://git.cflmy.cn/cflmy/deepseek-harness.git", + "cli": { + "path": "/root/work/marqdo/.issue-work/cli/marqdo-3.0.0-rc.6-x86_64-unknown-linux-gnu/marqdo", + "source_sha": "63776735e924ade279cdf59d5c733dc24bfdabbb" + }, + "platform": "x86_64-unknown-linux-gnu", + "node": "v24.22.3", + "commands": [ + "pnpm install --frozen-lockfile", + "pnpm run build (when apps/cli/lib/bin.js is missing)", + "MARQDO_BIN= node --import tsx/esm --test packages/marqdo/harness/tests/*.test.ts" + ], + "logs": [ + "/root/work/marqdo/.issue-work/harness/ci-629/tests.log", + "/root/work/marqdo/.issue-work/harness/ci-629/install.log" + ], + "gates": { + "shared_egress": "no direct Node-side fetch outside src/network; browser fetch in src/web/assets.ts is the page API client", + "unit_and_integration": "node --test packages/marqdo/harness/tests/*.test.ts", + "real_release": "MQDH_TEST_INSTALL=1 install.test.ts + bootstrap.test.ts" + }, + "unverified": [ + "real remote-model conversation (no model credential in this lane)", + "browser end-to-end automation in this CI lane (market browser run recorded in docs/mqdh/evidence/2026-11-29-market.md)" + ], + "market": { + "unit_and_integration": { + "file": "packages/marqdo/harness/tests/market.test.ts", + "cases": 13, + "status": "PASS" + }, + "real_gitea_discovery": { + "source": "official", + "topics": [ + "marqdo-tool" + ], + "entries": [ + "official:tool:marqdo-knowledge@0.1.0-beta.3", + "official:tool:marqdo-lint@0.2.0", + "official:tool:marqdo-view@0.3.0" + ], + "warning": "cflmy/marqdo-prove: no installable x86_64-unknown-linux-gnu release", + "status": "PASS" + }, + "real_acceptance": { + "runtime": "v3.0.0-rc.6", + "tool": "marqdo-view@0.3.0 registered to the active Runtime", + "visibility": "0 before enable; 1 after global enable; 0 after disable", + "project_import": "CLI add + CLI lock + sync --locked exit 0", + "uninstall": "refused by project reference", + "status": "PASS", + "update": "pending_activation=true; explicit activate switched 0.1.0 to 0.2.0", + "offline": "official:offline, local:ok, 4 entries retained", + "evidence_freshness": "run evidence binds marqdo.lock digest; re-lock marks old evidence stale" + }, + "browser": { + "engine": "Playwright Chromium 149.0.7827.55 (Playwright 1.61.1)", + "flows": [ + "refresh directory source", + "open detail", + "install", + "enable project scope", + "local search", + "disable all" + ], + "page_errors": 0, + "console_errors": 0, + "external_requests": 0, + "keyboard": "market-refresh focus; Enter opened detail", + "viewports": [ + "1280x900", + "420x900" + ], + "themes": [ + "light", + "dark" + ], + "screenshots": [ + "2026-11-29-market-wide-light.png", + "2026-11-29-market-narrow-light.png", + "2026-11-29-market-narrow-dark.png" + ], + "status": "PASS" + }, + "unverified": [ + "enterprise proxy/mirror", + "signature enforcement", + "real build-required extension", + "Windows/macOS packaging", + "full five-group catalog browser traversal" + ] + }, + "remote_ci": { + "push": "https://ci.cflmy.cn/repos/21/pipeline/13/1", + "pull_request": "https://ci.cflmy.cn/repos/21/pipeline/14/1" + } +} diff --git a/docs/mqdh/evidence/2026-11-29-market-narrow-dark.png b/docs/mqdh/evidence/2026-11-29-market-narrow-dark.png new file mode 100644 index 0000000000..b70eaaefa8 Binary files /dev/null and b/docs/mqdh/evidence/2026-11-29-market-narrow-dark.png differ diff --git a/docs/mqdh/evidence/2026-11-29-market-narrow-light.png b/docs/mqdh/evidence/2026-11-29-market-narrow-light.png new file mode 100644 index 0000000000..24c42362cd Binary files /dev/null and b/docs/mqdh/evidence/2026-11-29-market-narrow-light.png differ diff --git a/docs/mqdh/evidence/2026-11-29-market-wide-light.png b/docs/mqdh/evidence/2026-11-29-market-wide-light.png new file mode 100644 index 0000000000..1285e69514 Binary files /dev/null and b/docs/mqdh/evidence/2026-11-29-market-wide-light.png differ diff --git a/docs/mqdh/evidence/2026-11-29-market.md b/docs/mqdh/evidence/2026-11-29-market.md new file mode 100644 index 0000000000..7c0f8749df --- /dev/null +++ b/docs/mqdh/evidence/2026-11-29-market.md @@ -0,0 +1,106 @@ +# 2026-11-29 扩展市场、能力控制与项目导入证据 + +状态:本地真实命令 **PASS**;真实浏览器/键盘/窄窗口/暗色回归 **UNVERIFIED**。实现身份与命令退出码见 [CI 证据 JSON](2026-11-29-market-ci.json);平台 `x86_64-unknown-linux-gnu`,glibc 2.43,Node `v24.22.3`。 + +## 1. 输入与身份 + +| 输入 | 身份 | +| --- | --- | +| CLI Runtime | `v3.0.0-rc.6`,source `63776735e924ade279cdf59d5c733dc24bfdabbb`,资产 `8dc0b006302e03c23451b8ea9f8a0fcdae8bf67c80c546bee2434bf69755bfe3` | +| Tool view | `v0.3.0`,资产 `1cfb319ea0be7215f95e153a3d0f9bb74da1754ac83f77c366d768d37440a0b1`,source `04f3a0e9e5dcbf81166c54a993a44c27fa8ed642` | +| Tool knowledge | `v0.1.0-beta.3`,资产 `feaa99701c01123c6eab3e804226dbb4096c3272b1e4f917c421233948198c55` | +| Tool lint | `v0.2.0`,资产 `5ed23c9c3651b3b290b8ba7c042e99491deacf4ec801c56943eadf2fababf44c` | +| 市场来源 | `official` Gitea `https://git.cflmy.cn`,owner `cflmy`,topic `marqdo-tool` | + +| 本地 ext fixture | 由 `marqdo init` 生成、`tar -czf` 打包的 `demo-ext`,摘要由目录索引刷新时计算 | + +`marqdo-prove` 的公开 Release 没有当前平台资产,市场刷新如实记录 warning,不生成可安装条目,也不伪造候选。 + +## 2. 单元/集成测试 + +命令: + +```sh +MARQDO_BIN=/marqdo node --import tsx/esm --test packages/marqdo/harness/tests/*.test.ts +``` + +结果:73 项,71 pass,2 skipped(真实 release 安装测试由 `MQDH_TEST_INSTALL=1` 单独运行),0 fail。 + +`market.test.ts` 覆盖:默认来源、配置拒绝、目录发现、TTL 缓存、new/changed/stale、来源隔离、摘要/大小不匹配、符号链接归档拒绝、安装/启用/撤销、未安装导入拒绝、项目字面引用卸载拒绝、构建门禁、项目内副本 + 固定 argv CLI add、页面 JS 可解析且无 `innerHTML`。 + +## 3. 真实首次启动 + +命令: + +```sh +MQDH_TEST_INSTALL=1 node --import tsx/esm --test --test-concurrency=1 packages/marqdo/harness/tests/bootstrap.test.ts +``` + +结果:1 pass,0 fail(约 6.9s)。在线默认 Tool 安装已改走市场来源:`official` topic 发现 knowledge/view,安装到用户级能力存储并注册到当前 Runtime 隔离 Tool home;Runtime 校验、Bundle digest、真实 check/call smoke 与知识 compile/query 仍通过。 + +## 4. 真实市场、能力控制与项目导入 + +本地验收脚本按以下顺序执行(脚本位于工作区 `.issue-work/harness/accept-real.mts`,不进入仓库): + +1. `EcosystemManager.install` 用 rc.6 离线归档校验并激活 Runtime; +2. `MarketIndexService.refresh({force:true})` 通过 Gitea topic 发现 `knowledge@0.1.0-beta.3`、`lint@0.2.0`、`view@0.3.0`; +3. 安装 view:下载、SHA-256/大小校验、解包、`tool.json` 校验、CLI `tool install`,能力可见性在启用前为 0; +4. 全局启用后 `visible` 返回 `official:tool:marqdo-view:0.3.0:view`,撤销后立即为 0; +5. 本地目录来源安装 `demo-ext@0.1.0`;未启用时 `marqdo_find(kind=ext)` 为 0,项目作用域启用后出现 `ext:local:ext:demo-ext`; +6. `marqdo init` 初始化项目和 ext 包;市场导入复制到 `marqdo-vendor/demo`,CLI `add` 写入 `path: ./marqdo-vendor/demo`; +7. CLI `lock --json` 生成 `marqdo.lock`,CLI `sync --locked --json` exit 0; +8. 卸载被拒绝:`capability is referenced by marqdo.yaml, marqdo.lock`; +9. 目录索引出现 `0.2.0` 后安装:`pending_activation=true`、active 仍为 `0.1.0`;显式 `activate` 后 active 变为 `0.2.0`;运行证据绑定项目锁摘要,重新锁后旧证据按 fresh/stale 重算; +10. 配置 `offline=true` 后强制刷新:`official:offline`、`local:ok`,保留 4 个缓存/目录条目,无静默清空。 + +关键输出: + +```text +market entries [ + 'official:tool:marqdo-knowledge@0.1.0-beta.3', + 'official:tool:marqdo-lint@0.2.0', + 'official:tool:marqdo-view@0.3.0' +] +view installed 0.3.0 active 0.3.0 registered true +visible before enable 0 +visible after enable [ 'official:tool:marqdo-view:0.3.0:view' ] +visible after disable 0 +demo visible before enable 0 +demo visible after enable [ 'ext:local:ext:demo-ext' ] +manifest has project path true +lock success true lockfile 644 +sync locked 0 +uninstall refused capability is referenced by marqdo.yaml, marqdo.lock +update pending true active 0.1.0 requires_build false +activated 0.2.0 path .../capabilities/store/local-ext-demo-ext/0.2.0-ba32af8dc7d0 +offline source states [ 'official:offline', 'local:ok' ] entries 4 +``` + +## 5. 页面与同源边界 + +- `APP_JS` 用 `vm.Script` 解析通过;页面无 `innerHTML` 赋值、无外部字体/脚本/CDN、无在线 `url()`;旧版两处换行字符串导致的 JS 语法错误已修正。 +- `/mqdh/api/market*` 全部要求同源 fence;安装/激活/卸载/启用/撤销/导入/锁/来源写入都要求 `confirm:true`。真实 HTTP 验证:`/mqdh/api/market` 200;目录来源 refresh 返回 `local:ext:demo-ext@0.2.0` `new`;install 200(active `0.2.0`、ready);enable 返回 `global`、disable 清空;`Sec-Fetch-Site: cross-site` 返回 403。 +- 模型工具不提供市场安装/启用/来源/锁动作;`marqdo_find` 与 `marqdo_ecosystem capabilities` 只投影当前会话/项目已启用能力。 + +## 6. 真实浏览器与主题回归 + +Playwright Chromium `149.0.7827.55`(Playwright `1.61.1`)在 `http://127.0.0.1:3098/mqdh` 上真实操作:打开生态中心 → 刷新目录来源 → 打开 `Demo ext@0.2.0` 详情 → 安装 → 在“已安装”启用“当前项目” → 搜索 `demo`(本地过滤,无新请求)→ 撤销全部启用。结果:0 page error、0 console error、0 external request;`#market-refresh` 与市场行可通过键盘聚焦,Enter 打开详情;420px 窄窗口与 `prefers-color-scheme: dark` 均渲染,`body` 背景为 `rgb(23, 24, 26)`。 + +![市场宽屏亮色](2026-11-29-market-wide-light.png) + +![市场窄屏亮色](2026-11-29-market-narrow-light.png) + +![市场窄屏暗色](2026-11-29-market-narrow-dark.png) + +## 7. 未验证 + +- 真实浏览器、键盘遍历、窄窗口、亮/暗主题截图与回归; +- 企业内网 Gitea、真实代理/镜像下的市场刷新; +- 签名的实际校验(当前只展示 `present`/`unsigned`,不做中央信任裁决); +- 真实需要构建的扩展;构建路径仅在本地 fixture 用 `/bin/sh -c` 验证显式同意与失败回滚; +- Windows/macOS 路径、大小写与打包; +- 发布管线上的市场测试(当前 CI 覆盖单元测试与真实 bootstrap;市场真实 HTTP 证据来自本轮本机命令)。 + +## 8. 机器可读证据 + +[2026-11-29-market-ci.json](2026-11-29-market-ci.json) 记录 CI 命令、退出码、应用 SHA、CLI source SHA、平台、日志路径与未验证项。 diff --git a/packages/marqdo/harness/src/bootstrap/manager.ts b/packages/marqdo/harness/src/bootstrap/manager.ts index ea0dcf815d..03a001e466 100644 --- a/packages/marqdo/harness/src/bootstrap/manager.ts +++ b/packages/marqdo/harness/src/bootstrap/manager.ts @@ -25,6 +25,8 @@ import { EcosystemError } from '../ecosystem/manager.ts' import type { EnvironmentManifest, InstallSmokeContext } from '../ecosystem/manager.ts' import { discoverRelease, ReleaseError } from '../ecosystem/sources.ts' import type { ReleaseCandidate, ReleasedComponent } from '../ecosystem/sources.ts' +import type { MarketIndexService } from '../market/index.ts' +import type { CapabilityView } from '../market/capabilities.ts' import { MarqdoCli } from '../execution/cli.ts' import { KnowledgeError } from '../knowledge/manager.ts' import { NetworkError } from '../network/client.ts' @@ -731,23 +733,50 @@ export class BootstrapManager { await commit() const directory = offline ?? envOffline() const target = (await detectPlatform(this.#layout.home)).target + let marketError: string | null = null + let market: Awaited> | null = null + if (directory === undefined) { + try { + market = await this.#runtime.market.refresh() + } catch (error) { + marketError = error instanceof Error ? error.message : String(error) + } + } for (const component of ['knowledge', 'view'] as const) { if (!force && tools[component]?.installed === true && tools[component]?.status === 'ok') continue try { - const local = directory === undefined ? undefined : await this.#offlineTool(directory, component, target) - if (directory !== undefined && local === undefined) { + if (directory !== undefined) { + const local = await this.#offlineTool(directory, component, target) + if (local === undefined) { + tools[component] = { + command: component, installed: false, version: null, tag: null, + status: 'skipped', code: 'bootstrap.offline_tool_missing', + detail: `offline directory has no ${component} archive for ${target}`, + } + await commit() + continue + } + const installed = await this.#installToolWithRetry(component, local) tools[component] = { - command: component, installed: false, version: null, tag: null, - status: 'skipped', code: 'bootstrap.offline_tool_missing', - detail: `offline directory has no ${component} archive for ${target}`, + command: installed.command, installed: true, version: installed.version, tag: installed.tag, + status: 'ok', code: null, detail: `${installed.tag} · ${installed.sourceSha ?? 'source sha unknown'}`, + } + } else { + if (marketError !== null || market === null) { + throw new BootstrapError('bootstrap.market_unavailable', `market refresh failed: ${marketError ?? 'no projection'}`) + } + const entry = market.entries.find(candidate => ( + candidate.kind === 'tool' && (candidate.id === `marqdo-${component}` || candidate.manifest.tools.includes(component)) + )) + if (entry === undefined) { + throw new BootstrapError('bootstrap.tool_not_found', `market has no tool entry for ${component}`) + } + const installed = await this.#installMarketToolWithRetry(entry.key) + tools[component] = { + command: installed.command ?? component, installed: true, version: installed.active_version ?? entry.version, + tag: installed.active_version ?? entry.version, status: 'ok', code: null, + detail: `${entry.version} · ${entry.source_sha ?? 'source sha unknown'} · ${entry.source_label}`, } - await commit() - continue - } - const installed = await this.#installToolWithRetry(component, local) - tools[component] = { - command: installed.command, installed: true, version: installed.version, tag: installed.tag, - status: 'ok', code: null, detail: `${installed.tag} · ${installed.sourceSha ?? 'source sha unknown'}`, } } catch (error) { const mapped = mapBootstrapError(error) @@ -787,6 +816,24 @@ export class BootstrapManager { throw lastError } + /** Install one Tool through the market capability store, retrying a transient failure. */ + async #installMarketToolWithRetry(key: string): Promise { + let lastError: unknown + for (let attempt = 0; attempt < 2; attempt++) { + try { + const installed = await this.#runtime.capabilities.install(key) + return installed.capability + } catch (error) { + lastError = error + const code = mapBootstrapError(error).code + const retryable = /(timeout|connect_refused|connection_reset|dns_failed|http_5\d\d|proxy_)/.test(code) + if (attempt === 1 || !retryable) throw error + await new Promise(resolve => setTimeout(resolve, 500)) + } + } + throw lastError + } + /** Real check/call smoke against the extracted candidate, before activation. */ async #smokeRuntime(context: InstallSmokeContext): Promise { const workspace = join(this.#layout.tmp, `bootstrap-smoke-${randomBytes(6).toString('hex')}`) diff --git a/packages/marqdo/harness/src/core/home.ts b/packages/marqdo/harness/src/core/home.ts index 51ac63a073..5f3bcd5c85 100644 --- a/packages/marqdo/harness/src/core/home.ts +++ b/packages/marqdo/harness/src/core/home.ts @@ -39,6 +39,16 @@ export interface MdhLayout { readonly environments: string /** Atomic active-environment pointer. */ readonly current: string + /** Rebuildable market index and change events. */ + readonly market: string + readonly marketIndex: string + readonly marketEvents: string + /** Authoritative user-level installed-capability store. */ + readonly capabilities: string + readonly capabilityIndex: string + readonly capabilityStore: string + readonly capabilityStaging: string + readonly capabilityAudit: string /** Private knowledge root. */ readonly knowledge: string /** Imported original knowledge documents. */ @@ -83,6 +93,14 @@ export function layoutOf(home: string): MdhLayout { staging: join(root, 'ecosystem', 'staging'), environments: join(root, 'ecosystem', 'environments'), current: join(root, 'ecosystem', 'current.json'), + market: join(root, 'market'), + marketIndex: join(root, 'market', 'index.json'), + marketEvents: join(root, 'market', 'events.jsonl'), + capabilities: join(root, 'capabilities'), + capabilityIndex: join(root, 'capabilities', 'index.json'), + capabilityStore: join(root, 'capabilities', 'store'), + capabilityStaging: join(root, 'capabilities', 'staging'), + capabilityAudit: join(root, 'capabilities', 'audit.jsonl'), knowledge: join(root, 'knowledge'), knowledgeSources: join(root, 'knowledge', 'sources'), knowledgeIndex: join(root, 'knowledge', 'index'), @@ -114,6 +132,10 @@ export async function ensureMdhHome(home: string): Promise { layout.artifacts, layout.staging, layout.environments, + layout.market, + layout.capabilities, + layout.capabilityStore, + layout.capabilityStaging, layout.knowledge, layout.knowledgeSources, layout.knowledgeIndex, diff --git a/packages/marqdo/harness/src/core/process.ts b/packages/marqdo/harness/src/core/process.ts index 20e788c6be..4578b85970 100644 --- a/packages/marqdo/harness/src/core/process.ts +++ b/packages/marqdo/harness/src/core/process.ts @@ -157,7 +157,8 @@ export async function runProcess( export function killProcessGroup(pid: number): void { try { process.kill(-pid, 'SIGKILL') - } catch { - // Already gone. + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== 'ESRCH' && code !== 'EPERM') throw error } } diff --git a/packages/marqdo/harness/src/diagnostics/redact.ts b/packages/marqdo/harness/src/diagnostics/redact.ts index ccf7f61bb2..eb45f8881c 100644 --- a/packages/marqdo/harness/src/diagnostics/redact.ts +++ b/packages/marqdo/harness/src/diagnostics/redact.ts @@ -96,8 +96,8 @@ export function redactText(text: string, context: RedactionContext = {}): Redact output = output.replace(new RegExp(`\\b${escaped(user)}\\b`, 'g'), '$USER') if (before !== output) removed.push('username') } - } catch { - // A host without a passwd entry has no username to remove. + } catch (error) { + void error } for (const secret of [...(context.secrets ?? []), ...environmentSecrets()]) { if (secret.length < MINIMUM_SECRET_LENGTH) continue diff --git a/packages/marqdo/harness/src/ecosystem/manager.ts b/packages/marqdo/harness/src/ecosystem/manager.ts index d82fd32dd5..29062a8476 100644 --- a/packages/marqdo/harness/src/ecosystem/manager.ts +++ b/packages/marqdo/harness/src/ecosystem/manager.ts @@ -59,7 +59,7 @@ interface ReleaseInfo { target_triple: string supported_platforms?: string[] binaries?: Record - stdlib?: { version: string; tree_digest: string; aliases_digest?: string; name?: string } + stdlib?: { version: string; tree_digest: string; aliases_digest?: string; name?: string; files?: string[] } protocols?: Record } @@ -253,8 +253,8 @@ export class EcosystemManager { const root = join(this.#layout.environments, current.id) const stdlib = await readJson<{ modules?: unknown; files?: unknown }>(join(root, 'stdlib', 'stdlib.json')) const release = await readJson(join(root, 'RELEASE_INFO.json')) - if (release?.stdlib?.name && Array.isArray((release.stdlib as unknown as { files?: string[] }).files)) { - modules = (release.stdlib as unknown as { files: string[] }).files.filter(file => file.endsWith('.mq.md')) + if (release?.stdlib?.name && Array.isArray(release.stdlib.files)) { + modules = release.stdlib.files.filter(file => file.endsWith('.mq.md')) } else if (stdlib && Array.isArray(stdlib.files)) { modules = stdlib.files.filter((file): file is string => typeof file === 'string' && file.endsWith('.mq.md')) } diff --git a/packages/marqdo/harness/src/execution/evidence.ts b/packages/marqdo/harness/src/execution/evidence.ts index 5b0c3a724c..554c2ab7e6 100644 --- a/packages/marqdo/harness/src/execution/evidence.ts +++ b/packages/marqdo/harness/src/execution/evidence.ts @@ -132,7 +132,18 @@ export class EvidenceStore { if (current !== record.document_digest) { return { state: 'stale', detail: `source changed: now ${current}` } } - return { state: 'fresh', detail: 'source and Analysis identity match' } + if (record.lock_digest !== null) { + let currentLock: string + try { + currentLock = await digestFile(join(workspace, 'marqdo.lock')) + } catch { + return { state: 'stale', detail: 'project lock is missing' } + } + if (currentLock !== record.lock_digest) { + return { state: 'stale', detail: `project lock changed: now ${currentLock}` } + } + } + return { state: 'fresh', detail: 'source, Analysis and project lock identities match' } } } diff --git a/packages/marqdo/harness/src/market/capabilities.ts b/packages/marqdo/harness/src/market/capabilities.ts new file mode 100644 index 0000000000..7256603d5e --- /dev/null +++ b/packages/marqdo/harness/src/market/capabilities.ts @@ -0,0 +1,987 @@ +/** + * User-level capability store. + * + * Installing a market entry writes a verified payload below + * `MQDH_HOME/capabilities/store`; it never edits the project manifest or lock. + * A capability is visible to a model only after the user enables it for a + * global, session or project scope, and it is callable only while an active + * version exists. Project import and lock generation run the published CLI + * commands; the application never writes `marqdo.lock`. + * + * @module @marqdo/mqdh-harness/market/capabilities + */ + +import { randomBytes } from 'node:crypto' +import { constants } from 'node:fs' +import { + access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, +} from 'node:fs/promises' +import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path' +import { copyTree, digestBytes, digestFile, isDirectory, isWithin, readJson, readText, writeJsonAtomic } from '../core/fsx.ts' +import type { MdhLayout } from '../core/home.ts' +import { withLock } from '../core/lock.ts' +import { runProcess, type RunResult } from '../core/process.ts' +import { extractTarGz } from '../core/tar.ts' +import type { EgressClient } from '../network/client.ts' +import type { MarqdoCli } from '../execution/cli.ts' +import { compareVersions, emptyCapabilityIndex, entryKey, parseCapabilityIndex, safeSegment, scopeMatches } from './contract.ts' +import type { + CapabilityAudit, CapabilityImport, CapabilityIndex, CapabilityRecord, CapabilityScope, + CapabilityVersion, MarketEntry, MarketIndex, MarketManifest, +} from './contract.ts' +import type { MarketIndexService } from './index.ts' +import { MARKET_ERROR, MarketError } from './errors.ts' + +/** Scope supplied by the Web UI. */ +export interface ScopeRequest { + readonly kind: 'global' | 'session' | 'project' + readonly id?: string | undefined +} + +/** One installed capability rendered for the workbench. */ +export interface CapabilityView { + readonly key: string + readonly kind: 'ext' | 'tool' + readonly id: string + readonly name: string + readonly summary: string + readonly source_id: string + readonly source_label: string + readonly source_kind: 'gitea' | 'directory' + readonly active_version: string | null + readonly active_sha256: string | null + readonly active_path: string | null + readonly command: string | null + readonly versions: readonly { + readonly version: string + readonly sha256: string + readonly size: number + readonly installed_at: string + readonly active: boolean + readonly build_executed: boolean + readonly tool_registered: boolean + }[] + readonly enabled: readonly CapabilityScope[] + readonly project_references: readonly string[] + readonly update_available: boolean + readonly latest_version: string | null + readonly build_required: boolean + readonly ready: boolean +} + +/** One capability visible to a model scope. */ +export interface VisibleCapability { + readonly key: string + readonly kind: 'ext' | 'tool' + readonly id: string + readonly name: string + readonly version: string + readonly path: string + readonly command: string | null + readonly permissions: readonly string[] + readonly effects: readonly string[] + readonly enabled_by: readonly string[] +} + +/** Install outcome. */ +export interface InstallOutcome { + readonly capability: CapabilityView + readonly version: CapabilityVersion + readonly already_installed: boolean + readonly activated: boolean + readonly pending_activation: boolean + readonly requires_build: boolean +} + +/** Project import outcome. */ +export interface ImportOutcome { + readonly alias: string + /** Project-relative dependency path written to `marqdo.yaml` by the CLI. */ + readonly path: string + /** Canonical installed payload path. */ + readonly store_path: string + readonly manifest: string | null + readonly next: string +} + +/** Dependency on the CLI binary, kept as a narrow callback. */ +type CliProvider = () => Promise + +/** Dependency on the active environment's isolated Tool home. */ +type ToolHomeProvider = () => Promise + +/** Capability store options. */ +export interface CapabilityStoreOptions { + readonly layout: MdhLayout + readonly network: EgressClient + readonly market: MarketIndexService + readonly cli: CliProvider + readonly toolHome: ToolHomeProvider + readonly workspace: () => string +} + +/** Find one regular file below a root without following links. */ +async function findNamedFile(root: string, name: string, maxDepth: number): Promise { + const queue: { directory: string; depth: number }[] = [{ directory: root, depth: 0 }] + while (queue.length > 0) { + const current = queue.shift() + if (current === undefined) break + const entries = await readdir(current.directory, { withFileTypes: true }) + entries.sort((left, right) => left.name.localeCompare(right.name, 'en')) + for (const entry of entries) { + const absolute = join(current.directory, entry.name) + if (entry.isFile() && entry.name === name) return absolute + if (entry.isDirectory() && current.depth < maxDepth) { + queue.push({ directory: absolute, depth: current.depth + 1 }) + } + } + } + return undefined +} + +/** Move the directory produced by the archive to the payload root. */ +async function locateRoot(tree: string): Promise { + const entries = await readdir(tree, { withFileTypes: true }) + const files = await readdir(tree) + const only = entries[0] + if (files.length === 1 && only !== undefined && only.isDirectory()) return join(tree, only.name) + return tree +} + +/** Resolve a build program from an absolute path or PATH. */ +async function resolveProgram(name: string): Promise { + if (isAbsolute(name)) return name + const path = process.env.PATH + if (path === undefined) throw new MarketError(MARKET_ERROR.buildFailed, `cannot resolve build program: ${name}`) + for (const directory of path.split(delimiter)) { + if (directory === '') continue + const candidate = join(directory, name) + try { + await access(candidate, constants.X_OK) + return candidate + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + } + throw new MarketError(MARKET_ERROR.buildFailed, `build program is not executable: ${name}`) +} + +/** Compare an installed version against a newer market version. */ +function isNewer(installed: string | null, latest: string | null): boolean { + if (installed === null || latest === null) return false + return compareVersions(installed, latest) > 0 +} + +/** Active version of one record. */ +function activeOf(record: CapabilityRecord): CapabilityVersion | null { + if (record.active === null) return null + return record.versions.find(version => version.sha256 === record.active) ?? null +} + +/** Absolute payload path of one version. */ +function payloadPath(layout: MdhLayout, version: CapabilityVersion): string { + return join(layout.capabilityStore, version.path) +} + +/** Command declared by one capability manifest. */ +function commandOf(version: CapabilityVersion): string | null { + const command = version.manifest.tools[0] + return command === undefined ? null : command +} + +/** Whether a version satisfies its declared build requirement. */ +function buildSatisfied(version: CapabilityVersion): boolean { + if (version.manifest.build?.required !== true) return true + return version.build_executed +} + +/** The installed-capability authority. */ +export class CapabilityStore { + readonly #layout: MdhLayout + readonly #network: EgressClient + readonly #market: MarketIndexService + readonly #cli: CliProvider + readonly #toolHome: ToolHomeProvider + readonly #workspace: () => string + + constructor(options: CapabilityStoreOptions) { + this.#layout = options.layout + this.#network = options.network + this.#market = options.market + this.#cli = options.cli + this.#toolHome = options.toolHome + this.#workspace = options.workspace + } + + /** Project scope identity derived from the resolved workspace path. */ + projectDigest(): string { + return digestBytes(resolve(this.#workspace())) + } + + /** Read the authoritative capability index. */ + async index(): Promise { + const raw = await readJson>(this.#layout.capabilityIndex) + return raw === undefined ? emptyCapabilityIndex() : parseCapabilityIndex(raw) + } + + /** Write the capability index atomically. */ + async #write(index: CapabilityIndex): Promise { + await writeJsonAtomic(this.#layout.capabilityIndex, index, 0o600) + } + + /** Append one audit record. */ + async #audit(record: CapabilityAudit): Promise { + const handle = await open(this.#layout.capabilityAudit, 'a', 0o600) + try { + await handle.writeFile(`${JSON.stringify(record)}\n`) + } finally { + await handle.close() + } + } + + /** Read recent audit records, newest last. */ + async audit(limit = 100): Promise { + let text = '' + try { + text = await readFile(this.#layout.capabilityAudit, 'utf8') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + return [] + } + const records: CapabilityAudit[] = [] + for (const line of text.split('\n')) { + if (line.trim() === '') continue + try { + const parsed: unknown = JSON.parse(line) + if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { + const value = parsed as Record + const action = value.action + const actions = ['install', 'activate', 'enable', 'disable', 'uninstall', 'project-import', 'project-lock', 'build'] + if (typeof value.at !== 'string' || typeof action !== 'string' || !actions.includes(action)) continue + if (typeof value.key !== 'string' || typeof value.source_id !== 'string') continue + if (value.result !== 'ok' && value.result !== 'failed') continue + records.push({ + at: value.at, + action: action as CapabilityAudit['action'], + key: value.key, + source_id: value.source_id, + version: typeof value.version === 'string' ? value.version : null, + sha256: typeof value.sha256 === 'string' ? value.sha256 : null, + scope: typeof value.scope === 'string' ? value.scope : null, + result: value.result, + detail: typeof value.detail === 'string' ? value.detail : null, + }) + } + } catch (error) { + if (!(error instanceof SyntaxError)) throw error + } + } + return records.slice(-Math.max(1, limit)) + } + + /** Read project manifest/lock text for conservative reference checks. */ + async #projectTexts(): Promise<{ manifest: string; lock: string }> { + const workspace = this.#workspace() + return { + manifest: (await readText(join(workspace, 'marqdo.yaml'))) ?? '', + lock: (await readText(join(workspace, 'marqdo.lock'))) ?? '', + } + } + + /** Conservative literal references; this is not a second lock parser. */ + #references(record: CapabilityRecord, texts: { manifest: string; lock: string }): string[] { + const active = activeOf(record) + if (active === null) return [] + const needles = [ + payloadPath(this.#layout, active), + ...record.imports.flatMap(item => [item.path, ...(item.project_path === null ? [] : [item.project_path])]), + ] + const found: string[] = [] + for (const needle of needles) { + if (texts.manifest.includes(needle)) found.push('marqdo.yaml') + if (texts.lock.includes(needle)) found.push('marqdo.lock') + } + return [...new Set(found)] + } + + /** Render one capability record. */ + #view(record: CapabilityRecord, market: MarketIndex, texts: { manifest: string; lock: string }): CapabilityView { + const active = activeOf(record) + const entry = market.entries.find(candidate => candidate.key === record.key) + const latest = entry?.version ?? null + const version = active ?? record.versions[0] ?? null + const buildRequired = version?.manifest.build?.required === true + const ready = active !== null && buildSatisfied(active) && (record.kind !== 'tool' || active.tool_registered) + return { + key: record.key, + kind: record.kind, + id: record.id, + name: record.name, + summary: record.summary, + source_id: record.source_id, + source_label: record.source_label, + source_kind: record.source_kind, + active_version: active?.version ?? null, + active_sha256: active?.sha256 ?? null, + active_path: active === null ? null : payloadPath(this.#layout, active), + command: active === null ? null : commandOf(active), + versions: record.versions.map(item => ({ + version: item.version, + sha256: item.sha256, + size: item.size, + installed_at: item.installed_at, + active: active?.sha256 === item.sha256, + build_executed: item.build_executed, + tool_registered: item.tool_registered, + })), + enabled: record.enabled, + project_references: this.#references(record, texts), + update_available: isNewer(active?.version ?? null, latest), + latest_version: latest, + build_required: buildRequired, + ready, + } + } + + /** List installed capabilities. */ + async capabilities(): Promise { + const index = await this.index() + const market = await this.#market.current() + const texts = await this.#projectTexts() + return index.capabilities + .map(record => this.#view(record, market, texts)) + .sort((left, right) => left.name.localeCompare(right.name, 'en')) + } + + /** Read one capability by key. */ + async capability(key: string): Promise { + return (await this.capabilities()).find(capability => capability.key === key) + } + + /** + * Read the bounded manifest text of one installed capability. + * @param key - capability key. + * @param maxBytes - maximum returned bytes. + */ + async describe(key: string, maxBytes = 16 * 1024): Promise<{ text: string; path: string; digest: string }> { + const index = await this.index() + const record = index.capabilities.find(item => item.key === key) + if (record === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability is not installed: ${key}`) + const active = activeOf(record) + if (active === null) throw new MarketError(MARKET_ERROR.capabilityVersionUnknown, `capability has no active version: ${key}`) + const text = JSON.stringify({ + key: record.key, + name: record.name, + kind: record.kind, + source: { id: record.source_id, label: record.source_label }, + version: active.version, + path: payloadPath(this.#layout, active), + manifest: active.manifest, + signature: active.signature, + }, null, 2) + return { + text: text.length > maxBytes ? `${text.slice(0, maxBytes)}…` : text, + path: payloadPath(this.#layout, active), + digest: `sha256:${active.sha256}`, + } + } + + /** Read installed capabilities visible in one model scope. */ + async visible(sessionId: string | null, workspace = this.#workspace()): Promise { + const index = await this.index() + const project = digestBytes(resolve(workspace)) + const visible: VisibleCapability[] = [] + for (const record of index.capabilities) { + const active = activeOf(record) + if (active === null) continue + if (!buildSatisfied(active)) continue + if (record.kind === 'tool' && !active.tool_registered) continue + const matching = record.enabled.filter(scope => scopeMatches(scope, sessionId, project)) + if (matching.length === 0) continue + visible.push({ + key: record.key, + kind: record.kind, + id: record.id, + name: record.name, + version: active.version, + path: payloadPath(this.#layout, active), + command: commandOf(active), + permissions: active.manifest.permissions, + effects: active.manifest.effects, + enabled_by: matching.map(scope => scope.id === null ? scope.kind : `${scope.kind}:${scope.id}`), + }) + } + return visible.sort((left, right) => left.name.localeCompare(right.name, 'en')) + } + + /** Resolve the local source root for a directory entry. */ + async #copyLocalAsset(entry: MarketEntry, destination: string): Promise<{ size: number; sha256: string }> { + if (entry.asset.relative === null) throw new MarketError(MARKET_ERROR.installFailed, 'market entry has no local asset') + const config = await this.#market.config() + const source = config.sources.find(item => item.id === entry.source_id) + if (source === undefined || source.kind !== 'directory' || source.path === null) { + throw new MarketError(MARKET_ERROR.installFailed, `directory source ${entry.source_id} is not configured`) + } + const root = await realpath(source.path) + const absolute = resolve(join(root, entry.asset.relative)) + if (!isWithin(root, absolute) || isAbsolute(entry.asset.relative)) { + throw new MarketError(MARKET_ERROR.archiveUnsafe, `market asset escapes its source: ${entry.asset.relative}`) + } + const info = await lstat(absolute).catch(() => undefined) + if (info === undefined || info.isSymbolicLink() || !info.isFile()) { + throw new MarketError(MARKET_ERROR.archiveUnsafe, `market asset is not a regular file: ${entry.asset.name}`) + } + const canonical = await realpath(absolute) + if (!isWithin(root, canonical)) throw new MarketError(MARKET_ERROR.archiveUnsafe, 'market asset resolves outside its source') + await copyFile(absolute, destination, constants.COPYFILE_EXCL) + const digest = await digestFile(destination) + if (digest !== `sha256:${entry.asset.sha256}`) { + throw new MarketError(MARKET_ERROR.digestMismatch, `market asset digest mismatch: ${entry.asset.name}`) + } + const size = (await stat(destination)).size + if (entry.asset.size !== null && entry.asset.size !== size) { + throw new MarketError(MARKET_ERROR.digestMismatch, `market asset size mismatch: ${entry.asset.name}`) + } + return { size, sha256: entry.asset.sha256 } + } + + /** Download a remote asset through the single egress client. */ + async #downloadAsset(entry: MarketEntry, destination: string): Promise<{ size: number; sha256: string }> { + if (entry.asset.url === null) throw new MarketError(MARKET_ERROR.installFailed, 'market entry has no remote asset') + const config = await this.#market.config() + const source = config.sources.find(item => item.id === entry.source_id) + if (source === undefined || source.base === null || !entry.asset.url.startsWith(`${source.base}/`)) { + throw new MarketError(MARKET_ERROR.installFailed, 'market asset URL is outside its configured source') + } + const result = await this.#network.download({ + purpose: 'market', + url: entry.asset.url, + destination, + sha256: entry.asset.sha256, + ...(entry.asset.size === null ? {} : { size: entry.asset.size }), + }) + return { size: result.size, sha256: result.sha256.replace(/^sha256:/, '') } + } + + /** Explicitly run a declared build command. */ + async #build(version: CapabilityVersion, root: string): Promise { + const build = version.manifest.build + if (build === null || !build.required) return + if (build.command.length === 0) { + throw new MarketError(MARKET_ERROR.buildFailed, 'build is required but no command is declared') + } + const program = await resolveProgram(build.command[0] ?? '') + let result: RunResult + try { + result = await runProcess(program, build.command.slice(1), { + cwd: root, + env: { HOME: process.env.HOME, PATH: process.env.PATH }, + limits: { timeoutMs: 10 * 60_000, maxOutputBytes: 1024 * 1024 }, + }) + } catch (error) { + throw new MarketError(MARKET_ERROR.buildFailed, error instanceof Error ? error.message : String(error)) + } + if (result.exitCode !== 0) { + throw new MarketError(MARKET_ERROR.buildFailed, `build failed: ${(result.stderr || result.stdout).slice(0, 600)}`) + } + } + + /** Register an extracted Tool payload with the active CLI Tool home. */ + async #registerTool(version: CapabilityVersion, root: string): Promise { + const manifestPath = await findNamedFile(root, 'tool.json', 3) + if (manifestPath === undefined) throw new MarketError(MARKET_ERROR.installFailed, 'tool payload has no tool.json') + const tool = await readJson<{ command?: unknown }>(manifestPath) + if (typeof tool?.command !== 'string') throw new MarketError(MARKET_ERROR.installFailed, 'tool.json has no command') + const expected = commandOf(version) + if (expected !== null && tool.command !== expected) { + throw new MarketError(MARKET_ERROR.installFailed, `tool.json command ${tool.command} does not match ${expected}`) + } + const cli = await this.#cli() + const toolHome = await this.#toolHome() + if (!cli || !toolHome) throw new MarketError(MARKET_ERROR.runtimeNotInstalled, 'install a Runtime before registering a Tool') + const installed = await runProcess(cli.bin, ['tool', 'install', manifestPath], { + cwd: dirname(manifestPath), + env: { MARQDO_TOOL_HOME: toolHome }, + limits: { timeoutMs: 120_000, maxOutputBytes: 1024 * 1024 }, + }) + if (installed.exitCode !== 0) { + throw new MarketError(MARKET_ERROR.installFailed, `tool install failed: ${(installed.stderr || installed.stdout).slice(0, 600)}`) + } + return tool.command + } + + /** Remove one CLI Tool command when the runtime is available. */ + async #unregisterTool(command: string): Promise { + const cli = await this.#cli() + const toolHome = await this.#toolHome() + if (!cli || !toolHome) throw new MarketError(MARKET_ERROR.runtimeNotInstalled, 'the active Runtime is required to remove a Tool') + const removed = await runProcess(cli.bin, ['tool', 'remove', command], { + cwd: dirname(cli.bin), + env: { MARQDO_TOOL_HOME: toolHome }, + limits: { timeoutMs: 60_000, maxOutputBytes: 512 * 1024 }, + }) + if (removed.exitCode !== 0) { + throw new MarketError(MARKET_ERROR.installFailed, `tool remove failed: ${(removed.stderr || removed.stdout).slice(0, 600)}`) + } + } + + /** + * Install one entry from the current projection. + * + * The entry is resolved by key from the index, so a model or caller cannot + * supply a URL or path. Archive extraction enforces the shared path-safety + * limits. A newer version is installed beside the active one and never + * activated silently. + * @param key - projected entry key. + * @param options - explicit build consent. + * @returns the installed capability and activation state. + */ + async install(key: string, options: { allowBuild?: boolean | undefined } = {}): Promise { + return await withLock(join(this.#layout.capabilities, 'operation.lock'), async () => { + const entry = await this.#market.entry(key) + if (entry === undefined) throw new MarketError(MARKET_ERROR.entryUnknown, `unknown market entry: ${key}`) + if (entry.availability !== 'available') { + throw new MarketError(MARKET_ERROR.entryUnavailable, entry.unavailable_reason ?? `entry is ${entry.availability}`) + } + const index = await this.index() + const existing = index.capabilities.find(record => record.key === key) + const duplicate = existing?.versions.find(version => version.sha256 === entry.asset.sha256) + if (existing !== undefined && duplicate !== undefined) { + if (duplicate.manifest.build?.required === true && !duplicate.build_executed && options.allowBuild === true) { + const root = payloadPath(this.#layout, duplicate) + await this.#build(duplicate, root) + let built: CapabilityVersion = { ...duplicate, build_executed: true } + if (existing.kind === 'tool' && !built.tool_registered) { + const command = await this.#registerTool(built, root) + built = { + ...built, + tool_registered: true, + manifest: commandOf(built) === null ? { ...built.manifest, tools: [command] } : built.manifest, + } + } + const versions = existing.versions.map(version => version.sha256 === built.sha256 ? built : version) + const updated: CapabilityRecord = { + ...existing, + versions, + active: existing.active ?? (buildSatisfied(built) ? built.sha256 : null), + } + const capabilities = index.capabilities.map(record => record.key === key ? updated : record) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + await this.#audit({ + at: new Date().toISOString(), action: 'build', key, source_id: existing.source_id, + version: built.version, sha256: built.sha256, scope: null, result: 'ok', + detail: 'build executed for an already unpacked version', + }) + return { + capability: this.#view(updated, await this.#market.current(), await this.#projectTexts()), + version: built, + already_installed: true, + activated: updated.active === built.sha256, + pending_activation: false, + requires_build: false, + } + } + return { + capability: this.#view(existing, await this.#market.current(), await this.#projectTexts()), + version: duplicate, + already_installed: true, + activated: activeOf(existing)?.sha256 === entry.asset.sha256, + pending_activation: false, + requires_build: duplicate.manifest.build?.required === true && !duplicate.build_executed, + } + } + const staging = join(this.#layout.capabilityStaging, `install-${Date.now()}-${randomBytes(4).toString('hex')}`) + await mkdir(staging, { recursive: true, mode: 0o700 }) + let installedTarget: string | null = null + let registered: CapabilityVersion | null = null + try { + const archive = join(staging, entry.asset.name) + const received = entry.asset.url === null + ? await this.#copyLocalAsset(entry, archive) + : await this.#downloadAsset(entry, archive) + if (received.sha256 !== entry.asset.sha256) { + throw new MarketError(MARKET_ERROR.digestMismatch, `downloaded digest does not match ${entry.asset.name}`) + } + const tree = join(staging, 'tree') + await mkdir(tree, { recursive: true, mode: 0o700 }) + await extractTarGz(await readFile(archive), tree) + const root = await locateRoot(tree) + const relativePath = `${safeSegment(entry.source_id)}-${entry.kind}-${safeSegment(entry.id)}/${safeSegment(entry.version)}-${entry.asset.sha256.slice(0, 12)}` + const target = join(this.#layout.capabilityStore, relativePath) + const buildRequired = entry.manifest.build?.required === true + let buildExecuted = false + if (buildRequired && options.allowBuild === true) { + const scratch: CapabilityVersion = { + version: entry.version, + sha256: entry.asset.sha256, + size: received.size, + asset_name: entry.asset.name, + source_sha: entry.source_sha, + installed_at: new Date().toISOString(), + path: relativePath, + manifest: entry.manifest, + signature: entry.signature, + build_executed: false, + tool_registered: false, + } + await this.#build(scratch, root) + buildExecuted = true + } + let version: CapabilityVersion = { + version: entry.version, + sha256: entry.asset.sha256, + size: received.size, + asset_name: entry.asset.name, + source_sha: entry.source_sha, + installed_at: new Date().toISOString(), + path: relativePath, + manifest: entry.manifest, + signature: entry.signature, + build_executed: buildExecuted, + tool_registered: false, + } + if (entry.kind === 'tool' && buildSatisfied(version)) { + try { + const command = await this.#registerTool(version, root) + version = { + ...version, + tool_registered: true, + manifest: commandOf(version) === null ? { ...version.manifest, tools: [command] } : version.manifest, + } + registered = version + } catch (error) { + if (error instanceof MarketError && error.code === MARKET_ERROR.runtimeNotInstalled) { + // Keep the verified payload; activation will require a Runtime. + } else { + throw error + } + } + } + await mkdir(dirname(target), { recursive: true, mode: 0o700 }) + if (await isDirectory(target)) await rm(target, { recursive: true, force: true }) + await rename(root, target) + installedTarget = target + const record: CapabilityRecord = { + key, + source_id: entry.source_id, + source_label: entry.source_label, + source_kind: entry.source_kind, + kind: entry.kind, + id: entry.id, + name: entry.name, + summary: entry.summary, + versions: [...(existing?.versions ?? []), version], + active: existing?.active ?? (buildSatisfied(version) ? version.sha256 : null), + enabled: existing?.enabled ?? [], + imports: existing?.imports ?? [], + } + const capabilities = index.capabilities.filter(item => item.key !== key) + capabilities.push(record) + capabilities.sort((left, right) => left.key.localeCompare(right.key, 'en')) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + await this.#audit({ + at: new Date().toISOString(), + action: buildExecuted ? 'build' : 'install', + key, + source_id: entry.source_id, + version: entry.version, + sha256: entry.asset.sha256, + scope: null, + result: 'ok', + detail: buildExecuted ? 'build executed during install' : null, + }) + return { + capability: this.#view(record, await this.#market.current(), await this.#projectTexts()), + version, + already_installed: false, + activated: record.active === version.sha256, + pending_activation: existing?.active !== null && existing?.active !== undefined && existing.active !== version.sha256, + requires_build: buildRequired && !buildExecuted, + } + } catch (error) { + if (installedTarget !== null) await rm(installedTarget, { recursive: true, force: true }) + if (registered !== null && registered.tool_registered) { + await this.#unregisterTool(commandOf(registered) ?? entry.id).catch(() => undefined) + } + await rm(staging, { recursive: true, force: true }) + await this.#audit({ + at: new Date().toISOString(), + action: 'install', + key, + source_id: entry.source_id, + version: entry.version, + sha256: entry.asset.sha256, + scope: null, + result: 'failed', + detail: error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300), + }) + throw error + } finally { + await rm(staging, { recursive: true, force: true }) + } + }) + } + + /** + * Activate one installed version, registering a Tool with the active Runtime. + * @param key - capability key. + * @param sha256 - optional version digest; defaults to the newest installed version. + * @returns the updated capability view. + */ + async activate(key: string, sha256?: string): Promise { + return await withLock(join(this.#layout.capabilities, 'operation.lock'), async () => { + const index = await this.index() + let record = index.capabilities.find(item => item.key === key) + if (record === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability is not installed: ${key}`) + const latest = record.versions[record.versions.length - 1] + let version = sha256 === undefined ? latest : record.versions.find(item => item.sha256 === sha256) + if (version === undefined) throw new MarketError(MARKET_ERROR.capabilityVersionUnknown, `unknown version for ${key}`) + if (!buildSatisfied(version)) throw new MarketError(MARKET_ERROR.buildRequired, 'the version requires an explicit build before activation') + if (record.kind === 'tool' && !version.tool_registered) { + const root = payloadPath(this.#layout, version) + const command = await this.#registerTool(version, root) + const registered: CapabilityVersion = { + ...version, + tool_registered: true, + manifest: commandOf(version) === null ? { ...version.manifest, tools: [command] } : version.manifest, + } + version = registered + const versions = record.versions.map(item => item.sha256 === registered.sha256 ? registered : item) + record = { ...record, versions } + } + const updated: CapabilityRecord = { ...record, active: version.sha256 } + const capabilities = index.capabilities.map(item => item.key === key ? updated : item) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + await this.#audit({ + at: new Date().toISOString(), action: 'activate', key, source_id: record.source_id, + version: version.version, sha256: version.sha256, scope: null, result: 'ok', detail: null, + }) + return this.#view(updated, await this.#market.current(), await this.#projectTexts()) + }) + } + + /** + * Remove a capability and every installed payload version. + * @param key - capability key. + * @param options - force skips the conservative project-reference block. + */ + async uninstall( + key: string, + options: { force?: boolean | undefined } = {}, + ): Promise<{ key: string; removed_versions: string[]; references: string[] }> { + return await withLock(join(this.#layout.capabilities, 'operation.lock'), async () => { + const index = await this.index() + const record = index.capabilities.find(item => item.key === key) + if (record === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability is not installed: ${key}`) + const texts = await this.#projectTexts() + const references = this.#references(record, texts) + if (references.length > 0 && options.force !== true) { + throw new MarketError(MARKET_ERROR.capabilityProjectReferenced, `capability is referenced by ${references.join(', ')}; remove the dependency and re-lock first`) + } + const active = activeOf(record) + if (record.kind === 'tool' && active !== null && active.tool_registered) { + await this.#unregisterTool(commandOf(active) ?? record.id) + } + for (const version of record.versions) { + await rm(payloadPath(this.#layout, version), { recursive: true, force: true }) + } + const capabilities = index.capabilities.filter(item => item.key !== key) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + await this.#audit({ + at: new Date().toISOString(), action: 'uninstall', key, source_id: record.source_id, + version: active?.version ?? null, sha256: active?.sha256 ?? null, scope: null, + result: 'ok', detail: references.length > 0 ? `forced despite ${references.join(', ')}` : null, + }) + return { key, removed_versions: record.versions.map(version => version.version), references } + }) + } + + /** + * Enable one capability for a global, session or project scope. + * @param key - capability key. + * @param request - requested scope; project defaults to the current workspace digest. + */ + async enable(key: string, request: ScopeRequest): Promise { + return await withLock(join(this.#layout.capabilities, 'operation.lock'), async () => { + const index = await this.index() + const record = index.capabilities.find(item => item.key === key) + if (record === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability is not installed: ${key}`) + const active = activeOf(record) + if (active === null) throw new MarketError(MARKET_ERROR.capabilityVersionUnknown, 'activate a version before enabling') + if (!buildSatisfied(active)) throw new MarketError(MARKET_ERROR.buildRequired, 'the active version requires an explicit build first') + if (record.kind === 'tool' && !active.tool_registered) { + throw new MarketError(MARKET_ERROR.runtimeNotInstalled, 'the active Runtime is required before enabling a Tool') + } + const id = request.kind === 'global' ? null : request.id?.trim() + if (request.kind === 'session' && (id === undefined || id === '')) { + throw new MarketError(MARKET_ERROR.configInvalid, 'session scope requires an id') + } + const resolvedId = request.kind === 'project' ? this.projectDigest() : id ?? null + const exists = record.enabled.some(scope => scope.kind === request.kind && scope.id === resolvedId) + if (exists) return this.#view(record, await this.#market.current(), await this.#projectTexts()) + const scope: CapabilityScope = { kind: request.kind, id: resolvedId, enabled_at: new Date().toISOString() } + const updated: CapabilityRecord = { ...record, enabled: [...record.enabled, scope] } + const capabilities = index.capabilities.map(item => item.key === key ? updated : item) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + await this.#audit({ + at: scope.enabled_at, action: 'enable', key, source_id: record.source_id, + version: active.version, sha256: active.sha256, + scope: resolvedId === null ? request.kind : `${request.kind}:${resolvedId}`, result: 'ok', detail: null, + }) + return this.#view(updated, await this.#market.current(), await this.#projectTexts()) + }) + } + + /** + * Remove one or all enable scopes; visibility changes immediately. + * @param key - capability key. + * @param request - scope to remove; omitted removes every scope. + */ + async disable(key: string, request?: ScopeRequest): Promise { + return await withLock(join(this.#layout.capabilities, 'operation.lock'), async () => { + const index = await this.index() + const record = index.capabilities.find(item => item.key === key) + if (record === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability is not installed: ${key}`) + const id = request === undefined || request.kind === 'global' ? null : request.kind === 'project' ? this.projectDigest() : request.id?.trim() ?? null + const remaining = request === undefined + ? [] + : record.enabled.filter(scope => !(scope.kind === request.kind && scope.id === id)) + const active = activeOf(record) + const updated: CapabilityRecord = { ...record, enabled: remaining } + const capabilities = index.capabilities.map(item => item.key === key ? updated : item) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + await this.#audit({ + at: new Date().toISOString(), action: 'disable', key, source_id: record.source_id, + version: active?.version ?? null, sha256: active?.sha256 ?? null, + scope: request === undefined ? 'all' : `${request.kind}:${id ?? ''}`, result: 'ok', detail: null, + }) + return this.#view(updated, await this.#market.current(), await this.#projectTexts()) + }) + } + + /** + * Import the active capability into the project through public CLI `add`. + * The application never writes `marqdo.yaml` or `marqdo.lock` itself. + * @param key - capability key. + * @param options - optional dependency alias. + */ + async importToProject(key: string, options: { alias?: string | undefined } = {}): Promise { + const index = await this.index() + const record = index.capabilities.find(item => item.key === key) + if (record === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability is not installed: ${key}`) + const active = activeOf(record) + if (active === null) throw new MarketError(MARKET_ERROR.capabilityVersionUnknown, 'activate a version before importing') + if (!buildSatisfied(active)) throw new MarketError(MARKET_ERROR.buildRequired, 'the version requires an explicit build first') + if (record.kind !== 'ext') { + throw new MarketError(MARKET_ERROR.importUnsupported, 'only an extension package can be imported as a project dependency') + } + const workspace = this.#workspace() + if ((await readText(join(workspace, 'marqdo.yaml'))) === undefined) { + throw new MarketError(MARKET_ERROR.projectManifestMissing, 'the workspace has no marqdo.yaml; initialize the project first') + } + const cli = await this.#cli() + if (!cli) throw new MarketError(MARKET_ERROR.runtimeNotInstalled, 'install a Runtime before importing a project dependency') + const alias = (options.alias ?? record.id).trim() + if (!/^[A-Za-z][A-Za-z0-9._-]{0,127}$/.test(alias)) { + throw new MarketError(MARKET_ERROR.configInvalid, `invalid dependency alias: ${alias}`) + } + const path = payloadPath(this.#layout, active) + const projectPath = `marqdo-vendor/${safeSegment(alias)}` + const destination = resolve(join(workspace, projectPath)) + if (!isWithin(workspace, destination)) { + throw new MarketError(MARKET_ERROR.configInvalid, `dependency destination escapes the workspace: ${projectPath}`) + } + if (await isDirectory(destination)) { + throw new MarketError(MARKET_ERROR.importConflict, `project already contains ${projectPath}; remove it before importing again`) + } + try { + await copyTree(path, destination, { maxFiles: 20_000 }) + const result = await runProcess(cli.bin, ['add', alias, '--path', `./${projectPath}`, '--json'], { + cwd: workspace, + limits: { timeoutMs: 60_000, maxOutputBytes: 512 * 1024 }, + }) + if (result.exitCode !== 0) { + throw new MarketError(MARKET_ERROR.cliFailed, `marqdo add failed: ${(result.stderr || result.stdout).slice(0, 600)}`) + } + let manifest: string | null = null + try { + const parsed: unknown = JSON.parse(result.stdout) + if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { + const recordValue = parsed as Record + manifest = typeof recordValue.manifest === 'string' ? recordValue.manifest : null + } + } catch (error) { + if (!(error instanceof SyntaxError)) throw error + } + await this.#recordImport(record, { + workspace, alias, path, project_path: projectPath, at: new Date().toISOString(), + }) + await this.#audit({ + at: new Date().toISOString(), action: 'project-import', key, source_id: record.source_id, + version: active.version, sha256: active.sha256, scope: alias, result: 'ok', detail: projectPath, + }) + return { alias, path: projectPath, store_path: path, manifest, next: 'marqdo lock' } + } catch (error) { + await rm(destination, { recursive: true, force: true }) + throw error + } + } + + /** Persist one recorded project import and return its path. */ + async #recordImport(record: CapabilityRecord, item: CapabilityImport): Promise { + const index = await this.index() + const current = index.capabilities.find(candidate => candidate.key === record.key) + if (current === undefined) throw new MarketError(MARKET_ERROR.capabilityNotInstalled, `capability disappeared: ${record.key}`) + const updated: CapabilityRecord = { ...current, imports: [...current.imports, item] } + const capabilities = index.capabilities.map(candidate => candidate.key === record.key ? updated : candidate) + await this.#write({ schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities }) + return item.path + } + + /** + * Generate the project lock through the public CLI `lock` command. + * @returns the CLI's parsed JSON result and captured stderr. + */ + async lockProject(): Promise<{ success: boolean; result: unknown; stdout: string; stderr: string }> { + const workspace = this.#workspace() + const cli = await this.#cli() + if (!cli) throw new MarketError(MARKET_ERROR.runtimeNotInstalled, 'install a Runtime before locking a project') + const result = await runProcess(cli.bin, ['lock', '--json'], { + cwd: workspace, + limits: { timeoutMs: 120_000, maxOutputBytes: 1024 * 1024 }, + }) + let parsed: unknown = null + try { + parsed = result.stdout.trim() === '' ? null : JSON.parse(result.stdout) + } catch { + parsed = null + } + await this.#audit({ + at: new Date().toISOString(), action: 'project-lock', key: '', source_id: '', + version: null, sha256: null, scope: workspace, result: result.exitCode === 0 ? 'ok' : 'failed', + detail: result.stderr.slice(0, 300) || null, + }) + if (result.exitCode !== 0) { + throw new MarketError(MARKET_ERROR.cliFailed, `marqdo lock failed: ${(result.stderr || result.stdout).slice(0, 600)}`) + } + return { success: true, result: parsed, stdout: result.stdout, stderr: result.stderr } + } + + /** Market entry matching one installed capability key. */ + async marketEntry(key: string): Promise { + return await this.#market.entry(key) + } + + /** Every configured source id referenced by an installed capability. */ + async installedSourceIds(): Promise { + return [...new Set((await this.index()).capabilities.map(record => record.source_id))] + } + + /** Stable manifest for one capability version, used by tests and diagnostics. */ + static manifestOf(version: CapabilityVersion): MarketManifest { + return version.manifest + } +} + +/** Key helper re-exported for callers that build capability keys. */ +export { entryKey } diff --git a/packages/marqdo/harness/src/market/config.ts b/packages/marqdo/harness/src/market/config.ts new file mode 100644 index 0000000000..006c6a0e1b --- /dev/null +++ b/packages/marqdo/harness/src/market/config.ts @@ -0,0 +1,236 @@ +/** + * User market source configuration. + * + * `MQDH_HOME/config/market.json` is user-owned (0600). It is the only place a + * market source is declared; the product source tree contains no owner, + * repository or entry list. Every refresh re-reads this file, so adding or + * removing a source does not require restarting MQDH. + * + * @module @marqdo/mqdh-harness/market/config + */ + +import { isAbsolute, resolve } from 'node:path' +import { readJson, writeJsonAtomic } from '../core/fsx.ts' +import { AUTHORITY_OWNER } from '../release/gitea.ts' +import { + optionalBoolean, optionalInteger, optionalString, recordOf, rejectUnknownKeys, + requiredString, stringList, +} from './contract.ts' +import { MARKET_ERROR, MarketError } from './errors.ts' + +/** Configuration schema identifier. */ +export const MARKET_CONFIG_SCHEMA = 'marqdo.mqdh.market' + +/** Default cache lifetime for an explicit listing read. */ +export const DEFAULT_MARKET_CACHE_TTL_MS = 300_000 + +/** Repository topics that make an official repository discoverable. */ +export const DEFAULT_MARKET_TOPICS = ['marqdo-ext', 'marqdo-tool'] as const + +/** One configured source. */ +export interface MarketSourceConfig { + readonly id: string + readonly kind: 'gitea' | 'directory' + readonly label: string + /** Gitea base authority; ignored by a directory source. */ + readonly base: string | null + /** Repository owners admitted for a Gitea source. */ + readonly owners: readonly string[] + /** Repository topics used to discover repositories. */ + readonly topics: readonly string[] + /** Explicit `owner/repo` entries; discovery still reads their releases. */ + readonly repositories: readonly string[] + /** Absolute directory containing `index.json` and assets. */ + readonly path: string | null + /** Kind used for explicit repositories without a market topic. */ + readonly default_kind: 'ext' | 'tool' | null +} + +/** Validated market configuration. */ +export interface MarketConfig { + readonly schema: typeof MARKET_CONFIG_SCHEMA + readonly schema_version: 1 + readonly sources: readonly MarketSourceConfig[] + readonly cache_ttl_ms: number + readonly offline: boolean +} + +/** Source id syntax also used in capability directory names. */ +const SOURCE_ID = /^[a-z][a-z0-9-]{0,31}$/ + +/** Validate one source id. */ +function sourceId(value: unknown, label: string): string { + if (typeof value !== 'string' || !SOURCE_ID.test(value)) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.id must match ${SOURCE_ID}`) + } + return value +} + +/** Normalize a Gitea base authority without a trailing path. */ +function normalizeBase(value: string, label: string): string { + let url: URL + try { + url = new URL(value) + } catch { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.base is not a URL`) + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.base must be http(s)`) + } + if (url.username !== '' || url.password !== '') { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.base must not contain credentials`) + } + if (url.pathname !== '/' || url.search !== '' || url.hash !== '') { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.base must be an authority without a path`) + } + return url.toString().replace(/\/$/, '') +} + +/** + * Parse and validate one source object from a market configuration or a Web request. + * @param value - raw source object. + * @param label - diagnostic path for validation errors. + * @returns the validated source. + */ +export function parseSourceConfig(value: unknown, label = 'market source'): MarketSourceConfig { + return parseSource(value, label) +} + +/** Parse one source object. */ +function parseSource(value: unknown, index: number | string): MarketSourceConfig { + const label = typeof index === 'string' ? index : `market.sources[${index}]` + const record = recordOf(value) + if (record === undefined) throw new MarketError(MARKET_ERROR.configInvalid, `${label} must be an object`) + rejectUnknownKeys(record, [ + 'id', 'kind', 'label', 'base', 'owners', 'topics', 'repositories', 'path', 'default_kind', 'enabled', + ], label) + const enabled = optionalBoolean(record, 'enabled', label) + if (enabled === false) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.enabled=false must be removed, not configured`) + } + const id = sourceId(record.id, label) + const kind = requiredString(record, 'kind', label) + if (kind !== 'gitea' && kind !== 'directory') { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.kind must be gitea or directory`) + } + const display = optionalString(record, 'label', label)?.trim() || id + const owners = stringList(record, 'owners', label) + const topics = stringList(record, 'topics', label) + const repositories = stringList(record, 'repositories', label) + for (const repository of repositories) { + if (!/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(repository)) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.repositories entry is not owner/repo: ${repository}`) + } + } + const defaultKind = optionalString(record, 'default_kind', label) + if (defaultKind !== null && defaultKind !== 'ext' && defaultKind !== 'tool') { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.default_kind must be ext or tool`) + } + if (kind === 'gitea') { + const base = normalizeBase(optionalString(record, 'base', label) ?? 'https://git.cflmy.cn', label) + if (owners.length === 0 && topics.length === 0 && repositories.length === 0) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label} needs owners, topics or repositories`) + } + if (record.path !== undefined && record.path !== null) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.path is only valid for a directory source`) + } + return { id, kind, label: display, base, owners, topics, repositories, path: null, default_kind: defaultKind } + } + const directory = optionalString(record, 'path', label) + if (directory === null || !isAbsolute(directory)) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.path must be an absolute directory`) + } + if (owners.length > 0 || topics.length > 0 || repositories.length > 0) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label} is a directory source and cannot name repositories`) + } + return { + id, kind, label: display, base: null, owners: [], topics: [], repositories: [], + path: resolve(directory), default_kind: defaultKind, + } +} + +/** Build the default source list for the configured release authority. */ +export function defaultMarketSources(releaseAuthority: string): MarketSourceConfig[] { + return [{ + id: 'official', + kind: 'gitea', + label: 'Marqdo 官方', + base: normalizeBase(releaseAuthority, 'official'), + owners: [AUTHORITY_OWNER], + topics: [...DEFAULT_MARKET_TOPICS], + repositories: [], + path: null, + default_kind: null, + }] +} + +/** Default configuration used when no user file exists. */ +export function defaultMarketConfig(releaseAuthority: string): MarketConfig { + return { + schema: MARKET_CONFIG_SCHEMA, + schema_version: 1, + sources: defaultMarketSources(releaseAuthority), + cache_ttl_ms: DEFAULT_MARKET_CACHE_TTL_MS, + offline: false, + } +} + +/** Parse one market configuration file. */ +export function parseMarketConfig(value: unknown): MarketConfig { + const record = recordOf(value) + if (record === undefined) throw new MarketError(MARKET_ERROR.configInvalid, 'market configuration must be an object') + rejectUnknownKeys(record, ['schema', 'schema_version', 'sources', 'cache_ttl_ms', 'offline'], 'market configuration') + if (record.schema !== MARKET_CONFIG_SCHEMA || record.schema_version !== 1) { + throw new MarketError(MARKET_ERROR.configInvalid, 'unsupported market configuration schema') + } + const rawSources = record.sources + if (!Array.isArray(rawSources)) throw new MarketError(MARKET_ERROR.configInvalid, 'market.sources must be an array') + const sources = rawSources.map((source, index) => parseSource(source, index)) + const seen = new Set() + for (const source of sources) { + if (seen.has(source.id)) throw new MarketError(MARKET_ERROR.sourceDuplicate, `duplicate market source id: ${source.id}`) + seen.add(source.id) + } + const ttl = optionalInteger(record, 'cache_ttl_ms', 'market configuration', 0) ?? DEFAULT_MARKET_CACHE_TTL_MS + const offline = optionalBoolean(record, 'offline', 'market configuration') === true + if (sources.length === 0) { + return { schema: MARKET_CONFIG_SCHEMA, schema_version: 1, sources, cache_ttl_ms: ttl, offline } + } + return { schema: MARKET_CONFIG_SCHEMA, schema_version: 1, sources, cache_ttl_ms: ttl, offline } +} + +/** Read the effective market configuration, falling back to the official source. */ +export async function readMarketConfig(path: string, releaseAuthority: string): Promise { + const raw = await readJson>(path) + if (raw === undefined) return defaultMarketConfig(releaseAuthority) + return parseMarketConfig(raw) +} + +/** Serialize a configuration for the private file. */ +export function serializeMarketConfig(config: MarketConfig): Record { + return { + schema: config.schema, + schema_version: 1, + sources: config.sources.map(source => ({ + id: source.id, + kind: source.kind, + label: source.label, + ...(source.kind === 'gitea' + ? { + base: source.base, + owners: [...source.owners], + topics: [...source.topics], + repositories: [...source.repositories], + ...(source.default_kind === null ? {} : { default_kind: source.default_kind }), + } + : { path: source.path }), + })), + cache_ttl_ms: config.cache_ttl_ms, + offline: config.offline, + } +} + +/** Write the configuration atomically with owner-only permissions. */ +export async function writeMarketConfig(path: string, config: MarketConfig): Promise { + await writeJsonAtomic(path, serializeMarketConfig(config), 0o600) +} diff --git a/packages/marqdo/harness/src/market/contract.ts b/packages/marqdo/harness/src/market/contract.ts new file mode 100644 index 0000000000..0f2ed1dde9 --- /dev/null +++ b/packages/marqdo/harness/src/market/contract.ts @@ -0,0 +1,571 @@ +/** + * Market and capability data contracts. + * + * The market index is a rebuildable projection of user-configured sources. The + * capability store is authoritative user state: installed versions, the active + * version and the scopes where a capability is visible. Neither duplicates the + * project lock, the extension manifest parser or the CLI Tool registry. + * + * @module @marqdo/mqdh-harness/market/contract + */ + +import { MarketError } from './errors.ts' + +/** Kinds that can appear in the market. Std and private knowledge never do. */ +export const MARKET_KINDS = ['ext', 'tool'] as const + +/** One market-installable kind. */ +export type MarketKind = (typeof MARKET_KINDS)[number] + +/** Index entry availability. */ +export type MarketAvailability = 'available' | 'unavailable' | 'stale' + +/** How an entry changed relative to the previous projection. */ +export type MarketChange = 'new' | 'changed' | 'unchanged' | 'stale' + +/** Display-only signature state; no central trust decision is made here. */ +export interface MarketSignature { + readonly status: 'unsigned' | 'present' + readonly algorithm: string | null + readonly key_id: string | null + readonly value: string | null +} + +/** One install asset. Exactly one of `url` and `relative` is set. */ +export interface MarketAsset { + readonly name: string + readonly size: number | null + readonly sha256: string + /** Remote asset URL (Gitea source). */ + readonly url: string | null + /** Path relative to a directory source root. */ + readonly relative: string | null +} + +/** One declared dependency edge in a market entry. */ +export interface MarketDependency { + readonly id: string + readonly version: string | null +} + +/** Declared build/install instructions. Executed only with explicit consent. */ +export interface MarketBuild { + readonly required: boolean + readonly command: readonly string[] + readonly instructions: string | null +} + +/** Display manifest published by the entry or derived from its release. */ +export interface MarketManifest { + readonly mechanisms: readonly string[] + readonly tools: readonly string[] + readonly skills: readonly string[] + readonly capabilities: readonly string[] + readonly permissions: readonly string[] + readonly effects: readonly string[] + readonly dependencies: readonly MarketDependency[] + readonly min_cli: string | null + readonly min_protocol: string | null + readonly build: MarketBuild | null +} + +/** One projected market entry. */ +export interface MarketEntry { + /** `${source_id}:${kind}:${id}`; versions are selected at install time. */ + readonly key: string + readonly source_id: string + readonly source_label: string + readonly source_kind: 'gitea' | 'directory' + readonly kind: MarketKind + readonly id: string + readonly name: string + readonly summary: string + readonly description: string + readonly version: string + readonly channel: 'stable' | 'prerelease' + readonly platform: string | null + readonly asset: MarketAsset + readonly manifest: MarketManifest + readonly source_sha: string | null + readonly published_at: string | null + readonly publisher: string | null + readonly signature: MarketSignature + readonly known_limitations: readonly string[] + readonly risk: string | null + readonly browser_url: string | null + readonly availability: MarketAvailability + readonly unavailable_reason: string | null + readonly change: MarketChange + readonly first_seen_at: string + readonly last_seen_at: string +} + +/** Per-source refresh state, retained across failures. */ +export interface MarketSourceState { + readonly id: string + readonly status: 'never' | 'ok' | 'stale' | 'offline' + readonly checked_at: string + readonly error: string | null + readonly warnings: readonly string[] + readonly entries: number +} + +/** Rebuildable market index. */ +export interface MarketIndex { + readonly schema: 'marqdo.mqdh.market.index' + readonly schema_version: 1 + readonly generated_at: string + /** Digest of the source configuration the projection was built from. */ + readonly config_digest: string + readonly sources: readonly MarketSourceState[] + readonly entries: readonly MarketEntry[] +} + +/** Scope where an installed capability is visible. */ +export interface CapabilityScope { + readonly kind: 'global' | 'session' | 'project' + /** Session id or workspace digest; `null` for global. */ + readonly id: string | null + readonly enabled_at: string +} + +/** One installed payload version. */ +export interface CapabilityVersion { + readonly version: string + readonly sha256: string + readonly size: number + readonly asset_name: string + readonly source_sha: string | null + readonly installed_at: string + /** Payload path relative to the capability store root. */ + readonly path: string + readonly manifest: MarketManifest + readonly signature: MarketSignature + /** Whether a declared build step was explicitly executed during install. */ + readonly build_executed: boolean + /** Whether the active Runtime has a Tool install record for this payload. */ + readonly tool_registered: boolean +} + +/** One `marqdo.yaml` import recorded by the application. */ +export interface CapabilityImport { + readonly workspace: string + readonly alias: string + /** Absolute installed payload path recorded at import time. */ + readonly path: string + /** Project-relative copy written for the CLI manifest, or `null` for legacy records. */ + readonly project_path: string | null + readonly at: string +} + +/** Authoritative installed capability record. */ +export interface CapabilityRecord { + readonly key: string + readonly source_id: string + readonly source_label: string + readonly source_kind: 'gitea' | 'directory' + readonly kind: MarketKind + readonly id: string + readonly name: string + readonly summary: string + readonly versions: readonly CapabilityVersion[] + /** SHA-256 of the active version, or `null` before the first activation. */ + readonly active: string | null + readonly enabled: readonly CapabilityScope[] + readonly imports: readonly CapabilityImport[] +} + +/** Authoritative capability store index. */ +export interface CapabilityIndex { + readonly schema: 'marqdo.mqdh.capabilities' + readonly schema_version: 1 + readonly capabilities: readonly CapabilityRecord[] +} + +/** One audit record; never contains private content. */ +export interface CapabilityAudit { + readonly at: string + readonly action: + | 'install' + | 'activate' + | 'enable' + | 'disable' + | 'uninstall' + | 'project-import' + | 'project-lock' + | 'build' + readonly key: string + readonly source_id: string + readonly version: string | null + readonly sha256: string | null + readonly scope: string | null + readonly result: 'ok' | 'failed' + readonly detail: string | null +} + +/** Read a plain object, or `undefined` when the value is not an object. */ +export function recordOf(value: unknown): Record | undefined { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined + return value as Record +} + +/** Read a required non-empty string. */ +export function requiredString(record: Record, key: string, label: string): string { + const value = record[key] + if (typeof value !== 'string' || value.trim() === '') { + throw new MarketError('market.config_invalid', `${label}.${key} must be a non-empty string`) + } + return value +} + +/** Read an optional string, treating `null` as absent. */ +export function optionalString(record: Record, key: string, label: string): string | null { + const value = record[key] + if (value === undefined || value === null) return null + if (typeof value !== 'string') throw new MarketError('market.config_invalid', `${label}.${key} must be a string`) + return value +} + +/** Read an optional boolean. */ +export function optionalBoolean(record: Record, key: string, label: string): boolean | null { + const value = record[key] + if (value === undefined || value === null) return null + if (typeof value !== 'boolean') throw new MarketError('market.config_invalid', `${label}.${key} must be a boolean`) + return value +} + +/** Read an optional integer. */ +export function optionalInteger(record: Record, key: string, label: string, min = 0): number | null { + const value = record[key] + if (value === undefined || value === null) return null + if (typeof value !== 'number' || !Number.isInteger(value) || value < min) { + throw new MarketError('market.config_invalid', `${label}.${key} must be an integer >= ${min}`) + } + return value +} + +/** Read an optional string array, rejecting non-string members. */ +export function stringList(record: Record, key: string, label: string): string[] { + const value = record[key] + if (value === undefined || value === null) return [] + if (!Array.isArray(value) || !value.every(item => typeof item === 'string')) { + throw new MarketError('market.config_invalid', `${label}.${key} must be a string array`) + } + return value +} + +/** Reject unknown keys so a typo cannot silently change meaning. */ +export function rejectUnknownKeys(record: Record, allowed: readonly string[], label: string): void { + for (const key of Object.keys(record)) { + if (!allowed.includes(key)) { + throw new MarketError('market.config_invalid', `unknown ${label} key: ${key}`) + } + } +} + +/** Stable entry key. Source identity keeps same-id entries from different sources apart. */ +export function entryKey(sourceId: string, kind: MarketKind, id: string): string { + return `${sourceId}:${kind}:${id}` +} + +/** Convert arbitrary text to a safe single path segment. */ +export function safeSegment(value: string): string { + const normalized = value.toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '') + if (normalized === '' || normalized === '.' || normalized === '..') { + throw new MarketError('market.install_failed', `value is not a safe path segment: ${value}`) + } + return normalized +} + +/** Compare semver-ish versions, newest first semantics through a sign. */ +export function compareVersions(left: string, right: string): number { + const split = (value: string): { main: number[]; pre: string[] } => { + const [mainPart = '', prePart] = value.replace(/^v/, '').split('-', 2) + const main = mainPart.split('.').map(part => Number.parseInt(part, 10)).filter(Number.isFinite) + return { main, pre: prePart === undefined ? [] : prePart.split('.') } + } + const a = split(left) + const b = split(right) + for (let index = 0; index < Math.max(a.main.length, b.main.length); index++) { + const diff = (b.main[index] ?? 0) - (a.main[index] ?? 0) + if (diff !== 0) return diff + } + if (a.pre.length === 0 && b.pre.length === 0) return left.localeCompare(right, 'en') + if (a.pre.length === 0) return -1 + if (b.pre.length === 0) return 1 + return b.pre.join('.').localeCompare(a.pre.join('.'), 'en', { numeric: true }) +} + +/** Empty display manifest used when a release publishes no market metadata. */ +export function emptyManifest(): MarketManifest { + return { + mechanisms: [], + tools: [], + skills: [], + capabilities: [], + permissions: [], + effects: [], + dependencies: [], + min_cli: null, + min_protocol: null, + build: null, + } +} + +/** Parse one manifest object with strict field types. */ +export function parseManifest(value: unknown, label: string): MarketManifest { + if (value === undefined || value === null) return emptyManifest() + const record = recordOf(value) + if (record === undefined) throw new MarketError('market.config_invalid', `${label} must be an object`) + rejectUnknownKeys(record, [ + 'mechanisms', 'tools', 'skills', 'capabilities', 'permissions', 'effects', + 'dependencies', 'min_cli', 'min_protocol', 'build', + ], label) + const dependencies: MarketDependency[] = [] + const rawDependencies = record.dependencies + if (rawDependencies !== undefined && rawDependencies !== null) { + if (!Array.isArray(rawDependencies)) throw new MarketError('market.config_invalid', `${label}.dependencies must be an array`) + for (const item of rawDependencies) { + const dep = recordOf(item) + if (dep === undefined) throw new MarketError('market.config_invalid', `${label}.dependencies entries must be objects`) + dependencies.push({ + id: requiredString(dep, 'id', `${label}.dependencies`), + version: optionalString(dep, 'version', `${label}.dependencies`), + }) + } + } + let build: MarketBuild | null = null + const rawBuild = record.build + if (rawBuild !== undefined && rawBuild !== null) { + const buildRecord = recordOf(rawBuild) + if (buildRecord === undefined) throw new MarketError('market.config_invalid', `${label}.build must be an object`) + rejectUnknownKeys(buildRecord, ['required', 'command', 'instructions'], `${label}.build`) + build = { + required: optionalBoolean(buildRecord, 'required', `${label}.build`) === true, + command: stringList(buildRecord, 'command', `${label}.build`), + instructions: optionalString(buildRecord, 'instructions', `${label}.build`), + } + } + return { + mechanisms: stringList(record, 'mechanisms', label), + tools: stringList(record, 'tools', label), + skills: stringList(record, 'skills', label), + capabilities: stringList(record, 'capabilities', label), + permissions: stringList(record, 'permissions', label), + effects: stringList(record, 'effects', label), + dependencies, + min_cli: optionalString(record, 'min_cli', label), + min_protocol: optionalString(record, 'min_protocol', label), + build, + } +} + +/** Parse one signature object; absence means explicitly unsigned. */ +export function parseSignature(value: unknown, label: string): MarketSignature { + if (value === undefined || value === null) { + return { status: 'unsigned', algorithm: null, key_id: null, value: null } + } + const record = recordOf(value) + if (record === undefined) throw new MarketError('market.config_invalid', `${label} must be an object`) + rejectUnknownKeys(record, ['status', 'algorithm', 'key_id', 'value'], label) + const algorithm = optionalString(record, 'algorithm', label) + const keyId = optionalString(record, 'key_id', label) + const signature = optionalString(record, 'value', label) + if (algorithm === null && keyId === null && signature === null) { + return { status: 'unsigned', algorithm: null, key_id: null, value: null } + } + if (algorithm === null || keyId === null || signature === null) { + throw new MarketError('market.config_invalid', `${label} needs algorithm, key_id and value`) + } + return { status: 'present', algorithm, key_id: keyId, value: signature } +} + +/** Validate a digest string, normalizing to lowercase bare hex. */ +export function digestHex(value: string, label: string): string { + const match = /^(?:sha256:)?([0-9a-fA-F]{64})$/.exec(value.trim()) + if (match?.[1] === undefined) throw new MarketError('market.config_invalid', `${label} must be a SHA-256 digest`) + return match[1].toLowerCase() +} + +/** Parse and validate a full market index file. */ +export function parseMarketIndex(value: unknown): MarketIndex { + const record = recordOf(value) + if (record === undefined || record.schema !== 'marqdo.mqdh.market.index' || record.schema_version !== 1) { + throw new MarketError('market.config_invalid', 'market index has an unsupported schema') + } + const generatedAt = requiredString(record, 'generated_at', 'market index') + const rawSources = record.sources + const rawEntries = record.entries + if (!Array.isArray(rawSources) || !Array.isArray(rawEntries)) { + throw new MarketError('market.config_invalid', 'market index needs sources and entries arrays') + } + const sources: MarketSourceState[] = [] + for (const item of rawSources) { + const source = recordOf(item) + if (source === undefined) throw new MarketError('market.config_invalid', 'market source state must be an object') + const status = requiredString(source, 'status', 'market source state') + if (status !== 'never' && status !== 'ok' && status !== 'stale' && status !== 'offline') { + throw new MarketError('market.config_invalid', `unknown market source status: ${status}`) + } + sources.push({ + id: requiredString(source, 'id', 'market source state'), + status, + checked_at: requiredString(source, 'checked_at', 'market source state'), + error: optionalString(source, 'error', 'market source state'), + warnings: stringList(source, 'warnings', 'market source state'), + entries: optionalInteger(source, 'entries', 'market source state') ?? 0, + }) + } + const entries: MarketEntry[] = [] + for (const item of rawEntries) { + const entry = recordOf(item) + if (entry === undefined) throw new MarketError('market.config_invalid', 'market entry must be an object') + const kind = requiredString(entry, 'kind', 'market entry') + if (kind !== 'ext' && kind !== 'tool') throw new MarketError('market.config_invalid', `unknown market entry kind: ${kind}`) + const asset = recordOf(entry.asset) + if (asset === undefined) throw new MarketError('market.config_invalid', 'market entry has no asset') + entries.push({ + key: requiredString(entry, 'key', 'market entry'), + source_id: requiredString(entry, 'source_id', 'market entry'), + source_label: requiredString(entry, 'source_label', 'market entry'), + source_kind: requiredString(entry, 'source_kind', 'market entry') === 'directory' ? 'directory' : 'gitea', + kind, + id: requiredString(entry, 'id', 'market entry'), + name: requiredString(entry, 'name', 'market entry'), + summary: optionalString(entry, 'summary', 'market entry') ?? '', + description: optionalString(entry, 'description', 'market entry') ?? '', + version: requiredString(entry, 'version', 'market entry'), + channel: optionalString(entry, 'channel', 'market entry') === 'prerelease' ? 'prerelease' : 'stable', + platform: optionalString(entry, 'platform', 'market entry'), + asset: { + name: requiredString(asset, 'name', 'market asset'), + size: optionalInteger(asset, 'size', 'market asset'), + sha256: digestHex(requiredString(asset, 'sha256', 'market asset'), 'market asset.sha256'), + url: optionalString(asset, 'url', 'market asset'), + relative: optionalString(asset, 'relative', 'market asset'), + }, + manifest: parseManifest(entry.manifest, 'market entry manifest'), + source_sha: optionalString(entry, 'source_sha', 'market entry'), + published_at: optionalString(entry, 'published_at', 'market entry'), + publisher: optionalString(entry, 'publisher', 'market entry'), + signature: parseSignature(entry.signature, 'market entry signature'), + known_limitations: stringList(entry, 'known_limitations', 'market entry'), + risk: optionalString(entry, 'risk', 'market entry'), + browser_url: optionalString(entry, 'browser_url', 'market entry'), + availability: (() => { + const availability = optionalString(entry, 'availability', 'market entry') + return availability === 'unavailable' ? 'unavailable' : availability === 'stale' ? 'stale' : 'available' + })(), + unavailable_reason: optionalString(entry, 'unavailable_reason', 'market entry'), + change: (() => { + const change = optionalString(entry, 'change', 'market entry') + return change === 'new' ? 'new' : change === 'changed' ? 'changed' : change === 'stale' ? 'stale' : 'unchanged' + })(), + first_seen_at: requiredString(entry, 'first_seen_at', 'market entry'), + last_seen_at: requiredString(entry, 'last_seen_at', 'market entry'), + }) + } + return { + schema: 'marqdo.mqdh.market.index', + schema_version: 1, + generated_at: generatedAt, + config_digest: requiredString(record, 'config_digest', 'market index'), + sources, + entries, + } +} + +/** Parse the authoritative capability index, failing loud on corruption. */ +export function parseCapabilityIndex(value: unknown): CapabilityIndex { + const record = recordOf(value) + if (record === undefined || record.schema !== 'marqdo.mqdh.capabilities' || record.schema_version !== 1) { + throw new MarketError('market.config_invalid', 'capability index has an unsupported schema') + } + const raw = record.capabilities + if (!Array.isArray(raw)) throw new MarketError('market.config_invalid', 'capability index needs a capabilities array') + const capabilities: CapabilityRecord[] = [] + for (const item of raw) { + const capability = recordOf(item) + if (capability === undefined) throw new MarketError('market.config_invalid', 'capability record must be an object') + const rawVersions = capability.versions + if (!Array.isArray(rawVersions)) throw new MarketError('market.config_invalid', 'capability versions must be an array') + const versions: CapabilityVersion[] = rawVersions.map((version) => { + const entry = recordOf(version) + if (entry === undefined) throw new MarketError('market.config_invalid', 'capability version must be an object') + return { + version: requiredString(entry, 'version', 'capability version'), + sha256: digestHex(requiredString(entry, 'sha256', 'capability version'), 'capability version.sha256'), + size: optionalInteger(entry, 'size', 'capability version') ?? 0, + asset_name: requiredString(entry, 'asset_name', 'capability version'), + source_sha: optionalString(entry, 'source_sha', 'capability version'), + installed_at: requiredString(entry, 'installed_at', 'capability version'), + path: requiredString(entry, 'path', 'capability version'), + manifest: parseManifest(entry.manifest, 'capability manifest'), + signature: parseSignature(entry.signature, 'capability signature'), + build_executed: optionalBoolean(entry, 'build_executed', 'capability version') === true, + tool_registered: optionalBoolean(entry, 'tool_registered', 'capability version') === true, + } + }) + const rawScopes = capability.enabled + if (rawScopes !== undefined && !Array.isArray(rawScopes)) { + throw new MarketError('market.config_invalid', 'capability enabled must be an array') + } + const enabled: CapabilityScope[] = (rawScopes ?? []).map((scopeValue) => { + const scope = recordOf(scopeValue) + if (scope === undefined) throw new MarketError('market.config_invalid', 'capability scope must be an object') + const kind = requiredString(scope, 'kind', 'capability scope') + if (kind !== 'global' && kind !== 'session' && kind !== 'project') { + throw new MarketError('market.config_invalid', `unknown capability scope: ${kind}`) + } + return { + kind, + id: optionalString(scope, 'id', 'capability scope'), + enabled_at: requiredString(scope, 'enabled_at', 'capability scope'), + } + }) + const rawImports = capability.imports + if (rawImports !== undefined && !Array.isArray(rawImports)) { + throw new MarketError('market.config_invalid', 'capability imports must be an array') + } + const imports: CapabilityImport[] = (rawImports ?? []).map((importValue) => { + const item = recordOf(importValue) + if (item === undefined) throw new MarketError('market.config_invalid', 'capability import must be an object') + return { + workspace: requiredString(item, 'workspace', 'capability import'), + alias: requiredString(item, 'alias', 'capability import'), + path: requiredString(item, 'path', 'capability import'), + project_path: optionalString(item, 'project_path', 'capability import'), + at: requiredString(item, 'at', 'capability import'), + } + }) + const kind = requiredString(capability, 'kind', 'capability record') + if (kind !== 'ext' && kind !== 'tool') throw new MarketError('market.config_invalid', `unknown capability kind: ${kind}`) + capabilities.push({ + key: requiredString(capability, 'key', 'capability record'), + source_id: requiredString(capability, 'source_id', 'capability record'), + source_label: requiredString(capability, 'source_label', 'capability record'), + source_kind: requiredString(capability, 'source_kind', 'capability record') === 'directory' ? 'directory' : 'gitea', + kind, + id: requiredString(capability, 'id', 'capability record'), + name: requiredString(capability, 'name', 'capability record'), + summary: optionalString(capability, 'summary', 'capability record') ?? '', + versions, + active: optionalString(capability, 'active', 'capability record'), + enabled, + imports, + }) + } + return { schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities } +} + +/** Empty capability index. */ +export function emptyCapabilityIndex(): CapabilityIndex { + return { schema: 'marqdo.mqdh.capabilities', schema_version: 1, capabilities: [] } +} + +/** Whether one scope grants visibility for the supplied session/project identity. */ +export function scopeMatches(scope: CapabilityScope, sessionId: string | null, projectDigest: string | null): boolean { + if (scope.kind === 'global') return true + if (scope.kind === 'session') return sessionId !== null && scope.id === sessionId + return projectDigest !== null && scope.id === projectDigest +} diff --git a/packages/marqdo/harness/src/market/discovery.ts b/packages/marqdo/harness/src/market/discovery.ts new file mode 100644 index 0000000000..d1e594aeda --- /dev/null +++ b/packages/marqdo/harness/src/market/discovery.ts @@ -0,0 +1,606 @@ +/** + * Dynamic discovery for the market's two source kinds. + * + * A Gitea source is discovered from repository topics, explicit repositories or + * repository owners; nothing about a publisher or entry is compiled into the + * application. A directory source reads a local `index.json` and its assets, so + * offline and air-gapped markets use the same entry identity as online ones. + * + * Discovery only reads metadata. Installing is a separate, explicit action. + * + * @module @marqdo/mqdh-harness/market/discovery + */ + +import { lstat, realpath, stat } from 'node:fs/promises' +import { isAbsolute, join, relative, resolve } from 'node:path' +import type { EgressClient } from '../network/client.ts' +import { NetworkError } from '../network/client.ts' +import { digestFile, readJson, realpathWithin } from '../core/fsx.ts' +import { targetTriple } from '../platform/detect.ts' +import type { MarketSourceConfig } from './config.ts' +import { + compareVersions, digestHex, entryKey, emptyManifest, optionalString, parseManifest, + parseSignature, recordOf, requiredString, stringList, +} from './contract.ts' +import type { MarketAsset, MarketEntry, MarketKind, MarketManifest, MarketSignature } from './contract.ts' +import { MARKET_ERROR, MarketError } from './errors.ts' + +/** One discovery result for a single source. */ +export interface SourceDiscovery { + readonly entries: readonly MarketEntry[] + readonly warnings: readonly string[] +} + +/** Per-call discovery options. */ +export interface DiscoveryOptions { + readonly platform?: string | undefined + readonly offline: boolean + readonly now: () => Date +} + +/** Minimal Gitea repository fields used by discovery. */ +interface GiteaRepository { + readonly full_name: string + readonly name: string + readonly owner: string + readonly topics: readonly string[] + readonly archived: boolean + readonly empty: boolean + readonly description: string +} + +/** One Gitea release asset. */ +interface GiteaAsset { + readonly name: string + readonly size: number | null + readonly url: string +} + +/** Minimal Gitea release fields used by discovery. */ +interface GiteaRelease { + readonly tag_name: string + readonly prerelease: boolean + readonly draft: boolean + readonly target_commitish: string | null + readonly created_at: string | null + readonly body: string + readonly assets: readonly GiteaAsset[] +} + +/** Metadata published beside a release. */ +interface EntryMetadata { + readonly kind: MarketKind | null + readonly id: string | null + readonly name: string | null + readonly summary: string | null + readonly description: string | null + readonly version: string | null + readonly publisher: string | null + readonly source_sha: string | null + readonly manifest: MarketManifest + readonly signature: MarketSignature + readonly known_limitations: readonly string[] + readonly risk: string | null +} + +/** Request one market JSON document through the shared egress client. */ +async function marketJson(network: EgressClient, url: string, label: string, maxBytes = 2 * 1024 * 1024): Promise { + let response + try { + response = await network.request({ purpose: 'market', url, method: 'GET', maxBytes, timeoutMs: 30_000 }) + } catch (error) { + if (error instanceof NetworkError) throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: ${error.code}`) + throw error + } + if (response.status < 200 || response.status >= 300) { + throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: HTTP ${response.status}`) + } + const text = response.body.toString('utf8') + try { + const parsed: unknown = JSON.parse(text) + return parsed + } catch { + throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: response is not JSON`) + } +} + +/** Fetch one small text document through the shared egress client. */ +async function marketText(network: EgressClient, url: string, label: string, maxBytes = 64 * 1024): Promise { + let response + try { + response = await network.request({ purpose: 'market', url, method: 'GET', maxBytes, timeoutMs: 20_000 }) + } catch (error) { + if (error instanceof NetworkError) throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: ${error.code}`) + throw error + } + if (response.status < 200 || response.status >= 300) { + throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: HTTP ${response.status}`) + } + return response.body.toString('utf8') +} + +/** Parse one Gitea repository record. */ +function parseRepository(value: unknown, label: string): GiteaRepository { + const record = recordOf(value) + if (record === undefined) throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: repository is not an object`) + const ownerRecord = recordOf(record.owner) + if (ownerRecord === undefined) throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: repository has no owner`) + const topics = record.topics + return { + full_name: requiredString(record, 'full_name', label), + name: requiredString(record, 'name', label), + owner: requiredString(ownerRecord, 'login', `${label}.owner`), + topics: Array.isArray(topics) ? topics.filter((topic): topic is string => typeof topic === 'string') : [], + archived: record.archived === true, + empty: record.empty === true, + description: optionalString(record, 'description', label) ?? '', + } +} + +/** Parse one Gitea release record. */ +function parseRelease(value: unknown, label: string): GiteaRelease { + const record = recordOf(value) + if (record === undefined) throw new MarketError(MARKET_ERROR.refreshFailed, `${label}: release is not an object`) + const rawAssets = record.assets + const assets: GiteaAsset[] = [] + if (Array.isArray(rawAssets)) { + for (const item of rawAssets) { + const asset = recordOf(item) + if (asset === undefined) continue + const name = optionalString(asset, 'name', `${label}.asset`) + const url = optionalString(asset, 'browser_download_url', `${label}.asset`) + if (name === null || url === null) continue + assets.push({ name, size: typeof asset.size === 'number' ? asset.size : null, url }) + } + } + return { + tag_name: requiredString(record, 'tag_name', label), + prerelease: record.prerelease === true, + draft: record.draft === true, + target_commitish: optionalString(record, 'target_commitish', label), + created_at: optionalString(record, 'created_at', label), + body: optionalString(record, 'body', label) ?? '', + assets, + } +} + +/** Discover repositories for one Gitea source. */ +async function giteaRepositories( + source: MarketSourceConfig, + network: EgressClient, +): Promise<{ repositories: GiteaRepository[]; warnings: string[] }> { + if (source.base === null) throw new MarketError(MARKET_ERROR.configInvalid, `source ${source.id} has no base`) + const base = source.base + const repositories = new Map() + const warnings: string[] = [] + const add = (value: unknown, label: string): void => { + try { + const repository = parseRepository(value, label) + if (repository.archived || repository.empty) return + repositories.set(repository.full_name, repository) + } catch (error) { + if (error instanceof MarketError) warnings.push(error.message) + else throw error + } + } + for (const name of source.repositories) { + try { + add(await marketJson(network, `${base}/api/v1/repos/${name}`, `repository ${name}`), `repository ${name}`) + } catch (error) { + if (error instanceof MarketError) warnings.push(error.message) + else throw error + } + } + const search = async (topic: string): Promise => { + const url = `${base}/api/v1/repos/search?q=${encodeURIComponent(topic)}&topic=true&limit=50` + const parsed = await marketJson(network, url, `topic ${topic}`) + const record = recordOf(parsed) + const data = record === undefined ? undefined : record.data + if (!Array.isArray(data)) { + throw new MarketError(MARKET_ERROR.refreshFailed, `topic ${topic}: response has no data array`) + } + for (const item of data) add(item, `topic ${topic}`) + } + for (const topic of source.topics) await search(topic) + if (source.topics.length === 0) { + for (const owner of source.owners) { + const parsed = await marketJson(network, `${base}/api/v1/users/${owner}/repos?limit=50`, `repositories of ${owner}`) + if (!Array.isArray(parsed)) { + throw new MarketError(MARKET_ERROR.refreshFailed, `repositories of ${owner}: response is not an array`) + } + for (const item of parsed) add(item, `repositories of ${owner}`) + } + } + const allowedOwners = new Set(source.owners) + const filtered = [...repositories.values()].filter(repository => ( + allowedOwners.size === 0 || allowedOwners.has(repository.owner) + )) + return { repositories: filtered, warnings } +} + +/** Select the installable platform archive from one release. */ +function selectAsset(release: GiteaRelease, platform: string): GiteaAsset | undefined { + const archives = release.assets.filter(asset => asset.name.endsWith('.tar.gz')) + return archives.find(asset => asset.name.includes(platform)) ?? archives.find(asset => asset.name.includes('noarch')) +} + +/** Derive a stable display summary from a release body. */ +function bodySummary(body: string): string { + const line = body.split('\n').map(value => value.trim()).find(value => value !== '' && !value.startsWith('#')) + return line === undefined ? '' : line.slice(0, 240) +} + +/** Parse optional published market metadata. */ +function parseEntryMetadata(value: unknown): EntryMetadata { + const record = recordOf(value) + if (record === undefined) throw new MarketError(MARKET_ERROR.configInvalid, 'market-entry.json must be an object') + const rawKind = optionalString(record, 'kind', 'market-entry.json') + if (rawKind !== null && rawKind !== 'ext' && rawKind !== 'tool') { + throw new MarketError(MARKET_ERROR.configInvalid, `market-entry.json kind is not ext/tool: ${rawKind}`) + } + return { + kind: rawKind, + id: optionalString(record, 'id', 'market-entry.json'), + name: optionalString(record, 'name', 'market-entry.json'), + summary: optionalString(record, 'summary', 'market-entry.json'), + description: optionalString(record, 'description', 'market-entry.json'), + version: optionalString(record, 'version', 'market-entry.json'), + publisher: optionalString(record, 'publisher', 'market-entry.json'), + source_sha: optionalString(record, 'source_sha', 'market-entry.json'), + manifest: parseManifest(record.manifest, 'market-entry.json.manifest'), + signature: parseSignature(record.signature, 'market-entry.json.signature'), + known_limitations: stringList(record, 'known_limitations', 'market-entry.json'), + risk: optionalString(record, 'risk', 'market-entry.json'), + } +} + +/** Derive the CLI Tool command from a repository name when no metadata exists. */ +function commandForRepository(repositoryName: string): string { + return repositoryName.startsWith('marqdo-') ? repositoryName.slice('marqdo-'.length) : repositoryName +} + +/** Derive a display manifest for legacy tool releases without market metadata. */ +function derivedToolManifest(repositoryName: string): MarketManifest { + const command = commandForRepository(repositoryName) + return { ...emptyManifest(), tools: [command], capabilities: [command] } +} + +/** Resolve the entry kind from repository topics or the source default. */ +function kindOf(repository: GiteaRepository, source: MarketSourceConfig): MarketKind | null { + const ext = repository.topics.includes('marqdo-ext') + const tool = repository.topics.includes('marqdo-tool') + if (ext && !tool) return 'ext' + if (tool && !ext) return 'tool' + return source.default_kind +} + +/** Read the digest sidecar or release evidence for one asset. */ +async function assetDigest( + network: EgressClient, + release: GiteaRelease, + asset: GiteaAsset, +): Promise { + const sidecar = release.assets.find(candidate => candidate.name === `${asset.name}.sha256`) + if (sidecar !== undefined) { + const text = await marketText(network, sidecar.url, `digest ${asset.name}`, 4096) + const match = /([0-9a-fA-F]{64})/.exec(text) + if (match?.[1] !== undefined) return match[1].toLowerCase() + } + const evidence = release.assets.find(candidate => candidate.name === 'release-evidence.json') + if (evidence !== undefined) { + const parsed = await marketJson(network, evidence.url, `evidence ${asset.name}`) + const record = recordOf(parsed) + const assets = record?.assets + if (Array.isArray(assets)) { + for (const item of assets) { + const entry = recordOf(item) + if (entry === undefined) continue + const name = optionalString(entry, 'name', 'release evidence') + const sha = optionalString(entry, 'sha256', 'release evidence') + if (name === asset.name && sha !== null) return digestHex(sha, 'release evidence') + } + } + } + return null +} + +/** Read source SHA from release evidence when `target_commitish` is a branch. */ +async function releaseSourceSha(network: EgressClient, release: GiteaRelease, metadata: EntryMetadata | null): Promise { + if (metadata?.source_sha !== null && metadata?.source_sha !== undefined) return metadata.source_sha + if (release.target_commitish !== null && /^[0-9a-f]{40}$/.test(release.target_commitish)) return release.target_commitish + const evidence = release.assets.find(candidate => candidate.name === 'release-evidence.json') + if (evidence === undefined) return null + try { + const parsed = await marketJson(network, evidence.url, 'release evidence') + const record = recordOf(parsed) + const sha = record === undefined ? null : optionalString(record, 'source_sha', 'release evidence') + return sha !== null && /^[0-9a-f]{40}$/.test(sha) ? sha : null + } catch { + return null + } +} + +/** Build one entry with explicit identity and timestamps. */ +function makeEntry(input: { + source: MarketSourceConfig + kind: MarketKind + id: string + name: string + summary: string + description: string + version: string + channel: 'stable' | 'prerelease' + platform: string | null + asset: MarketAsset + manifest: MarketManifest + sourceSha: string | null + publishedAt: string | null + publisher: string | null + signature: MarketSignature + knownLimitations: readonly string[] + risk: string | null + browserUrl: string | null + now: string +}): MarketEntry { + return { + key: entryKey(input.source.id, input.kind, input.id), + source_id: input.source.id, + source_label: input.source.label, + source_kind: input.source.kind, + kind: input.kind, + id: input.id, + name: input.name, + summary: input.summary, + description: input.description, + version: input.version, + channel: input.channel, + platform: input.platform, + asset: input.asset, + manifest: input.manifest, + source_sha: input.sourceSha, + published_at: input.publishedAt, + publisher: input.publisher, + signature: input.signature, + known_limitations: input.knownLimitations, + risk: input.risk, + browser_url: input.browserUrl, + availability: 'available', + unavailable_reason: null, + change: 'unchanged', + first_seen_at: input.now, + last_seen_at: input.now, + } +} + +/** Discover one Gitea repository's newest installable release. */ +async function giteaEntry( + source: MarketSourceConfig, + repository: GiteaRepository, + network: EgressClient, + options: DiscoveryOptions, + warnings: string[], +): Promise { + const base = source.base + if (base === null) return null + const kind = kindOf(repository, source) + if (kind === null) { + warnings.push(`${repository.full_name}: no marqdo-ext/marqdo-tool topic and no source default_kind`) + return null + } + let releasesValue: unknown + try { + releasesValue = await marketJson(network, `${base}/api/v1/repos/${repository.full_name}/releases?limit=30`, `releases of ${repository.full_name}`) + } catch (error) { + warnings.push(error instanceof Error ? error.message : String(error)) + return null + } + if (!Array.isArray(releasesValue)) { + warnings.push(`${repository.full_name}: release list is not an array`) + return null + } + const platform = options.platform ?? targetTriple() + const releases = releasesValue + .map((value, index) => { + try { + return parseRelease(value, `release ${index}`) + } catch (error) { + warnings.push(error instanceof Error ? error.message : String(error)) + return null + } + }) + .filter((release): release is GiteaRelease => release !== null && !release.draft) + .sort((left, right) => compareVersions(left.tag_name, right.tag_name)) + for (const release of releases) { + const asset = selectAsset(release, platform) + if (asset === undefined) continue + if (!asset.url.startsWith(`${base}/`)) { + warnings.push(`${repository.full_name}@${release.tag_name}: asset URL is outside ${base}`) + continue + } + let metadata: EntryMetadata | null = null + const metadataAsset = release.assets.find(candidate => candidate.name === 'market-entry.json' || candidate.name === 'marqdo-market.json') + if (metadataAsset !== undefined) { + try { + metadata = parseEntryMetadata(await marketJson(network, metadataAsset.url, `${repository.full_name} market metadata`, 1024 * 1024)) + } catch (error) { + warnings.push(error instanceof Error ? error.message : String(error)) + continue + } + if (metadata.kind !== null && metadata.kind !== kind) { + warnings.push(`${repository.full_name}: metadata kind ${metadata.kind} disagrees with repository topics`) + continue + } + } + let sha: string | null + try { + sha = await assetDigest(network, release, asset) + } catch (error) { + warnings.push(error instanceof Error ? error.message : String(error)) + continue + } + if (sha === null) { + warnings.push(`${repository.full_name}@${release.tag_name}: asset ${asset.name} has no SHA-256 sidecar`) + continue + } + const sourceSha = await releaseSourceSha(network, release, metadata) + const version = metadata?.version ?? release.tag_name.replace(/^v/, '') + const command = commandForRepository(repository.name) + const manifest = metadata?.manifest ?? (kind === 'tool' ? derivedToolManifest(repository.name) : emptyManifest()) + const summary = metadata?.summary ?? (bodySummary(release.body) || repository.description) + return makeEntry({ + source, + kind, + id: metadata?.id ?? repository.name, + name: metadata?.name ?? repository.name, + summary, + description: (metadata?.description ?? release.body).slice(0, 4000), + version, + channel: release.prerelease ? 'prerelease' : 'stable', + platform, + asset: { name: asset.name, size: asset.size, sha256: sha, url: asset.url, relative: null }, + manifest: kind === 'tool' && manifest.tools.length === 0 ? { ...manifest, tools: [command] } : manifest, + sourceSha, + publishedAt: release.created_at, + publisher: metadata?.publisher ?? repository.owner, + signature: metadata?.signature ?? { status: 'unsigned', algorithm: null, key_id: null, value: null }, + knownLimitations: metadata?.known_limitations ?? [], + risk: metadata?.risk ?? null, + browserUrl: `${base}/${repository.full_name}/releases/tag/${release.tag_name}`, + now: options.now().toISOString(), + }) + } + warnings.push(`${repository.full_name}: no installable ${platform} release`) + return null +} + +/** Parse and validate one directory index entry. */ +async function directoryEntry( + source: MarketSourceConfig, + value: unknown, + index: number, + options: DiscoveryOptions, + warnings: string[], +): Promise { + if (source.path === null) return null + const label = `directory entry ${index}` + try { + const record = recordOf(value) + if (record === undefined) throw new MarketError(MARKET_ERROR.configInvalid, `${label} must be an object`) + const kind = optionalString(record, 'kind', label) ?? source.default_kind + if (kind !== 'ext' && kind !== 'tool') throw new MarketError(MARKET_ERROR.configInvalid, `${label}.kind must be ext or tool`) + const id = requiredString(record, 'id', label) + const version = requiredString(record, 'version', label) + const rawAsset = recordOf(record.asset) + if (rawAsset === undefined) throw new MarketError(MARKET_ERROR.configInvalid, `${label}.asset must be an object`) + const assetName = requiredString(rawAsset, 'name', `${label}.asset`) + const assetRelative = requiredString(rawAsset, 'path', `${label}.asset`) + if (isAbsolute(assetRelative) || assetRelative.split(/[\\/]/).includes('..')) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.asset.path must stay below the source directory`) + } + const root = await realpath(source.path) + const absolute = resolve(join(root, assetRelative)) + const rel = relative(root, absolute) + if (rel.startsWith('..') || isAbsolute(rel)) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.asset.path escapes the source directory`) + } + const info = await lstat(absolute).catch(() => undefined) + if (info === undefined) throw new MarketError(MARKET_ERROR.configInvalid, `${label}.asset.path is not a regular file`) + if (info.isSymbolicLink()) throw new MarketError(MARKET_ERROR.archiveUnsafe, `${label}.asset.path is a symbolic link`) + if (!info.isFile()) throw new MarketError(MARKET_ERROR.configInvalid, `${label}.asset.path is not a regular file`) + await realpathWithin(root, absolute, 'market asset') + const actualDigest = (await digestFile(absolute)).slice('sha256:'.length) + const actualSize = (await stat(absolute)).size + const declaredDigest = optionalString(rawAsset, 'sha256', `${label}.asset`) + if (declaredDigest !== null && digestHex(declaredDigest, `${label}.asset.sha256`) !== actualDigest) { + throw new MarketError(MARKET_ERROR.digestMismatch, `${label}.asset.sha256 does not match ${assetName}`) + } + const declaredSize = typeof rawAsset.size === 'number' ? rawAsset.size : null + if (declaredSize !== null && declaredSize !== actualSize) { + throw new MarketError(MARKET_ERROR.digestMismatch, `${label}.asset.size does not match ${assetName}`) + } + const metadata = parseEntryMetadata(record) + if (metadata.kind !== null && metadata.kind !== kind) { + throw new MarketError(MARKET_ERROR.configInvalid, `${label}.kind disagrees with metadata`) + } + return makeEntry({ + source, + kind, + id, + name: metadata.name ?? requiredString(record, 'name', label), + summary: metadata.summary ?? optionalString(record, 'summary', label) ?? '', + description: metadata.description ?? optionalString(record, 'description', label) ?? '', + version: metadata.version ?? version, + channel: optionalString(record, 'channel', label) === 'prerelease' ? 'prerelease' : 'stable', + platform: optionalString(record, 'platform', label) ?? (options.platform ?? targetTriple()), + asset: { name: assetName, size: actualSize, sha256: actualDigest, url: null, relative: assetRelative }, + manifest: metadata.manifest, + sourceSha: metadata.source_sha, + publishedAt: optionalString(record, 'published_at', label), + publisher: metadata.publisher ?? optionalString(record, 'publisher', label), + signature: metadata.signature, + knownLimitations: metadata.known_limitations, + risk: metadata.risk, + browserUrl: optionalString(record, 'browser_url', label), + now: options.now().toISOString(), + }) + } catch (error) { + warnings.push(error instanceof Error ? error.message : String(error)) + return null + } +} + +/** Discover one directory source from its `index.json`. */ +async function discoverDirectory(source: MarketSourceConfig, options: DiscoveryOptions, warnings: string[]): Promise { + if (source.path === null) return [] + const indexPath = join(source.path, 'index.json') + const raw = await readJson>(indexPath) + if (raw === undefined) throw new MarketError(MARKET_ERROR.refreshFailed, `directory source ${source.id} has no index.json`) + if (raw.schema !== 'marqdo.mqdh.market.directory' || raw.schema_version !== 1) { + throw new MarketError(MARKET_ERROR.refreshFailed, `directory source ${source.id} has an unsupported index schema`) + } + const entries = raw.entries + if (!Array.isArray(entries)) throw new MarketError(MARKET_ERROR.refreshFailed, `directory source ${source.id} entries must be an array`) + const discovered: MarketEntry[] = [] + const seen = new Set() + for (const [index, value] of entries.entries()) { + const entry = await directoryEntry(source, value, index, options, warnings) + if (entry === null) continue + if (seen.has(entry.key)) { + throw new MarketError(MARKET_ERROR.configInvalid, `directory source ${source.id} has duplicate entry ${entry.key}`) + } + seen.add(entry.key) + discovered.push(entry) + } + return discovered +} + +/** + * Discover every entry for one configured source. + * + * A source-level transport/configuration failure throws; per-entry problems are + * returned as warnings so one bad release cannot hide the rest of a source. + * @param source - validated source configuration. + * @param network - shared egress client. + * @param options - platform, offline mode and clock. + * @returns discovered entries and non-fatal warnings. + */ +export async function discoverSource( + source: MarketSourceConfig, + network: EgressClient, + options: DiscoveryOptions, +): Promise { + if (source.kind === 'directory') { + const warnings: string[] = [] + return { entries: await discoverDirectory(source, options, warnings), warnings } + } + if (options.offline) { + throw new MarketError(MARKET_ERROR.refreshFailed, `offline mode skips Gitea source ${source.id}`) + } + const { repositories, warnings } = await giteaRepositories(source, network) + const entries: MarketEntry[] = [] + for (const repository of repositories) { + const entry = await giteaEntry(source, repository, network, options, warnings) + if (entry !== null) entries.push(entry) + } + return { entries, warnings: warnings.slice(0, 20) } +} diff --git a/packages/marqdo/harness/src/market/errors.ts b/packages/marqdo/harness/src/market/errors.ts new file mode 100644 index 0000000000..f8414c3fcd --- /dev/null +++ b/packages/marqdo/harness/src/market/errors.ts @@ -0,0 +1,49 @@ +/** + * Stable market failure codes. + * + * The workbench maps these codes to actionable UI states; the model never sees + * them because market mutations are user-only. Codes are part of the local + * application contract and may be asserted by tests. + * + * @module @marqdo/mqdh-harness/market/errors + */ + +/** Market/configuration/capability failure with a stable code. */ +export class MarketError extends Error { + override name = 'MarketError' + readonly code: string + + constructor(code: string, message: string) { + super(message) + this.code = code + } +} + +/** Canonical local error codes. */ +export const MARKET_ERROR = { + configInvalid: 'market.config_invalid', + sourceUnknown: 'market.source_unknown', + sourceDuplicate: 'market.source_duplicate', + sourceInUse: 'market.source_in_use', + entryUnknown: 'market.entry_unknown', + entryUnavailable: 'market.entry_unavailable', + refreshFailed: 'market.refresh_failed', + installFailed: 'market.install_failed', + archiveUnsafe: 'market.archive_unsafe', + digestMismatch: 'market.digest_mismatch', + capabilityNotInstalled: 'extension.not_installed', + capabilityProjectReferenced: 'extension.project_referenced', + capabilityVersionUnknown: 'extension.version_unknown', + capabilityToolUnavailable: 'extension.tool_unavailable', + importUnsupported: 'extension.import_unsupported', + importConflict: 'project.import_conflict', + runtimeNotInstalled: 'runtime.not_installed', + projectManifestMissing: 'project.manifest_missing', + cliFailed: 'cli.command_failed', + buildDeclined: 'extension.build_declined', + buildRequired: 'extension.build_required', + buildFailed: 'extension.build_failed', +} as const + +/** One canonical market error code. */ +export type MarketErrorCode = (typeof MARKET_ERROR)[keyof typeof MARKET_ERROR] diff --git a/packages/marqdo/harness/src/market/index.ts b/packages/marqdo/harness/src/market/index.ts new file mode 100644 index 0000000000..124bb4606f --- /dev/null +++ b/packages/marqdo/harness/src/market/index.ts @@ -0,0 +1,308 @@ +/** + * The rebuildable market index projection. + * + * A refresh reads the user's sources, discovers current entries, compares them + * with the previous projection and retains the last good entries for a source + * that failed. The index is never an authority: capability identity is the + * installed payload digest, and project identity remains the CLI lock. + * + * @module @marqdo/mqdh-harness/market/index + */ + +import { open, readFile } from 'node:fs/promises' +import { join } from 'node:path' +import type { MdhLayout } from '../core/home.ts' +import { digestBytes, readJson, writeJsonAtomic } from '../core/fsx.ts' +import { withLock } from '../core/lock.ts' +import type { EgressClient } from '../network/client.ts' +import { parseMarketConfig, readMarketConfig, serializeMarketConfig, writeMarketConfig } from './config.ts' +import type { MarketConfig, MarketSourceConfig } from './config.ts' +import { parseMarketIndex } from './contract.ts' +import type { MarketEntry, MarketIndex, MarketSourceState } from './contract.ts' +import { discoverSource } from './discovery.ts' +import { MARKET_ERROR, MarketError } from './errors.ts' + +/** One market change event. */ +export interface MarketEvent { + readonly at: string + readonly type: 'market.changed' + readonly source_id: string | null + readonly changes: readonly { readonly key: string; readonly change: 'new' | 'changed' | 'stale' }[] +} + +/** Build an empty projection before the first refresh. */ +function emptyIndex(config: MarketConfig): MarketIndex { + return { + schema: 'marqdo.mqdh.market.index', + schema_version: 1, + generated_at: new Date(0).toISOString(), + config_digest: digestBytes(JSON.stringify(serializeMarketConfig(config))), + sources: config.sources.map(source => ({ + id: source.id, + status: 'never', + checked_at: new Date(0).toISOString(), + error: null, + warnings: [], + entries: 0, + })), + entries: [], + } +} + +/** Stable digest of the source selection. */ +function configDigest(config: MarketConfig): string { + return digestBytes(JSON.stringify(serializeMarketConfig(config))) +} + +/** Mark a discovered entry relative to the previous projection. */ +function applyChange(entry: MarketEntry, previous: MarketEntry | undefined, now: string): MarketEntry { + const changed = previous !== undefined && ( + previous.version !== entry.version || previous.asset.sha256 !== entry.asset.sha256 + ) + return { + ...entry, + change: previous === undefined ? 'new' : changed ? 'changed' : 'unchanged', + first_seen_at: previous?.first_seen_at ?? now, + last_seen_at: now, + } +} + +/** Keep a removed entry visible as stale without making it installable. */ +function staleEntry(entry: MarketEntry, now: string): MarketEntry { + return { + ...entry, + availability: 'stale', + change: 'stale', + unavailable_reason: '条目已从来源移除;已安装版本与项目引用不受影响', + last_seen_at: now, + } +} + +/** Append one bounded local change event. */ +async function appendEvent(path: string, event: MarketEvent): Promise { + const handle = await open(path, 'a', 0o600) + try { + await handle.writeFile(`${JSON.stringify(event)}\n`) + } finally { + await handle.close() + } +} + +/** The market index service. */ +export class MarketIndexService { + readonly #layout: MdhLayout + readonly #network: EgressClient + + constructor(layout: MdhLayout, network: EgressClient) { + this.#layout = layout + this.#network = network + } + + /** Read the effective source configuration on every call. */ + async config(): Promise { + return await readMarketConfig(join(this.#layout.config, 'market.json'), this.#network.config.releaseAuthority) + } + + /** Replace the source configuration after validation. */ + async saveConfig(config: MarketConfig): Promise { + await writeMarketConfig(join(this.#layout.config, 'market.json'), config) + } + + /** Add one source and persist the configuration. */ + async addSource(source: MarketSourceConfig): Promise { + const config = await this.config() + if (config.sources.some(existing => existing.id === source.id)) { + throw new MarketError(MARKET_ERROR.sourceDuplicate, `market source already exists: ${source.id}`) + } + const updated: MarketConfig = { ...config, sources: [...config.sources, source] } + await this.saveConfig(updated) + return updated + } + + /** Remove one source and persist the configuration. */ + async removeSource(id: string): Promise { + const config = await this.config() + if (!config.sources.some(source => source.id === id)) { + throw new MarketError(MARKET_ERROR.sourceUnknown, `unknown market source: ${id}`) + } + const updated: MarketConfig = { ...config, sources: config.sources.filter(source => source.id !== id) } + await this.saveConfig(updated) + return updated + } + + /** Read the last projection; a corrupt rebuildable index is ignored. */ + async current(): Promise { + const raw = await readJson>(this.#layout.marketIndex) + if (raw === undefined) return emptyIndex(await this.config()) + try { + return parseMarketIndex(raw) + } catch { + // The market index is a rebuildable projection; a corrupt file is replaced on the next refresh. + return emptyIndex(await this.config()) + } + } + + /** Read one entry from the current projection. */ + async entry(key: string): Promise { + return (await this.current()).entries.find(entry => entry.key === key) + } + + /** Read recent change events, newest last. */ + async events(limit = 50): Promise { + let text = '' + try { + text = await readFile(this.#layout.marketEvents, 'utf8') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + return [] + } + const events: MarketEvent[] = [] + for (const line of text.split('\n')) { + if (line.trim() === '') continue + try { + const parsed: unknown = JSON.parse(line) + if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) { + const record = parsed as Record + if (record.type === 'market.changed' && typeof record.at === 'string' && Array.isArray(record.changes)) { + events.push({ + at: record.at, + type: 'market.changed', + source_id: typeof record.source_id === 'string' ? record.source_id : null, + changes: record.changes.flatMap((change) => { + if (typeof change !== 'object' || change === null) return [] + const item = change as Record + if (typeof item.key !== 'string') return [] + const kind = item.change + if (kind !== 'new' && kind !== 'changed' && kind !== 'stale') return [] + return [{ key: item.key, change: kind }] + }), + }) + } + } + } catch (error) { + if (!(error instanceof SyntaxError)) throw error + } + } + return events.slice(-Math.max(1, limit)) + } + + /** + * Refresh the projection from every configured source. + * + * A fresh cache is returned unless `force` is set. A failed source retains + * its last entries and reports `stale`; an offline Gitea source reports + * `offline`. The write is atomic and serialized with other refreshes. + * @param options - force bypasses the TTL cache. + * @returns the projection written to disk. + */ + async refresh(options: { force?: boolean } = {}): Promise { + return await withLock(join(this.#layout.market, 'refresh.lock'), async () => { + const config = await this.config() + const digest = configDigest(config) + const cached = await this.current() + const generated = Date.parse(cached.generated_at) + const fresh = cached.config_digest === digest + && Number.isFinite(generated) + && Date.now() - generated < config.cache_ttl_ms + if (options.force !== true && fresh) return cached + const offline = config.offline || this.#network.config.offline + const now = new Date().toISOString() + const previousByKey = new Map(cached.entries.map(entry => [entry.key, entry])) + const configured = new Set(config.sources.map(source => source.id)) + const successful = new Set() + const states: MarketSourceState[] = [] + const entries: MarketEntry[] = [] + const emitted = new Set() + for (const source of config.sources) { + try { + const discovery = await discoverSource(source, this.#network, { + offline, + now: () => new Date(now), + }) + successful.add(source.id) + for (const entry of discovery.entries) { + const applied = applyChange(entry, previousByKey.get(entry.key), now) + entries.push(applied) + emitted.add(entry.key) + } + states.push({ + id: source.id, + status: 'ok', + checked_at: now, + error: null, + warnings: discovery.warnings, + entries: discovery.entries.length, + }) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + const status = offline && source.kind === 'gitea' ? 'offline' : 'stale' + states.push({ + id: source.id, + status, + checked_at: now, + error: message.slice(0, 300), + warnings: [], + entries: cached.entries.filter(entry => entry.source_id === source.id).length, + }) + for (const entry of cached.entries) { + if (entry.source_id !== source.id || emitted.has(entry.key)) continue + entries.push({ ...entry, change: 'unchanged', availability: entry.availability }) + emitted.add(entry.key) + } + } + } + for (const previous of cached.entries) { + if (emitted.has(previous.key)) continue + if (!configured.has(previous.source_id)) continue + if (!successful.has(previous.source_id)) continue + entries.push(staleEntry(previous, now)) + emitted.add(previous.key) + } + entries.sort((left, right) => ( + left.kind.localeCompare(right.kind, 'en') + || left.source_id.localeCompare(right.source_id, 'en') + || left.name.localeCompare(right.name, 'en') + || left.version.localeCompare(right.version, 'en') + )) + const index: MarketIndex = { + schema: 'marqdo.mqdh.market.index', + schema_version: 1, + generated_at: now, + config_digest: digest, + sources: states, + entries, + } + const changes: { key: string; change: 'new' | 'changed' | 'stale' }[] = [] + for (const entry of entries) { + const previous = previousByKey.get(entry.key) + const before = previous === undefined ? null : `${previous.version}:${previous.asset.sha256}` + const after = `${entry.version}:${entry.asset.sha256}` + if (entry.change === 'new') { + changes.push({ key: entry.key, change: 'new' }) + } else if (entry.change === 'stale' && previous?.availability !== 'stale') { + changes.push({ key: entry.key, change: 'stale' }) + } else if (entry.change === 'changed' && before !== after) { + changes.push({ key: entry.key, change: 'changed' }) + } else if (previous !== undefined && previous.availability !== entry.availability && entry.availability === 'stale') { + changes.push({ key: entry.key, change: 'stale' }) + } + } + await writeJsonAtomic(this.#layout.marketIndex, index, 0o600) + if (changes.length > 0) { + await appendEvent(this.#layout.marketEvents, { at: now, type: 'market.changed', source_id: null, changes }) + } + return index + }) + } + + /** + * Parse and persist a raw market configuration (Web source editing). + * @param raw - raw configuration object. + * @returns the validated and persisted configuration. + */ + async replaceConfig(raw: unknown): Promise { + const config = parseMarketConfig(raw) + await this.saveConfig(config) + return config + } +} diff --git a/packages/marqdo/harness/src/network/audit.ts b/packages/marqdo/harness/src/network/audit.ts index 5a50c6eec2..39e4fb7640 100644 --- a/packages/marqdo/harness/src/network/audit.ts +++ b/packages/marqdo/harness/src/network/audit.ts @@ -67,8 +67,9 @@ export class NetworkAudit { } finally { await handle.close() } - } catch { - // A full disk must not turn into a failed request. + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== 'ENOSPC' && code !== 'EACCES' && code !== 'EROFS') throw error } } @@ -81,8 +82,8 @@ export class NetworkAudit { try { const parsed: unknown = JSON.parse(line) if (isAuditEntry(parsed)) entries.push(parsed) - } catch { - // A truncated final line is ignored, not treated as an entry. + } catch (error) { + if (!(error instanceof SyntaxError)) throw error } } return entries.slice(-Math.max(1, limit)) diff --git a/packages/marqdo/harness/src/network/policy.ts b/packages/marqdo/harness/src/network/policy.ts index 775f9cd517..069918b93b 100644 --- a/packages/marqdo/harness/src/network/policy.ts +++ b/packages/marqdo/harness/src/network/policy.ts @@ -19,6 +19,7 @@ export const NETWORK_PURPOSES = [ 'release', 'update', 'issue', + 'market', 'bootstrap', 'model', 'knowledge-embedding', @@ -237,6 +238,11 @@ export function purposeAuthorities(purpose: NetworkPurpose, config: NetworkConfi return [release, ...mirror] case 'issue': return [issue, ...mirror] + case 'market': + // A market URL comes only from user-owned market.json; public HTTPS is + // admitted here and private/loopback targets still need an explicit + // allow_private/allow_loopback entry. + return [] case 'model': case 'knowledge-embedding': return mirror @@ -281,6 +287,15 @@ export function classifyUrl(url: URL, purpose: NetworkPurpose, config: NetworkCo return deny('private_address_denied', `private destination ${authority} is not explicitly allowed`) } if (!allowed.has(authority)) { + if (purpose === 'market' && url.protocol === 'https:' && !isLocal) { + return { + ...base, + allowed: true, + code: 'allowed', + reason: 'public HTTPS market source from user configuration', + mirror: false, + } + } return deny('host_denied', `${authority} is not an allowed ${purpose} destination`) } return { diff --git a/packages/marqdo/harness/src/platform/detect.ts b/packages/marqdo/harness/src/platform/detect.ts index 835335d88b..bd745dfd91 100644 --- a/packages/marqdo/harness/src/platform/detect.ts +++ b/packages/marqdo/harness/src/platform/detect.ts @@ -125,8 +125,9 @@ async function detectLibc(glibc: string | null): Promise { try { await access(marker, constants.F_OK) return 'musl' - } catch { - // Keep looking. + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== 'ENOENT' && code !== 'EACCES') throw error } } return 'unknown' @@ -137,7 +138,8 @@ export async function freeDiskBytes(path: string): Promise { try { const stats = await statfs(path) return Number(stats.bavail) * Number(stats.bsize) - } catch { + } catch (error) { + void error return null } } @@ -151,8 +153,9 @@ async function findExecutable(name: string): Promise { try { await access(candidate, constants.X_OK) return candidate - } catch { - // Keep looking. + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== 'ENOENT' && code !== 'EACCES') throw error } } return null @@ -171,8 +174,9 @@ async function findCaFile(): Promise { try { await access(candidate, constants.R_OK) return candidate - } catch { - // Keep looking. + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code !== 'ENOENT' && code !== 'EACCES') throw error } } return null diff --git a/packages/marqdo/harness/src/runtime.ts b/packages/marqdo/harness/src/runtime.ts index 6b502f91bc..f8b9a361a5 100644 --- a/packages/marqdo/harness/src/runtime.ts +++ b/packages/marqdo/harness/src/runtime.ts @@ -25,6 +25,9 @@ import { KnowledgeManager } from './knowledge/manager.ts' import { readProjectDependencies } from './ecosystem/project.ts' import type { ProjectDependencyStatus } from './ecosystem/project.ts' import { EgressClient } from './network/client.ts' +import { MarketIndexService } from './market/index.ts' +import { CapabilityStore } from './market/capabilities.ts' +import type { CapabilityView, VisibleCapability } from './market/capabilities.ts' import { BootstrapManager } from './bootstrap/manager.ts' import { DiagnosticsStore } from './diagnostics/store.ts' import type { DiagnosticIdentity } from './diagnostics/store.ts' @@ -64,7 +67,7 @@ export interface FunctionCandidate { export interface ReadResult { readonly id: string readonly kind: string - readonly provenance: string + readonly source_ref: string readonly digest: string readonly start: number readonly end: number @@ -77,6 +80,7 @@ export interface MdhStatus { readonly home: string workspace: string readonly ecosystem: EcosystemStatus + readonly market: { readonly entries: number; readonly installed: number; readonly enabled: number } readonly knowledge: { readonly collections: number; readonly sources: number; readonly enabled: number } readonly privacy: { readonly telemetry: false; readonly sessionUpload: false; readonly pluginInstall: false } readonly platform: string @@ -98,6 +102,8 @@ export class MdhRuntime { readonly layout: MdhLayout workspace: string readonly ecosystem: EcosystemManager + readonly market: MarketIndexService + readonly capabilities: CapabilityStore readonly network: EgressClient readonly diagnostics: DiagnosticsStore readonly bootstrap: BootstrapManager @@ -113,6 +119,18 @@ export class MdhRuntime { this.workspace = workspace this.network = network this.ecosystem = new EcosystemManager(layout, network) + this.market = new MarketIndexService(layout, network) + this.capabilities = new CapabilityStore({ + layout, + network, + market: this.market, + cli: () => this.cli(), + toolHome: async () => { + const environment = await this.ecosystem.current() + return environment ? join(layout.environments, environment.id, environment.tool_home) : undefined + }, + workspace: () => this.workspace, + }) this.diagnostics = new DiagnosticsStore({ layout, network, @@ -186,6 +204,16 @@ export class MdhRuntime { return await readProjectDependencies(this.workspace) } + /** Installed capabilities visible to one agent/session scope. */ + async visibleCapabilities(sessionId: string | null): Promise { + return await this.capabilities.visible(sessionId, this.workspace) + } + + /** Installed capability projection for the workbench. */ + async capabilityViews(): Promise { + return await this.capabilities.capabilities() + } + /** Stable identity used by local diagnostic reports. */ async identity(): Promise { const status = await this.ecosystem.status() @@ -212,10 +240,17 @@ export class MdhRuntime { /** Aggregate real state for the workbench and `marqdo_ecosystem(status)`. */ async status(): Promise { const collections = await this.knowledge.collections() + const market = await this.market.current() + const capabilities = await this.capabilities.capabilities() return { home: this.layout.home, workspace: this.workspace, ecosystem: await this.ecosystem.status(), + market: { + entries: market.entries.length, + installed: capabilities.length, + enabled: capabilities.filter(capability => capability.enabled.length > 0).length, + }, knowledge: { collections: collections.length, sources: collections.reduce((sum, collection) => sum + collection.sources.length, 0), @@ -247,14 +282,26 @@ export class MdhRuntime { */ async find( query: string, - options: { kind?: string | undefined; limit?: number | undefined; path?: string | undefined } = {}, + options: { + kind?: string | undefined + limit?: number | undefined + path?: string | undefined + sessionId?: string | null | undefined + } = {}, ): Promise { const limit = Math.max(1, Math.min(options.limit ?? 8, 20)) const needle = query.trim().toLocaleLowerCase() const candidates: FunctionCandidate[] = [] - const status = await this.ecosystem.status() + const [status, visible, installed] = await Promise.all([ + this.ecosystem.status(), + this.visibleCapabilities(options.sessionId ?? null), + this.capabilityViews(), + ]) + const enabledCommands = new Set(visible.flatMap(capability => capability.kind === 'tool' && capability.command !== null ? [capability.command] : [])) + const managedCommands = new Set(installed.flatMap(capability => capability.kind === 'tool' && capability.command !== null ? [capability.command] : [])) if (!options.kind || options.kind === 'tool') { for (const tool of status.tools) { + if (managedCommands.has(tool.command) && !enabledCommands.has(tool.command)) continue if (!needle || tool.command.toLocaleLowerCase().includes(needle) || needle.includes(tool.command.toLocaleLowerCase())) { candidates.push({ id: `tool:${tool.command}`, kind: 'tool', title: `marqdo ${tool.command}`, @@ -264,6 +311,25 @@ export class MdhRuntime { } } } + if (!options.kind || options.kind === 'ext') { + for (const capability of visible) { + if (capability.kind !== 'ext') continue + const haystack = `${capability.name} ${capability.id} ${capability.path}`.toLocaleLowerCase() + if (!needle || haystack.includes(needle)) { + candidates.push({ + id: `ext:${capability.key}`, + kind: 'ext', + title: capability.name, + signature: null, + location: capability.path, + summary: `user-enabled installed extension ${capability.version}; permissions: ${capability.permissions.join(', ') || 'none declared'}`, + availability: 'available', + source: 'ecosystem', + }) + } + if (candidates.length >= limit) return candidates.slice(0, limit) + } + } if (!options.kind || options.kind === 'stdlib') { for (const module of status.std.modules) { const title = module.replace(/\.mq\.md$/, '') @@ -315,7 +381,7 @@ export class MdhRuntime { /** * Read one exact candidate with a bounded range. - * @param id - `workspace:#-[@digest]` or `knowledge::`. + * @param id - `workspace:#-[@digest]`, `knowledge::` or `ext:`. */ async read( id: string, @@ -330,11 +396,20 @@ export class MdhRuntime { collection, relPath, start: options.start, end: options.end, maxBytes: options.maxBytes, }) return { - id, kind: 'knowledge', provenance: `knowledge:${collection}:${relPath}`, + id, kind: 'knowledge', source_ref: `knowledge:${collection}:${relPath}`, digest: result.digest, start: result.start, end: result.end, text: result.text, truncated: result.end - result.start >= (options.maxBytes ?? 16 * 1024), } } + if (id.startsWith('ext:')) { + const key = id.slice('ext:'.length) + const described = await this.capabilities.describe(key) + return { + id, kind: 'ext', source_ref: `ext:${key}`, + digest: described.digest, start: 0, end: described.text.length, + text: described.text, truncated: described.text.endsWith('…'), + } + } if (!id.startsWith('workspace:')) throw new Error(`unsupported candidate id: ${id}`) const body = id.slice('workspace:'.length) const [location, digestPart] = body.split('@') @@ -355,7 +430,7 @@ export class MdhRuntime { const requestedEnd = options.end ?? fallbackEnd const end = Math.max(start, Math.min(requestedEnd, bytes.byteLength, start + maxBytes)) return { - id, kind: 'workspace', provenance: `workspace:${relativePath}`, digest, + id, kind: 'workspace', source_ref: `workspace:${relativePath}`, digest, start, end, text: bytes.subarray(start, end).toString('utf8'), truncated: end < bytes.byteLength, } @@ -387,6 +462,12 @@ export class MdhRuntime { limits: { timeoutMs: this.config.maxRunMs ?? 300_000 }, }) const environment = await this.ecosystem.current() + let lockDigest: string | null = null + try { + lockDigest = await digestFile(join(this.workspace, 'marqdo.lock')) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } const record: RunEvidence = { schema: 'marqdo.mqdh.run-evidence', schema_version: 1, @@ -403,7 +484,7 @@ export class MdhRuntime { source_sha: cli.sourceSha ?? null, }, bundle_digest: environment?.bundle.tree_digest ?? null, - lock_digest: null, + lock_digest: lockDigest, action: input.action, function_name: input.functionName ?? null, arguments: [...(input.args ?? [])], diff --git a/packages/marqdo/harness/src/tools/index.ts b/packages/marqdo/harness/src/tools/index.ts index 282a9736d4..f11475c204 100644 --- a/packages/marqdo/harness/src/tools/index.ts +++ b/packages/marqdo/harness/src/tools/index.ts @@ -30,9 +30,14 @@ interface ApprovalService { }): Promise } +/** Agent identity visible to a tool execution. */ +interface AgentIdentity { + readonly id: string +} + /** Tool execution context fields consumed here. */ interface ToolExec { - readonly agent?: unknown + readonly agent?: AgentIdentity | undefined readonly callId?: unknown readonly signal: AbortSignal } @@ -120,9 +125,14 @@ export function createTools(ctx: Context, runtime: MdhRuntime): MdhToolDefinitio properties: { candidates: { type: 'array', items: { type: 'object', additionalProperties: true } } }, required: ['candidates'], }, - execute: async (raw) => { + execute: async (raw, exec) => { const args = raw as { query: string; kind?: string; limit?: number; path?: string } - const candidates = await runtime.find(args.query, { kind: args.kind, limit: args.limit, path: args.path }) + const candidates = await runtime.find(args.query, { + kind: args.kind, + limit: args.limit, + path: args.path, + sessionId: exec.agent?.id ?? null, + }) return { candidates, query: args.query, count: candidates.length } }, render: (value) => { @@ -156,8 +166,8 @@ export function createTools(ctx: Context, runtime: MdhRuntime): MdhToolDefinitio return await runtime.read(args.candidate, { start: args.start, end: args.end, maxBytes: args.max_bytes }) }, render: (value) => { - const result = value as { text: string; provenance: string; start: number; end: number } - return `${result.provenance} [${result.start}-${result.end}]\n\n${result.text}` + const result = value as { text: string; source_ref: string; start: number; end: number } + return `${result.source_ref} [${result.start}-${result.end}]\n\n${result.text}` }, }) @@ -339,7 +349,7 @@ export function createTools(ctx: Context, runtime: MdhRuntime): MdhToolDefinitio properties: { action: { type: 'string', - enum: ['status', 'install', 'rollback', 'cleanup', 'tool_install', 'tool_remove'], + enum: ['status', 'capabilities', 'install', 'rollback', 'cleanup', 'tool_install', 'tool_remove'], }, component: { type: 'string', enum: ['cli'], description: 'Trusted component id for install' }, version: { type: 'string', description: 'Exact trusted release version or tag' }, @@ -354,6 +364,12 @@ export function createTools(ctx: Context, runtime: MdhRuntime): MdhToolDefinitio if (args.action === 'status') { return { action: 'status', ...(await runtime.status()) } } + if (args.action === 'capabilities') { + return { + action: 'capabilities', + capabilities: await runtime.visibleCapabilities(exec.agent?.id ?? null), + } + } const reason = `Marqdo ecosystem ${args.action}${args.component ? ` ${args.component}` : ''}${args.version ? ` ${args.version}` : ''}${args.tool_path ? ` ${args.tool_path}` : ''}${args.command ? ` ${args.command}` : ''}` const outcome = await approve(ctx, exec, 'marqdo_ecosystem', reason) if (outcome !== 'allowed-once') return { action: args.action, status: 'not_approved', approval: outcome } @@ -399,6 +415,13 @@ export function createTools(ctx: Context, runtime: MdhRuntime): MdhToolDefinitio const result = value as { action: string; status?: string; error?: string; runtime?: { version: string | null } } if (result.error) return `Ecosystem ${result.action}: ${result.status ?? 'failed'} — ${textOf(result.error)}` if (result.action === 'status') return `Ecosystem status (runtime ${result.runtime?.version ?? 'not installed'}).` + if (result.action === 'capabilities') { + const capabilities = (result as { + capabilities?: { name: string; kind: string; version: string; enabled_by: string[] }[] + }).capabilities ?? [] + if (capabilities.length === 0) return 'No capability is enabled for this session.' + return capabilities.map(capability => `- ${capability.name} (${capability.kind} ${capability.version}) enabled by ${capability.enabled_by.join(', ')}`).join('\n') + } return `Ecosystem ${result.action}: ${result.status ?? 'done'}` }, }) diff --git a/packages/marqdo/harness/src/web/assets.ts b/packages/marqdo/harness/src/web/assets.ts index bfc1c78123..6a4d099a5e 100644 --- a/packages/marqdo/harness/src/web/assets.ts +++ b/packages/marqdo/harness/src/web/assets.ts @@ -90,6 +90,52 @@ export const APP_HTML = `

固定顺序 Runtime → Tool → Std → Ext → Knowledge。打开、筛选和查看详情不触发下载或执行;有副作用的操作只由按钮显式发起。

+ +
+
+

扩展市场

+

来源聚合视图:浏览与安装不是可信裁决;安装后仍需显式启用,项目锁仍由 CLI 生成。

+
+
+ + + + +
+
+ + + +
+

尚未读取市场。

+
+
+ + +
+ 来源配置(market.json) +

来源只由你在这里或 MQDH_HOME/config/market.json 配置;模型不能添加来源、URL 或条目。删除来源前需先卸载其能力。

+
+
+ + + +
+
+ + + +
+
+ + + +
+ +
+
    +
    +

    安装 / 更新 Runtime

    @@ -241,6 +287,28 @@ 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); } +.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; } +.market-toolbar input, .market-toolbar select { min-width: 11rem; } +.segmented { display: flex; gap: 0.3rem; flex-wrap: wrap; margin: 0.4rem 0 0.6rem; } +.segmented button { background: transparent; color: var(--olive); border-color: var(--line); } +.segmented button[aria-selected="true"] { background: var(--olive); color: #fff; } +.row-button { display: block; width: 100%; text-align: left; background: transparent; border: 0; color: inherit; padding: 0; cursor: pointer; } +.row-button:focus-visible { outline: 2px solid var(--olive); outline-offset: 3px; } +.market .list li { background: #fffdf8; } +.source-config { margin-top: 1rem; } +.source-config summary { cursor: pointer; color: var(--olive); } +.permissions { display: flex; flex-wrap: wrap; gap: 0.3rem; margin: 0.35rem 0; } +.permissions span { font-size: 0.78rem; border: 1px solid var(--line); border-radius: 1rem; padding: 0.05rem 0.45rem; } +@media (prefers-color-scheme: dark) { + :root { --paper: #17181a; --ink: #e8e6e0; --muted: #aaa79f; --olive: #a7bd94; --olive-soft: #2d352a; --line: #3a3b35; --danger: #e08a80; } + body { background: var(--paper); color: var(--ink); } + .top, .card, .form, .group, .list li, .hit, .market, .market .list li { background: #20211e; } + input, select { background: #262722; color: var(--ink); } + .code { background: #0e0f0d; color: #ece9df; } + .market-toolbar input, .market-toolbar select { background: #262722; } +} @media (max-width: 640px) { main { padding: 1rem; } .form.inline { flex-direction: column; align-items: stretch; } @@ -274,7 +342,11 @@ async function api(path, options = {}) { const text = await response.text(); let data = {}; try { data = text ? JSON.parse(text) : {}; } catch { data = { error: text }; } - if (!response.ok) throw new Error(data.error || ('HTTP ' + response.status)); + if (!response.ok) { + const error = new Error(data.error || ('HTTP ' + response.status)); + error.code = data.code || null; + throw error; + } return data; } const short = (value, max = 120) => { @@ -461,7 +533,9 @@ async function loadEcosystem() { project.lock.present ? ('sha256 ' + short(project.lock.digest, 70) + ' · ' + project.lock.size + ' bytes') : '当前工作区没有 marqdo.lock'), catalogRow('锁定状态', '未验证', '应用不解析第二套依赖图;只有显式检查才调用 CLI sync --locked --json', [el('button', { class: 'ghost', type: 'button', text: '检查项目锁', onclick: () => checkProjectLock() })])]; - extRows.push(catalogRow('依赖变更', '项目工作流', '使用 CLI marqdo add 与 marqdo lock 修改项目依赖;应用不提供第三方扩展市场、任意 URL 下载或第二套锁。')); + extRows.push(catalogRow('扩展市场', '来源聚合', '在上方“扩展市场”中浏览、安装与启用;安装写入用户级能力存储,项目导入仍由 CLI add/lock 完成。', + [el('button', { class: 'ghost', type: 'button', text: '打开市场', onclick: () => document.getElementById('market').scrollIntoView({ behavior: 'smooth' }) })])); + extRows.push(catalogRow('依赖变更', '项目工作流', '使用 CLI marqdo add 与 marqdo lock 修改项目依赖;应用不写入项目锁。')); catalog.append(catalogGroup('Ext', '以当前工作区为范围;锁存在不等于运行授权,实际调用仍逐步审批。', extRows)); const enabled = knowledge.collections.filter(collection => collection.enabled).length; @@ -478,44 +552,58 @@ async function loadEcosystem() { async function checkCandidates() { const host = $('#ecosystem-detail'); clear(host); - host.append(el('p', { class: 'muted', text: '正在读取受信任发行元数据…' })); + host.append(el('p', { class: 'muted', text: '正在读取 Runtime 与市场 Tool 候选…' })); try { const data = await api('/ecosystem/candidates'); clear(host); - host.append(el('h3', { text: '受信任发行候选' })); + host.append(el('h3', { text: '候选(Runtime 单列,Tool 来自市场来源)' })); for (const candidate of data.candidates) { if (candidate.error) { - host.append(el('p', { class: 'muted', text: candidate.component + ':' + candidate.error })); + host.append(el('p', { class: 'muted', text: (candidate.kind || candidate.component) + ':' + candidate.error })); continue; } - host.append(el('div', { class: 'hit' }, - el('h3', { text: candidate.component + ' · ' + candidate.tag + (candidate.prerelease ? ' (prerelease)' : '') }), - el('div', { class: 'src', text: candidate.platform + ' · ' + candidate.asset }), - el('div', { class: 'src', text: 'sha256 ' + candidate.sha256 + (candidate.source_sha ? ' · source ' + candidate.source_sha : '') }), - candidate.component === 'cli' - ? el('button', { class: 'ghost', type: 'button', text: '安装此 Runtime(确认)', onclick: async () => { - if (!confirm('安装受信任 Runtime ' + candidate.tag + '?会校验 tag/资产/平台/摘要/Bundle/协议并执行 smoke。')) return; + if (candidate.kind === 'market') { + host.append(el('p', { class: 'muted', text: '市场刷新失败:' + candidate.error })); + continue; + } + const title = candidate.kind === 'runtime' + ? 'Runtime · ' + candidate.tag + (candidate.prerelease ? ' (prerelease)' : '') + : (candidate.name || candidate.id) + ' · ' + candidate.tag + (candidate.channel === 'prerelease' ? ' (prerelease)' : ''); + const detail = candidate.kind === 'runtime' + ? (candidate.platform + ' · ' + candidate.asset) + : ((candidate.source_label || candidate.source_id) + ' · ' + candidate.platform + ' · ' + candidate.asset); + const button = candidate.kind === 'runtime' + ? el('button', { class: 'ghost', type: 'button', text: '安装此 Runtime(确认)', onclick: async () => { + if (!confirm('安装受信任 Runtime ' + candidate.tag + '?会校验 tag/资产/平台/摘要/Bundle/协议并执行 smoke。')) return; + try { + await api('/ecosystem/install', { method: 'POST', body: JSON.stringify({ confirm: true, version: candidate.version }) }); + showError('Runtime 已切换为 ' + candidate.tag); + await loadEcosystem(); + await loadStatus(); + } catch (error) { showError('安装 Runtime 失败:' + error.message); } + } }) + : candidate.availability !== 'available' + ? el('p', { class: 'muted', text: '当前不可安装:' + (candidate.availability || 'unknown') }) + : el('button', { class: 'ghost', type: 'button', text: '安装此 Tool 到能力存储(确认)', onclick: async () => { + if (!confirm('安装市场 Tool ' + candidate.name + ' ' + candidate.tag + '?会校验发行资产与 tool.json,并注册到当前 Runtime 的隔离 Tool home;安装不等于对模型启用。')) return; try { - await api('/ecosystem/install', { method: 'POST', body: JSON.stringify({ confirm: true, version: candidate.version }) }); - showError('Runtime 已切换为 ' + candidate.tag); - await loadEcosystem(); - await loadStatus(); - } catch (error) { showError('安装 Runtime 失败:' + error.message); } - } }) - : el('button', { class: 'ghost', type: 'button', text: '安装此 Tool(确认)', onclick: async () => { - if (!confirm('安装受信任 Tool ' + candidate.component + ' ' + candidate.tag + '?会校验发行资产与 tool.json 后写入当前环境。')) return; - try { - await api('/ecosystem/tool-install-release', { method: 'POST', body: JSON.stringify({ confirm: true, component: candidate.component, version: candidate.version }) }); - showError('Tool ' + candidate.component + ' 已安装'); + await api('/ecosystem/tool-install-release', { method: 'POST', body: JSON.stringify({ confirm: true, key: candidate.key }) }); + showError('Tool ' + candidate.name + ' 已安装到用户级能力存储'); await loadEcosystem(); + await loadMarket(); } catch (error) { showError('安装 Tool 失败:' + error.message); } - } }))); + } }); + host.append(el('div', { class: 'hit' }, + el('h3', { text: title }), + el('div', { class: 'src', text: detail }), + el('div', { class: 'src', text: 'sha256 ' + candidate.sha256 + (candidate.source_sha ? ' · source ' + candidate.source_sha : '') }), + button)); } - host.append(el('p', { class: 'muted', text: '以上读取不会下载或切换环境;安装仍需在表单中显式确认。' })); + host.append(el('p', { class: 'muted', text: '以上读取不会安装或切换环境;安装仍需在按钮中显式确认。Tool 安装后会出现在“扩展市场 → 已安装”,默认不对模型启用。' })); } catch (error) { showError('检查候选失败:' + error.message); } } -async function checkProjectLock() { - const host = $('#ecosystem-detail'); +async function checkProjectLock(selector = '#ecosystem-detail') { + const host = $(selector); clear(host); host.append(el('p', { class: 'muted', text: '正在调用 CLI sync --locked --json…' })); try { @@ -528,6 +616,319 @@ async function checkProjectLock() { } catch (error) { showError('检查项目锁失败:' + error.message); } } +const marketView = { data: null, view: 'market', query: '', source: '', kind: '' }; + +function marketInstalled(key) { + const data = marketView.data; + return data ? data.capabilities.find((capability) => capability.key === key) : undefined; +} + +function marketBadges(entry) { + const badges = el('span'); + badges.append(el('span', { class: 'badge', text: entry.source_label + ' · ' + entry.kind })); + if (entry.channel === 'prerelease') badges.append(el('span', { class: 'badge warn', text: 'prerelease' })); + if (entry.change === 'new') badges.append(el('span', { class: 'badge', text: 'new' })); + if (entry.change === 'changed') badges.append(el('span', { class: 'badge warn', text: 'changed' })); + if (entry.change === 'stale' || entry.availability === 'stale') badges.append(el('span', { class: 'badge warn', text: 'stale' })); + if (entry.availability === 'unavailable') badges.append(el('span', { class: 'badge warn', text: '不可用' })); + const installed = marketInstalled(entry.key); + if (installed) { + badges.append(el('span', { class: 'badge', text: '已安装 ' + (installed.active_version || '未激活') })); + if (installed.update_available) badges.append(el('span', { class: 'badge warn', text: '可更新 ' + installed.latest_version })); + } + return badges; +} + +async function loadMarket() { + const state = $('#market-state'); + if (state) state.textContent = '正在读取市场索引…'; + try { + marketView.data = await api('/market'); + renderMarket(); + } catch (error) { + if (state) state.textContent = '读取市场失败:' + error.message; + } +} + +function renderMarket() { + const data = marketView.data; + if (!data) return; + const sourceSelect = $('#market-source'); + const kindSelect = $('#market-kind'); + if (sourceSelect) { + const selected = marketView.source; + while (sourceSelect.options.length > 1) sourceSelect.remove(1); + for (const source of data.config.sources) { + sourceSelect.append(el('option', { value: source.id, text: source.label + ' (' + source.id + ')' })); + } + sourceSelect.value = data.config.sources.some((source) => source.id === selected) ? selected : ''; + marketView.source = sourceSelect.value; + } + if (kindSelect) kindSelect.value = marketView.kind; + const generated = data.index.generated_at && !data.index.generated_at.startsWith('1970') ? data.index.generated_at : '尚未刷新'; + const states = data.index.sources.map((source) => source.id + ':' + source.status + (source.error ? ' (' + short(source.error, 100) + ')' : '')).join(' · '); + const state = $('#market-state'); + if (state) { + state.textContent = '索引 ' + generated + ' · ' + data.index.entries.length + ' 个条目 · 已安装 ' + data.capabilities.length + ' 个 · ' + (states || '无来源') + (data.config.offline ? ' · 离线' : ''); + } + const sources = $('#market-sources'); + if (sources) { + clear(sources); + for (const source of data.config.sources) { + const remove = el('button', { class: 'danger', type: 'button', text: '移除来源', onclick: async () => { + if (!confirm('移除来源 ' + source.id + '?该来源的已安装能力必须先卸载。')) return; + try { + await api('/market/sources/remove', { method: 'POST', body: JSON.stringify({ confirm: true, id: source.id }) }); + await loadMarket(); + } catch (error) { showError('移除来源失败:' + error.message); } + } }); + sources.append(el('li', {}, + el('div', { class: 'row' }, + el('div', {}, + el('strong', { text: source.label + ' · ' + source.kind }), + el('div', { class: 'muted', text: source.kind === 'gitea' + ? ('base ' + (source.base || '') + ' · topics ' + (source.topics.join(', ') || '无') + ' · owners ' + (source.owners.join(', ') || '无')) + : ('path ' + (source.path || '')) }), + ), + remove, + ))); + } + if (data.config.sources.length === 0) sources.append(el('li', {}, el('span', { class: 'muted', text: '尚无来源;默认官方来源在首次读取时由发行源生成。' }))); + } + const list = $('#market-list'); + const installedHost = $('#market-installed'); + const projectHost = $('#market-project'); + if (!list || !installedHost || !projectHost) return; + list.hidden = marketView.view !== 'market'; + $('#market-detail').hidden = marketView.view !== 'market'; + installedHost.hidden = marketView.view !== 'installed'; + projectHost.hidden = marketView.view !== 'project'; + document.querySelectorAll('[data-market-view]').forEach((button) => { + button.setAttribute('aria-selected', String(button.dataset.marketView === marketView.view)); + }); + if (marketView.view === 'installed') { renderInstalled(); return; } + if (marketView.view === 'project') { renderMarketProject(); return; } + renderMarketList(); +} + +function renderMarketList() { + const list = $('#market-list'); + const data = marketView.data; + if (!list || !data) return; + clear(list); + const query = marketView.query.trim().toLowerCase(); + const configured = new Set(data.config.sources.map((source) => source.id)); + const entries = data.index.entries.filter((entry) => { + if (!configured.has(entry.source_id)) return false; + if (marketView.source !== '' && entry.source_id !== marketView.source) return false; + if (marketView.kind !== '' && entry.kind !== marketView.kind) return false; + if (query === '') return true; + return [entry.name, entry.id, entry.summary, entry.version, entry.source_label, entry.publisher || ''] + .join(' ').toLowerCase().includes(query); + }); + if (entries.length === 0) { + list.append(el('li', {}, el('span', { class: 'muted', text: data.index.entries.length === 0 ? '市场索引为空。点击“刷新市场”读取已配置来源;离线目录来源也会在同一刷新中出现。' : '没有匹配条目。' }))); + return; + } + for (const entry of entries) { + const button = el('button', { class: 'row-button', type: 'button' }, + el('strong', { text: entry.name + ' · ' + entry.version }), + marketBadges(entry), + el('p', { class: 'muted', text: (entry.summary || '无摘要') + ' · ' + entry.id }), + ); + button.addEventListener('click', () => showMarketEntry(entry)); + list.append(el('li', {}, button)); + } +} + +function showMarketEntry(entry) { + const host = $('#market-detail'); + if (!host) return; + clear(host); + const card = el('div', { class: 'hit' }); + card.append(el('h3', { text: entry.name + ' · ' + entry.version })); + card.append(el('div', { class: 'src', text: entry.source_label + ' / ' + entry.kind + ' / ' + entry.id + ' · sha256 ' + entry.asset.sha256 })); + card.append(el('p', { text: entry.summary || '无摘要' })); + if (entry.description) card.append(el('pre', { text: entry.description })); + card.append(el('p', { class: 'muted', text: '版本 ' + entry.version + ' · 平台 ' + (entry.platform || '未声明') + ' · 资产 ' + entry.asset.name + ' · ' + (entry.asset.size === null ? '大小未声明' : entry.asset.size + ' bytes') + ' · 来源 SHA ' + (entry.source_sha || '未声明') })); + card.append(el('p', { class: 'muted', text: '发布者 ' + (entry.publisher || '未声明') + ' · 签名 ' + (entry.signature.status === 'present' ? (entry.signature.algorithm + ' / ' + entry.signature.key_id + '(未做中央信任裁决)') : 'unsigned(未提供签名,不影响安装)') })); + card.append(el('p', { class: 'muted', text: '需要 CLI ' + (entry.manifest.min_cli || '未声明') + ' · 协议 ' + (entry.manifest.min_protocol || '未声明') })); + const permissions = el('div', { class: 'permissions' }); + const declared = [...entry.manifest.permissions, ...entry.manifest.effects, ...entry.manifest.capabilities]; + if (declared.length === 0) permissions.append(el('span', { text: '未声明权限/能力' })); + for (const item of declared) permissions.append(el('span', { text: item })); + card.append(permissions); + if (entry.manifest.tools.length > 0) card.append(el('p', { class: 'muted', text: '声明的工具:' + entry.manifest.tools.join(', ') })); + if (entry.manifest.build && entry.manifest.build.required) { + card.append(el('p', { class: 'badge warn', text: '安装/构建提示:该条目声明需要构建源码或安装脚本;安装前会再次询问是否执行声明的构建命令。' })); + if (entry.manifest.build.instructions) card.append(el('p', { class: 'muted', text: entry.manifest.build.instructions })); + } + if (entry.risk) card.append(el('p', { class: 'muted', text: '已知风险:' + entry.risk })); + for (const limitation of entry.known_limitations) card.append(el('p', { class: 'muted', text: '已知限制:' + limitation })); + if (entry.availability !== 'available') { + card.append(el('p', { class: 'muted', text: '当前不可安装:' + (entry.unavailable_reason || entry.availability) })); + } else { + const installed = marketInstalled(entry.key); + const same = installed && installed.versions.some((version) => version.sha256 === entry.asset.sha256); + if (same) { + card.append(el('p', { class: 'muted', text: '该版本已安装。安装不等于启用;请在“已安装”中显式激活并授权作用域。' })); + } else { + const button = el('button', { type: 'button', text: installed ? '安装新版本(不自动切换)' : '安装到用户级能力存储' }); + button.addEventListener('click', async () => { + if (!confirm('安装 ' + entry.name + ' ' + entry.version + '?会校验摘要、大小、解包路径与清单;安装不等于执行授权。')) return; + let allowBuild = false; + if (entry.manifest.build && entry.manifest.build.required) { + allowBuild = confirm('该条目声明需要构建或安装脚本。是否在安装时执行声明的构建命令?取消则仅解包,稍后需要手动处理。'); + } + button.disabled = true; + try { + const result = await api('/market/install', { method: 'POST', body: JSON.stringify({ confirm: true, key: entry.key, allow_build: allowBuild }) }); + let message = '已安装 ' + result.version.version; + if (result.requires_build) message += ';需要构建,尚未激活'; + if (result.pending_activation) message += ';新版本已安装,旧版本仍激活,请在“已安装”中显式切换'; + await loadMarket(); + await loadEcosystem(); + await loadStatus(); + showError(message); + } catch (error) { showError('安装失败:' + error.message); } + finally { button.disabled = false; } + }); + card.append(button); + } + } + if (entry.browser_url) card.append(el('p', { class: 'muted', text: '来源页面:' + entry.browser_url })); + host.append(card); +} + +function renderInstalled() { + const host = $('#market-installed'); + const data = marketView.data; + if (!host || !data) return; + clear(host); + host.append(el('h3', { text: '已安装能力' })); + if (data.capabilities.length === 0) { + host.append(el('p', { class: 'muted', text: '尚未安装市场条目。安装写入用户级能力存储,模型默认不可见。' })); + return; + } + for (const capability of data.capabilities) { + const card = el('div', { class: 'hit' }); + const badges = el('span'); + badges.append(el('span', { class: 'badge' + (capability.ready ? '' : ' warn'), text: capability.ready ? '就绪' : '未就绪' })); + if (capability.build_required) badges.append(el('span', { class: 'badge warn', text: '需要构建' })); + if (capability.update_available) badges.append(el('span', { class: 'badge warn', text: '可更新 ' + capability.latest_version })); + card.append(el('h3', { text: capability.name + ' · ' + capability.kind }), badges); + card.append(el('div', { class: 'src', text: capability.source_label + ' / ' + capability.id + ' · active ' + (capability.active_version || '无') + ' · ' + capability.active_path })); + if (capability.command) card.append(el('p', { class: 'muted', text: 'Tool 命令:' + capability.command })); + if (capability.project_references.length > 0) card.append(el('p', { class: 'muted', text: '项目引用:' + capability.project_references.join(', ') + '(卸载前需先移除依赖)' })); + const versions = el('div', { class: 'row' }); + for (const version of capability.versions) { + versions.append(el('button', { class: 'ghost', type: 'button', text: (version.active ? '当前 ' : '切换到 ') + version.version, onclick: async () => { + if (!confirm('激活版本 ' + version.version + '?Tool 会重新注册到当前 Runtime;已启用作用域保持。')) return; + try { + await api('/market/activate', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key, sha256: version.sha256 }) }); + await loadMarket(); + await loadEcosystem(); + } catch (error) { showError('激活失败:' + error.message); } + } })); + } + card.append(versions); + const scopes = capability.enabled.length === 0 ? '未启用(模型不可见)' : capability.enabled.map((scope) => scope.kind + (scope.id ? ':' + short(scope.id, 24) : '')).join(', '); + card.append(el('p', { class: 'muted', text: '启用作用域:' + scopes })); + const actions = el('div', { class: 'row' }); + actions.append(el('button', { class: 'ghost', type: 'button', text: '启用:全局', onclick: async () => { + if (!confirm('让所有会话的模型都看到该能力?每次调用仍需审批。')) return; + try { await api('/market/enable', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key, scope: 'global' }) }); await loadMarket(); } + catch (error) { showError('启用失败:' + error.message); } + } })); + actions.append(el('button', { class: 'ghost', type: 'button', text: '启用:当前项目', onclick: async () => { + if (!confirm('只在当前项目作用域启用?')) return; + try { await api('/market/enable', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key, scope: 'project' }) }); await loadMarket(); } + catch (error) { showError('启用失败:' + error.message); } + } })); + actions.append(el('button', { class: 'ghost', type: 'button', text: '启用:会话…', onclick: async () => { + const id = prompt('会话/智能体 id'); + if (!id) return; + try { await api('/market/enable', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key, scope: 'session', id }) }); await loadMarket(); } + catch (error) { showError('启用失败:' + error.message); } + } })); + actions.append(el('button', { class: 'ghost', type: 'button', text: '撤销全部启用', onclick: async () => { + try { await api('/market/disable', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key }) }); await loadMarket(); } + catch (error) { showError('撤销失败:' + error.message); } + } })); + if (capability.kind === 'ext') actions.append(el('button', { class: 'ghost', type: 'button', text: '导入项目(CLI add)', onclick: async () => { + const alias = prompt('依赖别名', capability.id); + if (!alias) return; + if (!confirm('由 CLI 写入 marqdo.yaml:' + alias + ' -> marqdo-vendor/' + alias + '(项目内副本)?应用不写锁,随后需显式运行 marqdo lock。')) return; + try { + const result = await api('/market/import', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key, alias }) }); + await loadMarket(); + await loadEcosystem(); + showError('已由 CLI 导入 ' + result.alias + ';下一步:' + result.next); + } catch (error) { showError('导入失败:' + error.message); } + } })); + const remove = el('button', { class: 'danger', type: 'button', text: '卸载', onclick: async () => { + if (!confirm('卸载该能力的全部已安装版本?被项目引用时会被拒绝。')) return; + try { + await api('/market/uninstall', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key }) }); + await loadMarket(); + await loadEcosystem(); + } catch (error) { + if (error.code === 'extension.project_referenced' && confirm(error.message + ' 仍要强制卸载?')) { + try { + await api('/market/uninstall', { method: 'POST', body: JSON.stringify({ confirm: true, key: capability.key, force: true }) }); + await loadMarket(); + await loadEcosystem(); + return; + } catch (forced) { showError('强制卸载失败:' + forced.message); return; } + } + showError('卸载失败:' + error.message); + } + } }); + actions.append(remove); + card.append(actions); + host.append(card); + } +} + +function renderMarketProject() { + const host = $('#market-project'); + const data = marketView.data; + if (!host || !data) return; + clear(host); + host.append(el('h3', { text: '当前项目与锁' })); + const project = data.project; + host.append(el('p', { class: 'muted', text: '工作区 ' + project.workspace + ' · 项目作用域 ' + data.project_digest })); + host.append(el('p', { text: 'marqdo.yaml:' + (project.manifest.present ? project.manifest.digest : '缺失') })); + 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 + ')'); + } + host.append(el('p', { class: 'muted', text: imports.length === 0 ? '尚无应用记录的导入。' : '应用记录的导入:' + imports.join(';') })); + host.append(el('p', { class: 'muted', text: '锁由 CLI 生成与校验;应用不解析第二套依赖图,也不把锁当作运行授权。' })); + const row = el('div', { class: 'row' }); + row.append(el('button', { class: 'ghost', type: 'button', text: '检查项目锁(CLI sync --locked)', onclick: async () => { + const target = $('#market-detail'); + if (target) target.scrollIntoView({ behavior: 'smooth' }); + await checkProjectLock('#market-detail'); + } })); + row.append(el('button', { type: 'button', text: '生成项目锁(CLI lock)', onclick: async () => { + if (!confirm('运行 CLI marqdo lock --json?锁只由 CLI 生成。')) return; + try { + const result = await api('/market/lock', { method: 'POST', body: JSON.stringify({ confirm: true }) }); + const target = $('#market-detail'); + if (target) { + clear(target); + target.append(el('h3', { text: 'CLI lock 完成' })); + target.append(el('pre', { class: 'code', text: JSON.stringify(result.result, null, 2) })); + } + await loadMarket(); + await loadEcosystem(); + } catch (error) { showError('生成锁失败:' + error.message); } + } })); + host.append(row); +} + async function loadRuns() { try { const data = await api('/runs'); @@ -653,7 +1054,7 @@ async function loadNetwork() { summary.append(el('p', { class: 'big', text: '发行源 ' + config.release_authority })); summary.append(el('p', { class: 'muted', text: 'Issue 端点 ' + config.issue_endpoint + ' · offline=' + String(config.offline) + ' · 镜像 ' + (config.mirrors.length ? config.mirrors.join(', ') : '无') })); summary.append(el('p', { class: 'muted', text: '代理 https=' + String(config.proxy_https) + ' http=' + String(config.proxy_http) + ' · NO_PROXY ' + config.no_proxy_entries + ' 项 · 允许的额外 host ' + config.allowed_hosts.join(', ') })); - $('#network-audit').textContent = data.recent.map((entry) => entry.at + ' ' + entry.purpose + ' ' + entry.authority + ' ' + entry.outcome + ' ' + (entry.status === null ? '-' : entry.status) + ' ' + entry.bytes + 'B' + (entry.mirror ? ' mirror' : '')).join('\n') || '尚无出口记录'; + $('#network-audit').textContent = data.recent.map((entry) => entry.at + ' ' + entry.purpose + ' ' + entry.authority + ' ' + entry.outcome + ' ' + (entry.status === null ? '-' : entry.status) + ' ' + entry.bytes + 'B' + (entry.mirror ? ' mirror' : '')).join('\\n') || '尚无出口记录'; } catch (error) { showError('读取出口状态失败:' + error.message); } } async function loadReports() { @@ -710,18 +1111,81 @@ async function openReport(id) { } function bind() { - document.querySelectorAll('[role="tab"]').forEach((button) => { + document.querySelectorAll('[role="tab"][data-tab]').forEach((button) => { button.addEventListener('click', () => { - document.querySelectorAll('[role="tab"]').forEach((other) => { + document.querySelectorAll('[role="tab"][data-tab]').forEach((other) => { other.setAttribute('aria-selected', String(other === button)); document.getElementById('tab-' + other.dataset.tab).hidden = other !== button; }); const tab = button.dataset.tab; + if (tab === 'ecosystem') { loadEcosystem(); loadMarket(); } if (tab === 'bootstrap') loadBootstrap(); if (tab === 'update') { loadUpdate(); loadNetwork(); } if (tab === 'reports') loadReports(); }); }); + document.querySelectorAll('[data-market-view]').forEach((button) => { + button.addEventListener('click', () => { + marketView.view = button.dataset.marketView || 'market'; + clear($('#market-detail')); + renderMarket(); + }); + }); + const marketSearch = $('#market-search'); + if (marketSearch) marketSearch.addEventListener('input', (event) => { + marketView.query = event.target.value; + renderMarket(); + }); + const marketSource = $('#market-source'); + if (marketSource) marketSource.addEventListener('change', (event) => { + marketView.source = event.target.value; + renderMarket(); + }); + const marketKind = $('#market-kind'); + if (marketKind) marketKind.addEventListener('change', (event) => { + marketView.kind = event.target.value; + renderMarket(); + }); + const marketRefresh = $('#market-refresh'); + if (marketRefresh) marketRefresh.addEventListener('click', async () => { + if (!confirm('刷新会访问已配置的市场来源(离线模式只读取本地目录),不会自动安装或执行任何条目。')) return; + marketRefresh.disabled = true; + try { + await api('/market/refresh', { method: 'POST', body: JSON.stringify({ confirm: true }) }); + await loadMarket(); + } catch (error) { showError('刷新失败:' + error.message); } + finally { marketRefresh.disabled = false; } + }); + const sourceForm = $('#market-source-form'); + if (sourceForm) sourceForm.addEventListener('submit', async (event) => { + event.preventDefault(); + const form = new FormData(event.target); + const split = (value) => String(value || '').split(',').map((item) => item.trim()).filter((item) => item !== ''); + const kind = String(form.get('kind') || 'gitea'); + const source = { + id: String(form.get('id') || '').trim(), + kind, + label: String(form.get('label') || '').trim() || undefined, + ...(kind === 'gitea' + ? { + base: String(form.get('base') || '').trim() || undefined, + owners: split(form.get('owners')), + topics: split(form.get('topics')), + repositories: split(form.get('repositories')), + default_kind: String(form.get('default_kind') || '') || undefined, + } + : { path: String(form.get('path') || '').trim() }), + }; + if (source.label === undefined) delete source.label; + if (source.base === undefined) delete source.base; + if (source.default_kind === undefined) delete source.default_kind; + if (!confirm('添加来源 ' + source.id + '?来源会进入 0600 的 market.json,刷新时才会访问。')) return; + try { + await api('/market/sources', { method: 'POST', body: JSON.stringify({ confirm: true, source }) }); + event.target.reset(); + await loadMarket(); + } catch (error) { showError('添加来源失败:' + error.message); } + }); $('#create-collection').addEventListener('submit', async (event) => { event.preventDefault(); const form = new FormData(event.target); @@ -820,8 +1284,7 @@ function bind() { $('#network-check').addEventListener('click', async () => { try { const result = await api('/network/check', { method: 'POST', body: JSON.stringify({}) }); - $('#network-audit').textContent = result.probes.map((probe) => probe.purpose + ': ' + probe.code + (probe.status === null ? '' : (' HTTP ' + probe.status)) + ' — ' + probe.reason).join(' -'); + $('#network-audit').textContent = result.probes.map((probe) => probe.purpose + ': ' + probe.code + (probe.status === null ? '' : (' HTTP ' + probe.status)) + ' — ' + probe.reason).join('\\n'); } catch (error) { showError('探测失败:' + error.message); } }); $('#load-diagnostics').addEventListener('click', async () => { @@ -841,5 +1304,6 @@ bind(); loadStatus(); loadCollections(); loadEcosystem(); +loadMarket(); loadRuns(); ` diff --git a/packages/marqdo/harness/src/web/index.ts b/packages/marqdo/harness/src/web/index.ts index 534b45385b..6b87e7d705 100644 --- a/packages/marqdo/harness/src/web/index.ts +++ b/packages/marqdo/harness/src/web/index.ts @@ -17,6 +17,8 @@ import type { MdhRuntime } from '../runtime.ts' import { NETWORK_PURPOSES } from '../network/policy.ts' 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 { runProcess } from '../core/process.ts' import { APP_CSS, APP_HTML, APP_JS } from './assets.ts' import { isLoopbackAuthority, isTrustedAuthority } from './trust.ts' @@ -67,7 +69,7 @@ async function readJson(req: IncomingMessage, maxBytes = 1024 * 1024): Promise } catch { @@ -150,6 +152,7 @@ function registerRoutes( await handleApi(req, res, pathname.slice('/mqdh/api'.length), url, runtime) } 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 } const message = error instanceof Error ? error.message : String(error) const path = req.url ?? '' const area: DiagnosticArea = path.startsWith('/mqdh/api/knowledge') ? 'knowledge' @@ -299,26 +302,165 @@ async function handleApi( }) return } + if (path === '/market' && method === 'GET') { + const config = await runtime.market.config() + json(res, 200, { + config: { + sources: config.sources.map(source => ({ + id: source.id, + kind: source.kind, + label: source.label, + base: source.base, + path: source.path, + owners: source.owners, + topics: source.topics, + repositories: source.repositories, + default_kind: source.default_kind, + })), + cache_ttl_ms: config.cache_ttl_ms, + offline: config.offline, + }, + index: await runtime.market.current(), + capabilities: await runtime.capabilities.capabilities(), + events: await runtime.market.events(20), + project: await runtime.projectDependencies(), + project_digest: runtime.capabilities.projectDigest(), + }) + return + } + if (path === '/market/refresh' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'market refresh requires explicit confirmation') + json(res, 200, { index: await runtime.market.refresh({ force: true }) }) + return + } + if (path === '/market/install' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'market install requires explicit confirmation') + const key = stringField(body, 'key') + json(res, 200, await runtime.capabilities.install(key, { allowBuild: body.allow_build === true })) + return + } + if (path === '/market/activate' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'activation requires explicit confirmation') + const key = stringField(body, 'key') + const sha256 = typeof body.sha256 === 'string' && body.sha256.trim() !== '' ? body.sha256.trim() : undefined + json(res, 200, { capability: await runtime.capabilities.activate(key, sha256) }) + return + } + if (path === '/market/uninstall' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'uninstall requires explicit confirmation') + const key = stringField(body, 'key') + json(res, 200, await runtime.capabilities.uninstall(key, { force: body.force === true })) + return + } + if (path === '/market/enable' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'enabling a capability requires explicit confirmation') + const key = stringField(body, 'key') + const scope = body.scope + if (scope !== 'global' && scope !== 'session' && scope !== 'project') { + throw new HttpError(400, 'scope must be global, session or project') + } + const id = typeof body.id === 'string' && body.id.trim() !== '' ? body.id.trim() : undefined + json(res, 200, { capability: await runtime.capabilities.enable(key, { kind: scope, id }) }) + return + } + if (path === '/market/disable' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'disabling a capability requires explicit confirmation') + const key = stringField(body, 'key') + if (body.scope === undefined) { + json(res, 200, { capability: await runtime.capabilities.disable(key) }) + return + } + if (body.scope !== 'global' && body.scope !== 'session' && body.scope !== 'project') { + throw new HttpError(400, 'scope must be global, session or project') + } + const id = typeof body.id === 'string' && body.id.trim() !== '' ? body.id.trim() : undefined + json(res, 200, { capability: await runtime.capabilities.disable(key, { kind: body.scope, id }) }) + return + } + if (path === '/market/import' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'project import requires explicit confirmation') + const key = stringField(body, 'key') + const alias = typeof body.alias === 'string' && body.alias.trim() !== '' ? body.alias.trim() : undefined + json(res, 200, await runtime.capabilities.importToProject(key, { alias })) + return + } + if (path === '/market/lock' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'project lock requires explicit confirmation') + json(res, 200, await runtime.capabilities.lockProject()) + return + } + if (path === '/market/sources' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'adding a market source requires explicit confirmation') + const source = parseSourceConfig(body.source) + json(res, 201, { config: await runtime.market.addSource(source) }) + return + } + if (path === '/market/sources/remove' && method === 'POST') { + const body = await readJson(req) + if (body.confirm !== true) throw new HttpError(400, 'removing a market source requires explicit confirmation') + const id = stringField(body, 'id') + const installed = await runtime.capabilities.installedSourceIds() + if (installed.includes(id)) { + throw new MarketError('market.source_in_use', `uninstall capabilities from source ${id} before removing it`) + } + json(res, 200, { config: await runtime.market.removeSource(id) }) + return + } + if (path === '/market/events' && method === 'GET') { + json(res, 200, { events: await runtime.market.events(50) }) + return + } if (path === '/ecosystem/candidates' && method === 'GET') { - const components = ['cli', 'knowledge', 'view', 'lint', 'prove'] as const - const candidates = [] - for (const component of components) { - try { - const candidate = await discoverRelease(component, { network: runtime.network }) + const candidates: Record[] = [] + try { + const candidate = await discoverRelease('cli', { network: runtime.network }) + candidates.push({ + kind: 'runtime', + component: 'cli', + tag: candidate.tag, + version: candidate.tag.replace(/^v/, ''), + prerelease: candidate.prerelease, + platform: candidate.platform, + asset: candidate.assetName, + sha256: candidate.assetSha256, + source_sha: candidate.sourceSha, + browser_url: candidate.browserUrl, + }) + } catch (error) { + candidates.push({ kind: 'runtime', component: 'cli', error: error instanceof Error ? error.message : String(error) }) + } + try { + const index = await runtime.market.refresh({ force: true }) + for (const entry of index.entries.filter(candidate => candidate.kind === 'tool')) { candidates.push({ - component, - tag: candidate.tag, - version: candidate.tag.replace(/^v/, ''), - prerelease: candidate.prerelease, - platform: candidate.platform, - asset: candidate.assetName, - sha256: candidate.assetSha256, - source_sha: candidate.sourceSha, - browser_url: candidate.browserUrl, + kind: 'tool', + key: entry.key, + id: entry.id, + name: entry.name, + tag: entry.version, + version: entry.version, + channel: entry.channel, + platform: entry.platform, + asset: entry.asset.name, + sha256: entry.asset.sha256, + source_sha: entry.source_sha, + source_id: entry.source_id, + source_label: entry.source_label, + browser_url: entry.browser_url, + availability: entry.availability, }) - } catch (error) { - candidates.push({ component, error: error instanceof Error ? error.message : String(error) }) } + } catch (error) { + candidates.push({ kind: 'market', error: error instanceof Error ? error.message : String(error) }) } json(res, 200, { candidates }) return @@ -326,14 +468,8 @@ async function handleApi( if (path === '/ecosystem/tool-install-release' && method === 'POST') { const body = await readJson(req) if (body.confirm !== true) throw new HttpError(400, 'tool installation requires explicit confirmation') - const component = body.component - if (component !== 'knowledge' && component !== 'view' && component !== 'lint' && component !== 'prove') { - throw new HttpError(400, 'component must be knowledge, view, lint or prove') - } - const version = typeof body.version === 'string' && body.version.trim() !== '' ? body.version.trim() : undefined - json(res, 200, await runtime.ecosystem.installToolFromRelease(component, { - ...(version === undefined ? {} : { version }), - })) + const key = stringField(body, 'key') + json(res, 200, await runtime.capabilities.install(key)) return } if (path === '/ecosystem/project-check' && method === 'POST') { diff --git a/packages/marqdo/harness/tests/bundle.test.ts b/packages/marqdo/harness/tests/bundle.test.ts index 42fac3a57a..2f0aea013c 100644 --- a/packages/marqdo/harness/tests/bundle.test.ts +++ b/packages/marqdo/harness/tests/bundle.test.ts @@ -30,7 +30,7 @@ function compose(): { id: string; disabled?: boolean; config?: Record undefined) as unknown as { data: unknown[] } + const result = applyEntryPatches(tree as never, patches as never, () => undefined) as { data: unknown[] } tree = result.data } return tree as never diff --git a/packages/marqdo/harness/tests/market.test.ts b/packages/marqdo/harness/tests/market.test.ts new file mode 100644 index 0000000000..8deb5c82a3 --- /dev/null +++ b/packages/marqdo/harness/tests/market.test.ts @@ -0,0 +1,406 @@ +/** + * Market discovery, capability lifecycle and project-import gate tests. + * + * These use a real local directory source and real `.tar.gz` archives. No + * network is required; Gitea discovery is exercised separately over HTTP in the + * evidence run. + */ + +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { readdirSync } from 'node:fs' +import { copyFile, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { test } from 'node:test' +import vm from 'node:vm' + +import { chmod } from 'node:fs/promises' +import { ensureMdhHome } from '../src/core/home.ts' +import { digestFile, writeJsonAtomic } from '../src/core/fsx.ts' +import { EgressClient } from '../src/network/client.ts' +import { defaultMarketConfig, parseMarketConfig } from '../src/market/config.ts' +import type { MarketSourceConfig } from '../src/market/config.ts' +import { MarketIndexService } from '../src/market/index.ts' +import { CapabilityStore } from '../src/market/capabilities.ts' +import type { MarqdoCli } from '../src/execution/cli.ts' +import { EvidenceStore } from '../src/execution/evidence.ts' +import { MARKET_ERROR, MarketError } from '../src/market/errors.ts' +import { APP_JS, APP_HTML } from '../src/web/assets.ts' + +interface Fixture { + readonly home: string + readonly workspace: string + readonly source: string + readonly network: EgressClient + readonly market: MarketIndexService + readonly capabilities: CapabilityStore + readonly sourceConfig: MarketSourceConfig +} + +/** Create one archive from a directory using the platform tar. */ +async function archiveOf(directory: string, archive: string, symlinks: string[] = []): Promise { + for (const name of symlinks) { + await symlink('/etc/passwd', join(directory, name)) + } + execFileSync('tar', ['-czf', archive, '-C', directory, ...readdirSync(directory)], { stdio: 'pipe' }) +} + +/** Build one directory-market fixture with a single ext entry. */ +async function fixture(options: { build?: boolean; version?: string; symlink?: boolean } = {}): Promise { + const root = await mkdtemp(join(tmpdir(), 'mqdh-market-')) + const layout = await ensureMdhHome(join(root, 'home')) + const workspace = join(root, 'workspace') + await mkdir(workspace, { recursive: true }) + const source = join(root, 'source') + await mkdir(source, { recursive: true }) + const packageDir = join(root, 'package') + await mkdir(join(packageDir, 'adapter'), { recursive: true }) + await writeFile(join(packageDir, 'adapter', 'plugin.yaml'), 'name: demo\n') + await writeFile(join(packageDir, 'index.mq.md'), '## @exec main\n\n`return 1`\n') + const version = options.version ?? '0.1.0' + const archiveName = `demo-${version}.tar.gz` + await archiveOf(packageDir, join(source, archiveName), options.symlink === true ? ['link.txt'] : []) + const entry: Record = { + kind: 'ext', + id: 'demo', + name: 'Demo extension', + summary: 'A fixture extension', + version, + asset: { name: archiveName, path: archiveName }, + manifest: { + mechanisms: ['plugin'], + capabilities: ['demo.run'], + permissions: ['read:demo'], + effects: ['filesystem.read'], + ...(options.build === true + ? { build: { required: true, command: ['/bin/sh', '-c', 'printf built > built.txt'] } } + : {}), + }, + } + const indexPath = join(source, 'index.json') + const writeIndex = async (entries: unknown[]): Promise => { + await writeJsonAtomic(indexPath, { + schema: 'marqdo.mqdh.market.directory', + schema_version: 1, + entries, + }) + } + await writeIndex([entry]) + const sourceConfig: MarketSourceConfig = { + id: 'local', kind: 'directory', label: 'Local', base: null, + owners: [], topics: [], repositories: [], path: source, default_kind: null, + } + await writeJsonAtomic(join(layout.config, 'market.json'), { + schema: 'marqdo.mqdh.market', schema_version: 1, + sources: [{ id: 'local', kind: 'directory', label: 'Local', path: source }], + cache_ttl_ms: 300000, + offline: false, + }) + const network = await EgressClient.open(layout, { audit: false }) + const market = new MarketIndexService(layout, network) + const capabilities = new CapabilityStore({ + layout, + network, + market, + cli: async () => undefined, + toolHome: async () => undefined, + workspace: () => workspace, + }) + return { home: layout.home, workspace, source, network, market, capabilities, sourceConfig } +} + +/** Write one directory index entry with an explicit payload version. */ +async function rewriteEntry(f: Fixture, entry: Record): Promise { + await writeJsonAtomic(join(f.source, 'index.json'), { + schema: 'marqdo.mqdh.market.directory', + schema_version: 1, + entries: [entry], + }) +} + +/** Remove a fixture root. */ +async function cleanup(root: string): Promise { + await rm(root, { recursive: true, force: true }) +} + +test('default market configuration names only a dynamic official source', () => { + const config = defaultMarketConfig('https://git.cflmy.cn') + assert.equal(config.sources.length, 1) + assert.equal(config.sources[0]?.id, 'official') + assert.deepEqual(config.sources[0]?.topics, ['marqdo-ext', 'marqdo-tool']) + assert.equal(config.sources[0]?.owners[0], 'cflmy') +}) + +test('market configuration rejects duplicates, unknown keys and relative directories', () => { + assert.throws(() => parseMarketConfig({ + schema: 'marqdo.mqdh.market', schema_version: 1, + sources: [ + { id: 'local', kind: 'directory', path: '/tmp/a' }, + { id: 'local', kind: 'directory', path: '/tmp/b' }, + ], + cache_ttl_ms: 300000, + offline: false, + }), (error: unknown) => error instanceof MarketError && error.code === MARKET_ERROR.sourceDuplicate) + assert.throws(() => parseMarketConfig({ + schema: 'marqdo.mqdh.market', schema_version: 1, + sources: [{ id: 'local', kind: 'directory', path: 'relative' }], + cache_ttl_ms: 300000, + offline: false, + extra: true, + }), (error: unknown) => error instanceof MarketError && error.code === MARKET_ERROR.configInvalid) +}) + +test('directory discovery, caching and new/changed/stale transitions are explicit', async () => { + const f = await fixture() + try { + const first = await f.market.refresh({ force: true }) + assert.equal(first.entries.length, 1) + assert.equal(first.entries[0]?.change, 'new') + assert.equal(first.sources[0]?.status, 'ok') + assert.match(first.config_digest, /^sha256:[0-9a-f]{64}$/) + const cached = await f.market.refresh() + assert.equal(cached.generated_at, first.generated_at) + const changed = await f.market.refresh({ force: true }) + assert.equal(changed.entries[0]?.change, 'unchanged') + assert.equal((await f.market.events()).length, 1) + + const archive = 'demo-0.2.0.tar.gz' + await archiveOf(join(f.home, '..', 'package'), join(f.source, archive)) + await rewriteEntry(f, { + kind: 'ext', id: 'demo', name: 'Demo extension', summary: 'changed', version: '0.2.0', + asset: { name: archive, path: archive }, + manifest: { capabilities: ['demo.run'] }, + }) + const updated = await f.market.refresh({ force: true }) + assert.equal(updated.entries[0]?.version, '0.2.0') + assert.equal(updated.entries[0]?.change, 'changed') + + await writeJsonAtomic(join(f.source, 'index.json'), { + schema: 'marqdo.mqdh.market.directory', schema_version: 1, entries: [], + }) + const removed = await f.market.refresh({ force: true }) + assert.equal(removed.entries[0]?.change, 'stale') + assert.equal(removed.entries[0]?.availability, 'stale') + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('installed capability is invisible until the user enables a scope', async () => { + const f = await fixture() + try { + const index = await f.market.refresh({ force: true }) + const key = index.entries[0]?.key + assert.ok(key) + const installed = await f.capabilities.install(key) + assert.equal(installed.requires_build, false) + assert.equal(installed.capability.ready, true) + assert.equal(installed.capability.enabled.length, 0) + assert.deepEqual(await f.capabilities.visible(null), []) + + await f.capabilities.enable(key, { kind: 'global' }) + const visible = await f.capabilities.visible(null) + assert.equal(visible.length, 1) + assert.equal(visible[0]?.id, 'demo') + assert.deepEqual(visible[0]?.permissions, ['read:demo']) + + await f.capabilities.disable(key, { kind: 'global' }) + assert.deepEqual(await f.capabilities.visible(null), []) + + await writeFile(join(f.workspace, 'marqdo.yaml'), 'project:\n name: demo\n version: 0.1.0\n') + await assert.rejects(f.capabilities.importToProject(key), (error: unknown) => ( + error instanceof MarketError && error.code === MARKET_ERROR.runtimeNotInstalled + )) + const removed = await f.capabilities.uninstall(key) + assert.deepEqual(removed.removed_versions, ['0.1.0']) + assert.deepEqual(await f.capabilities.capabilities(), []) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('project import is refused before install with extension.not_installed', async () => { + const f = await fixture() + try { + await assert.rejects(f.capabilities.importToProject('local:ext:demo'), (error: unknown) => ( + error instanceof MarketError && error.code === MARKET_ERROR.capabilityNotInstalled + )) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('uninstall refuses a literal project reference unless forced', async () => { + const f = await fixture() + try { + const index = await f.market.refresh({ force: true }) + const key = index.entries[0]?.key + assert.ok(key) + const installed = await f.capabilities.install(key) + const path = installed.capability.active_path + assert.ok(path) + await writeFile(join(f.workspace, 'marqdo.yaml'), `dependencies:\n demo:\n path: ${path}\n`) + await assert.rejects(f.capabilities.uninstall(key), (error: unknown) => ( + error instanceof MarketError && error.code === MARKET_ERROR.capabilityProjectReferenced + )) + const forced = await f.capabilities.uninstall(key, { force: true }) + assert.deepEqual(forced.references, ['marqdo.yaml']) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('build-required entries stay inactive until build consent is supplied', async () => { + const f = await fixture({ build: true }) + try { + const index = await f.market.refresh({ force: true }) + const key = index.entries[0]?.key + assert.ok(key) + const installed = await f.capabilities.install(key) + assert.equal(installed.requires_build, true) + assert.equal(installed.capability.active_version, null) + await assert.rejects(f.capabilities.enable(key, { kind: 'global' }), (error: unknown) => ( + error instanceof MarketError && error.code === MARKET_ERROR.capabilityVersionUnknown + )) + const built = await f.capabilities.install(key, { allowBuild: true }) + assert.equal(built.already_installed, true) + assert.equal(built.requires_build, false) + assert.equal(built.capability.active_version, '0.1.0') + assert.equal(built.capability.ready, true) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('unsafe archive entries are rejected before activation', async () => { + const f = await fixture({ symlink: true }) + try { + const index = await f.market.refresh({ force: true }) + const key = index.entries[0]?.key + assert.ok(key) + await assert.rejects(f.capabilities.install(key), (error: unknown) => ( + error instanceof Error && /link entries|symbolic/i.test(error.message) + )) + assert.deepEqual(await f.capabilities.capabilities(), []) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('two sources with the same entry id keep distinct identities', async () => { + const f = await fixture() + try { + const second = join(f.source, '..', 'source2') + await mkdir(second, { recursive: true }) + await writeFile(join(second, 'one.txt'), 'x') + const archive = join(f.home, '..', 'demo-other.tar.gz') + await archiveOf(second, archive) + await copyFile(archive, join(second, 'demo-0.1.0.tar.gz')) + await writeJsonAtomic(join(second, 'index.json'), { + schema: 'marqdo.mqdh.market.directory', schema_version: 1, + entries: [{ kind: 'ext', id: 'demo', name: 'Other demo', version: '0.1.0', asset: { name: 'demo-0.1.0.tar.gz', path: 'demo-0.1.0.tar.gz' } }], + }) + await writeJsonAtomic(join(f.home, 'config', 'market.json'), { + schema: 'marqdo.mqdh.market', schema_version: 1, + sources: [ + { id: 'local', kind: 'directory', path: f.source }, + { id: 'other', kind: 'directory', path: second }, + ], + cache_ttl_ms: 300000, offline: false, + }) + const index = await f.market.refresh({ force: true }) + assert.equal(index.entries.length, 2) + const keys = index.entries.map(entry => entry.key).sort() + assert.deepEqual(keys, ['local:ext:demo', 'other:ext:demo']) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('project import materializes a project-local copy and delegates add to the CLI', async () => { + const f = await fixture() + try { + const index = await f.market.refresh({ force: true }) + const key = index.entries[0]?.key + assert.ok(key) + await f.capabilities.install(key) + const fake = join(f.home, 'fake-marqdo') + await writeFile(fake, '#!/bin/sh\nprintf \'{"command":"add","success":true,"manifest":"%s/marqdo.yaml"}\\n\' "$PWD"\n') + await chmod(fake, 0o755) + const store = new CapabilityStore({ + layout: (await import('../src/core/home.ts')).layoutOf(f.home), + network: f.network, + market: f.market, + cli: async () => ({ bin: fake }) as MarqdoCli, + toolHome: async () => undefined, + workspace: () => f.workspace, + }) + await writeFile(join(f.workspace, 'marqdo.yaml'), 'project:\n name: demo\n version: 0.1.0\n') + const imported = await store.importToProject(key, { alias: 'demo' }) + assert.equal(imported.path, 'marqdo-vendor/demo') + 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/) + } finally { + await cleanup(join(f.home, '..')) + } +}) + +test('run evidence binds the project lock digest', async () => { + const root = await mkdtemp(join(tmpdir(), 'mqdh-evidence-')) + try { + const workspace = join(root, 'workspace') + const runs = join(root, 'runs') + await mkdir(workspace, { recursive: true }) + await writeFile(join(workspace, 'index.mq.md'), '## @exec main\n\n`return 1`\n') + await writeFile(join(workspace, 'marqdo.lock'), 'lock_version: 4\n') + const documentDigest = await digestFile(join(workspace, 'index.mq.md')) + const lockDigest = await digestFile(join(workspace, 'marqdo.lock')) + const store = new EvidenceStore(runs) + await store.save({ + schema: 'marqdo.mqdh.run-evidence', schema_version: 1, + run_id: 'run-lock-test', created_at: new Date().toISOString(), workspace, + document: 'index.mq.md', document_digest: documentDigest, analysis_digest: documentDigest, + environment_id: null, + cli: { path: '/bin/true', version: null, source_sha: null }, + bundle_digest: null, lock_digest: lockDigest, + action: 'run', function_name: null, arguments: [], mode: 'pure', grants: {}, + status: 'completed', terminal_kind: 'completed', + result: { value: null, error: null, value_render: null }, + observation: { event_count: 1, violations: [], stored: true }, + result_artifact: null, + }, '') + assert.equal((await store.read('run-lock-test', workspace))?.freshness, 'fresh') + await writeFile(join(workspace, 'marqdo.lock'), 'lock_version: 4\npackages: []\n') + const stale = await store.read('run-lock-test', workspace) + assert.equal(stale?.freshness, 'stale') + assert.match(stale?.freshness_detail ?? '', /project lock changed/) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) + +test('the workbench JavaScript parses and contains no inline HTML writes', () => { + assert.match(APP_HTML, /id="market"/) + assert.match(APP_HTML, /id="market-refresh"/) + assert.doesNotMatch(APP_JS, /innerHTML\s*=/) + const script = new vm.Script(APP_JS) + assert.ok(script) +}) + +test('installed payload retains the archive digest and byte size', async () => { + const f = await fixture() + try { + const index = await f.market.refresh({ force: true }) + const key = index.entries[0]?.key + assert.ok(key) + const installed = await f.capabilities.install(key) + const stat = await readFile(join(f.source, 'demo-0.1.0.tar.gz')) + assert.equal(installed.version.sha256.length, 64) + assert.equal(installed.version.size, stat.byteLength) + assert.match(installed.version.path, /^local-ext-demo\/0\.1\.0-[0-9a-f]{12}$/) + } finally { + await cleanup(join(f.home, '..')) + } +}) diff --git a/scripts/ci.sh b/scripts/ci.sh index 358bf1181f..3623911919 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -102,7 +102,7 @@ evidence = { }, 'unverified': [ 'real remote-model conversation (no model credential in this lane)', - 'browser end-to-end automation (route and API verified over HTTP, see docs/mqdh/STATUS.md)', + 'browser end-to-end automation in this CI lane (market browser run recorded in docs/mqdh/evidence/2026-11-29-market.md)', ], } (out / 'evidence.json').write_text(json.dumps(evidence, indent=2) + '\n')