oficina / equipo Public

feat: journal provider streams and preserve uncertain turns

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 50920582066b91d14f7c1f3f86c8b78530255662 parent 41f4bba
26 files changed, +3,981 −45
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md +1,421 −0
  • internal/equipo/runner_events.go +2 −2
  • internal/equipotest/runner_events_test.go +46 −1
  • internal/runner/capture.go +395 −0
  • internal/runner/capture_test.go +463 −0
  • internal/runner/containment/linux.go +25 −0
  • internal/runner/containment/recovery.go +90 −1
  • internal/runner/containment/recovery_test.go +64 −0
  • internal/runner/direct_events.go +211 −0
  • internal/runner/direct_recovery.go +336 −0
  • internal/runner/direct_recovery_test.go +538 −0
  • internal/runner/direct_usage.go +148 −0
  • internal/runner/journal.go +34 −7
  • internal/runner/journal_reset.go +3 −1
  • internal/runner/journal_test.go +1 −1
  • internal/runner/provider/claude/launcher.go +13 −0
  • internal/runner/provider/claude/launcher_test.go +67 −0
  • internal/runner/provider/codex/launcher.go +17 −5
  • internal/runner/provider/codex/launcher_test.go +64 −0
  • internal/runner/provider/codex/rpc.go +5 −2
  • internal/runner/provider/types.go +12 −0
  • internal/runner/tool_journal.go +1 −1
  • internal/runner/usage.go +7 −6
  • internal/runner/usage_test.go +16 −16
  • internal/runner/workflow_turn.go +1 −1

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index c5f467f6..778d1d61 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -21,5 +21,5 @@ time internal/runner 330s Final corrected package rerun measured 152.897s; revie
perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen.
perf GET /api/runner/v1/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
-size internal/runner 6500 - Final fixes add guarded journal reset, typed diagnostics and bounded prompts beside the mandated runner workflow; current source count: 5896.
+size internal/runner 7800 - Task 7 adds durable capture, direct recovery, atomic projection and provider accounting beside the required journal APIs; current source count: 7576.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
index 2780147d..cd192789 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md
@@ -12229,3 +12229,1424 @@ No UI strings or copy.go entries changed. New internal diagnostic codes are `cod
The remaining concerns are release/integration limits, not permission to weaken policy: real config/read defaults and layer shape, strict-config behavior, full deny-profile coverage including native/image/MCP readers and aliases, and on-request approval behavior still require Task 11b's bounded certification. Unexpected live readback is refused. These offline tests do not certify the installed provider sandbox. Task 7 owns durable accounting/recovery, and Task 8 owns tool configuration and validated answers.
No provider session, sign-in, enrolment, real credential-home creation, provider prompt, copy-review server, helper agent, push, merge, deployment, README edit or .claude/HANDOFF.md was performed. All test server goroutines and pipes were stopped by test cleanup. Owned scratch is removed after the evidence is saved; default Go caches are retained.
+
+
+## Task 7: Journal provider stdout and recover without replaying work
+
+Status: DONE_WITH_CONCERNS.
+Commit subject: `feat: journal provider streams and preserve uncertain turns`.
+Branch: `plan-2b`. Work stayed in `/home/paulca/amadan.net/oficina/equipo-plan-2b`.
+
+### What changed
+
+The private SQLite journal now migrates from version 1 to version 2 in an ordered transaction. Existing events, acknowledgements, intents and legacy accounting remain available. Reopen retains FULL synchronous commits and DELETE journaling. Unknown newer versions are refused. The upgrade test removes the v2 tables to reconstruct a v1 journal, upgrades it, and checks the existing outbox event and synchronous setting.
+
+`NewCaptureFactory(*Journal)` implements `provider.CaptureFactory`. It exclusively reads stdout and stderr and supplies the adapter's writable stdin wrapper. Each process has a durable stream ID, independent of upload identity, and locally increasing frame sequence numbers. Frames are validated and redacted without changing JSON structure or rounding integer counters. Duplicate keys, malformed JSON, a partial trailing record, oversized records and storage failures stop capture and contain the process. SQLite commit completes before a frame reaches an adapter. The internal frame limit is exactly 1 MiB. Stderr is separate, drains independently, and retains at most 64 KiB. A blocked read is interrupted by context cancellation; a blocked frame consumer has a five-second containment bound.
+
+The existing 128 MiB pending outbox limit now includes pending captured frames and normalized direct events as well as legacy events and tool results. It is checked before launch, before prompt writes and inside append transactions. Captured bytes leave that pending budget only after containment, normalization and acknowledgement; archived bytes remain in the private journal. SQLite FULL was injected with max_page_count to exercise the storage-exhaustion path without filling the shared filesystem.
+
+`Journal.BeginTurn` durably binds the session, turn ID, admission ID and prompt hash. The capture writer consumes that single-use intent in a committed transaction before writing the prompt. A partial or failed write stays uncertain. There is no resend path. Codex startup/configuration RPCs remain prompt-free; turn/start must match the admitted session and prompt. Both adapters now call the durable session-binding and turn-barrier hooks and retain capture sequence numbers in normalized events. Fake captures can still implement the Task 1 interface without the production hooks.
+
+`NewDirectHost(journal, manager)` records the concrete launch and namespace manifest before the manager can fork or release a namespace. The containment process exposes its immutable Record and a Contain method for capture failures. Namespace records now also retain the runner parent's PID and start ticks. Direct recovery compares namespace identity, boot, parent identity, namespace-manifest hash, egress hash and policy hash against the journaled launch; it also verifies the saved policy manifest's digest. A mismatch refuses recovery and leaves scratch alone.
+
+`Journal.RecoverDirect` returns durable Recovery records, preserves completed accounting, quarantines unfinished turns as waiting_for_person, and invalidates pending answers. `Journal.ReconcileDirect` checks containment and cleans only owned attempt scratch. HostPID=0 records never sent a prompt because the helper release follows durable init identity. New records wait for the recorded parent's death before cleanup. The crash window before the namespace record itself is written is also recoverable. Intent-only records become never_started and do not permanently block restart. Completed turns without containment remain completed_needs_containment and cannot authorize dependent admission. Live capture cancellation now durably quarantines the turn and invalidates answers immediately, including before any restart. A late completion cannot replace that uncertainty with known usage.
+
+`UsageAccumulator.Observe(provider.Event)` handles the direct adapters. The old reader remains as ObservePaseo for historical evidence and the not-yet-cut-over runtime. Provider/version/session baselines, per-turn settled receipts, known/unknown flags and cost baselines are saved with normalized events in one transaction. Claude counts result.usage input plus cache read plus cache creation once, and output once; it ignores modelUsage for settlement. Display cost uses cumulative differences. Codex settles the last durable total at the turn boundary: 14,054/96 followed by 28,254/142 produces 28,254/142 once, neither their sum nor last=14,200/46. Resume keeps the baseline. Regression, reset, compaction, missing required fields and overflow preserve uncertainty. Calls remain one per admitted user turn.
+
+`EventPump.AppendDirect` records normalized events, usage checkpoints and upload projection atomically. Large envelopes are preserved in ordered base64 chunks with a final bounded lifecycle/usage reference; every instance payload remains at most 16 KiB. Secrets are removed before chunk encoding. Duplicate delivery keeps stable IDs. The instance recognizes direct turn.completed and turn.failed events in its existing atomic receipt path, including replay after a server commit with a lost ACK. Synthetic adapter failure events without raw stdout payloads become an empty failure payload, never a fabricated completion or usage receipt.
+
+The runner reset also requires direct containment and pending projections to be reconciled. The runner source-size exception is now 7,800 lines for the required adjacent journal/capture/recovery APIs; the measured source count is 7,576 lines. The existing time budgets are unchanged.
+
+### Files
+
+- `.rastrillo/budgets.txt`
+- `internal/equipo/runner_events.go`
+- `internal/equipotest/runner_events_test.go`
+- `internal/runner/capture.go`
+- `internal/runner/capture_test.go`
+- `internal/runner/containment/linux.go`
+- `internal/runner/containment/recovery.go`
+- `internal/runner/containment/recovery_test.go`
+- `internal/runner/direct_events.go`
+- `internal/runner/direct_recovery.go`
+- `internal/runner/direct_recovery_test.go`
+- `internal/runner/direct_usage.go`
+- `internal/runner/journal.go`
+- `internal/runner/journal_reset.go`
+- `internal/runner/journal_test.go`
+- `internal/runner/provider/claude/launcher.go`
+- `internal/runner/provider/claude/launcher_test.go`
+- `internal/runner/provider/codex/launcher.go`
+- `internal/runner/provider/codex/launcher_test.go`
+- `internal/runner/provider/codex/rpc.go`
+- `internal/runner/provider/types.go`
+- `internal/runner/tool_journal.go`
+- `internal/runner/usage.go`
+- `internal/runner/usage_test.go`
+- `internal/runner/workflow_turn.go`
+
+- `docs/superpowers/plans/CONTROLLER-REPORT-plan-2b.md`: this appended controller evidence.
+- `.superpowers/sdd/2026-11-03-equipo-plan-2b-direct/task-7-report.md`: full local report; ignored by Git, like the earlier task reports.
+
+
+### Interpretations and integration limits
+
+1. Raw stdout is durable before the adapter validates its meaning. A raw-only completion at a crash boundary remains available as evidence but does not gain completion authority without the durable normalized event/accounting transaction. Recovery preserves explicit uncertainty rather than trusting provider rollout/history files.
+2. A new production direct launcher must receive NewDirectHost and NewCaptureFactory. Task 9/11a must compose these with startup ReconcileDirect and feed every normalized event through EventPump.AppendDirect. This task does not switch the existing Paseo runtime or invent new scheduler authority. The small ObservePaseo compatibility changes preserve the existing runtime until cutover.
+3. The existing adapters still refuse unknown sessions after a launcher-process restart. This task establishes durable recovery, accounting and replay but does not add an adapter rehydration authority API. A known completed session can continue only with a new admission, the same binding and policy, preserved baseline and required containment. Cross-restart continuation, if added later, must retain those checks; it is not automatic recovery.
+4. Legacy intent-only namespace records lack parent identity. They are handled in startup recovery using the existing parent-death/release-pipe lifecycle. Newly written records provide explicit parent PID/start-tick proof. No harness is released from an intent-only record, and no numeric host-PID guess or host process scan is used.
+5. The pinned Codex probe omits cache-detail counters. Known aggregate input/output totals still settle; optional cache counter absence is retained as nil in the durable checkpoint. Missing required aggregate counters remains unknown. team.Usage has no independent cache-known flag, so omitted cache detail must not be presented as a newly verified zero.
+6. Invalidating the existing unscoped pending-answer table on direct interruption/recovery is deliberately conservative. Task 8 owns the direct permission relay and any finer per-attempt answer association. Capture currently permits only the adapters' existing startup/turn transport, not a new permission-answer protocol.
+7. There was no live provider gate in this run. No real provider session, sign-in, enrolment, credential-home creation or model prompt occurred. Provider adapter tests use existing fake fixtures only. Live certification remains Task 11b. No make ci or whole-suite test was run, as instructed.
+
+### RED evidence
+
+The initial required RED command failed to compile because the new APIs did not exist. It is recorded as an API red, not as behavioral guard evidence. The later red runs and compiling mutations supply behavioral evidence.
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest -run 'TestDirectCrash|TestDirectCompletion|TestDirectInterrupted|TestDirectJournal|TestDirectUsage' -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+# amadan.net/oficina/equipo/internal/runner [amadan.net/oficina/equipo/internal/runner.test]
+internal/runner/capture_test.go:36:18: j.recordDirectLaunch undefined (type *Journal has no field or method recordDirectLaunch)
+internal/runner/capture_test.go:46:11: undefined: NewCaptureFactory
+internal/runner/capture_test.go:48:18: j.BeginTurn undefined (type *Journal has no field or method BeginTurn)
+internal/runner/capture_test.go:50:100: j.AppendFrame undefined (type *Journal has no field or method AppendFrame)
+internal/runner/capture_test.go:53:21: reopened.RecoverDirect undefined (type *Journal has no field or method RecoverDirect)
+internal/runner/capture_test.go:55:14: reopened.BeginTurn undefined (type *Journal has no field or method BeginTurn)
+internal/runner/capture_test.go:64:11: undefined: NewCaptureFactory
+internal/runner/capture_test.go:74:11: undefined: NewCaptureFactory
+internal/runner/direct_recovery_test.go:14:78: j.BeginTurn undefined (type *Journal has no field or method BeginTurn)
+internal/runner/direct_recovery_test.go:15:102: j.ObserveDirect undefined (type *Journal has no field or method ObserveDirect)
+internal/runner/direct_recovery_test.go:15:102: too many errors
+FAIL amadan.net/oficina/equipo/internal/runner [build failed]
+ok amadan.net/oficina/equipo/internal/equipotest 0.075s [no tests to run]
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run TestDirectInterruptedIntentOnly -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectInterruptedIntentOnly (0.03s)
+ recovery_test.go:531: intent-only restart blocked: {Record:{ID:abcdefabcdefabcdefabcdefabcdefab AttemptKey:intent BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID: ManifestHash:manifest EgressHash: PolicyHash:policy HostPID:0 StartTicks:0} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 34ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.037s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run TestDirectCompletionServerCommitBeforeACK -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.07s)
+ runner_events_test.go:491: direct receipt lost or duplicated: [{ID:1 Account:LHLQ5B5KMS7WZVRWY3I5YQDVKE 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:0 InputTokens:0 OutputTokens:0 CostMicros:0} State:open ReceiptID: SettledBy: CreatedAt:2026-11-03 14:33:39.217110843 +0000 UTC SettledAt:0001-01-01 00:00:00 +0000 UTC}]
+FAIL
+rastrillo-budget/v1 ran 1.075s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.125s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectJournalChunks|TestDirectInterruptedBinding|TestDirectJournalProjectionAtomic|TestDirectUsageResumeBinding' -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectJournalChunks (0.12s)
+ direct_recovery_test.go:83: lifecycle truncated
+FAIL
+rastrillo-budget/v1 ran 618ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.621s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectUsageResumeRejectsChangedBinding -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectUsageResumeRejectsChangedBinding (1.06s)
+ --- FAIL: TestDirectUsageResumeRejectsChangedBinding/policy (0.20s)
+ direct_recovery_test.go:103: resume trusted changed durable binding policy
+ --- FAIL: TestDirectUsageResumeRejectsChangedBinding/account (0.24s)
+ direct_recovery_test.go:103: resume trusted changed durable binding account
+ --- FAIL: TestDirectUsageResumeRejectsChangedBinding/binding (0.20s)
+ direct_recovery_test.go:103: resume trusted changed durable binding binding
+ --- FAIL: TestDirectUsageResumeRejectsChangedBinding/version (0.22s)
+ direct_recovery_test.go:103: resume trusted changed durable binding version
+ --- FAIL: TestDirectUsageResumeRejectsChangedBinding/unknown-resume (0.21s)
+ direct_recovery_test.go:103: resume trusted changed durable binding unknown-resume
+FAIL
+rastrillo-budget/v1 ran 1.063s
+FAIL amadan.net/oficina/equipo/internal/runner 1.067s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectJournalProjectionSecrets -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectJournalProjectionSecrets (0.35s)
+ direct_recovery_test.go:442: projection leaked credentials or rounded counters
+FAIL
+rastrillo-budget/v1 ran 347ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.380s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectInterruptedManifestIntegrity -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectInterruptedManifestIntegrity (0.37s)
+ direct_recovery_test.go:455: changed saved launch manifest accepted
+FAIL
+rastrillo-budget/v1 ran 372ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.378s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectJournalFrameRetirement -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectJournalFrameRetirement (0.53s)
+ direct_recovery_test.go:461: raw bytes retired before normalization
+FAIL
+rastrillo-budget/v1 ran 531ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.534s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectInterruptedBinding/(boot|parent)' -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectInterruptedBinding (0.31s)
+ --- FAIL: TestDirectInterruptedBinding/boot (0.00s)
+ direct_recovery_test.go:197: recovered identity mismatch accepted boot
+ --- FAIL: TestDirectInterruptedBinding/parent (0.00s)
+ direct_recovery_test.go:197: recovered identity mismatch accepted parent
+FAIL
+rastrillo-budget/v1 ran 315ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.318s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectInterruptedLiveCapture -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectInterruptedLiveCapture (0.48s)
+ capture_test.go:438: live cancellation left turn dispatchable dispatched
+FAIL
+rastrillo-budget/v1 ran 476ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.478s
+FAIL
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run TestDirectInterruptedSyntheticFailure -count=1
+```
+
+Exit 1. Output excerpt:
+
+```text
+--- FAIL: TestDirectInterruptedSyntheticFailure (0.24s)
+ direct_recovery_test.go:523: runner.invalid
+FAIL
+rastrillo-budget/v1 ran 242ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.244s
+FAIL
+```
+
+
+### GREEN evidence
+
+The hard-crash tests run a child test executable and terminate it with os.Exit at committed intent, before/after stdin, before/after frame commit, before upload, and server-commit-before-ACK boundaries. The parent reopens the same journal, checks exact stdin-write counts, committed/rolled-back frames, preserved usage and stable replay identity. The instance test separately exercises actual atomic server ingestion and replay after a lost acknowledgement.
+
+The final required command ran after all code changes and all mutations were restored. The additional integration and legacy regression commands passed before the last live-interruption refinement; that refinement was then covered by its own green run and the final required command. No affected adapter or legacy source changed after those regression runs.
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest -run 'TestDirectCrash|TestDirectCompletion|TestDirectInterrupted|TestDirectJournal|TestDirectUsage' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 29.651s
+ok amadan.net/oficina/equipo/internal/equipotest 1.590s
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment ./internal/runner/provider/claude ./internal/runner/provider/codex -run 'TestDirect|TestNamespaceRecovery|TestClaudeNoPromptBeforeAdmission|TestClaudeResume|TestClaudeWriteCancellation|TestClaudeCaptureSequence|TestCodexLifecycle|TestCodexAppServerPolicy|TestCodexCaptureRequired' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner/containment 2.622s
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 5.635s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 2.470s
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/equipotest -run 'TestRunnerJournal|TestBufferFull|TestRunnerEventReplay|TestTimelineEpoch|TestUsage|TestNormalize|TestQuestion' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 7.438s
+ok amadan.net/oficina/equipo/internal/equipotest 29.490s
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectInterruptedLiveCapture|TestDirectJournalFailureContains|TestDirectCrashBoundaries|TestDirectJournalShortInput' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 13.056s
+```
+
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run 'TestDirectInterruptedLiveCapture|TestDirectInterruptedSyntheticFailure' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 1.034s
+```
+
+
+### Guard mutations
+
+Each mutation was applied alone, the named test command was run, and the file was restored in a finally block before the next mutation. All 51 retained mutations compiled and failed in the named test. These include moving durable commit after consumption, disabling FULL sync, permitting a repeated uncertain write, resetting the saved baseline, summing cumulative counters, and using last instead of total.
+
+One initial late-completion mutation passed because the test checked state only after another recovery sweep. That was not counted as guard evidence. The test was strengthened to check the immediate returned usage before another sweep; the same mutation then failed. The initial weak test result is recorded below for completeness. No mutation is left in the implementation.
+
+
+#### sync-after-consumption
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalCommitBeforeDelivery$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalCommitBeforeDelivery (0.30s)
+ capture_test.go:200: sql: no rows in result set
+FAIL
+rastrillo-budget/v1 ran 299ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.304s
+FAIL
+```
+
+
+#### sync-off
+
+File: `internal/runner/journal.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalUpgrade$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalUpgrade (0.22s)
+ direct_recovery_test.go:172: capture commits are not FULL synchronous
+FAIL
+rastrillo-budget/v1 ran 222ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.227s
+FAIL
+```
+
+
+#### resend-uncertain-input
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectCrashSingleUseInput$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCrashSingleUseInput (0.45s)
+ capture_test.go:335: same prompt sent twice
+FAIL
+rastrillo-budget/v1 ran 447ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.455s
+FAIL
+```
+
+
+#### baseline-reset
+
+File: `internal/runner/direct_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageDeltas$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageDeltas (0.55s)
+ direct_recovery_test.go:34: cumulative totals settled incorrectly: <nil>
+FAIL
+rastrillo-budget/v1 ran 555ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.559s
+FAIL
+```
+
+
+#### sum-cumulative
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageDeltas$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageDeltas (0.56s)
+ direct_recovery_test.go:34: cumulative totals settled incorrectly: &{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:42308 OutputTokens:238 CostMicros:0}
+FAIL
+rastrillo-budget/v1 ran 556ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.561s
+FAIL
+```
+
+
+#### use-last-request
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageDeltas$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageDeltas (0.57s)
+ direct_recovery_test.go:34: cumulative totals settled incorrectly: &{CachedInputTokens:0 CostUnavailable:true Calls:1 InputTokens:14200 OutputTokens:46 CostMicros:0}
+FAIL
+rastrillo-budget/v1 ran 568ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.573s
+FAIL
+```
+
+
+#### claude-cache-write
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageDeltas$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageDeltas (1.03s)
+ direct_recovery_test.go:83: Claude per-turn usage: &{CachedInputTokens:3566 CostUnavailable:true Calls:1 InputTokens:3568 OutputTokens:3 CostMicros:0}
+FAIL
+rastrillo-budget/v1 ran 1.035s
+FAIL amadan.net/oficina/equipo/internal/runner 1.041s
+FAIL
+```
+
+
+#### sum-cumulative-cost
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageDeltas$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageDeltas (0.92s)
+ direct_recovery_test.go:88: summed cumulative cost 0.25
+FAIL
+rastrillo-budget/v1 ran 919ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.924s
+FAIL
+```
+
+
+#### allow-regression
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageDeltas$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageDeltas (0.75s)
+ --- FAIL: TestDirectUsageDeltas/reset (0.00s)
+ direct_recovery_test.go:70: uncertain counters became known
+ --- FAIL: TestDirectUsageDeltas/compaction (0.00s)
+ direct_recovery_test.go:70: uncertain counters became known
+FAIL
+rastrillo-budget/v1 ran 751ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.756s
+FAIL
+```
+
+
+#### ignore-compaction
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageCompaction$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageCompaction (0.00s)
+ direct_recovery_test.go:413: compaction invented verified baseline
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner 0.003s
+FAIL
+```
+
+
+#### frame-overflow
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFailureContains/outbox-crossing$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFailureContains (0.43s)
+ --- FAIL: TestDirectJournalFailureContains/outbox-crossing (0.43s)
+ capture_test.go:182: uncommitted or invalid frame escaped
+FAIL
+rastrillo-budget/v1 ran 429ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.457s
+FAIL
+```
+
+
+#### frame-limit
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFailureContains/oversized$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFailureContains (0.64s)
+ --- FAIL: TestDirectJournalFailureContains/oversized (0.64s)
+ capture_test.go:182: uncommitted or invalid frame escaped
+FAIL
+rastrillo-budget/v1 ran 640ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.657s
+FAIL
+```
+
+
+#### duplicate-json-key
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFailureContains/duplicate-key$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFailureContains (0.42s)
+ --- FAIL: TestDirectJournalFailureContains/duplicate-key (0.42s)
+ capture_test.go:182: uncommitted or invalid frame escaped
+FAIL
+rastrillo-budget/v1 ran 421ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.442s
+FAIL
+```
+
+
+#### stderr-limit
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFailureContains/stderr$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFailureContains (0.62s)
+ --- FAIL: TestDirectJournalFailureContains/stderr (0.62s)
+ capture_test.go:175: unbounded stderr
+FAIL
+rastrillo-budget/v1 ran 622ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.625s
+FAIL
+```
+
+
+#### atomic-completion
+
+File: `internal/runner/direct_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalProjectionAtomic$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalProjectionAtomic (0.62s)
+ direct_recovery_test.go:227: completion escaped projection rollback
+FAIL
+rastrillo-budget/v1 ran 622ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.627s
+FAIL
+```
+
+
+#### late-completion-charge
+
+File: `internal/runner/direct_events.go`. Initial weak test: PASS, not accepted as mutation evidence; strengthened and rerun below.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedWaitsForPerson$ -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.671s
+```
+
+
+#### unknown-charge-reset
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedWaitsForPerson$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedWaitsForPerson (0.42s)
+ direct_recovery_test.go:133: unknown charge erased: [{AttemptKey:attempt SessionID:session TurnID:turn State:completed_needs_containment Usage:<nil>}]
+FAIL
+rastrillo-budget/v1 ran 420ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.423s
+FAIL
+```
+
+
+#### pending-answer
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedWaitsForPerson$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedWaitsForPerson (0.52s)
+ direct_recovery_test.go:138: pending answer remained valid
+FAIL
+rastrillo-budget/v1 ran 522ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.525s
+FAIL
+```
+
+
+#### late-completion-charge-strengthened
+
+File: `internal/runner/direct_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedWaitsForPerson$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedWaitsForPerson (0.66s)
+ direct_recovery_test.go:141: late completion returned known usage after interruption
+FAIL
+rastrillo-budget/v1 ran 662ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.664s
+FAIL
+```
+
+
+#### namespace-manifest
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedBinding/manifest$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedBinding (0.40s)
+ --- FAIL: TestDirectInterruptedBinding/manifest (0.00s)
+ direct_recovery_test.go:195: recovered identity mismatch accepted manifest
+FAIL
+rastrillo-budget/v1 ran 396ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.399s
+FAIL
+```
+
+
+#### namespace-policy
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedBinding/policy$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedBinding (0.44s)
+ --- FAIL: TestDirectInterruptedBinding/policy (0.01s)
+ direct_recovery_test.go:195: recovered identity mismatch accepted policy
+FAIL
+rastrillo-budget/v1 ran 439ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.442s
+FAIL
+```
+
+
+#### journal-policy
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedBinding$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedBinding (0.36s)
+ direct_recovery_test.go:209: namespace record detached from journaled launch policy
+FAIL
+rastrillo-budget/v1 ran 361ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.363s
+FAIL
+```
+
+
+#### saved-manifest-integrity
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedManifestIntegrity$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedManifestIntegrity (0.35s)
+ direct_recovery_test.go:455: changed saved launch manifest accepted
+FAIL
+rastrillo-budget/v1 ran 346ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.348s
+FAIL
+```
+
+
+#### intent-only-recovery
+
+File: `internal/runner/containment/recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestDirectInterruptedIntentOnly$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedIntentOnly (0.04s)
+ recovery_test.go:541: intent-only restart blocked: {Record:{ID:abcdefabcdefabcdefabcdefabcdefab AttemptKey:intent BootID:1edb59fc-5665-4f1e-84f5-3b03b0992119 NamespaceID: ManifestHash:manifest EgressHash: PolicyHash:policy ParentPID:0 ParentTicks:0 HostPID:0 StartTicks:0} Exit:{Code:-1 Signal:0 ObservedAt:0001-01-01 00:00:00 +0000 UTC} Verified:false} namespace_identity_unproven
+FAIL
+rastrillo-budget/v1 ran 36ms
+FAIL amadan.net/oficina/equipo/internal/runner/containment 0.038s
+FAIL
+```
+
+
+#### parent-death-before-cleanup
+
+File: `internal/runner/containment/recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/containment -run ^TestDirectInterruptedParentLifecycle$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedParentLifecycle (60.00s)
+ recovery_test.go:576: cleanup preceded parent death
+FAIL
+rastrillo-budget/v1 ran 1m0.002s
+FAIL amadan.net/oficina/equipo/internal/runner/containment 60.004s
+FAIL
+```
+
+
+#### server-direct-settlement
+
+File: `internal/equipo/runner_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipotest -run ^TestDirectCompletionServerCommitBeforeACK$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCompletionServerCommitBeforeACK (1.75s)
+ runner_events_test.go:512: direct receipt lost or duplicated: [{ID:1 Account:HX6QHA3IKT2S3JTZQVCD3HNXCM 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:0 InputTokens:0 OutputTokens:0 CostMicros:0} State:open ReceiptID: SettledBy: CreatedAt:2026-11-03 14:52:33.655263654 +0000 UTC SettledAt:0001-01-01 00:00:00 +0000 UTC}]
+FAIL
+rastrillo-budget/v1 ran 1.754s
+FAIL amadan.net/oficina/equipo/internal/equipotest 1.834s
+FAIL
+```
+
+
+#### resume-policy-binding
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageResumeRejectsChangedBinding/policy$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageResumeRejectsChangedBinding (0.80s)
+ --- FAIL: TestDirectUsageResumeRejectsChangedBinding/policy (0.80s)
+ direct_recovery_test.go:346: resume trusted changed durable binding policy
+FAIL
+rastrillo-budget/v1 ran 798ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.832s
+FAIL
+```
+
+
+#### active-turn-replacement
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectCrashSingleUseInput$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCrashSingleUseInput (0.82s)
+ capture_test.go:341: active turn replaced
+FAIL
+rastrillo-budget/v1 ran 816ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.829s
+FAIL
+```
+
+
+#### uncontained-admission
+
+File: `internal/runner/journal.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedReconcileIntent/intent$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedReconcileIntent (0.39s)
+ --- FAIL: TestDirectInterruptedReconcileIntent/intent (0.39s)
+ direct_recovery_test.go:385: missing containment admitted dependent work
+FAIL
+rastrillo-budget/v1 ran 393ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.406s
+FAIL
+```
+
+
+#### resume-needs-containment
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectCompletionNeedsContainment$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCompletionNeedsContainment (0.72s)
+ direct_recovery_test.go:433: completion without containment admitted dependent work
+FAIL
+rastrillo-budget/v1 ran 723ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.734s
+FAIL
+```
+
+
+#### frame-sequence
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFrameSequence$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFrameSequence (0.39s)
+ capture_test.go:351: frame order regressed
+FAIL
+rastrillo-budget/v1 ran 386ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.391s
+FAIL
+```
+
+
+#### unterminated-frame
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFailureContains/unterminated$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFailureContains (0.42s)
+ --- FAIL: TestDirectJournalFailureContains/unterminated (0.42s)
+ capture_test.go:182: uncommitted or invalid frame escaped
+FAIL
+rastrillo-budget/v1 ran 415ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.452s
+FAIL
+```
+
+
+#### chunk-size
+
+File: `internal/runner/direct_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalChunks$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalChunks (0.38s)
+ direct_recovery_test.go:244: runner.invalid
+FAIL
+rastrillo-budget/v1 ran 380ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.391s
+FAIL
+```
+
+
+#### chunk-secrets
+
+File: `internal/runner/direct_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalProjectionSecrets$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalProjectionSecrets (0.38s)
+ direct_recovery_test.go:443: projection leaked credentials or rounded counters
+FAIL
+rastrillo-budget/v1 ran 377ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.380s
+FAIL
+```
+
+
+#### claude-turn-barrier
+
+File: `internal/runner/provider/claude/launcher.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run ^TestDirectJournalAdapterBarrier$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalAdapterBarrier (1.30s)
+ --- FAIL: TestDirectJournalAdapterBarrier/false (0.66s)
+ launcher_test.go:899: journal turn barrier not called
+ --- FAIL: TestDirectJournalAdapterBarrier/true (0.64s)
+ launcher_test.go:881: failed journal barrier ignored
+FAIL
+rastrillo-budget/v1 ran 1.299s
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 1.301s
+FAIL
+```
+
+
+#### codex-turn-barrier
+
+File: `internal/runner/provider/codex/launcher.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestDirectJournalAdapterBarrier$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalAdapterBarrier (0.81s)
+ --- FAIL: TestDirectJournalAdapterBarrier/false (0.42s)
+ launcher_test.go:923: journal turn barrier not called
+ --- FAIL: TestDirectJournalAdapterBarrier/true (0.40s)
+ launcher_test.go:908: failed journal barrier ignored
+FAIL
+rastrillo-budget/v1 ran 814ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.816s
+FAIL
+```
+
+
+#### claude-session-binding
+
+File: `internal/runner/provider/claude/launcher.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run ^TestDirectJournalAdapterBarrier$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalAdapterBarrier (1.31s)
+ --- FAIL: TestDirectJournalAdapterBarrier/false (0.64s)
+ launcher_test.go:876: session not durably bound
+ --- FAIL: TestDirectJournalAdapterBarrier/true (0.68s)
+ launcher_test.go:876: session not durably bound
+FAIL
+rastrillo-budget/v1 ran 1.313s
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 1.315s
+FAIL
+```
+
+
+#### codex-session-binding
+
+File: `internal/runner/provider/codex/launcher.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestDirectJournalAdapterBarrier$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalAdapterBarrier (0.84s)
+ --- FAIL: TestDirectJournalAdapterBarrier/false (0.42s)
+ launcher_test.go:903: session not durably bound
+ --- FAIL: TestDirectJournalAdapterBarrier/true (0.42s)
+ launcher_test.go:903: session not durably bound
+FAIL
+rastrillo-budget/v1 ran 841ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.843s
+FAIL
+```
+
+
+#### short-stdin-write
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalShortInput$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalShortInput (0.47s)
+ capture_test.go:374: short stdin write reported success
+FAIL
+rastrillo-budget/v1 ran 470ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.472s
+FAIL
+```
+
+
+#### capture-containment
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFailureContains/disk-full$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFailureContains (0.41s)
+ --- FAIL: TestDirectJournalFailureContains/disk-full (0.41s)
+ capture_test.go:188: not contained: paseo_uncertain
+ runner.journal
+FAIL
+rastrillo-budget/v1 ran 406ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.408s
+FAIL
+```
+
+
+#### full-outbox-before-stdin
+
+File: `internal/runner/journal.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectCrashFullOutbox$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectCrashFullOutbox (0.53s)
+ capture_test.go:427: full outbox admitted stdin
+FAIL
+rastrillo-budget/v1 ran 527ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.529s
+FAIL
+```
+
+
+#### retire-before-normalization
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFrameRetirement$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFrameRetirement (0.54s)
+ direct_recovery_test.go:501: raw bytes retired before normalization
+FAIL
+rastrillo-budget/v1 ran 537ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.539s
+FAIL
+```
+
+
+#### retire-before-ack
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalFrameRetirement$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalFrameRetirement (0.66s)
+ direct_recovery_test.go:511: raw bytes retired before upload acknowledgement
+FAIL
+rastrillo-budget/v1 ran 664ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.667s
+FAIL
+```
+
+
+#### namespace-boot-binding
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedBinding/boot$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedBinding (0.34s)
+ --- FAIL: TestDirectInterruptedBinding/boot (0.00s)
+ direct_recovery_test.go:201: recovered identity mismatch accepted boot
+FAIL
+rastrillo-budget/v1 ran 344ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.346s
+FAIL
+```
+
+
+#### namespace-parent-binding
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedBinding/parent$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedBinding (0.31s)
+ --- FAIL: TestDirectInterruptedBinding/parent (0.00s)
+ direct_recovery_test.go:201: recovered identity mismatch accepted parent
+FAIL
+rastrillo-budget/v1 ran 311ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.314s
+FAIL
+```
+
+
+#### exact-json-counters
+
+File: `internal/runner/capture.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectJournalCommitBeforeDelivery$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalCommitBeforeDelivery (0.53s)
+ capture_test.go:202: frame not durably redacted with exact counters: {"authorization":"***","input_tokens":9007199254740992}
+FAIL
+rastrillo-budget/v1 ran 533ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.536s
+FAIL
+```
+
+
+#### claude-event-sequence
+
+File: `internal/runner/provider/claude/launcher.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/claude -run ^TestDirectJournalAdapterBarrier/false$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalAdapterBarrier (0.68s)
+ --- FAIL: TestDirectJournalAdapterBarrier/false (0.68s)
+ launcher_test.go:895: capture sequence lost before projection
+FAIL
+rastrillo-budget/v1 ran 679ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 0.681s
+FAIL
+```
+
+
+#### codex-event-sequence
+
+File: `internal/runner/provider/codex/launcher.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestDirectJournalAdapterBarrier/false$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectJournalAdapterBarrier (0.43s)
+ --- FAIL: TestDirectJournalAdapterBarrier/false (0.43s)
+ launcher_test.go:919: capture sequence lost before projection
+FAIL
+rastrillo-budget/v1 ran 430ms
+FAIL amadan.net/oficina/equipo/internal/runner/provider/codex 0.432s
+FAIL
+```
+
+
+#### claude-token-overflow
+
+File: `internal/runner/direct_usage.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectUsageClaudeUnknown$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectUsageClaudeUnknown (0.00s)
+ direct_recovery_test.go:474: unknown Claude usage settled: {"input_tokens":9223372036854775807,"cache_read_input_tokens":1,"cache_creation_input_tokens":0,"output_tokens":2}
+FAIL
+rastrillo-budget/v1 ran 0s
+FAIL amadan.net/oficina/equipo/internal/runner 0.003s
+FAIL
+```
+
+
+#### live-interruption-state
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedLiveCapture$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedLiveCapture (0.58s)
+ capture_test.go:452: live cancellation left turn dispatchable dispatched
+FAIL
+rastrillo-budget/v1 ran 583ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.586s
+FAIL
+```
+
+
+#### live-interruption-answers
+
+File: `internal/runner/direct_recovery.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedLiveCapture$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedLiveCapture (0.55s)
+ capture_test.go:456: live cancellation retained pending answers
+FAIL
+rastrillo-budget/v1 ran 553ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.555s
+FAIL
+```
+
+
+#### synthetic-failure
+
+File: `internal/runner/direct_events.go`. Compiled behavioral failure; restored.
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run ^TestDirectInterruptedSyntheticFailure$ -count=1
+```
+
+Exit 1:
+
+```text
+--- FAIL: TestDirectInterruptedSyntheticFailure (0.31s)
+ direct_recovery_test.go:527: runner.invalid
+FAIL
+rastrillo-budget/v1 ran 308ms
+FAIL amadan.net/oficina/equipo/internal/runner 0.311s
+FAIL
+```
+
+
+### User-facing strings
+
+No UI strings, README prose or copy.go entries changed, so there are no new copy.go entries to mark pending. No copy-review skill or server was invoked.
+
+New internal diagnostic code: runner.direct_uncertain. New recovery-state values: waiting_for_person, never_started, never_started_needs_containment, completed_needs_containment and completed. The direct_chunk kind, direct-v2 epoch, capture_sequence field, test diagnostics and source-budget explanation are technical metadata, not approved product copy. If these are later presented as user-facing language, add individually pending copy.go entries and complete the release copy pass.
+
+### Concerns and handback
+
+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.
diff --git a/internal/equipo/runner_events.go b/internal/equipo/runner_events.go
index f138683e..5becf1e3 100644
--- a/internal/equipo/runner_events.go
+++ b/internal/equipo/runner_events.go
@@ -56,7 +56,7 @@ func (s *Store) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, event
return s.execution.IngestRunnerEvent(ctx, p, event)
}
func (e *Execution) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, event runnerproto.Event) error {
- if event.Validate() != nil {
+ if event.Validate() != nil || ((event.Kind == "turn.completed" || event.Kind == "turn.failed") && (event.TurnID == "" || event.ActionID <= 0)) {
return ErrInvalid
}
return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
@@ -118,7 +118,7 @@ func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, a runnerAssi
if err = e.validators.Events(ctx, value, q); err != nil {
return err
}
- if event.Kind == "turn_completed" || event.Kind == "turn_failed" {
+ if event.Kind == "turn_completed" || event.Kind == "turn_failed" || event.Kind == "turn.completed" || event.Kind == "turn.failed" {
if e.validators.Receipt == nil {
return ErrUnavailable
}
diff --git a/internal/equipotest/runner_events_test.go b/internal/equipotest/runner_events_test.go
index 08a477a4..f6af0ed5 100644
--- a/internal/equipotest/runner_events_test.go
+++ b/internal/equipotest/runner_events_test.go
@@ -258,7 +258,7 @@ func TestRunnerJournalServerCommitBeforeACK(t *testing.T) {
executionMust(t, j.Append(connectionContext, e))
acc, err := j.Usage(connectionContext, agent, profile)
executionMust(t, err)
- u := acc.Observe(paseo.Event{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Payload: e.Payload})
+ u := acc.ObservePaseo(paseo.Event{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Payload: e.Payload})
if u == nil {
t.Fatal("journal did not restore usage")
}
@@ -476,3 +476,48 @@ func TestTimelineEpochChangedReset(t *testing.T) {
t.Fatal("replacement ID accepted a different target epoch")
}
}
+
+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")
+ }
+}
diff --git a/internal/runner/capture.go b/internal/runner/capture.go
new file mode 100644
index 00000000..3569cd5f
--- /dev/null
+++ b/internal/runner/capture.go
@@ -0,0 +1,395 @@
+package runner
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+const MaxFrameBytes = 1 << 20
+const maxDiagnostics = 64 << 10
+const directPendingSize = `((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 }
+
+func NewCaptureFactory(j *Journal) provider.CaptureFactory { return &captureFactory{j} }
+
+type containedCaptureProcess interface {
+ provider.Process
+ Contain(context.Context) error
+ Record() containment.Record
+}
+type captureInput struct {
+ journal *Journal
+ process containedCaptureProcess
+ launch provider.Launch
+ input io.WriteCloser
+ ctx context.Context
+ mu sync.Mutex
+ closed bool
+ fail func(error)
+}
+
+func (c *captureInput) BindSession(ctx context.Context, s provider.Session) error {
+ return c.journal.BindSession(ctx, s)
+}
+func (c *captureInput) BeginTurn(ctx context.Context, s provider.Session, t provider.Turn) error {
+ return c.journal.BeginTurn(ctx, s, t)
+}
+func (c *captureInput) Close() error { return c.input.Close() }
+func (c *captureInput) Write(raw []byte) (int, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.closed || c.ctx.Err() != nil {
+ return 0, errDirectUncertain
+ }
+ if len(raw) > MaxFrameBytes+1 || !bytes.HasSuffix(raw, []byte{'\n'}) || !uniqueFrame(bytes.TrimSpace(raw)) {
+ return 0, runnerproto.ErrInvalid
+ }
+ var v struct {
+ Type, Method string
+ Session string `json:"session_id"`
+ Message struct{ Role, Content string }
+ Params struct {
+ Thread string `json:"threadId"`
+ Input []struct{ Type, Text string }
+ }
+ }
+ if json.Unmarshal(raw, &v) != nil {
+ return 0, runnerproto.ErrInvalid
+ }
+ prompt, session := "", ""
+ switch c.launch.Selection.Provider {
+ case "claude":
+ if v.Type != "user" || v.Message.Role != "user" {
+ return 0, runnerproto.ErrInvalid
+ }
+ prompt, session = v.Message.Content, v.Session
+ case "codex":
+ if v.Method == "turn/start" {
+ if len(v.Params.Input) != 1 || v.Params.Input[0].Type != "text" {
+ return 0, runnerproto.ErrInvalid
+ }
+ prompt, session = v.Params.Input[0].Text, v.Params.Thread
+ } else {
+ switch v.Method {
+ case "initialize", "initialized", "account/read", "config/read", "thread/start", "thread/resume", "turn/interrupt":
+ default:
+ return 0, runnerproto.ErrInvalid
+ }
+ }
+ default:
+ return 0, runnerproto.ErrInvalid
+ }
+ if prompt != "" {
+ if err := c.journal.consumeTurn(c.ctx, c.launch.AttemptKey, session, prompt); err != nil {
+ return 0, err
+ }
+ } else if v.Type == "user" || v.Method == "turn/start" {
+ return 0, runnerproto.ErrInvalid
+ }
+ n, err := c.input.Write(raw)
+ if err != nil || n != len(raw) {
+ c.closed = true
+ if err == nil {
+ err = io.ErrShortWrite
+ }
+ c.fail(err)
+ }
+ return n, err
+}
+func (j *Journal) consumeTurn(ctx context.Context, attempt, session, prompt string) error {
+ if err := j.AdmissionAllowed(ctx); err != nil {
+ return err
+ }
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ err = func() error {
+ defer tx.Rollback()
+ result, e := tx.ExecContext(ctx, `UPDATE direct_turns SET state='dispatched' WHERE attempt=? AND session=? AND prompt_hash=? AND state='intent' AND EXISTS(SELECT 1 FROM direct_attempts WHERE attempt=? AND recovered=0)`, attempt, session, runnerproto.EventHash(prompt), attempt)
+ if e != nil {
+ return e
+ }
+ n, e := result.RowsAffected()
+ if e != nil {
+ return e
+ }
+ if n != 1 {
+ return errDirectUncertain
+ }
+ return tx.Commit()
+ }()
+ if err != nil && !errors.Is(err, errDirectUncertain) {
+ return j.storageFailure(ctx, err)
+ }
+ return err
+}
+func (f *captureFactory) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
+ proc, ok := p.(containedCaptureProcess)
+ if !ok || f.journal == nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ contain := func() error {
+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ return proc.Contain(cleanup)
+ }
+ if err := f.journal.AdmissionAllowed(ctx); err != nil {
+ return nil, errors.Join(err, contain())
+ }
+ if err := f.journal.recordDirectLaunch(ctx, l, proc.Record()); err != nil {
+ return nil, errors.Join(err, contain())
+ }
+ result, err := f.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET opened=1 WHERE attempt=? AND opened=0 AND recovered=0", l.AttemptKey)
+ if err != nil {
+ return nil, errors.Join(f.journal.storageFailure(ctx, err), contain())
+ }
+ if n, e := result.RowsAffected(); e != nil || n != 1 {
+ return nil, errors.Join(errDirectUncertain, contain())
+ }
+ input, stdout, stderr := p.Stdin(), p.Stdout(), p.Stderr()
+ if input == nil || stdout == nil || stderr == nil {
+ return nil, errors.Join(runnerproto.ErrInvalid, contain())
+ }
+ runCtx, cancel := context.WithCancel(ctx)
+ frames := make(chan provider.Frame)
+ done := make(chan error, 1)
+ var once sync.Once
+ var failure error
+ fail := func(e error) {
+ once.Do(func() {
+ failure = e
+ cancel()
+ input.Close()
+ stdout.Close()
+ stderr.Close()
+ containmentErr := contain()
+ cleanup, stopCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ journalErr := f.journal.interruptDirect(cleanup, l.AttemptKey, containmentErr == nil)
+ stopCleanup()
+ failure = errors.Join(failure, containmentErr, journalErr)
+ if ctx.Err() == nil || journalErr != nil {
+ _ = f.journal.fail()
+ }
+ })
+ }
+ ci := &captureInput{journal: f.journal, process: proc, launch: l, input: input, ctx: runCtx, fail: fail}
+ go func() {
+ stop := context.AfterFunc(runCtx, func() { input.Close(); stdout.Close(); stderr.Close() })
+ defer stop()
+ defer cancel()
+ diagnostics := make(chan error, 1)
+ go func() {
+ b, e := io.ReadAll(io.LimitReader(stderr, maxDiagnostics))
+ if e == nil {
+ _, e = io.Copy(io.Discard, stderr)
+ }
+ if e == nil {
+ _, e = f.journal.db.ExecContext(runCtx, "UPDATE direct_attempts SET diagnostics=? WHERE attempt=?", redactText(string(b), nil), l.AttemptKey)
+ }
+ diagnostics <- e
+ }()
+ reader := bufio.NewReaderSize(stdout, MaxFrameBytes+2)
+ var seq int64
+ for {
+ raw, e := reader.ReadSlice('\n')
+ if e == io.EOF && len(raw) == 0 {
+ break
+ }
+ if e != nil {
+ fail(e)
+ break
+ }
+ raw = bytes.TrimSuffix(raw, []byte{'\n'})
+ seq++
+ if e = f.journal.AppendFrame(runCtx, l.AttemptKey, p.ID(), seq, raw); e != nil {
+ fail(e)
+ break
+ }
+ 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)
+ break
+ }
+ timer := time.NewTimer(5 * time.Second)
+ select {
+ case frames <- provider.Frame{Sequence: seq, Bytes: saved}:
+ case <-runCtx.Done():
+ fail(runCtx.Err())
+ case <-timer.C:
+ fail(errDirectUncertain)
+ }
+ timer.Stop()
+ if runCtx.Err() != nil {
+ break
+ }
+ }
+ if e := <-diagnostics; e != nil {
+ fail(e)
+ }
+ if runCtx.Err() != nil {
+ fail(runCtx.Err())
+ }
+ if runCtx.Err() == nil {
+ waitCtx, stopWait := context.WithTimeout(runCtx, 5*time.Second)
+ _, e := proc.Wait(waitCtx)
+ stopWait()
+ 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)
+ } else if e = f.journal.releaseDirectFrames(runCtx); e != nil {
+ fail(e)
+ }
+ }
+ input.Close()
+ stdout.Close()
+ stderr.Close()
+ close(frames)
+ done <- failure
+ close(done)
+ }()
+ return &provider.Capture{Input: ci, Frames: frames, Done: done}, nil
+}
+func (j *Journal) AppendFrame(ctx context.Context, attempt, stream string, seq int64, frame []byte) error {
+ if attempt == "" || stream == "" || seq <= 0 || len(frame) > MaxFrameBytes || !uniqueFrame(frame) {
+ return runnerproto.ErrInvalid
+ }
+ body := redactFrame(frame)
+ if len(body) > MaxFrameBytes {
+ return runnerproto.ErrInvalid
+ }
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ err = func() error {
+ defer tx.Rollback()
+ 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 {
+ return e
+ }
+ if saved != stream || recovered != 0 {
+ return provider.ErrIdentity
+ }
+ var last, size int64
+ var blocked int
+ if e := tx.QueryRowContext(ctx, "SELECT COALESCE(MAX(sequence),0) FROM direct_frames WHERE stream=?", stream).Scan(&last); e != nil {
+ return e
+ }
+ if seq <= last {
+ return runnerproto.ErrInvalid
+ }
+ if e := tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); e != nil {
+ return e
+ }
+ if blocked != 0 || size < 0 || int64(len(body)) > j.maxBytes-size {
+ return ErrJournal
+ }
+ if _, e := tx.ExecContext(ctx, "INSERT INTO direct_frames(stream,sequence,body) VALUES(?,?,?)", stream, seq, body); e != nil {
+ return e
+ }
+ return tx.Commit()
+ }()
+ if err != nil && !errors.Is(err, provider.ErrIdentity) {
+ return j.storageFailure(ctx, err)
+ }
+ return err
+}
+
+// Reject duplicate keys before redaction can collapse them or alter a decoder's
+// interpretation. Number tokens stay exact, including counters above 2^53.
+func uniqueFrame(raw []byte) bool {
+ if len(bytes.TrimSpace(raw)) == 0 || bytes.TrimSpace(raw)[0] != '{' {
+ return false
+ }
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.UseNumber()
+ var value func() bool
+ value = func() bool {
+ v, e := d.Token()
+ if e != nil {
+ return false
+ }
+ delim, ok := v.(json.Delim)
+ if !ok {
+ return true
+ }
+ switch delim {
+ case '{':
+ seen := map[string]bool{}
+ for d.More() {
+ k, e := d.Token()
+ s, ok := k.(string)
+ if e != nil || !ok || seen[s] {
+ return false
+ }
+ seen[s] = true
+ if !value() {
+ return false
+ }
+ }
+ v, e = d.Token()
+ return e == nil && v == json.Delim('}')
+ case '[':
+ for d.More() {
+ if !value() {
+ return false
+ }
+ }
+ v, e = d.Token()
+ return e == nil && v == json.Delim(']')
+ }
+ return false
+ }
+ if !value() {
+ return false
+ }
+ _, e := d.Token()
+ return e == io.EOF
+}
+func redactFrame(raw []byte) []byte { return redactFrameSecrets(raw, nil) }
+func redactFrameSecrets(raw []byte, secrets []string) []byte {
+ var v any
+ d := json.NewDecoder(bytes.NewReader(raw))
+ d.UseNumber()
+ if d.Decode(&v) != nil {
+ return nil
+ }
+ var walk func(any, bool) any
+ walk = func(v any, secret bool) any {
+ switch x := v.(type) {
+ case map[string]any:
+ for k, v := range x {
+ key := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(k))
+ s := strings.HasSuffix(key, "token") || strings.HasSuffix(key, "password") || strings.HasSuffix(key, "secret") || strings.HasSuffix(key, "apikey") || strings.HasSuffix(key, "privatekey") || key == "authorization" || key == "credentials" || key == "credential" || key == "bearer"
+ x[k] = walk(v, secret || s)
+ }
+ case []any:
+ for i, v := range x {
+ x[i] = walk(v, secret)
+ }
+ case string:
+ if secret {
+ return "***"
+ }
+ return redactText(x, secrets)
+ }
+ return v
+ }
+ b, _ := json.Marshal(walk(v, false))
+ return b
+}
diff --git a/internal/runner/capture_test.go b/internal/runner/capture_test.go
new file mode 100644
index 00000000..9c497330
--- /dev/null
+++ b/internal/runner/capture_test.go
@@ -0,0 +1,463 @@
+package runner
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+type directProcess struct {
+ writable io.WriteCloser
+ input bytes.Buffer
+ out io.ReadCloser
+ errout io.ReadCloser
+ stopped atomic.Bool
+ record containment.Record
+}
+type directInput struct{ *bytes.Buffer }
+
+func (directInput) Close() error { return nil }
+func (p *directProcess) ID() string { return p.record.ID }
+func (p *directProcess) Stdin() io.WriteCloser {
+ if p.writable != nil {
+ return p.writable
+ }
+ return directInput{&p.input}
+}
+func (p *directProcess) Stdout() io.ReadCloser { return p.out }
+func (p *directProcess) Stderr() io.ReadCloser { return p.errout }
+func (p *directProcess) Wait(context.Context) (provider.Exit, error) { return provider.Exit{}, nil }
+func (p *directProcess) Contain(context.Context) error {
+ p.stopped.Store(true)
+ p.out.Close()
+ p.errout.Close()
+ return nil
+}
+func (p *directProcess) Record() containment.Record { return p.record }
+func directFixture(t *testing.T, name string) (*Journal, provider.Launch, provider.Session, *directProcess) {
+ t.Helper()
+ j, err := OpenJournal(context.Background(), filepath.Join(t.TempDir(), "private", "journal.db"))
+ mustJournal(t, err)
+ t.Cleanup(func() { j.Close() })
+ version := "0.165.0"
+ if name == "claude" {
+ version = "2.1.312"
+ }
+ l := provider.Launch{AttemptKey: "attempt", Selection: provider.Selection{Provider: name, AccountID: "account", Family: name, Model: "model", ConnectionID: "connection"}, Binding: provider.Binding{ID: "binding", Provider: name, AccountID: "account", Expected: provider.Identity{ProviderVersion: version}}, Policy: provider.Policy{Hash: "policy", ManifestHash: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", Manifest: json.RawMessage(`{}`)}}
+ s := provider.Session{ID: "session", AttemptKey: l.AttemptKey, Provider: name, AccountID: "account", Family: name, Model: "model"}
+ p := &directProcess{record: containment.Record{ID: strings.Repeat("a", 32), AttemptKey: l.AttemptKey, ManifestHash: "namespace-manifest", PolicyHash: l.Policy.Hash}, out: io.NopCloser(strings.NewReader("")), errout: io.NopCloser(strings.NewReader(""))}
+ mustJournal(t, j.recordDirectLaunch(context.Background(), l, p.record))
+ return j, l, s, p
+}
+func directTurn() provider.Turn {
+ return provider.Turn{ID: "turn", AdmissionID: "admission", Prompt: "hello"}
+}
+func directPrompt(name string) []byte {
+ if name == "claude" {
+ return []byte("{\"type\":\"user\",\"session_id\":\"session\",\"message\":{\"role\":\"user\",\"content\":\"hello\"}}\n")
+ }
+ return []byte("{\"id\":1,\"method\":\"turn/start\",\"params\":{\"threadId\":\"session\",\"input\":[{\"type\":\"text\",\"text\":\"hello\"}]}}\n")
+}
+func TestDirectCrashBoundaries(t *testing.T) {
+ for _, name := range []string{"claude", "codex"} {
+ for _, stage := range []string{"intent", "before-stdin", "after-stdin", "before-frame", "after-frame", "before-upload", "server-before-ack"} {
+ t.Run(name+"/"+stage, func(t *testing.T) {
+ j, l, s, p := directFixture(t, name)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ // Keep stdout open until the simulated crash.
+ r, w := io.Pipe()
+ p.out = r
+ defer w.Close()
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ if _, err = cap.Input.Write(directPrompt(name)); err == nil || p.input.Len() != 0 {
+ t.Fatal("prompt bypassed intent")
+ }
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ if stage != "intent" && stage != "before-stdin" {
+ _, err = cap.Input.Write(directPrompt(name))
+ mustJournal(t, err)
+ }
+ if stage == "after-frame" || stage == "before-upload" || stage == "server-before-ack" {
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"type":"result","session_id":"session","subtype":"success","is_error":false}`)))
+ }
+ cancel()
+ <-cap.Done
+ path := j.path
+ mustJournal(t, j.Close())
+ reopened, err := OpenJournal(context.Background(), path)
+ mustJournal(t, err)
+ defer reopened.Close()
+ rows, err := reopened.RecoverDirect(context.Background())
+ mustJournal(t, err)
+ if len(rows) != 1 || rows[0].State != "waiting_for_person" || rows[0].Usage != nil {
+ t.Fatalf("uncertain recovery: %+v", rows)
+ }
+ if reopened.BeginTurn(context.Background(), s, directTurn()) == nil {
+ t.Fatal("restart admitted uncertain prompt again")
+ }
+ })
+ }
+ }
+}
+func TestDirectJournalFailureContains(t *testing.T) {
+ for _, kind := range []string{"torn", "unterminated", "malformed", "duplicate-key", "oversized", "disk-full", "outbox-full", "outbox-crossing", "blocked", "stderr"} {
+ t.Run(kind, func(t *testing.T) {
+ j, l, _, p := directFixture(t, "claude")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ raw := "{\"type\":\"system\",\"input_tokens\":9007199254740993,\"authorization\":\"Bearer secret\"}\n"
+ switch kind {
+ case "torn":
+ raw = `{"type":"system"`
+ case "unterminated":
+ raw = `{"type":"system"}`
+ case "malformed":
+ raw = "nope\n"
+ case "duplicate-key":
+ raw = "{\"type\":1,\"type\":2}\n"
+ case "oversized":
+ raw = "{\"text\":\"" + strings.Repeat("x", 1<<20) + "\"}\n"
+ case "disk-full":
+ 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)
+ raw = "{\"text\":\"" + strings.Repeat("a", 20000) + "\"}\n"
+ case "outbox-full":
+ _, err := j.db.Exec("INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES('full','full','full','{}',?)", MaxJournalBytes)
+ mustJournal(t, err)
+ case "outbox-crossing":
+ j.maxBytes = 256
+ raw = "{\"text\":\"" + strings.Repeat("x", 512) + "\"}\n"
+ case "blocked":
+ r, w := io.Pipe()
+ p.out = r
+ defer w.Close()
+ case "stderr":
+ p.errout = io.NopCloser(strings.NewReader(strings.Repeat("x", 70000)))
+ }
+ if kind != "blocked" {
+ p.out = io.NopCloser(strings.NewReader(raw))
+ }
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ if err != nil {
+ if !p.stopped.Load() {
+ t.Fatal("open failure did not contain")
+ }
+ return
+ }
+ if kind == "blocked" {
+ cancel()
+ }
+ if kind == "stderr" {
+ for range cap.Frames {
+ }
+ if err = <-cap.Done; err != nil {
+ t.Fatal(err)
+ }
+ var n int
+ mustJournal(t, j.db.QueryRow("SELECT length(diagnostics) FROM direct_attempts").Scan(&n))
+ if n > 64<<10 {
+ t.Fatal("unbounded stderr")
+ }
+ return
+ }
+ select {
+ case _, ok := <-cap.Frames:
+ if ok {
+ t.Fatal("uncommitted or invalid frame escaped")
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("capture blocked")
+ }
+ if err = <-cap.Done; err == nil || !p.stopped.Load() {
+ t.Fatalf("not contained: %v", err)
+ }
+ })
+ }
+}
+func TestDirectJournalCommitBeforeDelivery(t *testing.T) {
+ j, l, _, p := directFixture(t, "claude")
+ p.out = io.NopCloser(strings.NewReader("{\"input_tokens\":9007199254740993,\"authorization\":\"Bearer secret\"}\n"))
+ cap, err := NewCaptureFactory(j).Open(context.Background(), p, l)
+ mustJournal(t, err)
+ for f := range cap.Frames {
+ var b []byte
+ mustJournal(t, j.db.QueryRow("SELECT body FROM direct_frames WHERE stream=? AND sequence=?", p.ID(), f.Sequence).Scan(&b))
+ if !bytes.Equal(b, f.Bytes) || strings.Contains(string(b), "secret") || !strings.Contains(string(b), "9007199254740993") {
+ t.Fatalf("frame not durably redacted with exact counters: %s", b)
+ }
+ }
+ mustJournal(t, <-cap.Done)
+}
+
+func TestDirectCrashProcess(t *testing.T) {
+ if path := os.Getenv("EQUIPO_TASK7_CRASH_PATH"); path != "" {
+ ctx := context.Background()
+ j, err := OpenJournal(ctx, path)
+ mustJournal(t, err)
+ l := provider.Launch{AttemptKey: "attempt", Selection: provider.Selection{Provider: "codex", AccountID: "account", Family: "gpt", Model: "model"}, Binding: provider.Binding{ID: "binding", Provider: "codex", AccountID: "account", Expected: provider.Identity{ProviderVersion: "0.165.0"}}, Policy: provider.Policy{Hash: "policy", ManifestHash: "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a", Manifest: json.RawMessage(`{}`)}}
+ s := provider.Session{ID: "session", AttemptKey: "attempt", Provider: "codex", AccountID: "account", Family: "gpt", Model: "model"}
+ r, w := io.Pipe()
+ defer w.Close()
+ input, err := os.OpenFile(path+".stdin", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
+ mustJournal(t, err)
+ p := &directProcess{record: containment.Record{ID: strings.Repeat("a", 32), AttemptKey: "attempt", ManifestHash: "manifest", PolicyHash: "policy"}, out: r, errout: io.NopCloser(strings.NewReader("")), writable: input}
+ mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ stage := os.Getenv("EQUIPO_TASK7_CRASH_STAGE")
+ if stage == "intent" || stage == "before-stdin" {
+ os.Exit(0)
+ }
+ _, err = cap.Input.Write(directPrompt("codex"))
+ mustJournal(t, err)
+ mustJournal(t, input.Sync())
+ if stage == "after-stdin" {
+ os.Exit(0)
+ }
+ raw := []byte(`{"method":"turn/completed","params":{"threadId":"session","turn":{"id":"provider-turn","status":"completed"}}}`)
+ if stage == "before-frame" {
+ tx, err := j.db.BeginTx(ctx, nil)
+ mustJournal(t, err)
+ _, err = tx.Exec("INSERT INTO direct_frames(stream,sequence,body) VALUES(?,1,?)", p.ID(), raw)
+ mustJournal(t, err)
+ os.Exit(0)
+ }
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, raw))
+ if stage == "after-frame" {
+ os.Exit(0)
+ }
+ _, err = j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
+ mustJournal(t, err)
+ template := journalEvent("ignored", 1)
+ template.ActionID = 1
+ pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
+ mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template))
+ if stage == "server-before-ack" {
+ pending, err := j.Pending(ctx, 1)
+ mustJournal(t, err)
+ raw, _ := json.Marshal(pending[0])
+ mustJournal(t, os.WriteFile(path+".server", raw, 0600))
+ }
+ os.Exit(0)
+ }
+ for _, stage := range []string{"intent", "before-stdin", "after-stdin", "before-frame", "after-frame", "before-upload", "server-before-ack"} {
+ t.Run(stage, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "private", "journal.db")
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDirectCrashProcess$")
+ cmd.Env = append(os.Environ(), "EQUIPO_TASK7_CRASH_PATH="+path, "EQUIPO_TASK7_CRASH_STAGE="+stage)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatal(err, string(out))
+ }
+ j, err := OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer j.Close()
+ rows, err := j.RecoverDirect(ctx)
+ mustJournal(t, err)
+ if len(rows) != 1 {
+ t.Fatalf("missing recovery %+v", rows)
+ }
+ complete := stage == "before-upload" || stage == "server-before-ack"
+ if complete {
+ if rows[0].State != "completed_needs_containment" || rows[0].Usage == nil || rows[0].Usage.InputTokens != 28254 {
+ t.Fatalf("durable completion lost: %+v", rows)
+ }
+ } else if rows[0].State != "waiting_for_person" || rows[0].Usage != nil {
+ t.Fatalf("invented completion: %+v", rows)
+ }
+ var frames int
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_frames").Scan(&frames))
+ want := 0
+ if stage == "after-frame" || complete {
+ want = 1
+ }
+ if frames != want {
+ t.Fatal("torn transaction persisted", frames, want)
+ }
+ input, err := os.ReadFile(path + ".stdin")
+ mustJournal(t, err)
+ writes := bytes.Count(input, []byte{'\n'})
+ expected := 1
+ if stage == "intent" || stage == "before-stdin" {
+ expected = 0
+ }
+ if writes != expected {
+ t.Fatal("prompt repeated", writes)
+ }
+ if stage == "server-before-ack" {
+ server, err := os.ReadFile(path + ".server")
+ mustJournal(t, err)
+ pending, err := j.Pending(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 1 {
+ t.Fatal("lost upload")
+ }
+ replay, _ := json.Marshal(pending[0])
+ if !bytes.Equal(server, replay) {
+ t.Fatal("replay changed delivery identity")
+ }
+ }
+ })
+ }
+}
+
+func TestDirectCrashSingleUseInput(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r, w := io.Pipe()
+ defer w.Close()
+ p.out = r
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err = cap.Input.Write(directPrompt("codex"))
+ mustJournal(t, err)
+ if _, err = cap.Input.Write(directPrompt("codex")); err == nil {
+ t.Fatal("same prompt sent twice")
+ }
+ if bytes.Count(p.input.Bytes(), []byte{'\n'}) != 1 {
+ t.Fatal("single-use intent reused")
+ }
+ if j.BeginTurn(ctx, s, provider.Turn{ID: "other", AdmissionID: "other-admission", Prompt: "hello"}) == nil {
+ t.Fatal("active turn replaced")
+ }
+ cancel()
+ <-cap.Done
+}
+func TestDirectJournalFrameSequence(t *testing.T) {
+ j, l, _, p := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.AppendFrame(ctx, l.AttemptKey, p.ID(), 2, []byte(`{"n":2}`)))
+ if j.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"n":1}`)) == nil {
+ t.Fatal("frame order regressed")
+ }
+ if j.AppendFrame(ctx, l.AttemptKey, "other", 3, []byte(`{"n":3}`)) == nil {
+ t.Fatal("stream detached from attempt")
+ }
+}
+
+type shortDirectInput struct{}
+
+func (shortDirectInput) Write(b []byte) (int, error) { return len(b) / 2, nil }
+func (shortDirectInput) Close() error { return nil }
+func TestDirectJournalShortInput(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r, w := io.Pipe()
+ defer w.Close()
+ p.out = r
+ p.writable = shortDirectInput{}
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ if _, err = cap.Input.Write(directPrompt("codex")); err == nil {
+ t.Fatal("short stdin write reported success")
+ }
+ if err = <-cap.Done; err == nil || !p.stopped.Load() {
+ t.Fatal("short stdin write was not contained")
+ }
+ rows, err := j.RecoverDirect(context.Background())
+ mustJournal(t, err)
+ if rows[0].State != "waiting_for_person" {
+ t.Fatal("short write invented outcome")
+ }
+}
+func TestDirectJournalInputProtocol(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r, w := io.Pipe()
+ defer w.Close()
+ p.out = r
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ for _, raw := range []string{"{\"method\":\"command/exec\",\"params\":{}}\n", "{}\n{}\n", "{\"method\":\"turn/start\",\"params\":{\"threadId\":\"session\",\"input\":[]}}\n"} {
+ if _, err = cap.Input.Write([]byte(raw)); err == nil {
+ t.Fatal("invalid input admitted")
+ }
+ }
+ if p.input.Len() != 0 {
+ t.Fatal("invalid input transmitted")
+ }
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ wrong := bytes.ReplaceAll(directPrompt("codex"), []byte("hello"), []byte("different"))
+ if _, err = cap.Input.Write(wrong); err == nil {
+ t.Fatal("prompt differs from admitted intent")
+ }
+ if p.input.Len() != 0 {
+ t.Fatal("unadmitted prompt transmitted")
+ }
+ cancel()
+ <-cap.Done
+}
+
+func TestDirectCrashFullOutbox(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r, w := io.Pipe()
+ defer w.Close()
+ p.out = r
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err = j.db.Exec("INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES('full','full','full','{}',?)", MaxJournalBytes)
+ mustJournal(t, err)
+ if _, err = cap.Input.Write(directPrompt("codex")); err == nil || p.input.Len() != 0 {
+ t.Fatal("full outbox admitted stdin")
+ }
+ cancel()
+ <-cap.Done
+}
+
+func TestDirectInterruptedLiveCapture(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ r, w := io.Pipe()
+ defer w.Close()
+ p.out = r
+ cap, err := NewCaptureFactory(j).Open(ctx, p, l)
+ mustJournal(t, err)
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err = cap.Input.Write(directPrompt("codex"))
+ mustJournal(t, err)
+ _, err = j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')")
+ mustJournal(t, err)
+ cancel()
+ <-cap.Done
+ var state string
+ mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state))
+ if state != "waiting_for_person" {
+ t.Fatal("live cancellation left turn dispatchable", state)
+ }
+ mustJournal(t, j.db.QueryRow("SELECT state FROM journal_answers").Scan(&state))
+ if state != "invalid" {
+ t.Fatal("live cancellation retained pending answers")
+ }
+ late, err := j.ObserveDirect(context.Background(), s, directComplete("turn"))
+ mustJournal(t, err)
+ if late != nil {
+ t.Fatal("late completion erased live cancellation")
+ }
+}
diff --git a/internal/runner/containment/linux.go b/internal/runner/containment/linux.go
index 6e166fff..57f52aa1 100644
--- a/internal/runner/containment/linux.go
+++ b/internal/runner/containment/linux.go
@@ -51,6 +51,15 @@ type process struct {
err error
}
+func (p *process) Record() Record { return p.record }
+func (p *process) Contain(ctx context.Context) error {
+ if err := p.kill(); err != nil {
+ return err
+ }
+ _, err := p.Wait(ctx)
+ return err
+}
+
func (p *process) ID() string { return p.record.ID }
func (p *process) Stdin() io.WriteCloser { return p.stdin }
func (p *process) Stdout() io.ReadCloser { return p.stdout }
@@ -111,6 +120,10 @@ func New(cfg Config) (*Manager, error) {
return &Manager{cfg: cfg, processes: make(map[string]*process)}, nil
}
func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
+ return m.StartRecorded(ctx, l, argv, nil)
+}
+
+func (m *Manager) StartRecorded(ctx context.Context, l provider.Launch, argv []string, record func(context.Context, Record) error) (provider.Process, error) {
if e := ctx.Err(); e != nil {
return nil, e
}
@@ -174,6 +187,18 @@ func (m *Manager) Start(ctx context.Context, l provider.Launch, argv []string) (
return nil, e
}
r := Record{ID: id, AttemptKey: l.AttemptKey, BootID: boot, ManifestHash: manifestHash, PolicyHash: l.Policy.Hash, EgressHash: egressHash}
+ r.ParentPID = os.Getpid()
+ r.ParentTicks, _, e = identity(r.ParentPID)
+ if e != nil {
+ mounts.close()
+ return nil, e
+ }
+ if record != nil {
+ if e = record(ctx, r); e != nil {
+ mounts.close()
+ return nil, e
+ }
+ }
if e = m.persist(r); e != nil {
mounts.close()
return nil, e
diff --git a/internal/runner/containment/recovery.go b/internal/runner/containment/recovery.go
index 80aa69db..edccc196 100644
--- a/internal/runner/containment/recovery.go
+++ b/internal/runner/containment/recovery.go
@@ -19,6 +19,8 @@ import (
type Record struct {
ID, AttemptKey, BootID, NamespaceID, ManifestHash string
EgressHash, PolicyHash string
+ ParentPID int
+ ParentTicks uint64
HostPID int
StartTicks uint64
}
@@ -158,7 +160,7 @@ func durableJSON(root, name string, v any) error {
func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
proof := Proof{Record: r, Exit: provider.Exit{Code: -1}}
_, idErr := hex.DecodeString(r.ID)
- if len(r.ID) != 32 || idErr != nil || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" {
+ if len(r.ID) != 32 || idErr != nil || strings.ContainsAny(r.ID, "/.\\") || r.AttemptKey == "" || r.BootID == "" || r.ManifestHash == "" || r.PolicyHash == "" {
return proof, errIdentity
}
boot, e := bootID()
@@ -170,6 +172,47 @@ func (m *Manager) Recover(ctx context.Context, r Record) (Proof, error) {
proof.Exit.ObservedAt = time.Now().UTC()
return m.finishRecovery(proof)
}
+ if r.HostPID == 0 && r.StartTicks == 0 && r.NamespaceID == "" {
+ stored, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".json"))
+ var durable Record
+ if err != nil || json.Unmarshal(stored, &durable) != nil || durable != r || r.PolicyHash == "" {
+ return proof, errIdentity
+ }
+ if b, err := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, r.ID+".exit.json")); err == nil {
+ var prior Proof
+ if json.Unmarshal(b, &prior) != nil || !prior.Verified || prior.Record != r || prior.Exit.ObservedAt.IsZero() {
+ return proof, errIdentity
+ }
+ return m.finishRecovery(prior)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return proof, err
+ }
+ // Release is written only after the init identity is durable. An
+ // intent-only namespace cannot have launched the harness. Old records
+ // lack parent identity; their release pipe is already closed at restart.
+ if r.ParentPID > 0 {
+ fd, err := unix.PidfdOpen(r.ParentPID, 0)
+ if err == nil {
+ defer unix.Close(fd)
+ ticks, _, identityErr := identity(r.ParentPID)
+ if identityErr == nil && ticks == r.ParentTicks {
+ if err = waitPID(ctx, fd); err != nil {
+ return proof, err
+ }
+ } else if identityErr != nil && !errors.Is(identityErr, os.ErrNotExist) {
+ return proof, errIdentity
+ }
+ } else if err != unix.ESRCH {
+ return proof, err
+ }
+ }
+ proof.Verified = true
+ proof.Exit.ObservedAt = time.Now().UTC()
+ if err := durableJSON(m.cfg.ScratchRoot, r.ID+".exit.json", proof); err != nil {
+ return Proof{Record: r}, err
+ }
+ return m.finishRecovery(proof)
+ }
nsID, nsErr := strconv.ParseUint(strings.TrimSuffix(strings.TrimPrefix(r.NamespaceID, "pid:["), "]"), 10, 64)
if r.HostPID <= 0 || r.StartTicks == 0 || nsErr != nil || nsID == 0 || r.NamespaceID != fmt.Sprintf("pid:[%d]", nsID) {
return proof, errIdentity
@@ -247,3 +290,49 @@ func removeScratch(dir string) error {
}
return nil
}
+
+// Records returns only durable namespace identities, never a host process scan.
+func (m *Manager) Records(ctx context.Context) ([]Record, error) {
+ entries, err := os.ReadDir(m.cfg.ScratchRoot)
+ if err != nil {
+ return nil, err
+ }
+ var records []Record
+ for _, entry := range entries {
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
+ name := entry.Name()
+ if len(name) != 37 || !strings.HasSuffix(name, ".json") {
+ continue
+ }
+ b, e := os.ReadFile(filepath.Join(m.cfg.ScratchRoot, name))
+ if e != nil {
+ return nil, e
+ }
+ var r Record
+ if json.Unmarshal(b, &r) != nil || r.ID+".json" != name {
+ return nil, errIdentity
+ }
+ records = append(records, r)
+ }
+ return records, nil
+}
+
+// RecoverUnstarted covers the crash between the runner's journal intent and
+// the namespace record. Start cannot fork until that record is durable.
+func (m *Manager) RecoverUnstarted(ctx context.Context, r Record) (Proof, error) {
+ if r.HostPID != 0 || r.StartTicks != 0 || r.NamespaceID != "" {
+ return Proof{Record: r}, errIdentity
+ }
+ if _, err := os.Lstat(filepath.Join(m.cfg.ScratchRoot, r.ID+".json")); !errors.Is(err, os.ErrNotExist) {
+ return Proof{Record: r}, errIdentity
+ }
+ if len(r.ID) != 32 || strings.ContainsAny(r.ID, "/.\\") {
+ return Proof{Record: r}, errIdentity
+ }
+ if err := m.persist(r); err != nil {
+ return Proof{Record: r}, err
+ }
+ return m.Recover(ctx, r)
+}
diff --git a/internal/runner/containment/recovery_test.go b/internal/runner/containment/recovery_test.go
index 4014b08f..49e494a0 100644
--- a/internal/runner/containment/recovery_test.go
+++ b/internal/runner/containment/recovery_test.go
@@ -520,3 +520,67 @@ func TestNamespaceRecoveryMalformedRecord(t *testing.T) {
})
}
}
+
+func TestDirectInterruptedIntentOnly(t *testing.T) {
+ root := t.TempDir()
+ boot, e := bootID()
+ if e != nil {
+ t.Fatal(e)
+ }
+ m := &Manager{cfg: Config{ScratchRoot: root}, processes: map[string]*process{}}
+ r := Record{ID: "abcdefabcdefabcdefabcdefabcdefab", AttemptKey: "intent", BootID: boot, ManifestHash: "manifest", PolicyHash: "policy"}
+ if e = m.persist(r); e != nil {
+ t.Fatal(e)
+ }
+ dir := filepath.Join(root, "attempt-"+r.ID)
+ if e = os.Mkdir(dir, 0700); e != nil {
+ t.Fatal(e)
+ }
+ proof, e := m.Recover(context.Background(), r)
+ if e != nil || !proof.Verified || proof.Exit.Code != -1 {
+ t.Fatalf("intent-only restart blocked: %+v %v", proof, e)
+ }
+ if _, e = os.Stat(dir); !os.IsNotExist(e) {
+ t.Fatal("intent scratch retained", e)
+ }
+}
+
+func TestDirectInterruptedParentLifecycle(t *testing.T) {
+ root := t.TempDir()
+ boot, e := bootID()
+ if e != nil {
+ t.Fatal(e)
+ }
+ parent := exec.Command("/bin/sleep", "60")
+ if e = parent.Start(); e != nil {
+ t.Fatal(e)
+ }
+ defer parent.Process.Kill()
+ defer parent.Wait()
+ ticks, _, e := identity(parent.Process.Pid)
+ if e != nil {
+ t.Fatal(e)
+ }
+ m := &Manager{cfg: Config{ScratchRoot: root}, processes: map[string]*process{}}
+ r := Record{ID: "abcdefabcdefabcdefabcdefabcdefab", AttemptKey: "intent", BootID: boot, ManifestHash: "manifest", PolicyHash: "policy", ParentPID: parent.Process.Pid, ParentTicks: ticks}
+ if e = m.persist(r); e != nil {
+ t.Fatal(e)
+ }
+ dir := filepath.Join(root, "attempt-"+r.ID)
+ if e = os.Mkdir(dir, 0700); e != nil {
+ t.Fatal(e)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
+ defer cancel()
+ if proof, e := m.Recover(ctx, r); e == nil || proof.Verified {
+ t.Fatal("cleanup preceded parent death")
+ }
+ if _, e = os.Stat(dir); e != nil {
+ t.Fatal("live lifecycle scratch deleted")
+ }
+ parent.Process.Kill()
+ parent.Wait()
+ if proof, e := m.Recover(context.Background(), r); e != nil || !proof.Verified {
+ t.Fatalf("dead parent blocks recovery: %+v %v", proof, e)
+ }
+}
diff --git a/internal/runner/direct_events.go b/internal/runner/direct_events.go
new file mode 100644
index 00000000..2f2bc66b
--- /dev/null
+++ b/internal/runner/direct_events.go
@@ -0,0 +1,211 @@
+package runner
+
+import (
+ "context"
+ "database/sql"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func directEventKey(s provider.Session, e provider.Event) string {
+ if e.Sequence > 0 {
+ return runnerproto.EventHash([]any{s.AttemptKey, e.Sequence, e.Kind})
+ }
+ return runnerproto.EventHash([]any{s.AttemptKey, e})
+}
+func (j *Journal) ObserveDirect(ctx context.Context, s provider.Session, e provider.Event) (*team.Usage, error) {
+ return j.appendDirect(ctx, s, e, nil)
+}
+func (p *EventPump) AppendDirect(ctx context.Context, s provider.Session, e provider.Event, template Event) error {
+ if p.Journal == nil || p.Contain == nil {
+ return runnerproto.ErrInvalid
+ }
+ if e.Kind == "turn.failed" && len(e.Payload) == 0 {
+ e.Payload = json.RawMessage(`{}`)
+ }
+ if !uniqueFrame(e.Payload) {
+ return p.storageFailure(ctx, 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 nil
+}
+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(`{}`)
+ }
+ if e.SessionID != s.ID || e.Kind == "" || len(e.Payload) > MaxFrameBytes || !uniqueFrame(e.Payload) {
+ return nil, runnerproto.ErrInvalid
+ }
+ e.Payload = redactFrame(e.Payload)
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, j.storageFailure(ctx, err)
+ }
+ var usage *team.Usage
+ err = func() error {
+ defer tx.Rollback()
+ l, err := directLaunchTx(ctx, tx, s)
+ if err != nil {
+ return err
+ }
+ key := directEventKey(s, e)
+ body, _ := json.Marshal(e)
+ body = redactFrame(body)
+ var old, receipt []byte
+ var projected int
+ err = tx.QueryRowContext(ctx, "SELECT body,usage,projected FROM direct_events WHERE event_key=?", key).Scan(&old, &receipt, &projected)
+ if err == nil {
+ if string(old) != string(body) {
+ return runnerproto.ErrInvalid
+ }
+ if len(receipt) > 0 && json.Unmarshal(receipt, &usage) != nil {
+ return ErrJournal
+ }
+ if template == nil || projected == 1 {
+ return nil
+ }
+ } else {
+ if !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ 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 {
+ return provider.ErrIdentity
+ }
+ profile := directProfile(l)
+ stream, _ := usageKeys(profile, e)
+ acc := NewUsageAccumulator(profile)
+ var saved []byte
+ err = tx.QueryRowContext(ctx, "SELECT body FROM direct_usage WHERE stream=?", stream).Scan(&saved)
+ if err == nil {
+ if json.Unmarshal(saved, &acc.direct) != nil {
+ return ErrJournal
+ }
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ return err
+ }
+ if state != "waiting_for_person" {
+ usage = acc.Observe(e)
+ }
+ checkpoint, _ := json.Marshal(acc.direct)
+ if _, err = tx.ExecContext(ctx, "INSERT INTO direct_usage VALUES(?,?) ON CONFLICT(stream) DO UPDATE SET body=excluded.body", stream, checkpoint); err != nil {
+ return err
+ }
+ receipt, _ = json.Marshal(usage)
+ if e.Kind == "turn.completed" || e.Kind == "turn.failed" {
+ next := "waiting_for_person"
+ if e.Kind == "turn.completed" && state != "waiting_for_person" {
+ 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 {
+ return err
+ }
+ }
+ }
+ var size int64
+ var blocked int
+ if err = tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
+ return err
+ }
+ if blocked != 0 || int64(len(body)) > j.maxBytes-size {
+ return ErrJournal
+ }
+ if _, err = tx.ExecContext(ctx, "INSERT INTO direct_events(event_key,attempt,body,usage) VALUES(?,?,?,?)", key, s.AttemptKey, body, receipt); err != nil {
+ return err
+ }
+ }
+ if template != nil {
+ events, err := projectDirect(s, e, usage, *template, key)
+ if err != nil {
+ return err
+ }
+ for _, event := range events {
+ raw, _ := json.Marshal(event)
+ if err = j.appendTx(ctx, tx, event, event.ContentHash(), raw); err != nil {
+ return err
+ }
+ }
+ if _, err = tx.ExecContext(ctx, "UPDATE direct_events SET projected=1 WHERE event_key=?", key); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+ }()
+ if err != nil {
+ if errors.Is(err, provider.ErrIdentity) || errors.Is(err, runnerproto.ErrInvalid) {
+ return nil, err
+ }
+ return nil, j.storageFailure(ctx, err)
+ }
+ return usage, nil
+}
+func projectDirect(s provider.Session, e provider.Event, u *team.Usage, template Event, key string) ([]Event, error) {
+ envelope := struct {
+ Provider string `json:"provider"`
+ Event provider.Event `json:"event"`
+ Usage *team.Usage `json:"usage"`
+ }{s.Provider, e, u}
+ body, err := json.Marshal(envelope)
+ if err != nil {
+ return nil, err
+ }
+ template.ServerID = "direct"
+ template.AgentID = s.AttemptKey
+ template.SessionID = s.ID
+ template.TurnID = e.TurnID
+ template.RequestID = e.RequestID
+ template.Sequence = nil
+ template.Epoch = "direct-v2"
+ template.Kind = e.Kind
+ template.ID = key
+ template.RequestID = key
+ var result []Event
+ if len(body) > runnerproto.MaxEventBytes {
+ // Preserve the complete normalized envelope in ordered chunks. The final
+ // lifecycle/usage event remains small and references the durable chunks.
+ const chunkBytes = 8 << 10
+ total := (len(body) + chunkBytes - 1) / chunkBytes
+ for offset, index := 0, 0; offset < len(body); offset, index = offset+chunkBytes, index+1 {
+ end := offset + chunkBytes
+ if end > len(body) {
+ end = len(body)
+ }
+ part := template
+ part.Kind = "direct_chunk"
+ part.ID = fmt.Sprintf("%s-%d", key, index)
+ part.RequestID = part.ID
+ part.Payload, _ = json.Marshal(struct {
+ Key string `json:"key"`
+ Index, Total int
+ Data string `json:"base64"`
+ }{key, index, total, base64.StdEncoding.EncodeToString(body[offset:end])})
+ if err = part.Validate(); err != nil {
+ return nil, err
+ }
+ result = append(result, part)
+ }
+ template.Payload, _ = json.Marshal(struct {
+ Key string `json:"chunks"`
+ Count int `json:"count"`
+ Kind string `json:"kind"`
+ Usage *team.Usage `json:"usage"`
+ }{key, total, e.Kind, u})
+ } else {
+ template.Payload = body
+ }
+ if err = template.Validate(); err != nil {
+ return nil, err
+ }
+ return append(result, template), nil
+}
diff --git a/internal/runner/direct_recovery.go b/internal/runner/direct_recovery.go
new file mode 100644
index 00000000..6ba48999
--- /dev/null
+++ b/internal/runner/direct_recovery.go
@@ -0,0 +1,336 @@
+package runner
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+var errDirectUncertain = errors.New("runner.direct_uncertain")
+
+const directSchema = `
+CREATE TABLE IF NOT EXISTS direct_attempts (attempt TEXT PRIMARY KEY, stream TEXT UNIQUE NOT NULL, launch BLOB NOT NULL, record BLOB NOT NULL, session TEXT NOT NULL DEFAULT '', recovered INTEGER NOT NULL DEFAULT 0, contained INTEGER NOT NULL DEFAULT 0, opened INTEGER NOT NULL DEFAULT 0, diagnostics BLOB NOT NULL DEFAULT '');
+CREATE TABLE IF NOT EXISTS direct_turns (turn_key TEXT PRIMARY KEY, attempt TEXT NOT NULL, session TEXT NOT NULL, turn TEXT NOT NULL, admission TEXT UNIQUE NOT NULL, prompt_hash TEXT NOT NULL, state TEXT NOT NULL, usage BLOB, UNIQUE(attempt,turn));
+CREATE TABLE IF NOT EXISTS direct_frames (stream TEXT NOT NULL, sequence INTEGER NOT NULL, body BLOB NOT NULL, pending INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(stream,sequence));
+CREATE TABLE IF NOT EXISTS direct_events (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, event_key TEXT UNIQUE NOT NULL, attempt TEXT NOT NULL, body BLOB NOT NULL, usage BLOB, projected INTEGER NOT NULL DEFAULT 0);
+CREATE TABLE IF NOT EXISTS direct_usage (stream TEXT PRIMARY KEY, body BLOB NOT NULL);
+PRAGMA user_version=2;`
+
+type Recovery struct {
+ AttemptKey, SessionID, TurnID, State string
+ Usage *team.Usage
+}
+type directHost struct {
+ journal *Journal
+ manager *containment.Manager
+}
+
+func NewDirectHost(j *Journal, m *containment.Manager) provider.ProcessHost { return &directHost{j, m} }
+func (h *directHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) {
+ if h.journal == nil || h.manager == nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ if err := h.journal.AdmissionAllowed(ctx); err != nil {
+ return nil, err
+ }
+ return h.manager.StartRecorded(ctx, l, args, func(ctx context.Context, r containment.Record) error { return h.journal.recordDirectLaunch(ctx, l, r) })
+}
+func (j *Journal) recordDirectLaunch(ctx context.Context, l provider.Launch, r containment.Record) error {
+ if l.AttemptKey == "" || r.AttemptKey != l.AttemptKey || r.ID == "" || r.ManifestHash == "" || r.PolicyHash == "" || r.PolicyHash != l.Policy.Hash || l.Policy.ManifestHash == "" || !json.Valid(l.Policy.Manifest) {
+ return runnerproto.ErrInvalid
+ }
+ b, err := json.Marshal(l)
+ if err != nil {
+ return err
+ }
+ record, _ := json.Marshal(r)
+ // The manifest is nonsecret policy evidence, never a provider credential.
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ err = func() error {
+ defer tx.Rollback()
+ var oldLaunch, oldRecord []byte
+ var recovered int
+ e := tx.QueryRowContext(ctx, "SELECT launch,record,recovered FROM direct_attempts WHERE attempt=?", l.AttemptKey).Scan(&oldLaunch, &oldRecord, &recovered)
+ if e == nil {
+ var old containment.Record
+ if json.Unmarshal(oldRecord, &old) != nil || string(oldLaunch) != string(b) || old.ID != r.ID || old.ManifestHash != r.ManifestHash || old.PolicyHash != r.PolicyHash || old.BootID != r.BootID || old.ParentPID != r.ParentPID || old.ParentTicks != r.ParentTicks || recovered != 0 {
+ return provider.ErrIdentity
+ }
+ if old.HostPID != 0 && old != r {
+ return provider.ErrIdentity
+ }
+ if _, e = tx.ExecContext(ctx, "UPDATE direct_attempts SET record=? WHERE attempt=?", record, l.AttemptKey); e != nil {
+ return e
+ }
+ return tx.Commit()
+ }
+ if !errors.Is(e, sql.ErrNoRows) {
+ return e
+ }
+ if _, e = tx.ExecContext(ctx, "INSERT INTO direct_attempts(attempt,stream,launch,record) VALUES(?,?,?,?)", l.AttemptKey, r.ID, b, record); e != nil {
+ return e
+ }
+ return tx.Commit()
+ }()
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ return nil
+}
+func directLaunchTx(ctx context.Context, tx *sql.Tx, s provider.Session) (provider.Launch, error) {
+ var b []byte
+ 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 {
+ return l, err
+ }
+ if json.Unmarshal(b, &l) != nil || s.Validate(l) != nil || (saved != "" && saved != s.ID) {
+ return l, provider.ErrIdentity
+ }
+ if saved == "" {
+ var prior []byte
+ err := tx.QueryRowContext(ctx, "SELECT launch FROM direct_attempts WHERE session=? AND attempt!=? ORDER BY rowid DESC LIMIT 1", s.ID, s.AttemptKey).Scan(&prior)
+ if l.ResumeSessionID != "" {
+ var old provider.Launch
+ if err != nil || json.Unmarshal(prior, &old) != nil || old.Selection != l.Selection || old.Binding != l.Binding || old.Policy.Hash != l.Policy.Hash {
+ return l, provider.ErrIdentity
+ }
+ var finished int
+ if err = tx.QueryRowContext(ctx, "SELECT count(*) FROM direct_turns t JOIN direct_attempts a ON a.attempt=t.attempt WHERE t.session=? AND t.state='completed' AND a.contained=1", s.ID).Scan(&finished); err != nil {
+ return l, err
+ }
+ if finished == 0 {
+ return l, errDirectUncertain
+ }
+ var incomplete int
+ if err = tx.QueryRowContext(ctx, "SELECT count(*) FROM direct_turns WHERE session=? AND state!='completed'", s.ID).Scan(&incomplete); err != nil {
+ return l, err
+ }
+ if incomplete != 0 {
+ return l, errDirectUncertain
+ }
+ } else if err == nil {
+ return l, provider.ErrIdentity
+ } else if !errors.Is(err, sql.ErrNoRows) {
+ return l, err
+ }
+ }
+ if _, err := tx.ExecContext(ctx, "UPDATE direct_attempts SET session=? WHERE attempt=?", s.ID, s.AttemptKey); err != nil {
+ return l, err
+ }
+ return l, nil
+}
+func directProfile(l provider.Launch) UsageProfile {
+ return UsageProfile{Version: 2, Provider: l.Selection.Provider, ProviderVersion: l.Binding.Expected.ProviderVersion, Subscription: true}
+}
+func (j *Journal) BeginTurn(ctx context.Context, s provider.Session, t provider.Turn) error {
+ if t.ID == "" || t.AdmissionID == "" || t.Prompt == "" {
+ return runnerproto.ErrInvalid
+ }
+ if err := j.AdmissionAllowed(ctx); err != nil {
+ return err
+ }
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ err = func() error {
+ defer tx.Rollback()
+ l, e := directLaunchTx(ctx, tx, s)
+ if e != nil {
+ return e
+ }
+ var recovered, active int
+ if e = tx.QueryRowContext(ctx, "SELECT recovered FROM direct_attempts WHERE attempt=?", s.AttemptKey).Scan(&recovered); e != nil {
+ return e
+ }
+ if e = tx.QueryRowContext(ctx, "SELECT count(*) FROM direct_turns WHERE session=? AND state!='completed'", s.ID).Scan(&active); e != nil {
+ return e
+ }
+ if recovered != 0 || active != 0 {
+ return errDirectUncertain
+ }
+ _, 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 {
+ return errDirectUncertain
+ }
+ return tx.Commit()
+ }()
+ if err != nil && !errors.Is(err, errDirectUncertain) && !errors.Is(err, provider.ErrIdentity) {
+ return j.storageFailure(ctx, err)
+ }
+ return err
+}
+func (j *Journal) RecoverDirect(ctx context.Context) ([]Recovery, error) {
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return nil, j.storageFailure(ctx, err)
+ }
+ defer tx.Rollback()
+ if _, err = tx.ExecContext(ctx, "UPDATE direct_attempts SET recovered=1; UPDATE direct_turns SET state='waiting_for_person',usage=NULL WHERE state!='completed'; UPDATE journal_answers SET state='invalid' WHERE state='pending'"); err != nil {
+ return nil, err
+ }
+ rows, err := tx.QueryContext(ctx, `SELECT a.attempt,a.session,COALESCE(t.turn,''),CASE WHEN t.state='completed' THEN CASE WHEN a.contained=1 THEN 'completed' ELSE 'completed_needs_containment' END WHEN t.turn IS NULL THEN CASE WHEN a.contained=1 THEN 'never_started' ELSE 'never_started_needs_containment' END ELSE 'waiting_for_person' END,t.usage FROM direct_attempts a LEFT JOIN direct_turns t ON t.attempt=a.attempt ORDER BY a.rowid,t.rowid`)
+ if err != nil {
+ return nil, err
+ }
+ var result []Recovery
+ for rows.Next() {
+ var r Recovery
+ var raw []byte
+ if err = rows.Scan(&r.AttemptKey, &r.SessionID, &r.TurnID, &r.State, &raw); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ if len(raw) > 0 && json.Unmarshal(raw, &r.Usage) != nil {
+ rows.Close()
+ return nil, ErrJournal
+ }
+ result = append(result, r)
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return nil, err
+ }
+ if err = tx.Commit(); err != nil {
+ return nil, j.storageFailure(ctx, err)
+ }
+ return result, nil
+}
+
+// ReconcileDirect proves exit before cleanup or dependent work. It never starts
+// a process, resends input, or consults provider history for missing completion.
+func (j *Journal) ReconcileDirect(ctx context.Context, m *containment.Manager) ([]Recovery, error) {
+ if m == nil {
+ return nil, runnerproto.ErrInvalid
+ }
+ if _, err := j.RecoverDirect(ctx); err != nil {
+ return nil, err
+ }
+ records, err := m.Records(ctx)
+ if err != nil {
+ return nil, err
+ }
+ seen := map[string]bool{}
+ for _, r := range records {
+ seen[r.ID] = true
+ if err = j.validateDirectRecord(ctx, r); err != nil {
+ return nil, err
+ }
+ proof, e := m.Recover(ctx, r)
+ if e != nil || !proof.Verified {
+ return nil, errors.Join(provider.ErrContainment, e)
+ }
+ if _, e = j.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1 WHERE attempt=? AND stream=?", r.AttemptKey, r.ID); e != nil {
+ return nil, j.storageFailure(ctx, e)
+ }
+ }
+ rows, err := j.db.QueryContext(ctx, "SELECT record FROM direct_attempts WHERE contained=0")
+ if err != nil {
+ return nil, err
+ }
+ var missing []containment.Record
+ for rows.Next() {
+ var raw []byte
+ var r containment.Record
+ if rows.Scan(&raw) != nil || json.Unmarshal(raw, &r) != nil {
+ rows.Close()
+ return nil, ErrJournal
+ }
+ if !seen[r.ID] {
+ missing = append(missing, r)
+ }
+ }
+ err = rows.Err()
+ rows.Close()
+ if err != nil {
+ return nil, err
+ }
+ for _, r := range missing {
+ if err = j.validateDirectRecord(ctx, r); err != nil {
+ return nil, err
+ }
+ proof, e := m.RecoverUnstarted(ctx, r)
+ if e != nil || !proof.Verified {
+ return nil, errors.Join(provider.ErrContainment, e)
+ }
+ if _, e = j.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", r.AttemptKey); e != nil {
+ return nil, e
+ }
+ }
+ if err = j.releaseDirectFrames(ctx); err != nil {
+ return nil, err
+ }
+ return j.RecoverDirect(ctx)
+}
+func (j *Journal) validateDirectRecord(ctx context.Context, r containment.Record) error {
+ var raw, launch []byte
+ if err := j.db.QueryRowContext(ctx, "SELECT record,launch FROM direct_attempts WHERE attempt=? AND stream=?", r.AttemptKey, r.ID).Scan(&raw, &launch); err != nil {
+ return provider.ErrIdentity
+ }
+ var saved containment.Record
+ var l provider.Launch
+ if json.Unmarshal(raw, &saved) != nil || json.Unmarshal(launch, &l) != nil || !directManifestIntact(l) || saved.ID != r.ID || saved.AttemptKey != r.AttemptKey || saved.ManifestHash != r.ManifestHash || saved.PolicyHash != r.PolicyHash || r.PolicyHash == "" || saved.PolicyHash != l.Policy.Hash || saved.EgressHash != r.EgressHash || saved.BootID != r.BootID || saved.ParentPID != r.ParentPID || saved.ParentTicks != r.ParentTicks || (saved.HostPID != 0 && saved != r) {
+ return provider.ErrIdentity
+ }
+ return nil
+}
+
+func (j *Journal) BindSession(ctx context.Context, s provider.Session) error {
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ defer tx.Rollback()
+ if _, err = directLaunchTx(ctx, tx, s); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+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(
+ 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))`)
+ if err != nil {
+ return j.storageFailure(ctx, err)
+ }
+ return nil
+}
+
+func directManifestIntact(l provider.Launch) bool {
+ sum := sha256.Sum256(l.Policy.Manifest)
+ return hex.EncodeToString(sum[:]) == l.Policy.ManifestHash
+}
+
+func (j *Journal) interruptDirect(ctx context.Context, attempt string, contained bool) error {
+ tx, err := j.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if _, err = tx.ExecContext(ctx, "UPDATE direct_attempts SET recovered=1,contained=MAX(contained,?) WHERE attempt=?", contained, attempt); err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, "UPDATE direct_turns SET state='waiting_for_person',usage=NULL WHERE attempt=? AND state!='completed'", attempt); err != nil {
+ return err
+ }
+ if _, err = tx.ExecContext(ctx, "UPDATE journal_answers SET state='invalid' WHERE state='pending'"); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
diff --git a/internal/runner/direct_recovery_test.go b/internal/runner/direct_recovery_test.go
new file mode 100644
index 00000000..293f77a7
--- /dev/null
+++ b/internal/runner/direct_recovery_test.go
@@ -0,0 +1,538 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/containment"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+func codexUsage(turn string, input, output int64) provider.Event {
+ return provider.Event{SessionID: "session", TurnID: turn, Kind: "usage", Payload: json.RawMessage(fmt.Sprintf(`{"params":{"tokenUsage":{"total":{"inputTokens":%d,"outputTokens":%d},"last":{"inputTokens":14200,"outputTokens":46}}}}`, input, output))}
+}
+func directComplete(turn string) provider.Event {
+ return provider.Event{SessionID: "session", TurnID: turn, Kind: "turn.completed", Payload: json.RawMessage(`{"params":{"turn":{"status":"completed"}}}`)}
+}
+func TestDirectUsageDeltas(t *testing.T) {
+ ctx := context.Background()
+ j, _, s, _ := directFixture(t, "codex")
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ for _, v := range []provider.Event{codexUsage("turn", 14054, 96), codexUsage("turn", 28254, 142)} {
+ _, err := j.ObserveDirect(ctx, s, v)
+ mustJournal(t, err)
+ }
+ u, err := j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ if u == nil || u.InputTokens != 28254 || u.OutputTokens != 142 || u.Calls != 1 {
+ t.Fatalf("cumulative totals settled incorrectly: %+v", u)
+ }
+ again, err := j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ if again == nil || *again != *u {
+ t.Fatal("duplicate changed charge")
+ }
+ path := j.path
+ mustJournal(t, j.Close())
+ j, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer j.Close()
+ // 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))
+ _, err = j.ObserveDirect(ctx, s, codexUsage("next", 30000, 150))
+ mustJournal(t, err)
+ u, err = j.ObserveDirect(ctx, s, directComplete("next"))
+ mustJournal(t, err)
+ if u == nil || u.InputTokens != 1746 || u.OutputTokens != 8 {
+ t.Fatalf("baseline reset on reopen: %+v", u)
+ }
+ for _, kind := range []string{"reset", "compaction", "missing", "overflow"} {
+ t.Run(kind, func(t *testing.T) {
+ a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "codex", ProviderVersion: "0.165.0", Subscription: true})
+ a.Observe(codexUsage("one", 100, 10))
+ a.Observe(directComplete("one"))
+ e := codexUsage("two", 90, 9)
+ if kind == "missing" {
+ e.Payload = json.RawMessage(`{"params":{"tokenUsage":{"total":{"inputTokens":101}}}}`)
+ }
+ if kind == "overflow" {
+ e.Payload = json.RawMessage(`{"params":{"tokenUsage":{"total":{"inputTokens":9223372036854775808,"outputTokens":12}}}}`)
+ }
+ a.Observe(e)
+ if a.Observe(directComplete("two")) != nil {
+ t.Fatal("uncertain counters became known")
+ }
+ a.Observe(codexUsage("three", 200, 20))
+ if a.Observe(directComplete("three")) != nil {
+ t.Fatal("lost baseline regained authority")
+ }
+ })
+ }
+ a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "claude", ProviderVersion: "2.1.312", Subscription: true})
+ for i, cost := range []float64{.1, .15} {
+ e := provider.Event{SessionID: "session", TurnID: fmt.Sprint(i), Kind: "turn.completed", Payload: json.RawMessage(fmt.Sprintf(`{"usage":{"input_tokens":2,"cache_read_input_tokens":3566,"cache_creation_input_tokens":378,"output_tokens":3},"total_cost_usd":%g,"modelUsage":{"model":{"inputTokens":999999}}}`, cost))}
+ u := a.Observe(e)
+ if u == nil || u.InputTokens != 3946 || u.OutputTokens != 3 {
+ t.Fatalf("Claude per-turn usage: %+v", u)
+ }
+ a.Observe(e)
+ }
+ if a.EstimatedCostUSD() != .15 {
+ t.Fatal("summed cumulative cost", a.EstimatedCostUSD())
+ }
+}
+func TestDirectCompletionReplay(t *testing.T) {
+ j, _, s, _ := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
+ mustJournal(t, err)
+ pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
+ template := journalEvent("ignored", 1)
+ template.ActionID = 1
+ mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template))
+ rows, err := j.RecoverDirect(ctx)
+ mustJournal(t, err)
+ if len(rows) != 1 || rows[0].State != "completed_needs_containment" || rows[0].Usage == nil || rows[0].Usage.InputTokens != 28254 {
+ t.Fatalf("completion replay lost accounting: %+v", rows)
+ }
+ pending, err := j.Pending(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 1 {
+ t.Fatal("projection not atomic", len(pending))
+ }
+ mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template))
+ pending, err = j.Pending(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 1 {
+ t.Fatal("duplicate outbox")
+ }
+ mustJournal(t, j.Ack(ctx, pending[0].ID))
+ pending, err = j.Pending(ctx, 10)
+ mustJournal(t, err)
+ if len(pending) != 0 {
+ t.Fatal("ack not durable")
+ }
+}
+func TestDirectInterruptedWaitsForPerson(t *testing.T) {
+ j, _, s, _ := directFixture(t, "claude")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err := j.db.Exec("INSERT INTO journal_answers VALUES('answer','hash','pending')")
+ mustJournal(t, err)
+ rows, err := j.RecoverDirect(ctx)
+ mustJournal(t, err)
+ if len(rows) != 1 || rows[0].Usage != nil || rows[0].State != "waiting_for_person" {
+ t.Fatalf("unknown charge erased: %+v", rows)
+ }
+ var state string
+ mustJournal(t, j.db.QueryRow("SELECT state FROM journal_answers").Scan(&state))
+ if state != "invalid" {
+ t.Fatal("pending answer remained valid")
+ }
+ late, err := j.ObserveDirect(ctx, s, provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)})
+ if late != nil {
+ t.Fatal("late completion returned known usage after interruption")
+ }
+ mustJournal(t, err)
+ rows, err = j.RecoverDirect(ctx)
+ mustJournal(t, err)
+ if rows[0].State != "waiting_for_person" || rows[0].Usage != nil {
+ t.Fatal("late completion erased interruption")
+ }
+}
+func TestDirectJournalUpgrade(t *testing.T) {
+ j, _, _, _ := directFixture(t, "claude")
+ ctx := context.Background()
+ mustJournal(t, j.Append(ctx, journalEvent("legacy", 1)))
+ _, err := j.db.Exec("DROP TABLE direct_attempts; DROP TABLE direct_turns; DROP TABLE direct_frames; DROP TABLE direct_events; DROP TABLE direct_usage; PRAGMA user_version=1")
+ mustJournal(t, err)
+ path := j.path
+ mustJournal(t, j.Close())
+ j, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer j.Close()
+ var v int
+ mustJournal(t, j.db.QueryRow("PRAGMA user_version").Scan(&v))
+ if v != 2 {
+ t.Fatalf("journal version %d", v)
+ }
+ events, err := j.Pending(ctx, 10)
+ mustJournal(t, err)
+ if len(events) != 1 || events[0].ID != "legacy" {
+ t.Fatal("upgrade lost v1 outbox")
+ }
+ var sync int
+ mustJournal(t, j.db.QueryRow("PRAGMA synchronous").Scan(&sync))
+ if sync != 2 {
+ t.Fatal("capture commits are not FULL synchronous")
+ }
+}
+
+func TestDirectInterruptedBinding(t *testing.T) {
+ j, l, _, p := directFixture(t, "claude")
+ for _, field := range []string{"policy", "manifest", "attempt", "stream", "egress", "boot", "parent"} {
+ t.Run(field, func(t *testing.T) {
+ r := p.record
+ switch field {
+ case "policy":
+ r.PolicyHash = "other"
+ case "manifest":
+ r.ManifestHash = "other"
+ case "attempt":
+ r.AttemptKey = "other"
+ case "stream":
+ r.ID = "other"
+ case "egress":
+ r.EgressHash = "other"
+ case "boot":
+ r.BootID = "other"
+ case "parent":
+ r.ParentTicks++
+ }
+ if j.validateDirectRecord(context.Background(), r) == nil {
+ t.Fatal("recovered identity mismatch accepted", field)
+ }
+ })
+ }
+ if err := j.validateDirectRecord(context.Background(), p.record); err != nil {
+ t.Fatal(err)
+ }
+ // A durable record with a changed policy must also disagree with the saved launch.
+ bad := p.record
+ bad.PolicyHash = "changed"
+ raw, _ := json.Marshal(bad)
+ _, err := j.db.Exec("UPDATE direct_attempts SET record=?", raw)
+ mustJournal(t, err)
+ if j.validateDirectRecord(context.Background(), bad) == nil {
+ t.Fatal("namespace record detached from journaled launch", l.Policy.Hash)
+ }
+}
+func TestDirectJournalProjectionAtomic(t *testing.T) {
+ j, _, s, _ := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, 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")
+ mustJournal(t, err)
+ template := journalEvent("ignored", 1)
+ template.ActionID = 1
+ if _, err = j.appendDirect(ctx, s, directComplete("turn"), &template); err == nil {
+ t.Fatal("injected outbox failure ignored")
+ }
+ var state string
+ mustJournal(t, j.db.QueryRow("SELECT state FROM direct_turns").Scan(&state))
+ if state == "completed" {
+ t.Fatal("completion escaped projection rollback")
+ }
+ var n int
+ mustJournal(t, j.db.QueryRow("SELECT count(*) FROM direct_events WHERE json_extract(body,'$.Kind')='turn.completed'").Scan(&n))
+ if n != 0 {
+ t.Fatal("checkpoint escaped rollback")
+ }
+}
+func TestDirectJournalChunks(t *testing.T) {
+ j, _, s, _ := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ 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 }}
+ template := journalEvent("ignored", 1)
+ mustJournal(t, pump.AppendDirect(ctx, s, e, template))
+ events, err := j.Pending(ctx, 100)
+ mustJournal(t, err)
+ var decoded []byte
+ for i, event := range events {
+ if len(event.Payload) > 16<<10 {
+ t.Fatal("oversize upload")
+ }
+ if i == len(events)-1 {
+ if event.Kind != "tool.completed" {
+ t.Fatal("lifecycle truncated")
+ }
+ break
+ }
+ var chunk struct {
+ Index, Total int
+ Data string `json:"base64"`
+ }
+ mustJournal(t, json.Unmarshal(event.Payload, &chunk))
+ if chunk.Index != i || chunk.Total != len(events)-1 {
+ t.Fatal("unordered chunks")
+ }
+ b, err := base64.StdEncoding.DecodeString(chunk.Data)
+ mustJournal(t, err)
+ decoded = append(decoded, b...)
+ }
+ var envelope struct {
+ Event provider.Event `json:"event"`
+ }
+ mustJournal(t, json.Unmarshal(decoded, &envelope))
+ if string(envelope.Event.Payload) != string(payload) {
+ t.Fatal("tool output truncated")
+ }
+ e.Sequence = 4
+ mustJournal(t, pump.AppendDirect(ctx, s, e, template))
+ events2, err := j.Pending(ctx, 100)
+ mustJournal(t, err)
+ if len(events2) != 2*len(events) {
+ t.Fatal("identical later output was deduplicated")
+ }
+}
+func TestDirectUsageResumeBinding(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 28254, 142))
+ mustJournal(t, err)
+ _, err = j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ _, err = j.db.Exec("UPDATE direct_attempts SET contained=1")
+ mustJournal(t, err)
+ l.AttemptKey = "resume"
+ l.ResumeSessionID = s.ID
+ p.record.ID = strings.Repeat("b", 32)
+ p.record.AttemptKey = l.AttemptKey
+ 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"}))
+ _, err = j.ObserveDirect(ctx, s, codexUsage("resumed", 30000, 150))
+ mustJournal(t, err)
+ u, err := j.ObserveDirect(ctx, s, directComplete("resumed"))
+ mustJournal(t, err)
+ if u == nil || u.InputTokens != 1746 || u.OutputTokens != 8 {
+ t.Fatalf("resume lost baseline: %+v", u)
+ }
+}
+
+func TestDirectUsageResumeRejectsChangedBinding(t *testing.T) {
+ for _, field := range []string{"policy", "account", "binding", "version", "unknown-resume"} {
+ t.Run(field, func(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 100, 10))
+ mustJournal(t, err)
+ _, err = j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ _, err = j.db.Exec("UPDATE direct_attempts SET contained=1")
+ mustJournal(t, err)
+ l.AttemptKey = "resume"
+ l.ResumeSessionID = s.ID
+ p.record.ID = strings.Repeat("b", 32)
+ p.record.AttemptKey = l.AttemptKey
+ switch field {
+ case "policy":
+ l.Policy.Hash = "changed"
+ p.record.PolicyHash = l.Policy.Hash
+ case "account":
+ l.Binding.AccountID = "changed"
+ l.Selection.AccountID = "changed"
+ s.AccountID = "changed"
+ case "binding":
+ l.Binding.ID = "changed"
+ case "version":
+ l.Binding.Expected.ProviderVersion = "changed"
+ case "unknown-resume":
+ l.ResumeSessionID = "unknown"
+ s.ID = "unknown"
+ }
+ mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
+ s.AttemptKey = l.AttemptKey
+ if j.BeginTurn(ctx, s, provider.Turn{ID: "resumed", AdmissionID: "resumed-admit", Prompt: "hello"}) == nil {
+ t.Fatal("resume trusted changed durable binding", field)
+ }
+ })
+ }
+}
+
+func TestDirectInterruptedReconcileIntent(t *testing.T) {
+ for _, kind := range []string{"intent", "before-namespace-record", "policy-mismatch", "manifest-mismatch"} {
+ t.Run(kind, func(t *testing.T) {
+ j, _, _, p := directFixture(t, "codex")
+ ctx := context.Background()
+ root := t.TempDir()
+ mustJournal(t, os.Chmod(root, 0700))
+ binary, err := os.Executable()
+ mustJournal(t, err)
+ m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: binary, ScratchRoot: root})
+ mustJournal(t, err)
+ boot, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ mustJournal(t, err)
+ p.record.BootID = strings.TrimSpace(string(boot))
+ raw, _ := json.Marshal(p.record)
+ _, err = j.db.Exec("UPDATE direct_attempts SET record=?", raw)
+ mustJournal(t, err)
+ if kind == "policy-mismatch" {
+ p.record.PolicyHash = "other"
+ }
+ if kind == "manifest-mismatch" {
+ p.record.ManifestHash = "other"
+ }
+ raw, _ = json.Marshal(p.record)
+ dir := filepath.Join(root, "attempt-"+p.ID())
+ mustJournal(t, os.Mkdir(dir, 0700))
+ mustJournal(t, os.WriteFile(filepath.Join(dir, "scratch"), []byte("owned"), 0600))
+ if kind != "before-namespace-record" {
+ mustJournal(t, os.WriteFile(filepath.Join(root, p.ID()+".json"), raw, 0600))
+ }
+ _, err = j.RecoverDirect(ctx)
+ mustJournal(t, err)
+ if j.AdmissionAllowed(ctx) == nil {
+ t.Fatal("missing containment admitted dependent work")
+ }
+ rows, err := j.ReconcileDirect(ctx, m)
+ if strings.HasSuffix(kind, "mismatch") {
+ if err == nil {
+ t.Fatal("mismatch accepted")
+ }
+ if _, err = os.Stat(dir); err != nil {
+ t.Fatal("mismatch removed scratch")
+ }
+ return
+ }
+ mustJournal(t, err)
+ if len(rows) != 1 || rows[0].State != "never_started" || rows[0].Usage != nil {
+ t.Fatalf("intent not safely retired: %+v", rows)
+ }
+ if _, err = os.Stat(dir); !os.IsNotExist(err) {
+ t.Fatal("scratch remains", err)
+ }
+ mustJournal(t, j.AdmissionAllowed(ctx))
+ })
+ }
+}
+func TestDirectUsageCompaction(t *testing.T) {
+ a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "codex", ProviderVersion: "0.165.0", Subscription: true})
+ a.Observe(codexUsage("turn", 100, 10))
+ a.Observe(provider.Event{SessionID: "session", TurnID: "turn", Kind: "item/completed", Payload: json.RawMessage(`{"params":{"item":{"type":"contextCompaction"}}}`)})
+ a.Observe(codexUsage("turn", 200, 20))
+ if a.Observe(directComplete("turn")) != nil {
+ t.Fatal("compaction invented verified baseline")
+ }
+}
+
+func TestDirectCompletionNeedsContainment(t *testing.T) {
+ j, l, s, p := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ _, err := j.ObserveDirect(ctx, s, codexUsage("turn", 100, 10))
+ mustJournal(t, err)
+ _, err = j.ObserveDirect(ctx, s, directComplete("turn"))
+ mustJournal(t, err)
+ l.AttemptKey = "resume"
+ l.ResumeSessionID = s.ID
+ p.record.ID = strings.Repeat("b", 32)
+ p.record.AttemptKey = l.AttemptKey
+ mustJournal(t, j.recordDirectLaunch(ctx, l, p.record))
+ s.AttemptKey = l.AttemptKey
+ if j.BeginTurn(ctx, s, provider.Turn{ID: "new", AdmissionID: "new-admit", Prompt: "hello"}) == nil {
+ t.Fatal("completion without containment admitted dependent work")
+ }
+}
+
+func TestDirectJournalProjectionSecrets(t *testing.T) {
+ j, _, s, _ := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ 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)))
+ events, err := j.Pending(ctx, 100)
+ mustJournal(t, err)
+ var all []byte
+ for _, event := range events {
+ var chunk struct {
+ Data string `json:"base64"`
+ }
+ mustJournal(t, json.Unmarshal(event.Payload, &chunk))
+ if chunk.Data != "" {
+ b, err := base64.StdEncoding.DecodeString(chunk.Data)
+ mustJournal(t, err)
+ all = append(all, b...)
+ }
+ }
+ if strings.Contains(string(all), "private-token") || strings.Contains(string(all), "custom-secret") || !strings.Contains(string(all), "9007199254740993") {
+ t.Fatal("projection leaked credentials or rounded counters")
+ }
+}
+
+func TestDirectUsageClaudeUnknown(t *testing.T) {
+ for _, usage := range []string{`{}`, `{"input_tokens":1,"output_tokens":2}`, `{"input_tokens":9223372036854775807,"cache_read_input_tokens":1,"cache_creation_input_tokens":0,"output_tokens":2}`, `{"input_tokens":1,"cache_read_input_tokens":0,"cache_creation_input_tokens":-1,"output_tokens":2}`} {
+ a := NewUsageAccumulator(UsageProfile{Version: 2, Provider: "claude", ProviderVersion: "2.1.312", Subscription: true})
+ e := provider.Event{SessionID: "session", TurnID: "turn", Kind: "turn.completed", Payload: json.RawMessage(`{"usage":` + usage + `}`)}
+ if a.Observe(e) != nil {
+ t.Fatalf("unknown Claude usage settled: %s", usage)
+ }
+ }
+}
+
+func TestDirectInterruptedManifestIntegrity(t *testing.T) {
+ j, l, _, p := directFixture(t, "codex")
+ l.Policy.Manifest = json.RawMessage(`{"changed":true}`)
+ raw, _ := json.Marshal(l)
+ _, err := j.db.Exec("UPDATE direct_attempts SET launch=?", raw)
+ mustJournal(t, err)
+ if j.validateDirectRecord(context.Background(), p.record) == nil {
+ t.Fatal("changed saved launch manifest accepted")
+ }
+}
+
+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.AppendFrame(ctx, l.AttemptKey, p.ID(), 1, []byte(`{"n":1}`)))
+ _, err := j.db.Exec("UPDATE direct_attempts SET contained=1")
+ mustJournal(t, err)
+ mustJournal(t, j.releaseDirectFrames(ctx))
+ var pending int
+ mustJournal(t, j.db.QueryRow("SELECT pending FROM direct_frames").Scan(&pending))
+ if pending != 1 {
+ t.Fatal("raw bytes retired before normalization")
+ }
+ template := journalEvent("template", 1)
+ template.ActionID = 1
+ pump := EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(context.Context, Event) error { return nil }}
+ mustJournal(t, pump.AppendDirect(ctx, s, codexUsage("turn", 28254, 142), template))
+ mustJournal(t, pump.AppendDirect(ctx, s, directComplete("turn"), template))
+ mustJournal(t, j.releaseDirectFrames(ctx))
+ mustJournal(t, j.db.QueryRow("SELECT pending FROM direct_frames").Scan(&pending))
+ if pending != 1 {
+ 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))
+ if pending != 0 {
+ t.Fatal("acknowledged bytes still fill pending budget")
+ }
+}
+
+func TestDirectInterruptedSyntheticFailure(t *testing.T) {
+ j, _, s, _ := directFixture(t, "codex")
+ ctx := context.Background()
+ mustJournal(t, j.BeginTurn(ctx, s, directTurn()))
+ p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }}
+ template := journalEvent("template", 1)
+ template.ActionID = 1
+ mustJournal(t, p.AppendDirect(ctx, s, provider.Event{SessionID: s.ID, TurnID: "turn", Kind: "turn.failed"}, template))
+ rows, err := j.RecoverDirect(ctx)
+ mustJournal(t, err)
+ if rows[0].State != "waiting_for_person" || rows[0].Usage != nil {
+ t.Fatal("adapter failure invented accounting")
+ }
+ events, err := j.Pending(ctx, 10)
+ mustJournal(t, err)
+ if len(events) != 1 || events[0].Kind != "turn.failed" {
+ t.Fatal("adapter failure lost before upload")
+ }
+}
diff --git a/internal/runner/direct_usage.go b/internal/runner/direct_usage.go
new file mode 100644
index 00000000..1e98fec7
--- /dev/null
+++ b/internal/runner/direct_usage.go
@@ -0,0 +1,148 @@
+package runner
+
+import (
+ "encoding/json"
+ "math"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type directCounters struct {
+ Input, Output, Cached *int64
+ Bad bool
+}
+type directUsageState struct {
+ Baseline map[string]directCounters
+ Pending map[string]directCounters
+ Settled map[string]*team.Usage
+ Cost map[string]float64
+ CostUnknown map[string]bool
+ Estimated float64
+}
+
+func (a *UsageAccumulator) initDirect() {
+ if a.direct.Baseline == nil {
+ a.direct = directUsageState{Baseline: map[string]directCounters{}, Pending: map[string]directCounters{}, Settled: map[string]*team.Usage{}, Cost: map[string]float64{}, CostUnknown: map[string]bool{}}
+ }
+}
+func usageKeys(p UsageProfile, e provider.Event) (string, string) {
+ s := runnerproto.EventHash([]string{p.Provider, p.ProviderVersion, e.SessionID})
+ return s, runnerproto.EventHash([]string{s, e.TurnID})
+}
+func validCounter(v *int64) bool { return v != nil && *v >= 0 }
+func regress(v, old *int64) bool { return v != nil && old != nil && *v < *old }
+func (a *UsageAccumulator) Observe(e provider.Event) *team.Usage {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ a.initDirect()
+ p := a.profile
+ if p.Version != 2 || p.ProviderVersion == "" || e.SessionID == "" || e.TurnID == "" {
+ return nil
+ }
+ stream, key := usageKeys(p, e)
+ if u, ok := a.direct.Settled[key]; ok {
+ if u == nil {
+ return nil
+ }
+ copy := *u
+ return &copy
+ }
+ var u *team.Usage
+ switch p.Provider {
+ case "codex":
+ base := a.direct.Baseline[stream]
+ pending := a.direct.Pending[key]
+ var item struct {
+ Params struct{ Item struct{ Type string } }
+ }
+ _ = json.Unmarshal(e.Payload, &item)
+ if strings.Contains(strings.ToLower(e.Kind), "compact") || strings.Contains(strings.ToLower(item.Params.Item.Type), "compact") {
+ base.Bad = true
+ a.direct.Baseline[stream] = base
+ return nil
+ }
+ if e.Kind == "usage" {
+ var v struct {
+ Params struct {
+ TokenUsage struct {
+ Total struct {
+ Input *int64 `json:"inputTokens"`
+ Output *int64 `json:"outputTokens"`
+ Cached *int64 `json:"cachedInputTokens"`
+ } `json:"total"`
+ } `json:"tokenUsage"`
+ } `json:"params"`
+ }
+ err := json.Unmarshal(e.Payload, &v)
+ x := v.Params.TokenUsage.Total
+ bad := pending.Bad || base.Bad || err != nil || !validCounter(x.Input) || !validCounter(x.Output) || (x.Cached != nil && (!validCounter(x.Cached) || (x.Input != nil && *x.Cached > *x.Input))) || regress(x.Input, base.Input) || regress(x.Output, base.Output) || regress(x.Cached, base.Cached) || regress(x.Input, pending.Input) || regress(x.Output, pending.Output) || regress(x.Cached, pending.Cached)
+ a.direct.Pending[key] = directCounters{Input: x.Input, Output: x.Output, Cached: x.Cached, Bad: bad}
+ return nil
+ }
+ if e.Kind != "turn.completed" && e.Kind != "turn.failed" {
+ return nil
+ }
+ if !base.Bad && !pending.Bad && validCounter(pending.Input) && validCounter(pending.Output) && e.Kind == "turn.completed" {
+ u = &team.Usage{Calls: 1, InputTokens: *pending.Input, OutputTokens: *pending.Output, CostUnavailable: true}
+ if base.Input != nil {
+ u.InputTokens -= *base.Input
+ }
+ if base.Output != nil {
+ u.OutputTokens -= *base.Output
+ }
+ if pending.Cached != nil {
+ u.CachedInputTokens = *pending.Cached
+ if base.Cached != nil {
+ u.CachedInputTokens -= *base.Cached
+ }
+ }
+ // Cache detail may be absent in the pinned probe. Aggregate tokens are
+ // still known; the checkpoint retains the absent cache counter as nil.
+ } else {
+ pending.Bad = true
+ }
+ a.direct.Baseline[stream] = pending
+ case "claude":
+ if e.Kind != "turn.completed" && e.Kind != "turn.failed" {
+ return nil
+ }
+ var v struct {
+ Usage struct {
+ Input *int64 `json:"input_tokens"`
+ Read *int64 `json:"cache_read_input_tokens"`
+ Write *int64 `json:"cache_creation_input_tokens"`
+ Output *int64 `json:"output_tokens"`
+ } `json:"usage"`
+ Cost *float64 `json:"total_cost_usd"`
+ }
+ if json.Unmarshal(e.Payload, &v) == nil {
+ x := v.Usage
+ if e.Kind == "turn.completed" && validCounter(x.Input) && validCounter(x.Read) && validCounter(x.Write) && validCounter(x.Output) && *x.Input <= math.MaxInt64-*x.Read && *x.Input+*x.Read <= math.MaxInt64-*x.Write {
+ u = &team.Usage{Calls: 1, InputTokens: *x.Input + *x.Read + *x.Write, CachedInputTokens: *x.Read, OutputTokens: *x.Output, CostUnavailable: true}
+ }
+ if v.Cost != nil && *v.Cost >= 0 && !math.IsInf(*v.Cost, 0) && !math.IsNaN(*v.Cost) {
+ old := a.direct.Cost[stream]
+ if *v.Cost < old {
+ a.direct.CostUnknown[stream] = true
+ }
+ if !a.direct.CostUnknown[stream] {
+ a.direct.Estimated += *v.Cost - old
+ a.direct.Cost[stream] = *v.Cost
+ }
+ } else {
+ a.direct.CostUnknown[stream] = true
+ }
+ }
+ default:
+ return nil
+ }
+ a.direct.Settled[key] = u
+ if u == nil {
+ return nil
+ }
+ copy := *u
+ return &copy
+}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 02fb1430..44cdf08d 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -82,11 +82,18 @@ 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 > 1 {
+ if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 2 {
db.Close()
return nil, ErrJournal
}
- _, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS journal_events (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, event_key TEXT UNIQUE NOT NULL, content_hash TEXT NOT NULL, body BLOB NOT NULL, size INTEGER NOT NULL, acked INTEGER NOT NULL DEFAULT 0);
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ db.Close()
+ return nil, ErrJournal
+ }
+ defer tx.Rollback()
+ if version == 0 {
+ _, err = tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS journal_events (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, event_key TEXT UNIQUE NOT NULL, content_hash TEXT NOT NULL, body BLOB NOT NULL, size INTEGER NOT NULL, acked INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS journal_pending ON journal_events(acked,ordinal);
CREATE TABLE IF NOT EXISTS journal_aliases (id TEXT PRIMARY KEY, event_key TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS journal_answers (answer_key TEXT PRIMARY KEY, content_hash TEXT NOT NULL, state TEXT NOT NULL);
@@ -98,6 +105,16 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
INSERT OR IGNORE INTO journal_state VALUES(1,0);
UPDATE journal_streams SET ready=0;
PRAGMA user_version=1;`)
+ }
+ if err == nil && version < 2 {
+ _, err = tx.ExecContext(ctx, directSchema)
+ }
+ if err == nil {
+ _, err = tx.ExecContext(ctx, "UPDATE journal_streams SET ready=0")
+ }
+ if err == nil {
+ err = tx.Commit()
+ }
if err != nil {
db.Close()
return nil, ErrJournal
@@ -125,7 +142,11 @@ func (j *Journal) AdmissionAllowed(ctx context.Context) error {
}
var saved int
var size int64
- if err := j.db.QueryRowContext(ctx, "SELECT blocked,((SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)) 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 || saved != 0 || size >= j.maxBytes {
+ return ErrJournal
+ }
+ var unreconciled int
+ if err := j.db.QueryRowContext(ctx, "SELECT count(*) FROM direct_attempts WHERE recovered=1 AND contained=0").Scan(&unreconciled); err != nil || unreconciled != 0 {
return ErrJournal
}
return nil
@@ -156,9 +177,15 @@ func (j *Journal) append(ctx context.Context, e Event, hash string, body []byte)
return err
}
defer tx.Rollback()
+ if err = j.appendTx(ctx, tx, e, hash, body); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+func (j *Journal) appendTx(ctx context.Context, tx *sql.Tx, e Event, hash string, body []byte) error {
key := e.DedupKey()
var oldKey string
- err = tx.QueryRowContext(ctx, "SELECT event_key FROM journal_aliases WHERE id=?", e.ID).Scan(&oldKey)
+ err := tx.QueryRowContext(ctx, "SELECT event_key FROM journal_aliases WHERE id=?", e.ID).Scan(&oldKey)
if err == nil && oldKey != key {
return runnerproto.ErrInvalid
}
@@ -177,7 +204,7 @@ func (j *Journal) append(ctx context.Context, e Event, hash string, body []byte)
}
var size int64
var blocked int
- if err = tx.QueryRowContext(ctx, "SELECT blocked,((SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)+(SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)) FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
+ if err = tx.QueryRowContext(ctx, "SELECT blocked,"+directPendingSize+" FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil {
return err
}
if blocked != 0 || size < 0 || int64(len(body)) > j.maxBytes-size {
@@ -193,7 +220,7 @@ func (j *Journal) append(ctx context.Context, e Event, hash string, body []byte)
if _, err = tx.ExecContext(ctx, "INSERT OR IGNORE INTO journal_aliases(id,event_key) VALUES(?,?)", e.ID, key); err != nil {
return err
}
- return tx.Commit()
+ return nil
}
func (j *Journal) Pending(ctx context.Context, limit int) ([]Event, error) {
if limit < 1 || limit > 1024 {
@@ -224,7 +251,7 @@ func (j *Journal) Ack(ctx context.Context, id string) error {
if err != nil || n != 1 {
return ErrJournal
}
- return nil
+ return j.releaseDirectFrames(ctx)
}
func (j *Journal) RecordIntent(ctx context.Context, i paseo.Intent) error {
if i.Key == "" || i.Kind == "" || i.RequestHash == "" || !json.Valid(i.Request) {
diff --git a/internal/runner/journal_reset.go b/internal/runner/journal_reset.go
index 1b040916..0ee68ef3 100644
--- a/internal/runner/journal_reset.go
+++ b/internal/runner/journal_reset.go
@@ -33,7 +33,9 @@ func (j *Journal) resetAfterReconcile(ctx context.Context, reconcile func(contex
if err := j.db.QueryRowContext(ctx, `SELECT
(SELECT count(*) FROM journal_events WHERE acked=0)+
(SELECT count(*) FROM journal_tools WHERE acked=0)+
- (SELECT count(*) FROM journal_supervisor WHERE kind='attempt' AND json_extract(body,'$.Phase')!='contained')`).Scan(&pending); err != nil {
+ (SELECT count(*) FROM journal_supervisor WHERE kind='attempt' AND json_extract(body,'$.Phase')!='contained')+
+ (SELECT count(*) FROM direct_attempts WHERE contained=0)+
+ (SELECT count(*) FROM direct_events WHERE projected=0)`).Scan(&pending); err != nil {
return j.storageFailure(ctx, err)
}
if pending != 0 {
diff --git a/internal/runner/journal_test.go b/internal/runner/journal_test.go
index 9c7abf54..e1b94293 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=2")
+ _, err = j.db.Exec("PRAGMA user_version=3")
mustJournal(t, err)
mustJournal(t, j.Close())
if other, err := OpenJournal(journalCtx, path); err == nil {
diff --git a/internal/runner/provider/claude/launcher.go b/internal/runner/provider/claude/launcher.go
index 2c76a6e9..9e86a585 100644
--- a/internal/runner/provider/claude/launcher.go
+++ b/internal/runner/provider/claude/launcher.go
@@ -474,6 +474,13 @@ func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.S
process.Wait(context.Background())
return provider.Session{}, errNotReady
}
+ if binding, ok := capture.Input.(provider.SessionBinding); ok {
+ if e = binding.BindSession(ctx, session); e != nil {
+ cancel()
+ process.Wait(context.Background())
+ return provider.Session{}, e
+ }
+ }
s := &sessionState{session: session, launch: launch, base: base, lease: lease, process: process, capture: capture, ctx: attempt, cancel: cancel, events: make(chan provider.Event, 64), done: make(chan struct{}), used: map[string]bool{}}
if previous != nil {
previous.clean = false
@@ -564,6 +571,11 @@ func (l *Launcher) StartTurn(ctx context.Context, s provider.Session, t provider
v.turn = t
v.used[t.ID] = true
v.used[t.AdmissionID] = true
+ if barrier, ok := v.capture.Input.(provider.TurnBarrier); ok {
+ if e = barrier.BeginTurn(ctx, s, t); e != nil {
+ return fail(e)
+ }
+ }
l.mu.Unlock()
stopWrite := context.AfterFunc(ctx, func() { v.cancel(); v.capture.Input.Close() })
n, e := v.capture.Input.Write(raw)
@@ -645,6 +657,7 @@ func (l *Launcher) read(s *sessionState) {
if e == nil {
for i := range events {
ev := &events[i]
+ ev.Sequence = frame.Sequence
if ev.SessionID != s.session.ID {
e = provider.ErrIdentity
break
diff --git a/internal/runner/provider/claude/launcher_test.go b/internal/runner/provider/claude/launcher_test.go
index aa3c5d88..704e88b0 100644
--- a/internal/runner/provider/claude/launcher_test.go
+++ b/internal/runner/provider/claude/launcher_test.go
@@ -8,6 +8,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"io"
"os"
"os/exec"
@@ -834,3 +835,69 @@ func TestClaudeRefreshWithConfigTamper(t *testing.T) {
t.Fatal("tampered refresh left the attempt running")
}
}
+
+type directGuardCapture struct {
+ inner provider.CaptureFactory
+ fail bool
+ bound, turns int
+}
+type directGuardInput struct {
+ io.WriteCloser
+ owner *directGuardCapture
+}
+
+func (c *directGuardCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
+ cap, e := c.inner.Open(ctx, p, l)
+ if e == nil {
+ cap.Input = &directGuardInput{cap.Input, c}
+ }
+ return cap, e
+}
+func (w *directGuardInput) BindSession(context.Context, provider.Session) error {
+ w.owner.bound++
+ return nil
+}
+func (w *directGuardInput) BeginTurn(context.Context, provider.Session, provider.Turn) error {
+ w.owner.turns++
+ if w.owner.fail {
+ return io.ErrClosedPipe
+ }
+ return nil
+}
+
+func TestDirectJournalAdapterBarrier(t *testing.T) {
+ for _, fail := range []bool{false, true} {
+ t.Run(fmt.Sprint(fail), func(t *testing.T) {
+ f := fixtureFor(t, "Engineering")
+ guard := &directGuardCapture{inner: f.l.captures, fail: fail}
+ f.l.captures = guard
+ session, ch := openFixture(t, f)
+ if guard.bound != 1 {
+ t.Fatal("session not durably bound")
+ }
+ err := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "direct-turn", AdmissionID: "direct-admission", Prompt: "hello"})
+ if fail {
+ if err == nil {
+ t.Fatal("failed journal barrier ignored")
+ }
+ f.capture.mu.Lock()
+ n := f.capture.inputs
+ f.capture.mu.Unlock()
+ if n != 0 {
+ t.Fatal("failed barrier sent input")
+ }
+ } else {
+ if err != nil {
+ t.Fatal(err)
+ }
+ event := terminal(t, ch)
+ if event.Sequence <= 0 {
+ t.Fatal("capture sequence lost before projection")
+ }
+ }
+ if guard.turns != 1 {
+ t.Fatal("journal turn barrier not called")
+ }
+ })
+ }
+}
diff --git a/internal/runner/provider/codex/launcher.go b/internal/runner/provider/codex/launcher.go
index e6827f96..1280ff2d 100644
--- a/internal/runner/provider/codex/launcher.go
+++ b/internal/runner/provider/codex/launcher.go
@@ -230,7 +230,7 @@ func (l *Launcher) validatePolicy(b provider.Binding, p provider.Policy) (provid
}
return in, nil
}
-func (l *Launcher) start(ctx context.Context, launch provider.Launch, handler func([]byte) error) (provider.Process, *provider.Capture, *RPC, error) {
+func (l *Launcher) start(ctx context.Context, launch provider.Launch, handler func(provider.Frame) error) (provider.Process, *provider.Capture, *RPC, error) {
in, _, e := policyInputs(launch.Policy)
if e != nil {
return nil, nil, nil, e
@@ -249,7 +249,7 @@ func (l *Launcher) start(ctx context.Context, launch provider.Launch, handler fu
if cap == nil || cap.Input == nil || cap.Frames == nil || cap.Done == nil {
return proc, cap, nil, errNotReady
}
- return proc, cap, newRPC(ctx, cap, handler), nil
+ return proc, cap, newFrameRPC(ctx, cap, handler), nil
}
func waitProcess(proc provider.Process) {
if proc != nil {
@@ -370,7 +370,8 @@ func (l *Launcher) preflight(ctx context.Context, b provider.Binding, lease *pro
return provider.Identity{}, e
}
launch := provider.Launch{AttemptKey: "codex-preflight-" + token(), Workspace: in.Workspace, Binding: b, Policy: p, Selection: provider.Selection{Provider: "codex", AccountID: b.AccountID}}
- proc, _, r, e := l.start(ctx, launch, func(raw []byte) error {
+ proc, _, r, e := l.start(ctx, launch, func(frame provider.Frame) error {
+ raw := frame.Bytes
v, _ := parse(raw)
if v.Method == "account/updated" {
return provider.ErrIdentity
@@ -495,6 +496,11 @@ func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.S
if e = session.Validate(launch); e != nil {
return fail(e)
}
+ if binding, ok := s.capture.Input.(provider.SessionBinding); ok {
+ if e = binding.BindSession(ctx, session); e != nil {
+ return fail(e)
+ }
+ }
if previous != nil {
previous.mu.Lock()
previous.clean = false
@@ -630,6 +636,11 @@ func (l *Launcher) StartTurn(ctx context.Context, session provider.Session, t pr
json.Unmarshal(s.launch.Policy.TurnPolicy, &params)
params["threadId"] = marshal(session.ID)
params["input"] = marshal([]any{map[string]any{"type": "text", "text": t.Prompt}})
+ if barrier, ok := s.capture.Input.(provider.TurnBarrier); ok {
+ if e = barrier.BeginTurn(ctx, session, t); e != nil {
+ return s.stop(e)
+ }
+ }
raw, e := s.rpc.Call(ctx, "turn/start", marshal(params))
if e != nil {
return s.stop(errUncertain)
@@ -697,14 +708,15 @@ func (l *Launcher) Close(ctx context.Context, session provider.Session) error {
defer s.mu.Unlock()
return s.err
}
-func (s *sessionState) handle(raw []byte) error {
- events, e := Decode(raw)
+func (s *sessionState) handle(frame provider.Frame) error {
+ events, e := Decode(frame.Bytes)
if e != nil {
return e
}
s.mu.Lock()
defer s.mu.Unlock()
for _, ev := range events {
+ ev.Sequence = frame.Sequence
if ev.Kind == "account/updated" || strings.HasPrefix(ev.Kind, "config/") {
return provider.ErrContainment
}
diff --git a/internal/runner/provider/codex/launcher_test.go b/internal/runner/provider/codex/launcher_test.go
index 77584f65..c4999c1d 100644
--- a/internal/runner/provider/codex/launcher_test.go
+++ b/internal/runner/provider/codex/launcher_test.go
@@ -8,6 +8,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"io"
"os"
"path/filepath"
@@ -861,3 +862,66 @@ func TestCodexTypedNilConstructor(t *testing.T) {
t.Fatal("typed nil capture accepted")
}
}
+
+type directGuardCapture struct {
+ inner provider.CaptureFactory
+ fail bool
+ bound, turns int
+}
+type directGuardInput struct {
+ io.WriteCloser
+ owner *directGuardCapture
+}
+
+func (c *directGuardCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) {
+ cap, e := c.inner.Open(ctx, p, l)
+ if e == nil {
+ cap.Input = &directGuardInput{cap.Input, c}
+ }
+ return cap, e
+}
+func (w *directGuardInput) BindSession(context.Context, provider.Session) error {
+ w.owner.bound++
+ return nil
+}
+func (w *directGuardInput) BeginTurn(context.Context, provider.Session, provider.Turn) error {
+ w.owner.turns++
+ if w.owner.fail {
+ return io.ErrClosedPipe
+ }
+ return nil
+}
+
+func TestDirectJournalAdapterBarrier(t *testing.T) {
+ for _, fail := range []bool{false, true} {
+ t.Run(fmt.Sprint(fail), func(t *testing.T) {
+ f := fixtureFor(t)
+ guard := &directGuardCapture{inner: f.l.captures, fail: fail}
+ f.l.captures = guard
+ session, ch := openFixture(t, f)
+ if guard.bound != 1 {
+ t.Fatal("session not durably bound")
+ }
+ err := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "direct-turn", AdmissionID: "direct-admission", Prompt: "hello"})
+ if fail {
+ if err == nil {
+ t.Fatal("failed journal barrier ignored")
+ }
+ if f.host.count("turn/start") != 0 {
+ t.Fatal("failed barrier sent input")
+ }
+ } else {
+ if err != nil {
+ t.Fatal(err)
+ }
+ event := terminal(t, ch)
+ if event.Sequence <= 0 {
+ t.Fatal("capture sequence lost before projection")
+ }
+ }
+ if guard.turns != 1 {
+ t.Fatal("journal turn barrier not called")
+ }
+ })
+ }
+}
diff --git a/internal/runner/provider/codex/rpc.go b/internal/runner/provider/codex/rpc.go
index e3c340bf..96ec9f66 100644
--- a/internal/runner/provider/codex/rpc.go
+++ b/internal/runner/provider/codex/rpc.go
@@ -22,7 +22,7 @@ type RPC struct {
ctx context.Context
cancel context.CancelFunc
cap *provider.Capture
- handler func([]byte) error
+ handler func(provider.Frame) error
mu sync.Mutex
writeMu sync.Mutex
pending map[string]chan reply
@@ -32,6 +32,9 @@ type RPC struct {
}
func newRPC(ctx context.Context, cap *provider.Capture, handler func([]byte) error) *RPC {
+ return newFrameRPC(ctx, cap, func(f provider.Frame) error { return handler(f.Bytes) })
+}
+func newFrameRPC(ctx context.Context, cap *provider.Capture, handler func(provider.Frame) error) *RPC {
ctx, cancel := context.WithCancel(ctx)
r := &RPC{ctx: ctx, cancel: cancel, cap: cap, handler: handler, pending: map[string]chan reply{}, done: make(chan struct{})}
go r.read()
@@ -172,7 +175,7 @@ func (r *RPC) read() {
return
}
if v.Method != "" {
- if e = r.handler(bytes.Clone(frame.Bytes)); e != nil {
+ if e = r.handler(provider.Frame{Sequence: frame.Sequence, Bytes: bytes.Clone(frame.Bytes)}); e != nil {
r.fail(e)
return
}
diff --git a/internal/runner/provider/types.go b/internal/runner/provider/types.go
index dc210fce..4b6678b2 100644
--- a/internal/runner/provider/types.go
+++ b/internal/runner/provider/types.go
@@ -73,6 +73,7 @@ type Answer struct {
}
type Event struct {
+ Sequence int64 `json:"capture_sequence,omitempty"`
SessionID, TurnID, RequestID, Kind string
Payload json.RawMessage
}
@@ -167,3 +168,14 @@ func (e Event) ValidateIdentity(s Session, t Turn) error {
}
return nil
}
+
+// TurnBarrier is implemented by durable capture stdin. Adapters call it before
+// the prompt write, after admission and their final account/policy checks.
+type TurnBarrier interface {
+ BeginTurn(context.Context, Session, Turn) error
+}
+
+// SessionBinding persists the provider identity as soon as Open discovers it.
+type SessionBinding interface {
+ BindSession(context.Context, Session) error
+}
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go
index 51e90a18..50d54e25 100644
--- a/internal/runner/tool_journal.go
+++ b/internal/runner/tool_journal.go
@@ -47,7 +47,7 @@ func (j *Journal) appendTool(ctx context.Context, v ToolSubmission, inputHash st
return runnerproto.ErrInvalid
}
var size int64
- if err = tx.QueryRowContext(ctx, "SELECT (SELECT COALESCE(SUM(length(body)),0) FROM journal_tools WHERE acked=0)+(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0)").Scan(&size); err != nil {
+ if err = tx.QueryRowContext(ctx, "SELECT "+directPendingSize).Scan(&size); err != nil {
tx.Rollback()
return j.storageFailure(ctx, err)
}
diff --git a/internal/runner/usage.go b/internal/runner/usage.go
index 74d3c8b1..2da47542 100644
--- a/internal/runner/usage.go
+++ b/internal/runner/usage.go
@@ -55,9 +55,9 @@ func NormalizeTokens(v ProviderTokens, inputSemantics string, writeIncluded bool
}
type UsageProfile struct {
- Version int
- Provider, PaseoVersion, TokenSemantics, InputSemantics, CostSemantics string
- Subscription bool
+ Version int
+ Provider, ProviderVersion, PaseoVersion, TokenSemantics, InputSemantics, CostSemantics string
+ Subscription bool
// Paseo exposes cache writes only when its adapter includes them in input.
CacheWriteSeparate bool
}
@@ -67,6 +67,7 @@ type UsageAccumulator struct {
settled map[string]team.Usage
cost map[string]float64
estimated float64
+ direct directUsageState
}
func NewUsageAccumulator(profile UsageProfile) *UsageAccumulator {
@@ -81,7 +82,7 @@ type observedUsage struct {
Cost *float64 `json:"totalCostUsd"`
}
-func (a *UsageAccumulator) Observe(e paseo.Event) *team.Usage {
+func (a *UsageAccumulator) ObservePaseo(e paseo.Event) *team.Usage {
a.mu.Lock()
defer a.mu.Unlock()
p := a.profile
@@ -153,7 +154,7 @@ func (a *UsageAccumulator) Observe(e paseo.Event) *team.Usage {
func (a *UsageAccumulator) EstimatedCostUSD() float64 {
a.mu.Lock()
defer a.mu.Unlock()
- return a.estimated
+ return a.estimated + a.direct.Estimated
}
func (j *Journal) Usage(ctx context.Context, a paseo.Agent, profile UsageProfile) (*UsageAccumulator, error) {
accumulator := NewUsageAccumulator(profile)
@@ -169,7 +170,7 @@ func (j *Journal) Usage(ctx context.Context, a paseo.Agent, profile UsageProfile
return nil, ErrJournal
}
if e.ServerID == a.ServerID && e.AgentID == a.AgentID && e.SessionID == a.ProviderSessionID {
- accumulator.Observe(paseo.Event{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Epoch: e.Epoch, Sequence: e.Sequence, Payload: e.Payload})
+ accumulator.ObservePaseo(paseo.Event{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Epoch: e.Epoch, Sequence: e.Sequence, Payload: e.Payload})
}
}
return accumulator, rows.Err()
diff --git a/internal/runner/usage_test.go b/internal/runner/usage_test.go
index 790b0c81..2f9476bf 100644
--- a/internal/runner/usage_test.go
+++ b/internal/runner/usage_test.go
@@ -13,48 +13,48 @@ func usageEvent(turn, usage string) paseo.Event {
func TestUsageCumulativeAndMissing(t *testing.T) {
a := NewUsageAccumulator(UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "exclusive", CostSemantics: "cumulative", Subscription: true})
first := usageEvent("one", `{"inputTokens":18,"cachedInputTokens":29591,"outputTokens":404,"totalCostUsd":0.0673131}`)
- u := a.Observe(first)
+ u := a.ObservePaseo(first)
if u == nil || u.InputTokens != 29609 || u.CachedInputTokens != 29591 || u.CostMicros != 0 || !u.CostUnavailable {
t.Fatal("normalization", u)
}
next := usageEvent("two", `{"inputTokens":2,"cachedInputTokens":3,"outputTokens":4,"totalCostUsd":0.0758928}`)
- if a.Observe(next) == nil {
+ if a.ObservePaseo(next) == nil {
t.Fatal("second completion unknown")
}
if math.Abs(a.EstimatedCostUSD()-0.0758928) > 1e-10 {
t.Fatal("cumulative cost summed", a.EstimatedCostUSD())
}
- if a.Observe(usageEvent("missing", `null`)) != nil {
+ if a.ObservePaseo(usageEvent("missing", `null`)) != nil {
t.Fatal("missing usage became zero")
}
for _, kind := range []string{"agent_update", "queued", "idle", "timeline"} {
e := first
e.Kind = kind
e.Payload = json.RawMessage(`{"agent":{"lastUsage":{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}}}`)
- if a.Observe(e) != nil {
+ if a.ObservePaseo(e) != nil {
t.Fatal("status proved completion", kind)
}
}
- if got := a.Observe(first); got == nil || *got != *u {
+ if got := a.ObservePaseo(first); got == nil || *got != *u {
t.Fatal("lastUsage erased completion", got)
}
unknown := NewUsageAccumulator(UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "unverified", InputSemantics: "exclusive", Subscription: true})
- if unknown.Observe(first) != nil {
+ if unknown.ObservePaseo(first) != nil {
t.Fatal("unverified cumulative semantics settled")
}
- if got := a.Observe(usageEvent("zero", `{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}`)); got == nil || got.InputTokens != 0 {
+ if got := a.ObservePaseo(usageEvent("zero", `{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}`)); got == nil || got.InputTokens != 0 {
t.Fatal("known zero lost")
}
for _, raw := range []string{`{"inputTokens":1,"outputTokens":2}`, `{"inputTokens":9223372036854775807,"cachedInputTokens":1,"outputTokens":1}`, `{"inputTokens":-1,"cachedInputTokens":0,"outputTokens":1}`} {
- if a.Observe(usageEvent("invalid", raw)) != nil {
+ if a.ObservePaseo(usageEvent("invalid", raw)) != nil {
t.Fatal("partial or invalid usage settled")
}
}
inclusive := NewUsageAccumulator(UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "inclusive", Subscription: true})
- if v := inclusive.Observe(first); v != nil {
+ if v := inclusive.ObservePaseo(first); v != nil {
t.Fatal("cache exceeds inclusive input")
}
- got := inclusive.Observe(usageEvent("inclusive", `{"inputTokens":20,"cachedInputTokens":5,"outputTokens":2}`))
+ got := inclusive.ObservePaseo(usageEvent("inclusive", `{"inputTokens":20,"cachedInputTokens":5,"outputTokens":2}`))
if got == nil || got.InputTokens != 20 || got.CachedInputTokens != 5 {
t.Fatal("inclusive cache counted twice", got)
}
@@ -71,7 +71,7 @@ func TestUsageCumulativeCompletionGuards(t *testing.T) {
for _, kind := range []string{"idle", "queued", "timeline", "agent_update"} {
bad := e
bad.Kind = kind
- if NewUsageAccumulator(p).Observe(bad) != nil {
+ if NewUsageAccumulator(p).ObservePaseo(bad) != nil {
t.Fatal("noncompletion kind settled", kind)
}
}
@@ -92,25 +92,25 @@ func TestUsageCumulativeCompletionGuards(t *testing.T) {
case "input_mode":
profile.InputSemantics = "unknown"
}
- if NewUsageAccumulator(profile).Observe(bad) != nil {
+ if NewUsageAccumulator(profile).ObservePaseo(bad) != nil {
t.Fatal("unverified usage settled", field)
}
}
a := NewUsageAccumulator(p)
- u := a.Observe(e)
+ u := a.ObservePaseo(e)
if u == nil {
t.Fatal("completion missing")
}
zero := usageEvent("turn", `{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}`)
- if got := a.Observe(zero); got == nil || *got != *u {
+ if got := a.ObservePaseo(zero); got == nil || *got != *u {
t.Fatal("zero erased completed evidence")
}
p.Subscription = false
- if NewUsageAccumulator(p).Observe(e) != nil {
+ if NewUsageAccumulator(p).ObservePaseo(e) != nil {
t.Fatal("unverified cumulative currency settled")
}
p.CostSemantics = "turn"
- if got := NewUsageAccumulator(p).Observe(e); got == nil || got.CostMicros != 67314 || got.CostUnavailable {
+ if got := NewUsageAccumulator(p).ObservePaseo(e); got == nil || got.CostMicros != 67314 || got.CostUnavailable {
t.Fatal("metered per-turn normalization", got)
}
partial, err := NormalizeTokens(ProviderTokens{Input: 5, InputKnown: true, OutputKnown: true}, "inclusive", true)
diff --git a/internal/runner/workflow_turn.go b/internal/runner/workflow_turn.go
index c23460da..4effcf93 100644
--- a/internal/runner/workflow_turn.go
+++ b/internal/runner/workflow_turn.go
@@ -66,7 +66,7 @@ func (w *BugWorkflow) modelTurn(ctx context.Context, s *Supervisor, r *attemptSt
// Unknown token counts retain their reservation. No inferred usage receipt.
receipt := team.Receipt{ID: e.TurnID, Outcome: outcome, Provider: r.Agent.Provider, Model: r.Agent.Model}
if usage != nil {
- receipt.Usage = usage.Observe(e)
+ receipt.Usage = usage.ObservePaseo(e)
}
key := runnerproto.EventHash([]any{r.Claim.Scope, r.Claim.Handle.Attempt, r.Claim.Handle.Fence, action})
if err := w.cfg.Witness.record(ctx, "receipt", key, receipt); err != nil {