From 5e68f27ed372f22e1b8a70a4dc1237fbe34e429c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=8F=E6=89=BF?= Date: Mon, 23 Nov 2026 15:03:35 +0800 Subject: [PATCH 1/2] feat(hosts): add a partial OpenClaw host adapter OpenClaw keeps two storage families apart: a state directory (~/.openclaw, OPENCLAW_STATE_DIR, or a profile variant) and one workspace per agent. The workspace is an agent home rather than a code checkout, so project scope only applies when the requested workspace resolves to a configured agent. The adapter attributes the workspace through agents.defaults.workspace and agents.entries..workspace, keeps an unmatched or unreadable config explicit in diagnostics, and collects workspace skills plus the six instruction files OpenClaw loads at session start. openclaw.json is JSON5, so a comment-laden hand-edited config would have been dropped by a strict JSON reader. A small normalizer in scripts/agent-customize/core/json5.mjs handles comments, trailing commas, bare keys, and single-quoted strings, and every read reports a parse state (json, json5, empty, missing, skipped, invalid) so a config the reader cannot understand is reported instead of being treated as empty. The descriptor claims configured assets and portable HTML rendering only. Live sessions and transcripts stay in per-agent SQLite, which is never decoded here, and `openclaw sessions export-trajectory` mutates the workspace it exports from, so no session-evidence slice ships. Lifecycle targets keep rejecting openclaw, and the matrix, docs site page, zh-Hans mirror, platform note, and CLI help state that boundary. Spec: docs/specs/2026-11-23-openclaw-host-adapter.md (issue #114). Test: npm test - 1804 passed, 7 skipped. One unrelated failure remains: the Antigravity artifact build trips over local dependency drift (yaml 2.9.1 declared, 2.9.0 installed). npm run pack:verify passed; the doc-link graph resolves 39 files and 56 links. Co-authored-by: Qoder --- README.md | 8 +- README.zh-CN.md | 11 +- docs/adapters/README.md | 36 ++- docs/docs/hosts/adapter-matrix.md | 33 +- docs/docs/installation.mdx | 4 +- .../current/hosts/adapter-matrix.md | 19 +- .../current/installation.mdx | 3 +- .../specs/2026-11-23-openclaw-host-adapter.md | 148 +++++++++ references/agent-customize/README.md | 4 +- .../agent-customize/platforms/openclaw.md | 71 +++++ references/agent-customize/routing.md | 4 +- scripts/agent-customize/cli.mjs | 9 + scripts/agent-customize/core/json5.mjs | 173 +++++++++++ scripts/agent-customize/providers/index.mjs | 2 + .../agent-customize/providers/openclaw.mjs | 285 ++++++++++++++++++ scripts/host-support/index.mjs | 9 + templates/reporting/routing.md | 2 +- test/agents/agent-customize.test.mjs | 220 ++++++++++++++ test/agents/json5-config-reader.test.mjs | 90 ++++++ 19 files changed, 1101 insertions(+), 30 deletions(-) create mode 100644 docs/specs/2026-11-23-openclaw-host-adapter.md create mode 100644 references/agent-customize/platforms/openclaw.md create mode 100644 scripts/agent-customize/core/json5.mjs create mode 100644 scripts/agent-customize/providers/openclaw.mjs create mode 100644 test/agents/json5-config-reader.test.mjs diff --git a/README.md b/README.md index 282656e4..5ecf589d 100644 --- a/README.md +++ b/README.md @@ -384,12 +384,13 @@ Host differences remain explicit. Qoder Desktop is bundled, Cursor is session-only while its native command contract is being reconciled, Pi lifecycle commands without current native evidence remain manual or unavailable, and WorkBuddy has no managed Better Harness plugin lifecycle -surface. +surface. OpenClaw has neither a lifecycle profile nor a session-evidence +contract, so only its configured assets are inventoried. ### More adapters Beyond the hosts above, Better Harness also supports Qwen Code, Pi, Kimi Code, -WorkBuddy, and Grok. Their exact install, invocation, and +WorkBuddy, Grok, and OpenClaw. Their exact install, invocation, and evidence boundaries live in the docs so this README stays focused: - **Qwen Code** — [installation guide](docs/docs/installation.mdx#qwen-code) @@ -402,6 +403,9 @@ evidence boundaries live in the docs so this README stays focused: (`.kimi-plugin/plugin.json` plugin install). - **WorkBuddy** — [Host Adapter Matrix](docs/docs/hosts/adapter-matrix.md#workbuddy). - **Grok** — [Host Adapter Matrix](docs/docs/hosts/adapter-matrix.md#grok). +- **OpenClaw** — [Host Adapter Matrix](docs/docs/hosts/adapter-matrix.md#openclaw) + (partial adapter: configured assets only; live sessions stay in per-agent + SQLite, so no session evidence ships). Each produces a self-contained `report.html` with paired `report.md` and `findings.json`; missing or partial session evidence stays explicit. diff --git a/README.zh-CN.md b/README.zh-CN.md index 67e6f636..b2639552 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -35,7 +35,7 @@ 不同宿主的入口并不完全相同,请直接使用对应章节给出的命令。 本 README 仅内联展示最常用宿主的安装步骤。其余受支持的宿主(Qwen Code、Pi、 -Kimi Code、WorkBuddy 与 Grok)的步骤与边界保留在 +Kimi Code、WorkBuddy、Grok 与 OpenClaw)的步骤与边界保留在 [安装指南](docs/docs/installation.mdx)和[公开宿主适配矩阵](docs/docs/hosts/adapter-matrix.md)中; 参见[更多适配器](#更多适配器)。README 中的排布只是展示选择,并不代表支持等级。 @@ -184,7 +184,8 @@ better-harness plugin verify --host qwen --surface cli 宿主差异会保持显式:Qoder Desktop 为内置分发;Cursor 在原生命令合同完成核对前 只保留会话级状态;Pi 缺少当前原生证据的生命周期操作会标记为手工或不可用; -WorkBuddy 没有可管理的 Better Harness 插件生命周期入口。 +WorkBuddy 没有可管理的 Better Harness 插件生命周期入口。OpenClaw 既没有生命周期 +profile,也没有会话证据契约,因此只清点其已配置资产。 ### Claude Code @@ -363,8 +364,8 @@ Copilot 不记录逐次响应的 token 用量,VS Code Copilot Chat 也没有 ### 更多适配器 -除上述宿主外,Better Harness 还支持 Qwen Code、Pi、Kimi Code、WorkBuddy 与 -Grok。它们确切的安装、调用与证据边界都放在文档里,以保持本 README 精简: +除上述宿主外,Better Harness 还支持 Qwen Code、Pi、Kimi Code、WorkBuddy、 +Grok 与 OpenClaw。它们确切的安装、调用与证据边界都放在文档里,以保持本 README 精简: - **Qwen Code** —— [安装指南](docs/docs/installation.mdx#qwen-code) (`qwen extensions install QoderAI/better-harness`)。 @@ -376,6 +377,8 @@ Grok。它们确切的安装、调用与证据边界都放在文档里,以保 (`.kimi-plugin/plugin.json` 插件安装)。 - **WorkBuddy** —— [宿主适配器矩阵](docs/docs/hosts/adapter-matrix.md#workbuddy)。 - **Grok** —— [宿主适配器矩阵](docs/docs/hosts/adapter-matrix.md#grok)。 +- **OpenClaw** —— [宿主适配器矩阵](docs/docs/hosts/adapter-matrix.md#openclaw) + (部分适配器:仅已配置资产;实时会话保存在各 agent 的 SQLite 中,不提供会话证据)。 它们都产出自包含的 `report.html` 及配套的 `report.md` 与 `findings.json`; 缺失或不完整的会话证据会被明确标注。 diff --git a/docs/adapters/README.md b/docs/adapters/README.md index 0ebb3c06..4a65a367 100644 --- a/docs/adapters/README.md +++ b/docs/adapters/README.md @@ -1,16 +1,16 @@ # Host Adapter Matrix This is the single entry point for Claude Code, Augment/Auggie, Codex, Qoder, -Cursor, Qwen, GitHub Copilot, Pi, Kimi Code, WorkBuddy, and Grok host -boundaries, plus the +Cursor, Qwen, GitHub Copilot, Pi, Kimi Code, WorkBuddy, Grok, and OpenClaw +host boundaries, plus the DeepSeek Harness (DSH) verified install/discovery, developer-preview configured-assets, session, Asset Practices, neutral Harness analysis, and Evidence Bundle slices, plus qualified portable HTML report rendering. Do not create `docs/adapters/claude-code.md`, `docs/adapters/codex.md`, `docs/adapters/qoder.md`, `docs/adapters/cursor.md`, `docs/adapters/qwen.md`, `docs/adapters/copilot.md`, `docs/adapters/pi.md`, -`docs/adapters/kimi-code.md`, `docs/adapters/workbuddy.md`, or -`docs/adapters/grok.md` by default. +`docs/adapters/kimi-code.md`, `docs/adapters/workbuddy.md`, +`docs/adapters/grok.md`, or `docs/adapters/openclaw.md` by default. Adding another host? Follow [Contributing a New Coding Agent Host](contributing-new-coding-agent.md) before @@ -48,6 +48,7 @@ project `.kimi-code/skills/`), then runs `/skill:better-harness`. | Kimi Code | Analysis-capable source-local host | `.kimi-plugin/plugin.json` | `scripts/agent-customize/providers/kimi.mjs` | `scripts/session-analysis/platforms/kimi.mjs` | self-contained HTML + Markdown | `AGENTS.md` + `~/.kimi-code/skills` + project `.kimi-code/skills`/`.kimi/skills` + `~/.kimi-code/mcp.json` | `harness evidence-bundle --platform kimi` -> validated `html` render | | WorkBuddy | Analysis-capable source-local host | none (skills install into `~/.workbuddy/skills`) | `scripts/agent-customize/providers/workbuddy.mjs` | `scripts/session-analysis/platforms/workbuddy.mjs` | self-contained HTML + Markdown | `~/.workbuddy` `AGENTS.md` + identity files + `.agents` + `AGENTS.md` | `session-analysis --platform workbuddy sources` -> validated `html` render | | Grok | Analysis-capable source-local host | none (skills install into `~/.grok/skills`) | `scripts/agent-customize/providers/grok.mjs` | `scripts/session-analysis/platforms/grok.mjs` | self-contained HTML + Markdown | `~/.grok` + `.grok` + `.agents` + `AGENTS.md` | `session-analysis --platform grok sources` -> skill symlink -> validated `html` render | +| OpenClaw | Partial source-local host | none (skills install into OpenClaw-owned skill roots) | `scripts/agent-customize/providers/openclaw.mjs` | none; live sessions stay in per-agent SQLite | self-contained HTML + Markdown | state `skills/`, per-agent `workshop-skills`, `openclaw.json` `mcp.servers`, agent workspace `skills/` + `.agents/skills` + instruction files | fixture-covered focused tests only; no native smoke yet | | DeepSeek Harness (DSH) | Verified install/discovery for headless/base and Web `standard`/`code`/`cordis`; shared read-only analysis over developer-preview configured and Session evidence | `.dsh-plugin/cordis.patch.yml` host shell (one Cordis bundle row naming `scripts/dsh-skill-discovery/bundle.mjs`, which loads the local policy at `scripts/dsh-skill-discovery/index.mjs`); no lifecycle shell | `scripts/agent-customize/providers/dsh.mjs`; filesystem Skills and cwd-sensitive Instructions, configured-not-observed | `scripts/session-analysis/platforms/dsh.mjs`; `dsh-v1` for the audited format-0 session-evidence slice from DSH `dsh-v0.1.0-rc.7` and `dsh-v0.1.0-rc.8`, raw `.jsonl` and feature-detected `.jsonl.zstd` | self-contained HTML + Markdown | canonical Skill from the complete root; model Skill calls rejected | `dsh plugin --profile add @qoder-ai/better-harness` -> `npm run test:dsh-bundle`; `npm run test:dsh-native`; `npm run test:dsh-configured-assets-native`; validated portable `html` render and native output-root inertness | ## Read-only Plugin Lifecycle @@ -85,11 +86,12 @@ Plans never execute and always preserve native surface differences: | Pi CLI / CLI session | Persistent user/project install guidance and inventory; separate `pi -e` session-only activation whose update/remove operations are not applicable | | WorkBuddy | `PLUGIN_LIFECYCLE_UNSUPPORTED`; adapter evidence remains available | -Kimi Code, Grok, and DSH are absent from this table on purpose: none has a -validated native lifecycle contract yet, so lifecycle targets reject them with -`UNKNOWN_HOST` instead of borrowing another host's install route. Kimi Code and -Grok retain their configured-asset and session evidence. DSH retains its -bounded verified discovery, configured-assets, and partial session-evidence +Kimi Code, Grok, OpenClaw, and DSH are absent from this table on purpose: none +has a validated native lifecycle contract yet, so lifecycle targets reject them +with `UNKNOWN_HOST` instead of borrowing another host's install route. Kimi Code +and Grok retain their configured-asset and session evidence, OpenClaw retains +its configured-asset inventory, and DSH retains its bounded verified discovery, +configured-assets, and partial session-evidence slices, but has no lifecycle profile or native lifecycle claim. The lifecycle commands do not read raw session transcripts, contact a registry, @@ -221,6 +223,20 @@ edit host settings, or register an `apply` path. `signals.json`). The adapter honors `GROK_HOME`. Grok has no install shell in this repository; skills install manually into `~/.grok/skills` (symlink is enough for `/better-harness`). +- OpenClaw configured assets are inventoried through + `scripts/agent-customize/providers/openclaw.mjs`, covering managed skills under + the state directory, per-agent `workshop-skills`, the personal + `~/.agents/skills` root in a default state directory, `mcp.servers` from the + JSON5 `openclaw.json`, and the agent workspace `skills/`, `.agents/skills`, + and `AGENTS.md`/`SOUL.md`/`USER.md`/`IDENTITY.md`/`MEMORY.md`/`BOOT.md` + instruction files. The adapter resolves `agents.defaults.workspace` and + `agents.entries..workspace` to attribute the requested workspace, and + it reports an unparsed config as unparsed instead of empty. The adapter honors + `OPENCLAW_STATE_DIR`, `OPENCLAW_CONFIG_PATH`, `--openclaw-home`, and + `--openclaw-config-path`. Live sessions stay in per-agent SQLite, which this + repository does not decode, so no session-evidence slice ships; OpenClaw has no + install shell, plugin lifecycle, or native smoke evidence in this repository + and stays a partial adapter outside the verified Quickstart set. - DeepSeek Harness has independent bounded capabilities. Verified install/discovery uses DSH `0.1.1-rc.2` at audited source `b150a551b8d465e31e418e1b2eaf5e79bbb7d28e`. The supported discovery route is @@ -317,7 +333,7 @@ Canonical templates live under `templates/reporting/`. `findings.json`, Canvas-only `canvas.json`, and `report.canvas.tsx`. - `cursor-canvas.md`: Cursor Canvas output contract, covering the complete report, native Context Usage projection, and public IDE actions. -- `html-visual.md`: portable Claude Code/Codex/Qwen/Copilot/Pi/Kimi Code/WorkBuddy/Grok/DeepSeek Harness visual output contract, covering +- `html-visual.md`: portable Claude Code/Codex/Qwen/Copilot/Pi/Kimi Code/WorkBuddy/Grok/OpenClaw/DeepSeek Harness visual output contract, covering `findings.json`, `report.md`, and `report.html`. - Markdown-only output has no visual companion. diff --git a/docs/docs/hosts/adapter-matrix.md b/docs/docs/hosts/adapter-matrix.md index 4569cf94..73991ccb 100644 --- a/docs/docs/hosts/adapter-matrix.md +++ b/docs/docs/hosts/adapter-matrix.md @@ -14,11 +14,12 @@ host-neutral. ## Support levels Better Harness currently declares ten more complete capability-level host -adapters, a partial Augment/Auggie session-only adapter, plus bounded DSH +adapters, two partial adapters (Augment/Auggie session-only and OpenClaw +configured-assets only), plus bounded DSH discovery, configured-assets, and session slices. -Six have verified public Quickstart paths. Pi, Kimi Code, WorkBuddy, and Grok -are visible as adapter support because their installation and end-to-end -evidence boundaries differ from that six-host set. DSH has Verified +Six have verified public Quickstart paths. Pi, Kimi Code, WorkBuddy, Grok, and +OpenClaw are visible as adapter support because their installation and +end-to-end evidence boundaries differ from that six-host set. DSH has Verified install/discovery for a qualified runtime/preset boundary plus developer-preview configured-assets and session-evidence contracts. It supports shared read-only Asset Practices, neutral Harness analysis, Evidence Bundles, and qualified @@ -41,6 +42,7 @@ remains the complete capability-level source of truth. | Kimi Code | Adapter support | Analysis-capable source-local host | `.kimi-plugin/plugin.json` | Workspace-matching Kimi wire transcripts | Self-contained HTML + Markdown | | WorkBuddy | Adapter support | Analysis-capable source-local host | None; skills use WorkBuddy-owned paths | Workspace-matching WorkBuddy JSONL transcripts | Self-contained HTML + Markdown | | Grok | Adapter support | Analysis-capable source-local host | None; skills use Grok-owned paths | Workspace-matching Grok session dirs (`updates.jsonl`) | Self-contained HTML + Markdown | +| OpenClaw | Partial adapter | Configured assets only; no install, lifecycle, or session-evidence claim | None; skills use OpenClaw-owned paths | None; live sessions stay in per-agent SQLite | Self-contained HTML + Markdown | | DeepSeek Harness (DSH) | Verified install/discovery | Qualified headless/base and Web `standard`/`code`/`cordis`; shared read-only analysis over partial configured-assets and session evidence | `.dsh-plugin/cordis.patch.yml` Cordis bundle shell plus the local DSH Cordis policy; no lifecycle shell | DSH JSONL backend session format `0`: raw `.jsonl` and feature-detected `.jsonl.zstd` | Self-contained HTML + Markdown | The `@qoder-ai/better-harness` npm package includes all eight plugin metadata @@ -69,7 +71,10 @@ contract is stale, persistent Pi operations without native evidence stay unavailable, transient Pi update/remove are not applicable, and WorkBuddy returns `PLUGIN_LIFECYCLE_UNSUPPORTED`. Kimi Code and Grok have no validated native lifecycle contract yet, so lifecycle targets reject them with -`UNKNOWN_HOST` while their adapter evidence stays available. DSH likewise has +`UNKNOWN_HOST` while their adapter evidence stays available. OpenClaw has no +lifecycle profile and no session-evidence contract either, so lifecycle targets +reject it with `UNKNOWN_HOST` and only its configured assets are inventoried. +DSH likewise has no lifecycle profile: lifecycle targets reject it with `UNKNOWN_HOST`; its manually configured verified discovery and partial session evidence remain available. The shadow host profiles do not replace the canonical adapter matrix @@ -82,7 +87,7 @@ lifecycle target. `canvas.json`, and `report.canvas.tsx`. - **Cursor Canvas** — the same complete report contract rendered with `cursor/canvas`, native Context Window evidence, and IDE actions. -- **HTML visual** — portable Claude Code/Codex/Qwen/Copilot/Pi/Kimi Code/WorkBuddy/Grok/DeepSeek Harness contract +- **HTML visual** — portable Claude Code/Codex/Qwen/Copilot/Pi/Kimi Code/WorkBuddy/Grok/OpenClaw/DeepSeek Harness contract covering `findings.json`, `report.md`, and a self-contained `report.html` (see the [sample report](pathname:///demo/better-harness-report/)). - **Markdown-only** — no visual companion. @@ -166,6 +171,22 @@ npm-packaged host artifact; installation is a manual skill symlink into outside the verified Quickstart set until a complete interactive report-loop smoke is observed. +### OpenClaw {#openclaw} + +OpenClaw configured assets are inventoried through +`scripts/agent-customize/providers/openclaw.mjs`, and portable HTML routing +reuses the generic Better Harness-owned root. The adapter keeps the state +directory (`~/.openclaw` or `OPENCLAW_STATE_DIR`) apart from each agent +workspace, attributes the requested workspace to a configured agent, and +inventories `mcp.servers` from the JSON5 `openclaw.json` plus managed, personal, +and per-agent workshop skills. Live sessions and transcripts live in per-agent +SQLite, which this repository does not decode, and `openclaw sessions +export-trajectory` writes into the workspace it exports, so no session-evidence +slice ships. This repository does not ship an OpenClaw install shell, plugin +lifecycle profile, or npm-packaged host artifact, and no native smoke has been +recorded yet, so OpenClaw stays a partial adapter outside the verified +Quickstart set. + ### DeepSeek Harness (DSH) {#deepseek-harness-dsh} DSH has Verified install/discovery against DSH `0.1.1-rc.2` at audited source diff --git a/docs/docs/installation.mdx b/docs/docs/installation.mdx index dfb69f5d..220d7e83 100644 --- a/docs/docs/installation.mdx +++ b/docs/docs/installation.mdx @@ -53,7 +53,9 @@ Plans preserve host differences instead of inventing a common mutation path. Qoder Desktop is bundled, Codex Desktop returns manual UI steps, Cursor remains session-only while its native command contract is reconciled, Pi operations without current native evidence are manual or unavailable, and WorkBuddy has no -managed plugin lifecycle surface. There is no `plugin apply` command. +managed plugin lifecycle surface. OpenClaw has neither a lifecycle profile nor a +session-evidence contract, and only its configured assets are inventoried. There +is no `plugin apply` command. Git can clone the Cursor manifest for inspection, but manifest presence alone does not establish a supported installation route. diff --git a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/hosts/adapter-matrix.md b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/hosts/adapter-matrix.md index 7a34c03d..899432cb 100644 --- a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/hosts/adapter-matrix.md +++ b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/hosts/adapter-matrix.md @@ -13,7 +13,8 @@ Better Harness 运行在你现有的编码智能体内。宿主差异只进入 ## 支持层级 Better Harness 当前声明了十个能力层宿主适配器,其中六个已有验证过的公开 -快速开始路径。Pi、Kimi Code、WorkBuddy 与 Grok 以适配器支持展示,因为它们的安装方式和端到端 +快速开始路径。Pi、Kimi Code、WorkBuddy 与 Grok 以适配器支持展示,OpenClaw 以部分 +适配器展示(仅已配置资产),因为它们的安装方式和端到端 证据边界与这六个宿主不同。完整能力层事实源仍是 [规范适配器矩阵](https://github.com/QoderAI/better-harness/blob/main/docs/adapters/README.md)。 @@ -31,6 +32,7 @@ Better Harness 当前声明了十个能力层宿主适配器,其中六个已 | Kimi Code | 适配器支持 | 具备分析能力的源码本地宿主 | `.kimi-plugin/plugin.json` | 匹配工作区的 Kimi wire 转录 | 自包含 HTML + Markdown | | WorkBuddy | 适配器支持 | 具备分析能力的源码本地宿主 | 无;Skill 使用 WorkBuddy 自有路径 | 匹配工作区的 WorkBuddy JSONL 转录 | 自包含 HTML + Markdown | | Grok | 适配器支持 | 具备分析能力的源码本地宿主 | 无;Skill 使用 Grok 自有路径 | 匹配工作区的 Grok 会话目录(`updates.jsonl`) | 自包含 HTML + Markdown | +| OpenClaw | 部分适配器 | 仅已配置资产;不声称安装、生命周期或会话证据 | 无;Skill 使用 OpenClaw 自有路径 | 无;实时会话保存在各 agent 的 SQLite 中 | 自包含 HTML + Markdown | `@qoder-ai/better-harness` npm 包含全部七个插件元数据根目录。生成的 Qoder 运行时 bundle 只包含 Qoder shell。Pi 复用现有 `package.json` 中的安装元数据, @@ -52,6 +54,7 @@ Cursor 在本机 help 合同过期期间保持安装不可用;Pi 持久化 sur 证据的操作保持不可用,临时 session surface 的更新/移除不适用;WorkBuddy 返回 `PLUGIN_LIFECYCLE_UNSUPPORTED`。Kimi Code 与 Grok 尚无经验证的原生生命周期 合同,因此生命周期目标会以 `UNKNOWN_HOST` 拒绝它们,其适配器证据仍然可用。 +OpenClaw 同样没有生命周期 profile,也没有会话证据契约,只清点其已配置资产。 在 ADR-0002 仍为 proposed 期间,shadow host profile 不替代规范适配器矩阵。 ## 输出模式 @@ -60,7 +63,7 @@ Cursor 在本机 help 合同过期期间保持安装不可用;Pi 持久化 sur `canvas.json` 和 `report.canvas.tsx`。 - **Cursor Canvas** —— 使用 `cursor/canvas`、原生 Context Window 证据和 IDE actions 渲染同一份完整报告契约。 -- **HTML 可视化** —— 面向 Claude Code/Codex/Qwen/Copilot/Pi/Kimi Code/WorkBuddy/Grok 的可移植契约,覆盖 +- **HTML 可视化** —— 面向 Claude Code/Codex/Qwen/Copilot/Pi/Kimi Code/WorkBuddy/Grok/OpenClaw 的可移植契约,覆盖 `findings.json`、`report.md` 和自包含的 `report.html` (见[示例报告](pathname:///demo/better-harness-report/))。 - **纯 Markdown** —— 无视觉版本。 @@ -110,6 +113,18 @@ Grok 的已配置资产、工作区匹配的会话证据与可移植 HTML 路由 `~/.grok/skills/better-harness`(或项目 `.grok/skills`)。在观察到完整交互式 报告闭环冒烟验证前,Grok 仍不进入已验证快速开始集合。 +### OpenClaw {#openclaw} + +OpenClaw 的已配置资产由 `scripts/agent-customize/providers/openclaw.mjs` 清点, +可移植 HTML 路由复用通用的 Better Harness 自有根目录。适配器把状态目录 +(`~/.openclaw` 或 `OPENCLAW_STATE_DIR`)与各 agent 工作区区分开,把当前请求的 +工作区归属到已配置的 agent,并从 JSON5 格式的 `openclaw.json` 读取 `mcp.servers`, +同时清点托管技能、个人技能与每个 agent 的 workshop 技能。实时会话与转录保存在 +各 agent 的 SQLite 中,本仓库不解码宿主数据库;`openclaw sessions +export-trajectory` 会写入它导出的工作区,因此不提供会话证据切片。本仓库不提供 +OpenClaw 安装 Shell、插件生命周期 profile 或 npm 打包的宿主产物,也尚未记录 +原生冒烟验证,因此 OpenClaw 保持为部分适配器,不进入已验证快速开始集合。 + ## 能力覆盖 各宿主的能力刻意保持差异:没有真实证据源的宿主不会声称具备某项能力, diff --git a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/installation.mdx b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/installation.mdx index 0122f9d0..81acc25e 100644 --- a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/installation.mdx +++ b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/installation.mdx @@ -47,7 +47,8 @@ better-harness plugin verify --host qwen --surface cli 计划会保留宿主差异,不会伪造统一的变更路径。Qoder Desktop 为内置分发, Codex Desktop 返回手工 UI 步骤;Cursor 在原生命令合同完成核对前只保留会话级 状态;Pi 缺少当前原生证据的操作为手工或不可用;WorkBuddy 没有可管理的插件 -生命周期入口。CLI 不提供 `plugin apply` 命令。 +生命周期入口。OpenClaw 既没有生命周期 profile,也没有会话证据契约,只清点其 +已配置资产。CLI 不提供 `plugin apply` 命令。 可以使用 Git 克隆并检查 Cursor manifest,但仅存在 manifest 并不能证明当前 存在受支持的安装路径。 diff --git a/docs/specs/2026-11-23-openclaw-host-adapter.md b/docs/specs/2026-11-23-openclaw-host-adapter.md new file mode 100644 index 00000000..d48710d9 --- /dev/null +++ b/docs/specs/2026-11-23-openclaw-host-adapter.md @@ -0,0 +1,148 @@ +# OpenClaw Configured-Assets Host Adapter + +## Traceability + +- Spec ID: SPEC-2026-11-23-openclaw-host-adapter +- Status: Implemented +- Upstream request: [QoderAI/better-harness#114](https://github.com/QoderAI/better-harness/issues/114) +- Documentation baseline: `docs.openclaw.ai` product docs read on 2026-11-23 + (`concepts/agent-workspace`, `tools/skills`, `tools/mcp`). No native OpenClaw + install was inspected or smoked. + +## Intent + +Add OpenClaw as a partial, source-local host so Better Harness can inventory the +configured assets an OpenClaw agent actually loads — skills, MCP servers, and +workspace instruction files — through the existing configured-asset contract, +and emit results through an existing report mode. Issue #114 asked for harness +runs and agent customization inside an OpenClaw session; the configured-asset +slice is the part this repository can read without decoding a host database. + +## Non-Goals + +- No session-evidence adapter. OpenClaw keeps live sessions and transcripts in + per-agent SQLite (`agents//agent/openclaw-agent.sqlite`), which this + repository does not decode, and `openclaw sessions export-trajectory` requires + a running Gateway with owner approval and writes into the workspace it + exports. Neither is an adapter input. +- No OpenClaw install shell, plugin manifest, npm metadata root, or generated + host artifact. +- No plugin lifecycle profile. Like Kimi Code, Grok, and DSH, OpenClaw is an + unmanaged host here, so lifecycle targets keep rejecting `openclaw` with + `UNKNOWN_HOST`. +- No Asset Practices, Checkup, neutral Harness report preparation, or Evidence + Bundle claim. The descriptor lists only configured assets and portable HTML + rendering. +- No write, migration, repair, or cleanup of OpenClaw state. Collection is + read-only. +- No inventory of plugin packages, cron jobs, internal hooks, daily memory + notes, sandboxed workspaces, or MCP header/env values. + +## Evidence Format + +OpenClaw separates two storage families, and the adapter must not flatten them: + +- State directory: `~/.openclaw`, overridden by `OPENCLAW_STATE_DIR` or + `--openclaw-home`. A non-default `OPENCLAW_PROFILE` moves the default to + `~/.openclaw-`. It holds `openclaw.json` (overridden by + `OPENCLAW_CONFIG_PATH` or `--openclaw-config-path`), managed `skills/`, the + `agents//agent/` runtime directories, and credentials. +- Agent workspace: the agent's home directory, defaulting to + `/workspace`, overridden by `OPENCLAW_WORKSPACE_DIR`, + `agents.defaults.workspace`, or `agents.entries..workspace`. In an + explicit multi-agent roster, unpinned entries fall back to + `/` or `/workspace-`. + +Configured-asset surfaces inventoried: + +- Skills: `/skills` managed skills, per-agent + `agents//agent/workshop-skills`, personal `~/.agents/skills` (only + when the state directory is the default), workspace `skills/`, and + `/.agents/skills`. Bundled host skills are excluded. +- MCP: `mcp.servers` in `openclaw.json`. A stdio server carries `command`; a + remote server carries `url` plus `transport`, which maps onto the shared `type` + field. `enabled: false` is preserved as a disabled entry. Env keys are named; + values are never serialized. +- Rules: workspace `AGENTS.md`, `SOUL.md`, `USER.md`, `IDENTITY.md`, `MEMORY.md`, + and `BOOT.md`. +- Config dialect: `openclaw.json` is JSON5, so the reader normalizes line and + block comments, trailing commas, unquoted identifier keys, and single-quoted + strings. Text it cannot normalize is reported as unparsed instead of being + treated as an empty config. + +## Acceptance Criteria + +- AC1: `better-harness agent-customize inventory --provider openclaw` resolves + the state directory and config path from `OPENCLAW_STATE_DIR`, + `OPENCLAW_CONFIG_PATH`, `--openclaw-home`, and `--openclaw-config-path`, and + reports the resolved paths plus the config parse state (`json`, `json5`, + `empty`, `invalid`, `missing`, `skipped`). +- AC2: Skill inventory covers managed, per-agent workshop, personal (default + state directory only), and workspace `skills/` plus `.agents/skills` roots, + with managed/workshop/personal items in user scope and workspace items in + project scope. +- AC3: `mcp.servers` entries are inventoried as MCP items with `enabled` state + preserved, `transport` carried onto `type`, and no env value or header value + serialized. +- AC4: The requested workspace is attributed to a configured agent through + `agents.defaults.workspace` and `agents.entries..workspace`; workspace + instruction files are inventoried as project rules only for that workspace, + and a workspace outside every configured agent reports the skip instead of + scanning unrelated files. +- AC5: Shared registries accept `openclaw` wherever the claimed slices are + routed: the host descriptor catalog, the configured-asset provider map, the + agent-customize CLI home option and summary, and the portable HTML render + platform list. Capability tests catch a claimed slice without an + implementation or the reverse, and lifecycle targets keep rejecting + `openclaw`. +- AC6: The adapter matrix (canonical README, docs site page, and its zh-Hans + copy), the README "More adapters" lists, the platform reference note, and the + installation guide document OpenClaw with its limitations; the doc-link graph + and docs tests pass. + +## Plan / Tasks + +1. `docs/specs/2026-11-23-openclaw-host-adapter.md`: record the host contract, + the claimed and unavailable slices, and the acceptance ids. +2. `scripts/agent-customize/core/json5.mjs`: normalize the JSON5 subset + OpenClaw configs use and return an explicit parse state. +3. `scripts/agent-customize/providers/openclaw.mjs`: resolve the state + directory, config path, and agent workspaces; inventory user and project + primitives; report unsupported surfaces. +4. Register `openclaw` in `scripts/host-support/index.mjs` with only configured + assets and portable HTML rendering, then thread it through the provider map, + the CLI options, and the summary. +5. Tests: JSON5 reader units plus deterministic fixtures for managed, workshop, + personal, and workspace skills, MCP parsing with credential-shaped env keys, + workspace attribution, restricted runs, unparsed configs, and the CLI + overrides. +6. Docs: adapter matrix row and section, docs site and zh-Hans mirrors, adapters + README, README host lists, installation guide lifecycle sentence, template + routing row, and the platform reference note. + +## Test and Review Evidence + +- AC1, AC5: `npx vitest run test/agents/agent-customize.test.mjs` covers the + CLI overrides, the parse-state reporting, and the capability-descriptor + routing; `test/plugins/host-support.test.mjs` covers descriptor/registry + equality. +- AC2, AC3, AC4: the same customize suite covers skill scopes, MCP items with + enabled state and transport, workspace attribution, the outside-workspace + skip, and restricted runs. +- AC1 (JSON5): `npx vitest run test/agents/json5-config-reader.test.mjs` covers + comments, trailing commas, bare keys, single-quoted strings, string-embedded + comment markers, unparsed text, and empty/missing files. +- AC6: `node scripts/doc-link-graph/cli.mjs skills/better-harness`, + `npx vitest run test/skills-docs/doc-link-graph.test.mjs`, `npm test`, + `npm run pack:verify`, and `git diff --check`. +- Native smoke: not performed in this change. The adapter is fixture-verified + against the documented layout only, so the matrix lists OpenClaw as a partial + adapter with no install, lifecycle, session, or Quickstart claim. + +Residual risk: the JSON5 subset is a normalizer, not a full JSON5 parser. A +config that uses constructs outside it — an unquoted string value, a hex number +in a key position, a comment between a key and its colon — is reported as +invalid rather than guessed at, and its MCP servers stay uninventoried until the +config parses. Skill precedence and allowlists (`agents.defaults.skills`, +`agents.entries.*.skills`) are not evaluated, so a skill that exists but is +allowlisted away still appears in the inventory as a configured asset. diff --git a/references/agent-customize/README.md b/references/agent-customize/README.md index 887bf60a..c1b70ee0 100644 --- a/references/agent-customize/README.md +++ b/references/agent-customize/README.md @@ -16,8 +16,8 @@ authority, routing, overlap, observed use, and maintenance boundaries. - Inventory and authority: `global-assets.md`. - Provider-specific notes: `platforms/claude.md`, `platforms/codex.md`, `platforms/qoder.md`, `platforms/qwen.md`, `platforms/copilot.md`, - `platforms/pi.md`, `platforms/kimi.md`, `platforms/workbuddy.md`, and - `platforms/dsh.md`. + `platforms/pi.md`, `platforms/kimi.md`, `platforms/workbuddy.md`, + `platforms/openclaw.md`, and `platforms/dsh.md`. ## Does Not Own diff --git a/references/agent-customize/platforms/openclaw.md b/references/agent-customize/platforms/openclaw.md new file mode 100644 index 00000000..9c1c40df --- /dev/null +++ b/references/agent-customize/platforms/openclaw.md @@ -0,0 +1,71 @@ +# OpenClaw Best Practices + +Use this file for OpenClaw specific operating practice. Use `../routing.md` for +host-neutral owner selection and the other `platforms/` files for different +hosts. Do not copy OpenClaw-only layout advice into shared docs unless there is +matching source evidence. + +## Operating Frame + +OpenClaw separates two storage families, and a workspace is an agent home rather +than a code checkout: + +- **State directory**: `~/.openclaw`, relocated by `OPENCLAW_STATE_DIR` or + `--openclaw-home`. Holds `openclaw.json`, managed skills, credentials, and + per-agent runtime state. A non-default `OPENCLAW_PROFILE` moves the default to + `~/.openclaw-`. +- **Agent workspace**: the agent's home directory, holding `AGENTS.md` and its + sibling instruction files plus workspace skills. Default + `/workspace`, relocated by `OPENCLAW_WORKSPACE_DIR`; per-agent + overrides live in `agents.entries..workspace`. + +Because the workspace *is* the agent home, project-scope assets belong there, +not in an arbitrary repository. Put standing instructions in `AGENTS.md`, tone +and boundaries in `SOUL.md`, and repeated procedures in Skills. + +## Durable Guidance + +OpenClaw loads `AGENTS.md`, `SOUL.md`, `USER.md`, `IDENTITY.md`, and `BOOT.md` +from the workspace at session start, and `MEMORY.md` in a private main session +only. `memory/YYYY-MM-DD.md` files are daily logs, so keep durable rules in +`AGENTS.md` and let memory tooling own the daily files. + +## Configured Surfaces + +- **Skills**: precedence for one workspace runs `skills/`, then + `.agents/skills/`, then personal `~/.agents/skills` (default state only), then + `/skills` managed skills, then per-agent + `agents//agent/workshop-skills`. Bundled skills ship with the host and + are not user-configured inventory. `agents.defaults.skills` and + `agents.entries..skills` narrow the allowlist. +- **MCP servers**: `openclaw.json` stores them under `mcp.servers`. A stdio + server carries `command`; a remote server carries `url` plus `transport`. + `enabled: false` keeps a definition without starting it. Treat env and header + values as credentials: name the server, never the secret. +- **Config dialect**: `openclaw.json` is JSON5. Comments, trailing commas, + unquoted keys, and single-quoted strings are expected, so read it through + `scripts/agent-customize/core/json5.mjs` and report an unparsed config instead + of treating it as empty. +- **Not configured inventory**: plugin packages, cron jobs, and internal hooks + have no inventory contract here. + +## Session Evidence + +Live sessions and transcripts are stored in per-agent SQLite +(`agents//agent/openclaw-agent.sqlite`) plus the shared state database, +and this repository does not decode host databases. `agents//sessions/` +holds legacy migration inputs and archive artifacts, not a live transcript +stream. `openclaw sessions export-trajectory` is not an adapter input: it needs a +running Gateway with owner approval and writes into the workspace it exports. +Treat OpenClaw as configured-assets only until a documented, read-only session +format exists. + +## Boundaries + +- No install shell or plugin lifecycle profile exists for OpenClaw here; a + `/better-harness` run needs the skill copied or linked into a native skill + root manually, and lifecycle targets reject `openclaw` with `UNKNOWN_HOST`. +- Per-agent roster fields outside `agents.entries` and + `agents.defaults.workspace` are not resolved. +- Daily memory notes, sandboxed workspaces under the state directory, and remote + workspaces are outside the adapter. diff --git a/references/agent-customize/routing.md b/references/agent-customize/routing.md index 517c8d9c..ffd593ec 100644 --- a/references/agent-customize/routing.md +++ b/references/agent-customize/routing.md @@ -37,7 +37,9 @@ Route by ownership before choosing a vendor-specific feature: `platforms/codex.md`; for Qoder-specific feature taxonomy, then load `platforms/qoder.md`; for Copilot-specific operating practice, then load `platforms/copilot.md`; for Kimi-specific configured-asset scope, then load - `platforms/kimi.md`; for DSH filesystem Skills and cwd-sensitive + `platforms/kimi.md`; for OpenClaw state-directory and + agent-workspace separation, then load `platforms/openclaw.md`; for DSH + filesystem Skills and cwd-sensitive Instructions, then load `platforms/dsh.md`. For installed, user-home, settings screenshot, plugin cache, or memory scope, run the Global/User Asset Pass. diff --git a/scripts/agent-customize/cli.mjs b/scripts/agent-customize/cli.mjs index ce5021c8..09221010 100644 --- a/scripts/agent-customize/cli.mjs +++ b/scripts/agent-customize/cli.mjs @@ -26,6 +26,7 @@ function usage() { `Provider home overrides: ${CUSTOMIZE_HOME_OPTIONS.slice(0, 4).join(", ")},`, `${CUSTOMIZE_HOME_OPTIONS.slice(4).join(", ")}, --claude-state, --codex-app-path, --qoder-shared-client-cache-root.`, "DSH configured-assets options: --cwd , --include-user-home[=].", + "OpenClaw storage options: --openclaw-home , --openclaw-config-path .", "", ].join("\n"); } @@ -49,6 +50,10 @@ function summarize(inventory, options) { piHome: inventory.piHome, workbuddyHome: inventory.workbuddyHome, grokHome: inventory.grokHome, + openclawHome: inventory.openclawHome, + openclawConfigPath: inventory.openclawConfigPath, + openclawWorkspace: inventory.openclawWorkspace, + activeAgentId: inventory.activeAgentId, dshHome: inventory.dshHome, claudeStatePath: inventory.claudeStatePath, kimiHome: inventory.kimiHome, @@ -94,6 +99,7 @@ async function main() { claudeStatePath: options["claude-state"] ?? options["claude-state-path"], codexAppPath: options["codex-app-path"], qoderSharedClientCacheRoot: options["qoder-shared-client-cache-root"] ?? options["shared-client-cache-root"], + openclawConfigPath: options["openclaw-config-path"], workspace: options.workspace, ...(options.provider === "dsh" ? { @@ -101,6 +107,9 @@ async function main() { includeUserHome: parseBooleanFlag(options["include-user-home"] ?? false), } : {}), + ...(options.provider === "openclaw" && options["include-user-home"] !== undefined + ? { includeUserHome: parseBooleanFlag(options["include-user-home"]) } + : {}), }); const payload = command === "manage" diff --git a/scripts/agent-customize/core/json5.mjs b/scripts/agent-customize/core/json5.mjs new file mode 100644 index 00000000..c96ae11f --- /dev/null +++ b/scripts/agent-customize/core/json5.mjs @@ -0,0 +1,173 @@ +/** + * Tolerant reader for the JSON5 dialect OpenClaw uses for openclaw.json. + * + * Only the constructs a hand-edited OpenClaw config relies on are normalized: + * line and block comments, trailing commas, unquoted identifier keys, and + * single-quoted strings. Everything else stays a parse error, so a config this + * reader cannot understand is reported as unparsed instead of being silently + * treated as empty. + */ +import { readFile } from "node:fs/promises"; + +const IDENTIFIER_START = /[A-Za-z_$]/u; +const IDENTIFIER_PART = /[A-Za-z0-9_$]/u; + +function readDoubleQuoted(text, start) { + let index = start + 1; + while (index < text.length) { + if (text[index] === "\\") { + index += 2; + continue; + } + if (text[index] === '"') return index + 1; + index += 1; + } + throw new SyntaxError("unterminated double-quoted string"); +} + +function readSingleQuoted(text, start) { + let literal = '"'; + let index = start + 1; + while (index < text.length) { + const character = text[index]; + if (character === "\\") { + const escaped = text[index + 1]; + if (escaped === undefined) break; + if (escaped === "'") literal += "'"; + else if (escaped === '"') literal += '\\"'; + else literal += `\\${escaped}`; + index += 2; + continue; + } + if (character === "'") return { literal: `${literal}"`, nextIndex: index + 1 }; + if (character === '"') { + literal += '\\"'; + index += 1; + continue; + } + if (character === "\n") break; + literal += character; + index += 1; + } + throw new SyntaxError("unterminated single-quoted string"); +} + +export function normalizeJson5Text(text) { + if (typeof text !== "string") { + throw new TypeError("normalizeJson5Text expects a string"); + } + let output = ""; + let previous = ""; + let index = 0; + while (index < text.length) { + const character = text[index]; + if (character === "/" && text[index + 1] === "/") { + while (index < text.length && text[index] !== "\n") index += 1; + continue; + } + if (character === "/" && text[index + 1] === "*") { + const end = text.indexOf("*/", index + 2); + if (end === -1) throw new SyntaxError("unterminated block comment"); + index = end + 2; + continue; + } + if (character === '"') { + const end = readDoubleQuoted(text, index); + output += text.slice(index, end); + previous = '"'; + index = end; + continue; + } + if (character === "'") { + const { literal, nextIndex } = readSingleQuoted(text, index); + output += literal; + previous = '"'; + index = nextIndex; + continue; + } + if ((previous === "{" || previous === ",") && IDENTIFIER_START.test(character)) { + let end = index + 1; + while (end < text.length && IDENTIFIER_PART.test(text[end])) end += 1; + const identifier = text.slice(index, end); + let cursor = end; + while (cursor < text.length && /\s/u.test(text[cursor])) cursor += 1; + if (text[cursor] === ":") { + output += `"${identifier}"`; + previous = '"'; + } else { + output += identifier; + previous = identifier.at(-1) ?? previous; + } + index = end; + continue; + } + output += character; + if (!/\s/u.test(character)) previous = character; + index += 1; + } + return output; +} + +export function stripTrailingCommas(text) { + let output = ""; + let index = 0; + while (index < text.length) { + const character = text[index]; + if (character === '"') { + const end = readDoubleQuoted(text, index); + output += text.slice(index, end); + index = end; + continue; + } + if (character === ",") { + let cursor = index + 1; + while (cursor < text.length && /\s/u.test(text[cursor])) cursor += 1; + if (text[cursor] === "}" || text[cursor] === "]") { + index += 1; + continue; + } + } + output += character; + index += 1; + } + return output; +} + +export function parseJson5Text(text) { + try { + return { ok: true, value: JSON.parse(text), format: "json" }; + } catch { + // Fall through to the JSON5 subset. + } + try { + return { ok: true, value: JSON.parse(stripTrailingCommas(normalizeJson5Text(text))), format: "json5" }; + } catch (error) { + return { + ok: false, + value: undefined, + format: "invalid", + message: error instanceof Error ? error.message : String(error), + }; + } +} + +export async function readJson5File(filePath) { + let text; + try { + text = await readFile(filePath, "utf8"); + } catch { + return { ok: false, exists: false, value: undefined, format: "missing" }; + } + const parsed = parseJson5Text(text); + if (!parsed.ok) { + // A config that only holds comments is an empty config, not a broken one. + try { + if (stripTrailingCommas(normalizeJson5Text(text)).trim() === "") { + return { ok: true, exists: true, value: {}, format: "empty" }; + } + } catch { + // Keep the original parse failure below. + } + } + return { ...parsed, exists: true }; +} diff --git a/scripts/agent-customize/providers/index.mjs b/scripts/agent-customize/providers/index.mjs index eea97cdc..2697b71c 100644 --- a/scripts/agent-customize/providers/index.mjs +++ b/scripts/agent-customize/providers/index.mjs @@ -5,6 +5,7 @@ import { collectCursorCustomizeInventory } from "./cursor.mjs"; import { collectGrokCustomizeInventory } from "./grok.mjs"; import { collectPiCustomizeInventory } from "./pi.mjs"; import { collectKimiCustomizeInventory } from "./kimi.mjs"; +import { collectOpenClawCustomizeInventory } from "./openclaw.mjs"; import { collectQoderCustomizeInventory } from "./qoder.mjs"; import { collectQwenCustomizeInventory } from "./qwen.mjs"; import { collectWorkbuddyCustomizeInventory } from "./workbuddy.mjs"; @@ -34,6 +35,7 @@ export const PROVIDER_COLLECTORS = new Map([ ["kimi", collectKimiCustomizeInventory], ["workbuddy", collectWorkbuddyCustomizeInventory], ["grok", collectGrokCustomizeInventory], + ["openclaw", collectOpenClawCustomizeInventory], ["dsh", collectDshCustomizeInventory], ]); diff --git a/scripts/agent-customize/providers/openclaw.mjs b/scripts/agent-customize/providers/openclaw.mjs new file mode 100644 index 00000000..cf0d8ba4 --- /dev/null +++ b/scripts/agent-customize/providers/openclaw.mjs @@ -0,0 +1,285 @@ +/** + * OpenClaw configured-asset inventory. + * + * OpenClaw separates two storage families: + * - state directory: OPENCLAW_STATE_DIR or ~/.openclaw, holding openclaw.json, + * managed skills, and per-agent runtime state + * - agent workspace: the agent's home directory holding instruction files and + * workspace skills + * + * Live sessions and transcripts live in per-agent SQLite, so this adapter stays + * read-only, never decodes a database, and never runs `openclaw sessions + * export-trajectory` (that command mutates the workspace it exports from). + */ +import os from "node:os"; +import path from "node:path"; + +import { expandHome, normalizeWorkspace, pathExists } from "../../session-analysis/index.mjs"; +import { MANAGE_TABS } from "../constants.mjs"; +import { readJson5File } from "../core/json5.mjs"; +import { + buildManageCollections, + collectMcpFromValue, + collectRuleSources, + collectSkillFiles, + listDirectories, + sortByName, + workspaceSourceLabel, +} from "../core/items.mjs"; + +const NATIVE_HIDDEN_DIR = ".openclaw"; + +/** + * Bootstrap files OpenClaw loads into every session from the agent workspace. + * Daily memory notes under memory/ are intentionally left out: they are + * per-day logs, not standing instructions. + */ +const WORKSPACE_INSTRUCTION_FILES = ["AGENTS.md", "SOUL.md", "USER.md", "IDENTITY.md", "MEMORY.md", "BOOT.md"]; + +export function defaultOpenClawHome() { + const stateDir = process.env.OPENCLAW_STATE_DIR; + if (stateDir && stateDir.trim() !== "") return stateDir; + const profile = process.env.OPENCLAW_PROFILE; + const directory = + profile && profile.trim() !== "" && profile !== "default" ? `${NATIVE_HIDDEN_DIR}-${profile}` : NATIVE_HIDDEN_DIR; + return path.join(os.homedir(), directory); +} + +export function defaultOpenClawConfigPath(stateDir = defaultOpenClawHome()) { + const configPath = process.env.OPENCLAW_CONFIG_PATH; + if (configPath && configPath.trim() !== "") return configPath; + return path.join(stateDir, "openclaw.json"); +} + +export function openClawMcpServersFromConfig(config) { + if (!config || typeof config !== "object" || Array.isArray(config)) return null; + const section = config.mcp; + if (!section || typeof section !== "object" || Array.isArray(section)) return null; + const servers = section.servers; + return servers && typeof servers === "object" && !Array.isArray(servers) ? servers : null; +} + +/** + * OpenClaw names the remote transport `transport`; the shared MCP item shape + * keeps a single `type` field, so carry the host's name across. + */ +function normalizeTransportType(servers) { + const normalized = {}; + for (const [name, value] of Object.entries(servers)) { + const server = value && typeof value === "object" && !Array.isArray(value) ? value : null; + normalized[name] = server && server.type === undefined && typeof server.transport === "string" + ? { ...server, type: server.transport } + : value; + } + return normalized; +} + +/** + * Resolve every configured agent workspace. The default workspace applies to a + * sole agent and to the base of an unpinned multi-agent roster, matching the + * resolution order the agent-workspace docs describe. + */ +export function resolveOpenClawAgentWorkspaces(config, stateDir, env = process.env) { + const agents = config?.agents && typeof config.agents === "object" && !Array.isArray(config.agents) + ? config.agents + : {}; + const defaults = agents.defaults && typeof agents.defaults === "object" && !Array.isArray(agents.defaults) + ? agents.defaults + : {}; + const entries = agents.entries && typeof agents.entries === "object" && !Array.isArray(agents.entries) + ? agents.entries + : {}; + const envWorkspace = typeof env.OPENCLAW_WORKSPACE_DIR === "string" && env.OPENCLAW_WORKSPACE_DIR.trim() !== "" + ? env.OPENCLAW_WORKSPACE_DIR.trim() + : null; + const configuredRoot = typeof defaults.workspace === "string" && defaults.workspace.trim() !== "" + ? defaults.workspace.trim() + : null; + const workspaceRoot = envWorkspace ?? configuredRoot; + const rootSource = envWorkspace ? "env" : "defaults"; + const agentIds = Object.keys(entries); + const defaultWorkspace = path.resolve(expandHome(workspaceRoot ?? path.join(stateDir, "workspace"))); + + if (agentIds.length === 0) { + return [{ agentId: "main", workspace: defaultWorkspace, source: workspaceRoot ? rootSource : "default" }]; + } + if (agentIds.length === 1) { + const entry = entries[agentIds[0]] && typeof entries[agentIds[0]] === "object" ? entries[agentIds[0]] : {}; + const pinned = typeof entry.workspace === "string" && entry.workspace.trim() !== "" ? entry.workspace.trim() : null; + return [{ + agentId: agentIds[0], + workspace: pinned ? path.resolve(expandHome(pinned)) : defaultWorkspace, + source: pinned ? "entry" : workspaceRoot ? rootSource : "default", + }]; + } + return agentIds.map((agentId) => { + const entry = entries[agentId] && typeof entries[agentId] === "object" ? entries[agentId] : {}; + const pinned = typeof entry.workspace === "string" && entry.workspace.trim() !== "" ? entry.workspace.trim() : null; + if (pinned) { + return { agentId, workspace: path.resolve(expandHome(pinned)), source: "entry" }; + } + return { + agentId, + workspace: workspaceRoot + ? path.resolve(expandHome(path.join(workspaceRoot, agentId))) + : path.resolve(stateDir, `workspace-${agentId}`), + source: workspaceRoot ? rootSource : "state-dir", + }; + }); +} + +function isInsideOrEqual(candidate, root) { + const relative = path.relative(root, candidate); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); +} + +export function matchOpenClawAgentWorkspace(agentWorkspaces, workspace) { + const resolved = path.resolve(workspace); + const matches = agentWorkspaces.filter((entry) => isInsideOrEqual(resolved, entry.workspace)); + matches.sort((left, right) => right.workspace.length - left.workspace.length); + return matches[0] ?? null; +} + +function emptyPrimitives() { + return { skills: [], subagents: [], rules: [], commands: [], hooks: [], mcps: [] }; +} + +async function collectOpenClawUserPrimitives({ stateDir, personalSkillsDir, config, configPath, includeUserHome }) { + if (!includeUserHome) return emptyPrimitives(); + const skills = await collectSkillFiles(path.join(stateDir, "skills"), "user", "User", stateDir); + for (const agentDir of await listDirectories(path.join(stateDir, "agents"))) { + skills.push(...(await collectSkillFiles( + path.join(agentDir, "agent", "workshop-skills"), "user", "User", stateDir, + ))); + } + if (personalSkillsDir) { + skills.push(...(await collectSkillFiles(personalSkillsDir, "user", "User", personalSkillsDir))); + } + const servers = openClawMcpServersFromConfig(config); + return { + skills: skills.sort(sortByName), + subagents: [], + rules: [], + commands: [], + hooks: [], + mcps: servers ? collectMcpFromValue(normalizeTransportType(servers), "user", "User", configPath, stateDir) : [], + }; +} + +async function collectOpenClawWorkspacePrimitives(workspace) { + const sourceLabel = await workspaceSourceLabel(workspace); + const [workspaceSkills, standardSkills, rules] = await Promise.all([ + collectSkillFiles(path.join(workspace, "skills"), "project", sourceLabel, workspace), + collectSkillFiles(path.join(workspace, ".agents", "skills"), "project", sourceLabel, workspace), + collectRuleSources( + WORKSPACE_INSTRUCTION_FILES.map((name) => ({ + type: "file", + filePath: path.join(workspace, name), + scope: "project", + sourceLabel, + rootForEvidence: workspace, + name, + sourceKind: "openclaw-workspace-instruction", + precedence: "before-project-rules", + useHeading: true, + exactName: true, + })), + ), + ]); + return { + skills: [...workspaceSkills, ...standardSkills].sort(sortByName), + subagents: [], + rules, + commands: [], + hooks: [], + mcps: [], + }; +} + +export async function collectOpenClawCustomizeInventory(options = {}) { + const requestedHome = options.openclawHome ?? options["openclaw-home"]; + const usingDefaultStateDir = requestedHome === undefined || requestedHome === null; + const openclawHome = path.resolve(expandHome( + usingDefaultStateDir ? defaultOpenClawHome() : requestedHome, + )); + const openclawConfigPath = path.resolve(expandHome( + options.openclawConfigPath + ?? options["openclaw-config-path"] + ?? defaultOpenClawConfigPath(openclawHome), + )); + const workspace = normalizeWorkspace(options.workspace ?? process.cwd()); + const includeUserHome = options.includeUserHome !== false; + const configRead = includeUserHome + ? await readJson5File(openclawConfigPath) + : { ok: false, exists: false, value: undefined, format: "skipped" }; + const config = configRead.ok ? configRead.value : undefined; + const agentWorkspaces = resolveOpenClawAgentWorkspaces(config, openclawHome); + const matchedAgent = configRead.ok ? matchOpenClawAgentWorkspace(agentWorkspaces, workspace) : null; + // Without a readable config there is no roster to attribute against; treat + // the requested workspace as the agent workspace so a restricted run still + // reports the files OpenClaw would load from it. + const activeAgent = matchedAgent ?? (configRead.ok ? null : { agentId: null, workspace }); + const personalSkillsDir = includeUserHome && usingDefaultStateDir && !process.env.OPENCLAW_STATE_DIR + ? path.join(os.homedir(), ".agents", "skills") + : null; + + const [user, project] = await Promise.all([ + collectOpenClawUserPrimitives({ + stateDir: openclawHome, + personalSkillsDir, + config, + configPath: openclawConfigPath, + includeUserHome, + }), + activeAgent ? collectOpenClawWorkspacePrimitives(activeAgent.workspace) : emptyPrimitives(), + ]); + + return { + generatedAt: new Date().toISOString(), + provider: "openclaw", + openclawHome, + openclawConfigPath, + openclawWorkspace: activeAgent?.workspace ?? null, + activeAgentId: activeAgent?.agentId ?? null, + workspace, + tabs: MANAGE_TABS, + plugins: [], + manage: buildManageCollections([], user, project), + diagnostics: { + // OpenClaw installs plugin packages, but this adapter does not execute or + // inventory them; keep the empty state explicit. + installedPluginState: "unsupported", + installedPluginRecordCount: 0, + installedPluginRecordFiles: [], + remotePluginInstallMarkersRequired: false, + configPath: includeUserHome ? openclawConfigPath : null, + configParseState: configRead.format, + configParseMessage: configRead.ok ? null : configRead.message ?? null, + managedSkillsDir: includeUserHome ? path.join(openclawHome, "skills") : null, + personalSkillsDir, + workspaceRoot: workspace, + // Only a config-backed roster is reported; a restricted run must not + // imply it resolved agent workspaces from a config it never read. + agentWorkspaces: configRead.ok + ? agentWorkspaces.map((entry) => ({ + agentId: entry.agentId, + workspace: entry.workspace, + source: entry.source, + active: matchedAgent?.agentId === entry.agentId, + })) + : [], + exists: Boolean(await pathExists(openclawHome)), + }, + unsupported: [ + "live sessions and transcripts stored in per-agent openclaw-agent.sqlite and shared state SQLite", + "legacy session archives under agents//sessions", + "plugin packages and cron jobs configured under the state directory", + "daily memory notes under memory/ in each agent workspace", + "MCP header and env values in openclaw.json", + "agent roster fields outside agents.entries and agents.defaults.workspace", + ...(activeAgent + ? [] + : [`project scope skipped: ${workspace} is not a configured OpenClaw agent workspace`]), + ], + }; +} diff --git a/scripts/host-support/index.mjs b/scripts/host-support/index.mjs index 88b69b13..f75746d7 100644 --- a/scripts/host-support/index.mjs +++ b/scripts/host-support/index.mjs @@ -114,6 +114,15 @@ export const HOST_DESCRIPTORS = Object.freeze([ capabilities: COMMON_CAPABILITIES, sessionScopeTokens: [".grok", "grok"], }), + descriptor({ + id: "openclaw", + displayName: "OpenClaw", + aliases: ["Clawdbot", "Moltbot"], + capabilities: [ + HOST_CAPABILITIES.AGENT_CUSTOMIZE, + HOST_CAPABILITIES.REPORT_RENDERING, + ], + }), descriptor({ id: "dsh", displayName: "DeepSeek Harness", diff --git a/templates/reporting/routing.md b/templates/reporting/routing.md index 252f55d2..82b847d6 100644 --- a/templates/reporting/routing.md +++ b/templates/reporting/routing.md @@ -29,6 +29,6 @@ files from other routes. | --- | --- | --- | --- | | Qoder Canvas report | Active host is Qoder | renderer-owned `findings.json`, `canvas.json`, `report.canvas.tsx` | `qoder-canvas.md` | | Cursor Canvas report | Active host is Cursor | renderer-owned `findings.json`, `canvas.json`, `report.canvas.tsx` | `cursor-canvas.md` | -| Portable HTML report | Active host is Claude Code, Codex, Qwen Code, GitHub Copilot, Pi, Kimi Code, WorkBuddy, Grok, or DeepSeek Harness, or a portable visual is explicitly requested | renderer-owned `findings.json`, `report.md`, `report.html` | `html-visual.md` | +| Portable HTML report | Active host is Claude Code, Codex, Qwen Code, GitHub Copilot, Pi, Kimi Code, WorkBuddy, Grok, OpenClaw, or DeepSeek Harness, or a portable visual is explicitly requested | renderer-owned `findings.json`, `report.md`, `report.html` | `html-visual.md` | | Markdown only | Markdown without a visual companion is explicitly requested | `report.md`, `findings.json` | none | | Inline only | Inline or no-files output is explicitly requested | none; inline analysis writes nothing | none | diff --git a/test/agents/agent-customize.test.mjs b/test/agents/agent-customize.test.mjs index 6f587d5a..2ed6772b 100644 --- a/test/agents/agent-customize.test.mjs +++ b/test/agents/agent-customize.test.mjs @@ -3226,3 +3226,223 @@ test("Grok project skills dedupe when .grok/skills symlinks to .agents/skills", await rm(root, { recursive: true, force: true }); } }); + +async function makeOpenClawFixture() { + const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-openclaw-")); + const openclawHome = path.join(root, ".openclaw"); + const workspacesRoot = path.join(root, "workspaces"); + const mainWorkspace = path.join(workspacesRoot, "main"); + const opsWorkspace = path.join(root, "ops-workspace"); + const configPath = path.join(openclawHome, "openclaw.json"); + + // openclaw.json is JSON5: comments, bare keys, trailing commas, and + // single-quoted strings all appear in hand-edited configs. + await writeText( + configPath, + `{ + // single-agent roster keeps the default workspace + mcp: { + /* remote servers carry transport instead of type */ + servers: { + docs: { command: 'npx', args: ['-y', 'docs-mcp'], env: { DOCS_TOKEN: 'sk-live-0123456789abcdef' }, }, + remote: { url: 'https://mcp.example.com/sse', transport: 'http' }, + offline: { command: 'offline-mcp', enabled: false }, + }, + }, + agents: { + defaults: { workspace: '${workspacesRoot}' }, + entries: { + main: {}, + ops: { workspace: '${opsWorkspace}' }, + }, + }, +} +`, + ); + + await writeText( + path.join(openclawHome, "skills", "managed-a", "SKILL.md"), + "---\nname: managed-a\ndescription: Managed skill.\n---\n", + ); + await writeText( + path.join(openclawHome, "agents", "main", "agent", "workshop-skills", "workshop-a", "SKILL.md"), + "---\nname: workshop-a\ndescription: Agent workshop skill.\n---\n", + ); + await writeText(path.join(mainWorkspace, "AGENTS.md"), "# Main agent instructions\n"); + await writeText(path.join(mainWorkspace, "SOUL.md"), "# Persona\n"); + await writeText( + path.join(mainWorkspace, "skills", "local-a", "SKILL.md"), + "---\nname: local-a\ndescription: Workspace skill.\n---\n", + ); + await writeText( + path.join(mainWorkspace, ".agents", "skills", "standard-a", "SKILL.md"), + "---\nname: standard-a\ndescription: Shared Agent Skills standard.\n---\n", + ); + await writeText(path.join(mainWorkspace, "memory", "2026-11-23.md"), "Daily log entry.\n"); + await writeText( + path.join(opsWorkspace, "skills", "ops-a", "SKILL.md"), + "---\nname: ops-a\ndescription: Ops workspace skill.\n---\n", + ); + + return { root, openclawHome, configPath, workspacesRoot, mainWorkspace, opsWorkspace }; +} + +test("OpenClaw inventory reads MCP servers, managed skills, and the active agent workspace", async () => { + const fixture = await makeOpenClawFixture(); + try { + const inventory = await collectAgentCustomizeInventory({ + provider: "openclaw", + openclawHome: fixture.openclawHome, + workspace: path.join(fixture.mainWorkspace, "projects", "site"), + }); + + assert.equal(inventory.provider, "openclaw"); + assert.equal(inventory.openclawHome, fixture.openclawHome); + assert.equal(inventory.openclawConfigPath, fixture.configPath); + assert.equal(inventory.diagnostics.configParseState, "json5"); + assert.equal(inventory.diagnostics.personalSkillsDir, null); + assert.equal(inventory.diagnostics.installedPluginState, "unsupported"); + assert.deepEqual(inventory.plugins, []); + assert.equal(inventory.activeAgentId, "main"); + assert.equal(inventory.openclawWorkspace, fixture.mainWorkspace); + assert.deepEqual( + inventory.diagnostics.agentWorkspaces.map((entry) => [entry.agentId, entry.source, entry.active]), + [["main", "defaults", true], ["ops", "entry", false]], + ); + + const userSkills = filterManageItems(inventory, { tab: "skills", scopeKind: "user" }) + .map((item) => item.name) + .sort(); + assert.deepEqual(userSkills, ["managed-a", "workshop-a"]); + assert.deepEqual( + filterManageItems(inventory, { tab: "skills", scopeKind: "project" }).map((item) => item.name).sort(), + ["local-a", "standard-a"], + ); + + const projectRules = filterManageItems(inventory, { tab: "rules", scopeKind: "project" }) + .map((item) => item.name) + .sort(); + assert.deepEqual(projectRules, ["AGENTS.md", "SOUL.md"]); + + const mcps = filterManageItems(inventory, { tab: "mcps", scopeKind: "user" }); + assert.equal(mcps.find((item) => item.name === "docs")?.enabled, true); + assert.equal(mcps.find((item) => item.name === "offline")?.enabled, false); + assert.equal(mcps.find((item) => item.name === "remote")?.type, "http"); + + // Credentials may be named but their values must never be serialized. + assert.doesNotMatch(JSON.stringify(inventory), /sk-live-[A-Za-z0-9]+/u); + assert.ok(inventory.unsupported.some((item) => /openclaw-agent\.sqlite/u.test(item))); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("OpenClaw inventory attributes the requested workspace to its agent", async () => { + const fixture = await makeOpenClawFixture(); + try { + const inventory = await collectAgentCustomizeInventory({ + provider: "openclaw", + openclawHome: fixture.openclawHome, + workspace: fixture.opsWorkspace, + }); + assert.equal(inventory.activeAgentId, "ops"); + assert.equal(inventory.openclawWorkspace, fixture.opsWorkspace); + assert.deepEqual( + filterManageItems(inventory, { tab: "skills", scopeKind: "project" }).map((item) => item.name), + ["ops-a"], + ); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("OpenClaw inventory skips project scope outside any configured agent workspace", async () => { + const fixture = await makeOpenClawFixture(); + try { + const inventory = await collectAgentCustomizeInventory({ + provider: "openclaw", + openclawHome: fixture.openclawHome, + workspace: fixture.root, + }); + assert.equal(inventory.activeAgentId, null); + assert.deepEqual(filterManageItems(inventory, { tab: "skills", scopeKind: "project" }), []); + assert.ok(inventory.unsupported.some((item) => /not a configured OpenClaw agent workspace/u.test(item))); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("OpenClaw inventory without user-home authority reports workspace files only", async () => { + const fixture = await makeOpenClawFixture(); + try { + const inventory = await collectAgentCustomizeInventory({ + provider: "openclaw", + openclawHome: fixture.openclawHome, + workspace: fixture.mainWorkspace, + includeUserHome: false, + }); + assert.equal(inventory.diagnostics.configPath, null); + assert.equal(inventory.diagnostics.configParseState, "skipped"); + assert.deepEqual(inventory.diagnostics.agentWorkspaces, []); + assert.deepEqual(filterManageItems(inventory, { tab: "skills", scopeKind: "user" }), []); + assert.deepEqual(filterManageItems(inventory, { tab: "mcps", scopeKind: "user" }), []); + assert.deepEqual( + filterManageItems(inventory, { tab: "skills", scopeKind: "project" }).map((item) => item.name).sort(), + ["local-a", "standard-a"], + ); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("OpenClaw inventory reports a config it cannot parse instead of an empty one", async () => { + const fixture = await makeOpenClawFixture(); + try { + await writeText(fixture.configPath, "{ agents: { defaults: { workspace: /srv/openclaw } } }\n"); + const inventory = await collectAgentCustomizeInventory({ + provider: "openclaw", + openclawHome: fixture.openclawHome, + workspace: fixture.mainWorkspace, + }); + assert.equal(inventory.diagnostics.configParseState, "invalid"); + assert.equal(typeof inventory.diagnostics.configParseMessage, "string"); + assert.deepEqual(filterManageItems(inventory, { tab: "mcps", scopeKind: "user" }), []); + assert.deepEqual( + filterManageItems(inventory, { tab: "skills", scopeKind: "project" }).map((item) => item.name).sort(), + ["local-a", "standard-a"], + ); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("agent-customize CLI honours --openclaw-home and --openclaw-config-path", async () => { + const fixture = await makeOpenClawFixture(); + try { + const result = runAgentCustomizeCli([ + "inventory", + "--provider", + "openclaw", + "--workspace", + fixture.mainWorkspace, + "--openclaw-home", + fixture.openclawHome, + "--openclaw-config-path", + fixture.configPath, + ]); + assert.equal( + result.status, + 0, + JSON.stringify({ signal: result.signal, error: result.error?.code, stderr: result.stderr?.slice(0, 200) }), + ); + const inventory = JSON.parse(result.stdout); + assert.equal(inventory.openclawHome, fixture.openclawHome); + assert.equal(inventory.openclawConfigPath, fixture.configPath); + assert.equal(inventory.activeAgentId, "main"); + assert.notEqual(inventory.openclawHome, path.join(os.homedir(), ".openclaw")); + assert.ok(inventory.manage.skills.some((item) => item.name === "managed-a")); + assert.doesNotMatch(result.stdout, /sk-live-[A-Za-z0-9]+/u); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); diff --git a/test/agents/json5-config-reader.test.mjs b/test/agents/json5-config-reader.test.mjs new file mode 100644 index 00000000..2f9d1909 --- /dev/null +++ b/test/agents/json5-config-reader.test.mjs @@ -0,0 +1,90 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { test } from "vitest"; + +import { + normalizeJson5Text, + parseJson5Text, + readJson5File, + stripTrailingCommas, +} from "../../scripts/agent-customize/core/json5.mjs"; + +test("parseJson5Text leaves valid JSON on the strict path", () => { + const result = parseJson5Text('{"mcp":{"servers":{}}}'); + assert.equal(result.format, "json"); + assert.deepEqual(result.value, { mcp: { servers: {} } }); +}); + +test("parseJson5Text reads comments, trailing commas, bare keys, and single quotes", () => { + const text = `{ + // managed servers + mcp: { + /* nested block comment */ + servers: { + docs: { command: 'npx', args: ['-y', 'docs-mcp'], }, + remote: { url: "https://mcp.example.com/sse" }, + offline: { command: 'offline-mcp', enabled: false }, + }, + }, + }`; + const result = parseJson5Text(text); + assert.equal(result.format, "json5", result.message); + assert.deepEqual(result.value, { + mcp: { + servers: { + docs: { command: "npx", args: ["-y", "docs-mcp"] }, + remote: { url: "https://mcp.example.com/sse" }, + offline: { command: "offline-mcp", enabled: false }, + }, + }, + }); +}); + +test("parseJson5Text keeps comment and comma markers that live inside strings", () => { + const text = `{ + note: "https://example.com//path?q=1", // real comment + pattern: "a,}", + quoted: 'say "hi"', + escaped: 'it\\'s', + }`; + const result = parseJson5Text(text); + assert.equal(result.format, "json5", result.message); + assert.equal(result.value.note, "https://example.com//path?q=1"); + assert.equal(result.value.pattern, "a,}"); + assert.equal(result.value.quoted, 'say "hi"'); + assert.equal(result.value.escaped, "it's"); +}); + +test("parseJson5Text reports text it cannot normalize instead of returning an empty config", () => { + const result = parseJson5Text("{ agents: { defaults: { workspace: /opt/agents } } }"); + assert.equal(result.ok, false); + assert.equal(result.format, "invalid"); + assert.equal(typeof result.message, "string"); +}); + +test("stripTrailingCommas leaves arrays and nested closings intact", () => { + assert.equal(stripTrailingCommas('{"a":[1,2,],"b":{"c":3,},}'), '{"a":[1,2],"b":{"c":3}}'); + assert.equal(stripTrailingCommas('{"a":"x,}"}'), '{"a":"x,}"}'); + assert.equal(normalizeJson5Text('{"a":1}'), '{"a":1}'); +}); + +test("readJson5File separates empty and missing config files", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-json5-")); + try { + const empty = path.join(root, "empty.json"); + await writeFile(empty, " \n// nothing configured yet\n"); + const emptyResult = await readJson5File(empty); + assert.equal(emptyResult.ok, true); + assert.equal(emptyResult.exists, true); + assert.deepEqual(emptyResult.value, {}); + + const missingResult = await readJson5File(path.join(root, "missing.json")); + assert.equal(missingResult.ok, false); + assert.equal(missingResult.exists, false); + assert.equal(missingResult.format, "missing"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); From 2a643d84dad138373a51755e696aee3d9998af50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=9C=8F=E6=89=BF?= Date: Mon, 23 Nov 2026 15:32:13 +0800 Subject: [PATCH 2/2] test(agents): escape backslashes in the OpenClaw JSON5 fixture Windows CI reported the fixture config as unparsed. mkdtemp hands back a C:\Users\... path, and a raw path inside a single-quoted JSON5 string turns \U into an invalid escape, so the whole config was rejected and the four OpenClaw tests that depend on it failed on windows-latest. Escape the embedded paths and pin the escaped Windows path in the JSON5 reader tests so the case runs on every platform. Co-authored-by: Qoder --- test/agents/agent-customize.test.mjs | 6 ++++-- test/agents/json5-config-reader.test.mjs | 7 +++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/test/agents/agent-customize.test.mjs b/test/agents/agent-customize.test.mjs index 2ed6772b..5cb9a081 100644 --- a/test/agents/agent-customize.test.mjs +++ b/test/agents/agent-customize.test.mjs @@ -3234,6 +3234,8 @@ async function makeOpenClawFixture() { const mainWorkspace = path.join(workspacesRoot, "main"); const opsWorkspace = path.join(root, "ops-workspace"); const configPath = path.join(openclawHome, "openclaw.json"); + // Windows temp paths carry backslashes, which a JSON5 string reads as escapes. + const asJson5String = (value) => value.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'"); // openclaw.json is JSON5: comments, bare keys, trailing commas, and // single-quoted strings all appear in hand-edited configs. @@ -3250,10 +3252,10 @@ async function makeOpenClawFixture() { }, }, agents: { - defaults: { workspace: '${workspacesRoot}' }, + defaults: { workspace: '${asJson5String(workspacesRoot)}' }, entries: { main: {}, - ops: { workspace: '${opsWorkspace}' }, + ops: { workspace: '${asJson5String(opsWorkspace)}' }, }, }, } diff --git a/test/agents/json5-config-reader.test.mjs b/test/agents/json5-config-reader.test.mjs index 2f9d1909..697ab4e6 100644 --- a/test/agents/json5-config-reader.test.mjs +++ b/test/agents/json5-config-reader.test.mjs @@ -64,6 +64,13 @@ test("parseJson5Text reports text it cannot normalize instead of returning an em assert.equal(typeof result.message, "string"); }); +test("parseJson5Text reads an escaped Windows path the way a config writer stores it", () => { + const text = String.raw`{ agents: { defaults: { workspace: 'C:\\Users\\dev\\.openclaw' } } }`; + const result = parseJson5Text(text); + assert.equal(result.format, "json5", result.message); + assert.equal(result.value.agents.defaults.workspace, String.raw`C:\Users\dev\.openclaw`); +}); + test("stripTrailingCommas leaves arrays and nested closings intact", () => { assert.equal(stripTrailingCommas('{"a":[1,2,],"b":{"c":3,},}'), '{"a":[1,2],"b":{"c":3}}'); assert.equal(stripTrailingCommas('{"a":"x,}"}'), '{"a":"x,}"}');