oficina / equipo Public

fix: bound the coordinator tool journal and certify the coordinator live

Retire delivered tool rows atomically, share claims across calls, and retain open-turn replay. Preserve message sources, redact questions and suggestions, and supersede earlier pending questions consistently.

Run coordinator certification through both pinned adapters with observed inventories and independent tuple failures. Codex native MCP resource tools remain a documented release blocker. Only fake CLI and targeted offline tests were run; no live certification is claimed.
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 6836ff91a766f3c600e2990c732eebe16e864721 parent 4d07586
34 files changed, +1,432 −88
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +467 −0
  • internal/directlive/calibration.go +1 −1
  • internal/directlive/certificate.go +7 −0
  • internal/directlive/coordinator.go +26 −35
  • internal/directlive/coordinator_certificate_test.go +71 −0
  • internal/directlive/coordinator_fixes_test.go +87 −0
  • internal/directlive/coordinator_inventory.go +100 −0
  • internal/directlive/driver.go +13 −3
  • internal/directlive/driver_test.go +36 −1
  • internal/directlive/testdata/fake-cli.py +5 −1
  • internal/directlive/tuple_failures.go +10 −0
  • internal/equipo/conversation/models.go +10 −5
  • internal/equipo/conversation/tools.go +27 −13
  • internal/equipo/migrations/0021_coordinator_sources.sql +1 −0
  • internal/equipo/migrations/schema.sql +1 −1
  • internal/plan3test/conversation_test.go +4 −3
  • internal/plan3test/coordinator_sources_migration_test.go +48 −0
  • internal/plan3test/coordinator_tool_fixes_test.go +86 −0
  • internal/plan3test/coordinator_tools_test.go +26 −2
  • internal/plan3test/migration_test.go +2 −2
  • internal/release/manifest.json +1 −1
  • internal/runner/capture.go +1 −1
  • internal/runner/coordinator_journal_fixes_test.go +146 −0
  • internal/runner/coordinator_tool_journal.go +30 −7
  • internal/runner/coordinator_tool_retirement.go +121 −0
  • internal/runner/coordinator_tools_test.go +2 −2
  • internal/runner/journal.go +38 −6
  • internal/runner/provider/codex/coordinator.go +2 −1
  • internal/runner/provider/codex/launcher.go +5 −1
  • internal/runner/provider/direct_certification.go +6 −0
  • internal/runner/provider/direct_certification_test.go +24 −0
  • internal/runner/provider/direct_groups.go +6 −0
  • internal/runner/provider/direct_requirements.json +6 −0
  • internal/runner/provider/live_test.go +16 −2
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 3583e40e..b083c620 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -967,3 +967,470 @@ rastrillo-budget/v1 ran 638ms
FAIL amadan.net/oficina/equipo/internal/plan3test 0.680s
FAIL
```
+
+## Fix round 1
+
+Status: DONE_WITH_CONCERNS. All requested code fixes and offline checks are complete. Live coordinator certification remains blocked by a pinned Codex tool-inventory limitation described below. No live provider run or production certification is claimed.
+
+### Changes
+
+The runner now stores each coordinator claim/session once in `coordinator_tool_claims`; individual tool rows contain a claim reference and the call. The existing full submission hash still binds approval, execution and replay. Journal migration 6 compacts version-5 rows, preserving submitted calls and acknowledged results, and retires rows for delivery events that were already acknowledged.
+
+`Journal.Ack` commits delivery acknowledgement and deletion of that turn's tool rows and claim together. The match includes account/job, attempt, fence, turn and provider session. An indexed check against the existing delivery event prevents reopening a retired turn. Unacknowledged deliveries, open turns and uncertain turns retain their replay data. The shared byte budget counts the retained claim once plus tool calls/results. Re-acknowledging a result charges only its size difference. Task 7 must use this ordinary `Journal.Ack` delivery path after successful instance delivery; a provider's turn-completed frame alone is not a delivery acknowledgement.
+
+The coordinator certification case now accepts `direct-live` and launches the same pinned provider adapters used by the rest of the driver. Equipo operations use the existing in-process fixture through its Unix socket. The fixture accepts `ask_person`; the prompt supplies the fixture message ID and exact argument shape. Both providers must produce an observed inventory containing only the allowed Equipo tools. Claude is checked against the captured session init. Codex uses the pinned CLI's incremental Responses Lite catalog, captured through `experimentalRawEvents` as a developer `additional_tools` item. Missing, foreign-session, incomplete or widened observations fail. Evidence stores the captured frames, not merely the requested policy. The Codex constructor inventory hash is now `439feb9ef31873621697f1bfbd156d7d07b672ea132e670c1ca35e7deff97831`; the release entry remains uncertified.
+
+Coordinator failures get their own `tuple-completed` failure observation. Coordinator usage stays out of specialist calibration samples, and calibration errors name their tuple. The four-tuple fake test runs Engineering and Coordinator for both providers; injected Codex MCP resource tools fail only the Codex coordinator tuple while both specialist results retain passing calibration.
+
+Suggestions are tested against record counts with preference/playbook tables present, so a later migration creating those tables does not invalidate the test. Questions, option labels and all suggestion bodies use the same redaction as posted messages. Suggestions remain JSON objects in storage and tool results. A mutation exposed accidental base64 encoding in an intermediate implementation; the code now uses `json.RawMessage`, and tests require the stored and returned structure as well as redaction.
+
+Posted source references are stored on `conversation_messages.source_refs` and returned in `Message.SourceRefs`. The additive `0021_coordinator_sources.sql` migration sorts after `0021_coordinator.sql`; Rastrillo keys migrations by full filename, so the original migration stays unchanged and Task 8 retains 0022. The schema snapshot and old-conversation upgrade fixture include the new column. Historical messages retain their body and null sources.
+
+A newer question supersedes all other pending questions in the same binding, conversation and generation, including questions from delivered turns. State and revision are updated in both the question columns and JSON payload, and the card revision advances. An identical question is deduplicated only within its current turn. Answering the superseded question still fails.
+
+### Tests first and intermediate results
+
+Before implementation, these commands failed as expected:
+
+```text
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(Tool(Redaction|QuestionSupersession|Sources)|SuggestionOnly)$' -count=1
+exit 1
+TestCoordinatorToolRedaction: all four tool results leaked the fixture secret;
+stored message and stored question leaked the secret.
+TestCoordinatorToolQuestionSupersession/same_turn: column=superseded/2,
+payload.State=pending and payload.Revision=1.
+TestCoordinatorToolQuestionSupersession/earlier_delivered_turn:
+column=pending/1, payload.State=pending.
+TestCoordinatorToolSources: message sources lost from the conversation projection.
+The revised TestCoordinatorSuggestionOnly already passed; its regression guard
+was checked separately by restoring the old table-absence assertion.
+
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorToolJournalSettledBudget$' -count=1
+exit 1
+TestCoordinatorToolJournalSettledBudget: settled turn retained 1 tool rows.
+
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinator(InventoryObservation|CalibrationIsolation|LiveModeFakeCLI)$' -count=1
+exit 1
+Claude foreign-session inventory was certified.
+Codex missing, foreign, widened, incomplete and malformed inventory was certified.
+Both live-mode fake coordinator tuples returned provider_policy_rejected.
+Coordinator unknown usage poisoned specialist calibration.
+```
+
+The live-mode fixture test runs only fake executable bytes under test-only digest overlays. It does not run the installed signed-in CLIs. The fake source mode exercises the production admission branch; it is not a production certificate.
+
+Intermediate verification also caught the expected changed release inventory hash and an old conversation-upgrade fixture that applied the new column before creating its table. The release pin and dependent upgrade fixture were corrected. Migration support tests were added after the main regression tests; no claim is made that those support tests were initially red.
+
+### Covering tests and final verification
+
+- `TestCoordinatorToolJournalSettledBudget`: 40 settled turns under a 64 KiB limit, zero retained tool rows after each delivery, no admission exhaustion, no reopened delivered turn, one shared claim for 20 calls, reopen and replay after lost acknowledgements, immutable acknowledged call hashes.
+- `TestCoordinatorToolJournalRetirementScope`: an unacknowledged delivery retains both turns; acknowledging it removes only its own rows and preserves the uncertain turn.
+- `TestCoordinatorToolJournalLegacyUpgrade` and `TestCoordinatorToolJournalUpgrade`: preserve pending legacy submissions and the old outbox across ordered upgrades.
+- `TestCoordinatorInventoryObservation`: both providers reject absent, foreign, widened, incomplete, later-widened and malformed inventory; accepts the pinned Codex MCP namespace shape.
+- `TestCoordinatorLiveModeFakeCLI`: both fake providers exercise direct-live mode with the local socket fixture and observed catalogs.
+- `TestCoordinatorCalibrationIsolation` and `TestCoordinatorFailureIsolatedFakeCLI`: coordinator failure is independent of specialist tuples.
+- `TestCoordinatorToolRedaction`, `TestCoordinatorToolSources`, `TestCoordinatorToolQuestionSupersession` and `TestCoordinatorSuggestionOnly`: cover requested minor findings 2, 3, 4 and 5.
+- `TestCoordinatorMessageSourcesUpgrade`, the existing conversation upgrade, broker authorization tests, lost-commit replay tests and release-policy tests cover the affected integration seams.
+
+Exact final commands and output:
+
+```text
+CGO_ENABLED=0 go test ./internal/coordinator ./internal/runner ./internal/plan3test ./internal/release -run '^Test(Coordinator(Tool|Project|Suggestion|Migration|MessageSources)|PlanWorkflowReleasePolicyInventory|RunnerJournalCrashBoundaries|Conversation)' -count=1
+ok amadan.net/oficina/equipo/internal/coordinator 0.002s
+ok amadan.net/oficina/equipo/internal/runner 8.834s
+ok amadan.net/oficina/equipo/internal/plan3test 8.383s
+ok amadan.net/oficina/equipo/internal/release 0.003s
+exit 0
+
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinator(InventoryObservation|CalibrationIsolation|LiveModeFakeCLI|FailureIsolatedFakeCLI)$' -count=1
+ok amadan.net/oficina/equipo/internal/directlive 34.332s
+exit 0
+
+CGO_ENABLED=0 go test ./internal/runner/provider/claude ./internal/runner/provider/codex -run '^Test(ClaudePermissionResponse|CodexApprovalResponse|CoordinatorToolCatalogBound|PlanWorkflowProviderPolicies)' -count=1
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 4.445s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 5.652s
+exit 0
+
+CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
+ok amadan.net/oficina/equipo/internal/equipo 0.102s
+exit 0
+
+CGO_ENABLED=0 go vet ./internal/coordinator ./internal/runner ./internal/runner/provider/codex ./internal/equipo/conversation ./internal/plan3test ./internal/directlive ./internal/release
+(no output)
+exit 0
+
+gofmt -l internal/directlive internal/equipo/conversation internal/plan3test internal/runner internal/release
+(no output)
+exit 0
+
+git diff --check
+(no output)
+exit 0
+
+
+```
+
+### Guard mutations
+
+Every mutation was restored immediately. The first suggestion-redaction mutation unexpectedly passed because byte slices had been encoded as base64. The strengthened structure assertions and `json.RawMessage` correction were applied, and the same redaction bypass then failed. All 13 distinct guard mutations ultimately failed through test assertions; none depended on a build failure. Final restored tests passed as recorded above.
+
+```text
+
+### retirement
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorToolJournalSettledBudget$' -count=1
+--- FAIL: TestCoordinatorToolJournalSettledBudget (0.10s)
+ coordinator_journal_fixes_test.go:46: settled turn retained 1 tool rows
+FAIL
+rastrillo-budget/v1 ran 103ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.105s
+FAIL
+
+exit 1; restored
+
+### reopen fence
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorToolJournalSettledBudget$' -count=1
+--- FAIL: TestCoordinatorToolJournalSettledBudget (0.12s)
+ coordinator_journal_fixes_test.go:49: delivered turn reopened
+FAIL
+rastrillo-budget/v1 ran 119ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.121s
+FAIL
+
+exit 1; restored
+
+### claim deduplication
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorToolJournalSettledBudget$' -count=1
+--- FAIL: TestCoordinatorToolJournalSettledBudget (3.30s)
+ coordinator_journal_fixes_test.go:55: provider_uncertain
+ runner.journal
+FAIL
+rastrillo-budget/v1 ran 3.3s
+FAIL amadan.net/oficina/equipo/internal/runner 3.302s
+FAIL
+
+exit 1; restored
+
+### lost acknowledgement recovery
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorToolJournalSettledBudget$' -count=1
+--- FAIL: TestCoordinatorToolJournalSettledBudget (3.89s)
+ coordinator_journal_fixes_test.go:68: open lost-ack replay lost its full claim 20
+FAIL
+rastrillo-budget/v1 ran 3.89s
+FAIL amadan.net/oficina/equipo/internal/runner 3.892s
+FAIL
+
+exit 1; restored
+
+### question redaction
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorToolRedaction$' -count=1
+--- FAIL: TestCoordinatorToolRedaction (0.38s)
+ --- FAIL: TestCoordinatorToolRedaction/ask_person (0.01s)
+ coordinator_tool_fixes_test.go:28: tool result leaked secret
+ coordinator_tool_fixes_test.go:33: stored message leaked secret
+ coordinator_tool_fixes_test.go:36: stored question leaked secret
+FAIL
+rastrillo-budget/v1 ran 377ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.421s
+FAIL
+
+exit 1; restored
+
+### suggestion redaction
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorToolRedaction$' -count=1
+ok amadan.net/oficina/equipo/internal/plan3test 0.419s
+
+exit 0; restored
+
+### suggestion redaction
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorToolRedaction$' -count=1
+--- FAIL: TestCoordinatorToolRedaction (0.38s)
+ --- FAIL: TestCoordinatorToolRedaction/suggest_preference (0.01s)
+ coordinator_tool_fixes_test.go:42: tool result leaked secret
+ --- FAIL: TestCoordinatorToolRedaction/suggest_specialist (0.01s)
+ coordinator_tool_fixes_test.go:42: tool result leaked secret
+ --- FAIL: TestCoordinatorToolRedaction/suggest_playbook (0.01s)
+ coordinator_tool_fixes_test.go:42: tool result leaked secret
+ coordinator_tool_fixes_test.go:47: stored message leaked secret
+FAIL
+rastrillo-budget/v1 ran 379ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.421s
+FAIL
+
+exit 1; restored
+
+### persist message sources
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorToolSources$' -count=1
+--- FAIL: TestCoordinatorToolSources (0.37s)
+ coordinator_tools_test.go:257: message sources lost: {"SourceRefs":[],"ID":"LGP62SE5VFWWHCZDFFL3OAVE5Y","ConversationID":"4FGEWUX5T5GIZC6ACZLHSZTU2V","ThreadID":"","AuthorKind":"coordinator","AuthorID":"coordinator:JYDQA6CRUNZUQ56KQDKIYTUIIN","Body":"Project recommendation","Sequence":2,"Revision":1,"CreatedAt":"2026-11-04T02:23:06.50306182Z"}
+FAIL
+rastrillo-budget/v1 ran 367ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.410s
+FAIL
+
+exit 1; restored
+
+### superseded payload
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorToolQuestionSupersession$' -count=1
+--- FAIL: TestCoordinatorToolQuestionSupersession (0.54s)
+ --- FAIL: TestCoordinatorToolQuestionSupersession/same_turn (0.37s)
+ coordinator_tool_fixes_test.go:76: inconsistent supersession: column=superseded/2 payload={ID:LLQYMVB4BGUKYJSFR7ZSYDK6AQ MessageID:BHCSAVV5KLEGS3F5PU4RLWU766 TurnID:EFADBPDH5DBMCHVIZPFFK5ABXZ Prompt:First? State:pending Options:[] Revision:1 Generation:1 ExpiresAt:2026-11-05 02:23:07.834860368 +0000 UTC}
+ --- FAIL: TestCoordinatorToolQuestionSupersession/earlier_delivered_turn (0.18s)
+ coordinator_tool_fixes_test.go:76: inconsistent supersession: column=superseded/2 payload={ID:2W7DVC6JFMRENIK5JFYRRP4O4W MessageID:EFWJVKABQCLROHIGKLXKLL72JA TurnID:earlier Prompt:First? State:pending Options:[] Revision:1 Generation:1 ExpiresAt:2026-11-05 02:23:08.002057746 +0000 UTC}
+FAIL
+rastrillo-budget/v1 ran 544ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.598s
+FAIL
+
+exit 1; restored
+
+### earlier turn supersession
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorToolQuestionSupersession$' -count=1
+--- FAIL: TestCoordinatorToolQuestionSupersession (0.54s)
+ --- FAIL: TestCoordinatorToolQuestionSupersession/earlier_delivered_turn (0.18s)
+ coordinator_tool_fixes_test.go:76: inconsistent supersession: column=pending/1 payload={ID:JRVIMSVE2ASMPZOVXVEW7U2AIO MessageID:NV2PPX4EYFGB4SUGW3UUX3SRH7 TurnID:earlier Prompt:First? State:pending Options:[] Revision:1 Generation:1 ExpiresAt:2026-11-05 02:23:09.710017073 +0000 UTC}
+FAIL
+rastrillo-budget/v1 ran 542ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.586s
+FAIL
+
+exit 1; restored
+
+### observed Codex inventory
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorInventoryObservation$' -count=1
+--- FAIL: TestCoordinatorInventoryObservation (0.00s)
+ --- FAIL: TestCoordinatorInventoryObservation/codex (0.00s)
+ --- FAIL: TestCoordinatorInventoryObservation/codex/malformed (0.00s)
+ coordinator_fixes_test.go:51: unobserved or widened inventory certified
+ --- FAIL: TestCoordinatorInventoryObservation/codex/missing (0.00s)
+ coordinator_fixes_test.go:51: unobserved or widened inventory certified
+FAIL
+rastrillo-budget/v1 ran 1ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.044s
+FAIL
+
+exit 1; restored
+
+### live source admission
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorLiveModeFakeCLI$' -count=1
+--- FAIL: TestCoordinatorLiveModeFakeCLI (3.65s)
+ driver_test.go:77: full fake CLI driver: exit status 1
+ === RUN TestDirectDriverFakeWorker
+ driver_test.go:162: claude-Coordinator: open: provider_policy_rejected
+ codex-Coordinator: open: provider_policy_rejected
+ claude-Coordinator/certification.json calibration: provider_policy_rejected
+ codex-Coordinator/certification.json calibration: provider_policy_rejected
+ --- FAIL: TestDirectDriverFakeWorker (0.25s)
+ FAIL
+ rastrillo-budget/v1 ran 252ms
+ FAIL amadan.net/oficina/equipo/internal/directlive 0.294s
+ FAIL
+FAIL
+rastrillo-budget/v1 ran 3.648s
+FAIL amadan.net/oficina/equipo/internal/directlive 3.689s
+FAIL
+
+exit 1; restored
+
+### independent specialist calibration
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorCalibrationIsolation$' -count=1
+--- FAIL: TestCoordinatorCalibrationIsolation (0.00s)
+ coordinator_fixes_test.go:70: coordinator failure poisoned specialist calibration [{2 3 true} {0 0 false}]
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.043s
+FAIL
+
+exit 1; restored
+
+### future preference tables
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorSuggestionOnly$' -count=1
+--- FAIL: TestCoordinatorSuggestionOnly (0.39s)
+ coordinator_tools_test.go:128: unexpected library or preference save
+FAIL
+rastrillo-budget/v1 ran 391ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.437s
+FAIL
+
+exit 1; restored
+
+```
+
+### Self-review and remaining concern
+
+The requested certifier is runnable against the real pinned executables and now requires observations. It does not make the pinned Codex policy certifiable by assertion. Source inspection of Codex `rust-v0.165.0` found that `add_mcp_resource_tools` registers `list_mcp_resources`, `list_mcp_resource_templates` and `read_mcp_resource` whenever an MCP server exists. No supported configuration switch to suppress those three tools was found. They violate the brief's exact empty-native inventory. The injected-extra-tools fixture proves the new certifier rejects this case and leaves specialist tuples intact. Resolving the native inventory requires a supported upstream control or a controller-approved change of transport/pin; this round does not relax the allowlist, patch the provider binary, or claim the later live run will pass.
+
+Primary source inspected (downloaded read-only, no provider invocation):
+
+- [https://github.com/openai/codex/blob/rust-v0.165.0/codex-rs/core/src/tools/spec_plan.rs](https://github.com/openai/codex/blob/rust-v0.165.0/codex-rs/core/src/tools/spec_plan.rs), `add_mcp_resource_tools` at line 1276.
+- [https://github.com/openai/codex/blob/rust-v0.165.0/codex-rs/core/src/session/world_state.rs](https://github.com/openai/codex/blob/rust-v0.165.0/codex-rs/core/src/session/world_state.rs), incremental tool declarations at line 170.
+- [https://github.com/openai/codex/blob/rust-v0.165.0/codex-rs/app-server/src/bespoke_event_handling.rs](https://github.com/openai/codex/blob/rust-v0.165.0/codex-rs/app-server/src/bespoke_event_handling.rs), raw response-item notifications at line 1217.
+
+Existing specialist Contract/Isolation/Recovery requirements also remain independent release gates; the coordinator fixture's observations do not constitute those certificates. Task 7 still owns production coordinator scheduling and delivery wiring. Unrequested review minors 1, 6, 7, 9 and 10 were left for their owning work.
+
+### Copy inventory and process
+
+No new or changed user-facing copy keys. All existing Task 6 pending keys remain pending in `internal/equipo/copy.go`. The revised provider-only certification instruction is:
+
+```text
+Certification action: question. Call ask_person exactly once with request_id=certification-question, message_id=fixture-message, question=Which disposable case should be checked?, options=[]. Do not call any other tool.
+```
+
+No agents, copy-review server, live provider session, sign-in, enrolment, push, merge, deployment, full test suite or `make ci`. Go caches stayed at their defaults. Test processes were cleaned up by their fixtures. Task scratch was under `$TMPDIR/equipo-task6-fix` and is removed before commit. No `.claude/HANDOFF.md` was created. The report at the requested `.superpowers` path is ignored by Git; this verification record is also appended under Task 6 in the tracked controller report.
+
+### Files changed
+
+- `internal/directlive/calibration.go`
+- `internal/directlive/coordinator.go`
+- `internal/directlive/coordinator_fixes_test.go`
+- `internal/directlive/coordinator_inventory.go`
+- `internal/directlive/driver.go`
+- `internal/directlive/driver_test.go`
+- `internal/directlive/testdata/fake-cli.py`
+- `internal/equipo/conversation/models.go`
+- `internal/equipo/conversation/tools.go`
+- `internal/equipo/migrations/0021_coordinator_sources.sql`
+- `internal/equipo/migrations/schema.sql`
+- `internal/plan3test/conversation_test.go`
+- `internal/plan3test/coordinator_sources_migration_test.go`
+- `internal/plan3test/coordinator_tool_fixes_test.go`
+- `internal/plan3test/coordinator_tools_test.go`
+- `internal/plan3test/migration_test.go`
+- `internal/release/manifest.json`
+- `internal/runner/capture.go`
+- `internal/runner/coordinator_journal_fixes_test.go`
+- `internal/runner/coordinator_tool_journal.go`
+- `internal/runner/coordinator_tool_retirement.go`
+- `internal/runner/coordinator_tools_test.go`
+- `internal/runner/journal.go`
+- `internal/runner/provider/codex/coordinator.go`
+- `internal/runner/provider/codex/launcher.go`
+
+### Live-gate consumer fix and final checks
+
+Final review found that the build-tagged live gate stopped before reading any tuple whenever `Run` returned an error. The driver now returns `TupleFailures` only after saving a complete bundle; setup and storage failures keep their ordinary errors and still stop the gate. The live gate evaluates saved tuples in separate groups. `TestDirectLiveCoordinator` selects the coordinator cases and checks account/policy readback, observed empty inventory, the structured question and namespace controls. Specialist Contract, Isolation, Recovery and Calibration groups select specialist cases. A failed tuple cannot pass validation.
+
+The specialist manifest candidate excludes coordinator observations and requires at least one validated specialist policy. A coordinator-only bundle cannot create release authority. This is deliberate: the coordinator observations do not replace the existing refresh, isolation and recovery certificates. The pinned Codex resource-tool limitation remains a coordinator release blocker.
+
+Tests added for this consumer path were run red:
+
+```text
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorCertificationSelection$' -count=1
+--- FAIL: TestCoordinatorCertificationSelection (0.00s)
+ coordinator_fixes_test.go:82: Contract selected Coordinator: true
+exit 1
+
+CGO_ENABLED=0 go test ./internal/runner/provider -run '^TestCoordinatorCertificationGroup$' -count=1
+--- FAIL: TestCoordinatorCertificationGroup (0.00s)
+ direct_certification_test.go:136: complete coordinator observations rejected provider_policy_rejected
+exit 1
+```
+
+`TestCoordinatorManifestExclusion` builds a synthetic passing specialist bundle alongside a failed coordinator tuple and proves only the specialist reaches the candidate. The fake failure fixture also requires the typed saved-tuple error. Four further guards were mutated and restored, bringing this round to 17 distinct successful guard mutations:
+
+```text
+
+### separate live groups
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorCertificationSelection$' -count=1
+--- FAIL: TestCoordinatorCertificationSelection (0.00s)
+ coordinator_fixes_test.go:83: Contract selected Coordinator: true
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/directlive 0.051s
+FAIL
+exit 1; restored
+
+### failed tuple rejection
+CGO_ENABLED=0 go test ./internal/runner/provider -run '^TestCoordinatorCertificationGroup$' -count=1
+--- FAIL: TestCoordinatorCertificationGroup (0.00s)
+ direct_certification_test.go:151: failed coordinator tuple certified
+FAIL
+rastrillo-budget/v1 ran 2ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider 0.003s
+FAIL
+exit 1; restored
+
+### specialist candidate excludes coordinator
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorManifestExclusion$' -count=1
+--- FAIL: TestCoordinatorManifestExclusion (0.03s)
+ coordinator_certificate_test.go:58: coordinator failure blocked specialist candidate provider_policy_rejected
+FAIL
+rastrillo-budget/v1 ran 30ms
+FAIL amadan.net/oficina/equipo/internal/directlive 0.100s
+FAIL
+exit 1; restored
+
+### typed saved tuple failure
+CGO_ENABLED=0 go test ./internal/directlive -run '^TestCoordinatorFailureIsolatedFakeCLI$' -count=1
+--- FAIL: TestCoordinatorFailureIsolatedFakeCLI (33.72s)
+ driver_test.go:78: full fake CLI driver: exit status 1
+ === RUN TestDirectDriverFakeWorker
+ driver_test.go:156: coordinator failure not isolated: codex-Coordinator: open: inventory observed=false calls=1: provider_policy_rejected
+ --- FAIL: TestDirectDriverFakeWorker (28.72s)
+ FAIL
+ rastrillo-budget/v1 ran 28.718s
+ FAIL amadan.net/oficina/equipo/internal/directlive 28.774s
+ FAIL
+FAIL
+rastrillo-budget/v1 ran 33.722s
+FAIL amadan.net/oficina/equipo/internal/directlive 33.816s
+FAIL
+exit 1; restored
+
+```
+
+Final consumer verification, including compilation of the live gate while selecting only an offline unit test:
+
+```text
+CGO_ENABLED=0 go test ./internal/directlive ./internal/runner/provider -run '^TestCoordinator(InventoryObservation|CalibrationIsolation|LiveModeFakeCLI|FailureIsolatedFakeCLI|CertificationSelection|CertificationGroup|ManifestExclusion)$' -count=1
+ok amadan.net/oficina/equipo/internal/directlive 33.523s
+ok amadan.net/oficina/equipo/internal/runner/provider 0.004s
+exit 0
+
+CGO_ENABLED=0 go test -tags direct_live ./internal/runner/provider -run '^TestCoordinatorCertificationGroup$' -count=1
+ok amadan.net/oficina/equipo/internal/runner/provider 0.043s
+exit 0
+
+CGO_ENABLED=0 go test ./internal/runner/provider -run '^TestDirectLiveGate' -count=1
+ok amadan.net/oficina/equipo/internal/runner/provider 0.032s
+exit 0
+
+CGO_ENABLED=0 go vet ./internal/directlive ./internal/runner/provider
+(no output)
+exit 0
+
+CGO_ENABLED=0 go vet -tags direct_live ./internal/runner/provider
+(no output)
+exit 0
+
+gofmt -l internal/directlive internal/runner/provider
+(no output)
+exit 0
+
+git diff --check
+(no output)
+exit 0
+
+
+```
+
+The final journal review preserved the old unknown-acknowledgement behaviour. A nonexistent event ID returns an error without fencing admission. The added assertion first failed with `provider_uncertain / runner.journal`, then passed after separating that case from storage failure:
+
+```text
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorToolJournalRetirementScope$' -count=1
+--- FAIL: TestCoordinatorToolJournalRetirementScope (0.04s)
+ coordinator_journal_fixes_test.go:123: provider_uncertain
+ runner.journal
+exit 1
+
+CGO_ENABLED=0 go test ./internal/runner -run '^Test(CoordinatorToolJournal|RunnerJournalCrashBoundaries)' -count=1
+ok amadan.net/oficina/equipo/internal/runner 4.561s
+exit 0
+CGO_ENABLED=0 go vet ./internal/runner
+(no output), exit 0
+gofmt -l internal/runner
+(no output), exit 0
+git diff --check
+(no output), exit 0
+```
+
+Additional changed files for the gate consumer: `internal/directlive/certificate.go`, `internal/directlive/coordinator_certificate_test.go`, `internal/directlive/tuple_failures.go`, `internal/runner/provider/direct_groups.go`, `internal/runner/provider/direct_certification.go`, `internal/runner/provider/direct_certification_test.go`, `internal/runner/provider/direct_requirements.json`, and `internal/runner/provider/live_test.go`. No additional user-facing strings were introduced.
diff --git a/internal/directlive/calibration.go b/internal/directlive/calibration.go
index c7b1d400..5085bcad 100644
--- a/internal/directlive/calibration.go
+++ b/internal/directlive/calibration.go
@@ -5,7 +5,7 @@ import "amadan.net/oficina/equipo/internal/runner/provider"
func familyUsage(records []provider.DirectEvidence, name string) []provider.LiveUsage {
var samples []provider.LiveUsage
for _, e := range records {
- if e.Provider == name {
+ if e.Provider == name && e.Specialist != "Coordinator" {
samples = append(samples, e.Usage...)
}
}
diff --git a/internal/directlive/certificate.go b/internal/directlive/certificate.go
index 7fdac519..98ffb9d8 100644
--- a/internal/directlive/certificate.go
+++ b/internal/directlive/certificate.go
@@ -40,6 +40,10 @@ func ManifestCandidate(root string) error {
if json.Unmarshal(raw, &e) != nil {
return errEvidence
}
+ // Coordinator observations alone grant no refresh or release authority.
+ if !provider.DirectGroupIncludes("Contract", e.Specialist) {
+ continue
+ }
for _, group := range []string{"Contract", "Isolation", "Recovery", "Calibration"} {
if err = e.ValidateGroup(filepath.Dir(path), group); err != nil {
return err
@@ -61,6 +65,9 @@ func ManifestCandidate(root string) error {
}
binaries = e.Binaries
}
+ if len(m.DirectPolicies) == 0 {
+ return errEvidence
+ }
for _, name := range []string{"claude", "codex", "codex-code-mode-host", "bwrap", "equipo-tool-proxy"} {
version := map[string]string{"claude": m.Claude, "codex": m.Codex, "codex-code-mode-host": m.Codex, "bwrap": m.BwrapVersion, "equipo-tool-proxy": m.LauncherVersion}[name]
m.Binaries = append(m.Binaries, release.BinaryDigest{Name: name, Version: version, SHA256: binaries[name]})
diff --git a/internal/directlive/coordinator.go b/internal/directlive/coordinator.go
index abc52c8c..932bf78c 100644
--- a/internal/directlive/coordinator.go
+++ b/internal/directlive/coordinator.go
@@ -4,8 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
- "slices"
- "strings"
+ "sync"
"amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/equipo/team"
@@ -14,19 +13,20 @@ import (
"amadan.net/oficina/equipo/internal/runnerproto"
)
-// Coordinator fixtures exercise a fresh session with no native tools. The
-// specialist certification sequence requires native approval and a checkout;
-// it cannot certify this distinct policy. Live certification stays unavailable.
+// The provider is real during live certification; only Equipo operations use a local fixture.
func (x *exercise) coordinatorFixture(ctx context.Context) (provider.DirectEvidence, error) {
- if x.d.source != "fake-cli" {
- return x.evidence, provider.ErrPolicy
- }
deadline, _ := ctx.Deadline()
c := runnerproto.CoordinatorClaim{ToolCopy: equipo.CoordinatorToolCopy(), Binding: runnerproto.CoordinatorBinding{ID: "fixture-binding", Generation: 1}, Turn: runnerproto.CoordinatorTurn{ID: "certification-1", Generation: 1}, Scope: team.Scope{Account: team.AccountID(x.d.cfg.MachineFingerprint)}, Handle: team.Handle{Attempt: 1, Fence: 1}, LeaseDeadline: deadline, AttemptDeadline: deadline, Brief: runnerproto.RunnerBrief{Selection: runnerproto.Selection{Provider: x.launch.Selection.Provider, AccountID: x.launch.Selection.AccountID, Model: x.launch.Selection.Model, Isolation: team.IsolationSnapshot{Status: "confined"}}}}
var err error
- calls := 0
+ var calls int
+ var callMu sync.Mutex
x.proxy, err = runner.OpenCoordinatorToolProxy(ctx, runner.CoordinatorToolBinding{Claim: c, Journal: x.journal, Current: func(ctx context.Context) error { return ctx.Err() }, Call: func(_ context.Context, call runnerproto.CoordinatorToolCall) (runnerproto.CoordinatorToolResult, error) {
+ if call.Name != "ask_person" {
+ return runnerproto.CoordinatorToolResult{}, provider.ErrPolicy
+ }
+ callMu.Lock()
calls++
+ callMu.Unlock()
return runnerproto.CoordinatorToolResult{ResourceID: "fixture-question", Revision: 1, Value: json.RawMessage(`{"state":"pending"}`)}, nil
}})
if err != nil {
@@ -39,43 +39,34 @@ func (x *exercise) coordinatorFixture(ctx context.Context) (provider.DirectEvide
return x.evidence, fmt.Errorf("coordinator launcher open: %w", err)
}
defer x.launcher.Close(context.Background(), x.session)
+ if x.evidence.Provider == "codex" {
+ x.evidence.CodexPolicy = &provider.LiveCodexPolicy{ApprovalPolicy: "on-request", ApprovalsReviewer: "user", StrictConfig: true, DenyProfile: true}
+ }
+ for _, key := range []string{"account-version-readback", "effective-policy-readback"} {
+ if err = x.check(key, true, x.session); err != nil {
+ return x.evidence, err
+ }
+ }
x.events, err = x.launcher.Events(ctx, x.session)
if err != nil {
return x.evidence, fmt.Errorf("coordinator fixture line: %w", err)
}
- frames, err := x.turn(ctx, "Certification action: question. Use the bound Equipo clarification tool.")
+ frames, err := x.turn(ctx, "Certification action: question. Call ask_person exactly once with request_id=certification-question, message_id=fixture-message, question=Which disposable case should be checked?, options=[]. Do not call any other tool.")
if err != nil {
return x.evidence, fmt.Errorf("coordinator fixture line: %w", err)
}
- observed := x.evidence.Provider == "codex" // Codex config/catalog readback is checked at Open.
- if x.evidence.Provider == "claude" {
- want := append([]string{"mcp__equipo__permission"}, provider.ActionProfile{Action: "coordinate"}.MCPTools()...)
- slices.Sort(want)
- for _, raw := range frames {
- var init struct {
- Type, Subtype string
- Tools []string
- }
- if json.Unmarshal(raw, &init) == nil && init.Type == "system" && init.Subtype == "init" {
- slices.Sort(init.Tools)
- observed = slices.Equal(init.Tools, want)
- for _, tool := range init.Tools {
- if !strings.HasPrefix(tool, "mcp__equipo__") {
- return x.evidence, provider.ErrPolicy
- }
- }
- }
- }
+ callMu.Lock()
+ defer callMu.Unlock()
+ observed := coordinatorInventory(x.evidence.Provider, x.session.ID, frames)
+ if err = x.check("coordinator-empty-native-inventory", observed, frames); err != nil {
+ return x.evidence, err
+ }
+ if err = x.check("coordinator-structured-question", calls == 1, map[string]int{"calls": calls}); err != nil {
+ return x.evidence, err
}
if !observed || calls != 1 {
return x.evidence, fmt.Errorf("inventory observed=%v calls=%d: %w", observed, calls, provider.ErrPolicy)
}
- if err = x.check("coordinator-empty-native-inventory", observed, json.RawMessage(x.launch.Policy.Manifest)); err != nil {
- return x.evidence, fmt.Errorf("coordinator fixture line: %w", err)
- }
- if err = x.check("coordinator-structured-question", calls == 1, map[string]int{"calls": calls}); err != nil {
- return x.evidence, fmt.Errorf("coordinator fixture line: %w", err)
- }
if err = x.namespaceChecks(ctx); err != nil {
return x.evidence, fmt.Errorf("coordinator namespace: %w", err)
}
diff --git a/internal/directlive/coordinator_certificate_test.go b/internal/directlive/coordinator_certificate_test.go
new file mode 100644
index 00000000..8b3b75f1
--- /dev/null
+++ b/internal/directlive/coordinator_certificate_test.go
@@ -0,0 +1,71 @@
+package directlive
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/release"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func TestCoordinatorManifestExclusion(t *testing.T) {
+ root := t.TempDir()
+ raw := []byte("synthetic manifest-selection fixture")
+ hash := provider.DigestDirectEvidence(raw)
+ observation := provider.LiveObservation{Status: "pass", Artifact: "capture.json", SHA256: hash, Detail: "synthetic unit-test fixture"}
+ e := provider.DirectEvidence{Schema: 1, Source: "direct-live", RunID: "fixture", Provider: "codex", ProviderVersion: "0.165.0", LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: provider.PolicyVersion, PolicyHash: strings.Repeat("a", 64), AccountID: "fixture", HomeID: "fixture", Model: "fixture", Specialist: "Engineering", AuthHost: "auth.example.com", ConfigSHA256: hash, Artifacts: map[string]string{"capture.json": hash}, Checks: map[string]provider.LiveObservation{}, Binaries: map[string]string{}, Usage: []provider.LiveUsage{{Input: 1, Output: 1, Complete: true}}, Funding: provider.LiveFunding{Calls: 1, Seconds: 60, InputTokens: 1000, OutputTokens: 1000, JobInput: 23000, JobOutput: 23000, ProjectInputHeadroom: 23000, ProjectOutputHeadroom: 23000, TeamInputHeadroom: 23000, TeamOutputHeadroom: 23000}, CodexPolicy: &provider.LiveCodexPolicy{ApprovalPolicy: "on-request", ApprovalsReviewer: "user", StrictConfig: true, DenyProfile: true}}
+ for _, name := range []string{"claude", "codex", "codex-code-mode-host", "bwrap", "runner", "equipo-tool-proxy"} {
+ e.Binaries[name] = hash
+ }
+ for _, group := range []string{"Contract", "Isolation", "Recovery", "Calibration"} {
+ for _, key := range provider.DirectRequirements(group) {
+ e.Checks[key] = observation
+ }
+ }
+ for _, surface := range []string{"native", "shell", "search", "image", "mcp"} {
+ tool := provider.LiveTool{Name: surface, Surface: surface, Exposed: true, Probes: map[string]provider.LiveObservation{}}
+ for _, path := range []string{"selected-home", "other-home", "runner-state", "/egress", "/tool/equipo.sock", "symlink", "/proc/*/root", "/proc/*/fd", "/dev/fd"} {
+ o := observation
+ o.Status = "denied"
+ tool.Probes[path] = o
+ }
+ e.Tools = append(e.Tools, tool)
+ }
+ for _, name := range []string{"specialist", "coordinator"} {
+ dir := filepath.Join(root, name)
+ if err := os.Mkdir(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "capture.json"), raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if name == "coordinator" {
+ e.Specialist = "Coordinator"
+ e.PolicyHash = strings.Repeat("b", 64)
+ e.Checks = map[string]provider.LiveObservation{"tuple-completed": {Status: "not-certified"}}
+ }
+ if err := save(dir, "certification.json", e); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := save(root, "index.json", []string{"specialist/certification.json", "coordinator/certification.json"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := ManifestCandidate(root); err != nil {
+ t.Fatal("coordinator failure blocked specialist candidate", err)
+ }
+ saved, err := os.ReadFile(filepath.Join(root, "candidate-manifest.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var candidate release.Manifest
+ if err = json.Unmarshal(saved, &candidate); err != nil {
+ t.Fatal(err)
+ }
+ if len(candidate.DirectPolicies) != 1 || candidate.DirectPolicies[0].PolicyHash != strings.Repeat("a", 64) {
+ t.Fatal("coordinator gained release authority")
+ }
+}
diff --git a/internal/directlive/coordinator_fixes_test.go b/internal/directlive/coordinator_fixes_test.go
new file mode 100644
index 00000000..4c6b3b8f
--- /dev/null
+++ b/internal/directlive/coordinator_fixes_test.go
@@ -0,0 +1,87 @@
+package directlive
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func inventoryFrame(family, session string, names []string) []byte {
+ if family == "claude" {
+ return marshal(map[string]any{"type": "system", "subtype": "init", "session_id": session, "tools": names})
+ }
+ tools := []any{}
+ for _, n := range names {
+ tools = append(tools, map[string]any{"type": "function", "name": n, "parameters": map[string]any{"type": "object"}})
+ }
+ return marshal(map[string]any{"method": "rawResponseItem/completed", "params": map[string]any{"threadId": session, "turnId": "1", "item": map[string]any{"type": "additional_tools", "role": "developer", "tools": tools}}})
+}
+func TestCoordinatorInventoryObservation(t *testing.T) {
+ for _, family := range []string{"claude", "codex"} {
+ t.Run(family, func(t *testing.T) {
+ want := provider.ActionProfile{Action: "coordinate"}.MCPTools()
+ if family == "claude" {
+ want = append(want, "mcp__equipo__permission")
+ }
+ if family == "codex" {
+ members := []any{}
+ for _, name := range want {
+ members = append(members, map[string]any{"type": "function", "name": strings.TrimPrefix(name, "mcp__equipo__")})
+ }
+ namespaced := marshal(map[string]any{"method": "rawResponseItem/completed", "params": map[string]any{"threadId": "session", "item": map[string]any{"type": "additional_tools", "role": "developer", "tools": []any{map[string]any{"type": "namespace", "name": "mcp__equipo", "tools": members}}}}})
+ if !coordinatorInventory(family, "session", [][]byte{namespaced}) {
+ t.Fatal("pinned MCP namespace rejected")
+ }
+ }
+ good := inventoryFrame(family, "session", want)
+ if !coordinatorInventory(family, "session", [][]byte{good}) {
+ t.Fatal("valid observed inventory rejected")
+ }
+ for name, frames := range map[string][][]byte{
+ "missing": nil,
+ "foreign": {inventoryFrame(family, "foreign", want)},
+ "native": {inventoryFrame(family, "session", append(want, "exec_command"))},
+ "missing tool": {inventoryFrame(family, "session", want[:len(want)-1])},
+ "later native": {good, inventoryFrame(family, "session", []string{"exec_command"})},
+ "malformed": {json.RawMessage(`{"method":"rawResponseItem/completed","params":{}}`)},
+ } {
+ t.Run(name, func(t *testing.T) {
+ if coordinatorInventory(family, "session", frames) {
+ t.Fatal("unobserved or widened inventory certified")
+ }
+ })
+ }
+ })
+ }
+}
+func TestCoordinatorLiveModeFakeCLI(t *testing.T) {
+ t.Setenv("EQUIPO_FAKE_COORDINATOR_ONLY", "1")
+ t.Setenv("EQUIPO_FAKE_LIVE_MODE", "1")
+ TestDirectDriverFakeCLI(t)
+}
+func TestCoordinatorCalibrationIsolation(t *testing.T) {
+ records := []provider.DirectEvidence{
+ {Provider: "codex", Specialist: "Engineering", Usage: []provider.LiveUsage{{Complete: true, Input: 2, Output: 3}}},
+ {Provider: "codex", Specialist: "Coordinator", Usage: []provider.LiveUsage{{Complete: false}}},
+ }
+ got := familyUsage(records, "codex")
+ if len(got) != 1 || !got[0].Complete {
+ t.Fatal("coordinator failure poisoned specialist calibration", got)
+ }
+}
+
+func TestCoordinatorFailureIsolatedFakeCLI(t *testing.T) {
+ t.Setenv("EQUIPO_FAKE_BAD_COORDINATOR", "1")
+ TestDirectDriverFakeCLI(t)
+}
+
+func TestCoordinatorCertificationSelection(t *testing.T) {
+ for _, group := range []string{"Contract", "Isolation", "Recovery", "Calibration", "Coordinator"} {
+ for _, role := range []string{"Engineering", "Review", "Coordinator"} {
+ if got := provider.DirectGroupIncludes(group, role); got != ((group == "Coordinator") == (role == "Coordinator")) {
+ t.Fatalf("%s selected %s: %v", group, role, got)
+ }
+ }
+ }
+}
diff --git a/internal/directlive/coordinator_inventory.go b/internal/directlive/coordinator_inventory.go
new file mode 100644
index 00000000..04fb8bda
--- /dev/null
+++ b/internal/directlive/coordinator_inventory.go
@@ -0,0 +1,100 @@
+package directlive
+
+import (
+ "encoding/json"
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+// Codex's incremental catalog is emitted as a raw additional_tools item on a
+// fresh thread. Missing observations and later additions both fail closed.
+func coordinatorInventory(family, session string, frames [][]byte) bool {
+ want := provider.ActionProfile{Action: "coordinate"}.MCPTools()
+ if family == "claude" {
+ want = append(want, "mcp__equipo__permission")
+ }
+ slices.Sort(want)
+ observed := false
+ for _, raw := range frames {
+ var v struct {
+ Type, Subtype, Method string
+ Session string `json:"session_id"`
+ Tools []string
+ Params struct {
+ ThreadID string `json:"threadId"`
+ Item struct {
+ Type, Role string
+ Tools []json.RawMessage
+ }
+ }
+ }
+ if json.Unmarshal(raw, &v) != nil {
+ return false
+ }
+ var names []string
+ switch family {
+ case "claude":
+ if v.Type != "system" || v.Subtype != "init" {
+ continue
+ }
+ if v.Session != session {
+ return false
+ }
+ names = v.Tools
+ case "codex":
+ if v.Method != "rawResponseItem/completed" || v.Params.Item.Type != "additional_tools" {
+ continue
+ }
+ if v.Params.ThreadID != session || v.Params.Item.Role != "developer" {
+ return false
+ }
+ var ok bool
+ names, ok = coordinatorCatalogNames(v.Params.Item.Tools)
+ if !ok {
+ return false
+ }
+ default:
+ return false
+ }
+ slices.Sort(names)
+ if !slices.Equal(names, want) {
+ return false
+ }
+ observed = true
+ }
+ return observed
+}
+func coordinatorCatalogNames(raw []json.RawMessage) ([]string, bool) {
+ var names []string
+ for _, r := range raw {
+ var tool struct {
+ Type, Name string
+ Tools []json.RawMessage
+ }
+ if json.Unmarshal(r, &tool) != nil {
+ return nil, false
+ }
+ if tool.Type == "namespace" {
+ // Pinned Responses Lite serializes plain function tools in functions.
+ if tool.Name != "functions" && tool.Name != "mcp__equipo" {
+ return nil, false
+ }
+ members, ok := coordinatorCatalogNames(tool.Tools)
+ if !ok {
+ return nil, false
+ }
+ if tool.Name == "mcp__equipo" {
+ for i := range members {
+ members[i] = "mcp__equipo__" + members[i]
+ }
+ }
+ names = append(names, members...)
+ } else if tool.Type == "function" && tool.Name != "" {
+ names = append(names, tool.Name)
+ } else {
+ return nil, false
+ }
+ }
+ return names, true
+}
diff --git a/internal/directlive/driver.go b/internal/directlive/driver.go
index 8be10772..1253e0ca 100644
--- a/internal/directlive/driver.go
+++ b/internal/directlive/driver.go
@@ -94,6 +94,11 @@ func runRoles(ctx context.Context, c provider.DirectLiveConfig, config []byte, p
}
if err != nil {
failures = append(failures, fmt.Errorf("%s: %w", name, err))
+ failed := exercise{root: dir, evidence: e}
+ if saveErr := failed.check("tuple-completed", false, map[string]string{"error": err.Error()}); saveErr != nil {
+ return saveErr
+ }
+ e = failed.evidence
}
records = append(records, e)
index = append(index, name+"/certification.json")
@@ -101,7 +106,9 @@ func runRoles(ctx context.Context, c provider.DirectLiveConfig, config []byte, p
}
pooled := map[string][]provider.LiveUsage{"claude": familyUsage(records, "claude"), "codex": familyUsage(records, "codex")}
for i, e := range records {
- e.Usage = pooled[e.Provider]
+ if e.Specialist != "Coordinator" {
+ e.Usage = pooled[e.Provider]
+ }
dir := filepath.Dir(filepath.Join(root, index[i]))
x := exercise{d: d, root: dir, evidence: e}
for _, name := range provider.DirectRequirements("Calibration") {
@@ -112,7 +119,7 @@ func runRoles(ctx context.Context, c provider.DirectLiveConfig, config []byte, p
}
}
if err = x.calibration(); err != nil {
- failures = append(failures, err)
+ failures = append(failures, fmt.Errorf("%s calibration: %w", index[i], err))
}
x.evidence.Artifacts, err = bindArtifacts(dir)
if err != nil {
@@ -125,7 +132,10 @@ func runRoles(ctx context.Context, c provider.DirectLiveConfig, config []byte, p
if err = save(root, "index.json", index); err != nil {
return err
}
- return errors.Join(failures...)
+ if len(failures) > 0 {
+ return &TupleFailures{Failures: failures}
+ }
+ return nil
}
func (p Paths) verify() (map[string]string, error) {
hashes := map[string]string{}
diff --git a/internal/directlive/driver_test.go b/internal/directlive/driver_test.go
index 90c37d09..45499f8a 100644
--- a/internal/directlive/driver_test.go
+++ b/internal/directlive/driver_test.go
@@ -8,6 +8,7 @@ import (
"amadan.net/oficina/equipo/internal/runnerproto"
"context"
"encoding/json"
+ "errors"
"os"
"os/exec"
"path/filepath"
@@ -29,6 +30,10 @@ func TestDirectDriverFakeCLI(t *testing.T) {
if err != nil {
t.Fatal(err)
}
+ badCoordinator := os.Getenv("EQUIPO_FAKE_BAD_COORDINATOR") == "1"
+ if badCoordinator {
+ script = []byte(strings.Replace(string(script), "names=mcp()", "names=mcp()\n if 'mcp__equipo__read_project' in names:names+=['list_mcp_resources','list_mcp_resource_templates','read_mcp_resource']", 1))
+ }
pins := map[string]string{}
for _, name := range []string{"claude", "codex", "codex-code-mode-host"} {
raw := script
@@ -135,7 +140,22 @@ func TestDirectDriverFakeWorker(t *testing.T) {
return runRoles(ctx, c, raw, p, source, answer, paths, []string{"Coordinator"})
}
}
- if err := runFixture(context.Background(), c, marshal(c), p, "fake-cli", answer, paths); err != nil {
+ if os.Getenv("EQUIPO_FAKE_BAD_COORDINATOR") == "1" {
+ runFixture = func(ctx context.Context, c provider.DirectLiveConfig, raw []byte, p Paths, source string, answer answerFunc, paths PolicyPaths) error {
+ return runRoles(ctx, c, raw, p, source, answer, paths, []string{"Engineering", "Coordinator"})
+ }
+ }
+ source := "fake-cli"
+ if os.Getenv("EQUIPO_FAKE_LIVE_MODE") == "1" {
+ source = "direct-live"
+ }
+ runErr := runFixture(context.Background(), c, marshal(c), p, source, answer, paths)
+ if os.Getenv("EQUIPO_FAKE_BAD_COORDINATOR") == "1" {
+ var tuples *TupleFailures
+ if !errors.As(runErr, &tuples) || !strings.Contains(runErr.Error(), "codex-Coordinator") || strings.Contains(runErr.Error(), "Engineering") {
+ t.Fatalf("coordinator failure not isolated: %v", runErr)
+ }
+ } else if err := runErr; err != nil {
files, _ := filepath.Glob(filepath.Join(c.EvidenceDir, "*", "diagnostics.json"))
for _, p := range files {
raw, _ := os.ReadFile(p)
@@ -143,6 +163,9 @@ func TestDirectDriverFakeWorker(t *testing.T) {
}
t.Fatal(err)
}
+ if os.Getenv("EQUIPO_FAKE_COORDINATOR_ONLY") == "1" && ManifestCandidate(c.EvidenceDir) == nil {
+ t.Fatal("coordinator-only observations became release authority")
+ }
entries, err := os.ReadDir(paths.ScratchRoot)
if err != nil || len(entries) != 0 {
t.Fatalf("driver left runtime scratch: %v %v", entries, err)
@@ -156,6 +179,9 @@ func TestDirectDriverFakeWorker(t *testing.T) {
if os.Getenv("EQUIPO_FAKE_COORDINATOR_ONLY") == "1" {
want = 2
}
+ if os.Getenv("EQUIPO_FAKE_BAD_COORDINATOR") == "1" {
+ want = 4
+ }
if json.Unmarshal(raw, &index) != nil || len(index) != want {
t.Fatal("missing driver coverage")
}
@@ -166,6 +192,12 @@ func TestDirectDriverFakeWorker(t *testing.T) {
}
var e provider.DirectEvidence
if strings.Contains(name, "Coordinator") {
+ if os.Getenv("EQUIPO_FAKE_BAD_COORDINATOR") == "1" && strings.HasPrefix(name, "codex-") {
+ if json.Unmarshal(raw, &e) != nil || e.Checks["tuple-completed"].Status != "not-certified" || e.Checks["coordinator-empty-native-inventory"].Status != "not-certified" {
+ t.Fatal("failed coordinator tuple absent", string(raw))
+ }
+ continue
+ }
if json.Unmarshal(raw, &e) != nil || e.Checks["coordinator-empty-native-inventory"].Status != "pass" || e.Checks["coordinator-structured-question"].Status != "pass" {
t.Fatalf("empty inventory fixture failed: %s", raw)
}
@@ -177,6 +209,9 @@ func TestDirectDriverFakeWorker(t *testing.T) {
if json.Unmarshal(raw, &e) != nil || len(e.Usage) == 0 || e.Checks["workspace-positive-control"].Status != "pass" {
t.Fatalf("driver did not observe tools and usage: %s", raw)
}
+ if e.Checks["tuple-completed"].Status == "not-certified" || e.Checks["complete-input-output"].Status != "pass" {
+ t.Fatal("specialist contaminated by coordinator", name)
+ }
for _, check := range []string{"person-native-approval", "real-question-answer", "policy-escalation-denied", "equipo-broker-approval", "stale-broker-denied", "invalid-broker-denied", "clean-session-resume", "mid-turn-runner-kill", "durable-replay", "no-redispatch", "unknown-usage-retained", "pidfd-exit", "same-identity-generation-fresh-preflight-bind", "same-identity-continued-availability", "identity-marker-tamper-denied"} {
if e.Checks[check].Status != "pass" {
t.Fatalf("%s did not exercise %s: %+v", name, check, e.Checks[check])
diff --git a/internal/directlive/testdata/fake-cli.py b/internal/directlive/testdata/fake-cli.py
index a0b2c890..f92db2ce 100644
--- a/internal/directlive/testdata/fake-cli.py
+++ b/internal/directlive/testdata/fake-cli.py
@@ -29,6 +29,7 @@ for line in sys.stdin:
source={'type':'sessionFlags'}
result={'config':config,'layers':[{'name':source,'version':'fixture','config':config}],'origins':{k:{'name':source,'version':'fixture'} for k in config}}
elif method in ['thread/start','thread/resume']:
+ raw_events=req['params'].get('experimentalRawEvents',False)
result={'thread':{'id':'thread-fixture'},'model':'fixture-model','modelProvider':'openai','cwd':'/workspace','approvalPolicy':'on-request','approvalsReviewer':'user','activePermissionProfile':{'id':'equipo','extends':None},'runtimeWorkspaceRoots':['/workspace']}
elif method=='turn/start':
turn+=1
@@ -39,7 +40,10 @@ for line in sys.stdin:
if method!='turn/start':continue
prompt=req['params']['input'][0]['text']
session='thread-fixture'
- mcp()
+ names=mcp()
+ if 'mcp__equipo__read_project' in names:
+ if not raw_events or not config.get('features',{}).get('incremental_tools'):raise RuntimeError('missing observed catalog configuration')
+ emit({'method':'rawResponseItem/completed','params':{'threadId':session,'turnId':str(turn),'item':{'type':'additional_tools','role':'developer','tools':[{'type':'function','name':n,'parameters':{'type':'object'}} for n in names]}}})
else:
turn+=1
session=req['session_id']
diff --git a/internal/directlive/tuple_failures.go b/internal/directlive/tuple_failures.go
new file mode 100644
index 00000000..74933848
--- /dev/null
+++ b/internal/directlive/tuple_failures.go
@@ -0,0 +1,10 @@
+package directlive
+
+import "errors"
+
+// TupleFailures means the complete bundle was saved, with failures attached to
+// individual tuples. Setup and storage errors do not use this type.
+type TupleFailures struct{ Failures []error }
+
+func (e *TupleFailures) Error() string { return errors.Join(e.Failures...).Error() }
+func (e *TupleFailures) Unwrap() []error { return e.Failures }
diff --git a/internal/equipo/conversation/models.go b/internal/equipo/conversation/models.go
index 8ce6fc2f..1685f244 100644
--- a/internal/equipo/conversation/models.go
+++ b/internal/equipo/conversation/models.go
@@ -2,9 +2,13 @@
// Its operations use the caller's transaction and authority callbacks.
package conversation
-import "time"
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "time"
+)
type Message struct {
+ SourceRefs []team.SourceRef
ID, ConversationID, ThreadID, AuthorKind, AuthorID, Body string
Sequence, Revision int64
CreatedAt time.Time
@@ -39,9 +43,10 @@ type Thread struct {
func (Thread) TableName() string { return "conversation_threads" }
type messageRecord struct {
- ID string `gorm:"primaryKey"`
- StreamID string `gorm:"uniqueIndex:conversation_sequence,priority:1"`
- Sequence int64 `gorm:"uniqueIndex:conversation_sequence,priority:2"`
+ SourceRefs []team.SourceRef `gorm:"serializer:json"`
+ ID string `gorm:"primaryKey"`
+ StreamID string `gorm:"uniqueIndex:conversation_sequence,priority:1"`
+ Sequence int64 `gorm:"uniqueIndex:conversation_sequence,priority:2"`
ConversationID, ThreadID, AuthorKind, AuthorID, Body string
Revision int64
CreatedAt time.Time
@@ -49,7 +54,7 @@ type messageRecord struct {
func (messageRecord) TableName() string { return "conversation_messages" }
func (r messageRecord) message() Message {
- return Message{ID: r.ID, ConversationID: r.ConversationID, ThreadID: r.ThreadID, AuthorKind: r.AuthorKind, AuthorID: r.AuthorID, Body: r.Body, Sequence: r.Sequence, Revision: r.Revision, CreatedAt: r.CreatedAt}
+ return Message{SourceRefs: r.SourceRefs, ID: r.ID, ConversationID: r.ConversationID, ThreadID: r.ThreadID, AuthorKind: r.AuthorKind, AuthorID: r.AuthorID, Body: r.Body, Sequence: r.Sequence, Revision: r.Revision, CreatedAt: r.CreatedAt}
}
type cardRecord struct {
diff --git a/internal/equipo/conversation/tools.go b/internal/equipo/conversation/tools.go
index 098d4e38..e9ccdf83 100644
--- a/internal/equipo/conversation/tools.go
+++ b/internal/equipo/conversation/tools.go
@@ -4,7 +4,6 @@ import (
"context"
"crypto/rand"
"encoding/json"
- "errors"
"strconv"
"time"
@@ -126,7 +125,11 @@ func (e *Engine) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, c C
}
}
case *coordinator.AskPerson:
- out, err = cs.ask(row, call.RequestID, *a, e.Now())
+ safe := *a
+ if err = json.Unmarshal(e.Redact(mustCoordinatorJSON(a)), &safe); err != nil {
+ return err
+ }
+ out, err = cs.ask(row, call.RequestID, safe, e.Now())
if err != nil {
return err
}
@@ -151,12 +154,16 @@ func (e *Engine) CallCoordinatorTool(ctx context.Context, p RunnerPrincipal, c C
if err != nil {
return err
}
+ msg.SourceRefs = a.SourceRefs
+ if err = tx.Model(&messageRecord{}).Where("id=?", msg.ID).Select("source_refs").Updates(map[string]any{"source_refs": string(mustCoordinatorJSON(a.SourceRefs))}).Error; err != nil {
+ return err
+ }
out, err = result(msg.ID, msg.Revision, map[string]any{"message": msg, "source_refs": a.SourceRefs})
if err != nil {
return err
}
case *coordinator.SuggestPreference, *coordinator.SuggestDraft:
- out, err = cs.suggest(row, call.Name, args)
+ out, err = cs.suggest(row, call.Name, json.RawMessage(e.Redact(mustCoordinatorJSON(args))))
if err != nil {
return err
}
@@ -256,23 +263,30 @@ func (e *Engine) toolScope(tx *gorm.DB, cs *Store, row TurnRecord, sel runnerpro
return nil
}
func (s *Store) ask(row TurnRecord, request string, a coordinator.AskPerson, now time.Time) (CoordinatorToolResult, error) {
- var old QuestionRecord
- err := s.tx.Where("binding_id=? AND turn_id=? AND generation=? AND state='pending'", row.BindingID, row.ID, row.Generation).First(&old).Error
- if err == nil {
+ var pending []QuestionRecord
+ if err := s.tx.Where("binding_id=? AND generation=? AND state='pending' AND turn_id IN (SELECT id FROM coordinator_turns WHERE conversation_id=?)", row.BindingID, row.Generation, row.ConversationID).Find(&pending).Error; err != nil {
+ return CoordinatorToolResult{}, err
+ }
+ var duplicate *coordinator.ClarificationQuestion
+ for _, old := range pending {
var q coordinator.ClarificationQuestion
- if err = json.Unmarshal([]byte(old.Payload), &q); err != nil {
+ if err := json.Unmarshal([]byte(old.Payload), &q); err != nil {
return CoordinatorToolResult{}, err
}
- if q.Prompt == a.Question && runnerproto.EventHash(q.Options) == runnerproto.EventHash(a.Options) && now.Before(q.ExpiresAt) {
- return result(q.ID, q.Revision, q)
+ if old.TurnID == row.ID && q.Prompt == a.Question && runnerproto.EventHash(q.Options) == runnerproto.EventHash(a.Options) && now.Before(q.ExpiresAt) && duplicate == nil {
+ duplicate = &q
+ continue
+ }
+ q.State, q.Revision = "superseded", old.Revision+1
+ if err := s.tx.Model(&QuestionRecord{}).Where("id=?", q.ID).Select("state", "revision", "payload").Updates(map[string]any{"state": q.State, "revision": q.Revision, "payload": string(mustCoordinatorJSON(q))}).Error; err != nil {
+ return CoordinatorToolResult{}, err
}
- if err = s.tx.Model(&QuestionRecord{}).Where("id=?", q.ID).Select("state", "revision").Updates(map[string]any{"state": "superseded", "revision": gorm.Expr("revision+1")}).Error; err != nil {
+ if err := s.tx.Model(&cardRecord{}).Where("resource_id=? AND kind='clarification'", q.ID).Select("revision").Updates(map[string]any{"revision": q.Revision}).Error; err != nil {
return CoordinatorToolResult{}, err
}
- err = gorm.ErrRecordNotFound
}
- if !errors.Is(err, gorm.ErrRecordNotFound) {
- return CoordinatorToolResult{}, err
+ if duplicate != nil {
+ return result(duplicate.ID, duplicate.Revision, duplicate)
}
q := coordinator.ClarificationQuestion{ID: rand.Text(), MessageID: a.MessageID, TurnID: row.ID, Prompt: a.Question, Options: a.Options, State: "pending", Revision: 1, Generation: row.Generation, ExpiresAt: now.Add(24 * time.Hour)}
raw, err := json.Marshal(q)
diff --git a/internal/equipo/migrations/0021_coordinator_sources.sql b/internal/equipo/migrations/0021_coordinator_sources.sql
new file mode 100644
index 00000000..080b95bf
--- /dev/null
+++ b/internal/equipo/migrations/0021_coordinator_sources.sql
@@ -0,0 +1 @@
+ALTER TABLE conversation_messages ADD COLUMN source_refs text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index bf6a4337..1624a027 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -352,7 +352,7 @@ CREATE TABLE conversations (id text PRIMARY KEY, team_id text, person text, revi
CREATE UNIQUE INDEX conversation_person ON conversations(team_id,person);
CREATE TABLE conversation_threads (id text PRIMARY KEY, task_id text, team_id text, revision integer, last_sequence integer);
CREATE UNIQUE INDEX conversation_task ON conversation_threads(task_id);
-CREATE TABLE conversation_messages (id text PRIMARY KEY, stream_id text, sequence integer, conversation_id text, thread_id text, author_kind text, author_id text, body text, revision integer, created_at datetime);
+CREATE TABLE conversation_messages (id text PRIMARY KEY, stream_id text, sequence integer, conversation_id text, thread_id text, author_kind text, author_id text, body text, revision integer, created_at datetime, source_refs text);
CREATE UNIQUE INDEX conversation_sequence ON conversation_messages(stream_id,sequence);
CREATE TABLE conversation_cards (id text PRIMARY KEY, stream_id text, kind text, resource_id text, sequence integer, revision integer);
CREATE INDEX conversation_card_stream ON conversation_cards(stream_id);
diff --git a/internal/plan3test/conversation_test.go b/internal/plan3test/conversation_test.go
index b29cf316..ee1e27e8 100644
--- a/internal/plan3test/conversation_test.go
+++ b/internal/plan3test/conversation_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"html/template"
+ "reflect"
"strings"
"sync"
"testing"
@@ -75,7 +76,7 @@ func TestConversationMessageReplay(t *testing.T) {
f := newFixture(t)
m := send(t, f, owner, "", "hello", "once")
again := send(t, f, owner, "", "hello", "once")
- if m != again || m.Sequence != 1 || m.Revision != 1 || m.AuthorKind != "person" || m.AuthorID != owner.Address || m.CreatedAt.Location().String() != "UTC" {
+ if !reflect.DeepEqual(m, again) || m.Sequence != 1 || m.Revision != 1 || m.AuthorKind != "person" || m.AuthorID != owner.Address || m.CreatedAt.Location().String() != "UTC" {
t.Fatal("unstable replay or attribution", m, again)
}
if f.count(t, "SELECT count(*) FROM conversation_messages") != 1 || f.count(t, "SELECT count(*) FROM conversation_outboxes") != 1 {
@@ -120,7 +121,7 @@ func TestConversationRouteOnce(t *testing.T) {
must(t, e)
third, e := f.Store.RouteMessage(ctx, owner, secret.ID, task.ID, equipo.Mutation{RequestID: "route-again"})
must(t, e)
- if m != again || m != third {
+ if !reflect.DeepEqual(m, again) || !reflect.DeepEqual(m, third) {
t.Fatal("route replay changed reply")
}
if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", task.ID) != 1 || f.count(t, "SELECT count(*) FROM conversation_routes") != 1 {
@@ -253,7 +254,7 @@ func TestConversationReplayScopeAndPreconditions(t *testing.T) {
send(t, f, owner, "", "second", "second")
replay, e := f.Store.SendMessage(ctx, owner, "", "first", mutation)
must(t, e)
- if replay != m {
+ if !reflect.DeepEqual(replay, m) {
t.Fatal("replay rejected original revision")
}
mutation.Revision++
diff --git a/internal/plan3test/coordinator_sources_migration_test.go b/internal/plan3test/coordinator_sources_migration_test.go
new file mode 100644
index 00000000..24cb289b
--- /dev/null
+++ b/internal/plan3test/coordinator_sources_migration_test.go
@@ -0,0 +1,48 @@
+package plan3test
+
+import (
+ "io"
+ "log/slog"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+)
+
+func TestCoordinatorMessageSourcesUpgrade(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "sources.db")
+ d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
+ must(t, err)
+ defer d.Close()
+ old := &migrate.Set{}
+ for _, m := range equipo.BootSchema.All() {
+ if m.ID != "equipo/0021_coordinator_sources" {
+ old.Add(m)
+ }
+ }
+ _, err = migrate.Apply(ctx, d, old)
+ must(t, err)
+ _, err = d.Writer().Exec("INSERT INTO conversation_messages(id,body) VALUES('legacy','retained')")
+ must(t, err)
+ result, err := migrate.Apply(ctx, d, equipo.BootSchema)
+ must(t, err)
+ if len(result.Applied) != 1 || result.Applied[0] != "equipo/0021_coordinator_sources" {
+ t.Fatal(result.Applied)
+ }
+ var body string
+ var empty bool
+ must(t, d.Writer().QueryRow("SELECT body,source_refs IS NULL FROM conversation_messages WHERE id='legacy'").Scan(&body, &empty))
+ if body != "retained" || !empty {
+ t.Fatal("legacy message changed")
+ }
+ fresh := newFixture(t)
+ upgraded, err := migrate.Read(ctx, d.Writer())
+ must(t, err)
+ baseline, err := migrate.Read(ctx, fresh.DB.Writer())
+ must(t, err)
+ if !upgraded.Equal(baseline) {
+ t.Fatal(upgraded.Diff(baseline))
+ }
+}
diff --git a/internal/plan3test/coordinator_tool_fixes_test.go b/internal/plan3test/coordinator_tool_fixes_test.go
new file mode 100644
index 00000000..f1096414
--- /dev/null
+++ b/internal/plan3test/coordinator_tool_fixes_test.go
@@ -0,0 +1,86 @@
+package plan3test
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestCoordinatorToolRedaction(t *testing.T) {
+ f, x, p, c := claimTools(t)
+ secret := "Bearer abcdefghijklmnopqrstuvwxyz123456"
+ cases := []struct {
+ name string
+ args any
+ }{
+ {"ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": secret, "options": []map[string]string{{"id": "one", "label": secret}}}},
+ {"suggest_preference", map[string]any{"source_message_id": c.Turn.MessageID, "text": secret}},
+ {"suggest_specialist", map[string]any{"source_message_ids": []string{c.Turn.MessageID}, "draft": map[string]string{"name": "Draft", "instructions": secret}}},
+ {"suggest_playbook", map[string]any{"source_message_ids": []string{c.Turn.MessageID}, "draft": map[string]string{"name": "Draft", "instructions": secret}}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ out := toolCall(t, x, p, c, tc.name, tc.name, tc.args)
+ if strings.HasPrefix(tc.name, "suggest_") {
+ var envelope struct{ Result map[string]any }
+ must(t, json.Unmarshal(out.Value, &envelope))
+ if len(envelope.Result) == 0 {
+ t.Fatal("suggestion result lost its structure")
+ }
+ var body string
+ must(t, f.DB.Writer().QueryRow("SELECT body FROM conversation_messages WHERE id=?", out.ResourceID).Scan(&body))
+ var value map[string]any
+ must(t, json.Unmarshal([]byte(body), &value))
+ if len(value) == 0 {
+ t.Fatal("suggestion body lost its structure")
+ }
+ }
+ if strings.Contains(string(out.Value), "abcdefghijklmnopqrstuvwxyz123456") {
+ t.Error("tool result leaked secret")
+ }
+ })
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator' AND body LIKE '%abcdefghijklmnopqrstuvwxyz123456%'") != 0 {
+ t.Error("stored message leaked secret")
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_questions WHERE payload LIKE '%abcdefghijklmnopqrstuvwxyz123456%'") != 0 {
+ t.Error("stored question leaked secret")
+ }
+}
+
+func TestCoordinatorToolQuestionSupersession(t *testing.T) {
+ for _, earlier := range []bool{false, true} {
+ name := "same turn"
+ if earlier {
+ name = "earlier delivered turn"
+ }
+ t.Run(name, func(t *testing.T) {
+ f, x, p, c := claimTools(t)
+ first := toolCall(t, x, p, c, "first", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "First?", "options": []any{}})
+ if earlier {
+ // Keep the admitted current turn intact; move the old question to a
+ // delivered predecessor in the same binding and conversation.
+ f.exec(t, `INSERT INTO coordinator_turns(id,binding_id,conversation_id,person,generation,state) SELECT 'earlier',binding_id,conversation_id,person,generation,'delivered' FROM coordinator_turns WHERE id=?`, c.Turn.ID)
+ f.exec(t, `UPDATE coordinator_questions SET turn_id='earlier',payload=json_set(payload,'$.TurnID','earlier') WHERE id=?`, first.ResourceID)
+ }
+ toolCall(t, x, p, c, "second", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Next?", "options": []any{}})
+ var payload, state string
+ var rev int64
+ must(t, f.DB.Writer().QueryRow("SELECT state,revision,payload FROM coordinator_questions WHERE id=?", first.ResourceID).Scan(&state, &rev, &payload))
+ var q runnerproto.ClarificationQuestion
+ must(t, json.Unmarshal([]byte(payload), &q))
+ if state != "superseded" || q.State != state || q.Revision != rev {
+ t.Fatalf("inconsistent supersession: column=%s/%d payload=%+v", state, rev, q)
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_questions WHERE state='pending'") != 1 {
+ t.Fatal("multiple pending questions")
+ }
+ if err := f.Store.AnswerClarification(ctx, owner, first.ResourceID, "", "old", equipo.Mutation{RequestID: "old", Revision: 1}); err == nil {
+ t.Fatal("superseded question accepted")
+ }
+ })
+ }
+}
diff --git a/internal/plan3test/coordinator_tools_test.go b/internal/plan3test/coordinator_tools_test.go
index ee34f2d6..a800c7ed 100644
--- a/internal/plan3test/coordinator_tools_test.go
+++ b/internal/plan3test/coordinator_tools_test.go
@@ -101,7 +101,12 @@ func TestCoordinatorProjectInference(t *testing.T) {
}
func TestCoordinatorSuggestionOnly(t *testing.T) {
f, x, p, c := claimTools(t)
+ // Future library migrations must not change this behaviour assertion.
+ f.exec(t, "CREATE TABLE IF NOT EXISTS preferences(id text, state text)")
+ f.exec(t, "CREATE TABLE IF NOT EXISTS playbooks(id text)")
beforeSpecialists := f.count(t, "SELECT count(*) FROM specialists")
+ beforePreferences := f.count(t, "SELECT count(*) FROM preferences")
+ beforePlaybooks := f.count(t, "SELECT count(*) FROM playbooks")
for _, name := range []string{"suggest_specialist", "suggest_playbook"} {
toolCall(t, x, p, c, name, name, map[string]any{"source_message_ids": []string{c.Turn.MessageID}, "draft": map[string]any{"name": "Suggested", "instructions": "Consider this"}})
}
@@ -119,7 +124,7 @@ func TestCoordinatorSuggestionOnly(t *testing.T) {
if f.count(t, "SELECT count(*) FROM tasks") != before {
t.Fatal("prose executed")
}
- if f.count(t, "SELECT count(*) FROM specialists") != beforeSpecialists || f.count(t, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name IN ('playbooks','preferences')") != 0 {
+ if f.count(t, "SELECT count(*) FROM specialists") != beforeSpecialists || f.count(t, "SELECT count(*) FROM preferences") != beforePreferences || f.count(t, "SELECT count(*) FROM playbooks") != beforePlaybooks {
t.Fatal("unexpected library or preference save")
}
}
@@ -236,7 +241,26 @@ func TestCoordinatorToolSources(t *testing.T) {
}
must(t, json.Unmarshal(read.Value, &value))
args := map[string]any{"body": "Project recommendation", "source_refs": []team.SourceRef{value.Result.Ref}}
- toolCall(t, x, p, c, "sourced", "post_message", args)
+ posted := toolCall(t, x, p, c, "sourced", "post_message", args)
+ page, err := f.Store.Conversation(ctx, owner, "", 100)
+ must(t, err)
+ found := false
+ for _, msg := range page.Messages {
+ if msg.ID != posted.ResourceID {
+ continue
+ }
+ raw, err := json.Marshal(msg)
+ must(t, err)
+ var projection struct{ SourceRefs []team.SourceRef }
+ must(t, json.Unmarshal(raw, &projection))
+ if !reflect.DeepEqual(projection.SourceRefs, []team.SourceRef{value.Result.Ref}) {
+ t.Fatalf("message sources lost: %s", raw)
+ }
+ found = true
+ }
+ if !found {
+ t.Fatal("posted message absent")
+ }
value.Result.Ref.Hash = strings.Repeat("0", 64)
args["source_refs"] = []team.SourceRef{value.Result.Ref}
raw, _ := json.Marshal(args)
diff --git a/internal/plan3test/migration_test.go b/internal/plan3test/migration_test.go
index f07243fa..f8988066 100644
--- a/internal/plan3test/migration_test.go
+++ b/internal/plan3test/migration_test.go
@@ -19,7 +19,7 @@ func TestConversationMigrationUpgrade(t *testing.T) {
t.Cleanup(func() { must(t, d.Close()) })
old := &migrate.Set{}
for _, m := range equipo.BootSchema.All() {
- if m.ID != "equipo/0019_conversation" {
+ if m.ID != "equipo/0019_conversation" && m.ID != "equipo/0021_coordinator_sources" {
old.Add(m)
}
}
@@ -33,7 +33,7 @@ func TestConversationMigrationUpgrade(t *testing.T) {
before := f.count(t, "SELECT count(*) FROM audit_events")
result, e := migrate.Apply(ctx, d, equipo.BootSchema)
must(t, e)
- if !reflect.DeepEqual(result.Applied, []string{"equipo/0019_conversation"}) {
+ if !reflect.DeepEqual(result.Applied, []string{"equipo/0019_conversation", "equipo/0021_coordinator_sources"}) {
t.Fatal("wrong upgrade", result.Applied)
}
var saved equipo.Task
diff --git a/internal/release/manifest.json b/internal/release/manifest.json
index 22cf80e1..2854ec9c 100644
--- a/internal/release/manifest.json
+++ b/internal/release/manifest.json
@@ -120,7 +120,7 @@
{
"provider": "codex",
"action": "coordinate",
- "inventory_hash": "4c910ce3627df86de9114cbf3eb7007052ef711c06c97551f62e612eb88b6317",
+ "inventory_hash": "439feb9ef31873621697f1bfbd156d7d07b672ea132e670c1ca35e7deff97831",
"status": "uncertified"
}
]
diff --git a/internal/runner/capture.go b/internal/runner/capture.go
index 77a54e16..3a946440 100644
--- a/internal/runner/capture.go
+++ b/internal/runner/capture.go
@@ -19,7 +19,7 @@ import (
const MaxFrameBytes = 1 << 20
const maxDiagnostics = 64 << 10
-const directPendingSize = `((SELECT COALESCE(SUM(length(body)+COALESCE(length(result),0)),0) FROM coordinator_tools)+(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM direct_frames WHERE pending=1)+(SELECT COALESCE(SUM(length(body)),0) FROM direct_events WHERE projected=0))`
+const directPendingSize = `((SELECT COALESCE(SUM(length(body)),0) FROM coordinator_tool_claims)+(SELECT COALESCE(SUM(length(body)+COALESCE(length(result),0)),0) FROM coordinator_tools)+(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM direct_frames WHERE pending=1)+(SELECT COALESCE(SUM(length(body)),0) FROM direct_events WHERE projected=0))`
type captureFactory struct{ journal *Journal }
diff --git a/internal/runner/coordinator_journal_fixes_test.go b/internal/runner/coordinator_journal_fixes_test.go
new file mode 100644
index 00000000..e2c34ef7
--- /dev/null
+++ b/internal/runner/coordinator_journal_fixes_test.go
@@ -0,0 +1,146 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestCoordinatorToolJournalSettledBudget(t *testing.T) {
+ ctx := context.Background()
+ path := filepath.Join(t.TempDir(), "private", "journal.db")
+ j, err := OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer func() { j.Close() }()
+ j.maxBytes = 64 << 10
+ c := runnerproto.CoordinatorClaim{}
+ c.Binding.ID = "binding"
+ c.Binding.Generation = 1
+ c.Context.Messages = []runnerproto.CoordinatorMessage{{Body: strings.Repeat("context", 1024)}}
+ session := provider.Session{ID: "session", AttemptKey: "attempt", Provider: "claude"}
+ call := runnerproto.CoordinatorToolCall{RequestID: "r", Name: "post_message", Arguments: json.RawMessage(`{"body":"hello","source_refs":[]}`)}
+ result := runnerproto.CoordinatorToolResult{ResourceID: "message", Revision: 1, Value: json.RawMessage(`{}`)}
+ for i := 0; i < 40; i++ {
+ e := journalEvent(fmt.Sprintf("delivery-%d", i), int64(i+1))
+ e.Kind = "coordinator.delivery"
+ e.TurnID = fmt.Sprintf("turn-%d", i)
+ e.TaskID = e.TurnID
+ e.AssignmentID = e.TurnID
+ c.Turn.ID = e.TurnID
+ c.Scope = e.Scope
+ c.Handle = e.Handle
+ mustJournal(t, j.submitCoordinatorTool(ctx, c, session, call))
+ mustJournal(t, j.ackCoordinatorTool(ctx, c, session, call, result))
+ mustJournal(t, j.Append(ctx, e))
+ mustJournal(t, j.Ack(ctx, e.ID))
+ mustJournal(t, j.AdmissionAllowed(ctx))
+ var count int
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM coordinator_tools").Scan(&count))
+ if count != 0 {
+ t.Fatalf("settled turn retained %d tool rows", count)
+ }
+ if err = j.reserveCoordinatorTool(ctx, c, session, call); err == nil {
+ t.Fatal("delivered turn reopened")
+ }
+ }
+ c.Turn.ID = "open"
+ for i := 0; i < 20; i++ {
+ call.RequestID = fmt.Sprint(i)
+ mustJournal(t, j.submitCoordinatorTool(ctx, c, session, call))
+ }
+ var size int64
+ mustJournal(t, j.db.QueryRow("SELECT "+directPendingSize).Scan(&size))
+ if size > 24<<10 {
+ t.Fatalf("claim context duplicated across tools: %d", size)
+ }
+ mustJournal(t, j.Close())
+ j, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ pending, err := j.CoordinatorToolSubmissions(ctx, 128)
+ mustJournal(t, err)
+ if len(pending) != 20 || runnerproto.EventHash(pending[0].Claim) != runnerproto.EventHash(c) {
+ t.Fatal("open lost-ack replay lost its full claim", len(pending))
+ }
+ for _, v := range pending {
+ mustJournal(t, j.ackCoordinatorTool(ctx, v.Claim, v.Session, v.Call, result))
+ }
+ // Acknowledged tools stay hash-bound until delivery, including across reopen.
+ changed := call
+ changed.Arguments = json.RawMessage(`{"body":"changed","source_refs":[]}`)
+ if j.reserveCoordinatorTool(ctx, c, session, changed) == nil {
+ t.Fatal("open acknowledged call lost replay hash")
+ }
+}
+
+func TestCoordinatorToolJournalLegacyUpgrade(t *testing.T) {
+ ctx := context.Background()
+ path := filepath.Join(t.TempDir(), "private", "journal.db")
+ j, err := OpenJournal(ctx, path)
+ mustJournal(t, err)
+ c := runnerproto.CoordinatorClaim{}
+ c.Binding.ID = "legacy"
+ c.Turn.ID = "legacy-turn"
+ session := provider.Session{ID: "legacy-session"}
+ call := runnerproto.CoordinatorToolCall{RequestID: "legacy-request", Name: "post_message", Arguments: json.RawMessage(`{"body":"hi","source_refs":[]}`)}
+ v := CoordinatorToolSubmission{Claim: c, Session: session, Call: call}
+ raw, err := json.Marshal(v)
+ mustJournal(t, err)
+ _, err = j.db.Exec(`INSERT INTO coordinator_tools(request_key,content_hash,binding,generation,turn,body,submitted,acked) VALUES(?,?,?,?,?,?,1,0)`, coordinatorToolKey(c, call), runnerproto.EventHash(v), c.Binding.ID, c.Binding.Generation, c.Turn.ID, raw)
+ mustJournal(t, err)
+ _, err = j.db.Exec(`DROP TABLE coordinator_tool_claims; DROP INDEX coordinator_tools_claim; DROP INDEX journal_coordinator_delivery; PRAGMA user_version=5`)
+ mustJournal(t, err)
+ mustJournal(t, j.Close())
+ j, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer j.Close()
+ pending, err := j.CoordinatorToolSubmissions(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 1 || runnerproto.EventHash(pending[0]) != runnerproto.EventHash(v) {
+ t.Fatal("migration lost legacy pending submission")
+ }
+ mustJournal(t, j.reserveCoordinatorTool(ctx, c, session, call))
+ var body string
+ mustJournal(t, j.db.QueryRow("SELECT body FROM coordinator_tools").Scan(&body))
+ if strings.Contains(body, `"claim":`) {
+ t.Fatal("legacy claim not compacted")
+ }
+}
+
+func TestCoordinatorToolJournalRetirementScope(t *testing.T) {
+ ctx := context.Background()
+ j, err := OpenJournal(ctx, filepath.Join(t.TempDir(), "private", "journal.db"))
+ mustJournal(t, err)
+ defer j.Close()
+ if j.Ack(ctx, "unknown") == nil {
+ t.Fatal("unknown event acknowledged")
+ }
+ mustJournal(t, j.AdmissionAllowed(ctx))
+ e := journalEvent("delivery", 1)
+ e.Kind = "coordinator.delivery"
+ e.TurnID = "settled"
+ c := runnerproto.CoordinatorClaim{Scope: e.Scope, Handle: e.Handle, Turn: runnerproto.CoordinatorTurn{ID: e.TurnID}}
+ session := provider.Session{ID: e.SessionID}
+ call := runnerproto.CoordinatorToolCall{RequestID: "request", Name: "post_message", Arguments: json.RawMessage(`{"body":"hello","source_refs":[]}`)}
+ mustJournal(t, j.submitCoordinatorTool(ctx, c, session, call))
+ open := c
+ open.Turn.ID = "uncertain"
+ mustJournal(t, j.submitCoordinatorTool(ctx, open, session, call))
+ mustJournal(t, j.Append(ctx, e))
+ pending, err := j.CoordinatorToolSubmissions(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 2 {
+ t.Fatal("unacknowledged delivery pruned replay")
+ }
+ mustJournal(t, j.Ack(ctx, e.ID))
+ pending, err = j.CoordinatorToolSubmissions(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 1 || pending[0].Claim.Turn.ID != "uncertain" {
+ t.Fatal("delivery pruned the uncertain turn", pending)
+ }
+}
diff --git a/internal/runner/coordinator_tool_journal.go b/internal/runner/coordinator_tool_journal.go
index 71540308..c86a1e1c 100644
--- a/internal/runner/coordinator_tool_journal.go
+++ b/internal/runner/coordinator_tool_journal.go
@@ -26,7 +26,7 @@ func (j *Journal) reserveCoordinatorTool(ctx context.Context, c runnerproto.Coor
return err
}
v := CoordinatorToolSubmission{Claim: c, Session: s, Call: call}
- raw, err := json.Marshal(v)
+ ref, claimRaw, raw, err := coordinatorClaimRecord(v)
if err != nil {
return err
}
@@ -39,6 +39,13 @@ func (j *Journal) reserveCoordinatorTool(ctx context.Context, c runnerproto.Coor
return j.storageFailure(ctx, err)
}
defer tx.Rollback()
+ delivered, err := coordinatorDelivered(ctx, tx, c, s)
+ if err != nil {
+ return err
+ }
+ if delivered {
+ return runnerproto.ErrInvalid
+ }
var old string
err = tx.QueryRowContext(ctx, "SELECT content_hash FROM coordinator_tools WHERE request_key=?", key).Scan(&old)
if err == nil {
@@ -57,9 +64,20 @@ func (j *Journal) reserveCoordinatorTool(ctx context.Context, c runnerproto.Coor
if err = tx.QueryRowContext(ctx, "SELECT count(*) FROM coordinator_tools WHERE binding=? AND generation=? AND turn=?", c.Binding.ID, c.Binding.Generation, c.Turn.ID).Scan(&count); err != nil {
return err
}
- if count >= 128 || size+int64(len(raw)) > j.maxBytes {
+ var exists int
+ if err = tx.QueryRowContext(ctx, "SELECT count(*) FROM coordinator_tool_claims WHERE claim_ref=?", ref).Scan(&exists); err != nil {
+ return err
+ }
+ extra := len(raw)
+ if exists == 0 {
+ extra += len(claimRaw)
+ }
+ if count >= 128 || size+int64(extra) > j.maxBytes {
return ErrJournal
}
+ if _, err = tx.ExecContext(ctx, "INSERT OR IGNORE INTO coordinator_tool_claims(claim_ref,turn_key,body) VALUES(?,?,?)", ref, coordinatorTurnKey(c, s), claimRaw); err != nil {
+ return err
+ }
if _, err = tx.ExecContext(ctx, "INSERT INTO coordinator_tools(request_key,content_hash,binding,generation,turn,body,result,acked) VALUES(?,?,?,?,?,?,NULL,0)", key, hash, c.Binding.ID, c.Binding.Generation, c.Turn.ID, raw); err != nil {
return err
}
@@ -90,7 +108,7 @@ func (j *Journal) ackCoordinatorTool(ctx context.Context, c runnerproto.Coordina
if err = tx.QueryRowContext(ctx, "SELECT "+directPendingSize).Scan(&size); err != nil {
return err
}
- if size+int64(len(raw)) > j.maxBytes {
+ if size+int64(len(raw)-len(old)) > j.maxBytes {
return ErrJournal
}
if _, err = tx.ExecContext(ctx, "UPDATE coordinator_tools SET result=?,acked=1 WHERE request_key=?", raw, key); err != nil {
@@ -102,21 +120,26 @@ func (j *Journal) CoordinatorToolSubmissions(ctx context.Context, limit int) ([]
if limit < 1 || limit > 128 {
return nil, runnerproto.ErrInvalid
}
- rows, err := j.db.QueryContext(ctx, "SELECT body FROM coordinator_tools WHERE acked=0 AND submitted=1 ORDER BY ordinal LIMIT ?", limit)
+ rows, err := j.db.QueryContext(ctx, "SELECT t.body,c.body FROM coordinator_tools t JOIN coordinator_tool_claims c ON c.claim_ref=json_extract(t.body,'$.claim_ref') WHERE t.acked=0 AND t.submitted=1 ORDER BY t.ordinal LIMIT ?", limit)
if err != nil {
return nil, err
}
defer rows.Close()
out := []CoordinatorToolSubmission{}
for rows.Next() {
- var raw []byte
+ var raw, claimRaw []byte
+ var record coordinatorToolRecord
var v CoordinatorToolSubmission
- if err = rows.Scan(&raw); err != nil {
+ if err = rows.Scan(&raw, &claimRaw); err != nil {
+ return nil, err
+ }
+ if err = json.Unmarshal(claimRaw, &v); err != nil {
return nil, err
}
- if err = json.Unmarshal(raw, &v); err != nil {
+ if err = json.Unmarshal(raw, &record); err != nil {
return nil, err
}
+ v.Call = record.Call
out = append(out, v)
}
return out, rows.Err()
diff --git a/internal/runner/coordinator_tool_retirement.go b/internal/runner/coordinator_tool_retirement.go
new file mode 100644
index 00000000..b28d2e7a
--- /dev/null
+++ b/internal/runner/coordinator_tool_retirement.go
@@ -0,0 +1,121 @@
+package runner
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type coordinatorToolRecord struct {
+ ClaimRef string `json:"claim_ref"`
+ Call runnerproto.CoordinatorToolCall `json:"call"`
+}
+
+func coordinatorTurnKey(c runnerproto.CoordinatorClaim, s provider.Session) string {
+ return runnerproto.EventHash([]any{c.Scope, c.Handle.Attempt, c.Handle.Fence, c.Turn.ID, s.ID})
+}
+func coordinatorClaimRecord(v CoordinatorToolSubmission) (string, []byte, []byte, error) {
+ call := v.Call
+ v.Call = runnerproto.CoordinatorToolCall{}
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return "", nil, nil, err
+ }
+ ref := runnerproto.EventHash(v)
+ body, _ := json.Marshal(coordinatorToolRecord{ClaimRef: ref, Call: call})
+ return ref, raw, body, nil
+}
+
+// Upgrade old full-claim rows without dropping submitted or acknowledged calls.
+func compactCoordinatorTools(ctx context.Context, tx *sql.Tx) error {
+ rows, err := tx.QueryContext(ctx, "SELECT request_key,body FROM coordinator_tools WHERE json_extract(body,'$.claim_ref') IS NULL")
+ if err != nil {
+ return err
+ }
+ type oldRow struct {
+ key string
+ raw []byte
+ }
+ var old []oldRow
+ for rows.Next() {
+ var v oldRow
+ if err = rows.Scan(&v.key, &v.raw); err != nil {
+ rows.Close()
+ return err
+ }
+ old = append(old, v)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return err
+ }
+ for _, row := range old {
+ var v CoordinatorToolSubmission
+ if err = json.Unmarshal(row.raw, &v); err != nil {
+ return err
+ }
+ ref, claim, body, err := coordinatorClaimRecord(v)
+ if err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, "INSERT OR IGNORE INTO coordinator_tool_claims(claim_ref,turn_key,body) VALUES(?,?,?)", ref, coordinatorTurnKey(v.Claim, v.Session), claim); err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, "UPDATE coordinator_tools SET body=? WHERE request_key=?", body, row.key); err != nil {
+ return err
+ }
+ }
+ delivered, err := tx.QueryContext(ctx, "SELECT id FROM journal_events WHERE acked=1 AND json_extract(body,'$.kind')='coordinator.delivery'")
+ if err != nil {
+ return err
+ }
+ var ids []string
+ for delivered.Next() {
+ var id string
+ if err = delivered.Scan(&id); err != nil {
+ delivered.Close()
+ return err
+ }
+ ids = append(ids, id)
+ }
+ err = delivered.Err()
+ delivered.Close()
+ if err != nil {
+ return err
+ }
+ for _, id := range ids {
+ if err = retireCoordinatorTools(ctx, tx, id); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+func coordinatorDelivered(ctx context.Context, tx *sql.Tx, c runnerproto.CoordinatorClaim, s provider.Session) (bool, error) {
+ var n int
+ err := tx.QueryRowContext(ctx, `SELECT count(*) FROM journal_events WHERE acked=1 AND json_extract(body,'$.kind')='coordinator.delivery' AND json_extract(body,'$.scope.Account')=? AND json_extract(body,'$.scope.Job')=? AND json_extract(body,'$.handle.Attempt')=? AND json_extract(body,'$.handle.Fence')=? AND json_extract(body,'$.turn_id')=? AND json_extract(body,'$.session_id')=?`, c.Scope.Account, c.Scope.Job, c.Handle.Attempt, c.Handle.Fence, c.Turn.ID, s.ID).Scan(&n)
+ return n > 0, err
+}
+func retireCoordinatorTools(ctx context.Context, tx *sql.Tx, id string) error {
+ var raw []byte
+ if err := tx.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE event_key=(SELECT event_key FROM journal_aliases WHERE id=?) AND acked=1", id).Scan(&raw); err != nil {
+ return err
+ }
+ var e runnerproto.Event
+ if err := json.Unmarshal(raw, &e); err != nil {
+ return err
+ }
+ if e.Kind != "coordinator.delivery" {
+ return nil
+ }
+ c := runnerproto.CoordinatorClaim{Scope: e.Scope, Handle: e.Handle, Turn: runnerproto.CoordinatorTurn{ID: e.TurnID}}
+ key := coordinatorTurnKey(c, provider.Session{ID: e.SessionID})
+ if _, err := tx.ExecContext(ctx, `DELETE FROM coordinator_tools WHERE json_extract(body,'$.claim_ref') IN (SELECT claim_ref FROM coordinator_tool_claims WHERE turn_key=?)`, key); err != nil {
+ return err
+ }
+ _, err := tx.ExecContext(ctx, "DELETE FROM coordinator_tool_claims WHERE turn_key=?", key)
+ return err
+}
diff --git a/internal/runner/coordinator_tools_test.go b/internal/runner/coordinator_tools_test.go
index 868f1a23..3e131061 100644
--- a/internal/runner/coordinator_tools_test.go
+++ b/internal/runner/coordinator_tools_test.go
@@ -224,7 +224,7 @@ func TestCoordinatorToolJournalUpgrade(t *testing.T) {
j, err := OpenJournal(ctx, path)
mustJournal(t, err)
mustJournal(t, j.Append(ctx, journalEvent("retained", 1)))
- _, err = j.db.Exec("DROP TABLE coordinator_tools; PRAGMA user_version=4")
+ _, err = j.db.Exec("DROP TABLE coordinator_tools; DROP TABLE coordinator_tool_claims; DROP INDEX journal_coordinator_delivery; PRAGMA user_version=4")
mustJournal(t, err)
mustJournal(t, j.Close())
j, err = OpenJournal(ctx, path)
@@ -232,7 +232,7 @@ func TestCoordinatorToolJournalUpgrade(t *testing.T) {
defer j.Close()
var version int
mustJournal(t, j.db.QueryRow("PRAGMA user_version").Scan(&version))
- if version != 5 {
+ if version != 6 {
t.Fatal("ordered migration missing", version)
}
pending, err := j.Pending(ctx, 10)
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 88965a89..6d5f3faa 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -83,7 +83,7 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
db.SetMaxOpenConns(1)
j := &Journal{db: db, path: path, maxBytes: MaxJournalBytes}
var version int
- if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 5 {
+ if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 6 {
db.Close()
return nil, ErrJournal
}
@@ -129,6 +129,16 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
CREATE INDEX coordinator_tools_turn ON coordinator_tools(binding,generation,turn);
PRAGMA user_version=5;`)
}
+ if err == nil && version < 6 {
+ _, err = tx.ExecContext(ctx, `CREATE TABLE coordinator_tool_claims(claim_ref TEXT PRIMARY KEY,turn_key TEXT NOT NULL,body BLOB NOT NULL);
+ CREATE INDEX coordinator_tool_claims_turn ON coordinator_tool_claims(turn_key);
+ CREATE INDEX coordinator_tools_claim ON coordinator_tools(json_extract(body,'$.claim_ref'));
+ CREATE INDEX journal_coordinator_delivery ON journal_events(json_extract(body,'$.scope.Account'),json_extract(body,'$.scope.Job'),json_extract(body,'$.handle.Attempt'),json_extract(body,'$.handle.Fence'),json_extract(body,'$.turn_id'),json_extract(body,'$.session_id')) WHERE acked=1 AND json_extract(body,'$.kind')='coordinator.delivery';
+ PRAGMA user_version=6;`)
+ if err == nil {
+ err = compactCoordinatorTools(ctx, tx)
+ }
+ }
if err == nil {
_, err = tx.ExecContext(ctx, "UPDATE journal_streams SET ready=0")
}
@@ -266,14 +276,36 @@ func (j *Journal) Pending(ctx context.Context, limit int) ([]Event, error) {
return result, rows.Err()
}
func (j *Journal) Ack(ctx context.Context, id string) error {
- result, err := j.db.ExecContext(ctx, "UPDATE journal_events SET acked=1 WHERE event_key=(SELECT event_key FROM journal_aliases WHERE id=?)", id)
+ missing := false
+ err := func() error {
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ result, err := tx.ExecContext(ctx, "UPDATE journal_events SET acked=1 WHERE event_key=(SELECT event_key FROM journal_aliases WHERE id=?)", id)
+ if err != nil {
+ return err
+ }
+ n, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if n != 1 {
+ missing = true
+ return ErrJournal
+ }
+ if err = retireCoordinatorTools(ctx, tx, id); err != nil {
+ return err
+ }
+ return tx.Commit()
+ }()
+ if missing {
+ return ErrJournal
+ }
if err != nil {
return j.storageFailure(ctx, err)
}
- n, err := result.RowsAffected()
- if err != nil || n != 1 {
- return ErrJournal
- }
return j.releaseDirectFrames(ctx)
}
func (j *Journal) RecordIntent(ctx context.Context, i provider.Intent) error {
diff --git a/internal/runner/provider/codex/coordinator.go b/internal/runner/provider/codex/coordinator.go
index 322d8699..fa491c5c 100644
--- a/internal/runner/provider/codex/coordinator.go
+++ b/internal/runner/provider/codex/coordinator.go
@@ -9,7 +9,7 @@ import (
// shell flag. This startup-only catalog removes that surface as well.
func coordinatorCatalog(model string) json.RawMessage {
return marshal(map[string]any{"models": []any{map[string]any{
- "slug": model, "display_name": model, "supported_reasoning_levels": []any{}, "shell_type": "disabled", "visibility": "list", "supported_in_api": true, "priority": 0,
+ "use_responses_lite": true, "slug": model, "display_name": model, "supported_reasoning_levels": []any{}, "shell_type": "disabled", "visibility": "list", "supported_in_api": true, "priority": 0,
"support_verbosity": false, "apply_patch_tool_type": nil, "truncation_policy": map[string]any{"mode": "bytes", "limit": 65536}, "experimental_supported_tools": []string{},
"include_apps_usage_instructions": false, "include_skills_usage_instructions": false, "include_plugin_usage_instructions": false, "supports_search_tool": false, "node_repl_disabled": true,
"model_messages": map[string]any{"instructions_template": "Use only the supplied Equipo tools. Text is commentary and grants no authority."},
@@ -17,6 +17,7 @@ func coordinatorCatalog(model string) json.RawMessage {
}
func configureCoordinator(settings map[string]any, model string) {
features := settings["features"].(map[string]any)
+ features["incremental_tools"] = true
for _, key := range []string{"shell_tool", "unified_exec", "apply_patch_freeform", "view_image", "search_tool", "web_search", "web_search_cached", "web_search_request", "standalone_web_search", "browser_use", "browser_use_external", "computer_use", "image_generation", "imagegenext", "js_repl", "code_mode", "code_mode_only", "code_mode_host", "tool_search", "code_mode_tool_search", "plugins", "remote_plugin", "skill_search", "memory_tool", "memories", "goals", "sleep_tool", "current_time_reminder", "request_permissions_tool", "default_mode_request_user_input", "send_message_to_user_async", "deferred_executor", "multi_agent_v2", "multi_agent_mode", "multi_agent_v2_dynamic_tools", "agent_message_board", "tool_suggest", "collaboration_modes", "context_management", "token_budget", "runtime_agent_instances", "multi_env_copy_file"} {
features[key] = false
}
diff --git a/internal/runner/provider/codex/launcher.go b/internal/runner/provider/codex/launcher.go
index 9344cac1..50b2e6dd 100644
--- a/internal/runner/provider/codex/launcher.go
+++ b/internal/runner/provider/codex/launcher.go
@@ -147,7 +147,11 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (p
in.ProviderVersion = Version
in.Settings = marshal(settings)
in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`)
- in.ThreadPolicy = marshal(map[string]any{"model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo", "runtimeWorkspaceRoots": []string{"/workspace"}, "config": settings})
+ thread := map[string]any{"model": model, "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo", "runtimeWorkspaceRoots": []string{"/workspace"}, "config": settings}
+ if in.Action == "coordinate" {
+ thread["experimentalRawEvents"] = true
+ }
+ in.ThreadPolicy = marshal(thread)
in.TurnPolicy = json.RawMessage(`{}`)
in.Argv = []string{"/opt/codex", "app-server", "--strict-config", "--listen", "stdio://"}
keys := make([]string, 0, len(settings))
diff --git a/internal/runner/provider/direct_certification.go b/internal/runner/provider/direct_certification.go
index b5b08c71..2cca8aa1 100644
--- a/internal/runner/provider/direct_certification.go
+++ b/internal/runner/provider/direct_certification.go
@@ -131,6 +131,12 @@ func DigestDirectEvidence(raw []byte) string {
}
func (e DirectEvidence) ValidateGroup(root, group string) error {
+ if o, ok := e.Checks["tuple-completed"]; ok && o.Status != "pass" {
+ return ErrPolicy
+ }
+ if group == "Coordinator" && e.Specialist != "Coordinator" {
+ return ErrPolicy
+ }
if len(e.Artifacts) == 0 {
return ErrPolicy
}
diff --git a/internal/runner/provider/direct_certification_test.go b/internal/runner/provider/direct_certification_test.go
index 7a9a4dd5..675f36ae 100644
--- a/internal/runner/provider/direct_certification_test.go
+++ b/internal/runner/provider/direct_certification_test.go
@@ -127,3 +127,27 @@ func TestDirectLiveGateAllArtifacts(t *testing.T) {
t.Fatal("tampered supplemental capture accepted")
}
}
+
+func TestCoordinatorCertificationGroup(t *testing.T) {
+ e, root := directEvidenceFixture(t)
+ e.Specialist = "Coordinator"
+ e.Tools = nil
+ for _, key := range DirectRequirements("Coordinator") {
+ e.Checks[key] = e.Checks["account-version-readback"]
+ }
+ if err := e.ValidateGroup(root, "Coordinator"); err != nil {
+ t.Fatal("complete coordinator observations rejected", err)
+ }
+ for _, key := range DirectRequirements("Coordinator") {
+ saved := e.Checks[key]
+ delete(e.Checks, key)
+ if e.ValidateGroup(root, "Coordinator") == nil {
+ t.Fatal("missing coordinator observation accepted", key)
+ }
+ e.Checks[key] = saved
+ }
+ e.Checks["tuple-completed"] = LiveObservation{Status: "not-certified"}
+ if e.ValidateGroup(root, "Coordinator") == nil {
+ t.Fatal("failed coordinator tuple certified")
+ }
+}
diff --git a/internal/runner/provider/direct_groups.go b/internal/runner/provider/direct_groups.go
new file mode 100644
index 00000000..c63044cd
--- /dev/null
+++ b/internal/runner/provider/direct_groups.go
@@ -0,0 +1,6 @@
+package provider
+
+// Coordinator observations use a separate gate from specialist execution.
+func DirectGroupIncludes(group, specialist string) bool {
+ return (group == "Coordinator") == (specialist == "Coordinator")
+}
diff --git a/internal/runner/provider/direct_requirements.json b/internal/runner/provider/direct_requirements.json
index b8cdf739..753db3fe 100644
--- a/internal/runner/provider/direct_requirements.json
+++ b/internal/runner/provider/direct_requirements.json
@@ -1,4 +1,10 @@
{
+ "Coordinator": [
+ "account-version-readback", "effective-policy-readback",
+ "coordinator-empty-native-inventory", "coordinator-structured-question",
+ "pid1-go-helper-owner", "private-network", "immutable-settings",
+ "settings-write-denied", "host-services-absent", "host-control-sockets-denied"
+ ],
"Contract": [
"account-version-readback", "effective-policy-readback", "inner-sandbox-enabled",
"immutable-settings", "strict-mcp", "exact-tool-inventory", "no-hooks-plugins",
diff --git a/internal/runner/provider/live_test.go b/internal/runner/provider/live_test.go
index de6075ab..22eb95bb 100644
--- a/internal/runner/provider/live_test.go
+++ b/internal/runner/provider/live_test.go
@@ -6,6 +6,7 @@ import (
"amadan.net/oficina/equipo/internal/directlive"
"context"
"encoding/json"
+ "errors"
"io"
"os"
"os/exec"
@@ -22,6 +23,8 @@ import (
var liveDriver sync.Once
var liveDriverError error
+func TestDirectLiveCoordinator(t *testing.T) { verifyDirectLiveGroup(t, "Coordinator") }
+
func TestDirectLiveContract(t *testing.T) { verifyDirectLiveGroup(t, "Contract") }
func TestDirectLiveIsolation(t *testing.T) { verifyDirectLiveGroup(t, "Isolation") }
func TestDirectLiveRecovery(t *testing.T) { verifyDirectLiveGroup(t, "Recovery") }
@@ -41,7 +44,11 @@ func verifyDirectLiveGroup(t *testing.T, group string) {
liveDriverError = directlive.Run(context.Background(), cfg, configRaw, directlive.EnvironmentPaths(os.Getenv))
})
if liveDriverError != nil {
- t.Fatal(liveDriverError)
+ var tuples *directlive.TupleFailures
+ if !errors.As(liveDriverError, &tuples) {
+ t.Fatal(liveDriverError)
+ }
+ t.Logf("driver saved per-tuple failures: %v", tuples)
}
pins := map[string]string{"claude": claude.ExecutableSHA256, "codex": codex.ExecutableSHA256, "codex-code-mode-host": codex.CodeModeHostSHA256}
digests := map[string]string{}
@@ -89,6 +96,9 @@ func verifyDirectLiveGroup(t *testing.T, group string) {
path := filepath.Join(cfg.EvidenceDir, name)
var e provider.DirectEvidence
readLiveJSON(t, path, &e)
+ if !provider.DirectGroupIncludes(group, e.Specialist) {
+ continue
+ }
if seen[e.Provider+"/"+e.PolicyHash] {
t.Fatal("duplicate certified policy")
}
@@ -117,7 +127,11 @@ func verifyDirectLiveGroup(t *testing.T, group string) {
})
coverage[e.Provider+"/"+e.Specialist] = true
}
- for _, key := range []string{"claude/Engineering", "claude/Review", "claude/Product", "codex/Engineering", "codex/Review"} {
+ requiredCoverage := []string{"claude/Engineering", "claude/Review", "claude/Product", "codex/Engineering", "codex/Review"}
+ if group == "Coordinator" {
+ requiredCoverage = []string{"claude/Coordinator", "codex/Coordinator"}
+ }
+ for _, key := range requiredCoverage {
if !coverage[key] {
t.Errorf("missing policy coverage: %s", key)
}