oficina / equipo Public

fix: stop coordinator poll churn and contain refused recovery calls

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 02d46e61161ddfec1d88f7edb5b152659c9c2ec8 parent f6ffff0
15 files changed, +590 −47
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +178 −0
  • internal/equipo/conversation/context.go +3 −1
  • internal/equipo/conversation/coordinator.go +1 −1
  • internal/equipo/conversation/coordinator_application.go +1 −1
  • internal/equipo/conversation/coordinator_engine.go +10 −9
  • internal/equipo/conversation/coordinator_execution.go +14 −7
  • internal/equipo/conversation/coordinator_poll.go +4 −15
  • internal/equipo/conversation/store.go +2 −2
  • internal/equipo/coordinator_execution.go +1 −1
  • internal/equipo/copy.go +3 −1
  • internal/plan3test/coordinator_fix2_test.go +166 −0
  • internal/runner/coordinator_recovery.go +39 −4
  • internal/runner/coordinator_refusal_test.go +153 −0
  • internal/runner/coordinator_runtime_test.go +1 −1
  • internal/runner/coordinator_service.go +14 −4
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 1533f0a7..a4003d36 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -2570,3 +2570,181 @@ Self-review checked refusal classification, containment before retirement, share
- `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.
+
+## Fix round 2
+
+Status: DONE_WITH_CONCERNS. All dispatched findings are fixed. Pending copy and the existing offline/live-release boundaries remain. Commit subject: `fix: stop coordinator poll churn and contain refused recovery calls` (67 characters). Author: `codex <codex~paul@keymail.dev>`. No push, merge or deployment.
+
+### Changes and coverage
+
+Coordinator polling clears waiting metadata only when it can offer the turn. It no longer clears the record before checking budget availability. Changes between waiting reasons still use the existing transaction, revision and audit path. The first poll persists the reason; repeated polls of `budget_needed`, `waiting_connection`, `waiting_task` and `context_limit` perform no writes. Reset and connection changes retain their existing waiting cleanup. Claim-time cleanup remains before snapshot assembly so its conversation revision includes that change.
+
+`TestCoordinatorBlockedPollWritesOnlyOnChange` covers all four reasons. After the first blocked observation, SQLite triggers reject every INSERT, UPDATE and DELETE on conversation requests, turns, conversations and audit events. Three more polls must succeed with unchanged conversation revision and audit count. Restoring the budget offers the same queued turn, removes waiting metadata once and permits subsequent polls without writes. Existing connection-waiting and reset tests still cover task links and release.
+
+Recover and containment endpoint refusals are durable local outcomes. The journal records the operation, HTTP status and refusal before retiring pending events and saving completion. A refused containment report also retains its locally verified containment proof. Recovery resumes interrupted retirement locally, without repeating the refused call. Local containment failure still prevents retirement and lease release; transient endpoint failures retain the existing retry behavior.
+
+When recovery of a lost claim response is refused, there is no saved coordinator claim and therefore no local provider launch: RunTurn saves that claim before creating any process. Recovery preserves a refusal record keyed by the turn ID. Polling skips saved turns, including refused turns, and continues to later offers. RunTurn still refuses any saved turn. Neither path resends a prompt.
+
+- `TestCoordinatorRecoveryCallRefusalKeepsServing`: recover and containment responses 401, 403, 409 and 422; two journal reopenings; specialist work continues; exactly one refused call; saved refusal operation/status; saved local proof for containment; direct redispatch refused; a stale refused offer does not prevent a later coordinator turn from completing.
+- `TestCoordinatorContainmentCallRefusalOnCleanup`: normal completion tolerates a refused containment report; recovery repeats neither the call nor the prompt.
+- `TestCoordinatorRefusalInterruptedRetirement`: a database trigger interrupts the final completion write after the refusal is saved. After reopening the journal, retirement finishes without repeating the refusal.
+- `TestCoordinatorRefusalRequiresLocalContainment`: failed local containment cannot report or retire the turn.
+- Existing delivery-refusal, transient containment retry, instance uncertainty/unknown-charge, crash, journal upgrade and real-launcher continuity tests remain green.
+
+A request excluded by the context access filter now parks as `context_unavailable` in the claim transaction, before any job/admission or provider call. It has a coordinator card with its turn ID, the pending `coordinator.context_unavailable` key and the existing reset/retry actions. Polling skips it and direct claims refuse it. Retry and reset supersede it; a later explicit attempt builds a fresh authorized snapshot. Other context errors still propagate without being classified as this state.
+
+`TestCoordinatorFilteredRequestParked` revokes a routed source's connection access, checks that the request parks without an admission, checks its card/actions, and rejects all writes during repeated polls/direct claim refusals. Restoring access followed by retry or reset produces a fresh claim containing the request and removes the old card. The context-limit copy now names only reset and retry.
+
+### Test-first evidence
+
+The new blocked-poll, filtered-request and recovery/cleanup-refusal tests were written before implementation. The initial command exited 1:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner ./internal/plan3test -run '^TestCoordinator(BlockedPollWritesOnlyOnChange|FilteredRequestParked|RecoveryCallRefusalKeepsServing|ContainmentCallRefusalOnCleanup)$' -count=1
+```
+
+```text
+--- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing (1.55s)
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/recover/401 (0.18s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/recover/403 (0.19s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/recover/409 (0.19s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/recover/422 (0.19s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/containment/401 (0.21s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/containment/403 (0.21s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/containment/409 (0.19s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+ --- FAIL: TestCoordinatorRecoveryCallRefusalKeepsServing/containment/422 (0.19s)
+ coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=
+--- FAIL: TestCoordinatorContainmentCallRefusalOnCleanup (0.57s)
+ coordinator_refusal_test.go:98:
+FAIL
+rastrillo-budget/v1 ran 2.117s
+FAIL amadan.net/oficina/equipo/internal/runner 2.119s
+--- FAIL: TestCoordinatorBlockedPollWritesOnlyOnChange (2.24s)
+ --- FAIL: TestCoordinatorBlockedPollWritesOnlyOnChange/budget_needed (0.78s)
+ coordinator_fix2_test.go:48: constraint failed: unchanged poll wrote (1811)
+--- FAIL: TestCoordinatorFilteredRequestParked (0.30s)
+ --- FAIL: TestCoordinatorFilteredRequestParked/retry (0.15s)
+ coordinator_fix2_test.go:111: filtered request not parked
+ --- FAIL: TestCoordinatorFilteredRequestParked/reset (0.15s)
+ coordinator_fix2_test.go:111: filtered request not parked
+FAIL
+rastrillo-budget/v1 ran 2.535s
+FAIL amadan.net/oficina/equipo/internal/plan3test 2.576s
+FAIL
+```
+
+The same command passed after implementation (exit 0):
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 13.713s
+ok amadan.net/oficina/equipo/internal/plan3test 3.079s
+```
+
+The added interrupted-retirement and local-containment checks also passed:
+
+```sh
+CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorRefusal(InterruptedRetirement|RequiresLocalContainment)$' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/runner 0.168s
+```
+
+### Guard mutations
+
+Each of the 12 mutations was applied separately. Each command exited 1 on the named assertion, and the file was restored immediately. No failure was a build failure. The final targeted tests below ran with every mutation restored. Supplemental interrupted-retirement coverage also demonstrated its red assertion by removing the durable refusal save.
+
+- `early-wait-clear`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorBlockedPollWritesOnlyOnChange/budget_needed$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:48: constraint failed: unchanged poll wrote (1811)`.
+- `unchanged-wait`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorBlockedPollWritesOnlyOnChange/waiting_connection$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:48: constraint failed: unchanged poll wrote (1811)`.
+- `context-limit-park`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorBlockedPollWritesOnlyOnChange/context_limit$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:41: blocked turn offered [{QNQPCGV7WEVANJSKNDTLV34UH4 43PZHNQFJGTYBU2XTXYMLDJNVL request 1 1 context_limit}]`.
+- `filtered-request-park`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFilteredRequestParked/retry$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:111: filtered request not parked`.
+- `filtered-request-poll`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFilteredRequestParked/retry$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:129: constraint failed: unchanged poll wrote (1811)`.
+- `filtered-request-card`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFilteredRequestParked/retry$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:125: filtered request missing person-visible card`.
+- `filtered-request-retry`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFilteredRequestParked/retry$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:141: This record changed. Reload the page and try again.`.
+- `filtered-request-reset`: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFilteredRequestParked/reset$' -count=1`. Exit 1; restored. Assertion: `coordinator_fix2_test.go:148: reset did not release filtered request []`.
+- `recover-refusal`: `CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorRecoveryCallRefusalKeepsServing/recover/403$' -count=1`. Exit 1; restored. Assertion: `coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=`.
+- `containment-refusal`: `CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorRecoveryCallRefusalKeepsServing/containment/403$' -count=1`. Exit 1; restored. Assertion: `coordinator_refusal_test.go:61: coordinator stopped specialist work: ran=false error=`.
+- `refused-offer`: `CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorRecoveryCallRefusalKeepsServing/recover/403$' -count=1`. Exit 1; restored. Assertion: `coordinator_refusal_test.go:91: provider_uncertain`.
+- `durable-refusal`: `CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinatorRefusalInterruptedRetirement$' -count=1`. Exit 1; restored. Assertion: `coordinator_refusal_test.go:133: interrupted retirement repeated refused call`.
+
+### Final verification
+
+All commands below exited 0. Only targeted tests ran. The broader coordinator regression command includes the existing fixture continuity, authority, usage, uncertainty, source scope, waiting and journal upgrade tests:
+
+```sh
+CGO_ENABLED=0 go test ./internal/coordinator ./internal/equipo ./internal/equipo/conversation ./internal/runner ./internal/runner/provider/... ./internal/plan3test -run '^TestCoordinator' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/coordinator 0.027s
+ok amadan.net/oficina/equipo/internal/equipo 0.053s [no tests to run]
+ok amadan.net/oficina/equipo/internal/equipo/conversation 0.003s [no tests to run]
+ok amadan.net/oficina/equipo/internal/runner 37.038s
+ok amadan.net/oficina/equipo/internal/runner/provider 0.005s
+ok amadan.net/oficina/equipo/internal/runner/provider/claude 5.317s
+ok amadan.net/oficina/equipo/internal/runner/provider/codex 7.266s
+ok amadan.net/oficina/equipo/internal/plan3test 23.741s
+```
+
+Final instance rerun after retaining the original claim-time waiting cleanup before snapshot assembly:
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(BlockedPollWritesOnlyOnChange|FilteredRequestParked|ContextLimitParked|ContextBounds|ConnectionWaiting)$' -count=1
+```
+
+```text
+ok amadan.net/oficina/equipo/internal/plan3test 3.478s
+```
+
+```sh
+CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/conversation ./internal/runner ./internal/plan3test
+gofmt -l internal/equipo internal/equipo/conversation internal/runner internal/plan3test
+git diff --check
+```
+
+Vet, formatting and diff checks produced no output. No full suite or `make ci` ran. No migration was needed, so migration-check was not run. No budget exception changed. Counts using the pinned budget tool's line-count rule are: Equipo root 10,798 source / 437 test; conversation 2,445 / 9; runner 9,174 / 8,190; plan3test 442 / 3,078. All fit the existing ceilings. The root has two source lines and the runner ten test lines of remaining headroom. Targeted runner tests measured 37.038s and plan3test 23.741s; these are targeted timings, not full-package measurements.
+
+### Pending user-facing copy
+
+Both entries remain individually marked `COPY REVIEW REQUIRED` in `internal/equipo/copy.go`. No copy-review server or review submission was started. No other user-facing strings were added or changed.
+
+| Key | Draft text |
+| --- | --- |
+| `coordinator.context_unavailable` (new) | Your coordinator can no longer use a source for this request. Reset your coordinator or retry after access is restored. |
+| `coordinator.context_limit` (changed) | The required context is too long for this turn. Reset your coordinator or retry. |
+
+The card reuses existing `coordinator.reset` and `coordinator.retry` labels unchanged. The reports follow plain-writing and humane-docs guidance; this dispatch overrides the general writing pipeline, review-server and handoff-file workflows.
+
+### Self-review and limits
+
+Reviewed the distinction between local containment and remote acceptance, refusal persistence before event retirement, restart behavior between those writes, saved-turn dispatch barriers, independent specialist/coordinator progress, read-only repeated polling, source authorization, reset/retry state transitions and pending copy placement.
+
+Refused containment reporting does not invent remote acceptance or settle an unknown charge. The instance retains its existing unresolved containment/charge state when it refuses the call; the runner preserves local proof for reconciliation. Recovery can retire a lost claim response only because the durable pre-launch claim barrier proves no local process started. Actual local containment failure remains blocking. The new card uses the existing conversation projection; Task 9 still owns its HTML rendering. Production preference persistence remains with Task 8. No live provider, sign-in, enrolment or release certification was attempted.
+
+### Files changed
+
+- `internal/equipo/conversation/context.go`
+- `internal/equipo/conversation/coordinator.go`
+- `internal/equipo/conversation/coordinator_application.go`
+- `internal/equipo/conversation/coordinator_engine.go`
+- `internal/equipo/conversation/coordinator_execution.go`
+- `internal/equipo/conversation/coordinator_poll.go`
+- `internal/equipo/conversation/store.go`
+- `internal/equipo/coordinator_execution.go`
+- `internal/equipo/copy.go`
+- `internal/plan3test/coordinator_fix2_test.go`
+- `internal/runner/coordinator_recovery.go`
+- `internal/runner/coordinator_refusal_test.go`
+- `internal/runner/coordinator_runtime_test.go`
+- `internal/runner/coordinator_service.go`
+- `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md`
+- `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-7-report.md` (ignored report destination)
+
+No README, schema, default branch or release changes. No agents or `.claude/HANDOFF.md`. Go caches stayed at their defaults. Task scratch is under `$TMPDIR/equipo-task7-fix2` and is removed after copying the evidence into both reports. All test commands finished; fixture processes and endpoints close through test cleanup. No task server or watcher remains.
diff --git a/internal/equipo/conversation/context.go b/internal/equipo/conversation/context.go
index d6ba0406..950e63dd 100644
--- a/internal/equipo/conversation/context.go
+++ b/internal/equipo/conversation/context.go
@@ -12,6 +12,8 @@ import (
"gorm.io/gorm"
)
+var errCoordinatorContextUnavailable = errors.New("coordinator_context_unavailable")
+
// ContextSource is supplied by the instance, never by the provider. Task 8 adds
// confirmed preference records through this transaction-bound seam.
type ContextSource func(context.Context, *gorm.DB, CoordinatorClaim) (instructions, decisions, preferences, retrieved []runnerproto.ContextRef, err error)
@@ -53,7 +55,7 @@ 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
+ return out, errCoordinatorContextUnavailable
}
if s.deps.ContextSource != nil {
var err error
diff --git a/internal/equipo/conversation/coordinator.go b/internal/equipo/conversation/coordinator.go
index 7a9610b4..55a19c7f 100644
--- a/internal/equipo/conversation/coordinator.go
+++ b/internal/equipo/conversation/coordinator.go
@@ -163,7 +163,7 @@ func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutatio
if old.Revision != m.Revision {
return out, s.deps.Conflict
}
- if old.State != "context_limit" {
+ if old.State != "context_limit" && old.State != "context_unavailable" {
if old.State != "uncertain" || old.AttemptID == 0 {
return out, s.deps.Conflict
}
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go
index ae942161..b37c80db 100644
--- a/internal/equipo/conversation/coordinator_application.go
+++ b/internal/equipo/conversation/coordinator_application.go
@@ -134,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','context_limit')", 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','context_unavailable')", 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_engine.go b/internal/equipo/conversation/coordinator_engine.go
index 0651d92a..d344ebbf 100644
--- a/internal/equipo/conversation/coordinator_engine.go
+++ b/internal/equipo/conversation/coordinator_engine.go
@@ -13,15 +13,16 @@ type RunnerPrincipal = runnerproto.RunnerPrincipal
type Assignment = runnerproto.Assignment
type RunnerRequest = runnerproto.RunnerRequest
type Engine struct {
- ContextLimit error
- ContextSource ContextSource
- ToolCopy runnerproto.CoordinatorToolCopy
- Tools ToolOperations
- Selection func(*gorm.DB, BindingRecord) (runnerproto.Selection, error)
- CheckProject func(*gorm.DB, string, int64, runnerproto.Selection) (int64, error)
- StoreError func(error) error
- WaitingConnection error
- NotFound error
+ ContextLimit error
+ ContextUnavailable error
+ ContextSource ContextSource
+ ToolCopy runnerproto.CoordinatorToolCopy
+ Tools ToolOperations
+ Selection func(*gorm.DB, BindingRecord) (runnerproto.Selection, error)
+ CheckProject func(*gorm.DB, string, int64, runnerproto.Selection) (int64, error)
+ StoreError func(error) error
+ WaitingConnection error
+ NotFound error
Core *team.Store
Atomic func(context.Context, func(context.Context, *gorm.DB) error) error
diff --git a/internal/equipo/conversation/coordinator_execution.go b/internal/equipo/conversation/coordinator_execution.go
index a9480054..58443a6a 100644
--- a/internal/equipo/conversation/coordinator_execution.go
+++ b/internal/equipo/conversation/coordinator_execution.go
@@ -13,7 +13,7 @@ import (
func decodeCoordinator(raw string, v any) error { return json.Unmarshal([]byte(raw), v) }
func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID string, revision int64) (CoordinatorClaim, error) {
var result CoordinatorClaim
- limited := false
+ var parked error
if revision <= 0 || turnID == "" {
return result, e.Invalid
}
@@ -68,9 +68,19 @@ func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID
}
contextValue, err := e.contextStore(tx).CoordinatorContext(ctx, CoordinatorClaim{Binding: b.CoordinatorBinding, Turn: row.CoordinatorTurn, Brief: runnerproto.RunnerBrief{Selection: sel}})
if errors.Is(err, runnerproto.ErrPromptTooLarge) {
- limited = true
+ parked = e.ContextLimit
+ if parked == nil {
+ parked = runnerproto.ErrPromptTooLarge
+ }
return e.waitCoordinator(tx, b, row, "context_limit")
}
+ if errors.Is(err, errCoordinatorContextUnavailable) {
+ parked = e.ContextUnavailable
+ if parked == nil {
+ parked = e.Invalid
+ }
+ return e.waitCoordinator(tx, b, row, "context_unavailable")
+ }
if err != nil {
return err
}
@@ -150,11 +160,8 @@ func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID
if err != nil {
return CoordinatorClaim{}, err
}
- if limited {
- if e.ContextLimit != nil {
- return CoordinatorClaim{}, e.ContextLimit
- }
- return CoordinatorClaim{}, runnerproto.ErrPromptTooLarge
+ if parked != nil {
+ return CoordinatorClaim{}, parked
}
return result, nil
}
diff --git a/internal/equipo/conversation/coordinator_poll.go b/internal/equipo/conversation/coordinator_poll.go
index 81b6468b..7e875dbc 100644
--- a/internal/equipo/conversation/coordinator_poll.go
+++ b/internal/equipo/conversation/coordinator_poll.go
@@ -29,17 +29,6 @@ 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
@@ -54,7 +43,7 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor
return err
}
for _, row := range rows {
- if row.State == "running" || row.State == "uncertain" || row.State == "context_limit" {
+ if row.State == "running" || row.State == "uncertain" || row.State == "context_limit" || row.State == "context_unavailable" {
continue
}
blocked, err := coordinatorBlocked(tx, row)
@@ -78,15 +67,15 @@ 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")
}
return err
}
+ if err = e.Conversation(tx).clearCoordinatorWaiting(b); err != nil {
+ return err
+ }
out = append(out, row.CoordinatorTurn)
}
return nil
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go
index d763802d..c3c722a4 100644
--- a/internal/equipo/conversation/store.go
+++ b/internal/equipo/conversation/store.go
@@ -65,11 +65,11 @@ func (s *Store) Conversation(actor kernel.Actor, cursor string, limit int) (Conv
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 {
+ if err = s.tx.Where("binding_id=? AND generation=? AND state IN ('context_limit','context_unavailable')", 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"}})
+ page.Cards = append(page.Cards, Card{ID: turn.ID, Kind: "coordinator", ResourceID: turn.ID, Revision: turn.Revision, CopyKey: "coordinator." + turn.State, ActionKeys: []string{"coordinator.reset", "coordinator.retry"}})
}
return page, nil
}
diff --git a/internal/equipo/coordinator_execution.go b/internal/equipo/coordinator_execution.go
index 02af3c60..0e2d5fd5 100644
--- a/internal/equipo/coordinator_execution.go
+++ b/internal/equipo/coordinator_execution.go
@@ -11,7 +11,7 @@ import (
)
func (e *Execution) coordinatorEngine() *conversation.Engine {
- return &conversation.Engine{ContextLimit: &refusal{copyText("coordinator.context_limit"), ErrInvalid}, ToolCopy: CoordinatorToolCopy(), Tools: conversation.ToolOperations{AmbiguousProject: pageCopy["coordinator.project_question"], Planning: e.store.planningAt}, Core: e.Core, Atomic: e.atomic, Selection: e.store.coordinatorSelection, StoreError: storeError, NotFound: ErrNotFound, CheckProject: func(tx *gorm.DB, p string, id int64, sel Selection) (int64, error) {
+ return &conversation.Engine{ContextUnavailable: &refusal{copyText("coordinator.context_unavailable"), ErrInvalid}, ContextLimit: &refusal{copyText("coordinator.context_limit"), ErrInvalid}, ToolCopy: CoordinatorToolCopy(), Tools: conversation.ToolOperations{AmbiguousProject: pageCopy["coordinator.project_question"], Planning: e.store.planningAt}, Core: e.Core, Atomic: e.atomic, Selection: e.store.coordinatorSelection, StoreError: storeError, NotFound: ErrNotFound, CheckProject: func(tx *gorm.DB, p string, id int64, sel Selection) (int64, error) {
project, err := e.store.coordinatorProject(tx, p, id, sel)
return project.Revision, err
}, Conversation: conversationAt, Now: func() time.Time { return e.store.runnerClock.Now().UTC() }, Audit: coordinatorAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, WaitingConnection: errCoordinatorWaitingConnection, Events: e.validators.Events, Receipt: e.validators.Receipt, Containment: e.validators.Containment, Delivery: e.validators.CoordinatorDelivery, Redact: func(raw []byte) []byte { return runner.RedactJSON(raw, nil) },
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index dbdd0f54..72b2d51b 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -244,8 +244,10 @@ var runnerDraftCopy = map[string]string{
"coordinator.waiting_connection": "Waiting for your connection",
// COPY REVIEW REQUIRED: coordinator.waiting_task
"coordinator.waiting_task": "Waiting for %s",
+ // COPY REVIEW REQUIRED: coordinator.context_unavailable
+ "coordinator.context_unavailable": "Your coordinator can no longer use a source for this request. Reset your coordinator or retry after access is restored.",
// COPY REVIEW REQUIRED: coordinator.context_limit
- "coordinator.context_limit": "The required context is too long for this turn. Reset your coordinator or edit the request and retry.",
+ "coordinator.context_limit": "The required context is too long for this turn. Reset your coordinator or 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_fix2_test.go b/internal/plan3test/coordinator_fix2_test.go
new file mode 100644
index 00000000..f5b24b77
--- /dev/null
+++ b/internal/plan3test/coordinator_fix2_test.go
@@ -0,0 +1,166 @@
+package plan3test
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+)
+
+func TestCoordinatorBlockedPollWritesOnlyOnChange(t *testing.T) {
+ for _, reason := range []string{"budget_needed", "waiting_connection", "waiting_task", "context_limit"} {
+ t.Run(reason, func(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ if reason == "waiting_task" {
+ first := queueCoordinator(t, f, "first", "first")
+ c, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision)
+ must(t, err)
+ f.exec(t, "UPDATE coordinator_turns SET state='delivered',attempt_id=0 WHERE id=?", first.ID)
+ f.exec(t, `INSERT INTO runner_assignments(id,task_id,person,state,attempt_id,selection) VALUES('blocking','blocking-task',?,'claimed',?,?)`, owner.Address, c.Handle.Attempt, `{"ConnectionID":"claude"}`)
+ }
+ body := "request"
+ if reason == "context_limit" {
+ body = strings.Repeat("\x00", 16000)
+ }
+ turn := queueCoordinator(t, f, body, "request")
+ switch reason {
+ case "budget_needed":
+ f.exec(t, "DELETE FROM coordinator_limits")
+ case "waiting_connection":
+ f.exec(t, "DELETE FROM connections WHERE id='claude'")
+ case "context_limit":
+ if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil {
+ t.Fatal("oversized context accepted")
+ }
+ }
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 0 {
+ t.Fatal("blocked turn offered", turns)
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state=?", turn.ID, reason) != 1 {
+ t.Fatal("waiting state missing", reason)
+ }
+ assertCoordinatorPollReadOnly(t, f, func() {
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 0 {
+ t.Fatal("blocked turn re-offered", reason)
+ }
+ })
+ if reason == "budget_needed" {
+ must(t, f.Store.SetCoordinatorLimits(ctx, owner, owner.Address, team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000, Seconds: 10000}, equipo.Mutation{RequestID: "restore-limits"}))
+ turns, err = x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 1 || turns[0].ID != turn.ID {
+ t.Fatal("restored budget lost turn", turns)
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_requests WHERE operation='coordinator.waiting'") != 0 {
+ t.Fatal("restored budget retained waiting record")
+ }
+ assertCoordinatorPollReadOnly(t, f, func() {
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 1 {
+ t.Fatal("available turn lost")
+ }
+ })
+ }
+ })
+ }
+}
+
+func assertCoordinatorPollReadOnly(t *testing.T, f *fixture, poll func()) {
+ t.Helper()
+ revision := f.count(t, "SELECT revision FROM conversations WHERE person=?", owner.Address)
+ audit := f.count(t, "SELECT count(*) FROM audit_events")
+ for _, table := range []string{"conversation_requests", "coordinator_turns", "conversations", "audit_events"} {
+ for _, op := range []string{"INSERT", "UPDATE", "DELETE"} {
+ name := "forbid_poll_" + table + "_" + op
+ f.exec(t, fmt.Sprintf("CREATE TRIGGER %s BEFORE %s ON %s BEGIN SELECT RAISE(ABORT,'unchanged poll wrote'); END", name, op, table))
+ defer f.exec(t, "DROP TRIGGER "+name)
+ }
+ }
+ for i := 0; i < 3; i++ {
+ poll()
+ }
+ if got := f.count(t, "SELECT revision FROM conversations WHERE person=?", owner.Address); got != revision {
+ t.Fatal("unchanged poll bumped revision", revision, got)
+ }
+ if got := f.count(t, "SELECT count(*) FROM audit_events"); got != audit {
+ t.Fatal("unchanged poll appended audit", audit, got)
+ }
+}
+
+func TestCoordinatorFilteredRequestParked(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, "request with revoked source", "request")
+ var task string
+ must(t, f.DB.Writer().QueryRow("SELECT id FROM tasks LIMIT 1").Scan(&task))
+ // A routed source is checked during context assembly, after Current succeeds.
+ f.exec(t, "INSERT INTO conversation_routes(source_id,notice_id,task_id) VALUES(?,?,?)", turn.MessageID, turn.MessageID, task)
+ f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`)
+ if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil {
+ t.Fatal("filtered request reached provider")
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='context_unavailable'", turn.ID) != 1 {
+ t.Fatal("filtered request not parked")
+ }
+ if f.count(t, "SELECT count(*) FROM admission_tickets") != 0 {
+ t.Fatal("filtered request admitted")
+ }
+ page, err := f.Store.Conversation(ctx, owner, "", 50)
+ must(t, err)
+ found := false
+ for _, card := range page.Cards {
+ if card.ResourceID == turn.ID && card.CopyKey == "coordinator.context_unavailable" && strings.Join(card.ActionKeys, ",") == "coordinator.reset,coordinator.retry" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("filtered request missing person-visible card")
+ }
+ assertCoordinatorPollReadOnly(t, f, func() {
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 0 {
+ t.Fatal("filtered request re-offered")
+ }
+ if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil {
+ t.Fatal("parked request directly claimed")
+ }
+ })
+ f.exec(t, `UPDATE connection_choices SET connection_ids_json='["claude","codex"]',pinned_id='claude'`)
+ 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 filtered request", turns)
+ }
+ next = turns[0]
+ }
+ c, err := x.ClaimCoordinator(ctx, p, next.ID, next.Revision)
+ must(t, err)
+ if c.Context.Recent[len(c.Context.Recent)-1].ID != turn.MessageID {
+ t.Fatal("retry lost request")
+ }
+ page, err = f.Store.Conversation(ctx, owner, "", 50)
+ must(t, err)
+ for _, card := range page.Cards {
+ if card.CopyKey == "coordinator.context_unavailable" {
+ t.Fatal("resolved card survived")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/runner/coordinator_recovery.go b/internal/runner/coordinator_recovery.go
index cb1a5227..0e20ffad 100644
--- a/internal/runner/coordinator_recovery.go
+++ b/internal/runner/coordinator_recovery.go
@@ -27,7 +27,17 @@ func (s *CoordinatorService) Recover(ctx context.Context) error {
}
var c runnerproto.CoordinatorClaim
if err := s.call(ctx, "recover", q, &c); err != nil {
- return err
+ var refusal *RefusalError
+ if !errors.As(err, &refusal) {
+ return err
+ }
+ // RunTurn saves its claim before creating a namespace. With no saved
+ // claim there can be no local process, even if the server admitted it.
+ r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: runnerproto.CoordinatorTurn{ID: q.TurnID, Revision: q.Revision}}}
+ if err = s.recordRefusal(ctx, &r, "recover", refusal); err != nil {
+ return err
+ }
+ continue
}
if c.Turn.ID == "" {
if _, err := s.Journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='coordinator-claim' AND state_key=?", q.TurnID); err != nil {
@@ -47,6 +57,12 @@ func (s *CoordinatorService) Recover(ctx context.Context) error {
if r.Finished {
continue
}
+ if r.Refused {
+ if err := s.retireCoordinator(ctx, &r); err != nil {
+ return err
+ }
+ continue
+ }
proof, err := s.Contain(ctx, r.Claim)
if err != nil {
return err
@@ -83,20 +99,39 @@ func (s *CoordinatorService) Recover(ctx context.Context) error {
return nil
}
-// Containment must reach the instance even when delivery authority has expired.
+// Report local containment 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 !errors.As(err, &refusal) {
+ return err
+ }
+ r.Containment = &proof
+ return s.recordRefusal(ctx, r, "containment", refusal)
}
var refusal *RefusalError
if deliveryErr != nil && !errors.Is(deliveryErr, provider.ErrUncertain) && !errors.As(deliveryErr, &refusal) {
return deliveryErr
}
if refusal != nil {
- r.Refused = true
+ return s.recordRefusal(ctx, r, "delivery", refusal)
}
+ return s.retireCoordinator(ctx, r)
+}
+
+func (s *CoordinatorService) recordRefusal(ctx context.Context, r *coordinatorState, operation string, refusal *RefusalError) error {
+ r.Refused, r.RefusalOperation, r.RefusalStatus = true, operation, refusal.Status
+ // Save the refusal before acknowledging events, so interrupted retirement
+ // resumes locally without repeating a refused call or sending a prompt.
+ if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil {
+ return err
+ }
+ return s.retireCoordinator(ctx, r)
+}
+
+func (s *CoordinatorService) retireCoordinator(ctx context.Context, r *coordinatorState) error {
if err := s.retirePending(ctx, r.Claim.Turn.ID); err != nil {
return err
}
diff --git a/internal/runner/coordinator_refusal_test.go b/internal/runner/coordinator_refusal_test.go
new file mode 100644
index 00000000..18e019b4
--- /dev/null
+++ b/internal/runner/coordinator_refusal_test.go
@@ -0,0 +1,153 @@
+package runner
+
+import (
+ "context"
+ "errors"
+ "strconv"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type recoveryRefusalAPI struct {
+ *coordinatorAPIStub
+ operation string
+ status int
+ refusedID string
+ refusals, claims int
+ offers []runnerproto.CoordinatorTurn
+}
+
+func (a *recoveryRefusalAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error {
+ id := q.TurnID
+ if q.Claim != nil {
+ id = q.Claim.Turn.ID
+ }
+ if op == a.operation && id == a.refusedID {
+ a.refusals++
+ return &RefusalError{Status: a.status}
+ }
+ if op == "poll" {
+ *out.(*[]runnerproto.CoordinatorTurn) = a.offers
+ return nil
+ }
+ if op == "claim" {
+ a.claims++
+ }
+ return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out)
+}
+func TestCoordinatorRecoveryCallRefusalKeepsServing(t *testing.T) {
+ for _, op := range []string{"recover", "containment"} {
+ for _, status := range []int{401, 403, 409, 422} {
+ t.Run(op+"/"+strconv.Itoa(status), func(t *testing.T) {
+ ctx := context.Background()
+ s, base, launcher, c := coordinatorServiceFixture(t)
+ api := &recoveryRefusalAPI{coordinatorAPIStub: base, operation: op, status: status, refusedID: c.Turn.ID}
+ s.API = api
+ if op == "recover" {
+ mustJournal(t, s.Journal.saveState(ctx, "coordinator-claim", c.Turn.ID, runnerproto.CoordinatorRequest{TurnID: c.Turn.ID, Revision: c.Turn.Revision}))
+ } else {
+ mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, coordinatorState{Claim: c}))
+ }
+ for restart := 0; restart < 2; restart++ {
+ path := s.Journal.path
+ mustJournal(t, s.Journal.Close())
+ var err error
+ s.Journal, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer s.Journal.Close()
+ launcher.j = s.Journal
+ runSpecialistAfterCoordinator(t, s)
+ if api.refusals != 1 {
+ t.Fatal("repeated recovery refusal", api.refusals)
+ }
+ var states []coordinatorState
+ mustJournal(t, s.Journal.readStates(ctx, "coordinator", &states))
+ if len(states) != 1 || !states[0].Refused || !states[0].Finished {
+ t.Fatal("recovery refusal not durably retired", states)
+ }
+ if states[0].RefusalOperation != op || states[0].RefusalStatus != status {
+ t.Fatal("refusal operation/status missing", states[0])
+ }
+ if op == "containment" && (states[0].Containment == nil || states[0].Containment.CheckedAt.IsZero()) {
+ t.Fatal("refused report lost local containment proof")
+ }
+ if err := s.RunTurn(ctx, c); !errors.Is(err, provider.ErrUncertain) {
+ t.Fatal("refused prompt can restart", err)
+ }
+ }
+ if launcher.starts != 0 {
+ t.Fatal("recovery resent prompt", launcher.starts)
+ }
+ // A stale refused offer cannot prevent a later coordinator from running.
+ next := c
+ next.Turn.ID = "next-turn"
+ next.Scope.Job++
+ next.Handle.Attempt++
+ next.Admission.Scope, next.Admission.Handle = next.Scope, next.Handle
+ base.c = next
+ api.offers = []runnerproto.CoordinatorTurn{c.Turn, next.Turn}
+ mustJournal(t, s.Poll(ctx))
+ if api.claims != 1 || launcher.starts != 1 || !base.delivery {
+ t.Fatal("refused offer blocked another coordinator", api.claims, launcher.starts, base.delivery)
+ }
+ })
+ }
+ }
+}
+
+func TestCoordinatorContainmentCallRefusalOnCleanup(t *testing.T) {
+ s, base, launcher, c := coordinatorServiceFixture(t)
+ api := &recoveryRefusalAPI{coordinatorAPIStub: base, operation: "containment", status: 403, refusedID: c.Turn.ID}
+ s.API = api
+ mustJournal(t, s.RunTurn(context.Background(), c))
+ mustJournal(t, s.Recover(context.Background()))
+ if api.refusals != 1 || launcher.starts != 1 {
+ t.Fatal("cleanup repeated refused call or prompt", api.refusals, launcher.starts)
+ }
+}
+
+func TestCoordinatorRefusalInterruptedRetirement(t *testing.T) {
+ ctx := context.Background()
+ s, base, _, c := coordinatorServiceFixture(t)
+ api := &recoveryRefusalAPI{coordinatorAPIStub: base, operation: "containment", status: 403, refusedID: c.Turn.ID}
+ s.API = api
+ mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, coordinatorState{Claim: c}))
+ _, err := s.Journal.db.ExecContext(ctx, `CREATE TRIGGER interrupt_retirement BEFORE INSERT ON journal_supervisor WHEN NEW.kind='coordinator' AND json_extract(NEW.body,'$.Finished')=1 BEGIN SELECT RAISE(ABORT,'interrupted retirement'); END`)
+ mustJournal(t, err)
+ if err := s.Recover(ctx); err == nil {
+ t.Fatal("fixture did not interrupt retirement")
+ }
+ path := s.Journal.path
+ mustJournal(t, s.Journal.Close())
+ s.Journal, err = OpenJournal(ctx, path)
+ mustJournal(t, err)
+ defer s.Journal.Close()
+ _, err = s.Journal.db.ExecContext(ctx, "DROP TRIGGER interrupt_retirement")
+ mustJournal(t, err)
+ mustJournal(t, s.Recover(ctx))
+ var states []coordinatorState
+ mustJournal(t, s.Journal.readStates(ctx, "coordinator", &states))
+ if api.refusals != 1 || len(states) != 1 || !states[0].Finished || !states[0].Refused {
+ t.Fatal("interrupted retirement repeated refused call", api.refusals, states)
+ }
+}
+
+func TestCoordinatorRefusalRequiresLocalContainment(t *testing.T) {
+ s, base, _, c := coordinatorServiceFixture(t)
+ api := &recoveryRefusalAPI{coordinatorAPIStub: base, operation: "containment", status: 403, refusedID: c.Turn.ID}
+ s.API = api
+ s.Contain = func(context.Context, runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) {
+ return runnerproto.ContainmentProof{}, provider.ErrContainment
+ }
+ mustJournal(t, s.Journal.saveState(context.Background(), "coordinator", c.Turn.ID, coordinatorState{Claim: c}))
+ if err := s.Recover(context.Background()); !errors.Is(err, provider.ErrContainment) {
+ t.Fatal("local containment failure ignored", err)
+ }
+ var states []coordinatorState
+ mustJournal(t, s.Journal.readStates(context.Background(), "coordinator", &states))
+ if api.refusals != 0 || states[0].Finished || states[0].Refused {
+ t.Fatal("uncontained turn retired")
+ }
+}
diff --git a/internal/runner/coordinator_runtime_test.go b/internal/runner/coordinator_runtime_test.go
index 1eb7a6d1..336a6aed 100644
--- a/internal/runner/coordinator_runtime_test.go
+++ b/internal/runner/coordinator_runtime_test.go
@@ -180,7 +180,7 @@ func coordinatorServiceFixture(t *testing.T) (*CoordinatorService, *coordinatorA
l.proxy = p
v := provider.Launch{AttemptKey: c.Turn.ID, Binding: provider.Binding{Provider: "claude", AccountID: "account", Expected: provider.Identity{ProviderVersion: "2.1.312"}}, Selection: provider.Selection{Provider: "claude", Family: "claude", AccountID: "account", Model: "model"}, Policy: provider.Policy{Hash: "policy", Manifest: json.RawMessage(`{"Action":"coordinate"}`)}}
v.Policy.ManifestHash = team.ContentDigest(v.Policy.Manifest)
- err := j.recordDirectLaunch(ctx, v, containment.Record{ID: c.Turn.ID, AttemptKey: v.AttemptKey, ManifestHash: "namespace", PolicyHash: v.Policy.Hash})
+ err := s.Journal.recordDirectLaunch(ctx, v, containment.Record{ID: c.Turn.ID, AttemptKey: v.AttemptKey, ManifestHash: "namespace", PolicyHash: v.Policy.Hash})
return v, func() error { return nil }, err
}
return s, a, l, c
diff --git a/internal/runner/coordinator_service.go b/internal/runner/coordinator_service.go
index 0237a1b9..97bd0200 100644
--- a/internal/runner/coordinator_service.go
+++ b/internal/runner/coordinator_service.go
@@ -28,10 +28,13 @@ type CoordinatorService struct {
NamespaceContext func(context.Context, runnerproto.CoordinatorClaim) context.Context
}
type coordinatorState struct {
- Claim runnerproto.CoordinatorClaim
- Session provider.Session
- Finished bool
- Refused bool
+ Claim runnerproto.CoordinatorClaim
+ Session provider.Session
+ Finished bool
+ Refused bool
+ RefusalOperation string
+ RefusalStatus int
+ Containment *runnerproto.ContainmentProof
}
func coordinatorRequest(c runnerproto.CoordinatorClaim) runnerproto.CoordinatorRequest {
@@ -54,6 +57,13 @@ func (s *CoordinatorService) Poll(ctx context.Context) error {
return err
}
for _, turn := range turns {
+ var saved int
+ if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", turn.ID).Scan(&saved); err != nil {
+ return err
+ }
+ if saved != 0 {
+ continue
+ }
q := runnerproto.CoordinatorRequest{TurnID: turn.ID, Revision: turn.Revision}
if err := s.Journal.saveState(ctx, "coordinator-claim", turn.ID, q); err != nil {
return err