diff --git a/CHANGELOG.md b/CHANGELOG.md index bba2fec0..57a95a80 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,13 @@ observable behavior and compatibility, not every internal refactor. ### Added +- BitFun (OpenBitFun) joins as a partial source-local host: a configured-asset + provider covers user skills, agents, `config/app.json` MCP servers, hooks, and + project `.openbitfun` plus `.agents` assets, and a session-evidence adapter + reads `~/.openbitfun/projects/*/sessions/*/` metadata and turn files with + `--bitfun-home`/`OPENBITFUN_HOME` overrides. No install shell, plugin + lifecycle, or native smoke claim ships with it. + - DeepSeek Harness now ships a host shell bundle entry so `dsh plugin --profile add @qoder-ai/better-harness` registers skill discovery and the explicit-only policy automatically, replacing the manual diff --git a/README.md b/README.md index 282656e4..677daa99 100644 --- a/README.md +++ b/README.md @@ -39,8 +39,8 @@ invocation, and report-output steps. Better Harness does not use one universal entrypoint across every host. This README shows inline setup for the most common hosts. Additional supported -hosts (Qwen Code, Pi, Kimi Code, WorkBuddy, and Grok) keep their steps and -boundaries in the [installation guide](docs/docs/installation.mdx) and the +hosts (Qwen Code, Pi, Kimi Code, WorkBuddy, Grok, and BitFun) keep their steps +and boundaries in the [installation guide](docs/docs/installation.mdx) and the [public Host Adapter Matrix](docs/docs/hosts/adapter-matrix.md); see [More adapters](#more-adapters). README placement is a display choice, not a support-level claim. @@ -384,12 +384,14 @@ 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. BitFun likewise has no lifecycle profile: lifecycle targets reject it +with `UNKNOWN_HOST`, while its configured-asset and session evidence stay +available. ### 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 BitFun. 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 +404,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). +- **BitFun** — [Host Adapter Matrix](docs/docs/hosts/adapter-matrix.md#bitfun) + (partial adapter: configured assets and session evidence only; skills install + into the OpenBitFun user skills dir). 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..7cf0ff32 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 与 BitFun)的步骤与边界保留在 [安装指南](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 插件生命周期入口。BitFun 同样没有生命周期 +profile:生命周期目标会以 `UNKNOWN_HOST` 拒绝,而它的已配置资产与会话证据仍然可用。 ### 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 与 BitFun。它们确切的安装、调用与证据边界都放在文档里,以保持本 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)。 +- **BitFun** —— [宿主适配器矩阵](docs/docs/hosts/adapter-matrix.md#bitfun) + (部分适配器:仅已配置资产与会话证据;Skill 需安装到 OpenBitFun 用户 Skill 目录)。 它们都产出自包含的 `report.html` 及配套的 `report.md` 与 `findings.json`; 缺失或不完整的会话证据会被明确标注。 diff --git a/docs/adapters/README.md b/docs/adapters/README.md index 0ebb3c06..ecec20db 100644 --- a/docs/adapters/README.md +++ b/docs/adapters/README.md @@ -1,7 +1,7 @@ # 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 +Cursor, Qwen, GitHub Copilot, Pi, Kimi Code, WorkBuddy, Grok, and BitFun host boundaries, plus the DeepSeek Harness (DSH) verified install/discovery, developer-preview configured-assets, session, Asset Practices, neutral Harness analysis, and @@ -9,8 +9,8 @@ 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/bitfun.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 | +| BitFun | Partial source-local host | none (skills install into the OpenBitFun user skills dir) | `scripts/agent-customize/providers/bitfun.mjs` | `scripts/session-analysis/platforms/bitfun.mjs` | self-contained HTML + Markdown | user `agents/` + `config/app.json` MCP + `config/hooks.json` + project `.openbitfun` + `.agents` + 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,11 @@ 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, BitFun, 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, +Grok, and BitFun retain their configured-asset and session evidence. 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 +222,19 @@ 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`). +- BitFun configured assets are inventoried through + `scripts/agent-customize/providers/bitfun.mjs`, covering the OpenBitFun user + skills dir (builtin `.system` skills excluded), user `agents/`, `config/app.json` + MCP servers, `config/hooks.json`, the shared `.agents/skills` directories, and + project `.openbitfun` skills, agents, rules, and hooks plus `AGENTS.md` and the + compatibility instruction files. Session evidence comes from + `scripts/session-analysis/platforms/bitfun.mjs`, which scans + `~/.openbitfun/projects//sessions//` and trusts each + `metadata.json` workspace field instead of reimplementing the runtime project + key; turns are read from `turns/turn-%04d.json`. The adapter honors + `OPENBITFUN_HOME` and `--bitfun-home`. BitFun has no install shell, plugin + lifecycle, or native smoke evidence in this repository, so it 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 +331,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/BitFun/DeepSeek Harness visual output contract, covering `findings.json`, `report.md`, and `report.html`. - Markdown-only output has no visual companion. diff --git a/docs/concepts.md b/docs/concepts.md index c2a8eb94..24bb998b 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -73,7 +73,7 @@ until you need diagnosis. See [../models/routing.md](../models/routing.md). | Project evidence | `better-harness core-change-watch` | Project, history, core-path, and diff signals | | Change confidence | `hooks/git-scripts/blast-radius` | Symbol-graph blast radius of a change | | Dependency governance | `better-harness dependency-governance` | Update automation, audit, stale-dep signals | -| Session evidence | `better-harness session-analysis` | Normalize Qoder, Codex, Claude, Augment/Auggie, Cursor, Qwen, Copilot, Pi, Kimi Code, or WorkBuddy session behavior | +| Session evidence | `better-harness session-analysis` | Normalize Qoder, Codex, Claude, Augment/Auggie, Cursor, Qwen, Copilot, Pi, Kimi Code, WorkBuddy, Grok, or BitFun session behavior | | Agent assets | `better-harness coding-agent-practices inventory` | Inventory configured agent surfaces | | Guardrails | `hooks/`, `scripts/agent-guardrails` | Secret scanning and lifecycle checks | diff --git a/docs/docs/concepts/harness-inspector.md b/docs/docs/concepts/harness-inspector.md index 01c3dc65..5de1bb0c 100644 --- a/docs/docs/concepts/harness-inspector.md +++ b/docs/docs/concepts/harness-inspector.md @@ -92,8 +92,8 @@ The default output is: Useful bounds include `--platform`, `--since`, `--until`, `--commits`, and `--max-sessions`. `--platform all` discovers evidence across Qoder, Codex, -Claude Code, Cursor, Qwen Code, GitHub Copilot, Pi, Kimi Code, WorkBuddy, and -Grok, while preserving provider-specific gaps. +Claude Code, Cursor, Qwen Code, GitHub Copilot, Pi, Kimi Code, WorkBuddy, Grok, +and BitFun, while preserving provider-specific gaps. An optional `.better-harness/feature-tree.md` supplies reviewed intent: diff --git a/docs/docs/hosts/adapter-matrix.md b/docs/docs/hosts/adapter-matrix.md index 4569cf94..df02e270 100644 --- a/docs/docs/hosts/adapter-matrix.md +++ b/docs/docs/hosts/adapter-matrix.md @@ -14,10 +14,11 @@ 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 BitFun +configured-assets plus session evidence), and 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 +Six have verified public Quickstart paths. Pi, Kimi Code, WorkBuddy, Grok, and +BitFun 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 @@ -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 | +| BitFun | Partial adapter | Configured-assets and session evidence only; no install or lifecycle claim | None; skills use OpenBitFun-owned paths | Workspace-matching BitFun session dirs under `~/.openbitfun/projects/` | 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 @@ -67,8 +69,8 @@ steps without executing them. Qoder Desktop remains bundled, Codex Desktop uses manual UI steps, Cursor installation stays unavailable while its local help 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 +returns `PLUGIN_LIFECYCLE_UNSUPPORTED`. Kimi Code, Grok, and BitFun have no +validated native lifecycle contract yet, so lifecycle targets reject them with `UNKNOWN_HOST` while their adapter evidence stays available. DSH likewise has no lifecycle profile: lifecycle targets reject it with `UNKNOWN_HOST`; its manually configured verified discovery and partial session evidence remain @@ -82,7 +84,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/BitFun/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 +168,20 @@ 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. +### BitFun {#bitfun} + +BitFun configured assets and workspace-matched session evidence are implemented, +and portable HTML routing reuses the generic Better Harness-owned root. The +adapter treats the product home (`~/.openbitfun` or `OPENBITFUN_HOME`), the +platform user root, and the project `.openbitfun` directory as separate storage +families. Discovery scans +`projects//sessions//metadata.json` and trusts its +recorded workspace fields instead of reimplementing the host-owned project key; +sessions of unknown shape still appear with explicit metadata coverage. This +repository does not ship a BitFun install shell, plugin lifecycle profile, or +npm-packaged host artifact, and no native smoke has been recorded yet, so BitFun +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..2f6a341f 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. BitFun likewise has no lifecycle profile, so +lifecycle targets reject it with `UNKNOWN_HOST`. 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/docs/reference/architecture.md b/docs/docs/reference/architecture.md index dbb83eca..cc9a54ad 100644 --- a/docs/docs/reference/architecture.md +++ b/docs/docs/reference/architecture.md @@ -44,7 +44,7 @@ available after the agent acts: | Project evidence | `better-harness core-change-watch` | Project, history, core-path, and diff signals | | Change confidence | `hooks/git-scripts/blast-radius` | Symbol-graph blast radius of a change | | Dependency governance | `better-harness dependency-governance` | Update automation, audit, stale-dep signals | -| Session evidence | `better-harness session-analysis` | Normalize Qoder, Codex, Claude, Augment/Auggie, Cursor, Qwen, Copilot, Pi, Kimi Code, or WorkBuddy session behavior | +| Session evidence | `better-harness session-analysis` | Normalize Qoder, Codex, Claude, Augment/Auggie, Cursor, Qwen, Copilot, Pi, Kimi Code, WorkBuddy, Grok, or BitFun session behavior | | Agent assets | `better-harness coding-agent-practices inventory` | Inventory configured agent surfaces | | Guardrails | `hooks/`, `scripts/agent-guardrails` | Secret scanning and lifecycle checks | diff --git a/docs/glossary.md b/docs/glossary.md index 2df140a5..5c17b29a 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -60,7 +60,7 @@ for extension surfaces, read [community.md](community.md). | `core-change-watch` | Project, history, core-path, and current-diff evidence collection. | [scripts/core-change-watch](../scripts/core-change-watch) | | Blast radius | The symbol-graph reach of a change, computed with tree-sitter (JS/TS, Go, Python) as a git hook. | [hooks/git-scripts/blast-radius](../hooks/git-scripts/blast-radius) | | `dependency-governance` | Update-automation, audit, and stale-dependency signals. | [scripts/dependency-governance](../scripts/dependency-governance) | -| `session-analysis` | Normalizes Qoder, Codex, Claude, Augment/Auggie, Cursor, Qwen, Copilot, Pi, Kimi Code, or WorkBuddy agent session behavior into evidence. | [scripts/session-analysis](../scripts/session-analysis) | +| `session-analysis` | Normalizes Qoder, Codex, Claude, Augment/Auggie, Cursor, Qwen, Copilot, Pi, Kimi Code, WorkBuddy, Grok, or BitFun agent session behavior into evidence. | [scripts/session-analysis](../scripts/session-analysis) | | Guardrails | Change-time enforcement: secret scanning and lifecycle hook checks. | [hooks](../hooks), [scripts/agent-guardrails](../scripts/agent-guardrails) | ## The Action Loop (Report → Change) diff --git a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/concepts/harness-inspector.md b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/concepts/harness-inspector.md index 3bafdd12..4408a970 100644 --- a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/concepts/harness-inspector.md +++ b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/concepts/harness-inspector.md @@ -81,8 +81,8 @@ better-harness harness-inspector render --workspace . --open 可以使用 `--platform`、`--since`、`--until`、`--commits` 与 `--max-sessions` 限定范围。`--platform all` 会从 Qoder、Codex、Claude Code、 -Cursor、Qwen Code、GitHub Copilot、Pi、Kimi Code、WorkBuddy 和 Grok 中发现 -证据,同时保留各 Provider 的证据缺口。 +Cursor、Qwen Code、GitHub Copilot、Pi、Kimi Code、WorkBuddy、Grok 和 BitFun 中 +发现证据,同时保留各 Provider 的证据缺口。 可选的 `.better-harness/feature-tree.md` 用于声明经过评审的意图: 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..9781c20b 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 以适配器支持展示,BitFun 以部分 +适配器展示(仅已配置资产与会话证据),因为它们的安装方式和端到端 证据边界与这六个宿主不同。完整能力层事实源仍是 [规范适配器矩阵](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 | +| BitFun | 部分适配器 | 仅已配置资产与会话证据;不声称安装或生命周期 | 无;Skill 使用 OpenBitFun 自有路径 | `~/.openbitfun/projects/` 下匹配工作区的 BitFun 会话目录 | 自包含 HTML + Markdown | `@qoder-ai/better-harness` npm 包含全部七个插件元数据根目录。生成的 Qoder 运行时 bundle 只包含 Qoder shell。Pi 复用现有 `package.json` 中的安装元数据, @@ -50,7 +52,7 @@ better-harness doctor --platform all 但不会执行。Qoder Desktop 保持内置分发,Codex Desktop 使用手工 UI 步骤; Cursor 在本机 help 合同过期期间保持安装不可用;Pi 持久化 surface 中缺少原生 证据的操作保持不可用,临时 session surface 的更新/移除不适用;WorkBuddy 返回 -`PLUGIN_LIFECYCLE_UNSUPPORTED`。Kimi Code 与 Grok 尚无经验证的原生生命周期 +`PLUGIN_LIFECYCLE_UNSUPPORTED`。Kimi Code、Grok 与 BitFun 尚无经验证的原生生命周期 合同,因此生命周期目标会以 `UNKNOWN_HOST` 拒绝它们,其适配器证据仍然可用。 在 ADR-0002 仍为 proposed 期间,shadow host profile 不替代规范适配器矩阵。 @@ -60,7 +62,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/BitFun 的可移植契约,覆盖 `findings.json`、`report.md` 和自包含的 `report.html` (见[示例报告](pathname:///demo/better-harness-report/))。 - **纯 Markdown** —— 无视觉版本。 @@ -110,6 +112,17 @@ Grok 的已配置资产、工作区匹配的会话证据与可移植 HTML 路由 `~/.grok/skills/better-harness`(或项目 `.grok/skills`)。在观察到完整交互式 报告闭环冒烟验证前,Grok 仍不进入已验证快速开始集合。 +### BitFun {#bitfun} + +BitFun 的已配置资产、工作区匹配的会话证据与可移植 HTML 路由均已实现,输出复用 +通用的 Better Harness 自有根目录。适配器把产品 home(`~/.openbitfun` 或 +`OPENBITFUN_HOME`)、平台用户根目录与项目 `.openbitfun` 视为三套独立的存储。 +发现通过扫描 `projects//sessions//metadata.json` 并信任 +其中记录的工作区字段,而不重新实现宿主自有的 project key;形态未知的会话也会以 +显式元数据覆盖出现。本仓库不提供 BitFun 安装 Shell、插件生命周期 profile 或 npm +打包的宿主产物,也尚未记录原生冒烟验证,因此 BitFun 保持为部分适配器,不进入 +已验证快速开始集合。 + ## 能力覆盖 各宿主的能力刻意保持差异:没有真实证据源的宿主不会声称具备某项能力, 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..fdd0709f 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` 命令。 +生命周期入口。BitFun 同样没有生命周期 profile,生命周期目标会以 +`UNKNOWN_HOST` 拒绝。CLI 不提供 `plugin apply` 命令。 可以使用 Git 克隆并检查 Cursor manifest,但仅存在 manifest 并不能证明当前 存在受支持的安装路径。 diff --git a/docs/specs/2026-11-23-bitfun-host-adapter.md b/docs/specs/2026-11-23-bitfun-host-adapter.md new file mode 100644 index 00000000..1f94ce2e --- /dev/null +++ b/docs/specs/2026-11-23-bitfun-host-adapter.md @@ -0,0 +1,175 @@ +# BitFun (OpenBitFun) Partial Host Adapter + +## Traceability + +- Spec ID: SPEC-2026-11-23-bitfun-host-adapter +- Status: Implemented +- Upstream request: [QoderAI/better-harness#204](https://github.com/QoderAI/better-harness/issues/204) +- Native evidence: OpenBitFun `v1.0.12` (released 2026-11-20), upstream source + read at `openBitFun/OpenBitFun@main` on 2026-11-23 + (`src/crates/assembly/core/src/infrastructure/app_paths/path_manager.rs`, + `src/crates/contracts/core-types/src/product_identity.rs`, + `src/crates/services/services-core/src/session/types.rs`, + `src/crates/services/services-core/src/workspace_instructions.rs`, + `src/crates/execution/agent-runtime/src/skills/roots.rs`, + `src/crates/services/services-core/src/session/metadata_store.rs`, + `docs/features/agent-hooks.md`) + +## Intent + +Add OpenBitFun (referred to as BitFun below) as a partial, source-local host so +Better Harness can read BitFun session evidence and configured-asset inventory +through the existing contracts instead of inventing a parallel path. The +adapter covers the first slice requested in #204: configuration metadata plus +workspace-associated session evidence, mapped onto existing evidence contracts, +and emitted through an existing report mode (portable HTML with a companion +Markdown report). + +## Non-Goals + +- No BitFun install shell, plugin manifest, npm metadata root, or generated host + artifact. BitFun discovers skills from its own roots; this spec only documents + them. +- No plugin lifecycle profile. Like Kimi Code, Grok, and DSH, BitFun is an + unmanaged host here, so lifecycle targets keep rejecting `bitfun` with + `UNKNOWN_HOST`. +- No Asset Practices, Checkup, neutral Harness report preparation, or Evidence + Bundle claim. The capability descriptor lists only session analysis, + configured assets, and portable HTML rendering. +- No write, migration, repair, or cleanup of BitFun state. All collection is + read-only. +- No claim over remote SSH workspaces, the BitFun Tauri/Web UI state, SQLite + stores (`memories.sqlite`, `coordination.sqlite`), cron/miniapp data, or + BitFun plugin package execution. + +## Evidence Format + +BitFun keeps three storage families apart, and the adapter must not flatten +them: + +- Product home: `~/.openbitfun`, overridden by `OPENBITFUN_HOME`. Sessions live + below `~/.openbitfun/projects/<24-hex-runtime-key>/sessions//`. +- User root: platform config directory plus the `openbitfun` namespace — + `~/Library/Application Support/openbitfun` on macOS, `~/.config/openbitfun` + on Linux, `%APPDATA%\openbitfun` on Windows — overridden by + `OPENBITFUN_USER_ROOT`. It holds `config/app.json`, `config/hooks.json`, + `agents/`, and `data/`. +- Project root: `/.openbitfun` with `config/`, `agents/`, `rules/`, + `skills/`, and `plugins/`. + +Observed session layout below a session directory: + +- `metadata.json`: `{ schema_version, metadata }`, where `metadata` carries + `sessionId`, `sessionName`, `sessionKind`, `modelName`, `createdAt`, + `lastActiveAt`, `workspacePath`, optional `projectWorkspacePath`, and + `workspaceHostname`. Timestamps are Unix milliseconds. Metadata files are + authoritative; `index.json` is a rebuildable cache and is not read. +- `turns/turn-%04d.json`: `{ schema_version, turn }` where `turn` is a + `DialogTurnData` with `turnId`, `turnIndex`, `timestamp`, `kind` + (`user_dialog` / `manual_compaction` / `local_command`), `userMessage`, + `modelRounds`, `tokenUsage`, `finishReason`, `hasFinalResponse`, `error`, + and `status`. +- Each model round carries `textItems`, `toolItems`, and `thinkingItems`. + A tool item has `toolName` plus `toolCall { id, input }` and an optional + `toolResult { result, success, resultForAssistant, error }`. +- `artifacts/transcript.txt` is an export, not the source of truth, and stays + unread. + +Observed configured-asset surfaces: + +- Skills: `//SKILL.md` with the managed builtin subtree + `.system`, where the user skills dir is + `~/Library/Application Support/openbitfun/skills` on macOS, + `~/.local/share/openbitfun/skills` (or `$XDG_DATA_HOME`) on Linux, and + `%APPDATA%\openbitfun\skills` on Windows. Project skills come from + `.openbitfun/skills` plus the shared `.agents/skills`. +- Agents: markdown frontmatter files under `/agents` and + `.openbitfun/agents`. +- Rules: `.openbitfun/rules/`, plus workspace instruction files + `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`, `.claude/CLAUDE.md`, and + `CLAUDE.local.md` that BitFun reads for compatibility. +- Hooks: `/config/hooks.json` and + `/.openbitfun/config/hooks.json`, using the documented + `{ hooks: { : [{ matcher, hooks: [{ type: "command", command }] }] } }` + document. +- MCP: `app.json` stores MCP servers under the snake_case top-level + `mcp_servers` key whose value is `{ "mcpServers": { ... } }`. BitFun also + reads compatibility skill roots for Claude Code, Codex, Cursor, OpenCode, + `.agents`, DSH, and Pi; this adapter inventories only the native and + `.agents` roots so other hosts' assets are not double-counted. + +## Acceptance Criteria + +- AC1: `node scripts/session-analysis.mjs sessions --platform bitfun + --workspace ` discovers session directories under + `/projects/*/sessions/*` by scanning `metadata.json`, admits only + sessions whose `workspacePath`, `projectWorkspacePath`, or + `executionTarget.rootPath` matches the requested workspace scope, skips hosts + whose `workspaceHostname` is not `localhost`, and honours `--bitfun-home`, + `--home`, and `OPENBITFUN_HOME`. +- AC2: Normalized events cover user messages, assistant text items, tool calls + with invocation ids, tool results with success state and result facts, per-turn + token usage when `tokenUsage` is present, and explicit metadata for thinking, + non-dialog turn kinds, turn errors, and unknown records. Missing usage stays + unobserved rather than zero, and facts output leaks neither prompt text nor + home paths. +- AC3: `better-harness agent-customize inventory --provider bitfun` inventories + user skills (excluding `.system`), user agents, user hooks, user MCP servers + from `app.json`, project `.openbitfun` skills/agents/rules/hooks, shared + `.agents/skills`, and the workspace instruction files, while reporting + BitFun plugins and non-inventoried config surfaces as unsupported. +- AC4: Shared registries accept `bitfun` wherever the claimed slices are routed: + the host descriptor catalog, the configured-asset provider map, the + session-analysis platform registry and help, the agent-customize CLI home + option, and the portable HTML render platform list. Help snapshots stay in + sync, and capability-mapping tests catch a claimed slice without an + implementation or the reverse. +- AC5: The adapter matrix (canonical README, docs site page, and its zh-Hans + copy), the platform reference note, and the sessions diagnostics page + document BitFun with its limitations; the doc-link graph and docs tests pass. + +## Plan / Tasks + +1. `docs/specs/2026-11-23-bitfun-host-adapter.md`: record the host contract, + the claimed and unavailable slices, and the acceptance ids. +2. `scripts/agent-customize/providers/bitfun.mjs`: resolve the product home and + user root with documented overrides, inventory user and project primitives, + and parse `app.json` MCP servers without serializing env values. +3. `scripts/session-analysis/platforms/bitfun.mjs`: scan project runtime + directories for metadata-qualified sessions, read turns in order with the + workspace preflight budget, and normalize events into the shared contract. +4. Register `bitfun` in `scripts/host-support/index.mjs` with only the three + claimed capabilities, then thread it through the provider map, the platform + registry, help text, and the agent-customize summary. +5. Tests: deterministic synthetic fixtures for session discovery, workspace + rejection, event normalization, usage observation, configured-asset + inventory, home overrides, and help/routing contracts. +6. Docs: adapter matrix row and paragraph, docs site table row and per-host + section, zh-Hans mirror, platform reference page, and sessions diagnostics. + +## Test and Review Evidence + +- AC1-AC2: `npx vitest run test/sessions/session-analysis-providers.test.mjs` + covers workspace-qualified discovery, foreign-workspace and remote-host + rejection, turn ordering, tool call/result correlation, sparse usage, and + unknown-event accounting. +- AC3: `npx vitest run test/agents/agent-customize.test.mjs` covers user and + project inventory, `.system` skill exclusion, `app.json` MCP parsing with + credential-shaped env keys, and the `--bitfun-home` CLI override. +- AC4: host-support, provider/registry equality, help snapshot, and render + platform tests fail if the descriptor and the implementations drift. +- AC5: `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 BitFun as a partial + adapter with no install, lifecycle, or Quickstart claim. + +Residual risk: BitFun's runtime project directory name is a 24-hex key derived +from workspace identity, and the derivation is not part of the public contract. +The adapter therefore trusts `metadata.json` workspace fields instead of +reimplementing the hash. If a future release stops writing `workspacePath`, or +starts writing sessions with a non-`localhost` hostname for local workspaces, +discovery degrades to reporting no sessions rather than guessing. Turn files +that use an unknown item shape are preserved as metadata events, so a schema +addition stays visible instead of being silently dropped. diff --git a/references/agent-customize/README.md b/references/agent-customize/README.md index 887bf60a..bb021410 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/bitfun.md`, and `platforms/dsh.md`. ## Does Not Own diff --git a/references/agent-customize/platforms/bitfun.md b/references/agent-customize/platforms/bitfun.md new file mode 100644 index 00000000..85e03aef --- /dev/null +++ b/references/agent-customize/platforms/bitfun.md @@ -0,0 +1,74 @@ +# BitFun Best Practices + +Use this file for BitFun (OpenBitFun) specific operating practice. Use +`../routing.md` for host-neutral owner selection and the other `platforms/` +files for different hosts. Do not copy BitFun-only layout advice into shared +docs unless there is matching source evidence. + +## Operating Frame + +BitFun is a Rust runtime with a desktop front end. Treat its storage as three +separate families, because the runtime itself does: + +- **Product home**: `~/.openbitfun`, relocated by `OPENBITFUN_HOME`. Sessions + live here. +- **User root**: the platform config directory plus `openbitfun`, relocated by + `OPENBITFUN_USER_ROOT`. Holds `config/app.json`, `config/hooks.json`, and + `agents/`. +- **Project root**: `/.openbitfun`. Holds `config/`, `agents/`, + `rules/`, `skills/`, and `plugins/`. + +Move repeated guidance into project `AGENTS.md` or `.openbitfun/rules/`, turn +repeated work into Skills, and keep user-wide assets in the user root rather +than a project directory. + +## Durable Guidance + +BitFun loads `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`, +`.claude/CLAUDE.md`, and `CLAUDE.local.md` from the repository. Keep always-on +facts, build/test/lint commands, conventions, and do-not rules in `AGENTS.md`; +use `.openbitfun/rules/` for topic files that should stay workspace-scoped. + +## Configured Surfaces + +- **Skills**: the user skills directory follows the platform data root + (`~/Library/Application Support/openbitfun/skills` on macOS, + `~/.local/share/openbitfun/skills` or `$XDG_DATA_HOME` on Linux, + `%APPDATA%\openbitfun\skills` on Windows). The builtin `.system` directory is + host-managed and is not user-configured inventory. Project skills live in + `.openbitfun/skills/` and the shared `.agents/skills/`. +- **Agents**: user `/agents/*.md` and project + `.openbitfun/agents/*.md` are subagent profiles. +- **MCP servers**: `config/app.json` stores a snake_case top-level + `mcp_servers` whose value is `{ "mcpServers": { ... } }`. Treat env values as + credentials: name the server, never the secret. A bare server map is accepted + so a hand-edited file does not silently disappear. +- **Hooks**: `config/hooks.json` with `{ "hooks": { "": [ { "matcher", + "hooks": [ { "type": "command", "command" } ] } ] } }` at the user and project + roots. +- **Project assets**: `.openbitfun/` carries skills, agents, rules, and hooks. + Compatibility skill roots owned by other hosts (`.claude`, `.codex`, + `.cursor`, `.opencode`, `.dsh`, `.pi`) stay out of this scope. + +## Session Evidence + +Sessions are persisted per project key under +`~/.openbitfun/projects//sessions//`, with +`metadata.json` as the workspace identity and one `turns/turn-%04d.json` file +per turn. `index.json` is rebuildable cache and `artifacts/transcript.txt` is an +export, so neither is evidence. The runtime project key is a host-owned hash: +read `metadata.json` instead of reimplementing it, and treat a +`workspaceHostname` that is not `localhost` as remote. Route session reads +through `scripts/session-analysis/platforms/bitfun.mjs`; configured presence +never substitutes for observed session behavior. + +## Boundaries + +- Plugin packages, `agent_profiles.json`, `agent_subagents.json`, + `mode_skills.json`, and `tool_permissions.json` are not inventoried; keep + capability claims out of them. +- Remote SSH workspaces, memories/coordination SQLite stores, cron jobs, and + miniapps are outside the adapter. +- No install shell or plugin lifecycle profile exists for BitFun here; a + `/better-harness` run needs the skill copied or linked into the native skill + root manually. diff --git a/references/agent-customize/routing.md b/references/agent-customize/routing.md index 517c8d9c..7db6568e 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 BitFun product-home, user-root, and project-root + separation, then load `platforms/bitfun.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/references/session-evidence/sessions-diagnostics.md b/references/session-evidence/sessions-diagnostics.md index 9491635f..e37f4617 100644 --- a/references/session-evidence/sessions-diagnostics.md +++ b/references/session-evidence/sessions-diagnostics.md @@ -38,7 +38,7 @@ opening only the candidate sessions needed to explain a surprising aggregate. Command and user text flags are also local-only and must not be used for broad transcript dumps. -Supported platforms: `qoder`, `codex`, `claude`, `cursor`, `qwen`, `copilot`, `pi`, `kimi`, `workbuddy`, and `grok`. Do not invent +Supported platforms: `qoder`, `codex`, `claude`, `cursor`, `qwen`, `copilot`, `pi`, `kimi`, `workbuddy`, `grok`, and `bitfun`. Do not invent unsupported platform names. Always pass the absolute target workspace and load the matching Platform Notes before interpreting source roots or workspace bindings. @@ -371,3 +371,25 @@ zero-filled. The `GROK_HOME` environment variable relocates the data root. Route configured Grok skills, hooks, MCP servers in `config.toml`, installed plugins, and project `.grok` assets through `../agent-customize/global-assets.md`; configured presence does not prove use. + +### BitFun + +For BitFun, the analyzer scans `~/.openbitfun/projects//sessions//` +and reads the authoritative `metadata.json` (`schema_version` plus a `metadata` +object). The runtime project key is a host-owned hash, so discovery trusts the +recorded `workspacePath`, `projectWorkspacePath`, or +`executionTarget.rootPath` instead of reimplementing the key derivation; +sessions whose `workspaceHostname` is present and not `localhost` are remote and +stay out of local evidence. Turns are persisted one file per turn as +`turns/turn-%04d.json`; the zero-padded name is the host's own order, and +`index.json` is rebuildable cache rather than evidence. `OPENBITFUN_HOME` +relocates the data root. + +Treat turn timestamps, per-turn `tokenUsage` (`inputTokens`, `outputTokens`, +`cachedTokens`), tool items, and tool results as provider-labelled coverage. +Usage fields that are absent stay unobserved instead of becoming zero, and +reasoning, compaction, error, and unknown turn kinds degrade to bounded +`metadata.*` events rather than disappearing. Session titles are never +summarized. Route configured BitFun skills, user agents, `config/app.json` MCP +servers, hooks, project `.openbitfun` assets, and instruction files through +`../agent-customize/global-assets.md`; configured presence does not prove use. diff --git a/scripts/agent-customize/cli.mjs b/scripts/agent-customize/cli.mjs index ce5021c8..69f430a8 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[=].", + "BitFun storage options: --bitfun-user-root , --bitfun-user-skills-dir .", "", ].join("\n"); } @@ -49,6 +50,9 @@ function summarize(inventory, options) { piHome: inventory.piHome, workbuddyHome: inventory.workbuddyHome, grokHome: inventory.grokHome, + bitfunHome: inventory.bitfunHome, + bitfunUserRoot: inventory.bitfunUserRoot, + bitfunUserSkillsDir: inventory.bitfunUserSkillsDir, dshHome: inventory.dshHome, claudeStatePath: inventory.claudeStatePath, kimiHome: inventory.kimiHome, @@ -94,6 +98,8 @@ 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"], + bitfunUserRoot: options["bitfun-user-root"], + bitfunUserSkillsDir: options["bitfun-user-skills-dir"], workspace: options.workspace, ...(options.provider === "dsh" ? { diff --git a/scripts/agent-customize/providers/bitfun.mjs b/scripts/agent-customize/providers/bitfun.mjs new file mode 100644 index 00000000..94ca3b82 --- /dev/null +++ b/scripts/agent-customize/providers/bitfun.mjs @@ -0,0 +1,219 @@ +/** + * OpenBitFun (BitFun) configured-asset inventory. + * + * Three storage families, kept separate on purpose: + * - product home: OPENBITFUN_HOME or ~/.openbitfun + * - user root: OPENBITFUN_USER_ROOT or the platform config dir + openbitfun + * - project root: /.openbitfun + * + * Only surfaces BitFun reads natively (plus the shared .agents/skills root) are + * inventoried. Plugin packages and compatibility skill roots owned by other + * hosts are reported as unsupported instead of being copied into this scope. + */ +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 { + agentsMarkdownRuleSource, + buildManageCollections, + collectHookItems, + collectMarkdownItems, + collectMcpFromValue, + collectRuleSources, + collectSkillFiles, + directoryRuleSource, + readJson, + sortByName, + workspaceSourceLabel, +} from "../core/items.mjs"; + +const NATIVE_HIDDEN_DIR = ".openbitfun"; +const NATIVE_DATA_NAMESPACE = "openbitfun"; + +const COMPAT_INSTRUCTION_FILES = ["CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md"]; + +export function defaultBitfunHome() { + return process.env.OPENBITFUN_HOME ?? path.join(os.homedir(), NATIVE_HIDDEN_DIR); +} + +function platformConfigRoot() { + if (process.platform === "win32") { + return process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"); + } + if (process.platform === "darwin") { + return path.join(os.homedir(), "Library", "Application Support"); + } + return process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"); +} + +function platformDataRoot() { + if (process.platform === "win32") { + return process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"); + } + if (process.platform === "darwin") { + return path.join(os.homedir(), "Library", "Application Support"); + } + return process.env.XDG_DATA_HOME ?? path.join(os.homedir(), ".local", "share"); +} + +export function defaultBitfunUserRoot() { + return process.env.OPENBITFUN_USER_ROOT + ?? path.join(platformConfigRoot(), NATIVE_DATA_NAMESPACE); +} + +export function defaultBitfunUserSkillsDir(userRoot = defaultBitfunUserRoot()) { + // macOS resolves the user root and the user skills dir to the same directory. + if (process.platform === "darwin") return path.join(userRoot, "skills"); + return path.join(platformDataRoot(), NATIVE_DATA_NAMESPACE, "skills"); +} + +/** + * app.json stores MCP servers as snake_case `mcp_servers` whose value is + * `{ "mcpServers": { ... } }`. Accept a bare server map as well so a + * hand-edited file stays readable instead of silently disappearing. + */ +export function bitfunMcpServersFromAppConfig(config) { + if (!config || typeof config !== "object" || Array.isArray(config)) return null; + const section = config.mcp_servers ?? config.mcpServers; + if (!section || typeof section !== "object" || Array.isArray(section)) return null; + const servers = section.mcpServers ?? section; + return servers && typeof servers === "object" && !Array.isArray(servers) ? servers : null; +} + +async function collectBitfunMcps(appConfigPath, scope, sourceLabel, rootForEvidence) { + const config = await readJson(appConfigPath); + const servers = bitfunMcpServersFromAppConfig(config); + if (!servers) return []; + return collectMcpFromValue(servers, scope, sourceLabel, appConfigPath, rootForEvidence); +} + +function isInsideRoot(filePath, root) { + if (!filePath) return false; + const relative = path.relative(root, filePath); + return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative); +} + +function emptyPrimitives() { + return { skills: [], subagents: [], rules: [], commands: [], hooks: [], mcps: [] }; +} + +async function collectBitfunUserPrimitives({ userRoot, userSkillsDir, includeUserHome }) { + if (!includeUserHome) return emptyPrimitives(); + const configDir = path.join(userRoot, "config"); + const builtinSkillsDir = path.join(userSkillsDir, ".system"); + const [allSkills, subagents, hooks, mcps] = await Promise.all([ + collectSkillFiles(userSkillsDir, "user", "User", userRoot), + collectMarkdownItems(path.join(userRoot, "agents"), "subagent", "user", "User", userRoot), + collectHookItems(configDir, "user", "User", userRoot), + collectBitfunMcps(path.join(configDir, "app.json"), "user", "User", userRoot), + ]); + return { + // .system holds BitFun's own builtin skills; they are managed by the host. + skills: allSkills.filter((skill) => !isInsideRoot(skill.filePath, builtinSkillsDir)), + subagents, + rules: [], + commands: [], + hooks, + mcps, + }; +} + +function compatInstructionSource(workspace, sourceLabel, relativePath) { + return { + type: "file", + filePath: path.join(workspace, relativePath), + scope: "project", + sourceLabel, + rootForEvidence: workspace, + name: relativePath, + sourceKind: "compat-instructions", + precedence: "after-provider-rules", + useHeading: false, + exactName: true, + }; +} + +async function collectBitfunWorkspacePrimitives(workspace) { + const sourceLabel = await workspaceSourceLabel(workspace); + const projectRoot = path.join(workspace, NATIVE_HIDDEN_DIR); + const [skills, subagents, rules, hooks, agentsSkills] = await Promise.all([ + collectSkillFiles(path.join(projectRoot, "skills"), "project", sourceLabel, workspace), + collectMarkdownItems(path.join(projectRoot, "agents"), "subagent", "project", sourceLabel, workspace), + collectRuleSources([ + agentsMarkdownRuleSource(workspace, sourceLabel), + directoryRuleSource(path.join(projectRoot, "rules"), "project", sourceLabel, workspace), + ...COMPAT_INSTRUCTION_FILES.map((relativePath) => compatInstructionSource(workspace, sourceLabel, relativePath)), + ]), + collectHookItems(path.join(projectRoot, "config"), "project", sourceLabel, workspace), + collectSkillFiles(path.join(workspace, ".agents", "skills"), "project", sourceLabel, workspace), + ]); + return { + skills: [...skills, ...agentsSkills].sort(sortByName), + subagents, + rules, + commands: [], + hooks, + mcps: [], + }; +} + +export async function collectBitfunCustomizeInventory(options = {}) { + const bitfunHome = path.resolve(expandHome( + options.bitfunHome ?? options["bitfun-home"] ?? defaultBitfunHome(), + )); + const bitfunUserRoot = path.resolve(expandHome( + options.bitfunUserRoot ?? options["bitfun-user-root"] ?? defaultBitfunUserRoot(), + )); + const bitfunUserSkillsDir = path.resolve(expandHome( + options.bitfunUserSkillsDir + ?? options["bitfun-user-skills-dir"] + ?? defaultBitfunUserSkillsDir(bitfunUserRoot), + )); + const workspace = normalizeWorkspace(options.workspace ?? process.cwd()); + const includeUserHome = options.includeUserHome !== false; + const configDir = path.join(bitfunUserRoot, "config"); + const projectRoot = path.join(workspace, NATIVE_HIDDEN_DIR); + + const [user, project] = await Promise.all([ + collectBitfunUserPrimitives({ userRoot: bitfunUserRoot, userSkillsDir: bitfunUserSkillsDir, includeUserHome }), + collectBitfunWorkspacePrimitives(workspace), + ]); + + return { + generatedAt: new Date().toISOString(), + provider: "bitfun", + bitfunHome, + bitfunUserRoot, + bitfunUserSkillsDir, + workspace, + tabs: MANAGE_TABS, + plugins: [], + manage: buildManageCollections([], user, project), + diagnostics: { + // BitFun installs product plugin packages, but this adapter does not + // execute or inventory them; keep the empty state explicit. + installedPluginState: "unsupported", + installedPluginRecordCount: 0, + installedPluginRecordFiles: [], + remotePluginInstallMarkersRequired: false, + // app.json always names the user config document; null when the user + // home is out of scope so a redacted run cannot imply it was read. + appConfigPath: includeUserHome ? path.join(configDir, "app.json") : null, + userHooksPath: includeUserHome ? path.join(configDir, "hooks.json") : null, + projectConfigDir: path.join(projectRoot, "config"), + projectHooksPath: path.join(projectRoot, "config", "hooks.json"), + builtinUserSkillsDir: includeUserHome ? path.join(bitfunUserSkillsDir, ".system") : null, + exists: Boolean(await pathExists(bitfunHome)), + }, + unsupported: [ + "product plugin packages under .openbitfun/plugins and the user data plugins dir", + "compatibility skill roots owned by other hosts (.claude, .codex, .cursor, .opencode, .dsh, .pi)", + "agent_profiles.json, agent_subagents.json, mode_skills.json, and tool_permissions.json", + "project MCP overlay stored in the shared app.json project section", + "MCP env secret values from app.json", + "remote SSH workspaces, memories/coordination SQLite stores, cron jobs, and miniapps", + ], + }; +} diff --git a/scripts/agent-customize/providers/index.mjs b/scripts/agent-customize/providers/index.mjs index eea97cdc..6059cd09 100644 --- a/scripts/agent-customize/providers/index.mjs +++ b/scripts/agent-customize/providers/index.mjs @@ -1,3 +1,4 @@ +import { collectBitfunCustomizeInventory } from "./bitfun.mjs"; import { collectClaudeCustomizeInventory } from "./claude.mjs"; import { collectCodexCustomizeInventory } from "./codex.mjs"; import { collectCopilotCustomizeInventory } from "./copilot.mjs"; @@ -34,6 +35,7 @@ export const PROVIDER_COLLECTORS = new Map([ ["kimi", collectKimiCustomizeInventory], ["workbuddy", collectWorkbuddyCustomizeInventory], ["grok", collectGrokCustomizeInventory], + ["bitfun", collectBitfunCustomizeInventory], ["dsh", collectDshCustomizeInventory], ]); diff --git a/scripts/host-support/index.mjs b/scripts/host-support/index.mjs index 88b69b13..91a6a6f1 100644 --- a/scripts/host-support/index.mjs +++ b/scripts/host-support/index.mjs @@ -114,6 +114,17 @@ export const HOST_DESCRIPTORS = Object.freeze([ capabilities: COMMON_CAPABILITIES, sessionScopeTokens: [".grok", "grok"], }), + descriptor({ + id: "bitfun", + displayName: "BitFun", + aliases: ["OpenBitFun"], + capabilities: [ + HOST_CAPABILITIES.SESSION_ANALYSIS, + HOST_CAPABILITIES.AGENT_CUSTOMIZE, + HOST_CAPABILITIES.REPORT_RENDERING, + ], + sessionScopeTokens: [".openbitfun", "openbitfun"], + }), descriptor({ id: "dsh", displayName: "DeepSeek Harness", diff --git a/scripts/session-analysis/analyzer.mjs b/scripts/session-analysis/analyzer.mjs index 06250856..68165907 100644 --- a/scripts/session-analysis/analyzer.mjs +++ b/scripts/session-analysis/analyzer.mjs @@ -57,6 +57,7 @@ Options: --kimi-home Kimi Code data root (default: ~/.kimi-code) --workbuddy-home WorkBuddy data root (default: ~/.workbuddy) --grok-home Grok CLI data root (default: ~/.grok or $GROK_HOME) + --bitfun-home BitFun data root (default: ~/.openbitfun or $OPENBITFUN_HOME) --dsh-home DeepSeek Harness data root (default: ~/.dsh or $DSH_HOME) --include-cache Include optional Qoder cache evidence --include-global-capabilities @@ -261,6 +262,7 @@ const PLATFORM_MODULES = Object.freeze({ kimi: { load: () => import("./platforms/kimi.mjs"), analyzer: "KimiSessionAnalyzer" }, workbuddy: { load: () => import("./platforms/workbuddy.mjs"), analyzer: "WorkbuddySessionAnalyzer" }, grok: { load: () => import("./platforms/grok.mjs"), analyzer: "GrokSessionAnalyzer" }, + bitfun: { load: () => import("./platforms/bitfun.mjs"), analyzer: "BitfunSessionAnalyzer" }, dsh: { load: () => import("./platforms/dsh.mjs"), analyzer: "DshSessionAnalyzer" }, "harness-run": { load: () => import("./platforms/harness-run.mjs"), analyzer: "HarnessRunSessionAnalyzer" }, }); @@ -341,7 +343,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) { ...eventOptions, ...claudeOptions, "", - "Options: --augment-home overrides the Augment/Auggie data root (default: ~/.augment); --kimi-home overrides the Kimi Code data root (default: ~/.kimi-code); --workbuddy-home overrides the WorkBuddy data root (default: ~/.workbuddy); --grok-home overrides the Grok data root (default: ~/.grok or $GROK_HOME); --dsh-home overrides the DeepSeek Harness data root (default: ~/.dsh or $DSH_HOME).", + "Options: --augment-home overrides the Augment/Auggie data root (default: ~/.augment); --kimi-home overrides the Kimi Code data root (default: ~/.kimi-code); --workbuddy-home overrides the WorkBuddy data root (default: ~/.workbuddy); --grok-home overrides the Grok data root (default: ~/.grok or $GROK_HOME); --bitfun-home overrides the BitFun data root (default: ~/.openbitfun or $OPENBITFUN_HOME); --dsh-home overrides the DeepSeek Harness data root (default: ~/.dsh or $DSH_HOME).", "", "Use facts --debug only for local diagnosis; it exposes raw session ids and must not be passed to report agents.", ].join("\n") + "\n"); diff --git a/scripts/session-analysis/platforms/bitfun.mjs b/scripts/session-analysis/platforms/bitfun.mjs new file mode 100644 index 00000000..699c6643 --- /dev/null +++ b/scripts/session-analysis/platforms/bitfun.mjs @@ -0,0 +1,623 @@ +#!/usr/bin/env node +/** + * OpenBitFun (BitFun) session evidence adapter. + * + * Sessions live below the product home (~/.openbitfun, $OPENBITFUN_HOME): + * projects//sessions// + * metadata.json { schema_version, metadata } + * turns/turn-0000.json { schema_version, turn } + * + * The runtime project key is a host-owned hash, so discovery scans metadata.json + * and trusts its workspace fields instead of reimplementing the derivation. + */ +import { readdir } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { SessionAnalyzer } from "../analyzer.mjs"; +import { parseArgs } from "../cli.mjs"; +import { pathExists, readJson } from "../fs.mjs"; +import { expandHome, normalizeWorkspace } from "../paths.mjs"; +import { + bindSessionWorkspaceCwds, + emitProviderResult, + markSessionReadCoverage, + runProviderAnalysis, + runProviderCommand, + sessionWorkspaceCwd, + workspaceMatchScopeFromOptions, +} from "../provider-runner.mjs"; +import { parseResultFacts } from "../result-facts.mjs"; +import { mergeTimeRange, normalizeCliDate, normalizeTimestamp, timestampMillis, withinTimeRange } from "../time.mjs"; +import { WORKSPACE_CWD_MATCH, classifyWorkspaceCwd } from "../workspace-match.mjs"; + +const LOCAL_WORKSPACE_HOSTNAME = "localhost"; + +export function defaultBitfunHome() { + return process.env.OPENBITFUN_HOME ?? path.join(expandHome("~"), ".openbitfun"); +} + +function isWorkspaceMatch(candidate, workspace) { + if (!candidate) return false; + const resolved = normalizeWorkspace(candidate); + return resolved === workspace || resolved.startsWith(`${workspace}${path.sep}`); +} + +function isScopedWorkspaceMatch(candidate, scope) { + if (!scope?._workspaceMatchScope) return isWorkspaceMatch(candidate, scope.workspace); + return classifyWorkspaceCwd(candidate, scope._workspaceMatchScope) !== WORKSPACE_CWD_MATCH.UNMATCHED; +} + +function evidenceRef(sourceRef, type, itemIndex = null) { + return { + kind: sourceRef.kind, + path: sourceRef.path, + line: sourceRef.line ?? null, + seq: itemIndex, + type, + }; +} + +async function readJsonSafe(filePath) { + try { + return await readJson(filePath); + } catch { + return null; + } +} + +function finiteNumber(...values) { + return values.find((value) => typeof value === "number" && Number.isFinite(value)); +} + +function textItemContent(item) { + return typeof item?.content === "string" ? item.content : ""; +} + +function firstString(...values) { + return values.find((value) => typeof value === "string" && value.length > 0) ?? null; +} + +const BASH_TOOL_RE = /(?:bash|shell|exec|terminal|command|runcode|run_code|code_execute)/iu; +const FILE_TOOL_RE = /(?:read|edit|write|file|notebook|delete|view|create)/iu; + +function toolInput(toolItem) { + const input = toolItem?.toolCall?.input; + return input && typeof input === "object" && !Array.isArray(input) ? input : {}; +} + +function toolNameOf(toolItem) { + const input = toolInput(toolItem); + return firstString( + toolItem?.toolName, + input.tool, + input.toolName, + input.tool_name, + input.name, + toolItem?.aiIntent, + ) ?? "unknown-tool"; +} + +function inferCommandText(toolName, input) { + if (!BASH_TOOL_RE.test(String(toolName ?? ""))) return null; + return firstString(input.command, input.cmd); +} + +function inferFilePath(toolName, input) { + if (!FILE_TOOL_RE.test(String(toolName ?? ""))) return null; + return firstString( + input.file_path, + input.filePath, + input.target_file, + input.targetFile, + input.path, + input.filename, + ); +} + +export function bitfunTokenUsage(usage) { + if (!usage || typeof usage !== "object") return null; + const observed = {}; + for (const [key, value] of [ + ["inputTokens", finiteNumber(usage.inputTokens, usage.input_tokens, usage.promptTokens)], + ["outputTokens", finiteNumber(usage.outputTokens, usage.output_tokens, usage.completionTokens)], + ["totalTokens", finiteNumber(usage.totalTokens, usage.total_tokens)], + ["cacheReadInputTokens", finiteNumber(usage.cachedTokens, usage.cached_tokens)], + ]) { + if (value !== undefined) observed[key] = value; + } + return Object.keys(observed).length > 0 ? observed : null; +} + +function roundModel(round) { + return firstString(round?.effectiveModelName, round?.effective_model_name, round?.modelConfigId); +} + +function textSummary(role, length) { + return length > 0 ? `${role} message (${length} chars)` : role; +} + +/** + * Map one persisted DialogTurnData into normalized events. + * Unknown item kinds stay explicit metadata so a schema addition is visible + * instead of disappearing. + */ +export function bitfunTurnToEvents(turn, sourceRef, options = {}) { + if (!turn || typeof turn !== "object") return []; + const kind = String(turn.kind ?? turn.turn_kind ?? "user_dialog"); + const status = String(turn.status ?? ""); + const base = { + sessionId: sourceRef.sessionId, + timestamp: normalizeTimestamp(turn.timestamp ?? turn.startTime ?? turn.start_time ?? null), + sourceKind: sourceRef.kind, + planningScope: "workspace", + cwd: sourceRef.cwd ?? null, + isSubagent: sourceRef.isSubagent ?? null, + }; + const events = []; + const turnLabel = `turn ${Number.isInteger(turn.turnIndex) ? turn.turnIndex : (turn.turnIndex ?? "?")}`; + let model = null; + + if (kind !== "user_dialog") { + events.push({ + ...base, + type: "metadata.turn_kind", + category: "metadata", + evidenceRef: evidenceRef(sourceRef, "metadata.turn_kind"), + summary: `${turnLabel} ${kind}`, + turnKind: kind, + }); + } else { + const userContent = typeof turn.userMessage?.content === "string" ? turn.userMessage.content : ""; + events.push({ + ...base, + type: "user", + category: "user", + evidenceRef: evidenceRef(sourceRef, "user"), + summary: textSummary("user", userContent.length), + contentLength: userContent.length, + userPrompt: userContent.length > 0, + ...(options.includeUserText && userContent ? { userText: userContent } : {}), + ...(options.includeContent && userContent ? { content: userContent } : {}), + }); + + const rounds = Array.isArray(turn.modelRounds) ? turn.modelRounds : []; + rounds.forEach((round, roundIndex) => { + const observedModel = roundModel(round); + if (!model && observedModel) model = observedModel; + const roundTimestamp = normalizeTimestamp(round?.timestamp ?? round?.startTime ?? base.timestamp); + const roundBase = { ...base, timestamp: roundTimestamp }; + + const textItems = Array.isArray(round?.textItems) ? round.textItems : []; + const assistantText = textItems.map((item) => textItemContent(item)).join(""); + if (assistantText.length > 0) { + events.push({ + ...roundBase, + type: "assistant", + category: "assistant", + evidenceRef: evidenceRef(sourceRef, "assistant", roundIndex), + summary: textSummary("assistant", assistantText.length), + contentLength: assistantText.length, + userVisibleAssistantMessage: true, + model: observedModel, + ...(options.includeContent ? { content: assistantText } : {}), + }); + } + + const thinkingItems = Array.isArray(round?.thinkingItems) ? round.thinkingItems : []; + const thinkingLength = thinkingItems.reduce( + (total, item) => total + (typeof item?.content === "string" ? item.content.length : 0), + 0, + ); + if (thinkingItems.length > 0) { + events.push({ + ...roundBase, + type: "metadata.thinking", + category: "metadata", + evidenceRef: evidenceRef(sourceRef, "metadata.thinking", roundIndex), + summary: `thinking (${thinkingItems.length} item${thinkingItems.length === 1 ? "" : "s"}, ${thinkingLength} chars)`, + model: observedModel, + }); + } + + const toolItems = Array.isArray(round?.toolItems) ? round.toolItems : []; + toolItems.forEach((toolItem, toolIndex) => { + const input = toolInput(toolItem); + const toolName = toolNameOf(toolItem); + const toolInvocationId = firstString(toolItem?.toolCall?.id, toolItem?.id); + const toolBase = { + ...roundBase, + timestamp: normalizeTimestamp(toolItem?.startTime ?? toolItem?.start_time ?? roundBase.timestamp), + }; + const callEvent = { + ...toolBase, + type: "tool.call", + category: "tool", + lifecyclePhase: "request", + toolName, + toolInvocationId, + evidenceRef: evidenceRef(sourceRef, "tool.call", roundIndex * 1000 + toolIndex), + summary: `${toolName} request`, + }; + const commandText = inferCommandText(toolName, input); + const filePath = inferFilePath(toolName, input); + if (options.includeCommandText && commandText) callEvent.commandText = commandText; + if (filePath) callEvent.filePath = filePath; + events.push(callEvent); + + const result = toolItem?.toolResult; + if (!result || typeof result !== "object") return; + const success = result.success !== false && !result.error; + const resultEvent = { + ...toolBase, + timestamp: normalizeTimestamp(toolItem?.endTime ?? toolItem?.end_time ?? toolBase.timestamp), + type: "tool.result", + category: "tool", + lifecyclePhase: "result", + toolName, + toolInvocationId, + success, + hasError: !success, + evidenceRef: evidenceRef(sourceRef, "tool.result", roundIndex * 1000 + toolIndex), + summary: success ? "tool result" : "tool result error", + }; + const rawResult = result.resultForAssistant + ?? result.result_for_assistant + ?? result.result + ?? null; + if (rawResult != null) { + const text = typeof rawResult === "string" ? rawResult : JSON.stringify(rawResult); + const facts = parseResultFacts(text.slice(-8_192)); + if (facts) resultEvent.resultFacts = facts; + } + events.push(resultEvent); + }); + }); + } + + // Compaction and command turns also consume model tokens, so usage is read + // from the turn envelope regardless of its kind. + const usage = bitfunTokenUsage(turn.tokenUsage ?? turn.token_usage); + if (usage) { + events.push({ + ...base, + type: "model.response.completed", + category: "model", + modelUsage: usage, + usageFieldsObserved: true, + model, + evidenceRef: evidenceRef(sourceRef, "model.response.completed"), + summary: "BitFun turn token usage", + }); + } else if (turn.tokenUsage || turn.token_usage) { + events.push({ + ...base, + type: "metadata.token_usage", + category: "metadata", + evidenceRef: evidenceRef(sourceRef, "metadata.token_usage"), + summary: "token usage without observed fields", + }); + } + + if (status === "error" || turn.error) { + events.push({ + ...base, + type: "metadata.turn_error", + category: "metadata", + evidenceRef: evidenceRef(sourceRef, "metadata.turn_error"), + summary: `${turnLabel} error`, + turnStatus: status || "error", + }); + } else if (turn.finishReason || turn.finish_reason) { + events.push({ + ...base, + type: "metadata.finish_reason", + category: "metadata", + evidenceRef: evidenceRef(sourceRef, "metadata.finish_reason"), + summary: String(turn.finishReason ?? turn.finish_reason), + }); + } + + return events; +} + +function addRef(sessions, sessionId, workspace, ref) { + if (!sessionId) return; + const session = sessions.get(sessionId) ?? { + sessionId, + workspace, + firstSeen: null, + lastSeen: null, + sourceKinds: new Set(), + sourceRefs: [], + workspaceCwds: new Set(), + }; + if (typeof ref.cwd === "string" && ref.cwd.length > 0) session.workspaceCwds.add(ref.cwd); + session.sourceKinds.add(ref.kind); + session.sourceRefs.push(ref); + mergeTimeRange(session, ref.firstSeen ?? ref.timestamp); + mergeTimeRange(session, ref.lastSeen ?? ref.timestamp); + sessions.set(sessionId, session); +} + +function finalizeSession(session) { + const { workspaceCwds, ...publicSession } = session; + return bindSessionWorkspaceCwds( + { ...publicSession, sourceKinds: [...session.sourceKinds].sort() }, + [...workspaceCwds], + ); +} + +/** + * Sorted `turn-*.json` paths inside a turns directory. + * The zero-padded name is the host's own persistence order. + */ +export async function listBitfunTurnFiles(turnsDir) { + let entries; + try { + entries = await readdir(turnsDir, { withFileTypes: true }); + } catch { + return []; + } + return entries + .filter((entry) => entry.isFile() && /^turn-\d+\.json$/u.test(entry.name)) + .map((entry) => path.join(turnsDir, entry.name)) + .sort((left, right) => path.basename(left).localeCompare(path.basename(right))); +} + +/** + * Read every session directory below `/projects/*\/sessions`, keeping the + * parsed metadata so discovery does not stat the same session twice. + */ +async function scanBitfunSessionDirs(projectsDir) { + const results = []; + let projectEntries; + try { + projectEntries = await readdir(projectsDir, { withFileTypes: true }); + } catch { + return results; + } + for (const projectEntry of projectEntries) { + if (!projectEntry.isDirectory()) continue; + const sessionsDir = path.join(projectsDir, projectEntry.name, "sessions"); + let sessionEntries; + try { + sessionEntries = await readdir(sessionsDir, { withFileTypes: true }); + } catch { + continue; + } + for (const sessionEntry of sessionEntries) { + if (!sessionEntry.isDirectory()) continue; + const sessionDir = path.join(sessionsDir, sessionEntry.name); + const metadataPath = path.join(sessionDir, "metadata.json"); + if (!(await pathExists(metadataPath))) continue; + const stored = await readJsonSafe(metadataPath); + const metadata = stored?.metadata ?? stored; + if (!metadata || typeof metadata !== "object") continue; + results.push({ sessionDir, metadataPath, metadata }); + } + } + return results; +} + +function sessionWorkspaceCandidates(metadata) { + const target = metadata?.executionTarget ?? metadata?.execution_target; + return [...new Set([ + metadata?.workspacePath, + metadata?.workspace_path, + metadata?.projectWorkspacePath, + metadata?.project_workspace_path, + target?.rootPath, + target?.root_path, + ].filter((value) => typeof value === "string" && value.length > 0))]; +} + +function isRemoteWorkspace(metadata) { + const hostname = metadata?.workspaceHostname ?? metadata?.workspace_hostname; + if (typeof hostname !== "string" || hostname.length === 0) return false; + return hostname !== LOCAL_WORKSPACE_HOSTNAME; +} + +export class BitfunSessionAnalyzer extends SessionAnalyzer { + currentSessionId() { + // BitFun exposes no session-id environment variable to a host process. + return null; + } + + async resolveScope(options = {}) { + const since = normalizeCliDate(options.since, false); + const until = normalizeCliDate(options.until, true); + const workspace = normalizeWorkspace(options.workspace); + const home = path.resolve(expandHome( + options.home ?? options.bitfunHome ?? options["bitfun-home"] ?? defaultBitfunHome(), + )); + return { + platform: "bitfun", + workspace, + home, + projectsDir: path.join(home, "projects"), + since: since.label, + sinceTime: since.time, + until: until.label, + untilTime: until.time, + sessionId: options["session-id"] ?? options.sessionId ?? options._?.[0] ?? null, + includeGlobalCapabilities: false, + _workspaceMatchScope: workspaceMatchScopeFromOptions(options), + }; + } + + async sessionDirs(scope) { + if (!scope._bitfunSessionDirs) { + scope._bitfunSessionDirs = await scanBitfunSessionDirs(scope.projectsDir); + } + return scope._bitfunSessionDirs; + } + + async discoverSourceRoots(scope) { + const dirs = await this.sessionDirs(scope); + return [{ + id: "bitfun-sessions", + kind: "bitfun-session-store", + role: "session-transcript", + path: scope.projectsDir, + paths: [scope.projectsDir], + optional: false, + enabled: true, + workspaceScoped: true, + coverage: "primary", + exists: dirs.length > 0, + }]; + } + + async discoverSessions(scope) { + const sessions = new Map(); + for (const { sessionDir, metadataPath, metadata } of await this.sessionDirs(scope)) { + if (isRemoteWorkspace(metadata)) continue; + const candidates = sessionWorkspaceCandidates(metadata); + const qualifiedCwd = candidates.find((candidate) => isScopedWorkspaceMatch(candidate, scope)); + if (!qualifiedCwd) continue; + const sessionId = firstString(metadata.sessionId, metadata.session_id, path.basename(sessionDir)); + if (!sessionId) continue; + if (scope.sessionId && sessionId !== scope.sessionId) continue; + + const firstSeen = normalizeTimestamp(metadata.createdAt ?? metadata.created_at ?? null); + const lastSeen = normalizeTimestamp( + metadata.lastActiveAt ?? metadata.last_active_at ?? metadata.lastFinishedAt ?? null, + ); + if (!withinTimeRange(lastSeen ?? firstSeen, scope)) continue; + + const sessionKind = String(metadata.sessionKind ?? metadata.session_kind ?? "standard"); + const isSubagent = sessionKind === "subagent" || sessionKind === "ephemeral_child"; + const turnsDir = path.join(sessionDir, "turns"); + const hasTurns = await pathExists(turnsDir); + addRef(sessions, sessionId, scope.workspace, { + kind: hasTurns ? "bitfun-session-turns" : "bitfun-session-metadata", + role: hasTurns ? "session-transcript" : "session-metadata", + path: hasTurns ? turnsDir : metadataPath, + firstSeen, + lastSeen, + cwd: qualifiedCwd, + }); + // Metadata stays its own source so a session with no readable turns is + // still visible with explicit coverage instead of vanishing. + if (hasTurns) { + addRef(sessions, sessionId, scope.workspace, { + kind: "bitfun-session-metadata", + role: "session-metadata", + path: metadataPath, + firstSeen, + lastSeen, + cwd: qualifiedCwd, + }); + } + const session = sessions.get(sessionId); + session.sessionKind = sessionKind; + session.isSubagent = isSubagent; + session.model = firstString(metadata.modelName, metadata.model_name); + for (const ref of session.sourceRefs) ref.isSubagent = isSubagent; + } + return [...sessions.values()].map(finalizeSession) + .sort((left, right) => (timestampMillis(right.lastSeen) ?? 0) - (timestampMillis(left.lastSeen) ?? 0)); + } + + normalizeEvent(raw, sourceRef, options = {}) { + return this.normalizeEvents(raw, sourceRef, options)[0] ?? null; + } + + normalizeEvents(raw, sourceRef, options = {}) { + if (sourceRef.kind !== "bitfun-session-turns") return []; + return bitfunTurnToEvents(raw?.turn ?? raw, sourceRef, options); + } + + async readSession(session, scope, options = {}) { + const events = []; + const requestedMaxLines = Number(options.workspacePreflightMaxLines); + const preflight = Number.isFinite(requestedMaxLines) && requestedMaxLines > 0; + let remainingTurns = preflight ? Math.trunc(requestedMaxLines) : null; + let truncated = false; + const identityCwd = sessionWorkspaceCwd(session, scope._workspaceMatchScope); + + for (const ref of session.sourceRefs ?? []) { + if (remainingTurns !== null && remainingTurns <= 0) { + truncated = true; + break; + } + if (ref.kind === "bitfun-session-metadata") { + events.push({ + sessionId: session.sessionId, + timestamp: normalizeTimestamp(session.firstSeen), + sourceKind: ref.kind, + planningScope: "workspace", + cwd: identityCwd ?? ref.cwd ?? null, + isSubagent: ref.isSubagent ?? null, + type: "metadata.session", + category: "metadata", + evidenceRef: evidenceRef({ ...ref, sessionId: session.sessionId }, "metadata.session"), + // Session titles are user-visible text; keep only structural facts. + summary: `${session.sessionKind ?? "standard"} session`, + sessionKind: session.sessionKind, + model: session.model ?? null, + }); + continue; + } + if (ref.kind !== "bitfun-session-turns") continue; + + const turnFiles = await listBitfunTurnFiles(ref.path); + let consumed = 0; + for (const [index, turnFile] of turnFiles.entries()) { + if (remainingTurns !== null && consumed >= remainingTurns) { + truncated = true; + break; + } + consumed += 1; + const stored = await readJsonSafe(turnFile); + const turn = stored?.turn ?? stored; + if (!turn || typeof turn !== "object") { + truncated = true; + continue; + } + const sourceRef = { + ...ref, + path: turnFile, + sessionId: session.sessionId, + seq: index, + cwd: ref.cwd, + }; + for (const event of this.normalizeEvents(turn, sourceRef, options)) { + if (withinTimeRange(event.timestamp, scope)) events.push(event); + } + } + if (remainingTurns !== null) { + remainingTurns -= Math.min(consumed, remainingTurns); + if (consumed < turnFiles.length) truncated = true; + } + } + + const sorted = events + .map((event) => (event.cwd || !identityCwd ? event : { ...event, cwd: identityCwd })) + .sort((left, right) => + (timestampMillis(left.timestamp) ?? 0) - (timestampMillis(right.timestamp) ?? 0) + || Number(left.evidenceRef?.seq ?? 0) - Number(right.evidenceRef?.seq ?? 0)); + return markSessionReadCoverage(sorted, { truncated }); + } + + async analyze(options = {}) { + return runProviderAnalysis(this, options, { platform: "bitfun", adapterVersion: "bitfun-v1" }); + } +} + +export async function main(argv = process.argv.slice(2)) { + const { command = "sessions", options } = parseArgs(argv); + const analyzer = new BitfunSessionAnalyzer(); + const result = await runProviderCommand(analyzer, command, options); + await emitProviderResult({ provider: "BitFun", command, options, result }); + return result; +} + +const isCli = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); +if (isCli) { + main().catch((error) => { + process.stderr.write(`bitfun session-analysis failed: ${error.stack ?? error.message}\n`); + process.exitCode = 1; + }); +} diff --git a/templates/reporting/routing.md b/templates/reporting/routing.md index 252f55d2..08770500 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, BitFun, 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..0078a1a9 100644 --- a/test/agents/agent-customize.test.mjs +++ b/test/agents/agent-customize.test.mjs @@ -3226,3 +3226,172 @@ test("Grok project skills dedupe when .grok/skills symlinks to .agents/skills", await rm(root, { recursive: true, force: true }); } }); + +async function makeBitfunFixture() { + const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-bitfun-")); + const bitfunHome = path.join(root, ".openbitfun"); + const bitfunUserRoot = path.join(root, "user-root"); + const bitfunUserSkillsDir = path.join(root, "user-skills"); + const workspace = path.join(root, "workspace"); + + await writeText( + path.join(bitfunUserSkillsDir, "release-notes", "SKILL.md"), + "---\nname: release-notes\ndescription: Drain the release checklist.\n---\n", + ); + // Builtin host skills must never surface as user-configured assets. + await writeText( + path.join(bitfunUserSkillsDir, ".system", "builtin-helper", "SKILL.md"), + "---\nname: builtin-helper\ndescription: Host-owned builtin skill.\n---\n", + ); + await writeText( + path.join(bitfunUserRoot, "agents", "reviewer.md"), + "---\nname: reviewer\ndescription: Review diffs.\n---\n", + ); + await writeJson(path.join(bitfunUserRoot, "config", "hooks.json"), { + hooks: { + PreToolUse: [{ matcher: "*", hooks: [{ type: "command", command: "git status --short" }] }], + }, + }); + // BitFun stores MCP servers as snake_case mcp_servers wrapping mcpServers. + await writeJson(path.join(bitfunUserRoot, "config", "app.json"), { + mcp_servers: { + mcpServers: { + docs: { + command: "npx", + args: ["-y", "docs-mcp"], + env: { DOCS_TOKEN: "sk-live-0123456789abcdef" }, + }, + disabled_search: { command: "search-mcp", enabled: false }, + }, + }, + }); + + await writeText( + path.join(workspace, ".openbitfun", "skills", "project-flow", "SKILL.md"), + "---\nname: project-flow\ndescription: Project workflow.\n---\n", + ); + await writeText(path.join(workspace, ".openbitfun", "rules", "team.md"), "# Team rules\n\nUse pnpm.\n"); + await writeJson(path.join(workspace, ".openbitfun", "config", "hooks.json"), { + hooks: { PostToolUse: [{ matcher: "Edit", hooks: [{ type: "command", command: "npm run lint" }] }] }, + }); + await writeText( + path.join(workspace, ".agents", "skills", "shared-standard", "SKILL.md"), + "---\nname: shared-standard\ndescription: Shared Agent Skills standard.\n---\n", + ); + await writeText(path.join(workspace, "AGENTS.md"), "# BitFun Project Instructions\n"); + await writeText(path.join(workspace, "CLAUDE.md"), "# Compatibility Instructions\n"); + + return { root, bitfunHome, bitfunUserRoot, bitfunUserSkillsDir, workspace }; +} + +test("BitFun inventory collects native skills, MCP servers, hooks, rules, and subagents", async () => { + const fixture = await makeBitfunFixture(); + try { + const inventory = await collectAgentCustomizeInventory({ + provider: "bitfun", + bitfunHome: fixture.bitfunHome, + bitfunUserRoot: fixture.bitfunUserRoot, + bitfunUserSkillsDir: fixture.bitfunUserSkillsDir, + workspace: fixture.workspace, + }); + + assert.equal(inventory.provider, "bitfun"); + assert.equal(inventory.bitfunHome, fixture.bitfunHome); + assert.equal(inventory.bitfunUserRoot, fixture.bitfunUserRoot); + assert.equal(inventory.diagnostics.installedPluginState, "unsupported"); + assert.deepEqual(inventory.plugins, []); + assert.equal( + inventory.diagnostics.appConfigPath, + path.join(fixture.bitfunUserRoot, "config", "app.json"), + ); + + const userSkills = filterManageItems(inventory, { tab: "skills", scopeKind: "user" }) + .map((item) => item.name); + assert.ok(userSkills.includes("release-notes")); + assert.ok(!userSkills.includes("builtin-helper")); + assert.deepEqual( + filterManageItems(inventory, { tab: "skills", scopeKind: "project" }).map((item) => item.name).sort(), + ["project-flow", "shared-standard"], + ); + + const userMcps = filterManageItems(inventory, { tab: "mcps", scopeKind: "user" }); + assert.ok(userMcps.some((item) => item.name === "docs" && item.enabled !== false)); + assert.equal(userMcps.find((item) => item.name === "disabled_search")?.enabled, false); + + assert.ok( + filterManageItems(inventory, { tab: "agents", scopeKind: "user" }).some((item) => item.name === "reviewer"), + ); + assert.ok( + filterManageItems(inventory, { tab: "hooks", scopeKind: "user" }).some((item) => + item.evidence?.path?.includes("hooks.json")), + ); + assert.ok( + filterManageItems(inventory, { tab: "hooks", scopeKind: "project" }).some((item) => + item.evidence?.path?.includes(path.join(".openbitfun", "config"))), + ); + + const projectRules = filterManageItems(inventory, { tab: "rules", scopeKind: "project" }) + .map((item) => item.name ?? item.label); + assert.ok(projectRules.some((name) => /team/iu.test(String(name)))); + assert.ok(projectRules.some((name) => /AGENTS\.md/u.test(String(name)))); + assert.ok(projectRules.some((name) => /CLAUDE\.md/u.test(String(name)))); + + // 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) => /plugin packages/u.test(item))); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("BitFun inventory without user-home authority keeps project scope only", async () => { + const fixture = await makeBitfunFixture(); + try { + const inventory = await collectAgentCustomizeInventory({ + provider: "bitfun", + bitfunHome: fixture.bitfunHome, + bitfunUserRoot: fixture.bitfunUserRoot, + bitfunUserSkillsDir: fixture.bitfunUserSkillsDir, + workspace: fixture.workspace, + includeUserHome: false, + }); + assert.equal(inventory.diagnostics.appConfigPath, null); + assert.equal(inventory.diagnostics.builtinUserSkillsDir, null); + assert.deepEqual(filterManageItems(inventory, { tab: "skills", scopeKind: "user" }), []); + assert.deepEqual(filterManageItems(inventory, { tab: "mcps", scopeKind: "user" }), []); + assert.ok( + filterManageItems(inventory, { tab: "skills", scopeKind: "project" }) + .some((item) => item.name === "project-flow"), + ); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("agent-customize CLI honours --bitfun-home and isolates BitFun user storage", async () => { + const fixture = await makeBitfunFixture(); + try { + const result = runAgentCustomizeCli([ + "inventory", + "--provider", + "bitfun", + "--workspace", + fixture.workspace, + "--bitfun-home", + fixture.bitfunHome, + "--bitfun-user-root", + fixture.bitfunUserRoot, + "--bitfun-user-skills-dir", + fixture.bitfunUserSkillsDir, + ]); + assert.equal(result.status, 0, result.stderr); + const inventory = JSON.parse(result.stdout); + assert.equal(inventory.bitfunHome, fixture.bitfunHome); + assert.equal(inventory.bitfunUserRoot, fixture.bitfunUserRoot); + assert.notEqual(inventory.bitfunHome, path.join(os.homedir(), ".openbitfun")); + assert.ok(inventory.manage.mcps.some((item) => item.name === "docs")); + assert.doesNotMatch(result.stdout, /sk-live-[A-Za-z0-9]+/u); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); diff --git a/test/fixtures/scripts-refactor-contract/root-help.txt b/test/fixtures/scripts-refactor-contract/root-help.txt index 48f4d570..38370353 100644 --- a/test/fixtures/scripts-refactor-contract/root-help.txt +++ b/test/fixtures/scripts-refactor-contract/root-help.txt @@ -25,8 +25,8 @@ Commands: Project Evidence session-analysis Collect and normalize Qoder, Codex, Claude, Augment, Cursor, Qwen, - Copilot, Pi, Kimi, WorkBuddy, Grok, and DeepSeek Harness session - evidence + Copilot, Pi, Kimi, WorkBuddy, Grok, BitFun, and DeepSeek Harness + session evidence commit-session-link Correlate local git commits with discovered coding-agent sessions and render a commit-view HTML report dependency-governance Detect dependency governance files, automation, audit signals, and diff --git a/test/fixtures/scripts-refactor-contract/session-help.txt b/test/fixtures/scripts-refactor-contract/session-help.txt index ad117733..c538b297 100644 --- a/test/fixtures/scripts-refactor-contract/session-help.txt +++ b/test/fixtures/scripts-refactor-contract/session-help.txt @@ -1,7 +1,7 @@ -Usage: session-analysis --platform --workspace [options] +Usage: session-analysis --platform --workspace [options] Commands: sources, sessions, facets, insights, facts, file-reads, show, events, claude-facets -Options: --augment-home overrides the Augment/Auggie data root (default: ~/.augment); --kimi-home overrides the Kimi Code data root (default: ~/.kimi-code); --workbuddy-home overrides the WorkBuddy data root (default: ~/.workbuddy); --grok-home overrides the Grok data root (default: ~/.grok or $GROK_HOME); --dsh-home overrides the DeepSeek Harness data root (default: ~/.dsh or $DSH_HOME). +Options: --augment-home overrides the Augment/Auggie data root (default: ~/.augment); --kimi-home overrides the Kimi Code data root (default: ~/.kimi-code); --workbuddy-home overrides the WorkBuddy data root (default: ~/.workbuddy); --grok-home overrides the Grok data root (default: ~/.grok or $GROK_HOME); --bitfun-home overrides the BitFun data root (default: ~/.openbitfun or $OPENBITFUN_HOME); --dsh-home overrides the DeepSeek Harness data root (default: ~/.dsh or $DSH_HOME). Use facts --debug only for local diagnosis; it exposes raw session ids and must not be passed to report agents. diff --git a/test/governance/scripts-refactor-contract.test.mjs b/test/governance/scripts-refactor-contract.test.mjs index cd2e689f..13fb9197 100644 --- a/test/governance/scripts-refactor-contract.test.mjs +++ b/test/governance/scripts-refactor-contract.test.mjs @@ -107,12 +107,12 @@ test("scripts refactor contract freezes machine-readable CLI output", () => { { label: "command inventory", args: ["commands", "--json"], - sha256: "132e30886dc4280d9abd0825aaae08bf8b790855624748aeb676ad24e613c1b7", + sha256: "03532aa39ff5c8301e7640c499459e00db5794c1627dd315e738e62b57b98ccc", }, { label: "OpenCLI schema", args: ["schema"], - sha256: "a74252f9b66fd9c60e34ee46ca0913849f0670283e5f02d34eb57419e8d9b346", + sha256: "fa80f90b52f0e5e4aefded207471087186b3e2e107a3eb802c9a099dd46e0e48", }, { label: "Harness command description", diff --git a/test/sessions/session-analysis-providers.test.mjs b/test/sessions/session-analysis-providers.test.mjs index b550aa73..01669ec1 100644 --- a/test/sessions/session-analysis-providers.test.mjs +++ b/test/sessions/session-analysis-providers.test.mjs @@ -40,6 +40,12 @@ import { GrokSessionAnalyzer, workspaceToGrokSessionDirName, } from "../../scripts/session-analysis/platforms/grok.mjs"; +import { + BitfunSessionAnalyzer, + bitfunTokenUsage, + bitfunTurnToEvents, + listBitfunTurnFiles, +} from "../../scripts/session-analysis/platforms/bitfun.mjs"; import { CopilotSessionAnalyzer, parseWorkspaceDescriptor, @@ -70,6 +76,7 @@ test("root dispatcher creates Claude and Cursor provider analyzers", async () => assert.ok(await createAnalyzer("pi") instanceof PiSessionAnalyzer); assert.ok(await createAnalyzer("workbuddy") instanceof WorkbuddySessionAnalyzer); assert.ok(await createAnalyzer("grok") instanceof GrokSessionAnalyzer); + assert.ok(await createAnalyzer("bitfun") instanceof BitfunSessionAnalyzer); assert.ok(await createAnalyzer("dsh") instanceof DshSessionAnalyzer); assert.ok(await createCapabilityAnalyzer("claude") instanceof ClaudeSessionAnalyzer); assert.ok(await createCapabilityAnalyzer("augment") instanceof AugmentSessionAnalyzer); @@ -79,6 +86,7 @@ test("root dispatcher creates Claude and Cursor provider analyzers", async () => assert.ok(await createCapabilityAnalyzer("pi") instanceof PiSessionAnalyzer); assert.ok(await createCapabilityAnalyzer("workbuddy") instanceof WorkbuddySessionAnalyzer); assert.ok(await createCapabilityAnalyzer("grok") instanceof GrokSessionAnalyzer); + assert.ok(await createCapabilityAnalyzer("bitfun") instanceof BitfunSessionAnalyzer); assert.ok(await createCapabilityAnalyzer("dsh") instanceof DshSessionAnalyzer); await assert.rejects(() => createAnalyzer("unknown-host"), /Unsupported session provider: unknown-host/u); }); @@ -2510,3 +2518,285 @@ test("Grok provider leaves usage unobserved when signals.json is missing", async assert.equal(events.filter((event) => event.type === "model.response.completed").length, 0); assert.ok(!events.some((event) => event.modelUsage && Object.values(event.modelUsage).every((value) => value === 0))); }); + +const BITFUN_TURN_BASE = Date.parse("2026-07-19T10:00:00.000Z"); + +async function writeBitfunSession(home, { projectKey, sessionId, metadata, turns = [] }) { + const sessionDir = path.join(home, "projects", projectKey, "sessions", sessionId); + await mkdir(sessionDir, { recursive: true }); + await writeFile( + path.join(sessionDir, "metadata.json"), + `${JSON.stringify({ schema_version: 1, metadata: { sessionId, ...metadata } }, null, 2)}\n`, + ); + if (turns.length > 0) { + const turnsDir = path.join(sessionDir, "turns"); + await mkdir(turnsDir, { recursive: true }); + for (const [index, turn] of turns.entries()) { + await writeFile( + path.join(turnsDir, `turn-${String(index).padStart(4, "0")}.json`), + `${JSON.stringify({ schema_version: 1, turn }, null, 2)}\n`, + ); + } + } + return sessionDir; +} + +function bitfunTurnFixture({ sessionId, turnIndex, timestamp, kind = "user_dialog", extra = {} }) { + return { + turnId: `turn-${turnIndex}`, + turnIndex, + sessionId, + timestamp, + kind, + userMessage: { id: `user-${turnIndex}`, content: `Request ${turnIndex}`, timestamp }, + modelRounds: [], + finishReason: "stop", + status: "completed", + ...extra, + }; +} + +test("BitFun provider discovers local workspace sessions and expands turn evidence", async () => { + const root = await fixtureRoot("session-bitfun-provider-"); + const home = path.join(root, ".openbitfun"); + const workspace = path.join(root, "workspace", "project"); + const sessionId = "11111111-1111-4111-8111-111111111111"; + const projectKey = "0123456789abcdef01234567"; + + const interactiveTurn = { + ...bitfunTurnFixture({ sessionId, turnIndex: 0, timestamp: BITFUN_TURN_BASE }), + userMessage: { id: "user-0", content: "Implement the BitFun adapter", timestamp: BITFUN_TURN_BASE }, + modelRounds: [{ + id: "round-0", + turnId: "turn-0", + roundIndex: 0, + timestamp: BITFUN_TURN_BASE + 1_000, + effectiveModelName: "claude-sonnet-4", + status: "completed", + textItems: [{ content: "Plan the change." }], + thinkingItems: [{ content: "consider the contract" }], + toolItems: [ + { + id: "ti-1", + toolName: "ExecCommand", + toolCall: { id: "call-1", input: { command: "npm test" } }, + startTime: BITFUN_TURN_BASE + 2_000, + endTime: BITFUN_TURN_BASE + 3_000, + toolResult: { success: true, resultForAssistant: "ok", error: null }, + }, + { + id: "ti-2", + toolName: "Read", + toolCall: { id: "call-2", input: { file_path: path.join(workspace, "src", "app.mjs") } }, + startTime: BITFUN_TURN_BASE + 4_000, + endTime: BITFUN_TURN_BASE + 4_500, + toolResult: { success: false, error: "ENOENT" }, + }, + ], + }], + tokenUsage: { inputTokens: 1200, outputTokens: 300, cachedTokens: 100 }, + }; + const compactionTurn = bitfunTurnFixture({ + sessionId, + turnIndex: 1, + timestamp: BITFUN_TURN_BASE + 5_000, + kind: "manual_compaction", + }); + const errorTurn = bitfunTurnFixture({ + sessionId, + turnIndex: 2, + timestamp: BITFUN_TURN_BASE + 6_000, + extra: { status: "error", error: "provider timeout" }, + }); + + await writeBitfunSession(home, { + projectKey, + sessionId, + metadata: { + workspacePath: workspace, + workspaceHostname: "localhost", + sessionKind: "standard", + modelName: "claude-sonnet-4", + createdAt: BITFUN_TURN_BASE, + lastActiveAt: BITFUN_TURN_BASE + 6_000, + }, + turns: [interactiveTurn, compactionTurn, errorTurn], + }); + + // Foreign workspace, prefix-only sibling, remote hostname, and a session with + // no workspace identity must all stay out of this workspace inventory. + await writeBitfunSession(home, { + projectKey: "ffffffffffffffffffffffff", + sessionId: "22222222-2222-4222-8222-222222222222", + metadata: { workspacePath: path.join(root, "workspace", "other"), createdAt: BITFUN_TURN_BASE }, + turns: [bitfunTurnFixture({ sessionId: "22222222-2222-4222-8222-222222222222", turnIndex: 0, timestamp: BITFUN_TURN_BASE })], + }); + await writeBitfunSession(home, { + projectKey: "eeeeeeeeeeeeeeeeeeeeeeee", + sessionId: "33333333-3333-4333-8333-333333333333", + metadata: { workspacePath: `${workspace}-extra`, createdAt: BITFUN_TURN_BASE }, + }); + await writeBitfunSession(home, { + projectKey: "dddddddddddddddddddddddd", + sessionId: "44444444-4444-4444-8444-444444444444", + metadata: { workspacePath: workspace, workspaceHostname: "build-01", createdAt: BITFUN_TURN_BASE }, + }); + await writeBitfunSession(home, { + projectKey: "cccccccccccccccccccccccc", + sessionId: "55555555-5555-4555-8555-555555555555", + metadata: { sessionKind: "standard", createdAt: BITFUN_TURN_BASE }, + }); + + const analyzer = new BitfunSessionAnalyzer(); + const discovery = await analyzer.analyze({ command: "sources", workspace, home }); + + assert.equal(discovery.scope.platform, "bitfun"); + assert.deepEqual(discovery.sources.map((source) => source.kind), ["bitfun-session-store"]); + assert.deepEqual(discovery.sessions.map((session) => session.sessionId), [sessionId]); + const [session] = discovery.sessions; + assert.equal(session.sessionKind, "standard"); + assert.equal(session.isSubagent, false); + assert.equal(session.model, "claude-sonnet-4"); + assert.deepEqual( + [...session.sourceKinds].sort(), + ["bitfun-session-metadata", "bitfun-session-turns"], + ); + + const scope = await analyzer.resolveScope({ workspace, home }); + const events = await analyzer.readSession(session, scope, { + includeCommandText: true, + includeUserText: true, + }); + + const userEvents = events.filter((event) => event.type === "user"); + assert.equal(userEvents.length, 2); + assert.equal(userEvents[0].userText, "Implement the BitFun adapter"); + + const assistantEvents = events.filter((event) => event.type === "assistant"); + assert.equal(assistantEvents.length, 1); + assert.equal(assistantEvents[0].userVisibleAssistantMessage, true); + assert.equal(assistantEvents[0].model, "claude-sonnet-4"); + + const calls = events.filter((event) => event.type === "tool.call"); + assert.deepEqual(calls.map((event) => event.toolName), ["ExecCommand", "Read"]); + assert.deepEqual(calls.map((event) => event.toolInvocationId), ["call-1", "call-2"]); + assert.equal(calls[0].commandText, "npm test"); + assert.equal(calls[1].filePath, path.join(workspace, "src", "app.mjs")); + + const results = events.filter((event) => event.type === "tool.result"); + assert.deepEqual(results.map((event) => event.success), [true, false]); + assert.deepEqual(results.map((event) => event.hasError), [false, true]); + + const usage = events.filter((event) => event.type === "model.response.completed"); + assert.equal(usage.length, 1); + assert.deepEqual(usage[0].modelUsage, { + inputTokens: 1200, + outputTokens: 300, + cacheReadInputTokens: 100, + }); + + assert.ok(events.some((event) => event.type === "metadata.thinking")); + assert.ok(events.some((event) => event.type === "metadata.turn_kind" + && event.turnKind === "manual_compaction")); + assert.ok(events.some((event) => event.type === "metadata.turn_error")); + const metadataSession = events.find((event) => event.type === "metadata.session"); + assert.equal(metadataSession.summary, "standard session"); + + const facts = await analyzer.analyze({ command: "facts", workspace, home, limit: 1 }); + assert.equal(facts.scope.platform, "bitfun"); + const serialized = JSON.stringify(facts); + assert.doesNotMatch(serialized, new RegExp(sessionId, "u")); + assert.equal(serialized.includes(home), false); + assert.equal(serialized.includes(workspace), false); +}); + +test("BitFun sessions without turns stay discoverable with metadata-only coverage", async () => { + const root = await fixtureRoot("session-bitfun-metadata-only-"); + const home = path.join(root, ".openbitfun"); + const workspace = path.join(root, "workspace", "project"); + const sessionId = "66666666-6666-4666-8666-666666666666"; + await writeBitfunSession(home, { + projectKey: "abcdefabcdefabcdefabcdef", + sessionId, + metadata: { workspacePath: workspace, createdAt: BITFUN_TURN_BASE, lastActiveAt: BITFUN_TURN_BASE }, + }); + + const analyzer = new BitfunSessionAnalyzer(); + const discovery = await analyzer.analyze({ command: "sessions", workspace, home }); + assert.deepEqual(discovery.sessions.map((session) => session.sessionId), [sessionId]); + assert.deepEqual(discovery.sessions[0].sourceKinds, ["bitfun-session-metadata"]); + + const scope = await analyzer.resolveScope({ workspace, home }); + const events = await analyzer.readSession(discovery.sessions[0], scope); + assert.deepEqual(events.map((event) => event.type), ["metadata.session"]); +}); + +test("BitFun turn reads honour the workspace preflight budget", async () => { + const root = await fixtureRoot("session-bitfun-preflight-"); + const home = path.join(root, ".openbitfun"); + const workspace = path.join(root, "workspace", "project"); + const sessionId = "77777777-7777-4777-8777-777777777777"; + await writeBitfunSession(home, { + projectKey: "123412341234123412341234", + sessionId, + metadata: { workspacePath: workspace, createdAt: BITFUN_TURN_BASE, lastActiveAt: BITFUN_TURN_BASE }, + turns: [ + bitfunTurnFixture({ sessionId, turnIndex: 0, timestamp: BITFUN_TURN_BASE }), + bitfunTurnFixture({ sessionId, turnIndex: 1, timestamp: BITFUN_TURN_BASE + 1_000, kind: "manual_compaction" }), + bitfunTurnFixture({ sessionId, turnIndex: 2, timestamp: BITFUN_TURN_BASE + 2_000 }), + ], + }); + + const analyzer = new BitfunSessionAnalyzer(); + const discovery = await analyzer.analyze({ command: "sessions", workspace, home }); + const scope = await analyzer.resolveScope({ workspace, home }); + const events = await analyzer.readSession(discovery.sessions[0], scope, { + workspacePreflightMaxLines: 1, + }); + assert.equal(events.filter((event) => event.type === "user").length, 1); + assert.equal(events.some((event) => event.type === "metadata.turn_kind"), false); + + const unbounded = await analyzer.readSession(discovery.sessions[0], scope); + assert.equal(unbounded.filter((event) => event.type === "user").length, 2); + assert.ok(unbounded.some((event) => event.type === "metadata.turn_kind")); +}); + +test("BitFun turn normalization keeps sparse usage and unknown turn kinds explicit", async () => { + const sourceRef = { + kind: "bitfun-session-turns", + path: "/tmp/turn-0000.json", + sessionId: "88888888-8888-4888-8888-888888888888", + }; + + assert.equal(bitfunTokenUsage({}), null); + assert.deepEqual(bitfunTokenUsage({ input_tokens: 5, cached_tokens: 2 }), { + inputTokens: 5, + cacheReadInputTokens: 2, + }); + + const events = bitfunTurnToEvents( + { + turnIndex: 3, + kind: "local_command", + timestamp: BITFUN_TURN_BASE, + tokenUsage: { mystery: 1 }, + }, + sourceRef, + ); + assert.deepEqual(events.map((event) => event.type), ["metadata.turn_kind", "metadata.token_usage"]); + assert.equal(events[0].turnKind, "local_command"); +}); + +test("BitFun turn files list in host persistence order and ignore foreign names", async () => { + const root = await fixtureRoot("session-bitfun-turn-files-"); + const turnsDir = path.join(root, "turns"); + await mkdir(turnsDir, { recursive: true }); + for (const name of ["turn-0002.json", "turn-0000.json", "notes.json", "turn-abcd.json"]) { + await writeFile(path.join(turnsDir, name), "{}\n"); + } + assert.deepEqual( + (await listBitfunTurnFiles(turnsDir)).map((filePath) => path.basename(filePath)), + ["turn-0000.json", "turn-0002.json"], + ); + assert.deepEqual(await listBitfunTurnFiles(path.join(root, "absent")), []); +}); diff --git a/test/skills-docs/coding-agent-platform-notes.test.mjs b/test/skills-docs/coding-agent-platform-notes.test.mjs index 11879ab6..08549b95 100644 --- a/test/skills-docs/coding-agent-platform-notes.test.mjs +++ b/test/skills-docs/coding-agent-platform-notes.test.mjs @@ -47,7 +47,7 @@ test("session diagnostics keeps the shared workflow before platform source roots assertAfter(content, "~/.pi/agent/sessions", "## Platform Notes", "Sessions Diagnostics"); assertAfter(content, "~/.workbuddy/projects", "## Platform Notes", "Sessions Diagnostics"); assertAfter(content, "~/.grok/sessions", "## Platform Notes", "Sessions Diagnostics"); - assert.match(content, /Supported platforms: `qoder`, `codex`, `claude`, `cursor`, `qwen`, `copilot`, `pi`, `kimi`, `workbuddy`, and `grok`/); + assert.match(content, /Supported platforms: `qoder`, `codex`, `claude`, `cursor`, `qwen`, `copilot`, `pi`, `kimi`, `workbuddy`, `grok`, and `bitfun`/); assert.match(content, /Never decode Cursor `store\.db`/); assert.ok(content.indexOf("session-analysis.mjs sources") < content.indexOf("## Platform Notes")); });