diff --git a/.agents/package.json b/.agents/package.json index f08b8795b2..462beee825 100644 --- a/.agents/package.json +++ b/.agents/package.json @@ -5,6 +5,6 @@ "type": "module", "scripts": { "typecheck": "bun x tsc --noEmit -p tsconfig.json", - "test": "bun test __tests__" + "test": "bun --no-env-file --no-install ../scripts/run-workspace-tests.ts .agents unit" } } diff --git a/.agents/sessions/agent-tool-reliability-remediation/PLAN.md b/.agents/sessions/agent-tool-reliability-remediation/PLAN.md new file mode 100644 index 0000000000..fbd292f533 --- /dev/null +++ b/.agents/sessions/agent-tool-reliability-remediation/PLAN.md @@ -0,0 +1,419 @@ +# Openbuff agent and tool reliability — remediation plan + +**State:** Local implementation and acceptance complete. **Audit basis:** `6d5364de3`. + +**Verified progress:** Bundled SDK fixtures exercise real scoped editor/test/doc handoffs, verified no-ops, resumed writer groups, receipt-backed diagnostic repairs, blocked nonconvergent hooks, and exact native reviewer reads. The bundled Execute Plan fixture persists a claim, rejects foreign scope and an unissued checkpoint, completes against confirmed validation/review, and claims the next task on a fresh run without replaying edits. Read-only advisory review attests a joined commit comparison; unsupported scopes report an evidence gap instead of substituting a baseline. Runtime aliases, explicit MCP grants, supervision and detached settlement now have offline boundary controls. + +**Current status:** All roadmap tasks have local evidence for their supported lanes. Final Linux verification includes a clean lock-backed SDK install on pinned Node, exact SDK and CLI archives, joined compaction/restart and concurrent cancellation controls, and complete workspace unit/integration schedules. Unsupported host/producer/platform cells remain explicit refusals or unverified; no hosted CI or publication occurred. + +**Prior workspace verification (Bun 1.4.4, Linux; before the continuation above):** + +- Workspace `bun --no-env-file --no-install run test` schedules: `agents` 1,487 passed; `packages/agent-runtime` 3,393 passed; `sdk` 7,162 passed/1 skipped; `cli` 5,043 passed/277 skipped; `evals` 423 passed; `scripts` 475 passed/1 skipped. No failures in those schedules. Live Deep was intentionally excluded. Workspace typechecks passed for `common`, `agents`, `packages/agent-runtime`, `sdk`, `cli`, `evals`, and `scripts`. +- Source proofs with T (below): `sdk/src/__tests__/shipped-base2-contract.test.ts` 11 passed after regenerating agents with `bun --no-env-file --no-install run ./cli/scripts/prebuild-agents.ts` (bundle sha256 `871f9e1c74815891bd9888599c3f12ccd637f95f0e0896927449bbe99d122e6b`); plan scope/recovery group 188 passed; reviewed/auxiliary/error recovery group 93 passed; scoped audit/librarian/worktree group 207 passed; targeted-validation/audit group 299 passed/1 platform skip; MCP group 86 passed. Selections overlap and are not a combined test count. +- Native browser fixture: set `P57_PARENT_NETNS` to the invoking namespace, `P57_CHROME_PATH=/usr/bin/chromium`, then use `unshare --user --map-current-user --net --keep-caps` with only `lo` up to run `bun --no-env-file --no-install run ./test/fixtures/body/browser-smoke.ts`. Four owned Chromium steps, screenshot hash, capture/log windows, and cleanup passed. The same executable in the unisolated namespace correctly exited `2` (unavailable). The four offline browser policy suites passed 81 cases. +- Exact Linux x64 SDK candidate: `(cd sdk && unshare -Urn -- bun --no-env-file --no-install run scripts/verify.ts)` rebuilt, checked types, packed offline, matched 44 archive members and extracted CJS/ESM/15-language/ripgrep controls, and verified copied loopback routes/missing child/configured hook selection. Archive sha256 `ca9f4d94007daf8e9edcf339015743255a6378fd2ddb80a31683b1e8b2bfee69`. Node 26.1.0 differed from the release pin; the consumer used existing workspace dependencies rather than a clean lock-backed install. No packed CLI, hosted CI, or release verification credit. +- Egress-isolated full SDK unit and SDK/CLI integration schedules passed (SDK integration 25/25; CLI integration 11/11). The successful `bwrap` runner created owned `/` and private mode-0700 `/tmp`, cleared ambient config, kept only loopback networking, and read-only mounted the installed Blender ROCm/SYCL libraries for the SDK unit lane. Earlier user-namespace-only attempts correctly refused unmapped or shared-writable ancestry. Native producers' fixtures now use a host-backed project view for targeted validation, configure an actual check for post-validation snapshot probes, and explicitly bind MCP routes before checking cancellation; the 276 targeted-validation branch cases and 139 MCP wire cases passed before the full SDK rerun. + +No live application provider or hosted release was run. Native enforcement credit is confined to the recorded Linux controls (selected native terminal fixture and separately owned playback/browser lanes). The prior bounded 200-row recall probe measured a 4.2–4.7 ms indexed median over 24 repetitions per fixture; no cache was added. + +This is the execution checklist for the entire [agent/tool audit](../audit-agent-tool-coverage-2026-11/AUDIT-REPORT.md), not only its top ten. The [coverage index](#finding-to-task-coverage) maps all 70 findings from the eight shards, including duplicates, and six additional gaps noted in those shards. Every planned change, prerequisite, verification requirement, and scope decision is in this file. The linked reports preserve the original evidence and line numbers. + +## Target behavior + +- A shipped orchestrator can discover and retain context, delegate a scoped change, review the exact retained bytes, run the checks the user required, and checkpoint or report the actual result. +- **Authority, execution, evidence and acceptance are different.** A tool name or a selected agent is not permission; a launched job is not a finished test; a completed agent run is not task acceptance; a waiver is not a pass; a successful write is not necessarily durable or independently reviewed. +- Keep the existing role split: read-only reviewers, separate writer/runner, host-owned approvals and process custody, no model-driven canonical memory promotion. Fix the contracts before adding agents. Do not widen PLAN, silently attach optional tools, enable untrusted inferred hooks, auto-install dependencies, or require a live provider to prove correctness. + +## Execution and rollout rules + +1. **Bootstrap:** The audited runtime cannot use its own `EXECUTE_PLAN` checkpoint tools reliably. Start P0/P1 with an operator-tracked task and normal reviewed PRs. Until P2.7 passes on an upgraded runtime, use this checklist for planning and keep externally verified PR/evidence links with the review; don't forge checkpoint receipts, use generic Markdown edits as proof of a validated task, or activate a session pointer just to start this work. After P2.7, exercise `/resume-plan` first against an owned fixture, then reconcile previously reviewed tasks by verified evidence, not by retroactively synthesizing run receipts. +2. **Small merges, test first:** reproduce at the nearest real boundary; add a negative and positive control. For additive protocol changes land readers/legacy projections before relying on new producer fields. Missing/legacy evidence is `unknown` unless there is a proven, versioned translation. Do not defer a false-pass assertion to the packed test. Security fixes may intentionally refuse a previously allowed unsafe action; document migration and test that rollback cannot re-enable a known misrepresentation or broaden authority. +3. **Ordering:** Do P0 and the P1 false-green/permission fixes first. After P1, use the task DAG; unrelated branches can proceed separately. Serialize changes to the serialized Base2 generator, shared evidence schemas, and generated ABI/type/bundle outputs. Bind evidence producers/consumers in the same PR or use an additive bridge with explicit missing state. Do not run concurrent writers on overlapping scopes. +4. **Test shorthand:** `T` means `bun --no-env-file --no-install test --isolate` from the repo root, with explicit `./` path arguments. Run focused tests including the new cases listed for the task, affected package typechecks from their own directories, then the appropriate CI schedule. For CLI suites use the documented native preload/isolation and `cd cli && bun run test`, not bare `bun test`. Use private temp repos, local loopback/scripted inference and owned process fixtures; fail if a case unexpectedly requests an external provider or an unowned effect. +5. **Evidence:** A task is done only when its acceptance conditions and negative controls pass and the exact command, artifact/build identity, scope, executed/skipped counts, and receipt/postimage evidence are recorded by the implementing PR. Missing toolchains/permissions/platform cells are unavailable or blocked, never passed. Treat new public behavior, trusted tool execution, dependency changes, and release/publish as separate operator decisions; this plan is not authorization to perform them. + +## P0 — Baseline and reproducible contracts + +- [x] P0.1 Seed a hermetic shipped-root contract harness and pin the known failures. + - Touch: `agents/e2e/`, `sdk/src/__tests__/`, `test/fixtures/body/`, `.github/workflows/ci.yml`. Record the audit baseline/effective matrix and use real bundled definitions rather than always-accepting schemas. Build an offline scripted-provider fixture with a temp Git worktree, controlled hook/mutation/review receipts, exact negative oracles and a no-external-network barrier. Bring the existing fast deterministic gate subset into PR CI; add corrected assertions with each fix, not permanent expected-failure tests. + - Acceptance: The baseline independently reproduces writer refusal, skip reported as pass, repeat-finding convergence, missing Execute Plan tools, and the PLAN-selection discrepancy; fixture failures expose the precise contract under test, and neither the setup nor a test starts a live provider request. + - Validate: T `./agents/e2e/gate-lifecycle.e2e.test.ts` `./agents/e2e/gate-aux-ordering.e2e.test.ts` `./agents/e2e/editor-orchestrator-contract.e2e.test.ts`; run the new baseline controls. + +## P1 — Stop false success and restore safe delegation + +- [x] P1.1 Carry typed terminal and hook evidence end to end. + - Depends on: P0.1 + - Touch: `agents/basher.ts`, `sdk/src/tools/{run-terminal-command,file-change-hooks}.ts`, common tool schemas and terminal result observers. Introduce a positive executed-result branch separate from refused, failed-to-start, cancelled, timed out, background started, cleanup uncertain, missing and legacy-unclassified. Keep the terminal receipt, bounded output and verified retained log in both raw and summarized Basher output; remove preannounced log paths and broad temp cleanup. Use private host-owned logging; preserve suite exit and log-write failure separately. Correct the stale Basher timeout promise; explicit or host-captured deadlines must apply without inventing a default. + - Acceptance: A denied, malformed, cancelled, overflowing, log-failed or timed-out command can never turn into a success-like Basher response; background start, confirmed exit, cleanup and verified full-log custody are distinct. A genuine nonzero exit stays a failure even when stderr contains words such as `timeout` or `not found`. + - Validate: T `./agents/__tests__/basher.test.ts` `./sdk/src/__tests__/file-change-hooks.test.ts` `./sdk/src/__tests__/run-host-execution.test.ts`; add result-wire and logging faults with a successful-exit control. + +- [x] P1.2 Separate finalization, validation, review, waiver and delivery outcomes. + - Depends on: P1.1 + - Touch: `agents/base2/base2.ts`, `common/src/types/run-outcome.ts`, plan evidence consumers, SDK/NDJSON/TUI renderers, `cli/src/commands/run-command.ts`. Replace text/absence heuristics with discriminated stage outcomes and independent gate permission. Preserve exact source/actor/basis references and advisory receipt scopes. Only grant an explicit content-bound waiver through the authorized operator path; no synthetic `LOOKS_GOOD`, `reviewed-diff`, or normal specialist credit for a waiver. Preserve legacy run-completion exit behavior, but add explicit opt-in requiring accepted work and configured evidence for automation. + - Acceptance: No config, no match, denied hook, unparseable assertion failure, waiver and stale/missing evidence each render and serialize distinctly; only confirmed check kinds get credit. An old or bypassed receipt cannot count as confirmed acceptance; headless opt-in fails on an unmet gate while advisory callers retain a completed-run result. + - Validate: T `./agents/e2e/gate-lifecycle.e2e.test.ts` `./agents/e2e/gate-aux-ordering.e2e.test.ts`; add CLI/SDK schema and exit-code cases plus no-hook, refused, waived and genuine-pass controls. + +- [x] P1.3 Bind PLAN authority at host admission and display the admitted mode. + - Depends on: P0.1 + - Touch: `cli/src/hooks/use-send-message.ts`, `cli/src/utils/create-run-config.ts`, CLI mode/attach handling, `sdk/src/run.ts`, `sdk/src/serve/bridge.ts`, `sdk/src/client/acp-client.ts`, runtime plan guards. Make selected PLAN a trusted admission decision independent of model parameters, UI state, saved JSON or winning agent ID. Reject incompatible explicit or reserved-ID roots or wrap them with a monotonic ceiling. In ACP, use a negotiated effective authority, or show server-owned/unavailable and disable local mode claims. Preserve the existing artifact-only exception and native-only read-only process enforcement. + - Acceptance: Stock, override, `--agent`, slash-mode, resumed, nested and attached runs never display PLAN while admitting a write authority; conflicting/old peers clearly refuse or disclose their real mode. Verify zero denied-effect dispatch and pair with approved execute versus read-only controls. + - Validate: T `./sdk/src/__tests__/plan-terminal-enforcement.test.ts` `./packages/agent-runtime/src/__tests__/plan-mode-dispatch.test.ts` `./cli/src/__tests__/cli-args.test.ts`; add real local/ACP admission cases for same-ID Markdown and explicit conflicting root. + +- [x] P1.4 Restrict executable agent discovery and show only the admitted mention catalog. + - Depends on: P1.3 + - Touch: `sdk/src/agents/load-agents.ts`, `cli/src/utils/local-agent-registry.ts`, TUI mention and chat surfaces. Never import session, evidence, scratch, generated or fixture modules as definitions. Limit discovery to documented entrypoints or an explicit manifest; retain a migration path for valid trusted nested definitions and top-level Markdown. Derive enabled `@` entries from the effective root/registry/mode permissions; label a rejected or unavailable child instead of promising a mandatory spawn. + - Acceptance: An inert fixture with a sentinel side effect outside agent entrypoints is not imported; trusted legacy agents load only through the documented compatibility path; no untrusted discovery. Under PLAN/custom/attached roots the catalog agrees with actual admission, and excludes internal tools and other-mode writers. + - Validate: T `./sdk/src/__tests__/load-markdown-agents.test.ts` `./sdk/src/__tests__/project-trust-gate.test.ts`; extend registry/selector tests and test runtime admission for offered targets. + +- [x] P1.5 Enforce explicit scoped-writer authority and ownership. + - Depends on: P1.3 + - Touch: `common/src/types/agent-template.ts`, runtime `spawn-agent-utils.ts`, `tool-executor.ts`, edit transaction and workspace path leases. Add host-backed monotonic read/write and child/tool ceilings for opt-in scoped roles, including explicit deny-all. For test/doc/repair use hard **write** scopes and only the project reads their role genuinely needs; treat legacy advisory globs as such in types/policy/UI. Normalize and check both ends of move/delete and fail closed on out-of-scope or uncertain canonical paths before effects. Tie owned leases and receipts to actual paths instead of treating overlapping voluntary declarations as isolation. + - Acceptance: Manual, inline and nested test/doc/repair launches with missing/empty/disjoint scopes cannot mutate unintended production paths or move across scope; valid new tests and doc paths still work, findings repair requires an actionable nonempty path set, and unrelated legacy advisory callers do not silently gain or lose authority. + - Validate: T `./packages/agent-runtime/src/__tests__/spawn-agents-permissions.test.ts` `./sdk/src/__tests__/run-mutation-dispatch.test.ts`; add real broker/dispatch cases for no authority, scope union, lease overlap and two-ended moves. + - Verified: `sdk/src/__tests__/shipped-writer-ceiling.test.ts`, `packages/agent-runtime/src/util/__tests__/workspace-path-leases.test.ts`, and `common/src/util/__tests__/strict-project-read-policy.test.ts` exercise native SDK dispatch, outside/sensitive reads, exact scope inheritance, both move ends, exclusive leases, and unchanged legacy behavior. The writer read boundary is workspace confinement, not the separate descriptor-only read mode or an OS sandbox. + +- [x] P1.6 Repair and prove all three default writer handoffs. + - Depends on: P1.2, P1.5 + - Touch: `agents/base2/base2.ts`, `agents/{test-writer,doc-writer}/`, `agents/base2/spawn-contract.ts`, `agents/guides/editor-writers-and-repair.md`. Derive automatic test, coverage-only repair and doc writer tools from one canonical contract using `edit_transaction`, not standalone `write_file`/`str_replace`. Resolve legitimate package test paths (including scoped creation); keep explicit requested deliverables pending on failure. Do not mark unattempted groups done. Route source comments to editor, not the docs writer. + - Acceptance: All three handoffs admit the real bundled child and produce an authorized file change or a reasoned verified no-op; illegal mutation is refused; decline/crash/invalid receipt leaves that deliverable open without infinite retry. Docs/tests are not alleged to have passed by merely creating a file. + - Validate: T `./agents/__tests__/base2-writer-spawn-rules.test.ts` `./agents/e2e/gate-aux-ordering.e2e.test.ts` `./agents/tool-reachability.test.ts`; add real child dispatch, new test creation, docs write and failure controls to P0.1's harness. + - Verified: `sdk/src/__tests__/shipped-base2-contract.test.ts` proves all three joined dispatches, scoped edits, a real read-backed doc no-op, an identical unread claim, and a retained partial write without gate clearance. The writer-spawn suite JSON-round-trips completed A, partial B, and unattempted C; only B/C are retried when A's proof is fresh. A same-length change to A's artifact reopens A. Exact reads verify the no-op evidence's byte basis, not semantic correctness or execution of a selected test case (P5.2). + +## P2 — Bind review and plan checkpoints to actual changes + +- [x] P2.1 Capture gate identity from the run workspace and typed byte observations. + - Depends on: P1.2 + - Touch: `sdk/src/run.ts`, runtime programmatic control plane, `agents/base2/{base2,gate-fingerprint,gate-reviewer,gate-concurrency}.ts`. Replace ambient `cwd` markers with host-captured workspace/adapter identity and no-follow file observations. Bind receipt/reuse to workspace, scope, full content, comparison basis, requirements and reviewer family. Treat unreadable/unknown as non-attestable; only a trusted change basis can assert a deletion. Preserve old receipts for history without unearned new credit. + - Acceptance: Two roots with identical relative paths, present-but-unreadable files, genuine deletion, same-length rewrite, changes of requirement/baseline and unsupported adapters produce correct, distinct outcomes. A spoofed or stale token/file list alone cannot mint credit. + - Validate: T `./agents/__tests__/gate-reviewer.test.ts` `./agents/e2e/reviewer-spawn-conditions.e2e.test.ts` `./sdk/src/__tests__/get-change-review-bundle.test.ts`; new two-root real SDK and postimage probes. + - Verified: real SDK roots with identical relative paths/bytes remain distinct; a different admitted `content` changes the request basis even with the same prompt. Injected filesystem views, unreadable entries (including dangling links), absent paths without trusted Git deletion evidence, and copied tokens cannot earn live gate credit. The bundled fixture demonstrates a valid native whole/paged read, rejects a blind reviewer and one that read different bytes before a same-length reversion, and stores a reusable primary receipt only after rechecking the frozen final scope. Static advisory/committed-surface attestation and post-hook specialist freshness remain separate tasks (P2.5/P2.4). + +- [x] P2.2 Correct mutation attribution and converge without duplicate checks. + - Depends on: P2.1 + - Touch: `agents/base2/{base2,gate-repair,gate-paths}.ts`, `agents/editor/editor.ts`, `agents/guides/editor-writers-and-repair.md`. Feed the gate from correlated confirmed applied or retained partial receipts, not paths found in attempt inputs. Keep externally observed dirt, deliberate adoption and attempted paths distinct. Bind each `VF-*` to its actual diagnosed path and justified related paths, even outside the original pending set. Use one post-repair validation path or carry exact full evidence into reuse, including its summary. Bound repeated identical no-action editor steps independently of productive progress and align read/overwrite guidance with `cap.v4` and whole raw authority. + - Acceptance: Preflight rejection/no-op doesn't invent changes; mixed partial retains only proven paths. Fixing B when hook input was A counts as progress and causes one correct recheck of the expanded scope; stale evidence never substitutes. Repeated no-action exits with a typed blocked receipt, and prompt examples work with real authorization. + - Validate: T `./agents/__tests__/editor.test.ts` `./agents/__tests__/gate-repair.test.ts` `./agents/e2e/gate-lifecycle.e2e.test.ts` `./sdk/src/__tests__/run-mutation-dispatch.test.ts`; add exact hook count and A→B fixture. + +- [x] P2.3 Keep re-raised reviewer blockers open and require independent clearance. + - Depends on: P2.1, P2.2 + - Touch: `agents/base2/{base2,gate-reviewer,gate-repair}.ts` and the `base2.test.ts` convergence fixtures. Use repair-reported IDs only for progress/deduplication. Re-raised blocking findings remain open; unchanged or repeatedly unsuccessful repairs park clearly rather than loop or downgrade. Respect hard requirement gaps, protocol retry classes, independent clean verdict and the separate content-bound waiver. + - Acceptance: A byte-changing inadequate repair with the same raised defect cannot clear review; escalation cannot be condoned; a true fix requires fresh independent verdict. Old tests that intentionally credit persistent blockers become negative regressions, and any waiver retains its own class. + - Validate: T `./agents/__tests__/base2.test.ts` `./agents/__tests__/gate-reviewer.test.ts` `./agents/e2e/gate-lifecycle.e2e.test.ts`; include persistent, resolved, cancelled and explicit-waiver traces. + +- [x] P2.4 Refresh every required risk review after hooks and cover risk-sensitive configuration. + - Depends on: P2.1, P2.3 + - Touch: `agents/base2/base2.ts`, `agents/base2/specialist-risk-router.ts`, `common/src/agents/review-impact.ts`, Git delivery guard. Compare required aux and specialist receipts against final bytes and evidence after hooks; reroute same-membership rewrites and stop cycling on a nonconvergent mutating hook. Include relevant non-source config/manifest/lock/CI and behavior-led security signals, even for explicitly adopted existing Git dirt. Use redacted evidence or an explicit review gap for sensitive files, never send raw secrets. + - Acceptance: Same-path formatter/codegen changes invalidate prior approval; unchanged file credit is reused only on the same basis. Sensitive configuration-only, generic-named risk code, manifest-only Git delivery and unavailable scanner behavior are explicit; neither zero candidates nor an empty bundle gives implied clearance. + - Validate: T `./agents/e2e/gate-aux-ordering.e2e.test.ts` `./agents/__tests__/specialist-risk-router.test.ts` `./agents/__tests__/base2-review-wave-credit.test.ts`; add post-hook observed marker and config-only delivery cases. + +- [x] P2.5 Make explicit advisory review read-only and attest the delegated result. + - Depends on: P1.2, P1.3, P2.1 + - Touch: CLI `/review` prompt and dispatch, review receipt/selector projection, SDK run output. Use a scoped review turn without mutating tools or unrelated pending-edit gates. Require an independent result or explicit evidence gap before labeling it reviewed. Attribute same-ID overrides, baseline and scope; keep dynamic checks and operator commits separate. + - Acceptance: `/review` cannot edit source or clear an unrelated pending gate; a missing/failed reviewer is not reported as reviewed; worktree/last-commit comparison cannot silently substitute for a requested baseline. Headless callers can distinguish accepted advisory review, execution completion, and blocked change review. + - Validate: Existing CLI `/review` command/prompt tests plus a new local/attached scripted-provider dispatch test for denied edit, missing child, correct baseline and joined verdict. + +- [x] P2.6 Unify serialized root policy, triage capability, and retry defaults. + - Depends on: P1.2, P2.3 + - Touch: `agents/base2/` factory/wrappers/problem guidance, `packages/agent-runtime/src/run-programmatic-step.ts`, `docs/environment-variables.md`. Serialize one mode-resolved policy consumed by prompts and runtime. FAST keeps manual scoped checks and does not invoke the default automatic repair gate; FAST-NO-VALIDATION omits even the manual-validation guidance while remaining honest about unknown results. Make Deep eligible for risk triage by capability, not ID prefix. Document exact repair/no-verdict caps, diagnostics and convergence behavior; choose finite identical/no-progress retry bounds separately from productive work. + - Acceptance: Tests run the actual loaded root and its config for default/execute/plan/FAST/FAST-NO-VALIDATION/Deep; no mode tries to spawn a withheld agent; absent budgets, explicit caps, unchanged retry and changed evidence match documented behavior. + - Validate: T `./agents/__tests__/base2-mode-policy.test.ts` `./agents/__tests__/roster-drift.test.ts` `./agents/__tests__/base2.test.ts` `./agents/e2e/reviewer-spawn-conditions.e2e.test.ts`. + +- [x] P2.7 Restore safe Execute Plan checkpointing and recoverable plan state. + - Depends on: P1.2, P1.3, P2.1, P2.3, P2.4 + - Touch: `agents/base2/tool-tiers.ts`, plan tool schemas and `packages/agent-runtime/src/tools/handlers/tool/{create-plan,update-plan-status}.ts`, `common/src/util/plan-artifacts.ts`, CLI PlanLink. Bind to the captured root and exact session scope. Use a per-session CAS/lock with recoverable publication of Markdown/STATE/timeline; if interrupted, reconcile rather than replay effects. Stage exposure: after scoped persistence works, allow claim and bookkeeping in EXECUTE_PLAN on the initial tool surface; enable `done` only once the upgraded evidence issuer and verifier both work. Recheck the live claim, criteria and bytes when committing a transition. Limit `create_plan` to revisions that cannot bypass guarded completion; keep the tools in PLAN and EXECUTE_PLAN only. Runtime bookkeeping must not invalidate a source review. Older sessions remain readable but require fresh evidence; explicit no-diff/not-applicable policy is not a reviewed diff or a waiver-as-pass. + - Acceptance: Actual `/resume-plan` can claim one task, run work, complete with its genuine receipt, advance and survive restart. Refuse stale/wrong-task/legacy/waived receipts when validation is required, foreign cwd, conflicting revisions and otherwise partial writes; recover between state/Markdown/event publication. Ordinary DEFAULT gains no additional plan authority. + - Validate: T `./common/src/util/__tests__/plan-artifacts.test.ts` `./packages/agent-runtime/src/tools/handlers/tool/__tests__/update-plan-status.test.ts` `./agents/tool-reachability.test.ts`; new real two-root, competing revision, failure injection, and restart fixtures. + +## P3 — Make the effective tool and spawn permissions observable + +- [x] P3.1 Unify provider aliases, canonical dispatch and per-child results. + - Depends on: P1.3, P1.5 + - Touch: runtime `templates/prompts.ts`, `tools/{stream-parser,tool-executor}.ts`, spawn handlers and tool schemas. Resolve one authorized map before publication; ensure provider-visible direct aliases dispatch without requiring a contradictory surface, generic mode does not accept hidden aliases, and internal-only pruner is runtime-permit-only. Detect normalized collisions, reserve compatibility aliases, hide unresolved targets with diagnostics, and make legacy unrestricted roots an explicit compatibility policy. Keep original input indices and typed reasons for rejected/missing children; emit a correlated result or no transcript call for early refusal. Normalize validated aliases before job ownership checks. + - Acceptance: Direct, generic, legacy, missing, reserved, collided, denied and mixed-batch cases agree in schema and native/text dispatch; every submitted member is accounted for, successful siblings are not lost, and no internal tool is model-callable. Existing owned Plan-job decisions use validated input. + - Validate: T `./packages/agent-runtime/src/__tests__/prompts-schema-handling.test.ts` `./packages/agent-runtime/src/__tests__/spawn-agents-permissions.test.ts` `./packages/agent-runtime/src/__tests__/plan-mode-dispatch.test.ts`; add table-driven actual routing and paired result tests. + +- [x] P3.2 Make MCP grants explicit and monotonic. + - Depends on: P1.3, P1.5, P3.1 + - Touch: runtime `mcp.ts`, `run-agent-step.ts`, tool executor, SDK external integration and template schema. Separate server attachment, model selectors, programmatic selectors and an explicit compatibility all-tools grant. A removed selector does not mean unrestricted; preserve explicit empty through narrowing, restart, supervised/ACP transport and catalog generations. Legacy broad exposure remains clearly labelled where explicitly chosen; PLAN still has no MCP dispatch. + - Acceptance: Authorizing one server cannot expose another; programmatic-only stays hidden; narrowing to empty produces no calls; stale catalogs and foreign origins refuse; explicit compatible positive modes work on both in-process and supervised paths. + - Validate: T `./sdk/src/__tests__/external-tool-consumers.test.ts` `./sdk/src/__tests__/run-mcp-tool-filter.test.ts` `./sdk/src/__tests__/run-mcp-execution.test.ts`; add inert two-server and inherited-empty cases. + +- [x] P3.3 Report supervision guarantees and bound detached settlement. + - Depends on: P1.1, P1.3, P3.1 + - Touch: `sdk/src/impl/agent-runtime.ts`, supervised child entry, `spawn-agent-utils.ts`, runtime background settlement. Distinguish `prefer` from `require`; expose actual backend and reason to callers, never degrade a strict request. Fence and bound retention retries to owner/lease lifetime; emit unresolved cleanup/persistence as an explicit status and reconcile without relaunching. Keep internal pruner and verified native PLAN process boundaries distinct. + - Acceptance: Required supervision emits a refusal without in-process effects; preference preserves compatibility with explicit downgrade; disk/lease loss or owner crash leaves cancellable owned work or an unconfirmed terminal record, not an open retry loop or duplicate launch. + - Validate: T `./packages/agent-runtime/src/__tests__/spawn-process-supervision.test.ts` `./packages/agent-runtime/src/__tests__/background-agent-jobs.test.ts` `./sdk/src/__tests__/run-host-execution.test.ts`; add timed retention outage and required-mode tests. + +- [x] P3.4 Expose effective capabilities and routed-role readiness. + - Depends on: P1.4, P3.1, P3.2, P3.3 + - Touch: CLI help/agent menus, runtime tool prompts, SDK tool admission, provider readiness, registration guard. Expose a redacted per-actor list of callable, loadable, generator-only, requires-host and unavailable tools with reason and canonical alias. Return typed `ask_user` unavailable/skipped when interaction is not provided. Diagnose missing child model/provider routes even if root is ready; never expose credentials or silently introduce a new fallback. Use the same admitted catalog for textual help and machine tests. + - Acceptance: Core versus loaded versus denied matches actual provider calls; an SDK without elicitation and a CLI with an unroutable child give useful status, while supported hosts retain functionality. Generated types and bundled/installed CI schema agree with actual dispatch, including host-only and compatibility names. + - Validate: T `./agents/tool-reachability.test.ts` `./common/src/tools/__tests__/tool-registration-consistency.test.ts` `./sdk/src/__tests__/run-model-override.test.ts`; add SDK/CLI readiness and provider/direct-call catalog differential test. + - Source and packaged evidence: prepared runtime tool schemas drive the actor-specific catalog and admitted `@` members receive redacted route diagnoses. Focused egress-isolated source and CLI selections passed 188 and 84 cases respectively. The final SDK and batch pair passed 22 more cases: an invalid named child route reports a correlated `child_route_unavailable` without a child launch, using no root fallback. The installed CJS/ESM probes verify the same refusal. + +- [x] P3.5 Bound and deduplicate external capability discovery. + - Depends on: P3.1, P3.2 + - Touch: runtime `run-agent-step.ts`, `mcp.ts`, catalog strings/prompts and SDK discovery. Share actor/authority/catalog-generation scoped in-flight results across schema/prompt/tier refresh; avoid duplicate child resolution. Bound slow external peers and cancellation; surface partial results without inheriting another actor's authority. + - Acceptance: Counted fixture shows one probe per valid actor/generation, no cached result survives cancellation/authorization changes, and a stalled peer does not delay already-available built-ins beyond the selected bound; other peers and actors remain isolated. + - Validate: T `./sdk/src/__tests__/external-tool-consumers.test.ts`; measure cold/warm discovery under fake time, slow peer, cancellation and invalidated tier/actor controls. + +- [x] P3.6 Add an explicit path for isolated multi-editor work, without changing default spawn. + - Depends on: P1.5, P2.1, P3.3 + - Touch: existing `sdk/src/services/workspace-worker-host.ts`, operator workspace/worker controls and worktree admission. Reuse managed workers and durable job ownership; add operator-approved owned worktree allocation, exact branch/base/change receipts, explicit aggregation/merge decision and cleanup. No arbitrary Git management from model tools, sharing approvals, automatic conflict resolution, or automatic merging to the user branch. Keep serial same-worktree editing as the default; if native support is unavailable it must refuse with the manual alternative. + - Acceptance: Before claiming isolation, two owned worktrees can edit independently with proven identities/custody, cannot address each other's jobs or files, and cancellation/conflicts/restart preserve user data. Integration grants no review credit until the merged bytes have passed fresh checks and review. + - Validate: Extend `./cli/src/__tests__/managed-workers.integration.test.ts` via the documented Linux build/tmux lane; add granted/refused/partial allocation and conflicting integration fixtures without remote Git effects. + - Verified: 7 SDK allocation cases, 9 CLI panel cases, and 2 isolated real CLI/tmux cases. Managed Workers → Worktrees previews the exact local ref/commit before allocating a detached workspace and requires independent edit approval. Selection revalidates exact receipts, never merges or grants review credit, and cleanup retains dirty/uncertain allocations. SDK cases exercise simultaneous workers and restart; terminal coverage verifies the two writers sequentially. + +## P4 — Context gathering, transfer, and memory + +- [x] P4.1 Bind index retrieval to the admitted workspace across CLI, SDK and ACP. + - Depends on: P1.3, P3.1 + - Touch: `sdk/src/client.ts`, SDK client tool binding, `sdk/src/serve/bridge.ts`, `cli/src/utils/codebuff-client.ts`, SDK MCP index projection. Add canonical query binding for supported hosts and preserve client overrides when installing ACP elicitation. Respect fs scope, index configuration and trust; return typed disabled/stale/unavailable/virtual-host limitations; carry bounded related-file and indexed-basis evidence consistently in the CLI/SDK/MCP projections rather than claiming full parity on a truncated packet. + - Acceptance: Root and joined child use real index binding through direct CLI, supported bare SDK and attached ACP with `ask_user` present; unrelated per-run overrides do not erase index capability. Disabled, scoped, strict-read and unsupported views do not gain raw access; fallback is actionable and partial claims are labelled. + - Validate: T `./packages/agent-runtime/src/tools/handlers/tool/__tests__/query-index.test.ts` `./sdk/src/__tests__/mcp-server.test.ts`; add loopback SDK/ACP root-and-child binding and no-backend controls. + +- [x] P4.2 Replace nested picker text parsing with typed retrieval receipts. + - Depends on: P3.1, P4.1 + - Touch: `agents/file-explorer/{file-lister,file-picker}.ts`, runtime `read-subtree.ts`, output schemas. Pass canonical project-relative entries from a scoped live view, preserve path basis and child outcomes through `set_output`, merge index and live support with bounded deduplication, and distinguish empty, capped, unavailable, stale, cancelled and failed. Verify stale candidates with bounded targeted reads rather than an unconditional full subtree scan. + - Acceptance: Index-disabled real nested/sibling scope produces the expected paths, including `files/`, extensionless, whitespace and non-ASCII names; no false empty or silent cap/truncation; failed child receipt remains visible. Downlevel typed/legacy agent output has an explicit compatibility path, not a green guess. + - Validate: T `./agents/__tests__/file-lister.test.ts` `./agents/__tests__/file-picker.test.ts` `./agents/e2e/file-explorer.e2e.test.ts`; add real engine and nested spawn dataset with malformed/truncated cases. + +- [x] P4.3 Guarantee pre-read of concrete files or explain omissions. + - Depends on: P4.2 + - Touch: `agents/general-agent/general-agent.ts`, exact readers and spawn brief guidance. Make file and directory inputs distinct; validate type for mixed legacy inputs without basename heuristics. Preserve per-path success/refusal/truncation and explicit file-read authority rather than substitute a subtree outline for source bytes. + - Acceptance: Dotfiles, extensionless scripts, dotted directories, nonexistent, outside-scope and over-budget input have explicit outcomes; a concrete readable file contributes exact content, and no partial pre-read is silently represented as complete. + - Validate: T `./agents/__tests__/general-agent.test.ts`; add real read/subtree controls and mixed-path/partial fixtures. + +- [x] P4.4 Make librarian custody positive and narrow. + - Depends on: P1.1, P3.3 + - Touch: `agents/librarian/librarian.ts`, spawn cleanup, terminal policy/host adapter. Accept canonical supported public HTTPS sources once; bind normalized repo identity and exclusive temp directory to a host-issued custody receipt. Announce clone/retain only on positive matching evidence; join cleanup and report unconfirmed state. Withhold unavailable routes in PLAN and steer public docs to approved read-only researchers instead of weakening enforcement. + - Acceptance: Trailing slash normalizes consistently; unknown schema, absent result, denied clone, cancellation, wrong directory and cleanup failure never report clone complete or retained. Use a no-network fake adapter plus owned local-repo completion control; no external checkout required. + - Validate: T `./agents/librarian/librarian.test.ts` `./packages/agent-runtime/src/__tests__/librarian-cleanup.test.ts`; add custody/collision and actual Plan catalog tests. + - Local evidence: these suites plus `./sdk/src/__tests__/librarian-checkout.test.ts` passed 45 cases. The SDK binds the exact registered spawn to a native, operator-approved checkout with no portable fallback. The positive fixture uses a private local repository and an injected native monitor, not real network/platform enforcement. + +- [x] P4.5 Support pinned documentation evidence and explicit fallback. + - Depends on: P3.4 + - Touch: `agents/researcher/researcher-docs.ts`, `common/src/tools/params/tool/read-docs.ts`, Context7 handler/provider bridge. Add verified library/version/reference selection, bounded retry on ambiguity and a parent-owned official versioned URL fallback via `researcher-web`. Keep external keys/backend optional; return a provenance-rich unavailable or wrong-version result rather than treating top-ranked default docs as pinned. + - Acceptance: An explicitly requested older version either returns exact verified provenance or a typed gap; ambiguity, credentials, cancellation and rate limits are not silent substitutions. + - Validate: T `./packages/agent-runtime/src/llm-api/__tests__/context7-api.test.ts` `./agents/__tests__/audit-contracts.test.ts`; add fake-provider pinned-version and fallback cases. + +- [x] P4.6 Make conversation search-to-exact-page recall composable. + - Depends on: P3.1 + - Touch: `common/src/tools/provider-schema.ts`, recall input/handler, archive and FTS query, archive reader. Publish the exact `message` + `sourceRunId` selector supported by native validation. Carry source provenance through local/host/edited-branch query, synthetic IDs, UTF-8 page cursors and degraded reads without granting body credit to excerpts. Benchmark repeated FTS work; only introduce a bounded generation-keyed cache if it improves the measured path with unchanged behavior and isolation. + - Acceptance: A provider schema validator accepts the intended selector; both local scanners and host results can page their original bytes or return stale/unavailable, with no cross-run leak. Benchmarks record probes and memory bounds; no speculative caching required if it doesn't improve measured reads. + - Validate: T `./common/src/tools/params/__tests__/recall-context.test.ts` `./packages/agent-runtime/src/util/__tests__/archive-recall-index.test.ts` `./sdk/src/__tests__/context-archive-reader.test.ts`; add actual search→provider-call→page fixture. + +- [x] P4.7 Make decision writes isolated, guarded and verifiably durable. + - Depends on: P1.2, P3.1 + - Touch: `record-decision` runtime handler, inherited task memory, native observation and SDK/CLI memory coordinators, Base2 tool tiers/prompt. Use copy-on-write or CAS for ordinary, deduplicated and superseding records; isolate siblings/parallel batches. Distinguish local/session acknowledgment from host-accepted durable observation, including disabled/unavailable/failure. Expose `record_decision` in the appropriate execution tier only **after** those guards work; align prompts and capabilities, and keep read-only specialists unable to promote decisions. + - Acceptance: Frozen and unfrozen shared input produce consistent child isolation; one actor never changes another's private memory, persistence/refusal is truthful across CLI vs bare SDK and after restart, and the shipped root calls the tool via its published reachable schema. + - Validate: T `./packages/agent-runtime/src/tools/handlers/tool/__tests__/record-decision.test.ts` `./sdk/src/__tests__/memory-v2-roundtrip.test.ts` `./sdk/src/__tests__/memory-v2-child-authority.test.ts` `./agents/tool-reachability.test.ts`; add sibling mutation, capture outage and root receipt controls. + +- [x] P4.8 Add an operator-owned path to apply a specific reviewed memory proposal. + - Depends on: P2.1, P4.7 + - Touch: `agents/memory/contracts.ts`, SDK memory operator service, CLI `/memory`. Provide stable proposal ID, target identity, exact evidence basis/revision, preview and single-use approval. Forward approved repository-file changes to the guarded editor/review path, derived maps to deterministic producers, and canonical retirement/correction to history-preserving operator actions. Do not let manager output, free-text targets or reviewer verification prose authorize changes. + - Acceptance: An operator can preview, approve, apply and reverify the exact eligible change; stale/replayed/foreign/unsupported or unapproved proposals refuse with no effects; partial apply has a typed outcome and recovery path. SDKs without the operator surface explicitly report the limitation. + - Validate: T `./sdk/src/__tests__/memory-management-agents.test.ts` `./sdk/src/__tests__/memory-v2-roundtrip.test.ts`; extend CLI memory command and restart/approval replay fixtures. + + - Verified: `/memory operator` stages an exact root `knowledge.md` edit or deterministic `knowledge-outline-v1` rebuild, or selects a history-preserving canonical correction. Apply requires a fresh single-use host approval. Restart verification joins its durable native receipt and exact live bytes without replaying or repairing an edit; an independently controlled Ed25519 key attests the exact postimage/proposal/worktree/receipt. Unbound approval, foreign worktrees and unsupported graph/index producers refuse. This is an operator-selected lane, not automatic promotion of manager output or semantic gate credit. Focused isolated selections passed 72 SDK/agent tests and 106 CLI tests; the final combined playback/memory CLI selection passed 205. + +## P5 — Positive test, dependency, and smoke execution evidence + +- [x] P5.1 Route affected tests using verified project targets and safe invocation. + - Depends on: P1.1, P4.1 + - Touch: `sdk/src/services/{harness-intelligence,build-graph}.ts`, `get_affected_tests`, `get_build_targets`, Base2 target selection. Reuse workspace probe and indexed relationship results; keep ownership/confidence, partial scans and evidence. Extend conventions beyond same-extension siblings (CLI/SDK, Python, Go, JVM); prefer the admitted workspace script and proven filters. Pass validated cwd and arguments separately from shell text; never interpolate a repository path into a command. The CLI fallback uses the documented package runner. + - Acceptance: Real CLI/SDK distant tests are found; mixed-package and space-bearing paths route correctly; unknown or unsupported cases remain unknown. Typecheck is never counted as tests, and affected/owning targets are hints unless backed by a real dispatch. + - Validate: T `./sdk/src/__tests__/harness-read-tools.test.ts` `./agents/__tests__/base2-writer-spawn-rules.test.ts`; add polyglot workspace, CLI-runner and bounded probe-count fixtures. + - Verified: typed polyglot target discovery and fresh owner checks feed a shell-free supported Bun route with separate cwd and file argv. The documented workspace/CLI scripts validate exact unit-lane inventory and preserve the CLI preload. The targeted CLI invocation `bun --no-env-file --no-install run test --selected-cases-junit ./src/__tests__/cli-args.test.ts` in `cli/` ran 93 cases in exactly one file. Other discovered runner/selector families remain hints until a verified dispatch path supports them. + +- [x] P5.2 Bind requested behavior to actual tests on a known snapshot. + - Depends on: P1.2, P1.6, P2.1, P5.1 + - Touch: test-writer brief/receipts, Base2 auxiliary checks, runner adapters and result validators. Pass criterion IDs and concrete source/behavior; correlate changed test path, case and assertion with runner attestations. Capture executed/skip counts, cwd/command and snapshot; require positive nonzero execution of the selected checks for test credit (unsupported runners report inconclusive). When appropriate capture a regression's red-before/green-after without undoing user work. Preserve per-group failed, skipped, not-attempted and unresolved results for targeted retry; evaluate writer-requested validation rather than treating arbitrary requests as trusted commands. + - Acceptance: Unrelated green suite, typecheck-only, no tests, skipped target or a writer's self-claim cannot satisfy an explicit test requirement. Multi-group checks list unattempted groups without dropping them; a real selected assertion is traceable, including intentional existing-test coverage/no-op. + - Validate: T `./agents/__tests__/base2-writer-spawn-rules.test.ts` `./agents/e2e/gate-aux-ordering.e2e.test.ts`; add runner-backed fail/skip/pass, no-tests, multi-workspace and criterion-ID cases. + - Verified: `bash scripts/run-offline-base2.sh` passed 14 source cases, including an exact selected Bun JUnit case with nonzero assertion count plus skipped, unrelated, absent-case and zero-assertion negatives. Writer case associations are suggestions checked by the parent; the receipt binds execution and exact scoped byte/runner-config markers, not semantic coverage. Stored receipts render as history but require a current host attestation for gate reuse. The affected Base2/routing/workspace selection passed 92 tests. No other runner or intentionally deceptive project code earns attestation by this path. + +- [x] P5.3 Fix targeted validation binding, typed classification, cancellation and hook scheduling. + - Depends on: P1.1, P2.1, P5.1 + - Touch: `sdk/src/tools/{run-targeted-validation,file-change-hooks,get-change-review-bundle}.ts`, `sdk/src/run.ts`, shared schemas. Refuse adapter/host checkout mismatch before scheduling, compose caller and captured deadline signals, and require positively confirmed results; empty/unknown record never upgrades assurance. Report actual executed kinds separately from requested labels. Bound concurrency, serialize checks with declared shared outputs, avoid redundant probes and preserve no-config/untrusted inference behavior. + - Acceptance: Custom filesystem, unmatched, refused, malformed, no check, mid-run changed or unavailable snapshot produce explicit no/reduced evidence without a foreign launch; successful relevant work receives scoped credit only, not full reviewer or commit authority. Cancellation joins cleanup and remembers the original scope/deadline. + - Validate: T `./sdk/src/__tests__/run-targeted-validation.test.ts` `./sdk/src/__tests__/file-change-hooks.test.ts` `./sdk/src/__tests__/get-change-review-bundle.test.ts`; add mixed malformed results, identity mismatch and scheduling tests. + +- [x] P5.4 Specify and enforce dependency-manager capability before dispatch. + - Depends on: P1.1, P1.3, P3.1 + - Touch: `agents/dependency-manager/dependency-manager.ts`, SDK terminal admission/profile, approved manager command table. Share validated ecosystem/version/operation/selector data between generator and terminal policy. Resolve Yarn root/workspace command mismatch and scoped `uv` semantics; reject unsupported selectors rather than silently broadening. Route trusted repo guards through validation instead of a shell exception. Keep deterministic process/write calls hidden from the model and intersect role restrictions with host policy; retain explicit dependency approval. + - Acceptance: Operation/selector matrix has paired accepted/refused controls at actual dispatch, including unavailable or unauthorized managers. Unsupported combinations do not launch, install, change scope, or become arbitrary shell. Never test against a real package registry by default. + - Validate: T `./agents/__tests__/dependency-manager.test.ts` `./sdk/src/__tests__/terminal-profile-bound.test.ts` `./sdk/src/__tests__/terminal-command-policy.test.ts`; extend with inert manager binaries and checked argv/no-network oracles. + +- [x] P5.5 Confirm dependency outcomes and conditional rollback. + - Depends on: P2.1, P5.4 + - Touch: dependency generator, transaction broker, raw evidence and SDK native receipts. Require positive executed exit zero; preserve refused, indeterminate and partial. Capture whole exact manifests/locks before and confirmed after, including newly created lockfiles. Roll back only against attributable exact postimages, never concurrent user bytes; attest confirmed restored/missing/conflicting/unknown paths rather than attempted writes. + - Acceptance: Native error/missing result never becomes success. New lockfiles count as changes; failure after partial write, stale rollback scope, truncation, missing authority and concurrent external write preserve correct bytes and typed recovery status. + - Validate: T `./agents/__tests__/dependency-manager.test.ts` `./sdk/src/__tests__/run-mutation-dispatch.test.ts`; new receipt-wire and real broker rollback tests using synthetic fixtures. + - Verified: `./sdk/src/__tests__/staged-dependency-runner.test.ts` drives the native broker for an explicitly composed npm-root staged operation. Adds require an exact requested version, matching npm v3 root dependencies, a canonical registry artifact and SHA-512 integrity; approval sees exact before/proposed bytes. A failed second publication restores exact retained bytes and file mode or deletes only a broker-owned created lockfile. Stale/missing/conflicting/unknown cases remain distinct, including same-byte replacement and borrowed receipts. No legacy shell diff grants rollback; its nonzero result stays partial and preserves concurrent user bytes. Staging publishes manifests/locks, not an install or a transitive artifact verification. Combined dependency and host-audit selection: 163 passed/1 platform skip; final boundary/package selection: 59/59. + +- [x] P5.6 Use owned diagnostic and terminal UI execution instead of broad shell profiles. + - Depends on: P1.1, P1.3, P3.3, P5.4 + - Touch: `agents/{tmux-cli.ts,debugger/}`, SDK terminal profile/admission, PTY/tmux host lifecycle. Build narrow executor inputs with validated cwd/argv/ids, bounded actions and no implicit wider host grant. Acquire cleanup ownership before partial setup; use owned temp/socket; distinguish target exit, empty capture, silence, idle timeout and assertion. Debugger retains its reproduction receipt, bounds repeated attempts at runtime, and requests rechecking the original failing case after repair. Model status must cite actual captures/logs, not arbitrary `/tmp` paths. + - Acceptance: Setup refusal, session death, timeout, diagnostic command denied, nonzero target exit and cleanup failure cannot appear as success. A real owned terminal with known expected output and exit can pass, release its socket and leave no late effects. PLAN never gets a weaker fallback. + - Validate: T `./agents/__tests__/tmux-cli.test.ts` `./sdk/src/__tests__/terminal-profile-bound.test.ts`; add owned tmux/playback and debugger refusal, retry and cleanup integration fixtures. + - Verified: the Linux interactive CLI binds a canonical executable through `--tmux-playback-executable`; each exact launch/action set requires a fresh Allow once even under allow-all. PLAN, attached, headless and scoped hosts refuse without fallback. 107 CLI controls included 5 real playback cases; 35 debugger/profile controls verified typed receipts and retry rules. The 87-case prior SDK set included 24 real process/cleanup controls. The rebuilt CLI archive exposes the flag; no other platform or live TUI/provider credit is inferred. + +- [x] P5.7 Make browser smoke authority and evidence explicit. + - Depends on: P1.3, P3.3 + - Touch: `agents/browser-use/`, runtime browser policy, `sdk/src/tools/browser-logs.ts`, local smoke fixture and browser renderer readiness. Bind interactions/origins to host-approved grants, keep PLAN inspection-only and do not describe navigation as no-network. Prefer verified sandboxing; report incompatible isolation and require explicit host policy for any degraded compatibility path. Require actual successful step checks and owned capture/console/network evidence windows; label trimming and incomplete observation. Make smoke fail on required blocked/missing/partial output and verify cleanup. + - Acceptance: Tests run against an owned loopback app; allowed and denied actions, missing Chrome, disabled sandbox, truncated evidence, cancellation and cleanup are distinguishable. Positive success binds actual checked steps and retained evidence; merely returning structured output cannot pass. + - Validate: T `./packages/agent-runtime/src/__tests__/browser-logs-policy.test.ts` `./sdk/src/__tests__/browser-logs.test.ts` `./sdk/src/__tests__/browser-logs-sandbox.test.ts`; add real opt-in local Chrome cases and exact failure exits. + +## P6 — Make broad-audit evidence composable and safe + +- [x] P6.1 Bind audit analysis to the same bytes as the structural snapshot. + - Depends on: P2.1 + - Touch: `sdk/src/services/audit-intelligence.ts`, SDK audit bridge and scope traversal. Use no-follow bounded evidence reads or exclude link content; audit classification never reads a target not covered by admitted snapshot bytes. Make accumulation linear, batch compatible re-attestation, and move bounded repeated work off the event loop with cancellation where possible. Preserve snapshot membership and same-length change detection. + - Acceptance: Confined symlink/directory replacement and out-of-root fixtures are refused/excluded, changed target/basis is not accepted, and large snapshot/cancellation tests record read-count/time without weakening freshness. + - Validate: T `./sdk/src/__tests__/audit-intelligence.test.ts`; add verification counters, large/same-subsystem and symlink/abort controls on temp trees. + +- [x] P6.2 Return recoverable canonical audit artifact receipts and prove evidence provenance. + - Depends on: P3.1, P6.1 + - Touch: `sdk/src/tools/{write-audit-findings,audit-intelligence}.ts`, shard completion, common receipt schema. Make byte-identical retries same snapshot/shard/version return identical canonical structural evidence and hash; use a typed recovery path with full validation for retained artifacts; reject conflicting contents. Promote feature verification using confirmed bound exact reads/coverage, not caller text changing a flag alone. + - Acceptance: Exclusive write→identical retry→coverage evaluator composes without reconstructing receipts; stale/collision/bad shape/not read cannot complete; lifetime remains usable after compaction and artifact custody can be recovered honestly. + - Validate: T `./sdk/src/__tests__/write-audit-findings.test.ts` `./sdk/src/__tests__/audit-intelligence.test.ts` `./agents/__tests__/general-agent.test.ts`; add restart and typed retry→evaluator control. + +- [x] P6.3 Separate durable/plan/unwritable audit lanes and constrain synthesis. + - Depends on: P1.5, P6.2 + - Touch: `agents/patterns/audit-codebase.md`, `agents/guides/broad-audit.md`, prompt section, general agent and synthesizer. Give durable execution a single host-bound session slug, expected shard IDs and an artifact allowlist/hash set; constrain synthesizer reads/writes to that input and exact report target and require its confirmed write receipt. Provide bounded read-only fallback for PLAN/unwritable scratch with no forced map, no synthesized file claims, and explicit coverage limits. Separate complete source inventory, feature maturity/failure completeness and release readiness in receipts and language. + - Acceptance: Foreign shard/report path, missing artifact, conflicting slug, unsupported writes and incomplete coverage are not claimed green; durable synthesis verifies exact joined artifacts; plan stays read-only and never needs the unavailable synthesizer/renderer. + - Validate: T `./agents/tool-reachability.test.ts` `./sdk/src/__tests__/audit-intelligence.test.ts` `./agents/__tests__/audit-contracts.test.ts`; add actual scoped synthesis and paired no-write PLAN/failed artifact fixtures. + - Verified: the local SDK entry `OpenbuffClient.runScopedAudit` requires an explicit artifact-only host decision. It uses configured role routes with one pinned snapshot, bounded independently witnessed data packets, and only `set_output` for model workers. Exact native shards and one report create are bound; source drift (even before a packet could be sent), wrong shard, foreign reads/writes, forged result, overlapping ledger and PLAN/unwritable inputs fail closed. Ordinary model/spawn parameters and compatibility receipts never confer this grant. Final boundary suite passed 59/59, including the configured loopback workflow and raw-byte drift negatives. No automatic promotion of CLI chat audits or readiness credit. + +- [x] P6.4 Make the audit sharding rubric and coverage oracle agree. + - Depends on: P6.2, P6.3 + - Touch: audit guide/pattern, `evals/buffbench/plan-sharding-signals.ts` and evaluator. Use one scope classifier/rubric and count actual joined pair, subsystem, domain and snapshot IDs with verified receipts; no round-robin inferred coverage from headcount or repeated names. Preserve focused checks without costly broad sharding and require explicit out-of-scope or missing slots for broad requests. + - Acceptance: A broad plan with enough agents but duplicated/absent coverage cannot pass; actual paired findings and verified features can; read-only/skipped/heuristic cases keep the correct evidence label. + - Validate: T `./evals/buffbench/__tests__/plan-sharding-signals.test.ts` `./sdk/src/__tests__/audit-intelligence.test.ts`; add nominal and negative real-trace fixtures. + - Verified: real offline SDK joined audit traces pass positive source coverage, then fail when a join is removed; PLAN remains a no-write/read-only trace. The combined audit selection passed 231 with one platform skip. Copied IDs and repeated slots do not count. + +## P7 — CI, installed-agent acceptance, and closeout + +- [x] P7.1 Align test inventory, evidence accounting and eval configuration. + - Depends on: P0.1, P5.1 + - Touch: root/workspace test manifests, `cli/scripts/run-cli-tests.ts`, `.github/workflows/{ci,nightly-e2e,eval-pr-subset,nightly-evals}.yml`, `evals/buffbench/regression-gate.ts`, testing docs. Use one authoritative per-workspace intended suite inventory and fail loud on partial discovery, unexpected empty or nonexistent suites. Explain intentional exclusions, install/provision only needed pinned capabilities for required platform lanes, and expose executed/skipped/missing/retried counts. Cover SDK/runtime/CLI evidence changes in eval triggers; publish distinct no-key, no-baseline, dry-run, live, failed outcomes. Give jobs only the named secrets at the step that needs them; no all-secrets env inventory. + - Acceptance: Local/CI commands select documented matching sets, including intended CLI and agents E2E lanes; absent native/browser/tmux prerequisites are explicit. Missing baseline or dry run cannot imply verified live regression performance. Fixture changes exercise triggers and leaked/implicit success paths without printing secrets. + - Validate: T `./cli/src/__tests__/run-cli-tests.test.ts` and the checked-in CI/eval guard tests; compare actual suite inventories, run `cd cli && bun run test` and affected package schedules, and exercise key-free dry-run status. + - Verified locally: authoritative unit/integration inventories converge on the CI matrices; both SDK/CLI integration lanes passed with egress isolated as described above. Dry-run and key-free modes executed zero cases and yielded no live baseline; missing or incomparable baselines and lookup failure do not claim a verified regression comparison. Named provider secrets are scoped to the live steps. No hosted workflow or live scores were exercised. + +- [x] P7.2 Tighten individual integration tests for real boundaries, errors and custody. + - Depends on: P0.1, P1.2, P2.1, P3.1 + - Touch: `agents/e2e/`, `sdk/e2e/`, update outdated test comments/docs. Replace permissive schema stubs and fabricated success with actual parsed outputs and confirmed postimages where the seam is being asserted. Use a rendezvous for cancellation and exact invalid-agent/outcome assertions, including no late effects. Keep opt-in Deep/live/provider/native status visible; distinguish classifier evidence from verified OS enforcement. Test stale read after compaction, refusal, refresh and confirmed edit with the real code path. + - Acceptance: Invalid agent cannot pass merely by not throwing; cancellation observes exact terminal reason and joins cleanup; Deep opt-in unauthorized/unavailable is not a pass; real SDK gate and permission fixtures fail when their predicates are removed. + - Validate: T `./agents/e2e/editor-orchestrator-contract.e2e.test.ts` `./agents/e2e/context-pruning-threshold.e2e.test.ts` `./sdk/e2e/workflows/error-recovery.e2e.test.ts` `./sdk/src/__tests__/run-host-execution.test.ts`; use the documented native opt-in lane for OS claims. + - Verified: 62 focused source cases passed, 6 intentional skips. The SDK observes retained native `cap.v4` across real semantic compaction, rejects an identical-looking same-length rewrite without mutation, then commits exact bytes after a fresh read. One separate native opt-in case passed for the selected existing Linux x64 GNU artifact with Bubblewrap; no new artifact or other platform inference. + +- [x] P7.3 Test copied example authority and the exact install artifacts. + - Depends on: P3.4, P4.1, P7.1 + - Touch: `openbuff.json.example`, `openbuff.d.example/`, `sdk/scripts/verify.ts`, CI/release packaging. Verify copy-and-resolve against a loopback provider (root and all necessary child roles, missing route, trusted versus untrusted hooks). Correct mismatched examples and ensure hook examples don't imply tests ran in a non-testing lane. Test the exact tarball with isolated lock-backed compatible fixtures using `npm ci` where supported; test extracted CLI plus CLI SDK bundle, CJS/ESM and generated types/grammars. Do not publish from the test. + - Acceptance: The config fixture needs no live key and reports unresolved routes before delegated work. The same candidate artifact validated is the one eligible for release; package does not contain private fixture/profile state, install dependency provenance is recorded, and skipped platform cells are explicit. + - Validate: Build SDK/CLI with the documented pinned toolchain, run existing SDK compatibility and packed-language-asset fixtures against owned artifacts, add fresh copied-config and trust matrix. + - Final exact SDK: fresh Linux x64 candidate `497cb47669387f71bc763d5b8b829c3305e77b5df46844156b37ae512a65bf9c` built with Bun 1.4.4, Node 26.13.1. `sdk/scripts/verify-installed.ts --require-pinned-node --fetch-locked-cache` populated 154 public integrity-pinned releases, then `npm ci --offline --ignore-scripts` on the same pinned Node/npm 11.20.0 installed all 166 locked host packages without workspace/ancestor links. Effective lock SHA-256 `e5b2f1c8e671b15eb6de5420fb60b603cfdffb3c7dce460ae38d3d1a55e9b381`; extracted ESM `51571cb6d52ccec758f57b82b694c7d8d1f7dce0fa2096751e912634dc5d4635`. CJS/ESM, copied route/trust controls, declarations and languages passed with separately isolated 15-case packaged lifecycle. `publish.ts --check --require-installed` verified the exact archive and current dependency/runtime evidence. Logs/artifact: `/var/tmp/openbuff-reliability-sdk-verified.jyC8J9/`. + - Final exact CLI: Linux x64 archive `30489f847ac7483bb422fb400343f4034b90d1f488f72b5722e9d629697d45c4`, ELF `e04250d59f15fe3bc5b9d48d6c2a0c6257a51249ced271b486a0026b11fcd8af`, 32 archive members. Built in a private offline overlay with the pinned Bun baseline compile target and prebuilt native sidecar. `cli-release-candidate.ts` verified help (including the optional tmux flag), version, 14/14 code-map queries, and all three headless exits (validated 0, missing hooks 1, unavailable child route 1). Logs/artifact: `/var/tmp/openbuff-reliability-cli-verified.x5Si5Q/`. No hosted release or other platform cells exercised. + +- [x] P7.4 Require an offline default-lifecycle acceptance gate for PR/release. + - Depends on: P1.6, P2.3, P2.4, P2.5, P2.6, P2.7, P3.2, P3.3, P4.2, P4.3, P4.6, P4.7, P5.2, P5.3, P6.4, P7.1, P7.2, P7.3 + - Touch: actual shipped CLI and packed SDK fixture under `test/fixtures/body/` and CI/release gates. Use scripted loopback inference in a credential-free worker that denies non-loopback egress, real discovery and selected tool calls, real context preservation across compaction/restart, actual scoped writer/editor and exact mutation receipt, configured test executing a known case, independent reviewer of the final bytes, and a receipt-bound checkpoint. Cover refused/no hooks, stale authority and review, persistent finding, wrong/waived mode, denied writes, missing route, timeout/cancel and cleanup. Measure bounded concurrent default actors with distinct run/attempt IDs, no effect bleed and selective cancellation; do not use wall-clock-only assertions. Keep fast source and heavier packed lanes separately attributable. + - Acceptance: Positive fixture proves the whole chain using shipped definitions and real tools; disk/exit/case ID/evidence/checkpoint match. Each negative case demonstrates no false acceptance or late effect. Captures report exact selected/executed/skipped counts, identity, and platform; platform-specific behavior separately verified or unclaimed. Both PR and release gating are wired without needing external credentials. + - Validate: Run the new deterministic source and exact-artifact integration in ordinary CI and offline against release candidates; run the owned prerequisite browser/PTY/OS lanes for claims made there. Confirm no published artifact is needed for the test. + - Verified: `scripts/run-offline-base2.sh` required and passed exactly 15/15 in source, extracted SDK, and lock-installed SDK cells, with no skips and independent loopback-only namespaces. The shipped Execute Plan chain crosses real semantic compaction, rejects a wrong digest, recalls exact archived bytes, retains the writer/editor postimages, runs the named asserting Bun case, verifies independent native review and accepts the live checkpoint. A fresh SDK client restores serialized state, recalls the same evidence and claims the next task without replay. The overlap control holds both actual editor replies after independently correlated reads, cancels one run, supplies its late reply, and verifies only the survivor edited, validated and completed. Run, attempt, child and workspace identities differ. PR/source and release gates are wired, and the exact CLI archive passes a separate three-case headless smoke. No hosted or product-provider run. + +- [x] P7.5 Close every audit item with evidence, migration notes and final compatibility checks. + - Depends on: P2.6, P3.5, P3.6, P4.4, P4.5, P4.8, P5.5, P5.6, P5.7, P6.4, P7.4 + - Touch: relevant guides, public types, docs, eval contracts and this checklist. Compare this coverage index against shard findings, including lower-priority and policy/UX notes. Regenerate synchronized agent/type surfaces; update mode, execution, skip/waiver, terminal profile, memory and host readiness docs. Document migration, defaults, explicit opt-in, unknown/red flags and platform gaps; record verification for new and old SDK/ACP/CLI consumers and independent review. Only the operator can accept a scope change; don't quietly close unsupported requirements as fixed. + - Acceptance: Every issue tag has a confirming task result and an evidence location, or documented approved scope decision; no uncovered matrix entries, compatibility gaps hidden by fallback, newly public unapproved capability or outstanding blocking findings. No source or deployment action runs from opening this plan. + - Validate: Run affected CI schedules/typechecks, generator/prompt/tool-registration guards, SDK build/package and final scripted integrated lane; compare tool capability inventory, validation kinds, cleanup and artifact baselines. Independently review all high-priority boundary changes. + - Final verification: `bun --no-env-file --no-install run typecheck` passed in `common`, `agents`, `packages/agent-runtime`, `sdk`, `cli`, `evals`, and `scripts`. Tool definition stubs and the CLI initial-agent type source are synchronized. Gate-helper drift, config sync, tool registration, workflow parsing, and `git diff --check` passed. Existing docs describe the guarded/legacy split and each explicit opt-in. + - Final isolated schedules used private profiles and writable overlays with loopback-only egress, Bun 1.4.4 and Node 26.13.1. Unit: `common` 2,117; `agents` 1,488; `packages/agent-runtime` 3,394; `sdk` 7,265/21 skipped; `cli` 5,057/278 skipped; `evals` 428; `scripts` 478/1 skipped. All selected files loaded; no failures. Integration: SDK 49/49, CLI 17/17. The previously interrupted SDK schedule completed uninterrupted across all 324 files. JSON receipts and logs: `/var/tmp/openbuff-reliability-final-suite.AcAmih/`. + - Root-owned system Git was intentionally unavailable in the user namespace; the isolated local synthetic custody group with Git visible separately passed 45/45. Independent review found stale release evidence, archive/receipt read aliasing, a different npm interpreter, mismatched staged resolutions, and overlapping audit state. The final boundary controls require current lock/runtime digests, bounded no-follow reads, the pinned Node for npm, exact artifact selectors and a disjoint audit ledger. The 59 focused follow-up controls passed; the final install recheck uses the same bounded receipt reader. Local source/installed artifact checks do not certify hosted, live-provider or cross-platform behavior. + +## Finding-to-task coverage + +The tags below follow the order of the original reports. Each maps to a primary implementing task or explicitly split primary tasks. Matching symptoms in multiple shards intentionally share a fix, not a separate implementation. P0.1 and P7.4/P7.5 provide shared regression and closeout evidence. + +| Finding | Issue | Planned work | +|---|---|---| +| R01 | Execute Plan cannot claim/checkpoint/advance | P2.7 | +| R02 | FAST serialized validation contradicts the roster and prompt | P2.6 | +| R03 | Explicit roots and ACP can disagree with the displayed PLAN mode | P1.3 | +| R04 | `@` suggests agents the selected root can't spawn | P1.4, P3.4 | +| R05 | Decision-capture prompt without a callable tool | P4.7 | +| C01 | ACP override erases index; SDK has no default usable query implementation | P4.1 | +| C02 | Scoped subtree basename loses nested fallback paths | P4.2 | +| C03 | File lister/picker text drops paths, failures and cap/truncation | P4.2 | +| C04 | General agent heuristics omit real concrete file reads | P4.3 | +| C05 | Librarian clone success, path/retention/cleanup and PLAN mismatch | P4.4 | +| C06 | Docs lookup cannot pin versions or reliably handle ambiguity | P4.5 | +| M01 | Root cannot call `record_decision` | P4.7 | +| M02 | Execute Plan omits native status tooling | P2.7 | +| M03 | Ambient CWD and non-atomic plan revisions | P2.7 | +| M04 | Exact recall provider selector and lost local provenance | P4.6 | +| M05 | Shared task-memory mutation without copy-on-write | P4.7 | +| M06 | No first-class operator apply of reviewed memory proposal | P4.8 | +| M07 | Synthesizer scope and persisted report are prompt claims | P6.3 | +| M08 | Decision acknowledgment doesn't prove durability | P4.7 | +| I1 | Automatic doc writer rejected and failure treated as done | P1.6 | +| I2 | Advisory writer scopes and incomplete repair/lease authority | P1.5 | +| I3 | Dependency false success, incomplete raw bases and unproven rollback | P5.5 | +| I4 | Manager/policy mismatch, broadened selectors, lockfile no-op mistakes | P5.4, P5.5 | +| I5 | Narrow task terminal profiles not bound in ordinary execute | P5.4, P5.6 | +| I6 | Diagnostic-only path fix loses finding progress | P2.2 | +| I7 | Editor no-action retries not bounded | P2.2 | +| I8 | Attempt-only edits enqueue unchanged paths | P2.2 | +| I9 | Stale `cap.v3` and range-overwrite guidance | P2.2 | +| V01 | Repair claims can overrule repeated independent findings | P2.3 | +| V02 | Wrong workspace/unreadable/deletion marker; reuse missing requirement basis | P2.1 | +| V03 | Same-path hook writes retain stale specialist approval | P2.4 | +| V04 | Waiver/skip mislabeled green; hook failures classified by prose | P1.1, P1.2, P2.7 | +| V05 | Config-only/security/manifest delivery misses reviewers | P2.4 | +| V06 | FAST mismatch, Deep triage by ID and misleading retry defaults | P2.6 | +| V07 | `/review` authority and headless acceptance are untyped/incomplete | P1.2, P2.5 | +| V08 | Duplicate post-repair validation and lost reused summary | P2.2 | +| TEST-01 | Both automatic test-writer handoffs rejected | P1.6 | +| TEST-02 | Test-only write boundary is advisory | P1.5 | +| TEST-03 | Basher summary loses refusals/timeouts, no executed-test proof and weak log custody | P1.1, P1.2, P5.2 | +| TEST-04 | tmux/debugger/task terminal profiles don't bind or don't work | P5.4, P5.6 | +| TEST-05 | Lost UI/diagnostic receipt, ambiguity and incomplete cleanup | P5.6 | +| TEST-06 | Unproven criterion coverage, group outcomes and no-op claims | P1.6, P5.2 | +| TEST-07 | Missed affected tests, unsafe CWD construction and CLI schedule drift | P5.1 | +| TEST-08 | Targeted validation wrong FS/weak states/cancellation/concurrency | P5.3 | +| TEST-09 | Browser smoke false success, approval and bounded observation gaps | P5.7 | +| TEST-10 | CI inventory, skips, host/platform dependencies, lane proof | P7.1 | +| TEST-11 | Eval filters, unverified baseline/dry-run and broad secret exposure | P7.1 | +| RT-01 | Same-ID PLAN override removes intended admission authority | P1.3 | +| RT-02 | Trusted discovery imports non-agent session code | P1.4 | +| RT-03 | Direct/generic alias, collision, hidden tool and allowlist inconsistencies | P3.1 | +| RT-04 | MCP narrowing can turn into implicit all-tools | P3.2 | +| RT-05 | Advisory path scope, inheritance, and no true zero grant | P1.5, P3.2 | +| RT-06 | Pre-handler refusals, input alias and mixed-batch receipts lost | P3.1 | +| RT-07 | Supervision degrades silently; Chrome sandbox compatibility unlabelled | P3.3, P5.7 | +| RT-08 | Host-delegated tool gaps and help/registration not equal to dispatch | P3.4 | +| RT-09 | Repeat discovery and unbounded detached settlement retries | P3.3, P3.5 | +| E01 | Deterministic E2E outside PR; no complete installed-root proof | P0.1, P7.1, P7.4 | +| E02 | Overpermissive test stubs and synthetic editor/tool evidence | P0.1, P7.2 | +| E03 | Compaction proof doesn't exercise real refreshed edit authority | P7.2, P7.4 | +| E04 | SDK error/cancel false positives, skipped Deep validation and weak smoke | P7.2, P7.4 | +| E05 | Classifier/native proof gap, no-effect and untrusted-hook controls | P1.3, P7.2, P7.4 | +| E06 | Concurrent real edits/review/cancellation not proven | P7.4 | +| E07 | SDK verify not exact publish tarball/lock-backed contract | P7.3 | +| E08 | Copied example route/hook/trust readiness not proved | P7.3 | +| A01 | Audit source-inspection coverage overclaimed as readiness | P6.2, P6.3 | +| A02 | Audit findings retry loses structural receipt | P6.2 | +| A03 | Incompatible durable/PLAN/unwritable instructions and synth scope | P6.3 | +| A04 | Shard rubric drift and headcount substituted for actual coverage | P6.4 | +| A05 | Feature follows link target bytes not bound to inventory | P6.1 | +| A06 | Synchronous repeat scans and quadratic aggregation | P6.1 | +| S01 | No host-owned isolated parallel edit allocation and integration | P3.6 | +| S02 | Docs writer prompt misroutes source comments | P1.6 | +| S03 | MCP index drops result detail/provenance relative to CLI | P4.1 | +| S04 | Root model readiness can mask missing child routes | P3.4, P7.3 | +| S05 | Repeated local FTS archive construction should be measured | P4.6 | +| S06 | BuffBench dry-run, no-baseline and live results lack clear separation | P7.1 | + +**Evidence key:** R [root](../audit-agent-tool-coverage-2026-11/findings/root-delegation.md); C [retrieval](../audit-agent-tool-coverage-2026-11/findings/context-retrieval.md); M [memory](../audit-agent-tool-coverage-2026-11/findings/memory-handoff.md); I [implementation](../audit-agent-tool-coverage-2026-11/findings/implementation.md); V [review](../audit-agent-tool-coverage-2026-11/findings/review-gate.md); TEST [testing](../audit-agent-tool-coverage-2026-11/findings/testing.md); RT [runtime](../audit-agent-tool-coverage-2026-11/findings/runtime-tools.md); E/A [end-to-end and audit contracts](../audit-agent-tool-coverage-2026-11/findings/end-to-end.md). S01/S02 are implementation follow-ups, S03 retrieval, S04 root routing, S05 memory, S06 end-to-end/evals. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/AUDIT-REPORT.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/AUDIT-REPORT.md new file mode 100644 index 0000000000..83622dda4c --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/AUDIT-REPORT.md @@ -0,0 +1,41 @@ +# Openbuff audit: orchestrator, agents, and tool coverage + +**Checkout:** `6d5364de3` · **Scope:** the shipped discovery → retention → edit → review → test lifecycle and its CLI/SDK wiring. [Full tool and spawn matrix](TOOL-MATRIX.md) · [Scope and verification](STATUS.md) + +**Verdict:** The default local CLI has enough specialists and primitives for a human-directed coding workflow. It does not consistently compose them into the advertised automatic workflow. The biggest gaps are rejected handoffs, validation/review results that can overstate what happened, and unreachable tools for plan execution and explicit memory. No additional general-purpose investigator, editor, reviewer or test-writing agent is needed to fix those. + +## Top 10 fixes, in priority order + +1. **High — Keep “allowed to finish” separate from “validated.”** The SDK returns structured `no_hooks_configured` / `hooks_skipped` with messages. Base2 prefixes these with `REDUCED_ASSURANCE:` but the final branch recognizes only the original strings, so a clean review can produce `validationStatus: passed`, `hooksRan: true` when nothing ran. Confirmed in an offline generator probe for both cases. Separately, a real nonzero hook exit can be downgraded to infrastructure failure based on a word such as `timeout` in assertion text; a matched-waiver path can be called `LOOKS_GOOD`; and summarized Basher output can omit refusal/timeout fields needed by the parent. Use affirmative, typed execution evidence, preserve all terminal outcomes through summaries, and publish independent `review`, `validation`, `waiver`, and `delivery` statuses. Make headless CI acceptance opt-in based on those statuses, not generic process success. `sdk/src/tools/file-change-hooks.ts:1642–1670`; `agents/base2/base2.ts:5895–5908,6175–6200,7999–8002,8129–8170,15259–15328`; `agents/basher.ts:397–431`. [Testing](findings/testing.md) · [Review](findings/review-gate.md) +2. **High — Honor the independent reviewer and its exact evidence.** A repair receipt can make the gate suppress an ordinary finding when the next reviewer raises it again; existing tests explicitly accept this. Same-path writes by hooks can invalidate earlier security/specialist reads without triggering re-review. In-process SDK use with `cwd` different from the embedding process can also make the gate hash the wrong workspace; an outer hash has accepted an unreadable marker in a focused probe. Keep re-raised blockers open unless explicitly waived, bind evidence to the run's captured workspace and task/baseline, reject unreadable inputs and unconfirmed deletions, and refresh all risk-required reviewer credits on final bytes. `agents/base2/base2.ts:6251–6289,6670–6752,7297–7363,7863–7897,14705–14720,14771–14799`; `agents/__tests__/base2.test.ts:7435–7518`. [Review](findings/review-gate.md) +3. **High — Repair all three automatic writer handoffs.** Initial `test-writer`, coverage-only repair, and the `doc-writer` handoff name legacy standalone `str_replace` / `write_file`, which the actual writers no longer expose. The runtime rejects all three before the child starts; coverage repair omits `edit_transaction` entirely. A manual handoff with the real tools was admitted in a paired probe. Use one shared contract, scope coverage repair to legitimate new test paths, and keep explicitly requested writer deliverables pending when the child fails. Test real admission and committed child edits rather than feeding synthetic success to the parent. `agents/base2/base2.ts:2643–2650,2804–2813,7123–7130`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:539–565`. [Implementation](findings/implementation.md) · [Testing](findings/testing.md) +4. **High — Bind PLAN authority to host admission, not a display label or replaceable definition.** The TUI can say PLAN while an explicit `--agent` wins selection. A same-ID user-owned or trusted project definition can also replace `base2-plan` without the marker the SDK uses to establish read-only lineage. An attached client uses the server's chosen root and should display that authority. These are admission/UX mismatches, not escapes from a run that already has enforced plan ancestry. Preserve the selected authority independently, reject conflicting choices or incompatible reserved-ID overrides, and align the `@` catalog with the actual permitted children. Separate but related: restrict imports during trusted agent discovery to agent entrypoints; recursively importing executable session artifacts before validating agent metadata adds unintended work and side effects. `cli/src/hooks/use-send-message.ts:130–142`; `cli/src/utils/local-agent-registry.ts:426–461`; `sdk/src/run.ts:2176–2186`; `sdk/src/agents/load-agents.ts:65–92,184–222`. [Root modes](findings/root-delegation.md) · [Runtime](findings/runtime-tools.md) +5. **High — Give EXECUTE_PLAN its receipt-checked checkpoint path.** Its own prompt requires `update_plan_status` to claim, checkpoint and advance, and recommends `create_plan` for larger revisions. Those tools are admitted only in PLAN, absent even after all Execute Plan tiers are unlocked. Confirmed by extracting the effective surface. Restore scoped plan tools to both modes; use the run's captured workspace and make plan revision/Markdown/timeline persistence transactional or explicitly recoverable. Generic source edits to the Markdown are not a substitute for validated transitions. `agents/base2/tool-tiers.ts:140–152,209–231`; `agents/base2/base2.ts:15550–15554`; `packages/agent-runtime/src/tools/handlers/tool/update-plan-status.ts:202–245,365–390`. [Root modes](findings/root-delegation.md) · [Memory](findings/memory-handoff.md) +6. **Medium–high — Close the memory handoff without granting the model unrestricted memory writes.** `record_decision` is registered and prompted, but unavailable to the shipped Base2 roots even with all tiers loaded. Wire it with the existing provenance guards, repair copy-on-write before enabling eligible child writers, and distinguish a retained session event from a confirmed durable observation. `memory-manager` is correctly proposal-only. There are existing manual operator and editor routes, but no first-class way to preview, approve, apply and verify the exact reviewed proposal by ID. Introduce a host-owned, revision-checked approval handoff only if that workflow is needed. Fix the `recall_context` provider schema and preserve source provenance for exact-message paging. `agents/base2/base2.ts:418–469`; `packages/agent-runtime/src/util/base2-tool-tiers.ts:29–97`; `agents/memory/contracts.ts:143–160,209–242`; `common/src/tools/provider-schema.ts:26`. [Memory](findings/memory-handoff.md) +7. **Medium — Make code discovery portable and lossless at the handoff.** The local CLI binds `query_index`; the bare SDK lacks that backend and the ACP ask-user override replaces the CLI's override map. The nested lister/picker can lose fallback paths when the subtree is rendered from a nested directory; parsing the newline payload also drops valid paths, including extensionless names and paths with spaces. Move index binding into a common admitted root or preserve the map, and return typed candidates with real project-relative paths and explicit stale, partial, empty or failed status. Also make `general-agent` distinguish explicit files from directories without a filename-extension guess. `sdk/src/client.ts:62–69`; `sdk/src/serve/bridge.ts:901–908`; `agents/file-explorer/file-lister.ts:128–165,285–313`; `agents/file-explorer/file-picker.ts:153–189`. [Retrieval](findings/context-retrieval.md) +8. **Medium–high — Make role boundaries and tool admission match what the orchestrator sees.** Handoff file scopes for test/doc/repair writers normally warn rather than prevent in-project out-of-scope edits. Some role-specific shell profiles do not bind in normal SDK execution. Optional configured MCP can fall back to an all-tools catalog when a narrowing handoff removes its last selector. Spawn alias presentation/permissions and per-entry rejection results also diverge in some custom configurations. Use explicit enforced ceilings where advertised, including move destinations, monotonic inheritance and a true empty grant. Keep native project containment, strict reads and plan-lineage protections distinct. Resolve one permitted catalog after host and child restrictions. `packages/agent-runtime/src/tools/tool-executor.ts:3344–3408`; `sdk/src/tools/terminal-profile-bound.ts:9–44`; `packages/agent-runtime/src/mcp.ts:98–160`. [Runtime](findings/runtime-tools.md) · [Implementation](findings/implementation.md) +9. **Medium–high — Improve test and dependency execution evidence rather than adding more model roles.** `get_affected_tests` and build targets are discovery hints, not an executed suite. Hooks need trusted configuration and may only typecheck. Some package targeting falls back to the wrong CLI schedule, and a writer's reported acceptance criteria are not bound to tests that actually ran. A dependency generator can accept an absent/unrecognized native error receipt as success and report attempted, not confirmed, rollback. Prefer validated command/cwd inputs, runner-attested check kinds and executed counts, per-criterion coverage when required, and confirmed mutation/rollback evidence. For UI smoke, use host-owned browser/PTy sessions with typed start, assertion, exit and cleanup evidence. `sdk/src/services/harness-intelligence.ts:1585–1596,1683–1719`; `agents/base2/base2.ts:12325–12355`; `agents/dependency-manager/dependency-manager.ts:587–622,699–726,783–817`. [Testing](findings/testing.md) · [Implementation](findings/implementation.md) +10. **High leverage — Require one offline shipped-root lifecycle test in PR/release CI.** Strong focused suites and real consumer fixtures exist, but the gate tests often inject tool results, and the default installed release smoke does not require a full shipped `base2` turn. Add an extracted CLI/packed SDK test with a scripted loopback provider, one actual delegated editor and writer, disk assertions, real test commands and an exact-snapshot reviewer receipt. Include negative cases for missing hooks, denied execution, persistent review findings, PLAN authority, and a successful post-restart checkpoint. Run the fast deterministic gate subset in normal PR CI too. `.github/workflows/ci.yml:291–306`; `.github/workflows/nightly-e2e.yml:63–69`; `agents/e2e/editor-orchestrator-contract.e2e.test.ts:94–129`. [End-to-end evidence](findings/end-to-end.md) + +## Role and tool coverage + +| Phase | Shipped coverage | What the orchestrator still owns | +|---|---|---| +| Gather | Root search, index, reads and language navigation; `file-picker` → `file-lister`; `general-agent`, `thinker`; `researcher-docs`, `researcher-web`, `librarian`. | Scope and verify evidence; use native search/read fallback when index or external research is unavailable. Context7 and browser/research tools have independent prerequisites. | +| Retain and share | Root `recall_context`, internal compaction, per-child handoffs/structured output, repository knowledge, durable plan/audit artifacts, CLI memory; `memory-manager` → knowledge retriever and reviewer. | Choose the right durability layer. Child output is not canonical memory; explicit proposal acceptance and publication remain operator-owned. Bare SDK hosts do not automatically get CLI SQLite memory. | +| Change | `editor`, `repair-editor`, `test-writer`, `doc-writer`, guarded `dependency-manager`, plus root `edit_transaction` for scoped inline changes. `debugger` investigates, not repairs. | Supply a brief and explicit ownership, join actual mutation results, re-read stale bases. Ordinary sibling spawns share a worktree; isolated parallel mutation is not a default spawn feature. | +| Review | Independent `code-reviewer`, `security-reviewer`, `review-triage`, and domain specialists for accessibility, UX, API compatibility, migrations, reliability, performance and more. | Compare against exact changes and requirements, enforce vetoes, and re-review drift. A static verdict is not command/test proof. | +| Test | Separate author (`test-writer`), command runner (`basher`), diagnosis (`debugger`), browser (`browser-use`) and terminal UI (`tmux-cli`). Root has programmatic file hooks and loadable targeted validation/test-build intelligence. | Choose commands/assertions and join execution receipts. `run_targeted_validation` cannot clear the review gate. A successful spawn or zero exit is not proof of a particular test suite. | + +The stock default root has 23 initial built-ins (before optional host substitutions), 19 additional loadable tools and 8 generator declarations; the inventories overlap. It declares 38 spawn targets including the internal pruner. Not every specialist should receive every root tool: read-only review, writer/executor separation, and user-owned approval are the right design. `base-deep` shares the primary roster; FAST drops editor/repair/thinker and uses inline editing. FAST currently runs the automatic gate when the serialized config is used despite prompts/tests that expect the lighter path; align those policies. PLAN intentionally withholds source mutations and only permits terminal descendants with verified native read-only enforcement. Headless CLI includes the shipped registry; the plain SDK requires a selected host-known definition and any necessary client tool bindings. See [the exact per-definition matrix](TOOL-MATRIX.md). + +## Additional findings by area + +- **Retrieval and performance:** documents research cannot pin an exact dependency version through `read_docs`; librarian has clone-success/custody reporting gaps. Repeated synchronous broad-audit feature scans can do avoidable whole-snapshot work. +- **Memory and broad-audit evidence:** an identical audit artifact retry can report `alreadyPersisted` without the structural receipt needed for the coverage evaluator. Completion of source inspection is not release readiness. Plan-only/read-only instructions conflict with parts of the durable synthesizer flow, and the synthesizer's assigned-session read/write scope is not strongly enforced. Inventory/feature byte reads also need matching symlink semantics. +- **Review and delivery:** risk selection misses some config-only paths; `/review` requests static analysis but does not itself enforce a read-only tool set or require a child verdict. Explicit bypass and ordinary acceptance need distinct machine-readable states. +- **Runtime/API:** pre-dispatch refusals and invalid members of mixed spawn batches are not consistently present in joined structured results. Process supervision may degrade to in-process when requested; that behavior should be explicit and distinct from a strict execution boundary. `ask_user` is registered but needs a host integration in the standalone SDK. + +## Coverage and limits + +Eight vertical shard reports are indexed in [STATUS.md](STATUS.md). All 49 shipped definitions matched the local generated registry's tool and roster inventory. The audit lead ran **1,140 focused tests across 52 files, zero failures**, plus deterministic handoff, tool-ceiling and gate-outcome probes. The green tests do not contradict the audit: some pin individual seams or the current behavior rather than the advertised whole workflow. No live remote-provider performance, complete monorepo test pass, published-release lifecycle, or live browser/TUI/native sandbox result is claimed. Only audit artifacts were written; no tracked sources changed. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/STATUS.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/STATUS.md new file mode 100644 index 0000000000..2a2a7c0576 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/STATUS.md @@ -0,0 +1,48 @@ +# Agent and tool audit coverage + +- Checkout: `6d5364de3`; no tracked source, config or tests changed. +- Scope: the shipped coding lifecycle and the local/ACP/SDK interfaces that affect it, not a general codebase security or release audit. The project breadth classifier recognized `agents` and `runtime` and returned `unclear`; repository size and the cross-package tool path warranted eight vertical shards rather than a single-file review. +- Inventory: 49 shipped definitions, including 8 roots, compared to the generated CLI registry. Effective initial built-ins, progressive ceilings, generator tools, and child allowlists are in [TOOL-MATRIX.md](TOOL-MATRIX.md). +- Discovery: the local cached index was unusable; built a read-only index in memory (2,171 paths), queried search and command modes, and verified code against the checkout. The SDK structural service reported 3,482 paths in the selected inventory, snapshot `4a4f41d9d39fbe23ca9572f6145e4b94bab5a09144ee13088a3a3d172c31fc62`. These counts measure discovery breadth, not individually audited files. Feature scans provided heuristic leads only. This external audit does not claim a native Openbuff `evaluate_audit_coverage` receipt or product readiness. + +## Coverage matrix + +| Shard | Feature evidence | Coverage | +|---|---|---| +| [Root delegation](findings/root-delegation.md) | TUI/headless/SDK entrypoints, base root modes, actual tool and spawn availability, child routing | Source, generated definitions, offline probes | +| [Retrieval](findings/context-retrieval.md) | File discovery, read/index/search implementation, docs/web/librarian, thinker, evidence handoff | Source and existing tests; local index query by audit lead | +| [Memory and handoff](findings/memory-handoff.md) | Recall/compaction, structured output, plans/audit artifacts, knowledge management, CLI and SDK durable storage | Source, offline task/memory suites, effective-surface probe | +| [Implementation](findings/implementation.md) | Editor/writer/repair, edit authority, dependency operations, path ownership/leases | Source, offline suites and handoff/error probes | +| [Review](findings/review-gate.md) | Independent code/security/specialist review, blockers, snapshots, repair, bypass, completion | Source, isolated unit/generator tests and result probes | +| [Testing](findings/testing.md) | Test design, writing, command selection, running, refusal, evidence; TUI and browser smoke | Source, offline suites and classifier/generator probes; not actual browser/TUI work | +| [Runtime tools](findings/runtime-tools.md) | Declared/effective tools, schema/dispatch, child authority, optional providers and transport boundaries | Source, unit and SDK integration fixtures | +| [End-to-end evidence](findings/end-to-end.md) | CI/eval schedules, composition gaps, broad-audit contracts, installed-consumer evidence | Source and selected deterministic tests | + +Audit checklist used: security/permissions, correctness, state mutation, error handling, performance, dependency hygiene, test coverage, and API contracts. Entry points, declaration/registration, execution, consumers, docs, and relevant unavailable/skip/failure/cancel states were considered. Findings with only a source trace are not labelled live reproductions. + +## Tracked subsystem enumeration + +| Top-level directory | Disposition | +|---|---| +| `.agents/` | Limited: project-agent loading/trust and session/artifact surfaces; personal/team templates, skills and historical sessions are not an audit of shipped roles. | +| `.bin/` | Out of scope: repository environment wrapper, not shipped tool dispatch. | +| `.github/` | Audited: workflow/test/eval/release evidence relevant to these roles. | +| `.vscode/` | Out of scope: IDE workspace settings. | +| `agents-graveyard/` | Out of scope: archived definitions, not shipped. | +| `agents/` | Audited: all shipped declarations, relevant phase implementations, prompts and tests. | +| `cli/` | Audited: TUI/headless/ACP selection, agent registry, tool binding, memory, hooks and test/publish evidence; not unrelated screens. | +| `common/` | Audited: relevant tool schemas, policy/metadata, shared plan/knowledge/validation contracts. | +| `docs/` | Audited: relevant mode, tool, request-flow, permission, validation and testing contracts; not unrelated roadmap history. | +| `evals/` | Audited: lifecycle, retention, sharding, and regression coverage relevant to the question; not individual benchmark tasks. | +| `openbuff.d.example/` | Audited: role routes, provider expectations, and hook examples. | +| `packages/` | Audited: `agent-runtime`, retrieval interfaces in `indexer`/`code-map`, relevant BYOK adapter integration. `build-tools` compiler internals and unrelated vendor/provider internals out of scope. | +| `rust/` | Limited: native admission and platform/dependency interface; Rust internals and OS sandbox implementation not audited. | +| `scripts/` | Audited: relevant binding, guard, indexing, and smoke/validation entrypoints, not all utilities. | +| `sdk/` | Audited: run/template dispatch, tools and hook evidence, memory and ACP, related test coverage. | +| `test/` | Audited: selected owned fixtures and what they prove; other fixtures out of scope. | + +Root manifests, `openbuff.json.example`, and Bun/test setup were consulted where relevant. Untracked/ignored local-only config, credentials, build/dependency directories, runtime state, logs and caches were out of scope (including `.aws`, `.codex`, `.idea`, `.omx`, `.openbuff`, `.tmp`, `debug`, `e2e-traces`, `node_modules`, `scratch-logs`, `tmp`, and `web`). The derived CLI bundle was read only to compare counts and tool surfaces. + +## Verification performed by the audit lead + +Bun 1.4.4 with `--no-env-file --no-install test --isolate`: **1,140 passed, zero failed across 52 explicitly selected files**. This total does not include overlapping shard runs. Suites cover declarations/reachability, model tool disclosure, handoffs, spawn jobs and permission boundaries, index/recall and memory/strict reads, MCP filtering/execution, edit/repair, hook/targeted validation, source-review attestation, deterministic gate transitions, and audit receipts. A filtered Base2 file ran three focused cases (two repeat-finding cases, one mode opt-out). The audit also ran targeted generator/capability probes for the reported writer refusals, missing plan/decision tools and no-hooks green result. No external provider, full monorepo suite, published artifact workflow, native sandbox run, or real UI smoke was executed by the audit lead. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/TOOL-MATRIX.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/TOOL-MATRIX.md new file mode 100644 index 0000000000..6fe3ad6907 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/TOOL-MATRIX.md @@ -0,0 +1,72 @@ +# Shipped agent tool matrix + +Snapshot: 6d5364de3. Extracted from 49 TypeScript definitions and cross-checked against the local generated CLI bundle. Lists effective initial built-ins (including derived structured output/progressive disclosure), declared programmatic tools, mode ceiling, and child allowlists; not a live permissions or provider test. Tools may appear in both the model and programmatic columns. Synthetic direct spawn tools, optional custom/MCP and mailbox substitutions, path/scope/plan restrictions, provider routes, and host/OS/tool dependencies are applied later. + +## Default root: `base2` + +- Initial model tools (23): `ask_user`, `check_background_agent`, `check_job`, `code_search`, `find_references`, `glob`, `go_to_definition`, `hover_type`, `list_directory`, `list_jobs`, `query_index`, `read_files`, `read_logs`, `read_outline`, `read_subtree`, `recall_context`, `skill`, `spawn_agents`, `suggest_followups`, `tool_load`, `tool_search`, `workspace_symbol`, `write_todos` +- Additional loadable tools (19): `code_action`, `edit_3d_asset`, `edit_transaction`, `evaluate_audit_coverage`, `extract_symbol`, `get_affected_tests`, `get_build_targets`, `get_change_review_bundle`, `get_task`, `inspect_3d_asset`, `inspect_codebase_structure`, `inspect_environment`, `inspect_feature_completeness`, `inspect_workspace`, `kill_job`, `read_image`, `rename_symbol`, `render_3d_preview`, `run_targeted_validation` +- Generator tools (8): `get_affected_tests`, `get_build_targets`, `get_change_review_bundle`, `git_status`, `inspect_codebase_structure`, `inspect_environment`, `run_file_change_hooks`, `spawn_agent_inline` +- Spawn allowlist (38): `accessibility-reviewer`, `architect`, `basher`, `browser-use`, `code-reviewer`, `compatibility-reviewer`, `context-pruner`, `debugger`, `dependency-manager`, `dependency-reviewer`, `doc-writer`, `docs-architect`, `editor`, `evaluator`, `file-picker`, `general-agent`, `git-committer`, `incident-coordinator`, `integration-agent`, `knowledge-retriever`, `knowledge-reviewer`, `librarian`, `memory-manager`, `migration-reviewer`, `performance-specialist`, `product-reviewer`, `release-manager`, `reliability-reviewer`, `repair-editor`, `researcher-docs`, `researcher-web`, `review-triage`, `security-reviewer`, `synthesizer`, `test-writer`, `thinker`, `tmux-cli`, `ux-visual-reviewer` + +## Other roots (differences from `base2`) + +| Agent | Initial model tools | Additional loadable tools | Generator tools | Spawn allowlist | +|---|---|---|---|---| +| `base-deep` | Same | Same | Same | Same | +| `base-deep-evals` | − `ask_user` | Same | Same | Same | +| `base2-evals` | − `ask_user` | Same | Same | Same | +| `base2-execute-plan` | Same | + `run_terminal_command` | Same | Same | +| `base2-fast` | − `write_todos` | Same | Same | − `editor`, `repair-editor`, `thinker` | +| `base2-fast-no-validation` | − `write_todos` | Same | Same | − `editor`, `repair-editor`, `thinker` | +| `base2-plan` | + `create_plan`, `update_plan_status`; − `write_todos` | − `code_action`, `edit_3d_asset`, `edit_transaction`, `extract_symbol`, `kill_job`, `rename_symbol`, `run_targeted_validation` | Same | − `dependency-manager`, `doc-writer`, `editor`, `git-committer`, `repair-editor`, `synthesizer`, `test-writer`, `tmux-cli` | + +Every root emits the generic `spawn_agents` surface; identical tool permissions do not imply identical prompts or validation policies. + +## Other shipped definitions + +| Agent | Model tools | Generator tools | Child allowlist | Definition | +|---|---|---|---|---| +| `accessibility-reviewer` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/accessibility-reviewer.ts` | +| `architect` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/architect.ts` | +| `basher` | `run_terminal_command` | `set_output` | — | `agents/basher.ts` | +| `browser-use` | `add_message`, `browser_logs`, `read_image`, `set_output` | — | — | `agents/browser-use/browser-use.ts` | +| `code-reviewer` | `code_search`, `read_files`, `set_output` | — | — | `agents/reviewer/code-reviewer.ts` | +| `compatibility-reviewer` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/compatibility-reviewer.ts` | +| `context-pruner` | `set_output` | — | — | `agents/context-pruner.ts` | +| `debugger` | `code_search`, `git_status`, `read_files`, `read_outline`, `run_terminal_command` | — | — | `agents/debugger/debugger.ts` | +| `dependency-manager` | `read_files`, `run_terminal_command`, `write_file` | `edit_transaction`, `inspect_environment`, `read_files`, `set_output`, `write_file` | — | `agents/dependency-manager/dependency-manager.ts` | +| `dependency-reviewer` | `code_search`, `get_build_targets`, `get_change_review_bundle`, `get_task`, `inspect_environment`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/dependency-reviewer.ts` | +| `directory-lister` | `list_directory` | `set_output` | — | `agents/file-explorer/directory-lister.ts` | +| `doc-writer` | `edit_transaction`, `read_files`, `read_outline`, `read_subtree`, `set_output` | — | — | `agents/doc-writer/doc-writer.ts` | +| `docs-architect` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/docs-architect.ts` | +| `editor` | `edit_transaction`, `read_files`, `read_outline` | `set_output` | — | `agents/editor/editor.ts` | +| `evaluator` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_codebase_structure`, `inspect_feature_completeness`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/evaluator.ts` | +| `file-lister` | `query_index`, `read_subtree` | — | — | `agents/file-explorer/file-lister.ts` | +| `file-picker` | `set_output`, `spawn_agents` | — | `file-lister` | `agents/file-explorer/file-picker.ts` | +| `general-agent` | `code_search`, `glob`, `list_directory`, `query_index`, `read_files`, `read_outline`, `read_subtree`, `set_output`, `spawn_agents`, `task_completed`, `write_audit_findings` | `spawn_agent_inline` | `context-pruner`, `file-picker`, `researcher-docs`, `researcher-web` | `agents/general-agent/general-agent.ts` | +| `git-committer` | `code_search`, `git_branch`, `git_status`, `read_files`, `read_outline`, `run_terminal_command` | — | — | `agents/git-committer/git-committer.ts` | +| `glob-matcher` | `glob` | `set_output` | — | `agents/file-explorer/glob-matcher.ts` | +| `incident-coordinator` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `run_terminal_command`, `set_output` | — | — | `agents/specialists/incident-coordinator.ts` | +| `integration-agent` | `code_search`, `get_affected_tests`, `get_build_targets`, `get_change_review_bundle`, `get_task`, `inspect_environment`, `inspect_workspace`, `read_files`, `read_outline`, `run_terminal_command`, `set_output` | — | — | `agents/specialists/integration-agent.ts` | +| `knowledge-retriever` | `glob`, `list_directory`, `read_files`, `read_outline`, `set_output` | — | — | `agents/memory/knowledge-retriever.ts` | +| `knowledge-reviewer` | `glob`, `list_directory`, `read_files`, `read_outline`, `set_output` | — | — | `agents/memory/knowledge-reviewer.ts` | +| `librarian` | `run_terminal_command`, `set_output` | — | — | `agents/librarian/librarian.ts` | +| `memory-manager` | `set_output`, `spawn_agents` | — | `knowledge-retriever`, `knowledge-reviewer` | `agents/memory/memory-manager.ts` | +| `migration-reviewer` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/migration-reviewer.ts` | +| `performance-specialist` | `code_search`, `get_build_targets`, `get_change_review_bundle`, `get_task`, `inspect_environment`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/performance-specialist.ts` | +| `product-reviewer` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_codebase_structure`, `inspect_feature_completeness`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/product-reviewer.ts` | +| `release-manager` | `code_search`, `get_affected_tests`, `get_build_targets`, `get_change_review_bundle`, `get_task`, `inspect_environment`, `inspect_workspace`, `read_files`, `read_outline`, `run_terminal_command`, `set_output` | — | — | `agents/specialists/release-manager.ts` | +| `reliability-reviewer` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/reliability-reviewer.ts` | +| `repair-editor` | `edit_transaction`, `read_files`, `read_outline`, `read_subtree` | `set_output` | — | `agents/editor/repair-editor.ts` | +| `researcher-docs` | `read_docs`, `set_output` | — | — | `agents/researcher/researcher-docs.ts` | +| `researcher-web` | `set_output`, `web_search` | — | — | `agents/researcher/researcher-web.ts` | +| `review-triage` | `set_output` | — | — | `agents/reviewer/review-triage.ts` | +| `security-reviewer` | `code_search`, `git_status`, `read_files`, `read_outline`, `set_output` | — | — | `agents/security-reviewer/security-reviewer.ts` | +| `synthesizer` | `glob`, `list_directory`, `read_files`, `set_output`, `write_file` | — | — | `agents/synthesizer/synthesizer.ts` | +| `test-writer` | `edit_transaction`, `read_files`, `read_outline`, `set_output` | — | — | `agents/test-writer/test-writer.ts` | +| `thinker` | `read_files` | `set_output` | — | `agents/thinker/thinker.ts` | +| `tmux-cli` | `add_message`, `read_files`, `run_terminal_command`, `set_output` | — | — | `agents/tmux-cli.ts` | +| `ux-visual-reviewer` | `code_search`, `get_change_review_bundle`, `get_task`, `inspect_workspace`, `read_files`, `read_outline`, `set_output` | — | — | `agents/specialists/ux-visual-reviewer.ts` | + +Notes: `file-lister` is reached via `file-picker`; `context-pruner` is internal/inline. `directory-lister` and `glob-matcher` are intentionally not in the root catalog (their native tools are). A read-only plan remains read-only even if terminal-capable children are declared. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/context-retrieval.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/context-retrieval.md new file mode 100644 index 0000000000..74532d27d5 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/context-retrieval.md @@ -0,0 +1,31 @@ +# Retrieval shard — agent/tool coverage + +**Snapshot:** `6d5364de3` (verified). Static source and test inspection only; no tests, agents, tools against live targets, or provider/network calls executed. Memory persistence is out of scope. + +**Verdict:** Yes, for most work if the orchestrator sends a self-contained prompt and the right path/version/source selectors, joins the child, checks its outcome, and verifies discovery candidates. The chain is incomplete on ACP/bare SDK index dispatch and lossy at file-picker’s nested discovery boundary. A scoped brief is not necessarily a filesystem authorization boundary. + +## Material findings + +1. **P2 — ACP drops the CLI’s `query_index` implementation; the bare SDK advertises but does not implement this client tool.** (Correctness, API, error handling.) CLI registers the index as a client override (`cli/src/utils/codebuff-client.ts:235–242,269–316`). `ManagedOpenbuffClient.run` passes ACP's run options through to `super.run` (`cli/src/utils/codebuff-client.ts:92–114`); the ACP bridge supplies an `overrideTools` object containing only `ask_user` (`sdk/src/serve/bridge.ts:864–908`), and `OpenbuffClient.run` shallow-merges the run over client options (`sdk/src/client.ts:60–69`). With no override, the runtime forwards to the SDK (`packages/agent-runtime/src/tools/handlers/tool/query-index.ts:135–141`), whose native client-tool switch has no `query_index` implementation and returns the generic not-implemented error (`sdk/src/run.ts:5579–5622,6329–6350`). Native SDK repository-context preparation and the MCP server's injected index (`sdk/src/run.ts:3358–3364`; `sdk/src/mcp/server.ts:837–892`) are separate paths and do not repair dispatch. **Risk:** root and nested discovery degrade to tree/search while graph modes appear callable; supplying an unrelated per-run override can cause the same loss. **Fix:** preserve client index binding when adding ACP elicitation; ideally install a canonical SDK query handler using the admitted project/config/index, with tested typed disabled/unavailable results for unsupported host views. Test root and joined picker through the real SDK and ACP bridge, with and without a host index. + +2. **P2 — Scoped picker loses live fallback candidates for nested directories.** (Correctness, tests.) The subtree engine renders a non-root target starting at that directory’s **basename**, e.g. `backend/file.ts` for `packages/backend` (`packages/agent-runtime/src/tools/handlers/tool/read-subtree.ts:115–143,424–438`). The lister parses `entry.printedTree` without using `entry.path` and then applies the original full-directory filter (`agents/file-explorer/file-lister.ts:128–165,219–224,285–313`). When the index is disabled, unimplemented, building or empty, an otherwise healthy live subtree can therefore contribute no candidates. The one-step model fallback is not equivalent to preserving actual paths. **Fix:** return and consume structured project-relative paths from the subtree, or rebase parsed paths with the canonical source directory; test index-disabled nested and sibling scopes with the actual subtree engine, not just the one-level fixture (`agents/__tests__/file-lister.test.ts:32–72`). + +3. **P2 — File-picker’s text boundary drops valid paths and buries omissions.** (Correctness, error handling, state, performance.) The lister unconditionally follows its index query with a subtree scan, combines candidates despite status/truncation, and returns newline text restricted to eight (`agents/file-explorer/file-lister.ts:167–219,225–313`). Picker discards the child receipt before parsing (`agents/file-explorer/file-picker.ts:86–93`; actual spawn envelope at `packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:1228–1234,1267–1273`). The parser rejects extensionless files such as `Dockerfile`, unquoted spaces (the deterministic producer emits bare paths), non-ASCII paths, and even `files/example.ts` because its prose-prefix test matches `files/` (`agents/file-explorer/file-picker.ts:153–189`). No candidates/error yields prose only, not the declared structured receipt, and successful output holds only paths and basename “summaries” (`:298–309,343–364`). **Risk:** misleadingly sparse shortlist or unclear failure; no way to distinguish genuinely empty discovery from stale/truncated retrieval or a failed child. The two caps and directory-scope semantics are reasonable; silent loss is not. **Fix:** use a typed lister → picker receipt carrying canonical relative candidates, source/provenance and `empty`/`partial`/`failed` diagnostics; preserve the joined receipt outcome and distinguish cap omissions. Use a bounded live fallback to verify stale/partial index candidates; do not rescan full trees when only a narrow gap needs closing. Add real nested spawn coverage for no candidates, unavailable/stale index, truncated subtree, mixed filenames and failed child. Existing picker generator fixtures cover malformed text, traversal, scope and caps, but specifically expect prose-only errors (`agents/__tests__/file-picker.test.ts:160–185,443–484,485–525,675–749,811–923`). + +4. **P2 — `general-agent.params.filePaths` is not a reliable pre-read contract.** (Correctness, API.) The advertised concrete-path pre-read uses a basename heuristic plus a short allowlist (`agents/general-agent/general-agent.ts:34–52,150–189`). A valid dotfile like `.gitignore` or an extensionless script is sent to `read_subtree`, which for a file returns variable names/provenance, not source bytes (`packages/agent-runtime/src/tools/handlers/tool/read-subtree.ts:184–198,424–430`); a dotted directory accidentally supplied through the documented compatibility path goes the other way. The model *can* recover using `read_files`/search, but only after recognizing the missing evidence. **Fix:** make `directoryPaths` explicit and use typed `read_files` per requested file with an actual directory classification/fallback for legacy mixed lists. Surface failed or partial initial reads in the brief/result and test dotfiles, extensionless files, dotted directory paths and bounded rereads before synthesis. + +5. **P2 — Librarian can announce a clone it did not obtain and misreport custody.** (Correctness, state, error handling, security.) Clone success is rejected only for a *present JSON part* with a nonzero/absent exit code; absent/non-JSON results fall through to “Clone complete” (`agents/librarian/librarian.ts:168–223`). An accepted trailing-slash URL produces `/tmp/librarian-repo-…` via the generator’s fallback name, but cleanup derives the actual repo name after removing the slash and refuses the mismatched path. HTTP is accepted by the generator, while the policy's clone exception and cleanup require HTTPS (`agents/librarian/librarian.ts:133–165`; `sdk/src/tools/terminal-command-policy.ts:2369–2380`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:1916–1953`). The retain branch also stamps `cloneRetained: true` even on an unsuccessful spawn without a trusted clone directory (`:1909–1918`). Plan roots advertise the agent (`agents/base2/base2.ts:557–579`), but plan downgrades to read-only and cannot use the librarian clone exception (`packages/agent-runtime/src/tools/handlers/tool/run-terminal-command.ts:83–97`); this is a routing problem, not a reason to weaken plan policy. **Fix:** canonicalize once; have a host-owned clone operation claim an exclusive temp directory and issue a custody receipt before exploration; preserve explicit failures and key cleanup/retention on that receipt rather than banner text. Mark unavailable in plan and route public-document tasks to researchers instead. Test no result, trailing slash, denied/failed clone with retain, and cleanup failure. The existing cleanup tests exercise supplied clone banners, not allocation or successful clone dispatch (`packages/agent-runtime/src/__tests__/librarian-cleanup.test.ts:29–83`). + +6. **P3 — Version-specific docs briefs cannot pin what `read_docs` retrieves.** (API, dependency, correctness.) Researcher-docs gets only prompt text and is told to call `read_docs` only once (`agents/researcher/researcher-docs.ts:9–38`). The tool accepts title/topic/token count, not version, exact library ID, or branch (`common/src/tools/params/tool/read-docs.ts:7–31`), and Context7 fetches the top title-ranked result, exposing alternatives only after the choice (`packages/agent-runtime/src/llm-api/context7-api.ts:436–465,549–552`). **Risk:** a clearly scoped old API question can yield current-branch evidence; missing credentials or ambiguity require a second spawn. **Fix:** support verified exact candidate/version selection and bounded retry, or make the root deterministically route wrong-branch/auth/ambiguous results to researcher-web with the already-known versioned official URL. Do not add shell or arbitrary web to docs just to work around missing selectors. Context7 tests confirm title ranking and surfaced alternatives, not a pinned version (`packages/agent-runtime/src/llm-api/__tests__/context7-api.test.ts:205–245`). + +## Verified wiring and coverage boundaries + +| Surface | Effective retrieval and how to scope it | +|---|---| +| Root and nested spawn | Base2 default exposes all six named roles; fast intentionally skips thinker, and base-deep inherits default roster (`agents/base2/base2.ts:535–579`; `agents/base2/base-deep.ts:325–355`). Use prompt/params or a validated versioned handoff; prompt and params enter the child user message (`packages/agent-runtime/src/run-agent-step.ts:2398–2416`; `packages/agent-runtime/src/util/messages.ts:94–103`). History defaults to none without opt-in (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:3582–3626`). Handoff compacts context, narrows model tools and can explicitly grant a closed list of local discovery tools; it does not add shell/web/edit powers (`:385–434,504–624`). Legacy path scopes are advisory within the workspace, not a hard per-child sandbox (`packages/agent-runtime/src/tools/tool-executor.ts:3374–3405`); the strict-project-read SDK boundary deliberately withholds unguarded index/search/subtree (`sdk/src/run.ts:3673–3680`; `docs/agents-and-tools.md:107–111`). | +| File-picker family | `file-picker`: `spawn_agents,set_output`; one `file-lister` (not root catalog) with `query_index,read_subtree` and no children. `directory-lister`/`glob-matcher` are not additional picker children (`agents/file-explorer/file-picker.ts:57–61,235–246`; `agents/file-explorer/file-lister.ts:33–39`; `agents/__tests__/roster-drift.test.ts:45–53`). General-agent → picker → lister fits the default three child levels; deeper nesting fails with a typed depth guard (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:4275–4286`; `packages/agent-runtime/src/__tests__/spawn-depth.test.ts:55–62`). | +| General-agent / thinker | Shipped general-agent has `spawn_agents,query_index,read_files,read_subtree,read_outline,glob,list_directory,code_search,task_completed,write_audit_findings,set_output` plus hidden `spawn_agent_inline` for context-pruner. It can spawn picker and both researchers (`agents/general-agent/general-agent.ts:108–137,372–385,524–529`). Give exact files/dirs, required questions and unresolved-evidence criteria. Thinker has only `read_files`, hidden `set_output`, no children or inherited history (`agents/thinker/thinker.ts:11–66`); send the decision, verified evidence and paths, constraints, options and unknowns. Its STEP loop supports reads before harvesting multi-fragment text (`:107–207,269–311`; `packages/agent-runtime/src/__tests__/loop-agent-steps.test.ts:952–1026`). Limited discovery is intentional. | +| Read/search/index | `read_files` goes through SDK actor-aware file requests, explicit per-block size errors and omitted-symbol recovery; `read_subtree` is an engine inventory, live where possible, capped (5,000 nodes) and labeled cached/partial when appropriate; it is not a byte read (`sdk/src/run.ts:4208–4274`; `packages/agent-runtime/src/tools/handlers/tool/read-files.ts:504–510,660–699`; `packages/agent-runtime/src/tools/handlers/tool/read-subtree.ts:30,101–110,155–198,496–572`). SDK `code_search` uses bundled ripgrep under the host view, flag filtering, timeout/partial output; non-host process views require an override (`sdk/src/run.ts:5987–6005`; `sdk/src/tools/code-search.ts:202–281,333–390`). CLI index waits up to two seconds, can serve labeled building/stale/degraded/coverage-limited results, and verifies evidence only via subsequent reads. Indexer uses code-map for parse/graph metadata, with a pinned tree-sitter/grammar dependency and coverage tests; repo-map helpers are a distinct public API, not a replacement for dispatched index (`cli/src/utils/codebuff-client.ts:269–370`; `packages/indexer/src/index-manager.ts:553–645,1180–1270`; `packages/indexer/src/metadata-indexer.ts:4–11`; `packages/code-map/package.json:29–31`; `packages/code-map/__tests__/all-language-wasm.test.ts:35–52`; `docs/agents-and-tools.md:1023–1041`). MCP’s separate bounded projection omits `relatedFiles` and `indexedHash` even when supplied; do not treat a same-named MCP result as the full CLI evidence packet (`sdk/src/mcp/server.ts:866–892`; `cli/src/utils/codebuff-client.ts:321–347`). | +| Public web / docs / clone | Docs uses only `read_docs,set_output`, no children; `CONTEXT7_API_KEY` is separate from BYOK provider credentials, with typed auth/rate-limit/timeout and cancellation results (`packages/agent-runtime/src/llm-api/context7-api.ts:118–125,160–233,374–392`; `packages/agent-runtime/src/tools/handlers/tool/read-docs.ts:61–143`). Web uses `web_search,set_output`, no children: engine routes rendered actions to SDK, `auto` falls back only on unavailability for URL calls, required browser does not; `search` is static. Search leads are not source evidence. Direct fetch uses public address pinning/redirect revalidation and size caps; static complete results use short run-local cache with refresh and cooldown. Output validation binds citations to observed URLs, text coverage and retained artifacts, not semantic entailment (`packages/agent-runtime/src/tools/handlers/tool/web-search.ts:145–267,289–405`; `packages/agent-runtime/src/tools/handlers/tool/web-search-utils.ts:48–151`; `sdk/src/run.ts:5962–5971`; `packages/agent-runtime/src/tools/handlers/tool/research-evidence.ts:96–167`; `packages/agent-runtime/src/tools/handlers/tool/set-output.ts:1063–1076`). Renderer needs pinned agent-browser and compatible Chromium isolation (`docs/agents-and-tools.md:324–356`). Librarian instead reads a GitHub checkout through `run_terminal_command,set_output`; neither a general HTTP fetcher nor a substitute for versioned documentation (`agents/librarian/librarian.ts:13–31,79–106`). | + +Parent should read structured `value` **plus** `agentReceipt.status/outcome/runOutcome`, not treat text or a path list as proof. Oversize child results can carry a joined recoverable artifact or explicit persistence failure (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:1406–1490,2688–2867,4638–4648`). Further regression surfaces inspected: stale/refresh index tests (`packages/indexer/src/index-manager.test.ts:135–157,229–249`), MCP invoke/response budget (`sdk/src/__tests__/mcp-server.test.ts:424–430,853–883`), and agent wire/harvest checks cited above. No dependency upgrade or additional role permissions recommended by this shard. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/end-to-end.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/end-to-end.md new file mode 100644 index 0000000000..b27c7a2005 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/end-to-end.md @@ -0,0 +1,65 @@ +# Cross-cutting evidence: default/release lifecycle + +HEAD `6d5364de3`. Static inspection only: no tests, live providers, or source edits. Scope: `evals/`, `agents/e2e/`, targeted SDK tests and packaging checks, smoke scripts, docs, `.github/`, `openbuff*.example`, `test/fixtures/body/`, and the shipped broad-audit contracts. Confidence below refers to checked-in assertions and wiring, not current green runs. + +**Verdict:** Strong offline evidence at individual boundaries; no checked-in default/release gate found that ties **actual discovery → retained constraint/source evidence → confirmed mutation → real validation hooks → snapshot-bound review → finalization** to one shipped `base2` run. Default gate order is hooks before final code review, and repairs can loop through both. Build, parser, prompt, and historical fixture receipts do not compose into that assertion. + +## Strongest regression evidence + +| Phase or outcome | What the test really proves | +|---|---| +| Discovery | `agents/e2e/file-explorer.e2e.test.ts:168,252,351` exercises shipped file-lister plus `read_subtree` with mocked inference, including narrowing. `test/fixtures/body/packed-language-assets.ts:76,176,199,236` does stronger installed CJS/ESM and extracted Linux CLI query/index asset checks, including degradation; it uses a custom read-only agent, not default `base2`. | +| Context and restart | `agents/e2e/context-pruning-threshold.e2e.test.ts:320,402–428` requires semantic compaction, exact path and constraint survival, provenance, ordering and budget; discovery is injected at lines 326–355. `sdk/src/__tests__/b13-memory-restart.test.ts:7–24` drives actual tool results through three production compactions, SQLite, a fresh request and archive recall, with exact counts, factual scoring and zero external provider requests. `evals/compaction-retention/scenario.test.ts:743,766,1097` pins blockers and review fingerprints across context pressure. | +| Mutation and recovery | `sdk/src/__tests__/run-mutation-dispatch.test.ts:506,585,1074,1209,1267` distinguishes refused from applied receipts, confirms surviving paths, authority scope and observers. `packages/agent-runtime/src/__tests__/edit-transaction-multi-file-recovery.e2e.test.ts:144–272,350–386` checks actual recovery, preserved bytes and fresh-read requirements. `test/fixtures/body/workspace-edit-sequential.ts:108–157` checks the exact executed file census and input hashes; it is a targeted evidence runner, not a default turn. | +| Hooks, review and finalization | `agents/e2e/gate-lifecycle.e2e.test.ts:144–279,624,741,979` checks blocked → repair → revalidation/review, cumulative scope, single finalization, and stale reviewer identity. `agents/e2e/gate-aux-ordering.e2e.test.ts:289,806,1272,3548` covers auxiliary order, crash, per-file drift and no credit for an empty bundle. These feed synthetic results to the real generator (`docs/testing.md:283–296`). `sdk/src/__tests__/run-host-execution.test.ts:1350–1556` executes local Bun/tsc and checks actual receipt reuse across actors with and without supervision and validation; custom agents, not the `base2` gate. | +| Exceptional validation and permissions | `sdk/src/__tests__/run-targeted-validation.test.ts:159–189,219,304,419–495` asserts missing context, re-attestation refusal, stale snapshots, failed and skipped results without invented assurance; `run-dynamic-review.test.ts:71–105` separates success-like stdout from exit and dirty-snapshot failure. `run-host-execution.test.ts:274,437,472,526–581` proves denial has no launch/state effect and a command with real writes can advance state despite exit failure. `plan-terminal-enforcement.test.ts:127–187,273–305` proves no availability/override widening, usable reads and a positive execute control. Paths in this row after the first are also under `sdk/src/__tests__/`. | +| Cancellation, deadline, unsupported, route, concurrency | `sdk/src/__tests__/run-host-execution.test.ts:717–793,822–960,1177` checks original expiry, no setup on expired/invalid bindings, caller cancel vs deadline, journal agreement and detached child expiry. `sdk/src/__tests__/run-handle-event.test.ts:504–562` asserts the exact unsupported SDK result (mocked callback). `sdk/src/__tests__/run-model-override.test.ts:309,323,355–364` proves loopback route isolation and zero requests/no fallback for invalid selection; `sdk/e2e/readme-examples.test.ts:217–230,327` proves missing config fails before a request. `sdk/src/__tests__/check-job-execution-context.test.ts:424–552` proves one settlement dispatch, cursor ordering and per-waiter cancellation/deadline isolation. | + +## False confidence and coverage gaps (eight domains) + +| Domain / severity / confidence | Evidence, risk and fix | +|---|---| +| **Testing / High / High** | `.github/workflows/ci.yml:291–306,367–373`, `agents/package.json:8–9`, and `.github/workflows/nightly-e2e.yml:65–69`: ordinary agents CI runs `__tests__` only; deterministic gate, editor-contract and pruning E2E are on a separate schedule. “Default CI” in `agents/e2e/context-pruning-threshold.e2e.test.ts:254` is misleading. CLI release-source tests (`.github/workflows/cli-release-prod.yml:33–44`) and installed smoke (`.github/workflows/cli-release-build.yml:418–471,610`; `cli/scripts/smoke-binary.ts:329–356`) verify different things: startup, native assets and boot, not a default agent workload. Gate a scripted loopback scenario using the extracted CLI and packed SDK, real shipped agents and tools, no external requests, and terminal-event plus disk/receipt oracles. Run the deterministic agent E2E subset in ordinary PR CI as a faster layer. | +| **Correctness / Medium / High** | `agents/e2e/editor-orchestrator-contract.e2e.test.ts:94–129,143–183` substitutes a schema that always accepts, a fabricated edit receipt and synthetic CLI events; `gate-lifecycle.e2e.test.ts:170–193` injects results. A broken editor brief or dispatch can leave both green. Replace the accepting stub with the shipped schema and add a rejected brief; carry a real tool-result ID and postimage through the parent gate, rather than inferring integration from matching shapes. Targeted validation/dynamic checks are optional evidence, not finalization credit (`docs/agents-and-tools.md:195–198,217–228`). | +| **State mutation / Medium / High** | `agents/e2e/context-pruning-threshold.e2e.test.ts:326–355,410–428` proves retained text, not that an editor relies on it or refreshes stale read authority. `agents/e2e/reviewer-spawn-conditions.e2e.test.ts:819` and `sdk/src/__tests__/run-mutation-dispatch.test.ts:506` defend the separate ends. Join a stale read after compaction with refused edit/no observer progress, fresh read and applied edit; then drift the postimage and require renewed validation/review. | +| **Error handling / Medium / High** | `sdk/e2e/workflows/error-recovery.e2e.test.ts:52–68,94–116` can pass with no error on an invalid agent and with any events on a normal completion in the cancellation case. The SDK helper does **not** skip and installs mocks (`sdk/e2e/utils/get-api-key.ts:8–17`). Separately, all `base-deep` live cases are under `RUN_BASE_DEEP_SLOW_E2E` and can return without assertions on auth rejection (`agents/e2e/base-deep.e2e.test.ts:20–21,74–86,228–256`); nightly only sets the now-unused pruning flag. Use a rendezvous rather than a timer, assert exact terminal cause, no late effects and cleanup, and distinguish skipped/no-auth from exercised. `scripts/openbuff-smoke.ts:11–12,32–51` is a live-provider echo-by-substring probe, not a no-tool or completed-run assertion. | +| **Security / Medium / High** | `scripts/harness-smoke.mjs:3–5,42–52` checks classification only. Actual Linux OS enforcement is separately opt-in, not proven by the absence of a launch in a source test (`sdk/src/__tests__/plan-terminal-native.integration.test.ts:22–29,93–94`; `docs/testing.md:183–207`). Add a packed default permission lane with paired allowed/denied controls and effect/cleanup checks, an untrusted hook fragment and no ambient credentials. Keep non-native cells explicitly unproven, not passed by classifier output. | +| **Performance / Medium / High for test limits** | `sdk/e2e/streaming/concurrent-streams.e2e.test.ts:34–69,110–147` has a useful output-isolation oracle but mocks the provider and does not overlap default edit/review actors. `sdk/src/__tests__/concurrency.test.ts:88,181,284` and `evals/buffbench/__tests__/agent-runner.test.ts:519,556,573` cover bounded parallelism and dependent checks locally. Add bounded overlapping default turns with distinct run/attempt IDs, actual effects and receipts, cancellation of one waiter, and measured max active work/settlement; avoid timing-only assertions. | +| **Dependency hygiene / Medium / High** | `.github/workflows/sdk-release.yml:91–94` runs `verify`, which rebuilds and smoke-checks dist, installs compatibility deps with `npm install` and tests dist copies or a file reference (`sdk/scripts/verify.ts:20–28,84–123,154–171`). Those are meaningful consumer checks but not the published tarball's behavior; the compatibility installs are not lock-enforced despite tracked locks. Prefer `npm ci` for compatible fixtures and an isolated install of the exact publish tarball. `test/fixtures/body/packed-language-assets.ts:16–34,76–95,176–194` is the stronger Linux asset precedent, not multi-platform acceptance. | +| **API / Medium / High** | `openbuff.json.example:2–8`, `openbuff.d.example/routes.json:18–45`, `providers.json:167–170` in that directory: copied defaults target AgentRouter, not the named route examples; it is not a key-free runnable fixture. `hooks.json` does load via implicit sibling-directory discovery (`sdk/src/provider-config.ts:1189–1202`), but loading is not trust/permission or hook success. README tests use a separate fixture config (`sdk/e2e/readme-examples.test.ts:143–151`). Add a copy-from-repo config loading/resolution census for shipped roles, missing child routes, and trusted vs untrusted hooks, with a locally substituted transport; assert intended public error shapes and zero unauthorized effects. | + +Buffbench is complementary: `.github/workflows/eval-pr-subset.yml:9–26,61–65,94–132` omits most SDK/CLI implementation paths, falls back to dry-run without keys, and compares only when the live run succeeds. The dry-run validates schema/task/agent/static prompt (`evals/buffbench/main-nightly.ts:120–164`); the live suite uses three score tasks (`:44–53`), and a measured run without a baseline can pass (`evals/buffbench/regression-gate.ts:319–329`). Do not label this a release lifecycle gate. The deterministic retrieval metric tests (`evals/buffbench/__tests__/retrieval-flow-metrics.test.ts:8,78`) and runner cancellation/check DAG tests (`agent-runner.test.ts:235,478,519,556,573` in the same directory) are useful but not shipped workflow assertions. + +## Broad-audit contract mismatches (bounded) + +- **Correctness / Medium / High — source inspection is not readiness.** `agents/guides/broad-audit.md:12` and the compiled prompt source `common/src/constants/prompt-sections.ts:121` say unreachable, unimplemented or missing failure-state coverage blocks a complete audit. `sdk/src/services/audit-intelligence.ts:579–615` deliberately treats any nonempty, verified in-inventory evidence as structurally eligible; `complete` means source inspection, `readinessComplete` is always false. `sdk/src/__tests__/audit-intelligence.test.ts:697–745` pins precisely that outcome for docs-only partial/unwired/absent cases. Separate inspection eligibility from release readiness in prompts and reports. Verification is a caller claim here, not runtime proof of exact reads (`sdk/src/tools/audit-intelligence.ts:150–168`). +- **API / Medium / High — completion on retry is not composable.** `sdk/src/tools/write-audit-findings.ts:186–193` says byte-identical idempotence returns the same receipt; code `:347–378` returns only `alreadyPersisted`, with no structural receipt/hash. The shard completion checker accepts that marker (`agents/general-agent/general-agent.ts:302–347`), while the guide requires the exact structural receipt and forbids reconstructing it. Return the original canonical receipt on a verified byte-identical retry, or add typed recovery from the persisted artifact and test retry → evaluator across the tool boundary. File-picker is correctly discovery-only (`agents/file-explorer/file-picker.ts:43–64`); it cannot supply missing evidence. +- **API / Medium / High — one workflow is prescribed across incompatible lanes.** `agents/patterns/audit-codebase.md:21–23,133–155,164–223,289–294` calls Markdown optional for read-only workspaces but requires writes/`STATUS.md`, instructs synthesis from that directory and ends by requiring artifact path/hash; the risks section also re-requires the legacy map despite `:82–94`. Plan deliberately withholds `synthesizer` (`agents/base2/base2.ts:581–584`, `agents/tool-reachability.test.ts:219–250`); the synthesizer only reads findings glob and can write `AUDIT-REPORT.md` (`agents/synthesizer/synthesizer.ts:47–61`), not read `STATUS.md` as the pattern implies. Spell out execute/durable, plan-only and unwritable lanes; pass compact validated coverage and expected shard IDs as input, not extra read authority. Use one session slug and distinct shard IDs. The synthesizer's prompt restricts one scratchpad, while static patterns span all session slugs; narrow with a trusted handoff and test cross-session denial before calling that property enforced. +- **Testing / Medium / High — pair count is not evidence coverage.** Pattern `:118–129` sets `max(domainCount,5)`; guide `:6–8` permits only 3–4 pairs for that breadth. `evals/buffbench/plan-sharding-signals.ts:535–542,666–702,885–905` counts kinds and distributes pairs round-robin regardless of actual shard scope. The live runner passes the prompt to enable the numeric floor (`run-plan-sharding-eval.ts:105–123`), but an agent count/text mention does not prove a paired discovery result or persisted receipt. Share one rubric and require actual shard IDs/receipt joins, keeping heuristic matrices diagnostic. +- **Security / Medium / High code, untested effects — snapshot and feature read disagree on links.** Inventory includes links and hashes link bytes (`sdk/src/services/audit-intelligence.ts:155–158,180–187`), while feature `safeRead` uses following `statSync/readFileSync` (`:427,449,483–489`) on those same paths; dispatch passes only cwd/scope (`sdk/src/run.ts:6273–6288`). This can classify evidence using bytes not covered by the snapshot, including outside the audit root. Use a confined no-follow source read or skip link content; add owned symlink tests for outside-root and changed-target evidence. +- **Performance / Medium / High code, unmeasured impact.** Each feature/evaluation call reattests via a new synchronous inventory (`sdk/src/tools/audit-intelligence.ts:31–53,71–78,141–144`); the hash reads full bytes and `subsystemMap` copies each growing file array (`sdk/src/services/audit-intelligence.ts:177–225,241–246`). Repeated calls multiply scan work, and the census does quadratic array copying per large subsystem. Accumulate linearly and batch or make re-attestation cancellable with the same freshness guarantee; measure large-scope latency and abort behavior. + +## Focused run for the parent (suggested, not run) + +Use pinned Bun, installed repo deps, an existing up-to-date SDK dist for agent E2E imports, and an isolated credential-free environment; do not enable the live/slow flags. Separate the lanes for attribution. Current names below are repo-root relative. + +```bash +bun --no-env-file --no-install test --isolate \ + ./agents/e2e/file-explorer.e2e.test.ts \ + ./agents/e2e/context-pruning-threshold.e2e.test.ts \ + ./agents/e2e/editor-orchestrator-contract.e2e.test.ts \ + ./agents/e2e/gate-lifecycle.e2e.test.ts \ + ./agents/e2e/reviewer-spawn-conditions.e2e.test.ts +bun --no-env-file --no-install test --isolate \ + ./sdk/src/__tests__/{b13-memory-restart,run-mutation-dispatch,run-host-execution,run-targeted-validation,run-handle-event,check-job-execution-context,plan-terminal-enforcement}.test.ts \ + ./sdk/e2e/readme-examples.test.ts +bun --no-env-file --no-install test --isolate \ + --test-name-pattern 'unroutable override|parallel run overrides' \ + ./sdk/src/__tests__/run-model-override.test.ts +bun --no-env-file --no-install test --isolate \ + ./sdk/src/__tests__/{audit-intelligence,write-audit-findings}.test.ts \ + ./agents/__tests__/general-agent.test.ts ./agents/tool-reachability.test.ts \ + ./evals/buffbench/__tests__/plan-sharding-signals.test.ts +``` + +Add `agents/e2e/gate-aux-ordering.e2e.test.ts` for auxiliary or drift changes, and `evals/compaction-retention/scenario.test.ts` or `evals/buffbench/__tests__/agent-runner.test.ts` when changing those layers. Do not substitute `smoke:openbuff`, live Buffbench, or the opt-in native/packed experiment for this suite. A green run here supports the enumerated seams, not the missing packed default composition test. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/implementation.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/implementation.md new file mode 100644 index 0000000000..36e6d5e5d6 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/implementation.md @@ -0,0 +1,57 @@ +# IMPLEMENTATION — Openbuff agent/tool coverage + +**Snapshot:** HEAD `6d5364de3`. **Verdict:** The ordinary code, docs, and test edit primitives are present, including exact patches and file lifecycle actions. Default mode delegates substantial code edits, fast mode can edit inline, and the debugger intentionally proposes fixes rather than applying them. The gaps are concrete wiring and outcome-contract defects, not missing general-purpose editing agents. No source changes, live provider, package-manager command, browser session, Blender invocation, or worktree mutation was used. Test-writer ownership and general SDK/approval security are sibling-shard scope; this report covers their implementation-side handoffs only. + +## Reachability and pending-to-settled traces + +| Case | Entrypoint, actual declaration, and observable outcome | +| --- | --- | +| Ordinary code or mixed implementation | `agents/base2/base2.ts:537–579,692–715`: default uses `editor` for nontrivial edits; tiny edits may be inline. Fast omits `editor`/`repair-editor` from the advertised roster and uses root `edit_transaction`; `base-deep` inherits the default surface and generator (`agents/base2/base-deep.ts:322–359`) but its prompt also recommends transactions directly. Mode rosters are the advertised surface, not universal permissions: base-agent generic spawn lookup admits registered IDs separately (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:343–367`); plan lineage actually refuses edit tools (`packages/agent-runtime/src/tools/plan-mode-guard.ts:30`, `common/src/tools/plan-mode-policy.ts:46–55`). Runtime validates a concrete editor brief (five labeled fields or equivalent actionable prose) rather than relying on parent history (`spawn-agent-utils.ts:3376–3414`). `editor` declares `read_files`, `read_outline`, `edit_transaction` and hidden `set_output` (`agents/editor/editor.ts:132–136`); it primes its named targets before inference, and its receipt is `blocked`/`partial`/`completed` based on committed paths plus target progress (`:274–292,355–406`). Receipt-backed edits enter base2's pending validation/review set (`agents/base2/base2.ts:1994–2049,13596–13602`); see I8 for one call-input exception. | +| Exact patch/range/write/create/move/delete | `common/src/tools/params/tool/edit-transaction.ts:93–300,442–474` exposes `str_replace`, `structured`, `replace_range`, `rewrite_symbol`, `patch`, `write_file`, `create`, `move`, and `delete` in one bounded transaction; standalone names do not need to be on the editor surface. `patch` is an exact per-existing-file unified diff, not an arbitrary shell patch or a multi-path diff application (`packages/agent-runtime/src/process-edit-transaction.ts:1342–1374`). Complete whole-file reads or confirmed whole after-content can register reusable authority; complete range/window/symbol reads supply scoped `cap.v4`; truncated reads do not grant whole authority (`packages/agent-runtime/src/tools/handlers/tool/read-files.ts:709–748`; `docs/deterministic-edit-system.md:28–95`). In strict mode exact localized replacements can take the bounded unique-match auto-read path; overwrite requires a fresh whole raw basis, whereas range/symbol replacements honor their scoped authority (`edit-transaction.ts:642–671,781–832,848–1009`, same handler directory). Create requires an absent path; delete/move require a fresh whole source basis, and move requires an absent destination (`:887–927,1022–1067`). The handler forwards exact raw before-hashes and absent destination to SDK `changeFiles` (`:1430–1550`; `sdk/src/run.ts:5769–5795`); checked add/delete/move are supported, not shell fallbacks. | +| Edit pending → applied / blocked / uncertain | Native dispatch emits `tool_call`, defers queued same-path work behind the barrier, and emits `tool_start` when ready (`packages/agent-runtime/src/tools/tool-executor.ts:4169–4192`). Handler snapshots after that barrier (`edit-transaction.ts:584–606`) and preflights all content/lifecycle edits before SDK dispatch. Malformed/overlapping/stale preflight is an error or recovery directive with no requested writes; a stale range may relocate only with a unique unchanged raw slice. Same-file disjoint edits compose against original-span provenance (`packages/agent-runtime/src/process-edit-transaction.ts:634–716,860–870`). SDK commit-stage failure is distinct: durable intent/conditional writes allow rollback, partial or unconfirmed acknowledgement; never infer no writes from a dispatch failure (`sdk/src/tools/change-file.ts:602–673,827–846,912–1045`). Only confirmed actions can provide reuse anchors. A handler throw after publication becomes correlated `native_tool_result_error`/`tool_result`, not a successful apply (`tool-executor.ts:4292–4311,4439–4445`). | +| Documentation | `doc-writer` exposes `read_files`, `read_outline`, `read_subtree`, `edit_transaction`, `set_output`; static scope advertises repo-wide reads plus docs-pattern writes; `target_doc_files` is an optional pre-read, not hard write authorization (`agents/doc-writer/doc-writer.ts:16–28,63–95,131–142`). Manual doc-only work can spawn this role (or root can use the transaction); no source change is required to use that path. Automated path: explicit docs intent + eligible pending public-source paths → sequential `spawn_agent_inline` with package-rooted handoff → accept completed/changed with changed files or completed/noop with evidence; otherwise mark reduced assurance and continue (`agents/base2/base2.ts:2518–2540,2738–2874,12567–12578,12650–12652`). At HEAD this automated dispatch has I1. `doc-writer` should not own source comments: its spawner blurb says comments (`doc-writer.ts:11`), but source-comment edits belong to the code editor. | +| Validation/reviewer repair | `repair-editor` inherits editor's transaction and programmatic receipt, adds `read_subtree`, and requires versioned handoff/findings at spawn (`agents/editor/repair-editor.ts:5–26`; `spawn-agent-utils.ts:437–494`). The parent runs hooks; parseable failures enter `repair_loop`, repeated rounds may join debugger first, then send `VF-*` findings and await a repair receipt before rereading Git state and rerunning hooks (`agents/base2/base2.ts:5892–6120`). Absent/incomplete receipt or remaining source failures block; unparseable infrastructure failures can use explicitly reduced assurance (`:6071–6095,6139–6225`). Security, specialist and final reviewer blockers have separate exact-finding repair spawns (`:3183–3249,4573–4647,7155–7224`). Pure test-coverage findings go to `test-writer`, not `repair-editor`; mixed/code findings stay on the repair path and validation/re-review stays parent-owned (`:6793–6804,6989,7155`). | +| Diagnosis | `debugger` has `read_files`, `read_outline`, `code_search`, `git_status`, `run_terminal_command`, no edit/spawn tools, and returns the last message. `reproduce_command` is optional and executed before `suspect_files` reads; automatic validation repair supplies suspects and hook output (no executable command) and joins the diagnosis before repair (`agents/debugger/debugger.ts:18–73`; `agents/base2/base2.ts:5934–6051`). Plan execution has separate read-only enforcement. Execute-mode `validation-diagnosis` profile binding has I5; it is not a file editing role. | +| Exceptional dependencies | User-authorized dependency mutation → parent discovers manifest/lockfile, then advertises structured `dependency-manager` (not a retry on missing deps; no normal Basher fallback; `agents/base2/base2.ts:562–563,620–624`). The agent declares model-facing `run_terminal_command`, `read_files`, `write_file`, and programmatic inspect/read/write/transaction/output; in the shipped generator there is **no** model `STEP`, it only constructs the authorized operation and calls tools (`agents/dependency-manager/dependency-manager.ts:61–80,314–435,587–835`). Missing/invalid parameters, manager conflicts and unsupported pairs short-circuit; nonzero exit/flat terminal refusal run rollback, then a structured `schemaVersion: 2` receipt; success/noop is based on snapshots and optional repo guards (I3–I5). SYNC terminal `touchedPaths` is best-effort attribution, not commit authority or a substitute for the parent gate (`sdk/src/tools/run-terminal-command.ts:1259–1308,1621–1628`; `agents/base2/base2.ts:2126–2150`). | +| Browser and asset boundary | Nobody in the five specialist mutation/diagnosis roles exposes browser/asset tools. `browser-use` is a separate child with `browser_logs`, `read_image`, `set_output`, `add_message` and no terminal/source edit tool; parent opts into interactions, default is inspection, plan ancestry overrides the request, handler can refuse before dispatch (`agents/browser-use/browser-use.ts:22–26,37–44,154–163`; `packages/agent-runtime/src/tools/handlers/tool/browser-logs.ts:41–56`). `render_ui` is a root presentation tool, not a source-file mutator; 3D source mutation is separately available via root non-plan tool tiers (`agents/base2/tool-tiers.ts:82–83,114–115,147–150`). `edit_3d_asset` dispatches to the SDK, supports guarded declarative `.blend` operations; stale source hash/guarded-CAS loss refuses, winning commit returns resulting source/artifact evidence and an independent preview outcome (`sdk/src/run.ts:5940–5960`; `sdk/src/tools/3d-assets.ts:1234–1243,1429–1513`). No request to exercise product or external-state mutations. | + +## Findings (file:line → effect → mitigation) + +1. **I1 — High · Correctness / error handling / API / tests: automated `doc-writer` cannot start.** `agents/base2/base2.ts:2804–2813` puts legacy *tool names* `str_replace` and `write_file` in the handoff. `agents/doc-writer/doc-writer.ts:87–93` exposes neither (only edit types inside `edit_transaction`); `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-inline.ts:175–196` calls `deriveSpawnTemplateCapabilities`, whose closed allowlist rejects that widening (`spawn-agent-utils.ts:540–565`) before lease/launch. Offline invocation of the real derivation returned `Handoff attempted to widen doc-writer tool authority with: str_replace, write_file.` The parent treats the missing receipt as failure but marks the writer done and continues (`base2.ts:2827–2860`); later passing hooks can set validation assurance back to `full` (`:5857–5868`), so successful code validation says nothing about actual requested docs. **Mitigate:** derive the handoff from a shared writer tool contract, remove the two legacy names, and separately persist requested-doc delivery failure or block final completion with an actionable retry. Exercise the actual inline spawn boundary; current writer/aux tests assert generator yields and inject a fake success (`agents/__tests__/base2-writer-spawn-rules.test.ts:557–595`, `agents/e2e/gate-aux-ordering.e2e.test.ts:370–400`). + +2. **I2 — Medium · Security / state: writer scopes and batch leases are not hard role boundaries.** `agents/doc-writer/doc-writer.ts:63–85` declares doc-only writes and `agents/editor/repair-editor.ts:15–24` says finding-only edits. The handoff resolves patterns, but empty path lists preserve static scope (`spawn-agent-utils.ts:568–588`); repair's inherited static write scope is absent, and the repair handoff validator checks for a permissions object, not a nonempty write ceiling (`:478–493`). `packages/agent-runtime/src/tools/tool-executor.ts:3355–3410` *intentionally* warns and continues on in-project scope mismatches (escaped paths are separately refused). Thus even a valid nonempty doc/repair handoff does not guarantee doc-only or exact finding paths, including the two ends of a move (`:2458–2465`). This is not a claim of out-of-project access. **Mitigate:** opt shipped scoped writers/repair into a hard write ceiling, require explicit nonempty finding-bound paths for repair, enforce source and destination prior to mutation, and verify receipts against that scope. Preserve advisory legacy behavior for other callers if needed. Test lease/dispatch together, not just narrowed template shape. Static `docs/**` is location-based, not a guarantee every file there is documentation; shared target naming should distinguish executable fixtures from docs if that matters. + +3. **I3 — High · Correctness / state / error handling: dependency failures can become `success`, and rollback restores are not positively attested.** `agents/dependency-manager/dependency-manager.ts:587–604,783–817` checks only flat `errorMessage` or nonzero `exitCode` on the first JSON part. A `native_tool_result_error` or absent/unrecognized result is not positive exit-0 evidence, but falls through; a local mocked generator trace of `inspect_environment → run_terminal_command → native error → guard probes → set_output` produced `success`. The runtime actually emits this envelope on handler failure (`packages/agent-runtime/src/tools/tool-executor.ts:4292–4311`). On detected failure, `dependency-manager.ts:606–622` rewrites old `read_files` text without first verifying the command's postimage; `packages/agent-runtime/src/tools/handlers/tool/write-file.ts:601–648` correctly refuses stale whole-file auth for bytes that were actually changed. Snapshot extraction does not validate whole/raw completeness (`dependency-manager.ts:123–157,419–430`); `restoredFiles` is the attempted snapshot list and `rolled_back` can be inferred from absence of explicit errors (`:699–726`), not confirmed restored hashes. The delete side is better: it requires a whole read plus a per-path applied action in v2 (`:643–687`; `docs/request-flow.md:428–450`). **Mitigate:** validate a typed successful terminal receipt including exit 0; surface denied/unavailable/timed-out/unconfirmed distinctly. Use raw complete manifest/lockfile preimages and attributable postimages; conditional rollback only against the command's postimage, and report independently confirmed restored/failed/unknown paths without overwriting unrelated changes. Include first-created files in post-inventory and add real tool-wire/error-envelope tests (generator tests inject flat terminal/restore results at `agents/__tests__/dependency-manager.test.ts:216–257,258–497`). + +4. **I4 — Medium · Dependency hygiene / API: accepted dependency inputs do not always mean the advertised operation.** `agents/dependency-manager/dependency-manager.ts:458–474` maps a root Yarn update to `yarn upgrade`, which the `dependency-mutation` policy denies (top-level verbs omit `upgrade`; workspace form allows it, `sdk/src/tools/terminal-command-policy.ts:676–692,2329–2357`). The same profile denies the generated Bun repo-guard commands (`dependency-manager.ts:760–783`); both refusals were verified by calling the policy function, not executing commands. Separately uv `update` ignores `packages` and emits a whole-environment `uv sync --upgrade` (`:488–496`), broadening a named update; and success inspects only pre-discovered `snapshotPaths` (`:743–759`), so it can label creation of a new lockfile a no-op when the existing manifest stays unchanged. **Mitigate:** define one tested manager/version/operation/operand matrix shared by generator, policy and receipts, reject ignored selectors/specs or use the precise manager flag, verify post-operation manifest/lockfile/selected packages, and place trusted repository checks in the validation path (not a broad shell allowance). Test supported pairs at actual policy dispatch, not just string generation. + +5. **I5 — Medium · Security / dependency hygiene: the narrower task terminal profiles are not binding on ordinary SDK execution.** `packages/agent-runtime/src/tools/handlers/tool/run-terminal-command.ts:34–47,70–79` forwards the specialist declaration. In execute mode `sdk/src/tools/terminal-profile-bound.ts:20–29,55–63` binds only `read-only`/`workspace-write`; `sdk/src/run.ts:5828–5847` instead passes the captured host profile to `runTerminalCommand` when present (default `workspace-write`, `sdk/src/host-execution.ts:35–36`). The `dependency-mutation` command allowlist and `validation-diagnosis` diagnostic-output limits therefore are not assured by the specialist ID in execute mode; the existing test explicitly pins host precedence (`sdk/src/__tests__/terminal-profile-bound.test.ts:50–53`). The deterministic dependency generator is still restrictive, and host policy/approvals and plan-lineage restrictions still apply; this is not a finding that they can be bypassed. **Mitigate:** compose task-specific policy as an additional bound over the captured host policy for these bundled agents, reconcile I4 before binding it, hide dependency terminal/write tools from the provider, and cover two independent policy denials at SDK dispatch. + +6. **I6 — Medium · Correctness / state: a real validation fix on a diagnostic-only path can be recorded as no finding progress.** In `agents/base2/base2.ts:5995–6035`, a parsed diagnostic file outside the pending set is explicitly writable, but *every* `VF-*` record's `files` is `Array.from(pendingGateFiles)`, not its parsed path. Editor receipt intersects actual committed paths with each finding's `files` (`agents/editor/editor.ts:851–882`); runtime likewise attests against the handoff (`spawn-agent-utils.ts:2665–2690`). A repair confined to that diagnostic-only path fails the ID check and blocks before re-validation (`base2.ts:6055–6095`); conversely a touched pending file can be attributed to unrelated VF IDs, although rerunning hooks still checks correctness. **Mitigate:** use parsed per-finding paths and explicitly linked directly needed files; generate a consistent exact write scope and hook fileset. Mark infrastructure/prose-only diagnostics separately. Test current pending A + fix solely in diagnosed B, then assert finding correlation and rerun against the expanded set. + +7. **I7 — Medium · Performance / error handling / tests: editor action-required retries omit the no-progress bound.** `agents/editor/editor.ts:300–352` bounds repeated identical *transaction recovery* directives and honors an explicit step cap, but the distinct branch for completed steps with targets and zero mutation results always injects `buildActionRequiredDirective` and continues. A model repeatedly returning a read-only/empty completion never reaches the structured `blocked/no_edit_transaction` path, consuming provider requests until a host limit/cancel. **Mitigate:** separately cap identical no-action continuations, reset on new evidence/commit, and terminate with existing failure stage plus pending targets. Existing repeat-exhaustion test exercises the transaction-recovery branch only (`agents/__tests__/editor.test.ts:662–753`); add read-only and empty-completion traces. This is distinct from letting productive edits remain uncapped. + +8. **I8 — Medium · Correctness / state: a direct attempted edit can enqueue unmodified paths as changed.** `agents/base2/base2.ts:14364–14392` scans assistant tool inputs for edit paths without pairing them to the result, then `:2009–2049` marks the inferred paths as edited before git-status observation. Thus a validly submitted direct transaction that later aborts in preflight can enter `GATE: PENDING` for a path with no change; this is different from canonical result-based adoption. Same pattern can retain an attempted path even when the result was a legitimate no-op. **Mitigate:** correlate call ID and authority-backed applied/retained results to populate the touched set; retain attempted paths separately for retry UX; add abort/no-op and mixed partial tests ensuring only retained changes go to hooks/review. Existing positive parent/CLI contract test supplies a canonical applied result (`agents/e2e/editor-orchestrator-contract.e2e.test.ts:81`), and the no-receipt test at `agents/__tests__/base2.test.ts:3472` covers unverified **child** summaries rather than direct failed tool inputs. + +9. **I9 — Low · API / error handling: editor guidance describes obsolete read authority.** `agents/editor/editor.ts:155–158,170–175,206–207` (also inherited by repair) advertises `cap.v3` and implies full-file range can authorize a whole overwrite; `agents/base2/base2.ts:709` repeats the range/whole shortcut. Exact range edits require authenticated `cap.v4` raw basis (`packages/agent-runtime/src/process-edit-transaction.ts:730–747`); a full-looking range still has lines scope, and whole overwrite requires whole raw authority (`packages/agent-runtime/src/tools/handlers/tool/edit-transaction.ts:642–671`, `docs/deterministic-edit-system.md:28–44,129–139`). **Effect:** valid-range reads may be misused for rewrites, producing unnecessary refusals and recovery cycles; the handler is correctly fail-closed. **Mitigate:** source examples from the canonical contract, use `read_files.paths` for whole overwrites, copy the returned capability verbatim, and distinguish no-write preflight aborts from partial/unconfirmed SDK outcomes. Test prompt examples against canonical schema and authorization, not token-prefix wording. + +## Coordination and intentional separation + +- `spawn_agents` awaits earlier work, validates the batch, caps fan-out, acquires leases for declared `handoff.permissions.writablePaths` before launch and joins foreground children (detached work is job-tracked, not implicitly joined): `packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:207–218,251–326,463–526`; inline acquires similarly before `spawn_started` (`spawn-agent-inline.ts:253–264`). Same-project declared overlaps throw; disjoint joined children can run concurrently. Empty/no handoff has no lease; leases are process-local reservations with retained cleanup semantics, not protection against every root/undeclared/out-of-agent writer (`packages/agent-runtime/src/util/workspace-path-leases.ts:36–108,175–206`). If assigning independent edits, give nonempty disjoint ownership including move destinations, then join; keep overlapping/diagnostic repair serial. Per-path ordering and the worktree-scoped SDK cooperative mutation broker protect exact writes from stale preimages, not cross-agent task intent (`docs/architecture.md:52–53`). +- `inspect_workspace` observes existing worktree state (`common/src/tools/params/tool/inspect-workspace.ts:13–20`); operator Workspace Jobs observes/stops jobs in the existing worktree (`cli/src/cli-args.ts:277,320–329`), not a child provisioning/merge flow. `git-committer` expressly forbids creating/removing worktrees (`agents/git-committer/git-committer.ts:76–77`); roadmap records agent/session isolation as pending (`docs/execution/body-roadmap/STATE.md:347`). No advertised editor option allocates a fresh Git worktree or joins/merges its edits. Treat this as a missing isolation feature, not a prerequisite for serial ordinary editing; if implementing isolation, add host-owned creation/cleanup, merge conflict ownership and post-merge validation rather than relying on ad hoc shell. +- No repo-wide automatic docs/test rewrite is intended. Explicit aux trigger, no-op evidence, and serial order are useful. Test writing and actual test execution, source editing and validation/review, debugger diagnosis and repair writes, browser visual verification and product source changes are intentionally separated; do not enlarge individual tool diets to erase these boundaries. + +## Coverage and offline verification + +| Domain | Checked evidence / disposition | +| --- | --- | +| Security | Plan containment vs advertised roles, hard project boundary vs soft writer ceilings, source and destination checks, browser opt-in, specialist-vs-host terminal ceilings. I2/I5. | +| Correctness | Read/edit/create/delete/move matrix, canonical commit evidence; runtime doc spawn, dependency matching/status, repair attribution, direct pending input. I1/I3/I4/I6/I8. | +| State mutation | Scoped/shared worktree, leases, CAS/rollback, pending gates, docs done state, failed dependency restores. I1/I2/I3/I6/I8. | +| Error handling | Preflight/retry vs partial/uncertain dispatch, emitted native error shape, debugger escalation, invalid writer receipt, failure-vs-success detection. I1/I3/I7/I9. | +| Performance | Bounded transaction input, batched leases and joined independent work, bounded identical recovery vs unbounded no-action retries. I7. | +| Dependency hygiene | Manager selection from manifests, native command/selector match, lockfile rollback/postconditions and repo guard behavior. I3/I4/I5; no installed-version or advisory scan. | +| Test coverage | Current focused suites plus missing actual writer inline-spawn, dependency wire, repair file map, and action-required terminal cases. I1/I3/I4/I6/I7/I8. | +| API/ABI | Structured handoff contracts, declared vs legacy tool names, authority-version guidance, dependency v2 receipt. I1/I3/I4/I9. | + +**Validation:** Bun 1.4.4; 365 passed, 0 failed across 14 isolated existing test files. Groups: (144) `editor.test.ts`, `dependency-manager.test.ts`, `base2-writer-spawn-rules.test.ts`, `tool-reachability.test.ts`, `editor-orchestrator-contract.e2e.test.ts`; (167) `spawn-agents-permissions.test.ts`, `process-edit-transaction.test.ts`, `edit-transaction-capability-guard.test.ts`, `workspace-path-leases.test.ts`, `terminal-profile-bound.test.ts`, `terminal-command-policy.test.ts`; (54) `read-files-capability-authorization.test.ts`, `edit-transaction-multi-file-recovery.e2e.test.ts`, `edit-transaction.schema.test.ts`. Additionally ran in-memory probes against actual doc handoff derivation, terminal lexical policy, and the dependency generator with a synthetic native terminal-error receipt. Tests used existing offline fixtures; no model/provider requests were made. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/memory-handoff.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/memory-handoff.md new file mode 100644 index 0000000000..7266f101e2 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/memory-handoff.md @@ -0,0 +1,53 @@ +# Memory and durable handoff — vertical audit + +**HEAD:** `6d5364de3`. Static inspection only; cited tests were inspected, not run. Scope: agent/runtime declarations, parent↔child transfer, plan and audit artifacts, host/operator storage, CLI/SDK consumers and tests. General-purpose retrieval specialists, model quality, and unrelated subsystems are out of scope. + +**Verdict:** Yes, with distinct boundaries. Openbuff can preserve and recall bounded conversation context, transfer scoped context and structured receipts between agents, and store work across runs. A structured result is not a durable record, an archive excerpt is not canonical knowledge, and a maintenance proposal is not an approval. The shipped root has real reachability gaps despite working native tools; plain SDK and CLI defaults differ. + +## Findings + +### P1 — Shipped roots cannot explicitly record decisions despite being prompted to do so +- **Evidence:** `agents/base2/base2.ts:424–469` injects decision-capture guidance and builds both initial and full tool surfaces through `resolveModelToolNames`; `agents/base2/tool-tiers.ts:75,224–239` classifies `record_decision` mode-neutral but only emits CORE and tier entries. Neither includes it (`packages/agent-runtime/src/util/base2-tool-tiers.ts:29–97`); the hidden allowlist does not either (`agents/base2/spawn-contract.ts:57–75`). Deep mode derives from Base2 (`agents/base2/base-deep.ts:330`). The registered native tool works for SDK templates that declare it (`common/src/tools/list.ts:129`; `packages/agent-runtime/src/tools/handlers/list.ts:124`). +- **Impact / fix:** Normal orchestrator users cannot intentionally persist a fact, rationale, or constraint through the documented route; automatic observation is not equivalent. Add the tool to a reachable implementation tier, align guidance and tool search, and test effective provider schema plus a native capture in the actual root. Current prompt tests check text (`agents/__tests__/quality-prompt-snapshot.test.ts:244`), native tests use the handler or explicit fixture templates (`packages/agent-runtime/src/tools/handlers/tool/__tests__/record-decision.test.ts:25`; `sdk/src/__tests__/memory-v2-roundtrip.test.ts:217`). Preserve the specialists' deliberate denial. + +### P1 — EXECUTE_PLAN loses the native status/checkpoint path +- **Evidence:** `agents/base2/tool-tiers.ts:140–142,224–239` admits `create_plan` and `update_plan_status` only for `planOnly`; unlocking the implementation tier cannot override that ceiling. Yet EXECUTE_PLAN specifically asks the model to pass gate-issued receipt IDs into `update_plan_status` and keep STATUS/LESSONS current (`agents/base2/base2.ts:8121,15553–15554`). The execute-plan reachability test verifies implementation tools but not plan artifact tools (`agents/tool-reachability.test.ts:129–148`); native completion receipt tests exist independently (`packages/agent-runtime/src/tools/handlers/tool/__tests__/update-plan-status.test.ts:518,555`). +- **Impact / fix:** The root cannot use the intended receipt-checked task transition while executing a plan; a generic Markdown edit is not equivalent. Expose both artifact tools in PLAN and EXECUTE_PLAN only, and test a real gate receipt → task done → next task transition through the execute root. + +### P2 — Plan status writes use ambient CWD and do not commit one revision atomically +- **Evidence:** `packages/agent-runtime/src/tools/handlers/tool/update-plan-status.ts:202–245,365–390` resolves against `process.cwd()`, checks a revision, writes STATE, then replaces the Markdown. `common/src/util/plan-artifacts.ts:260–293` rereads and increments STATE without carrying the checked expected revision through a lock. Direct tests change process CWD (`packages/agent-runtime/src/tools/handlers/tool/__tests__/update-plan-status.test.ts:177`) and cover lexical path/symlink and ordinary updates (`:190–266`), not an SDK workspace different from process CWD or concurrent/crash-partial commits. +- **Impact / fix:** Embedded or multi-workspace hosts can miss or update the wrong plan; concurrent callers can pass the same check, and a Markdown failure after STATE advances leaves resume state contradictory. Use the captured workspace/filesystem and a per-session conditional commit for Markdown, STATE, and timeline publication, with typed partial/recovery outcomes. Test divergent CWD, competing revisions and failure between writes. + +### P2 — Exact conversation recall is not composable across provider and local search paths +- **Evidence:** `common/src/tools/params/tool/recall-context.ts:28–33,67–79` requires typed `message` plus `sourceRunId` without `query`/`toolCallId`, but the shared provider schema only advertises query or tool ID (`common/src/tools/provider-schema.ts:26`, applied by `packages/agent-runtime/src/tools/prompts.ts:184`). In addition, both local search implementations drop source run provenance (`packages/agent-runtime/src/util/context-archive.ts:605–614`; `packages/agent-runtime/src/util/archive-recall-index.ts:276–296`); the handler converts synthetic IDs into typed message references without reconstructing sourceRunId (`packages/agent-runtime/src/tools/handlers/tool/recall-context.ts:263–272`). +- **Impact / fix:** A native schema-enforcing provider can reject valid exact message calls; a local/edited-branch hit can lack the run ID needed to page that result. Publish the matching third selector alternative and preserve original source identity in both local search paths without granting original-body credit to an excerpt. Existing Zod selector (`common/src/tools/params/__tests__/recall-context.test.ts:15`), FTS parity (`packages/agent-runtime/src/util/__tests__/archive-recall-index.test.ts:152,220`), and host paging (`sdk/src/__tests__/context-archive-reader.test.ts:108–188`) tests do not cover the combined provider/search-to-page flow. + +### P2 — In-process explicit decision writes breach task-memory copy-on-write +- **Evidence:** `packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:245–251,329` shares one clone cache across a batch. `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:3523–3537,3660–3679` returns that same inherited task-memory node to eligible `pinned`/`full` children, frozen only outside production. `packages/agent-runtime/src/tools/handlers/tool/record-decision.ts:180,216–218,243–267` pushes/shifts its arrays in place rather than assigning an independent revision. +- **Impact / fix:** With preexisting memory and custom in-process children declaring the tool, development/test can reject a valid record while production siblings can observe one another's mutation. Use the task-memory commit/CAS API or copy-on-write before both ordinary and duplicate/supersede updates. Add a same-batch regression with seeded parent memory, writer plus reader, and both freeze modes. Do not solve this by removing the freeze or merging private child transcripts. + +### P2 — Proposal-only is intentional; no first-class supported application of a reviewed proposal +- **Evidence:** `agents/memory/memory-manager.ts:25–33,126–200` joins retrieval and independent review, refuses failed/rejected children, and returns proposals through `set_output`. `agents/memory/contracts.ts:143–160,209–242` provides free-text targets and fixed `requiresUserApproval:true`, `applied:false`, `untrustedSuggestions:true`, not an executable receipt or approval. Host-evidence references are shape-checked, not a new grant of verification. The only documented follow-through is user approval then ordinary editor/reviewer or operator action (`docs/agents-and-tools.md:83–93`). `/memory revalidate`, `correct`, `forget`, and `pin` exist independently (`cli/src/commands/memory-command.ts:817–955`); `/index rebuild` is independent (`cli/src/commands/index-command.ts:255–266`). +- **Impact / fix:** Users can manually apply an approved file edit, map rebuild or ID-based lifecycle operation; they cannot pass a manager proposal ID to a supported consumer to preview, approve, apply and verify that exact change. Add an operator-owned typed handoff with stable target identity, captured basis/revision, explicit approval, and replay-safe outcome. Keep arbitrary direct canonical authoring and automatic approval disabled. SDK tests prove actual join, refusals, and partial outcomes, not application (`sdk/src/__tests__/memory-management-agents.test.ts:245,281,390,434–456`). + +### P2 — Synthesizer filesystem confinement and report success are prompt claims +- **Evidence:** `agents/synthesizer/synthesizer.ts:26–83,120–121,189–200` takes paths in prose, declares wildcard `filesystemScope`, exposes generic reads/writes and returns a self-reported `reportPath`. In-project scope misses only warn (`packages/agent-runtime/src/tools/tool-executor.ts:3356–3400`). It does not bind to the assigned session's artifact receipts or check a successful report write before publishing. The shard writer itself is stronger: schema check, derived path, exclusive change and byte-identical collision check (`sdk/src/tools/write-audit-findings.ts:245–392`). +- **Impact / fix:** A missing or contaminated findings set can produce a misleading report pointer, or findings prose can steer reads/writes elsewhere inside the permitted project. Basic project containment still applies. Bind synthesis to host-selected session and artifact list/hash, deny off-scope filesystem calls, and require a confirmed report-write receipt. Existing tests cover writer collisions and plan roster exclusion, not the synthesis contract (`sdk/src/__tests__/write-audit-findings.test.ts:173,1135,1266`; `agents/tool-reachability.test.ts:219–223`). + +### P2 — Explicit record acknowledgment does not tell the user what actually survived +- **Evidence:** The handler returns “Recorded” after session-state mutation (`packages/agent-runtime/src/tools/handlers/tool/record-decision.ts:269–284`). The native observation is awaited, attributed and validated but returns no durability receipt (`packages/agent-runtime/src/tools/tool-executor.ts:4415–4428`; `sdk/src/run.ts:4693–4787`). Capture can be off, unavailable, or outside ready/active preparation (`sdk/src/services/memory-v2/coordinator.ts:1507–1535`); absence/failure does not alter the native acknowledgment. +- **Impact / fix:** A custom agent can report something is remembered for future turns when only its local state changed, especially when V2 is authoritative and V1 injection is suppressed. Keep local success non-fatal, but return/display separate typed `session` vs `canonical` confirmation (including unavailable/disabled and observation ID on confirmed commit). Cover failed append, disabled capture, and detached completion after terminal finalization. + +## Capability and test trace + +| Surface | Observed behavior and verification | +|---|---| +| Ephemeral pin / compaction | No dedicated arbitrary `pin_context` tool. `add_message` inserts ordinary history (`common/src/tools/params/tool/add-message.ts:7–16`; `packages/agent-runtime/src/tools/handlers/tool/add-message.ts:25–32`); privileged programmatic framework owns `keepDuringTruncation` and newest pinned memory/active-work blocks (`packages/agent-runtime/src/util/messages.ts:381–460`). `/compact` and automatic pruner use archive-before-rewrite; `set_messages` prepares memory via revision check before replacing history and the inline child proposes rather than committing parent history directly (`packages/agent-runtime/src/run-agent-step.ts:1410–1490`; `packages/agent-runtime/src/tools/handlers/tool/set-messages.ts:29–66`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-inline.ts:405–418`). Transaction reject/no-assistant tests: `packages/agent-runtime/src/__tests__/pruner-output.test.ts:12,50`. | +| Ephemeral/archive recall | Base2 CORE includes `recall_context`; other agents need the declared tool. It searches aged/size-bounded archive and optional consolidation hits, pages exact originals, and distinguishes stale/missing/conflict/degraded cases; it is not a V2 canonical query or a grant of edit authority (`packages/agent-runtime/src/util/base2-tool-tiers.ts:29–34`; `packages/agent-runtime/src/tools/handlers/tool/recall-context.ts:43–87,134–258`; `sdk/src/services/context-archive-reader.ts:33–137,156–255`). Strict readers and edited branches do not get project-wide archive access. Default TTL 30d; configured pin/retention flags are host metadata, not `/memory pin` of transcript text (`common/src/util/context-archive-body.ts:11–15`). Local FTS builds and closes one memory DB per query below a 16M-character cap, with scanner fallback if Bun/FTS is absent; consider a bounded generation-keyed reuse cache only with measurement (`packages/agent-runtime/src/util/archive-recall-index.ts:78,158–176,244–309`; tests `:249–261,461` in `packages/agent-runtime/src/util/__tests__/archive-recall-index.test.ts`). | +| Parent ↔ child and `set_output` | Explicit prompt/params/handoff plus `none`/`pinned`/`full`; ordinary template defaults follow `includeMessageHistory`, inline defaults pinned, pruner full. Private child transcripts do not merge back by default (`packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:268–323,1190–1239`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:3584–3679`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-inline.ts:215–242`). `set_output` validates and replaces the prior value; structured results become child receipts. Oversize recovery artifacts are joined before publication but are scratch, not durable workflow state (`packages/agent-runtime/src/tools/handlers/tool/set-output.ts:814–867,1114–1131`; `packages/agent-runtime/src/util/agent-output.ts:63–72`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:1293–1337,1434–1489,3024`). Invalid/recoverable outputs tested in `packages/agent-runtime/src/tools/handlers/tool/__tests__/set-output.test.ts:157,976,1247`. | +| Durable workflow files | PLAN/STATUS/LESSONS plus STATE and EVENTS carry execution state without relying on transcript. `create_plan` requests a host write; `update_plan_status` validates checklist/gate transitions and emits timeline events (`packages/agent-runtime/src/tools/handlers/tool/create-plan.ts:72–147`; `packages/agent-runtime/src/tools/handlers/tool/update-plan-status.ts:291–418`). Broad audit shards use `write_audit_findings` and carry snapshot-bound receipts rather than full prose (`agents/general-agent/general-agent.ts:426–471`; `sdk/src/tools/write-audit-findings.ts:205–224,245–392`); synthesis is the file consumer, intentionally not in PLAN (`agents/base2/base2.ts:582–584`). | +| Knowledge files and canonical operator tools | Repo knowledge/instruction files and home guidance load via SDK file context at startup/continuation; Base2 routes advisory references separately. Change project Markdown through normal editor/validation after approval, not canonical-memory mutation (`common/src/constants/knowledge.ts:8–41`; `sdk/src/run-state.ts:778–852,905–942,1248–1305`; `packages/agent-runtime/src/util/base2-turn-prompt.ts:44–89`; `sdk/src/__tests__/initial-session-state.test.ts:220,496–518`). The common native catalog has no general canonical query/CRUD tool; `/memory query`/`inspect` and preview/apply operator actions are supported host APIs (`cli/src/commands/memory-command.ts:664–755,817–955`; `sdk/src/services/memory-v2/operator-service.ts:776,928`; `cli/src/commands/__tests__/memory-command.test.ts:430,865`). SDK `VerifiedKnowledgeService` is an exported separate harness metadata helper, not the V2 prompt read or a model tool (`sdk/src/services/harness-intelligence.ts:2341–2378`; `sdk/src/index.ts:537`; `sdk/src/__tests__/harness-intelligence.test.ts:1364`). | +| Actual defaults and lifecycle | CLI unset/blank authority is **`sqlite-v2-opt-in`** despite its name. TUI, headless `run`, and `serve` use the managed CLI client; `--attach` delegates to the server. Healthy CLI passes repository with safe capture. `json-v1` does not open SQLite; invalid flags select V1; shadow captures/queries without V2 knowledge injection (V1 remains authoritative); default V2 outages retain V2 authority with no V1 prompt fallback. Plain SDK has **no V2 repository/coordinator by default**; supplied V2 config without authority/mode defaults to shadow. The SDK can still load/reconcile and merge-save V1 JSON with `cwd`, including on normal terminal error/cancel paths; V2 mode retains that compatibility shadow (`cli/src/utils/env.ts:98–115`; `cli/src/utils/codebuff-client.ts:54–74,187–241`; `cli/src/commands/run-command.ts:118`; `cli/src/serve-command.ts:144`; `cli/src/hooks/use-send-message.ts:872`; `sdk/src/run.ts:602,1036–1039,2152–2155,4655–4674`; `sdk/src/run-state.ts:951–971`; `sdk/src/services/memory-v2/types.ts:37–73`). Defaults/provider mapping tests: `cli/src/__tests__/utils/env.test.ts:100`, `cli/src/utils/__tests__/codebuff-client.test.ts:23`, `sdk/src/__tests__/memory-v2-authority-wire.test.ts:118`. | +| V2 trust, storage, and restart | Turn preparation queries and validates project/query identity, clears stale injection and degrades without changing selected authority; actor-specific host preparation rechecks dependency digests instead of trusting child/restored state (`sdk/src/services/memory-v2/coordinator.ts:900–1018,1270–1393`; `sdk/src/services/repository-intelligence.ts:257–330`; `packages/agent-runtime/src/run-agent-step.ts:2000–2055,2085–2103,3020–3068`). Native decision capture redacts/bounds evidence and writes observations, not authority; finalization is bounded and parks unconfirmed terminal events for reconciliation (`sdk/src/services/memory-v2/coordinator.ts:1811–1840,2243–2289`; `sdk/src/services/memory-v2/finish-turn.ts:8–56`). CLI leased SQLite uses local preflight/identity checks and WAL; strict secure-open is explicitly unsupported by `bun:sqlite` and fails closed. Semantic expansion is optional and provider-configured, not required for lexical memory (`cli/src/services/memory-v2/bun-sqlite-memory-repository.ts:631–674`; `cli/src/services/memory-v2/provider.ts:75–124,221–323`). CLI chat persistence explicitly flushes/hydrates archive; plain SDK hosts must retain `RunState` or persist originals through their repository—V2 decision persistence does not imply auto-persistence of every transcript (`cli/src/utils/run-state-storage.ts:805–814`; `cli/src/hooks/use-send-message.ts:440–473`; `test/fixtures/body/memory-restart.ts:487`). Tests cover reopened SQLite/original pages, degraded child authority, stale digest and history-preserving forget (`sdk/src/__tests__/b13-memory-restart.test.ts:7`; `sdk/src/__tests__/memory-v2-child-authority.test.ts:145,203,227`; `cli/src/services/memory-v2/__tests__/two-session-cold-start.test.ts:242,313,425`). | + +All eight domains checked: security, correctness, state mutation, errors, performance, dependencies, tests, and API contract. No separate dependency-version finding from this static scope; Bun/host adapter constraints and fallback behavior are noted above. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/review-gate.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/review-gate.md new file mode 100644 index 0000000000..4c46cbf3aa --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/review-gate.md @@ -0,0 +1,27 @@ +# REVIEW shard — independent review and gate acceptance + +**Basis:** `6d5364de3`, shipped `agents/` + CLI/SDK/runtime wiring; not the graveyard or example agents. Static source trace, existing local tests and two in-memory probes; no live providers. Validation-command selection, browser/CLI smoke and UI execution are out of scope. + +## Verified behavior and boundaries + +- **Access and scope.** The CLI embeds `agents/` definitions and serializes their generators (`cli/scripts/prebuild-agents.ts:18–55,66–86`); the registry exposes the roster and permits configured same-ID overrides (`cli/src/utils/local-agent-registry.ts:347–382,440–460`). `DEFAULT`, `PLAN`, and `EXECUTE_PLAN` map to Base2 roots (`cli/src/utils/constants.ts:109–115`); all have the code/security reviewer and scoped reviewer-family specialists (`agents/base2/base2.ts:532–598`), with mutating children filtered in PLAN (`cli/src/utils/local-agent-registry.ts:417–437`). An explicit agent mention has prompt-level delegation (`agents/base2/base2.ts:600–610`); a plain review request likewise depends on root judgment, not on the edit gate (`agents/base2/base2.ts:712–716`). `/review` presets and direct/custom scopes all generate a **static advisory prompt**, not a reviewer-mode switch: it requests an actual scope/baseline, independent code review, scoped risk specialists, and evidence gaps. Clean worktree/last-commit fallback is not a valid substitute for an explicitly requested uncommitted scope or branch baseline (`cli/src/commands/prompt-builders.ts:7–14,110–157`; `cli/src/components/review-screen.tsx:53–58`; `cli/src/commands/command-registry.ts:1704–1717`; `cli/src/commands/router.ts:499–511`). A narrow request is not a whole-repo audit: broad requests use structural inventory, bounded file-picker + reasoning shards, and explicit coverage receipts before synthesis (`agents/guides/broad-audit.md:3–17`; `agents/patterns/audit-codebase.md:5–9,154–174`). Those are audit completeness receipts, not edit-gate approvals. +- **Independent judgment, not automatic proof.** Shipped `code-reviewer` has `read_files`, `code_search`, `set_output`; security adds `read_outline` and `git_status`. Both are leaf agents without parent prompt/history or terminal/edit tools (`agents/reviewer/code-reviewer.ts:16–39,163–190`; `agents/security-reviewer/security-reviewer.ts:11–36,123–135`). Main review covers correctness/security/tests/API/performance plus requirement evidence; security covers input boundaries, authorization, secrets, resource safety and fail-closed behavior. Routed reviewer-family leaves add bounded workspace/task/diff inspection and selected intelligence tools; shell-capable integration/release/incident agents are **advisory**, not routed reviewer gates (`agents/specialists/create-specialist.ts:173–291`; `agents/specialists/integration-agent.ts:5–10`, `release-manager.ts:5–10`, `incident-coordinator.ts:5–9` under the same directory). The shared rubric treats scanner hits/diff fragments as leads, asks for exact callers/tests and names evidence gaps (`agents/reviewer/static-review-method.ts:1–7`). Optional Semgrep in the bundle is static scanner evidence and can be unavailable or skipped, not independent approval (`sdk/src/tools/get-change-review-bundle.ts:187–220,982–992`). The separate CLI `review-runtime` / SDK `runDynamicReview` receipt has `gateCredit: false`; it requires successful target exit, stable observed worktree basis and confirmed cleanup. Refused, stale, timed-out, cancelled and inconclusive results are not passes; even success says nothing about unselected checks or ignored inputs (`docs/agents-and-tools.md:702–721`; `sdk/src/tools/run-dynamic-review.ts:110–120,245–267,295–385`). Targeted validation likewise cannot clear review or unlock commit (`agents/base2/quality-prompt-section.ts:68–75`). +- **Gate and routing.** In DEFAULT/EXECUTE_PLAN, task-owned pending edits drive test/doc auxiliaries → security → selected specialists → hooks → final `code-reviewer` against post-hook bytes (`agents/base2/base2.ts:2077–2157,2569,2740,2930–3008,3448,5757–5859,6251–6289,6443–6485`). Foreign turn-start dirt isn't indiscriminately adopted. Modern Base2 hosts supply bounded, scope-filtered actual Git hunks for a one-step, `set_output`-only risk triager; recommendations must cite assessed hunk IDs. Partial/invalid/unavailable evidence falls back to path/intent routing; complete triage displaces soft routes but keeps manifest/CI policy and previously owed specialists. Neither triage nor the bundle is a reviewer receipt (`packages/agent-runtime/src/run-programmatic-step.ts:457–502`; `agents/reviewer/review-triage.ts:11–25,49–60`; `common/src/agents/review-impact.ts:5–19,75–96,215–273`; `agents/base2/base2.ts:3551–3655`). A specialist token is automatic `params.snapshot_id` or omitted for manual work; manual security still takes `changed_files` plus a caller-chosen `snapshot_fingerprint` (`agents/guides/specialist-routing.md:61–76`; `agents/specialists/create-specialist.ts:102–135`; `agents/security-reviewer/security-reviewer.ts:19–33,152–157`). +- **Receipts and blockers.** Automated final review requires structured schema version 1, exact `v3:` echo, coverage of pending source **and tests**, full dimensions and nonempty requirement evidence; genuinely deleted paths are exempt from the read list. Mismatched well-formed tokens **do** hard-block at this HEAD despite stale drift-tolerance comments in Base2. Missing behavior coverage, a `block*` dimension and in-scope missing/uncertain requirements block; parent-owned process work and advisories do not. A clean security `NON_BLOCKING` may pass its own aux gate, not substitute for the final code-review verdict (`agents/base2/gate-reviewer.ts:234–357,883–974`; `agents/base2/base2.ts:3034–3097,6496–6607`; `agents/e2e/gate-lifecycle.e2e.test.ts:1045–1087`). Findings route to repair (coverage-only to test-writer) and re-review; incomplete repair, no bytes progress and cycles can park rather than pass (`agents/base2/base2.ts:6802–6847,7280–7362,7390–7503`). A final status/byte check reopens on drift; the durable review key uses gate-computed content, while the receipt separately keeps the reviewer token, bounded file hashes, findings, and advisory evidence (`agents/base2/base2.ts:6325–6366,7863–7897,13111–13342`). The echo plus file list is an attestation of **model judgment**, not a host-confirmed transcript of reads or proof of test quality. It also is not the SDK bundle’s bare-hex worktree ID. +- **Intentional no-review states.** No edits outside an already pending cycle need no automated code review. An empty reviewable subset (e.g. documentation/bookkeeping), exact prior credit, PLAN artifact-only work and explicit no-validation can skip as appropriate (`agents/base2/base2.ts:6382–6439,7999–8028,8213–8247`); FAST divergence below. A separate opt-in committed-surface path refuses dirty/empty/unattestable inputs rather than treating a clean tree as old review proof (`agents/base2/base2.ts:2187–2253,2285–2302,2418–2438`). Protocol retries, crash, no-verdict and specialist failure are not normal clean verdicts. The documented `BYPASS REVIEWER` escape checks an unconsumed, content-bound challenge and an exact later user-role input (`docs/environment-variables.md:76–85`; `agents/base2/base2.ts:5707–5754,7597–7669,7726–7832,12187–12261`); security protocol failure instead parks incomplete (`agents/base2/base2.ts:3352–3387`). `COMMIT ANYWAY` is a different guard, scoped to previously listed files and does not open a still-pending gate (`packages/agent-runtime/src/tools/tool-executor.ts:3688–3711`). + +## Findings (risk → fix) + +1. **High — Repair can overrule the independent re-review.** A completed repair receipt claiming a matching finding ID with a nonempty changed-path list seeds condone keys. The next reviewer can report the *same required finding again* and its verdict is replaced with `LOOKS_GOOD` when all findings are suppressed. Matching allows even same-class `BLOCKING` (and BLOCKING→NON_BLOCKING); existing coverage protects escalation and hard structured rules, not persistent ordinary findings. The test explicitly expects green on a fresh `NON_BLOCKING` re-raise (`agents/base2/base2.ts:7297–7363,6670–6752,9027–9068`; `agents/__tests__/base2.test.ts:7435–7465,7476–7518`). **Risk:** a byte-changing but inadequate repair can silence the reviewer instead of resolving the issue, contrary to `docs/agents-and-tools.md:741`. **Fix:** use repair claims only for deduplication/progress; keep unresolved re-raised findings open, stop on no progress or ask for explicit waiver, and require an independent clean verdict to record review credit. Test with a real persistent defect rather than an advisory-style finding. +2. **High — Snapshot tokens can represent the wrong workspace or no bytes.** SDK Git observes the captured `cwd`, but Base2 uses ambient `process.cwd()` for marker reads; SDK’s in-process filesystem sandbox sets async context, not process cwd (`sdk/src/run.ts:1409–1446,6098–6106`; `common/src/util/filesystem-sandbox.ts:51–62`; `agents/base2/base2.ts:14771–14799,14889–14931`). With a different SDK project root this can hash an unrelated same-name file or turn a present pending path into `missing`; the latter removes that path from required review coverage. Separately, the outer hash accepts a details row containing `unreadable:*` and yields a syntactically attestable token (`agents/base2/base2.ts:11821–11846,14705–14720`; `agents/base2/gate-reviewer.ts:289–324`). In-memory pure probe: hashing a fixture details row containing `unreadable:lstat-failed` returned `v3:` with `isAttestableSnapshotFingerprint === true`. Per-file ledgers reject unreadable markers, but the outer digest/final exact-echo check does not. **Fix:** bind normalized paths and reads to the trusted captured project/filesystem adapter; require typed successful observations for every row, and confirm deletion against the trusted change basis before granting the exemption. Add two-root/same-relative-path and unreadable/deleted-file regressions through the real SDK generator boundary. Bind reuse to reviewed requirements/baseline as well as the bytes: the existing receipt match uses family, file set and byte token, not task/criteria/adjacent evidence (`agents/base2/base2.ts:6322–6335,14705–14720`). +3. **High — Same-path hook writes can invalidate risk reviews without reopening them.** Aux security/specialist freshness is checked before hooks. The post-hook branch only restarts on **membership** change, then freezes the new bytes for code-reviewer; the final gate checks that *post-hook* view without checking the aux markers again (`agents/base2/base2.ts:2914–2936,3421–3442,3635–3656,6251–6289,7863–7897,7923–7935`). **Risk:** a formatter/codegen hook that changes an already-attested security/compatibility file can receive final green without independent risk review of its new bytes. **Fix:** reconcile every required auxiliary marker/wave against the final freeze, re-route drifted paths and carry verified hook evidence on the new basis. Add a same-membership hook rewrite test; the existing ordering fixture checks the post-hook refresh before the final spawn, not aux invalidation (`agents/e2e/gate-aux-ordering.e2e.test.ts:487–504`). +4. **High — Final/plan/API evidence collapses a waiver or skipped check into green.** Protocol, crash and no-verdict bypasses assign `LOOKS_GOOD` (`agents/base2/base2.ts:6292–6312,7603–7636,7730–7764`); specialist bypass even writes normal marker credit for all spawned specialists (`agents/base2/base2.ts:5366–5403`). Finalization writes a green durable pass and calls any nonempty reviewable plan-task scope `reviewed-diff` regardless of the waiver; the plan consumer matches task/receipt IDs without an assurance class (`agents/base2/base2.ts:7912–7939,7999–8085,8121–8189`; `packages/agent-runtime/src/tools/handlers/tool/update-plan-status.ts:134–156,307–320`; `packages/agent-runtime/src/util/plan-execution-state.ts:129–153`). Hook skips have a related reporting bug: SDK emits `no_hooks_configured`/`hooks_skipped` with messages; Base2 prefixes `REDUCED_ASSURANCE:` and later recognizes only the *unprefixed* strings, so telemetry says `validationStatus: passed`, `hooksRan: true`. Infrastructure exception detection additionally regex-matches human failure text (including nonzero-command stdout/stderr), rather than typed failure cause (`sdk/src/tools/file-change-hooks.ts:1642–1670`; `agents/base2/base2.ts:5893–5908,6175–6200,7999–8002,8151–8170,15291–15328`; fixture `agents/__tests__/base2.test.ts:1636–1680`). **Fix:** separate `gateAllowed` from reviewer/validation outcomes (`passed`, `reused`, `waived`, `skipped`, `inconclusive`, `failed`); classify infrastructure via typed receipts, reject malformed/unknown results, and make plan checkpoint policy consume the evidence class. Explicit consent can unblock a workflow without creating independent review evidence. +5. **Medium — Real no-review gaps in security/dependency scope.** The security predicate sees full pending paths but only sends the intersection with reviewable sources; a matched policy YAML/JSON or `.env` can leave **zero** candidates and mark the security gate done. Security is still path-name driven, and evidence-led risk triage has no security route (`agents/base2/gate-paths.ts:67–88`; `agents/base2/base2.ts:1107–1124,2883–2889,2972–3007,12300–12324`; `common/src/agents/review-impact.ts:5–15`). The dependency aux widens its input for pending manifest/lock/CI changes, but explicit Git delivery first adopts only legacy reviewable turn-start files, so a previously dirty manifest-/CI-only delivery can miss both reviewers and the unvalidated-file guard (`agents/base2/base2.ts:1694–1718,3542–3579,14628–14634`; `packages/agent-runtime/src/tools/tool-executor.ts:3690–3730`). **Fix:** decouple gate-required risk surfaces from generic source scope, classify behavior-sensitive config and provenance on explicit delivery, and use redacted metadata or a typed evidence gap for secret-bearing paths rather than sending secret contents to reviewers. Test sensitive configuration-only, generic-named security-relevant source and manifest-only delivery. +6. **Medium — Mode and retry promises diverge from serialized execution.** `base2-fast` does not actually skip with the shipped config: `hasNoValidation` defaults to `false`, is serialized explicitly, and takes precedence over the legacy ID fallback. The fast skip test omits `config`, unlike the runtime. In-memory generator probe with the real definitions' config advanced to `run_file_change_hooks` for DEFAULT **and FAST**, versus the disabled notice for FAST-NO-VALIDATION (`agents/base2/base2-fast.ts:3–5`; `agents/base2/base2.ts:270–273,512–522,1090–1098`; `packages/agent-runtime/src/run-programmatic-step.ts:542–550`; `agents/e2e/reviewer-spawn-conditions.e2e.test.ts:377–429`). Deep shares the gate but `template.id.startsWith('base2')` excludes `base-deep` from evidence-led triage and retains compatibility routing. Also, the docs promise default two no-verdict retries, whereas the factory and resolvers default to unlimited; identical diagnostics may still converge (`agents/base2/base-deep.ts:325–334,363–364`; `packages/agent-runtime/src/run-programmatic-step.ts:455–503`; `docs/environment-variables.md:76–85`; `agents/base2/base2.ts:327–343,1194–1212,7771–7817`; `common/src/util/gate-repair-budgets.ts:88–120`). **Fix:** one explicit serialized mode policy and capability-driven control-plane injection; test shipped configs and omitted budgets at the runtime boundary; reconcile help/docs with the chosen defaults. +7. **Medium — Advisory independence and headless acceptance are not enforced by transport.** `/review` enters the active root mode with an instruction, not a read-only tool ceiling or required reviewer receipt. A root can summarize without a child result, and a pending edit cycle can still invoke ordinary automatic gates. A same-ID custom override is intentional and should be attributed, not silently assumed to have the stock reviewer tool set (`cli/src/commands/prompt-builders.ts:7–14`; `cli/src/chat.tsx:1698–1707`; `cli/src/utils/local-agent-registry.ts:440–460`; `agents/base2/base2.ts:1969–1987,2071–2076`). Conversely, an edit gate can park without a public run error: runtime terminal completion leaves `taskAcceptance: unknown`; headless checks termination/error/rejection and otherwise returns 0. That exit code means **run completed**, not review accepted (`agents/base2/base2.ts:6558–6596`; `packages/agent-runtime/src/run-agent-step.ts:2267–2304`; `common/src/types/run-outcome.ts:91–108`; `cli/src/commands/run-command.ts:378–418`). **Fix:** give explicit static review a least-privilege turn and a required join/evidence-gap result; expose a typed gate outcome independently of run termination for SDK/headless consumers, with opt-in CI enforcement. Do not conflate provider success or TUI subagent output acknowledgment with finalization credit (`cli/src/utils/review-outcome.ts:67–93`). +8. **Low — Successful repair can run the same validation twice.** Inline re-validation after code-review repair sets the summary/phase but does not persist the full marker evidence used by the subsequent main gate; it loops back on success. A pre-repair receipt fails byte matching and the hooks run again. Even a legitimate full-evidence reuse leaves the local `validationSummary` initialized to “No file changes…” rather than copying the reused summary (`agents/base2/base2.ts:5789–5888,7463–7503`). **Risk:** duplicate latency/side effects and bad handoff evidence. **Fix:** route repaired bytes to one authoritative post-repair validation path or persist its typed evidence on exactly the same scope, copy the reused summary, and assert exact dispatch count and reviewer packet contents. + +## Local evidence + +- Bun 1.4.4, **216 passed** in focused reviewer/gate schema, wave credit, specialist router/parity, roster, spawn-condition, `/review` prompt and SDK dynamic receipt suites; **73 passed** in auxiliary ordering, lifecycle, review-impact and worktree bundle suites; **28 passed** in filtered Base2 condone, docs-only, receipt reuse and no-verdict cases. Counts are from separate invocations, not a full-suite claim. +- The FAST and unreadable-token probes were local/in-memory only. Other findings above are source-traced; the audit did not exercise provider judgment, actual UI behavior, or an exploit. No new package dependency is needed for these fixes; maintain generator/helper freshness (`docs/agents-and-tools.md:778–789`). diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/root-delegation.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/root-delegation.md new file mode 100644 index 0000000000..6562f86ea7 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/root-delegation.md @@ -0,0 +1,28 @@ +# ROOT — shipped orchestration and delegation + +HEAD `6d5364de3`. The normal local CLI **has** the core discovery, scoped context-retention, source-edit, review, and test roles. The primary gaps are mode/authority wiring, not missing specialist definitions. Availability is not a claim that a model always delegates, that all child routes are configured, or that validation or knowledge promotion succeeded. + +## Material findings + +1. **High — correctness/state/API: EXECUTE_PLAN cannot claim or checkpoint a durable task with its instructed tool.** `agents/base2/base2.ts:15497–15505,15550–15555` requires `update_plan_status` to claim one task, record the gate's exact receipt, mark it done, and advance; it also specifies `create_plan` for larger revisions. The CLI actually selects this root on `/resume-plan` (`cli/src/commands/command-registry.ts:1528–1538`). `agents/base2/tool-tiers.ts:140–152` permits both artifact tools only when `planOnly`, and `:199–218` uses that predicate for the advertised surface and tier ceiling; neither is in the hidden generator list (`agents/base2/spawn-contract.ts:57–75`). Offline inspection of the generated bundle confirmed both absent even with all tiers loaded; `tool_search('update_plan_status')` returned a PLAN match and no EXECUTE_PLAN match. Normal file edits are not a substitute for the receipt-backed state transition. The current mode-policy test deliberately asserts PLAN-only access (`agents/__tests__/base2-mode-policy.test.ts:45–55`), while `agents/__tests__/base2.test.ts:8277` checks prompt text. **Fix:** explicitly permit scoped artifact tools in PLAN and EXECUTE_PLAN (with the existing path, lifecycle and receipt checks), keep ordinary DEFAULT unchanged, and add a fake-model `/resume-plan` test that claims, checkpoints, and advances a task through the shipped surface. + +2. **Medium — correctness/performance/test coverage: shipped FAST activates the full automatic gate even though its prompt and roster assume a lightweight route.** `agents/base2/base2-fast.ts:3–6` calls `createBase2('fast')`; that emits `hasNoValidation: false` (`agents/base2/base2.ts:270–274,512–517`). The runtime supplies the actual template config (`packages/agent-runtime/src/run-programmatic-step.ts:542–548`), so the boolean branch enables the gate and never checks the FAST ID fallback (`agents/base2/base2.ts:1091–1098`). In contrast, the prompt decides a gate is active only for non-fast (`:15439–15441,15517–15519`); the validation repair path can request `repair-editor` (`:5795–5797,5959–5974`), excluded from FAST at `:559–564` and refused by the nonlegacy roster check (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:346–364`). Offline source-generator probe passed the actual bundle config and saw a gate-receipt ledger for FAST but not FAST-NO-VALIDATION. The existing regression explicitly omits config for FAST (`agents/__tests__/base2.test.ts:14673–14697`). **Fix:** emit one authoritative mode-resolved gate policy shared by prompt and generator; if FAST should use manual scoped validation, retain Basher/targeted validation and disable the automatic gate, and test the loaded FAST template. If automatic validation is desired, align the prompt, repair path and roster instead. + +3. **Medium — security posture/API: TUI can advertise PLAN while dispatching a root that is not plan-only.** The local parser accepts both mode and agent (even covered by `cli/src/__tests__/cli-args.test.ts:88–110`), Chat sets the displayed mode (`cli/src/chat.tsx:365–370`), but `resolveAgent` always prioritizes the explicit root (`cli/src/hooks/use-send-message.ts:130–142,894–906`). Slash mode selection likewise sets mode and announces it (`cli/src/commands/command-registry.ts:1403–1424`); SDK plan ancestry keys off the selected template flag, not UI state (`sdk/src/run.ts:2176–2186`). Separate attached variant: the ACP client sends prompt and optional coordination metadata, not the requested root/mode (`sdk/src/client/acp-client.ts:1048–1075`); the bridge runs its fixed server agent (`sdk/src/serve/bridge.ts:219–221,867–871`, CLI defaults `base2` at `cli/src/serve-command.ts:159–160`). This is a misleading safety indicator, **not** a bypass of a run that actually has authenticated plan ancestry. Explicit-agent precedence and a server-owned root may both be intentional. **Fix:** refuse conflicting local choices or show actual root authority instead of PLAN, and lock/label attached controls with the server's effective mode unless mode negotiation is supported; test that displayed PLAN and dispatch agree. Both paths source-traced, not driven through TUI/ACP. + +4. **Medium — correctness/API: the `@` menu advertises targets the effective root cannot spawn.** Chat supplies only the UI mode to `loadLocalAgents` (`cli/src/chat.tsx:488–521`). The menu derives bundled suggestions from the stock roster and always includes local definitions (`cli/src/utils/local-agent-registry.ts:338–389`), but execution merges overrides, augments `base*` rosters, and filters PLAN writers (`:426–484`). The selected completion inserts ordinary `@id` text (`cli/src/utils/mention-helpers.ts:24–29`); the root prompt says it must spawn a mentioned agent (`agents/base2/base2.ts:605–609`), and actual nonlegacy spawn permission requires a roster match (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:295–312,345–374`). An offline fixture confirmed the same custom writer is offered in PLAN and absent from the PLAN roster. With an explicit alternate root the menu still derives suggestions from the stock mode, not that root; exact model behavior after a mention is untested. **Fix:** derive enabled agent mentions from the same effective root catalog as runtime, excluding internal entries, or explain disabled entries; test PLAN custom writer vs reader and explicit custom root. Keep the actual PLAN restriction. + +5. **Medium — root tool affordance; coordinate with memory shard: decision-capture prompt has no callable `record_decision`.** Root injects the decision-capture policy in default-family execution (`agents/base2/base2.ts:418–425`); existing prompt test pins that it names `record_decision` (`agents/__tests__/quality-prompt-snapshot.test.ts:244–258`). Mode classification calls it neutral (`agents/base2/tool-tiers.ts:72–76`), but classification alone is not membership (`:199–218`); neither CORE nor any unlockable tier nor the generator list contains it (`packages/agent-runtime/src/util/base2-tool-tiers.ts:29–97`; `agents/base2/spawn-contract.ts:57–75`). Offline effective-surface enumeration confirmed the absence at CORE and fully unlocked. Other mechanisms still retain context; this finding is specifically the direct durable decision-capture affordance. **Fix:** assign it to an explicit appropriate mode/tier with existing evidence/host guards, or remove the unusable instruction; test prompt-to-provider-schema reachability. Memory semantics not re-audited. + +## Coverage and restrictions + +- **Entrypoints:** TUI preference falls back to DEFAULT (`cli/src/state/chat-store.ts:265`, `cli/src/utils/settings.ts:169–174`); the three modes map to `base2`, `base2-plan`, `base2-execute-plan` (`cli/src/utils/constants.ts:109–116`). `openbuff run` is the headless text/NDJSON path and defaults to `base2`, takes explicit `--agent`, or reuses a stored agent on `--continue` (`cli/src/index.tsx:795–804`; `cli/src/commands/run-command.ts:123–140,297–305,334–348`). FAST, FAST-NO-VALIDATION and `base-deep` are bundled alternate IDs, not TUI modes; deep inherits default roster (`agents/base2/base-deep.ts:329–359`). The prebuild scans official definitions and serializes generators; CLI consumes the generated registry (`cli/scripts/prebuild-agents.ts:22–82`; `cli/src/utils/local-agent-registry.ts:15–18,440–456`; `cli/src/utils/codebuff-client.ts:89–109`). Plain in-process SDK requires `agent` (`sdk/src/run.ts:681–685`); it uses host definitions/inline root, or fresh-state home registry if none (`sdk/src/run.ts:1884–1909`, `sdk/src/run-state.ts:857–868`), not the CLI bundle. Local unknown IDs fail rather than fetching remote definitions (`packages/agent-runtime/src/main-prompt.ts:91–117`, `sdk/src/impl/agent-runtime.ts:1392–1400`). Separately the SDK serve bridge helper defaults to legacy `base` if its host omits `agentId`, unlike CLI serve (`sdk/src/serve/bridge.ts:219–221`). +- **Roles:** generated roster counts are 38 default/execute/deep, 35 fast variants, 30 plan, each including internal `context-pruner`, which is filtered from provider catalog (`packages/agent-runtime/src/templates/prompts.ts:234–242`). Discovery: file-picker, general-agent, web/docs researchers, librarian, thinker (not FAST). Knowledge roles: retriever/reviewer/manager are retained across modes and proposal-only; not arbitrary memory writers. Implementation: editor/repair-editor in DEFAULT/EXECUTE_PLAN, root inline edits in FAST, test/doc writers and dependency-manager in implementation modes; Basher, debugger, review/security/specialist family and browser-use remain in PLAN for appropriate analysis (`agents/base2/base2.ts:552–600`). PLAN's narrower surface is intentional: no source edits, direct terminal, or writer delegation; runtime applies lineage restrictions even to child terminal/browser, with terminal requiring verified native read-only authority (`common/src/tools/plan-mode-policy.ts:1–29`; `agents/base2/base2.ts:15573–15585`). The `context-pruner` is internal bookkeeping, not a user delegation role. CLI admits project/parent agents according to trust; user definitions may override shipped IDs and are auto-added only to `base*` definitions with a roster (`cli/src/utils/local-agent-registry.ts:134–159,440–484`); SDK definition presence alone is not a spawn grant. The standard Base2 models must choose `spawn_agents` (generic schema + compact catalog, not per-agent native tools); a task's model ability to follow handoffs/confirm effects is not deterministic. +- **Tools and policy:** CORE provides index/search, file/outline/subtree, language navigation, recall, generic spawn; tool search/load exposes only permitted tiers on the next step, exact unambiguous search auto-loads, and fresh turns reset unlocks (`packages/agent-runtime/src/util/base2-tool-tiers.ts:29–97`; `packages/agent-runtime/src/tools/handlers/tool/tool-search.ts:31–78`; `packages/agent-runtime/src/util/agent-tool-names.ts:9–24,78–112`). `implement` adds the canonical transaction, environment/workspace and affected/build targets, scoped validation and only in EXECUTE_PLAN direct terminal; `audit` adds structural/completeness/review/task evidence. Broad findings are written by audit shards, not a general root edit privilege. Generator separately has inline spawn, git status, hooks and the audit/diff/environment/affected/build evidence tools (`agents/base2/spawn-contract.ts:57–75`); overlap with loaded model tools is intentional. Default uses direct reads and tightly scoped inline edits only for tiny work, self-contained editor/thinker handoffs for nontrivial work, independent bounded discovery waves for larger concerns, and joined validation/review, with dependency mutations explicitly separate from validation (`agents/base2/base2.ts:675–729,15453–15478`). These are prompt policies unless backed by a boundary; an ordinary focused task should not require a PLAN packet or full swarm. +- **Provider:** Base2 ships without a hardcoded template model (`agents/base2/base2.ts:352–363,475–478`); normal resolution is mode for named roots, per-agent, global default, then routable template model, or clear configuration error (`sdk/src/provider-config.ts:3132–3147,3234–3305`). FAST/deep IDs do not get a root mode route by ID and need an agent/global/default source; roots can be configured while child routes are missing, because readiness checks only the selected root (`cli/src/utils/openbuff-provider.ts:1095–1133`). Explicit `run --model`/SDK model is a captured run-wide override, including spawned actors, not merely a root chooser (`sdk/src/run.ts:1228–1229`; `sdk/src/host-config.ts:280–294`; inspected fake-wire test `sdk/src/__tests__/run-model-override.test.ts:323–353`). Check provider support/credentials for child model routes when configuring only mode-specific roots. No conclusion about live model adherence or provider quality. + +## Validation and domain receipt + +Ran eight hermetic Bun files (`roster-drift`, `base2-mode-policy`, `base2-progressive-tool-disclosure`, `base2-tool-loading`, `base2-writer-spawn-rules`, `plan-mode-spawnable-filter`, `run-command`, `cli-args`): **207 passed, 0 failed**. Two additional focused `base2.test.ts` cases (execute-plan prompt reuse and gate-disabled variant) passed. Offline probes inspected the generated bundle's initial/all-tiers surfaces/rosters, called the actual discovery handler, compared mode-gate initialization with emitted config, and checked the actual custom-agent registry/menu. SDK/ACP seam, dispatched mode authority and model behavior were inspected, not live-exercised. No live provider calls or source changes. + +Security: root/lineage trust, read-only mode presentation and registry filtering. Correctness/state: mode, persisted selection, tier reset, artifact claims, FAST policy. Errors: invalid ID, provider root readiness, spawn refusal; join policy inspected. Performance: tiered startup, scoped/bounded waves, FAST gate mismatch. Dependency hygiene: shipped bundling and route/agent obligations, separate explicit dependency mutation; no general dependency scan. Test/API: per-mode and entrypoint contracts and gaps above. Specialist internals, validation-gate algorithm, memory internals and generic dispatch mechanics are outside the shard except where necessary to establish a root boundary. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/runtime-tools.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/runtime-tools.md new file mode 100644 index 0000000000..5c261d6b76 --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/runtime-tools.md @@ -0,0 +1,87 @@ +# Runtime permissions — audit shard + +**Snapshot:** `6d5364de3`. **Verdict:** the canonical native path generally matches declaration and dispatch, but a declaration, provider schema, effective permission and usable host backend are four different things. The highest-priority gaps are Plan mode depending on a replaceable root template, executable discovery under non-agent directories, and delegation/MCP paths whose dispatch authority does not match the advertised surface. Roster, mode UX beyond the runtime handoff, role prompt quality and the validation/reviewer gate are covered by other shards. Findings are from static inspection; the tests listed below were existing local tests, not proof-of-concept runs. + +## Findings + +### RT-01 · High · Security / state · Replacing the Plan root can remove Plan enforcement + +The local TUI resolves `PLAN` to the ordinary ID `base2-plan`, then hands the resolved ID/definition and the merged registry to the SDK; it does not pass an independent Plan authority bit on this route (`cli/src/utils/constants.ts:109–114`, `cli/src/hooks/use-send-message.ts:131–142,891–907,1135–1159,1181–1186`; `cli/src/utils/create-run-config.ts:211–263`). Local definitions, including user-owned home definitions and trusted project Markdown, may replace a bundled definition by ID. The CLI's Plan spawn filter only runs on definitions that actually retain `programmaticConfig.planOnly` (`cli/src/utils/local-agent-registry.ts:426–461`; `sdk/src/agents/load-markdown-agent.ts:87–105`). The SDK likewise captures `mainPlanOnly` from the winning template/explicit object; descendants inherit that captured decision, and the native runtime guard consults the template marker (`sdk/src/run.ts:2176–2186,2424–2431`; `packages/agent-runtime/src/tools/plan-mode-guard.ts:18–40,137–149`). A local prompt-only definition reusing the reserved ID can therefore accidentally change the authority of a Plan-selected turn without any executable agent code. This is not an untrusted-project default or a failure of lineage once Plan has been latched. + +**Fix:** bind the operator-selected read-only mode to host admission independently of registry resolution, then project it into runtime, bridge and terminal restrictions; reserve the Plan root ID or diagnose overrides that cannot preserve it. Pin an end-to-end local CLI admission test for a same-ID prompt-only definition. + +### RT-02 · High (trusted-directory prerequisite) · Security / dependencies · Agent discovery imports executable session artifacts + +The SDK loader descends every directory except `skills`; recursion disables only Markdown, not executable formats. It imports each matching module before looking for an exported `id` or validating its definition (`sdk/src/agents/load-agents.ts:65–92,184–222,331–352`). Directory containment is not an agent-manifest check. This tree actually contains TypeScript outside the agent roster, e.g. `.agents/sessions/index-records-architecture-20261114/evidence/index-lifecycle-benchmark.ts`; its location alone does not exempt it from discovery in a trusted project load. This can run side effects, add incidental dependencies or delay startup without selecting any agent or invoking a tool. Project/parent discovery is opt-in; the same breadth applies to the user-owned home directory when loaded. The existing inert-artifact regression is about Markdown (`sdk/src/__tests__/load-markdown-agents.test.ts:133–153`). + +**Fix:** restrict executable discovery to explicitly configured definition entrypoints or documented entrypoint directories, exclude session/fixture/generated artifacts, and provide migration diagnostics for nested agents. Test that a non-agent module is not imported, not just absent from the result map. + +### RT-03 · Medium · Correctness / least privilege / API · Direct, generic and dispatch aliases disagree + +Direct mode builds a schema per resolvable child even when the parent has not granted `spawn_agents`; the stream translates a direct call to `spawn_agents`, whose executor then checks that canonical name against the model tool list. Thus a direct-mode definition with a valid `spawnableAgents` list but no model-facing `spawn_agents` can advertise a tool that dispatch refuses. Generic mode suppresses the schemas, not the alias translation, and translation uses the raw declared spawn list, not the published alias map. `context-pruner` is filtered from both provider presentations, but the generic handler authorizes against raw declarations and has no internal-only child check; its separate inline compaction path does have a permit. A provider schema enum and a prompt instruction are not an authorization boundary. This finding is about admission parity, not a demonstrated parent-history mutation. Legacy base IDs (`base`, `base-free`, `base-max`, `base-experimental`) also intentionally allow any registered child through generic validation, so their `spawnableAgents` is not a ceiling. Evidence: `packages/agent-runtime/src/templates/prompts.ts:226–242,317–364`; `packages/agent-runtime/src/tools/stream-parser.ts:614–626,715–740`; `packages/agent-runtime/src/tools/tool-executor.ts:3208–3231,4023–4041,4980–4996`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:248–277,285–376`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-inline.ts:119–143`; `common/src/tools/params/tool/spawn-agents.ts:252–285`; `agents/base2/base2.ts:417–422,550–558`. + +Two additional namespace edges: a direct alias is just the short ID with hyphens replaced by underscores, so colliding qualified short IDs can overwrite a schema before first-match dispatch; and SDK custom registrations reserve current native names, not removed stream aliases such as `apply_patch`. A custom tool with that name can be published but gets routed to the compatibility edit path, where the canonical grant and Plan checks still apply (`sdk/src/run-state.ts:285–305`; `packages/agent-runtime/src/templates/prompts.ts:230–232,343–361`; `packages/agent-runtime/src/tools/stream-parser.ts:388–410,610–625`). Unresolved spawn IDs are skipped in the direct ToolSet but can appear in the generic catalog/schema and fail only at dispatch (`packages/agent-runtime/src/templates/prompts.ts:206–212,343–350`; `packages/agent-runtime/src/templates/strings.ts:453–476`; `packages/agent-runtime/src/tools/tool-executor.ts:4045–4066`). + +**Fix:** resolve one per-step table of model-visible aliases, canonical targets and authorized spawn routes after validating the registry. Use it in both exposure and dispatch, reserve compatibility alias names and reject collisions at admission. Enforce internal-only status for all model-origin routes while retaining the runtime-owned harness permit. If legacy unrestricted spawning remains, expose it as an explicit trusted-host option. Existing schema tests verify presentation/transformation separately, not this matrix (`packages/agent-runtime/src/__tests__/prompts-schema-handling.test.ts:121–180,400–470`). + +### RT-04 · Medium · Least privilege / API · MCP attachment can publish more than the grant implies + +Custom tool publication normally requires a matching model-visible canonical name or alias. MCP selection is different: each configured server is discovered with `toolNames: null`, and unless that server has a model-visible scoped/alias selector, its whole compatible catalog is published. Explicitly selecting one server leaves unrelated servers in implicit-all mode; that behavior is pinned in tests. In particular, an MCP selector in **only** `programmaticToolNames` does not make that tool private when its configured server has no model selector. A nonempty handoff `allowedTools` can also remove a former server selector from `toolNames` without removing `mcpServers`, degrading from explicit selection to implicit-all. The executor accepts published MCP descriptor aliases and does not re-check MCP tools against the native/template name list. Plan mode's early discovery and dispatch refusal is intact. Evidence: `packages/agent-runtime/src/run-agent-step.ts:429–480`; `packages/agent-runtime/src/mcp.ts:32–65,98–160`; `packages/agent-runtime/src/tools/tool-executor.ts:4693–4714,4732–4815`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:539–549,612–625`; `sdk/src/__tests__/external-tool-consumers.test.ts:1243–1330`. + +**Fix:** separate server connection permission, provider-visible tool selectors and hidden generator selectors. Default new/scoped configurations to none unless explicit, make all-tools per server an affirmative compatibility grant, and preserve explicit-empty restrictions through handoff and transport. Use inert catalog fixtures to test model and generator reachability, including handoff narrowing. + +### RT-05 · Medium · Security / API · Handoff path scopes are advisory, not least-privilege confinement + +`AgentTemplate.filesystemScope` is documented in the type as runtime-enforced, and a versioned handoff can narrow derived patterns. But the executor intentionally only warns on in-project glob mismatches; project containment, SDK authorization and tool-specific controls are separate. `allowedTools: []` means unchanged, not deny-all; hidden programmatic declarations and the child's own spawn roster survive a nonempty handoff. This is intentional compatibility behavior, but embedders must not treat a scoped handoff as an enforced pathname/descendant ceiling. This does **not** negate strict project reads, the mutation broker, the review requirement on managed-worker writes or the dedicated findings writer's own checks. Evidence: `common/src/types/agent-template.ts:183–191`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:528–625`; `packages/agent-runtime/src/tools/tool-executor.ts:3344–3405`; `packages/agent-runtime/src/__tests__/spawn-agents-permissions.test.ts:384–495`; `packages/agent-runtime/src/__tests__/run-programmatic-step.test.ts:1730–1780`. + +**Fix:** clearly call current globs advisory in the public types and UI. Offer a host-enforced, monotonically inherited worktree/path/tool ceiling for callers that need confinement, with an explicit deny-all option and tests across native, callback, terminal and descendant paths. Keep `strictProjectReads` distinct: it is a guarded project boundary, not a general handoff glob sandbox. + +### RT-06 · Medium · Errors / state / API · Early refusal and partial spawn outcome can disappear from structured results + +A native pre-handler Plan refusal emits an error event and returns without appending a tool result. Generator yields get only the result for their own call ID, default to `[]`, and an explicit `includeToolCall: true` inserts an assistant call before dispatch. On this path there is no paired result from the refusal, unlike the external Plan path, which synthesizes a typed result for `handleSteps`. The model stream has a separate `TOOL_CALL_ERROR` recovery message; it does not fix generator or SDK-result parity. An ordinary Plan-owned job's `kill_job` request using the otherwise supported `job_id` input alias also fails here: the guard reads **raw** `input.jobId` after parsing, not the normalized input. Evidence: `common/src/tools/params/input-aliases.ts:127`; `packages/agent-runtime/src/tools/plan-mode-guard.ts:151–165`; `packages/agent-runtime/src/tools/tool-executor.ts:3172–3209,4693–4714`; `packages/agent-runtime/src/run-programmatic-step.ts:662–668,1108–1138,1218–1249`; `packages/agent-runtime/src/tools/stream-parser.ts:328–365`. The Plan regression asserts the event and absence of forwarding, not the paired generator result (`packages/agent-runtime/src/__tests__/plan-mode-dispatch.test.ts:116–155,181–236`). + +Mixed generic spawn batches have a related API mismatch: prevalidation emits prose and drops invalid entries when any valid sibling remains; the handler returns a report per entry of the **filtered** batch. Consequently a joiner's JSON cannot account for every originally requested child by index, even though valid launches are preserved (`packages/agent-runtime/src/tools/tool-executor.ts:4086–4124,4167–4176,4200–4209`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:1316–1399`). A later handoff/candidate validation failure instead rejects the handler preflight as a batch, before background launch (`spawn-agents.ts:253–339`, same directory). + +**Fix:** standardize typed, correlated pre-entry refusals for generator consumers; pair or omit synthetic transcript calls atomically. Check Plan ownership with validated input. Preserve the original spawn indices and per-entry rejection reason in the parent receipt, and pin mixed denied/missing/valid cases against actual stream-to-handler dispatch. + +### RT-07 · Medium · Security / dependencies · Requested process supervision can silently degrade for callers + +The SDK supervisor is capability/runtime-dependent. A requested but unlaunchable setup logs a warning and runs in-process; the runtime similarly falls back if the flag resolves on but no seam was wired. Pruner execution is intentionally in-process to propagate permitted parent history changes, and is a separate case. Process supervision is not equivalent to strict native tool enforcement; the Plan terminal path independently fails closed. Evidence: `sdk/src/impl/agent-runtime.ts:106–155,1162–1196`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:4350–4386`; `packages/agent-runtime/src/__tests__/spawn-process-supervision.test.ts:938–970`. Browser-use likewise requires Chrome/Chromium and uses an owner-scoped session, but the SDK can choose Chrome's `--no-sandbox` compatibility path when its sandbox probe determines the sandbox cannot work; do not describe browser inspection as an OS or network isolation guarantee (`sdk/src/run.ts:2824–2827,3924–3942`; `sdk/src/tools/browser-logs.ts:872–933`). + +**Fix:** distinguish `prefer` from `require` for process supervision; expose the selected backend/decline reason in typed run metadata and reject incompatible launches for `require`. Surface browser sandbox availability separately from browser-action policy, and require verified isolation or explicit host opt-in to degraded Chrome for hosts browsing untrusted pages. + +### RT-08 · Low · API / help / test coverage · Registered does not mean available in this host + +No missing canonical native handler was identified: schema/name parity is tested and the runtime handler map is exhaustive over `ToolName` (`common/src/tools/__tests__/tool-registration-consistency.test.ts:37–65`; `packages/agent-runtime/src/tools/handlers/list.ts:85–164`). Nonetheless, `ask_user` is public and has a registered handler, which delegates to the client; plain SDK dispatch needs a host override, whereas Serve installs one. Without it the SDK falls through to `Tool not implemented in SDK` (`common/src/tools/constants.ts:96–105`; `common/src/tools/list.ts:184–189`; `packages/agent-runtime/src/tools/handlers/tool/ask-user.ts:8–23`; `sdk/src/run.ts:5583–5601,6329–6355`; `sdk/src/serve/bridge.ts:902–908`). `browser_logs` and progressive controls are valid runtime names, not all public generated starter names; `browser_logs` is deliberately used by the internal browser agent (`agents/browser-use/browser-use.ts:153–158`; `common/src/tools/__tests__/tool-registration-consistency.test.ts:85–126`). Also, the short/full textual help and inherited-child instructions are not built from the final provider ToolSet; the inherited-child addendum literally lists static `toolNames` while actual MCP aliases, synthetic spawns or derived tools can differ. The TUI `/help` is a shortcut banner, not an effective-capability query (`packages/agent-runtime/src/tools/prompts.ts:419–459,486–526,536–649`; `packages/agent-runtime/src/templates/strings.ts:418–456`; `cli/src/commands/help.ts:5–13`). `scripts/check-tool-registration.ts:73–148` uses several source-text presence probes including an SDK equality check; these do not distinguish runtime-only, host-only and actually dispatchable client tools. + +**Fix:** expose a redacted effective-capability/diagnostic view (provider alias, canonical identity, generator-only, integration unavailable/why), and use it for help and admission warnings. Validate `ask_user` availability or return a typed unavailable/skipped result. Add an executable reachability contract over native/runtime-only/host-delegated descriptors, not just generated-type/source-presence checks. + +### RT-09 · Low · Performance / state · Discovery and settlement have avoidable repeat work + +Prompt placeholders can discover external schemas through a turn-local, tier-keyed cache, but the initial ToolSet and each tier change run separate external discovery against the actor. One configured server that is slow to list can hold the whole publication until settlement; the SDK caps each discovery operation at 15 seconds. Direct schemas resolve child templates serially, then catalog rendering resolves them again. Reusing actor- and generation-bound, in-flight discovery with cancellation would reduce startup/catalog drift without reusing parent authority. Evidence: `packages/agent-runtime/src/run-agent-step.ts:2350–2396,2535–2566,3399–3424`; `packages/agent-runtime/src/mcp.ts:50–71,168–181`; `sdk/src/run.ts:4159–4198`; `packages/agent-runtime/src/templates/prompts.ts:343–361`; `packages/agent-runtime/src/templates/strings.ts:453–476`. Separately, detached spawn settlement can retain a journal interest via an unbounded retry loop during durable-store failure (`packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:595–603,654–681`). Bound/fence this to an owning lifetime with an observable unconfirmed-retention state rather than silently treating failed persistence as success. Neither issue was benchmarked. + +## Verified runtime map and prerequisites + +| Layer | What is actually usable / enforced | Evidence | +|---|---|---| +| Common schema → SDK root | TS/generated definitions admit extension strings; Zod defaults model tools and spawn lists to empty, `direct` by default. Markdown accepts only canonical native names, with no executable metadata. `OpenbuffClient` accepts an ID or definition; an explicit root object wins its ID, a supplied nonempty roster skips home discovery, otherwise home-only by default. The SDK has no automatic CLI roster or remote registry fallback. Continuation can merge definitions by ID. | `common/src/types/agent-template.ts:162–192`; `common/src/types/dynamic-agent-template.ts:191–222`; `sdk/src/agents/load-markdown-agent.ts:76–109`; `sdk/src/run.ts:1889–1908`; `sdk/src/run-state.ts:239–255,857–870,1348–1359`; `sdk/src/impl/agent-runtime.ts:1392–1401`; `sdk/README.md:113–118`. | +| CLI add-ons and project custom definitions | CLI merges the trusted-source roster into bundled entries, automatically adds local IDs to `base*` spawn lists, filters known Plan rosters, and separately attaches MCP config to `base*` templates. Project and parent `.agents`/MCP require trust on this path. `.agents/notion-agent.ts:17–29` and `.agents/notion-researcher.ts:21–38` declare only search/fetch against a pinned launcher; availability needs allowed stdio execution, `npx`/the package, trusted env for `NOTION_TOKEN` and a functioning peer. `.agents/lib/create-cli-agent.ts:48–67` and `.agents/claude-code-cli.ts:15–46,106–128` illustrate registered terminal use with `tmux-test`, the local `scripts/tmux/tmux-cli.sh`, `tmux` and the named installed/authenticated CLI; registration does not install any of them. SDK callback tools instead need a host definition/handler; the SDK validates original Zod input and checks declared path parameters after parsing, not arbitrary callback behavior. | `cli/src/utils/local-agent-registry.ts:140–172,199–224,426–492`; `sdk/src/agents/load-agents.ts:95–110,247–260`; `sdk/src/run-state.ts:281–335`; `sdk/src/run.ts:5430–5577`. External packages/binaries were not invoked or scanned. | +| Provider → stream → handler | Provider publication uses registered native schemas, the per-step model allowlist including tier changes, optional aliases and derived `set_output` for structured agents without an explicit hidden version. `runOutputSchema` explicitly moves root `set_output` to the model. SDK strips inline effects from advertised definitions and streams accepted calls; legacy no-native-tool compatibility uses text instructions/history, whereas named candidates marked unable to meet required tool capability are rejected. Both native and text calls reach the stream router. `handleSteps` separately checks visible + hidden declarations plus `add_message`, `set_messages`, `set_output`, `end_turn`; its default result context is provider-neutral and it uses common dispatch. `apply_patch`/`apply_smart_patch` text/model compatibility normalizes to the existing `edit_transaction` authority, not a separate grant. | `packages/agent-runtime/src/util/agent-tool-names.ts:72–108`; `packages/agent-runtime/src/run-agent-step.ts:1876–1892,2487–2571,3399–3424,3899–3913`; `packages/agent-runtime/src/run-programmatic-step.ts:955–975,1069–1148,1224–1249`; `packages/agent-runtime/src/tools/stream-parser.ts:388–410,610–626,705–761,873–881`; `sdk/src/impl/llm.ts:1415–1427,1457–1475,1716–1787,2318–2334`. | +| Child, supervision, worktree | Normal siblings get the child's derived capabilities, not the parent's ToolSet; only native order can align. Joined results carry child output/receipts and failure status; detached jobs return a job ID and settle via owned polling/inbox, with no-custody workers refusing detached entries. Supervised bridging binds actor/action/input, reconstructs supported schemas, maintains generation and cleanup boundaries; unsupported dependencies return typed failure, not dummy success. Ordinary spawn is not worktree creation/isolation. Managed workspace workers are a separate host/grant path bound to a real worktree: fresh no-shell/no-spawn tool set, strict read view for read grants, write grants require exact operator edit review, dispatch checks ownership and tool set. Worktree-wide jobs are separately gated and not assumed in virtual/replayed runs. | `packages/agent-runtime/src/run-agent-step.ts:484–540,2555–2571`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agents.ts:209–227,1019–1043,1073–1092,1316–1399`; `packages/agent-runtime/src/supervision/child-entry.ts:245–268,466–481,826–828`; `sdk/src/impl/agent-runtime.ts:253–346,582–661`; `sdk/src/services/workspace-worker-host.ts:83–146`; `sdk/src/run.ts:3323–3333,3644–3680`. | +| Plan and strict reads | Known native workspace mutators are refused before handlers; allowed plan artifacts are explicitly listed. Plan external callbacks and MCP discovery fail closed, regardless of peer read-only hints. Plan terminal requires verified native exact-env/filesystem/network/process-tree capability, has no portable fallback, refuses terminal overrides, and tracks owned Plan jobs. Execute terminal's undeclared role profile defaults to `full-access` subject to host controls; declared `read-only`/`workspace-write` lexical checks are not OS enforcement. Browser interaction policy is independent, denies active interaction on Plan ancestry but permits inspection/navigation. Strict project reads are distinct and require a guarded reader, allowlisted tools and no overrides; unsupported adapters fail closed. | `common/src/tools/plan-mode-policy.ts:16–58`; `common/src/util/execution-context.ts:48–63`; `packages/agent-runtime/src/tools/plan-mode-guard.ts:129–167`; `packages/agent-runtime/src/tools/handlers/tool/run-terminal-command.ts:29–99`; `sdk/src/run.ts:2580–2632,3662–3695,5603–5623,5798–5840`; `sdk/src/tools/terminal-profile-bound.ts:11–23,52–83`; `common/src/tools/browser-policy.ts:1–15,56–73`; `sdk/src/run.ts:4235–4269`. | +| Optional integration readiness | MCP discovery and calls use host-captured config/origin and request-owned scopes; client-origin first calls require approval, stale catalog generations refuse, schema/discovery errors remove unavailable descriptors rather than retrying an arbitrary name. `browser_logs` uses the host Chrome executable; the separate `web_search` browser route needs a managed process view and the verified **0.41.2 Linux x64 GNU** `agent-browser` binary, plus Chrome, and can surface an unavailable route. `@modelcontextprotocol/sdk` is declared; npm/Chrome/third-party CLI tools and native plan provisioning remain external prerequisites, not implied by a `toolNames` entry. | `sdk/src/run.ts:2100–2148,3924–3943,4159–4198,5292–5368,5962–5987`; `sdk/src/services/run-mcp-execution.ts:25–126`; `sdk/src/tools/agent-browser-process.ts:27–100`; `sdk/package.json:59–70`. | + +## Coverage and verification + +| Audit domain | Coverage | +|---|---| +| Security | Trust/identity, least privilege and Plan admission/dispatch, child/bridge and optional process boundaries (RT-01–05, RT-07). | +| Correctness | Canonical schema vs aliases, staged exposure, result/argument normalization and local registry resolution (RT-03, RT-06, RT-08). | +| State | Per-turn tool tiers, immutable actor ancestry, ownership, catalog generation, partial spawn and detached settlement (RT-01, RT-06, RT-09). | +| Error handling | Missing registrations/backends, invalid/stale aliases, pre-dispatch/handler outcomes and unconfirmed settlement (RT-03, RT-06–09). | +| Performance | Discovery/topology repeated work and bounds; static only (RT-09). | +| Dependency hygiene | Checked declared SDK MCP dependency and optional binary/config/process prerequisites; no version advisories, installation or live probes (RT-02, RT-07, runtime map). | +| Test coverage | Verified existing tests below; gaps called out per finding, especially registry-to-provider-to-dispatch equality and per-child result alignment. | +| API/ABI | Public vs runtime/starter/help tools, host overrides, name/alias compatibility, typed refusal and child result contracts (RT-03–08). | + +**Executed:** Bun 1.4.4, 156 passes, zero failures in nine existing files. First group (87): `common/src/tools/__tests__/tool-registration-consistency.test.ts`, `agents/tool-reachability.test.ts`, `packages/agent-runtime/src/__tests__/prompts-schema-handling.test.ts`, `packages/agent-runtime/src/util/__tests__/agent-tool-names.test.ts`. Second group (69): runtime `plan-mode-dispatch.test.ts`, `plan-mode-external-tools.test.ts`, `spawn-agents-permissions.test.ts`, `browser-logs-policy.test.ts` and SDK `sdk/src/__tests__/plan-mode-external-tools.test.ts` (blocks provider requests; uses local fixtures). The SDK MCP catalog/runtime cases in `sdk/src/__tests__/external-tool-consumers.test.ts:1063–1450`, native Plan controls in `sdk/src/__tests__/native-host-integration.test.ts:595ff`, supervised and managed-worker tests were inspected, not executed. No live services, new probes, or source edits. diff --git a/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/testing.md b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/testing.md new file mode 100644 index 0000000000..3fbd0235bf --- /dev/null +++ b/.agents/sessions/audit-agent-tool-coverage-2026-11/findings/testing.md @@ -0,0 +1,35 @@ +# TEST shard — design, execution, observation, retry, and proof + +Snapshot: `6d5364de3ec8416aa80ecd28c13d1257c1ceab99`. Reviewed the shipped roles, runtime/SDK dispatch and evidence, command discovery, package/CI/eval selection and prerequisites. The reviewer gate's verdict and clearance algorithm are out of scope; coverage-repair invocation and test evidence are in scope. No source edits, installs, network, live providers, or live browser/tmux/native process runs. + +## What really runs + +| Surface | Effective behavior and evidence | +|---|---| +| `test-writer` | Test design/authorship via `read_files`, `read_outline`, `edit_transaction`, `set_output`; no terminal or subagents. Structured writer intent includes changed/no-op, evidence, requirement/acceptance IDs, unresolved items, requested validation, not execution proof. `agents/test-writer/test-writer.ts:20–30,34–92,98–135`. Base2 offers it outside plan mode; automatic path derives environment → affected tests → build targets, attempts one inline writer per workspace and then Basher; coverage repair has a separate generic spawn (`agents/base2/base2.ts:560–598,2511–2727,7037–7149`). Both automatic handoffs currently fail admission (TEST-01); manual writer capability differs. Test-first is a prompt preference for a pre-implementation handoff, not an observed deterministic red→green pipeline. | +| `basher` / `debugger` | Basher is deterministic, not a second model: required `params.command`, `run_terminal_command` → hidden `set_output`; `SYNC` for tests, `BACKGROUND` returns job ID, not proof of exit (parent `check_job`/`read_logs`). Runtime-tagged permission/refusal and log evidence are important. Basher's declared `workspace-write` binds lexically; plan ancestry forces native read-only execution or refusal. Debugger programmatically attempts `reproduce_command`, reads `suspect_files`, then uses `read_files`/`read_outline`/`code_search`/terminal/`git_status` for diagnosis; prose-only output and prompt-only three-attempt limit. `agents/basher.ts:15–88,233–269`; `agents/debugger/debugger.ts:17–78`; `sdk/src/tools/terminal-profile-bound.ts:9–30`. | +| `tmux-cli` / `browser-use` | tmux agent is not `scripts/tmux/tmux-cli.sh`: it emits an inline Bash helper, starts a session, captures terminal state, and asks its model to return `overallStatus`, results/issues and paths under `/tmp`. Requires Bash, tmux/socket, writable temp and POSIX helpers; optional ANSI strip uses Perl. Browser-use exposes `browser_logs`, `read_image`, `set_output`, `add_message`, not terminal/server startup. Its backend is SDK Chrome/Chromium CDP, not the separately managed `agent-browser` web-research daemon. Needs host browser execution authority and an installed Chrome/Chromium (`CHROME_PATH`/`CHROMIUM_PATH`, Linux/macOS/Windows candidates); owner cleanup at run end. `agents/tmux-cli.ts:111–171,294–450,499–539,749–766`; `agents/browser-use/browser-use.ts:30–57,139–152`; `sdk/src/tools/browser-logs.ts:306–339,2385–2400,3090–3136`; `sdk/src/run.ts:4619,5971–5986`. | +| `evaluator` / `integration-agent` | Evaluator is an independent **static** reviewer: source, task, bundle, workspace, structural/feature inventory, structured requirement coverage; no shell/agent spawning. Integration is advisory, adds environment/test/build discovery and `read-only` terminal capability, with a bounded diagnostic-command contract in the prompt, not a suite planner/executor with a trusted test count. Neither supplies run proof just by reporting success. `agents/specialists/evaluator.ts:2–13`, `integration-agent.ts:2–15`, `create-specialist.ts:212–244,246–278`; base2's evaluator trigger is requirement-language matching (`agents/base2/base2.ts:1027–1043`). | +| Hooks / targeted | Default configuration has no hooks and inferred hooks disabled. Untrusted project declarations cannot enable them; managed workers get no captured hooks. Opt-in inference on this checkout returns **only** `bun run 'typecheck'` for JS/TS files, not `bun run test`. Explicit matching hooks run in the captured cwd/environment/terminal policy; timeout defaults to no local cap; `runPerFile` appends ≤50 arguments as a sequential `&&` chain per hook. No config/no match is explicit, not a test pass. Targeted takes `{snapshot_id,files,artifact_kinds?}`, uses same hook executor, recomputes Git/content identity before/after, returns results/status/assurance; kinds are echoed labels, not selectors. Not an immutable checkout or requirement proof. Durable native validation receipt observer separately recognizes actual terminal runs and file-change hooks, not targeted (`sdk/src/run.ts:3783–3811,4072–4100`). `sdk/src/provider-config.ts:615–631,967–968,1543–1563`; `sdk/src/run.ts:1676–1685`; `sdk/src/tools/file-change-hooks.ts:47–53,507–653,1620–1710,1837–1865`; `common/src/tools/params/tool/run-targeted-validation.ts:10–39`; `sdk/src/tools/get-change-review-bundle.ts:647–716`; `docs/agents-and-tools.md:198,217–228`. | +| Root / CI / platform schedules | Root `bun run test` selects eight workspace scripts, omits `.agents`, `code-map`, `internal`, Rust (`package.json:30`); `check:ci-local` tests only full agents/common schedules in addition to guards (`scripts/check-ci-local.ts:20–24,56–57`). Agents/.agents use `bun test __tests__` (`agents/package.json:6–9`, `.agents/package.json:6–8`), not agents/e2e or the standalone Browser smoke. CLI runner uses sorted `.test.ts`/`.test.tsx`, only excludes `.integration.test.ts`, native OpenTUI preload, `--isolate`, `NODE_ENV=production`, and an empty-discovery guard (`cli/scripts/run-cli-tests.ts:34–57,67–104,111–161`); indexer script adds isolate, SDK/common/runtime/scripts/evals bare Bun scripts do not share CI's explicit filters. SDK-local `sdk/bunfig.toml:6–12` does not exclude integrations. Normal CI unit matrix (11 legs) uses the three package scripts above and explicit non-`.integration.test.ts` isolation elsewhere; builds SDK/CLI bundles and sets `CODEBUFF_WASM_DIR` for code-map. Separate four-leg integration matrix (CLI/common/runtime/SDK) selects only `.integration.test.ts` with timeout, not CLI's full unit preload/isolation; Rust workflow builds five targets but only host-compatible legs run tests and two run smoke. `.github/workflows/ci.yml:169–191,258–313,368–374,441–462`; `.github/workflows/rust-workspace.yml:45–58,74–99,132–142`; `docs/testing.md:32–57,182–228`. | +| E2E / evals | Nightly E2E runs `agents/test:e2e` (generator-boundary deterministic fixtures included, not listed by agents' default script), not SDK E2E. SDK tests named `*.e2e.test.ts` are selected by ordinary CI filename discovery; `sdk/e2e/utils/get-api-key.ts:3–22` uses mocks, `skipIfNoApiKey` always false. BuffBench PR subset: three fixed commit tasks, dry-run config check, live only with provider keys; nightly full set with live provider/judge; optional per-task final checks run only when configured, not a replacement for behavioral assertions. `docs/testing.md:282–295`; `.github/workflows/nightly-e2e.yml:62–70`, `eval-pr-subset.yml:11–28,67–108`, `nightly-evals.yml:61–95`; `evals/buffbench/main-nightly.ts:38–52`, `agent-runner.ts:237–255`; `evals/README.md:23–33`. | + +## Findings + +1. **TEST-01 · High · correctness, permissions/API, regression coverage — both automatic test-writer spawns are rejected.** The initial handoff requests standalone `write_file`/`str_replace` in addition to `edit_transaction` (`agents/base2/base2.ts:2643–2650`); the reviewer-coverage retry requests the same forbidden tools *instead of* `edit_transaction` and restricts writes to pending/finding-listed paths (`agents/base2/base2.ts:7113–7130`). Test-writer declares only `edit_transaction` for mutations (`agents/test-writer/test-writer.ts:91,103`). Both spawn handlers actually call `deriveSpawnTemplateCapabilities` (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-inline.ts:176–182`, `spawn-agents.ts:277–283`), which throws on non-static mutators (`spawn-agent-utils.ts:539–563`). **Observed:** passing both exact allowlists to that runtime function rejects both with `Handoff attempted to widen test-writer tool authority with: write_file, str_replace.` Thus a generator test fed a synthetic successful child can hide the real failure (`agents/__tests__/base2-writer-spawn-rules.test.ts:519–541,675–719`). Fix the handoffs, permit scoped new test files on retry, and test real child admission plus a new-test transaction using the bundled definition and scripted provider. +2. **TEST-02 · High · security, state — the test-only write boundary is advisory.** Test-writer says not to modify source and advertises test globs, but its static read list starts with `**/*`; generic handoff narrows patterns and executor merely logs an in-project scope mismatch even for writes (`agents/test-writer/test-writer.ts:73–103`; `packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:565–588`; `packages/agent-runtime/src/tools/tool-executor.ts:3355–3408`). Project containment and edit capabilities are separate controls, not a test-only ceiling. A manual or correctly admitted writer can modify production given a valid in-repo edit capability; writer output can expose unrelated in-repo reads. Fix with a test-writer-specific mandatory normalized+canonical write/read scope (including destinations) and audit attestation; exercise manual, inherited, move/rename and scope-escape cases. Do not treat `filesystemScope` globs alone as authorization. +3. **TEST-03 · High · correctness, API, failure proof — command failure can collapse to green.** Automatic Basher path always requests a summary (`agents/base2/base2.ts:2691–2713`); summary builds text from `errorMessage` but drops `errorMessage`, `executionRefusal`, `permissionDenied`, `timedOut`, `spawnFailed`, cleanup and runner overflow metadata, and emits `exitCode` only if present (`agents/basher.ts:293–299,360–367,400–431`). `detectCommandFailure` looks for structured error/nonzero/success=false/status=failed and returns null for absent success proof (`agents/base2/base2.ts:15259–15288`). **Observed** mock denial with no exit code became only `message`/`extractedLines`; the raw path preserved typed refusal. After TEST-01 this can turn admission denial, timeout, missing output or result with zero executed tests into a pass-looking aux event. Fix by preserving the native terminal receipt (including `fullLogPath`/persistence) under a stable field, requiring affirmative exited/zero/clean status plus runner-recognized nonzero test count for **test** credit, and distinguishing background start, no tests, refusal and abort. The advertised omitted 120s timeout is also stale (`agents/basher.ts:51–54,177–183`; `sdk/src/services/terminal-timeout-policy.ts:6,62–79`); explicitly bound suite/profile time and surface idle vs timeout. Full-log wrapper predeclares a retained `/tmp` path even on refusals (`agents/basher.ts:190–228,371–374,424–429`); use private native log storage, publish only verified paths, never sweep a global writable namespace or silently mask a `tee` failure behind the suite exit. +4. **TEST-04 · High · security, correctness, dependencies — task-specific terminal labels don't enforce the advertised execution boundary.** Non-plan only `read-only` and `workspace-write` bind; SDK replaces the child profile with captured host policy (`sdk/src/tools/terminal-profile-bound.ts:9–44`; `sdk/src/run.ts:5827–5861`). Default unrestricted host may run tmux/debugger with `full-access` (`sdk/src/host-execution.ts:128–130`); an actually selected `validation-diagnosis` host profile refuses before launch as unimplemented (`sdk/src/tools/run-terminal-command.ts:1412–1417`). **Observed** exact generated tmux setup around harmless `printf ok`: lexical `full-access` allows; `tmux-test` refuses fixture writes; `workspace-write` refuses the wrapper as inherited-env dumping. Not a browser/tmux execution test. Do not loosen a shell regex to make the whole helper pass: implement an owned PTY/tmux executor with narrow argv, validated labels/paths, finite lifecycle and typed start/exit/capture/cancel results; implement a separately scoped debugger adapter. Test real dispatch on declared/host/plan combinations. Existing tmux tests parse Bash and simulate yields (`agents/__tests__/tmux-cli.test.ts:8–15,61–115,138–159`). +5. **TEST-05 · Medium · state, error handling — UI smoke has incomplete/ambiguous teardown and observations.** tmux setup interprets admission refusal (`errorMessage` with no stdout/stderr) as a generic `/tmp` failure and exits before teardown, and initial capture ignores exit status (`agents/tmux-cli.ts:541–599,603–620,749–766`). Wait-idle silently treats a vanished pane as empty output and exits 0 on timeout, while session alive means outer Bash alive, not target succeeded (`agents/tmux-cli.ts:348–360,419–450`). Output schema does not require a check or nonempty captures for success (`agents/tmux-cli.ts:26–46,77–117`); no post-exit assertion. Fix by acquiring cleanup ownership before partial setup, distinguish target death/silence/deadline, propagate structured refusal/cleanup result, use a private socket and directory, and require assertions referencing actual capture IDs, not just a pane string or `overallStatus`. Debugger likewise discards the programmatic reproduction receipt and proceeds to model inference even on pass/denied (`agents/debugger/debugger.ts:49–76`); return structured reproduction/attempt/line evidence, keep retry limits in runtime and rerun the originally failing case after repair. +6. **TEST-06 · Medium · correctness, traceability — writer completion does not prove any requested behavior was asserted.** Automatic group gets generic `tests-required`/`tests-written`, a path list (not concrete symbol/contract summaries), and a package command (`agents/base2/base2.ts:2584–2630`). Child requirement and criterion arrays are copied as claims (`packages/agent-runtime/src/tools/handlers/tool/spawn-agent-utils.ts:2986–3009`); parent validates changed-file count or nonempty no-op evidence, not requirement IDs/test names or unresolved items, extracts `requestedValidation` but actually runs only `group.testCommand` (`agents/base2/base2.ts:2663–2713,15105–15147`). It can misattribute an unrelated existing green suite and, on first group failure, break out and mark writer done, leaving later groups unattempted (`2714–2727`). Fix with per-criterion test path+case+assertion mapping, parent-selected and runner-attested command/cwd/count/skip/test IDs on an identified snapshot, red-before/green-after evidence for regression tasks where feasible, independent review for omissions, and retain per-group failed/skipped/not-attempted states for targeted retry. +7. **TEST-07 · Medium · selection accuracy, shell safety, performance — affected/build intelligence is not a runnable test plan.** `get_affected_tests` checks four same-extension sibling patterns; graph is unwired, coverage empty, and the two async collectors repeat path/ownership/candidate probes despite the shared discovery cache (`sdk/src/tools/get-affected-tests.ts:6–38`; `sdk/src/services/harness-intelligence.ts:1585–1596,1683–1719,1943–1970,2036–2057`). **Observed** it finds tmux agent unit tests but misses `cli/src/__tests__/run-cli-tests.test.ts` and `sdk/src/__tests__/run-targeted-validation.test.ts` for their implementation files. `get_build_targets` has advisory manager commands plus optional owning targets (bounded to 500; Cargo/Go probes require local toolchains); root selector consumes only `targets`, not impact tiers, owning targets/confidence or selected test names (`sdk/src/tools/get-build-targets.ts:13–34`; `sdk/src/services/build-graph.ts:5–12,57–59,717–741`; `agents/base2/base2.ts:12460–12540`). CLI fallback uses raw `bun test` (documented non-parity/stall) rather than package runner (`agents/base2/base2.ts:12325–12355`; `docs/testing.md:76–125`). Raw `cd ${root}` also breaks workspace paths with spaces and interprets repository-controlled shell metacharacters before the test; project-path containment is not shell escaping. Fix by passing validated `cwd`/argv separately, selecting scope with verified project script and framework filters, retaining explicit missing coverage/partial scan markers, and reusing indexed deps/probe results. Adopt non-JS conventions (`test_*.py`, Go `_test.go`, JVM `src/test`) without fabricating coverage. +8. **TEST-08 · Medium · targeted-validation API/security, performance — mismatched filesystem and weak result shapes.** Direct hooks refuse `fs.hostProcessView === false`; targeted passes the same adapter to hook inference but takes host Git identity and executes host commands without the equivalent guard (`sdk/src/run.ts:6040–6058,6128–6150`; `sdk/src/tools/run-targeted-validation.ts:59–115`). A custom FS may receive proof for a different host checkout. Targeted's negative-list classification can promote an empty/unknown *record* to `passed/full` (as opposed to a missing result list, which skips) (`sdk/src/tools/file-change-hooks.ts:1709–1735`; `sdk/src/tools/run-targeted-validation.ts:105–166`). Requested kinds cannot attest execution of that kind. Fix host/adapter identity parity, positive validation result variant and explicit executed check kinds, preserve independent cancellation (line 39 currently selects execution signal over caller, also `get-change-review-bundle.ts:653`), bound matching hook concurrency, and serialize checks known to share mutable caches/build outputs. Add malformed/mixed/refusal/custom-adapter regressions alongside existing stale/drift/identity tests (`sdk/src/__tests__/run-targeted-validation.test.ts:219–332,557–680`). Pre/post identity does not attest ignored inputs, dependencies or transient mutate-and-revert. +9. **TEST-09 · Medium · browser proof/security — standalone smoke returns success without validating browser behavior.** `agents/browser-use/browser-use.test.ts:29–48,71–75,119–138,190–208` asks for interactions in two tasks but passes only URL; default runtime blocks click/type, `success = output?.type !== 'error'` accepts typed failure/partial/missing output, and summary doesn't fail exit on failed checks. Outside plan, the handler checks the caller/model-supplied opt-in string, not an independent user approval receipt (`packages/agent-runtime/src/tools/handlers/tool/browser-logs.ts:40–59`; `common/src/tools/browser-policy.ts:62–74`); inspection still navigates real URLs and is not a no-network setting. Console/network claims are bounded action windows, not full coverage; trim exists but is not conveyed to diagnostic assertions (`sdk/src/tools/browser-logs.ts:797–812,2541–2560,2971–3021`). Fix with runtime-bound interaction/origin grants for interactive tests, an owned deterministic local fixture, assert `overallStatus`, event evidence, exact step conditions and nonzero exit on insecure/incomplete/skipped required steps, emit persisted artifact IDs and explicit truncated windows. Keep separate opt-in tests for real Chrome/egress cleanup instead of treating policy-unit passes as browser runs. +10. **TEST-10 · Medium · CI and dependency coverage — schedule/skip truth is not uniform.** Observed 346 CLI unit paths (includes `integration-tmux.test.ts` and a `.integration.test.tsx`); legacy tmux test is selected but skips itself on CI, as does integration-lane `rerender-perf` (`cli/src/__tests__/test-utils.ts:11–25`, `integration-tmux.test.ts:15–19,47–49`, `rerender-perf.integration.test.ts:145–146`). CI does run the distinct Linux managed-worker fixtures if tmux is present (`managed-workers.integration.test.ts:6–9`). Browser-cleanup requires explicit Linux `CHROME_PATH`; browser-research additionally needs pinned native executable and Linux x64; native plan integration requires Linux x64, `OPENBUFF_TEST_PLAN_NATIVE=1`, trusted artifact and bubblewrap (`sdk/src/__tests__/browser-cleanup.integration.test.ts:18–21`, `browser-research.integration.test.ts:25–34`, `plan-terminal-native.integration.test.ts:22–26,94–101`; `docs/testing.md:182–207`). CI integration does not provision the explicit browser/native opt-ins (`.github/workflows/ci.yml:368–462`); no suffix matches intentionally echo-success for currently empty common/runtime inventory, and `find ... 2>/dev/null` can hide partial or broken discovery in both matrices. SDK-local `bun run test` is broader than docs' ordinary SDK CI schedule (`sdk/package.json:28–30`; `sdk/bunfig.toml:6–12`; observed Bash/Bun SDK-local `browser-cleanup` filter selected the integration file; deliberately matched zero case names). Fix single explicit per-workspace suite inventory, fail-loud discovery, report executed/skipped/attempt counts as artifacts, identify legitimately empty lanes, and provision required offline browser/native/PTY cells instead of implicitly claiming coverage. Follow the CI runner's 25m/3 attempts for units and 15m/3 for integration; unit flake artifact exists but does not distinguish absent count from first-attempt success (`.github/workflows/ci.yml:280–282,328–356,453–454`). +11. **TEST-11 · Medium · eval coverage/security — live eval green isn't subsystem test proof.** The PR eval path filter omits SDK test execution/discovery and runtime handlers (`.github/workflows/eval-pr-subset.yml:11–28`); forks skip live runs, and missing baseline yields exit 0 (`evals/buffbench/regression-gate.ts:319–335`). Nightly workflow injects `toJSON(secrets)` into the environment of the Bun env-inventory command, unlike bounded named env in E2E (`.github/workflows/nightly-evals.yml:50–60`; `nightly-e2e.yml:22–57`). Fix trigger coverage for execution/proof changes and publish explicit dry-run/skipped/no-baseline/live distinctions; give a separate deterministic requirement→test trace eval positive and negative tool/retry cases. Limit secrets to named providers and pass them only to the job step using them. + +## Evidence limits + +- Linux host: Bun 1.4.4, Bash/tmux/bwrap/Chromium present, SDK WASM directory present, no `agent-browser` on PATH. Presence is not permission, browser startup, bubblewrap enforcement, or provider evidence. +- Offline `bun --no-env-file --no-install test --isolate` over `agents/__tests__/{basher,new-bundled-agents,specialists}.test.ts` and `packages/agent-runtime/src/tools/__tests__/browser-policy.test.ts`: **107 passed, 0 failed**; declaration, generator/reporting and policy tests only. The SDK discovery-only `^$` probe intentionally exited 1 after finding one integration file and running zero cases. Handoff, shell-policy, Basher refusal, SDK discovery and hook-inference probes performed no launches of the generated commands. No broad package run or real-provider eval was attempted. +- Audited: agent design/write/run/diagnose and UI test roles, native dispatch, scoped test/build discovery, validation evidence, SDK/CLI/runtime tests, CI/eval/test docs. All eight domains covered in findings; broader reviewer algorithm, packaging/release compatibility, and unrelated product tests are outside this shard. diff --git a/.agents/types/tools.ts b/.agents/types/tools.ts index a6e977a681..5df9e86dc2 100644 --- a/.agents/types/tools.ts +++ b/.agents/types/tools.ts @@ -150,13 +150,7 @@ export interface AddMessageParams { */ export interface AgentInboxParams { op: - | 'list' - | 'send' - | 'wait' - | 'cancel' - | 'task' - | 'workspace' - | 'managed-task' + 'list' | 'send' | 'wait' | 'cancel' | 'task' | 'workspace' | 'managed-task' /** Owned managed worker request for op=managed-task (explicit grant required). */ managedTask?: | { @@ -566,6 +560,8 @@ export interface FindReferencesParams { * Read-only git status and (optionally) diff for the current project. */ export interface GitStatusParams { + /** Return the exact commit basis and machine-readable full worktree path membership. */ + capture_basis?: boolean /** When true, also return the unified diff of uncommitted changes. */ include_diff?: boolean /** When true with include_diff, returns the staged diff instead of unstaged. */ @@ -613,6 +609,8 @@ export interface GetTaskParams { */ export interface GetChangeReviewBundleParams { max_chars?: number + /** Return Git evidence without running the optional static analyzer. */ + skip_security_scan?: boolean } /** @@ -638,6 +636,11 @@ export interface Inspect3dAssetParams { */ export interface GetAffectedTestsParams { files: string[] + /** Previously retrieved index reference paths, grouped by source. They are advisory and are rechecked on disk. */ + references?: { + source: string + path: string + }[] } /** @@ -684,6 +687,11 @@ export interface EvaluateAuditCoverageParams { | 'test-coverage' | 'api-contract' )[] + /** Copy from write_audit_findings; identifies the exact retained artifact bytes for this shard. */ + artifact?: { + session_slug: string + content_hash: string + } }[] features: { schema_version: 1 @@ -709,6 +717,10 @@ export interface EvaluateAuditCoverageParams { failure_states: string[] } }[] + read_proofs?: { + path: string + read_capability: string + }[] out_of_scope?: { id: string reason: string @@ -801,6 +813,11 @@ export interface RecallContextParams { query?: string /** Exact call ID named by an eviction pointer. Retrieves bounded UTF-8 pages of the retained immutable original; legacy fullness remains unknown. */ toolCallId?: string + /** Exact user or assistant message reference from an archive result; requires sourceRunId. */ + message?: { + role: 'user' | 'assistant' + messageId: string + } /** Original source run; required when a call ID is ambiguous across runs. */ sourceRunId?: string /** Expected SHA-256 of the complete original UTF-8 text, copied from the preceding result. */ @@ -819,18 +836,22 @@ export interface RecordDecisionParams { text: string /** Kind of record to save. Defaults to decision. */ kind?: 'decision' | 'fact' | 'constraint' - /** Required evidence: 1..32 project-relative paths without traversal or glob syntax. */ + /** Required citations: 1..32 allowed project-relative paths. A citation is not proof of a read or verification. */ evidenceSelectors: string[] /** Optional supporting excerpt, at most 1024 characters. */ excerpt?: string - /** Optional observation ids this decision supersedes (1..16 ids, each 1..128 chars). Emits append-only claim.superseded events; never blocks capture. */ + /** Optional observation IDs to request superseding (1..16 IDs, each 1..128 chars). The request is not confirmation of a change. */ supersedes?: string[] } /** - * Fetch up-to-date documentation for libraries and frameworks using Context7 API. + * Fetch public documentation for libraries and frameworks via Context7, optionally pinned to a verified project and ref. */ export interface ReadDocsParams { + /** Exact Context7 project ID (e.g. "/vercel/next.js") or versioned ID (e.g. "/vercel/next.js/v13.5.11"). Not a URL. */ + libraryId?: string + /** Exact Context7 reference (e.g. "v13.5.11"). Copy the literal published version, tag or ref segment, not a range or URL. Must agree with any versioned libraryId. */ + ref?: string /** The library or framework name (e.g., "Next.js", "MongoDB", "React"). Use the official name as it appears in documentation if possible. Only public libraries available in Context7's database are supported, so small or private libraries may not be available. */ libraryTitle: string /** Specific topic to focus on (e.g., "routing", "hooks", "authentication") */ @@ -940,6 +961,8 @@ export interface ReadOutlineParams { export interface ReadSubtreeParams { /** List of paths to directories or files. Absolute or relative to the project root; access follows the configured sandbox policy. If omitted, the entire project tree is used. */ paths?: string[] + /** Opt in to canonical project-relative inventory: paths lists bounded file paths; stat classifies only the named entries without walking directories. Omit for the legacy tree/symbol rendering. */ + mode?: 'paths' | 'stat' /** Maximum token budget for the subtree blob; the tree will be truncated to fit within this budget by first dropping file variables and then removing the most-nested files and directories. */ maxTokens?: number } @@ -1040,6 +1063,8 @@ export interface RunTerminalCommandParams { detach?: boolean /** The working directory to run the command in. Default is the project root. */ cwd?: string + /** For SYNC commands, request a host-owned output log even when the inline output fits. Logging does not change the command or its exit code. Use only a returned, verified path. */ + save_full_log?: boolean /** Wall-clock bound in seconds, including startup and approval waits. Omitted or -1 adds no local timeout unless the host explicitly configures a default or cap. Cancellation and any finite parent/run deadline always apply. */ timeout_seconds?: number /** Runtime-managed background job owner; agents must omit. */ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 300578727c..c1b64aedd4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,10 @@ on: permissions: contents: read +env: + CODEBUFF_GITHUB_ACTIONS: 'true' + NEXT_PUBLIC_CB_ENVIRONMENT: test + # Define reusable job template jobs: # Build and check @@ -21,7 +25,7 @@ jobs: runs-on: ubuntu-26.04 steps: - name: Checkout repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Set up Node uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 @@ -48,42 +52,6 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile - - name: Set environment variables - env: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - CANOPYWAVE_API_KEY: ${{ secrets.CANOPYWAVE_API_KEY }} - CODEBUFF_GITHUB_TOKEN: ${{ secrets.OPENBUFF_GITHUB_TOKEN }} - CONTEXT7_API_KEY: ${{ secrets.CONTEXT7_API_KEY }} - DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} - FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }} - GRAVITY_API_KEY: ${{ secrets.GRAVITY_API_KEY }} - IPINFO_TOKEN: ${{ secrets.IPINFO_TOKEN }} - LINKUP_API_KEY: ${{ secrets.LINKUP_API_KEY }} - MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} - NEXT_PUBLIC_CODEBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_CODEBUFF_APP_URL }} - NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID: ${{ secrets.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID }} - NEXT_PUBLIC_OPENBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_OPENBUFF_APP_URL }} - NEXT_PUBLIC_POSTHOG_API_KEY: ${{ secrets.NEXT_PUBLIC_POSTHOG_API_KEY }} - NEXT_PUBLIC_POSTHOG_HOST_URL: ${{ secrets.NEXT_PUBLIC_POSTHOG_HOST_URL }} - NEXT_PUBLIC_SUPPORT_EMAIL: ${{ secrets.NEXT_PUBLIC_SUPPORT_EMAIL }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} - OPEN_ROUTER_API_KEY: ${{ secrets.OPEN_ROUTER_API_KEY }} - SILICONFLOW_API_KEY: ${{ secrets.SILICONFLOW_API_KEY }} - run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts) - # Export each required var from its named step env entry above. - # generate-ci-env.ts prints a JSON array, so parse it before looping. - for name in $(printf '%s' "$VAR_NAMES" | jq -r '.[]'); do - value="${!name:-}" - if [ -n "$value" ]; then - echo "$name=$value" >> $GITHUB_ENV - fi - done - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - echo "NEXT_PUBLIC_CB_ENVIRONMENT=test" >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_TOKEN=$CODEBUFF_GITHUB_TOKEN" >> $GITHUB_ENV - - name: Check generated tool definitions are current run: | bun run generate-tool-definitions @@ -191,7 +159,7 @@ jobs: runs-on: ubuntu-26.04 steps: - name: Checkout repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Set up Node uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 @@ -218,46 +186,9 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile - - name: Set environment variables - env: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - CANOPYWAVE_API_KEY: ${{ secrets.CANOPYWAVE_API_KEY }} - CODEBUFF_GITHUB_TOKEN: ${{ secrets.OPENBUFF_GITHUB_TOKEN }} - CONTEXT7_API_KEY: ${{ secrets.CONTEXT7_API_KEY }} - DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} - FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }} - GRAVITY_API_KEY: ${{ secrets.GRAVITY_API_KEY }} - IPINFO_TOKEN: ${{ secrets.IPINFO_TOKEN }} - LINKUP_API_KEY: ${{ secrets.LINKUP_API_KEY }} - MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} - NEXT_PUBLIC_CODEBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_CODEBUFF_APP_URL }} - NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID: ${{ secrets.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID }} - NEXT_PUBLIC_OPENBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_OPENBUFF_APP_URL }} - NEXT_PUBLIC_POSTHOG_API_KEY: ${{ secrets.NEXT_PUBLIC_POSTHOG_API_KEY }} - NEXT_PUBLIC_POSTHOG_HOST_URL: ${{ secrets.NEXT_PUBLIC_POSTHOG_HOST_URL }} - NEXT_PUBLIC_SUPPORT_EMAIL: ${{ secrets.NEXT_PUBLIC_SUPPORT_EMAIL }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} - OPEN_ROUTER_API_KEY: ${{ secrets.OPEN_ROUTER_API_KEY }} - SILICONFLOW_API_KEY: ${{ secrets.SILICONFLOW_API_KEY }} - run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts) - # Export each required var from its named step env entry above. - # generate-ci-env.ts prints a JSON array, so parse it before looping. - for name in $(printf '%s' "$VAR_NAMES" | jq -r '.[]'); do - value="${!name:-}" - if [ -n "$value" ]; then - echo "$name=$value" >> $GITHUB_ENV - fi - done - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - echo "NEXT_PUBLIC_CB_ENVIRONMENT=test" >> $GITHUB_ENV - echo "NEXT_PUBLIC_INFISICAL_UP=true" >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_TOKEN=$CODEBUFF_GITHUB_TOKEN" >> $GITHUB_ENV - # The SDK memory-management suite also launches the CLI source entry. - - name: Build SDK dist for CLI imports and code-map grammar coverage - if: matrix.package == 'cli' || matrix.package == 'sdk' || matrix.package == 'packages/code-map' + - name: Build SDK dist for CLI, agents and packaged code-map grammars + if: matrix.package == 'cli' || matrix.package == 'sdk' || matrix.package == 'agents' || matrix.package == 'packages/code-map' run: cd sdk && bun run build - name: Use packaged grammars for code-map tests @@ -268,6 +199,16 @@ jobs: if: matrix.package == 'cli' || matrix.package == 'sdk' run: cd cli && bun run prebuild:agents + - name: Run shipped Base2 lifecycle with no egress + if: matrix.package == 'sdk' + run: | + command -v ip + if ! command -v bwrap; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends bubblewrap + fi + bash scripts/run-offline-base2.sh + - id: tests name: Run ${{ matrix.package }} tests uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 # v4.0.0 @@ -287,31 +228,8 @@ jobs: annotations="$RUNNER_TEMP/unit-test-annotations" : > "$annotations" || exit 1 ( - cd ${{ matrix.package }} || exit 1 - if [ "${{ matrix.package }}" = ".agents" ] || [ "${{ matrix.package }}" = "agents" ] || [ "${{ matrix.package }}" = "cli" ]; then - bun run test - else - # Run all non-integration tests in a single bun test invocation - # This avoids xargs exit code issues with orphaned child processes - # M1-T6: search the whole package (not just src/) so packages - # whose tests live in __tests__/ (e.g. scripts) actually run. - # 2026-10-03b: include '*.test.tsx' too — the OpenTUI render - # tests (36 files, 463 tests) were previously invisible to CI; - # the full tsx suite passes under the pinned bun 1.4.4. - TEST_FILES=$(find . \( -path ./node_modules -o -path ./.git -o -path ./dist \) -prune -o -type f \( -name '*.test.ts' -o -name '*.test.tsx' \) ! -name '*.integration.test.ts' -print 2>/dev/null | sort | tr '\n' ' ') - if [ -n "$TEST_FILES" ]; then - # --isolate: per-file test isolation prevents cross-file - # mock.module / module-state leakage (e.g. indexer's - # p8-degraded-delta mock leaking into p8-lite). - bun test --isolate $TEST_FILES - else - # M4-T3: an empty glob is a truth failure, not a pass. A - # missing/pruned test directory must fail the job instead of - # reporting a vacuous green suite. - echo "No tests found in ${{ matrix.package }} (expected '*.test.ts'/'*.test.tsx' files; find glob or checkout is broken)" >&2 - exit 1 - fi - fi + cd '${{ matrix.package }}' || exit 1 + OPENBUFF_TEST_RECEIPT="$RUNNER_TEMP/test-receipt.json" bun --no-env-file --no-install run test ) 2>&1 | awk -v annotations="$annotations" ' /^::error( |::)/ { print >> annotations; fflush(annotations); next } { print; fflush() } @@ -345,7 +263,8 @@ jobs: fi UPDATED=$(LEDGER="$LEDGER" SUITE="$SUITE" ATTEMPTS="${{ steps.tests.outputs.total_attempts }}" bun -e ' const ledger = JSON.parse(process.env.LEDGER); - ledger[process.env.SUITE] = Number(process.env.ATTEMPTS) || 1; + const raw = process.env.ATTEMPTS; + ledger[process.env.SUITE] = raw ? Number(raw) : null; console.log(JSON.stringify(ledger, null, 2) + "\n"); ') printf '%s\n' "$UPDATED" > scripts/flake-ledger.json @@ -356,7 +275,9 @@ jobs: uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: flake-ledger-${{ env.FLAKE_SUITE }} - path: scripts/flake-ledger.json + path: | + scripts/flake-ledger.json + ${{ runner.temp }}/test-receipt.json if-no-files-found: error # - name: Open interactive debug shell @@ -370,12 +291,12 @@ jobs: strategy: fail-fast: false matrix: - package: [cli, common, packages/agent-runtime, sdk] + package: [cli, sdk] name: test-integration-${{ matrix.package }} runs-on: ubuntu-26.04 steps: - name: Checkout repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 - name: Set up Node uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 @@ -402,44 +323,7 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile - - name: Set environment variables - env: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - CANOPYWAVE_API_KEY: ${{ secrets.CANOPYWAVE_API_KEY }} - CODEBUFF_GITHUB_TOKEN: ${{ secrets.OPENBUFF_GITHUB_TOKEN }} - CONTEXT7_API_KEY: ${{ secrets.CONTEXT7_API_KEY }} - DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} - FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }} - GRAVITY_API_KEY: ${{ secrets.GRAVITY_API_KEY }} - IPINFO_TOKEN: ${{ secrets.IPINFO_TOKEN }} - LINKUP_API_KEY: ${{ secrets.LINKUP_API_KEY }} - MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} - NEXT_PUBLIC_CODEBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_CODEBUFF_APP_URL }} - NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID: ${{ secrets.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID }} - NEXT_PUBLIC_OPENBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_OPENBUFF_APP_URL }} - NEXT_PUBLIC_POSTHOG_API_KEY: ${{ secrets.NEXT_PUBLIC_POSTHOG_API_KEY }} - NEXT_PUBLIC_POSTHOG_HOST_URL: ${{ secrets.NEXT_PUBLIC_POSTHOG_HOST_URL }} - NEXT_PUBLIC_SUPPORT_EMAIL: ${{ secrets.NEXT_PUBLIC_SUPPORT_EMAIL }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} - OPEN_ROUTER_API_KEY: ${{ secrets.OPEN_ROUTER_API_KEY }} - SILICONFLOW_API_KEY: ${{ secrets.SILICONFLOW_API_KEY }} - run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts) - # Export each required var from its named step env entry above. - # generate-ci-env.ts prints a JSON array, so parse it before looping. - for name in $(printf '%s' "$VAR_NAMES" | jq -r '.[]'); do - value="${!name:-}" - if [ -n "$value" ]; then - echo "$name=$value" >> $GITHUB_ENV - fi - done - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - echo "NEXT_PUBLIC_CB_ENVIRONMENT=test" >> $GITHUB_ENV - echo "NEXT_PUBLIC_INFISICAL_UP=true" >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_TOKEN=$CODEBUFF_GITHUB_TOKEN" >> $GITHUB_ENV - - - name: Build sdk dist (cli tests import @openbuff/sdk through the ESM import condition) + - name: Build SDK dist for CLI integration tests if: matrix.package == 'cli' run: cd sdk && bun run build @@ -447,18 +331,34 @@ jobs: if: matrix.package == 'cli' run: cd cli && bun run prebuild:agents - - name: Run ${{ matrix.package }} integration tests + - name: Identify required Linux tmux capability on the runner image + if: matrix.package == 'cli' + run: tmux -V || { echo '::error::CLI integration requires tmux on the ubuntu-26.04 runner'; exit 1; } + + - id: integration + name: Run ${{ matrix.package }} integration tests uses: nick-fields/retry@ad984534de44a9489a53aefd81eb77f87c70dc60 # v4.0.0 with: timeout_minutes: 15 max_attempts: 3 command: | - cd ${{ matrix.package }} - TEST_FILES=$(find . \( -path ./node_modules -o -path ./.git -o -path ./dist \) -prune -o -type f -name '*.integration.test.ts' -print 2>/dev/null | sort | tr '\n' ' ') - if [ -n "$TEST_FILES" ]; then - bun test --timeout=60000 $TEST_FILES - else - echo "No integration tests found in ${{ matrix.package }}" - fi + cd '${{ matrix.package }}' || exit 1 + OPENBUFF_TEST_RECEIPT="$RUNNER_TEMP/test-receipt.json" bun --no-env-file --no-install run test:integration + + - name: Record integration attempts + if: always() + env: + ATTEMPTS: ${{ steps.integration.outputs.total_attempts }} + run: | + bun -e 'const attempts = process.env.ATTEMPTS ? Number(process.env.ATTEMPTS) : null; + console.log(JSON.stringify({attempts, retries: attempts === null ? null : attempts - 1}))' > "$RUNNER_TEMP/test-attempts.json" + + - name: Upload integration test evidence + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: integration-evidence-${{ matrix.package }} + path: ${{ runner.temp }}/test-*.json + if-no-files-found: error # E2E tests for web intentionally omitted for now. diff --git a/.github/workflows/cli-release-build.yml b/.github/workflows/cli-release-build.yml index ed6528e03a..03ba9b0b16 100644 --- a/.github/workflows/cli-release-build.yml +++ b/.github/workflows/cli-release-build.yml @@ -450,6 +450,21 @@ jobs: bun "$SMOKE_SCRIPT" "$BIN" fi + - name: Verify Linux x64 archive lifecycle without egress + if: matrix.target == 'linux-x64' + shell: bash + env: + BINARY_NAME: ${{ inputs.binary-name }} + CLI_VERSION: ${{ inputs.new-version }} + run: | + set -euo pipefail + if ! command -v bwrap; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends bubblewrap + fi + bun --no-env-file --no-install test/fixtures/body/cli-release-candidate.ts \ + "$BINARY_NAME-linux-x64.tar.gz" "$CLI_VERSION" + - name: Set up QEMU for Linux ARM64 smoke if: matrix.smoke_test == 'emulated' uses: docker/setup-qemu-action@v3 diff --git a/.github/workflows/eval-pr-subset.yml b/.github/workflows/eval-pr-subset.yml index 45a0ff824e..242193b8c8 100644 --- a/.github/workflows/eval-pr-subset.yml +++ b/.github/workflows/eval-pr-subset.yml @@ -1,30 +1,45 @@ name: Eval PR Subset -# N10: run a small fixed buffbench subset (evals/buffbench/main-nightly.ts -# EVAL_SUBSETS.pr) on changes to agents, tool schemas or system prompts, and -# fail when it regresses past the noise band against the last green run on -# main. Pushes to main refresh that baseline. +# N10: validate the source checkout on evidence-related changes. If a named +# BYOK credential is available, measure the fixed PR subset and compare it +# with the most recent eligible main push artifact. on: pull_request: paths: - 'agents/**' - - 'common/src/tools/params/**' - - 'packages/agent-runtime/src/system-prompt/**' - - 'packages/agent-runtime/src/templates/**' - - 'packages/agent-runtime/src/tools/prompts.ts' - - 'evals/buffbench/**' + - 'cli/**' + - 'common/**' + - 'evals/**' + - 'packages/**' + - 'sdk/**' + - 'test/fixtures/body/**' + - 'scripts/run-workspace-tests.ts' + - '.github/workflows/ci.yml' + - '.github/workflows/nightly-e2e.yml' + - '.github/workflows/nightly-evals.yml' - '.github/workflows/eval-pr-subset.yml' + - '.bun-version' + - 'bun.lock' + - 'package.json' push: branches: [main] paths: - 'agents/**' - - 'common/src/tools/params/**' - - 'packages/agent-runtime/src/system-prompt/**' - - 'packages/agent-runtime/src/templates/**' - - 'packages/agent-runtime/src/tools/prompts.ts' - - 'evals/buffbench/**' + - 'cli/**' + - 'common/**' + - 'evals/**' + - 'packages/**' + - 'sdk/**' + - 'test/fixtures/body/**' + - 'scripts/run-workspace-tests.ts' + - '.github/workflows/ci.yml' + - '.github/workflows/nightly-e2e.yml' + - '.github/workflows/nightly-evals.yml' - '.github/workflows/eval-pr-subset.yml' + - '.bun-version' + - 'bun.lock' + - 'package.json' workflow_dispatch: permissions: @@ -32,6 +47,11 @@ permissions: # Read the last green main run's results artifact for the baseline. actions: read +env: + CODEBUFF_GITHUB_ACTIONS: 'true' + NEXT_PUBLIC_CB_ENVIRONMENT: test + OPENBUFF_TELEMETRY: '0' + concurrency: group: eval-pr-subset-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true @@ -42,7 +62,9 @@ jobs: timeout-minutes: 90 steps: - name: Checkout repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Set up Bun uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 @@ -63,86 +85,104 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile - # Key-free: a prompt or agent change that breaks agent loading, the eval - # file or the subset task ids fails here, even on fork PRs. + # This runs on fork PRs too, with neither credentials nor a live result. - name: Validate subset configuration (no LLM calls) - run: cd evals && bun run-buffbench-pr-subset --dry-run + working-directory: evals + run: | + bun --no-env-file --no-install run run-buffbench-pr-subset --dry-run \ + --status-out "$RUNNER_TEMP/eval-evidence/DRY_RUN.json" + + # Repository variable: reviewed Openbuff routing JSON with apiKeyEnv + # names, never key values. The fork/no-key lane does not need it. + - name: Prepare live BYOK routing + if: vars.BUFFBENCH_PROVIDER_CONFIG_JSON != '' + env: + CONFIG_JSON: ${{ vars.BUFFBENCH_PROVIDER_CONFIG_JSON }} + run: | + umask 077 + printf '%s' "$CONFIG_JSON" > "$RUNNER_TEMP/eval-provider-config.json" - - name: Set environment variables - id: env + - name: Run eval subset (base2, when a named provider key is available) + id: run + working-directory: evals env: + OPENBUFF_PROVIDER_CONFIG: ${{ runner.temp }}/eval-provider-config.json ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - CODEBUFF_GITHUB_TOKEN: ${{ secrets.OPENBUFF_GITHUB_TOKEN }} + CANOPYWAVE_API_KEY: ${{ secrets.CANOPYWAVE_API_KEY }} DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }} MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} OPEN_ROUTER_API_KEY: ${{ secrets.OPEN_ROUTER_API_KEY }} SILICONFLOW_API_KEY: ${{ secrets.SILICONFLOW_API_KEY }} run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts) - for name in $(printf '%s' "$VAR_NAMES" | jq -r '.[]'); do - value="${!name:-}" - if [ -n "$value" ]; then - echo "$name=$value" >> $GITHUB_ENV - fi - done - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - echo "NEXT_PUBLIC_CB_ENVIRONMENT=test" >> $GITHUB_ENV - echo "NEXT_PUBLIC_INFISICAL_UP=true" >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_TOKEN=$CODEBUFF_GITHUB_TOKEN" >> $GITHUB_ENV - # Fork PRs get no secrets: skip the live subset instead of failing. - if [ -n "$ANTHROPIC_API_KEY$OPENAI_API_KEY$OPEN_ROUTER_API_KEY$DEEPSEEK_API_KEY$FIREWORKS_API_KEY$MOONSHOT_API_KEY$OPENCODE_API_KEY$SILICONFLOW_API_KEY" ]; then - echo "has_keys=true" >> "$GITHUB_OUTPUT" - else - echo "has_keys=false" >> "$GITHUB_OUTPUT" - echo "::notice::No provider keys available; skipping the live eval subset." - fi - - - name: Run eval subset (base2) - id: run - if: steps.env.outputs.has_keys == 'true' - run: | - cd evals && bun run-buffbench-pr-subset \ - --results-out "$RUNNER_TEMP/eval-results/FINAL_RESULTS.json" + set -euo pipefail + STATUS="$RUNNER_TEMP/eval-evidence/LIVE.json" + # Do not stream provider exceptions or raw task output into CI logs. + bun --no-env-file --no-install run run-buffbench-pr-subset \ + --skip-without-provider-key --status-out "$STATUS" \ + --results-out "$RUNNER_TEMP/eval-results/FINAL_RESULTS.json" >/dev/null 2>&1 + bun --no-env-file --no-install -e ' + const {status} = await Bun.file(process.argv[1]).json() + if (status !== "no-key" && status !== "live-measured") process.exit(1) + console.log("status=" + status) + ' "$STATUS" >> "$GITHUB_OUTPUT" - - name: Download last green main results - if: steps.run.outcome == 'success' && github.event_name != 'push' + - name: Find eligible main baseline + if: steps.run.outputs.status == 'live-measured' env: GH_TOKEN: ${{ github.token }} run: | - set -uo pipefail - RUN_ID=$(gh run list --repo "$GITHUB_REPOSITORY" \ - --workflow eval-pr-subset.yml --branch main --event push \ - --status success --limit 1 --json databaseId -q '.[0].databaseId // empty') - mkdir -p "$RUNNER_TEMP/eval-baseline" - if [ -n "$RUN_ID" ]; then - gh run download "$RUN_ID" --repo "$GITHUB_REPOSITORY" \ - -n buffbench-pr-subset-results -D "$RUNNER_TEMP/eval-baseline" \ - || echo "Baseline artifact for run $RUN_ID is unavailable." - else - echo "No green main run yet; comparison skipped." - fi - - - name: Compare with last green run - if: steps.run.outcome == 'success' + bash evals/scripts/download-eval-baseline.sh eval-pr-subset.yml main push \ + buffbench-pr-subset-results "$RUNNER_TEMP/eval-baseline" + + - name: Compare measured results + id: gate + if: steps.run.outputs.status == 'live-measured' + working-directory: evals run: | - set +e - mkdir -p "$RUNNER_TEMP/eval-baseline" - cd evals && bun eval-gate \ + bun --no-env-file --no-install run eval-gate \ --current "$RUNNER_TEMP/eval-results/FINAL_RESULTS.json" \ --baseline "$RUNNER_TEMP/eval-baseline" \ - --report "$RUNNER_TEMP/eval-results/GATE_REPORT.md" - STATUS=$? - cat "$RUNNER_TEMP/eval-results/GATE_REPORT.md" >> "$GITHUB_STEP_SUMMARY" 2>/dev/null - exit $STATUS + --report "$RUNNER_TEMP/eval-evidence/GATE_REPORT.md" - - name: Upload results artifact - if: always() && steps.run.outcome != 'skipped' + - name: Upload measured result + if: steps.gate.outcome == 'success' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: buffbench-pr-subset-results - path: ${{ runner.temp }}/eval-results/ + path: ${{ runner.temp }}/eval-results/FINAL_RESULTS.json + if-no-files-found: error + retention-days: 90 + + - name: Publish eval outcome + if: always() + env: + JOB_STATUS: ${{ job.status }} + run: | + { + printf '# BuffBench PR subset (%s)\n\n' "$JOB_STATUS" + if [[ "$JOB_STATUS" != success ]]; then + printf 'The workflow did not complete successfully. Regression verified: no.\n\n' + fi + for report in "$RUNNER_TEMP/eval-evidence/"*.json; do + if [[ -f "$report" ]]; then + printf '```json\n' + cat "$report" + printf '```\n\n' + fi + done + report="$RUNNER_TEMP/eval-evidence/GATE_REPORT.md" + if [[ -f "$report" ]]; then cat "$report"; fi + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload eval evidence + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: buffbench-pr-subset-evidence + path: ${{ runner.temp }}/eval-evidence/ if-no-files-found: warn retention-days: 90 diff --git a/.github/workflows/nightly-e2e.yml b/.github/workflows/nightly-e2e.yml index 9ae8bf7b4c..ef13bb65b6 100644 --- a/.github/workflows/nightly-e2e.yml +++ b/.github/workflows/nightly-e2e.yml @@ -2,70 +2,40 @@ name: Nightly E2E Tests on: schedule: - # Run every day at 5:00 AM PT (12:00 UTC) - cron: '0 12 * * *' - workflow_dispatch: # Allow manual triggering + workflow_dispatch: -# M1-T6: scope the workflow token to read-only contents — a scheduled workflow -# must not run with the default write-scoped GITHUB_TOKEN. permissions: contents: read +env: + CODEBUFF_GITHUB_ACTIONS: 'true' + NEXT_PUBLIC_CB_ENVIRONMENT: test + jobs: e2e-tests: runs-on: ubuntu-26.04 timeout-minutes: 45 steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 + with: + persist-credentials: false - uses: ./.github/actions/setup-project - - name: Set environment variables - env: - ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - CANOPYWAVE_API_KEY: ${{ secrets.CANOPYWAVE_API_KEY }} - CODEBUFF_GITHUB_TOKEN: ${{ secrets.OPENBUFF_GITHUB_TOKEN }} - CONTEXT7_API_KEY: ${{ secrets.CONTEXT7_API_KEY }} - DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} - FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }} - GRAVITY_API_KEY: ${{ secrets.GRAVITY_API_KEY }} - IPINFO_TOKEN: ${{ secrets.IPINFO_TOKEN }} - LINKUP_API_KEY: ${{ secrets.LINKUP_API_KEY }} - MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} - NEXT_PUBLIC_CODEBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_CODEBUFF_APP_URL }} - NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID: ${{ secrets.NEXT_PUBLIC_GOOGLE_SITE_VERIFICATION_ID }} - NEXT_PUBLIC_OPENBUFF_APP_URL: ${{ secrets.NEXT_PUBLIC_OPENBUFF_APP_URL }} - NEXT_PUBLIC_POSTHOG_API_KEY: ${{ secrets.NEXT_PUBLIC_POSTHOG_API_KEY }} - NEXT_PUBLIC_POSTHOG_HOST_URL: ${{ secrets.NEXT_PUBLIC_POSTHOG_HOST_URL }} - NEXT_PUBLIC_SUPPORT_EMAIL: ${{ secrets.NEXT_PUBLIC_SUPPORT_EMAIL }} - OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} - OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} - OPEN_ROUTER_API_KEY: ${{ secrets.OPEN_ROUTER_API_KEY }} - SILICONFLOW_API_KEY: ${{ secrets.SILICONFLOW_API_KEY }} - run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts) - # Export each required var from its named step env entry above. - # M1-T6: no toJSON(secrets) dump — the whole secrets object used to - # be piped through jq; now only the named secrets above are exposed - # and only the required-and-present subset is persisted. - for name in $(printf '%s' "$VAR_NAMES" | jq -r '.[]'); do - value="${!name:-}" - if [ -n "$value" ]; then - echo "$name=$value" >> $GITHUB_ENV - fi - done - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - echo "NEXT_PUBLIC_CB_ENVIRONMENT=test" >> $GITHUB_ENV - echo "NEXT_PUBLIC_INFISICAL_UP=true" >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_TOKEN=$CODEBUFF_GITHUB_TOKEN" >> $GITHUB_ENV - - name: Build SDK run: cd sdk && bun run build - - name: Run agents e2e tests - env: - RUN_CONTEXT_PRUNING_E2E: 'true' - run: cd agents && bun run test:e2e --timeout=120000 - - # Hosted web docs and Playwright checks were removed with the web package. + - name: Run deterministic agents E2E schedule (no live Deep/provider coverage) + run: | + cd agents + OPENBUFF_TEST_RECEIPT="$RUNNER_TEMP/agent-e2e-receipt.json" bun --no-env-file --no-install run test:e2e + + - name: Upload agents E2E evidence + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 + with: + name: agent-e2e-evidence + path: ${{ runner.temp }}/agent-e2e-receipt.json + if-no-files-found: error diff --git a/.github/workflows/nightly-evals.yml b/.github/workflows/nightly-evals.yml index b5913e013f..4d50df5680 100644 --- a/.github/workflows/nightly-evals.yml +++ b/.github/workflows/nightly-evals.yml @@ -20,21 +20,28 @@ permissions: # Read the last green run's results artifact for the baseline. actions: read +env: + CODEBUFF_GITHUB_ACTIONS: 'true' + NEXT_PUBLIC_CB_ENVIRONMENT: test + OPENBUFF_TELEMETRY: '0' + jobs: run-nightly-evals: runs-on: ubuntu-26.04 timeout-minutes: 360 # 6 hours is the max for any hosted github action steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + persist-credentials: false - name: Set up Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: bun-version: '1.4.4' - name: Cache dependencies - uses: actions/cache@v5 + uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5 with: path: | node_modules @@ -47,69 +54,109 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile - - name: Set environment variables + - name: Validate eval configuration (no LLM calls) + working-directory: evals env: - SECRETS_CONTEXT: ${{ toJSON(secrets) }} + TASKS: ${{ inputs.tasks }} run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts) - echo "$SECRETS_CONTEXT" | jq -r --argjson vars "$VAR_NAMES" ' - to_entries | .[] | select(.key as $k | $vars | index($k)) | .key + "=" + .value - ' >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - echo "NEXT_PUBLIC_CB_ENVIRONMENT=test" >> $GITHUB_ENV - echo "NEXT_PUBLIC_INFISICAL_UP=true" >> $GITHUB_ENV - echo "CODEBUFF_GITHUB_TOKEN=${{ secrets.OPENBUFF_GITHUB_TOKEN }}" >> $GITHUB_ENV + ARGS=(--dry-run --status-out "$RUNNER_TEMP/eval-evidence/DRY_RUN.json") + if [[ -n "${TASKS:-}" ]]; then ARGS+=(--tasks "$TASKS"); fi + bun --no-env-file --no-install run run-buffbench-nightly "${ARGS[@]}" - - name: Validate eval configuration (no LLM calls) - run: cd evals && bun run-buffbench-nightly --dry-run + # Repository variable: reviewed Openbuff routing JSON with apiKeyEnv + # names, never key values. No routing file is needed for the key-free lane. + - name: Prepare live BYOK routing + if: vars.BUFFBENCH_PROVIDER_CONFIG_JSON != '' + env: + CONFIG_JSON: ${{ vars.BUFFBENCH_PROVIDER_CONFIG_JSON }} + run: | + umask 077 + printf '%s' "$CONFIG_JSON" > "$RUNNER_TEMP/eval-provider-config.json" - - name: Run nightly evals (base2) + - name: Run nightly evals (base2, when a named provider key is available) id: run + working-directory: evals env: TASKS: ${{ inputs.tasks }} + OPENBUFF_PROVIDER_CONFIG: ${{ runner.temp }}/eval-provider-config.json + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + CANOPYWAVE_API_KEY: ${{ secrets.CANOPYWAVE_API_KEY }} + DEEPSEEK_API_KEY: ${{ secrets.DEEPSEEK_API_KEY }} + FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }} + MOONSHOT_API_KEY: ${{ secrets.MOONSHOT_API_KEY }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + OPENCODE_API_KEY: ${{ secrets.OPENCODE_API_KEY }} + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + OPEN_ROUTER_API_KEY: ${{ secrets.OPEN_ROUTER_API_KEY }} + SILICONFLOW_API_KEY: ${{ secrets.SILICONFLOW_API_KEY }} run: | set -euo pipefail - ARGS=(--results-out "$RUNNER_TEMP/eval-results/FINAL_RESULTS.json") - if [ -n "${TASKS:-}" ]; then ARGS+=(--tasks "$TASKS"); fi - cd evals && bun run-buffbench-nightly "${ARGS[@]}" + STATUS="$RUNNER_TEMP/eval-evidence/LIVE.json" + ARGS=(--skip-without-provider-key --status-out "$STATUS" --results-out "$RUNNER_TEMP/eval-results/FINAL_RESULTS.json") + if [[ -n "${TASKS:-}" ]]; then ARGS+=(--tasks "$TASKS"); fi + # Do not stream provider exceptions or raw task output into CI logs. + bun --no-env-file --no-install run run-buffbench-nightly "${ARGS[@]}" >/dev/null 2>&1 + bun --no-env-file --no-install -e ' + const {status} = await Bun.file(process.argv[1]).json() + if (status !== "no-key" && status !== "live-measured") process.exit(1) + console.log("status=" + status) + ' "$STATUS" >> "$GITHUB_OUTPUT" - - name: Download last green nightly results - if: steps.run.outcome == 'success' + # A manual subset run never serves as the nightly baseline. + - name: Find eligible scheduled baseline + if: steps.run.outputs.status == 'live-measured' env: GH_TOKEN: ${{ github.token }} + BASELINE_BRANCH: ${{ github.event.repository.default_branch }} run: | - set -uo pipefail - # Only scheduled runs on the full set serve as the baseline, so a - # manual subset run never becomes the comparison point. - RUN_ID=$(gh run list --repo "$GITHUB_REPOSITORY" \ - --workflow nightly-evals.yml --event schedule --status success \ - --limit 1 --json databaseId -q '.[0].databaseId // empty') - mkdir -p "$RUNNER_TEMP/eval-baseline" - if [ -n "$RUN_ID" ]; then - gh run download "$RUN_ID" --repo "$GITHUB_REPOSITORY" \ - -n buffbench-nightly-results -D "$RUNNER_TEMP/eval-baseline" \ - || echo "Baseline artifact for run $RUN_ID is unavailable." - else - echo "No green scheduled nightly yet; this run can become the baseline." - fi - - - name: Compare with last green run - if: steps.run.outcome == 'success' + bash evals/scripts/download-eval-baseline.sh nightly-evals.yml "$BASELINE_BRANCH" schedule \ + buffbench-nightly-results "$RUNNER_TEMP/eval-baseline" + + - name: Compare measured results + id: gate + if: steps.run.outputs.status == 'live-measured' + working-directory: evals run: | - set +e - cd evals && bun eval-gate \ + bun --no-env-file --no-install run eval-gate \ --current "$RUNNER_TEMP/eval-results/FINAL_RESULTS.json" \ --baseline "$RUNNER_TEMP/eval-baseline" \ - --report "$RUNNER_TEMP/eval-results/GATE_REPORT.md" - STATUS=$? - cat "$RUNNER_TEMP/eval-results/GATE_REPORT.md" >> "$GITHUB_STEP_SUMMARY" 2>/dev/null - exit $STATUS + --report "$RUNNER_TEMP/eval-evidence/GATE_REPORT.md" - - name: Upload results artifact - if: always() - uses: actions/upload-artifact@v7 + - name: Upload measured result + if: steps.gate.outcome == 'success' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: buffbench-nightly-results - path: ${{ runner.temp }}/eval-results/ + path: ${{ runner.temp }}/eval-results/FINAL_RESULTS.json + if-no-files-found: error + retention-days: 90 + + - name: Publish eval outcome + if: always() + env: + JOB_STATUS: ${{ job.status }} + run: | + { + printf '# BuffBench nightly (%s)\n\n' "$JOB_STATUS" + if [[ "$JOB_STATUS" != success ]]; then + printf 'The workflow did not complete successfully. Regression verified: no.\n\n' + fi + for report in "$RUNNER_TEMP/eval-evidence/"*.json; do + if [[ -f "$report" ]]; then + printf '```json\n' + cat "$report" + printf '```\n\n' + fi + done + report="$RUNNER_TEMP/eval-evidence/GATE_REPORT.md" + if [[ -f "$report" ]]; then cat "$report"; fi + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload eval evidence + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: buffbench-nightly-evidence + path: ${{ runner.temp }}/eval-evidence/ if-no-files-found: warn retention-days: 90 diff --git a/.github/workflows/rust-workspace.yml b/.github/workflows/rust-workspace.yml index f5f1bfe76f..b57e1dde9a 100644 --- a/.github/workflows/rust-workspace.yml +++ b/.github/workflows/rust-workspace.yml @@ -43,7 +43,7 @@ jobs: run: working-directory: rust steps: - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 # Explicit pin matches rust/rust-toolchain.toml; rustup installs it on # uncached runners, so the job never depends on a preinstalled toolchain. @@ -102,7 +102,7 @@ jobs: working-directory: ${{ runner.temp }} run: git config --global core.longpaths true - - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 # Same explicit 1.99.1 pin as build-test; `targets:` installs the target # std in one rustup pass. diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index 15b5d2ef6c..77257b505c 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -67,42 +67,56 @@ jobs: git add sdk/package.json git commit -m "Bump SDK version to ${{ steps.bump_version.outputs.new_version }}" - - name: Set environment variables - env: - SECRETS_CONTEXT: ${{ toJSON(secrets) }} - ENV_OVERRIDES: '{"NEXT_PUBLIC_CB_ENVIRONMENT": "prod"}' - shell: bash - run: | - VAR_NAMES=$(bun scripts/generate-ci-env.ts --scope client) - echo "$SECRETS_CONTEXT" | jq -r --argjson vars "$VAR_NAMES" ' - to_entries | .[] | select(.key as $k | $vars | index($k)) | .key + "=" + .value - ' >> $GITHUB_ENV - - # Set default environment variables - echo "CODEBUFF_GITHUB_ACTIONS=true" >> $GITHUB_ENV - - echo "CODEBUFF_GITHUB_TOKEN=${{ secrets.OPENBUFF_GITHUB_TOKEN }}" >> $GITHUB_ENV - - # Apply environment variable overrides - if [ "$ENV_OVERRIDES" != "{}" ]; then - echo "$ENV_OVERRIDES" | jq -r 'to_entries | .[] | .key + "=" + .value' >> $GITHUB_ENV - fi - - - name: Build SDK - run: | - cd sdk - bun run verify - - - name: Set up Node.js for npm publishing + - name: Set up pinned Node.js for verification and publishing uses: actions/setup-node@v6 with: node-version-file: .node-version registry-url: https://registry.npmjs.org/ - - name: Publish to npm + - name: Prepare offline lifecycle namespaces run: | - cd sdk - bun run scripts/publish.ts + command -v ip + if ! command -v bwrap; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends bubblewrap + fi + + - name: Build and verify the exact SDK candidate + id: candidate + working-directory: sdk + shell: bash + env: + SDK_VERSION: ${{ steps.bump_version.outputs.new_version }} + run: | + set -euo pipefail + candidate_parent="$(mktemp -d "$RUNNER_TEMP/openbuff-sdk-release.XXXXXX")" + candidate_dir="$(cd "$candidate_parent" && pwd -P)/candidate" + bun --no-env-file --no-install run scripts/verify.ts --require-packed-lifecycle --candidate-dir "$candidate_dir" + # Use the digest recorded by the successful verifier, not a newly + # calculated checksum of whatever happens to be on disk at publish time. + digest="$(jq -er --arg version "$SDK_VERSION" 'select(.version == $version) | .sha256 | select(test("^[a-f0-9]{64}$"))' "$candidate_dir/verification.json")" + printf 'directory=%s\nsha256=%s\n' "$candidate_dir" "$digest" >> "$GITHUB_OUTPUT" + + - name: Verify a clean locked SDK installation on pinned Node + working-directory: sdk + env: + SDK_CANDIDATE_DIR: ${{ steps.candidate.outputs.directory }} + SDK_CANDIDATE_SHA256: ${{ steps.candidate.outputs.sha256 }} + run: | + env -i PATH="$PATH" HOME="$RUNNER_TEMP" DO_NOT_TRACK=1 OPENBUFF_TELEMETRY=0 \ + bun --no-env-file --no-install run scripts/verify-installed.ts \ + --candidate-dir "$SDK_CANDIDATE_DIR" --sha256 "$SDK_CANDIDATE_SHA256" \ + --require-pinned-node --fetch-locked-cache + + - name: Publish the verified SDK archive to npm + working-directory: sdk + env: + SDK_CANDIDATE_DIR: ${{ steps.candidate.outputs.directory }} + SDK_CANDIDATE_SHA256: ${{ steps.candidate.outputs.sha256 }} + SDK_VERSION: ${{ steps.bump_version.outputs.new_version }} + run: | + bun --no-env-file --no-install run scripts/publish.ts --publish \ + --candidate-dir "$SDK_CANDIDATE_DIR" --sha256 "$SDK_CANDIDATE_SHA256" --version "$SDK_VERSION" - name: Push to git run: | diff --git a/ROUTER.md b/ROUTER.md index 37d8064bf4..fbdadb8f1e 100644 --- a/ROUTER.md +++ b/ROUTER.md @@ -1,19 +1,21 @@ # Openbuff ROUTER (P0.11, mex-borrowing) -Task-routed knowledge loader. Mirrors the mex `ROUTER.md` pattern: this -file maps each shipped agent identity to the subset of project knowledge -files it should load into its system prompt, so agents that only need a -subset of the docs don't pay the full context cost on every turn. +Task-routed knowledge loader. For Base2, this table selects advisory references +for the current turn. The runtime supplies paths and bounded excerpts after the +retained transcript; active root/ancestor policy, its imports, and user policy +stay in the system prompt independently of this table. Nested instruction files +still load when a relevant path is touched. Routes may target an agent identity (`agentTemplate.id`) or a task-specific identity in the form `agent:task`, where task is one of `audit`, `planning`, `implementation`, `debugging`, `validation`, or `general`. Task-specific rows -take precedence and are rendered within a bounded character budget. When this -file is absent, the loader falls back to root knowledge files. +take precedence. When this file is absent, Base2 has no routed references but +still loads the applicable instruction files. Custom templates explicitly using +`{CODEBUFF_ROUTED_KNOWLEDGE_FILES}` retain the older system-prompt rendering. This file is consumed by `common/src/util/router.ts` and wired into the -agent runtime via the `{CODEBUFF_ROUTED_KNOWLEDGE_FILES}` placeholder in -`packages/agent-runtime/src/templates/strings.ts`. The P0.12 drift suite +Base2 turn context in `packages/agent-runtime/src/util/base2-turn-prompt.ts`. +The P0.12 drift suite (`scripts/memory-drift-guard.ts`) lints this file for entries that point at files which no longer exist on disk. @@ -38,8 +40,8 @@ at files which no longer exist on disk. - Files are listed comma-separated. Paths are repo-root-relative. Use the basename (`AGENTS.md`) for files at the project root; use the full path (`docs/architecture.md`) for subdirectory docs. -- Agents not listed here will fall back to the full root knowledge set, - so this table should grow rather than shrink as we add new agents. +- Agents not listed here still get their applicable root and user policy; add a + route when specific reference docs would help. - The P0.12 `tool-config-sync` checker will warn when a row points at a file that no longer exists, so this file should not be a free-form scratchpad — keep it in sync with the repo. diff --git a/agents/__tests__/audit-contracts.test.ts b/agents/__tests__/audit-contracts.test.ts index a026a7742e..af3893d485 100644 --- a/agents/__tests__/audit-contracts.test.ts +++ b/agents/__tests__/audit-contracts.test.ts @@ -3,6 +3,15 @@ import { describe, expect, test } from 'bun:test' import browserUse from '../browser-use/browser-use' import researcherDocs from '../researcher/researcher-docs' +type DocsContext = Parameters>[0] +const agentState = {} as DocsContext['agentState'] +const noop = () => {} +const logger = { debug: noop, info: noop, warn: noop, error: noop } + +function startDocs(params: DocsContext['params']) { + return researcherDocs.handleSteps!({ agentState, logger, params }) +} + describe('audited specialist contracts', () => { test('browser-use advertises read-only inspection and requires an explicit browser opt-in', () => { expect( @@ -14,10 +23,9 @@ describe('audited specialist contracts', () => { expect(browserUse.toolNames).not.toContain('run_terminal_command') expect(browserUse.terminalPermissionProfile).toBeUndefined() expect(browserUse.spawnerPrompt).toContain('allow-interactions') - expect(browserUse.spawnerPrompt).toContain('user authorization') expect(browserUse.spawnerPrompt).not.toContain('Chrome: installed') - const prompts = `${browserUse.systemPrompt}\n${browserUse.instructionsPrompt}` + expect(prompts).toContain('an exact host-approved origin') expect(prompts).toContain('tab list/switch') expect(prompts).toContain('plan-only') expect(prompts).not.toContain('defaults to allow-interactions') @@ -42,5 +50,49 @@ describe('audited specialist contracts', () => { enum: ['answered', 'partial', 'failed'], }) expect(researcherDocs.outputSchema?.properties).toHaveProperty('failure') + expect(researcherDocs.outputSchema?.properties).toHaveProperty('failureCode') + expect(researcherDocs.inputSchema?.params?.properties).toHaveProperty('libraryId') + expect(researcherDocs.inputSchema?.params?.properties).toHaveProperty('ref') + expect(researcherDocs.toolNames).toEqual(['read_docs', 'set_output']) + expect(researcherDocs.spawnableAgents).toEqual([]) + expect(researcherDocs.spawnerPrompt).toMatch(/official version-pinned URL.*researcher-web/) + expect(researcherDocs.instructionsPrompt).toContain('resolvedRef') + }) + + test('structured documentation pins are dispatched verbatim and an exactness gap ends the child', () => { + const generator = startDocs({ libraryTitle: 'React', topic: 'hooks', libraryId: '/facebook/react', ref: 'v17.0.2' }) + expect(generator.next().value).toMatchObject({ + toolName: 'read_docs', + input: { libraryTitle: 'React', topic: 'hooks', libraryId: '/facebook/react', ref: 'v17.0.2' }, + }) + expect(generator.next({ + agentState, + stepsComplete: true, + toolResult: [{ type: 'json', value: { + status: 'wrong_version', + reason: 'No verified version', + nextStep: 'Only the parent can hand off an official version-pinned URL.', + } }], + }).value).toMatchObject({ + toolName: 'set_output', + input: { + status: 'failed', answer: '', source: 'unknown', version: 'unknown', + failureCode: 'wrong_version', failure: expect.stringContaining('official version-pinned URL'), + }, + }) + expect(generator?.next().done).toBe(true) + }) + + test('researcher-docs does not accept unqualified docs for a structured pin', () => { + const generator = startDocs({ libraryTitle: 'React', ref: 'v17.0.2' }) + generator.next() + expect(generator.next({ + agentState, + stepsComplete: true, + toolResult: [{ type: 'json', value: { documentation: 'latest', library: { id: '/facebook/react', branch: 'main' } } }], + }).value).toMatchObject({ + toolName: 'set_output', + input: { status: 'failed', answer: '', failureCode: 'unavailable' }, + }) }) }) diff --git a/agents/__tests__/base2-mode-policy.test.ts b/agents/__tests__/base2-mode-policy.test.ts index 8e38b42ac3..4452cf6db1 100644 --- a/agents/__tests__/base2-mode-policy.test.ts +++ b/agents/__tests__/base2-mode-policy.test.ts @@ -47,7 +47,7 @@ describe('base2 mode policy coverage', () => { } }) - test('disclosure controls are mode-neutral and plan artifacts remain PLAN-only', () => { + test('disclosure is mode-neutral; Execute Plan receives bookkeeping only', () => { for (const isFast of [false, true]) { for (const planOnly of [false, true]) { for (const executePlan of [false, true]) { @@ -56,7 +56,7 @@ describe('base2 mode policy coverage', () => { expect(modeAllowsTool('tool_load', gates)).toBe(true) expect(modeAllowsTool('tool_search', gates)).toBe(true) expect(modeAllowsTool('create_plan', gates)).toBe(planOnly) - expect(modeAllowsTool('update_plan_status', gates)).toBe(planOnly) + expect(modeAllowsTool('update_plan_status', gates)).toBe(planOnly || executePlan) } } } diff --git a/agents/__tests__/base2-progressive-tool-disclosure.test.ts b/agents/__tests__/base2-progressive-tool-disclosure.test.ts index 7001e37571..f4a03f4296 100644 --- a/agents/__tests__/base2-progressive-tool-disclosure.test.ts +++ b/agents/__tests__/base2-progressive-tool-disclosure.test.ts @@ -108,6 +108,7 @@ describe('base2 progressive tool disclosure (M1)', () => { 'check_job', 'check_background_agent', 'read_logs', + 'record_decision', 'edit_transaction', 'rename_symbol', 'code_action', @@ -597,6 +598,7 @@ describe('tier resolution helpers (M1-T3)', () => { expect(result).toEqual([ 'spawn_agents', 'read_files', + 'record_decision', 'edit_transaction', 'rename_symbol', 'code_action', @@ -630,6 +632,7 @@ describe('tier resolution helpers (M1-T3)', () => { expect(result).toEqual([ 'spawn_agents', 'read_files', + 'record_decision', 'edit_transaction', 'rename_symbol', 'code_action', @@ -654,6 +657,7 @@ describe('tier resolution helpers (M1-T3)', () => { expect(result).toEqual([ 'spawn_agents', 'read_files', + 'record_decision', 'edit_transaction', 'rename_symbol', 'code_action', @@ -702,6 +706,7 @@ describe('tier resolution helpers (M1-T3)', () => { expect(result).toEqual([ 'spawn_agents', 'read_files', + 'record_decision', 'edit_transaction', 'rename_symbol', 'code_action', @@ -749,6 +754,7 @@ describe('tier resolution helpers (M1-T3)', () => { 'create_plan', 'read_files', 'edit_transaction', + 'record_decision', 'rename_symbol', 'code_action', 'extract_symbol', @@ -785,6 +791,7 @@ describe('tier resolution helpers (M1-T3)', () => { expect(result).toEqual([ 'spawn_agents', 'read_files', + 'record_decision', 'edit_transaction', 'rename_symbol', 'code_action', @@ -879,9 +886,7 @@ describe('base2 tier membership — resolveModelToolNames stays in sync', () => ) for (const [tier, toolNames] of Object.entries(BASE2_TIER_TOOL_NAMES)) { for (const name of toolNames) { - const planArtifactTool = - name === 'create_plan' || name === 'update_plan_status' - expect(surface.has(name), `${tier}:${name}`).toBe(!planArtifactTool) + expect(surface.has(name), `${tier}:${name}`).toBe(name !== 'create_plan') } } }) diff --git a/agents/__tests__/base2-review-wave-credit.test.ts b/agents/__tests__/base2-review-wave-credit.test.ts index e64dab41ba..22e881dd66 100644 --- a/agents/__tests__/base2-review-wave-credit.test.ts +++ b/agents/__tests__/base2-review-wave-credit.test.ts @@ -151,6 +151,7 @@ function loadInlineReviewCreditHelpers(): { `const GATE_FILE_MISSING_CONTENT_MARKER = 'missing';\n` + `const GATE_MARKER_CACHE_MAX = 250;\n` + `const GATE_MARKER_CACHE_GRACE_MS = 3000;\n` + + `const gateProjectRoot = process.cwd();\nconst gateWorkspace = undefined;\n` + `const gateMarkerCache = new Map();\n` const epilogue = `\nreturn {\n recordWaveCompletionsForFiles,\n findDriftedPriorWaveFiles,\n invalidateWaveCompletionsForSpecialistBlockers,\n seedWaveLedgers: (completions, markers) => { activeWorkState.waveCompletions = completions; activeWorkState.specialistWaveCreditMarkers = markers; },\n isCreditEligibleSpecialistResult,\n boundNoVerdictDiagnosticCodes,\n boundWaveCompletions,\n getWaveCompletions: () => activeWorkState.waveCompletions,\n getWaveCreditMarkers: () => activeWorkState.specialistWaveCreditMarkers,\n resetWaveCompletions: () => { activeWorkState.waveCompletions = undefined; activeWorkState.specialistWaveCreditMarkers = undefined; },\n};\n` diff --git a/agents/__tests__/base2-writer-spawn-rules.test.ts b/agents/__tests__/base2-writer-spawn-rules.test.ts index 0cff9189a5..c4dc16a286 100644 --- a/agents/__tests__/base2-writer-spawn-rules.test.ts +++ b/agents/__tests__/base2-writer-spawn-rules.test.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' import { describe, expect, test } from 'bun:test' @@ -152,6 +153,7 @@ function loadInlineWriterTargetHelpers(): WriterTargetHelpers { 'isAlnumChar', 'basenameContainsSensitiveName', 'matchesSecuritySensitiveGlob', + 'isReviewableGateFile', 'selectAuxRelevantFiles', ] as const @@ -269,16 +271,26 @@ describe('base2 writer target selection predicates', () => { const commonGroup = selection.groups.find((group) => group.targetFiles.includes('common/src/util/array.ts'), ) - expect(agentsGroup?.testCommand).toBe( - 'cd agents && bun run typecheck && bun test', - ) + expect(agentsGroup?.testCommand).toBe('bun run test') expect(agentsGroup?.packageRoot).toBe('agents') - expect(commonGroup?.testCommand).toBe( - 'cd common && bun run typecheck && bun test', - ) + expect(commonGroup?.testCommand).toBe('bun run test') expect(commonGroup?.packageRoot).toBe('common') }) + test('keeps same-command fallback targets in distinct workspaces', () => { + const selection = helpers.selectTestWriterTargets([ + 'packages/alpha/src/item.ts', + 'packages/beta/src/item.ts', + 'src/root.ts', + ]) + expect(selection.groups.map(({ packageRoot, targetFiles }) => ({ packageRoot, targetFiles }))).toEqual([ + { packageRoot: 'packages/alpha', targetFiles: ['packages/alpha/src/item.ts'] }, + { packageRoot: 'packages/beta', targetFiles: ['packages/beta/src/item.ts'] }, + { packageRoot: '.', targetFiles: ['src/root.ts'] }, + ]) + expect(helpers.docWriterScopePatterns(['src/root.ts'])).toContain('docs/**') + }) + test('selectTestWriterTargets returns no groups for empty, test-only, or non-source files', () => { expect(helpers.selectTestWriterTargets([]).groups).toEqual([]) expect( @@ -351,6 +363,10 @@ describe('base2 writer target selection predicates', () => { ).toEqual(['agents/base2/base2.ts']) }) + test('keeps SQL and UI artifacts eligible for specialist routing without re-arming on docs', () => { + expect(helpers.selectAuxRelevantFiles(['db/bootstrap.sql', 'ui/theme.css', 'docs/example.html'])).toEqual(['db/bootstrap.sql', 'ui/theme.css']) + }) + test('selectAuxRelevantFiles reconstruction fails LOUDLY when a closed-over helper or constant is missing', () => { // selectAuxRelevantFiles closes over multiple local helpers // (isNonTestSourceFile / inferPackageTestCommand / isPublicApiSourceFile / @@ -538,15 +554,25 @@ describe('base2 writer request predicates and sequential aux gates', () => { expect(testWriterSpawn.input.params.target_files).toEqual([ 'agents/base2/base2.ts', ]) - expect(testWriterSpawn.input.params.test_command).toBe( - 'cd agents && bun run typecheck && bun test', - ) + expect(testWriterSpawn.input.params.test_command).toBe('bun run test') expect(testWriterSpawn.input.handoff.permissions.writablePaths).toEqual( expect.arrayContaining(['agents/**/*.test.*', 'agents/**/__tests__/**']), ) + expect(testWriterSpawn.input.handoff.permissions.allowedTools.toSorted()).toEqual( + ['edit_transaction', 'read_files', 'read_outline', 'set_output'], + ) // Inline spawn is sequential/blocking; writers are not launched via // spawn_agents batching that would run in parallel with each other. expect(testWriterSpawn.toolName).toBe('spawn_agent_inline') + const failure = gen.next({ toolResult: [{ type: 'json', value: {} }] } as any) + expect(failure.value).toMatchObject({ toolName: 'add_message' }) + expect((failure.value as any).input.content).toContain('still pending') + expect((agentState as any).base2ActiveWork).toMatchObject({ + currentPhase: 'blocked', + testWriterGateDone: false, + auxWriterRequests: { tests: 'Add tests for the new gate behavior' }, + }) + expect(gen.next().done).toBe(true) }) test('doc request spawns doc-writer after optional test gate with multi-root write scope', () => { @@ -585,6 +611,9 @@ describe('base2 writer request predicates and sequential aux gates', () => { expect(docWriterSpawn.input.params.source_files).toEqual([ 'common/src/util/array.ts', ]) + expect(docWriterSpawn.input.handoff.permissions.allowedTools.toSorted()).toEqual( + ['edit_transaction', 'read_files', 'read_outline', 'read_subtree', 'set_output'], + ) expect(docWriterSpawn.input.handoff.permissions.writablePaths).toEqual( expect.arrayContaining(['common/docs/**', 'common/**/*.md']), ) @@ -593,6 +622,112 @@ describe('base2 writer request predicates and sequential aux gates', () => { ]) }) + test('passes a package name containing spaces as Basher cwd, not shell text', () => { + const base2 = createBase2('default') + const source = 'packages/example workspace/src/item.ts' + const gen = base2.handleSteps!({ + agentState: { agentId: 'writer-cwd-fixture' }, + prompt: 'Add tests for this behavior', params: {}, config: base2.programmaticConfig, + } as any) + const result = (value: unknown) => ({ toolResult: [{ type: 'json', value }] }) as any + advanceToPostEditGitStatus(gen, source) + expect(gen.next(result({ status: ` M ${source}` })).value).toMatchObject({ toolName: 'inspect_environment' }) + expect(gen.next(result({})).value).toMatchObject({ toolName: 'get_affected_tests' }) + expect(gen.next(result({ targets: [] })).value).toMatchObject({ toolName: 'get_build_targets' }) + const packageRoot = 'packages/example workspace' + const cwd = '/owned-fixture/packages/example workspace' + const manifest = `${packageRoot}/package.json` + const writer = gen.next(result({ evidence: 'discovery-only', targets: [{ + packageRoot, manifest, workspace: { root: packageRoot, cwd, manifest, confidence: 'confirmed' }, + checks: [{ kind: 'test', basis: 'package-script', executable: 'bun', argv: ['run', 'test'], cwd, manifest, evidencePaths: [manifest] }], + }] })).value + expect(writer).toMatchObject({ toolName: 'spawn_agent_inline', input: { agent_type: 'test-writer', params: { test_command: 'bun run test' } } }) + expect(gen.next(result({ result: { type: 'structuredOutput' }, agentReceipt: { + schemaVersion: 1, receiptId: 'writer-cwd', status: 'completed', + changedFiles: [{ path: 'packages/example workspace/src/item.test.ts', mutationReceiptId: 'mutation-cwd' }], + output: { type: 'structuredOutput', value: { completionKind: 'changed', evidence: [] } }, + } })).value).toMatchObject({ toolName: 'spawn_agents', input: { agents: [{ + agent_type: 'basher', params: { command: 'bun run test', cwd: 'packages/example workspace' }, + }] } }) + }) + + test.each([false, true])('resumes unfinished package groups and reopens stale proof (drift=%p)', (drift) => { + const definition = createBase2('default') + const sources = ['a', 'b', 'c'].map((id) => `packages/writer-${id}/src/item.ts`) + const artifacts = sources.map((file) => file.replace('item.ts', 'item.test.ts')) + const files = new Map(sources.map((file) => [file, 'export const item = 1\n'])) + const headCommit = 'b'.repeat(40) + const workspace = { + identity: 'workspace-writer-resume', requestFingerprint: 'initial-request-key', + matchesCheckout: (root: string) => root === '/owned-fixture', + observeComparisonBasis: () => headCommit, + observe(path: string) { + const bytes = files.get(path) + return bytes === undefined ? { kind: 'absent' } : { + kind: 'file', digest: createHash('sha256').update(bytes).digest('hex'), + byteLength: Buffer.byteLength(bytes), + } + }, + } + const makeGenerator = (state: Record, prompt: string) => definition.handleSteps!({ + agentState: state, prompt, config: definition.programmaticConfig, + params: { orchestrationControlPlane: { gateWorkspace: workspace } }, + } as any) + const result = (value: unknown) => ({ toolResult: [{ type: 'json', value }] }) as any + const drive = (gen: ReturnType, start = gen.next()) => { + let step = start + const steps: unknown[] = [] + for (let i = 0; i < 40 && !step.done; i++) { + const call = step.value as any + steps.push(call?.toolName ?? call) + if (call?.toolName === 'spawn_agent_inline' && call.input.agent_type === 'test-writer') return call + if (call?.toolName === 'git_status') { + const changes = [...files.keys()].map((path) => ({ path, xy: ' M' })) + step = gen.next(result({ status: '', changes, workspaceBasis: { + kind: 'observed', checkoutRoot: '/owned-fixture', headCommit, confirmedDeletions: [], + } })) + } else if (call === 'STEP') { + step = gen.next({ stepsComplete: true, toolResult: sources.map((file) => ({ type: 'json', value: editReceipt(file) })) } as any) + } else if (['inspect_environment', 'get_affected_tests', 'get_build_targets'].includes(call?.toolName)) { + step = gen.next(result({ targets: [] })) + } else if ((call?.toolName === 'spawn_agent_inline' && call.input.agent_type === 'context-pruner') || call?.toolName === 'add_message') { + step = gen.next() + } else break + } + throw new Error(`Expected writer dispatch: ${JSON.stringify(steps)}`) + } + const writerResult = (index: number, status: 'completed' | 'partial') => { + files.set(artifacts[index]!, `export const testFixture = ${index}\n`) + return result({ result: { type: 'structuredOutput' }, agentReceipt: { + schemaVersion: 1, receiptId: `writer-${index}`, agentId: `writer-${index}`, status, + changedFiles: [{ path: artifacts[index], mutationReceiptId: `mutation-${index}` }], + output: { type: 'structuredOutput', value: { status, completionKind: 'changed', evidence: [] } }, + } }) + } + const state: Record = { agentId: 'writer-resume-root' } + const first = makeGenerator(state, 'Add tests for the requested behavior') + expect(drive(first).input.params.target_files).toEqual([sources[0]]) + expect(first.next(writerResult(0, 'completed')).value).toMatchObject({ + toolName: 'spawn_agents', input: { agents: [{ agent_type: 'basher' }] }, + }) + expect(drive(first, first.next(result({ executionStatus: { version: 1, kind: 'exited', exitCode: 0, source: 'host' } }))).input.params.target_files).toEqual([sources[1]]) + expect(first.next(writerResult(1, 'partial')).value).toMatchObject({ + toolName: 'add_message', input: { content: expect.stringContaining('tests are still pending') }, + }) + const persisted = JSON.parse(JSON.stringify(state)) + const rows = Object.values(persisted.base2ActiveWork.auxWriterGroupProgress.tests.groups) as Array<{ status: string }> + expect(rows.map(({ status }) => status)).toEqual(['complete', 'failed', 'pending']) + expect(files.has(artifacts[1]!)).toBe(true) + if (drift) files.set(artifacts[0]!, 'export const testFixture = 9\n') + const resumed = makeGenerator(persisted, 'Continue the pending deliverables') + const selected = drift ? 0 : 1 + expect(drive(resumed).input.params.target_files).toEqual([sources[selected]]) + if (!drift) { + expect(resumed.next(writerResult(1, 'completed')).value).toMatchObject({ toolName: 'spawn_agents' }) + expect(drive(resumed, resumed.next(result({ executionStatus: { version: 1, kind: 'exited', exitCode: 0, source: 'host' } }))).input.params.target_files).toEqual([sources[2]]) + } + }) + test('combined test+docs request runs writers sequentially, not in parallel', () => { const base2 = createBase2('default') const agentState = { agentId: 'base2-custom' } @@ -651,6 +786,7 @@ describe('editor / repair-editor / test-writer cohesion', () => { agentState, prompt: 'Make the requested change now please', params: {}, + config: base2.programmaticConfig, } as any) advanceToPostEditGitStatus(gen, 'src/a.ts') @@ -715,6 +851,13 @@ describe('editor / repair-editor / test-writer cohesion', () => { }) expect(repairSpawn.input.agents).toHaveLength(1) expect(repairSpawn.input.agents[0].agent_type).not.toBe('repair-editor') + const permissions = repairSpawn.input.agents[0].handoff.permissions + expect(permissions.allowedTools.toSorted()).toEqual( + ['edit_transaction', 'read_files', 'read_outline', 'set_output'], + ) + expect(permissions.writablePaths).toContain('**/tests/**') + expect(permissions.writablePaths).toContain('**/*.test.*') + expect(permissions.writablePaths).not.toContain('src/a.ts') }) test('mixed code + coverage findings keep repair-editor only (no parallel test-writer)', () => { @@ -798,7 +941,7 @@ describe('editor / repair-editor / test-writer cohesion', () => { 'You cannot observe results from parallel agents unless the prompt explicitly includes those completed results', ) expect(reviewer.spawnableAgents).toEqual([]) - expect(reviewer.toolNames).toEqual(['read_files', 'set_output']) + expect(reviewer.toolNames).toEqual(['read_files', 'code_search', 'set_output']) }) test('createSpecialist agents never spawn editor/repair-editor/test-writer children', () => { diff --git a/agents/__tests__/base2.test.ts b/agents/__tests__/base2.test.ts index c6545ad2a5..c0cd99afa3 100644 --- a/agents/__tests__/base2.test.ts +++ b/agents/__tests__/base2.test.ts @@ -11,6 +11,7 @@ import { join } from 'node:path' import { afterAll, describe, expect, test } from 'bun:test' import { transitionBase2GateSafe } from '@codebuff/agent-runtime/orchestration/workflow-engine' +import { buildReviewImpactPacket, resolveReviewImpact } from '@codebuff/common/agents/review-impact' import { getEffectiveAgentToolNames } from '@codebuff/agent-runtime/util/agent-tool-names' import { createBaseDeep } from '../base2/base-deep' @@ -310,7 +311,7 @@ function attestedReviewerResult( function repairSpawnReport(params: { receiptId: string status: string - changedFiles: Array<{ path: string }> + changedFiles: Array<{ path: string; mutationReceiptId?: string }> findingsAddressed: string[] requestedValidation?: string[] value?: Record @@ -345,7 +346,7 @@ function completedRepairReceipt(findingIds: string[], files: string[]) { return repairSpawnReport({ receiptId: 'repair-receipt', status: 'completed', - changedFiles: files.map((path) => ({ path })), + changedFiles: files.map((path) => ({ path, mutationReceiptId: `fixture-mutation:${path}` })), findingsAddressed: findingIds, value: { status: 'completed', @@ -360,7 +361,7 @@ function progressOnlyRepairReceipt(files: string[]) { return repairSpawnReport({ receiptId: 'repair-progress-only', status: 'blocked', - changedFiles: files.map((path) => ({ path })), + changedFiles: files.map((path) => ({ path, mutationReceiptId: `fixture-mutation:${path}` })), findingsAddressed: [], value: { status: 'blocked', @@ -427,10 +428,6 @@ type InlineCondoneHelpers = { strippedText: string, id?: string, ) => boolean - legacyCondonedTextMatches: ( - condonedTexts: Set, - text: string, - ) => boolean boundCondonedEntries: (values: string[]) => string[] correlateReviewerFindingRecord: ( blockerText: string, @@ -441,9 +438,8 @@ type InlineCondoneHelpers = { // The condone helpers live inside the serialized handleSteps generator, so they // cannot be imported. Reconstruct them together with the helpers they close over // (stripReviewerVerdictPrefix / isMintedReviewerFindingId / -// condonedFindingKeysFor) so the class-matching, legacy-fallback, bounding, and -// record-correlation rules can be asserted directly instead of only through a -// full gate lifecycle. +// condonedFindingKeysFor) so class-matching, bounding and record-correlation +// can be asserted directly instead of only through a full gate lifecycle. function loadInlineCondoneHelpers(): InlineCondoneHelpers { const base2Source = readFileSync( new URL('../base2/base2.ts', import.meta.url), @@ -456,10 +452,9 @@ function loadInlineCondoneHelpers(): InlineCondoneHelpers { extractInlineFunctionSource(base2Source, 'isMintedReviewerFindingId'), extractInlineFunctionSource(base2Source, 'condonedFindingKeysFor'), extractInlineFunctionSource(base2Source, 'condonedKeyMatches'), - extractInlineFunctionSource(base2Source, 'legacyCondonedTextMatches'), extractInlineFunctionSource(base2Source, 'boundCondonedEntries'), extractInlineFunctionSource(base2Source, 'correlateReviewerFindingRecord'), - 'return { condonedKeyMatches, legacyCondonedTextMatches, boundCondonedEntries, correlateReviewerFindingRecord }', + 'return { condonedKeyMatches, boundCondonedEntries, correlateReviewerFindingRecord }', ].join('\n') const combinedJs = transpiler.transformSync(combinedTs) const buildHelpers = new Function( @@ -561,7 +556,6 @@ describe('base2 inline repairEditorReadablePaths', () => { describe('base2 inline condone helpers', () => { const { condonedKeyMatches, - legacyCondonedTextMatches, boundCondonedEntries, correlateReviewerFindingRecord, } = loadInlineCondoneHelpers() @@ -632,21 +626,6 @@ describe('base2 inline condone helpers', () => { ).toBe(false) }) - // RF-6: the pre-T1.5 legacy text fallback is one helper, so all three call - // sites accept both the stripped text and the raw prefixed blocker. - test('the legacy text fallback matches both stripped and raw prefixed blockers', () => { - const strippedOnly = new Set([findingText]) - expect( - legacyCondonedTextMatches(strippedOnly, `NON_BLOCKING: ${findingText}`), - ).toBe(true) - expect(legacyCondonedTextMatches(strippedOnly, findingText)).toBe(true) - const rawOnly = new Set([`BLOCKING: ${findingText}`]) - expect(legacyCondonedTextMatches(rawOnly, `BLOCKING: ${findingText}`)).toBe( - true, - ) - expect(legacyCondonedTextMatches(rawOnly, 'A different nit.')).toBe(false) - }) - // RF-4: the durable condone lists are bounded like reviewReceipts. test('boundCondonedEntries dedupes and keeps only the most recent 200 entries', () => { const bounded = boundCondonedEntries( @@ -1571,7 +1550,7 @@ describe('base2 verification and reviewer gates', () => { toolResult: [ { type: 'json', - value: [{ hookName: 'typecheck', exitCode: 1, stderr: 'TS2322' }], + value: [{ hookName: 'tests', exitCode: 1, stderr: 'AssertionError: application timeout should be configurable' }], }, ], } as any) @@ -1596,7 +1575,10 @@ describe('base2 verification and reviewer gates', () => { }) }) - test('passing verification hooks trigger code review before completion for non-allowlisted default ids', () => { + test.each([ + ['no_hooks_configured', 'No configured file-change hooks ran.'], + ['hooks_skipped', 'Configured file-change hooks were skipped because none matched the changed files.'], + ])('review may finish but %s must not report passing validation', (hookStatus, hookMessage) => { const tmpDir = makeProjectTempDir('base2-passing-hooks-review-') try { const base2 = createBase2('default') @@ -1638,9 +1620,8 @@ describe('base2 verification and reviewer gates', () => { type: 'json', value: [ { - validationStatus: 'hooks_skipped', - message: - 'Configured file-change hooks were skipped because none matched the changed files.', + validationStatus: hookStatus, + message: hookMessage, configuredHookCount: 1, changedFiles: [gateFile], }, @@ -1657,7 +1638,7 @@ describe('base2 verification and reviewer gates', () => { input: { agents: [{ agent_type: 'code-reviewer' }] }, }) expect((agentState as any).base2ActiveWork.lastValidationSummary).toBe( - 'REDUCED_ASSURANCE: Configured file-change hooks were skipped because none matched the changed files.', + `REDUCED_ASSURANCE: ${hookMessage}`, ) const afterReview = gen.next( attestedReviewerResult(reviewCall.value) as any, @@ -1678,9 +1659,11 @@ describe('base2 verification and reviewer gates', () => { ) expect(passGate).toMatchObject({ gate: 'validation/reviewer', - status: 'passed', + status: 'skipped', }) expect(passGate!.details).toContain('LOOKS_GOOD') + expect(passGate!.details).toContain(hookMessage) + expect(passGate!.details).not.toContain('validation hooks ran;') expect((agentState as any).base2ActiveWork).toMatchObject({ changedFiles: [gateFile], touchedFiles: [gateFile], @@ -3233,7 +3216,11 @@ describe('base2 verification and reviewer gates', () => { schemaVersion: 1, receiptId: 'editor-batch-receipt', status: 'completed', - changedFiles: [{ path: 'src/one.ts' }, { path: 'src/two.ts' }], + changedFiles: [ + { path: 'src/one.ts', mutationReceiptId: 'native-one' }, + { path: 'src/two.ts', mutationReceiptId: 'native-two' }, + { path: 'src/no-proof.ts' }, + ], findingsAddressed: [], requestedValidation: [], } @@ -3254,9 +3241,7 @@ describe('base2 verification and reviewer gates', () => { ], } as any).value, ).toMatchObject({ toolName: 'git_status' }) - expect((agentState as any).base2ActiveWork.pendingGateFiles).toEqual( - expect.arrayContaining(['src/one.ts', 'src/two.ts']), - ) + expect((agentState as any).base2ActiveWork.pendingGateFiles).toEqual(['src/one.ts', 'src/two.ts']) expect((agentState as any).base2ActiveWork.currentPhase).toBe( 'awaiting_validation', ) @@ -3509,7 +3494,7 @@ describe('base2 verification and reviewer gates', () => { ) }) - test('direct edit tool calls in message history trigger gates when git status was already dirty', () => { + test('a confirmed direct edit in message history revalidates an already dirty file', () => { // Use a real on-disk file so creditGatePassedFiles can store an attestable // content marker. A virtual path cannot be credited; P0 would re-arm on the // next loop and the generator would not finish. @@ -3561,10 +3546,7 @@ describe('base2 verification and reviewer gates', () => { content: [ { type: 'json', - value: { - file: gateFile, - message: 'String replace applied successfully.', - }, + value: editReceipt(gateFile), }, ], }, @@ -3646,7 +3628,7 @@ describe('base2 verification and reviewer gates', () => { } }) - test('apply_patch calls in message history trigger gates when git status was already dirty', () => { + test('a compatibility patch with a confirmed mutation receipt triggers the gate', () => { const base2 = createBase2('default') const initialMessage = { role: 'user', @@ -3695,10 +3677,7 @@ describe('base2 verification and reviewer gates', () => { content: [ { type: 'json', - value: { - message: 'Patch applied successfully.', - applied: [{ file: 'src/already-dirty.ts', action: 'update' }], - }, + value: editReceipt('src/already-dirty.ts'), }, ], }, @@ -3722,7 +3701,7 @@ describe('base2 verification and reviewer gates', () => { }) }) - test('apply_smart_patch calls in message history trigger gates when git status was already dirty', () => { + test('an unconfirmed patch request cannot adopt an already dirty file', () => { const base2 = createBase2('default') const initialMessage = { role: 'user', @@ -3775,10 +3754,8 @@ describe('base2 verification and reviewer gates', () => { ], } as any) - expect(afterGit.value).toMatchObject({ - toolName: 'run_file_change_hooks', - input: { files: ['src/already-dirty.ts'] }, - }) + expect(afterGit.value).toMatchObject({ toolName: 'add_message' }) + expect((afterGit.value as any).input.content).toContain('No edited files were detected') }) test('prior write_todos state in message history is pinned before the next step', () => { @@ -4018,6 +3995,13 @@ describe('base2 verification and reviewer gates', () => { }, ], }, + { + role: 'tool', toolName: 'edit_transaction', toolCallId: 'tool-call-1', + content: [ + { type: 'json', value: editReceipt('src/one.ts') }, + { type: 'json', value: editReceipt('src/two.ts') }, + ], + }, ], }, } as any).value, @@ -4110,7 +4094,7 @@ describe('base2 verification and reviewer gates', () => { expect(done.done).toBe(true) }) - test('fast/no-validation mode skips file-change hooks and reviewer after edits', () => { + test('fast mode skips the automatic gate with its shipped serialized config', () => { const base2 = createBase2('fast') expect(base2.spawnableAgents).toContain('code-reviewer') const agentState = { agentId: 'base2-fast' } @@ -4118,6 +4102,7 @@ describe('base2 verification and reviewer gates', () => { agentState, prompt: 'Make the requested change now please', params: {}, + config: base2.programmaticConfig, } as any) expect(gen.next().value).toMatchObject({ toolName: 'git_status' }) @@ -5036,7 +5021,7 @@ describe('base2 verification and reviewer gates', () => { repairSpawnReport({ receiptId: 'repair-progress-addressing-finding', status: 'blocked', - changedFiles: [{ path: gateFile }], + changedFiles: [{ path: gateFile, mutationReceiptId: 'retained-progress' }], findingsAddressed: [findingId], }) as any, ).value, @@ -6770,7 +6755,7 @@ describe('base2 verification and reviewer gates', () => { schemaVersion: 1, receiptId: 'tw-receipt', status: 'completed', - changedFiles: [{ path: 'agents/__tests__/base2.test.ts' }], + changedFiles: [{ path: 'agents/__tests__/base2.test.ts', mutationReceiptId: 'fixture-mutation' }], findingsAddressed: [], requestedValidation: [], completionKind: 'changed', @@ -6796,7 +6781,7 @@ describe('base2 verification and reviewer gates', () => { const dirtyStatus = ' M agents/base2/base2.ts\n M agents/__tests__/base2.test.ts' let hookStep = gen.next({ - toolResult: [{ type: 'json', value: [] }], + toolResult: [{ type: 'json', value: { exitCode: 0 } }], } as any).value as any let hookGuard = 0 while ( @@ -7115,11 +7100,6 @@ describe('base2 verification and reviewer gates', () => { gen.next({ toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], } as any).value, - ).toMatchObject({ - toolName: 'run_file_change_hooks', - }) - expect( - gen.next({ toolResult: [{ type: 'json', value: [] }] } as any).value, ).toMatchObject({ toolName: 'git_status' }) const secondReviewCall = gen.next({ toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], @@ -7128,7 +7108,7 @@ describe('base2 verification and reviewer gates', () => { return secondReviewCall } - test('same NON_BLOCKING finding text after repair-editor addressed it finalizes instead of looping', () => { + test('a fresh clean reviewer verdict clears the prior finding after repair', () => { const findingText = 'Minor style suggestion.' const { gen, agentState, reviewCall, tmpDir, tmpFile, gateFile } = driveToFirstReview() @@ -7145,24 +7125,14 @@ describe('base2 verification and reviewer gates', () => { expect( (agentState as any).base2ActiveWork.condonedFindingTexts, ).toContain(findingText) - // Second reviewer pass returns the SAME finding text (stale re-derivation). - const secondReview = attestedReviewerResult( - secondReviewCall, - 'NON_BLOCKING', - [findingText], + const afterSecond = gen.next( + attestedReviewerResult(secondReviewCall, 'LOOKS_GOOD', []) as any, ) - const afterSecond = gen.next(secondReview as any) - // The condoned filter suppressed every blocker, so the gate must NOT - // re-enter the repair loop; the condoned pass credits the review as - // LOOKS_GOOD and finalization proceeds. const active = (agentState as any).base2ActiveWork expect(active.currentPhase).not.toBe('repair_loop') expect(active.currentPhase).not.toBe('blocked') - expect(active.openReviewerBlockers ?? []).not.toContain( - `NON_BLOCKING: ${findingText}`, - ) - // Drive the finalization: git_status -> gate-passed add_message. No - // repair-editor spawn may appear. + // The clean verdict still needs the final snapshot check before clearing + // the recorded blockers; the repair claim never clears them by itself. expect(afterSecond.value).toMatchObject({ toolName: 'git_status' }) const gatePassed = gen.next({ toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], @@ -7254,7 +7224,7 @@ describe('base2 verification and reviewer gates', () => { ) expect(gateState).toMatchObject({ gate: 'validation/reviewer', - status: 'passed', + status: 'skipped', }) expect(gateState!.advisories).toEqual(expectedGateStateAdvisories) for (const advisory of gateState!.advisories ?? []) { @@ -7428,51 +7398,37 @@ describe('base2 verification and reviewer gates', () => { } }) - // Same-class re-raise: a NON_BLOCKING finding already reported as addressed - // and re-raised as NON_BLOCKING carries no new information, so the loop must - // converge. (The de-escalation direction is the separate test below.) - test('a condoned finding re-raised at the same class still converges', () => { - const findingText = 'Minor style suggestion.' - const { gen, agentState, reviewCall, tmpDir, tmpFile, gateFile } = - driveToFirstReview() - try { - const secondReviewCall = driveThroughRepairToSecondReview( - gen, - agentState, - reviewCall, - tmpFile, - gateFile, - findingText, - ) - const secondReview = attestedReviewerResult( - secondReviewCall, - 'NON_BLOCKING', - [findingText], - ) - const afterSecond = gen.next(secondReview as any) - const active = (agentState as any).base2ActiveWork - expect(active.currentPhase).not.toBe('repair_loop') - expect(active.currentPhase).not.toBe('blocked') - // Condoned pass: finalization, not another repair spawn. - expect(afterSecond.value).toMatchObject({ toolName: 'git_status' }) - const gatePassed = gen.next({ - toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], - } as any) - expect((gatePassed.value as any).input.content).toMatch( - /reviewer gate passed with LOOKS_GOOD/i, - ) - } finally { - rmSync(tmpDir, { recursive: true, force: true }) - } - }) + test.each(['NON_BLOCKING', 'BLOCKING'] as const)( + 'an independent %s re-raise stays open after a repair claim', + (verdict) => { + const findingText = 'The selected validation case still fails.' + const { gen, agentState, reviewCall, tmpDir, tmpFile, gateFile } = + driveToFirstReview() + try { + const secondReviewCall = driveThroughRepairToSecondReview( + gen, agentState, reviewCall, tmpFile, gateFile, findingText, verdict, + ) + const afterSecond = gen.next( + attestedReviewerResult(secondReviewCall, verdict, [findingText]) as any, + ) + expect(afterSecond.value).toMatchObject({ toolName: 'add_message' }) + const text = (afterSecond.value as any).input.content + expect(text).toContain('still open') + expect(parseGateStateBlock(text)).toMatchObject({ + gate: 'reviewer', status: 'failed', skipReason: 'reviewer-findings-persist-after-repair', + }) + const active = (agentState as any).base2ActiveWork + expect(active.currentPhase).toBe('blocked') + expect(active.openReviewerBlockers).toContain(`${verdict}: ${findingText}`) + expect(active.reviewReceipts).toEqual([]) + expect(gen.next().done).toBe(true) + } finally { + rmSync(tmpDir, { recursive: true, force: true }) + } + }, + ) - // RF-1/RF-2/RF-8: de-escalation is the mirror of the escalation case above and - // IS condonable, one-directionally. A finding condoned at BLOCKING and - // re-raised as a NON_BLOCKING nit carries no new information; if it were not - // condoned the blocker list would stay non-empty, another repair-editor would - // be spawned, and the already-applied repair would trip the no-progress guard, - // leaving the gate 'blocked' instead of converging. - test('a finding condoned at BLOCKING and re-raised as NON_BLOCKING still converges', () => { + test('a BLOCKING finding re-raised as NON_BLOCKING remains open', () => { const findingText = 'Minor style suggestion.' const { gen, agentState, reviewCall, tmpDir, tmpFile, gateFile } = driveToFirstReview() @@ -7503,28 +7459,12 @@ describe('base2 verification and reviewer gates', () => { [findingText], ) const afterSecond = gen.next(secondReview as any) - expect(active.currentPhase).not.toBe('repair_loop') - expect(active.currentPhase).not.toBe('blocked') - // Condoned pass: git_status -> gate-passed add_message, no repair spawn. - expect(afterSecond.value).toMatchObject({ toolName: 'git_status' }) - const gatePassed = gen.next({ - toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], - } as any) - expect(gatePassed.value).toMatchObject({ - toolName: 'add_message', - input: { role: 'user' }, - }) - expect((gatePassed.value as any).input.content).toMatch( - /reviewer gate passed with LOOKS_GOOD/i, - ) - expect((agentState as any).base2ActiveWork.currentPhase).toBe( - 'final_response_allowed', - ) - // The first round's BLOCKING blocker string is cleared by the - // condoned-pass cleanup rather than left looking open. - expect((agentState as any).base2ActiveWork.openReviewerBlockers).toEqual( - [], - ) + expect(afterSecond.value).toMatchObject({ toolName: 'add_message' }) + expect((afterSecond.value as any).input.content).toContain('still open') + expect(active.currentPhase).toBe('blocked') + expect(active.openReviewerBlockers).toContain(`NON_BLOCKING: ${findingText}`) + expect(active.reviewReceipts).toEqual([]) + expect(gen.next().done).toBe(true) } finally { rmSync(tmpDir, { recursive: true, force: true }) } @@ -7614,13 +7554,7 @@ describe('base2 verification and reviewer gates', () => { } }) - // RF-1: the condoned-pass cleanup used to filter openReviewerBlockers by - // STRIPPED TEXT only. mergeReviewerFindings retains other families' blockers, - // so a security-reviewer `BLOCKING: ` blocker that was never - // condoned was silently dropped when the code-reviewer round credited a - // condoned pass. The cleanup must key on (verdict class, identity) like every - // other condone decision. - test('condoned pass keeps another reviewer BLOCKING blocker that shares the condoned text', () => { + test('the repeated finding and another reviewer’s same-text blocker both stay open', () => { const findingText = 'Minor style suggestion.' const securityBlocker = `BLOCKING: ${findingText}` const tmpDir = makeProjectTempDir('base2-condoned-cleanup-') @@ -7700,17 +7634,14 @@ describe('base2 verification and reviewer gates', () => { const reviewCall = gen.next(feedJson({ status: ` M ${gateFile}` })) .value as any expect(reviewCall).toMatchObject({ toolName: 'spawn_agents' }) - // Every collected blocker is condoned, so the round credits a condoned - // pass and runs the cleanup instead of spawning repair-editor. const afterReview = gen.next( - attestedReviewerResult(reviewCall, 'NON_BLOCKING', [ - findingText, - ]) as any, + attestedReviewerResult(reviewCall, 'NON_BLOCKING', [findingText]) as any, ) - expect(afterReview.value).toMatchObject({ toolName: 'git_status' }) + expect(afterReview.value).toMatchObject({ toolName: 'add_message' }) const active = (agentState as any).base2ActiveWork - // The never-condoned security blocker survives the cleanup. + expect(active.currentPhase).toBe('blocked') expect(active.openReviewerBlockers).toContain(securityBlocker) + expect(active.openReviewerBlockers).toContain(`NON_BLOCKING: ${findingText}`) } finally { rmSync(tmpDir, { recursive: true, force: true }) } @@ -7983,7 +7914,7 @@ describe('base2 verification and reviewer gates', () => { const blockedReceipt = repairSpawnReport({ receiptId: 'repair-blocked-claiming-findings', status: 'blocked', - changedFiles: [{ path: gateFile }], + changedFiles: [{ path: gateFile, mutationReceiptId: 'retained-blocked-progress' }], findingsAddressed: findingIds, value: { status: 'blocked', @@ -8023,9 +7954,6 @@ describe('base2 verification and reviewer gates', () => { gen.next({ toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], } as any).value, - ).toMatchObject({ toolName: 'run_file_change_hooks' }) - expect( - gen.next({ toolResult: [{ type: 'json', value: [] }] } as any).value, ).toMatchObject({ toolName: 'git_status' }) const secondReviewCall = gen.next({ toolResult: [{ type: 'json', value: { status: ` M ${gateFile}` } }], @@ -8961,7 +8889,148 @@ describe('base2 validation-first reviewer snapshots', () => { }) describe('base2 repair-loop gate-state telemetry (M6.4)', () => { - test('repair-incomplete gate-state block surfaces repairRound and maxRepairRounds', () => { + test('checks a stable postimage but blocks hooks that rewrite the reviewed path every time', () => { + const temp = makeProjectTempDir('mutating-hook-') + try { + const absolute = join(temp, 'ordinary.ts') + writeFileSync(absolute, 'export const value = 1\n') + const file = normalizeGateFilePath(absolute) + const state = { agentId: 'base2-custom' } as any + const gen = createBase2('default').handleSteps!({ agentState: state, prompt: 'Make the requested change.', params: {} } as any) + expect(gen.next().value).toMatchObject({ toolName: 'git_status' }) + expect(gen.next(feedJson({ status: '' })).value).toMatchObject({ toolName: 'spawn_agent_inline' }) + expect(gen.next().value).toBe('STEP') + expect(gen.next(finishStepWithToolResult(editReceipt(file))).value).toMatchObject({ toolName: 'git_status' }) + let next = gen.next(feedJson({ status: ` M ${file}` })) + let executed = 0 + for (let i = 0; i < 30 && !next.done; i++) { + const call = next.value as any + if (call?.toolName === 'run_file_change_hooks') { + expect(call.input.files).toEqual([file]) + executed++ + writeFileSync(absolute, `export const value = ${10 ** executed}\n`) + next = gen.next(feedJson([{ hookName: 'format-and-test', executionStatus: { version: 1, kind: 'exited', exitCode: 0, source: 'host' }, exitCode: 0 }])) + } else if (call?.toolName === 'git_status') { + next = gen.next(feedJson({ status: ` M ${file}` })) + } else { + expect(call).not.toBe('STEP') + expect(call?.input?.agents?.some((agent: any) => agent.agent_type === 'code-reviewer')).not.toBe(true) + next = gen.next() + } + } + expect(next.done).toBe(true) + expect(executed).toBe(3) + expect(state.base2ActiveWork).toMatchObject({ + currentPhase: 'blocked', lastReviewerGateSkipReason: 'validation-hooks-nonconvergent', validationEvidence: [], + }) + expect(state.base2GateVerification).toBeUndefined() + } finally { + rmSync(temp, { recursive: true, force: true }) + } + }) + + test('requires a specialist for manifest-only delivery even with an empty change bundle', () => { + const temp = makeProjectTempDir('manifest-delivery-') + try { + const absolute = join(temp, 'package.json') + writeFileSync(absolute, '{"dependencies":{"fixture":"1.0.0"}}\n') + const file = normalizeGateFilePath(absolute) + const state = { agentId: 'base2-custom' } as any + const gen = createBase2('default').handleSteps!({ agentState: state, prompt: 'Commit these changes only.', params: {} } as any) + const status = feedJson({ status: ` M ${file}` }) + expect(gen.next().value).toMatchObject({ toolName: 'git_status' }) + let next = gen.next(status) + for (let i = 0; i < 24 && !next.done; i++) { + const call = next.value as any + if (call?.toolName === 'spawn_agents') { + expect(call.input.agents).toEqual(expect.arrayContaining([expect.objectContaining({ + agent_type: 'dependency-reviewer', params: expect.objectContaining({ files: [file], snapshot_id: expect.stringMatching(/^v3:/) }), + })])) + expect(state.base2GateVerification).toBeUndefined() + return + } + expect(call?.toolName).not.toBe('run_file_change_hooks') + if (call === 'STEP') next = gen.next(finishStepWithToolResult({})) + else if (call?.toolName === 'git_status') next = gen.next(status) + else if (call?.toolName === 'get_change_review_bundle') next = gen.next(feedJson({ files: [], changes: [] })) + else next = gen.next() + } + throw new Error('Expected a manifest-only change to require a scoped specialist review') + } finally { + rmSync(temp, { recursive: true, force: true }) + } + }) + + test('explicitly adopted protected config is a review gap without reads or validation', () => { + const state = { agentId: 'base2-custom' } as any + const gen = createBase2('default').handleSteps!({ agentState: state, prompt: 'Commit these changes; do not push.', params: {} } as any) + const dirty = feedJson({ status: ' M config/.env' }) + expect(gen.next().value).toMatchObject({ toolName: 'git_status' }) + let next = gen.next(dirty) + for (let i = 0; i < 20 && !next.done; i++) { + const call = next.value as any + if (call === 'STEP') next = gen.next(finishStepWithToolResult({})) + else if (call?.toolName === 'git_status') next = gen.next(dirty) + else { + expect(['spawn_agents', 'read_files', 'run_file_change_hooks']).not.toContain(call?.toolName) + next = gen.next() + } + } + expect(next.done).toBe(true) + expect(state.base2ActiveWork).toMatchObject({ + pendingGateFiles: ['config/.env'], currentPhase: 'blocked', lastReviewerGateSkipReason: 'security-review-evidence-unavailable', + }) + expect(state.base2GateVerification).toBeUndefined() + }) + + test.each([true, false])('only a receipted repair adopts a pre-dirty diagnostic and rechecks once (%p)', (confirmed) => { + const base2 = createBase2('default') + const state = { agentId: 'base2-custom' } as any + const gen = base2.handleSteps!({ agentState: state, prompt: 'Implement the scoped change.', params: {} } as any) + const pending = 'src/owned.ts' + const diagnostic = 'src/diagnosed.ts' + const foreign = 'src/other-actor.ts' + const diff = (...files: string[]) => feedJson({ status: files.map((file) => ` M ${file}`).join('\n') }) + expect(gen.next().value).toMatchObject({ toolName: 'git_status' }) + expect(gen.next(diff(diagnostic, foreign)).value).toMatchObject({ toolName: 'spawn_agent_inline' }) + expect(gen.next().value).toBe('STEP') + expect(gen.next(finishStepWithToolResult(editReceipt(pending))).value).toMatchObject({ toolName: 'git_status' }) + expect(gen.next(diff(pending, diagnostic, foreign)).value).toMatchObject({ toolName: 'run_file_change_hooks', input: { files: [pending] } }) + const repair = gen.next(feedJson([{ hookName: 'typecheck', exitCode: 1, stderr: `${diagnostic}(1,1): error TS1234: type error` }])).value as any + expect(repair).toMatchObject({ toolName: 'spawn_agents', input: { agents: [{ + agent_type: 'repair-editor', handoff: { findings: [{ id: 'VF-1', files: [diagnostic] }], permissions: { writablePaths: [diagnostic] } }, + }] } }) + const report = repairSpawnReport({ + receiptId: 'repair-scope', status: 'completed', + changedFiles: [{ path: diagnostic, ...(confirmed && { mutationReceiptId: 'host-mutation-b' }) }], + findingsAddressed: ['VF-1'], value: { status: 'completed' }, + }) + let next = gen.next(report as any) + if (!confirmed) { + expect(state.base2ActiveWork.pendingGateFiles).toEqual([pending]) + expect(state.base2ActiveWork.currentPhase).toBe('blocked') + expect(next.done).toBe(true) + return + } + expect(next.value).toMatchObject({ toolName: 'git_status' }) + next = gen.next(diff(pending, diagnostic, foreign)) + expect(next.value).toMatchObject({ toolName: 'run_file_change_hooks', input: { files: [pending, diagnostic] } }) + next = gen.next(feedJson([{ hookName: 'typecheck-after-repair', executionStatus: { version: 1, kind: 'exited', exitCode: 0, source: 'host' }, exitCode: 0 }])) + for (let i = 0; i < 16 && !next.done; i++) { + const call = next.value as any + if (call?.toolName === 'spawn_agents' && call.input.agents[0]?.agent_type === 'code-reviewer') { + expect(call.input.agents[0].prompt).toContain('Configured file-change hooks passed: typecheck-after-repair.') + expect(call.input.agents[0].prompt).not.toContain(foreign) + return + } + expect(call?.toolName).not.toBe('run_file_change_hooks') + expect(call).not.toBe('STEP') + next = gen.next(call?.toolName === 'git_status' ? diff(pending, diagnostic, foreign) : undefined) + } + throw new Error('Expected the repaired snapshot to advance directly to code review') + }) + + test('validation repair scopes a finding to the diagnosed file and reports incomplete recheck', () => { const base2 = createBase2('default') const agentState = { agentId: 'base2-custom' } const gen = base2.handleSteps!({ @@ -8997,14 +9066,14 @@ describe('base2 repair-loop gate-state telemetry (M6.4)', () => { toolName: 'run_file_change_hooks', }) - // Validation fails with a parseable (tsc-shaped) failure -> repair loop. + // Validation fails on a different file with a parseable tsc diagnostic. const typecheckFailure = { type: 'json', value: [ { hookName: 'typecheck', exitCode: 1, - stderr: 'src/a.ts(1,1): error TS1234: type error', + stderr: 'src/diagnosed.ts(1,1): error TS1234: type error', }, ], } @@ -9022,7 +9091,10 @@ describe('base2 repair-loop gate-state telemetry (M6.4)', () => { repairSpawn.input.agents[0].handoff.permissions .readablePaths as string[], ), - ).toEqual(new Set(['src/a.ts', 'src/**/*'])) + ).toEqual(new Set(['src/a.ts', 'src/diagnosed.ts', 'src/**/*'])) + expect(repairSpawn.input.agents[0].handoff.findings).toMatchObject([ + { id: 'VF-1', files: ['src/diagnosed.ts'] }, + ]) expect( repairSpawn.input.agents[0].handoff.permissions.readablePaths, ).not.toContain('.env') @@ -9041,19 +9113,17 @@ describe('base2 repair-loop gate-state telemetry (M6.4)', () => { ) expect( repairSpawn.input.agents[0].handoff.permissions.writablePaths, - ).toEqual(['src/a.ts']) + ).toEqual(['src/diagnosed.ts']) // Repair editor ran; git_status after the repair editor. expect( - gen.next(completedRepairReceipt(['VF-1'], ['src/a.ts']) as any).value, - ).toMatchObject({ - toolName: 'git_status', - }) - // Re-verify hooks run after the repair editor. + gen.next(completedRepairReceipt(['VF-1'], ['src/diagnosed.ts']) as any).value, + ).toMatchObject({ toolName: 'git_status' }) + // Re-verify both the old pending file and the diagnosed path. expect( gen.next({ - toolResult: [{ type: 'json', value: { status: ' M src/a.ts' } }], + toolResult: [{ type: 'json', value: { status: ' M src/a.ts\n M src/diagnosed.ts' } }], } as any).value, - ).toMatchObject({ toolName: 'run_file_change_hooks' }) + ).toMatchObject({ toolName: 'run_file_change_hooks', input: { files: ['src/a.ts', 'src/diagnosed.ts'] } }) // Re-verify still fails -> the repair-incomplete blocked path emits the // gate-state block carrying structured repair-loop progress. @@ -9106,7 +9176,7 @@ describe('base2 repair-loop gate-state telemetry (M6.4)', () => { expect(parsed).toBeDefined() expect(parsed!.gate).toBe('validation/reviewer') - expect(parsed!.status).toBe('passed') + expect(parsed!.status).toBe('skipped') expect(parsed!.repairRound).toBeUndefined() expect(parsed!.maxRepairRounds).toBeUndefined() }) @@ -9173,7 +9243,7 @@ describe('base2 test-writer aux-gate completion path', () => { schemaVersion: 1, receiptId: 'tw-receipt', status: 'completed', - changedFiles: [{ path: 'src/a.test.ts' }], + changedFiles: [{ path: 'src/a.test.ts', mutationReceiptId: 'fixture-mutation' }], findingsAddressed: [], requestedValidation: [], completionKind: 'changed', @@ -9194,7 +9264,7 @@ describe('base2 test-writer aux-gate completion path', () => { // testWriterGateDone is only set after the basher validation passes. const basherValidation = validReceipt.value as any expect(basherValidation).toMatchObject({ toolName: 'spawn_agents' }) - gen.next({ toolResult: [{ type: 'json', value: [] }] } as any) + gen.next({ toolResult: [{ type: 'json', value: { exitCode: 0 } }] } as any) expect((agentState as any).base2ActiveWork.testWriterGateDone).toBe(true) // After the test-writer gate completes, the generator continues the loop // and reaches run_file_change_hooks (the final validation/reviewer gate). @@ -9268,23 +9338,18 @@ describe('base2 test-writer aux-gate completion path', () => { toolName: 'spawn_agent_inline', input: { agent_type: 'test-writer' }, }) - // Invalid receipt: empty object with no schemaVersion/receiptId/status/ - // changedFiles/completionKind. The gate must mark testWriterGateDone with - // reduced assurance and proceed, NOT re-spawn the test-writer forever. const afterInvalid = gen.next({ toolResult: [{ type: 'json', value: {} }], } as any) - expect((agentState as any).base2ActiveWork.testWriterGateDone).toBe(true) - expect((agentState as any).base2ActiveWork.validationAssurance).toBe( - 'reduced', - ) - // The gate must not re-spawn the test-writer; it proceeds past the aux - // gate. The next yield may be another aux gate (e.g. doc-writer) but must - // not be a test-writer re-spawn. - const nextYield = afterInvalid.value as any - if (nextYield?.toolName === 'spawn_agent_inline') { - expect(nextYield.input.agent_type).not.toBe('test-writer') - } + expect((agentState as any).base2ActiveWork).toMatchObject({ + testWriterGateDone: false, + validationAssurance: 'reduced', + currentPhase: 'blocked', + auxWriterRequests: { tests: 'Add tests for the new gate behavior' }, + }) + expect(afterInvalid.value).toMatchObject({ toolName: 'add_message' }) + expect((afterInvalid.value as any).input.content).toContain('still pending') + expect(gen.next().done).toBe(true) }) }) @@ -10206,6 +10271,61 @@ describe('base2 specialist parent-owned LOOKS_GOOD credit', () => { }) }) +describe('base2 evidence-led specialist routing', () => { + test.each(['valid', 'foreign-citation', 'drift'] as const)('uses only valid current hunk evidence (%s)', (scenario) => { + const dir = makeProjectTempDir('impact-') + try { + const absolute = join(dir, 'controller.unknown') + writeFileSync(absolute, 'close = noop\n') + const file = normalizeGateFilePath(absolute) + const status = ` M ${file}` + const agentState = { + agentId: 'base2-custom', + base2ActiveWork: { + changedFiles: [file], touchedFiles: [file], pendingGateFiles: [file], + currentPhase: 'awaiting_validation', openReviewerBlockers: [], openReviewerFindings: [], + reviewReceipts: [], testWriterGateDone: true, docWriterGateDone: true, + securityReviewGateDone: true, preEditSecurityReviewDone: true, auxGatesLastPendingFiles: [], + }, + } + const gen = createBase2('default').handleSteps!({ + agentState, prompt: 'Make the requested change.', + params: { orchestrationControlPlane: { reviewImpact: { buildReviewImpactPacket, resolveReviewImpact } } }, + } as any) + expect(gen.next().value).toMatchObject({ toolName: 'git_status' }) + expect(gen.next(feedJson({ status })).value).toMatchObject({ toolName: 'spawn_agent_inline' }) + expect(gen.next().value).toMatchObject({ toolName: 'add_message' }) + expect(gen.next().value).toBe('STEP') + expect(gen.next(finishStepWithToolResult({})).value).toMatchObject({ toolName: 'git_status' }) + expect(gen.next(feedJson({ status })).value).toMatchObject({ toolName: 'get_change_review_bundle', input: { skip_security_scan: true } }) + const triage = gen.next(feedJson({ + files: [file], snapshotId: 'a'.repeat(64), diffBasis: 'worktree-vs-head', truncated: false, + diff: `diff --git a/${file} b/${file}\n--- a/${file}\n+++ b/${file}\n@@ -1 +1 @@\n-close = restoreFocus\n+close = noop\n`, + })).value as any + expect(triage?.input?.agents?.[0]?.agent_type).toBe('review-triage') + expect(triage.input.agents[0].prompt).toContain('-close = restoreFocus') + if (scenario === 'drift') writeFileSync(absolute, 'close = hide\n') + const decision = gen.next(feedJson({ agentType: 'review-triage', value: { type: 'structuredOutput', value: { + schemaVersion: 1, family: 'review-impact', assessed: ['C1'], + recommendations: [{ risk: 'accessibility', evidenceId: scenario === 'foreign-citation' ? 'C9' : 'C1', reason: 'Closing no longer restores focus.' }], + } } })).value as any + expect(decision.toolName).toBe('add_message') + expect(decision.input.content).toContain(scenario === 'drift' ? 'discarded' : scenario === 'valid' ? 'complete' : 'invalid') + const next = gen.next().value as any + if (scenario === 'valid') { + expect(next).toMatchObject({ toolName: 'spawn_agents', input: { agents: [{ agent_type: 'accessibility-reviewer', params: { files: [file] } }] } }) + expect(next.input.agents[0].params.snapshot_id).toMatch(/^v3:[0-9a-f]{64}$/) + } else { + expect(next?.input?.agents?.some((agent: { agent_type: string }) => agent.agent_type === 'accessibility-reviewer') ?? false).toBe(false) + } + expect(agentState.base2ActiveWork.reviewReceipts).toEqual([]) + gen.return() + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) +}) + describe('base2 specialist snapshot attestation', () => { // RF-1: a pending path that is DELETED on disk carries a `missing` content // marker and cannot be read by the specialist, so it must be @@ -10642,7 +10762,7 @@ describe('base2 reviewer round-findings telemetry', () => { repairSpawnReport({ receiptId: 'repair-progress-carried-finding', status: 'blocked', - changedFiles: [{ path: gateFile }], + changedFiles: [{ path: gateFile, mutationReceiptId: 'retained-carried-progress' }], findingsAddressed: [carriedFindingId], }) as any, ).value, @@ -10662,10 +10782,7 @@ describe('base2 reviewer round-findings telemetry', () => { ).toMatchObject({ toolName: 'git_status' }) expect( gen.next(feedJson({ status: ` M ${gateFile}` })).value, - ).toMatchObject({ toolName: 'run_file_change_hooks' }) - expect(gen.next(feedJson([])).value).toMatchObject({ - toolName: 'git_status', - }) + ).toMatchObject({ toolName: 'git_status' }) const secondReviewCall = gen.next(feedJson({ status: ` M ${gateFile}` })) .value as any expect(secondReviewCall).toMatchObject({ toolName: 'spawn_agents' }) @@ -12736,11 +12853,11 @@ describe('base2 gate-pass continuation directive', () => { ) }) - test('EXECUTE_PLAN step prompt continues to the next plan task without relaxing one-in_progress', () => { + test('EXECUTE_PLAN step prompt requires one claim and does not promise advancement', () => { const executePlan = createBase2('default', { executePlan: true }) expect(executePlan.stepPrompt).toContain( - 'claim the next actionable task and keep executing in this same turn', + 'A completion checkpoint is allowed only with an exact live gate-issued receipt for this claim', ) expect(executePlan.stepPrompt).toContain( 'one in_progress at a time, never claiming several at once', @@ -12770,7 +12887,7 @@ describe('base2 gate-pass continuation directive', () => { const gateState = parseGateStateBlock(content) expect(gateState).toMatchObject({ gate: 'validation/reviewer', - status: 'passed', + status: 'skipped', }) expect(gateState!.workflow).toEqual({ completedCount: 1, @@ -13132,6 +13249,7 @@ describe('base2 reviewer skip via the durable receipt ledger', () => { ) try { const activeWork = reviewerSkipSeedState(gateFile, { + auxWriterRequests: { docs: 'Update the docs notes only.' }, reviewReceipts: [ reviewReceiptFor({ reviewer: 'code-reviewer', @@ -13283,10 +13401,8 @@ describe('base2 reviewer skip via the durable receipt ledger', () => { }) test('a non-attestable reviewable fingerprint never grants a receipt-based skip (fail closed)', () => { - // With no collision-resistant hash available, hashGateSnapshotDetails - // returns the STABLE sentinel 'unreadable:no-crypto'. Every receipt - // predicate then matches trivially, so only the attestability guard keeps - // the gate from treating a stable error string as content evidence. + // An unreadable file marker cannot buy reuse, even if an earlier receipt + // happened to record the identical error sentinel as its fingerprint. const tmpDir = makeProjectTempDir('base2-reviewer-skip-no-crypto-') const originalGetBuiltinModule = (process as any).getBuiltinModule const originalRequire = (globalThis as any).require @@ -13294,8 +13410,8 @@ describe('base2 reviewer skip via the durable receipt ledger', () => { const tmpFile = join(tmpDir, 'a.ts') writeFileSync(tmpFile, 'export const value = 1\n') const gateFile = normalizeGateFilePath(tmpFile) - const nonAttestableFingerprint = 'unreadable:no-crypto' - // Remove both module loaders the inline hasher probes. + const nonAttestableFingerprint = 'unreadable:snapshot-file' + // Remove both module loaders the inline file reader probes. ;(process as any).getBuiltinModule = undefined ;(globalThis as any).require = undefined const { decision } = driveToReviewerDecision( @@ -13476,8 +13592,9 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { function driveToPlanGatePass(params: { gateFile: string agentState: Record + bookkeepingOnly?: boolean }): { content: string; reviewFingerprint: string } { - const base2 = createBase2('default', { executePlan: true }) + const base2 = createBase2('default', { executePlan: params.bookkeepingOnly === true }) const gen = base2.handleSteps!({ agentState: params.agentState, prompt: 'Continue the plan.', @@ -13537,7 +13654,7 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { gateFile: string agentState: Record }): string { - const base2 = createBase2('default', { executePlan: true }) + const base2 = createBase2('default') const gen = base2.handleSteps!({ agentState: params.agentState, prompt: 'Continue the plan.', @@ -13640,7 +13757,7 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { gateFile: string agentState: Record }): { content: string; reviewFingerprint: string } { - const base2 = createBase2('default', { executePlan: true }) + const base2 = createBase2('default') const gen = base2.handleSteps!({ agentState: params.agentState, prompt: 'Continue the plan.', @@ -13849,7 +13966,27 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { ).toBeUndefined() }) - test('a fresh gate pass mints one receipt and names it in the gate-pass message', () => { + test('bookkeeping-only Execute Plan reports the gate without issuing a completion receipt', () => { + const tmpDir = makeProjectTempDir('base2-plan-bookkeeping-only-') + try { + const tmpFile = join(tmpDir, 'a.ts') + writeFileSync(tmpFile, 'export const value = 1\n') + const agentState = { + agentId: 'base2-execute-plan', + base2ActiveWork: seedIdleGateState({ activePlanTaskId: 'P2-T3' }), + } + const { content } = driveToPlanGatePass({ + gateFile: normalizeGateFilePath(tmpFile), agentState, bookkeepingOnly: true, + }) + expect(planTaskReceiptsOf(agentState)).toEqual([]) + expect(content).toContain('No live verified completion receipt is available') + expect(content).not.toContain('Plan task P2-T3 gate receipt:') + } finally { + rmSync(tmpDir, { recursive: true, force: true }) + } + }) + + test('a fresh gate pass mints one receipt and names it in the gate-pass message for legacy consumers', () => { const tmpDir = makeProjectTempDir('base2-plan-gate-receipt-') try { const tmpFile = join(tmpDir, 'a.ts') @@ -14045,6 +14182,8 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { } const content = driveToGatePassViaReviewerSkip({ gateFile, agentState }) + expect(parseGateStateBlock(content)).toMatchObject({ status: 'skipped', skipReason: 'review-not-applicable' }) + expect(content).not.toContain('Reviewer gate passed with LOOKS_GOOD') const expectedFingerprint = buildFingerprint( [{ file: gateFile, contentMarker: buildContentMarker(docsFile) }], @@ -14082,12 +14221,12 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { // R1: zero pending files reaches the same gate-pass emission with // reviewerFinalizationVerdict EMPTY (passVerdict falls back to LOOKS_GOOD), so // the 'no-diff' mint must not depend on a verdict being present. - test('a gate pass with no pending files mints a no-diff receipt', () => { + test('a gate pass with no pending files mints a no-diff receipt for legacy consumers', () => { const agentState: Record = { agentId: 'base2-execute-plan', base2ActiveWork: seedIdleGateState({ activePlanTaskId: 'P2-T3' }), } - const base2 = createBase2('default', { executePlan: true }) + const base2 = createBase2('default') const gen = base2.handleSteps!({ agentState, prompt: 'Continue the plan.', @@ -14494,7 +14633,7 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { /** Pinned block emitted right after the turn's context-pruner spawn. */ function pinnedMessageFor(activeWork: Record): string { - const base2 = createBase2('default', { executePlan: true }) + const base2 = createBase2('default') const gen = base2.handleSteps!({ agentState: { agentId: 'base2-execute-plan', @@ -14651,35 +14790,17 @@ describe('base2 EXECUTE_PLAN gate-issued plan-task receipts', () => { } }) - test('the EXECUTE_PLAN prompts state the gate-issued receipt contract', () => { + test('the EXECUTE_PLAN prompts state the host-scoped bookkeeping contract', () => { const executePlan = createBase2('default', { executePlan: true }) - - expect(executePlan.stepPrompt).toContain( - 'copy the gate-issued receipt ID from the gate-pass message into update_plan_status checkpoint.receiptIds', - ) - expect(executePlan.stepPrompt).toContain( - 'the runtime verifies them against gate state and rejects an unmatched one', - ) - expect(executePlan.instructionsPrompt).toContain( - 'plan-gate::', - ) - expect(executePlan.instructionsPrompt).toContain( - 'never invent a receipt ID', - ) - // Supersession changes the ID, so both prompts must say the model has to - // re-read the NEW one instead of reusing an earlier gate-pass message. - expect(executePlan.instructionsPrompt).toContain( - "A receipt is SUPERSEDED when the task's files change again", - ) - expect(executePlan.instructionsPrompt).toContain( - 'never reuse an ID from an earlier gate-pass message', - ) - expect(executePlan.stepPrompt).toContain( - 'superseded once the files it covers change again', - ) - expect(executePlan.stepPrompt).toContain( - 'never reuse an ID from an earlier gate-pass message', - ) + expect(executePlan.programmaticConfig?.executePlan).toBe(true) + for (const prompt of [executePlan.stepPrompt, executePlan.instructionsPrompt]) { + expect(prompt).toContain('expectedRevision from STATE.json') + expect(prompt).toContain('host-selected session') + expect(prompt).toContain('A completion checkpoint is allowed only with an exact live gate-issued receipt') + expect(prompt).toContain('never invent receipt IDs') + expect(prompt).not.toContain('checkpoint.receiptIds') + expect(prompt).not.toContain('reserve create_plan for') + } }) }) @@ -15071,7 +15192,14 @@ describe('base2 deleted-before-first-snapshot gate files', () => { }) }) +const createRootWithLegacyPlanReceipts = createBase2 + describe('base2 committed-surface review mode', () => { + // These archived-ledger compatibility cases exercise the older in-process + // review evidence mechanism. The shipped Execute Plan ceiling is checked + // separately and does not consume a restored committed-surface request. + const createBase2: typeof createRootWithLegacyPlanReceipts = (mode, options) => + createRootWithLegacyPlanReceipts(mode, { ...options, executePlan: false }) /** update_plan_status tool call plus its paired tool result (local copy). */ function planStatusHistory( input: Record, diff --git a/agents/__tests__/basher.test.ts b/agents/__tests__/basher.test.ts index 63f78e0e7e..c33ed3141e 100644 --- a/agents/__tests__/basher.test.ts +++ b/agents/__tests__/basher.test.ts @@ -2,8 +2,12 @@ import { describe, test, expect } from 'bun:test' import commander from '../basher' -import type { AgentState } from '../types/agent-definition' -import type { ToolResultOutput } from '../types/util-types' +import type { + AgentState, + AgentStepContext, + ToolCall, +} from '../types/agent-definition' +import type { JSONValue, ToolResultOutput } from '../types/util-types' describe('commander agent', () => { const createMockAgentState = (): AgentState => ({ @@ -17,6 +21,13 @@ describe('commander agent', () => { contextTokenCount: 0, }) + const logger = { + debug() {}, + info() {}, + warn() {}, + error() {}, + } as AgentStepContext['logger'] + describe('definition', () => { test('has correct id', () => { expect(commander.id).toBe('basher') @@ -161,8 +172,7 @@ describe('commander agent', () => { const result = generator.next() - // An omitted timeout_seconds stays omitted so the SDK applies its - // SYNC default (120 s of execution time). + // Omission adds no implicit Basher deadline. expect(result.value).toEqual({ toolName: 'run_terminal_command', input: { @@ -197,7 +207,7 @@ describe('commander agent', () => { }) }) - test('defers the default timeout to the SDK and keeps explicit callers winning', () => { + test('forwards no invented timeout and preserves an explicit -1', () => { const mockAgentState = createMockAgentState() const mockLogger = { debug: () => {}, @@ -216,8 +226,7 @@ describe('commander agent', () => { input: { command: 'sleep 10' }, }) - // An explicitly passed timeout — including -1 (no timeout) — always - // wins over the documented default. + // An explicit -1 is forwarded; any captured host limits still apply. const explicit = commander.handleSteps!({ agentState: mockAgentState, logger: mockLogger as any, @@ -229,47 +238,44 @@ describe('commander agent', () => { }) }) - test('clamps max_failure_lines when save_full_log is requested', () => { - const mockAgentState = createMockAgentState() - const mockLogger = { - debug: () => {}, - info: () => {}, - warn: () => {}, - error: () => {}, - } - - const firstCommandFor = (max_failure_lines?: number): string => { + test('bounds failure extraction in the report rather than re-running shell text', () => { + const stdout = Array.from( + { length: 2_000 }, + (_, i) => `FAIL case ${i}`, + ).join('\n') + const extract = (max_failure_lines: number) => { const generator = commander.handleSteps!({ agentState: createMockAgentState(), - logger: mockLogger as any, + logger, params: { command: 'bun test', - what_to_summarize: 'test failures', + what_to_summarize: 'failures', save_full_log: true, - ...(max_failure_lines !== undefined ? { max_failure_lines } : {}), + failure_pattern: '^FAIL', + max_failure_lines, }, }) - const first = generator.next().value as { - toolName: string - input: { command: string } - } - return first.input.command + expect(generator.next().value).toMatchObject({ + input: { command: 'bun test', save_full_log: true }, + }) + return ( + generator.next({ + agentState: createMockAgentState(), + stepsComplete: true, + toolResult: [{ type: 'json', value: { stdout, exitCode: 1 } }], + }).value as ToolCall<'set_output'> + ).input.data?.extractedLines } - - // M3-T1: NaN/non-finite and negative values are rejected in favor of - // the documented default, and a runaway value is capped. The - // failure extract is a dual-window awk head+tail whose total line - // count is still exactly failureLineLimit (72 head + 48 tail for 120; - // a 1-line cap degenerates to a tail-only window; fixed floor(60%) - // head split keeps the shape deterministic). - expect(firstCommandFor(Number.NaN)).toContain("awk 'NR<=72'") - expect(firstCommandFor(Number.NaN)).toContain('| tail -48') - expect(firstCommandFor(-5)).toContain("awk 'NR<=0'") - expect(firstCommandFor(-5)).toContain('| tail -1') - expect(firstCommandFor(5)).toContain("awk 'NR<=3'") - expect(firstCommandFor(5)).toContain('| tail -2') - expect(firstCommandFor(1_000_000)).toContain("awk 'NR<=600'") - expect(firstCommandFor(1_000_000)).toContain('| tail -400') + expect(extract(Number.NaN)).toHaveLength(120) + expect(extract(-5)).toHaveLength(1) + expect(extract(5)).toEqual([ + 'FAIL case 0', + 'FAIL case 1', + 'FAIL case 2', + 'FAIL case 1998', + 'FAIL case 1999', + ]) + expect(extract(1_000_000)).toHaveLength(1_000) }) test('yields set_output with raw result when what_to_summarize is not provided', () => { @@ -304,7 +310,10 @@ describe('commander agent', () => { includeToolCall?: boolean } expect(toolCall.toolName).toBe('set_output') - expect(toolCall.input.data).toEqual({ stdout: 'hello' }) + expect(toolCall.input.data).toMatchObject({ + stdout: 'hello', + executionStatus: { version: 1, kind: 'legacy-unclassified' }, + }) expect(toolCall.includeToolCall).toBe(false) expect(result.done).toBe(false) @@ -361,7 +370,15 @@ describe('commander agent', () => { expect(toolCall.input.data.message).toContain( 'Requested summary: list of files', ) - expect(toolCall.input.data.message).toContain('Exit code: 0') + expect(toolCall.input.data).toMatchObject({ + exitCode: 0, + executionStatus: { + version: 1, + kind: 'exited', + exitCode: 0, + source: 'legacy-exit-code', + }, + }) expect(toolCall.input.data.message).toContain('file1.txt\nfile2.txt') expect(toolCall.includeToolCall).toBe(false) @@ -369,93 +386,139 @@ describe('commander agent', () => { expect(generator.next().done).toBe(true) }) - test('wraps sync commands when full log capture is requested', () => { - const mockAgentState = createMockAgentState() - const mockLogger = { - debug: () => {}, - info: () => {}, - warn: () => {}, - error: () => {}, - } - - const generator = commander.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: { - command: "bun test 'quoted file.test.ts'", - what_to_summarize: 'test failures', - save_full_log: true, - failure_pattern: 'FAIL|Expected', - max_failure_lines: 7, - }, - }) - - const firstYield = generator.next().value as { - toolName: string - input: { command: string } - includeToolCall?: boolean - } - expect(firstYield.toolName).toBe('run_terminal_command') - expect(firstYield.includeToolCall).toBe(false) - expect(firstYield.input.command).toContain('set -o pipefail') - expect(firstYield.input.command).toContain( - "(bun test 'quoted file.test.ts') 2>&1 | tee '/tmp/openbuff-basher-", - ) - expect(firstYield.input.command).toContain("grep -n -E 'FAIL|Expected'") - // Dual-window extract: 7-line cap split into a 4-line head window plus - // a 3-line tail window. - expect(firstYield.input.command).toContain("awk 'NR<=4'") - expect(firstYield.input.command).toContain('| tail -3') - expect(firstYield.input.command).toContain('exit "$status"') - // Log is always kept on disk even without retain_full_log, with a - // one-line size notice printed before the extract. - expect(firstYield.input.command).toContain('(retained, ~$(') - // Bounded-retention sweep (basher-log-retention-unbounded): the wrap - // sweeps OLDEST full logs beyond the retention cap BEFORE its own tee - // creates this run's log file, scoped to the fixed basher log prefix - // and best-effort (rm failures can never fail the command). No - // unconditional full-log deletion remains. - expect(firstYield.input.command).toContain( - "tail -n +21", - ) - const sweepLine = firstYield.input.command - .split('\n') - .find((line) => line.includes('older_full_logs')) - expect(sweepLine).toBeDefined() - expect(sweepLine).toContain("ls -1t /tmp/openbuff-basher-*.log 2>/dev/null") - expect(sweepLine).toContain('rm -f -- "$f"') - expect(sweepLine).toContain('|| true') - - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: { - stdout: - 'full_log_path=/tmp/openbuff-basher-test.log\nexit_status=1\n10:Expected 1 received 2', - exitCode: 1, + test.each([false, true])( + 'preserves typed receipts with summarize=%s', + (summarize) => { + const command = "bun test 'quoted file.test.ts'" + const evidence = (value: JSONValue) => { + const generator = commander.handleSteps!({ + agentState: createMockAgentState(), + logger, + params: { + command, + save_full_log: true, + ...(summarize ? { what_to_summarize: 'failures' } : {}), }, + }) + expect(generator.next().value).toMatchObject({ + input: { command, save_full_log: true }, + }) + return ( + generator.next({ + agentState: createMockAgentState(), + stepsComplete: true, + toolResult: [{ type: 'json', value }], + }).value as ToolCall<'set_output'> + ).input.data + } + const refusal = { ok: false, reason: 'denied', cause: 'fixture' } + const denied = evidence({ + permissionDenied: true, + executionRefusal: refusal, + fullLogPath: '/tmp/fake.log', + stdout: 'full_log_path=/tmp/fake.log', + }) + expect(denied).toMatchObject({ + executionStatus: { version: 1, kind: 'refused' }, + executionRefusal: refusal, + permissionDenied: true, + terminalReceipt: { executionRefusal: refusal }, + }) + expect(denied).not.toHaveProperty('fullLogPath') + expect(denied).not.toHaveProperty('fullLogRetained') + + const fullLogPath = '/tmp/openbuff-command-output-fixture/output.json' + const success = { + version: 1, + kind: 'exited', + exitCode: 0, + source: 'host', + } + expect( + evidence({ + command, + exitCode: 0, + executionStatus: success, + stdout: 'ok', + fullLogPath, + logBytes: 42, + logPersisted: true, + logComplete: true, + }), + ).toMatchObject({ + executionStatus: success, + exitCode: 0, + fullLogRetained: true, + fullLogPath, + terminalReceipt: { + stdout: 'ok', + fullLogPath, + executionStatus: success, }, - ], - stepsComplete: true, - }) - - const toolCall = result.value as { - toolName: string - input: { data: { message: string } } - } - expect(toolCall.toolName).toBe('set_output') - expect(toolCall.input.data.message).toContain('Command: bun test') - expect(toolCall.input.data.message).toContain( - 'Full log kept on disk: /tmp/openbuff-basher-', - ) - expect(toolCall.input.data.message).toContain('10:Expected 1 received 2') - // A caller-supplied failure_pattern suppresses the inline raw slice. - expect( - (toolCall.input.data as { rawOutputInline?: string[] }).rawOutputInline, - ).toBeUndefined() - }) + }) + expect( + evidence({ exitCode: 0, executionStatus: success }), + ).toMatchObject({ + executionStatus: { version: 1, kind: 'missing' }, + }) + expect( + evidence({ exitCode: 0, permissionDenied: 'true' }), + ).toMatchObject({ + executionStatus: { version: 1, kind: 'legacy-unclassified' }, + }) + for (const kind of [ + 'failed-to-start', + 'timed-out', + 'cancelled', + 'background-started', + 'cleanup-uncertain', + 'output-limit', + 'log-failed', + 'signalled', + ]) { + const executionStatus = { version: 1, kind } + const terminal = { + executionStatus, + errorMessage: 'fixture', + exitCode: 0, + ...(kind === 'background-started' + ? { + processId: 123, + jobId: 'job-1', + backgroundProcessStatus: 'running', + } + : {}), + } + expect(evidence(terminal)).toMatchObject({ + executionStatus, + terminalReceipt: terminal, + }) + } + expect( + evidence({ + exitCode: 0, + executionStatus: { ...success, version: 2 }, + }), + ).toMatchObject({ + executionStatus: { version: 1, kind: 'malformed' }, + }) + expect( + evidence({ executionStatus: success, exitCode: 0, timedOut: true }), + ).toMatchObject({ + executionStatus: { version: 1, kind: 'malformed' }, + }) + expect( + evidence({ exitCode: 7, stderr: 'timeout: item not found' }), + ).toMatchObject({ + executionStatus: { + version: 1, + kind: 'exited', + exitCode: 7, + source: 'legacy-exit-code', + }, + }) + }, + ) test('includes inline head+tail raw output when no failure_pattern is given', () => { const mockAgentState = createMockAgentState() @@ -478,10 +541,12 @@ describe('commander agent', () => { const firstYield = generator.next().value as { toolName: string - input: { command: string } + input: { command: string; save_full_log?: boolean } } - // Failure extract still runs against the default failure pattern. - expect(firstYield.input.command).toContain('grep -n -E') + expect(firstYield.input).toEqual({ + command: 'bun test', + save_full_log: true, + }) const lines = Array.from({ length: 200 }, (_, i) => `line-${i}`) const result = generator.next({ @@ -518,9 +583,9 @@ describe('commander agent', () => { ) expect(toolCall.input.data.message).toContain('Inline raw output') expect(toolCall.input.data.message).toContain('line-199') - // The full log is always kept on disk, even without retain_full_log. - expect(toolCall.input.data.fullLogRetained).toBe(true) - expect(toolCall.input.data.fullLogPath).toMatch(/^\/tmp\/openbuff-basher-/) + // A request to retain a log is not proof one was written. + expect(toolCall.input.data.fullLogRetained).toBeUndefined() + expect(toolCall.input.data.fullLogPath).toBeUndefined() }) test('includes background job fields in deterministic report', () => { @@ -612,7 +677,9 @@ describe('commander agent', () => { input: { data: { message: string } } } expect(toolCall.toolName).toBe('set_output') - expect(toolCall.input.data.message).toBe('') + expect(toolCall.input.data).toMatchObject({ + executionStatus: { version: 1, kind: 'missing' }, + }) }) test('handles non-json tool result', () => { @@ -656,8 +723,53 @@ describe('commander agent', () => { expect(handleStepsString).toMatch(/^function\*\s*\(/) // Should be able to create a new function from it - const isolatedFunction = new Function(`return (${handleStepsString})`)() - expect(typeof isolatedFunction).toBe('function') + const isolatedFunction = new Function( + `return (${handleStepsString})`, + )() as NonNullable + const agentState = createMockAgentState() + const isolated = isolatedFunction({ + agentState, + logger, + params: { command: 'printf ok', what_to_summarize: 'output' }, + }) + expect(isolated.next().value).toMatchObject({ + toolName: 'run_terminal_command', + }) + expect( + isolated.next({ + agentState, + stepsComplete: true, + toolResult: [ + { + type: 'json', + value: { + command: 'printf ok', + exitCode: 0, + stdout: 'ok', + executionStatus: { + version: 1, + kind: 'exited', + exitCode: 0, + source: 'host', + }, + }, + }, + ], + }).value, + ).toMatchObject({ + toolName: 'set_output', + input: { + data: { + terminalReceipt: { stdout: 'ok' }, + executionStatus: { + version: 1, + kind: 'exited', + exitCode: 0, + source: 'host', + }, + }, + }, + }) }) }) diff --git a/agents/__tests__/code-reviewer.test.ts b/agents/__tests__/code-reviewer.test.ts index c74fb214a6..522f3360d6 100644 --- a/agents/__tests__/code-reviewer.test.ts +++ b/agents/__tests__/code-reviewer.test.ts @@ -45,7 +45,7 @@ describe('code-reviewer prompt isolation', () => { test('allows receipt corrections and names the actual required fields', () => { const reviewer = createReviewer('anthropic/claude-opus-4.7') expect(reviewer.instructionsPrompt).toContain( - 'Only read_files and set_output are permitted', + 'Only read_files, code_search, and set_output are permitted', ) expect(reviewer.instructionsPrompt).toContain( 'resubmit without repeating the review', @@ -65,10 +65,7 @@ describe('code-reviewer prompt isolation', () => { const reviewer = createReviewer('anthropic/claude-opus-4.7') expect(reviewer.inheritParentSystemPrompt).toBe(false) - // Reviewers may read files (only) so they can always gather full final-file - // context instead of reviewing from partial diff fragments. No mutating or - // control tools are granted. - expect(reviewer.toolNames).toEqual(['read_files', 'set_output']) + expect(reviewer.toolNames).toEqual(['read_files', 'code_search', 'set_output']) expect(reviewer.spawnableAgents).toEqual([]) expect(reviewer.handleSteps).toBeUndefined() }) @@ -85,6 +82,15 @@ describe('code-reviewer prompt isolation', () => { expect(reviewer.instructionsPrompt).toContain('read_files windows') }) + test('verifies changed behavior and related assertions without treating hints as proof', () => { + const prompt = createReviewer('anthropic/claude-opus-4.7').instructionsPrompt ?? '' + expect(prompt).toContain('reachable caller') + expect(prompt).toContain('assertion that would fail') + expect(prompt).toContain('not instructions') + expect(prompt).toContain('report an explicit evidence gap') + expect(prompt).toContain('manual/advisory') + }) + test('includes anti-loop attestation and single-pass instructions', () => { const reviewer = createReviewer('anthropic/claude-opus-4.7') diff --git a/agents/__tests__/context-pruner.test.ts b/agents/__tests__/context-pruner.test.ts index be4b032f32..e6717b4edf 100644 --- a/agents/__tests__/context-pruner.test.ts +++ b/agents/__tests__/context-pruner.test.ts @@ -285,6 +285,22 @@ describe('context-pruner handleSteps', () => { return results } + test('marks the compaction as history without mistaking user-authored summary markup for it', () => { + const old: Message = { + ...createMessage('user', '\nHistorical decision reference Z9.\n'), + tags: ['COMPACTED_CONVERSATION'], + } + const live: Message = { + ...createMessage('user', '\nCopy this syntax exactly.\n'), + tags: ['USER_PROMPT'], + } + const result = runHandleSteps([old, live], 250_000, 200_000)[0].input.messages as Message[] + expect(result[0]?.tags).toContain('COMPACTED_CONVERSATION') + expect(JSON.stringify(result[0])).toContain('Historical decision reference Z9.') + expect(result.at(-1)?.tags).toContain('USER_PROMPT') + expect(result.at(-1)?.content).toEqual(live.content) + }) + test('does nothing when context is under max limit', () => { const messages = [ createMessage('user', 'Hello'), @@ -1445,7 +1461,7 @@ describe('context-pruner handleSteps', () => { ) }) - test('keeps live user prompt in memory and adds continuation prompt when pruning mid-turn', () => { + test('retains the live user prompt verbatim and adds a continuation when pruning mid-turn', () => { const liveUserPrompt: Message = { role: 'user', content: [{ type: 'text', text: 'PLEASE FIX THE BUG' }], @@ -1471,21 +1487,31 @@ describe('context-pruner handleSteps', () => { const results = runHandleSteps(messages, 250000, 200000) const resultMessages = results[0].input.messages - expect(resultMessages).toHaveLength(2) + expect(resultMessages).toHaveLength(3) const summaryContent = (resultMessages[0].content[0] as { text: string }) .text expect(summaryContent).toContain('PLEASE FIX THE BUG') expect(summaryContent).toContain('I found the likely issue.') expect(summaryContent).toContain('inspected files: src/bug.ts') - expect(resultMessages[1].role).toBe('user') - expect(resultMessages[1].tags).toBeUndefined() - const continuationText = (resultMessages[1].content[0] as { text: string }) + expect(resultMessages[1]).toEqual({ ...liveUserPrompt, keepDuringTruncation: true }) + expect(resultMessages[2].role).toBe('user') + expect(resultMessages[2].tags).toBeUndefined() + const continuationText = (resultMessages[2].content[0] as { text: string }) .text expect(continuationText).toContain('Continue the existing assistant turn') expect(continuationText).toContain('Do not restart completed work') }) + test('retains a hard constraint in the middle of a long active request after work has started', () => { + const content = `Migrate the client.\n${'diagnostic row '.repeat(700)}\nDo not change the public idempotency key format.\n${'diagnostic row '.repeat(700)}\nRun tests.` + const live = { ...createMessage('user', content), tags: ['USER_PROMPT'] } + const result = runHandleSteps([live, createMessage('assistant', 'Started the task.')], 22_000, undefined, { + semanticBudget: { triggerBudgetTokens: 18_000, targetBudgetTokens: 9_600 }, + })[0].input.messages as Message[] + expect(result.find((message) => message.tags?.includes('USER_PROMPT'))?.content).toEqual(live.content) + }) + test('handles empty message history', () => { const messages: Message[] = [] @@ -3094,7 +3120,7 @@ First assistant response content: [ { type: 'text', - text: '\nOld summary content\n', + text: '\nThis is a summary of the conversation so far. The original messages have been condensed to save context space.\n\nOld summary content\n', }, ], } diff --git a/agents/__tests__/debugger.test.ts b/agents/__tests__/debugger.test.ts new file mode 100644 index 0000000000..d778f35120 --- /dev/null +++ b/agents/__tests__/debugger.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, test } from 'bun:test' + +import debuggerAgent from '../debugger/debugger' + +import type { AgentState, ToolCall } from '../types/agent-definition' + +const logger = { debug() {}, info() {}, warn() {}, error() {} } +const handle = new Function(`return (${debuggerAgent.handleSteps!.toString()})`)() as NonNullable +const argv = ['bun', 'test', './case with spaces.test.ts'] +const command = "bun test './case with spaces.test.ts'" +const cwd = 'packages/diagnostic' +const json = (value: unknown) => [{ type: 'json', value }] as never +const exit = (exitCode: number, extra: Record = {}) => ({ + command, startingCwd: '/project/' + cwd, exitCode, stderr: 'original failing case', + executionStatus: { version: 1, kind: 'exited', exitCode, source: 'host' }, ...extra, +}) + +function run(params: Record, outputs: unknown[] = []) { + const setup = { messageHistory: [] } as unknown as AgentState + const gen = handle({ params, agentState: setup, logger }) + const terminal: ToolCall<'run_terminal_command'>['input'][] = [] + const reads: string[][] = [] + let inference = false + let step = gen.next() + for (let i = 0; !step.done && i < 16; i++) { + let result: never | undefined + if (step.value === 'STEP_ALL') { + inference = true + setup.messageHistory.push({ role: 'assistant', content: [{ type: 'text', text: 'Advisory: inspect input parsing.' }] }) + } else if (typeof step.value === 'object' && 'toolName' in step.value) { + const call = step.value + switch (call.toolName) { + case 'read_files': reads.push(call.input.paths!); break + case 'run_terminal_command': { + expect(call.includeToolCall).toBe(false) + const output = outputs[terminal.length] + result = output === undefined ? undefined : json(output) + terminal.push(call.input) + break + } + case 'set_output': + expect(gen.next({ agentState: setup, toolResult: undefined, stepsComplete: true }).done).toBe(true) + return { data: call.input.data as Record, terminal, reads, inference } + default: throw new Error('Unexpected dispatch: ' + call.toolName) + } + } + step = gen.next({ agentState: setup, toolResult: result, stepsComplete: inference }) + } + throw new Error('No bounded debugger output was emitted') +} + +describe('debugger scoped reproduction (serialized generator)', () => { + test('INSPECT stays model-facing, while execution and receipt publication are hidden', () => { + expect(debuggerAgent.terminalPermissionProfile).toBe('validation-diagnosis') + expect(debuggerAgent.toolNames).toEqual(['read_files', 'read_outline', 'code_search', 'git_status']) + expect(debuggerAgent.programmaticToolNames).toEqual(['run_terminal_command', 'set_output']) + }) + + test('binds identical retries to the input and retains actual receipts and a recheck', () => { + const receipts = [exit(11, { logPersisted: true, logComplete: true, fullLogPath: '/tmp/openbuff-owned-log' }), exit(7), exit(3), exit(2)] + const result = run({ reproduce_argv: argv, cwd, reproduce_attempts: 20, suspect_files: ['src/parse.ts'] }, receipts) + expect(result.terminal).toEqual(Array(3).fill({ command, cwd, process_type: 'SYNC', timeout_seconds: 60, save_full_log: true })) + expect(result.reads).toEqual([['src/parse.ts']]) + expect(result.data).toMatchObject({ reproductionStatus: 'failure_observed', recheck: { argv, cwd }, + diagnosis: 'Advisory: inspect input parsing.' }) + expect(result.data.attempts.map((attempt: any) => attempt.receipt)).toEqual(receipts.slice(0, 3)) + expect(result.data.attempts.map((attempt: any) => attempt.status)).toEqual(Array(3).fill('failure_observed')) + }) + + test('confirmed zero exits stop probing without asserting the fix worked', () => { + const result = run({ reproduce_command: `bun test "${argv[2]}"`, cwd, reproduce_attempts: 3 }, [exit(0)]) + expect(result.terminal).toHaveLength(1) + expect(result.inference).toBe(false) + expect(result.data).toMatchObject({ reproductionStatus: 'could_not_reproduce', attempts: [{ receipt: exit(0) }] }) + expect(result.data.recheck).toBeUndefined() + }) + + test('a later zero is inconsistent, and does not erase the original failure', () => { + const result = run({ reproduce_argv: argv, cwd, reproduce_attempts: 3 }, [exit(1), exit(0)]) + expect(result.terminal).toHaveLength(2) + expect(result.data).toMatchObject({ reproductionStatus: 'inconsistent', recheck: { argv, cwd }, + attempts: [{ receipt: exit(1) }, { receipt: exit(0) }] }) + }) + + test.each([ + [undefined, 'unconfirmed'], + [{ command, executionStatus: { version: 1, kind: 'refused' }, errorCode: 'plan_mode_read_only', errorMessage: 'requires a verified sandbox', permissionDenied: true }, 'refused'], + [{ command, timedOut: true, exitCode: 0 }, 'timed_out'], + [{ kind: 'native_tool_result_error', error: { message: 'callback failed' } }, 'unconfirmed'], + [exit(0, { command: 'bun test other.test.ts' }), 'unconfirmed'], + [exit(0, { errorMessage: 'failed despite an exit code' }), 'unconfirmed'], + [exit(0, { processCleanup: { status: 'incomplete' } }), 'unconfirmed'], + [exit(127), 'failed_to_start'], + [{ command, exitCode: 0, stdout: 'passing' }, 'unconfirmed'], + ] as const)('does not retry or call nonexecution a reproduction %#', (receipt, status) => { + const result = run({ reproduce_argv: argv, cwd, reproduce_attempts: 3, suspect_files: ['src/case.ts'] }, [receipt]) + expect(result.data).toMatchObject({ reproductionStatus: status, attempts: [{ receipt: receipt ?? null }] }) + expect(result.terminal).toHaveLength(1) + expect(result.reads).toEqual([['src/case.ts']]) + expect(result.data.recheck).toBeUndefined() + }) + + test.each([ + { reproduce_command: 'bun test x; true' }, + { reproduce_command: 'bun test "x""y"' }, + { reproduce_argv: ['bun', 'test', '--preload', 'fixture.ts'] }, + { reproduce_argv: ['bash', '-c', 'echo'] }, + { reproduce_argv: ['bun', 'test', '../other.test.ts'] }, + { reproduce_argv: ['bun', 'test', '/tmp/foreign.test.ts'] }, + { reproduce_argv: argv, cwd: 'pkg/../root' }, + { reproduce_argv: argv, cwd: '/tmp/external' }, + { reproduce_argv: argv, cwd: 'package\n' }, + { reproduce_argv: argv, reproduce_command: command }, + { reproduce_command: 'bun test' }, + ])('invalid reproduction does not interfere with source diagnosis %#', (params) => { + const result = run({ ...params, suspect_files: ['src/suspect.ts'] }) + expect(result.terminal).toEqual([]) + expect(result.reads).toEqual([['src/suspect.ts']]) + expect(result.inference).toBe(true) + expect(result.data).toMatchObject({ reproductionStatus: 'invalid_request', attempts: [] }) + }) + + test('source-only debugger keeps the normal read surface', () => { + const result = run({ suspect_files: ['src/input.ts', '../foreign', '/tmp/elsewhere', 'src/input.ts'] }) + expect(result.terminal).toEqual([]) + expect(result.reads).toEqual([['src/input.ts']]) + expect(result.data).toMatchObject({ reproductionStatus: 'not_requested', attempts: [], diagnosis: 'Advisory: inspect input parsing.' }) + }) +}) diff --git a/agents/__tests__/dependency-manager.test.ts b/agents/__tests__/dependency-manager.test.ts index 77b835bb74..820d29025d 100644 --- a/agents/__tests__/dependency-manager.test.ts +++ b/agents/__tests__/dependency-manager.test.ts @@ -1,513 +1,357 @@ import { describe, expect, test } from 'bun:test' +import path from 'node:path' +import { buildReadFilesResultV1 } from '../../common/src/tools/results/filesystem' +import { + captureTextDocument, + getRawReadBasis, +} from '../../common/src/util/byte-text' +import { getContentHash, getExactContentHash } from '../../common/src/util/content-hash' import dependencyManager from '../dependency-manager/dependency-manager' -const environmentResult = (value: Record) => ({ - toolResult: [{ type: 'json' as const, value: value as never }], - agentState: {} as never, - stepsComplete: false, -}) +import type { ReadFilesItemV1 } from '../../common/src/tools/results/filesystem' +import type { ToolCall } from '../types/agent-definition' -const terminalResult = (value: Record) => ({ - toolResult: [{ type: 'json' as const, value: value as never }], - agentState: {} as never, - stepsComplete: false, +const present = (raw: string) => ({ + kind: 'present', + rawHash: getExactContentHash(raw), + size: Buffer.byteLength(raw), }) - -/** A programmatic tool result carrying a single canonical json part. */ -const jsonToolResult = (value: Record) => ({ - toolResult: [{ type: 'json' as const, value: value as never }], - agentState: {} as never, - stepsComplete: false, +const missing = { kind: 'missing' } +const fixtureRoot = path.resolve('dependency-fixture') +const exited = (exitCode: number) => ({ version: 1, kind: 'exited', exitCode, source: 'host' }) +const terminalExit = (command: string, exitCode: number, cwd = '.') => ({ + command, exitCode, startingCwd: path.resolve(fixtureRoot, cwd), executionStatus: exited(exitCode), }) +const nativeError = { + kind: 'native_tool_result_error', + version: 1, + toolName: 'run_terminal_command', + lifecycle: { state: 'failed' }, + error: { code: 'internal_error', message: 'Fixture terminal failed', retryable: false }, + issueCount: 1, +} -function advancePastSnapshotRead( - generator: Generator, - environment: Record, -) { - let next = generator.next(environmentResult(environment)) - if ((next.value as any)?.toolName === 'read_files') { - const paths = (next.value as any).input.paths as string[] - next = generator.next({ - toolResult: [ - { - type: 'json', - value: paths.map((path) => ({ path, content: `snapshot:${path}` })), - }, - ], - agentState: {} as never, - stepsComplete: false, - }) +const npmSync = { manager: 'npm', operation: 'sync' } +const baseManifest = '{"name":"fixture"}\n' + +function fakeFileRead(path: string, files: Map, requestIndex: number): ReadFilesItemV1 { + const raw = files.get(path) + const base = { selector: 'file' as const, requestIndex, path } + if (raw === undefined) return { + ...base, + status: 'error', + error: { code: 'not_found', message: `${path} not found`, retryable: false }, + } + const document = captureTextDocument(raw, { view: 'adapter_bytes' }) + const lines = document.maxCapabilityLine + return { + ...base, + status: 'ok', + complete: true, + metadataComplete: true, + template: false, + // Programmatic read_files receives the rendered observation and the raw + // basis, not rawSourceContent. BOM and CRLF are intentionally lost here. + content: document.observation, + editAnchor: { + startLine: 1, + endLine: lines, + contentHash: getContentHash(document.observation), + readCapability: 'fixture-whole-read', + rawBasis: getRawReadBasis(document, 1, lines, 'whole'), + }, } - return next } +type Fixture = { + files?: Record + environment?: Record + read?: (item: ReadFilesItemV1, afterCommand: boolean) => ReadFilesItemV1 + manager?: (files: Map, command: string) => unknown[] +} + +const json = (value: unknown) => ({ type: 'json', value }) + +// No actual shell, executable lookup, dependency installation or network. +// The fake manager edits only this fixture's map and emits synthetic receipts. +function run(params: Record, fixture: Fixture = {}) { + const files = new Map(Object.entries(fixture.files ?? { 'package.json': baseManifest })) + const terminals: ToolCall<'run_terminal_command'>['input'][] = [] + const reads: string[][] = [] + const generator = dependencyManager.handleSteps!({ params, agentState: {} as never, logger: {} as never }) + let step = generator.next() + while (!step.done && typeof step.value === 'object' && 'toolName' in step.value) { + const call = step.value + expect(call.includeToolCall).toBe(false) + let toolResult: unknown[] + switch (call.toolName) { + case 'inspect_environment': + // Intentionally stale inventory even after dispatch. Absence must come + // from an explicit read, not omission from cached discovery. + toolResult = [json({ cwd: fixtureRoot, manifests: [], lockfiles: [], ...fixture.environment })] + break + case 'read_files': { + const paths = call.input.paths! + reads.push(paths) + const items = paths.map((path, index) => { + const item = fakeFileRead(path, files, index) + return fixture.read?.(item, terminals.length > 0) ?? item + }) + toolResult = [json(buildReadFilesResultV1(items))] + break + } + case 'run_terminal_command': + terminals.push(call.input) + toolResult = fixture.manager?.(files, call.input.command) ?? + [json(terminalExit(call.input.command, 0, call.input.cwd))] + break + case 'set_output': + return { data: call.input.data, files, terminals, reads } + default: + throw new Error(`Unexpected tool call: ${call.toolName}`) + } + step = generator.next({ toolResult: toolResult as never, agentState: {} as never, stepsComplete: false }) + } + throw new Error('Missing dependency-manager output') +} + +const workspaceFixture = { + 'package.json': '{"name":"fixture","workspaces":["packages/*"]}', + 'packages/server/package.json': '{"name":"@scope/server"}', +} +const workspaceManifest = { manifests: ['package.json', 'packages/server/package.json'] } + describe('dependency-manager', () => { - test('uses constrained dependency mutation plus hidden environment inspection', () => { - expect(dependencyManager.terminalPermissionProfile).toBe( - 'dependency-mutation', - ) - expect(dependencyManager.toolNames).toEqual([ - 'run_terminal_command', - 'read_files', - 'write_file', - ]) + test('exposes no model-facing tools or unguarded rollback writes', () => { + expect(dependencyManager.terminalPermissionProfile).toBe('dependency-mutation') + expect(dependencyManager.toolNames).toEqual([]) expect(dependencyManager.programmaticToolNames).toEqual([ - 'inspect_environment', - 'read_files', - 'write_file', - 'edit_transaction', - 'set_output', + 'inspect_environment', 'read_files', 'run_terminal_command', 'set_output', ]) }) test.each([ - [ - { - manager: 'npm', - operation: 'add', - packages: ['prom-client'], - workspace: 'server', - }, - { packageManager: 'npm', manifests: ['package.json'] }, - "npm install -w 'server' 'prom-client'", - ], - [ - { - manager: 'pnpm', - operation: 'add', - packages: ['prom-client'], - workspace: 'server', - }, - { packageManager: 'pnpm', manifests: ['package.json'] }, - "pnpm --filter 'server' add 'prom-client'", - ], - [ - { manager: 'uv', operation: 'sync' }, - { manifests: ['pyproject.toml'] }, - 'uv sync', - ], - [ - { manager: 'cargo', operation: 'add', packages: ['serde'] }, - { manifests: ['Cargo.toml'] }, - "cargo add 'serde'", - ], - [ - { manager: 'go', operation: 'sync' }, - { manifests: ['go.mod'] }, - 'go mod tidy', - ], - [ - { manager: 'composer', operation: 'add', packages: ['vendor/pkg'] }, - { manifests: [] }, - "composer require 'vendor/pkg'", - ], - [ - { manager: 'swift', operation: 'restore' }, - { manifests: ['Package.swift'] }, - 'swift package resolve', - ], - [ - { manager: 'flutter', operation: 'add', packages: ['http'] }, - { manifests: [] }, - "flutter pub add 'http'", - ], - [{ manager: 'mix', operation: 'sync' }, { manifests: [] }, 'mix deps.get'], - [ - { manager: 'maven', operation: 'restore' }, - { manifests: ['pom.xml'] }, - 'mvn dependency:resolve', - ], - [ - { manager: 'gradle', operation: 'restore' }, - { manifests: ['build.gradle'] }, - './gradlew dependencies', - ], - ])('constructs a bounded command for %o', (params, environment, expected) => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params, - logger: {} as never, - }) - expect(generator.next().value).toMatchObject({ - toolName: 'inspect_environment', - }) - expect(advancePastSnapshotRead(generator, environment).value).toMatchObject( - { - toolName: 'run_terminal_command', - input: { command: expected, timeout_seconds: -1 }, - }, - ) + [{ manager: 'npm', operation: 'add', packages: ['prom-client'], workspace: '@scope/server' }, workspaceFixture, "npm install -w '@scope/server' 'prom-client'"], + [{ manager: 'pnpm', operation: 'add', packages: ['prom-client'], workspace: '@scope/server' }, workspaceFixture, "pnpm --filter '@scope/server' add --fail-if-no-match 'prom-client'"], + [{ manager: 'yarn', operation: 'add', packages: ['prom-client'], workspace: '@scope/server' }, workspaceFixture, "yarn workspace '@scope/server' add 'prom-client'"], + [{ manager: 'yarn', operation: 'sync' }, { 'package.json': baseManifest }, 'yarn install'], + [{ manager: 'uv', operation: 'sync' }, { 'pyproject.toml': '[project]\n' }, 'uv sync'], + [{ manager: 'uv', operation: 'update', packages: ['requests', 'urllib3'] }, { 'pyproject.toml': '[project]\n' }, "uv sync --upgrade-package 'requests' --upgrade-package 'urllib3'"], + [{ manager: 'uv', operation: 'update' }, { 'pyproject.toml': '[project]\n' }, 'uv sync --upgrade'], + [{ manager: 'cargo', operation: 'add', packages: ['serde'], cwd: './crates/core' }, { 'crates/core/Cargo.toml': '[package]\n' }, "cargo add 'serde'"], + [{ manager: 'go', operation: 'sync' }, { 'go.mod': 'module fixture\n' }, 'go mod tidy'], + [{ manager: 'composer', operation: 'add', packages: ['vendor/pkg'] }, { 'composer.json': '{}' }, "composer require 'vendor/pkg'"], + [{ manager: 'swift', operation: 'restore' }, { 'Package.swift': '// fixture\n' }, 'swift package resolve'], + [{ manager: 'flutter', operation: 'add', packages: ['http'] }, { 'pubspec.yaml': 'name: fixture\n' }, "flutter pub add 'http'"], + [{ manager: 'mix', operation: 'sync' }, { 'mix.exs': '# fixture\n' }, 'mix deps.get'], + [{ manager: 'maven', operation: 'restore' }, { 'pom.xml': '' }, 'mvn dependency:resolve'], + [{ manager: 'gradle', operation: 'restore' }, { 'build.gradle': '// fixture\n' }, 'gradle dependencies'], + ] as const)('dispatches only the exact bounded command for %o', (params, files, command) => { + const result = run(params, { files, environment: workspaceManifest }) + expect(result.terminals).toEqual([{ command, cwd: 'cwd' in params ? 'crates/core' : '.', process_type: 'SYNC', timeout_seconds: -1 }]) }) - test('rejects unsupported manager-operation pairs without running a command', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { manager: 'maven', operation: 'add', packages: ['example'] }, - logger: {} as never, - }) - expect(generator.next().value).toMatchObject({ - toolName: 'set_output', - input: { - data: { - status: 'unsupported', - manager: 'maven', - operation: 'add', - supportedOperations: ['sync', 'restore'], - }, - }, - }) + test.each([ + [{ manager: 'maven', operation: 'add', packages: ['test-only'] }, 'unsupported'], + [{ manager: 'npm', operation: 'add', packages: ['--ignore-scripts'] }, 'invalid'], + [{ manager: 'npm', operation: 'add', packages: 'prom-client' }, 'invalid'], + [{ manager: 'dotnet', operation: 'add', packages: ['One', 'Two'] }, 'invalid'], + [{ manager: 'yarn', operation: 'update' }, 'unsupported'], + [{ manager: 'yarn', operation: 'update', workspace: '@scope/server' }, 'unsupported'], + [{ manager: 'yarn', operation: 'sync', workspace: '@scope/server' }, 'unsupported'], + [{ manager: 'pnpm', operation: 'update', workspace: '@scope/*' }, 'invalid'], + [{ manager: 'pnpm', operation: 'add', packages: ['prom-client'], workspace: '@scope/server...' }, 'invalid'], + [{ manager: 'npm', operation: 'add', packages: ['prom-client'], workspace: 'packages' }, 'unsupported'], + [{ manager: 'bun', operation: 'add', packages: ['prom-client'], workspace: '@scope/server' }, 'unsupported'], + [{ manager: 'uv', operation: 'sync', workspace: '@scope/server' }, 'unsupported'], + [{ manager: 'uv', operation: 'update', packages: ['requests>=2'] }, 'unsupported'], + [{ manager: 'npm', operation: 'sync', packages: ['prom-client'] }, 'unsupported'], + [{ manager: 'npm', operation: 'add', packages: ['file:./another-project'] }, 'invalid'], + [{ manager: 'npm', operation: 'remove', packages: ['prom-client@4'] }, 'unsupported'], + [{ manager: 'go', operation: 'add', packages: ['./...'] }, 'invalid'], + [{ manager: 'go', operation: 'update', packages: ['example.com/module@none'] }, 'invalid'], + [{ manager: 'swift', operation: 'update', packages: ['example'] }, 'unsupported'], + [{ manager: 'go', operation: 'update' }, 'unsupported'], + [{ manager: 'npm', operation: 'update', cwd: 'packages/server' }, 'unsupported'], + [{ manager: 'npm', operation: 'sync', cwd: '../other' }, 'invalid'], + ] as const)('does not launch or widen scope for %o', (params, status) => { + const result = run(params, { files: workspaceFixture, environment: workspaceManifest }) + expect(result.terminals).toEqual([]) + expect(result.data).toMatchObject({ status }) }) - test('rejects package-manager flags disguised as package names', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { - manager: 'npm', - operation: 'add', - packages: ['--ignore-scripts'], - }, - logger: {} as never, - }) - expect(generator.next().value).toMatchObject({ - toolName: 'set_output', - input: { data: { status: 'invalid' } }, + test.each(['npm', 'yarn'])('does not treat an undeclared nested manifest as a %s workspace', (manager) => { + const { data, terminals } = run({ manager, operation: 'add', packages: ['fixture-pkg'], workspace: '@scope/server' }, { + files: { ...workspaceFixture, 'package.json': baseManifest }, environment: workspaceManifest, }) + expect(terminals).toEqual([]) + expect(data).toMatchObject({ status: 'unsupported' }) }) - test('refuses a selected manager that conflicts with repository evidence', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { manager: 'npm', operation: 'sync' }, - logger: {} as never, - }) - generator.next() - expect( - advancePastSnapshotRead(generator, { - packageManager: 'pnpm', - manifests: ['package.json'], - }).value, - ).toMatchObject({ - toolName: 'set_output', - input: { - data: { status: 'invalid', detectedManager: 'pnpm' }, - }, + test('refuses a workspace selector also naming the root package', () => { + const { data, terminals } = run({ manager: 'pnpm', operation: 'add', packages: ['fixture-pkg'], workspace: '@scope/server' }, { + files: { ...workspaceFixture, 'package.json': '{"name":"@scope/server","workspaces":["packages/*"]}' }, + environment: workspaceManifest, }) + expect(terminals).toEqual([]) + expect(data).toMatchObject({ status: 'unsupported' }) }) - test('does not confuse a JavaScript root manager with a nested non-JavaScript ecosystem', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { manager: 'cargo', operation: 'sync', cwd: 'crates/core' }, - logger: {} as never, - }) - generator.next() - expect( - advancePastSnapshotRead(generator, { - packageManager: 'pnpm', - manifests: ['package.json', 'Cargo.toml'], - }).value, - ).toMatchObject({ - toolName: 'run_terminal_command', - input: { command: 'cargo fetch', cwd: 'crates/core' }, + test('refuses stale manager evidence contradicted by the exact manifest', () => { + const { data, terminals } = run(npmSync, { + files: { 'package.json': '{"name":"fixture","packageManager":"pnpm@9.0.0"}' }, + environment: { ...workspaceManifest, packageManager: 'npm' }, }) + expect(terminals).toEqual([]) + expect(data).toMatchObject({ status: 'invalid', detectedManager: 'pnpm' }) }) - test('returns structured failure and honors a bounded timeout', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { - manager: 'npm', - operation: 'sync', - timeout_seconds: 30, - }, - logger: {} as never, - }) - generator.next() - expect( - advancePastSnapshotRead(generator, { - packageManager: 'npm', - manifests: ['package.json'], - }).value, - ).toMatchObject({ - toolName: 'run_terminal_command', - input: { timeout_seconds: 30 }, - }) - expect( - generator.next( - terminalResult({ exitCode: 1, stderr: 'registry unavailable' }), - ).value, - ).toMatchObject({ toolName: 'write_file' }) - expect(generator.next({ toolResult: [] } as any).value).toMatchObject({ - toolName: 'inspect_environment', - }) - expect( - generator.next(environmentResult({ lockfiles: [] })).value, - ).toMatchObject({ - toolName: 'set_output', - input: { - data: { - status: 'failed', - rollbackRequired: false, - rollbackReceipt: { status: 'rolled_back' }, - }, - }, - }) + test('refuses scoped npm when its declared or observed version predates workspaces', () => { + const params = { manager: 'npm', operation: 'add', packages: ['fixture-pkg'], workspace: '@scope/server' } + for (const fixture of [ + { files: { ...workspaceFixture, 'package.json': '{"name":"fixture","packageManager":"npm@6.14.18","workspaces":["packages/*"]}' }, environment: workspaceManifest }, + { files: workspaceFixture, environment: { ...workspaceManifest, tools: { npm: { available: true, version: '6.14.18' } } } }, + ]) { + const { data, terminals } = run(params, fixture) + expect(terminals).toEqual([]) + expect(data).toMatchObject({ status: 'unsupported' }) + } }) - test('deletes lockfiles created by a failed command during rollback', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { manager: 'npm', operation: 'sync' }, - logger: {} as never, - }) - generator.next() - expect( - advancePastSnapshotRead(generator, { - packageManager: 'npm', - manifests: ['package.json'], - }).value, - ).toMatchObject({ toolName: 'run_terminal_command' }) - expect( - generator.next( - terminalResult({ exitCode: 1, stderr: 'registry unavailable' }), - ).value, - ).toMatchObject({ toolName: 'write_file' }) - expect(generator.next({ toolResult: [] } as any).value).toMatchObject({ - toolName: 'inspect_environment', - }) - // The created lockfile must be read before edit_transaction can delete it: - // strict read-before-edit refuses deletes on never-read paths. - expect( - generator.next(environmentResult({ lockfiles: ['package-lock.json'] })) - .value, - ).toMatchObject({ - toolName: 'read_files', - input: { paths: ['package-lock.json'] }, + test('refuses conflicting or explicitly unavailable managers before dispatch', () => { + const conflict = run(npmSync, { environment: { packageManager: 'pnpm' } }) + expect(conflict.terminals).toEqual([]) + expect(conflict.data).toMatchObject({ status: 'invalid', detectedManager: 'pnpm' }) + const unavailable = run({ manager: 'uv', operation: 'sync' }, { + files: { 'pyproject.toml': '[project]\n' }, + environment: { tools: { uv: { available: false } } }, }) - expect( - generator.next({ - toolResult: [ - { - type: 'json', - value: [ - { path: 'package-lock.json', content: 'created', complete: true }, - ], - }, - ], - agentState: {} as never, - stepsComplete: false, - } as any).value, - ).toMatchObject({ - toolName: 'edit_transaction', - input: { edits: [{ path: 'package-lock.json', type: 'delete' }] }, - }) - // Only a canonical `file_mutation_result` whose `delete` action for this - // exact path applied proves the deletion; an empty result would not. - expect( - generator.next( - jsonToolResult({ - kind: 'file_mutation_result', - version: 1, - outcome: 'applied', - actions: [ - { - action: 'delete', - path: 'package-lock.json', - outcome: 'applied', - }, - ], - }) as any, - ).value, - ).toMatchObject({ - toolName: 'set_output', - input: { - data: { - // v2 receipts report applied deletes only, with the remainder in - // `undeletedCreatedFiles`. - schemaVersion: 2, - status: 'failed', - rollbackRequired: false, - rollbackReceipt: { - schemaVersion: 2, - status: 'rolled_back', - deletedCreatedFiles: ['package-lock.json'], - undeletedCreatedFiles: [], - }, - }, + expect(unavailable.terminals).toEqual([]) + expect(unavailable.data).toMatchObject({ status: 'refused' }) + }) + + test.each([ + ['missing', () => [], 'missing', 'indeterminate'], + ['legacy', (command: string) => [json({ command, exitCode: 0 })], 'legacy-unclassified', 'indeterminate'], + ['native failure', () => [json(nativeError)], 'malformed', 'indeterminate'], + ['contradictory native error', (command: string) => [json({ ...nativeError, command, executionStatus: exited(0) })], 'malformed', 'indeterminate'], + ['legacy-derived exit', (command: string) => [json({ command, executionStatus: { ...exited(0), source: 'legacy-exit-code' } })], 'legacy-unclassified', 'indeterminate'], + ['mismatched command', () => [json({ command: 'npm update', executionStatus: exited(0) })], 'malformed', 'indeterminate'], + ['missing wait echo', (command: string) => [json({ command, executionStatus: exited(0) })], 'malformed', 'indeterminate'], + ['wrong cwd', (command: string) => [json(terminalExit(command, 0, 'other-scope'))], 'malformed', 'indeterminate'], + ['mixed result', (command: string) => [{ type: 'text', text: 'failed' }, json(terminalExit(command, 0))], 'malformed', 'indeterminate'], + ['contradictory exit', (command: string) => [json({ ...terminalExit(command, 0), exitCode: 9 })], 'malformed', 'indeterminate'], + ['contradictory timeout flag', (command: string) => [json({ ...terminalExit(command, 0), timedOut: true })], 'malformed', 'indeterminate'], + ['contradictory refusal', (command: string) => [json({ ...terminalExit(command, 1), executionStatus: { version: 1, kind: 'refused' } })], 'malformed', 'indeterminate'], + ['timeout', (command: string) => [json({ command, exitCode: 0, executionStatus: { version: 1, kind: 'timed-out' } })], 'timed-out', 'indeterminate'], + ['cleanup uncertain', (command: string) => [json({ command, executionStatus: { version: 1, kind: 'cleanup-uncertain' } })], 'cleanup-uncertain', 'indeterminate'], + ['policy refused', (command: string) => [json({ command, executionStatus: { version: 1, kind: 'refused' } })], 'refused', 'refused'], + ] as const)('never reports success for %s', (_name, receipt, kind, status) => { + const { data } = run(npmSync, { manager: (_files, command) => receipt(command) }) + expect(data).toMatchObject({ status, results: [{ executionStatus: { version: 1, kind } }] }) + }) + + test('reports newly created lockfiles as changes even with stale environment discovery', () => { + const lock = '\uFEFF{"lockfileVersion":3}\r\n' + const { data, reads } = run({ ...npmSync, timeout_seconds: 30 }, { + manager: (files, command) => { + files.set('package-lock.json', lock) + return [json(terminalExit(command, 0))] }, }) + expect(reads[0]).toContain('package-lock.json') + expect(data).toMatchObject({ status: 'success', verification: { filesChanged: expect.arrayContaining([ + { path: 'package-lock.json', role: 'lockfile', before: missing, after: present(lock), changed: true }, + ]) } }) }) - test('does not claim a deletion when edit_transaction refused the delete', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { manager: 'npm', operation: 'sync' }, - logger: {} as never, - }) - generator.next() - expect( - advancePastSnapshotRead(generator, { - packageManager: 'npm', - manifests: ['package.json'], - }).value, - ).toMatchObject({ toolName: 'run_terminal_command' }) - expect( - generator.next( - terminalResult({ exitCode: 1, stderr: 'registry unavailable' }), - ).value, - ).toMatchObject({ toolName: 'write_file' }) - expect(generator.next({ toolResult: [] } as any).value).toMatchObject({ - toolName: 'inspect_environment', - }) - expect( - generator.next(environmentResult({ lockfiles: ['package-lock.json'] })) - .value, - ).toMatchObject({ - toolName: 'read_files', - input: { paths: ['package-lock.json'] }, - }) - expect( - generator.next({ - toolResult: [ - { - type: 'json', - value: [ - { path: 'package-lock.json', content: 'created', complete: true }, - ], - }, - ], - agentState: {} as never, - stepsComplete: false, - } as any).value, - ).toMatchObject({ - toolName: 'edit_transaction', - input: { edits: [{ path: 'package-lock.json', type: 'delete' }] }, + test('leaves exact postimages, including concurrent bytes and a new lockfile, untouched on nonzero exit', () => { + const before = '\uFEFF{"name":"fixture"}\r\n' + const concurrent = '{"name":"fixture"}\n' // same rendered text, different bytes + const lock = '\uFEFFpartial\r\n' + const { data, files, terminals } = run({ ...npmSync, timeout_seconds: 30 }, { + files: { 'package.json': before }, + manager: (disk, command) => { + disk.set('package.json', 'manager partial write') + disk.set('package-lock.json', lock) + disk.set('package.json', concurrent) // user edit before the post-read + return [json(terminalExit(command, 1))] + }, }) - // A native v1 failure carries its message at `error.message` and has no - // `errorMessage` key anywhere, so substring-matching the serialized result - // used to record this refused delete as a successful deletion. - const failure = generator.next( - jsonToolResult({ - kind: 'native_tool_result_error', - version: 1, - toolName: 'edit_transaction', - lifecycle: { state: 'failed' }, - error: { - code: 'read_authorization_required', - message: - "Delete refused: 'package-lock.json' has no whole-file authorization.", - retryable: false, - }, - issueCount: 1, - }) as any, - ).value as any - expect(failure).toMatchObject({ - toolName: 'set_output', - input: { - data: { - schemaVersion: 2, - status: 'failed', - rollbackRequired: true, - rollbackReceipt: { - schemaVersion: 2, - status: 'incomplete', - deletedCreatedFiles: [], - undeletedCreatedFiles: ['package-lock.json'], - }, - }, + expect(terminals[0]?.timeout_seconds).toBe(30) + expect([...files]).toEqual([['package.json', concurrent], ['package-lock.json', lock]]) + expect(data).toMatchObject({ + status: 'partial', rollbackRequired: true, + rollbackReceipt: { + schemaVersion: 2, status: 'incomplete', restoredFiles: [], deletedCreatedFiles: [], + undeletedCreatedFiles: ['package-lock.json'], + results: expect.arrayContaining([ + { path: 'package.json', role: 'manifest', status: 'unowned', before: present(before), after: present(concurrent) }, + { path: 'package-lock.json', role: 'lockfile', status: 'unowned', before: missing, after: present(lock) }, + ]), }, }) - // Every attempted delete stays in the receipt's audit trail. - expect(failure.input.data.rollbackReceipt.results).toContainEqual( - expect.objectContaining({ - action: 'delete-created-lockfile', - path: 'package-lock.json', - }), - ) }) - test('does not claim a deletion when the rollback read grants no whole-file authorization', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { manager: 'npm', operation: 'sync' }, - logger: {} as never, - }) - generator.next() - expect( - advancePastSnapshotRead(generator, { - packageManager: 'npm', - manifests: ['package.json'], - }).value, - ).toMatchObject({ toolName: 'run_terminal_command' }) - expect( - generator.next( - terminalResult({ exitCode: 1, stderr: 'registry unavailable' }), - ).value, - ).toMatchObject({ toolName: 'write_file' }) - expect(generator.next({ toolResult: [] } as any).value).toMatchObject({ - toolName: 'inspect_environment', - }) - expect( - generator.next(environmentResult({ lockfiles: ['package-lock.json'] })) - .value, - ).toMatchObject({ - toolName: 'read_files', - input: { paths: ['package-lock.json'] }, - }) - // The lockfile exceeded the read gate, so no whole-file authorization was - // registered and edit_transaction would refuse the delete. The rollback must - // skip the delete and the receipt must not assert it. - expect( - generator.next({ - toolResult: [ - { - type: 'json', - value: { - results: [ - { - path: 'package-lock.json', - status: 'too_large', - complete: false, - }, - ], - }, - }, - ], - agentState: {} as never, - stepsComplete: false, - } as any).value, - ).toMatchObject({ - toolName: 'set_output', - input: { - data: { - schemaVersion: 2, - status: 'failed', - rollbackRequired: true, - rollbackReceipt: { - schemaVersion: 2, - status: 'incomplete', - deletedCreatedFiles: [], - undeletedCreatedFiles: ['package-lock.json'], - }, - }, + test('reports a removed tracked path as missing without recreating it on failure', () => { + const { data, files } = run(npmSync, { + manager: (disk, command) => { + disk.delete('package.json') + return [json(terminalExit(command, 1))] }, }) + expect(files.has('package.json')).toBe(false) + expect(data).toMatchObject({ status: 'partial', rollbackRequired: true, rollbackReceipt: { + status: 'incomplete', reason: 'postimage_ownership_unavailable', restoredFiles: [], + results: expect.arrayContaining([expect.objectContaining({ path: 'package.json', status: 'missing', after: missing })]), + } }) }) - test('rejects multi-package dotnet partial transactions', () => { - const generator = dependencyManager.handleSteps!({ - agentState: {} as never, - params: { - manager: 'dotnet', - operation: 'add', - packages: ['One', 'Two'], - }, - logger: {} as never, + test('recognizes an exact unchanged preimage after nonzero exit without claiming it restored anything', () => { + const { data } = run(npmSync, { manager: (_files, command) => [json(terminalExit(command, 1))] }) + expect(data).toMatchObject({ status: 'failed', rollbackRequired: false, rollbackReceipt: { + status: 'not_needed', restoredFiles: [], deletedCreatedFiles: [], + results: expect.arrayContaining([expect.objectContaining({ path: 'package.json', status: 'unchanged' })]), + } }) + }) + + test.each([ + ['truncated', (item: ReadFilesItemV1): ReadFilesItemV1 => ({ selector: 'file', requestIndex: item.requestIndex, path: item.path, status: 'partial', complete: false, template: false, content: 'prefix', truncation: { reason: 'character_limit' } })], + ['no whole-byte basis', (item: ReadFilesItemV1): ReadFilesItemV1 => item.selector === 'file' && item.status === 'ok' ? { ...item, editAnchor: undefined } : item], + ] as const)('treats %s as unknown rather than missing or unchanged', (_label, unavailable) => { + const before = run(npmSync, { read: (item) => item.path === 'package.json' ? unavailable(item) : item }) + expect(before.terminals).toEqual([]) + expect(before.data).toMatchObject({ status: 'indeterminate' }) + const after = run(npmSync, { + read: (item, afterCommand) => afterCommand && item.path === 'package.json' ? unavailable(item) : item, }) - expect(generator.next().value).toMatchObject({ - toolName: 'set_output', - input: { data: { status: 'invalid' } }, + expect(after.data).toMatchObject({ status: 'partial', verification: { filesChanged: expect.arrayContaining([ + expect.objectContaining({ path: 'package.json', after: { kind: 'unknown' }, changed: null }), + ]) } }) + }) + + test('leaves a newly written lockfile alone when its postimage cannot be read', () => { + const path = 'package-lock.json' + const { data, files } = run(npmSync, { + manager: (disk, command) => { disk.set(path, 'retained bytes'); return [json(terminalExit(command, 1))] }, + read: (item, afterCommand) => afterCommand && item.path === path ? + { selector: 'file', requestIndex: item.requestIndex, path, status: 'error', error: { code: 'io_error', message: 'Cannot observe', retryable: true } } : item, }) + expect(files.get(path)).toBe('retained bytes') + expect(data).toMatchObject({ status: 'indeterminate', rollbackRequired: true, rollbackReceipt: { + status: 'incomplete', deletedCreatedFiles: [], results: expect.arrayContaining([ + expect.objectContaining({ path, status: 'unknown' }), + ]), + } }) + }) + + test('defers repository guards instead of executing them through the dependency terminal', () => { + const { data, terminals } = run(npmSync, { files: { + 'package.json': baseManifest, + 'scripts/dependency-provenance-guard.ts': '// fixture guard', + } }) + expect(terminals).toHaveLength(1) + expect(data).toMatchObject({ status: 'partial', verification: { guards: { status: 'deferred' } } }) }) }) diff --git a/agents/__tests__/editor.test.ts b/agents/__tests__/editor.test.ts index 5030b24b40..2aa34d904b 100644 --- a/agents/__tests__/editor.test.ts +++ b/agents/__tests__/editor.test.ts @@ -1,5 +1,18 @@ import { describe, test, expect } from 'bun:test' import { readFileSync } from 'node:fs' +import { applyPatch } from 'diff' +import { editTransactionParams } from '@codebuff/common/tools/params/tool/edit-transaction' +import { readFilesParams } from '@codebuff/common/tools/params/tool/read-files' +import { readFilesResultV1Schema } from '@codebuff/common/tools/results/filesystem' +import { handleEditTransaction } from '@codebuff/agent-runtime/tools/handlers/tool/edit-transaction' +import { handleReadFiles } from '@codebuff/agent-runtime/tools/handlers/tool/read-files' +import { + buildReadFilesResponseV1, + confirmedMutationOutput, + createFileProcessingState, + defaultTestHandlerAuthority, + defaultTestAuthorityScope, +} from '@codebuff/agent-runtime/__tests__/read-files-edit-state-fixtures' import editor, { createCodeEditor } from '../editor/editor' import repairEditor from '../editor/repair-editor' @@ -122,7 +135,9 @@ describe('editor agent', () => { expect(editor.instructionsPrompt).toContain( 'parent responsibilities after you return', ) - expect(editor.instructionsPrompt).toContain('If edit_transaction aborts') + expect(editor.instructionsPrompt).toContain('If edit_transaction rejects preflight') + expect(editor.instructionsPrompt).toContain('a line range is not whole-file authority') + expect(editor.instructionsPrompt).not.toContain('cap.v3') expect(editor.instructionsPrompt).toContain( 'rebuild the whole related transaction', ) @@ -293,11 +308,107 @@ describe('editor agent', () => { expect(editor.instructionsPrompt).toContain('"newContent"') }) - test('contains write_file format example', () => { - expect(editor.instructionsPrompt).toContain('write_file') + test('advertises whole overwrite only with a complete paths read', () => { expect(editor.instructionsPrompt).toContain( 'write_file only for a necessary whole-file rewrite', ) + expect(editor.instructionsPrompt).toContain('using paths, not ranges') + }) + + test('read and edit examples use real capabilities and reject a full-span line token for overwrite', async () => { + type Example = { cb_tool_name: string } & Record + const examples = Array.from(editor.instructionsPrompt!.matchAll( + /\s*(\{[\s\S]*?\})\s*<\/codebuff_tool_call>/g, + ), ([, json]) => JSON.parse(json) as Example) + expect(examples.map(({ cb_tool_name }) => cb_tool_name)).toEqual([ + 'read_files', 'edit_transaction', + 'read_files', 'edit_transaction', + 'read_files', 'edit_transaction', + ]) + + const before: Record = { + 'src/config.ts': 'export const timeout = 1000\n', + 'src/client.ts': 'export const client = true\n', + 'src/large-file.ts': '// context\n'.repeat(11) + + 'export function loadConfig() {\n return { timeout: 1000 }\n}\n', + 'src/defaults.ts': '\uFEFFexport const timeout = 1000\r\n', + } + const after = { + 'src/config.ts': 'export const timeout = 1500\n', + 'src/client.ts': "import { timeout } from './config'\n\nexport const client = true\n", + 'src/large-file.ts': before['src/large-file.ts'].replace('1000', '1500'), + 'src/defaults.ts': 'export const timeout = 1500\n', + } + const verify = async (read: Example, edit: Example, refused = false) => { + const fileProcessingState = createFileProcessingState() + fileProcessingState.strictReadBeforeEdit = true + const common = { + ...defaultTestHandlerAuthority, + previousToolCallFinished: Promise.resolve(), + logger: noopLogger, + requestOptionalFile: async ({ filePath }: { filePath: string }) => before[filePath] ?? null, + } + const { output: readOutput } = await handleReadFiles({ + ...common, + toolCall: { + toolCallId: 'editor-example-read', + toolName: 'read_files', + input: readFilesParams.inputSchema.parse(read), + }, + fileProcessingState, + requestFiles: async (input) => buildReadFilesResponseV1(input, (path) => before[path] ?? null), + }) + const readResult = readFilesResultV1Schema.parse(readOutput[0]?.value) + expect(readResult.status).toBe('ok') + const anchor = 'editAnchor' in readResult.results[0] && readResult.results[0].editAnchor + expect(anchor).toBeTruthy() + if (!anchor) throw new Error('The example read must issue a capability') + const hasLines = (read.ranges as unknown[] | undefined)?.length + expect(anchor.rawBasis?.scope).toBe(hasLines ? 'lines' : 'whole') + const editInput = JSON.parse(JSON.stringify(edit).replace( + /CAPABILITY_FROM_THIS_(?:WHOLE|RANGE)_READ/g, anchor.readCapability, + )) + expect(editTransactionParams.providerInputSchema.safeParse(editInput).success).toBe(true) + const input = editTransactionParams.inputSchema.parse(editInput) + const applied: Record = {} + const explicit = input.edits.some((edit) => edit.type === 'write_file' || edit.type === 'replace_range') + const { output } = await handleEditTransaction({ + ...common, + toolCall: { toolCallId: 'editor-example-edit', toolName: 'edit_transaction', input }, + // Prove these explicit tokens work without relying on sticky authority. + fileProcessingState: explicit ? { ...createFileProcessingState(), strictReadBeforeEdit: true } : fileProcessingState, + requestClientToolCall: async (call) => { + for (const change of call.input) { + if (!('content' in change)) throw new Error('Expected a content edit') + const next = change.type === 'file' ? change.content : applyPatch(before[change.path], change.content) + if (next === false) throw new Error(`Could not apply example edit: ${change.path}`) + applied[change.path] = next + } + return confirmedMutationOutput(call, applied, defaultTestAuthorityScope) as any + }, + }) + if (refused) { + expect(applied).toEqual({}) + expect(output[0]?.value).toMatchObject({ + errorMessage: expect.any(String), + failures: [expect.objectContaining({ + errorMessage: expect.stringContaining('a range capability cannot authorize a whole-file overwrite'), + })], + }) + return + } + expect(output[0]?.value).not.toHaveProperty('errorMessage') + expect(applied).toEqual(Object.fromEntries(input.edits.map(({ path }) => [ + path, after[path as keyof typeof after], + ]))) + } + + for (let index = 0; index < examples.length; index += 2) { + await verify(examples[index], examples[index + 1]) + } + await verify({ + cb_tool_name: 'read_files', ranges: [{ path: 'src/defaults.ts', startLine: 1, endLine: 2 }], + }, examples[5], true) }) test('contains edit_transaction format example', () => { @@ -1515,8 +1626,8 @@ describe('editor agent', () => { }).value, ).toBe('STEP') - // Continuations are unlimited: a second stepsComplete with still-no - // edits yields ANOTHER action-required directive, not the receipt. + // A second stepsComplete without edits still gets a retry, within the + // no-edit retry budget. const secondActionRequired = generator.next({ agentState: createMockAgentState([ ...preReadMessages, @@ -1562,6 +1673,205 @@ describe('editor agent', () => { ]) }) + test('reports a blocked receipt after bounded completions without an edit', () => { + const state = createMockAgentState([]) + const generator = editor.handleSteps!({ + agentState: state, + logger: noopLogger as any, + prompt: 'Target files:\n- src/target.ts', + params: {}, + }) + expect(generator.next().value).toMatchObject({ toolName: 'read_files' }) + const stepResult = { agentState: state, toolResult: undefined, stepsComplete: true } + expect(generator.next(stepResult).value).toBe('STEP') + for (let attempt = 0; attempt < 3; attempt++) { + expect(generator.next(stepResult).value).toMatchObject({ toolName: 'add_message' }) + expect(generator.next(stepResult).value).toBe('STEP') + } + expect(generator.next(stepResult).value).toMatchObject({ + toolName: 'set_output', + input: { output: { status: 'blocked', failureStage: 'no_edit_transaction' } }, + }) + }) + + describe('no-action convergence', () => { + const path = 'src/target.ts' + const source = 'export const limit = 2' + const read = (call: number, content = source) => ({ + role: 'tool', + toolName: 'read_files', + toolCallId: `read-${call}`, + content: [{ + type: 'json' as const, + value: { + kind: 'read_files_result', + version: 1, + results: [{ + selector: 'file', + path, + status: 'ok', + complete: true, + content, + editAnchor: { + startLine: 1, + endLine: 1, + contentHash: `hash:${content}`, + readCapability: `cap.v4.fixture-${call}`, + }, + }], + }, + }], + }) + const rejected = (call: number) => ({ + role: 'tool', + toolName: 'edit_transaction', + toolCallId: `edit-${call}`, + content: [{ + type: 'json', + value: { + requiresFreshRead: true, + errorCode: 'no_match', + recovery: { paths: [path], preferredStrategy: 'replace_range' }, + }, + }], + }) + const start = (preRead?: ReturnType) => { + let messages: unknown[] = [] + const handleSteps = new Function( + `return (${editor.handleSteps!.toString()})`, + )() as NonNullable + const generator = handleSteps({ + agentState: createMockAgentState(), + logger: noopLogger as any, + prompt: `Requirements:\n- Set the limit to 2\n\nTarget files:\n- ${path}`, + params: {}, + }) + const step = (stepsComplete: boolean, ...newMessages: unknown[]) => { + messages = [...messages, ...newMessages] + return generator.next({ + agentState: createMockAgentState(messages), + toolResult: undefined, + stepsComplete, + }).value + } + expect(generator.next().value).toMatchObject({ toolName: 'read_files' }) + expect(generator.next({ + agentState: createMockAgentState(messages), + toolResult: preRead?.content, + stepsComplete: false, + }).value).toBe('STEP') + const resume = (directive: unknown) => { + expect(directive).toMatchObject({ toolName: 'add_message' }) + const { input } = directive as { input: { content: string } } + expect(step(false, { role: 'user', content: input.content })).toBe('STEP') + } + return { step, resume } + } + + test('stops repeated identical read-only evidence across completion and in-progress steps', () => { + const { step, resume } = start(read(0)) + expect(step(false, read(1))).toBe('STEP') + resume(step(true, { + role: 'assistant', + content: [{ type: 'text', text: 'Looking at the file again.' }], + })) + expect(step(false, read(2))).toBe('STEP') + expect(step(false, read(3))).toMatchObject({ + toolName: 'set_output', + input: { output: { + status: 'blocked', + failureStage: 'no_edit_transaction', + blockedReason: expect.stringContaining('without new evidence'), + changedFiles: [], + requirementsAddressed: [], + unresolved: [path], + targetFileProgress: { pendingTargetFiles: [path] }, + } }, + }) + }) + + test('stops repeated identical transaction recovery even when tools keep the step open', () => { + const { step } = start() + for (let call = 1; call <= 3; call++) { + expect(step(false, rejected(call))).toBe('STEP') + } + expect(step(false, rejected(4))).toMatchObject({ + toolName: 'set_output', + input: { output: { + status: 'blocked', + failureStage: 'edit_recovery_exhausted', + changedFiles: [], + unresolved: [path], + recovery: { paths: [path], errorCode: 'no_match', attempts: 0 }, + } }, + }) + }) + + test('allows fresh source evidence and fruitful recovery after three no-action completions', () => { + const { step, resume } = start(read(0)) + for (let attempt = 0; attempt < 3; attempt++) resume(step(true)) + resume(step(true, read(1, 'export const limit = 3'))) + resume(step(true, rejected(2))) + expect(step(false, read(3, 'export const limit = 4'))).toBe('STEP') + for (let edit = 1; edit <= 5; edit++) { + const operationId = `productive-${edit}` + expect(step(false, { + role: 'tool', + toolName: 'edit_transaction', + content: [{ type: 'json', value: withCommittedReceipt({ + kind: 'file_mutation_result', + version: 1, + operationId, + outcome: 'applied', + authorityTier: 'portable_path', + actions: [{ + index: 0, + actionId: `${operationId}:0`, + action: 'update', + path, + outcome: 'applied', + afterHash: `after-${edit}`, + }], + errors: [], + freshCapabilities: [], + }) }], + })).toBe('STEP') + } + expect(step(true)).toMatchObject({ + toolName: 'set_output', + input: { output: { + status: 'completed', + changedFiles: [path], + unresolved: [], + mutationReceipts: Array.from({ length: 5 }, (_, index) => ({ + operationId: `productive-${index + 1}`, + })), + } }, + }) + }) + + test.each([true, false])('finishes an explicit no-op only when the source supports its quote (%s)', (supported) => { + const { step, resume } = start(read(0)) + for (let attempt = 0; attempt < 3; attempt++) resume(step(true)) + const evidence = [{ + path, + quote: supported ? source : 'export const limit = 99', + reason: 'The requested limit is already set.', + }] + const result = step(true, { + role: 'assistant', + content: [{ type: 'text', text: `${JSON.stringify(evidence)}` }], + }) + expect(result).toMatchObject({ + toolName: 'set_output', + input: { output: supported + ? { status: 'completed', completionKind: 'noop', changedFiles: [], evidence, unresolved: [] } + : { status: 'blocked', failureStage: 'no_edit_transaction', changedFiles: [], unresolved: [path] }, + }, + }) + }) + }) + test('reports target file progress when one target remains unchanged', () => { const mockAgentState = createMockAgentState([]) const mockLogger = noopLogger diff --git a/agents/__tests__/file-lister.test.ts b/agents/__tests__/file-lister.test.ts index e5c807be8d..32d6c17768 100644 --- a/agents/__tests__/file-lister.test.ts +++ b/agents/__tests__/file-lister.test.ts @@ -2,258 +2,198 @@ import { describe, expect, test } from 'bun:test' import { createFileLister } from '../file-explorer/file-lister' -import type { AgentState, StepText, ToolCall } from '../types/agent-definition' -import type { ToolResultOutput } from '../types/util-types' - -const createMockAgentState = (): AgentState => ({ - agentId: 'file-lister-test', - runId: 'test-run', - parentId: undefined, - messageHistory: [], - output: undefined, - systemPrompt: '', - toolDefinitions: {}, - contextTokenCount: 0, -}) - -const nextResult = (toolResult?: ToolResultOutput[]) => ({ - agentState: createMockAgentState(), - toolResult, - stepsComplete: true, +const inventory = (rootPath: string, filePaths: string[], options = {}) => ({ + path: rootPath, + type: 'directory', + inventory: { + kind: 'read_subtree_inventory', + version: 1, + mode: 'paths', + pathBasis: 'project-relative', + rootPath, + filePaths, + provenance: 'live', + status: 'complete', + omissions: [], + ...options, + }, }) - -const logger = { - debug: () => {}, - info: () => {}, - warn: () => {}, - error: () => {}, +const result = (value: unknown) => + ({ toolResult: [{ type: 'json', value }] }) as any +function lister( + directories?: string[], + prompt: string | undefined = 'Find router', +) { + return createFileLister().handleSteps!({ + prompt, + params: directories ? { directories } : {}, + } as any) } -describe('file-lister agent', () => { - test('returns deterministic paths only from requested directories', () => { - const definition = createFileLister() - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find React component files', - params: { directories: ['frontend'] }, +describe('file-lister local retrieval contract', () => { + test('uses project-relative entries without parsing rendered trees, dedupes, ranks and reports caps', () => { + const generator = lister(['packages/backend', 'packages/peer']) + expect(generator.next().value).toMatchObject({ + toolName: 'query_index', + input: { pathPrefixes: ['packages/backend', 'packages/peer'] }, }) - - const queryCall = generator.next().value as ToolCall - expect(queryCall.toolName).toBe('query_index') - expect(queryCall.input).toMatchObject({ - pathPrefixes: ['frontend'], + expect( + generator.next( + result({ + kind: 'query_index_result', + schemaVersion: 1, + status: { state: 'disabled' }, + results: [], + }), + ).value, + ).toMatchObject({ + toolName: 'read_subtree', + input: { mode: 'paths', paths: ['packages/backend', 'packages/peer'] }, }) - expect((generator.next(nextResult([])).value as ToolCall).toolName).toBe( - 'read_subtree', - ) - - const result = generator.next( - nextResult([ - { - type: 'json', - value: [ + const primary = [ + 'packages/backend/assets/ contrôle ', + 'packages/backend/files/router.ts', + 'packages/backend/notes 2026', + ] + const output = generator.next( + result([ + inventory('packages/backend', [ + ...primary, + primary[0], + ...Array.from({ length: 7 }, (_, i) => `packages/backend/${i}.ts`), + ]), + inventory('packages/peer', [], { + status: 'partial', + omissions: ['node_limit'], + }), + ]), + ).value + expect(output).toMatchObject({ + toolName: 'set_output', + input: { + files: [ + expect.objectContaining({ path: primary[1] }), + ...Array.from({ length: 7 }, () => expect.any(Object)), + ], + retrieval: { + status: 'partial', + candidateCount: 10, + omittedCount: 2, + observations: expect.arrayContaining([ + { source: 'index', status: 'unavailable' }, { - path: 'frontend', - type: 'directory', - printedTree: - 'frontend/\n src/\n App.tsx\n App render\n components/\n Button.tsx\n Button\nbackend/\n src/\n server.ts\n', + source: 'live', + scope: 'packages/peer', + status: 'partial', + reasons: ['node_limit'], }, - ], + ]), }, - ]), - ) - const output = result.value as StepText - - expect(output.type).toBe('STEP_TEXT') - expect(output.text).toContain('frontend/src/App.tsx') - expect(output.text).toContain('frontend/src/components/Button.tsx') - expect(output.text).not.toContain('backend') - }) - - test('ranks project files from the subtree when directories are omitted', () => { - const definition = createFileLister() - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find files related to user authentication and user management', + }, }) + }) - expect((generator.next().value as ToolCall).toolName).toBe('query_index') - expect((generator.next(nextResult([])).value as ToolCall).toolName).toBe( - 'read_subtree', - ) - - const result = generator.next( - nextResult([ - { - type: 'json', - value: [ + test('verifies stale and related index paths with bounded stat, not a tree scan', () => { + const generator = lister(['lib']) + generator.next() + expect( + generator.next( + result({ + kind: 'query_index_result', + schemaVersion: 1, + status: { state: 'stale', stale: true }, + snapshot: { snapshotId: 'snap' }, + results: [ { - path: '.', - type: 'directory', - printedTree: - 'src/\n services/\n user-service.ts\n getUser\n auth-service.ts\n login\n billing-service.ts\n types/\n user.ts\n invoice.ts\n utils/\n logger.ts\nindex.ts\npackage.json\nREADME.md\ndocs/\n guide.md\n', + path: 'lib/deleted', + relatedFiles: [ + { path: 'lib/live' }, + { path: 'elsewhere/hidden' }, + ], }, ], + }), + ).value, + ).toMatchObject({ + toolName: 'read_subtree', + input: { mode: 'stat', paths: ['lib/deleted', 'lib/live'] }, + }) + const output = generator.next( + result([ + { path: 'lib/deleted', error: { code: 'not_found' } }, + { + ...inventory('lib/live', ['lib/live'], { mode: 'stat' }), + type: 'file', }, ]), - ) - const output = result.value as StepText - const rankedPaths = output.text.split('\n') - - expect(output.type).toBe('STEP_TEXT') - expect(rankedPaths).toContain('src/services/user-service.ts') - expect(rankedPaths).toContain('src/services/auth-service.ts') - expect(rankedPaths).toContain('src/types/user.ts') - expect(rankedPaths.indexOf('src/services/user-service.ts')).toBeLessThan( - rankedPaths.indexOf('src/services/billing-service.ts'), - ) - expect(rankedPaths.indexOf('src/types/user.ts')).toBeLessThan( - rankedPaths.indexOf('src/services/billing-service.ts'), - ) - }) - - test('uses query_index results as candidates when the subtree is unusable', () => { - const definition = createFileLister() - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find files related to user authentication and user management', - }) - - expect((generator.next().value as ToolCall).toolName).toBe('query_index') - expect( - ( - generator.next( - nextResult([ + ).value + expect(output).toMatchObject({ + toolName: 'set_output', + input: { + files: [{ path: 'lib/live', basis: 'index_verified', summary: 'live' }], + retrieval: { + status: 'partial', + observations: expect.arrayContaining([ + { source: 'index', status: 'stale', snapshotId: 'snap' }, { - type: 'json', - value: { - kind: 'query_index_result', - results: [ - { - path: 'src/services/user-service.ts', - relatedFiles: [ - { path: 'src/services/auth-service.ts' }, - { path: 'src/types/user.ts' }, - ], - }, - ], - }, + source: 'verification', + status: 'partial', + reasons: ['not_found'], }, ]), - ).value as ToolCall - ).toolName, - ).toBe('read_subtree') - - const result = generator.next( - nextResult([{ type: 'json', value: { errorMessage: 'read failed' } }]), - ) - const output = result.value as StepText - - expect(output.type).toBe('STEP_TEXT') - expect(output.text).toContain('src/services/user-service.ts') - expect(output.text).toContain('src/services/auth-service.ts') - expect(output.text).toContain('src/types/user.ts') - }) - - test('falls back to model ranking when index and subtree output are malformed', () => { - const definition = createFileLister() - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find React component files', - params: { directories: ['frontend'] }, + }, + }, }) + }) - generator.next() - generator.next(nextResult([])) - const result = generator.next( - nextResult([{ type: 'json', value: { errorMessage: 'read failed' } }]), - ) - - expect(result.value).toBe('STEP') + test('never treats malformed, downlevel or omitted subtree inventory as confirmed empty', () => { + for (const value of [ + null, + [{ path: '.', type: 'directory', printedTree: '' }], + [inventory('.', [], { status: 'complete', omissions: ['entry_limit'] })], + ]) { + const generator = lister(undefined, '') + expect(generator.next().value).toMatchObject({ toolName: 'read_subtree' }) + expect(generator.next(result(value)).value).toMatchObject({ + toolName: 'set_output', + input: { + files: [], + retrieval: { + status: expect.stringMatching(/^(partial|failed|unavailable)$/), + }, + }, + }) + } }) - test('parses a 2-space-indented printedTree when directories are omitted', () => { - const definition = createFileLister() - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find user service files', + test('does not broaden invalid scope and reports the directory cap', () => { + expect(lister(['/abs', '../escape', 'src/**']).next().value).toMatchObject({ + toolName: 'set_output', + input: { files: [], retrieval: { status: 'failed' } }, }) - - expect((generator.next().value as ToolCall).toolName).toBe('query_index') - expect((generator.next(nextResult([])).value as ToolCall).toolName).toBe( - 'read_subtree', - ) - - const result = generator.next( - nextResult([ - { - type: 'json', - value: [ + const requested = Array.from({ length: 9 }, (_, i) => `d${i}`) + const generator = lister(requested, '') + expect(generator.next().value).toMatchObject({ + toolName: 'read_subtree', + input: { paths: requested.slice(0, 8) }, + }) + expect( + generator.next( + result(requested.slice(0, 8).map((path) => inventory(path, []))), + ).value, + ).toMatchObject({ + input: { + retrieval: { + status: 'partial', + observations: expect.arrayContaining([ { - path: '.', - type: 'directory', - printedTree: - 'src/\n services/\n user-service.ts\n getUser\n auth-service.ts\n', + source: 'scope', + status: 'partial', + reasons: ['directory_limit'], }, - ], + ]), }, - ]), - ) - const output = result.value as StepText - - expect(output.type).toBe('STEP_TEXT') - expect(output.text).toContain('src/services/user-service.ts') - }) - - test('rejects invalid directories without calling query_index or read_subtree', () => { - const definition = createFileLister() - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find React component files', - params: { - directories: ['/abs/path', '../escape', 'src/**', 'foo*'], }, }) - - const result = generator.next() - const output = result.value as StepText - - expect(output.type).toBe('STEP_TEXT') - expect(output.text).toBe( - 'No valid project-relative directory scope was provided.', - ) - expect((result.value as { toolName?: string }).toolName).toBeUndefined() - expect(result.done).toBe(false) - expect(generator.next().done).toBe(true) - }) - - test('uses at most 8 valid directories and ignores extras', () => { - const definition = createFileLister() - const directories = ['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9'] - const generator = definition.handleSteps!({ - agentState: createMockAgentState(), - logger, - prompt: 'Find files', - params: { directories }, - }) - - const queryCall = generator.next().value as ToolCall - expect(queryCall.toolName).toBe('query_index') - expect(queryCall.input).toMatchObject({ - pathPrefixes: ['d1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8'], - }) - expect( - ( - definition.inputSchema?.params?.properties?.directories as { - description?: string - } - )?.description, - ).toContain('extra entries are ignored') }) }) diff --git a/agents/__tests__/file-picker.test.ts b/agents/__tests__/file-picker.test.ts index bc65ea2040..b1d98a1f40 100644 --- a/agents/__tests__/file-picker.test.ts +++ b/agents/__tests__/file-picker.test.ts @@ -1,1039 +1,229 @@ -import { describe, test, expect } from 'bun:test' +import { describe, expect, test } from 'bun:test' import filePicker, { createFilePicker, extractErrorMessage, } from '../file-explorer/file-picker' -import type { AgentState, ToolCall, StepText } from '../types/agent-definition' - -describe('file-picker agent', () => { - const createMockAgentState = (): AgentState => ({ - agentId: 'file-picker-test', - runId: 'test-run', - parentId: undefined, - messageHistory: [], - output: undefined, - systemPrompt: '', - toolDefinitions: {}, - contextTokenCount: 0, - }) +const completed = { + receiptId: 'receipt-fixture', + status: 'completed', + outcome: 'ok', + runOutcome: { termination: 'completed' }, +} +const child = (value: unknown, agentReceipt: unknown = completed) => ({ + value, + agentReceipt, +}) +const structured = (files: string[], receipt: unknown) => ({ + type: 'structuredOutput', + value: { + files: files.map((path) => ({ + path, + summary: 'legacy-compatible', + basis: 'live', + })), + retrieval: receipt, + }, +}) +const receipt = (scope: string[], candidateCount: number, overrides = {}) => ({ + kind: 'file_retrieval_receipt', + version: 1, + pathBasis: 'project-relative', + scope, + status: candidateCount ? 'complete' : 'empty', + candidateCount, + omittedCount: 0, + observations: [ + { source: 'live', status: 'complete', scope: scope[0] ?? '.' }, + ], + ...overrides, +}) - const createMockLogger = () => ({ - debug: () => {}, - info: () => {}, - warn: () => {}, - error: () => {}, +function picker( + input: unknown[], + directories?: string[], + prompt = 'Find files', +) { + const generator = createFilePicker().handleSteps!({ + prompt, + params: directories && { directories }, + } as any) + expect(generator.next().value).toMatchObject({ + toolName: 'spawn_agents', + input: { agents: [{ agent_type: 'file-lister', prompt }] }, }) + const finish = generator.next({ + toolResult: [{ type: 'json', value: input }], + } as any) + expect(finish.value).toMatchObject({ toolName: 'set_output' }) + expect(generator.next().done).toBe(true) + return (finish.value as any).input +} + +const message = (text: string, type = 'lastMessage') => ({ + type, + value: [{ role: 'assistant', content: [{ type: 'text', text }] }], +}) - describe('definition', () => { - test('has correct id', () => { - expect(filePicker.id).toBe('file-picker') - }) - - test('has display name', () => { - expect(filePicker.displayName).toBe('Fletcher the File Fetcher') - }) - - test('has structured file output', () => { - expect(filePicker.outputMode).toBe('structured_output') - expect(filePicker.outputSchema).toBeDefined() - }) - - test('does not include message history', () => { - expect(filePicker.includeMessageHistory).toBe(false) - }) - - test('has spawn_agents tool', () => { - expect(filePicker.toolNames).toContain('spawn_agents') - expect(filePicker.toolNames).toContain('set_output') - expect(filePicker.programmaticToolNames ?? []).not.toContain('read_files') - }) - - test('can spawn file-lister agent', () => { - expect(filePicker.spawnableAgents).toContain('file-lister') - }) - - test('has disabled reasoning', () => { - expect(filePicker.reasoningOptions?.enabled).toBe(false) - }) +describe('file-picker contract', () => { + test('keeps its public file projection and existing tool/child restrictions', () => { + expect(filePicker.id).toBe('file-picker') + expect(filePicker.outputMode).toBe('structured_output') + expect(filePicker.includeMessageHistory).toBe(false) + expect(filePicker.toolNames).toEqual(['spawn_agents', 'set_output']) + expect(filePicker.spawnableAgents).toEqual(['file-lister']) + expect(extractErrorMessage({ type: 'error', value: 'failed' })).toBe( + 'failed', + ) }) - describe('createFilePicker', () => { - test('uses flash-lite model', () => { - const picker = createFilePicker() - expect(picker.model).toBeUndefined() - }) - - test('spawns single file-lister', () => { - const picker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = picker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - const result = generator.next() - - const toolCall = result.value as ToolCall<'spawn_agents'> - expect(toolCall.toolName).toBe('spawn_agents') - expect(toolCall.input.agents).toHaveLength(1) - expect(toolCall.input.agents[0].agent_type).toBe('file-lister') + test('preserves exact typed names and child receipt, including whitespace and extensionless', () => { + const scope = ['packages/backend'] + const paths = [ + 'packages/backend/files/example.ts', + 'packages/backend/.gitignore', + 'packages/backend/Dockerfile', + 'packages/backend/ forêt avec espaces ', + ] + const output = picker( + [child(structured(paths, receipt(scope, paths.length)))], + scope, + ) + expect(output.files.map((file: { path: string }) => file.path)).toEqual( + paths, + ) + expect(output.retrieval).toMatchObject({ + status: 'complete', + child: { + receiptId: completed.receiptId, + status: 'completed', + outcome: 'ok', + termination: 'completed', + }, }) }) - describe('input schema', () => { - test('has prompt parameter', () => { - expect(filePicker.inputSchema?.prompt?.type).toBe('string') - }) - - test('has optional directories parameter', () => { - const dirSchema = filePicker.inputSchema?.params?.properties?.directories - const dirSchemaObj = - dirSchema && typeof dirSchema === 'object' && !Array.isArray(dirSchema) - ? dirSchema - : undefined - expect(dirSchemaObj?.type).toBe('array') - expect(filePicker.inputSchema?.params?.required).toHaveLength(0) - }) - - test('directories is array of strings', () => { - const dirSchema = filePicker.inputSchema?.params?.properties?.directories - const dirSchemaObj = - dirSchema && typeof dirSchema === 'object' && !Array.isArray(dirSchema) - ? dirSchema - : undefined - const itemsSchema = dirSchemaObj?.items - const itemsSchemaObj = - itemsSchema && - typeof itemsSchema === 'object' && - !Array.isArray(itemsSchema) - ? (itemsSchema as { type?: string }) - : undefined - expect(itemsSchemaObj?.type).toBe('string') - }) - }) - - describe('handleStepsDefault', () => { - test('yields spawn_agents with file-lister', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - prompt: 'Find auth files', - params: {}, - }) - - const result = generator.next() - - const toolCall = result.value as ToolCall<'spawn_agents'> - expect(toolCall.toolName).toBe('spawn_agents') - expect(toolCall.input.agents[0].prompt).toBe('Find auth files') - }) - - test('passes params to file-lister', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - prompt: 'Find files', - params: { directories: ['src', 'lib'] }, - }) - - const result = generator.next() - - const toolCall = result.value as ToolCall<'spawn_agents'> - expect(toolCall.input.agents[0].params).toEqual({ - directories: ['src', 'lib'], - }) - }) - - test('handles empty tool result gracefully', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - // First yield is spawn_agents - generator.next() - - // Return empty result - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [] as ToolResultOutput[], - stepsComplete: true, - }) - - const stepText = result.value as StepText - expect(stepText.type).toBe('STEP_TEXT') - expect(stepText.text).toContain('Error') - }) - - test('yields set_output with extracted paths from lastMessage format', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - // First yield is spawn_agents - generator.next() - - // Mock spawn_agents result - wrapped in toolResult object with production structure - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { type: 'text', text: 'src/auth.ts\nsrc/login.ts' }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - expect(paths).toContain('src/auth.ts') - expect(paths).toContain('src/login.ts') - }) - - test('yields set_output with extracted paths from allMessages format', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - generator.next() - - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'allMessages', - value: [ - { - role: 'user', - content: [{ type: 'text', text: 'find files' }], - }, - { - role: 'assistant', - content: [ - { type: 'text', text: 'src/user.ts\nsrc/config.ts' }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - expect(paths).toContain('src/user.ts') - expect(paths).toContain('src/config.ts') - }) - - test('yields set_output with extracted paths from structuredOutput format', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - generator.next() - - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'structuredOutput', - value: { message: 'src/foo.ts\nsrc/bar.ts' }, - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - expect(paths).toContain('src/foo.ts') - expect(paths).toContain('src/bar.ts') - }) - - test('deduplicates paths from results', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - generator.next() - - // Result with duplicate paths - wrapped in toolResult with production structure - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { - type: 'text', - text: 'src/file.ts\nsrc/file.ts\nsrc/other.ts', - }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - // Should deduplicate - const toolCall = result.value as ToolCall<'set_output'> - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - expect(paths).toHaveLength(2) - expect(paths).toContain('src/file.ts') - expect(paths).toContain('src/other.ts') - }) - - test('yields set_output without read_files', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - generator.next() - - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [{ type: 'text', text: 'src/file.ts' }], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - expect(toolCall.includeToolCall).toBe(false) - expect(toolCall.input.files).toEqual([ - { path: 'src/file.ts', summary: 'file.ts' }, - ]) - expect(result.done).toBe(false) - expect(generator.next().done).toBe(true) - }) - - test('handles error results from spawned agents', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - params: {}, - }) - - generator.next() - - // Result with error - wrapped in toolResult with production structure - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'error', - message: 'File lister failed', - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - const stepText = result.value as StepText - expect(stepText.type).toBe('STEP_TEXT') - expect(stepText.text).toContain('Error from file-lister') - expect(stepText.text).toContain('File lister failed') - }) - - test('keeps valid paths when neighboring file-lister lines are malformed', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: {}, - }) - generator.next() - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { - type: 'text', - text: 'Files:\n- `src/a.ts`\nhttps://example.com\n2. src/b.ts', - }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - }) - expect( - (result.value as ToolCall<'set_output'>).input.files.map( - (file: { path: string }) => file.path, - ), - ).toEqual(['src/a.ts', 'src/b.ts']) - }) - - test('rejects unsafe directory prefixes instead of rewriting them to project-relative scope', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: { directories: ['src', '/etc'] }, - }) - generator.next() - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { - type: 'text', - text: 'src/a.ts\netc/passwd.ts', - }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - }) - expect( - (result.value as ToolCall<'set_output'>).input.files.map( - (file: { path: string }) => file.path, + test('preserves clean empty and upstream cap separately', () => { + expect( + picker([child(structured([], receipt([], 0)))]).retrieval.status, + ).toBe('empty') + const files = Array.from({ length: 8 }, (_, i) => `src/${i}.ts`) + expect( + picker([ + child( + structured( + files, + receipt([], 20, { status: 'partial', omittedCount: 12 }), + ), ), - ).toEqual(['src/a.ts']) - }) - - test('enforces requested directory scope on returned candidates', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: { directories: ['packages/sdk'] }, - }) - generator.next() - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { - type: 'text', - text: 'packages/sdk/a.ts\ncli/src/outside.ts', - }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - }) - expect( - (result.value as ToolCall<'set_output'>).input.files.map( - (file: { path: string }) => file.path, - ), - ).toEqual(['packages/sdk/a.ts']) - }) - - test('uses a scope-specific message when every safe path is outside requested directories', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: { directories: ['packages/sdk'] }, - }) - generator.next() - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { - type: 'text', - text: 'cli/src/outside.ts\nweb/app.ts', - }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - }) - const stepText = result.value as StepText - expect(stepText.type).toBe('STEP_TEXT') - expect(stepText.text).toBe( - 'No file paths were found within the requested directories.', - ) - expect(stepText.text).not.toContain('No safe project-relative file paths') - }) + ]).retrieval, + ).toMatchObject({ status: 'partial', candidateCount: 20, omittedCount: 12 }) + }) - const spawnFileListResult = (text: string) => ({ - agentState: createMockAgentState(), - toolResult: [ + test('failed, cancelled or truncated receipts cannot salvage an apparently green snapshot', () => { + for (const [upstream, status] of [ + [ { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [{ type: 'text', text }], - }, - ], - }, - }, - ], + ...completed, + status: 'failed', + outcome: 'crashed', + runOutcome: { termination: 'failed' }, }, + 'failed', ], - stepsComplete: true, - }) - - // C1.9: reject path traversal and absolute-outside-cwd before set_output. - test('keeps filenames that contain adjacent dots but not a .. path segment', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: {}, - }) - generator.next() - const result = generator.next( - spawnFileListResult('src/foo..bar.ts\nsrc/ok.ts'), - ) + [ + { + ...completed, + status: 'cancelled', + runOutcome: { termination: 'cancelled' }, + }, + 'cancelled', + ], + [{ ...completed, status: 'partial', outcome: 'truncated' }, 'partial'], + ] as const) { expect( - (result.value as ToolCall<'set_output'>).input.files.map( - (file: { path: string }) => file.path, - ), - ).toEqual(['src/foo..bar.ts', 'src/ok.ts']) - }) - - test('rejects ../ traversal paths and keeps sibling project files', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: {}, - }) - generator.next() - const result = generator.next( - spawnFileListResult('src/safe.ts\n../secret.ts\nsrc/also-safe.ts'), - ) - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - expect(paths).toEqual(['src/safe.ts', 'src/also-safe.ts']) - expect(paths).not.toContain('../secret.ts') - }) - - test('rejects absolute paths outside the project cwd', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: {}, - }) - generator.next() - const result = generator.next( - spawnFileListResult('src/ok.ts\n/tmp/outside-cwd.ts\n/etc/passwd.ts'), - ) - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - expect(paths).toEqual(['src/ok.ts']) - expect(paths).not.toContain('/tmp/outside-cwd.ts') - expect(paths).not.toContain('/etc/passwd.ts') - }) - - test('yields STEP_TEXT and skips set_output when every path is unsafe', () => { - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: createMockLogger() as any, - params: {}, - }) - generator.next() - const result = generator.next( - spawnFileListResult( - '../secret.ts\n/tmp/outside-cwd.ts\n../../etc/hosts.ts', - ), - ) - const stepText = result.value as StepText - expect(stepText.type).toBe('STEP_TEXT') - expect(stepText.text).toContain('No safe project-relative file paths') - expect((result.value as { toolName?: string }).toolName).not.toBe( - 'set_output', - ) - }) - - test('traversal drop log counts only unsafe paths, not directory-scope drops', () => { - const debugMessages: string[] = [] - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: { - debug: (message: string) => { - debugMessages.push(message) - }, - info: () => {}, - warn: () => {}, - error: () => {}, - } as any, - params: { directories: ['src'] }, + picker([ + child(structured(['src/looks-good.ts'], receipt([], 1)), upstream), + ]), + ).toMatchObject({ + files: [], + retrieval: { + status, + child: { status: upstream.status, outcome: upstream.outcome }, + }, }) - generator.next() - const result = generator.next( - spawnFileListResult( - 'src/in-scope.ts\nlib/out-of-scope.ts\n../escape.ts', - ), - ) - expect( - (result.value as ToolCall<'set_output'>).input.files.map( - (file: { path: string }) => file.path, - ), - ).toEqual(['src/in-scope.ts']) - const traversalLogs = debugMessages.filter((message) => - message.includes('outside project root or containing traversal'), - ) - expect(traversalLogs).toEqual([ - 'file-picker: dropped 1 path(s) outside project root or containing traversal', - ]) + } + expect(picker([])).toMatchObject({ + files: [], + retrieval: { status: 'unavailable' }, }) + }) - test('does not log traversal drops when only directory-scope paths are filtered', () => { - const debugMessages: string[] = [] - const generator = createFilePicker().handleSteps!({ - agentState: createMockAgentState(), - logger: { - debug: (message: string) => { - debugMessages.push(message) - }, - info: () => {}, - warn: () => {}, - error: () => {}, - } as any, - params: { directories: ['src'] }, - }) - generator.next() - generator.next( - spawnFileListResult('src/in-scope.ts\nlib/out-of-scope.ts'), - ) - expect( - debugMessages.some((message) => - message.includes('outside project root or containing traversal'), + test('rejects malformed/unknown typed data and out-of-scope siblings without reinterpreting it as text', () => { + const scope = ['src'] + for (const pair of [ + child(structured(['src/wrong.ts'], receipt(scope, 1, { version: 2 }))), + child(structured(['src/first.ts'], receipt(scope, 3))), + child( + structured( + ['src-extra/leak.ts', 'src/../escape', '/tmp/absolute'], + receipt(scope, 3), ), - ).toBe(false) - }) - - // M2.2: relevance scoring orders paths by prompt-keyword matches, and caps - // to the top 8 (matching the spawner prompt's advertised limit). - test('orders paths by prompt-keyword relevance', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - prompt: 'Find auth files', - params: {}, - }) - - generator.next() - - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [ - { - type: 'text', - text: 'src/unrelated.ts\nsrc/auth/login.ts\nsrc/auth/session.ts\nsrc/utils/helpers.ts', - }, - ], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - const paths = toolCall.input.files.map( - (file: { path: string }) => file.path, - ) - // auth-bearing paths score higher than unrelated/utils paths. - expect(paths[0]).toBe('src/auth/login.ts') - expect(paths[1]).toBe('src/auth/session.ts') - // The two non-auth files retain the file-lister's upstream rank. - expect(paths).toContain('src/unrelated.ts') - expect(paths).toContain('src/utils/helpers.ts') - expect(paths).toHaveLength(4) - }) - - test('caps to top 8 paths when more candidates are returned', () => { - const defaultPicker = createFilePicker() - const mockAgentState = createMockAgentState() - const mockLogger = createMockLogger() - - const generator = defaultPicker.handleSteps!({ - agentState: mockAgentState, - logger: mockLogger as any, - prompt: 'search', - params: {}, + ), + ]) { + expect(picker([pair], scope)).toMatchObject({ + files: [], + retrieval: { status: 'failed' }, }) - - generator.next() - - // 15 candidate paths — should be capped to 8. - const fifteenPaths = Array.from( - { length: 15 }, - (_, i) => `src/file${i}.ts`, - ).join('\n') - const mockToolResult = { - agentState: createMockAgentState(), - toolResult: [ - { - type: 'json' as const, - value: [ - { - agentName: 'File Lister', - agentType: 'file-lister', - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [{ type: 'text', text: fifteenPaths }], - }, - ], - }, - }, - ], - }, - ], - stepsComplete: true, - } - - const result = generator.next(mockToolResult) - - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - expect(toolCall.input.files).toHaveLength(8) - }) + } }) - describe('serialization', () => { - test('handleSteps can be serialized for default mode', () => { - const defaultPicker = createFilePicker() - const handleStepsString = defaultPicker.handleSteps!.toString() - - expect(handleStepsString).toMatch(/^function\*\s*\(/) - - const isolatedFunction = new Function(`return (${handleStepsString})`)() - expect(typeof isolatedFunction).toBe('function') - }) - - test('serialized default handleSteps does not reference closure helpers', () => { - const defaultPicker = createFilePicker() - const isolatedFunction = new Function( - `return (${defaultPicker.handleSteps!.toString()})`, - )() - const generator = isolatedFunction({ - agentState: createMockAgentState(), - logger: createMockLogger(), - params: {}, - }) - - generator.next() - const result = generator.next({ - agentState: createMockAgentState(), - toolResult: [ + test('downlevel typed and text paths are bounded, scoped, and explicitly unverified', () => { + const output = picker( + [ + { + value: message( + 'Files:\n- `files/example.ts`\n- files/Dockerfile\n- files/été notes\n- ../escape.ts\n- /tmp/outside.ts\n- files-extra/leak.ts', + ), + }, + ], + ['files'], + ) + expect(output).toMatchObject({ + files: [ + { path: 'files/example.ts', basis: 'legacy' }, + { path: 'files/Dockerfile', basis: 'legacy' }, + { path: 'files/été notes', basis: 'legacy' }, + ], + retrieval: { + status: 'partial', + observations: [ { - type: 'json' as const, - value: [ - { - value: { - type: 'lastMessage', - value: [ - { - role: 'assistant', - content: [{ type: 'text', text: 'src/isolated.ts' }], - }, - ], - }, - }, - ], + source: 'legacy', + status: 'unknown', + reasons: ['unverified_paths'], }, ], - stepsComplete: true, - }) - - const toolCall = result.value as ToolCall<'set_output'> - expect(toolCall.toolName).toBe('set_output') - expect( - toolCall.input.files.map((file: { path: string }) => file.path), - ).toEqual(['src/isolated.ts']) - }) - }) - - describe('system prompt', () => { - test('contains file tree placeholder', () => { - expect(filePicker.systemPrompt).toContain('{CODEBUFF_FILE_TREE_PROMPT}') - }) - - test('describes file finding purpose', () => { - expect(filePicker.systemPrompt).toContain('finding') - }) - }) - - describe('instructions prompt', () => { - test('asks for short report', () => { - expect(filePicker.instructionsPrompt).toContain('short report') - }) - - test('requests full paths', () => { - expect(filePicker.instructionsPrompt).toContain('full path') - }) - - test('instructs not to use tools', () => { - expect(filePicker.instructionsPrompt).toContain('Do not use') - expect(filePicker.instructionsPrompt).toContain('set_output') - expect(filePicker.instructionsPrompt).toContain('files') - }) - }) - - describe('spawner prompt', () => { - test('mentions finding relevant files', () => { - expect(filePicker.spawnerPrompt).toContain('relevant files') - }) - - test('mentions up to 8 file paths', () => { - expect(filePicker.spawnerPrompt).toContain('8') - }) - - test('mentions fuzzy search', () => { - expect(filePicker.spawnerPrompt).toContain('fuzzy') - }) - }) - - describe('extractErrorMessage', () => { - test('extracts message from error result', () => { - expect( - extractErrorMessage({ type: 'error', message: 'Something failed' }), - ).toBe('Something failed') - }) - - test('falls back to value if no message', () => { - expect(extractErrorMessage({ type: 'error', value: 'Error value' })).toBe( - 'Error value', - ) - }) - - test('returns null for non-error types', () => { - expect(extractErrorMessage({ type: 'lastMessage', value: [] })).toBeNull() - }) - - test('returns null for null input', () => { - expect(extractErrorMessage(null)).toBeNull() + }, + }) + expect( + picker( + [ + child({ + type: 'structuredOutput', + value: { files: [{ path: 'files/Makefile' }] }, + }), + ], + ['files'], + ), + ).toMatchObject({ + files: [{ path: 'files/Makefile', basis: 'legacy' }], + retrieval: { status: 'partial' }, + }) + expect(picker([child(message('Files:'))])).toMatchObject({ + files: [], + retrieval: { status: 'unavailable' }, }) }) }) diff --git a/agents/__tests__/gate-aux-triggers.test.ts b/agents/__tests__/gate-aux-triggers.test.ts index 622f664178..5a66838839 100644 --- a/agents/__tests__/gate-aux-triggers.test.ts +++ b/agents/__tests__/gate-aux-triggers.test.ts @@ -52,6 +52,7 @@ type InlineFunctionName = | 'inferWorkspaceRootFromPath' | 'isAlnumChar' | 'basenameContainsSensitiveName' + | 'isReviewableGateFile' // Minimal structural stand-in for Base2ActiveWorkState fields the inline // functions touch. Constructed in tests via a local factory; never imported @@ -90,6 +91,7 @@ const INLINE_FUNCTION_NAMES: InlineFunctionName[] = [ 'selectProjectAwareTestWriterTargets', 'isPublicApiSourceFile', 'selectDocWriterTargets', + 'isReviewableGateFile', 'selectAuxRelevantFiles', 'detectPendingGateFileSetChange', 'resetAuxGateFlags', @@ -301,7 +303,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['packages/sdk/src/run.ts'], - testCommand: 'cd packages/sdk && bun run typecheck && bun test', + testCommand: 'bun test', candidateTests: [], packageRoot: 'packages/sdk', }, @@ -315,7 +317,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['agents/git-committer/git-committer.ts'], - testCommand: 'cd agents && bun run typecheck && bun test', + testCommand: 'bun run test', candidateTests: [], packageRoot: 'agents', }, @@ -329,7 +331,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['common/src/tools/list.ts'], - testCommand: 'cd common && bun run typecheck && bun test', + testCommand: 'bun run test', candidateTests: [], packageRoot: 'common', }, @@ -343,7 +345,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['cli/src/components/foo.tsx'], - testCommand: 'cd cli && bun run typecheck && bun test', + testCommand: 'bun run test', candidateTests: [], packageRoot: 'cli', }, @@ -380,7 +382,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['packages/sdk/src/run.ts'], - testCommand: 'cd packages/sdk && bun run typecheck && bun test', + testCommand: 'bun test', candidateTests: [], packageRoot: 'packages/sdk', }, @@ -394,7 +396,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([]) }) - test('groups mixed packages by their own validation command', () => { + test('groups mixed packages by workspace and validation command', () => { const result = helpers.selectTestWriterTargets([ 'packages/sdk/src/run.ts', 'cli/src/chat.tsx', @@ -402,13 +404,13 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['packages/sdk/src/run.ts'], - testCommand: 'cd packages/sdk && bun run typecheck && bun test', + testCommand: 'bun test', candidateTests: [], packageRoot: 'packages/sdk', }, { targetFiles: ['cli/src/chat.tsx'], - testCommand: 'cd cli && bun run typecheck && bun test', + testCommand: 'bun run test', candidateTests: [], packageRoot: 'cli', }, @@ -430,7 +432,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['packages/sdk/src/run.ts'], - testCommand: 'cd packages/sdk && bun run typecheck && bun test', + testCommand: 'bun test', candidateTests: [], packageRoot: 'packages/sdk', }, @@ -463,7 +465,7 @@ describe('gate-aux-triggers', () => { expect(result.groups).toEqual([ { targetFiles: ['packages/sdk/src/run.ts'], - testCommand: 'cd packages/sdk && bun run typecheck && bun test', + testCommand: 'bun test', candidateTests: ['packages/sdk/src/__tests__/run.test.ts'], manifest: 'packages/sdk/package.json', packageRoot: 'packages/sdk', diff --git a/agents/__tests__/gate-changed-files.test.ts b/agents/__tests__/gate-changed-files.test.ts index c238333d31..9e30c10930 100644 --- a/agents/__tests__/gate-changed-files.test.ts +++ b/agents/__tests__/gate-changed-files.test.ts @@ -109,7 +109,7 @@ describe('serialized base2 changed-file helpers', () => { { type: 'tool-call', toolName: 'str_replace', - input: { path: './src/a.ts' }, + input: { path: './src/attempt-only.ts' }, }, { type: 'tool-call', @@ -135,6 +135,7 @@ describe('serialized base2 changed-file helpers', () => { { role: 'tool', toolName: 'edit_transaction', + toolCallId: 'gate-all:call', content: [ { type: 'json', @@ -188,6 +189,7 @@ describe('serialized base2 changed-file helpers', () => { { role: 'tool', toolName: 'write_file', + toolCallId: 'failed-write', content: [ { type: 'json', @@ -202,6 +204,7 @@ describe('serialized base2 changed-file helpers', () => { { role: 'tool', toolName: 'write_file', + toolCallId: 'gate-ok:call', content: [ { type: 'json', diff --git a/agents/__tests__/gate-files.test.ts b/agents/__tests__/gate-files.test.ts index 5b6075f005..2943a0787a 100644 --- a/agents/__tests__/gate-files.test.ts +++ b/agents/__tests__/gate-files.test.ts @@ -244,41 +244,42 @@ describe('collectToolInputFiles', () => { }) describe('collectAgentReceiptChangedFiles', () => { - test('collects string and {path} items from a schemaVersion=1 receipt', () => { + test('ignores legacy string and path-only summaries without a native envelope', () => { const record = { schemaVersion: 1, receiptId: 'r1', changedFiles: ['src/a.ts', { path: 'src/b.ts' }], } - expect(collectReceipt(record)).toEqual(['src/a.ts', 'src/b.ts']) + expect(collectReceipt(record)).toEqual([]) }) test('drops blank-string and non-path items', () => { const record = { - schemaVersion: 1, - receiptId: 'r2', - changedFiles: [' ', { path: 'src/b.ts' }, { file: 'nope' }, 42], + result: {}, + agentReceipt: { schemaVersion: 1, receiptId: 'r2', changedFiles: [ + ' ', { path: 'src/b.ts', mutationReceiptId: 'native-b' }, { file: 'nope' }, 42, + ] }, } expect(collectReceipt(record)).toEqual(['src/b.ts']) }) test('collects from a nested agentReceipt.changedFiles', () => { const record = { - agentId: 'aux-1', + agentId: 'aux-1', agentName: 'Editor', agentType: 'editor', value: {}, agentReceipt: { schemaVersion: 1, receiptId: 'r3', - changedFiles: [{ path: 'src/c.ts' }, 'src/d.ts'], + changedFiles: [{ path: 'src/c.ts', mutationReceiptId: 'native-c' }, 'src/d.ts'], }, } - expect(collectReceipt(record)).toEqual(['src/c.ts', 'src/d.ts']) + expect(collectReceipt(record)).toEqual(['src/c.ts']) }) - test('collects from a nested agentReceipt that omits schemaVersion', () => { + test('rejects a nested agentReceipt that omits schemaVersion', () => { const record = { - agentReceipt: { changedFiles: ['src/e.ts', { path: 'src/f.ts' }] }, + result: {}, agentReceipt: { changedFiles: ['src/e.ts', { path: 'src/f.ts', mutationReceiptId: 'native-f' }] }, } - expect(collectReceipt(record)).toEqual(['src/e.ts', 'src/f.ts']) + expect(collectReceipt(record)).toEqual([]) }) test('collects nothing from records without changedFiles or receipts', () => { @@ -336,12 +337,10 @@ describe('visitToolValue', () => { expect(collectVisited(receipt)).toEqual([]) }) - test('collects action paths nested inside a json envelope', () => { + test('collects a native action carried directly inside a json envelope', () => { const value = { type: 'json', - value: { - nested: [editReceipt('src/d.ts')], - }, + value: editReceipt('src/d.ts'), } expect(collectVisited(value)).toEqual(['src/d.ts']) }) diff --git a/agents/__tests__/gate-fingerprint-parity.test.ts b/agents/__tests__/gate-fingerprint-parity.test.ts index 935b7e7168..8b6021a2c6 100644 --- a/agents/__tests__/gate-fingerprint-parity.test.ts +++ b/agents/__tests__/gate-fingerprint-parity.test.ts @@ -91,6 +91,13 @@ describe('gate-fingerprint helpers — inline copies match canonical exports', ( } }) + test('cannot attest an unreadable file marker in a gate snapshot', () => { + const details = 'files-v4\nsrc/a.ts\tunreadable:outside-project-symlink\n--\n' + const inline = loadInlineGateFingerprintHelpers() + expect(isAttestableSnapshotFingerprint(hashGateSnapshotDetails(details))).toBe(false) + expect(inline.hashGateSnapshotDetails(details)).toBe(hashGateSnapshotDetails(details)) + }) + test('hashGateSnapshotDetails parity with crypto available', () => { const inlineHelpers = loadInlineGateFingerprintHelpers() diff --git a/agents/__tests__/general-agent.test.ts b/agents/__tests__/general-agent.test.ts index fb603d10e3..cc619df2a0 100644 --- a/agents/__tests__/general-agent.test.ts +++ b/agents/__tests__/general-agent.test.ts @@ -2,6 +2,17 @@ import { describe, expect, test } from 'bun:test' import { createGeneralAgent } from '../general-agent/general-agent' +function scopedAuditToolObservation(snapshotId = 'snapshot-1') { + const contentHash = `sha256:${'a'.repeat(64)}` + return { role: 'tool', toolName: 'write_audit_findings', toolCallId: 'native-audit-write', content: [{ + type: 'json', value: { artifactPath: '.agents/sessions/readiness/findings/services.md', contentHash, + structuralReceipt: { schema_version: 1, snapshot_id: snapshotId, shard_id: 'services', + subsystem_ids: ['services'], files: ['src/services.ts'], domains: ['runtime'], + artifact: { session_slug: 'readiness', content_hash: contentHash } }, + }, + }] } +} + describe('general-agent programmatic tools', () => { test('declares the hidden context-pruner tool used by handleSteps', () => { const agent = createGeneralAgent({ model: 'opus' }) @@ -25,26 +36,184 @@ describe('general-agent programmatic tools', () => { expect(agent.programmaticToolNames).toContain('spawn_agent_inline') }) - test('routes directory-like bootstrap paths through read_subtree', () => { + test('reads concrete paths exactly and only inventories proven legacy directories', () => { const agent = createGeneralAgent({ model: 'opus' }) const generator = agent.handleSteps!({ - prompt: 'Audit the server subsystem', params: { - filePaths: ['server/src/services', 'server/src/worker.ts'], - directoryPaths: ['server/src/integrations'], + filePaths: [ + '.gitignore', + 'scripts/run', + 'server.v2', + 'missing', + '../escape', + 'large.ts', + ], + directoryPaths: ['server/integrations'], }, } as any) - - expect(generator.next().value).toEqual({ + const result = (value: unknown) => + ({ toolResult: [{ type: 'json', value }] }) as any + expect(generator.next().value).toMatchObject({ + toolName: 'read_files', + input: { + paths: [ + '.gitignore', + 'scripts/run', + 'server.v2', + 'missing', + 'large.ts', + ], + }, + }) + expect( + generator.next( + result({ + kind: 'read_files_result', + version: 1, + results: [ + { + path: '.gitignore', + selector: 'file', + status: 'ok', + complete: true, + content: 'build/\n', + }, + { + path: 'scripts/run', + selector: 'file', + status: 'ok', + complete: true, + content: '#!/bin/sh\n', + }, + { + path: 'server.v2', + selector: 'file', + status: 'error', + error: { code: 'io_error' }, + }, + { + path: 'missing', + selector: 'file', + status: 'error', + error: { code: 'not_found' }, + }, + { + path: 'large.ts', + selector: 'file', + status: 'partial', + content: 'truncated', + }, + { + path: 'large.ts', + selector: 'window', + status: 'ok', + content: 'only one window', + }, + ], + }), + ).value, + ).toMatchObject({ + toolName: 'read_subtree', + input: { mode: 'stat', paths: ['server.v2'] }, + }) + const directory = (path: string, mode: string, status = 'complete') => ({ + path, + type: 'directory', + inventory: { + kind: 'read_subtree_inventory', + version: 1, + mode, + pathBasis: 'project-relative', + rootPath: path, + provenance: 'live', + status, + }, + }) + expect( + generator.next(result([directory('server.v2', 'stat')])).value, + ).toMatchObject({ toolName: 'read_subtree', + input: { mode: 'paths', paths: ['server/integrations', 'server.v2'] }, + }) + const notice = generator.next( + result([ + directory('server/integrations', 'paths', 'partial'), + directory('server.v2', 'paths'), + ]), + ).value + expect(notice).toMatchObject({ toolName: 'add_message' }) + expect(generator.next({} as any).value).toMatchObject({ + toolName: 'spawn_agent_inline', + }) + expect(generator.next({} as any).value).toBe('STEP') + expect( + generator.next({ + stepsComplete: true, + agentState: { output: { summary: 'Answer' } }, + } as any).value, + ).toMatchObject({ + toolName: 'set_output', input: { - paths: ['server/src/integrations', 'server/src/services'], - maxTokens: 10_000, + summary: 'Answer', + preRead: { + version: 1, + status: 'partial', + entries: expect.arrayContaining([ + { path: '.gitignore', requestedAs: 'file', status: 'read' }, + { path: 'scripts/run', requestedAs: 'file', status: 'read' }, + { + path: 'server.v2', + requestedAs: 'file', + status: 'inventoried', + reason: 'legacy_directory', + }, + { + path: 'server/integrations', + requestedAs: 'directory', + status: 'partial', + reason: 'partial_inventory', + }, + { + path: '../escape', + requestedAs: 'file', + status: 'omitted', + reason: 'outside_project', + }, + { + path: 'missing', + requestedAs: 'file', + status: 'omitted', + reason: 'not_found', + }, + { + path: 'large.ts', + requestedAs: 'file', + status: 'partial', + reason: 'truncated', + }, + ]), + }, }, }) - expect(generator.next({ toolResult: [] } as any).value).toEqual({ + }) + + test('caps bootstrap attempts at 16 and reports each over-budget path', () => { + const filePaths = Array.from({ length: 17 }, (_, index) => `file-${index}`) + const generator = createGeneralAgent({ model: 'opus' }).handleSteps!({ + params: { filePaths }, + } as any) + expect(generator.next().value).toMatchObject({ toolName: 'read_files', - input: { paths: ['server/src/worker.ts'] }, + input: { paths: filePaths.slice(0, 16) }, + }) + const notice = generator.next({ toolResult: [] } as any).value + expect(notice).toMatchObject({ + toolName: 'add_message', + input: { + content: expect.stringContaining( + '"path":"file-16","requestedAs":"file","status":"omitted","reason":"path_limit"', + ), + }, }) }) @@ -129,21 +298,17 @@ describe('general-agent programmatic tools', () => { }) expect(generator.next({ toolResult: [] } as any).value).toBe('STEP') + const observed = generator.next({ + stepsComplete: false, + agentState: { messageHistory: [scopedAuditToolObservation()] }, + toolResult: [], + } as any) + expect(observed.value).toBe('STEP') + // The native observation remains useful even if its body was compacted + // out of the subsequent step's history before the final task completion. const completion = generator.next({ stepsComplete: true, - agentState: { - messageHistory: [ - { - role: 'tool', - content: [ - { - type: 'json', - value: { structuralReceipt: { snapshot_id: 'snapshot-1' } }, - }, - ], - }, - ], - }, + agentState: { messageHistory: [] }, toolResult: [], } as any) @@ -159,7 +324,7 @@ describe('general-agent programmatic tools', () => { expect((afterHarvest.value as any)?.toolName).not.toBe('add_message') }) - test('clears the audit gate for receipts nested deeper than the old mirror cap', () => { + test('rejects receipts buried in unsupported wrappers, even on the native tool', () => { const agent = createGeneralAgent({ model: 'opus' }) const generator = agent.handleSteps!({ prompt: 'Audit service completeness', @@ -175,13 +340,8 @@ describe('general-agent programmatic tools', () => { }) expect(generator.next({ toolResult: [] } as any).value).toBe('STEP') - // A receipt nested 20 wrapper objects deep exceeds the old 8-level inline - // mirror cap but stays within the canonical containsStructuralAuditReceipt - // MAX_TRAVERSAL_DEPTH (32) that backs the runtime receipt gate, so the - // agent-level gate must also clear it — the two gates must not drift. - let deeplyNested: unknown = { - structuralReceipt: { snapshot_id: 'snapshot-1' }, - } + const native = scopedAuditToolObservation() + let deeplyNested: unknown = native.content[0]!.value for (let i = 0; i < 20; i++) { deeplyNested = { nested: deeplyNested } } @@ -191,7 +351,7 @@ describe('general-agent programmatic tools', () => { agentState: { messageHistory: [ { - role: 'tool', + ...native, content: [{ type: 'json', value: deeplyNested }], }, ], @@ -199,14 +359,10 @@ describe('general-agent programmatic tools', () => { toolResult: [], } as any) - expect(completion.done).toBe(false) expect(completion.value).toMatchObject({ - toolName: 'set_output', - input: { harvestedFromFallback: true }, + toolName: 'add_message', + input: { content: expect.stringContaining('Audit completion was rejected') }, }) - const afterHarvest = generator.next({ toolResult: [] } as any) - expect(afterHarvest.done).toBe(true) - expect((afterHarvest.value as any)?.toolName).not.toBe('add_message') }) test('keeps rejecting when the present receipt is for a different snapshot', () => { @@ -696,7 +852,7 @@ describe('general-agent programmatic tools', () => { expect(agent.instructionsPrompt).not.toContain('-2') }) - test('breaks the audit loop on an already-persisted collision result', () => { + test('requires a canonical structural acknowledgment rather than an already-persisted collision marker', () => { const agent = createGeneralAgent({ model: 'opus' }) const artifactPath = '.agents/sessions/readiness/findings/services.md' const generator = agent.handleSteps!({ @@ -713,10 +869,7 @@ describe('general-agent programmatic tools', () => { }) expect(generator.next({ toolResult: [] } as any).value).toBe('STEP') - // The artifact is created exclusively, so this rejection means the shard's - // findings are already durably on disk. There is no structuralReceipt in - // this history, so without the snapshot-bound already-persisted marker the - // gate would burn both retries and exit partial. + // A legacy marker signals a collision; it is not a composable scoped receipt. const completion = generator.next({ stepsComplete: true, agentState: { @@ -744,15 +897,10 @@ describe('general-agent programmatic tools', () => { toolResult: [], } as any) - // No add_message retry: the gate cleared, so the only remaining yield is - // the always-on harvest. expect(completion.value).toMatchObject({ - toolName: 'set_output', - input: { harvestedFromFallback: true }, + toolName: 'add_message', + input: { content: expect.stringContaining('Audit completion was rejected') }, }) - const afterHarvest = generator.next({ toolResult: [] } as any) - expect(afterHarvest.done).toBe(true) - expect((afterHarvest.value as any)?.toolName).not.toBe('add_message') }) test('keeps rejecting an already-persisted marker for a different snapshot', () => { @@ -1005,9 +1153,9 @@ describe('general-agent programmatic tools', () => { agent: ReturnType, ) => // eslint-disable-next-line no-new-func -- reproduces the runtime sandbox - new Function( - 'return (' + String(agent.handleSteps) + ')', - )() as (args: unknown) => Generator + new Function('return (' + String(agent.handleSteps) + ')')() as ( + args: unknown, + ) => Generator test('serialized handleSteps clears the audit gate on a snapshot-bound receipt', () => { const agent = createGeneralAgent({ model: 'opus' }) @@ -1025,30 +1173,11 @@ describe('general-agent programmatic tools', () => { }) expect(generator.next({ toolResult: [] } as any).value).toBe('STEP') - // A write_audit_findings tool result embedding a snapshot-bound receipt: - // the gate must pass without any ReferenceError, so the next yield is the - // ordinary harvest fallback rather than an add_message nudge. + // A native write_audit_findings result with the exact scoped receipt + // remains recognized by the serialized generator. const completion = generator.next({ stepsComplete: true, - agentState: { - messageHistory: [ - { - role: 'tool', - content: [ - { - type: 'json', - value: { - structuralReceipt: { - schema_version: 1, - snapshot_id: 'snapshot-1', - shard_id: 'services', - }, - }, - }, - ], - }, - ], - }, + agentState: { messageHistory: [scopedAuditToolObservation()] }, toolResult: [], } as any) diff --git a/agents/__tests__/new-bundled-agents.test.ts b/agents/__tests__/new-bundled-agents.test.ts index 2f5afb5212..8d325c8012 100644 --- a/agents/__tests__/new-bundled-agents.test.ts +++ b/agents/__tests__/new-bundled-agents.test.ts @@ -1,6 +1,5 @@ import { describe, expect, test } from 'bun:test' -import { shouldRunBrowserUseAgentTest } from '../browser-use/browser-use.test' import debuggerAgent from '../debugger/debugger' import docWriter from '../doc-writer/doc-writer' import { shouldRunLibrarianAgentTest } from '../librarian/librarian.test' @@ -141,16 +140,18 @@ describe('new bundled agents (M2.6)', () => { expect(debuggerAgent.model).toBeUndefined() }) - test('exposes read + terminal + git tools', () => { + test('exposes read and git tools but hides deterministic terminal execution', () => { const tools = debuggerAgent.toolNames ?? [] expect(tools).toContain('read_files') - expect(tools).toContain('run_terminal_command') + expect(tools).not.toContain('run_terminal_command') + expect(debuggerAgent.programmaticToolNames).toContain('run_terminal_command') + expect(debuggerAgent.terminalPermissionProfile).toBe('validation-diagnosis') expect(tools).toContain('git_status') }) test('instructions prompt mentions root cause + does not apply fix', () => { const p = debuggerAgent.instructionsPrompt ?? '' - expect(p).toContain('Root cause') + expect(p.toLowerCase()).toContain('root cause') expect(p.toLowerCase()).toContain('do not') }) }) @@ -178,22 +179,6 @@ describe('new bundled agents (M2.6)', () => { }) describe('opt-in E2E test scripts', () => { - test('browser-use script is skipped unless explicitly enabled', () => { - expect(shouldRunBrowserUseAgentTest({}, true)).toBe(false) - expect( - shouldRunBrowserUseAgentTest( - { OPENBUFF_RUN_BROWSER_USE_AGENT_TEST: '1' }, - false, - ), - ).toBe(false) - expect( - shouldRunBrowserUseAgentTest( - { OPENBUFF_RUN_BROWSER_USE_AGENT_TEST: '1' }, - true, - ), - ).toBe(true) - }) - test('librarian script is skipped unless explicitly enabled', () => { expect(shouldRunLibrarianAgentTest({}, true)).toBe(false) expect( diff --git a/agents/__tests__/quality-prompt-snapshot.test.ts b/agents/__tests__/quality-prompt-snapshot.test.ts index 8e4748191c..be9eac6978 100644 --- a/agents/__tests__/quality-prompt-snapshot.test.ts +++ b/agents/__tests__/quality-prompt-snapshot.test.ts @@ -272,7 +272,7 @@ describe('shared craftsmanship prompt sections', () => { const editor = createCodeEditor({ model: 'opus' }) expect(base2.systemPrompt).toContain(qualitySection) - expect(base2.systemPrompt).toContain(PLACEHOLDER.FRONTEND_SECTION) + expect(base2.systemPrompt).not.toContain(PLACEHOLDER.FRONTEND_SECTION) expect(base2.programmaticConfig?.base2TurnContext).toBe(true) expect(base2.systemPrompt).not.toContain(PLACEHOLDER.LANGUAGE_PROFILE) expect(base2.systemPrompt).not.toContain(frontendSection) diff --git a/agents/__tests__/roster-drift.test.ts b/agents/__tests__/roster-drift.test.ts index 367a5b0bfa..0f6278b73f 100644 --- a/agents/__tests__/roster-drift.test.ts +++ b/agents/__tests__/roster-drift.test.ts @@ -90,6 +90,7 @@ function getAllTsFiles(dir: string): string[] { // The canonical set of shipped bundled agent ids, derived from the same scan // the prebuild uses. Populated in beforeAll because the collection is async. const shippedIds = new Set() +const shippedSourcePaths: string[] = [] // Union of every id spawnable via an orchestrator/pattern spawnable set. const reachableViaOrchestrator = new Set() @@ -99,8 +100,11 @@ beforeAll(async () => { try { const module = await import(fullPath) const id = module.default?.id - if (typeof id === 'string') { + if (typeof id === 'string' && id.length > 0) { shippedIds.add(id) + shippedSourcePaths.push( + path.relative(agentsRoot, fullPath).split(path.sep).join('/'), + ) } } catch { // Match prebuild's tolerant behavior: an unrelated non-agent .ts file @@ -123,6 +127,13 @@ beforeAll(async () => { }) describe('roster drift guard', () => { + test('the explicit eval entrypoints match the source files admitted by prebuild', () => { + const entrypoints = JSON.parse( + fs.readFileSync(path.join(agentsRoot, 'agent-entrypoints.json'), 'utf8'), + ) + expect([...entrypoints].sort()).toEqual([...shippedSourcePaths].sort()) + }) + test('routes.json references only shipped or allowlisted agents', () => { const routesPath = path.join( agentsRoot, diff --git a/agents/__tests__/spawn-contract.test.ts b/agents/__tests__/spawn-contract.test.ts index 8bf2e498ef..449851c0b1 100644 --- a/agents/__tests__/spawn-contract.test.ts +++ b/agents/__tests__/spawn-contract.test.ts @@ -14,10 +14,8 @@ import dependencyManager from '../dependency-manager/dependency-manager' import generalAgent from '../general-agent/general-agent' import librarian from '../librarian/librarian' -// The retired hand-written paragraph from base2's system prompt (D17). The -// derived builder must reproduce it byte-for-byte, so pin it here and assert -// equality — a drifting fallback clause fails here without touching any prompt -// snapshot. +// Frozen spawn contract. The inherited clauses remain byte-for-byte; the +// scoped tmux playback clause intentionally follows its new required parameters. const EXPECTED_SPAWN_CONTRACT_PARAGRAPH = [ 'basher needs `params.command` (a shell string)', 'general-agent needs prompt + params.filePaths/directoryPaths (not files)', @@ -25,6 +23,7 @@ const EXPECTED_SPAWN_CONTRACT_PARAGRAPH = [ 'dependency-manager needs params.manager+params.operation from manifest evidence', 'architect/advisory needs prompt+files (snapshot_id optional)', 'reviewer-family manual spawns omit params.snapshot_id (security-reviewer needs changed_files+snapshot_fingerprint)', + 'tmux-cli needs params.argv (array), params.expect (string)', ].join('; ') type InputParamsLike = { @@ -80,7 +79,7 @@ describe('base2 spawn contract (D17)', () => { expect(first.programmaticToolNames).not.toBe(second.programmaticToolNames) }) - test('derived clause emission is byte-identical to the retired prose', () => { + test('derived clause emission matches the pinned spawn contract', () => { expect(buildSpawnContractClauses()).toBe(EXPECTED_SPAWN_CONTRACT_PARAGRAPH) }) diff --git a/agents/__tests__/specialist-risk-router.test.ts b/agents/__tests__/specialist-risk-router.test.ts index 2ae480a242..6637fd5980 100644 --- a/agents/__tests__/specialist-risk-router.test.ts +++ b/agents/__tests__/specialist-risk-router.test.ts @@ -3,6 +3,20 @@ import { describe, expect, test } from 'bun:test' import { selectSpecialistReviewers } from '../base2/specialist-risk-router' describe('specialist risk router', () => { + test('routes a SQL artifact regardless of ordering or accompanying requirements', () => { + expect(selectSpecialistReviewers({ + files: ['.github/workflows/ci.yml'], + })).toEqual(['dependency-reviewer']) + expect(selectSpecialistReviewers({ + files: ['ops/check.sql', 'src/main.ts'], + requirements: 'Verify the change.', + })).toEqual(['migration-reviewer']) + }) + + test('does not confuse a generic regression with performance risk', () => { + expect(selectSpecialistReviewers({ files: ['src/main.ts'], requirements: 'Fix the regression.' })).toEqual([]) + expect(selectSpecialistReviewers({ files: ['src/main.ts'], requirements: 'Fix the latency regression.' })).toEqual(['performance-specialist']) + }) test('defaults omitted requirements to empty instead of throwing', () => { expect(selectSpecialistReviewers({ files: [] })).toEqual([]) expect( diff --git a/agents/__tests__/specialists.test.ts b/agents/__tests__/specialists.test.ts index 792682d05c..ccfeec54a4 100644 --- a/agents/__tests__/specialists.test.ts +++ b/agents/__tests__/specialists.test.ts @@ -70,6 +70,16 @@ describe('specialist agents', () => { ) }) + test('routed reviewer templates provide evidence rules and no terminal authority', () => { + for (const agent of specialists.filter((candidate) => candidate.outputSchema?.required?.includes('verdict'))) { + expect(agent.toolNames).not.toContain('run_terminal_command') + expect(agent.inheritParentSystemPrompt).toBe(false) + expect(agent.instructionsPrompt).toContain('assertion that would fail') + } + expect(architect.instructionsPrompt).toContain('Worked advisory example') + expect(architect.instructionsPrompt).not.toContain('"verdict": "LOOKS_GOOD"') + }) + test('remain read-only even when diagnostic terminal access is enabled', () => { for (const agent of specialists) { expect(agent.toolNames).not.toContain('write_file') diff --git a/agents/__tests__/tmux-cli.test.ts b/agents/__tests__/tmux-cli.test.ts index d11ba322b6..8aedb0e0ed 100644 --- a/agents/__tests__/tmux-cli.test.ts +++ b/agents/__tests__/tmux-cli.test.ts @@ -1,185 +1,108 @@ import { describe, expect, test } from 'bun:test' -import { execFileSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' import tmuxCli from '../tmux-cli' -// SB-5: the tmux-cli agent writes a self-contained bash helper to /tmp, drives -// it through run_terminal_command, and tears the session + helper down in a -// finally block. A stray `'>` in the teardown command previously turned it into -// a bash parse error, so `stop`/`rm -f` never ran (the P0-T3 fix removed it). -// These tests run `bash -n` (parse-only, no execution) over the exact command -// bytes the agent emits, so any future re-introduction of a shell syntax error -// in the helper, the setup wrapper, or the teardown command fails loudly here -// instead of silently leaking tmux sessions/helper files at runtime. +const logger = { debug() {}, info() {}, warn() {}, error() {} } +const params = { argv: ['bun', './fixture.ts', 'argument with spaces'], cwd: 'packages/my app', expect: 'READY' } +const handle = new Function(`return (${tmuxCli.handleSteps!.toString()})`)() as NonNullable +const json = (value: unknown) => [{ type: 'json', value }] as never -const noopLogger = { - debug: () => {}, - info: () => {}, - warn: () => {}, - error: () => {}, +function drive(input: Record = params) { + const agentState = {} as never + const gen = handle({ params: input, agentState, logger }) + return { first: gen.next().value, next: (toolResult?: never) => gen.next({ agentState, toolResult, stepsComplete: false }).value } } -// bash availability guard: the parse-only checks need a real bash. Skip (rather -// than error) on the rare host without one so the suite stays green off-CI. -const hasBash = (() => { - try { - execFileSync('bash', ['-c', 'true'], { stdio: 'ignore' }) - return true - } catch { - return false - } -})() - -/** - * Run `bash -n `, { + headers: { 'content-type': 'text/html', 'cache-control': 'no-store' }, + }) + } }) + return { + origin: `http://127.0.0.1:${site.port}`, deniedUrl, requests, + deniedRequests: () => deniedRequests, + close: async () => { await Promise.all([site.stop(true), denied.stop(true)]) }, + } +} + +export type BrowserSmokeDispatch = (action: BrowserAction, signal?: AbortSignal) => Promise + +export function makeBrowserSmokeDispatch(options: { + origin: string + executablePath: string + spawn?: CodebuffSpawn + planOnly?: boolean + degraded?: boolean + cacheScope?: object +}) { + const fixture = executionFixture() + const owner: BrowserSessionOwner = { + clientSessionId: randomUUID(), rootRunId: 'p57-smoke', parentRunId: 'p57-smoke', parentAgentId: 'browser-use', + } + const policy = captureBrowserHostPolicy({ + OPENBUFF_BROWSER_INTERACTION_ORIGINS: options.origin, + OPENBUFF_BROWSER_SANDBOX: options.degraded ? 'degraded' : undefined, + }, options.planOnly) + const dispatch: BrowserSmokeDispatch = async (action, signal) => { + const result = await browserLogs(action, owner, { + ...fixture.context(signal), resources: fixture.resources, policy, + executablePath: options.executablePath, spawn: options.spawn, + cacheScope: options.cacheScope ?? fixture.context().cacheScope, + }) + const response = result.find(part => part.type === 'json')?.value + assert(response, 'No native browser result') + return response + } + return { dispatch, close: async () => { + try { await dispatch({ type: 'stop' }) } finally { fixture.close() } + } } +} + +export function requireBrowserSmokeEvidence( + diagnostic: BrowserResponse, + stopped: BrowserResponse, +) { + assert(diagnostic.success && diagnostic.sandbox?.status === 'verified', + `Required browser steps or sandbox withheld: ${diagnostic.failure ?? diagnostic.sandbox?.status ?? 'missing'} (${diagnostic.error ?? 'no details'})`) + const result = diagnostic.result as { results?: Array<{ label?: string; passed?: boolean; response?: BrowserResponse }>; passedSteps?: number; skippedSteps?: number; omittedMedia?: number } | undefined + const labels = ['ready', 'click', 'confirmed', 'capture'] + assert(result && result.passedSteps === labels.length && result.skippedSteps === 0 && result.omittedMedia === 0, 'Missing required diagnostic steps or media') + assert.deepEqual(result.results?.map(step => step.label), labels) + const responses = result.results!.map(({ passed, response }) => { + assert(passed && response?.success && response.sandbox?.status === 'verified') + const observation = response.observation + assert(observation?.status === 'complete' && observation.stepId && observation.console.id && observation.network.id) + assert.equal(observation.console.count, response.logs.length) + assert.equal(observation.network.count, response.networkEvents?.length) + assert.equal(observation.console.dropped + observation.network.dropped + observation.network.pending, 0) + return { response, observation } + }) + const [ready, click, confirmed, capture] = responses as [typeof responses[number], typeof responses[number], typeof responses[number], typeof responses[number]] + assert(ready.response.logs.some(log => log.message === readyMarker) && ready.response.networkEvents?.some(event => event.status === 200 && new URL(event.url).pathname === '/'), 'Startup window is missing the expected console message or document response') + assert(click.response.logs.some(log => log.message === doneMarker) && click.response.networkEvents?.some(event => event.status === 200 && new URL(event.url).pathname === '/done'), 'Click window is missing the expected console message or document response') + assert(confirmed.response.title === doneMarker && confirmed.response.url?.endsWith('/done'), 'The required click outcome was not observed') + const ids = responses.flatMap(({ observation }) => [observation.stepId, observation.console.id, observation.network.id]) + assert.equal(new Set(ids).size, labels.length * 3) + assert(responses.every(({ observation }) => observation.sessionId === ready.observation.sessionId && observation.targetId === ready.observation.targetId)) + const artifact = capture.response.artifact + assert(artifact?.mediaType === 'image/png' && capture.response.screenshotAttached) + const bytes = readFileSync(artifact.path) + assert.equal(bytes.length, artifact.bytes) + assert.equal(createHash('sha256').update(bytes).digest('hex'), artifact.sha256) + assert.equal(capture.observation.captureId, `${capture.observation.stepId}:${artifact.sha256}`) + assert(stopped.success && stopped.cleanup?.status === 'confirmed' && stopped.cleanup.id && stopped.cleanup.sessionId === ready.observation.sessionId, 'Cleanup did not confirm the session that produced the evidence') + return { stepIds: responses.map(({ observation }) => observation.stepId), cleanupId: stopped.cleanup.id } +} + +export const smokeSteps = (origin: string): BrowserAction => ({ type: 'diagnose', steps: [ + { label: 'ready', action: { type: 'navigate', url: origin, waitUntil: 'networkidle0' }, expectedLogs: [readyMarker], noJsErrors: true, noNetworkErrors: true }, + { label: 'click', action: { type: 'click', selector: '#run', waitForNavigation: true }, expectedLogs: [doneMarker], noJsErrors: true, noNetworkErrors: true }, + { label: 'confirmed', action: { type: 'wait_for', text: doneMarker, timeout: 1_500 }, noJsErrors: true, noNetworkErrors: true }, + { label: 'capture', action: { type: 'screenshot', screenshotCompression: 'png' }, noJsErrors: true, noNetworkErrors: true }, +] }) + +// Native assertions, if explicitly selected, run only in a loopback-only +// namespace created by the caller. No install, download, provider, or fallback. +if (import.meta.main) { + const executablePath = process.env.P57_CHROME_PATH + const parentNetns = process.env.P57_PARENT_NETNS + if (process.platform !== 'linux' || !executablePath || !path.isAbsolute(executablePath) || !existsSync(executablePath) || + !parentNetns || parentNetns === readlinkSync('/proc/self/ns/net') || Object.keys(networkInterfaces()).some(name => name !== 'lo')) { + console.error('P5.7 native browser smoke unavailable: select an installed Chromium and a separate loopback-only network namespace.') + process.exitCode = 2 + } else { + const scratch = mkdtempSync(path.join(tmpdir(), 'p57-native-')) + const site = startBrowserSmokeSite() + const processes: Array<{ pid?: number; exitCode: () => number | null; signalCode: () => string | null; profile: string }> = [] + const browser = makeBrowserSmokeDispatch({ origin: site.origin, executablePath, spawn: (command, args, options) => { + const child = spawn(command, [...args ?? []], { + ...options, env: { PATH: '/usr/bin:/bin', HOME: scratch, XDG_RUNTIME_DIR: scratch, LANG: 'C.UTF-8' }, + }) + processes.push({ pid: child.pid, exitCode: () => child.exitCode, signalCode: () => child.signalCode, + profile: args?.find(arg => arg.startsWith('--user-data-dir='))?.slice('--user-data-dir='.length) ?? '' }) + return child + } }) + let outcome: BrowserResponse | undefined + try { + outcome = await browser.dispatch(smokeSteps(site.origin)) + const stopped = await browser.dispatch({ type: 'stop' }) + const receipt = requireBrowserSmokeEvidence(outcome, stopped) + assert(site.requests.includes('/') && site.requests.includes('/done'), 'The owned loopback server did not receive both expected requests') + const cleanup = processes.map(proc => ({ pid: proc.pid, exitCode: proc.exitCode(), signalCode: proc.signalCode(), profileRemoved: !!proc.profile && !existsSync(proc.profile) })) + assert(cleanup.length >= 2 && cleanup.every(proc => proc.pid && (proc.exitCode !== null || proc.signalCode !== null) && proc.profileRemoved), + `Chrome probe or session cleanup was not observed: ${JSON.stringify(cleanup)}`) + console.log(JSON.stringify({ status: 'passed', backend: 'native-chromium', ...receipt })) + } catch (error) { + const unavailable = outcome?.failure === 'chrome_missing' || outcome?.failure === 'sandbox_unavailable' || outcome?.failure === 'startup_failed' + console.error(JSON.stringify({ status: unavailable ? 'unavailable' : 'failed', failure: outcome?.failure, error: String(error) })) + process.exitCode = unavailable ? 2 : 1 + } finally { + try { await browser.close() } finally { + await site.close() + rmSync(scratch, { recursive: true, force: true }) + } + } + } +} diff --git a/test/fixtures/body/cli-release-candidate.ts b/test/fixtures/body/cli-release-candidate.ts new file mode 100644 index 0000000000..f306c4676c --- /dev/null +++ b/test/fixtures/body/cli-release-candidate.ts @@ -0,0 +1,450 @@ +import assert from 'node:assert/strict' +import { execFile, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + createReadStream, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + readlinkSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { networkInterfaces } from 'node:os' +import { basename, join } from 'node:path' + +// Linux x64 only. Takes the archive produced by cli-release-build.yml, not +// cli/bin or a PATH lookup. Needs only installed Bun, bubblewrap and userland +// (GNU tar, git, sh). No checkout, node_modules or home mounted in the worker. +// Usage: bun --no-env-file --no-install test/fixtures/body/cli-release-candidate.ts +const worker = '--isolated-worker' +const source = 'src/candidate.ts' +const before = 'export const candidate = 1\n' +const after = 'export const candidate = 2\n' +const prompt = `Change ${source} to export candidate = 2. Keep all other files unchanged.` +const unroutedEditor = 'unmapped-candidate/editor' +const editorBrief = [ + '## Requirements', '- Change candidate from 1 to 2.', + '## Target files', `- ${source}`, + '## Constraints/non-goals', '- Do not change other files or run validation.', + '## Patterns', '- Keep the exported constant.', + '## Risks', '- Do not change the public name or file shape.', +].join('\n') +const caseId = 'candidate-export-equals-2' +// Run a fixed read-only comparison, not an arbitrary shell script that the +// strict headless policy would legitimately refuse without approval. +const hookCommand = `grep -Fx -- '${after.trimEnd()}' ${source}` +// First-run DB, telemetry, and CLI diagnostics are allowed; any other +// untracked path fails the scope check. +const allowedRuntimeFiles = new Set([ + '.openbuff/memory/memory-v2.sqlite', + '.openbuff/memory/memory-v2.sqlite-shm', + '.openbuff/memory/memory-v2.sqlite-wal', + '.openbuff/memory/task-memory.json', + '.openbuff/telemetry/base2-gate.jsonl', + 'debug/cli.jsonl', +]) +const finalText = 'The candidate edit was verified.' +const runDeadlineSeconds = 75 +const cases = ['validated', 'no-hooks', 'missing-child-route'] as const +type Scenario = (typeof cases)[number] +type Json = Record +type Reply = { text: string } | { tool: string; input: Json } +type Event = { + type: string + agentId?: string + agentType?: string + toolName?: string + toolCallId?: string + spawnToolCallId?: string + output?: { type: string; value?: unknown }[] + runOutcome?: { termination: string; cause?: { message?: string } } + gateVerification?: { validation: string; review: string; workRemaining: boolean } + message?: string + text?: string + scope?: string + model?: string +} + +const digest = (value: string | Buffer) => createHash('sha256').update(value).digest('hex') +async function hashFile(path: string) { + const hash = createHash('sha256') + for await (const chunk of createReadStream(path)) hash.update(chunk) + return hash.digest('hex') +} + +function assertLinuxX64() { + assert.equal(process.platform, 'linux', 'The exact archive fixture is Linux only') + assert.equal(process.arch, 'x64', 'The exact archive fixture is x64 only') +} + +function launch(archive: string, version: string) { + const filename = basename(archive) + assert(/^(?:openbuff|codecane)-linux-x64\.tar\.gz$/.test(filename), 'Select the Linux x64 release tarball') + assert(lstatSync(archive).isFile(), 'Select a regular release archive (not a symlink)') + const input = realpathSync(archive) + const result = spawnSync('/usr/bin/bwrap', [ + '--unshare-user', '--unshare-net', '--unshare-pid', '--die-with-parent', '--new-session', + '--clearenv', '--ro-bind', '/usr', '/usr', '--ro-bind', '/bin', '/bin', + '--ro-bind', '/lib', '/lib', '--ro-bind', '/lib64', '/lib64', + '--ro-bind', '/etc/passwd', '/etc/passwd', '--ro-bind', '/etc/group', '/etc/group', + '--proc', '/proc', '--dev', '/dev', '--tmpfs', '/tmp', '--chdir', '/tmp', + '--ro-bind', process.execPath, '/fixture/bun', + '--ro-bind', import.meta.path, '/fixture/cli-release-candidate.ts', + '--ro-bind', input, `/fixture/${filename}`, + '--', '/fixture/bun', '--no-env-file', '--no-install', '/fixture/cli-release-candidate.ts', + worker, readlinkSync('/proc/self/ns/net'), `/fixture/${filename}`, version, + ], { env: {}, stdio: ['ignore', 'inherit', 'inherit'] }) + if (result.error) throw new Error('The smoke requires working /usr/bin/bwrap and Linux namespaces', { cause: result.error }) + assert.equal(result.status, 0, `Isolated CLI smoke failed (${result.signal ?? result.status})`) +} + +function readNetworkProof(parentNetns: string) { + const netns = readlinkSync('/proc/self/ns/net') + assert(/^net:\[\d+\]$/.test(parentNetns)) + assert.notEqual(netns, parentNetns, 'Refusing to start the CLI in the caller network namespace') + const interfaces = readFileSync('/proc/net/dev', 'utf8').trim().split('\n').slice(2) + .map((line) => line.split(':')[0]?.trim()) + assert.deepEqual(interfaces, ['lo'], 'Non-loopback interface present') + assert(networkInterfaces().lo?.some(({ address }) => address === '127.0.0.1'), 'IPv4 loopback is down') + // Bun supplies PWD itself when execve receives an empty environment. + const { PWD, ...inherited } = process.env + assert(PWD === undefined || PWD === '/tmp') + assert.deepEqual(Object.keys(inherited), [], 'The worker must not inherit the caller environment') + return { namespace: netns, interfaces } +} + +function command(file: string, args: string[], cwd: string, env: NodeJS.ProcessEnv, timeout = 30_000) { + return new Promise<{ code: number; stdout: string; stderr: string }>((resolve, reject) => { + const child = execFile(file, args, { + cwd, env, encoding: 'utf8', timeout, killSignal: 'SIGKILL', maxBuffer: 8 * 1024 * 1024, + }, (error, stdout, stderr) => { + if (error && typeof error.code !== 'number') { + reject(new Error(`${basename(file)} ${args[0]}: ${error.message}\n${stderr.slice(-4000)}`, { cause: error })) + return + } + resolve({ code: typeof error?.code === 'number' ? error.code : 0, stdout, stderr }) + }) + child.stdin?.end() + }) +} + +async function checked(file: string, args: string[], cwd: string, env: NodeJS.ProcessEnv) { + const result = await command(file, args, cwd, env) + assert.equal(result.code, 0, `${basename(file)} ${args.join(' ')}\n${result.stderr.slice(-4000)}`) + return result.stdout +} + +function fixtureEnv(home: string): NodeJS.ProcessEnv { + return { + PATH: '/usr/bin:/bin', HOME: home, XDG_CONFIG_HOME: home, XDG_CACHE_HOME: home, + TMPDIR: '/tmp', OPENBUFF_CONFIG_DIR: join(home, 'openbuff'), LANG: 'C.UTF-8', + TERM: 'dumb', NO_COLOR: '1', OPENBUFF_TELEMETRY: '0', DO_NOT_TRACK: '1', + GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0', + } +} + +function object(value: unknown): Json { + assert(value && typeof value === 'object' && !Array.isArray(value), 'Expected a JSON object') + return value as Json +} + +async function extract(archive: string, destination: string, binaryName: string, env: NodeJS.ProcessEnv) { + const tar = (args: string[]) => checked('/usr/bin/tar', args, destination, env) + const members = (await tar(['-tzf', archive])).trimEnd().split('\n') + const asset = /^(?:tree-sitter(?:-[a-z0-9-]+)?\.wasm|tree-sitter-manifest\.json|tree-sitter-queries\/[a-z0-9_-]+\.scm)$/ + assert(members.every((name) => name === binaryName || asset.test(name)), 'Unexpected archive member') + assert.equal(new Set(members).size, members.length, 'Duplicate archive member') + const listing = (await tar(['-tvzf', archive])).trimEnd().split('\n') + assert(listing.length === members.length && listing.every((line) => line.startsWith('-')), 'Archive members must be regular files') + await tar(['-xzf', archive, '--no-same-owner', '--no-same-permissions']) + const manifest = object(JSON.parse(readFileSync(join(destination, 'tree-sitter-manifest.json'), 'utf8'))) + const files = object(manifest.files) + const queries = object(manifest.queries) + assert.equal(manifest.schemaVersion, 1) + assert('tree-sitter.wasm' in files && Object.keys(files).length > 1 && Object.keys(queries).length > 0) + const assets = [...Object.entries(files), ...Object.entries(queries).map(([path, hash]) => [`tree-sitter-queries/${path}`, hash] as const)] + assert.deepEqual([...members].sort(), [binaryName, 'tree-sitter-manifest.json', ...assets.map(([name]) => name)].sort(), 'Actual members do not match packaged manifest') + for (const [name, hash] of assets) { + assert.equal(await hashFile(join(destination, name)), hash, `Invalid archive member ${name}`) + } + const binary = join(destination, binaryName) + const header = await Bun.file(binary).slice(0, 20).arrayBuffer() + assert.equal(Buffer.from(header).subarray(0, 6).toString('hex'), '7f454c460201', 'Not a 64-bit little-endian ELF') + assert.equal(new DataView(header).getUint16(18, true), 0x3e, 'Not a Linux x64 candidate') + return { binary, fileCount: members.length } +} + +function stream(model: string, id: number, reply: Reply) { + const chunk = (delta: Json, finish_reason: string | null, usage?: Json) => + `data: ${JSON.stringify({ + id: `chatcmpl-candidate-${id}`, object: 'chat.completion.chunk', model, created: 0, + choices: [{ index: 0, delta, finish_reason }], ...(usage ? { usage } : {}), + })}\n\n` + const delta = 'tool' in reply ? { tool_calls: [{ index: 0, type: 'function', id: `candidate-tool-${id}`, + function: { name: reply.tool, arguments: JSON.stringify(reply.input) }, + }] } : { content: reply.text } + return new Response(chunk({ role: 'assistant', ...delta }, null) + + chunk({}, 'tool' in reply ? 'tool_calls' : 'stop', { prompt_tokens: 50, completion_tokens: 5, total_tokens: 55 }) + + 'data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } }) +} + +function scriptReply(scenario: Scenario, model: string, step: number, messages: Json[]): Reply { + const context = JSON.stringify(messages.filter(({ role }) => role === 'user')) + const toolEvidence = JSON.stringify(messages.filter(({ role }) => role === 'tool')) + if (model === 'root') { + if (step === 0) { + assert(context.includes(prompt)) + return { tool: 'spawn_agents', input: { agents: [{ agent_type: 'editor', prompt: editorBrief }] } } + } + if (scenario === 'missing-child-route' && step <= 3) { + assert(toolEvidence.includes(unroutedEditor), 'Root did not receive the failed editor route result') + return { text: 'The editor route is unavailable; no edits were made.' } + } + if (scenario === 'missing-child-route') throw new Error('The route refusal did not settle') + if (/reviewer gate passed with LOOKS_GOOD for pending files:/i.test(context)) { + return { text: scenario === 'validated' ? finalText : 'No validation hooks ran.' } + } + if (step <= 3) return { text: 'Awaiting the validation and reviewer gate.' } + } + assert.notEqual(scenario, 'missing-child-route', 'A child should not reach the provider with an unresolved editor route') + if (model === 'editor') { + if (step === 0) return { tool: 'read_files', input: { paths: [source] } } + if (step === 1) { + assert(toolEvidence.includes(before.trim()), 'Editor did not observe the preimage') + return { tool: 'edit_transaction', input: { edits: [{ + type: 'str_replace', path: source, replacements: [{ oldString: before.trim(), newString: after.trim() }], + }] } } + } + if (step === 2) return { text: 'Scoped edit completed.' } + } + if (model === 'review-triage' && step === 0) { + return { tool: 'set_output', input: { schemaVersion: 1, family: 'review-impact', assessed: [], recommendations: [] } } + } + if (model === 'code-reviewer') { + const fingerprint = context.match(/Snapshot fingerprint \(echo exactly\): (v3:[a-f0-9]{64})/)?.[1] + assert(fingerprint && context.includes(digest(after)), 'Reviewer did not receive the scope fingerprint and postimage hash') + if (step === 0) return { tool: 'read_files', input: { paths: [source] } } + if (step === 1) { + assert(toolEvidence.includes(after.trim()), 'Reviewer did not read the final bytes') + return { tool: 'set_output', input: { + schemaVersion: 1, family: 'reviewer', verdict: 'LOOKS_GOOD', snapshotFingerprint: fingerprint, + reviewedFiles: [source], findings: [], coverage: 'covered', + dimensions: { correctness: 'pass', security: 'pass', tests: 'pass', apiCompatibility: 'pass', performance: 'pass' }, + requirementCoverage: [{ requirement: prompt, status: 'satisfied', evidence: [`Read ${source}.`] }], + } } + } + } + throw new Error(`Unexpected ${scenario} inference: ${model} step ${step}`) +} + +async function headless(binary: string, root: string, name: Scenario) { + const cwd = join(root, name) + const home = join(root, `${name}-home`) + mkdirSync(join(cwd, 'src'), { recursive: true }) + mkdirSync(home, { mode: 0o700 }) + const env = fixtureEnv(home) + const requests: string[] = [] + const faults: string[] = [] + const models = ['root', 'editor', 'review-triage', 'code-reviewer'] + const server = Bun.serve({ + hostname: '127.0.0.1', port: 0, + async fetch(req) { + try { + assert.equal(req.method, 'POST') + assert.equal(new URL(req.url).pathname, '/v1/chat/completions') + for (const header of ['authorization', 'proxy-authorization', 'x-api-key', 'cookie']) assert(!req.headers.has(header), `Unexpected ${header} header`) + const body = object(await req.json()) + assert(typeof body.model === 'string' && models.includes(body.model), `Unexpected provider route ${String(body.model)}`) + assert.equal(body.stream, true) + assert(Array.isArray(body.messages)) + const model = body.model + const step = requests.filter((entry) => entry === model).length + requests.push(model) + const reply = scriptReply(name, model, step, body.messages.map(object)) + if ('tool' in reply) { + assert(Array.isArray(body.tools) && body.tools.some((entry: { function?: { name?: string } }) => entry.function?.name === reply.tool), + `${model} did not advertise ${reply.tool}`) + } + return stream(model, requests.length, reply) + } catch (error) { + faults.push(String(error)) + return Response.json({ error: { message: 'Unexpected candidate fixture request' } }, { status: 400 }) + } + }, + }) + try { + writeFileSync(join(cwd, source), before) + writeFileSync(join(cwd, 'openbuff.json'), JSON.stringify({ + defaultModel: 'fixture/root', indexing: { enabled: false }, autoFileChangeHooks: false, + providers: { fixture: { type: 'openai-compatible', baseURL: `http://127.0.0.1:${server.port}/v1`, models } }, + agents: { + editor: name === 'missing-child-route' ? unroutedEditor : 'fixture/editor', + 'code-reviewer': 'fixture/code-reviewer', 'review-triage': 'fixture/review-triage', + }, + ...(name === 'no-hooks' ? {} : { fileChangeHooks: [ + { name: caseId, command: hookCommand, filePattern: source, timeoutSeconds: 5 }, + ] }), + })) + const git = (...args: string[]) => checked('/usr/bin/git', args, cwd, env) + await git('init', '-q', '--template=') + await git('add', '--', source, 'openbuff.json') + await git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgSign=false', 'commit', '-qm', 'fixture baseline') + + // Trust only this owned project. Strict mode with stdin closed proves + // routine scoped work needs neither allow-all nor interactive approval. + const result = await command(binary, ['run', '--json', '--require-gate', '--trust-project-agents', + '--approval-mode', 'strict', '--timeout', String(runDeadlineSeconds), '-p', prompt], + cwd, env, (runDeadlineSeconds + 15) * 1000) + const diagnosis = `${name}: ${requests.join(', ')}\n${result.stderr.slice(-4000)}\n${result.stdout.slice(-7500)}` + assert.deepEqual(faults, [], diagnosis) + const events = result.stdout.trim().split('\n').map((line) => JSON.parse(line) as Event) + assert(events.some(({ type, scope, agentId, model }) => + type === 'usage' && scope === 'root' && agentId === 'base2' && model === 'fixture/root'), diagnosis) + const finish = events.findLast(({ type }) => type === 'finish') + const failure = events.at(-1) + const results = events.filter(({ type }) => type === 'tool_result') + const value = (event?: Event) => event?.output?.find(({ type }) => type === 'json')?.value + const edits = results.filter(({ toolName }) => toolName === 'edit_transaction') + const hooks = results.filter(({ toolName }) => toolName === 'run_file_change_hooks') + const starts = events.filter(({ type }) => type === 'subagent_start') + const finishOf = (agentId: string) => events.find((event) => event.type === 'subagent_finish' && event.agentId === agentId) + const editor = starts.find(({ agentType }) => agentType === 'editor') + assert(editor?.agentId && editor.spawnToolCallId, diagnosis) + const editorJoin = results.find(({ toolCallId }) => toolCallId === editor.spawnToolCallId) + assert.equal(editorJoin?.toolName, 'spawn_agents', diagnosis) + const editorFinish = finishOf(editor.agentId) + let mutationReceiptId: string | undefined + let reviewerId: string | undefined + let validation: { status: string; caseId?: string; exitCode?: number } | undefined + if (name === 'missing-child-route') { + assert.equal(result.code, 1, diagnosis) + assert.equal(finish?.runOutcome?.termination, 'completed', diagnosis) + assert.equal(failure?.type, 'error', diagnosis) + assert.match(failure.message ?? '', /--require-gate: no fresh completed change gate/, diagnosis) + assert(requests.length >= 2 && requests.every((model) => model === 'root'), diagnosis) + assert.equal(starts.length, 1, diagnosis) + assert.equal(editorFinish?.runOutcome?.termination, 'failed', diagnosis) + assert(editorFinish.runOutcome.cause?.message?.includes(unroutedEditor), diagnosis) + assert(JSON.stringify(value(editorJoin)).includes(unroutedEditor), diagnosis) + assert.equal(edits.length + hooks.length, 0, diagnosis) + assert.equal(readFileSync(join(cwd, source), 'utf8'), before) + assert.equal(await git('diff', '--name-only', 'HEAD'), '') + } else { + assert.equal(editorFinish?.runOutcome?.termination, 'completed', diagnosis) + assert.equal(edits.length, 1, diagnosis) + const edit = edits[0]! + const mutation = object(value(edit)) + const receipt = object(mutation.authorityReceipt) + assert.equal(edit.agentId, editor.agentId) + assert.equal(mutation.outcome, 'applied') + assert(typeof mutation.receiptId === 'string' && mutation.receiptId.length > 0) + assert.equal(receipt.receiptId, mutation.receiptId) + assert.equal(receipt.callId, edit.toolCallId) + assert.equal(receipt.status, 'committed') + assert.deepEqual(receipt.finalHashes, { [source]: `sha256:${digest(after)}` }) + mutationReceiptId = mutation.receiptId + const joined = (value(editorJoin) as { agentReceipt?: Json }[] | undefined)?.[0]?.agentReceipt + assert.equal(joined?.agentId, editor.agentId, diagnosis) + assert(Array.isArray(joined.changedFiles), diagnosis) + assert.deepEqual(joined.changedFiles.map(({ path, mutationReceiptId: id }) => [path, id]), + [[source, mutationReceiptId]], diagnosis) + assert.equal(readFileSync(join(cwd, source), 'utf8'), after) + assert.equal(await git('diff', '--name-only', 'HEAD'), `${source}\n`) + assert.equal(requests.filter((model) => model === 'editor').length, 3, diagnosis) + assert.equal(hooks.length, 1, diagnosis) + const hook = (value(hooks[0]) as Json[] | undefined)?.[0] + assert(hook, diagnosis) + if (name === 'validated') { + assert.equal(result.code, 0, diagnosis) + assert.equal(finish?.runOutcome?.termination, 'completed', diagnosis) + assert.equal(hook.hookName, caseId) + assert.equal(hook.exitCode, 0) + assert(typeof hook.stdout === 'string' && hook.stdout.trimEnd() === after.trimEnd()) + const reviewer = events.find(({ type, agentType }) => type === 'subagent_start' && agentType === 'code-reviewer') + assert(reviewer?.agentId && reviewer.agentId !== editor.agentId, diagnosis) + assert.equal(finishOf(reviewer.agentId)?.runOutcome?.termination, 'completed', diagnosis) + assert.equal(requests.filter((model) => model === 'code-reviewer').length, 2, diagnosis) + assert(events.filter(({ type }) => type === 'text').map(({ text }) => text).join('').includes(finalText), diagnosis) + reviewerId = reviewer.agentId + validation = { status: 'passed', caseId, exitCode: 0 } + } else { + assert.equal(result.code, 1, diagnosis) + assert.equal(finish?.runOutcome?.termination, 'completed', diagnosis) + assert.equal(hook.validationStatus, 'no_hooks_configured', diagnosis) + assert.equal(failure?.type, 'error', diagnosis) + assert.match(failure.message ?? '', /--require-gate: no fresh completed change gate/, diagnosis) + assert.equal(failure.gateVerification?.validation, 'skipped', diagnosis) + assert.equal(failure.gateVerification?.review, 'passed', diagnosis) + validation = { status: 'no_hooks_configured' } + } + } + const untracked = (await git('ls-files', '--others', '--exclude-standard')).trimEnd().split('\n').filter(Boolean) + assert.deepEqual(untracked.filter((path) => !allowedRuntimeFiles.has(path)), [], 'Unexpected workspace writes') + return { case: name, exitCode: result.code, termination: finish?.runOutcome?.termination, + requests, mutationReceiptId, reviewerId, validation, runtimeFiles: untracked, + postimageSha256: await hashFile(join(cwd, source)) } + } finally { + server.stop(true) + } +} + +async function runIsolated(parentNetns: string, archive: string, version: string) { + const network = readNetworkProof(parentNetns) + const root = mkdtempSync('/tmp/cli-release-candidate-') + try { + const destination = join(root, 'extracted') + const home = join(root, 'smoke-home') + mkdirSync(destination) + mkdirSync(home, { mode: 0o700 }) + const env = fixtureEnv(home) + const binaryName = basename(archive).split('-linux-x64.tar.gz')[0]! + const archiveSha256 = await hashFile(archive) + const { binary, fileCount } = await extract(archive, destination, binaryName, env) + const binarySha256 = await hashFile(binary) + console.error(`Linux x64 candidate ${basename(archive)} sha256=${archiveSha256}; ${binaryName} sha256=${binarySha256}`) + // Pin the same help contract as binary-entry-fast-path and e2e-cli.test.ts. + const invoke = (args: string[]) => checked(binary, args, destination, env) + const help = await invoke(['--help']) + for (const marker of ['Usage: openbuff', 'Commands:', '--agent']) assert(help.includes(marker), `Missing --help marker: ${marker}`) + assert(!help.includes('Using environment:')) + assert.equal((await invoke(['--version'])).trim(), version) + const parsing = (await invoke(['--smoke-code-map'])).trim() + assert.match(parsing, /code-map smoke ok \(symbols=[1-9]\d* calls=[1-9]\d* imports=[1-9]\d* queries=([1-9]\d*)\/\1\)/) + const results = [] + const failed: Scenario[] = [] + for (const candidateCase of cases) { + try { + results.push(await headless(binary, root, candidateCase)) + } catch (error) { + failed.push(candidateCase) + console.error(`${candidateCase} failed:`, error) + } + } + assert.equal(await hashFile(binary), binarySha256, 'Extracted candidate changed during testing') + assert.equal(await hashFile(archive), archiveSha256, 'Release archive changed during testing') + console.log(JSON.stringify({ + platform: 'linux-x64', archive: basename(archive), archiveSha256, binary: binaryName, binarySha256, + archiveMembers: fileCount, version, network, checks: { help: 'passed', codeMap: parsing }, + headless: { selected: cases.length, executed: results.length + failed.length, skipped: 0, results, failed }, + scope: 'Exact extracted archive, packaged code map and narrow Base2 edit/validation/review controls only', + }, null, 2)) + assert.deepEqual(failed, [], 'Headless candidate acceptance failed') + } finally { + rmSync(root, { recursive: true, force: true }) + } +} + +assertLinuxX64() +const args = process.argv.slice(2) +if (args[0] === worker) { + const [, namespace, archive, version] = args + assert(args.length === 4 && namespace && archive && version) + await runIsolated(namespace, archive, version) +} else { + const [archive, version] = args + assert(args.length === 2 && archive && version, 'Supply -linux-x64.tar.gz and expected version') + launch(archive, version) +} diff --git a/test/fixtures/body/packed-language-assets-probe.cjs b/test/fixtures/body/packed-language-assets-probe.cjs index f026b46cbe..05bcad8562 100644 --- a/test/fixtures/body/packed-language-assets-probe.cjs +++ b/test/fixtures/body/packed-language-assets-probe.cjs @@ -3,6 +3,38 @@ const assert = require('node:assert/strict') const fs = require('node:fs') const path = require('node:path') +// The local SDK verifier shares this healthy oracle without weakening the +// B24 namespace requirement or reusing source extraction as packaged proof. +async function observeHealthyLanguageAssets(sdk, project, rows) { + const files = rows.flatMap(row => [row.caller, row.definition]) + const result = await sdk.getFileTokenScores(project, files) + const observed = rows.map(row => { + const caller = result.parsed[row.caller] + const definition = result.parsed[row.definition] + const text = fs.readFileSync(path.join(project, row.caller), 'utf8') + const imports = caller?.imports?.length ? caller.imports : sdk.extractImportSites(text, row.caller).map(site => site.specifier) + const callers = result.tokenCallers[row.definition]?.[row.callee] ?? [] + return { ...row, identifiers: caller?.identifiers, targets: definition?.identifiers, + calls: caller?.calls, imports, callers } + }) + return { rows: observed, coverage: result.coverage, diagnostics: result.diagnostics } +} + +function assertHealthyLanguageAssets({ rows, coverage, diagnostics }) { + assert(rows.length > 0, 'No language cases were selected') + for (const row of rows) { + assert(row.identifiers?.includes(row.entry), `${row.extension} caller definition`) + assert(row.targets?.includes(row.callee), `${row.extension} target definition`) + assert(row.calls?.includes(row.callee), `${row.extension} direct call`) + assert(row.imports.some(specifier=>specifier.includes(row.importMarker)), `${row.extension} import`) + assert.deepEqual(row.callers, [row.caller], `${row.extension} exact same-family caller`) + } + assert.equal(coverage.parsedFiles, rows.length * 2) + assert.deepEqual(diagnostics, []) +} + +module.exports = { observeHealthyLanguageAssets, assertHealthyLanguageAssets } + async function main() { const [mode, scenario, checkout] = process.argv.slice(2) assert(!fs.existsSync(checkout), 'The checkout must be absent from the consumer namespace') @@ -27,29 +59,13 @@ async function main() { } const sdk = mode === 'cjs' ? require('@openbuff/sdk') : await import('@openbuff/sdk') if (scenario === 'typed-override') sdk.setWasmDir('/override') - const result = await sdk.getFileTokenScores('/project', files) if (scenario === 'healthy' || scenario.endsWith('override')) { - const observed = rows.map(row => { - const caller = result.parsed[row.caller] - const definition = result.parsed[row.definition] - const text = fs.readFileSync(`/project/${row.caller}`, 'utf8') - const imports = caller?.imports?.length ? caller.imports : sdk.extractImportSites(text, row.caller).map(site => site.specifier) - const callers = result.tokenCallers[row.definition]?.[row.callee] ?? [] - return { ...row, identifiers: caller?.identifiers, targets: definition?.identifiers, - calls: caller?.calls, imports, callers } - }) + const observed = await observeHealthyLanguageAssets(sdk, '/project', rows) console.log('B24_RESULT '+JSON.stringify({ mode, scenario, entry, runtime: process.version, - noCheckout: true, rows: observed, coverage: result.coverage, diagnostics: result.diagnostics })) - for (const row of observed) { - assert(row.identifiers?.includes(row.entry), `${row.extension} caller definition`) - assert(row.targets?.includes(row.callee), `${row.extension} target definition`) - assert(row.calls?.includes(row.callee), `${row.extension} direct call`) - assert(row.imports.some(specifier=>specifier.includes(row.importMarker)), `${row.extension} import`) - assert.deepEqual(row.callers, [row.caller], `${row.extension} exact same-family caller`) - } - assert.equal(result.coverage.parsedFiles, files.length) - assert.deepEqual(result.diagnostics, []) + noCheckout: true, ...observed })) + assertHealthyLanguageAssets(observed) } else { + const result = await sdk.getFileTokenScores('/project', files) console.log('B24_RESULT '+JSON.stringify({ mode, scenario, entry, runtime: process.version, noCheckout: true, coverage: result.coverage, diagnostics: result.diagnostics, wrongAbi: scenario === 'wrong-abi' ? 255 : undefined })) @@ -64,4 +80,6 @@ async function main() { } } } -main().catch(error => { console.error(error); process.exitCode = 1 }) +if (require.main === module) { + main().catch(error => { console.error(error); process.exitCode = 1 }) +} diff --git a/test/fixtures/body/packed-sdk-config-probe.mjs b/test/fixtures/body/packed-sdk-config-probe.mjs new file mode 100644 index 0000000000..84475c0dd3 --- /dev/null +++ b/test/fixtures/body/packed-sdk-config-probe.mjs @@ -0,0 +1,298 @@ +// Runs in a fresh Node consumer, against the package export map (not SDK source). +import assert from 'node:assert/strict' +import { cpSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' + +import languageProbe from './packed-language-assets-probe.cjs' + +const model = 'qwen3:8b' +const selection = `local/${model}` +const baseURL = 'http://127.0.0.1:11434/v1' +const rootRole = 'base2' +const reviewRole = 'code-reviewer' +const missingRoute = 'route:p73-missing-review' +const noModel = id => `No model configured for agent '${id}'. Run /setup or set defaultModel (or agents['${id}']) in your openbuff.json.` +const noRoute = `Named provider route '${missingRoute}' is not configured. Define it in routes or choose a configured model.` +const readJson = file => JSON.parse(readFileSync(file, 'utf8')) + +function hostInputs(cwd, home, projectConfig) { + return { + environment: { OPENBUFF_TELEMETRY: '0', DO_NOT_TRACK: '1', OPENBUFF_PROCESS_SUPERVISION: '0' }, + platform: process.platform, + invocationCwd: cwd, + projectRoot: cwd, + home: { kind: 'path', path: home }, + globals: { kind: 'disabled' }, + selection: { kind: 'discover' }, + trust: { ancestorConfig: false, projectReadableRoots: false, projectConfig }, + } +} + +function capture(sdk, inputs) { + const result = sdk.loadHostConfigSnapshot({ inputs, fs: sdk.nodeConfigReadFs }) + assert.equal(result.status, 'complete', result.cause) + const loaded = sdk.getCapturedProviderConfig(result.snapshot) + assert.deepEqual(loaded.diagnostics ?? [], []) + assert.equal(loaded.projectTrust?.status, inputs.trust.projectConfig) + return loaded +} + +function assertLocallyRouted(sdk, loadedConfig, agentId) { + const resolved = sdk.resolveConfiguredAgentModelConfig({ loadedConfig, agentId }) + assert.equal(resolved.model, selection, `${agentId} should select the copied local default`) + const mapping = sdk.resolveConfiguredProviderModel({ model: resolved.model, loadedConfig, env: {}, credentialStoreDir: null }) + assert.equal(mapping?.providerId, 'local', agentId) + assert.equal(mapping.providerModel, model, agentId) + assert.equal(mapping.provider.baseURL, baseURL, agentId) + assert.equal(mapping.apiKey, undefined, agentId) +} + +async function checkHooks(sdk, trusted, untrusted, trustedInputs, untrustedInputs) { + const cwd = trustedInputs.projectRoot + const launches = [] + const probe = async (loaded, hostConfiguration, file) => { + const host = sdk.createDirectHostExecution({ + cwd, + hostConfiguration, + limit: { kind: 'finite', durationMs: 10_000 }, + spawn: () => assert.fail('The copied-config admission probe must not spawn a process'), + }) + assert.equal(host.ok, true, host.cause) + const result = await sdk.ToolHelpers.runFileChangeHooks({ + cwd, + files: [file], + capturedConfiguration: { + fileChangeHooks: loaded.config.fileChangeHooks, + autoFileChangeHooks: loaded.config.autoFileChangeHooks, + }, + executionContext: host.value.executionContext, + // Record selection at the launch seam; no copied project command runs. + runCommand: async ({ command, cwd: launchCwd }) => { + launches.push({ command, cwd: launchCwd }) + return [{ type: 'json', value: { command, exitCode: 0 } }] + }, + }) + assert.equal(result.length, 1) + assert.equal(result[0].type, 'json') + return result[0].value + } + + assert.equal(trusted.config.autoFileChangeHooks, false) + const count = trusted.config.fileChangeHooks.length + assert(count > 0) + assert.deepEqual(untrusted.config.fileChangeHooks, []) + const gated = untrusted.projectTrust?.gated?.filter(item => item.kind === 'fileChangeHooks') + assert.equal(gated?.length, count, 'Project trust must account for every withheld hook') + assert.deepEqual(await probe(untrusted, untrustedInputs, 'sdk/src/index.ts'), [{ + validationStatus: 'no_hooks_configured', + message: 'No configured file-change hooks ran.', + changedFiles: ['sdk/src/index.ts'], + }]) + assert.deepEqual(await probe(trusted, trustedInputs, 'README.md'), [{ + validationStatus: 'hooks_skipped', + message: 'Configured file-change hooks were skipped because none matched the changed files.', + configuredHookCount: count, + changedFiles: ['README.md'], + }]) + assert.deepEqual(launches, []) + const matched = await probe(trusted, trustedInputs, 'sdk/src/index.ts') + const command = 'cd sdk && bun run typecheck' + assert.deepEqual(launches, [{ command, cwd }]) + assert.equal(matched.length, 1) + assert.equal(matched[0].hookName, 'typecheck-sdk') + assert.equal(matched[0].executionStatus?.kind, 'exited') + assert.equal(matched[0].executionStatus?.exitCode, 0) + return { configured: count, untrustedSelected: 0, unmatchedSelected: 0, trustedSelected: ['typecheck-sdk'], executedCommands: 0 } +} + +function reply(content, toolCall = false) { + const packet = (delta, finishReason) => `data: ${JSON.stringify({ + id: 'p73-fixture', object: 'chat.completion.chunk', model, + choices: [{ index: 0, delta, finish_reason: finishReason }], + })}\n\n` + return new Response( + packet({ role: 'assistant', ...content }, null) + + packet({}, toolCall ? 'tool_calls' : 'stop') + 'data: [DONE]\n\n', + { headers: { 'content-type': 'text/event-stream' } }, + ) +} + +async function checkDelegation(sdk, inputs, wrongRoute) { + const requests = [] + const events = [] + const rootMarker = 'P73-ROUTING-ROOT' + const childMarker = 'P73-ROUTING-CHILD' + const childText = 'P73 child reached the copied local route.' + const previousFetch = globalThis.fetch + globalThis.fetch = async (input, init) => { + requests.push('unexpected') + assert.equal(input instanceof Request ? input.url : String(input), `${baseURL}/chat/completions`) + assert.equal(init.method, 'POST') + assert.equal(new Headers(init.headers).get('authorization'), null) + const request = JSON.parse(init.body) + assert.equal(request.model, model) + const messages = JSON.stringify(request.messages) + if (messages.includes(childMarker)) { + assert.equal(wrongRoute, false, 'The unroutable child must not reach inference or borrow its parent route') + requests[requests.length - 1] = reviewRole + return reply({ content: childText }) + } + assert(messages.includes(rootMarker)) + requests[requests.length - 1] = rootRole + if (request.messages.some(({ role }) => role === 'tool')) { + if (wrongRoute) { + const toolResult = request.messages.find(({ role }) => role === 'tool') + assert.deepEqual(JSON.parse(toolResult.content).map(({ agentType, spawnIndex, value }) => [agentType, spawnIndex, value.errorCode]), + [[reviewRole, 0, 'child_route_unavailable']]) + } else assert(messages.includes(childText)) + return reply({ content: 'P73 root finished.' }) + } + assert(request.tools?.some(({ function: tool }) => tool.name === 'spawn_agents')) + return reply({ tool_calls: [{ index: 0, id: 'p73-spawn', type: 'function', function: { + name: 'spawn_agents', arguments: JSON.stringify({ agents: [{ agent_type: reviewRole }] }), + } }] }, true) + } + try { + const result = await new sdk.OpenbuffClient({ + cwd: inputs.projectRoot, + hostConfiguration: inputs, + harnessStateDir: join(inputs.projectRoot, 'harness'), + projectFiles: {}, knowledgeFiles: {}, userKnowledgeFiles: {}, repositoryIntelligence: false, + runTimeoutMs: 10_000, + handleEvent: event => events.push(event), + }).run({ + agent: { + id: rootRole, displayName: 'Copied config root fixture', systemPrompt: rootMarker, + toolNames: ['spawn_agents'], spawnableAgentToolMode: 'generic', spawnableAgents: [reviewRole], + }, + agentDefinitions: [{ id: reviewRole, displayName: 'Copied config child fixture', systemPrompt: childMarker }], + prompt: 'Probe copied configuration routing.', + }) + const spawns = events.filter(event => event.type === 'tool_call' && event.toolName === 'spawn_agents') + const children = events.filter(event => event.type === 'subagent_finish') + if (wrongRoute) { + // The root's independent route is still usable. The child must be + // rejected before its own inference and retain the correlated failure. + assert.equal(result.runOutcome?.termination, 'completed', JSON.stringify(result.output)) + assert.deepEqual(requests, [rootRole, rootRole]) + assert.equal(spawns.length, 1) + assert.equal(children.length, 0, 'A preflight refusal must not launch a child') + const response = events.find(event => event.type === 'tool_result' && event.toolCallId === spawns[0].toolCallId) + const [member] = response?.output[0]?.value ?? [] + assert.equal(member?.agentType, reviewRole) + assert.equal(member?.spawnIndex, 0) + assert.deepEqual(member.value, { + status: 'rejected', errorCode: 'child_route_unavailable', + errorMessage: 'The selected child model/provider route is unavailable. Configure a supported route for this agent.', + }) + return { requests, termination: result.runOutcome.termination, rejectedChild: member.value } + } + assert.equal(result.runOutcome?.termination, 'completed', JSON.stringify(result.output)) + assert.deepEqual(requests, [rootRole, reviewRole, rootRole]) + assert.equal(spawns.length, 1) + assert.equal(children.length, 1) + const child = children[0] + assert.equal(child.agentType, reviewRole) + assert.equal(child.spawnToolCallId, spawns[0].toolCallId) + assert.equal(child.spawnIndex, 0) + assert.equal(child.runOutcome?.termination, 'completed') + return { requests, termination: child.runOutcome.termination } + } finally { + globalThis.fetch = previousFetch + } +} + +async function checkCopiedConfig(sdk, template, home, roles) { + assert(roles.includes(rootRole) && roles.includes(reviewRole) && roles.includes('file-lister'), 'Missing required route subjects') + mkdirSync(home) + const makeCase = (name, change) => { + const cwd = join(home, name) + cpSync(template, cwd, { recursive: true }) + if (change) { + const file = join(cwd, 'openbuff.d/routes.json') + const routes = readJson(file) + change(routes) + writeFileSync(file, JSON.stringify(routes, null, 2)) + } + return hostInputs(cwd, home, 'trusted') + } + const inputs = makeCase('baseline') + const loaded = capture(sdk, inputs) + assert.deepEqual([...loaded.sourceFilePaths].sort(), [ + 'openbuff.json', 'openbuff.d/hooks.json', 'openbuff.d/indexing.json', + 'openbuff.d/providers.json', 'openbuff.d/routes.json', + ].map(file => join(inputs.projectRoot, file)).sort()) + assert.equal(loaded.config.indexing.enabled, true) + assert.equal(loaded.config.indexing.semantic.enabled, false) + for (const id of roles) assertLocallyRouted(sdk, loaded, id) + const attempts = route => sdk.resolveProviderRoutePlan({ model: `route:${route}`, loadedConfig: loaded }).candidates + assert.deepEqual(attempts('example-gpt-5-5').map(({ target }) => [target.provider, target.model, target.api, target.account]), [ + ['openai', 'gpt-5.5', 'responses', 'primary'], ['openai', 'gpt-5.5', 'responses', 'secondary'], + ['pioneer', 'gpt-5.5', undefined, 'gateway'], + ]) + assert.deepEqual(attempts('example-go-kimi-k3').map(({ target, quotaKey }) => [target.provider, target.model, target.api, target.account, quotaKey]), [ + ['opencode-go-current', 'kimi-k3', 'responses', 'subscription', 'quota:opencode-go-subscription'], + ['opencode-go-current', 'kimi-k3', 'chat-completions', 'subscription', 'quota:opencode-go-subscription'], + ['opencode-go-anthropic', 'kimi-k3', undefined, 'subscription', 'quota:opencode-go-subscription'], + ]) + + // The preflight checks the child independently while the root is still ready. + const missing = capture(sdk, makeCase('missing-child-selection', routes => { + delete routes.defaultModel + delete routes.agents[reviewRole] + routes.modes = { default: selection } + })) + assertLocallyRouted(sdk, missing, rootRole) + assert.throws(() => sdk.resolveConfiguredAgentModelConfig({ agentId: reviewRole, loadedConfig: missing }), { message: noModel(reviewRole) }) + const wrongInputs = makeCase('wrong-child-route', routes => { routes.agents[reviewRole] = missingRoute }) + const wrong = capture(sdk, wrongInputs) + assertLocallyRouted(sdk, wrong, rootRole) + assertLocallyRouted(sdk, wrong, 'general-agent') + const wrongModel = sdk.resolveConfiguredAgentModelConfig({ agentId: reviewRole, loadedConfig: wrong }).model + assert.equal(wrongModel, missingRoute) + assert.throws(() => sdk.resolveProviderRoutePlan({ model: wrongModel, loadedConfig: wrong }), { + code: 'provider_configuration', message: noRoute, + }) + + const untrustedInputs = hostInputs(inputs.projectRoot, home, 'untrusted') + const untrusted = capture(sdk, untrustedInputs) + assert.equal(untrusted.config.providers.openai, undefined, 'A project cannot grant itself credential-bearing providers') + assert.throws(() => sdk.resolveConfiguredAgentModelConfig({ agentId: rootRole, loadedConfig: untrusted }), { message: noModel(rootRole) }) + const hooks = await checkHooks(sdk, loaded, untrusted, inputs, untrustedInputs) + return { + routedRoles: roles.length, + preflight: { missingChildSelection: noModel(reviewRole), wrongChildRoute: { code: 'provider_configuration', message: noRoute } }, + baseline: await checkDelegation(sdk, inputs, false), + wrongRoute: await checkDelegation(sdk, wrongInputs, true), + hooks, + } +} + +async function main() { + const [mode, template, home, rolesPath, parserProject, rowsPath] = process.argv.slice(2) + assert(mode === 'cjs' || mode === 'esm') + const consumer = dirname(fileURLToPath(import.meta.url)) + const require = createRequire(import.meta.url) + const entry = mode === 'cjs' ? require.resolve('@openbuff/sdk') : fileURLToPath(import.meta.resolve('@openbuff/sdk')) + const expected = join(consumer, 'node_modules/@openbuff/sdk/dist', `index.${mode === 'cjs' ? 'cjs' : 'mjs'}`) + assert.equal(entry, expected) + assert.equal(realpathSync(entry), expected) + const unexpectedFetch = [] + globalThis.fetch = async () => { + unexpectedFetch.push('attempted') + throw new Error('Non-scripted fetch forbidden by the packed SDK probe') + } + const sdk = mode === 'cjs' ? require('@openbuff/sdk') : await import('@openbuff/sdk') + const copiedConfig = await checkCopiedConfig(sdk, template, home, readJson(rolesPath)) + const assets = await languageProbe.observeHealthyLanguageAssets(sdk, parserProject, readJson(rowsPath)) + languageProbe.assertHealthyLanguageAssets(assets) + assert.deepEqual(unexpectedFetch, []) + console.log('P73_PACKED ' + JSON.stringify({ mode, entry, runtime: process.version, copiedConfig, + parsedLanguages: assets.rows.map(row => row.extension), parsedFiles: assets.coverage.parsedFiles })) +} + +if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { + main().catch(error => { console.error(error); process.exitCode = 1 }) +}