oficina / equipo Public

fix: contain direct faults per attempt and settle at the instance

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 8c9ecac28a20d02a6abaf4d333bdf3e24824b687 parent 5092058
12 files changed, +1,773 −63
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,224 −0
  • internal/equipo/runner_report_validation.go +13 −4
  • internal/equipotest/runner_api_test.go +6 −2
  • internal/equipotest/runner_events_test.go +94 −41
  • internal/runner/capture.go +15 −3
  • internal/runner/direct_events.go +23 −5
  • internal/runner/direct_fixes_test.go +356 −0
  • internal/runner/direct_recovery.go +11 −2
  • internal/runner/direct_recovery_test.go +15 −2
  • internal/runner/journal.go +13 −2
  • internal/runner/journal_reset.go +2 −1
  • internal/runner/journal_test.go +1 −1

CI passed — run details

diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index cd192789..d35bf47c 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -13650,3 +13650,1227 @@ New internal diagnostic code: runner.direct_uncertain. New recovery-state values
The offline durability/accounting implementation and targeted checks are complete. Runtime composition and any safe post-restart adapter rehydration remain explicit follow-on integration work as described above. Full CI and live certification were not run because the task forbids them here. The source-budget exception was adjusted for the required adjacent APIs; no time budget was raised.
No helper agent, provider reviewer, copy-review server, push, merge, deployment, README edit or .claude/HANDOFF.md was created. Default Go caches were retained. Test-owned subprocesses and pipes were stopped by their cleanup paths; hard-crash children exited and were waited. No listening server was started by this session. Only this task's scratch files are removed after this evidence is saved. The final commit uses the requested codex author and exact subject.
+
+
+## Task 7 fix round 1: contain direct faults and settle at the instance
+
+Status: DONE. All five findings against 5092058 are addressed.
+Branch: `plan-2b`.
+Commit subject: `fix: contain direct faults per attempt and settle at the instance` (65 characters).
+Author: `codex <codex~paul@keymail.dev>`.
+Work directory for every command below: `/home/paulca/amadan.net/oficina/equipo-plan-2b`.
+
+### Changes
+
+1. Capture contains and quarantines malformed, torn, oversized, stalled or failed-input attempts without permanently blocking the journal. Identity errors and missing caller-supplied attempt identities also leave unrelated work admissible. Real journal failures and failed quarantine still fence the journal. Tests admit a second attempt after the first fails. Projection failures now persist quarantine after containment too. Corrupt turn-table reads and SQLite FULL during intent writes retain their storage-error classification instead of being reported as identity or uncertain-turn errors.
+2. The private journal upgrades from version 2 to version 3 in the existing ordered migration transaction. It removes old pending=0 raw frames and adds pending-frame, pending-projection and retirement lookup indexes. Retirement deletes eligible pending frames instead of rewriting archives. The query starts with pending frames and uses indexed attempt lookups. Normalized events, receipts and accounting checkpoints remain available for recovery and replay. Tests cover 200 archived frames, migration cleanup, actual row deletion, leading-column indexes and changes()=0 on a repeated ACK with synthetic archived rows. Startup frames stay available while consumption may still be in progress; recovery can retire them once containment is established.
+3. Production instanceValidators().Receipt accepts turn.completed and turn.failed. It reads only the settled usage field carried by the authenticated event, including the final envelope for chunked output. Missing/null usage remains unknown, and turn.failed produces OutcomeFailure. The integration fixture now supports AttachSupervisedExecution, so the lost-ACK test uses production validators with no receipt/event stubs. It verifies exact 28,254/142 accounting, unknown charge preservation, failed turns, chunked envelopes, one event/audit effect, malformed usage rejection, and existing scope/runner/attempt/fence/action checks.
+4. A mutex protects capture failure updates and publication through Done. The deterministic test lets stdout finish while a failed stdin write is still waiting for containment, and verifies that Done waits for the complete error result. The requested single CGO_ENABLED=1 race run passed.
+5. Terminal observations cannot settle an intent or replace a completed turn. Only dispatched turns update terminal state and settled usage. Exact event replay remains idempotent. Later observations of quarantined turns preserve uncertainty. Pre-dispatch usage cannot become settled accounting. Existing completion, usage, resume and retirement fixtures now consume their turn before reporting terminal events.
+
+### Files
+
+- `internal/runner/capture.go`: attempt-local failures, synchronized result publication and storage classification.
+- `internal/runner/direct_events.go`: projection quarantine, dispatched-only accounting and terminal transitions.
+- `internal/runner/direct_recovery.go`: unknown-attempt classification, storage errors during intent writes and indexed raw-frame retirement.
+- `internal/runner/journal.go`: private schema v3 and admission storage-error fencing.
+- `internal/runner/journal_reset.go`: identity and uncertain-turn errors are not storage failures.
+- `internal/runner/direct_fixes_test.go`: regression tests for all five findings and their adjacent storage/retention guards.
+- `internal/runner/direct_recovery_test.go`: dispatched-turn fixtures, v3 upgrade expectation and deletion assertion.
+- `internal/runner/journal_test.go`: future-version refusal now uses version 4.
+- `internal/equipo/runner_report_validation.go`: production direct receipts and durable usage.
+- `internal/equipotest/runner_api_test.go`: optional production supervised fixture setup.
+- `internal/equipotest/runner_events_test.go`: production settlement and lost-ACK replay tests.
+- `docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md`: this appended evidence.
+- `.superpowers/sdd/2026-11-03-equipo-plan-2b-direct/task-7-report.md`: this appended local report, preserving the original report. The dispatch-report directory remains Git-ignored under the existing repository layout.
+
+### Interpretations
+
+- The original task established private schema version 2. An explicit version 3 migration is needed to upgrade already-existing v2 journals; changing only the v2 CREATE statements would not upgrade them. No instance/app schema or migration changed.
+- An unknown attempt lookup is an identity error. A missing/corrupt journal table or failed write is a storage error. A duplicate intent constraint remains an uncertain, non-repeatable admission; SQLite FULL during that write must fence.
+- A late terminal observation after quarantine may remain historical evidence, but it cannot change the saved terminal state or accounting. A new terminal observation for an already completed turn is rejected; exact durable-event replay still returns its original receipt.
+- Raw frames are dispensable only after the existing containment, normalization and ACK checks. Normalized event bodies and usage baselines remain for replay and accounting. SQLite reuses freed pages; this change does not VACUUM or promise to shrink an existing file below its prior high-water size.
+- The deterministic concurrency test supplies behavioral RED and mutation evidence. The single authorized race run checks the restored implementation, so no extra race run was used for RED or mutations.
+
+### Test-first evidence and intermediate checks
+
+The initial runner test addition had a duplicate helper declaration. That compile failure is recorded below but is not guard evidence. It was corrected before the behavioral RED run. The first production fixture attempt tried to reattach execution to an already-attached store; it failed before receipt validation and is likewise not guard evidence. The revised fixture installs production validators at initial attachment and then fails at the actual unsupported direct receipt.
+
+An intermediate GREEN attempt found that the chunk fixture used Go field names rather than the JSON field tags; the fixture was corrected to the actual envelope. The first covering run found a resumed-turn fixture that had not consumed its intent; it was corrected. All final checks below pass. No compile failure is counted as a successful mutation.
+
+#### 1. red-runner
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectFaultIsolation|TestDirectTerminalTransition|TestDirectCaptureFailurePublication|TestDirectJournalPrunesFrames' -count=1
+```
+
+Exit 1:
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/direct_fixes_test.go:95:6: shortDirectInput redeclared in this block
+ internal/runner/capture_test.go:358:6: other declaration of shortDirectInput
+internal/runner/direct_fixes_test.go:96:25: method shortDirectInput.Write already declared at internal/runner/capture_test.go:360:25
+internal/runner/direct_fixes_test.go:97:25: method shortDirectInput.Close already declared at internal/runner/capture_test.go:361:25
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+FAIL
+```
+
+#### 2. red-runner
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectFaultIsolation|TestDirectTerminalTransition|TestDirectCaptureFailurePublication|TestDirectJournalPrunesFrames' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectFaultIsolation (9.52s)
+ --- FAIL: TestDirectFaultIsolation/torn (0.38s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/oversized (0.41s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/malformed (0.40s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/stall (5.44s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/short-input (0.56s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/identity (0.35s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/unknown-frame (0.30s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/unknown-turn (0.32s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/unknown-event (0.28s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/pump-identity (0.30s)
+ direct_fixes_test.go:82: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/storage (0.27s)
+ direct_fixes_test.go:79: storage fault did not fence journal
+--- FAIL: TestDirectTerminalTransition (1.46s)
+ --- FAIL: TestDirectTerminalTransition/intent (0.34s)
+ direct_fixes_test.go:116: terminal event changed intent to completed or replaced usage
+ --- FAIL: TestDirectTerminalTransition/completed (0.58s)
+ direct_fixes_test.go:116: terminal event changed completed to waiting_for_person or replaced usage
+ --- FAIL: TestDirectTerminalTransition/waiting_for_person (0.54s)
+ direct_fixes_test.go:116: terminal event changed waiting_for_person to waiting_for_person or replaced usage
+--- FAIL: TestDirectCaptureFailurePublication (0.52s)
+ direct_fixes_test.go:150: Done published while failure cleanup still writes its result
+--- FAIL: TestDirectJournalPrunesFrames (0.82s)
+ direct_fixes_test.go:167: upgrade kept retired frames 200
+ direct_fixes_test.go:170: missing pending index direct_frames
+ direct_fixes_test.go:170: missing pending index direct_events
+ direct_fixes_test.go:178: retired frames not pruned 201
+ direct_fixes_test.go:181: ACK touched archived frames 201
+FAIL
+rastrillo-budget/v1 ran 12.328s
+FAIL amadan.net/oficina/equipo/internal/runner 12.331s
+FAIL
+```
+
+#### 3. red-instance
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK$' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.03s)
+ runner_events_test.go:491: This record changed. Reload the page and try again.
+FAIL
+rastrillo-budget/v1 ran 1.03s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.093s
+FAIL
+```
+
+#### 4. red-instance
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK$' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.51s)
+ runner_events_test.go:510: One or more values are invalid. Check the form and try again.
+FAIL
+rastrillo-budget/v1 ran 1.515s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.562s
+FAIL
+```
+
+#### 5. green-runner
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectFaultIsolation|TestDirectTerminalTransition|TestDirectCaptureFailurePublication|TestDirectJournalPrunesFrames' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 13.219s
+```
+
+#### 6. red-instance-modes
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK$' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (4.24s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/completed-known (1.50s)
+ runner_events_test.go:526: One or more values are invalid. Check the form and try again.
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/completed-unknown (0.87s)
+ runner_events_test.go:526: One or more values are invalid. Check the form and try again.
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/failed-unknown (0.89s)
+ runner_events_test.go:526: One or more values are invalid. Check the form and try again.
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/chunked-known (0.98s)
+ runner_events_test.go:526: One or more values are invalid. Check the form and try again.
+FAIL
+rastrillo-budget/v1 ran 4.24s
+FAIL amadan.net/oficina/equipo/internal/equipotest 4.365s
+FAIL
+```
+
+#### 7. red-projection
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectProjectionFaultQuarantines$' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectProjectionFaultQuarantines (1.30s)
+ --- FAIL: TestDirectProjectionFaultQuarantines/protocol (0.53s)
+ direct_fixes_test.go:210: projection fault left attempt active 0 dispatched
+ --- FAIL: TestDirectProjectionFaultQuarantines/containment (0.36s)
+ direct_fixes_test.go:210: projection fault left attempt active 0 dispatched
+ --- FAIL: TestDirectProjectionFaultQuarantines/interrupt-storage (0.40s)
+ direct_fixes_test.go:203: failed quarantine did not fence
+FAIL
+rastrillo-budget/v1 ran 1.3s
+FAIL amadan.net/oficina/equipo/internal/runner 1.303s
+FAIL
+```
+
+#### 8. green-instance
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK$' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (4.44s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/chunked-known (0.97s)
+ runner_events_test.go:533: direct receipt lost or duplicated: [{ID:1 Account:QXTSMELJ4ZIH7VHOBXTZ5WKJ6C Job:1 Step:1 Attempt:1 Action:1 Reserved:{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:32000 OutputTokens:4000 CostMicros:0} Settled:{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:0 OutputTokens:0 CostMicros:0} State:settled ReceiptID:turn SettledBy:adapter:claude CreatedAt:2026-11-03 15:30:55.751144023 +0000 UTC SettledAt:2026-11-03 15:30:55.751144023 +0000 UTC}]
+FAIL
+rastrillo-budget/v1 ran 4.439s
+FAIL amadan.net/oficina/equipo/internal/equipotest 4.491s
+FAIL
+```
+
+#### 9. green-projection
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectProjectionFaultQuarantines$' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 1.311s
+```
+
+#### 10. green-covering
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest ./internal/equipo -run 'TestDirect|TestJournal|TestRunnerEvents|TestMigration' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageResumeBinding (0.79s)
+ direct_recovery_test.go:318: runner.direct_uncertain
+FAIL
+rastrillo-budget/v1 ran 49.861s
+FAIL amadan.net/oficina/equipo/internal/runner 49.869s
+ok amadan.net/oficina/equipo/internal/equipotest 4.851s
+ok amadan.net/oficina/equipo/internal/equipo 0.149s
+FAIL
+```
+
+#### 11. red-storage-accounting
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectFaultIsolation/(event-storage|intent-storage)$|TestDirectUsageBeforeDispatch' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.61s)
+ --- FAIL: TestDirectFaultIsolation/event-storage (0.33s)
+ direct_fixes_test.go:92: storage fault did not fence journal
+ --- FAIL: TestDirectFaultIsolation/intent-storage (0.27s)
+ direct_fixes_test.go:92: storage fault did not fence journal
+--- FAIL: TestDirectUsageBeforeDispatch (0.50s)
+ direct_fixes_test.go:241: undispatched usage became settled accounting &{0 true 1 28254 142 0}
+FAIL
+rastrillo-budget/v1 ran 1.103s
+FAIL amadan.net/oficina/equipo/internal/runner 1.106s
+FAIL
+```
+
+#### 12. green-storage-accounting
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectFaultIsolation/(event-storage|intent-storage)$|TestDirectUsageBeforeDispatch|TestDirectCaptureFailurePublication' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 1.861s
+```
+
+#### 13. green-covering
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest ./internal/equipo -run 'TestDirect|TestJournal|TestRunnerEvents|TestMigration' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 51.757s
+ok amadan.net/oficina/equipo/internal/equipotest 4.429s
+ok amadan.net/oficina/equipo/internal/equipo 0.095s
+```
+
+#### 14. red-startup
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalRetainsUndecodedStartup$' -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalRetainsUndecodedStartup (0.42s)
+ direct_fixes_test.go:347: startup frame retired before consumption or recovery
+FAIL
+rastrillo-budget/v1 ran 421ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.423s
+FAIL
+```
+
+#### 15. green-startup
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalRetainsUndecodedStartup$' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.466s
+```
+
+#### 16. final-race
+
+```sh
+CGO_ENABLED=1 go test -race ./internal/runner -run '^TestDirectCaptureFailurePublication$' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 1.589s
+```
+
+#### 17. final-covering
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest ./internal/equipo -run 'TestDirect|TestJournal|TestRunnerEvents|TestMigration' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 51.837s
+ok amadan.net/oficina/equipo/internal/equipotest 4.457s
+ok amadan.net/oficina/equipo/internal/equipo 0.095s
+```
+
+### Independent compiling mutations
+
+Each mutation was applied alone, the named test compiled and failed behaviorally, and the source was restored in a finally block before the next mutation. The final covering run follows all restorations. The startup-retention case also has its own RED/GREEN cycle above.
+
+#### protocol-fences-runner
+
+File: `internal/runner/capture.go`. Replaced:
+
+```text
+if errors.Is(e, ErrJournal) || journalErr != nil {
+```
+
+with:
+
+```text
+if ctx.Err() == nil || journalErr != nil {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/torn$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.44s)
+ --- FAIL: TestDirectFaultIsolation/torn (0.44s)
+ direct_fixes_test.go:126: attempt fault fenced unrelated work
+FAIL
+rastrillo-budget/v1 ran 438ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.440s
+FAIL
+```
+
+#### capture-quarantine-failure
+
+File: `internal/runner/capture.go`. Replaced:
+
+```text
+if errors.Is(e, ErrJournal) || journalErr != nil {
+```
+
+with:
+
+```text
+if errors.Is(e, ErrJournal) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/interrupt-storage$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.42s)
+ --- FAIL: TestDirectFaultIsolation/interrupt-storage (0.42s)
+ direct_fixes_test.go:122: storage fault did not fence journal
+FAIL
+rastrillo-budget/v1 ran 423ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.426s
+FAIL
+```
+
+#### identity-fences-runner
+
+File: `internal/runner/journal_reset.go`. Replaced:
+
+```text
+errors.Is(err, provider.ErrIdentity) ||
+```
+
+with:
+
+```text
+false && errors.Is(err, provider.ErrIdentity) ||
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/identity$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.65s)
+ --- FAIL: TestDirectFaultIsolation/identity (0.34s)
+ direct_fixes_test.go:126: attempt fault fenced unrelated work
+ --- FAIL: TestDirectFaultIsolation/pump-identity (0.30s)
+ direct_fixes_test.go:126: attempt fault fenced unrelated work
+FAIL
+rastrillo-budget/v1 ran 645ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.648s
+FAIL
+```
+
+#### uncertain-fences-runner
+
+File: `internal/runner/journal_reset.go`. Replaced:
+
+```text
+errors.Is(err, errDirectUncertain) ||
+```
+
+with:
+
+```text
+false && errors.Is(err, errDirectUncertain) ||
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectTerminalTransition/intent$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectTerminalTransition (0.40s)
+ --- FAIL: TestDirectTerminalTransition/intent (0.40s)
+ direct_fixes_test.go:173: attempt fault fenced unrelated work
+FAIL
+rastrillo-budget/v1 ran 401ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.404s
+FAIL
+```
+
+#### unknown-frame-fences-runner
+
+File: `internal/runner/capture.go`. Replaced:
+
+```text
+if errors.Is(e, sql.ErrNoRows) {
+```
+
+with:
+
+```text
+if false && errors.Is(e, sql.ErrNoRows) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/unknown-frame$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.31s)
+ --- FAIL: TestDirectFaultIsolation/unknown-frame (0.31s)
+ direct_fixes_test.go:126: attempt fault fenced unrelated work
+FAIL
+rastrillo-budget/v1 ran 306ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.308s
+FAIL
+```
+
+#### unknown-session-fences-runner
+
+File: `internal/runner/direct_recovery.go`. Replaced:
+
+```text
+if errors.Is(err, sql.ErrNoRows) {
+```
+
+with:
+
+```text
+if false && errors.Is(err, sql.ErrNoRows) {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/unknown-turn$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.29s)
+ --- FAIL: TestDirectFaultIsolation/unknown-turn (0.29s)
+ direct_fixes_test.go:126: attempt fault fenced unrelated work
+FAIL
+rastrillo-budget/v1 ran 292ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.294s
+FAIL
+```
+
+#### storage-admission-unfenced
+
+File: `internal/runner/journal.go`. Replaced:
+
+```text
+Scan(&saved, &size); err != nil {
+ return j.storageFailure(ctx, err)
+```
+
+with:
+
+```text
+Scan(&saved, &size); err != nil {
+ return err
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/storage$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (1.61s)
+ --- FAIL: TestDirectFaultIsolation/storage (0.32s)
+ direct_fixes_test.go:122: storage fault did not fence journal
+FAIL
+rastrillo-budget/v1 ran 1.605s
+FAIL amadan.net/oficina/equipo/internal/runner 1.608s
+FAIL
+```
+
+#### event-storage-as-identity
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+if !errors.Is(err, sql.ErrNoRows) {
+ return err
+```
+
+with:
+
+```text
+if !errors.Is(err, sql.ErrNoRows) {
+ return provider.ErrIdentity
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/event-storage$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.36s)
+ --- FAIL: TestDirectFaultIsolation/event-storage (0.36s)
+ direct_fixes_test.go:122: storage fault did not fence journal
+FAIL
+rastrillo-budget/v1 ran 364ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.366s
+FAIL
+```
+
+#### intent-storage-as-uncertain
+
+File: `internal/runner/direct_recovery.go`. Replaced:
+
+```text
+sqliteErr.Code()&0xff != sqlite3.SQLITE_CONSTRAINT {
+ return e
+```
+
+with:
+
+```text
+sqliteErr.Code()&0xff != sqlite3.SQLITE_CONSTRAINT {
+ return errDirectUncertain
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectFaultIsolation/intent-storage$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectFaultIsolation (0.33s)
+ --- FAIL: TestDirectFaultIsolation/intent-storage (0.33s)
+ direct_fixes_test.go:122: storage fault did not fence journal
+FAIL
+rastrillo-budget/v1 ran 332ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.334s
+FAIL
+```
+
+#### projection-skips-quarantine
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+journalErr := p.Journal.interruptDirect(cleanup, attempt, containmentErr == nil)
+```
+
+with:
+
+```text
+journalErr := error(nil)
+ _ = attempt
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectProjectionFaultQuarantines/protocol$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectProjectionFaultQuarantines (0.34s)
+ --- FAIL: TestDirectProjectionFaultQuarantines/protocol (0.34s)
+ direct_fixes_test.go:311: projection fault left attempt active 0 dispatched
+FAIL
+rastrillo-budget/v1 ran 341ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.343s
+FAIL
+```
+
+#### projection-false-containment
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+p.Journal.interruptDirect(cleanup, attempt, containmentErr == nil)
+```
+
+with:
+
+```text
+p.Journal.interruptDirect(cleanup, attempt, true)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectProjectionFaultQuarantines/containment$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectProjectionFaultQuarantines (0.43s)
+ --- FAIL: TestDirectProjectionFaultQuarantines/containment (0.43s)
+ direct_fixes_test.go:315: uncontained attempt admitted work
+FAIL
+rastrillo-budget/v1 ran 428ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.430s
+FAIL
+```
+
+#### projection-quarantine-unfenced
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+if journalErr != nil {
+ _ = p.Journal.fail()
+```
+
+with:
+
+```text
+if false && journalErr != nil {
+ _ = p.Journal.fail()
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectProjectionFaultQuarantines/interrupt-storage$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectProjectionFaultQuarantines (0.44s)
+ --- FAIL: TestDirectProjectionFaultQuarantines/interrupt-storage (0.43s)
+ direct_fixes_test.go:302: failed quarantine did not fence
+FAIL
+rastrillo-budget/v1 ran 435ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.438s
+FAIL
+```
+
+#### retirement-without-pruning
+
+File: `internal/runner/direct_recovery.go`. Replaced:
+
+```text
+DELETE FROM direct_frames WHERE pending=1
+```
+
+with:
+
+```text
+UPDATE direct_frames SET pending=0 WHERE pending=1
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalPrunesFrames$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectJournalPrunesFrames (1.09s)
+ direct_fixes_test.go:262: retired frames not pruned 1
+FAIL
+rastrillo-budget/v1 ran 1.086s
+FAIL amadan.net/oficina/equipo/internal/runner 1.088s
+FAIL
+```
+
+#### retirement-touches-archives
+
+File: `internal/runner/direct_recovery.go`. Replaced:
+
+```text
+DELETE FROM direct_frames WHERE pending=1 AND EXISTS
+```
+
+with:
+
+```text
+DELETE FROM direct_frames WHERE EXISTS
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalPrunesFrames$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectJournalPrunesFrames (1.21s)
+ direct_fixes_test.go:269: ACK touched archived frames 200
+FAIL
+rastrillo-budget/v1 ran 1.209s
+FAIL amadan.net/oficina/equipo/internal/runner 1.211s
+FAIL
+```
+
+#### migration-keeps-archives
+
+File: `internal/runner/journal.go`. Replaced:
+
+```text
+DELETE FROM direct_frames WHERE pending=0;
+```
+
+with:
+
+```text
+SELECT 1;
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalPrunesFrames$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectJournalPrunesFrames (0.93s)
+ direct_fixes_test.go:247: upgrade kept retired frames 200
+ direct_fixes_test.go:262: retired frames not pruned 200
+ direct_fixes_test.go:265: constraint failed: UNIQUE constraint failed: direct_frames.stream, direct_frames.sequence (1555)
+FAIL
+rastrillo-budget/v1 ran 932ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.935s
+FAIL
+```
+
+#### missing-pending-frame-index
+
+File: `internal/runner/journal.go`. Replaced:
+
+```text
+CREATE INDEX IF NOT EXISTS direct_frames_pending ON direct_frames(pending);
+```
+
+with:
+
+```text
+SELECT 1;
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalPrunesFrames$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectJournalPrunesFrames (1.08s)
+ direct_fixes_test.go:252: missing pending index direct_frames
+FAIL
+rastrillo-budget/v1 ran 1.078s
+FAIL amadan.net/oficina/equipo/internal/runner 1.080s
+FAIL
+```
+
+#### missing-pending-event-index
+
+File: `internal/runner/journal.go`. Replaced:
+
+```text
+CREATE INDEX IF NOT EXISTS direct_events_projected ON direct_events(projected);
+```
+
+with:
+
+```text
+SELECT 1;
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalPrunesFrames$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectJournalPrunesFrames (1.12s)
+ direct_fixes_test.go:252: missing pending index direct_events
+FAIL
+rastrillo-budget/v1 ran 1.116s
+FAIL amadan.net/oficina/equipo/internal/runner 1.118s
+FAIL
+```
+
+#### production-rejects-completion
+
+File: `internal/equipo/runner_report_validation.go`. Replaced:
+
+```text
+ && event.Kind != "turn.completed"
+```
+
+with:
+
+```text
+(removed)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK/completed-known$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.44s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/completed-known (1.43s)
+ runner_events_test.go:543: One or more values are invalid. Check the form and try again.
+FAIL
+rastrillo-budget/v1 ran 1.435s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.481s
+FAIL
+```
+
+#### production-failure-as-success
+
+File: `internal/equipo/runner_report_validation.go`. Replaced:
+
+```text
+if event.Kind == "turn_failed" || event.Kind == "turn.failed" {
+```
+
+with:
+
+```text
+if event.Kind == "turn_failed" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK/failed-unknown$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.51s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/failed-unknown (1.51s)
+ runner_events_test.go:566: receipt changed outcome or usage certainty: &{ID:turn Outcome:success Usage:<nil> Provider:claude Model:sonnet Effort: Detail: Fields:map[]}
+FAIL
+rastrillo-budget/v1 ran 1.514s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.563s
+FAIL
+```
+
+#### production-loses-accounting
+
+File: `internal/equipo/runner_report_validation.go`. Replaced:
+
+```text
+usage = settled.Usage
+```
+
+with:
+
+```text
+usage = nil
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK/completed-known$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.51s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/completed-known (1.51s)
+ runner_events_test.go:554: direct receipt lost or duplicated: [{ID:1 Account:YUQJIHDMAWHCXCNG7U2CAEKG73 Job:1 Step:1 Attempt:1 Action:1 Reserved:{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:32000 OutputTokens:4000 CostMicros:0} Settled:{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:32000 OutputTokens:4000 CostMicros:0} State:settled ReceiptID: SettledBy:unknown CreatedAt:2026-11-03 15:36:41.192374217 +0000 UTC SettledAt:2026-11-03 15:36:41.192374217 +0000 UTC}]
+FAIL
+rastrillo-budget/v1 ran 1.507s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.555s
+FAIL
+```
+
+#### production-invents-usage
+
+File: `internal/equipo/runner_report_validation.go`. Replaced:
+
+```text
+usage = settled.Usage
+```
+
+with:
+
+```text
+usage = settled.Usage
+ if usage==nil { usage=&team.Usage{} }
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK/completed-unknown$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.41s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/completed-unknown (1.41s)
+ runner_events_test.go:554: direct receipt lost or duplicated: [{ID:1 Account:RZUBZSAPYRLJUIVINUIXEKBTVG Job:1 Step:1 Attempt:1 Action:1 Reserved:{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:32000 OutputTokens:4000 CostMicros:0} Settled:{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:0 OutputTokens:0 CostMicros:0} State:settled ReceiptID:turn SettledBy:adapter:claude CreatedAt:2026-11-03 15:36:44.316850558 +0000 UTC SettledAt:2026-11-03 15:36:44.316850558 +0000 UTC}]
+FAIL
+rastrillo-budget/v1 ran 1.409s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.459s
+FAIL
+```
+
+#### production-ignores-bad-usage
+
+File: `internal/equipo/runner_report_validation.go`. Replaced:
+
+```text
+if json.Unmarshal(event.Payload, &settled) != nil {
+```
+
+with:
+
+```text
+if json.Unmarshal(event.Payload, &settled) != nil && false {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run '^TestDirectCompletionServerCommitBeforeACK/completed-known$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (0.94s)
+ --- FAIL: TestDirectCompletionServerCommitBeforeACK/completed-known (0.94s)
+ runner_events_test.go:519: foreign completion accepted usage
+FAIL
+rastrillo-budget/v1 ran 940ms
+FAIL amadan.net/oficina/equipo/internal/equipotest 0.990s
+FAIL
+```
+
+#### unsynchronized-failure-publication
+
+File: `internal/runner/capture.go`. Replaced:
+
+```text
+failureMu.Lock()
+ done <- failure
+ failureMu.Unlock()
+```
+
+with:
+
+```text
+done <- failure
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectCaptureFailurePublication$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectCaptureFailurePublication (0.38s)
+ direct_fixes_test.go:224: Done published while failure cleanup still writes its result
+FAIL
+rastrillo-budget/v1 ran 383ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.386s
+FAIL
+```
+
+#### terminal-without-dispatch
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+&& (state == "intent" || state == "completed")
+```
+
+with:
+
+```text
+&& (state == "completed")
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectTerminalTransition/intent$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectTerminalTransition (0.36s)
+ --- FAIL: TestDirectTerminalTransition/intent (0.36s)
+ direct_fixes_test.go:164: accepted terminal observation for intent
+FAIL
+rastrillo-budget/v1 ran 363ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.366s
+FAIL
+```
+
+#### second-terminal-accepted
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+&& (state == "intent" || state == "completed")
+```
+
+with:
+
+```text
+&& (state == "intent")
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectTerminalTransition/completed$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectTerminalTransition (0.48s)
+ --- FAIL: TestDirectTerminalTransition/completed (0.48s)
+ direct_fixes_test.go:164: accepted terminal observation for completed
+FAIL
+rastrillo-budget/v1 ran 478ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.480s
+FAIL
+```
+
+#### late-terminal-overwrites-quarantine
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+&& state == "dispatched" {
+```
+
+with:
+
+```text
+{
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectTerminalTransition/waiting_for_person$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectTerminalTransition (0.48s)
+ --- FAIL: TestDirectTerminalTransition/waiting_for_person (0.48s)
+ direct_fixes_test.go:170: terminal event changed waiting_for_person to completed or replaced usage
+FAIL
+rastrillo-budget/v1 ran 477ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.480s
+FAIL
+```
+
+#### usage-before-dispatch
+
+File: `internal/runner/direct_events.go`. Replaced:
+
+```text
+if state == "dispatched" {
+```
+
+with:
+
+```text
+if state != "waiting_for_person" {
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectUsageBeforeDispatch$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectUsageBeforeDispatch (0.47s)
+ direct_fixes_test.go:334: undispatched usage became settled accounting &{0 true 1 28254 142 0}
+FAIL
+rastrillo-budget/v1 ran 472ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.475s
+FAIL
+```
+
+#### startup-retirement
+
+File: `internal/runner/direct_recovery.go`. Replaced:
+
+```text
+ AND (recovered=1 OR EXISTS(SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt))
+```
+
+with:
+
+```text
+(removed)
+```
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectJournalRetainsUndecodedStartup$' -count=1
+```
+
+Exit 1, compiled behavioral failure, restored:
+
+```text
+--- FAIL: TestDirectJournalRetainsUndecodedStartup (0.51s)
+ direct_fixes_test.go:347: startup frame retired before consumption or recovery
+FAIL
+rastrillo-budget/v1 ran 508ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.510s
+FAIL
+```
+
+### User-facing strings
+
+No new user-facing strings, error codes or copy.go entries. No pending copy entries are needed. Test assertion messages and SQL index/schema names are technical test/storage metadata. No README prose changed. No copy-review skill or server was invoked.
+
+### Concerns and handback
+
+No unresolved findings from this round. The original Task 7 runtime-composition and live-certification boundaries still apply; this fix does not cut over runtime composition or prompt a provider. Full CI and live gates were not run, as instructed. The targeted covering command and the single race command passed, and all 28 mutations compiled and failed as expected. Formatting and git diff --check passed.
+
+Work stayed on plan-2b in the authorized checkout. No agents, provider sessions, credentials, sign-ins, enrolments, model prompts, servers, deployments, pushes, merges, sudo commands or .claude/HANDOFF.md were created. Default Go caches were retained. All test invocations were awaited. Session-owned evidence scratch is removed after the report and commit are saved; no session-started process needs to remain running.
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go
index 893b630d..346e3e85 100644
--- a/internal/equipo/runner_report_validation.go
+++ b/internal/equipo/runner_report_validation.go
@@ -71,15 +71,24 @@ func instanceValidators() RunnerValidators {
return *q.Receipt, nil
}
var event runnerproto.Event
- if runnerproto.DecodeLimit(bytes.NewReader(q.Event), &event, runnerproto.MaxEventBytes+4096) != nil || event.Validate() != nil || (event.Kind != "turn_completed" && event.Kind != "turn_failed") {
+ if runnerproto.DecodeLimit(bytes.NewReader(q.Event), &event, runnerproto.MaxEventBytes+4096) != nil || event.Validate() != nil || (event.Kind != "turn_completed" && event.Kind != "turn_failed" && event.Kind != "turn.completed" && event.Kind != "turn.failed") {
return team.Receipt{}, ErrInvalid
}
outcome := team.OutcomeSuccess
- if event.Kind == "turn_failed" {
+ if event.Kind == "turn_failed" || event.Kind == "turn.failed" {
outcome = team.OutcomeFailure
}
- // Without a separate authenticated usage receipt, completion remains unmeasured.
- return team.Receipt{ID: event.TurnID, Outcome: outcome, Provider: a.Selection.Provider, Model: a.Selection.Model}, nil
+ var usage *team.Usage
+ if event.Kind == "turn.completed" || event.Kind == "turn.failed" {
+ var settled struct {
+ Usage *team.Usage `json:"usage"`
+ }
+ if json.Unmarshal(event.Payload, &settled) != nil {
+ return team.Receipt{}, ErrInvalid
+ }
+ usage = settled.Usage
+ }
+ return team.Receipt{ID: event.TurnID, Outcome: outcome, Provider: a.Selection.Provider, Model: a.Selection.Model, Usage: usage}, nil
},
Containment: func(_ context.Context, a Assignment, q RunnerRequest) error {
var p runnerproto.ContainmentProof
diff --git a/internal/equipotest/runner_api_test.go b/internal/equipotest/runner_api_test.go
index a6599962..8c58b5c2 100644
--- a/internal/equipotest/runner_api_test.go
+++ b/internal/equipotest/runner_api_test.go
@@ -29,7 +29,7 @@ type runnerFixture struct {
claim equipo.ClaimResponse
}
-func runnerFixtureNew(t *testing.T, claim bool) runnerFixture {
+func runnerFixtureNew(t *testing.T, claim bool, supervised ...bool) runnerFixture {
t.Helper()
f := bugFixture(t)
task := bugTask(t, f)
@@ -37,7 +37,11 @@ func runnerFixtureNew(t *testing.T, claim bool) runnerFixture {
executionMust(t, err)
var path string
executionMust(t, f.d.Writer().QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&path))
- x, err := f.s.AttachExecution(connectionContext, filepath.Clean(path), team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock), Provenance: func(ctx context.Context, tx *sql.Tx, _ team.Scope, h team.Handle) (team.Provenance, error) {
+ attach := f.s.AttachExecution
+ if len(supervised) > 0 && supervised[0] {
+ attach = f.s.AttachSupervisedExecution
+ }
+ x, err := attach(connectionContext, filepath.Clean(path), team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock), Provenance: func(ctx context.Context, tx *sql.Tx, _ team.Scope, h team.Handle) (team.Provenance, error) {
var raw string
if err := tx.QueryRowContext(ctx, "SELECT selection FROM runner_assignments WHERE attempt_id=?", h.Attempt).Scan(&raw); err != nil {
return team.Provenance{}, err
diff --git a/internal/equipotest/runner_events_test.go b/internal/equipotest/runner_events_test.go
index f6af0ed5..186fca70 100644
--- a/internal/equipotest/runner_events_test.go
+++ b/internal/equipotest/runner_events_test.go
@@ -478,46 +478,99 @@ func TestTimelineEpochChangedReset(t *testing.T) {
}
func TestDirectCompletionServerCommitBeforeACK(t *testing.T) {
- f := runnerFixtureNew(t, true)
- id := eventTurn(t, f)
- e := completionEvent(f, id)
- e.Kind = "turn.completed"
- u := &team.Usage{Calls: 1, InputTokens: 28254, OutputTokens: 142, CostUnavailable: true}
- completionValidators(f, u)
- path := filepath.Join(t.TempDir(), "private", "journal.db")
- j, err := runner.OpenJournal(connectionContext, path)
- executionMust(t, err)
- pump := runner.EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(ctx context.Context, event runnerproto.Event) error {
- if err := f.s.IngestRunnerEvent(ctx, f.principal, event); err != nil {
- return err
- }
- return errors.New("lost ACK after server commit")
- }}
- executionMust(t, pump.Append(connectionContext, e, nil))
- if pump.Flush(connectionContext, 10) == nil {
- t.Fatal("lost acknowledgement ignored")
- }
- executionMust(t, j.Close())
- j, err = runner.OpenJournal(connectionContext, path)
- executionMust(t, err)
- defer j.Close()
- pump.Journal = j
- pump.Upload = func(ctx context.Context, event runnerproto.Event) error {
- return f.s.IngestRunnerEvent(ctx, f.principal, event)
- }
- executionMust(t, pump.Flush(connectionContext, 10))
- rows, err := f.x.Core.Reservations(connectionContext, e.Scope)
- executionMust(t, err)
- if len(rows) != 1 || rows[0].Settled != *u {
- t.Fatalf("direct receipt lost or duplicated: %+v", rows)
- }
- if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 {
- t.Fatal("replay repeated event effects")
- }
- e.ID = "bad-direct"
- e.TurnID = ""
- e.ActionID = 0
- if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
- t.Fatal("direct completion lacks turn authority")
+ for _, mode := range []string{"completed-known", "completed-unknown", "failed-unknown", "chunked-known"} {
+ t.Run(mode, func(t *testing.T) {
+ f := runnerFixtureNew(t, true, true)
+ id := eventTurn(t, f)
+ e := completionEvent(f, id)
+ e.Kind = "turn.completed"
+ u := &team.Usage{Calls: 1, InputTokens: 28254, OutputTokens: 142, CostUnavailable: true}
+ if mode == "failed-unknown" {
+ e.Kind = "turn.failed"
+ }
+ if mode == "completed-unknown" || mode == "failed-unknown" {
+ u = nil
+ }
+ var payloadErr error
+ e.Payload, payloadErr = json.Marshal(struct {
+ Usage *team.Usage `json:"usage"`
+ }{u})
+ executionMust(t, payloadErr)
+ if mode == "chunked-known" {
+ e.Payload = []byte(`{"chunks":"durable-envelope","count":2,"kind":"turn.completed","usage":{"calls":1,"input_tokens":28254,"output_tokens":142,"cost_unavailable":true}}`)
+ }
+ for _, field := range []string{"fence", "attempt", "action", "runner", "scope", "usage"} {
+ bad := e
+ switch field {
+ case "fence":
+ bad.Handle.Fence++
+ case "attempt":
+ bad.Handle.Attempt++
+ case "action":
+ bad.ActionID++
+ case "runner":
+ bad.Handle.Runner = "foreign"
+ case "scope":
+ bad.Scope.Account = "foreign"
+ case "usage":
+ bad.Payload = []byte(`{"usage":"unknown"}`)
+ }
+ if f.s.IngestRunnerEvent(connectionContext, f.principal, bad) == nil {
+ t.Fatal("foreign completion accepted", field)
+ }
+ }
+ path := filepath.Join(t.TempDir(), "private", "journal.db")
+ j, err := runner.OpenJournal(connectionContext, path)
+ executionMust(t, err)
+ pump := runner.EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(ctx context.Context, event runnerproto.Event) error {
+ if err := f.s.IngestRunnerEvent(ctx, f.principal, event); err != nil {
+ return err
+ }
+ return errors.New("lost ACK after server commit")
+ }}
+ executionMust(t, pump.Append(connectionContext, e, nil))
+ if pump.Flush(connectionContext, 10) == nil {
+ t.Fatal("lost acknowledgement ignored")
+ }
+ executionMust(t, j.Close())
+ j, err = runner.OpenJournal(connectionContext, path)
+ executionMust(t, err)
+ defer j.Close()
+ pump.Journal = j
+ pump.Upload = func(ctx context.Context, event runnerproto.Event) error {
+ return f.s.IngestRunnerEvent(ctx, f.principal, event)
+ }
+ executionMust(t, pump.Flush(connectionContext, 10))
+ rows, err := f.x.Core.Reservations(connectionContext, e.Scope)
+ executionMust(t, err)
+ if len(rows) != 1 {
+ t.Fatal("reservation count", len(rows))
+ }
+ expected := rows[0].Reserved
+ if u != nil {
+ expected = *u
+ }
+ if rows[0].State != team.ReservationSettled || rows[0].Settled != expected {
+ t.Fatalf("direct receipt lost or duplicated: %+v", rows)
+ }
+ if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 {
+ t.Fatal("replay repeated event effects")
+ }
+ action, err := f.x.Core.GetAction(connectionContext, e.Scope, id)
+ executionMust(t, err)
+ wantOutcome := team.OutcomeSuccess
+ if mode == "failed-unknown" {
+ wantOutcome = team.OutcomeFailure
+ }
+ if action.Receipt == nil || action.Receipt.Outcome != wantOutcome || (action.Receipt.Usage == nil) != (u == nil) {
+ t.Fatalf("receipt changed outcome or usage certainty: %+v", action.Receipt)
+ }
+ e.ID = "bad-direct"
+ e.TurnID = ""
+ e.ActionID = 0
+ if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil {
+ t.Fatal("direct completion lacks turn authority")
+ }
+ })
}
}
diff --git a/internal/runner/capture.go b/internal/runner/capture.go
index 3569cd5f..52211528 100644
--- a/internal/runner/capture.go
+++ b/internal/runner/capture.go
@@ -4,6 +4,7 @@ import (
"bufio"
"bytes"
"context"
+ "database/sql"
"encoding/json"
"errors"
"io"
@@ -168,8 +169,11 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
done := make(chan error, 1)
var once sync.Once
var failure error
+ var failureMu sync.Mutex
fail := func(e error) {
once.Do(func() {
+ failureMu.Lock()
+ defer failureMu.Unlock()
failure = e
cancel()
input.Close()
@@ -180,7 +184,7 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
journalErr := f.journal.interruptDirect(cleanup, l.AttemptKey, containmentErr == nil)
stopCleanup()
failure = errors.Join(failure, containmentErr, journalErr)
- if ctx.Err() == nil || journalErr != nil {
+ if errors.Is(e, ErrJournal) || journalErr != nil {
_ = f.journal.fail()
}
})
@@ -198,6 +202,9 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
}
if e == nil {
_, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET diagnostics=? WHERE attempt=?", redactText(string(b), nil), l.AttemptKey)
+ if e != nil {
+ e = f.journal.storageFailure(runCtx, e)
+ }
}
diagnostics <- e
}()
@@ -220,7 +227,7 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
}
var saved []byte
if e = f.journal.db.QueryRowContext(runCtx, "SELECT body FROM direct_frames WHERE stream=? AND sequence=?", p.ID(), seq).Scan(&saved); e != nil {
- fail(e)
+ fail(f.journal.storageFailure(runCtx, e))
break
}
timer := time.NewTimer(5 * time.Second)
@@ -249,7 +256,7 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
if e != nil {
fail(e)
} else if _, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", l.AttemptKey); e != nil {
- fail(e)
+ fail(f.journal.storageFailure(runCtx, e))
} else if e = f.journal.releaseDirectFrames(runCtx); e != nil {
fail(e)
}
@@ -258,7 +265,9 @@ func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provide
stdout.Close()
stderr.Close()
close(frames)
+ failureMu.Lock()
done <- failure
+ failureMu.Unlock()
close(done)
}()
return &provider.Capture{Input: ci, Frames: frames, Done: done}, nil
@@ -280,6 +289,9 @@ func (j *Journal) AppendFrame(ctx context.Context, attempt, stream string, seq i
var saved string
var recovered int
if e := tx.QueryRowContext(ctx, "SELECT stream,recovered FROM direct_attempts WHERE attempt=?", attempt).Scan(&saved, &recovered); e != nil {
+ if errors.Is(e, sql.ErrNoRows) {
+ return provider.ErrIdentity
+ }
return e
}
if saved != stream || recovered != 0 {
diff --git a/internal/runner/direct_events.go b/internal/runner/direct_events.go
index 2f2bc66b..dc00c633 100644
--- a/internal/runner/direct_events.go
+++ b/internal/runner/direct_events.go
@@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "time"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runner/provider"
@@ -30,15 +31,26 @@ func (p *EventPump) AppendDirect(ctx context.Context, s provider.Session, e prov
e.Payload = json.RawMessage(`{}`)
}
if !uniqueFrame(e.Payload) {
- return p.storageFailure(ctx, runnerproto.ErrInvalid)
+ return p.directFailure(ctx, s.AttemptKey, runnerproto.ErrInvalid)
}
e.Payload = redactFrameSecrets(e.Payload, p.Secrets)
_, err := p.Journal.appendDirect(ctx, s, e, &template)
if err != nil {
- return p.storageFailure(ctx, err)
+ return p.directFailure(ctx, s.AttemptKey, err)
}
return nil
}
+func (p *EventPump) directFailure(ctx context.Context, attempt string, err error) error {
+ _ = p.Journal.storageFailure(ctx, err)
+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ containmentErr := p.Contain(cleanup)
+ journalErr := p.Journal.interruptDirect(cleanup, attempt, containmentErr == nil)
+ if journalErr != nil {
+ _ = p.Journal.fail()
+ }
+ return errors.Join(err, containmentErr, journalErr)
+}
func (j *Journal) appendDirect(ctx context.Context, s provider.Session, e provider.Event, template *Event) (*team.Usage, error) {
if e.Kind == "turn.failed" && len(e.Payload) == 0 {
e.Payload = json.RawMessage(`{}`)
@@ -81,8 +93,14 @@ func (j *Journal) appendDirect(ctx context.Context, s provider.Session, e provid
if e.TurnID != "" {
var state string
if err = tx.QueryRowContext(ctx, "SELECT state FROM direct_turns WHERE attempt=? AND session=? AND turn=?", s.AttemptKey, s.ID, e.TurnID).Scan(&state); err != nil {
+ if !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
return provider.ErrIdentity
}
+ if (e.Kind == "turn.completed" || e.Kind == "turn.failed") && (state == "intent" || state == "completed") {
+ return errDirectUncertain
+ }
profile := directProfile(l)
stream, _ := usageKeys(profile, e)
acc := NewUsageAccumulator(profile)
@@ -95,7 +113,7 @@ func (j *Journal) appendDirect(ctx context.Context, s provider.Session, e provid
} else if !errors.Is(err, sql.ErrNoRows) {
return err
}
- if state != "waiting_for_person" {
+ if state == "dispatched" {
usage = acc.Observe(e)
}
checkpoint, _ := json.Marshal(acc.direct)
@@ -103,9 +121,9 @@ func (j *Journal) appendDirect(ctx context.Context, s provider.Session, e provid
return err
}
receipt, _ = json.Marshal(usage)
- if e.Kind == "turn.completed" || e.Kind == "turn.failed" {
+ if (e.Kind == "turn.completed" || e.Kind == "turn.failed") && state == "dispatched" {
next := "waiting_for_person"
- if e.Kind == "turn.completed" && state != "waiting_for_person" {
+ if e.Kind == "turn.completed" {
next = "completed"
}
if _, err = tx.ExecContext(ctx, "UPDATE direct_turns SET state=?,usage=? WHERE attempt=? AND turn=?", next, receipt, s.AttemptKey, e.TurnID); err != nil {
diff --git a/internal/runner/direct_fixes_test.go b/internal/runner/direct_fixes_test.go
new file mode 100644
index 00000000..1eb4370a
--- /dev/null
+++ b/internal/runner/direct_fixes_test.go
@@ -0,0 +1,356 @@
+package runner
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func directUnblocked(t *testing.T, j *Journal) {
+ t.Helper()
+ var blocked int
+ mustJournal(t, j.db.QueryRow("SELECT blocked FROM journal_state").Scan(&blocked))
+ if blocked != 0 || j.AdmissionAllowed(context.Background()) != nil {
+ t.Fatal("attempt fault fenced unrelated work")
+ }
+}
+
+func TestDirectFaultIsolation(t *testing.T) {
+ for _, kind := range []string{"torn", "oversized", "malformed", "stall", "short-input", "identity", "unknown-frame", "unknown-turn", "unknown-event", "pump-identity", "storage", "interrupt-storage", "event-storage", "intent-storage"} {
+ t.Run(kind, func(t *testing.T) {
+ ctx := context.Background()
+ j, l, s, p := directFixture(t, "codex")
+ switch kind {
+ case "event-storage", "intent-storage":
+ mustJournal(t, j.BindSession(ctx, s))
+ if kind == "event-storage" {
+ _, err := j.db.Exec("DROP TABLE direct_turns")
+ mustJournal(t, err)
+ if _, err = j.ObserveDirect(ctx, s, directComplete("turn")); err == nil {
+ t.Fatal("missing turn table accepted")
+ }
+ } else {
+ var pages int
+ mustJournal(t, j.db.QueryRow("PRAGMA page_count").Scan(&pages))
+ _, err := j.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages))
+ mustJournal(t, err)
+ turn := directTurn()
+ turn.AdmissionID = strings.Repeat("a", 20000)
+ if err = j.BeginTurn(ctx, s, turn); err == nil {
+ t.Fatal("full intent write accepted")
+ }
+ }
+ case "identity":
+ mustJournal(t, j.interruptDirect(ctx, l.AttemptKey, true))
+ if j.recordDirectLaunch(ctx, l, p.record) == nil {
+ t.Fatal("relaunch accepted")
+ }
+ case "unknown-frame":
+ if j.AppendFrame(ctx, "missing", p.ID(), 1, []byte(`{}`)) == nil {
+ t.Fatal("unknown frame accepted")
+ }
+ case "unknown-turn", "unknown-event", "pump-identity":
+ s.AttemptKey = "missing"
+ var err error
+ if kind == "unknown-turn" {
+ err = j.BeginTurn(ctx, s, directTurn())
+ } else if kind == "unknown-event" {
+ _, err = j.ObserveDirect(ctx, s, directComplete("turn"))
+ } else {
+ pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
+ err = pump.AppendDirect(ctx, s, directComplete("turn"), journalEvent("e", 1))
+ }
+ if err == nil {
+ t.Fatal("unknown attempt accepted")
+ }
+ default:
+ raw := "{}\n"
+ switch kind {
+ case "torn":
+ raw = `{"partial":`
+ case "oversized":
+ raw = "{\"text\":\"" + strings.Repeat("x", MaxFrameBytes) + "\"}\n"
+ case "malformed":
+ raw = "bad\n"
+ case "storage":
+ // A broken journal table is a storage fault, unlike malformed provider JSON.
+ _, err := j.db.Exec("DROP TABLE direct_frames")
+ mustJournal(t, err)
+ case "interrupt-storage":
+ _, err := j.db.Exec("DROP TABLE journal_answers")
+ mustJournal(t, err)
+ raw = "bad\n"
+ case "short-input":
+ r, w := io.Pipe()
+ defer w.Close()
+ p.out = r
+ p.writable = shortDirectInput{}
+ }
+ if kind != "short-input" {
+ p.out = io.NopCloser(strings.NewReader(raw))
+ }
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ if err == nil {
+ if kind == "short-input" {
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ if _, err = cap.Input.Write(directPrompt("codex")); err == nil {
+ t.Fatal("short input accepted")
+ }
+ }
+ select {
+ case err = <-cap.Done:
+ case <-time.After(8 * time.Second):
+ t.Fatal("containment stalled")
+ }
+ }
+ if err == nil || !p.stopped.Load() {
+ t.Fatal("fault not contained", err)
+ }
+ }
+ if kind == "storage" || kind == "interrupt-storage" || kind == "event-storage" || kind == "intent-storage" {
+ j.mu.Lock()
+ blocked := j.blocked
+ j.mu.Unlock()
+ if !blocked {
+ t.Fatal("storage fault did not fence journal")
+ }
+ return
+ }
+ directUnblocked(t, j)
+ l.AttemptKey = "attempt-b"
+ p.record.AttemptKey = l.AttemptKey
+ p.record.ID = strings.Repeat("b", 32)
+ s.AttemptKey = l.AttemptKey
+ s.ID = "session-b"
+ mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
+ mustJournal(t, j.BeginTurn(ctx, s, provider.Turn{ID: "b", AdmissionID: "b", Prompt: "hello"}))
+ })
+ }
+}
+
+func TestDirectTerminalTransition(t *testing.T) {
+ for _, state := range []string{"intent", "completed", "waiting_for_person"} {
+ t.Run(state, func(t *testing.T) {
+ ctx := context.Background()
+ j, _, s, _ := directFixture(t, "codex")
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ if state != "intent" {
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
+ }
+ if state == "completed" {
+ _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
+ mustJournal(t, err)
+ _, err = j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ }
+ if state == "waiting_for_person" {
+ mustJournal(t, j.interruptDirect(ctx, s.AttemptKey, true))
+ }
+ var before []byte
+ mustJournal(t, j.db.QueryRow("SELECT usage FROM direct_turns").Scan(&before))
+ for _, kind := range []string{"turn.completed", "turn.failed"} {
+ e := directComplete("turn")
+ e.Kind = kind
+ e.Sequence = 99 // A distinct observation, not idempotent replay.
+ _, err := j.ObserveDirect(ctx, s, e)
+ if state != "waiting_for_person" && err == nil {
+ t.Fatal("accepted terminal observation for", state)
+ }
+ var afterState string
+ var after []byte
+ mustJournal(t, j.db.QueryRow("SELECT state,usage FROM direct_turns").Scan(&afterState, &after))
+ if afterState != state || string(before) != string(after) {
+ t.Fatalf("terminal event changed %s to %s or replaced usage", state, afterState)
+ }
+ }
+ directUnblocked(t, j)
+ })
+ }
+}
+
+// Hold failure cleanup open after the stdout owner reaches its final Close.
+type finalCloseInput struct {
+ entered, release chan struct{}
+ calls atomic.Int32
+}
+
+func (p *finalCloseInput) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }
+func (p *finalCloseInput) Close() error {
+ if p.calls.Add(1) == 1 {
+ close(p.entered)
+ <-p.release
+ }
+ return nil
+}
+
+type slowContainProcess struct {
+ *directProcess
+ entered, release chan struct{}
+}
+
+func (p *slowContainProcess) Contain(context.Context) error {
+ close(p.entered)
+ <-p.release
+ return errors.New("containment failed")
+}
+func TestDirectCaptureFailurePublication(t *testing.T) {
+ j, l, _, base := directFixture(t, "codex")
+ in := &finalCloseInput{entered: make(chan struct{}), release: make(chan struct{})}
+ base.writable = in
+ p := &slowContainProcess{directProcess: base, entered: make(chan struct{}), release: make(chan struct{})}
+ cap, err := NewCaptureFactory(j).Open(context.Background(), p, l)
+ mustJournal(t, err)
+ <-in.entered
+ writer := make(chan struct{})
+ go func() { _, _ = cap.Input.Write([]byte("{\"method\":\"initialized\"}\n")); close(writer) }()
+ <-p.entered
+ close(in.release)
+ var early bool
+ select {
+ case <-cap.Done:
+ early = true
+ case <-time.After(100 * time.Millisecond):
+ }
+ close(p.release)
+ <-writer
+ if early {
+ t.Fatal("Done published while failure cleanup still writes its result")
+ }
+ if err = <-cap.Done; err == nil || !strings.Contains(err.Error(), "containment failed") {
+ t.Fatal("failure result lost", err)
+ }
+}
+
+func TestDirectJournalPrunesFrames(t *testing.T) {
+ j, l, _, p := directFixture(t, "codex")
+ ctx := context.Background()
+ // Simulate a v2 archive and one pending frame awaiting retirement.
+ _, err := j.db.Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<200) INSERT INTO direct_frames(stream,sequence,body,pending) SELECT ?,x,'{}',0 FROM n", p.ID())
+ mustJournal(t, err)
+ _, err = j.db.Exec("DROP INDEX IF EXISTS direct_frames_pending; DROP INDEX IF EXISTS direct_events_projected; PRAGMA user_version=2")
+ mustJournal(t, err)
+ path := j.path
+ mustJournal(t, j.Close())
+ j, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer j.Close()
+ var n int
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames WHERE pending=0").Scan(&n))
+ if n != 0 {
+ t.Error("upgrade kept retired frames", n)
+ }
+ for _, spec := range []struct{ table, column string }{{"direct_frames", "pending"}, {"direct_events", "projected"}} {
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM sqlite_master m JOIN pragma_index_info(m.name) i WHERE m.type='index' AND m.tbl_name=? AND i.seqno=0 AND i.name=?", spec.table, spec.column).Scan(&n))
+ if n == 0 {
+ t.Error("missing pending index", spec.table)
+ }
+ }
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 201, []byte(`{}`)))
+ _, err = j.db.Exec("UPDATE direct_attempts SET contained=1,recovered=1")
+ mustJournal(t, err)
+ mustJournal(t, j.Append(ctx, journalEvent("ack", 1)))
+ mustJournal(t, j.Ack(ctx, "ack"))
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&n))
+ if n != 0 {
+ t.Error("retired frames not pruned", n)
+ }
+ _, err = j.db.Exec("WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n WHERE x<200) INSERT INTO direct_frames(stream,sequence,body,pending) SELECT ?,x,'{}',0 FROM n", p.ID())
+ mustJournal(t, err)
+ mustJournal(t, j.Ack(ctx, "ack"))
+ mustJournal(t, j.db.QueryRow("SELECT changes()").Scan(&n))
+ if n != 0 {
+ t.Error("ACK touched archived frames", n)
+ }
+}
+
+func TestDirectProjectionFaultQuarantines(t *testing.T) {
+ for _, kind := range []string{"protocol", "containment", "interrupt-storage"} {
+ t.Run(kind, func(t *testing.T) {
+ ctx := context.Background()
+ j, _, s, _ := directFixture(t, "codex")
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
+ if kind == "interrupt-storage" {
+ _, err := j.db.Exec("DROP TABLE journal_answers")
+ mustJournal(t, err)
+ }
+ called := false
+ pump := EventPump{Journal: j, Contain: func(context.Context) error {
+ called = true
+ if kind == "containment" {
+ return provider.ErrContainment
+ }
+ return nil
+ }}
+ e := directComplete("turn")
+ e.Payload = []byte("invalid")
+ if pump.AppendDirect(ctx, s, e, journalEvent("bad", 1)) == nil || !called {
+ t.Fatal("protocol fault escaped containment")
+ }
+ if kind == "interrupt-storage" {
+ j.mu.Lock()
+ blocked := j.blocked
+ j.mu.Unlock()
+ if !blocked {
+ t.Fatal("failed quarantine did not fence")
+ }
+ return
+ }
+ var recovered, contained int
+ var state string
+ mustJournal(t, j.db.QueryRow("SELECT recovered,contained FROM direct_attempts").Scan(&recovered, &contained))
+ mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state))
+ if recovered != 1 || state != "waiting_for_person" {
+ t.Fatal("projection fault left attempt active", recovered, state)
+ }
+ if kind == "containment" {
+ if contained != 0 || j.AdmissionAllowed(ctx) == nil {
+ t.Fatal("uncontained attempt admitted work")
+ }
+ } else {
+ directUnblocked(t, j)
+ }
+ })
+ }
+}
+
+func TestDirectUsageBeforeDispatch(t *testing.T) {
+ ctx := context.Background()
+ j, _, s, _ := directFixture(t, "codex")
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
+ mustJournal(t, err)
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
+ usage, err := j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ if usage != nil {
+ t.Fatal("undispatched usage became settled accounting", usage)
+ }
+}
+
+func TestDirectJournalRetainsUndecodedStartup(t *testing.T) {
+ ctx := context.Background()
+ j, l, _, p := directFixture(t, "codex")
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{}`)))
+ _, err := j.db.Exec("UPDATE direct_attempts SET contained=1")
+ mustJournal(t, err)
+ mustJournal(t, j.releaseDirectFrames(ctx))
+ var n int
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames WHERE pending=1").Scan(&n))
+ if n != 1 {
+ t.Fatal("startup frame retired before consumption or recovery")
+ }
+ mustJournal(t, j.interruptDirect(ctx, l.AttemptKey, true))
+ mustJournal(t, j.releaseDirectFrames(ctx))
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&n))
+ if n != 0 {
+ t.Fatal("recovered startup retained raw frames")
+ }
+}
diff --git a/internal/runner/direct_recovery.go b/internal/runner/direct_recovery.go
index 6ba48999..e19e7506 100644
--- a/internal/runner/direct_recovery.go
+++ b/internal/runner/direct_recovery.go
@@ -7,6 +7,8 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "modernc.org/sqlite"
+ sqlite3 "modernc.org/sqlite/lib"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runner/containment"
@@ -93,6 +95,9 @@ func directLaunchTx(ctx context.Context, tx *sql.Tx, s provider.Session) (provid
var saved string
var l provider.Launch
if err := tx.QueryRowContext(ctx, "SELECT launch,session FROM direct_attempts WHERE attempt=?", s.AttemptKey).Scan(&b, &saved); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return l, provider.ErrIdentity
+ }
return l, err
}
if json.Unmarshal(b, &l) != nil || s.Validate(l) != nil || (saved != "" && saved != s.ID) {
@@ -163,6 +168,10 @@ func (j *Journal) BeginTurn(ctx context.Context, s provider.Session, t provider.
}
_, key := usageKeys(directProfile(l), provider.Event{SessionID: s.ID, TurnID: t.ID})
if _, e = tx.ExecContext(ctx, "INSERT INTO direct_turns(turn_key,attempt,session,turn,admission,prompt_hash,state) VALUES(?,?,?,?,?,?,'intent')", key, s.AttemptKey, s.ID, t.ID, t.AdmissionID, runnerproto.EventHash(t.Prompt)); e != nil {
+ var sqliteErr *sqlite.Error
+ if !errors.As(e, &sqliteErr) || sqliteErr.Code()&0xff != sqlite3.SQLITE_CONSTRAINT {
+ return e
+ }
return errDirectUncertain
}
return tx.Commit()
@@ -301,8 +310,8 @@ func (j *Journal) BindSession(ctx context.Context, s provider.Session) error {
}
func (j *Journal) releaseDirectFrames(ctx context.Context) error {
- _, err := j.db.ExecContext(ctx, `UPDATE direct_frames SET pending=0 WHERE stream IN (
- SELECT stream FROM direct_attempts a WHERE contained=1 AND NOT EXISTS(
+ _, err := j.db.ExecContext(ctx, `DELETE FROM direct_frames WHERE pending=1 AND EXISTS (
+ SELECT 1 FROM direct_attempts a WHERE a.stream=direct_frames.stream AND contained=1 AND (recovered=1 OR EXISTS(SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt)) AND NOT EXISTS(
SELECT 1 FROM direct_turns t WHERE t.attempt=a.attempt AND t.state IN ('intent','dispatched')) AND NOT EXISTS(
SELECT 1 FROM journal_events e WHERE e.acked=0 AND json_extract(e.body,'$.agent_id')=a.attempt)
AND NOT EXISTS(SELECT 1 FROM direct_events d WHERE d.attempt=a.attempt AND d.projected=0))`)
diff --git a/internal/runner/direct_recovery_test.go b/internal/runner/direct_recovery_test.go
index 293f77a7..b4d490a6 100644
--- a/internal/runner/direct_recovery_test.go
+++ b/internal/runner/direct_recovery_test.go
@@ -24,6 +24,7 @@ func TestDirectUsageDeltas(t *testing.T) {
ctx := context.Background()
j, _, s, _ := directFixture(t, "codex")
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
for _, v := range []provider.Event{codexUsage("turn", 14054, 96), codexUsage("turn", 28254, 142)} {
_, err := j.ObserveDirect(ctx, s, v)
mustJournal(t, err)
@@ -46,6 +47,7 @@ func TestDirectUsageDeltas(t *testing.T) {
// A new admitted turn in the same live attempt demonstrates the durable baseline.
next := provider.Turn{ID: "next", AdmissionID: "next-admission", Prompt: "hello"}
mustJournal(t, j.BeginTurn(ctx, s, next))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, next.Prompt))
_, err = j.ObserveDirect(ctx, s, codexUsage("next", 30000, 150))
mustJournal(t, err)
u, err = j.ObserveDirect(ctx, s, directComplete("next"))
@@ -92,6 +94,7 @@ func TestDirectCompletionReplay(t *testing.T) {
j, _, s, _ := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
mustJournal(t, err)
pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
@@ -125,6 +128,7 @@ func TestDirectInterruptedWaitsForPerson(t *testing.T) {
j, _, s, _ := directFixture(t, "claude")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err := j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')")
mustJournal(t, err)
rows, err := j.RecoverDirect(ctx)
@@ -161,7 +165,7 @@ func TestDirectJournalUpgrade(t *testing.T) {
defer j.Close()
var v int
mustJournal(t, j.db.QueryRow("PRAGMA user_version").Scan(&v))
- if v != 2 {
+ if v != 3 {
t.Fatalf("journal version %d", v)
}
events, err := j.Pending(ctx, 10)
@@ -219,6 +223,7 @@ func TestDirectJournalProjectionAtomic(t *testing.T) {
j, _, s, _ := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
mustJournal(t, err)
_, err = j.db.Exec("CREATE TRIGGER fail_projection BEFORE INSERT ON journal_events BEGIN SELECT RAISE(ABORT,'injected outbox failure'); END")
@@ -243,6 +248,7 @@ func TestDirectJournalChunks(t *testing.T) {
j, _, s, _ := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
payload := json.RawMessage(`{"output":"` + strings.Repeat("猫", 15000) + `","status":"completed"}`)
e := provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "tool.completed", Payload: payload, Sequence: 3}
pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
@@ -292,6 +298,7 @@ func TestDirectUsageResumeBinding(t *testing.T) {
j, l, s, p := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
mustJournal(t, err)
_, err = j.ObserveDirect(ctx, s, directComplete("turn"))
@@ -305,6 +312,7 @@ func TestDirectUsageResumeBinding(t *testing.T) {
mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
s.AttemptKey = l.AttemptKey
mustJournal(t, j.BeginTurn(ctx, s, provider.Turn{ID: "resumed", AdmissionID: "resumed-admit", Prompt: "hello"}))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err = j.ObserveDirect(ctx, s, codexUsage("resumed", 30000, 150))
mustJournal(t, err)
u, err := j.ObserveDirect(ctx, s, directComplete("resumed"))
@@ -320,6 +328,7 @@ func TestDirectUsageResumeRejectsChangedBinding(t *testing.T) {
j, l, s, p := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err := j.ObserveDirect(ctx, s, codexUsage("turn", 100, 10))
mustJournal(t, err)
_, err = j.ObserveDirect(ctx, s, directComplete("turn"))
@@ -425,6 +434,7 @@ func TestDirectCompletionNeedsContainment(t *testing.T) {
j, l, s, p := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
_, err := j.ObserveDirect(ctx, s, codexUsage("turn", 100, 10))
mustJournal(t, err)
_, err = j.ObserveDirect(ctx, s, directComplete("turn"))
@@ -444,6 +454,7 @@ func TestDirectJournalProjectionSecrets(t *testing.T) {
j, _, s, _ := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
e := provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "tool.output", Sequence: 1, Payload: json.RawMessage(`{"output":"Bearer private-token ` + strings.Repeat("x", 20000) + ` custom-secret","input_tokens":9007199254740993}`)}
p := EventPump{Journal: j, Secrets: []string{"custom-secret"}, Contain: func(context.Context) error { return nil }}
mustJournal(t, p.AppendDirect(ctx, s, e, journalEvent("template", 1)))
@@ -491,6 +502,7 @@ func TestDirectJournalFrameRetirement(t *testing.T) {
j, l, s, p := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"n":1}`)))
_, err := j.db.Exec("UPDATE direct_attempts SET contained=1")
mustJournal(t, err)
@@ -511,7 +523,7 @@ func TestDirectJournalFrameRetirement(t *testing.T) {
t.Fatal("raw bytes retired before upload acknowledgement")
}
mustJournal(t, pump.Flush(ctx, 10))
- mustJournal(t, j.db.QueryRow("SELECT pending FROM direct_frames").Scan(&pending))
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&pending))
if pending != 0 {
t.Fatal("acknowledged bytes still fill pending budget")
}
@@ -521,6 +533,7 @@ func TestDirectInterruptedSyntheticFailure(t *testing.T) {
j, _, s, _ := directFixture(t, "codex")
ctx := context.Background()
mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello"))
p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
template := journalEvent("template", 1)
template.ActionID = 1
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 44cdf08d..484eebed 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -82,7 +82,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 > 2 {
+ if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 3 {
db.Close()
return nil, ErrJournal
}
@@ -109,6 +109,14 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
if err == nil && version < 2 {
_, err = tx.ExecContext(ctx, directSchema)
}
+ if err == nil && version < 3 {
+ _, err = tx.ExecContext(ctx, `CREATE INDEX IF NOT EXISTS direct_frames_pending ON direct_frames(pending);
+ CREATE INDEX IF NOT EXISTS direct_events_projected ON direct_events(projected);
+ CREATE INDEX IF NOT EXISTS direct_events_attempt_pending ON direct_events(attempt,projected);
+ CREATE INDEX IF NOT EXISTS journal_events_direct_pending ON journal_events(json_extract(body,'$.agent_id')) WHERE acked=0;
+ DELETE FROM direct_frames WHERE pending=0;
+ PRAGMA user_version=3;`)
+ }
if err == nil {
_, err = tx.ExecContext(ctx, "UPDATE journal_streams SET ready=0")
}
@@ -142,7 +150,10 @@ func (j *Journal) AdmissionAllowed(ctx context.Context) error {
}
var saved int
var size int64
- if err := j.db.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&saved, &size); err != nil || saved != 0 || size >= j.maxBytes {
+ if err := j.db.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&saved, &size); err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ if saved != 0 || size >= j.maxBytes {
return ErrJournal
}
var unreconciled int
diff --git a/internal/runner/journal_reset.go b/internal/runner/journal_reset.go
index 0ee68ef3..cf4d1f6b 100644
--- a/internal/runner/journal_reset.go
+++ b/internal/runner/journal_reset.go
@@ -1,13 +1,14 @@
package runner
import (
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runnerproto"
"context"
"errors"
)
func nonStorageError(err error) bool {
- return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, runnerproto.ErrInvalid)
+ return errors.Is(err, provider.ErrIdentity) || errors.Is(err, errDirectUncertain) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, runnerproto.ErrInvalid)
}
func (j *Journal) storageFailure(ctx context.Context, err error) error {
if ctx.Err() != nil {
diff --git a/internal/runner/journal_test.go b/internal/runner/journal_test.go
index e1b94293..e38dc601 100644
--- a/internal/runner/journal_test.go
+++ b/internal/runner/journal_test.go
@@ -338,7 +338,7 @@ func TestRunnerJournalDurabilityConfiguration(t *testing.T) {
if syncLevel != 2 || mode != "delete" {
t.Fatal("journal writes are not durably synced", syncLevel, mode)
}
- _, err = j.db.Exec("PRAGMA user_version=3")
+ _, err = j.db.Exec("PRAGMA user_version=4")
mustJournal(t, err)
mustJournal(t, j.Close())
if other, err := OpenJournal(journalCtx, path); err == nil {