fix: keep the runner serving when coordinator recovery is refused
30 files changed,
+1,511
−185
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+607 −0internal/coordinator/context_fix_test.go+30 −0internal/coordinator/runtime_test.go+2 −2internal/equipo/conversation/context.go+10 −50internal/equipo/conversation/context_decisions.go+77 −0internal/equipo/conversation/coordinator.go+24 −7internal/equipo/conversation/coordinator_application.go+5 −1internal/equipo/conversation/coordinator_execution.go+1 −1internal/equipo/conversation/coordinator_poll.go+27 −4internal/equipo/conversation/coordinator_recovery.go+4 −1internal/equipo/conversation/models.go+2 −1internal/equipo/conversation/store.go+7 −0internal/equipo/copy.go+1 −1internal/plan3test/coordinator_continuity_fixture.go+55 −7internal/plan3test/coordinator_continuity_test.go+5 −0internal/plan3test/coordinator_instance_fixture.go+52 −0internal/plan3test/coordinator_review_test.go+297 −0internal/plan3test/coordinator_test.go+0 −26internal/plan3test/{harness_test.go => harness_fixture.go}+0 −0internal/plan3test/plans_approval_test.go+0 −15internal/runner/coordinator_fix_test.go+193 −0internal/runner/coordinator_recovery.go+26 −15internal/runner/coordinator_runtime_test.go+8 −0internal/runner/coordinator_service.go+9 −16internal/runner/coordinator_tool_proxy.go+14 −6internal/runner/journal.go+1 −1internal/runner/service.go+44 −26internal/runner/supervisor.go+4 −2internal/runnerproto/coordinator_prompt.go+5 −2
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index ce0e205c..1752ef91 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -21,7 +21,7 @@ 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/v2/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 9300 - Task 7 retains coordinator service wiring, scoped tool delivery, namespace cleanup and journal recovery beside the existing capture and lease boundaries. Measured 9097 source and 7836 test lines; pure context and turn sequencing live in runnerproto and coordinator. Targeted runner regressions measured 19.976s; the existing full-package time ceiling is unchanged. |
| +size internal/runner 9300 8200 Task 7 fix round 1 retains shared-journal refusal recovery, independent polling, containment retry and lease-cadence regression tests beside the runner hooks. Measured 9129 source and 8037 test lines; targeted coordinator runner tests measured 27.384s. Pure context rules remain in runnerproto/coordinator; the 330s time ceiling is unchanged. |
| 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. |
| time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.659s (prior attempt 11.464s) for schema, native approval and fsynced capture fixtures; 15s gives 29 percent headroom under shared-runner load. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 40157b01..1533f0a7 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -1963,3 +1963,610 @@ Provider prompt instructions are protocol text, not interface copy. Other new st |
| The requested full report is written to `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-7-report.md`, which is ignored by Git. The tracked controller report preserves the test commands and mutation evidence. |
| No agents, copy-review server, `.claude/HANDOFF.md`, push, merge or deployment. Go caches stayed at their defaults. Scratch is limited to task-owned files under `$TMPDIR/equipo-task7`; it is removed before handing back. Recorded fixture processes and endpoints were closed by their test cleanup. |
| + |
| +## Fix round 1 |
| + |
| +Status: DONE_WITH_CONCERNS. The dispatched critical, important and minor findings are fixed. The changed context-limit copy remains pending review. This section supersedes the earlier concern that expired delivery authority could block reconciliation. Commit subject: `fix: keep the runner serving when coordinator recovery is refused`. Author: `codex <codex~paul@keymail.dev>`. No push. |
| + |
| +### Changes and covering tests |
| + |
| +Refused delivery now reports verified containment before retiring the local turn. The instance's existing containment transaction marks undelivered work uncertain and retains its unknown reservation charge, including after expiry, reset or connection change. The journal records refusal and completion, retains event evidence and never resends the prompt. Temporary containment-report failure remains retryable. Coordinator recovery uses the service's fatal/retry classification; coordinator polling and specialist polling have separate recovery state. The ordinary task uploader excludes coordinator-owned events so specialist recovery cannot consume them first. |
| + |
| +- `TestCoordinatorRecoveryRefusedKeepsServing`: completed, unreported turns refused with 403, 409 and 422; shared coordinator/specialist journal; specialist assignment handling continues across two journal reopenings; exactly one refusal/containment; durable refusal/finished flags; no provider restart. |
| +- `TestCoordinatorCleanupRefusalReportsContainment`: the normal completion defer also reports containment and does not retry the finished turn on restart. |
| +- `TestCoordinatorRecoveryInstanceRefusals`: real instance authority refuses the completed event after lease expiry, reset or connection change; containment persists uncertainty and the full unknown charge; a subsequent generation can claim a new request. |
| +- `TestCoordinatorRefusalContainmentRetry`: a temporary containment failure does not inherit the delivery refusal's fatal classification; successful retry retires the turn. |
| +- `TestCoordinatorPollErrorKeepsServing`: a coordinator poll error cannot skip specialist assignments. |
| + |
| +A `context_limit` turn stays parked and cannot be claimed again until explicit retry or reset. Retry creates a new turn/snapshot without requiring containment for work that was never admitted. Reset supersedes parked turns. The private conversation includes a coordinator card with the turn ID/revision, `coordinator.context_limit`, and `coordinator.reset` / `coordinator.retry` action keys. Task 9 still owns HTML rendering, as for the existing waiting card. `TestCoordinatorContextLimitParked` checks repeat polling, direct claim refusal, the card/actions, retry/reset and card removal. |
| + |
| +Required decisions now belong to open work. Approved plans remain required while their task is open; finished or cancelled plans become optional retrieval. Answers follow tasks created from or explicitly attached to their request. Until a task exists, an outstanding answer follow-up or pending clarification owns that decision. Completed standalone question work becomes optional. Optional answers and approvals each have a deterministic 50-record retrieval window; active records retain the existing fail-closed 1000-record bound. Source access is rechecked, and optional decisions are trimmed before recent messages. Team instructions and confirmed preferences remain required. |
| + |
| +- `TestCoordinatorContextFinishedDecisionsOptional`: 1002 approved tasks, finished/cancelled except one open task; a new turn succeeds, retains the open decision, and can retrieve finished decisions without requiring them. |
| +- `TestCoordinatorContextAnsweredWorkFinished` and `TestCoordinatorContextAnswerFollowsOpenWork`: finished answers become optional; answers for open linked work stay required and stop being required when that work is cancelled. |
| +- Existing `TestCoordinatorContextConfirmedAnswer` still checks an outstanding explicit answer and excludes inferred preferences. |
| + |
| +The admitted request is required. Context assembly verifies that the newest retained message is the admitted message, and both body-window and serialized-prompt trimming retain it. If required instructions/decisions plus the request do not fit, context assembly returns `context_limit`. `TestCoordinatorContextRequestRequired` covers both raw and JSON-escaped pressure. The prior test that expected a single escaped request to disappear now expects rejection. |
| + |
| +The requested minor fixes are also covered: |
| + |
| +| Finding | Change and coverage | |
| +| --- | --- | |
| +| Minor 1 | The real Claude/Codex continuity fixtures now obtain each history/decision/project snapshot from a fresh instance claim using that provider's connection. They delete fixture preference records and revoke one project's connection access between claims. Both prompts retain an accessible source and open decision; the first contains the removed records and the second excludes them. Preference persistence remains a fixture database source until Task 8. The shared instance helpers moved into fixture files so the real-launcher tests can reuse them. Bypassing production project access makes continuity fail. | |
| +| Minor 2 | Separate `TestCoordinatorContextFiftySmallMessages` tests exercise the wire bound and the instance query with small bodies. The instance test counts source checks, so removing SQL `Limit(50)` fails even though the wire layer still trims. | |
| +| Minor 4 | `CoordinatorToolResult` returns the `Validate` error. `TestCoordinatorRecoveryInvalidTool` covers rejected recovery arguments. `Canonical` already validates before this second check, so this regression passed before the cleanup; removing only the redundant second check cannot demonstrate a distinct reachable failure and is not counted as a guard mutation. | |
| +| Minor 5 | Own-project retrieval precedes generic project labels. `TestCoordinatorContextOwnProjectFirst` forces label trimming and retains the own-project snapshot. | |
| +| Minor 6 | Reset/connection changes remove the waiting record. Polling clears it when the blocking assignment releases, before a coordinator claim. The runner refreshes status after specialist release. `TestCoordinatorWaitingReset`, the strengthened `TestCoordinatorConnectionWaiting`, and `TestCoordinatorWaitingObserverChanges` cover this. | |
| +| Minor 8 | Idle coordinator renewal and waiting observation use the existing 15-second lease cadence. The tool proxy's 100 ms watchdog checks only local state/deadlines; actual tool use still rechecks remote authority. Waiting records are written only on changes. `TestCoordinatorRenewalCadence`, `TestCoordinatorWaitingObserverChanges` and `TestCoordinatorWaitingWritesOnlyOnChange` cover traffic and persistence. | |
| +| Minor 9 | The context-limit card and reset/retry action references are covered by `TestCoordinatorContextLimitParked`; copy is individually pending. | |
| + |
| +Review minor findings 3 and 7 were not dispatched for this round and were left unchanged. No migrations or README changes were needed. App runtime copy remains in `internal/equipo/copy.go`. |
| + |
| +### Red evidence |
| + |
| +Tests were added before the main fixes. Initial runner tests reproduced restart failure, specialist starvation and request trimming. Instance tests reproduced parked-turn re-offering and stale waiting records. The long-history tests reproduced the permanent required-decision limit. The cadence test also exposed the proxy watchdog's remote renewal every 100 ms; changing only the service ticker was insufficient. The shared-journal test caught the ordinary uploader consuming coordinator events. These failures were fixed and the covering tests rerun. |
| + |
| +Command (exit 1): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner ./internal/coordinator -run '^TestCoordinator(RecoveryRefused|PollError|CleanupRefusal|ContextRequestRequired|ContextFifty)' -count=1 |
| +``` |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRecoveryRefusedKeepsServing (0.64s) |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/Ɠ (0.22s) |
| + coordinator_fix_test.go:48: coordinator stopped specialist work: ran=false error= |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/ƙ (0.22s) |
| + coordinator_fix_test.go:48: coordinator stopped specialist work: ran=false error= |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/Ʀ (0.21s) |
| + coordinator_fix_test.go:48: coordinator stopped specialist work: ran=false error= |
| +--- FAIL: TestCoordinatorPollErrorKeepsServing (0.58s) |
| + coordinator_fix_test.go:73: coordinator stopped specialist work: ran=false error=context canceled |
| +FAIL |
| +rastrillo-budget/v1 ran 1.39s |
| +FAIL amadan.net/oficina/equipo/internal/runner 1.392s |
| +--- FAIL: TestCoordinatorContextRequestRequired (0.00s) |
| + context_fix_test.go:15: admitted request was trimmed <nil> |
| +FAIL |
| +rastrillo-budget/v1 ran 1ms |
| +FAIL amadan.net/oficina/equipo/internal/coordinator 0.003s |
| +FAIL |
| +``` |
| + |
| +Command (exit 1): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(ContextLimitParked|ContextFiftySmallMessages|WaitingReset|RecoveryInstanceRefusals|RecoveryInvalidTool|ConnectionWaiting)$' -count=1 |
| +``` |
| + |
| +```text |
| +--- FAIL: TestCoordinatorConnectionWaiting (0.42s) |
| + coordinator_continuity_test.go:65: released task retained waiting record before claim |
| +--- FAIL: TestCoordinatorContextLimitParked (0.31s) |
| + --- FAIL: TestCoordinatorContextLimitParked/retry (0.15s) |
| + coordinator_review_test.go:23: context_limit turn re-offered |
| + --- FAIL: TestCoordinatorContextLimitParked/reset (0.16s) |
| + coordinator_review_test.go:23: context_limit turn re-offered |
| +--- FAIL: TestCoordinatorWaitingReset (0.16s) |
| + coordinator_review_test.go:62: reset retained waiting record/card |
| +FAIL |
| +rastrillo-budget/v1 ran 2.131s |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 2.178s |
| +FAIL |
| +``` |
| + |
| +Command (exit 1): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorContext(FinishedDecisionsOptional|AnsweredWorkFinished)$' -count=1 |
| +``` |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextFinishedDecisionsOptional (0.45s) |
| + coordinator_review_test.go:111: finished work permanently blocked conversation The required context is too long for this turn. Reset your coordinator or edit the request and retry. |
| +--- FAIL: TestCoordinatorContextAnsweredWorkFinished (0.20s) |
| + coordinator_review_test.go:127: finished question retained as required decision |
| +FAIL |
| +rastrillo-budget/v1 ran 655ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.698s |
| +FAIL |
| +``` |
| + |
| +Command (exit 1): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner ./internal/plan3test -run '^TestCoordinator(ContextOwnProjectFirst|WaitingWritesOnlyOnChange|RenewalCadence|WaitingObserverChanges)$' -count=1 |
| +``` |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRenewalCadence (1.27s) |
| + coordinator_fix_test.go:104: idle turn renewed too frequently 17 |
| +FAIL |
| +rastrillo-budget/v1 ran 2.474s |
| +FAIL amadan.net/oficina/equipo/internal/runner 2.477s |
| +ok amadan.net/oficina/equipo/internal/plan3test 1.094s |
| +FAIL |
| +``` |
| + |
| +Command (exit 1): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorRefusalContainmentRetry$' -count=1 |
| +``` |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRefusalContainmentRetry (0.03s) |
| + coordinator_fix_test.go:187: delivery refusal made transient containment failure fatal |
| + runner_transient |
| +FAIL |
| +rastrillo-budget/v1 ran 30ms |
| +FAIL amadan.net/oficina/equipo/internal/runner 0.032s |
| +FAIL |
| +``` |
| + |
| +### Guard mutations |
| + |
| +Each mutation below was applied separately, its named test failed with exit 1, and the original implementation was restored immediately. All 19 failures were test assertions, not compile errors. The final green runs below cover the restored code. Mutations of the minor retrieval/cadence/card guards provide their red/restoration evidence as well. |
| + |
| +#### refused-recovery |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRecoveryRefusedKeepsServing$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRecoveryRefusedKeepsServing (0.62s) |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/403 (0.21s) |
| + coordinator_fix_test.go:60: coordinator stopped specialist work: ran=false error= |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/409 (0.21s) |
| + coordinator_fix_test.go:60: coordinator stopped specialist work: ran=false error= |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/422 (0.20s) |
| + coordinator_fix_test.go:60: coordinator stopped specialist work: ran=false error= |
| +FAIL |
| +rastrillo-budget/v1 ran 623ms |
| +FAIL amadan.net/oficina/equipo/internal/runner 0.625s |
| +FAIL |
| +``` |
| + |
| +#### cleanup-containment |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorCleanupRefusalReportsContainment$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorCleanupRefusalReportsContainment (0.25s) |
| + coordinator_fix_test.go:101: cleanup skipped containment after delivery refusal |
| +FAIL |
| +rastrillo-budget/v1 ran 250ms |
| +FAIL amadan.net/oficina/equipo/internal/runner 0.253s |
| +FAIL |
| +``` |
| + |
| +#### specialist-poll |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorPollErrorKeepsServing$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorPollErrorKeepsServing (0.08s) |
| + coordinator_fix_test.go:93: coordinator stopped specialist work: ran=false error=context canceled |
| +FAIL |
| +rastrillo-budget/v1 ran 81ms |
| +FAIL amadan.net/oficina/equipo/internal/runner 0.083s |
| +FAIL |
| +``` |
| + |
| +#### task-uploader |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRecoveryRefusedKeepsServing$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRecoveryRefusedKeepsServing (4.13s) |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/403 (1.38s) |
| + coordinator_fix_test.go:63: refused recovery repeated or missed containment: &{coordinatorAPIStub:0x2df3efd2008 refusal:0x2df3efb8900 contained:1 rejected:0 pollError:<nil>} starts=0 |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/409 (1.37s) |
| + coordinator_fix_test.go:63: refused recovery repeated or missed containment: &{coordinatorAPIStub:0x2df3f28e008 refusal:0x2df3f11f340 contained:1 rejected:0 pollError:<nil>} starts=0 |
| + --- FAIL: TestCoordinatorRecoveryRefusedKeepsServing/422 (1.37s) |
| + coordinator_fix_test.go:63: refused recovery repeated or missed containment: &{coordinatorAPIStub:0x2df3f28e708 refusal:0x2df3efb9940 contained:1 rejected:0 pollError:<nil>} starts=0 |
| +FAIL |
| +rastrillo-budget/v1 ran 4.127s |
| +FAIL amadan.net/oficina/equipo/internal/runner 4.129s |
| +FAIL |
| +``` |
| + |
| +#### park-context-limit |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorContextLimitParked$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextLimitParked (0.51s) |
| + --- FAIL: TestCoordinatorContextLimitParked/retry (0.36s) |
| + coordinator_review_test.go:30: context_limit turn re-offered |
| + --- FAIL: TestCoordinatorContextLimitParked/reset (0.16s) |
| + coordinator_review_test.go:30: context_limit turn re-offered |
| +FAIL |
| +rastrillo-budget/v1 ran 512ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.560s |
| +FAIL |
| +``` |
| + |
| +#### finished-decisions |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorContextFinishedDecisionsOptional$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextFinishedDecisionsOptional (0.45s) |
| + coordinator_review_test.go:190: finished work permanently blocked conversation The required context is too long for this turn. Reset your coordinator or edit the request and retry. |
| +FAIL |
| +rastrillo-budget/v1 ran 453ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.495s |
| +FAIL |
| +``` |
| + |
| +#### required-request |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/coordinator -run ^TestCoordinatorContextRequestRequired$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextRequestRequired (0.00s) |
| + context_fix_test.go:17: admitted request was trimmed <nil> |
| +FAIL |
| +rastrillo-budget/v1 ran 1ms |
| +FAIL amadan.net/oficina/equipo/internal/coordinator 0.003s |
| +FAIL |
| +``` |
| + |
| +#### source-message-count |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorContextFiftySmallMessages$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextFiftySmallMessages (0.71s) |
| + coordinator_review_test.go:96: instance fetched more than 50 messages 61 |
| +FAIL |
| +rastrillo-budget/v1 ran 707ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.749s |
| +FAIL |
| +``` |
| + |
| +#### wire-message-count |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/coordinator -run ^TestCoordinatorContextFiftySmallMessages$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextFiftySmallMessages (0.00s) |
| + context_fix_test.go:28: message count bound lost 60 <nil> |
| +FAIL |
| +rastrillo-budget/v1 ran 0s |
| +FAIL amadan.net/oficina/equipo/internal/coordinator 0.002s |
| +FAIL |
| +``` |
| + |
| +#### reset-waiting |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorWaitingReset$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorWaitingReset (0.37s) |
| + coordinator_review_test.go:113: reset retained waiting record/card |
| +FAIL |
| +rastrillo-budget/v1 ran 368ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.412s |
| +FAIL |
| +``` |
| + |
| +#### release-waiting |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorConnectionWaiting$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorConnectionWaiting (0.42s) |
| + coordinator_continuity_test.go:65: released task retained waiting record before claim |
| +FAIL |
| +rastrillo-budget/v1 ran 421ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.462s |
| +FAIL |
| +``` |
| + |
| +#### unchanged-waiting |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorWaitingWritesOnlyOnChange$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorWaitingWritesOnlyOnChange (0.37s) |
| + coordinator_review_test.go:264: unchanged waiting status wrote again constraint failed: unchanged waiting write (1811) |
| +FAIL |
| +rastrillo-budget/v1 ran 371ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.413s |
| +FAIL |
| +``` |
| + |
| +#### own-project-priority |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorContextOwnProjectFirst$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextOwnProjectFirst (0.76s) |
| + coordinator_review_test.go:248: own project source trimmed before labels |
| +FAIL |
| +rastrillo-budget/v1 ran 764ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.807s |
| +FAIL |
| +``` |
| + |
| +#### renew-cadence |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRenewalCadence$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRenewalCadence (1.35s) |
| + coordinator_fix_test.go:145: idle turn renewed too frequently 6 7 |
| +FAIL |
| +rastrillo-budget/v1 ran 1.352s |
| +FAIL amadan.net/oficina/equipo/internal/runner 1.354s |
| +FAIL |
| +``` |
| + |
| +#### local-watchdog |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRenewalCadence$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRenewalCadence (1.35s) |
| + coordinator_fix_test.go:145: idle turn renewed too frequently 7 18 |
| +FAIL |
| +rastrillo-budget/v1 ran 1.354s |
| +FAIL amadan.net/oficina/equipo/internal/runner 1.356s |
| +FAIL |
| +``` |
| + |
| +#### context-limit-card |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorContextLimitParked$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextLimitParked (0.54s) |
| + --- FAIL: TestCoordinatorContextLimitParked/retry (0.37s) |
| + coordinator_review_test.go:45: context_limit omitted person-visible card |
| + --- FAIL: TestCoordinatorContextLimitParked/reset (0.17s) |
| + coordinator_review_test.go:45: context_limit omitted person-visible card |
| +FAIL |
| +rastrillo-budget/v1 ran 537ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.579s |
| +FAIL |
| +``` |
| + |
| +#### context-limit-retry |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorContextLimitParked$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorContextLimitParked (0.58s) |
| + --- FAIL: TestCoordinatorContextLimitParked/retry (0.38s) |
| + coordinator_review_test.go:51: This record changed. Reload the page and try again. |
| +FAIL |
| +rastrillo-budget/v1 ran 582ms |
| +FAIL amadan.net/oficina/equipo/internal/plan3test 0.627s |
| +FAIL |
| +``` |
| + |
| +#### containment-retry |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRefusalContainmentRetry$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorRefusalContainmentRetry (0.03s) |
| + coordinator_fix_test.go:187: delivery refusal made transient containment failure fatal |
| + runner_transient |
| +FAIL |
| +rastrillo-budget/v1 ran 27ms |
| +FAIL amadan.net/oficina/equipo/internal/runner 0.029s |
| +FAIL |
| +``` |
| + |
| +#### continuity-source-revocation |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner/provider/claude -run ^TestCoordinatorSessionContinuity$ -count=1 |
| +``` |
| + |
| +Exit 1; restored. Exact output: |
| + |
| +```text |
| +--- FAIL: TestCoordinatorSessionContinuity (2.65s) |
| + coordinator_continuity_test.go:10: fresh turn retained revoked context |
| +FAIL |
| +rastrillo-budget/v1 ran 2.649s |
| +FAIL amadan.net/oficina/equipo/internal/runner/provider/claude 2.691s |
| +FAIL |
| +``` |
| + |
| +### Final verification |
| + |
| +Only targeted tests were run. No `make ci`, full suite, live provider run, sign-in or enrolment. The provider adapters ran recorded fixtures. `go vet` and formatting covered all changed packages; package size is within budget. The runner's existing size exception now records 9129 source / 8037 test lines, with unchanged 9300 source and 330-second time ceilings and a measured test ceiling increase to 8200. The first size check failed at 8006 test lines before the final containment-retry test was added; the narrow exception preserves these shared-journal/lease tests beside the runner internals they exercise. |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/coordinator ./internal/runner ./internal/runnerproto ./internal/equipo/conversation ./internal/plan3test -run '^TestCoordinator' -count=1 |
| +``` |
| + |
| +```text |
| +ok amadan.net/oficina/equipo/internal/coordinator 0.028s |
| +ok amadan.net/oficina/equipo/internal/runner 27.384s |
| +ok amadan.net/oficina/equipo/internal/runnerproto 0.004s [no tests to run] |
| +ok amadan.net/oficina/equipo/internal/equipo/conversation 0.003s [no tests to run] |
| +ok amadan.net/oficina/equipo/internal/plan3test 24.207s |
| +``` |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner/provider/claude ./internal/runner/provider/codex -run '^TestCoordinatorSessionContinuity$' -count=1 |
| +``` |
| + |
| +```text |
| +ok amadan.net/oficina/equipo/internal/runner/provider/claude 4.810s |
| +ok amadan.net/oficina/equipo/internal/runner/provider/codex 5.175s |
| +``` |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run '^Test(ServiceSurvivesPollAndAttemptErrors|RunnerLeaseRenewMeasuredAtSend|RunnerEventReplay|RunnerEventDrainBacklog|RunnerJournalCrashBoundaries|DirectJournalUpgrade|DirectCompletionReplay|BlockedJournalDoesNotClaim|JournalResetRequiresReconciliation)$' -count=1 |
| +``` |
| + |
| +```text |
| +ok amadan.net/oficina/equipo/internal/runner 19.590s |
| +``` |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go vet ./internal/coordinator ./internal/runner ./internal/runnerproto ./internal/equipo/conversation ./internal/equipo ./internal/plan3test |
| +``` |
| + |
| +Output: empty. |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +make budget |
| +``` |
| + |
| +```text |
| +go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size |
| +budget size: 30 directories within budget |
| +``` |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +gofmt -l internal/coordinator internal/runner internal/runnerproto internal/equipo/conversation internal/equipo/copy.go internal/plan3test |
| +``` |
| + |
| +Output: empty. |
| + |
| +Command (exit 0): |
| + |
| +```sh |
| +git diff --check |
| +``` |
| + |
| +Output: empty. |
| + |
| +### Copy and remaining boundaries |
| + |
| +Changed pending copy, marked individually `COPY REVIEW REQUIRED` in `internal/equipo/copy.go`: |
| + |
| +| Key | Draft text | |
| +| --- | --- | |
| +| `coordinator.context_limit` | The required context is too long for this turn. Reset your coordinator or edit the request and retry. | |
| + |
| +No other runtime string was introduced or changed. Existing `coordinator.reset`, `coordinator.retry`, `runner.poll_retry` and `runner.recovery_retry` keys are reused. No copy-review server or drafting/reviewer agent was started, following the dispatch's explicit instructions. The report uses the plain-writing/humane-docs guidance; the dispatch's report and pending-copy rules override the general writing/review workflow. |
| + |
| +Self-review checked refusal classification, containment before retirement, shared-journal event ownership, idempotent restart, separate polling, source scope, open-work decision ownership, required-request retention, waiting-card clearing and unchanged-state writes. The existing instance containment transaction supplies uncertainty and unknown-charge preservation; no alternate recovery ledger was introduced. Genuine oversized open-work requirements still stop with context-limit. Production preferences and HTML action rendering remain with Tasks 8 and 9. Live containment/certification remains outside this offline fix, under the existing Plan 2b/3 release restrictions. |
| + |
| +### Files changed |
| + |
| +- `.rastrillo/budgets.txt` |
| +- `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md` |
| +- `internal/coordinator/context_fix_test.go` |
| +- `internal/coordinator/runtime_test.go` |
| +- `internal/equipo/conversation/context.go` |
| +- `internal/equipo/conversation/context_decisions.go` |
| +- `internal/equipo/conversation/coordinator.go` |
| +- `internal/equipo/conversation/coordinator_application.go` |
| +- `internal/equipo/conversation/coordinator_execution.go` |
| +- `internal/equipo/conversation/coordinator_poll.go` |
| +- `internal/equipo/conversation/coordinator_recovery.go` |
| +- `internal/equipo/conversation/models.go` |
| +- `internal/equipo/conversation/store.go` |
| +- `internal/equipo/copy.go` |
| +- `internal/plan3test/coordinator_continuity_fixture.go` |
| +- `internal/plan3test/coordinator_continuity_test.go` |
| +- `internal/plan3test/coordinator_instance_fixture.go` |
| +- `internal/plan3test/coordinator_review_test.go` |
| +- `internal/plan3test/coordinator_test.go` |
| +- `internal/plan3test/harness_fixture.go` |
| +- `internal/plan3test/harness_test.go` |
| +- `internal/plan3test/plans_approval_test.go` |
| +- `internal/runner/coordinator_fix_test.go` |
| +- `internal/runner/coordinator_recovery.go` |
| +- `internal/runner/coordinator_runtime_test.go` |
| +- `internal/runner/coordinator_service.go` |
| +- `internal/runner/coordinator_tool_proxy.go` |
| +- `internal/runner/journal.go` |
| +- `internal/runner/service.go` |
| +- `internal/runner/supervisor.go` |
| +- `internal/runnerproto/coordinator_prompt.go` |
| + |
| +Full report destination: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-7-report.md` (ignored by Git). The same fix-round section is appended under Task 7 in the tracked controller report. All guard mutations were restored. No agents, `.claude/HANDOFF.md`, servers, push, merge or deployment. Go caches stayed at their defaults. Task scratch was created only under `$TMPDIR/equipo-task7-fix` and is removed after its evidence is copied into these reports. Fixture processes and endpoints close through test cleanup. |
diff --git a/internal/coordinator/context_fix_test.go b/internal/coordinator/context_fix_test.go| new file mode 100644 |
| index 00000000..fb559a45 |
| --- /dev/null |
| +++ b/internal/coordinator/context_fix_test.go |
| @@ -0,0 +1,30 @@ |
| +package coordinator |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "errors" |
| + "fmt" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestCoordinatorContextRequestRequired(t *testing.T) { |
| + for _, body := range []string{strings.Repeat("\x00", 16000), strings.Repeat("x", 16000)} { |
| + c := contextFixture() |
| + c.ConfirmedDecisions[0].Text = strings.Repeat("d", 40000) |
| + c.Recent = []runnerproto.MessageRef{{ID: "request", Body: body}} |
| + if _, err := runnerproto.BoundCoordinatorContext(c); !errors.Is(err, runnerproto.ErrPromptTooLarge) { |
| + t.Fatal("admitted request was trimmed", err) |
| + } |
| + } |
| +} |
| +func TestCoordinatorContextFiftySmallMessages(t *testing.T) { |
| + c := contextFixture() |
| + for i := 0; i < 60; i++ { |
| + c.Recent = append(c.Recent, runnerproto.MessageRef{ID: fmt.Sprint(i), Body: "small"}) |
| + } |
| + got, err := runnerproto.BoundCoordinatorContext(c) |
| + if err != nil || len(got.Recent) != 50 || got.Recent[0].ID != "10" || got.Recent[49].ID != "59" { |
| + t.Fatal("message count bound lost", len(got.Recent), err) |
| + } |
| +} |
diff --git a/internal/coordinator/runtime_test.go b/internal/coordinator/runtime_test.go| index aa6335c6..d5aab0a9 100644 |
| --- a/internal/coordinator/runtime_test.go |
| +++ b/internal/coordinator/runtime_test.go |
| @@ -67,8 +67,8 @@ func TestCoordinatorContextBounds(t *testing.T) { |
| c = contextFixture() |
| c.Recent = []runnerproto.MessageRef{{Body: strings.Repeat("\x00", 16000)}} |
| bounded, err = runnerproto.BoundCoordinatorContext(c) |
| - if err != nil || len(bounded.Recent) != 0 { |
| - t.Fatal("escaped optional history not trimmed", err) |
| + if !errors.Is(err, runnerproto.ErrPromptTooLarge) { |
| + t.Fatal("escaped admitted request was trimmed", err) |
| } |
| c = contextFixture() |
| c.Retrieved = []runnerproto.ContextRef{{Text: strings.Repeat("x", 48<<10)}} |
diff --git a/internal/equipo/conversation/context.go b/internal/equipo/conversation/context.go| index 8b7ad03c..d6ba0406 100644 |
| --- a/internal/equipo/conversation/context.go |
| +++ b/internal/equipo/conversation/context.go |
| @@ -52,6 +52,9 @@ func (s *Store) CoordinatorContext(ctx context.Context, c CoordinatorClaim) (Coo |
| } |
| out.Recent = append(out.Recent, runnerproto.MessageRef{ID: m.ID, AuthorKind: m.AuthorKind, Body: m.Body, Sequence: m.Sequence, Revision: m.Revision}) |
| } |
| + if len(out.Recent) == 0 || out.Recent[len(out.Recent)-1].ID != admitted.ID { |
| + return out, runnerproto.ErrInvalid |
| + } |
| if s.deps.ContextSource != nil { |
| var err error |
| out.Instructions, out.ConfirmedDecisions, out.ConfirmedPreferences, out.Retrieved, err = s.deps.ContextSource(ctx, s.tx, c) |
| @@ -141,10 +144,6 @@ func (e *Engine) contextSource(ctx context.Context, tx *gorm.DB, c CoordinatorCl |
| err = e2 |
| return |
| } |
| - for _, p := range projects { |
| - raw, _ := json.Marshal(p) |
| - retrieved = append(retrieved, contextRef("project_label", strconv.FormatInt(p.ID, 10), p.Revision, string(raw))) |
| - } |
| if row.ProjectID > 0 { |
| var source runnerproto.SourceSnapshot |
| _, source, err = e.Project(tx, c.Binding.Person, row.ProjectID, c.Brief.Selection) |
| @@ -155,52 +154,13 @@ func (e *Engine) contextSource(ctx context.Context, tx *gorm.DB, c CoordinatorCl |
| source.Ref.Hash = team.ContentDigest(source.Payload) |
| retrieved = append(retrieved, runnerproto.ContextRef{Source: source.Ref, Text: string(source.Payload)}) |
| } |
| - var answers []struct { |
| - ID, Body string |
| - Revision int64 |
| - ProjectID int64 |
| - } |
| - err = tx.Table("coordinator_questions q").Select("q.id,m.body,q.revision,t.project_id").Joins("JOIN coordinator_turns t ON t.id=q.turn_id").Joins("JOIN conversation_requests r ON r.resource=q.id AND r.operation='clarification.answer' AND r.principal=q.person").Joins("JOIN conversation_messages m ON m.id=json_extract(r.result,'$.MessageID')").Where("q.person=? AND t.conversation_id=? AND q.state='answered'", c.Binding.Person, row.ConversationID).Order("q.id").Limit(1001).Scan(&answers).Error |
| - if err != nil { |
| - return |
| - } |
| - if len(answers) > 1000 { |
| - err = runnerproto.ErrPromptTooLarge |
| - return |
| - } |
| - for _, a := range answers { |
| - if a.ProjectID > 0 { |
| - if _, er := e.CheckProject(tx, c.Binding.Person, a.ProjectID, c.Brief.Selection); er != nil { |
| - _, err = e.contextDenied(er) |
| - if err != nil { |
| - return |
| - } |
| - continue |
| - } |
| - } |
| - decisions = append(decisions, contextRef("answer", a.ID, a.Revision, a.Body)) |
| - } |
| - var approvals []struct { |
| - ID, Plan string |
| - ProjectID, Revision int64 |
| - } |
| - err = tx.Table("tasks t").Select("t.id,p.plan,t.project_id,p.revision").Joins("JOIN plan_revisions p ON p.task_id=t.id AND p.revision=t.approval_revision").Where("t.requester=? AND t.team_id=? AND t.approval_revision=t.plan_revision AND EXISTS (SELECT 1 FROM plan_requests r WHERE r.resource=t.id AND r.operation='plan.approve' AND r.principal=? AND json_extract(r.result,'$.ApprovalRevision')=t.approval_revision AND json_extract(r.result,'$.PlanRevision')=t.plan_revision)", c.Binding.Person, row.TeamID, c.Binding.Person).Order("t.id").Limit(1001).Scan(&approvals).Error |
| - if err != nil { |
| - return |
| - } |
| - if len(approvals) > 1000 { |
| - err = runnerproto.ErrPromptTooLarge |
| - return |
| - } |
| - for _, a := range approvals { |
| - if _, er := e.CheckProject(tx, c.Binding.Person, a.ProjectID, c.Brief.Selection); er != nil { |
| - _, err = e.contextDenied(er) |
| - if err != nil { |
| - return |
| - } |
| - continue |
| - } |
| - decisions = append(decisions, contextRef("plan_approval", a.ID, a.Revision, a.Plan)) |
| + for _, p := range projects { |
| + raw, _ := json.Marshal(p) |
| + retrieved = append(retrieved, contextRef("project_label", strconv.FormatInt(p.ID, 10), p.Revision, string(raw))) |
| } |
| + var current, past []runnerproto.ContextRef |
| + current, past, err = e.contextDecisions(tx, c, row) |
| + decisions = append(decisions, current...) |
| + retrieved = append(retrieved, past...) |
| return |
| } |
diff --git a/internal/equipo/conversation/context_decisions.go b/internal/equipo/conversation/context_decisions.go| new file mode 100644 |
| index 00000000..69f0955a |
| --- /dev/null |
| +++ b/internal/equipo/conversation/context_decisions.go |
| @@ -0,0 +1,77 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// A published candidate still awaits its person. A delivered recommendation is |
| +// terminal; a successful investigation may still await its next plan. |
| +const contextOpenWork = `w.state NOT IN ('merged','cancelled','failed','completed') |
| + AND COALESCE(j.state,'') NOT IN ('cancelled','failed') |
| + AND NOT (w.kind='recommendation' AND COALESCE(j.state,'')='succeeded')` |
| + |
| +// Answers follow the work created from, or explicitly attached to, their request. |
| +// Until that work exists, the answer's pending follow-up owns the decision. |
| +const contextAnswerOpen = `COALESCE((SELECT MAX(CASE WHEN ` + contextOpenWork + ` THEN 1 ELSE 0 END) |
| + FROM tasks w LEFT JOIN jobs j ON j.id=w.job_id |
| + WHERE w.team_id=t.team_id AND w.id IN ( |
| + SELECT task_id FROM conversation_routes WHERE source_id IN (json_extract(q.payload,'$.MessageID'),m.id) |
| + UNION SELECT json_extract(cr.result,'$.resource_id') FROM conversation_requests cr |
| + WHERE cr.principal=q.person AND cr.operation='coordinator.tool' |
| + AND json_extract(cr.result,'$.value.message_id') IN (json_extract(q.payload,'$.MessageID'),m.id))), |
| + EXISTS(SELECT 1 FROM coordinator_turns followup WHERE followup.id=json_extract(r.result,'$.TurnID') |
| + AND followup.generation=? AND followup.state NOT IN ('delivered','superseded')) |
| + OR EXISTS(SELECT 1 FROM coordinator_questions pending WHERE pending.binding_id=q.binding_id |
| + AND pending.generation=? AND pending.state='pending' |
| + AND json_extract(pending.payload,'$.MessageID')=json_extract(q.payload,'$.MessageID')))` |
| + |
| +type contextDecision struct { |
| + ID, Body string |
| + Revision, ProjectID int64 |
| +} |
| + |
| +func (e *Engine) contextDecisions(tx *gorm.DB, c CoordinatorClaim, row TurnRecord) (required, optional []runnerproto.ContextRef, err error) { |
| + answers := tx.Table("coordinator_questions q").Select("q.id,m.body,q.revision,t.project_id").Joins("JOIN coordinator_turns t ON t.id=q.turn_id").Joins("JOIN conversation_requests r ON r.resource=q.id AND r.operation='clarification.answer' AND r.principal=q.person").Joins("JOIN conversation_messages m ON m.id=json_extract(r.result,'$.MessageID')").Where("q.person=? AND t.conversation_id=? AND q.state='answered'", c.Binding.Person, row.ConversationID) |
| + approvals := tx.Table("tasks w").Select("w.id,p.plan AS body,w.project_id,p.revision").Joins("LEFT JOIN jobs j ON j.id=w.job_id").Joins("JOIN plan_revisions p ON p.task_id=w.id AND p.revision=w.approval_revision").Where("w.requester=? AND w.team_id=? AND w.approval_revision=w.plan_revision AND EXISTS (SELECT 1 FROM plan_requests r WHERE r.resource=w.id AND r.operation='plan.approve' AND r.principal=? AND json_extract(r.result,'$.ApprovalRevision')=w.approval_revision AND json_extract(r.result,'$.PlanRevision')=w.plan_revision)", c.Binding.Person, row.TeamID, c.Binding.Person) |
| + for _, open := range []bool{true, false} { |
| + limit := 50 |
| + if open { |
| + limit = 1001 |
| + } |
| + for _, source := range []struct { |
| + kind string |
| + query *gorm.DB |
| + }{ |
| + {"answer", answers.Session(&gorm.Session{}).Where("("+contextAnswerOpen+") = ?", c.Binding.Generation, c.Binding.Generation, open).Order("m.sequence DESC,q.id")}, |
| + {"plan_approval", approvals.Session(&gorm.Session{}).Where("("+contextOpenWork+") = ?", open).Order("p.created_at DESC,w.id")}, |
| + } { |
| + var rows []contextDecision |
| + if err = source.query.Limit(limit).Scan(&rows).Error; err != nil { |
| + return |
| + } |
| + if open && len(rows) > 1000 { |
| + err = runnerproto.ErrPromptTooLarge |
| + return |
| + } |
| + for _, a := range rows { |
| + if a.ProjectID > 0 { |
| + if _, checkErr := e.CheckProject(tx, c.Binding.Person, a.ProjectID, c.Brief.Selection); checkErr != nil { |
| + _, err = e.contextDenied(checkErr) |
| + if err != nil { |
| + return |
| + } |
| + continue |
| + } |
| + } |
| + ref := contextRef(source.kind, a.ID, a.Revision, a.Body) |
| + if open { |
| + required = append(required, ref) |
| + } else { |
| + optional = append(optional, ref) |
| + } |
| + } |
| + } |
| + } |
| + return |
| +} |
diff --git a/internal/equipo/conversation/coordinator.go b/internal/equipo/conversation/coordinator.go| index 4c6af981..7a9610b4 100644 |
| --- a/internal/equipo/conversation/coordinator.go |
| +++ b/internal/equipo/conversation/coordinator.go |
| @@ -160,16 +160,22 @@ func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutatio |
| if err = s.tx.Where("id=? AND person=? AND team_id=?", id, actor.Address, b.TeamID).First(&old).Error; err != nil { |
| return out, err |
| } |
| - if old.Revision != m.Revision || old.State != "uncertain" || old.AttemptID == 0 { |
| + if old.Revision != m.Revision { |
| return out, s.deps.Conflict |
| } |
| - var n int64 |
| - if err = s.tx.Table("attempts").Where("id=? AND containment='contained'", old.AttemptID).Count(&n).Error; err != nil { |
| - return out, err |
| - } |
| - if n != 1 { |
| - return out, s.deps.Conflict |
| + if old.State != "context_limit" { |
| + if old.State != "uncertain" || old.AttemptID == 0 { |
| + return out, s.deps.Conflict |
| + } |
| + var n int64 |
| + if err = s.tx.Table("attempts").Where("id=? AND containment='contained'", old.AttemptID).Count(&n).Error; err != nil { |
| + return out, err |
| + } |
| + if n != 1 { |
| + return out, s.deps.Conflict |
| + } |
| } |
| + |
| if old.Revision == math.MaxInt64 { |
| return out, s.deps.Conflict |
| } |
| @@ -186,3 +192,14 @@ func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutatio |
| } |
| return row.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.retry", id, m, input, row.CoordinatorTurn) |
| } |
| + |
| +func (s *Store) clearCoordinatorWaiting(b BindingRecord) error { |
| + var n int64 |
| + if err := s.tx.Model(&requestRecord{}).Where("principal=? AND operation='coordinator.waiting' AND resource=?", b.Person, b.ID).Count(&n).Error; err != nil || n == 0 { |
| + return err |
| + } |
| + if err := s.tx.Where("principal=? AND operation='coordinator.waiting' AND resource=?", b.Person, b.ID).Delete(&requestRecord{}).Error; err != nil { |
| + return err |
| + } |
| + return s.tx.Model(&Main{}).Where("person=? AND team_id=?", b.Person, b.TeamID).Select("revision").Updates(map[string]any{"revision": gorm.Expr("revision+1")}).Error |
| +} |
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go| index 401d59f4..ae942161 100644 |
| --- a/internal/equipo/conversation/coordinator_application.go |
| +++ b/internal/equipo/conversation/coordinator_application.go |
| @@ -105,6 +105,10 @@ func (s *Application) changeCoordinator(ctx context.Context, actor Actor, runner |
| } |
| } |
| } |
| + if err = cs.clearCoordinatorWaiting(b); err != nil { |
| + return err |
| + } |
| + b.WaitingTaskID, b.WaitingTaskURL = "", "" |
| if pending { |
| return s.Audit(tx, actor, op+".containment", b.ID) |
| } |
| @@ -130,7 +134,7 @@ func (s *Application) changeCoordinator(ctx context.Context, actor Actor, runner |
| if err != nil { |
| return err |
| } |
| - if err = tx.Model(&TurnRecord{}).Where("binding_id=? AND state IN ('queued','waiting_connection','waiting_task','budget_needed')", b.ID).Select("state", "revision").Updates(map[string]any{"state": "superseded", "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| + if err = tx.Model(&TurnRecord{}).Where("binding_id=? AND state IN ('queued','waiting_connection','waiting_task','budget_needed','context_limit')", b.ID).Select("state", "revision").Updates(map[string]any{"state": "superseded", "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| return err |
| } |
| result = b.CoordinatorBinding |
diff --git a/internal/equipo/conversation/coordinator_execution.go b/internal/equipo/conversation/coordinator_execution.go| index 7dbfc2f2..a9480054 100644 |
| --- a/internal/equipo/conversation/coordinator_execution.go |
| +++ b/internal/equipo/conversation/coordinator_execution.go |
| @@ -39,7 +39,7 @@ func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID |
| _, err = e.Core.AdmitOnce(ctx, result.Scope, result.Handle, result.Admission.Dispatch.Action, row.RequestID) |
| return err |
| } |
| - if row.State != "queued" && row.State != "waiting_connection" && row.State != "waiting_task" && row.State != "budget_needed" && row.State != "context_limit" { |
| + if row.State != "queued" && row.State != "waiting_connection" && row.State != "waiting_task" && row.State != "budget_needed" { |
| return e.Conflict |
| } |
| blocked, err := coordinatorBlocked(tx, row) |
diff --git a/internal/equipo/conversation/coordinator_poll.go b/internal/equipo/conversation/coordinator_poll.go| index a5259325..81b6468b 100644 |
| --- a/internal/equipo/conversation/coordinator_poll.go |
| +++ b/internal/equipo/conversation/coordinator_poll.go |
| @@ -29,6 +29,17 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| if b.RunnerID != p.RunnerID { |
| return nil |
| } |
| + if b.WaitingTaskID != "" { |
| + var busy int64 |
| + if err = tx.Table("runner_assignments").Where("task_id=? AND person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", b.WaitingTaskID, p.Person, b.ConnectionID).Count(&busy).Error; err != nil { |
| + return err |
| + } |
| + if busy == 0 { |
| + if err = e.Conversation(tx).clearCoordinatorWaiting(b); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| var messages []struct{ ID string } |
| if err = tx.Table("conversation_messages m").Select("m.id").Joins("JOIN conversations c ON c.id=m.conversation_id").Where("c.person=? AND c.team_id=? AND m.author_kind='person' AND NOT EXISTS (SELECT 1 FROM coordinator_turns t WHERE t.message_id=m.id AND t.state<>'superseded')", p.Person, b.TeamID).Order("m.sequence").Limit(50).Scan(&messages).Error; err != nil { |
| return err |
| @@ -43,7 +54,7 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| return err |
| } |
| for _, row := range rows { |
| - if row.State == "running" || row.State == "uncertain" { |
| + if row.State == "running" || row.State == "uncertain" || row.State == "context_limit" { |
| continue |
| } |
| blocked, err := coordinatorBlocked(tx, row) |
| @@ -67,6 +78,9 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| if busy > 0 { |
| return e.waitCoordinator(tx, b, row, "waiting_task") |
| } |
| + if err = e.Conversation(tx).clearCoordinatorWaiting(b); err != nil { |
| + return err |
| + } |
| if err = e.Core.CoordinatorAvailable(ctx, team.AccountID(b.TeamID), p.Person); err != nil { |
| if errors.Is(err, team.ErrBudget) { |
| return e.waitCoordinator(tx, b, row, "budget_needed") |
| @@ -93,11 +107,20 @@ func (e *Engine) waitCoordinator(tx *gorm.DB, b BindingRecord, row TurnRecord, s |
| return err |
| } |
| } |
| - wait := requestRecord{Principal: row.Person, Operation: "coordinator.waiting", Resource: b.ID, RequestID: "current", Result: string(mustCoordinatorJSON(taskID))} |
| - if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "principal"}, {Name: "operation"}, {Name: "resource"}, {Name: "request_id"}}, DoUpdates: clause.AssignmentColumns([]string{"result"})}).Create(&wait).Error; err != nil { |
| + var prior requestRecord |
| + err := tx.Where("principal=? AND operation='coordinator.waiting' AND resource=? AND request_id='current'", row.Person, b.ID).First(&prior).Error |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| return err |
| } |
| - if row.State == state { |
| + result := string(mustCoordinatorJSON(taskID)) |
| + changed := err != nil || prior.Result != result |
| + if changed { |
| + wait := requestRecord{Principal: row.Person, Operation: "coordinator.waiting", Resource: b.ID, RequestID: "current", Result: result} |
| + if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "principal"}, {Name: "operation"}, {Name: "resource"}, {Name: "request_id"}}, DoUpdates: clause.AssignmentColumns([]string{"result"})}).Create(&wait).Error; err != nil { |
| + return err |
| + } |
| + } |
| + if row.State == state && !changed { |
| return nil |
| } |
| if err := tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": state}).Error; err != nil { |
diff --git a/internal/equipo/conversation/coordinator_recovery.go b/internal/equipo/conversation/coordinator_recovery.go| index 7337be63..39c6b41d 100644 |
| --- a/internal/equipo/conversation/coordinator_recovery.go |
| +++ b/internal/equipo/conversation/coordinator_recovery.go |
| @@ -45,7 +45,10 @@ func (e *Engine) CoordinatorToolResult(ctx context.Context, p RunnerPrincipal, c |
| if err != nil { |
| return err |
| } |
| - args, _ := coordinator.Validate(canonical) |
| + args, err := coordinator.Validate(canonical) |
| + if err != nil { |
| + return err |
| + } |
| if err = e.toolScope(tx, e.Conversation(tx), row, c.Brief.Selection, args); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/conversation/models.go b/internal/equipo/conversation/models.go| index 3092743d..26be796e 100644 |
| --- a/internal/equipo/conversation/models.go |
| +++ b/internal/equipo/conversation/models.go |
| @@ -14,7 +14,8 @@ type Message struct { |
| CreatedAt time.Time |
| } |
| type Card struct { |
| - CopyKey, WaitingTaskID, WaitingTaskURL string `json:",omitempty"` |
| + ActionKeys []string `json:",omitempty"` |
| + CopyKey, WaitingTaskID, WaitingTaskURL string `json:",omitempty"` |
| ID, Kind, ResourceID string |
| Revision int64 |
| } |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index 62565546..d763802d 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -64,6 +64,13 @@ func (s *Store) Conversation(actor kernel.Actor, cursor string, limit int) (Conv |
| if b.WaitingTaskID != "" { |
| page.Cards = append(page.Cards, Card{ID: b.ID, Kind: "coordinator", ResourceID: b.ID, Revision: page.Revision, CopyKey: "coordinator.waiting_task", WaitingTaskID: b.WaitingTaskID, WaitingTaskURL: b.WaitingTaskURL}) |
| } |
| + var limited []TurnRecord |
| + if err = s.tx.Where("binding_id=? AND generation=? AND state='context_limit'", b.ID, b.Generation).Order("sequence").Limit(1).Find(&limited).Error; err != nil { |
| + return page, err |
| + } |
| + for _, turn := range limited { |
| + page.Cards = append(page.Cards, Card{ID: turn.ID, Kind: "coordinator", ResourceID: turn.ID, Revision: turn.Revision, CopyKey: "coordinator.context_limit", ActionKeys: []string{"coordinator.reset", "coordinator.retry"}}) |
| + } |
| return page, nil |
| } |
| func (s *Store) SendMessage(actor kernel.Actor, threadID, body string, m kernel.Mutation) (Message, error) { |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 7890d75f..dbdd0f54 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -245,7 +245,7 @@ var runnerDraftCopy = map[string]string{ |
| // COPY REVIEW REQUIRED: coordinator.waiting_task |
| "coordinator.waiting_task": "Waiting for %s", |
| // COPY REVIEW REQUIRED: coordinator.context_limit |
| - "coordinator.context_limit": "The required context is too long for this turn.", |
| + "coordinator.context_limit": "The required context is too long for this turn. Reset your coordinator or edit the request and retry.", |
| // COPY REVIEW REQUIRED: tool.acceptance |
| "tool.acceptance": "Submit acceptance tests for the requested behaviour. Encode file bytes as base64. Reuse the request ID only for an identical retry.", |
| // COPY REVIEW REQUIRED: tool.answer |
diff --git a/internal/plan3test/coordinator_continuity_fixture.go b/internal/plan3test/coordinator_continuity_fixture.go| index cd108c03..2baeed78 100644 |
| --- a/internal/plan3test/coordinator_continuity_fixture.go |
| +++ b/internal/plan3test/coordinator_continuity_fixture.go |
| @@ -13,6 +13,7 @@ import ( |
| "testing" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| @@ -129,6 +130,25 @@ func RunCoordinatorSessionContinuity(t *testing.T, name string, factory Continui |
| var source provider.Binding |
| var prior string |
| var prompts []string |
| + f, instance, principal, binding := coordinatorFixture(t) |
| + if name != binding.ConnectionID { |
| + _, err := f.Store.SaveCoordinatorBinding(ctx, owner, principal.RunnerID, name, equipo.Mutation{RequestID: "fixture-provider", Revision: binding.Revision}) |
| + must(t, err) |
| + } |
| + t.Cleanup(schema.Remove) |
| + f.exec(t, "UPDATE projects SET name='revoked source'") |
| + var revokedProject int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&revokedProject)) |
| + retained := equipo.Project{Name: "current scoped source", Repository: "amadan.net/test/retained", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| + must(t, f.DB.G.Create(&retained).Error) |
| + f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude","codex"]','claude')`, owner.Address, retained.ID) |
| + f.exec(t, "INSERT INTO tasks(id,requester,request_id,project_id,team_id,state,kind,plan_revision,approval_revision,revision) VALUES('confirmed-work',?,'confirmed-work',?,?,'proposed','bug',1,1,1)", owner.Address, retained.ID, f.TeamID) |
| + f.exec(t, "INSERT INTO plan_revisions(task_id,revision,plan) VALUES('confirmed-work',1,'confirmed decision')") |
| + f.exec(t, `INSERT INTO plan_requests(principal,operation,resource,request_id,result) VALUES(?,'plan.approve','confirmed-work','approved','{"ApprovalRevision":1,"PlanRevision":1}')`, owner.Address) |
| + f.exec(t, "UPDATE connection_choices SET pinned_id=?", name) |
| + f.exec(t, "CREATE TABLE fixture_preferences(id TEXT PRIMARY KEY,text TEXT)") |
| + f.exec(t, "INSERT INTO fixture_preferences VALUES('pref','deleted preference')") |
| + var conversationID string |
| for i := 0; i < 2; i++ { |
| if i == 1 { |
| credential := "auth.json" |
| @@ -158,15 +178,40 @@ func RunCoordinatorSessionContinuity(t *testing.T, name string, factory Continui |
| } |
| c := runnerproto.CoordinatorClaim{Binding: runnerproto.CoordinatorBinding{ID: "binding", Person: "person", Generation: 1}, Turn: runnerproto.CoordinatorTurn{ID: fmt.Sprint(i), Revision: 1, Generation: 1}, Scope: team.Scope{Account: "team", Job: team.JobID(i + 1)}, Handle: team.Handle{Attempt: team.AttemptID(i + 1), Fence: 1, Runner: "runner"}, LeaseDeadline: time.Now().Add(time.Minute), AttemptDeadline: time.Now().Add(time.Minute)} |
| c.Brief.Selection = runnerproto.Selection{Provider: launch.Selection.Provider, Model: launch.Selection.Model, Family: launch.Selection.Family, AccountID: launch.Selection.AccountID, Isolation: team.IsolationSnapshot{Status: "confined"}} |
| - contextValue := runnerproto.CoordinatorContext{ConversationID: "same-conversation", Revision: int64(i + 1), Recent: []runnerproto.MessageRef{{ID: "message", AuthorKind: "person", Body: "bounded recent history", Sequence: 1, Revision: 1}}, ConfirmedDecisions: []runnerproto.ContextRef{{Source: team.SourceRef{Kind: "answer", ID: "answer", Revision: 1, Hash: team.ContentDigest([]byte("confirmed decision"))}, Text: "confirmed decision"}}} |
| + if i == 1 { |
| + f.exec(t, "DELETE FROM fixture_preferences WHERE id='pref'") |
| + other := "codex" |
| + if name == "codex" { |
| + other = "claude" |
| + } |
| + choices, err := json.Marshal([]string{other}) |
| + must(t, err) |
| + f.exec(t, "UPDATE connection_choices SET connection_ids_json=?,pinned_id=? WHERE project_id=?", string(choices), other, revokedProject) |
| + } |
| + turn := queueCoordinator(t, f, "bounded recent history", fmt.Sprint(i)) |
| + claim, err := instance.ClaimCoordinator(ctx, principal, turn.ID, turn.Revision) |
| + must(t, err) |
| + contextValue := claim.Context |
| if i == 0 { |
| - contextValue.ConfirmedPreferences = []runnerproto.ContextRef{{Source: team.SourceRef{Kind: "preference", ID: "pref", Revision: 1, Hash: team.ContentDigest([]byte("deleted preference"))}, Text: "deleted preference"}} |
| - contextValue.Retrieved = []runnerproto.ContextRef{{Source: team.SourceRef{Kind: "project", ID: "project", Revision: 1, Hash: team.ContentDigest([]byte("revoked source"))}, Text: "revoked source"}} |
| + conversationID = contextValue.ConversationID |
| } |
| - c.Context, err = runnerproto.BoundCoordinatorContext(contextValue) |
| - if err != nil { |
| - t.Fatal(err) |
| + if contextValue.ConversationID != conversationID { |
| + t.Fatal("instance replaced conversation") |
| + } |
| + // Task 8 supplies the production preference table. This fixture source is |
| + // read afresh from the instance database after deletion, never hand-trimmed. |
| + var prefs []struct{ ID, Text string } |
| + must(t, f.DB.G.Table("fixture_preferences").Find(&prefs).Error) |
| + for _, pref := range prefs { |
| + contextValue.ConfirmedPreferences = append(contextValue.ConfirmedPreferences, runnerproto.ContextRef{Source: team.SourceRef{Kind: "preference", ID: pref.ID, Revision: 1, Hash: team.ContentDigest([]byte(pref.Text))}, Text: pref.Text}) |
| } |
| + c.Context, err = runnerproto.BoundCoordinatorContext(contextValue) |
| + must(t, err) |
| + // The real instance snapshot is now complete; provider fixture I/O supplies |
| + // the runner's ticket/session identities independently below. |
| + f.exec(t, "UPDATE coordinator_turns SET state='delivered' WHERE id=?", turn.ID) |
| + instance.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + must(t, instance.ContainCoordinator(ctx, principal, claim, runnerproto.ContainmentProof{Scope: claim.Scope, Handle: claim.Handle})) |
| c.Turn.ContextHash = c.Context.Hash |
| c.Admission = team.AdmissionTicket{Scope: c.Scope, Handle: c.Handle, Dispatch: team.Dispatch{Action: team.ActionID(i + 1)}, ExpiresAt: time.Now().Add(5 * time.Second), Incarnation: 1} |
| api := &continuityAPI{claim: c} |
| @@ -226,9 +271,12 @@ func RunCoordinatorSessionContinuity(t *testing.T, name string, factory Continui |
| } |
| } |
| for i, prompt := range prompts { |
| - if !strings.Contains(prompt, "same-conversation") || !strings.Contains(prompt, "bounded recent history") || !strings.Contains(prompt, "confirmed decision") { |
| + if !strings.Contains(prompt, conversationID) || !strings.Contains(prompt, "bounded recent history") || !strings.Contains(prompt, "confirmed decision") || !strings.Contains(prompt, "current scoped source") { |
| t.Fatal("fresh prompt lost instance context") |
| } |
| + if i == 0 && (!strings.Contains(prompt, "deleted preference") || !strings.Contains(prompt, "revoked source")) { |
| + t.Fatal("first snapshot omitted fixture preference/source") |
| + } |
| if i == 1 && (strings.Contains(prompt, "deleted preference") || strings.Contains(prompt, "revoked source")) { |
| t.Fatal("fresh turn retained revoked context") |
| } |
diff --git a/internal/plan3test/coordinator_continuity_test.go b/internal/plan3test/coordinator_continuity_test.go| index d377be9e..581cb892 100644 |
| --- a/internal/plan3test/coordinator_continuity_test.go |
| +++ b/internal/plan3test/coordinator_continuity_test.go |
| @@ -59,6 +59,11 @@ func TestCoordinatorConnectionWaiting(t *testing.T) { |
| if len(turns) != 1 || turns[0].ID != second.ID { |
| t.Fatal("released home lost queued turn") |
| } |
| + status, err = f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + if status.WaitingTaskID != "" || f.count(t, "SELECT count(*) FROM conversation_requests WHERE operation='coordinator.waiting'") != 0 { |
| + t.Fatal("released task retained waiting record before claim") |
| + } |
| next, err := x.ClaimCoordinator(ctx, p, second.ID, second.Revision) |
| must(t, err) |
| if next.Handle.Attempt == c.Handle.Attempt || next.Binding.ID != b.ID { |
diff --git a/internal/plan3test/coordinator_instance_fixture.go b/internal/plan3test/coordinator_instance_fixture.go| new file mode 100644 |
| index 00000000..5295fc00 |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_instance_fixture.go |
| @@ -0,0 +1,52 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func coordinatorFixture(t *testing.T) (*fixture, *equipo.Execution, equipo.RunnerPrincipal, equipo.CoordinatorBinding) { |
| + f := newFixture(t) |
| + task := f.createTask(t) |
| + f.planConnections(t, task.ProjectID) |
| + var path string |
| + must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| + x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil), Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: f.Store.RunnerAdapter(team.OpProviderCall)}}) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, x.Core.Close()) }) |
| + _, err = x.Core.Resume(ctx) |
| + must(t, err) |
| + f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('fixture-credential','fixture-runner',?,?,?,'','fixture-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC()) |
| + p := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| + must(t, f.Store.SetCoordinatorLimits(ctx, owner, owner.Address, team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}, equipo.Mutation{RequestID: "limits"})) |
| + b, err := f.Store.SaveCoordinatorBinding(ctx, owner, p.RunnerID, "claude", equipo.Mutation{RequestID: "bind"}) |
| + must(t, err) |
| + return f, x, p, b |
| +} |
| +func queueCoordinator(t *testing.T, f *fixture, body, key string) equipo.CoordinatorTurn { |
| + t.Helper() |
| + msg, err := f.Store.SendMessage(ctx, owner, "", body, equipo.Mutation{RequestID: key}) |
| + must(t, err) |
| + turn, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: key}) |
| + must(t, err) |
| + return turn |
| +} |
| +func (f *fixture) planConnections(t *testing.T, project int64) { |
| + t.Helper() |
| + var tuples []team.IsolationTuple |
| + f.exec(t, "INSERT INTO runners(id,person,instance_id,revision) VALUES('fixture-runner',?,?,1)", owner.Address, f.TeamID) |
| + for _, v := range []struct{ provider, family, version string }{{"claude", "claude", "2.1.312"}, {"codex", "gpt", "0.165.0"}} { |
| + r := equipo.ConnectionReport{LocalID: v.provider, Provider: v.provider, Family: v.family, Model: "fixture-model", ProviderVersion: v.version, LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: "policy-v2", Kind: "subscription", Available: true, ReadIsolation: true, IsolationConfigHash: strings.Repeat("a", 64), Routing: equipo.ConnectionRouting{BindingID: v.provider, AccountID: v.provider, ObservedAccountID: v.provider, CredentialHomeHash: strings.Repeat("b", 64), AccountPinned: true, NoFailover: true, TimelineRecovery: true, ProcessOwnership: true}} |
| + tuples = append(tuples, team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, LauncherVersion: r.LauncherVersion, BwrapVersion: r.BwrapVersion, PolicyVersion: r.PolicyVersion, IsolationConfigHash: r.IsolationConfigHash}) |
| + raw, err := json.Marshal([]equipo.ConnectionReport{r}) |
| + must(t, err) |
| + f.exec(t, "INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash) VALUES(?,'fixture-runner',?,?,1,?,?,'fixture')", v.provider, owner.Address, v.provider, time.Now().UTC(), string(raw)) |
| + } |
| + f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude","codex"]','claude')`, owner.Address, project) |
| + f.Store = equipo.NewStore(f.DB, equipo.WithVerifiedIsolationTuples(tuples)) |
| +} |
diff --git a/internal/plan3test/coordinator_review_test.go b/internal/plan3test/coordinator_review_test.go| new file mode 100644 |
| index 00000000..5d8fb168 |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_review_test.go |
| @@ -0,0 +1,297 @@ |
| +package plan3test |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func TestCoordinatorContextLimitParked(t *testing.T) { |
| + for _, action := range []string{"retry", "reset"} { |
| + t.Run(action, func(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, strings.Repeat("\x00", 16000), "large") |
| + if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| + t.Fatal("oversized request ran without its message") |
| + } |
| + for i := 0; i < 2; i++ { |
| + turns, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(turns) != 0 { |
| + t.Fatal("context_limit turn re-offered") |
| + } |
| + } |
| + if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| + t.Fatal("parked turn directly claimed") |
| + } |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + found := false |
| + for _, card := range page.Cards { |
| + if card.Kind == "coordinator" && card.CopyKey == "coordinator.context_limit" && card.ResourceID == turn.ID && strings.Join(card.ActionKeys, ",") == "coordinator.reset,coordinator.retry" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Fatal("context_limit omitted person-visible card") |
| + } |
| + f.exec(t, "UPDATE conversation_messages SET body='smaller request',revision=revision+1 WHERE id=?", turn.MessageID) |
| + var next equipo.CoordinatorTurn |
| + if action == "retry" { |
| + next, err = f.Store.RetryCoordinatorTurn(ctx, owner, turn.ID, equipo.Mutation{RequestID: "retry", Revision: turn.Revision}) |
| + must(t, err) |
| + } else { |
| + _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + turns, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(turns) != 1 { |
| + t.Fatal("reset did not release parked request", turns) |
| + } |
| + next = turns[0] |
| + } |
| + _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| + must(t, err) |
| + page, err = f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + for _, card := range page.Cards { |
| + if card.CopyKey == "coordinator.context_limit" { |
| + t.Fatal("resolved context_limit card survived") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestCoordinatorContextFiftySmallMessages(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + for i := 0; i < 60; i++ { |
| + _, err := f.Store.SendMessage(ctx, owner, "", fmt.Sprint("small-", i), equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| + must(t, err) |
| + } |
| + turn := queueCoordinator(t, f, "request", "request") |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + if len(c.Context.Recent) != 50 || c.Context.Recent[0].Body != "small-11" || c.Context.Recent[49].ID != turn.MessageID { |
| + t.Fatal("claim ignored 50-message limit") |
| + } |
| + checked := 0 |
| + must(t, x.Write(ctx, func(tx *gorm.DB) error { |
| + cs := conversation.New(tx, conversation.Dependencies{Authorize: func(*gorm.DB, kernel.Actor) (string, error) { return f.TeamID, nil }, ContextMessage: func(*gorm.DB, runnerproto.CoordinatorClaim, conversation.Message) (bool, error) { |
| + checked++ |
| + return true, nil |
| + }}) |
| + _, err := cs.CoordinatorContext(ctx, c) |
| + return err |
| + })) |
| + if checked != 50 { |
| + t.Fatal("instance fetched more than 50 messages", checked) |
| + } |
| + |
| +} |
| +func TestCoordinatorWaitingReset(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "request", "request") |
| + // Persist the same waiting state used while a specialist owns the home. |
| + f.exec(t, "UPDATE coordinator_turns SET state='waiting_task' WHERE id=?", turn.ID) |
| + f.exec(t, `INSERT INTO conversation_requests(principal,operation,resource,request_id,result) VALUES(?,'coordinator.waiting',?,'current','"blocking-task"')`, owner.Address, b.ID) |
| + _, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + _ = x |
| + _ = p |
| + status, err := f.Store.Coordinator(ctx, owner) |
| + must(t, err) |
| + if status.WaitingTaskID != "" || f.count(t, "SELECT count(*) FROM conversation_requests WHERE operation='coordinator.waiting'") != 0 { |
| + t.Fatal("reset retained waiting record/card") |
| + } |
| +} |
| +func TestCoordinatorRecoveryInstanceRefusals(t *testing.T) { |
| + for _, cause := range []string{"expired", "reset", "connection"} { |
| + t.Run(cause, func(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + old := queueCoordinator(t, f, "completed but unreported", "old") |
| + c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision) |
| + must(t, err) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + change := func() (equipo.CoordinatorBinding, error) { |
| + if cause == "connection" { |
| + return f.Store.SaveCoordinatorBinding(ctx, owner, p.RunnerID, "codex", equipo.Mutation{RequestID: "change", Revision: b.Revision}) |
| + } |
| + return f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "change", Revision: b.Revision}) |
| + } |
| + if cause == "expired" { |
| + f.exec(t, "UPDATE attempts SET lease_deadline=? WHERE id=?", time.Now().Add(-time.Hour).UTC(), c.Handle.Attempt) |
| + } else { |
| + if _, err = change(); err == nil { |
| + t.Fatal("change skipped pending containment") |
| + } |
| + } |
| + if err = x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "turn.completed")); err == nil { |
| + t.Fatal("stale completed turn accepted") |
| + } |
| + must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| + must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| + if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='uncertain'", old.ID) != 1 || f.count(t, "SELECT count(*) FROM reservations WHERE job_id=? AND state='settled' AND settled_by='unknown' AND s_calls=r_calls AND s_input=r_input AND s_output=r_output", c.Scope.Job) != 1 { |
| + t.Fatal("refusal lost uncertainty or charge") |
| + } |
| + nextBinding, err := change() |
| + must(t, err) |
| + next := queueCoordinator(t, f, "new request", "new") |
| + claim, err := x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| + must(t, err) |
| + if claim.Binding.Generation != nextBinding.Generation || claim.Binding.Generation <= b.Generation { |
| + t.Fatal("new generation stayed blocked") |
| + } |
| + }) |
| + } |
| +} |
| +func TestCoordinatorRecoveryInvalidTool(t *testing.T) { |
| + _, x, p, c := claimTools(t) |
| + _, err := x.CoordinatorToolResult(ctx, p, c, runnerproto.CoordinatorToolCall{RequestID: "invalid", Name: "post_message", Arguments: json.RawMessage(`{"body":"","source_refs":[]}`)}) |
| + if err == nil { |
| + t.Fatal("invalid recovery tool arguments accepted") |
| + } |
| +} |
| + |
| +func TestCoordinatorContextFinishedDecisionsOptional(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + var project int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&project)) |
| + tx, err := f.DB.Writer().Begin() |
| + must(t, err) |
| + for i := 0; i < 1002; i++ { |
| + id := fmt.Sprint("finished-", i) |
| + state := "merged" |
| + if i%2 == 0 { |
| + state = "cancelled" |
| + } |
| + _, err = tx.Exec("INSERT INTO tasks(id,requester,request_id,project_id,team_id,state,kind,plan_revision,approval_revision,revision) VALUES(?,?,?,?,?,?,'bug',1,1,1)", id, owner.Address, id, project, f.TeamID, state) |
| + must(t, err) |
| + _, err = tx.Exec("INSERT INTO plan_revisions(task_id,revision,plan) VALUES(?,1,?)", id, strings.Repeat("finished decision ", 120)) |
| + must(t, err) |
| + _, err = tx.Exec(`INSERT INTO plan_requests(principal,operation,resource,request_id,result) VALUES(?,'plan.approve',?,'approved','{"ApprovalRevision":1,"PlanRevision":1}')`, owner.Address, id) |
| + must(t, err) |
| + } |
| + must(t, tx.Commit()) |
| + // One open approval must remain required even under pressure from history. |
| + f.exec(t, "UPDATE tasks SET state='proposed' WHERE id='finished-0'") |
| + f.exec(t, "UPDATE plan_revisions SET plan='keep open decision' WHERE task_id='finished-0'") |
| + turn := queueCoordinator(t, f, "new request", "new") |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + if err != nil { |
| + t.Fatal("finished work permanently blocked conversation", err) |
| + } |
| + if len(c.Context.ConfirmedDecisions) != 1 || c.Context.ConfirmedDecisions[0].Text != "keep open decision" { |
| + t.Fatal("open-work decision lost or terminal decisions required", len(c.Context.ConfirmedDecisions)) |
| + } |
| + found := false |
| + for _, ref := range c.Context.Retrieved { |
| + if ref.Source.Kind == "plan_approval" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Fatal("finished decisions not available as optional retrieval") |
| + } |
| + if len(c.Context.Recent) != 1 || c.Context.Recent[0].ID != turn.MessageID { |
| + t.Fatal("optional decisions displaced request") |
| + } |
| +} |
| +func TestCoordinatorContextAnsweredWorkFinished(t *testing.T) { |
| + f, x, p, c := claimTools(t) |
| + question := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a direction", "options": []any{}}) |
| + must(t, f.Store.AnswerClarification(ctx, owner, question.ResourceID, "", "old finished answer", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| + // Both the original request and the answer's follow-up have finished. |
| + f.exec(t, "UPDATE coordinator_turns SET state='delivered'") |
| + f.exec(t, "UPDATE attempts SET containment='contained'") |
| + turn := queueCoordinator(t, f, "next work", "next") |
| + next, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + if len(next.Context.ConfirmedDecisions) != 0 { |
| + t.Fatal("finished question retained as required decision") |
| + } |
| + found := false |
| + for _, r := range next.Context.Retrieved { |
| + if r.Text == "old finished answer" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Fatal("finished answer missing from optional retrieval") |
| + } |
| +} |
| + |
| +func TestCoordinatorContextOwnProjectFirst(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + var own int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&own)) |
| + for i := 0; i < 40; i++ { |
| + project := equipo.Project{Name: strings.Repeat("label", 400), Repository: fmt.Sprint("amadan.net/test/", i), DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| + must(t, f.DB.G.Create(&project).Error) |
| + f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude"]','claude')`, owner.Address, project.ID) |
| + } |
| + msg, err := f.Store.SendMessage(ctx, owner, "", "own project request", equipo.Mutation{RequestID: "own"}) |
| + must(t, err) |
| + turn, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, own, equipo.Mutation{RequestID: "own"}) |
| + must(t, err) |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + if len(c.Context.Retrieved) == 0 || c.Context.Retrieved[0].Source.Kind != "project" || c.Context.Retrieved[0].Source.ID != fmt.Sprint(own) { |
| + t.Fatal("own project source trimmed before labels") |
| + } |
| + if len(c.Context.Retrieved) >= 42 { |
| + t.Fatal("fixture did not exercise retrieval trimming") |
| + } |
| +} |
| +func TestCoordinatorWaitingWritesOnlyOnChange(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "request", "request") |
| + f.exec(t, "DELETE FROM connections WHERE id='claude'") |
| + _, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + f.exec(t, "CREATE TRIGGER forbid_waiting_update BEFORE UPDATE ON conversation_requests WHEN OLD.operation='coordinator.waiting' BEGIN SELECT RAISE(ABORT,'unchanged waiting write'); END") |
| + f.exec(t, "CREATE TRIGGER forbid_waiting_insert BEFORE INSERT ON conversation_requests WHEN NEW.operation='coordinator.waiting' BEGIN SELECT RAISE(ABORT,'unchanged waiting write'); END") |
| + _, err = x.PollCoordinator(ctx, p) |
| + if err != nil { |
| + t.Fatal("unchanged waiting status wrote again", err) |
| + } |
| + if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='waiting_connection'", turn.ID) != 1 { |
| + t.Fatal("waiting status missing") |
| + } |
| +} |
| + |
| +func TestCoordinatorContextAnswerFollowsOpenWork(t *testing.T) { |
| + for _, state := range []string{"proposed", "cancelled"} { |
| + t.Run(state, func(t *testing.T) { |
| + f, x, p, c := claimTools(t) |
| + var task string |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM tasks LIMIT 1").Scan(&task)) |
| + question := toolCall(t, x, p, c, "question", "ask_person", map[string]any{"message_id": c.Turn.MessageID, "question": "Choose a direction", "options": []any{}}) |
| + toolCall(t, x, p, c, "route", "route_to_task", map[string]any{"message_id": c.Turn.MessageID, "task_id": task}) |
| + must(t, f.Store.AnswerClarification(ctx, owner, question.ResourceID, "", "linked decision", equipo.Mutation{RequestID: "answer", Revision: 1})) |
| + f.exec(t, "UPDATE coordinator_turns SET state='delivered'") |
| + f.exec(t, "UPDATE attempts SET containment='contained'") |
| + f.exec(t, "UPDATE tasks SET state=? WHERE id=?", state, task) |
| + turn := queueCoordinator(t, f, "next work", "next") |
| + next, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + found := false |
| + for _, ref := range next.Context.ConfirmedDecisions { |
| + if ref.Text == "linked decision" { |
| + found = true |
| + } |
| + } |
| + if found != (state == "proposed") { |
| + t.Fatal("answer did not follow linked work state", state, found) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/plan3test/coordinator_test.go b/internal/plan3test/coordinator_test.go| index 91fafe2f..885dcb81 100644 |
| --- a/internal/plan3test/coordinator_test.go |
| +++ b/internal/plan3test/coordinator_test.go |
| @@ -15,32 +15,6 @@ import ( |
| "time" |
| ) |
| -func coordinatorFixture(t *testing.T) (*fixture, *equipo.Execution, equipo.RunnerPrincipal, equipo.CoordinatorBinding) { |
| - f := newFixture(t) |
| - task := f.createTask(t) |
| - f.planConnections(t, task.ProjectID) |
| - var path string |
| - must(t, f.DB.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| - x, err := f.Store.AttachExecution(ctx, path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil), Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: f.Store.RunnerAdapter(team.OpProviderCall)}}) |
| - must(t, err) |
| - t.Cleanup(func() { must(t, x.Core.Close()) }) |
| - _, err = x.Core.Resume(ctx) |
| - must(t, err) |
| - f.exec(t, "INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) VALUES('fixture-credential','fixture-runner',?,?,?,'','fixture-token',?)", f.TeamID, runnerproto.RunnerAudience, owner.Address, time.Now().Add(time.Hour).UTC()) |
| - p := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| - must(t, f.Store.SetCoordinatorLimits(ctx, owner, owner.Address, team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}, equipo.Mutation{RequestID: "limits"})) |
| - b, err := f.Store.SaveCoordinatorBinding(ctx, owner, p.RunnerID, "claude", equipo.Mutation{RequestID: "bind"}) |
| - must(t, err) |
| - return f, x, p, b |
| -} |
| -func queueCoordinator(t *testing.T, f *fixture, body, key string) equipo.CoordinatorTurn { |
| - t.Helper() |
| - msg, err := f.Store.SendMessage(ctx, owner, "", body, equipo.Mutation{RequestID: key}) |
| - must(t, err) |
| - turn, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: key}) |
| - must(t, err) |
| - return turn |
| -} |
| func TestCoordinatorSingleWriter(t *testing.T) { |
| f, x, p, _ := coordinatorFixture(t) |
| first := queueCoordinator(t, f, "first", "first") |
diff --git a/internal/plan3test/harness_test.go b/internal/plan3test/harness_fixture.go| similarity index 100% |
| rename from internal/plan3test/harness_test.go |
| rename to internal/plan3test/harness_fixture.go |
diff --git a/internal/plan3test/plans_approval_test.go b/internal/plan3test/plans_approval_test.go| index 2a46960c..9ac9e1c1 100644 |
| --- a/internal/plan3test/plans_approval_test.go |
| +++ b/internal/plan3test/plans_approval_test.go |
| @@ -3,7 +3,6 @@ package plan3test |
| import ( |
| "crypto/sha256" |
| "encoding/hex" |
| - "encoding/json" |
| "errors" |
| "strings" |
| "testing" |
| @@ -14,20 +13,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| -func (f *fixture) planConnections(t *testing.T, project int64) { |
| - t.Helper() |
| - var tuples []team.IsolationTuple |
| - f.exec(t, "INSERT INTO runners(id,person,instance_id,revision) VALUES('fixture-runner',?,?,1)", owner.Address, f.TeamID) |
| - for _, v := range []struct{ provider, family, version string }{{"claude", "claude", "2.1.312"}, {"codex", "gpt", "0.165.0"}} { |
| - r := equipo.ConnectionReport{LocalID: v.provider, Provider: v.provider, Family: v.family, Model: "fixture-model", ProviderVersion: v.version, LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: "policy-v2", Kind: "subscription", Available: true, ReadIsolation: true, IsolationConfigHash: strings.Repeat("a", 64), Routing: equipo.ConnectionRouting{BindingID: v.provider, AccountID: v.provider, ObservedAccountID: v.provider, CredentialHomeHash: strings.Repeat("b", 64), AccountPinned: true, NoFailover: true, TimelineRecovery: true, ProcessOwnership: true}} |
| - tuples = append(tuples, team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, LauncherVersion: r.LauncherVersion, BwrapVersion: r.BwrapVersion, PolicyVersion: r.PolicyVersion, IsolationConfigHash: r.IsolationConfigHash}) |
| - raw, err := json.Marshal([]equipo.ConnectionReport{r}) |
| - must(t, err) |
| - f.exec(t, "INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash) VALUES(?,'fixture-runner',?,?,1,?,?,'fixture')", v.provider, owner.Address, v.provider, time.Now().UTC(), string(raw)) |
| - } |
| - f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude","codex"]','claude')`, owner.Address, project) |
| - f.Store = equipo.NewStore(f.DB, equipo.WithVerifiedIsolationTuples(tuples)) |
| -} |
| func TestPlanApprovalPrecedenceDispatch(t *testing.T) { |
| f := newFixture(t) |
| p := proposed(t, f) |
diff --git a/internal/runner/coordinator_fix_test.go b/internal/runner/coordinator_fix_test.go| new file mode 100644 |
| index 00000000..06a4062e |
| --- /dev/null |
| +++ b/internal/runner/coordinator_fix_test.go |
| @@ -0,0 +1,193 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "strconv" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type refusingCoordinatorAPI struct { |
| + *coordinatorAPIStub |
| + refusal error |
| + contained, rejected int |
| + pollError error |
| +} |
| + |
| +func (a *refusingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| + if op == "event" && q.Event.Kind == "turn.completed" && a.refusal != nil { |
| + a.rejected++ |
| + return a.refusal |
| + } |
| + if op == "containment" { |
| + a.contained++ |
| + } |
| + if op == "poll" { |
| + return a.pollError |
| + } |
| + return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) |
| +} |
| +func TestCoordinatorRecoveryRefusedKeepsServing(t *testing.T) { |
| + for _, status := range []int{403, 409, 422} { |
| + t.Run(strconv.Itoa(status), func(t *testing.T) { |
| + ctx := context.Background() |
| + s, api, launcher, c := coordinatorServiceFixture(t) |
| + launch, _, err := s.OpenLaunch(ctx, c, nil) |
| + mustJournal(t, err) |
| + session := provider.Session{ID: "completed-session", AttemptKey: launch.AttemptKey, Provider: "claude", Family: "claude", AccountID: "account", Model: "model"} |
| + mustJournal(t, s.Journal.BindSession(ctx, session)) |
| + r := coordinatorState{Claim: c, Session: session} |
| + mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, r)) |
| + turn := provider.Turn{ID: c.Turn.ID, AdmissionID: c.Turn.ID, Prompt: "hello"} |
| + mustJournal(t, s.Journal.BeginTurn(ctx, session, turn)) |
| + mustJournal(t, s.Journal.consumeTurn(ctx, session.AttemptKey, session.ID, turn.Prompt)) |
| + pump := EventPump{Journal: s.Journal, Contain: func(context.Context) error { return nil }} |
| + mustJournal(t, pump.AppendDirect(ctx, session, provider.Event{SessionID: session.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)}, s.template(r))) |
| + refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Status: status}} |
| + s.API = refused |
| + for restart := 0; restart < 2; restart++ { |
| + path := s.Journal.path |
| + mustJournal(t, s.Journal.Close()) |
| + s.Journal, err = OpenJournal(ctx, path) |
| + mustJournal(t, err) |
| + defer s.Journal.Close() |
| + runSpecialistAfterCoordinator(t, s) |
| + } |
| + if refused.contained != 1 || refused.rejected != 1 || launcher.starts != 0 { |
| + t.Fatalf("refused recovery repeated or missed containment: %+v starts=%d", refused, launcher.starts) |
| + } |
| + var states []coordinatorState |
| + mustJournal(t, s.Journal.readStates(ctx, "coordinator", &states)) |
| + if len(states) != 1 || !states[0].Finished || !states[0].Refused { |
| + t.Fatal("refusal not durably retired") |
| + } |
| + }) |
| + } |
| +} |
| +func runSpecialistAfterCoordinator(t *testing.T, coordinator *CoordinatorService) { |
| + t.Helper() |
| + s, record, _, _ := cleanupFixture(t) |
| + s.journal = coordinator.Journal |
| + record.Phase = "contained" |
| + mustJournal(t, s.save(context.Background(), record)) |
| + s.workflow = &BugWorkflow{} |
| + source := &resilientSource{attempt: true} |
| + ran := false |
| + service := Service{Supervisor: s, Source: source, Coordinator: coordinator, BeforeRun: func(RunClaim) { ran = true }} |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| + defer cancel() |
| + err := service.Run(ctx) |
| + if !errors.Is(err, context.Canceled) || !ran { |
| + t.Fatalf("coordinator stopped specialist work: ran=%v error=%v", ran, err) |
| + } |
| +} |
| +func TestCoordinatorPollErrorKeepsServing(t *testing.T) { |
| + s, api, _, _ := coordinatorServiceFixture(t) |
| + s.API = &refusingCoordinatorAPI{coordinatorAPIStub: api, pollError: ErrTransient} |
| + runSpecialistAfterCoordinator(t, s) |
| +} |
| +func TestCoordinatorCleanupRefusalReportsContainment(t *testing.T) { |
| + s, api, _, c := coordinatorServiceFixture(t) |
| + refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Status: 403}} |
| + s.API = refused |
| + _ = s.RunTurn(context.Background(), c) |
| + if refused.contained != 1 { |
| + t.Fatal("cleanup skipped containment after delivery refusal") |
| + } |
| + mustJournal(t, s.Recover(context.Background())) |
| + if refused.contained != 1 { |
| + t.Fatal("cleanup refusal retried on recovery") |
| + } |
| +} |
| + |
| +type countingCoordinatorAPI struct { |
| + *coordinatorAPIStub |
| + renews, polls atomic.Int32 |
| +} |
| + |
| +func (a *countingCoordinatorAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| + if op == "renew" { |
| + a.renews.Add(1) |
| + } |
| + if op == "poll" { |
| + a.polls.Add(1) |
| + return nil |
| + } |
| + return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) |
| +} |
| +func TestCoordinatorRenewalCadence(t *testing.T) { |
| + s, api, l, c := coordinatorServiceFixture(t) |
| + counted := &countingCoordinatorAPI{coordinatorAPIStub: api} |
| + s.API = counted |
| + l.hold = true |
| + l.started = make(chan struct{}) |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| + defer cancel() |
| + done := make(chan error, 1) |
| + go func() { done <- s.RunTurn(ctx, c) }() |
| + select { |
| + case <-l.started: |
| + case <-ctx.Done(): |
| + t.Fatal("fixture did not start") |
| + } |
| + before := counted.renews.Load() |
| + time.Sleep(1100 * time.Millisecond) |
| + after := counted.renews.Load() |
| + cancel() |
| + <-done |
| + if after != before { |
| + t.Fatal("idle turn renewed too frequently", before, after) |
| + } |
| +} |
| +func TestCoordinatorWaitingObserverChanges(t *testing.T) { |
| + counted := &countingCoordinatorAPI{} |
| + s := &Service{Coordinator: &CoordinatorService{API: counted}} |
| + err := s.withCoordinatorWaiting(context.Background(), func() error { |
| + time.Sleep(1200 * time.Millisecond) |
| + if n := counted.polls.Load(); n != 1 { |
| + t.Errorf("waiting observer polled without a state change: %d", n) |
| + } |
| + return nil |
| + }) |
| + mustJournal(t, err) |
| + if n := counted.polls.Load(); n != 2 { |
| + t.Fatal("release did not refresh waiting status", n) |
| + } |
| +} |
| + |
| +type containmentRetryAPI struct { |
| + attempts int |
| +} |
| + |
| +func (a *containmentRetryAPI) CoordinatorCall(_ context.Context, op string, _ runnerproto.CoordinatorRequest, _ any) error { |
| + if op != "containment" { |
| + return provider.ErrContract |
| + } |
| + a.attempts++ |
| + if a.attempts == 1 { |
| + return ErrTransient |
| + } |
| + return nil |
| +} |
| +func TestCoordinatorRefusalContainmentRetry(t *testing.T) { |
| + s, _, _, c := coordinatorServiceFixture(t) |
| + api := &containmentRetryAPI{} |
| + s.API = api |
| + state := coordinatorState{Claim: c} |
| + proof := runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle} |
| + refusal := &RefusalError{Status: 403} |
| + err := s.finishContained(context.Background(), &state, proof, refusal) |
| + if !errors.Is(err, ErrTransient) || fatalServiceError(err) || state.Finished { |
| + t.Fatal("delivery refusal made transient containment failure fatal", err) |
| + } |
| + mustJournal(t, s.finishContained(context.Background(), &state, proof, refusal)) |
| + if !state.Finished || !state.Refused { |
| + t.Fatal("successful retry did not retire refused turn") |
| + } |
| +} |
diff --git a/internal/runner/coordinator_recovery.go b/internal/runner/coordinator_recovery.go| index 9948ca64..cb1a5227 100644 |
| --- a/internal/runner/coordinator_recovery.go |
| +++ b/internal/runner/coordinator_recovery.go |
| @@ -69,30 +69,41 @@ func (s *CoordinatorService) Recover(ctx context.Context) error { |
| if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| return err |
| } |
| + var deliveryErr error |
| if status == "completed" { |
| - if err = s.reconcileTools(ctx, r); err != nil { |
| - return err |
| - } |
| - if err = s.finishDelivery(ctx, r); err != nil && !errors.Is(err, provider.ErrUncertain) { |
| - return err |
| + deliveryErr = s.reconcileTools(ctx, r) |
| + if deliveryErr == nil { |
| + deliveryErr = s.finishDelivery(ctx, r) |
| } |
| } |
| - q := coordinatorRequest(r.Claim) |
| - q.Proof = &proof |
| - if err = s.call(ctx, "containment", q, nil); err != nil { |
| - return err |
| - } |
| - if err = s.retirePending(ctx, r.Claim.Turn.ID); err != nil { |
| - return err |
| - } |
| - r.Finished = true |
| - if err = s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, r); err != nil { |
| + if err = s.finishContained(ctx, &r, proof, deliveryErr); err != nil { |
| return err |
| } |
| } |
| return nil |
| } |
| +// Containment must reach the instance even when delivery authority has expired. |
| +func (s *CoordinatorService) finishContained(ctx context.Context, r *coordinatorState, proof runnerproto.ContainmentProof, deliveryErr error) error { |
| + q := coordinatorRequest(r.Claim) |
| + q.Proof = &proof |
| + if err := s.call(ctx, "containment", q, nil); err != nil { |
| + return err |
| + } |
| + var refusal *RefusalError |
| + if deliveryErr != nil && !errors.Is(deliveryErr, provider.ErrUncertain) && !errors.As(deliveryErr, &refusal) { |
| + return deliveryErr |
| + } |
| + if refusal != nil { |
| + r.Refused = true |
| + } |
| + if err := s.retirePending(ctx, r.Claim.Turn.ID); err != nil { |
| + return err |
| + } |
| + r.Finished = true |
| + return s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r) |
| +} |
| + |
| // Contained uncertain observations stay in the local audit journal but cannot |
| // leak into the ordinary task uploader or regain delivery authority. |
| func (s *CoordinatorService) retirePending(ctx context.Context, turn string) error { |
diff --git a/internal/runner/coordinator_runtime_test.go b/internal/runner/coordinator_runtime_test.go| index 04a1b812..1eb7a6d1 100644 |
| --- a/internal/runner/coordinator_runtime_test.go |
| +++ b/internal/runner/coordinator_runtime_test.go |
| @@ -101,6 +101,8 @@ type coordinatorFixtureLauncher struct { |
| proxy *ToolProxy |
| events chan provider.Event |
| starts int |
| + hold bool |
| + started chan struct{} |
| crash string |
| } |
| @@ -140,6 +142,12 @@ func (l *coordinatorFixtureLauncher) StartTurn(ctx context.Context, s provider.S |
| if l.crash == "tool" { |
| return provider.ErrUncertain |
| } |
| + if l.hold { |
| + if l.started != nil { |
| + close(l.started) |
| + } |
| + return nil |
| + } |
| l.events <- provider.Event{Sequence: 1, SessionID: s.ID, TurnID: t.ID, Kind: "turn.completed", Payload: json.RawMessage(`{"usage":{"input_tokens":2,"cache_read_input_tokens":0,"cache_creation_input_tokens":0,"output_tokens":3}}`)} |
| return nil |
| } |
diff --git a/internal/runner/coordinator_service.go b/internal/runner/coordinator_service.go| index 86ff35d4..0237a1b9 100644 |
| --- a/internal/runner/coordinator_service.go |
| +++ b/internal/runner/coordinator_service.go |
| @@ -31,6 +31,7 @@ type coordinatorState struct { |
| Claim runnerproto.CoordinatorClaim |
| Session provider.Session |
| Finished bool |
| + Refused bool |
| } |
| func coordinatorRequest(c runnerproto.CoordinatorClaim) runnerproto.CoordinatorRequest { |
| @@ -116,22 +117,11 @@ func (s *CoordinatorService) RunTurn(ctx context.Context, c runnerproto.Coordina |
| } |
| s.release = nil |
| } |
| + var deliveryErr error |
| if result == nil { |
| - result = s.finishDelivery(cleanup, state) |
| - if result != nil && !errors.Is(result, provider.ErrUncertain) { |
| - return |
| - } |
| - } |
| - q := coordinatorRequest(c) |
| - q.Proof = &proof |
| - err = s.call(cleanup, "containment", q, nil) |
| - if err == nil { |
| - err = s.retirePending(cleanup, c.Turn.ID) |
| - } |
| - if err == nil { |
| - state.Finished = true |
| - err = s.Journal.saveState(cleanup, "coordinator", c.Turn.ID, state) |
| + deliveryErr = s.finishDelivery(cleanup, state) |
| } |
| + err = s.finishContained(cleanup, &state, proof, deliveryErr) |
| result = errors.Join(result, err) |
| }() |
| launcher := s.Launchers[c.Brief.Selection.Provider] |
| @@ -213,7 +203,7 @@ func (s *CoordinatorService) RunTurn(ctx context.Context, c runnerproto.Coordina |
| done := make(chan struct{}) |
| go func() { |
| defer close(done) |
| - tick := time.NewTicker(time.Second) |
| + tick := time.NewTicker(leaseRenewInterval) |
| defer tick.Stop() |
| for { |
| select { |
| @@ -343,7 +333,10 @@ func (s *CoordinatorService) finishDelivery(ctx context.Context, r coordinatorSt |
| var raw, body []byte |
| err := s.Journal.db.QueryRowContext(ctx, `SELECT t.body,t.result FROM coordinator_tools t JOIN coordinator_tool_claims c ON c.claim_ref=json_extract(t.body,'$.claim_ref') WHERE c.turn_key=? AND t.acked=1 AND json_extract(t.result,'$.value.tool') IN ('post_message','propose_plan','ask_person','route_to_task','suggest_preference','suggest_specialist','suggest_playbook') ORDER BY t.ordinal LIMIT 1`, coordinatorTurnKey(r.Claim, r.Session)).Scan(&body, &raw) |
| if err != nil { |
| - return errors.Join(provider.ErrUncertain, err) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return provider.ErrUncertain |
| + } |
| + return err |
| } |
| var record coordinatorToolRecord |
| var out runnerproto.CoordinatorToolResult |
diff --git a/internal/runner/coordinator_tool_proxy.go b/internal/runner/coordinator_tool_proxy.go| index 67cb04fa..dade4028 100644 |
| --- a/internal/runner/coordinator_tool_proxy.go |
| +++ b/internal/runner/coordinator_tool_proxy.go |
| @@ -87,7 +87,7 @@ func OpenCoordinatorToolProxy(ctx context.Context, b CoordinatorToolBinding) (*T |
| case <-ctx.Done(): |
| return |
| case <-tick.C: |
| - if err := p.coordinator.current(ctx, false); err != nil { |
| + if err := p.coordinator.check(ctx, false, false); err != nil { |
| cancel() |
| return |
| } |
| @@ -98,17 +98,25 @@ func OpenCoordinatorToolProxy(ctx context.Context, b CoordinatorToolBinding) (*T |
| return p, nil |
| } |
| func (b *coordinatorBroker) current(ctx context.Context, dispatched bool) error { |
| + return b.check(ctx, dispatched, true) |
| +} |
| + |
| +// The local watchdog checks deadlines without renewing remote authority. Actual |
| +// tool use rechecks authority, and the service renews at the lease cadence. |
| +func (b *coordinatorBroker) check(ctx context.Context, dispatched, remote bool) error { |
| b.mu.Lock() |
| v, invalid, deadline := b.binding, b.invalid, b.deadline |
| b.mu.Unlock() |
| if invalid || ctx.Err() != nil || !time.Now().Before(deadline) || !time.Now().Before(v.Claim.AttemptDeadline) { |
| return runnerproto.ErrInvalid |
| } |
| - if err := v.Current(ctx); err != nil { |
| - b.mu.Lock() |
| - b.invalid = true |
| - b.mu.Unlock() |
| - return err |
| + if remote { |
| + if err := v.Current(ctx); err != nil { |
| + b.mu.Lock() |
| + b.invalid = true |
| + b.mu.Unlock() |
| + return err |
| + } |
| } |
| if v.Session.ID != "" { |
| if v.Session.Provider != v.Claim.Brief.Selection.Provider || v.Session.AccountID != v.Claim.Brief.Selection.AccountID || v.Session.Model != v.Claim.Brief.Selection.Model { |
diff --git a/internal/runner/journal.go b/internal/runner/journal.go| index d40d7245..9415fa61 100644 |
| --- a/internal/runner/journal.go |
| +++ b/internal/runner/journal.go |
| @@ -267,7 +267,7 @@ func (j *Journal) Pending(ctx context.Context, limit int) ([]Event, error) { |
| if limit < 1 || limit > 1024 { |
| return nil, runnerproto.ErrInvalid |
| } |
| - rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events WHERE acked=0 ORDER BY ordinal LIMIT ?", limit) |
| + rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events WHERE acked=0 AND NOT EXISTS (SELECT 1 FROM journal_supervisor s WHERE s.kind='coordinator' AND s.state_key=json_extract(journal_events.body,'$.assignment_id')) ORDER BY ordinal LIMIT ?", limit) |
| if err != nil { |
| return nil, j.storageFailure(ctx, err) |
| } |
diff --git a/internal/runner/service.go b/internal/runner/service.go| index fb41f059..efbc062a 100644 |
| --- a/internal/runner/service.go |
| +++ b/internal/runner/service.go |
| @@ -29,17 +29,13 @@ func (s *Service) Run(ctx context.Context) error { |
| return provider.ErrContract |
| } |
| needsRecovery := true |
| + coordinatorRecovery := true |
| claimRefusals := 0 |
| for { |
| if ctx.Err() != nil { |
| return ctx.Err() |
| } |
| if needsRecovery { |
| - if s.Coordinator != nil { |
| - if err := s.Coordinator.Recover(ctx); err != nil { |
| - return err |
| - } |
| - } |
| err := errors.Join(s.recoverClaims(ctx), s.Supervisor.Recover(ctx)) |
| if err != nil { |
| s.Supervisor.ready = false |
| @@ -54,29 +50,36 @@ func (s *Service) Run(ctx context.Context) error { |
| } |
| needsRecovery = false |
| } |
| + var coordinatorErr error |
| + if s.Coordinator != nil && coordinatorRecovery { |
| + coordinatorErr = s.Coordinator.Recover(ctx) |
| + coordinatorRecovery = coordinatorErr != nil |
| + if fatalServiceError(coordinatorErr) || errors.Is(coordinatorErr, context.Canceled) { |
| + return coordinatorErr |
| + } |
| + if coordinatorErr != nil { |
| + s.report("runner.recovery_retry") |
| + } |
| + } |
| assignments, err := s.Source.Poll(ctx) |
| if err != nil { |
| if fatalServiceError(err) || errors.Is(err, context.Canceled) { |
| return err |
| } |
| s.report("runner.poll_retry") |
| - if err := serviceBackoff(ctx); err != nil { |
| - return err |
| - } |
| - continue |
| + assignments = nil |
| } |
| - if s.Coordinator != nil { |
| - if err := s.Coordinator.Poll(ctx); err != nil { |
| - needsRecovery = true |
| - if fatalServiceError(err) || ctx.Err() != nil { |
| - return err |
| - } |
| - if err = serviceBackoff(ctx); err != nil { |
| - return err |
| - } |
| - continue |
| + pollErr := err |
| + if s.Coordinator != nil && !coordinatorRecovery { |
| + coordinatorErr = s.Coordinator.Poll(ctx) |
| + if coordinatorErr != nil { |
| + coordinatorRecovery = true |
| + s.report("runner.poll_retry") |
| } |
| } |
| + if errors.Is(coordinatorErr, ErrJournal) || ctx.Err() != nil { |
| + return errors.Join(coordinatorErr, ctx.Err()) |
| + } |
| for _, a := range assignments { |
| if err := s.Supervisor.journal.AdmissionAllowed(ctx); err != nil { |
| needsRecovery = true |
| @@ -126,33 +129,48 @@ func (s *Service) Run(ctx context.Context) error { |
| break |
| } |
| } |
| + if pollErr != nil || coordinatorErr != nil { |
| + if err := serviceBackoff(ctx); err != nil { |
| + return err |
| + } |
| + } |
| } |
| } |
| -// Polling while a specialist owns the serial work loop lets the instance persist |
| -// its waiting card. This observer never claims or starts coordinator work. |
| +// Observe the shared home at claim/release and at the lease cadence so messages |
| +// queued during specialist work acquire waiting status. This never dispatches. |
| func (s *Service) withCoordinatorWaiting(ctx context.Context, run func() error) error { |
| if s.Coordinator == nil { |
| return run() |
| } |
| + observe := func(ctx context.Context) { |
| + var turns []runnerproto.CoordinatorTurn |
| + // A failed poll supplies no status and must not invent availability. |
| + _ = s.Coordinator.call(ctx, "poll", runnerproto.CoordinatorRequest{}, &turns) |
| + } |
| + observe(ctx) |
| watch, cancel := context.WithCancel(ctx) |
| done := make(chan struct{}) |
| go func() { |
| defer close(done) |
| - tick := time.NewTicker(time.Second) |
| + tick := time.NewTicker(leaseRenewInterval) |
| defer tick.Stop() |
| for { |
| - var turns []runnerproto.CoordinatorTurn |
| - // A failed poll supplies no status and must not invent availability. |
| - _ = s.Coordinator.call(watch, "poll", runnerproto.CoordinatorRequest{}, &turns) |
| select { |
| case <-watch.Done(): |
| return |
| case <-tick.C: |
| + observe(watch) |
| } |
| } |
| }() |
| - defer func() { cancel(); <-done }() |
| + defer func() { |
| + cancel() |
| + <-done |
| + cleanup, stop := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| + defer stop() |
| + observe(cleanup) |
| + }() |
| return run() |
| } |
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go| index c9fbc752..d1a45451 100644 |
| --- a/internal/runner/supervisor.go |
| +++ b/internal/runner/supervisor.go |
| @@ -15,6 +15,8 @@ import ( |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| +const leaseRenewInterval = 15 * time.Second |
| + |
| type InstanceAPI interface { |
| Call(context.Context, string, runnerproto.RunnerRequest, any) error |
| } |
| @@ -201,7 +203,7 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelCauseF |
| cancel(attemptCancellation{"watchLease.Read", err}) |
| return |
| } |
| - renewAt := last.Elapsed + 15*time.Second |
| + renewAt := last.Elapsed + leaseRenewInterval |
| for { |
| select { |
| case <-ctx.Done(): |
| @@ -260,7 +262,7 @@ func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelCauseF |
| return |
| } |
| } |
| - renewAt = now.Elapsed + 15*time.Second |
| + renewAt = now.Elapsed + leaseRenewInterval |
| goto renewed |
| case <-tick.C: |
| _, e := l.checkClock(s.clock) |
diff --git a/internal/runnerproto/coordinator_prompt.go b/internal/runnerproto/coordinator_prompt.go| index 829ece80..db9c878b 100644 |
| --- a/internal/runnerproto/coordinator_prompt.go |
| +++ b/internal/runnerproto/coordinator_prompt.go |
| @@ -56,10 +56,13 @@ func BoundCoordinatorContext(c CoordinatorContext) (CoordinatorContext, error) { |
| for _, m := range c.Recent { |
| size += len(m.Body) |
| } |
| - for size > 32<<10 && len(c.Recent) > 0 { |
| + for size > 32<<10 && len(c.Recent) > 1 { |
| size -= len(c.Recent[0].Body) |
| c.Recent = c.Recent[1:] |
| } |
| + if size > 32<<10 { |
| + return CoordinatorContext{}, ErrPromptTooLarge |
| + } |
| for { |
| c.Hash = CoordinatorContextHash(c) |
| if _, err := coordinatorPrompt(c); err == nil { |
| @@ -71,7 +74,7 @@ func BoundCoordinatorContext(c CoordinatorContext) (CoordinatorContext, error) { |
| c.Retrieved = c.Retrieved[:len(c.Retrieved)-1] |
| continue |
| } |
| - if len(c.Recent) > 0 { |
| + if len(c.Recent) > 1 { |
| c.Recent = c.Recent[1:] |
| continue |
| } |