diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 047aa81..80b2788 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,6 +28,9 @@ jobs: - name: Test run: bun test + - name: Test native qualification harness fixtures + run: python3 -B scripts/test-native-qualification.py + - name: Lint, format check, and typecheck run: bun run check diff --git a/AGENTS.md b/AGENTS.md index a286c58..8b12492 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,12 +10,12 @@ ## Where truth lives -Start with [`docs/README.md`](docs/README.md). It indexes current documents and their distinct responsibilities. You do not need to read `docs/reviews/` or dated records to learn current behavior. +Start with [`docs/README.md`](docs/README.md). It indexes current documents and their distinct responsibilities. - **Intended behavior** lives in the canonical specs `openspec/specs/*/spec.md`. Requirements and scenarios change only through an owner-approved OpenSpec change. Editorial fixes to a spec's Purpose are allowed. - **Packaged guidance** in `assets/oc-beads/` ships to users and is behavioral, so edit it like source, not like docs. - **User docs** are `README.md` (concise onboarding) and `docs/user-guide.md` (details). **Reference facts** about pinned OpenCode interfaces and sources go in `docs/opencode-sdk-contract.md`, and Beads artifact policy goes in `docs/beads-artifact-policy.md`. Neither restates product rules; link the spec requirement instead. -- **Design rationale** lives in `openspec/changes/archive/`. **Historical evidence** lives in `docs/reviews/`, dated qualification/evaluation/acceptance records in `docs/`, and `docs/history/`. It is frozen: never edit it to sound current, and add new evidence as a new record. **Live execution status** (claims, progress, acceptance, closure) lives in Beads; do not duplicate mutable status in specs or guides. Dated acceptance records remain evidence. +- **Design rationale** lives in `openspec/changes/archive/`. **Qualification evidence** for the current stable release is indexed in [compatibility evidence](docs/compatibility-evidence.md). Superseded reports stay in Git history; never rewrite old verdicts to sound current. **Live execution status** (claims, progress, acceptance, closure) lives in Beads; do not duplicate mutable status in specs or guides. Dated acceptance records remain evidence. - **Disagreements:** specs define intended behavior, not observed upstream facts or execution permission. Correct inaccurate explanatory prose within scope; never rewrite evidence or invent an API to match a spec. If code, SDK facts or test results conflict with the intended behavior, report the precise gap and stop the affected change for disposition. Do not silently change the accepted contract or infer dispatch, publication or activation authority from it. ## Code quality @@ -101,6 +101,10 @@ If the user specifies a version number (e.g., "bump to 0.4.0") or bump type (maj - Add new version release link at the end of the reference links list 3. **`README.md`** - Update version in the installation example JSON (also the options example in `docs/user-guide.md`) +### Qualification evidence retention + +Before cutting the release, update [compatibility evidence](docs/compatibility-evidence.md) to list only the original validations needed for the stable release being prepared. Record exact tested configurations and exclusions; replace a receipt only when a newer validation covers the same claim. Keep receipts at immutable Git revisions, not as duplicate reports in the live `docs/` tree. Remove superseded drafts, reviews, and reports from the live tree and repair affected links and docs checks. Keep active runbooks, collector inputs, and actionable upgrade notes. + ### Commit Convention Use this exact format: @@ -110,7 +114,8 @@ Use this exact format: ### Checklist -- [ ] All three files updated with consistent version +- [ ] Version and installation examples agree +- [ ] Current qualification evidence reconciled and superseded artifacts removed - [ ] CHANGELOG has actual changes listed (not empty) - [ ] CHANGELOG links point to correct versions - [ ] Single commit with all version bump changes diff --git a/CHANGELOG.md b/CHANGELOG.md index 87ac2fd..d7f1ef7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,7 +73,7 @@ and this project attempts to adhere to [Semantic Versioning](https://semver.org/ - Change OpenCode admission to `>=2.3.0 <2.4`, dropping 2.2 support; retain released plugin 2.1.0 for OpenCode 2.2. Type against SDK 2.3.0. - Distinguish asynchronous subagent launch handles, later reports and accepted completion; use a neutral reconciliation cue without changing stop or permission behavior. -- Accept bounded exact 2.3.0 native qualification. Repeated idle reports with outstanding work and cancellation during real `bd` execution remain deferred and unexecuted; see the [qualification record](docs/opencode-23-qualification-xwq.md). +- Accept bounded exact 2.3.0 native qualification. Repeated idle reports with outstanding work and cancellation during real `bd` execution remain deferred and unexecuted; see the [qualification record](https://github.com/snarkipus/opencode-beads/blob/592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c/docs/opencode-23-qualification-xwq.md). - Add independent OpenCode stable-release monitoring and metadata-only CI failure notifications; advancing the reviewed baseline remains a deliberate decision. - Retain the unresolved model-switch snapshot-recovery limitation `opencode-beads-o66`. @@ -191,7 +191,7 @@ Documentation-only release; the plugin code is unchanged from 1.0.0. It updates - `stealth` plugin option runs `bd prime --stealth`, matching `bd setup claude --stealth`. - When `bd prime` fails or times out, the agent receives a short notice instead of silently missing context, as Beads' Codex hooks report refresh failures. - `refreshAfterIdleMinutes` plugin option (default 30): a session that resumes after that much inactivity gets fresh `bd prime`, matching Claude Code's `SessionStart` resume behavior. -- Claude Code parity matrix (`docs/claude-code-parity.md`), validated on OpenCode 2.0.26 with bd 1.3.1. +- [Claude Code parity matrix](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/claude-code-parity.md), validated on OpenCode 2.0.26 with bd 1.3.1. - bd contract check (`scripts/bd-contract.ts`): runs a real `bd` against the guard and the task-agent commands in CI (validated release) and daily against the latest stable Beads release via the `beads-contract` workflow, which also flags releases that have not been reviewed yet, and changes that would make the plugin redundant (for example `bd setup opencode` starting to install hooks or plugin files). ### Changed diff --git a/README.md b/README.md index 73d2470..e781770 100644 --- a/README.md +++ b/README.md @@ -7,40 +7,37 @@ [Beads](https://github.com/gastownhall/beads) issue tracker integration for [OpenCode](https://opencode.ai). -`@snarkipus/opencode-beads` is a maintained OpenCode adapter. It gives an OpenCode session what `bd setup claude` gives Claude Code, plus native OpenCode surfaces: +`@snarkipus/opencode-beads` is a maintained OpenCode adapter purpose-built for OpenCode V2 and Code Mode: -- **Context:** guarded `bd prime` workflow context on every eligible request, refreshed after compaction and idle resume. -- **Typed operations:** eleven permissioned operations in the native `beads` code-mode namespace: find, get, edges, memories, recall, claim, note, selected-field update, close, create and remember. Every write carries the actual session-and-agent Beads actor. -- **Workflows:** 29 `oc-beads:` workflows plus `oc-beads:diagnostics`, and a packaged `oc-beads` skill. -- **Task agent:** a scope-bounded `beads-task-agent`. Exact assignments stop with their item; an already-authorized batch may continue within its bounds. +- **Typed operations:** compose eleven permissioned operations in the native `beads` code-mode namespace (`find`, `get`, `edges`, `memories`, `recall`, `claim`, `note`, selected-field `update`, `close`, `create`, `remember`); writes carry the session-and-agent actor and respect OpenCode permissions. +- **Native context:** attaches guarded native full prime (including persistent memories) on eligible requests, refreshed after compaction and idle resume. +- **Delegation and workflows:** adds a scope-bounded `beads-task-agent`, 29 `oc-beads:` workflows plus `oc-beads:diagnostics`, and a packaged `oc-beads` skill. Exact assignments stop with their item; authorized batches continue within bounds. -The installed `bd` CLI stays authoritative for issues, project initialization, shared skills, migrations and Dolt synchronization. The plugin does not replace it. Ordinary native store opens may migrate; the obsolete `autoMigrate` option is accepted and ignored. See [native store behavior](docs/user-guide.md#native-beads-store-behavior). +The plugin follows upstream Beads conventions for claims, dependencies, and checkpoints. The installed `bd` CLI still owns issues, initialization, shared skills, store lifecycle, and Dolt sync. Native store opens may migrate; legacy `autoMigrate` is ignored. See [native store behavior](docs/user-guide.md#native-beads-store-behavior). ## Supported versions -Version **2.4.1** admits stable OpenCode 2.3.x and exact OpenCode 2.4.1 and 2.4.2. Other 2.4.x hosts are not admitted. +The plugin does not register on unsupported OpenCode versions. | Component | Supported | Evidence | | --- | --- | --- | -| OpenCode | `>=2.3.0 <2.4`, `2.4.1`, or `2.4.2` | [Bounded native qualification](docs/compatibility-evidence.md) on exact 2.3.0, 2.4.1, and 2.4.2 | -| `bd` CLI | 1.3.1 through 1.x | 1.3.4 contract baseline | +| OpenCode | `>=2.3.0 <2.4`, `2.4.1`, or `2.4.2` | [Compatibility evidence](docs/compatibility-evidence.md) | +| `bd` CLI | 1.3.1 through 1.x | 1.3.4 baseline | -A compatible range is admission, not proof that every patch was tested. The plugin refuses to register on hosts outside the range. Older hosts: see [Compatibility](docs/user-guide.md#compatibility). +The [daily upstream workflow](https://github.com/snarkipus/opencode-beads/actions/workflows/beads-contract.yml) checks the latest stable Beads CLI contract plus tests, typecheck, and packaged fixture smoke against newest stable OpenCode's exact published SDK. New releases are flagged for human review even if checks pass. Live-host qualification is separate; see [compatibility evidence](docs/compatibility-evidence.md) and [Compatibility](docs/user-guide.md#compatibility). ## Installation -1. Install the [`bd` CLI](https://github.com/gastownhall/beads/blob/main/docs/getting-started/installation.md) once, then initialize each project: +1. Install the [`bd` CLI](https://github.com/gastownhall/beads/blob/main/docs/getting-started/installation.md), then initialize each project: ```bash - git init # only when the directory is not already a Git worktree + git init # if needed bd init ``` - `bd init` owns project initialization and creates the canonical shared Beads skill at `.agents/skills/beads`, plus a minimal `AGENTS.md` pointer to `bd prime`. The plugin additionally owns its packaged `oc-beads` skill; it does not write startup files or change the shared skill. + `bd init` creates the canonical shared Beads skill at `.agents/skills/beads` and an `AGENTS.md` pointer. The plugin additionally owns its packaged `oc-beads` skill; it does not write startup files or edit the shared skill. **Do not run `bd setup opencode`.** See [why and how to undo it](docs/user-guide.md#why-not-bd-setup-opencode). - **Do not run `bd setup opencode`.** That recipe is for OpenCode *without* this plugin and adds redundant instructions to every request. See [why, and how to undo it](docs/user-guide.md#why-not-bd-setup-opencode). - -2. Add the version-pinned plugin to `~/.config/opencode/opencode.json` (all projects) or a project's `.opencode/opencode.json`: +2. Pin the plugin in `~/.config/opencode/opencode.json` or `.opencode/opencode.json`: ```json { @@ -48,63 +45,31 @@ A compatible range is admission, not proof that every patch was tested. The plug } ``` - OpenCode reloads configuration automatically. Update the pin explicitly when upgrading. Options such as `luna`, `terra`, `stealth` use the [object form](docs/user-guide.md#plugin-options). - -3. Check the install: `opencode debug agents` lists `beads-task-agent`, and `/oc-beads:diagnostics` reports native registration and observed capabilities. - -### Upgrading to 2.4.1 - -Replace the existing plugin pin with `2.4.1` rather than adding another entry. No host upgrade is required on stable 2.3.x or exact OpenCode 2.4.1; exact OpenCode 2.4.2 is newly admitted. Run `/oc-beads:diagnostics` to verify registration and host admission. - -### Upgrading to 2.3.1 - -Replace the existing exact plugin pin with `2.3.1`. This patch fixes overlapping workflow snapshot reads, acknowledges native last-label removal correctly and improves command-mismatch guidance. Supported versions and options are unchanged. Regression tests and package checks cover these corrections; no new full native-host qualification is claimed. - -### Upgrading to 2.3.0 - -Replace the existing exact plugin pin with `2.3.0`, rather than adding another entry. This release adds integrated Plugin / Beads diagnostic tables, `details` and static `help`, with code-populated DATE / VERSION / repository-root PATH under the heading. It retains the OpenCode range and Beads minimum. Native store behavior and ignored legacy `autoMigrate` settings are unchanged; follow the [native upgrade procedure](docs/user-guide.md#native-beads-store-behavior) before upgrading `bd`. The unchanged base retains its recorded 2.2.0 native qualification; diagnostics additionally has deterministic/package checks and owner-reported normal-output canaries on OpenCode 2.3.0. See the [acceptance record](docs/diagnostics-acceptance-2026-11-15.md). + Update the pin explicitly when upgrading ([Upgrading](docs/user-guide.md#upgrading), [changelog](CHANGELOG.md)); options (`luna`, `terra`, `stealth`) use the [object form](docs/user-guide.md#plugin-options). -### Upgrading to 2.2.0 - -Upgrade OpenCode before changing the plugin pin: 2.2.0 requires `>=2.3.0 <2.4`. Then replace the existing plugin entry, not add a second one, and check `/oc-beads:diagnostics`. Existing exact 1.x and beta pins remain available; installations are not upgraded automatically. Staying on OpenCode 2.1? Keep the exact `1.1.0-beta.5` pin, which retains its `>=2.1.1 <2.2` range. Other migration notes are in the [user guide](docs/user-guide.md#upgrading). - -For OpenCode 2.2, keep the released exact `2.1.0` plugin pin; it retains `>=2.2.6 <2.3` support. Version 2.2.0 changes the host range while retaining existing options. To add the optional `beads-task-agent-terra` profile, enable `terra: true` in the object form. It uses `openai/gpt-6.1-terra#medium`; the default agent still inherits its model, Luna Max remains available, and both optional profiles can coexist. Enabling a profile does not authorize work or change the parent route. +3. Verify: `opencode debug agents` lists `beads-task-agent` and `/oc-beads:diagnostics` reports native registration and observed capabilities. ## First use -In an initialized project: - ```text /oc-beads:diagnostics /oc-beads:ready ``` -Diagnostics shows compact Plugin and Beads check tables. Use `/oc-beads:diagnostics details` for bounded evidence and `/oc-beads:diagnostics help` for the static reference. Collection uses strict-readonly native store access for the sync target and may connect to the configured database in server mode. Remote history remains unchecked on Beads 1.3.1 and 1.3.4. The normal submitted prompt can still load native full prime. The visible answer is model-mediated. See the [diagnostics reference](docs/diagnostics.md) for rows, states and remedies. `ready` lists actionable work; listing alone never claims anything. Then ask in plain language, for example: - -```text -Claim bd-a1b2 and work it to its acceptance criteria. Checkpoint what you learn. -``` +`/oc-beads:diagnostics` shows what’s working, what needs attention, and what couldn’t be verified in the plugin and Beads workspace. Use `details` for evidence or `help` for the static reference. It doesn’t check database integrity or confirm a remote is in sync. See the [diagnostics reference](docs/diagnostics.md). -The agent claims the issue atomically and appends checkpoints under the actual session-and-agent actor. It validates against acceptance, then stops with that item instead of picking up other work. Each typed operation is checked against your OpenCode permission rules. To delegate, ask the agent to hand the issue to `beads-task-agent`. +`/oc-beads:ready` lists actionable work without claiming it. Then ask in plain language (e.g., *"Claim bd-a1b2, work it to acceptance, and checkpoint learnings"*) or delegate to `beads-task-agent`. ## Known limitations -- **Workflow guidance after a model switch.** This is an unresolved deficiency. After native conversation compaction on model A, switching to model B that cannot replay A's native context can make earlier workflow instruction snapshots and captured diagnostics unavailable. The plugin reports that guidance as unavailable and continues with the ordinary request; it does not reconstruct it. The limitation affects prompt guidance only: it does not change or repair the Beads issue database or its stored data. It is tracked upstream as [upstream issue #57424](https://github.com/anomalyco/opencode/issues/57424) and locally as `opencode-beads-o66`. -- **Rejecting a permission is not Stop.** If you reject one nested operation, it does not run and is not retried. However, that does not promise to end the rest of the composition, because each later operation gets its own permission check. Use explicit Stop/Cancel to stop the composition. -- **Bounded evidence.** Bounded qualification covers exact OpenCode 2.3.0 and a genuine OpenAI workflow, with the deferred cases described above. It is not a model-reliability, token-saving, cross-provider checkpoint or multi-hour claim. +- **Rejecting a permission is not Stop.** Denying one nested operation skips it without retry; later operations still get their own permission checks. Use explicit Stop/Cancel to halt a composition. +- **Model switch after compaction.** After native conversation compaction on model A, switching to model B that cannot replay A's context can make prior workflow snapshots and diagnostics unavailable. The plugin reports guidance unavailable without reconstructing it; this affects prompt guidance only and does not change or repair the Beads issue database or its stored data ([upstream issue #57424](https://github.com/anomalyco/opencode/issues/57424), `opencode-beads-o66`). ## Documentation -- [User guide](docs/user-guide.md): options, upgrading, context injection, native store behavior, workflows, task agent, customization, compatibility and troubleshooting. -- [Code-mode guidance](assets/oc-beads/resources/CODE_MODE.md): composing typed operations and recovering from partial or uncertain outcomes. -- [Documentation index](docs/README.md): where behavior, rationale, reference facts and historical evidence live. -- [OpenCode integration reference](docs/opencode-sdk-contract.md) and [Beads artifact policy](docs/beads-artifact-policy.md). -- [Changelog](CHANGELOG.md) and [security policy](SECURITY.md). +- [User guide](docs/user-guide.md) · [Changelog](CHANGELOG.md) · [Diagnostics](docs/diagnostics.md) · [Compatibility evidence](docs/compatibility-evidence.md) +- [SDK reference](docs/opencode-sdk-contract.md) · [Code-mode guidance](assets/oc-beads/resources/CODE_MODE.md) · [Beads artifact policy](docs/beads-artifact-policy.md) · [Documentation index](docs/README.md) · [Security](SECURITY.md) ## Authorship and license -This is an independent project maintained by Matt Jackson. It began as a fork of [Josh Thomas's `opencode-beads`](https://github.com/joshuadavidthomas/opencode-beads), and the original work remains credited to its author. Its project-owned guidance includes attributed MIT-licensed excerpts; it redistributes no upstream executable, host integration or sync-managed vendor tree. See the [notice](assets/oc-beads/THIRD_PARTY_NOTICES.md). The daily/manual maintenance workflow checks tagged CLI compatibility and independently compares reviewed upstream integration sources with current MAIN. Completed source changes are informational; adoption remains a human decision. - -opencode-beads is licensed under the MIT license. See [`LICENSE`](LICENSE). - -opencode-beads is not built by or affiliated with the OpenCode team. OpenCode is ©2025 Anomaly. +Maintained by Matt Jackson; forked from [Josh Thomas's `opencode-beads`](https://github.com/joshuadavidthomas/opencode-beads), with original work credited to Josh Thomas. Project-owned guidance includes attributed MIT-licensed excerpts with no vendored executable or sync tree ([notice](assets/oc-beads/THIRD_PARTY_NOTICES.md)). MIT licensed ([`LICENSE`](LICENSE)). This project is not affiliated with the OpenCode team. diff --git a/bun.lock b/bun.lock index 148bbbe..9844ae5 100644 --- a/bun.lock +++ b/bun.lock @@ -9,6 +9,7 @@ "@tsconfig/bun": "1.0.9", "@types/bun": "1.3.4", "@types/node": "^22.0.0", + "ajv": "8.17.1", "oxlint": "1.93.0", "prettier": "3.6.2", "typescript": "5.9.3", @@ -256,6 +257,8 @@ "agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="], + "ajv": ["ajv@8.17.1", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="], + "ansi-regex": ["ansi-regex@6.4.0", "", {}, "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw=="], "ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="], @@ -324,6 +327,10 @@ "extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="], + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "fetch-blob": ["fetch-blob@3.2.0", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="], @@ -384,6 +391,8 @@ "json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="], + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + "json-stringify-nice": ["json-stringify-nice@1.1.4", "", {}, "sha512-5Z5RFW63yxReJ7vANgW6eZFGWaQvnPE3WNmZoOJrSkGju2etKA2L5rrOa1sm877TVTFt57A80BH1bArcmlLfPw=="], "jsonparse": ["jsonparse@1.3.1", "", {}, "sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg=="], @@ -482,6 +491,8 @@ "redis": ["redis@6.3.0", "", { "dependencies": { "@redis/bloom": "6.3.0", "@redis/client": "6.3.0", "@redis/json": "6.3.0", "@redis/search": "6.3.0", "@redis/time-series": "6.3.0" } }, "sha512-XFQbPie1lGpKeUZ8ySYY43yLnQy/iIQtHNvIr/1XdaABpb96rUSdm3Mfl+98FEVbv9ZJIzINMno5s0Nh8E5LEw=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + "rimraf": ["rimraf@5.0.10", "", { "dependencies": { "glob": "^10.3.7" }, "bin": { "rimraf": "dist/esm/bin.mjs" } }, "sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ=="], "run-applescript": ["run-applescript@7.1.0", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="], diff --git a/docs/README.md b/docs/README.md index 3a88168..57ea890 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,12 +1,19 @@ # Documentation index +## Start here + +- **Using the plugin?** Start with [installation and first use](../README.md). +- **Troubleshooting an installation?** Read the [diagnostics reference](diagnostics.md). +- **Maintaining the integration?** Start with the [canonical specs](#canonical-specs) and the [OpenCode integration reference](opencode-sdk-contract.md). + ## Where each kind of truth lives | Kind | Home | Authority | | --- | --- | --- | | Intended behavior | Canonical specs under `openspec/specs/` | **Normative.** Change it only through an owner-approved OpenSpec change. | | Design rationale | Archived changes under `openspec/changes/archive/` | Explains decisions at the time; does not override the specs. | -| User guidance | [README](../README.md), [user guide](user-guide.md), packaged [`assets/oc-beads/`](../assets/oc-beads/SKILL.md) | Explains current behavior; must agree with the specs. | +| User guidance | [README](../README.md), [user guide](user-guide.md) | Explains current behavior to people using the plugin; must agree with the specs. | +| Shipped agent guidance | [`assets/oc-beads/`](../assets/oc-beads/SKILL.md) | Loaded into OpenCode at runtime. Treat changes as behavior, not ordinary docs edits. | | Reference facts | [OpenCode integration reference](opencode-sdk-contract.md), [Beads artifact policy](beads-artifact-policy.md) | Pinned upstream interfaces, sources and implementation mapping; not product rules. | | Qualification evidence | [Compatibility evidence](compatibility-evidence.md), with links to the original runs | Records which configurations and behaviors were actually tested, not what the plugin admits. | | Live execution status | Beads (`bd`) | Assignment, progress, acceptance and closure; do not duplicate it as mutable state in specs or guides. Dated acceptance evidence remains in historical records. | @@ -28,6 +35,8 @@ publication or activation authority. ## Current documents +### Human user and maintainer guides + - [User guide](user-guide.md): installation details, options, upgrading, context, native store behavior, workflows, task agent, compatibility and troubleshooting. - [Diagnostics reference](diagnostics.md): normal/details/help views, row sources and states, remedies, instruction scope, hooks and native boundaries. - [OpenCode integration reference](opencode-sdk-contract.md): pinned host interfaces and where the adapter uses them. @@ -35,10 +44,14 @@ publication or activation authority. - [Native release probe](native-release-probe.md): opt-in canary runbook for maintainers. - [Compatibility evidence](compatibility-evidence.md): measured coverage and exclusions behind the current compatibility claims. -## Historical records +### Shipped agent guidance + +Packaged under `assets/oc-beads/` and loaded by OpenCode agents at runtime rather than maintained as human onboarding prose: + +- [`assets/oc-beads/SKILL.md`](../assets/oc-beads/SKILL.md): packaged `oc-beads` skill entry. +- [Code-mode guidance](../assets/oc-beads/resources/CODE_MODE.md): typed `beads` namespace composition and recovery rules. +- [Troubleshooting guidance](../assets/oc-beads/resources/TROUBLESHOOTING.md): agent-side compact, restore, and recovery guidance. -Archived OpenSpec designs explain past decisions. `docs/reviews/`, [`docs/history/`](history/), -and dated analysis, qualification and acceptance records describe their named revisions. -Follow those records to investigate a past decision, not to learn current operating -instructions. Preserve original verdicts and failures; link to a pinned Git revision -when a superseded report no longer needs a live path. +Archived OpenSpec designs explain past decisions. Superseded qualification and +review records remain in Git history, not in the current documentation tree. See +the [release checklist](../AGENTS.md#checklist) for retention. diff --git a/docs/beads-1.3.4-review-2026-11-09.md b/docs/beads-1.3.4-review-2026-11-09.md deleted file mode 100644 index c7887ec..0000000 --- a/docs/beads-1.3.4-review-2026-11-09.md +++ /dev/null @@ -1,23 +0,0 @@ -# Beads 1.3.4 review — 2026-11-09 - -Reviewed from plugin 2.0.0 source `bb496c1bc0b05a4131856c90106f05748e396d57`. Disposition: validate exactly Beads 1.3.4, retaining minimum 1.3.1. No adapter runtime, packaged guidance, API or dependency change is needed for the reviewed deltas. This is CLI compatibility evidence, not a guarantee about every upstream storage topology or an operator upgrade. - -## Reviewed deltas and disposition - -- [1.3.2 release/upgrade notes](https://github.com/gastownhall/beads/releases/tag/v1.3.2): retention, backup, concurrent blocked-state recheck, least-privilege connections and export fixes belong to the installed CLI. The migration0059 stored-blockedness warning can affect ready results in older adopted stores; the upstream notes prescribe `bd recompute-blocked` for affected workspaces. The adapter must report CLI results honestly, not recompute or repair them itself. No operator action was performed here. -- [1.3.3 release](https://github.com/gastownhall/beads/releases/tag/v1.3.3) and [tagged changelog, including rc.1 upgrade notes and known issues](https://github.com/gastownhall/beads/blob/v1.3.3/CHANGELOG.md): `.beads/.env` allowlisting, user-owned mail delegation and remote URL refusal are upstream boundaries. The plugin invokes the installed CLI with project context and explicit executor attribution; it does not parse these settings or implement mail/remote transport. `src/prime.ts` retains stdout and stderr on failures, unlike the cited Gas City stderr-only failure. No new environment or routing layer is warranted. -- [Exact-id deletion change](https://github.com/gastownhall/beads/blob/v1.3.4/cmd/bd/delete.go) and rules-compaction confirmation changes: the eleven typed operations in `src/continuity.ts` do not implement deletion or rules compaction. `src/workflows.ts` delivers scoped command guidance rather than parsing either changed JSON shape. Existing target/effect and authority guidance remains applicable; no prompt change is required. -- Database timestamp preservation, proxy startup, doctor cleanup, GitHub sync, history compaction and security dependency fixes remain CLI-owned. The adapter neither identifies proxy children from their config filename nor reimplements these internals. The changelog's remaining shared-endpoint credential, stale-local-copy sync and server reset-data issues remain upstream limitations; validation does not claim their repair, confinement or universal store safety. No downstream mitigation, credential/config change or store experiment was undertaken. -- [1.3.4 release](https://github.com/gastownhall/beads/releases/tag/v1.3.4) and [tagged environment loader/tests](https://github.com/gastownhall/beads/blob/v1.3.4/cmd/bd/envfile_test.go): the exact `GT_ROOT` key is admitted again, shell environment still wins, and other `GT_*` keys remain refused. The [loader](https://github.com/gastownhall/beads/blob/v1.3.4/cmd/bd/main.go) delegates admission upstream. This fixes the 1.3.3 rig notice/formula-discovery regression; no local workaround is needed. -- **Migration0062 warning retained:** 1.3.4 does not include the [events restoration fix](https://github.com/gastownhall/beads/issues/7039). Its [upgrade notes](https://github.com/gastownhall/beads/blob/v1.3.4/CHANGELOG.md) say not to run `bd compact` or `bd flatten` on clones that adopted that migration by pull/bootstrap or were cloned afterward: these can erase history needed for recovery. The plugin's compact command explicitly distinguishes semantic `bd admin compact` from Dolt-history squashing. No local migration guard, backfill, history compaction or live-store test is justified by this review. - -The [tagged comparison](https://github.com/gastownhall/beads/compare/v1.3.1...v1.3.4), including the loader, exact-id deletion and migration timestamp changes, was inspected against the prime/guard/typed-operation/workflow seams and artifact policy. No new migration file or embedded engine change is claimed by these patch releases; existing guard behavior and its 1.3.1 refusal fixtures remain unchanged. - -## Evidence and separate baselines - -[Scheduled run 42591441654](https://github.com/snarkipus/opencode-beads/actions/runs/42591441654) installed exact bd 1.3.4 (`7ef2fd05e: HEAD@7ef2fd05eb0c`), passed Check bd contract, and failed only Require review of new Beads releases because validated metadata was still 1.3.1. The retained receipt is `/opt/data/research/opencode-beads-1.3.4-status/latest-scheduled.log`. This exercises the existing disposable contract, including actual guard, prime, init/setup, typed operations and actor/outcome assertions. Native OpenCode qualification's 1.3.4 fixture is separate evidence and is not the release-note review. - -The artifact policy's Beads 1.3.1 comparison is historical integration evidence and stays intact. CLI validation does not advance `docs/claude-code-integration-inventory.json`, adopt upstream source, raise the supported minimum, change package 2.0.0, or publish a release. No real store was migrated or used as a fixture. - - -Local candidate verification on 2026-11-09 ran the unchanged `bun run test:bd-contract` once with exact bd 1.3.4 (`7ef2fd05e: HEAD@7ef2fd05eb0c`) and actor `codex:d1075a97`: **contract satisfied**. All stores used by that command were disposable under the environment scratch directory; the real tracker was not a fixture. The full receipt is `/opt/data/research/opencode-beads-upstream-maintenance-implementation/bd-contract.log`. No live Actions source-comparison execution is established by this CLI receipt. diff --git a/docs/beads-artifact-policy.md b/docs/beads-artifact-policy.md index 2ffcecf..b7aab8b 100644 --- a/docs/beads-artifact-policy.md +++ b/docs/beads-artifact-policy.md @@ -1,16 +1,11 @@ # Beads Artifact Policy -Status: current policy for the published 2.x line. The package includes attributed MIT-licensed excerpts in project-owned guidance; it redistributes no upstream executable, host integration or sync-managed vendor tree. See the [notice](../assets/oc-beads/THIRD_PARTY_NOTICES.md). It ships project-owned adaptations under `assets/oc-beads/` (one skill, 15 corpus resources, CODE_MODE and the adapted ADR, 17 explicit links), 30 native commands and the typed `beads` operations, rather than an upstream executable or host-specific integration. The installed `bd` CLI remains the execution and data owner, and `bd init` owns the shared `.agents/skills/beads`. The sections below are dated rationale and evidence: earlier stable exclusion and one-bead descriptions, and "candidate", "unpublished" or "withheld" wording, describe the state when they were written. Current behavior is defined by the canonical specs; see the [documentation index](README.md). +Status: current policy for the published 2.x line. The package includes attributed MIT-licensed excerpts in project-owned guidance; it redistributes no upstream executable, host integration or sync-managed vendor tree. See the [notice](../assets/oc-beads/THIRD_PARTY_NOTICES.md). It ships project-owned adaptations under `assets/oc-beads/` (one skill, 15 corpus resources, CODE_MODE and the adapted ADR, 17 explicit links), 30 native commands and the typed `beads` operations, rather than an upstream executable or host-specific integration. The installed `bd` CLI remains the execution and data owner, and `bd init` owns the shared `.agents/skills/beads`. Current behavior is defined by the canonical specs; see the [documentation index](README.md). ## Current collector maintenance -The daily/manual `beads-contract` workflow defines independent tagged-CLI and advisory MAIN source-comparison jobs, with collector JSON and exit status in the Actions summary. Completed source comparisons are informational successes; unavailable evidence fails only the independent source job, never a product/release prerequisite. Adoption and reviewed source-baseline changes require explicit human disposition under the [canonical upstream-review spec](../openspec/specs/upstream-review/spec.md). The [1.3.4 CLI review](beads-1.3.4-review-2026-11-09.md) leaves the historical 1.3.1 integration comparison and marketplace-main inventory intact. The dated source-only acceptance below remains historical evidence, not proof of workflow execution. +The daily/manual `beads-contract` workflow defines independent tagged-CLI and advisory MAIN source-comparison jobs, with collector JSON and exit status in the Actions summary. Completed source comparisons are informational successes; unavailable evidence fails only the independent source job, never a product/release prerequisite. Adoption and reviewed source-baseline changes require explicit human disposition under the [canonical upstream-review spec](../openspec/specs/upstream-review/spec.md). The [1.3.4 CLI review](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/beads-1.3.4-review-2026-11-09.md) leaves the historical 1.3.1 integration comparison and marketplace-main inventory intact. -## Historical policy summary - -Preserved for release provenance. - -Status: current stable implementation policy, under review in the [full integration decision packet](claude-code-integration-analysis.md). Owner selections for an opt-in beta/next redesign are recorded; task 2.1 supplied the accepted guidance assets and the tasks 2.2/3.3 candidate adds package inclusion and skill registration. All 30 command definitions now register through native precedence; runtime qualification remains unexecuted. Revised for 1.0.0 by `opencode-beads-w5y`. The package vendors no upstream Beads artifacts. The current source package includes the project-owned adaptations under `assets/oc-beads/`; the published stable artifact remains separate. Earlier revisions were the OpenCode V2 port (`opencode-beads-2zs`), the 0.9.0 contract (`opencode-beads-98l`), and the retired 0.8.0 companion lifecycle decision. ## Evidence @@ -33,7 +28,7 @@ Upstream host integrations at Beads `v1.3.1` (commit `c1c4b642ac1c08d8c828007a1c | Upstream artifact | Policy | Reason | | --- | --- | --- | -| `skills/beads/commands/*.md` | Retired in 1.0.0 (`opencode-beads-2zs.4`) | Claude Code command templates, not part of the native OpenCode or Codex install. They largely wrap single `bd` subcommands and duplicate `bd prime` plus the canonical `.agents/skills/beads` skill, which OpenCode V2 discovers natively. V2 plugin command registration uses executable code, but native Markdown and JSON prompt commands are also supported. Retirement was a package policy choice, not a limitation of all V2 commands; see the [full integration analysis](claude-code-integration-analysis.md). | +| `skills/beads/commands/*.md` | Retired in 1.0.0 (`opencode-beads-2zs.4`) | Claude Code command templates, not part of the native OpenCode or Codex install. They largely wrap single `bd` subcommands and duplicate `bd prime` plus the canonical `.agents/skills/beads` skill, which OpenCode V2 discovers natively. V2 plugin command registration uses executable code, but native Markdown and JSON prompt commands are also supported. Retirement was a package policy choice, not a limitation of all V2 commands; see the [full integration analysis](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/claude-code-integration-analysis.md). | | `agents/task-agent.md` | Retired in 1.0.0 (`opencode-beads-w5y`) | A Claude Code-only artifact whose autonomous multi-task loop this adapter deliberately does not adopt. Before retirement, its body was never executed: the runtime prompt was already a project-owned bounded OpenCode adaptation, and only the upstream description string reached users, misdescribing the one-bead worker. The task agent's prompt and description now live in `src/guidance.ts`. It does not execute upstream's autonomous multi-task loop. | | `skills/beads/SKILL.md`, `skills/beads/adr/`, and `skills/beads/resources/` | Excluded | `bd init` owns per-project initialization. Its automatic Codex project integration creates the canonical shared skill at `.agents/skills/beads`, which OpenCode discovers. This package does not fork, install, update, or remove that skill. | | Claude/Codex manifests and hooks | Excluded | `.claude-plugin` and `.codex-plugin` formats and lifecycle hooks are not OpenCode plugin registration formats. This adapter implements the equivalent lifecycle through OpenCode V2's session context hook and session events. | @@ -45,7 +40,7 @@ Until 1.0.0 a daily workflow synced the upstream task agent into `vendor/` with ### Consequences -- No `vendor/` directory, sync workflow, or provenance manifest. Packages contain only `src/`, `README.md`, `LICENSE`, and `package.json`. +- No `vendor/` directory, sync workflow, or provenance manifest. The package contains the adapter and project-owned guidance, not upstream vendor files. - `scripts/bd-contract.ts` exercises a real `bd` in a disposable repository: version parsing and the supported minimum, config-only workspace discovery, `bd prime --full` under a Claude Code MCP configuration, and every command named by the task-agent prompt. It runs the plugin's own compatibility checks; it does not qualify Beads schema-engine behavior. - CI runs the contract against `beads.validated` from `package.json`. The scheduled `beads-contract` workflow runs it daily against the latest stable Beads release and fails when a release breaks the contract or has not been reviewed yet, replacing the sync PRs as the new-release signal. After reviewing a release's upgrade notes against the surfaces above, the maintainer updates `beads.validated` and the README compatibility table, and records any follow-up work in Beads. - The task-agent contract is tested directly against the project-owned prompt and description. @@ -53,7 +48,7 @@ Until 1.0.0 a daily workflow synced the upstream task agent into `vendor/` with ## Skill ownership -OpenCode does not search npm package internals, so this package ships no skill payload. Projects install `bd` once on the host, create a Git worktree when necessary, and run `bd init` in each project. The canonical `.agents/skills/beads` is created by `bd init`'s automatic Codex project integration, not by `bd setup opencode` and not by this plugin. +OpenCode does not search npm package internals; the plugin explicitly registers its packaged `oc-beads` skill. Projects install `bd` once on the host, create a Git worktree when necessary, and run `bd init` in each project. The canonical `.agents/skills/beads` is created by `bd init`'s automatic Codex project integration, not by `bd setup opencode` and not by this plugin. Users upgrading from 0.8.0 must remove its old `.opencode/skills/beads` installation with `bunx @snarkipus/opencode-beads@0.8.0 remove` before upgrading. The 0.9.0 package has no companion executable, `/beads:setup` command, ownership manifest, collision policy, or `dist/init` payload. @@ -82,40 +77,4 @@ Any future upstream artifact proposed for inclusion must first show: - deterministic validation, package-content tests, and failure behavior; - a documented owner and removal or upgrade path. -## Selected beta/next source candidate - -The [owner record](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md) selects package-owned `oc-beads` skill/resources, `oc-beads:` workflows, N1 continuity tools and scope-bounded continuation on OpenCode `>=2.1.1 <2.2`. This is an opt-in redesign; the current implementation policies above remain historical/current-stable descriptions, not prohibitions against the selected future assets. No upstream shared skill or user file is overwritten, and bd remains executable/data owner. Delivery is complete through npm with native registration/disposal; no manual rich-skill installation. - -Task 2.1 owns the source assets at `assets/oc-beads/`: one `SKILL.md`, the 15 selected marketplace-main resources, and the adapted ADR-0001 rationale. These are project-owned adaptations of the inventory's pinned marketplace-main commit `4a67d0d0288c1b4ee23e17fc896f47616931ba2d`; the [inventory](claude-code-integration-inventory.json) records each selected mapping and disposition. `TROUBLESHOOTING.md` is a curated replacement that preserves the support topic while removing unsafe stale repair advice. The skill links all 16 supporting files explicitly because host auto-listing is limited to ten. Advanced files stay on demand. - -The assets preserve Beads CLI ownership and use `bd prime` and installed command help as dynamic syntax references. Examples of writes carry an explicit executor actor. The agent-bead resource documents that `bd agent` and `bd slot` are not exposed by the inspected installed CLI; ordinary issue claims, assignees, and heartbeat leases are related supported conventions, not a complete substitute for those APIs. Shared `.agents/skills/beads` remains Beads-owned and must not be overwritten. - -The tasks 2.2/3.3 source candidate includes these assets in npm and registers `oc-beads` through a public skill transform with per-rebuild candidate collision checks. No initial list gate permanently suppresses a removed skill customization. Package smoke checks both exports and all 16 installed-base links/resource bytes, invokes actual registration callbacks and exercises all 30 native command bodies with attachments/delivery. It never copies assets into user repositories, settings or upstream caches. One ordinary transform registers the 29 selected stems plus status; initial command collisions are diagnostic-only. Ordinary user configuration/file commands win through later native transforms and removing an override restores the package definition. Same-name other-plugin conflicts follow normal native order. Status reports effective names/descriptions, observable mismatches, missing entries and lookup failures; public owner identity and identical-description overrides are unobservable, and matching descriptions do not prove ownership. See [native registration and diagnostics](opencode-sdk-contract.md#tasks-2233-source-candidate-native-registration-and-diagnostics). No initialization, synchronization or permission changes occur. - -Completed marketplace-main source comparisons succeed whether content changed or not. Ordinary development changes are informational evidence with immutable review links, not drift warning/error annotations, product CI failures, mandatory immediate review/adoption or release gates. A lagging tagged CLI release does not make main changes actionable compatibility failures; changes requiring unreleased features may be deferred until verified inclusion in a supported release. Retrieval/comparison failure is unavailable evidence, never successful no change; it may fail a separate advisory collector but cannot gate product/release checks. Stable tagged CLI compatibility tests remain independent and retain real failure semantics. Reuse the scheduled pattern only under workflow-edit authority. No GitHub issues, issue-write permissions, automatic copying, baseline advancement or releases. Human review selects subsequent Beads execution work. This planning reconciliation does not edit the workflow or package. - -SKILL.md explicitly links all 15 resources plus ADR; host auto-listing of ten files is insufficient. Package fixtures verify installed-base links, and live acceptance honors external-directory ask/deny without concealing unreachable guidance. Ordinary configuration/file command precedence is preserved across rebuilds; competing plugin transforms follow native order, with no universal collision guarantee. Pinned package/config ordering is distinct from the original reviewer's unpinned released-cache suffix-reactivation evidence; neither is live qualification. Before the prerelease compatibility change reaches stable main, separately authorized release work must settle a stable 1.0.x maintenance branch strategy; no branch/release action or present source-work blocker is implied. - -Operative host selection now targets exact 2.1.1; the [contract delta](opencode-2.1.1-contract-delta.md) preserves historical evidence and separates source admission from unexecuted runtime acceptance. This candidate changes source/package registration only; shared skills and operator runtime remain untouched. - -### Task 5.1 accepted source collector — usage and evidence - -Parent accepted the source/script/tests after the [Opus READY review](reviews/opus-source-collector-review-vuy7.md), verified all reviewed file hashes unchanged, and independently passed 166 tests, typecheck, strict global OpenSpec, pinned source/corpus validation and whitespace checks. The parent also independently repeated the live comparison below: five upstream edits still returned informational changed/exit 0 with no drift annotations. This is source acceptance only; scheduled/CI wiring is not implemented or activated. The exact published source handle is recorded in `opencode-beads-vuy.7`. - -Run the read-only [collector](../scripts/check-beads-integration.ts) locally: - -```sh -npm exec --yes --package=bun@1.3.14 -- bun scripts/check-beads-integration.ts -``` - -It reads `marketplace_main` in the existing [inventory](claude-code-integration-inventory.json), resolves the repository's default branch once to an immutable candidate, and retrieves complete recursive Git trees for both commits. Selection includes every blob under `plugins/beads/` and `internal/templates/skills/beads/`, plus each inventory path outside those roots. Baseline membership/blob IDs must match the reviewed inventory. Comparison uses upstream Git blob IDs and modes, never local adaptation bytes. Output sorts paths and includes both commits, source links and a direct comparison link. Unique removed/added pairs with identical blob ID and mode are reported as exact renames; ambiguous or edited moves remain additions/deletions. - -Completed comparisons emit informational JSON (`kind: completed`, `level: info`, `channel: development-source`, `status: changed` or `unchanged`) and exit **0**. Incomplete/truncated trees, missing/malformed required data, HTTP/network failures or an inventory mismatch emit `kind: unavailable` and exit **2**, without a successful comparison status. Requests have a 20-second timeout each; optional existing `GH_TOKEN` or `GITHUB_TOKEN` authenticates read-only GitHub API requests without printing credentials. Truncated trees are unavailable evidence rather than partial comparisons. - -This collector has no workflow/CI wiring and is not a product, runtime compatibility or release gate. Future authorized wiring must isolate its failures from those gates. Stable tagged CLI contract tests and their actual failures remain independent; the collector does not query tags or establish release inclusion. There is no stored candidate state, source copying, automatic adoption, baseline advancement option, version change or issue/PR creation. Human review may accept an adaptation, accept no local change with rationale, or defer adoption until verified inclusion in a supported release. Only an explicit reviewed inventory revision can change the baseline; detection grants no authority to do so. - -Fixture evidence in [upstream-review.test.ts](../tests/upstream-review.test.ts) exercises the actual runner and subprocess entrypoint: unchanged and changed MAIN both exit 0; changed MAIN with the same independent tagged CLI result stays informational with no warning/error annotations or mutation; a repeated candidate emits identical output; truncated retrieval exits 2 as unavailable. Fixtures also cover complete membership, adds/deletes/edits, exact renames, support paths, unrelated paths, malformed/error responses, explicit reviewed inventory input and refusal of a blind advancement argument. They do not qualify a live CLI or host. - -Separate read-only live evidence on 2026-10-21: [reviewed baseline `4a67d0d0288c1b4ee23e17fc896f47616931ba2d`](https://github.com/gastownhall/beads/tree/4a67d0d0288c1b4ee23e17fc896f47616931ba2d) versus [resolved MAIN `882317770349f3c2f61e603b5c1e74030354c955`](https://github.com/gastownhall/beads/tree/882317770349f3c2f61e603b5c1e74030354c955) completed with **exit 0**, informational `changed`, and 74 selected files at each commit. Five edited support paths were reported: `cmd/bd/init.go`, `cmd/bd/init_agent.go`, `cmd/bd/init_embedded_test.go`, `cmd/bd/setup/claude.go`, and `cmd/bd/setup/claude_test.go`. The [exact source comparison](https://github.com/gastownhall/beads/compare/4a67d0d0288c1b4ee23e17fc896f47616931ba2d..882317770349f3c2f61e603b5c1e74030354c955) is source information only; no tagged-release behavior, local adoption or baseline advancement was established. Parent source acceptance is recorded above; no scheduled/CI activation or tagged CLI compatibility outcome is implied. - -The diagnostic child probes are `version`, `context --json`, `hooks list --json`, and `--readonly dolt remote list --json --sandbox`. The 1.3.1 and 1.3.4 source and fixture evidence supports the scoped `BD_DISABLE_METRICS=1`, `BD_DISABLE_EVENT_FLUSH=1`, and `OTEL_SDK_DISABLED=true` overlay. Strict readonly skips native maintenance and automatic export during listing. Ordinary prime retains native behavior. See [Read-only native diagnostics](../openspec/specs/workflow-access/spec.md#requirement-read-only-native-diagnostics). +For the advisory source comparison, see the [collector entry point](../scripts/README.md) and its [reviewed input inventory](claude-code-integration-inventory.json). diff --git a/docs/beta-release-preparation-jrm.md b/docs/beta-release-preparation-jrm.md deleted file mode 100644 index d596183..0000000 --- a/docs/beta-release-preparation-jrm.md +++ /dev/null @@ -1,36 +0,0 @@ -# Beta preparation — opencode-beads-jrm - -## Parent-reviewed candidate - -- Package: `@snarkipus/opencode-beads@1.1.0-beta.1`. -- Intended npm dist-tag: **next**. Registry **latest remains 1.0.2**; no publication or tag mutation has occurred. -- Exact prepared archive: `/opt/data/cache/scratch/oc-beads-beta-preparation/archive/snarkipus-opencode-beads-1.1.0-beta.1.tgz`. -- SHA-256: `c78a1bb98e0703172205c4f46bc9e5ea26bf50eb1daf2280ff5ad09e169cceea`. -- Baseline: merged implementation `450176905e46ac96f0f2aab23c9b1cc5281cd62b`. -- Sole implementation executor: `codex:oc-beta`, Sol/high, session `01a16067-fbf7-75f1-a047-7513ae39d5b6`. - -The normal public plugin entrypoint now enables the already-qualified registration. Opt-in means selecting this beta artifact; no external wrapper, dependency injection or additional activation setting is required. Existing version admission, host interface checks, per-operation permissions, identity, guards, cancellation and outcomes remain intact. No argv/normalizer/runner changes were made. - -Release preparation supports stable/latest and beta/next explicitly. GitHub prerelease metadata must agree with the package version; conflicting or missing CLI metadata fails before an archive or publication. The protected release workflow verifies the one prepared archive and passes an explicit dist-tag to npm. Existing OIDC, attestation and immutable archive handling are retained. - -## Verification - -Parent independently ran **196 tests, zero failures**, typecheck, package smoke and exact-archive verification with `--tag v1.1.0-beta.1 --dist-tag next --prerelease true`. Packed-package tests exercise the ordinary public setup, eleven native code-mode definitions, 30 commands, 17 resource links and owned disposal. Channel tests cover stable/beta and mismatched metadata; the implementation worker retained RED/GREEN evidence under the scratch root. - -A short actual OpenCode **2.1.1** native run loaded the ordinary unchanged archive through package configuration, without wrapper or internal qualification injection. Native search observed all eleven `tools.beads.*` signatures; actual native execute returned an acknowledged structured get for the disposable `BETA_PUBLIC_ENTRY_READ_PROOF` issue. Controlled provider responses drive these entrypoint mechanics; prior genuine model semantics remain the accepted implementation evidence, not a repeated model campaign. Parent inspected the native messages and independently compared all **31 archive files** to installed and current source bytes. - -All **145 protected repository paths** remained unchanged. Parent independently confirmed owned listener absence. Operator executable/config/auth remained unchanged; the controlled fixture used no genuine provider account. Initial scratch harness attempts and their logs are retained separately; only the final `native4` observations are passing evidence. No registry or operator mutation is implied by local archive preparation. - -## Publication boundary - -This report is preparation evidence, not proof of a public release. Source/CI review precedes tag/GitHub prerelease/npm publication. The implementation worker did not commit, push, tag, publish or close the release task. Parent owns source integration; owner approval gates actual publication. After publication, verify `next=1.1.0-beta.1`, `latest=1.0.2`, registry/release archive digests and exact clean-consumer installation before closing the release task. - -Proposed owner installation after publication: - -```json -{ - "plugins": ["@snarkipus/opencode-beads@1.1.0-beta.1"] -} -``` - -`@next` follows the beta channel; the exact version is preferable for evaluation reproducibility. OpenCode `>=2.1.1 <2.2` and Beads `>=1.3.1` remain prerequisites. No operator runtime upgrade or installation is performed automatically. diff --git a/docs/claude-code-integration-analysis.md b/docs/claude-code-integration-analysis.md deleted file mode 100644 index d1c7304..0000000 --- a/docs/claude-code-integration-analysis.md +++ /dev/null @@ -1,187 +0,0 @@ -# Full Beads integration experience: analysis and owner decision packet - -Status: historical evidence collected 2026-10-17 and reconciled 2026-10-18 remains below. Current 2026-10-21 [installed/model evidence and 6.3 reconciliation](opencode-installed-model-continuation-vuy9.md) pass the selected bounded 6.2 worker evaluation after accepted source/native/Stop prerequisites. Exact2.1.1/Beads 1.3.1, unchanged accepted package and genuine OpenAI Sol/high substantiate A–D semantics; actual corrected cleanup/17 resource access are reused. All 19normative requirements and every 73 release/74 marketplace-main disposition plus CODE_MODE are mapped without claiming all admin operations or comparative Claude/model quality. Parent acceptance is complete for all 16 implementation tasks; release and activation remain separately gated. Ordinary typed activation is withheld and its internal installed-source bootstrap remains scratch-only. Same-provider/model native replay is observed; cross-route migration, multi-hour reliability and stronger immediate location-reload revocation are not certified. Historical failed probes/reviews remain unchanged. No source/operator/publication authority is implied. - -## Outcome and evidence boundaries - -Matt reports better ongoing task notes and more appropriate `bd remember` use with Claude Code's Beads integration than with OpenCode and OpenAI models. This is an observed user experience, not controlled evidence that the host, provider, model, or prompt caused it. The objective is recovery of attempted approaches, learning, rationale, blockers, and the next action across sessions without repeated user prompting. More writes alone are not success. - -This review enumerates the full shipped plugin subtree, shared skill template, marketplace entry, and the implementation paths that connect them. Static source evidence establishes availability and intended wiring, not that a model loaded a resource, followed a prompt, or successfully invoked a stale command. No Claude/OpenCode inference trial or Beads command was run. Examples of Beads commands below describe future behavior only. - -The [native architecture assessment](opencode-native-parity-assessment.md) completes the behavior-to-mechanism investigation: released V2 call sites, experimental candidates, selected N1 bundle, historical 2.0.26 alternative N0 and explicit qualification gaps. It refines the delivery recommendation below without replacing the historical Claude corpus identity. - -### Selected marketplace-main reference - -Read-only GitHub default-branch/commit/tree retrieval on 2026-10-18 resolved `main` to [`4a67d0d0288c1b4ee23e17fc896f47616931ba2d`](https://github.com/gastownhall/beads/tree/4a67d0d0288c1b4ee23e17fc896f47616931ba2d/plugins/beads), equal to the recorded installed revision. The same declared roots/support paths contain **74 files**: 57 plugin files, 2 shared-template files and 15 support files; 29 commands, 15 resources and one ADR remain. All 57 plugin bytes match the installed cache. The separate `marketplace_main` inventory records exact current blob/hash identities and per-member delivery, reason and task mapping. The original 73 release identities are preserved. - -There is one addition (`plugins/beads/BUILD.bazel`, build-only evidence), no deletion and 16 modifications. Plugin manifest versions differ (1.3.1 release versus 1.3.0 installed/main); versions/dates do not establish ancestry. Five guidance files switch examples from replacement `--notes` to `--append-notes`: skill README and WORKFLOWS, PATTERNS, INTEGRATION_PATTERNS, ISSUE_CREATION. ASYNC_GATES adds cross-repository `--repo` guidance. Unchanged rich skill, agent, commands and ADR still need native adaptation, including stale MCP and TodoWrite examples. See [local reference](claude-code-local-reference.md) for the complete categorized delta. - -Current support source also changes prime disable/routing/project-memory guidance and memory write/commit status, budget refusal and empty-value recall. These are **source differences**, not proof the installed CLI has those semantics. N1 must preserve failed/uncertain/landed-but-uncommitted states and qualify supported released CLI output; no source snapshot implicitly authorizes a CLI upgrade. - -### Source pins and scope - -| Source | Exact reference | Evidence / limit | -| --- | --- | --- | -| This repository | `c5c29f2e0cca98826658cc09b7806eb95afca360`, main at start | Historical first-pass baseline. The earlier native assessment started at `7e710b6e5608bb8aef73fccadbd08e761a77a652`; this reconciliation starts at `3dc2ea327ed490ceb9cf0b95c31af77631613287`; existing package and parent changes are preserved. Prior live results remain historical, not rerun here. | -| Historical Beads stable pin | [v1.3.1 release](https://github.com/gastownhall/beads/releases/tag/v1.3.1), published 2026-09-30; annotated tag resolves to `c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c` | Verified with GitHub release/ref/tag APIs; historical inventory source links use this commit. | -| OpenCode V2 source/docs | [`8f7b0120eb6b4aa3da1f82b1a9094a9fb4db2d06`](https://github.com/anomalyco/opencode/tree/8f7b0120eb6b4aa3da1f82b1a9094a9fb4db2d06); `packages/plugin/package.json` says 2.0.32 | Development snapshot, **not the released 2.0.32 source**. The native assessment corrects provenance: released tag is `843a6c514e606b436a7fe713422ace0a93ad3d61`; npm latest was 2.0.32 when the native assessment was recorded. Public, experimental, development-only and unknown-runtime evidence are separated there. No new runtime qualification of 2.0.26. | -| Original OpenCode adapter | [`a508c1205a04516490d9d1078d5a4e788cd6553b`](https://github.com/joshuadavidthomas/opencode-beads/tree/a508c1205a04516490d9d1078d5a4e788cd6553b) | V1 implementation and vendor tree; not evidence of V2 runtime compatibility. | -| OpenSpec | Installed 1.14.2; [official 1.14.3 release](https://github.com/Fission-AI/OpenSpec/releases/tag/v1.14.3), published 2026-10-17 | New release fixes zero-column validation hangs, linked specs, glob bounds and a dependency issue. Installed version is suitable for ordinary local spec-driven files with explicit noninteractive validation and path checks. No upgrade, symlinks, custom schema or setup regeneration needed. | - -[Machine-readable inventory](claude-code-integration-inventory.json): **73 files**, including **56** files under `plugins/beads/`, **2** shared-template files, and **15** explicit supporting sources. Within that inventory: **29 commands**, **15 resources**, **1 ADR**, **2 skill bodies**. Recursive tree API was not truncated. Each entry records Git blob identity, SHA-256, commit link, historical recommendation and selected engineering disposition. Coverage is bounded to these declared roots and support paths; it is not a claim to audit the whole Beads repository. Resource review used systematic heading/trigger enumeration plus the behavior-bearing passages; no resource's CLI examples are certified wholesale. - -## Installation paths and actual reachability - -Subsequent local installation evidence is recorded in [Installed Claude reference integration](claude-code-local-reference.md): Claude recognizes the rich skill, all command entries, agent and hooks. The installed marketplace checkout differs from the pinned release corpus; this does not replace its inventory or establish live model behavior. Future comparisons must align or explicitly distinguish these revisions. The OpenCode packaging objective is a complete owner-selected integration from its npm package, not a hidden separate skill installer. - -| ID / surface | Shipped/runtime connection | Selected adaptation; dependencies and risks | -| --- | --- | --- | -| F01: setup lifecycle | [`setup/claude.go`](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/setup/claude.go) installs `SessionStart` → `bd prime --hook-json`, minimal instruction pointer, project/global/check/remove and legacy-hook cleanup. Comments identify startup/resume/clear/compact. It removes old PreCompact prime hooks. Recognized enabled `beads@…` plugin skips duplicate setup hook registration. | Adapt lifecycle through awaited native V2 context/compaction hooks and observational events (M01/M03/M04); events cannot delay compaction. Keep setup diagnostics and removal understandable. Do not translate Claude hook JSON into OpenCode system text. Detection reduces duplicates but does not prove arbitrary combined installations are duplicate-free. | -| F02: initialization | [`init.go`](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/init.go) creates store/config/version state and integrations; normal non-bare, non-stealth, non-skip-agents path installs Claude, Codex and Cursor integrations. Codex setup writes the shared skill. Init can install Git hooks and stage/commit generated files. | Retain upstream ownership of initialization; document its real side effects. Neither an absent store nor a failed hook authorizes initialization, migration or repair. No initialization occurs in this plan. | -| F03: marketplace | [marketplace entry](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/.claude-plugin/marketplace.json) points to `plugins/beads`; [Claude manifest](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/.claude-plugin/plugin.json) explicitly registers skills/commands and plain `bd prime` on SessionStart and PreCompact. | Adapt the full discoverable experience, not the manifest format. Plain prime is not guaranteed full output: MCP detection can shorten it. Marketplace PreCompact differs from setup's removal of that hook. No evidence here that both hook outputs reach every supported Claude runtime identically. | -| F04: rich skill | [plugin skill](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/SKILL.md) advertises multi-session/dependency/recovery triggers, says to add notes during work, links every resource and ADR. Body/resources load progressively, not all at startup. Manual skill-directory copying is separately documented in its README; that alone does not install marketplace hooks, commands or agent. | Adapt cognitive guidance and resource navigation through package-owned `oc-beads`. CLI help remains dynamic. More resource files alone do not ensure discovery. | -| F05: lean shared skill | [`internal/templates/skills/beads/SKILL.md`](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/internal/templates/skills/beads/SKILL.md) is the local `.agents/skills/beads/SKILL.md` content. It has broad triggers, prime-first advice and basic task workflow but no resource tree, checkpoint examples or explicit remember/recall trigger guidance. | Preserve bd ownership. Enrich experience via the distinct package-owned `oc-beads` surface, not silent overwrite. Its first-step prime instruction and later conditional manual-prime rule can provoke duplicate calls. | -| F06: command catalog | All 29 files are manifest-addressed. Two lack YAML. Several bodies require MCP. [Integration docs](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/docs/integrations/claude-code-plugin.md) explicitly say no MCP server is bundled. | Review every command below; adapt supported workflows instead of blindly loading bodies. Distinguish registration, discovery and successful execution. Exact Claude discovery behavior for malformed/metadata-free templates remains untested. | -| F07: autonomous task agent | [`agents/task-agent.md`](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/agents/task-agent.md) is a convention-discovered Claude agent (also covered by layout test/docs), iterating ready/claim/execute/discover/close. It names MCP tools despite no bundled MCP server. | Adapt native delegation, task selection, validation and knowledge return. Use the selected scope-bounded continuation contract. A bounded worker can be an extension mode, not an unexplained substitute for the base experience. MCP-only text is not directly executable in this CLI-only adapter. | -| F08: configuration/approval/errors | Setup preserves settings and supports stealth/global/remove/check. Plugin docs describe optional standalone MCP approval settings, including broad auto-approval. Skill troubleshooting includes init/server/repair advice. | Replace host-specific settings with documented native configuration and existing permission policy. Do not import blanket approvals or automatic repair. Error vs empty result vs withheld migration context must remain distinct. | -| F09: dynamic context/memory | [`prime.go`](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/prime.go) generates workflow and memories; `--full` defeats MCP detection, not custom PRIME.md. Local, redirected-workspace, then global overrides are possible; memories append unless disabled. Memory read failures can emit a diagnostic; some hook errors are suppressed. | Retain full CLI context and authorized custom workflow. Add targeted retrieval when stale/missing; don't infer successful memory retrieval solely from process exit 0. Respect upstream truncation notices without inventing new token quotas. | -| F10: durable writes/retrieval | [`memory.go`](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/memory.go) provides remember, memories, recall and forget. Bare existing key passed to remember recalls; unknown key-like input is refused. | Adapt explicit triggers: task-specific attempts/results/rationale belong with the issue; reusable validated project learning belongs in memory, with provenance/scope. Search before adding overlapping knowledge; use explicit recall for a known key; amend stale knowledge intentionally. Do not invent facts or copy credentials/log dumps. | -| F11: adjacent host payloads | Codex manifest shares skill tree and points to its own four-event hook file; Copilot manifest and `copilot_manifest.go` are separate host packaging. Both `agents/openai.yaml` files are UI metadata, not Claude task-agent execution. | Exclude host-specific payload installation from the OpenCode package recommendation; retain lifecycle comparison evidence. This does not exclude their useful shared behavior. | -| F12: support/maintenance text | Plugin README, skill README, skill CLAUDE.md and ADR explain installation and maintenance. CLAUDE.md says ADRs are maintainer references, not automatically loaded skill content. | Retain rationale/provenance and adapt relevant user docs. Do not inject maintenance files or all resources as runtime instructions. | - -F01–F12 are resolved: F01/F03/F04/F06/F07/F08/F09/F10 adapt through native lifecycle, discovery, scope and continuity; F02/F05 retain external bd ownership; F11 retains evidence but replaces host payloads; F12 retains rationale and adapts user guidance. Each file has a selected mapping, reason and implementation task in the inventory; support source/tests are not copied into the product. - -## Guidance, memory and conflict analysis - -The rich skill/resources provide substantially more advice about *when* to write and *what meaning to preserve* than the lean shared skill. `WORKFLOWS`, `PATTERNS`, `RESUMABILITY` and `INTEGRATION_PATTERNS` cover milestones, current state, key decisions, tested examples, blockers and next steps. They also conflict: some recommend ephemeral TodoWrite while current prime prohibits it; historical release WORKFLOWS asks permission at every handoff and uses replacement notes; marketplace-main changes the examples to `--append-notes` but retains contradictory "overwrite previous notes, not append" prose and the approval loop, while other passages advocate proactive updates. The skill says initialization is human work yet its error table suggests initialization as the fix. Stale version strings and MCP examples coexist with the ADR's canonical-prime principle. These are reasons to adapt, not evidence that all upstream behavior is desirable. - -Recommended base behavior is to checkpoint meaningful transitions: a failed approach with why it failed; a validated discovery; a changed decision; a blocker; delegation return; stopping/compaction when feasible. Save enough of the previous rationale to avoid repeating dead ends. Append-style notes preserve current position and prior evidence; comments can retain discussion. Replacement is deliberate, never the default checkpoint. Issue descriptions/design/acceptance have distinct roles. Ordinary authorized task updates should not need repeated user prompting, but an explicit hold or missing authority still wins. An abrupt process loss cannot guarantee a final write, so periodic meaningful checkpoints matter more than relying on an end hook. - -Reusable memory needs a separate decision: is the finding supported, project-relevant, likely useful beyond this issue, and absent or outdated in existing memory? If so, preserve its evidence/context and applicability, using the supported memory CLI. A temporary failure is usually a task note, not universal knowledge. On recovery, read the active issue and relevant memories before choosing the next action; prime is a workflow/memory entry point, not a complete reconstruction of all issue notes. No fixed write counts, token targets, or automatic memory dump are proposed. - -[Local guidance](../src/guidance.ts) currently requires delegation for multi-command work/graph analysis and allows only single atomic operations in the primary. The worker prompt says one bead, create discoveries but never work them in that invocation, validate, close/block, return concisely. It does not explicitly require returning failed attempts, learning, or memory keys. A concise return can lose precisely what the primary needs to preserve. Recommended handoff includes task state, attempted approach/outcome, evidence, rationale, blockers, next action and durable record references when relevant. The primary should reconcile the result before closure or continuation. Selected scope-bounded execution removes mandatory command-count delegation; direct work and blocking children remain available within authorization. - -[Context](../src/context.ts) caches by session **and audience**, coalesces loads within that key, retries absence/failure after 30 seconds, and refreshes after compaction or a 30-minute idle gap by default. Every request gets cached text. Continuous activity can retain old memory indefinitely; idle refresh is not an exact resume event. Independent child sessions and different audiences may prime separately. [Host](../src/host.ts) invalidates on `session.compaction.ended`, forgets deleted sessions, and adds summarization guidance for IDs/status/follow-ups/blockers/validation. It does not persist semantic progress itself. Targeted fresh reads at recovery or after relevant changes are a simpler candidate than re-running full prime every model step or adding a new memory service. - -[Guard](../src/guard.ts) checks version/location/marker before automatic prime, but it is not a sandbox for subsequent model shell calls. The migration notice says not to run bd; static skill/worker/failure fallback says run prime when context is missing. Future guidance must distinguish **withheld** from **failed** context so manual recovery cannot bypass a hold. `autoMigrate` and permission rules are existing options, not authority to change this repository now. [Instruction minimization](../src/instructions.ts) strips matching full/Codex managed blocks in requests when prime is attached; it does not prove those blocks are semantically redundant (profiles and updated policy can differ). Retain local authority and test non-duplicate constraints before extending minimization. - -### Local tests: what is and is not established - -`tests/context.test.ts` checks mocked cache, audience, retry, idle and invalidation behavior. `tests/host.test.ts` checks hook registration, flags, guard wiring, compaction guidance and cleanup. `tests/guard.test.ts` verifies the limited safe probe sequence and notices. `tests/instructions.test.ts` checks marker transformation and preservation outside blocks. `tests/guidance.test.ts` asserts prompt strings and a prompt length ceiling; it does not show model comprehension or durable note quality. `tests/agents.test.ts` exercises a copied permission matcher, not a complete host sandbox; source explicitly acknowledges wrapper/alias bypass. Historical live observations apply to their recorded 2.0.26 scenarios only. None of these establish fresh-session recall, appropriate remember selection, or full marketplace experience parity. No product tests were run for this planning-only change. - -## Complete resource and ADR review - -The rich SKILL.md links all 15 resource files. They are reachable on demand if the skill is actually installed and selected; mere packaging does not load their contents. Rows retain release-source provenance; dispositions now apply the accepted groups. Every resource ships in adapted form, including advanced on-demand guidance without automatic enabling. Runtime use is unmeasured; retain means intent, not copied bytes. -| Source | Recommendation | Reason / dependency | -| --- | --- | --- | -| [AGENTS.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/AGENTS.md) | adapt | On-demand agent-state/slot guidance; do not create or enable an orchestration service. | -| [ASYNC_GATES.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/ASYNC_GATES.md) | adapt | On-demand human/CI wait and resolution concepts; no new gate service or automatic approval. | -| [BOUNDARIES.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/BOUNDARIES.md) | adapt | Durable context vs ephemeral execution; reconcile TodoWrite advice with current prime and repository OpenSpec authority. | -| [CHEMISTRY_PATTERNS.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/CHEMISTRY_PATTERNS.md) | adapt | On-demand molecule/wisp selection guidance; execution requires authorized recurring work. | -| [CLI_REFERENCE.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/CLI_REFERENCE.md) | retain | Keep live prime/help pointers; avoid duplicating CLI reference. | -| [DEPENDENCIES.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/DEPENDENCIES.md) | adapt | Preserve dependency direction, provenance and hierarchy concepts; verify examples against current CLI. | -| [INTEGRATION_PATTERNS.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/INTEGRATION_PATTERNS.md) | adapt | Capture meaning at milestones; map planning to OpenSpec, evidence to docs, execution later to Beads. | -| [ISSUE_CREATION.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/ISSUE_CREATION.md) | adapt | Distinguish design from acceptance and capture resumption context; follow existing authorization. | -| [MOLECULES.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/MOLECULES.md) | adapt | On-demand recurring-work guidance with current formula/CLI compatibility checks. | -| [PATTERNS.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/PATTERNS.md) | adapt | Preserve hypotheses, decisions, blocker and closure patterns; replace MCP examples and unnecessary approval loops. | -| [RESUMABILITY.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/RESUMABILITY.md) | adapt | Preserve tested examples, failures, rationale and next action proportionate to task; no raw dumps. | -| [STATIC_DATA.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/STATIC_DATA.md) | adapt | Reference-database pattern is available on demand; use project memory for reusable knowledge rather than open issues as a glossary by default. | -| [TROUBLESHOOTING.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/TROUBLESHOOTING.md) | replace | Curate current CLI/guard failure recovery; stale server/export/import advice must not become automatic repair. | -| [WORKFLOWS.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/WORKFLOWS.md) | adapt | Checkpoint and recovery triggers; use marketplace-main append checkpoints and remove redundant approval loops while retaining applicable authority. | -| [WORKTREES.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/resources/WORKTREES.md) | adapt | On-demand workspace routing and ownership guidance; no automatic worktree creation or store initialization. | - -[ADR-0001](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/adr/0001-bd-prime-as-source-of-truth.md): retain the separation of dynamic CLI syntax from cognitive resources. Its assertion that drift is impossible is not borne out by the shipped surrounding examples. References and compatibility still need review. - -## Complete command review - -All 29 names are reviewed below, with the file itself as evidence. Common dependency for adoption: current CLI semantics and native host discovery/arguments must be verified. All 29 entries are selected under `oc-beads:` through package registration. Replace preserves intent via corrected guidance; advanced/admin entries remain accessible under normal permissions. Per-file selected mappings in the inventory control implementation. -| Source | Recommendation | Reason / dependency | -| --- | --- | --- | -| [audit.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/audit.md) | adapt | Optional diagnostics; avoid making prompt/response logging or a telemetry service a parity dependency. | -| [blocked.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/blocked.md) | retain | Useful blocker view; preserve read-only intent and distinguish blocked status from dependency blocking. | -| [close.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/close.md) | adapt | Replace MCP with CLI; require completion evidence and relevant validation, not merely a successful close call. | -| [comments.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/comments.md) | adapt | Keep discussion/checkpoint history; use noninteractive field updates instead of bd edit advice. | -| [compact.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/compact.md) | adapt | Administrative destructive issue compaction is distinct from conversation compaction; review current CLI and explicit scope. | -| [create.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/create.md) | adapt | CLI structured creation with acceptance/design and discovered-from where applicable; avoid redundant questions when intent is known. | -| [decision.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/decision.md) | adapt | Retain rationale and alternatives; link OpenSpec intended behavior and docs rationale without duplicating their authority. | -| [delete.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/delete.md) | adapt | Selected administrative workflow needs explicit operation authority and verified current semantics; not ordinary closure. | -| [dep.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/dep.md) | adapt | Retain graph operations; correct conflicting prose about dependency direction and verify X depends on Y. | -| [epic.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/epic.md) | adapt | Retain hierarchy/status; do not equate all children closed with validated parent acceptance. | -| [export.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/export.md) | retain | Useful explicit interchange; distinguish issue export from full backup and memory-inclusive export. | -| [import.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/import.md) | adapt | Preserve documented stale/upsert/partial-write cautions and route limits; never implicit setup or restore. | -| [init.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/init.md) | replace | Human-directed setup guide with side effects and ownership; do not invoke nonexistent MCP init or initialize automatically. | -| [label.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/label.md) | retain | Useful metadata operations; respect existing project taxonomy. | -| [list.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/list.md) | adapt | Keep filters with current CLI help; separate retrieval from automatic task selection or mutation. | -| [prime.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/prime.md) | adapt | No frontmatter upstream; explicit guarded refresh using full CLI context; distinguish missing context from migration hold. | -| [quickstart.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/quickstart.md) | replace | Deprecated command; offer current onboarding/resource entry without invoking bd quickstart. | -| [ready.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/ready.md) | adapt | CLI ready view; honor already-authorized task choice and atomic claim rather than always asking again. | -| [rename-prefix.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/rename-prefix.md) | adapt | Project-wide identifier migration; verify syntax and references before any separately approved admin workflow. | -| [reopen.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/reopen.md) | retain | Useful correction/regression operation with reason and current state check. | -| [restore.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/restore.md) | adapt | Historical retrieval useful for recovery; verify current Dolt implementation instead of trusting mixed git/Dolt prose. | -| [search.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/search.md) | adapt | Preserve issue search; remove unsupported MCP efficiency claims and distinguish memory search. | -| [show.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/show.md) | adapt | CLI detail retrieval including notes, acceptance and dependencies; do not mutate when asked to inspect. | -| [stats.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/stats.md) | adapt | CLI overview; no automatic claiming from statistics. | -| [sync.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/sync.md) | adapt | Current federation-loop bd sync differs from removed JSONL sync; preserve explicit authorization and conflict handling, no forced side selection. | -| [template.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/template.md) | adapt | Replace stale template syntax with supported template/formula discovery; no automatic workflow execution. | -| [update.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/update.md) | adapt | CLI fields/atomic claim; distinguish current-state notes from append-only discussion; preserve prior learning. | -| [version.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/version.md) | replace | Query installed CLI/plugin versions; remove hardcoded 0.9.2, MCP assumptions and automatic install advice. | -| [workflow.md](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads/skills/beads/commands/workflow.md) | adapt | Native CLI workflow and recovery entry; remove assumed MCP and unbounded continuation as universal default. | - -The original adapter's [loader](https://github.com/joshuadavidthomas/opencode-beads/blob/a508c1205a04516490d9d1078d5a4e788cd6553b/src/vendor.ts) returns null without frontmatter, registers `beads:`, and passes parsed prompt bodies through. Its [README](https://github.com/joshuadavidthomas/opencode-beads/blob/a508c1205a04516490d9d1078d5a4e788cd6553b/README.md) advertises `/bd-*`. Its tree contains 29 vendored command files, but that is not proof of 29 usable commands. In the reviewed Beads corpus `prime.md` and `template.md` lack frontmatter; that loader would skip those bytes. CLI safety text elsewhere does not rewrite command bodies that request MCP tools. Native V2 Markdown supports bodies without frontmatter, so the old parser limitation must not be carried forward as a V2 limitation. - -## Native delivery choices and extension model - -The [V2 command documentation](https://opencode.ai/v2/docs/commands/) explicitly supports Markdown templates and JSON commands; see its [pinned source](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/commands.mdx). The [plugin API](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/build/plugins/index.mdx) separately registers executable commands. The old artifact-policy wording confused these surfaces. Native prompt commands are a viable option; removal of vendoring was a policy choice, not a platform necessity. - -| Evaluated delivery route | Benefits | Ownership/removal/override and risk | -| --- | --- | --- | -| D01: package-owned executable commands | One package/version controls registration and removal; no project-file installer | Must forward prompt attachments/delivery correctly, define naming/collision behavior, and verify user override precedence at the supported host. More adapter code; never directly interpolate user arguments into shell execution. | -| D02: explicit project/global Markdown command install | Native editable prompts, description and argument substitution; familiar file review | Needs an explicit installation/update/removal contract and provenance. Preserve user edits/collisions; remove only owned unchanged files. Project commands override global ones. Avoid shell-output interpolation: V2 evaluates it outside agent tool permission flow. | -| D03: JSON command configuration | Native templates and agent/model selection | User config merging/removal is harder to own safely; no unrequested runtime-config edits. Keep as documented alternative rather than automatic mutation unless selected. | -| D04: package-owned skill registered with real asset path | Resource base can be packaged and versioned; uninstall follows package registration | Npm internals are not automatically discovered. Must provide a valid path and package resources, test resolution after install, and establish user override behavior. | -| D05: supplemental skill in native discovery directories | Explicit resource tree and user-controlled customization | Shared `beads` ID collisions can shadow content. Historical alternative; selected design uses distinct `oc-beads` and does not install shared files; duplicate discovery prompts may confuse models. Upgrades/removal need ownership discipline. | -| D06: lean shared skill plus runtime guidance only | Minimal asset/installer maintenance | Can add checkpoint/recovery triggers but lacks the rich progressive resource experience unless references are actually reachable. Must demonstrate outcome and discoverability rather than assume prime alone suffices. | - -Selected bundle: **N1 with D01+D04**, `oc-beads`, OpenCode `>=2.1.1 <2.2`, opt-in beta/next. N0 and D02/D03/D05/D06 are evaluated historical alternatives, not pending choices or silent fallback. Package registration supplies all selected assets and commands; no installer restoration or dependency change happens in this planning turn. - -The [pinned skill docs](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/skills.mdx) describe description-based advertisement, explicit tool loading, relative resource paths, and permission checks. They document later-source wins by ID, with `.agents` after `.claude` and project `.opencode` later still. A copied rich Claude skill can therefore be shadowed by the lean shared `beads` skill. Supporting file contents are not automatically loaded. Test actual selected content and resource access, not just file existence. - -| Extension ID | Selected disposition relative to the base experience | Tradeoff / owner decision | -| --- | --- | --- | -| E01: bounded one-bead worker | Optional one-bead mode alongside selected scope-bounded continuation | Bounds scope and protects primary context, but may add handoffs and lose discoveries. Exact assignments stop; authorized batches/goals may continue; discoveries do not expand scope. | -| E02: Luna profile | Retain existing opt-in model routing | A provider/model-specific choice is not required for parity. Same behavioral criteria, separately recorded model results; no claimed cost/quality superiority. | -| E03: migration guard | Retain protective behavior with consistent holds/fallback guidance | Marker is conservative, guard covers automatic context only. Do not turn ordinary recoverable errors into blanket permanent denial. | -| E04: permission rules / step cap | Adapt as transparent configurable safeguards | Pattern rules are not a sandbox; caps may interrupt before checkpoint. Respect existing authorization, report incomplete work, and qualify real host behavior. | -| E05: mandatory delegation | Discretionary task-based delegation; remove mandatory command-count routing | Direct atomic operations remain simple; graph analysis benefits from isolation in some tasks. Qualify semantic handoff; no universal mandatory delegation. | -| E06: memory freshness | Adapt targeted retrieval/refresh for relevant state transitions | Balance current knowledge with stable prompt caching. Avoid a new orchestration service, polling telemetry, token/write quotas or broad shell parsing. | - -## Proportionate qualification plan (not executed) - -Use disposable fixtures only after separate implementation authorization and lifting any applicable hold. Keep deterministic checks separate from model-dependent evaluations. - -| Scenario | Deterministic integration evidence | Behavioral outcome to evaluate | -| --- | --- | --- | -| Progress and failed approach | Selected guidance/resource reachable; checkpoint path and error handling covered | Preserve what was tried, failure evidence and rationale; resume without repeating the rejected approach. | -| Reusable discovery vs transient detail | Supported remember/search/recall syntax and persistence fixture | Save supported reusable learning, avoid promoting temporary state; retrieve and apply it later without nagging. | -| Compaction/resume/fresh session | Context invalidation, idle approximation, guarded retry and targeted retrieval paths | Recover active task, attempts, decision, blockers and concrete next action from durable state with old conversation absent. | -| Atomic operation vs graph/delegation | Routing/permissions, child result and failure delivery | Read-only analysis does not claim/mutate; worker returns learning and validation; primary retains intent and reconciles closure. | -| Command workflow | Selected names discoverable, args/attachments/delivery and override/removal tests | Command produces correct scoped workflow through CLI; no invented MCP calls, unsolicited setup or concealed failed write. | -| Error/hold and closure | Withheld context distinguished from empty/failure; validation and permission boundary fixtures | No manual-prime bypass of hold, no false success, no closure with unresolved acceptance; preserve next action if blocked. | - -A small representative set can combine these scenarios. Record host, Beads release, installation path, selected skill/resource, provider/model, reasoning setting, starting state and outcome evidence. Compare host changes on the same model where feasible; compare models under the same host configuration separately. Use targeted repeat runs for uncertain outcomes rather than an exhaustive cross-product. Review actual task/memory records and recovery behavior, not prompt text, write count or model self-report alone. Report failures and attribution limits; no universal architecture or model superiority claim. No new telemetry or evaluation service is required. - -## Selected contract and evidence layers - -The [owner record](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md) resolves marketplace-main, N1/minimum host, beta/next, scope-bounded execution, full corpus groups, package ownership/namespace and check-based drift. The [design](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md) resolves technical mappings and the [reconciliation record](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md) maps findings and requirements to tasks. Earlier recommendations remain historical alternatives, not another owner gate. - -Source qualification is completed evidence, deterministic fixtures are future implementation work, and installed-host/model behavior is future acceptance. Only a demonstrated contract-changing incompatibility returns to the owner. OpenSpec owns touched intended behavior, docs evidence, and Beads later execution; no tracker/store access is needed here. - -## Planning validation - -OpenSpec 1.14.2 strict validation passes for `improve-beads-workflow-parity`; `--all --strict` reports one change passed, zero failed. `--specs --strict` reports no items because the canonical baseline is empty; this is not a claim that baseline behavior was tested. Status reports all four artifact kinds present, with all three capability deltas. Programmatic inventory checks compare the declared roots/support paths to the pinned non-truncated Git tree, verify all 73 Git blob identities and SHA-256 values, check command/resource/ADR source links and all 15 rich-skill resource links, and confirm the local lean skill matches the shared upstream template. Tracked and new-file whitespace checks pass. These checks certify planning structure/source coverage, not runtime or model outcomes. - -### Native revision evidence - -The repository-owned [planning evidence validator](validate-parity-planning.py) preserves the original corpus identity/coverage checks and adds pinned native-source and published-declaration checks, without asserting the intentionally removed freeze marker. See the [native assessment](opencode-native-parity-assessment.md) for exact release distinctions, recommendation and unexecuted material probes. Strict OpenSpec and whitespace results for this revision are recorded in the handoff; source inspection is not implementation or behavioral qualification. - -Operative host selection now targets exact 2.1.1; the [contract delta](opencode-2.1.1-contract-delta.md) preserves historical evidence and separates source admission from unexecuted runtime acceptance. No product or shared-skill changes occur in this pass. diff --git a/docs/claude-code-local-reference.md b/docs/claude-code-local-reference.md deleted file mode 100644 index 765bf76..0000000 --- a/docs/claude-code-local-reference.md +++ /dev/null @@ -1,67 +0,0 @@ -# Installed Claude reference integration - -## Evidence boundary - -The actual `beads@beads-marketplace` plugin is installed and enabled at **local project scope** for the Hermes `/opt/data/opencode-beads` workspace. This records installation/component discovery, not a live model-behavior or functional-parity result. It does not require collaborators to install a Claude plugin to use the OpenCode package. - -## Current OpenCode comparison boundary — 2026-10-21 - -The [installed/model continuation](opencode-installed-model-continuation-vuy9.md) adds genuine OpenAI Sol/high semantic evidence on exact OpenCode 2.1.1 and the unchanged accepted package, including actual failure/partial child, meaningful append/relevant recall, bounded scope and same-provider summary/native recovery. Corrected actual cleanup/17 resource reads are reused; all 19 requirements and 73/74 selected corpus dispositions plus CODE_MODE are mapped. This is a parent-accepted bounded evaluation, not a controlled Claude-versus-OpenCode comparison or a model-quality finding. Ordinary typed execution remains withheld; the internal installed-source qualification seam is scratch-only. The installed Claude identity and all historical source comparisons below are unchanged. All 16 implementation tasks are accepted; release/activation remain separate. - -## Installed identity - -- Claude Code: `2.1.292`. -- Plugin-reported version: `1.3.0` (distinct from the Beads CLI/release version). -- Marketplace: `gastownhall/beads`, name `beads-marketplace`. -- Installed source commit recorded by Claude: `4a67d0d0288c1b4ee23e17fc896f47616931ba2d`. -- Installation path in this runtime: `/opt/data/home/.claude/plugins/cache/beads-marketplace/beads/1.3.0`. -- Local activation: `.claude/settings.local.json`, `enabledPlugins["beads@beads-marketplace"] = true`. -- CLI `plugin list --json` reports `enabled: true`, `scope: local`, and the exact project path. Its separate `projectEnabled: false` field is retained as reported, not treated as a project-scope installation claim. - -Source: [installed revision](https://github.com/gastownhall/beads/tree/4a67d0d0288c1b4ee23e17fc896f47616931ba2d/plugins/beads). The analysis baseline remains [Beads v1.3.1 source](https://github.com/gastownhall/beads/tree/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/plugins/beads). Installation used the marketplace's current checkout, **not** a claim that the pinned release was installed. Behavioral comparisons must record and align the chosen revision, or disclose differences, before attributing outcomes. - -## Reconciled installed/release/current comparison - -On 2026-10-18, read-only GitHub repository/commit/tree APIs resolved default branch `main` to **`4a67d0d0288c1b4ee23e17fc896f47616931ba2d`**, matching the recorded installed revision. All **57** current `plugins/beads/` files byte-match the installed cache. The complete declared current scope has 74 files versus the historical 73; all current blobs are hash-verified against the non-truncated tree. Equality of source identities is established; ancestry is **not** inferred from dates or manifest versions. - -Compared with the historical release `c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c`, the full selected scope has one addition, no deletions and 16 edited files: - -| Members | Characterized change and planning consequence | -| --- | --- | -| `plugins/beads/skills/beads/README.md`, resources `WORKFLOWS.md`, `PATTERNS.md`, `INTEGRATION_PATTERNS.md`, `ISSUE_CREATION.md` | Checkpoint examples change `--notes` to `--append-notes`. Preserve previous attempts/learning through append-style checkpoints; do not describe overwriting as the current main recommendation. WORKFLOWS still says "overwrite previous notes, not append" at line 368 and retains approval-on-every-handoff instructions. Its prose conflicts with its updated examples; adapt both to append checkpoints under existing authority. | -| resource `ASYNC_GATES.md` | Adds cross-repository `--repo` guidance for GitHub gates; qualify installed CLI support and normal access rather than enabling a monitor. | -| `.claude-plugin/marketplace.json`, plugin Claude/Codex/Copilot manifests | Version strings 1.3.1 in the release versus 1.3.0 in installed/main; discovery wiring is unchanged. Manifest version does not identify full source behavior. | -| `cmd/bd/prime.go` | Adds disabled-prime behavior before workspace/store access; changes `-C`/redirect/custom-prime and Git routing; distinguishes project facts from operator preferences and recommends append notes. Empty output is not proof of absent memory or a reason to bypass disable/hold. | -| `cmd/bd/memory.go` | Adds opt-in corpus-budget refusal/force semantics, explicit landed-but-uncommitted or indeterminate commit JSON fields, and found-empty versus absent recall. A zero exit is not proof of committed durability. Never silently force, change budgets or commit. | -| `cmd/bd/init.go`, `cmd/bd/init_embedded_test.go` | Home-directory/missing-database safety, explicit routing/initialization boundaries and fixture reorganization/coverage change. Upstream owns setup; this plan neither copies init nor authorizes it. | -| `cmd/bd/setup/claude.go`, `cmd/bd/setup/codex.go` | Adds output-directed installation wrappers; does not change ownership of integrations. | -| added `plugins/beads/BUILD.bazel` | Build/layout metadata only; reference evidence, no OpenCode runtime payload. | - -The remaining **57 selected files** are unchanged from release (including all 29 command bodies, rich skill, agent and ADR); unchanged bytes may still contain obsolete MCP/TodoWrite/setup advice. `--append-notes` already exists in historical CLI source (`cmd/bd/cli_fast_test.go`), so the guidance correction alone does not require a runtime upgrade. Current-source memory/prime changes are not claims about the installed executable. See the separate `marketplace_main` inventory and [design](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md) for the selected acknowledgement and authority contract. - -## Observed component discovery - -`claude plugin details beads@beads-marketplace` reports: - -- **30 skills**: the rich `beads` entry plus all **29 command entries**, including `prime` and `template`. -- **One agent**: `task-agent`. -- **Two hook types**: `SessionStart` and `PreCompact`. -- **Zero MCP servers** and zero LSP servers. - -The installed resource directory contains **15 Markdown resources**. Inspection confirmed that the rich skill and task-agent body byte-match the examined release source. The characterized differences above prevent treating component counts as whole-corpus release equivalence. The static 73-file release inventory remains unchanged and authoritative for its explicitly pinned scope. - -Claude's discovery of `prime` and `template` establishes component recognition in this installed harness. It does not prove successful invocation, argument handling, CLI/MCP resolution, or applicability to the pinned release. The original OpenCode loader's frontmatter limitation is not a Claude discovery limitation. - -## Hook ownership and Codex setup - -`bd setup claude` initially installed a standalone project `SessionStart` hook. After marketplace installation, only that newly generated standalone settings file was removed to avoid duplicate prime execution; marketplace hooks now own Claude startup/compaction wiring. Existing user instructions were preserved. No marketplace payload was modified. - -`bd setup codex` installed the shared `.agents/skills/beads` entry, `.codex/hooks.json`, `.codex/config.toml` enabling hooks, and an `AGENTS.md` section. Setup verification passed. Generated Codex instructions explicitly call for persistent project memory through `bd remember`. This is potential behavior-bearing input to compare, not evidence of actual model compliance. Codex CLI was `0.162.1` when inspected. - -Fresh worker sessions are required to evaluate effective loaded guidance. Do not interpret prior Astra runs as having exercised these newly installed integrations. Shared/generated instruction files and local activation are workspace setup, not implementation of the proposed OpenCode package. - -## Packaging conclusion - -The intended OpenCode product delivers its **complete owner-selected integration through its npm package**: registered command workflows, skill/resource assets, agent policies, lifecycle wiring and selected continuity tools. A separate manual skill/resource installation is not an acceptable hidden prerequisite for advertised capability. The installed `bd` executable and upstream-owned project initialization/data remain external. This refines the proposed packaging goal; the owner has selected N1, the full corpus groups, `oc-beads` and opt-in beta/next; implementation and acceptance remain unexecuted. - -Qualification must inspect the installed artifact and effective registrations, resource reachability, overrides, teardown and a fresh session's actual guidance. Claude component discovery is a useful reference observation, not proof that OpenCode or any model achieves behavioral equivalence. diff --git a/docs/claude-code-parity.md b/docs/claude-code-parity.md deleted file mode 100644 index 6c2ad86..0000000 --- a/docs/claude-code-parity.md +++ /dev/null @@ -1,54 +0,0 @@ -# Claude Code Parity - -Status: historical **setup-lifecycle** comparison recorded by epic `opencode-beads-unh`, validated on **OpenCode 2.0.26** with **bd 1.3.1**. This did not establish full Claude Code Beads experience parity. The marketplace skill/resources, command catalog, autonomous task agent, and durable knowledge outcomes are now assessed in the [full integration analysis and owner decision packet](claude-code-integration-analysis.md); that broader work is planning only, with owner selections recorded and implementation/behavioral acceptance unexecuted. - -## Target - -The target is the integration `bd setup claude` installs, which `bd init` also installs by default (`cmd/bd/setup/claude.go` at Beads v1.3.1): - -- A `SessionStart` hook that runs `bd prime --hook-json`. `SessionStart` fires on `startup`, `resume`, `clear`, and `compact`, which is why upstream removed its `PreCompact` hook. -- A minimal `CLAUDE.md` section that points to `bd prime`. The hooks do the heavy lifting. - -The separate Beads Claude Code marketplace plugin (a rich skill, 29 slash commands, and the autonomous `@task-agent`) is **not** the target; see [Deliberate divergences](#deliberate-divergences). - -Installing this plugin after a plain `bd init`, and never running `bd setup opencode`, gives OpenCode the same shape. The `bd` contract (`scripts/bd-contract.ts`) checks that premise in CI and daily. - -## `bd setup claude` behaviors - -| Claude Code (`bd setup claude`) | OpenCode equivalent in this plugin | Evidence on OpenCode 2.0.26 | -| --- | --- | --- | -| `SessionStart` (`startup`) runs `bd prime` | The session context hook attaches `bd prime` to the first and every later request, cached per session | New sessions primed once each (#16) | -| `SessionStart` (`resume`) | A session that returns after `refreshAfterIdleMinutes` (default 30) re-runs prime | Resume within the window reused the cache; resume after the window re-primed (#16) | -| `SessionStart` (`clear`) | A new session gets its own prime | Same path as startup (#16) | -| `SessionStart` (`compact`) | `session.compaction.ended` invalidates the cache, so the next request re-primes | Manual compaction (with idle refresh excluded) and automatic compaction both re-primed (#16) | -| Minimal `CLAUDE.md` pointer to `bd prime` | `bd init` writes the minimal `AGENTS.md` pointer. While prime is attached, bd's full-profile and Codex blocks are replaced in the request with a one-line pointer | Instructions part 22,866 → 16,816 chars; contract checks the markers (#14, #15) | -| `--stealth` (`bd prime --stealth`) | `stealth` plugin option | Prime ran with `--stealth` and reached the agent (#18) | -| `--global` or project install | Global or project `plugins` entry | Project `plugins` loading and options verified in the V2 spike; global configuration uses the same mechanism and was not separately exercised | -| `--remove` | Remove the `plugins` entry | Configuration only | -| `--check` | `opencode debug agents` lists `beads-task-agent`; the agent sees `` | Used throughout validation | -| Hook errors are visible to the user | `bd prime` failure or timeout gives the agent a `` (as Beads' Codex hooks report refresh failures) | Simulated failure: the agent reported the notice (#18) | -| Migrates legacy hook files | Not applicable: the plugin writes no project files | — | - -## Beyond Claude Code - -OpenCode V2 exposes surfaces that Claude Code's hooks cannot use. The plugin uses them deliberately: - -| Capability | How | Evidence on OpenCode 2.0.26 | -| --- | --- | --- | -| Prime in subagents | The `beads-task-agent` child session passes through the same context hook | The worker reported `` in its own session (#16) | -| Context survives compaction | Prime is a per-request system part, never stored in history | Spike `opencode-beads-2zs.1` | -| Enforced no-push policy | Task-agent permissions `ask` for `git commit`, `git push`, `bd dolt push`, `bd dolt pull`, `bd sync`, including forms with global options | A delegated `git commit` was rejected in a non-interactive run (#17) | -| Worker step cap | `taskAgentSteps` (default 100) sets the agent's `steps` | Resolved by `opencode debug agents` (#17) | -| Beads state across compaction | The compaction hook asks the summarizer to keep bead IDs, statuses, follow-ups, and blockers | The summary kept both bead IDs, their state, and the blocker (#17) | -| Schema migration guard | `bd version`, `bd where --json`, and `.beads/.local_version` checks before automatic prime; `autoMigrate` opts out | A v1.2.2-created store got a notice and stayed unmigrated (1.0.0) | - -## Deliberate divergences - -- **Task agent.** `bd setup claude` installs no agent; the marketplace plugin ships an autonomous multi-task `@task-agent`. This plugin ships a bounded `beads-task-agent` that handles exactly one bead per invocation, by design. See the [artifact policy](beads-artifact-policy.md). -- **Slash commands.** None, as with `bd setup claude`. The marketplace plugin's commands were retired (`opencode-beads-2zs.4`). -- **Skill.** `bd init` installs the slim `.agents/skills/beads` skill, which OpenCode discovers. `bd setup claude` gives Claude Code no skill, and Codex gets the same slim skill. The marketplace plugin's resource documents are not vendored. -- **Hook JSON envelope.** `--hook-json` is specific to Claude Code's hook protocol. OpenCode receives prime as a system part instead. - -## Not exercised - -- Restarting the OpenCode service was not exercised live because it would disrupt running sessions. The prime cache is in memory, so a restart behaves like a plugin reload, which re-primes (#16). diff --git a/docs/code-mode-final-acceptance-vuy9.md b/docs/code-mode-final-acceptance-vuy9.md deleted file mode 100644 index ad08e29..0000000 --- a/docs/code-mode-final-acceptance-vuy9.md +++ /dev/null @@ -1,22 +0,0 @@ -# Final beta/next implementation acceptance - -Parent accepts tasks **6.2 and 6.3**, completing all 16 implementation/qualification tasks for `improve-beads-workflow-parity`. This is implementation acceptance, not registry publication or operator activation. - -## Evidence accepted - -- Runtime source `8831169d3c83c333fdf13d4a4efc743eaf495e2b`: 191 source tests, typecheck and package validation; independent corrected-source Opus READY. -- Beads minimum/current **1.3.1**: 63 real disposable CLI checks. Retired 1.3.0 runs remain historical, not compatibility obligations. -- Exact OpenCode **2.1.1**, source `ba546ec1598a70db2570e9c6258028d955ba8f58`: accepted native namespace/permission and explicit Stop/handoff observations. -- Actual installed cleanup/reactivation and all 17 native resource accesses: corrected lifecycle observation verified by parent with 64 evidence assertions. Whole-location reload is not plugin-scope unload; the original stronger failed probe remains intact. -- Genuine `openai/gpt-6.1-sol#high` workflows: parent ran 53 raw-trace assertions and read actual final model outputs for graph projection, exact assignment, authorized continuation, relevant memory, real partial child, fresh/summary/provider-native recovery and permission refusal. Native code-mode actually executed, including concurrent reads and ordered writes. Uncertain create landed once and was separately read back without retry. -- All 19 normative requirements, 73 historical/74 selected-marketplace corpus dispositions, 30 commands and 17 links are explicitly mapped in [the continuation report](opencode-installed-model-continuation-vuy9.md). -- Parent reran final closeout gates: **191 tests passed**, typecheck and packed-package validation passed. The closeout documentation changes produce archive SHA-256 `96deb78254d9a2369a5a16298914ec3037fc0d31dbacaa326ff3f9720eb14457`; runtime source is unchanged from the qualified archive. This is not yet a versioned beta publication. -- Parent docs tests, strict named/all OpenSpec, planning/inventory checks and whitespace passed. Auth access was imported from the current native OpenCode record without refresh; source credential and operator configuration remained unchanged. Owned runtime resources were cleaned. - -The reports retain failed specimen validation as failed work, original location-reload and nested plain-decline observations as historical failures with exact dispositions, and harness errors separately. No comparative model-quality, token-saving, cross-provider checkpoint portability or multi-hour reliability claim is made. - -## Beta release readiness boundary - -The accepted archive was `e952532140b44f812e2660425ec485d3bbd474962dd424ed03d70108593b259f`, with typed tools enabled only through the existing internal qualification seam. **Do not publish the current package unchanged as a code-mode evaluation beta:** ordinary typed activation is still withheld. - -A separately tracked bounded prerelease preparation must provide a public beta-only activation path using the qualified registration, select a prerelease version, update onboarding/changelog, and explicitly publish under npm dist-tag `next` while preserving `latest`. The existing release workflow currently runs `npm publish` without `--tag`; it must not be used blindly for a prerelease. Build/verify one exact archive and verify the registry artifact after separately authorized publication. No stable rollout, operator upgrade or new architecture campaign is required. diff --git a/docs/code-mode-product-investigation.md b/docs/code-mode-product-investigation.md deleted file mode 100644 index 869fae3..0000000 --- a/docs/code-mode-product-investigation.md +++ /dev/null @@ -1,262 +0,0 @@ -# Code-mode product investigation - -2026-10-21 · `opencode-beads-wgv` · executor `codex:oc-codemode` · parent owns acceptance and closure. - -## Recommended decision - -Keep composition and make one bounded pre-release improvement: publish correctly declared, discriminated results for the five continuity operations, group them using the host's native `beads` namespace, and add **one read-only `query` operation** for ready/list/direct-dependency inspection. Keep the existing 30 commands, shared adapted Beads skill and permissioned native shell. This gives broad work discovery, graph triage and selective recovery a useful structured path without wrapping every CLI verb or building a workflow engine. Implementation requires separate parent dispatch; this investigation changes no product behavior. - -Accept the owner-selected OpenCode 2.1.1 limitation explicitly: a plain decline must prevent that operation from executing, but code mode can report an outer completed/error envelope and continue independently permissioned calls or model steps. Preserve the historical failed stronger guarantee as failed evidence with an accepted limitation. Later operations retain their own permission checks. Explicit Stop/Cancel remains separately unqualified and required; it is not covered by accepting plain-decline continuation. - -## Evidence and boundaries - -Product baseline: `072429f1a7723ade23e756a921924d9d0acacf31`. Host: exact OpenCode 2.1.1 source `ba546ec1598a70db2570e9c6258028d955ba8f58`. Local Beads help identifies 1.3.1, commit `c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c`; package minimum remains 1.3.0. Current help is evidence for 1.3.1 syntax, not certification of every flag on the minimum version. - -Read `AGENTS.md`, the Beads skill, `bd --sandbox prime`, and the exact investigation Bead before claiming. Claim used `bd --actor codex:oc-codemode --sandbox update opencode-beads-wgv --claim --json`; readback confirmed `in_progress`, assignee `codex:oc-codemode`, original `created_by: snarkimedes`, and no reported owner. Only this Bead is writable by this worker. Existing dirty documents and concurrent parent OpenSpec edits were left untouched. - -Primary source links below identify immutable host files. Their cached bytes were checked against Git blob IDs in `/opt/data/cache/scratch/opencode-v2-test-gap-assessment/tree.json`. In particular, the cached `minimum/` copies of catalog/instructions match the exact 2.1.1 tree despite that directory's name. Existing installed-host decline evidence in [opencode-host-qualification-vuy2.md](opencode-host-qualification-vuy2.md) is prior evidence, not a host run performed here; its historical disposition may be reconciled by the parent. - -Two isolated probes used installed dependencies and the cached baseline Bun 1.3.14. CLI, permission and session dependencies were fixtures. No host startup, external model/provider request, dependency installation, real fixture database write, operator change, source fix, staging, publication or closure occurred. - -## Complete registration and result path - -1. `src/host.ts` admits the supported host range and owns scoped registrations/cleanup. Ordinary setup **withholds** continuity tools; only the internal `continuityQualified` seam registers `createContinuityTools(...)` through `ctx.tool.transform(editor.add)`. Therefore this defect is not evidence of currently activated operator tools failing. -2. The [Promise tool interface](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/tool.ts) carries `input`, optional `output`, options and Promise execution. The [Promise adapter](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/adapter.ts#L477-L510) spreads the definition into the Effect editor, wraps execution with `Effect.tryPromise`, and supplies execution signal/progress. It does not infer output schemas from returned values or TypeScript interfaces. -3. The [host registry and snapshot](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool.ts#L156-L340) validates registrations, applies transforms and coarse permission visibility, and splits direct tools (`codemode: false`) from code-mode tools (default). These five definitions default to code mode. A whole `shell` deny can remove them because they declare `options.permission: "shell"`; this visibility filter does not replace invocation authorization. The snapshot exposes `execute` plus direct-tool definitions and a separate code-mode inventory. -4. [Code-mode construction](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/codemode/tool.ts#L236-L271) converts each host definition into a callable and uses its declared output schema, falling back to `string | null` when absent. Catalog and execution use the same immutable inventory. Native paths derive from `options.namespace` plus normalized name. -5. Each inner call goes back through host `execute.before`, the actual [tool executor](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool/runtime.ts#L21-L61), and applicable `execute.after`. The plugin checks actual session location, guard, external-directory permission where needed, exact canonical shell resource, abort and location again before spawning. Write actor comes from actual host session/agent identity, never model input; `--sandbox` suppresses auto-push and is not confinement. Beads owns routing/database semantics. -6. The host executor checks/encodes declared output **after** the implementation has run. Effect/Standard schemas validate their shape; raw JSON output schemas only trigger a JSON-value check, not branch validation. `src/continuity.ts` acknowledges writes and invalidates context inside the executor, once, before returning. An outer output-contract failure can therefore follow a real CLI mutation; it cannot justify retrying that mutation. The existing `host.ts` exclusion for outer `execute` and inner `beads_*` events correctly prevents duplicate write acknowledgement. -7. The [code-mode bridge](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/codemode/tool.ts#L89-L150) gives JavaScript declared structured `output` when present, otherwise joined text/null. It returns the program's selected result, warnings/logs, files and per-call trace information in the outer result. Direct tool consumers receive readable `content`; [model replay](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/runner/to-llm-message.ts#L121-L151) uses completed-tool content. Supplying only structured output and an unreadable direct rendering would underserve the direct path. - -### Demonstrated defect and adjacent concrete gaps - -All five definitions (`src/continuity.ts:138–223`) omit `output` and return `{ output: result, content: JSON.stringify(result) }`. The pinned executor dies with `Tool result declared output without an output schema`. Direct-definition tests in `tests/continuity.test.ts` bypass this boundary. - -Re-ran `/opt/data/cache/scratch/opencode-codemode-shape-review/check-output-contract.ts`: exit 0; two harmless fixture reads; as-built definition **Failure** with that exact cause; diagnostic copied definition declaring `{type: "object"}` **Success**. The object-only control is not a production contract: it advertises `{}` and does not describe usable branches or payload fields. - -The new catalog/result-bridge probe also demonstrates the misleading current signature: `tools.beads_show({id: string}): Promise`. A diagnostic discriminated schema produces a discoverable object union and works through the pinned result executor. This is the same root defect in discovery as well as execution, not a second upstream bug. A further diagnostic copied definition returning an undeclared status branch is accepted under a raw JSON output schema: pinned `encodeOutput` checks only JSON-ness in that case, and the code-mode schema bridge treats raw JSON schemas as render-only. This is a concrete enforcement distinction, not a claim that the host promises full raw-schema validation. Our adapter must enforce the outcomes it advertises. - -Other bounded improvements justified by source inspection: - -- `ContinuityResult` is one permissive interface with optional payload fields. It allows impossible combinations and does not tell code which data exists after checking status. Use operation-specific discriminated unions and runtime output declarations. -- Input declarations advertise arbitrary strings while `inputFor` additionally enforces nonempty text, a 64,000-character cap, no NUL, and token syntax for IDs/keys. Reflect these constraints and useful field descriptions in schemas so discovery does not invite predictable rejected calls. -- A post-spawn uncertain write currently lacks `reference`, although its requested issue/key is known. Include that target as a recovery reference without claiming persistence. The host currently cannot retain that reference when the uncertain result omits it. -- If acknowledgement notification throws, line 221 replaces `detail`; retain the original failure/uncertainty detail and append the notification problem. This is a diagnostic-loss path visible in code, not a demonstrated normal production outage. - -No additional upstream executor defect was established here. In particular, do not infer new routing/confinement failures or repair speculative CLI behavior. - -## Contract and discovery shape - -Use the host's existing namespace mechanism: definitions named `show`, `checkpoint`, etc. with `options.namespace: "beads"` and the existing shell permission option. This preserves effective host IDs such as `beads_show` while catalog paths become `tools.beads.show`. Register a short namespace description through `editor.namespace`. Do not retain duplicate flat catalog aliases or pin every large signature inline. - -The pinned [catalog](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/codemode/catalog.ts) uses a default 2,000-unit inline budget based on a four-characters-per-token heuristic, keeps namespace summaries visible and selects signatures within the budget. This is not a tokenizer measurement. The [native search](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/codemode/src/tool-runtime.ts#L89-L107) is synchronous inside code mode: - -```ts -search({ query?: string, namespace?: string, limit?: number, offset?: number }) -// => { items: [{path, description, signature}], remaining, next: {offset} | null } -``` - -Default limit is 10; positive limits and nonnegative offsets are supported. Ranking uses paths, descriptions, namespace descriptions and input-property information; it is tool discovery, not Beads issue/memory search. [Instructions](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/codemode/instructions.ts) support partial catalogs and subsequent catalog changes. No new registry/search service is needed. - -Keep the five input shapes, with proposed namespaced paths: - -```ts -tools.beads.show({id: string}) -tools.beads.checkpoint({id: string, text: string}) -tools.beads.memories({search?: string}) -tools.beads.recall({key: string}) -tools.beads.remember({key: string, text: string}) -``` - -These namespaced paths are **proposed**; current definitions are flat `tools.beads_show`, etc., and ordinary setup withholds them. The existing input shapes were verified from product source, not guessed from a future API. Each call takes one input object and returns a Promise. Always use paths/signatures actually supplied by catalog/search. - -Declare result branches separately, retaining current persistence meanings: - -| Operation | Structured branches and required information | -| --- | --- | -| show | `acknowledged` with operation, reference and issue data; `failed` with operation/detail. Do not reinterpret arbitrary CLI failure as missing. | -| memories | `acknowledged` with operation and string-value map; `failed` with detail. Empty map means successful no matches. | -| recall | `found` with reference/value, including `value: ""`; `missing` with reference; `failed` with detail. Only supported CLI evidence establishes missing. | -| checkpoint | `acknowledged` with target and acknowledged issue; `uncertain` with target/detail after an ambiguous execution. Appending is not idempotent. | -| remember | `acknowledged` with key and CLI acknowledgement; `landed-uncommitted` with key, commit qualification and CLI evidence; `uncertain` with target/detail. Replacing one key is not a transactional handoff. | - -Use literal `operation` and `status` in each schema branch (`anyOf`/equivalent union), with required fields for that branch. Keep strict envelopes and compatible extra CLI fields under `data`; describe stable issue fields for projection, leaving absent fields absent. Do not force a complete upstream issue schema into every catalog signature. A TypeScript union alone does not declare host output. For the smallest delta, declare raw JSON output schemas and enforce their branch invariants in the existing acknowledgement/result construction and focused contract tests; do not assume the host validates raw output against those schemas or introduce a general validation framework. Return concise readable content from the same result, retaining status/reference/detail; code mode consumes the structured branch and need not parse that rendering. - -Permission rejection, guard hold, invalid input, and cancellation before spawn remain thrown host failures/interruptions; do not fabricate an acknowledged or ordinary `denied` persistence result. Promise fulfillment, outer tool completion and trace `completed` each differ from durable success: an `uncertain` result can fulfill normally. Return evidence and inspect state before considering a further write; no automatic retry. - -## Broad workflow coverage and the one added read operation - -Five tools plus native shell are functionally sufficient: [native shell](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool/plugin/shell.ts#L31-L100) exposes `command`, optional `workdir`, `timeout`, `background`, and structured `output`, `exit`, `signal`, `truncated`, optional timeout/status/shell ID. Code can check completion and parse JSON outside model context. However, repeated shell-string construction, quoting, process-status checks and CLI JSON normalization are unnecessary model work for common read discovery. The five tools currently cover continuity well and leave broad work/graph discovery less convenient. - -Propose one additional callable, not a command-per-tool mapping: - -```ts -type QueryInput = - | {view: "ready", assignee?: string, parent?: string, limit?: number} - | {view: "list", status?: string, assignee?: string, parent?: string, limit?: number} - | {view: "dependencies", id: string, direction?: "down" | "up", type?: string, limit?: number}; -// tools.beads.query(input: QueryInput): Promise -// Proposed QueryResult: -// {operation:"query", status:"acknowledged", view, records, complete:boolean} -// | {operation:"query", status:"failed", view, detail:string} -``` - -Use a default limit of 20 and a documented positive cap of 50; fixed argv, no arbitrary command/flags, no claims or automatic traversal. Ready/list records project ID, title, status, priority and available assignee; dependency records additionally retain input root, direction and CLI `dependency_type`. Preserve provenance relations such as `discovered-from` separately from scheduling blockers. Do not recompute readiness from an incomplete graph. - -Map to supported `bd ready --json --limit ...`, `bd list --json --limit ...`, and `bd dep list --direction ... --type ... --json` forms under the same guard/cwd/permission/cancellation boundary. `dep list` returns hydrated related issues with relation type (observed read-only for this investigation's Bead), not an invented `{from,to}` edge API. For dependencies cap the normalized return, mark incomplete when records were omitted, and offer narrower relation selection or normal CLI for the remainder. For list/ready do not claim exhaustive completeness merely because a limited response succeeded; a full cap is conservatively incomplete. Do not invent a cross-backend pagination cursor; current help limits `--offset` to proxied-server routes. Avoid depending on `--brief` until minimum-version support is checked; projection can occur after supported JSON reads. - -| Product workflow | Recommended route and benefit | -| --- | --- | -| Ready work, assigned work, issue search | Query ready/list for concise candidates; exact assignment still wins. Native shell `bd search` and less common filters remain available. Catalog search does not search issue text. | -| Task hydration and dependency graph triage | Show only selected IDs; query direct dependencies/dependents with relation types. Compose bounded adjacency views; use native CLI for tree/whole-graph output. No graph cache or local scheduler. | -| Selective knowledge recovery | Search memories by relevant term, return candidate keys; recall only chosen keys. Do not eagerly hydrate every memory. A known key can be recalled alongside its task. | -| Checkpoint/handoff | Ordered checkpoint and optional justified memory update; return each outcome/reference. Assignment transfer uses a separately authorized atomic CLI update, not implicit tool composition. | -| Wider Beads product | Keep formula, admin, search, lifecycle and advanced CLI operations behind current permissions and current CLI help. Native commands invoke model workflows; callable tools provide structured primitives; the shared skill supplies judgment, authority and supporting resources. | - -Retain all 29 workflow commands plus status in `src/workflows.ts`, their native precedence and the package-owned shared skill. A command executes `session.prompt`; it is not automatically a callable code-mode function. Keep upstream-derived guidance and its 16 explicit resource/ADR links. Add a small project-owned code-mode guidance layer instead of replacing that material with static CLI wrappers or duplicating all command syntax. - -## Representative compositions - -These are design sketches for a separately implemented/qualified namespaced contract, not calls run here. IDs, keys and write content must already be selected within authorized scope. Discovery itself is supported today inside code mode: - -```js -// Current ungrouped catalog: search by term, not namespace "beads". -return search({query: "beads", limit: 6}); -// After proposed grouping: search({namespace: "beads", query: "show", limit: 1}) -// Read returned path/signature before calling it; follow next.offset when needed. -``` - -Known-task recovery with one relevant known memory can overlap independent reads. Do not return raw issue history or all memory values: - -```js -const reads = await Promise.allSettled([ - tools.beads.show({id: "assigned-task"}), - tools.beads.recall({key: "chosen-build-lesson"}) -]); -return reads.map((r, i) => { - if (r.status === "rejected") - return {read: i, outcome: "rejected", detail: String(r.reason)}; - const x = r.value; - if (x.operation === "show" && x.status === "acknowledged") - return {read: i, status: x.status, reference: x.reference, - task: {title: x.data.title, status: x.data.status, - acceptance: x.data.acceptance_criteria, notes: x.data.notes}}; - if (x.operation === "recall" && x.status === "found") - return {read: i, status: x.status, reference: x.reference, value: x.value}; - return {read: i, status: x.status, reference: x.reference, detail: x.detail}; -}); -``` - -Select notes/excerpts according to the recovery question; if notes are long, return an explicitly labelled excerpt and omitted-length indicator or relevant validated structure, then hydrate further as needed. Do not silently discard failed attempts or acceptance blockers. For unknown keys, first use `memories({search: "relevant term"})` and return `Object.keys(result.data)` only on `acknowledged`; let the model choose relevance before recall. This keeps search values out of the prompt even though this CLI operation returns them to the runtime. - -Graph triage separates candidate discovery from judgment. A first `query({view:"ready",parent:"authorized-epic",limit:10})` returns candidate summaries/completeness; readiness supplies no dispatch authority. After choosing a candidate within existing authority, inspect it and its direct blockers concurrently: - -```js -const reads = await Promise.allSettled([ - tools.beads.show({id: "chosen-task"}), - tools.beads.query({view: "dependencies", id: "chosen-task", - direction: "down", type: "blocks", limit: 20}) -]); -return reads.map((r, i) => { - if (r.status === "rejected") return {read: i, outcome: "rejected", detail: String(r.reason)}; - const x = r.value; - if (x.operation === "query" && x.status === "acknowledged") - return {read: i, status: x.status, view: x.view, - complete: x.complete, records: x.records}; - if (x.operation === "show" && x.status === "acknowledged") - return {read: i, status: x.status, reference: x.reference, - acceptance: x.data.acceptance_criteria, notes: x.data.notes}; - return {read: i, status: x.status, detail: x.detail}; -}); -``` - -Do not turn an incomplete/failed dependency read into “unblocked.” Direct queries do not promise a graph snapshot across concurrent writers. Hydrate further only when needed; do not recursively dump the graph into logs. - -Ordered persistence uses explicit status checks. This example assumes both writes were already authorized and the reusable finding already validated and reconciled against its existing key: - -```js -const checkpoint = await tools.beads.checkpoint({ - id: "assigned-task", text: "Measured outcome; evidence path; blocker; next authorized action." -}); -const first = {operation: checkpoint.operation, status: checkpoint.status, - reference: checkpoint.reference, detail: checkpoint.detail}; -if (checkpoint.status !== "acknowledged") - return {checkpoint: first, memory: {status: "not-attempted"}}; -const memory = await tools.beads.remember({ - key: "validated-lesson", text: "Validated reusable finding, scope and evidence." -}); -return {checkpoint: first, memory: {operation: memory.operation, - status: memory.status, reference: memory.reference, - commitIndeterminate: memory.commitIndeterminate, detail: memory.detail}}; -``` - -An exception interrupts this sketch before dependent work; do not catch it and manufacture success. A landed-uncommitted or uncertain memory retains its qualification even after a successful checkpoint. No rollback, exactly-once guarantee or automatic retry is implied. Many handoffs need only a checkpoint and concise return, with no reusable-memory write. - -Atomicity belongs to the individual supported CLI operation. Authorized claiming still uses `bd update --claim --actor --sandbox --json`, followed by separate assignee/status readback. Native `tools.shell({command, workdir, ...})` is the verified shell signature; inspect its exit/timeout/truncation before parsing JSON. Use command-scoped actor attribution on every shell write. The typed write adapter derives its actor from host identity; do not add a model-controlled actor argument to these tools. Parent review does not transfer ownership. - -Batching reduces model round trips; it does not make two writes atomic or idempotent. Never put dependent writes in `Promise.all`. Limit concurrent work to bounded independent reads, await all calls whose completion matters, and inspect every settled result. The host warns that pending calls are interrupted when an execution ends. - -The model still decides relevance, task scope, acceptance sufficiency and whether a finding is reusable. Those decisions cannot be encoded as “if ready, claim/close.” Permissions remain per operation, including later calls following a decline. On rejection, dependent work must stop; independently authorized work may continue under the accepted host limitation. Do not add a plugin decline translator, retry loop or claim that prompt guidance guarantees whole-turn termination. Explicit Stop/Cancel must prevent later dispatch/resumption through the separately measured cancellation path, including child/handoff and late-result behavior. No final checkpoint is promised after Stop, unload or compaction. - -## Context efficiency and measured limits - -The benefit is selective return: raw CLI JSON, unrelated graph nodes, full memory maps and intermediate joins can remain in runtime values instead of the next model request. Native shell JSON parsing can already do this; typed reads improve reliable use and discoverability rather than uniquely enabling it. Small one-off reads may cost more catalog/code than they save. No real token, latency, quality or intervention savings were established. - -Scratch `/opt/data/cache/scratch/opencode-codemode-product-wgv/bridge-probe.ts` uses Git-blob-verified copies of the actual pinned catalog/result bridge (`tool-runtime`, schema rendering, tool, namespace, tool-error) and actual product show plus pinned host output executor. It exercises native search and eight independent fixture reads. A diagnostic union/namespace is a copied definition only. Results in `bridge-results.json`: - -| Measurement | Result | -| --- | --- | -| As-built catalog return | `Promise` | -| Diagnostic catalog/search return | Structured `acknowledged`/`failed` union at `tools.beads.show` | -| Eight verbose fixture results, summed compact JSON bytes | 18,432 | -| Eight projected summaries, compact JSON bytes | 905 | -| Bridge call records | 9: one search plus eight reads | -| Logs | 0 | -| Current primary / task-agent injected guidance bytes | 7,758 / 4,421, excluding prime and task-agent prompt | - -These are synthetic UTF-8 byte counts, not tokens or product savings. The comparison excludes generated program text, catalog/signatures, outer formatting, permission interaction, trace storage and provider replay overhead; the fixture deliberately contains irrelevant long history. Projection runs in the scratch driver using the actual bridge, **not the confined interpreter or an installed host**. A full pinned interpreter comparison was not pursued: three required stdlib files were not available at matching blob IDs in the inspected caches. No dependencies were installed and no mismatched-source run was substituted. - -Budget accounting must include: - -- Catalog namespace summaries, selected signatures, search results, and generated code. Large unions cost context; keep fields and descriptions informative and bounded. Native catalog budget is heuristic, not a guaranteed provider token ceiling. -- Outer `execute` text includes returned value, warnings and **logs**. Returning raw results or logging them defeats projection. Files can also escape as collected result parts; do not use attachments as an accidental raw-dump path. -- Host `toolCalls` retains per-call name/status and nonempty input objects in progress/output metadata. The program itself and write text are model-authored input. Do not claim intermediates or sensitive input are never retained. Ordinary replay uses content rather than dumping every metadata field, but storage/traces and model-visible context are different budgets. -- `src/context.ts` injects full guarded prime plus shared guidance on eligible model requests. Caching avoids subprocess work and stabilizes repeated text; it does not remove that text from the request. Full prime can itself include memory content. Code-mode selection therefore does not eliminate the existing eager prime/memory budget. -- `src/host.ts` keeps bounded durable references and recovery cues, invalidates after writes/events, and contributes compaction references. A summary is not a persistence acknowledgement. Preserve these semantics and native replay metadata. - -Do not change full-prime policy or cache freshness during this pre-release delta. Record current injected bytes separately in the existing acceptance exercise; reducing that policy needs its own evidence and owner decision. - -## Smallest implementation handoff and acceptance additions - -Priority is correctness first, then the single broad read improvement in the same separately authorized candidate. Avoid a new certification campaign or tracking graph. - -| Priority | Named source/test/guidance delta | Acceptance evidence | -| --- | --- | --- | -| P0 | `src/continuity.ts`: real per-operation output schemas/unions; matching input constraints; preserve readable content, uncertain targets and original diagnostic detail. Keep existing guard, permission identity, actor, cancellation and sole acknowledgement boundary. | Deterministic status/payload/schema cases in `tests/continuity.test.ts`; execute real registered definitions through pinned host output validation in the existing host qualification harness. Include one write acknowledgement followed by result delivery: no duplicate write/notification or blind retry. Do not vendor an upstream executor into product tests or add a runtime host dependency merely to duplicate it. | -| P1 | `src/continuity.ts`: one bounded `query` definition using the same fixed-argv invocation boundary; no generic runner API, recursive graph manager or writes. `src/host.ts`: namespace metadata and existing gated registration for six tools; preserve effective IDs, lifecycle and outer-result exclusion. | Query view argv/normalization, relation direction/type, caps/incompleteness, read failure, guard/denial/abort cases in `tests/continuity.test.ts`; registration/disposal/visibility in `tests/host.test.ts`. Extend `scripts/bd-contract.ts` only for the newly used supported read shapes, in its disposable repositories and with explicit authority. Check minimum 1.3.0 flag support before depending on 1.3.1-only options. | -| P1 | `src/guidance.ts`: short discovery, structured-status, projection, independent-read/ordered-write guidance, and accurate accepted plain-decline limitation. `src/workflows.ts`: command common guidance can refer to actually registered tools, keeping shell/help fallback and all 30 commands. Keep shared `assets/oc-beads` skill/resources; reconcile any contradictory unconditional stop language precisely, without rewriting upstream-derived workflows. | Focused `tests/guidance.test.ts`, `tests/workflows.test.ts`, `tests/host.test.ts` assertions that preserve actor/authority, missing versus failed, uncertain writes and no retry. Guidance must not claim typed tools are available before registration or that decline guarantees whole-turn Stop. | - -Reuse `.9` installed/model acceptance (task 6.2) for one representative ready/graph triage, selective recovery and ordered handoff using the actual installed catalog, signatures and host executor. Capture current versus selected return/context bytes with correctness and completeness observations, not an invented savings target. Reuse existing restricted-agent, permission, lifecycle/unload/reactivate cases to cover the added read tool and renamed catalog paths. This probe has not passed those gates. - -Reuse `.6` cancellation/handoff work (task 4.2) for explicit Stop/Cancel during a nested permission wait and in-flight operation, no later dispatch or stopped-parent restart, and recovery from earlier acknowledged records. Reconcile the existing plain-decline case under the accepted limitation: rejected target absent, no plugin retry, later calls independently permissioned, original stronger case remains a historical failure. Keep provider/model/reasoning/install provenance and actual actor separate from author/owner/assignee evidence. Parent maps these additions into existing acceptance and decides when to resume; source readiness is not dispatch permission. - -Defer write wrappers for claim/close/dependencies/admin, arbitrary CLI passthrough tools, bulk transactions/idempotency machinery, persistent graph caches, automatic semantic memory extraction, prime-policy reduction, general benchmarks, upstream patches and new multi-agent automation. Native shell plus the preserved skill/commands covers the wider Beads product without making those additions prerequisites. - -**Decision needed:** parent acceptance of this six-tool, schema-first direction and a separately bounded implementation dispatch. The owner has already accepted plain-decline continuation; do not ask for that decision again. Activation, outstanding installed/model and Stop/Cancel qualification, release and tracker closure remain separately owned. - -## Reproduction commands and disposition - -Executed successfully using command-scoped baseline Bun PATH: - -```sh -PATH=/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin:$PATH \ - bun /opt/data/cache/scratch/opencode-codemode-shape-review/check-output-contract.ts -PATH=/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin:$PATH \ - bun /opt/data/cache/scratch/opencode-codemode-product-wgv/bridge-probe.ts -``` - -Additional read-only checks: Git HEAD/status, local source inspection, blob-ID verification against the pinned tree, `bd --sandbox version --json`, current ready/list/dep help and this Bead's direct dependency response. Initial bridge execution failed on a missing scratch `tool-error` module; adding its blob-verified copy resolved it. The added raw-output control initially omitted the required fixture ID and was correctly rejected by input validation; supplying the ID resolved that driver error. The recorded final rerun exited 0. No product tests/typecheck/package checks were needed for this report-only change; the two focused probes supply its runtime evidence. - -Exact repository file added: `docs/code-mode-product-investigation.md`. Exact new scratch entries under `/opt/data/cache/scratch/opencode-codemode-product-wgv/`: `bridge-probe.ts`, `bridge-results.json`, blob-verified source copies `tool-runtime.ts`, `tool-schema.ts`, `tool.ts`, `namespace.ts`, `tool-error.ts`, and `node_modules` symlink to the existing repository dependencies. No existing scratch/source evidence file was changed. - -Evidence/report pointer is appended only to `opencode-beads-wgv`; leave it `in_progress` and assigned to `codex:oc-codemode` for parent review. No acceptance or closure is asserted. diff --git a/docs/code-mode-source-acceptance-vuy10.md b/docs/code-mode-source-acceptance-vuy10.md deleted file mode 100644 index 5a69a4a..0000000 --- a/docs/code-mode-source-acceptance-vuy10.md +++ /dev/null @@ -1,17 +0,0 @@ -# Code-mode source acceptance — tasks 7.1–7.3 - -Parent accepted the corrected source after owner-authorized implementation and closeout. The original plan baseline is `f2d6617619e2c3a35e4aeadd5be0092259b9979c`; the owner subsequently selected Beads CLI minimum **1.3.1**, also the qualification target. Earlier dual-version and not-yet-dispatched wording in the planning package is historical dispatch context, not current execution authority. Only source tasks 7.1–7.3 are accepted here. Remaining tasks 1.1, 4.2, 6.2 and 6.3 stay unchecked. - -- **7.1:** Existing disposable real-CLI contract records 63 passing checks on 1.3.1. The SDK ledger identifies exact binaries, commands and raw captures; 1.3.0 failures remain historical and retired, not passing or blocking supported source acceptance. -- **7.2:** Eleven fixed operations, structured declared outcomes, canonical permission resources, sandbox/actor handling and representative boundary regressions. Existing exact-host scratch executor/catalog observations support result mechanics only, not installed qualification. -- **7.3:** Actual-request identity/capability guidance, packaged CODE_MODE resource and 17 explicit links, 30 retained human commands, conservative freshness and recovery references. Ordinary typed activation remains withheld. - -Independent source review [REVISE](reviews/opus-code-mode-source-vuy10.md) identified one medium recovery-gap overwrite. Sol corrected only `src/host.ts` and `tests/host.test.ts`; all 146 other protected file hashes were preserved. Same-session Opus [recheck READY](reviews/opus-code-mode-source-recheck-vuy10.md) resolved that finding without material correction-caused regressions. Both verdicts are retained. Reviewer model/completion/permission results and exact candidate manifests were parent-verified. - -Parent independently executed the corrected candidate: **191 tests passed, zero failed**, typecheck and packed-package validation passed, whitespace passed. Packed archive SHA-256: `e952532140b44f812e2660425ec485d3bbd474962dd424ed03d70108593b259f`. Optional review observations remain nonblocking; no additional refactoring campaign is implied. - -The source executor was `codex:oc-loop`, session `01a15f23-611b-7f51-886e-f77b574087c8`, Sol/high. Independent reviewer was `claude:aa15a6fe`, session `aa15a6fe-0427-4c80-a763-9d64cb6d12cc`, Opus 5.5/requested medium. Both are stopped; parent owns acceptance and explicit closeout-only assignment handoffs. Beads `.10` and `co7` retain original execution provenance. - -## Remaining gates - -Existing `.2`, `.6` and `.9` own exact OpenCode 2.1.1 native host, explicit Stop/handoff and installed/model/lifecycle qualification. Reuse accepted source evidence and add only their distinct real-host observations. The owner-accepted nested plain-decline continuation remains a failed stronger historical case, not passing Stop/Cancel. The operator OpenCode 2.0.29 is unchanged. This closeout publishes source only; no runtime provisioning, activation, release, archive or new qualification dispatch is authorized by it. diff --git a/docs/command-action-evaluation.md b/docs/command-action-evaluation.md deleted file mode 100644 index b95c818..0000000 --- a/docs/command-action-evaluation.md +++ /dev/null @@ -1,210 +0,0 @@ -# Command action correction: bounded evidence - -## Current status - -**Parent accepted the source and bounded behavioral evidence.** The corrected -R1–R5 evaluation produced one valid sample per case, and the parent checked all -five task markers after independent verification. Publication remains unauthorized. - -The first R1 was invalid because a harness false positive rejected `--no-adopt` -before execution; it is neither a pass nor a product failure. The historical -first-attempt status below is superseded by the corrected evaluation and parent -acceptance. Its byte-for-byte original is retained as -`evaluation-corrected/report-original.md` under the raw evidence root. - -## Superseded first attempt: invalid harness rejection - -At the first handoff, source checks passed but semantic acceptance was unverified: -the harness rejected R1 before execution, and R2–R5 had not run. The following -first-attempt sections preserve that historical state, not the current acceptance. - -## Candidate and source evidence - -Baseline: `de2443c2624950dfdda7fdcf98f71d2bad1d3ad3`, branch -`fix/command-action-wzk`, executor `codex:oc-actions-sol`, Bead -`opencode-beads-wzk`. Parent owns verification/acceptance; the Bead remains -in progress and OpenSpec acceptance markers remain unchecked. - -The local source archive retains version `1.1.0-beta.2` but is **not the published -beta.2 archive**. Its SHA-256 is -`bbf302250f6e71878101a458ca2bcad4b18761eb501f8e9faad43500288234c6`. -The owned native host installed that archive through normal plugin configuration -and loaded its public `@snarkipus/opencode-beads/src/plugin.ts` entrypoint without -wrapper or dependency injection. Every installed archive file matched; native -registration exposed 30 commands and the installed skill retained 17 links. -A separate read-only observer captured native hooks/provider requests and tool -selection; it changed no command, model response, prompt or permission decision. - -Raw evidence root: -`/opt/data/cache/scratch/oc-beads-command-action-implementation/`. -The `evaluation/installed-verification.json` file records the exact installed path. - -| Source check | Observed result | -| --- | --- | -| RED/GREEN invocation and real callback slice | 2 expected failures, then 66 tests passed | -| RED/GREEN purpose/resource/authority/docs slice | 4 expected failures, then 91 focused tests passed | -| Typecheck | Passed | -| Full `bun test` | 205 passed, 0 failed | -| Installed package smoke | Passed, including bare sync/explain callbacks and literal native metadata | -| Named/global strict OpenSpec | Passed, 4 total change/spec items | -| Protected source hashes | All 153 matched | - -Logs are in `logs/`; these deterministic checks verify contracts and forwarding, -not genuine model intent or successful remote synchronization. - -## First and only R1 sample - -The exact retained runtime reported OpenCode `2.1.1`; its SHA-256 is -`4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9`. -Beads reported `1.3.1 (c1c4b642a: HEAD@c1c4b642ac1c)`. -The genuine native configuration was `openai/gpt-6.1-sol/high`, with observed -provider route `https://chatgpt.com/backend-api/codex`. There was no controlled -provider. Session: `ses_e9ea40308ffeh7DtkDhK6EoHht`; host-rendered actor: -`opencode:action_eval:f071722b7d81`. - -Harness setup created isolated HOME/XDG/store/local-file remote and two replicas, -then seeded unrelated base issue `act-6hl`, local-only issue `act-eon` and -remote-only issue `act-b6x`. Setup/probe writes were separately authorized harness -operations, not product provisioning. The local store and remote genuinely differed -before the bare command; no real project issue database or remote was used. - -The native command endpoint received `name: oc-beads:sync`, empty text and queued -delivery. The submitted prompt retained the invoked name and requested outcome. -The model loaded the packaged skill, discovered the native namespace, read the -focused CLI reference and inspected `bd sync --help`, then selected direct shell: - -```sh -bd sync --no-adopt --actor='opencode:action_eval:f071722b7d81' --sandbox --json -``` - -Its selected cwd was the disposable `evaluation/repo` directory. The real host -permission request reached the harness. The harness's forbidden-word regex matched -`adopt` inside `--no-adopt`, incorrectly replying `reject`. Native denial then -prevented execution and the assistant step ended interrupted, without a final -outcome response. The logging CLI wrapper recorded no actual sync invocation. -This is a harness false positive, not evidence of missing invocation authority, -a broken upstream sync or successful permissioned convergence. - -Before/after issue state, unrelated sentinel files and configured remote were -unchanged. Local readback still contained only the base/local issues; a harness -peer pull/readback still contained only the base/remote issues. Convergence was -not achieved. `evaluation/semantic-result.json`, `permissions.jsonl`, -`R1-tool-selection.json`, `R1-bd-calls.json`, `R1-before.json`, `R1-after.json` and -`R1-peer-readback.json` preserve those outcomes. `R1-command-supplied-prompt.json`, -`R1-model-input.json`, `model-provenance.json` and native traces distinguish the -command prompt from actual model requests and chosen tools. - -## Stop, cleanup and limits - -R2 sync explain, R3 missing-input update, R4 denied sync and R5 bare compact guide -were **not executed** after the first R1 failure. This run proves genuine selection -of the intended action, but does not satisfy the five-case semantic gate. Parent -disposition is required before any corrected-harness evaluation; no rerun is -claimed or implied. - -The supported credential API imported current active native access only into the -isolated host, with an empty noncredential refresh field. No source refresh value -was read, no account refresh/rotation occurred, and no source credential database -was written. The owned foreground host exited, its listener closed, and transient -credential-bearing runtime state was removed. No current-access string remains in -retained evaluation files; operator config/runtime and selected auth fingerprints -matched before/after. See `evaluation/cleanup.json` and operator fingerprint files. - -No commit, push, tracker sync/closure, archive, version change, release, extra agent, -operator service restart or production path expansion occurred. Evidence is bounded -to this source candidate and one interrupted sample on the exact host/model above; -there is no new universal, reliability or other-host qualification claim. - -## Parent-authorized corrected-harness evaluation - -The original interrupted observation above and its `evaluation/` evidence remain -unchanged. Parent explicitly authorized correcting the disposable harness false -positive and making **one valid R1–R5 evaluation**, with no integration/source/ -guidance/prompt changes. The corrected evidence is separate, under -`/opt/data/cache/scratch/oc-beads-command-action-implementation/evaluation-corrected/`. -The five valid samples passed the bounded evidence review; parent acceptance is -still pending. The total history is one invalid interrupted R1 selection plus -one corrected valid R1 execution, followed by one sample each of R2–R5. - -Before model use, `rule-red-old.log` reproduced the old responder's rejection of -the intended command as an expected assertion failure. `rule-green-corrected.log` -passed four deterministic tests: exact no-adopt sync with actual actor/sandbox -was allowed, while adoption flags, administration, unrelated writes, actor -substitution, shell substitution/redirection and compound commands were rejected. -The small fixture tokenizes only enumerated command shapes; it is not a general -permission interpreter. R4 receives no shell override, and actual native deny -rules remain controlling. No product prompt or permission implementation changed. - -The exact candidate SHA-256 remained -`bbf302250f6e71878101a458ca2bcad4b18761eb501f8e9faad43500288234c6` before and after. -The corrected isolated host installed an identical copy of the frozen archive -through its normal public entrypoint, without wrapper/DI; every installed and -packaged source file matched. The retained OpenCode `2.1.1` binary, Beads `1.3.1` -binary and genuine native `openai/gpt-6.1-sol/high` account route were unchanged. -Observed provider route remained `https://chatgpt.com/backend-api/codex`. -There were zero native retry events and no model reruns or fallback executor. - -| Valid sample | Session | Observed outcome | -| --- | --- | --- | -| R1 bare sync | `ses_e9e9bb268ffeUO5mWahu6487kM` | Actual normal CLI sync succeeded; local and remote readback converged; unrelated state unchanged | -| R2 sync explain | `ses_e9e9b6621ffemn5UmE8K524DAN` | Explained the workflow and explicitly reported no sync attempt; no mutation | -| R3 bare update | `ses_e9e9b213fffeJ7m4wJcIqgbosS` | Asked which issue and which fields/notes to change; zero writes | -| R4 bare sync, native shell/execute denied | `ses_e9e9af009ffeRKlZ6uNhMIs1Ii` | Reported blocked capability honestly; no sync or bypass | -| R5 bare compact | `ses_e9e9acec8ffefvgm8SacRSisV1` | Delivered semantic-compaction guidance with mode/actor/recovery limits; no administration mutation | - -R1 ran exactly: - -```sh -bd sync --no-adopt --actor=opencode:action_eval:6f98120839e0 --sandbox --json -``` - -Its actual cwd was `evaluation-corrected/repo`. Native permission requested this -command and received `once`. The real CLI returned exit 0, `status: ok`, -`attempts: 1`, `pulled: true`, `pushed: true`, and `rows_corrected: 0`. -Harness setup had seeded base issue `act-3bm`, local-only `act-adl` and remote-only -`act-lxq` against an existing local disposable file remote. After the selected -sync, local readback and a separately authorized harness peer pull/readback both -contained all three IDs. The unrelated base issue, sentinel files, Git status -and configured remote were unchanged. The harness peer pull was a readback probe -after product success, not a product repair/retry loop. - -R2–R5 each preserved before/after issue, file, remote and Git state exactly. -Their CLI traces contained only ordinary context/version/prime probes, plus -`bd admin compact --help` for R5. No issue-write, sync, initialization, compact -application or other administrative command ran. The actual R4 model requests -contained neither `shell` nor `execute` in their native tool inventories, and the -model selected neither; no permission responder overrode a deny. Normal host -context probes remained visible and were not misreported as absent. -R5's analysis/apply examples were explanatory text and were not executed. - -`semantic-evidence-review.json` records the response review, actual tool choices, -model route, inventories, permission decisions and before/after comparisons. -Per-case `R*-command-supplied-prompt.json`, `R*-model-input.json`, -`R*-tool-selection.json`, `R*-bd-calls.json`, `R*-response.json` and state files -retain the distinction between command prompt, genuine model selection, actual -argv/outcome and readback. `installed-verification.json` records the exact public -installed entrypoint. Script PASS was checked against these observations rather -than treated as the acceptance decision. - -Cleanup verification found the owned foreground host exited, its listener closed, -no owned processes remaining, transient credential-capable state removed, and no -current-access string in retained corrected evidence. The supported isolated -credential import carried current access only, with no refresh capability; -operator config/runtime and selected source-auth fingerprints remained unchanged. -`cleanup-verification.json` records these checks. - -All 172 frozen repository file hashes matched before this sole permitted report -append. The archive, installed content, original interrupted evaluation and prior -handoff hashes also matched. The parent's live `harness-correction-worker.log` -records this correction session and was separately identified as externally -updated; it is not original interrupted-run evidence. Historical raw evidence and -prior handoffs were not overwritten or relabeled. The original report is retained -byte-for-byte as the prefix of this file and in `report-original.md`. - -No source qualification was repeated; the parent's independent source checks are -reused. No integration/source/guidance/test/spec/task acceptance marker changed. -No commit, push, project tracker sync/closure, archive, version/release, owner -store/runtime/auth mutation or extra agent occurred. Evidence remains limited to -these five single samples on the exact frozen host/model/candidate; it establishes -no universal, reliability or other-host qualification. Parent independent evidence -acceptance remains the next gate. diff --git a/docs/compatibility-evidence.md b/docs/compatibility-evidence.md index 8a496e4..a75efde 100644 --- a/docs/compatibility-evidence.md +++ b/docs/compatibility-evidence.md @@ -17,5 +17,15 @@ canaries used Beads 1.3.4 on Linux and stopped a pending permission request, not already-running `bd` process. Reopening a saved session is not compaction or cross-provider replay. These runs do not establish live database upgrade behavior. +## Automated checks vs. live-host receipts + +- **Ordinary CI is pinned:** standard CI tests against the validated `bd` release (`beads.validated` in `package.json`) and the pinned development `@opencode/plugin` SDK. +- **Scheduled upstream source gates** ([`beads-contract`](../.github/workflows/beads-contract.yml)): + - Exercises the real `bd` CLI contract against the latest stable Beads release. + - Installs the exact published SDK for the newest stable OpenCode V2+ release in a disposable snapshot and runs tests, typecheck, and packed-fixture smoke checks. + - Flags newer unreviewed releases for human review even if checks pass. + - Runs an independent Beads `main` source comparison as an informational check (changed and unchanged comparisons succeed; retrieval/comparison errors fail that job) without blocking releases or advancing baselines. +- **Exact live-host receipts are distinct:** passing pinned CI or scheduled SDK/CLI gates does not establish live-host or model-backed qualification. Only exact live-host runs—recorded in the table above—provide native-host receipts. + For a new run use the [native release probe](native-release-probe.md). For a released plugin pin for an older host, see the [user guide](user-guide.md#compatibility). diff --git a/docs/diagnostics-acceptance-2026-11-15.md b/docs/diagnostics-acceptance-2026-11-15.md deleted file mode 100644 index ca3db8a..0000000 --- a/docs/diagnostics-acceptance-2026-11-15.md +++ /dev/null @@ -1,58 +0,0 @@ -# Integrated diagnostics acceptance — 2026-11-15 - -## Accepted source - -The integrated diagnostics candidate adds separate Plugin / Beads observations, -compact normal output, bounded details and static help. New captures contain a -finished code-populated report with DATE, executing package VERSION and observed -native repository-root PATH under the title, plus explicit newline-separated -report/invocation boundaries. Existing saved snapshots are not retrofitted. - -Implementation tasks 1–6 in `add-integrated-beads-diagnostics` are accepted. -The native Beads 1.3.1 / 1.3.4 qualification from the initial implementation is -reused; presentation-only follow-ons did not add native probes or change the -ordinary full prime/memory lifecycle. The collector-only no-store boundary does -not extend to that subsequent lifecycle. - -## Independent review and execution - -Claude Opus 5.5 / medium reviewed the initial integration and subsequent -presentation candidates. Final c4a delta review session -`9f78d4c8-614c-4ed2-8c80-b1ea176dd26d` returned **READY**, zero Standards and -zero Spec blockers. It inspected source/tests/spec evidence without rerunning -tests. Its nonblocking free-text observation is clarified in the diagnostics -reference: appended prose selects normal output, not an additional answer. -No speculative empty-root hardening was added. - -Parent independently reran **256 tests / 12,787 assertions**, typecheck, strict -active/all-canonical specification validation, whitespace and exact-archive -package smoke. Every packed member matched the reviewed source. The no-network -regression uses the installed OpenCode 2.3.0 Chat serializer on actual expanded -command messages, not a duplicate concatenation mock. - -## Owner-reported canary - -Archive: `opencode-beads-template-canary-89f1cd57a447.tgz`. -SHA-256: `89f1cd57a4479573205625771d5ab1b45dd0a28d29fd3835f1e96acba03c3a22`. -Its internal version remains 2.2.1; the checksum identifies the candidate. - -The owner supplied normal displayed reports from Zeus/snark-surface at -`2026-11-15T01:01:34.240Z` and VPS/docker-lab at -`2026-11-15T01:01:45.904Z`. Both show the intended header order, repository roots, -no appended invocation and no leaked report markers. Zeus reports healthy; -VPS retains its expected hook mismatch and action. Neutral first-capture context -and absent shared skills were not treated as integration failures. - -This is owner-reported normal-output evidence, not independent raw provider/TUI -inspection. Help/details have automated coverage but were not supplied in this -visual pass. The original affected turn's precise cause remains unlocalized; -fixing the demonstrated request-boundary ambiguity does not prove that cause or -guarantee byte-exact model output. - -## Custody and publication boundary - -Detailed immutable reports, manifests, RED/GREEN and parent logs are retained at -`/opt/data/research/beads-health-design/diagnostic-report-template/`, with the -preceding integration/native receipts under `/opt/data/research/beads-health-design/`. -This record supports source/task/spec closeout. Registry release, version bump -and operator-host activation remain separate from source integration. diff --git a/docs/history/opencode-sdk-contract-ledger.md b/docs/history/opencode-sdk-contract-ledger.md deleted file mode 100644 index 4f80242..0000000 --- a/docs/history/opencode-sdk-contract-ledger.md +++ /dev/null @@ -1,284 +0,0 @@ -> **Historical record — not current guidance.** This is the complete former body -> of `docs/opencode-sdk-contract.md` as it stood at released main -> [`a4936526103cfc9a0112110a70a518f01d16f2f4`](https://github.com/snarkipus/opencode-beads/blob/a4936526103cfc9a0112110a70a518f01d16f2f4/docs/opencode-sdk-contract.md), -> moved here during the post-2.0.0 documentation reconciliation. Only relative -> links were rebased for the new directory; all text, pins, verdicts, failures and -> dated candidate/unexecuted wording are preserved as written at the time. Statements -> such as "release candidate", "not yet qualified" or "activation remains withheld" -> describe the state when each section was written, not the published 2.0.0 package. -> Current behavior lives in the canonical specs listed in the -> [documentation index](../README.md); current host interface facts live in the -> [OpenCode integration reference](../opencode-sdk-contract.md). - -# OpenCode V2 Plugin Contract - -## 2.0.0 release candidate — OpenCode 2.2.6 - -The 2.0.0 release candidate pins development types to `@opencode/plugin` `2.2.6`, declares optional peer range `@opencode/plugin` `>=2.2.6 <2.3`, and admits hosts in that range. Exact OpenCode 2.2.6 qualification is parent-accepted for archive SHA-256 `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`; see [current qualification](../opencode-22-qualification-5rj2.md). The `opencode-beads-o66` deficiency remains unresolved. The 2.0.0 candidate preserves the qualified runtime and packaged guidance; its version/README metadata produce a different archive from that qualified canary. The published beta.5 artifact retains its historical `>=2.1.1 <2.2` range. Preparation is not registry publication or operator activation. - -With the installed 2.2.6 SDK, OpenCode projects durable user records into `@opencode/ai` request `Message` values without their metadata while retaining message IDs. The candidate checks session location before calling the supported `ctx.session.context({ sessionID })` API, then matches each projected typed user-message ID to the durable `SessionMessageInfo` record. One request-local read builds the ID map; no snapshot cache or alternate message API is used. The current `ocBeadsWorkflow` snapshot takes precedence over legacy `ocBeadsSync`; workflow instructions and captured diagnostics are expanded only by the existing primary and compaction hooks. A failed or incomplete native read reports guidance unavailable and leaves ordinary input intact. Location, generation and cancellation are checked at the existing host boundary. - -**Known unavailable recovery case:** after native compaction on model A, changing to model B that cannot replay A's native context may leave the earlier workflow snapshot or captured diagnostics absent from the current `session.context` result. The candidate reports that guidance unavailable and does not reconstruct it. This corresponds to [upstream issue #57424](https://github.com/anomalyco/opencode/issues/57424) and local deficiency `opencode-beads-o66`; both remain unresolved. This limitation concerns prompt guidance only; it does not read, change or repair Beads issue data. - -The candidate's native request guidance handles three observed capability shapes separately: composed `execute` with catalog discovery, directly visible namespaced Beads leaves when exposed, and direct-only shell. Each operation retains its own host permission check; failures are not retried through another surface, and Stop/Cancel remains controlling. Direct leaves and shell are used only when actually visible and permissioned. - -## Current measured boundary — tasks 6.2–6.3 - -Source tasks 7.1–7.3 are parent-accepted at `8831169d3c83c333fdf13d4a4efc743eaf495e2b`; [191-test/source and63 CLI evidence](../code-mode-source-acceptance-vuy10.md), [15-case native](../opencode-host-codemode-qualification-vuy2.md) and [74-check Stop/handoff](../opencode-stop-handoff-qualification-vuy6.md) remain accepted and were consumed without rerun. The [installed/model continuation](../opencode-installed-model-continuation-vuy9.md) now records passing worker evidence for selected 6.2 and subsequent 6.3 reconciliation: exact released2.1.1, unchanged accepted packed artifact, genuine OpenAI Sol/high A–D semantics, durable uncertainty/readback, actual child actors and fresh/summary/provider-native recovery, with corrected actual cleanup/17 resource passes reused. Parent acceptance is complete for all 16 implementation tasks; see [final acceptance](../code-mode-final-acceptance-vuy9.md). - -Ordinary typed activation remains withheld. The typed evaluation uses the existing internal dependency through an immutable scratch bootstrap importing the installed unchanged package. Actual provider-native replacement replay is same-provider/model only; no cross-route migration or multi-hour guarantee is claimed. The nested plain-decline limitation and original location-reload failure remain failed historical evidence. Native watched-config cleanup is the unload acceptance boundary; registry replacement alone does not prove disposal. All 19 requirements and 73/74corpus dispositions plus CODE_MODE are mapped in the new report. Earlier candidate/unexecuted wording below retains historical scope; no release/operator change is authorized. - -## Task 7.1–7.3 source candidate — 2026-10-21 - -Executor `codex:oc-loop`, assigned only `opencode-beads-vuy.10`, based on published plan `f2d6617619e2c3a35e4aeadd5be0092259b9979c`. This section records a working-tree candidate, not parent acceptance, a source commit, installed qualification or activation. Earlier planning and accepted five-operation/170-test evidence below retains its historical scope. The product now declares eleven operations in one native `beads` namespace with code-mode-only registration; ordinary setup still withholds that registration pending the separate native/installed gates. The owner explicitly raised the Beads support floor to >=1.3.1 during this source work; package release version, dependencies, operator installation and host admission remain unchanged. The published planning baseline now has a parent-owned local support-policy delta. - -### Owner support correction and CLI contract ledger - -Owner decision: “1.3.1 should be the minimum beads version not 1.3.0.” -The supported minimum and current qualification target now coincide at **1.3.1**. -Package `beads.minimum`, runtime `MINIMUM_BD_VERSION`, README and positive fixtures -use that floor; 1.3.0 is refused before any store/context lookup, even with -`autoMigrate`. Older captures below remain failed historical evidence, neither -current qualification nor a current blocker. No compatibility branch or further -1.3.0 execution follows. This supersedes the old dual-version/support/blocker -statements in the historical planning sections below. - -Existing `scripts/install-bd.sh` installed official checksum-verified Linux amd64 releases only into `/opt/data/cache/scratch/oc-loop-implementation/bin-1.3.0` and `bin-1.3.1`. Binary identities: - -| Role | Actual version/source reported by binary | Binary SHA-256 | -| --- | --- | --- | -| Historical retired minimum (not supported) | `1.3.0 (f45b249ce: HEAD@f45b249ce6b4)` | `fb387d28410390eb9f0ef81f242a0c789c632f0024f58fe6a8b02d3f06ea20ef` | -| Supported minimum/current target | `1.3.1 (c1c4b642a: HEAD@c1c4b642ac1c)` | `a8f48d771b9e11eccfced4aed72923b59eda746f7a9b425e7ca1af7a51251653` | - -Historical provisioning and initial commands executed once per then-selected version, from the repository (the 1.3.0 commands are records, not instructions to repeat): - -```sh -./scripts/install-bd.sh 1.3.0 /opt/data/cache/scratch/oc-loop-implementation/bin-1.3.0 -./scripts/install-bd.sh 1.3.1 /opt/data/cache/scratch/oc-loop-implementation/bin-1.3.1 -PATH=/opt/data/cache/scratch/oc-loop-implementation/bin-1.3.0:/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin:$PATH BEADS_ACTOR=codex:oc-loop bun run test:bd-contract -PATH=/opt/data/cache/scratch/oc-loop-implementation/bin-1.3.1:/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin:$PATH BEADS_ACTOR=codex:oc-loop bun run test:bd-contract -``` - -The existing script creates finite disposable Git repositories and a separate HOME/XDG, clears inherited BEADS_DIR, uses explicit `cwd`, 60-second process bounds, `--sandbox` on every CLI call and the real executor actor on mutations, then removes those repositories. `fixture-owner` is an intentionally assigned fixture assignee, never the command author. No real tracker is a fixture. The script now captures every exact argv, cwd, stdout, exit and failure stderr in `observed` JSON lines. This ledger cites those captures rather than introducing another generator. - -Full captures: `/opt/data/cache/scratch/oc-loop-implementation/contract-1.3.0.log` (SHA-256 `84d76a88b653a545fb3b78f5acef229783011d2a3dabb757ba668e83dc9f2373`) and `contract-1.3.1.log` (SHA-256 `5855393ab67de6d750489974be832cebe2f6a779103a544d06663d6eaa97182d`). **Historical 1.3.0 exited1 (59 checks passed, five fixture assertions failed); supported 1.3.1 exited0 (63 checks passed).** The assertions were corrected before the 1.3.1 run. The owner retired 1.3.0 support; its old failure remains failed and requires no further qualification or fixture work. Supported 1.3.1 has positive blocked-filter evidence and no demonstrated unsupported core behavior. Only the explicit owner-selected floor changed; no upstream repair was made. - -In the table, `I/C/P/O` identify the historical retired-floor issue `repo-g57`, child `repo-an5.1`, parent `repo-an5`, occupied issue `repo-cmo`; current equivalents are `repo-aa0`, `repo-3up.1`, `repo-3up`, `repo-ki3`. `A` is exactly `codex:oc-loop`. Substituting these aliases reconstructs the recorded argv; multiline text and full outputs remain in the captures. All listed successful calls exited 0 unless stated otherwise. Product permission resources render their exact fixed subcommand-first argv; writes insert `--actor A --sandbox` before any `--` terminator, reads insert `--sandbox` there. Product actors derive from actual host session/agent, not this implementation worker's actor. - -| Surface | Runtime argv/evidence in both captures | Observed contract and product decision | -| --- | --- | --- | -| Ready/list/search | ` --limit 2 --json` and filtered variants; ready: `--parent P --label contract-label`; list additionally `--status open`; search: `--label contract-label --status open -- --assignee=x`; assignee calls use `--assignee A --limit 2 --json` (search adds `-- contract`) | Arrays, filtered child C, limit 2 enforced. Ready assignee query returns `[]` because I is in_progress; list/search return I. Product defaults 20/max50 and fetches limit+1 where supported. Ready/list completeness is query-scoped; search stays unknown when not demonstrably truncated, because a short filtered response does not prove absence of CLI truncation. Search parent, ready status and blocked assignee/status are not advertised. No version branching. | -| Blocked | `blocked --parent P --label contract-label --json --sandbox` | Historical 1.3.0 returned `[]`; supported 1.3.1 returned C with ordinary issue fields plus blocker fields. The retired 1.3.0 positive case was unverified because its fixture blocker was not created successfully; supported 1.3.1 has positive filter evidence. Product reports bounded returned rows with completeness unknown (false when capped), never claims empty implies globally unblocked. No unsupported `--limit` flag is sent. | -| Single-ID get | `show I --json --sandbox`; `show contract-not-found --json --sandbox` | Success is a one-record array preserving notes/acceptance/design and separate audit/owner/assignee. Unknown ID exits 1 with error JSON and stderr, never a synthetic missing record. Product get is sequential, at most25 unique IDs, one approval listing all exact resources and fresh checks before every spawn. Partial success preserves per-ID failures; all failed stays failed. | -| Direct edges | `dep list C --direction down --type parent-child --json --sandbox`; `dep list P --direction up --type parent-child --json --sandbox`; unfiltered down call | Typed issue arrays: down yields P, up yields C. Unfiltered output preserves discovered-from and parent-child. Current additionally evidences a blocks edge. Product allows one optional qualified CLI type per call, caps after normalizing, preserves unknown status and returns unknown completeness unless capped; no transitive graph or unblocked inference. | -| Claim | `update I --claim --json --actor A --sandbox` | One-record array with `assignee=A,status=in_progress`; later show confirms author and assignee separately. This is required for acknowledged. Exit0/malformed/wrong actor/state is uncertain, with target and actor. No hidden show or second approval. | -| Claim conflict | `update O --claim --json --actor A --sandbox` | Both exit1, empty stdout. Stderr includes a human diagnostic then JSON `{"error":"1 of 1 issues failed to update","failed":[{"id":O,"error":"updating issue: issue already claimed: already assigned to …"}],"schema_version":1}`. Product not-claimed requires this single-target structured evidence; arbitrary errors remain uncertain. | -| Append note | `update I --append-notes --json --actor A --sandbox` | One-record array retains prior notes plus newline and exact appended text; fresh show confirms retention. Product requires matching target and appended suffix. Notification failure appends detail without erasing the original diagnostic. | -| Selected update | `update C --status blocked --priority 3 --add-label added --remove-label contract-label --json --actor A --sandbox`, then separate deferred/open/in_progress status calls | Returned records evidence status, priority3 and labels `["added"]`; all four nonclosed statuses observed. Product rejects empty updates, closed/ownership/claim changes, conflicting label sets and unknown fields. Requested fields must be evidenced for acknowledgement. | -| Close | `close I --reason contract --json --actor A --sandbox` | Returned one-record array has exact target and status closed. Caller still owns authority and acceptance judgment. | -| Create | `create --title --assignee=x --type task --priority 1 --description "contract-marker description" --acceptance "contract acceptance" --design "contract design" --parent P --deps discovered-from:I --labels contract-label --json --actor A --sandbox` | Generated child ID C; literal title `--assignee=x`, no assignee, actual created_by A, exact selected fields. Other calls establish bug/feature/chore/epic types. Product uses supported `--title`, never a free option-like positional, and never auto-assigns. Uncertain creation preserves its identifying query/title; caller searches/gets before considering another write. | -| Memories/recall/remember | `memories --json --sandbox [-- contract-marker]`; `recall contract-knowledge --json --sandbox`; `remember --key contract-knowledge --json --actor A --sandbox -- ` | Version1 metadata plus key→value map; no matches is a successful empty map. Recall found has exact value; missing exits1 with key/value empty/found=false; empty remember exits1 with error, not an empty stored row. Remember actions remembered/updated preserve exact content. Product retains empty-found versus missing fixtures and landed-uncommitted/commit_error/commit_indeterminate branches, without claiming those commit failures were induced in these real runs. | -| Full prime | `prime --full --sandbox` before and after issue writes | Both bounded comparisons were equal; this does not establish independence across all supported project policies/content. Keep full prime and conservative location invalidation for possible issue/memory writes. Existing guard, migration-marker, default-install and setup contracts also ran in disposable repositories. | - -Historical 1.3.0 fixture failures: adding blocks to a pair already linked discovered-from was correctly refused, causing two downstream positive-blocker assertions to fail; the claim test incorrectly expected `[]` stdout and different text; the ready test incorrectly expected an in_progress issue. The captures preserve all five failures. Corrections use a separate blocker, the observed conflict diagnostic and ready's actual actionable scope. These historical 1.3.0 failures are not relabeled passing. The now-selected 1.3.1 minimum/current run establishes the positive blocked-filter behavior and passes the aggregate; no obsolete-target repair or inference from help is required. Help/source was discovery only. - -### Final verification after the owner floor correction - -The new floor is implemented in `src/guard.ts` and `package.json` only; release -version1.0.2, validated1.3.1, dependencies and lockfile remain unchanged. Focused -RED `minimum131-red.log` records26 pass/four failures (old binary admitted, -old notice, old README and manifest assertions). GREEN `minimum131-green.log` -records30 pass/zero failures, including 1.3.0 refusal after version alone and -1.3.1 readiness. Positive supported fixtures use1.3.1; retired1.3.0 appears only -in rejection fixtures and historical evidence. - -One supported1.3.1 contract rerun was justified by the changed runtime floor, -using the same command above and unchanged extended script, captured separately -as `/opt/data/cache/scratch/oc-loop-implementation/minimum131-contract.log`: -exit0, **63 passed**, SHA-256 -`8b28e3069fbf0bab8051fe28ce47008d7a509a1e7f37020a7d72e1accaa9dfe4`. -The positive blocked query was exactly -`bd blocked --parent repo-a5a --label contract-label --json --sandbox`, exit0; -its returned child `repo-a5a.1` has `status:open`, -`labels:["contract-label"]`, `blocked_by_count:1`, `blocked_by:["repo-6oi"]`. -No1.3.1 core/blocked-filter gap remains from the retired fixture failure. No -1.3.0 command or compatibility repair ran after the owner correction. - -Final branch review also tightened declared issue-field normalization and omits -optional undefined values so output and readable JSON content agree. These are -normalizer corrections in the same module, not a schema validator framework. -Their RED `minimum131-normalization-red.log` is31 pass/one failure; the combined -focused GREEN is62/0. Existing operation table cases now check malformed-output -branches as well as success; no additional version or permission matrix. - -Final cheap checks use new captures `minimum131-final-tests.log` (**190/0**, -1895 assertions), `minimum131-final-typecheck.log` (exit0), and -`minimum131-package.log` (exit0; archive SHA-256 -`86f781ba6a17949665448e0603ad696afb7eeb6be95311b68ca6e26c105766d7`). -That is still20 added tests over170; floor rejection/manifest checks retarget -existing cases. Package smoke checks all30 command callbacks and17 installed -links. Status records registration-plus-execute visibility as observed evidence, -with leaf availability explicitly unknown; it never treats execute alone as -proof every typed leaf exists. User/repository policy and actual permission -identity remain distinct from audit attribution. - -### Actual native output executor/catalog scratch rerun - -A single new scratch adaptation of the existing two probes supplied the initial check: - -```sh -PATH=/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin:$PATH bun /opt/data/cache/scratch/oc-loop-implementation/native/candidate-probe.ts -``` - -Initial exit0. Pre-floor candidate `src/continuity.ts` SHA-256 `ef9e28be509f35499a183e6a84108d777a3a16236491301a2025ac0b3fac0a8e`. All11 actual definitions supply their own input/output schemas through `definition`, without synthetic schema replacement. Native catalog search returns structured union signatures at `tools.beads.get`/`tools.beads.note`. The actual `packages/core/src/tool/runtime.ts` executor runs inside the copied code-mode result bridge: get acknowledges two separate issue reads, note acknowledges one fixture update and its actual derived actor. These are fixture CLI calls, not real mutations. There is no fallback string/null output schema and no direct-method-only success claim. - -Source pin independently checked against the complete cached 2.1.1 tree (`ba546ec1598a70db2570e9c6258028d955ba8f58`, truncated=false): executed core tool/runtime blob `d1c5e29caf157fce941024570bc1fe9d5727621e`, code-mode tool-runtime blob `9c179bbfe070959704bc6e750e6e2d0045da2b6a`, tool-schema `900556191ca454318de25710df038be96a422035`. The copied tool/namespace/tool-error and Promise adapter inputs also match that tree. Original probes are untouched; all copies and this adaptation live only under the new scratch directory. Results `/opt/data/cache/scratch/oc-loop-implementation/native/results.json`, SHA-256 `eaef8c953bd3df7e9671a0aefe01fe87e7761a34aca7d49b5350fb6847fb217c`; stderr is empty. Product tests import no host executor and add no dependency or maintained runtime seam. This is a native schema/catalog bridge check, **not** interpreter, installed-host, model, permission-matcher or lifecycle qualification; .2/.6/.9 retain their acceptance scope. - -The same scratch adaptation was rerun after the changed guard floor, then after -final normalizer corrections, preserving separate `minimum131-results.json` and -`minimum131-final-results.json` captures. Final exit0 on continuity SHA-256 -`0bb76279663fd865ba99247a3f1f71b5442c39b4fbcea7eeac875da21d37515c`, -guard SHA-256 -`ebfca3c54960d527c7cdca8193c6310714e408240e01b74db249e15bec10ba18`. -Final native result bytes are unchanged (SHA-256 -`eaef8c953bd3df7e9671a0aefe01fe87e7761a34aca7d49b5350fb6847fb217c`), -and final stderr is empty. Exact final dependency hashes and actual worker -session are in `native/minimum131-final-inputs.json`. These reruns check the -changed candidate through the same single scratch seam; they do not create a -maintained test/runtime dependency or qualify the installed host. Earlier -results and original historical probes are preserved. - -### Context, guidance and deterministic verification - -Guarded full prime is cached separately from per-request actor/capability rendering. Actual request session/agent drives the same executorActor function as typed writes; permission assertions independently retain actual invocation context.agent. Status uses observed request identity/capabilities or unknown, discloses unknown leaf availability and effective registry ownership limits, and never opens a store to invent capability. Native shell remains direct-only. Every possible issue/memory write conservatively invalidates relevant location prime; acknowledged outcomes avoid a redundant generic readback cue. Failed/uncertain/partial outcomes retain targets, actor, original diagnostics and recovery gaps. Task and memory references remain distinct; ordinary unrelated tool errors no longer cause a generic prime refresh, while child/important recovery and external changes retain freshness checks. Owned cleanup clears request observations with the existing session/reference state. - -The scope/ownership/stop policy remains in the task-agent prompt; its repeated executor section is removed only from that agent's injected guidance. Detailed project planning/review elaboration moves on demand to existing WORKFLOWS; distinct user/repository policy minimization is unchanged. All30 commands and native override precedence remain, with capability-neutral workflow prompts. CODE_MODE is explicitly linked and packaged: 16 resources plus ADR, 17 links. - -Evidence directory `/opt/data/cache/scratch/oc-loop-implementation`: declaration RED `operations-red.log` (15 pass/1 fail), first GREEN (16/0), final operation suite (32/0), request-context RED `context-red.log` (16/1), integrated GREEN (111/0), final full `bun test` **190 pass/0 fail**, `bun run typecheck` exit0 and `bun run test:package` exit0. This adds20 tests over the accepted170-test baseline, largely operation-specific table cases and representative request states, not an operations×versions×permissions matrix. Package archive SHA-256 `afae8906f44d534a352e8d0fb86469b0ab59b4051e5f5a5e205cb8ef72f658ba`; unpacked callbacks and all17 links passed. Strict OpenSpec change/all, planning validator and whitespace checks passed. Worker task markers, review reports, shared/operator integrations and activation remain untouched; the seven active-plan edits are the separately recorded parent support-policy delta. Historical 1.3.0 aggregate failure remains failed and retired; supported 1.3.1 minimum/current qualification passes. - - - -## Historical planning correction — Opus S1–S5 / P1–P3 - -The [original REVISE review](../reviews/opus-code-mode-plan-review-wgv.md) remains immutable. The [correction map](../../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md) records the new local candidate, not independent acceptance. All typed argv/resources preserve subcommand-first prefixes and --sandbox on reads/writes, with actual derived write actor inserted after operation arguments but before any -- terminator. Pre-spawn input/identity/hold/location refusals stay thrown; permission rejection/cancellation remain unchanged and started-write uncertainty survives. Actors derive from actual request/invocation session and agent; audit attribution grants no permission and assertions separately use context.agent. - -Future task7.1 authority must explicitly cover existing install-bd.sh into disposable directories and existing bd-contract.ts once per1.3.0/1.3.1 for runtime JSON/mutation/claim/create/close/prime-dependence facts. The SDK ledger will be a table citing captured existing-contract output; help/source is discovery, not passing evidence. No installation or contract run occurred in this correction. Task7.2 reruns existing scratch executor/catalog probes once against the actual candidate and records exact pin/commands/results here; there is no maintained product executor seam. Product tests assert declared outputs/branch invariants and bounded table/shared negatives. Task7.3 uses four representative capability states plus the existing cheap suite/typecheck/package gates. .6 consumes deterministic evidence and adds its own Stop/handoff observation; installed catalog/executor/model confirmation remains .2/.9. No graph/ownership change, implementation, activation, publication or closure follows. - - -## Historical planning correction — broader code-mode architecture (2026-10-21) - -The [broader Opus assessment](../reviews/opus-code-mode-architecture-wgv.md) and parent pinned-blob verification supersede six-tool sufficiency and the earlier narrow READY. Exact 2.1.1 shell.ts:195 declares native shell codemode:false; tool.ts:236–262 splits direct/code-mode inventories and removes code-mode-only tools when execute is wholly denied. Ordinary shell is a direct model-turn fallback only. Historical direct/code-mode fixture references below describe host hook/permission seams, not proof that the default plugin tools have direct exposure. - -The selected unpublished [active design](../../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md) section 7 targets eleven typed daily-loop operations with declared outputs, actual host-derived actors visible in context/results, request-capability guidance and targeted freshness. Tasks 7.1–7.3 own this new source delta; historical 3.1 and 6.1 acceptance does not cover it. Keep full prime until measured; do not suppress issue-write refresh until supported prime dependence is established. Planned CODE_MODE adds one resource: 16 resources plus ADR, 17 explicit links; prior 16-link package results remain historical measurements. All 30 human commands/overrides and advanced/admin coverage remain. - -The actual actor is derived from the executing session/agent, not a mandatory beads-task-agent identity or delegation topology; permission checks continue using context.agent. Minimum/current Beads remain >=1.3.0 / installed 1.3.1. Unsupported flags, multi-ID show, claim-conflict shapes and prime-state assumptions remain bounded 7.1 checks. Operator 2.0.29 is untouched. The owner-accepted nested plain-decline continuation remains a failed stronger case accepted as a host limitation, not a passing Stop/Cancel test. Existing .2/.6/.9 independently own host, Stop/handoff and installed/model gates. Planning reconciliation only: implementation_authorized=false; no resumed qualification, activation, publication or closure. Earlier source/live records retain their original scope. - -Reviewed on 2026-10-11 for the narrow OpenCode boundary used by the published stable package (`opencode-beads-2zs`). OpenCode 1.x and its `@opencode-ai/plugin` hook API are no longer supported; 0.10.x and earlier target that line. The current source branch separately prepares an opt-in beta/next candidate on the 2.1 line. - -## Versions and sources - -- Historical stable 1.0.2 declarations used optional peer range `@opencode/plugin` `>=2.0.26 <3` and development dependency `2.0.26`. The only import is type-only (`import type { Plugin } from "@opencode/plugin"`), so packages install nothing from OpenCode and use the host's runtime. -- Published beta.5 declarations use optional peer range `@opencode/plugin` `>=2.1.1 <2.2` and development typing dependency `@opencode/plugin` `2.1.1`; exact 2.1.1 has bounded accepted evidence for that artifact. This checkout's 2.0.0 release candidate uses `@opencode/plugin` `>=2.2.6 <2.3` and `2.2.6` for development typing only. Exact OpenCode 2.2.6 qualification is parent-accepted for archive SHA-256 `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`; see [current qualification](../opencode-22-qualification-5rj2.md). The `opencode-beads-o66` deficiency remains unresolved. -- Authoritative sources: the installed `@opencode/plugin` 2.0.26 declarations, the [plugin guide](https://opencode.ai/v2/docs/build/plugins/), the [V1 migration guide](https://opencode.ai/v2/docs/build/plugins/migrate-v1/), [plugin configuration](https://opencode.ai/v2/docs/plugins/), the [skills reference](https://opencode.ai/v2/docs/skills/), the published OpenAPI document (`https://opencode.ai/v2/openapi.json`), and `@opencode/schema` 2.0.26 for event names. -- Qualification: a throwaway V2 plugin (`opencode-beads-2zs.1`) and the actual source plugin were loaded into disposable projects on OpenCode 2.0.26. Results were read with `opencode debug agents`, a JSONL trace from the plugin, and short `opencode run` sessions. Test sessions were deleted afterwards. - -## Plugin shape and loading - -The package default-exports `{ id: "opencode-beads", setup }`, the object `Plugin.define` returns; no runtime import is needed. `setup` returns a cleanup that aborts the event subscription. - -OpenCode resolves a package plugin as `/server`, then ``. The package exports both specifiers to `src/plugin.ts`, and the package smoke test checks both. A configured local plugin must be a directory with an `index` or `server` entry file; a file path is rejected, relative paths resolve from the config file's directory, and a missing entry is skipped without a log line. Files in `.opencode/plugins/` load automatically. - -## Boundary inventory - -| Boundary | Supported contract and decision | -| --- | --- | -| Location | `ctx.location.directory` scopes every `bd` process. The host's `process.cwd()` is the user's home directory, so `bd` is always spawned with an explicit `cwd`. | -| Options | `ctx.options` carries the object form `{ "package": ..., "options": {...} }`. The plugin reads `luna`, `autoMigrate`, and `stealth` as strict booleans, and `refreshAfterIdleMinutes` and `taskAgentSteps` as non-negative numbers; invalid values fall back to defaults. | -| Agents | `ctx.agent.transform(editor => editor.update(id, fn))`. The editor has no `add`; `update` on an unknown ID creates the agent from OpenCode defaults, including the default permission ruleset. User `agents` configuration overrides plugin fields one by one, and the editor does not list configuration-only agents, so V1 collision warnings were dropped. The host appends a `browser` deny rule. | -| Agent permissions and steps | `Agent.Info.permissions` is an ordered rule list where the last match wins, and agent rules apply after base rules. Shell resources match whole command text with `*` and `?`, and compound commands are checked per command. The task agents append `ask` rules for `git commit *`, `git push *`, `bd dolt push *`, `bd dolt pull *`, and `bd sync *`, each paired with a global-options form such as `git * push *`. `tests/agents.test.ts` checks the resulting decisions with a copy of the 2.0.27 matcher (a trailing ` *` also matches nothing). A non-interactive run rejects these (`permission.rejected`). `steps` caps a worker invocation (default 100). | -| Agent lookup | `ctx.agent.get({ agentID })` returns `Agent.Info` with `mode`; it is safe to call inside a session hook (about 1 ms). Subagents are excluded from context; lookup failures fail open. | -| Context | `ctx.session.hook("context", event => event.system.push({ type: "text", text }))` runs before every agent-loop model request with `sessionID` and `agent`. Pushed parts reach the model, are not stored in history, and survive compaction. Subagents launched through the `subagent` tool run in child sessions with their own `sessionID` and also pass through this hook. Compaction requests use the separate `compaction` hook; the plugin registers it only to add Beads state-preservation guidance for sessions that had Beads context. While prime is attached, bd's full-profile and Codex `AGENTS.md` blocks in the system text are replaced with a pointer (request only). | -| Events | `ctx.event.subscribe({ signal })` yields `{ type, data }`. The plugin uses `session.compaction.ended` (invalidate cached prime) and `session.deleted` (drop session state), both with `data.sessionID`. A manual compaction emitted `session.compaction.ended`, not `session.compacted`. | -| Diagnostics | V2 has no plugin log API. Rate-limited `console.warn` lines prefixed `[opencode-beads]` are emitted, and their failures never affect requests. | -| Shell | There is no `$` helper in V2. Bounded process lifecycle control uses `Bun.spawn(["bd", "prime"], { cwd, ... })` through a shared `runBd` runner with timeout and process-group cleanup; `node:child_process` also works in the host. | - -## Commands and skills - -V2 plugin commands are executable (`execute` calls `ctx.session.prompt`). Separately, native [Markdown and JSON commands](https://opencode.ai/v2/docs/commands/) support prompt templates, description metadata and argument substitution. The [full integration analysis](../claude-code-integration-analysis.md) pins current source and records the remaining minimum-host qualification; command retirement was not forced by an absence of V2 prompt templates. Plugin-provided skills need a `path`. The vendored `/beads:*` templates were retired instead of ported (`opencode-beads-2zs.4`). OpenCode V2 discovers the canonical `.agents/skills/beads` skill installed by `bd init` natively, and users can load it with `@beads`. - -## Compatibility decisions for the historical stable 1.0.2 baseline - -The supported line begins at OpenCode 2.0.26, the first version qualified. There is no V1 fallback or dual export: V2 ignores V1 `server()` exports, and supporting both would mean maintaining two hook implementations. Tests fake only the small context slice the plugin uses (`location`, `options`, `event`, `agent.get`, `agent.transform`, `session.hook`) so behavior can be checked without the host. - -When running `opencode run` from a non-interactive shell during qualification, close stdin (`< /dev/null`); otherwise the CLI waits indefinitely, which looks like a hang. - -## Selected beta/next boundary (not yet qualified) - -The [reconciled design](../../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md) selects N1 on OpenCode `>=2.1.1 <2.2`, released source `ba546ec1598a70db2570e9c6258028d955ba8f58`. The package now declares that optional peer range and pins development types to exact `@opencode/plugin` `2.1.1`; the import remains type-only. The host context's existing `ctx.app.version` field is used to report an unsupported-host diagnostic and skip agent/hook registration outside that range. This source guard and the published declarations do not constitute runtime qualification: exact 2.1.1 remains untested, and future 2.1 patches are admitted candidates subject to checks rather than tested versions. The 2.0.26 runtime evidence above remains historical and does not qualify N1. No stable package version, consumer pin, or host runtime was changed. - -Required acceptance covers typed-tool `options.permission: shell` filtering, actual invocation agent in assertions, canonical fixed-operation resources, `save: []` without new broad saved grants, external-directory/location equivalence, holds and cancellation. Command schema/registry accepts string names including the selected `oc-beads:` namespace; installed UI/dispatch still needs qualification. Compaction only carries acknowledged references and known gaps, never a pending-write queue or same-runner checkpoint. Package assets/registrations/disposal and blocking-child stop races need their own fixtures and installed-host checks. N0 is a historical alternative, not an automatic fallback. - -Final review B1 sequencing: task 1.2 prepares the 2.1.1 development types before 1.1’s minimal throwaway host tool/command probes. Current 2.0.26 types lack permission.assert. Adapter-specific fixtures remain in 3.1; fake contexts cannot qualify host filtering or dispatch. Live gates 1.1/4.2/6.2 require a pinned isolated disposable host, initially 2.1.1 within `>=2.1.1 <2.2`, and later authority to provide/install it. The image CLI package currently reads 2.0.29; the older qualified 2.0.26 results above are historical. Neither qualifies N1, and neither runtime is upgraded by this plan. Missing live prerequisites block live acceptance, not independent source/fixture work. - -Expected approval outcomes: `save: []` installs no new saved rule even for “always”; repeated ask prompts are intentional and must be explained. Existing shell `bd *` grants can authorize equivalent typed operations, subject to configured denies; do not broaden scope for convenience. Installed acceptance also checks all 16 explicit resource links under external-directory ask/deny and initial/rebuilt command preservation. The native assessment records config transforms replaying after package transforms, while retaining the bounded public-API collision gate. - -The [2.1.1 delta](../opencode-2.1.1-contract-delta.md) governs relevant fixture migration: SessionCompactionResult.native, metadata.keepID/legacy metadata.recent, fork remapping and native.messages replacement semantics. Keep reference-only hooks; no replacement result or replay window. Tool state/UI metadata are not renamed. Current lifecycle events replace any obsolete session.compacted assumption. Released paginated session.list is unnecessary for known-session recovery. Historical 2.0.32 source evidence remains separate; future admitted 2.1 patches are not claimed tested, and 2.2+ requires another explicit contract review. - -## Task 3.1/3.2 accepted source and separate activation boundary - -Parent acceptance: reviewed the complete source/fixture candidate against `f4dddb31eb31cc7b61fb381a5a8740c427be64ba` and the owner-corrected CLI responsibility boundary. Standards and spec review found no remaining material source issue. Independently executed 133 tests (0 failures), typecheck, package smoke, strict change validation and whitespace checks. This accepts tasks 3.1/3.2 source only; it does not qualify native host permissions, model behavior or production activation. The execution record `opencode-beads-vuy.4` holds the resulting publication identity. Historical review findings retain their original verdicts; this is parent acceptance of the corrected implementation, not a new independent-review verdict. - -`src/continuity.ts` defines only checkpoint/show/memories/recall/remember, with direct argv, shell-filtering metadata, actual invocation agent/session/message/call assertions and `save: []`. The normal adapter uses `runBd`; tests override that runner and public host methods, without a separate execution implementation. Actor/cwd/env/force/administration are not model inputs. Matching CLI payloads establish acknowledgement; interrupted or malformed writes remain uncertain with no retry. Memory results retain failed/indeterminate commit fields, and missing-key stdout on a nonzero exit is distinguished from an empty found value. Tests establish plugin-side behavior only. - -**Attribution correction after targeted review:** exact 2.1.1 [core/tool.ts](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool.ts) lines 264–270 supplies invocation sessionID and agent, independently of model input. These primitives suffice for audit attribution: `opencode::<12-hex-digest>` uses a bounded agent label and SHA-256 of full sessionID, NUL, and full agent ID. The same invocation session/executor keeps its actor across calls; another session or executor has a different actor. Permission evaluation continues to use actual `context.agent`. Missing invocation identity refuses execution; there is no human Git fallback, model actor parameter, external actor-field requirement or identity service. Attribution is not authentication and never changes assignee: deliberate handoffs still require separately authorized ownership changes and evidence. The earlier actor blocker was overstated. - -**No-open guard correction:** the parent verified the cached `where.go`, `routed.go` and `main.go` Git blobs against the pinned Beads 1.3.1 tree at **c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c**. The earlier unknown-source-identity statement was incorrect. [where.go](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/where.go) lines 87–98 can open storage to recover a missing prefix. The shared automatic guard and typed adapter now use `bd context --json`, not `where`. Installed `context --help` documents configuration-only diagnostics; pinned [main.go](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/main.go) skips its store initialization, [context_cmd.go](https://github.com/gastownhall/beads/blob/c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c/cmd/bd/context_cmd.go) reads configuration, and the proxied variant uses the filesystem context provider. The guard checks `.local_version` under the reported `beads_dir` as before. An unsupported or failed context probe produces an explicit `probe-failed` hold, not silent absence or unsafe fallback. No shadow configuration, environment clearing, alternate database, bootstrap or server was introduced. Help and pinned source were sufficient; no disposable datastore or project-store experiment was needed. - -**Operative owner correction — upstream responsibility:** normal supported Beads routing, including fallback after a local miss, is CLI-owned behavior rather than an observed defect. The owner explicitly withdrew the earlier final-store confinement prerequisite and upstream routing-disable remedy. Checkpoint/show now invoke the installed CLI normally from the actual session/project cwd; no final-store attestation, route-disable flag, backend restriction, local metadata/resolver clone or upstream repair framework is introduced. The plugin does not clear inherited routing environment or claim runtime shell/plugin confinement of internal CLI accesses. Historical review reports and Beads notes remain evidence of prior interpretations, not current authority. - -The adapter's boundary is correct invocation context, exact-operation OpenCode shell permission using actual agent/session/message/call identity, `save: []`, external-directory checks for explicit invocation/location access, executor attribution, cancellation, the existing migration guard and honest outcomes. Session/location and guard are checked again after approval and before spawn. External-directory checks concern the explicit lexical/resolved cwd against host workspace/project roots; internal CLI redirects, backend selection and routing are not additional plugin targets. The guard uses supported `bd context --json` to obtain `beads_dir`; it does not decode or snapshot backend metadata/routes. CLI errors remain visible, ambiguous append/remember outcomes are not retried, and memory acknowledgement does not promise database consistency repair or plugin-issued commits. - -**Source versus activation:** one adapter implementation uses the normal `runBd` default; tests override dependencies only. Ordinary `setupBeads` registers no continuity tools before successful live 1.1. The internal `continuityQualified` dependency lets tests exercise that same registration path, without a permanent user activation option or a qualification claim. Source fixtures cover all five requested operations, explicit actor/permission identities, direct argv, denial, location access, guard/cancellation after approval, acknowledgement distinctions and normal inherited routing/backend choice. They do not emulate upstream routing or qualify live host behavior. No source blocker for intended CLI routing remains; parent acceptance and live qualification/activation are separate. - -Context now records missing/withheld/failed/empty/ready states separately, aborts invalidated loads, and refreshes at relevant execution/compaction/model/agent transitions. Guard failures diagnose `guard_failed` and prohibit manual bypass. Write acknowledgements dirty location caches; generic tool failures and child returns supply focused recovery cues without extracting memory or parsing shell text. Session get returns session info directly, whose public location exposes directory, not workspaceID. When available on the host/test slice it checks that directory before supplying context; move/fork/delete discard local references and caches. No private workspace identity is inferred from the public response. Cleanup aborts owned processes/observers and disposes owned registrations, with no final-write guarantee. Only complete instruction bodies demonstrably present in supplied context are reduced; customized local policy survives managed markers. - -Compaction hooks append reference/gap guidance only: no Beads call, permission wait, queued persistence, recursive prompt, replacement result or `native.messages` injection. Fixtures assert that supplied summary/native results, `metadata.keepID`, legacy `metadata.recent`, fork-remapped references and changed provider/model fields remain untouched. They do not execute or prove the host's replay/fork/mismatch behavior; the pinned 2.1.1 host owns compatibility and replay, including the fact that `native.messages` replaces summary replay. Direct/code-mode acknowledgement is handled only inside typed execution; the outer `execute` hook never repeats it. Live filtering, deny/grant precedence, repeat approval prompts, external access, stop races and replay remain unexecuted qualification/acceptance work. - - -## Tasks 2.2/3.3 source candidate: native registration and diagnostics - -Parent source acceptance: the corrected implementation resolves the original Opus plan findings without claiming a new reviewer READY verdict. Parent inspected ordinary registration/status, per-rebuild customization checks, packed delivery and lifecycle changes against baseline `38206ff428838e0290b6d2bb3db5ddc7b7beb9d4`, and independently executed 150 tests (0 failures), typecheck, package smoke, strict global OpenSpec and whitespace checks. Packed smoke invokes all 30 native bodies and verifies owned disposal. This accepts tasks 2.2/3.3 source/package/fixtures only; live 1.1/6.2 and privileged continuity activation remain unexecuted. Bead `opencode-beads-vuy.5` holds publication identity and limitations. - -`src/workflows.ts` supplies native Promise `CommandDefinition` bodies for exactly the selected inventory's 29 stems plus `oc-beads:status`. One ordinary command transform registers every definition, checks abort before adds and retains its owned disposer. Initial `command.list()` collisions or lookup failures are diagnostic-only: they do not suppress registration. Bodies submit normal `session.prompt` requests with literal user text, `files`, `agents`, `skills` and `delivery` (`queue`/`steer`), without Claude template evaluation, shell interpolation, permission escalation or synthetic continuation. Typed privileged continuity remains withheld pending separate live 1.1; registering prompt commands does not activate it. - -The pinned [Promise command declarations](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/command.ts) expose a synchronous add-only transform. [Core command](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/command.ts) uses map set; [state rebuild](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/state.ts) replays transforms in order. Pinned 2.1.1 `plugin/supervisor.ts:99–103` orders pre → packages → post, and `plugin/internal.ts:254–259` places ConfigCommandPlugin in post. Its single transform replays refreshed configuration/file commands after package transforms on initial load and config rebuild; removing an override restores our definition. Same-name conflicts with other plugin transforms use normal native ordering and may replace an earlier entry. The package neither promises universal collision prevention nor edits user files or host configuration. - -The original [Opus resolution review](../reviews/opus-registration-resolution-review-vuy5.md) additionally inspected suffix reactivation in the **unpinned** `released` cache because that registry file was absent from `baseline211`. That detail is not pinned 2.1.1 evidence or live qualification. The report retains its original REVISE verdict; this correction is not a second independent review. Installed reactivation/discovery and permissions remain separate unexecuted acceptance work. - -The registered status body reuses the existing context controller, persistence gaps and config-only guard. It reports actual registration completion, effective public command names/descriptions, missing expected names, description mismatches and lookup failures. A mismatch is observable evidence of a different effective definition, not owner proof. Public owner identity and identical-description overrides are unavailable; matching names/descriptions do not prove ownership. A failed lookup reports unknown effective entries and does not invent missing names or override findings. Context distinguishes missing, withheld, failed, empty and ready; an in-progress load or unknown session location is explicitly uncertain. Unconfirmed location withholds the probe and discards stale session references. Status never runs prime or a store-opening diagnostic, claims a final write, or reports live qualification from fixture results. - -Skill registration always installs the public transform when packaged guidance is readable; the candidate editor's list is checked on every rebuild for a colliding ID/name. There is no initial list collision/unavailability gate. A removed customization therefore allows restoration through native rebuild, while later config transforms keep their precedence. Abort guards and the owned disposer apply to the skill as well. Missing/unreadable packaged guidance is diagnosed without filesystem exception details; accepted asset bodies remain unchanged. - -Package smoke resolves both existing exports, compares the unpacked inventory/resource bytes, resolves all 16 explicit links from the installed base and checks a missing installed file. It invokes the actual registration callbacks, verifies all 30 native definitions, executes their prompt bodies with attachments/delivery, and derives the five owned disposers from agent/skill/command registration plus the two registered hooks. Focused fixtures replay a small ordered list of package/config callbacks to check overrides, restoration and owned removal; they do not clone host internals. - -The host-owned 2.1.1 [skill scan](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/config/plugin/skill-scan.ts) stops at depth six, skips hidden/ignored directories and stops descending when SKILL.md is found. [Resource preparation](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/skill.ts) applies ignore globs and samples only ten files; [config skill watches](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/config/plugin/skill.ts) watch out-of-root resolved files specifically. Fixtures load explicit assets below hidden/ignored node_modules paths deeper than six levels without emulating scanners/watchers. Explicit package registration and all 16 links do not imply recursive discovery or resource watches. No package watcher is added. External-directory ask/deny, model use and installed namespace dispatch remain unexecuted live 1.1/6.2 checks. - -Cleanup is awaitable and idempotent: abort context loads/processes and the event subscription immediately, clear session/location references, then await every owned disposer and observer. Disposal failures are reported; a later setup failure releases earlier registrations. Fixtures include command/skill abort guards, native status cancellation, user config preservation and late-context suppression. They establish source/package obligations, not live unload behavior or a final durable write. Source task markers, acceptance and release/activation state remain parent-owned. - -## Task 1.1 exact released-host observations — 2026-10-21 - -This append records new measurements; preceding source acceptances and historical unexecuted statements retain their original scope. **Task 1.1 is not qualified:** exact 2.1.1 code-mode explicit decline loses the distinct abort outcome. The [qualification record](../opencode-host-qualification-vuy2.md) supplies identities, per-case results, reproduction, sanitized traces and cleanup. Actor `codex:oc-host`, actual worker session `01a15c62-d106-7e80-af58-5a47b1032cd4`, repository baseline `072429f1a7723ade23e756a921924d9d0acacf31`. - -The official `@opencode/cli-linux-x64-baseline@2.1.1` tarball passed published SRI/SHA-1 and registry-signature checks; extracted executable SHA-256 `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9` reports `opencode v2.1.1`. Official tag/source pin remains `ba546ec1598a70db2570e9c6258028d955ba8f58`. The real host ran only on loopback with separate HOME/XDG and an initially committed scratch repository under `/opt/data/cache/scratch/vuy2-oc-host`. A controlled local HTTP/SSE provider fixture drove minimal throwaway tools/commands through native host execution; no production adapter, mock host, external-provider/model acceptance or project Beads probe was used. - -**Passed measured contracts:** whole-shell denial removes direct and code-mode probes from actual model inventories; selective denial leaves discovery intact and blocks the forbidden resource. Assertions carry actual invoking identity, including an original restrictive invocation after the live session default was switched to an allowing agent. Allow/ask and correction feedback propagate without rejected-target execution/retry. `save: []` plus “always” leaves the saved list empty and asks again. Fixture-owned shell `bd *` grants authorize equivalent typed operations and a harmless native-shell stub; configured denies still win. Native grant edits/revocation are re-evaluated, including within one unchanged live session. Native shell and typed probes request the same explicit external-directory and shell resources and execute `pwd` in the same approved cwd; external correction/deny prevents target execution. The real command registry admits and invokes exact `oc-beads:ready` with literal arguments and queue delivery. - -**Failed measured contract:** direct explicit decline yields `Permission.DeclinedError`, an aborted native tool/step and no next provider request. In code mode the same rethrown leaf outcome becomes outer `execute` completion with inner error metadata and generic `Tool.Error` text, followed by another provider request. The target does not execute or retry, and `metadata.error: true` must not be mistaken for target success; nevertheless the distinct decline/abort outcome is lost. Evidence: session `ses_ea396cc6affenEp6WisS1KyHef`, message `msg_15c6933a4001vwxlp9uhAKg3TG`, call `vuy2_declined-code`, `cases.jsonl`, `plugin.jsonl`, provider traces and native message readback. This conflicts with the selected preserved-outcome guarantee and the plain-rejection step-ending contract in the pinned Promise permission declaration. The affected path stopped; no upstream/product patch, translator, fallback or activation follows. Parent/owner disposition and subsequently passing authorized host evidence remain required. - -All owned host/provider processes and listeners were stopped; operator 2.0.29 executable/configuration hashes match the pre-provisioning record. `.2` remains open for parent review. No task markers, `continuityQualified`, installed-package/model acceptance, child qualification, publication or source acceptance were changed. - -## Superseding owner decision: retain code mode and accept bounded continuation - -The owner accepted the observed OpenCode 2.1.1 code-mode plain-decline continuation limitation while retaining composition. The failed stronger whole-step-termination case above remains failed historical evidence, now a known accepted host limitation; it is not relabeled as passed. The adapter must still propagate assertion rejection unchanged, preserve correction feedback, never execute the rejected target or automatically retry it, and never acknowledge target success. Later operations retain independent permissions. Explicit Stop/Cancel, scope and honest persistence guarantees are not waived. - -Remaining qualification/activation is paused for parent review of the broader code-mode planning reconciliation in `opencode-beads-wgv`, with new source tasks 7.1–7.3. An isolated pinned-host-executor reproduction of our undeclared output-schema defect is recorded under `/opt/data/cache/scratch/opencode-codemode-shape-review/`; this is fixture evidence, not installed-product/model acceptance, and the defect is NOT covered by the upstream limitation acceptance. Task 1.1 remains unchecked pending parent reconciliation. No product source, activation, public filing, publication or operator change follows from this decision. diff --git a/docs/integrated-acceptance-vuy8.md b/docs/integrated-acceptance-vuy8.md deleted file mode 100644 index 5ea061b..0000000 --- a/docs/integrated-acceptance-vuy8.md +++ /dev/null @@ -1,370 +0,0 @@ -# Task 6.1 qualification candidate — 2026-10-21 - -**Final parent verification: task 6.1 accepted locally.** Both response-handling -corrections, the deterministic/package checks and the installed-Beads CLI contract -pass. The candidate and acceptance marker remain uncommitted/unpublished; `.8` -stays open for publication/closeout. Live OpenCode qualification is unexecuted. -Earlier incomplete results below are retained as historical phases, not the -current verdict. - -**Hold-retirement disposition (historical phase):** Matt confirmed the Docker Lab-only ancestor hold -was obsolete after the completed Beads 1.3.1 migration and authorized retiring it -and its guidance. Parent removed the exact `/opt/data/cache/MIGRATION-FREEZE` -marker and verified its absence; no command-scoped bypass or replacement marker -was introduced. No separate matching active AGENTS.md/SKILL.md guidance was found. -The freeze failures recorded below are historical evidence, not a current hold. -Removal custody is `/opt/data/cache/scratch/vuy8-retired-freeze-removal.json`. -The guard-classification mismatch remains unresolved, append/memory checks have -not been rerun, and 6.1 remains unchecked. This cleanup does not authorize a guard -source edit, another worker, live host/model work, publication or activation. - -## Identity and consumed evidence - -- Executor `codex:oc-integration`; full Codex session - `01a15c16-2bc1-7841-8289-0cf74b40090b` (environment-provided). Requested route: - `gpt-6.1-sol`, reasoning `high`; no independent model-route attestation made. -- Candidate baseline HEAD `c7d2129584365764b2ea65d50007244cebeb1f6a`, branch - `openspec/improve-beads-workflow-parity`, plus the parent-owned protected local - planning refinements and this worker's two paths below. -- `.8` atomically claimed with - `BEADS_ACTOR=codex:oc-integration bd --sandbox update opencode-beads-vuy.8 --claim --json`. - Readback: `status=in_progress`, `assignee=codex:oc-integration`, - `created_by=unknown`, account/record `owner` absent. Heartbeat's `owner` is the - lease holder, not a stored account-owner observation. -- Consumed `.6`'s explicit `deterministic_contribution_accepted=true` at - `a5d6b2bea779259ba9aa3175ab86fb2f4f2b862b`, evidence - [native assessment](opencode-native-parity-assessment.md), - [Opus READY review](reviews/opus-flow-source-review-vuy6.md), and parent-verified - 160-test/typecheck/package results. Its nested historical `not_started` field - does not replace that acceptance. No `.6` write or repeated independent review. - Source/assets, host/flow/guidance/continuity fixtures, package declarations, - lockfile and package script compare unchanged against that revision (exit 0; - `/opt/data/cache/scratch/vuy8-consumed-source-diff.log`). The additional current - tests include the separately accepted `.7` upstream comparison work. -- Actual CLI: `/usr/local/bin/bd`, - `bd version 1.3.1 (c1c4b642a: HEAD@c1c4b642ac1c)`; - executable SHA-256 `a8f48d771b9e11eccfced4aed72923b59eda746f7a9b425e7ca1af7a51251653`. - Full source pin `c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c` from the cached - release tree; downloaded `memory.go`/`admin.go` at that commit match the cache. -- Bun **1.3.14**, existing cached baseline binary. OpenCode **2.1.1**, source - `ba546ec1598a70db2570e9c6258028d955ba8f58`, is only the source/type target; - admission `>=2.1.1 <2.2`. No OpenCode command was run. - -## Commands and actual results - -All logs below are in `/opt/data/cache/scratch/`. The successful Bun route and -both real-contract attempts used this command-scoped environment: - -```sh -TMPDIR=/opt/data/cache/scratch BEADS_ACTOR=codex:oc-integration \ -PATH=/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin:$PATH \ -bun -``` - -| Arguments / command | Exit | Result / log | -| --- | --- | --- | -| `bun run test:bd-contract` via the requested npm wrapper, before edits | 1 | Did not reach checks: cached wrapper says Bun postinstall was not run; `vuy8-contract-baseline.log` | -| `run test:bd-contract`, original script, cached baseline Bun | 1 | 7 failed checks; `vuy8-contract-baseline-cached-bun.log` | -| `run test:bd-contract`, diagnostic candidate | 1 | 7 failed checks including dependent assertions; `vuy8-contract-diagnostic.log` | -| `test` | 0 | **166 pass, 0 fail**, 1,245 assertions, 12 files; `vuy8-tests.log` | -| `run typecheck` | 0 | `tsc --noEmit`; `vuy8-typecheck.log` | -| `run test:package` | 0 | Packed consumer/import/callback/resource checks; `vuy8-package.log` | -| `openspec validate improve-beads-workflow-parity --strict --no-interactive` | 0 | `vuy8-openspec-change.log` | -| `openspec validate --all --strict --no-interactive` | 0 | 1 passed, 0 failed; `vuy8-openspec-all.log` | -| `python3 docs/validate-parity-planning.py /opt/data/cache/scratch/parity-sources` | 0 | All seven validation groups pass; `vuy8-planning.log` | -| `git diff --check` | 0 | `vuy8-diff-check.log` | - -The first command was exactly -`TMPDIR=/opt/data/cache/scratch BEADS_ACTOR=codex:oc-integration npm exec --yes --package=bun@1.3.14 -- bun run test:bd-contract`. -The cached optimized x64 binary also raised SIGILL on `--version`; the existing -baseline binary returned `1.3.14` and ran the checks. No runtime install, -postinstall repair or upgrade was performed. - -Package identity: `@snarkipus/opencode-beads@1.0.2`, archive -`snarkipus-opencode-beads-1.0.2.tgz`, SHA-256 -`51f0d2ab294e1b23f90bec424ba479fa2162cef621b47e161743eb4d652d8cb1`. -The existing package script deleted its temporary archive/consumer after checking -both exports, all 30 commands, 16 resource links and owned fixture disposal. -This is fixture/package evidence, not installed-host activation. - -## Failures, correction and stop boundary - -1. In the script's disposable repository with no workspace, - `bd --sandbox --actor codex:oc-integration context --json` exits **1** with - `{"error":"cannot resolve repo context: no .beads directory found","schema_version":1}`. - The production guard returns `probe-failed`; the existing contract requires - `uninitialized`. That assertion remains failing. Resolving this distinction - needs parent disposition and potentially production-source authority; no guard - edit, fallback probe or weaker passing assertion was introduced. -2. Disposable `create` and `migrate schema` exit **14** because - `/opt/data/cache/MIGRATION-FREEZE` says: - “Docker Lab-only migration: all other workspaces/stores remain held; do not - migrate or remove without separate approval. docker-lab-3dpc.3”. - The hold is intact. No `BD_MIGRATION_FREEZE_FILE` override, removal, force or - repair was attempted. Fresh disposable init/setup/prime checks did execute; - issue creation, claim/close and schema-refresh outcomes remain unqualified. -3. One stale script assertion called `minimizeBeadsInstructions` without supplied - context and expected deletion by marker alone. The accepted implementation - intentionally retains unique policy. The candidate now checks exact retention - without context and actual replacement with the complete duplicate body - supplied. Both checks pass; this preserves and strengthens the real checks. - -Stopped affected qualification after confirming the guard mismatch and the hold. -No append-retention or memory mutation extension was qualified, and none is -reported as passing. Pinned 1.3.1 source inspection shows remember JSON exposes -`key`, `value`, `action`, without `committed`, `commit_error` or -`commit_indeterminate`; recall renders `found` as `value != ""` and exits 1 for -an empty value. A real found-empty distinction and failed/indeterminate commit -fields were therefore **not observed** on this release. Existing adapter fixtures -cover those shapes separately; no empty store injection, synthetic live result, -unsupported flag or demand for marketplace-main outcomes was added. - -Current help advertises `admin cleanup`, `admin compact`, `admin reset`; -top-level `compact` squashes Dolt history and directs semantic issue compaction -to `admin compact`. Existing packaged guidance asks for current help and explicit -administrative authority. Only help/source were inspected, with no administrative -mutation or backend expansion. CLI routing/database/consistency remain upstream -responsibilities; this qualification introduces no product confinement promise. - -## Candidate custody and remaining acceptance - -Worker changes only: - -- `scripts/bd-contract.ts`: explicit command actor and `--sandbox` for test CLI - calls; actual stdout/stderr failure diagnostics and observed guard kind; correct - supplied-context minimization checks. Existing disposable HOME/root re-exec and - cleanup remain in use. Successful test setup writes use disposable fixture Git - identity, never the human Git identity. -- `docs/integrated-acceptance-vuy8.md`: this evidence and stop report. - -Five protected paths were checked against the supplied SHA-256 manifest before -and after work; all match. Exact readback is -`/opt/data/cache/scratch/vuy8-protected-final.json`. The separately observed -untracked `.claude/settings.local.json` was untouched. No production source, -dependencies, versions, OpenSpec markers or prior review reports changed. - -The worker left `.8` in progress under `codex:oc-integration` for parent review. -Parent subsequently classified it blocked on the two items below, preserving -worker assignment and history. **6.1 is unchecked and incomplete.** Live **1.1, -4.2 and 6.2 remain UNEXECUTED**, including permission correction/decline and the -installed unload/reactivate case. Model behavior, external-directory approvals, -real child delivery and host lifecycle were not evaluated. No installation or -activation, extra agent, staging/commit/push, publication, Dolt remote sync or -closure occurred. Parent owns acceptance and any separately scoped next step. - -## Parent review — incomplete acceptance - -Snarkimedes inspected the complete script diff, the failed CLI-contract log, -the actual freeze marker and production guard source, and verified all five -protected planning/report hashes. The script changes are limited to test actor -attribution/sandboxing, diagnostics and the supplied-context assertion correction; -no production-source change or freeze bypass was made. - -Parent independently ran the existing cached baseline Bun 1.3.14 with its -containing directory on PATH: **166 tests pass, 0 fail**, typecheck passes, and -package smoke passes. Logs are `vuy8-parent-tests.log`, -`vuy8-parent-package.log` under the scratch directory; typecheck returned exit 0 -in the parent tool output. An earlier direct-binary test invocation without Bun -on PATH failed a subprocess lookup; that distinct invocation is preserved in -`vuy8-parent-tests-direct-binary.log`, not represented as a product defect or a -passing run. The worker's requested model/reasoning route was independently -verified in the parent-captured Codex startup banner as gpt-6.1-sol/high. - -A parent-created disposable Git repository with an isolated HOME and no -BEADS_DIR reproduced the exit-1 no-workspace JSON response exactly; the observed -result is retained in `vuy8-parent-context.json`. The guard catches this supported -CLI absence response as `probe-failed`, so the uninitialized-workspace contract -fails. This is our classification mismatch, not broken upstream behavior to -repair. Initial parent probes without a Git boundary instead discovered ancestor -workspace configuration and were not used as this reproduction evidence. - -The ancestor `/opt/data/cache/MIGRATION-FREEZE` explicitly holds other workspaces -and still blocks disposable create/migrate writes. Parent did not rerun the -already-demonstrated blocked mutation path, remove the marker, redirect its check -or weaken the contract assertion. Source inspection of memory output is not -append/memory execution evidence. - -**Disposition:** retain the candidate as partial, leave task 6.1 unchecked and -`.8` blocked. Completing it needs a bounded authorization for our guard's known -no-workspace result handling and authority to run only disposable fixture writes -despite the ancestor hold (or an owner-authorized disposition of that hold). -Do not reopen upstream storage/routing semantics, install a newer CLI, construct -unsupported memory outcomes, or start live host/model acceptance. - -## Resumed phase — authorized guard correction and disposable CLI checks - -**Current result: incomplete; stopped on a new memory-list acknowledgement -mismatch.** Matt authorized the narrow guard correction and disposable rerun in -the same Codex session/actor. This authority supersedes the earlier guard-edit -restriction; the parent review and failed runs above remain historical evidence. -The retired ancestor hold remains absent, with no replacement or bypass. `.8` -was read as blocked/assigned to `codex:oc-integration`, transitioned with -`bd --sandbox --actor codex:oc-integration update opencode-beads-vuy.8 --if-assignee codex:oc-integration --if-status blocked --status in_progress --json`, -then read back in progress with the same assignee, historical `created_by=unknown` -and absent record/account owner. Readbacks are `vuy8-resume-transition.json` and -`vuy8-resumed-readback.json` under the existing scratch directory. - -### Regression and guard correction - -First added a regression using the runner's actual `PrimeProcessError`: exit 1, -empty stderr and stdout -`{"error":"cannot resolve repo context: no .beads directory found","schema_version":1}`. -Focused **RED**: 15 pass, 1 fail, exit 1; the expected uninitialized result was -probe-failed (`vuy8-resume-guard-red.log`). Only afterward, changed -`probeBeadsWorkspace` to recognize that exact error text/schema on exit 1 from -`PrimeProcessError`. It returns absence without marker/store reads or fallback. -Other errors still fail the probe. The negative regression covers an unrelated -exit-1 error, a different exit code, unsupported error schema and interruption; -existing malformed/unsupported context tests remain. Focused **GREEN**: 16 pass, -0 fail, 52 assertions, exit 0 (`vuy8-resume-guard-green.log`). The real CLI -no-workspace guard check now passes too. - -### Actual CLI results and newly demonstrated blocker - -The existing disposable HOME/root re-exec was retained. Every test CLI invocation -carries `--sandbox --actor codex:oc-integration`; no project tracker was used for -fixture operations. Append acknowledges and fresh show retains the exact prior -notes plus newline-separated multiline checkpoint, including literal shell-like -text. Created audit author and claimed assignee match the explicit executor. -Disposable create/claim/discovered-from/close and schema-refresh checks now pass. - -Installed **bd 1.3.1 (c1c4b642a: HEAD@c1c4b642ac1c)** actually returned: - -- Empty remember: exit 1, JSON `error="memory content cannot be empty"`, - `schema_version=1`; no empty memory is created. -- Recall of both the rejected-empty key and an absent key: exit 1, JSON contains - the requested key, `value=""`, `found=false`, `schema_version=1`. -- Remember and same-key update: exit 0, exact multiline value, explicit key, - actions `remembered`/`updated`, and `schema_version=1`. A separate recall finds - the exact stored content with `found=true`. -- **Empty list and no-match search:** exit 0, `{"schema_version":1}`. - **List and matching search:** exit 0, an object containing the exact updated - memory value plus numeric `schema_version:1`. - -The last shape is a genuine **plugin acknowledgement mismatch**, not an upstream -defect: `src/continuity.ts`'s memories branch requires every object value to be a -string. The installed CLI's numeric metadata therefore makes even successful -empty/populated lists fail that branch. The four raw-map contract expectations -remain failing; they are not weakened by deleting metadata only inside the test. -The first extended run (`vuy8-resume-contract.log`) and a diagnostic-only rerun -in another fresh disposable root (`vuy8-resume-contract-evidence.log`) both exit -1. The latter records exact JSON: **36 checks pass, 4 fail**, all four failures -are this list/search shape. Source tracing establishes the adapter consequence; -no installed OpenCode tool invocation or model behavior was tested. - -Stopped on that newly demonstrated blocker. Correcting the acknowledgement and -its fixtures would require `src/continuity.ts`/`tests/continuity.test.ts`, outside -the authorized paths. Neither was edited; no upstream repair, new harness or -backend restriction was introduced. Empty-found and failed/indeterminate commit -fields are still not fabricated: this release refuses empty writes, and its -observed remember JSON has no commit outcome fields. Existing adapter fixtures -for richer outcomes remain unchanged and pass. No admin experiment was run. - -### Consolidated current candidate checks - -All commands used the verified cached baseline Bun on PATH, `TMPDIR` and explicit -test actor exactly as in the earlier environment block; no wrapper repair, -runtime/CLI install or upgrade occurred. Logs below are all in -`/opt/data/cache/scratch/` and preserve earlier runs under their original names. - -| Command | Exit | Current evidence | -| --- | --- | --- | -| `bun test` | 0 | **168 pass, 0 fail**, 1,260 assertions, 12 files; `vuy8-resume-tests.log` | -| `bun run typecheck` | 0 | `vuy8-resume-typecheck.log` | -| `bun run test:package` | 0 | `vuy8-resume-package.log` | -| `bun run test:bd-contract` | 1 | First extended run and diagnostic rerun described above | -| `openspec validate improve-beads-workflow-parity --strict --no-interactive` | 0 | `vuy8-resume-openspec-change.log` | -| `openspec validate --all --strict --no-interactive` | 0 | 1 passed, 0 failed; `vuy8-resume-openspec-all.log` | -| `python3 docs/validate-parity-planning.py /opt/data/cache/scratch/parity-sources` | 0 | Seven groups pass; `vuy8-resume-planning.log` | -| `git diff --check` | 0 | `vuy8-resume-diff-check.log` | - -Current package: `@snarkipus/opencode-beads@1.0.2`, -`snarkipus-opencode-beads-1.0.2.tgz`, SHA-256 -`d7f32c76f1b9abcfe788a1362bbaea325faf51f460fd3fe055f16e64074eb8d7`. -The archive/consumer were cleaned up by the existing smoke script. Its changed -identity reflects the guard source correction; no version or publication changed. - -### Source relationship, custody and parent handoff - -The original `.6` acceptance/review remains immutable at -`a5d6b2bea779259ba9aa3175ab86fb2f4f2b862b`; it did **not** review this new guard -correction. `src/guard.ts` is now the sole production-source difference against -that revision. The current full suite reran the relevant host/guard/flow, -guidance/agent and continuity fixtures, plus package/type checks. Those passing -fixtures do not supersede the real CLI failure or establish live acceptance. -No `.6` ownership, metadata or acceptance record was changed. - -Total worker paths are now exactly `src/guard.ts`, `tests/guard.test.ts`, -`scripts/bd-contract.ts`, and `docs/integrated-acceptance-vuy8.md`. The five -protected paths still match the supplied manifest; custody is -`vuy8-resume-protected-final.json`. The previous report including parent edits -was retained as an exact byte prefix (snapshot `vuy8-resume-prior-evidence.md`, -SHA-256 `371afa8e1f35a9df4d3fc37eb661684528934cb23c180342d2d4ea59d6024f00`). -Current four-path hashes are in `vuy8-resume-candidate-manifest.json`. - -`.8` remains open/in progress under the same executor with a final evidence -pointer for parent disposition. **No task 6.1 acceptance or checkmark is claimed.** -Live **1.1/4.2/6.2 remain UNEXECUTED**, including correction/decline and actual -installed unload/reactivate. No next child, OpenCode command, model evaluation, -activation, extra agent, Git staging/commit/push, remote Dolt sync or closure. - -## Final parent correction and task 6.1 acceptance - -Snarkimedes reviewed the worker guard diff and its RED/GREEN evidence. The exact -supported exit-1/schema-1 no-workspace response is classified as uninitialized; -other errors, unsupported error versions and interruption remain probe failures. -There is no fallback store access. This resolves our adapter classification, not -an upstream defect. - -The resumed real CLI run also exposed numeric `schema_version: 1` in memory -lists. Parent treated this small response-decoding correction as part of the -same task 6.1 integration work, without another worker, issue or upstream repair. -Parent added a regression in `tests/continuity.test.ts` and observed RED (exit 1, -acknowledged expected but failed returned; `vuy8-parent-memory-red.log`) before -editing production code. `src/continuity.ts` now removes only known numeric -schema-1 envelope metadata from a copy of the memory map and validates all -remaining values as strings. Empty and populated versioned lists are accepted; -unsupported numeric versions and unrelated non-string fields remain rejected. -The CLI contract now asserts the actual versioned raw envelope, exact memory -contents and absence of additional entries. Metadata is not merely discarded -inside tests while leaving production decoding broken. - -Final independent parent executions used cached baseline Bun 1.3.14 on PATH, -`TMPDIR=/opt/data/cache/scratch` and actual actor `snarkimedes` for disposable -CLI operations. All exited 0: - -- Guard/continuity focused tests: **31 pass, 0 fail**. -- Full repository suite: **170 pass, 0 fail**, 1,267 assertions, 12 files. -- Typecheck and packed-package smoke: pass. -- Real Beads 1.3.1 disposable CLI contract: **40 checks pass, 0 fail**. -- Strict named/global OpenSpec, planning/source validation and whitespace: pass. - -Execution logs and exits are indexed in -`/opt/data/cache/scratch/vuy8-parent-final-checks.json`; detailed logs use the -`vuy8-parent-{focused-green,tests-final,typecheck-final,package-final,contract-final}.log` -names. Tested production/fixture/contract hashes are retained in -`vuy8-parent-final-source-manifest.json`. The final archive SHA-256 is -`043257ca145a775bf8b10cb73194a2fae2eb0d2d25b379e00f90ca8219e6ddf3`, still package -`@snarkipus/opencode-beads@1.0.2`; no version bump or publication occurred. - -Real checks establish append retention/readback, explicit audit/claim actor, -remember/update/recall, empty-content rejection, missing-key exits, empty and -populated list/search envelopes, setup/prime and disposable schema-marker refresh. -The installed release does not demonstrate found-empty memory or richer commit -outcome fields; those remain fixture-supported shapes, not fabricated live results. - -**Standards:** no remaining blocking finding in the bounded guard/parser/test -changes; direct CLI invocation, attribution, no retry/bypass and user-file -preservation remain intact. **Spec:** task 6.1's supported deterministic/package/CLI -acceptance is met; live 1.1/4.2/6.2 and final reconciliation 6.3 are not satisfied -by these checks. The original `.6` review remains unchanged and does not review -the new guard/parser fixes; relevant current host/guard/flow/continuity fixtures -were rerun by the parent in the full suite. - -Parent checked only task 6.1 and reconciled the validator's accepted task set; -the local ledger is now nine accepted of thirteen. The five protected planning -paths matched before acceptance; the sole subsequent protected-file change is -the parent-owned 6.1 checkbox, with no task wording or gap-resolution changes. -`.8` remains open pending separately authorized publication/closeout; no worker -continuation, next child, live host/model evaluation, install, activation, -commit/push, Dolt synchronization or closure is implied. diff --git a/docs/opencode-2.1.1-contract-delta.md b/docs/opencode-2.1.1-contract-delta.md deleted file mode 100644 index 163ba21..0000000 --- a/docs/opencode-2.1.1-contract-delta.md +++ /dev/null @@ -1,33 +0,0 @@ -# OpenCode 2.0.32 → 2.1.1 contract delta - -**2026-10-20 — READY for parent/owner review; PAUSED FOR REVIEW.** This is source-backed planning, not host compatibility acceptance or implementation authority. Custody starts at `907232a393443a0f0d59133ffb0e2612f3fd9026`; the accepted 84ab18e plan and dd56cf1 mapping/review remain historical. Matt selected the newer host; all other product selections stand. - -## Identity, scope and admission - -- New exact tag `v2.1.1` resolves directly to commit **`ba546ec1598a70db2570e9c6258028d955ba8f58`**, verified by GitHub ref/tree APIs. Previous release remains **`843a6c514e606b436a7fe713422ace0a93ad3d61`** (2.0.32), not the old development snapshot. -- Published `@opencode/plugin@2.1.1` exists. Downloaded tarball integrity: `sha512-wvbvx/GeFNL7lb2Aj0IlXxPN01J6L1qJ2IbkUE5FaLmnC78aLjibzFP+wuzb28yUAM65dYw7WJRvHv+5GZRL8Q==`. Declarations were extracted as evidence only; nothing was installed. Registry metadata/tarball SHA-256 and source Git/SHA-256 identities are in `host_baseline_211` in the [inventory](claude-code-integration-inventory.json). -- The supplied tag’s [changelog](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/CHANGELOG.md) starts at **v2.1.0**, not curated 2.1.1 notes. Exact released-file comparisons govern this memo. GitHub compare reports diverged history and caps its file list at 300; it is navigation evidence, not an exhaustive endpoint diff. No ancestry is inferred from version/date order. -- Proposed admission: **`>=2.1.1 <2.2`**, exact disposable qualification target **2.1.1**. The explicit breaking minor invalidates blanket V2 compatibility. Future 2.1 patches are admitted candidates subject to source checks and affected acceptance, not claimed tested; 2.0 and 2.2+ are outside this redesign’s declaration. No version has passed live qualification for this redesign. Task 1.2 changes types/declarations only under later authority, before 1.1 probes. Operator 2.0.29 stays untouched. - -Bounded coverage: all 45 previously pinned native files plus 18 directly related schema/history/skill/permission/client sources, including the changelog: **63 files (31 unchanged, 29 modified, 3 added)**. Fourteen published Effect/Promise domain declarations were compared: session changes; tool/skill/command/agent/permission/plugin remain byte-identical. The historical 45-file native inventory, 73-file Claude release inventory, 74-file selected marketplace corpus, and all three independent reviews remain distinct and unchanged in identity. Source cache: `/opt/data/cache/scratch/parity-sources/baseline211/`. - -## Contract decisions - -| Surface and evidence | Decision and task impact | -| --- | --- | -| Provider replay names: [message schema](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/schema/src/session-message.ts), [event schema](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/schema/src/session-event.ts), [Promise session](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/session.ts) | **Adapt** relevant types/fixtures in 1.2/3.2/6.1: replay `state`, `providerState`, `providerResultState`, `resultState` become `native`; SessionCompactionResult uses native. Tool execution `state` and UI `metadata` are NOT renamed. Tool call/result native data merge shallowly with result keys winning; do not interpret opaque provider data as Beads memory. | -| Retained summary history: [compaction](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/compaction.ts), [history](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/history.ts), [fork projector](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/projector.ts) | **Retain reference-only M03; adapt** 3.2/4.2/6.2 fixtures. New summaries reference metadata.keepID; legacy flattened text is metadata.recent. History reconstructs the retained tail; forks remap the reference. Preserve host metadata, do not flatten/rewrite it or inject a replacement result. Summary preparation now sees the whole conversation before fallback shrinking; reserve is 15% with a 16k floor where the window permits. Meaningful earlier checkpoints remain necessary; no final-write guarantee. | -| Native replay: [history](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/history.ts), [to-LLM conversion](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/runner/to-llm-message.ts) | **Adapt**, not replace: providerContext becomes native.messages; replay matches provider and model rather than endpoint provenance, falling back to original messages on mismatch. Hook result.native.messages replaces summary replay; never populate it merely to add Beads references. Tool calls require matching provider/model; provider-run results may cross a model change within the same provider, while local results require matching model and nonfailed step. 3.2/6.2 cover recovery boundaries. No compatibility decoder/service of our own; host legacy decoding owns old data. | -| Compaction notifications: event schema above and [legacy decoder](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/schema/src/session-legacy.ts) | **Retire** any session.compacted assumption; use current session.compaction.started/ended/failed. No selected mechanism depended on the transitional event. M04 remains observation, not an awaited stop barrier. Metadata/provider shape adapters are fixture scope in 3.2, not a new event manager. | -| Paginated session listing: Promise session above and [Effect session](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/effect/session.ts) | **Reclassify X09 released-public; do not adopt.** list now exposes opaque cursor pagination and filters; cursor carries filters, limit defaults in core. Known-session/task recovery suffices. Historical development-only classification stays valid for 2.0.32. No session scan or extra ticket. | -| Permission filtering/identity/save: [tool](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool.ts), [permission](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/permission.ts), [saved grants](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/permission/saved.ts) | **Retain** shell filtering, invocation agent, deny precedence, save: [] and external-target checks. Tool change caches inventory by registry/visible names but keeps request executors fresh; permission change drops undefined metadata values. Saved grants now support editing; do not edit permissions from the plugin. 1.1 checks re-evaluation after operator grant edits/revocation; 3.1 retains adapter guard/cancellation/argv checks. Existing shell bd * equivalence and repeated one-call “always” prompts remain. | -| Skills: [scan](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/config/plugin/skill-scan.ts), [watch integration](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/config/plugin/skill.ts), [resource preparation](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/skill.ts) | **Retain explicit package registration/16 links.** Scanning bounds depth at six, skips hidden/ignored directories, stops descending at SKILL.md, watches outside-root resolved files specifically; resource preparation adds ignore globs but still lists only ten. 2.2/3.3 fixtures cover paths/reload without assuming recursive auto-discovery; 6.2 honors external_directory ask/deny. No installer or watch manager. | -| Long-running TUI transport (changelog above) | **Host-owned fix, qualification relevance only.** Release notes report requests surviving the five-minute fetch deadline; inspected client entry surfaces are unchanged, not proof of the lower-level fix or live reliability. 4.2/6.2 observe cancellation/late results on the target host; do not build a transport shim or an exhaustive duration matrix. | - -The direct endpoint comparison found no change in the pinned registration/editor/state ordering, hook dispatcher, external-access/shell authorization, prompt/execution, subagent return/completion/job, supervisor or file-access sources. Context/model preparation changes are native replay and image-budget handling; plugin host adds session.list forwarding, not a new cleanup contract. Session removal uses the underlying store list so child deletion does not inherit public pagination; new archive/unarchive events do not authorize continuation or require a new observer. These observations support **retaining** M01/M02/M05/M07/M09/M10 and collision/stop/unload gates, not claiming them passed. Restrictive-agent discovery, cancellation after approval, late children, namespace dispatch and lifecycle still need exact-host qualification. - -## Delivery and review boundary - -Existing 13 tasks and nine children fit the delta: .1 types before .2 host probes; .4 context/compaction fixtures; .5 resource/lifecycle fixtures; .6 child and fork/live checks; .8 deterministic integration; .9 measured end-to-end acceptance. .3 guidance and .7 drift stay independent. No new epic, service, queue, compatibility manager or task split. .6 remains the sole authoritative deterministic 4.2 evidence owner; .8 consumes only parent-verified evidence and stays blocked otherwise. .9 waits for complete live 1.1/4.2 and 6.1. - -Validation covers immutable old/new source and published artifact integrity, complete corpus dispositions, exact task ownership/17 requirements, dependency/phase acyclicity, scoped lint, fresh tracker readback, whitespace and setup custody. These are static planning checks. Live environment/model access and implementation/dependency authority remain absent. All ten records stay blocked, unassigned and implementation_authorized=false; d9n stays open. Pause for parent/owner review; no host/model run, installation, source implementation, sync, publication or dispatch is authorized. diff --git a/docs/opencode-22-qualification-5rj2.md b/docs/opencode-22-qualification-5rj2.md deleted file mode 100644 index b0e8c04..0000000 --- a/docs/opencode-22-qualification-5rj2.md +++ /dev/null @@ -1,56 +0,0 @@ -# OpenCode 2.2.6 qualification — parent accepted - -## Current verdict - -**Source and the selected installed-host qualification are accepted locally.** Tasks 2.2 and 2.3 under `opencode-beads-5rj.2` are complete, following the previously accepted source tasks 1.1, 1.2 and 2.1. **The owner-required final Claude Opus 5.5 gate returned Standards READY / Spec READY after one documentation-only correction and same-session recheck.** Parent acceptance uses retained native evidence, independent offline checks and current cleanup/preservation readback—not worker exit codes alone. - -- **Standards: READY.** Qualification used the public frozen package and supported host interfaces; production code, permissions and attribution were not modified to make probes pass. No upstream patch, retry/routing framework or expanded host/provider matrix was added. -- **Spec: READY for the five selected tasks.** Source checks, controlled native mechanics and one genuine model-selected workflow cover their respective boundaries. Known limitations remain explicit rather than being relabelled fixes. The [original final review](reviews/claude-opencode-22-final-tjd.md) retains its documentation-only REVISE; the [same-session recheck](reviews/claude-opencode-22-final-recheck-tjd.md) records F1 resolved and final READY. Actual reviewer model/session and no-error/no-denial completion were verified; all 201 corrected candidate file hashes remained unchanged across recheck. The status/marker/report additions in this local closeout are evidence-only successors, not runtime changes. -- The owner subsequently authorized canonical-spec synchronization/archive and source publication. The accepted deltas are synchronized into the canonical specs and the completed change is [archived](../openspec/changes/archive/2026-11-09-adapt-opencode-2-2/proposal.md). Source publication follows the normal PR/CI path; registry release, npm-tag changes and operator activation remain separately gated. Publication identities and execution-epic closure are recorded in Beads, not inferred from the earlier review verdict. - -## Exact candidate - -- Runtime source: `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643`. -- Source acceptance: [review and parent evidence](reviews/opencode-22-source-acceptance-5rj1.md). -- Qualification checkout: `f22177939b65ad95e6cf6b7cdb049c07447fd8aa`; its successors to runtime source contain acceptance evidence and agent-tooling guidance, not packed runtime changes. -- Archive: `snarkipus-opencode-beads-1.1.0-beta.5.tgz`. -- SHA-256: `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`. -- All 31 installed package files match that archive. The internal beta.5 version does **not** identify the published beta.5 artifact. -- Actual CLI/server qualification target: **OpenCode 2.2.6**. Beads fixture CLI: **1.3.4**; the supported minimum remains 1.3.1, with prior deterministic minimum-version evidence reused. - -## Evidence and acceptance boundaries - -The following original reports are retained verbatim. Their worker-time pending/partial verdicts describe their own handoffs; this current parent summary integrates the later evidence without rewriting those observations. - -1. [Initial controlled installed-host pass — historical partial handoff](reviews/opencode-22-controlled-qualification-5rj2.md): compact native command admission, actual storage/projector/provider snapshot transport, current/legacy snapshots, once-captured diagnostics replay, auxiliary generate exclusion, native namespace discovery, composed/direct operations, independent permissions, denied-target nonexecution, scoped native child identity, summary/native replay, Stop and actual plugin disposal. Parent independently reran its **33 raw-evidence assertions**. -2. [Completion of title and pending-disposal mechanics](reviews/opencode-22-mechanics-completion-5rj2.md): actual native title-provider frame excluded snapshots while the matching primary request expanded once; a genuinely pending diagnostics callback was aborted by the original product cleanup before held real subprocess output was released. No late prompt or provider call occurred. Parent independently reran **22 assertions**, verified prior/source hashes and checked current owned-process/listener absence. -3. [One genuine model-selected workflow](reviews/opencode-22-genuine-workflow-5rj2.md): native **OpenAI subscription / gpt-6.1-sol / high**, session `ses_e42640b98ffeC3CF3XhLJXcA5I`. An ordinary `/oc-beads:comments` request led the model to load the installed skill, discover native signatures, get the target and append the exact requested note through `beads.note`. Separate once-only permissions protected get and note. Independent readback established exactly one append, preserved original target fields/authorship/assignment and an unchanged sentinel. The final assistant report completed truthfully. Parent independently reran **29 assertions** and verified current cleanup and source/prior-evidence hashes. - -The genuine run is one sample, not a model reliability certification or a new all-command campaign. Its observation-only request contexts are pre-serializer evidence, not genuine wire captures; the actual controlled-provider transport observations cover that separate boundary. The genuine run used a fresh user-completed native isolated login, not copied operator credentials, a credential translator or a controlled-provider response. The five primary steps belong to the one requested workflow, not five separately prompted samples. - -The unchanged source suite, typecheck, exact-package smoke and strict specifications were consumed from accepted source evidence rather than repeated for each runtime pass. The suite had 218 passing tests and 11,883 assertions. Qualification worker: `codex:86c72145`, actual Codex session `01a1bd7e-5bd2-7720-88f3-870d909d432b`, observed Astra/medium; that is separate from the genuine OpenCode model/actor. - -Durable raw evidence and offline analyzers are under `/opt/data/research/opencode-beads-2.2.6-impact/qualification-5rj2/`, with `completion-pass/` and `genuine-pass/` separating the bounded continuations. Parent checked the original 197 tracked-file baseline and each pass's preserved earlier evidence before making this intentional documentation/marker successor. - -## Limitations retained - -- **Historical frozen README status:** The qualified canary archive retains the old README statements at lines 24 and 202 saying qualification was pending; this summary supersedes them for digest `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`. The separately tracked 2.0.0 metadata preparation reconciles the current README and its compatibility assertions. It does not mutate or silently repackage the original qualified archive. - -- **`opencode-beads-o66` remains unresolved and upstream-blocked.** After native compaction on A then switching to non-replayable B, old ordinary transcript commands can lack accessible saved snapshots. The controlled native run verified the selected outcome: explicit unavailable-guidance disclosure, expansion of accessible snapshots, and no invented historical instructions. This is a verified limitation, not restored old snapshots or a fixed deficiency. README and the active specification retain it. -- Stop aborted the selected waiting operation and prevented its write, but the old host permission entry remained listed through session deletion. That stronger retirement observation remains failed historical evidence; no target execution, bypass or adapter repair requirement is inferred. The genuine run's final execution/permission inventories were empty. -- Original malformed controlled-compaction responses and the first unload sample's too-early callback return remain preserved as invalid/inconclusive observations. The separately identified fixture correction and actual pending-callback measurement supply the passing evidence; they do not retroactively turn the original attempts green. -- Source monitoring remains separate under `opencode-beads-rou`. No quantitative cost or context-savings claim is made. - -## Cleanup and next release decision - -Owned host/provider/fixture processes and loopback listeners were removed; transient server secrets/private startup logs were deleted. Source/archive and scoped operator fingerprints were preserved. The fresh authenticated native test profile remains private at `/opt/data/cache/scratch/oc-beads-22-genuine` for parent custody; its real credential database was not copied into evidence or deleted. No Zeus or operator service/configuration change occurred. - -Specification closeout is complete: the archive operation synchronized one added and six modified requirements, with no removals or renames. All five implementation/qualification tasks remain checked in the archived package. The archive-closeout successor to the accepted candidate changes specification/evidence documentation only; the qualified packed files and archive remain unchanged. - -Remaining release steps, under their own authority: - -- Prepare **stable 2.0.0**, not a silent 1.x promotion: new host admission is `>=2.2.6 <2.3`; there is no parallel 2.1 compatibility layer. Document upgrading OpenCode first and installing the new plugin deliberately. -- Preserve existing stable/beta exact pins for users staying on older hosts. Until a trusted release is authorized and verified, npm `latest=1.0.2` and `next=1.1.0-beta.5` remain the previously published releases, not this local candidate. -- A future version/migration-note change creates a new release archive identity and needs ordinary release checks/provenance; it does not erase this exact-candidate qualification or silently authorize another live campaign. - -Parent acceptance and source publication are not package publication, operator activation or resolution of the known deficiency. Canonical synchronization and archival follow the owner's separate closeout authorization, not an implied release approval. diff --git a/docs/opencode-23-qualification-xwq.md b/docs/opencode-23-qualification-xwq.md deleted file mode 100644 index bcf4fe8..0000000 --- a/docs/opencode-23-qualification-xwq.md +++ /dev/null @@ -1,64 +0,0 @@ -# OpenCode 2.3.0 bounded qualification and deferred coverage - -## Owner disposition — 2026-11-13 - -**Accepted with explicitly deferred coverage, not an exhaustive native pass.** After the parent recommended accepting the bounded qualification rather than another timing campaign, the owner agreed: “I agree - just document the gap and the rationale for deferring.” - -This decision removes the two cases below from the remaining required qualification scope for this candidate. They remain **deferred and unexecuted, not passed**. It does not weaken the intended stop, freshness, scope, acceptance or honest-outcome requirements, resolve `opencode-beads-o66`, or authorize publication, release, merge or operator upgrades. - -## Exact candidate and evidence classes - -- Source: baseline `bc8031c1f8bb80baf0f739cb6fff0644d902a5c2` plus the reviewed thirteen-file working candidate; no product changes during qualification. -- Normal packed archive: SHA-256 `80d3295bcdd378a6b920eb309e1bfb5e33b46e35f36bb490a4f1160b03253724`; all 32 packaged files matched the candidate source. -- Exact native host and SDK/client: OpenCode 2.3.0; Beads CLI 1.3.4. -- Genuine provider/model: OpenAI `gpt-6.1-terra`, `high`, for primary and inherited default task-agent children. Codex Terra/high orchestrated the probes; that is distinct from the native model execution being evaluated. -- Source checks: parent-run 233 tests / 12,340 assertions, typecheck, exact-package smoke, strict specification validation and whitespace checks passed. Independent Claude Opus 5.5 source review returned READY. That review did not independently review the later native evidence. -- Native evidence: parent reran both offline analyzers against retained traces and independently checked source preservation and owned-process/fixture cleanup. Actual request observations are pre-serializer captures, not provider-wire interception. - -## Measured native coverage accepted - -- Ordinary packed-plugin registration: 30 commands, installed skill/default task agent and all eleven native Beads namespace operations. -- Immediate running launch handle, later real child report and idle-parent wake; actual model/session/actor provenance, child claim and checkpoint independently read back. -- Report delivery while the parent remained active after launch-time processing; subsequent actual task and reusable-knowledge reads matched independent fixture state. The transparent observer captured the post-report request; final model prose alone was not treated as freshness proof. -- Native VM discovery and composed `find`/`get` execution, with actual leaf results and invoking permissions. -- Child interruption at a checkpoint permission wait before CLI approval; independent readback showed no landed note. -- Parent interruption followed by a late child report: the host woke the parent, which disclosed the interrupted read and made no further tool calls. Native wake was not mislabelled as an adapter-initiated restart or authorization for task work/closure. -- Approved checkpoint landed before acknowledgement was interrupted; durable readback confirmed it, the parent reported uncertainty and did not retry. This used a disclosed fixture-only wrapper which ran the real CLI unchanged and held its output after exit; it did not fabricate an execution result or implement custom abort behavior. - -## Deferred, unexecuted coverage and rationale - -### 1. Repeated idle reports while the same work is still outstanding - -**Gap:** Native reports and a separately authorized follow-up report were observed, but not repeated idle-period reports while the same assignment retained outstanding work. The existing source/fixture checks are not a substitute for this missing native observation. - -**Why defer:** The changed adapter cue does not parse report contents/status or implement a completion state machine. The meaningful changed boundaries—launch versus report, active/idle parent freshness, durable reconciliation and no work after stop—were observed on the real host. Obtaining this additional timing/state combination would require more deliberately arranged background work and another native campaign, without a demonstrated adapter defect. The owner judged that incremental qualification cost disproportionate for this bounded compatibility change. - -**Residual uncertainty:** Repeated reports with outstanding work have not been demonstrated end to end with this candidate. Neither reliable report ordering nor repeated-report model judgment is claimed. - -**Revisit when:** Ordinary authorized use supplies this case, an upstream report-lifecycle change affects our integration, or evidence shows incorrect closure/reconciliation on a repeated report. No automatic follow-up campaign is scheduled. - -### 2. Cancellation while the real `bd` process is still executing - -**Gap:** The probes covered both pre-execution permission-wait cancellation and a landed write with interrupted acknowledgement. They did not interrupt `bd` during its own execution. The output-hold result must not be presented as proof of a mid-CLI kill, rollback or uncertain database commit. - -**Why defer:** The compatibility patch does not change the CLI process runner or typed-operation cancellation implementation; existing deterministic cancellation coverage remains applicable. The native samples demonstrated cooperative interruption and the important landed-but-unacknowledged recovery path without blind retry. Hitting the narrower in-process timing window would require further timing instrumentation or repeated attempts. No observed failure currently justifies that additional campaign. - -**Residual uncertainty:** Mid-`bd` process termination and resulting durable state were not measured on this host/candidate. Atomic rollback, exactly-once execution and a guaranteed final checkpoint are not promised. - -**Revisit when:** The runner/cancellation path changes, a real interrupted operation exposes incorrect settlement/readback, or an upstream cancellation change materially invalidates retained coverage. - -## Preserved invalid observations and qualifications - -The first monitor incorrectly treated parent idle as completion while its child remained active. Its initial completion flag is invalid; observation continued on the same native sessions through the real report, and the original capture remains preserved. The cancellation fixture note anticipated an interruption before it occurred; that wording is not evidence. Independent permission/process/interruption/readback timestamps establish the actual outcome. No product behavior was tuned to hide these harness/executor errors. - -The original worker reports remain historical handoffs with their then-current INCOMPLETE verdicts. This owner decision is a successor disposition, not a retroactive alteration of those reports. - -## Evidence locations and boundaries - -Raw evidence stays outside the product and credential profile: - -- `/opt/data/research/opencode-2.3.0-plugin-impact/native-qualification/native-report.md`, `verify.py`, `assertions.json` and associated sanitized native traces. -- The `remaining/` subdirectory contains `remaining-report.md`, the second analyzer, request/event/permission traces, independent state readbacks, wrapper source/timeline and cleanup receipt. -- Source-stage review and parent acceptance are under the adjacent `source-review/` and `implementation-terra-high/` directories. - -All owned qualification servers/listeners, disposable trackers and transient server secrets were removed. The authorized isolated native authentication profile was retained in place, outside scratch pruning; no operator credentials were copied or bundled. The public README/package documentation in the frozen archive still says native qualification is pending because it predates this evidence disposition; the 2.2.0 preparation reconciles current documentation to this bounded scope without relabelling the deferred checks as passed. This qualification record itself changed no packed runtime file or operator installation; release preparation and publication are separate actions. diff --git a/docs/opencode-host-codemode-qualification-vuy2.md b/docs/opencode-host-codemode-qualification-vuy2.md deleted file mode 100644 index b135699..0000000 --- a/docs/opencode-host-codemode-qualification-vuy2.md +++ /dev/null @@ -1,91 +0,0 @@ -# OpenCode 2.1.1 native code-mode follow-up — vuy.2 / task 1.1 - -## Parent acceptance - -Parent independently inspected and reran the offline analyzer: all 15 follow-up cases passed, all 150 protected repository paths and 116 historical evidence files were unchanged. Operator before/after records match; independent current socket inspection confirmed neither owned port listening. Task 1.1 is accepted against the selected contract, combining these new observations with retained prior host evidence and the explicitly owner-accepted decline limitation. The stronger historical decline expectation remains failed, not relabeled passed. No installed product, real-model, explicit Stop/handoff or lifecycle acceptance is implied. The original worker handoff below records its pre-acceptance state. - -**Bounded follow-up passed; parent acceptance is pending.** Fifteen isolated released-host cases measured the new namespace, inventory, signature, result-bridge and permission-resource facts. No new unsupported host contract was observed. The historical stronger nested-decline termination case remains **failed, owner-accepted**, as recorded in [the original qualification](opencode-host-qualification-vuy2.md) and [owner decisions](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md). This report does not check task 1.1, close `.2`, enable the adapter or qualify later installed/model/Stop behavior. - -## Identity, authority and retained evidence - -- Date: 2026-10-21 UTC. Actor: `codex:oc-host`. Fresh replacement session: `01a15f7e-af76-7d73-9ed3-6d0fe89e3af7`; launch metadata records `gpt-6.1-sol`, high reasoning. No additional worker. This is not a continuation of unavailable session `01a15c62-d106-7e80-af58-5a47b1032cd4`. -- Evidence root **F**: `/opt/data/cache/scratch/vuy2-codemode-followup`. Exact bounded assignment: `F/prompt.md`; current authority: `F/record-current.json`. The original failed resume remains in `F/worker.log`, byte-identical by SHA-256 in `F/identity.json`. `fresh-worker.log` records this replacement's route and actual session. -- Published accepted source / repository HEAD: `8831169d3c83c333fdf13d4a4efc743eaf495e2b`. Entry worktree was clean. Only this new report was added in the repository; all 150 protected paths remain byte-identical to `F/protected.json`. -- Reused exact first-party `@opencode/cli-linux-x64-baseline@2.1.1` from **R**: `/opt/data/cache/scratch/vuy2-oc-host`. Tarball SHA-256 `216d3861d0a167adad5850282439bae13483203f4b110f0510f260118bba2858`; executable SHA-256 `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9`. Published SHA-512 SRI/SHA-1 and both retained registry signatures were independently reverified; actual version output is `opencode v2.1.1`. -- Pinned host source: `ba546ec1598a70db2570e9c6258028d955ba8f58`. All 36 retained source-file SHA-256 and Git-blob identities reverified against the original recorded manifest. This reuses the prior official tag/tree provenance; it is not a reproducible-build attestation or a new upstream lookup. -- Retained analyzer rerun with its single results-file write redirected to `F/prior-analysis.json`: 31 settled historical cases asserted, including the failed stronger decline contract. No old case was rerun. All 116 original evidence files and their path set remain unchanged, checked against `F/prior-evidence-before.json`. -- Beads remains `1.3.1 (c1c4b642a)`; no 1.3.0 qualification. Only `.2` progress notes were written, with explicit `--actor codex:oc-host --sandbox`. `.2` remains `in_progress`, assigned to that actor; `created_by=unknown` remains historical audit data. - -## Isolation and measurement boundary - -The real released executable served only `127.0.0.1:39161`, PID/process group `747580`. The controlled HTTP/SSE response fixture served only `127.0.0.1:45971`, PID/group `747573`. Separate `F/home`, `config`, `data`, `cache`, `state`, temporary files and committed disposable `F/repo` were used. The actual host project ID was `9ffa3d06bf093090747246e6ac95a65d78123a8c`, with project and location both `F/repo`. Startup used an explicit isolated environment and a newly generated transient server credential. Operator auth/config/environment was not reused. - -The provider fixture uses the native OpenAI-compatible HTTP transport. It records request bodies, never Authorization headers, emits the specified tool call, then `CONTROLLED_FIXTURE_STOP`. This measures real host mechanics; it provides no external inference or model-judgment evidence. All registration, catalog instructions, native search/execute, executor/result bridge, permission decisions and native shell execution were supplied by the unmodified release. - -The throwaway plugin registers the eleven `beads` leaves through actual `editor.namespace` and `editor.add`, with `namespace: "beads", permission: "shell", codemode: true`. `schema-declarations.ts` copies only the published candidate's declarative schema constants, `outputFor` and input table into scratch; `definitions.json` contains their evaluated JSON. It neither imports nor executes product adapter, guard, argv, routing, normalization or acknowledgement code. `fixtures.json` supplies explicit accepted example inputs, fixed canonical resource templates and synthetic structured output objects. Each permitted target only appends a scratch observation. The resource strings beginning `bd` are never executed. No real project Beads store is opened by a probe. - -The plugin returns a deliberately different text sentinel alongside each structured `output`. Observed composed results contain the structured objects, not that sentinel. This demonstrates the real bridge's object result behavior; it does not establish validation of every JSON-schema branch or genuine persistence. The candidate's source tests/CLI acceptance remain separate evidence. - -## Observations - -| Case | Actual released-host observation | -| --- | --- | -| `catalog-allow` | Provider direct inventory includes `execute` and native `shell`, with no direct Beads leaf duplicates. Code-mode instructions show `beads (11 tools, 4 shown)` and the namespace description. | -| `namespace-search` | Real `search({namespace:"beads",limit:20})` returns all eleven exact `tools.beads.*` paths, `remaining:0`, `next:null`. Signatures expose object inputs, structured Promise unions, status branches and relevant fields; no `Promise` fallback. | -| `execute-denied-shell-allowed` | Provider request has no `execute`, no Beads leaf tools and no Code Mode instructions/catalog. Direct native `shell` remains visible. | -| `execute-and-shell-denied` | Neither `execute` nor `shell` is in direct inventory; no Beads catalog or direct duplicates. | -| `whole-shell-denied` | Native shell and all eleven Beads leaves disappear; `execute` itself remains available for its independently allowed functionality. | -| `selective-catalog` | `shell: bd update *` deny preserves all eleven searchable leaf signatures, including note and get. Resource-selective denial is enforced at invocation, not inferred from tool visibility. | -| `shell-code-search` | Native `search({query:"shell",limit:20})` returns no code-mode tools. Shell remains direct-only; no `tools.shell` fallback is used. | -| `eleven-resource-and-result-bridge` | One composition invokes every leaf once. Eleven native approvals with `save:[]` precede eleven scratch targets. All eleven structured objects survive the real bridge, including multi-ID get, memory map, empty found recall value, completeness and write actor fields. | -| `selective-note-denied` | One note invocation, `Permission.BlockedError`, zero scratch targets, zero prompts/retries. Outer execute carries an inner error and `metadata.error:true`. | -| `selective-get-allowed` | Same selective agent invokes get once, obtains its independent approval and reaches one scratch target. | -| `namespace-correction` | One note invocation, one reject, zero targets/retries. `Tool.Error` wraps `Permission.CorrectedError`; exact feedback `Use staging; namespace original target is not authorized.` survives the leaf, execute output and next provider request. | -| `namespace-decline` | One note invocation, one reject, zero targets/retries. Leaf rethrows `Permission.DeclinedError` unchanged. Outer execute is completed with inner error, `metadata.error:true` and text `Tool.Error`; two provider requests occur. This reproduces the accepted continuation limitation, not a passing whole-step-termination claim. | -| `decline-then-independent-permission` | One composition catches note's plain decline and attempts get. Note never reaches its target; get asks separately and reaches its target only after its own approval. Two invocations, two permission replies, one scratch target. | -| `namespace-invoking-agent` | Response was held after the request snapshot under `probe_selective`; native API changed session default to `probe_allow` before release. Actual invocation/assertion retains `probe_selective` and blocks note. A native agent-omitted evaluation of the exact same resource under the new default allows it. No forged invocation or child dispatch. | -| `native-shell-with-execute-denied` | Real direct `shell` executes `/usr/bin/pwd` once, after its own shell approval, while `execute` remains absent from provider inventory. Exit 0; stdout is exactly `F/repo`. No Beads command runs. | - -There are 18 typed leaf invocations, 13 scratch targets and five rejections across these cases. Every rejected leaf has one invocation and zero rejected-target executions; no rejected leaf is automatically retried. The independent later get is a different explicitly planned operation. There is also one harmless native shell process. Exact case session IDs, provider-request counts, inputs, permission source/call IDs, errors and result envelopes are retained in `results.json`, `cases.jsonl`, `api.jsonl`, `provider.jsonl` and `plugin.jsonl`. - -Registration definitions are distinct from effective inventory: native transform callbacks logged 44 definition events across rebuilds and two plugin setups; each definition set has the same eleven names. Effective provider inventories and real search outputs establish the eleven callable leaves. The partial inline catalog is not mistaken for a four-tool registration limit. - -### Canonical permission-resource observations - -All eleven representative operation shapes were observed as native `action:"shell"` permission requests. `get` submits both resources together. Each request includes the actual invocation session and agent, tool message/call source and `save:[]`. **A** below abbreviates the observed host-derived `opencode:probe_ask:<12-hex-session-and-agent-hash>` actor, not a literal actor input. Full resources are in the raw captures. Newlines shown as `\n` below are actual newline bytes in the request. - -| Operation | Observed resource shape | -| --- | --- | -| find | `bd ready --limit 3 --json --sandbox` | -| get | `bd show scratch-1 --json --sandbox`, `bd show scratch-2 --json --sandbox` | -| edges | `bd dep list scratch-1 --direction down --type blocks --json --sandbox` | -| memories | `bd memories --json --sandbox -- 'build lesson'` | -| recall | `bd recall build --json --sandbox` | -| claim | `bd update scratch-1 --claim --json --actor A --sandbox` | -| note | `bd update scratch-1 --append-notes 'scratch '\''note'\''\nnext' --json --actor A --sandbox` | -| update | `bd update scratch-1 --status blocked --priority 1 --add-label review --remove-label old --json --actor A --sandbox` | -| close | `bd close scratch-1 --reason 'scratch accepted' --json --actor A --sandbox` | -| create | `bd create --title 'Scratch only' --type task --priority 2 --description 'Fixture only' --acceptance Observed --design Minimal --parent scratch-parent --deps discovered-from:scratch-1 --labels review --json --actor A --sandbox` | -| remember | `bd remember --key build --json --actor A --sandbox -- '-- literal scratch\nlesson'` | - -These are host observations of fixed probe definitions representing accepted canonical shapes. Adapter argv construction and every optional operation branch are not requalified here. Existing saved-grant, grant-edit/revocation, deny-precedence, external-directory/location, native command admission and `save:[]` repeat/always observations remain applicable from the original 31-case evidence; no new observation invalidated them. - -## Reproduction, harness corrections and cleanup - -Run the compact analyzer offline, without a host, provider, credential or product import: - -```sh -python3 /opt/data/cache/scratch/vuy2-codemode-followup/analyze.py -``` - -It asserts actual inventories/search signatures, all eleven observed resources/results, actual actors, denied target counts, feedback/decline envelopes, independent later permissions, native shell result, final empty active/saved lists, protected hashes and unchanged original evidence. It deliberately asserts the stronger decline mismatch instead of relabeling it passed. `results.json` is its retained output. - -The exact scratch scripts are retained: `prepare.py`, `make-fixtures.py`, `schema-declarations.ts`, `probe-plugin.mjs`/`plugin/index.mjs`, `start.py`, `provider.py`, `client.py`, `probes.py`, `run-cases.py`, `run-delta.py`, `resume-probe-control.py`, `run-remaining.py`, `run-shell.py` and `cleanup.py`. Launch commands were `python3 F/provider.py` under the explicit provider environment and `python3 F/start.py`; the latter records the actual `serve --hostname 127.0.0.1 --port 39161` command identity/environment names in `process.json`. Schema evaluation used the pinned available Bun executable at `/opt/data/.npm/_npx/60c3515df86f25b1/node_modules/@oven/bun-linux-x64-baseline/bin/bun`. Per-case code and direct tool inputs are captured in native request bodies; `run-delta.log`, `run-remaining.log` and `run-shell.log` preserve execution outputs. - -Two harness corrections are disclosed. The first runner attempted to read a not-yet-created plugin log before creating a session; it was changed to treat the absent initial log as empty, with no tool measurement/retry. One approval payload used `reply` instead of the pinned API's `decision` key, producing an actual HTTP 400 (`Missing key at ["decision"]`) in `api.jsonl`/`run-delta.log`. The same pending call was completed using the correct key, without resubmitting the tool or duplicating any target. No host/product contract was changed. - -`cleanup.json` confirms both owned process groups terminated, no remaining owned process or listener and neither owned port listening. Before shutdown the native active-session list was empty and saved grants were empty. The server secret and unsanitized private server log were removed; only sanitized logs remain. The provider API-key value was a noncredential fixture placeholder. No genuine external provider credentials were read or used. - -`operator-before.json` and `operator-after.json` match for the resolved executable, known global/project configuration/package hashes and version `opencode v2.0.29`; executable SHA-256 remains `7e23471f4ebe2313d78baacc9ac96fe9e197ce26d808de4b0fcc37efbe473dad`. Original evidence and the failed resume log are preserved. The offline analyzer and whitespace checks passed. The unchanged 191-test source suite was not rerun for this report-only qualification. - -No source/tests/package/assets/OpenSpec/old report/operator integration edits, task checkmarks, staging, repository commits, pushes, Dolt sync, closure, activation, release or `.6`/`.9` dispatch occurred. The SDK contract is protected by this assignment; parent can reconcile accepted evidence separately. **Smallest next gate:** parent independently reruns the offline analyzer and reviews this bounded report together with the retained historical evidence/accepted limitation, then decides task 1.1 acceptance and publication. Explicit Stop/handoff and real installed/model/lifecycle qualification remain with their existing later owners. diff --git a/docs/opencode-host-qualification-vuy2.md b/docs/opencode-host-qualification-vuy2.md deleted file mode 100644 index 1907414..0000000 --- a/docs/opencode-host-qualification-vuy2.md +++ /dev/null @@ -1,117 +0,0 @@ -# Exact OpenCode 2.1.1 host qualification — vuy.2 / task 1.1 - -**Result: NOT QUALIFIED.** The real released host passed the independent permission, discovery, identity, grant, location and command probes below. Code-mode explicit decline failed to preserve the abort outcome. Task 1.1 remains unaccepted; privileged continuity remains withheld. No source fix, fallback, namespace change, activation or later-child work was performed. - -## Identity and isolation - -- Repository baseline: `072429f1a7723ade23e756a921924d9d0acacf31`, branch `openspec/improve-beads-workflow-parity`. Entry status included an untracked `.claude/settings.local.json`, left untouched. -- Executor: `codex:oc-host`; actual worker session/thread `01a15c62-d106-7e80-af58-5a47b1032cd4`. Requested model/reasoning: `gpt-6.1-sol` / high. No delegated workers. -- Execution date: 2026-10-21 UTC. Evidence root, abbreviated **R** below: `/opt/data/cache/scratch/vuy2-oc-host`. -- Official exact package discovered from pinned `packages/cli/package.json`, `script/build.ts`, `script/publish.ts` and [exact CLI registry metadata](https://registry.npmjs.org/@opencode%2fcli/2.1.1): `@opencode/cli-linux-x64-baseline@2.1.1`. No latest install or global package mutation. -- [Binary metadata](https://registry.npmjs.org/@opencode%2fcli-linux-x64-baseline/2.1.1) identifies the first-party repository and exact tarball. Published SHA-512 SRI and SHA-1 both matched. Both registry signatures verified with the matching public key from `https://registry.npmjs.org/-/npm/v1/keys` using `openssl dgst -sha256 -verify`; results retained in `npm-signature-results.json`. -- Tarball SHA-256: `216d3861d0a167adad5850282439bae13483203f4b110f0510f260118bba2858`. Extracted executable `R/release/package/bin/opencode` SHA-256: `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9`. Actual command output: `opencode v2.1.1`; extracted package name/version also read back. -- Official `v2.1.1` tag resolves to `ba546ec1598a70db2570e9c6258028d955ba8f58`, tree `6b520b02605e7eafa41c03bf9d4e0cab029d5f9c`. Thirty-six bounded source files fetched for setup/API lookup were Git-blob verified against the complete cached pinned tree; see `source-verification.json`, `source-tag.json`, `source-commit.json`. This establishes artifact integrity and official source/release identities, not an independent reproducible-build attestation. -- Separate `R/home`, `config`, `data`, `cache`, `state`, temporary files and a fresh `R/repo` with an initial Git commit. The resolved project ID was `4cc9a0e821dd59eb76d00cd84d22650766c9efd0`, not the shared global project. All startup environment variables were explicitly constructed; no operator environment/auth database was reused. -- Foreground `serve --hostname 127.0.0.1 --port 43355`, PID/process group `634873`, launched from `R/repo`. The controlled local HTTP provider ultimately ran as PID/group `635618` on `127.0.0.1:39209`. No service command, external binding, tunnel or operator restart. -- Provider/model: **controlled local response fixture**, provider ID `vuy2-fixture`, model `deterministic`, using the host's native OpenAI-compatible HTTP/SSE transport. It emits one planned tool call and then `CONTROLLED_FIXTURE_STOP`. No external inference, genuine credential access or model-obedience claim. It records request bodies, never Authorization headers. Host tool registries, permission service, saved-grant storage, code-mode runtime and execution are real. - -## Probe scope and results - -`plugin/index.mjs` is a throwaway Promise plugin registering only `probe_direct` (`codemode: false`), `probe_code` (native code mode), both with `options.permission: "shell"`, and a harmless `oc-beads:ready` command. Its tools pass actual invocation `sessionID`, `agent`, `messageID` and call ID into `permission.assert`, use exact supplied resources and `save: []`, and rethrow rejection unchanged. Before approval the target cannot run. Early targets append a scratch observation only; later location probes additionally run `/usr/bin/pwd` with an explicit scratch cwd. Resource strings beginning `bd` are permission probes, not project-tracker operations. The native `bd` comparison uses a scratch-only shell stub that prints `VUY2_THROWAWAY_BD_STUB_NO_DATABASE` and its cwd. - -The local fixture chooses calls and API replies deterministically. This measures host contracts and propagation; subsequent real-model decisions remain task 6.2. `analyze.py` checks the recorded observations, not a mock implementation. `results.json` indexes all full host session IDs; `cases.jsonl` contains invocation, assertion, evaluation, rejection, target and after-hook records. There were 31 settled probe cases plus one superseded setup attempt with no tool measurement. Counts do not determine acceptance. - -| Selected case | Result and exact evidence | -| --- | --- | -| Whole-shell deny, direct and code-mode discovery | **PASS.** `deny-discovery`: provider request lacks direct `probe_direct` and the `tools.probe_code` catalog entry. `selective-discovery` contains both. Actual inventories are in `provider.jsonl`, not inferred from registration metadata. | -| Selective operation denial in both paths | **PASS.** `selective-deny-direct` / `selective-deny-code`: `bd forbidden target` yields `Permission.BlockedError`; no target event. Code-mode outer completion carries `metadata.error: true` and an inner error record; it is not target success. | -| Actual invoking agent differs from session default | **PASS.** `invoking-agent-differs`, session `ses_ea3960befffeIVHsw6iL9hJ4H3`: provider response held after the real request snapshot for `probe_selective`; native `POST /api/session/:id/agent` switches the session to `probe_allow`. Readback confirms that default; an agent-omitted native permission request for the same resource allows. Releasing the original response invokes the tool as `probe_selective`; its explicit-agent assertion denies `bd forbidden identity-target`. No child agent or forged invocation context. | -| Allow and ask | **PASS.** `allow-direct-http` / `allow-code` reach one target each without a prompt. Ask cases wait for native API approval before a target event. Exact action/resource/source fields are retained in `api.jsonl` and `plugin.jsonl`. | -| `save: []`, always and repeat ask | **PASS.** `ask-always-first` approves `bd update throwaway --append-notes 'probe text' --json --actor codex:oc-host --sandbox` with `always`; saved list remains empty. `ask-always-repeat` asks again. Each reaches one target after its own reply. No Beads write occurs. | -| Correction with feedback, direct | **PASS.** `corrected-direct`: `reject` with `Use staging; original target is not authorized.` yields `Tool.Error` wrapping `Permission.CorrectedError`. Native message has `state.status: error`, `error.type: permission.rejected` and exact feedback. Zero target events and one invocation; the fixture's next step only stops. | -| Correction with feedback, code mode | **PASS.** `corrected-code`: exact `Use staging; code target is not authorized.` survives leaf rejection, inner error and outer code-mode output/`metadata.error: true`. Zero target events and one invocation; no retry. | -| Explicit decline, direct | **PASS.** `declined-direct`: leaf rejects with `Permission.DeclinedError`; native tool message is `aborted`, assistant error says `Step interrupted`, and no next provider request occurs. Zero target events, one invocation. | -| Explicit decline, code mode | **FAIL.** `declined-code`, session `ses_ea396cc6affenEp6WisS1KyHef`, message `msg_15c6933a4001vwxlp9uhAKg3TG`, call `vuy2_declined-code`: leaf rejects with `Permission.DeclinedError`, but outer `execute` has `status: completed`, text `Tool.Error`, inner `status: error` and `metadata.error: true`. It loses the distinct decline/abort outcome and allows a second provider request, unlike direct decline. Target never runs and is not retried. This is a failure of preserved decline propagation, not evidence that the rejected operation succeeded. Affected path stopped after observation. | -| Existing shell `bd *` grant and deny precedence | **PASS.** A fixture-owned grant is created through native session permission request/reply with `save: ["bd *"]` and `always`. `saved-bd-direct`, `saved-bd-code` and `native-bd-existing-grant` proceed without asks. The native command resolves to the scratch stub (first checked by `native-stub-path`), never the installed Beads CLI. `saved-deny-wins` remains blocked by configured `bd forbidden *` deny. | -| Externally edited/revoked grant | **PASS.** Native saved-permission PATCH changes `bd *` to `bd other *`; the next equivalent request asks. Restoring it allows code mode; DELETE makes code mode ask again. Stronger same-session sequence `native-bd-existing-grant` → `same-session-grant-allows` → `same-session-edited-reask` → `same-session-revoked-reask` also asks after edit/revoke, without restarting the host or replacing the session. All fixture grants removed; final saved list empty. | -| Explicit external-directory assertions and actual location | **PASS.** `native-external-pwd` and `typed-external-pwd` request exactly `external_directory: ["R/external/*"]` followed by `shell: ["/usr/bin/pwd"]`, each asking twice. Both actual processes exit zero and print `R/external`. Typed host/session locations both remain `R/repo`; explicit cwd is `R/external`. `typed-local-pwd` / `native-local-pwd` both print `R/repo` and require no external permission. Here `R` abbreviates the full path; logs retain the literal strings. | -| External correction and deny | **PASS.** `typed-external-reject` retains correction feedback and never reaches shell assertion/target. `typed-external-deny` and `native-external-deny` retain the actual blocked external resource and report errors before successful execution. No routing or final-store confinement claim. | -| Native `oc-beads:ready` registration/admission/invocation | **PASS.** `/api/plugin` reports the local throwaway plugin active; `/api/command` lists the exact namespace. `POST /api/session/:id/command` with literal `literal $ARGUMENTS / ready` and `delivery: queue` returns 204; the command body records those literal arguments and the actual session ID. No command rename or production adapter. | - -## Decline mismatch and supported disposition - -Pinned [Promise permission declarations](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/permission.ts) document plain rejection ending the current step and requiring rethrow. The probe does rethrow. The [code-mode result construction](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/codemode/tool.ts#L89) returns a normal tool result with error metadata when runtime execution fails; the observed outer envelope and continuation are consistent with that path. No upstream test service mock was used to establish this result. - -The concrete remaining prerequisite is a parent/owner disposition of the demonstrated exact-host code-mode decline incompatibility, followed by passing measured evidence for the selected guarantee on an explicitly authorized host. No supported 2.1.1 configuration remedy was established. This worker did not patch upstream, add a permission translator, hide code-mode tools as a workaround, choose N0 or activate continuity. Independent passing cases do not complete task 1.1. External-provider/model behavior, child handoff/stop/recovery, installed-package access/unload/reactivation and final product acceptance were **NOT RUN** under this authority. - -## Reproduction and evidence - -All scripts and payloads are scratch-local. To reproduce in a **fresh** dedicated scratch root, replace the literal root in the retained Python/plugin files, retain the verified `release/package` artifact and `plugin/package.json`, and follow this sequence. `start.py` now contains the final supported package-object configuration; the original setup attempt used a string directive, which did not load a package. A separate abandoned in-process language-hook fixture did not intercept native HTTP transport, tried only an unreachable loopback URL, reached no tool, and was interrupted. Neither setup attempt is accepted contract evidence. - -```sh -# From the fresh scratch root; provider binds loopback and writes provider-process.json. -python3 provider.py > provider-process.log 2>&1 & -python3 start.py -python3 - <<'PY' -from probes import * -api('POST', '/api/location/reload', {}) -s = create('probe_allow') -api('POST', f'/api/session/{s}/command', { - 'name': 'oc-beads:ready', 'text': 'literal $ARGUMENTS / ready', 'delivery': 'queue'}) -run('repro-deny-discovery', 'probe_deny') -run('repro-correction', 'probe_ask', { - 'name': 'probe_direct', 'input': {'resource': 'bd show throwaway --json'}}, - [{'decision': 'reject', 'message': 'Use staging'}]) -run('repro-code-decline', 'probe_ask', { - 'name': 'execute', 'input': { - 'code': 'return await tools.probe_code({resource:"bd show throwaway --json"});'}}, - [{'decision': 'reject'}]) -PY -python3 cleanup.py -``` - -`client.py` sends authenticated native API requests without logging the transient credential. Actual request/reply payloads for **all** measured cases, including native grant creation/PATCH/DELETE and the agent switch, remain in sanitized `api.jsonl`; provider bodies are in `provider.jsonl`. `plugin.jsonl`, `cases.jsonl` and message API readbacks expose leaf versus outer outcomes. `analyze.py` verifies filtering, exact resources, target absence/counts, feedback, same-session grant behavior and the decline difference from those retained traces; it passed. `evidence-sha256.json` identifies retained evidence bytes. Runtime commands read Bun `1.3.14` (existing baseline build), OpenSpec `1.14.2` and Beads `1.3.1 (c1c4b642a)`; no runtime repair or dependency edit occurred. - -## Cleanup and handoff - -`cleanup.json` records both owned process groups stopped, no remaining owned process and no listening socket on either port (`43355`, `39209`), checked through `/proc` process/FD/socket data. The scratch server credential and unsanitized server log were deleted; sanitized logs, source/artifact identities and executable remain under R. Final active-session and saved-permission API lists were empty before shutdown. - -Before provisioning and after shutdown, `/usr/local/bin/opencode` resolves to `/opt/hermes/image-toolchain/npm/node_modules/@opencode/cli/bin/opencode.exe`, reports `opencode v2.0.29`, and hashes to `7e23471f4ebe2313d78baacc9ac96fe9e197ce26d808de4b0fcc37efbe473dad`. `operator-before.json` / `operator-after.json` show identical hashes for the executable and known existing global/project OpenCode configuration/package files. No configuration or credential contents were dumped. - -Documentation checks: strict change and all OpenSpec validation, planning validator against `/opt/data/cache/scratch/parity-sources`, and `git diff --check`. Source/package/assets/OpenSpec/reviews remain unchanged. No staging, repository commit, publication, remote synchronization or closure. At worker handoff `.2` remained `in_progress`, assigned to `codex:oc-host`; parent owns acceptance, markers and closure. - -## Parent evidence review and disposition - -Parent inspected the throwaway plugin and the pinned Promise permission and -code-mode implementation, then independently ran the retained evidence analyzer. -Its raw-log assertions passed for 31 settled cases, including zero target events, -one leaf invocation and the same `Permission.DeclinedError` for each decline -path. The direct path made one provider request and aborted; code mode made two -requests and exposed an outer completed envelope with inner error metadata. -This is **not** evidence of unauthorized target execution, a retry, or a successful -persistence acknowledgement. It is a host-owned decline/step-termination mismatch -against the selected preserved-outcome contract and the pinned declaration. - -Parent independently verified the isolated executable hash, current operator -executable/config hashes, absence of both owned listeners and deletion of the -transient fixture credential. The controlled provider tests real host contracts, -not external-provider or model-obedience behavior. - -A bounded first-party lookup found [PR #46056](https://github.com/anomalyco/opencode/pull/46056), -which describes the same nested-decline problem and proposes explicit decline -propagation. Its API state is closed with `merged_at: null`; **this is not a merged -or released fix**, and no successor or supported released remedy is established -by that lookup. No upstream issue/comment, patch, version change or further host -experiment was performed. - -**Disposition:** `.2` blocked for owner/parent disposition of the code-mode -plain-decline path; task 1.1 remains unchecked and activation stays withheld. -Preserve the passing independent observations. Do not invent a local translator, -weaken the selected contract, silently disable code mode or choose another host -baseline. Later .6/.9 work, publication and activation remain separately gated. - -## Superseding owner disposition: accepted limitation, investigation pause - -Matt subsequently accepted the as-built code-mode continuation limitation while retaining composition. The failed stronger plain-decline/whole-step-termination observation above remains failed historical evidence; it is now an accepted host limitation rather than a demand for downstream repair or a supported upstream fix before shipping. Zero rejected-target execution, no plugin automatic retry, correction feedback, independent later-operation permissions and truthful persistence results remain required. Explicit Stop/Cancel is separate and still requires qualification. - -Task 1.1 is not checked or closed by this decision. Remaining qualification/activation is paused for bounded product investigation `opencode-beads-wgv`, including the separate product output-schema defect. No current host experiment, operator change, activation, source fix, publication or tracker closure is authorized. The existing 31-case evidence and cleanup remain intact. diff --git a/docs/opencode-installed-model-continuation-vuy9.md b/docs/opencode-installed-model-continuation-vuy9.md deleted file mode 100644 index 6b5a5de..0000000 --- a/docs/opencode-installed-model-continuation-vuy9.md +++ /dev/null @@ -1,112 +0,0 @@ -# Installed/model continuation — vuy.9, tasks 6.2–6.3 - -**The selected bounded 6.2 evaluation passes on worker evidence; 6.3 evidence reconciliation follows it. Parent acceptance is pending.** `.9` remains `in_progress / codex:oc-accept`; the original **14 accepted / 2 unchecked** task markers are unchanged. This report supplies no ordinary typed activation, release or publication authority. It adds genuine semantic evidence to the previously accepted source/native/Stop evidence and the parent-verified corrected lifecycle/resource observations. - -The original [failed qualification](opencode-installed-model-qualification-vuy9.md), [lifetime investigation](opencode-unload-lifetime-investigation-vuy9.md) and [corrected mechanics report](opencode-installed-model-qualification-vuy9-corrected.md) remain byte-identical. The old location-reload stronger probe remains **failed historical evidence**. It is not retroactively passing: routing replacement can retain an in-flight old graph, whereas this acceptance boundary observes actual plugin cleanup through native watched configuration. - -## Identity and installed boundary - -Execution: 2026-10-21 UTC, sole Sol/high worker `codex:oc-accept`, actual resumed session **`01a15ff1-fc4e-7d53-9b4d-2cb102cd4f76`**. **R** is `/opt/data/cache/scratch/vuy9-model-continuation`. Its complete assignment, authoritative native-auth override and original record are retained in `prompt.md`, `native-auth-resume-prompt.md` and `record-before.json`. The superseded Codex-auth paragraphs were not followed. - -| Surface | Observed identity | -| --- | --- | -| Repository HEAD / runtime source | `d5e2b172c3ab7106b2ea1a55af3725821f4b4d9a` / `8831169d3c83c333fdf13d4a4efc743eaf495e2b` | -| Released host / exact source | OpenCode **2.1.1** / `ba546ec1598a70db2570e9c6258028d955ba8f58` | -| Retained first-party executable | `/opt/data/cache/scratch/vuy2-oc-host/release/package/bin/opencode` | -| Executable / release archive SHA-256 | `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9` / `216d3861d0a167adad5850282439bae13483203f4b110f0510f260118bba2858` | -| Beads | **1.3.1**, commit `c1c4b642ac1c`; executable SHA-256 `a8f48d771b9e11eccfced4aed72923b59eda746f7a9b425e7ca1af7a51251653` | -| Accepted actual packed package | `R/archive/snarkipus-opencode-beads-1.0.2.tgz`, SHA-256 **`e952532140b44f812e2660425ec485d3bbd474962dd424ed03d70108593b259f`** | -| Genuine native route | **`openai/gpt-6.1-sol#high`**, ChatGPT backend `/backend-api/codex`; no provider/model substitution | -| Immutable internal bootstrap SHA-256 | `4520214eb4407eb8fab5dbe48866497be977933b8aa75ffc7300d91e1434cfbe` | - -`prepare.py` reverified retained release bytes, both registry signatures and 36 pinned source files; `additional-source-verification.json` verifies 16 relevant credential/compaction/replay blobs against the exact retained upstream tree. No source runtime was transplanted or patched. The disposable committed project/Beads database lives at `R/repo`, with isolated HOME/XDG config/data/cache/state and an explicitly constructed environment. Foreground native `serve` has the same relevant lifetime semantics as the managed service; no operator service was discovered or restarted. - -The unchanged 31-file accepted archive was packed through the existing `bun pm pack` path and installed through native `file:` package resolution. Its actual installed root is: - -```text -/opt/data/cache/scratch/vuy9-model-continuation/cache/opencode/npm/file:/opt/data/cache/scratch/vuy9-model-continuation/archive/snarkipus-opencode-beads-1.0.2.tgz/1792615248831/node_modules/@snarkipus/opencode-beads -``` - -`artifact.json` retains every content hash and the separate consumer install. Ordinary package setup supplies native command/skill/agent registries; ordinary typed registration remains withheld. For typed semantics only, the immutable `R/bootstrap/index.mjs` imports **this installed package's unchanged `src/host.ts`** and calls `setupBeads(..., {continuityQualified:true})`. Its only other changes transparently log/await the actual native permission assertions, hooks and returned cleanup. No runner, signal, asset, result, registry or provider replacement is supplied. This is an internal qualification dependency, **not an ordinary installed activation switch**. The CLI shim executes the real CLI with unchanged argv and can hold already-completed create output to exercise uncertainty; the real runner supplies the timeout. `bootstrap-identity.json`, `bin/bd`, `package.jsonl` and `bd.jsonl` disclose these differences. - -The archive was made before the later permitted README evidence edit. No new archive was built after documentation reconciliation; the qualified artifact remains the accepted hash above. - -## Native account access and model provenance - -The authority was the existing active OpenAI `credential` record in `/opt/data/.local/share/opencode/opencode-hermes-v2.db`, read using SQLite **`mode=ro` plus `query_only`**. Schema and targeted type/method/expiry/access/account metadata were selected; no other provider or refresh token was selected. The actual method is `chatgpt-headless`, expiry **2026-10-31 20:35:38.990 UTC**, with almost ten days remaining before inference. Native `POST /api/credential` imported current access and necessary metadata into the isolated database. The required refresh string was empty; no refresh capability was imported. Secret API input/output bypassed trace logging. - -`native-auth-before.json`, `credential-import.json`, `scratch-credential-state.json` and `native-auth-after.json` retain nonsecret provenance/digests. The selected source record and imported access/expiry stayed unchanged; **no refresh or rotation occurred**. The source DB was never opened for write or copied; no explicit lock, service stop or checkpoint was requested. Unrelated SQLite maintenance is outside the selected digest comparison. No Codex or legacy OpenCode auth file was read, converted or used. Private host logs/native DB/sidecars and server password were removed after sanitized exports. The exact native database opener creates/restricts its database and sidecars to mode 0600 (`packages/core/src/database/database.ts:79–97`); the harness also restricts scratch native files before inference, with a mode 0600 server password/private log. The earlier run's refresh/discard caveat remains historical; this continuation does not repair or overwrite it. - -`native-model-discovery.json` confirms enabled exact model/tool capability and the `high` variant before inference. `provider-model-provenance.json` and sanitized `native.jsonl` contain actual model request identities, outgoing frames and genuine returned provider frames. All **56 model requests** use the exact route/variant; **55** outgoing `response.create` frames say `gpt-6.1-sol` with `reasoning.effort: high`; the summary request uses actual HTTP and returns 200. There were no retry events, controlled-provider calls or alternative credentials in this continuation. These facts establish route execution, not model superiority. - -## Genuine semantic outcomes and actual records - -`semantic-review.json` gives the worker's evidence-backed judgments. Model descriptions are evaluated against actual native calls, real CLI outputs and persisted records; narration and an outer execute completion are never sufficient persistence evidence. - -| Case | Actual outcome and evidence | -| --- | --- | -| Design A: bounded graph | Two ready issues, declared `complete:false`; actual get preserves a nonexistent-ID failure. Concurrent `Promise.allSettled` edge reads preserve failed/unknown status, including empty edges with `complete:null`. Model returns useful title/blocker/unknown projection and makes no claim/write. `context-A.json`. | -| Design B: exact assignment | Actual typed claim of `repo-9se` acknowledges `opencode:accept:c991a47475e3`. Direct `python3 validate.py invalid` exits **1**, actual **9**, expected **8**, `pass:false`. Original seed notes survive start/measured/handoff appends; rationale, blocker and next scope remain. No specimen repair, closure or other ready task execution in that turn. `context-B.json`, `records-after-exact.json`. | -| Meaningful append versus memory | Direct-shell evidence append uses the same actual actor as typed claim/note. One acknowledged memory `vuy9.validation.invalid-mismatch` captures the reusable lesson to check process exit and semantic result together, rather than the whole transcript. Later model chooses/recalls it for numeric diagnosis and does not recall unrelated CSS. `final-memory-records.json`, fresh recovery context. | -| Failure discovery / uncertain create | One real create produced `repo-itw`, then its output was held and the runner returned **uncertain after 10,000 ms**. The model separately searched the exact title and got the generated ID, proving the real unassigned `discovered-from:repo-9se` record exists; it never repeated create. Search stays `complete:null`, not global uniqueness proof. `bd.jsonl`, `context-B.json`, `final-full-records.json`. | -| Newly authorized continuation | Only after the exact turn ended did a new prompt authorize `repo-onv` plus `repo-712`. Parent claims `repo-onv`, runs the valid specimen directly: exit **0**, actual/expected **16**, `pass:true`, then appends evidence. Unrelated `repo-mi8` remains open/unassigned; followup remains unassigned. `context-authorized-continuation.json`. | -| Actual native partial child | Installed `beads-task-agent` child `ses_e9fca26b1ffeMSPh6fUGoSKXLj` claims `repo-712` as **`opencode:beads-task-agent:d37cf66d75d5`**; typed/shell writes agree. Its actual invalid-specimen run exits1 with9/8/false. Durable note and normal native parent delivery retain attempts/rationale/validation/refs/unresolved next scope. Parent preserves partial/failed validation, leaves both tasks in progress and does not close or repair. Native session/context exports and final records substantiate this, rather than a fixture-supplied failed experiment. | -| Design C: fresh recovery | New actor **`opencode:accept:e5d28a79e8f5`** concurrently finds its own in-progress work (none, complete) and topic memories, projects keys first, then retrieves relevant records/lesson. It distinguishes found/nonempty from missing and does not infer ownership transfer. `context-fresh-recovery.json`. | -| Actual compacted recovery | Real native host summary compaction completes; model then performs fresh durable reads and keeps failure, original assignment and undecided repair scope explicit. No persistence is triggered by compaction. `context-native-compaction.json`, `context-compacted-recovery.json`. | -| Provider-native replacement replay | Public scratch-only `providers.openai.settings.compaction.type=native`, confirmed in actual catalog, produces a real completed encrypted `native.messages` window with empty summary. The next actual request sends the same checkpoint digest, then uses provider continuation IDs and recovers by real reads on the same Sol/high route. `context-provider-native-compaction.json`, `native.jsonl`, `context-provider-native-recovery.json`. No replacement result was manufactured. | -| Remaining design D | Noexecute/noshell agent honestly reports no current lookup capability, with no tool bypass. Selective typed note hits actual canonical `bd update` denial; no target process/text persists, no retry or dependent write; independent get succeeds. `context-noexec.json`, `context-selective-denial.json`, `package.jsonl`, `bd.jsonl`. Prior genuine execute-denied shell fallback is reused. | -| Final command restoration | Actual watched-config override add/remove converges to ordinary ready description, all 30 unique commands and same installed skill. Both membership and description are awaited; `command-restoration.json` resolves the old inconclusive sample with new evidence, without changing it. | - -For all three executed fixture tasks, `created_by=codex:oc-accept` and `owner=scratch@example.invalid`; primary/child assignees are the distinct actual actors above. The discovered followup has `created_by=opencode:accept:c991a47475e3`, the same separate account owner and no assignee. The current fresh actor inherits neither assignment nor permission. `native-sessions.json`, actual permission assertions and `final-full-records.json` preserve these distinctions. All five records remain open/in-progress as appropriate. Diagnostic acceptance means the failed validation was discovered and handed off honestly; **the invalid specimen is still failing** and repair/closure is unresolved work outside this evaluation's authorization. - -## Reused lifecycle, access and replay limits - -The [corrected report](opencode-installed-model-qualification-vuy9-corrected.md) retains the one actual installed watched-config removal/reactivation. Actual ordinary setup cleanup completes at `1792613744.282`; its pending context returns at `.283` with zero Beads envelopes; actual provider request at `.287152` has zero. The held real prime process was aborted by unchanged product cleanup while the harness hold marker remained. Reactivation restores owned registrations once under preserved user overrides; one eligible request receives one envelope. All 17 installed resource links were read through native direct `read`, with17 ask acceptances plus separate ask rejection and deny without bypass. Parent independently verified64 offline checks; those campaigns were not repeated. This continuation only rechecks installed link hashes and settles the previously premature command-description sample. - -Accepted [source/CLI](code-mode-source-acceptance-vuy10.md), [15-case native qualification](opencode-host-codemode-qualification-vuy2.md) and [74-check Stop/handoff](opencode-stop-handoff-qualification-vuy6.md) are consumed without rerunning191 tests,63 CLIcases,15 nativecases or74 Stopchecks. They supply changed-default identity, failed/cancelled/NO_TEXT/late-child/Stop, retained summary/fork/keepID/recent, CLI commit/empty-memory and provider/model mismatch mechanics where this representative model run does not repeat them. Nested plain decline's stronger termination failure remains an owner-accepted host limitation, separate from Stop. - -Actual provider-native replay here is **same OpenAI provider/model/high only**. Exact pinned public docs say encrypted checkpoints are not portable to a different provider/model; the host can rebuild original history on mismatch. No cross-provider/model migration was executed or certified, no extra account/model was invoked, and no fabricated native window was used to claim such a pass. Changed-route mechanics retain their accepted source-evidence classification. This bounded result also does not certify multi-hour transport reliability, comparative model quality or token savings. These limits do not become stronger selected requirements or an activation authorization. - -## Requirement and corpus reconciliation (6.3) - -All **19 normative requirements** have explicit evidence mappings in `requirement-coverage.json`; every row distinguishes genuine new measurements from accepted source/CLI/host/Stop mechanics. There is no unresolved selected semantic/lifecycle/access outcome in this bounded candidate. Owner acceptance, ordinary typed enablement and broader unmeasured runtime claims remain separate gates. - -| Normative requirement | Selected case / reused boundary | Evidence coverage | -| --- | --- | --- | -| Relevant upstream source comparison | reusedaccepted 5.1 | Existing reviewed exact source/inventory/check evidence consumed; no comparison campaign, CLI-upgrade or baseline advancement. | -| Check-based review notification | reusedaccepted 5.1 | Accepted check fixtures/informational main-vs-tag distinction consumed unchanged; no issue dispatch/release inference. | -| Explicit baseline disposition | reusedaccepted 5.1;inventory-coverage.json | Existing owner-selected full inventory dispositions retained; source identity/corpus mapping maintained, no automatic adoption. | -| Meaningful progress checkpoints | B;authorized-continuation | Actual initial/measured/final append checkpoints preserve prior notes, failed experiment/rationale/blocker/nextscope; child partial note; accepted CLI/source append semantics. | -| Relevant reusable knowledge | B;fresh-recovery | Actual reusable validation lesson acknowledged, relevant key selected/recall; unrelated CSS not recalled; missing explicit; landed-uncommitted/empty contracts reused accepted CLI/source. | -| Recovery from durable state | fresh-recovery;compacted-recovery;provider-native-recovery | Fresh and compacted actual durable reads preserve failed attempts/ownership; retained/fork mechanics reused .6. | -| Delegated knowledge and closure evidence | authorized-continuation | Actual native child runs failed diagnostic and returns meaningful partial durable handoff, parent does not close or infer success; failure/cancel/NO_TEXT/Stop interleavings reused .6. | -| Native trigger and semantic responsibility separation | native-compaction;provider-native-compaction;provider-native-recovery | Real summary and encrypted native compactions preserve failure references; no persistence in compaction, no fabricated provider window; actual matching replay observed; changed-provider/model and keepID/recent/fork mechanics reused accepted source/.6, no new migration claim. | -| Honest persistence acknowledgement | B;selective-denial | Real landed create acknowledgment lost -> uncertain -> actual search/get, no retry; denied target never spawns; accepted source/CLI commit/cancel distinctions reused. | -| Typed daily-loop composition | A;B;fresh-recovery;D | Actual catalog signatures, bounded allSettled projection/partial unknowns, ordered claims/writes and current relevant reads; all 11 operation contract/source/native prerequisite reused. | -| Discoverable selected workflows | command-restoration;reused17 resources;reusedfallback | 30 native commands,17 installed links including CODE_MODE; all native resource reads and ask/reject/deny reused; no claim29advanced command semantic trials. | -| Coherent context and authority | A;B;authorized-continuation;fresh-recovery | Model obeys exact versus newly authorized scope, failures/ownership visible; source unique policy/guard mechanisms reused. | -| Owned installation and user customization | reusedcorrectedLifecycle;command-restoration | Actual installed unchanged ordinary package cleanup/reactivation under user overrides reused; final ordinary command description now settled; original failed proxy retained. | -| Scope-preserving execution and visible failure | B;authorized-continuation;D | Readiness not authority, genuine failed validation/childpartial retained; no repairs/closure/unrelated execution; actualStop source/host evidence reused. | -| Explicit native availability and fallback | reusedfallback;noexec | Real2.1.1 catalog; ordinary typed withheld; qualificationbootstrap explicit; prior genuine shell fallback; no-execution admits inability. | -| Restricted-agent typed operation boundary | noexec;selective-denial;reused17 resources | Actual noexecute/noshell capability and selective canonical shell deny; resource ask/reject/deny; actual permission assertion identity. | -| Authorized continuation without scope expansion | B;authorized-continuation | Exact turn stops, new scopedtwo-item batch claims only designated tasks, childownactor; unrelatedready and followupunassigned remainuntouched. | -| Read-only native diagnostics | registry-ordinary-baseline;registry-final;reusedsource/native | Existing status/diagnostic/source/host accepted evidence reused; native registry snapshots do not open/repair project database; no new all-operation modelcampaign. | -| Capability-aware actor and context guidance | B;authorized-continuation;noexec;selective-denial | Actual current/child/fresh request actors, typed/shell agreement, audit/account/assignee distinctions and unavailable leaf capabilities. | - -`inventory-coverage.json` maps **every 73 historical-release and 74 selected-marketplace-main member**, retaining its original disposition, delivery target and task IDs. It includes all 29 workflow names plus status, all 15 adapted corpus resources, project-owned CODE_MODE and ADR: **30 commands /17 links**. The original inventory hash/dispositions remain unchanged. Full resource delivery/access is measured; representative A–D semantic outcomes are measured. Reference/build/admin/CLI-only mappings are not silently converted into claims that all operations or upstream Claude behavior were executed. Relevant source comparison/check/baseline evidence remains the accepted 5.1 evidence, without a new benchmark or drift campaign. - -Current summaries only were reconciled in README, SDK contract, native assessment, Claude local reference, integration analysis and artifact policy. Their detailed historical evidence/reviews remain intact. No source, tests, assets, package/lockfile, validator, OpenSpec/owner-decision or shared operator integration was edited. The task file remains 14checked/2 unchecked. - -## Measurements, retained failures and cleanup - -`measurements.json` separates actual UTF-8 prime (**5,714–6,387 bytes**), appended guidance (**3,234–7,863**), catalog system text (**0 or 16,618**, absent where execute is unavailable), direct schemas (**9,876–12,471 compact JSON bytes**), returned signature catalog text, and returned tool content/results. Returned text ranges **0–19,322 bytes**; whole result JSON **4–40,978 bytes**, including wrapper/metadata duplication. These are individual observed byte categories, not incremental network transmission, token savings or semantic quality measures. All 54 observed eligible qualification context returns contain one Beads envelope; the reused unloaded-generation return remains zero. - -Captured processes/calls: **one native host**, **231 CLI shims +231 real CLI children**, **16 primes**, **7 direct shell calls**, **40 typed leaf calls**, **one actual native child**, **56 genuine model requests**, **zero controlled provider processes/requests** in this root. Counts include initialization/seeding/guard/evidence reads, are not quotas, and exclude uninstrumented `ps` helpers/startup internals; they are not a total OS census. - -Two harness errors are retained separately from product outcomes: initial memory seeding used two unsupported positional arguments; the actual CLI refused it and `seed-correction.json` records supported `--key` correction. Initial cleanup deleted a parent, whose native cascade also deleted its child; the stale cleanup list then got a real404. `cleanup.initial.log` and `cleanup-harness-correction.json` retain this; final cleanup used actual remaining inventory. Neither is relabeled as a product defect or repaired source. The first focused documentation check also failed one retained vendoring-sentence assertion (13 pass/1 fail); the permitted current summary was corrected without changing tests, and the repeated focused check passed 14/0. Its initial log remains `validate-docs.initial.log`. - -`cleanup.json` verifies zero pending/active/saved/remaining sessions/grants, owned server group **781500** stopped, no listener on **53205**, and none of **462 captured shim/CLI PIDs** live. Private native database/sidecars, host log and server secret are removed. Source credential/current access digest and expiry match before/after, no refresh token was selected, no normal or manual OAuth refresh occurred. Known operator executable/config/package files and OpenCode 2.0.29 are unchanged. All 149protected repository paths and all prior evidence path/byte sets (**345 original,72 lifetime,386 corrected files**) match; only the six authorized summaries and this new report differ. No publication, tracker closure, marker or source repair occurred. - -Offline reproduction: `python3 R/analyze.py` validates raw observations without host/account/network access. The final analyzer includes explicit semantic-review consistency; passing asserts evidence consistency rather than independently proving model judgment or owner acceptance. Strict named/all OpenSpec, planning, docs/link/whitespace checks and final protection hashes are retained in `validation.json` and `protection-final.json`; source full-suite tests were not rerun. `case-map.json` keeps new/reused/historical-failed/harness-failed/unmeasured categories distinct. - -**Smallest next gate:** parent independently reviews this bounded 6.2 evidence and 6.3 reconciliation, then decides acceptance and the two remaining markers. Ordinary typed activation, commit/push/sync/closure/archive/release remain separately parent-owned. Scratch final handoff: `R/result.md`. No automatic continuation follows. diff --git a/docs/opencode-installed-model-qualification-vuy9-corrected.md b/docs/opencode-installed-model-qualification-vuy9-corrected.md deleted file mode 100644 index 5c3d956..0000000 --- a/docs/opencode-installed-model-qualification-vuy9-corrected.md +++ /dev/null @@ -1,95 +0,0 @@ -# Corrected installed acceptance — vuy.9 - -**Actual plugin-scope cleanup/removal/reactivation passed its controlled native observation. Task 6.2 remains incomplete: existing OpenAI access is expired, so the remaining genuine-model evaluation was not run. Task 6.3 was not started.** One final command-restoration snapshot also remains inconclusive, as detailed below. No passing analyzer exit substitutes for these selected gaps. - -The owner clarification in [owner decisions](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md) authorizes this corrected probe boundary. The [original location-reload failure](opencode-installed-model-qualification-vuy9.md), [lifetime diagnosis](opencode-unload-lifetime-investigation-vuy9.md) and both prior raw evidence trees remain byte-identical. Their historical failure is not relabeled passing. - -## Identity, artifact and credential gate - -The sole worker remains `codex:oc-accept`, actual session **`01a15ff1-fc4e-7d53-9b4d-2cb102cd4f76`**, Sol/high. HEAD is `d5e2b172c3ab7106b2ea1a55af3725821f4b4d9a`, accepted runtime source `8831169d3c83c333fdf13d4a4efc743eaf495e2b`. Scratch root **R** is `/opt/data/cache/scratch/vuy9-corrected-acceptance`. Authority/preimages are `prompt.md`, `record-before.json` and `protected.json`; the parent's dirty owner-decision clarification is protected. - -The existing pack/install path reproduced archive **`e952532140b44f812e2660425ec485d3bbd474962dd424ed03d70108593b259f`**, `snarkipus-opencode-beads-1.0.2.tgz`. Both consumer and native installations contain the same 31 accepted files. `artifact.json` identifies every file/hash and both install paths. The native root was: - -```text -/opt/data/cache/scratch/vuy9-corrected-acceptance/cache/opencode/npm/file:/opt/data/cache/scratch/vuy9-corrected-acceptance/archive/snarkipus-opencode-beads-1.0.2.tgz/1792613743027/node_modules/@snarkipus/opencode-beads -``` - -The retained released OpenCode **2.1.1** executable SHA-256 remains `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9`; its first-party archive hash, both registry signatures and 36 retained source-file SHA-256/Git-blob identities were reverified at source **`ba546ec1598a70db2570e9c6258028d955ba8f58`**. Beads is **1.3.1**, commit `c1c4b642a`, executable SHA-256 `a8f48d771b9e11eccfced4aed72923b59eda746f7a9b425e7ca1af7a51251653`. This retains the prior release provenance without claiming reproducible builds. - -Before inference or credential import, only the authorized existing OpenAI OAuth type/expiry metadata and nonsecret file provenance were inspected. `auth-gate.json` records expiry **2026-09-18 17:26:59.021 UTC**, checked **2026-10-21 20:13:38.090 UTC**. Access was already expired, independent of the 30-minute reserve selected for a bounded run. **No access/refresh value was selected, copied, imported, printed or submitted; no refresh, login, credential repair/writeback or real-model call was attempted.** Native scratch credential-table rows were zero. Original credential bytes, mode, size, inode, mtime and ctime match after cleanup. - -The previously observed genuine `openai/gpt-6.1-sol/high` route and its passing read-only fallback remain reusable evidence. They do not establish current authentication or the unexecuted semantic cases. No other account credential, provider or model was substituted. The local controlled provider below supplies explicit mechanics-only responses and is never described as genuine model evaluation. - -## Corrected actual lifecycle observation - -The real released foreground server used isolated HOME/XDG/state/cache, a committed disposable project/Beads store and **enabled native file watching**. The lifetime diagnosis already established shared Core semantics with the default managed service; no managed startup comparison or operator service action was performed. - -The initial baseline loaded the unchanged archive normally and captured actual plugin, command, skill and agent registries. A minimal immutable scratch wrapper then imported the **installed `src/plugin.ts` default export**. It calls ordinary `setup`, transparently logs context-hook entry/return, and calls/awaits the actual returned cleanup. `wrapper-identity.json` records its hash and exact difference: generation/timestamp observation only. It supplies no qualification dependency, runner, abort signal, replacement result, asset path or registry. Ordinary typed activation stays withheld; the internal `continuityQualified` bootstrap was not activated because the genuine-model path stopped at the auth gate. - -All transitions used atomic edits of the harness-owned watched config and native activation in the **same location graph**. `/api/location/reload` was never called. Observer generation **`2ec4c7fe-9339-4b69-aad7-f66dfb930ec9`** remained constant through the live cases, with zero `location.shutdown` events before cleanup. Product generation IDs are distinct from that observer identity. - -| Epoch seconds | Actual observation | -| --- | --- | -| `1792613743.9845989` | Real `bd prime --full` output is held by shim PID/group `776323`. | -| `1792613744.281` | Removed product generation `73d72bb3-8d3d-40b2-b7a9-e1e3df66e70d` logs actual cleanup start. | -| `1792613744.282` | Awaited actual package cleanup completes. | -| `1792613744.283` | Its pending context callback returns with **zero Beads envelopes**. | -| `1792613744.287152` | Actual request to the local controlled provider contains **zero Beads envelopes**. | -| `1792613744.667–.668` | Reactivated generation `010c390c-0a8b-497f-bfa2-5307f25dac34` starts/completes ordinary setup. | -| `1792613745.227` | One eligible post-reactivation context returns with **one Beads envelope**; its actual provider request also contains one. | - -The held process was aborted by accepted product cleanup while the harness hold marker still existed; the harness did not release output or kill that process to manufacture suppression. The shim ran the real CLI with unchanged argv and held only its already-completed prime output. No prime/provider result was fabricated or suppressed by the wrapper. `package.jsonl`, `bd.jsonl`, `native.jsonl`, `provider.jsonl` and `lifecycle-result.json` retain the actual chronology. - -Ordinary and transparent baselines each expose 30 unique namespaced commands and the installed skill. Under user command/skill overrides, removal leaves only the user namespaced command/skill and removes the owned task agent. Reactivation restores 30 distinct names and the agent once while preserving those overrides. These are actual native registries, not fixture reconstruction; `registry-ordinary-baseline.json`, `registry-with-user-overrides.json`, `registry-removed.json` and `registry-reactivated-user-overrides.json` retain them. - -**Inconclusive final override-deletion sample:** after the harness removed its test overrides, `registry-restored.json` shows the package skill again but still shows the user command description. The final wait predicate checked skill convergence and command membership but omitted command-description convergence. Offline validation caught that omission. The initial analyzer failure is retained in `analysis.initial.log`; the mixed snapshot is explicitly asserted as unresolved in the corrected analyzer. No new pass for final command restoration, product defect or permanent precedence failure is inferred. Prior accepted override-removal observations remain separate evidence. This does not undo the measured actual cleanup and reactivation under preserved overrides, but final in-place command restoration still needs a settled observation. - -## Installed resource access - -All **17** explicit skill links resolve inside the accepted installed package, including 15 corpus resources, CODE_MODE and ADR rationale. Each was read successfully through the actual native **direct `read` tool**, with `external_directory: ask` accepted once per read and no saved grant. All returned native read results report `truncated:false`. A separate ask rejection returns `executed:false` with the native decline error; a configured external-directory deny returns `executed:false` with `permission.rejected` and no approval prompt. Neither case uses another path or reader to bypass refusal. - -`installed-links.json` records exact paths, archive-content hashes and file bytes; `resources-result.json` maps successful native call/session IDs and denied tool states. These are access mechanics, not evidence of model relevance judgment or comprehension. - -An initial harness attempt incorrectly called `tools.read` inside execute. Its actual search result did not expose that path; the programs returned genuine unknown-tool errors and performed no local reads. Those failed traces remain in `resources.log`/`cases.jsonl`. `direct-read-schema.json` records the real provider-visible direct tool contract used by the corrected calls in `resources-direct.log`. No product change, invented catalogue signature or successful replacement result was introduced. - -## Coverage and selected gaps - -`case-map.json` labels new controlled observations, reused genuine/mechanical evidence, initial harness failures and unresolved cases. The source 191-test, CLI 63-case, native 15-case and Stop 74-check campaigns were consumed without rerun. The owner-accepted plain-decline limitation and the original stronger location-reload failure remain separate historical failed observations. - -The following is an **incomplete acceptance evidence inventory**, not task 6.3 reconciliation or owner acceptance. `requirement-coverage.json` retains all 19 exact normative titles and unresolved selected guarantees; `inventory-coverage.json` enumerates all 29 workflow names plus status and all 17 installed links. The existing reviewed corpus dispositions remain unchanged; no advanced/admin member was dropped or operation executed implicitly. - -| Normative requirement | Evidence and remaining gate | -| --- | --- | -| Meaningful progress checkpoints | Accepted source/CLI mechanics reused; actual-model meaningful append remains auth-blocked. | -| Relevant reusable knowledge | Accepted memory contracts reused; model selection, remember/recall relevance unresolved. | -| Recovery from durable state | Accepted source/Stop retrieval reused; fresh/compacted semantic recovery unresolved. | -| Delegated knowledge and closure evidence | Prior native child outcomes reused; genuine failure discovery/partial child judgment unresolved. | -| Native trigger and semantic responsibility separation | Source/Stop/lifetime boundaries retained; semantic recovery/provider-model interpretation unresolved. | -| Honest persistence acknowledgement | Accepted deterministic/CLI/Stop outcomes retained; selected model uncertain-create readback unresolved. | -| Typed daily-loop composition | Accepted eleven-operation/source/host evidence reused; model workflows A–C, projection/completeness/partial outcomes unexecuted. | -| Discoverable selected workflows | 30 native entries and 17 successful native resource reads; selected workflow semantic outcomes still partial. | -| Coherent context and authority | Source/fallback evidence reused; full selected model behavior unresolved. | -| Owned installation and user customization | Actual cleanup/removal/reactivation and preserved overrides measured; final in-place command restoration sample inconclusive. | -| Scope-preserving execution and visible failure | Genuine read-only fallback reused; exact assignment/continuation/partial failure semantics unresolved. | -| Explicit native availability and fallback | Exact host/source pins and prior genuine fallback retained; no ordinary typed enablement claimed. | -| Restricted-agent typed operation boundary | Accepted host/Stop evidence reused; native resource refusal measured; remaining installed/model capability cases unresolved. | -| Authorized continuation without scope expansion | Source/Stop evidence retained; genuine bounded batch versus exact assignment unresolved. | -| Read-only native diagnostics | Accepted source/native evidence retained; no new model diagnostic acceptance claimed. | -| Capability-aware actor and context guidance | Source and genuine fallback actor retained; actual-model typed/shell primary/child agreement unresolved. | -| Relevant upstream source comparison | Prior accepted deterministic/inventory evidence consumed; no comparison campaign rerun. | -| Check-based review notification | Prior accepted source/check evidence consumed; no new compatibility or release claim. | -| Explicit baseline disposition | Existing reviewed baseline/dispositions preserved; no automatic advancement. | - -In particular, no fixture-supplied narrative qualifies meaningful work, a failed experiment, child reasoning, ownership agreement or compaction recovery. **Design A–C and remaining D/continuation/memory/child/recovery/actor/uncertain-create/replay semantics are unexecuted at the required genuine model boundary.** Task 6.2 cannot pass from the mechanics above; task 6.3 and its six current-summary document edits remain gated. - -## Measurements, cleanup and next gate - -`measurements.json` separates prime, appended guidance, stock host catalogue and returned-result bytes. The suppressed pending request has zero prime/guidance bytes and zero Beads envelopes. A normal post-reactivation context contains **5,714 prime bytes**, **7,621 guidance bytes**, and **13,292 stock catalogue bytes**; that catalogue is not a qualified Beads typed catalogue. Successful resource reads return **1,501–5,631 text bytes** each, with full JSON-result sizes separately retained. No token-saving, transmission or model-quality claim follows. - -There were **76 shim processes and 76 real CLI children**, including initialization and ordinary version/context/prime probes across resource sessions; **25 prime processes**, one host, one local provider, **47 controlled provider requests**, **zero genuine-model requests**, zero typed Beads invocations and zero native children. These are captured counts, not quotas, a benchmark or a total-OS-process census; runner `ps` helpers/startup internals were not instrumented. - -`cleanup.json` confirms empty active sessions, pending permissions and saved grants; owned sessions removed; host group **776177** and provider group **776176** stopped; no listeners on **46727/39321**; and no live process among all **152** recorded shim/CLI PIDs. Transient server-only credentials, private native logs and native DB/sidecars were removed. No real credential material ever entered scratch. Known operator executable/config/package bytes remain unchanged, operator OpenCode remains 2.0.29, and authorized auth bytes/metadata match before/after. All **148 frozen repository paths**, including the owner clarification and both old reports, remain unchanged; both prior evidence trees retain their complete byte/path sets. Only this corrected report is added. README and the five permitted current-summary docs remain unchanged. - -Offline reproduction uses `python3 R/analyze.py`. The analyzer verifies actual cleanup ordering, request contents, resource outcomes, the mixed final snapshot and explicit auth-blocked verdict; success means the evidence assertions agree, **not** that 6.2 passes. Appropriate strict named/all OpenSpec, planning, focused docs/link/whitespace validation is retained in `validation.json`. The unchanged source full suite was not rerun. - -**Smallest next gate:** parent reviews the corrected mechanics and unresolved snapshot, then arranges valid existing operator-managed OpenAI access and explicitly resumes the remaining 6.2 genuine-model evaluation, including a settled final override-restoration read. This worker did not refresh or repair credentials, request secrets, waive a guarantee or authorize itself to continue. `.9` remains `in_progress / codex:oc-accept`; 14 accepted / 2 unchecked markers remain. Parent owns acceptance, task markers and any commit/push/sync/closure/archive/publication/activation/release. Final scratch handoff is `R/result.md`. diff --git a/docs/opencode-installed-model-qualification-vuy9.md b/docs/opencode-installed-model-qualification-vuy9.md deleted file mode 100644 index 1767c06..0000000 --- a/docs/opencode-installed-model-qualification-vuy9.md +++ /dev/null @@ -1,79 +0,0 @@ -# Installed-package / real-model qualification — vuy.9 - -**Task 6.2 failed a selected lifecycle guarantee and remains incomplete. Task 6.3 was not started.** On the released host, an actual request waiting for package-owned prime output sent a late Beads context to OpenAI after the package had disappeared from the native registries. Passing registry restoration and earlier source/host/Stop evidence do not satisfy that guarantee. No source repair, changed acceptance contract or activation is authorized by this report. - -## Candidate, identity and evidence - -The sole worker was `codex:oc-accept`, actual Codex session `01a15ff1-fc4e-7d53-9b4d-2cb102cd4f76`, gpt-6.1-sol/high. Repository HEAD was `d5e2b172c3ab7106b2ea1a55af3725821f4b4d9a`; accepted runtime source was `8831169d3c83c333fdf13d4a4efc743eaf495e2b`. Evidence root **R** is `/opt/data/cache/scratch/vuy9-installed-model`. `prompt.md`, `record-before.json`, `identity.json` and the parent-frozen `protected.json` retain authority and provenance. - -The reused first-party OpenCode executable is `/opt/data/cache/scratch/vuy2-oc-host/release/package/bin/opencode`, version **2.1.1**, SHA-256 `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9`. Its retained archive SHA-256 is `216d3861d0a167adad5850282439bae13483203f4b110f0510f260118bba2858`. SHA-512 SRI, SHA-1, both registry signatures, and all 36 previously retained source-file SHA-256/Git-blob identities were reverified. Additional inspected provider/lifecycle files were checked against the retained official tree at **`ba546ec1598a70db2570e9c6258028d955ba8f58`**. This reuses release provenance, without asserting reproducible-build equivalence. Beads was **1.3.1**, commit `c1c4b642a`, executable SHA-256 `a8f48d771b9e11eccfced4aed72923b59eda746f7a9b425e7ca1af7a51251653`. - -The existing `bun pm pack --destination R/archive --quiet` path produced `snarkipus-opencode-beads-1.0.2.tgz`, SHA-256 **`e952532140b44f812e2660425ec485d3bbd474962dd424ed03d70108593b259f`**, matching accepted source acceptance. Both the scratch consumer installation and native host installation contain the same 31 files, each byte-identical to the repository preimage. `artifact.json` records the entire content manifest and both exact install paths. The native installed root was: - -```text -/opt/data/cache/scratch/vuy9-installed-model/cache/opencode/npm/file:/opt/data/cache/scratch/vuy9-installed-model/archive/snarkipus-opencode-beads-1.0.2.tgz/1792611344357/node_modules/@snarkipus/opencode-beads -``` - -All qualifying package behavior below used the **ordinary, unchanged packed package** through native `file:` archive installation. Its privileged typed path remained withheld. A minimal immutable bootstrap importing this installed `src/host.ts` with the existing `continuityQualified:true` dependency was prepared but **never activated**: no typed qualification ran before the lifecycle failure. It did not bundle a different source candidate, replace assets or alter the installed package. `bootstrap-identity.json` preserves that unused preparation and its distinction from ordinary installation. - -The [accepted source report](code-mode-source-acceptance-vuy10.md), [native-host report](opencode-host-codemode-qualification-vuy2.md), [original host evidence](opencode-host-qualification-vuy2.md) and [Stop/handoff report](opencode-stop-handoff-qualification-vuy6.md) were consumed. The 191 source tests, 63 CLI cases, 15 native follow-up cases and 74 Stop checks were **not rerun**. Their source/mechanical results do not establish missing model semantics. The owner-accepted plain-decline continuation failure remains historical failed evidence, separate from explicit Stop. - -## Real route and isolation - -Before inference, native `/api/model` discovery established `providerID:"openai"`, model/modelID `gpt-6.1-sol`, tool support and the `high` variant. Its package was `@opencode/ai/providers/openai`, with native ChatGPT/Codex base URL `https://chatgpt.com/backend-api/codex`. Actual outbound WebSocket `response.create` frames used that model and `reasoning.effort:"high"`; actual completed provider frames and native assistant results are retained. There was no OpenRouter, controlled provider, fallback model or supplied model answer. Returned native service tier was `default`; high describes reasoning, not service tier. - -The operator's existing OpenAI OAuth entry alone was copied programmatically into mode-0600 scratch material, after reading the exact native credential/global-path/import contract. Supported native `POST /api/credential` imported it into the disposable database. Native refresh changed the scratch access and refresh tokens and advanced expiry before successful inference. No manual token exchange, login or operator migration occurred. `operator-auth-before.json`, `auth-provenance.json` and `operator-auth-after.json` record nonsecret evidence. **Operator auth bytes, inode, mode, size, mtime and ctime remained unchanged. Refreshed scratch credentials were discarded, never written back over operator auth.** This does not assert that an old operator refresh token remains usable after rotation. - -The host used isolated HOME/XDG/cache/state, committed disposable `R/repo`, its own Beads store and only loopback port **56167**, owned process group **767999**. Harness-created tasks used explicit `--actor codex:oc-accept --sandbox`; their creator, disposable account owner and absent assignee were kept distinct. The model made no issue writes, claims or handoffs. Its actual fallback identity was `opencode:fallback:44e5ef89b5cd`, derived from native session `ses_ea007a134ffer7ErRF24VMZokT` and agent `fallback`. - -An independent scratch observer recorded actual context, tool events, model selection and native transport frames without replacing requests, responses, compaction or tool results. Sanitized `native.jsonl`, `api.jsonl`, `cases.jsonl` and `bd.jsonl` preserve observations. The `bd` logging shim executed unchanged argv against the real CLI. Its only timing intervention held already-completed `prime --full` output until an owned marker was removed, before the normal runner timeout. It supplied no replacement prime text, CLI result or provider response. The unused create-output hold was never exercised. - -## Observed case map - -| Case | Actual result and limit | -| --- | --- | -| Ordinary installed command / design D fallback subset | **PASS.** Native `oc-beads:ready` forwarded the read-only request. With execute denied, the real model loaded the installed skill, read WORKFLOWS, checked current help and invoked direct shell. It reported two of four ready issues with incomplete coverage, no execution authority, separate creator/owner/assignee observations and its actual actor. No issue mutation, delegation or unrelated continuation occurred. | -| Settled native registries | **PASS.** Thirty distinct namespaced commands and the installed skill were effective. User command/skill overrides won. Unload left only the user-owned `oc-beads:ready` and user skill; product agents disappeared. Reactivation restored package entries once while preserving overrides. Removing only the harness-owned overrides restored package descriptions/path. Before/after command/skill/agent/plugin snapshots are `registry-*-settled.json`. | -| Pending-generation output after removal | **FAIL, selected acceptance.** The real prime process was held before unload. The package was absent from the settled plugin registry, product commands/agents were absent and its skill was replaced by the preserved user skill. Releasing the held output then produced a Beads context in the still-running request and an actual outgoing OpenAI request. The held process had remained alive until release. | -| Post-reactivation context | **PASS.** One eligible request received exactly one Beads envelope and one actual model response. This does not erase the preceding failure. | -| Seventeen installed links | **Filesystem PASS; native access partial.** All 17 explicit links resolve inside the unchanged native installation, with bytes/hashes in `installed-links.json`. Native skill loading and WORKFLOWS reading were observed, including one accepted `external_directory: ask` request. Native reading of every other resource, ask rejection and deny remain **unexecuted**. | -| Provider/native replay | **Limited observation.** Genuine same-provider/model requests and native reasoning/replay metadata were observed; encrypted payload fields are sanitized. No compaction, provider/model switch or replacement `native.messages` was manufactured. Their remaining semantic acceptance is unresolved. | - -The decisive settled timeline is retained in `failure.json` and the raw traces: - -| UTC epoch seconds | Observation | -| --- | --- | -| `1792611636.0914652` | Real `bd prime --full` completed; shim PID/group `769512` holds its unmodified output. | -| `1792611636.3046305` | Native registry shows only the user namespaced command; adjacent settled plugin/skill/agent snapshots confirm package removal. | -| `1792611636.338` | After the harness releases output, the in-flight context event contains one Beads envelope. | -| `1792611636.665` | Actual WebSocket `response.create`, OpenAI gpt-6.1-sol/high, includes that envelope. | - -The selected guarantee fails at the outgoing request boundary, independently of the model's simple lifecycle reply. This is installed host/package lifetime evidence; precise upstream-versus-adapter causation was not established. A request continuing across native location reload is not reclassified as explicit Stop failure, and no upstream patch, new supervisor or compensating lifetime framework was attempted. - -Registry snapshots and observer setup/dispose events are retained. The ordinary package's individual disposer invocation counts are not public native observations here; none was invented. In particular, registry removal is not treated as proof that the pending package process had already been aborted. - -The remaining design **A–C** typed composition/projection/partial-failure cases, meaningful append versus selective reusable memory, exact assignment versus authorized continuation, actual-model failure discovery/partial child handoff, fresh/compacted recovery, typed/shell actor agreement, restricted leaf/neither-capability outcomes and uncertain-create readback are **unexecuted selected acceptance gates**. Earlier deterministic/mechanical passes do not complete them. `case-map.json` maps every attempted case and these gaps. Task 6.3's current-summary changes and final 19-requirement/corpus/CODE_MODE coverage reconciliation remain gated; none was marked complete. - -## Measurements and harness corrections - -`measurements.json` separates UTF-8 prime/guidance/catalog text bytes, compact-JSON direct tool schemas, returned result JSON and returned text. Per fallback request, prime was **5,714 bytes**, appended guidance **7,624**, code-mode catalog **0** and direct schemas **11,360**. Lifecycle requests had prime **5,714**, guidance **7,622**, stock host code-mode catalog **13,192–13,272** and direct schemas **12,483**. That stock catalog is not a qualified Beads typed catalog. Returned text bytes were skill **10,679**, WORKFLOWS read **3,965**, shell help **6,125**, and ready output **1,444**; full result JSON sizes are recorded separately. No transmission, token-saving or model-quality inference follows from these sizes. - -Captured processes were **22 shim invocations plus 22 real CLI children**, including initialization, four harness task creations, version/context/prime probes and two model-selected shell commands. There was one additional direct real-CLI final readback, separately disclosed from shim counts. The runner's own `ps` helpers and process-wide startup internals were not instrumented; this is not a total-OS-process census. There were **eight actual model request frames**: four fallback steps and four lifecycle replies across initial and settled runs; **zero typed calls and zero native children**. These are measured counts, not quotas or a benchmark campaign. - -Initial setup failures remain distinct from product findings. An absolute installed-directory reference had no native server entry point; the supported native `file:` archive path resolved the package without editing it. The initial scratch database contained no imported legacy credential row; the supported native credential-create route supplied only the existing scoped OpenAI credential. Early model/registry snapshots were taken before asynchronous settlement. The first lifecycle run similarly sampled premature empty registries, so its unsuffixed snapshots are **inconclusive**, not passing removal proof. The one bounded correction waited for observable effective registries at each stage; it confirmed the late-output failure. `run-fallback.log`, `run-lifecycle.log` and `run-lifecycle-settled.log` retain those runs. No inferred API output or silent successful retry was substituted. - -## Offline verification, cleanup and handoff - -Run without credentials, host, network or inference: - -```sh -python3 /opt/data/cache/scratch/vuy9-installed-model/analyze.py -``` - -The analyzer asserts exact installed bytes/identity, actual provider/model/reasoning frames, read-only fallback, settled registries/overrides, **the observed failure**, single post-reactivation injection, link inventory, unresolved cases, unchanged markers and cleanup. Its passing evidence checks are not a passing acceptance verdict; `analysis.json` says `selectedAcceptance: FAILED / incomplete`. - -`cleanup.json` and `final-native-state.json` establish empty active sessions, pending permissions and saved grants, removal of owned sessions, termination of the owned host group, no listener on 56167 and no live process among all 44 recorded shim/CLI PIDs. The scoped credential was removed through native API; its temporary file, native database/sidecars, private native logs and server secret were removed. Sanitized observations and the disposable Beads records remain. Operator OpenCode is still **2.0.29** with unchanged executable/config/package bytes; all **146 protected repository paths** remain unchanged. Only this new report changes repository content. README and the five permitted current-summary docs remain unchanged because 6.3 did not start. Fourteen accepted and two unchecked markers remain intact; `.9` stays `in_progress / codex:oc-accept`. - -Existing strict named/all OpenSpec validation, planning validation, focused docs/link checks and whitespace verification are recorded in `validation.json`; the unchanged source full suite was not rerun. The focused docs check passed 14 tests/180 assertions. Its initial launch failed before running tests because the script's child shell lacked Bun on PATH; that log is retained separately from the corrected explicit-PATH run. Final scratch handoff is `R/result.md`. - -**Smallest next gate:** parent independently runs the offline analyzer and reviews the failed outgoing-request timeline, then the owner decides the required lifecycle contract and any separately scoped investigation/correction. The late-output guarantee has not been waived. No continuation of qualification, source repair, task acceptance/closure, marker edit, commit, push, sync, archive, publication, release or operator activation is authorized by this handoff. diff --git a/docs/opencode-native-parity-assessment.md b/docs/opencode-native-parity-assessment.md deleted file mode 100644 index a324b14..0000000 --- a/docs/opencode-native-parity-assessment.md +++ /dev/null @@ -1,255 +0,0 @@ -# Native OpenCode architecture assessment - -## Current measured acceptance — tasks 6.2–6.3 - -The [installed/model continuation](opencode-installed-model-continuation-vuy9.md) records passing selected 6.2 worker evidence on unchanged accepted archive/released OpenCode 2.1.1/Beads 1.3.1 and genuine `openai/gpt-6.1-sol#high`, followed by 6.3 reconciliation. Actual A–D outcomes cover useful bounded/partial projections, append versus relevant memory, exact versus authorized scope, genuine failed validation/partial native child, actual typed/shell actors, uncertain create readback without retry and fresh/summary/provider-native recovery. Corrected actual watched-config cleanup and 17 native resource access passes are reused; final command-description restoration is now settled. All 19normative requirements and 73/74corpus dispositions plus CODE_MODE have explicit evidence mappings. Parent acceptance is complete for all 16 implementation tasks; see [final acceptance](code-mode-final-acceptance-vuy9.md). - -Previously accepted [source/CLI](code-mode-source-acceptance-vuy10.md), [native permissions](opencode-host-codemode-qualification-vuy2.md) and [Stop/handoff](opencode-stop-handoff-qualification-vuy6.md) were consumed without repeating their campaigns. The original stronger location-reload probe remains failed; actual awaited cleanup governs unload acceptance. Nested plain decline remains a separately accepted host limitation. Ordinary typed activation remains withheld: semantic qualification used an immutable internal bootstrap importing the actual installed source. Only same-provider/model encrypted replay was observed; cross-route migration and multi-hour reliability remain unmeasured. No comparative Claude/model-quality, source repair, operator change or publication follows. Earlier evidence below retains its historical candidate scope. - -## Task 7.1–7.3 working source candidate — 2026-10-21 - -The authorized `.10` worker (`codex:oc-loop`) prepared the eleven-operation native -beads namespace, declared outputs, actual-request actor/capability guidance, -operation-aware references, conservative full-prime freshness and CODE_MODE -resource. See the [CLI/native bridge ledger](opencode-sdk-contract.md#task-7173-source-candidate--2026-10-21) -for exact binaries, commands, captures, candidate hash and limits. Historical -five-tool sufficiency and tools.shell-in-execute statements are superseded; -native shell is direct-only. All30 human command names, native user overrides -and advanced/admin coverage remain; the package now resolves17 explicit links. - -Current deterministic evidence:190 tests pass, typecheck and packed-package smoke -pass; the new scratch copy of the exact2.1.1 output executor/catalog bridge passes -using actual candidate schemas. The owner subsequently selected **Beads >=1.3.1**; -minimum and current qualification target now coincide. Its existing contract run -passes63, including positive blocked-filter evidence. The earlier1.3.0 run remains -historical failed evidence (59 pass/five fixture failures), neither passing nor a -current blocker; no further1.3.0 work is authorized. Package/guard/current guidance -now use1.3.1 and reject older binaries before store access. Host admission remains ->=2.1.1<2.2, with no release/dependency/operator change. This explicitly supersedes -older support and blocker statements in the historical sections below. - -Focused guard/manifest RED→GREEN records26/4 then30/0. A final supported1.3.1 -CLI rerun after the runtime floor change also passes63, including exact positive -blocked query `blocked --parent repo-a5a --label contract-label --json --sandbox`. -Final source checks pass190 tests, typecheck and package smoke (archive -`86f781ba6a17949665448e0603ad696afb7eeb6be95311b68ca6e26c105766d7`). -The same scratch executor/catalog seam was rerun on final continuity SHA-256 -`0bb76279663fd865ba99247a3f1f71b5442c39b4fbcea7eeac875da21d37515c`; -its structured get/note outcomes still pass. New policy-specific captures are -separate from the earlier captures. No retired-target rerun, compatibility -branch, host provisioning or model experiment occurred. - -This is a reviewable uncommitted source candidate, not task acceptance, installed -qualification, activation or publication. `.10` stays in_progress with its worker; -parent owns markers and acceptance. `.2` retains installed native inventory and -permissions, `.6` consumes deterministic results and adds Stop/handoff, and `.9` -retains installed/model workflows and lifecycle. Ordinary continuity activation -remains withheld; operator2.0.29, shared integrations, plans and reports are intact. - -## Historical planning correction — Opus S1–S5 / P1–P3 - -The [original REVISE review](reviews/opus-code-mode-plan-review-wgv.md) remains immutable. The [correction map](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md) records the new local candidate, not independent acceptance. All typed argv/resources preserve subcommand-first prefixes and --sandbox on reads/writes, with actual derived write actor inserted after operation arguments but before any -- terminator. Pre-spawn input/identity/hold/location refusals stay thrown; permission rejection/cancellation remain unchanged and started-write uncertainty survives. Actors derive from actual request/invocation session and agent; audit attribution grants no permission and assertions separately use context.agent. - -Future task7.1 authority must explicitly cover existing install-bd.sh into disposable directories and existing bd-contract.ts once per1.3.0/1.3.1 for runtime JSON/mutation/claim/create/close/prime-dependence facts. The SDK ledger will be a table citing captured existing-contract output; help/source is discovery, not passing evidence. No installation or contract run occurred in this correction. Task7.2 reruns existing scratch executor/catalog probes once against the actual candidate and records exact pin/commands/results here; there is no maintained product executor seam. Product tests assert declared outputs/branch invariants and bounded table/shared negatives. Task7.3 uses four representative capability states plus the existing cheap suite/typecheck/package gates. .6 consumes deterministic evidence and adds its own Stop/handoff observation; installed catalog/executor/model confirmation remains .2/.9. No graph/ownership change, implementation, activation, publication or closure follows. - - -## Historical planning correction — broader code-mode architecture (2026-10-21) - -The [broader Opus assessment](reviews/opus-code-mode-architecture-wgv.md) and parent pinned-blob verification supersede six-tool sufficiency and the earlier narrow READY. Exact 2.1.1 shell.ts:195 declares native shell codemode:false; tool.ts:236–262 splits direct/code-mode inventories and removes code-mode-only tools when execute is wholly denied. Ordinary shell is a direct model-turn fallback only. Historical direct/code-mode fixture references below describe host hook/permission seams, not proof that the default plugin tools have direct exposure. - -The selected unpublished [active design](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md) section 7 targets eleven typed daily-loop operations with declared outputs, actual host-derived actors visible in context/results, request-capability guidance and targeted freshness. Tasks 7.1–7.3 own this new source delta; historical 3.1 and 6.1 acceptance does not cover it. Keep full prime until measured; do not suppress issue-write refresh until supported prime dependence is established. Planned CODE_MODE adds one resource: 16 resources plus ADR, 17 explicit links; prior 16-link package results remain historical measurements. All 30 human commands/overrides and advanced/admin coverage remain. - -The actual actor is derived from the executing session/agent, not a mandatory beads-task-agent identity or delegation topology; permission checks continue using context.agent. Minimum/current Beads remain >=1.3.0 / installed 1.3.1. Unsupported flags, multi-ID show, claim-conflict shapes and prime-state assumptions remain bounded 7.1 checks. Operator 2.0.29 is untouched. The owner-accepted nested plain-decline continuation remains a failed stronger case accepted as a host limitation, not a passing Stop/Cancel test. Existing .2/.6/.9 independently own host, Stop/handoff and installed/model gates. Planning reconciliation only: implementation_authorized=false; no resumed qualification, activation, publication or closure. Earlier source/live records retain their original scope. - -Historical source assessment from 2026-10-17, reconciled 2026-10-18. Owner selections are complete; current bounded source/fixture evidence is recorded below, separately from unexecuted runtime qualification. This is part of the [full packet](claude-code-integration-analysis.md). The inventory preserves 73 historical release files separately from 74 current marketplace-main files. Claude supplies desired behavior, not the architecture. - -## Operative baseline update — 2026-10-20 - -The owner now selects **2.1.1**, with conservative admission **>=2.1.1 <2.2**. See [the bounded contract delta](opencode-2.1.1-contract-delta.md) for new immutable evidence and adaptations. All S01–S21 source identities and tables below remain the historical 2.0.32 assessment; they are not relabeled 2.1.1. X09 session.list is now released but remains unused in the minimal design. New runtime qualification is unexecuted. - -## Tasks 4.1 / 4.2 deterministic worker contribution — 2026-10-21 - -**Parent-accepted 4.1 source and 4.2 deterministic contribution; live qualification remains unexecuted.** Bead `opencode-beads-vuy.6` owns both tasks and stays open for later live 4.2 after separately authorized 1.1. Baseline HEAD is `db3b65ee86ad02d363baf9cbf24511a15d7bb644`; it contains the accepted `.5` source `5ea915a` and evidence-only successor. Parent records the exact accepted contribution revision in `.6`; neither worker results nor the dependency graph authorize `.8`. Only task 4.1 is checked; 4.2 remains unchecked. [Opus source review](reviews/opus-flow-source-review-vuy6.md) returned READY; parent verified all 10 candidate file hashes unchanged before acceptance. - -Executor: `codex:oc-flow`, full session UUID `01a15bbd-42d2-7d90-867a-1ad927e68fad`. Local session `turn_context` records actual model `gpt-6.1-sol`, reasoning `high`, provider `openai`. The worker atomically claimed only `.6` with command-scoped `BEADS_ACTOR=codex:oc-flow`, read back `assignee=codex:oc-flow`, and retained historical `created_by=unknown` and absent record/account `owner`. The `owner` returned by `bd heartbeat` is the lease holder, not evidence of a stored account-owner field. Checkpoints and heartbeats retain the explicit actor; coordination/review does not itself transfer ownership. - -### 4.1 source contract - -`src/guidance.ts` replaces mandatory one-bead and command-count delegation with authorized-scope guidance. Exact assignments and explicit one-bead mode stop without substitution; a single operation does not authorize a task claim. An already-authorized batch/goal may proceed only within its scope and acceptance gates, with atomic per-bead claim/readback, relevant validation, append checkpoints and closure evidence. Discovery is a report or separately authorized record, never added execution authority. Read-only graph requests authorize no mutation. Denial, cancellation, deliberate stop, permission wait, exhausted scope, decision blockers and incomplete acceptance remain stops. - -The guidance carries actual executor actors through shell claims, writes, updates, heartbeats and delegation, separately from host permission identity. It requires deliberate handoffs, distinct audit-author/account-owner/assignee readback, preserved historical authorship and no human Git/model-name impersonation. Substantive planning and independently owned review have bounded records and their own acceptance; corrections reuse the review item. A quick draft, retry or document does not get a mandatory ticket. Native blocking child return carries scope, actor/session, attempts, outcomes/rationale, candidate, validation, references, blockers and next action; invocation completion alone is not task acceptance. - -`src/agents.ts` keeps both existing IDs, inherited default model, opt-in Luna Max, permissions, default 100-step cap and `0` cap removal. Caps limit an invocation, never its authority or acceptance. No scheduler, scope parser, manager, transport, retry or upstream-repair code was added. The accepted rich assets already express the selected scope and remain untouched. README's former mandatory-one-bead design/task-agent/Luna wording is reconciled for the beta/next candidate while published 1.0.2 remains historical. - -### Deterministic evidence map - -| Contribution | Executed fixture boundary | What remains unproved | -| --- | --- | --- | -| 4.1 exact assignment, authorized continuation, discovery, read-only analysis, denial/incomplete acceptance | `tests/guidance.test.ts` checks canonical prompt contracts; `tests/agents.test.ts` retains profiles/caps/permission rules; `tests/workflows.test.ts` forwards literal caller scope and partial-handoff cues and checks agreement with existing assets | Model compliance, semantic checkpoint quality and real claims/handoffs are not established by text assertions | -| 4.2 failed/cancelled/NO_TEXT/partial child | `tests/host.test.ts` supplies public `execute.after` payloads, checks original input/result/error and identities survive, parent context is invalidated, child cache stays isolated, and only a later requested context gets a recovery cue | No child is actually launched; host job transport, result delivery and model interpretation remain live checks | -| 4.2 deliberate stop racing a late child and success notification | No plugin prompt/synthetic/re-prime is initiated; late payload remains intact; compaction still reports no guaranteed final checkpoint; unload ignores later callbacks | A mock notification is not proof the host itself suppresses background wake or a late native result | -| 4.2 actual parent/child invocation identities, partial handoff and recovery | Registered checkpoint tools append fixture notes with each invocation-derived actor and actual permission agent, despite a different session-default agent. Show preserves attempts, rationale, validation/gaps, references, candidate and separate created_by/owner/assignee data on a fresh setup. Fork starts without parent reference state | This is an in-memory CLI response fixture, with no mutation experiments on the project store; assignment semantics, live durable recovery and host fork remapping are external | -| 4.2 permission wait / late approval | Pending assertion performs no update; reference-only compaction does not write or add permission waits; actual invocation cancellation rejects and later approval cannot spawn the operation | Live allow/ask/deny/filtering, approval UI, saved-grant edits/revocation and wait delivery remain 1.1/4.2 checks | -| 4.2 retained history and provider/model boundary | Representative public compaction payloads preserve absent result, summary metadata.keepID, legacy metadata.recent, supplied native.messages and model identity. The hook adds only system guidance, without replacing result or messages | No provider replay, retained-tail reconstruction, mismatch fallback or fork-remapping algorithm is executed by these fixtures | -| Prior 3.3 / 3.1–3.2 evidence retained | Existing host/continuity tests retain direct + code-mode inner acknowledgement dedup, permission/guard holds, abort/unload, no stale location injection, owned disposal, native command precedence, all 30 registrations, resource paths and honest status limits; [accepted source boundary](opencode-sdk-contract.md#tasks-2233-source-candidate-native-registration-and-diagnostics) | Earlier source acceptance does not qualify live 1.1, 4.2 or end-to-end 6.2 | - -The fixture contract is pinned **2.1.1**, commit `ba546ec1598a70db2570e9c6258028d955ba8f58`, from `baseline211/source` and installed `@opencode/plugin@2.1.1` declarations. [Core tool](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool.ts) lines 103–149 passes session/agent/message/call identity to awaited before/after hooks, with after status `completed` or `error`, not a fabricated cancellation status; lines 264–270 construct actual invocation identity. [Native subagent](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/tool/plugin/subagent.ts) lines 234–268 blocks on the host job, interrupts/cancels on interruption, returns Tool.Error for failed/cancelled children, and returns a completed result with [NO_TEXT](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/subagent-completion.ts) when text is absent. The after hook is not a universal finally for defects, pre-hook rejection or cancellation. The plugin preserves outcomes and supplies cues; it neither enforces host transport nor adds semantic persistence from arbitrary child text. - -Awaited context/compaction hooks edit the current request. The server event subscription only observes/invalidate state; it is not awaited stop enforcement and never restarts the parent. Natural blocking subagent calls are host-owned. Host history owns retained tails, keepID remapping, legacy decoding and provider/model mismatch; native.messages replaces summary replay. This contribution leaves native replay untouched and performs no compaction persistence, permission wait or replacement result. The prior `.5` suffix-reactivation evidence from the **unpinned** `released` cache remains separately identified in the SDK contract; it is not new pinned or live evidence here. - -The installed Beads CLI continues to own supported database/routing/consistency semantics. These changes do not add confinement promises, routing guards, backend restrictions, upstream repairs, competing-plugin collision guarantees or an activation option. - -### Validation and unexecuted gates - -Focused RED: updated guidance/agent/host assertions failed 6 tests against the old prompt. Minimal GREEN: 58 passed, 0 failed (278 assertions). After adding the narrow deterministic fixtures, the four focused files passed 85 tests, 0 failed (757 assertions); typecheck passed. A fixture initially compared JSON key order and eagerly awaited a rejection before issuing cancellation; both fixture errors were corrected. A partial ToolEditor fixture also required an explicit boundary cast; typecheck then passed. None demonstrated a production host defect, so `src/host.ts` and `src/context.ts` are unchanged. - -The first full cheap suite (`npm exec --yes --package=bun@1.3.14 -- bun test`) reported **159 pass, 1 fail**, 1,137 assertions. The failure is the stale `tests/docs.test.ts` contract demanding old one-bead README wording. `npm exec --yes --package=bun@1.3.14 -- bun run typecheck` passed. `npm exec --yes --package=bun@1.3.14 -- bun run test:package` failed at `scripts/test-package.ts:332–335`, which still requires a sub-1,000-character worker prompt and the old actor-less claim string. Both check files are outside the worker's initial edit scope; narrow correction authority was requested rather than weakening the new guidance or editing them silently. These checks are not reported as passing. - -Parent verification after the worker handoff: the two stale check files were corrected within this source task, replacing old README/one-bead/actor-less claim assertions with the selected scoped-execution contract. Parent reproduced two failing README assertions plus the package-prompt failure before correction. Final independent execution passed **160 tests, 0 failures**, typecheck, packed-package smoke (archive SHA-256 `51f0d2ab294e1b23f90bec424ba479fa2162cef621b47e161743eb4d652d8cb1`), strict global OpenSpec and whitespace checks. The packed prompt's old 1,000-character ceiling was replaced with semantic scope/attribution/closure checks rather than an arbitrary larger quota. These results supersede the earlier failed checks, not their history. Source acceptance and deterministic handoff are now parent-accepted after Opus READY; the exact published revision is recorded in `.6`, and no live outcome is claimed. The review's optional executor-guidance duplication/style observations are not source blockers. Its actor-consistency observation is retained for live 1.1/4.2: verify that shell claims and invocation-derived typed checkpoints use the intended actual executor identity, without silently transferring assignment. - -**LIVE 4.2 remains unexecuted:** no installed host/model launch, install/upgrade, activation, real child/claim scenario or project-store mutation fixture. Live checks must observe blocking child identity/content and failures/NO_TEXT, cancellation and deliberate-stop/late-result races, permission waits, partial handoff/fresh recovery, retained history/fork and provider/model mismatch, and relevant long-running transport behavior on a separately authorized disposable 2.1.1 host after 1.1. Model obedience and meaningful recovery remain behavioral acceptance. No task marker, closure, consumer dispatch, release or publication follows from this worker contribution. - -## Historical selected bundle and alternatives (2.0.32) - -**N1 + D01 + D04 is selected:** narrow typed checkpoint/recovery/memory operations, awaited context/tool hooks, reference-only compaction, observational events, package-owned `oc-beads` skill/resources and `oc-beads:` entries. All corpus members have engineering dispositions under the accepted groups. bd remains executable/database owner; preserve the shared skill and customizations. See [design decisions 2–5](../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md) for concrete delivery and authority boundaries. - -The superseded selected minimum was **OpenCode >=2.0.32 <3**, delivered through opt-in beta/next with separately authorized publication. Released permission assertion is the reason for the minimum; no runtime/dependency change occurs here. N0 on 2.0.26 was an evaluated lower-cost alternative, including the Opus review's N0-first advice; Matt selected N1. A failed N1 guarantee is a bounded stop/qualification gate, not an implicit downgrade to N0. - -Scope-bounded continuation is selected: atomic claims and per-bead validation, exact assignment stopping, authorized batch/goal continuation and no discovery-driven scope expansion. Normal blocking child return is the base native mechanism. N2 background completion, nested-depth changes and auxiliary checkpoint/compaction automation are deferred engineering mechanisms; they are unnecessary to implement authorized sequential continuation and carry stop/wake risks. No plugin synthetic restart, command-count delegation mandate or new orchestration service. Optional one-bead mode and opt-in Luna remain. - -Upstream drift compares reviewed marketplace-main commits across full selected roots/support paths, using the existing scheduled check pattern and check output/review links. Unreviewed drift fails a distinct check/job with a drift error; retrieval failure fails with a distinct error diagnostic. No GitHub issue or issue-write permission. Human review advances the baseline; no automatic adaptation, bump or release. - -## Release provenance and availability - -The official [V2 documentation](https://opencode.ai/v2/docs) and [plugin guide](https://opencode.ai/v2/docs/build/plugins/) were checked alongside source and published npm declarations. Rolling docs are discovery evidence; pinned release call sites control availability claims here. - -| Evidence class | Verified identity | Consequence | -| --- | --- | --- | -| Released supported V2 surface | npm `@opencode/cli` and `@opencode/plugin` latest = **2.0.32**; published 2026-10-16 (CLI 22:14:49.966Z, plugin 22:15:43.217Z). Git tag `v2.0.32` = `843a6c514e606b436a7fe713422ace0a93ad3d61`. | All S references below use this tag commit. Published package tarballs were downloaded as evidence, not installed. “Supported” here means public, non-experimental released contract, not proven behavior in the user's runtime. | -| Existing minimum | `v2.0.26` = `9b4ec5714d481559990db0a816d5dec19541a814`; published plugin declarations compared directly. | Session/tool/skill/command/agent/registration declarations are byte-identical to 2.0.32. Permission declaration adds `assert` in 2.0.32; context also adds credential activation (irrelevant). Core compaction/model/subagent implementations differ, so type equality is not runtime equivalence. | -| Released experimental | WebSocket handshake/send/receive hooks; terminal read; `experimental.subagent_depth`; `experimental.portable_shell_scanner`. | Evaluate individually below; no blanket exclusion for instability. | -| Unreleased development | Existing `8f7b0120eb6b4aa3da1f82b1a9094a9fb4db2d06` is current `dev`, not release tag, although package says 2.0.32. Comparison is diverged: 30 development commits vs one release-side commit. `main` lookup returns 422; default branch is `dev`. | Plugin `session.list` is present on development, absent from released SessionDomain. Do not use rolling-doc session listing in the base recovery design. | -| Unknown runtime | No installed host or model/service was exercised. | Source establishes contracts and ordering, not deployed availability, permissions, actual recovery quality or crash durability. | - -GitHub `releases/latest` returned V1 v1.19.3; it does not identify V2 latest. npm registry metadata and Git ref APIs establish the V2 release above. Registry URLs: [plugin](https://registry.npmjs.org/@opencode%2fplugin), [CLI](https://registry.npmjs.org/@opencode%2fcli). Exact source hashes and package integrity checks are reproducible with the inventory validator described below. - -## Native mechanism inventory and call-site findings - -All mechanisms below are released public contracts at 2.0.32 unless explicitly marked experimental/development. Source references identify both declaration and consuming code. A hook being awaited is a trigger guarantee on that code path, not proof that a model will make the right decision. - -| ID / mechanism | Ordering, control and scope | Recommendation and limits | -| --- | --- | --- | -| M01 context / model request | S01/S02/S03: `session.hook("context")` is awaited while assembling each agent-loop request, including tool continuations. Can edit system/messages/tool definitions/options for that request, not persisted history. `model.request` then edits endpoint/headers; HTTP/WS hooks act lower down. Tools invented in context are dropped unless matched to registered definitions. | Use context for guarded prime plus relevant recovery/dirty-state guidance, primary and worker alike with explicit audience. Register tools through the tool domain. Do not use provider traffic rewriting for memory or silently override model settings. | -| M02 tool execution and typed tools | S04/S05: `tool.hook("execute.before")` is awaited before execution, can replace input/tool and reject the call. Promise rejection maps to Tool.Error. After-hook runs after success or typed Tool.Error and before returning result; can edit result/error. It is not a universal finally for defects/cancellation or pre-hook rejection. Both direct and code-mode inner tool paths invoke hooks; observing outer `execute` as well risks duplicates. | Preferred exact acknowledgement comes from the plugin's typed adapter, keyed by session/message/call and operation. For other tools, record only a checkpoint opportunity or concise failure cue, not automatic memory. Preserve original result/error; never hide failures. Narrow tool uses normal permission assertion and abort-aware bounded CLI I/O. No shell-text parser as default. | -| M03 compaction interception | S02/S06: compaction preparation awaits its own hook on both summary and native-provider paths. Summary prompt is appended later; optional `result` bypasses model generation. Auto compaction's started event is emitted inside delivery after preparation; ended/failed are later notifications. Retries can shrink or flatten history. | Use the awaited hook only to add acknowledged durable references and known unsaved/uncertain state. No writes, flush queue, semantic checkpoint wait or new permission wait in this path. Do not enqueue a same-session prompt and wait for it here: compaction occupies that runner. A summary is not a Beads write. Do not replace native compaction with `result` unless deliberately accepting that semantic change. | -| M04 execution/step/permission events | S07/S08/S09: `session.execution.started/succeeded/failed/interrupted` delimit a busy period; step-ended can precede more tools/steps. Interruption carries reason; shutdown differs from deliberate stop. Public `event.subscribe` consumes a server event stream, not the core's awaited internal projection/listener API. The bus applies location routing when a Location service is present; global events and move routing still require explicit session checks. Permission requests/replies are separate from successful execution. | Observe status, invalidate relevant state and expose incomplete checkpoint/blocker diagnostics. No public before-stop interceptor appears in the released SessionHooks contract; no veto or guaranteed checkpoint at stop; no restart on every idle notification. A permission wait is not completed work and must not induce auto-approval. | -| M05 session lifecycle and recovery | S07/S10: created has project/location/parent; moved/forked/deleted are explicit. `get`/`context` can inspect a known session. No released plugin `session.list`, exact “resume” hook, or semantic task-binding API was found. `viewed` is an idle watermark, not recovery authority. | Recover from relevant issue identity and current durable Beads state at the first eligible context request, not merely session-created. Filter server-wide events by actual session location/project; moved/forked sessions require re-resolution. Do not discover tasks by scanning all host transcripts. | -| M06 prompts, synthetic inputs and generation | S10/S11: prompt hook awaits before attachment/skill resolution and durable inbox admission; mutations become canonical input. Default steer vs queue controls admission. Concurrent retries can invoke hooks more than once. S10 synthetic admission bypasses prompt hook, can carry id/metadata, defaults to wake execution unless `resume:false` or revert blocks wake. `session.generate` is transient generation, a separate model request, not persisted task knowledge. | Explicit commands forward attachments/delivery and submit normal prompts. Use synthetic only for selected notifications with provenance, idempotency and explicit continuation policy. `resume:false` does not wake an idle session but is not a promise that active execution cannot consume it. Avoid rewriting user intent or recursive prompt hooks. Auxiliary semantic extraction is an optional future probe, not a background service. | -| M07 native child results | S12: blocking subagent execution waits for the job; completed output is returned in a tool result, failures/cancellation distinguished. Background completion sends a synthetic with child metadata and stable notification ID, then marks notification complete. Returned meaning is last assistant text, possibly NO_TEXT. | Prefer host completion transport over a plugin poller/daemon. Worker guidance must preserve failed attempts, rationale, evidence, blocker/next action and record references; primary reconciles. Do not equate host job completion with issue acceptance or successful checkpoint. No automatic task closure in event listeners. Built-in background delivery wakes by default; deliberate-stop job cancellation exists (S08), but race/restart behavior must be qualified before selecting N2. No synthetic-admission hook was found to let this plugin veto arbitrary host notifications. Until qualified, prefer blocking child return for stop-preserving workflows. | -| M08 registration/discovery | S13/S14: agent, command, skill and tool transforms operate synchronously on domain state, replay in registration order on rebuild and dispose with scope. Command and skill add use map set, so collision can replace an earlier entry. Skill content has real path/resource-base requirements; command executor receives prompt and delivery. | Prefer D01+D04 package ownership, distinct names and preserve-existing collision policy; diagnose collisions instead of overwriting. Command editor exposes only add: inspect `command.list` before registration, then qualify reload/order behavior; do not invent editor.get. Treat later user/plugin transforms as possible overrides and verify effective registry. Agent registration supports optional routing, not a requirement to create new coding agents. | -| M09 permissions, options and diagnostics | S15/S16: permission evaluate hook runs after configured rules; explicit deny bypasses it. Can modify allow/ask to allow/ask/deny. 2.0.32 assertion waits for permission decision; plain rejection must propagate to stop current step. Plugin code is privileged; tool registration alone is not a permission sandbox. Options and `app.version`, plugin list, registry lists and permission list/get expose useful status. | Typed adapter asserts operation-specific authority, preserving existing restrictions and user denials. Do not auto-allow from semantic classification. Read-only diagnostics distinguish unavailable, failed and withheld context without opening stores unnecessarily; no automatic config or credential changes. | -| M10 cleanup/isolation | S03/S09/S16: hooks are location-scoped, registrations have disposal/finalizers, setup may return cleanup. The documented event surface is server-wide; source can location-filter streams, so do not infer session ownership from receipt alone; explicit AbortController required for Promise subscriber cleanup. Hook dispatcher awaits callbacks in order without a generic timeout. Promise hooks other than tool-before use Effect.promise, so unexpected rejection is a defect, not supported policy rejection. | Per-location adapter plus per-session state; abort streams/in-flight work and dispose registrations on unload. Bound plugin-owned I/O, catch/report non-policy failures and avoid leaving queued retries. Do not assume reload or deletion flushes memory. Deduplicate by operation identity, not elapsed-time quotas; don't claim exactly-once CLI mutation across crash. | - -### Experimental and adjacent mechanisms checked - -| ID | Availability / useful possibility | Disposition, qualification and fallback | -| --- | --- | --- | -| X01 WebSocket handshake/send/receive | Released experimental in S01/S02. Awaited per request/frame; HTTP hooks do not cover WS traffic. Can replace frames verbatim; host does not validate semantic rewrites. | Do not adopt for Beads continuity: transport interception offers no semantic checkpoint boundary and adds provider-specific maintenance. If future diagnostics require it, opt in, pin/test WS and HTTP fallback, never log credentials/raw transcripts. Fallback is domain context/tool hooks; no provider mutation needed. | -| X02 persistent terminal read | Released experimental context exposes terminal read (S16), not a new plugin terminal execution lifecycle contract. Could recover visible output from a long-running command. | Deferred from the base; future evidence retrieval only when an identified terminal is relevant and authorized; not a memory feed or daemon. Qualify session/terminal ownership, missing/expired output and truncation; fall back to explicit tool/job results. Do not promise terminal output is durable task state. | -| X03 nested subagent depth | Released experimental config S17, consumed by S12; default depth 1, limit rejects deeper calls. Could support authorized multi-stage investigation without bespoke orchestration. | Deferred engineering mechanism; retain default depth and normal blocking children. A future nested-flow selection would need depth/permission/cancellation and parent-handoff qualification first. Costs more concurrent context and more semantic boundaries. Fallback: primary sequences normal children. No config changed here. | -| X04 portable shell scanner | Released experimental S17/S18; replaces default parser, no tree-sitter fallback; scanner failure is distinct from permission denial. Potentially useful for portability of CLI workflows. | Deferred host qualification candidate, not continuity base or shell-parsing strategy for this plugin. Test relevant platform syntax/error handling separately; owner may retain default scanner. Changing parser does not improve semantic memory or expand authority. | -| X05 policies / V1 experiments | `experimental.policies` is deprecated compatibility input; use supported top-level policy semantics. Migration docs explicitly lack direct equivalents for V1 compaction-autocontinue/text-complete/small-model hooks (S19). | Do not invent V2 hook names or carry V1 guarantees forward. Policy configuration is owner-controlled. Public V2 context/compaction and synthetic delivery cover parts of the behavior, not a universal stop gate. | -| X06 native provider compaction | Released documented option, **not marked experimental** (S06/S20). Provider context may be opaque; endpoint provenance constrains rerouting. | Support as a compatibility path, preserving independent Beads checkpoints and failure reporting. Do not require changing provider/config or replacing opaque state with a custom summary. Probe both native and summary modes only if selected hook behavior depends on it. | -| X07 AI SDK middleware, HTTP, shell hooks | Released domains S02/S21: lower-level request/tool plumbing and shell `create.before` can alter environment/command/timeouts. | Checked, not preferred: semantic task transitions are better served by session/tool contracts. Shell hook has no session identity in its public draft; broad rewriting/parsing is fragile. No middleware-based second agent loop. | -| X08 storage, RPC, reference, worktree, VCS, MCP/integration, UI | Released context domains S16. Storage could retain plugin bookkeeping; RPC/UI could expose richer diagnostics; references can resolve attachments. | No new store/service, telemetry, RPC daemon, auth integration, worktree policy or custom UI required for this outcome. Keep semantic durability in Beads. Read-only plugin-owned status command is enough initially; host-owned durable inbox/child delivery may be used without building a replacement. | -| X09 session listing | Development-only addition at `8f7b012…`, absent in published 2.0.32 plugin SessionDomain. | Exclude from base dependency, not from future consideration. Known-session context plus explicit task recovery works now. Reassess once released, only if cross-session discovery materially improves recovery. | - -## Behavior-to-mechanism mapping - -| Desired behavior | Preferred native path | Semantic owner / verification gap | -| --- | --- | --- | -| Meaningful progress checkpoint | M01 trigger guidance + N1 typed tool; M02 acknowledgement marks task context dirty | Model decides materiality; adapter confirms actual write. No fixed frequency or tool-count write rule. Test duplicate calls, partial failure, fresh recovery. | -| Failed approach | M02 preserves error and suggests task checkpoint at next eligible request; typed checkpoint captures attempt/evidence/next step | Error alone does not prove an approach failed; model distinguishes transient errors and abandoned approaches. Before-hook rejection/cancellation needs separate coverage. | -| Decision and rationale | Registered decision workflow plus typed checkpoint, linked to OpenSpec/docs when relevant | Model/user chooses rationale and alternatives; do not extract decisions automatically from arbitrary transcript text. | -| Reusable discovery / selective remember | Typed explicit memory operation with prior targeted search/recall; on-demand resource examples | Model evaluates evidence, applicability and novelty; no promotion of every successful tool output, private content or hypothesis to memory. | -| Targeted recall / freshness | Recovery context + typed reads; invalidate after acknowledged writes and child handoff/compaction | No complete change feed for external bd writers is established. Re-read active issue/relevant keys at recovery and important transitions; cached absence is not proof of absence. | -| Precompaction durable checkpoint vs summary | M03 carries acknowledged durable IDs/references and known unsaved state without persistence | Cannot ask same runner to perform a new semantic checkpoint inside the hook. Periodic meaningful writes are base protection. An ordinary acknowledged checkpoint before user-requested compaction can protect planned work; automatic overflow/crash remains qualified. | -| Fresh-session recovery | First eligible M01 request + current issue/memory retrieval, using explicit task identity | No reliance on missed creation events or development-only listing. If identity ambiguous, narrow read/search or ask; never auto-claim ready work to reconstruct intent. | -| Worker completion / semantic handoff | M07 host job transport + typed worker checkpoint; context verifies child/primary audience | Host reliably transports status on examined paths, not rationale quality. Parent reconciles record references and acceptance, including NO_TEXT, cancellation and stale records. | -| Stop / failure / permission blocker | M04 observations and M09 permission semantics; earlier checkpoints plus next-request recovery diagnostics | No external veto or crash-final-write guarantee. No synthetic auto-wake after user stop or permission wait. Model decides durable blocker; permission rejection cannot be swallowed as success. | -| Command / skill discoverability | M08 D01+D04, scoped command prompts, installed resource paths, effective registry diagnostics | Model selection remains uncertain; test explicit invocation and normal task-trigger selection separately. All 29 corpus commands retain dispositions even if workflows consolidate. | -| Setup / ownership | Package registrations/disposal, distinct skill ID, preserve-existing collision behavior; upstream initialization remains explicit | Installed package path/override tests needed. No automatic file installer, init, repair, config update or privilege expansion. | - -## Lifecycle and alternatives - -N1 writes synchronously inside the typed operation and returns its evidenced status before ordinary continuation. The compaction hook is reference-only: it carries acknowledged references and known gaps, with no pending-write state, new permission wait or recursive same-session prompt. `session.prompt`/`session.compact` admission is not completion evidence. Meaningful earlier checkpoints protect against compaction; crash-final-write guarantees are unsupported. - -**Concrete permission contract (F2):** S05 `Tool.snapshot` filters on `tool.options?.permission ?? name`; set `options.permission: "shell"` for direct and code-mode inventory filtering. S15 `configured` resolves `agent ?? session.agent`; pass the actual invocation `context.agent`, sessionID and source message/call ID. Assert `action: "shell"` with canonical resource text for the fixed argv operation, preserving selective write denials. S15 saves an "always" reply only when `request.save?.length`; use `save: []`, never a new broad `bd *` grant. Expected “always” acceptance is one-call, so explain repeat prompts. Existing shell `bd *` project grants can authorize equivalent typed operations, subject to configured denies evaluated first. S18 shell parsing gives `bd` a one-token prefix, explaining that existing grant scope. Qualify these outcomes without broadening permissions. Plain rejection must propagate. - -S18 shell preparation resolves cwd, scans target directories, calls `access.authorizeExternal`, then asserts shell resources. The added S18 file-access source shows `external_directory` resources and scope. Plugin assertion alone does not reproduce this path. Bind the narrow adapter to the actual resolved location/workspace, check routing/redirect/symlink/environment effects and guard hold before spawn and after approval. Assert equivalent external-directory restrictions with invocation identity and no broad saved grant where needed; if target or equivalence cannot be established, refuse before store access. Never add a permissive custom action or silently use N0. Qualification covers shell-denied/read-only agents, changed invocation identity, allow/ask/deny, cancelled approval and external targets; no new generic permission manager. - -S13 command names are schema strings and map keys. The released app parser splits the slash name only on whitespace, and submit finds the exact registered name, so `oc-beads:ready` is source-supported through that path. Installed slash discovery/dispatch, collision/rebuild preservation and resource paths remain acceptance checks. Preserve-existing behavior must survive reload; an initial list check alone is insufficient. Report a concrete namespace or lifecycle incompatibility before enabling the affected registration. - -Load registers package-owned surfaces and bounded, location-scoped hooks, then subscribes to notifications with explicit cleanup. First eligible request resolves actual session scope and authority, provides guarded workflow and targeted recovery. During work, the model selects task checkpoints or reusable-memory operations; the typed tool validates and asserts permission, runs supported CLI arguments and returns an honest acknowledgement. Relevant context becomes stale only on known changes, with targeted reads for external uncertainty. Tool hooks provide focused cues and child-result feedback, not autonomous semantic writes. Compaction carries acknowledged references and known gaps only; it neither writes nor requests another same-session turn. Completion/failure events update diagnostics without forcing continuation. Reload/deletion abort observers and clear ephemeral state; later recovery reads durable records. - -Compared with Claude hook shell scripts, typed tool identity and success/error payloads allow precise feedback without parsing arbitrary shell text; mutable context hooks can scope guidance to the actual session/request; native inbox/child results avoid a separate completion poller; package registrations can remove discovery entries with package lifecycle. These are evidenced integration affordances, not proof of better model judgment or durability than Claude. Claude's richer resource guidance remains valuable. - -Historically evaluated CLI-based N0 with native hooks has lower implementation/compatibility cost but weaker acknowledgement and refresh precision. Blanket automatic extraction from tool output is rejected because transport success does not establish reusable meaning and introduces privacy/duplication errors. An end-event-triggered “save everything” loop is rejected because it races shutdown/compaction, can undo deliberate stop and recursively trigger itself. Custom compaction replacement or auxiliary `generate` could extract semantics, but adds model cost/failure/authorization and provider-state consequences; it is not the recommended base. No extractor seam needs implementation now; a later demonstrated need can be evaluated separately. - -## Qualification and stop gates - -Executed evidence is source/API/package inspection and static planning validation only. No inference, server startup, dependency installation, product tests or bd/store operations were executed. Owner selection is not acceptance evidence. - -Future tasks separate stub/disposable fixtures from installed-host/model evaluation. Material checks are typed visibility and allow/ask/deny/save/identity/external-access equivalence; safe multiline argv and uncertain acknowledgements; direct/code-mode handling; package collision/disposal/resource resolution; reference-only summary/native compaction; blocking-child NO_TEXT, cancellation/late-result races and fresh recovery. No exhaustive model matrix or speculative smoke framework. Background/nested automation is deferred, not silently required by scope-bounded continuation. - -All X01–X09 dispositions are recorded in the inventory and design. A concrete contract-changing incompatibility stops the affected path for resolution; normal implementation details do not reopen the owner interview. Source qualification, fixture acceptance and behavioral acceptance remain distinct. - -## Pinned source index and reproducibility - -Each S entry is a released call-site/declaration source, also SHA-256/Git-blob identified in the inventory's `native_assessment.sources`. Run `python3 docs/validate-parity-planning.py /opt/data/cache/scratch/parity-sources` after populating the documented pinned evidence trees. It verifies original corpus identity/coverage, native source identities/links, declared availability anchors, published tarball integrity and declaration comparisons, local links and whitespace. This is a planning evidence checker, not a markdown test framework or runtime qualification. - -- S01: [packages/plugin/src/promise/session.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/session.ts). -- S02: [packages/core/src/session/model-request.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/model-request.ts). -- S03: [packages/core/src/plugin/hooks.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/plugin/hooks.ts), [packages/plugin/src/promise/adapter.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/adapter.ts). -- S04: [packages/plugin/src/promise/tool.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/tool.ts). -- S05: [packages/core/src/tool.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/tool.ts). -- S06: [packages/core/src/session/compaction.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/compaction.ts). -- S07: [packages/schema/src/session-event.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/schema/src/session-event.ts). -- S08: [packages/core/src/session/execution.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/execution.ts), [packages/core/src/session/projector.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/projector.ts). -- S09: [packages/core/src/bus.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/bus.ts), [packages/core/src/plugin/host.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/plugin/host.ts). -- S10: [packages/core/src/session/session.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/session.ts), [packages/core/src/session.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session.ts). -- S11: [packages/core/src/session/prompt.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/prompt.ts), [packages/core/src/session/inbox.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/inbox.ts). -- S12: [packages/core/src/tool/plugin/subagent.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/tool/plugin/subagent.ts), [packages/core/src/session/subagent-completion.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/subagent-completion.ts), [packages/core/src/session/subagent-job.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/session/subagent-job.ts). -- S13: [packages/core/src/command.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/command.ts), [packages/core/src/skill.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/skill.ts), [packages/core/src/state.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/state.ts). -- S14: [services/www/src/docs/content/build/plugins/index.mdx](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/build/plugins/index.mdx), [services/www/src/docs/content/commands.mdx](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/commands.mdx), [services/www/src/docs/content/skills.mdx](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/skills.mdx). -- S15: [packages/plugin/src/promise/permission.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/permission.ts), [packages/plugin/src/permission.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/permission.ts), [packages/core/src/permission.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/permission.ts). -- S16: [packages/plugin/src/promise/plugin.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/plugin.ts). -- S17: [packages/schema/src/config/experimental.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/schema/src/config/experimental.ts). -- S18: [packages/core/src/tool/plugin/shell.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/tool/plugin/shell.ts), [services/www/src/docs/content/permissions.mdx](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/permissions.mdx). -- S19: [services/www/src/docs/content/build/plugins/migrate-v1.mdx](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/build/plugins/migrate-v1.mdx), [packages/core/src/config/normalize.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/config/normalize.ts). -- S20: [services/www/src/docs/content/compaction.mdx](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/services/www/src/docs/content/compaction.mdx). -- S21: [packages/plugin/src/promise/aisdk.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/aisdk.ts), [packages/plugin/src/promise/shell.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/plugin/src/promise/shell.ts). - -Additional checked sources in existing groups: - -- S18: [packages/core/src/file-access.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/file-access.ts). -- S13: [packages/schema/src/command.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/schema/src/command.ts). - -- S13: [packages/app/src/composer/client-slash-command.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/app/src/composer/client-slash-command.ts). - -- S13: [packages/app/src/composer/submit.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/app/src/composer/submit.ts). - -## Final review correction evidence - -The [50919ae independent review](reviews/opus-planning-review-50919ae.md) remains REVISE as issued. B1 is addressed in tasks 1.2 → 1.1: prepare 2.0.32 types first, then minimal throwaway host probes; adapter fixtures are solely 3.1. Live gates 1.1/4.2/6.2 require a separately authorized disposable host pinned initially to 2.0.32 (`>=2.0.32 <3`). The image CLI package is 2.0.29; no runtime was started or upgraded. Missing live environment does not block independent source/fixture work. - -Collision recommendation evidence needs a narrower interpretation: S13 supervisor `ordered` is pre → packages → post; internal `post` includes ConfigCommandPlugin. That plugin refreshes loaded documents, calls command.reload and replays its transform after package commands. Thus source supports later config commands overriding package entries, not the review’s blanket claim that package plugins overwrite them on rebuild. Other transform ordering still needs qualification: command editor has add/Map.set but no conditional get/list; initial listing alone cannot prove preservation. Withhold affected colliding entries where possible, and stop the affected path if public APIs cannot preserve customization. No override permission or generic registry is introduced. Skill editor get/list permits checking each rebuild. - -S13 Skill.prepare sorts and truncates automatic resource listing to ten. Future SKILL.md must explicitly link all 15 resources plus ADR; 2.2 verifies their installed-base paths, and 6.2 checks reachability with external_directory ask/deny (S18), reporting unavailable files without bypass. - -Additional pinned sources for these corrections (same release tree, no new source baseline): - -- S13: [packages/core/src/plugin/supervisor.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/plugin/supervisor.ts). -- S13: [packages/core/src/plugin/internal.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/plugin/internal.ts). -- S13: [packages/core/src/config/plugin/command.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/config/plugin/command.ts). -- S18: [packages/core/src/shell/parse.ts](https://github.com/anomalyco/opencode/blob/843a6c514e606b436a7fe713422ace0a93ad3d61/packages/core/src/shell/parse.ts). diff --git a/docs/opencode-sdk-contract.md b/docs/opencode-sdk-contract.md index f808571..ac3d623 100644 --- a/docs/opencode-sdk-contract.md +++ b/docs/opencode-sdk-contract.md @@ -7,7 +7,7 @@ linked below. Incorrect explanatory prose should be corrected; a genuine mismatc between upstream capabilities and required behavior must be reported, not hidden by rewriting facts (see the [documentation index](README.md)). The dated ledger that used to live at this path is preserved as -[historical evidence](history/opencode-sdk-contract-ledger.md). +[historical evidence](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/history/opencode-sdk-contract-ledger.md). ## Versions and sources @@ -34,7 +34,7 @@ to live at this path is preserved as [artifact policy](beads-artifact-policy.md). - Earlier candidate evidence: exact OpenCode 2.2.6 native-host qualification plus one genuine model workflow is recorded in the - [2.2.6 qualification](opencode-22-qualification-5rj2.md). That record is + [2.2.6 qualification](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-22-qualification-5rj2.md). That record is frozen; the published 2.0.0 package carries the same runtime files and packaged guidance with updated version metadata. @@ -124,6 +124,13 @@ Typed write actors are derived from the invocation as `src/continuity.ts`); permission checks use the actual `context.agent`, and attribution grants no permission. +### What to recheck when upstream changes + +- **OpenCode registration:** changes to the transforms above can affect which agents, commands, skills, or typed tools appear and whether user overrides still win. +- **OpenCode session APIs:** changes to hook timing, readable history, or location lookup can affect prime delivery, cache refresh, and replay of saved workflow instructions or diagnostics. +- **OpenCode permissions:** changes to `ctx.permission.assert` or agent rules can affect whether an operation is allowed, denied, or sent for approval. Verify permission outcomes separately from write attribution. +- **Native Beads CLI:** changes in flags, output shapes, or exit codes can affect workspace discovery, prime, diagnostics, and typed operations even when OpenCode registration succeeds. The disposable CLI contract and adapter fixtures below check different parts of that boundary. + ## Typed read example and verification For example, `tools.beads.get({ ids: ["project-42", "project-57"] })` invokes @@ -158,11 +165,3 @@ this reference know which host behavior they depend on. entry; files in `.opencode/plugins/` load automatically. - When running `opencode run` from a non-interactive shell, close stdin (`< /dev/null`); otherwise the CLI waits indefinitely. - -## Former ledger sections - -Older documents link to sections of the former ledger at this path. Those -sections now live in the historical copy: - -- [Task 7.1–7.3 CLI/native bridge ledger](history/opencode-sdk-contract-ledger.md#task-7173-source-candidate--2026-10-21) -- [Tasks 2.2/3.3 native registration and diagnostics](history/opencode-sdk-contract-ledger.md#tasks-2233-source-candidate-native-registration-and-diagnostics) diff --git a/docs/opencode-stop-handoff-qualification-vuy6.md b/docs/opencode-stop-handoff-qualification-vuy6.md deleted file mode 100644 index cbb670a..0000000 --- a/docs/opencode-stop-handoff-qualification-vuy6.md +++ /dev/null @@ -1,99 +0,0 @@ -# OpenCode 2.1.1 live Stop/handoff qualification — vuy.6 / task 4.2 - -## Parent acceptance - -Parent accepted task 4.2 after inspecting the actual-source wrapper, CLI shim and offline assertions, independently running all 74 checks, confirming 151 protected source paths unchanged and independently checking that all three owned ports have no listeners. The selected Stop/Cancel, actual-child outcome/identity, partial handoff and durable/retained/fork recovery mechanics are supported by live observations plus explicitly retained deterministic evidence. The shim's intentional post-mutation output hold establishes started-write uncertainty, not rollback. Model judgment/provider replay/lifecycle evaluation remains task 6.2; unmeasured multi-hour behavior is not certified. No successful post-Stop child callback was fabricated as a live pass. The following worker report preserves the pre-acceptance handoff and its exact limits. - -**The bounded native observations passed. Parent acceptance remains pending.** Explicit native Stop suppressed later composed writes during a started mutation and a pending approval. Actual native children preserved failure, cancellation, NO_TEXT and partial-return distinctions. Primary/child shell and typed actors agreed. Durable readback, summary compaction and a real fork were observed. These are controlled-provider mechanics, not installed activation, external inference or model-judgment acceptance. Task 4.2 remains unchecked and `.6` remains in progress. - -## Candidate, worker and artifact - -Execution date: 2026-10-21 UTC. Sole worker `codex:oc-flow`, fresh session `01a15f8f-fcfb-7990-871e-af2661619648`; actual local rollout `turn_context` records `gpt-6.1-sol`, high effort. No prior-session continuity or additional worker is claimed. Full assignment and original task preimage are retained under **R**, `/opt/data/cache/scratch/vuy6-stop-handoff`, in `prompt.md`, `record-before.json` and `record-current.json`. - -| Identity | Exact value | -| --- | --- | -| Published repository HEAD | `2cbd87363baf67a6a271259cdeec02041fc6cef0` | -| Accepted runtime source | `8831169d3c83c333fdf13d4a4efc743eaf495e2b` | -| Historical 4.1 / deterministic 4.2 | `a5d6b2bea779259ba9aa3175ab86fb2f4f2b862b`, retained accepted | -| Native released host | OpenCode `2.1.1`, source `ba546ec1598a70db2570e9c6258028d955ba8f58` | -| Reused first-party package | `@opencode/cli-linux-x64-baseline@2.1.1`, from `/opt/data/cache/scratch/vuy2-oc-host/release/package/bin/opencode` | -| Executable SHA-256 | `4595933989548a452e920c971d5931898d7d64e73e039f777ed62c84a18916c9` | -| Tarball SHA-256 | `216d3861d0a167adad5850282439bae13483203f4b110f0510f260118bba2858` | -| Immutable wrapper source SHA-256 | `5bf30eae3361928c7b3d46664b8f3adf89b5257a32f2201a5ead1bedfa8aca11` | -| Bundled wrapper SHA-256 | `3e347c202d575e0478d7a6f82517f153660eb4bd2e0cc261512d59fa822226cb` | -| Installed disposable-project CLI | Beads `1.3.1 (c1c4b642a: HEAD@c1c4b642ac1c)`; executable SHA-256 `a8f48d771b9e11eccfced4aed72923b59eda746f7a9b425e7ca1af7a51251653` | - -`identity.json` records the identities, 36 retained source-file SHA-256/Git-blob checks and nine additional pinned local source checks for session, child, execution and compaction APIs. Published tarball SRI/SHA-1 and both registry signatures were reverified using retained metadata/keys. This reuses the accepted release provenance; it does not attest a reproducible binary build. No upstream runtime was transplanted or patched. - -The accepted [source acceptance](code-mode-source-acceptance-vuy10.md), original [flow review](reviews/opus-flow-source-review-vuy6.md), code-mode [REVISE](reviews/opus-code-mode-source-vuy10.md) and [READY recheck](reviews/opus-code-mode-source-recheck-vuy10.md) were consumed. Existing deterministic tests and the 191-test suite were not rerun. The accepted [native follow-up](opencode-host-codemode-qualification-vuy2.md) and [original qualification](opencode-host-qualification-vuy2.md), including the failed stronger plain-decline expectation and superseding owner disposition, remain unchanged. - -## Actual host and adapter boundary - -The committed disposable Git project is `R/repo`, native project ID `df9152e52485c2ead34220bc0e80204f0f9abf25`. Its newly initialized `.beads` is the only issue store used for qualification mutations. Separate HOME, XDG config/data/cache/state and an explicitly constructed environment are recorded in `env.json`/`process.json`; the reliable Bun directory is on PATH. No operator environment or external-provider credential was inherited. The local HTTP/SSE provider uses the released OpenAI-compatible transport, a noncredential provider placeholder and a fresh transient native-server password. It records bodies, never Authorization headers. No external inference occurred. - -The real host ultimately ran PID/group `752378`, loopback port `46749`; the provider ran PID/group `752027`, loopback port `33813`. An earlier setup host PID/group `752064`, port `45097`, was stopped before the qualified sequence. `start.py`, `launch.py`, `provider.py`, `client.py` and `env.json` retain the launcher and payload construction. - -`wrapper.ts` imports actual accepted `setupBeads`; Bun bundles its unchanged ten source modules into read-only `plugin/index.mjs`. The only behavioral dependency supplied is existing internal `continuityQualified:true`. The wrapper observes native hooks/events, forwards `permission.assert` unchanged while logging the real request/result, and never fabricates a child result, calls a callback with invented payloads, prompts/restarts a parent or replaces compaction/replay results. Native session, tool, subagent, cancellation and permission services execute the observations. `wrapper-identity.json` identifies the immutable wrapper, package and executable shim. This is adapter-in-real-host evidence through a test-only qualification seam, not normal installed activation. Ordinary production activation remains withheld. - -The scratch PATH shim `bin/bd` delegates to unchanged `/usr/local/bin/bd`, records actual argv, cwd, wrapper/process PID and exit/stdout/stderr, and adds `--sandbox` to automatic read-only guard/prime calls that otherwise omit it. Typed mutation argv already include their own `--actor` and `--sandbox`; the shim does not replace adapter guard, routing, normalization or acknowledgements. Every actual CLI call stays at `R/repo`. No routing/confinement framework or upstream compensation was introduced. - -For the started-write Stop point, the shim runs the real append to completion, records its result, then holds stdout before the adapter can acknowledge it. Native Stop kills that process group through the real runner. This deliberately measures cancellation while a started operation lacks a returned acknowledgement; it does not claim cancellation before the database mutation or rollback. Other calls are not delayed. No operation is automatically retried. - -The bundled scratch wrapper reports `skill-unreachable SKILL.md` because its bundle does not carry the installed package resource tree. That diagnostic is retained; installed skill discovery/resources and unload/reactivation were not qualified here and remain `.9` work. It did not block native adapter tools or context. - -## Scenario map and measured outcomes - -Every task 4.2 scenario is mapped below. “Reused deterministic” means accepted source evidence was inspected and consumed, without rerunning its fixtures. “Later-model-owned” is an outstanding gate, not waived acceptance. Raw case names refer to `R/cases.jsonl`; native messages, calls and permission payloads also appear in `api.jsonl`/`plugin.jsonl` and provider requests in `provider.jsonl`. - -| Task 4.2 scenario | Classification and evidence | -| --- | --- | -| Stop during composed multi-write work | **Live measured PASS**, `stop-started-multiwrite`. The first actual append process ran; native `POST /api/session/:id/interrupt?resume=false` returned `interrupted:true`. Neither the second note nor priority update dispatched. No next provider step for that stopped call. The original tool is aborted, with no normal leaf acknowledgement. | -| Started mutation uncertainty / no final checkpoint | **Live measured PASS**, same case plus `same-session-recovery` and `retained-compacted-recovery`. Recovery context retains `note "repo-mh4" actor=opencode:probe_ask:7d30f5d3596d: uncertain` and the explicit no-final-checkpoint gap. Authorized readback found the append once. Later success/reads/compaction did not erase its conservative in-session uncertainty. No rollback or final-write guarantee is asserted. | -| Stop during native approval; late acceptance | **Live measured PASS**, `stop-pending-approval`. Native pending permission `per_15f948c20001QCUUXcJg1nGU06` carried the exact note resource, source message/call and `save:[]`. Stop returned true. A late `decision:"once"` reply returned 204; pending permissions became empty, and neither the pending note nor later note spawned. A successful reply response is not execution evidence. | -| Primary shell / typed attribution | **Live measured PASS**, `primary-create`, native `primary-shell-claim`, `primary-checkpoint`. Actual session `ses_ea06cc133ffeKSO5jGi4sgYvGW`, agent `probe_ask`, actor `opencode:probe_ask:7d30f5d3596d` agree across context, typed create/note and direct-shell atomic claim. Permission requests separately carry actual invoking agent/message/call. | -| Actual child identity / shell and typed agreement | **Live measured PASS**, `native-child-created`, `child-partial-handoff`. Native parent `ses_ea06a7ad3ffe7LOswjthORHdbB` launched actual child `ses_ea06a79caffedOGAfB7kcC1vVB` via `subagent`, then continued that same child through native `sessionID`. The native parent context exposes actor `opencode:probe_ask:e9cab5cccfa7`; it is a separate primary session from the started-write case. Child agent `flow_child`, actor `opencode:flow_child:169fca4a5c33`; create, shell claim, typed note and remember agree. This actor differs from the primary actor. | -| Actual invocation versus changed session default | **Reused deterministic + accepted host evidence**: accepted continuity actor/permission fixtures and `.2` `namespace-invoking-agent` prove the deliberately changed-default case. Here every real typed assertion was matched against its actual before-hook session/agent/message/call. No new changed-default matrix was run. | -| Failed child | **Live measured PASS**, `child-failure`, child `ses_ea069eb7bffeQILXxl0GCPw5nY`. Controlled local HTTP 400 fails a real child request. Parent receives native error `Subagent failed (sessionID: …): VUY6_CONTROLLED_CHILD_FAILURE`; original outcome is preserved, no success/closure inferred. | -| Cancelled child | **Live measured PASS**, `child-cancelled`, child `ses_ea069e89dffeMvnHwSJP3hX1bz`. Native child interrupt while parent blocks returns true; native parent result remains `Subagent cancelled (sessionID: …)`. Later fixture response does not revive it. | -| NO_TEXT | **Live measured PASS**, `child-no-text`, child `ses_ea069ee88ffephlywkXHOqTmFH`. Empty child assistant text becomes native completed output `Subagent completed without a text response.` Completion is transport status, not acceptance. | -| Deliberate parent Stop racing child / late work | **Live measured PASS for cancellation winning**, `parent-stop-late-child`. Parent `ses_ea069dc46ffePV50ctoqGofSHz` stops while actual child `ses_ea069db57ffejxDYgD681qsDd4` is running. Child request held 12 seconds; both executions settle. Parent subagent state is error with `error.type:"aborted"` and actual child ID, while progress metadata still says running. That metadata is not treated as completed work. Releasing delayed provider text produces no new provider request, target operation or parent restart. | -| Successfully completed child result arriving after Stop | **Reused deterministic evidence**, `tests/host.test.ts` case “a late child return and execution success after deliberate stop do not restart or imply a final checkpoint”, accepted at `a5d6b2b`, retained by corrected source. Live case above observes native cancellation and late provider response, not a successful completed-child callback after Stop. No such live result was fabricated or relabeled. Background delivery/nested automation were not enabled to force that interleaving. | -| Partial handoff / attempts, rationale, validation, references | **Live measured transport/persistence PASS**, `child-partial-handoff`. Real note/memory acknowledgements and native child text preserve a scoped partial payload, task/memory references, unresolved acceptance, unsaved followup and next action. `.6` deterministic partial/failure fixtures remain consumed. Semantic quality/model obedience is **later-model-owned** by `.9`. The payload’s hypothetical failed approach A and phrase “get validated” are fixture-supplied text, not evidence that the child ran that experiment/get; executed CLI facts come from raw traces. | -| Fresh-session recovery and original ownership | **Live measured PASS for retrieval**, `fresh-recovery`, new session `ses_ea069130dffectIPjfiR0BH8RC`. With no inherited transcript it reads both actual tasks and recalls `vuy6-handoff`. Original audit authors/assignees stay distinct from the fresh session; no recovery claim, closure or reassignment. Model interpretation of that state remains **later-model-owned**. | -| Retained summary/history and real fork | **Live measured PASS**, `native-retained-compaction-final`, `fork-compacted-recovery`, `retained-compacted-recovery`. Native summary contains partial status/references; `metadata.keepID` and legacy `recent` are present. Real fork `ses_ea0682c03ffeNxE1pORWP5CwU1` changes compaction/message/keepID identifiers and preserves summary/recent bytes. Projected context exposes summary/recent rather than enumerating all historical keepID referents; no broader storage-consistency attestation is claimed. Compaction itself makes zero CLI calls. | -| Provider-native replay / provider-model mismatch | **Reused deterministic + later-model-owned**, existing accepted host/context fixtures preserve native.messages, keepID/recent and mismatch semantics. This OpenAI-compatible fixture exercised native summary compaction, not encrypted/provider replacement replay or external-provider/model migration. The latter remain `.9` acceptance; no substituted replay window. | -| Transport reliability | **Live measured, bounded**, five real native children, foreground return, error, cancellation and a 12-second held request; exact settlement/outcome evidence above. No poller, transport rewrite or parent restart engine. Multi-hour reliability and external-provider performance remain **unresolved/unmeasured**; this small scenario set does not certify them. | -| Plain decline / independent later permissions | **Reused accepted host limitation**, original `.2` failure plus accepted follow-up. Nested PLAIN DECLINE may allow independently permissioned later work/model steps; failed stronger termination stays failed. It was never used as Stop evidence. | -| Event-only final save, rollback, automatic retry or closure | **Explicitly unsupported guarantees**, preserved by accepted deterministic evidence and live Stop/readback. No event-driven final write/restart, blind retry or automatic closure occurred. Scope/assignment/acceptance are never inferred from readiness. | - -The scenario set used two real disposable tasks, `repo-mh4` and `repo-s31`, plus scoped memory `vuy6-handoff`; five actual child sessions were created. There were 19 typed invocations (including the refused setup call) and 184 actual CLI invocations, including guard/prime probes and initialization. Counts describe observations, not quotas or acceptance criteria. - -Both task creations were unassigned with `created_by` equal to their actual native creator. Shell claims intentionally assigned each to that same executor. `owner` was absent, read separately rather than inferred. Fresh readback retains both original `created_by` and `assignee`, with `status:"in_progress"`. Parent coordination does not transfer ownership. Historical project-tracker `created_by=unknown` is unchanged; `.6` account-owner field is absent and its assignee remains `codex:oc-flow`. - -The explicit post-Stop handoff was a separately requested normal tool sequence after readback. It records that the first append landed once, later writes never dispatched, final semantic work is unsaved and parent acceptance remains unresolved. Stop itself did not prepare that handoff. Raw records retain the earlier notes as append history. - -## Harness failures retained honestly - -- Initial scratch wrapper build had a syntax error; the initial launcher also used a mistaken scratch artifact path. Both failed before any qualifying tool measurement. The final wrapper was then frozen before live use. -- Initial TMPDIR was `R/tmp`, making sibling `R/repo` fall outside Beads’ designated temporary boundary under `/opt`. The real config-only guard returned `probe-failed`, so the first typed create never reached permissions or mutation. The harness corrected isolated TMPDIR to **R**, matching the prior scaffold, and restarted only its owned setup host. The failed call and guard output remain in raw traces. No source/CLI repair, routing override or hidden fallback. -- Raw case name `child-created-no-text` is a harness mislabel: its native output was `CONTROLLED_FIXTURE_STOP`. The analyzer/report use the later `child-no-text` case for genuine NO_TEXT. The original raw record is retained. -- Two manual native compactions failed: first the controlled response used an unsupported heading; then the response was put at an already-consumed provider index. Both native `compaction.failed` outcomes remain recorded, including the host’s template nudge. `run-retained-final.py` supplies the correct structured template at the actual next request index; its separate completed case is the passing observation. No automatic product retry or replacement compaction result was introduced. -- Final live cleanup assertion initially expected an empty active-session array. Native API actually returned `data:{}`. Raw active, saved and per-session pending responses had already been captured; `final-native-state.json` reconstructs their empty state offline after shutdown. No new host was started to manufacture cleanup evidence. - -## Reproduction, protection and remaining gates - -Run the retained analyzer without host, provider, credential, network or product import: - -```sh -python3 /opt/data/cache/scratch/vuy6-stop-handoff/analyze.py -``` - -It passes **74 checks** over actual invocation/process, permission, cancellation, result and recovery traces. It checks the started/pending forbidden targets, native child errors/NO_TEXT, actual actors and original ownership, compaction/fork observations, and cleanup/protection evidence. It also checks current protected repository, wrapper and operator executable/config bytes. `results.json` retains its output; `evidence-sha256.json` identifies stable evidence. `run-stop.py`, `run-child.py`, `run-outcomes.py`, `run-recovery.py`, `run-retained.py` and `run-retained-final.py`, with corresponding logs and `plans.json`, retain exact driver inputs. Only the offline analyzer is intended for immediate parent rerun; live replay needs a new isolated root and fresh credential. - -Before shutdown, native active sessions were empty, all session pending permissions were empty, and saved grants were empty. `cleanup.json`, `protection.json` and `cleanup.log` record termination of owned groups, absence of their listeners and all 369 recorded invocation/initial-host PIDs, and no listeners on ports `45097`, `46749` or `33813`. Only owned groups were terminated. The transient secret and private unsanitized logs were removed; sanitized raw traces remain. - -All **151** protected repository paths match `protected.json`. All **116** original host evidence files and **85** native follow-up files retain their hashes and path sets. The wrapper/source checksums remain unchanged. Operator OpenCode still reports `2.0.29`; executable SHA-256 remains `7e23471f4ebe2313d78baacc9ac96fe9e197ce26d808de4b0fcc37efbe473dad`, with matching before/after config/package hashes. Operator auth was not used by the isolated runtime: its cleanup SHA-256 and inode/mtime/ctime are recorded in `operator-auth-check.json`; both modification/change times predate this worker. A pre-run auth digest was not captured, so no separate before/after auth digest pair is claimed. No credential contents are logged. Beads minimum/current remains 1.3.1. - -Only this new repository report was added. No production code, old report, SDK, tests, assets, package, OpenSpec or operator integration was edited. No staging, repository commit, push, Dolt synchronization, task checkmark, closure, activation, release, external model call or `.9` dispatch occurred. - -**Remaining limits/gates:** no new selected Stop failure or required source repair was demonstrated. A successful late child callback after Stop remains accepted deterministic evidence rather than a new live interleaving; long-duration reliability is unmeasured; provider-native/mismatch and semantic/model/lifecycle acceptance remain with `.9`. None is silently promoted to live passing evidence. The smallest next gate is parent inspection of this case map/raw traces and an independent offline analyzer run, followed by an explicit decision on task 4.2 acceptance and publication. `.6` stays `in_progress / codex:oc-flow`; the worker does not check the task or close it. diff --git a/docs/opencode-terra-qualification-ug9.md b/docs/opencode-terra-qualification-ug9.md deleted file mode 100644 index c8cd75a..0000000 --- a/docs/opencode-terra-qualification-ug9.md +++ /dev/null @@ -1,24 +0,0 @@ -# Terra task-agent qualification — 2026-11-10 - -Parent acceptance for `opencode-beads-ug9`, OpenSpec task 2.2. This record supplements the [accepted base integration qualification](opencode-22-qualification-5rj2.md); it does not repeat that campaign. - -## Observed result - -Actual OpenCode **2.2.6** loaded the exact prepared **2.1.0** package with `terra: true`. Native model discovery exposed enabled Terra with the `medium` variant, and the package registered the inherited default and Terra agents plus all 30 commands. - -- Parent `ses_e3a4da974ffeXLLwZBauh2kbmY`: `terra_qualification_parent`, `openai/gpt-6.1-sol` / `high`. -- One native subagent call created child `ses_e3a4d919bffd39dwywJDdOjp9H`: `beads-task-agent-terra`, `openai/gpt-6.1-terra` / `medium`. -- The child loaded the packaged skill, discovered `tools.beads.get`, read disposable issue `t21-bne`, and returned its actual title and `TERRA_UG9_READ_ONLY_OK` acceptance marker. -- The Beads result was acknowledged and complete, with no failures. Both sessions completed successfully; the parent remained on Sol/high after the child returned. -- Native assistant records and provider response IDs establish the actual routes. An observation-only context hook agrees; it is pre-serializer evidence, not a wire capture. -- Independent CLI readback found the entire fixture issue unchanged, including revision and timestamps. The three one-time permission grants covered only delegation, packaged skill access and the exact fixture read. No issue write, claim, synchronization or retry occurred. - -The disposable host used a previously user-authenticated native test profile in place, not an operator session. Credentials/databases were not copied, hashed, translated or exported. The owned server and listener were stopped, execution/permission inventories were empty, and transient server secrets/logs were removed. The native test profile remains privately retained in its original custody. - -## Artifact and evidence boundary - -The native run used archive SHA256 `b1e084f66f129ebbf2d857e2fb6b1179e6a427e50c647a9cf612ebbad9f73b89`; all 31 installed files matched. The parent verifier passed 50 assertions. That immutable archive retains the earlier README table saying “Terra qualification pending”; this dated record supersedes that historical status statement, not its runtime bytes. Subsequent release preparation may refresh the README, but must identify the new archive and verify unchanged executable and packaged-guidance bytes rather than relabeling it as the archive used by this run. - -Detailed native sessions, tool results, permissions, before/after issue records, archive inventory, preservation checks and cleanup receipts are retained outside the repository at `/opt/data/research/opencode-beads-terra-qualification/`, indexed by `qualification-report.md` and `analysis.json`. - -This is one representative read-only parent-to-Terra sample, not a model reliability benchmark, Luna requalification or a new permission/disposal campaign. Earlier deterministic source checks cover profile combinations and preserved shared mechanisms. The disclosed `opencode-beads-o66` limitation remains unresolved. Packaged-guidance follow-up `opencode-beads-gjk` is separate and nonblocking. No publication, consumer activation, or canonical specification archival is established by this record. diff --git a/docs/opencode-unload-lifetime-investigation-vuy9.md b/docs/opencode-unload-lifetime-investigation-vuy9.md deleted file mode 100644 index 48b89af..0000000 --- a/docs/opencode-unload-lifetime-investigation-vuy9.md +++ /dev/null @@ -1,72 +0,0 @@ -# OpenCode 2.1.1 unload/lifetime diagnosis — vuy.9 - -**Conclusion: the observed late context is explained by supported location-generation retention. It does not demonstrate an adapter cleanup defect or an upstream bug.** The earlier probe changed configuration and called `/api/location/reload`. That operation detaches the old location graph and builds a replacement; a running step can continue borrowing the old graph. The replacement registry's absence of the package does not establish that the old package's setup cleanup ran. Default managed-service startup uses the same Core lifetime mechanism. - -The [original qualification failure](opencode-installed-model-qualification-vuy9.md) remains failed and unchanged. This diagnosis neither passes task 6.2 nor waives its selected guarantee. Task 6.3 remains unstarted. The smallest recommended disposition is an **owner-reviewed acceptance-probe correction**, distinguishing actual plugin-scope unload from location routing replacement. No product fix is established or authorized. - -## Scope and source identity - -Same sole Sol/high worker: `codex:oc-accept`, actual session `01a15ff1-fc4e-7d53-9b4d-2cb102cd4f76`. Repository HEAD remains `d5e2b172c3ab7106b2ea1a55af3725821f4b4d9a`; accepted adapter source is `8831169d3c83c333fdf13d4a4efc743eaf495e2b`. Investigation root **I** is `/opt/data/cache/scratch/vuy9-lifetime-investigation`; prior qualification root **Q** is `/opt/data/cache/scratch/vuy9-installed-model`. - -All upstream claims below use **`ba546ec1598a70db2570e9c6258028d955ba8f58`**, the exact 2.1.1 source tree. Relevant cached files were reused; only missing relevant files were fetched at that commit. `I/source-manifest.json` records Git-blob identity and SHA-256 for every inspected copy. `I/finding-to-source.json` distinguishes public contract, source facts, prior measurement and inference, with exact paths/lines. The historical `specs/v2/catalog-config-plugin-lifecycle.md` labels its option sketches historical; they were not treated as current API authority. - -**No live probe was needed.** Core comments, public endpoint semantics, request ownership and the retained observer timeline agree. Source provides no plausible foreground-versus-managed lifetime branch requiring a comparison. No host or controlled provider was started, and no credential file was accessed, checked, refreshed or used. No semantic evaluation, implementation, task/contract edit or publication occurred. - -## What the failed probe actually measured - -The prior driver, `Q/lifecycle-settled.py`, wrote its scratch configuration and called **location reload**, with file watching disabled in its isolated environment. It then queried registries through new HTTP requests. Those reads resolve the **current** location map; the running Session drain retains the graph it already borrowed. Two complete location graphs can therefore coexist, with different effective plugins. - -The retained timeline is measured evidence, not a reconstructed provider response: - -| Epoch seconds | Retained observation | -| --- | --- | -| `1792611635.780` | Observer setup in the pre-reload location. | -| `1792611636.0914652` | Real prime output held by the qualification shim. | -| `1792611636.102` | `location.shutdown` observed. This is logical location shutdown, not a logged package cleanup callback. | -| `1792611636.1173723` | `/api/location/reload` returns 204. | -| `1792611636.158` | Another observer setup, while the old step is still active. | -| `1792611636.3035364` | Current plugin registry omits the product; adjacent command/skill/agent snapshots show the replacement registry state. | -| `1792611636.338` | After held output release, the pending context contains one Beads envelope. | -| `1792611636.665` | The actual outgoing OpenAI request contains that envelope. No new inference was performed for this diagnosis. | -| `1792611638.396` | The retained step ends; the event appears twice because overlapping observers saw it. | -| `1792611638.397` | An observer's actual setup disposer logs `observer.dispose`. | -| `1792611638.401` | Session execution succeeds. | - -`I/retained-timeline.json` extracts the original API/observer events. `Q/failure.json` retains the prime and outgoing-frame observations. **Inference:** the deferred observer disposal fits release of the old borrowed graph after its step. Observer records lack generation IDs, so this pairing is not a directly tagged product-disposer measurement. The original probe did not log the product's setup cleanup timestamp. It cannot establish that prime completed *after that cleanup*. - -## Owning scopes and ordering - -The normal whole-location reload path has this order: - -1. The global Session executor acquires the selected location graph through `Instance.provide`, running the location-scoped runner inside that borrowed layer. A `Reloaded` result releases that invocation and recursively acquires the selected replacement. This borrow owns the graph lifetime; an HTTP registry request has its own shorter borrow. [Session execution:95–107](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/execution.ts#L95-L107), [instance selection:8–18](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/effect/app-node-builder.ts#L8-L18). -2. Reload enumerates loaded locations and invalidates their routing entries. `location-services.ts` explicitly preserves running steps' borrowed graphs until a boundary. Its logical shutdown closes permissions, forms and RPC and emits `location.shutdown`; it does **not** call `Plugin.close` there. Replacement builds are then booted. Returning from reload establishes replacement builds, not completion of every old graph's teardown. [Location map:20–37](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/location-service-map.ts#L20-L37), [invalidation:63–79](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/location-services.ts#L63-L79), [logical shutdown:43–59](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/location-lifecycle.ts#L43-L59). -3. The runner checks `lifecycle.isClosed()` at `advanceToStep`. If reload happens after that check while request context preparation is pending, the current step can finish using its captured services. Once that step returns, the next boundary closes its model transport and returns `Reloaded`. No location-closed recheck is inserted between the awaited context hook and construction of the current provider request. [Runner:69–82](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/runner/llm.ts#L69-L82), [current request:228–243](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/session/runner/llm.ts#L228-L243). -4. After old borrowers release, closing that graph reaches the plugin supervisor's `registry.close` finalizer. Core then closes the plugin root/activation scopes. The Promise adapter's actual setup-disposer invocation is `Effect.acquireRelease(...plugin.setup(context2), cleanup => ...cleanup())`, at **`packages/plugin/src/promise/adapter.ts:619–622`**. This is when the product cleanup is invoked, rather than when another graph's registry changes. [Supervisor:135–138](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/plugin/supervisor.ts#L135-L138), [plugin scope close:238–248](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/plugin.ts#L238-L248), [setup cleanup:619–622](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/adapter.ts#L619-L622). - -Promise hook registrations are attached to the setup scope using the captured runtime at adapter lines 243–251. Session callbacks are wrapped as awaited Promises at lines 591–595. The callback itself does not acquire an additional plugin-generation lease: the Session's graph borrow keeps its owning services alive. Hook disposal removes an entry from the map used by **future triggers**. `PluginHooks.trigger` already iterates an array reference; replacing the map's array does not retract callbacks already selected or cancel a Promise already running. The public `SessionContext` declaration provides no unload AbortSignal. [Hook registration/trigger:69–94](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/plugin/hooks.ts#L69-L94), [Promise session declarations:25–37](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/promise/session.ts#L25-L37). - -**In-place plugin removal is a different ordering within the same graph.** A watched config change publishes `Config.Event.Updated`; the existing supervisor reruns activation. For a healthy removed/replaced plugin suffix, `Plugin.activate` deletes the old active slot, **awaits `Scope.close` of its activation**, loads remaining/replacement definitions, assigns the new public inventory, then publishes `Plugin.Event.Updated`. It does not first detach a location graph and substitute another registry. Normal plugin removal/replacement must also be distinguished from the separate transform-failure recovery path, which can schedule teardown asynchronously. [Normal activation:125–175](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/plugin.ts#L125-L175), [config-change activation:223–244](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/src/plugin/supervisor.ts#L223-L244). - -## Adapter responsibility and the selected guarantee - -The accepted adapter's cleanup immediately sets its abort flag and disposes the context controller before awaiting registration/observer cleanup: `src/host.ts:172–190`. Controller disposal marks it disposed and aborts cached loads; `systemFor` checks disposal/abort again after its awaited load (`src/context.ts:173–175,187–191`). The host context hook checks the plugin abort flag after awaiting `systemFor`, before appending context (`src/host.ts:357–358`). Thus the accepted source already suppresses late injection **when actual setup cleanup has occurred before completion**. This is source evidence, not a new runtime pass or proof covering every race. - -The public Promise-plugin documentation says OpenCode awaits cleanup on actual unload/replacement. The public **location.reload** description separately says running sessions continue with fresh services at the next step boundary. Those are compatible contracts. The old probe substituted absence from a replacement graph's registry for completion of the old setup scope's cleanup. The unconditional interpretation “no old output after location reload returns or the new registry omits the package” exceeds the public/native 2.1.1 reload behavior. The narrower actual-unload guarantee remains a reasonable separate acceptance target and still needs its correctly owned observation. [Plugin cleanup docs:29–38](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/src/README.md#L29-L38), [public reload contract:51–59](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/protocol/src/groups/location.ts#L51-L59). - -There is no demonstrated failure of the adapter's abort checks after its cleanup, no demonstrated upstream violation of the documented reload boundary, and no basis for a downstream drain/supervisor/replay engine. The original stronger selected acceptance result remains **failed**, not retroactively passing under this explanation. - -## Managed service and practical consequence - -The user's default-service correction is confirmed. `server-connection.ts:21–48` selects an explicit endpoint for `--server`, a private server for `--standalone` or disabled service, and otherwise resolves a managed service with `Service.ensure`. Its managed command is the same CLI `serve --service` (`service-config.ts:133–145`). Private standalone starts `serve --stdio --port 0`, with stdin acting as its process ownership lease. - -Foreground and managed modes converge on the same server `start(...)` in `server-process.ts:100–160`, and the same `AppNodeBuilder`/`buildLocationServiceMap` Core graph. Managed mode changes discovery/registration, persistent process ownership, saved server settings/environment and startup cwd; explicit session location therefore matters. It does **not** select a different plugin cleanup or current-step reload rule. This conclusion is source-backed; it is not a claim that managed startup itself was live-qualified. [Connection selection](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/cli/src/services/server-connection.ts#L21-L48), [common server launch](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/cli/src/server-process.ts#L100-L160). - -For real managed-service users, closing or reopening a client does not imply server/plugin teardown. Config reload can make new requests use new registries while a current step finishes with its old context. Native watched plugin changes can instead unload/rebuild plugin scopes in the existing location. Restarting the server is process teardown with separate execution recovery semantics, and deliberate Stop is explicit cancellation. None of those operations is interchangeable with a registry query or hot location reload. No operator action was performed here. - -## Recommended owner disposition and remaining limits - -Recommend recording a **probe/lifecycle-boundary mismatch**, not opening a repair campaign. Owner should decide whether the installed unload criterion means actual plugin-scope cleanup or immediate revocation at whole-location routing replacement. For actual unload, the smallest later scoped gate is a controlled native watched-config plugin removal/reactivation observation in the same location graph, recording the setup disposer and pending context ordering. Keep the existing no-output-after-actual-cleanup checks and preserved failure; do not silently alter tasks/specs. If immediate revocation at location replacement is intended, it is an unsupported stronger contract requiring explicit owner disposition, not an inferred adapter bug. - -No new probe was run: the source/log evidence resolves the cause category, while the unlogged product-disposer timestamp and unexecuted in-place installed probe remain explicit empirical limits. No exact cleanup timestamp, managed-mode runtime comparison or passing actual-unload result is invented. Follow-up authority belongs to the parent/owner; this memo does not resume 6.2/6.3. - -`I/verification.json` records exact-source identity, source-map references, report links/whitespace, unchanged frozen repository/prior-evidence bytes and known noncredential operator executable/config bytes. No new host/provider processes, listeners, sessions, grants or transient server secrets were created. Only this new memo is added; the original failed report and all existing tracked/untracked files are preserved. `.9` remains `in_progress / codex:oc-accept`; markers remain 14 accepted / 2 unchecked. Final bounded handoff: `I/result.md`. diff --git a/docs/reviews/2026-11-13-opencode-2.2.0-final-review.md b/docs/reviews/2026-11-13-opencode-2.2.0-final-review.md deleted file mode 100644 index b46a433..0000000 --- a/docs/reviews/2026-11-13-opencode-2.2.0-final-review.md +++ /dev/null @@ -1,59 +0,0 @@ -# Final 2.2.0 source-plus-qualification review - -Reviewer: Claude Code, actual `claude-opus-5-5`, requested medium effort; resumed session `fbbee515-a562-46ab-892a-1a3b4e455afd`. Completed without errors or permission denials. Parent verified complete candidate membership and hashes match the frozen reviewed manifest. This evidence-only record was added after review and does not alter any reviewed source. - -Optional-observation disposition: retain the exact reviewed candidate; nonblocking wording nits are deferred. The public release highlights will emphasize the support drop as **Breaking** without changing the owner-selected minor version. Original planning commit `bc8031c1f8bb80baf0f739cb6fff0644d902a5c2` preserves pre-disposition task text. Hosted CI, registry and installation verification remain separately required. - -## Original reviewer verdict - -**Verdict: READY.** This covers the final source-plus-qualification scope for the exact `@snarkipus/opencode-beads` **2.2.0** candidate: -- baseline `bc8031c` plus the frozen snapshot and patch; -- release archive `1e0df828…`, and qualified archive `80d3295b…` with identical runtime; -- the native evidence and the owner's disposition of the two gaps. - -I only read files. I reran nothing: the 233 tests / 12,354 assertions, typecheck, smoke, validation and the archive-to-archive comparison are taken from the worker's report and your parent verification. My earlier source-stage READY still holds, because `src/`, assets and tests are unchanged from that review. The release patch adds only metadata, docs, specs and the archive move. - -**What this does not establish** -- Hosted CI on the exact head, merge, tag, trusted stable/`latest` publication, registry provenance, or that installing from the registry works. npm 2.2.0 currently returns E404. -- Any native evidence for the two deferred cases (unexecuted, not passed): - - repeated idle reports while the same work is outstanding; - - cancellation while the real `bd` process is still running. -- Behaviour on 2.3 patches above 2.3.0, model reliability, or any cross-provider claim. -- A fix for o66, or any change to replay or metadata. - -**Standards axis** -- The release step leaves runtime untouched: per the archive comparison, only `README.md` and the `package.json` version differ. -- No new mechanism, guard or test campaign was added. The doc-contract assertions in `tests/docs.test.ts:711-727` pin the user-visible claims without duplicating behaviour tests. -- The qualification record is new and dated (`docs/opencode-23-qualification-xwq.md`), and earlier records stay frozen. This follows AGENTS.md L17. -- The original INCOMPLETE worker reports are kept as history, and the owner's decision is recorded as a later disposition (qualification record L54). - -**Spec axis** -- **Support policy.** The canonical `workflow-access` spec says exact 2.3.0 with `>=2.3.0 <2.4` admission. That matches the guard, the peer range, the exact 2.3.0 SDK dev dependency, the lockfile, `test-package.ts` and every current doc. - - The released 2.1.0 pin for 2.2 hosts is stated clearly in the README (L81), the user guide's Upgrading section (L240) and a new `2.1.0 released` compatibility-table row. That fixes my earlier observation. -- **Claims match the evidence.** Each claim in the qualification record's "Measured native coverage" (L18-26) traces to a PASS / PASS (bounded) row in `native-report.md` or `remaining-report.md`: - - launch handle and idle wake; - - active-parent task and knowledge freshness, based on the real permissioned reads, not prose; - - VM `find`/`get`; - - stop at the permission wait; - - parent stop followed by a late report with no further tools; - - the landed write. - - The output-hold shim is disclosed as not being a mid-`bd` kill, and the observer is described as capturing before serialization, not on the provider wire. -- **Deferrals.** Each of the two gaps has a recorded gap, rationale, residual uncertainty and revisit triggers. README, user guide, SDK contract and CHANGELOG all repeat "deferred and unexecuted". None calls them passed. -- **Canonical specs and archive.** - - `work-continuity` adds the two delegation scenarios and retargets "selected 2.2 host" to "selected host". `workflow-access` retargets to 2.3. No other identities change. - - The archived `tasks.md` explicitly says the 3.1/3.2 checkmarks record accepted evidence and deferral, not execution of the two cases (L3, L21). - - A canonical scenario requirement ("repeated idle reports…") that has no native evidence yet is consistent with AGENTS.md L18: specs define intended behaviour, and the gap is disclosed. -- **Release metadata lines up:** - - `package.json` 2.2.0; - - install and options examples in README and user guide at `@2.2.0`; - - CHANGELOG `[2.2.0]` section and compare/tag links; - - reviewed-version marker 2.2.7→2.3.0, which your preparation report says the owner explicitly authorized; - - Beads 1.3.1 minimum, validated 1.3.4. - -**Blockers:** none. - -**Optional nits** (none block the release) -1. `docs/user-guide.md` (~L256) says "…apply to their recorded candidates, not this 2.3 candidate". Replace "this 2.3 candidate" with "2.2.0". -2. CHANGELOG `[2.2.0]`: the first bullet could start with **Breaking:** so users who skim notice the dropped 2.2 support. This is only a label; it doesn't reopen the minor-version decision. -3. In the archived `tasks.md`, the wording of 3.1/3.2 now differs from the plan text reviewed at `bc8031c`. That is acceptable because the archive records the disposition and the original stays in git history, but a one-line note pointing to the original would help traceability. -4. Qualification record L64 says the 2.2.0 preparation "reconciles" the docs, which reads as future work. Past tense would read better once this is merged. \ No newline at end of file diff --git a/docs/reviews/2026-11-13-opencode-2.3-spec-review.md b/docs/reviews/2026-11-13-opencode-2.3-spec-review.md deleted file mode 100644 index 900a4d9..0000000 --- a/docs/reviews/2026-11-13-opencode-2.3-spec-review.md +++ /dev/null @@ -1,33 +0,0 @@ -# OpenCode 2.3 compatibility specification review - -- Baseline: `63386812c6b57b1e91e8f834c3240f22b418e1d8`. -- Change: `openspec/changes/adapt-opencode-2-3/`. -- Reviewer: Claude Code, actual `claude-opus-5-5`, requested medium effort; session `ea45b0bb-b870-4081-9fd5-dbef465f27d2`. -- Scope: independent planning-package review only, not implementation or installed-host qualification. -- Owner selected exact 2.3.0 qualification and `>=2.3.0 <2.4` admission, dropping 2.2 support for the future candidate. - -## Original verdict: REVISE - -One blocking finding: two canonical scenarios still called 2.2 the selected/current host. The availability delta alone left those clauses inconsistent with the selected floor. - -Parent correction added complete MODIFIED blocks for Native trigger and semantic responsibility separation and Documented snapshot-recovery deficiency, changing only the selected/current host references. Scenario identities and all replay/stop/deficiency semantics remain intact. Proposal and design mappings were updated. - -Optional advice dispositions: - -- N1, add a separate prohibition on a 2.2 blocking-return layer: declined as redundant with the selected support floor and existing non-goals. -- N2, distinguish admission prose from measured native qualification: adopted in task 2.1. -- N3, report unexercised native branches as incomplete: adopted in task 3.1 without waiving required acceptance evidence. - -## Same-reviewer recheck: READY - -The exact substantive reviewer session checked the correction-only patch and full corrected immutable package. Both runs completed with `is_error: false`, `terminal_reason: completed`, actual Opus 5.5 model usage, no permission denials and no subagents. - -Standards: proportionate wording-only correction, evidence ownership preserved. Spec: both retargeted requirements match canonical text except the host references; scenario identities and existing guarantees remain coherent. - -Final optional observation: task 3.3 could say “semantically unchanged” rather than “unchanged” for the retargeted requirements. Parent disposition: no additional edit required; the design explicitly identifies the wording-only changes and unchanged semantics. This is not an unresolved acceptance blocker. - -## Parent verification and boundaries - -Parent independently reran strict validation for the change and all three canonical specs: pass, zero issues. The complete six-file live planning candidate matched the corrected review manifest before publication. No product tests or native checks were rerun for this planning-only change. Canonical specs, product code, pins and reviewed-release marker remain unchanged. Implementation mapping may follow publication; implementation, native qualification, release and operator upgrades require their own dispatch. - -Full raw streams, original verdict, correction patch, dispositions and frozen manifests are retained under `/opt/data/research/opencode-2.3.0-plugin-impact/spec-review/`. These local evidence paths are not product runtime dependencies. diff --git a/docs/reviews/2026-11-14-native-beads-store-source-review.md b/docs/reviews/2026-11-14-native-beads-store-source-review.md deleted file mode 100644 index 7dd3248..0000000 --- a/docs/reviews/2026-11-14-native-beads-store-source-review.md +++ /dev/null @@ -1,27 +0,0 @@ -**Verdict: READY.** I found no blocking defects in the uncommitted candidate (baseline `8127826`), including the new `openspec/changes/correct-beads-guard-observation/` files. This does not authorize acceptance, a commit, archival, publication or any action on operator stores; those stay with the parent. - -**What I inspected:** the full `candidate.diff` and `status.txt`, current `src/guard.ts`, the relevant parts of `src/continuity.ts`, `src/context.ts` and `src/host.ts`, the test fixture in `tests/guard.test.ts`, the requirement headings of the new spec delta, and a search of `src/` for leftover marker-gate or `autoMigrate` references. - -**What I executed:** nothing. The 231 tests, typecheck, package smoke test and real 1.3.4 contract run are the parent's evidence, not mine, and none of it is installed or live qualification. - -## Standards -- **The marker gate and `autoMigrate` bypass are fully removed.** `guard.ts` no longer touches the filesystem; its runtime is `bd` only (lines 16-19 and 102-104). The only remaining checks are the 1.3.1 minimum and the config-only workspace probe (lines 71-99). In `src/`, `autoMigrate` now appears only in the comment at `host.ts:76`. `readText` remains only in `workflows.ts`, where it reads the skill file and has nothing to do with the gate. Nothing still calls `migration-pending`. -- **Typed operations keep their checks.** `continuity.ts:316-322` still checks the session location, then reruns the compatibility check after permission is granted and before the command runs. Actor and cancellation handling are unchanged. -- **Native full prime is unchanged.** `host.ts:105` still runs the normal prime with `--full`, plus `--stealth` when enabled, and the context path returns its output verbatim. Native memories and partial-availability text pass through as-is. Prime failures still produce the existing failure notice. -- **The tests give real regression evidence.** - - The host test (`host.test.ts` "native full prime ignores CLI witnesses…") writes an actual `.local_version` file and runs the production runtime. It checks every marker state combined with `autoMigrate` set to undefined, false or true. It asserts that prime receives `["--full"]`, that only `version` and `context --json` run first, and that the native memory and partial-availability text is rendered unchanged. The old code would have failed this test, so it is a genuine RED→GREEN check. - - The continuity test checks that the minimum version is enforced both before and after permission, and that `show` never runs when the check fails. -- **Contract script:** removing the marker and `migrate schema` assertions is correctly scoped; the prime, stealth and MCP checks are kept. -- **The guard runtime has no other callers.** The 11 typed operations and 30 commands don't depend on it, and the diff doesn't touch either. - -## Spec findings -- The code matches the active delta. The new requirement "Native Beads store ownership" covers witness-independence, ignoring legacy `autoMigrate`, preserving full native context and partial results, and separating missing prerequisites from failed ones. -- Diagnostics now promises "without opening a store" (delta lines 71 and 83). The host diagnostics test still runs only the config probes and now also asserts that no marker or migrate wording appears. -- None of the plugin's own protections were removed. Host admission, the CLI minimum, the workspace probe, the session-location hold, permissions, actor handling, cancellation, and the rule against substituting `where` or a manual prime are all intact. Only the witness-based schema decision was removed, and that now belongs to native Beads. -- One pre-existing gap is unchanged and not made worse: a successful context envelope is not checked for `schema_version` (the parent already disclosed this). - -## Optional observations (non-blocking) -1. **Leftover "held" wording.** `continuity.ts:322` still throws `Beads store held: ${guard.kind}`, so an old CLI or a failed probe is reported as a "store hold", which echoes the removed feature. Something like `Beads CLI/workspace check failed: …` would be clearer; the existing test only matches "unsupported". `context.ts:119` likewise labels the `unsupported` kind as status "withheld". That predates this change and is acceptable, but "withheld" now really means explicit holds. -2. **Two tautological test assertions.** `continuity.test.ts` slips an unused `readText` into the dependencies with `Object.assign` and then asserts it was never called. The `runtime()` fixture in `tests/guard.test.ts` (lines 16-26) does the same. Since nothing can call `readText` any more, those assertions prove nothing. The other assertions in the same tests do carry the regression, so these could simply be dropped. -3. **Leftover block in `bd-contract.ts`.** The bare `{ … }` block left after removing `if (markerPath)` (diff line 300) could be un-nested. -4. **Spec title.** The "Migration hold conflicts with prime-first advice" scenario title (delta line 8) still suggests a plugin-issued migration hold. That's cosmetic; the scenario body is correct. \ No newline at end of file diff --git a/docs/reviews/2026-11-14-opencode-2.2.1-final-review.md b/docs/reviews/2026-11-14-opencode-2.2.1-final-review.md deleted file mode 100644 index f50e9d9..0000000 --- a/docs/reviews/2026-11-14-opencode-2.2.1-final-review.md +++ /dev/null @@ -1,23 +0,0 @@ -**Verdict: READY.** I found no blocking defects in the 2.2.1 closeout. This verdict is not evidence that CI, a merge or npm publication has happened; those belong to the parent. - -**What I inspected:** `closeout.diff`, current `README.md` lines 14-58 and the CHANGELOG head, the summary of `tests.log`, and `package.log`. I also searched for stray version pins in `src/*.ts`, `docs/opencode-sdk-contract.md` and `.opencode/opencode.json`. - -**What I executed:** nothing. The parent's logs show 231 pass, 0 fail, 12457 assertions across 14 files (`tests.log:262-265`). `package.log:8` shows the packed archive validated at SHA `dfb8bf69…ee6ee2`. Both are parent evidence, not runs of mine, and there is no operator or live-host qualification. - -## Closeout findings -- **Versions are consistent.** `package.json` is 2.2.1, and so are the README install pin, the user-guide exact pin and options example, and the CHANGELOG section. The `[unreleased]` compare link now starts from v2.2.1, and the `[2.2.1]` tag link is added. That satisfies the AGENTS.md release checklist. The Unreleased section is empty and its Fixed entry moved under 2.2.1. The diff shows no `src/` or `assets/` changes, which matches the parent's byte-for-byte check. -- **Qualification claims are honest.** - - The user-guide row for 2.2.1 says "Deterministic/package regression checks; inherits 2.2.0 native baseline". - - The paragraph below it says "no new installed-host qualification is claimed". - - The deferred items (idle reports, cancellation during real bd execution) are kept, as is "Admission does not qualify later patches". - - The README upgrade note likewise says it "remains the recorded 2.2.0 baseline". - - Nothing claims every 2.3.x host patch was measured. -- **Safety wording is present.** The README upgrade note says native opens may migrate, says to follow the native upgrade procedure before upgrading `bd`, and says `autoMigrate` is ignored. That matches the accepted contract. -- **The OpenSpec archive and sync match the accepted delta.** The archive is a pure rename apart from `design.md`, where the stale "local candidate only" wording was replaced. The canonical spec gains one requirement ("Native Beads store ownership") and modifies three: coherent context, typed operation boundary, and diagnostics. One scenario gains the extra line saying observations don't certify SQL health or memory delivery. The new explanatory sentence above the hold scenario resolves my earlier note about its title without renaming the scenario. -- **The docs test changes are sound.** They now derive the version from the manifest instead of hard-coding "2.2.0", and they assert both the inherited-baseline row and the upgrade heading. -- **The repo's own `.opencode` pin was not bumped**, which follows the repo note to change it only after npm publish. - -## Optional nits (non-blocking) -1. The README compatibility table row (`README.md:25`) still reads "Exact 2.3.0 bounded native qualification" without saying it is inherited from 2.2.0. The upgrade note covers this, but "(2.2.0 baseline)" in that cell would mirror the user guide. -2. The evidence wording varies slightly. `user-guide.md` says "deterministic, package and real Beads CLI contract checks", while the README says "deterministic and packaged regression checks". Both are accurate, because the real 1.3.4 contract ran on unchanged source, but aligning them would avoid one looking like it under-claims. -3. Patch versus minor is the owner's call. The release makes `autoMigrate` inert and withdraws the plugin-level hold. Framing that as a bug fix fits the AGENTS.md patch definition, given that options are still accepted and nothing breaks. If the GitHub release notes repeat the "native opens may migrate" line, that would help. \ No newline at end of file diff --git a/docs/reviews/astra-opencode-22-mapping-65r.md b/docs/reviews/astra-opencode-22-mapping-65r.md deleted file mode 100644 index a9db8ba..0000000 --- a/docs/reviews/astra-opencode-22-mapping-65r.md +++ /dev/null @@ -1,17 +0,0 @@ -# READY — bounded spec-to-Bead mapping review - -Reviewed the actual exported records against accepted commit `0ad03a6eebc61d3c0559610fbacd22989b47b21f`, reading `tasks.md`, `design.md` and `proposal.md` directly from Git. HEAD matches that commit; the working tree was clean. This verdict concerns mapping only, not implementation readiness or dispatch authority. - -**Findings: no material gaps, duplicates or authority mistakes. No corrections required.** - -- **Exclusive coverage:** `opencode-beads-5rj.1` owns exactly 1.1, 1.2 and 2.1; `opencode-beads-5rj.2` owns exactly 2.2 and 2.3. All five accepted task IDs occur once across execution leaves, with no extras. The epic and review record have empty task membership. All five spec checkboxes remain unchecked. -- **Prerequisites and parentage:** both leaves identify `opencode-beads-5rj` as parent. Qualification's `blocks` dependency points to the source leaf, correctly making source its prerequisite; acceptance additionally requires the exact parent-accepted revision/artifact digest. The epic's `discovered-from` edge to `9za` and review's `discovered-from` edge to the epic are provenance, not execution blockers. Parent-child edges are likewise not blocker edges. No exported edge gates delivery on `o66` or `rou`. -- **Scope and acceptance:** source owns the two adapter seams, accompanying documentation/regressions, normal full gates and one frozen artifact. Continuity, Beads behavior and agent definitions remain preservation/verification surfaces. Qualification consumes that artifact and evidence, retains permission/actor/Stop coverage, bounds genuine-provider work and requires honest pass/limitation/failure/unexecuted reporting. The pinned tasks remain authoritative for detailed requirements, including task 2.3's migration/release recommendation; concise record summaries do not remove them. -- **Markers and closure:** parent-accepted evidence controls task markers. Epic closeout requires both children, actual host qualification, owner acceptance and canonical sync/archive under granted authority; source-only success cannot close delivery. `o66` remains unresolved and nonblocking. Missing snapshots after the specified model switch are explicitly disclosed unavailable, not claimed restored. Monitoring stays separate. -- **Authority and stops:** all three execution records are open, have no exported assignee, and state mapping-only/execution-authorized false. `created_by: snarkimedes` is audit authorship, not executor assignment; no owner field is exported. Review coordination implies no worker claim. Provisioning absence leaves qualification pending. Additional mitigation requires discussion with Matt; the pinned design also supplies its concrete snapshot-resolution stop condition. Publication, operator changes and release remain separately authorized. - -**Proportionate:** one epic, two meaningful delivery leaves and one bounded review record are appropriate. The task preamble's older “one implementation Bead” wording is superseded by Matt's explicit source/qualification split in this request; it is not a mapping defect. No extra tickets, graph expansion, test cuts or architecture reconsideration are warranted. - -**Evidence:** `/opt/data/research/opencode-beads-2.2.6-impact/bead-mapping-records.json` and adjacent `bead-mapping.json`; pinned files under `openspec/changes/adapt-opencode-2-2/`. - -**Limits:** export-only tracker review; parent retains live re-fetch, graph/count/hash verification and acceptance. No bd invocation, tests, research campaign, project edits, Git writes or delegation. Only this report was written. diff --git a/docs/reviews/claude-opencode-22-final-recheck-tjd.md b/docs/reviews/claude-opencode-22-final-recheck-tjd.md deleted file mode 100644 index 292c4c8..0000000 --- a/docs/reviews/claude-opencode-22-final-recheck-tjd.md +++ /dev/null @@ -1,33 +0,0 @@ -# F1 recheck: final SOURCE+QUALIFICATION gate (`opencode-beads-tjd`, session `71dc3fce-9fb7-40a3-a7eb-c833ba95d080`) - -I read `f1-correction.patch`, grepped the current docs, and looked at the parent's test log. I ran nothing and wrote nothing. - -## Verdicts - -- **Standards: READY.** The correction only touches docs and one test. It adds no runtime change, no packed-file change and no new mechanism. -- **Spec (corrected final gate): READY.** F1 is resolved, and the correction introduced no material regression. - -## F1: resolved - -- **SDK contract:** `docs/opencode-sdk-contract.md:5` and `:169` now say exact OpenCode 2.2.6 qualification is parent-accepted for the full archive SHA-256 `072d9c29…ac836`. Both link to `opencode-22-qualification-5rj2.md` and say `opencode-beads-o66` is still unresolved. A grep of `docs/` finds no remaining "has not been qualified" sentence. The wording doesn't overclaim: it doesn't call the candidate released, and the published beta.5 range and "not a release or operator activation" are still stated in the same paragraph. -- **Tests:** in `tests/docs.test.ts`, the old assertion is replaced by checks for the accepted-status phrase, the digest and the link. A new negative check makes sure the obsolete wording can't come back. The README table assertion at `:215` is deliberately left as it was, which is correct because the README is packed and frozen. -- **Summary:** the new "Frozen README status" bullet at `docs/opencode-22-qualification-5rj2.md:37`: - - names `README.md:24` and `:202` exactly; - - says this summary supersedes them for that exact digest; - - assigns updating both README statements and their compatibility-row test to the separately authorized 2.0.0 metadata change; - - forbids changing or silently repackaging the qualified archive. - - That covers the task 2.3 duty to reconcile docs while leaving the remaining gap explicit. Nothing else in the summary changed. - -## Regression check - -- **Packed files and archive:** the three changed files are all outside the package. `package.json` `files` covers only `src`, `assets/oc-beads`, `README.md` and `LICENSE`. So the 31-file archive identity is unaffected, which matches the parent's byte-identity and SHA check. -- **Tests:** `f1-green-tests.log:245-248` shows 218 pass, 0 fail, 11,888 `expect()` calls, across 12 files. The parent's red log shows the updated assertion first failing at `docs.test.ts:212`, as expected. -- **Wording:** the new text doesn't contradict the README's o66 limitation, the published beta.5 range or the 2.0.0 release recommendation. - -## Optional (nonblocking) - -- The assertion count went up by 5, while the patch's net change is +3 explicit `expect` lines. This most likely comes from shared helpers or iterated checks. It doesn't affect the verdict. -- The earlier optional observations still stand and are still nonblocking. - -READY here closes the final review of this exact runtime and qualification candidate, so parent can now accept task 2.3. It does not approve publication, release, version or metadata changes, canonical sync or archive, CI, or operator activation, and it does not resolve `o66`. diff --git a/docs/reviews/claude-opencode-22-final-tjd.md b/docs/reviews/claude-opencode-22-final-tjd.md deleted file mode 100644 index 6d94920..0000000 --- a/docs/reviews/claude-opencode-22-final-tjd.md +++ /dev/null @@ -1,50 +0,0 @@ -# Final SOURCE+QUALIFICATION gate — `opencode-beads-tjd` (session `71dc3fce-9fb7-40a3-a7eb-c833ba95d080`) - -**Candidate:** runtime `ccc9851`, HEAD `f221779`, plus the uncommitted qualification docs and the task 2.2 marker. Archive SHA-256 is `072d9c29…ac836`. I only used Read, Grep and Glob. I did not run, edit or change anything. - -## Verdicts - -- **Standards: READY.** No findings. -- **Spec (final source+qualification gate): REVISE.** There is one finding, and it is documentation only. The runtime, archive and evidence need no change. - -## Material finding - -**F1 — Current docs still say the candidate is unqualified. Task 2.3 requires reconciling them.** - -- **What the contract says:** task 2.3 (`openspec/changes/adapt-opencode-2-2/tasks.md:14`) requires "Reconcile current docs and task markers from accepted evidence, leaving limitations/unexecuted checks explicit." -- **What the summary says:** `docs/opencode-22-qualification-5rj2.md:5` says the selected installed-host qualification on 2.2.6 is parent-accepted. -- **What the other current docs still say:** - - `docs/opencode-sdk-contract.md:5` — "The 2.2.6 runtime candidate has not been qualified." - - `docs/opencode-sdk-contract.md:169` — the same sentence again. - - `README.md:24` — "The candidate has not passed live host qualification." - - `README.md:202` — the compatibility table row reads "2.2.6 (source target; host gate pending)". - - `tests/docs.test.ts:212,215` pin both the SDK-contract sentence and the README table row as they are. -- **Consequence:** the repository's own SDK contract and README contradict the accepted qualification summary. If parent marks 2.3 complete now, the record would claim docs are reconciled when two current docs still say the opposite. Readers or the 2.0.0 release work could pick up a wrong "unqualified/pending" status. This understates the evidence rather than overclaiming it, so it is not a safety problem. It is still a gap against the task contract. -- **Packaging constraint:** `README.md` is one of the packed files (`package.json:44-49`). Editing it changes the archive, so it can't be fixed in this frozen candidate. `docs/` is not packed. -- **Smallest correction (no runtime or archive change):** - 1. Update `docs/opencode-sdk-contract.md:5,169` to say exact 2.2.6 qualification is parent-accepted for this archive digest, link the summary, and restate that `o66` is unresolved. Update `tests/docs.test.ts:212` to match. - 2. Add one line to the summary's limitations or next-steps section. It should say that the README text at lines 24 and 202 is frozen packed text, superseded by the summary for this digest, and will be updated in the separately authorized 2.0.0 metadata change, together with `tests/docs.test.ts:215`. - -A recheck only needs to confirm those two edits and that the 31-file archive identity is unchanged. - -## What I checked and found sound - -- **Pending-unload abort (completion pass).** `completion-pass/timeline.jsonl:4-8` shows this order: - 1. The callback was confirmed pending while the real child had already exited (`realChildExists:false`, `commandReturned:false`). - 2. Config removal, then "Beads workflow unloaded" about 271 ms later. - 3. The shim was gone before `hold-release`. - - `analyze.py:31-36` independently checks the order of cleanup completion and hold release, that no output was released or forwarded for the held PID, that it happened before the ordinary timeout, and that there was no late admission or provider frame. These checks are meaningful and are not a relabel of the earlier too-early sample. The initial analyzer at `analyze.py:52` still records that sample as unqualified. -- **Denied, child-session and Stop outcomes (initial pass).** The denied leaf was rejected and the independent read was acknowledged (`analyze.py:33-34`). The child session had a distinct actor (`:37`). The final fixture readback contains exactly `CONTROLLED_NOTE_5RJ2\nCHILD_NOTE_5RJ2` (`:49`), so neither the denied write nor the Stop-interrupted write landed. The failed permission-entry retirement is still recorded as a failure (`:48`) and was not turned into a repair requirement. That matches the owner-settled scope. -- **o66 limitation behavior.** After the A→B switch, old message IDs are absent, the notice appears exactly once, current snapshots expand twice, and nothing is reconstructed (`analyze.py:42-44`). This matches `specs/workflow-access/spec.md:205-209` and `specs/work-continuity/spec.md:30`. The malformed first compaction is kept as failed (`:38`). -- **Genuine sample.** `genuine-pass/readback-receipts.json:11` shows the target notes as `ORIGINAL_TARGET_NOTE\nGENUINE_NOTE_5RJ2_ONCE` with no assignee, and the creator kept. The sentinel at `:23` still has its original `updated_at`. The report keeps its evidence boundaries clear: pre-serializer contexts are not wire captures, there was one sample, and there was no retry. This fits the task 2.2 limit of one representative genuine workflow. -- **Frozen patch scope.** `tracked.patch` touches only the SDK/admission, workflow-transport, guidance, test, doc and AGENTS files, consistent with the accepted source review. Version stays `1.1.0-beta.5`. The Beads minimum stays 1.3.1. -- **Release recommendation.** It is proportionate and scoped correctly: stable 2.0.0, a new host floor, existing exact pins kept, OpenCode upgraded before the plugin, and npm tags unchanged (`qualification-5rj2.md:46-51`). It doesn't claim any future metadata, CI or archive work is done. - -## Optional observations (nonblocking) - -1. **Initial report's final verdict.** `analyze.py:55` still prints `BLOCKED/PARTIAL`, and `:54` asserts the genuine gate was blocked. That is correct historical output. Anyone rerunning it should read it together with the summary's integration paragraph (`qualification-5rj2.md:23`), which already explains it. -2. **Abort timing check.** `completion-pass/analyze.py:35` compares the abort timing against a hard-coded 1000 ms rather than the product's actual timeout value. That's fine for this evidence, since the observed ~271 ms is well inside it, but citing the real timeout would make the assertion clearer. -3. **File counts.** The summary's "197 tracked-file baseline" plus the 4 new docs adds up to the manifest's 201. They are consistent, but the summary doesn't state the 201 total, so a reader has to work it out. - -READY was not granted here. Even once granted, it would not authorize publication, release, a canonical sync or archive, or operator activation. diff --git a/docs/reviews/claude-opencode-22-plan-29k.md b/docs/reviews/claude-opencode-22-plan-29k.md deleted file mode 100644 index 2bcc2e3..0000000 --- a/docs/reviews/claude-opencode-22-plan-29k.md +++ /dev/null @@ -1,41 +0,0 @@ -**Verdict: REVISE.** The plan needs one narrow correction plus an owner decision. Everything else is ready. - -## Standards findings -- No blocking issues. The plan stays planning-only. It maps to one implementation Bead (`tasks.md:3`), keeps actor, permission and Stop contracts unchanged, keeps Beads-owned behavior out of scope, and keeps publication and operator activation as separate gates (`design.md:47`, `tasks.md:19`). This matches `AGENTS.md`. -- Nit, not blocking: `design.md:5` points to `/opt/data/research/...`, which is outside the repo. AGENTS.md says committed docs own evidence, so cite the committed evidence location at acceptance. - -## Spec/Design findings - -**B1 (blocker): a model change after native compaction will reliably lose snapshots, but the plan describes this as an "opaque older window" case.** -- **Upstream evidence:** - - `ctx.session.context` → `store.context` → `SessionHistory.load(db, id, "latest")` (`store.ts:194`). - - With `"latest"`, `latestCompaction` stops at the newest completed compaction of any kind, including native (`history.ts:70`, `replayable` at `:49`). - - The runner reads history with `model.ref` instead (`llm.ts:137`). If a native window can't replay on the new model, it reads back from the previous compaction (`history.ts:220-223`). -- **Result:** after a native compaction on model A, a switch to model B sends the ordinary, durable, ID-bearing tagged user messages from before that compaction (`to-llm-message.ts:241-254`). `context()` does not return those records, so the planned lookup marks them "unavailable". These messages are plain retained transcript, not opaque windows. The plugin `SessionDomain` has no other history reader: it has `context` but not `messages` or `message.get` (`plugin/dist/promise/session.d.ts:186`). -- **Where the plan gets it wrong:** - - `work-continuity/spec.md:30` and `design.md:19` frame disclosure as limited to "opaque older windows". - - `workflow-access/spec.md:162` ("accessible durable snapshot") leaves "accessible" undefined. - - `tasks.md:13` asks qualification to cover "a model-change boundary" but gives no expected result. A predictable degradation could therefore be recorded as an adapter failure, or quietly passed. -- **Smallest correction:** - - State in `design.md:19` and `work-continuity/spec.md:30` that "accessible" means present in the native latest-boundary context. - - Name the case explicitly: snapshots from before a native compaction, replayed after a model change. - - Set the expected qualification outcome for that case to "disclosed unavailable". - - Have the owner accept that degradation (see decisions). No new store or reader is needed. - -## Material nonblocking notes -1. **What happens if the read fails is unspecified.** `load` decodes every row and fails the whole call on any `MessageDecodeError` (`history.ts:215-218`). Spec `:199-203` covers this in general. Add one line to `design.md:17`: if the context read rejects, treat all tagged messages in that request as unavailable (with the notice), and still deliver the request and the rest of the guidance. -2. **Order of steps.** `design.md:17` puts the location check before the lookup, but beta.5 currently expands before the location check (`src/host.ts:339-343`). Task 1.1 should mention this reordering so the regression test fixes it in place. -3. **The direct-tool reasoning is consistent with upstream.** When `execute` is wholly denied, eligible leaves become direct tools (`tool.ts:260-264`), and per-leaf wholly-disabled filtering still applies (`:257`). Spec `:33-36` and `:103-107` match this. The capability check in beta.5 (`host.ts:356`) is the right seam to change. -4. **ID matching depends on a published type.** `SessionRequest.messages: Array` (`session.d.ts:30`) has to expose `id` to the plugin. Task 1.1's SDK typecheck should assert this, not cast it. - -## Consequential owner decisions -- Accept the B1 degradation: after a native compaction followed by a model switch, pre-compaction workflow snapshots show an unavailable-guidance notice rather than being expanded. The alternative is to reopen the rejected side-store choice: `ctx.storage` exists, but `design.md:21` rejects durable side stores. I recommend accepting the degradation and documenting it. - -## Evidence -- **Inspected:** - - The six candidate files and `AGENTS.md`. - - Beta.5 `src/host.ts:226-410`. - - Upstream `history.ts` (load/boundary), `store.ts:194`, the native-session context path (`:446-448`), `host.ts:609`, `to-llm-message.ts:226-280`, `llm.ts` boundary usage and `tool.ts:251-320`. - - Plugin SDK `session.d.ts` (SessionDomain, SessionRequest), the schema user `metadata` field, and report greps. -- **Not inspected:** the canonical `openspec/specs/*`, the candidate-manifest hashes and the compaction-hook request construction. -- **Not executed:** any typecheck, test, OpenSpec validation, SDK fixture or installed-host run. That compaction hooks keep message IDs, and that the `id` field is visible in the published types, is inferred from source, not verified. diff --git a/docs/reviews/claude-opencode-22-plan-recheck-29k.md b/docs/reviews/claude-opencode-22-plan-recheck-29k.md deleted file mode 100644 index a6d95b8..0000000 --- a/docs/reviews/claude-opencode-22-plan-recheck-29k.md +++ /dev/null @@ -1,34 +0,0 @@ -**Verdict: READY** for owner review of the corrected plan. The original REVISE stands as history. READY only means the plan is coherent. It does not show runtime behavior, does not replace the still-unrun 2.2.6 native/model qualification, and is not owner acceptance or permission to implement, release or close `opencode-beads-o66`. - -## B1: resolved -- **"Accessible" is now defined.** `design.md` defines it as "present in native latest-compaction context". It names the exact trigger: native compaction on model A, then a switch to model B that can't replay A's window, which restores plain older user messages to the request. It links the pinned boundary code (`history.ts#L45-L84`). This matches what I checked earlier (`history.ts:49,70,220-223`; `llm.ts:137`). -- **The expected result is now set.** The new scenario at `workflow-access/spec.md:205-209` and `work-continuity/spec.md:30` both expect a visible "unavailable" disclosure for affected historical instructions and reports. Accessible snapshots still expand. Host replay content and Beads data are not rewritten. -- **Qualification can now judge it.** Task 2.2 records this case as a "verified limitation", not a pass or a failure. The stop condition in `design.md` excludes this documented outcome, so it no longer triggers a design revision. -- **The owner's decision is recorded.** The design states that the owner chose disclosure plus a follow-up over a separate snapshot store. - -## Standards findings -- No blockers. -- The machine-local evidence path is gone, and the design now links pinned upstream sources instead. -- The follow-up is one Bead, separate from this change and not blocking it: `deficiency-record.json` shows it blocked, unassigned, `blocks_release:false`, `implementation_authorized:false`, and linked by `discovered-from` to `9za`. Its closure requires a released supported API plus a demonstrated recovery, not just an issue closure or PR merge. That fits the AGENTS.md split between OpenSpec, docs and Beads. -- Nothing creates a duplicate GitHub issue, a side store or a polling service. - -## Spec/Design findings -No correction introduced a blocker. -- **Nonblocking wording nit:** `workflow-access/spec.md:222` ("Scenario: User evaluates the documented limitation", last line) says "the published beta's narrower host support". Beta.5 supports a *different* host line (2.1), not a narrower one. Suggested wording: "the published beta's 2.1 host support". -- **Earlier nonblocking notes, now folded in:** - - What happens when the history read fails: disclose unavailable, leave the content alone, keep the other guidance, don't retry. - - Moving the location check before the lookup. - - Checking message IDs through published types, without casts. - - Task 1.1 now owns these and tests them. - - The proposal now names the native current-context API correctly. -- **The ADDED requirement is reasonable.** "Documented snapshot-recovery deficiency" makes README disclosure a requirement in the spec. The design already says docs and specs get updated when the deficiency is resolved, so it won't harden into a permanent rule. -- **The controlled-provider fixture should work** for the model-switch case. The compaction hook result can supply `native.messages` (`session.d.ts:42-43`), so a native window for model A can be produced without a second run against a real provider. This is inferred from the types, not executed. - -## Remaining owner decisions -- Accepting the complete corrected package, including the documented deficiency as a known limitation of the 2.0 adaptation. Your direction already says you'll take this disclosure-and-follow-up approach; formal acceptance is still pending. -- No other new decisions. - -## Evidence -- **Inspected:** `correction.patch`, `deficiency-record.json`, and a heading/grep check of the current `workflow-access` spec. The working tree matches the patched heading structure, including the scenario at :205 and the ADDED requirement at :211-222. -- **Not re-inspected, by your scoping:** upstream sources beyond my earlier review, canonical specs, the hashes in `corrected-manifest.json`, and `review.md`. -- **Not executed by me:** OpenSpec validation, typecheck, tests, the SDK fixtures, and the installed-host/model/compaction qualification. The validation and hash checks you cite are your own runs. diff --git a/docs/reviews/claude-opencode-22-source-81x.md b/docs/reviews/claude-opencode-22-source-81x.md deleted file mode 100644 index 6ab7c8e..0000000 --- a/docs/reviews/claude-opencode-22-source-81x.md +++ /dev/null @@ -1,76 +0,0 @@ -# Source review: opencode-beads-5rj.1 - -**Candidate:** `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643`, compared with the accepted base `cd4630c7a4322a8a1439acb714274f6a89ff6c15`. I only read files; nothing was run. - -## Verdicts -- **SOURCE: READY** -- **Standards: READY** -- **Spec (tasks 1.1, 1.2, 2.1 source portion): READY** - -**No blockers found.** - -## What I checked against the contract - -**Metadata transport (1.1)** -- `src/host.ts:236` makes one `ctx.session.context({sessionID})` call per hook run. -- `src/workflows.ts:576-581` builds an ID map that exists only for that request. There is no cache and no per-message lookup. -- Matching uses `message.id` from the published `SessionContext["messages"]` type against the stored record's `id`, with no casts. -- The upstream conversion step keeps user-message IDs (`to-llm-message.ts:236,250,256,258`), which confirms the gap this change is built around. - -**Order of checks** -- In both hooks, the location check (`host.ts:396-406`, `456-466`) runs before the history read. -- After every await, the code checks for unload/cancel (`abort`) and that the request is still current (`host.ts:237-241`, `245-249`, `397-401`, `457-461`). -- `forgetSession` clears the in-flight read marker (`host.ts:170`). So a move, fork or delete during the read throws away a late result. The "late native snapshot" test covers this. - -**Precedence and repeat runs** -- `storedWorkflowInstructions` (`workflows.ts:551-561`) prefers a valid `ocBeadsWorkflow` and falls back to the legacy `ocBeadsSync`. Malformed or wrong-version records are ignored. -- The first-part equality check (`workflows.ts:600`) means running expansion twice adds nothing. -- Stored history is never changed. The request copy is replaced, not edited. - -**Unavailable notice** -- The notice tells the model not to invent missing guidance or replay an operation. It is added at most once per request (`host.ts:220`), and the warning log fires once per session (`workflowDiagnostic`). -- If the read fails, the user's text is left alone and the rest of the guidance still runs (`host.ts:250-251`), as `design.md:17` requires. -- There is no re-submission or retry, and nothing is reconstructed from current command definitions. This matches the owner-settled o66 outcome. - -**Hook scope** -- Only the context and compaction hooks expand snapshots. The title/generate tests confirm they don't. - -**Direct tools (1.2)** -- `DIRECT_BEADS_TOOLS` (`host.ts:48-51`) matches 2.2.6 tool naming (`runtime.ts:290-293`: `${namespace}_${name}`) and the 11 operations in `continuity.ts:55`. -- In 2.2.6, when execute is wholly denied, Code Mode tools are exposed directly (`tool.ts:262-264`). So `registered-direct-visible` describes something the host really does. -- Tool definitions, permissions (`permission: "shell"`), actor handling and Stop behavior are unchanged. -- The guidance text says a rejected operation must not be retried elsewhere, that Stop/Cancel must be honored, and that shell is only available if it is listed separately (`guidance.ts:90-93`). - -**Version range and docs** -- Version admission is `2.2.x` with patch ≥ 6, and the unsupported-version list includes `2.2.5`, `2.3.0` and `2.2.6-beta.1`. The package version is unchanged. -- The README separates the published beta.5 (`>=2.1.1 <2.2`) from the unreleased source and claims no host qualification. -- The README limitation covers the trigger, the impact, that Beads data is unaffected, upstream #57424 and the unresolved `opencode-beads-o66`. -- The outdated "operations disappear when execute is denied" wording is gone from `CODE_MODE.md`. I found no remaining copies of it. - -**Tests** -- Tests build real SDK 2.2.6 messages with `Message.make` and assert that `metadata` is absent. They also assert location-then-history order and exactly one read, and cover rejected/missing reads, a late result after a move, and input/files/delivery preservation. -- These checks would fail if the code still relied on request metadata. They exercise the code against the SDK types, not a real installed 2.2.6 host. - -## Optional advice (not required) -1. **Overlapping requests in one session** (`host.ts:238-240`, `398-401`): if a second request for the same session starts before the first one's read finishes, the first request shows the unavailable notice even though its snapshots were readable. It also skips the rest of its Beads guidance. I haven't shown this can happen, since the 2.2.6 runner seems to run a session's hooks one at a time. Worth watching in 2.2, not fixing now. -2. **Stale diagnostics label** (`host.ts:387`): `typedRegistration` still says `"code-mode-only"`, but 2.2.6 can expose the tools directly. The `leafAvailability` field is correct; the label could just say `"registered: beads namespace"`. -3. **Dead line** (`host.ts:419`): the marker was already deleted at `host.ts:415`. The two hooks also repeat the same location/read block, which could be shared. Cosmetic. -4. **Over-eager notice** (`workflows.ts:567`): `hasWorkflowInvocation` matches any user line starting with `/oc-beads:`, so an ordinary message quoting a command could trigger the notice. This errs toward disclosure, which is acceptable. -5. **Log key not cleared on session reset** (`host.ts:219`): the key format (`session=X`) doesn't match `forgetSession`'s `:X` suffix match, so the warning won't repeat after a move or fork. It's harmless and consistent with "once". - -## Inspected -- The frozen `source.patch` and `tracking.json` -- Current `src/host.ts`, `src/workflows.ts` (through the patch) and `src/guidance.ts` -- The `continuity.ts` tool names and permission option -- The spec, design and tasks files under `openspec/changes/adapt-opencode-2-2/` -- `AGENTS.md`, sampled for rules -- Upstream 2.2.6 `to-llm-message.ts`, `tool.ts` and `tool/runtime.ts` -- The installed `@opencode/ai` 2.2.6 `./effect` export - -## Not executed or not checked -- Typecheck, the 218 tests, the packed smoke test, OpenSpec validation and diff checks. These remain worker claims plus your own reruns. -- The frozen `.tgz`: I didn't check its contents or digest. -- The full plugin `session.context` declaration chain, beyond how the code uses it. -- Task 2.2/2.3: a real 2.2.6 host, model and compaction run, including whether `session.context` IDs match request IDs on an installed host, and the o66 model-switch disclosure. - -READY here doesn't close the 2.2 gate and doesn't authorize push, release or operator changes. diff --git a/docs/reviews/opencode-22-controlled-qualification-5rj2.md b/docs/reviews/opencode-22-controlled-qualification-5rj2.md deleted file mode 100644 index 6148869..0000000 --- a/docs/reviews/opencode-22-controlled-qualification-5rj2.md +++ /dev/null @@ -1,80 +0,0 @@ -# OpenCode 2.2.6 local qualification — BLOCKED/PARTIAL - -Executor: `codex:86c72145`; actual native Codex session UUID `01a1bd7e-5bd2-7720-88f3-870d909d432b`. The actor suffix is the parent-generated execution token, not a native session claim. Requested worker model/effort: Codex/Astra medium. This report does not independently attest the orchestration model banner. Native Codex performed qualification; it was not an OpenCode agent session. - -Work began 2026-11-08 23:29 UTC and completed within the 45-minute bound. Only `opencode-beads-5rj.2` was claimed/checkpointed, with the explicit actor and `--sandbox`; heartbeat used the supported command. It remains `in_progress` for parent review. Tasks 2.2/2.3 checkboxes, acceptance, closure, assignment and sync remain parent-owned. - -## Candidate and isolation - -- Branch `work/adapt-opencode-2-2-5rj1`; HEAD `f22177939b65ad95e6cf6b7cdb049c07447fd8aa`. -- Runtime source `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643`; source acceptance is `docs/reviews/opencode-22-source-acceptance-5rj1.md`. Evidence/tooling successors do not replace the runtime. -- Used the frozen archive `/opt/data/research/opencode-beads-2.2.6-impact/implementation-5rj1/snarkipus-opencode-beads-1.1.0-beta.5.tgz`, SHA256 `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`. Extracted the public package unchanged; all 31 installed files match the archive. No repack or source installation. The internal beta.5 version is not published beta.5 bytes. -- Actual executable `/usr/local/bin/opencode`, resolved to `/opt/hermes/image-toolchain/npm/node_modules/@opencode/cli/bin/opencode.exe`. CLI and owned server both report **2.2.6**; executable fingerprint is retained. SDK/client package is the existing installed 2.2.6 contract. -- Explicit isolated HOME/XDG config/cache/data/state and TMPDIR under `/opt/data/cache/scratch/oc-beads-22-5rj2`. Disposable committed Git project and embedded Beads 1.3.4 fixture at `tmp/project`; explicit `BEADS_DIR`, no tracker redirect or remote. `preflight-corrected.json` retains successful actual `bd context --json`, seed and prime before any provider request. Seed audit actor is `codex:86c72145`; fixture item `q22-r36` remained open/unassigned. -- Owned foreground/private server bound only to `127.0.0.1:54973`; controlled HTTP provider bound only to `127.0.0.1:44367`. No managed service, operator server, Zeus transport or global install was used. -- `harness/observer-plugin.ts` forwards and awaits the unmodified public plugin setup/cleanup; it records four lifecycle timestamps only. It does not replace dependencies, results or cancellation. - -The source suite (218 tests / 11,883 assertions), typecheck, exact packed smoke and strict 4/4 evidence were reused, not rerun. No per-command/argv matrix was added. - -## Controlled installed-host observations - -All provider frames are **CONTROLLED**, not genuine inference. Provider ID `controlled`, native package `@opencode/ai/providers/openai`; models `model-a` and `model-b`, native variant `default`, no reasoning effort configured. Twenty-eight actual outgoing HTTP requests were captured without headers; native tool calls/results and permission requests are retained. Fixture token counts are synthetic and support no usage, quality or cost claim. - -| Case | Outcome | Evidence | -| --- | --- | --- | -| Ordinary command admission and expansion | Passed: one compact persisted user invocation, one static snapshot in its first provider input, no serialized routing key | `ordinary-context.json`, `provider-001.json` | -| Diagnostics capture/replay | Passed transport: durable captured report reappears byte-identically in later primary input; no new diagnostics invocation on replay | `diagnostics-context.json`, frames 002–003; source once-capture evidence reused | -| Legacy/current snapshots | Passed: legacy v1 snapshot expands; new command uses current v1 metadata | `legacy-context.json`, frame 003 | -| Auxiliary generate exclusion | Passed: native session.generate request lacks action/diagnostic/legacy expansion | `generate-result.json`, frame 004 | -| Native title exclusion | Unrun; no independent title-provider frame was established | No title pass inferred from generate | -| Native code-mode catalog and operations | Passed: host search returned real signatures; composed get/note returned actual CLI outcomes | `catalog-context.json`, `composed-allowed-context.json`, frames 005–008 | -| Independent permissions | Passed: separate get/note asks, distinct permission IDs, exact CLI resources, source call correlation, `save: []`, once replies | `permissions.jsonl`, `native-events.jsonl` | -| Denied inner operation | Passed nonexecution: note rejected, independent read approved/completed; outer execute completed with inner error and host continued | `composed-denied-context.json`, frames 009–010; no whole-step-termination claim | -| Direct fallback | Passed: execute denied; real provider catalog exposes direct Beads leaves; actual beads_get succeeds under separate shell-equivalent permission | `direct-inventory-context.json`, `direct-get-context.json`, frames 011–013 | -| Scoped native child identity | Passed bounded observation: native child session with parentID executed direct note with a distinct derived actor; seed authorship and assignment preserved | `session-child.json`, `child-note-context.json`, frame 014; this is not a genuine delegated reasoning/handoff assessment | -| Native compaction and A replay | Passed corrected fixture: real host compaction hook/request, stored native replacement and provider replay | `corrected-native-compaction-context.json`, frames 022–023 | -| Native A → non-replayable B | **Verified limitation**: earlier plain command transcript restored; old snapshot IDs absent from native latest context; unavailable notice emitted, accessible current snapshots expanded | `corrected-native-switch-b-context.json`, frame 024 | -| Summary compaction/replay | Passed corrected fixture transport: stored summary and compact recent text, current snapshot expansion on replay | `corrected-summary-compaction-context.json`, frames 025–026; fixture summary is not semantic model evidence | -| Stop at permission wait | Passed selected nonexecution/no-restart behavior: actual pending ask, native interrupt, aborted tool/step, idle execution, no stopped note | `stop-*.json`, frame 027, final fixture readback | -| Permission request retirement after Stop | **Failed stronger observation**: the stopped request remained listed through session deletion | `stop-pending-after.json`, `after-session-removal-permissions.json`; no repair, no claim that the inventory was empty | -| Actual plugin disposal | Passed lifecycle observation: watched-config removal caused original cleanup entry/return, then native command registry lacked package commands | `lifecycle.jsonl`, `unloaded-commands.json`, `unloaded-plugins.json` | -| Pending diagnostics callback during unload | **Unrun/inconclusive timing**: command returned before cleanup; no pending-callback cancellation pass | `case-timeline.jsonl`; command return 1794181147283, cleanup start 1794181147474, completion 1794181147478 | -| Genuine model workflow | **Blocked/unrun**: no authorized account-managed path supporting the required isolated state | `genuine-readiness.json`; zero isolated accounts, zero genuine requests | - -Native sessions: - -- Main: `ses_e427c565bffeO1o7GcXCdTA5Zk`, actor `opencode:qualifier:ff5a4b12d522`. -- Direct/Stop: `ses_e427adc94ffeKTHBN4K0GHT1zX`, actor `opencode:qualifier:433d578cb780`. -- Child and unload IDs, exact native agents/models and derived child actor are retained in `session-child.json`, `child-note-context.json`, `session-unload.json` and `permissions.jsonl`. - -The native host executors legitimately use their derived OpenCode session actors on fixture writes. These do not replace the qualification worker's `codex:86c72145` coordination actor. Independent CLI readback shows exactly `CONTROLLED_NOTE_5RJ2\nCHILD_NOTE_5RJ2`, unchanged seed author, no assignee, and neither denied nor stopped note. - -The B-switch result is the accepted unresolved deficiency `opencode-beads-o66` / upstream #57424, **not recovery of old snapshots, a fix, or a new downstream repair blocker**. The retained native window is used only by A; B receives earlier ordinary user transcript plus explicit unavailable disclosure. No Beads data or stored history was rewritten to manufacture restoration. - -## Preserved setup failures and limits - -1. Initial `bd context` rejected the fixture outside TMPDIR because installed Beads blocks `/opt` except supported temporary roots. Moving the disposable project beneath the already configured isolated TMPDIR corrected the setup; no CLI/guard patch. Original preflight and narrow probes remain. The pinned reference inspected was `https://raw.githubusercontent.com/gastownhall/beads/7ef2fd05e/internal/beads/context.go`; a retained copy is in `harness/`. -2. Initial plugin config pointed to a file; this host expects a package directory. Before inference, the observer became a directory with a package `./server` export. Native registry then settled to 30 package commands plus 3 built-ins. A first snapshot before settlement showed only built-ins; it was not a dispatch pass. Bun was unavailable on PATH, so the existing generated Promise client ran with installed Node 26.12.1; no installation occurred. -3. Original provider fixture incorrectly answered native compaction with text and summary compaction without mandatory headings. Frames 016, 019–020 and native failed compaction records remain. The host's automatic summary nudge is retained. Only the controlled fixture response protocol was corrected, plus explicit `keep.tokens=0` to select the required missing-old-snapshot case. No product prompt/source was tuned. Original and corrected provider scripts remain; only the owned fixture provider process was replaced, not the OpenCode server. Later corrected frames are separately numbered. -4. Initial offline analyzer assumed one global show instruction copy despite four separate durable show invocations. The corrected assertion derives multiplicity from stored user snapshots. A second assertion expected permission retirement after Stop and failed against actual retained inventory. That stronger failed observation remains explicit; selected Stop nonexecution is verified independently. No host rerun or guarantee silently waived. -5. Session cleanup initially removed the parent before its child, so the host's cascading removal produced SessionNotFound for the child. The remaining cleanup recorded that absence and removed the unload session. The stopped permission entry remained in the host registry until owned process/state teardown. - -No authorized genuine route was available in isolated state. No operator credentials/database were copied, selected, imported, translated, refreshed or authenticated. No alternative public/free/paid account or provider was chosen. Inspecting the fresh isolated credential list found zero entries. Existing Codex inference is not OpenCode model qualification. The smallest missing prerequisite is an explicitly authorized account-managed genuine OpenCode route that supports these isolated-state constraints without changing credential custody. - -## Cleanup and preservation - -`cleanup.json` records terminated owned host PID 45210, controlled provider PID 46715, and retired provider PID 45209, all absent. Both loopback listeners refuse connections. `owned-process-census.json` finds no process with a cwd beneath the scratch root. Only owned process groups were signalled. Private native logs, transient server password and isolated OpenCode data/state/cache were removed. No real provider credential entered the fixture. The fixture/public dummy provider key was removed from final config; retained source contains only its clearly labelled nonsecret constant. - -All 197 protected repository paths match the supplied manifest. Captured operator executable and known JSON/JSONC config fingerprints match; no operator credential/database content was inspected or fingerprinted. This is a scoped fingerprint claim, not a census of every possible operator file. All 31 extracted package files match the exact archive. No existing tracked file changed; only the optional new concise repository qualification report is added. No commit, push, tag, release, publication, tracker sync, canonical spec sync/archive or upstream posting occurred. - -## Parent verification and remaining gates - -Run, offline and without restarting a host: - -```sh -python3 /opt/data/research/opencode-beads-2.2.6-impact/qualification-5rj2/analyze.py -``` - -The analyzer checks **33 assertions against raw evidence**, including preservation of the failed permission-retirement observation and the unqualified pending-unload timing. It prints **BLOCKED/PARTIAL** even when assertions succeed. `analysis.json`, `case-index.json`, `installed-manifest.json`, provider frames, native contexts/events, permission records and `harness/` support review. `result.md` is reserved for the parent CLI's final summary and is not this report. - -Task 2.2 is not complete: genuine workflow is blocked; pending diagnostics unload and native title exclusion are unrun. Parent should review the useful controlled mechanics and the retained host permission-inventory observation, then arrange the smallest authorized genuine route and explicitly scope any remaining live check. Task 2.3 final acceptance, marker reconciliation and issue closure remain parent-owned. Stable 2.0 preparation/publication or operator activation is not recommended as accepted from this partial gate; preserve the frozen source and existing pins pending that review. diff --git a/docs/reviews/opencode-22-genuine-workflow-5rj2.md b/docs/reviews/opencode-22-genuine-workflow-5rj2.md deleted file mode 100644 index d333915..0000000 --- a/docs/reviews/opencode-22-genuine-workflow-5rj2.md +++ /dev/null @@ -1,95 +0,0 @@ -# Genuine workflow — GENUINE_WORKFLOW_READY - -The single authorized genuine workflow completed on actual OpenCode **2.2.6**, native **OpenAI subscription / gpt-6.1-sol / high**, using the exact frozen public package. Independent CLI readback confirms exactly one requested note append, preserved prior notes and target fields, and an unchanged sentinel. The completed nonempty model report agrees with the acknowledged operation. Cleanup and preservation checks pass. - -This is one bounded observation, not broad model reliability or parent acceptance of tasks 2.2/2.3. Parent owns marker reconciliation, final acceptance, closure and sync. `opencode-beads-5rj.2` remains in progress under `codex:86c72145`. No source publication, release or operator activation is authorized by this result. - -## Identity and custody - -- Qualification worker: same `codex:86c72145`, native Codex session `01a1bd7e-5bd2-7720-88f3-870d909d432b`, requested Astra/medium. Its actor suffix is the parent execution token, separate from the native session UUID. -- Native OpenCode sample session: `ses_e42640b98ffeC3CF3XhLJXcA5I`, agent `workflow_eval`, actual derived fixture executor `opencode:workflow_eval:b266ee9b97e7`. -- Runtime source `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643`; HEAD `f22177939b65ad95e6cf6b7cdb049c07447fd8aa`. -- Frozen archive `/opt/data/research/opencode-beads-2.2.6-impact/implementation-5rj1/snarkipus-opencode-beads-1.1.0-beta.5.tgz`, SHA256 `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`. All 31 installed files match. Internal beta.5 is not the published beta.5 artifact. -- Native model discovery reported enabled `openai/gpt-6.1-sol`, including variant `high`, package `@opencode/ai/providers/openai/responses`. Every observed request context and native assistant record uses that exact provider/model/variant. -- The parent's frozen `completion-pass/native-auth-ready.json` establishes fresh user-completed native `chatgpt-headless` OAuth in this own profile. No credential value was read, selected, hashed, exported, copied, translated or manually refreshed by this worker. The nullable optional method column was not changed. - -The workflow used `/opt/data/cache/scratch/oc-beads-22-genuine` with the exact authorized HOME/XDG/TMPDIR values and `OPENCODE_DB=.../data/qualification.db`. That DB was neither moved nor copied. An owned foreground server (PID 50153) listened on loopback port 52403; no concurrent server or operator service was used. - -The fresh committed Git/embedded Beads fixture is `.../tmp/workflow`, beneath declared TMPDIR, with explicit fixture BEADS_DIR. Actual `bd context --json` and prime passed before inference. Seed writes used `codex:86c72145`. Target `g22-1f2` began with `ORIGINAL_TARGET_NOTE`; sentinel `g22-mv0` began with `ORIGINAL_SENTINEL_NOTE`; neither was assigned. Exact before records are retained separately. - -## The one native workflow - -The existing comments purpose permits appending a requested comment/checkpoint without replacing prior notes. Before inference, the selected native command and exact user text were fixed as: - -```text -/oc-beads:comments Append exactly GENUINE_NOTE_5RJ2_ONCE to the notes/checkpoint of g22-1f2. Preserve its existing notes. Do not claim, close, sync, or change other fields or issues. Report the actual result and stop. -``` - -This was one ordinary public `session.command` invocation, not direct invocation of plugin hooks. The model was not given literal tool code or signatures. The session had an explicit title and the title agent was disabled; no auxiliary title inference or separate smoke request occurred. Eight steps were available; the workflow completed in five. - -Observed model choices: - -1. Loaded the installed `oc-beads` skill. -2. Used native code-mode namespace search to discover real Beads signatures. -3. Called `beads.get` on `g22-1f2`. -4. Called `beads.note` with exactly `GENUINE_NOTE_5RJ2_ONCE`. -5. Returned a completed, nonempty final report and stopped. - -The three native permission asks were independently handled with **once**, without saved grants: packaged skill access, exact target read, and exact target append. The get and note each had their own shell-equivalent permission ID and `save: []`; source call IDs match their actual native tool records. The note permission resource was: - -```text -bd update g22-1f2 --append-notes GENUINE_NOTE_5RJ2_ONCE --json --actor opencode:workflow_eval:b266ee9b97e7 --sandbox -``` - -The fixture permission evaluator parses shell tokens and allows only the exact target append with the actual actor, fixture-owned reads, packaged skill access and exact `git status --short`. It rejects other-target writes, claims, shell chaining and auth-DB reads. No broad auto-approval was enabled. No unrelated operation was requested or approved. The model did not request Git completion work in this sample. - -The native append result is **acknowledged**, with target, actor and updated issue. Independent post-run `bd --readonly show` verifies: - -```text -ORIGINAL_TARGET_NOTE -GENUINE_NOTE_5RJ2_ONCE -``` - -The new note occurs exactly once. All target fields except notes, `updated_at` and the expected record revision are identical to before, including audit author, absence of assignee/owner, status and priority. The sentinel's entire parsed record is identical. No claim, close, sync or additional issue write occurred. - -Actual final model text: - -> Appended exactly `GENUINE_NOTE_5RJ2_ONCE` to `g22-1f2`, preserving `ORIGINAL_TARGET_NOTE`. The append was acknowledged; no claim, close, or sync was performed. - -The native execution succeeded without a retry or failed-step event. The first valid outcome was retained; no prompt retuning, second attempt, model substitution, controlled response or source fix occurred. - -## Evidence boundaries - -`context.json` contains one compact native user message with its durable v1 instruction snapshot. The observation-only plugin records five actual primary request contexts after public package expansion; each contains that exact snapshot once and the actual model/agent/tool catalog. It does not modify requests or results, inspect headers/credential options, replace the provider, intercept TLS or use a relay. The public package itself is configured directly from the extracted archive directory, not through checkout source or replacement dependencies. - -These are pre-serializer context observations, **not genuine wire-body captures**. Already accepted controlled-host serializer/transport evidence is reused for that boundary. Native stored assistant records carry five distinct real provider response IDs, exact model/variant, tool results and usage. This genuine pass assesses the actual model-selected workflow and durable outcome; it does not repeat earlier title, compaction, Stop or disposal campaigns. - -Native usage fields total 19,211 input, 58,368 cache-read and 177 output tokens, with zero recorded reasoning/cache-write tokens. These are the host's reported fields, not independent billing measurements; no cost or savings inference is made. The five primary request/response steps are not five separately prompted samples. - -Evidence index: - -| Evidence | Purpose | -| --- | --- | -| `identity.json`, `model-readiness.json`, `server.json`, `session-*.json`, `executor.json` | Exact archive/host/model/session/actor identities | -| `environment.json`, `preflight.json`, `fixture-ids.json`, `*-before.json` | Isolated context and independent seeded baselines | -| `commands.json`, `plugins.json`, `admission.json` | Native public package activation and one command | -| `request-contexts.jsonl`, `context.json`, `native-events.jsonl` | Actual expanded contexts, genuine native messages/results and completion | -| `permissions.jsonl`, `permission.py` | Exact requests, source correlation and scoped decisions | -| `*-after.json`, `readback-receipts.json` | Independent durable outcomes | -| `cleanup.json`, `private-path-modes-*.json`, `fingerprints-*.json`, `installed-manifest.json` | Cleanup, retained auth custody and preservation | - -## Cleanup and preservation - -Owned host PID 50153 is absent; loopback port 52403 refuses connections; no process remains with a cwd under the fixture. Final execution and permission inventories are empty, with no saved grants. The transient server password and private startup logs were deleted. **The native authenticated DB and its session history remain in the authorized profile for the parent**; its contents were not read, hashed, exported, copied or deleted. Recorded private path modes are unchanged. - -All **196 earlier evidence files**, **197 protected repository files**, the existing untracked repository qualification summary, captured executable fingerprints and all **31 installed archive files** match. No repository file was edited. Earlier partial/completion findings remain immutable. No source gates or previous host campaigns were rerun; no siblings, sync, markers, close/reassign, commits/push, releases, upstream posting or operator changes. - -## Parent offline verification - -```sh -python3 /opt/data/research/opencode-beads-2.2.6-impact/qualification-5rj2/genuine-pass/analyze.py -``` - -The analyzer checks 29 assertions against raw native evidence, exact readbacks, identity, actual permission-evaluator boundaries, cleanup and preservation. It performs no inference, host startup or auth access. `analysis.json` preserves its result. `case-index.json` records the selected workflow outcome. `genuine-report.md` is this detailed handoff; `result.md` remains reserved for the CLI-owned final summary. - -**GENUINE_WORKFLOW_READY**, pending parent review and full task 2.2/2.3 acceptance. The accepted unresolved `o66` limitation and earlier host observations are neither fixed nor superseded by this append-only sample. diff --git a/docs/reviews/opencode-22-mechanics-completion-5rj2.md b/docs/reviews/opencode-22-mechanics-completion-5rj2.md deleted file mode 100644 index 9d9e46b..0000000 --- a/docs/reviews/opencode-22-mechanics-completion-5rj2.md +++ /dev/null @@ -1,70 +0,0 @@ -# Two-mechanics completion — TWO_MECHANICS_READY - -This bounded continuation supplies the two missing controlled-host measurements: **native title-request snapshot exclusion** and **cancellation of an actually pending diagnostics invocation at product plugin disposal**. Both passed. This is not full task 2.2/2.3 acceptance: the genuine-model workflow remains separately pending with the parent. No genuine inference or account/authentication work occurred. - -Executor `codex:86c72145`, unchanged native Codex session UUID `01a1bd7e-5bd2-7720-88f3-870d909d432b`; the actor suffix is the parent execution token. Requested model/effort remains Astra/medium. Same actor claimed normally, read back `in_progress`, and used explicit `--sandbox` for checkpoints/heartbeat. Parent retains assignment, synchronization, markers, acceptance and closure. Work started 2026-11-08 23:50:36 UTC and finished inside the 20-minute bound. - -## Exact inputs and isolation - -HEAD `f22177939b65ad95e6cf6b7cdb049c07447fd8aa`; runtime `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643`. The unchanged frozen archive is `/opt/data/research/opencode-beads-2.2.6-impact/implementation-5rj1/snarkipus-opencode-beads-1.1.0-beta.5.tgz`, SHA256 `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836`. All 31 extracted files match it. Internal beta.5 does not identify the published beta.5 bytes. No source installation, repack, installs or production changes. - -Actual installed CLI and owned foreground server report **OpenCode 2.2.6**. Used the existing Node 26 Promise client and public package `./server` directory export. A lifecycle-only observer forwards and awaits the archive's original setup and cleanup without changing context, dependencies, results, hooks or abort behavior. - -New scratch root only: `/opt/data/cache/scratch/oc-beads-22-5rj2-completion`. Explicit isolated HOME/XDG config/cache/data/state/TMPDIR; disposable committed Git and embedded Beads fixture at `.../tmp/project`, beneath declared `TMPDIR` (`.../tmp`). `BEADS_DIR` is explicitly `.../tmp/project/.beads`; actual `bd context --json` passed before inference. Fixture init used `codex:86c72145`; no issue writes were needed. `isolated-environment.json` and `preflight.json` record the exact environment and CLI outcomes. - -Owned host PID 48839 listened on `127.0.0.1:45205`; owned controlled provider PID 48838 on `127.0.0.1:44577`. Provider `controlled`, model `completion`, native package `@opencode/ai/providers/openai`, variant default, no reasoning effort configured. The native title agent was explicitly routed to this same controlled model, avoiding any implicit alternative provider selection. **Exactly two outgoing provider frames**, both CONTROLLED; fixture token values are synthetic and establish no cost, usage or model-quality claim. - -## Native title exclusion — passed - -Untitled native root session `ses_e426bc4d1ffenWOvPhD2ZPvMLg` received one actual `/oc-beads:show` command, with exact free text `Explain only the workflow; do not read or modify issues. TITLE_CASE_5RJ2`. No plugin hook was invoked directly. - -- `title-context.json` contains compact native user text and a durable current v1 workflow snapshot. -- `provider-001.json` is the actual native title request: stock “Here is the first message…” / “Reply with only the title” framing contains the compact command, zero workflow instruction expansions, no routing metadata and no tools. -- `provider-002.json` is the normal primary request: the identical durable snapshot appears exactly once. This provides a positive expansion comparison in the same native session. -- `provider-001-response.json` records the controlled title response. `native-events.jsonl` records native `session.renamed`, and `title-session-after.json` confirms `CONTROLLED completion title`. - -This closes the native title mechanics gap independently of the earlier accepted generate exclusion. It is a representative ordinary-command snapshot observation, not a semantic title-quality claim or a new all-command campaign. - -## Actually pending diagnostics at disposal — passed - -Native session `ses_e426bc367ffenwuNM2xvM112DT` received an actual `/oc-beads:diagnostics` invocation. A fixture-local PATH shim invokes the real installed `/usr/local/bin/bd`, captures its exact stdout/stderr/exit, and normally forwards them unchanged. For this one diagnostic `context --json`, it held output **after the real subprocess completed**. The shim has no signal handlers, abort mechanism, substitute result or suppression logic. It would forward the original bytes when released if still alive. - -The observed sequence (epoch milliseconds): - -| Observation | Time | -| --- | ---: | -| Native diagnostics command started | 1794181971099 | -| Real `bd context --json` child 48984 completed, exit 0 | 1794181971231.655 | -| Shim 48982 held completed real output | 1794181971231.7756 | -| Callback confirmed pending; shim live, real child absent | 1794181971251 | -| Watched config removed the plugin | 1794181971251 | -| Original product cleanup entered | 1794181971516 | -| Original product cleanup returned | 1794181971520 | -| Native command returned `CommandExecutionError: Beads workflow unloaded` | 1794181971522 | -| Shim confirmed absent, then harness released hold | 1794181971552 | - -`bd-subprocess.jsonl` preserves the real successful context JSON and its SHA256. The diagnostic's result was pending across actual cleanup. The shim disappeared before release, with neither output-forwarded nor output-released event; the product owns cancellation. This occurred roughly 290 ms after holding output, well below the unmodified 10-second subprocess timeout. No harness signal was sent to the shim. Later cleanup signalled only the owned host/provider groups, after this observation was complete. - -`disposal-context.json` and `disposal-inbox.json` are empty; no user prompt was admitted and no diagnostics provider frame followed. `commands-after.json` confirms package commands were removed from the native registry. `lifecycle.jsonl`, `timeline.jsonl`, `held-process.json` and `native-events.jsonl` retain the correlation. This is actual watched-config plugin-scope disposal, not location reload, a registry-only inference, Stop, or custom cancellation. - -The previous sample in the frozen partial report still remains timing-inconclusive; it has not been relabelled or edited. - -## Cleanup and preservation - -`cleanup.json` confirms all 12 recorded owned host/provider/shim/real-child PIDs absent, both listeners refusing connections, and no process with a cwd under the new scratch root. Owned sessions were removed; final active execution and permission inventories were empty. Private startup logs, the transient server password and isolated OpenCode data/state/cache were removed. No operator credential was inspected, selected, copied, imported, translated, refreshed or authenticated. No genuine call occurred. The fixture-only dummy API key is a nonsecret constant; it was removed from final scratch config. - -All **146 prior durable evidence files** match `prior-evidence-manifest.json`. All **197 protected repository files** match the parent manifest. Captured installed executable/CLI/config fingerprints and the existing repository qualification summary match before/after. All 31 installed archive files match. Old scratch fixtures and raw evidence were not written. No repository file was edited in this continuation. Original compaction failures, stale Stop permission observation and incomplete unload remain preserved historical evidence. - -No full source gates or earlier passing campaign were rerun; no source fixes, mitigation, upstream changes, expanded matrix, tracker sync, sibling work, markers, closure/reassignment, commits/push, releases or operator runtime changes. - -## Offline parent verification - -Run without a host, provider or credentials: - -```sh -python3 /opt/data/research/opencode-beads-2.2.6-impact/qualification-5rj2/completion-pass/analyze.py -``` - -The analyzer checks **22 assertions** against retained raw provider/native/subprocess/timing evidence, archive identity, installed file equality, cleanup and preservation. `analysis.json` retains its output. `harness/` contains the exact scripts and transparent observer/shim; `case-index.json` labels these two passed mechanics and the separately pending genuine gate. No `passed:true`-only surrogate is used. The detailed report is this file; `result.md` is reserved for the CLI final summary. - -**Handoff: TWO_MECHANICS_READY.** Leave `opencode-beads-5rj.2` in progress. Parent should review these two observations and integrate accepted status separately; the genuine workflow and full qualification/owner acceptance are not established by this pass. diff --git a/docs/reviews/opencode-22-source-acceptance-5rj1.md b/docs/reviews/opencode-22-source-acceptance-5rj1.md deleted file mode 100644 index 8691e79..0000000 --- a/docs/reviews/opencode-22-source-acceptance-5rj1.md +++ /dev/null @@ -1,50 +0,0 @@ -# Source acceptance — OpenCode 2.2 adaptation - -## Current status - -Parent accepts **source tasks 1.1, 1.2 and 2.1 only** for `opencode-beads-5rj.1`. Runtime source is frozen at `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643`, against accepted planning/mapping base `cd4630c7a4322a8a1439acb714274f6a89ff6c15`. Tasks 2.2 and 2.3, installed-host qualification and final owner acceptance remain unexecuted and separately gated under `opencode-beads-5rj.2`. The epic and active specification change are not complete. - -Codex execution: `codex:01a1bce9`, session `01a1bce9-a85c-7492-bf4a-8f462c056a12`, observed `gpt-6-luna/max`. The worker completed normally and handed off SOURCE_READY; this document supersedes its parent-review-pending status without rewriting the original handoff. - -## Independent review - -Claude source review record `opencode-beads-81x`, session `8173b43a-85d9-4d0c-b5a3-08e91dbf69df`, observed `claude-opus-5-5`, requested medium effort. Read/Grep/Glob only; final result completed without error or permission denials. The complete tracked candidate hash manifest was unchanged across review. - -- **Standards: READY, no blocking findings.** -- **Spec, source tasks 1.1/1.2/2.1: READY, no blocking findings.** -- Original report preserved verbatim in [claude-opencode-22-source-81x.md](claude-opencode-22-source-81x.md). -- Some workflow line references in that report use source-patch positions rather than actual source lines. Parent inspected the implementation directly: snapshot validation and current/legacy precedence are at `src/workflows.ts:93–103`, and request-local ID matching/expansion at `114–139`. This citation correction does not change the report's substantive findings. - -The review's optional overlapping-request observation is not an established host defect. Its registration-label, redundant-line/extraction, conservative notice recognition and log-key suggestions remain nonblocking; no additional mitigation or refactor was commissioned. `code-mode-only` still describes the native registration option, not a claim that 2.2 cannot expose direct leaves. Per-request leaf availability describes the actual request surface. - -## Execution and preservation evidence - -Parent independently reran: - -- Full suite: **218 pass, 0 fail, 11,883 assertions** across 12 files. -- Exact frozen-archive package smoke: passed; packed public V2 plugin loaded. -- Strict global OpenSpec validation: **4/4 passed**, including the active change. -- Candidate diff whitespace check: passed. - -Typecheck passed in the Codex execution log (`$ tsc --noEmit`, successful command result). This is inspected worker execution evidence, not a separately executed parent typecheck; the parent's gateway compiler scan-size limit was not bypassed. Installed SDK was independently verified as **2.2.6**. - -The worker's retained RED→GREEN receipt isolates the transport failure after the required SDK harness migration and old admission refusal: location alone was observed before the repair; location then one native context read restores snapshots by retained user ID after it. Tests now use SDK metadata-free projected messages and paired durable native records, rather than injecting metadata directly into model messages. These are deterministic source seams, not an installed-host qualification claim. - -Parent compared command callback/payload construction and the workflow purpose/resource inventory byte-for-byte with the accepted base. Continuity operations/CLI invocation, agent definitions, context/cache module, repository guidance and shared Beads skill are unchanged. The accepted deltas are confined to SDK/admission, workflow transport, request capabilities, fixtures and targeted guidance/documentation. No operator configuration/authentication/database changes or upstream patches were made. - -## Frozen artifact handoff - -- File: `snarkipus-opencode-beads-1.1.0-beta.5.tgz` -- SHA-256: `072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836` -- Runtime source: `ccc9851bce42ec3f5a5b348cfa4cc40e1d93a643` -- Parent verified all **31 packed files** are byte-identical to the corresponding committed source files, with exact expected membership. -- Evidence root: `/opt/data/research/opencode-beads-2.2.6-impact/implementation-5rj1/`; worker `implementation-report.md`, `run.log`, parent `parent-tests.log`, `parent-package.log`, and `claude-source-review/` frozen packet/result. - -The internal version remains `1.1.0-beta.5`; this unreleased archive is **not** the published beta.5 artifact. Identify the candidate by source commit and digest. Published beta.5 retains its old `<2.2` admission. The same frozen archive, not a repackaged successor, is the input to task 2.2. - -## Remaining boundaries - -- Native context/real provider, compaction/model-switch, direct/composed/denied native operations, worker identity and Stop/unload qualification remain unrun under 2.2; final owner acceptance is 2.3. -- The native-compaction/model-switch snapshot-access deficiency `opencode-beads-o66` remains unresolved, upstream-blocked and owner-accepted as nonblocking. README and the active spec disclose unavailable guidance, not restored snapshots or a fixed deficiency. -- Source monitoring remains separate under `opencode-beads-rou`. -- The local evidence/task-marker successor changes no packed file and does not replace the artifact. No source push/merge, registry publication, version promotion, Zeus change, operator activation, canonical-spec synchronization or archival is authorized or implied by this source acceptance. diff --git a/docs/reviews/opus-code-mode-architecture-wgv.md b/docs/reviews/opus-code-mode-architecture-wgv.md deleted file mode 100644 index cad8eab..0000000 --- a/docs/reviews/opus-code-mode-architecture-wgv.md +++ /dev/null @@ -1,268 +0,0 @@ -# Independent broader code-mode architecture assessment - -Review `opencode-beads-ecj`; investigation `opencode-beads-wgv`. Actual reviewer `claude-opus-5-5`, requested medium effort; resumed session `ef963df0-acdb-4479-af76-29a067b3975f`. This supersedes the six-tool architectural recommendation and narrows the prior READY to its valid output-schema/namespace mechanics; original evidence/verdict is preserved. - -Parent verified completed/is_error=false, actual modelUsage, no permission denials and all 58 frozen hashes. Baseline `072429f1a7723ade23e756a921924d9d0acacf31`; host `ba546ec1598a70db2570e9c6258028d955ba8f58`. Frozen packet/manifest and full result under `/opt/data/cache/scratch/opencode-codemode-opus-broader/`. No product implementation or live/model qualification was performed or authorized. - -## Opus assessment (verbatim) - -**Recommendation: yes, substantial reshaping is warranted.** In pinned OpenCode 2.1.1, native `shell` is not callable from code mode. Inside a code-mode program, Beads can only be reached through tools this plugin registers. So the current five continuity tools plus one query (Sol's "six-tool" proposal) would leave claim, close, create and status changes outside composition entirely. That is a legacy seam, not a coherent code-mode product. - -The target I recommend is one `beads` code-mode namespace of about 11 typed operations covering the daily work loop (reads and lifecycle writes), not a wrapper for every CLI verb. It comes with capability-aware context, a single executor-actor source, and the 30 human commands kept as entry points. - -**My earlier narrow READY missed this.** It accepted the claims at `code-mode-product-investigation.md:89` and `:195` that code can call `tools.shell`. That READY should be read as covering the output-schema and namespace mechanics only. - -## 1. Source-backed facts that change the design - -| # | Fact | Evidence | Consequence | -|---|---|---|---| -| F1 | Native `shell` is registered `options: { codemode: false }`, so it is direct-only. | `parity-sources/baseline211/source/packages/core/src/tool/plugin/shell.ts:195` (tag v2.1.1 → `ba546ec`, `baseline211/tag.json`). The other three cached copies agree. | Code mode can't run `bd`, tests or git. Sol `:89` ("five tools plus native shell are functionally sufficient… code can check completion and parse JSON") and `:195` (`tools.shell` as "the verified shell signature") are wrong for code mode. Any Beads operation without a plugin tool can't be composed. | -| F2 | Snapshot split: `codemode !== false` tools appear only inside `execute`. Direct definitions are just the `codemode:false` tools plus `execute`. If `execute` is wholly denied, code-mode tools vanish completely. | `core/src/tool.ts:236-262` | The current tools have no direct path. Sol `:29` ("direct tool consumers receive readable content") and parity doc `:126` ("direct and code-mode inventory") describe a path that doesn't exist under default registration. An agent that denies `execute` loses every typed Beads operation and needs the shell fallback. | -| F3 | Effective ID is `namespace_name`; the catalog path is `namespace.name`; `pinned` is supported; namespace descriptions stay visible in the catalog. | `tool/runtime.ts:278-281`, `codemode/tool.ts:191-208, 321-322` | A namespace with any number of operations keeps `beads_*` IDs, so the after-hook exclusion at `host.ts:349` still works. Catalog cost is the namespace summary plus selected signatures; everything else is reached through search. | -| F4 | The code-mode runtime has no timers, imports or filesystem. Pending calls are interrupted when execution ends. Concurrency comes from `Promise.allSettled`. The outer result is the returned value plus logs; `toolCalls` metadata keeps inner inputs. | `codemode/tool.ts:71-78, 95-150, 333-345` | Code mode is the place for state reads, joins and ordered Beads writes. Repository validation still runs in direct shell turns. Write text persists in trace metadata. | -| F5 | Every typed call runs `session.get` twice and the store guard twice (`bd version`, and possibly `bd context --json`) before the operation itself. | `continuity.ts:188-200`, `guard.ts:39,106` | Hydrating N issues one call at a time costs about 3–5 process spawns per issue. Reads should be batch-shaped: one guard check and one permission assertion per call. | -| F6 | Any typed write runs `invalidateAll()` and sets a "re-read the affected task" recovery cue (`host.ts:279, 288`). Any non-Beads tool error invalidates prime and injects a "A tool failed…" cue (`host.ts:350-355`). | `host.ts` | In code-mode-heavy work, every checkpoint or claim triggers a guard and prime re-run for every session at that location. The cue also tells the model to re-read its own just-acknowledged write. Every failing test command injects a generic cue. That is repeated reasoning and process work with no information gained. | -| F7 | Typed writes use a derived `opencode::` actor (`continuity.ts:34-41`). Guidance and the skill tell the model to use "the actual executor actor… if unavailable, establish it" for shell writes (`guidance.ts:28`, `SKILL.md:45-48`). The model is never told the derived value. | as cited | One executor ends up with two identities: a typed claim as `opencode:build:…`, then shell heartbeats or notes under a model-chosen actor. That breaks the "keep the actor through updates" policy. | -| F8 | Always-on text: full `bd prime --full` (which can include memories) plus 7,758 B of guidance for primary agents and 4,421 B for task agents, on every eligible request. The task agent gets the executor section twice (prompt `guidance.ts:66` plus injected `:84`). The host guidance says "There is no native `bd`… Run `bd` through the `shell` tool" (`:36`). Commands say "no assumed MCP tool or typed tool" (`workflows.ts:99`). | as cited; byte counts from `bridge-results.json` | Once typed tools are active, the always-on guidance contradicts the real capability. The duplication costs bytes on every request. The context hook can see the request's tool set (`event.tools`, as shell's own hook does at `shell.ts:285`), so the capability statement can be made truthful per request. | -| F9 | The five tools have no output schema, so the executor fails, and the catalog shows `Promise`. | shape-review reproduction; `bridge-results.json` | Our defect, still unfixed and withheld. It is a prerequisite for everything below. | - -## 2. Alternatives considered (choosing one) - -| Shape | Verdict | -|---|---| -| **A. Five continuity tools + one query (Sol)** | Rejected as the target. Given F1, claim, close, create and status changes can't be composed. "Start authorized work → read back → checkpoint → close or hand off" has to be split across model turns, which defeats the point of code mode. | -| **B. One wrapper per CLI verb (~29)** | Rejected. Catalog and maintenance cost scale with verbs that are rare, administrative or human-directed. Code mode adds nothing to `init`, `rename-prefix` or `import`. | -| **C. Generic `beads.cli({args})` passthrough** | Rejected for daily use. The output can't be declared (`Promise`). The plugin can't tell writes from reads, so acknowledgement, invalidation and `uncertain` reporting become guesswork. The actor would have to be parsed out of arguments, which invites impersonation. Justified later only as a read-only, allow-listed `--json` escape hatch, and only if evaluation shows models need advanced or admin reads inside programs. Deferrable. | -| **D. Workflow macros (`beads.start`, `beads.handoff`)** | Rejected. They encode scope and acceptance judgment in plugin code. The one exception is folding a pure invariant into an operation: claim readback (D2 below). | -| **E. Typed daily-loop API in one namespace (recommended)** | About 11 operations, each with a discriminated, declared output and a fixed argv. Each exists because code mode gains something specific from it: fields for programmatic decisions, truthful per-operation outcomes, actor injection, or a single acknowledgement site. | - -## 3. Target design - -### Ownership layers - -| Layer | Owns | -|---|---| -| **Beads CLI** | Database, routing, consistency, atomic claim, ID generation, readiness semantics | -| **Host (OpenCode)** | Code-mode runtime, catalog and search, per-call permission, cancellation, compaction, child transport, trace storage | -| **Plugin primitives** | Fixed argv, guard and location checks, permission assertion, derived actor, output normalisation, completeness, acknowledgement and invalidation | -| **Model-authored JavaScript** | Filtering, joins, adjacency checks, projection, ordering of dependent writes, bounded concurrent reads | -| **Model or user judgment** | Relevance, scope, whether to claim, whether acceptance is met, closure authority, what to remember | - -### Proposed operations - -These are **proposed contracts, not available today.** Flags not marked "AGENTS.md-documented" are unverified on 1.3.0/1.3.1. - -**Reads** (no actor, no invalidation): -- `beads.find({view: "ready"|"list"|"search"|"blocked", parent?, assignee?, status?, labels?, text?, limit≤50})` - - Returns `{status:"acknowledged", view, records:[{id,title,status,priority,type,assignee}], complete}` or `failed`. - - Fetches `limit+1` so `complete` is exact for that view's own CLI filters. -- `beads.get({ids: string[] (≤25)})` - - Returns `{status:"acknowledged", issues:{[id]: issue}, failed:[{id,detail}]}`. - - One guard check and one assertion per call. Uses a multi-ID `bd show` if 1.3.0 supports it, otherwise sequential spawns inside the call. - - Per-ID failure is never relabelled as "missing". -- `beads.edges({id, direction:"down"|"up", types?})` - - Direct relations with `dependency_type`; capped after normalisation, so `complete` is exact. -- `beads.memories({search?})` / `beads.recall({key})` - - Current semantics: `found` / `missing` / `failed`, with empty-found distinct from missing. - -**Writes** (derived actor, sole acknowledgement; each call asserts its own canonical shell resource with `save: []`): -- `beads.claim({id})` - - `acknowledged` only when the CLI's returned record shows `assignee === actor`. - - `not-claimed` (with the returned assignee and status) when the CLI returned a record showing someone else. - - `uncertain` (with target) on any ambiguous failure. - - Claim uses `bd update --claim --json` (AGENTS.md-documented). -- `beads.note({id, text})` — append checkpoint, as today. -- `beads.update({id, set:{status?, priority?, addLabels?, removeLabels?}})` - - Notes replacement and description rewrites stay in shell as deliberate edits. -- `beads.close({id, reason})` — `bd close --reason` (AGENTS.md-documented); acknowledged from the returned status. -- `beads.create({title, type, priority, description?, acceptance?, design?, parent?, discoveredFrom?, labels?})` - - `--deps discovered-from:` is AGENTS.md-documented. - - An `uncertain` create says to search before retrying, because blind retry risks a duplicate. -- `beads.remember({key, text})` — as today: `acknowledged` / `landed-uncommitted` / `uncertain`. - -Every write result carries `{operation, status, target, actor}`. No operation takes an actor input. - -**Implementation shape:** keep the existing runner, guard, permission and acknowledgement pipeline from `continuity.ts`. Replace the `inputFor` / `operationArgs` / `acknowledge` ternaries with one table of about 11 entries: input JSON Schema, output JSON Schema, argv builder, normaliser, read/write kind. That is a table, not a framework. The plugin enforces branch invariants itself, because the host only checks JSON-ness for raw schemas. - -**Registration:** code-mode-only (default), namespace `beads` with a short description, none pinned at first. `oc-beads:status` reports whether typed operations are registered and whether `execute` is visible for the session's agent. Agents without `execute` follow the shell fallback. - -**Actor:** the derived host actor becomes the single executor identity for OpenCode sessions. -- It is rendered into injected context per session and agent ("Your Beads executor actor: `opencode:build:3f…`; use it for any shell write"). -- It is returned on every typed write. -- Child sessions get their own derived actor, which matches "the executing worker claims its own work". -- Owner decision D2. - -**Context:** -- Keep prime injection unchanged for now. -- Restructure guidance into: - - a short always-on core: authority, missing/failed/withheld context, honest persistence; - - a capability block chosen from the request's actual tool set ("`beads.*` available in code mode; use `search({namespace:"beads"})`", or "use `bd` via shell"); - - on-demand material: a new `resources/CODE_MODE.md`, and existing delegation, planning and review policy. -- Remove the duplicated task-agent sections. - -**Invalidation:** -- Refresh prime on `remember` (prime can contain memories) and on external events. -- Don't refresh on note, claim, close or update, unless measured prime content turns out to depend on issue state (unverified). -- Emit the recovery cue only for non-acknowledged outcomes and child returns, not for the model's own acknowledged writes or every ordinary tool error. -- References become operation-aware (`task:` for issue operations, `memory:` for memory operations). - -## 4. What stays, what changes, what goes - -| Mechanism | Disposition | -|---|---| -| `prime.ts` runner, abort, timeout | **Keep**. Optional: a stdout byte cap. | -| `guard.ts` migration and store guard | **Keep**; run once per batch read. | -| `continuity.ts` pipeline (location, external-dir, permission, abort, actor, sole acknowledgement) | **Keep the core**. **Replace** the five flat tools with the namespaced operation table and declared outputs (fixes F9). | -| `host.ts` lifecycle, disposal, compaction references, event observer | **Keep**. **Change** `rememberResult` invalidation and cues (F6) and the `execute.after` generic error cue. Status adds typed-registration and `execute` visibility. Production activation still gated on 1.1. | -| `context.ts` cache, audience, prime policy | **Keep the mechanism**. Its render step gets the capability block and actor line, so the cache key must include the agent when the actor is rendered. | -| `guidance.ts` | **Restructure** (F7, F8): remove the "no native `bd`" and "no typed tool" claims; deduplicate; move this repo's planning/review-ticket policy (`:32`) out of always-on product guidance into a resource (D4). | -| `workflows.ts` 30 commands | **Keep all names**: they're the human entry points, user overrides depend on them, and they cost nothing until invoked. **Rewrite the shared text** (`:99`) to be capability-neutral. Daily commands (ready, show, list, blocked, workflow, update, close, create, comments, dep) say "compose with `beads.*` in code mode when present". Admin commands keep shell plus `--help`. Nothing removed; no human writes JS. | -| `oc-beads` skill and resources | **Change**: add `CODE_MODE.md` (status handling, ordered writes, bounded reads, projection, decline/Stop semantics, pointer to catalog search instead of copied signatures). The link count rises 16 → 17, which needs the hard-coded `16` at `workflows.ts:63` updated. Upstream `.agents/skills/beads` untouched. | -| `agents.ts` task agents and permission asks | **Keep**. Prompt deduplicated; mentions the namespace. | -| `instructions.ts` duplicate-block minimiser | **Keep**. | -| Sol's six-tool and namespace proposal | **Replaced** by section 3. Its output-schema, namespace, completeness and no-retry findings carry over. | - -## 5. Representative workflows - -These are **proposed signatures, not qualified behaviour.** Each block is one `execute` program; the gaps between programs are model or user decisions. - -**A. Discovery and graph triage (read-only; no claim):** -```js -const f = await tools.beads.find({view: "ready", parent: "EPIC", limit: 20}); -if (f.status !== "acknowledged") return {failed: f.detail}; -const ids = f.records.map(r => r.id).slice(0, 8); // bounded fan-out -const edges = await Promise.allSettled(ids.map(id => tools.beads.edges({id, direction: "down", types: ["blocks"]}))); -return {complete: f.complete, candidates: f.records.slice(0, 8).map((r, i) => { - const e = edges[i]; - if (e.status === "rejected" || e.value.status !== "acknowledged") return {...r, blockers: "unknown"}; - const open = e.value.records.filter(d => d.status !== "closed").map(d => d.id); - return {...r, openBlockers: open, edgesComplete: e.value.complete}; -})}; -``` -The join and the "all direct blockers closed" check are computation in JavaScript. Choosing a candidate, and whether it is in scope, stays with the model or user. `unknown` is never turned into "unblocked". Ready status gives no dispatch authority. - -**B. Authorized execution:** -- **Program 1:** - ```js - const g = await tools.beads.get({ids: ["T"]}); const t = g.issues?.T; - if (!t || t.status === "closed") return {stop: "not actionable", g}; - const c = await tools.beads.claim({id: "T"}); - return {claim: c.status, actor: c.actor, assignee: c.issue?.assignee, acceptance: t.acceptance_criteria, notesTail: t.notes?.slice(-2000)}; - ``` - Anything other than `acknowledged` makes the model stop. -- **Direct shell turns:** implement and run validation (code mode can't do this). -- **Program 2:** - ```js - const n = await tools.beads.note({id: "T", text: ""}); - if (n.status !== "acknowledged") return {note: n}; - // Only when the model has judged acceptance met AND closure authority exists: - const x = await tools.beads.close({id: "T", reason: ""}); - return {note: n.status, close: x.status, detail: x.detail}; - ``` - A follow-up `create({..., discoveredFrom: "T"})` only when authorized. A rejected write throws and stops the dependent writes; don't catch it and continue. Under the accepted limitation, later independent calls still get their own permission check. - -**C. Selective recovery:** -- **Program 1:** - ```js - const [mine, mem] = await Promise.allSettled([ - tools.beads.find({view: "list", status: "in_progress", assignee: ACTOR, limit: 10}), - tools.beads.memories({search: "build"})]); - // return ids/titles and memory KEYS only - ``` - `ACTOR` is the rendered actor value. -- **Model:** picks the task and the relevant keys. -- **Program 2:** `get` the chosen issue plus `recall` the chosen keys concurrently; return an excerpt of the notes and the recalled values. - -## 6. Operational semantics - -- **Ordering:** dependent writes are sequential `await`s; there is no write batching, and batching never implies transactions, exactly-once execution or idempotency. Reads are batch-shaped (`get` takes IDs). Program fan-out is bounded by guidance. A small per-location spawn semaphore is an optional bounded-I/O addition, not a scheduler. -- **Authorization:** one assertion per operation with its canonical resource. Existing `bd *` grants apply, denies win, and there is no new saved grant. A three-write program can prompt three times under `ask`, and that is correct. -- **Uncertain outcomes:** the plugin never retries. It returns `uncertain` with the target, and the program or model reads back with `get` before considering another write. -- **Identity:** a single derived actor (D2). The permission agent is still the actual invocation agent. -- **Cancellation:** the combined abort signal stays as it is. Stop/Cancel is still unqualified (.6). -- **Not built:** no queue, poller, graph cache, or state engine. - -## 7. Context economy - -| Budget | Change | -|---|---| -| Always-on system | Capability-aware and deduplicated guidance; planning/review policy moved on demand. Prime unchanged. | -| Catalog | One namespace summary plus selected signatures under a heuristic 2,000-unit budget. Large unions get trimmed and reached via search. Measure before pinning anything. | -| Generated code | Model-authored; a small extra cost for one-off reads. For a single trivial read, plain shell may be cheaper. | -| Returned output | Projection in JavaScript. Tools return full typed records, since raw data stays in the runtime. | -| Trace storage | Inner inputs, including write text, are kept in `toolCalls`. Not replayed, but not ephemeral. | -| Process cost | Batch reads and targeted invalidation cut spawns (F5, F6). | - -Possible regressions: -- Models that ignore the catalog and use shell anyway. -- Agents with `execute` denied. -- Larger union signatures crowding the catalog. - -No token savings are claimed. The synthetic 18,432 → 905-byte figure remains fixture bytes only. - -Prime policy: measure prime bytes and the size of its memory section in .9. Any lighter prime is a later owner decision (D6), and depends on a supported CLI mode that I have not verified. - -## 8. Minimum coherent pre-release slice - -1. Operation table with declared outputs and matching input constraints (fixes F9). Namespace registration for the 11 operations. Keep the earlier detail fixes: uncertain results keep their target, and the original detail survives a notification failure. -2. Actor rendered into context and returned by writes. -3. Capability-conditional, deduplicated guidance, plus the `CODE_MODE.md` resource. Rewrite the shared command text. Update the link count. -4. Narrower invalidation and recovery cues; operation-aware references; status reports typed/`execute` visibility. -5. Tests: `continuity` (per-operation argv, normalisation, branches, `limit+1` completeness, claim `not-claimed` / `uncertain`, create-uncertain, no retry), `host` (registration, disposal, IDs, invalidation scope, actor rendering), `guidance` / `workflows` (no false capability claims). `bd-contract`: check every flag used on 1.3.0 and 1.3.1, and drop unsupported filters from the schemas rather than branching on version. - -**Independently deferrable:** -- `link` / `dep add` -- `heartbeat` -- description/notes edits -- read-only passthrough (C) -- prime reduction -- spawn semaphore -- pinning -- comments - -**Spec and tasks** (the parent maps these; I'm not creating a graph): -- `work-continuity` spec: the typed set becomes the daily-loop API. -- `workflow-access` spec: capability-neutral command text. -- Task 3.1 is checked against the five-operation scope, so the expansion needs either a new task or an explicit re-scope (parent/owner). -- 1.1 adds: namespace path, `execute`-denied visibility, write-operation permission resources. -- 6.2 / .9 adds workflows A–C on the installed host, using actual catalog signatures and recorded bytes. -- 4.2 / .6 adds Stop during a multi-write program, with no later dispatch. - -## 9. Owner decisions needed - -| # | Decision | My recommendation | -|---|---|---| -| D1 | Adopt the ~11-operation daily-loop API, including lifecycle writes, instead of the six-tool shape | Yes | -| D2 | Derived host actor is the canonical OpenCode executor identity, shown to the model, never model-supplied | Yes | -| D3 | Code-mode-only registration with shell fallback; no direct duplicates | Yes | -| D4 | Restructure always-on guidance; move repo-specific planning/review policy on demand | Yes | -| D5 | Narrower invalidation and cue policy | Yes | -| D6 | Prime policy unchanged until .9 measurement | Yes | -| D7 | Keep all 30 command names; their prompt text changes, and that is a compatibility-visible change | Yes | - -## 10. Evidence limits - -- Verified by reading source: F1–F8 and the cited lines. -- Not verified: - - 1.3.0 support for any proposed flag, multi-ID `show`, or the claim-conflict output shape; - - whether prime content depends on issue state; - - whether `execute` is enabled for every installed agent and provider; - - blob IDs for `shell.ts` against `tree.json` (I relied on `tag.json` and agreement between the four cached copies); - - any installed, model, interpreter or token behaviour. -- No probes were run. - -## Readiness - -**Ready for an owner design decision.** This is not code or installed-behaviour acceptance. - -**Blockers to implementing the design:** owner decisions D1–D3, and the 1.3.0 flag check for each operation (which may shrink the filter sets). - -**Remaining unknowns, not blockers:** claim-conflict CLI output, whether prime depends on issue state, catalog fit under the budget, and real model uptake. These are resolved in implementation tests and .9. - -## Parent verification and disposition - -The decision-changing F1/F2 findings were independently verified against the exact pinned Git-tree blob IDs after the review: `packages/core/src/tool/plugin/shell.ts:195` declares `codemode:false`, and `packages/core/src/tool.ts:236-262` excludes direct-only tools from code-mode inventory and omits code-mode exposure when execute is wholly denied. Both cached files match the pinned complete tree. The earlier claim that ordinary shell provides an in-code-mode CLI fallback was incorrect; shell remains a direct/model-turn fallback only. Sol report and narrow READY are historical and not broader design approval. - -The recommendation is ready for owner DESIGN decision, not accepted product implementation. The review itself is complete; investigation and remaining implementation/qualification remain open and paused. The parent recommends the coherent daily-loop direction rather than the six-tool patch. Before implementation contracts are finalized, verify supported CLI inputs/outputs, including claim/conflict evidence, multi-ID reads and flags. Do not silently weaken post-approval/pre-spawn guard, location, identity and abort rechecks while optimizing batched reads. Narrowing invalidation also requires confirming whether selected prime output depends on issue state. These are bounded correctness checks, not authority for a new infrastructure or test project. - -No task markers, source, assets, provider/runtime configuration, upstream posts, publication, release or activation changed. Proposed additional resources/commands/tool shapes and context policy require owner selection and active-spec/task reconciliation before implementation. diff --git a/docs/reviews/opus-code-mode-investigation-wgv.md b/docs/reviews/opus-code-mode-investigation-wgv.md deleted file mode 100644 index 7690054..0000000 --- a/docs/reviews/opus-code-mode-investigation-wgv.md +++ /dev/null @@ -1,64 +0,0 @@ -# Opus code-mode investigation review - -Review: `opencode-beads-ecj`; investigation: `opencode-beads-wgv`. - -Scope: frozen investigation report and proposed implementation direction, NOT implemented source, installed/model qualification, activation or release. - -- Baseline: `072429f1a7723ade23e756a921924d9d0acacf31`. -- Actual model: `claude-opus-5-5`; requested effort: medium. -- Reviewer session: `ef963df0-acdb-4479-af76-29a067b3975f`. -- Report SHA-256: `58af436a57730d4df396b9e38551a1c689efa848af7509c4fe1062f277db1826`. -- Parent verified all 14 frozen hashes and completed working-report identity. -- Result: `is_error=false`, `terminal_reason=completed`, no permission denials; actual modelUsage identifies Opus 5.5. -- Read-only tools: Read/Grep/Glob; no subagents spawned. -- Full execution record: `/opt/data/cache/scratch/opencode-codemode-opus-review/review.jsonl`; manifest alongside. - -## Independent verdict - -**Verdict: READY.** This covers the investigation and the implementation direction it recommends. It does not approve source code, installed behaviour, activation or release. - -## Standards findings -No material findings. - -- **Ownership and scope fit `AGENTS.md`.** The report proposes no upstream patch, no decline translator, no retry loop and no confinement or routing framework (`docs/code-mode-product-investigation.md:46`, `:199`, `:243`). Beads keeps routing and the database (`:27`). Write actors still come from the host's session and agent identity, and the model gets no actor argument (`:195`; matches `src/continuity.ts:34-41`, `:150`, `:201`). -- **Size is proportionate.** It adds one fixed-argv read operation with no generic runner and no writes (`:91-106`, `:236`). Schemas stay as raw JSON with branch checks inside the existing result construction, rather than a validation framework (`:83`). The deferral list is explicit (`:243`). -- **Namespace claim confirmed in pinned source.** `effectiveName` turns namespace + name into `beads_show` (`core/src/tool/runtime.ts:278-281`). `editor.namespace` exists (`core/src/tool.ts:171-178`), and code-mode paths become `beads.show` (`codemode/tool.ts:321-322`). So `host.ts`'s existing exclusion of `beads_*` events can stay as it is (`:28`, `:236`). - -## Spec findings -No blockers. Two low-severity points are worth fixing in the implementation dispatch rather than in another report revision: - -1. **Low: the query filter flags aren't backed by captured evidence.** `:95-97` and `:106` propose `parent` on ready/list, `status`, `assignee`, and `--direction`/`--type` on `dep list`. The packet has no saved help output for them; I found no `--parent`/`--direction` text in any packet file. `:258` says help was inspected, and `:236` makes a 1.3.0 check a condition of implementation. - - **Consequence:** the published `QueryInput` could advertise a filter that the 1.3.0 minimum rejects. - - **Smallest fix:** in the P1 acceptance, require recorded 1.3.0 and 1.3.1 help (or `bd-contract` runs) for every advertised filter. Drop any unsupported filter from the input schema instead of branching on version at runtime. -2. **Low: the `complete` flag for ready/list leaves an ambiguous edge.** `:106` treats a full page as conservatively incomplete. That is honest: it never claims completeness falsely. But a result of exactly `limit` records gets reported as incomplete even when nothing was left out. - - **Smallest fix:** ask the CLI for `limit+1`, return at most `limit`, and set `complete` from whether the extra record arrived. State that "complete" means complete for the CLI view's own default filters, not the whole tracker. - -The remaining spec checks passed: -- **Your accepted plain-decline decision is kept, not reopened.** Stop/Cancel stays separate and still unqualified, and the historical failure stays recorded as a failure (`:9`, `:199`, `:241`). -- **Persistence stays truthful.** Fulfilment and completion are kept distinct from durable success; `uncertain` writes carry their target; there is no automatic retry; a mutation that runs before an outer contract failure is called out (`:28`, `:43`, `:85`). -- **Proposed signatures are labelled as proposed, not available** (`:71`, `:98-101`, `:120`, `:125`). The search signature matches pinned source (`tool-runtime.ts:89-107`). -- **Status checks don't lose uncertainty.** The ordered-write sketch stops on any non-`acknowledged` checkpoint and keeps `commitIndeterminate`. The read sketches keep `rejected` separate from `failed` and `missing` (`:136-147`, `:183-190`). -- **Branch table matches current code.** Write failures produce only `uncertain`, reads produce `failed`, and recall-missing is decided only from the CLI's exit-1 output (`continuity.ts:206-214`). -- **Value of `query` is stated honestly.** It improves discoverability and reliability over structured shell; it doesn't uniquely make selective handling possible. No real savings are claimed (`:89`, `:203`, `:217`). -- **Bridge metrics match `bridge-results.json`:** 18,432 vs 905 bytes, 9 calls, 0 logs, guidance 7,758 / 4,421 bytes, and the as-built signature `Promise`. -- **The scope fits your broad objective.** All commands, the shared skill and shell fallback stay; typed tools cover the common read paths and the continuity primitives (`:108-116`). - -## Optional observations -- **Parent follow-up:** the parent's spec and tasks don't yet mention the six-tool namespaced direction; `candidate.diff` only covers the decline decision and the defect it doesn't accept. That is the parent's reconciliation step after acceptance, as `:245` says, not a defect in the report. -- `:83` could say the readable `content` keeps the `failed`/`uncertain` detail in the direct path. It's implied by "retaining status/reference/detail". -- The dependencies view caps after normalising, so its `complete` flag is exact. Saying so would make it clearer than the ready/list case. - -## Not verified -- Whether 1.3.0 or 1.3.1 supports the query flags, and what `dep list` actually returns. -- The count of 30 commands and 16 resource links (`:116`). -- That the cached source matches its Git blob IDs (I took the researcher's claim). -- Any installed host, model, interpreter, real token use, or cancellation behaviour. -- `host.ts` registration details beyond what the report cites. - -I didn't re-run either probe and relied on the reported results. I also didn't check the manifest hashes. - -## Parent disposition - -Review completed READY for the report and recommended direction. No blocking corrections; retain both low-severity implementation notes: record minimum/current CLI support for every advertised filter, dropping unsupported filters rather than adding runtime version branches; and consider a limit-plus-one lookahead with completeness explicitly scoped to the CLI view defaults. Neither note authorizes implementation or changes the frozen report. - -The owner-accepted upstream plain-decline limitation remains accepted; the output-schema defect is not waived. Investigation remains open pending parent/owner direction and normative implementation reconciliation. No product source, task marker, host/model run, upstream filing, publication, activation or release follows from this review. diff --git a/docs/reviews/opus-code-mode-plan-recheck-wgv.md b/docs/reviews/opus-code-mode-plan-recheck-wgv.md deleted file mode 100644 index b8bd6fa..0000000 --- a/docs/reviews/opus-code-mode-plan-recheck-wgv.md +++ /dev/null @@ -1,50 +0,0 @@ -# Opus corrected-plan delta recheck - -Review `opencode-beads-ecj`; planning `opencode-beads-wgv`; prospective source `opencode-beads-vuy.10`. - -Actual model `claude-opus-5-5`; requested medium effort; resumed session `ef963df0-acdb-4479-af76-29a067b3975f`. Parent verified completed/is_error=false, actual modelUsage, no permission denials, all20 frozen hashes and exact working-candidate identity. Packet, manifest, correction-only diff and stream are under `/opt/data/cache/scratch/opencode-codemode-opus-plan-recheck/`. Baseline `072429f1a7723ade23e756a921924d9d0acacf31`. - -The original REVISE in opus-code-mode-plan-review-wgv.md remains intact. This is a separate READY on the corrected plan, not implementation or installed/model acceptance. - -## Independent recheck (verbatim) - -**Verdict: READY** for the corrected plan. All eight findings (S1–S5, P1–P3) are resolved, and the corrections introduced no regressions. **Proportionality: yes.** The corrections bound the testing work without weakening any real guarantee: permissions, attribution, guard holds, cancellation and persistence honesty are all kept. The original REVISE stands unchanged as the historical verdict; this recheck is separate from it. - -## Spec findings (correctness) - -| Finding | Status | Evidence | -|---|---|---| -| **S1 — High** (argv order, `--sandbox`) | **Resolved** | The design rule (`design.md` corrected clause, diff :36) now keeps subcommand-first argv. `--sandbox` goes on every read and write; `--actor` goes on writes, after the operation's arguments and before any `--` terminator. Global flags never go before the subcommand or after `--`. The ledger rows (diff :51-61) match the frozen source exactly: `continuity.ts:70-74` plus the splice at `:154` produce `bd show --json --sandbox`, `bd memories --json --sandbox -- [search]`, `bd recall --json --sandbox`, `bd update --append-notes --json --actor --sandbox` and `bd remember --key --json --actor --sandbox -- `. The new rows (claim, update, close, create, find, edges) follow the same pattern. The new normative scenario "Canonical execution preserves permission and sync policy" (`work-continuity/spec.md`, diff :148-152) and the requirement clause (diff :140) state it. Task 7.2 (diff :193) carries it into implementation. | -| **S2 — Moderate** (throw vs. value) | **Resolved** | Diff :64 and the new scenario "Execution is refused before spawn" (diff :154-158): invalid input, missing identity, guard hold and location change stay thrown. There is no `executed:false` branch. Permission rejection and cancellation are unchanged. A started write that is interrupted keeps its recovery uncertainty even without a normal return. This matches accepted `continuity.ts:56-60, 179, 185, 201`. | -| **S3 — Moderate** (actor wording) | **Resolved** | `workflow-access/spec.md` (diff :170) and design (diff :74): the context actor and the typed-write actor both derive from the same actual request/invocation session and agent, never the session-default agent. Attribution grants no permission, and permission checks separately use the actual `context.agent`. Task 7.3 (diff :194) adds "no session-default substitution or mandatory delegation". | -| **S4 — Moderate** (1.3.0 evidence path) | **Resolved** | Task 7.1 (diff :192) and design (diff :87): under a future authorised assignment, `scripts/install-bd.sh` installs 1.3.0 and 1.3.1 into disposable directories, and the existing `scripts/bd-contract.ts` runs once per version. Extensions are limited to the touched shapes. Help and source count only as discovery, never as passing evidence. The ledger is a table in the SDK contract citing captured output. Nothing is authorised now, and the operator environment and the minimum version are untouched. Unsupported optional filters are omitted; a core operation that fails its contract stops for a parent decision. | -| **S5 — Low** (executor seam) | **Resolved** | Diff :89 and task 7.2 state plainly that no maintained executor seam exists. 7.2 reruns the two existing scratch probes once against the real candidate definitions and records the pin, commands and results in the SDK contract. Product tests assert that every definition declares `output` and that normalised fixtures satisfy their declared branch. No vendored runtime, new dependency or host replica. Installed confirmation stays with .2 and .9. | - -## Standards findings (proportionality) - -| Finding | Status | Evidence | -|---|---|---| -| **P1 — Moderate** (capability combinations) | **Resolved** | Task 7.3 (diff :194) and design (diff :93) now name four representative states: typed available; `execute` denied with shell available; neither available; guard hold. Actor isolation stays, and the capability cross-product is explicitly excluded. | -| **P2 — Low** (test multiplication) | **Resolved** | Task 7.2 and diff :91: one table-driven case set per operation. Shared negative tests are retargeted once, against a representative multi-spawn `get` and a representative write, plus only the necessary new partial/completeness/uncertain cases. Production still rechecks before every child spawn. The matrix and the upstream-owned tests are excluded. | -| **P3 — Low** (.6 overlap) | **Resolved** | Task 4.2 (diff :181), `execution-map.md` (diff :104), design (diff :83, :93), and the scoped `.6` record (`scoped-beads.json:227-228, 244`) all say the same thing. .6 consumes the 7.2/7.3 deterministic evidence and adds only its own Stop/handoff observation. Explicit cancellation must still prevent later dispatch. | - -**Regressions from the corrections:** none found. The two optional items the planner chose to resolve are consistent with the necessary contracts: -- `memories` keeps the accepted key→value map (diff :54). -- An uncertain claim returns its target and actor, and the caller runs `get` explicitly; claim no longer hides a second permission prompt (diff :69). - -Task IDs, markers, ownership and dependencies are unchanged in the files I read. - -## Optional notes (non-blocking) - -- **`create` title can be parsed as flags.** This predates the corrections and is outside the recheck scope. The `create` row (diff :60) passes `` as a free positional before the flags. IDs and keys can't start with `-` because of the token check, but a model-supplied title starting with `-` (for example `--assignee=x`) could be read as a flag. When 7.1 qualifies the exact argv for create, use a supported title flag or reject titles with a leading `-`. Search text already follows `--`. -- **"No per-command reapproval" wording.** In 7.1 (diff :192) this should be read as orchestration/tracker approval inside the scoped assignment, not as bypassing OpenCode or host permission prompts. Making that explicit would remove any doubt. - -## Scope - -This verdict covers the corrected plan only. It does not accept any source, installed behaviour or model behaviour, and it does not authorise implementation, CLI installation or contract runs. I didn't run anything. I read the correction diff, the corrected clauses, the frozen `continuity.ts` argv placement and the scoped Beads fields. - -## Parent disposition - -All S1-S5 and P1-P3 corrections are independently resolved; no additional plan revision/review is required for the two nonblocking notes. Carry these into the existing task7.1/7.2 implementation handoff: qualify a supported title flag or otherwise ensure flag-like create titles remain data, never CLI options; scoped orchestration authority never bypasses native host permission prompts. These are reminders within existing operation/argv qualification, not new tasks or runtime fixes. - -The review gate is complete. Source .10 remains blocked/unassigned/implementation_authorized=false; no source execution, CLI installation/contract runs, host/model qualification, publication, activation or release is authorized by this verdict. Planning record remains open for parent-controlled adoption/publication closeout. diff --git a/docs/reviews/opus-code-mode-plan-review-wgv.md b/docs/reviews/opus-code-mode-plan-review-wgv.md deleted file mode 100644 index 08e24aa..0000000 --- a/docs/reviews/opus-code-mode-plan-review-wgv.md +++ /dev/null @@ -1,106 +0,0 @@ -# Opus review of reconciled code-mode plan - -Review `opencode-beads-ecj`; planning `opencode-beads-wgv`; prospective source owner `opencode-beads-vuy.10`. - -Actual model `claude-opus-5-5`, requested medium effort, resumed session `ef963df0-acdb-4479-af76-29a067b3975f`. Review scope: correctness, completeness AND proportionality of Astra-reconciled planning, not implementation or installed qualification. Parent verified completed/is_error=false, actual modelUsage, no permission denials, and all20 frozen hashes. Baseline `072429f1a7723ade23e756a921924d9d0acacf31`. Full execution and candidate manifest: `/opt/data/cache/scratch/opencode-codemode-opus-plan-review/`. - -## Independent verdict (verbatim) - -**Verdict: REVISE** — four bounded wording corrections, then the plan is ready for parent acceptance. **Proportionality: yes, apart from three wording fixes** (P1–P3 below). - -The eleven-operation direction is still the right product. It adds no generic runner, macros, queue or cache, and it doesn't pull in a full upstream data model. - -The corrections fix two problems: -- **A permission and sync regression:** the new argv ledger moves `--actor` in front of the subcommand and drops `--sandbox`. -- **Ambiguities an implementer would have to guess at:** whether pre-spawn refusals throw or return a value, the actor wording in the spec, the 1.3.0 evidence path, and an executor test seam the plan treats as existing when it doesn't. - -## Spec findings (correctness) - -**S1 — High. The argv ledger drops `--sandbox` and puts `--actor` before the subcommand.** -- **Where:** `design.md:121-126` writes every write as `bd --actor <derived> <sub> … --json`; `:112` makes the permission resource the rendering of that argv. Neither the specs nor the design mention `--sandbox` anywhere. -- **What's accepted today:** `continuity.ts:154` adds `--actor` and `--sandbox` after the subcommand. The accepted tests assert resources starting `bd update task-1 --append-notes` and `bd remember --key` (`continuity.test.ts:58, 72`). The skill documents the same subcommand-first form with `--sandbox`. -- **Consequence 1:** a user's selective rule such as `bd close *` (deny or ask) no longer matches `bd --actor … close …`. That is a permission-parity regression against existing user rules. -- **Consequence 2:** without `--sandbox`, Dolt auto-push is no longer suppressed, which breaks the no-automatic-sync policy. -- **Fix:** change the ledger column to "`bd <sub> <positionals> <flags> --actor <derived> --sandbox --json` (writes); reads append `--sandbox --json`; keep the accepted `--` terminator before free text where the current mapping uses it. The canonical resource is this exact subcommand-first rendering." -- **Also:** add one clause to the requirement at `work-continuity/spec.md:115`: "fixed argv keeps the accepted subcommand-first canonical form and `--sandbox`". -- **Test:** covered by the per-operation table test below; nothing extra. - -**S2 — Moderate. It's unclear whether pre-spawn refusals throw or return a value.** -- **Where:** `design.md:128` says "a pre-spawn refusal is `failed` with `executed:false`". In the same paragraph, permission rejection and cancellation propagate unchanged. -- **What's accepted today:** invalid input, missing identity, guard holds and location changes all throw (`continuity.ts:56-60, 179, 185, 201`; tests at `:78` and `:99`). -- **Consequence:** an implementer has to guess which refusals become values. Turning a hold into a returned value changes code-mode control flow: the program keeps running instead of being interrupted. It would also mean rewriting accepted tests. -- **Fix (smaller option):** "Invalid input, missing identity, guard hold and location change remain thrown pre-spawn refusals, as accepted; there is no `executed:false` result branch." If the owner does want the value branch, list exactly which refusals use it and keep permission and abort thrown. - -**S3 — Moderate. The spec's actor wording contradicts how the actor is derived.** -- **Where:** `workflow-access/spec.md:208` says the actor is the same "independently of permission context.agent". -- **The contradiction:** the actor is derived from the actual invocation session plus agent (`continuity.ts:34-41`; `design.md:136`). The vuy2 evidence shows the invoking agent can differ from the session default. -- **Consequence:** taken literally, an implementer could render a session-default actor in context that doesn't match the actor the tool actually writes with. -- **Fix:** "context and typed results expose the same actor derived from the actual request/invocation session and agent; attribution grants no permission, and permission checks separately use the actual `context.agent`." - -**S4 — Moderate. Task 7.1's evidence path can't establish what the minimum version needs.** -- **Where:** `tasks.md:46` says "existing cached source/help and, only under separately authorized source execution, disposable `bd-contract` cases". -- **The gap:** help text can't establish JSON shapes, claim-conflict evidence, the generated ID from create, close state, or whether prime depends on issue state. The risk is either "qualifying" 1.3.0 from help alone, or stalling with no defined rule. -- **Fix:** "JSON, claim, create, close and prime-dependence facts for 1.3.0 and 1.3.1 are established only by running the existing `scripts/bd-contract.ts`. Its binaries are installed into disposable directories via the existing `scripts/install-bd.sh`, under explicit authority. Help-only evidence leaves a contract unestablished: omit the optional filter, or stop for a core operation. The ledger is a table in the SDK contract that cites `bd-contract` output, not a second tool." - -**S5 — Low. The "existing pinned executor/catalog seam" isn't in the product tests.** -- **Where:** `tasks.md:47` says to extend it. The product tests import only `@opencode/plugin` types. The seam exists only as scratch probes (`opencode-codemode-shape-review/check-output-contract.ts`, `opencode-codemode-product-wgv/bridge-probe.ts`), which run against copied host files. -- **Consequence:** an implementer may vendor the host runtime into maintained tests, or skip the one check that catches the demonstrated undeclared-output failure. -- **Fix:** "Rerun the existing scratch executor/catalog probe against the exact .10 candidate's real definitions and record the result in the SDK contract. Product tests assert that every definition declares `output` and that each normalised fixture satisfies its declared branch. Installed catalog and executor confirmation stays with .2 and .9." - -Checks that passed: -- **Capability rendering:** source-supported; `event.tools` is on the context hook (`plugin/src/effect/session.ts:35`). -- **Batch partial failure:** per-ID failures; all failed returns `failed`. -- **Completeness:** true / false / unknown (`null`), and `limit+1` only where the CLI view supports a bounded query. -- **Uncertain outcomes:** uncertain claim and create keep their target; `not-claimed` only on evidence. -- **Prime refresh:** stays conservative until 7.1 settles prime dependence; acknowledged writes no longer trigger a redundant cue. -- **Settled boundaries:** the accepted plain-decline limitation and Stop/Cancel owned by .6. -- **Task 1.1:** already covers the namespace, catalog signatures and execute-denied checks (`tasks.md:12`). - -## Standards findings (proportionality and ownership) - -**P1 — Moderate.** `tasks.md:48` says "for each capability combination". That invites a cross-product of capabilities. Replace with "representative states: typed available; `execute` denied with shell available; neither available; guard hold". - -**P2 — Low.** `tasks.md:47`, "exercise all result branches … rechecks for every child spawn", is a correct implementation requirement but an unbounded test instruction. Add: "Tests: one table-driven case set per operation (argv, normalisation, declared branches). Shared boundary negatives run once against a representative multi-spawn `get` and a representative write. Retarget the 15 existing shared-boundary tests rather than multiplying them across operations." - -**P3 — Low.** `execution-map.md:34` gives .6 "affected identity/handoff/abort rechecks", which overlaps the deterministic abort checks in 7.2/7.3. Add: ".6 consumes the 7.2/7.3 deterministic results; it adds only its Stop/handoff observation." - -Optional, non-blocking: -- The claim readback fallback via "a separately permissioned show" (`design.md:132`) hides a second permission prompt inside one claim. Returning `uncertain` plus the target and letting the program call `get` is simpler. -- Define the `memories` result shape once (`design.md:119` says "records"; the accepted adapter returns a key→value map). -- The `.2 → .10` edge blocks .2's throwaway host probes, which don't need the adapter. Live-host authority gates them anyway. - -The ownership graph is otherwise coherent: one source owner (.10) for 7.1 → 7.2 → 7.3, and the qualification owners (.2, .6, .9) consume its outputs. - -## Verification outline - -| Category | Owner | Content | -|---|---|---| -| Per-operation argv and normalisation | 7.2 | One table entry per operation (about 11): canonical subcommand-first argv with `--sandbox`, the resource string, success normalisation, each declared branch from fixture CLI output. | -| Shared boundary failures | 7.2 | Retarget the existing tests once: permission identity and `save: []`, external directory, hold before and after approval, location change, abort during approval and after spawn, missing identity, no retry, notification error keeps the original detail, sole acknowledgement. Plus new: batch partial failure, complete/unknown, uncertain claim and create. | -| Native executor and catalog seam | 7.2 (scratch), .2 / .9 (installed) | One rerun of the scratch probe against the real definitions, recorded in the SDK contract. Product test only asserts declared outputs. | -| CLI ledger | 7.1 | Existing `bd-contract.ts`, extended only for new shapes (find views with limit, close, update fields, `dep list` direction/type, claim conflict, create ID, prime before/after an issue write). Run once on 1.3.0 and once on 1.3.1. | -| Guidance, context, package | 7.3 | The four capability states, actor isolation across agents and sessions, operation-aware references, conservative invalidation, 17 links installed, disposal. | -| Installed workflows and Stop | .9 / .6 | Workflows A–D on the actual host; one Stop during a composed write; actor agreement between typed and shell writes. Byte and process observations, with no token-savings claim. | -| Regression | 7.3 | Existing suite, typecheck, package smoke. | - -**Do not test downstream:** -- OpenCode's interpreter, JavaScript or Promise semantics. -- Catalog search ranking or renderer internals. -- The permission service's wildcard engine. -- Compaction, replay or scheduling. -- Beads readiness, routing or consistency. -- Plain-decline whole-step termination (owner-accepted). -- Cross-products of operations × versions × modes × permission outcomes. -- A host replica, or a vendored executor in product tests. - -## Scope - -This verdict covers the reconciled plan only. It does not approve implemented source or installed or model behaviour, and it does not authorise implementation. I didn't run anything. I read the plan, the frozen source and tests, `bd-contract.ts`, the scoped Beads, and the pinned host session-type cache. - -## Parent verification and disposition - -REVISE is retained. The broader eleven-operation architecture is judged proportionate; required corrections concern the actual plan/verification scope. Independently confirmed the canonical argv drift against src/continuity.ts:148-154, contradictory actor wording at workflow-access/spec.md:208, and task7.2/7.3 references to an existing product executor seam and every-capability-combination testing. Review finding IDs S1-S5 and P1-P3 are the authoritative correction references; the opening prose count does not enumerate them accurately. - -No product defect was introduced into running code by these planning errors: product source remains unchanged and typed activation withheld. Plan corrections and a bounded recheck are still pending; no source implementation or auto-correction dispatched from this review notification. Preserve all prior reports and accepted source task history. Proposed reuse of existing boundary tests and representative native/installed evidence must not weaken real guard, permission, actor, cancellation or truthful-persistence requirements. - -Minimum/current JSON/mutation/prime contract qualification requires observed supported CLI evidence in isolated repositories, not help alone. Tagged source/help remains useful for planning/discovery; do not create a parallel qualification tool or upstream test campaign. diff --git a/docs/reviews/opus-code-mode-source-recheck-vuy10.md b/docs/reviews/opus-code-mode-source-recheck-vuy10.md deleted file mode 100644 index f85e76c..0000000 --- a/docs/reviews/opus-code-mode-source-recheck-vuy10.md +++ /dev/null @@ -1,45 +0,0 @@ -# Opus corrected-source recheck — vuy.10 - -Review `opencode-beads-co7`; actual Claude Opus 5.5, requested medium, same reviewer session `aa15a6fe-0427-4c80-a763-9d64cb6d12cc`. Verified completed, `is_error=false`, no permission denials. Corrected 44-path manifest `/opt/data/cache/scratch/opencode-codemode-opus-source-recheck/manifest.json` matched working source after review. Only `src/host.ts` and `tests/host.test.ts` changed from the original reviewed source. Original REVISE remains in `opus-code-mode-source-vuy10.md`. Parent independently passed 191 tests, typecheck, packed-package validation and whitespace checks. - -This evidence-only report is outside the frozen manifest. READY is source review, not live qualification, release or activation. Optional observations remain nonblocking; no remediation is authorized by their inclusion. - -## Reviewer report (verbatim) - -**Verdict: READY.** The original medium finding is resolved, and the correction introduces no material regression. - -## Finding disposition - -The medium finding (later events overwriting an uncertain write's recovery state, `src/host.ts:299-302/365-366/392-394`) is **resolved**. Each part checked against the frozen files: - -- **Bounded retention.** `gaps` now holds a set of distinct unresolved details per session (`snapshot/src/host.ts:139,144-149`). It keeps at most 32 details plus one overflow line that says earlier details are retained. That is a set of strings, not an event log. -- **Reads stay out of the gap set.** Only write outcomes call `recordGap` (`:314`). Read failures and `complete === false` now set only the one-shot recovery cue (`:315`), and those results are also returned to the caller. A capped `find` or failed `get` can no longer displace a write gap. -- **Success doesn't erase uncertainty.** No success path removes an entry. An acknowledged write later to the same target leaves the earlier uncertain entry in place. -- **Interruption appends.** Execution or compaction stopping now adds a generic entry (`:408`) and no longer overwrites the specific ones. -- **Rendering.** Every request now shows the retained gaps together with the one-shot cue (`:368-371`). Only the cue is deleted after use. Compaction (`:380-381`) and status (`:276`) show the same set. An aborted write still reaches `rememberResult`, because the existing notify-before-throw path in `continuity.ts:361-365` is unchanged. -- **Cleanup.** Session deletion and move clear gaps (`:162`), and unload clears them all (`:179`). - -## Standards - -The change is small and matches the surrounding code: JSDoc comments on both helpers, the same Map/Set idiom used for `references`, and no new abstractions. Nothing in argv, normalizers, CLI handling or versions changed. - -## Spec - -The work-continuity scenarios at `spec.md:81-84`, `:108-111` and `:123-126` are now met in source. Compaction and recovery keep the operation, target, actor and uncertainty across later reads, later successes and interruptions. Nothing triggers persistence and nothing retries. Other sessions stay isolated. - -## Correction-caused regressions - -None are material. Two low, nonblocking observations: - -1. **Gap text is now in every request.** - - **Where:** `host.ts:313-314` builds each gap from `JSON.stringify(result.target)` plus `result.detail`. - - **Trigger:** an uncertain `create`. Its target object carries description, acceptance and design (each up to 64k characters), and its detail can include CLI stderr and stdout. - - **Consequence:** these gaps are now rendered on every request for the rest of the session, not just at compaction or status. Before, the cue was shown once. A large uncertain create therefore enlarges every later request. - - **Fix if wanted:** cap the length of each rendered detail, or render create targets as title/type only. -2. **Gaps never clear within a session.** This is the intended conservative trade-off: entries are bounded and removed when the session is moved or deleted. - -## Evidence - -- **What I inspected:** `correction.patch` (both `src/host.ts` and `tests/host.test.ts` hunks), plus the frozen `snapshot/src/host.ts` lines covering the gap helpers, `forgetSession`, unload, `rememberResult`, the context and compaction hooks and the event subscriber. The new test walks the required sequence: started-then-aborted note, landed-uncommitted remember from a second actor, capped find, failed get, later acknowledged note, interrupt, compaction, two recovery requests, no-retry counts, another session, and the moved-session cleanup. -- **What I relied on without re-verifying:** the parent's report that only these two files changed, and their runs. Those were `bun test` (191 pass / 0 fail), typecheck (exit 0), packed-package smoke (exit 0, archive `e9525321…`) and `git diff --check` (exit 0). I ran nothing. -- **Still pending, not source blockers:** the live host, explicit Stop/handoff, installed and model workflows, and lifecycle gates. This verdict covers source only and does not accept or activate anything. diff --git a/docs/reviews/opus-code-mode-source-vuy10.md b/docs/reviews/opus-code-mode-source-vuy10.md deleted file mode 100644 index 13dd2ba..0000000 --- a/docs/reviews/opus-code-mode-source-vuy10.md +++ /dev/null @@ -1,80 +0,0 @@ -# Opus source review — eleven-operation code-mode candidate - -Review: `opencode-beads-co7`. Actual reviewer: `claude:aa15a6fe`, Claude Opus 5.5, requested medium effort. Session `aa15a6fe-0427-4c80-a763-9d64cb6d12cc`. Completed with `is_error=false`, `terminal_reason=completed`, no permission denials or spawned subagents. - -Candidate: local delta over `f2d6617619e2c3a35e4aeadd5be0092259b9979c`; frozen 44-path manifest `/opt/data/cache/scratch/opencode-codemode-opus-source-review/manifest.json`. Parent verified all candidate hashes unchanged after review and independently inspected the cited host recovery overwrites. This report is evidence-only, outside the reviewed manifest. No correction, source acceptance, task markers, publication or activation follows from this verdict. - -## Reviewer report (verbatim) - -**Verdict: REVISE** for this source candidate. There is one medium defect, and the fix is small. Everything else I checked meets the standards and the spec. - -## Standards - -The code follows AGENTS.md: strict ESM, `import type`, `node:` imports, and indexed access handled. Plugin and Beads responsibilities stay separate: no compatibility code for upstream, and no claim of absolute store confinement. - -Nonblocking smells (none needs a change for acceptance): -- **Duplicated write list.** The list of write operations appears twice, at `src/continuity.ts:240` and `src/host.ts:287`. Adding a twelfth operation would mean editing both. Exporting one set would fix it. -- **Thin wrapper.** `OperationDefinition` (`continuity.ts:184-191,239-242`) only wraps four separate per-operation switches (`validate`, `argv`, `outputFor`, `normalize`). It adds a layer without bringing the per-operation logic together. -- **Hard-to-read one-liners.** `continuity.ts:153,157,159,209` are dense. Line 209 is hardest to review. -- **Hand-repeated rules.** The input JSON Schema and `validate()` restate the same rules by hand, e.g. the status enum at `:61`, `:128` and `:134`. That is acceptable given the rule against adding a validator framework, but the two copies can drift apart. -- **Dead check.** The `assignee !== null` check at `:206` can never matter, because `isIssue` (`:78`) already rejects a null assignee. - -## Spec - -**Medium: later events overwrite the recovery state of an uncertain write.** -- **Where:** `src/host.ts:299-302`, consumed at `:365-366`. The same pattern exists before this change at `:392-394`. -- **Trigger:** `gaps` and `recoveryCues` hold one value per session. `rememberResult` now also writes them for read `failed` results and for `complete === false`. The routine case is a ready/list `find` with more than 20 matches, since the default limit is 20. -- **Consequence:** suppose a claim or note comes back `uncertain`, or a started write is aborted. Its gap records the operation, target and actor. A capped `find`, a failed `get`/`recall`, or a later `session.execution.interrupted` event then replaces that gap. Compaction (`:366`) and the next recovery cue no longer carry the write's target and actor. -- **Why it matters:** for an aborted write, the recovery state is the only place this information lives, because the tool throws instead of returning a result. That breaks three spec scenarios: - - "Compaction carries known … uncertain status" (`specs/work-continuity/spec.md:81-84`). - - "Interrupted append … exposes the uncertainty" (`:108-111`). - - "result or recovery state preserves operation, target/query, actual actor" (`:123-126`). - - It also contradicts `CODE_MODE.md:64-66`. -- **Why it's new now:** code mode composes many reads per step, which makes this overwrite routine. The candidate is what widened the overwrite to reads. -- **Smallest fix:** - - Let only write outcomes (`uncertain` / `landed-uncommitted` / interrupted write) set or append to `gaps`. Read partials and failures are already returned to the caller in the result. - - Make the interrupted-event path append to an existing gap instead of replacing it. - - Add one host test: uncertain or aborted write, then a capped `find` and an interrupt event, then compaction still contains the write's target and actor. - -The rest of the spec checks out: -- **Fixed namespace:** exactly eleven operations in namespace `beads`, code-mode-only (`continuity.ts:55,279`). -- **Input contracts:** declared with `additionalProperties:false`, and `validate` rejects unknown keys. -- **Output contracts:** a separate output shape for each outcome, and only evidenced CLI results count as acknowledged (`:192-234`). -- **Fixed argv:** the subcommand comes first in the permission resource; `--sandbox`, plus `--actor` on writes, goes before `--` (`:287-290`). -- **Option-like text:** titles go through `--title`, and free text goes after `--` or as a flag value. -- **Identity:** the actor comes from session and agent (`:46-53`). The same actor is shown to the model (`context.ts:56`) and checked again before each spawn (`:345`). The permission identity separately uses `context.agent` (`:299`). -- **Permissions:** - - Uses the native `permission.assert` with `save: []`. - - Abort rejects the pending permission wait, so a late approval can never start the process (`:302-312`). - - Guard, location and actor are rechecked before every spawn, including each `get` (`:340-346`). -- **Outcomes:** - - `not-claimed` requires the observed structured conflict (`:253-260`). - - Malformed or failed writes report `uncertain`; there are no retries. - - `get` keeps per-ID failures; `complete` is `true`, `false` or `null` per view (`:209`). - - A started write that is aborted still notifies before rethrowing (`:361-365`). -- **Context and guidance:** - - Writes invalidate all cached context. - - Guidance depends on the request's actual capabilities (`guidance.ts:87-91`). - - Shell is direct-only. - - Commands total 29 workflows plus `status`, i.e. 30; the skill requires exactly 17 links. -- **No activation leakage:** tools register only with the test-only `continuityQualified === true` (`host.ts:308`). Status reports them as "withheld pending 1.1". - -**Nonblocking observation:** an update that removes an issue's *last* label may come back `uncertain` even though it landed. `normalize` requires the `labels` array (`continuity.ts:224`), and Beads might leave that field out when it's empty. I haven't confirmed this. The contract run only covered removing a label while another remained (`docs/opencode-sdk-contract.md:49`). One more disposable 1.3.1 contract case would settle it. - -## Evidence / remaining gates - -- **What I read:** - - `candidate.patch`, for the old versions of the host gap and cue lines. - - Frozen `src/{continuity,host,context,workflows,guidance}.ts` and `assets/oc-beads/resources/CODE_MODE.md`. - - Parts of `tests/host.test.ts` and `scripts/bd-contract.ts`. - - The `work-continuity` spec. - - The `opencode-sdk-contract.md` ledger, lines 20-99. -- **What I did not do:** I ran nothing. The rest of the spec and planning docs were only checked through targeted searches. -- **Evidence from the parent and worker, not re-verified by me:** - - `bun test`: 190 pass / 0 fail. - - Typecheck: exit 0. - - Packed package: exit 0, SHA `86f781ba…`. - - Docs tests: 14/14. - - Worker's 1.3.1 contract run: 63 checks passed (`minimum131-contract.log`). -- **Still pending, outside source review:** the live host test, explicit Stop/handoff, installed discovery and model workflows, and unload/reactivation (gates .2/.6/.9). Their pending state is not why I'm asking for revision. -- **Scope of this verdict:** it covers this source only. It does not accept or activate anything. diff --git a/docs/reviews/opus-command-action-source-recheck-wzk.md b/docs/reviews/opus-command-action-source-recheck-wzk.md deleted file mode 100644 index 3104fbd..0000000 --- a/docs/reviews/opus-command-action-source-recheck-wzk.md +++ /dev/null @@ -1,30 +0,0 @@ -# Opus command-action implementation review — corrected READY - -Baseline: `de2443c2624950dfdda7fdcf98f71d2bad1d3ad3`. Reviewer: actual Claude Opus 5.5, medium requested; session `8571889e-f5be-4cbe-9a69-7ce2c72ab257`. Parent verified completed/no-error/no-permission-denial result and frozen candidate identities. Review inspection is separate from parent-run 205 tests and the five bounded real-model samples. No publication or runtime authority is conferred. - -Only `docs/command-action-evaluation.md` and the active change task introduction changed after the original review. All other 17 reviewed files were byte-identical. Parent verified the corrected manifest. Canonical archive synchronization and these evidence-only review files are subsequent closeout work, not runtime changes. - ---- - -**Verdict: READY.** Both documentation findings on the `fix/command-action-wzk` candidate are resolved, and the fix doesn't introduce a contradiction that would change the decision. I didn't recheck the corrected-manifest hashes. - -## Spec -- **Finding 1 is resolved.** `docs/command-action-evaluation.md` now opens with "Current status" (lines 3–13). That section says: - - parent accepted the source and the bounded evidence; - - all five task markers were checked after independent verification; - - publication remains unauthorized; - - the first R1 was invalid because of a harness false positive, and was neither a pass nor a product failure; - - the original copy is kept at `report-original.md`. -- Lines 15–19 label the first-attempt sections as superseded history. That covers the old "unverified", "markers remain unchecked" and "not executed" statements at lines 17, 26 and 100. -- **Finding 2 is resolved.** `tasks.md:3` now matches the `[x]` markers and keeps publication and closure as separate gates. - -## Standards/Proportionality -- The correction only touches documentation. There is no change to source, the model prompt or the evidence, and no re-evaluation. That fits a finding that was only about documentation. - -## Not blocking -- Two statements outside the superseded section still say acceptance is pending: - - **Lines 125–126:** "parent acceptance is still pending" - - **Line 210:** "Parent independent evidence acceptance remains the next gate" -- Both were accurate when the worker handed off, and the Current status section at the top takes precedence. Adding "(at worker handoff; see Current status)" to each would remove the remaining ambiguity. - -This READY applies only to whether this source candidate is ready. It isn't new host/model qualification, a reliability claim, or approval to commit, publish, activate or close. \ No newline at end of file diff --git a/docs/reviews/opus-command-action-source-wzk.md b/docs/reviews/opus-command-action-source-wzk.md deleted file mode 100644 index cc0a619..0000000 --- a/docs/reviews/opus-command-action-source-wzk.md +++ /dev/null @@ -1,58 +0,0 @@ -# Opus command-action implementation review — original REVISE - -Baseline: `de2443c2624950dfdda7fdcf98f71d2bad1d3ad3`. Reviewer: actual Claude Opus 5.5, medium requested; session `8571889e-f5be-4cbe-9a69-7ce2c72ab257`. Parent verified completed/no-error/no-permission-denial result and frozen candidate identities. Review inspection is separate from parent-run 205 tests and the five bounded real-model samples. No publication or runtime authority is conferred. - -Reviewed tracked-plus-new diff SHA-256: `0ea3ba41e4492fbbe29bc261778656d27ded1785b0af1f1f905c762e7ead339a`. The report below is retained verbatim; its documentation findings were subsequently corrected and independently rechecked. - ---- - -**Verdict for this candidate: REVISE, for documentation honesty only.** The candidate is the uncommitted `fix/command-action-wzk` branch on baseline `de2443c`: the 19-path manifest, `candidate.diff`, and installed archive `bbf30225…`. Source, guidance, tests, the spec delta and the evaluation evidence all meet the accepted plan and Matt's intent. Two committed docs state an acceptance status that the rest of the candidate contradicts. Neither fix needs a source change, test change or re-evaluation. My earlier plan verdicts stand: the first review was REVISE with F1–F3, and the recheck was READY. - -## Spec/Behavior - -**Material findings** - -1. **The evaluation report opens with an outdated status** (`docs/command-action-evaluation.md`, diff lines 487–490, 497, 570–574). Its first lines still say "Semantic acceptance remains **unverified**… No… R2–R5 sample followed" and "OpenSpec acceptance markers remain unchecked." The corrected R1–R5 results only appear after line 589. - - **Consequence:** anyone reading this committed doc from the top gets the wrong current status. That conflicts with `tasks.md` (all `[x]`) and with `parent-acceptance.json`, which accepts R1–R5. - - **Smallest fix:** add a 2–3 line current-status header. It should say: - - the first R1 was invalid, caused by a harness false positive; - - the one corrected R1–R5 run gave valid single samples; - - parent accepted the evidence, and release is not authorized. - - Retitle the original section "Superseded first attempt: invalid harness rejection." `report-original.md` already keeps the byte-for-byte copy, so the committed doc doesn't need to lead with outdated status. -2. **`tasks.md` contradicts itself** (diff line 877). The prose says "all acceptance markers remain unchecked until parent verification", but every box is `[x]`. - - **Fix:** reword it to say parent checked the markers after independent verification. - -**Checked and correct** -- **Rendering:** `src/workflows.ts` puts `Invoked command` and `Requested outcome` first. `Literal user details` appears only when text is present, so bare invocations no longer end in an empty `User request:` label. There is no parser or executor. The `diagnostics` command is unchanged. -- **F1 authority wording:** the sync, delete, import, restore, rename-prefix and compact purpose strings and `guidance.ts:37` are reconciled. Restore `--apply`, compact `--auto`/`--dolt` plus the explicit `--actor`, the concrete rename prefix, and parent acceptance are all kept. No admin action is quietly broadened. -- **F2 `--no-adopt`:** it is unconditional in the sync purpose, in CLI_REFERENCE's Synchronization section, in SKILL.md and in the spec delta. A missing remote is a blocker. -- **Resources:** all seven remaps match the plan. CLI_REFERENCE gets concise sections. WORKTREES is now a secondary link and no longer contradicts the sync guidance. The other mappings are unchanged, with 30 names and 17 links. -- **Spec delta:** the three MODIFIED requirements carry their full original scenarios plus additive ones, consistent with canonical compact/restore. -- **README and CHANGELOG:** both clearly separate unreleased source behavior from the published beta.2 archive. -- **Evidence:** - - `R1-bd-calls.json` shows exactly one `sync --no-adopt --actor=… --sandbox --json` call, exit 0, `pulled`/`pushed`, after help was inspected as a preparation step. - - R2 explained and stated that no sync was attempted. - - R3 asked for the missing issue and fields, with no writes. - - The invalid first R1 is labeled honestly and is not counted as either a pass or a product failure. - -## Standards/Proportionality -- No machinery was added. The tests check the changed contracts: every stem renders correctly whether details are empty, help text, or hostile-looking text; resources are pinned; and the installed package callbacks check bare and explain sync. The tests explicitly say fixtures don't prove model behavior. Changing the purpose check from `toBe` to `toContain` is acceptable because the full purpose is asserted through `startsWith`. -- Adding `tests/guidance.test.ts`, outside the planned test paths, is justified by the `guidance.ts` change. - -## Optional observations (not blocking) -- **Model resolved a precedence question:** in R1, `bd prime` said "local-only/no-remote… no push, pull, or remote sync". That was detected from the missing Git remote, even though the context showed a configured Dolt remote. The model chose to sync anyway. Treating the explicit invocation as taking priority matches AGENTS.md, but this was the model's judgment on a single sample, not something the guidance spells out. A deliberate project-level no-sync policy still depends on the model honoring it. -- **Actor wording:** the spec delta (line 827) says "actor identity… remain controlling". On the direct-shell path, actor attribution is guidance; only typed tools derive it deterministically. Consider adding "(host-enforced where applicable)". -- **Ambiguous sentence:** in SKILL.md (diff line 72), "a concrete migration needs the intended prefix" doesn't name rename-prefix and sits next to compact text. -- **Long descriptions:** purposes double as command descriptions, and the sync description is now about 480 characters in the picker. -- **R4 scope:** R4 tested capability that was absent from the tool inventory, not a deny issued mid-flow. Existing deterministic tests cover typed denials. -- **Scratch paths:** the evaluation doc points to scratch paths that won't last. - -## What I inspected vs. what parent ran -- **Inspected (read-only):** - - `candidate.diff` in full, including the new docs and OpenSpec files - - `manifest.json` - - baseline `src/workflows.ts`, `guidance.ts`, SKILL.md and the canonical spec - - `R1-bd-calls.json`, the R2 and R3 responses, and `parent-acceptance.json` -- **Not verified by me:** hashes, the 205 tests, typecheck, package smoke, OpenSpec validation, whitespace checks, and the R4/R5/cleanup raw files. - -READY after these two doc fixes would cover this candidate only. It is not new host/model qualification, a reliability claim, or approval to commit, publish, activate or close. \ No newline at end of file diff --git a/docs/reviews/opus-content-recheck-sol.md b/docs/reviews/opus-content-recheck-sol.md deleted file mode 100644 index a403846..0000000 --- a/docs/reviews/opus-content-recheck-sol.md +++ /dev/null @@ -1,22 +0,0 @@ -# Content correction recheck - -Original candidate: `981bfbecad58347d4af2fb4cf3c8625ddd56774c`; original report published at `dd1edc192dd087ac625c4c16728e0b8860855f2b`. This report covers the uncommitted Sol correction delta over dd1edc1, subsequently published together with this report. Reviewer `claude:oc-content`, existing session `77b30a82-e681-4cf8-a138-95199707f49a`, explicit Opus 5.5 medium. No runtime qualification or implementation beyond content is implied. - -# Delta recheck of review opencode-beads-8rl (content corrections on `dd1edc1`): **READY** - -**Reviewer:** claude:oc-content - -All four original findings (M1–M4) are fixed. The corrections introduced no new material defects. I checked the flags the new examples use against the 1.3.1 source. - -| Finding | Status | Evidence | -| --- | --- | --- | -| **M1** Actor examples and shell safety | Resolved | Every `--actor` in the corpus is now the quoted `'<executor-actor>'`. The one exception is the human gate step, which uses `'<actual-human-actor>'`. No `codex:` or `9c2e1` remains. In shell examples every placeholder is quoted (`SKILL.md:41-42,68,87-89`, `MOLECULES.md:31-49`, `WORKFLOWS.md:26`, `DEPENDENCIES.md:41-48`). `SKILL.md:45-48` says to use the actor from your assignment and to ask if none was given. It mentions `opencode:<suffix>` only as an illustration in prose. `ASYNC_GATES.md:42-48` now says the human runs the resolve command and that an agent must never supply a human actor. `SKILL.md:97-98` now explains that the examples include `--sandbox` because of project policy. | -| **M2** Dependency direction and readback | Resolved | `DEPENDENCIES.md:36-51` adds the rule "X needs Y means X depends on Y" and the `bd dep add '<dependent-id>' '<prerequisite-id>'` form. It adds a wrong/right Phase 1/Phase 2 example and readback through `bd blocked` and `bd dep list`. It notes that `dep list` defaults to showing dependencies, which matches `dep.go:254,905` and `ready.go:298`. | -| **M3** Recovery entry point | Resolved | `RESUMABILITY.md:61-76` adds a cold-start/compaction sequence: `bd list --status=in_progress --assignee='<executor-actor>' --json`, then `bd show '<issue-id>' --long --json`. It says to recover assigned work rather than take new work from `bd ready`, and that an empty list does not permit claiming another task. Then read the latest checkpoint and verify state before acting. The flags exist in the source (`list.go:402`, `show.go:300`). `SKILL.md:83-84` also adds the warning that reusing a memory key replaces it in place. | -| **M4** OpenSpec presented as universal | Resolved | `SKILL.md:17-18`, `BOUNDARIES.md:17` and `INTEGRATION_PATTERNS.md:10,37,64` now refer to "the project's specification system (for example OpenSpec, when used)". `INTEGRATION_PATTERNS.md:21-25` labels the planning/review Bead pattern as a project-policy example, not a universal Beads requirement. | - -**Regression tests:** The four new tests (`tests/workflows.test.ts:164-208`) check these properties directly: neutral quoted actors, no unquoted angle brackets in shell blocks, the dependency examples, recovery and memory-key wording, and the conditional specification wording. I did not run them. - -**No remaining correction is required.** The only thing I'd tidy is cosmetic: `ASYNC_GATES.md:50` is one unwrapped long line. - -**Limits:** This was a static, read-only recheck covering M1–M4 only. I didn't run tests or `bd`, and I have no runtime, packaging or model-behavior evidence. CLI checks are against the scratch tree whose CHANGELOG shows 1.3.1, not the installed binary. Tracking, publication and closure stay with the parent. diff --git a/docs/reviews/opus-content-review-981bfbe.md b/docs/reviews/opus-content-review-981bfbe.md deleted file mode 100644 index 073b927..0000000 --- a/docs/reviews/opus-content-review-981bfbe.md +++ /dev/null @@ -1,119 +0,0 @@ -# Independent guidance content review - -Candidate: `981bfbecad58347d4af2fb4cf3c8625ddd56774c`; review Bead `opencode-beads-8rl`; actor `claude:oc-content`; session `77b30a82-e681-4cf8-a138-95199707f49a`. Actual model `claude-opus-5-5`, medium effort explicitly requested. Completed without permission denials. Findings are not represented as corrected. - -# Content-quality review: `oc-beads` guidance corpus at `981bfbe` - -**Reviewer:** claude:oc-content · **Bead:** opencode-beads-8rl · **Verdict: REVISE** - -The corpus mostly keeps the useful depth of the Claude reference rather than shrinking it to filenames and generic warnings. Four content-only problems stand in the way of READY. Two of them are in the material agents will actually copy, and one is in the project's own core attribution rule. - -## Material issues (smallest fix for each) - -**M1. The actor examples will misattribute OpenCode work, and several aren't shell-safe.** -- **Where:** - - `SKILL.md:40,41,64,84`, `WORKFLOWS.md:26` and `ISSUE_CREATION.md:40` use `--actor=codex:<short-session>` with no quotes. - - `MOLECULES.md:32,42,49` use the literal `--actor=codex:9c2e1`. - - `ASYNC_GATES.md`, `DEPENDENCIES.md` and `INTEGRATION_PATTERNS.md` quote the same actor. So the quoting is inconsistent, and every example uses the `codex:` prefix. -- **What goes wrong:** - - This is an OpenCode skill. An OpenCode executor that copies the central example records itself as `codex:…`. That is exactly the misattribution `AGENTS.md` forbids. - - `codex:9c2e1` is the sample ID from this project's own policy. Copied literally, it attributes work to an actor that looks real. - - Without quotes, bash reads `<short-session>` as a redirection. The command fails on a missing file, or, if a file named `short-session` exists, it creates or truncates a file named `--sandbox`. Either way it doesn't run as intended. -- **Fix:** Use one quoted, host-neutral placeholder everywhere, e.g. `--actor='<executor-actor>'`. Add one sentence to `SKILL.md`: "use the actor named in your assignment (e.g. `opencode:<suffix>`); if none was given, ask rather than invent one or copy an example." Replace `codex:9c2e1` with that placeholder. - -**M2. Dependency direction is explained only for `bd create --deps`. Nothing covers adding edges afterwards or checking the result.** -- **Where:** - - `DEPENDENCIES.md:5-8` defers to `bd dep --help`, and lines 55-56/64 say "read the graph back" without saying how. - - No asset mentions `dep add`, `bd blocked`, `dep tree` or `dep list` (searched the whole corpus). - - Upstream has the material this replaces: `DEPENDENCIES.md:126-131` and 613-631 (`bd dep add <dependent> <prerequisite>`, a wrong/right example and a mnemonic), and `WORKFLOWS.md:147-256` (the "Phase 1 before Phase 2" inversion trap, walking backward from the goal, and checking with `bd blocked`). - - 1.3.1 source confirms the semantics: `dep.go:254,264` is `add [issue-id] [depends-on-id]`, and `ready.go:298` has `blocked`. -- **What goes wrong:** Inverting edges is the most common Beads graph mistake. An agent wiring up an existing epic has no worked mechanics and no way to check, so `bd ready` ends up offering dependents before their prerequisites. The parent's earlier rejection named "worked graph examples"; only the diamond and the create-time example came back. -- **Fix:** About 10–12 lines in `DEPENDENCIES.md`: - - "X needs Y → `bd dep add X Y`", with one wrong/right pair. - - The two-line phase trap. - - A check step: `bd blocked` / `bd dep list <id>` should show each task blocked by its prerequisites, never by its dependents. - - The backward goal walk can stay a 5-line sketch. - -**M3. The resume and recovery path never shows how to find the active work.** -- **Where:** - - `RESUMABILITY.md:59-64` says "Read the active issue and its recent notes", and `PATTERNS.md:18-23` is similar. - - No asset contains `in_progress`, `bd list`, `bd show`, `bd ready` or `bd close`. - - Upstream `SKILL.md:84` ("Recover after compaction: `bd list --status in_progress` → `bd show <id> --long`") and `PATTERNS.md:213-235` keep this even under their own ADR-0001. -- **What goes wrong:** After compaction or a cold start, which is exactly when an agent opens this skill, it has the checkpoint format but no entry point. It may then guess, re-run `bd ready` and claim new work instead of resuming its own. -- **Fix:** Add a 3–4 line recovery sequence to `RESUMABILITY.md`: - - List in-progress work, filtered to your actor or assignee where help supports it. - - `bd show <id>`. - - Read the latest appended checkpoint. - - Re-check state before acting. - - Optionally add one line pairing closure with `--reason` and a `RESOLUTION:` note in `PATTERNS.md`. Three core verb forms are not the broad flag catalog that ADR-0001 excludes. - -**M4. OpenSpec is presented as a universal Beads requirement in a public plugin.** -- **Where:** `SKILL.md:17-18` (stated outright), the `BOUNDARIES.md:17` row, the `INTEGRATION_PATTERNS.md:10` table, and the planning/review Bead model at lines 21-35. -- **What goes wrong:** Users without OpenSpec are told their intended behavior "is" OpenSpec, and may conclude they need it or create planning and review Beads by default. The inventory's INTEGRATION_PATTERNS mapping does say "map planning to OpenSpec", but the settled goal is to avoid presenting that as universal. -- **Fix:** Make it conditional, e.g. "the project's specification system (for example OpenSpec, when used)". Label the planning/review Bead pattern as one project policy example, not a Beads rule. - -## Missing guidance vs intentional adaptation - -**Intentional adaptations I accept** (they are not omissions): -- `TodoWrite` becomes an optional, host-owned, experimental todo. -- MCP tool examples are removed. -- Upstream's "overwrite notes" rule is replaced by append-only checkpoints, explicitly attributed at `WORKFLOWS.md:3`. -- The approve-every-handoff loops are removed. -- Stale v0.15 and Dolt-server repair recipes are dropped. -- The `.beads-wisp/` storage table and the static CLI catalog are dropped. -- The "epic if 5+ tasks" heuristic is dropped. -- Agent/slot: verified that 1.3.1 `cmd/bd` has no `agent` or `slot` command. `AGENTS.md:18-35` explains the limit honestly and offers no false equivalent. - -**Missing important guidance:** only M2 and M3. - -## Accuracy checks against the 1.3.1 source (all passed) - -- `--actor` and `--sandbox` are global flags (`main.go:875,879`). `--sandbox` only disables Dolt auto-push. -- `--append-notes` exists (`flags.go:34`). -- `bd heartbeat` runs as the current actor, and only the owner may heartbeat (`heartbeat.go`). -- Memory commands: `memories`, `recall` and `remember --key` exist; an existing key is updated in place (`memory.go:487`). -- The `--deps` direction text matches `create.go:936`. -- Gates: - - `create` accepts human, timer, `gh:run` and `gh:pr`, not `bead` (`gate.go:1283`). `check` accepts `bead` (`gate.go:1276`). So `ASYNC_GATES.md:21-26` is accurate. - - `resolve --reason` exists. -- Molecules: `bd mol wisp create --var` is valid (wisp is registered under `mol`, `wisp.go:1022`), as are `mol squash --summary`, `mol burn` and `mol show`. - -## Nonblocking improvements - -- **`--sandbox`:** Every example includes it, but `SKILL.md:90` says it applies only where auto-push is prohibited. Say once that the examples assume that policy. -- **Memory keys:** Add "recall before reusing a key; same key replaces in place". This protects other agents' knowledge. -- **2-week test:** Bring back upstream's one-line "Could I resume this after 2 weeks away?" heuristic in `BOUNDARIES.md`. It is a sharper decision aid than the table alone. -- **Human gate example:** In `ASYNC_GATES.md:43-44`, say that the human runs the resolve command; an agent must never type a human's actor. -- **Wisp cleanup:** Add one line: leftover wisps can be found with `bd mol wisp list` and should not pile up (upstream `CHEMISTRY_PATTERNS.md:192`). -- **TROUBLESHOOTING:** - - Name what the human can run, without running it. For example, a missing store means the owner may run `bd init`; `bd doctor` is a diagnostic, but whether it is read-only without a fix flag is unverified. - - Keep the cloud-synced-folder I/O hint. - - As written, "ask the owner" doesn't help the agent tell the owner what to do. -- **Ask first or create directly:** Within authority, keep the heuristic: fuzzy or strategic work → ask; possible duplicate → `bd search` first. -- **Repetition:** The authority, actor and no-automation caveats are restated in almost every file. That's tolerable for files loaded on demand, but `MOLECULES.md:57-66` repeats itself within the same file. - -## Completeness and quality by file group - -- **Main skill:** Lean, with strong policy: scope, atomic claims, `created_by`/`owner`/`assignee`, handoff and stop rules. It separates notes from memory well. The examples defect (M1) is the main problem. -- **Core resources:** - - `RESUMABILITY.md` (before/after example and template), `ISSUE_CREATION.md` (parser design-vs-acceptance example) and `BOUNDARIES.md` (transition example) carry real decision aids. - - `PATTERNS.md` keeps failed approaches and the rejected-hypothesis rationale. - - `DEPENDENCIES.md` keeps the meaning of each relation but lacks the mechanics and the check step (M2). - - `WORKFLOWS.md` has good checkpoint triggers but lost epic planning and unblocking. - - `TROUBLESHOOTING.md` is honest but thin. - - `CLI_REFERENCE.md` is appropriately minimal under the ADR. -- **Advanced resources:** - - `ASYNC_GATES.md` is the strongest file and accurate. - - `MOLECULES.md` and `CHEMISTRY_PATTERNS.md` are adequate, with a decision matrix and squash/burn lifecycle. - - `AGENTS.md` is honest. - - `STATIC_DATA.md` and `WORKTREES.md` are short but enough. -- **Attribution:** Every file has a commit-pinned upstream link, and TROUBLESHOOTING is correctly labelled a replacement. - -## Evidence limits - -- **Static review only:** read-only, no live `bd` help, no host or runtime run, no model-behavior evidence. -- **Source identity:** I checked CLI syntax against `/opt/data/cache/scratch/parity-sources/beads/cmd/bd`, whose CHANGELOG top entry is 1.3.1. I did not confirm it is the exact tagged commit or the installed binary. -- **Asset claims of "installed help confirms…"** were checked against that source, not re-run. -- **No delivery claim:** Nothing here shows the files are discoverable at runtime or improve agent behavior. -- **Tracking:** I made no `bd` calls and wrote no files. Tracking updates on opencode-beads-8rl are left to the parent. diff --git a/docs/reviews/opus-epic-map-review-vuy.md b/docs/reviews/opus-epic-map-review-vuy.md deleted file mode 100644 index b6e2d14..0000000 --- a/docs/reviews/opus-epic-map-review-vuy.md +++ /dev/null @@ -1,36 +0,0 @@ -# Epic map cross-check — opencode-beads-vuy - -Planning baseline: `84ab18e76be43f9a733bd799c5a506fed03ce7f6`. Actual model verified: `claude-opus-5-5`; medium effort explicitly requested. Review is read-only and covers the created records before publication, not runtime qualification. - -**READY.** I found no material mapping defects and no corrections are needed. - -## Verdict on each check - -- **13 tasks, each owned exactly once.** The `metadata.task_ids` in the parent readback matches the execution map and `task_owners`: .1→1.2, .2→1.1, .3→2.1, .4→3.1/3.2, .5→2.2/3.3, .6→4.1/4.2, .7→5.1, .8→6.1, .9→6.2/6.3. That's 13 IDs with no duplicates or gaps. -- **17 requirements covered.** The `requirement_coverage` in the check results matches the reconciliation table at `reconciliation.md:39-55` row by row, with the same task IDs. The owners follow correctly from the task owners. -- **Dependency order and cycles.** The `blocks` edges in the readback are exactly .2→.1; .4→.1; .5→.1/.3/.4; .6→.3/.4/.5; .8→.5/.7; .9→.2/.5/.6/.8. These match the map. There's also .8→.6 as `related` (readback line 1011), not a blocking edge. The graph orders cleanly as {.1,.3,.7} → {.2,.4} → .5 → {.6,.8} → .9, so there are no cycles. Every prerequisite in tasks.md is satisfied directly or through another child. -- **The live 2.0.32 host prerequisite blocks only live work.** .3, .7 and .1 have no edges at all. .4 and .5 have no edge to .2. Their phase boundaries say they deliver source and fixtures only, and that the 1.1 activation step and the 6.2 end-to-end acceptance remain open. Nothing claims a closed source child means the feature is live. -- **The .6 partial phase is explicit in the records themselves, not just the map:** - - .6 description, design, acceptance and metadata all say: "owns ALL of 4.2 and stays open until live checks pass", in the order 4.1, then the 4.2 fixtures, then the 4.2 live checks after 1.1. - - The `deterministic_handoff` metadata records `state: not_started`, `live_prerequisite: opencode-beads-vuy.2` and `completion_requires_live: true`. - - The .6 notes require the tested source revision, the fixture commands and results, and an explicit list of pending live checks. The parent verifies these before dispatching .8. Relevant source edits invalidate the evidence. -- **.8 waits on the .6 evidence without waiting for .6 to close.** Its description and acceptance say to consume the passing 4.2 fixture evidence and "Do NOT wait for that child to close or for 1.1/4.2 live checks." It also says to record the tested revision and invalidate the evidence if relevant source changes. -- **.9 has real blocking edges** on .2, .5, .6 and .8. Because .6 only closes after its live checks, .9 correctly waits for all of 4.2. -- **Nothing is marked done early or dispatched automatically.** All 10 records are `blocked`, have `implementation_authorized=false` and carry the `execution-not-authorized` label. The only `assignee` in the readback belongs to d9n (`Snarkimedes`), which is the planning record, not one of the new ones. Every description says "dependency-ready never means authorized". The handoff state is not_started with no evidence, and all 13 OpenSpec task checkboxes are still unchecked. -- **Splitting into nine children is reasonable.** The groupings (continuity, package, flow, acceptance) follow the order the tasks have to run in. I see no harmful fragmentation. - -## Minor nits (none block) - -1. **The handoff state is stored twice.** The `deterministic_handoff` JSON is copied into both the .6 and .8 metadata, so the two copies could drift apart. Treat .6 as the single source of truth and have .8 point to it, or at least update both together. -2. **Graph readiness for .8 doesn't reflect the .6 gate.** Once .5 and .7 close, .8 will look ready even if the .6 evidence hasn't been verified. The blocked status and the notes cover this, but the parent shouldn't move .8 to open just because the graph says it's ready. -3. **One redundant edge.** .9→.5 is already implied through .6 and .8. It's harmless and makes the 2.2 activation dependency explicit. - -## Evidence limitations - -- I read the parent readback for .6, .8 and .9 in full. For the other children I only scanned status, `implementation_authorized`, task IDs and dependencies. I relied on the results file for their phase boundaries. -- I didn't check that every child's `requirement_contributions` matches the coverage table, apart from .6, .8 and .9. -- I didn't open the records snapshot separately from the readback. -- The lint and validation passes are the reported results in the check file; I didn't rerun them. -- No runtime or behaviour qualification is being claimed. - -I made no writes, ran no `bd` commands and launched no agents. You asked for findings in this response only, so I didn't create a plan file or call ExitPlanMode. diff --git a/docs/reviews/opus-flow-source-review-vuy6.md b/docs/reviews/opus-flow-source-review-vuy6.md deleted file mode 100644 index d5ee6b5..0000000 --- a/docs/reviews/opus-flow-source-review-vuy6.md +++ /dev/null @@ -1,67 +0,0 @@ -# Opus scope-bounded flow source review - -Baseline: `db3b65ee86ad02d363baf9cbf24511a15d7bb644` plus the unchanged 10-path uncommitted candidate. -Reviewer: `claude:oc-flow-review`, Claude Opus 5.5, requested effort medium. -Session: `c76548d8-0fad-4278-b9b7-1f434284391e`; review record `opencode-beads-8ri`. -Result: completed, is_error=false, no permission denials; actual modelUsage confirms claude-opus-5-5. -Parent verified all reviewed candidate hashes unchanged before retaining this result. -Scope: task 4.1 source and 4.2 deterministic contribution only; no live qualification. - -**Verdict: READY** for the 4.1 source and the 4.2 deterministic contribution. This does not cover live qualification. Task 4.2 should stay unchecked and `.6` should stay open. - -I only read files; I ran no tests. I checked the candidate diff against the 4.1/4.2 text in `tasks.md:25-26`, `AGENTS.md:31-44`, the current `src/guidance.ts`, `src/host.ts:338-379`, and the pinned `baseline211/.../subagent.ts:234-268`. I did not recompute the manifest hashes, so the parent still needs to confirm the candidate is unchanged before accepting. - -### Standards findings -None of these block acceptance. - -- **`src/guidance.ts:84` and `src/guidance.ts:64`:** the task agent gets the executor/ownership section twice, once in its system prompt and again in the injected `beadsGuidance("task-agent")`. The copies are identical, so nothing contradicts. The prompt copy is still needed when prime fails, so I don't think it's worth changing. If you want to trim it, you could drop the section from the injected task-agent guidance only, but that's optional. -- **`tests/host.test.ts:410-411`:** the value import and the type import from `../src/continuity` are on separate lines. That's style only. -- **The parent's assertion fixes are not weakened:** - - `scripts/test-package.ts:331-339` replaces the 1,000-character limit and the old claim string with five specific positive checks. It also adds a negative check against the old "otherwise choose one highest-priority ready bead" fallback. - - `tests/docs.test.ts:189, 232-237` now checks the new README wording. - - Neither file has a placeholder or a check that always passes. I don't see a reason for a new character limit. - -### Spec findings -**4.1 (`src/guidance.ts:13-31, 51-66`): no material gaps.** -- **Exact assignment:** stops without substitution. -- **Single operation:** does not authorize a claim. The prompt also says "Readiness is not dispatch permission". -- **Batch/goal:** continues only within the scope and acceptance gates already granted. -- **Claims:** atomic, using an actor placeholder, with readback and a stop on failure. -- **Discovery:** does not add authority. -- **Read-only analysis:** makes no mutations. -- **Stops:** cover denial, cancellation, and a pending permission wait. Unresolved acceptance stays incomplete. -- **Closure:** when the parent owns closure, the bead is left open. -- **Delegation:** the old command-count rule is gone. Delegation is normal blocking delegation, with no background or nested automation. -- **Identity:** `created_by`, `owner` and `assignee` are read back separately. Handoffs are deliberate, and planning/review items are bounded with no ticket per retry. -- **Other features unchanged:** Luna, the step caps, cap `0` and the agent IDs are untouched (`src/agents.ts:11,48`; `tests/agents.test.ts:33-44`). -- **Instructions don't conflict:** the old one-bead/ready-selection text appears nowhere in `src/`. The README (lines 26-28) correctly says this is guidance, not enforcement. - -**Non-blocking observation:** `guidance.ts:47` says typed writes derive the actor from the session and agent. `guidance.ts:29` tells the agent to use the actor supplied by the invocation or handoff. Once typed continuity is turned on, a worker could claim under one actor and checkpoint under another. Activation is withheld today, so this belongs in the live 1.1/4.2 checks, not as a source fix now. - -**4.2 deterministic: the payloads match the pinned 2.1.1 source.** -- Failed and cancelled children are `status:"error"`, and their messages match `subagent.ts:247-251`. -- NO_TEXT is a completed result. Its `output`/`content`/`metadata` shape matches lines 252-264. -- No fixture invents a `cancelled` status for the after-hook. - -**The tests check what the docs say they check:** -- **No restart:** the plugin never calls `prompt` or `synthetic` and never writes to the store. -- **Child outcomes:** the after-hook only invalidates context and sets a recovery cue for the next request (`host.ts:350-355`). The child's cache stays isolated. -- **Late child result:** after interruption it keeps the "no final checkpoint" note (`host.ts:372`). Callbacks after unload do nothing. -- **Fork:** the fork starts without the parent's references (`host.ts:365`). -- **Permission wait:** a pending permission does no write during compaction. Aborting it rejects, and a later approval does not run the write. -- **Actors:** each checkpoint records the actor of the invocation that made it, and the permission check uses that invocation's agent. - -`src/host.ts` is unchanged, and I'm not asking for any repair of the plugin, transport or upstream Beads. - -**Is the evidence mapping honest? Yes.** The table in `docs/opencode-native-parity-assessment.md:99-109` names what is not proved for every row. That includes: no child is actually launched, mock notifications prove nothing about host suppression, the store is an in-memory fixture, and fork remapping and provider replay are not exercised. The doc keeps the earlier 159-pass/1-fail run and the package failure, then records the parent's 160/0 run as superseding them. It also discloses that there is no final-checkpoint guarantee and labels the earlier unpinned `.5` evidence as such. - -### Live work still not done -Live 4.2 has not been run, and it needs the separately authorized live 1.1 first. That means: -- no installed 2.1.1 host -- no real child or claim -- no permission UI or saved-grant checks -- no retained-history, fork or provider-mismatch checks -- no long-running transport observation -- no verification that the model actually follows the guidance - -Nothing in this candidate supports checking 4.2, closing `.6`, dispatching `.8`, activating anything, or releasing. Before accepting, the parent should record the actual model, session and verdict, and confirm the candidate is unchanged. diff --git a/docs/reviews/opus-integration-closeout-vuy8.md b/docs/reviews/opus-integration-closeout-vuy8.md deleted file mode 100644 index 921a4a3..0000000 --- a/docs/reviews/opus-integration-closeout-vuy8.md +++ /dev/null @@ -1,40 +0,0 @@ -# Opus closeout review — vuy.8 / task 6.1 - -## Identity and candidate - -- Reviewer: `claude:oc-integration-review`, actual model `claude-opus-5-5`; requested effort Medium. -- Reviewer session: `00503bba-2d4c-4fd9-a704-404d53276abc`. -- Review record: `opencode-beads-9hd`; implementation owner remains `opencode-beads-vuy.8`. -- Baseline: `c7d2129584365764b2ea65d50007244cebeb1f6a`; exact uncommitted candidate is the 12-path manifest at `/opt/data/cache/scratch/vuy8-opus-closeout/manifest.json`, with tracked delta `candidate.diff` and both new evidence documents explicitly included. -- Parent verified all 12 hashes unchanged after review. This report is an evidence-only addition, not a source correction or a new reviewed runtime candidate. -- Raw review stream: `/opt/data/cache/scratch/vuy8-opus-closeout/review.jsonl`; stderr retained beside it. - -## Verdict - -**READY. No required corrections.** - -The reviewer concluded that the frozen candidate supports task 6.1 local acceptance. Publication and closeout remain parent-authorized actions; live qualification remains open. This is the independent source/evidence verdict, separate from the earlier parent acceptance. - -## Standards - -**No material source or test issues.** The reviewer checked: - -- `src/guard.ts:36–51`: only the supported process-error exit/text/schema combination becomes absence, before marker access; other failures remain probe failures. No `where` fallback or store read. Positive/negative tests and the supplied actual CLI result support the distinction. -- `src/continuity.ts:100–108`: known numeric schema-1 metadata is removed from a copied map; actual string memory values are retained. Legacy and versioned empty/populated maps are accepted; unsupported numeric versions/non-string fields remain rejected. Production parsing, not merely test normalization, was corrected. -- `scripts/bd-contract.ts`: explicit sandbox/actor, real append acknowledgement plus readback, audit/claim identity, empty-write rejection, missing recall, remember/update/recall and exact versioned list/search payload checks. No invented commit fields, store injection, permission expansion or retry mechanism. - -## Spec - -**No material gaps or false claims against task 6.1.** Exact tool versions and supplied passing deterministic/package/CLI evidence are recorded. The original `.6` immutable review is not claimed to review the new guard/parser fixes; relevant current fixtures were rerun. Earlier failed phases are retained as history, while the final parent verdict is explicit. The nine-of-thirteen local task ledger and validator agree; tasks 1.1, 4.2, 6.2 and 6.3 remain unchecked. The two approved future live cases preserve task ownership and authority boundaries without new tasks or a host test framework. - -## Nonblocking observations and disposition - -1. The raw CLI memory envelope is not passed through the production acknowledgement path by the contract script itself; that link is covered by the unit regression. Reviewer explicitly stated this does not block 6.1. Retain as an optional refinement, not a new acceptance gate. -2. Supported/replaced administration was checked by help/source rather than destructive contract operations. Reviewer accepted this as consistent with the touched-semantics scope and disclosed limitation. No administrative mutation is added. -3. The old `execution-not-authorized` label is stale closeout bookkeeping. Current `implementation_authorized=false` intentionally means no further worker execution while publication is gated, not that the performed work lacked owner approval. Preserve historical grants and clarify current state in `.8` rather than re-enable execution. - -The raw result also contains an unrelated connector-availability notice. It has no bearing on this review and does not authorize connector setup or other work. - -## Verified review limits - -Parent verified `is_error=false`, `terminal_reason=completed`, actual `modelUsage` for `claude-opus-5-5`, no permission denials and no spawned subagents. Only Read/Grep/Glob were available. The reviewer did not execute tests, CLI commands or validators; it inspected source and supplied parent logs, including the final real-CLI log and execution index. It did not qualify installed OpenCode permissions, cancellation, lifecycle, model behavior or activation. No source remediation or repeated broad review is required by this verdict. diff --git a/docs/reviews/opus-planning-review-50919ae.md b/docs/reviews/opus-planning-review-50919ae.md deleted file mode 100644 index 2013c84..0000000 --- a/docs/reviews/opus-planning-review-50919ae.md +++ /dev/null @@ -1,113 +0,0 @@ -# Independent review of planning candidate `50919ae` (branch `openspec/improve-beads-workflow-parity`) - -Attribution: supplied independent Claude review of `50919ae0f6b192bb8c2773398685c550fdaad22f`; trace model `claude-opus-5-5`. The parent reports an explicit medium invocation; effort was not introspectable by the reviewer. Original verdict and review substance are retained below, including its source interpretation; the planning agent’s corrections are recorded separately in [reconciliation](../../openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md). Only the unrelated connector-advertisement footer is omitted. - -## Verdict: **REVISE** - -There is one small blocking finding. It affects task ordering and a missing prerequisite, not the design. Everything else is ready to map. Once tasks 1.1 and 1.2 are re-sequenced and the host prerequisite is stated, I would accept the package for epic mapping without another full review. - -HEAD is `50919ae0f6b192bb8c2773398685c550fdaad22f`. I left the `AGENTS.md` change, `.codex/` and `.claude/settings.local.json` alone and did not count them as part of the candidate. I made no edits, ran no `bd` commands, wrote no plan file, ran no product tests and started no host or model. - -## Blocking finding - -### B1 — Medium-high: task 1.1, the first gate, can't run as ordered, and it needs a host that isn't installed - -**Evidence** -- **The gate order:** - - `tasks.md:7` (1.1) qualifies the 2.0.32 permission surfaces using fixtures in `tests/continuity.test.ts`. It runs "before adapter activation". - - `tasks.md:8` (1.2) changes the dependency to `>=2.0.32 <3` and only runs "After 1.1". - - `design.md:39` says 1.1 "must precede N1 activation". -- **The pinned typings don't have the API 1.1 tests:** - - `package.json` pins `devDependencies["@opencode/plugin"]` to `2.0.26` (the lockfile matches). - - `permission.assert` exists in `npm32/package/dist/promise/permission.d.ts:28` but not in the 2.0.26 typings. - - So 1.1's fixtures can't typecheck until 1.2 lands, and 1.2 is ordered after 1.1. -- **1.1 duplicates 3.1:** the adapter 1.1 would exercise is written in 3.1 (`tasks.md:17`, "After 1.1–1.2"). The two tasks list the same checks: invocation agent, allow/ask/reject, held access and cancellation after approval. -- **Fake-host fixtures can't prove host behavior:** the existing tests fake only a small slice of the host context (`docs/opencode-sdk-contract.md:38`). They can show the plugin sets `options.permission`. They can't show that the host's `Tool.snapshot` filters on it (`core/src/tool.ts:231`), and they can't check whether the host accepts `oc-beads:ready`. -- **The installed runtime is below the selected minimum:** - - The OpenCode on PATH is `@opencode/cli` **2.0.29** (`/opt/hermes/image-toolchain/npm/node_modules/@opencode/cli/package.json`). I read that file and did not run the binary. - - Live-host checks in 1.1, 4.2 ("installed-host checks") and 6.2 all need a host at 2.0.32 or later. - - `owner-decisions.md:25` keeps runtime upgrades separately gated, and no artifact declares this prerequisite. - -**Failure if mapped as-is** -- The epic's first ready bead would be blocked by its own successor. -- The 1.1 and 3.1 beads would duplicate each other. -- Every installed-host gate would hit an undeclared need for runtime-upgrade authority partway through execution. - -**Smallest correction (edit `tasks.md`; mirror it in the `reconciliation.md` requirement table)** -1. Make 1.2's dependency/typing edit the first step, or merge it into the start of 1.1. It still needs dependency-edit authority. -2. Restate 1.1 as host-contract qualification only. Use a minimal throwaway probe tool and command on an OpenCode 2.0.32+ host, and record the results in `docs/opencode-sdk-contract.md`. -3. Move the adapter-specific fixture items into 3.1. -4. Add an explicit prerequisite to 1.1, 4.2 and 6.2. Either provide an isolated, disposable OpenCode 2.0.32+ install that leaves the operator's 2.0.29 runtime untouched, or get explicit authority to upgrade the runtime. If neither exists, stop and report it. - -## Nonblocking recommendations - -1. **Command collisions — the gate is likely to trip; plan the fallback the spec already allows.** - - In the released supervisor, package plugins activate after the config plugins (`core/src/plugin/supervisor.ts:29,37`). The command editor only has `add`, which is a plain `Map.set` (`core/src/command.ts`). - - So a user command with the same name, present at load, can be detected through `ctx.command.list()` and skipped. One added later is overwritten when commands are rebuilt, and the package can't see that happen. - - `design.md:31` and `tasks.md:13` say "stop registration". The spec (`workflow-access/spec.md:57-59`) also allows "documented override behavior". - - Recommendation: scope the stop to the colliding name only. Document that rebuilds shadow later-added same-name overrides, and have `oc-beads:status` report it. - - Skills don't have this problem: the skill editor has `get` and `list`, so the `oc-beads` skill can be checked during every rebuild. - -2. **Skill resources: link all 16 files explicitly from `SKILL.md`.** - - `Skill.prepare` lists only the first 10 sorted files (`core/src/skill.ts:55-62`). With the ADR plus 15 resources, the sorted cutoff drops `PATTERNS`, `RESUMABILITY`, `STATIC_DATA`, `TROUBLESHOOTING`, `WORKFLOWS` and `WORKTREES`. - - The resources sit in the npm cache, outside the project. They are readable by default (`permissions.mdx:142-145`), but a user rule such as `external_directory: ask` or `deny` would prompt or block. - - Add one fixture and an acceptance case to 2.2 and 6.2 that reports an unreachable resource honestly. - -3. **Saved approvals for the typed tool: state the intended outcome in 1.1.** - - With `save: []`, an "always" reply works only once (`core/src/permission.ts:299-305`). Users with an `ask` rule will be prompted on every checkpoint. - - The built-in shell tool saves `bd *` for any `bd` command, because `bd` has no arity entry (`core/src/shell/parse.ts:375-380`). - - Saved rules apply to the whole project and are checked after deny rules (`permission.ts:176`). So an existing shell `bd *` grant will also authorize the typed operations. That matches what the shell does, and is not a broader grant. - - The plan's narrower choice is defensible. 1.1 should list these as expected results, and the guidance should say that "always" on a typed prompt is not saved. - -4. **Drift alerts need to fail the check.** GitHub notifies people about failed scheduled runs, not successful ones. Task 5.1 should say that unreviewed drift fails a separate job or step, the same way the existing review step does (`beads-contract.yml:57-65`). Drift and retrieval failure should produce distinct `::error::` messages. Otherwise "visible in check output" means nobody sees it. - -5. **Drop the 5.1 → 1.1 dependency.** The drift script doesn't depend on N1 qualification. Removing the edge lets 5.1 run in parallel. - -6. **Release branch strategy.** Stable releases are cut from `main` through PRs. Before 1.2 merges (raising the peer range to 2.0.32+), the epic should note where stable 1.0.x fixes will come from. This is a release decision, not a planning defect. - -## Prior findings F1–F5 - -| Finding | Status | What I checked | -| --- | --- | --- | -| F1 | **Resolved** | See detail below. | -| F2 | **Resolved in design** | `options.permission` is part of the released `Tool.Options`; `ToolContext` carries `agent`, `signal`, `messageID` and the call `id`; `configured` resolves `agentID ?? session.agent`; external access can be checked with the public `permission.assert({action: "external_directory"})`, which matches `file-access.ts:125-141`. One nuance remains, recommendation 3. | -| F3 | **Resolved** | Compaction is reference-only (`design.md:49`, `work-continuity/spec.md:76-80`, task 3.2 verifies no writes, waits or recursion). Some scenario wording still says "prepared", which is harmless. | -| F4 | **Resolved** | The alert reuses the existing `contents: read` check, with no issues and no issue-write permission. The upstream-review spec, `design.md:63`, task 5.1 and the artifact policy all agree. See recommendation 4. | -| F5 | **Resolved** | The analysis says "all three capability deltas" (line 181), its command and skill doc links use `843a6c5`, and no freeze-marker or tracker history remains in the tasks. | - -**F1 detail** -- The installed cache matches marketplace-main `4a67d0d` byte for byte, apart from a `.in_use` marker file. -- Release `c1c4b64` → main differs by exactly 16 edited files and 1 added file (`plugins/beads/BUILD.bazel`), with no deletions. That one addition is the whole 73 → 74 difference. -- Five guidance files now use `--append-notes` instead of `--notes`: skill `README.md`, `WORKFLOWS`, `PATTERNS`, `INTEGRATION_PATTERNS` and `ISSUE_CREATION`. -- `WORKFLOWS.md:368` still says "overwrite previous notes, not append". The inventory mapping flags this for the adaptation. -- On drift, the reviewed baseline is `marketplace_main.commit`, and only an explicit human disposition advances it. - -## Coverage and proportionality - -- **Requirements:** all 17 normative requirements (6 work-continuity, 8 workflow-access, 3 upstream-review) match the reconciliation table by title. I checked this by hand, not just through the validator. -- **Tasks:** 13 unique tasks. -- **Corpus:** all 74 marketplace-main members have a disposition, a group, a target and task IDs. The 29 commands map to `oc-beads:<stem>`, plus `oc-beads:status`. The 15 resources and the ADR map to `assets/oc-beads/`. The shared `beads` skill is preserved, and host-specific and support files are reference-only. -- **Native API claims:** these hold against released 2.0.32 source — tool filtering, invocation identity, the assertion schema, colon names in the command schema, absolute skill paths, and hooks awaited with no timeout. -- **Stop, compaction and late-child behavior:** no recursive same-session runner, no queue, no restarts from plugin events, no false persistence claims. Partial or late child results count as incomplete. -- **Implementation seams exist:** - - `src/host.ts` already uses context and compaction hooks plus an abortable event subscription. - - `runBd` in `src/prime.ts` is a bounded runner without abort support yet; 3.1 adds that. - - `src/guard.ts` already probes safely with `bd where --json`. -- **Proportionality:** good. There are no new services, stores, pollers or tracker work. Fixtures (6.1) are kept separate from model qualification (6.2). -- **Verdict on tasks:** apart from B1, coverage is complete and proportionate. - -## Validations I ran - -- `openspec validate improve-beads-workflow-parity --strict --no-interactive`: valid. -- `openspec validate --all --strict --no-interactive`: 1 passed, 0 failed. -- `python3 -I docs/validate-parity-planning.py /opt/data/cache/scratch/parity-sources`: all 6 PASS lines. -- `git diff --check`: clean. -- Read-only `diff`/`cmp` of the installed cache, marketplace-main and the release tree; inventory inspection with `python3 -I`; `grep`/`sed` reads of the pinned 2.0.32 source. - -## What was not tested - -- No OpenCode host was started, and no plugin was loaded at either 2.0.29 or 2.0.32. -- No slash-command dispatch, permission prompts, saved grants, compaction, child-stop races or fresh-session recovery were exercised. -- No `bd` or store access, no npm pack or install, no model sessions. - -All N1, namespace, collision, resource-reachability and behavioral claims above rest on pinned source reading only. They remain future acceptance gates. My model is Opus 5.5; I can't see the reasoning-effort setting, so "medium" is unverified. diff --git a/docs/reviews/opus-planning-review-510c332.md b/docs/reviews/opus-planning-review-510c332.md deleted file mode 100644 index a30284a..0000000 --- a/docs/reviews/opus-planning-review-510c332.md +++ /dev/null @@ -1,103 +0,0 @@ -# Independent 2.1.1 rebaseline review - -Candidate: `510c3320fd357d5530373f2aefcfaa213d1a26df`. Actual model verified from result: `claude-opus-5-5`; medium effort explicitly requested. First attempt failed before inference on OAuth refresh contention; bounded retry completed with no permission denials. This review does not grant implementation authority. - -# Review: OpenCode 2.1.1 rebaseline, candidate `510c332` - -## Verdict: **READY** - -I found no blocking findings. The delta is bounded and backed by source. It fits the existing 13 tasks and 9 children without new services, tasks or graph changes. The tracker records agree with the spec. No runtime acceptance is claimed anywhere. - -## Blocking findings - -None. - -## Nonblocking observations (wording or record-hygiene fixes the parent can make at publication) - -1. **The new experimental `todowrite` tool is not dispositioned.** The changed sources include it: `packages/core/src/plugin/internal.ts` (+`TodoTool.Plugin`), `config/normalize.ts`, `schema/src/config/experimental.ts` (`todo`, default false), and changelog lines 10/94. The memo does not mention it. This doesn't change any decision, because the existing disposition already covers TodoWrite advice ("reconcile TodoWrite advice with current prime", `docs/claude-code-integration-inventory.json:1483`). Smallest fix: one memo row saying it is opt-in, host-owned, and does not change the 2.1 guidance reconciliation. - -2. **The `session.compacted` row overstates what the evidence shows.** `session.compacted` appears zero times in both the 2.0.32 and the 2.1.1 `session-event.ts`. It only shows up in the 2.0.32 V1 web plugin docs (`released/packages/web/.../plugins.mdx`), and `session-legacy.ts` does not map it. So "retire" is correct, and `src/host.ts:127` already uses `session.compaction.ended`. But the cited legacy decoder doesn't show a 2.1 removal. The real 2.1 lifecycle change is that `compaction.started` no longer carries `recent` (`session-legacy.ts:27`, `compaction.ts` publish). Fix: reword the row. - -3. **Some task cross-references in the memo are slightly off.** - - Row 1 cites 1.2/3.2/**6.1**, but the 6.1 text is unchanged. This is harmless, since 6.1 runs the suites. - - Row 2 calls 6.2 "fixtures", but 6.2 is the live evaluation. - - The transport row cites 6.2, but the 6.2 text doesn't mention transport. - - The skills row cites 3.3, which is unchanged (reload is covered there already). - - Fix: wording only. - -4. **"Unpublished" labels are now stale.** `execution-map.md:1`, the reconciliation 2026-10-20 section, and the record descriptions ("unpublished… No invented publication SHA") all say the delta is unpublished. But `metadata.planning_commit` already says `510c332`. I checked the manifest `/opt/data/cache/scratch/baseline211-planning-manifest.json`: its root is `72906511…`, its file set exactly equals `git diff --name-only 907232a 510c332`, and all 15 blob hashes match `510c332`. So the content identity is sound and only the labels lag. Separately, the epic notes cite a "content digest `d71f1642…`" that I couldn't reproduce from the manifest. Fix: clarify or drop that digest when the labels are refreshed. - -5. **One line in `reconciliation.md:61` still reads as operative.** It says "Selected released OpenCode v2.0.32", under a heading that isn't marked historical. The verdict at line 1 and the bottom section do supersede it. Fix: prefix it with "Historical". The phrase "within V2" at `design.md:82` is generic and harmless. - -6. **`metadata.recent` is a little subtler than the memo says.** `history.ts:144–182` rebuilds `metadata.recent` *in memory* from the `keepID` range for new summaries too, so readers see `recent` in both shapes. The 3.2 fixture should assert that this text is never persisted or flattened back. That fits the existing no-write rule; no task change is needed. - -7. **One evidence gap on skills.** The contents of `FSUtil.ignoreGlobs` and `ignoredDirectories` aren't in the 63-file cache (`packages/util` wasn't fetched). The claim "adds ignore globs" is bounded, and explicit package registration avoids the scan path (`skill-scan.ts` filters children, not the root). Task 2.2's installed-base fixture is the right gate. Nothing to change. - -8. **`.6` has no hard dependency on `.2`, even though its 4.2 live part needs 1.1.** This predates the rebaseline and is intentional: the phase dependency `4.2-live←1.1` and `metadata.deterministic_handoff.live_prerequisite=opencode-beads-vuy.2` encode it, so `.6` can hand off deterministic evidence first. Not a new issue. - -## Source claims I checked against the pinned source - -- **Replay renames:** `state`/`providerState`/`providerResultState`/`resultState` became `native`. - - Tool `state: ToolState` and the `ToolState*` metadata are kept (`session-message.ts` AssistantTool; `session-legacy.ts:54` "A tool part's own `state` is its lifecycle status"). - - `SessionCompactionResult.native` matches (`plugin/src/promise/session.ts:38–44`). -- **`native.messages` replaces the summary:** it is replayed only on the same provider and model, and a mismatched or malformed window is skipped and the original transcript is used (`history.ts:27–45,135–139`; `to-llm-message.ts:294`). A malformed window "from a compaction hook" is skipped, which supports never populating it. -- **Tool replay rules** match `to-llm-message.ts:154–212`: - - call metadata needs the same model (plus no error, or executed and settled); - - hosted (provider-run) results need the same provider; - - local results need the same model and no error. -- **Compaction and forks:** - - `keepID` is written in `compaction.ts` (`metadata: { keepID, ...result.metadata }`). - - Forks remap `keepID` (`projector.ts` fork copy). - - `RESERVE_SHARE 0.15` / `RESERVE_MIN 16_000` match. - - Summary preparation now sees the whole conversation (`prepare(context, context.messages…)`). -- **Permissions:** - - Undefined metadata values are filtered (`permission.ts:198`). - - The code-mode inventory is cached by registry and visible names while executors stay fresh (`tool.ts:236–255`). - - `PermissionSaved.update` is added (`saved.ts`). -- **`session.list`:** - - Plugin host and adapter only add forwarding (`plugin/host.ts:549`, `promise/adapter.ts:596`). - - Child removal uses `store.list`, not the public paginated list (`session.ts:383`). - - `inbox.ts` and `bus.ts` changes are decode-only (legacy upgrade). -- **Counts:** the inventory shows 63 sources (31 unchanged / 29 modified / 3 added) and 14 declarations, with only the two `session.d.ts` files modified. Both match the memo. - -## Contract-delta completeness: **adequate** - -- All the requested surfaces are covered: replay names, `native`, replacement replay, provider/model fallback, `keepID`/`recent`/forks, lifecycle, reference-only compaction (no writes, no recursive waits, no injected result or window), permissions, identity, deny/save/external access, grant edits/revocation, skills/reload, cancellation and late children. -- The claims that declarations and implementation are unchanged are bounded to the endpoint files and are correct where I sampled. -- Released `session.list` is reclassified but not adopted. -- Admission `>=2.1.1 <2.2` is kept separate from exact unexecuted 2.1.1 qualification. Operator 2.0.29 stays untouched, and there's no blanket V2 promise. -- Settled product choices are not reopened. -- The only omission is the experimental `todowrite` tool (observation 1). - -## Tracker-map verdict: **consistent** - -Checked against the fresh readback `opencode-beads-211-opus-readback.json`: - -- **Ownership:** 13 unique task IDs, exactly equal to `tasks.md`. 17/17 requirement titles match the spec headings. -- **Graph:** 14 `blocks` edges, acyclic, identical to the worker snapshot and to `check-results.hard_dependencies`. `.8→.6` is `related` only. -- **Authority:** all ten records are `blocked`, have no assignee, and have `implementation_authorized=false`. -- **Gating:** - - `.6` owns 4.2, with `completion_requires_live: true`. - - `.8` requires parent-verified handoff evidence. - - `.9` is blocked by `.2`, `.5`, `.6` and `.8`. -- **Stale baseline:** none. Each record has one historical "supersedes the former 2.0.32 baseline" mention, and zero operative `>=2.0.32 <3`. -- **Embedded links:** the only pinned planning links point to `84ab18e`, and they are explicitly labelled historical. - -## Checks - -**Executed by me (all passed):** -- `openspec validate improve-beads-workflow-parity --strict --no-interactive` — valid. -- `openspec validate --all --strict --no-interactive` — 1 passed, 0 failed. -- `python3 docs/validate-parity-planning.py /opt/data/cache/scratch/parity-sources` — 7 PASS lines, including the 2.1.1 blob, tarball and declaration integrity. -- `git diff --check` on the worktree and on `907232a..510c332` — clean. -- Read-only git diffs and source greps. -- The read-only Python record, manifest and graph checks above. -- Protected setup: the hashes of `AGENTS.md` and `.codex/*` match `check-results`, and they are unchanged in the commit range. - -**Reported only, not re-run by me:** -- `bd lint` scoped lint. -- The live GitHub tag/tree API and npm registry retrieval (the validator re-verifies only the cached copies). -- The worker's "notes preserved / only eleven records updated" claim. - -**Not executed:** no `bd` commands, typecheck, package tests or installs, host runs, or model runs. No runtime or model evidence exists for 2.1.1. Live gates 1.1, 4.2 and 6.2 remain wholly unexecuted, and they need separately authorized disposable host and model access. diff --git a/docs/reviews/opus-planning-review-e74b507.md b/docs/reviews/opus-planning-review-e74b507.md deleted file mode 100644 index 169c8b5..0000000 --- a/docs/reviews/opus-planning-review-e74b507.md +++ /dev/null @@ -1,146 +0,0 @@ -# Independent planning review: candidate `e74b507` on `openspec/improve-beads-workflow-parity` - -HEAD is `e74b507fca555b42558ddd6307ce488b30c0e3a6`. The local `AGENTS.md`, `.claude/` and `.codex/` changes are not part of the candidate, and I left them alone. I made no edits, ran no `bd` commands, made no commits and installed nothing. - -## 1. Verdict: **REVISE** (one small, targeted revision; this is not an implementation authorization) - -The architecture analysis is sound and its key API claims match the pinned release source. One finding changes what the owner is actually comparing against. It needs a short evidence correction and a choice of upstream-review baseline before the packet goes to Matt. Everything else is material advice that doesn't block the decision. - -## 2. Findings, in priority order - -### F1 — Blocks owner review: the installed Claude plugin already differs from the pinned baseline on note-taking, which is the behavior that motivated this work - -- **Where:** `docs/claude-code-local-reference.md:28` only says "Other files differ". `docs/claude-code-integration-analysis.md:48,82` presents "WORKFLOWS … tells agents to overwrite notes" as an unresolved adaptation tension. `specs/upstream-review/spec.md:7` and `design.md:86` compare only against a "candidate stable release". -- **Evidence:** - - The installed marketplace checkout is `4a67d0d…`, committed 2026-10-17 on upstream main. It is newer than the v1.3.1 tag `c1c4b64…` (published 2026-09-30). Its `plugin.json` still says `1.3.0`. - - Diffing the installed files against `parity-sources/beads/plugins/beads`: the installed `WORKFLOWS.md`, `PATTERNS.md`, `INTEGRATION_PATTERNS.md`, `ISSUE_CREATION.md` and skill `README.md` all use `bd update … --append-notes`. The pinned release uses `--notes`, which overwrites. For example, `WORKFLOWS.md` lines 69, 79, 345 and 407. - - `--append-notes` already exists in the pinned CLI (`cmd/bd/cli_fast_test.go:469`). - - None of the candidate docs, specs or sources mention `append-notes`. -- **Consequences:** - 1. Matt's observation that Claude takes better notes was formed against guidance the packet never analyzed. Upstream has already resolved the overwrite tension in favor of appending. - 2. Claude marketplace installs follow upstream main, not releases. A drift monitor that only looks at stable releases misses exactly this kind of behavior change for weeks. - 3. The 73-file release inventory is still correct for its own pin, but it is the wrong reference for any "parity with what I see in Claude" comparison. -- **Smallest fix:** - - Add a short, characterized installed-vs-pinned diff to the local-reference doc: list the files, and record that the note write mode changed from replace to append. - - Update the WORKFLOWS/PATTERNS rows to recommend append-style checkpoints. - - Add one gate item: the parity reference is either the release or the marketplace main head. - - Let `upstream-review` optionally track the marketplace default-branch head as a second, informational baseline, or state explicitly that this is a known blind spot. - - No new inventory campaign is needed. - -### F2 — Material, nonblocking: the typed tool's visibility to agents isn't covered, so authorization equivalence is incomplete - -- **Where:** `design.md:33` and `docs/opencode-native-parity-assessment.md:86` only discuss call-time `permission.assert`. -- **Evidence:** - - Released `packages/core/src/tool.ts:231` hides a tool from an agent when `whollyDisabled(tool.options?.permission ?? name, rules)`. So a new `beads_*` tool is visible to any agent that wholly denies `shell`, unless the tool sets `options.permission`. - - `core/src/permission.ts:157-162` (`configured`) resolves `agent ?? session.agent`. The shell tool passes `agent: context.agent` and calls `access.authorizeExternal` before asserting (`core/src/tool/plugin/shell.ts:132-145`). - - The `save` field can turn an "always" reply into a broader saved rule. -- **Consequence:** a read-only or shell-denied agent could still get a write-capable Beads tool. Saved approvals could also become wider than intended. -- **Fix:** add these to the N1 mapping as required qualification items: - - set `options.permission` to the shell action; - - assert `action: "shell"` with canonical `bd …` resource strings and pass `context.agent`; - - narrow or omit `save`; - - check the guard hold before running. - - The plan's principle ("not default-allow") already implies this. It needs to be written down concretely. - -### F3 — Material, nonblocking: the "prepared checkpoint at compaction" state is effectively unreachable under N1's own design - -- **Where:** `design.md:33` (synchronous writes, no queue) versus `design.md:53`, `specs/work-continuity/spec.md:81-85` and `tasks.md:29` ("prepared-write compaction ordering"). -- **Evidence:** the hook dispatcher awaits callbacks one after another with no timeout (`core/src/plugin/hooks.ts:88-95`). The assessment itself says "usually the compaction hook only carries acknowledged references" (`assessment.md:84`). -- **Consequence:** the spec scenario and the test task invite someone to build a pending-write state just so it can be tested. That is the deferred queue the design rejects. -- **Fix:** restate M03 as "compaction adds acknowledged durable references and flags known unsaved state; no writes in the hook unless qualification shows an in-flight overlap". Drop "prepared-write" from 4.2 or make it conditional. - -### F4 — Material, nonblocking: the upstream-review alert sink conflicts with the repo's tracking rule - -- **Where:** `design.md:86` says "deduplicated GitHub review issue". The committed `AGENTS.md:166` says "Do NOT use external issue trackers". -- **Context:** the existing `beads-contract.yml` alerts by failing the check, with `permissions: contents: read`. -- **Consequence:** this adds `issues: write` to a scheduled workflow, which is a new security surface for the zizmor ruleset. It also creates a second tracking surface. -- **Fix:** either state that the GitHub issue is a notification only and a maintainer files the Beads work on disposition, or reuse the existing failing-check pattern with deduplication keyed by candidate commit. This is an engineering choice once the conflict is acknowledged. - -### F5 — Cosmetic - -- `analysis.md:177` says "both proposed capability deltas"; there are three. -- `analysis.md` lines 126 and 139 cite the development pin `8f7b012` for the command and skill docs, even though the assessment corrects provenance to `843a6c5`. -- `tasks.md:2.4` and `analysis.md:173` repeat history about the freeze marker and tracker that isn't needed. -- `design.md` Decision 4 contains the N2 and X-dispositions paragraph, which belongs elsewhere. - -### Checked and confirmed (no findings) - -| Claim | Source checked | -| --- | --- | -| `permission.assert` exists only in 2.0.32 | `npm32` `dist/promise/permission.d.ts:28`; absent from `npm26` and `minimum/` | -| Hooks are awaited in sequence with no timeout | `core/src/plugin/hooks.ts:88-95` | -| Command `add` is a map set, so a collision overwrites; `list` exists | `core/src/command.ts:61,79` | -| Code-mode and direct tool paths both go through `beforeExecute` | `core/src/tool.ts:240-243` | -| Upstream task agent repeats the ready cycle | `agents/task-agent.md:36-38` | -| 29 commands, 15 resources, `SessionStart`/`PreCompact` run plain `bd prime` | pinned `plugin.json` | - -The planning validator passes. No requirement silently fixes one-bead scope or a default command set. - -## 3. N1 versus the alternatives, and proportionality - -- **What the custom tool really buys:** - - safe argument passing for multi-line notes, avoiding shell quoting failures; - - a named tool in the model's tool list, which may be a stronger prompt to checkpoint than prose; - - precise cache invalidation. - - The "typed acknowledgement" over a shell exit code is modest, since the model already sees CLI success or failure. -- **What it costs:** - - raising the minimum host to 2.0.32, which was published two days before this review; - - permission-equivalence engineering (F2); - - a second surface that must track `bd` flags. `--append-notes` shows those flags carry meaning. -- **Is authorization equivalence achievable?** Probably, for a fixed and narrow set of operations, if F2 is done. It is not automatic. The plan correctly makes falling back to N0 the default if equivalence can't be demonstrated. -- **Proportionality:** there is no second datastore, daemon, reviewer fleet or automatic memory capture. The design is proportionate. -- **Framing bias:** the user-reported gap is unexplained, and F1 suggests a cheap guidance-level cause. Most of the plausible improvement comes from the resources and skill, recovery reads and append-style checkpoints. All of that works on N0. The packet presents N0 only as a "compatibility fallback". -- **Recommendation:** offer a staged option, **N0 now with an N1 seam**. The typed tool is adopted only if evaluation shows tool-call salience or quoting failures that guidance can't fix. This is advice for the owner's choice, not a defect. - -## 4. Owner decisions that are genuinely consequential - -These need Matt: - -1. The parity reference: pinned release or marketplace main (new, from F1). -2. The minimum host: 2.0.32 with N1, 2.0.26 with N0, or N0 now with an N1 seam. -3. Invocation-scope policy (E01/E05/N2), and whether batch continuation is the default. -4. Ownership and naming of the supplemental skill and commands, including whether to ever override the shared `beads` skill. -5. Corpus dispositions as groups, especially the deferred resources and admin commands. -6. The upstream alert sink, because of the AGENTS.md conflict (F4). - -These can be engineering decisions: - -- the M01–M10 mechanism mapping; -- X01, X02, X04, X05, X07, X08 and X09 (the plan already recommends against or defers them); -- collision and precedence handling; -- the exact permission mapping in F2, provided it is equivalent or falls back to N0; -- how the compaction hook is simplified (F3). - -X03 (nested delegation depth) and N2 background continuation stay with the owner only if selected. - -## 5. Checks run, limitations and disclosures - -**Checks run (all read-only):** -- `git rev-parse` / `git status`, and the diff stat from base `c5c29f2`. -- Read every candidate artifact, the analysis doc in full, and inventory summaries via `python3 -I`. -- Source call sites in `parity-sources/{released,minimum,npm26,npm32,beads}`, as listed in the findings. -- `diff -rq` of the installed plugin cache against the pinned plugin tree, plus `git log` on the shallow marketplace checkout. -- `python3 -I docs/validate-parity-planning.py …`: all 4 checks PASS. -- `openspec validate improve-beads-workflow-parity --strict`: valid. The OpenSpec CLI printed a notice that it collects anonymous usage stats, so the run may have sent telemetry. -- Read `beads-contract.yml`, `src/host.ts` and `src/agents.ts`. - -**Not done:** -- No product tests, since the candidate is docs-only. -- No runtime or host probes. -- I could not check commit ancestry in the shallow clone; the ordering in F1 rests on commit dates. - -**Installed Claude plugin context in this session:** -- It appeared. The SessionStart `bd prime` hook output was injected, including 4 persistent memories. -- The skill list showed the `beads:beads` skill and all 29 `beads:*` command entries. -- No compaction happened, so `PreCompact` was not observed. -- I had no agent tool, so `task-agent` registration couldn't be checked. - -**Model:** the session reports `claude-opus-5-5` (Opus 5.5). The reasoning-effort setting isn't visible to me, so "medium" is unverified. Nothing was substituted. - -**Tools and authorization:** no tools were soft-denied. Plan mode was active and I wrote no plan file. Exit status 0 from the validators is not proof the review is complete. - -**Unavailable connectors:** the claude.ai Excalidraw, Gmail, Google Calendar and Google Drive connectors need authorization in claude.ai connector settings. They weren't needed here. - -I've stopped here, as requested. The planning bead is not marked complete. \ No newline at end of file diff --git a/docs/reviews/opus-registration-delta-recheck-5ea915a.md b/docs/reviews/opus-registration-delta-recheck-5ea915a.md deleted file mode 100644 index e0e4e5d..0000000 --- a/docs/reviews/opus-registration-delta-recheck-5ea915a.md +++ /dev/null @@ -1,70 +0,0 @@ -# Opus registration delta recheck - -Candidate: `5ea915ac5b65852da70a1b4bd25457f3259f6b76`. -Reviewer: `claude:oc-registration`, Claude Opus 5.5, requested effort medium. -Session: `95b72364-ff32-423f-a63d-3e007f05768a`; review record `opencode-beads-cny`. -Original REVISE report: [registration resolution review](opus-registration-resolution-review-vuy5.md), retained unchanged. -Scope: original findings and correction-caused regressions only. Read-only source review; no tests, git commands or live qualification by reviewer. -Parent verified exact candidate HEAD and clean worktree before retaining this report. -Result: completed, is_error=false, no permission denials; modelUsage confirms claude-opus-5-5. - -## Verdict: **READY** for the corrected .5 **source** at `5ea915a` - -The branch ref `refs/heads/openspec/improve-beads-workflow-parity` reads `5ea915ac5b65852da70a1b4bd25457f3259f6b76`. The working-tree `src/host.ts` matches the committed diff. I can't run `git status`, so "clean" is the parent's claim, not mine. Every material finding from the original review is fixed in code and tests that I read myself. This verdict covers source only, not live qualification. The original REVISE report stays as it was. - -## How each original finding was handled - -**1. Initial collision withholding → fixed.** -- `src/host.ts:258-263`: the setup-time `command.list()` only produces a diagnostic, including when the lookup fails ("earlier entries follow native precedence and may be replaced"). -- `:264-269`: a single transform adds all definitions with no withholding. -- `COMMAND_REGISTRATION_HOLD` is gone. A search finds it only in the historical review. -- Tests (`tests/host.test.ts`, diff 1150-1186): a 30-command registry despite the initial collision. With callbacks in `[package, config]` order, the user config wins and its body is the one that runs. Removing it restores ours. Cleanup leaves `callbacks == [config]`, removes status, and stops the stale callback from adding anything. Dispatch passes literal text, files, agents, skills and delivery through unchanged. -- Separate test (diff 1188-1193): registration still happens after an initial lookup failure. - -**2. Hardcoded withheld status → fixed.** -- `src/host.ts:232-252`: status now reports: - - the actual `registration` state (`pending`/`registered`/`failed`) - - `lookup` (`available`/`failed`) - - effective names and descriptions, `mismatches` and `missing` - - an `ownership` disclosure covering owner identity, identical-description overrides, and that matching does not prove ownership -- A failed lookup reports "unknown" and never an invented empty list (`:235,243`); the test checks that `mismatches` is undefined in that case. -- The guard is still the config-only probe (`:227-231`). The status test (diff 1347-1401) asserts only `version` and `context --json` are called, and that prime is not called for missing, withheld or failed context. -- Status is reachable as a registered native command, and an in-flight status is cancelled on unload (diff 1403-1422). - -**3. Spec, design and task wording → fixed.** -- spec.md customization and discovery-collision scenarios (diff 247-267), design.md:31 (diff 201-203) and task 2.2 (diff 285) now state the native-precedence boundary. The old "withhold/stop path" sentences are gone. -- Pinned ordering (`supervisor.ts:99-103`, `internal.ts:254-259`) is kept separate from the unpinned released-cache suffix-reactivation evidence. That separation appears in the design, artifact policy and SDK contract. -- 2.2 and 3.3 are marked for source only; the text says live 1.1/6.2 remain unexecuted. - -**4. Abort guard and disposer → fixed.** -- `src/host.ts:265-268` checks abort before any add and pushes the registration into `registrations`. -- Command transform failure is diagnosed, then setup fails and releases earlier registrations (`:270-273`; test diff 1424-1436). - -**Skill gate defect → fixed.** -- `src/host.ts:198-203` no longer has an initial `skill.list()` gate; the per-rebuild `editor.list()` check (`src/workflows.ts:82-88`) is kept. -- Test (diff 1224-1261): `list` is never called. An earlier customization is preserved, then the packaged skill returns after removal, a later config skill wins, and the callback adds nothing after cleanup. - -**Zero-registration tests and package smoke → fixed.** -- `scripts/test-package.ts` (diff 414-481) calls the real callbacks and requires exactly 30 names. -- It runs every body and checks the forwarded fields, the installed guidance path, the status fields and one prompt per command. -- It derives the five owned disposers (agent, skill, command, two hooks) and checks all of them are disposed. -- The 16-link, resource-byte, export and missing-file checks are intact. - -**Stale docs and anchor → fixed.** README, artifact policy and SDK contract are rewritten, and the anchor is now `#tasks-2233-source-candidate-native-registration-and-diagnostics` on both sides. - -## Remaining blockers -None. - -**Non-blocking observation (outside the original findings):** status `skill` reports only loader failures plus effective IDs. A per-rebuild `oc-beads` skill collision only shows up as a warning, and the ownership disclosure is worded for commands only. A one-line skill ownership note would make the status honesty symmetric. This is optional and doesn't affect the verdict. - -## Standards vs spec -- **Standards:** no regressions caused by the correction. Permissions, attribution text, config-only probing, cleanup idempotence and user-file preservation are unchanged. There is no host replica or collision manager. -- **Spec:** reconciled as described under finding 3. - -## Still unexecuted live checks -- Installed 2.1.1 discovery and dispatch of the `oc-beads:*` commands. -- Whether user-config precedence and suffix reactivation behave this way in a real host. Pinned ordering is from source reading; the reactivation evidence comes from the unpinned cache. -- External-directory ask/deny for resource reads, and model use. -- Typed continuity activation (1.1) and the 6.2 acceptance checks. - -All of the above rests on mocks and source reading. I ran no tests and no git commands. diff --git a/docs/reviews/opus-registration-resolution-review-vuy5.md b/docs/reviews/opus-registration-resolution-review-vuy5.md deleted file mode 100644 index 4040ba7..0000000 --- a/docs/reviews/opus-registration-resolution-review-vuy5.md +++ /dev/null @@ -1,71 +0,0 @@ -# Opus review — vuy.5 registration resolution - -Reviewer: claude:oc-registration; Claude Opus5.5, requested effort medium. -Session: 95b72364-ff32-423f-a63d-3e007f05768a. Review record: opencode-beads-cny. -Baseline:38206ff428838e0290b6d2bb3db5ddc7b7beb9d4 plus unchanged13path uncommitted candidate. -Proposed resolution: /opt/data/cache/scratch/opencode-beads-vuy5-resolution-review.md; tracked diff SHA2569c95159946e8431e26651e3fa3be53c29a449cb58a305e716c21c07792df06fe (untracked workflows.ts separately hashed/read). -Outcome: completed, is_error=false, no permission denials. Initial pre-inference OAuth refresh failure is not a review verdict. No code or tests run by reviewer. Current implementation remains partial; this review does not accept source or live qualification. - -## Verdict: **REVISE** (small plan corrections; the boundary itself is sound) - -The approved intent holds up against host source: use the dedicated namespace, follow native precedence, and disclose that earlier plugins can collide. Two parts of step 2 are not mechanically sound as written, though, and the status contract needs its own step. None of this needs an architectural restart. READY on the corrected plan would not mean the source is complete or live-qualified. The candidate still registers 0 of 30 commands, and that is partial delivery. - -## Mechanically verified host ordering (pinned 2.1.1 unless noted) - -- **How commands are stored.** `core/src/command.ts:28-30,61`: the editor exposes only `add`, which is a map set, so the last write wins. -- **How rebuilds run.** `core/src/state.ts:162,178-181`: a rebuild replays every transform in insertion order (a Set), and `reload()` (`:250`) re-runs the same order. -- **Plugin order.** `plugin/supervisor.ts:99-103` orders plugins as `pre → packages → post`. `plugin/internal.ts:254-259` places `ConfigCommandPlugin` in `post`. `config/plugin/command.ts:44-47,71-72` registers one transform once; config edits only refresh `loaded.documents` and call `ctx.command.reload()`. - - So ordinary user config and file commands always replay after our transform, on the initial load and on every config rebuild. - - When the user removes their entry, our definition comes back naturally. -- **Skills behave the same way.** `skill.ts:106-107` (`add` is a map set) plus `ConfigSkillPlugin` in `post` means config skills also win natively. -- **Not pinned:** the registry's re-activation semantics. `core/src/plugin.ts` is missing from `baseline211`. The non-pinned `released/.../core/src/plugin.ts:108-139` shows a prefix diff that tears down and reloads the changed suffix in order. That keeps post after packages when a package is re-activated. Treat this as strong but unpinned evidence. Plan step 2's "verify actual host ordering" must cite it as such, or find pinned evidence. - -Calling earlier-plugin overwrites "native last-writer semantics" is correct. It is not an upstream defect. - -## Spec/plan findings - -1. **"Initial collision detection may withhold an affected name" doesn't work for user config and causes stale withholding.** - - Our setup runs during the package phase, before `ConfigCommandPlugin`'s post transform is loaded. On a suffix re-activation, that transform is torn down before we load. So the `ctx.command.list()` at `src/host.ts:256` can only see built-in (pre) and earlier-package names, which are exactly the cases the boundary hands to native precedence. - - A name withheld at setup never comes back if the earlier plugin later drops it. That contradicts the plan's own "removal restoring normal host registry". - - **Correction:** register all 30 unconditionally. Keep the setup-time list check only as a diagnostic, e.g. "earlier entry X will be replaced by package precedence". Do not withhold. -2. **The status contract is not in the plan.** `src/host.ts:249` hardcodes `commands: { state: "withheld", reason: COMMAND_REGISTRATION_HOLD }`. Once the hold is removed, that is false status, which task 3.3 makes a stop condition. The spec scenario "status identifies the collision and effective entry" (spec.md:172-175) can be met through public APIs: - - `command.list()` returns `{name, description}`. - - Any owned name whose effective description differs from our definition has been overridden by a higher-precedence entry. - - Disclose the limits: the owner isn't exposed, and an override with an identical description can't be detected. - - Add this to step 2/4 and delete `COMMAND_REGISTRATION_HOLD` (`src/workflows.ts:90-91`). -3. **The spec text needs exact wording replacements.** - - spec.md:66 ("withholds… if preservation cannot be established across rebuilds; documented override behavior does not authorize overwriting user commands"). - - design.md:31 ("stop that affected registration path…"). - - tasks.md:15 ("stop that affected registration path rather than overwrite it"). - - Replacement for each: user config and file commands are preserved by post-ordered native precedence; same-name conflicts with other plugins follow native order and are disclosed and diagnosed. Step 1 covers this; make the target sentences explicit so the reconciliation stays bounded. -4. **Keep the abort guard.** The new command transform should mirror the skill and agent transforms: `if (!abort.signal.aborted)` before any `add`, and push its registration into `registrations` so cleanup disposes it. - -## Candidate source defects affecting the plan - -- **Initial skill gate is redundant and blocks restoration.** `src/host.ts:200-213` checks `skill.list()` once at setup and, on a collision, never installs the transform. The per-rebuild `editor.list()` check (`src/workflows.ts:82-88`) already covers earlier entries. The setup-time gate only stops our skill from returning after the user removes their customization. This is minor, and it is the same pattern as finding 1. Either drop the initial gate or document it. -- **Tests and package smoke still treat zero registrations as success.** - - The package smoke script fails if any command is registered: `scripts/test-package.ts` (diff lines 224-226) checks `commandTransforms !== 0`, and its `disposed !== 4` count must become 5. - - `tests/host.test.ts` asserts `commandTransform).not.toHaveBeenCalled()`. - - The fake transform in the package smoke never invokes its callback, so it can't verify registration. Step 3 covers replacing these; flagging the exact sites. -- **The status command is unreachable while withheld.** `oc-beads:status` is defined but not registered, so the "native status" requirement is currently unmet. -- **Docs to replace in step 4:** - - README "withholds their registration" (diff lines 11 and 43). - - Artifact policy (diff line 64). - - SDK contract section "Unresolved source blocker" (diff line 86); the cross-link anchor `#tasks-2233-source-candidate-delivery-and-concrete-command-hold` will change. -- **No regressions found** in the touched code: - - Command bodies pass literal text, `files`, `agents`, `skills` and `delivery` straight through, with no template or shell evaluation (`src/workflows.ts:107-118`). - - Cleanup is awaitable and idempotent, and setup failures release earlier registrations. - - Status guard uses only the config-only probe. - - Package plumbing is fine: `files`, archive inventory and the 16-link smoke check. - - No permission waiver. - -## Smallest corrective plan - -1. Step 1: add the three exact spec/design/task replacements from finding 3, plus the status-scenario wording from finding 2. -2. Step 2: register all 30 commands without withholding; turn the setup-time list check into a diagnostic only; add the status override detection; add the abort guard; drop `COMMAND_REGISTRATION_HOLD`. -3. Step 3: add a fixture that replays transforms as `[package, config]` in order, covering: user config added later wins, removing it restores ours, and disposal removes only our transform. A small ordered-callback list is enough; this is not a host replica. Also test a status override report. -4. Step 2 evidence: record that registry suffix ordering comes from the unpinned `released` cache. - -## Limitations - -This review used only Read and Grep. Nothing was run, and there were no live host checks. The registry `activate` file is not in the pinned cache. Whether user config precedence holds in a live 2.1.1 install, how commands are discovered and invoked, and how external-directory permissions behave are all still unexecuted (tasks 1.1/6.2). diff --git a/docs/reviews/opus-source-collector-review-vuy7.md b/docs/reviews/opus-source-collector-review-vuy7.md deleted file mode 100644 index 4a4f15c..0000000 --- a/docs/reviews/opus-source-collector-review-vuy7.md +++ /dev/null @@ -1,39 +0,0 @@ -# Opus source collector review - -Baseline: `a5d6b2bea779259ba9aa3175ab86fb2f4f2b862b` plus unchanged 10-path candidate. -Reviewer: `claude:oc-source-check`, Claude Opus 5.5, requested effort medium. -Session: `38ee7b26-db63-400c-bf94-d9f3e28119bc`; review record `opencode-beads-t1v`. -Actual modelUsage confirmed; completed, is_error=false, no permission denials. -Parent verified all reviewed path hashes unchanged before acceptance. -Source only; no workflow/CI activation or tagged-CLI qualification. - -Review done; writing up the verdict now. - -## READY (source only) - -I did a read-only review of `scripts/check-beads-integration.ts`, `tests/upstream-review.test.ts`, the upstream-review spec, task 5.1 and the policy appendix (`docs/beads-artifact-policy.md:91-107`). I ran no tests, network calls, edits or agents. The live run evidence is the parent's, not mine. - -### Standards findings -No material defects. - -- **Complete enumeration and SHA selection:** a tree only counts if its SHA matches the expected one and it reports `truncated === false` (`:65`). Every entry needs a valid path, a 40-hex SHA and a mode/type pair that agree (`:70-79`). The baseline's selected files must match the reviewed inventory exactly, in both count and blob IDs (`:164`). So a partial or empty retrieval can never show up as `unchanged`. If every candidate file disappears, that is reported as deletions (`changed`), not as no change. -- **Root matching:** prefixes end in a slash (`:3`), so `plugins/beads-extra` isn't pulled in. A test covers this (`:93-95`). -- **Renames:** a rename is only reported when the removed file's blob and mode are unique and there is exactly one matching added file (`:98-100`). Anything else stays a delete plus an add. The appendix documents this limit (`:99`). -- **Credentials:** transport errors are swallowed without echoing them (`:138-140`). Error messages carry only the API path and HTTP status. The token never reaches stdout, and the subprocess test checks this (`:226`). -- **Scope:** there's no `.github` wiring, no tag or release queries (test `:147`), no baseline-advance option (`:196`), and no file writes. The script only reads `marketplace_main`. - -### Spec findings -No material gaps against the spec or task 5.1. - -- **Main changes exit 0 as information:** both `changed` and `unchanged` return exit 0 with `level: info` and `channel: development-source` (`:175-183`). This is checked through the real CLI entrypoint with a stubbed fetch (`:220-226`), not just the pure function: exit 0, empty stderr, and no `::error::` or `::warning::`. -- **Unavailable is distinct:** every failure path returns `kind: unavailable`, exit 2, and no `status` or `changes`. The tests check this (`:163-199`), and the entrypoint returns exit 2 for a truncated tree (`:233-238`). -- **CLI compatibility stays independent:** the collector never queries tags, its report has no `compatible` or `taggedRelease` fields (`:227-228`), and the inventory and `package.json` bytes are unchanged afterwards (`:243-244`). Nothing ties it to a hardcoded release. -- **Output:** includes both commits, per-file links at their exact commits, and a compare link (`:157-173`). Output is sorted, and repeated runs are byte-identical (`:132-133`, `:229`). -- **Explicit baseline advancement:** this only happens through a revised inventory passed in by hand (`:150-161`). There's no automatic path. - -### Non-blocking notes (no fix needed) -- The frozen `stableCLIResult` / `stableCLIFailure` objects in the entrypoint test (`:209-239`) prove almost nothing, because nothing could change them. The real independence evidence is the no-tag-query check, the missing report fields and the unchanged files. -- An oddly named path anywhere in the upstream repo (say, one containing a backslash) would make the whole run unavailable. That fails safe, never as a false success, so it isn't material. - -### Smallest material correction -None. diff --git a/docs/reviews/opus-sync-context-source-bbd.md b/docs/reviews/opus-sync-context-source-bbd.md deleted file mode 100644 index c835bf8..0000000 --- a/docs/reviews/opus-sync-context-source-bbd.md +++ /dev/null @@ -1,70 +0,0 @@ -# Source/evidence verdict: READY for opencode-beads-9ux (16-path candidate) - -This review (opencode-beads-bbd) found no material Spec/Behavior or Standards/Proportionality findings. The candidate matches the corrected plan's scope. The retained evidence supports accepting it as a bounded walking skeleton. I did not re-run anything; this rests on reading the source plus the retained artifacts. - -## Spec/Behavior - -No material findings. The contract points check out against source: - -- **One compact native prompt.** - - Sync stores `/oc-beads:sync` plus `Literal user details:` when details are present, with a versioned snapshot in `metadata.ocBeadsSync` (candidate.diff:176-186). - - `...input.prompt` still passes files, agents and skills through unchanged. - - Overwriting `metadata` loses nothing from the invocation. `CommandInvocation.prompt` is `PromptInput.Prompt`, which has only text/files/agents/skills (schema `prompt.js:46-51`). Admission metadata is a separate field (`promise/session.d.ts:17`). - - The snapshot is the beta.3 instruction text exactly, digest-pinned at host.test:313. The other 29 commands still go through the shared `instructions + details` path (candidate.diff:186), and all 29 are digest-checked against generated baseline values (workflows.test:445-454). -- **Expansion helper** (`expandBeadsSyncContext`, candidate.diff:152-166). - - It replaces array entries rather than mutating the stored message, and acts only on user-role messages whose metadata is exactly version 1 with string instructions. - - It drops only its own key and keeps foreign metadata and IDs. Running it twice is a no-op. - - Tests cover each rejection case: assistant role, version 2, non-string instructions, empty metadata, and slash-looking text without a tag. -- **Hook placement.** - - In `context` it runs after the unload check and before `session.get` and the location/eligibility returns (host diff :117-120). A test proves expansion still happens on the location-mismatch path, and that nothing is expanded after cleanup (host.test:265-281). - - `compaction` was restructured equivalently, so the cue keeps its existing eligibility gate. - - Only `context` and `compaction` are registered. Both the host test (:272) and the packed smoke test (:79) assert that title and generate are absent. -- **Compaction (SB-1 as implemented).** - - The added `BEADS_COMPACTION_GUIDANCE` sentence is exactly the approved one, with no promise of verbatim retention or native-window override. - - Replay of a JSON round-tripped retained message expands exactly once through the registered hooks. -- **Lifecycle.** - - An ambiguous admission failure propagates after one call, with no retry (workflows.test:437-443). Pre-admission unload still throws. - - There is no synthetic pairing, pending queue, or new model call. Queue and steer are passed through unchanged. -- **OpenSpec delta** (spec.md:898-933): its scenarios match the behavior above, including the explicit no-verbatim-retention limit. - -## Standards/Proportionality - -No material findings. - -- The product change is about 30 lines across three source files, using only supported SDK types (`SessionContext["messages"]`). There is no framework, parser, floor change, or provider/CLI workaround. -- Tests extend the existing fakes. The serializer check reuses the real `@opencode/ai` Responses path over loopback rather than adding a fixture corpus. -- The packed smoke test drives the registered hooks at the actual installed skill path. - -## Context effectiveness - -**Shown by the deterministic serializer test** (actual OpenAI Responses serialization, no inference): -- Each tagged message carries exactly one snapshot, and `ocBeadsSync` never reaches the outbound request. -- Unexpanded stored messages also serialize without the key. For this serializer, the metadata is not emitted, which settles the SB-3 question for this provider. -- Expansion is byte-stable across replays, and storage is unchanged. -- Compared with beta.3, the only difference is the visible `/oc-beads:sync` part plus one extra text-part boundary: +46 chars per invocation (2738→2784 for one sync, 7858→7996 for three). That growth is bounded and linear, the same shape as beta.3. -- The 113-char compaction cue is disclosed separately. - -**Shown by the one genuine 2.1.2 sample:** -- `R1-provider-wire-inputs.json:16-29` shows a single user message: the snapshot first, then `/oc-beads:sync`, with no marker. -- Later requests use `previous_response_id`, so the sample does not re-test replay; that rests on the fixture. -- The persisted record holds compact text plus metadata only (`R1-persisted-user-message.json`). There were 5 primary and 0 auxiliary requests. - -**Not measured:** cost, savings, and cache attribution. -- `R1-provider-usage.json` shows cached input going 0 → 12544 → 9216 → 21760. A single sample cannot attribute that pattern to the plugin. Expansion is deterministic, so nothing in the source would make the prefix unstable. -- The docs correctly say the instructions are relocated, not made cheaper. - -## Optional observations (nonblocking) - -1. **Undeclared test dependency.** `tests/host.test.ts` imports `@opencode/ai` without declaring it. It resolves deterministically today as an exact `2.1.1` dependency of `@opencode/plugin` (`plugin/package.json:50`). Declaring it in devDependencies, pinned, would make that explicit. -2. **Wrapper hides missing `messages`.** The `fakeContext` hook wrapper defaults `event.messages ??= []` for every test. That matches the SDK type, where `messages` is required, but it would hide a host that omitted it. -3. **Cue scope.** The cue is added on every eligible Beads compaction, not only sessions with a tagged sync. This was accepted earlier and is disclosed. -4. **Archive naming.** The sample archive is local source under the beta.3 version string. That is for publication/versioning to handle, not this gate. - -## Limitations - -- This is a source and evidence review only. I did not run tests, the typecheck, the package smoke test, or the sample. -- I relied on the parent's custody of the 16 candidate paths, the 164 protected paths, and the logs. -- I did not view the UI renders. -- Serializer evidence covers OpenAI Responses only. Hooked paths delete the key before conversion, so other providers' handling matters only for unhooked lowerings. - -READY does not authorize commit, release or publication; the parent owns acceptance. \ No newline at end of file diff --git a/docs/reviews/opus-workflow-context-plan-0ny.md b/docs/reviews/opus-workflow-context-plan-0ny.md deleted file mode 100644 index 8f6debc..0000000 --- a/docs/reviews/opus-workflow-context-plan-0ny.md +++ /dev/null @@ -1,65 +0,0 @@ -## Verdict: **READY** - -This verdict covers the plan and task structure only: plan.md (SHA256 `4aacd155…`) and task `opencode-beads-8fl` as captured in the packet. It does not approve any implementation, release or publication. - -I found no material spec, behavior, authority or completeness issue that would change the decision. The plan fits the current source: it is a small extension of the existing sync mechanism, not a new architecture. - -## Spec and behavior findings (none blocking) - -**1. Mechanism and schema: coherent and proportionate.** -- Current sync writes `metadata: { ocBeadsSync: { version: 1, instructions } }` (`src/workflows.ts:136-139`). The reader expands it once and strips the key (`src/workflows.ts:92-106`). The plan adds one key, one writer and one renamed helper on top of this. -- **No metadata clobbering.** `CommandInvocation.prompt` is a `PromptInput.Prompt`, and that type has no `metadata` field. So spreading `...input.prompt` and then setting `metadata` overwrites nothing. Prompt-hook edits to `SessionPrompt.metadata` happen after admission and are untouched. -- **Dual-key handling is idempotent in every combination:** - - Both keys valid: generalized wins and both keys are stripped. - - Generalized malformed, legacy valid: legacy expands, and the malformed key stays and is inert on a second pass. - - The reverse case works the same way. -- **Provider serialization (actual behavior, not speculation):** the existing local Responses harness test sends unexpanded stored history with `ocBeadsSync` metadata. It asserts that neither `ocBeadsSync` nor `Invoked command:` appears in the outbound request (`tests/host.test.ts:1037-1039`). The serializer drops message metadata, so leftover unknown or malformed metadata is not a provider leak. -- **Hook placement:** expansion stays before the location and eligibility early returns (`src/host.ts:337, 378`), as the plan states. Nothing else in `host.ts` needs to change. - -**2. Command semantics: preserved.** -- All per-command authority lives in the static `WORKFLOWS` purpose strings plus the shared `common` block (`src/workflows.ts:15-45, 115-124`). This includes: - - restore display-only unless `--apply` - - compact `--auto`/`--dolt` mode authority - - stats using `bd status` - - QuickStart, init, template and delete/import/rename-prefix limits -- The plan moves these bytes into the snapshot unchanged and adds no parsing. -- **Inventory:** 30 unique names, matching the canonical spec's "exactly 30" (`openspec/specs/workflow-access/spec.md:35`). -- **Exceptions:** only diagnostics has dynamic content, built from a runtime report (`src/workflows.ts:143-155`). It is correctly the one retained exception. No other command, including prime, needs one. -- **Canonical spec:** the "invoked name, requested outcome and any literal details" scenario (`spec.md:17`) is still met in the effective context. - -**3. Compaction cue: sufficient.** -- The proposed sentence replaces `src/guidance.ts:76`. Its "unresolved inputs or explicit modes" wording covers `--apply`, `--auto` and `--dolt`. -- Eligibility gating stays as is (`src/host.ts:379`). -- The compaction request itself sees the expanded snapshots, so the summarizer gets full instructions. Retention stays semantic and makes no verbatim claim. - -**4. Task 8fl: correct.** -- One cohesive record: status `blocked`, no assignee, `implementation_authorized: false`, a `blocks` dependency on 5jm, and an approval-plus-dispatch gate. -- It names the local uncommitted reference (not HEAD), says no release is required, and states that the parent owns sync closeout. -- **Spec sequencing:** the plan requires a scoped change before any product edits. That change must replace the active delta's "All other command outputs and descriptions SHALL remain unchanged" (`openspec/changes/compact-sync-command-context/specs/workflow-access/spec.md:7`). This is the right planning and dispatch boundary. - -**5. Tests and evidence: adequate.** -- They reuse the existing five-case results, replay tests and serializer harness, and add one justified smoke test: `update` through native code mode, a path sync never exercised. -- No benchmark or command-by-model test matrix. - -## Standards and proportionality findings - -None material. The changes are limited to `workflows.ts`, two helper calls in `host.ts` and one sentence in `guidance.ts`. No new hooks, model calls, pending state or registry redesign. Having sync write the generalized key keeps a single writer, and the legacy reader is a small cost for old histories. - -## Optional observations (non-blocking) - -1. **Fixture reconciliation mechanism.** `tests/fixtures/non-sync-command-baseline.json` stores hashes of `{description, sent}` from a call made with details (`tests/workflows.test.ts:305-308`). It does not store the bare instruction bodies the plan says to compare against. Two ways to get that baseline without "blind regeneration": - - Rebuild the old payload from each new snapshot (`snapshot + "\n\nLiteral user details:\n" + fixedText` plus the same native fields) and assert it matches the **existing** hash unchanged. - - Or capture bare-body digests from the reference source before editing. - - Spelling out one of these in the design would remove ambiguity for the implementer. -2. **Spec ordering.** If the sync change is still active, a new delta can't use MODIFIED against a requirement that isn't canonical yet. That would leave the implementer to redo the "unchanged" constraint by hand. Archiving the sync change first is the cleaner path. The plan already delegates this choice to the parent. -3. **Base check durability.** The base check relies on a manifest under `/opt/data/cache/scratch/…`. Recording that manifest's digest in 8fl or the evaluation doc would keep the check usable if scratch is cleaned up. Also, 8fl's acceptance text omits the design's "or parent-accepted equivalent integration" clause, which matters if closeout changes any bytes. -4. **Legacy reader necessity.** If sync and the migration ship together, no released build ever wrote `ocBeadsSync`. The legacy reader then only serves local canary and disposable histories. It is cheap, so keeping it is reasonable while the base order is undecided. -5. **Test updates.** Existing assertions on `ocBeadsSync` and the old cue (`tests/host.test.ts:954, 972, 1008, 1024`; `scripts/test-package.ts:340`) need updating. They fall within the listed test files, but `host.test.ts:972` is a cue assertion that the plan only mentions for `guidance.test.ts`. - -## Evidence and limitations - -- **Read:** the packet's `plan.md`, `implementation-bead.json` (including the embedded 5jm record), `parent-inventory-check.json` and `command-inventory.json` dispositions. -- **Read in source:** `src/workflows.ts` (all), `src/host.ts:320-389`, `src/guidance.ts:70-77`, the plugin session/command type definitions, the canonical `workflow-access` spec slices, the active sync delta spec, and the relevant test slices (`tests/host.test.ts:940-1048`, `tests/workflows.test.ts` baseline usage). -- **Not run:** nothing. No tests, inventory factory, smoke or live probes. I didn't verify the 182-path hashes myself or reread the evaluation and plan docs. -- **Status:** implementation stays blocked pending owner approval, explicit dispatch, and the parent's choice of base and spec order. The future tests and the `update` smoke haven't been run, and no results are claimed. \ No newline at end of file diff --git a/docs/reviews/opus-workflow-context-source-79l.md b/docs/reviews/opus-workflow-context-source-79l.md deleted file mode 100644 index 95db918..0000000 --- a/docs/reviews/opus-workflow-context-source-79l.md +++ /dev/null @@ -1,77 +0,0 @@ -## Verdict: **READY** - -This verdict covers the 13-path candidate (diff SHA256 `344241836a8b…`) and the evidence for `opencode-beads-79l` / `8fl`. It is a separate gate from my earlier review. That READY (plan `4aacd155…`) covered the plan and task structure only, not source. I also note that the parent accepted and closed 8fl before the owner asked for this review; my verdict doesn't make that closure retroactive. - -I found no material correctness, completeness or authority issue. READY does not authorize a commit, archive, publication or activation. - -## Spec and behavior findings (none blocking) - -**1. Admission is unchanged apart from presentation.** -- All 29 `WORKFLOWS` callbacks now use the code path sync already used (`src/workflows.ts:133-141`): the `...input.prompt` spread, `sessionID`, `delivery`, `text` and one `metadata.ocBeadsWorkflow` value. -- Visible text is built with no trimming or parsing. Bare `/oc-beads:<stem>`, a space before single-line text, a newline before text containing `\r` or `\n`. -- `PromptInput.Prompt` has no `metadata` field, so the write overwrites nothing. Diagnostics is unchanged and still dynamic (`src/workflows.ts:143-155` in the reference). The table test asserts diagnostics is never called during workflow admission. - -**2. The snapshot reader is correct and idempotent** (`src/workflows.ts:92-110`). -- It checks the keys in order `["ocBeadsSync", "ocBeadsWorkflow"]` and keeps the last valid one, so the generalized key wins when both are valid. Every valid key is deleted from the metadata clone. -- A malformed key stays and expands nothing on a second pass. Unrecognized metadata, foreign keys and non-user messages are left alone; the code returns early before reassigning, and the tests check this with `toBe(message)`. -- Snapshots are never rebuilt from the current `WORKFLOWS`. The legacy path uses the stored text. -- All five precedence combinations, including both one-sided malformed cases, are tested with copy-immutability and replay checks (diff lines 673-698). - -**3. Hooks and the summary cue.** -- `host.ts` only renames the import and the two calls (`:2, :337, :378`). Expansion still runs before the location and eligibility returns. -- No hooks, title/generate expansion or model calls are added. The host test still asserts the registered hooks are exactly `["compaction","context"]`. -- The summary cue changes one sentence (`src/guidance.ts:76`). - -**4. Semantic fixture preservation is honest.** -- The baseline test (diff lines 742-760) rebuilds the old rich payload as `{...native, text: snapshot + "\n\nLiteral user details:\n" + ORIGINAL fixed text}`. Destructuring keeps the original key order, so it matches the **unchanged** digests in `baseline.commands`. -- That proves byte equality of every migrated instruction body and description, plus the native fields. Diagnostics is hashed directly. The sync instruction digest is still checked (`tests/host.test.ts`, diff line 491). - -**5. Command-specific authority is unchanged.** -- Purposes and the common text are byte-identical (point 4), and the snapshot contains no actor or session ID (asserted). -- Restore `--apply`, compact `--auto`/`--dolt`, the stats/QuickStart wording, the 17 links and the eleven operations are untouched in source. -- Spec delta scenarios added for legacy precedence and authority contracts (diff lines 196-207) match the code. - -**6. Replay and serialization coverage.** -- The mixed history (show / update / compact / legacy sync, an interleaved assistant turn, foreign metadata, prepared content) is serialized through the real local Responses serializer. -- The test checks one snapshot per invocation and no routing keys. It also checks stable output across primary, compaction, a second pass and replay, the current-turn details, immutable storage, and that unexpanded auxiliary history carries no snapshot or keys. - -**7. Packaged smoke test** (`scripts/test-package.ts`, diff lines 238-300). -- Each workflow's exact metadata key set, version, installed skill path and resource suffix are checked, and the resource file must be readable. -- Both the generalized and legacy keys go through both hooks, with idempotence and storage checks. The 29 × 4 visible-text forms, including CRLF and whitespace-only, are covered. - -## Evidence sufficiency: **sufficient for the promised scope** - -I read the raw files, not only the pass flags: -- **Persisted message:** compact visible text plus exactly one `ocBeadsWorkflow` v1 snapshot. It contains the installed-archive paths and no actor. -- **`native-operations.json`:** four code-mode `execute` calls (search → `beads.get` → `beads.note` → `beads.get`). -- **`bd-calls.json`:** exactly one write, `update wctx-rxu --append-notes … --actor opencode:workflow_eval:6cce9201edd5 --sandbox`, exit 0. Readbacks before and after show the original note plus one append, with author and assignee preserved. -- **Permission:** the `once` decision has `save: []` and source `call_7e4bfd7d…`, matching the note call ID. -- **Snapshot counts:** 1,0,0,0,0,0 across six primary requests, zero auxiliary, no retries. - -The original guard-blocked attempt is correctly kept as non-passing history. - -**Limits, stated accurately in the evaluation doc:** -- This is one prescriptive, fully specified sample. The prompt itself named `beads.note` and `beads.get`. -- It shows that compact admission plus effective instructions supports a bounded native code-mode write. It does not show that the model picks tools on its own, and it doesn't cover the help/missing-input/mode distinctions for the other 28 commands. -- Those distinctions rest on the byte-identical instructions (point 4) and the reused five-case sync evidence. That is consistent with the approved plan, and no broader claim is made. - -## Standards and proportionality findings - -None material. -- **Code size:** one shared writer and one ~15-line reader, replacing the sync special case. Net source is smaller than the reference. -- **Scope:** no framework, pending state, parser or extra calls. -- **AGENTS.md style:** JSDoc kept on the renamed helper, strict typing is respected, and the actor policy is preserved (snapshot has no actor; the actual `--actor` was used at execution). -- **Sequencing:** the parent's in-place extension of the active spec package fits the conditional option in my plan review. The five completed sync tasks are kept and 4.1–4.5 are appended. - -## Optional observations (non-blocking) - -1. **Stale design statement.** `openspec/changes/compact-sync-command-context/design.md:39` (diff line 118) still says tasks 4.1–4.5 "remain unchecked for parent acceptance", but `tasks.md` now marks them `[x]` as parent-accepted. A one-phrase doc fix before archive would remove the contradiction. -2. **Normative wording.** The "Deliberately migrated workflow presentation" scenario (spec delta, diff lines 163-167) is phrased as history ("WHEN the sync-only implementation is extended…"). When the change is archived into the canonical spec, wording it as a present-tense rule would read better. -3. **Duplicate `prime --full` in the sample.** `bd-calls.json` shows `prime --full` running twice, once at the start and once after the write. This is existing cache-invalidation behavior, not part of this change; it's only noted as context for token figures. - -## What I inspected vs. did not execute - -- **Inspected:** the full `candidate.diff` (796 lines), `manifest.json`, and the live `src/` grep confirming the reader, writer and hook calls match the diff. Also `AGENTS.md`, and from `evaluation-corrected/`: `evidence-review.json`, `persisted-user-message.json`, `bd-calls.json` and `native-operations.json`. -- **Not opened:** `native.jsonl`, the UI PNGs, `implementation-bead.json`, `preflight.json`, the custody files, or the `candidate/` and `reference/` copies file by file. -- **Not executed:** nothing. No tests, typecheck, package smoke, OpenSpec validation or hashing. The 212 tests / 11,696 assertions, strict 4/4, exact-archive smoke, the 183/167/239 hash matches and the archive checksum `cfb14410…` are the parent's results, which I did not reproduce. -- **No changes made:** no candidate, source, Beads, proof or operator state was modified. \ No newline at end of file diff --git a/docs/reviews/upstream-plugin-test-gap-assessment.md b/docs/reviews/upstream-plugin-test-gap-assessment.md deleted file mode 100644 index 079cd14..0000000 --- a/docs/reviews/upstream-plugin-test-gap-assessment.md +++ /dev/null @@ -1,46 +0,0 @@ -# Upstream plugin test gap assessment - -## Scope and evidence - -Parent source comparison against exact OpenCode 2.1.1 commit `ba546ec1598a70db2570e9c6258028d955ba8f58`, the selected qualification target. This is not an independent Opus verdict or executed acceptance result. - -The recursive upstream GitHub tree was complete (`truncated: false`). Twelve selected first-party test files were fetched and their Git blob hashes verified against that tree. The survey covered core plugin command, skill, permission-assert, Promise-tool, supervisor, supervisor-reload, session-compact and module tests; SDK host resolution; core plugin lifecycle and failure isolation; and subagent observer lifetime. Relevant assertions were compared with local workflow, continuity, host and packed-package tests and the current OpenSpec tasks. Upstream tests were inspected, not executed; no installed host or model was exercised. - -The preceding Claude Beads comparison found relevant layout/setup and prime tests alongside the CLI rather than a separate test suite in the selected plugin subtree. This follow-up checks OpenCode-owned integration contracts, not test-count parity or a claim of superior thoroughness. - -## Case crosswalk - -- **Command registration and invocation — locally covered; installed dispatch pending.** Upstream checks effective membership, execution, literal arguments, attachments and queue/steer delivery. Local workflow tests and package smoke exercise the actual registration callbacks and bodies through a fixture host. Those fixtures do not qualify actual installed dispatch. -- **Skills and package entrypoints — locally covered at the package boundary; installed access pending.** Upstream checks effective skill registration and root/server resolution. Local smoke resolves both exports, verifies packaged resource bytes and all 16 supporting links, registers guidance and diagnoses missing resources. Task 6.2 already owns installed discovery and external-directory ask/deny. Generic TUI/RPC and conditional-export resolution belong upstream. -- **Cleanup and interruption — plugin responsibilities covered in fixtures; host behavior pending.** Local tests cover owned disposal, idempotent cleanup, partial-setup cleanup, process/approval cancellation and ignored late results. Upstream exercises host interruption reaching Promise executors. Tasks 1.1/4.2 retain the relevant live signal/permission checks. -- **Permission outcomes — generic propagation covered; concrete host variants pending.** Upstream distinguishes blocked, correction-with-feedback and explicit decline. Local `tests/continuity.test.ts` verifies identical rejection propagation and no rejected target operation. `src/continuity.ts` leaves permission assertions outside the CLI-result catch. No implementation defect was demonstrated; actual host outcome delivery remains qualification work. -- **Compaction — intentionally different API usage.** Upstream plugin compaction tests admit a compaction request. This plugin does not invoke that API; it adds reference-only guidance while preserving host compaction payloads. Keep the existing noninterference fixtures and installed recovery checks rather than porting unused-API tests. -- **Supervisor, module loader and background notification infrastructure — host-owned or outside selected scope.** Do not duplicate reload scheduling, dependency redirection, policy admission, failed-generation isolation or moved background-child notification matrices. The selected task flow uses normal blocking child return; task 4.2 already owns relevant failure/stop/handoff checks. - -## Owner-approved refinements - -### Permission correction and decline — task 1.1 / opencode-beads-vuy.2 - -Include correction with feedback and explicit decline alongside the existing allow/ask/deny probe. Verify preservation of the actual host outcome and correction feedback, no rejected target operation, no false success and no automatic retry. Use the existing minimal disposable-host probe, not an adapter replica or a new permission translator. - -**Evidence state: unexecuted.** The generic rejection fixture and source inspection are not actual host qualification. - -### Installed unload/reactivate — task 6.2 / opencode-beads-vuy.9 - -Include one actual installed unload/reactivate round trip. Observe owned entry removal and restoration of the expected commands and skill under native user-override precedence; one eligible request must receive one Beads context injection, with no late result injected from pending old-generation work. Registry rebuilds, imports and disposer fixtures are not substitutes for actual host lifecycle evidence. No reload matrix or supervisor rewrite is selected. - -**Evidence state: unexecuted.** Existing source/package acceptance is preserved, not retroactively relabeled as live success. - -## Authority and disposition - -Matt approved incorporating these two cases into existing acceptance. They do not create tasks, change checkmarks or dependencies, reopen accepted source work, block independent task 6.1, or authorize host provisioning, model experiments, activation, dispatch, publication or release. Existing disposable-host and execution authority gates remain in force. Intended behavior lives in the workflow-access delta; exact cases are in tasks 1.1/6.2 and their existing Beads owners. - -## Representative pinned sources - -- [Core plugin lifecycle, unload and replacement command on reload](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/test/plugin.test.ts) -- [Permission outcomes for Effect and Promise plugins](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/test/plugin/permission-assert.test.ts) -- [Promise-tool interruption and error propagation](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/test/plugin/promise-tool.test.ts) -- [Command registry and invocation contract](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/core/test/plugin/command.test.ts) -- [SDK host entrypoint resolution](https://github.com/anomalyco/opencode/blob/ba546ec1598a70db2570e9c6258028d955ba8f58/packages/plugin/test/host.test.ts) - -Detailed retrieval inventories remain supporting scratch evidence under `/opt/data/cache/scratch/opencode-v2-test-gap-assessment/`; the pinned links and this disposition are the repository-owned record. diff --git a/docs/sync-native-context-evaluation.md b/docs/sync-native-context-evaluation.md deleted file mode 100644 index ec56a0a..0000000 --- a/docs/sync-native-context-evaluation.md +++ /dev/null @@ -1,298 +0,0 @@ -# Sync native context evaluation - -Historical reference: this document preserves qualification of the original sync slice and its later UX polish. The accepted generalization and final implementation review are recorded in [workflow native context evaluation](workflow-native-context-evaluation.md); original sample/archive identities below remain unchanged. - -This local uncommitted candidate implements only sync presentation/context from -baseline `76549cff2558404f8b855b8708d13ac81c52f138`. Implementation Bead: -`opencode-beads-9ux`, executor `codex:oc-sync-sol`. Source and bounded corrected-runtime -checks are parent-accepted. This is not the published beta.3 archive. - -## Current owner-authorized presentation follow-up - -After the owner demonstrated a completed explanation-only canary turn on Zeus, -the owner approved removing the implementation-facing `Literal user details:` -heading from new sync history. Single-line free text now follows the command on -the same line; multiline text follows on a new line, preserving the exact input, -including whitespace and line endings. This is presentation only: no help-keyword -parser, instruction-snapshot change, hook change or non-sync migration. - -The parent implemented this narrow follow-up directly. The regression first failed -on `/oc-beads:sync explain`, then passed after the one-line product correction. -Fresh gates: 210 tests / 3036 assertions, typecheck, scoped strict specification -validation and exact-archive installed package smoke passed. The 29 other command -baseline digests and static sync instruction digest remain unchanged. Actual local -provider serialization remains 2738 → 2784 characters for the bare-sync fixture; -the three-sync fixture is now 7858 → 7944, rather than the original 7996, because -two generated free-text headings were removed. These are character observations, -not token-cost measurements. - -New local archive: `opencode-beads-sync-canary-a3945401.tgz`, SHA256 -`a3945401eecee09a9370d308e502eddae3aeed5a909d50e7b34281b6c5701098`. -Evidence is in the implementation scratch directory's `ux-followup/`; the initial -RED observation is `ux-followup-red.log`. No new genuine model run or Zeus -installation was performed for this small follow-up. The original archive and -independent review/runtime packets below are retained unchanged and apply to their -original bytes, not this revised artifact. No commit, push, release or shared -service change is implied. - -## Original reviewed candidate: parent-verified status - -The parent accepted the source and deterministic checks after direct diff review -and independent reruns: 210 tests, typecheck, the exact sampled archive package -smoke, strict scoped/global specs, baseline fixture comparison and protected hashes. -All five source/runtime task markers are parent-reconciled. The original interrupted sample remains historical and -incomplete. The owner separately approved one harness-only correction and one -additional sample: the parent independently verified its non-interrupted final -report and observed compact native TUI entry, actual provider context and sync -result, convergence, unchanged sentinels, custody and operator fingerprints. -Product/source acceptance is unchanged; no release or task closure is implied. -No automatic retry occurred. - -Accepted inherited evidence is the beta.3 bounded action/explanation, denial, -missing-input and guide campaign described in -[command action evaluation](command-action-evaluation.md), including its corrected -R1–R5 result and user-confirmed ordinary sync behavior. Those cases are not rerun. -The accepted sync-only design and READY review establish the intended approach; -they do not themselves prove runtime behavior. - -New deterministic checks capture meaningful prompt RED/GREEN and registered-hook -RED/GREEN, literal/native input preservation, request-copy immutability and -idempotence, serialized native replay, compact summary recent-context, unload, -location-return ordering and unchanged 29-command baseline digests. Actual -`@opencode/ai` 2.1.1 Responses serialization is captured through a local endpoint; -its fixture responses are not model inference or semantic action evidence. - -| Provider fixture | beta.3 serialized characters | Candidate serialized characters | -| --- | ---: | ---: | -| One sync plus interleaved assistant | 2738 | 2784 | -| Three syncs, interleaved assistant, native replay | 7858 | 7996 | - -The +46 characters per sync are exactly the visible invocation and additional -text-part framing. Static instructions match the baseline digest; each tagged -message contributes one snapshot, the routing metadata never serializes, the -current turn retains its instructions and unchanged consecutive expansions are -byte-stable. Unhooked title/generate serialization stays compact without action -snapshots; existing hook registration remains exactly primary context/compaction. -Character counts are payload-size observations, not token usage or billing. -The compaction cue adds 113 text characters (including its newline) separately for semantic continuity. -Native storage can contain another snapshot copy after compaction, while native -estimation from visible text can undercount it. No cache or price savings are -claimed, and actual summary quality is not inferred from a guidance assertion. - -## Original prescribed sample: historical incomplete acceptance - -The one genuine sample used pinned OpenCode 2.1.2, binary SHA-256 -`22636c800ba6c8dc5353e264183bb3927725d824cba412f007dea9c694740f52`, -Beads 1.3.1 and local unpublished beta.3-version candidate archive SHA-256 -`2031a1afc6f27dfd3530deead2be215cfaa7f0429cb0668a6de84d6c8a47b109`. -The native host installed every archive file unchanged through the public -entrypoint and registered 30 commands and 17 resource links. It used genuine -`openai/gpt-6.1-sol/high` at `https://chatgpt.com/backend-api/codex`. -Session: `ses_e9c4752aeffeO5prp4cLaxHVnb`; executor: -`opencode:sync_eval:690d5b278e4a`. - -The ordinary command endpoint admitted one bare queued sync. Native prompt -observation and persisted user-message readback contain exactly `/oc-beads:sync` -with version-1 metadata. The first actual outbound provider frame contains the -exact snapshot once and the host-rendered actual actor/capability guidance, -without the routing marker or serialized second copy. Later frames use native -`previous_response_id` continuation and incremental tool outputs rather than -resending history; their zero snapshot occurrences are not missing context. -All four observed requests were primary requests; no auxiliary expansion or -extra plugin model call was introduced. Deterministic tests above separately -check full serialization and replay, not provider cache behavior. - -The model selected and received a real native permission approval for: - -```sh -bd sync --no-adopt --actor='opencode:sync_eval:690d5b278e4a' --sandbox --json -``` - -It ran exactly once in the owned `sample/repo` directory and returned exit 0, -`status: ok`, pulled/pushed true, one attempt and zero corrected rows. Independent -local and peer readback contained all three seeded IDs (`sctx-9nn`, `sctx-ter`, -`sctx-uae`). The peer pull was harness readback, not product repair. The unrelated -issue, file sentinel and configured remotes remained unchanged. - -**This original sample did not complete runtime acceptance.** After successful sync the model asked -for read-only `git status --short`. The reused narrow permission responder -rejected this command, which interrupted the native step before a final model -report. This is a harness-caused interruption, not demonstrated product failure. -The original runner's `passed: true` checks only CLI/convergence/sentinels; it -does not establish complete acceptance. The authoritative evidence review -records the missing final report. At that original handoff, no second sample, -continuation inference or permission-policy repair had been performed. - -A real owned TUI was connected to that same completed/interrupted session without -submitting a prompt. Its retained ANSI capture, decoded terminal screen and native -API readback show the sync output and interruption. The compact invocation was -above the captured viewport, so **that original capture did not verify the -visible compact UI**; persisted compact text was verified. Neither fixture rendering nor -an inferred screenshot is substituted for this missing observation. - -| Genuine primary request | Provider input tokens (including cached) | Cached input tokens | Output tokens | -| --- | ---: | ---: | ---: | -| 1 | 9281 | 0 | 19 | -| 2 | 12462 | 9088 | 172 | -| 3 | 21612 | 12288 | 73 | -| 4 | 21743 | 21504 | 20 | -| Observed interrupted-sample total | 65098 | 42880 | 284 | - -These are provider-reported observations for this single interrupted sample, -not an A/B comparison or subscription/billing proof. Character estimates above -are separate. Current native access was read through a read-only connection and -imported into owned disposable state with no refresh capability. No login, -refresh, operator database copy, billing fallback or operator mutation occurred. -Operator credential/file fingerprints matched before and after. Owned host/TUI -processes and listener exited; disposable credential-capable data/state were -removed, while sanitized raw evidence and disposable repositories were retained. - -## Owner-approved corrected sample - -The owner then approved exactly one corrected disposable sample in the same -Sol/high implementation session, limited to the harness and this evidence doc. -Current source custody is the parent's 16-path -`parent-source-reviewed-manifest.json` (SHA-256 -`3fce62c87ed6f26e7e5012382f93b2ea0e50b21d38485426106750fcd76b3bf5`), -with only this evaluation document subsequently permitted to change. All 164 -other protected paths and all 31 members of the original candidate archive -matched before and after the corrected run. No product prompt, runtime, test, -baseline fixture, dependency, README, changelog, spec or task marker changed. -The original `sample/` packet's 234 files and historical `final-candidate.json` -remained byte-identical, including the original narrow `passed: true` result. - -New evidence lives exclusively in -`/opt/data/cache/scratch/oc-beads-sync-context-implementation/evaluation-corrected/`. -The copied permission fixture added only: - -```python -if argv == ['git', 'status', '--short']: - return case == 'R1' -``` - -This check follows existing shell-syntax rejection and tokenization. The new -RED test failed against the unchanged copy; GREEN passed six tests, including -existing token-aware `--no-adopt` acceptance and denials for other Git commands, -extra status options, destructive/unrelated operations and shell chaining. -Native product permissions were unchanged. The runner also requires the latest -completed assistant to have `finish: stop`, nonempty final text and no error, -plus observed compact native UI, alongside CLI/convergence/sentinel checks. -Three deterministic harness tests verify that CLI-only or interrupted results -and missing UI cannot pass. The narrow fixture diff and runner diff are retained. - -The corrected run reused the exact archive SHA-256 -`2031a1afc6f27dfd3530deead2be215cfaa7f0429cb0668a6de84d6c8a47b109` -and the same pinned 2.1.2 host binary above. Its native installed public entrypoint, -all archive files, 30 commands and 17 resource links were verified again. Fresh -isolated HOME/XDG/store/local-file remote and two divergent replicas held base -sentinel `sctx-3gh`, local-only seed `sctx-71r` and remote-only seed `sctx-ajz`. -These setup writes and peer readback were separately attributed harness work, -not product initialization or repair. The model route was genuine native -`openai/gpt-6.1-sol/high` at `https://chatgpt.com/backend-api/codex`. -Session: `ses_e9c3431c3ffeZoDiGaIEL2RB7C`; actual executor: -`opencode:sync_eval:b14ef2bcbb4a`. - -One ordinary bare queued command produced one native prompt admission. Persisted -user text is exactly `/oc-beads:sync`, with version-1 instruction metadata. The -first actual provider-bound frame contains the exact static snapshot once plus -actual executor context, and no routing marker or duplicate snapshot. Later -frames use native `previous_response_id` incremental continuation. Five primary -requests were observed, with no auxiliary request or added plugin model call. -The actual selected direct-shell operation received native approval once: - -```sh -bd sync --no-adopt --actor='opencode:sync_eval:b14ef2bcbb4a' --sandbox --json -``` - -It executed exactly once in the owned `evaluation-corrected/repo` directory, -returning exit 0, `status: ok`, one attempt, pulled/pushed true and zero corrected -rows. The model subsequently requested the exact observed read-only -`git status --short`, received one approval under the corrected fixture, and -completed that read. Both replica readbacks then contained all three seeds; -the unrelated issue, sentinel file, staged/untracked files and remote -configuration were unchanged. No manual product repair occurred. - -The owned native TUI started before command admission and was read continuously. -Its real user-message viewport displayed `/oc-beads:sync` with no generated -action/authority body. `native-ui.ansi` retains the raw sanitized terminal stream; -`native-ui-compact.txt` records the decoded 160×60 viewport and -`native-ui-compact.png` faithfully renders those captured terminal cells. -This is an image of the actual ANSI-derived native viewport, not an invented -mock screenshot or a persisted-text substitute. The end-state viewport/image -also shows the successful sync, permitted Git read and final model report. -No navigation was needed, and the TUI capture submitted no text or model prompt. - -The latest assistant completed with `finish: stop` and no error. Its report -matches the observed CLI and sentinel evidence: - -> Dolt-remote synchronization succeeded using `--no-adopt`, the actual executor actor, and `--sandbox`. -> -> - Pulled and pushed in one attempt. -> - No blocked-state corrections needed. -> - No adoption or manual repair performed. -> - Existing staged/untracked files left untouched. - -| Corrected primary request | Provider input tokens (including cached) | Cached input tokens | Output tokens | -| --- | ---: | ---: | ---: | -| 1 | 9300 | 0 | 19 | -| 2 | 12525 | 0 | 176 | -| 3 | 21683 | 12544 | 66 | -| 4 | 21807 | 9216 | 37 | -| 5 | 21900 | 21760 | 60 | -| Observed corrected-sample total | 87215 | 43520 | 358 | - -These provider-reported figures describe this one corrected sample only. They -are separate from deterministic payload character counts and are not an A/B -comparison, savings claim or subscription/billing measurement. The corrected -sample resolves the two prior observations without relabeling the interrupted -sample as successful. - -Current native access alone was used, imported into disposable state with an -empty refresh capability. No refresh, login, whole operator database copy, -billing fallback or operator state/config/install/service change occurred. -Before/after operator credential and file fingerprints matched. Owned TUI and -private host exited, the listener closed, no process remained under the corrected -scratch cwd, and disposable credential-capable data/state were removed. Raw -sanitized evidence, exact archive reference and disposable replicas were retained. -No additional sample or continuation inference was attempted. Product/source -hashes still match the accepted candidate; only this evidence document changed. -Parent verified this corrected runtime sample and reconciled task 3.1; closure -and any further dispatch/publication remain separate. - -The corrected packet's `semantic-evidence-review.json` binds native/model/actor, -provider context, UI, permission, argv/cwd/result, final report, convergence, -usage and custody checks. `permission-fixture.diff`, `permission-red.log`, -`permission-green.log`, `runner-correction.diff`, `qualification-checks.log`, -`R1-provider-wire-inputs.json`, `R1-provider-usage.json`, -`R1-persisted-user-message.json`, `R1-final-report-check.json`, native traces, -operator snapshots and UI artifacts retain the detailed evidence. - -## Local verification and handoff - -Prompt and registered-hook RED/GREEN logs, actual serializer captures and the -original and corrected runtime packets are retained under -`/opt/data/cache/scratch/oc-beads-sync-context-implementation/`. -`sample/semantic-evidence-review.json` distinguishes verified action/context -checks from incomplete final-report/UI acceptance; -`sample/semantic-result.json` is the narrower original mechanical runner result. -`sample/R1-provider-wire-inputs.json`, `R1-provider-usage.json`, -`R1-persisted-user-message.json`, native events, permissions, argv/cwd/CLI captures, -replica readbacks and `native-ui-screen.txt` retain the underlying observations. - -The direct simplification review found the source limited to one sync branch, -one pure helper, two existing-hook calls and the selected sentence. There is no -new registration, dispatcher, state queue, CLI wrapper in product code or change -to authority/tool boundaries. Final source/package/spec/protected checks are -recorded in the implementation Bead. Final typecheck passed; `bun test` passed -210 tests with 0 failures (2964 assertions); installed package smoke passed using -the exact sampled archive/checksum. Named strict validation passed and global -strict validation passed all four items. Whitespace passed, all 164 protected -paths matched baseline, and the generated comparison preserved all 29 other -command payloads/descriptions. No bd contract campaign was run for this -presentation/context-only change. All five task markers are parent-reconciled; -the bounded runtime sample is accepted, and canonical specs and -archives are unchanged. Full source gates were not repeated during this -qualification-only correction: product and accepted source hashes stayed fixed. -The corrected sample supplies the previously missing runtime observations, -verified independently by the parent. The candidate remains local and uncommitted; -closure, canonical archival and any publication remain separate. diff --git a/docs/sync-native-context-plan.md b/docs/sync-native-context-plan.md deleted file mode 100644 index a19801f..0000000 --- a/docs/sync-native-context-plan.md +++ /dev/null @@ -1,58 +0,0 @@ -# Sync native context design - -This source change implements only `/oc-beads:sync` from the parent-accepted -plan in `opencode-beads-ueb` and READY review `opencode-beads-ag4`, under current -implementation authority `opencode-beads-9ux`. Baseline: -`76549cff2558404f8b855b8708d13ac81c52f138` (published beta.3). -The completed change is [compact-sync-command-context](../openspec/changes/archive/2026-10-22-compact-sync-command-context/proposal.md). - -This is the historical sync-only design, including the earlier visible details heading. The final natural presentation and all-workflow generalization are described in [workflow native context evaluation](workflow-native-context-evaluation.md) and the archived design. - -One ordinary native prompt carries `/oc-beads:sync`, followed by an exact -`Literal user details` block when nonempty. Native files, agents, skills, -prompt preparation and queue/steer delivery stay with that admission. A -version-1 `ocBeadsSync` metadata record stores the unchanged static action, -authority and installed-resource instructions, excluding literal details and -runtime actor/capabilities. This metadata is durable and exportable, not secret. - -The existing primary and compaction hooks restore the snapshot into a user -text part on a transient message copy and remove only their routing key from -that copy. They run after unload protection and before context eligibility or -location returns. Foreign content/metadata, roles and IDs survive; absent or -unknown markers and unmarked beta.3 history remain untouched. The current -executor actor, capabilities, permissions and holds still come from existing -request handling. Repeated application to the request copy is idempotent; -serialized replay uses the stored record without a process-local queue. - -Native-window compaction retains lowered metadata, so the next primary hook -expands retained messages once. Summary recent-context is rebuilt from visible -stored text and stays compact. One sentence in existing compaction guidance asks -for an active sync's outcome and applicable authority limits; summary retention -is semantic, without a verbatim guarantee or replay repair. The plugin must -be active to restore compact history. Title/generate have no expansion hook. - -Native admission, scheduling, interruption, cancellation, revert and resume -remain host-owned. An ambiguous failure propagates without retry. Each callback -submits one prompt; externally repeated callbacks have no new exactly-once -promise. No auxiliary model call, synthetic pair or historical operation is -re-admitted. Bare sync and explicit explanation retain beta.3 semantics: -permissioned `bd sync --no-adopt`, existing configuration, actual actor and -applicable sandbox; no inferred adoption, provisioning or manual repair loop. - -The other 29 command descriptions/submissions are checked against one small -generated SHA-256 fixture from baseline source using fixed inputs and resource -paths. Hashes keep the regression fixture small without a handwritten corpus. -Provider tests additionally pin the original static sync instructions, capture -real Responses serialization through a loopback endpoint, compare one and three -sync messages with an interleaved assistant and serialized native replay, and -assert stable expansion, current instructions, one snapshot and absent routing -metadata. These are deterministic serializer tests, not genuine model behavior. -See [evaluation](sync-native-context-evaluation.md) for results and the separate -bounded runtime sample. - -Instructions are relocated, not claimed cheaper. Each historical sync still -carries its own static snapshot as beta.3 already did. The extra visible command -line and text-part framing add small provider bytes. Native compaction may store -another snapshot copy; native estimation from visible text can underestimate -instructions. These are disclosed storage/estimation limitations, not reasons -for an upstream workaround. No billing or cache-hit benefit is inferred. diff --git a/docs/user-guide.md b/docs/user-guide.md index 20d40e7..0e78bdf 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -1,8 +1,10 @@ # opencode-beads user guide -Details behind the [README](../README.md) for the current 2.x line. Normative -behavior is defined by the canonical specs listed in the -[documentation index](README.md); this guide explains it for users. +User reference for `@snarkipus/opencode-beads` on OpenCode V2 and +Code Mode, expanding on the [README](../README.md). Normative behavior is +defined by the canonical specs listed in the [documentation index](README.md); +this guide covers current operation first and preserves historical upgrade and +compatibility records where needed. - [Installation details](#installation-details) - [Plugin options](#plugin-options) @@ -53,30 +55,35 @@ Plugin options use the object form: ## Upgrading -Upgrade OpenCode first: 2.2.0 requires `>=2.3.0 <2.4`. Then replace the existing plugin entry instead of stacking a second version, and check `/oc-beads:diagnostics`. OpenCode upgrades and plugin installation remain operator-owned actions; existing exact pins are never upgraded automatically. +Check the [supported versions](../README.md#supported-versions) first. If your host is outside the supported range, upgrade OpenCode before changing the plugin pin. Replace the existing plugin entry instead of stacking a second version, then check `opencode debug agents` and `/oc-beads:diagnostics`. OpenCode upgrades and plugin installation remain operator-owned actions; existing exact pins are never upgraded automatically. Existing exact 1.x and beta pins remain available. + +### Upgrading to 2.4.1 + +- **Host range:** 2.4.1 admits stable OpenCode `>=2.3.0 <2.4`, `2.4.1`, or `2.4.2` and requires `bd` `1.3.1` through `1.x`. +- **From 2.2.x, 2.3.x, or 2.4.0:** confirm OpenCode is on an admitted version, update the plugin pin to `@snarkipus/opencode-beads@2.4.1`, and verify with `/oc-beads:diagnostics`. +- **Legacy `autoMigrate`:** existing `true`/`false` values are accepted and ignored without warnings and can be removed from configuration. +- **Snapshot limitation:** upgrading does not reconstruct workflow guidance made inaccessible by the [known model-switch limitation](../README.md#known-limitations). + +### Upgrading to 2.2.0 + +Version 2.2.0 requires OpenCode `>=2.3.0 <2.4` and drops OpenCode 2.2 admission. - **Staying on OpenCode 2.2:** keep the released exact `2.1.0` pin, which retains `>=2.2.6 <2.3` support. Version 2.2.0 drops OpenCode 2.2 admission. -- **Staying on OpenCode 2.1:** keep the exact beta.5 pin rather than following `latest`; beta.5 retains its historical `>=2.1.1 <2.2` range. Stable 1.0.2 remains a historical option for its separately qualified host. +- **Staying on OpenCode 2.1:** keep the exact beta.5 pin rather than following `latest`; beta.5 retains its historical `>=2.1.1 <2.2` range. Stable 1.0.2 remains a historical option for its separately qualified host (`2.0.26`). - **From stable 1.0.2:** task execution now follows the explicitly authorized scope instead of imposing one Bead per invocation. Exact assignments still stop with their item; discovery never grants authority. - **Diagnostics rename:** Beta.1 used `oc-beads:status`; 2.0.0 uses `oc-beads:diagnostics`. Existing user overrides are not silently renamed, and an installation still pinned to beta.1 keeps `/oc-beads:status` until explicitly upgraded. -- **Snapshot limitation:** upgrading does not reconstruct workflow guidance made inaccessible by the [known model-switch limitation](../README.md#known-limitations). ## Why not `bd setup opencode` -**Do not run `bd setup opencode`.** That recipe is for OpenCode without this plugin. Beads assumes OpenCode has no hooks, so it replaces `bd init`'s minimal pointer with the full command reference, about 2 kB more on every request. With this plugin, `bd prime` arrives through OpenCode's hooks instead, as it does for Claude Code. If you already ran it, `bd setup opencode --remove` deletes the Beads section from `AGENTS.md` (prime still arrives through the plugin), or simply leave it: while prime is attached, the plugin replaces it in the request with a one-line pointer. +**Do not run `bd setup opencode`.** That recipe is a fallback for OpenCode without this plugin: Beads assumes OpenCode has no hooks and rewrites `bd init`'s minimal `AGENTS.md` pointer into a static ~2 kB command reference sent on every request. -Installing the plugin gives OpenCode the same integration that `bd setup claude` gives Claude Code: +With this plugin, responsibilities stay cleanly split on OpenCode V2's native surfaces: -| `bd setup claude` (Claude Code) | This plugin (OpenCode 2) | -| --- | --- | -| `SessionStart` hook runs `bd prime --hook-json`, also on resume and after compaction | The session context hook attaches `bd prime` to each request; it is refreshed after compaction and on resume after an idle gap | -| Minimal `CLAUDE.md` pointer to `bd prime` | `bd init`'s minimal `AGENTS.md` pointer; bd's full or Codex sections are reduced to a pointer while prime is attached | -| `--global` or project install | Global `~/.config/opencode/opencode.json` or project `.opencode/opencode.json` `plugins` entry | -| `--stealth` | `stealth` plugin option | -| `--remove` | Remove the `plugins` entry | -| `--check` | `opencode debug agents` lists `beads-task-agent`; a session's agent sees a `<beads-context>` block | +- **`bd init` owns project setup:** it initializes the workspace, creates the canonical shared `.agents/skills/beads` skill, and writes the minimal `AGENTS.md` pointer. +- **The plugin owns native OpenCode integration:** it attaches guarded `bd prime --full` context on eligible requests (refreshed after compaction and idle resume), registers the eleven permissioned `beads` code-mode operations, provides the 29 `oc-beads:<stem>` workflows plus `oc-beads:diagnostics` and the packaged `oc-beads` skill, and supplies the current scope-bounded `beads-task-agent`. +- **OpenCode configuration owns install lifecycle:** install globally (`~/.config/opencode/opencode.json`) or per project (`.opencode/opencode.json`), set options such as `stealth`, remove the `plugins` entry to unload, and verify with `opencode debug agents` and `/oc-beads:diagnostics`. -The [Claude Code parity matrix](claude-code-parity.md) is the historical setup-lifecycle record with live evidence and deliberate divergences. +If you already ran `bd setup opencode`, `bd setup opencode --remove` deletes the Beads section from `AGENTS.md` (prime still arrives through the plugin), or simply leave it: while prime is attached, the plugin replaces that managed block in outgoing requests with a one-line pointer without editing `AGENTS.md`. ## Context injection @@ -96,7 +103,7 @@ Diagnostics may read a bounded `.local_version` witness as an advisory recorded Follow the [Beads 1.3.4 upgrade procedure](https://github.com/gastownhall/beads/blob/7ef2fd05eb0cd3bdbde051f93cfc14ccf270cdde/docs/getting-started/upgrading.md), including backup with the old binary before upgrading and coordination for shared stores. The plugin does not run automatic migration, repair, bootstrap, update or synchronization commands. Agent-initiated administration still requires an explicit applicable request and normal permissions. Native open semantics do not grant extra administrative authority. -The old `autoMigrate` feature is obsolete: existing true/false values are ignored without warnings and can be removed from configuration. Diagnostic collection uses only `bd version`, `bd context --json`, and `bd hooks list --json`, cached state and bounded local file observations. Diagnostic children suppress native metrics and OTel export without changing user configuration. Hook status is native evidence: missing may mean unreadable or unresolved, an installed hook need not be a Beads hook, and a shim does not certify wrapper freshness. Root instruction counts and latest request counts are separate; retained managed text can be customization. The shared skill and effective registry indicate presence, not use. Context status, load time and the preceding CLI version are observations; external writes are not tracked. SQL health, historical maintenance and remote freshness are not checked. The submitted prompt follows the ordinary context lifecycle: native full prime may open or migrate a store. +The old `autoMigrate` feature is obsolete: existing true/false values are ignored without warnings and can be removed from configuration. Diagnostics does not check SQL health, historical maintenance, or fetch remote history; see the [diagnostics reference](diagnostics.md) for probe boundaries and row details. The submitted prompt still follows the ordinary context lifecycle: native full prime may open or migrate a store. ## Workflows and commands @@ -104,7 +111,7 @@ The plugin registers 29 `oc-beads:<stem>` workflows plus `oc-beads:diagnostics` **Command invocation:** an invocation itself requests the advertised bounded operation, including bare `/oc-beads:sync`. With sufficient inputs the agent uses permissioned tools and reports the actual outcome; `/oc-beads:sync explain` explains without syncing, and missing required inputs prompt focused clarification. Ordinary sync uses existing configuration and `--no-adopt`; a missing remote blocks without setup/adoption. Host permissions, project restrictions, actor identity, explicit modes and parent acceptance still apply. Guide/report commands produce their advertised artifact. This action-contract correction starts with beta.3; earlier beta artifacts do not contain this correction. -Invocations stay compact in history: single-line text follows the command, multiline text goes below it, and the full static instructions live in durable message metadata expanded by the primary and compaction hooks. Diagnostics renders and captures its observed report once the same way, including the loaded plugin name/version alongside the observed host version. The visible answer is relayed by the model and is not guaranteed to reproduce the captured report verbatim. Summaries retain semantic context, not verbatim snapshots, and this is not a token-savings claim. See the [workflow evaluation](workflow-native-context-evaluation.md) for history. +Invocations stay compact in history: single-line text follows the command, multiline text goes below it, and the full static instructions live in durable message metadata expanded by the primary and compaction hooks. Diagnostics renders and captures its observed report once the same way, including the loaded plugin name/version alongside the observed host version. The visible answer is relayed by the model and is not guaranteed to reproduce the captured report verbatim. Summaries retain semantic context, not verbatim snapshots, and this is not a token-savings claim. See the [workflow evaluation](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/workflow-native-context-evaluation.md) for history. Diagnostics shows compact Plugin / Beads tables with short rows including AGENTS Configured, Workspace (Located) and Recorded bd version. ✅ Healthy, ⚠️ Mismatch and ❌ Unhealthy reflect assessed checks; neutral rows remain visible without affecting severity or heading counts. Description evidence clipping alone does not make complete command-name membership partial. Immediately below the title and before any summary, DATE, VERSION and PATH appear in separate paragraphs: exact capture time, executing package name/version and observed native repository root (`cwd_repo_root`). A missing root is explicitly not observed; no path stripping or cwd fallback is used. The Beads directory remains in details. @@ -124,7 +131,7 @@ Each operation asks for its exact `bd` command with `save: []`, so "always" adds ## Task agent -The 2.0 integration uses scope-bounded task execution: +The current task agent (`beads-task-agent`) uses scope-bounded task execution: - The primary OpenCode thread retains planning context, decisions, and control. - An exact assignment or explicit one-bead mode stops with that item; read-only graph requests never authorize claims or writes. @@ -174,9 +181,9 @@ Remove the `plugins` entry to unload the plugin. Cleanup aborts owned context/pr | `bd` CLI | 1.3.1 through 1.x | 1.3.4 | | Bun (OpenCode host runtime) | >=1.3.14 | 1.4.2 | -Version 2.3.0 adds integrated diagnostics while retaining the same SDK, host range and native baseline. Its [diagnostics acceptance](diagnostics-acceptance-2026-11-15.md) combines deterministic/package checks with owner-reported normal-output canaries on exact OpenCode 2.3.0; it is not a new full model/host qualification campaign. +Version 2.3.0 adds integrated diagnostics while retaining the same SDK, host range and native baseline. Its [diagnostics acceptance](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/diagnostics-acceptance-2026-11-15.md) combines deterministic/package checks with owner-reported normal-output canaries on exact OpenCode 2.3.0; it is not a new full model/host qualification campaign. -Version 2.2.1 retains the same SDK, host range and qualified host baseline as 2.2.0. Its schema-hold removal is covered by deterministic, package and real Beads CLI contract checks; no new installed-host qualification is claimed. Version 2.2.0 type-checks against `@opencode/plugin` 2.3.0 and admits `>=2.3.0 <2.4`. Its [bounded native qualification](opencode-23-qualification-xwq.md) covers real launch, report freshness, stop and Code Mode reads on exact 2.3.0; repeated idle reports with outstanding work and cancellation during real bd execution were deferred and remain unexecuted. Admission does not qualify later patches. Earlier [2.2.6 qualification](opencode-22-qualification-5rj2.md) and [Terra qualification](opencode-terra-qualification-ug9.md) apply to their recorded candidates, not this 2.3 candidate. See the [OpenCode integration reference](opencode-sdk-contract.md). The supported Beads minimum is 1.3.1; the current CLI baseline was reviewed against Beads v1.3.4; see the [release review](beads-1.3.4-review-2026-11-09.md). The historical integration comparison remains Beads v1.3.1 (commit `c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c`), separately from CLI validation and the reviewed marketplace-main inventory. +Version 2.2.1 retains the same SDK, host range and qualified host baseline as 2.2.0. Its schema-hold removal is covered by deterministic, package and real Beads CLI contract checks; no new installed-host qualification is claimed. Version 2.2.0 type-checks against `@opencode/plugin` 2.3.0 and admits `>=2.3.0 <2.4`. Its [bounded native qualification](https://github.com/snarkipus/opencode-beads/blob/592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c/docs/opencode-23-qualification-xwq.md) covers real launch, report freshness, stop and Code Mode reads on exact 2.3.0; repeated idle reports with outstanding work and cancellation during real bd execution were deferred and remain unexecuted. Admission does not qualify later patches. Earlier [2.2.6 qualification](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-22-qualification-5rj2.md) and [Terra qualification](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-terra-qualification-ug9.md) apply to their recorded candidates, not this 2.3 candidate. See the [OpenCode integration reference](opencode-sdk-contract.md). The supported Beads minimum is 1.3.1; the current CLI baseline was reviewed against Beads v1.3.4; see the [release review](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/beads-1.3.4-review-2026-11-09.md). The historical integration comparison remains Beads v1.3.1 (commit `c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c`), separately from CLI validation and the reviewed marketplace-main inventory. ## Tracking upstream Beads diff --git a/docs/validate-parity-planning.py b/docs/validate-parity-planning.py deleted file mode 100644 index 37ad40b..0000000 --- a/docs/validate-parity-planning.py +++ /dev/null @@ -1,301 +0,0 @@ -"""Check this planning packet against pinned evidence; no network or store access. - -Usage: python3 docs/validate-parity-planning.py /path/to/parity-sources -Evidence layout: beads/ + beads-tree.json at inventory.commit; released/ + -native-release-tree.json at native_assessment.commit; minimum/ at minimum_commit; -native/ at development_commit; npm26/package and npm32/package extracted from -plugin-2.0.26.tgz / plugin-2.0.32.tgz. Download with gh api repo tarball/tree/ref -and the exact npm tarball URLs in the inventory, all outside the repository. -Current marketplace evidence: marketplace-main-commit.json, marketplace-main-tree.json -and marketplace-main/ at marketplace_main.commit. This validates source evidence and -planning coverage, not runtime contracts or model behavior. -""" -import base64 -import hashlib -import json -from pathlib import Path -import re -import subprocess -import sys -from collections import Counter - -repo = Path(__file__).resolve().parents[1] -scratch = Path(sys.argv[1]).resolve() -data = json.loads((repo / 'docs/claude-code-integration-inventory.json').read_text()) -report = (repo / 'docs/claude-code-integration-analysis.md').read_text() -native = data['native_assessment'] -assessment = (repo / 'docs' / native['document']).read_text() - -def verify_blob(path, entry, tree_entry): - content = path.read_bytes() - assert hashlib.sha256(content).hexdigest() == entry['sha256'], path - blob = hashlib.sha1(b'blob ' + str(len(content)).encode() + b'\0' + content).hexdigest() - assert blob == entry['git_blob'] == tree_entry['sha'], path - -beads_tree = json.loads((scratch / 'beads-tree.json').read_text()) -assert not beads_tree['truncated'] -expected = {e['path']: e for e in beads_tree['tree'] if e['type'] == 'blob' and - (e['path'].startswith(('plugins/beads/', 'internal/templates/skills/beads/')) or - e['path'] in data['support_paths'])} -actual = {e['path']: e for e in data['files']} -assert len(actual) == len(data['files']) == 73 -assert actual.keys() == expected.keys() -counts = Counter(e['category'] for e in actual.values()) -assert counts['command'] == 29 and counts['resource'] == 15 and counts['adr'] == 1 -for path, entry in actual.items(): - verify_blob(scratch / 'beads' / path, entry, expected[path]) - assert entry['owner_disposition'] in {'adapt', 'replace', 'preserve-external', 'reference-only', 'exclude', 'defer'} - assert entry['url'] == f"https://github.com/{data['source_repository']}/blob/{data['commit']}/{path}" - if entry['category'] in ('command', 'resource', 'adr'): - assert entry['url'] in report -skill = (scratch / 'beads/plugins/beads/skills/beads/SKILL.md').read_text() -links = set(re.findall(r'\]\((resources/[^)]+)\)', skill)) -resources = {str(Path(e['path']).relative_to('plugins/beads/skills/beads')) - for e in data['files'] if e['category'] == 'resource'} -assert links == resources -assert (repo / '.agents/skills/beads/SKILL.md').read_bytes() == ( - scratch / 'beads/internal/templates/skills/beads/SKILL.md').read_bytes() - -# Preserve historical identity separately; validate all current selected members. -current = data['marketplace_main'] -commit_evidence = json.loads((scratch / current['commit_evidence']).read_text()) -assert commit_evidence['sha'] == current['commit'] -current_tree = json.loads((scratch / current['tree_evidence']).read_text()) -assert not current_tree['truncated'] -assert current_tree['sha'] in {current['commit'], commit_evidence['commit']['tree']['sha']} -current_expected = {e['path']: e for e in current_tree['tree'] if e['type'] == 'blob' and - (e['path'].startswith(('plugins/beads/', 'internal/templates/skills/beads/')) or - e['path'] in data['support_paths'])} -current_actual = {e['path']: e for e in current['files']} -assert len(current_actual) == len(current['files']) == 74 -assert current_actual.keys() == current_expected.keys() -assert Counter(e['category'] for e in current_actual.values())['command'] == 29 -assert Counter(e['category'] for e in current_actual.values())['resource'] == 15 -assert Counter(e['category'] for e in current_actual.values())['adr'] == 1 -assert Counter(e['release_delta'] for e in current_actual.values()) == { - 'added': 1, 'modified': 16, 'unchanged': 57} -for path, entry in current_actual.items(): - verify_blob(scratch / 'marketplace-main' / path, entry, current_expected[path]) - assert entry['url'] == f"https://github.com/{current['repository']}/blob/{current['commit']}/{path}" - prior = actual.get(path) - expected_delta = 'added' if prior is None else 'unchanged' if prior['git_blob'] == entry['git_blob'] else 'modified' - assert entry['release_delta'] == expected_delta -assert current_actual.keys() - actual.keys() == {'plugins/beads/BUILD.bazel'} -assert not actual.keys() - current_actual.keys() -current_skill = (scratch / 'marketplace-main/plugins/beads/skills/beads/SKILL.md').read_text() -assert set(re.findall(r'\]\((resources/[^)]+)\)', current_skill)) == resources -# Ignore only the cache owner's .in_use runtime marker; all payload membership/hashes remain exact. -# Installed cache comparison is optional for other machines; its identity is not inferred from version. -installed = Path('/opt/data/home/.claude/plugins/cache/beads-marketplace/beads/1.3.0') -if installed.is_dir(): - plugin_entries = {p.removeprefix('plugins/beads/'): e for p, e in current_actual.items() - if p.startswith('plugins/beads/')} - assert {str(p.relative_to(installed)) for p in installed.rglob('*') if p.is_file() and p.relative_to(installed).as_posix() != '.in_use'} == plugin_entries.keys() - for path, entry in plugin_entries.items(): - assert hashlib.sha256((installed / path).read_bytes()).hexdigest() == entry['sha256'], path - -change = repo / 'openspec/changes/improve-beads-workflow-parity' -if not change.exists(): - change = repo / 'openspec/changes/archive/2026-10-21-improve-beads-workflow-parity' -assert change.is_dir(), 'Expected active or accepted archived packet' -tasks = (change / 'tasks.md').read_text() -parsed_tasks = re.findall(r'^- \[([ xX])\] (\d+\.\d+) ', tasks, re.M) -task_ids = [task_id for _, task_id in parsed_tasks] -assert len(task_ids) == len(set(task_ids)) and task_ids -# The active execution map must own every task exactly once, including new source deltas. -execution_map = (change / 'execution-map.md').read_text() -owner_rows = re.findall(r'^\| `(opencode-beads-vuy\.\d+)` \| ([0-9., ]+) \|', execution_map, re.M) -owned_ids = [task_id for _, ids in owner_rows for task_id in ids.strip().split(', ')] -assert len(owned_ids) == len(set(owned_ids)) and set(owned_ids) == set(task_ids) -assert len(owner_rows) == len({owner for owner, _ in owner_rows}) - -# Source tasks and 6.1 have parent-accepted deterministic/CLI evidence; live gates remain unexecuted. -accepted_tasks = {task_id for mark, task_id in parsed_tasks if mark.lower() == 'x'} -historical_accepted = {'1.2', '2.1', '2.2', '3.1', '3.2', '3.3', '4.1', '5.1', '6.1'} -source_delta = {'7.1', '7.2', '7.3'} -source_evidence = repo / 'docs/code-mode-source-acceptance-vuy10.md' -assert historical_accepted <= accepted_tasks -host_evidence = repo / 'docs/opencode-host-codemode-qualification-vuy2.md' -flow_evidence = repo / 'docs/opencode-stop-handoff-qualification-vuy6.md' -assert accepted_tasks <= set(task_ids) -if accepted_tasks & {'6.2', '6.3'}: - assert accepted_tasks == set(task_ids) and (repo / 'docs/code-mode-final-acceptance-vuy9.md').is_file(), 'Final acceptance requires all prerequisites and parent evidence' -if '4.2' in accepted_tasks: - assert '1.1' in accepted_tasks and flow_evidence.is_file(), 'Live flow acceptance requires native host acceptance and its parent-reviewed observation record' -if '1.1' in accepted_tasks: - assert host_evidence.is_file(), 'Native host acceptance requires its parent-reviewed observation record' -if accepted_tasks & source_delta: - assert source_delta <= accepted_tasks and source_evidence.is_file(), 'Source delta acceptance requires its parent evidence record' -# Final review B1: stable task IDs with dependency/types preparation first. -assert task_ids.index('1.2') < task_ids.index('1.1') -task_text = dict(re.findall(r'^- \[[ xX]\] (\d+\.\d+) (.+)$', tasks, re.M)) -assert 'After 1.2' in task_text['1.1'] and 'throwaway' in task_text['1.1'] -assert 'tests/continuity.test.ts' not in task_text['1.1'] -assert 'tests/continuity.test.ts' in task_text['3.1'] -assert '1.1' not in task_text['5.1'] -assert 'Live prerequisite for 1.1, 4.2 and 6.2' in tasks -valid_dispositions = {'adapt', 'replace', 'preserve-external', 'reference-only'} -for entry in data['files'] + current['files']: - mapping = entry['selected_mapping'] - assert mapping['disposition'] in valid_dispositions - assert all(mapping[k].strip() for k in ('group', 'target', 'reason')) - assert mapping['task_ids'] and set(mapping['task_ids']) <= set(task_ids) - if entry['category'] == 'command': - assert mapping['target'] == 'oc-beads:' + Path(entry['path']).stem - if entry['category'] == 'resource': - assert mapping['target'] == 'assets/oc-beads/resources/' + Path(entry['path']).name - if entry['path'] in actual and 'owner_disposition' in entry: - assert entry['owner_disposition'] == mapping['disposition'] - assert entry['historical_owner_disposition'] == 'pending' -requirements = {(p.parent.name, title) for p in (change / 'specs').glob('*/spec.md') - for title in re.findall(r'^### Requirement: (.+)$', p.read_text(), re.M)} -record = (change / 'reconciliation.md').read_text() -coverage_rows = re.findall(r'^\| (work-continuity|workflow-access|upstream-review) \| ([^|]+) \| ([0-9., ]+) \|$', record, re.M) -coverage = {(cap, title.strip()): ids.strip().split(', ') for cap, title, ids in coverage_rows} -assert len(coverage) == len(coverage_rows) and coverage.keys() == requirements -assert all(set(ids) <= set(task_ids) and ids for ids in coverage.values()) -assert set(task_ids) - {i for ids in coverage.values() for i in ids} == {'6.3'} - -release_tree = json.loads((scratch / 'native-release-tree.json').read_text()) -assert not release_tree['truncated'] -tree = {e['path']: e for e in release_tree['tree'] if e['type'] == 'blob'} -assert json.loads((scratch / 'native-tag.json').read_text())['object']['sha'] == native['commit'] -assert json.loads((scratch / 'native-min-tag.json').read_text())['object']['sha'] == native['minimum_commit'] -assert (scratch / 'native-dev-head.txt').read_text().strip() == native['development_commit'] -source_paths = set() -for entry in native['sources']: - path = entry['path'] - assert path not in source_paths - source_paths.add(path) - verify_blob(scratch / 'released' / path, entry, tree[path]) - assert entry['url'] == f"https://github.com/anomalyco/opencode/blob/{native['commit']}/{path}" - assert entry['url'] in assessment and entry['id'] in assessment -assessment_source_urls = set(re.findall(r'https://github.com/anomalyco/opencode/blob/[a-f0-9]{40}/[^)\s]+', assessment)) -historical_source_urls = {e['url'] for e in native['sources']} -current_source_urls = {e['url'] for e in data['host_baseline_211']['sources']} -# Preserve complete historical source membership while allowing cited 2.1.1 evidence. -# Both inventories' blobs/hashes are independently verified; unknown source URLs still fail. -assert historical_source_urls <= assessment_source_urls -assert assessment_source_urls <= historical_source_urls | current_source_urls -assert {e['id'] for e in native['sources']} == {f'S{i:02}' for i in range(1, 22)} -mechanisms = native['mechanisms'] + native['candidates'] -assert {e['id'] for e in mechanisms} == {f'M{i:02}' for i in range(1, 11)} | {f'X{i:02}' for i in range(1, 10)} -assert {e['id'] for e in native['availability_anchors']} == {e['id'] for e in mechanisms} -for entry in mechanisms: - assert entry['owner_disposition'] in {'adapt', 'replace', 'preserve-external', 'reference-only', 'exclude', 'defer'} - assert f"| {entry['id']} " in assessment - if entry['id'].startswith('M'): - assert entry['availability'] == 'released-public' - elif entry['id'] in ('X01', 'X02', 'X03', 'X04'): - assert entry['availability'] == 'released-experimental' - elif entry['id'] == 'X09': - assert entry['availability'] == 'development-only' -for entry in native['availability_anchors']: - assert entry['path'] in source_paths - content = (scratch / 'released' / entry['path']).read_text() - assert all(token in content for token in entry['tokens']), entry['id'] - assert all(token not in content for token in entry.get('absent', [])), entry['id'] -assert 'tool.options?.permission ?? name' in (scratch / 'released/packages/core/src/tool.ts').read_text() -permission_source = (scratch / 'released/packages/core/src/permission.ts').read_text() -assert 'agentID ?? session.agent' in permission_source -assert 'existing.request.save?.length' in permission_source -assert 'access.authorizeExternal([target, ...directories], context)' in (scratch / 'released/packages/core/src/tool/plugin/shell.ts').read_text() -assert 'action: "external_directory"' in (scratch / 'released/packages/core/src/file-access.ts').read_text() -assert 'text.search(/\\s/)' in (scratch / 'released/packages/app/src/composer/client-slash-command.ts').read_text() -assert '| "list"' in (scratch / 'native/packages/plugin/src/promise/session.ts').read_text() -assert 'readonly assert:' not in (scratch / 'minimum/packages/plugin/src/promise/permission.ts').read_text() -for entry in native['package_evidence']: - version = entry['version'] - content = (scratch / f'plugin-{version}.tgz').read_bytes() - assert entry['integrity'] == 'sha512-' + base64.b64encode(hashlib.sha512(content).digest()).decode() - directory = scratch / ('npm26' if version == '2.0.26' else 'npm32') / 'package' - assert json.loads((directory / 'package.json').read_text())['version'] == version -for name in native['declarations_identical_26_32']: - rel = f'package/dist/promise/{name}.d.ts' - assert (scratch / 'npm26' / rel).read_bytes() == (scratch / 'npm32' / rel).read_bytes() -assert 'readonly assert:' not in (scratch / 'npm26/package/dist/promise/permission.d.ts').read_text() -assert 'readonly assert:' in (scratch / 'npm32/package/dist/promise/permission.d.ts').read_text() -assert '| "list"' not in (scratch / 'npm32/package/dist/promise/session.d.ts').read_text() -assert native['status'] == 'historical-planning' and native['runtime_qualification'] == 'not executed' -assert native['selected_minimum'] == '>=2.0.32 <3' - -# New baseline evidence is additive; never relabel historical 2.0.32 sources. -new = data['host_baseline_211'] -assert new['commit'] == 'ba546ec1598a70db2570e9c6258028d955ba8f58' -assert new['previous_commit'] == native['commit'] -assert new['admission_range'] == '>=2.1.1 <2.2' and new['exact_live_target'] == '2.1.1' -assert new['runtime_qualification'] == 'not executed' -cache = scratch / new['cache'] -assert json.loads((cache / 'tag.json').read_text())['object'] == { - 'sha': new['commit'], 'type': 'commit', - 'url': f"https://api.github.com/repos/anomalyco/opencode/git/commits/{new['commit']}"} -new_tree = json.loads((cache / 'tree.json').read_text()) -assert not new_tree['truncated'] and new_tree['sha'] == new['commit'] -new_blobs = {e['path']: e for e in new_tree['tree'] if e['type'] == 'blob'} -new_paths = [e['path'] for e in new['sources']] -assert len(new_paths) == len(set(new_paths)) and source_paths <= set(new_paths) -for entry in new['sources']: - path = entry['path'] - verify_blob(cache / 'source' / path, entry, new_blobs[path]) - assert entry['url'] == f"https://github.com/anomalyco/opencode/blob/{new['commit']}/{path}" - prior = tree.get(path) - assert entry['old_git_blob'] == (prior['sha'] if prior else None) - delta = 'added' if prior is None else 'unchanged' if prior['sha'] == entry['git_blob'] else 'modified' - assert entry['delta'] == delta - if prior: - old = (scratch / 'released' / path).read_bytes() - assert hashlib.sha1(b'blob ' + str(len(old)).encode() + b'\0' + old).hexdigest() == prior['sha'] -npm = json.loads((cache / 'npm.json').read_text()) -package = new['package'] -assert npm['name'] == package['name'] and npm['version'] == package['version'] == '2.1.1' -assert npm['dist']['tarball'] == package['tarball'] and npm['dist']['integrity'] == package['integrity'] -tarball = (cache / 'plugin-2.1.1.tgz').read_bytes() -assert hashlib.sha256(tarball).hexdigest() == package['sha256'] -assert 'sha512-' + base64.b64encode(hashlib.sha512(tarball).digest()).decode() == package['integrity'] -import io -import tarfile -with tarfile.open(fileobj=io.BytesIO(tarball)) as archive: - assert json.loads(archive.extractfile('package/package.json').read())['version'] == '2.1.1' - for entry in new['declarations']: - content = (cache / 'npm' / entry['path']).read_bytes() - assert content == archive.extractfile(entry['path']).read() - prior = (scratch / 'npm32' / entry['path']).read_bytes() - assert hashlib.sha256(content).hexdigest() == entry['sha256'] - assert hashlib.sha256(prior).hexdigest() == entry['old_sha256'] - assert entry['delta'] == ('unchanged' if content == prior else 'modified') -for domain in ('effect', 'promise'): - source = (cache / f'source/packages/plugin/src/{domain}/session.ts').read_text() - declaration = (cache / f'npm/package/dist/{domain}/session.d.ts').read_text() - assert '| "list"' in source and 'native?:' in source and 'providerState?:' not in source - assert '"list"' in declaration and 'native?:' in declaration -assert new['availability_overrides']['X09']['availability'] == 'released-public' -assert new['availability_overrides']['X09']['disposition'] == 'reference-only' -assert 'metadata.keepID' in (cache / 'source/packages/core/src/session/history.ts').read_text() -assert 'tool.options?.permission ?? name' in (cache / 'source/packages/core/src/tool.ts').read_text() -assert 'existing.request.save?.length' in (cache / 'source/packages/core/src/permission.ts').read_text() -assert re.search(r'^## (v[^ ]+)', (cache / 'source/CHANGELOG.md').read_text(), re.M)[1] == 'v2.1.0' -assert set(new['task_ids']) <= set(task_ids) -print(f"PASS: 2.1.1 separate pin, {len(new_paths)} endpoint sources, published tarball/declarations, conservative admission; runtime unexecuted") - -files = [p for p in change.rglob('*') if p.is_file()] -files += [repo / 'docs' / name for name in ( - 'claude-code-integration-analysis.md', 'claude-code-integration-inventory.json', - 'opencode-native-parity-assessment.md', 'validate-parity-planning.py', - 'claude-code-local-reference.md', 'beads-artifact-policy.md', - 'claude-code-parity.md', 'opencode-sdk-contract.md', - 'reviews/opus-planning-review-50919ae.md', 'opencode-2.1.1-contract-delta.md')] -for path in files: - assert not path.is_symlink() and path.resolve().is_relative_to(repo) - check = subprocess.run(['git', 'diff', '--no-index', '--check', '/dev/null', str(path)], - capture_output=True, text=True) - assert check.returncode in (0, 1) and not check.stdout and not check.stderr, (path, check.stdout, check.stderr) - if path.suffix == '.md': - for link in re.findall(r'\]\(([^)]+)\)', path.read_text()): - if not link.startswith(('https:', 'http:', '#')): - assert (path.parent / link.split('#')[0]).exists(), (path, link) -print(f'PASS: {len(actual)} Claude files; 29 commands, 15 resources, 1 ADR; Git/SHA identity and complete coverage') -print(f'PASS: {len(native["sources"])} native files / 21 source groups; 10 mechanisms, 9 candidates; links and availability anchors') -print('PASS: npm tarball integrity, 2.0.26/2.0.32 declaration comparison, permission assertion and development-only listing distinctions') -print(f'PASS: {len(current_actual)} marketplace-main files, complete dispositions and installed comparison when available') -print(f'PASS: {len(task_ids)} unique tasks ({len(accepted_tasks)} accepted, {len(task_ids) - len(accepted_tasks)} unchecked); {len(requirements)} normative requirements mapped; full corpus task coverage') -print(f'PASS: {len(files)} planning files whitespace/local links/containment, including untracked artifacts; no tracker access') diff --git a/docs/workflow-native-context-evaluation.md b/docs/workflow-native-context-evaluation.md deleted file mode 100644 index 0fc40b6..0000000 --- a/docs/workflow-native-context-evaluation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Workflow native context evaluation - -Independent review records: [original sync source review](reviews/opus-sync-context-source-bbd.md), [migration plan review](reviews/opus-workflow-context-plan-0ny.md), and [migration source/evidence review](reviews/opus-workflow-context-source-79l.md). They are preserved byte-for-byte; their verdicts apply to the candidates named in each report. Local closeout resolves the two nonblocking wording observations without changing runtime source or the tested archive. - -Owner-approved implementation: opencode-beads-8fl, executor codex:oc-command-sol, gpt-6.1-sol/high, session 01a1644d-e92b-7421-9cc9-7bf4c762aac0. Parent independently accepted source tasks 4.1–4.4 after diff review and rerunning typecheck, 212 tests / 11,696 assertions, exact-archive package smoke and strict global 4/4 validation. The parent also independently matched all 30 command descriptions/static instructions/diagnostics against the accepted reference, all 167 protected paths, all 31 archive/source files and all 239 retained historical artifacts. The owner later authorized exactly one corrected qualification-only smoke. The parent independently accepted corrected runtime task 4.5 after checking raw native note/permission call identity, exact one-append issue readbacks, genuine provider frames, both native TUI captures, cleanup and frozen product/original evidence. All migration tasks 4.1–4.5 are accepted; no further model attempt is authorized. The accepted source is committed locally. The completed change is archived into canonical workflow-access requirements; push, merge, publication and activation remain separate. - -The base is the accepted local uncommitted sync UX reference atop 76549cff2558404f8b855b8708d13ac81c52f138, not HEAD alone. Implementation evidence lives in `/opt/data/cache/scratch/oc-beads-command-migration-implementation/`. `baseline.json` binds 182 paths and `protected.json` binds 167; all matched before edits. Reviewed plan SHA256: 4aacd1559214d2b16f92449faee4712f1228a9e533e7c23b21afcdf51f69680f; READY planning review: 08cfcc7d81dfd4d6d65c4607f36efd82bfcb219c5d99f86a66f5945b5d03f555. Those reviews cover planning, not these implementation bytes. - -All 29 workflows now admit compact ordinary prompts with exact free text and native inputs. New v1 snapshots use ocBeadsWorkflow; valid ocBeadsSync v1 history remains readable. Generalized snapshots win if both are valid, with both valid routing keys stripped only from request copies. Diagnostics remains dynamic. No current actor/capabilities are stored in snapshots. The existing two hooks and single summary cue are reused. - -Source validation passed. Meaningful RED/GREEN captured compact update admission, generalized/legacy reader selection and the active-workflow summary cue. Existing 29 non-sync payload hashes are unchanged: tests reconstruct the historical rich submission from snapshots plus ORIGINAL fixed details/native fields. The sync instruction digest remains checked. A table exercises all 29 callbacks, both deliveries and ten literal input forms (580 admissions). Mixed show/update/compact/legacy-sync Responses serialization checks one snapshot per eligible invocation, absent provider routing metadata, current details, immutable history and stable primary/compaction repeated/native replay. This local serializer fixture performs no inference. - -Typecheck and the full ordinary suite passed: 212 tests / 11,696 assertions. Scoped strict OpenSpec passed 1/1; global strict validation passed 4/4. Exact-archive installed package smoke passed all 29 workflows, diagnostics, legacy read compatibility, 17 installed links and eleven code-mode registrations. The source-derived factory inventory confirms 30 unique names: 28 migrated, sync reference, diagnostics exception. All descriptions, instruction bodies and resource mappings match the exact reference. No semantic fixture hashes were regenerated. - -Tested archive SHA256: `cfb1441081931ca452a75d35e340a496b024c90f8fd474f31cd5e4a1a823a6c9`. The retained archive and `archive-source-manifest.json` are in implementation scratch; all 31 packed files match current source. Baseline manifest SHA256: `9c2d072d3f4527369cf7d20f80c2f6e98f9929be086904960992ec8c256556ef`; protected manifest SHA256: `541266a01ffa413202fc0e1563854b7374e3b99518c12e95c711fdd68035cc60`. All 167 protected paths and 239 recorded original planning/review/sync artifact files remain unchanged. Twelve allowed existing paths changed, with only this new repository document. Original sync task text/checkmarks remain intact; parent accepted and checked migration 4.1–4.5, with runtime acceptance based on the owner-approved corrected sample below. - -The original genuine OpenCode 2.1.2 / openai/gpt-6.1-sol/high update attempt was **guard-blocked/no-write and did not qualify append behavior**. Native session `ses_e9ba6ce27ffexLRw7fmkj26LPi` used agent workflow_eval. Captured TUI and stored entry are compact; the first provider request contains the exact static snapshot once without routing metadata. Two primary requests used native previous-response continuation (snapshot counts 1 then 0); no auxiliary requests occurred. The store guard ran `bd context --json`, which failed because the disposable fixture had no Git repository root. The model respected the hold and truthfully reported that no note was appended. No issue read/write, native append permission, code-mode append or runtime actor rendering was reached. `opencode:workflow_eval:d0e53818645c` is the actor derived from the actual session/agent, not an observed write attribution. Both fixture issues and sentinel files are unchanged on independent readback. No retry was performed. - -That original fixture precheck verified explicit location, seed/readback and narrow permission RED/GREEN, but missed the existing context safety probe before inference; this is a harness qualification gap, not passed runtime acceptance. Initial preparation without explicit BEADS_DIR found a held ancestor and create was rejected; subsequent fixture seeding used an explicit owned BEADS_DIR verified by where. No freeze marker, Git state or operator tracker was repaired. Evidence is in `smoke/evidence-review.json`, native UI/ANSI/provider captures and readbacks. Current required access was imported once without refresh capability. Owned host/TUI/listener and credential-capable data/state were removed; operator config/binary/active-credential fingerprints match and no required access value remains in retained owned files. - -The owner-approved corrected sample used a NEW `evaluation-corrected/` fixture, explicit BEADS_DIR, and a genuine Git root with a minimal command-scoped-identity fixture commit. Before inference, exact `bd context --json` resolved the expected beads_dir/repo_root/cwd_repo_root with schema version 1 and no redirection; the frozen adapter's own checkBeadsStore/runBd returned ready under the same cwd/environment as the host. Where/list/two seeded issues/target readback, narrow permission positive/negative checks and current access metadata also passed. Source/product and the exact archive remained frozen; no accepted full source gates were rerun for this fixture correction. - -The **parent independently accepted the one corrected sample's scoped observation**: native session `ses_e9b945634ffeUCourDQisDYoiR`, OpenCode 2.1.2 / openai/gpt-6.1-sol/high, actual agent workflow_eval, execution actor `opencode:workflow_eval:6cce9201edd5`. Ordinary `/oc-beads:update` admission produced one compact persisted/native TUI entry; the exact static snapshot appeared once in the first provider input, with actual actor guidance in current context and no routing keys. Six primary provider requests used native previous-response continuation (snapshot counts 1,0,0,0,0,0); no auxiliary calls, retry or extra command admission occurred. - -Native code-mode beads.get inspected `wctx-rxu`, beads.note performed exactly one `bd update --append-notes` with the exact requested note, explicit actual actor and --sandbox, and beads.get read it back. The append returned acknowledged. Native shell permission for that exact command was answered once, with save: [] and source call ID matching the observed beads_note operation; read permissions were also scoped and answered once. Independent harness readback confirms the original note plus exactly one appended note, unchanged assignee/audit author/owner and all other fields except expected notes/updated_at, and unchanged unrelated issue/files/fixture Git. The completed final response accurately reports the one append and verification. This observes a bounded action, not broad command/model reliability. - -Corrected sanitized evidence, UI/ANSI, native operations, permissions, CLI calls, provider usage and independent readbacks are in `evaluation-corrected/`; `evidence-review.json` records the assertions. Reported provider totals are 106,848 input tokens including 84,736 cached input tokens, and 422 output tokens across six requests; no savings inference is made. Current required access was imported once with no refresh capability. Owned host/TUI/listener and credential-capable state were removed, no owned processes remain, operator config/binary/active-credential fingerprints match, and the retained-secret scan is clear. Original 154-file smoke evidence and all 239 historical bindings remain intact. Only this repository evidence document changed during correction; all other 182 repository paths, 167 protected paths and 31 archive/source files match accepted custody. Task 4.5 and 8fl closure remain parent-owned. - -Original sync design/evaluation and sample/review artifacts remain historical evidence, not reviews of these new bytes. Parent owns acceptance and any separately authorized next runtime observation, closeout, archive, commit or publication. - -Plugin activation is needed for expansion. Durable metadata is inspectable/exportable; summary recent-context stays compact with semantic retention rather than guaranteed verbatim snapshots. Native storage may contain additional copies and estimates may miss hidden instructions. No token-saving, model-quality or universal runtime-reliability claim is made. Existing five-case action/permission and native lifecycle evidence is inherited only for unchanged boundaries. diff --git a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md index 58bc55d..61e019c 100644 --- a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md +++ b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/design.md @@ -2,7 +2,7 @@ ## Operative code-mode planning reconciliation — 2026-10-21 -Matt authorized Astra/medium to reconcile the broader Opus recommendations into this active change and Beads. Actual planning executor: `codex:oc-plan`, bounded record `opencode-beads-wgv`. The selected planning direction is the [broader architecture memo](../../../../docs/reviews/opus-code-mode-architecture-wgv.md), including its parent verification; the six-tool recommendation and narrow READY remain historical only. This local unpublished revision is based on published HEAD `072429f1a7723ade23e756a921924d9d0acacf31`, not a new published candidate or independent approval. +Matt authorized Astra/medium to reconcile the broader Opus recommendations into this active change and Beads. Actual planning executor: `codex:oc-plan`, bounded record `opencode-beads-wgv`. The selected planning direction is the [broader architecture memo](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-code-mode-architecture-wgv.md), including its parent verification; the six-tool recommendation and narrow READY remain historical only. This local unpublished revision is based on published HEAD `072429f1a7723ade23e756a921924d9d0acacf31`, not a new published candidate or independent approval. Adopt the eleven-operation daily-loop namespace, host-derived executor actor visible to the model, capability-aware deduplicated guidance, operation-aware references and conservative targeted freshness. Retain all 30 human command names/user overrides, full advanced/admin coverage and full prime initially. Canonical actor means the actual host-derived executor identity, not the literal `beads-task-agent` name or mandatory delegation. Primary agents keep their own actor; delegated workers receive their own. Permission identity remains actual invocation `context.agent`. @@ -16,7 +16,7 @@ Remaining qualification/activation is paused for parent review of the selected b ## Context -See [proposal](proposal.md), [owner decisions](owner-decisions.md), [full corpus analysis](../../../../docs/claude-code-integration-analysis.md) and [native call-site assessment](../../../../docs/opencode-native-parity-assessment.md). Reconciliation baseline is `3dc2ea327ed490ceb9cf0b95c31af77631613287`. Historical release evidence is retained separately from the selected marketplace-main commit. The operative host baseline is now 2.1.1; see the [contract delta](../../../../docs/opencode-2.1.1-contract-delta.md). The following 2.0.32 pin remains historical, not relabeled. Released OpenCode 2.0.32 is `843a6c514e606b436a7fe713422ace0a93ad3d61`; development `8f7b012…` is not that release. +See [proposal](proposal.md), [owner decisions](owner-decisions.md), [full corpus analysis](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/claude-code-integration-analysis.md) and [native call-site assessment](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-native-parity-assessment.md). Reconciliation baseline is `3dc2ea327ed490ceb9cf0b95c31af77631613287`. Historical release evidence is retained separately from the selected marketplace-main commit. The operative host baseline is now 2.1.1; see the [contract delta](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-2.1.1-contract-delta.md). The following 2.0.32 pin remains historical, not relabeled. Released OpenCode 2.0.32 is `843a6c514e606b436a7fe713422ace0a93ad3d61`; development `8f7b012…` is not that release. Published baseline already contains the accepted five-operation adapter (activation withheld), package commands/resources and scope-bounded guidance. The new source delta replaces its missing output schemas and narrow operation surface; historical acceptance does not establish code-mode readiness. @@ -44,7 +44,7 @@ All advanced resources remain available on demand (agent beads, molecules/chemis Register all 29 namespaced workflows plus status through one ordinary command transform. The pinned command editor exposes only add/map set; initial `ctx.command.list()` collisions are diagnostic-only, not a reason to withhold a name permanently. S13 supervisor ordering is pre → packages → post, and ConfigCommandPlugin is post: ordinary configuration/file commands replay after package transforms, including config reload, and removing an override restores the package definition. Same-name conflicts with other plugin transforms follow native order; disclose detectable conflicts without promising universal preservation. This is supported host precedence, not broken upstream behavior. Keep public per-rebuild skill `editor.list()` collision checks, but remove the redundant initial skill gate so a removed customization does not permanently suppress registration. Every owned transform checks abort before add and has an owned disposer. Qualify initial/rebuilt/disposed registries using a small ordered-callback fixture, not a host replica or collision manager. Status compares effective public names/descriptions with definitions, reports observable overrides and lookup failures, and discloses that owner identity and identical-description overrides are unobservable; no hardcoded all-command hold survives. Qualify all packaged resource links and external-directory ask/deny from the installed base, reporting unreachable files without bypass. Do not write user files. Native scoped disposers plus setup cleanup remove only owned registrations and abort observers/processes. Shared `beads` skill, user configuration/files, agent names and npm package name remain unchanged. -Opus's resolution review verifies package/config ordering from pinned 2.1.1 `plugin/supervisor.ts:99–103`, `plugin/internal.ts:254–259`, `command.ts:61` and `state.ts:162,178–181`. Its registry suffix-reactivation evidence comes from the unpinned `released` cache, not the exact 2.1.1 cache; do not label that detail pinned or live-qualified. Installed-host discovery, reactivation and permissions remain unexecuted 1.1/6.2 acceptance work. See [the original review](../../../../docs/reviews/opus-registration-resolution-review-vuy5.md); its REVISE verdict is historical evidence, not changed by this reconciliation. +Opus's resolution review verifies package/config ordering from pinned 2.1.1 `plugin/supervisor.ts:99–103`, `plugin/internal.ts:254–259`, `command.ts:61` and `state.ts:162,178–181`. Its registry suffix-reactivation evidence comes from the unpinned `released` cache, not the exact 2.1.1 cache; do not label that detail pinned or live-qualified. Installed-host discovery, reactivation and permissions remain unexecuted 1.1/6.2 acceptance work. See [the original review](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-registration-resolution-review-vuy5.md); its REVISE verdict is historical evidence, not changed by this reconciliation. ### 3. N1 continuity operations and authorization @@ -86,7 +86,7 @@ Admission is intentionally narrower than the historical >=2.0.32 <3 proposal bec Qualification has three layers: pinned source checks (completed planning evidence), stub/disposable fixture integration (future task work), and installed-host/model behavior (future acceptance). Exercise the complete installed catalog mechanically and a small representative behavioral set: ordinary ready/claim/validate flow, failed approach and discovered follow-up, task notes versus reusable memory, fresh-session recovery, exact assignment versus authorized continuation, restricted agents, hold/failure and partial child handoff. Record host/CLI/model/provider/reasoning/install path and actual durable outcomes. Repeat only uncertain cases; no write/tool-count quota or exhaustive matrix. -The owner-approved [upstream plugin test gap assessment](../../../../docs/reviews/upstream-plugin-test-gap-assessment.md) refines existing live acceptance, without reopening accepted source work or adding tasks. Task 1.1 includes user correction feedback and explicit decline alongside allow/ask/deny, verifying host outcome propagation and no rejected target execution or automatic retry. Task 6.2 includes one actual installed unload/reactivate round trip: owned removal/restoration under native precedence, a single context injection and suppression of pending old-generation results. Both remain unexecuted and require the existing disposable-host authority. Internal upstream host-service tests, local disposal fixtures and package imports do not establish installed lifecycle behavior. Do not port supervisor/module-loader or background-observer suites, add permission translation, or build another test harness. +The owner-approved [upstream plugin test gap assessment](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/upstream-plugin-test-gap-assessment.md) refines existing live acceptance, without reopening accepted source work or adding tasks. Task 1.1 includes user correction feedback and explicit decline alongside allow/ask/deny, verifying host outcome propagation and no rejected target execution or automatic retry. Task 6.2 includes one actual installed unload/reactivate round trip: owned removal/restoration under native precedence, a single context injection and suppression of pending old-generation results. Both remain unexecuted and require the existing disposable-host authority. Internal upstream host-service tests, local disposal fixtures and package imports do not establish installed lifecycle behavior. Do not port supervisor/module-loader or background-observer suites, add permission translation, or build another test harness. ## Risks / Trade-offs diff --git a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md index c8ac4ea..d35b391 100644 --- a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md +++ b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/owner-decisions.md @@ -14,7 +14,7 @@ The already-authorized same Sol/high .10 worker continues source tasks 7.1–7.3 ## Operative code-mode planning reconciliation — 2026-10-21 -Matt authorized Astra/medium to reconcile the broader Opus recommendations into this active change and Beads. Actual planning executor: `codex:oc-plan`, bounded record `opencode-beads-wgv`. The selected planning direction is the [broader architecture memo](../../../../docs/reviews/opus-code-mode-architecture-wgv.md), including its parent verification; the six-tool recommendation and narrow READY remain historical only. This local unpublished revision is based on published HEAD `072429f1a7723ade23e756a921924d9d0acacf31`, not a new published candidate or independent approval. +Matt authorized Astra/medium to reconcile the broader Opus recommendations into this active change and Beads. Actual planning executor: `codex:oc-plan`, bounded record `opencode-beads-wgv`. The selected planning direction is the [broader architecture memo](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-code-mode-architecture-wgv.md), including its parent verification; the six-tool recommendation and narrow READY remain historical only. This local unpublished revision is based on published HEAD `072429f1a7723ade23e756a921924d9d0acacf31`, not a new published candidate or independent approval. Adopt the eleven-operation daily-loop namespace, host-derived executor actor visible to the model, capability-aware deduplicated guidance, operation-aware references and conservative targeted freshness. Retain all 30 human command names/user overrides, full advanced/admin coverage and full prime initially. Canonical actor means the actual host-derived executor identity, not the literal `beads-task-agent` name or mandatory delegation. Primary agents keep their own actor; delegated workers receive their own. Permission identity remains actual invocation `context.agent`. @@ -42,7 +42,7 @@ Design, workflow-access scenarios, task 2.2 and operative vuy.5 acceptance inclu ## Upstream test gap resolutions — accepted acceptance refinements -Matt approved folding the bounded upstream plugin test comparison into existing acceptance. Add correction-with-feedback and explicit-decline outcomes to task 1.1 (`opencode-beads-vuy.2`), with no rejected target execution, false success or automatic retry. Add one actual installed unload/reactivate round trip to task 6.2 (`opencode-beads-vuy.9`), checking owned removal/restoration, native user-override precedence, one context injection and no late old-generation result. See [the source assessment](../../../../docs/reviews/upstream-plugin-test-gap-assessment.md). +Matt approved folding the bounded upstream plugin test comparison into existing acceptance. Add correction-with-feedback and explicit-decline outcomes to task 1.1 (`opencode-beads-vuy.2`), with no rejected target execution, false success or automatic retry. Add one actual installed unload/reactivate round trip to task 6.2 (`opencode-beads-vuy.9`), checking owned removal/restoration, native user-override precedence, one context injection and no late old-generation result. See [the source assessment](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/upstream-plugin-test-gap-assessment.md). These are acceptance-case refinements, not demonstrated product defects or new tasks. Preserve the 13 task IDs, their checkmarks, exclusive child ownership and dependencies. Both live cases remain unexecuted; this approval authorizes the bounded planning/tracker reconciliation, not host installation, model experiments, source implementation, dispatch, publication or activation. Existing host-owned supervisor, loader, permission-conversion and background-notification suites are not downstream implementation requirements. @@ -56,7 +56,7 @@ These are acceptance-case refinements, not demonstrated product defects or new t ## Operative host selection — 2026-10-20 -Matt directly selected OpenCode **2.1.1**, superseding the earlier 2.0.32 minimum above while retaining all other product choices. Source pin: `ba546ec1598a70db2570e9c6258028d955ba8f58`. Engineering admission policy is `>=2.1.1 <2.2` because 2.1 changes public replay/compaction contracts; exact 2.1.1 is the unexecuted disposable qualification target, not a tested compatibility claim. Future patch candidates require normal qualification; no arbitrary minor compatibility. See [delta memo](../../../../docs/opencode-2.1.1-contract-delta.md). +Matt directly selected OpenCode **2.1.1**, superseding the earlier 2.0.32 minimum above while retaining all other product choices. Source pin: `ba546ec1598a70db2570e9c6258028d955ba8f58`. Engineering admission policy is `>=2.1.1 <2.2` because 2.1 changes public replay/compaction contracts; exact 2.1.1 is the unexecuted disposable qualification target, not a tested compatibility claim. Future patch candidates require normal qualification; no arbitrary minor compatibility. See [delta memo](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-2.1.1-contract-delta.md). Authority covers planning/docs/validator and existing scoped tracker updates only, followed by **PAUSED FOR REVIEW**. No implementation, dependency installation, host upgrade, dispatch or publication. Operator 2.0.29 remains untouched. AGENTS.md/.codex setup is now tracked at `907232a393443a0f0d59133ffb0e2612f3fd9026` and must remain identical; earlier dirty-setup descriptions are historical. @@ -68,7 +68,7 @@ Authority covers planning/docs/validator and existing scoped tracker updates onl ## Review corrections to reconcile -The original Opus verdict was REVISE. The reconciliation record addresses F1–F5 with source evidence and exact artifact/task mappings: installed/release/main differences, typed-tool visibility/agent/save/external-access, reference-only compaction and check-based drift. This is the planning agent’s reconciliation, not new independent reviewer approval. The [50919ae review](../../../../docs/reviews/opus-planning-review-50919ae.md) is preserved with its REVISE verdict. Final B1/recommendation corrections are mapped in reconciliation; no owner selection is reopened. Dependency preparation now precedes host probes, with separately authorized disposable live-host prerequisites. Runtime and behavioral acceptance remain unexecuted; no new infrastructure or wholesale analysis restart is required. +The original Opus verdict was REVISE. The reconciliation record addresses F1–F5 with source evidence and exact artifact/task mappings: installed/release/main differences, typed-tool visibility/agent/save/external-access, reference-only compaction and check-based drift. This is the planning agent’s reconciliation, not new independent reviewer approval. The [50919ae review](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-planning-review-50919ae.md) is preserved with its REVISE verdict. Final B1/recommendation corrections are mapped in reconciliation; no owner selection is reopened. Dependency preparation now precedes host probes, with separately authorized disposable live-host prerequisites. Runtime and behavioral acceptance remain unexecuted; no new infrastructure or wholesale analysis restart is required. ## Authority diff --git a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/proposal.md b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/proposal.md index d7fb70e..fa5b95e 100644 --- a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/proposal.md +++ b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/proposal.md @@ -14,7 +14,7 @@ The historical comparison established setup-lifecycle parity, not the complete C - **BREAKING, opt-in beta/next only:** target OpenCode `>=2.1.1 <2.2` and replace mandatory one-bead/command-count delegation with scope-bounded continuation. Exact assignments stop; authorized batches/goals may continue with atomic claims and per-bead validation. Stable consumers do not silently migrate. No package/version/tag changes are made here. - Preserve restricted-agent visibility, invocation identity, narrow saved approvals, location restrictions, holds, cancellation and honest persistence failures. An unqualified N1 guarantee blocks the affected path; N0 is a historical alternative, not a silent degraded default. - Extend the existing scheduled pattern with advisory marketplace-main source comparison and immutable review links. Completed comparisons succeed despite ordinary main development; they do not gate product CI, adoption or release. Incomplete comparison is unavailable evidence, distinct from no change, without gating product/release checks. Tagged CLI compatibility remains separate. Human-reviewed baseline advancement only; no GitHub issue creation or issue-write permission. -- Apply the [2.1.1 contract delta](../../../../docs/opencode-2.1.1-contract-delta.md): adopt native replay fields and retained-history semantics without replacing host compaction. Admit only the 2.1 patch line (`>=2.1.1 <2.2`); exact 2.1.1 is the unexecuted live target, not a proven compatibility result. Future patches are candidates for normal source/acceptance checks, not automatically tested versions. +- Apply the [2.1.1 contract delta](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-2.1.1-contract-delta.md): adopt native replay fields and retained-history semantics without replacing host compaction. Admit only the 2.1 patch line (`>=2.1.1 <2.2`); exact 2.1.1 is the unexecuted live target, not a proven compatibility result. Future patches are candidates for normal source/acceptance checks, not automatically tested versions. - Retain code-mode composition with the owner-accepted OpenCode 2.1.1 nested plain-decline continuation limitation: the rejected operation never executes or receives success acknowledgement, but whole-step termination is not promised. Later operations retain their own permissions; explicit Stop/Cancel qualification remains required. Preserve the failed stronger case as historical evidence. The broader investigation is now reconciled into tasks 7.1–7.3 for source preparation; remaining qualification stays paused for parent review and separate dispatch. This is not authority for an upstream patch or implementation. - Qualify source contracts, disposable deterministic fixtures and live/model outcomes separately, including fresh-session recovery, discovery and authorized continuation. Architecture and tool-call counts are not behavioral proof. diff --git a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md index eccdb96..5733b36 100644 --- a/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md +++ b/openspec/changes/archive/2026-10-21-improve-beads-workflow-parity/reconciliation.md @@ -2,7 +2,7 @@ ## Bounded Opus correction pass — S1–S5 and P1–P3 -Matt authorized incorporation of the [plan review findings](../../../../docs/reviews/opus-code-mode-plan-review-wgv.md). Original REVISE and frozen candidate/reports remain historical and immutable; this is a corrected local candidate awaiting parent finding-scoped recheck, not a new review verdict. Executor codex:oc-plan, session 01a15ee8-9655-7f02-b8dd-3b8541d3e42f. Eleven operations, 16 task IDs, nine accepted task texts/marks, seven unchecked IDs, ownership and dependency graph are unchanged. +Matt authorized incorporation of the [plan review findings](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-code-mode-plan-review-wgv.md). Original REVISE and frozen candidate/reports remain historical and immutable; this is a corrected local candidate awaiting parent finding-scoped recheck, not a new review verdict. Executor codex:oc-plan, session 01a15ee8-9655-7f02-b8dd-3b8541d3e42f. Eleven operations, 16 task IDs, nine accepted task texts/marks, seven unchecked IDs, ownership and dependency graph are unchanged. | Finding | Correction and artifact | Tracker scope | | --- | --- | --- | @@ -84,7 +84,7 @@ F01–F12, D01–D06, E01–E06 and M01–M10/X01–X09 have explicit dispositio ## Opus review disposition -The [original review](../../../../docs/reviews/opus-planning-review-e74b507.md) is preserved unchanged as a review of e74b507. Its REVISE verdict is not rewritten or claimed as approval of this reconciliation. +The [original review](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-planning-review-e74b507.md) is preserved unchanged as a review of e74b507. Its REVISE verdict is not rewritten or claimed as approval of this reconciliation. | Finding | Resolution and evidence | Acceptance still required | | --- | --- | --- | @@ -136,7 +136,7 @@ At the original reconciliation (published as 50919ae), executed: `openspec valid ## Final review corrections — candidate 50919ae -The [supplied independent review](../../../../docs/reviews/opus-planning-review-50919ae.md) retains its **REVISE** verdict. Actual trace model: `claude-opus-5-5`; explicit medium invocation is parent-reported, not introspectable by the reviewer. The following is the planning agent’s correction assessment, not a second independent approval. No second full review was requested or required by that review. +The [supplied independent review](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/reviews/opus-planning-review-50919ae.md) retains its **REVISE** verdict. Actual trace model: `claude-opus-5-5`; explicit medium invocation is parent-reported, not introspectable by the reviewer. The following is the planning agent’s correction assessment, not a second independent approval. No second full review was requested or required by that review. | Finding / recommendation | Exact correction evidence | Future acceptance boundary | | --- | --- | --- | @@ -160,7 +160,7 @@ Exact SHA-256 comparison against `/opt/data/cache/scratch/opencode-beads-reconci ## 2026-10-20 host-baseline delta -The [contract-delta memo](../../../../docs/opencode-2.1.1-contract-delta.md) supersedes only the operative host baseline: 2.1.1 `ba546ec1598a70db2570e9c6258028d955ba8f58`, proposed admission >=2.1.1 <2.2. Historical 2.0.32 identities, inventory and passed reviews remain intact. Provider replay/compaction fields and retained history need fixture adaptation (1.2/3.2/6.2); released session.list remains unnecessary. Permission, registration, stop and unload contracts retain bounded qualification. No new services, compatibility layer, tasks or owners. +The [contract-delta memo](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-2.1.1-contract-delta.md) supersedes only the operative host baseline: 2.1.1 `ba546ec1598a70db2570e9c6258028d955ba8f58`, proposed admission >=2.1.1 <2.2. Historical 2.0.32 identities, inventory and passed reviews remain intact. Provider replay/compaction fields and retained history need fixture adaptation (1.2/3.2/6.2); released session.list remains unnecessary. Permission, registration, stop and unload contracts retain bounded qualification. No new services, compatibility layer, tasks or owners. The 13-task/17-requirement map above remains exact. Existing epic vuy and .1–.9 remain blocked/unassigned/implementation_authorized=false; .6 owns deterministic evidence consumed by gated .8, and .9 still awaits complete live acceptance. Review URLs at 84ab18e/dd56cf1 are explicitly historical; this unpublished delta has a local content digest, not an invented commit. d9n remains open. Setup custody now uses committed 907232a, not the old dirty-file assumption. diff --git a/openspec/changes/archive/2026-11-09-adapt-opencode-2-2/tasks.md b/openspec/changes/archive/2026-11-09-adapt-opencode-2-2/tasks.md index bc9f694..4508417 100644 --- a/openspec/changes/archive/2026-11-09-adapt-opencode-2-2/tasks.md +++ b/openspec/changes/archive/2026-11-09-adapt-opencode-2-2/tasks.md @@ -1,6 +1,6 @@ # Tasks -**Archived completion:** All five mapped tasks are accepted, including the final Claude Opus 5.5 READY gate. Source, qualification and retained limitations are summarized in [the acceptance record](../../../../docs/opencode-22-qualification-5rj2.md). The mapping below records implementation custody; it is not a new execution or release authorization. +**Archived completion:** All five mapped tasks are accepted, including the final Claude Opus 5.5 READY gate. Source, qualification and retained limitations are summarized in [the acceptance record](https://github.com/snarkipus/opencode-beads/blob/723f0ccb35daefb7a9e541689a00c0b33375515e/docs/opencode-22-qualification-5rj2.md). The mapping below records implementation custody; it is not a new execution or release authorization. Planning accepted; execution mapping is epic `opencode-beads-5rj`, with source/checks child `opencode-beads-5rj.1` owning 1.1, 1.2 and 2.1, and qualification/acceptance child `opencode-beads-5rj.2` owning 2.2 and 2.3, blocked by the source child. Shared edit limits and stop conditions are in [design.md](design.md). Mapping is not execution authority; discuss additional corner-case mitigation before implementation and do not begin from artifact-complete status alone. diff --git a/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/design.md b/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/design.md index 4984a26..3f8b576 100644 --- a/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/design.md +++ b/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/design.md @@ -46,7 +46,7 @@ The Code Mode VM-only engine and cooperative context.signal settlement merit rep ## Representative qualification design -The following is the original probe design. The owner subsequently accepted the measured subset and deferred repeated idle reports with the same work outstanding and cancellation while the real bd process is executing. Both remain unexecuted, not passed; no runtime guarantee changed. See the [qualification decision and rationale](../../../../docs/opencode-23-qualification-xwq.md), which supersedes only the further-execution obligation for those two cases. The observed cancellation seam was a real landed write followed by interrupted acknowledgement, not mid-CLI termination. +The following is the original probe design. The owner subsequently accepted the measured subset and deferred repeated idle reports with the same work outstanding and cancellation while the real bd process is executing. Both remain unexecuted, not passed; no runtime guarantee changed. See the [qualification decision and rationale](https://github.com/snarkipus/opencode-beads/blob/592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c/docs/opencode-23-qualification-xwq.md), which supersedes only the further-execution obligation for those two cases. The observed cancellation seam was a real landed write followed by interrupted acknowledgement, not mid-CLI termination. All checks below require separate future dispatch. Use one authorized exact 2.3.0 disposable host and one available owner-selected model route, with existing approved authentication. Do not access operator hosts/Zeus/services, copy credentials or create auth profiles. Do not create synthetic records in the live project tracker. Writes require a separately authorized existing work item with meaningful evidence, or an expressly disposable isolated tracker; if neither is authorized, report the blocked write check rather than fabricate live work. diff --git a/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/proposal.md b/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/proposal.md index aeaaf83..acefd27 100644 --- a/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/proposal.md +++ b/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/proposal.md @@ -24,7 +24,7 @@ None. ## Qualification disposition -The owner accepted bounded native qualification with two cases deferred and unexecuted: repeated idle reports while the same work remains outstanding, and cancellation while the real bd process is executing. The [qualification decision](../../../../docs/opencode-23-qualification-xwq.md) records evidence, cost rationale, residual uncertainty and revisit triggers. Neither case is labelled passed; behavioral guarantees and publication boundaries are unchanged. No further timing campaign is selected. +The owner accepted bounded native qualification with two cases deferred and unexecuted: repeated idle reports while the same work remains outstanding, and cancellation while the real bd process is executing. The [qualification decision](https://github.com/snarkipus/opencode-beads/blob/592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c/docs/opencode-23-qualification-xwq.md) records evidence, cost rationale, residual uncertainty and revisit triggers. Neither case is labelled passed; behavioral guarantees and publication boundaries are unchanged. No further timing campaign is selected. ## Impact diff --git a/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/tasks.md b/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/tasks.md index d3d7f36..7c829c6 100644 --- a/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/tasks.md +++ b/openspec/changes/archive/2026-11-13-adapt-opencode-2-3/tasks.md @@ -1,6 +1,6 @@ # Tasks -These task IDs define the accepted work and evidence obligations; Beads owns dispatch, progress and acceptance. The owner selected the 2.3 floor and exact 2.3.0 qualification. The owner subsequently accepted bounded native evidence with the two expressly deferred, unexecuted cases documented in [the qualification decision](../../../../docs/opencode-23-qualification-xwq.md). Deferral is not a passing test or permission to weaken runtime guarantees. No further native campaign is required for those cases; publication and operator upgrades remain separate. +These task IDs define the accepted work and evidence obligations; Beads owns dispatch, progress and acceptance. The owner selected the 2.3 floor and exact 2.3.0 qualification. The owner subsequently accepted bounded native evidence with the two expressly deferred, unexecuted cases documented in [the qualification decision](https://github.com/snarkipus/opencode-beads/blob/592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c/docs/opencode-23-qualification-xwq.md). Deferral is not a passing test or permission to weaken runtime guarantees. No further native campaign is required for those cases; publication and operator upgrades remain separate. ## 1. Delegation wording and launch cue @@ -18,7 +18,7 @@ These task IDs define the accepted work and evidence obligations; Beads owns dis - [x] 3.2 In that same bounded qualification environment, discover the beads namespace through native Code Mode VM and compose one find/get read, then exercise representative outer execute cancellation of an authorized started checkpoint and durable readback before any further write. Verify actual invoking identity, permission outcome, signal settlement and honest landed/failed/uncertain status with no blind retry. Use only an explicitly authorized existing task or isolated disposable tracker, no synthetic live tracker records. Deliver exact host/model/candidate/CLI identities and evidence; report any unexercised branch without fixture substitution. The owner accepted the observed landed-write/interrupted-acknowledgement seam and deferred cancellation during real bd execution as unexecuted, not passed; that boundary and rationale are recorded in the qualification decision. No host/model/version cross-product, operator access, copied credentials or new auth profile. - [x] 3.3 Add a new dated qualification record separating source/SDK/fixture results from native observations and remaining limitations; update current documentation only to the measured scope. Verify mapping to both deltas and the unchanged stop, permission, actor, uncertainty and snapshot-deficiency requirements. Run strict change validation, canonical validation and whitespace checks; report inherited canonical warnings separately. Return the candidate and unresolved evidence to parent for acceptance; do not infer closure, release, marker update or deployment authority. -Evidence and custody: `opencode-beads-xwq`; [qualification decision](../../../../docs/opencode-23-qualification-xwq.md), source and native reports referenced there. Checkmarks for 3.1 and 3.2 record the accepted evidence and explicit deferrals, not execution of the two deferred cases. +Evidence and custody: `opencode-beads-xwq`; [qualification decision](https://github.com/snarkipus/opencode-beads/blob/592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c/docs/opencode-23-qualification-xwq.md), source and native reports referenced there. Checkmarks for 3.1 and 3.2 record the accepted evidence and explicit deferrals, not execution of the two deferred cases. ## Workflow follow-up diff --git a/package.json b/package.json index 605346b..90080a1 100644 --- a/package.json +++ b/package.json @@ -78,6 +78,7 @@ "@tsconfig/bun": "1.0.9", "@types/bun": "1.3.4", "@types/node": "^22.0.0", + "ajv": "8.17.1", "oxlint": "1.93.0", "prettier": "3.6.2", "typescript": "5.9.3" diff --git a/tests/agents.test.ts b/tests/agents.test.ts index 1329d70..65ad6b3 100644 --- a/tests/agents.test.ts +++ b/tests/agents.test.ts @@ -29,8 +29,8 @@ function evaluate(action: string, resource: string, rules: readonly Rule[]): str const rules: Rule[] = [{ action: "*", resource: "*", effect: "allow" }, ...TASK_AGENT_PERMISSIONS]; const decide = (command: string) => evaluate("shell", command, rules); -describe("task-agent permission decisions", () => { - test("keeps IDs, inherited model, optional Luna and interruption caps independent of scope", () => { +describe("beadsAgents factory configuration", () => { + test("uses the default agent and step cap, shares guidance with opt-in Luna, and accepts cap overrides", () => { const defaults = beadsAgents(); expect(Object.keys(defaults)).toEqual(["beads-task-agent"]); expect(defaults["beads-task-agent"]?.model).toBeUndefined(); @@ -42,6 +42,9 @@ describe("task-agent permission decisions", () => { expect(capped["beads-task-agent-luna"]?.steps).toBe(12); expect(beadsAgents({ steps: 0 })["beads-task-agent"]?.steps).toBeUndefined(); }); +}); + +describe("task-agent shell rules under the transcribed matcher", () => { test.each([ "git commit", "git commit -m done", diff --git a/tests/ci-failure-notification.test.ts b/tests/ci-failure-notification.test.ts index 9db2089..9149c29 100644 --- a/tests/ci-failure-notification.test.ts +++ b/tests/ci-failure-notification.test.ts @@ -1,99 +1,57 @@ import { expect, test } from "bun:test"; -import * as fs from "node:fs/promises"; import { resolve } from "node:path"; const workflow = resolve(import.meta.dir, "../.github/workflows/notify-ci-failure.yml"); +const fixture = resolve(import.meta.dir, "fixtures/ci-failure-notification.py"); +const python = process.platform === "win32" ? "python" : "python3"; +const inertToken = "fixture-not-real"; +const webhook = `https://discord.com/api/webhooks/123/${inertToken}`; -test("CI failure notifications use trusted metadata and a bounded, secret-safe Discord sender", async () => { - expect(await Bun.file(workflow).exists(), "failure notifier must be wired into CI").toBeTrue(); - const text = (await fs.readFile(workflow, "utf8")).replace(/\r\n/g, "\n"); - expect(text).toContain("workflows: [ci, beads-contract]"); +const workflowText = Bun.file(workflow) + .text() + .then((text) => text.replaceAll("\r\n", "\n")); + +test("CI failure notifier runs on trusted workflow metadata with no GitHub permissions", async () => { + const text = await workflowText; + expect(text).toMatch(/^ workflow_run:\n workflows: \[ci, beads-contract\]\n types: \[completed\]$/m); expect(text).toContain("github.event.workflow_run.conclusion == 'failure'"); - expect(text).toContain("permissions: {}"); - expect(text).not.toMatch(/uses:|download-artifact|actions\/checkout/); - const source = text.match(/ python3 - <<'PY'\n([\s\S]+?) PY\n/)?.[1]?.replace(/^ /gm, ""); - expect(source).toBeDefined(); - const program = ` -import io, json, os, tempfile, urllib.error, urllib.request -scope = {"__name__": "fixture"} -exec(${JSON.stringify(source)}, scope) -webhook = "https://discord.com/api/webhooks/123/fixture-not-real" -calls = [] -mode = "success" -class Opener: - def open(self, request, timeout): - calls.append(request) - assert timeout == 10 - assert request.full_url == webhook + "?wait=true" - assert request.get_header("User-agent") == "OpenCode-Beads-CI-Notifier/1.0" - payload = json.loads(request.data) - assert payload["allowed_mentions"] == {"parse": []} - assert "https://github.com/snarkipus/opencode-beads/actions/runs/42" in payload["content"] - assert len(payload["content"]) < 2000 - if mode == "http": - raise urllib.error.HTTPError(webhook, 403, "Forbidden", {}, None) - if mode == "network": - raise OSError(webhook) - return io.BytesIO(b'{"id":"456"}') -def opener(*handlers): - assert len(handlers) == 1 - assert handlers[0].redirect_request(None, None, None, None, None, None) is None - return Opener() -urllib.request.build_opener = opener -with tempfile.TemporaryDirectory(prefix="ci-notify-test-") as directory: - event_path = os.path.join(directory, "event.json") - os.environ["GITHUB_EVENT_PATH"] = event_path - os.environ["DISCORD_CI_WEBHOOK_URL"] = webhook - event = {"repository": {"full_name": "snarkipus/opencode-beads"}, - "workflow_run": {"name": "ci", "conclusion": "failure", "id": 42, - "head_branch": "@everyone " + "x" * 300}} - def event_file(): - with open(event_path, "w") as target: json.dump(event, target) - event_file() - assert scope["main"]() == 0 and len(calls) == 1 - calls.clear() - event["workflow_run"]["conclusion"] = "success" - event_file() - assert scope["main"]() == 0 and not calls - event["workflow_run"]["conclusion"] = "failure" - for field, invalid in [("repository", "other/repo"), ("workflow", "release")]: - original_repo = event["repository"]["full_name"] - original_name = event["workflow_run"]["name"] - if field == "repository": event["repository"]["full_name"] = invalid - else: event["workflow_run"]["name"] = invalid - event_file() - try: scope["main"](); raise AssertionError("Untrusted metadata accepted") - except SystemExit as error: assert "Unexpected" in str(error) - assert not calls - event["repository"]["full_name"] = original_repo - event["workflow_run"]["name"] = original_name - event_file() - for invalid in ["", "https://other.example/api/webhooks/123/token"]: - os.environ["DISCORD_CI_WEBHOOK_URL"] = invalid - try: scope["main"](); raise AssertionError("Missing/incorrect destination accepted") - except SystemExit as error: assert "Set DISCORD_CI_WEBHOOK_URL" in str(error) - assert not calls - os.environ["DISCORD_CI_WEBHOOK_URL"] = webhook - for failure in ["http", "network"]: - mode = failure - calls.clear() - try: scope["main"](); raise AssertionError("Delivery failure hidden") - except SystemExit as error: - assert webhook not in str(error) and "fixture-not-real" not in str(error) - assert "HTTP 403" in str(error) if failure == "http" else "uncertain" in str(error) - assert len(calls) == 1 -print("NOTIFIER_OFFLINE_PASS") -`; - const child = Bun.spawn([process.platform === "win32" ? "python" : "python3", "-c", program], { - stdout: "pipe", - stderr: "pipe", - }); - const [code, stdout, stderr] = await Promise.all([ - child.exited, - new Response(child.stdout).text(), - new Response(child.stderr).text(), - ]); - expect(code, stderr).toBe(0); - expect(stdout).toContain("NOTIFIER_OFFLINE_PASS"); - expect(stdout + stderr).not.toContain("fixture-not-real"); + expect(text).toMatch(/^permissions: \{\}$/m); + expect(text).not.toMatch(/\buses:|download-artifact/); + expect(text).toContain("DISCORD_CI_WEBHOOK_URL: ${{ secrets.DISCORD_CI_WEBHOOK_URL }}"); +}); + +const senderSource = workflowText.then((text) => { + const [, indent, body] = text.match(/^( +)python3 - <<'PY'\n([\s\S]+?)^\1PY$/m) ?? []; + if (!indent || !body) throw new Error("Expected an inline Python sender in the failure notifier workflow"); + return body.replace(new RegExp(`^${indent}`, "gm"), ""); +}); + +test.each([ + { name: "successful delivery", attempts: 1, output: "Discord accepted message ID 456" }, + { name: "successful upstream run", conclusion: "success" }, + { name: "unexpected repository", repository: "other/repo", error: "Unexpected repository or workflow" }, + { name: "unexpected workflow", workflowName: "release", error: "Unexpected repository or workflow" }, + { name: "missing webhook", destination: "", error: "Set DISCORD_CI_WEBHOOK_URL" }, + { + name: "incorrect webhook host", + destination: `https://other.example/api/webhooks/123/${inertToken}`, + error: "Set DISCORD_CI_WEBHOOK_URL", + }, + { name: "HTTP rejection", failure: "http", attempts: 1, error: "HTTP 403" }, + { name: "network failure", failure: "network", attempts: 1, error: "delivery may be uncertain" }, +])("inline CI failure sender handles $name offline", async ({ name: _name, output, error, ...scenario }) => { + const child = Bun.spawnSync( + [python, "-I", fixture, JSON.stringify({ destination: webhook, attempts: 0, ...scenario })], + { stdin: Buffer.from(await senderSource, "utf8"), stdout: "pipe", stderr: "pipe" }, + ); + const stdout = child.stdout.toString(); + const stderr = child.stderr.toString(); + expect(stdout + stderr).not.toContain(inertToken); + expect(child.exitCode, stderr).toBe(error ? 1 : 0); + // A fixture assertion can also exit 1 and print the sender's original error in a chained traceback. + expect(stderr).not.toContain("Traceback (most recent call last)"); + if (error) expect(stderr).toContain(error); + else expect(stderr).toBe(""); + if (output) expect(stdout).toContain(output); + else expect(stdout).toBe(""); }); diff --git a/tests/command-payload-parity.test.ts b/tests/command-payload-parity.test.ts new file mode 100644 index 0000000..8b76419 --- /dev/null +++ b/tests/command-payload-parity.test.ts @@ -0,0 +1,67 @@ +import { createHash } from "node:crypto"; +import { resolve } from "node:path"; +import type { Plugin } from "@opencode/plugin"; +import type { CommandInvocation } from "@opencode/plugin/promise/command"; +import { describe, expect, mock, test } from "bun:test"; +import { createBeadsCommands, WORKFLOWS } from "../src/workflows"; +import baseline from "./fixtures/non-sync-command-baseline.json"; + +describe("historical command payload parity", () => { + test("all 29 historical non-sync payload digests preserve descriptions, instructions and diagnostics", async () => { + const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); + const actual: Record<string, string> = {}; + for (const c of createBeadsCommands( + { prompt }, + async () => "DIAGNOSTICS", + "/fixture/package/assets/oc-beads/SKILL.md", + )) { + if (c.name === "oc-beads:sync") continue; + await c.execute({ + sessionID: "s1", + delivery: "queue", + prompt: { + text: "exact 'details' $(nope) `literal`\nsecond line", + files: [{ uri: "file:///tmp/a%20b", name: "a b" }], + agents: [{ name: "build" }], + skills: [{ id: "oc-beads" }], + }, + } as unknown as CommandInvocation); + const submitted = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; + let sent = submitted; + if (c.name !== "oc-beads:diagnostics") { + // Restore the ORIGINAL fixed rich payload, including its native fields/key order. + // Existing hashes cover description + full submission, not bare instructions. + const { metadata, ...native } = submitted; + const snapshot = (metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; + // The frozen historical digest uses POSIX fixture paths, not the runner's drive/separators. + const resource = WORKFLOWS[c.name.slice("oc-beads:".length) as keyof typeof WORKFLOWS][1]; + const instructions = snapshot.instructions.replace( + JSON.stringify(resolve("/fixture/package/assets/oc-beads/resources", `${resource}.md`)), + JSON.stringify(`/fixture/package/assets/oc-beads/resources/${resource}.md`), + ); + sent = { + ...native, + text: `${instructions}\n\nLiteral user details:\nexact 'details' $(nope) \`literal\`\nsecond line`, + }; + } + if (c.name === "oc-beads:diagnostics") { + const { metadata, ...native } = submitted; + const snapshot = (metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; + // Diagnostics uses the current command purpose and accepted preamble. + // Exact full framing has dedicated coverage; generic workflow digests remain frozen. + sent = { + ...native, + text: `${snapshot.instructions.split("\n").slice(0, 2).join("\n")}\n\nUser request:\n${String(submitted.text).slice("/oc-beads:diagnostics\n".length)}`, + }; + } + actual[c.name] = createHash("sha256") + .update(JSON.stringify({ description: c.description, sent })) + .digest("hex"); + } + expect(actual).toEqual({ + ...baseline.commands, + "oc-beads:diagnostics": "8f85945c394e5c7548195ac9eb5303dacbbadc3230091c81534f1e5d1e3c390c", + "oc-beads:update": "b4f6a0e8b2729bab4361a6252a86217eac825b6c66f2db8d3dcc0f1803de7b25", + }); + }); +}); diff --git a/tests/context.test.ts b/tests/context.test.ts index e4ddcf7..cebe17c 100644 --- a/tests/context.test.ts +++ b/tests/context.test.ts @@ -75,23 +75,23 @@ describe("context controller", () => { const held = fixture({ guard: { kind: "unsupported", installed: "1.3.0" } }); expect(await held.controller.systemFor("s1", "build", typed)).not.toContain("direct shell"); }); - test("distinguishes missing, withheld, failed and intentionally empty context", async () => { - const missing = fixture({ guard: { kind: "uninitialized" } }); - await missing.controller.systemFor("s1", "build"); - expect(missing.controller.statusFor("s1", "primary")).toBe("missing"); - const held = fixture({ guard: { kind: "unsupported", installed: "1.3.0" } }); - await held.controller.systemFor("s1", "build"); - expect(held.controller.statusFor("s1", "primary")).toBe("withheld"); - const failed = fixture({ - prime: async () => { - throw new Error("failure"); + test.each([ + ["the workspace is uninitialized", { guard: { kind: "uninitialized" } }, "missing"], + ["the CLI is unsupported", { guard: { kind: "unsupported", installed: "1.3.0" } }, "withheld"], + [ + "prime rejects", + { + prime: async (): Promise<string> => { + throw new Error("failure"); + }, }, - }); - await failed.controller.systemFor("s1", "build"); - expect(failed.controller.statusFor("s1", "primary")).toBe("failed"); - const empty = fixture({ prime: async () => "" }); - await empty.controller.systemFor("s1", "build"); - expect(empty.controller.statusFor("s1", "primary")).toBe("empty"); + "failed", + ], + ["prime returns no text", { prime: async (): Promise<string> => "" }, "empty"], + ] as const)("reports context status when %s", async (_label, options, expectedStatus) => { + const { controller } = fixture(options); + await controller.systemFor("s1", "build"); + expect(controller.statusFor("s1", "primary")).toBe(expectedStatus); }); test("aborts stale loads on invalidation and unload without leaking a late result", async () => { diff --git a/tests/continuity.test.ts b/tests/continuity.test.ts index f4daa4e..2d99d8e 100644 --- a/tests/continuity.test.ts +++ b/tests/continuity.test.ts @@ -1,3 +1,4 @@ +import Ajv from "ajv"; import { describe, expect, mock, test } from "bun:test"; import type { ToolContext } from "@opencode/plugin/promise/tool"; import { @@ -5,6 +6,8 @@ import { executorActor, type ContinuityDependencies, type ContinuityHost, + type ContinuityResult, + type Operation, } from "../src/continuity"; import { PrimeProcessError, PrimeTimeoutError, type PrimeExecutionOptions } from "../src/prime"; @@ -18,17 +21,25 @@ const invocation = (signal = new AbortController().signal) => progress: async () => {}, }) as unknown as ToolContext; -function fixture() { - let output = JSON.stringify({ key: "lesson", value: "first\nsecond", action: "remembered" }); +const validator = new Ajv(); + +function expectSchema(schema: unknown, value: unknown, valid = true) { + if (typeof schema !== "object" || schema === null) throw new Error("Missing registered JSON Schema"); + const validate = validator.compile(schema); + expect(validate(value), validator.errorsText(validate.errors)).toBe(valid); +} + +function fixture(realpath: ContinuityDependencies["realpath"] = async (path) => path) { let directory = "/project"; - let workspace = "/project/.beads"; - const permission = mock(async (_input: unknown) => {}); - const acknowledged = mock((_sessionID: string, _result: unknown) => {}); + const version = mock(async () => "bd version 1.3.1"); + let workspace = '{"beads_dir":"/project/.beads","backend":"dolt","dolt_mode":"embedded","database":"beads"}'; + const reply = mock(async (_args: readonly string[]) => "{}"); + const permission = mock<ContinuityHost["permission"]["assert"]>(async () => {}); + const acknowledged = mock<NonNullable<ContinuityDependencies["acknowledged"]>>(() => {}); const bd = mock(async (_cwd: string, args: readonly string[], _options?: PrimeExecutionOptions) => { - if (args[0] === "version") return "bd version 1.3.1"; - if (args[0] === "context") - return JSON.stringify({ beads_dir: workspace, backend: "dolt", dolt_mode: "embedded", database: "beads" }); - return output; + if (args[0] === "version") return version(); + if (args[0] === "context") return workspace; + return reply(args); }); const host = { location: { directory: "/project", project: { directory: "/project" } }, @@ -38,47 +49,268 @@ function fixture() { const dependencies: ContinuityDependencies = { bd, acknowledged, - realpath: async (path) => path, + realpath, }; const tools = createContinuityTools(host, dependencies); - const execute = (name: string, input: unknown, context = invocation()) => { + const registered = (name: Operation) => { const tool = tools.find((tool) => tool.name === name); if (!tool) throw new Error(`missing tool ${name}`); - return tool.execute(input, context).then((result) => { - const schema = tool.output as { - anyOf: Array<{ properties: Record<string, { const?: unknown }>; required: string[] }>; - }; - const branch = schema.anyOf.find((b) => b.properties.status?.const === result.output.status); - expect(branch).toBeDefined(); - for (const required of branch!.required) expect(Object.hasOwn(result.output as object, required)).toBeTrue(); - expect(Object.keys(result.output as object).every((k) => k in branch!.properties)).toBeTrue(); - expect(result.output.operation).toBe(name); - if (["claim", "note", "update", "close", "create", "remember"].includes(name)) - expect(result.output.actor).toBe(executorActor(context)); - expect(JSON.parse(String(result.content))).toEqual(result.output); - return result; - }); + return tool; + }; + const executeRaw = async (name: Operation, input: unknown, context = invocation()) => { + const tool = registered(name); + const result = await tool.execute(input, context); + expectSchema(tool.output, result.output); + expect(JSON.parse(String(result.content))).toStrictEqual(result.output); + return result; + }; + const execute = (name: Operation, input: unknown, context = invocation()) => { + expectSchema(registered(name).input, input); + return executeRaw(name, input, context); }; return { tools, execute, + executeRaw, + registered, + reply, + spawns: () => bd.mock.calls.filter(([, args]) => args[0] !== "version" && args[0] !== "context"), bd, permission, acknowledged, dependencies, output: (value: string) => { - output = value; + reply.mockResolvedValue(value); }, move: (value: string) => { directory = value; }, + version, workspace: (value: string) => { workspace = value; }, }; } -describe("continuity adapter (plugin fixtures, not host qualification)", () => { +const actor = "opencode:restricted-worker:960defe988fd"; +const row = { id: "task-1", title: "Task", status: "open", priority: 2, issue_type: "task" }; +const note = { id: "task-1", text: "new\n'quoted'" }; +const notedIssue = { ...row, notes: "prior\nnew\n'quoted'" }; +const unsupportedReply = "Unsupported CLI acknowledgement; inspect current durable state before another write"; +const memoryText = "first\n'quoted' $(echo never) `never` --force"; + +const cases: Array<{ + name: Operation; + input: unknown; + cli: unknown; + args: string[]; + resource?: string; + result: Omit<ContinuityResult, "operation">; +}> = [ + { + name: "find", + input: { view: "search", text: "--assignee=x", status: "open", assignee: actor, labels: ["a"], limit: 1 }, + cli: [row, { ...row, id: "task-2" }], + args: [ + "search", + "--assignee", + actor, + "--status", + "open", + "--label", + "a", + "--limit", + "2", + "--json", + "--sandbox", + "--", + "--assignee=x", + ], + result: { + status: "acknowledged", + complete: false, + limit: 1, + view: "search", + target: { view: "search", text: "--assignee=x", status: "open", assignee: actor, labels: ["a"], limit: 1 }, + scope: { view: "search", text: "--assignee=x", status: "open", assignee: actor, labels: ["a"], limit: 1 }, + records: [{ id: "task-1", title: "Task", status: "open", priority: 2, type: "task" }], + }, + }, + { + name: "get", + input: { ids: ["task-1"] }, + cli: [row], + args: ["show", "task-1", "--json", "--sandbox"], + result: { status: "acknowledged", target: ["task-1"], issues: { "task-1": row }, failed: [], complete: true }, + }, + { + name: "edges", + input: { id: "task-1", direction: "up", types: ["blocks"] }, + cli: [{ ...row, dependency_type: "blocks", extra: { source: "cli" } }], + args: ["dep", "list", "task-1", "--direction", "up", "--type", "blocks", "--json", "--sandbox"], + result: { + status: "acknowledged", + target: "task-1", + complete: null, + direction: "up", + scope: { id: "task-1", direction: "up", types: ["blocks"] }, + records: [{ ...row, dependency_type: "blocks", extra: { source: "cli" } }], + }, + }, + { + name: "memories", + input: { search: "--force" }, + cli: { schema_version: 1, lesson: "text" }, + args: ["memories", "--json", "--sandbox", "--", "--force"], + result: { status: "found", target: { search: "--force" }, memories: { lesson: "text" } }, + }, + { + name: "recall", + input: { key: "lesson" }, + cli: { key: "lesson", found: true, value: "" }, + args: ["recall", "lesson", "--json", "--sandbox"], + result: { status: "found", target: "lesson", reference: "lesson", value: "" }, + }, + { + name: "claim", + input: { id: "task-1" }, + cli: [{ ...row, assignee: actor, status: "in_progress" }], + args: ["update", "task-1", "--claim", "--json", "--actor", actor, "--sandbox"], + result: { + status: "acknowledged", + target: "task-1", + actor, + reference: "task-1", + issue: { ...row, assignee: actor, status: "in_progress" }, + }, + }, + { + name: "note", + input: note, + resource: "bd update task-1 --append-notes 'new\n'\\''quoted'\\''' --json --actor " + actor + " --sandbox", + cli: [notedIssue], + args: ["update", "task-1", "--append-notes", "new\n'quoted'", "--json", "--actor", actor, "--sandbox"], + result: { status: "acknowledged", target: "task-1", actor, reference: "task-1", issue: notedIssue }, + }, + { + name: "update", + input: { id: "task-1", set: { status: "blocked", priority: 1, addLabels: ["a"], removeLabels: ["b"] } }, + cli: [{ ...row, status: "blocked", priority: 1, labels: ["a"] }], + args: [ + "update", + "task-1", + "--status", + "blocked", + "--priority", + "1", + "--add-label", + "a", + "--remove-label", + "b", + "--json", + "--actor", + actor, + "--sandbox", + ], + result: { + status: "acknowledged", + target: "task-1", + actor, + reference: "task-1", + issue: { ...row, status: "blocked", priority: 1, labels: ["a"] }, + }, + }, + { + name: "close", + input: { id: "task-1", reason: "Accepted" }, + cli: [{ ...row, status: "closed" }], + args: ["close", "task-1", "--reason", "Accepted", "--json", "--actor", actor, "--sandbox"], + result: { + status: "acknowledged", + target: "task-1", + actor, + reference: "task-1", + issue: { ...row, status: "closed" }, + }, + }, + { + name: "create", + input: { + title: "--assignee=x", + type: "task", + priority: 2, + description: "d", + acceptance: "a", + design: "r", + parent: "epic-1", + discoveredFrom: "task-1", + labels: ["a"], + }, + cli: { ...row, id: "generated-1", title: "--assignee=x" }, + args: [ + "create", + "--title", + "--assignee=x", + "--type", + "task", + "--priority", + "2", + "--description", + "d", + "--acceptance", + "a", + "--design", + "r", + "--parent", + "epic-1", + "--deps", + "discovered-from:task-1", + "--labels", + "a", + "--json", + "--actor", + actor, + "--sandbox", + ], + result: { + status: "acknowledged", + actor, + reference: "generated-1", + target: { + title: "--assignee=x", + type: "task", + priority: 2, + description: "d", + acceptance: "a", + design: "r", + parent: "epic-1", + discoveredFrom: "task-1", + labels: ["a"], + }, + issue: { ...row, id: "generated-1", title: "--assignee=x" }, + }, + }, + { + name: "remember", + input: { key: "lesson", text: memoryText }, + resource: + "bd remember --key lesson --json --actor " + + actor + + " --sandbox -- 'first\n'\\''quoted'\\'' $(echo never) `never` --force'", + cli: { key: "lesson", value: memoryText, action: "updated" }, + args: ["remember", "--key", "lesson", "--json", "--actor", actor, "--sandbox", "--", memoryText], + result: { + status: "acknowledged", + target: "lesson", + actor, + reference: "lesson", + data: { key: "lesson", value: memoryText, action: "updated" }, + commitIndeterminate: false, + }, + }, +]; + +describe("continuity catalog and executor attribution", () => { test("declares eleven native namespace operations and structured output branches", () => { const f = fixture(); expect(f.tools.map((t) => t.name)).toEqual([ @@ -99,174 +331,363 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { expect(tool.output).toHaveProperty("anyOf"); } }); - const actor = "opencode:restricted-worker:960defe988fd"; - const row = { id: "task-1", title: "Task", status: "open", priority: 2, issue_type: "task" }; - const cases: Array<{ name: string; input: unknown; cli: unknown; args: string[]; result: Record<string, unknown> }> = - [ - { - name: "find", - input: { view: "search", text: "--assignee=x", status: "open", assignee: actor, labels: ["a"], limit: 1 }, - cli: [row, { ...row, id: "task-2" }], - args: [ - "search", - "--assignee", - actor, - "--status", - "open", - "--label", - "a", - "--limit", - "2", - "--json", - "--sandbox", - "--", - "--assignee=x", - ], - result: { status: "acknowledged", complete: false, limit: 1 }, - }, - { - name: "get", - input: { ids: ["task-1"] }, - cli: [row], - args: ["show", "task-1", "--json", "--sandbox"], - result: { status: "acknowledged", issues: { "task-1": row }, failed: [], complete: true }, - }, - { - name: "edges", - input: { id: "task-1", direction: "up", types: ["blocks"] }, - cli: [{ ...row, dependency_type: "blocks" }], - args: ["dep", "list", "task-1", "--direction", "up", "--type", "blocks", "--json", "--sandbox"], - result: { status: "acknowledged", complete: null, direction: "up" }, - }, - { - name: "memories", - input: { search: "--force" }, - cli: { schema_version: 1, lesson: "text" }, - args: ["memories", "--json", "--sandbox", "--", "--force"], - result: { status: "found", memories: { lesson: "text" } }, - }, - { - name: "recall", - input: { key: "lesson" }, - cli: { key: "lesson", found: true, value: "" }, - args: ["recall", "lesson", "--json", "--sandbox"], - result: { status: "found", value: "" }, - }, - { - name: "claim", - input: { id: "task-1" }, - cli: [{ ...row, assignee: actor, status: "in_progress" }], - args: ["update", "task-1", "--claim", "--json", "--actor", actor, "--sandbox"], - result: { status: "acknowledged", reference: "task-1" }, - }, - { - name: "note", - input: { id: "task-1", text: "new\n'quoted'" }, - cli: [{ ...row, notes: "prior\nnew\n'quoted'" }], - args: ["update", "task-1", "--append-notes", "new\n'quoted'", "--json", "--actor", actor, "--sandbox"], - result: { status: "acknowledged", reference: "task-1" }, - }, - { - name: "update", - input: { id: "task-1", set: { status: "blocked", priority: 1, addLabels: ["a"], removeLabels: ["b"] } }, - cli: [{ ...row, status: "blocked", priority: 1, labels: ["a"] }], - args: [ - "update", - "task-1", - "--status", - "blocked", - "--priority", - "1", - "--add-label", - "a", - "--remove-label", - "b", - "--json", - "--actor", - actor, - "--sandbox", - ], - result: { status: "acknowledged", reference: "task-1" }, - }, - { - name: "close", - input: { id: "task-1", reason: "Accepted" }, - cli: [{ ...row, status: "closed" }], - args: ["close", "task-1", "--reason", "Accepted", "--json", "--actor", actor, "--sandbox"], - result: { status: "acknowledged", reference: "task-1" }, - }, - { - name: "create", - input: { - title: "--assignee=x", - type: "task", - priority: 2, - description: "d", - acceptance: "a", - design: "r", - parent: "epic-1", - discoveredFrom: "task-1", - labels: ["a"], - }, - cli: { ...row, id: "generated-1", title: "--assignee=x" }, - args: [ - "create", - "--title", - "--assignee=x", - "--type", - "task", - "--priority", - "2", - "--description", - "d", - "--acceptance", - "a", - "--design", - "r", - "--parent", - "epic-1", - "--deps", - "discovered-from:task-1", - "--labels", - "a", - "--json", - "--actor", - actor, - "--sandbox", + + test("derives stable audit attribution from the invocation session and executor", () => { + expect(executorActor(invocation())).toBe("opencode:restricted-worker:960defe988fd"); + expect(executorActor({ ...invocation(), id: "another-call" } as unknown as ToolContext)).toBe( + executorActor(invocation()), + ); + expect(executorActor({ ...invocation(), agent: "another-worker" } as unknown as ToolContext)).not.toBe( + executorActor(invocation()), + ); + expect(executorActor({ ...invocation(), sessionID: "another-session" } as unknown as ToolContext)).not.toBe( + executorActor(invocation()), + ); + expect(() => executorActor({ ...invocation(), agent: "" } as ToolContext)).toThrow("executor"); + }); +}); + +describe("continuity request translation", () => { + for (const { name, input, cli, args, resource } of cases) { + test(`${name} uses the exact approved argv in the invocation directory`, async () => { + const f = fixture(); + f.output(JSON.stringify(cli)); + const context = invocation(); + await f.execute(name, input, context); + const spawns = f.spawns(); + expect(spawns).toEqual([["/project", args, { signal: context.signal }]]); + expect(spawns[0]?.[2]?.signal).toBe(context.signal); + expect(f.permission.mock.calls).toEqual([ + [ + { + action: "shell", + agent: "restricted-worker", + sessionID: "session-1", + save: [], + source: { type: "tool", messageID: "message-1", id: "call-1" }, + resources: [resource ?? ["bd", ...args].join(" ")], + }, ], - result: { status: "acknowledged", reference: "generated-1" }, - }, - { - name: "remember", - input: { key: "lesson", text: "text" }, - cli: { key: "lesson", value: "text", action: "updated" }, - args: ["remember", "--key", "lesson", "--json", "--actor", actor, "--sandbox", "--", "text"], - result: { status: "acknowledged", reference: "lesson" }, - }, - ]; - for (const c of cases) - test(`${c.name}: qualified argv, resource and declared success branch`, async () => { + ]); + }); + } + + test.each([ + ["find", { view: "search", text: "q", parent: "epic" }, "parent unsupported"], + ["find", { view: "ready", status: "open" }, "Invalid status"], + ["update", { id: "task-1", set: { status: "closed" } }, "Invalid update status"], + ["create", { title: "a", type: "task", priority: 2, assignee: actor }, "assignee"], + ["get", { ids: ["task-1", "task-1"] }, "Invalid ids"], + ["remember", { key: "lesson", text: "hello", actor: "human" }, "actor"], + ["remember", { key: "lesson", text: "hello", force: true }, "force"], + ["recall", { key: "lesson", cwd: "/elsewhere" }, "cwd"], + ] satisfies [Operation, unknown, string][])( + "%s rejects raw input before permission (%j)", + async (name, input, message) => { const f = fixture(); - f.output(JSON.stringify(c.cli)); - expect((await f.execute(c.name, c.input)).output).toMatchObject(c.result); - expect(f.bd.mock.calls.at(-1)?.[1]).toEqual(c.args); - const quote = (a: string) => (/^[a-zA-Z0-9_./:=-]+$/.test(a) ? a : "'" + a.replaceAll("'", "'\\''") + "'"); - expect(f.permission).toHaveBeenCalledWith( - expect.objectContaining({ action: "shell", resources: [["bd", ...c.args].map(quote).join(" ")], save: [] }), - ); - f.output(JSON.stringify(c.name === "memories" ? { schema_version: 2 } : {})); - expect((await f.execute(c.name, c.input)).output.status).toBe( - ["find", "get", "edges", "memories", "recall"].includes(c.name) ? "failed" : "uncertain", - ); + expectSchema(f.registered(name).input, input, false); + await expect(f.executeRaw(name, input)).rejects.toThrow(message); + expect(f.permission).not.toHaveBeenCalled(); + expect(f.bd).not.toHaveBeenCalled(); + }, + ); + + test("find reports the first invalid filter before requesting permission", async () => { + const f = fixture(); + await expect(f.executeRaw("find", { view: "invalid", limit: 0 })).rejects.toThrow("Invalid view"); + await expect(f.executeRaw("find", { view: "search", limit: 0, parent: "epic" })).rejects.toThrow("Invalid limit"); + await expect(f.executeRaw("find", { view: "search", parent: "epic" })).rejects.toThrow("Invalid text"); + expect(f.permission).not.toHaveBeenCalled(); + expect(f.bd).not.toHaveBeenCalled(); + }); + + test("update validates both label lists before checking overlap or requesting permission", async () => { + const f = fixture(); + for (const [set, message, schemaValid] of [ + [{ addLabels: [], removeLabels: [] }, "Invalid addLabels", false], + [{ addLabels: ["a"], removeLabels: ["a", "a"] }, "Invalid removeLabels", false], + [{ addLabels: ["a"], removeLabels: ["a"] }, "Conflicting label update", true], + ] as const) { + const input = { id: "task-1", set }; + expectSchema(f.registered("update").input, input, schemaValid); + await expect(f.executeRaw("update", input)).rejects.toThrow(message); + } + expect(f.permission).not.toHaveBeenCalled(); + expect(f.bd).not.toHaveBeenCalled(); + }); + + test("raw JS optional undefined is omitted from the memories target", async () => { + const f = fixture(); + f.output('{"schema_version":1}'); + expect((await f.executeRaw("memories", { search: undefined })).output).toStrictEqual({ + operation: "memories", + target: {}, + status: "found", + memories: {}, + }); + }); +}); + +describe("continuity spawn decisions", () => { + test("requires executor attribution before permission", async () => { + const f = fixture(); + await expect(f.execute("note", note, { ...invocation(), agent: "" } as ToolContext)).rejects.toThrow("executor"); + expect(f.permission).not.toHaveBeenCalled(); + expect(f.bd).not.toHaveBeenCalled(); + }); + + test("propagates permission denial for reads and writes without spawning", async () => { + const f = fixture(); + const denial = new Error("permission rejected"); + f.permission.mockRejectedValue(denial); + await expect(f.execute("note", note)).rejects.toBe(denial); + await expect(f.execute("get", { ids: ["task-1"] })).rejects.toBe(denial); + expect(f.permission).toHaveBeenCalledTimes(2); + expect(f.spawns()).toHaveLength(0); + expect(f.acknowledged).not.toHaveBeenCalled(); + }); + + test("rechecks actual session location after approval", async () => { + const f = fixture(); + f.permission.mockImplementation(async () => f.move("/elsewhere")); + await expect(f.execute("get", { ids: ["task-1"] })).rejects.toThrow("location"); + expect(f.spawns()).toHaveLength(0); + }); + + test("an already aborted note reaches neither permission nor spawn", async () => { + const f = fixture(); + const signal = AbortSignal.abort(); + await expect(f.execute("note", note, invocation(signal))).rejects.toBe(signal.reason); + expect(f.permission).not.toHaveBeenCalled(); + expect(f.spawns()).toHaveLength(0); + expect(f.acknowledged).not.toHaveBeenCalled(); + }); + + test("unload aborts a note awaiting approval and late approval cannot spawn it", async () => { + const f = fixture(); + const abort = new AbortController(); + f.dependencies.signal = abort.signal; + const approval = Promise.withResolvers<void>(); + const permissionRequested = Promise.withResolvers<void>(); + f.permission.mockImplementation(() => { + permissionRequested.resolve(); + return approval.promise; + }); + const pending = f.execute("note", note); + await permissionRequested.promise; + abort.abort(); + await expect(pending).rejects.toBe(abort.signal.reason); + approval.resolve(); + // Let the late approval and any continuations run before checking the spawn count. + await new Promise<void>((resolve) => setImmediate(resolve)); + expect(f.permission).toHaveBeenCalledTimes(1); + expect(f.spawns()).toHaveLength(0); + expect(f.acknowledged).not.toHaveBeenCalled(); + }); + + test("cancellation after note approval still prevents spawn", async () => { + const f = fixture(); + const abort = new AbortController(); + const secondGuard = Promise.withResolvers<void>(); + const version = Promise.withResolvers<string>(); + f.permission.mockImplementation(async () => { + f.version.mockImplementation(() => { + secondGuard.resolve(); + return version.promise; + }); + }); + const pending = f.execute("note", note, invocation(abort.signal)); + await secondGuard.promise; + abort.abort(); + version.resolve("1.3.1"); + await expect(pending).rejects.toBe(abort.signal.reason); + expect(f.permission).toHaveBeenCalledTimes(1); + expect(f.spawns()).toHaveLength(0); + expect(f.acknowledged).not.toHaveBeenCalled(); + }); + + test("batch get requests one approval for both IDs and rechecks location before the next spawn", async () => { + const f = fixture(); + f.reply.mockImplementation(async () => { + f.move("/moved"); + return JSON.stringify([row]); + }); + await expect(f.execute("get", { ids: ["task-1", "task-2"] })).rejects.toThrow("location"); + expect(f.permission).toHaveBeenCalledTimes(1); + expect(f.permission.mock.calls[0]![0].resources).toEqual([ + "bd show task-1 --json --sandbox", + "bd show task-2 --json --sandbox", + ]); + expect(f.spawns().map(([, args]) => args)).toEqual([["show", "task-1", "--json", "--sandbox"]]); + }); + + test("typed calls ignore stale, missing and different witnesses", async () => { + for (const marker of [undefined, "1.3.2", "1.3.4", "1.4.0"]) { + const f = fixture(); + const readText = mock(async () => marker); + Object.assign(f.dependencies, { readText }); + f.version.mockResolvedValue("1.3.4"); + f.output(JSON.stringify([{ id: "task-1", notes: "progress" }])); + expect((await f.execute("note", { id: "task-1", text: "progress" })).output.status).toBe("acknowledged"); + expect(readText).not.toHaveBeenCalled(); + expect(f.permission).toHaveBeenCalledTimes(1); + expect(f.spawns().at(-1)?.[1]).toContain("--actor"); + } + }); + + test("preserves minimum checks before and after shell approval", async () => { + for (const afterApproval of [false, true]) { + const f = fixture(); + f.version.mockResolvedValue(afterApproval ? "1.3.4" : "1.3.0"); + f.permission.mockImplementation(async () => { + f.version.mockResolvedValue("1.3.0"); + }); + await expect(f.execute("get", { ids: ["task-1"] })).rejects.toThrow("unsupported"); + expect(f.permission).toHaveBeenCalledTimes(afterApproval ? 1 : 0); + expect(f.spawns()).toHaveLength(0); + } + }); + + test("checks external access for the explicit resolved invocation directory, preserving denial and save:[]", async () => { + const f = fixture(async (path) => (path === "/project" ? "/external/work" : path)); + f.output('[{"id":"task-1"}]'); + await f.execute("get", { ids: ["task-1"] }); + expect(f.permission).toHaveBeenCalledWith( + expect.objectContaining({ + action: "external_directory", + resources: ["/external/work/*"], + save: [], + agent: "restricted-worker", + }), + ); + f.permission.mockImplementation(async (input) => { + if (input.action === "external_directory") throw new Error("external denied"); + }); + await expect(f.execute("get", { ids: ["task-1"] })).rejects.toThrow("external denied"); + expect(f.spawns()).toHaveLength(1); + }); + + test("leaves inherited Beads routing and backend choice to the installed CLI", async () => { + const f = fixture(); + const previous = process.env.BEADS_DIR; + f.workspace('{"beads_dir":"/shared/.beads","backend":"dolt","dolt_mode":"server","database":"team"}'); + f.output('[{"id":"task-1"}]'); + try { + f.permission.mockImplementation(async () => { + process.env.BEADS_DIR = "/shared/.beads"; + }); + expect((await f.execute("get", { ids: ["task-1"] })).output).toMatchObject({ + status: "acknowledged", + issues: { "task-1": { id: "task-1" } }, + }); + expect(process.env.BEADS_DIR).toBe("/shared/.beads"); + expect(f.spawns().at(-1)).toEqual(["/project", ["show", "task-1", "--json", "--sandbox"], expect.anything()]); + expect(f.permission.mock.calls.every(([input]) => input.action === "shell")).toBeTrue(); + } finally { + if (previous === undefined) delete process.env.BEADS_DIR; + else process.env.BEADS_DIR = previous; + } + }); +}); + +describe("continuity outcome evidence", () => { + test.each(["uncertain", "acknowledged"] as const)( + "a note aborted after spawn throws AbortError and reports %s evidence once", + async (status) => { + const f = fixture(); + const abort = new AbortController(); + f.reply.mockImplementation(async () => { + abort.abort(); + if (status === "uncertain") throw abort.signal.reason; + return JSON.stringify([notedIssue]); + }); + const pending = f.execute("note", note, invocation(abort.signal)); + await expect(pending).rejects.toHaveProperty("name", "AbortError"); + await expect(pending).rejects.toBe(abort.signal.reason); + const expected: ContinuityResult = { + operation: "note", + target: "task-1", + actor, + status, + ...(status === "uncertain" + ? { detail: abort.signal.reason.message } + : { reference: "task-1", issue: notedIssue }), + }; + expect(f.acknowledged.mock.calls).toStrictEqual([["session-1", expected]]); + expectSchema(f.registered("note").output, f.acknowledged.mock.calls[0]![1]); + expect(f.spawns()).toHaveLength(1); + }, + ); + + test("a timed-out note returns uncertainty and reports it once", async () => { + const f = fixture(); + const timeout = new PrimeTimeoutError(1); + f.reply.mockRejectedValue(timeout); + const expected: ContinuityResult = { + operation: "note", + target: "task-1", + actor, + status: "uncertain", + detail: timeout.message, + }; + expect((await f.execute("note", note)).output).toStrictEqual(expected); + expect(f.acknowledged.mock.calls).toStrictEqual([["session-1", expected]]); + expect(f.spawns()).toHaveLength(1); + }); + + test("notification failure retains the original diagnostic and persistence outcome", async () => { + const f = fixture(); + f.acknowledged.mockImplementation(() => { + throw new Error("notification failed"); + }); + expect((await f.execute("note", note)).output).toStrictEqual({ + operation: "note", + target: "task-1", + actor, + status: "uncertain", + detail: `${unsupportedReply}; Context refresh notification failed; the reported persistence outcome still applies.`, + }); + expect(f.acknowledged).toHaveBeenCalledTimes(1); + expect(f.spawns()).toHaveLength(1); + }); + + for (const { name, input, cli, result } of cases) { + test(`${name} reports the exact evidenced payload`, async () => { + const f = fixture(); + f.output(JSON.stringify(cli)); + const expected = { operation: name, ...result }; + expect((await f.execute(name, input)).output).toStrictEqual(expected); + expect(f.acknowledged.mock.calls).toStrictEqual([["session-1", expected]]); + }); + + test(`${name} classifies unsupported CLI evidence without retry`, async () => { + const f = fixture(); + f.output(name === "memories" ? '{"schema_version":2}' : "{}"); + expect((await f.execute(name, input)).output).toStrictEqual({ + operation: name, + target: result.target, + ...(result.actor ? { actor } : {}), + status: result.actor ? "uncertain" : "failed", + detail: name === "get" ? `task-1: ${unsupportedReply}` : unsupportedReply, + }); + expect(f.spawns()).toHaveLength(1); }); + } + test("create accepts a legacy single-row array and preserves the raw issue", async () => { const f = fixture(); const created = { ...row, id: "generated-1", created_by: actor, extra: { source: "cli" } }; const input = { title: row.title, type: row.issue_type, priority: row.priority }; f.output(JSON.stringify([created])); const result = await f.execute("create", input); - expect(result.output).toMatchObject({ status: "acknowledged", reference: created.id }); - expect(result.output.issue).toEqual(created); + expect(result.output).toStrictEqual({ + operation: "create", + target: input, + actor, + status: "acknowledged", + reference: created.id, + issue: created, + }); for (const reply of [[created, created], [{ ...created, assignee: null }]]) { f.output(JSON.stringify(reply)); @@ -304,50 +725,23 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { const f = fixture(); f.output(JSON.stringify([c.row])); const result = await f.execute("update", { id: native.id, set: c.set }); - expect(result.output.status).toBe(c.status); - expect(f.acknowledged).toHaveBeenCalledWith("session-1", expect.objectContaining({ status: c.status })); - expect(f.bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(1); + expect(result.output).toStrictEqual({ + operation: "update", + target: native.id, + actor, + status: c.status, + ...(c.status === "acknowledged" ? { reference: native.id, issue: c.row } : { detail: unsupportedReply }), + }); + expect(f.acknowledged.mock.calls).toStrictEqual([["session-1", result.output]]); + expect(f.spawns()).toHaveLength(1); } }); - test("batch get preserves per-ID failures; rechecks before the next child spawn", async () => { - const f = fixture(); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - if (args[1] === "task-2") throw new PrimeProcessError(1, "not found", "bd show"); - return JSON.stringify([{ ...row, id: args[1] }]); - }); - expect((await f.execute("get", { ids: ["task-1", "task-2"] })).output).toMatchObject({ - status: "acknowledged", - complete: false, - failed: [{ id: "task-2", detail: expect.stringContaining("not found") }], - }); - expect(f.permission.mock.calls).toHaveLength(1); - expect((f.permission.mock.calls[0]![0] as { resources: string[] }).resources).toEqual([ - "bd show task-1 --json --sandbox", - "bd show task-2 --json --sandbox", - ]); - expect((await f.execute("get", { ids: ["task-2"] })).output).toMatchObject({ - status: "failed", - target: ["task-2"], - }); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - f.move("/moved"); - return JSON.stringify([row]); - }); - const before = f.bd.mock.calls.filter(([, a]) => a[0] === "show").length; - await expect(f.execute("get", { ids: ["task-1", "task-2"] })).rejects.toThrow("location"); - expect(f.bd.mock.calls.filter(([, a]) => a[0] === "show")).toHaveLength(before + 1); - }); + test("batch get preserves its serialized result and exact show sequence", async () => { const f = fixture(); const first = { ...row, id: "10", extra: { source: "cli" } }; const second = { ...row, id: "2", extra: ["raw"] }; - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; + f.reply.mockImplementation(async (args) => { if (args[1] === "missing") throw new PrimeProcessError(1, " not found ", "bd show", " diagnostic "); if (args[1] === "invalid") return JSON.stringify([row]); return JSON.stringify([args[1] === "10" ? first : second]); @@ -376,11 +770,15 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { detail: `invalid: ${failed[1]!.detail}; missing: ${failed[0]!.detail}`, }), ); - await expect(f.execute("get", { ids: ["10", "10"] })).rejects.toThrow("Invalid ids"); - expect(f.bd.mock.calls.filter(([, args]) => args[0] === "show").map(([, args]) => args)).toEqual( + expect(f.spawns().map(([, args]) => args)).toEqual( [...partial, ...allFailed].map((id) => ["show", id, "--json", "--sandbox"]), ); + expect((await f.execute("get", { ids: ["missing"] })).output).toMatchObject({ + status: "failed", + target: ["missing"], + }); }); + test("find and edges distinguish bounded, unknown and failed data", async () => { const f = fixture(); f.output(JSON.stringify([row])); @@ -392,9 +790,24 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { expect((await f.execute("find", { view: "ready" })).output).toMatchObject({ status: "failed" }); f.output(JSON.stringify([{ ...row, title: "" }])); expect((await f.execute("get", { ids: ["task-1"] })).output.status).toBe("failed"); - f.output('{"schema_version":1}'); - expect((await f.execute("memories", { search: undefined })).output.target).toEqual({}); }); + + test("edges rejects malformed issue fields even when the dependency type is present", async () => { + const f = fixture(); + for (const edge of [ + { ...row, id: "--flag" }, + { ...row, priority: 5 }, + ]) { + f.output(JSON.stringify([{ ...edge, dependency_type: "blocks" }])); + expect((await f.execute("edges", { id: "task-1", direction: "down" })).output).toStrictEqual({ + operation: "edges", + target: "task-1", + status: "failed", + detail: unsupportedReply, + }); + } + }); + test("find and edges reject invalid rows beyond the result cap", async () => { const f = fixture(); const edge = { ...row, dependency_type: "blocks" }; @@ -409,6 +822,7 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { detail: expect.stringContaining("Unsupported CLI acknowledgement"), }); }); + test("claim uses observed non-claim evidence; ambiguous claim/create keep target and actor without retry", async () => { const f = fixture(); f.output(JSON.stringify([{ ...row, assignee: "another-worker", status: "in_progress" }])); @@ -423,9 +837,7 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { target: { title: "new task" }, actor, }); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; + f.reply.mockImplementation(async () => { throw new PrimeProcessError( 1, "Error updating task-1: issue already claimed\n" + @@ -448,330 +860,10 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { target: "task-1", actor, }); - expect(f.bd.mock.calls.filter(([, a]) => ["update", "create"].includes(a[0] ?? ""))).toHaveLength(3); - }); - test("started abort preserves recovery uncertainty and notification failure retains the original diagnostic", async () => { - const f = fixture(); - const abort = new AbortController(); - f.dependencies.acknowledged = () => { - throw new Error("notification failed"); - }; - f.output("{}"); - expect((await f.execute("note", { id: "task-1", text: "evidence" })).output.detail).toContain( - "Unsupported CLI acknowledgement", - ); - expect((await f.execute("note", { id: "task-1", text: "evidence" })).output.detail).toContain( - "notification failed", - ); - const g = fixture(); - g.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - abort.abort(); - throw abort.signal.reason; - }); - await expect(g.execute("note", { id: "task-1", text: "pending" }, invocation(abort.signal))).rejects.toHaveProperty( - "name", - "AbortError", - ); - expect(g.acknowledged).toHaveBeenCalledWith( - "session-1", - expect.objectContaining({ status: "uncertain", target: "task-1", actor }), - ); - }); - test("rejects unsupported variants and ownership changes before permission", async () => { - const f = fixture(); - for (const [name, input] of [ - ["find", { view: "search", text: "q", parent: "epic" }], - ["find", { view: "ready", status: "open" }], - ["update", { id: "task-1", set: { status: "closed" } }], - ["create", { title: "a", type: "task", priority: 2, assignee: actor }], - ["get", { ids: ["task-1", "task-1"] }], - ] as const) - await expect(f.execute(name, input)).rejects.toThrow(); - expect(f.permission).not.toHaveBeenCalled(); - }); - test("find reports the first invalid filter before requesting permission", async () => { - const f = fixture(); - await expect(f.execute("find", { view: "invalid", limit: 0 })).rejects.toThrow("Invalid view"); - await expect(f.execute("find", { view: "search", limit: 0, parent: "epic" })).rejects.toThrow("Invalid limit"); - await expect(f.execute("find", { view: "search", parent: "epic" })).rejects.toThrow("Invalid text"); - expect(f.permission).not.toHaveBeenCalled(); - }); - test("update validates both label lists before checking overlap or requesting permission", async () => { - const f = fixture(); - for (const [set, message] of [ - [{ addLabels: [], removeLabels: [] }, "Invalid addLabels"], - [{ addLabels: ["a"], removeLabels: ["a", "a"] }, "Invalid removeLabels"], - [{ addLabels: ["a"], removeLabels: ["a"] }, "Conflicting label update"], - ] as const) { - await expect(f.execute("update", { id: "task-1", set })).rejects.toThrow(message); - } - expect(f.permission).not.toHaveBeenCalled(); - }); - test("derives stable audit attribution from actual session and executor, independently of Git identity", () => { - expect(executorActor(invocation())).toBe("opencode:restricted-worker:960defe988fd"); - expect(executorActor({ ...invocation(), id: "another-call" } as unknown as ToolContext)).toBe( - executorActor(invocation()), - ); - expect(executorActor({ ...invocation(), agent: "another-worker" } as unknown as ToolContext)).not.toBe( - executorActor(invocation()), - ); - expect(executorActor({ ...invocation(), sessionID: "another-session" } as unknown as ToolContext)).not.toBe( - executorActor(invocation()), - ); - expect(() => executorActor({ ...invocation(), agent: "" } as ToolContext)).toThrow("executor"); - }); - test("executes fixed checkpoint/show operations in actual project context with explicit write attribution", async () => { - const f = fixture(); - f.output(JSON.stringify([{ id: "task-1", notes: "previous\nfirst\nsecond" }])); - expect((await f.execute("note", { id: "task-1", text: "first\nsecond" })).output).toMatchObject({ - status: "acknowledged", - reference: "task-1", - }); - expect(f.bd.mock.calls.at(-1)).toEqual([ - "/project", - [ - "update", - "task-1", - "--append-notes", - "first\nsecond", - "--json", - "--actor", - "opencode:restricted-worker:960defe988fd", - "--sandbox", - ], - expect.anything(), - ]); - expect(f.permission).toHaveBeenCalledWith( - expect.objectContaining({ - action: "shell", - agent: "restricted-worker", - sessionID: "session-1", - save: [], - source: { type: "tool", messageID: "message-1", id: "call-1" }, - resources: [expect.stringMatching(/^bd update task-1 --append-notes /)], - }), - ); - expect((await f.execute("get", { ids: ["task-1"] })).output).toMatchObject({ - status: "acknowledged", - issues: { "task-1": { id: "task-1" } }, - }); - expect(f.bd.mock.calls.at(-1)).toEqual(["/project", ["show", "task-1", "--json", "--sandbox"], expect.anything()]); - expect(f.bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(1); - expect(f.acknowledged).toHaveBeenCalledTimes(2); - }); - test("uses fixed multiline argv, actual invocation permission identity and explicit executor actor", async () => { - const f = fixture(); - expect(f.tools.map((tool) => tool.options?.permission)).toEqual(Array(11).fill("shell")); - const result = await f.execute("remember", { key: "lesson", text: "first\nsecond" }); - expect(f.bd.mock.calls.at(-1)).toEqual([ - "/project", - [ - "remember", - "--key", - "lesson", - "--json", - "--actor", - "opencode:restricted-worker:960defe988fd", - "--sandbox", - "--", - "first\nsecond", - ], - expect.anything(), - ]); - expect(f.permission).toHaveBeenCalledWith( - expect.objectContaining({ - action: "shell", - agent: "restricted-worker", - sessionID: "session-1", - save: [], - source: { type: "tool", messageID: "message-1", id: "call-1" }, - resources: [expect.stringMatching(/^bd remember --key lesson /)], - }), - ); - expect(result.output).toMatchObject({ status: "acknowledged", reference: "lesson" }); - expect(f.acknowledged).toHaveBeenCalledTimes(1); + expect(f.spawns()).toHaveLength(3); }); - test("rejects denied access, missing executor attribution and model supplied actor before mutation", async () => { - const f = fixture(); - await expect( - f.execute("remember", { key: "lesson", text: "hello" }, { ...invocation(), agent: "" } as ToolContext), - ).rejects.toThrow("executor"); - await expect(f.execute("remember", { key: "lesson", text: "hello", actor: "human" })).rejects.toThrow("actor"); - const denial = new Error("permission rejected"); - f.permission.mockImplementation(async () => { - throw denial; - }); - await expect(f.execute("note", { id: "task-1", text: "hello" })).rejects.toBe(denial); - await expect(f.execute("get", { ids: ["task-1"] })).rejects.toBe(denial); - expect(f.bd.mock.calls.every(([, args]) => ["version", "context"].includes(args[0] ?? ""))).toBeTrue(); - }); - - test("rechecks cancellation and actual session location after approval", async () => { - const f = fixture(); - const abort = new AbortController(); - f.permission.mockImplementation(async () => { - abort.abort(); - }); - await expect(f.execute("note", { id: "task-1", text: "hello" }, invocation(abort.signal))).rejects.toHaveProperty( - "name", - "AbortError", - ); - f.permission.mockImplementation(async () => { - f.move("/elsewhere"); - }); - await expect(f.execute("get", { ids: ["task-1"] })).rejects.toThrow("location"); - expect(f.bd.mock.calls.some(([, args]) => args[0] === "recall")).toBeFalse(); - }); - - test("typed calls ignore stale, missing and different witnesses", async () => { - for (const marker of [undefined, "1.3.2", "1.3.4", "1.4.0"]) { - const f = fixture(); - const readText = mock(async () => marker); - Object.assign(f.dependencies, { readText }); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.4"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - return JSON.stringify([{ id: "task-1", notes: "progress" }]); - }); - expect((await f.execute("note", { id: "task-1", text: "progress" })).output.status).toBe("acknowledged"); - expect(readText).not.toHaveBeenCalled(); - expect(f.permission).toHaveBeenCalledTimes(1); - expect(f.bd.mock.calls.at(-1)?.[1]).toContain("--actor"); - } - }); - - test("preserves minimum checks before and after shell approval", async () => { - for (const afterApproval of [false, true]) { - const f = fixture(); - let version = afterApproval ? "1.3.4" : "1.3.0"; - f.bd.mockImplementation(async (_cwd, args) => - args[0] === "version" ? version : '{"beads_dir":"/project/.beads"}', - ); - f.permission.mockImplementation(async () => { - version = "1.3.0"; - }); - await expect(f.execute("get", { ids: ["task-1"] })).rejects.toThrow("unsupported"); - expect(f.bd.mock.calls.some(([, args]) => args[0] === "show")).toBeFalse(); - } - }); - - test("checks external access for the explicit resolved invocation directory, preserving denial and save:[]", async () => { - const f = fixture(); - const host = { - location: { directory: "/project", project: { directory: "/project" } }, - permission: { assert: f.permission }, - session: { get: async () => ({ location: { directory: "/project" } }) }, - } as unknown as ContinuityHost; - const tools = createContinuityTools(host, { - ...f.dependencies, - realpath: async (path) => (path === "/project" ? "/external/work" : path), - }); - const show = tools.find((tool) => tool.name === "get")!; - f.output('[{"id":"task-1"}]'); - await show.execute({ ids: ["task-1"] }, invocation()); - expect(f.permission).toHaveBeenCalledWith( - expect.objectContaining({ - action: "external_directory", - resources: ["/external/work/*"], - save: [], - agent: "restricted-worker", - }), - ); - f.permission.mockImplementation(async (input) => { - if ((input as { action: string }).action === "external_directory") throw new Error("external denied"); - }); - await expect(show.execute({ ids: ["task-1"] }, invocation())).rejects.toThrow("external denied"); - expect(f.bd.mock.calls.filter(([, args]) => args[0] === "show")).toHaveLength(1); - }); - - test("leaves inherited Beads routing and backend choice to the installed CLI", async () => { - const f = fixture(); - const previous = process.env.BEADS_DIR; - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") - return '{"beads_dir":"/shared/.beads","backend":"dolt","dolt_mode":"server","database":"team"}'; - return '[{"id":"task-1"}]'; - }); - try { - f.permission.mockImplementation(async () => { - process.env.BEADS_DIR = "/shared/.beads"; - }); - expect((await f.execute("get", { ids: ["task-1"] })).output).toMatchObject({ - status: "acknowledged", - issues: { "task-1": { id: "task-1" } }, - }); - expect(process.env.BEADS_DIR).toBe("/shared/.beads"); - expect(f.bd.mock.calls.at(-1)).toEqual([ - "/project", - ["show", "task-1", "--json", "--sandbox"], - expect.anything(), - ]); - expect(f.permission.mock.calls.every(([input]) => (input as { action: string }).action === "shell")).toBeTrue(); - } finally { - if (previous === undefined) delete process.env.BEADS_DIR; - else process.env.BEADS_DIR = previous; - } - }); - - test("unload aborts a pending approval and a later approval cannot spawn", async () => { - const f = fixture(); - const abort = new AbortController(); - let approve: () => void = () => {}; - f.permission.mockImplementation( - () => - new Promise<void>((resolve) => { - approve = resolve; - }), - ); - const pending = f.execute("recall", { key: "lesson" }, invocation(abort.signal)); - for (let i = 0; i < 20 && f.permission.mock.calls.length === 0; i++) - await new Promise((resolve) => setTimeout(resolve, 0)); - abort.abort(); - await expect(pending).rejects.toHaveProperty("name", "AbortError"); - approve(); - await Promise.resolve(); - expect(f.bd.mock.calls.some(([, args]) => args[0] === "recall")).toBeFalse(); - }); - - test("keeps quoted multiline content as a single argv value and exposes no force or arbitrary execution fields", async () => { - const f = fixture(); - const text = "first\n'quoted' $(echo never) `never` --force"; - f.output(JSON.stringify({ key: "lesson", value: text, action: "remembered" })); - await f.execute("remember", { key: "lesson", text }); - const argv = f.bd.mock.calls.at(-1)?.[1]; - expect(argv).toEqual([ - "remember", - "--key", - "lesson", - "--json", - "--actor", - "opencode:restricted-worker:960defe988fd", - "--sandbox", - "--", - text, - ]); - await expect(f.execute("remember", { key: "lesson", text: "hello", force: true })).rejects.toThrow("force"); - await expect(f.execute("recall", { key: "lesson", cwd: "/elsewhere" })).rejects.toThrow("cwd"); - f.output("{}"); - expect((await f.execute("memories", { search: "--force" })).output).toMatchObject({ - status: "found", - memories: {}, - }); - expect(f.bd.mock.calls.at(-1)?.[1]).toEqual(["memories", "--json", "--sandbox", "--", "--force"]); - }); - - test("treats exit zero without a matching acknowledgement as uncertain and never retries", async () => { - const f = fixture(); - f.output("{}"); - expect((await f.execute("note", { id: "task-1", text: "hello" })).output).toMatchObject({ status: "uncertain" }); - expect(f.bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(1); - }); - - test("distinguishes landed but uncommitted memory and interrupted writes without retry", async () => { + test("distinguishes landed but uncommitted memory", async () => { const f = fixture(); f.output( JSON.stringify({ @@ -783,25 +875,29 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { commit_indeterminate: true, }), ); - expect((await f.execute("remember", { key: "lesson", text: "validated finding" })).output).toMatchObject({ + expect((await f.execute("remember", { key: "lesson", text: "validated finding" })).output).toStrictEqual({ + operation: "remember", + target: "lesson", + actor, + data: { + key: "lesson", + value: "validated finding", + action: "remembered", + committed: false, + commit_error: "dirty keys", + commit_indeterminate: true, + }, status: "landed-uncommitted", reference: "lesson", commitIndeterminate: true, }); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") - return '{"beads_dir":"/project/.beads","backend":"dolt","dolt_mode":"embedded","database":"beads"}'; - throw new PrimeTimeoutError(1); - }); - expect((await f.execute("note", { id: "task-1", text: "hello" })).output).toMatchObject({ status: "uncertain" }); - expect(f.bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(1); }); test("accepts versioned memory lists without treating schema metadata as memory", async () => { - for (const entries of [{}, { lesson: "first\nsecond" }]) { + for (const payload of [{}, { schema_version: 1 }, { schema_version: 1, lesson: "first\nsecond" }]) { + const { schema_version: _schemaVersion, ...entries } = payload; const f = fixture(); - f.output(JSON.stringify({ ...entries, schema_version: 1 })); + f.output(JSON.stringify(payload)); const result = await f.execute("memories", {}); expect(result.output).toMatchObject({ status: "found" }); expect(result.output.memories).toEqual(entries); @@ -822,23 +918,26 @@ describe("continuity adapter (plugin fixtures, not host qualification)", () => { test("distinguishes empty found memory, missing-key exit and CLI failure", async () => { const f = fixture(); + const input = { key: "lesson" }; + const base = { operation: "recall", target: "lesson" }; f.output('{"key":"lesson","value":"","found":true}'); - expect((await f.execute("recall", { key: "lesson" })).output).toMatchObject({ status: "found", value: "" }); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") - return '{"beads_dir":"/project/.beads","backend":"dolt","dolt_mode":"embedded","database":"beads"}'; - throw new PrimeProcessError(1, "", "bd recall", '{"key":"lesson","value":"","found":false}'); + expect((await f.execute("recall", input)).output).toStrictEqual({ + ...base, + status: "found", + reference: "lesson", + value: "", }); - expect((await f.execute("recall", { key: "lesson" })).output).toMatchObject({ status: "missing" }); - f.bd.mockImplementation(async (_cwd, args) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - throw new PrimeProcessError(1, "database unavailable", "bd recall"); + f.reply.mockRejectedValue(new PrimeProcessError(1, "", "bd recall", '{"key":"lesson","value":"","found":false}')); + expect((await f.execute("recall", input)).output).toStrictEqual({ + ...base, + status: "missing", + reference: "lesson", }); - expect((await f.execute("recall", { key: "lesson" })).output).toMatchObject({ + f.reply.mockRejectedValue(new PrimeProcessError(1, "database unavailable", "bd recall")); + expect((await f.execute("recall", input)).output).toStrictEqual({ + ...base, status: "failed", - detail: expect.stringContaining("database unavailable"), + detail: "bd recall exited with code 1: database unavailable", }); }); }); diff --git a/tests/docs.test.ts b/tests/docs.test.ts index 1b18792..f4d591f 100644 --- a/tests/docs.test.ts +++ b/tests/docs.test.ts @@ -1,511 +1,329 @@ import { describe, expect, test } from "bun:test"; -import * as fs from "node:fs/promises"; -import { dirname, resolve } from "node:path"; +import { readFile, stat } from "node:fs/promises"; +import { dirname, relative, resolve, sep } from "node:path"; import { MINIMUM_BD_VERSION } from "../src/guard"; +import { SUPPORTED_OPENCODE_RANGE } from "../src/host-admission"; -const readme = await fs.readFile("README.md", "utf8"); -const userGuide = await fs.readFile("docs/user-guide.md", "utf8"); -const docsIndex = await fs.readFile("docs/README.md", "utf8"); -const compatibilityEvidence = await fs.readFile("docs/compatibility-evidence.md", "utf8"); -const agentGuide = await fs.readFile("AGENTS.md", "utf8"); -const changelog = await fs.readFile("CHANGELOG.md", "utf8"); -const sdkContract = await fs.readFile("docs/opencode-sdk-contract.md", "utf8"); -const sdkHistory = await fs.readFile("docs/history/opencode-sdk-contract-ledger.md", "utf8"); -const artifactPolicy = await fs.readFile("docs/beads-artifact-policy.md", "utf8"); -const parity = await fs.readFile("docs/claude-code-parity.md", "utf8"); -const packageManifest = JSON.parse(await fs.readFile("package.json", "utf8")) as { +const indexDestinations = [ + "README.md", + "docs/user-guide.md", + "docs/diagnostics.md", + "docs/opencode-sdk-contract.md", + "docs/beads-artifact-policy.md", + "docs/native-release-probe.md", + "docs/compatibility-evidence.md", + "openspec/specs/workflow-access/spec.md", + "openspec/specs/work-continuity/spec.md", + "openspec/specs/upstream-review/spec.md", + "assets/oc-beads/SKILL.md", + "assets/oc-beads/resources/CODE_MODE.md", + "assets/oc-beads/resources/TROUBLESHOOTING.md", +]; + +const noticeFile = "assets/oc-beads/THIRD_PARTY_NOTICES.md"; +const artifactFiles = [ + "AGENTS.md", + "CHANGELOG.md", + "docs/README.md", + ...indexDestinations, + "assets/oc-beads/resources/WORKTREES.md", + "assets/oc-beads/resources/CLI_REFERENCE.md", + "assets/oc-beads/resources/RESUMABILITY.md", + noticeFile, +]; + +const manifest = (await Bun.file("package.json").json()) as { name: string; version: string; - contributors?: Array<{ name?: string; url?: string }>; + contributors: Array<{ name: string; url: string }>; beads: { minimum: string; validated: string }; peerDependencies: Record<string, string>; peerDependenciesMeta: Record<string, { optional?: boolean }>; devDependencies: Record<string, string>; }; -const packageIdentity = `${packageManifest.name}@${packageManifest.version}`; +const sdk = "@opencode/plugin"; +const peerRange = manifest.peerDependencies[sdk] ?? ""; +const developmentVersion = manifest.devDependencies[sdk] ?? ""; +const packageIdentity = `${manifest.name}@${manifest.version}`; +const repository = "https://github.com/snarkipus/opencode-beads"; -/** GitHub-style heading anchors plus explicit `id` attributes in a Markdown document. */ -function anchorsOf(markdown: string): Set<string> { - const anchors = new Set<string>(); - for (const [, heading] of markdown.matchAll(/^#{1,6}\s+(.+)$/gm)) { - anchors.add( - (heading ?? "") - .trim() - .toLowerCase() - .replace(/[^\p{L}\p{N}\s_-]/gu, "") - .replace(/\s/g, "-"), - ); - } - for (const [, id] of markdown.matchAll(/\bid="([^"]+)"/g)) anchors.add(id ?? ""); - return anchors; +// The pinned Bun runtime provides Markdown rendering, which the older pinned type package omits. +const { markdown: markdownRenderer } = Bun as typeof Bun & { + markdown: { + html(source: string): string; + render( + source: string, + callbacks: { + link(text: string, info: { href: string }): string; + heading(text: string): string; + code(text: string, info?: { language?: string }): string; + }, + ): string; + }; +}; + +function isExternal(href: string): boolean { + return /^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href); } -describe("documentation contracts", () => { - test("uses current package, command, and upstream identities", () => { - // Old `/bd-*` slash commands; a path segment such as `scripts/bd-contract.ts` is fine. - expect(readme).not.toMatch(/(?<![\w.])\/bd-[a-z]/); - expect(readme).not.toContain("github.com/steveyegge"); - expect(readme).toContain("https://github.com/gastownhall/beads"); - expect(readme).toContain(`"plugins": ["${packageIdentity}"]`); - expect(readme).not.toContain(`"plugin": [`); +function localDestination(file: string, href: string): string { + if (isExternal(href)) return href; + const [path, fragment] = href.split("#", 2); + const destination = path + ? relative(".", resolve(dirname(file), decodeURIComponent(path))) + .split(sep) + .join("/") + : file; + return fragment ? `${destination}#${decodeURIComponent(fragment)}` : destination; +} - for (const document of [readme, userGuide]) { - const documentedVersions = [ - ...document.matchAll( - new RegExp(`${packageManifest.name.replace("/", "\\/")}@(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)`, "g"), - ), - ].map((match) => match[1]); - expect(documentedVersions.length).toBeGreaterThan(0); - expect(new Set(documentedVersions)).toEqual(new Set([packageManifest.version])); - } - expect(userGuide).toContain(`"package": "${packageIdentity}"`); - }); +async function readMarkdown(file: string) { + const markdown = await readFile(file, "utf8"); + const links = new Set<string>(); + const headings: string[] = []; + const anchors = new Set<string>(); + const codeBlocks: Array<{ text: string; language?: string }> = []; - test("pairs the current release pin with diagnostics and preserves beta.1 migration history", () => { - expect(readme).toContain(`**${packageManifest.version}**`); - expect(readme).not.toContain("publication remains pending owner approval"); - const install = readme.split("## Installation")[1]?.split("### Upgrading to")[0] ?? ""; - expect(install).toContain(`"plugins": ["${packageIdentity}"]`); - expect(install).toContain("`/oc-beads:diagnostics` reports native registration and observed capabilities"); - expect(install).not.toContain("`/oc-beads:status` reports"); - expect(readme).toContain("29 `oc-beads:<stem>` workflows plus `oc-beads:diagnostics`"); - expect(userGuide).toContain("Beta.1 used `oc-beads:status`"); - expect(userGuide).toContain( - "Starting with beta.2, the package-owned `oc-beads:status` is removed without an alias", - ); - for (const document of [readme, userGuide]) { - expect(document).not.toContain( - "The diagnostics rename is not included in published beta.1 or the current npm `next` artifact", - ); - } + const visibleText = markdownRenderer.render(markdown, { + link(text, { href }) { + // Bun supplies bare email autolinks without the mailto: scheme. + const target = href === text && /^[^\s/@]+@[^\s/@]+\.[^\s/@]+$/.test(href) ? `mailto:${href}` : href; + links.add(localDestination(file, target)); + return text; + }, + heading(text) { + headings.push(text); + const slug = text + .toLowerCase() + .replace(/[^\p{L}\p{M}\p{N} _-]/gu, "") + .replaceAll(" ", "-"); + let anchor = slug; + for (let suffix = 1; anchors.has(anchor); suffix++) anchor = `${slug}-${suffix}`; + anchors.add(anchor); + return text; + }, + code(text, info) { + if (info) codeBlocks.push({ text, language: info.language }); + return text; + }, }); - test("documents diagnostics replacement, workflow mappings and compact/restore boundaries", async () => { - expect(userGuide).toContain("29 `oc-beads:<stem>` workflows plus `oc-beads:diagnostics`"); - expect(userGuide).toContain("package-owned `oc-beads:status` is removed without an alias"); - expect(userGuide).toContain("User-defined old status overrides are untouched and are not migrated"); - expect(userGuide).toContain("`bd status` (alias `bd stats`)"); - expect(userGuide).toContain("workflow prompts, not exact CLI aliases"); - expect(userGuide).toContain("`bd admin compact`"); - expect(userGuide).toContain("`bd compact` squashes Dolt history"); - expect(changelog.split("## [1.1.0-beta.1]")[0]).toContain("oc-beads:diagnostics"); - for (const file of ["assets/oc-beads/SKILL.md", "assets/oc-beads/resources/CLI_REFERENCE.md"]) { - const guidance = await fs.readFile(file, "utf8"); - expect(guidance).toContain("workflow prompts, not exact CLI aliases"); - expect(guidance).toContain("oc-beads:diagnostics"); - expect(guidance).toContain("oc-beads:stats"); - } - const troubleshooting = await fs.readFile("assets/oc-beads/resources/TROUBLESHOOTING.md", "utf8"); - expect(troubleshooting).toContain("bare invocation"); - expect(troubleshooting).toContain("examples still say `bd compact`"); - expect(troubleshooting).toContain("conflicts with restore's snapshot description"); - const restore = await fs.readFile("assets/oc-beads/resources/RESUMABILITY.md", "utf8"); - expect(restore).toContain("pre-compaction issue content"); - expect(restore).toContain("display-only by default"); - expect(restore).toMatch(/--apply[\s\S]*explicit authority[\s\S]*write/); - expect(restore).toContain("not database backup recovery"); - const worktrees = await fs.readFile("assets/oc-beads/resources/WORKTREES.md", "utf8"); - expect(worktrees).toContain("Dolt-remote synchronization"); - expect(worktrees).toContain("bd federation sync"); - }); + const html = markdownRenderer.html(markdown); + for (const [, id] of html.matchAll(/<[^>]+\sid=["']([^"']+)["']/g)) { + if (id) anchors.add(id); + } + return { links, headings, anchors, codeBlocks, visibleText, html }; +} - test("documents bounded invocation authority, operational sync and release scope", async () => { - expect(userGuide).toContain("**Command invocation:**"); - expect(userGuide).toContain("This action-contract correction starts with beta.3"); - expect(userGuide).toContain("/oc-beads:sync explain"); - for (const file of ["assets/oc-beads/SKILL.md", "assets/oc-beads/resources/CLI_REFERENCE.md"]) { - const text = await fs.readFile(file, "utf8"); - expect(text).toContain("invocation itself"); - expect(text).toContain("--no-adopt"); - expect(text).toContain("missing configured remote"); - } - const cli = await fs.readFile("assets/oc-beads/resources/CLI_REFERENCE.md", "utf8"); - expect(cli).toContain("bd sync --no-adopt"); - expect(cli).toContain("--actor='<executor-actor>'"); - expect(cli).toContain("not completion"); - expect(cli).toContain("## Audit and interchange"); - expect(cli).toContain("## Onboarding and discovery"); - const worktrees = await fs.readFile("assets/oc-beads/resources/WORKTREES.md", "utf8"); - expect(worktrees).toContain("CLI_REFERENCE.md#synchronization"); - const troubleshooting = await fs.readFile("assets/oc-beads/resources/TROUBLESHOOTING.md", "utf8"); - expect(troubleshooting).toContain("does not need another generic approval"); - expect(troubleshooting).toContain("## Deletion and identifier migration"); - }); +const documents = new Map( + await Promise.all(artifactFiles.map(async (file) => [file, await readMarkdown(file)] as const)), +); - test("documents stable 2.0 installation, historical pins and known Stop limits", () => { - expect(userGuide).toContain(`${packageManifest.name}@next`); - expect(userGuide).toContain(`${packageManifest.name}@latest`); - expect(userGuide).toContain("normal public entrypoint enables the eleven qualified operations"); - expect(readme).toContain("eleven permissioned operations in the native `beads` code-mode namespace"); - expect(readme).toContain("**Rejecting a permission is not Stop.**"); - for (const document of [readme, userGuide]) { - expect(document).toContain("Use explicit Stop/Cancel"); - } - for (const document of [readme, userGuide, sdkContract]) { - expect(document).not.toContain("typed activation remains withheld"); - expect(document).not.toContain("Ordinary typed continuity execution remains withheld"); - } - }); +function document(file: string) { + const markdown = documents.get(file); + if (!markdown) throw new Error(`Missing document under test: ${file}`); + return markdown; +} - test("presents the stable 2.x contract and credits the original project", () => { - expect(packageManifest.version).toMatch(/^2\.\d+\.\d+$/); - expect(readme).not.toContain("This plugin is intentionally small in scope"); - expect(readme).not.toContain("limits its scope to bug fixes"); - expect(readme).toContain("maintained OpenCode adapter"); - expect(readme).not.toContain("managed companion skill lifecycle"); - expect(readme).toContain("https://github.com/joshuadavidthomas/opencode-beads"); - expect(readme).toContain("Josh Thomas"); - expect(packageManifest.contributors).toContainEqual({ - name: "Josh Thomas", - url: "https://github.com/joshuadavidthomas", - }); - expect(changelog).toContain("## [0.8.0]"); - expect(changelog).toContain("## [0.9.0]"); - expect(changelog).toContain("## [0.9.1]"); - expect(changelog).toContain("## [0.9.2]"); - expect(changelog).toContain("## [0.9.3]"); - expect(changelog).toContain("## [0.9.4]"); - expect(changelog).toContain("## [0.10.0]"); - expect(changelog).toContain("## [1.0.0]"); - expect(changelog).toContain("## [1.0.1]"); - expect(changelog).toContain("[0.8.0]: https://github.com/snarkipus/opencode-beads/releases/tag/v0.8.0"); - }); +function expectLinks(file: string, destinations: readonly string[]) { + for (const destination of destinations) { + const { links } = document(file); + const linked = + links.has(destination) || + (!isExternal(destination) && + !destination.includes("#") && + [...links].some((link) => link.startsWith(`${destination}#`))); + expect(linked, `${file} must link to ${destination}`).toBeTrue(); + } +} - test("documents canonical per-project initialization and current ownership boundaries", () => { - for (const required of [ - "Install the [`bd` CLI]", - "git init", - "bd init", - "creates the canonical shared Beads skill", - "`.agents/skills/beads`", - "The plugin additionally owns its packaged `oc-beads` skill", - "does not write startup files", - "Update the pin explicitly when upgrading", - "**Do not run `bd setup opencode`.**", - ]) { - expect(readme).toContain(required); - expect(userGuide).toContain(required); - } - for (const required of [ - "| `bd setup claude` (Claude Code) | This plugin (OpenCode 2) |", - "`bd setup opencode --remove`", - ]) { - expect(userGuide).toContain(required); - } - for (const document of [readme, userGuide]) { - expect(document).not.toContain("Upgrading from 0.8.0"); - expect(document).not.toContain("bunx @snarkipus/opencode-beads@0.8.0 remove"); - expect(document).not.toContain("/beads:setup"); - } - expect(artifactPolicy).toContain("not by `bd setup opencode`"); - expect(artifactPolicy).toContain( - "The canonical `.agents/skills/beads` is created by `bd init`'s automatic Codex project integration", - ); - }); +function plainText(html: string): string { + return html + .replace(/<[^>]*>/g, "") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll("&", "&") + .replace(/\s+/g, " ") + .trim(); +} - test("keeps changelog headings unique and current links pointing at this repository", () => { - const headings = changelog.split("\n").filter((line) => /^## \[[^\]]+\]$/.test(line) && line !== "## [${version}]"); - expect(new Set(headings).size).toBe(headings.length); - expect(changelog).toContain( - `[unreleased]: https://github.com/snarkipus/opencode-beads/compare/v${packageManifest.version}...HEAD`, - ); - expect(changelog).toContain("[${version}]: https://github.com/snarkipus/opencode-beads/releases/tag/v${version}"); - }); +function compatibilityRow(file: string, component: string): string[] { + const rows = [...document(file).html.matchAll(/<tr>([\s\S]*?)<\/tr>/g)] + .map(([row]) => [...row.matchAll(/<td>([\s\S]*?)<\/td>/g)].map(([, cell = ""]) => plainText(cell))) + .filter(([name]) => name === component); + expect(rows, `${file} must document one compatibility row for ${component}`).toHaveLength(1); + return rows[0] ?? []; +} - test("resolves checked-in Markdown links and anchors", async () => { - for (const file of [ - "README.md", - "AGENTS.md", - "CHANGELOG.md", - "docs/README.md", - "docs/user-guide.md", - "docs/beads-artifact-policy.md", - "docs/opencode-sdk-contract.md", - "docs/history/opencode-sdk-contract-ledger.md", - "docs/claude-code-parity.md", - ]) { - const content = await fs.readFile(file, "utf8"); - const links = [...content.matchAll(/\[[^\]]*\]\(([^)]+)\)/g)] - .map((match) => match[1]) - .filter( - (target): target is string => - target !== undefined && !target.includes("://") && !target.startsWith("mailto:"), - ); - for (const target of links) { - const [pathPart = "", fragment] = target.split("#", 2); - const path = pathPart ? resolve(dirname(file), pathPart) : resolve(file); - expect(await fs.exists(path), `${file}: ${target}`).toBeTrue(); +describe("documentation integrity", () => { + test("required artifacts exist and checked-in links resolve", async () => { + const linkedDocuments = new Map(documents); + for (const [file, { links }] of documents) { + for (const destination of links) { + if (isExternal(destination)) continue; + const [path = "", fragment] = destination.split("#", 2); + await stat(path); if (fragment && path.endsWith(".md")) { - expect(anchorsOf(await fs.readFile(path, "utf8")).has(fragment), `${file}: ${target}`).toBeTrue(); + const linked = linkedDocuments.get(path) ?? (await readMarkdown(path)); + linkedDocuments.set(path, linked); + expect(linked.anchors.has(fragment), `${file} → ${destination}`).toBeTrue(); } } } }); - test("keeps the OpenCode reference current and the former ledger historical", () => { - expect(sdkContract).toContain("# OpenCode integration reference"); - expect(sdkContract).toMatch(/\*\*not a\s+behavioral contract\*\*/); - expect(packageManifest.peerDependencies["@opencode/plugin"]).toBe(">=2.3.0 <2.4 || 2.4.1 || 2.4.2"); - expect(sdkContract).toContain("`>=2.3.0 <2.4 || 2.4.1 || 2.4.2`"); - expect(packageManifest.peerDependenciesMeta["@opencode/plugin"]?.optional).toBeTrue(); - expect(packageManifest.devDependencies["@opencode/plugin"]).toBe("2.3.0"); - expect(sdkContract).toContain("`@opencode/plugin` `>=2.3.0 <2.4 || 2.4.1 || 2.4.2`"); - expect(sdkContract).toContain("`2.3.0` for development typing only"); - expect(sdkContract).toContain("`<name>/server`, then `<name>`"); - expect(sdkContract).toContain("`session.compaction.ended`"); - expect(sdkContract).toContain("`ctx.session.context({ sessionID })`"); - expect(sdkContract).toContain("[2.2.6 qualification](opencode-22-qualification-5rj2.md)"); - expect(sdkContract).toContain("(history/opencode-sdk-contract-ledger.md)"); - expect(sdkContract).toContain( - "(../openspec/specs/workflow-access/spec.md#requirement-explicit-native-availability-and-fallback)", - ); - for (const stale of ["release candidate", "unpublished", "not yet qualified", "remains withheld", "1.18."]) { - expect(sdkContract).not.toContain(stale); - } - expect(sdkContract).not.toContain("The 2.2.6 runtime candidate has not been qualified"); - - expect(sdkHistory).toContain("**Historical record — not current guidance.**"); - expect(sdkHistory).toContain( - "https://github.com/snarkipus/opencode-beads/blob/a4936526103cfc9a0112110a70a518f01d16f2f4/docs/opencode-sdk-contract.md", - ); - expect(sdkHistory).toContain("# OpenCode V2 Plugin Contract"); - expect(sdkHistory).toContain("Exact OpenCode 2.2.6 qualification is parent-accepted"); - expect(sdkHistory).toContain("072d9c29ef89fa2697109be072798e79cf4af622111266de40ef65e7950ac836"); - expect(sdkHistory).toContain("[current qualification](../opencode-22-qualification-5rj2.md)"); - expect(sdkHistory).toContain("**Historical 1.3.0 exited1 (59 checks passed, five fixture assertions failed)"); - expect(sdkHistory).toContain("**Task 1.1 is not qualified:**"); - expect(sdkHistory).toContain('Bun.spawn(["bd", "prime"]'); - }); - - test("separates accepted base compatibility from the representative Terra qualification", () => { - expect(userGuide).toContain( - "| OpenCode (historical beta.5) | `>=2.1.1 <2.2` | 2.1.1 (bounded accepted evidence) |", - ); - expect(userGuide).toContain( - "| OpenCode (2.0.0) | `>=2.2.6 <2.3` | 2.2.6 (accepted native and genuine-model qualification) |", - ); - expect(userGuide).toContain("| OpenCode (2.3.1) | `>=2.3.0 <2.4` |"); - expect(userGuide).toContain( - `| OpenCode (${packageManifest.version}) | \`>=2.3.0 <2.4\`, \`2.4.1\`, or \`2.4.2\` |`, - ); - expect(userGuide).toContain("| OpenCode (2.1.0 released) | `>=2.2.6 <2.3` |"); - expect(userGuide).toContain("| OpenCode (2.2.0) | `>=2.3.0 <2.4` | Exact 2.3.0 bounded native qualification |"); - expect(userGuide).toContain("Deterministic/package regression checks; inherits 2.2.0 native baseline"); - expect(userGuide).toContain("| OpenCode (stable 1.0.2 historical) | 2.0.26 | 2.0.26 |"); - expect(userGuide).toContain("| `bd` CLI | 1.3.1 through 1.x | 1.3.4 |"); - expect(readme).toContain("| OpenCode | `>=2.3.0 <2.4`, `2.4.1`, or `2.4.2` |"); - for (const document of [readme, userGuide, sdkContract, docsIndex]) { - expect(document).toContain("compatibility-evidence.md"); - expect(document).not.toContain("native qualification is pending"); - } - const pinnedReports = Array.from( - compatibilityEvidence.matchAll( - /https:\/\/github\.com\/snarkipus\/opencode-beads\/blob\/[a-f0-9]{40}\/docs\/([\w-]+\.md)\)/g, - ), - (match) => match[1], - ); - expect(pinnedReports).toEqual([ - "opencode-23-qualification-xwq.md", - "opencode-241-qualification.md", - "opencode-242-qualification.md", + test("readers can reach the index, guides, and normative requirements", () => { + expectLinks("AGENTS.md", ["docs/README.md"]); + expectLinks("docs/README.md", indexDestinations); + expectLinks("README.md", [ + "docs/README.md", + "docs/user-guide.md", + "docs/user-guide.md#upgrading", + "docs/diagnostics.md", + "docs/compatibility-evidence.md", + noticeFile, + ]); + expectLinks("docs/user-guide.md", [ + "docs/diagnostics.md", + "docs/compatibility-evidence.md", + "scripts/bd-contract.ts", + noticeFile, + ]); + expectLinks("docs/opencode-sdk-contract.md", [ + "docs/compatibility-evidence.md", + "openspec/specs/workflow-access/spec.md#requirement-explicit-native-availability-and-fallback", + ]); + expectLinks("assets/oc-beads/resources/WORKTREES.md", [ + "assets/oc-beads/resources/CLI_REFERENCE.md#synchronization", ]); - expect(userGuide).toContain("repeated idle reports with outstanding work"); - expect(userGuide).toContain("cancellation during real bd execution"); - expect(readme).toContain("### Upgrading to 2.2.0"); - expect(readme).toContain(`### Upgrading to ${packageManifest.version}`); - expect(userGuide).toContain("**Staying on OpenCode 2.2:** keep the released exact `2.1.0` pin"); - expect(readme).toContain("Upgrade OpenCode before changing the plugin pin"); - expect(readme).toContain("Existing exact 1.x and beta pins remain available"); - expect(readme).toContain("native conversation compaction on model A, switching to model B"); - expect(readme).toContain("upstream issue #57424"); - expect(readme).toContain("opencode-beads-o66"); - expect(readme).toContain("does not change or repair the Beads issue database or its stored data"); - for (const document of [readme, userGuide]) { - expect(document).not.toContain("@opencode-ai/"); - } - }); - - test("keeps the Beads compatibility range in one place", () => { - const { minimum, validated } = packageManifest.beads; - expect(minimum).toBe("1.3.1"); - expect(minimum).toBe(MINIMUM_BD_VERSION); - expect(userGuide).toContain(`| \`bd\` CLI | ${minimum} through 1.x | ${validated} |`); - expect(userGuide).toContain(`reviewed against Beads v${validated}`); - expect(readme).toContain(`| \`bd\` CLI | ${minimum} through 1.x |`); - expect(userGuide).toContain("beads-contract"); - expect(artifactPolicy).toContain("scripts/bd-contract.ts"); - expect(artifactPolicy).toContain("REASSESS:"); }); - test("records Claude Code parity with live evidence and explicit divergences", () => { - expect(userGuide).toContain("[Claude Code parity matrix](claude-code-parity.md)"); - expect(parity).toContain("validated on **OpenCode 2.0.26** with **bd 1.3.1**"); - for (const source of ["`startup`", "`resume`", "`clear`", "`compact`"]) { - expect(parity).toContain(`\`SessionStart\` (${source})`); - } - for (const row of [ - "Minimal `CLAUDE.md` pointer", - "`--stealth`", - "`--remove`", - "`--check`", - "Hook errors are visible", - ]) { - expect(parity).toContain(row); - } - for (const heading of ["## Beyond Claude Code", "## Deliberate divergences", "## Not exercised"]) { - expect(parity).toContain(heading); - } - for (const option of ["refreshAfterIdleMinutes", "stealth", "taskAgentSteps", "autoMigrate", "luna", "terra"]) { - expect(userGuide).toContain(`| \`${option}\` |`); + test("copyable installation and options examples match the package manifest", async () => { + for (const [file, plugin] of [ + ["README.md", packageIdentity], + ["docs/user-guide.md", expect.objectContaining({ package: packageIdentity, options: expect.any(Object) })], + ] as const) { + const examples: unknown[] = document(file) + .codeBlocks.filter(({ language }) => language?.toLowerCase() === "json") + .map(({ text }) => JSON.parse(text)); + const config = examples.find( + (example) => typeof example === "object" && example !== null && "plugins" in example, + ); + expect(config, `${file} must contain a JSON plugin config with the current pin`).toHaveProperty("plugins", [ + plugin, + ]); + expect(config).not.toHaveProperty("plugin"); + const text = await Bun.file(file).text(); + for (const occurrence of text.split(`${manifest.name}@`).slice(1)) { + const pin = occurrence.match(/^\d+\.\d+\.\d+(?:-[\w.-]+)?/)?.[0]; + if (pin) expect(pin, `${file} package pin`).toBe(manifest.version); + } } }); - test("documents native store ownership and retired option compatibility", () => { - expect(userGuide).toContain("## Native Beads store behavior"); - expect(userGuide).toContain("does not guarantee migration-free context"); - expect(userGuide).not.toContain("run `bd migrate schema`"); - expect(userGuide).toContain("| `autoMigrate` | ignored |"); - expect(userGuide).toContain("| `luna` | `false` |"); - expect(userGuide).toContain("| `terra` | `false` |"); - expect(userGuide).toContain("`openai/gpt-6.1-terra#medium`"); - expect(userGuide).toContain('"options": { "luna": true }'); - expect(userGuide).toContain("Terra is introduced in `2.1.0`; published `2.0.0` does not include it."); - expect(userGuide).not.toContain('"beads-task-agent-luna": {}'); - expect(artifactPolicy).toContain("Native Beads owns store opening, schema bounds and migrations"); + test("runtime compatibility declarations agree with the manifest", () => { + expect(manifest.beads.minimum).toBe(MINIMUM_BD_VERSION); + expect(peerRange).toBe(SUPPORTED_OPENCODE_RANGE); }); - test("documents upstream-aligned full-prime context boundaries", () => { - expect(userGuide).toContain("runs `bd prime --full`"); - expect(userGuide).not.toContain("runs `bd prime --memories-only`"); - expect(userGuide).toContain("standalone guidance for authorized scope"); - expect(sdkContract).toContain('Bun.spawn(["bd", ...args]'); - expect(artifactPolicy).toContain("Claude Code plugin manifests both run full `bd prime`"); - expect(artifactPolicy).toContain("`PreCompact` uses `--memories-only` only to check context availability"); - expect(artifactPolicy).toContain("eligible primary agents and `beads-task-agent`"); + test("current user-facing OpenCode ranges and Beads values match the manifest", () => { + for (const [file, component] of [ + ["README.md", "OpenCode"], + ["docs/user-guide.md", `OpenCode (${manifest.version})`], + ] as const) { + const [, range = ""] = compatibilityRow(file, component); + const alternatives = range.split(/\s*\|\|\s*|\s*,\s*(?:or\s+)?|\s+or\s+/i).map((piece) => piece.trim()); + expect(alternatives.sort(), `${file} current OpenCode range`).toEqual(peerRange.split(" || ").sort()); + + const [, supported = "", baseline = ""] = compatibilityRow(file, "bd CLI"); + const versions = /\b\d+\.\d+\.\d+\b/g; + expect(supported.match(versions), `${file} Beads supported minimum`).toEqual([manifest.beads.minimum]); + expect(baseline.match(versions), `${file} Beads validated baseline`).toEqual([manifest.beads.validated]); + } }); - test("records the retired vendoring decision and the historical baselines", async () => { - expect(userGuide).toContain("attributed MIT-licensed excerpts"); - expect(userGuide).toContain("The historical integration comparison remains Beads v1.3.1"); - expect(userGuide).toContain("c1c4b642ac1c08d8c828007a1c2f96e47e43ef7c"); - expect(artifactPolicy).toContain("attributed MIT-licensed excerpts"); - expect(await fs.readFile("assets/oc-beads/THIRD_PARTY_NOTICES.md", "utf8")).toContain( - "Copyright (c) 2025 Beads Contributors", - ); - expect(artifactPolicy).toContain("| `agents/task-agent.md` | Retired in 1.0.0 (`opencode-beads-w5y`) |"); - expect(artifactPolicy).toContain("### Rationale for retiring vendoring"); - expect(artifactPolicy).toContain("Codex ships skills and hooks but no agent."); - expect(artifactPolicy).toContain("`v1.0.5` plugin manifest incorrectly referenced `./hooks/hooks.json`"); - expect(artifactPolicy).toContain("`v1.1.0` corrected the operational path to `./.codex-plugin/hooks/hooks.json`"); - expect(artifactPolicy).toContain( - "Earlier baselines were Beads `v1.2.2`, commit `6c124203e771433a3550c348771a5b5e27fd3c21`", - ); + test("the SDK package declaration names the manifest peer range and development pin", () => { + expect(manifest.peerDependenciesMeta[sdk]?.optional).toBeTrue(); + expect(developmentVersion).toMatch(/^\d+\.\d+\.\d+$/); + // The declaration groups the SDK package and peer selector with its separate typing pin. + const declaration = [...document("docs/opencode-sdk-contract.md").html.matchAll(/<(li|p)>([\s\S]*?)<\/\1>/g)] + .map(([, , block = ""]) => [...block.matchAll(/<code>([^<]*)<\/code>/g)].map(([, code = ""]) => plainText(code))) + .find((tokens) => tokens.includes(sdk) && tokens.includes(peerRange)); + expect(declaration, "SDK package declaration must include the manifest peer range").toBeDefined(); + expect(declaration?.filter((token) => /^\d+\.\d+\.\d+$/.test(token))).toEqual([developmentVersion]); }); - test("documents the withdrawn-guidance recovery boundary", () => { - const recoveryGuide = "https://github.com/gastownhall/beads/blob/v1.2.2/docs/RECOVERY-1.2.1.md"; - for (const document of [userGuide, changelog, artifactPolicy]) { - expect(document).toContain("did not bundle"); - expect(document).toContain("implement database migrations"); - expect(document).toContain("consumer-installed"); - expect(document).toContain("`bd prime`"); - expect(document).toMatch(/even one v1\.2\.1 execution could migrate the database/i); - expect(document).toContain("v1.2.1"); - expect(document).toContain(recoveryGuide); + test("the changelog keys each current release link to its heading", () => { + const { headings, html } = document("CHANGELOG.md"); + const releases = headings + .map((heading) => heading.replace(/^\[([^\]]+)\]$/, "$1")) + .filter((heading) => /^(?:unreleased|\d+\.\d+\.\d+(?:-[\w.-]+)?)$/i.test(heading)); + expect(new Set(releases.map((heading) => heading.toLowerCase())).size).toBe(releases.length); + const headingsWithLinks = [...html.matchAll(/<h[1-6]>\s*<a href="([^"]+)"[^>]*>([\s\S]*?)<\/a>\s*<\/h[1-6]>/g)]; + for (const [label, destination] of [ + ["Unreleased", `${repository}/compare/v${manifest.version}...HEAD`], + [manifest.version, `${repository}/releases/tag/v${manifest.version}`], + ] as const) { + const links = headingsWithLinks + .filter(([, , heading = ""]) => plainText(heading).toLowerCase() === label.toLowerCase()) + .map(([, href]) => href); + expect(links, `CHANGELOG.md heading ${label}`).toEqual([destination]); } - expect(userGuide).toContain("if v1.2.1 was installed and may have run"); - expect(artifactPolicy).toContain("upstream v1.2.2 database recovery guidance"); - expect(artifactPolicy).toContain("local repository commit `e51b8fe`"); }); - test("documents scope-bounded task execution and runtime provenance", () => { - expect(userGuide).toContain("scope-bounded task execution"); - expect(userGuide).not.toContain("Autonomous issue completion"); - expect(userGuide).toContain("An exact assignment or explicit one-bead mode stops with that item"); - expect(userGuide).toContain("already-authorized batch or goal may continue within scope"); - expect(userGuide).toContain("Discovery does not expand that authority"); - expect(userGuide).toContain("primary OpenCode thread retains planning context, decisions, and control"); - expect(userGuide).toContain("unknown custom primary agents"); - expect(userGuide).toContain("Known regular subagents remain excluded"); - expect(readme).toContain("Exact assignments stop with their item"); - expect(artifactPolicy).toContain("metadata, provenance, and compatibility validation"); - expect(artifactPolicy).toContain("project-owned bounded OpenCode adaptation"); - expect(artifactPolicy).toContain("does not execute upstream's autonomous multi-task loop"); - expect(artifactPolicy).toContain("fail open for context injection"); + test("compatibility evidence links to the original immutable receipts", () => { + const revision = "592177b194ac8d9d3a1d3c2a0cd2b5cd44d9c67c"; + const rows = [...document("docs/compatibility-evidence.md").html.matchAll(/<tr>([\s\S]*?)<\/tr>/g)]; + for (const [host, report] of [ + ["2.3.0", "opencode-23-qualification-xwq"], + ["2.4.1", "opencode-241-qualification"], + ["2.4.2", "opencode-242-qualification"], + ]) { + const matching = rows + .map(([row]) => row) + .filter((row) => plainText(row.match(/<td>(.*?)<\/td>/)?.[1] ?? "") === host); + expect(matching, `qualification row for ${host}`).toHaveLength(1); + expect(matching[0]).toContain(`href="${repository}/blob/${revision}/docs/${report}.md"`); + } }); - test("retains compact OpenCode-specific runtime policy", () => { - expect(userGuide).toContain("validate before closure"); - expect(artifactPolicy).toContain("prohibits automatic commit, push, or Dolt synchronization"); - expect(artifactPolicy).not.toContain("companion lifecycle CLI"); - expect(artifactPolicy).not.toContain("project-owned CLI"); + test("keeps critical upstream and recovery destinations discoverable", () => { + expectLinks("README.md", [ + "https://github.com/gastownhall/beads/blob/main/docs/getting-started/installation.md", + "https://github.com/anomalyco/opencode/issues/57424", + ]); + const recovery = "https://github.com/gastownhall/beads/blob/v1.2.2/docs/RECOVERY-1.2.1.md"; + expectLinks("docs/user-guide.md", [recovery]); }); - test("states documentation authority once and points agents to it", () => { - expect(docsIndex).toContain("For intended product behavior, the canonical specs are authoritative."); - expect(docsIndex).toContain("never rewrite historical evidence or invent an upstream API"); - for (const spec of ["workflow-access", "work-continuity", "upstream-review"]) { - expect(docsIndex).toContain(`(../openspec/specs/${spec}/spec.md)`); + test("retains literal invocation and report identifiers in the relevant references", () => { + const diagnostics = document("docs/diagnostics.md").visibleText; + for (const token of ["/oc-beads:diagnostics details remote", "BEGIN_DIAGNOSTIC_REPORT", "END_DIAGNOSTIC_REPORT"]) { + expect(diagnostics).toContain(token); } - expect(readme).toContain("[Documentation index](docs/README.md)"); - expect(agentGuide).toContain("## Where truth lives"); - expect(agentGuide).toContain("[`docs/README.md`](docs/README.md)"); - expect(agentGuide).toContain("report the precise gap and stop"); + + const { codeBlocks } = document("assets/oc-beads/resources/CLI_REFERENCE.md"); + const syncExample = codeBlocks + .flatMap(({ text }) => text.replace(/\\\r?\n/g, " ").split(/\r?\n/)) + .some( + (line) => + /^bd sync\s/.test(line.trim()) && + /(?:^|\s)--no-adopt(?:\s|$)/.test(line) && + /(?:^|\s)--actor(?:=|\s+)['"]<executor-actor>['"](?:\s|$)/.test(line) && + /(?:^|\s)--sandbox(?:\s|$)/.test(line), + ); + expect(syncExample, "CLI_REFERENCE.md must show a bounded sync invocation with an executor actor").toBeTrue(); + expect(document("assets/oc-beads/resources/WORKTREES.md").visibleText).toContain("bd federation sync"); + const restore = document("assets/oc-beads/resources/RESUMABILITY.md").visibleText; + expect(restore).toContain("bd restore"); + expect(restore).toContain("--apply"); }); -}); -test("diagnostics reference and static help remain discoverable without adding packed resources", async () => { - const reference = await Bun.file("docs/diagnostics.md").text(); - const index = await Bun.file("docs/README.md").text(); - const { DIAGNOSTICS_HELP } = await import("../src/diagnostics"); - expect(index).toContain("[Diagnostics reference](diagnostics.md)"); - expect(readme).toContain("docs/diagnostics.md"); - expect(userGuide).toContain("[diagnostics reference](diagnostics.md)"); - for (const label of [ - "Host", - "Commands", - "Skill", - "Typed tools", - "Context", - "AGENTS Configured", - "Write outcomes", - "bd CLI", - "Workspace", - "Recorded bd version", - "Git hooks", - "Sync target", - "Remote history", - ]) { - expect(reference).toContain(`| ${label} |`); - expect(DIAGNOSTICS_HELP).toContain(`| ${label} |`); - } - for (const term of [ - "details remote", - "--readonly dolt remote list --json --sandbox", - "configured database", - "sync remote", - "Not applicable", - "Not checked", - ]) { - expect(reference).toContain(term); - expect(DIAGNOSTICS_HELP).toContain(term); - } - for (const term of [ - "512", - "64 KiB", - "256 bytes", - "unrecognized", - "shims", - "last observed request", - "ordinary prompt", - "remain unmeasured", - ]) - expect(reference).toContain(term); - expect(DIAGNOSTICS_HELP).toContain("https://github.com/snarkipus/opencode-beads/blob/main/docs/diagnostics.md"); - for (const term of ["DATE", "VERSION", "PATH", "cwd_repo_root"]) { - expect(reference).toContain(term); - expect(DIAGNOSTICS_HELP).toContain(term); - } - expect(reference).toContain("`BEGIN_DIAGNOSTIC_REPORT` / `END_DIAGNOSTIC_REPORT`"); - expect(reference).toContain("byte-exact visible relay is not guaranteed"); + test("retains original project credit and the Beads copyright notice", () => { + const contributor = { name: "Josh Thomas", url: "https://github.com/joshuadavidthomas" }; + expect(manifest.contributors).toContainEqual(expect.objectContaining(contributor)); + expectLinks("README.md", [`${contributor.url}/opencode-beads`, "LICENSE"]); + expect(document("README.md").visibleText).toContain(contributor.name); + expect(document(noticeFile).visibleText).toContain("Copyright (c) 2025 Beads Contributors"); + }); }); diff --git a/tests/fixtures/ci-failure-notification.py b/tests/fixtures/ci-failure-notification.py new file mode 100644 index 0000000..4ae8354 --- /dev/null +++ b/tests/fixtures/ci-failure-notification.py @@ -0,0 +1,69 @@ +"""Execute the workflow's inline sender with one fake event and offline transport.""" + +import io +import json +import os +from pathlib import Path +import sys +import tempfile +import urllib.error +import urllib.request + + +def block_sockets(event, _args): + if event == "socket.__new__": + raise SystemExit("The notifier fixture forbids real sockets") + + +def run_sender(source, scenario, directory): + event_path = Path(directory) / "event.json" + event = { + "repository": {"full_name": scenario.get("repository", "snarkipus/opencode-beads")}, + "workflow_run": { + "name": scenario.get("workflowName", "ci"), + "conclusion": scenario.get("conclusion", "failure"), + "id": 42, + "head_branch": "@everyone " + "x" * 300, + }, + } + event_path.write_text(json.dumps(event), encoding="utf-8") + destination = scenario["destination"] + os.environ["GITHUB_EVENT_PATH"] = str(event_path) + os.environ["DISCORD_CI_WEBHOOK_URL"] = destination + + attempts = [] + + class FakeOpener: + def __init__(self, *handlers): + self.handlers = handlers + + def open(self, request, timeout): + attempts.append((self.handlers, request, timeout)) + if scenario.get("failure") == "http": + raise urllib.error.HTTPError(request.full_url, 403, "Forbidden", {}, None) + if scenario.get("failure") == "network": + raise OSError(request.full_url) + return io.BytesIO(b'{"id":"456"}') + + urllib.request.build_opener = FakeOpener + try: + exec(compile(source, "notify-ci-failure.yml (inline Python)", "exec"), {"__name__": "__main__"}) + finally: + # Check outside the sender's exception handler so assertion failures keep their traceback. + assert len(attempts) == scenario["attempts"], f"Unexpected delivery attempts: {len(attempts)}" + for handlers, request, timeout in attempts: + assert len(handlers) == 1 + assert handlers[0].redirect_request(None, None, None, None, None, None) is None + assert timeout == 10 + assert request.full_url == destination + "?wait=true" + assert request.get_header("User-agent") == "OpenCode-Beads-CI-Notifier/1.0" + payload = json.loads(request.data) + assert payload["allowed_mentions"] == {"parse": []} + assert "https://github.com/snarkipus/opencode-beads/actions/runs/42" in payload["content"] + assert len(payload["content"]) < 2000 + + +if __name__ == "__main__": + sys.addaudithook(block_sockets) + with tempfile.TemporaryDirectory(prefix="ci-notify-test-") as directory: + run_sender(sys.stdin.buffer.read(), json.loads(sys.argv[1]), directory) diff --git a/tests/guard.test.ts b/tests/guard.test.ts index df86264..549e1d1 100644 --- a/tests/guard.test.ts +++ b/tests/guard.test.ts @@ -32,34 +32,29 @@ describe("parseVersion", () => { describe("checkBeadsStore", () => { test("does not read CLI witnesses or infer schema admission", async () => { - for (const marker of [undefined, "1.3.2", "1.3.4", "1.4.0", new Error("EACCES")]) { - const fake = runtime({ version: "1.3.4", context: CONTEXT, marker }); - const result = await checkBeadsStore("/project", fake); - expect(result).toEqual({ kind: "ready", version: "1.3.4", workspace: { path: "/project/.beads" } }); - expect(fake.readText).not.toHaveBeenCalled(); - expect(guardNotice(result)).toBeUndefined(); - } + const fake = runtime({ version: "1.3.4", context: CONTEXT, marker: new Error("EACCES") }); + expect(await checkBeadsStore("/project", fake)).toEqual({ + kind: "ready", + version: "1.3.4", + workspace: { path: "/project/.beads" }, + }); + expect(fake.readText).not.toHaveBeenCalled(); }); test("is ready when CLI and workspace checks succeed", async () => { - const fake = runtime({ version: "bd version 1.3.1 (abc)", context: CONTEXT, marker: "1.3.1\n" }); + const fake = runtime({ version: "bd version 1.3.1 (abc)", context: CONTEXT }); expect(await checkBeadsStore("/project", fake)).toEqual({ kind: "ready", version: "1.3.1", workspace: { path: "/project/.beads" }, }); - expect(fake.bd).toHaveBeenCalledWith("/project", ["version"]); - expect(fake.bd).toHaveBeenCalledWith("/project", ["context", "--json"]); + expect(fake.bd.mock.calls).toEqual([ + ["/project", ["version"]], + ["/project", ["context", "--json"]], + ]); expect(fake.readText).not.toHaveBeenCalled(); }); - test("never invokes a command that opens the store", async () => { - const fake = runtime({ version: "bd version 1.3.1", context: CONTEXT, marker: "1.2.2" }); - await checkBeadsStore("/project", fake); - const commands = fake.bd.mock.calls.map((call) => (call[1] as string[])[0]); - expect(commands).toEqual(["version", "context"]); - }); - test("rejects 1.3.0 before locating or opening the store", async () => { const fake = runtime({ version: "bd version 1.3.0 (f45b249ce)", context: CONTEXT, marker: "1.3.0" }); expect(await checkBeadsStore("/project", fake)).toEqual({ diff --git a/tests/guidance-examples.test.ts b/tests/guidance-examples.test.ts new file mode 100644 index 0000000..30d8327 --- /dev/null +++ b/tests/guidance-examples.test.ts @@ -0,0 +1,31 @@ +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { describe, expect, test } from "bun:test"; +import inventory from "../docs/claude-code-integration-inventory.json"; + +const repositoryRoot = resolve(import.meta.dir, ".."); +const skillPath = resolve(repositoryRoot, "assets/oc-beads/SKILL.md"); + +function selectedSupportingFiles() { + return inventory.marketplace_main.files.flatMap(({ category, selected_mapping }) => + (category === "resource" || category === "adr") && selected_mapping?.task_ids.includes("2.1") + ? [selected_mapping] + : [], + ); +} + +describe("packaged guidance shell examples", () => { + test("keeps copyable placeholders quoted and executor actors neutral", () => { + const files = [skillPath, ...selectedSupportingFiles().map(({ target }) => resolve(repositoryRoot, target))]; + const guidance = files.map((file) => readFileSync(file, "utf8")).join("\n"); + const actors = [...guidance.matchAll(/--actor=([^\s`]+)/g)].map((match) => match[1]); + + expect(actors.length).toBeGreaterThan(0); + expect(actors.filter((actor) => actor !== "'<executor-actor>'" && actor !== "'<actual-human-actor>'")).toEqual([]); + expect(guidance).not.toMatch(/codex:/); + // Strip quoted arguments: remaining angle brackets in shell blocks would be redirects. + const shellBlocks = [...guidance.matchAll(/```(?:sh|bash)\n([\s\S]*?)```/g)].map((match) => match[1] ?? ""); + const unquotedShell = shellBlocks.join("\n").replace(/'[^']*'|"[^"]*"/g, ""); + expect(unquotedShell).not.toMatch(/<[^>\n]+>/); + }); +}); diff --git a/tests/guidance.test.ts b/tests/guidance.test.ts index 5172c99..a91832c 100644 --- a/tests/guidance.test.ts +++ b/tests/guidance.test.ts @@ -10,7 +10,8 @@ import { const unsupportedPattern = /beads mcp|mcp server|via mcp|\bmcp\b|claude code|\/plugin update beads/i; -describe("project-owned task-agent contract", () => { +// These checks cover the guidance delivered to agents. +describe("project-owned agent guidance", () => { test("describes read-only analysis and execution within an authorized scope", () => { expect(BEADS_TASK_AGENT_DESCRIPTION).toContain("authorized task, batch or goal"); expect(BEADS_TASK_AGENT_DESCRIPTION).toContain("read-only"); @@ -22,32 +23,21 @@ describe("project-owned task-agent contract", () => { test("keeps exact assignments bounded while allowing authorized continuation", () => { const prompt = BEADS_TASK_AGENT_PROMPT; expect(prompt).not.toMatch(unsupportedPattern); - expect(prompt).toContain("Full `bd prime` workflow context is injected"); - expect(prompt).toContain( - "For status or graph analysis, never claim, update, close, or modify a bead. Return the analysis and stop.", - ); - expect(prompt).toContain("An exact assignment or explicit one-bead mode ends with that bead"); - expect(prompt).toContain("already-authorized batch or goal"); + expect(prompt).toContain("`bd prime`"); + expect(prompt).toContain("never claim, update, close, or modify a bead"); expect(prompt).toContain("Readiness is not dispatch permission"); const showIndex = prompt.indexOf("`bd show <id> --json --sandbox`"); const claimIndex = prompt.indexOf("`bd update <id> --claim --json --actor='<executor-actor>' --sandbox`"); expect(showIndex).toBeGreaterThanOrEqual(0); expect(claimIndex).toBeGreaterThan(showIndex); - expect(prompt).toContain( - "If an assigned bead is closed, blocked, unsuitable, missing, or otherwise not actionable, report and return without mutation or substitution.", - ); + expect(prompt).toContain("without mutation or substitution"); expect(prompt).toContain("claim fails or readback does not confirm your assignment, stop"); expect(prompt).toContain("Discovery does not add execution authority"); expect(prompt).toContain("discovered-from:<current-id>"); expect(prompt).toContain("current-state handoff"); - expect(prompt).toContain("--notes"); - expect(prompt).toContain("authorized corrections or clarifications"); - expect(prompt).toContain("oc-beads"); expect(prompt).toContain("unresolved acceptance or failed validation remains incomplete"); expect(prompt).toContain("If the parent owns acceptance or closure, return evidence and leave the bead open"); expect(prompt).toContain("permission denial, cancellation, deliberate stop"); - expect(prompt).toContain("concise results, not raw JSON"); - expect(prompt).not.toContain("Agent Delegation"); expect(prompt).not.toContain("otherwise choose one highest-priority ready bead"); }); @@ -60,16 +50,12 @@ describe("project-owned task-agent contract", () => { }); test("carries executor attribution and separates planning/review acceptance", () => { - for (const text of [ - BEADS_TASK_AGENT_PROMPT, - beadsGuidance("primary"), - BEADS_TASK_AGENT_PROMPT + beadsGuidance("task-agent"), - ]) { - expect(text).toContain("command-scoped"); + for (const text of [BEADS_TASK_AGENT_PROMPT, beadsGuidance("primary")]) { + expect(text).toContain("command-scoped `BEADS_ACTOR` or `--actor`"); expect(text).toContain("heartbeat"); - expect(text).toContain("created_by"); - expect(text).toContain("owner"); - expect(text).toContain("assignee"); + expect(text).toContain("`created_by`"); + expect(text).toContain("`owner`"); + expect(text).toContain("`assignee`"); expect(text).toContain("human Git identity"); expect(text).toContain("deliberate handoff"); } @@ -77,40 +63,41 @@ describe("project-owned task-agent contract", () => { expect(planning).toContain("same review item"); expect(planning).toContain("owner acceptance"); expect(beadsGuidance("primary")).not.toContain("same review item"); - expect(beadsGuidance("task-agent")).not.toContain("## Executor and work ownership"); }); test("shares one guidance layer and adds delegation only for primary agents", () => { const primary = beadsGuidance("primary"); const taskAgent = beadsGuidance("task-agent"); for (const guidance of [primary, taskAgent]) { - expect(guidance).toMatch(/^<beads-guidance>\n[\s\S]*\n<\/beads-guidance>$/); + expect(guidance).toStartWith("<beads-guidance>\n"); + expect(guidance).toEndWith("\n</beads-guidance>"); expect(guidance).toContain("--append-notes"); expect(guidance).toContain("--notes"); expect(guidance).toContain("current-state handoff"); expect(guidance).toContain("authorized corrections or clarifications"); - expect(guidance).toContain("oc-beads"); + expect(guidance).toContain("`oc-beads`"); expect(guidance).toContain("Native shell is direct-only"); expect(guidance).toContain("Do not commit, push, or run Dolt synchronization automatically"); expect(guidance).toContain("explicit command invocation is the invoking user's bounded request"); expect(guidance).toContain("incidental automation"); } - expect(primary).toContain("through the `subagent` tool"); - expect(primary).toContain("launch handle"); + expect(primary).toContain("`beads-task-agent` subagent through the `subagent` tool"); expect(primary).toContain("later and repeated idle reports"); - expect(primary).toContain("accepted task completion"); + expect(primary).toContain("launch handle as an acknowledgement, not accepted task completion"); expect(primary).toContain("Host-owned transport"); - expect(primary).not.toContain("normal blocking child return"); expect(BEADS_TASK_AGENT_PROMPT).toContain("additional background or nested automation"); expect(primary).toContain("NO_TEXT"); expect(primary).toContain("actual executor actor"); - expect(primary).not.toMatch(/Delegate multi-command|only single atomic operations/); - expect(taskAgent).not.toContain("## Delegation"); + expect(taskAgent).not.toContain("`subagent`"); + for (const section of ["## Authorized scope", "## Executor and work ownership", "## Delegation"]) { + expect(primary).toContain(section); + expect(taskAgent).not.toContain(section); + } }); test("names OpenCode V2's `shell` tool, not V1's `bash`", () => { + expect(BEADS_TASK_AGENT_PROMPT).toContain("`shell`"); for (const text of [BEADS_TASK_AGENT_PROMPT, beadsGuidance("primary"), beadsGuidance("task-agent")]) { - expect(text).toContain("shell"); expect(text).not.toContain("`bash`"); } }); @@ -122,9 +109,9 @@ describe("project-owned task-agent contract", () => { shell: true, direct: false, }); - expect(composed).toContain("Beads namespace is registered and execute is visible"); + expect(composed).toContain('search({namespace: "beads"})'); expect(composed).toContain("Each operation still checks its own permissions"); - expect(composed).toContain("rejected operation is not success"); + expect(composed).toContain("must not be retried through another surface"); expect(composed).toContain("Stop/Cancel"); expect(composed).toContain("Do not call tools.shell inside execute"); @@ -134,28 +121,20 @@ describe("project-owned task-agent contract", () => { shell: false, direct: true, }); - expect(direct).toContain("Native Beads leaf tools are directly visible"); - expect(direct).toContain("Use only the listed direct leaves"); - expect(direct).toContain("rejected operation is not success"); - expect(direct).toContain("Stop/Cancel"); + expect(direct).toContain("must not be retried through shell or another surface"); + expect(direct).toContain("only if separately listed and permissioned"); const shell = capabilityGuidance({ typed: "unavailable", execute: false, shell: true, direct: false }); - expect(shell).toContain("independently available direct shell tool"); + expect(shell).toContain("only when authorized and no hold applies"); expect(shell).toContain("Shell cannot run inside execute"); const denied = capabilityGuidance({ typed: "unavailable", execute: false, shell: false, direct: false }); - expect(denied).toContain("Neither native Beads leaves nor direct shell access"); expect(denied).toContain("do not route around it"); }); - test("gives the Luna profile the same prompt and description", () => { - const agents = beadsAgents({ luna: true }); - expect(agents["beads-task-agent-luna"]).toEqual({ - description: BEADS_TASK_AGENT_DESCRIPTION, - system: BEADS_TASK_AGENT_PROMPT, - model: { providerID: "openai", id: "gpt-6-luna", variant: "max" }, - steps: 100, - }); - expect(Object.keys(beadsAgents())).toEqual(["beads-task-agent"]); + test("gives Luna the worker description and default step budget", () => { + const luna = beadsAgents({ luna: true })["beads-task-agent-luna"]; + expect(luna?.description).toBe(BEADS_TASK_AGENT_DESCRIPTION); + expect(luna?.steps).toBe(100); }); }); diff --git a/tests/host-child-handoff.test.ts b/tests/host-child-handoff.test.ts new file mode 100644 index 0000000..3ca8ea0 --- /dev/null +++ b/tests/host-child-handoff.test.ts @@ -0,0 +1,305 @@ +import type { HostContext } from "../src/host"; +import { expect, mock, test } from "bun:test"; +import { setImmediate } from "node:timers/promises"; +import { setupBeads } from "../src/host"; +import { Error as ToolError } from "@opencode/plugin/promise/tool"; +import { executorActor } from "../src/continuity"; +import { BEADS_COMPACTION_GUIDANCE } from "../src/guidance"; +import { + type ContextEvent, + type ToolAfterEvent, + createHost, + toolFixture, + nonCodeMode, + invocation, + sessionInfo, +} from "./host-fixture"; + +test.each(["running", "failed", "cancelled", "NO_TEXT", "partial"] as const)( + "preserves %s child outcome and adds only a next-request recovery cue", + async (outcome) => { + const f = createHost(); + const t = toolFixture(f); + const prompt = mock(async () => ({})); + const synthetic = mock(async () => ({})); + Object.assign(f.ctx.session, { + prompt, + synthetic, + get: async () => sessionInfo("/project", "human-default"), + }); + const prime = mock(async () => "CURRENT"); + const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); + await f.request("parent", "build"); + await f.request("child", "beads-task-agent"); + const parent = invocation("parent", "build"); + const child = invocation("child", "beads-task-agent"); + const handoff = `Task fixture-1 only; actor ${executorActor(child)}; session child; tried A; failed validation; because B; reference task:fixture-1; candidate fixture-rev; blocker acceptance; next authorized action C; partial.`; + const input = { agent: "beads-task-agent", description: "bounded fixture", prompt: handoff }; + const base = { + tool: "subagent", + codemode: false, + sessionID: parent.sessionID, + agent: parent.agent, + messageID: parent.messageID, + id: parent.id, + input, + }; + // Exercise the 2.3 launch handle and error boundary alongside earlier result + // forms; execute.after has no status="cancelled". + const event: ToolAfterEvent = + outcome === "failed" || outcome === "cancelled" + ? { + ...base, + status: "error", + error: new ToolError({ + message: + outcome === "failed" + ? "Subagent failed (sessionID: child): fixture failure" + : "Subagent cancelled (sessionID: child)", + }), + } + : { + ...base, + status: "completed", + result: { + output: { + sessionID: "child", + status: outcome === "running" ? "running" : "completed", + output: + outcome === "running" + ? "The subagent is working in the background (sessionID: child). You will receive a <subagent> message when it goes idle, and again after each later round of work." + : outcome === "NO_TEXT" + ? "Subagent completed without a text response." + : handoff, + }, + content: + outcome === "running" + ? '<subagent sessionID="child" state="running">Launched</subagent>' + : `<subagent sessionID="child" state="completed">\n${outcome === "NO_TEXT" ? "Subagent completed without a text response." : handoff}\n</subagent>`, + metadata: { sessionID: "child", status: outcome === "running" ? "running" : "completed" }, + }, + }; + const before = JSON.stringify(event); + await t.after(event); + expect(JSON.stringify(event)).toBe(before); + expect(event.input).toBe(input); + expect(prime).toHaveBeenCalledTimes(2); + expect(prompt).not.toHaveBeenCalled(); + expect(synthetic).not.toHaveBeenCalled(); + const recovered = await f.request("parent", "build"); + expect(prime).toHaveBeenCalledTimes(3); + expect(recovered[1]).toContain("may only acknowledge launch or follow-up"); + expect(recovered[1]).toContain("actual reports or results"); + expect(recovered[1]).not.toContain("A child returned"); + // Child context is isolated; a parent-side result does not change its actor/cache. + expect(await f.request("child", "beads-task-agent")).toHaveLength(1); + expect(prime).toHaveBeenCalledTimes(3); + await cleanup(); + }, +); + +test("a late child return and execution success after deliberate stop do not restart or imply a final checkpoint", async () => { + const f = createHost(); + const t = toolFixture(f); + const prompt = mock(async () => ({})); + const synthetic = mock(async () => ({})); + Object.assign(f.ctx.session, { prompt, synthetic }); + const prime = mock(async () => "CURRENT"); + const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); + await f.request("parent", "build"); + await f.events.emit({ type: "session.execution.interrupted", data: { sessionID: "parent", reason: "user" } }); + const context = invocation("parent", "build"); + const event: ToolAfterEvent = { + tool: "subagent", + ...nonCodeMode, + sessionID: context.sessionID, + agent: context.agent, + messageID: context.messageID, + id: context.id, + input: { agent: "beads-task-agent", prompt: "exact fixture-1" }, + status: "completed", + result: { + output: { sessionID: "child", status: "completed", output: "late partial evidence" }, + metadata: { sessionID: "child", status: "completed" }, + }, + }; + const before = JSON.stringify(event); + await t.after(event); + await f.events.emit({ type: "session.execution.succeeded", data: { sessionID: "parent" } }); + expect(JSON.stringify(event)).toBe(before); + expect(prime).toHaveBeenCalledTimes(1); + expect(prompt).not.toHaveBeenCalled(); + expect(synthetic).not.toHaveBeenCalled(); + const summary: ContextEvent = { sessionID: "parent", agent: "build", system: [] }; + await f.hooks.get("compaction")!(summary); + expect(summary.system[1]?.text).toContain("no final checkpoint"); + expect(prime).toHaveBeenCalledTimes(1); + // Only a caller-initiated request asks for fresh recovery; the test does not run a model. + expect((await f.request("parent", "build"))[1]).toContain("incomplete work"); + await cleanup(); + const calls = prime.mock.calls.length; + await t.after(event); + expect(await f.request("parent", "build")).toEqual([]); + expect(prime).toHaveBeenCalledTimes(calls); +}); + +test("preserves parent/child checkpoint actors and partial handoff on fresh-session/fork recovery", async () => { + const f = createHost(); + const t = toolFixture(f); + const permission = mock(async (_input: unknown) => {}); + Object.assign(f.ctx, { + permission: { assert: permission }, + location: { directory: "/project", project: { directory: "/project" } }, + }); + Object.assign(f.ctx.session, { + get: async () => sessionInfo("/project", "human-default"), + }); + const child = invocation("child-full-session", "beads-task-agent"); + const parent = invocation("parent-full-session", "build"); + const notes = [`Earlier attempt failed; rationale retained.`]; + const handoff = `Scope fixture-1; executor ${executorActor(child)}; full session ${child.sessionID}; tried alternative; result partial; validation unit pass/live unexecuted; because source only; reference task:fixture-1; candidate fixture-rev; blocker live gate; next authorized action parent review.`; + const bd = mock(async (_cwd: string, args: readonly string[]) => { + if (args[0] === "version") return "1.3.1"; + if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; + if (args[0] === "update") notes.push(String(args[args.indexOf("--append-notes") + 1])); + return JSON.stringify([ + { + id: "fixture-1", + created_by: "unknown", + owner: "account-owner", + assignee: executorActor(child), + notes: notes.join("\n"), + }, + ]); + }); + const prime = mock(async () => "CURRENT"); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime }, + continuityQualified: true, + continuity: { bd, realpath: async (value) => value }, + }); + await f.request(String(child.sessionID), String(child.agent)); + await f.request(String(parent.sessionID), String(parent.agent)); + const checkpoint = t.tools.find((tool) => tool.name === "note")!; + await checkpoint.execute({ id: "fixture-1", text: handoff }, child); + await checkpoint.execute({ id: "fixture-1", text: "Parent review only; no ownership transfer or closure." }, parent); + const writes = bd.mock.calls.filter(([, args]) => args[0] === "update"); + expect(writes.map(([, args]) => args[args.indexOf("--actor") + 1])).toEqual([ + executorActor(child), + executorActor(parent), + ]); + expect(writes[0]?.[1]).toContain(handoff); + expect(permission.mock.calls.map(([input]) => (input as { agent: string }).agent)).toEqual([ + child.agent, + parent.agent, + ]); + const compact = async (sessionID: string, agent: string) => { + const event: ContextEvent = { sessionID, agent, system: [] }; + await f.hooks.get("compaction")!(event); + return event.system; + }; + expect((await compact(String(parent.sessionID), String(parent.agent)))[1]?.text).toContain("task:fixture-1"); + await f.events.emit({ + type: "session.forked", + data: { + sessionID: "fork", + parentID: parent.sessionID, + boundary: { type: "through", messageID: parent.messageID }, + }, + }); + await f.request("fork", "build"); + expect(await compact("fork", "build")).toHaveLength(1); + expect((await compact(String(parent.sessionID), String(parent.agent)))[1]?.text).toContain("task:fixture-1"); + await cleanup(); + const fresh = createHost(); + const recoveredTools = toolFixture(fresh); + Object.assign(fresh.ctx, { location: f.ctx.location, permission: f.ctx.permission }); + Object.assign(fresh.ctx.session, { get: f.ctx.session.get }); + const freshCleanup = await setupBeads(fresh.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime }, + continuityQualified: true, + continuity: { bd, realpath: async (value) => value }, + }); + const recovery = await fresh.request("fresh", "build"); + expect(recovery[0]).toContain("retrieve the assigned task and relevant reusable knowledge"); + const result = await recoveredTools.tools + .find((tool) => tool.name === "get")! + .execute({ ids: ["fixture-1"] }, invocation("fresh", "build")); + expect(JSON.stringify(result.output)).toContain(handoff); + expect(JSON.stringify(result.output)).toContain("Earlier attempt failed"); + expect(JSON.stringify(result.output)).toContain('"created_by":"unknown"'); + expect(JSON.stringify(result.output)).toContain('"owner":"account-owner"'); + expect(JSON.stringify(result.output)).toContain(`"assignee":"${executorActor(child)}"`); + expect(bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(2); + await freshCleanup(); +}); + +test("a permission wait neither writes nor checkpoints during compaction; stop rejects a later approval", async () => { + const f = createHost(); + const t = toolFixture(f); + const permissionStarted = Promise.withResolvers<void>(); + const approval = Promise.withResolvers<void>(); + const permission = mock<NonNullable<HostContext["permission"]>["assert"]>(() => { + permissionStarted.resolve(); + return approval.promise; + }); + const get = mock(async () => sessionInfo("/project", "human-default")); + const prompt = mock(async () => ({})); + const synthetic = mock(async () => ({})); + Object.assign(f.ctx, { + permission: { assert: permission }, + location: { directory: "/project", project: { directory: "/project" } }, + }); + Object.assign(f.ctx.session, { + prompt, + synthetic, + get, + }); + const bd = mock(async (_cwd: string, args: readonly string[]) => { + if (args[0] === "version") return "1.3.1"; + if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; + throw new Error(`Unexpected bd operation while permission is withheld: ${args[0]}`); + }); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "CURRENT" }, + continuityQualified: true, + continuity: { bd, realpath: async (value) => value }, + }); + await f.request("child", "beads-task-agent"); + const abort = new AbortController(); + const context = invocation("child", "beads-task-agent", abort.signal); + const pending = t.tools + .find((tool) => tool.name === "note")! + .execute({ id: "fixture-1", text: "unsaved partial result" }, context); + const outcome = pending.then( + () => undefined, + (error: unknown) => error, + ); + await permissionStarted.promise; + expect(permission).toHaveBeenCalledWith( + expect.objectContaining({ + agent: context.agent, + sessionID: context.sessionID, + save: [], + source: { type: "tool", messageID: context.messageID, id: context.id }, + }), + ); + const count = bd.mock.calls.length; + const summary: ContextEvent = { sessionID: "child", agent: "beads-task-agent", system: [] }; + await f.hooks.get("compaction")!(summary); + expect(summary.system).toEqual([{ type: "text", text: BEADS_COMPACTION_GUIDANCE }]); + expect(bd).toHaveBeenCalledTimes(count); + expect(permission).toHaveBeenCalledTimes(1); + abort.abort(); + expect(await outcome).toHaveProperty("name", "AbortError"); + const sessionReads = get.mock.calls.length; + approval.resolve(); + // Let the in-memory approval continuation drain before checking for late work. + await setImmediate(); + expect(get).toHaveBeenCalledTimes(sessionReads); + expect(bd).toHaveBeenCalledTimes(count); + expect(bd.mock.calls.every(([, args]) => ["version", "context"].includes(args[0] ?? ""))).toBe(true); + expect(prompt).not.toHaveBeenCalled(); + expect(synthetic).not.toHaveBeenCalled(); + await cleanup(); +}); diff --git a/tests/host-command-fixture.ts b/tests/host-command-fixture.ts new file mode 100644 index 0000000..c3da611 --- /dev/null +++ b/tests/host-command-fixture.ts @@ -0,0 +1,76 @@ +import { mock } from "bun:test"; +import type { CommandDefinition, CommandDomain, CommandInvocation } from "@opencode/plugin/promise/command"; +import type { HostContext } from "../src/host"; +import { type createHost, sessionInfo, unsupported } from "./host-fixture"; + +/** Replay only the public add callbacks in native package/config order. */ +export function commandFixture(f: ReturnType<typeof createHost>) { + const callbacks: Array<Parameters<CommandDomain["transform"]>[0]> = []; + const initial: CommandDefinition = { + name: "oc-beads:ready", + description: "EARLIER PLUGIN", + execute: async () => unsupported("earlier plugin command execution"), + }; + let lookupFailed = false; + let omitted: string | undefined; + const commands = () => { + const result = new Map([[initial.name, initial]]); + for (const callback of callbacks) callback({ add: (definition) => result.set(definition.name, definition) }); + return result; + }; + const transform = mock<CommandDomain["transform"]>(async (callback) => { + callbacks.push(callback); + commands(); + return { + dispose: async () => { + callbacks.splice(callbacks.indexOf(callback), 1); + }, + }; + }); + type Prompt = NonNullable<HostContext["session"]["prompt"]>; + const prompt = mock<Prompt>(async ({ sessionID, text, delivery }) => ({ + id: "submitted-message", + sessionID, + type: "user", + payload: { text }, + time: { created: 1 }, + delivery: delivery ?? "steer", + })); + f.ctx.command = { + transform, + list: async () => { + if (lookupFailed) throw new Error("lookup failed"); + return { + location: { directory: f.ctx.location.directory }, + data: [...commands().values()] + .filter((entry) => entry.name !== omitted) + .map(({ name, description }) => ({ name, description })), + }; + }, + }; + Object.assign(f.ctx.session, { prompt, get: async () => sessionInfo("/project", "build") }); + const invocation = { + sessionID: "s1", + delivery: "queue", + prompt: { + text: "literal '$ARGUMENTS' $(touch nope) `text`", + files: [{ uri: "file:///tmp/a%20b" }], + agents: [{ name: "build" }], + skills: [{ id: "oc-beads" }], + }, + } as unknown as CommandInvocation; + return { + callbacks, + commands, + transform, + prompt, + invocation, + detailsInvocation: { ...invocation, prompt: { ...invocation.prompt, text: "details" } }, + failLookup: (failed: boolean) => { + lookupFailed = failed; + }, + omit: (name?: string) => { + omitted = name; + }, + }; +} diff --git a/tests/host-diagnostic-collection.test.ts b/tests/host-diagnostic-collection.test.ts new file mode 100644 index 0000000..b539eeb --- /dev/null +++ b/tests/host-diagnostic-collection.test.ts @@ -0,0 +1,401 @@ +import { Message } from "@opencode/ai/effect"; +import { expect, mock, test } from "bun:test"; +import { setupBeads } from "../src/host"; +import * as diagnosticPresentation from "../src/diagnostics"; +import { type ContextEvent, storedUserMessage, createHost } from "./host-fixture"; +import { commandFixture } from "./host-command-fixture"; + +test("registered diagnostics distinguishes missing, held, failed, loading and uncertain context", async () => { + const f = createHost(); + const c = commandFixture(f); + let time = 0; + let version = "1.3.1"; + let probe: "missing" | "failed" | "ready" = "missing"; + const bd = mock(async (_directory: string, args: readonly string[]) => { + if (args.join(" ") === "version") return `bd ${version}`; + if (args.join(" ") === "context --json") { + if (probe === "failed") throw new Error("probe failed"); + return JSON.stringify({ beads_dir: probe === "ready" ? "/unused-fixture/.beads" : "" }); + } + if (args.join(" ") === "hooks list --json") return '{"hooks":[]}'; + throw new Error("unexpected command"); + }); + const primeStarted = Promise.withResolvers<void>(); + const primeResult = Promise.withResolvers<string>(); + const prime = mock(() => { + primeStarted.resolve(); + return primeResult.promise; + }); + const cleanup = await setupBeads(f.ctx, { bd, runtime: { prime }, now: () => time, retryMs: 1, warn: () => {} }); + const diagnostics = c.commands().get("oc-beads:diagnostics")!; + const report = async () => { + await diagnostics.execute(c.detailsInvocation); + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + return JSON.parse(metadata.ocBeadsWorkflow.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + }; + const initial = await report(); + expect(initial.liveQualification).toBe("not measured by diagnostics; see release acceptance evidence"); + expect(initial.context).toBe("unobserved: no cached context"); + expect(initial.requestCapability).toBe("unknown: no actual request observation"); + await f.request("s1", "build"); + expect((await report()).context).toBe("missing"); + version = "1.2.0"; + time += 2; + await f.request("s1", "build"); + expect((await report()).context).toBe("withheld"); + version = "1.3.1"; + probe = "failed"; + time += 2; + await f.request("s1", "build"); + const failed = await report(); + expect(failed.context).toBe("failed"); + expect(failed.guard.kind).toBe("probe-failed"); + expect(prime).not.toHaveBeenCalled(); + probe = "ready"; + time += 2; + const pending = f.request("s1", "build"); + await primeStarted.promise; + expect((await report()).context).toBe("uncertain: context refresh in progress"); + primeResult.resolve("PRIME"); + await pending; + const observed = await report(); + expect(observed.context).toBe("ready"); + expect(observed.guard).toEqual({ kind: "ready", version: "1.3.1", workspace: { path: "/unused-fixture/.beads" } }); + expect(observed.syncTarget).toEqual({ + state: "unknown", + reason: "native backend was not reported", + listingSkipped: true, + }); + expect(JSON.stringify(observed)).not.toMatch(/migration-pending|migrate schema/); + expect(observed.requestCapability.agent).toBe("build"); + expect(observed.requestCapability.capabilities.typed).toBe("unknown"); + expect(observed.leafAvailability).toContain("unknown"); + expect(prime).toHaveBeenCalledTimes(1); + await f.events.emit({ type: "session.execution.interrupted", data: { sessionID: "s1" } }); + expect((await report()).persistence).toContain("no final checkpoint"); + Object.assign(f.ctx.session, { + get: async () => { + throw new Error("unknown location"); + }, + }); + const count = bd.mock.calls.length; + const unknown = await report(); + expect(unknown.context).toBe("uncertain: session lookup failed"); + expect(unknown.guard.kind).toBe("withheld"); + expect(unknown.persistence).toContain("uncertain: no final-write guarantee"); + expect(bd).toHaveBeenCalledTimes(count); + expect(new Set(bd.mock.calls.map(([, args]) => args.join(" ")))).toEqual( + new Set(["version", "context --json", "hooks list --json"]), + ); + await cleanup(); +}); + +test("diagnostics starts lookup synchronously and reads new request evidence after the registry probe", async () => { + const f = createHost(); + const c = commandFixture(f); + const session = { agent: "build", location: { directory: "/project" } }; + const lookup = Promise.withResolvers<typeof session>(); + const registryStarted = Promise.withResolvers<void>(); + const releaseRegistry = Promise.withResolvers<void>(); + const effects: string[] = []; + const cleanup = await setupBeads(f.ctx, { + bd: async () => '{"hooks":[]}', + warn: () => {}, + runtime: { + guard: async () => { + effects.push("guard"); + return { kind: "ready" }; + }, + prime: async () => "BODY", + }, + }); + const originalList = f.ctx.command!.list; + let firstLookup = true; + Object.assign(f.ctx.session, { + get() { + if (!firstLookup) return Promise.resolve(session); + firstLookup = false; + effects.push("lookup"); + return lookup.promise; + }, + }); + Object.assign(f.ctx.command!, { + async list() { + registryStarted.resolve(); + await releaseRegistry.promise; + return originalList.call(this); + }, + }); + + const pending = c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + try { + expect(effects).toEqual(["lookup"]); + lookup.resolve(session); + queueMicrotask(() => effects.push("caller microtask")); + await Promise.race([registryStarted.promise, pending]); + expect(effects).toEqual(["lookup", "guard", "caller microtask"]); + + await f.request("s1", "build"); + releaseRegistry.resolve(); + await pending; + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + const report = JSON.parse(metadata.ocBeadsWorkflow.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + expect(report.context).toBe("unobserved: no cached context"); + expect(report.requestCapability.agent).toBe("build"); + expect(report.requestInstructions).toHaveProperty("at"); + } finally { + lookup.resolve(session); + releaseRegistry.resolve(); + await pending.catch(() => {}); + await cleanup(); + } +}); + +test("unload aborts an in-flight native diagnostics without submitting a late prompt", async () => { + const f = createHost(); + const c = commandFixture(f); + const guardStarted = Promise.withResolvers<AbortSignal | undefined>(); + const guardResult = Promise.withResolvers<void>(); + const cleanup = await setupBeads(f.ctx, { + warn: () => {}, + runtime: { + guard: async (_directory, abortSignal) => { + guardStarted.resolve(abortSignal); + await guardResult.promise; + return { kind: "ready" }; + }, + }, + }); + const pending = c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const signal = await guardStarted.promise; + await cleanup(); + expect(signal?.aborted).toBe(true); + guardResult.resolve(); + await expect(pending).rejects.toThrow("unloaded"); + expect(c.prompt).not.toHaveBeenCalled(); +}); + +test("unload prevents a pending native target listing from submitting a report", async () => { + const f = createHost(); + const c = commandFixture(f); + const { promise: listingStarted, resolve: startListing } = Promise.withResolvers<void>(); + const { promise: listing, resolve: finishListing } = Promise.withResolvers<string>(); + const cleanup = await setupBeads(f.ctx, { + warn: () => {}, + bd: async (_directory, args) => { + switch (args.join(" ")) { + case "version": + return "bd version 1.3.4"; + case "context --json": + return '{"beads_dir":"/fixture/.beads","backend":"dolt","dolt_mode":"embedded"}'; + case "hooks list --json": + return '{"hooks":[]}'; + case "--readonly dolt remote list --json --sandbox": + startListing(); + return listing; + default: + throw new Error("unexpected command"); + } + }, + }); + const pending = c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + try { + await Promise.race([listingStarted, pending]); + await cleanup(); + finishListing("[]"); + await expect(pending).rejects.toThrow("unloaded"); + expect(c.prompt).not.toHaveBeenCalled(); + } finally { + finishListing("[]"); + await cleanup(); + } +}); + +test("diagnostics reports preceding context version and request instruction counts", async () => { + const f = createHost(); + const c = commandFixture(f); + let version = "1.3.1"; + const bd = mock(async (_directory: string, args: readonly string[]) => { + if (args[0] === "version") return `bd version ${version}`; + if (args[0] === "context") return JSON.stringify({ beads_dir: "/unused/.beads", cwd_repo_root: "/project" }); + if (args[0] === "hooks") return JSON.stringify({ hooks: [] }); + throw new Error("unexpected invocation"); + }); + const cleanup = await setupBeads(f.ctx, { bd, runPrime: async () => "prime body", warn: () => {} }); + try { + await f.request("s1", "build"); + version = "1.3.4"; + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + expect(metadata.ocBeadsWorkflow.instructions).toContain("1.3.1"); + expect(metadata.ocBeadsWorkflow.instructions).toContain("1.3.4"); + expect(metadata.ocBeadsWorkflow.instructions).toContain("requestInstructions"); + } finally { + await cleanup(); + } +}); + +test("registered diagnostics uses the last request time for duplicate guidance", async () => { + const f = createHost(); + const c = commandFixture(f); + let now = 1_700_000_000_000; + const cleanup = await setupBeads(f.ctx, { + now: () => now, + warn: () => {}, + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "BODY" }, + }); + try { + const block = "<!-- BEGIN BEADS INTEGRATION v:1 profile:full -->BODY<!-- END BEADS INTEGRATION -->"; + const event: ContextEvent = { + sessionID: "s1", + agent: "build", + system: [{ type: "text", text: `${block}\n${block}` }], + }; + await f.hooks.get("context")!(event); + const observedAt = now; + now += 60_000; + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) + .ocBeadsWorkflow.instructions; + const report = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + const finding = report.findings.find((item: { id: string }) => item.id === "request-full-duplicates"); + expect(finding.scope).toBe("last observed request"); + expect(finding.observedAt).toBe(new Date(observedAt).toISOString()); + expect(report.requestInstructions.at).toBe(observedAt); + } finally { + await cleanup(); + } +}); + +test("registered diagnostics handles exact selectors locally and replays captured output once", async () => { + const f = createHost(); + const c = commandFixture(f); + const bd = mock(async (_directory: string, args: readonly string[]) => { + switch (args.join(" ")) { + case "version": + return "bd version 1.3.4"; + case "context --json": + return '{"beads_dir":"/fixture/.beads","backend":"dolt","dolt_mode":"server","server_port":3307}'; + case "hooks list --json": + return '{"hooks":[]}'; + case "--readonly dolt remote list --json --sandbox": + return '[{"name":"origin","url":"https://user:remote-secret@example.invalid","sql_url":"https://sql-secret.example.invalid","cli_url":"https://cli-secret.example.invalid","status":"ok"}]'; + default: + throw new Error("unexpected command"); + } + }); + const prime = mock(async () => "PRIME INCLUDING MEMORY"); + const cleanup = await setupBeads(f.ctx, { bd, now: () => 2000, warn: () => {}, runPrime: prime }); + try { + for (const text of [ + "", + " DeTaIlS ", + " ReMoTe ", + " DeTaIlS ReMoTe\n", + "remote please", + "remote details", + "details remote", + " HeLp ", + "help me", + "help\n", + ]) { + const input = { ...c.invocation, prompt: { ...c.invocation.prompt, text } }; + const beforeCalls = bd.mock.calls.length; + await c.commands().get("oc-beads:diagnostics")!.execute(input); + const sent = c.prompt.mock.calls.at(-1)![0]; + const snapshot = (sent.metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; + const selector = text.trim().toLowerCase(); + expect(snapshot.instructions.includes("Details: ")).toBe(selector === "details" || selector === "details remote"); + const framedReport = snapshot.instructions + .split("\nBEGIN_DIAGNOSTIC_REPORT\n")[1] + ?.split("\nEND_DIAGNOSTIC_REPORT\n")[0]; + expect(framedReport).toBeDefined(); + expect(snapshot.instructions).toEndWith("\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n"); + if (selector === "help") { + expect(bd.mock.calls.length).toBe(beforeCalls); + expect(snapshot.instructions).toContain(diagnosticPresentation.DIAGNOSTICS_HELP); + } else { + expect(bd.mock.calls.slice(beforeCalls)).toEqual([ + [f.ctx.location.directory, ["version"]], + [f.ctx.location.directory, ["context", "--json"]], + [f.ctx.location.directory, ["hooks", "list", "--json"]], + [f.ctx.location.directory, ["--readonly", "dolt", "remote", "list", "--json", "--sandbox"]], + ]); + expect(framedReport).toContain("| Sync target | ✅ | Resolved · origin |"); + expect(framedReport).toContain("| Remote history | — | Not checked"); + expect(framedReport!.includes("No qualified Beads history probe is available")).toBe( + selector === "remote" || selector === "details remote", + ); + expect(snapshot.instructions).not.toMatch(/secret|Check failed|cannot resolve|no.configured.remote/); + } + expect(sent.text).toBe(`/oc-beads:diagnostics${text ? `${/[\r\n]/.test(text) ? "\n" : " "}${text}` : ""}`); + expect(sent.files).toBe(input.prompt.files); + expect(sent.delivery).toBe(input.delivery); + if (!prime.mock.calls.length) { + const system = await f.request("s1", "build"); + expect(system.join("\n")).toContain("PRIME INCLUDING MEMORY"); + expect(prime).toHaveBeenCalledWith(f.ctx.location.directory, ["--full"]); + } + const count = bd.mock.calls.length; + const stored = storedUserMessage("presented", String(sent.text), { + ocBeadsWorkflow: { version: 1, ...snapshot }, + }); + Object.assign(f.ctx.session, { context: async () => [stored] }); + for (const kind of ["context", "compaction"] as const) { + const event: ContextEvent = { + sessionID: "s1", + agent: "build", + system: [], + messages: [Message.make({ id: stored.id, role: "user", content: String(sent.text) })], + }; + await f.hooks.get(kind)!(event); + expect(event.messages![0]!.content[0]).toEqual(Message.text(snapshot.instructions)); + expect(event.messages![0]!.content[1]).toEqual(Message.text(String(sent.text))); + const once = JSON.stringify(event.messages); + await f.hooks.get(kind)!(event); + expect(JSON.stringify(event.messages)).toBe(once); + } + expect(bd.mock.calls.length).toBe(count); + } + } finally { + await cleanup(); + } +}); + +test("registered command completeness separates membership truncation from description clipping", async () => { + const f = createHost(); + const c = commandFixture(f); + const cleanup = await setupBeads(f.ctx, { + bd: async () => '{"hooks":[]}', + warn: () => {}, + runtime: { guard: async () => ({ kind: "ready" }) }, + }); + try { + const owned = c.commands().get("oc-beads:ready")!; + c.callbacks.push((editor) => editor.add({ ...owned, description: "x".repeat(600) })); + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + let instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) + .ocBeadsWorkflow.instructions; + let report = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + expect(report.commands.truncated).toBe(true); + expect(report.commands.membershipTruncated).toBe(false); + expect(report.commands.expectedCount).toBe(30); + expect(instructions).toContain("| Commands | ✅ | 30/30 present |"); + c.callbacks.push((editor) => editor.add({ ...owned, description: "custom changed" })); + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) + .ocBeadsWorkflow.instructions; + expect(instructions).toContain("| Commands | ⚠️ | 30/30 · 1 changed |"); + c.callbacks.push((editor) => { + for (let i = 0; i < 130; i++) editor.add({ name: `custom-${i}`, description: "custom", execute: async () => {} }); + }); + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) + .ocBeadsWorkflow.instructions; + report = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + expect(report.commands.membershipTruncated).toBe(true); + expect(instructions).toContain("| Commands | — | list incomplete · 1 changed |"); + } finally { + await cleanup(); + } +}); diff --git a/tests/host-diagnostic-fixture.ts b/tests/host-diagnostic-fixture.ts new file mode 100644 index 0000000..237f712 --- /dev/null +++ b/tests/host-diagnostic-fixture.ts @@ -0,0 +1,42 @@ +import { type DiagnosticsSnapshot } from "../src/diagnostics"; + +/** Fixed observed fields shared by the representative compact-presentation cases. */ +export function presentationFixture() { + return { + plugin: { name: "@snarkipus/opencode-beads", version: "2.2.1" }, + host: "2.3.0", + commands: { + registration: "registered", + lookup: "available", + truncated: true, + membershipTruncated: false, + expectedCount: 30, + effective: [], + missing: [], + mismatches: [], + }, + skill: { effective: ["oc-beads"], collision: "none detected" }, + typedContinuity: "enabled: qualified beta registration", + typedRegistration: "registered: beads namespace, code-mode-only", + requestCapability: { agent: "build", capabilities: { execute: true } }, + context: "ready", + contextObservation: { status: "ready", version: "1.3.4", loadedAt: 1000 }, + guard: { kind: "ready", version: "1.3.4", workspace: { path: "/fixture/.beads", repoRoot: "/fixture" } }, + local: { + scope: "context cwd_repo_root", + managedInstructions: { state: "available", full: 1, minimal: 0, codex: 1 }, + sharedSkill: "missing", + witness: { state: "match", recorded: "1.3.4", running: "1.3.4" }, + }, + hooks: ["pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"].map((name) => ({ + name, + installed: true, + shim: true, + outdated: false, + version: "1.3.4", + })), + syncTarget: { state: "resolved", name: "origin" }, + requestInstructions: { at: 1000, full: 1, minimal: 0, codex: 1, replaced: 1, retained: 1 }, + persistence: "uncertain: no final-write guarantee", + } satisfies DiagnosticsSnapshot; +} diff --git a/tests/host-diagnostic-native-evidence.test.ts b/tests/host-diagnostic-native-evidence.test.ts new file mode 100644 index 0000000..e0f6654 --- /dev/null +++ b/tests/host-diagnostic-native-evidence.test.ts @@ -0,0 +1,390 @@ +import { expect, mock, test } from "bun:test"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { setupBeads } from "../src/host"; +import { PrimeProcessError, PrimeTimeoutError } from "../src/prime"; +import { createHost, sessionInfo } from "./host-fixture"; +import { commandFixture } from "./host-command-fixture"; + +test("registered diagnostics reports an embedded store with no native remotes or installed hooks", async () => { + const f = createHost(); + const c = commandFixture(f); + const bd = mock(async (_directory: string, args: readonly string[]) => { + if (args.join(" ") === "version") return "bd version 1.3.4"; + if (args.join(" ") === "context --json") + return JSON.stringify({ beads_dir: "/unused/.beads", backend: "dolt", dolt_mode: "embedded" }); + if (args.join(" ") === "hooks list --json") + return JSON.stringify({ + hooks: [{ Name: "pre-commit", Installed: false, Version: "", IsShim: false, Outdated: false }], + }); + if (args.join(" ") === "--readonly dolt remote list --json --sandbox") return "[]"; + throw new Error("unexpected invocation"); + }); + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + try { + await c + .commands() + .get("oc-beads:diagnostics")! + .execute({ ...c.detailsInvocation, prompt: { ...c.detailsInvocation.prompt, text: "details remote" } }); + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + const report = metadata.ocBeadsWorkflow.instructions; + expect(report).toContain("| Git hooks | — | 0/1 installed · 1 missing/unreadable/unresolved |"); + expect(report).toContain("| Sync target | ✅ | Local-only |"); + expect(report).toContain("| Remote history | — | Not applicable |"); + expect(report).not.toContain("No qualified Beads history probe is available"); + expect(report).toContain("Git-origin adoption with consent"); + expect(report).toContain("Source-Git freshness was not checked"); + expect(report).toContain("pre-commit"); + expect(report).not.toContain("Git hooks need attention"); + expect(report).not.toContain("bd hooks install"); + expect(bd.mock.calls).toEqual([ + [f.ctx.location.directory, ["version"]], + [f.ctx.location.directory, ["context", "--json"]], + [f.ctx.location.directory, ["hooks", "list", "--json"]], + [f.ctx.location.directory, ["--readonly", "dolt", "remote", "list", "--json", "--sandbox"]], + ]); + } finally { + await cleanup(); + } +}); + +test("registered diagnostics keeps incomplete or ambiguous native target evidence neutral", async () => { + const f = createHost(); + const c = commandFixture(f); + const origin = { name: "origin", status: "ok", url: "https://user:listing-secret@example.invalid" }; + const remoteList = ["--readonly", "dolt", "remote", "list", "--json", "--sandbox"]; + let context: Record<string, unknown>; + let listing: string | Error; + const bd = mock(async (_directory: string, args: readonly string[]) => { + switch (args.join(" ")) { + case "version": + return "bd version 1.3.4"; + case "context --json": + return JSON.stringify({ beads_dir: "/fixture/.beads", ...context }); + case "hooks list --json": + return '{"hooks":[]}'; + case "--readonly dolt remote list --json --sandbox": + if (listing instanceof Error) throw listing; + return listing; + default: + throw new Error("unexpected command"); + } + }); + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + const embedded = { backend: "dolt", dolt_mode: "embedded" }; + const server = { + backend: "dolt", + dolt_mode: "server", + server_host: "server-secret.example.invalid", + server_port: 3307, + }; + const cases = [ + { context: server, output: "[]", reason: "empty native listing in server mode" }, + { + context: embedded, + output: JSON.stringify([{ ...origin, name: "alternate" }]), + reason: "native origin was not listed", + }, + { + context: { ...server, ...embedded }, + output: JSON.stringify([origin]), + reason: "embedded mode conflicts with server endpoint evidence", + skipListing: true, + }, + { + context: { backend: "dolt" }, + output: JSON.stringify([origin]), + reason: "native Dolt mode was not reported", + skipListing: true, + }, + { + context: { ...embedded, dolt_mode: "unknown-mode" }, + output: "[]", + reason: "unrecognized native Dolt mode", + skipListing: true, + }, + { context: { dolt_mode: "embedded" }, output: "[]", reason: "native backend was not reported", skipListing: true }, + { + context: { ...embedded, backend: "unknown-backend" }, + output: "[]", + reason: "native backend is not Dolt", + skipListing: true, + }, + { + context: { backend: "dolt", dolt_mode: "proxied-server", proxied_dir: "/proxy-secret" }, + output: "[]", + reason: "proxied-server mode is unsupported", + skipListing: true, + }, + { + context: embedded, + output: JSON.stringify([origin, { name: "incomplete" }]), + reason: "native listing returned an unsupported response", + }, + { context: embedded, output: "invalid JSON", reason: "native listing returned an unsupported response" }, + { + context: embedded, + output: new PrimeProcessError(1, origin.url, "bd dolt remote list", origin.url), + reason: "native listing exited with code 1", + }, + { context: embedded, output: new PrimeTimeoutError(5, "bd dolt remote list"), reason: "native listing timed out" }, + ]; + try { + for (const example of cases) { + context = example.context; + listing = example.output; + const start = bd.mock.calls.length; + await c + .commands() + .get("oc-beads:diagnostics")! + .execute({ ...c.detailsInvocation, prompt: { ...c.detailsInvocation.prompt, text: "details remote" } }); + const { ocBeadsWorkflow } = c.prompt.mock.calls.at(-1)![0].metadata as { + ocBeadsWorkflow: { instructions: string }; + }; + const report = ocBeadsWorkflow.instructions; + expect(report).toContain(`| Sync target | — | Unknown · ${example.reason} |`); + expect(report).toContain("| Remote history | — | Not checked · No qualified Beads history probe is available |"); + expect(report).toContain("Comparison was not attempted"); + expect(report).not.toMatch(/secret|Check failed|Unresolved|❌ Unhealthy/); + expect(bd.mock.calls.slice(start).map(([, args]) => args)).toEqual([ + ["version"], + ["context", "--json"], + ["hooks", "list", "--json"], + ...(example.skipListing ? [] : [remoteList]), + ]); + const details = JSON.parse(report.split("\nDetails: ")[1]!.split("\n")[0]!) as { + findings: Array<{ id: string; producer: string; meaning: string }>; + }; + const target = details.findings.find(({ id }) => id === "sync-target"); + expect(target?.producer).toBe( + example.skipListing + ? "bd context --json" + : "bd --readonly dolt remote list --json --sandbox and bd context --json", + ); + if (example.skipListing) expect(target?.meaning).toContain("The strict-readonly remote listing was skipped"); + } + } finally { + await cleanup(); + } +}); + +test("diagnostics captures witness and scoped managed guidance without remote secrets", async () => { + const root = await mkdtemp(path.join(tmpdir(), "health-diag-")); + const beads = path.join(root, ".beads"); + await mkdir(beads); + await writeFile(path.join(beads, ".local_version"), "1.3.1\n"); + await writeFile( + path.join(root, "AGENTS.md"), + "<!-- BEGIN BEADS INTEGRATION v:1 profile:full -->body<!-- END BEADS INTEGRATION -->", + ); + const f = createHost(); + Object.assign(f.ctx, { location: { directory: root } }); + const c = commandFixture(f); + Object.assign(f.ctx.session, { get: async () => sessionInfo(root, "build") }); + const bd = async (_dir: string, args: readonly string[]) => + args[0] === "version" + ? "bd 1.3.4" + : args[0] === "context" + ? JSON.stringify({ beads_dir: beads, cwd_repo_root: root, sync_remote: "https://user:secret@example.invalid" }) + : JSON.stringify({ hooks: [] }); + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + try { + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + const text = metadata.ocBeadsWorkflow.instructions; + expect(text).toContain("1.3.1"); + expect(text).toContain("differ"); + expect(text).toContain("managedInstructions"); + expect(text).not.toContain("secret"); + expect(text).toContain('"sharedSkill":"missing"'); + expect(text).toContain(`PATH: \`${root}\``); + expect(JSON.parse(text.split("\nDetails: ")[1]!.split("\n")[0]!).guard.workspace).toEqual({ + path: beads, + repoRoot: root, + remote: true, + }); + await mkdir(path.join(root, ".agents", "skills", "beads"), { recursive: true }); + await writeFile(path.join(root, ".agents", "skills", "beads", "SKILL.md"), "local skill"); + await writeFile(path.join(beads, ".local_version"), "1.3.4\n"); + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + let latest = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) + .ocBeadsWorkflow.instructions; + expect(latest).toContain("Recorded 1.3.4 matches running 1.3.4"); + expect(latest).toContain('"sharedSkill":"readable"'); + await rm(path.join(beads, ".local_version")); + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + latest = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow + .instructions; + expect(latest).toContain("Witness missing"); + } finally { + await cleanup(); + await rm(root, { recursive: true, force: true }); + } +}); + +test("captured diagnostics renders compact hook summary before explicit evidence", async () => { + const f = createHost(); + const c = commandFixture(f); + const bd = async (_directory: string, args: readonly string[]) => + args[0] === "version" + ? "bd 1.3.4" + : args[0] === "context" + ? '{"beads_dir":"/none"}' + : JSON.stringify({ + hooks: [{ Name: "pre-commit", Installed: false, Version: "", IsShim: false, Outdated: false }], + }); + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + try { + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + const text = metadata.ocBeadsWorkflow.instructions; + expect(text).toContain("**Plugin**"); + expect(text).toContain("**Beads**"); + expect(text.indexOf("0/1 installed")).toBeLessThan(text.indexOf("**Evidence**")); + expect(JSON.parse(text.split("\nDetails: ")[1]!.split("\n")[0]!).hooks[0].name).toBe("pre-commit"); + expect(text).toContain("bd hooks list"); + } finally { + await cleanup(); + } +}); + +test("native hook failures and installation mismatches stay independent of the sync target", async () => { + const f = createHost(); + const c = commandFixture(f); + let hookOutput = "broken"; + let timedOut = false; + const calls: string[] = []; + const bd = async (_directory: string, args: readonly string[]) => { + const command = args.join(" "); + calls.push(command); + if (command === "version") return "bd 1.3.4"; + if (command === "context --json") return '{"beads_dir":"/none","backend":"dolt","dolt_mode":"embedded"}'; + if (command === "hooks list --json") { + if (timedOut) throw new PrimeTimeoutError(5, "bd hooks list --json"); + return hookOutput; + } + if (command === "--readonly dolt remote list --json --sandbox") + return '[{"name":"origin","url":"file:///fixture","status":"ok"}]'; + throw new Error("unexpected command"); + }; + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + const capture = async () => { + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + return (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow + .instructions; + }; + try { + const failed = await capture(); + expect(failed).toContain("hooks list observation unavailable or unsupported"); + expect(failed).toContain("| Git hooks | — | observation failed |"); + expect(failed).toContain("| Sync target | ✅ | Resolved · origin |"); + timedOut = true; + expect(await capture()).toContain("hooks list observation unavailable or unsupported"); + timedOut = false; + const shim = { Name: "pre-push", Installed: true, Version: "", IsShim: true, Outdated: false }; + hookOutput = JSON.stringify({ hooks: [shim] }); + const ordinaryShim = await capture(); + expect(ordinaryShim).toContain("| Git hooks | ✅ | 1/1 installed (shims) |"); + expect(ordinaryShim).not.toContain("bd hooks install"); + hookOutput = JSON.stringify({ hooks: [{ ...shim, Outdated: true }] }); + const outdatedShim = await capture(); + expect(outdatedShim).toContain("| Git hooks | ⚠️ | 1/1 installed · 1 outdated |"); + expect(outdatedShim).toContain("pre-push: outdated"); + expect(outdatedShim).toContain("Verify with `bd hooks list`."); + hookOutput = JSON.stringify({ + hooks: [ + { Name: "pre-commit", Installed: true, Version: "", IsShim: false, Outdated: false }, + { Name: "post-merge", Installed: true, Version: "1.2.0", IsShim: false, Outdated: true }, + { Name: "pre-push", Installed: true, Version: "1.3.4", IsShim: true, Outdated: false }, + ], + }); + const report = await capture(); + expect(report).toContain("installed without a reported version"); + expect(report).toContain("outdated"); + expect(report).toContain("shim does not certify current wrapper policy"); + expect(report).toContain("| Git hooks | ⚠️ | 3/3 installed (1 shim) · 1 outdated · 1 unrecognized |"); + expect(report).toContain("| Sync target | ✅ | Resolved · origin |"); + expect(report).toContain("**Plugin** ✅ Healthy"); + expect(report).toContain("**Beads** ⚠️ Mismatch"); + expect(report).not.toMatch(/no.configured.remote|hook execution succeeded/); + expect(new Set(calls)).toEqual( + new Set(["version", "context --json", "hooks list --json", "--readonly dolt remote list --json --sandbox"]), + ); + } finally { + await cleanup(); + } +}); + +test("diagnostics identifies incomplete root guidance and a missing shared skill", async () => { + const root = await mkdtemp(path.join(tmpdir(), "health-incomplete-")); + const f = createHost({ directory: root }); + const c = commandFixture(f); + Object.assign(f.ctx.session, { get: async () => sessionInfo(root, "build") }); + const bd = async (_directory: string, args: readonly string[]) => + args[0] === "version" + ? "bd 1.3.4" + : args[0] === "context" + ? JSON.stringify({ beads_dir: path.join(root, ".beads"), cwd_repo_root: root }) + : '{"hooks":[]}'; + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + const capture = async () => { + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + return (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow + .instructions; + }; + try { + await mkdir(path.join(root, "AGENTS.md")); + let report = await capture(); + expect(report.split("\nDetails: ")[0]).toContain("| AGENTS Configured | — | unreadable |"); + expect(report.split("\nDetails: ")[0]).toContain("unreadable"); + expect(report.split("\nDetails: ")[0]).toContain("shared: absent"); + expect(report).toContain("not a plugin failure"); + let details = JSON.parse(report.split("\nDetails: ")[1]!.split("\n")[0]!); + expect(details.findings.find((finding: { id: string }) => finding.id === "shared-skill-missing").class).toBe( + "note", + ); + await mkdir(path.join(root, ".agents", "skills", "beads", "SKILL.md"), { recursive: true }); + report = await capture(); + expect(report.split("\nDetails: ")[0]).toContain("shared: unreadable"); + details = JSON.parse(report.split("\nDetails: ")[1]!.split("\n")[0]!); + expect(details.findings.find((finding: { id: string }) => finding.id === "shared-skill-unreadable").class).toBe( + "failed", + ); + await rm(path.join(root, "AGENTS.md"), { recursive: true }); + await writeFile(path.join(root, "AGENTS.md"), "x".repeat(65_537)); + report = await capture(); + expect(report.split("\nDetails: ")[0]).toContain("truncated"); + expect(report).toContain("last-request"); + } finally { + await cleanup(); + await rm(root, { recursive: true, force: true }); + } +}); + +test("diagnostics withholds hook observation when session location is unconfirmed", async () => { + const f = createHost(); + const c = commandFixture(f); + Object.assign(f.ctx.session, { + get: async () => { + throw new Error("session lookup failed"); + }, + }); + const bd = mock(async (_directory: string, _args: readonly string[]) => { + throw new Error("unexpected native collection"); + }); + const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); + try { + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) + .ocBeadsWorkflow.instructions; + const snapshot = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + const hookFinding = snapshot.findings.find((finding: { id: string }) => finding.id === "hooks-unavailable"); + expect(hookFinding.class).toBe("unknown"); + expect(hookFinding.observation).toContain("withheld: session location unconfirmed"); + expect(instructions.split("\nDetails: ")[0]).not.toContain("[failed] beads / bd hooks list"); + expect(bd).not.toHaveBeenCalled(); + } finally { + await cleanup(); + } +}); diff --git a/tests/host-diagnostic-rendering.test.ts b/tests/host-diagnostic-rendering.test.ts new file mode 100644 index 0000000..cb9268a --- /dev/null +++ b/tests/host-diagnostic-rendering.test.ts @@ -0,0 +1,410 @@ +import { expect, test } from "bun:test"; +import { renderHealthReport, type DiagnosticsSnapshot } from "../src/diagnostics"; +import * as diagnosticPresentation from "../src/diagnostics"; +import type { PluginHealthObservation } from "../src/diagnostics-collection"; +import { presentationFixture } from "./host-diagnostic-fixture"; + +test("diagnostics groups repeated hooks while retaining other findings and exact native evidence", () => { + const names = ["pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"]; + const missing = names.map((name) => ({ name, installed: false, version: "", shim: false, outdated: false })); + const shims = names.map((name) => ({ name, installed: true, version: "1.3.4", shim: true, outdated: false })); + const base = { + plugin: { name: "fixture", version: "1" }, + host: "2.3.0", + context: "ready", + guard: { kind: "ready", version: "1.3.4" }, + } satisfies DiagnosticsSnapshot; + for (const hooks of [missing, shims]) { + const snapshot: DiagnosticsSnapshot = { + ...base, + hooks, + local: { + witness: { state: "differ", recorded: "1.3.1", running: "1.3.4" }, + managedInstructions: { state: "available", full: 0 }, + sharedSkill: "readable", + }, + contextObservation: { version: "1.3.1", loadedAt: 1000 }, + }; + const report = renderHealthReport(snapshot, 2000, true); + const [summary, details] = report.split("\nDetails: "); + expect(summary).toContain("1.3.1 ≠ CLI 1.3.4"); + expect(summary).toContain("| Context | ⚠️ | Loaded under bd 1.3.1 |"); + const captured = JSON.parse(details!); + expect(captured.hooks).toEqual(hooks); + expect( + captured.findings.filter((finding: { producer: string }) => finding.producer === "bd hooks list"), + ).toHaveLength(1); + expect(report).toContain( + "https://github.com/gastownhall/beads/blob/7ef2fd05eb0cd3bdbde051f93cfc14ccf270cdde/docs/getting-started/upgrading.md", + ); + } +}); + +test("diagnostic duplicate findings preserve root and last-request provenance", () => { + const requestAt = 1700000000000; + const captureAt = 1700000060000; + const report = renderHealthReport( + { + plugin: {}, + host: "2.3.0", + context: "ready", + guard: { kind: "ready" }, + hooks: [], + local: { + scope: "context cwd_repo_root", + managedInstructions: { state: "available", full: 2 }, + sharedSkill: "readable", + }, + requestInstructions: { at: requestAt, full: 2, retained: 1 }, + }, + captureAt, + true, + ); + const captured = JSON.parse(report.split("\nDetails: ")[1]!); + const root = captured.findings.find((f: { id: string }) => f.id === "duplicate-full"); + const request = captured.findings.find((f: { id: string }) => f.id === "request-full-duplicates"); + expect(root.scope).toBe("root-file observation: context cwd_repo_root"); + expect(root.observedAt).toBe(new Date(captureAt).toISOString()); + expect(request.scope).toBe("last observed request"); + expect(request.observedAt).toBe(new Date(requestAt).toISOString()); + expect(captured.requestInstructions.at).toBe(requestAt); +}); + +test("witness guidance links the pinned release guide", () => { + const report = renderHealthReport( + { + plugin: {}, + host: "2.3.0", + context: "ready", + guard: { kind: "ready" }, + hooks: [], + local: { witness: { state: "differ", recorded: "1.3.1", running: "1.3.4" } }, + }, + 0, + true, + ); + expect(report).toContain( + "https://github.com/gastownhall/beads/blob/7ef2fd05eb0cd3bdbde051f93cfc14ccf270cdde/docs/getting-started/upgrading.md", + ); +}); + +test("command observations suggest reviewing customization only for complete missing or changed membership", () => { + const ready = presentationFixture(); + const hint = "Review command customization and rerun diagnostics."; + const cases: Array<{ commands: DiagnosticsSnapshot["commands"]; expected: boolean }> = [ + { commands: { ...ready.commands, missing: ["oc-beads:show"] }, expected: true }, + { commands: { ...ready.commands, mismatches: [{ name: "oc-beads:show" }] }, expected: true }, + { commands: ready.commands, expected: false }, + { commands: { ...ready.commands, lookup: "failed", missing: ["oc-beads:show"] }, expected: false }, + { commands: { ...ready.commands, membershipTruncated: true, missing: ["oc-beads:show"] }, expected: false }, + { commands: { ...ready.commands, missing: undefined }, expected: false }, + ]; + for (const c of cases) + expect(renderHealthReport({ ...ready, commands: c.commands }, 2000).includes(hint)).toBe(c.expected); +}); + +test("normal diagnostics uses compact tables and assessed severity with literal coverage", () => { + const ready = presentationFixture(); + const report = renderHealthReport(ready, 2000); + expect(report).toBe(`## Beads diagnostics — ✅ Healthy + +DATE: \`1970-01-01T00:00:02.000Z\` + +VERSION: @snarkipus/opencode-beads \`2.2.1\` + +PATH: \`/fixture\` + +Remote history not checked. + +**Plugin** ✅ Healthy + +| Check | Status | Value | +|---|---|---| +| Host | ✅ | OpenCode 2.3.0 | +| Commands | ✅ | 30/30 present | +| Skill | ✅ | oc-beads active · shared: absent | +| Typed tools | ✅ | Registered | +| Context | ✅ | Loaded | +| AGENTS Configured | ✅ | bd block | + +**Beads** ✅ Healthy + +| Check | Status | Value | +|---|---|---| +| bd CLI | ✅ | 1.3.4 | +| Workspace | ✅ | Located | +| Recorded bd version | ✅ | 1.3.4 = CLI | +| Git hooks | ✅ | 5/5 installed (shims) | +| Sync target | ✅ | Resolved · origin | +| Remote history | — | Not checked |`); + expect(report).toContain("## Beads diagnostics — ✅ Healthy"); + expect(report).toContain("**Plugin**"); + expect(report).toContain("**Beads**"); + expect(report).toContain("| Check | Status | Value |"); + expect(report).toContain("| Recorded bd version | ✅ | 1.3.4 = CLI |"); + expect(report).not.toMatch(/partial|Request instructions|Codex|descriptions/i); + expect(report).not.toMatch( + /Details:|Limits:|does not establish|model-mediated|unique build|liveQualification|no final-write guarantee|remote freshness/i, + ); + const first = renderHealthReport( + { + ...ready, + context: "unobserved: no cached context", + contextObservation: undefined, + requestInstructions: "unobserved", + requestCapability: undefined, + }, + 2000, + ); + expect(first).toBe(`## Beads diagnostics — ✅ Healthy + +DATE: \`1970-01-01T00:00:02.000Z\` + +VERSION: @snarkipus/opencode-beads \`2.2.1\` + +PATH: \`/fixture\` + +Remote history not checked. + +**Plugin** ✅ Healthy + +| Check | Status | Value | +|---|---|---| +| Host | ✅ | OpenCode 2.3.0 | +| Commands | ✅ | 30/30 present | +| Skill | ✅ | oc-beads active · shared: absent | +| Typed tools | ✅ | Registered | +| Context | — | Not yet loaded | +| AGENTS Configured | ✅ | bd block | + +**Beads** ✅ Healthy + +| Check | Status | Value | +|---|---|---| +| bd CLI | ✅ | 1.3.4 | +| Workspace | ✅ | Located | +| Recorded bd version | ✅ | 1.3.4 = CLI | +| Git hooks | ✅ | 5/5 installed (shims) | +| Sync target | ✅ | Resolved · origin | +| Remote history | — | Not checked |`); + expect(first).toContain("| Context | — | Not yet loaded |"); + expect(first).toContain("✅ Healthy"); + const unreadableSkill = renderHealthReport({ ...ready, local: { ...ready.local, sharedSkill: "unreadable" } }, 2000); + expect(unreadableSkill).toContain("| Skill | — | oc-beads active · shared: unreadable |"); + expect( + renderHealthReport({ ...ready, local: { ...ready.local, scope: "confirmed session directory" } }, 2000), + ).toContain("| AGENTS Configured | ✅ | bd block |"); + const vps = renderHealthReport( + { ...ready, hooks: ready.hooks.map((h) => ({ ...h, installed: false, shim: false, version: "" })) }, + 2000, + ); + expect(vps).toBe(`## Beads diagnostics — ✅ Healthy + +DATE: \`1970-01-01T00:00:02.000Z\` + +VERSION: @snarkipus/opencode-beads \`2.2.1\` + +PATH: \`/fixture\` + +Remote history not checked. + +**Plugin** ✅ Healthy + +| Check | Status | Value | +|---|---|---| +| Host | ✅ | OpenCode 2.3.0 | +| Commands | ✅ | 30/30 present | +| Skill | ✅ | oc-beads active · shared: absent | +| Typed tools | ✅ | Registered | +| Context | ✅ | Loaded | +| AGENTS Configured | ✅ | bd block | + +**Beads** ✅ Healthy + +| Check | Status | Value | +|---|---|---| +| bd CLI | ✅ | 1.3.4 | +| Workspace | ✅ | Located | +| Recorded bd version | ✅ | 1.3.4 = CLI | +| Git hooks | — | 0/5 installed · 5 missing/unreadable/unresolved | +| Sync target | ✅ | Resolved · origin | +| Remote history | — | Not checked |`); + const incompatible = renderHealthReport( + { + ...ready, + guard: { kind: "unsupported", installed: "1.3.0" }, + context: "withheld", + hooks: "failed: unsupported", + syncTarget: undefined, + }, + 2000, + ); + expect(incompatible).toBe(`## Beads diagnostics — ❌ Unhealthy + +DATE: \`1970-01-01T00:00:02.000Z\` + +VERSION: @snarkipus/opencode-beads \`2.2.1\` + +PATH: \`not observed\` + +bd CLI unavailable or below the supported minimum. Remote history not checked. + +**Plugin** ❌ Unhealthy + +| Check | Status | Value | +|---|---|---| +| Host | ✅ | OpenCode 2.3.0 | +| Commands | ✅ | 30/30 present | +| Skill | ✅ | oc-beads active · shared: absent | +| Typed tools | ✅ | Registered | +| Context | ❌ | Withheld | +| AGENTS Configured | ✅ | bd block | + +**Beads** ❌ Unhealthy + +| Check | Status | Value | +|---|---|---| +| bd CLI | ❌ | 1.3.0 (needs ≥1.3.1) | +| Workspace | — | not observed | +| Recorded bd version | ✅ | 1.3.4 = CLI | +| Git hooks | — | observation failed | +| Sync target | — | Unknown · native listing not performed | +| Remote history | — | Not checked | + +**Actions** + +- Install or upgrade bd to ≥1.3.1, then start a new session. Check: \`bd version\`.`); + expect(incompatible).toContain("❌ Unhealthy"); + expect(incompatible).toContain("| Git hooks | — | observation failed |"); + const noEvidence = renderHealthReport({}, 2000); + expect(noEvidence).not.toContain("✅ Healthy"); + expect(noEvidence).toContain("| Sync target | — | Unknown · native listing not performed |"); + expect(noEvidence).toContain("| Remote history | — | Not checked |"); + expect(noEvidence).toContain("No checks assessed"); +}); + +test("normal command membership, witness and write uncertainty keep distinct severity", () => { + const ready = presentationFixture(); + const partial = renderHealthReport( + { ...ready, commands: { ...ready.commands, membershipTruncated: true, missing: undefined } }, + 2000, + ); + expect(partial).toContain("| Commands | — | list incomplete |"); + const partialChanged = renderHealthReport( + { + ...ready, + commands: { + ...ready.commands, + membershipTruncated: true, + missing: undefined, + mismatches: [{ name: "oc-beads:show" }], + }, + }, + 2000, + ); + expect(partialChanged).toContain("| Commands | — | list incomplete · 1 changed |"); + const differs = renderHealthReport( + { ...ready, local: { ...ready.local, witness: { state: "differ", recorded: "1.3.1", running: "1.3.4" } } }, + 2000, + ); + expect(differs).toContain("| Recorded bd version | ⚠️ | 1.3.1 ≠ CLI 1.3.4 |"); + expect(differs).not.toContain("❌ Unhealthy"); + const gap = renderHealthReport({ ...ready, persistence: "update task-1: uncertain; readback required" }, 2000); + expect(gap).toContain("update task-1"); + expect(gap).toContain("⚠️ Mismatch"); +}); + +test("AGENTS Configured recognizes markers while unknown guidance stays neutral", () => { + const ready = presentationFixture(); + const rootObservations: PluginHealthObservation["managedInstructions"][] = [ + { state: "available", full: 0, minimal: 0, codex: 0 }, + { state: "missing" }, + { state: "unreadable" }, + { state: "truncated" }, + ]; + for (const managedInstructions of rootObservations) { + const report = renderHealthReport({ ...ready, local: { ...ready.local, managedInstructions } }, 2000); + expect(report).toContain("| AGENTS Configured | — |"); + expect(report).not.toMatch(/partial|Request instructions|full ·|Codex/); + } + for (const counts of [ + { full: 0, minimal: 1, codex: 0 }, + { full: 0, minimal: 0, codex: 1 }, + ]) { + expect( + renderHealthReport( + { ...ready, local: { ...ready.local, managedInstructions: { state: "available", ...counts } } }, + 2000, + ), + ).toContain("| AGENTS Configured | ✅ | bd block |"); + } + expect( + renderHealthReport( + { ...ready, local: { ...ready.local, managedInstructions: { state: "available", full: 2 } } }, + 2000, + ), + ).toContain("| AGENTS Configured | ⚠️ | duplicate bd blocks |"); + const unrecognized = renderHealthReport( + { ...ready, hooks: [{ name: "pre-commit", installed: true, version: "", shim: false, outdated: false }] }, + 2000, + ); + expect(unrecognized).toContain("1 unrecognized"); + expect(unrecognized).not.toContain("not bd"); +}); + +test("command names remain measurable without hiding missing or changed entries", () => { + const ready = presentationFixture(); + expect( + renderHealthReport( + { + ...ready, + commands: { ...ready.commands, missing: ["oc-beads:ready"], mismatches: [{ name: "oc-beads:show" }] }, + }, + 2000, + ), + ).toContain("| Commands | ⚠️ | 29/30 · 1 missing · 1 changed |"); + expect(renderHealthReport({ ...ready, commands: { ...ready.commands, lookup: "failed" } }, 2000)).toContain( + "| Commands | — | not observed |", + ); + const details = renderHealthReport(ready, 2000, true); + expect(details).toContain('"requestInstructions":{"at":1000'); + expect(details).toContain('"truncated":true'); + for (const row of renderHealthReport({ ...ready, persistence: "update unresolved" }, 2000) + .split("\n") + .filter((line) => line.startsWith("| ") && !line.startsWith("| Check"))) { + expect(diagnosticPresentation.DIAGNOSTICS_HELP).toContain(row.split(" | ")[0]!.slice(2)); + } +}); + +test("diagnostic header metadata uses observed root and exact code-populated values", () => { + const fixture = presentationFixture(); + const report = renderHealthReport(fixture, 2000); + expect(report).toStartWith( + "## Beads diagnostics — ✅ Healthy\n\nDATE: `1970-01-01T00:00:02.000Z`\n\nVERSION: @snarkipus/opencode-beads `2.2.1`\n\nPATH: `/fixture`\n\nRemote history not checked.\n\n**Plugin**", + ); + expect(report.match(/DATE:/g)).toHaveLength(1); + expect(report.match(/VERSION:/g)).toHaveLength(1); + expect(report.match(/PATH:/g)).toHaveLength(1); + expect(report).not.toContain("/fixture/.beads"); + const missingRoot = renderHealthReport( + { ...fixture, guard: { ...fixture.guard, workspace: { path: "/fixture/.beads" } } }, + 2000, + true, + ); + expect(missingRoot).toContain("PATH: `not observed`"); + expect(missingRoot).toContain('"path":"/fixture/.beads"'); + expect( + renderHealthReport( + { + ...fixture, + guard: { ...fixture.guard, workspace: { path: "/different/.beads", repoRoot: "/observed/root/" } }, + }, + 2000, + ), + ).toContain("PATH: `/observed/root/`"); + const mismatch = renderHealthReport( + { ...fixture, hooks: fixture.hooks.map((hook) => ({ ...hook, shim: false, outdated: true })) }, + 2000, + ); + expect(mismatch.indexOf("PATH:")).toBeLessThan(mismatch.indexOf("Git hooks need attention.")); +}); diff --git a/tests/host-fixture.ts b/tests/host-fixture.ts new file mode 100644 index 0000000..bb27d9f --- /dev/null +++ b/tests/host-fixture.ts @@ -0,0 +1,230 @@ +import { mock } from "bun:test"; +import type { HostContext } from "../src/host"; +import type { Info, ToolContext, ToolDomain, ToolEditor } from "@opencode/plugin/promise/tool"; +import type { SessionCompaction, SessionContext } from "@opencode/plugin/promise/session"; + +export type ContextEvent = { + messages?: SessionContext["messages"]; + tools?: Record<string, unknown>; + sessionID: string; + agent: string; + system: Array<{ type: "text"; text: string }>; +}; + +export type ToolAfterEvent = Extract<Parameters<Parameters<ToolDomain["hook"]>[1]>[0], { status: string }>; + +export type StoredSessionMessage = Awaited<ReturnType<HostContext["session"]["context"]>>[number]; + +export type StoredUserMessage = Extract<StoredSessionMessage, { type: "user" }>; + +export function storedUserMessage( + id: string, + text: string, + metadata?: StoredUserMessage["metadata"], +): StoredUserMessage { + return { id, type: "user", time: { created: 1 }, text, ...(metadata === undefined ? {} : { metadata }) }; +} + +export function unsupported(interaction: string): never { + throw new Error(`Unexpected host interaction: ${interaction}`); +} + +type LifecycleEvent = { type: string; data: { sessionID: string } & Record<string, unknown> }; + +/** A subsequent pull acknowledges that the consumer advanced past the event. */ +function eventStream() { + type Delivery = { event: LifecycleEvent; advanced: PromiseWithResolvers<void> }; + const queue: Delivery[] = []; + const subscribed = Promise.withResolvers<void>(); + let wake = Promise.withResolvers<void>(); + let signal: AbortSignal | undefined; + let closed = false; + + async function* subscribe(input?: { signal?: AbortSignal }) { + signal = input?.signal; + const onAbort = () => wake.resolve(); + signal?.addEventListener("abort", onAbort, { once: true }); + subscribed.resolve(); + let current: Delivery | undefined; + try { + while (!signal?.aborted) { + current = queue.shift(); + if (current) { + yield current.event; + current.advanced.resolve(); + current = undefined; + } else { + await wake.promise; + wake = Promise.withResolvers<void>(); + } + } + } finally { + closed = true; + signal?.removeEventListener("abort", onAbort); + const dropped = new Error("Event dropped: stream closed before the next pull"); + current?.advanced.reject(dropped); + for (const { advanced } of queue.splice(0)) advanced.reject(dropped); + } + } + + return { + // Tests supply only the session envelope consumed by the adapter. + subscribe: subscribe as HostContext["event"]["subscribe"], + subscribed: subscribed.promise, + async emit(event: LifecycleEvent) { + await subscribed.promise; + if (closed || signal?.aborted) unsupported("event.emit after stream closed"); + const advanced = Promise.withResolvers<void>(); + queue.push({ event, advanced }); + wake.resolve(); + await advanced.promise; + }, + aborted: () => signal?.aborted === true, + }; +} + +type SessionLookup = NonNullable<HostContext["session"]["get"]>; + +/** Session reads expose the location and optional default agent used by the adapter. */ +export function sessionInfo(directory: string, agent?: string): Awaited<ReturnType<SessionLookup>> { + return { location: { directory }, ...(agent === undefined ? {} : { agent }) } as Awaited<ReturnType<SessionLookup>>; +} + +export function createHost( + options: { + directory?: string; + pluginOptions?: Record<string, unknown>; + appVersion?: string; + } = {}, +) { + const hooks = new Map<string, (event: ContextEvent) => Promise<void> | void>(); + const events = eventStream(); + type AgentLookup = HostContext["agent"]["get"]; + const directory = options.directory ?? "/project"; + const agentGet = mock<AgentLookup>(async ({ agentID }) => ({ + location: { directory }, + data: { + id: agentID, + name: agentID, + request: { settings: {}, headers: {}, body: {} }, + mode: agentID === "explore" ? "subagent" : "primary", + hidden: false, + permissions: [], + }, + })); + type AgentEditor = Parameters<Parameters<HostContext["agent"]["transform"]>[0]>[0]; + type EditableAgent = Parameters<Parameters<AgentEditor["update"]>[1]>[0]; + type ObservedAgent = Omit<EditableAgent, "id" | "name" | "model"> & { + id: string; + name: string; + model?: { providerID: string; id: string; variant?: string }; + }; + const agents = new Map<string, ObservedAgent>(); + const editor: AgentEditor = { + list: () => unsupported("agent.editor.list"), + get: () => unsupported("agent.editor.get"), + default: () => unsupported("agent.editor.default"), + remove: () => unsupported("agent.editor.remove"), + // Mirrors OpenCode: update() on an unknown ID starts from defaults. + update(id, update) { + const agent = agents.get(id) ?? { + id, + name: id, + request: { settings: {}, headers: {}, body: {} }, + mode: "primary", + hidden: false, + permissions: [], + }; + update(agent as EditableAgent); + agents.set(id, agent); + }, + }; + const agentTransform: HostContext["agent"]["transform"] = async (callback) => { + callback(editor); + return { dispose: async () => {} }; + }; + const sessionHook: HostContext["session"]["hook"] = async (name, callback) => { + if (name !== "context" && name !== "compaction") return unsupported(`session.hook(${name})`); + const invoke = callback as (event: SessionContext | SessionCompaction) => Promise<void> | void; + hooks.set(name, (event) => { + event.messages ??= []; + // Events omit model fields unless the individual story observes them. + return invoke(event as SessionContext); + }); + return { dispose: async () => {} }; + }; + const ctx: HostContext = { + app: { name: "OpenCode", version: options.appVersion ?? "2.3.0", channel: "stable" }, + location: { directory } as HostContext["location"], + options: options.pluginOptions ?? {}, + event: { subscribe: events.subscribe }, + agent: { get: agentGet, transform: agentTransform }, + session: { + context: async () => [], + hook: sessionHook, + }, + }; + + async function request(sessionID: string, agent: string, tools?: Record<string, unknown>): Promise<string[]> { + const event: ContextEvent = { + sessionID, + agent, + ...(tools ? { tools } : {}), + system: [{ type: "text", text: "HOST" }], + }; + const hook = hooks.get("context"); + if (!hook) throw new Error("context hook not registered"); + await hook(event); + return event.system.slice(1).map((part) => part.text); + } + + return { ctx, hooks, events, agentGet, agents, request }; +} + +/** Capture public hook/registration callbacks, without simulating host child transport. */ +export function toolFixture(f: ReturnType<typeof createHost>, dispose = async () => {}) { + const tools: Info[] = []; + const namespaces: Array<Parameters<ToolEditor["namespace"]>[0]> = []; + let after: ((event: ToolAfterEvent) => Promise<void> | void) | undefined; + const hook: ToolDomain["hook"] = async (name, callback) => { + if (name !== "execute.after") return unsupported(`tool.hook(${name})`); + after = callback as NonNullable<typeof after>; + return { dispose }; + }; + const editor: ToolEditor = { + list: () => unsupported("tool.editor.list"), + get: () => unsupported("tool.editor.get"), + update: () => unsupported("tool.editor.update"), + remove: () => unsupported("tool.editor.remove"), + namespace: (value) => namespaces.push(value), + add: (tool) => tools.push(tool), + }; + const transform: ToolDomain["transform"] = async (callback) => { + callback(editor); + return { dispose }; + }; + f.ctx.tool = { hook, transform }; + return { + tools, + namespaces, + after(event: ToolAfterEvent) { + if (!after) return unsupported("tool.execute.after before registration"); + return after(event); + }, + }; +} + +// The 2.4 SDK requires codemode; the 2.3 SDK does not declare it. +export const nonCodeMode = { codemode: false }; + +/** Cast only host-branded IDs at the fixture boundary. */ +export function invocation(sessionID: string, agent: string, signal = new AbortController().signal): ToolContext { + return { + sessionID, + agent, + messageID: `message-${sessionID}`, + id: `call-${sessionID}`, + signal, + progress: async () => {}, + } as unknown as ToolContext; +} diff --git a/tests/host-lifecycle.test.ts b/tests/host-lifecycle.test.ts new file mode 100644 index 0000000..01c2dc6 --- /dev/null +++ b/tests/host-lifecycle.test.ts @@ -0,0 +1,184 @@ +import { expect, mock, test } from "bun:test"; +import { setImmediate } from "node:timers/promises"; +import { setupBeads, type HostContext } from "../src/host"; +import { createHost, sessionInfo, toolFixture } from "./host-fixture"; +import { commandFixture } from "./host-command-fixture"; + +test("stops the event stream on cleanup", async () => { + const f = createHost(); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, + }); + await f.events.subscribed; + await cleanup(); + expect(f.events.aborted()).toBeTrue(); +}); + +test("awaits idempotent cleanup of every owned registration and aborts pending context", async () => { + const f = createHost(); + const disposed: string[] = []; + const completed: string[] = []; + const registrations = ["agent", "hook:compaction", "hook:context", "skill", "tool", "tool-hook"]; + const finishDisposals = Promise.withResolvers<void>(); + const finishLastDisposal = Promise.withResolvers<void>(); + const own = (name: string) => ({ + dispose: async () => { + disposed.push(name); + await (name === "agent" ? finishLastDisposal.promise : finishDisposals.promise); + completed.push(name); + }, + }); + const originalAgent = f.ctx.agent.transform; + const transform: HostContext["agent"]["transform"] = async (callback) => { + await originalAgent(callback); + return own("agent"); + }; + Object.assign(f.ctx.agent, { transform }); + const originalHook = f.ctx.session.hook; + const hook: HostContext["session"]["hook"] = async (name, callback) => { + await originalHook(name, callback); + return own(`hook:${name}`); + }; + Object.assign(f.ctx.session, { hook }); + Object.assign(f.ctx, { + skill: { + list: async () => ({ data: [] }), + transform: async (callback: (editor: unknown) => void) => { + callback({ list: () => [], add: () => {} }); + return own("skill"); + }, + }, + permission: { assert: async () => {} }, + }); + Object.assign(f.ctx.session, { get: async () => sessionInfo("/project") }); + toolFixture(f); + const registeredTools = f.ctx.tool!; + f.ctx.tool = { + transform: async (callback) => { + await registeredTools.transform(callback); + return own("tool"); + }, + hook: async (name, callback) => { + await registeredTools.hook(name, callback); + return own("tool-hook"); + }, + }; + const primeStarted = Promise.withResolvers<AbortSignal | undefined>(); + const primeResult = Promise.withResolvers<string>(); + const cleanup = await setupBeads(f.ctx, { + continuityQualified: true, + runtime: { + guard: async () => ({ kind: "ready" }), + prime: async (_cwd, abortSignal) => { + primeStarted.resolve(abortSignal); + return primeResult.promise; + }, + }, + }); + const pending = f.request("s1", "build"); + const signal = await primeStarted.promise; + let cleanupCompleted = false; + const firstCleanup = cleanup(); + const completion = firstCleanup.then(() => { + cleanupCompleted = true; + }); + const secondCleanup = cleanup(); + expect(secondCleanup).toBe(firstCleanup); + expect([...disposed].sort()).toEqual(registrations); + finishDisposals.resolve(); + // Drain continuations from the five released disposers before checking cleanup. + await setImmediate(); + expect(cleanupCompleted).toBe(false); + finishLastDisposal.resolve(); + await Promise.all([completion, secondCleanup]); + expect(signal?.aborted).toBe(true); + expect(f.events.aborted()).toBe(true); + expect(completed.sort()).toEqual(registrations); + primeResult.resolve("LATE OLD LOCATION"); + expect(await pending).toEqual([]); + await cleanup(); + expect(disposed).toHaveLength(6); +}); + +test("releases earlier owned registrations if a later setup seam fails", async () => { + const f = createHost(); + const disposed = mock(async () => {}); + const originalAgent = f.ctx.agent.transform; + const transform: HostContext["agent"]["transform"] = async (callback) => { + await originalAgent(callback); + return { dispose: disposed }; + }; + Object.assign(f.ctx.agent, { transform }); + Object.assign(f.ctx.session, { + hook: async () => { + throw new Error("host hook failed"); + }, + }); + await expect(setupBeads(f.ctx)).rejects.toThrow("host hook failed"); + expect(disposed).toHaveBeenCalledTimes(1); +}); + +test("missing packaged guidance is withheld with honest diagnostics", async () => { + const transform = mock(async () => ({ dispose: async () => {} })); + const warnings: string[] = []; + const missing = createHost(); + Object.assign(missing.ctx, { skill: { list: async () => ({ data: [] }), transform } }); + const missingCleanup = await setupBeads(missing.ctx, { + warn: (message) => warnings.push(message), + workflowAssets: { + readText: async () => { + throw new Error("sensitive exception content"); + }, + }, + }); + expect(transform).not.toHaveBeenCalled(); + expect(warnings.some((warning) => warning.includes("skill-unreachable SKILL.md"))).toBe(true); + expect(warnings.join("\n")).not.toContain("sensitive exception content"); + await missingCleanup(); +}); + +test("cleanup attempts every owned disposer and reports a failed disposal", async () => { + const f = createHost(); + const warn = mock((_message: string) => {}); + const disposed = mock(async () => {}); + const transform: HostContext["agent"]["transform"] = async () => ({ + dispose: async () => { + throw new Error("dispose failed"); + }, + }); + Object.assign(f.ctx.agent, { transform }); + const originalHook = f.ctx.session.hook; + const hook: HostContext["session"]["hook"] = async (name, callback) => { + await originalHook(name, callback); + return { dispose: disposed }; + }; + Object.assign(f.ctx.session, { hook }); + const cleanup = await setupBeads(f.ctx, { warn }); + await expect(cleanup()).rejects.toThrow("Beads cleanup failed"); + expect(disposed).toHaveBeenCalledTimes(2); + expect(warn.mock.calls.flat().join("\n")).toContain("cleanup-failed"); + expect(f.events.aborted()).toBe(true); +}); + +test("a failed native command registration diagnoses failure and releases earlier owned registrations", async () => { + const f = createHost(); + commandFixture(f); + const disposed = mock(async () => {}); + const original = f.ctx.agent.transform; + const transform: HostContext["agent"]["transform"] = async (callback) => { + await original(callback); + return { dispose: disposed }; + }; + Object.assign(f.ctx.agent, { transform }); + Object.assign(f.ctx.command!, { + transform: async () => { + throw new Error("native registration failed"); + }, + }); + const warnings: string[] = []; + await expect(setupBeads(f.ctx, { warn: (message) => warnings.push(message) })).rejects.toThrow( + "native registration failed", + ); + expect(warnings.join("\n")).toContain("command-registration-failed"); + expect(disposed).toHaveBeenCalledTimes(1); +}); diff --git a/tests/host-request.test.ts b/tests/host-request.test.ts new file mode 100644 index 0000000..193c28a --- /dev/null +++ b/tests/host-request.test.ts @@ -0,0 +1,328 @@ +import type { SessionCompaction } from "@opencode/plugin/promise/session"; +import { expect, mock, test } from "bun:test"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { renderBeadsContext } from "../src/context"; +import { setupBeads } from "../src/host"; +import { executorActor } from "../src/continuity"; +import { BEADS_COMPACTION_GUIDANCE, primeFailureNotice } from "../src/guidance"; +import { type ContextEvent, createHost, toolFixture, sessionInfo } from "./host-fixture"; + +test("refreshes recovery state for external changes, isolates fork/move/audience and never restarts on interruption", async () => { + const f = createHost(); + let directory = "/project"; + let output = "FIRST"; + Object.assign(f.ctx.session, { get: async () => sessionInfo(directory) }); + const prime = mock(async () => output); + const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); + await f.request("s1", "build"); + await f.request("s10", "build"); + output = "EXTERNAL CHANGE"; + await f.events.emit({ type: "session.execution.started", data: { sessionID: "s1" } }); + const recovered = await f.request("s1", "build"); + expect(recovered[0]).toContain("EXTERNAL CHANGE"); + expect(recovered[1]).toContain("Cached absence is not proof of absence"); + expect((await f.request("s10", "build"))[0]).toContain("FIRST"); + expect((await f.request("fork", "build"))[0]).toContain("EXTERNAL CHANGE"); + const hidden: ContextEvent = { sessionID: "s1", agent: "explore", system: [] }; + await f.hooks.get("compaction")!(hidden); + expect(hidden.system).toEqual([]); + const count = prime.mock.calls.length; + await f.events.emit({ type: "session.execution.interrupted", data: { sessionID: "s1" } }); + expect(prime).toHaveBeenCalledTimes(count); + directory = "/elsewhere"; + await f.events.emit({ type: "session.moved", data: { sessionID: "s1" } }); + expect(await f.request("s1", "build")).toEqual([]); + expect(prime).toHaveBeenCalledTimes(count); + await cleanup(); +}); + +test("renders actual filtered request capability and actor, preserving guard holds", async () => { + const f = createHost(); + const t = toolFixture(f); + let guard: any = { kind: "ready" }; + const prime = mock(async () => "FULL PRIME"); + Object.assign(f.ctx, { permission: { assert: async () => {} } }); + Object.assign(f.ctx.session, { + get: async () => sessionInfo("/project", "session-default"), + }); + const cleanup = await setupBeads(f.ctx, { + continuityQualified: true, + runtime: { guard: async () => guard, prime }, + }); + expect(t.namespaces).toEqual([{ name: "beads", description: expect.any(String) }]); + expect(t.tools).toHaveLength(11); + expect(t.tools.every((tool) => tool.options?.namespace === "beads" && tool.options.codemode === true)).toBeTrue(); + const typed = (await f.request("actual", "build", { execute: {}, shell: {} }))[0]!; + expect(typed).toContain(executorActor({ sessionID: "actual", agent: "build" })); + expect(typed).toContain("Beads namespace is registered and execute is visible"); + const direct = (await f.request("actual", "restricted", { beads_get: {}, beads_note: {} }))[0]!; + expect(direct).toContain(executorActor({ sessionID: "actual", agent: "restricted" })); + expect(direct).toContain("Native Beads leaf tools are directly visible"); + expect(direct).toContain("Use only the listed direct leaves"); + expect(direct).toContain("Each operation still checks its own permission"); + expect(direct).not.toContain("direct shell tool"); + const shell = (await f.request("actual", "review", { shell: {} }))[0]!; + expect(shell).toContain(executorActor({ sessionID: "actual", agent: "review" })); + expect(shell).not.toContain(executorActor({ sessionID: "actual", agent: "build" })); + expect(shell).toContain("direct shell tool"); + expect((await f.request("actual", "review", {}))[0]).toContain("Neither native Beads leaves nor direct shell access"); + expect(prime).toHaveBeenCalledTimes(1); + guard = { kind: "unsupported", installed: "1.3.0" }; + await f.events.emit({ type: "session.compaction.ended", data: { sessionID: "actual" } }); + const held = (await f.request("actual", "build", { execute: {}, shell: {} }))[0]!; + expect(held).not.toContain("Beads namespace is registered"); + expect(held).not.toContain("direct shell tool"); + await cleanup(); +}); + +test("appends rendered prime to eligible requests through the context hook only", async () => { + const f = createHost(); + const prime = mock(async (_directory: string) => "PRIME"); + const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); + + expect([...f.hooks.keys()]).toEqual(["context", "compaction"]); + expect(await f.request("s1", "build")).toEqual([ + renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" }), + ]); + expect(await f.request("s1", "build")).toEqual([ + renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" }), + ]); + expect(await f.request("s1", "explore")).toEqual([]); + expect(prime).toHaveBeenCalledTimes(1); + expect(prime).toHaveBeenCalledWith("/project", expect.any(AbortSignal)); + expect(f.agentGet).toHaveBeenCalledWith({ agentID: "build" }); + await cleanup(); +}); + +test("minimizes bd's full AGENTS.md block only when prime is attached", async () => { + const block = "<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:1 -->\nPRIME\n<!-- END BEADS INTEGRATION -->"; + let guard: { kind: "ready" } | { kind: "unsupported"; installed: string } = { + kind: "ready", + }; + const f = createHost(); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => guard, prime: async () => "PRIME" }, + retryMs: 0, + }); + const hook = f.hooks.get("context"); + if (!hook) throw new Error("context hook not registered"); + + const withPrime: ContextEvent = { sessionID: "s1", agent: "build", system: [{ type: "text", text: block }] }; + await hook(withPrime); + expect(withPrime.system[0]?.text).toContain("provided by the opencode-beads plugin"); + expect(withPrime.system[0]?.text).not.toContain("BEGIN BEADS"); + expect(withPrime.system[1]?.text).toBe(renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" })); + + const subagent: ContextEvent = { sessionID: "s1", agent: "explore", system: [{ type: "text", text: block }] }; + await hook(subagent); + expect(subagent.system).toEqual([{ type: "text", text: block }]); + + guard = { kind: "unsupported", installed: "1.3.0" }; + const withNotice: ContextEvent = { sessionID: "s2", agent: "build", system: [{ type: "text", text: block }] }; + await hook(withNotice); + expect(withNotice.system[0]?.text).toBe(block); + expect(withNotice.system[1]?.text).toContain("<beads-notice>"); + await cleanup(); +}); + +test("attaches prime without altering instructions when AGENTS.md has no Beads block", async () => { + const f = createHost(); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, + }); + const hook = f.hooks.get("context"); + if (!hook) throw new Error("context hook not registered"); + const instructions = "Instructions from: /repo/AGENTS.md\n# Project rules"; + const event: ContextEvent = { + sessionID: "s1", + agent: "build", + system: [{ type: "text", text: instructions }], + }; + await hook(event); + expect(event.system).toEqual([ + { type: "text", text: instructions }, + { type: "text", text: renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" }) }, + ]); + await cleanup(); +}); + +test("refreshes after compaction ends and forgets deleted sessions", async () => { + const f = createHost(); + let output = "FIRST"; + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => output }, + }); + + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); + output = "SECOND"; + await f.events.emit({ type: "session.step.ended", data: { sessionID: "s1" } }); + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); + + await f.events.emit({ type: "session.compaction.ended", data: { sessionID: "s1" } }); + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("SECOND"); + + output = "THIRD"; + await f.events.emit({ type: "session.deleted", data: { sessionID: "s1" } }); + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("THIRD"); + await cleanup(); +}); + +test("always runs bd prime with --full, and adds --stealth only when the stealth option is set", async () => { + for (const [options, flags] of [ + [{}, ["--full"]], + [{ stealth: true }, ["--full", "--stealth"]], + [{ stealth: "yes" }, ["--full"]], + ] as const) { + const runPrime = mock(async (_cwd: string, _flags: readonly string[]) => "PRIME"); + const f = createHost({ pluginOptions: options }); + const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }) }, runPrime }); + await f.request("s1", "build"); + expect(runPrime).toHaveBeenCalledWith("/project", flags); + await cleanup(); + } +}); + +test("asks compaction to keep Beads state only for sessions that had Beads context", async () => { + const f = createHost(); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, + }); + const compaction = f.hooks.get("compaction"); + if (!compaction) throw new Error("compaction hook not registered"); + await f.request("s1", "build"); + const withBeads: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; + await compaction(withBeads); + expect(withBeads.system).toEqual([{ type: "text", text: BEADS_COMPACTION_GUIDANCE }]); + const other: ContextEvent = { sessionID: "s2", agent: "build", system: [] }; + await compaction(other); + expect(other.system).toEqual([]); + await f.events.emit({ type: "session.deleted", data: { sessionID: "s1" } }); + const deleted: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; + await compaction(deleted); + expect(deleted.system).toEqual([]); + await cleanup(); +}); + +test("compaction preserves native replay, keepID, legacy recent and model boundaries without I/O", async () => { + const f = createHost(); + const prime = mock(async () => "PRIME"); + const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); + await f.request("s1", "build"); + const hook = f.hooks.get("compaction")!; + // Representative public payloads, not a provider/history implementation or cross-product. + const cases = [ + { model: { providerID: "provider-a", id: "model-a" } }, + { + model: { providerID: "provider-a", id: "model-a" }, + result: { summary: "host summary", metadata: { keepID: "fork-remapped-id" } }, + }, + { + model: { providerID: "provider-b", id: "model-b" }, + result: { + summary: "host fallback", + metadata: { recent: "legacy retained tail" }, + native: { messages: [{ opaque: true }] }, + }, + }, + ]; + for (const fields of cases) { + const event = { + sessionID: "s1", + agent: "build", + system: [], + messages: [], + options: {}, + tools: {}, + ...fields, + } as unknown as SessionCompaction; + const before = JSON.stringify(event); + await hook(event); + const { system, ...preserved } = event; + expect(system).toEqual([{ type: "text", text: BEADS_COMPACTION_GUIDANCE }]); + expect({ ...preserved, system: [] }).toEqual({ ...JSON.parse(before), system: [] }); + expect(event.result).toBe(fields.result); + } + expect(prime).toHaveBeenCalledTimes(1); + await cleanup(); +}); + +test("passes refreshAfterIdleMinutes through to the context cache", async () => { + let time = 0; + let output = "FIRST"; + const f = createHost({ pluginOptions: { refreshAfterIdleMinutes: 1 } }); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => output }, + now: () => time, + }); + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); + output = "SECOND"; + time = 59_000; + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); + time = 59_000 + 60_001; + expect((await f.request("s1", "beads-task-agent"))[0]).toContain("SECOND"); + await cleanup(); +}); + +test("native full prime ignores CLI witnesses and retired autoMigrate values", async () => { + const directory = await mkdtemp(path.join(tmpdir(), "beads-host-")); + try { + for (const marker of [undefined, "1.3.2", "1.3.4", "1.4.0"]) { + const markerPath = path.join(directory, ".local_version"); + if (marker === undefined) await rm(markerPath, { force: true }); + else await writeFile(markerPath, marker); + for (const autoMigrate of [undefined, false, true]) { + const bd = mock(async (_cwd: string, args: readonly string[]) => + args[0] === "version" ? "bd version 1.3.4" : JSON.stringify({ beads_dir: directory }), + ); + const text = "WORKFLOW\n## Persistent Memories\nNative selected memory\nNative partial-availability notice"; + const runPrime = mock(async () => text); + const f = createHost({ directory, pluginOptions: { autoMigrate } }); + const cleanup = await setupBeads(f.ctx, { bd, runPrime }); + try { + expect(await f.request("s1", "build")).toEqual([ + renderBeadsContext(text, "primary", { sessionID: "s1", agent: "build" }), + ]); + expect(runPrime).toHaveBeenCalledWith(directory, ["--full"]); + expect(bd.mock.calls.map((call) => call[1])).toEqual([["version"], ["context", "--json"]]); + } finally { + await cleanup(); + } + } + } + } finally { + await rm(directory, { recursive: true, force: true }); + } +}); + +test("rate-limits diagnostics and never lets them fail a request", async () => { + const f = createHost(); + let time = 0; + const warn = mock((_message: string) => { + throw new Error("log sink down"); + }); + const cleanup = await setupBeads(f.ctx, { + runtime: { + guard: async () => ({ kind: "ready" }), + prime: async () => { + throw new Error("exit 1"); + }, + }, + warn, + now: () => time, + retryMs: 0, + diagnosticIntervalMs: 1_000, + }); + + const notice = [primeFailureNotice("failed")]; + expect(await f.request("s1", "build")).toEqual(notice); + time = 1; + expect(await f.request("s1", "build")).toEqual(notice); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toContain("prime_failed"); + time = 1_002; + await f.request("s1", "build"); + expect(warn).toHaveBeenCalledTimes(2); + await cleanup(); +}); diff --git a/tests/host-serialization.test.ts b/tests/host-serialization.test.ts new file mode 100644 index 0000000..933848a --- /dev/null +++ b/tests/host-serialization.test.ts @@ -0,0 +1,214 @@ +import { Effect } from "effect"; +import { fromRequest as serializeChatRequest } from "@opencode/ai/protocols/openai-chat"; +import { createHash } from "node:crypto"; +import { make } from "@opencode/ai"; +import { Message } from "@opencode/ai/effect"; +import { configure } from "@opencode/ai/providers/openai"; +import baseline from "./fixtures/non-sync-command-baseline.json"; +import { expect, mock, test } from "bun:test"; +import { writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupBeads } from "../src/host"; +import type { SessionContext } from "@opencode/plugin/promise/session"; +import { + type ContextEvent, + type StoredSessionMessage, + type StoredUserMessage, + storedUserMessage, + createHost, +} from "./host-fixture"; +import { commandFixture } from "./host-command-fixture"; + +test("actual Responses serialization retains mixed workflow and legacy instructions once on native replay", async () => { + const f = createHost(); + const c = commandFixture(f); + const { createBeadsCommands } = await import("../src/workflows"); + const commands = createBeadsCommands( + { prompt: c.prompt as unknown as Parameters<typeof createBeadsCommands>[0]["prompt"] }, + async () => "DIAGNOSTICS", + "/fixture/package/assets/oc-beads/SKILL.md", + ); + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + const captures: unknown[] = []; + const server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + async fetch(request) { + captures.push(await request.json()); + const response = { + id: "resp_fixture", + object: "response", + created_at: 0, + model: "fixture", + status: "completed", + output: [], + usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 }, + }; + return new Response(`data: ${JSON.stringify({ type: "response.completed", response })}\n\n`, { + headers: { "content-type": "text/event-stream" }, + }); + }, + }); + const client = make(); + const model = configure({ apiKey: "disposable-fixture", baseURL: `${server.url.origin}/v1` }).responses("fixture"); + const serialize = async (messages: SessionContext["messages"]) => { + await client.generate({ model, messages }); + return JSON.stringify(captures.at(-1)); + }; + try { + const stored: StoredSessionMessage[] = []; + const projected: SessionContext["messages"] = []; + const expected: SessionContext["messages"] = []; + Object.assign(f.ctx.session, { context: mock(async () => stored) }); + const stems = ["show", "update", "compact", "sync", "diagnostics"]; + for (const [index, stem] of stems.entries()) { + const details = + index === stems.length - 1 ? "current turn exact details" : `fixture-1 ${stem} literal --apply --auto`; + await commands + .find((c) => c.name === `oc-beads:${stem}`)! + .execute({ ...c.invocation, prompt: { ...c.invocation.prompt, text: details } }); + const sent = c.prompt.mock.calls.at(-1)![0] as Record<string, unknown>; + const snapshot = (sent.metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; + if (stem === "sync") { + // Canonicalize only the fixed resource path for the historical POSIX digest. + const instructions = snapshot.instructions.replace( + JSON.stringify(path.resolve("/fixture/package/assets/oc-beads/resources/CLI_REFERENCE.md")), + JSON.stringify("/fixture/package/assets/oc-beads/resources/CLI_REFERENCE.md"), + ); + expect(createHash("sha256").update(instructions).digest("hex")).toBe(baseline.syncInstructionsSha256); + } + const messageID = `response-workflow-${stem}`; + const content = [String(sent.text), "native file/skill preparation + prompt hook edits"]; + // Legacy retained history uses its stored snapshot, never a current-definition lookup. + const metadata: StoredUserMessage["metadata"] = + stem === "sync" ? { ocBeadsSync: snapshot, foreign: true } : { ocBeadsWorkflow: snapshot, foreign: true }; + stored.push(storedUserMessage(messageID, String(sent.text), metadata)); + projected.push(Message.make({ id: messageID, role: "user", content: content.map((text) => Message.text(text)) })); + expected.push( + Message.make({ + id: messageID, + role: "user", + content: [snapshot.instructions, ...content].map((text) => Message.text(text)), + }), + ); + if (index === 0) { + const assistant = Message.make({ role: "assistant", content: Message.text("interleaved assistant") }); + projected.push(assistant); + expected.push(assistant); + } + } + const storage = JSON.stringify(stored); + const projectedStorage = JSON.stringify(projected); + let candidate: string | undefined; + for (const kind of ["context", "compaction"] as const) { + const event = { + sessionID: "s1", + agent: "build", + system: [], + messages: projected.map((message) => Message.make(message)), + } as ContextEvent; + await f.hooks.get(kind)!(event); + const serialized = await serialize(event.messages!); + candidate ??= serialized; + expect(serialized).toBe(candidate); + expect(serialized).toBe(await serialize(expected)); + expect(serialized).not.toMatch(/ocBeadsWorkflow|ocBeadsSync/); + for (const stem of stems) + expect( + serialized.match( + new RegExp( + stem === "diagnostics" ? "Reproduce only the finished Markdown" : `Invoked command: /oc-beads:${stem}`, + "g", + ), + ), + ).toHaveLength(1); + expect(serialized).toContain("current turn exact details"); + const once = JSON.stringify(event.messages); + await f.hooks.get(kind)!(event); + expect(JSON.stringify(event.messages)).toBe(once); + expect(await serialize(event.messages!)).toBe(candidate); + const replay = { ...event, messages: projected.map((message) => Message.make(message)) }; + await f.hooks.get(kind)!(replay); + expect(await serialize(replay.messages!)).toBe(candidate); + } + expect(JSON.stringify(stored)).toBe(storage); + expect(JSON.stringify(projected)).toBe(projectedStorage); + const auxiliary = await serialize(projected); + expect(auxiliary).not.toContain("Invoked command:"); + expect(auxiliary).not.toContain("Reproduce only the finished Markdown"); + expect(auxiliary).not.toMatch(/ocBeadsWorkflow|ocBeadsSync/); + expect([...f.hooks.keys()].sort()).toEqual(["compaction", "context"]); + expect(c.prompt).toHaveBeenCalledTimes(stems.length); + if (process.env.OC_BEADS_WORKFLOW_EVIDENCE_DIR) + await writeFile( + path.join(process.env.OC_BEADS_WORKFLOW_EVIDENCE_DIR, "provider-fixture.json"), + JSON.stringify( + { + kind: "local Responses serialization only; no inference", + invocations: stems, + candidate: JSON.parse(candidate!), + auxiliary: JSON.parse(auxiliary), + stablePrimaryCompactionReplay: true, + }, + null, + 2, + ), + ); + } finally { + await client.dispose(); + server.stop(true); + await cleanup(); + } +}); + +test("actual Chat serializer keeps a registered diagnostic report separated from its invocation", async () => { + const f = createHost(); + const c = commandFixture(f); + const cleanup = await setupBeads(f.ctx, { + bd: async () => '{"hooks":[]}', + now: () => 2000, + warn: () => {}, + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, + }); + try { + await c + .commands() + .get("oc-beads:diagnostics")! + .execute({ ...c.invocation, prompt: { ...c.invocation.prompt, text: "" } }); + const sent = c.prompt.mock.calls.at(-1)![0]; + const snapshot = (sent.metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; + const stored = storedUserMessage( + "serialized-diagnostic", + String(sent.text), + sent.metadata as StoredUserMessage["metadata"], + ); + Object.assign(f.ctx.session, { context: async () => [stored] }); + const event: ContextEvent = { + sessionID: "s1", + agent: "build", + system: [], + messages: [Message.make({ id: stored.id, role: "user", content: String(sent.text) })], + }; + await f.hooks.get("context")!(event); + const body = await Effect.runPromise( + serializeChatRequest({ + model: { + id: "fixture-no-network", + provider: "openai", + route: { endpoint: { baseURL: "https://fixture.invalid/v1" } }, + capabilities: {}, + compatibility: {}, + }, + system: [], + messages: event.messages, + tools: [], + } as unknown as Parameters<typeof serializeChatRequest>[0]), + ); + const content = body.messages.find((message) => message.role === "user")?.content; + expect(content).toContain("\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n/oc-beads:diagnostics"); + expect(content).toBe(`${snapshot.instructions}${String(sent.text)}`); + expect(content).not.toContain("`/oc-beads:diagnostics"); + } finally { + await cleanup(); + } +}); diff --git a/tests/host-workflow-registration.test.ts b/tests/host-workflow-registration.test.ts new file mode 100644 index 0000000..ef1605d --- /dev/null +++ b/tests/host-workflow-registration.test.ts @@ -0,0 +1,220 @@ +import { Message } from "@opencode/ai/effect"; +import { expect, mock, test } from "bun:test"; +import { setupBeads } from "../src/host"; +import type { CommandDefinition } from "@opencode/plugin/promise/command"; +import { type ContextEvent, storedUserMessage, createHost } from "./host-fixture"; +import { commandFixture } from "./host-command-fixture"; + +test("registers all commands despite initial collisions; config wins on rebuild, removal restores and disposal preserves config", async () => { + const f = createHost(); + const c = commandFixture(f); + const warns: string[] = []; + const cleanup = await setupBeads(f.ctx, { warn: (message) => warns.push(message) }); + expect(c.transform).toHaveBeenCalledTimes(1); + expect(c.commands().size).toBe(30); + expect(warns.join("\n")).toContain("command-collision"); + expect(warns.join("\n")).toContain("native precedence"); + const packageCallback = c.callbacks[0]!; + const ready = c.commands().get("oc-beads:ready")!; + await ready.execute(c.invocation); + const sent = c.prompt.mock.calls.at(-1)![0]; + expect(sent.text).toContain(c.invocation.prompt.text); + expect(sent.files).toBe(c.invocation.prompt.files); + expect(sent.agents).toBe(c.invocation.prompt.agents); + expect(sent.skills).toBe(c.invocation.prompt.skills); + expect(sent.delivery).toBe(c.invocation.delivery); + const user = { name: ready.name, description: "USER CONFIG", execute: mock(async () => {}) }; + const config = (editor: { add(definition: CommandDefinition): void }) => editor.add(user); + c.callbacks.push(config); + expect(c.commands().get(ready.name)).toBe(user); + await c.commands().get(ready.name)!.execute(c.invocation); + expect(user.execute).toHaveBeenCalledTimes(1); + c.callbacks.splice(c.callbacks.indexOf(config), 1); + expect(c.commands().get(ready.name)).toBe(ready); + c.callbacks.push(config); + await cleanup(); + expect(c.callbacks).toEqual([config]); + expect(c.commands().get(ready.name)).toBe(user); + expect(c.commands().has("oc-beads:diagnostics")).toBe(false); + const add = mock((_definition: CommandDefinition) => {}); + packageCallback({ add }); + expect(add).not.toHaveBeenCalled(); + await expect(ready.execute(c.invocation)).rejects.toThrow("unloaded"); + expect(f.events.aborted()).toBe(true); +}); + +test("diagnostics identifies its loaded package and expands the captured report through existing hooks", async () => { + const f = createHost(); + const c = commandFixture(f); + const prime = mock(async () => "PRIME"); + const cleanup = await setupBeads(f.ctx, { + warn: () => {}, + runtime: { guard: async () => ({ kind: "ready" }), prime }, + }); + try { + await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); + const sent = c.prompt.mock.calls.at(-1)![0]; + const metadata = sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }; + const snapshot = metadata.ocBeadsWorkflow; + const report = JSON.parse(snapshot.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + const manifest = await Bun.file(new URL("../package.json", import.meta.url)).json(); + expect(report.plugin).toEqual({ name: manifest.name, version: manifest.version }); + expect(report.host).toBe("2.3.0"); + expect(snapshot.instructions).toContain(`DATE: \`${report.capturedAt}\``); + expect(snapshot.instructions).toContain(`VERSION: ${manifest.name} \`${manifest.version}\``); + expect(snapshot.instructions).toContain("PATH: `not observed`"); + expect(prime).not.toHaveBeenCalled(); + const stored = storedUserMessage("diagnostics-message", String(sent.text), { ocBeadsWorkflow: snapshot }); + const request = Message.make({ id: stored.id, role: "user", content: String(sent.text) }); + const raw = JSON.stringify(stored); + const context = mock(async () => [stored]); + Object.assign(f.ctx.session, { context }); + for (const kind of ["context", "compaction"] as const) { + const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [Message.make(request)] }; + await f.hooks.get(kind)!(event); + expect(event.messages![0]!.content[0]).toEqual({ type: "text", text: snapshot.instructions }); + expect(JSON.stringify(event.messages)).not.toContain("ocBeadsWorkflow"); + expect(JSON.stringify(event.messages).split(snapshot.instructions.split("\n")[0]!)).toHaveLength(2); + } + for (const kind of ["title", "generate"]) { + const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [Message.make(request)] }; + await f.hooks.get(kind)?.(event); + expect(JSON.stringify(event.messages!.map((message) => message.content))).not.toContain( + "Reproduce only the finished Markdown", + ); + } + expect(JSON.stringify(stored)).toBe(raw); + expect(c.prompt).toHaveBeenCalledTimes(1); + } finally { + await cleanup(); + } +}); + +test("diagnostics overrides restore natively and user-owned old status survives package removal", async () => { + const f = createHost(); + const c = commandFixture(f); + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + expect(c.commands().size).toBe(30); + expect(c.commands().has("oc-beads:status")).toBe(false); + const diagnostics = c.commands().get("oc-beads:diagnostics")!; + expect(diagnostics.description).toContain("strict-readonly store access"); + expect(diagnostics.description).toContain("configured database"); + expect(diagnostics.description).toContain("All selectors skip remote history fetches"); + const oldStatus = { name: "oc-beads:status", description: "USER OLD STATUS", execute: mock(async () => {}) }; + const override = { ...diagnostics, description: "USER DIAGNOSTICS", execute: mock(async () => {}) }; + const oldConfig = (editor: { add(definition: CommandDefinition): void }) => editor.add(oldStatus); + const newConfig = (editor: { add(definition: CommandDefinition): void }) => editor.add(override); + c.callbacks.push(oldConfig, newConfig); + expect(c.commands().get(diagnostics.name)).toBe(override); + await c.commands().get(diagnostics.name)!.execute(c.invocation); + expect(override.execute).toHaveBeenCalledTimes(1); + c.callbacks.splice(c.callbacks.indexOf(newConfig), 1); + expect(c.commands().get(diagnostics.name)).toBe(diagnostics); + expect(c.commands().get(oldStatus.name)).toBe(oldStatus); + await c.commands().get(oldStatus.name)!.execute(c.invocation); + expect(oldStatus.execute).toHaveBeenCalledTimes(1); + await c.commands().get("oc-beads:stats")!.execute(c.invocation); + const statsMetadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + expect(statsMetadata.ocBeadsWorkflow.instructions).toContain( + "issue-database overview using bd status (alias bd stats)", + ); + expect(statsMetadata.ocBeadsWorkflow.instructions).toContain("Supporting guidance:"); + await cleanup(); + expect(c.commands().get(oldStatus.name)).toBe(oldStatus); + expect(c.commands().has(diagnostics.name)).toBe(false); +}); + +test("registers after an initial lookup failure and reports observable mismatches, missing names and ownership blind spots", async () => { + const f = createHost(); + const c = commandFixture(f); + c.failLookup(true); + const cleanup = await setupBeads(f.ctx, { warn: () => {}, runtime: { guard: async () => ({ kind: "ready" }) } }); + expect(c.transform).toHaveBeenCalledTimes(1); + c.failLookup(false); + const ready = c.commands().get("oc-beads:ready")!; + const diagnostics = c.commands().get("oc-beads:diagnostics")!; + const report = async () => { + await diagnostics.execute(c.detailsInvocation); + const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; + return JSON.parse(metadata.ocBeadsWorkflow.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); + }; + let observed = await report(); + expect(observed.commands.registration).toBe("registered"); + expect(observed.commands.lookup).toBe("available"); + expect(observed.commands.ownership).toContain("unavailable"); + expect(observed.commands.ownership).toContain("identical-description"); + expect(observed.commands.ownership).toContain("do not prove ownership"); + c.callbacks.push((editor) => editor.add({ ...ready, description: "USER DESCRIPTION" })); + observed = await report(); + expect(observed.commands.mismatches).toContainEqual({ + name: ready.name, + expectedDescription: ready.description, + effectiveDescription: "USER DESCRIPTION", + }); + expect(observed.commands.effective).toContainEqual({ name: ready.name, description: "USER DESCRIPTION" }); + c.callbacks.push((editor) => editor.add({ ...ready, execute: async () => {} })); + expect((await report()).commands.mismatches).toEqual([]); + c.omit("oc-beads:show"); + expect((await report()).commands.missing).toEqual(["oc-beads:show"]); + c.failLookup(true); + observed = await report(); + expect(observed.commands.lookup).toBe("failed"); + expect(observed.commands.effective).toBe("unknown: registry lookup failed"); + expect(observed.commands.mismatches).toBeUndefined(); + await cleanup(); +}); + +test("skill checks each candidate without an initial list gate and restores a disappearing override", async () => { + const f = createHost(); + type Skill = { id: string; name: string; path: string; content: string }; + const custom = { id: "oc-beads", name: "oc-beads", path: "/user/SKILL.md", content: "USER" }; + let before: Skill | undefined = custom; + let after: Skill | undefined; + const skills = new Map<string, Skill>(); + const callbacks: Array<(editor: unknown) => void> = []; + const rebuild = () => { + skills.clear(); + if (before) skills.set(before.id, before); + const editor = { list: () => [...skills.values()], add: (skill: Skill) => skills.set(skill.id, skill) }; + for (const callback of callbacks) callback(editor); + if (after) skills.set(after.id, after); + }; + const list = mock(async () => { + throw new Error("setup must not gate on list"); + }); + Object.assign(f.ctx, { + skill: { + list, + transform: async (callback: (editor: unknown) => void) => { + callbacks.push(callback); + rebuild(); + return { + dispose: async () => { + callbacks.splice(callbacks.indexOf(callback), 1); + rebuild(); + }, + }; + }, + }, + }); + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + expect(list).not.toHaveBeenCalled(); + expect(callbacks).toHaveLength(1); + expect(skills.get("oc-beads")).toBe(custom); + before = undefined; + rebuild(); + expect(skills.get("oc-beads")?.content).toContain("Beads work in OpenCode"); + after = custom; + rebuild(); + expect(skills.get("oc-beads")).toBe(custom); + after = undefined; + rebuild(); + expect(skills.get("oc-beads")?.content).toContain("Beads work in OpenCode"); + const callback = callbacks[0]!; + after = custom; + await cleanup(); + expect(skills.get("oc-beads")).toBe(custom); + const add = mock((_skill: Skill) => {}); + callback({ list: () => [], add }); + expect(add).not.toHaveBeenCalled(); +}); diff --git a/tests/host-workflow-replay.test.ts b/tests/host-workflow-replay.test.ts new file mode 100644 index 0000000..92fe48c --- /dev/null +++ b/tests/host-workflow-replay.test.ts @@ -0,0 +1,292 @@ +import { Message } from "@opencode/ai/effect"; +import { expect, mock, test } from "bun:test"; +import { setupBeads } from "../src/host"; +import type { SessionContext } from "@opencode/plugin/promise/session"; +import { BEADS_COMPACTION_GUIDANCE } from "../src/guidance"; +import { + type ContextEvent, + type StoredSessionMessage, + storedUserMessage, + createHost, + sessionInfo, +} from "./host-fixture"; +import { commandFixture } from "./host-command-fixture"; + +test("registered mixed workflow and legacy hooks expand replay once before location/eligibility returns", async () => { + const f = createHost(); + const c = commandFixture(f); + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + const update = c.commands().get("oc-beads:update")!; + const stored: StoredSessionMessage[] = []; + const projected: SessionContext["messages"] = []; + const context = mock(async () => stored); + Object.assign(f.ctx.session, { context }); + for (const [stem, text, delivery] of [ + ["show", "fixture-1", "queue"], + ["update", "append note", "steer"], + ["compact", "explain --auto", "queue"], + ["sync", "explain only", "steer"], + ] as const) { + await c + .commands() + .get(`oc-beads:${stem}`)! + .execute({ ...c.invocation, delivery, prompt: { ...c.invocation.prompt, text } }); + const sent = c.prompt.mock.calls.at(-1)![0]; + expect(sent.text).toBe(`/oc-beads:${stem} ${text}`); + expect(sent.files).toBe(c.invocation.prompt.files); + expect(sent.delivery).toBe(delivery); + const workflow = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }).ocBeadsWorkflow; + const messageID = `workflow-${stem}`; + stored.push( + storedUserMessage( + messageID, + String(sent.text), + stem === "sync" ? { ocBeadsSync: workflow } : { ocBeadsWorkflow: workflow }, + ), + ); + projected.push( + Message.make({ + id: messageID, + role: "user", + content: [Message.text(String(sent.text)), Message.text("native prepared attachment/skill + hook edit")], + }), + ); + } + expect(c.prompt).toHaveBeenCalledTimes(4); + const raw = JSON.stringify(projected); + const storedRaw = JSON.stringify(stored); + for (const kind of ["context", "compaction"] as const) { + const event = { + sessionID: "s1", + agent: "build", + system: [], + messages: projected.map((message) => Message.make(message)), + } as ContextEvent; + await f.hooks.get(kind)!(event); + const once = JSON.stringify(event.messages); + expect(once).not.toContain("ocBeadsSync"); + expect(once).not.toContain("ocBeadsWorkflow"); + expect(once.match(/Invoked command: \/oc-beads:/g)).toHaveLength(4); + expect(once).toContain("With sufficient inputs, perform the requested operation"); + await f.hooks.get(kind)!(event); + expect(JSON.stringify(event.messages)).toBe(once); + expect(event.messages![1]!.content).toContainEqual({ type: "text", text: "/oc-beads:update append note" }); + } + expect(context).toHaveBeenCalledTimes(4); + // A moved session is withheld before native snapshot lookup. + Object.assign(f.ctx.session, { get: async () => sessionInfo("/elsewhere") }); + const moved = { + sessionID: "s1", + agent: "build", + system: [], + messages: projected.map((message) => Message.make(message)), + } as ContextEvent; + await f.hooks.get("context")!(moved); + expect(JSON.stringify(moved.messages)).not.toContain("Requested outcome:"); + expect(JSON.stringify(moved.system)).toContain("Saved Beads workflow instructions or diagnostics are unavailable"); + expect(context).toHaveBeenCalledTimes(4); + expect(JSON.stringify(stored)).toBe(storedRaw); + expect([...f.hooks.keys()].sort()).toEqual(["compaction", "context"]); + // Summary recent-context uses stored visible text; no promise of verbatim snapshot retention. + const recent = stored + .filter((message) => message.type === "user") + .map((message) => message.text) + .join("\n"); + expect(recent).not.toContain("Requested outcome:"); + expect(BEADS_COMPACTION_GUIDANCE).toContain( + "active /oc-beads workflow invocation's requested outcome, unresolved inputs or explicit modes, and applicable authority limits", + ); + const calls = c.prompt.mock.calls.length; + await cleanup(); + const unloaded = { + sessionID: "s1", + agent: "build", + system: [], + messages: projected.map((message) => Message.make(message)), + } as ContextEvent; + await f.hooks.get("context")!(unloaded); + expect(JSON.stringify(unloaded.messages)).toBe(raw); + await expect(update.execute(c.invocation)).rejects.toThrow("unloaded"); + expect(c.prompt).toHaveBeenCalledTimes(calls); +}); + +test("restores a saved workflow by ID from native context after the SDK projects a metadata-free user message", async () => { + const f = createHost({ appVersion: "2.3.0" }); + const c = commandFixture(f); + const order: string[] = []; + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + await c + .commands() + .get("oc-beads:show")! + .execute({ + ...c.invocation, + delivery: "queue", + prompt: { ...c.invocation.prompt, text: "fixture-1 --json" }, + }); + const sent = c.prompt.mock.calls.at(-1)![0]; + const workflow = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }).ocBeadsWorkflow; + const messageID = "workflow-message-1"; + const get = mock(async () => { + order.push("location"); + return { location: { directory: "/project" } }; + }); + const context = mock(async ({ sessionID }: { sessionID: string }) => { + order.push("context"); + expect(sessionID).toBe(c.invocation.sessionID); + return [ + { + id: messageID, + type: "user" as const, + time: { created: 1 }, + text: String(sent.text), + metadata: { ocBeadsWorkflow: workflow }, + }, + ]; + }); + Object.assign(f.ctx.session, { get, context }); + + const projected = Message.make({ id: messageID, role: "user", content: String(sent.text) }); + expect(projected.role).toBe("user"); + expect(Object.hasOwn(projected, "metadata")).toBeFalse(); + const event: ContextEvent = { + sessionID: c.invocation.sessionID, + agent: "build", + system: [], + messages: [projected], + }; + await f.hooks.get("context")!(event); + + expect(order).toEqual(["location", "context"]); + expect(context).toHaveBeenCalledTimes(1); + expect(event.messages?.[0]?.content[0]).toEqual(Message.text(workflow.instructions)); + expect(event.messages?.[0]?.content[1]).toEqual(Message.text(String(sent.text))); + expect(c.prompt.mock.calls.at(-1)![0].delivery).toBe("queue"); + await cleanup(); +}); + +test("reports unavailable snapshots after a rejected or incomplete native read without re-admission", async () => { + for (const result of ["rejected", "missing"] as const) { + const f = createHost(); + const c = commandFixture(f); + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + await c.commands().get("oc-beads:show")!.execute(c.invocation); + const message = Message.make({ id: `missing-${result}`, role: "user", content: "/oc-beads:show fixture-1" }); + const context = mock(async () => { + if (result === "rejected") throw new Error("fixture native read rejected"); + return []; + }); + Object.assign(f.ctx.session, { context }); + const before = JSON.stringify(message.content); + const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [message] }; + const promptCount = c.prompt.mock.calls.length; + await f.hooks.get("context")!(event); + expect(JSON.stringify(event.messages?.[0]?.content)).toBe(before); + expect(JSON.stringify(event.system)).toContain("Saved Beads workflow instructions or diagnostics are unavailable"); + expect(context).toHaveBeenCalledTimes(1); + expect(c.prompt).toHaveBeenCalledTimes(promptCount); + await cleanup(); + } +}); + +test("overlapping snapshot reads share a lifecycle while actual invalidations reject late results", async () => { + for (const seam of ["get", "context"] as const) + for (const action of [ + "context", + "compaction", + "session.moved", + "session.deleted", + "session.forked", + "unload", + ] as const) { + const f = createHost(); + commandFixture(f); + const stored = storedUserMessage("overlap", "/oc-beads:show fixture", { + ocBeadsWorkflow: { version: 1, instructions: "SAVED OVERLAP" }, + }); + Object.assign(f.ctx.session, { context: async () => [stored] }); + const cleanup = await setupBeads(f.ctx, { + warn: () => {}, + runtime: { + guard: async () => ({ kind: "ready", version: "1.3.4", workspace: { path: "/project/.beads" } }), + prime: async () => "PRIME FIXTURE", + }, + }); + const event = (): ContextEvent => ({ + sessionID: "s1", + agent: "build", + system: [], + messages: [Message.make({ id: "overlap", role: "user", content: stored.text })], + }); + await f.hooks.get("context")!(event()); + const readStarted = Promise.withResolvers<void>(); + const finishRead = Promise.withResolvers<void>(); + let firstRead = true; + function delayFirstRead<Input, Result>(read: (input: Input) => Promise<Result>) { + return (input: Input) => { + if (!firstRead) return read(input); + firstRead = false; + readStarted.resolve(); + return finishRead.promise.then(() => read(input)); + }; + } + const { get, context } = f.ctx.session; + if (seam === "get") Object.assign(f.ctx.session, { get: delayFirstRead(get!) }); + else Object.assign(f.ctx.session, { context: delayFirstRead(context) }); + const firstKind = action === "context" ? "compaction" : "context"; + const first = event(); + const pending = f.hooks.get(firstKind)!(first); + await readStarted.promise; + if (action === "context" || action === "compaction") { + const second = event(); + await f.hooks.get(action)!(second); + expect(JSON.stringify(second.messages)).toContain("SAVED OVERLAP"); + expect(JSON.stringify(second.system)).toContain(action === "context" ? "<beads-context" : "<beads-compaction>"); + } else if (action === "unload") await cleanup(); + else { + await f.events.emit({ type: action, data: { sessionID: "s1" } }); + } + finishRead.resolve(); + await pending; + const valid = action === "context" || action === "compaction"; + expect(JSON.stringify(first.messages).includes("SAVED OVERLAP")).toBe(valid); + if (valid) + expect(JSON.stringify(first.system)).toContain( + firstKind === "context" ? "<beads-context" : "<beads-compaction>", + ); + else if (action !== "unload") + expect(JSON.stringify(first.system)).toContain( + "Saved Beads workflow instructions or diagnostics are unavailable", + ); + await cleanup(); + } +}); + +test("discards a late native snapshot after session generation changes", async () => { + const f = createHost(); + commandFixture(f); + const messageID = "moving-workflow"; + const stored = storedUserMessage(messageID, "/oc-beads:show fixture-1", { + ocBeadsWorkflow: { version: 1, instructions: "STALE SNAPSHOT" }, + }); + const readStarted = Promise.withResolvers<void>(); + const snapshot = Promise.withResolvers<StoredSessionMessage[]>(); + const context = mock(() => { + readStarted.resolve(); + return snapshot.promise; + }); + Object.assign(f.ctx.session, { context }); + const cleanup = await setupBeads(f.ctx, { warn: () => {} }); + const message = Message.make({ id: messageID, role: "user", content: stored.text }); + const before = JSON.stringify(message.content); + const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [message] }; + const pending = f.hooks.get("context")!(event); + await readStarted.promise; + await f.events.emit({ type: "session.moved", data: { sessionID: "s1" } }); + snapshot.resolve([stored]); + await pending; + expect(JSON.stringify(event.messages?.[0]?.content)).toBe(before); + expect(JSON.stringify(event.system)).toContain("Saved Beads workflow instructions or diagnostics are unavailable"); + expect(JSON.stringify(event.messages)).not.toContain("STALE SNAPSHOT"); + expect(context).toHaveBeenCalledTimes(1); + await cleanup(); +}); diff --git a/tests/host-write-recovery.test.ts b/tests/host-write-recovery.test.ts new file mode 100644 index 0000000..f3b1705 --- /dev/null +++ b/tests/host-write-recovery.test.ts @@ -0,0 +1,223 @@ +import { expect, mock, test } from "bun:test"; +import { setupBeads } from "../src/host"; +import type { ContinuityHost } from "../src/continuity"; +import { Error as ToolError, type Info, type ToolContext } from "@opencode/plugin/promise/tool"; +import { executorActor } from "../src/continuity"; +import { type ContextEvent, createHost, toolFixture, nonCodeMode, invocation, sessionInfo } from "./host-fixture"; + +test("normal adapter writes invalidate location caches once and compaction only carries acknowledged references/gaps", async () => { + const f = createHost(); + const tools: Info[] = []; + let after: (event: any) => unknown = () => {}; + const disposed = mock(async () => {}); + Object.assign(f.ctx, { + tool: { + hook: async (_name: string, callback: typeof after) => { + after = callback; + return { dispose: disposed }; + }, + }, + }); + const host = { + location: { directory: "/project", project: { directory: "/project" } }, + permission: { assert: mock(async () => {}) }, + session: { get: async () => sessionInfo("/project") }, + tool: { + transform: async (callback: (editor: { namespace(input: unknown): void; add(tool: Info): void }) => void) => { + callback({ namespace: () => {}, add: (tool) => tools.push(tool) }); + return { dispose: disposed }; + }, + }, + } as unknown as ContinuityHost & { tool: { transform: any } }; + let output = "BEFORE"; + const prime = mock(async () => output); + const acknowledged = mock(() => {}); + const bd = mock(async (_cwd: string, args: readonly string[]) => { + if (args[0] === "version") return "1.3.1"; + if (args[0] === "context") + return '{"beads_dir":"/project/.beads","backend":"dolt","dolt_mode":"embedded","database":"beads"}'; + return '{"key":"lesson","value":"validated finding","action":"remembered","committed":false,"commit_error":"not committed"}'; + }); + Object.assign(f.ctx, { + location: host.location, + permission: host.permission, + tool: { ...f.ctx.tool, ...host.tool }, + }); + Object.assign(f.ctx.session, host.session); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" }), prime }, + continuityQualified: true, + continuity: { + bd, + acknowledged, + realpath: async (path) => path, + }, + }); + await f.request("s1", "build"); + await f.request("s2", "build"); + const tool = tools.find((tool) => tool.name === "remember")!; + const context = { + sessionID: "s1", + agent: "worker", + messageID: "m1", + id: "c1", + signal: new AbortController().signal, + progress: async () => {}, + } as unknown as ToolContext; + const result = await tool.execute({ key: "lesson", text: "validated finding" }, context); + await after({ ...context, tool: "beads_remember", status: "completed", result }); + await after({ ...context, tool: "execute", status: "completed", result }); + expect(acknowledged).toHaveBeenCalledTimes(1); + expect(bd.mock.calls.filter(([, args]) => args[0] === "remember")).toHaveLength(1); + output = "AFTER"; + expect((await f.request("s2", "build"))[0]).toContain("AFTER"); + const count = bd.mock.calls.length; + const event: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; + await f.hooks.get("compaction")!(event); + expect(event.system[1]?.text).toContain("memory:lesson"); + expect(event.system[1]?.text).toContain("landed-uncommitted"); + expect(bd).toHaveBeenCalledTimes(count); + await cleanup(); + expect(disposed).toHaveBeenCalledTimes(2); +}); + +test("retains unresolved write identities across partial reads, interruption and recovery", async () => { + const f = createHost(); + const t = toolFixture(f); + const stopped = new AbortController(); + const writer = invocation("s1", "build", stopped.signal); + const otherWriter = invocation("s1", "worker"); + const writeStarted = Promise.withResolvers<void>(); + const finishWrite = Promise.withResolvers<string>(); + const bd = mock(async (_cwd: string, args: readonly string[]) => { + if (args[0] === "version") return "1.3.1"; + if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; + if (args[0] === "update" && args[3] === "started note") { + writeStarted.resolve(); + return finishWrite.promise; + } + if (args[0] === "update") return JSON.stringify([{ id: args[1], notes: args[3] }]); + if (args[0] === "remember") + return JSON.stringify({ + key: "lesson-uncommitted", + value: "finding", + action: "remembered", + committed: false, + commit_error: "fixture commit failed", + }); + if (args[0] === "list") + return JSON.stringify( + ["read-1", "read-2"].map((id) => ({ id, title: id, status: "open", priority: 2, issue_type: "task" })), + ); + throw new Error("fixture read failed"); + }); + Object.assign(f.ctx, { + location: { directory: "/project", project: { directory: "/project" } }, + permission: { assert: async () => {} }, + }); + Object.assign(f.ctx.session, { get: async () => sessionInfo("/project") }); + const cleanup = await setupBeads(f.ctx, { + continuityQualified: true, + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, + continuity: { bd, realpath: async (p) => p }, + }); + try { + await f.request("s1", "build"); + const interrupted = t.tools + .find((tool) => tool.name === "note")! + .execute({ id: "task-first", text: "started note" }, writer); + await writeStarted.promise; + stopped.abort(new Error("fixture write interrupted")); + finishWrite.reject(stopped.signal.reason); + await expect(interrupted).rejects.toThrow("fixture write interrupted"); + expect( + ( + await t.tools + .find((tool) => tool.name === "remember")! + .execute({ key: "lesson-uncommitted", text: "finding" }, otherWriter) + ).output.status, + ).toBe("landed-uncommitted"); + const read = invocation("s1", "build"); + expect( + (await t.tools.find((tool) => tool.name === "find")!.execute({ view: "list", limit: 1 }, read)).output, + ).toMatchObject({ status: "acknowledged", complete: false }); + expect( + (await t.tools.find((tool) => tool.name === "get")!.execute({ ids: ["unavailable-task"] }, read)).output.status, + ).toBe("failed"); + // Even a later acknowledged write to the same target does not resolve the earlier append. + expect( + (await t.tools.find((tool) => tool.name === "note")!.execute({ id: "task-first", text: "later note" }, read)) + .output.status, + ).toBe("acknowledged"); + await f.events.emit({ type: "session.execution.interrupted", data: { sessionID: "s1" } }); + const summary: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; + const beforeCompaction = bd.mock.calls.length; + await f.hooks.get("compaction")!(summary); + expect(bd).toHaveBeenCalledTimes(beforeCompaction); + const gap = JSON.parse(summary.system[1]!.text.replace(/^<beads-references>|<\/beads-references>$/g, "")).gap; + const expected = [ + `note "task-first" actor=${executorActor(writer)}: uncertain; fixture write interrupted`, + `remember "lesson-uncommitted" actor=${executorActor(otherWriter)}: landed-uncommitted`, + ]; + const recovery = (await f.request("s1", "build")).join("\n"); + const later = (await f.request("s1", "build")).join("\n"); + for (const detail of expected) { + expect(gap).toContain(detail); + expect(recovery).toContain(detail); + expect(later).toContain(detail); + } + expect(gap).toContain("no final checkpoint is guaranteed"); + expect(bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(2); + expect(bd.mock.calls.filter(([, args]) => args[0] === "remember")).toHaveLength(1); + expect((await f.request("other-session", "build")).join("\n")).not.toContain("task-first"); + await f.events.emit({ type: "session.moved", data: { sessionID: "s1" } }); + expect((await f.request("s1", "build")).join("\n")).not.toContain("lesson-uncommitted"); + } finally { + await cleanup(); + } +}); + +test("acknowledged task writes retain task references without a redundant cue; unrelated errors do not refresh prime", async () => { + const f = createHost(); + const t = toolFixture(f); + const prime = mock(async () => "PRIME"); + Object.assign(f.ctx, { + location: { directory: "/project", project: { directory: "/project" } }, + permission: { assert: async () => {} }, + }); + Object.assign(f.ctx.session, { get: async () => sessionInfo("/project") }); + const cleanup = await setupBeads(f.ctx, { + continuityQualified: true, + runtime: { guard: async () => ({ kind: "ready" }), prime }, + continuity: { + realpath: async (p) => p, + bd: async (_cwd, args) => + args[0] === "version" + ? "1.3.1" + : args[0] === "context" + ? '{"beads_dir":"/project/.beads"}' + : '[{"id":"task-1","notes":"evidence"}]', + }, + }); + await f.request("s1", "build"); + await t.after({ + ...invocation("s1", "build"), + ...nonCodeMode, + tool: "shell", + input: {}, + status: "error", + error: new ToolError({ message: "test failed" }), + }); + expect(await f.request("s1", "build")).toHaveLength(1); + expect(prime).toHaveBeenCalledTimes(1); + await t.tools + .find((tool) => tool.name === "note")! + .execute({ id: "task-1", text: "evidence" }, invocation("s1", "build")); + expect(await f.request("s1", "build")).toHaveLength(1); + expect(prime).toHaveBeenCalledTimes(2); + const event: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; + await f.hooks.get("compaction")!(event); + expect(event.system[1]?.text).toContain("task:task-1"); + expect(event.system[1]?.text).not.toContain("memory:task-1"); + await cleanup(); +}); diff --git a/tests/host.test.ts b/tests/host.test.ts index 0be7596..93242ad 100644 --- a/tests/host.test.ts +++ b/tests/host.test.ts @@ -1,3336 +1,172 @@ -import { Effect } from "effect"; -import { fromRequest as serializeChatRequest } from "@opencode/ai/protocols/openai-chat"; -import { createHash } from "node:crypto"; -import { make } from "@opencode/ai"; -import { Message } from "@opencode/ai/effect"; -import { configure } from "@opencode/ai/providers/openai"; -import baseline from "./fixtures/non-sync-command-baseline.json"; -import { describe, expect, mock, test } from "bun:test"; -import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import path from "node:path"; +import { expect, mock, test } from "bun:test"; import * as pluginModule from "../src/plugin"; import { renderBeadsContext } from "../src/context"; -import { setupBeads, type HostContext } from "../src/host"; -import type { CommandDefinition, CommandInvocation } from "@opencode/plugin/promise/command"; -import type { ContinuityHost } from "../src/continuity"; -import { Error as ToolError, type Info, type ToolContext, type ToolDomain } from "@opencode/plugin/promise/tool"; -import type { SessionContext, SessionCompaction } from "@opencode/plugin/promise/session"; -import { executorActor } from "../src/continuity"; -import { PrimeProcessError, PrimeTimeoutError } from "../src/prime"; -import { renderHealthReport, type DiagnosticsSnapshot } from "../src/diagnostics"; -import * as diagnosticPresentation from "../src/diagnostics"; -import type { PluginHealthObservation } from "../src/diagnostics-collection"; +import { setupBeads } from "../src/host"; +import { renderHealthReport } from "../src/diagnostics"; import { DEFAULT_TASK_AGENT_STEPS, TASK_AGENT_PERMISSIONS } from "../src/agents"; -import { BEADS_COMPACTION_GUIDANCE, primeFailureNotice } from "../src/guidance"; +import { createHost, toolFixture, sessionInfo } from "./host-fixture"; +import { presentationFixture } from "./host-diagnostic-fixture"; -type ContextEvent = { - messages?: SessionContext["messages"]; - tools?: Record<string, unknown>; - sessionID: string; - agent: string; - system: Array<{ type: "text"; text: string }>; -}; -type ToolAfterEvent = Extract<Parameters<Parameters<ToolDomain["hook"]>[1]>[0], { status: string }>; -type StoredSessionMessage = Awaited<ReturnType<HostContext["session"]["context"]>>[number]; -type StoredUserMessage = Extract<StoredSessionMessage, { type: "user" }>; - -function storedUserMessage(id: string, text: string, metadata?: StoredUserMessage["metadata"]): StoredUserMessage { - return { id, type: "user", time: { created: 1 }, text, ...(metadata === undefined ? {} : { metadata }) }; -} - -/** A controllable server event stream. */ -function eventStream() { - const queue: unknown[] = []; - let wake: () => void = () => {}; - let signal: AbortSignal | undefined; - async function* subscribe(input?: { signal?: AbortSignal }) { - signal = input?.signal; - while (!signal?.aborted) { - const next = queue.shift(); - if (next !== undefined) { - yield next; - continue; - } - await new Promise<void>((resolve) => { - wake = resolve; - signal?.addEventListener("abort", () => resolve(), { once: true }); - }); - } - } - return { - subscribe, - push(event: unknown) { - queue.push(event); - wake(); - }, - aborted: () => signal?.aborted === true, - }; -} - -async function settle(): Promise<void> { - for (let index = 0; index < 5; index++) await new Promise((resolve) => setTimeout(resolve, 0)); -} - -function fakeContext( - options: { - directory?: string; - pluginOptions?: Record<string, unknown>; - appVersion?: string; - } = {}, -) { - const hooks = new Map<string, (event: ContextEvent) => Promise<void> | void>(); - const events = eventStream(); - const agentGet = mock(async ({ agentID }: { agentID: string }) => ({ - data: { id: agentID, mode: agentID === "explore" ? "subagent" : "primary" }, - })); - // Mirrors OpenCode: update() on an unknown ID starts from defaults. - const agents = new Map<string, Record<string, unknown>>(); - const editor = { - update(id: string, update: (agent: Record<string, unknown>) => void) { - const agent = agents.get(id) ?? { id, name: id, mode: "primary", hidden: false, permissions: [] }; - update(agent); - agents.set(id, agent); - }, - }; - const agentTransform = mock(async (callback: (input: typeof editor) => void) => { - callback(editor); - return { dispose: async () => {} }; - }); - const ctx = { - app: { name: "OpenCode", version: options.appVersion ?? "2.3.0", channel: "stable" }, - location: { directory: options.directory ?? "/project" }, - options: options.pluginOptions ?? {}, - event: { subscribe: events.subscribe }, - agent: { get: agentGet, transform: agentTransform }, - session: { - context: mock(async () => []), - hook: mock(async (name: string, callback: (event: ContextEvent) => void) => { - hooks.set(name, (event) => { - event.messages ??= []; - return callback(event); - }); - return { dispose: async () => {} }; - }), - }, - } as unknown as HostContext; - - async function request(sessionID: string, agent: string, tools?: Record<string, unknown>): Promise<string[]> { - const event: ContextEvent = { - sessionID, - agent, - ...(tools ? { tools } : {}), - system: [{ type: "text", text: "HOST" }], - }; - const hook = hooks.get("context"); - if (!hook) throw new Error("context hook not registered"); - await hook(event); - return event.system.slice(1).map((part) => part.text); - } - - return { ctx, hooks, events, agentGet, agents, request }; -} - -/** Capture public hook/registration callbacks, without simulating host child transport. */ -function toolFixture(f: ReturnType<typeof fakeContext>) { - const tools: Info[] = []; - const namespaces: unknown[] = []; - let after: (event: ToolAfterEvent) => Promise<void> | void = () => {}; - const hook: ToolDomain["hook"] = async (name, callback) => { - if (name === "execute.after") after = callback as typeof after; - return { dispose: async () => {} }; - }; - const transform: ToolDomain["transform"] = async (callback) => { - callback({ - namespace: (value: unknown) => { - namespaces.push(value); - }, - add: (tool: Info) => { - tools.push(tool); - }, - } as unknown as Parameters<typeof callback>[0]); - return { dispose: async () => {} }; - }; - Object.assign(f.ctx, { tool: { hook, transform } }); - return { tools, namespaces, after: (event: ToolAfterEvent) => after(event) }; -} - -// The 2.4 SDK requires codemode; the 2.3 SDK does not declare it. -const nonCodeMode = { codemode: false }; - -/** Cast only host-branded IDs at the fixture boundary. */ -function invocation(sessionID: string, agent: string, signal = new AbortController().signal): ToolContext { - return { - sessionID, - agent, - messageID: `message-${sessionID}`, - id: `call-${sessionID}`, - signal, - progress: async () => {}, - } as unknown as ToolContext; -} - -describe("OpenCode V2 entry", () => { - test("default-exports a V2 plugin definition and nothing else", () => { - expect(Object.keys(pluginModule)).toEqual(["default"]); - expect(pluginModule.default.id).toBe("opencode-beads"); - expect(typeof pluginModule.default.setup).toBe("function"); - }); +test("default-exports a V2 plugin definition and nothing else", () => { + expect(Object.keys(pluginModule)).toEqual(["default"]); + expect(pluginModule.default.id).toBe("opencode-beads"); + expect(typeof pluginModule.default.setup).toBe("function"); }); -describe("public beta entrypoint", () => { - test("does not register typed operations when native permission or session interfaces are unavailable", async () => { - for (const missing of ["permission", "session"]) { - const f = fakeContext(); - const t = toolFixture(f); - if (missing === "session") Object.assign(f.ctx, { permission: { assert: async () => {} } }); - else Object.assign(f.ctx.session, { get: async () => ({ location: { directory: "/project" } }) }); - const cleanup = await pluginModule.default.setup(f.ctx as Parameters<typeof pluginModule.default.setup>[0]); - expect(t.tools).toEqual([]); - await cleanup!(); - } - }); - - test("registers the eleven code-mode operations without injected dependencies and disposes owned tools", async () => { - const f = fakeContext(); - const tools: Info[] = []; - const namespaces: unknown[] = []; - const dispose = mock(async () => {}); - Object.assign(f.ctx, { - permission: { assert: async () => {} }, - tool: { - hook: async () => ({ dispose }), - transform: async (callback: Parameters<ToolDomain["transform"]>[0]) => { - callback({ - list: () => [], - get: () => undefined, - update: () => {}, - remove: () => {}, - namespace: (namespace) => { - namespaces.push(namespace); - }, - add: (tool) => { - tools.push(tool); - }, - }); - return { dispose }; - }, - }, - }); - Object.assign(f.ctx.session, { get: async () => ({ location: { directory: "/project" } }) }); +test("does not register typed operations when native permission or session interfaces are unavailable", async () => { + for (const missing of ["permission", "session"]) { + const f = createHost(); + const t = toolFixture(f); + if (missing === "session") Object.assign(f.ctx, { permission: { assert: async () => {} } }); + else Object.assign(f.ctx.session, { get: async () => sessionInfo("/project") }); const cleanup = await pluginModule.default.setup(f.ctx as Parameters<typeof pluginModule.default.setup>[0]); - expect(namespaces).toEqual([expect.objectContaining({ name: "beads" })]); - expect(tools.map((tool) => tool.name).sort()).toEqual( - ["find", "get", "edges", "memories", "recall", "claim", "note", "update", "close", "create", "remember"].sort(), - ); - expect(tools.every((tool) => tool.options?.codemode === true && tool.options.namespace === "beads")).toBeTrue(); + expect(t.tools).toEqual([]); await cleanup!(); - expect(dispose).toHaveBeenCalledTimes(2); - }); -}); - -describe("setupBeads", () => { - test("refreshes recovery state for external changes, isolates fork/move/audience and never restarts on interruption", async () => { - const f = fakeContext(); - let directory = "/project"; - let output = "FIRST"; - Object.assign(f.ctx.session, { get: async () => ({ location: { directory } }) }); - const prime = mock(async () => output); - const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); - await f.request("s1", "build"); - await f.request("s10", "build"); - output = "EXTERNAL CHANGE"; - f.events.push({ type: "session.execution.started", data: { sessionID: "s1" } }); - await settle(); - const recovered = await f.request("s1", "build"); - expect(recovered[0]).toContain("EXTERNAL CHANGE"); - expect(recovered[1]).toContain("Cached absence is not proof of absence"); - expect((await f.request("s10", "build"))[0]).toContain("FIRST"); - expect((await f.request("fork", "build"))[0]).toContain("EXTERNAL CHANGE"); - const hidden: ContextEvent = { sessionID: "s1", agent: "explore", system: [] }; - await f.hooks.get("compaction")!(hidden); - expect(hidden.system).toEqual([]); - f.events.push({ type: "session.execution.interrupted", data: { sessionID: "s1" } }); - await settle(); - const count = prime.mock.calls.length; - await settle(); - expect(prime).toHaveBeenCalledTimes(count); - directory = "/elsewhere"; - f.events.push({ type: "session.moved", data: { sessionID: "s1" } }); - await settle(); - expect(await f.request("s1", "build")).toEqual([]); - expect(prime).toHaveBeenCalledTimes(count); - cleanup(); - }); - - test("normal adapter writes invalidate location caches once and compaction only carries acknowledged references/gaps", async () => { - const f = fakeContext(); - const tools: Info[] = []; - let after: (event: any) => unknown = () => {}; - const disposed = mock(async () => {}); - Object.assign(f.ctx, { - tool: { - hook: async (_name: string, callback: typeof after) => { - after = callback; - return { dispose: disposed }; - }, - }, - }); - const host = { - location: { directory: "/project", project: { directory: "/project" } }, - permission: { assert: mock(async () => {}) }, - session: { get: async () => ({ location: { directory: "/project" } }) }, - tool: { - transform: async (callback: (editor: { namespace(input: unknown): void; add(tool: Info): void }) => void) => { - callback({ namespace: () => {}, add: (tool) => tools.push(tool) }); - return { dispose: disposed }; - }, - }, - } as unknown as ContinuityHost & { tool: { transform: any } }; - let output = "BEFORE"; - const prime = mock(async () => output); - const acknowledged = mock(() => {}); - const bd = mock(async (_cwd: string, args: readonly string[]) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") - return '{"beads_dir":"/project/.beads","backend":"dolt","dolt_mode":"embedded","database":"beads"}'; - return '{"key":"lesson","value":"validated finding","action":"remembered","committed":false,"commit_error":"not committed"}'; - }); - Object.assign(f.ctx, { - location: host.location, - permission: host.permission, - tool: { ...f.ctx.tool, ...host.tool }, - }); - Object.assign(f.ctx.session, host.session); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime }, - continuityQualified: true, - continuity: { - bd, - acknowledged, - realpath: async (path) => path, - }, - }); - await f.request("s1", "build"); - await f.request("s2", "build"); - const tool = tools.find((tool) => tool.name === "remember")!; - const context = { - sessionID: "s1", - agent: "worker", - messageID: "m1", - id: "c1", - signal: new AbortController().signal, - progress: async () => {}, - } as unknown as ToolContext; - const result = await tool.execute({ key: "lesson", text: "validated finding" }, context); - await after({ ...context, tool: "beads_remember", status: "completed", result }); - await after({ ...context, tool: "execute", status: "completed", result }); - expect(acknowledged).toHaveBeenCalledTimes(1); - expect(bd.mock.calls.filter(([, args]) => args[0] === "remember")).toHaveLength(1); - output = "AFTER"; - expect((await f.request("s2", "build"))[0]).toContain("AFTER"); - const count = bd.mock.calls.length; - const event: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; - await f.hooks.get("compaction")!(event); - expect(event.system[1]?.text).toContain("memory:lesson"); - expect(event.system[1]?.text).toContain("landed-uncommitted"); - expect(bd).toHaveBeenCalledTimes(count); - cleanup(); - expect(disposed).toHaveBeenCalledTimes(2); - }); - - test("retains unresolved write identities across partial reads, interruption and recovery", async () => { - const f = fakeContext(); - const t = toolFixture(f); - const stopped = new AbortController(); - const writer = invocation("s1", "build", stopped.signal); - const otherWriter = invocation("s1", "worker"); - const bd = mock(async (_cwd: string, args: readonly string[]) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - if (args[0] === "update" && args[3] === "started note") { - stopped.abort(new Error("fixture write interrupted")); - throw stopped.signal.reason; - } - if (args[0] === "update") return JSON.stringify([{ id: args[1], notes: args[3] }]); - if (args[0] === "remember") - return JSON.stringify({ - key: "lesson-uncommitted", - value: "finding", - action: "remembered", - committed: false, - commit_error: "fixture commit failed", - }); - if (args[0] === "list") - return JSON.stringify( - ["read-1", "read-2"].map((id) => ({ id, title: id, status: "open", priority: 2, issue_type: "task" })), - ); - throw new Error("fixture read failed"); - }); - Object.assign(f.ctx, { - location: { directory: "/project", project: { directory: "/project" } }, - permission: { assert: async () => {} }, - }); - Object.assign(f.ctx.session, { get: async () => ({ location: { directory: "/project" } }) }); - const cleanup = await setupBeads(f.ctx, { - continuityQualified: true, - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, - continuity: { bd, realpath: async (p) => p }, - }); - try { - await f.request("s1", "build"); - await expect( - t.tools.find((tool) => tool.name === "note")!.execute({ id: "task-first", text: "started note" }, writer), - ).rejects.toThrow("fixture write interrupted"); - expect( - ( - await t.tools - .find((tool) => tool.name === "remember")! - .execute({ key: "lesson-uncommitted", text: "finding" }, otherWriter) - ).output.status, - ).toBe("landed-uncommitted"); - const read = invocation("s1", "build"); - expect( - (await t.tools.find((tool) => tool.name === "find")!.execute({ view: "list", limit: 1 }, read)).output, - ).toMatchObject({ status: "acknowledged", complete: false }); - expect( - (await t.tools.find((tool) => tool.name === "get")!.execute({ ids: ["unavailable-task"] }, read)).output.status, - ).toBe("failed"); - // Even a later acknowledged write to the same target does not resolve the earlier append. - expect( - (await t.tools.find((tool) => tool.name === "note")!.execute({ id: "task-first", text: "later note" }, read)) - .output.status, - ).toBe("acknowledged"); - f.events.push({ type: "session.execution.interrupted", data: { sessionID: "s1" } }); - await settle(); - const summary: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; - const beforeCompaction = bd.mock.calls.length; - await f.hooks.get("compaction")!(summary); - expect(bd).toHaveBeenCalledTimes(beforeCompaction); - const gap = JSON.parse(summary.system[1]!.text.replace(/^<beads-references>|<\/beads-references>$/g, "")).gap; - const expected = [ - `note "task-first" actor=${executorActor(writer)}: uncertain; fixture write interrupted`, - `remember "lesson-uncommitted" actor=${executorActor(otherWriter)}: landed-uncommitted`, - ]; - const recovery = (await f.request("s1", "build")).join("\n"); - const later = (await f.request("s1", "build")).join("\n"); - for (const detail of expected) { - expect(gap).toContain(detail); - expect(recovery).toContain(detail); - expect(later).toContain(detail); - } - expect(gap).toContain("no final checkpoint is guaranteed"); - expect(bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(2); - expect(bd.mock.calls.filter(([, args]) => args[0] === "remember")).toHaveLength(1); - expect((await f.request("other-session", "build")).join("\n")).not.toContain("task-first"); - f.events.push({ type: "session.moved", data: { sessionID: "s1" } }); - await settle(); - expect((await f.request("s1", "build")).join("\n")).not.toContain("lesson-uncommitted"); - } finally { - await cleanup(); - } - }); - - test("renders actual filtered request capability and actor, preserving guard holds", async () => { - const f = fakeContext(); - const t = toolFixture(f); - let guard: any = { kind: "ready" }; - const prime = mock(async () => "FULL PRIME"); - Object.assign(f.ctx, { permission: { assert: async () => {} } }); - Object.assign(f.ctx.session, { - get: async () => ({ location: { directory: "/project" }, agent: "session-default" }), - }); - const cleanup = await setupBeads(f.ctx, { - continuityQualified: true, - runtime: { guard: async () => guard, prime }, - }); - expect(t.namespaces).toEqual([{ name: "beads", description: expect.any(String) }]); - expect(t.tools).toHaveLength(11); - expect(t.tools.every((tool) => tool.options?.namespace === "beads" && tool.options.codemode === true)).toBeTrue(); - const typed = (await f.request("actual", "build", { execute: {}, shell: {} }))[0]!; - expect(typed).toContain(executorActor({ sessionID: "actual", agent: "build" })); - expect(typed).toContain("Beads namespace is registered and execute is visible"); - const direct = (await f.request("actual", "restricted", { beads_get: {}, beads_note: {} }))[0]!; - expect(direct).toContain(executorActor({ sessionID: "actual", agent: "restricted" })); - expect(direct).toContain("Native Beads leaf tools are directly visible"); - expect(direct).toContain("Use only the listed direct leaves"); - expect(direct).toContain("Each operation still checks its own permission"); - expect(direct).not.toContain("direct shell tool"); - const shell = (await f.request("actual", "review", { shell: {} }))[0]!; - expect(shell).toContain(executorActor({ sessionID: "actual", agent: "review" })); - expect(shell).not.toContain(executorActor({ sessionID: "actual", agent: "build" })); - expect(shell).toContain("direct shell tool"); - expect((await f.request("actual", "review", {}))[0]).toContain( - "Neither native Beads leaves nor direct shell access", - ); - expect(prime).toHaveBeenCalledTimes(1); - guard = { kind: "unsupported", installed: "1.3.0" }; - f.events.push({ type: "session.compaction.ended", data: { sessionID: "actual" } }); - await settle(); - const held = (await f.request("actual", "build", { execute: {}, shell: {} }))[0]!; - expect(held).not.toContain("Beads namespace is registered"); - expect(held).not.toContain("direct shell tool"); - await cleanup(); - }); - test("acknowledged task writes retain task references without a redundant cue; unrelated errors do not refresh prime", async () => { - const f = fakeContext(); - const t = toolFixture(f); - const prime = mock(async () => "PRIME"); - Object.assign(f.ctx, { - location: { directory: "/project", project: { directory: "/project" } }, - permission: { assert: async () => {} }, - }); - Object.assign(f.ctx.session, { get: async () => ({ location: { directory: "/project" } }) }); - const cleanup = await setupBeads(f.ctx, { - continuityQualified: true, - runtime: { guard: async () => ({ kind: "ready" }), prime }, - continuity: { - realpath: async (p) => p, - bd: async (_cwd, args) => - args[0] === "version" - ? "1.3.1" - : args[0] === "context" - ? '{"beads_dir":"/project/.beads"}' - : '[{"id":"task-1","notes":"evidence"}]', - }, - }); - await f.request("s1", "build"); - await t.after({ - ...invocation("s1", "build"), - ...nonCodeMode, - tool: "shell", - input: {}, - status: "error", - error: new ToolError({ message: "test failed" }), - }); - expect(await f.request("s1", "build")).toHaveLength(1); - expect(prime).toHaveBeenCalledTimes(1); - await t.tools - .find((tool) => tool.name === "note")! - .execute({ id: "task-1", text: "evidence" }, invocation("s1", "build")); - expect(await f.request("s1", "build")).toHaveLength(1); - expect(prime).toHaveBeenCalledTimes(2); - const event: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; - await f.hooks.get("compaction")!(event); - expect(event.system[1]?.text).toContain("task:task-1"); - expect(event.system[1]?.text).not.toContain("memory:task-1"); - await cleanup(); - }); - - test("ordinary setup withholds privileged continuity registration", async () => { - const f = fakeContext(); - const transform = mock(async () => ({ dispose: async () => {} })); - Object.assign(f.ctx, { tool: { transform, hook: mock(async () => ({ dispose: async () => {} })) } }); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, - }); - expect(transform).not.toHaveBeenCalled(); - cleanup(); - }); - - test("compaction preserves native replay, keepID, legacy recent and model boundaries without I/O", async () => { - const f = fakeContext(); - const prime = mock(async () => "PRIME"); - const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); - await f.request("s1", "build"); - const hook = f.hooks.get("compaction")!; - // Representative public payloads, not a provider/history implementation or cross-product. - const cases = [ - { model: { providerID: "provider-a", id: "model-a" } }, - { - model: { providerID: "provider-a", id: "model-a" }, - result: { summary: "host summary", metadata: { keepID: "fork-remapped-id" } }, - }, - { - model: { providerID: "provider-b", id: "model-b" }, - result: { - summary: "host fallback", - metadata: { recent: "legacy retained tail" }, - native: { messages: [{ opaque: true }] }, - }, - }, - ]; - for (const fields of cases) { - const event = { - sessionID: "s1", - agent: "build", - system: [], - messages: [], - options: {}, - tools: {}, - ...fields, - } as unknown as SessionCompaction; - const before = JSON.stringify(event); - await hook(event); - const { system, ...preserved } = event; - expect(system).toEqual([{ type: "text", text: BEADS_COMPACTION_GUIDANCE }]); - expect({ ...preserved, system: [] }).toEqual({ ...JSON.parse(before), system: [] }); - expect(event.result).toBe(fields.result); - } - expect(prime).toHaveBeenCalledTimes(1); - cleanup(); - }); - test("host admission and diagnostics agree on unsupported versions", async () => { - for (const appVersion of [ - "2.0.29", - "2.1.1", - "2.2.5", - "2.2.6", - "2.2.8", - "2.4.0", - "2.4.3", - "3.0.0", - "2.3.0-beta.1", - "2.4.2-beta.1", - "2.3", - "unknown", - ]) { - const f = fakeContext({ appVersion }); - const warn = mock(() => {}); - - const cleanup = await setupBeads(f.ctx, { warn }); - - expect(warn).toHaveBeenCalledWith(expect.stringContaining(`OpenCode ${appVersion}`)); - expect(warn).toHaveBeenCalledWith(expect.stringContaining(">=2.3.0 <2.4 || 2.4.1 || 2.4.2")); - expect(f.agents.size).toBe(0); - expect(f.hooks.size).toBe(0); - expect(renderHealthReport({ ...presentationFixture(), host: appVersion }, 2000)).toContain( - appVersion === "unknown" ? "| Host | — | not observed |" : `| Host | ❌ | OpenCode ${appVersion} unsupported |`, - ); - cleanup(); - } - }); - - test.each(["2.3.0", "2.3.8", "2.4.1", "2.4.2"])( - "host admission and diagnostics agree on supported version %s", - async (appVersion) => { - const f = fakeContext({ appVersion }); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" }, - }); - - expect([...f.hooks.keys()]).toEqual(["context", "compaction"]); - expect([...f.agents.keys()]).toEqual(["beads-task-agent"]); - expect(renderHealthReport({ ...presentationFixture(), host: appVersion }, 2000)).toContain( - `| Host | ✅ | OpenCode ${appVersion} |`, - ); - cleanup(); - }, - ); - - test("registers the bounded task agent as a subagent and keeps Luna opt-in", async () => { - const ready = { runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" } }; - const vanilla = fakeContext(); - const cleanupVanilla = await setupBeads(vanilla.ctx, ready); - expect([...vanilla.agents.keys()]).toEqual(["beads-task-agent"]); - const agent = vanilla.agents.get("beads-task-agent"); - expect(agent?.mode).toBe("subagent"); - expect(agent?.name).toBe("beads-task-agent"); - expect(agent?.model).toBeUndefined(); - expect(String(agent?.system)).toContain("An exact assignment or explicit one-bead mode ends with that bead"); - expect(String(agent?.system)).toContain("bd update <id> --claim --json --actor='<executor-actor>' --sandbox"); - expect(typeof agent?.description).toBe("string"); - expect(agent?.permissions).toEqual([...TASK_AGENT_PERMISSIONS]); - expect(agent?.steps).toBe(DEFAULT_TASK_AGENT_STEPS); - cleanupVanilla(); - - const luna = fakeContext({ pluginOptions: { luna: true } }); - const cleanupLuna = await setupBeads(luna.ctx, ready); - const lunaAgent = luna.agents.get("beads-task-agent-luna"); - expect(lunaAgent?.model).toEqual({ providerID: "openai", id: "gpt-6-luna", variant: "max" }); - expect(lunaAgent?.system).toBe(luna.agents.get("beads-task-agent")?.system); - expect(lunaAgent?.mode).toBe("subagent"); - cleanupLuna(); - }); - - test("registers Terra independently and with Luna, with shared policy and context", async () => { - const ready = { runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" } }; - for (const luna of [false, true]) { - const f = fakeContext({ pluginOptions: { terra: true, luna, taskAgentSteps: 12 } }); - const cleanup = await setupBeads(f.ctx, ready); - expect([...f.agents.keys()]).toEqual( - luna - ? ["beads-task-agent", "beads-task-agent-luna", "beads-task-agent-terra"] - : ["beads-task-agent", "beads-task-agent-terra"], - ); - const base = f.agents.get("beads-task-agent")!; - const terra = f.agents.get("beads-task-agent-terra")!; - expect(base.model).toBeUndefined(); - expect(terra.model).toEqual({ providerID: "openai", id: "gpt-6.1-terra", variant: "medium" }); - expect(terra.system).toBe(base.system); - expect(terra.description).toBe(base.description); - expect(terra.mode).toBe(base.mode); - expect(terra.permissions).toEqual(base.permissions); - expect(terra.steps).toBe(base.steps); - if (luna) - expect(f.agents.get("beads-task-agent-luna")?.model).toEqual({ - providerID: "openai", - id: "gpt-6-luna", - variant: "max", - }); - expect(await f.request("terra-child", "beads-task-agent-terra")).toEqual([ - renderBeadsContext("PRIME", "task-agent", { sessionID: "terra-child", agent: "beads-task-agent-terra" }), - ]); - await cleanup(); - } - }); - - test("appends rendered prime to eligible requests through the context hook only", async () => { - const f = fakeContext(); - const prime = mock(async (_directory: string) => "PRIME"); - const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); - - expect([...f.hooks.keys()]).toEqual(["context", "compaction"]); - expect(await f.request("s1", "build")).toEqual([ - renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" }), - ]); - expect(await f.request("s1", "build")).toEqual([ - renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" }), - ]); - expect(await f.request("s1", "explore")).toEqual([]); - expect(prime).toHaveBeenCalledTimes(1); - expect(prime).toHaveBeenCalledWith("/project", expect.any(AbortSignal)); - expect(f.agentGet).toHaveBeenCalledWith({ agentID: "build" }); - cleanup(); - }); - - test("minimizes bd's full AGENTS.md block only when prime is attached", async () => { - const block = "<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:1 -->\nPRIME\n<!-- END BEADS INTEGRATION -->"; - let guard: { kind: "ready" } | { kind: "unsupported"; installed: string } = { - kind: "ready", - }; - const f = fakeContext(); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => guard, prime: async () => "PRIME" }, - retryMs: 0, - }); - const hook = f.hooks.get("context"); - if (!hook) throw new Error("context hook not registered"); - - const withPrime: ContextEvent = { sessionID: "s1", agent: "build", system: [{ type: "text", text: block }] }; - await hook(withPrime); - expect(withPrime.system[0]?.text).toContain("provided by the opencode-beads plugin"); - expect(withPrime.system[0]?.text).not.toContain("BEGIN BEADS"); - expect(withPrime.system[1]?.text).toBe(renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" })); - - const subagent: ContextEvent = { sessionID: "s1", agent: "explore", system: [{ type: "text", text: block }] }; - await hook(subagent); - expect(subagent.system).toEqual([{ type: "text", text: block }]); - - guard = { kind: "unsupported", installed: "1.3.0" }; - const withNotice: ContextEvent = { sessionID: "s2", agent: "build", system: [{ type: "text", text: block }] }; - await hook(withNotice); - expect(withNotice.system[0]?.text).toBe(block); - expect(withNotice.system[1]?.text).toContain("<beads-notice>"); - cleanup(); - }); - - test("attaches prime without altering instructions when AGENTS.md has no Beads block", async () => { - const f = fakeContext(); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, - }); - const hook = f.hooks.get("context"); - if (!hook) throw new Error("context hook not registered"); - const instructions = "Instructions from: /repo/AGENTS.md\n# Project rules"; - const event: ContextEvent = { - sessionID: "s1", - agent: "build", - system: [{ type: "text", text: instructions }], - }; - await hook(event); - expect(event.system).toEqual([ - { type: "text", text: instructions }, - { type: "text", text: renderBeadsContext("PRIME", "primary", { sessionID: "s1", agent: "build" }) }, - ]); - cleanup(); - }); - - test("refreshes after compaction ends and forgets deleted sessions", async () => { - const f = fakeContext(); - let output = "FIRST"; - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => output }, - }); - - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); - output = "SECOND"; - f.events.push({ type: "session.step.ended", data: { sessionID: "s1" } }); - await settle(); - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); - - f.events.push({ type: "session.compaction.ended", data: { sessionID: "s1" } }); - await settle(); - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("SECOND"); - - output = "THIRD"; - f.events.push({ type: "session.deleted", data: { sessionID: "s1" } }); - await settle(); - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("THIRD"); - cleanup(); - }); - - test("always runs bd prime with --full, and adds --stealth only when the stealth option is set", async () => { - for (const [options, flags] of [ - [{}, ["--full"]], - [{ stealth: true }, ["--full", "--stealth"]], - [{ stealth: "yes" }, ["--full"]], - ] as const) { - const runPrime = mock(async (_cwd: string, _flags: readonly string[]) => "PRIME"); - const f = fakeContext({ pluginOptions: options }); - const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }) }, runPrime }); - await f.request("s1", "build"); - expect(runPrime).toHaveBeenCalledWith("/project", flags); - cleanup(); - } - }); - - test("caps worker steps from taskAgentSteps, and 0 removes the cap", async () => { - const ready = { runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" } }; - const capped = fakeContext({ pluginOptions: { taskAgentSteps: 25, luna: true } }); - (await setupBeads(capped.ctx, ready))(); - expect(capped.agents.get("beads-task-agent")?.steps).toBe(25); - expect(capped.agents.get("beads-task-agent-luna")?.steps).toBe(25); - const uncapped = fakeContext({ pluginOptions: { taskAgentSteps: 0 } }); - (await setupBeads(uncapped.ctx, ready))(); - expect(uncapped.agents.get("beads-task-agent")?.steps).toBeUndefined(); - const invalid = fakeContext({ pluginOptions: { taskAgentSteps: "lots" } }); - (await setupBeads(invalid.ctx, ready))(); - expect(invalid.agents.get("beads-task-agent")?.steps).toBe(DEFAULT_TASK_AGENT_STEPS); - }); - - test("asks compaction to keep Beads state only for sessions that had Beads context", async () => { - const f = fakeContext(); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, - }); - const compaction = f.hooks.get("compaction"); - if (!compaction) throw new Error("compaction hook not registered"); - await f.request("s1", "build"); - const withBeads: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; - await compaction(withBeads); - expect(withBeads.system).toEqual([{ type: "text", text: BEADS_COMPACTION_GUIDANCE }]); - const other: ContextEvent = { sessionID: "s2", agent: "build", system: [] }; - await compaction(other); - expect(other.system).toEqual([]); - f.events.push({ type: "session.deleted", data: { sessionID: "s1" } }); - await settle(); - const deleted: ContextEvent = { sessionID: "s1", agent: "build", system: [] }; - await compaction(deleted); - expect(deleted.system).toEqual([]); - cleanup(); - }); - - test("passes refreshAfterIdleMinutes through to the context cache", async () => { - let time = 0; - let output = "FIRST"; - const f = fakeContext({ pluginOptions: { refreshAfterIdleMinutes: 1 } }); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => output }, - now: () => time, - }); - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); - output = "SECOND"; - time = 59_000; - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("FIRST"); - time = 59_000 + 60_001; - expect((await f.request("s1", "beads-task-agent"))[0]).toContain("SECOND"); - cleanup(); - }); - - test("stops the event stream on cleanup", async () => { - const f = fakeContext(); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, - }); - await settle(); - cleanup(); - await settle(); - expect(f.events.aborted()).toBeTrue(); - }); - - test("native full prime ignores CLI witnesses and retired autoMigrate values", async () => { - const directory = await mkdtemp(path.join(tmpdir(), "beads-host-")); - try { - for (const marker of [undefined, "1.3.2", "1.3.4", "1.4.0"]) { - const markerPath = path.join(directory, ".local_version"); - if (marker === undefined) await rm(markerPath, { force: true }); - else await writeFile(markerPath, marker); - for (const autoMigrate of [undefined, false, true]) { - const bd = mock(async (_cwd: string, args: readonly string[]) => - args[0] === "version" ? "bd version 1.3.4" : JSON.stringify({ beads_dir: directory }), - ); - const text = "WORKFLOW\n## Persistent Memories\nNative selected memory\nNative partial-availability notice"; - const runPrime = mock(async () => text); - const f = fakeContext({ directory, pluginOptions: { autoMigrate } }); - const cleanup = await setupBeads(f.ctx, { bd, runPrime }); - try { - expect(await f.request("s1", "build")).toEqual([ - renderBeadsContext(text, "primary", { sessionID: "s1", agent: "build" }), - ]); - expect(runPrime).toHaveBeenCalledWith(directory, ["--full"]); - expect(bd.mock.calls.map((call) => call[1])).toEqual([["version"], ["context", "--json"]]); - } finally { - cleanup(); - } - } - } - } finally { - await rm(directory, { recursive: true, force: true }); - } - }); - - test("rate-limits diagnostics and never lets them fail a request", async () => { - const f = fakeContext(); - let time = 0; - const warn = mock((_message: string) => { - throw new Error("log sink down"); - }); - const cleanup = await setupBeads(f.ctx, { - runtime: { - guard: async () => ({ kind: "ready" }), - prime: async () => { - throw new Error("exit 1"); - }, - }, - warn, - now: () => time, - retryMs: 0, - diagnosticIntervalMs: 1_000, - }); - - const notice = [primeFailureNotice("failed")]; - expect(await f.request("s1", "build")).toEqual(notice); - time = 1; - expect(await f.request("s1", "build")).toEqual(notice); - expect(warn).toHaveBeenCalledTimes(1); - expect(warn.mock.calls[0]?.[0]).toContain("prime_failed"); - time = 1_002; - await f.request("s1", "build"); - expect(warn).toHaveBeenCalledTimes(2); - cleanup(); - }); + } }); -/** Replay only the public add callbacks in native package/config order. */ -function commandFixture(f: ReturnType<typeof fakeContext>) { - type Editor = { add(definition: CommandDefinition): void }; - const callbacks: Array<(editor: Editor) => void> = []; - const initial: CommandDefinition = { name: "oc-beads:ready", description: "EARLIER PLUGIN", execute: async () => {} }; - let lookupFailed = false; - let omitted: string | undefined; - const commands = () => { - const result = new Map([[initial.name, initial]]); - for (const callback of callbacks) callback({ add: (definition) => result.set(definition.name, definition) }); - return result; - }; - const transform = mock(async (callback: (editor: Editor) => void) => { - callbacks.push(callback); - commands(); - return { - dispose: async () => { - callbacks.splice(callbacks.indexOf(callback), 1); - }, - }; - }); - const prompt = mock(async (_input: Record<string, unknown>) => ({})); - Object.assign(f.ctx, { - command: { - transform, - list: async () => { - if (lookupFailed) throw new Error("lookup failed"); - return { - data: [...commands().values()] - .filter((entry) => entry.name !== omitted) - .map(({ name, description }) => ({ name, description })), - }; - }, - }, - }); - Object.assign(f.ctx.session, { prompt, get: async () => ({ agent: "build", location: { directory: "/project" } }) }); - const invocation = { - sessionID: "s1", - delivery: "queue", - prompt: { - text: "literal '$ARGUMENTS' $(touch nope) `text`", - files: [{ uri: "file:///tmp/a%20b" }], - agents: [{ name: "build" }], - skills: [{ id: "oc-beads" }], - }, - } as unknown as CommandInvocation; - return { - callbacks, - commands, - transform, - prompt, - invocation, - detailsInvocation: { ...invocation, prompt: { ...invocation.prompt, text: "details" } }, - failLookup: (failed: boolean) => { - lookupFailed = failed; - }, - omit: (name?: string) => { - omitted = name; - }, - }; -} - -describe("child handoff plugin boundary (not live host qualification)", () => { - test.each(["running", "failed", "cancelled", "NO_TEXT", "partial"] as const)( - "preserves %s child outcome and adds only a next-request recovery cue", - async (outcome) => { - const f = fakeContext(); - const t = toolFixture(f); - const prompt = mock(async () => ({})); - const synthetic = mock(async () => ({})); - Object.assign(f.ctx.session, { - prompt, - synthetic, - get: async () => ({ agent: "human-default", location: { directory: "/project" } }), - }); - const prime = mock(async () => "CURRENT"); - const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); - await f.request("parent", "build"); - await f.request("child", "beads-task-agent"); - const parent = invocation("parent", "build"); - const child = invocation("child", "beads-task-agent"); - const handoff = `Task fixture-1 only; actor ${executorActor(child)}; session child; tried A; failed validation; because B; reference task:fixture-1; candidate fixture-rev; blocker acceptance; next authorized action C; partial.`; - const input = { agent: "beads-task-agent", description: "bounded fixture", prompt: handoff }; - const base = { - tool: "subagent", - codemode: false, - sessionID: parent.sessionID, - agent: parent.agent, - messageID: parent.messageID, - id: parent.id, - input, - }; - // Exercise the 2.3 launch handle and error boundary alongside earlier result - // forms; execute.after has no status="cancelled". - const event: ToolAfterEvent = - outcome === "failed" || outcome === "cancelled" - ? { - ...base, - status: "error", - error: new ToolError({ - message: - outcome === "failed" - ? "Subagent failed (sessionID: child): fixture failure" - : "Subagent cancelled (sessionID: child)", - }), - } - : { - ...base, - status: "completed", - result: { - output: { - sessionID: "child", - status: outcome === "running" ? "running" : "completed", - output: - outcome === "running" - ? "The subagent is working in the background (sessionID: child). You will receive a <subagent> message when it goes idle, and again after each later round of work." - : outcome === "NO_TEXT" - ? "Subagent completed without a text response." - : handoff, - }, - content: - outcome === "running" - ? '<subagent sessionID="child" state="running">Launched</subagent>' - : `<subagent sessionID="child" state="completed">\n${outcome === "NO_TEXT" ? "Subagent completed without a text response." : handoff}\n</subagent>`, - metadata: { sessionID: "child", status: outcome === "running" ? "running" : "completed" }, - }, - }; - const before = JSON.stringify(event); - await t.after(event); - expect(JSON.stringify(event)).toBe(before); - expect(event.input).toBe(input); - expect(prime).toHaveBeenCalledTimes(2); - expect(prompt).not.toHaveBeenCalled(); - expect(synthetic).not.toHaveBeenCalled(); - const recovered = await f.request("parent", "build"); - expect(prime).toHaveBeenCalledTimes(3); - expect(recovered[1]).toContain("may only acknowledge launch or follow-up"); - expect(recovered[1]).toContain("actual reports or results"); - expect(recovered[1]).not.toContain("A child returned"); - // Child context is isolated; a parent-side result does not change its actor/cache. - expect(await f.request("child", "beads-task-agent")).toHaveLength(1); - expect(prime).toHaveBeenCalledTimes(3); - await cleanup(); - }, +test("registers the eleven code-mode operations without injected dependencies and disposes owned tools", async () => { + const f = createHost(); + const dispose = mock(async () => {}); + const { tools, namespaces } = toolFixture(f, dispose); + f.ctx.permission = { assert: async () => {} }; + Object.assign(f.ctx.session, { get: async () => sessionInfo("/project") }); + const cleanup = await pluginModule.default.setup(f.ctx as Parameters<typeof pluginModule.default.setup>[0]); + expect(namespaces).toEqual([expect.objectContaining({ name: "beads" })]); + expect(tools.map((tool) => tool.name).sort()).toEqual( + ["find", "get", "edges", "memories", "recall", "claim", "note", "update", "close", "create", "remember"].sort(), ); - - test("a late child return and execution success after deliberate stop do not restart or imply a final checkpoint", async () => { - const f = fakeContext(); - const t = toolFixture(f); - const prompt = mock(async () => ({})); - const synthetic = mock(async () => ({})); - Object.assign(f.ctx.session, { prompt, synthetic }); - const prime = mock(async () => "CURRENT"); - const cleanup = await setupBeads(f.ctx, { runtime: { guard: async () => ({ kind: "ready" }), prime } }); - await f.request("parent", "build"); - f.events.push({ type: "session.execution.interrupted", data: { sessionID: "parent", reason: "user" } }); - await settle(); - const context = invocation("parent", "build"); - const event: ToolAfterEvent = { - tool: "subagent", - ...nonCodeMode, - sessionID: context.sessionID, - agent: context.agent, - messageID: context.messageID, - id: context.id, - input: { agent: "beads-task-agent", prompt: "exact fixture-1" }, - status: "completed", - result: { - output: { sessionID: "child", status: "completed", output: "late partial evidence" }, - metadata: { sessionID: "child", status: "completed" }, - }, - }; - const before = JSON.stringify(event); - await t.after(event); - f.events.push({ type: "session.execution.succeeded", data: { sessionID: "parent" } }); - await settle(); - expect(JSON.stringify(event)).toBe(before); - expect(prime).toHaveBeenCalledTimes(1); - expect(prompt).not.toHaveBeenCalled(); - expect(synthetic).not.toHaveBeenCalled(); - const summary: ContextEvent = { sessionID: "parent", agent: "build", system: [] }; - await f.hooks.get("compaction")!(summary); - expect(summary.system[1]?.text).toContain("no final checkpoint"); - expect(prime).toHaveBeenCalledTimes(1); - // Only a caller-initiated request asks for fresh recovery; the test does not run a model. - expect((await f.request("parent", "build"))[1]).toContain("incomplete work"); - await cleanup(); - const calls = prime.mock.calls.length; - await t.after(event); - expect(await f.request("parent", "build")).toEqual([]); - expect(prime).toHaveBeenCalledTimes(calls); - }); - - test("preserves parent/child checkpoint actors and partial handoff on fresh-session/fork recovery", async () => { - const f = fakeContext(); - const t = toolFixture(f); - const permission = mock(async (_input: unknown) => {}); - Object.assign(f.ctx, { - permission: { assert: permission }, - location: { directory: "/project", project: { directory: "/project" } }, - }); - Object.assign(f.ctx.session, { - get: async () => ({ agent: "human-default", location: { directory: "/project" } }), - }); - const child = invocation("child-full-session", "beads-task-agent"); - const parent = invocation("parent-full-session", "build"); - const notes = [`Earlier attempt failed; rationale retained.`]; - const handoff = `Scope fixture-1; executor ${executorActor(child)}; full session ${child.sessionID}; tried alternative; result partial; validation unit pass/live unexecuted; because source only; reference task:fixture-1; candidate fixture-rev; blocker live gate; next authorized action parent review.`; - const bd = mock(async (_cwd: string, args: readonly string[]) => { - if (args[0] === "version") return "1.3.1"; - if (args[0] === "context") return '{"beads_dir":"/project/.beads"}'; - if (args[0] === "update") notes.push(String(args[args.indexOf("--append-notes") + 1])); - return JSON.stringify([ - { - id: "fixture-1", - created_by: "unknown", - owner: "account-owner", - assignee: executorActor(child), - notes: notes.join("\n"), - }, - ]); - }); - const prime = mock(async () => "CURRENT"); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime }, - continuityQualified: true, - continuity: { bd, realpath: async (value) => value }, - }); - await f.request(String(child.sessionID), String(child.agent)); - await f.request(String(parent.sessionID), String(parent.agent)); - const checkpoint = t.tools.find((tool) => tool.name === "note")!; - await checkpoint.execute({ id: "fixture-1", text: handoff }, child); - await checkpoint.execute( - { id: "fixture-1", text: "Parent review only; no ownership transfer or closure." }, - parent, - ); - const writes = bd.mock.calls.filter(([, args]) => args[0] === "update"); - expect(writes.map(([, args]) => args[args.indexOf("--actor") + 1])).toEqual([ - executorActor(child), - executorActor(parent), - ]); - expect(writes[0]?.[1]).toContain(handoff); - expect(permission.mock.calls.map(([input]) => (input as { agent: string }).agent)).toEqual([ - child.agent, - parent.agent, - ]); - const compact = async (sessionID: string, agent: string) => { - const event: ContextEvent = { sessionID, agent, system: [] }; - await f.hooks.get("compaction")!(event); - return event.system; - }; - expect((await compact(String(parent.sessionID), String(parent.agent)))[1]?.text).toContain("task:fixture-1"); - f.events.push({ - type: "session.forked", - data: { - sessionID: "fork", - parentID: parent.sessionID, - boundary: { type: "through", messageID: parent.messageID }, - }, - }); - await settle(); - await f.request("fork", "build"); - expect(await compact("fork", "build")).toHaveLength(1); - expect((await compact(String(parent.sessionID), String(parent.agent)))[1]?.text).toContain("task:fixture-1"); - await cleanup(); - const fresh = fakeContext(); - const recoveredTools = toolFixture(fresh); - Object.assign(fresh.ctx, { location: f.ctx.location, permission: f.ctx.permission }); - Object.assign(fresh.ctx.session, { get: f.ctx.session.get }); - const freshCleanup = await setupBeads(fresh.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime }, - continuityQualified: true, - continuity: { bd, realpath: async (value) => value }, - }); - const recovery = await fresh.request("fresh", "build"); - expect(recovery[0]).toContain("retrieve the assigned task and relevant reusable knowledge"); - const result = await recoveredTools.tools - .find((tool) => tool.name === "get")! - .execute({ ids: ["fixture-1"] }, invocation("fresh", "build")); - expect(JSON.stringify(result.output)).toContain(handoff); - expect(JSON.stringify(result.output)).toContain("Earlier attempt failed"); - expect(JSON.stringify(result.output)).toContain('"created_by":"unknown"'); - expect(JSON.stringify(result.output)).toContain('"owner":"account-owner"'); - expect(JSON.stringify(result.output)).toContain(`"assignee":"${executorActor(child)}"`); - expect(bd.mock.calls.filter(([, args]) => args[0] === "update")).toHaveLength(2); - await freshCleanup(); - }); - - test("a permission wait neither writes nor checkpoints during compaction; stop rejects a later approval", async () => { - const f = fakeContext(); - const t = toolFixture(f); - let release: () => void = () => {}; - const permission = mock( - async (_input: unknown) => - new Promise<void>((resolve) => { - release = resolve; - }), - ); - const prompt = mock(async () => ({})); - const synthetic = mock(async () => ({})); - Object.assign(f.ctx, { - permission: { assert: permission }, - location: { directory: "/project", project: { directory: "/project" } }, - }); - Object.assign(f.ctx.session, { - prompt, - synthetic, - get: async () => ({ agent: "human-default", location: { directory: "/project" } }), - }); - const bd = mock(async (_cwd: string, args: readonly string[]) => - args[0] === "version" ? "1.3.1" : '{"beads_dir":"/project/.beads"}', - ); - const cleanup = await setupBeads(f.ctx, { - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "CURRENT" }, - continuityQualified: true, - continuity: { bd, realpath: async (value) => value }, - }); - await f.request("child", "beads-task-agent"); - const abort = new AbortController(); - const context = invocation("child", "beads-task-agent", abort.signal); - const pending = t.tools - .find((tool) => tool.name === "note")! - .execute({ id: "fixture-1", text: "unsaved partial result" }, context); - const outcome = pending.then( - () => undefined, - (error: unknown) => error, - ); - await settle(); - expect(permission).toHaveBeenCalledWith( - expect.objectContaining({ - agent: context.agent, - sessionID: context.sessionID, - save: [], - source: { type: "tool", messageID: context.messageID, id: context.id }, - }), - ); - const count = bd.mock.calls.length; - const summary: ContextEvent = { sessionID: "child", agent: "beads-task-agent", system: [] }; - await f.hooks.get("compaction")!(summary); - expect(summary.system).toEqual([{ type: "text", text: BEADS_COMPACTION_GUIDANCE }]); - expect(bd).toHaveBeenCalledTimes(count); - expect(permission).toHaveBeenCalledTimes(1); - abort.abort(); - expect(await outcome).toHaveProperty("name", "AbortError"); - release(); - await settle(); - expect(bd).toHaveBeenCalledTimes(count); - expect(bd.mock.calls.every(([, args]) => ["version", "context"].includes(args[0] ?? ""))).toBe(true); - expect(prompt).not.toHaveBeenCalled(); - expect(synthetic).not.toHaveBeenCalled(); - await cleanup(); - }); + expect(tools.every((tool) => tool.options?.codemode === true && tool.options.namespace === "beads")).toBeTrue(); + await cleanup!(); + expect(dispose).toHaveBeenCalledTimes(2); }); -describe("owned workflow registration", () => { - test("registers all commands despite initial collisions; config wins on rebuild, removal restores and disposal preserves config", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const warns: string[] = []; - const cleanup = await setupBeads(f.ctx, { warn: (message) => warns.push(message) }); - expect(c.transform).toHaveBeenCalledTimes(1); - expect(c.commands().size).toBe(30); - expect(warns.join("\n")).toContain("command-collision"); - expect(warns.join("\n")).toContain("native precedence"); - const packageCallback = c.callbacks[0]!; - const ready = c.commands().get("oc-beads:ready")!; - await ready.execute(c.invocation); - const sent = c.prompt.mock.calls.at(-1)![0]; - expect(sent.text).toContain(c.invocation.prompt.text); - expect(sent.files).toBe(c.invocation.prompt.files); - expect(sent.agents).toBe(c.invocation.prompt.agents); - expect(sent.skills).toBe(c.invocation.prompt.skills); - expect(sent.delivery).toBe(c.invocation.delivery); - const user = { name: ready.name, description: "USER CONFIG", execute: mock(async () => {}) }; - const config = (editor: { add(definition: CommandDefinition): void }) => editor.add(user); - c.callbacks.push(config); - expect(c.commands().get(ready.name)).toBe(user); - await c.commands().get(ready.name)!.execute(c.invocation); - expect(user.execute).toHaveBeenCalledTimes(1); - c.callbacks.splice(c.callbacks.indexOf(config), 1); - expect(c.commands().get(ready.name)).toBe(ready); - c.callbacks.push(config); - await cleanup(); - expect(c.callbacks).toEqual([config]); - expect(c.commands().get(ready.name)).toBe(user); - expect(c.commands().has("oc-beads:diagnostics")).toBe(false); - const add = mock((_definition: CommandDefinition) => {}); - packageCallback({ add }); - expect(add).not.toHaveBeenCalled(); - await expect(ready.execute(c.invocation)).rejects.toThrow("unloaded"); - expect(f.events.aborted()).toBe(true); - }); - - test("registered mixed workflow and legacy hooks expand replay once before location/eligibility returns", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - const update = c.commands().get("oc-beads:update")!; - const stored: StoredSessionMessage[] = []; - const projected: SessionContext["messages"] = []; - const context = mock(async () => stored); - Object.assign(f.ctx.session, { context }); - for (const [stem, text, delivery] of [ - ["show", "fixture-1", "queue"], - ["update", "append note", "steer"], - ["compact", "explain --auto", "queue"], - ["sync", "explain only", "steer"], - ] as const) { - await c - .commands() - .get(`oc-beads:${stem}`)! - .execute({ ...c.invocation, delivery, prompt: { ...c.invocation.prompt, text } }); - const sent = c.prompt.mock.calls.at(-1)![0]; - expect(sent.text).toBe(`/oc-beads:${stem} ${text}`); - expect(sent.files).toBe(c.invocation.prompt.files); - expect(sent.delivery).toBe(delivery); - const workflow = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }) - .ocBeadsWorkflow; - const messageID = `workflow-${stem}`; - stored.push( - storedUserMessage( - messageID, - String(sent.text), - stem === "sync" ? { ocBeadsSync: workflow } : { ocBeadsWorkflow: workflow }, - ), - ); - projected.push( - Message.make({ - id: messageID, - role: "user", - content: [Message.text(String(sent.text)), Message.text("native prepared attachment/skill + hook edit")], - }), - ); - } - expect(c.prompt).toHaveBeenCalledTimes(4); - const raw = JSON.stringify(projected); - const storedRaw = JSON.stringify(stored); - for (const kind of ["context", "compaction"]) { - const event = { - sessionID: "s1", - agent: "build", - system: [], - messages: projected.map((message) => Message.make(message)), - } as ContextEvent; - await f.hooks.get(kind)!(event); - const once = JSON.stringify(event.messages); - expect(once).not.toContain("ocBeadsSync"); - expect(once).not.toContain("ocBeadsWorkflow"); - expect(once.match(/Invoked command: \/oc-beads:/g)).toHaveLength(4); - expect(once).toContain("With sufficient inputs, perform the requested operation"); - await f.hooks.get(kind)!(event); - expect(JSON.stringify(event.messages)).toBe(once); - expect(event.messages![1]!.content).toContainEqual({ type: "text", text: "/oc-beads:update append note" }); - } - expect(context).toHaveBeenCalledTimes(4); - // A moved session is withheld before native snapshot lookup. - Object.assign(f.ctx.session, { get: async () => ({ location: { directory: "/elsewhere" } }) }); - const moved = { - sessionID: "s1", - agent: "build", - system: [], - messages: projected.map((message) => Message.make(message)), - } as ContextEvent; - await f.hooks.get("context")!(moved); - expect(JSON.stringify(moved.messages)).not.toContain("Requested outcome:"); - expect(JSON.stringify(moved.system)).toContain("Saved Beads workflow instructions or diagnostics are unavailable"); - expect(context).toHaveBeenCalledTimes(4); - expect(JSON.stringify(stored)).toBe(storedRaw); - expect([...f.hooks.keys()].sort()).toEqual(["compaction", "context"]); - // Summary recent-context uses stored visible text; no promise of verbatim snapshot retention. - const recent = stored - .filter((message) => message.type === "user") - .map((message) => message.text) - .join("\n"); - expect(recent).not.toContain("Requested outcome:"); - expect(BEADS_COMPACTION_GUIDANCE).toContain( - "active /oc-beads workflow invocation's requested outcome, unresolved inputs or explicit modes, and applicable authority limits", - ); - const calls = c.prompt.mock.calls.length; - await cleanup(); - const unloaded = { - sessionID: "s1", - agent: "build", - system: [], - messages: projected.map((message) => Message.make(message)), - } as ContextEvent; - await f.hooks.get("context")!(unloaded); - expect(JSON.stringify(unloaded.messages)).toBe(raw); - await expect(update.execute(c.invocation)).rejects.toThrow("unloaded"); - expect(c.prompt).toHaveBeenCalledTimes(calls); - }); - - test("restores a saved workflow by ID from native context after the SDK projects a metadata-free user message", async () => { - const f = fakeContext({ appVersion: "2.3.0" }); - const c = commandFixture(f); - const order: string[] = []; - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - await c - .commands() - .get("oc-beads:show")! - .execute({ - ...c.invocation, - delivery: "queue", - prompt: { ...c.invocation.prompt, text: "fixture-1 --json" }, - }); - const sent = c.prompt.mock.calls.at(-1)![0]; - const workflow = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }).ocBeadsWorkflow; - const messageID = "workflow-message-1"; - const get = mock(async () => { - order.push("location"); - return { location: { directory: "/project" } }; - }); - const context = mock(async ({ sessionID }: { sessionID: string }) => { - order.push("context"); - expect(sessionID).toBe(c.invocation.sessionID); - return [ - { - id: messageID, - type: "user" as const, - time: { created: 1 }, - text: String(sent.text), - metadata: { ocBeadsWorkflow: workflow }, - }, - ]; - }); - Object.assign(f.ctx.session, { get, context }); - - const projected = Message.make({ id: messageID, role: "user", content: String(sent.text) }); - expect(projected.role).toBe("user"); - expect(Object.hasOwn(projected, "metadata")).toBeFalse(); - const event: ContextEvent = { - sessionID: c.invocation.sessionID, - agent: "build", - system: [], - messages: [projected], - }; - await f.hooks.get("context")!(event); - - expect(order).toEqual(["location", "context"]); - expect(context).toHaveBeenCalledTimes(1); - expect(event.messages?.[0]?.content[0]).toEqual(Message.text(workflow.instructions)); - expect(event.messages?.[0]?.content[1]).toEqual(Message.text(String(sent.text))); - expect(c.prompt.mock.calls.at(-1)![0].delivery).toBe("queue"); - await cleanup(); - }); - - test("reports unavailable snapshots after a rejected or incomplete native read without re-admission", async () => { - for (const result of ["rejected", "missing"] as const) { - const f = fakeContext(); - const c = commandFixture(f); - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - await c.commands().get("oc-beads:show")!.execute(c.invocation); - const message = Message.make({ id: `missing-${result}`, role: "user", content: "/oc-beads:show fixture-1" }); - const context = mock(async () => { - if (result === "rejected") throw new Error("fixture native read rejected"); - return []; - }); - Object.assign(f.ctx.session, { context }); - const before = JSON.stringify(message.content); - const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [message] }; - const promptCount = c.prompt.mock.calls.length; - await f.hooks.get("context")!(event); - expect(JSON.stringify(event.messages?.[0]?.content)).toBe(before); - expect(JSON.stringify(event.system)).toContain( - "Saved Beads workflow instructions or diagnostics are unavailable", - ); - expect(context).toHaveBeenCalledTimes(1); - expect(c.prompt).toHaveBeenCalledTimes(promptCount); - await cleanup(); - } - }); - - test("overlapping snapshot reads share a lifecycle while actual invalidations reject late results", async () => { - for (const seam of ["get", "context"] as const) - for (const action of [ - "context", - "compaction", - "session.moved", - "session.deleted", - "session.forked", - "unload", - ] as const) { - const f = fakeContext(); - commandFixture(f); - const stored = storedUserMessage("overlap", "/oc-beads:show fixture", { - ocBeadsWorkflow: { version: 1, instructions: "SAVED OVERLAP" }, - }); - Object.assign(f.ctx.session, { context: async () => [stored] }); - const cleanup = await setupBeads(f.ctx, { - warn: () => {}, - runtime: { - guard: async () => ({ kind: "ready", version: "1.3.4", workspace: { path: "/project/.beads" } }), - prime: async () => "PRIME FIXTURE", - }, - }); - const event = (): ContextEvent => ({ - sessionID: "s1", - agent: "build", - system: [], - messages: [Message.make({ id: "overlap", role: "user", content: stored.text })], - }); - await f.hooks.get("context")!(event()); - const original = f.ctx.session[seam]!; - let release: (value: never) => void = () => {}; - let calls = 0; - Object.assign(f.ctx.session, { - [seam]: async (input: never) => - ++calls === 1 - ? new Promise((resolve) => { - release = resolve; - }) - : original(input), - }); - const firstKind = action === "context" ? "compaction" : "context"; - const first = event(); - const pending = f.hooks.get(firstKind)!(first); - await settle(); - if (action === "context" || action === "compaction") { - const second = event(); - await f.hooks.get(action)!(second); - expect(JSON.stringify(second.messages)).toContain("SAVED OVERLAP"); - expect(JSON.stringify(second.system)).toContain( - action === "context" ? "<beads-context" : "<beads-compaction>", - ); - } else if (action === "unload") await cleanup(); - else { - f.events.push({ type: action, data: { sessionID: "s1" } }); - await settle(); - } - release((await original({ sessionID: "s1" } as never)) as never); - await pending; - const valid = action === "context" || action === "compaction"; - expect(JSON.stringify(first.messages).includes("SAVED OVERLAP")).toBe(valid); - if (valid) - expect(JSON.stringify(first.system)).toContain( - firstKind === "context" ? "<beads-context" : "<beads-compaction>", - ); - else if (action !== "unload") - expect(JSON.stringify(first.system)).toContain( - "Saved Beads workflow instructions or diagnostics are unavailable", - ); - await cleanup(); - } - }); - - test("discards a late native snapshot after session generation changes", async () => { - const f = fakeContext(); - commandFixture(f); - const messageID = "moving-workflow"; - const stored = storedUserMessage(messageID, "/oc-beads:show fixture-1", { - ocBeadsWorkflow: { version: 1, instructions: "STALE SNAPSHOT" }, - }); - let release: (messages: StoredSessionMessage[]) => void = () => {}; - const context = mock( - async () => - new Promise<StoredSessionMessage[]>((resolve) => { - release = resolve; - }), - ); - Object.assign(f.ctx.session, { context }); - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - const message = Message.make({ id: messageID, role: "user", content: stored.text }); - const before = JSON.stringify(message.content); - const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [message] }; - const pending = f.hooks.get("context")!(event); - await settle(); - f.events.push({ type: "session.moved", data: { sessionID: "s1" } }); - await settle(); - release([stored]); - await pending; - expect(JSON.stringify(event.messages?.[0]?.content)).toBe(before); - expect(JSON.stringify(event.system)).toContain("Saved Beads workflow instructions or diagnostics are unavailable"); - expect(JSON.stringify(event.messages)).not.toContain("STALE SNAPSHOT"); - expect(context).toHaveBeenCalledTimes(1); - await cleanup(); - }); - - test("actual Responses serialization retains mixed workflow and legacy instructions once on native replay", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const { createBeadsCommands } = await import("../src/workflows"); - const commands = createBeadsCommands( - { prompt: c.prompt as unknown as Parameters<typeof createBeadsCommands>[0]["prompt"] }, - async () => "DIAGNOSTICS", - "/fixture/package/assets/oc-beads/SKILL.md", - ); - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - const captures: unknown[] = []; - const server = Bun.serve({ - hostname: "127.0.0.1", - port: 0, - async fetch(request) { - captures.push(await request.json()); - const response = { - id: "resp_fixture", - object: "response", - created_at: 0, - model: "fixture", - status: "completed", - output: [], - usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 }, - }; - return new Response(`data: ${JSON.stringify({ type: "response.completed", response })}\n\n`, { - headers: { "content-type": "text/event-stream" }, - }); - }, - }); - const client = make(); - const model = configure({ apiKey: "disposable-fixture", baseURL: `${server.url.origin}/v1` }).responses("fixture"); - const serialize = async (messages: SessionContext["messages"]) => { - await client.generate({ model, messages }); - return JSON.stringify(captures.at(-1)); - }; - try { - const stored: StoredSessionMessage[] = []; - const projected: SessionContext["messages"] = []; - const expected: SessionContext["messages"] = []; - Object.assign(f.ctx.session, { context: mock(async () => stored) }); - const stems = ["show", "update", "compact", "sync", "diagnostics"]; - for (const [index, stem] of stems.entries()) { - const details = - index === stems.length - 1 ? "current turn exact details" : `fixture-1 ${stem} literal --apply --auto`; - await commands - .find((c) => c.name === `oc-beads:${stem}`)! - .execute({ ...c.invocation, prompt: { ...c.invocation.prompt, text: details } }); - const sent = c.prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - const snapshot = (sent.metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; - if (stem === "sync") { - // Canonicalize only the fixed resource path for the historical POSIX digest. - const instructions = snapshot.instructions.replace( - JSON.stringify(path.resolve("/fixture/package/assets/oc-beads/resources/CLI_REFERENCE.md")), - JSON.stringify("/fixture/package/assets/oc-beads/resources/CLI_REFERENCE.md"), - ); - expect(createHash("sha256").update(instructions).digest("hex")).toBe(baseline.syncInstructionsSha256); - } - const messageID = `response-workflow-${stem}`; - const content = [String(sent.text), "native file/skill preparation + prompt hook edits"]; - // Legacy retained history uses its stored snapshot, never a current-definition lookup. - const metadata: StoredUserMessage["metadata"] = - stem === "sync" ? { ocBeadsSync: snapshot, foreign: true } : { ocBeadsWorkflow: snapshot, foreign: true }; - stored.push(storedUserMessage(messageID, String(sent.text), metadata)); - projected.push( - Message.make({ id: messageID, role: "user", content: content.map((text) => Message.text(text)) }), - ); - expected.push( - Message.make({ - id: messageID, - role: "user", - content: [snapshot.instructions, ...content].map((text) => Message.text(text)), - }), - ); - if (index === 0) { - const assistant = Message.make({ role: "assistant", content: Message.text("interleaved assistant") }); - projected.push(assistant); - expected.push(assistant); - } - } - const storage = JSON.stringify(stored); - const projectedStorage = JSON.stringify(projected); - let candidate: string | undefined; - for (const kind of ["context", "compaction"]) { - const event = { - sessionID: "s1", - agent: "build", - system: [], - messages: projected.map((message) => Message.make(message)), - } as ContextEvent; - await f.hooks.get(kind)!(event); - const serialized = await serialize(event.messages!); - candidate ??= serialized; - expect(serialized).toBe(candidate); - expect(serialized).toBe(await serialize(expected)); - expect(serialized).not.toMatch(/ocBeadsWorkflow|ocBeadsSync/); - for (const stem of stems) - expect( - serialized.match( - new RegExp( - stem === "diagnostics" ? "Reproduce only the finished Markdown" : `Invoked command: /oc-beads:${stem}`, - "g", - ), - ), - ).toHaveLength(1); - expect(serialized).toContain("current turn exact details"); - const once = JSON.stringify(event.messages); - await f.hooks.get(kind)!(event); - expect(JSON.stringify(event.messages)).toBe(once); - expect(await serialize(event.messages!)).toBe(candidate); - const replay = { ...event, messages: projected.map((message) => Message.make(message)) }; - await f.hooks.get(kind)!(replay); - expect(await serialize(replay.messages!)).toBe(candidate); - } - expect(JSON.stringify(stored)).toBe(storage); - expect(JSON.stringify(projected)).toBe(projectedStorage); - const auxiliary = await serialize(projected); - expect(auxiliary).not.toContain("Invoked command:"); - expect(auxiliary).not.toContain("Reproduce only the finished Markdown"); - expect(auxiliary).not.toMatch(/ocBeadsWorkflow|ocBeadsSync/); - expect([...f.hooks.keys()].sort()).toEqual(["compaction", "context"]); - expect(c.prompt).toHaveBeenCalledTimes(stems.length); - if (process.env.OC_BEADS_WORKFLOW_EVIDENCE_DIR) - await writeFile( - path.join(process.env.OC_BEADS_WORKFLOW_EVIDENCE_DIR, "provider-fixture.json"), - JSON.stringify( - { - kind: "local Responses serialization only; no inference", - invocations: stems, - candidate: JSON.parse(candidate!), - auxiliary: JSON.parse(auxiliary), - stablePrimaryCompactionReplay: true, - }, - null, - 2, - ), - ); - } finally { - await client.dispose(); - server.stop(true); - await cleanup(); - } - }); - - test("diagnostics identifies its loaded package and expands the captured report through existing hooks", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const prime = mock(async () => "PRIME"); - const cleanup = await setupBeads(f.ctx, { - warn: () => {}, - runtime: { guard: async () => ({ kind: "ready" }), prime }, - }); - try { - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - const sent = c.prompt.mock.calls.at(-1)![0]; - const metadata = sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }; - const snapshot = metadata.ocBeadsWorkflow; - const report = JSON.parse(snapshot.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - const manifest = await Bun.file(new URL("../package.json", import.meta.url)).json(); - expect(report.plugin).toEqual({ name: manifest.name, version: manifest.version }); - expect(report.host).toBe("2.3.0"); - expect(snapshot.instructions).toContain(`DATE: \`${report.capturedAt}\``); - expect(snapshot.instructions).toContain(`VERSION: ${manifest.name} \`${manifest.version}\``); - expect(snapshot.instructions).toContain("PATH: `not observed`"); - expect(prime).not.toHaveBeenCalled(); - const stored = storedUserMessage("diagnostics-message", String(sent.text), { ocBeadsWorkflow: snapshot }); - const request = Message.make({ id: stored.id, role: "user", content: String(sent.text) }); - const raw = JSON.stringify(stored); - const context = mock(async () => [stored]); - Object.assign(f.ctx.session, { context }); - for (const kind of ["context", "compaction"]) { - const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [Message.make(request)] }; - await f.hooks.get(kind)!(event); - expect(event.messages![0]!.content[0]).toEqual({ type: "text", text: snapshot.instructions }); - expect(JSON.stringify(event.messages)).not.toContain("ocBeadsWorkflow"); - expect(JSON.stringify(event.messages).split(snapshot.instructions.split("\n")[0]!)).toHaveLength(2); - } - for (const kind of ["title", "generate"]) { - const event: ContextEvent = { sessionID: "s1", agent: "build", system: [], messages: [Message.make(request)] }; - await f.hooks.get(kind)?.(event); - expect(JSON.stringify(event.messages!.map((message) => message.content))).not.toContain( - "Reproduce only the finished Markdown", - ); - } - expect(JSON.stringify(stored)).toBe(raw); - expect(c.prompt).toHaveBeenCalledTimes(1); - } finally { - await cleanup(); - } - }); - - test("diagnostics overrides restore natively and user-owned old status survives package removal", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - expect(c.commands().size).toBe(30); - expect(c.commands().has("oc-beads:status")).toBe(false); - const diagnostics = c.commands().get("oc-beads:diagnostics")!; - expect(diagnostics.description).toContain("strict-readonly store access"); - expect(diagnostics.description).toContain("configured database"); - expect(diagnostics.description).toContain("All selectors skip remote history fetches"); - const oldStatus = { name: "oc-beads:status", description: "USER OLD STATUS", execute: mock(async () => {}) }; - const override = { ...diagnostics, description: "USER DIAGNOSTICS", execute: mock(async () => {}) }; - const oldConfig = (editor: { add(definition: CommandDefinition): void }) => editor.add(oldStatus); - const newConfig = (editor: { add(definition: CommandDefinition): void }) => editor.add(override); - c.callbacks.push(oldConfig, newConfig); - expect(c.commands().get(diagnostics.name)).toBe(override); - await c.commands().get(diagnostics.name)!.execute(c.invocation); - expect(override.execute).toHaveBeenCalledTimes(1); - c.callbacks.splice(c.callbacks.indexOf(newConfig), 1); - expect(c.commands().get(diagnostics.name)).toBe(diagnostics); - expect(c.commands().get(oldStatus.name)).toBe(oldStatus); - await c.commands().get(oldStatus.name)!.execute(c.invocation); - expect(oldStatus.execute).toHaveBeenCalledTimes(1); - await c.commands().get("oc-beads:stats")!.execute(c.invocation); - const statsMetadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - expect(statsMetadata.ocBeadsWorkflow.instructions).toContain( - "issue-database overview using bd status (alias bd stats)", - ); - expect(statsMetadata.ocBeadsWorkflow.instructions).toContain("Supporting guidance:"); - await cleanup(); - expect(c.commands().get(oldStatus.name)).toBe(oldStatus); - expect(c.commands().has(diagnostics.name)).toBe(false); - }); - - test("registers after an initial lookup failure and reports observable mismatches, missing names and ownership blind spots", async () => { - const f = fakeContext(); - const c = commandFixture(f); - c.failLookup(true); - const cleanup = await setupBeads(f.ctx, { warn: () => {}, runtime: { guard: async () => ({ kind: "ready" }) } }); - expect(c.transform).toHaveBeenCalledTimes(1); - c.failLookup(false); - const ready = c.commands().get("oc-beads:ready")!; - const diagnostics = c.commands().get("oc-beads:diagnostics")!; - const report = async () => { - await diagnostics.execute(c.detailsInvocation); - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - return JSON.parse(metadata.ocBeadsWorkflow.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - }; - let observed = await report(); - expect(observed.commands.registration).toBe("registered"); - expect(observed.commands.lookup).toBe("available"); - expect(observed.commands.ownership).toContain("unavailable"); - expect(observed.commands.ownership).toContain("identical-description"); - expect(observed.commands.ownership).toContain("do not prove ownership"); - c.callbacks.push((editor) => editor.add({ ...ready, description: "USER DESCRIPTION" })); - observed = await report(); - expect(observed.commands.mismatches).toContainEqual({ - name: ready.name, - expectedDescription: ready.description, - effectiveDescription: "USER DESCRIPTION", - }); - expect(observed.commands.effective).toContainEqual({ name: ready.name, description: "USER DESCRIPTION" }); - c.callbacks.push((editor) => editor.add({ ...ready, execute: async () => {} })); - expect((await report()).commands.mismatches).toEqual([]); - c.omit("oc-beads:show"); - expect((await report()).commands.missing).toEqual(["oc-beads:show"]); - c.failLookup(true); - observed = await report(); - expect(observed.commands.lookup).toBe("failed"); - expect(observed.commands.effective).toBe("unknown: registry lookup failed"); - expect(observed.commands.mismatches).toBeUndefined(); - await cleanup(); - }); - - test("skill checks each candidate without an initial list gate and restores a disappearing override", async () => { - const f = fakeContext(); - type Skill = { id: string; name: string; path: string; content: string }; - const custom = { id: "oc-beads", name: "oc-beads", path: "/user/SKILL.md", content: "USER" }; - let before: Skill | undefined = custom; - let after: Skill | undefined; - const skills = new Map<string, Skill>(); - const callbacks: Array<(editor: unknown) => void> = []; - const rebuild = () => { - skills.clear(); - if (before) skills.set(before.id, before); - const editor = { list: () => [...skills.values()], add: (skill: Skill) => skills.set(skill.id, skill) }; - for (const callback of callbacks) callback(editor); - if (after) skills.set(after.id, after); - }; - const list = mock(async () => { - throw new Error("setup must not gate on list"); - }); - Object.assign(f.ctx, { - skill: { - list, - transform: async (callback: (editor: unknown) => void) => { - callbacks.push(callback); - rebuild(); - return { - dispose: async () => { - callbacks.splice(callbacks.indexOf(callback), 1); - rebuild(); - }, - }; - }, - }, - }); - const cleanup = await setupBeads(f.ctx, { warn: () => {} }); - expect(list).not.toHaveBeenCalled(); - expect(callbacks).toHaveLength(1); - expect(skills.get("oc-beads")).toBe(custom); - before = undefined; - rebuild(); - expect(skills.get("oc-beads")?.content).toContain("Beads work in OpenCode"); - after = custom; - rebuild(); - expect(skills.get("oc-beads")).toBe(custom); - after = undefined; - rebuild(); - expect(skills.get("oc-beads")?.content).toContain("Beads work in OpenCode"); - const callback = callbacks[0]!; - after = custom; - await cleanup(); - expect(skills.get("oc-beads")).toBe(custom); - const add = mock((_skill: Skill) => {}); - callback({ list: () => [], add }); - expect(add).not.toHaveBeenCalled(); - }); -}); - -describe("owned lifecycle", () => { - test("awaits idempotent cleanup of every owned registration and aborts pending context", async () => { - const f = fakeContext(); - const disposed: string[] = []; - const completed: string[] = []; - const own = (name: string) => ({ - dispose: async () => { - disposed.push(name); - await new Promise((resolve) => setTimeout(resolve, 1)); - completed.push(name); - }, - }); - const originalAgent = f.ctx.agent.transform; - const transform: HostContext["agent"]["transform"] = async (callback) => { - await originalAgent(callback); - return own("agent"); - }; - Object.assign(f.ctx.agent, { transform }); - const originalHook = f.ctx.session.hook; - const hook: HostContext["session"]["hook"] = async (name, callback) => { - await originalHook(name, callback); - return own(`hook:${name}`); - }; - Object.assign(f.ctx.session, { hook }); - Object.assign(f.ctx, { - skill: { - list: async () => ({ data: [] }), - transform: async (callback: (editor: unknown) => void) => { - callback({ list: () => [], add: () => {} }); - return own("skill"); - }, - }, - tool: { transform: async () => own("tool"), hook: async () => own("tool-hook") }, - permission: { assert: async () => {} }, - }); - Object.assign(f.ctx.session, { get: async () => ({ location: { directory: "/project" } }) }); - let signal: AbortSignal | undefined; - let release: (value: string) => void = () => {}; - const cleanup = await setupBeads(f.ctx, { - continuityQualified: true, - runtime: { - guard: async () => ({ kind: "ready" }), - prime: async (_cwd, abortSignal) => { - signal = abortSignal; - return new Promise<string>((resolve) => { - release = resolve; - }); - }, - }, - }); - const pending = f.request("s1", "build"); - await settle(); - await cleanup(); - expect(signal?.aborted).toBe(true); - expect(f.events.aborted()).toBe(true); - expect(completed.sort()).toEqual(["agent", "skill", "tool", "hook:context", "hook:compaction", "tool-hook"].sort()); - release("LATE OLD LOCATION"); - expect(await pending).toEqual([]); - await cleanup(); - expect(disposed).toHaveLength(6); - }); - - test("releases earlier owned registrations if a later setup seam fails", async () => { - const f = fakeContext(); - const disposed = mock(async () => {}); - const originalAgent = f.ctx.agent.transform; - const transform: HostContext["agent"]["transform"] = async (callback) => { - await originalAgent(callback); - return { dispose: disposed }; - }; - Object.assign(f.ctx.agent, { transform }); - Object.assign(f.ctx.session, { - hook: async () => { - throw new Error("host hook failed"); - }, - }); - await expect(setupBeads(f.ctx)).rejects.toThrow("host hook failed"); - expect(disposed).toHaveBeenCalledTimes(1); - }); -}); - -test("missing packaged guidance is withheld with honest diagnostics", async () => { +test("ordinary setup withholds privileged continuity registration", async () => { + const f = createHost(); const transform = mock(async () => ({ dispose: async () => {} })); - const warnings: string[] = []; - const missing = fakeContext(); - Object.assign(missing.ctx, { skill: { list: async () => ({ data: [] }), transform } }); - const missingCleanup = await setupBeads(missing.ctx, { - warn: (message) => warnings.push(message), - workflowAssets: { - readText: async () => { - throw new Error("sensitive exception content"); - }, - }, - }); - expect(transform).not.toHaveBeenCalled(); - expect(warnings.some((warning) => warning.includes("skill-unreachable SKILL.md"))).toBe(true); - expect(warnings.join("\n")).not.toContain("sensitive exception content"); - await missingCleanup(); -}); - -test("cleanup attempts every owned disposer and reports a failed disposal", async () => { - const f = fakeContext(); - const warn = mock((_message: string) => {}); - const disposed = mock(async () => {}); - const transform: HostContext["agent"]["transform"] = async () => ({ - dispose: async () => { - throw new Error("dispose failed"); - }, - }); - Object.assign(f.ctx.agent, { transform }); - const originalHook = f.ctx.session.hook; - const hook: HostContext["session"]["hook"] = async (name, callback) => { - await originalHook(name, callback); - return { dispose: disposed }; - }; - Object.assign(f.ctx.session, { hook }); - const cleanup = await setupBeads(f.ctx, { warn }); - await expect(cleanup()).rejects.toThrow("Beads cleanup failed"); - expect(disposed).toHaveBeenCalledTimes(2); - expect(warn.mock.calls.flat().join("\n")).toContain("cleanup-failed"); - expect(f.events.aborted()).toBe(true); -}); - -test("registered diagnostics distinguishes missing, held, failed, loading and uncertain context", async () => { - const f = fakeContext(); - const c = commandFixture(f); - let time = 0; - let version = "1.3.1"; - let probe: "missing" | "failed" | "ready" = "missing"; - const bd = mock(async (_directory: string, args: readonly string[]) => { - if (args.join(" ") === "version") return `bd ${version}`; - if (args.join(" ") === "context --json") { - if (probe === "failed") throw new Error("probe failed"); - return JSON.stringify({ beads_dir: probe === "ready" ? "/unused-fixture/.beads" : "" }); - } - if (args.join(" ") === "hooks list --json") return '{"hooks":[]}'; - throw new Error("unexpected command"); - }); - let release: (text: string) => void = () => {}; - const prime = mock( - async () => - new Promise<string>((resolve) => { - release = resolve; - }), - ); - const cleanup = await setupBeads(f.ctx, { bd, runtime: { prime }, now: () => time, retryMs: 1, warn: () => {} }); - const diagnostics = c.commands().get("oc-beads:diagnostics")!; - const report = async () => { - await diagnostics.execute(c.detailsInvocation); - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - return JSON.parse(metadata.ocBeadsWorkflow.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - }; - const initial = await report(); - expect(initial.liveQualification).toBe("not measured by diagnostics; see release acceptance evidence"); - expect(initial.context).toBe("unobserved: no cached context"); - expect(initial.requestCapability).toBe("unknown: no actual request observation"); - await f.request("s1", "build"); - expect((await report()).context).toBe("missing"); - version = "1.2.0"; - time += 2; - await f.request("s1", "build"); - expect((await report()).context).toBe("withheld"); - version = "1.3.1"; - probe = "failed"; - time += 2; - await f.request("s1", "build"); - const failed = await report(); - expect(failed.context).toBe("failed"); - expect(failed.guard.kind).toBe("probe-failed"); - expect(prime).not.toHaveBeenCalled(); - probe = "ready"; - time += 2; - const pending = f.request("s1", "build"); - await settle(); - expect((await report()).context).toBe("uncertain: context refresh in progress"); - release("PRIME"); - await pending; - const observed = await report(); - expect(observed.context).toBe("ready"); - expect(observed.guard).toEqual({ kind: "ready", version: "1.3.1", workspace: { path: "/unused-fixture/.beads" } }); - expect(observed.syncTarget).toEqual({ - state: "unknown", - reason: "native backend was not reported", - listingSkipped: true, - }); - expect(JSON.stringify(observed)).not.toMatch(/migration-pending|migrate schema/); - expect(observed.requestCapability.agent).toBe("build"); - expect(observed.requestCapability.capabilities.typed).toBe("unknown"); - expect(observed.leafAvailability).toContain("unknown"); - expect(prime).toHaveBeenCalledTimes(1); - f.events.push({ type: "session.execution.interrupted", data: { sessionID: "s1" } }); - await settle(); - expect((await report()).persistence).toContain("no final checkpoint"); - Object.assign(f.ctx.session, { - get: async () => { - throw new Error("unknown location"); - }, - }); - const count = bd.mock.calls.length; - const unknown = await report(); - expect(unknown.context).toBe("uncertain: session lookup failed"); - expect(unknown.guard.kind).toBe("withheld"); - expect(unknown.persistence).toContain("uncertain: no final-write guarantee"); - expect(bd).toHaveBeenCalledTimes(count); - expect(new Set(bd.mock.calls.map(([, args]) => args.join(" ")))).toEqual( - new Set(["version", "context --json", "hooks list --json"]), - ); - await cleanup(); -}); - -test("diagnostics starts lookup synchronously and reads new request evidence after the registry probe", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const session = { agent: "build", location: { directory: "/project" } }; - const lookup = Promise.withResolvers<typeof session>(); - const registryStarted = Promise.withResolvers<void>(); - const releaseRegistry = Promise.withResolvers<void>(); - const effects: string[] = []; - const cleanup = await setupBeads(f.ctx, { - bd: async () => '{"hooks":[]}', - warn: () => {}, - runtime: { - guard: async () => { - effects.push("guard"); - return { kind: "ready" }; - }, - prime: async () => "BODY", - }, - }); - const originalList = f.ctx.command!.list; - let firstLookup = true; - Object.assign(f.ctx.session, { - get() { - if (!firstLookup) return Promise.resolve(session); - firstLookup = false; - effects.push("lookup"); - return lookup.promise; - }, - }); - Object.assign(f.ctx.command!, { - async list() { - registryStarted.resolve(); - await releaseRegistry.promise; - return originalList.call(this); - }, - }); - - const pending = c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - try { - expect(effects).toEqual(["lookup"]); - lookup.resolve(session); - queueMicrotask(() => effects.push("caller microtask")); - await Promise.race([registryStarted.promise, pending]); - expect(effects).toEqual(["lookup", "guard", "caller microtask"]); - - await f.request("s1", "build"); - releaseRegistry.resolve(); - await pending; - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - const report = JSON.parse(metadata.ocBeadsWorkflow.instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - expect(report.context).toBe("unobserved: no cached context"); - expect(report.requestCapability.agent).toBe("build"); - expect(report.requestInstructions).toHaveProperty("at"); - } finally { - lookup.resolve(session); - releaseRegistry.resolve(); - await pending.catch(() => {}); - await cleanup(); - } -}); - -test("unload aborts an in-flight native diagnostics without submitting a late prompt", async () => { - const f = fakeContext(); - const c = commandFixture(f); - let signal: AbortSignal | undefined; - let release: () => void = () => {}; + Object.assign(f.ctx, { tool: { transform, hook: mock(async () => ({ dispose: async () => {} })) } }); const cleanup = await setupBeads(f.ctx, { - warn: () => {}, - runtime: { - guard: async (_directory, abortSignal) => { - signal = abortSignal; - await new Promise<void>((resolve) => { - release = resolve; - }); - return { kind: "ready" }; - }, - }, + runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, }); - const pending = c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - await settle(); + expect(transform).not.toHaveBeenCalled(); await cleanup(); - expect(signal?.aborted).toBe(true); - release(); - await expect(pending).rejects.toThrow("unloaded"); - expect(c.prompt).not.toHaveBeenCalled(); }); -test("unload prevents a pending native target listing from submitting a report", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const { promise: listingStarted, resolve: startListing } = Promise.withResolvers<void>(); - const { promise: listing, resolve: finishListing } = Promise.withResolvers<string>(); - const cleanup = await setupBeads(f.ctx, { - warn: () => {}, - bd: async (_directory, args) => { - switch (args.join(" ")) { - case "version": - return "bd version 1.3.4"; - case "context --json": - return '{"beads_dir":"/fixture/.beads","backend":"dolt","dolt_mode":"embedded"}'; - case "hooks list --json": - return '{"hooks":[]}'; - case "--readonly dolt remote list --json --sandbox": - startListing(); - return listing; - default: - throw new Error("unexpected command"); - } - }, - }); - const pending = c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - try { - await Promise.race([listingStarted, pending]); - await cleanup(); - finishListing("[]"); - await expect(pending).rejects.toThrow("unloaded"); - expect(c.prompt).not.toHaveBeenCalled(); - } finally { - finishListing("[]"); - await cleanup(); - } -}); - -test("a failed native command registration diagnoses failure and releases earlier owned registrations", async () => { - const f = fakeContext(); - commandFixture(f); - const disposed = mock(async () => {}); - const original = f.ctx.agent.transform; - const transform: HostContext["agent"]["transform"] = async (callback) => { - await original(callback); - return { dispose: disposed }; - }; - Object.assign(f.ctx.agent, { transform }); - Object.assign(f.ctx.command!, { - transform: async () => { - throw new Error("native registration failed"); - }, - }); - const warnings: string[] = []; - await expect(setupBeads(f.ctx, { warn: (message) => warnings.push(message) })).rejects.toThrow( - "native registration failed", - ); - expect(warnings.join("\n")).toContain("command-registration-failed"); - expect(disposed).toHaveBeenCalledTimes(1); -}); - -test("registered diagnostics reports an embedded store with no native remotes or installed hooks", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const bd = mock(async (_directory: string, args: readonly string[]) => { - if (args.join(" ") === "version") return "bd version 1.3.4"; - if (args.join(" ") === "context --json") - return JSON.stringify({ beads_dir: "/unused/.beads", backend: "dolt", dolt_mode: "embedded" }); - if (args.join(" ") === "hooks list --json") - return JSON.stringify({ - hooks: [{ Name: "pre-commit", Installed: false, Version: "", IsShim: false, Outdated: false }], - }); - if (args.join(" ") === "--readonly dolt remote list --json --sandbox") return "[]"; - throw new Error("unexpected invocation"); - }); - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - try { - await c - .commands() - .get("oc-beads:diagnostics")! - .execute({ ...c.detailsInvocation, prompt: { ...c.detailsInvocation.prompt, text: "details remote" } }); - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - const report = metadata.ocBeadsWorkflow.instructions; - expect(report).toContain("| Git hooks | — | 0/1 installed · 1 missing/unreadable/unresolved |"); - expect(report).toContain("| Sync target | ✅ | Local-only |"); - expect(report).toContain("| Remote history | — | Not applicable |"); - expect(report).not.toContain("No qualified Beads history probe is available"); - expect(report).toContain("Git-origin adoption with consent"); - expect(report).toContain("Source-Git freshness was not checked"); - expect(report).toContain("pre-commit"); - expect(report).not.toContain("Git hooks need attention"); - expect(report).not.toContain("bd hooks install"); - expect(bd.mock.calls).toEqual([ - [f.ctx.location.directory, ["version"]], - [f.ctx.location.directory, ["context", "--json"]], - [f.ctx.location.directory, ["hooks", "list", "--json"]], - [f.ctx.location.directory, ["--readonly", "dolt", "remote", "list", "--json", "--sandbox"]], - ]); - } finally { - await cleanup(); - } -}); - -test("registered diagnostics keeps incomplete or ambiguous native target evidence neutral", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const origin = { name: "origin", status: "ok", url: "https://user:listing-secret@example.invalid" }; - const remoteList = ["--readonly", "dolt", "remote", "list", "--json", "--sandbox"]; - let context: Record<string, unknown>; - let listing: string | Error; - const bd = mock(async (_directory: string, args: readonly string[]) => { - switch (args.join(" ")) { - case "version": - return "bd version 1.3.4"; - case "context --json": - return JSON.stringify({ beads_dir: "/fixture/.beads", ...context }); - case "hooks list --json": - return '{"hooks":[]}'; - case "--readonly dolt remote list --json --sandbox": - if (listing instanceof Error) throw listing; - return listing; - default: - throw new Error("unexpected command"); - } - }); - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - const embedded = { backend: "dolt", dolt_mode: "embedded" }; - const server = { - backend: "dolt", - dolt_mode: "server", - server_host: "server-secret.example.invalid", - server_port: 3307, - }; - const cases = [ - { context: server, output: "[]", reason: "empty native listing in server mode" }, - { - context: embedded, - output: JSON.stringify([{ ...origin, name: "alternate" }]), - reason: "native origin was not listed", - }, - { - context: { ...server, ...embedded }, - output: JSON.stringify([origin]), - reason: "embedded mode conflicts with server endpoint evidence", - skipListing: true, - }, - { - context: { backend: "dolt" }, - output: JSON.stringify([origin]), - reason: "native Dolt mode was not reported", - skipListing: true, - }, - { - context: { ...embedded, dolt_mode: "unknown-mode" }, - output: "[]", - reason: "unrecognized native Dolt mode", - skipListing: true, - }, - { context: { dolt_mode: "embedded" }, output: "[]", reason: "native backend was not reported", skipListing: true }, - { - context: { ...embedded, backend: "unknown-backend" }, - output: "[]", - reason: "native backend is not Dolt", - skipListing: true, - }, - { - context: { backend: "dolt", dolt_mode: "proxied-server", proxied_dir: "/proxy-secret" }, - output: "[]", - reason: "proxied-server mode is unsupported", - skipListing: true, - }, - { - context: embedded, - output: JSON.stringify([origin, { name: "incomplete" }]), - reason: "native listing returned an unsupported response", - }, - { context: embedded, output: "invalid JSON", reason: "native listing returned an unsupported response" }, - { - context: embedded, - output: new PrimeProcessError(1, origin.url, "bd dolt remote list", origin.url), - reason: "native listing exited with code 1", - }, - { context: embedded, output: new PrimeTimeoutError(5, "bd dolt remote list"), reason: "native listing timed out" }, - ]; - try { - for (const example of cases) { - context = example.context; - listing = example.output; - const start = bd.mock.calls.length; - await c - .commands() - .get("oc-beads:diagnostics")! - .execute({ ...c.detailsInvocation, prompt: { ...c.detailsInvocation.prompt, text: "details remote" } }); - const { ocBeadsWorkflow } = c.prompt.mock.calls.at(-1)![0].metadata as { - ocBeadsWorkflow: { instructions: string }; - }; - const report = ocBeadsWorkflow.instructions; - expect(report).toContain(`| Sync target | — | Unknown · ${example.reason} |`); - expect(report).toContain("| Remote history | — | Not checked · No qualified Beads history probe is available |"); - expect(report).toContain("Comparison was not attempted"); - expect(report).not.toMatch(/secret|Check failed|Unresolved|❌ Unhealthy/); - expect(bd.mock.calls.slice(start).map(([, args]) => args)).toEqual([ - ["version"], - ["context", "--json"], - ["hooks", "list", "--json"], - ...(example.skipListing ? [] : [remoteList]), - ]); - const details = JSON.parse(report.split("\nDetails: ")[1]!.split("\n")[0]!) as { - findings: Array<{ id: string; producer: string; meaning: string }>; - }; - const target = details.findings.find(({ id }) => id === "sync-target"); - expect(target?.producer).toBe( - example.skipListing - ? "bd context --json" - : "bd --readonly dolt remote list --json --sandbox and bd context --json", - ); - if (example.skipListing) expect(target?.meaning).toContain("The strict-readonly remote listing was skipped"); - } - } finally { - await cleanup(); - } -}); - -test("diagnostics reports preceding context version and request instruction counts", async () => { - const f = fakeContext(); - const c = commandFixture(f); - let version = "1.3.1"; - const bd = mock(async (_directory: string, args: readonly string[]) => { - if (args[0] === "version") return `bd version ${version}`; - if (args[0] === "context") return JSON.stringify({ beads_dir: "/unused/.beads", cwd_repo_root: "/project" }); - if (args[0] === "hooks") return JSON.stringify({ hooks: [] }); - throw new Error("unexpected invocation"); - }); - const cleanup = await setupBeads(f.ctx, { bd, runPrime: async () => "prime body", warn: () => {} }); - try { - await f.request("s1", "build"); - version = "1.3.4"; - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - expect(metadata.ocBeadsWorkflow.instructions).toContain("1.3.1"); - expect(metadata.ocBeadsWorkflow.instructions).toContain("1.3.4"); - expect(metadata.ocBeadsWorkflow.instructions).toContain("requestInstructions"); - } finally { - await cleanup(); - } -}); - -test("diagnostics captures witness and scoped managed guidance without remote secrets", async () => { - const root = await mkdtemp(path.join(tmpdir(), "health-diag-")); - const beads = path.join(root, ".beads"); - await mkdir(beads); - await writeFile(path.join(beads, ".local_version"), "1.3.1\n"); - await writeFile( - path.join(root, "AGENTS.md"), - "<!-- BEGIN BEADS INTEGRATION v:1 profile:full -->body<!-- END BEADS INTEGRATION -->", - ); - const f = fakeContext(); - Object.assign(f.ctx, { location: { directory: root } }); - const c = commandFixture(f); - Object.assign(f.ctx.session, { get: async () => ({ agent: "build", location: { directory: root } }) }); - const bd = async (_dir: string, args: readonly string[]) => - args[0] === "version" - ? "bd 1.3.4" - : args[0] === "context" - ? JSON.stringify({ beads_dir: beads, cwd_repo_root: root, sync_remote: "https://user:secret@example.invalid" }) - : JSON.stringify({ hooks: [] }); - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - try { - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - const text = metadata.ocBeadsWorkflow.instructions; - expect(text).toContain("1.3.1"); - expect(text).toContain("differ"); - expect(text).toContain("managedInstructions"); - expect(text).not.toContain("secret"); - expect(text).toContain('"sharedSkill":"missing"'); - expect(text).toContain(`PATH: \`${root}\``); - expect(JSON.parse(text.split("\nDetails: ")[1]!.split("\n")[0]!).guard.workspace).toEqual({ - path: beads, - repoRoot: root, - remote: true, - }); - await mkdir(path.join(root, ".agents", "skills", "beads"), { recursive: true }); - await writeFile(path.join(root, ".agents", "skills", "beads", "SKILL.md"), "local skill"); - await writeFile(path.join(beads, ".local_version"), "1.3.4\n"); - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - let latest = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) - .ocBeadsWorkflow.instructions; - expect(latest).toContain("Recorded 1.3.4 matches running 1.3.4"); - expect(latest).toContain('"sharedSkill":"readable"'); - await rm(path.join(beads, ".local_version")); - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - latest = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow - .instructions; - expect(latest).toContain("Witness missing"); - } finally { - await cleanup(); - await rm(root, { recursive: true, force: true }); - } -}); - -test("captured diagnostics renders compact hook summary before explicit evidence", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const bd = async (_directory: string, args: readonly string[]) => - args[0] === "version" - ? "bd 1.3.4" - : args[0] === "context" - ? '{"beads_dir":"/none"}' - : JSON.stringify({ - hooks: [{ Name: "pre-commit", Installed: false, Version: "", IsShim: false, Outdated: false }], - }); - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - try { - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - const metadata = c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }; - const text = metadata.ocBeadsWorkflow.instructions; - expect(text).toContain("**Plugin**"); - expect(text).toContain("**Beads**"); - expect(text.indexOf("0/1 installed")).toBeLessThan(text.indexOf("**Evidence**")); - expect(JSON.parse(text.split("\nDetails: ")[1]!.split("\n")[0]!).hooks[0].name).toBe("pre-commit"); - expect(text).toContain("bd hooks list"); - } finally { - await cleanup(); - } -}); - -test("native hook failures and installation mismatches stay independent of the sync target", async () => { - const f = fakeContext(); - const c = commandFixture(f); - let hookOutput = "broken"; - let timedOut = false; - const calls: string[] = []; - const bd = async (_directory: string, args: readonly string[]) => { - const command = args.join(" "); - calls.push(command); - if (command === "version") return "bd 1.3.4"; - if (command === "context --json") return '{"beads_dir":"/none","backend":"dolt","dolt_mode":"embedded"}'; - if (command === "hooks list --json") { - if (timedOut) throw new PrimeTimeoutError(5, "bd hooks list --json"); - return hookOutput; - } - if (command === "--readonly dolt remote list --json --sandbox") - return '[{"name":"origin","url":"file:///fixture","status":"ok"}]'; - throw new Error("unexpected command"); - }; - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - const capture = async () => { - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - return (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow - .instructions; - }; - try { - const failed = await capture(); - expect(failed).toContain("hooks list observation unavailable or unsupported"); - expect(failed).toContain("| Git hooks | — | observation failed |"); - expect(failed).toContain("| Sync target | ✅ | Resolved · origin |"); - timedOut = true; - expect(await capture()).toContain("hooks list observation unavailable or unsupported"); - timedOut = false; - const shim = { Name: "pre-push", Installed: true, Version: "", IsShim: true, Outdated: false }; - hookOutput = JSON.stringify({ hooks: [shim] }); - const ordinaryShim = await capture(); - expect(ordinaryShim).toContain("| Git hooks | ✅ | 1/1 installed (shims) |"); - expect(ordinaryShim).not.toContain("bd hooks install"); - hookOutput = JSON.stringify({ hooks: [{ ...shim, Outdated: true }] }); - const outdatedShim = await capture(); - expect(outdatedShim).toContain("| Git hooks | ⚠️ | 1/1 installed · 1 outdated |"); - expect(outdatedShim).toContain("pre-push: outdated"); - expect(outdatedShim).toContain("Verify with `bd hooks list`."); - hookOutput = JSON.stringify({ - hooks: [ - { Name: "pre-commit", Installed: true, Version: "", IsShim: false, Outdated: false }, - { Name: "post-merge", Installed: true, Version: "1.2.0", IsShim: false, Outdated: true }, - { Name: "pre-push", Installed: true, Version: "1.3.4", IsShim: true, Outdated: false }, - ], - }); - const report = await capture(); - expect(report).toContain("installed without a reported version"); - expect(report).toContain("outdated"); - expect(report).toContain("shim does not certify current wrapper policy"); - expect(report).toContain("| Git hooks | ⚠️ | 3/3 installed (1 shim) · 1 outdated · 1 unrecognized |"); - expect(report).toContain("| Sync target | ✅ | Resolved · origin |"); - expect(report).toContain("**Plugin** ✅ Healthy"); - expect(report).toContain("**Beads** ⚠️ Mismatch"); - expect(report).not.toMatch(/no.configured.remote|hook execution succeeded/); - expect(new Set(calls)).toEqual( - new Set(["version", "context --json", "hooks list --json", "--readonly dolt remote list --json --sandbox"]), - ); - } finally { - await cleanup(); - } -}); - -test("diagnostics identifies incomplete root guidance and a missing shared skill", async () => { - const root = await mkdtemp(path.join(tmpdir(), "health-incomplete-")); - const f = fakeContext({ directory: root }); - const c = commandFixture(f); - Object.assign(f.ctx.session, { get: async () => ({ agent: "build", location: { directory: root } }) }); - const bd = async (_directory: string, args: readonly string[]) => - args[0] === "version" - ? "bd 1.3.4" - : args[0] === "context" - ? JSON.stringify({ beads_dir: path.join(root, ".beads"), cwd_repo_root: root }) - : '{"hooks":[]}'; - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - const capture = async () => { - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - return (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow - .instructions; - }; - try { - await mkdir(path.join(root, "AGENTS.md")); - let report = await capture(); - expect(report.split("\nDetails: ")[0]).toContain("| AGENTS Configured | — | unreadable |"); - expect(report.split("\nDetails: ")[0]).toContain("unreadable"); - expect(report.split("\nDetails: ")[0]).toContain("shared: absent"); - expect(report).toContain("not a plugin failure"); - let details = JSON.parse(report.split("\nDetails: ")[1]!.split("\n")[0]!); - expect(details.findings.find((finding: { id: string }) => finding.id === "shared-skill-missing").class).toBe( - "note", - ); - await mkdir(path.join(root, ".agents", "skills", "beads", "SKILL.md"), { recursive: true }); - report = await capture(); - expect(report.split("\nDetails: ")[0]).toContain("shared: unreadable"); - details = JSON.parse(report.split("\nDetails: ")[1]!.split("\n")[0]!); - expect(details.findings.find((finding: { id: string }) => finding.id === "shared-skill-unreadable").class).toBe( - "failed", - ); - await rm(path.join(root, "AGENTS.md"), { recursive: true }); - await writeFile(path.join(root, "AGENTS.md"), "x".repeat(65_537)); - report = await capture(); - expect(report.split("\nDetails: ")[0]).toContain("truncated"); - expect(report).toContain("last-request"); - } finally { - await cleanup(); - await rm(root, { recursive: true, force: true }); - } -}); +test("host admission and diagnostics agree on unsupported versions", async () => { + for (const appVersion of [ + "2.0.29", + "2.1.1", + "2.2.5", + "2.2.6", + "2.2.8", + "2.4.0", + "2.4.3", + "3.0.0", + "2.3.0-beta.1", + "2.4.2-beta.1", + "2.3", + "unknown", + ]) { + const f = createHost({ appVersion }); + const warn = mock(() => {}); -test("diagnostics withholds hook observation when session location is unconfirmed", async () => { - const f = fakeContext(); - const c = commandFixture(f); - Object.assign(f.ctx.session, { - get: async () => { - throw new Error("session lookup failed"); - }, - }); - const bd = mock(async (_directory: string, _args: readonly string[]) => { - throw new Error("unexpected native collection"); - }); - const cleanup = await setupBeads(f.ctx, { bd, warn: () => {} }); - try { - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - const instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) - .ocBeadsWorkflow.instructions; - const snapshot = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - const hookFinding = snapshot.findings.find((finding: { id: string }) => finding.id === "hooks-unavailable"); - expect(hookFinding.class).toBe("unknown"); - expect(hookFinding.observation).toContain("withheld: session location unconfirmed"); - expect(instructions.split("\nDetails: ")[0]).not.toContain("[failed] beads / bd hooks list"); - expect(bd).not.toHaveBeenCalled(); - } finally { - await cleanup(); - } -}); + const cleanup = await setupBeads(f.ctx, { warn }); -test("diagnostics groups repeated hooks while retaining other findings and exact native evidence", () => { - const names = ["pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"]; - const missing = names.map((name) => ({ name, installed: false, version: "", shim: false, outdated: false })); - const shims = names.map((name) => ({ name, installed: true, version: "1.3.4", shim: true, outdated: false })); - const base = { - plugin: { name: "fixture", version: "1" }, - host: "2.3.0", - context: "ready", - guard: { kind: "ready", version: "1.3.4" }, - } satisfies DiagnosticsSnapshot; - for (const hooks of [missing, shims]) { - const snapshot: DiagnosticsSnapshot = { - ...base, - hooks, - local: { - witness: { state: "differ", recorded: "1.3.1", running: "1.3.4" }, - managedInstructions: { state: "available", full: 0 }, - sharedSkill: "readable", - }, - contextObservation: { version: "1.3.1", loadedAt: 1000 }, - }; - const report = renderHealthReport(snapshot, 2000, true); - const [summary, details] = report.split("\nDetails: "); - expect(summary).toContain("1.3.1 ≠ CLI 1.3.4"); - expect(summary).toContain("| Context | ⚠️ | Loaded under bd 1.3.1 |"); - const captured = JSON.parse(details!); - expect(captured.hooks).toEqual(hooks); - expect( - captured.findings.filter((finding: { producer: string }) => finding.producer === "bd hooks list"), - ).toHaveLength(1); - expect(report).toContain( - "https://github.com/gastownhall/beads/blob/7ef2fd05eb0cd3bdbde051f93cfc14ccf270cdde/docs/getting-started/upgrading.md", + expect(warn).toHaveBeenCalledWith(expect.stringContaining(`OpenCode ${appVersion}`)); + expect(warn).toHaveBeenCalledWith(expect.stringContaining(">=2.3.0 <2.4 || 2.4.1 || 2.4.2")); + expect(f.agents.size).toBe(0); + expect(f.hooks.size).toBe(0); + expect(renderHealthReport({ ...presentationFixture(), host: appVersion }, 2000)).toContain( + appVersion === "unknown" ? "| Host | — | not observed |" : `| Host | ❌ | OpenCode ${appVersion} unsupported |`, ); - } -}); - -test("diagnostic duplicate findings preserve root and last-request provenance", () => { - const requestAt = 1700000000000; - const captureAt = 1700000060000; - const report = renderHealthReport( - { - plugin: {}, - host: "2.3.0", - context: "ready", - guard: { kind: "ready" }, - hooks: [], - local: { - scope: "context cwd_repo_root", - managedInstructions: { state: "available", full: 2 }, - sharedSkill: "readable", - }, - requestInstructions: { at: requestAt, full: 2, retained: 1 }, - }, - captureAt, - true, - ); - const captured = JSON.parse(report.split("\nDetails: ")[1]!); - const root = captured.findings.find((f: { id: string }) => f.id === "duplicate-full"); - const request = captured.findings.find((f: { id: string }) => f.id === "request-full-duplicates"); - expect(root.scope).toBe("root-file observation: context cwd_repo_root"); - expect(root.observedAt).toBe(new Date(captureAt).toISOString()); - expect(request.scope).toBe("last observed request"); - expect(request.observedAt).toBe(new Date(requestAt).toISOString()); - expect(captured.requestInstructions.at).toBe(requestAt); -}); - -test("witness guidance links the pinned release guide", () => { - const report = renderHealthReport( - { - plugin: {}, - host: "2.3.0", - context: "ready", - guard: { kind: "ready" }, - hooks: [], - local: { witness: { state: "differ", recorded: "1.3.1", running: "1.3.4" } }, - }, - 0, - true, - ); - expect(report).toContain( - "https://github.com/gastownhall/beads/blob/7ef2fd05eb0cd3bdbde051f93cfc14ccf270cdde/docs/getting-started/upgrading.md", - ); -}); - -test("registered diagnostics uses the last request time for duplicate guidance", async () => { - const f = fakeContext(); - const c = commandFixture(f); - let now = 1_700_000_000_000; - const cleanup = await setupBeads(f.ctx, { - now: () => now, - warn: () => {}, - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "BODY" }, - }); - try { - const block = "<!-- BEGIN BEADS INTEGRATION v:1 profile:full -->BODY<!-- END BEADS INTEGRATION -->"; - const event: ContextEvent = { - sessionID: "s1", - agent: "build", - system: [{ type: "text", text: `${block}\n${block}` }], - }; - await f.hooks.get("context")!(event); - const observedAt = now; - now += 60_000; - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - const instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) - .ocBeadsWorkflow.instructions; - const report = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - const finding = report.findings.find((item: { id: string }) => item.id === "request-full-duplicates"); - expect(finding.scope).toBe("last observed request"); - expect(finding.observedAt).toBe(new Date(observedAt).toISOString()); - expect(report.requestInstructions.at).toBe(observedAt); - } finally { await cleanup(); } }); -/** Fixed observed fields shared by the representative compact-presentation cases. */ -function presentationFixture() { - return { - plugin: { name: "@snarkipus/opencode-beads", version: "2.2.1" }, - host: "2.3.0", - commands: { - registration: "registered", - lookup: "available", - truncated: true, - membershipTruncated: false, - expectedCount: 30, - effective: [], - missing: [], - mismatches: [], - }, - skill: { effective: ["oc-beads"], collision: "none detected" }, - typedContinuity: "enabled: qualified beta registration", - typedRegistration: "registered: beads namespace, code-mode-only", - requestCapability: { agent: "build", capabilities: { execute: true } }, - context: "ready", - contextObservation: { status: "ready", version: "1.3.4", loadedAt: 1000 }, - guard: { kind: "ready", version: "1.3.4", workspace: { path: "/fixture/.beads", repoRoot: "/fixture" } }, - local: { - scope: "context cwd_repo_root", - managedInstructions: { state: "available", full: 1, minimal: 0, codex: 1 }, - sharedSkill: "missing", - witness: { state: "match", recorded: "1.3.4", running: "1.3.4" }, - }, - hooks: ["pre-commit", "post-merge", "pre-push", "post-checkout", "prepare-commit-msg"].map((name) => ({ - name, - installed: true, - shim: true, - outdated: false, - version: "1.3.4", - })), - syncTarget: { state: "resolved", name: "origin" }, - requestInstructions: { at: 1000, full: 1, minimal: 0, codex: 1, replaced: 1, retained: 1 }, - persistence: "uncertain: no final-write guarantee", - } satisfies DiagnosticsSnapshot; -} - -test("command observations suggest reviewing customization only for complete missing or changed membership", () => { - const ready = presentationFixture(); - const hint = "Review command customization and rerun diagnostics."; - const cases: Array<{ commands: DiagnosticsSnapshot["commands"]; expected: boolean }> = [ - { commands: { ...ready.commands, missing: ["oc-beads:show"] }, expected: true }, - { commands: { ...ready.commands, mismatches: [{ name: "oc-beads:show" }] }, expected: true }, - { commands: ready.commands, expected: false }, - { commands: { ...ready.commands, lookup: "failed", missing: ["oc-beads:show"] }, expected: false }, - { commands: { ...ready.commands, membershipTruncated: true, missing: ["oc-beads:show"] }, expected: false }, - { commands: { ...ready.commands, missing: undefined }, expected: false }, - ]; - for (const c of cases) - expect(renderHealthReport({ ...ready, commands: c.commands }, 2000).includes(hint)).toBe(c.expected); -}); - -test("normal diagnostics uses compact tables and assessed severity with literal coverage", () => { - const ready = presentationFixture(); - const report = renderHealthReport(ready, 2000); - expect(report).toBe(`## Beads diagnostics — ✅ Healthy - -DATE: \`1970-01-01T00:00:02.000Z\` - -VERSION: @snarkipus/opencode-beads \`2.2.1\` - -PATH: \`/fixture\` - -Remote history not checked. - -**Plugin** ✅ Healthy - -| Check | Status | Value | -|---|---|---| -| Host | ✅ | OpenCode 2.3.0 | -| Commands | ✅ | 30/30 present | -| Skill | ✅ | oc-beads active · shared: absent | -| Typed tools | ✅ | Registered | -| Context | ✅ | Loaded | -| AGENTS Configured | ✅ | bd block | - -**Beads** ✅ Healthy - -| Check | Status | Value | -|---|---|---| -| bd CLI | ✅ | 1.3.4 | -| Workspace | ✅ | Located | -| Recorded bd version | ✅ | 1.3.4 = CLI | -| Git hooks | ✅ | 5/5 installed (shims) | -| Sync target | ✅ | Resolved · origin | -| Remote history | — | Not checked |`); - expect(report).toContain("## Beads diagnostics — ✅ Healthy"); - expect(report).toContain("**Plugin**"); - expect(report).toContain("**Beads**"); - expect(report).toContain("| Check | Status | Value |"); - expect(report).toContain("| Recorded bd version | ✅ | 1.3.4 = CLI |"); - expect(report).not.toMatch(/partial|Request instructions|Codex|descriptions/i); - expect(report).not.toMatch( - /Details:|Limits:|does not establish|model-mediated|unique build|liveQualification|no final-write guarantee|remote freshness/i, - ); - const first = renderHealthReport( - { - ...ready, - context: "unobserved: no cached context", - contextObservation: undefined, - requestInstructions: "unobserved", - requestCapability: undefined, - }, - 2000, - ); - expect(first).toBe(`## Beads diagnostics — ✅ Healthy - -DATE: \`1970-01-01T00:00:02.000Z\` - -VERSION: @snarkipus/opencode-beads \`2.2.1\` - -PATH: \`/fixture\` - -Remote history not checked. - -**Plugin** ✅ Healthy - -| Check | Status | Value | -|---|---|---| -| Host | ✅ | OpenCode 2.3.0 | -| Commands | ✅ | 30/30 present | -| Skill | ✅ | oc-beads active · shared: absent | -| Typed tools | ✅ | Registered | -| Context | — | Not yet loaded | -| AGENTS Configured | ✅ | bd block | - -**Beads** ✅ Healthy - -| Check | Status | Value | -|---|---|---| -| bd CLI | ✅ | 1.3.4 | -| Workspace | ✅ | Located | -| Recorded bd version | ✅ | 1.3.4 = CLI | -| Git hooks | ✅ | 5/5 installed (shims) | -| Sync target | ✅ | Resolved · origin | -| Remote history | — | Not checked |`); - expect(first).toContain("| Context | — | Not yet loaded |"); - expect(first).toContain("✅ Healthy"); - const unreadableSkill = renderHealthReport({ ...ready, local: { ...ready.local, sharedSkill: "unreadable" } }, 2000); - expect(unreadableSkill).toContain("| Skill | — | oc-beads active · shared: unreadable |"); - expect( - renderHealthReport({ ...ready, local: { ...ready.local, scope: "confirmed session directory" } }, 2000), - ).toContain("| AGENTS Configured | ✅ | bd block |"); - const vps = renderHealthReport( - { ...ready, hooks: ready.hooks.map((h) => ({ ...h, installed: false, shim: false, version: "" })) }, - 2000, - ); - expect(vps).toBe(`## Beads diagnostics — ✅ Healthy - -DATE: \`1970-01-01T00:00:02.000Z\` - -VERSION: @snarkipus/opencode-beads \`2.2.1\` - -PATH: \`/fixture\` - -Remote history not checked. - -**Plugin** ✅ Healthy - -| Check | Status | Value | -|---|---|---| -| Host | ✅ | OpenCode 2.3.0 | -| Commands | ✅ | 30/30 present | -| Skill | ✅ | oc-beads active · shared: absent | -| Typed tools | ✅ | Registered | -| Context | ✅ | Loaded | -| AGENTS Configured | ✅ | bd block | - -**Beads** ✅ Healthy - -| Check | Status | Value | -|---|---|---| -| bd CLI | ✅ | 1.3.4 | -| Workspace | ✅ | Located | -| Recorded bd version | ✅ | 1.3.4 = CLI | -| Git hooks | — | 0/5 installed · 5 missing/unreadable/unresolved | -| Sync target | ✅ | Resolved · origin | -| Remote history | — | Not checked |`); - const incompatible = renderHealthReport( - { - ...ready, - guard: { kind: "unsupported", installed: "1.3.0" }, - context: "withheld", - hooks: "failed: unsupported", - syncTarget: undefined, - }, - 2000, - ); - expect(incompatible).toBe(`## Beads diagnostics — ❌ Unhealthy - -DATE: \`1970-01-01T00:00:02.000Z\` - -VERSION: @snarkipus/opencode-beads \`2.2.1\` - -PATH: \`not observed\` - -bd CLI unavailable or below the supported minimum. Remote history not checked. - -**Plugin** ❌ Unhealthy - -| Check | Status | Value | -|---|---|---| -| Host | ✅ | OpenCode 2.3.0 | -| Commands | ✅ | 30/30 present | -| Skill | ✅ | oc-beads active · shared: absent | -| Typed tools | ✅ | Registered | -| Context | ❌ | Withheld | -| AGENTS Configured | ✅ | bd block | - -**Beads** ❌ Unhealthy - -| Check | Status | Value | -|---|---|---| -| bd CLI | ❌ | 1.3.0 (needs ≥1.3.1) | -| Workspace | — | not observed | -| Recorded bd version | ✅ | 1.3.4 = CLI | -| Git hooks | — | observation failed | -| Sync target | — | Unknown · native listing not performed | -| Remote history | — | Not checked | - -**Actions** - -- Install or upgrade bd to ≥1.3.1, then start a new session. Check: \`bd version\`.`); - expect(incompatible).toContain("❌ Unhealthy"); - expect(incompatible).toContain("| Git hooks | — | observation failed |"); - const noEvidence = renderHealthReport({}, 2000); - expect(noEvidence).not.toContain("✅ Healthy"); - expect(noEvidence).toContain("| Sync target | — | Unknown · native listing not performed |"); - expect(noEvidence).toContain("| Remote history | — | Not checked |"); - expect(noEvidence).toContain("No checks assessed"); -}); - -test("normal command membership, witness and write uncertainty keep distinct severity", () => { - const ready = presentationFixture(); - const partial = renderHealthReport( - { ...ready, commands: { ...ready.commands, membershipTruncated: true, missing: undefined } }, - 2000, - ); - expect(partial).toContain("| Commands | — | list incomplete |"); - const partialChanged = renderHealthReport( - { - ...ready, - commands: { - ...ready.commands, - membershipTruncated: true, - missing: undefined, - mismatches: [{ name: "oc-beads:show" }], - }, - }, - 2000, - ); - expect(partialChanged).toContain("| Commands | — | list incomplete · 1 changed |"); - const differs = renderHealthReport( - { ...ready, local: { ...ready.local, witness: { state: "differ", recorded: "1.3.1", running: "1.3.4" } } }, - 2000, - ); - expect(differs).toContain("| Recorded bd version | ⚠️ | 1.3.1 ≠ CLI 1.3.4 |"); - expect(differs).not.toContain("❌ Unhealthy"); - const gap = renderHealthReport({ ...ready, persistence: "update task-1: uncertain; readback required" }, 2000); - expect(gap).toContain("update task-1"); - expect(gap).toContain("⚠️ Mismatch"); -}); +test.each(["2.3.0", "2.3.8", "2.4.1", "2.4.2"])( + "host admission and diagnostics agree on supported version %s", + async (appVersion) => { + const f = createHost({ appVersion }); + const cleanup = await setupBeads(f.ctx, { + runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" }, + }); -test("registered diagnostics handles exact selectors locally and replays captured output once", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const bd = mock(async (_directory: string, args: readonly string[]) => { - switch (args.join(" ")) { - case "version": - return "bd version 1.3.4"; - case "context --json": - return '{"beads_dir":"/fixture/.beads","backend":"dolt","dolt_mode":"server","server_port":3307}'; - case "hooks list --json": - return '{"hooks":[]}'; - case "--readonly dolt remote list --json --sandbox": - return '[{"name":"origin","url":"https://user:remote-secret@example.invalid","sql_url":"https://sql-secret.example.invalid","cli_url":"https://cli-secret.example.invalid","status":"ok"}]'; - default: - throw new Error("unexpected command"); - } - }); - const prime = mock(async () => "PRIME INCLUDING MEMORY"); - const cleanup = await setupBeads(f.ctx, { bd, now: () => 2000, warn: () => {}, runPrime: prime }); - try { - for (const text of [ - "", - " DeTaIlS ", - " ReMoTe ", - " DeTaIlS ReMoTe\n", - "remote please", - "remote details", - "details remote", - " HeLp ", - "help me", - "help\n", - ]) { - const input = { ...c.invocation, prompt: { ...c.invocation.prompt, text } }; - const beforeCalls = bd.mock.calls.length; - await c.commands().get("oc-beads:diagnostics")!.execute(input); - const sent = c.prompt.mock.calls.at(-1)![0]; - const snapshot = (sent.metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; - const selector = text.trim().toLowerCase(); - expect(snapshot.instructions.includes("Details: ")).toBe(selector === "details" || selector === "details remote"); - const framedReport = snapshot.instructions - .split("\nBEGIN_DIAGNOSTIC_REPORT\n")[1] - ?.split("\nEND_DIAGNOSTIC_REPORT\n")[0]; - expect(framedReport).toBeDefined(); - expect(snapshot.instructions).toEndWith("\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n"); - if (selector === "help") { - expect(bd.mock.calls.length).toBe(beforeCalls); - expect(snapshot.instructions).toContain(diagnosticPresentation.DIAGNOSTICS_HELP); - } else { - expect(bd.mock.calls.slice(beforeCalls)).toEqual([ - [f.ctx.location.directory, ["version"]], - [f.ctx.location.directory, ["context", "--json"]], - [f.ctx.location.directory, ["hooks", "list", "--json"]], - [f.ctx.location.directory, ["--readonly", "dolt", "remote", "list", "--json", "--sandbox"]], - ]); - expect(framedReport).toContain("| Sync target | ✅ | Resolved · origin |"); - expect(framedReport).toContain("| Remote history | — | Not checked"); - expect(framedReport!.includes("No qualified Beads history probe is available")).toBe( - selector === "remote" || selector === "details remote", - ); - expect(snapshot.instructions).not.toMatch(/secret|Check failed|cannot resolve|no.configured.remote/); - } - expect(sent.text).toBe(`/oc-beads:diagnostics${text ? `${/[\r\n]/.test(text) ? "\n" : " "}${text}` : ""}`); - expect(sent.files).toBe(input.prompt.files); - expect(sent.delivery).toBe(input.delivery); - if (!prime.mock.calls.length) { - const system = await f.request("s1", "build"); - expect(system.join("\n")).toContain("PRIME INCLUDING MEMORY"); - expect(prime).toHaveBeenCalledWith(f.ctx.location.directory, ["--full"]); - } - const count = bd.mock.calls.length; - const stored = storedUserMessage("presented", String(sent.text), { - ocBeadsWorkflow: { version: 1, ...snapshot }, + expect([...f.hooks.keys()]).toEqual(["context", "compaction"]); + expect([...f.agents.keys()]).toEqual(["beads-task-agent"]); + expect(renderHealthReport({ ...presentationFixture(), host: appVersion }, 2000)).toContain( + `| Host | ✅ | OpenCode ${appVersion} |`, + ); + await cleanup(); + }, +); + +test("registers the bounded task agent as a subagent and keeps Luna opt-in", async () => { + const ready = { runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" } }; + const vanilla = createHost(); + const cleanupVanilla = await setupBeads(vanilla.ctx, ready); + expect([...vanilla.agents.keys()]).toEqual(["beads-task-agent"]); + const agent = vanilla.agents.get("beads-task-agent"); + expect(agent?.mode).toBe("subagent"); + expect(agent?.name).toBe("beads-task-agent"); + expect(agent?.model).toBeUndefined(); + expect(String(agent?.system)).toContain("An exact assignment or explicit one-bead mode ends with that bead"); + expect(String(agent?.system)).toContain("bd update <id> --claim --json --actor='<executor-actor>' --sandbox"); + expect(typeof agent?.description).toBe("string"); + expect(agent?.permissions).toEqual([...TASK_AGENT_PERMISSIONS]); + expect(agent?.steps).toBe(DEFAULT_TASK_AGENT_STEPS); + cleanupVanilla(); + + const luna = createHost({ pluginOptions: { luna: true } }); + const cleanupLuna = await setupBeads(luna.ctx, ready); + const lunaAgent = luna.agents.get("beads-task-agent-luna"); + expect(lunaAgent?.model).toEqual({ providerID: "openai", id: "gpt-6-luna", variant: "max" }); + expect(lunaAgent?.system).toBe(luna.agents.get("beads-task-agent")?.system); + expect(lunaAgent?.mode).toBe("subagent"); + cleanupLuna(); +}); + +test("registers Terra independently and with Luna, with shared policy and context", async () => { + const ready = { runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" } }; + for (const luna of [false, true]) { + const f = createHost({ pluginOptions: { terra: true, luna, taskAgentSteps: 12 } }); + const cleanup = await setupBeads(f.ctx, ready); + expect([...f.agents.keys()]).toEqual( + luna + ? ["beads-task-agent", "beads-task-agent-luna", "beads-task-agent-terra"] + : ["beads-task-agent", "beads-task-agent-terra"], + ); + const base = f.agents.get("beads-task-agent")!; + const terra = f.agents.get("beads-task-agent-terra")!; + expect(base.model).toBeUndefined(); + expect(terra.model).toEqual({ providerID: "openai", id: "gpt-6.1-terra", variant: "medium" }); + expect(terra.system).toBe(base.system); + expect(terra.description).toBe(base.description); + expect(terra.mode).toBe(base.mode); + expect(terra.permissions).toEqual(base.permissions); + expect(terra.steps).toBe(base.steps); + if (luna) + expect(f.agents.get("beads-task-agent-luna")?.model).toEqual({ + providerID: "openai", + id: "gpt-6-luna", + variant: "max", }); - Object.assign(f.ctx.session, { context: async () => [stored] }); - for (const kind of ["context", "compaction"]) { - const event: ContextEvent = { - sessionID: "s1", - agent: "build", - system: [], - messages: [Message.make({ id: stored.id, role: "user", content: String(sent.text) })], - }; - await f.hooks.get(kind)!(event); - expect(event.messages![0]!.content[0]).toEqual(Message.text(snapshot.instructions)); - expect(event.messages![0]!.content[1]).toEqual(Message.text(String(sent.text))); - const once = JSON.stringify(event.messages); - await f.hooks.get(kind)!(event); - expect(JSON.stringify(event.messages)).toBe(once); - } - expect(bd.mock.calls.length).toBe(count); - } - } finally { - await cleanup(); - } -}); - -test("registered command completeness separates membership truncation from description clipping", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const cleanup = await setupBeads(f.ctx, { - bd: async () => '{"hooks":[]}', - warn: () => {}, - runtime: { guard: async () => ({ kind: "ready" }) }, - }); - try { - const owned = c.commands().get("oc-beads:ready")!; - c.callbacks.push((editor) => editor.add({ ...owned, description: "x".repeat(600) })); - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - let instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) - .ocBeadsWorkflow.instructions; - let report = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - expect(report.commands.truncated).toBe(true); - expect(report.commands.membershipTruncated).toBe(false); - expect(report.commands.expectedCount).toBe(30); - expect(instructions).toContain("| Commands | ✅ | 30/30 present |"); - c.callbacks.push((editor) => editor.add({ ...owned, description: "custom changed" })); - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) - .ocBeadsWorkflow.instructions; - expect(instructions).toContain("| Commands | ⚠️ | 30/30 · 1 changed |"); - c.callbacks.push((editor) => { - for (let i = 0; i < 130; i++) editor.add({ name: `custom-${i}`, description: "custom", execute: async () => {} }); - }); - await c.commands().get("oc-beads:diagnostics")!.execute(c.detailsInvocation); - instructions = (c.prompt.mock.calls.at(-1)![0].metadata as { ocBeadsWorkflow: { instructions: string } }) - .ocBeadsWorkflow.instructions; - report = JSON.parse(instructions.split("\nDetails: ")[1]!.split("\n")[0]!); - expect(report.commands.membershipTruncated).toBe(true); - expect(instructions).toContain("| Commands | — | list incomplete · 1 changed |"); - } finally { + expect(await f.request("terra-child", "beads-task-agent-terra")).toEqual([ + renderBeadsContext("PRIME", "task-agent", { sessionID: "terra-child", agent: "beads-task-agent-terra" }), + ]); await cleanup(); } }); -test("AGENTS Configured recognizes markers while unknown guidance stays neutral", () => { - const ready = presentationFixture(); - const rootObservations: PluginHealthObservation["managedInstructions"][] = [ - { state: "available", full: 0, minimal: 0, codex: 0 }, - { state: "missing" }, - { state: "unreadable" }, - { state: "truncated" }, - ]; - for (const managedInstructions of rootObservations) { - const report = renderHealthReport({ ...ready, local: { ...ready.local, managedInstructions } }, 2000); - expect(report).toContain("| AGENTS Configured | — |"); - expect(report).not.toMatch(/partial|Request instructions|full ·|Codex/); - } - for (const counts of [ - { full: 0, minimal: 1, codex: 0 }, - { full: 0, minimal: 0, codex: 1 }, - ]) { - expect( - renderHealthReport( - { ...ready, local: { ...ready.local, managedInstructions: { state: "available", ...counts } } }, - 2000, - ), - ).toContain("| AGENTS Configured | ✅ | bd block |"); - } - expect( - renderHealthReport( - { ...ready, local: { ...ready.local, managedInstructions: { state: "available", full: 2 } } }, - 2000, - ), - ).toContain("| AGENTS Configured | ⚠️ | duplicate bd blocks |"); - const unrecognized = renderHealthReport( - { ...ready, hooks: [{ name: "pre-commit", installed: true, version: "", shim: false, outdated: false }] }, - 2000, - ); - expect(unrecognized).toContain("1 unrecognized"); - expect(unrecognized).not.toContain("not bd"); -}); - -test("command names remain measurable without hiding missing or changed entries", () => { - const ready = presentationFixture(); - expect( - renderHealthReport( - { - ...ready, - commands: { ...ready.commands, missing: ["oc-beads:ready"], mismatches: [{ name: "oc-beads:show" }] }, - }, - 2000, - ), - ).toContain("| Commands | ⚠️ | 29/30 · 1 missing · 1 changed |"); - expect(renderHealthReport({ ...ready, commands: { ...ready.commands, lookup: "failed" } }, 2000)).toContain( - "| Commands | — | not observed |", - ); - const details = renderHealthReport(ready, 2000, true); - expect(details).toContain('"requestInstructions":{"at":1000'); - expect(details).toContain('"truncated":true'); - for (const row of renderHealthReport({ ...ready, persistence: "update unresolved" }, 2000) - .split("\n") - .filter((line) => line.startsWith("| ") && !line.startsWith("| Check"))) { - expect(diagnosticPresentation.DIAGNOSTICS_HELP).toContain(row.split(" | ")[0]!.slice(2)); - } -}); - -test("diagnostic header metadata uses observed root and exact code-populated values", () => { - const fixture = presentationFixture(); - const report = renderHealthReport(fixture, 2000); - expect(report).toStartWith( - "## Beads diagnostics — ✅ Healthy\n\nDATE: `1970-01-01T00:00:02.000Z`\n\nVERSION: @snarkipus/opencode-beads `2.2.1`\n\nPATH: `/fixture`\n\nRemote history not checked.\n\n**Plugin**", - ); - expect(report.match(/DATE:/g)).toHaveLength(1); - expect(report.match(/VERSION:/g)).toHaveLength(1); - expect(report.match(/PATH:/g)).toHaveLength(1); - expect(report).not.toContain("/fixture/.beads"); - const missingRoot = renderHealthReport( - { ...fixture, guard: { ...fixture.guard, workspace: { path: "/fixture/.beads" } } }, - 2000, - true, - ); - expect(missingRoot).toContain("PATH: `not observed`"); - expect(missingRoot).toContain('"path":"/fixture/.beads"'); - expect( - renderHealthReport( - { - ...fixture, - guard: { ...fixture.guard, workspace: { path: "/different/.beads", repoRoot: "/observed/root/" } }, - }, - 2000, - ), - ).toContain("PATH: `/observed/root/`"); - const mismatch = renderHealthReport( - { ...fixture, hooks: fixture.hooks.map((hook) => ({ ...hook, shim: false, outdated: true })) }, - 2000, - ); - expect(mismatch.indexOf("PATH:")).toBeLessThan(mismatch.indexOf("Git hooks need attention.")); -}); - -test("actual Chat serializer keeps a registered diagnostic report separated from its invocation", async () => { - const f = fakeContext(); - const c = commandFixture(f); - const cleanup = await setupBeads(f.ctx, { - bd: async () => '{"hooks":[]}', - now: () => 2000, - warn: () => {}, - runtime: { guard: async () => ({ kind: "ready" }), prime: async () => "PRIME" }, - }); - try { - await c - .commands() - .get("oc-beads:diagnostics")! - .execute({ ...c.invocation, prompt: { ...c.invocation.prompt, text: "" } }); - const sent = c.prompt.mock.calls.at(-1)![0]; - const snapshot = (sent.metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; - const stored = storedUserMessage( - "serialized-diagnostic", - String(sent.text), - sent.metadata as StoredUserMessage["metadata"], - ); - Object.assign(f.ctx.session, { context: async () => [stored] }); - const event: ContextEvent = { - sessionID: "s1", - agent: "build", - system: [], - messages: [Message.make({ id: stored.id, role: "user", content: String(sent.text) })], - }; - await f.hooks.get("context")!(event); - const body = await Effect.runPromise( - serializeChatRequest({ - model: { - id: "fixture-no-network", - provider: "openai", - route: { endpoint: { baseURL: "https://fixture.invalid/v1" } }, - capabilities: {}, - compatibility: {}, - }, - system: [], - messages: event.messages, - tools: [], - } as unknown as Parameters<typeof serializeChatRequest>[0]), - ); - const content = body.messages.find((message) => message.role === "user")?.content; - expect(content).toContain("\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n/oc-beads:diagnostics"); - expect(content).toBe(`${snapshot.instructions}${String(sent.text)}`); - expect(content).not.toContain("`/oc-beads:diagnostics"); - } finally { - await cleanup(); - } +test("caps worker steps from taskAgentSteps, and 0 removes the cap", async () => { + const ready = { runtime: { guard: async () => ({ kind: "ready" as const }), prime: async () => "PRIME" } }; + const capped = createHost({ pluginOptions: { taskAgentSteps: 25, luna: true } }); + (await setupBeads(capped.ctx, ready))(); + expect(capped.agents.get("beads-task-agent")?.steps).toBe(25); + expect(capped.agents.get("beads-task-agent-luna")?.steps).toBe(25); + const uncapped = createHost({ pluginOptions: { taskAgentSteps: 0 } }); + (await setupBeads(uncapped.ctx, ready))(); + expect(uncapped.agents.get("beads-task-agent")?.steps).toBeUndefined(); + const invalid = createHost({ pluginOptions: { taskAgentSteps: "lots" } }); + (await setupBeads(invalid.ctx, ready))(); + expect(invalid.agents.get("beads-task-agent")?.steps).toBe(DEFAULT_TASK_AGENT_STEPS); }); diff --git a/tests/instructions.test.ts b/tests/instructions.test.ts index 94e6fcc..fe21723 100644 --- a/tests/instructions.test.ts +++ b/tests/instructions.test.ts @@ -37,35 +37,38 @@ describe("minimizeBeadsInstructions", () => { }); test("collapses bd's full-profile and Codex blocks into one pointer", () => { const text = [USER_BEFORE, FULL_BLOCK, CODEX_BLOCK, USER_AFTER].join("\n\n"); - const result = minimizeBeadsInstructions(text, text); - expect(result.replaced).toBe(2); - expect(result.text).toBe([USER_BEFORE, MINIMAL_BEADS_POINTER, "", USER_AFTER].join("\n\n")); - expect(result.text.match(/opencode-beads plugin/g)).toHaveLength(1); - expect(result.text).not.toContain("BEGIN BEADS"); + expect(minimizeBeadsInstructions(text, text)).toEqual({ + text: [USER_BEFORE, MINIMAL_BEADS_POINTER, "", USER_AFTER].join("\n\n"), + replaced: 2, + }); }); test("leaves minimal-profile blocks and text without bd blocks unchanged", () => { const minimal = [USER_BEFORE, MINIMAL_BLOCK, USER_AFTER].join("\n\n"); - expect(minimizeBeadsInstructions(minimal)).toEqual({ text: minimal, replaced: 0 }); + expect(minimizeBeadsInstructions(minimal, minimal)).toEqual({ text: minimal, replaced: 0 }); expect(minimizeBeadsInstructions(USER_BEFORE)).toEqual({ text: USER_BEFORE, replaced: 0 }); }); test("never removes an unterminated block", () => { const unterminated = `${USER_BEFORE}\n\n<!-- BEGIN BEADS INTEGRATION v:1 profile:full hash:x -->\ntruncated`; - expect(minimizeBeadsInstructions(unterminated)).toEqual({ text: unterminated, replaced: 0 }); + expect(minimizeBeadsInstructions(unterminated, "truncated")).toEqual({ text: unterminated, replaced: 0 }); }); }); describe("minimizeSystemParts", () => { test("rewrites only text parts that contain bd blocks", () => { + const systemText = "You are an AI agent running in OpenCode."; const parts = [ - { type: "text", text: "You are an AI agent running in OpenCode." }, + { type: "text", text: systemText }, { type: "text", text: `Instructions from: /repo/AGENTS.md\n${FULL_BLOCK}` }, - { type: "image" }, + { type: "image", text: FULL_BLOCK }, ]; expect(minimizeSystemParts(parts, FULL_BLOCK)).toBe(1); - expect(parts[0]?.text).toBe("You are an AI agent running in OpenCode."); - expect(parts[1]?.text).toBe(`Instructions from: /repo/AGENTS.md\n${MINIMAL_BEADS_POINTER}`); + expect(parts).toEqual([ + { type: "text", text: systemText }, + { type: "text", text: `Instructions from: /repo/AGENTS.md\n${MINIMAL_BEADS_POINTER}` }, + { type: "image", text: FULL_BLOCK }, + ]); }); }); diff --git a/tests/opencode-release-monitor.test.ts b/tests/opencode-release-monitor.test.ts index d58d4de..c7b350d 100644 --- a/tests/opencode-release-monitor.test.ts +++ b/tests/opencode-release-monitor.test.ts @@ -1,7 +1,8 @@ import { afterEach, describe, expect, test } from "bun:test"; +import assert from "node:assert/strict"; import * as fs from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join, resolve } from "node:path"; +import { delimiter, join, resolve } from "node:path"; const root = resolve(import.meta.dir, ".."); const reviewedVersion = (await fs.readFile(join(root, ".github/opencode-reviewed-version"), "utf8")).trim(); @@ -12,44 +13,68 @@ afterEach(async () => { await Promise.all(directories.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); }); -/** Exercise the actual workflow shell, mocking only GitHub retrieval and SDK commands. */ -async function monitor( - version: string, - options: { - sdkFailure?: boolean; - unavailable?: boolean; - prerelease?: boolean; - noMatch?: boolean; - crlf?: boolean; - } = {}, -) { - let workflow = await fs.readFile(join(root, ".github/workflows/beads-contract.yml"), "utf8"); - if (options.crlf) workflow = workflow.replace(/\r?\n/g, "\r\n"); - workflow = workflow.replace(/\r\n/g, "\n"); - const job = workflow.split(" opencode-release:\n")[1]?.split("\n source-comparison:\n")[0]; - expect(job, "the existing daily workflow must include an independent OpenCode release job").toBeDefined(); - const blocks = [...job!.matchAll(/ run: \|\n((?: .*\n|\n)+)/g)].map((match) => - match[1]!.replace(/^ /gm, ""), - ); - expect(blocks).toHaveLength(3); - expect(job).toContain("always() && steps.opencode-release.outcome == 'success'"); - expect(job).not.toContain("needs:"); +const workflow = await fs.readFile(join(root, ".github/workflows/beads-contract.yml"), "utf8"); + +type WorkflowStep = { id?: string; if?: string; env?: Record<string, string>; run?: string }; + +function releaseSteps(source: string) { + const { jobs } = Bun.YAML.parse(source) as { jobs: Record<string, { needs?: unknown; steps: WorkflowStep[] }> }; + const job = jobs["opencode-release"]; + if (!job) throw new Error("The workflow must include an independent OpenCode release job"); + expect(job).not.toHaveProperty("needs"); + const steps = job.steps.filter((step): step is WorkflowStep & { run: string } => typeof step.run === "string"); + const version = "${{ steps.opencode-release.outputs.version }}"; + expect(steps).toMatchObject([ + { id: "opencode-release", env: { REQUESTED: "${{ inputs.opencode_version }}" } }, + { id: "sdk-check", env: { VERSION: version } }, + { + env: { + VERSION: version, + REVIEWED: "${{ steps.opencode-release.outputs.reviewed }}", + SDK_OUTCOME: "${{ steps.sdk-check.outcome }}", + }, + }, + ]); + const [release, sdk, report] = steps; + assert(release && sdk && report, "Expected three OpenCode release shell steps"); + expect(sdk).not.toHaveProperty("if"); + expect(sdk).not.toHaveProperty("continue-on-error"); + const condition = report.if?.trim().replace(/^\$\{\{\s*|\s*\}\}$/g, ""); + expect(condition).toMatch(/^always\s*\(\s*\)\s*&&\s*steps\.opencode-release\.outcome\s*==\s*'success'$/); + return { release: release.run, sdk: sdk.run, report: report.run }; +} +type ReleaseOptions = { + unavailable?: boolean; + prerelease?: boolean; + noMatch?: boolean; +}; + +const originalSdk = "2.2.6"; +const originalLock = "original-lock\n"; + +async function releaseFixture(version: string, options: ReleaseOptions & { sdkFailure?: boolean }) { const directory = await fs.mkdtemp(join(tmpdir(), "oc-release-monitor-")); directories.push(directory); const repo = join(directory, "repo"); const bin = join(directory, "bin"); const scratch = join(directory, "scratch"); await Promise.all([fs.mkdir(join(repo, ".github"), { recursive: true }), fs.mkdir(bin), fs.mkdir(scratch)]); - const manifest = JSON.stringify({ devDependencies: { "@opencode/plugin": "2.2.6" }, marker: "unchanged" }); + const manifest = JSON.stringify({ devDependencies: { "@opencode/plugin": originalSdk }, marker: "unchanged" }); await fs.writeFile(join(repo, "package.json"), manifest); - await fs.writeFile(join(repo, "bun.lock"), "original-lock\n"); + await fs.writeFile(join(repo, "bun.lock"), originalLock); await fs.copyFile(join(root, ".github/opencode-reviewed-version"), join(repo, ".github/opencode-reviewed-version")); + // Use real Git only in the fixture, without inherited Git routing, hooks or signing. + const gitEnv = { + PATH: process.env.PATH, + GIT_CONFIG_NOSYSTEM: "1", + GIT_CONFIG_GLOBAL: "/dev/null", + }; const git = async (...args: string[]) => { - const p = Bun.spawn(["git", ...args], { cwd: repo, stdout: "pipe", stderr: "pipe" }); + const p = Bun.spawn(["git", ...args], { cwd: repo, env: gitEnv, stdout: "pipe", stderr: "pipe" }); expect(await p.exited, await new Response(p.stderr).text()).toBe(0); }; - await git("init", "--quiet"); + await git("init", "--quiet", "--template="); await git("add", "."); await git( "-c", @@ -64,7 +89,19 @@ async function monitor( ); await fs.writeFile( join(bin, "gh"), - '#!/usr/bin/env bash\nif [[ "$GH_FAILURE" == 1 ]]; then exit 22; fi\nif [[ "$1" == api ]]; then printf "%s\\n" "$RELEASE_PAGES"; elif [[ "$3" == "$EXPECTED_TAG" ]]; then printf "%s\\n" "$RELEASE_JSON"; else printf "%s\\n" "$LEGACY_RELEASE_JSON"; fi\n', + String.raw`#!/usr/bin/env bash +if [[ "$GH_FAILURE" == 1 ]]; then exit 22; fi +case "$1 $2" in + "api graphql") printf "%s\n" "$RELEASE_PAGES" ;; + "release view") + if [[ "$3" == "$EXPECTED_TAG" ]]; then + printf "%s\n" "$RELEASE_JSON" + else + printf "%s\n" "$LEGACY_RELEASE_JSON" + fi ;; + *) exit 64 ;; +esac +`, { mode: 0o755 }, ); await fs.writeFile(join(bin, "bun"), '#!/usr/bin/env bash\nexec "$BUN_EXECUTABLE" "$SDK_STUB" "$@"\n', { @@ -80,7 +117,9 @@ const args = process.argv.slice(2); const manifest = JSON.parse(await fs.readFile("package.json", "utf8")); if (args[0] === "install") { if (!args.includes("--ignore-scripts")) throw new Error("SDK installation must not run lifecycle scripts"); - if (!relative(process.cwd(), process.env.BUN_INSTALL_CACHE_DIR!).startsWith("..")) throw new Error("Cache must be outside source"); + const cache = process.env.BUN_INSTALL_CACHE_DIR!; + if (!relative(process.cwd(), cache).startsWith("../")) throw new Error("Cache must be outside source"); + await fs.writeFile(cache + "/fixture-cache", "inert cache entry"); await fs.mkdir("node_modules/@opencode/plugin", { recursive: true }); await fs.writeFile("node_modules/@opencode/plugin/package.json", JSON.stringify({ version: manifest.devDependencies["@opencode/plugin"] })); await fs.writeFile("bun.lock", "candidate-lock"); @@ -95,8 +134,8 @@ if (process.env.SDK_FAILURE === "1" && args[0] === "test") process.exit(33); const callLog = join(directory, "calls.jsonl"); await fs.writeFile(output, ""); const env = { - ...process.env, - PATH: `${bin}${process.platform === "win32" ? ";" : ":"}${process.env.PATH}`, + ...gitEnv, + PATH: [bin, process.env.PATH].join(delimiter), GITHUB_WORKSPACE: repo, RUNNER_TEMP: scratch, GITHUB_OUTPUT: output, @@ -114,32 +153,18 @@ if (process.env.SDK_FAILURE === "1" && args[0] === "test") process.exit(33); isPrerelease: false, url: "https://github.com/anomalyco/opencode/releases/tag/v1.19.5", }), - RELEASE_PAGES: JSON.stringify([ - { - data: { - repository: { - releases: { - nodes: [ - { tagName: "process-daemon-v0.5.2", isDraft: false, isPrerelease: false }, - { tagName: "v1.19.5", isDraft: false, isPrerelease: false }, - { tagName: "v9.0.0", isDraft: false, isPrerelease: true }, - { tagName: "v8.0.0", isDraft: true, isPrerelease: false }, - ...(options.noMatch ? [] : [{ tagName: `v${reviewedVersion}`, isDraft: false, isPrerelease: false }]), - ], - }, - }, - }, - }, - { - data: { - repository: { - releases: { - nodes: options.noMatch ? [] : [{ tagName: `v${version}`, isDraft: false, isPrerelease: false }], - }, - }, - }, - }, - ]), + RELEASE_PAGES: JSON.stringify( + [ + [ + { tagName: "process-daemon-v0.5.2", isDraft: false, isPrerelease: false }, + { tagName: "v1.19.5", isDraft: false, isPrerelease: false }, + { tagName: "v9.0.0", isDraft: false, isPrerelease: true }, + { tagName: "v8.0.0", isDraft: true, isPrerelease: false }, + ...(options.noMatch ? [] : [{ tagName: `v${reviewedVersion}`, isDraft: false, isPrerelease: false }]), + ], + options.noMatch ? [] : [{ tagName: `v${version}`, isDraft: false, isPrerelease: false }], + ].map((nodes) => ({ data: { repository: { releases: { nodes } } } })), + ), RELEASE_JSON: JSON.stringify({ tagName: `v${version}`, isDraft: false, @@ -161,11 +186,14 @@ if (process.env.SDK_FAILURE === "1" && args[0] === "test") process.exit(33); ]); return { exitCode, stdout, stderr }; } - const release = await shell(blocks[0]!); - if (release.exitCode !== 0) { - expect(await fs.readFile(output, "utf8")).toBe(""); - return { release, sdk: undefined, review: undefined, calls: [], summary: "" }; - } + return { repo, scratch, manifest, output, summary, callLog, shell }; +} + +async function monitor(version: string, { sdkFailure, crlf }: { sdkFailure?: boolean; crlf?: boolean } = {}) { + const steps = releaseSteps(crlf ? workflow.replace(/\r?\n/g, "\r\n") : workflow); + const { repo, scratch, manifest, output, summary, callLog, shell } = await releaseFixture(version, { sdkFailure }); + const release = await shell(steps.release); + expect(release.exitCode, release.stderr).toBe(0); const outputs = Object.fromEntries( (await fs.readFile(output, "utf8")) .trim() @@ -174,32 +202,44 @@ if (process.env.SDK_FAILURE === "1" && args[0] === "test") process.exit(33); ); expect(outputs.version).toBe(version); expect(outputs.reviewed).toBe(reviewedVersion); - const sdk = await shell(blocks[1]!, { VERSION: outputs.version! }); - // Actions runs this always-step even if the SDK step failed. - const review = await shell(blocks[2]!, { + const sdk = await shell(steps.sdk, { VERSION: outputs.version! }); + // Supply the Actions outcome expression locally so the report shell sees the SDK result. + const review = await shell(steps.report, { VERSION: outputs.version!, REVIEWED: outputs.reviewed!, SDK_OUTCOME: sdk.exitCode === 0 ? "success" : "failure", }); - const calls = (await fs.readFile(callLog, "utf8")) + const calls: { args: string[]; installed: string; declared: string; lock: string }[] = ( + await fs.readFile(callLog, "utf8") + ) .trim() .split("\n") .map((line) => JSON.parse(line)); expect(await fs.readFile(join(repo, "package.json"), "utf8")).toBe(manifest); - expect(await fs.readFile(join(repo, "bun.lock"), "utf8")).toBe("original-lock\n"); + expect(await fs.readFile(join(repo, "bun.lock"), "utf8")).toBe(originalLock); expect((await fs.readFile(join(repo, ".github/opencode-reviewed-version"), "utf8")).trim()).toBe(reviewedVersion); expect((await fs.readdir(scratch)).sort()).toEqual(["opencode-release.json", "opencode-releases.json"]); - return { release, sdk, review, calls, summary: await fs.readFile(summary, "utf8") }; + return { sdk, review, calls, summary: await fs.readFile(summary, "utf8") }; +} + +async function expectResolutionFailure(options: ReleaseOptions, files: readonly string[], exitCode: number) { + const { release } = releaseSteps(workflow); + const { output, summary, scratch, shell } = await releaseFixture(nextVersion, options); + const result = await shell(release); + // The redirects show which resolver stages were reached, even when a request fails. + expect((await fs.readdir(scratch)).sort()).toEqual([...files]); + expect(result.exitCode, result.stderr).toBe(exitCode); + expect(await fs.readFile(output, "utf8")).toBe(""); + expect(await Bun.file(summary).exists()).toBeFalse(); } // These literal Bash/Git/jq blocks target the Ubuntu-only maintenance job. // Product Windows coverage and the platform-independent notifier test remain enabled. describe.skipIf(process.platform === "win32")("OpenCode stable-release monitoring", () => { - test("already reviewed release runs exact SDK checks without advancing the pinned baseline", async () => { + test("reviewed release uses the exact SDK version and check commands from CRLF YAML", async () => { const result = await monitor(reviewedVersion, { crlf: true }); - expect(result.release.exitCode).toBe(0); - expect(result.sdk?.exitCode).toBe(0); - expect(result.review?.exitCode).toBe(0); + expect(result.sdk.exitCode).toBe(0); + expect(result.review.exitCode).toBe(0); expect(result.calls.map((call) => call.args)).toEqual([ ["install", "--ignore-scripts"], ["test"], @@ -208,53 +248,45 @@ describe.skipIf(process.platform === "win32")("OpenCode stable-release monitorin ]); expect(result.calls.every((call) => call.installed === reviewedVersion)).toBeTrue(); expect( - result.calls.slice(1).every((call) => call.declared === "2.2.6" && call.lock === "original-lock\n"), + result.calls.slice(1).every((call) => call.declared === originalSdk && call.lock === originalLock), ).toBeTrue(); expect(result.summary).toContain("SDK checks: success"); expect(result.summary).toContain( `Release: [v${reviewedVersion}](https://github.com/anomalyco/opencode/releases/tag/v${reviewedVersion})`, ); expect(result.summary).toContain("not live-host/model qualification"); - expect(result.review?.stdout).not.toContain("::error::"); + expect(result.review.stdout).not.toContain("::error::"); }); test("new stable release requires human review even when SDK checks pass", async () => { const result = await monitor(nextVersion); - expect(result.sdk?.exitCode).toBe(0); - expect(result.review?.exitCode).toBe(1); - expect(result.review?.stdout).toContain(`::error::OpenCode ${nextVersion}`); + expect(result.sdk.exitCode).toBe(0); + expect(result.review.exitCode).toBe(1); + expect(result.review.stdout).toContain(`::error::OpenCode ${nextVersion}`); expect(result.calls.every((call) => call.installed === nextVersion)).toBeTrue(); expect(result.summary).toContain("requires human review"); }); - test("failed SDK checks remain failed and still produce a review summary", async () => { + test("SDK test failure stops later checks and the report records failure", async () => { const result = await monitor(reviewedVersion, { sdkFailure: true }); - expect(result.sdk?.exitCode).toBe(33); - expect(result.review?.exitCode).toBe(0); + expect(result.sdk.exitCode).toBe(33); + expect(result.review.exitCode).toBe(0); expect(result.calls.map((call) => call.args)).toEqual([["install", "--ignore-scripts"], ["test"]]); expect(result.summary).toContain("SDK checks: failure"); }); - test("unavailable or prerelease input cannot be reported as a completed stable comparison", async () => { - for (const options of [{ unavailable: true }, { prerelease: true }]) { - const result = await monitor(nextVersion, options); - expect(result.release.exitCode).not.toBe(0); - expect(result.sdk).toBeUndefined(); - expect(result.review).toBeUndefined(); - } - }); - - test("no matching stable release is unavailable rather than successful no-change", async () => { - const result = await monitor(nextVersion, { noMatch: true }); - expect(result.release.exitCode).not.toBe(0); - expect(result.sdk).toBeUndefined(); - expect(result.review).toBeUndefined(); + test.each([ + ["unavailable GitHub response", { unavailable: true }, ["opencode-releases.json"], 22], + ["explicit prerelease", { prerelease: true }, ["opencode-release.json"], 1], + ["no matching stable release", { noMatch: true }, ["opencode-releases.json"], 4], + ] as const)("resolver fails without publishing outputs for %s", async (_scenario, options, files, exitCode) => { + await expectResolutionFailure(options, files, exitCode); }); test("new release still requires review when its SDK checks fail", async () => { const result = await monitor(nextVersion, { sdkFailure: true }); - expect(result.sdk?.exitCode).toBe(33); - expect(result.review?.exitCode).toBe(1); + expect(result.sdk.exitCode).toBe(33); + expect(result.review.exitCode).toBe(1); expect(result.summary).toContain("SDK checks: failure"); expect(result.summary).toContain("requires human review"); }); diff --git a/tests/prime.test.ts b/tests/prime.test.ts index e57fea1..56ca529 100644 --- a/tests/prime.test.ts +++ b/tests/prime.test.ts @@ -66,69 +66,71 @@ describe("runBdPrime", () => { expect(cancelled).toBeTrue(); }); - test("reports non-zero process exits", async () => { - await expect(runBdPrime("/project", { spawn: () => completedProcess(2) })).rejects.toBeInstanceOf( - PrimeProcessError, + test("reports a full-prime failure without retrying", async () => { + const spawn = mock((_directory: string, _args: readonly string[]) => + completedProcess(2, "partial context", "database unavailable"), ); - }); + const result = runBdPrime("/project", { spawn }, ["--full"]); - test("does not hide full-prime failures behind another invocation", async () => { - const genericFailure = mock((_directory: string, _args: readonly string[]) => - completedProcess(1, "", "database unavailable"), - ); - await expect(runBdPrime("/project", { spawn: genericFailure })).rejects.toBeInstanceOf(PrimeProcessError); - expect(genericFailure).toHaveBeenCalledTimes(1); - expect(genericFailure).toHaveBeenCalledWith("/project", ["prime"]); + await expect(result).rejects.toBeInstanceOf(PrimeProcessError); + await expect(result).rejects.toMatchObject({ + exitCode: 2, + stdout: "partial context", + stderr: "database unavailable", + }); + expect(spawn.mock.calls).toEqual([["/project", ["prime", "--full"]]]); }); test("bounds stream draining after timeout", async () => { let triggerTimeout: () => void = () => {}; let resolveExit: (exitCode: number) => void = () => {}; - let closeStdout: () => void = () => {}; const exit = new Promise<number>((resolve) => { resolveExit = resolve; }); - const stdout = new ReadableStream<Uint8Array>({ - start(controller) { - closeStdout = () => controller.close(); - }, - }); const kill = mock((_signal?: NodeJS.Signals) => resolveExit(137)); const killTree = mock((_signal?: NodeJS.Signals) => resolveExit(137)); const process: PrimeProcess = { pid: 1, - stdout, + stdout: new ReadableStream<Uint8Array>(), stderr: stream(""), exited: exit, kill, killTree, }; - + const drainTimeoutMs = 5; + const scheduleDrainTimeout = mock((_callback: () => void, _delayMs: number) => () => {}); const result = runBdPrime("/project", { timeoutMs: 25, - drainTimeoutMs: 5, + drainTimeoutMs, spawn: () => process, scheduleTimeout: (callback) => { triggerTimeout = callback; return () => {}; }, + scheduleDrainTimeout, }); - let settled = false; + let outcome: { value: string } | { error: unknown } | undefined; void result.then( - () => { - settled = true; + (value) => { + outcome = { value }; }, - () => { - settled = true; + (error: unknown) => { + outcome = { error }; }, ); triggerTimeout(); - await expect(result).rejects.toBeInstanceOf(PrimeTimeoutError); + await new Promise<void>((resolve) => setImmediate(resolve)); + expect(scheduleDrainTimeout).toHaveBeenCalledTimes(1); + const [finishDraining, delayMs] = scheduleDrainTimeout.mock.calls[0]!; + expect(delayMs).toBe(drainTimeoutMs); expect(killTree).toHaveBeenCalledWith("SIGKILL"); expect(kill).not.toHaveBeenCalled(); - expect(settled).toBeTrue(); - closeStdout(); + expect(outcome).toBeUndefined(); + + finishDraining(); + await new Promise<void>((resolve) => setImmediate(resolve)); + expect(outcome).toEqual({ error: expect.any(PrimeTimeoutError) }); }); }); diff --git a/tests/release.test.ts b/tests/release.test.ts index 9de28ea..7379519 100644 --- a/tests/release.test.ts +++ b/tests/release.test.ts @@ -1,4 +1,5 @@ import { afterEach, describe, expect, test } from "bun:test"; +import assert from "node:assert/strict"; import * as fs from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, dirname, join, resolve } from "node:path"; @@ -25,19 +26,32 @@ afterEach(async () => { ); }); -async function metadataFixture(): Promise<string> { - const directory = await fs.mkdtemp(join(tmpdir(), "opencode-beads-release-metadata-")); +async function scratch(label: string) { + const directory = await fs.mkdtemp(join(tmpdir(), `opencode-beads-${label}-`)); temporaryDirectories.push(directory); - await fs.writeFile(join(directory, "package.json"), JSON.stringify({ name: "@scope/package", version: "1.2.3" })); - await fs.writeFile(join(directory, "CHANGELOG.md"), "## [1.2.3]\n"); - await fs.writeFile(join(directory, "README.md"), "bunx @scope/package@1.2.3 init\n"); return directory; } -async function runSmoke(args: string[], env = process.env) { - const child = Bun.spawn([process.execPath, "scripts/packaging/test-package.ts", ...args], { - cwd: projectDirectory, - env, +async function metadataFixture(version = "1.2.3"): Promise<string> { + const directory = await scratch("release-metadata"); + await fs.writeFile(join(directory, "package.json"), JSON.stringify({ name: "@scope/package", version })); + await fs.writeFile(join(directory, "CHANGELOG.md"), `## [${version}]\n`); + await fs.writeFile(join(directory, "README.md"), `bunx @scope/package@${version} init\n`); + return directory; +} + +function tempEnv(directory: string) { + return { TMPDIR: directory, TEMP: directory, TMP: directory }; +} + +async function run(command: string[], cwd: string, env: Record<string, string> = {}) { + const child = Bun.spawn(command, { + cwd, + env: { + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, + ...env, + }, stdout: "pipe", stderr: "pipe", }); @@ -49,7 +63,16 @@ async function runSmoke(args: string[], env = process.env) { return { stdout, stderr, code }; } -describe("rejects malformed smoke options before allocating scratch", () => { +function runPackagingScript(script: "release" | "test-package", args: string[], cwd: string, temp: string) { + // These rejection paths should never need an installer or any other external command. + return run( + [process.execPath, "--no-env-file", join(projectDirectory, `scripts/packaging/${script}.ts`), ...args], + cwd, + { ...tempEnv(temp), PATH: temp }, + ); +} + +describe("malformed smoke CLI options", () => { const digest = "a".repeat(64); for (const [name, args, error] of [ ["archive without digest", ["--archive", "package.tgz"], /provided together/], @@ -64,14 +87,12 @@ describe("rejects malformed smoke options before allocating scratch", () => { ["positional argument", ["package.tgz"], /unexpected|positional/i], ] as const) { test(name, async () => { - const root = await fs.mkdtemp(join(tmpdir(), "opencode-beads-smoke-options-")); - temporaryDirectories.push(root); - const missing = join(root, "missing"); - const env = { ...process.env, TMPDIR: missing, TEMP: missing, TMP: missing }; - const result = await runSmoke([...args], env); + // Bun may create its own "bun" directory before the script starts. + const root = await scratch("smoke-options"); + const result = await runPackagingScript("test-package", [...args], root, root); expect(result.code).toBe(1); expect(result.stderr).toMatch(error); - expect(await fs.readdir(root)).toEqual([]); + expect((await fs.readdir(root)).filter((entry) => entry !== "bun")).toEqual([]); }); } }); @@ -107,47 +128,32 @@ describe("release artifact identity", () => { await expect(validateReleaseMetadata(directory, "v1.2.3", { distTag: "next", prerelease: true })).rejects.toThrow( "channel", ); - await fs.writeFile( - join(directory, "package.json"), - JSON.stringify({ name: "@scope/package", version: "1.1.0-beta.1" }), - ); - await fs.writeFile(join(directory, "CHANGELOG.md"), "## [1.1.0-beta.1]\n"); - await fs.writeFile(join(directory, "README.md"), "install @scope/package@1.1.0-beta.1 or @scope/package@next\n"); + const beta = await metadataFixture("1.1.0-beta.1"); + await fs.appendFile(join(beta, "README.md"), "or install @scope/package@next\n"); await expect( - validateReleaseMetadata(directory, "v1.1.0-beta.1", { distTag: "next", prerelease: true }), + validateReleaseMetadata(beta, "v1.1.0-beta.1", { distTag: "next", prerelease: true }), ).resolves.toMatchObject({ version: "1.1.0-beta.1" }); for (const metadata of [ { distTag: "latest", prerelease: true }, { distTag: "next", prerelease: false }, ]) { - await expect(validateReleaseMetadata(directory, "v1.1.0-beta.1", metadata)).rejects.toThrow("channel"); + await expect(validateReleaseMetadata(beta, "v1.1.0-beta.1", metadata)).rejects.toThrow("channel"); } - await fs.writeFile( - join(directory, "package.json"), - JSON.stringify({ name: "@scope/package", version: "1.1.0-rc.1" }), - ); - await expect(validateReleaseMetadata(directory, "v1.1.0-rc.1")).rejects.toThrow("Unsupported release channel"); + const rc = await metadataFixture("1.1.0-rc.1"); + await expect(validateReleaseMetadata(rc, "v1.1.0-rc.1")).rejects.toThrow("Unsupported release channel"); }); - test("CLI refuses missing or ambiguous prerelease flags before producing an archive", async () => { + test("prepare CLI refuses missing, invalid, or conflicting prerelease flags before producing an archive", async () => { const directory = await metadataFixture(); for (const flag of [[], ["--prerelease", "yes"], ["--prerelease", "true"]]) { - const child = Bun.spawn( - [ - process.execPath, - join(projectDirectory, "scripts/packaging/release.ts"), - "prepare", - "--tag", - "v1.2.3", - "--output", - "out", - ...flag, - ], - { cwd: directory, stdout: "pipe", stderr: "pipe" }, + const result = await runPackagingScript( + "release", + ["prepare", "--tag", "v1.2.3", "--output", "out", ...flag], + directory, + directory, ); - const error = await new Response(child.stderr).text(); - expect(await child.exited).toBe(1); - expect(error).toMatch(/prerelease|channel/); + expect(result.code).toBe(1); + expect(result.stderr).toMatch(/prerelease|channel/); expect(await fs.exists(join(directory, "out"))).toBeFalse(); } }); @@ -171,12 +177,11 @@ describe("release artifact identity", () => { await expect(validateReleaseMetadata(modifiedRemoval, "v1.2.3")).rejects.toThrow("references @scope/package@0.8.0"); }); - test("builds, inspects, and verifies one immutable publication archive", async () => { - const root = await fs.mkdtemp(join(tmpdir(), "opencode-beads-release-")); - temporaryDirectories.push(root); + test("checks the local or supplied archive digest, inventory, and npm pack report", async () => { + const root = await scratch("release"); const capstoneArchive = process.env.CAPSTONE_ARCHIVE; const capstoneSha256 = process.env.CAPSTONE_SHA256; - if ((capstoneArchive === undefined) !== (capstoneSha256 === undefined)) { + if ((capstoneArchive !== undefined || capstoneSha256 !== undefined) && (!capstoneArchive || !capstoneSha256)) { throw new Error("CAPSTONE_ARCHIVE and CAPSTONE_SHA256 must be provided together"); } const prepared = @@ -184,7 +189,7 @@ describe("release artifact identity", () => { ? await verifyReleaseArchive(projectDirectory, capstoneArchive, capstoneSha256) : await prepareReleaseArchive(projectDirectory, `v${packageManifest.version}`, join(root, "out")); const archiveName = `${packageManifest.name.slice(1).replace("/", "-")}-${packageManifest.version}.tgz`; - expect(prepared.path.endsWith(archiveName)).toBeTrue(); + expect(basename(prepared.path)).toBe(archiveName); expect(prepared.sha256).toMatch(/^[a-f0-9]{64}$/); await expect(verifyReleaseArchive(projectDirectory, prepared.path, prepared.sha256)).resolves.toEqual(prepared); @@ -198,25 +203,38 @@ describe("release artifact identity", () => { const smokeScratch = join(root, "smoke-scratch"); await fs.mkdir(smokeScratch); - const smokeEnv = { ...process.env, TMPDIR: smokeScratch }; - const rejectedSmoke = await runSmoke(["--archive", changed, "--sha256", prepared.sha256], smokeEnv); + const rejectedSmoke = await runPackagingScript( + "test-package", + ["--archive", changed, "--sha256", prepared.sha256], + smokeScratch, + smokeScratch, + ); expect(rejectedSmoke.code).toBe(1); expect(rejectedSmoke.stderr).toContain("Provided archive checksum differs"); - expect(await fs.readdir(smokeScratch)).not.toContainEqual(expect.stringMatching(/^opencode-beads-package-/)); - - const npmRehearsalDirectory = join(root, "npm-pack-rehearsal"); - await fs.mkdir(npmRehearsalDirectory); - const npmPack = Bun.spawn(["npm", "pack", prepared.path, "--dry-run", "--json", "--ignore-scripts"], { - cwd: npmRehearsalDirectory, - stdout: "pipe", - stderr: "pipe", - }); - const [npmPackOutput, npmPackError, npmPackExit] = await Promise.all([ - new Response(npmPack.stdout).text(), - new Response(npmPack.stderr).text(), - npmPack.exited, - ]); - expect(npmPackExit, npmPackError).toBe(0); + expect((await fs.readdir(smokeScratch)).filter((entry) => entry !== "bun")).toEqual([]); + + const npmDirectory = join(root, "npm-pack-rehearsal"); + await fs.mkdir(npmDirectory); + const npmPack = await run( + [ + "npm", + "pack", + prepared.path, + "--dry-run", + "--json", + "--ignore-scripts", + "--offline", + "--cache", + join(npmDirectory, "cache"), + "--userconfig", + join(npmDirectory, "user.npmrc"), + "--globalconfig", + join(npmDirectory, "global.npmrc"), + ], + npmDirectory, + tempEnv(npmDirectory), + ); + expect(npmPack.code, npmPack.stderr).toBe(0); type NpmPackReport = { id: string; name: string; @@ -226,7 +244,7 @@ describe("release artifact identity", () => { files: Array<{ path: string }>; }; // npm <= 11 prints an array of reports; npm 12 prints an object keyed by package name. - const npmPackJson = JSON.parse(npmPackOutput) as NpmPackReport[] | Record<string, NpmPackReport>; + const npmPackJson = JSON.parse(npmPack.stdout) as NpmPackReport[] | Record<string, NpmPackReport>; const npmReports = Array.isArray(npmPackJson) ? npmPackJson : Object.values(npmPackJson); expect(npmReports).toHaveLength(1); const npmReport = npmReports[0]; @@ -235,27 +253,18 @@ describe("release artifact identity", () => { expect(npmReport?.version).toBe(packageManifest.version); expect(npmReport?.filename).toBe(basename(prepared.path)); - const tar = Bun.spawn(["tar", "-tzf", prepared.path], { - cwd: projectDirectory, - stdout: "pipe", - stderr: "pipe", - }); - const [tarOutput, tarError, tarExit] = await Promise.all([ - new Response(tar.stdout).text(), - new Response(tar.stderr).text(), - tar.exited, - ]); - expect(tarExit, tarError).toBe(0); - const archiveEntryCount = tarOutput + const tar = await run(["tar", "-tzf", prepared.path], projectDirectory); + expect(tar.code, tar.stderr).toBe(0); + const archiveFiles = tar.stdout .split(/\r?\n/) - .filter((entry) => entry.startsWith("package/") && !entry.endsWith("/")).length; - expect(npmReport?.entryCount).toBe(archiveEntryCount); - expect(npmReport?.files).toHaveLength(archiveEntryCount); + .filter((entry) => entry.startsWith("package/") && !entry.endsWith("/")) + .map((entry) => entry.slice("package/".length)); + expect(npmReport?.entryCount).toBe(archiveFiles.length); + expect(npmReport?.files.map(({ path }) => path).sort()).toEqual(archiveFiles.sort()); }, 30_000); test("rejects malformed archive inventory", async () => { - const root = await fs.mkdtemp(join(tmpdir(), "opencode-beads-release-malformed-")); - temporaryDirectories.push(root); + const root = await scratch("release-malformed"); const packageDirectory = join(root, "package"); await fs.mkdir(packageDirectory); await fs.writeFile( @@ -263,91 +272,204 @@ describe("release artifact identity", () => { JSON.stringify({ name: "@snarkipus/opencode-beads", version: "0.7.0" }), ); const archive = join(root, "malformed.tgz"); - const tar = Bun.spawn(["tar", "-czf", archive, "package"], { cwd: root }); - expect(await tar.exited).toBe(0); + const tar = await run(["tar", "-czf", archive, "package"], root); + expect(tar.code, tar.stderr).toBe(0); await expect(inspectReleaseArchive(projectDirectory, archive)).rejects.toThrow("Release archive inventory differs"); }); +}); - test("routes every release consumer through the prepared archive output", async () => { - const workflow = (await fs.readFile(join(projectDirectory, ".github/workflows/release.yml"), "utf8")).replaceAll( - "\r\n", - "\n", +type WorkflowStep = { + id?: string; + uses?: string; + run?: string; + shell?: string; + if?: string; + "continue-on-error"?: boolean; + env?: Record<string, string>; + with?: Record<string, unknown>; +}; + +type Workflow = { + on: Record<string, unknown>; + permissions?: Record<string, string>; + jobs: Record< + string, + { + permissions?: Record<string, string>; + defaults?: { run?: { shell?: string } }; + steps: WorkflowStep[]; + } + >; + defaults?: { run?: { shell?: string } }; +}; + +async function readWorkflow(name: string) { + return Bun.YAML.parse(await fs.readFile(join(projectDirectory, ".github/workflows", name), "utf8")) as Workflow; +} + +function shellLines(step: WorkflowStep) { + return (step.run ?? "") + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith("#")); +} + +function findStep(steps: WorkflowStep[], description: string, matches: (step: WorkflowStep) => boolean) { + const found = steps.filter(matches); + expect(found, description).toHaveLength(1); + assert(found[0], description); + return found[0]; +} + +// Inspect YAML bindings and local command text without running Actions or workflow shell blocks. +describe("static workflow wiring", () => { + test("binds the prepared archive to smoke, attestation, upload, and guarded npm publication", async () => { + const workflow = await readWorkflow("release.yml"); + const job = workflow.jobs.publish; + assert(job, "Expected the release publish job"); + const { steps } = job; + const prepare = findStep(steps, "archive producer", (step) => step.id === "package"); + const smoke = findStep(steps, "prepared archive smoke check", (step) => /test-package\.ts/.test(step.run ?? "")); + const attest = findStep( + steps, + "artifact attestation", + (step) => step.uses?.startsWith("actions/attest-build-provenance@") === true, + ); + const upload = findStep(steps, "release upload", (step) => + shellLines(step).some((line) => line.startsWith("gh release upload ")), + ); + const publish = findStep(steps, "npm publication", (step) => + shellLines(step).some((line) => /^npm publish\b/.test(line)), ); - expect(workflow.match(/steps\.package\.outputs\.archive/g)).toHaveLength(4); - const steps = workflow.split(/^ - name: /m); - const prepare = steps.findIndex((step) => step.startsWith("Validate and build release archive\n")); - const smoke = steps.findIndex((step) => step.startsWith("Test prepared release archive\n")); - expect(prepare).toBeGreaterThan(-1); - expect(smoke).toBe(prepare + 1); - for (const name of ["Generate artifact attestation", "Upload release assets to GitHub", "Publish to npm"]) { - expect(steps.findIndex((step) => step.startsWith(`${name}\n`))).toBeGreaterThan(smoke); + + const archive = "${{ steps.package.outputs.archive }}"; + const digest = "${{ steps.package.outputs.sha256 }}"; + const release = { + RELEASE_TAG: "${{ github.event.release.tag_name }}", + RELEASE_PRERELEASE: "${{ github.event.release.prerelease }}", + }; + expect(prepare.env).toMatchObject(release); + expect(shellLines(prepare)).toEqual([ + 'bun scripts/packaging/release.ts prepare --tag "$RELEASE_TAG" --prerelease "$RELEASE_PRERELEASE" --output release-artifacts', + ]); + expect(smoke.env).toMatchObject({ ARCHIVE: archive, ARCHIVE_SHA256: digest }); + expect(shellLines(smoke)).toEqual([ + 'bun scripts/packaging/test-package.ts --archive "$ARCHIVE" --sha256 "$ARCHIVE_SHA256"', + ]); + expect(steps.indexOf(smoke)).toBeGreaterThan(steps.indexOf(prepare)); + for (const consumer of [attest, upload, publish]) { + expect(steps.indexOf(consumer)).toBeGreaterThan(steps.indexOf(smoke)); + } + for (const step of [prepare, smoke, attest, upload, publish]) { + expect(step.if).toBeUndefined(); + expect(step["continue-on-error"] ?? false).toBe(false); } - expect(steps[smoke]).toContain("ARCHIVE: ${{ steps.package.outputs.archive }}"); - expect(steps[smoke]).toContain("ARCHIVE_SHA256: ${{ steps.package.outputs.sha256 }}"); - expect(steps[smoke]).toContain( - 'run: bun scripts/packaging/test-package.ts --archive "$ARCHIVE" --sha256 "$ARCHIVE_SHA256"', + expect(attest.with).toMatchObject({ "subject-path": archive }); + expect(upload.env).toMatchObject({ ARCHIVE: archive, RELEASE_TAG: release.RELEASE_TAG }); + expect(shellLines(upload)).toEqual(['gh release upload "$RELEASE_TAG" "$ARCHIVE"']); + expect(publish.env).toMatchObject({ + ...release, + ARCHIVE: archive, + ARCHIVE_SHA256: digest, + DIST_TAG: "${{ steps.package.outputs.dist_tag }}", + }); + expect(shellLines(publish)).toEqual([ + 'bun scripts/packaging/release.ts verify --archive "$ARCHIVE" --sha256 "$ARCHIVE_SHA256" --tag "$RELEASE_TAG" --dist-tag "$DIST_TAG" --prerelease "$RELEASE_PRERELEASE"', + 'npm publish "$ARCHIVE" --access public --tag "$DIST_TAG"', + ]); + // These Actions shells fail the step if the verification command exits nonzero. + const publishShell = publish.shell ?? job.defaults?.run?.shell ?? workflow.defaults?.run?.shell; + expect(publishShell ?? "bash").toMatch(/^(bash|sh)$/); + }); + + test("configures trusted publishing in the release job", async () => { + const workflow = await readWorkflow("release.yml"); + const job = workflow.jobs.publish; + assert(job, "Expected the release publish job"); + const node = findStep(job.steps, "Node setup", (step) => step.uses?.startsWith("actions/setup-node@") === true); + const bun = findStep(job.steps, "Bun setup", (step) => step.uses?.startsWith("oven-sh/setup-bun@") === true); + const npm = findStep(job.steps, "npm installation", (step) => + shellLines(step).some((line) => line.startsWith("npm install --global npm@")), + ); + const publish = findStep(job.steps, "npm publication", (step) => + shellLines(step).some((line) => /^npm publish\b/.test(line)), ); - expect(workflow.match(/test-package\.ts/g)).toHaveLength(1); - expect(workflow).toContain("ARCHIVE: ${{ steps.package.outputs.archive }}"); - expect(workflow).toContain('node-version: "24"'); - expect(workflow).toContain('registry-url: "https://registry.npmjs.org"'); - expect(workflow).toContain("package-manager-cache: false"); - expect(workflow).toContain("npm install --global npm@11.10.1"); - // Publishing authenticates through npm trusted publishing (OIDC); no token secret. - expect(workflow).toContain("id-token: write"); - expect(workflow).not.toContain("NPM_TOKEN"); - expect(workflow).not.toContain("NODE_AUTH_TOKEN"); - expect(workflow).toContain('npm publish "$ARCHIVE" --access public --tag "$DIST_TAG"'); - expect(workflow).toContain("DIST_TAG: ${{ steps.package.outputs.dist_tag }}"); - expect(workflow).toContain("RELEASE_PRERELEASE: ${{ github.event.release.prerelease }}"); - expect(workflow).toContain('--prerelease "$RELEASE_PRERELEASE"'); - expect(workflow).not.toMatch(/npm publish\s*(?:\n|$)/); + expect(node.with).toMatchObject({ + "node-version": "24", + "registry-url": "https://registry.npmjs.org", + "package-manager-cache": false, + }); + expect(bun.with?.["no-cache"]).toBe(true); + expect(npm.run).toMatch(/^npm install --global npm@11\.10\.1(?:\s+#.*)?\s*$/); + expect(job.steps.indexOf(node)).toBeLessThan(job.steps.indexOf(npm)); + expect(job.steps.indexOf(npm)).toBeLessThan(job.steps.indexOf(publish)); + expect((job.permissions ?? workflow.permissions)?.["id-token"]).toBe("write"); + expect(JSON.stringify(workflow)).not.toMatch(/\b(?:NPM_TOKEN|NODE_AUTH_TOKEN)\b/); }); - test("keeps source comparison independent and reports even unavailable collection", async () => { - const workflow = await fs.readFile(join(projectDirectory, ".github/workflows/beads-contract.yml"), "utf8"); - expect(workflow).toContain("schedule:"); - expect(workflow).toContain("workflow_dispatch:"); - expect( - workflow.match(/^ [a-z-]+:$/gm)?.filter((line) => line === " contract:" || line === " source-comparison:"), - ).toHaveLength(2); - expect(workflow).not.toMatch(/\bneeds:|continue-on-error:|(?:issues|checks):\s*write/); - const source = workflow.split(" source-comparison:")[1]!; - expect(source).toContain("bun scripts/check-beads-integration.ts"); - expect(source).toContain('exit "$status"'); - expect(source).toContain("if: ${{ always() }}"); - expect(source).toContain('>> "$GITHUB_STEP_SUMMARY"'); - expect(source).not.toMatch(/install-bd|test:bd-contract|::(?:error|warning)::/); - expect(workflow).toContain("Require review of new Beads releases"); + test("keeps the source comparison independent and wires its summary to run after failure", async () => { + const workflow = await readWorkflow("beads-contract.yml"); + expect(workflow.on).toHaveProperty("schedule"); + expect(workflow.on).toHaveProperty("workflow_dispatch"); + const { contract, "source-comparison": source } = workflow.jobs; + assert(contract && source, "Expected separate CLI contract and source comparison jobs"); + expect(JSON.stringify(workflow)).not.toMatch(/"(?:needs|continue-on-error)":|"(?:issues|checks)":"write"/); + expect(workflow.permissions?.contents).toBe("read"); + expect(contract.steps.some((step) => step.run?.includes("./scripts/install-bd.sh"))).toBeTrue(); + expect(contract.steps).toContainEqual(expect.objectContaining({ name: "Require review of new Beads releases" })); + + const collect = findStep(source.steps, "source collector", (step) => + shellLines(step).some((line) => line.startsWith("bun scripts/check-beads-integration.ts ")), + ); + const summary = findStep(source.steps, "source summary", (step) => + shellLines(step).some((line) => line.includes('>> "$GITHUB_STEP_SUMMARY"')), + ); + expect(collect.if).toBeUndefined(); + expect(shellLines(collect)).toEqual([ + "status=0", + 'bun scripts/check-beads-integration.ts > "$RUNNER_TEMP/beads-source.json" || status=$?', + `printf '%s\\n' "$status" > "$RUNNER_TEMP/beads-source.exit"`, + 'exit "$status"', + ]); + expect(source.steps.indexOf(summary)).toBeGreaterThan(source.steps.indexOf(collect)); + const condition = summary.if?.trim().replace(/^\$\{\{\s*|\s*\}\}$/g, ""); + expect(condition).toMatch(/^always\s*\(\s*\)$/); + expect(summary.run).toContain("Comparison unavailable: collector did not finish."); + expect(source.steps.map((step) => step.run ?? "").join("\n")).not.toMatch( + /install-bd|test:bd-contract|::(?:error|warning)::/, + ); for (const name of ["ci.yml", "release.yml"]) { - const product = await fs.readFile(join(projectDirectory, ".github/workflows", name), "utf8"); - expect(product).not.toContain("source-comparison"); - expect(product).not.toContain("beads-contract.yml"); + expect(JSON.stringify(await readWorkflow(name))).not.toMatch(/source-comparison|beads-contract\.yml/); } }); - test("hardens workflow dependencies, credentials, caching, and update cooldowns", async () => { - const workflowNames = ["ci.yml", "release.yml", "beads-contract.yml"]; - const workflows = await Promise.all( - workflowNames.map((name) => fs.readFile(join(projectDirectory, ".github/workflows", name), "utf8")), - ); - for (const [index, workflow] of workflows.entries()) { - expect( - [...workflow.matchAll(/uses:\s+[^\s@]+@([^\s#]+)/g)].every((match) => /^[a-f0-9]{40}$/.test(match[1] ?? "")), - workflowNames[index], - ).toBeTrue(); - expect(workflow).toContain("persist-credentials: false"); + test("pins workflow actions and disables credential persistence at checkout", async () => { + for (const name of ["ci.yml", "release.yml", "beads-contract.yml"]) { + const workflow = await readWorkflow(name); + const actions = Object.values(workflow.jobs).flatMap(({ steps }) => steps.filter((step) => step.uses)); + const checkouts = actions.filter((step) => step.uses?.startsWith("actions/checkout@")); + expect(checkouts.length, name).toBeGreaterThan(0); + for (const action of actions) { + expect(action.uses, name).toMatch(/@\b[a-f0-9]{40}$/); + } + for (const checkout of checkouts) { + expect(checkout.with?.["persist-credentials"], name).toBe(false); + } } - expect(workflows[0]).toContain("zizmorcore/zizmor-action@"); - expect(workflows[1]).toContain("no-cache: true"); - expect(workflows[2]).toMatch(/permissions:\r?\n contents: read/); - expect(workflows[2]).toContain("./scripts/install-bd.sh"); - expect(workflows[0]).toContain("bun run test:bd-contract"); - // The upstream sync workflow (and its push credentials) was retired with vendoring. + const ci = await readWorkflow("ci.yml"); + expect(ci.jobs.zizmor?.steps.some((step) => step.uses?.startsWith("zizmorcore/zizmor-action@"))).toBeTrue(); + expect(ci.jobs.test?.steps.some((step) => shellLines(step).includes("bun run test:bd-contract"))).toBeTrue(); expect(await fs.exists(join(projectDirectory, ".github/workflows/sync-beads.yml"))).toBeFalse(); + }); - const dependabot = await fs.readFile(join(projectDirectory, ".github/dependabot.yml"), "utf8"); - expect(dependabot.match(/default-days: 7/g)).toHaveLength(2); + test("applies the update cooldown to npm and GitHub Actions", async () => { + const source = await fs.readFile(join(projectDirectory, ".github/dependabot.yml"), "utf8"); + const config = Bun.YAML.parse(source) as { updates: Array<Record<string, unknown>> }; + for (const ecosystem of ["npm", "github-actions"]) { + const updates = config.updates.filter((entry) => entry["package-ecosystem"] === ecosystem); + expect(updates).toHaveLength(1); + expect(updates[0]?.cooldown).toMatchObject({ "default-days": 7 }); + } }); }); diff --git a/tests/upstream-review.test.ts b/tests/upstream-review.test.ts index cdc1474..837a581 100644 --- a/tests/upstream-review.test.ts +++ b/tests/upstream-review.test.ts @@ -12,7 +12,11 @@ const repository = "gastownhall/beads"; const api = `https://api.github.com/repos/${repository}`; const script = resolve(import.meta.dir, "../scripts/check-beads-integration.ts"); const inventoryPath = resolve(import.meta.dir, "../docs/claude-code-integration-inventory.json"); +const workflowPath = resolve(import.meta.dir, "../.github/workflows/beads-contract.yml"); +const packagePath = resolve(import.meta.dir, "../package.json"); +const fixtureToken = "fixture-secret-never-print"; const temporaryDirectories: string[] = []; +const testWorkflow = test.skipIf(process.platform === "win32"); afterEach(async () => { await Promise.all(temporaryDirectories.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); @@ -40,12 +44,12 @@ const inventory = { }; /** GitHub-shaped responses; no tag or local adaptation bytes enter the comparison. */ -function responses(next = entries): Record<string, unknown> { +function responses(next = entries, before = entries, reviewedCommit = baseline): Record<string, unknown> { return { [api]: { default_branch: "main" }, [`${api}/commits/main`]: { sha: candidate, commit: { tree: { sha: nextTree } } }, - [`${api}/commits/${baseline}`]: { sha: baseline, commit: { tree: { sha: baseTree } } }, - [`${api}/git/trees/${baseTree}?recursive=1`]: { sha: baseTree, truncated: false, tree: entries }, + [`${api}/commits/${reviewedCommit}`]: { sha: reviewedCommit, commit: { tree: { sha: baseTree } } }, + [`${api}/git/trees/${baseTree}?recursive=1`]: { sha: baseTree, truncated: false, tree: before }, [`${api}/git/trees/${nextTree}?recursive=1`]: { sha: nextTree, truncated: false, tree: next }, }; } @@ -63,79 +67,105 @@ async function run(data = responses(), sourceInventory: unknown = inventory) { return { ...result, report: JSON.parse(result.stdout) }; } -/** Run the actual CLI with a temporary preload replacing only HTTP retrieval. */ -async function entrypoint(data: Record<string, unknown>, args: string[] = [], workflowText?: string) { +/** Stage the real CLI and its inventory so a regression cannot edit the checkout through these paths. */ +async function cliFixture() { const directory = await fs.mkdtemp(join(tmpdir(), "oc-upstream-entrypoint-")); temporaryDirectories.push(directory); - const preload = join(directory, "fetch.ts"); + await fs.mkdir(join(directory, "scripts")); + await fs.mkdir(join(directory, "docs")); + const actualInventory = await fs.readFile(inventoryPath, "utf8"); + const actualPackage = await fs.readFile(packagePath, "utf8"); + const inventoryCopy = join(directory, "docs/claude-code-integration-inventory.json"); + const packageCopy = join(directory, "package.json"); + await fs.copyFile(script, join(directory, "scripts/check-beads-integration.ts")); + await fs.writeFile(inventoryCopy, actualInventory); + await fs.writeFile(packageCopy, actualPackage); + return { directory, actualInventory, actualPackage, inventoryCopy, packageCopy }; +} + +function runChild(command: string[], directory: string, env: Record<string, string> = {}) { + const systemRoot = process.platform === "win32" ? process.env.SystemRoot : undefined; + return Bun.spawnSync(command, { + cwd: directory, + env: { PATH: directory, GH_TOKEN: fixtureToken, ...(systemRoot ? { SystemRoot: systemRoot } : {}), ...env }, + stdout: "pipe", + stderr: "pipe", + }); +} + +/** Parse the actual job with Bun's YAML parser, then run its two shell blocks with an offline Bun shim. */ +async function runWorkflow( + workflowText: string, + fixture: Awaited<ReturnType<typeof cliFixture>>, + data: Record<string, unknown>, +) { + const workflow = Bun.YAML.parse(workflowText) as { jobs: Record<string, { steps: Array<{ run?: string }> }> }; + const blocks = workflow.jobs["source-comparison"]?.steps.flatMap(({ run }) => (run ? [run] : [])); + const [collect, summarize] = blocks ?? []; + if (blocks?.length !== 2 || !collect || !summarize) throw new Error("Expected collector and summary shell blocks"); + + const { directory } = fixture; + const bash = Bun.which("bash"); + const cat = Bun.which("cat"); + if (!bash || !cat) throw new Error("Workflow fixture requires bash and cat"); + const bin = await fs.mkdtemp(join(directory, "bin-")); + await fs.symlink(cat, join(bin, "cat")); + const preload = join(bin, "fetch.ts"); await fs.writeFile( preload, ` const data = ${JSON.stringify(data)}; globalThis.fetch = async (url) => { - if (!(String(url) in data)) throw new Error("Unexpected fixture request"); + if (!Object.hasOwn(data, String(url))) throw new Error("Unexpected fixture request"); return new Response(JSON.stringify(data[String(url)]), { status: 200 }); }; `, ); - const workflow = ( - workflowText ?? (await fs.readFile(resolve(import.meta.dir, "../.github/workflows/beads-contract.yml"), "utf8")) - ).replace(/\r\n/g, "\n"); - const runBlocks = [ - ...workflow.split(" source-comparison:")[1]!.matchAll(/ run: \|\n((?: .*\n|\n)+)/g), - ].map((match) => match[1]!.replace(/^ /gm, "")); - expect(runBlocks).toHaveLength(2); - const [collect, summarize] = runBlocks as [string, string]; - // Exercise the literal workflow shell; only add the existing HTTP preload to its real collector invocation. - const command = collect.replace( - "bun scripts/check-beads-integration.ts", - '"$BUN_EXECUTABLE" --preload "$FETCH_PRELOAD" "$COLLECTOR"', + await fs.writeFile( + join(bin, "bun"), + '#!/bin/sh\nexec "$BUN_EXECUTABLE" --no-env-file --preload "$FETCH_PRELOAD" "$@"\n', + { mode: 0o700 }, ); - const summaryPath = join(directory, "summary.md"); + const summaryPath = join(bin, "summary.md"); const env = { - ...process.env, - GH_TOKEN: "fixture-secret-never-print", - RUNNER_TEMP: directory, + PATH: bin, + RUNNER_TEMP: bin, GITHUB_STEP_SUMMARY: summaryPath, BUN_EXECUTABLE: process.execPath, FETCH_PRELOAD: preload, - COLLECTOR: script, }; - const proc = Bun.spawn( - args.length ? [process.execPath, "--preload", preload, script, ...args] : ["bash", "-e", "-c", command], - { - cwd: directory, - stdout: "pipe", - stderr: "pipe", - env, - }, - ); - const [exitCode, output, stderr] = await Promise.all([ - proc.exited, - new Response(proc.stdout).text(), - new Response(proc.stderr).text(), - ]); - let stdout = output; - let summary = ""; - if (!args.length) { - stdout = await fs.readFile(join(directory, "beads-source.json"), "utf8"); - expect(await fs.readFile(join(directory, "beads-source.exit"), "utf8")).toBe(`${exitCode}\n`); - const reporting = Bun.spawn(["bash", "-e", "-c", summarize], { - cwd: directory, - env, - stdout: "pipe", - stderr: "pipe", - }); - expect(await reporting.exited).toBe(0); - summary = await fs.readFile(summaryPath, "utf8"); - expect(summary).toContain(`Collector exit status: ${exitCode}`); - expect(summary).toContain(stdout); - expect(summary).not.toMatch(/::(?:error|warning)::|fixture-secret-never-print/); + const collected = runChild([bash, "-e", "-c", collect], directory, env); + const exitCode = collected.exitCode; + const stdout = await fs.readFile(join(bin, "beads-source.json"), "utf8"); + expect(await fs.readFile(join(bin, "beads-source.exit"), "utf8")).toBe(`${exitCode}\n`); + + const reporting = runChild([bash, "-e", "-c", summarize], directory, env); + expect(reporting.exitCode, reporting.stderr.toString()).toBe(0); + const summary = await fs.readFile(summaryPath, "utf8"); + expect(summary).toContain(`Collector exit status: ${exitCode}`); + expect(summary).toContain(stdout); + for (const output of [stdout, summary]) { + expect(output).not.toMatch(/::(?:error|warning)::/); + expect(output).not.toContain(fixtureToken); } - expect((await fs.readdir(directory)).sort()).toEqual( - args.length ? ["fetch.ts"] : ["beads-source.exit", "beads-source.json", "fetch.ts", "summary.md"], - ); - return { exitCode, stdout, stderr, summary, report: JSON.parse(stdout) }; + expect((await fs.readdir(bin)).sort()).toEqual([ + "beads-source.exit", + "beads-source.json", + "bun", + "cat", + "fetch.ts", + "summary.md", + ]); + return { exitCode, stdout, stderr: collected.stderr.toString(), report: JSON.parse(stdout) }; +} + +function reviewedTree(actualInventory: string) { + const main = JSON.parse(actualInventory).marketplace_main as { + commit: string; + files: Array<{ path: string; git_blob: string }>; + }; + const selected = main.files.map(({ path, git_blob }) => ({ path, sha: git_blob, type: "blob", mode: "100644" })); + return { main, selected }; } describe("advisory marketplace MAIN source collector", () => { @@ -186,12 +216,13 @@ describe("advisory marketplace MAIN source collector", () => { expect(result.report.baselineCommit).toBe(baseline); expect(result.report.candidateCommit).toBe(candidate); expect(result.report.reviewUrl).toContain(`${baseline}..${candidate}`); - expect( - result.report.changes.every( - (c: { beforeUrl?: string; afterUrl?: string }) => - c.beforeUrl?.includes(baseline) || c.afterUrl?.includes(candidate), - ), - ).toBeTrue(); + for (const change of result.report.changes) { + const web = `https://github.com/${repository}/blob`; + expect(change.beforeUrl).toBe( + change.kind === "added" ? undefined : `${web}/${baseline}/${change.previousPath ?? change.path}`, + ); + expect(change.afterUrl).toBe(change.kind === "deleted" ? undefined : `${web}/${candidate}/${change.path}`); + } expect((await run(responses([...next].reverse()))).stdout).toBe(result.stdout); expect((await run(data)).stdout).toBe(result.stdout); expect(inventory.marketplace_main.commit).toBe(baseline); @@ -225,114 +256,135 @@ describe("advisory marketplace MAIN source collector", () => { test("incomplete, malformed or failed retrieval is unavailable, never unchanged", async () => { const treeUrl = `${api}/git/trees/${nextTree}?recursive=1`; - for (const invalid of [ - { sha: nextTree, truncated: true, tree: entries }, - { sha: nextTree, tree: entries }, - { sha: nextTree, truncated: false }, - { sha: baseTree, truncated: false, tree: entries }, - { sha: nextTree, truncated: false, tree: [{ path: "plugins/beads/x", type: "blob" }] }, - { sha: nextTree, truncated: false, tree: [blob("plugins/beads/x", "1", "invalid")] }, - { sha: nextTree, truncated: false, tree: [...entries, entries[0]] }, - ]) { + const incompleteTree = /tree identity, completeness or entries/i; + for (const [invalid, error] of [ + [{ sha: nextTree, truncated: true, tree: entries }, incompleteTree], + [{ sha: nextTree, tree: entries }, incompleteTree], + [{ sha: nextTree, truncated: false }, incompleteTree], + [{ sha: baseTree, truncated: false, tree: entries }, incompleteTree], + [{ sha: nextTree, truncated: false, tree: [{ path: "plugins/beads/x", type: "blob" }] }, /immutable Git SHA/], + [{ sha: nextTree, truncated: false, tree: [blob("plugins/beads/x", "1", "invalid")] }, /type\/mode/], + [{ sha: nextTree, truncated: false, tree: [...entries, entries[0]] }, /duplicate tree path/i], + ] as const) { const data = responses(); data[treeUrl] = invalid; const result = await run(data); expect(result.exitCode).toBe(2); - expect(result.report.kind).toBe("unavailable"); + expect(result.report).toMatchObject({ kind: "unavailable", error: expect.stringMatching(error) }); expect(result.report.status).toBeUndefined(); expect(result.report.changes).toBeUndefined(); } - for (const fetchSource of [ - async () => new Response('{"message":"denied"}', { status: 403 }), - async () => new Response("not JSON"), - async () => { - throw new Error("network unavailable"); - }, - fixtureFetch({ [api]: {} }), - ]) { + for (const [fetchSource, error] of [ + [async () => new Response('{"message":"denied"}', { status: 403 }), /HTTP 403/], + [async () => new Response("not JSON"), /not valid JSON/], + [ + async () => { + throw new Error(fixtureToken); + }, + /retrieval unavailable/, + ], + [fixtureFetch({ [api]: {} }), /missing default branch/i], + ] as const) { const result = await runSourceCheck(inventory, fetchSource); expect(result.exitCode).toBe(2); - expect(JSON.parse(result.stdout).kind).toBe("unavailable"); + expect(JSON.parse(result.stdout)).toMatchObject({ kind: "unavailable", error: expect.stringMatching(error) }); + expect(result.stdout).not.toContain(fixtureToken); } const missingBaseline = responses(); missingBaseline[`${api}/git/trees/${baseTree}?recursive=1`] = { sha: baseTree, truncated: false, tree: [] }; - expect((await run(missingBaseline)).exitCode).toBe(2); + const baselineFailure = await run(missingBaseline); + expect(baselineFailure.exitCode).toBe(2); + expect(baselineFailure.report.error).toMatch(/does not match reviewed inventory/); const missingCommit = responses(); missingCommit[`${api}/commits/main`] = { sha: candidate }; - expect((await run(missingCommit)).exitCode).toBe(2); - expect((await run(responses(), { marketplace_main: { commit: "main" } })).exitCode).toBe(2); + const commitFailure = await run(missingCommit); + expect(commitFailure.exitCode).toBe(2); + expect(commitFailure.report.error).toMatch(/malformed record/); + + const inventoryFailure = await run(responses(), { + marketplace_main: { ...inventory.marketplace_main, commit: "main" }, + }); + expect(inventoryFailure.exitCode).toBe(2); + expect(inventoryFailure.report.error).toMatch(/immutable Git SHA/); }); - test("actual workflow shell accepts CRLF line endings", async () => { - const workflow = await fs.readFile(resolve(import.meta.dir, "../.github/workflows/beads-contract.yml"), "utf8"); - const selected = JSON.parse(await fs.readFile(inventoryPath, "utf8")).marketplace_main.files.map( - (file: { path: string; git_blob: string }) => ({ - path: file.path, - sha: file.git_blob, - type: "blob", - mode: "100644", - }), + testWorkflow("actual workflow parses CRLF YAML and reports an unchanged comparison", async () => { + const workflow = await fs.readFile(workflowPath, "utf8"); + const fixture = await cliFixture(); + const { main, selected } = reviewedTree(fixture.actualInventory); + const result = await runWorkflow( + workflow.replace(/\r?\n/g, "\r\n"), + fixture, + responses(selected, selected, main.commit), ); - const data = responses(selected); - data[`${api}/git/trees/${baseTree}?recursive=1`] = { sha: baseTree, truncated: false, tree: selected }; - const result = await entrypoint(data, [], workflow.replace(/\r?\n/g, "\r\n")); - expect(result.exitCode).toBe(0); + expect(result.exitCode, result.stderr).toBe(0); expect(result.report.kind).toBe("completed"); expect(result.report.status).toBe("unchanged"); }); - test("actual entrypoint: changed MAIN with the same tagged CLI result stays informational/0 and read-only", async () => { - const actualInventory = await fs.readFile(inventoryPath, "utf8"); - const packagePath = resolve(import.meta.dir, "../package.json"); - const actualPackage = await fs.readFile(packagePath, "utf8"); - const main = JSON.parse(actualInventory).marketplace_main; - expect(main.commit).toBe("4a67d0d0288c1b4ee23e17fc896f47616931ba2d"); - expect(main.files.find((f: { path: string }) => f.path === "LICENSE")?.git_blob).toBe( + testWorkflow("workflow reports MAIN changes as informational and incomplete retrieval as unavailable", async () => { + const workflow = await fs.readFile(workflowPath, "utf8"); + const fixture = await cliFixture(); + const { main, selected } = reviewedTree(fixture.actualInventory); + expect(main.commit).toBe(baseline); + expect(main.files.find(({ path }) => path === "LICENSE")?.git_blob).toBe( "2a187917a0b9e8ea3ab3db2d9e60649f0e2e4ea5", ); - const selected = main.files.map((f: { path: string; git_blob: string }) => ({ - path: f.path, - sha: f.git_blob, - type: "blob", - mode: "100644", - })); - const stableCLIResult = Object.freeze({ taggedRelease: "v1.3.1", compatible: true, exitCode: 0 }); - const stableCLIFailure = Object.freeze({ taggedRelease: "v1.3.1", compatible: false, exitCode: 1 }); - const before = JSON.stringify({ stableCLIResult, stableCLIFailure }); - const data = responses(selected); - data[`${api}/git/trees/${baseTree}?recursive=1`] = { sha: baseTree, truncated: false, tree: selected }; - const unchanged = await entrypoint(data); - expect(unchanged.exitCode).toBe(0); - expect(unchanged.report.status).toBe("unchanged"); - data[`${api}/git/trees/${nextTree}?recursive=1`] = { - sha: nextTree, - truncated: false, - tree: [...selected, blob("plugins/beads/new-main-work.md", "a")], - }; - const changed = await entrypoint(data); - expect(changed.exitCode).toBe(0); - expect(changed.report.status).toBe("changed"); - expect(changed.report.channel).toBe("development-source"); - expect(changed.report.level).toBe("info"); + const data = responses([...selected, blob("plugins/beads/new-main-work.md", "a")], selected, main.commit); + const changed = await runWorkflow(workflow, fixture, data); + expect(changed.exitCode, changed.stderr).toBe(0); + expect(changed.report).toMatchObject({ + kind: "completed", + status: "changed", + channel: "development-source", + level: "info", + }); expect(changed.stderr).toBe(""); - expect(changed.stdout).not.toMatch(/::(?:error|warning)::|fixture-secret-never-print/); expect(changed.report).not.toHaveProperty("compatible"); expect(changed.report).not.toHaveProperty("taggedRelease"); - expect((await entrypoint(data)).stdout).toBe(changed.stdout); - expect(JSON.stringify({ stableCLIResult, stableCLIFailure })).toBe(before); - expect(stableCLIFailure.exitCode).toBe(1); - expect(await fs.readFile(inventoryPath, "utf8")).toBe(actualInventory); + expect((await runWorkflow(workflow, fixture, data)).stdout).toBe(changed.stdout); + data[`${api}/git/trees/${nextTree}?recursive=1`] = { sha: nextTree, truncated: true, tree: selected }; - const unavailable = await entrypoint(data); + const unavailable = await runWorkflow(workflow, fixture, data); expect(unavailable.exitCode).toBe(2); expect(unavailable.report.kind).toBe("unavailable"); + expect(unavailable.report.error).toMatch(/truncated/); expect(unavailable.report.status).toBeUndefined(); expect(unavailable.stderr).toBe(""); - expect(JSON.stringify({ stableCLIResult, stableCLIFailure })).toBe(before); - const blindAdvancement = await entrypoint({}, ["--advance-baseline", candidate]); - expect(blindAdvancement.exitCode).toBe(2); - expect(blindAdvancement.report.kind).toBe("unavailable"); - expect(await fs.readFile(inventoryPath, "utf8")).toBe(actualInventory); - expect(await fs.readFile(packagePath, "utf8")).toBe(actualPackage); + expect(await fs.readFile(fixture.inventoryCopy, "utf8")).toBe(fixture.actualInventory); + expect(await fs.readFile(fixture.packageCopy, "utf8")).toBe(fixture.actualPackage); + }); + + test("actual CLI rejects baseline advancement before making a request", async () => { + const fixture = await cliFixture(); + const preload = join(fixture.directory, "fetch.ts"); + const requestMarker = join(fixture.directory, "request"); + await fs.writeFile( + preload, + `globalThis.fetch = async () => { + await Bun.write(${JSON.stringify(requestMarker)}, "unexpected request"); + throw new Error("Unexpected fixture request"); + };`, + ); + const result = runChild( + [ + process.execPath, + "--no-env-file", + "--preload", + preload, + join(fixture.directory, "scripts", "check-beads-integration.ts"), + "--advance-baseline", + candidate, + ], + fixture.directory, + ); + expect(result.exitCode).toBe(2); + expect(JSON.parse(result.stdout.toString())).toMatchObject({ + kind: "unavailable", + error: expect.stringContaining("invalid arguments"), + }); + expect(await fs.exists(requestMarker)).toBeFalse(); + expect(await fs.readFile(fixture.inventoryCopy, "utf8")).toBe(fixture.actualInventory); + expect(await fs.readFile(fixture.packageCopy, "utf8")).toBe(fixture.actualPackage); }); }); diff --git a/tests/workflows.test.ts b/tests/workflows.test.ts index 7735678..10cff92 100644 --- a/tests/workflows.test.ts +++ b/tests/workflows.test.ts @@ -1,865 +1,374 @@ -import { createHash } from "node:crypto"; import { Message } from "@opencode/ai/effect"; -import baseline from "./fixtures/non-sync-command-baseline.json"; +import type { Plugin } from "@opencode/plugin"; +import type { CommandInvocation } from "@opencode/plugin/promise/command"; +import { Session } from "@opencode/schema/session"; +import { SessionMessage } from "@opencode/schema/session-message"; +import { Skill } from "@opencode/schema/skill"; import { describe, expect, mock, test } from "bun:test"; -import { existsSync, readFileSync } from "node:fs"; -import { relative, resolve, sep } from "node:path"; -import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import inventory from "../docs/claude-code-integration-inventory.json"; +import { DIAGNOSTICS_HELP } from "../src/diagnostics"; import { createBeadsCommands, expandBeadsWorkflowContext, loadBeadsSkill, WORKFLOWS } from "../src/workflows"; -import type { Plugin } from "@opencode/plugin"; -import type { CommandInvocation } from "@opencode/plugin/promise/command"; +type NativePrompt = Parameters<Plugin.Context["session"]["prompt"]>[0]; type StoredSessionMessage = Awaited<ReturnType<Plugin.Context["session"]["context"]>>[number]; type StoredUserMessage = Extract<StoredSessionMessage, { type: "user" }>; -function storedUserMessage(id: string, text: string, metadata?: StoredUserMessage["metadata"]): StoredUserMessage { - return { id, type: "user", time: { created: 1 }, text, ...(metadata === undefined ? {} : { metadata }) }; -} - -function projectedUserMessage(id: string, text: string) { - return Message.make({ id, role: "user", content: text }); -} - -type InventoryEntry = { - category: string; - path: string; - selected_mapping: { - disposition: string; - target: string; - task_ids: string[]; +const assetRoot = fileURLToPath(new URL("../assets/oc-beads", import.meta.url)); +const diagnosticsName = "oc-beads:diagnostics"; +const selectedCommands = inventory.marketplace_main.files + .filter(({ category, path }) => category === "command" && path.startsWith("plugins/beads/skills/beads/commands/")) + .map(({ selected_mapping }) => selected_mapping!.target) + .sort(); + +function invocation(text: string, delivery: CommandInvocation["delivery"] = "queue"): CommandInvocation { + return { + sessionID: Session.ID.make(`ses_fixture_${delivery}`), + delivery, + prompt: { + text, + files: [{ uri: "file:///tmp/a%20b", name: "a b" }], + agents: [{ name: "build" }], + skills: [{ id: Skill.ID.make("oc-beads") }], + }, }; -}; - -type Inventory = { - marketplace_main: { - files: InventoryEntry[]; - }; -}; - -const repositoryRoot = process.cwd(); -const assetRoot = resolve(repositoryRoot, "assets/oc-beads"); -const skillPath = resolve(assetRoot, "SKILL.md"); - -function readInventory(): Inventory { - return JSON.parse( - readFileSync(resolve(repositoryRoot, "docs/claude-code-integration-inventory.json"), "utf8"), - ) as Inventory; } -function selectedSupportingFiles(): InventoryEntry[] { - return readInventory().marketplace_main.files.filter( - (entry) => - (entry.category === "resource" || entry.category === "adr") && entry.selected_mapping.task_ids.includes("2.1"), +function recordPrompt() { + return mock( + async (input: NativePrompt): ReturnType<Plugin.Context["session"]["prompt"]> => ({ + id: SessionMessage.ID.make("msg_fixture"), + sessionID: input.sessionID, + delivery: input.delivery ?? "queue", + type: "user", + time: { created: 1 }, + payload: { text: input.text }, + }), ); } -function readResource(name: string): string { - return readFileSync(resolve(assetRoot, `resources/${name}.md`), "utf8"); -} - -describe("oc-beads guidance assets", () => { - test("covers and explicitly links every selected marketplace resource and ADR", () => { - const supportingFiles = selectedSupportingFiles(); - const resources = supportingFiles.filter((entry) => entry.category === "resource"); - const adrs = supportingFiles.filter((entry) => entry.category === "adr"); - const skill = readFileSync(skillPath, "utf8"); - - expect(resources).toHaveLength(15); - expect(adrs).toHaveLength(1); - - const missing = supportingFiles.filter( - (entry) => !existsSync(resolve(repositoryRoot, entry.selected_mapping.target)), - ); - expect(missing.map((entry) => entry.selected_mapping.target)).toEqual([]); - - const unlinked = supportingFiles.filter((entry) => { - const relativePath = relative(assetRoot, resolve(repositoryRoot, entry.selected_mapping.target)) - .split(sep) - .join("/"); - return !skill.includes(`](${relativePath})`); - }); - expect(unlinked.map((entry) => entry.selected_mapping.target)).toEqual([]); - }); - - test("teaches append checkpoints, selective memory, and bounded actor-owned work", () => { - const skill = readFileSync(skillPath, "utf8"); - const workflows = readFileSync(resolve(assetRoot, "resources/WORKFLOWS.md"), "utf8"); - const resumability = readFileSync(resolve(assetRoot, "resources/RESUMABILITY.md"), "utf8"); - const creation = readFileSync(resolve(assetRoot, "resources/ISSUE_CREATION.md"), "utf8"); - const guidance = `${skill}\n${workflows}`; - - expect(guidance).toContain("--append-notes"); - expect(guidance).toContain("--actor"); - expect(guidance).toContain("--sandbox"); - expect(guidance).toContain("created_by"); - expect(guidance).toContain("assignee"); - expect(guidance).toContain("reusable knowledge"); - expect(guidance).toContain("authorized batch"); - expect(guidance).toContain("--notes="); - expect(guidance).toContain("typed-only"); - for (const text of [skill, workflows, resumability]) { - expect(text).toContain("--append-notes"); - expect(text).toContain("--notes"); - } - for (const text of [creation, resumability, workflows]) { - expect(text).toContain("Verbatim upstream excerpt"); - expect(text).toContain("OpenCode adaptation"); - expect(text).toContain("5ac194105c138ca799bc2f6534c8f92712d8d782"); - } - expect(skill).toContain("acceptance states stable, verifiable outcomes"); - expect(workflows).toContain("OpenCode adaptation"); - expect(workflows).toContain("5ac194105c138ca799bc2f6534c8f92712d8d782"); - }); - - test("keeps current CLI access honest without claiming host prerequisites or automatic setup", () => { - const skill = readFileSync(skillPath, "utf8"); - - expect(skill).toContain("permissioned CLI"); - expect(skill).toContain( - "Do not initialize or reroute a store, synchronize it, change permissions, or enable automation as a side effect.", - ); - expect(skill).not.toMatch(/requires? OpenCode\s+v?\d/i); - expect(skill).not.toMatch(/OpenCode\s*>=\s*2\./i); - expect(skill).not.toMatch(/\bmcp__\w+/i); - expect(skill).not.toMatch(/automatically run `bd init`/i); - }); - - test("states the unsupported agent and slot CLI limitation with a supported boundary", () => { - const agents = readFileSync(resolve(assetRoot, "resources/AGENTS.md"), "utf8"); - const troubleshooting = readFileSync(resolve(assetRoot, "resources/TROUBLESHOOTING.md"), "utf8"); - - expect(agents).toMatch(/`bd agent --help` and `bd slot --help` both\s+return unknown-command errors\./); - expect(agents).toContain("not a one-to-one implementation"); - expect(troubleshooting).toMatch(/do not initialize, migrate, reroute, repair, or synchronize it\s+automatically/); - }); - - test("gives dependency choices, direction, and a parallel merge example", () => { - const dependencies = readResource("DEPENDENCIES"); - - expect(dependencies).toMatch(/\|\s*Question\s*\|\s*Relationship\s*\|/); - expect(dependencies).toMatch(/--deps=.*depends-on:/); - expect(dependencies).toContain("--parent='<epic-id>'"); - expect(dependencies).toContain("not an ordering edge"); - expect(dependencies).toMatch(/hard\s+block only when a real prerequisite exists/i); - expect(dependencies).toMatch(/diamond/i); - expect(dependencies).toMatch(/`discovered-from` does not make that\s+cascade required work/i); - }); - - test("shows a useful before-and-after checkpoint and a compact handoff shape", () => { - const resumability = readResource("RESUMABILITY"); - - expect(resumability).toContain("### Before checkpoint"); - expect(resumability).toContain("### After checkpoint"); - expect(resumability).toMatch(/attempted[\s\S]*evidence[\s\S]*rationale[\s\S]*blocker[\s\S]*next/i); - expect(resumability).toContain("Minimal handoff template"); - expect(resumability).toMatch(/tested.{0,50}(snippet|example)|(?:snippet|example).{0,50}tested/i); - expect(resumability).toMatch(/raw (?:log|JSON|dump)/i); - }); - - test("helps choose transient versus durable work and preserves planning authority", () => { - const boundaries = readResource("BOUNDARIES"); - const integration = readResource("INTEGRATION_PATTERNS"); - - expect(boundaries).toContain("| Situation | Record | Why |"); - expect(boundaries).toMatch(/experimental[\s\S]{0,100}opt-in[\s\S]{0,100}host-owned/i); - expect(boundaries).toMatch(/transition/i); - expect(integration).toContain("OpenSpec"); - expect(integration).toContain("one bounded planning Bead"); - expect(integration).toMatch(/review is independently owned/i); - expect(integration).toMatch(/same review Bead[\s\S]*retry|same review Bead[\s\S]*recheck/i); - expect(integration).toMatch(/do not create a ticket per\s+document, retry/i); - expect(integration).toContain("--append-notes"); - expect(integration).toContain("--sandbox"); - }); - - test("distinguishes human and timer gates and documents deliberate inspection and resolution", () => { - const gates = readResource("ASYNC_GATES"); - - expect(gates).toMatch(/human.{0,100}timeout.{0,100}(?:stored|metadata).{0,100}(?:not enforced|does not enforce)/is); - expect(gates).toMatch(/timeout has elapsed when an authorized executor runs/i); - expect(gates).toContain("bd gate check --type=timer"); - expect(gates).toMatch(/success[\s\S]*failure[\s\S]*escalat/i); - expect(gates).toContain("bd gate create"); - expect(gates).toContain("bd gate show"); - expect(gates).toContain("bd gate resolve"); - expect(gates).toMatch(/do not (?:add|run|schedule).{0,40}(?:poll|watch|approval)/i); - }); - - test("explains molecule lifetime and a bounded research or review wisp lifecycle", () => { - const chemistry = readResource("CHEMISTRY_PATTERNS"); - const molecules = readResource("MOLECULES"); - const guidance = `${chemistry}\n${molecules}`; - - expect(guidance).toMatch(/persistent molecule.{0,80}audit history/i); - expect(guidance).toMatch(/wisp.{0,100}ephemeral/i); - expect(guidance).toMatch(/research|review/i); - expect(guidance).toContain("bd mol wisp create"); - expect(guidance).toContain("bd mol squash"); - expect(guidance).toContain("bd mol burn"); - expect(guidance).toMatch(/promot[\s\S]{0,100}findings[\s\S]{0,100}(?:noise|no future value)/i); - }); - - test("keeps copyable placeholders quoted and executor actors neutral", () => { - const files = [ - skillPath, - ...selectedSupportingFiles().map((entry) => resolve(repositoryRoot, entry.selected_mapping.target)), - ]; - const guidance = files.map((file) => readFileSync(file, "utf8")).join("\n"); - const actors = [...guidance.matchAll(/--actor=([^\s`]+)/g)].map((match) => match[1]); - - expect(actors.length).toBeGreaterThan(0); - expect(actors.filter((actor) => actor !== "'<executor-actor>'" && actor !== "'<actual-human-actor>'")).toEqual([]); - expect(guidance).not.toMatch(/codex:/); - // Strip quoted arguments: remaining angle brackets in shell blocks would be redirects. - const shellBlocks = [...guidance.matchAll(/```(?:sh|bash)\n([\s\S]*?)```/g)].map((match) => match[1] ?? ""); - const unquotedShell = shellBlocks.join("\n").replace(/'[^']*'|"[^"]*"/g, ""); - expect(unquotedShell).not.toMatch(/<[^>\n]+>/); - expect(readFileSync(skillPath, "utf8")).toMatch(/host-rendered actor[\s\S]{0,100}request session and agent/i); - expect(readResource("ASYNC_GATES")).toMatch(/(?:human[^.]*runs|run by[^.]*human)/i); - }); - - test("shows existing-issue dependency direction and graph readback", () => { - const dependencies = readResource("DEPENDENCIES"); - - expect(dependencies).toMatch( - /bd dep add '<dependent-id>' '<prerequisite-id>'[^\n]*--actor='<executor-actor>'[^\n]*--sandbox/, - ); - expect(dependencies).toMatch(/wrong[\s\S]*right/i); - expect(dependencies).toMatch(/phase 1[\s\S]*phase 2/i); - expect(dependencies).toContain("bd blocked --json"); - expect(dependencies).toContain("bd dep list '<dependent-id>'"); - }); - - test("recovers assigned active work before acting and protects existing memory keys", () => { - const recovery = readResource("RESUMABILITY"); - const skill = readFileSync(skillPath, "utf8"); - - expect(recovery).toMatch(/bd list --status=in_progress --assignee='<executor-actor>'[^\n]*--json/); - expect(recovery).toContain("bd show '<issue-id>'"); - expect(recovery).toMatch(/checkpoint[\s\S]*verify[\s\S]*before acting/i); - expect(recovery).toMatch(/(?:not|never|rather than)[^.]*`bd ready`/i); - expect(skill).toMatch(/recall[^.]*before[^.]*key/i); - expect(skill).toMatch(/same key[^.]*replace[^.]*in place/i); +function expectSubmission(sent: NativePrompt, input: CommandInvocation, text: string) { + expect(sent.text).toBe(text); + expect(sent.sessionID).toBe(input.sessionID); + expect(sent.delivery).toBe(input.delivery); + expect(sent.files).toBe(input.prompt.files); + expect(sent.agents).toBe(input.prompt.agents); + expect(sent.skills).toBe(input.prompt.skills); + expect(sent.metadata).toEqual({ + ocBeadsWorkflow: { version: 1, instructions: expect.any(String) }, }); + return (sent.metadata!.ocBeadsWorkflow as { instructions: string }).instructions; +} - test("makes the project specification system and planning pattern conditional", () => { - for (const guidance of [ - readFileSync(skillPath, "utf8"), - readResource("BOUNDARIES"), - readResource("INTEGRATION_PATTERNS"), - ]) { - expect(guidance).toMatch(/project.{0,20}specification system/i); - expect(guidance).toMatch(/OpenSpec, when used/); - } - expect(readResource("INTEGRATION_PATTERNS")).toMatch(/project.policy example[^.]*not[^.]*Beads requirement/is); - }); -}); +function expectDiagnosticReport(instructions: string, report: string) { + expect(instructions.split("\nBEGIN_DIAGNOSTIC_REPORT\n")).toEqual([ + expect.stringMatching(/[^\n]\n$/), + `${report}\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n`, + ]); +} -/** Visible bodies and effective static instructions are asserted separately. */ -function effectiveText(sent: Record<string, unknown>): string { - const id = "workflow-command"; - const metadata = sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }; - const stored = storedUserMessage(id, String(sent.text), { ocBeadsWorkflow: metadata.ocBeadsWorkflow }); - const messages = [projectedUserMessage(id, String(sent.text))]; - expandBeadsWorkflowContext(messages, [stored]); - return messages[0]!.content - .filter((part) => part.type === "text") - .map((part) => part.text) - .join("\n"); +function storedUserMessage(id: string, text: string, metadata?: StoredUserMessage["metadata"]): StoredUserMessage { + return { id, type: "user", time: { created: 1 }, text, ...(metadata === undefined ? {} : { metadata }) }; } -describe("packaged native workflows", () => { - test("diagnostics captures once behind compact history and replays without recollecting", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const report = JSON.stringify({ - host: "2.1.2", - plugin: { name: "@snarkipus/opencode-beads", version: "fixture-version" }, - guard: "withheld", - }); - const diagnostics = mock(async () => report); - const command = createBeadsCommands({ prompt }, diagnostics).find((c) => c.name === "oc-beads:diagnostics")!; - for (const delivery of ["queue", "steer"] as const) { - for (const text of ["", "explain", " exact input ", "first\r\n second\r\n"]) { - const input = { - sessionID: "s1", - delivery, - prompt: { - text, - files: [{ uri: "file:///fixture" }], - agents: [{ name: "build" }], - skills: [{ id: "custom" }], - }, - } as unknown as CommandInvocation; - const count = diagnostics.mock.calls.length; - await command.execute(input); - const sent = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - expect(sent.text).toBe(`/oc-beads:diagnostics${text ? `${/[\r\n]/.test(text) ? "\n" : " "}${text}` : ""}`); - expect(sent.files).toBe(input.prompt.files); - expect(sent.agents).toBe(input.prompt.agents); - expect(sent.skills).toBe(input.prompt.skills); - expect(sent.sessionID).toBe(input.sessionID); - expect(sent.delivery).toBe(delivery); - const snapshot = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }) - .ocBeadsWorkflow; - expect(snapshot.version).toBe(1); - expect(snapshot.instructions.split(report)).toHaveLength(2); - expect(snapshot.instructions).toContain("or add diagnoses or commentary"); - expect(diagnostics).toHaveBeenLastCalledWith(input.sessionID, text); - expect(snapshot.instructions).not.toContain("unique build"); - const storageText = JSON.stringify(sent); - const stored = storedUserMessage("diagnostic-command", String(sent.text), { - ocBeadsWorkflow: (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }) - .ocBeadsWorkflow, - }); - const messages = [projectedUserMessage(stored.id, stored.text)]; - expandBeadsWorkflowContext(messages, [stored]); - expect(messages[0]!.content[0]).toEqual(Message.text(snapshot.instructions)); - const expanded = JSON.stringify(messages); - expandBeadsWorkflowContext(messages, [stored]); - expect(JSON.stringify(messages)).toBe(expanded); - expect(JSON.stringify(sent)).toBe(storageText); - expect(diagnostics).toHaveBeenCalledTimes(count + 1); - } +describe("WORKFLOWS catalog", () => { + test("matches the reviewed inventory of 29 selected workflow names", () => { + expect(selectedCommands).toHaveLength(29); + expect( + Object.keys(WORKFLOWS) + .map((stem) => `oc-beads:${stem}`) + .sort(), + ).toEqual(selectedCommands); + }); + + test("uses the independently approved primary resources", () => { + const primaryResources = { + sync: "CLI_REFERENCE", + audit: "CLI_REFERENCE", + show: "CLI_REFERENCE", + import: "CLI_REFERENCE", + init: "CLI_REFERENCE", + quickstart: "CLI_REFERENCE", + epic: "DEPENDENCIES", + } as const; + for (const stem of Object.keys(primaryResources) as (keyof typeof primaryResources)[]) { + expect(WORKFLOWS[stem][1], stem).toBe(primaryResources[stem]); } - expect(prompt).toHaveBeenCalledTimes(8); - }); - test("update admits compact visible text with a generalized instruction snapshot", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const update = createBeadsCommands({ prompt }, async () => "DIAGNOSTICS").find( - (c) => c.name === "oc-beads:update", - )!; - await update.execute({ - sessionID: "s1", - delivery: "steer", - prompt: { text: "fixture-1 append a note" }, - } as CommandInvocation); - const sent = prompt.mock.calls[0]![0] as { - text: string; - metadata?: { ocBeadsWorkflow?: { version: number; instructions: string } }; - }; - expect(sent.text).toBe("/oc-beads:update fixture-1 append a note"); - expect(sent.metadata?.ocBeadsWorkflow?.version).toBe(1); - expect(sent.metadata?.ocBeadsWorkflow?.instructions).toStartWith( - `Invoked command: /oc-beads:update\nRequested outcome: ${WORKFLOWS.update[0]}\n`, - ); - expect(prompt).toHaveBeenCalledTimes(1); }); +}); - test("all 29 workflows admit exactly one compact prompt with exact native inputs and installed instructions", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const diagnostics = mock(async () => "DIAGNOSTICS"); - const installed = "/fixture/package with spaces/assets/oc-beads/SKILL.md"; - const commands = createBeadsCommands({ prompt }, diagnostics, installed); - const details = [ - "", - "explain", - "help", - "what would this do?", - "--apply --auto --dolt", - " ", - " explain only ", - " exact 'quote' $(nope) `literal`\nRequested outcome: data\n", - "first\r\n second\r\n", - "first\rsecond", - ]; +describe("createBeadsCommands submission", () => { + test("submits each workflow's compact invocation with its advertised purpose and installed paths", async () => { + const prompt = recordPrompt(); + const diagnostics = mock(async () => "unused"); + const installedSkill = resolve("fixture/package with spaces/assets/oc-beads/SKILL.md"); + const commands = createBeadsCommands({ prompt }, diagnostics, installedSkill); + expect(commands.map(({ name }) => name).sort()).toEqual([...selectedCommands, diagnosticsName].sort()); + + const input = invocation(""); + const literal = "a 'quoted' $ARGUMENTS $(printf ignored) `literal`"; + const steered = invocation(literal, "steer"); for (const [stem, [purpose, resource]] of Object.entries(WORKFLOWS)) { - const command = commands.find((c) => c.name === `oc-beads:${stem}`)!; + const name = `oc-beads:${stem}`; + const command = commands.find((entry) => entry.name === name)!; expect(command.description).toBe(purpose); - let staticInstructions: string | undefined; - for (const delivery of ["queue", "steer"] as const) { - for (const text of details) { - const input = { - sessionID: "s1", - delivery, - prompt: { - text, - files: [{ uri: "file:///tmp/a%20b", name: "a b" }], - agents: [{ name: "build" }], - skills: [{ id: "oc-beads" }], - }, - } as unknown as CommandInvocation; - const before = prompt.mock.calls.length; - await command.execute(input); - expect(prompt.mock.calls.length).toBe(before + 1); - const sent = prompt.mock.calls.at(-1)![0] as { - text: string; - metadata: { ocBeadsWorkflow: { version: number; instructions: string } }; - files: unknown; - agents: unknown; - skills: unknown; - delivery: string; - sessionID: string; - }; - expect(sent.text).toBe(`/oc-beads:${stem}${text ? `${/[\r\n]/.test(text) ? "\n" : " "}${text}` : ""}`); - expect(Object.keys(sent.metadata)).toEqual(["ocBeadsWorkflow"]); - const snapshot = sent.metadata.ocBeadsWorkflow; - expect(snapshot.version).toBe(1); - expect(snapshot.instructions).toStartWith( - `Invoked command: /oc-beads:${stem}\nRequested outcome: ${purpose}\n`, - ); - expect(snapshot.instructions).toContain(JSON.stringify(installed)); - expect(snapshot.instructions).toEndWith( - `Supporting guidance: ${JSON.stringify(resolve("/fixture/package with spaces/assets/oc-beads/resources", `${resource}.md`))}`, - ); - expect(snapshot.instructions).not.toContain("Literal user details:"); - expect(snapshot.instructions).not.toMatch(/codex:|claude:|s1|beads-task-agent/); - staticInstructions ??= snapshot.instructions; - expect(snapshot.instructions).toBe(staticInstructions); - expect(sent.files).toBe(input.prompt.files); - expect(sent.agents).toBe(input.prompt.agents); - expect(sent.skills).toBe(input.prompt.skills); - expect(sent.delivery).toBe(delivery); - expect(sent.sessionID).toBe(input.sessionID); - } - } + + prompt.mockClear(); + await command.execute(input); + expect(prompt).toHaveBeenCalledTimes(1); + const instructions = expectSubmission(prompt.mock.calls[0]![0], input, `/${name}`); + expect(instructions).toStartWith(`Invoked command: /${name}\nRequested outcome: ${purpose}\n`); + expect(instructions).toContain(JSON.stringify(installedSkill)); + expect(instructions).not.toMatch(/codex:|claude:|\bs1\b|beads-task-agent/); + expect(instructions).not.toContain(input.sessionID); + expect(instructions).not.toContain(steered.sessionID); + expect(instructions).toEndWith( + `Supporting guidance: ${JSON.stringify(join(dirname(installedSkill), "resources", `${resource}.md`))}`, + ); + + prompt.mockClear(); + await command.execute(steered); + expect(prompt).toHaveBeenCalledTimes(1); + expect(expectSubmission(prompt.mock.calls[0]![0], steered, `/${name} ${literal}`)).toBe(instructions); } - expect(prompt).toHaveBeenCalledTimes(29 * 2 * details.length); expect(diagnostics).not.toHaveBeenCalled(); }); - test("generalized and legacy snapshots select one stored instruction body without mutating history", () => { - const good = (instructions: string) => ({ version: 1, instructions }); - const malformed = { version: 1, instructions: 42 }; - for (const [metadata, instructions] of [ - [{ ocBeadsWorkflow: good("GENERAL") }, "GENERAL"], - [{ ocBeadsSync: good("LEGACY") }, "LEGACY"], - [{ ocBeadsWorkflow: good("GENERAL"), ocBeadsSync: good("LEGACY") }, "GENERAL"], - [{ ocBeadsWorkflow: malformed, ocBeadsSync: good("LEGACY") }, "LEGACY"], - [{ ocBeadsWorkflow: good("GENERAL"), ocBeadsSync: malformed }, "GENERAL"], - ] as const) { - const stored = storedUserMessage("retained-id", "hook-edited /oc-beads:show", { ...metadata, foreign: "keep" }); - const raw = JSON.stringify(stored); - const request = projectedUserMessage(stored.id, stored.text); - const messages = [request]; - expect(expandBeadsWorkflowContext(messages, [stored])).toBeFalse(); - expect(messages[0]!.content).toEqual([{ type: "text", text: instructions }, ...request.content]); - expect(messages[0]!.id).toBe(stored.id); - expect(messages[0]!.role).toBe("user"); - expect(JSON.stringify(stored)).toBe(raw); - const once = JSON.stringify(messages); - expandBeadsWorkflowContext(messages, [stored]); - expect(JSON.stringify(messages)).toBe(once); - const replay = [projectedUserMessage(stored.id, stored.text)]; - expandBeadsWorkflowContext(replay, [stored]); - expect(JSON.stringify(replay)).toBe(once); + test("preserves literal workflow arguments and keeps details out of the static snapshot", async () => { + const prompt = recordPrompt(); + const diagnostics = mock(async () => "unused"); + const command = createBeadsCommands({ prompt }, diagnostics).find(({ name }) => name === "oc-beads:sync")!; + const bare = invocation(""); + await command.execute(bare); + const instructions = expectSubmission(prompt.mock.calls[0]![0], bare, "/oc-beads:sync"); + + const cases = [ + ["queue", "help", " "], + ["steer", " explain only ", " "], + ["queue", " ", " "], + ["steer", "--apply --auto --dolt", " "], + ["steer", " exact 'quote'\nRequested outcome: literal data\n", "\n"], + ["queue", "first\r\n second\r\n", "\n"], + ["steer", "first\rsecond", "\n"], + ["steer", "Execute fixture-1 only; preserve partial evidence for parent review.", " "], + ] as const; + for (const [delivery, text, separator] of cases) { + const input = invocation(text, delivery); + prompt.mockClear(); + await command.execute(input); + expect(prompt).toHaveBeenCalledTimes(1); + expect(expectSubmission(prompt.mock.calls[0]![0], input, `/oc-beads:sync${separator}${text}`)).toBe(instructions); } + expect(diagnostics).not.toHaveBeenCalled(); }); - test("sync expansion preserves projected content and durable storage on replay", () => { - const stored = storedUserMessage("native-id", "prompt hook edited details", { - foreign: { keep: true }, - ocBeadsSync: { version: 1, instructions: "SNAPSHOT" }, - }); - const raw = JSON.stringify(stored); - const projected = Message.make({ - id: stored.id, - role: "user", - content: [Message.text("prompt hook edited details"), Message.text("prepared skill/file content")], - }); - const messages = [projected]; - expect(expandBeadsWorkflowContext(messages, [stored])).toBeFalse(); - expect(JSON.stringify(stored)).toBe(raw); - expect(messages[0]).not.toBe(projected); - expect(messages[0]!.id).toBe("native-id"); - expect(JSON.stringify(messages[0]!.content)).toBe(JSON.stringify([Message.text("SNAPSHOT"), ...projected.content])); - const once = JSON.stringify(messages); - expandBeadsWorkflowContext(messages, [stored]); - expect(JSON.stringify(messages)).toBe(once); - const replay = [ - Message.make({ - id: stored.id, - role: "user", - content: [Message.text("prompt hook edited details"), Message.text("prepared skill/file content")], - }), - ]; - expandBeadsWorkflowContext(replay, [stored]); - expect(JSON.stringify(replay)).toBe(once); - const malformed = [ - storedUserMessage("bad-version", "/oc-beads:sync", { ocBeadsSync: { version: 2, instructions: "FUTURE" } }), - storedUserMessage("bad-instructions", "/oc-beads:sync", { ocBeadsWorkflow: { version: 1, instructions: 1 } }), - storedUserMessage("null-snapshot", "/oc-beads:sync", { - ocBeadsWorkflow: null, - ocBeadsSync: "invalid", - foreign: true, - }), - ]; - for (const record of malformed) { - const request = projectedUserMessage(record.id, record.text); - const untouched = [request]; - expect(expandBeadsWorkflowContext(untouched, [record])).toBeTrue(); - expect(untouched[0]).toBe(request); - } - const assistant = Message.make({ id: stored.id, role: "assistant", content: "assistant" }); - const assistantMessages = [assistant]; - expect(expandBeadsWorkflowContext(assistantMessages, [stored])).toBeFalse(); - expect(assistantMessages[0]).toBe(assistant); - const ordinary = projectedUserMessage("ordinary", "plain user input"); - const ordinaryMessages = [ordinary]; - expect(expandBeadsWorkflowContext(ordinaryMessages, [])).toBeFalse(); - expect(ordinaryMessages[0]).toBe(ordinary); - }); + test.each([ + ["bare", "queue", "", ""], + ["explanation", "steer", "explain", " explain"], + ["help prefix", "queue", "help me", " help me"], + ["literal single line", "steer", " exact $ARGUMENTS ", " exact $ARGUMENTS "], + ["literal multiline", "queue", "first\r\n second\r\n", "\nfirst\r\n second\r\n"], + ] as const)("captures a finished diagnostic report once for %s input", async (_case, delivery, text, suffix) => { + const prompt = recordPrompt(); + const report = + "## Beads diagnostics — ✅ Healthy\n\n| Check | Value |\n|---|---|\n| Workspace | `/observed/root` |\n"; + const diagnostics = mock(async (_sessionID: string, _text?: string) => report); + const command = createBeadsCommands({ prompt }, diagnostics).find(({ name }) => name === diagnosticsName)!; + const input = invocation(text, delivery); - test("ambiguous sync admission failure propagates once without retry", async () => { - const failure = new Error("ambiguous native admission"); - const prompt = mock(async () => { - throw failure; + await command.execute(input); + + expect(diagnostics.mock.calls).toEqual([[input.sessionID, text]]); + expect(prompt).toHaveBeenCalledTimes(1); + const instructions = expectSubmission(prompt.mock.calls[0]![0], input, `/${diagnosticsName}${suffix}`); + expectDiagnosticReport(instructions, report); + expect(instructions.split(report)).toHaveLength(2); + if (text) expect(instructions).not.toContain(text); + }); + + test.each([ + ["help", " help"], + [" HeLp ", " HeLp "], + ["help\n", "\nhelp\n"], + ])("submits static diagnostics help for %j without collection", async (text, suffix) => { + const prompt = recordPrompt(); + const diagnostics = mock(async () => { + throw new Error("help must skip collection"); }); - const sync = createBeadsCommands({ prompt }, async () => "DIAGNOSTICS").find((c) => c.name === "oc-beads:sync")!; - await expect( - sync.execute({ sessionID: "s1", delivery: "queue", prompt: { text: "" } } as CommandInvocation), - ).rejects.toBe(failure); + const command = createBeadsCommands({ prompt }, diagnostics).find(({ name }) => name === diagnosticsName)!; + const input = invocation(text); + + await command.execute(input); + + expect(diagnostics).not.toHaveBeenCalled(); expect(prompt).toHaveBeenCalledTimes(1); + expectDiagnosticReport( + expectSubmission(prompt.mock.calls[0]![0], input, `/${diagnosticsName}${suffix}`), + DIAGNOSTICS_HELP, + ); }); - test("all 29 historical non-sync payload digests preserve descriptions, instructions and diagnostics", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const actual: Record<string, string> = {}; - for (const c of createBeadsCommands( - { prompt }, - async () => "DIAGNOSTICS", - "/fixture/package/assets/oc-beads/SKILL.md", - )) { - if (c.name === "oc-beads:sync") continue; - await c.execute({ - sessionID: "s1", - delivery: "queue", - prompt: { - text: "exact 'details' $(nope) `literal`\nsecond line", - files: [{ uri: "file:///tmp/a%20b", name: "a b" }], - agents: [{ name: "build" }], - skills: [{ id: "oc-beads" }], - }, - } as unknown as CommandInvocation); - const submitted = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - let sent = submitted; - if (c.name !== "oc-beads:diagnostics") { - // Restore the ORIGINAL fixed rich payload, including its native fields/key order. - // Existing hashes cover description + full submission, not bare instructions. - const { metadata, ...native } = submitted; - const snapshot = (metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; - // The frozen historical digest uses POSIX fixture paths, not the runner's drive/separators. - const resource = WORKFLOWS[c.name.slice("oc-beads:".length) as keyof typeof WORKFLOWS][1]; - const instructions = snapshot.instructions.replace( - JSON.stringify(resolve("/fixture/package/assets/oc-beads/resources", `${resource}.md`)), - JSON.stringify(`/fixture/package/assets/oc-beads/resources/${resource}.md`), - ); - sent = { - ...native, - text: `${instructions}\n\nLiteral user details:\nexact 'details' $(nope) \`literal\`\nsecond line`, - }; - } - if (c.name === "oc-beads:diagnostics") { - const { metadata, ...native } = submitted; - const snapshot = (metadata as { ocBeadsWorkflow: { instructions: string } }).ocBeadsWorkflow; - // Diagnostics uses the current command purpose and accepted preamble. - // Exact full framing has dedicated coverage; generic workflow digests remain frozen. - sent = { - ...native, - text: `${snapshot.instructions.split("\n").slice(0, 2).join("\n")}\n\nUser request:\n${String(submitted.text).slice("/oc-beads:diagnostics\n".length)}`, - }; - } - actual[c.name] = createHash("sha256") - .update(JSON.stringify({ description: c.description, sent })) - .digest("hex"); - } - expect(actual).toEqual({ - ...baseline.commands, - "oc-beads:diagnostics": "8f85945c394e5c7548195ac9eb5303dacbbadc3230091c81534f1e5d1e3c390c", - "oc-beads:update": "b4f6a0e8b2729bab4361a6252a86217eac825b6c66f2db8d3dcc0f1803de7b25", + test("propagates a rejected diagnostic capture without retry or prompt submission", async () => { + const failure = new Error("capture failed"); + const prompt = recordPrompt(); + const diagnostics = mock(async () => { + throw failure; }); - }); + const command = createBeadsCommands({ prompt }, diagnostics).find(({ name }) => name === diagnosticsName)!; - test("forwards exact scope and partial-handoff authority cues without selecting or claiming work", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const commands = createBeadsCommands({ prompt }, async () => "DIAGNOSTICS"); - // These are literal caller instructions, not a mock model or a scope interpreter. - const scenarios = [ - ["ready", "Execute exact fixture-1 only; stop without substitution; closure belongs to parent."], - [ - "ready", - "Authorized batch fixture-1 and fixture-2 only; claim each atomically; validate and append evidence before continuing.", - ], - [ - "create", - "Record discovered-from:fixture-1 follow-up when authorized; this does not authorize its execution or assignment.", - ], - ["list", "Read-only graph overview; do not claim or write."], - [ - "close", - "Permission denied and acceptance incomplete; preserve partial status, do not close. Actor worker:fixture; full session fixture-session; tried A; result failed; because B; validation pending; reference task:fixture-1; next parent review.", - ], - ] as const; - for (const [stem, text] of scenarios) { - const input = { sessionID: "parent", delivery: "queue", prompt: { text } } as unknown as CommandInvocation; - await commands.find((command) => command.name === `oc-beads:${stem}`)!.execute(input); - const sent = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - expect(sent.sessionID).toBe("parent"); - expect(sent.delivery).toBe("queue"); - expect(sent.text).toContain(text); - expect(effectiveText(sent)).toContain(WORKFLOWS[stem][0]); - } - expect(prompt).toHaveBeenCalledTimes(scenarios.length); - // The established rich assets agree with the new canonical scope guidance. - const skill = readFileSync(skillPath, "utf8"); - const workflows = readResource("WORKFLOWS"); - expect(skill).toContain("An assignment to one specific item is an exact assignment"); - expect(workflows).toContain("Explicitly authorized batches may continue within their stated scope"); - expect(workflows).toContain("If a parent or human owns acceptance"); - expect(workflows).toContain("new discoveries never expand it"); - }); + await expect(command.execute(invocation("details"))).rejects.toBe(failure); - test("defines exactly the selected inventory's 29 command stems plus diagnostics", async () => { - const inventory = await Bun.file("docs/claude-code-integration-inventory.json").json(); - const selected = inventory.marketplace_main.files - .filter((file: { path: string }) => file.path.startsWith("plugins/beads/skills/beads/commands/")) - .map((file: { selected_mapping: { target: string } }) => file.selected_mapping.target) - .sort(); - expect( - Object.keys(WORKFLOWS) - .map((stem) => `oc-beads:${stem}`) - .sort(), - ).toEqual(selected); - const commands = createBeadsCommands( - { prompt: mock(async () => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>) }, - async () => "DIAGNOSTICS", - ); - expect(commands).toHaveLength(30); - expect(new Set(commands.map((command) => command.name)).size).toBe(30); - expect(commands.some((command) => command.name === "oc-beads:status")).toBe(false); - expect(commands.map((command) => command.name).sort()).toEqual([...selected, "oc-beads:diagnostics"].sort()); + expect(diagnostics).toHaveBeenCalledTimes(1); + expect(prompt).not.toHaveBeenCalled(); }); - test("forwards literal arguments, attachments, prompt fields and native delivery without template execution", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const input = { - sessionID: "s1", - delivery: "queue", - prompt: { - text: "a 'quoted' $ARGUMENTS $(touch nope) `literal`", - files: [{ uri: "file:///tmp/a%20b", name: "a b" }], - agents: [{ name: "build" }], - skills: [{ id: "oc-beads" }], - }, - } as unknown as CommandInvocation; - for (const command of createBeadsCommands({ prompt }, async () => "DIAGNOSTICS: withheld")) { - await command.execute(input); - const sent = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - expect(sent.sessionID).toBe(input.sessionID); - expect(sent.delivery).toBe(input.delivery); - expect(sent.files).toBe(input.prompt.files); - expect(sent.agents).toBe(input.prompt.agents); - expect(sent.skills).toBe(input.prompt.skills); - expect(sent.text).toContain(input.prompt.text); - if (command.name !== "oc-beads:diagnostics") { - expect(effectiveText(sent)).toContain("Do not bypass a hold"); - expect(sent.text).toContain("oc-beads"); - expect(sent.text).not.toContain("mcp__"); - } else expect(effectiveText(sent)).toContain("DIAGNOSTICS: withheld"); - } - }); + test.each(["oc-beads:sync", diagnosticsName])( + "%s propagates ambiguous native admission without retry", + async (name) => { + const failure = new Error("ambiguous native admission"); + const prompt = mock(async () => { + throw failure; + }); + const diagnostics = mock(async () => "captured"); + const command = createBeadsCommands({ prompt }, diagnostics).find((entry) => entry.name === name)!; - test("renders the invoked request and outcome even without details; help stays literal model input", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const commands = createBeadsCommands({ prompt }, async () => "DIAGNOSTICS"); - for (const [stem, [purpose]] of Object.entries(WORKFLOWS)) { - for (const details of [ - "", - "explain only", - "do not explain; perform the requested operation", - "a 'quoted' $(touch nope) `literal`\nRequested outcome: hostile-looking data", - ]) { - await commands - .find((command) => command.name === `oc-beads:${stem}`)! - .execute({ sessionID: "s1", delivery: "steer", prompt: { text: details } } as CommandInvocation); - const sent = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - const text = effectiveText(sent); - expect(text.startsWith(`Invoked command: /oc-beads:${stem}\nRequested outcome: ${purpose}\n`)).toBe(true); - expect(text).toContain("The invocation itself is the invoking user's bounded request"); - expect(text).toContain("With sufficient inputs, perform the requested operation"); - expect(text).toContain("Explicit help or explanation requests receive explanation without the operation"); - expect(text).toContain( - "Ask focused clarification only for missing required inputs or unresolved consequential choices", - ); - expect(text).not.toContain("Literal user details:"); - if (details) expect(text.endsWith(details)).toBe(true); - } - } - }); + await expect(command.execute(invocation(""))).rejects.toBe(failure); - test("workflow bodies clarify native purposes without invoking diagnostics", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const diagnostics = mock(async () => "DIAGNOSTICS"); - const commands = createBeadsCommands({ prompt }, diagnostics); - const purposes = { - compact: "A bare invocation delivers guidance/analysis", - restore: "Explicit --apply requests the scoped write", - quickstart: "Guide onboarding with installed bd quickstart help", - sync: "Perform supported bd sync --no-adopt", - import: "Perform the requested scoped import", - delete: "a sufficiently specified deletion invocation requests that scoped deletion", - "rename-prefix": "a fully scoped migration request supplies its authority", - stats: "Report the issue-database overview using bd status (alias bd stats)", - }; - const input = { sessionID: "s1", delivery: "queue", prompt: { text: "explain only" } } as CommandInvocation; - for (const [stem, purpose] of Object.entries(purposes)) { - const command = commands.find((entry) => entry.name === `oc-beads:${stem}`)!; - expect(command.description).toContain(purpose); - await command.execute(input); - expect(effectiveText(prompt.mock.calls.at(-1)![0] as Record<string, unknown>)).toContain(purpose); - } - for (const stem of ["init", "prime", "version", "decision", "template", "workflow"]) { - await commands.find((entry) => entry.name === `oc-beads:${stem}`)!.execute(input); - expect(effectiveText(prompt.mock.calls.at(-1)![0] as Record<string, unknown>)).toContain( - "Workflow commands guide permitted operations, not exact CLI aliases.", - ); - } - expect(diagnostics).not.toHaveBeenCalled(); - }); + expect(prompt).toHaveBeenCalledTimes(1); + expect(diagnostics).toHaveBeenCalledTimes(name === diagnosticsName ? 1 : 0); + }, + ); +}); + +describe("expandBeadsWorkflowContext replay", () => { + const current = { version: 1, instructions: "Current workflow instructions" }; + const legacy = { version: 1, instructions: "Legacy sync instructions" }; + const malformed = { version: 1, instructions: 42 }; + const oldReport = "Saved report\n\n`/old/.beads`"; + const sync = "/oc-beads:sync"; + + test.each([ + ["current", { ocBeadsWorkflow: current }, current.instructions, sync], + ["legacy", { ocBeadsSync: legacy }, legacy.instructions, sync], + ["both valid", { ocBeadsWorkflow: current, ocBeadsSync: legacy }, current.instructions, sync], + ["invalid current", { ocBeadsWorkflow: malformed, ocBeadsSync: legacy }, legacy.instructions, sync], + ["invalid legacy", { ocBeadsWorkflow: current, ocBeadsSync: malformed }, current.instructions, sync], + [ + "old diagnostics", + { ocBeadsWorkflow: { version: 1, instructions: oldReport } }, + oldReport, + "/oc-beads:diagnostics", + ], + ] as const)( + "replays %s snapshots by native ID exactly once and preserves stored history", + (_case, metadata, instructions, text) => { + const stored = storedUserMessage("retained-id", text, { ...metadata, foreign: { keep: true } }); + const unrelated = storedUserMessage("other-id", stored.text, { + ocBeadsWorkflow: { version: 1, instructions: "Unrelated snapshot" }, + }); + const history = [unrelated, stored]; + const before = JSON.stringify(history); + const projected = [Message.text(`${text} (prompt hook edit)`), Message.text("prepared skill/file content")]; + const request = Message.make({ id: stored.id, role: "user", content: projected }); + const originalRequest = JSON.stringify(request); + const messages = [request]; + const expected = [{ id: stored.id, role: "user" as const, content: [Message.text(instructions), ...projected] }]; + + expect(expandBeadsWorkflowContext(messages, history)).toBeFalse(); + expect(messages).toEqual(expected); + expect(JSON.stringify(request)).toBe(originalRequest); + expect(expandBeadsWorkflowContext(messages, history)).toBeFalse(); + expect(messages).toEqual(expected); + const replay = [Message.make(request)]; + expect(expandBeadsWorkflowContext(replay, history)).toBeFalse(); + expect(replay).toEqual(expected); + expect(JSON.stringify(history)).toBe(before); + }, + ); + + test.each([ + ["missing snapshot", undefined], + ["unsupported version", { ocBeadsSync: { version: 2, instructions: "future" } }], + ["non-string instructions", { ocBeadsWorkflow: malformed }], + ["invalid snapshots", { ocBeadsWorkflow: null, ocBeadsSync: "invalid", foreign: true }], + ] as const)("flags a visible command with %s while leaving both message copies intact", (_case, metadata) => { + const stored = storedUserMessage("unavailable", "/oc-beads:sync", metadata); + const before = JSON.stringify(stored); + const request = Message.make({ id: stored.id, role: "user", content: stored.text }); + const messages = [request]; + const originalRequest = JSON.stringify(request); + + expect(expandBeadsWorkflowContext(messages, [stored])).toBeTrue(); + expect(JSON.stringify(messages[0])).toBe(originalRequest); + expect(JSON.stringify(stored)).toBe(before); + }); + + test("leaves ordinary user messages and assistant messages alone", () => { + const stored = storedUserMessage("retained-id", "/oc-beads:sync", { ocBeadsSync: legacy }); + const ordinary = Message.make({ id: "ordinary", role: "user", content: "plain user input" }); + const assistant = Message.make({ id: stored.id, role: "assistant", content: stored.text }); + const messages = [ordinary, assistant]; - test("uses approved primary resources and retains bounded sync authority", () => { - for (const stem of ["sync", "audit", "show", "import", "init", "quickstart"] as const) - expect(WORKFLOWS[stem][1]).toBe("CLI_REFERENCE"); - expect(WORKFLOWS.epic[1]).toBe("DEPENDENCIES"); - expect(WORKFLOWS.sync[0]).toContain("existing project configuration"); - expect(WORKFLOWS.sync[0]).toContain("missing configured remote is a blocker"); - expect(WORKFLOWS.sync[0]).toContain("actual executor actor"); - expect(WORKFLOWS.sync[0]).toContain("applicable sandbox policy"); - expect(WORKFLOWS.sync[0]).toContain("no --yes, adoption, provisioning"); - expect(WORKFLOWS.template[0]).toContain("actual available templates/formulas"); + expect(expandBeadsWorkflowContext(messages, [stored])).toBeFalse(); + expect(messages).toEqual([ordinary, assistant]); }); +}); - test("TROUBLESHOOTING.md gives compact analyze/apply, separate mode authority and explicit actor guidance", () => { - expect(readResource("TROUBLESHOOTING")).toMatch( - /Prefer the agent-driven analyze\/apply path[\s\S]*--auto[\s\S]*external AI provider[\s\S]*--dolt[\s\S]*storage garbage collection[\s\S]*each require separate explicit authority[\s\S]*ordinary compact approval selects neither[\s\S]*explicit `--actor`[\s\S]*default of `agent`/, +describe("loadBeadsSkill installed guidance", () => { + test("loads the package-owned identity and every selected explicit resource link", async () => { + const mappedLinks = inventory.marketplace_main.files.flatMap(({ category, selected_mapping }) => + (category === "resource" || category === "adr") && selected_mapping?.task_ids.includes("2.1") + ? [selected_mapping.target.replace(/^assets\/oc-beads\//, "")] + : [], ); - }); - test("loads the rich skill at its installed path with all 17 explicit links, beyond a sampled ten", async () => { const skill = await loadBeadsSkill(); + expect(String(skill.id)).toBe("oc-beads"); expect(String(skill.name)).toBe("oc-beads"); - expect(String(skill.path)).toBe(fileURLToPath(new URL("../assets/oc-beads/SKILL.md", import.meta.url))); - expect(skill.content).toContain("### Advanced"); - const links = [...skill.content.matchAll(/\]\(((?:resources|adr)\/[^)]+)\)/g)].map((match) => match[1]!); - expect(new Set(links).size).toBe(17); - for (const link of links) expect(await readFile(new URL(link, `file://${skill.path}`), "utf8")).not.toBeEmpty(); - }); - - test("reports missing or unreachable packaged guidance rather than silently advertising it", async () => { - const realRead = (file: string) => readFile(file, "utf8"); - for (const code of ["ENOENT", "EACCES"]) { - await expect( - loadBeadsSkill({ - readText: async (file) => { - if (file.endsWith("WORKTREES.md")) throw Object.assign(new Error("sensitive detail"), { code }); - return realRead(file); - }, - }), - ).rejects.toThrow("resource-unreachable resources/WORKTREES.md"); + expect(String(skill.path)).toBe(join(assetRoot, "SKILL.md")); + const links = new Set([...skill.content.matchAll(/\]\(((?:resources|adr)\/[^)]+)\)/g)].map((match) => match[1])); + expect(new Set(mappedLinks).size).toBe(16); + expect([...mappedLinks, "resources/CODE_MODE.md"].filter((link) => !links.has(link))).toEqual([]); + }); + + test("loads and reloads real files beneath a deep hidden package path with spaces", async () => { + const root = await mkdtemp(join(tmpdir(), "oc-beads-path-")); + const installed = join(root, ".hidden/node_modules/package with spaces/a/b/c/d/e/f/g/oc-beads"); + const skillPath = join(installed, "SKILL.md"); + try { + await cp(assetRoot, installed, { recursive: true }); + const first = await loadBeadsSkill({ skillPath }); + expect(String(first.path)).toBe(skillPath); + + const edit = "Reloaded package fixture."; + await writeFile(skillPath, `${(await readFile(skillPath, "utf8")).trimEnd()}\n\n${edit}\n`); + const reloaded = await loadBeadsSkill({ skillPath }); + expect(String(reloaded.path)).toBe(skillPath); + expect(reloaded.content).toBe(`${first.content}\n\n${edit}`); + + const resource = join(installed, "resources/WORKTREES.md"); + await writeFile(resource, " \n"); + await expect(loadBeadsSkill({ skillPath })).rejects.toThrow("resource-unreachable resources/WORKTREES.md"); + await rm(resource); + await expect(loadBeadsSkill({ skillPath })).rejects.toThrow("resource-unreachable resources/WORKTREES.md"); + } finally { + await rm(root, { recursive: true, force: true }); } }); - test("stable 2.x package manifest includes the owned assets", async () => { - const manifest = await Bun.file("package.json").json(); - expect(manifest.files).toContain("assets/oc-beads"); - expect(manifest.version).toMatch(/^2\.\d+\.\d+$/); - }); -}); - -test("explicit installed skill base survives ignored/hidden roots beyond the host scan depth and reload", async () => { - const root = await mkdtemp(resolve(tmpdir(), "oc-beads-path-")); - const installed = resolve(root, ".hidden/node_modules/a/b/c/d/e/f/g/oc-beads"); - try { - await mkdir(installed, { recursive: true }); - await cp(assetRoot, installed, { recursive: true }); - const path = resolve(installed, "SKILL.md"); - const first = await loadBeadsSkill({ skillPath: path }); - expect(String(first.path)).toBe(path); - expect(first.content).toContain("resources/WORKTREES.md"); - await writeFile(path, `${await readFile(path, "utf8")}\nReloaded package fixture.\n`); - const reloaded = await loadBeadsSkill({ skillPath: path }); - expect(reloaded.content).toContain("Reloaded package fixture."); - // Explicit registration supplies SKILL.md; it never asks a recursive scanner or - // resource watcher to discover the other 17 files. Reads still use host permissions. - expect(reloaded.content.match(/\]\((?:resources|adr)\//g)).toHaveLength(17); - } finally { - await rm(root, { recursive: true, force: true }); - } -}); - -test("static diagnostics help skips its callback and preserves literal input and v1 replay", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const diagnostics = mock(async () => { - throw new Error("help must not collect"); - }); - const command = createBeadsCommands({ prompt }, diagnostics).find((c) => c.name === "oc-beads:diagnostics")!; - for (const text of ["help", " HeLp ", "help\n"]) { - const input = { - sessionID: "help-session", - delivery: "queue", - prompt: { text, files: [{ uri: "file:///fixture.txt" }] }, - } as unknown as CommandInvocation; - await command.execute(input); - const sent = prompt.mock.calls.at(-1)![0] as Record<string, unknown>; - const snapshot = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }).ocBeadsWorkflow; - expect(snapshot.version).toBe(1); - expect(snapshot.instructions).toContain("Beads diagnostics help"); - expect(snapshot.instructions).toStartWith("Reproduce only the finished Markdown"); - expect(snapshot.instructions).toContain("\nBEGIN_DIAGNOSTIC_REPORT\n## Beads diagnostics help"); - expect(snapshot.instructions).toEndWith("\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n"); - expect(snapshot.instructions).toContain( - "https://github.com/snarkipus/opencode-beads/blob/main/docs/diagnostics.md", - ); - expect(sent.files).toBe(input.prompt.files); - expect(sent.delivery).toBe(input.delivery); - expect(sent.text).toBe(`/oc-beads:diagnostics${text.includes("\n") ? "\n" : " "}${text}`); - const persisted = storedUserMessage("help-id", String(sent.text), sent.metadata as StoredUserMessage["metadata"]); - const messages = [Message.make({ id: persisted.id, role: "user", content: String(sent.text) })]; - expandBeadsWorkflowContext(messages, [persisted]); - expect(messages[0]!.content[0]).toEqual(Message.text(snapshot.instructions)); - const once = JSON.stringify(messages); - expandBeadsWorkflowContext(messages, [persisted]); - expect(JSON.stringify(messages)).toBe(once); - } - expect(diagnostics).not.toHaveBeenCalled(); -}); - -test("diagnostics captures only a finished delimited report before the unchanged invocation", async () => { - const prompt = mock(async (_input: unknown) => ({}) as Awaited<ReturnType<Plugin.Context["session"]["prompt"]>>); - const report = - "## Beads diagnostics — ✅ Healthy\n\nDATE: `1970-01-01T00:00:02.000Z`\n\nVERSION: fixture `2.2.1`\n\nPATH: `/observed/root`\n\n| Check | Status | Value |\n|---|---|---|\n| Workspace | ✅ | Located |"; - const diagnostics = mock(async () => report); - const command = createBeadsCommands({ prompt }, diagnostics).find( - (command) => command.name === "oc-beads:diagnostics", - )!; - const input = { - sessionID: "framed", - delivery: "queue", - prompt: { text: "exact literal\nsecond line", files: [{ uri: "file:///fixture.txt" }] }, - } as unknown as CommandInvocation; - await command.execute(input); - const sent = prompt.mock.calls[0]![0] as Record<string, unknown>; - const snapshot = (sent.metadata as { ocBeadsWorkflow: { version: number; instructions: string } }).ocBeadsWorkflow; - expect(snapshot).toEqual({ - version: 1, - instructions: `Reproduce only the finished Markdown between BEGIN_DIAGNOSTIC_REPORT and END_DIAGNOSTIC_REPORT. Preserve values, labels, order and Markdown exactly. Do not include the markers or original invocation, infer or reconstruct values, or add diagnoses or commentary.\n\nBEGIN_DIAGNOSTIC_REPORT\n${report}\nEND_DIAGNOSTIC_REPORT\n\nOriginal invocation:\n`, - }); - expect(sent.text).toBe("/oc-beads:diagnostics\nexact literal\nsecond line"); - expect(snapshot.instructions).not.toContain("exact literal"); - expect(sent.files).toBe(input.prompt.files); - expect(sent.delivery).toBe(input.delivery); - expect(diagnostics).toHaveBeenCalledTimes(1); - const oldInstructions = "Original saved report\n\n`/old/.beads`"; - const old = storedUserMessage("old", "/oc-beads:diagnostics", { - ocBeadsWorkflow: { version: 1, instructions: oldInstructions }, + test("reports a denied resource read by its relative path", async () => { + const denial = Object.assign(new Error("private filesystem detail"), { code: "EACCES" }); + await expect( + loadBeadsSkill({ + readText: async (file) => { + if (file === join(assetRoot, "resources/WORKTREES.md")) throw denial; + return readFile(file, "utf8"); + }, + }), + ).rejects.toThrow(/^resource-unreachable resources\/WORKTREES\.md$/); }); - const messages = [Message.make({ id: old.id, role: "user", content: old.text })]; - expandBeadsWorkflowContext(messages, [old]); - expect(messages[0]!.content[0]).toEqual(Message.text(oldInstructions)); - expect(JSON.stringify(messages)).not.toContain("BEGIN_DIAGNOSTIC_REPORT"); - const once = JSON.stringify(messages); - expandBeadsWorkflowContext(messages, [old]); - expect(JSON.stringify(messages)).toBe(once); });