feat: admit coordinator turns with person-bound authority
54 files changed,
+2,778
−346
.rastrillo/budgets.txt+3 −3docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+74 −0internal/directlive/driver.go+3 −3internal/directlive/driver_test.go+1 −1internal/equipo/authority.go+3 −0internal/equipo/conversation/coordinator.go+169 −0internal/equipo/conversation/coordinator_api.go+47 −0internal/equipo/conversation/coordinator_application.go+202 −0internal/equipo/conversation/coordinator_authority.go+49 −0internal/equipo/conversation/coordinator_engine.go+45 −0internal/equipo/conversation/coordinator_events.go+196 −0internal/equipo/conversation/coordinator_execution.go+190 −0internal/equipo/conversation/coordinator_poll.go+70 −0internal/equipo/conversation/models.go+1 −1internal/equipo/coordinator.go+138 −0internal/equipo/coordinator_api.go+7 −0internal/equipo/coordinator_authority.go+54 −0internal/equipo/coordinator_execution.go+71 −0internal/equipo/copy.go+18 −0internal/equipo/execution_models.go+11 −1internal/equipo/migrations/0021_coordinator.sql+12 −0internal/equipo/migrations/schema.sql+12 −0internal/equipo/models.go+6 −5internal/equipo/runner_api.go+10 −274internal/equipo/runner_events.go+2 −10internal/equipo/runner_execution_models.go+7 −6internal/equipo/runner_models.go+5 −2internal/equipo/runner_mutations.go+1 −1internal/equipo/team/actions.go+3 −0internal/equipo/team/authority.go+4 −0internal/equipo/team/budget.go+11 −1internal/equipo/team/coordinator.go+188 −0internal/equipo/team/coordinator_test.go+232 −0internal/equipo/team/feature_evidence.go+3 −0internal/equipo/team/harness_test.go+16 −0internal/equipo/team/jobs.go+17 −1internal/equipo/team/model.go+21 −14internal/equipo/team/periodbudget.go+16 −0internal/equipo/team/scheduler.go+12 −0internal/equipo/team/shared.go+1 −0internal/equipo/team/store.go+5 −2internal/equipo/team/subscription_test.go+1 −1internal/equipotest/execution_schema_test.go+16 −12internal/plan3test/coordinator_migration_test.go+56 −0internal/plan3test/coordinator_test.go+322 −0internal/release/manifest.json+12 −0internal/release/manifest_test.go+1 −1internal/runner/provider/actions.go+2 −0internal/runner/provider/claude/launcher.go+1 −1internal/runner/provider/claude/plan_policy_test.go+3 −3internal/runner/provider/codex/plan_policy_test.go+3 −3internal/runnerproto/coordinator.go+56 −0internal/runnerproto/coordinator_handler.go+61 −0internal/runnerproto/handler.go+308 −0
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 96ac46fd..6efd9e8f 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -9,12 +9,12 @@ |
| # time <dir> <duration> <reason> |
| # perf <METHOD> <path> <duration>|skip <reason> |
| # boot <duration> <reason> |
| -size internal/equipo/team 9500 - Task 3 retains fenced evidence registration, current publication approval checks and atomic source validation beside the transaction core. Measured 9088 source and 6353 test lines; tests remain under the default ceiling. Pure answer rules and application approval operations live in taskplan and planning. |
| +size internal/equipo/team 9500 - Task 5 retains coordinator period accounting, fenced delivery and ordered schema upgrades beside the shared core. Measured 9351 source and 6601 test lines. Coordinator application operations live in conversation; targeted tests stay below the existing time ceiling. |
| perf GET /* skip Unknown private paths render 404; this fallback contains no screens. |
| time internal/equipo/team 45s Final fix package rerun measured 29.461s (prior CI 28.271s); 45s gives 52 percent headroom for core migration, recovery and concurrency coverage. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 10800 - Final fixes retain the plan layout and add bounded row-change notifications, aggregate task counts and runner refusal handling; current source count: 9660. |
| +size internal/equipo 10800 - Task 5 keeps the existing ceiling by extracting coordinator operations into conversation and runner HTTP mechanics into runnerproto. Measured 10781 source and 437 test lines; roster, database and execution wiring remain here. |
| size internal/equipotest - 13000 Final finding regressions stay beside the mandated integration fixtures; current test count: 11667. |
| time internal/runner/checks 60s CI worker measured 44.553s (44.6s rounded); 60s gives 34 percent headroom. Shared baseline capture reduces repeated Go runs; retain the CI allowance for sandbox sentinels, timeout and child cleanup. |
| time internal/runner 330s Final corrected package rerun measured 152.897s; review worst 220.6s, interrupted CI 245.239s. 330s exceeds even the interrupted run by 34 percent. Injected-clock lease test measured 8.416s instead of about 65s. |
| @@ -25,5 +25,5 @@ size internal/runner 8000 - Task 4 retains direct journal, proxy, attestation an |
| 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. |
| -time internal/directlive 360s Task 4 expands the fake certification matrix from 7 to 17 cases. The targeted fixture measured 246.910s; 360s leaves 46 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch. |
| +time internal/directlive 360s Task 5 adds both coordinator policy cases to the fake certification matrix. The targeted 19-case fixture measured 287.275s; 360s leaves 25 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch. |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 4e14e4ce..0fa35cac 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -316,3 +316,77 @@ The manifest contains 16 explicitly uncertified constructor inventory hashes. Th |
| Final measured source/test lines: runner 7627/6592 (source cap 8000); equipo 10747/437 (existing source cap 10800); team 9088/6353 (existing source cap 9500); planflow 142/9; plan3test 0/1437; directlive 1673/263. Full-package runtime was not measured under this targeted-only dispatch. |
| Full report and copy inventory: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-4-report.md` (workspace-local, ignored by the repository). No live providers, sign-ins, enrolment, pushes, merges or deployment. No agents or copy-review server were started. |
| + |
| + |
| +## Task 5 |
| + |
| +Status: DONE_WITH_CONCERNS. Coordinator admission is implemented on `plan-3`; live certification and the Task 6/7 tool/runtime integration remain pending. The local full report is `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-5-report.md`. |
| + |
| +The implementation uses the existing core ledger and write transaction. Conversation owns bindings/turns/questions; the core owns versioned personal limits. Migration 0021 and core schema version 8 agree. A unique active-turn index and ordered queue prevent concurrent turns for one person/team. Current roster, runner, connection, generation and claim identity are checked before claim/renew/tool use. Reset fences first and advances only after containment. Retry requires recorded uncertainty and containment and gets a fresh admission. Completion requires trusted durable-delivery validation and commits message, outbox, usage, completion and audit together. |
| + |
| +The initial context contains only the admitted message and permitted project labels. Explicit project material requires the current project connection allowlist/pin and revision. Additional provider-family policy and richer classified history remain integration requirements for later tasks. The coordinator provider policies are recorded as uncertified and cannot reuse existing certificates. |
| + |
| +### Commands and results |
| + |
| +`CGO_ENABLED=0 go test ./internal/equipo/team ./internal/plan3test -run '^TestCoordinator(Single|Authority|Budget|NoProject|Turn)' -count=1` |
| + |
| +Initial red: exit 1, missing coordinator APIs/types/limits. Final green after restoration and deadline fix: exit 0, team 0.363s and plan3test 2.878s. |
| + |
| +`CGO_ENABLED=0 go test ./internal/equipo/team ./internal/plan3test ./internal/equipotest -run '^(TestCoordinatorMigration|TestPlanWorkflowRecommendationDelivery|TestPlanWorkflowInvestigationCheckpoint|TestPlanMigrationUpgrade|TestConversationMigrationUpgrade|TestPeriodBudgetReservations|TestBoundedTurnReservation|TestUnknownUsageStillCharged|TestUnknownChargesStayInTheirMonth|TestOpenChargesStayInTheirMonth|TestMixedConnectionPolicies|TestSubscriptionPolicy|TestExecutionSchemaParity|TestRunnerAppCSRF|TestRunnerEventReplayHTTP|TestDirectReleaseRequiresCertification)' -count=1` |
| + |
| +Exit 0: team 1.564s, plan3test 2.650s, equipotest 6.806s. Includes standalone/app/core upgrades, recommendation delivery, period accounting and existing runner bearer/CSRF behavior. |
| + |
| +`CGO_ENABLED=0 go test ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/release -run '^TestPlanWorkflow(ProviderPolicies|Release)' -count=1` |
| + |
| +Initial red: exit 1, coordinate profile rejected, then missing inventory hashes. Final exit 0: Claude 4.166s, Codex 2.605s, release 0.014s. |
| + |
| +`CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/conversation ./internal/equipo/team ./internal/runnerproto ./internal/plan3test ./internal/equipotest ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex ./internal/release ./internal/directlive` |
| + |
| +Exit 0 on all touched packages. An unkeyed RunnerPrincipal literal exposed by the new protocol alias was made explicit. |
| + |
| +`gofmt -l internal/equipo internal/runnerproto internal/plan3test internal/equipotest internal/runner/provider internal/release internal/directlive` |
| + |
| +Exit 0, no output. |
| + |
| +`make migration-check`: exit 0 (`TestMigrationModels`, 0.298s). |
| + |
| +`make budget`: exit 0, 29 directories within budget. Root remains at 10,781/10,800 source lines; core is 9,351/9,500. Test lines: root 437, core 6,601. No ceilings were raised. Initial root size failures were resolved by moving coordinator application operations to conversation and protocol HTTP mechanics to runnerproto. |
| + |
| +`CGO_ENABLED=0 go test ./internal/directlive -run '^TestDirectDriverFakeCLI$' -count=1`: first exit 1 (214.260s), because the fixture could not exercise an empty Claude native-tool inventory. The final profile uses the existing read-only native surface. Rerun exit 0 (287.275s), all 19 fake cases. Production driver edits only add role/action case mappings. The recorded fake-driver test count and its existing time-exception measurement were updated. No live provider invocation or production certificate was used. |
| + |
| +`git diff --check`: exit 0. |
| + |
| +The schema parity fixture originally failed because 0020 was applied before tasks existed and the comparison omitted coordinator_limits. Its upgrade sets now include 0020/0021, the comparison includes the new core-owned table, and versions 1 through 8 are tested. Version-2 execution fixtures now configure explicit project budgets; their old account-fallback expectation was updated to the required budget refusal. All listed regression commands passed after these fixes. |
| + |
| +Additional red/green checks: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorTurnDeliveryAtomic$' -count=1`: exit 1, `unclassified prior project material entered coordinator context`; after narrowing seed context, exit 0 (0.439s). |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorTurnResetPreservesQueuedMessages$' -count=1`: exit 1, `reset lost queued messages []`; after generation-specific requeue of superseded unclaimed messages, exit 0 (0.667s). |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorTurnReplay$' -count=1`: exit 1, `coordinator brief omitted attempt deadline`; after projecting actual core deadlines into claim and brief, the exact named command above passed. |
| +- `CGO_ENABLED=0 go test ./internal/equipo/team ./internal/plan3test -run '^TestCoordinator(Migration|SingleWriterStorage)' -count=1`: the storage guard initially exited 1, `storage permits two active coordinator turns`; adding the partial unique index made it pass. The app-upgrade fixture was also corrected to update its existing service singleton. The final regression command covers both upgrade paths. |
| + |
| +### Guard mutations |
| + |
| +The implementation was broken one guard at a time and restored after each command. The final named command passed after all restorations. |
| + |
| +- storage uniqueness: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorSingleWriterStorageGuard$ -count=1`; exit 1; `coordinator_test.go:261: storage permits two active coordinator turns BUIYV7RIJWEBW33U2ETYVDZY27`; restored. |
| +- generation: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAuthorityRevoked/generation$ -count=1`; exit 1; `coordinator_test.go:99: tool use ignored revoked authority`; restored. |
| +- membership: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAuthorityRevoked/membership$ -count=1`; exit 1; `coordinator_test.go:99: tool use ignored revoked authority`; restored. |
| +- role revision: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAuthorityRevoked/role$ -count=1`; exit 1; `internal/equipo/coordinator.go:22:2: declared and not used: m`; restored. |
| +- team reservation: `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestCoordinatorBudgetSharesTeamProjectFirst$ -count=1`; exit 1; `coordinator_test.go:196: want budget, got nil`; restored. |
| +- target operation: `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestCoordinatorNoProjectBudgetBypass$ -count=1`; exit 1; `coordinator_test.go:24: coordinate capability permits forge`; restored. |
| +- delivery proof: `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestCoordinatorNoProjectBudgetBypass$ -count=1`; exit 1; `coordinator_test.go:53: process completion proved delivery`; restored. |
| +- replay input: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorTurnReplay$ -count=1`; exit 1; `coordinator_test.go:121: changed message replay accepted`; restored. |
| +- reset containment: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorTurnReplay$ -count=1`; exit 1; `coordinator_test.go:139: reset advanced before containment`; restored. |
| +- claim integrity: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAuthorityClaimTampering$ -count=1`; exit 1; `coordinator_test.go:296: changed claim authorized tool use`; restored. |
| +- capability negotiation: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAuthorityCapabilityNegotiation$ -count=1`; exit 1; `coordinator_test.go:277: old runner received coordinator work 200`; restored. |
| +- release certification: `CGO_ENABLED=0 go test ./internal/release -run ^TestPlanWorkflowReleaseRejectsOldCertificate$ -count=1`; exit 1; `manifest_test.go:98: old certificate enabled changed inventory reproduce`; restored. |
| +- role revision (compiling mutation): `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorAuthorityRevoked/role$ -count=1`; exit 1; `coordinator_test.go:99: tool use ignored revoked authority`; restored. |
| + |
| +The first role-revision mutation only caused a compile error and is not behavioral evidence. Its compiling replacement failed the intended authority assertion. All 12 semantic mutations failed their named assertions. |
| + |
| +### Handoff boundaries |
| + |
| +Tasks 6/7 must supply the durable tool-effect delivery validator, richer policy-filtered context, provider journal/runtime wiring and task-wait behavior without holding a lease. The default delivery validator is absent and refuses completion. The initial subscription lane and read-only action inventories do not enable live work. Paul's new live certification is still required, and Task 6's expanded tool inventory will require new hashes again. Historical version-1 standalone account-policy fixtures remain compatible; current runner version-2 jobs require positive configured projects unless their target is conversation. |
| + |
| +New copy is individually pending in copy.go and listed with draft text in the full report. README prose was unchanged. No subagents, copy-review server, live sign-in, enrolment, push, merge, deployment or handoff file. Go caches stayed at defaults. No server was started. Task-owned scratch was removed. |
diff --git a/internal/directlive/driver.go b/internal/directlive/driver.go| index 7814897f..78abdf3a 100644 |
| --- a/internal/directlive/driver.go |
| +++ b/internal/directlive/driver.go |
| @@ -76,7 +76,7 @@ func run(ctx context.Context, c provider.DirectLiveConfig, config []byte, p Path |
| var records []provider.DirectEvidence |
| var failures []error |
| for _, b := range c.Bindings { |
| - for _, role := range []string{"Engineering", "Engineering-reproduction", "Review", "Product", "Scope", "Research", "Investigation", "Copy", "Design"} { |
| + for _, role := range []string{"Engineering", "Engineering-reproduction", "Review", "Product", "Scope", "Research", "Investigation", "Copy", "Design", "Coordinator"} { |
| if b.Binding.Provider == "codex" && role == "Product" { |
| continue |
| } |
| @@ -235,8 +235,8 @@ func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, rol |
| if err != nil { |
| return e, err |
| } |
| - step := map[string]string{"Engineering": "implement", "Engineering-reproduction": "reproduce", "Review": "review", "Product": "reproduce", "Scope": "scope", "Research": "recommend", "Investigation": "investigate", "Copy": "copy", "Design": "design"}[role] |
| - tool := map[string]string{"implement": "submit_candidate", "reproduce": "submit_reproduction", "review": "submit_review", "scope": "submit_acceptance", "recommend": "submit_answer", "investigate": "submit_answer", "copy": "submit_candidate", "design": "submit_candidate"}[step] |
| + step := map[string]string{"Engineering": "implement", "Engineering-reproduction": "reproduce", "Review": "review", "Product": "reproduce", "Scope": "scope", "Research": "recommend", "Investigation": "investigate", "Copy": "copy", "Design": "design", "Coordinator": "coordinate"}[role] |
| + tool := map[string]string{"implement": "submit_candidate", "reproduce": "submit_reproduction", "review": "submit_review", "scope": "submit_acceptance", "recommend": "submit_answer", "investigate": "submit_answer", "copy": "submit_candidate", "design": "submit_candidate", "coordinate": "submit_answer"}[step] |
| selection := provider.Selection{ConnectionID: b.Binding.ID, Provider: binding.Provider, Family: map[string]string{"claude": "claude", "codex": "gpt"}[binding.Provider], AccountID: binding.AccountID, Model: b.Model} |
| in, err := runner.CertificationInputs(ctx, d.policyPaths.config(d.paths), selection, binding, d.cfg.Repository, step, policyScratch) |
| if err != nil { |
diff --git a/internal/directlive/driver_test.go b/internal/directlive/driver_test.go| index 6f9b1177..e19ce281 100644 |
| --- a/internal/directlive/driver_test.go |
| +++ b/internal/directlive/driver_test.go |
| @@ -142,7 +142,7 @@ func TestDirectDriverFakeWorker(t *testing.T) { |
| t.Fatal(err) |
| } |
| var index []string |
| - if json.Unmarshal(raw, &index) != nil || len(index) != 17 { |
| + if json.Unmarshal(raw, &index) != nil || len(index) != 19 { |
| t.Fatal("missing driver coverage") |
| } |
| for _, name := range index { |
diff --git a/internal/equipo/authority.go b/internal/equipo/authority.go| index ed7bba54..05bc77f0 100644 |
| --- a/internal/equipo/authority.go |
| +++ b/internal/equipo/authority.go |
| @@ -66,6 +66,9 @@ func (a *RosterAuthority) Introspect(ctx context.Context, req team.AdmissionRequ |
| if err := ctx.Err(); err != nil { |
| return team.Admission{}, fmt.Errorf("%w: %w", team.ErrAuthorityUnavailable, err) |
| } |
| + if req.Target.Kind == team.TargetConversation { |
| + return a.coordinator(ctx, req) |
| + } |
| grant, err := parseGrantReference(req.Grant) |
| if err != nil { |
| return team.Admission{}, err |
diff --git a/internal/equipo/conversation/coordinator.go b/internal/equipo/conversation/coordinator.go| new file mode 100644 |
| index 00000000..d637fe7f |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator.go |
| @@ -0,0 +1,169 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| + "math" |
| +) |
| + |
| +type CoordinatorBinding = runnerproto.CoordinatorBinding |
| +type CoordinatorTurn = runnerproto.CoordinatorTurn |
| +type CoordinatorContext = runnerproto.CoordinatorContext |
| + |
| +type BindingRecord struct { |
| + CoordinatorBinding `gorm:"embedded"` |
| + TeamID string `gorm:"uniqueIndex:coordinator_person,priority:1"` |
| + PersonKey string `gorm:"uniqueIndex:coordinator_person,priority:2"` |
| + MemberRevision, ConnectionRevision int64 |
| +} |
| + |
| +func (BindingRecord) TableName() string { return "coordinator_bindings" } |
| + |
| +type TurnRecord struct { |
| + CoordinatorTurn `gorm:"embedded"` |
| + TeamID string `gorm:"uniqueIndex:coordinator_active,priority:1,where:state='running'"` |
| + Person string `gorm:"uniqueIndex:coordinator_active,priority:2,where:state='running'"` |
| + BindingID, ConversationID string |
| + Sequence, ProjectID, ProjectRevision, MemberRevision, ConnectionRevision int64 |
| + Claim, Selection, InputHash, DeliveryHash, SessionID string |
| + JobID, AttemptID, Fence int64 |
| +} |
| + |
| +func (TurnRecord) TableName() string { return "coordinator_turns" } |
| + |
| +type QuestionRecord struct { |
| + ID string `gorm:"primaryKey"` |
| + BindingID, TurnID, Person, RequestID, State, Payload string |
| + Generation, Revision int64 |
| +} |
| + |
| +func (QuestionRecord) TableName() string { return "coordinator_questions" } |
| +func (s *Store) Binding(actor kernel.Actor) (BindingRecord, error) { |
| + teamID, err := s.deps.Authorize(s.tx, actor) |
| + if err != nil { |
| + return BindingRecord{}, err |
| + } |
| + var b BindingRecord |
| + err = s.tx.Where("team_id=? AND person_key=?", teamID, actor.Address).First(&b).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return b, s.deps.NotFound |
| + } |
| + return b, err |
| +} |
| +func (s *Store) CoordinatorReplay(actor kernel.Actor, op, resource string, m kernel.Mutation, input, out any) (bool, error) { |
| + if !m.Valid() { |
| + return false, s.deps.Invalid |
| + } |
| + if _, err := s.deps.Authorize(s.tx, actor); err != nil { |
| + return false, err |
| + } |
| + hash, err := kernel.InputHash(input) |
| + if err != nil { |
| + return false, err |
| + } |
| + var old requestRecord |
| + err = s.tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", actor.Address, op, resource, m.RequestID).First(&old).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return false, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + if old.InputHash != hash { |
| + return false, s.deps.Conflict |
| + } |
| + return true, json.Unmarshal([]byte(old.Result), out) |
| +} |
| +func (s *Store) SaveCoordinatorResult(actor kernel.Actor, op, resource string, m kernel.Mutation, input, result any) error { |
| + hash, err := kernel.InputHash(input) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(result) |
| + if err != nil { |
| + return err |
| + } |
| + return s.tx.Create(&requestRecord{Principal: actor.Address, Operation: op, Resource: resource, RequestID: m.RequestID, InputHash: hash, Result: string(raw)}).Error |
| +} |
| +func (s *Store) QueueCoordinator(actor kernel.Actor, messageID string, project int64, m kernel.Mutation) (CoordinatorTurn, error) { |
| + b, err := s.Binding(actor) |
| + if err != nil { |
| + return CoordinatorTurn{}, err |
| + } |
| + input := struct { |
| + Message, Binding string |
| + Generation, Project, Revision int64 |
| + }{messageID, b.ID, b.Generation, project, m.Revision} |
| + var out CoordinatorTurn |
| + if ok, err := s.CoordinatorReplay(actor, "coordinator.queue", actor.Address, m, input, &out); ok || err != nil { |
| + return out, err |
| + } |
| + var msg messageRecord |
| + if err = s.tx.Where("id=? AND author_kind='person' AND author_id=? AND conversation_id<>''", messageID, actor.Address).First(&msg).Error; err != nil { |
| + return out, err |
| + } |
| + var main Main |
| + if err = s.tx.Where("id=? AND team_id=? AND person=?", msg.ConversationID, b.TeamID, actor.Address).First(&main).Error; err != nil { |
| + return out, err |
| + } |
| + var old TurnRecord |
| + err = s.tx.Where("message_id=? AND state<>'superseded'", messageID).First(&old).Error |
| + if err == nil { |
| + return old.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.queue", actor.Address, m, input, old.CoordinatorTurn) |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return out, err |
| + } |
| + hash, err := kernel.InputHash(input) |
| + if err != nil { |
| + return out, err |
| + } |
| + row := TurnRecord{CoordinatorTurn: CoordinatorTurn{ID: rand.Text(), MessageID: messageID, RequestID: m.RequestID, Generation: b.Generation, Revision: 1, State: "queued"}, TeamID: b.TeamID, Person: actor.Address, BindingID: b.ID, ConversationID: msg.ConversationID, Sequence: msg.Sequence, ProjectID: project, MemberRevision: b.MemberRevision, ConnectionRevision: b.ConnectionRevision, InputHash: hash} |
| + if err = s.tx.Create(&row).Error; err != nil { |
| + return out, err |
| + } |
| + return row.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.queue", actor.Address, m, input, row.CoordinatorTurn) |
| +} |
| +func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutation) (CoordinatorTurn, error) { |
| + b, err := s.Binding(actor) |
| + if err != nil { |
| + return CoordinatorTurn{}, err |
| + } |
| + input := struct { |
| + ID string |
| + Revision int64 |
| + }{id, m.Revision} |
| + var out CoordinatorTurn |
| + if ok, err := s.CoordinatorReplay(actor, "coordinator.retry", id, m, input, &out); ok || err != nil { |
| + return out, err |
| + } |
| + var old TurnRecord |
| + 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 { |
| + 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 |
| + } |
| + if err = s.tx.Model(&TurnRecord{}).Where("id=?", id).Select("state", "revision").Updates(map[string]any{"state": "superseded", "revision": old.Revision + 1}).Error; err != nil { |
| + return out, err |
| + } |
| + row := TurnRecord{CoordinatorTurn: CoordinatorTurn{ID: rand.Text(), MessageID: old.MessageID, RequestID: m.RequestID, Generation: b.Generation, Revision: 1, State: "queued"}, TeamID: b.TeamID, Person: actor.Address, BindingID: b.ID, ConversationID: old.ConversationID, Sequence: old.Sequence, ProjectID: old.ProjectID, MemberRevision: b.MemberRevision, ConnectionRevision: b.ConnectionRevision} |
| + if err = s.tx.Create(&row).Error; err != nil { |
| + return out, err |
| + } |
| + return row.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.retry", id, m, input, row.CoordinatorTurn) |
| +} |
diff --git a/internal/equipo/conversation/coordinator_api.go b/internal/equipo/conversation/coordinator_api.go| new file mode 100644 |
| index 00000000..2a590a24 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_api.go |
| @@ -0,0 +1,47 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +// CoordinatorContextFor supplies only the admitted message. Task 7 may extend |
| +// context once prior material can be checked against current project policy. |
| +func (s *Store) CoordinatorContextFor(row TurnRecord) (CoordinatorContext, error) { |
| + actor := kernel.Actor{Address: row.Person} |
| + if _, err := s.deps.Authorize(s.tx, actor); err != nil { |
| + return CoordinatorContext{}, err |
| + } |
| + var main Main |
| + if err := s.tx.Where("id=? AND person=? AND team_id=?", row.ConversationID, row.Person, row.TeamID).First(&main).Error; err != nil { |
| + return CoordinatorContext{}, err |
| + } |
| + var messages []messageRecord |
| + if err := s.tx.Where("id=? AND conversation_id=? AND sequence=? AND author_kind='person' AND author_id=?", row.MessageID, main.ID, row.Sequence, row.Person).Find(&messages).Error; err != nil { |
| + return CoordinatorContext{}, err |
| + } |
| + if len(messages) != 1 { |
| + return CoordinatorContext{}, s.deps.NotFound |
| + } |
| + out := CoordinatorContext{ConversationID: main.ID, Revision: main.Revision, Messages: []runnerproto.CoordinatorMessage{}} |
| + size := 0 |
| + for i := len(messages) - 1; i >= 0; i-- { |
| + msg := messages[i] |
| + size += len(msg.Body) |
| + if size > 16384 { |
| + return out, s.deps.Invalid |
| + } |
| + out.Messages = append(out.Messages, runnerproto.CoordinatorMessage{ID: msg.ID, AuthorKind: msg.AuthorKind, AuthorID: msg.AuthorID, Body: msg.Body, Sequence: msg.Sequence, Revision: msg.Revision}) |
| + } |
| + return out, nil |
| +} |
| +func (s *Store) DeliverCoordinator(row TurnRecord, body string) error { |
| + if len(body) == 0 || len(body) > 16384 { |
| + return s.deps.Invalid |
| + } |
| + if _, err := s.deps.Authorize(s.tx, kernel.Actor{Address: row.Person}); err != nil { |
| + return err |
| + } |
| + _, err := s.appendMessage(row.ConversationID, row.ConversationID, "", "coordinator", "coordinator:"+row.BindingID, body, "delivery") |
| + return err |
| +} |
diff --git a/internal/equipo/conversation/coordinator_application.go b/internal/equipo/conversation/coordinator_application.go| new file mode 100644 |
| index 00000000..401d59f4 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_application.go |
| @@ -0,0 +1,202 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "crypto/rand" |
| + "errors" |
| + "gorm.io/gorm" |
| + "math" |
| +) |
| + |
| +type Actor = kernel.Actor |
| +type Mutation = kernel.Mutation |
| +type Application struct { |
| + Core *team.Store |
| + Write func(context.Context, func(*gorm.DB) error) error |
| + Conversation func(*gorm.DB) *Store |
| + Normalize func(string) string |
| + BindingIdentity func(*gorm.DB, Actor, string, string) (int64, int64, error) |
| + LimitsAuthority func(*gorm.DB, Actor, string) error |
| + Audit func(*gorm.DB, Actor, string, string) error |
| + Invalid, Conflict, Forbidden, Unavailable, NotFound error |
| +} |
| + |
| +func (s *Application) Coordinator(ctx context.Context, actor Actor) (CoordinatorBinding, error) { |
| + var b BindingRecord |
| + err := s.Write(ctx, func(tx *gorm.DB) error { var err error; b, err = s.Conversation(tx).Binding(actor); return err }) |
| + return b.CoordinatorBinding, err |
| +} |
| +func (s *Application) SaveCoordinatorBinding(ctx context.Context, actor Actor, runnerID, connectionID string, m Mutation) (CoordinatorBinding, error) { |
| + return s.changeCoordinator(ctx, actor, runnerID, connectionID, false, m) |
| +} |
| +func (s *Application) ResetCoordinator(ctx context.Context, actor Actor, m Mutation) (CoordinatorBinding, error) { |
| + return s.changeCoordinator(ctx, actor, "", "", true, m) |
| +} |
| +func (s *Application) changeCoordinator(ctx context.Context, actor Actor, runnerID, connectionID string, reset bool, m Mutation) (CoordinatorBinding, error) { |
| + actor.Address = s.Normalize(actor.Address) |
| + var result CoordinatorBinding |
| + pending := false |
| + op := "coordinator.bind" |
| + if reset { |
| + op = "coordinator.reset" |
| + } |
| + input := struct { |
| + Runner, Connection string |
| + Reset bool |
| + Revision int64 |
| + }{runnerID, connectionID, reset, m.Revision} |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + ctx := tx.Statement.Context |
| + teamID, err := s.Conversation(tx).deps.Authorize(tx, actor) |
| + if err != nil { |
| + return err |
| + } |
| + cs := s.Conversation(tx) |
| + if ok, err := cs.CoordinatorReplay(actor, op, actor.Address, m, input, &result); ok || err != nil { |
| + return err |
| + } |
| + b, err := cs.Binding(actor) |
| + exists := err == nil |
| + if err != nil && !errors.Is(err, s.NotFound) { |
| + return err |
| + } |
| + if (!exists && reset) || m.Revision != b.Revision { |
| + return s.Conflict |
| + } |
| + if reset { |
| + runnerID, connectionID = b.RunnerID, b.ConnectionID |
| + } |
| + memberRevision, connectionRevision, err := s.BindingIdentity(tx, actor, runnerID, connectionID) |
| + if err != nil { |
| + return err |
| + } |
| + var turns []TurnRecord |
| + if exists { |
| + if err = tx.Where("binding_id=? AND job_id>0 AND state<>'superseded'", b.ID).Find(&turns).Error; err != nil { |
| + return err |
| + } |
| + for _, turn := range turns { |
| + if s.Core == nil { |
| + return s.Unavailable |
| + } |
| + scope := team.Scope{Account: team.AccountID(teamID), Job: team.JobID(turn.JobID)} |
| + job, err := s.Core.GetJob(ctx, scope) |
| + if err != nil { |
| + return err |
| + } |
| + if !job.State.Terminal() { |
| + if _, err = s.Core.Cancel(ctx, scope, actor.Address, op); err != nil { |
| + return err |
| + } |
| + } |
| + var n int64 |
| + if err = tx.Table("attempts").Where("job_id=? AND containment='pending'", turn.JobID).Count(&n).Error; err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + pending = true |
| + } |
| + if turn.State != "delivered" { |
| + if err = tx.Model(&TurnRecord{}).Where("id=? AND state<>'uncertain'", turn.ID).Select("state", "revision").Updates(map[string]any{"state": "uncertain", "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + } |
| + if pending { |
| + return s.Audit(tx, actor, op+".containment", b.ID) |
| + } |
| + if b.Generation == math.MaxInt64 || b.Revision == math.MaxInt64 { |
| + return s.Conflict |
| + } |
| + if !exists { |
| + b.ID = rand.Text() |
| + b.TeamID = teamID |
| + b.PersonKey = actor.Address |
| + b.Person = actor.Address |
| + } |
| + b.RunnerID, b.ConnectionID = runnerID, connectionID |
| + b.Generation++ |
| + b.Revision++ |
| + b.MemberRevision = memberRevision |
| + b.ConnectionRevision = connectionRevision |
| + if exists { |
| + err = tx.Model(&BindingRecord{}).Where("id=?", b.ID).Select("runner_id", "connection_id", "generation", "revision", "member_revision", "connection_revision").Updates(&b).Error |
| + } else { |
| + err = tx.Create(&b).Error |
| + } |
| + 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 { |
| + return err |
| + } |
| + result = b.CoordinatorBinding |
| + if err = s.Audit(tx, actor, op, b.ID); err != nil { |
| + return err |
| + } |
| + return cs.SaveCoordinatorResult(actor, op, actor.Address, m, input, result) |
| + }) |
| + if err == nil && pending { |
| + err = s.Conflict |
| + } |
| + return result, err |
| +} |
| +func (s *Application) QueueCoordinatorTurn(ctx context.Context, actor Actor, messageID string, projectID int64, m Mutation) (CoordinatorTurn, error) { |
| + var out CoordinatorTurn |
| + if projectID < 0 { |
| + return out, s.Invalid |
| + } |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + var err error |
| + out, err = s.Conversation(tx).QueueCoordinator(actor, messageID, projectID, m) |
| + return err |
| + }) |
| + return out, err |
| +} |
| +func (s *Application) RetryCoordinatorTurn(ctx context.Context, actor Actor, id string, m Mutation) (CoordinatorTurn, error) { |
| + var out CoordinatorTurn |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + var err error |
| + out, err = s.Conversation(tx).RetryCoordinator(actor, id, m) |
| + if err != nil { |
| + return err |
| + } |
| + return s.Audit(tx, actor, "coordinator.retry", out.ID) |
| + }) |
| + return out, err |
| +} |
| +func (s *Application) SetCoordinatorLimits(ctx context.Context, actor Actor, person string, limits team.Limits, m Mutation) error { |
| + if s.Core == nil { |
| + return s.Unavailable |
| + } |
| + person = s.Normalize(person) |
| + input := struct { |
| + Person string |
| + Limits team.Limits |
| + Revision int64 |
| + }{person, limits, m.Revision} |
| + return s.Write(ctx, func(tx *gorm.DB) error { |
| + if err := s.LimitsAuthority(tx, actor, person); err != nil { |
| + return err |
| + } |
| + teamID, err := s.Conversation(tx).deps.Authorize(tx, actor) |
| + if err != nil { |
| + return err |
| + } |
| + var result bool |
| + cs := s.Conversation(tx) |
| + if ok, err := cs.CoordinatorReplay(actor, "coordinator.limits", person, m, input, &result); ok || err != nil { |
| + return err |
| + } |
| + if err = s.Core.ConfigureCoordinatorLimits(tx.Statement.Context, team.AccountID(teamID), person, m.Revision, limits); err != nil { |
| + return err |
| + } |
| + if err = s.Audit(tx, actor, "coordinator.limits", person); err != nil { |
| + return err |
| + } |
| + return cs.SaveCoordinatorResult(actor, "coordinator.limits", person, m, input, true) |
| + }) |
| +} |
diff --git a/internal/equipo/conversation/coordinator_authority.go b/internal/equipo/conversation/coordinator_authority.go| new file mode 100644 |
| index 00000000..3151f0b7 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_authority.go |
| @@ -0,0 +1,49 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (e *Engine) Current(ctx context.Context, tx *gorm.DB, p RunnerPrincipal, id string) (BindingRecord, TurnRecord, runnerproto.Selection, error) { |
| + var b BindingRecord |
| + var row TurnRecord |
| + var sel runnerproto.Selection |
| + if err := e.RunnerCurrent(tx, p); err != nil { |
| + return b, row, sel, err |
| + } |
| + if err := tx.Where("id=? AND person=?", id, p.Person).First(&row).Error; err != nil { |
| + return b, row, sel, e.StoreError(err) |
| + } |
| + if err := tx.First(&b, "id=? AND team_id=? AND person=?", row.BindingID, row.TeamID, p.Person).Error; err != nil { |
| + return b, row, sel, e.StoreError(err) |
| + } |
| + if b.RunnerID != p.RunnerID || b.Generation != row.Generation || b.MemberRevision != row.MemberRevision || b.ConnectionRevision != row.ConnectionRevision { |
| + return b, row, sel, e.Forbidden |
| + } |
| + var err error |
| + sel, err = e.Selection(tx, b) |
| + if err != nil { |
| + return b, row, sel, err |
| + } |
| + if row.Selection != "" { |
| + var saved runnerproto.Selection |
| + if err = decodeCoordinator(row.Selection, &saved); err != nil { |
| + return b, row, sel, err |
| + } |
| + if saved.ConnectionID != sel.ConnectionID || saved.Provider != sel.Provider || saved.Model != sel.Model || saved.AccountID != sel.AccountID || saved.Revision != sel.Revision { |
| + return b, row, sel, e.Forbidden |
| + } |
| + } |
| + if row.ProjectID > 0 { |
| + project, err := e.CheckProject(tx, p.Person, row.ProjectID, sel) |
| + if err != nil { |
| + return b, row, sel, err |
| + } |
| + if row.ProjectRevision > 0 && project != row.ProjectRevision { |
| + return b, row, sel, e.Conflict |
| + } |
| + } |
| + return b, row, sel, nil |
| +} |
diff --git a/internal/equipo/conversation/coordinator_engine.go b/internal/equipo/conversation/coordinator_engine.go| new file mode 100644 |
| index 00000000..c54a8c31 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_engine.go |
| @@ -0,0 +1,45 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "gorm.io/gorm" |
| + "time" |
| +) |
| + |
| +type CoordinatorClaim = runnerproto.CoordinatorClaim |
| +type RunnerPrincipal = runnerproto.RunnerPrincipal |
| +type Assignment = runnerproto.Assignment |
| +type RunnerRequest = runnerproto.RunnerRequest |
| +type Engine struct { |
| + Selection func(*gorm.DB, BindingRecord) (runnerproto.Selection, error) |
| + CheckProject func(*gorm.DB, string, int64, runnerproto.Selection) (int64, error) |
| + StoreError func(error) error |
| + NotFound error |
| + |
| + Core *team.Store |
| + Atomic func(context.Context, func(context.Context, *gorm.DB) error) error |
| + Conversation func(*gorm.DB) *Store |
| + Projects func(*gorm.DB, string, runnerproto.Selection) ([]runnerproto.CoordinatorProject, error) |
| + Project func(*gorm.DB, string, int64, runnerproto.Selection) (int64, runnerproto.SourceSnapshot, error) |
| + RunnerCurrent func(*gorm.DB, RunnerPrincipal) error |
| + Audit func(*gorm.DB, BindingRecord, string, string) error |
| + Now func() time.Time |
| + Events func(context.Context, Assignment, RunnerRequest) error |
| + Receipt func(context.Context, Assignment, RunnerRequest) (team.Receipt, error) |
| + Containment func(context.Context, Assignment, RunnerRequest) error |
| + Delivery func(context.Context, CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) |
| + Redact func([]byte) []byte |
| + Invalid, Conflict, Forbidden, Unavailable error |
| +} |
| +type EventRecord struct { |
| + Key string `gorm:"primaryKey"` |
| + AssignmentID string `gorm:"index:runner_event_assignment"` |
| + StreamKey string `gorm:"index:runner_event_timeline,priority:1"` |
| + Epoch string `gorm:"index:runner_event_timeline,priority:2"` |
| + Sequence *int64 `gorm:"index:runner_event_timeline,priority:3"` |
| + Kind, ContentHash, Body, Isolation string |
| +} |
| + |
| +func (EventRecord) TableName() string { return "runner_events" } |
diff --git a/internal/equipo/conversation/coordinator_events.go b/internal/equipo/conversation/coordinator_events.go| new file mode 100644 |
| index 00000000..86667f80 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_events.go |
| @@ -0,0 +1,196 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func coordinatorAssignment(c CoordinatorClaim) Assignment { |
| + return Assignment{ID: c.Turn.ID, TaskID: c.Turn.ID, Kind: "coordinator", StepKey: "coordinate", Scope: c.Scope, Selection: c.Brief.Selection, Revision: c.Turn.Revision} |
| +} |
| + |
| +// CompleteCoordinator requires a server validator of committed tool results and |
| +// delivery. A provider process-completed event is never this proof. |
| +func (e *Engine) CompleteCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| + if event.Kind != "coordinator.delivery" || event.Validate() != nil { |
| + return team.ErrEvidence |
| + } |
| + return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + b, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| + if err != nil { |
| + return err |
| + } |
| + if event.Scope != c.Scope || event.Handle != c.Handle || event.AssignmentID != row.ID || event.TaskID != row.ID || event.TurnID != row.ID || event.ActionID != c.Admission.Dispatch.Action { |
| + return e.Forbidden |
| + } |
| + hash := event.ContentHash() |
| + if row.State == "delivered" { |
| + if row.DeliveryHash != hash { |
| + return e.Conflict |
| + } |
| + return nil |
| + } |
| + if row.State != "running" || e.Delivery == nil { |
| + return team.ErrEvidence |
| + } |
| + if err = e.Core.ValidateHandle(ctx, c.Scope, c.Handle); err != nil { |
| + return err |
| + } |
| + body, receipt, err := e.Delivery(ctx, c, event) |
| + if err != nil { |
| + return err |
| + } |
| + if receipt.Outcome != team.OutcomeSuccess { |
| + return team.ErrEvidence |
| + } |
| + if err = e.Conversation(tx).DeliverCoordinator(row, body); err != nil { |
| + return err |
| + } |
| + if err = e.Core.Record(ctx, c.Scope, event.ActionID, receipt); err != nil { |
| + return err |
| + } |
| + if err = e.Core.DeliverCoordinator(ctx, c.Scope, c.Handle, b.ID, hash); err != nil { |
| + return err |
| + } |
| + if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state", "delivery_hash", "provider_session_id").Updates(map[string]any{"state": "delivered", "delivery_hash": hash, "provider_session_id": event.SessionID}).Error; err != nil { |
| + return err |
| + } |
| + return e.Audit(tx, b, "coordinator.delivered", row.ID) |
| + }) |
| +} |
| +func (e *Engine) CoordinatorEvent(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| + if event.Kind == "coordinator.delivery" { |
| + return e.CompleteCoordinator(ctx, p, c, event) |
| + } |
| + if event.Validate() != nil || event.Scope != c.Scope || event.Handle != c.Handle || event.AssignmentID != c.Turn.ID || event.TaskID != c.Turn.ID { |
| + return e.Invalid |
| + } |
| + switch event.Kind { |
| + case "namespace.owner", "namespace.launch", "session.bound", "turn.completed", "turn.failed", "turn.uncertain": |
| + default: |
| + return e.Invalid |
| + } |
| + return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + b, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| + if err != nil { |
| + return err |
| + } |
| + if row.State != "running" { |
| + return e.Conflict |
| + } |
| + if err = e.Core.ValidateHandle(ctx, c.Scope, c.Handle); err != nil { |
| + return err |
| + } |
| + var prior EventRecord |
| + err = tx.First(&prior, "key=?", event.DedupKey()).Error |
| + if err == nil { |
| + if prior.ContentHash != event.ContentHash() { |
| + return e.Conflict |
| + } |
| + return nil |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + if e.Events == nil { |
| + return e.Unavailable |
| + } |
| + q := RunnerRequest{Version: 2, AssignmentID: row.ID, Scope: c.Scope, Handle: c.Handle, RequestID: event.ID, ActionID: event.ActionID, Event: mustCoordinatorJSON(event)} |
| + if err = e.Events(ctx, coordinatorAssignment(c), q); err != nil { |
| + return err |
| + } |
| + if event.Kind == "session.bound" { |
| + if row.ProviderSessionID != "" && row.ProviderSessionID != event.SessionID { |
| + return e.Conflict |
| + } |
| + if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("provider_session_id").Updates(map[string]any{"provider_session_id": event.SessionID}).Error; err != nil { |
| + return err |
| + } |
| + } |
| + if event.Kind == "turn.completed" || event.Kind == "turn.failed" || event.Kind == "turn.uncertain" { |
| + if event.ActionID != c.Admission.Dispatch.Action || event.TurnID != row.ID || row.ProviderSessionID == "" || row.ProviderSessionID != event.SessionID { |
| + return e.Forbidden |
| + } |
| + if event.Kind == "turn.uncertain" { |
| + if err = e.Core.Lost(ctx, c.Scope, event.ActionID, "coordinator.uncertain"); err != nil { |
| + return err |
| + } |
| + } else { |
| + if e.Receipt == nil { |
| + return e.Unavailable |
| + } |
| + receipt, err := e.Receipt(ctx, coordinatorAssignment(c), q) |
| + if err != nil { |
| + return err |
| + } |
| + if err = e.Core.Record(ctx, c.Scope, event.ActionID, receipt); err != nil { |
| + return err |
| + } |
| + } |
| + if event.Kind != "turn.completed" { |
| + if err = e.Core.StopAttempt(ctx, c.Scope, c.Handle, "coordinator.uncertain"); err != nil { |
| + return err |
| + } |
| + if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state", "revision").Updates(map[string]any{"state": "uncertain", "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + hash := event.ContentHash() |
| + event.Payload = e.Redact(event.Payload) |
| + if err = tx.Create(&EventRecord{Key: event.DedupKey(), AssignmentID: row.ID, StreamKey: event.StreamKey(), Epoch: event.Epoch, Sequence: event.Sequence, Kind: event.Kind, ContentHash: hash, Body: string(mustCoordinatorJSON(event)), Isolation: string(mustCoordinatorJSON(c.Brief.Selection.Isolation))}).Error; err != nil { |
| + return err |
| + } |
| + return e.Audit(tx, b, "coordinator.event", event.ID) |
| + }) |
| +} |
| +func (e *Engine) ContainCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, proof runnerproto.ContainmentProof) error { |
| + return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + // Cleanup authenticates the runner but deliberately permits an old generation. |
| + if err := e.RunnerCurrent(tx, p); err != nil { |
| + return err |
| + } |
| + var row TurnRecord |
| + if err := tx.First(&row, "id=? AND person=?", c.Turn.ID, p.Person).Error; err != nil { |
| + return err |
| + } |
| + var saved CoordinatorClaim |
| + if err := decodeCoordinator(row.Claim, &saved); err != nil { |
| + return err |
| + } |
| + if runnerproto.EventHash(saved) != runnerproto.EventHash(c) || c.Handle.Runner != p.RunnerID || proof.Scope != c.Scope || proof.Handle != c.Handle { |
| + return e.Forbidden |
| + } |
| + if e.Containment == nil { |
| + return e.Unavailable |
| + } |
| + raw, err := json.Marshal(proof) |
| + if err != nil { |
| + return err |
| + } |
| + if err = e.Containment(ctx, coordinatorAssignment(saved), RunnerRequest{Version: 2, AssignmentID: row.ID, RequestID: row.ID, Scope: c.Scope, Handle: c.Handle, Proof: raw}); err != nil { |
| + return err |
| + } |
| + if err = e.Core.ContainUntrusted(ctx, c.Scope, c.Handle); err != nil { |
| + return err |
| + } |
| + if row.State != "delivered" { |
| + action, err := e.Core.GetAction(ctx, saved.Scope, saved.Admission.Dispatch.Action) |
| + if err != nil { |
| + return err |
| + } |
| + if action.State == team.ActionDispatching || action.State == team.ActionUncertain { |
| + if err = e.Core.Lost(ctx, saved.Scope, saved.Admission.Dispatch.Action, "coordinator.uncertain"); err != nil { |
| + return err |
| + } |
| + } |
| + |
| + return tx.Model(&TurnRecord{}).Where("id=? AND state<>'uncertain'", row.ID).Select("state", "revision").Updates(map[string]any{"state": "uncertain", "revision": gorm.Expr("revision+1")}).Error |
| + } |
| + return nil |
| + }) |
| +} |
diff --git a/internal/equipo/conversation/coordinator_execution.go b/internal/equipo/conversation/coordinator_execution.go| new file mode 100644 |
| index 00000000..0c615e7c |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_execution.go |
| @@ -0,0 +1,190 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| + "time" |
| +) |
| + |
| +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 |
| + if revision <= 0 || turnID == "" { |
| + return result, e.Invalid |
| + } |
| + err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + if err := e.Core.AdmissionAvailable(ctx); err != nil { |
| + return err |
| + } |
| + b, row, sel, err := e.Current(ctx, tx, p, turnID) |
| + if err != nil { |
| + return err |
| + } |
| + if row.Revision != revision { |
| + return e.Conflict |
| + } |
| + if row.State == "running" { |
| + if err = decodeCoordinator(row.Claim, &result); err != nil { |
| + return err |
| + } |
| + if err = e.Core.ValidateHandle(ctx, result.Scope, result.Handle); err != nil { |
| + return err |
| + } |
| + // Replays return the same admission, including its original expiry. |
| + _, 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" { |
| + return e.Conflict |
| + } |
| + var n int64 |
| + if err = tx.Model(&TurnRecord{}).Where("team_id=? AND person=? AND id<>? AND (state IN ('running','uncertain') OR (sequence<? AND state NOT IN ('delivered','superseded')) OR attempt_id IN (SELECT id FROM attempts WHERE containment='pending'))", row.TeamID, row.Person, row.ID, row.Sequence).Count(&n).Error; err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return e.Conflict |
| + } |
| + // A shared credential home remains unavailable while specialist work holds it. |
| + if err = tx.Table("runner_assignments").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", p.Person, b.ConnectionID).Count(&n).Error; err != nil { |
| + return err |
| + } |
| + if n > 0 { |
| + return e.Unavailable |
| + } |
| + contextValue, err := e.Conversation(tx).CoordinatorContextFor(row) |
| + if err != nil { |
| + return err |
| + } |
| + contextValue.Projects, err = e.Projects(tx, p.Person, sel) |
| + if err != nil { |
| + return err |
| + } |
| + if row.ProjectID > 0 { |
| + var source runnerproto.SourceSnapshot |
| + row.ProjectRevision, source, err = e.Project(tx, p.Person, row.ProjectID, sel) |
| + if err != nil { |
| + return err |
| + } |
| + contextValue.Sources = []runnerproto.SourceSnapshot{source} |
| + } |
| + hash, err := kernel.InputHash(contextValue) |
| + if err != nil { |
| + return err |
| + } |
| + row.ContextHash = hash |
| + limits, _, err := e.Core.CoordinatorLimits(ctx, team.AccountID(row.TeamID), p.Person) |
| + if err != nil { |
| + return err |
| + } |
| + policy, err := team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: min(limits.InputTokens, 32000), OutputTokens: min(limits.OutputTokens, 4000)}, team.Rates{}) |
| + if err != nil { |
| + return err |
| + } |
| + policy.MaxAttemptsPerStep = 1 |
| + policy.AttemptSeconds = int(min(limits.Seconds, 1200)) |
| + policy.JobSeconds = policy.AttemptSeconds |
| + spec := team.JobSpec{RequestKey: "coordinator:" + row.ID, Account: team.AccountID(row.TeamID), Requester: p.Person, GrantRef: team.CoordinatorGrantRef(p.Person), Target: team.TargetBinding{Kind: team.TargetConversation, Subject: p.Person}, Policy: policy, Steps: []team.StepSpec{{Key: "coordinate", Capability: team.CapCoordinate, Version: 1}}} |
| + job, err := e.Core.CreateJob(ctx, spec) |
| + if err != nil { |
| + return err |
| + } |
| + scope := team.Scope{Account: job.Account, Job: job.ID} |
| + handle, err := e.Core.Claim(ctx, scope, "coordinate", p.RunnerID, "coordinator:"+row.ID) |
| + if err != nil { |
| + return err |
| + } |
| + payload, err := json.Marshal(struct { |
| + TurnID, MessageID, ContextHash, BindingID string |
| + Generation int64 |
| + }{row.ID, row.MessageID, hash, b.ID, b.Generation}) |
| + if err != nil { |
| + return err |
| + } |
| + action, err := e.Core.Intend(ctx, scope, handle, team.IntentSpec{Key: row.ID, Operation: team.OpProviderCall, Payload: payload}) |
| + if err != nil { |
| + return err |
| + } |
| + ticket, err := e.Core.AdmitOnce(ctx, scope, handle, action, row.RequestID) |
| + if err != nil { |
| + return err |
| + } |
| + attempts, err := e.Core.Attempts(ctx, scope) |
| + if err != nil { |
| + return err |
| + } |
| + var lease, deadline time.Time |
| + for _, attempt := range attempts { |
| + if attempt.ID == handle.Attempt { |
| + lease = attempt.LeaseDeadline |
| + deadline = attempt.CreatedAt.Add(time.Duration(policy.AttemptSeconds) * time.Second) |
| + } |
| + } |
| + if lease.IsZero() { |
| + return e.Unavailable |
| + } |
| + if end := job.CreatedAt.Add(time.Duration(policy.JobSeconds) * time.Second); end.Before(deadline) { |
| + deadline = end |
| + } |
| + row.State = "running" |
| + row.JobID = int64(job.ID) |
| + row.AttemptID = int64(handle.Attempt) |
| + row.Fence = handle.Fence |
| + row.Selection = string(mustCoordinatorJSON(sel)) |
| + result = CoordinatorClaim{Binding: b.CoordinatorBinding, Turn: row.CoordinatorTurn, Scope: scope, Handle: handle, Context: contextValue, Admission: ticket, LeaseDeadline: lease, AttemptDeadline: deadline, Brief: runnerproto.RunnerBrief{AttemptDeadline: deadline, Step: runnerproto.StepBrief{StepKey: "coordinate", Action: "coordinate", SpecialistKey: "coordinator"}, Policy: policy, Target: spec.Target, Selection: sel}} |
| + row.Claim = string(mustCoordinatorJSON(result)) |
| + if err = tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state", "job_id", "attempt_id", "fence", "claim", "selection", "context_hash", "project_revision").Updates(&row).Error; err != nil { |
| + return err |
| + } |
| + return e.Audit(tx, b, "coordinator.claim", row.ID) |
| + }) |
| + if err != nil { |
| + return CoordinatorClaim{}, err |
| + } |
| + return result, nil |
| +} |
| +func mustCoordinatorJSON(v any) []byte { raw, _ := json.Marshal(v); return raw } |
| +func (e *Engine) validateCoordinatorClaim(ctx context.Context, tx *gorm.DB, p RunnerPrincipal, c CoordinatorClaim) (BindingRecord, TurnRecord, error) { |
| + b, row, _, err := e.Current(ctx, tx, p, c.Turn.ID) |
| + if err != nil { |
| + return b, row, err |
| + } |
| + var saved CoordinatorClaim |
| + if err = decodeCoordinator(row.Claim, &saved); err != nil { |
| + return b, row, err |
| + } |
| + if runnerproto.EventHash(saved) != runnerproto.EventHash(c) { |
| + return b, row, e.Forbidden |
| + } |
| + return b, row, nil |
| +} |
| +func (e *Engine) ValidateCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim) error { |
| + return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + _, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| + if err != nil { |
| + return err |
| + } |
| + if row.State != "running" { |
| + return e.Conflict |
| + } |
| + return e.Core.ValidateHandle(ctx, c.Scope, c.Handle) |
| + }) |
| +} |
| +func (e *Engine) RenewCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim) (time.Time, error) { |
| + var deadline time.Time |
| + err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + _, row, err := e.validateCoordinatorClaim(ctx, tx, p, c) |
| + if err != nil { |
| + return err |
| + } |
| + if row.State != "running" { |
| + return e.Conflict |
| + } |
| + deadline, err = e.Core.Renew(ctx, c.Scope, c.Handle) |
| + return err |
| + }) |
| + return deadline, err |
| +} |
diff --git a/internal/equipo/conversation/coordinator_poll.go b/internal/equipo/conversation/coordinator_poll.go| new file mode 100644 |
| index 00000000..a8ea6adc |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_poll.go |
| @@ -0,0 +1,70 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| + "strconv" |
| +) |
| + |
| +func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]CoordinatorTurn, error) { |
| + out := []CoordinatorTurn{} |
| + err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + if err := e.RunnerCurrent(tx, p); err != nil { |
| + return err |
| + } |
| + if err := e.Core.AdmissionAvailable(ctx); err != nil { |
| + return err |
| + } |
| + b, err := e.Conversation(tx).Binding(kernel.Actor{Address: p.Person}) |
| + if err != nil { |
| + return err |
| + } |
| + if b.RunnerID != p.RunnerID { |
| + return e.Forbidden |
| + } |
| + 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 |
| + } |
| + for _, msg := range messages { |
| + if _, err = e.Conversation(tx).QueueCoordinator(kernel.Actor{Address: p.Person}, msg.ID, 0, kernel.Mutation{RequestID: "message:" + msg.ID + ":" + strconv.FormatInt(b.Generation, 10)}); err != nil { |
| + return err |
| + } |
| + } |
| + var rows []TurnRecord |
| + if err = tx.Where("binding_id=? AND generation=? AND state NOT IN ('delivered','superseded')", b.ID, b.Generation).Order("sequence").Limit(1).Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + for _, row := range rows { |
| + if row.State == "running" || row.State == "uncertain" { |
| + continue |
| + } |
| + _, _, _, err = e.Current(ctx, tx, p, row.ID) |
| + if err != nil { |
| + if errors.Is(err, e.Forbidden) || errors.Is(err, e.Unavailable) || errors.Is(err, e.NotFound) { |
| + return tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": "waiting_connection"}).Error |
| + } |
| + return err |
| + } |
| + var busy int64 |
| + if err = tx.Table("runner_assignments").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", p.Person, b.ConnectionID).Count(&busy).Error; err != nil { |
| + return err |
| + } |
| + if busy > 0 { |
| + return tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": "waiting_task"}).Error |
| + } |
| + if err = e.Core.CoordinatorAvailable(ctx, team.AccountID(b.TeamID), p.Person); err != nil { |
| + if errors.Is(err, team.ErrBudget) { |
| + return tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": "budget_needed"}).Error |
| + } |
| + return err |
| + } |
| + out = append(out, row.CoordinatorTurn) |
| + } |
| + return nil |
| + }) |
| + return out, err |
| +} |
diff --git a/internal/equipo/conversation/models.go b/internal/equipo/conversation/models.go| index 4a9eaf52..8ce6fc2f 100644 |
| --- a/internal/equipo/conversation/models.go |
| +++ b/internal/equipo/conversation/models.go |
| @@ -94,4 +94,4 @@ type cursorRecord struct { |
| func (cursorRecord) TableName() string { return "conversation_cursors" } |
| -var Models = []any{&Main{}, &Thread{}, &messageRecord{}, &cardRecord{}, &requestRecord{}, &routeRecord{}, &outboxRecord{}, &cursorRecord{}} |
| +var Models = []any{&BindingRecord{}, &TurnRecord{}, &QuestionRecord{}, &Main{}, &Thread{}, &messageRecord{}, &cardRecord{}, &requestRecord{}, &routeRecord{}, &outboxRecord{}, &cursorRecord{}} |
diff --git a/internal/equipo/coordinator.go b/internal/equipo/coordinator.go| new file mode 100644 |
| index 00000000..3cdd8ee7 |
| --- /dev/null |
| +++ b/internal/equipo/coordinator.go |
| @@ -0,0 +1,138 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "gorm.io/gorm" |
| + "time" |
| +) |
| + |
| +type CoordinatorBinding = runnerproto.CoordinatorBinding |
| +type CoordinatorTurn = runnerproto.CoordinatorTurn |
| +type CoordinatorClaim = runnerproto.CoordinatorClaim |
| +type CoordinatorContext = runnerproto.CoordinatorContext |
| + |
| +func CoordinatorGrantRef(person string) string { |
| + return team.CoordinatorGrantRef(normalizeAddress(person)) |
| +} |
| + |
| +func (s *Store) coordinatorSelection(tx *gorm.DB, b conversation.BindingRecord) (Selection, error) { |
| + m, err := currentRunnerMember(tx, b.Person) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + if m.Revision != b.MemberRevision { |
| + return Selection{}, ErrForbidden |
| + } |
| + var c connectionRecord |
| + if err = tx.First(&c, "id=?", b.ConnectionID).Error; err != nil { |
| + return Selection{}, storeError(err) |
| + } |
| + if c.Person != b.Person || c.RunnerID != b.RunnerID || c.Revision != b.ConnectionRevision { |
| + return Selection{}, ErrForbidden |
| + } |
| + if err = decodeConnection(&c); err != nil { |
| + return Selection{}, err |
| + } |
| + for _, r := range c.Reports { |
| + ok, _, err := s.eligible(tx, c, r, s.runnerClock.Now().UTC()) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + if !ok { |
| + continue |
| + } |
| + // Task 5 supports the subscription lane; metered calls need explicit prices. |
| + if r.Kind != "subscription" { |
| + continue |
| + } |
| + iso, err := s.isolationSnapshot(tx, c, r) |
| + if err != nil { |
| + return Selection{}, err |
| + } |
| + return Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: c.Person, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountID: r.Routing.AccountID, AccountLabel: r.AccountLabel, Revision: c.Revision, Isolation: iso}, nil |
| + } |
| + return Selection{}, ErrUnavailable |
| +} |
| +func (s *Store) coordinatorApplication() *conversation.Application { |
| + var core *team.Store |
| + if s.execution != nil { |
| + core = s.execution.Core |
| + } |
| + return &conversation.Application{Core: core, Write: s.write, Conversation: conversationAt, Normalize: normalizeAddress, Audit: appendAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, NotFound: ErrNotFound, |
| + BindingIdentity: func(tx *gorm.DB, actor Actor, runner, connection string) (int64, int64, error) { |
| + member, err := currentRunnerMember(tx, actor.Address) |
| + if err != nil { |
| + return 0, 0, err |
| + } |
| + var c connectionRecord |
| + if err = tx.First(&c, "id=? AND runner_id=? AND person=?", connection, runner, actor.Address).Error; err != nil { |
| + return 0, 0, storeError(err) |
| + } |
| + instance, err := runnerInstance(tx) |
| + if err != nil { |
| + return 0, 0, err |
| + } |
| + r, err := runnerAt(tx, instance, runner) |
| + if err != nil { |
| + return 0, 0, err |
| + } |
| + if r.Person != actor.Address { |
| + return 0, 0, ErrForbidden |
| + } |
| + return member.Revision, c.Revision, nil |
| + }, LimitsAuthority: func(tx *gorm.DB, actor Actor, person string) error { |
| + member, err := currentRunnerMember(tx, actor.Address) |
| + if err != nil { |
| + return err |
| + } |
| + if member.Role != RoleOwner { |
| + return ErrForbidden |
| + } |
| + _, err = currentRunnerMember(tx, person) |
| + return err |
| + }} |
| +} |
| +func (s *Store) Coordinator(ctx context.Context, a Actor) (CoordinatorBinding, error) { |
| + return s.coordinatorApplication().Coordinator(ctx, a) |
| +} |
| +func (s *Store) SaveCoordinatorBinding(ctx context.Context, a Actor, r, c string, m Mutation) (CoordinatorBinding, error) { |
| + return s.coordinatorApplication().SaveCoordinatorBinding(ctx, a, r, c, m) |
| +} |
| +func (s *Store) ResetCoordinator(ctx context.Context, a Actor, m Mutation) (CoordinatorBinding, error) { |
| + return s.coordinatorApplication().ResetCoordinator(ctx, a, m) |
| +} |
| +func (s *Store) QueueCoordinatorTurn(ctx context.Context, a Actor, id string, p int64, m Mutation) (CoordinatorTurn, error) { |
| + return s.coordinatorApplication().QueueCoordinatorTurn(ctx, a, id, p, m) |
| +} |
| +func (s *Store) RetryCoordinatorTurn(ctx context.Context, a Actor, id string, m Mutation) (CoordinatorTurn, error) { |
| + return s.coordinatorApplication().RetryCoordinatorTurn(ctx, a, id, m) |
| +} |
| +func (s *Store) SetCoordinatorLimits(ctx context.Context, a Actor, p string, l team.Limits, m Mutation) error { |
| + return s.coordinatorApplication().SetCoordinatorLimits(ctx, a, p, l, m) |
| +} |
| +func coordinatorAudit(tx *gorm.DB, b conversation.BindingRecord, kind, id string) error { |
| + return tx.Create(&AuditEvent{Actor: "coordinator:" + b.ID, DelegatingPerson: b.Person, Kind: kind, RecordID: id, At: time.Now().UTC()}).Error |
| +} |
| +func (s *Store) coordinatorProject(tx *gorm.DB, person string, projectID int64, sel Selection) (Project, error) { |
| + var p Project |
| + if err := tx.First(&p, projectID).Error; err != nil { |
| + return p, storeError(err) |
| + } |
| + choice, ids, err := choiceAt(tx, person, projectID) |
| + if err != nil { |
| + return p, err |
| + } |
| + allowed := false |
| + for _, id := range ids { |
| + if id == sel.ConnectionID { |
| + allowed = true |
| + } |
| + } |
| + if !allowed || choice.PinnedID != "" && choice.PinnedID != sel.ConnectionID { |
| + return p, ErrForbidden |
| + } |
| + return p, nil |
| +} |
diff --git a/internal/equipo/coordinator_api.go b/internal/equipo/coordinator_api.go| new file mode 100644 |
| index 00000000..c6c4d0cd |
| --- /dev/null |
| +++ b/internal/equipo/coordinator_api.go |
| @@ -0,0 +1,7 @@ |
| +package equipo |
| + |
| +import "context" |
| + |
| +func (e *Execution) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]CoordinatorTurn, error) { |
| + return e.coordinatorEngine().PollCoordinator(ctx, p) |
| +} |
diff --git a/internal/equipo/coordinator_authority.go b/internal/equipo/coordinator_authority.go| new file mode 100644 |
| index 00000000..291a3ad3 |
| --- /dev/null |
| +++ b/internal/equipo/coordinator_authority.go |
| @@ -0,0 +1,54 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "gorm.io/gorm" |
| + "gorm.io/plugin/dbresolver" |
| + "time" |
| +) |
| + |
| +func (a *RosterAuthority) coordinator(ctx context.Context, req team.AdmissionRequest) (team.Admission, error) { |
| + person := req.Target.Subject |
| + if !validAddress(person) || req.Grant != CoordinatorGrantRef(person) || req.Project != 0 || req.Target.Repository != "" || req.Target.Ref != "" || req.Target.DefaultRef != "" || req.Target.BaseRevision != "" || req.Target.App != "" { |
| + return team.Admission{}, team.ErrGrantRevoked |
| + } |
| + if req.Operation != team.OpProviderCall && req.Operation != team.OpJobContinue && req.Operation != team.OpAttemptContinue { |
| + return team.Admission{}, team.ErrGrantRevoked |
| + } |
| + var out team.Admission |
| + check := func(tx *gorm.DB) error { |
| + b, err := conversationAt(tx).Binding(Actor{Address: person}) |
| + if err != nil { |
| + return err |
| + } |
| + if string(req.Account) != b.TeamID { |
| + return ErrForbidden |
| + } |
| + if _, err = a.store.coordinatorSelection(tx, b); err != nil { |
| + return err |
| + } |
| + var instance Team |
| + if err = tx.First(&instance).Error; err != nil { |
| + return err |
| + } |
| + now := a.clock.Now() |
| + out = team.Admission{Grant: req.Grant, Version: b.Generation, Epoch: instance.RosterEpoch, IssuedAt: now, ExpiresAt: now.Add(5 * time.Second)} |
| + return nil |
| + } |
| + var err error |
| + if tx, ok := ctx.Value(runnerTxKey{}).(*gorm.DB); ok { |
| + err = check(tx) |
| + } else { |
| + err = a.store.db.G.WithContext(ctx).Clauses(dbresolver.Read).Transaction(check, &sql.TxOptions{ReadOnly: true}) |
| + } |
| + if err != nil { |
| + if errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, gorm.ErrRecordNotFound) { |
| + return out, team.ErrGrantRevoked |
| + } |
| + return out, team.ErrAuthorityUnavailable |
| + } |
| + return out, nil |
| +} |
diff --git a/internal/equipo/coordinator_execution.go b/internal/equipo/coordinator_execution.go| new file mode 100644 |
| index 00000000..7b19cd11 |
| --- /dev/null |
| +++ b/internal/equipo/coordinator_execution.go |
| @@ -0,0 +1,71 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| + "time" |
| +) |
| + |
| +func decodeCoordinator(raw string, v any) error { return json.Unmarshal([]byte(raw), v) } |
| +func (e *Execution) coordinatorEngine() *conversation.Engine { |
| + return &conversation.Engine{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, 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) }, |
| + RunnerCurrent: func(tx *gorm.DB, p RunnerPrincipal) error { |
| + _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()) |
| + return err |
| + }, |
| + Projects: func(tx *gorm.DB, person string, sel Selection) ([]runnerproto.CoordinatorProject, error) { |
| + var projects []Project |
| + if err := tx.Order("id").Find(&projects).Error; err != nil { |
| + return nil, err |
| + } |
| + out := []runnerproto.CoordinatorProject{} |
| + for _, p := range projects { |
| + allowed, err := e.store.coordinatorProject(tx, person, p.ID, sel) |
| + if err != nil { |
| + if errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) { |
| + continue |
| + } |
| + return nil, err |
| + } |
| + out = append(out, runnerproto.CoordinatorProject{ID: allowed.ID, Label: allowed.Name, Revision: allowed.Revision}) |
| + } |
| + return out, nil |
| + }, Project: func(tx *gorm.DB, person string, id int64, sel Selection) (int64, runnerproto.SourceSnapshot, error) { |
| + p, err := e.store.coordinatorProject(tx, person, id, sel) |
| + if err != nil { |
| + return 0, runnerproto.SourceSnapshot{}, err |
| + } |
| + source, ref, err := projectSourceAt(tx, id) |
| + if err != nil { |
| + return 0, runnerproto.SourceSnapshot{}, err |
| + } |
| + raw, err := json.Marshal(source) |
| + return p.Revision, runnerproto.SourceSnapshot{Ref: ref, Payload: raw}, err |
| + }} |
| +} |
| +func (e *Execution) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, id string, rev int64) (CoordinatorClaim, error) { |
| + return e.coordinatorEngine().ClaimCoordinator(ctx, p, id, rev) |
| +} |
| +func (e *Execution) ValidateCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim) error { |
| + return e.coordinatorEngine().ValidateCoordinator(ctx, p, c) |
| +} |
| +func (e *Execution) RenewCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim) (time.Time, error) { |
| + return e.coordinatorEngine().RenewCoordinator(ctx, p, c) |
| +} |
| +func (e *Execution) CompleteCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| + return e.coordinatorEngine().CompleteCoordinator(ctx, p, c, event) |
| +} |
| +func (e *Execution) CoordinatorEvent(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| + return e.coordinatorEngine().CoordinatorEvent(ctx, p, c, event) |
| +} |
| +func (e *Execution) ContainCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, proof runnerproto.ContainmentProof) error { |
| + return e.coordinatorEngine().ContainCoordinator(ctx, p, c, proof) |
| +} |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 8e2172b6..7166dfda 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -205,6 +205,24 @@ func RunnerToolCopy() runner.ToolCopy { |
| // runnerDraftCopy is the Task 16 runtime inventory. Each entry needs review. |
| var runnerDraftCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: coordinator.connection |
| + "coordinator.connection": "Coordinator connection", |
| + // COPY REVIEW REQUIRED: coordinator.unavailable |
| + "coordinator.unavailable": "Your coordinator is unavailable.", |
| + // COPY REVIEW REQUIRED: coordinator.budget_needed |
| + "coordinator.budget_needed": "Ask a team owner to set coordinator limits.", |
| + // COPY REVIEW REQUIRED: coordinator.queued |
| + "coordinator.queued": "Waiting for your coordinator", |
| + // COPY REVIEW REQUIRED: coordinator.uncertain |
| + "coordinator.uncertain": "This turn was interrupted. Its result is unknown.", |
| + // COPY REVIEW REQUIRED: coordinator.retry |
| + "coordinator.retry": "Try this turn again", |
| + // COPY REVIEW REQUIRED: coordinator.reset |
| + "coordinator.reset": "Reset coordinator", |
| + // COPY REVIEW REQUIRED: coordinator.waiting_connection |
| + "coordinator.waiting_connection": "Waiting for your connection", |
| + // COPY REVIEW REQUIRED: coordinator.waiting_task |
| + "coordinator.waiting_task": "Waiting for the task to release your connection", |
| // 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/equipo/execution_models.go b/internal/equipo/execution_models.go| index c7e05ed4..4e8df7d5 100644 |
| --- a/internal/equipo/execution_models.go |
| +++ b/internal/equipo/execution_models.go |
| @@ -194,7 +194,7 @@ type executionTimeReservations struct { |
| func (executionTimeReservations) TableName() string { return "time_reservations" } |
| -var executionModels = []any{&executionGrantFences{}, &executionRecoveryCharges{}, &executionRecoveryEvents{}, &executionActions{}, &executionArtifacts{}, &executionAttempts{}, &executionEvents{}, &executionJobs{}, &executionPeriodBudgets{}, &executionReservations{}, &executionService{}, &executionSteps{}, &executionTimeReservations{}} |
| +var executionModels = []any{&executionCoordinatorLimits{}, &executionGrantFences{}, &executionRecoveryCharges{}, &executionRecoveryEvents{}, &executionActions{}, &executionArtifacts{}, &executionAttempts{}, &executionEvents{}, &executionJobs{}, &executionPeriodBudgets{}, &executionReservations{}, &executionService{}, &executionSteps{}, &executionTimeReservations{}} |
| type executionGrantFences struct { |
| Ref string `gorm:"type:text;primaryKey"` |
| @@ -226,3 +226,13 @@ type executionRecoveryEvents struct { |
| } |
| func (executionRecoveryEvents) TableName() string { return "recovery_events" } |
| + |
| +type executionCoordinatorLimits struct { |
| + Account string `gorm:"primaryKey;type:text;not null"` |
| + Person string `gorm:"primaryKey;type:text;not null"` |
| + Revision int64 `gorm:"type:integer;not null"` |
| + Limits string `gorm:"type:text;not null"` |
| + ContentHash string `gorm:"type:text;not null"` |
| +} |
| + |
| +func (executionCoordinatorLimits) TableName() string { return "coordinator_limits" } |
diff --git a/internal/equipo/migrations/0021_coordinator.sql b/internal/equipo/migrations/0021_coordinator.sql| new file mode 100644 |
| index 00000000..3ab7755c |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0021_coordinator.sql |
| @@ -0,0 +1,12 @@ |
| +CREATE TABLE coordinator_bindings (id text PRIMARY KEY, person text, runner_id text, connection_id text, revision integer, generation integer, team_id text, person_key text, member_revision integer, connection_revision integer); |
| +CREATE UNIQUE INDEX coordinator_person ON coordinator_bindings(team_id,person_key); |
| +CREATE TABLE coordinator_turns (id text PRIMARY KEY, message_id text, request_id text, provider_session_id text, context_hash text, generation integer, revision integer, state text, team_id text, person text, binding_id text, conversation_id text, sequence integer, project_id integer, project_revision integer, member_revision integer, connection_revision integer, claim text, selection text, input_hash text, delivery_hash text, session_id text, job_id integer, attempt_id integer, fence integer); |
| +CREATE TABLE coordinator_questions (id text PRIMARY KEY, binding_id text, turn_id text, person text, request_id text, state text, payload text, generation integer, revision integer); |
| +CREATE TABLE IF NOT EXISTS coordinator_limits ( |
| + account TEXT NOT NULL, person TEXT NOT NULL, revision INTEGER NOT NULL, |
| + limits TEXT NOT NULL, content_hash TEXT NOT NULL, |
| + PRIMARY KEY(account,person) |
| +); |
| +UPDATE service SET schema_version=8 WHERE id=1; |
| +ALTER TABLE audit_events ADD COLUMN delegating_person text; |
| +CREATE UNIQUE INDEX coordinator_active ON coordinator_turns(team_id,person) WHERE state='running'; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 1c703b28..bf6a4337 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -369,3 +369,15 @@ ALTER TABLE tasks ADD COLUMN replaces_id text NOT NULL DEFAULT ""; |
| CREATE TABLE plan_revisions (task_id text, revision integer, plan text, actor_kind text, actor text, changed_keys text, created_at datetime, PRIMARY KEY(task_id,revision)); |
| CREATE TABLE plan_requests (principal text, operation text, resource text, request_id text, input_hash text, result text, PRIMARY KEY(principal,operation,resource,request_id)); |
| CREATE TABLE plan_approval_settings (project_id integer, person text, mode text, revision integer, PRIMARY KEY(project_id,person)); |
| +CREATE TABLE coordinator_bindings (id text PRIMARY KEY, person text, runner_id text, connection_id text, revision integer, generation integer, team_id text, person_key text, member_revision integer, connection_revision integer); |
| +CREATE UNIQUE INDEX coordinator_person ON coordinator_bindings(team_id,person_key); |
| +CREATE TABLE coordinator_turns (id text PRIMARY KEY, message_id text, request_id text, provider_session_id text, context_hash text, generation integer, revision integer, state text, team_id text, person text, binding_id text, conversation_id text, sequence integer, project_id integer, project_revision integer, member_revision integer, connection_revision integer, claim text, selection text, input_hash text, delivery_hash text, session_id text, job_id integer, attempt_id integer, fence integer); |
| +CREATE TABLE coordinator_questions (id text PRIMARY KEY, binding_id text, turn_id text, person text, request_id text, state text, payload text, generation integer, revision integer); |
| +CREATE TABLE IF NOT EXISTS coordinator_limits ( |
| + account TEXT NOT NULL, person TEXT NOT NULL, revision INTEGER NOT NULL, |
| + limits TEXT NOT NULL, content_hash TEXT NOT NULL, |
| + PRIMARY KEY(account,person) |
| +); |
| +UPDATE service SET schema_version=8 WHERE id=1; |
| +ALTER TABLE audit_events ADD COLUMN delegating_person text; |
| +CREATE UNIQUE INDEX coordinator_active ON coordinator_turns(team_id,person) WHERE state='running'; |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index cd6cc257..4476ebd9 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -35,11 +35,12 @@ type Team struct { |
| } |
| type AuditEvent struct { |
| - ID int64 |
| - Actor string |
| - Kind string |
| - RecordID string |
| - At time.Time |
| + DelegatingPerson string |
| + ID int64 |
| + Actor string |
| + Kind string |
| + RecordID string |
| + At time.Time |
| } |
| type Account struct { |
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go| index 7d7cd7ee..b50cf2fe 100644 |
| --- a/internal/equipo/runner_api.go |
| +++ b/internal/equipo/runner_api.go |
| @@ -1,35 +1,21 @@ |
| package equipo |
| import ( |
| - "mime" |
| - "net/http" |
| - "strconv" |
| - "strings" |
| - |
| - "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "github.com/go-chi/chi/v5" |
| + "net/http" |
| ) |
| -// RunnerHandler exposes only outbound runner protocol endpoints. Normal app |
| -// construction leaves execution unattached and these endpoints fail closed. |
| -func (s *Store) RunnerHandler() http.Handler { return s.runnerRouter() } |
| - |
| -func (s *Store) runnerRouter() chi.Router { |
| - r := chi.NewRouter() |
| - r.Post("/poll", s.runnerPoll) |
| - r.Post("/blobs", s.runnerPutBlob) |
| - r.Post("/blobs/read", s.runnerReadBlob) |
| - r.Post("/claim", s.runnerClaim) |
| - r.Post("/recover_claim", s.runnerRecoverClaim) |
| - for _, op := range []string{"validate", "evidence", "freeze", "freeze_feature", "conclude", "publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { |
| - r.Post("/"+op, s.runnerMutation(op)) |
| - } |
| - r.Post("/connections", s.runnerConnections) |
| - r.Post("/heartbeat", s.runnerConnections) |
| - r.Get("/artifacts/{assignment}/{artifact}", s.runnerArtifact) |
| - return r |
| +func (s *Store) runnerProtocol() *runnerproto.Handler { |
| + return &runnerproto.Handler{Execution: func() runnerproto.ExecutionAPI { |
| + if s.execution == nil { |
| + return nil |
| + } |
| + return s.execution |
| + }, AuthenticateRunner: s.AuthenticateRunner, ReportConnections: s.ReportConnections, PutBlob: s.PutBlob, Blob: s.Blob, Failure: runnerFailure, JSON: runnerJSON, Invalid: ErrInvalid, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, MaxBlobBytes: MaxBlobBytes} |
| } |
| +func (s *Store) RunnerHandler() http.Handler { return s.runnerRouter() } |
| +func (s *Store) runnerRouter() chi.Router { return s.runnerProtocol().Router() } |
| func runnerCSRFExemptPaths(r chi.Routes) []string { |
| var paths []string |
| // Use the registered bearer routes so additions inherit the exemption. |
| @@ -41,253 +27,3 @@ func runnerCSRFExemptPaths(r chi.Routes) []string { |
| }) |
| return paths |
| } |
| - |
| -func runnerBody(w http.ResponseWriter, r *http.Request, v any, limit int64) bool { |
| - content, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| - if err != nil || content != "application/json" || runnerproto.DecodeLimit(r.Body, v, limit) != nil { |
| - runnerFailure(w, ErrInvalid) |
| - return false |
| - } |
| - return true |
| -} |
| -func (s *Store) runnerBearer(w http.ResponseWriter, r *http.Request) (RunnerPrincipal, string, bool) { |
| - w.Header().Set("Cache-Control", "no-store") |
| - values := r.Header.Values("Authorization") |
| - if len(r.Header.Values("Cookie")) != 0 || len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") { |
| - runnerFailure(w, ErrForbidden) |
| - return RunnerPrincipal{}, "", false |
| - } |
| - token := strings.TrimPrefix(values[0], "Bearer ") |
| - p, err := s.AuthenticateRunner(r.Context(), token) |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return p, "", false |
| - } |
| - return p, token, true |
| -} |
| -func (s *Store) runnerPoll(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - var q runnerproto.PollRequest |
| - if !runnerBody(w, r, &q, 8192) { |
| - return |
| - } |
| - if q.Version != 2 { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - if s.execution == nil { |
| - runnerFailure(w, ErrUnavailable) |
| - return |
| - } |
| - if err := s.execution.Sync(r.Context()); err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - value, err := s.execution.Poll(r.Context(), p, q.After) |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: value}) |
| -} |
| -func (s *Store) runnerClaim(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - var q ClaimRequest |
| - if !runnerBody(w, r, &q, 8192) { |
| - return |
| - } |
| - if s.execution == nil { |
| - runnerFailure(w, ErrUnavailable) |
| - return |
| - } |
| - value, err := s.execution.Claim(r.Context(), p, q) |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: value}) |
| -} |
| -func (s *Store) runnerMutation(op string) http.HandlerFunc { |
| - return func(w http.ResponseWriter, r *http.Request) { |
| - if s.execution == nil { |
| - runnerFailure(w, ErrUnavailable) |
| - return |
| - } |
| - var q RunnerRequest |
| - limit := int64(runnerproto.MaxActionBytes) |
| - if op == "artifacts" { |
| - limit = 2 * runnerproto.MaxArtifactBytes |
| - } |
| - if op == "events" { |
| - limit = runnerproto.MaxEventBytes + 4096 |
| - } |
| - if !runnerBody(w, r, &q, limit) { |
| - return |
| - } |
| - var value any |
| - var err error |
| - if strings.HasPrefix(r.Header.Get("Authorization"), "Cleanup ") { |
| - if len(r.Header.Values("Authorization")) != 1 || len(r.Header.Values("Cookie")) != 0 { |
| - runnerFailure(w, ErrForbidden) |
| - return |
| - } |
| - value, err = s.execution.Cleanup(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Cleanup "), op, q) |
| - } else { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - value, err = s.execution.Mutate(r.Context(), p, op, q) |
| - } |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: value}) |
| - } |
| -} |
| -func (s *Store) runnerConnections(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - var q runnerproto.HeartbeatRequest |
| - if !runnerBody(w, r, &q, runnerproto.MaxActionBytes) { |
| - return |
| - } |
| - if q.Version != 2 || q.RequestID == "" || len(q.RequestID) > 256 { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - if q.RotationRequestID != "" { |
| - if s.execution == nil { |
| - runnerFailure(w, ErrUnavailable) |
| - return |
| - } |
| - if err := s.execution.AcknowledgeRotation(r.Context(), p, q.RotationRequestID); err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - } |
| - if len(q.Reports) > 0 { |
| - var reports []ConnectionReport |
| - if runnerproto.DecodeLimit(strings.NewReader(string(q.Reports)), &reports, runnerproto.MaxActionBytes) != nil { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - if err := s.ReportConnections(r.Context(), p, reports); err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: struct{}{}}) |
| -} |
| -func (s *Store) runnerArtifact(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - if s.execution == nil { |
| - runnerFailure(w, ErrUnavailable) |
| - return |
| - } |
| - id, err := strconv.ParseInt(chi.URLParam(r, "artifact"), 10, 64) |
| - if err != nil { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - q := r.URL.Query() |
| - if q.Get("version") != "1" { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - attempt, err := strconv.ParseInt(q.Get("attempt"), 10, 64) |
| - if err != nil { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - fence, err := strconv.ParseInt(q.Get("fence"), 10, 64) |
| - if err != nil { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - job, err := strconv.ParseInt(q.Get("job"), 10, 64) |
| - if err != nil { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - request := RunnerRequest{Version: 2, AssignmentID: chi.URLParam(r, "assignment"), RequestID: q.Get("request_id"), Scope: Scope{Account: team.AccountID(q.Get("account")), Job: team.JobID(job)}, Handle: team.Handle{Attempt: team.AttemptID(attempt), Fence: fence, Runner: p.RunnerID}} |
| - value, err := s.execution.ReadArtifact(r.Context(), p, request, team.ArtifactID(id)) |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: value}) |
| -} |
| - |
| -func (s *Store) runnerPutBlob(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - var q runnerproto.BlobRequest |
| - if !runnerBody(w, r, &q, 2*MaxBlobBytes) { |
| - return |
| - } |
| - if q.Version != 2 { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - if err := s.PutBlob(r.Context(), p, q.Scope, q.Handle, q.Digest, q.Bytes); err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: struct{}{}}) |
| -} |
| -func (s *Store) runnerReadBlob(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - var q runnerproto.BlobReadRequest |
| - if !runnerBody(w, r, &q, 8192) { |
| - return |
| - } |
| - if q.Version != 2 { |
| - runnerFailure(w, ErrInvalid) |
| - return |
| - } |
| - b, err := s.Blob(r.Context(), p, q.Scope, q.Digest) |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: b}) |
| -} |
| - |
| -func (s *Store) runnerRecoverClaim(w http.ResponseWriter, r *http.Request) { |
| - p, _, ok := s.runnerBearer(w, r) |
| - if !ok { |
| - return |
| - } |
| - var q ClaimRequest |
| - if !runnerBody(w, r, &q, 8192) { |
| - return |
| - } |
| - if s.execution == nil { |
| - runnerFailure(w, ErrUnavailable) |
| - return |
| - } |
| - value, err := s.execution.RecoverClaim(r.Context(), p, q) |
| - if err != nil { |
| - runnerFailure(w, err) |
| - return |
| - } |
| - runnerJSON(w, 200, runnerproto.WorkResponse{Version: 2, Result: value}) |
| -} |
diff --git a/internal/equipo/runner_events.go b/internal/equipo/runner_events.go| index 972de1d8..37a23b1f 100644 |
| --- a/internal/equipo/runner_events.go |
| +++ b/internal/equipo/runner_events.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| "context" |
| "encoding/json" |
| "errors" |
| @@ -11,16 +12,7 @@ import ( |
| "gorm.io/gorm" |
| ) |
| -type runnerEvent struct { |
| - Key string `gorm:"primaryKey"` |
| - AssignmentID string `gorm:"index:runner_event_assignment"` |
| - StreamKey string `gorm:"index:runner_event_timeline,priority:1"` |
| - Epoch string `gorm:"index:runner_event_timeline,priority:2"` |
| - Sequence *int64 `gorm:"index:runner_event_timeline,priority:3"` |
| - Kind, ContentHash, Body, Isolation string |
| -} |
| - |
| -func (runnerEvent) TableName() string { return "runner_events" } |
| +type runnerEvent = conversation.EventRecord |
| type runnerEventID struct { |
| RunnerID string `gorm:"primaryKey"` |
diff --git a/internal/equipo/runner_execution_models.go b/internal/equipo/runner_execution_models.go| index 410634d3..2eb7e7ed 100644 |
| --- a/internal/equipo/runner_execution_models.go |
| +++ b/internal/equipo/runner_execution_models.go |
| @@ -69,12 +69,13 @@ type executionAdmissionTicket struct { |
| func (executionAdmissionTicket) TableName() string { return "admission_tickets" } |
| type RunnerValidators struct { |
| - Question func(context.Context, Assignment, RunnerRequest) error |
| - Receipt func(context.Context, Assignment, RunnerRequest) (team.Receipt, error) |
| - Containment func(context.Context, Assignment, RunnerRequest) error |
| - Prepare func(context.Context, Assignment, RunnerRequest) (PreparedBug, error) |
| - Events func(context.Context, Assignment, RunnerRequest) error |
| - Artifact func(context.Context, Assignment, RunnerRequest) error |
| + CoordinatorDelivery func(context.Context, CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) |
| + Question func(context.Context, Assignment, RunnerRequest) error |
| + Receipt func(context.Context, Assignment, RunnerRequest) (team.Receipt, error) |
| + Containment func(context.Context, Assignment, RunnerRequest) error |
| + Prepare func(context.Context, Assignment, RunnerRequest) (PreparedBug, error) |
| + Events func(context.Context, Assignment, RunnerRequest) error |
| + Artifact func(context.Context, Assignment, RunnerRequest) error |
| } |
| // SetRunnerValidators is a startup-only dependency injection seam. |
diff --git a/internal/equipo/runner_models.go b/internal/equipo/runner_models.go| index 9f5b85e0..75228e47 100644 |
| --- a/internal/equipo/runner_models.go |
| +++ b/internal/equipo/runner_models.go |
| @@ -1,6 +1,9 @@ |
| package equipo |
| -import "time" |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "time" |
| +) |
| type Runner struct { |
| TrialOwner string `gorm:"-"` |
| @@ -14,7 +17,7 @@ type Runner struct { |
| RevokedAt *time.Time |
| } |
| -type RunnerPrincipal struct{ RunnerID, Person, CredentialID string } |
| +type RunnerPrincipal = runnerproto.RunnerPrincipal |
| type runnerRecord struct { |
| Runner `gorm:"embedded"` |
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go| index bd44d076..d9bdceab 100644 |
| --- a/internal/equipo/runner_mutations.go |
| +++ b/internal/equipo/runner_mutations.go |
| @@ -345,7 +345,7 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen |
| if err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", a.RunnerID, now).First(&credential).Error; err != nil { |
| return nil, storeError(err) |
| } |
| - task, err = e.store.PrepareBug(ctx, RunnerPrincipal{a.RunnerID, a.Person, credential.ID}, task.ID, task.Revision, prepared) |
| + task, err = e.store.PrepareBug(ctx, RunnerPrincipal{RunnerID: a.RunnerID, Person: a.Person, CredentialID: credential.ID}, task.ID, task.Revision, prepared) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/equipo/team/actions.go b/internal/equipo/team/actions.go| index e678a43a..d5e27718 100644 |
| --- a/internal/equipo/team/actions.go |
| +++ b/internal/equipo/team/actions.go |
| @@ -171,6 +171,9 @@ func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec |
| if ((hd.job.Evidence.RequireBugFreeze && hd.step.Capability == CapPublish) || ((hd.job.Evidence.Predicate == PredicateSoftwareFeature || hd.job.Evidence.Predicate == PredicateRenderedChange) && (hd.step.Capability == CapPublish || hd.step.Capability == CapVerify))) && in.Operation == OpProviderCall { |
| return fail(CodeScope, "bug_publish_is_runner_only") |
| } |
| + if hd.job.Target.Kind == TargetConversation && (hd.step.Capability != CapCoordinate || in.Operation != OpProviderCall) { |
| + return ErrScope |
| + } |
| if !operationAllowed(hd.step.Capability, in.Operation) { |
| return fail(CodeScope, "capability %s cannot perform %s", hd.step.Capability, in.Operation) |
| } |
diff --git a/internal/equipo/team/authority.go b/internal/equipo/team/authority.go| index ebebe07f..3df8b9cb 100644 |
| --- a/internal/equipo/team/authority.go |
| +++ b/internal/equipo/team/authority.go |
| @@ -147,6 +147,10 @@ func (a *FakeAuthority) Introspect(ctx context.Context, req AdmissionRequest) (A |
| if g.Repository != "" && g.Repository != req.Target.Repository { |
| return Admission{}, fail(CodeGrantRevoked, "grant %q does not cover repository %s", req.Grant, req.Target.Repository) |
| } |
| + case TargetConversation: |
| + if req.Project != 0 || (req.Operation != OpProviderCall && req.Operation != OpJobContinue && req.Operation != OpAttemptContinue) { |
| + return Admission{}, ErrGrantRevoked |
| + } |
| case TargetBusiness: |
| if g.Subject != "" && g.Subject != req.Target.Subject { |
| return Admission{}, fail(CodeGrantRevoked, "grant %q does not cover subject %s", req.Grant, req.Target.Subject) |
diff --git a/internal/equipo/team/budget.go b/internal/equipo/team/budget.go| index 3a399ab0..5b70f527 100644 |
| --- a/internal/equipo/team/budget.go |
| +++ b/internal/equipo/team/budget.go |
| @@ -421,7 +421,17 @@ func boundedTurn(ctx context.Context, tx *sql.Tx, j jobRow, now time.Time) (Usag |
| if err != nil { |
| return want, err |
| } |
| - if configured { |
| + if configured && j.Target.Kind == TargetConversation { |
| + caps, err := coordinatorCharges(ctx, tx, j, b, now) |
| + if err != nil { |
| + return want, err |
| + } |
| + for _, c := range caps { |
| + if err = clip(Usage{Calls: c.used.Calls, InputTokens: c.used.InputTokens, OutputTokens: c.used.OutputTokens}, Limits{Calls: c.cap.Calls, InputTokens: c.cap.InputTokens, OutputTokens: c.cap.OutputTokens}); err != nil { |
| + return want, err |
| + } |
| + } |
| + } else if configured { |
| project, ok := b.Projects[j.Project] |
| if !ok { |
| return want, fail(CodeBudget, "project budget unavailable") |
diff --git a/internal/equipo/team/coordinator.go b/internal/equipo/team/coordinator.go| new file mode 100644 |
| index 00000000..8e5c7ac2 |
| --- /dev/null |
| +++ b/internal/equipo/team/coordinator.go |
| @@ -0,0 +1,188 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "time" |
| +) |
| + |
| +func CoordinatorGrantRef(person string) string { |
| + return "coordinator:" + base64.RawURLEncoding.EncodeToString([]byte(person)) |
| +} |
| + |
| +const coordinatorSchema = ` |
| +CREATE TABLE IF NOT EXISTS coordinator_limits ( |
| + account TEXT NOT NULL, person TEXT NOT NULL, revision INTEGER NOT NULL, |
| + limits TEXT NOT NULL, content_hash TEXT NOT NULL, |
| + PRIMARY KEY(account,person) |
| +); |
| +UPDATE service SET schema_version=8 WHERE id=1; |
| +` |
| + |
| +func coordinatorLimit(ctx context.Context, tx *sql.Tx, account AccountID, person string) (Limits, int64, error) { |
| + var l Limits |
| + var rev int64 |
| + var raw, hash string |
| + err := tx.QueryRowContext(ctx, "SELECT revision,limits,content_hash FROM coordinator_limits WHERE account=? AND person=?", account, person).Scan(&rev, &raw, &hash) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return l, 0, ErrBudget |
| + } |
| + if err != nil { |
| + return l, 0, err |
| + } |
| + if rev <= 0 || hash != hashBytes([]byte(raw)) || strictJSON([]byte(raw), &l) != nil || coordinatorPeriod(l).validate() != nil || l.CostMicros != 0 { |
| + return l, 0, ErrInvalid |
| + } |
| + return l, rev, nil |
| +} |
| +func coordinatorPeriod(l Limits) PeriodLimits { |
| + return PeriodLimits{Calls: l.Calls, InputTokens: l.InputTokens, OutputTokens: l.OutputTokens, Seconds: l.Seconds} |
| +} |
| +func (s *Store) CoordinatorLimits(ctx context.Context, account AccountID, person string) (Limits, int64, error) { |
| + var l Limits |
| + var rev int64 |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| + var err error |
| + l, rev, err = coordinatorLimit(ctx, tx, account, person) |
| + return err |
| + }) |
| + return l, rev, err |
| +} |
| +func (s *Store) ConfigureCoordinatorLimits(ctx context.Context, account AccountID, person string, revision int64, l Limits) error { |
| + if account == "" || person == "" || revision < 0 || l.CostMicros != 0 || coordinatorPeriod(l).validate() != nil { |
| + return ErrInvalid |
| + } |
| + return s.tx(ctx, func(tx *sql.Tx) error { |
| + _, old, err := coordinatorLimit(ctx, tx, account, person) |
| + if err != nil && !errors.Is(err, ErrBudget) { |
| + return err |
| + } |
| + if old != revision { |
| + return ErrRevision |
| + } |
| + next, err := addChecked(revision, 1) |
| + if err != nil { |
| + return err |
| + } |
| + b, ok, err := loadBudgets(ctx, tx, account) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok || !coordinatorPeriod(l).within(b.Team) { |
| + return ErrBudget |
| + } |
| + raw, err := json.Marshal(l) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.ExecContext(ctx, "INSERT INTO coordinator_limits(account,person,revision,limits,content_hash) VALUES(?,?,?,?,?) ON CONFLICT(account,person) DO UPDATE SET revision=excluded.revision,limits=excluded.limits,content_hash=excluded.content_hash", account, person, next, string(raw), hashBytes(raw)) |
| + if err != nil { |
| + return err |
| + } |
| + return advanceRecovery(ctx, tx) |
| + }) |
| +} |
| + |
| +type coordinatorCharge struct{ used, cap PeriodLimits } |
| + |
| +func coordinatorCharges(ctx context.Context, tx *sql.Tx, j jobRow, b BudgetSet, now time.Time) ([]coordinatorCharge, error) { |
| + if j.Project != 0 || j.Target.Subject != j.Requester { |
| + return nil, ErrScope |
| + } |
| + l, _, err := coordinatorLimit(ctx, tx, j.Account, j.Requester) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var out []coordinatorCharge |
| + for _, v := range []struct { |
| + person string |
| + cap PeriodLimits |
| + }{{"", b.Team}, {j.Requester, coordinatorPeriod(l)}} { |
| + sum, err := periodSumFor(ctx, tx, j.Account, 0, v.person, now) |
| + if err != nil { |
| + return nil, err |
| + } |
| + total, err := sum.Reserved.add(sum.Spent) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, coordinatorCharge{total, v.cap}) |
| + } |
| + return out, nil |
| +} |
| +func checkCoordinatorBudget(ctx context.Context, tx *sql.Tx, j jobRow, b BudgetSet, want PeriodLimits, now time.Time) error { |
| + caps, err := coordinatorCharges(ctx, tx, j, b, now) |
| + if err != nil { |
| + return err |
| + } |
| + for _, c := range caps { |
| + total, err := c.used.add(want) |
| + if err != nil { |
| + return err |
| + } |
| + if !total.within(c.cap) { |
| + return ErrBudget |
| + } |
| + } |
| + return nil |
| +} |
| +func (s *Store) CoordinatorUsage(ctx context.Context, account AccountID, person string, at time.Time) (PeriodUsage, error) { |
| + var u PeriodUsage |
| + if account == "" || person == "" || at.IsZero() { |
| + return u, ErrInvalid |
| + } |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| + if _, _, err := coordinatorLimit(ctx, tx, account, person); err != nil { |
| + return err |
| + } |
| + var err error |
| + u, err = periodSumFor(ctx, tx, account, 0, person, at) |
| + return err |
| + }) |
| + return u, err |
| +} |
| + |
| +// DeliverCoordinator is called by the application inside the delivery transaction. |
| +func (s *Store) DeliverCoordinator(ctx context.Context, scope Scope, h Handle, bindingID, deliveryHash string) error { |
| + if bindingID == "" || !lowerHex(deliveryHash, 64) { |
| + return ErrInvalid |
| + } |
| + return s.Atomic(ctx, func(ctx context.Context, tx *sql.Tx) error { |
| + hd, err := current(ctx, tx, scope, h, s.clock.Now()) |
| + if err != nil { |
| + return err |
| + } |
| + if hd.job.Target.Kind != TargetConversation || hd.step.Capability != CapCoordinate { |
| + return ErrScope |
| + } |
| + if err = appendEvent(ctx, tx, scope, "coordinator.delivered", "coordinator:"+bindingID, map[string]string{"hash": deliveryHash, "delegating_person": hd.job.Requester}, s.clock.Now()); err != nil { |
| + return err |
| + } |
| + if err = s.Complete(ctx, scope, h, AttemptResult{Outcome: OutcomeSuccess}); err != nil { |
| + return err |
| + } |
| + _, err = bumpJob(ctx, tx, hd.job, JobSucceeded, WaitNone, "", s.clock.Now()) |
| + return err |
| + }) |
| +} |
| + |
| +func (s *Store) CoordinatorAvailable(ctx context.Context, account AccountID, person string) error { |
| + return s.read(ctx, func(tx *sql.Tx) error { |
| + l, _, err := coordinatorLimit(ctx, tx, account, person) |
| + if err != nil { |
| + return err |
| + } |
| + b, ok, err := loadBudgets(ctx, tx, account) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + return ErrBudget |
| + } |
| + j := jobRow{Job: Job{Account: account, Requester: person, Target: TargetBinding{Kind: TargetConversation, Subject: person}}} |
| + return checkCoordinatorBudget(ctx, tx, j, b, PeriodLimits{Calls: 1, InputTokens: 1, OutputTokens: 1, Seconds: min(l.Seconds, 1200)}, s.clock.Now()) |
| + }) |
| +} |
diff --git a/internal/equipo/team/coordinator_test.go b/internal/equipo/team/coordinator_test.go| new file mode 100644 |
| index 00000000..e3f400d6 |
| --- /dev/null |
| +++ b/internal/equipo/team/coordinator_test.go |
| @@ -0,0 +1,232 @@ |
| +package team |
| + |
| +import ( |
| + "database/sql" |
| + "errors" |
| + "math" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +func coordinatorSpec() JobSpec { |
| + p := testPolicy() |
| + return JobSpec{Account: acctA, Requester: "paul", GrantRef: grant, Target: TargetBinding{Kind: TargetConversation, Subject: "paul"}, Policy: p, Steps: []StepSpec{{Key: "coordinate", Capability: CapCoordinate, Version: 1}}} |
| +} |
| +func coordinatorLimits() Limits { |
| + return Limits{Calls: 20, InputTokens: 10000, OutputTokens: 10000, Seconds: 10000} |
| +} |
| +func configureCoordinator(t *testing.T, e *env) { |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + must(t, e.store.ConfigureCoordinatorLimits(e.ctx, acctA, "paul", 0, coordinatorLimits())) |
| +} |
| +func TestCoordinatorNoProjectBudgetBypass(t *testing.T) { |
| + if operationAllowed(CapCoordinate, OpForgePublish) { |
| + t.Fatal("coordinate capability permits forge") |
| + } |
| + e := newEnv(t) |
| + configureCoordinator(t, e) |
| + ordinary := softwareSpec(SoftwareSteps(false)) |
| + if _, err := e.store.CreateJob(e.ctx, ordinary); err == nil { |
| + t.Fatal("ordinary Project=0 admitted") |
| + } |
| + spec := coordinatorSpec() |
| + _, s := e.createJob(spec) |
| + h := e.claim(s, "coordinate", "runner", "coordinator") |
| + if _, err := e.store.Intend(e.ctx, s, h, IntentSpec{Key: "forge", Operation: OpForgePublish, Payload: []byte(`{}`)}); err == nil { |
| + t.Fatal("conversation gained forge authority") |
| + } |
| + spec.Target.Repository = "repo" |
| + if _, err := e.store.CreateJob(e.ctx, spec); err == nil { |
| + t.Fatal("conversation gained repository context") |
| + } |
| + spec = coordinatorSpec() |
| + spec.Steps[0].Capability = CapImplement |
| + if _, err := e.store.CreateJob(e.ctx, spec); err == nil { |
| + t.Fatal("conversation gained implement capability") |
| + } |
| + spec = coordinatorSpec() |
| + spec.Project = 1 |
| + if _, err := e.store.CreateJob(e.ctx, spec); err == nil { |
| + t.Fatal("conversation used project budget") |
| + } |
| + if err := e.store.Complete(e.ctx, s, h, AttemptResult{Outcome: OutcomeSuccess}); err == nil { |
| + t.Fatal("process completion proved delivery") |
| + } |
| +} |
| +func TestCoordinatorBudgetSharesTeam(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + b.Team.Calls = 1 |
| + for id, p := range b.Projects { |
| + p.Calls = 1 |
| + b.Projects[id] = p |
| + } |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| + l := coordinatorLimits() |
| + l.Calls = 1 |
| + must(t, e.store.ConfigureCoordinatorLimits(e.ctx, acctA, "paul", 0, l)) |
| + _, s := e.createJob(coordinatorSpec()) |
| + h := e.claim(s, "coordinate", "runner", "coordinator") |
| + p, ph := periodJob(e, 1) |
| + var wg sync.WaitGroup |
| + results := make(chan error, 2) |
| + for _, v := range []struct { |
| + s Scope |
| + h Handle |
| + }{{s, h}, {p, ph}} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + _, err := e.store.Intend(e.ctx, v.s, v.h, intent("turn", Usage{InputTokens: 1, OutputTokens: 1})) |
| + results <- err |
| + }() |
| + } |
| + wg.Wait() |
| + close(results) |
| + successes := 0 |
| + for err := range results { |
| + if err == nil { |
| + successes++ |
| + } else if !errors.Is(err, ErrBudget) { |
| + t.Fatal(err) |
| + } |
| + } |
| + if successes != 1 { |
| + t.Fatalf("shared last reservation: %d successes", successes) |
| + } |
| + if periodUsage(e, 0).Reserved.Calls != 1 { |
| + t.Fatal("team omitted coordinator reservation") |
| + } |
| +} |
| +func TestCoordinatorBudgetUnknownRollover(t *testing.T) { |
| + e := newEnv(t) |
| + configureCoordinator(t, e) |
| + _, s := e.createJob(coordinatorSpec()) |
| + h := e.claim(s, "coordinate", "runner", "coordinator") |
| + id, err := e.store.Intend(e.ctx, s, h, intent("turn", Usage{InputTokens: 10, OutputTokens: 5})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, s, id) |
| + must(t, err) |
| + must(t, e.store.Lost(e.ctx, s, id, "unknown")) |
| + _, err = e.store.Cancel(e.ctx, s, "paul", "cancel") |
| + must(t, err) |
| + must(t, e.store.ContainUntrusted(e.ctx, s, h)) |
| + u, err := e.store.CoordinatorUsage(e.ctx, acctA, "paul", e.clock.Now()) |
| + must(t, err) |
| + if u.Spent.Calls != 1 || u.Spent.InputTokens != 10 || u.Spent.Seconds != 1200 { |
| + t.Fatalf("unknown/cancelled exposure refunded: %+v", u) |
| + } |
| + u, err = e.store.CoordinatorUsage(e.ctx, acctA, "paul", e.clock.Now().AddDate(0, 1, 0)) |
| + must(t, err) |
| + if u != (PeriodUsage{}) { |
| + t.Fatal("old charge leaked into next period", u) |
| + } |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { |
| + _, err := tx.Exec("UPDATE reservations SET s_input=?", math.MaxInt64) |
| + return err |
| + })) |
| + _, s2 := e.createJob(coordinatorSpec()) |
| + _, err = e.store.Claim(e.ctx, s2, "coordinate", "runner", "coordinator-2") |
| + if !errors.Is(err, ErrOverflow) && !errors.Is(err, ErrBudget) { |
| + t.Fatal("overflow admitted", err) |
| + } |
| +} |
| + |
| +func TestCoordinatorMigrationCoreUpgrade(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { |
| + _, err := tx.Exec("DROP TABLE coordinator_limits") |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.Exec("UPDATE service SET schema_version=7") |
| + return err |
| + })) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + e.open() |
| + var version int |
| + must(t, e.store.db.QueryRow("SELECT schema_version FROM service").Scan(&version)) |
| + if version != 8 { |
| + t.Fatal("core upgrade did not advance version", version) |
| + } |
| + configureCoordinator(t, e) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + e.open() |
| + l, rev, err := e.store.CoordinatorLimits(e.ctx, acctA, "paul") |
| + must(t, err) |
| + if rev != 1 || l != coordinatorLimits() { |
| + t.Fatal("core reopen lost limits") |
| + } |
| +} |
| + |
| +func TestCoordinatorBudgetPersonCeiling(t *testing.T) { |
| + e := newEnv(t) |
| + configureCoordinator(t, e) |
| + l := coordinatorLimits() |
| + l.Calls = 1 |
| + must(t, e.store.ConfigureCoordinatorLimits(e.ctx, acctA, "paul", 1, l)) |
| + _, scope := e.createJob(coordinatorSpec()) |
| + h := e.claim(scope, "coordinate", "runner", "first") |
| + _, err := e.store.Intend(e.ctx, scope, h, intent("one", Usage{InputTokens: 1, OutputTokens: 1})) |
| + must(t, err) |
| + _, err = e.store.Intend(e.ctx, scope, h, intent("two", Usage{InputTokens: 1, OutputTokens: 1})) |
| + wantCode(t, err, CodeBudget) |
| +} |
| + |
| +func TestCoordinatorBudgetSharesTeamProjectFirst(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + b.Team.Calls = 1 |
| + for id, p := range b.Projects { |
| + p.Calls = 1 |
| + b.Projects[id] = p |
| + } |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| + l := coordinatorLimits() |
| + l.Calls = 1 |
| + must(t, e.store.ConfigureCoordinatorLimits(e.ctx, acctA, "paul", 0, l)) |
| + project, ph := periodJob(e, 1) |
| + _, scope := e.createJob(coordinatorSpec()) |
| + h := e.claim(scope, "coordinate", "runner", "coordinator") |
| + _, err := e.store.Intend(e.ctx, project, ph, intent("project-first", Usage{InputTokens: 1, OutputTokens: 1})) |
| + must(t, err) |
| + _, err = e.store.Intend(e.ctx, scope, h, intent("coordinator-second", Usage{InputTokens: 1, OutputTokens: 1})) |
| + wantCode(t, err, CodeBudget) |
| +} |
| + |
| +func TestCoordinatorNoProjectBudgetBypassRunnerPolicy(t *testing.T) { |
| + e := newEnv(t) |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + spec.Policy = runnerPolicy(t, "subscription") |
| + _, err := e.store.CreateJob(e.ctx, spec) |
| + wantCode(t, err, CodeBudget) |
| + spec.Project = 1 |
| + _, err = e.store.CreateJob(e.ctx, spec) |
| + wantCode(t, err, CodeBudget) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + _, err = e.store.CreateJob(e.ctx, spec) |
| + must(t, err) |
| +} |
| + |
| +func TestCoordinatorBudgetOverflow(t *testing.T) { |
| + e := newEnv(t) |
| + configureCoordinator(t, e) |
| + _, scope := e.createJob(coordinatorSpec()) |
| + h := e.claim(scope, "coordinate", "runner", "overflow") |
| + _, err := e.store.Intend(e.ctx, scope, h, intent("one", Usage{InputTokens: 1, OutputTokens: 1})) |
| + must(t, err) |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { |
| + _, err := tx.Exec("UPDATE reservations SET r_input=?", math.MaxInt64) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.Exec(`INSERT INTO reservations(account,job_id,step_id,attempt_id,action_id,r_calls,r_input,r_output,r_cost,s_calls,s_input,s_output,s_cost,state,receipt_id,settled_by,created_at,settled_at,project_id,period,cost_unavailable) SELECT account,job_id,step_id,attempt_id,action_id,1,1,1,0,0,0,0,0,'open','','',created_at,'',project_id,period,cost_unavailable FROM reservations LIMIT 1`) |
| + return err |
| + })) |
| + _, err = e.store.CoordinatorUsage(e.ctx, acctA, "paul", e.clock.Now()) |
| + wantCode(t, err, CodeOverflow) |
| + _, err = e.store.PeriodUsage(e.ctx, acctA, 0, e.clock.Now()) |
| + wantCode(t, err, CodeOverflow) |
| +} |
diff --git a/internal/equipo/team/feature_evidence.go b/internal/equipo/team/feature_evidence.go| index d4799d2e..1c84ca1e 100644 |
| --- a/internal/equipo/team/feature_evidence.go |
| +++ b/internal/equipo/team/feature_evidence.go |
| @@ -17,6 +17,9 @@ func validateTargetSteps(target TargetBinding, e EvidenceRequirement, p Policy, |
| return ErrInvalid |
| } |
| for _, st := range steps { |
| + if (target.Kind == TargetConversation) != (st.Capability == CapCoordinate) { |
| + return ErrScope |
| + } |
| if target.Kind == TargetProjectRead && st.Capability != CapResearch { |
| return ErrScope |
| } |
diff --git a/internal/equipo/team/harness_test.go b/internal/equipo/team/harness_test.go| index 6fc86861..63d3f59b 100644 |
| --- a/internal/equipo/team/harness_test.go |
| +++ b/internal/equipo/team/harness_test.go |
| @@ -108,6 +108,22 @@ func softwareSpec(steps []StepSpec) JobSpec { |
| func (e *env) createJob(spec JobSpec) (Job, Scope) { |
| e.t.Helper() |
| + if spec.Policy.Version == 2 { |
| + if spec.Target.Kind != TargetConversation && spec.Project == 0 { |
| + spec.Project = 1 |
| + } |
| + if _, err := e.store.ConfiguredBudgets(e.ctx, spec.Account); errors.Is(err, ErrBudget) { |
| + b := periodSet() |
| + l := PeriodLimits{Calls: 10000, InputTokens: 100000000, OutputTokens: 100000000, Seconds: 100000000} |
| + b.Team = l |
| + for id := range b.Projects { |
| + b.Projects[id] = l |
| + } |
| + must(e.t, e.store.ConfigureBudgets(e.ctx, spec.Account, 0, b)) |
| + } else { |
| + must(e.t, err) |
| + } |
| + } |
| j, err := e.store.CreateJob(e.ctx, spec) |
| if err != nil { |
| e.t.Fatalf("create job: %v", err) |
diff --git a/internal/equipo/team/jobs.go b/internal/equipo/team/jobs.go| index bfe4904a..149d6cc3 100644 |
| --- a/internal/equipo/team/jobs.go |
| +++ b/internal/equipo/team/jobs.go |
| @@ -34,6 +34,12 @@ func (js JobSpec) validate() error { |
| if js.Evidence.FrozenAcceptanceHash != "" || js.Evidence.RenderedApprovalHash != "" || len(js.Evidence.RenderedApprovals) > 0 { |
| return ErrInvalid |
| } |
| + if js.Policy.Version == 2 && js.Target.Kind != TargetConversation && js.Project <= 0 && js.Parent == 0 { |
| + return ErrBudget |
| + } |
| + if js.Target.Kind == TargetConversation && (js.Project != 0 || js.Parent != 0 || js.Target.Subject != js.Requester || len(js.Steps) != 1) { |
| + return ErrInvalid |
| + } |
| if js.Account == "" || js.Requester == "" || js.GrantRef == "" { |
| return fail(CodeInvalid, "job needs account, requester and grant") |
| } |
| @@ -177,6 +183,9 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| if err != nil { |
| return err |
| } |
| + if !configuredAccount && spec.Policy.Version == 2 { |
| + return ErrBudget |
| + } |
| if !configuredAccount { |
| account, err := accountPolicy(ctx, tx, spec.Account) |
| if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| @@ -211,7 +220,14 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| if err != nil { |
| return err |
| } |
| - if configured { |
| + if spec.Target.Kind == TargetConversation { |
| + if !configured { |
| + return ErrBudget |
| + } |
| + if _, _, err := coordinatorLimit(ctx, tx, spec.Account, spec.Requester); err != nil { |
| + return err |
| + } |
| + } else if configured { |
| if _, ok := b.Projects[spec.Project]; !ok || spec.Project <= 0 { |
| return fail(CodeBudget, "job needs configured project") |
| } |
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go| index 8646d467..0abff747 100644 |
| --- a/internal/equipo/team/model.go |
| +++ b/internal/equipo/team/model.go |
| @@ -205,9 +205,10 @@ func (w WaitReason) claimable() bool { |
| type TargetKind string |
| const ( |
| - TargetProjectRead TargetKind = "project_read" |
| - TargetRepository TargetKind = "repository" |
| - TargetBusiness TargetKind = "business" |
| + TargetConversation TargetKind = "conversation" |
| + TargetProjectRead TargetKind = "project_read" |
| + TargetRepository TargetKind = "repository" |
| + TargetBusiness TargetKind = "business" |
| ) |
| // TargetBinding is the explicit account-side mapping of a job to what it |
| @@ -231,6 +232,10 @@ type TargetBinding struct { |
| func (t TargetBinding) validate() error { |
| switch t.Kind { |
| + case TargetConversation: |
| + if t.Subject == "" || t.Repository != "" || t.Ref != "" || t.DefaultRef != "" || t.BaseRevision != "" || t.App != "" { |
| + return ErrInvalid |
| + } |
| case TargetProjectRead: |
| if t.Repository == "" || t.BaseRevision == "" || t.Ref != "" || t.DefaultRef != "" || t.Subject != "" { |
| return fail(CodeInvalid, "read_target_invalid") |
| @@ -300,7 +305,7 @@ type EvidenceRequirement struct { |
| func (e EvidenceRequirement) validate(kind TargetKind) error { |
| switch e.Predicate { |
| case "": |
| - if kind != TargetProjectRead { |
| + if kind != TargetProjectRead && kind != TargetConversation { |
| return fail(CodeInvalid, "read_target_required") |
| } |
| case PredicateSoftwareFeature, PredicateRenderedChange: |
| @@ -367,20 +372,21 @@ type Job struct { |
| type Capability string |
| const ( |
| - CapScope Capability = "scope" |
| - CapResearch Capability = "research" |
| - CapReproduce Capability = "reproduce" |
| - CapImplement Capability = "implement" |
| - CapReview Capability = "review" |
| - CapVerify Capability = "verify" |
| - CapPublish Capability = "publish" |
| - CapCollect Capability = "collect" |
| - CapReconcile Capability = "reconcile" |
| + CapCoordinate Capability = "coordinate" |
| + CapScope Capability = "scope" |
| + CapResearch Capability = "research" |
| + CapReproduce Capability = "reproduce" |
| + CapImplement Capability = "implement" |
| + CapReview Capability = "review" |
| + CapVerify Capability = "verify" |
| + CapPublish Capability = "publish" |
| + CapCollect Capability = "collect" |
| + CapReconcile Capability = "reconcile" |
| ) |
| func (c Capability) Valid() bool { |
| switch c { |
| - case CapScope, CapResearch, CapReproduce, CapImplement, CapReview, CapVerify, CapPublish, CapCollect, CapReconcile: |
| + case CapCoordinate, CapScope, CapResearch, CapReproduce, CapImplement, CapReview, CapVerify, CapPublish, CapCollect, CapReconcile: |
| return true |
| } |
| return false |
| @@ -972,6 +978,7 @@ type LedgerSummary struct { |
| // Limits bounds usage. Every field is a hard cap. |
| type Limits struct { |
| + Seconds int64 `json:"seconds,omitempty"` |
| Calls int64 `json:"calls"` |
| InputTokens int64 `json:"input_tokens"` |
| OutputTokens int64 `json:"output_tokens"` |
diff --git a/internal/equipo/team/periodbudget.go b/internal/equipo/team/periodbudget.go| index 3e5dd25a..32cf3709 100644 |
| --- a/internal/equipo/team/periodbudget.go |
| +++ b/internal/equipo/team/periodbudget.go |
| @@ -151,6 +151,9 @@ func (s *Store) ConfigureBudgetsTx(ctx context.Context, tx *sql.Tx, account Acco |
| func period(at time.Time) string { return at.UTC().Format("2006-01") } |
| func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error) { |
| + return periodSumFor(ctx, tx, account, project, "", at) |
| +} |
| +func periodSumFor(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, person string, at time.Time) (PeriodUsage, error) { |
| var sum PeriodUsage |
| chargeQuery := "SELECT reserved FROM recovery_charges WHERE account=? AND substr(created_at,1,7)=?" |
| chargeArgs := []any{string(account), period(at)} |
| @@ -158,6 +161,9 @@ func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project Proje |
| chargeQuery += " AND project_id=?" |
| chargeArgs = append(chargeArgs, project) |
| } |
| + if person != "" { |
| + chargeQuery += " AND project_id=0" |
| + } |
| charges, err := tx.QueryContext(ctx, chargeQuery, chargeArgs...) |
| if err != nil { |
| return sum, err |
| @@ -190,6 +196,10 @@ func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project Proje |
| for _, table := range []string{"reservations", "time_reservations"} { |
| for _, settled := range []bool{false, true} { |
| q, args := periodQuery(table, account, project, at, settled) |
| + if person != "" { |
| + q += " AND job_id IN (SELECT id FROM jobs WHERE account=? AND requester=? AND json_extract(target,'$.kind')='conversation')" |
| + args = append(args, string(account), person) |
| + } |
| rows, err := tx.QueryContext(ctx, q, args...) |
| if err != nil { |
| return sum, err |
| @@ -280,8 +290,14 @@ func (s *Store) PeriodUsage(ctx context.Context, account AccountID, project Proj |
| func checkPeriodBudget(ctx context.Context, tx *sql.Tx, j jobRow, want PeriodLimits, now time.Time) (bool, error) { |
| b, configured, err := loadBudgets(ctx, tx, j.Account) |
| if err != nil || !configured { |
| + if err == nil && j.Target.Kind == TargetConversation { |
| + err = ErrBudget |
| + } |
| return configured, err |
| } |
| + if j.Target.Kind == TargetConversation { |
| + return true, checkCoordinatorBudget(ctx, tx, j, b, want, now) |
| + } |
| return true, CheckPlanBudgetTx(ctx, tx, j.Account, j.Project, b, want, now) |
| } |
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go| index 6544e078..1d99b85c 100644 |
| --- a/internal/equipo/team/scheduler.go |
| +++ b/internal/equipo/team/scheduler.go |
| @@ -127,6 +127,9 @@ func (s *Store) ClaimRevision(ctx context.Context, scope Scope, expectedRevision |
| return err |
| } |
| } |
| + if (j.Target.Kind == TargetConversation) != (st.Capability == CapCoordinate) { |
| + return ErrScope |
| + } |
| if j.Target.Kind == TargetProjectRead && st.Capability != CapResearch { |
| return ErrScope |
| } |
| @@ -309,6 +312,15 @@ func (s *Store) Complete(ctx context.Context, scope Scope, h Handle, r AttemptRe |
| if err != nil { |
| return err |
| } |
| + if r.Outcome == OutcomeSuccess && hd.job.Target.Kind == TargetConversation { |
| + var n int |
| + if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM events WHERE job_id=? AND type='coordinator.delivered'", scope.Job).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n != 1 { |
| + return ErrEvidence |
| + } |
| + } |
| if r.Outcome == OutcomeSuccess && hd.step.Capability == CapScope && hd.job.Evidence.Predicate == PredicateSoftwareFeature { |
| if err := completedFeatureScope(ctx, tx, hd); err != nil { |
| return err |
diff --git a/internal/equipo/team/shared.go b/internal/equipo/team/shared.go| index 34e86764..77b7da97 100644 |
| --- a/internal/equipo/team/shared.go |
| +++ b/internal/equipo/team/shared.go |
| @@ -112,6 +112,7 @@ func (s *Store) checkSharedSchema(ctx context.Context) error { |
| } |
| var sharedSchemaQueries = []string{ |
| + `SELECT account,person,revision,limits,content_hash FROM coordinator_limits LIMIT 0`, |
| `SELECT action_id,job_id,request_id,attempt_id,fence,runner,dispatch,expires_at,incarnation FROM admission_tickets LIMIT 0`, |
| `SELECT release_required,recovery_revision,reconciled_revision,clock_high_water FROM service LIMIT 0`, |
| `SELECT grant_stale,request_key,request_hash FROM jobs LIMIT 0`, |
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go| index 5e01bfb7..727c5732 100644 |
| --- a/internal/equipo/team/store.go |
| +++ b/internal/equipo/team/store.go |
| @@ -19,7 +19,7 @@ import ( |
| // SchemaVersion is the one schema this binary writes. A database with a |
| // newer version is refused (ErrStaleStore): the binary would not know the |
| // rows it was reading. |
| -const SchemaVersion = 7 |
| +const SchemaVersion = 8 |
| // Adapter executes one operation class against an external system. Execute |
| // runs an admitted dispatch and returns its receipt; an error from Execute |
| @@ -328,7 +328,7 @@ func (s *Store) migrate(ctx context.Context) error { |
| return err |
| } |
| v = 2 |
| - case v != 2 && v != 3 && v != 4 && v != 5 && v != 6 && v != SchemaVersion: |
| + case v != 2 && v != 3 && v != 4 && v != 5 && v != 6 && v != 7 && v != SchemaVersion: |
| return fail(CodeStaleStore, "unsupported schema %d", v) |
| } |
| rows, err := tx.QueryContext(ctx, `PRAGMA table_info(jobs)`) |
| @@ -395,6 +395,9 @@ func (s *Store) migrate(ctx context.Context) error { |
| if v < 7 { |
| _, err = tx.ExecContext(ctx, admissionSchema) |
| } |
| + if err == nil && v < 8 { |
| + _, err = tx.ExecContext(ctx, coordinatorSchema) |
| + } |
| return err |
| }) |
| } |
diff --git a/internal/equipo/team/subscription_test.go b/internal/equipo/team/subscription_test.go| index ac6a0aef..1cbf5a0a 100644 |
| --- a/internal/equipo/team/subscription_test.go |
| +++ b/internal/equipo/team/subscription_test.go |
| @@ -98,7 +98,7 @@ func TestMixedConnectionPolicies(t *testing.T) { |
| spec := softwareSpec(SoftwareSteps(false)) |
| spec.Policy = runnerPolicy(t, "metered") |
| _, err := e.store.CreateJob(e.ctx, spec) |
| - wantCode(t, err, CodeConflict) |
| + wantCode(t, err, CodeBudget) |
| } |
| func TestLoweredBudgetBlocksReservedAdmission(t *testing.T) { |
| e := newEnv(t) |
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go| index 75c48a17..49716815 100644 |
| --- a/internal/equipotest/execution_schema_test.go |
| +++ b/internal/equipotest/execution_schema_test.go |
| @@ -145,7 +145,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" { |
| + if m.ID != "equipo/0020_plans" && m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" { |
| before.Add(m) |
| } |
| } |
| @@ -154,7 +154,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error) |
| result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch", "equipo/0020_plans", "equipo/0021_coordinator"}) { |
| t.Fatalf("upgrade migrations: %v", result.Applied) |
| } |
| var account equipo.Account |
| @@ -174,7 +174,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" { |
| + if m.ID != "equipo/0020_plans" && m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" { |
| before.Add(m) |
| } |
| } |
| @@ -185,7 +185,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| executionMust(t, err) |
| result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch", "equipo/0020_plans", "equipo/0021_coordinator"}) { |
| t.Fatalf("task one upgrade migrations: %v", result.Applied) |
| } |
| var evidence string |
| @@ -207,7 +207,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0009_runner_policy" { |
| + if m.ID != "equipo/0020_plans" && m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" && m.ID != "equipo/0009_runner_policy" { |
| before.Add(m) |
| } |
| } |
| @@ -233,7 +233,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| return |
| } |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy", "equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch", "equipo/0020_plans", "equipo/0021_coordinator"}) { |
| t.Fatal("wrong task two upgrade", result.Applied) |
| } |
| var project, input, cost int |
| @@ -256,7 +256,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" { |
| + if m.ID != "equipo/0020_plans" && m.ID != "equipo/0021_coordinator" && m.ID != "equipo/0018_direct_launch" && m.ID != "equipo/0013_runner_assignments" && m.ID != "equipo/0012_tasks" { |
| before.Add(m) |
| } |
| } |
| @@ -265,7 +265,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| executionMust(t, seedExecutionJob(old.Writer())) |
| result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0012_tasks", "equipo/0013_runner_assignments", "equipo/0018_direct_launch", "equipo/0020_plans", "equipo/0021_coordinator"}) { |
| t.Fatal("task six upgrade migrations", result.Applied) |
| } |
| var key, hash string |
| @@ -273,8 +273,8 @@ func TestExecutionSchemaParity(t *testing.T) { |
| if key != "" || hash != "" { |
| t.Fatal("legacy request identity invented") |
| } |
| - if scalar(t, old, "SELECT schema_version FROM service") != 7 { |
| - t.Fatal("core version not seven") |
| + if scalar(t, old, "SELECT schema_version FROM service") != team.SchemaVersion { |
| + t.Fatal("core version not current") |
| } |
| for i := 0; i < 2; i++ { |
| result, err = migrate.Apply(ctx, old, equipo.BootSchema) |
| @@ -285,7 +285,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| } |
| }) |
| - coreNames := map[string]bool{"admission_tickets": true, "grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true} |
| + coreNames := map[string]bool{"coordinator_limits": true, "admission_tickets": true, "grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true} |
| var appCore migrate.Snapshot |
| for _, table := range expected.Tables { |
| if coreNames[table.Name] { |
| @@ -295,7 +295,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| if len(appCore.Tables) != len(coreNames) { |
| t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames)) |
| } |
| - for _, version := range []int{1, 2, 3, 4, 5, 6, 7} { |
| + for _, version := range []int{1, 2, 3, 4, 5, 6, 7, 8} { |
| t.Run(fmt.Sprint(version), func(t *testing.T) { |
| standalonePath := filepath.Join(t.TempDir(), "core.db") |
| core, err := team.Open(ctx, standalonePath, executionOptions()) |
| @@ -306,6 +306,10 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer raw.Close() |
| raw.SetMaxOpenConns(1) |
| executionMust(t, seedExecutionJob(raw)) |
| + if version < 8 { |
| + _, err = raw.Exec("DROP TABLE coordinator_limits") |
| + executionMust(t, err) |
| + } |
| if version < 7 { |
| _, err = raw.Exec("DROP TABLE admission_tickets") |
| executionMust(t, err) |
diff --git a/internal/plan3test/coordinator_migration_test.go b/internal/plan3test/coordinator_migration_test.go| new file mode 100644 |
| index 00000000..12d587ba |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_migration_test.go |
| @@ -0,0 +1,56 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| +) |
| + |
| +func TestCoordinatorMigrationUpgrade(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "coordinator-upgrade.db") |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, d.Close()) }) |
| + old := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0021_coordinator" { |
| + old.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, d, old) |
| + must(t, err) |
| + _, err = d.Writer().Exec("INSERT INTO audit_events(actor,kind,record_id,at) VALUES('historical','fixture','record',CURRENT_TIMESTAMP)") |
| + must(t, err) |
| + _, err = d.Writer().Exec("UPDATE service SET schema_version=7 WHERE id=1") |
| + must(t, err) |
| + result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if len(result.Applied) != 1 || result.Applied[0] != "equipo/0021_coordinator" { |
| + t.Fatal("wrong upgrade", result.Applied) |
| + } |
| + f := &fixture{DB: d, Store: equipo.NewStore(d)} |
| + if f.count(t, "SELECT count(*) FROM audit_events WHERE actor='historical'") != 1 { |
| + t.Fatal("upgrade lost history") |
| + } |
| + if f.count(t, "SELECT schema_version FROM service") != 8 { |
| + t.Fatal("core schema version not advanced") |
| + } |
| + for range 2 { |
| + core, err := team.OpenShared(ctx, d.Writer(), path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) |
| + must(t, err) |
| + must(t, core.Close()) |
| + } |
| + fresh := newFixture(t) |
| + upgraded, err := migrate.Read(ctx, d.Writer()) |
| + must(t, err) |
| + baseline, err := migrate.Read(ctx, fresh.DB.Writer()) |
| + must(t, err) |
| + if !upgraded.Equal(baseline) { |
| + t.Fatal("upgrade schema differs", upgraded.Diff(baseline)) |
| + } |
| +} |
diff --git a/internal/plan3test/coordinator_test.go b/internal/plan3test/coordinator_test.go| new file mode 100644 |
| index 00000000..49d5473e |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_test.go |
| @@ -0,0 +1,322 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "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 TestCoordinatorSingleWriter(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + first := queueCoordinator(t, f, "first", "first") |
| + second := queueCoordinator(t, f, "second", "second") |
| + if _, err := x.ClaimCoordinator(ctx, p, second.ID, second.Revision); err == nil { |
| + t.Fatal("later message overtook first") |
| + } |
| + var wg sync.WaitGroup |
| + results := make(chan error, 2) |
| + for _, turn := range []equipo.CoordinatorTurn{first, second} { |
| + wg.Add(1) |
| + go func() { defer wg.Done(); _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); results <- err }() |
| + } |
| + wg.Wait() |
| + close(results) |
| + successes := 0 |
| + for err := range results { |
| + if err == nil { |
| + successes++ |
| + } |
| + } |
| + if successes != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE state='running' AND message_id=?", first.MessageID) != 1 { |
| + t.Fatal("single writer or message ordering broken", successes) |
| + } |
| + if f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { |
| + t.Fatal("turn not admitted exactly once") |
| + } |
| + other := p |
| + other.RunnerID = "another-runner" |
| + if _, err := x.ClaimCoordinator(ctx, other, first.ID, first.Revision); err == nil { |
| + t.Fatal("other runner claimed binding") |
| + } |
| +} |
| +func TestCoordinatorAuthorityRevoked(t *testing.T) { |
| + for _, change := range []string{"membership", "role", "generation", "connection", "runner", "lookup"} { |
| + t.Run(change, func(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "hello", "turn") |
| + claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + switch change { |
| + case "membership": |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + case "role": |
| + f.exec(t, "UPDATE members SET revision=revision+1,role='member' WHERE address=?", owner.Address) |
| + case "generation": |
| + f.exec(t, "UPDATE coordinator_bindings SET generation=generation+1") |
| + case "connection": |
| + f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") |
| + case "runner": |
| + f.exec(t, "UPDATE runners SET revoked_at=?", time.Now().UTC()) |
| + case "lookup": |
| + f.exec(t, "ALTER TABLE members RENAME TO missing_members") |
| + } |
| + if err = x.ValidateCoordinator(ctx, p, claim); err == nil { |
| + t.Fatal("tool use ignored revoked authority") |
| + } |
| + if _, err = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| + t.Fatal("claim ignored revoked authority") |
| + } |
| + if _, err = x.RenewCoordinator(ctx, p, claim); err == nil { |
| + t.Fatal("renew ignored revoked authority") |
| + } |
| + }) |
| + } |
| +} |
| +func TestCoordinatorTurnReplay(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "hello", "turn") |
| + again, err := f.Store.QueueCoordinatorTurn(ctx, owner, turn.MessageID, 0, equipo.Mutation{RequestID: "turn"}) |
| + must(t, err) |
| + if again.ID != turn.ID { |
| + t.Fatal("queue replay duplicated turn") |
| + } |
| + msg, err := f.Store.SendMessage(ctx, owner, "", "different", equipo.Mutation{RequestID: "different"}) |
| + must(t, err) |
| + if _, err = f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: "turn"}); err == nil { |
| + t.Fatal("changed message replay accepted") |
| + } |
| + claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + if claim.Brief.AttemptDeadline.IsZero() || claim.Brief.AttemptDeadline != claim.AttemptDeadline { |
| + t.Fatal("coordinator brief omitted attempt deadline") |
| + } |
| + againClaim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + if againClaim.Handle.Attempt != claim.Handle.Attempt || f.count(t, "SELECT count(*) FROM admission_tickets") != 1 { |
| + t.Fatal("claim replay duplicated admission") |
| + } |
| + event := runnerproto.Event{Kind: "turn_completed", Payload: json.RawMessage(`{}`)} |
| + if err = x.CompleteCoordinator(ctx, p, claim, event); err == nil { |
| + t.Fatal("process completion proved delivery") |
| + } |
| + if _, err = f.Store.RetryCoordinatorTurn(ctx, owner, turn.ID, equipo.Mutation{RequestID: "retry", Revision: turn.Revision}); err == nil { |
| + t.Fatal("retry ignored containment") |
| + } |
| + _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + if err == nil { |
| + t.Fatal("reset advanced before containment") |
| + } |
| + if f.count(t, "SELECT count(*) FROM attempts WHERE state='stopping'") != 1 { |
| + t.Fatal("reset did not fence active attempt") |
| + } |
| +} |
| + |
| +func TestCoordinatorTurnDeliveryAtomic(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "hello", "delivery") |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + event := runnerproto.Event{Version: 2, ID: "delivered", TaskID: turn.ID, AssignmentID: turn.ID, ServerID: "fixture", AgentID: "fixture", SessionID: "session", TurnID: turn.ID, Kind: "coordinator.delivery", Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action, Payload: json.RawMessage(`{"result":"committed"}`), SourceTime: time.Now().UTC()} |
| + if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| + t.Fatal("missing delivery validator accepted") |
| + } |
| + x.SetRunnerValidators(equipo.RunnerValidators{CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) { |
| + return "Recorded answer", team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess}, nil |
| + }, Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + f.exec(t, "CREATE TRIGGER coordinator_delivery_failure BEFORE INSERT ON conversation_messages BEGIN SELECT RAISE(ABORT,'fixture delivery failure'); END") |
| + if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| + t.Fatal("delivery failure ignored") |
| + } |
| + if f.count(t, "SELECT count(*) FROM attempts WHERE state='succeeded'") != 0 || f.count(t, "SELECT count(*) FROM reservations WHERE state='settled'") != 0 { |
| + t.Fatal("delivery failure partially committed") |
| + } |
| + f.exec(t, "DROP TRIGGER coordinator_delivery_failure") |
| + must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| + must(t, x.CompleteCoordinator(ctx, p, c, event)) |
| + if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 1 || f.count(t, "SELECT count(*) FROM jobs WHERE state='succeeded'") != 1 { |
| + t.Fatal("turn delivery was not atomic and unique") |
| + } |
| + if f.count(t, "SELECT count(*) FROM audit_events WHERE actor=? AND delegating_person=? AND kind='coordinator.delivered'", "coordinator:"+c.Binding.ID, owner.Address) != 1 { |
| + t.Fatal("coordinator impersonated person") |
| + } |
| + event.Payload = json.RawMessage(`{"result":"changed"}`) |
| + if err = x.CompleteCoordinator(ctx, p, c, event); err == nil { |
| + t.Fatal("changed delivery replay accepted") |
| + } |
| + next := queueCoordinator(t, f, "next", "next") |
| + if _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision); err == nil { |
| + t.Fatal("delivery bypassed containment") |
| + } |
| + must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| + second, err := x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| + must(t, err) |
| + for _, message := range second.Context.Messages { |
| + if message.ID != next.MessageID { |
| + t.Fatal("unclassified prior project material entered coordinator context") |
| + } |
| + } |
| +} |
| +func TestCoordinatorTurnResetRetry(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "hello", "retry-test") |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + if err == nil { |
| + t.Fatal("reset skipped containment") |
| + } |
| + must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| + b2, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + if b2.Generation != b.Generation+1 { |
| + t.Fatal("reset did not advance generation") |
| + } |
| + if _, err = f.Store.QueueCoordinatorTurn(ctx, owner, turn.MessageID, 0, equipo.Mutation{RequestID: "retry-test"}); err == nil { |
| + t.Fatal("queue replay ignored changed binding") |
| + } |
| + retry, err := f.Store.RetryCoordinatorTurn(ctx, owner, turn.ID, equipo.Mutation{RequestID: "retry", Revision: 2}) |
| + must(t, err) |
| + c2, err := x.ClaimCoordinator(ctx, p, retry.ID, retry.Revision) |
| + must(t, err) |
| + if c2.Scope.Job == c.Scope.Job || c2.Handle.Attempt == c.Handle.Attempt || f.count(t, "SELECT count(*) FROM reservations") != 2 { |
| + t.Fatal("retry reused admission") |
| + } |
| + if err = x.ValidateCoordinator(ctx, p, c); err == nil { |
| + t.Fatal("old generation still works") |
| + } |
| +} |
| +func TestCoordinatorBudgetAbsentLimit(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + f.exec(t, "DELETE FROM coordinator_limits") |
| + turn := queueCoordinator(t, f, "hello", "no-limits") |
| + if _, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| + t.Fatal("missing personal budget granted authority") |
| + } |
| + if f.count(t, "SELECT count(*) FROM jobs") != 0 { |
| + t.Fatal("failed admission left a job") |
| + } |
| + f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| + if err := f.Store.SetCoordinatorLimits(ctx, peer, owner.Address, team.Limits{Calls: 1, InputTokens: 100, OutputTokens: 50, Seconds: 1200}, equipo.Mutation{RequestID: "unauthorized"}); err == nil { |
| + t.Fatal("non-owner set limits") |
| + } |
| + if _, err := f.Store.SaveCoordinatorBinding(ctx, peer, b.RunnerID, b.ConnectionID, equipo.Mutation{RequestID: "borrow"}); err == nil { |
| + t.Fatal("borrowed another person's subscription") |
| + } |
| +} |
| +func TestCoordinatorAuthorityProjectContext(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + var projectID int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id FROM projects LIMIT 1").Scan(&projectID)) |
| + f.exec(t, `UPDATE connection_choices SET connection_ids_json='["codex"]',pinned_id='codex'`) |
| + msg, err := f.Store.SendMessage(ctx, owner, "", "project question", equipo.Mutation{RequestID: "project"}) |
| + must(t, err) |
| + turn, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, projectID, equipo.Mutation{RequestID: "project"}) |
| + must(t, err) |
| + if _, err = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision); err == nil { |
| + t.Fatal("restricted project material entered prompt") |
| + } |
| + f.exec(t, "UPDATE coordinator_turns SET state='superseded'") |
| + general := queueCoordinator(t, f, "general question", "general") |
| + c, err := x.ClaimCoordinator(ctx, p, general.ID, general.Revision) |
| + must(t, err) |
| + if len(c.Context.Projects) != 0 || len(c.Context.Sources) != 0 { |
| + t.Fatal("general turn disclosed restricted project", c.Context) |
| + } |
| +} |
| + |
| +func TestCoordinatorSingleWriterStorageGuard(t *testing.T) { |
| + f, _, _, b := coordinatorFixture(t) |
| + a := queueCoordinator(t, f, "first", "first") |
| + z := queueCoordinator(t, f, "second", "second") |
| + f.exec(t, "UPDATE coordinator_turns SET state='running' WHERE id=?", a.ID) |
| + if _, err := f.DB.Writer().Exec("UPDATE coordinator_turns SET state='running' WHERE id=?", z.ID); err == nil { |
| + t.Fatal("storage permits two active coordinator turns", b.ID) |
| + } |
| +} |
| + |
| +func TestCoordinatorAuthorityCapabilityNegotiation(t *testing.T) { |
| + f, _, _, _ := coordinatorFixture(t) |
| + queueCoordinator(t, f, "hello", "http") |
| + hash := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + strings.Repeat("A", 43))) |
| + f.exec(t, "UPDATE runner_credentials SET token_hash=?", hex.EncodeToString(hash[:])) |
| + for _, caps := range []string{`[]`, `["coordinator.v1"]`} { |
| + request := httptest.NewRequest("POST", "/coordinator/poll", strings.NewReader(`{"version":2,"capabilities":`+caps+`}`)) |
| + request.Header.Set("Authorization", "Bearer "+strings.Repeat("A", 43)) |
| + request.Header.Set("Content-Type", "application/json") |
| + response := httptest.NewRecorder() |
| + f.Store.RunnerHandler().ServeHTTP(response, request) |
| + if caps == `[]` && response.Code != 403 { |
| + t.Fatal("old runner received coordinator work", response.Code) |
| + } |
| + if caps != `[]` && (response.Code != 200 || !strings.Contains(response.Body.String(), "message_id")) { |
| + t.Fatal("capable runner did not receive turn", response.Code, response.Body.String()) |
| + } |
| + } |
| +} |
| + |
| +func TestCoordinatorAuthorityClaimTampering(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "hello", "tamper") |
| + claim, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + for _, change := range []func(*equipo.CoordinatorClaim){func(c *equipo.CoordinatorClaim) { c.Handle.Fence++ }, func(c *equipo.CoordinatorClaim) { c.Admission.Dispatch.Action++ }, func(c *equipo.CoordinatorClaim) { c.Brief.Selection.Person = peer.Address }, func(c *equipo.CoordinatorClaim) { |
| + c.Context.Sources = []runnerproto.SourceSnapshot{{Payload: json.RawMessage(`{"forged":true}`)}} |
| + }} { |
| + changed := claim |
| + change(&changed) |
| + if err = x.ValidateCoordinator(ctx, p, changed); err == nil { |
| + t.Fatal("changed claim authorized tool use") |
| + } |
| + } |
| +} |
| + |
| +func TestCoordinatorTurnResetPreservesQueuedMessages(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + first := queueCoordinator(t, f, "first", "queued-first") |
| + queueCoordinator(t, f, "second", "queued-second") |
| + b, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset-queued", Revision: b.Revision}) |
| + must(t, err) |
| + turns, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(turns) != 1 || turns[0].MessageID != first.MessageID || turns[0].Generation != b.Generation { |
| + t.Fatal("reset lost queued messages", turns) |
| + } |
| + _, err = x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision) |
| + must(t, err) |
| +} |
diff --git a/internal/release/manifest.json b/internal/release/manifest.json| index 8c54f759..807d4b08 100644 |
| --- a/internal/release/manifest.json |
| +++ b/internal/release/manifest.json |
| @@ -110,6 +110,18 @@ |
| "action": "review", |
| "inventory_hash": "89def32bc61ed02bc26dcba811c6d14e556932ec5570dfcd6b54dcf23f79446b", |
| "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "coordinate", |
| + "inventory_hash": "0d4014b45648a34a48b35bdc37416dd440e7be2def55ce34b7cc93c5af1bf5d3", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "coordinate", |
| + "inventory_hash": "046ad41840ffb70ab541b5543644ee43f5fd4e14b539504126a8e8ba195ef28a", |
| + "status": "uncertified" |
| } |
| ] |
| } |
diff --git a/internal/release/manifest_test.go b/internal/release/manifest_test.go| index e2ea15e6..66c4aa92 100644 |
| --- a/internal/release/manifest_test.go |
| +++ b/internal/release/manifest_test.go |
| @@ -63,7 +63,7 @@ func TestToolProxyDigestPinned(t *testing.T) { |
| func TestPlanWorkflowReleasePolicyInventory(t *testing.T) { |
| m := BuildManifest() |
| for _, name := range []string{"claude", "codex"} { |
| - for _, action := range []string{"reproduce", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + for _, action := range []string{"coordinate", "reproduce", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| hash, err := ActionInventoryHash(name, action) |
| if err != nil { |
| t.Fatal(err) |
diff --git a/internal/runner/provider/actions.go b/internal/runner/provider/actions.go| index b68ca057..aa3cf783 100644 |
| --- a/internal/runner/provider/actions.go |
| +++ b/internal/runner/provider/actions.go |
| @@ -10,6 +10,8 @@ type ActionProfile struct { |
| func Profile(action string) (ActionProfile, error) { |
| p := ActionProfile{Action: action} |
| switch action { |
| + case "coordinate": |
| + p.Specialist, p.Submission, p.ReadOnly = "Coordinator", "submit_answer", true |
| case "reproduce": |
| p.Specialist, p.Submission = "Engineering", "submit_reproduction" |
| case "scope": |
diff --git a/internal/runner/provider/claude/launcher.go b/internal/runner/provider/claude/launcher.go| index 741fa1a3..2e908c83 100644 |
| --- a/internal/runner/provider/claude/launcher.go |
| +++ b/internal/runner/provider/claude/launcher.go |
| @@ -101,7 +101,7 @@ func nativeTools(role string) ([]string, error) { |
| switch role { |
| case "Engineering", "Copy", "Design": |
| return []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}, nil |
| - case "Review", "Product", "Scope", "Research": |
| + case "Review", "Product", "Scope", "Research", "Coordinator": |
| return []string{"Read", "Glob", "Grep", "Bash"}, nil |
| } |
| return nil, provider.ErrPolicy |
diff --git a/internal/runner/provider/claude/plan_policy_test.go b/internal/runner/provider/claude/plan_policy_test.go| index 3585ee11..7b070bae 100644 |
| --- a/internal/runner/provider/claude/plan_policy_test.go |
| +++ b/internal/runner/provider/claude/plan_policy_test.go |
| @@ -10,7 +10,7 @@ import ( |
| ) |
| func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| - for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + for _, action := range []string{"coordinate", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| profile, err := provider.Profile(action) |
| if err != nil { |
| t.Fatal(err) |
| @@ -30,7 +30,7 @@ func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| if json.Unmarshal(got.Settings, &settings) != nil { |
| t.Fatal("invalid settings") |
| } |
| - if (action == "scope" || action == "recommend" || action == "investigate" || action == "review") && (slices.Contains(got.Tools, "Write") || slices.Contains(got.Tools, "Edit")) { |
| + if (action == "coordinate" || action == "scope" || action == "recommend" || action == "investigate" || action == "review") && (slices.Contains(got.Tools, "Write") || slices.Contains(got.Tools, "Edit")) { |
| t.Fatal("read-only profile writes") |
| } |
| @@ -42,7 +42,7 @@ func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| } |
| func TestPlanWorkflowProviderPoliciesLauncher(t *testing.T) { |
| - for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + for _, action := range []string{"coordinate", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| t.Run(action, func(t *testing.T) { |
| f := fixtureFor(t, "Engineering") |
| p, _ := provider.Profile(action) |
diff --git a/internal/runner/provider/codex/plan_policy_test.go b/internal/runner/provider/codex/plan_policy_test.go| index 521d09b5..1a3170b1 100644 |
| --- a/internal/runner/provider/codex/plan_policy_test.go |
| +++ b/internal/runner/provider/codex/plan_policy_test.go |
| @@ -10,7 +10,7 @@ import ( |
| ) |
| func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| - for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + for _, action := range []string{"coordinate", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| profile, err := provider.Profile(action) |
| if err != nil { |
| t.Fatal(err) |
| @@ -31,7 +31,7 @@ func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| t.Fatal("invalid settings") |
| } |
| fs := settings["permissions"].(map[string]any)["equipo"].(map[string]any)["filesystem"].(map[string]any) |
| - if (action == "scope" || action == "recommend" || action == "investigate" || action == "review") && fs["/workspace"] != "read" { |
| + if (action == "coordinate" || action == "scope" || action == "recommend" || action == "investigate" || action == "review") && fs["/workspace"] != "read" { |
| t.Fatal("read-only profile writes") |
| } |
| @@ -43,7 +43,7 @@ func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| } |
| func TestPlanWorkflowProviderPoliciesLauncher(t *testing.T) { |
| - for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + for _, action := range []string{"coordinate", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| t.Run(action, func(t *testing.T) { |
| f := fixtureFor(t) |
| p, _ := provider.Profile(action) |
diff --git a/internal/runnerproto/coordinator.go b/internal/runnerproto/coordinator.go| new file mode 100644 |
| index 00000000..20018e26 |
| --- /dev/null |
| +++ b/internal/runnerproto/coordinator.go |
| @@ -0,0 +1,56 @@ |
| +package runnerproto |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "time" |
| +) |
| + |
| +type RunnerPrincipal struct{ RunnerID, Person, CredentialID string } |
| + |
| +const CoordinatorCapability = "coordinator.v1" |
| + |
| +type CoordinatorBinding struct { |
| + ID, Person, RunnerID, ConnectionID string |
| + Revision, Generation int64 |
| +} |
| +type CoordinatorTurn struct { |
| + ID, MessageID, RequestID, ProviderSessionID, ContextHash string |
| + Generation, Revision int64 |
| + State string |
| +} |
| +type CoordinatorMessage struct { |
| + ID, AuthorKind, AuthorID, Body string |
| + Sequence, Revision int64 |
| +} |
| +type CoordinatorProject struct { |
| + ID int64 |
| + Label string |
| + Revision int64 |
| +} |
| +type CoordinatorContext struct { |
| + ConversationID string |
| + Revision int64 |
| + Messages []CoordinatorMessage |
| + Projects []CoordinatorProject |
| + Sources []SourceSnapshot |
| + ConfirmedPreferences []string |
| +} |
| +type CoordinatorClaim struct { |
| + Binding CoordinatorBinding |
| + Turn CoordinatorTurn |
| + Scope team.Scope |
| + Handle team.Handle |
| + Brief RunnerBrief |
| + Context CoordinatorContext |
| + Admission team.AdmissionTicket |
| + LeaseDeadline, AttemptDeadline time.Time |
| +} |
| +type CoordinatorRequest struct { |
| + Version int `json:"version"` |
| + Capabilities []string `json:"capabilities"` |
| + TurnID string `json:"turn_id,omitempty"` |
| + Revision int64 `json:"revision,omitempty"` |
| + Claim *CoordinatorClaim `json:"claim,omitempty"` |
| + Event *Event `json:"event,omitempty"` |
| + Proof *ContainmentProof `json:"proof,omitempty"` |
| +} |
diff --git a/internal/runnerproto/coordinator_handler.go b/internal/runnerproto/coordinator_handler.go| new file mode 100644 |
| index 00000000..1f16125f |
| --- /dev/null |
| +++ b/internal/runnerproto/coordinator_handler.go |
| @@ -0,0 +1,61 @@ |
| +package runnerproto |
| + |
| +import ( |
| + "net/http" |
| + "slices" |
| +) |
| + |
| +func (s *Handler) coordinatorRunnerOperation(op string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q CoordinatorRequest |
| + if !s.Body(w, r, &q, MaxActionBytes) { |
| + return |
| + } |
| + if q.Version != DirectVersion || !slices.Contains(q.Capabilities, CoordinatorCapability) { |
| + s.Failure(w, s.Forbidden) |
| + return |
| + } |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + var value any |
| + var err error |
| + switch op { |
| + case "poll": |
| + value, err = s.Execution().PollCoordinator(r.Context(), p) |
| + case "claim": |
| + value, err = s.Execution().ClaimCoordinator(r.Context(), p, q.TurnID, q.Revision) |
| + default: |
| + if q.Claim == nil { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + switch op { |
| + case "renew": |
| + value, err = s.Execution().RenewCoordinator(r.Context(), p, *q.Claim) |
| + case "event": |
| + if q.Event == nil { |
| + err = s.Invalid |
| + } else { |
| + err = s.Execution().CoordinatorEvent(r.Context(), p, *q.Claim, *q.Event) |
| + } |
| + case "containment": |
| + if q.Proof == nil { |
| + err = s.Invalid |
| + } else { |
| + err = s.Execution().ContainCoordinator(r.Context(), p, *q.Claim, *q.Proof) |
| + } |
| + } |
| + } |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) |
| + } |
| +} |
diff --git a/internal/runnerproto/handler.go b/internal/runnerproto/handler.go| new file mode 100644 |
| index 00000000..a19e443b |
| --- /dev/null |
| +++ b/internal/runnerproto/handler.go |
| @@ -0,0 +1,308 @@ |
| +package runnerproto |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "github.com/go-chi/chi/v5" |
| + "mime" |
| + "net/http" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +type ExecutionAPI interface { |
| + PollCoordinator(context.Context, RunnerPrincipal) ([]CoordinatorTurn, error) |
| + ClaimCoordinator(context.Context, RunnerPrincipal, string, int64) (CoordinatorClaim, error) |
| + RenewCoordinator(context.Context, RunnerPrincipal, CoordinatorClaim) (time.Time, error) |
| + CoordinatorEvent(context.Context, RunnerPrincipal, CoordinatorClaim, Event) error |
| + ContainCoordinator(context.Context, RunnerPrincipal, CoordinatorClaim, ContainmentProof) error |
| + |
| + Sync(context.Context) error |
| + Poll(context.Context, RunnerPrincipal, string) ([]Assignment, error) |
| + Claim(context.Context, RunnerPrincipal, ClaimRequest) (ClaimResponse, error) |
| + RecoverClaim(context.Context, RunnerPrincipal, ClaimRequest) (ClaimResponse, error) |
| + Mutate(context.Context, RunnerPrincipal, string, RunnerRequest) (any, error) |
| + Cleanup(context.Context, string, string, RunnerRequest) (any, error) |
| + AcknowledgeRotation(context.Context, RunnerPrincipal, string) error |
| + ReadArtifact(context.Context, RunnerPrincipal, RunnerRequest, team.ArtifactID) (team.Artifact, error) |
| +} |
| +type Handler struct { |
| + Execution func() ExecutionAPI |
| + AuthenticateRunner func(context.Context, string) (RunnerPrincipal, error) |
| + ReportConnections func(context.Context, RunnerPrincipal, []ConnectionReport) error |
| + PutBlob func(context.Context, RunnerPrincipal, team.Scope, team.Handle, string, []byte) error |
| + Blob func(context.Context, RunnerPrincipal, team.Scope, string) ([]byte, error) |
| + Failure func(http.ResponseWriter, error) |
| + JSON func(http.ResponseWriter, int, any) |
| + Invalid, Forbidden, Unavailable error |
| + MaxBlobBytes int64 |
| +} |
| + |
| +func (s *Handler) Router() chi.Router { |
| + r := chi.NewRouter() |
| + for _, op := range []string{"poll", "claim", "renew", "event", "containment"} { |
| + r.Post("/coordinator/"+op, s.coordinatorRunnerOperation(op)) |
| + } |
| + r.Post("/poll", s.runnerPoll) |
| + r.Post("/blobs", s.runnerPutBlob) |
| + r.Post("/blobs/read", s.runnerReadBlob) |
| + r.Post("/claim", s.runnerClaim) |
| + r.Post("/recover_claim", s.runnerRecoverClaim) |
| + for _, op := range []string{"validate", "evidence", "freeze", "freeze_feature", "conclude", "publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { |
| + r.Post("/"+op, s.runnerMutation(op)) |
| + } |
| + r.Post("/connections", s.runnerConnections) |
| + r.Post("/heartbeat", s.runnerConnections) |
| + r.Get("/artifacts/{assignment}/{artifact}", s.runnerArtifact) |
| + return r |
| +} |
| +func (s *Handler) Body(w http.ResponseWriter, r *http.Request, v any, limit int64) bool { |
| + content, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || content != "application/json" || DecodeLimit(r.Body, v, limit) != nil { |
| + s.Failure(w, s.Invalid) |
| + return false |
| + } |
| + return true |
| +} |
| +func (s *Handler) Bearer(w http.ResponseWriter, r *http.Request) (RunnerPrincipal, string, bool) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + values := r.Header.Values("Authorization") |
| + if len(r.Header.Values("Cookie")) != 0 || len(values) != 1 || !strings.HasPrefix(values[0], "Bearer ") { |
| + s.Failure(w, s.Forbidden) |
| + return RunnerPrincipal{}, "", false |
| + } |
| + token := strings.TrimPrefix(values[0], "Bearer ") |
| + p, err := s.AuthenticateRunner(r.Context(), token) |
| + if err != nil { |
| + s.Failure(w, err) |
| + return p, "", false |
| + } |
| + return p, token, true |
| +} |
| +func (s *Handler) runnerPoll(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q PollRequest |
| + if !s.Body(w, r, &q, 8192) { |
| + return |
| + } |
| + if q.Version != 2 { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + if err := s.Execution().Sync(r.Context()); err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + value, err := s.Execution().Poll(r.Context(), p, q.After) |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) |
| +} |
| +func (s *Handler) runnerClaim(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q ClaimRequest |
| + if !s.Body(w, r, &q, 8192) { |
| + return |
| + } |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + value, err := s.Execution().Claim(r.Context(), p, q) |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) |
| +} |
| +func (s *Handler) runnerMutation(op string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + var q RunnerRequest |
| + limit := int64(MaxActionBytes) |
| + if op == "artifacts" { |
| + limit = 2 * MaxArtifactBytes |
| + } |
| + if op == "events" { |
| + limit = MaxEventBytes + 4096 |
| + } |
| + if !s.Body(w, r, &q, limit) { |
| + return |
| + } |
| + var value any |
| + var err error |
| + if strings.HasPrefix(r.Header.Get("Authorization"), "Cleanup ") { |
| + if len(r.Header.Values("Authorization")) != 1 || len(r.Header.Values("Cookie")) != 0 { |
| + s.Failure(w, s.Forbidden) |
| + return |
| + } |
| + value, err = s.Execution().Cleanup(r.Context(), strings.TrimPrefix(r.Header.Get("Authorization"), "Cleanup "), op, q) |
| + } else { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + value, err = s.Execution().Mutate(r.Context(), p, op, q) |
| + } |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) |
| + } |
| +} |
| +func (s *Handler) runnerConnections(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q HeartbeatRequest |
| + if !s.Body(w, r, &q, MaxActionBytes) { |
| + return |
| + } |
| + if q.Version != 2 || q.RequestID == "" || len(q.RequestID) > 256 { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + if q.RotationRequestID != "" { |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + if err := s.Execution().AcknowledgeRotation(r.Context(), p, q.RotationRequestID); err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + } |
| + if len(q.Reports) > 0 { |
| + var reports []ConnectionReport |
| + if DecodeLimit(strings.NewReader(string(q.Reports)), &reports, MaxActionBytes) != nil { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + if err := s.ReportConnections(r.Context(), p, reports); err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: struct{}{}}) |
| +} |
| +func (s *Handler) runnerArtifact(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + id, err := strconv.ParseInt(chi.URLParam(r, "artifact"), 10, 64) |
| + if err != nil { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + q := r.URL.Query() |
| + if q.Get("version") != "1" { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + attempt, err := strconv.ParseInt(q.Get("attempt"), 10, 64) |
| + if err != nil { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + fence, err := strconv.ParseInt(q.Get("fence"), 10, 64) |
| + if err != nil { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + job, err := strconv.ParseInt(q.Get("job"), 10, 64) |
| + if err != nil { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + request := RunnerRequest{Version: 2, AssignmentID: chi.URLParam(r, "assignment"), RequestID: q.Get("request_id"), Scope: Scope{Account: team.AccountID(q.Get("account")), Job: team.JobID(job)}, Handle: team.Handle{Attempt: team.AttemptID(attempt), Fence: fence, Runner: p.RunnerID}} |
| + value, err := s.Execution().ReadArtifact(r.Context(), p, request, team.ArtifactID(id)) |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) |
| +} |
| + |
| +func (s *Handler) runnerPutBlob(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q BlobRequest |
| + if !s.Body(w, r, &q, 2*s.MaxBlobBytes) { |
| + return |
| + } |
| + if q.Version != 2 { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + if err := s.PutBlob(r.Context(), p, q.Scope, q.Handle, q.Digest, q.Bytes); err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: struct{}{}}) |
| +} |
| +func (s *Handler) runnerReadBlob(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q BlobReadRequest |
| + if !s.Body(w, r, &q, 8192) { |
| + return |
| + } |
| + if q.Version != 2 { |
| + s.Failure(w, s.Invalid) |
| + return |
| + } |
| + b, err := s.Blob(r.Context(), p, q.Scope, q.Digest) |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: b}) |
| +} |
| + |
| +func (s *Handler) runnerRecoverClaim(w http.ResponseWriter, r *http.Request) { |
| + p, _, ok := s.Bearer(w, r) |
| + if !ok { |
| + return |
| + } |
| + var q ClaimRequest |
| + if !s.Body(w, r, &q, 8192) { |
| + return |
| + } |
| + if s.Execution() == nil { |
| + s.Failure(w, s.Unavailable) |
| + return |
| + } |
| + value, err := s.Execution().RecoverClaim(r.Context(), p, q) |
| + if err != nil { |
| + s.Failure(w, err) |
| + return |
| + } |
| + s.JSON(w, 200, WorkResponse{Version: 2, Result: value}) |
| +} |