feat: add guarded plan revisions and approval settings
Persist plan history, approval settings and task metadata with atomic graph edits. Preserve started work during project correction and recheck policy at preparation, dispatch and claim boundaries. Record targeted tests and guard mutations in the controller report.
29 files changed,
+2,331
−75
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+105 −0internal/equipo/conversation/store.go+1 −1internal/equipo/conversation/threads.go+24 −0internal/equipo/conversations.go+1 −1internal/equipo/copy.go+31 −0internal/equipo/migrations/0020_plans.sql+10 −0internal/equipo/migrations/schema.sql+9 −0internal/equipo/models.go+2 −1internal/equipo/planning/approval_settings.go+154 −0internal/equipo/planning/budget_test.go+10 −0internal/equipo/planning/dispatch.go+195 −0internal/equipo/planning/plans.go+306 −0internal/equipo/plans.go+226 −0internal/equipo/runner_execution.go+33 −0internal/equipo/task_prepare.go+39 −40internal/equipo/tasks.go+8 −18internal/equipo/team/jobs.go+186 −0internal/equipo/team/periodbudget.go+18 −10internal/equipo/team/plan_test.go+151 −0internal/equipo/team/scheduler.go+8 −1internal/equipotest/tasks_test.go+2 −2internal/plan3test/plans_approval_test.go+162 −0internal/plan3test/plans_migration_test.go+77 −0internal/plan3test/plans_test.go+263 −0internal/taskplan/budget_test.go+10 −0internal/taskplan/types.go+43 −0internal/taskplan/validate.go+111 −0internal/taskplan/validate_test.go+145 −0
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 3db08bcc..c5c48ef0 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -9,7 +9,7 @@ |
| # time <dir> <duration> <reason> |
| # perf <METHOD> <path> <duration>|skip <reason> |
| # boot <duration> <reason> |
| -size internal/equipo/team 8500 - Preserve the mandated core layout; final fixes add conservative period settlement and authority guards. Current source count: 8176. |
| +size internal/equipo/team 9000 - Task 2 keeps transaction-bound graph edits and period-ledger admission checks in the core. Measured 8565 source and 5975 test lines; tests remain under the default ceiling. Pure plan rules and application operations live in taskplan and planning. |
| 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. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index bf1d525d..b4cb6641 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -64,3 +64,108 @@ Each mutation was applied alone, the named test failed at an assertion (not a co |
| | `conversation.cursor_expired` | This conversation page has expired. Open the conversation again. | |
| Both entries are individually marked COPY REVIEW REQUIRED in copy.go. No copy-review server was started. No provider runs, live sign-ins, enrolment, external publication or Plan 2b code changes were needed. README is unchanged. Full report is in `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-1-report.md`. |
| + |
| +## Task 2 |
| + |
| +Task 2 adds guarded plan revisions and approval settings. Plans, task metadata, cards, audit and core graph changes share the execution transaction. Project corrections preserve started work and create an explicitly linked replacement. |
| + |
| +### Verification |
| + |
| +The first required command was run before implementation: |
| + |
| +`CGO_ENABLED=0 go test ./internal/taskplan ./internal/equipo/team ./internal/plan3test -run '^TestPlan' -count=1` |
| + |
| +Exit 1: missing Plan, Validate, ValidateEdit, EditUnstarted and ClaimRevision symbols. The named required-step, started-step, edit/claim race, approval-precedence and project-correction tests were already present. The same command passes after implementation and after restoration of every guard mutation. Final package times: taskplan 0.002s, team 0.427s, plan3test 1.912s. These are targeted timings, not full-suite measurements. |
| + |
| +Additional red/green evidence: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanProjectCorrectionPreparationStarted$' -count=1`: exit 1, “retargeted started preparation”; after counting preparation claims and fencing them, exit 0. |
| +- `CGO_ENABLED=0 go test ./internal/equipo/team -run '^TestPlanBudgetReadiness$' -count=1`: exit 1, undefined CheckPlanBudgetTx; after adding the existing-ledger check, exit 0. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanApprovalPrecedence$' -count=1`: an added conversation assertion failed with “proposal card is not visible in conversation”; attaching the card to a system reference message made the command pass. |
| +- `make migration-check`: initially exit 2 because SQL string defaults used single quotes while the GORM mirror emitted double quotes; corrected defaults pass, exit 0. |
| +- The legacy TestBugPreparationCrash/link assertion expected one orphaned job after a failed task link. It failed against the new atomic implementation. The assertion now requires zero jobs and no task link at that boundary; the recovery retry still creates exactly one job. |
| + |
| +Final targeted gates (all exit 0): |
| + |
| +- `CGO_ENABLED=0 go test ./internal/equipo/team -run '^(TestClaimFenceLeaseAndReclaim|TestConcurrentClaimsOneWinner|TestConcurrencyCaps|TestPeriodBudgetReservations|TestBudgetLoweringBelowUsage|TestPeriodBudgetSecondsAndOverflow|TestPeriodBudgetFailuresAreAtomic)$' -count=1` (0.470s). |
| +- `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestBugSubmissionRetry|TestBugPreparationCrash|TestBugStartGuards|TestRunnerPrepareOutbox|TestRunnerClaimAtomicRollback|TestRunnerClaimRetryAndRace)$' -count=1` (3.003s). |
| +- `CGO_ENABLED=0 go test ./internal/plan3test ./internal/equipo -run '^TestConversation|^TestTemplateCopyKeys$|^TestRunnerCopyInventory$' -count=1` (2.790s and 2.046s). |
| +- `CGO_ENABLED=0 go vet ./internal/taskplan ./internal/equipo/planning ./internal/equipo/conversation ./internal/equipo/team ./internal/equipo ./internal/plan3test ./internal/equipotest`. |
| +- `gofmt -l internal/taskplan internal/equipo internal/plan3test internal/equipotest` (no output), `git diff --check`, `make migration-check`, and `make budget`. |
| + |
| +TestPlanMigrationUpgrade verifies the 0019-to-0020 upgrade, exact BugPlan seed, preserved historical task state/revision/audit records, repeat migration, fresh-schema parity and core open/reopen on the upgraded app database. TestConversationMigrationSnapshot verifies the saved schema against ordered migrations. No core columns changed, so core SchemaVersion remains 7; the new task and plan records belong to Models and app migration 0020 only. |
| + |
| +### Guard mutations |
| + |
| +Each mutation was applied alone and restored in a finally block. All 18 produced assertion failures, not compile failures. The final required command passes with every guard restored. |
| + |
| +| Guard removed | Command | Exit | Observed failure | Restoration | |
| +| --- | --- | --- | --- | --- | |
| +| review invariant | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanRequiredSteps$/review/delete$ -count=1` | 1 | validate_test.go:40: mandatory step bypassed | Restored | |
| +| checks invariant | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanRequiredSteps$/verify/delete$ -count=1` | 1 | validate_test.go:40: mandatory step bypassed | Restored | |
| +| final person | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanRequiredSteps$/merge/delete$ -count=1` | 1 | validate_test.go:40: mandatory step bypassed | Restored | |
| +| duplicate keys | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanRequiredSteps$/duplicate$ -count=1` | 1 | validate_test.go:67: invalid plan accepted | Restored | |
| +| dependency cycle | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanRequiredSteps$/cycle$ -count=1` | 1 | validate_test.go:67: invalid plan accepted | Restored | |
| +| evidence before publication | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanRequiredSteps$/early_publish$ -count=1` | 1 | validate_test.go:67: invalid plan accepted | Restored | |
| +| started app step | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanStartedImmutable$/instructions$ -count=1` | 1 | validate_test.go:109: started step changed | Restored | |
| +| core revision | `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestPlanRevisionFences$ -count=1` | 1 | plan_test.go:148: want revision, got nil | Restored | |
| +| claim revision | `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestPlanRevisionFences$ -count=1` | 1 | plan_test.go:150: want revision, got nil | Restored | |
| +| started core dependencies | `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestPlanStartedImmutable$ -count=1` | 1 | plan_test.go:56: started core step changed | Restored | |
| +| approval at dispatch | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanApprovalPrecedenceDispatch$ -count=1` | 1 | plans_approval_test.go:36: switch to required did not stop dispatch <nil> | Restored | |
| +| override precedence | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanApprovalPrecedence$ -count=1` | 1 | plans_test.go:60: override ignored | Restored | |
| +| period budget | `CGO_ENABLED=0 go test ./internal/equipo/team -run ^TestPlanBudgetReadiness$ -count=1` | 1 | plan_test.go:97: want budget, got nil | Restored | |
| +| hidden execution limit | `CGO_ENABLED=0 go test ./internal/taskplan -run ^TestPlanExecutionLimit$ -count=1` | 1 | validate_test.go:133: hidden publication exceeds limit | Restored | |
| +| approval at preparation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanApprovalPrecedenceStart$ -count=1` | 1 | plans_approval_test.go:143: prepare ignored current approval <nil> | Restored | |
| +| approval at core creation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanApprovalPrecedenceStart$ -count=1` | 1 | plans_approval_test.go:150: start ignored current approval <nil> | Restored | |
| +| approval at claim | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanApprovalPrecedenceClaim$ -count=1` | 1 | plans_approval_test.go:115: claim ignored current approval mode <nil> | Restored | |
| +| setting revision | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanApprovalPrecedence$ -count=1` | 1 | plans_test.go:49: two tabs lost update <nil> | Restored | |
| + |
| +### Contracts and integration |
| + |
| +- New proposals accept empty TaskID and revision 0. The server assigns task/thread/card identities and revision 1. Task, outbox, history, system reference message, card and audit commit together. |
| +- Plan edits and approvals use the plan revision. Task.Revision also advances for task-level changes. Approval settings use their own revision, with 0 only for the first write. Nil personal overrides retain a revisioned inheritance row. Current authority is checked before replay; identical requests return the saved result and changed canonical inputs conflict. |
| +- Plans are ordered. DependsOn adds explicit references to earlier steps; backwards references and cycles fail. Required flags are recomputed by the server. Publication uses canonical review, verify and merge keys with review, checks and person actions. Checks and final-person steps cannot select a model/account. If publish is omitted, compilation inserts it before the person and counts it against the limit. |
| +- App history stores immutable plan JSON, actor kind/address, changed step keys and UTC time. Core steps/attempts and runner assignments retain actual execution identity. Instruction-only edits also advance the core revision. Every claim advances the job revision, including claims while the job is already running. ClaimRevision is available to consumers with a captured revision; legacy Claim remains a wrapper. |
| +- EditUnstarted runs under the bound transaction, checks the current grant and expected core revision, retains cancelled step rows, recomputes ordered dependencies and requires review/checks after every candidate-producing core step. Core graph capacity includes retained historical step identities; cancelled keys cannot be reused. |
| +- Preparation, core-job creation, pending assignment generation and new claims recheck approval policy, work authority, model eligibility and the existing period budget ledger. No second budget counter is introduced. Approval is not itself provider admission. StartBug creates the job and task link in one transaction, with a request key formed from task ID and plan revision. |
| +- Before any start, project correction clears saved picks, preparation, approval and the job link. An existing unstarted job is cancelled without deleting its history. Once a step or preparation has started, the old target stays fixed, pending/claimed assignments are fenced, core cancellation requests containment, and a linked replacement stays proposed until explicitly approved. Replacement history attributes the real correcting actor while retaining the original requester’s connection ownership. |
| +- Task and outbox models now live in planning, with root aliases preserving callers. Feature operations use transaction-bound authority, audit, conversation, runner-fencing and readiness callbacks. The public ProposePlan entry remains a verified-person operation. Task 6 must add coordinator attribution and delegated authority to its own transaction path, not manufacture a person Actor. |
| + |
| +### Size budget |
| + |
| +| Directory | Source lines | Test lines | |
| +| --- | ---: | ---: | |
| +| `internal/equipo/team` | 8565 | 5975 | |
| +| `internal/equipo` | 10073 | 437 | |
| +| `internal/equipo/planning` | 655 | 10 | |
| +| `internal/equipo/conversation` | 452 | 9 | |
| +| `internal/taskplan` | 154 | 155 | |
| +| `internal/plan3test` | 0 | 1034 | |
| + |
| +make budget initially failed at 8565 core source lines against the existing 8500 ceiling. The core exception now allows 9000 source lines and records the measured 8565 source / 5975 test lines. The graph transaction and ledger hook remain in the core; pure validation and application operations were extracted. No new default-valued exceptions or time changes were added. |
| + |
| +### Concerns |
| + |
| +All five kinds are persisted and validated. Investigation/recommendation plans allow only read-only planning actions plus a person checkpoint. The existing executable adapter still supports the bug lane; non-bug dispatch fails closed until the kind-specific evidence and runner workflow in Tasks 3, 4 and 7 are installed. This change does not claim an executable investigation or recommendation run. A kind change on an existing core job is refused to preserve its evidence contract. No person step is compiled into runner execution; the existing review-branch/human-merge path remains in place. |
| + |
| +The 15 new runtime entries remain individually pending copy review. No browser copy review, external drafter, reviewer agent, provider session, sign-in or live enrolment was used. Connection/runner records in tests are isolated fixtures. Full suites, make ci and live release gates were not run. The inherited Plan 2b certificate, live-driver and policy-digest blockers remain. Task 9 still owns general plan rendering and editing screens; Task 10 owns API projections. |
| + |
| +### Copy pending review |
| + |
| +| Key | Draft text | |
| +| --- | --- | |
| +| `plan.proposed` | Proposed plan | |
| +| `plan.edit` | Edit plan | |
| +| `plan.approve` | Approve plan | |
| +| `plan.immediate` | Start straight away | |
| +| `plan.required` | Wait for approval | |
| +| `plan.inherit` | Use the project setting | |
| +| `plan.locked_step` | This step has started and cannot be changed. | |
| +| `plan.revision_conflict` | The plan has changed. Open the latest version. | |
| +| `plan.project` | Project | |
| +| `plan.correct_project` | Correct project | |
| +| `plan.replacement` | Replacement task | |
| +| `plan.investigation_checkpoint` | Review the findings before planning more work. | |
| +| `plan.playbook` | Playbook | |
| +| `plan.changes` | Plan changes | |
| +| `task.state.proposed` | Proposed | |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index a046f421..fb01d7be 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -21,7 +21,7 @@ type Dependencies struct { |
| Task func(*gorm.DB, kernel.Actor, string) (TaskAccess, error) |
| Audit func(*gorm.DB, kernel.Actor, string, string) error |
| NotFound, Conflict, Invalid, CursorExpired error |
| - RoutedCopy string |
| + ProposedCopy, RoutedCopy string |
| } |
| type Store struct { |
| tx *gorm.DB |
diff --git a/internal/equipo/conversation/threads.go b/internal/equipo/conversation/threads.go| index 0a8ce8ac..97c6b1eb 100644 |
| --- a/internal/equipo/conversation/threads.go |
| +++ b/internal/equipo/conversation/threads.go |
| @@ -124,3 +124,27 @@ func (s *Store) RouteMessage(actor kernel.Actor, messageID, taskID string, m ker |
| } |
| return reply, s.save(req, reply) |
| } |
| + |
| +// TaskCard participates in the task transaction and contains no authority. |
| +func (s *Store) TaskCard(actor kernel.Actor, task TaskAccess) error { |
| + main, err := s.main(actor) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err = EnsureThread(s.tx, task.ID, task.TeamID); err != nil { |
| + return err |
| + } |
| + var old cardRecord |
| + err = s.tx.Where("stream_id=? AND kind='task' AND resource_id=?", main.ID, task.ID).First(&old).Error |
| + if err == nil { |
| + return s.tx.Model(&cardRecord{}).Where("id=?", old.ID).Select("Revision").Updates(&cardRecord{Revision: task.Revision}).Error |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + notice, err := s.appendMessage(main.ID, main.ID, "", "system", "system", s.deps.ProposedCopy, "reference") |
| + if err != nil { |
| + return err |
| + } |
| + return s.tx.Create(&cardRecord{ID: notice.ID, StreamID: main.ID, Kind: "task", ResourceID: task.ID, Revision: task.Revision, Sequence: notice.Sequence}).Error |
| +} |
diff --git a/internal/equipo/conversations.go b/internal/equipo/conversations.go| index a4fb84ec..48025706 100644 |
| --- a/internal/equipo/conversations.go |
| +++ b/internal/equipo/conversations.go |
| @@ -39,7 +39,7 @@ func conversationAt(tx *gorm.DB) *conversation.Store { |
| err = tx.Where("id=? AND team_id=?", id, teamID).First(&task).Error |
| return conversation.TaskAccess{ID: task.ID, TeamID: task.TeamID, Requester: task.Requester, Revision: task.Revision}, storeError(err) |
| }, |
| - Audit: appendAudit, NotFound: ErrNotFound, Conflict: ErrConflict, Invalid: ErrInvalid, CursorExpired: ErrCursorExpired, RoutedCopy: pageCopy["conversation.routed"], |
| + Audit: appendAudit, NotFound: ErrNotFound, Conflict: ErrConflict, Invalid: ErrInvalid, CursorExpired: ErrCursorExpired, RoutedCopy: pageCopy["conversation.routed"], ProposedCopy: copyText("plan.proposed"), |
| }) |
| } |
| func (s *Store) Conversation(ctx context.Context, actor Actor, cursor string, limit int) (ConversationPage, error) { |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 12a4bd03..29958405 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -205,6 +205,37 @@ func RunnerToolCopy() runner.ToolCopy { |
| // runnerDraftCopy is the Task 16 runtime inventory. Each entry needs review. |
| var runnerDraftCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: plan.proposed |
| + "plan.proposed": "Proposed plan", |
| + // COPY REVIEW REQUIRED: plan.edit |
| + "plan.edit": "Edit plan", |
| + // COPY REVIEW REQUIRED: plan.approve |
| + "plan.approve": "Approve plan", |
| + // COPY REVIEW REQUIRED: plan.immediate |
| + "plan.immediate": "Start straight away", |
| + // COPY REVIEW REQUIRED: plan.required |
| + "plan.required": "Wait for approval", |
| + // COPY REVIEW REQUIRED: plan.inherit |
| + "plan.inherit": "Use the project setting", |
| + // COPY REVIEW REQUIRED: plan.locked_step |
| + "plan.locked_step": "This step has started and cannot be changed.", |
| + // COPY REVIEW REQUIRED: plan.revision_conflict |
| + "plan.revision_conflict": "The plan has changed. Open the latest version.", |
| + // COPY REVIEW REQUIRED: plan.project |
| + "plan.project": "Project", |
| + // COPY REVIEW REQUIRED: plan.correct_project |
| + "plan.correct_project": "Correct project", |
| + // COPY REVIEW REQUIRED: plan.replacement |
| + "plan.replacement": "Replacement task", |
| + // COPY REVIEW REQUIRED: plan.investigation_checkpoint |
| + "plan.investigation_checkpoint": "Review the findings before planning more work.", |
| + // COPY REVIEW REQUIRED: plan.playbook |
| + "plan.playbook": "Playbook", |
| + // COPY REVIEW REQUIRED: plan.changes |
| + "plan.changes": "Plan changes", |
| + // COPY REVIEW REQUIRED: task.state.proposed |
| + "task.state.proposed": "Proposed", |
| + |
| // COPY REVIEW REQUIRED: live.answer |
| "live.answer": "Type Allow once, Deny, or an answers JSON object. This request expires in 60 seconds.", |
| // COPY REVIEW REQUIRED: live.beyond-profile |
diff --git a/internal/equipo/migrations/0020_plans.sql b/internal/equipo/migrations/0020_plans.sql| new file mode 100644 |
| index 00000000..6113161e |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0020_plans.sql |
| @@ -0,0 +1,10 @@ |
| +ALTER TABLE tasks ADD COLUMN kind text NOT NULL DEFAULT "bug"; |
| +ALTER TABLE tasks ADD COLUMN plan_revision integer NOT NULL DEFAULT 0; |
| +ALTER TABLE tasks ADD COLUMN approval_revision integer NOT NULL DEFAULT 0; |
| +ALTER TABLE tasks ADD COLUMN replacement_id text NOT NULL DEFAULT ""; |
| +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)); |
| +INSERT INTO plan_revisions(task_id,revision,plan,actor_kind,actor,changed_keys,created_at) SELECT id,1,json_object('TaskID',id,'Revision',1,'Kind','bug','ProjectID',project_id,'Steps',json('[{"Key":"reproduce","Specialist":"engineering","Action":"reproduce","Instructions":"","ConnectionID":"","Model":"","SelectionReason":"","Required":false,"DependsOn":null},{"Key":"implement","Specialist":"engineering","Action":"implement","Instructions":"","ConnectionID":"","Model":"","SelectionReason":"","Required":false,"DependsOn":null},{"Key":"review","Specialist":"review","Action":"review","Instructions":"","ConnectionID":"","Model":"","SelectionReason":"","Required":true,"DependsOn":null},{"Key":"verify","Specialist":"","Action":"checks","Instructions":"","ConnectionID":"","Model":"","SelectionReason":"","Required":true,"DependsOn":null},{"Key":"publish","Specialist":"","Action":"publish","Instructions":"","ConnectionID":"","Model":"","SelectionReason":"","Required":false,"DependsOn":null},{"Key":"merge","Specialist":"","Action":"person","Instructions":"","ConnectionID":"","Model":"","SelectionReason":"","Required":true,"DependsOn":null}]'),'PlaybookID','','PlaybookRevision',0),'system','migration/0020','[]',CURRENT_TIMESTAMP FROM tasks; |
| +UPDATE tasks SET plan_revision=1; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index e255d7d6..1c703b28 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -360,3 +360,12 @@ CREATE TABLE conversation_requests (principal text, operation text, resource tex |
| CREATE TABLE conversation_routes (source_id text PRIMARY KEY, task_id text, reply_id text, notice_id text); |
| CREATE TABLE conversation_outboxes (message_id text PRIMARY KEY, stream_id text, purpose text); |
| CREATE TABLE conversation_cursors (id text PRIMARY KEY, principal text, stream_id text, after integer, through integer, revision integer, expires_at datetime); |
| + |
| +ALTER TABLE tasks ADD COLUMN kind text NOT NULL DEFAULT "bug"; |
| +ALTER TABLE tasks ADD COLUMN plan_revision integer NOT NULL DEFAULT 0; |
| +ALTER TABLE tasks ADD COLUMN approval_revision integer NOT NULL DEFAULT 0; |
| +ALTER TABLE tasks ADD COLUMN replacement_id text NOT NULL DEFAULT ""; |
| +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)); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 3ecdc7b7..cd6cc257 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -5,9 +5,10 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/conversation" |
| "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| ) |
| -var Models = append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...) |
| +var Models = append(append(append([]any{&supervisedTrialRecord{}, &questionRecord{}, &runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...), conversation.Models...), planning.Models...) |
| type Role string |
diff --git a/internal/equipo/planning/approval_settings.go b/internal/equipo/planning/approval_settings.go| new file mode 100644 |
| index 00000000..f6e56e65 |
| --- /dev/null |
| +++ b/internal/equipo/planning/approval_settings.go |
| @@ -0,0 +1,154 @@ |
| +package planning |
| + |
| +import ( |
| + "errors" |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type ApprovalMode string |
| + |
| +const ( |
| + ApprovalImmediate ApprovalMode = "immediate" |
| + ApprovalRequired ApprovalMode = "required" |
| +) |
| + |
| +type ApprovalSetting struct { |
| + ProjectID int64 `gorm:"primaryKey;autoIncrement:false"` |
| + Person string `gorm:"primaryKey"` |
| + Mode ApprovalMode |
| + Revision int64 |
| +} |
| + |
| +func (ApprovalSetting) TableName() string { return "plan_approval_settings" } |
| +func validMode(mode ApprovalMode) bool { return mode == ApprovalImmediate || mode == ApprovalRequired } |
| +func (s *Store) Approval(person string, projectID int64) (ApprovalMode, error) { |
| + for _, p := range []string{person, ""} { |
| + var row ApprovalSetting |
| + err := s.tx.First(&row, "project_id=? AND person=?", projectID, p).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + continue |
| + } |
| + if err != nil { |
| + return "", err |
| + } |
| + if row.Mode == "" && p != "" { |
| + continue |
| + } |
| + if !validMode(row.Mode) { |
| + return "", s.deps.Unavailable |
| + } |
| + return row.Mode, nil |
| + } |
| + return ApprovalImmediate, nil |
| +} |
| +func (s *Store) SetApproval(actor kernel.Actor, projectID int64, mode *ApprovalMode, m kernel.Mutation, project bool) error { |
| + if err := s.deps.Member(s.tx, actor, project); err != nil { |
| + return err |
| + } |
| + if err := s.deps.Project(s.tx, projectID); err != nil { |
| + return err |
| + } |
| + if (project && mode == nil) || (mode != nil && !validMode(*mode)) { |
| + return s.deps.Invalid |
| + } |
| + person, op := actor.Address, "plan.override" |
| + if project { |
| + person = "" |
| + op = "plan.project_approval" |
| + } |
| + var result bool |
| + q, replay, err := s.request(actor, op, strconv.FormatInt(projectID, 10), m, struct { |
| + Mode *ApprovalMode |
| + Revision int64 |
| + }{mode, m.Revision}, &result) |
| + if err != nil || replay { |
| + return err |
| + } |
| + row := ApprovalSetting{ProjectID: projectID, Person: person} |
| + err = s.tx.First(&row, "project_id=? AND person=?", projectID, person).Error |
| + exists := err == nil |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return err |
| + } |
| + if row.Revision != m.Revision { |
| + return s.deps.Conflict |
| + } |
| + row.Mode = "" |
| + if mode != nil { |
| + row.Mode = *mode |
| + } |
| + row.Revision++ |
| + if exists { |
| + err = s.tx.Model(&ApprovalSetting{}).Where("project_id=? AND person=?", projectID, person).Select("Mode", "Revision").Updates(&row).Error |
| + } else { |
| + err = s.tx.Create(&row).Error |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if err = s.deps.Audit(s.tx, actor, op, strconv.FormatInt(projectID, 10)); err != nil { |
| + return err |
| + } |
| + return s.save(q, true) |
| +} |
| +func (s *Store) Approve(actor kernel.Actor, id string, m kernel.Mutation) (Task, error) { |
| + t, err := s.task(actor, id) |
| + if err != nil { |
| + return t, err |
| + } |
| + var result Task |
| + q, replay, err := s.request(actor, "plan.approve", id, m, m, &result) |
| + if err != nil || replay { |
| + return result, err |
| + } |
| + p, err := s.Plan(t) |
| + if err != nil { |
| + return result, err |
| + } |
| + if m.Revision <= 0 || p.Revision != m.Revision { |
| + return result, s.deps.Conflict |
| + } |
| + if err = s.deps.Ready(s.tx, t, p); err != nil { |
| + return result, err |
| + } |
| + if t.PlanRevision == 0 { |
| + t.PlanRevision = 1 |
| + if err = s.history(&t, p, actor, nil); err != nil { |
| + return result, err |
| + } |
| + } |
| + t.ApprovalRevision = t.PlanRevision |
| + t.Revision++ |
| + if err = s.persist(t, actor, "plan.approve"); err != nil { |
| + return result, err |
| + } |
| + return t, s.save(q, t) |
| +} |
| +func (s *Store) CheckDispatch(actor kernel.Actor, id string) error { |
| + t, err := s.task(actor, id) |
| + if err != nil { |
| + return err |
| + } |
| + switch t.State { |
| + case "cancelled", "cancel_requested", "merged", "succeeded", "failed", "merge": |
| + return s.deps.Conflict |
| + } |
| + p, err := s.Plan(t) |
| + if err != nil { |
| + return err |
| + } |
| + if taskErr := taskPlanValid(p); taskErr != nil { |
| + return s.deps.Invalid |
| + } |
| + mode, err := s.Approval(t.Requester, t.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + if (mode == ApprovalRequired || t.ReplacesID != "") && t.ApprovalRevision != p.Revision { |
| + return s.deps.Conflict |
| + } |
| + return s.deps.Ready(s.tx, t, p) |
| +} |
diff --git a/internal/equipo/planning/budget_test.go b/internal/equipo/planning/budget_test.go| new file mode 100644 |
| index 00000000..72a27b56 |
| --- /dev/null |
| +++ b/internal/equipo/planning/budget_test.go |
| @@ -0,0 +1,10 @@ |
| +package planning |
| + |
| +import ( |
| + "os" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/equipo/planning/dispatch.go b/internal/equipo/planning/dispatch.go| new file mode 100644 |
| index 00000000..48493530 |
| --- /dev/null |
| +++ b/internal/equipo/planning/dispatch.go |
| @@ -0,0 +1,195 @@ |
| +package planning |
| + |
| +import ( |
| + "reflect" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +func taskPlanValid(p taskplan.Plan) error { return taskplan.Validate(p) } |
| +func ExecutionSteps(p taskplan.Plan) ([]team.StepSpec, error) { |
| + if err := taskplan.Validate(p); err != nil { |
| + return nil, err |
| + } |
| + var steps []team.StepSpec |
| + publish := false |
| + add := func(key string, cap team.Capability) { |
| + st := team.StepSpec{Key: key, Capability: cap, Version: 1} |
| + if len(steps) > 0 { |
| + st.DependsOn = []string{steps[len(steps)-1].Key} |
| + } |
| + steps = append(steps, st) |
| + } |
| + for _, st := range p.Steps { |
| + var cap team.Capability |
| + switch st.Action { |
| + case "reproduce": |
| + cap = team.CapReproduce |
| + case "implement": |
| + cap = team.CapImplement |
| + case "review": |
| + cap = team.CapReview |
| + case "checks": |
| + cap = team.CapVerify |
| + case "publish": |
| + cap = team.CapPublish |
| + publish = true |
| + case "person": |
| + if taskplan.Publication(p.Kind) && !publish { |
| + add("publish", team.CapPublish) |
| + } |
| + continue |
| + default: |
| + return nil, taskplan.ErrInvalid |
| + } |
| + add(st.Key, cap) |
| + } |
| + return steps, nil |
| +} |
| +func GraphChange(p taskplan.Plan, old []team.Step) (team.PlanChange, error) { |
| + specs, err := ExecutionSteps(p) |
| + if err != nil { |
| + return team.PlanChange{}, err |
| + } |
| + c := team.PlanChange{} |
| + existing := map[string]team.Step{} |
| + seen := map[string]bool{} |
| + for _, st := range old { |
| + existing[st.Key] = st |
| + } |
| + for _, st := range specs { |
| + seen[st.Key] = true |
| + c.Order = append(c.Order, st.Key) |
| + prior, ok := existing[st.Key] |
| + if !ok { |
| + c.Append = append(c.Append, st) |
| + } else if prior.Capability != st.Capability || !reflect.DeepEqual(append([]string{}, prior.DependsOn...), append([]string{}, st.DependsOn...)) { |
| + c.Replace = append(c.Replace, st) |
| + } |
| + } |
| + for _, st := range old { |
| + if !seen[st.Key] && st.State != team.StepCancelled { |
| + c.Cancel = append(c.Cancel, st.Key) |
| + } |
| + } |
| + return c, nil |
| +} |
| +func (s *Store) Correct(actor kernel.Actor, id string, projectID int64, m kernel.Mutation) (Task, error) { |
| + t, err := s.task(actor, id) |
| + if err != nil { |
| + return t, err |
| + } |
| + a, err := s.deps.Access(s.tx, actor, projectID) |
| + if err != nil { |
| + return Task{}, err |
| + } |
| + var result Task |
| + q, replay, err := s.request(actor, "plan.correct", id, m, struct{ ProjectID, Revision int64 }{projectID, m.Revision}, &result) |
| + if err != nil || replay { |
| + return result, err |
| + } |
| + p, err := s.Plan(t) |
| + if err != nil { |
| + return result, err |
| + } |
| + if m.Revision <= 0 || m.Revision != p.Revision { |
| + return result, s.deps.Conflict |
| + } |
| + started, err := s.deps.Started(s.tx, t.ID) |
| + if err != nil { |
| + return result, err |
| + } |
| + if t.JobID != 0 { |
| + if s.deps.Core == nil { |
| + return result, s.deps.Unavailable |
| + } |
| + scope := team.Scope{Account: team.AccountID(t.TeamID), Job: t.JobID} |
| + steps, err := s.deps.Core.Steps(s.ctx, scope) |
| + if err != nil { |
| + return result, err |
| + } |
| + for _, st := range steps { |
| + if st.Attempts > 0 { |
| + started = true |
| + } |
| + } |
| + job, err := s.deps.Core.GetJob(s.ctx, scope) |
| + if err != nil { |
| + return result, err |
| + } |
| + if !job.State.Terminal() { |
| + if _, err = s.deps.Core.Cancel(s.ctx, scope, actor.Address, "project_corrected"); err != nil { |
| + return result, err |
| + } |
| + } |
| + } |
| + if err = s.deps.Stop(s.tx, t.ID); err != nil { |
| + return result, err |
| + } |
| + before := p |
| + if started { |
| + p.TaskID = "" |
| + p.Revision = 0 |
| + p.ProjectID = projectID |
| + for i := range p.Steps { |
| + p.Steps[i].ConnectionID = "" |
| + p.Steps[i].Model = "" |
| + p.Steps[i].SelectionReason = "" |
| + } |
| + replacementKey, err := kernel.InputHash(q) |
| + if err != nil { |
| + return result, err |
| + } |
| + replacement, err := s.propose(actor, t.Requester, p, kernel.Mutation{RequestID: replacementKey}) |
| + if err != nil { |
| + return result, err |
| + } |
| + if err = s.tx.Model(&Task{}).Where("id=?", replacement.TaskID).Select("ReplacesID").Updates(&Task{ReplacesID: t.ID}).Error; err != nil { |
| + return result, err |
| + } |
| + t.ReplacementID = replacement.TaskID |
| + t.State = "cancel_requested" |
| + t.Revision++ |
| + } else { |
| + if t.PlanRevision == 0 { |
| + t.PlanRevision = 1 |
| + if err = s.history(&t, before, actor, nil); err != nil { |
| + return result, err |
| + } |
| + } |
| + t.ProjectID = projectID |
| + t.JobID = 0 |
| + t.MergeOwner = a.MergeOwner |
| + t.BaseCommit = "" |
| + t.CheckDefinitionHash = "" |
| + t.BaselineTestSetHash = "" |
| + t.ApprovalRevision = 0 |
| + t.WaitCode = "" |
| + t.State = "proposed" |
| + t.Revision++ |
| + t.PlanRevision++ |
| + p.ProjectID = projectID |
| + p.Revision = t.PlanRevision |
| + for i := range p.Steps { |
| + p.Steps[i].ConnectionID = "" |
| + p.Steps[i].Model = "" |
| + p.Steps[i].SelectionReason = "" |
| + } |
| + if err = s.history(&t, p, actor, &before); err != nil { |
| + return result, err |
| + } |
| + } |
| + out := Outbox{State: "plan", ProjectRevision: a.ProjectRevision} |
| + if started { |
| + out.State = "cancelled" |
| + } |
| + if err = s.tx.Model(&Outbox{}).Where("task_id=?", id).Select("State", "ProjectRevision", "BudgetRevision", "Engineering", "Review", "Prepared", "JobSpec").Updates(&out).Error; err != nil { |
| + return result, err |
| + } |
| + if err = s.persist(t, actor, "plan.correct"); err != nil { |
| + return result, err |
| + } |
| + return t, s.save(q, t) |
| +} |
diff --git a/internal/equipo/planning/plans.go b/internal/equipo/planning/plans.go| new file mode 100644 |
| index 00000000..5df6dd15 |
| --- /dev/null |
| +++ b/internal/equipo/planning/plans.go |
| @@ -0,0 +1,306 @@ |
| +package planning |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/json" |
| + "errors" |
| + "reflect" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type Task struct { |
| + ID string `gorm:"primaryKey"` |
| + Requester string `gorm:"uniqueIndex:task_request,priority:1"` |
| + Description string |
| + RequestID string `gorm:"uniqueIndex:task_request,priority:2"` |
| + ProjectID, Revision int64 |
| + JobID team.JobID |
| + State, WaitCode, BaseCommit, ReviewRef, CheckDefinitionHash string |
| + TeamID, MergeOwner, BaselineTestSetHash string |
| + Kind taskplan.Kind `gorm:"not null;default:bug"` |
| + PlanRevision, ApprovalRevision int64 `gorm:"not null;default:0"` |
| + ReplacementID, ReplacesID string `gorm:"not null;default:''"` |
| +} |
| +type Outbox struct { |
| + TaskID string `gorm:"primaryKey"` |
| + State string |
| + ProjectRevision, BudgetRevision int64 |
| + Engineering, Review, Prepared, JobSpec string |
| +} |
| + |
| +func (Outbox) TableName() string { return "task_outboxes" } |
| + |
| +type Revision struct { |
| + TaskID string `gorm:"primaryKey"` |
| + Revision int64 `gorm:"primaryKey;autoIncrement:false"` |
| + Plan, ActorKind, Actor, ChangedKeys string |
| + CreatedAt time.Time |
| +} |
| + |
| +func (Revision) TableName() string { return "plan_revisions" } |
| + |
| +type Request struct { |
| + Principal, Operation, Resource, RequestID string `gorm:"primaryKey"` |
| + InputHash, Result string |
| +} |
| + |
| +func (Request) TableName() string { return "plan_requests" } |
| + |
| +var Models = []any{&Revision{}, &Request{}, &ApprovalSetting{}} |
| + |
| +type Access struct { |
| + TeamID, MergeOwner string |
| + ProjectRevision int64 |
| +} |
| +type Dependencies struct { |
| + Access func(*gorm.DB, kernel.Actor, int64) (Access, error) |
| + Project func(*gorm.DB, int64) error |
| + Member func(*gorm.DB, kernel.Actor, bool) error |
| + Audit func(*gorm.DB, kernel.Actor, string, string) error |
| + Card func(*gorm.DB, Task) error |
| + Started func(*gorm.DB, string) (bool, error) |
| + Stop func(*gorm.DB, string) error |
| + Fence func(*gorm.DB, string) error |
| + Ready func(*gorm.DB, Task, taskplan.Plan) error |
| + Core *team.Store |
| + Invalid, Conflict, Forbidden, Unavailable error |
| +} |
| +type Store struct { |
| + tx *gorm.DB |
| + ctx context.Context |
| + deps Dependencies |
| +} |
| + |
| +func New(ctx context.Context, tx *gorm.DB, deps Dependencies) *Store { |
| + return &Store{ctx: ctx, tx: tx, deps: deps} |
| +} |
| +func (s *Store) request(actor kernel.Actor, op, resource string, m kernel.Mutation, input any, result any) (Request, bool, error) { |
| + if !m.Valid() { |
| + return Request{}, false, s.deps.Invalid |
| + } |
| + hash, err := kernel.InputHash(input) |
| + if err != nil { |
| + return Request{}, false, err |
| + } |
| + q := Request{Principal: actor.Address, Operation: op, Resource: resource, RequestID: m.RequestID, InputHash: hash} |
| + var old Request |
| + err = s.tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", q.Principal, op, resource, m.RequestID).First(&old).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return q, false, nil |
| + } |
| + if err != nil { |
| + return q, false, err |
| + } |
| + if old.InputHash != hash { |
| + return q, false, s.deps.Conflict |
| + } |
| + err = json.Unmarshal([]byte(old.Result), result) |
| + return q, true, err |
| +} |
| +func (s *Store) save(q Request, result any) error { |
| + raw, err := json.Marshal(result) |
| + if err != nil { |
| + return err |
| + } |
| + q.Result = string(raw) |
| + return s.tx.Create(&q).Error |
| +} |
| +func (s *Store) task(actor kernel.Actor, id string) (Task, error) { |
| + if err := s.deps.Member(s.tx, actor, false); err != nil { |
| + return Task{}, err |
| + } |
| + var t Task |
| + if err := s.tx.First(&t, "id=?", id).Error; err != nil { |
| + return t, err |
| + } |
| + _, err := s.deps.Access(s.tx, actor, t.ProjectID) |
| + return t, err |
| +} |
| +func (s *Store) Plan(t Task) (taskplan.Plan, error) { |
| + if t.PlanRevision == 0 { |
| + return taskplan.BugPlan(t.ID, t.ProjectID), nil |
| + } |
| + var r Revision |
| + err := s.tx.First(&r, "task_id=? AND revision=?", t.ID, t.PlanRevision).Error |
| + var p taskplan.Plan |
| + if err == nil { |
| + err = json.Unmarshal([]byte(r.Plan), &p) |
| + } |
| + return p, err |
| +} |
| +func (s *Store) history(t *Task, p taskplan.Plan, actor kernel.Actor, before *taskplan.Plan) error { |
| + p = taskplan.Normalize(p) |
| + p.TaskID = t.ID |
| + p.Revision = t.PlanRevision |
| + keys := []string{} |
| + prior := map[string]taskplan.Step{} |
| + if before != nil { |
| + for _, st := range before.Steps { |
| + prior[st.Key] = st |
| + } |
| + } |
| + for i, st := range p.Steps { |
| + old, ok := prior[st.Key] |
| + if !ok || !reflect.DeepEqual(st, old) || (before != nil && (i >= len(before.Steps) || before.Steps[i].Key != st.Key)) { |
| + keys = append(keys, st.Key) |
| + } |
| + delete(prior, st.Key) |
| + } |
| + if before != nil { |
| + for _, st := range before.Steps { |
| + if _, ok := prior[st.Key]; ok { |
| + keys = append(keys, st.Key) |
| + } |
| + } |
| + } |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return err |
| + } |
| + changed, _ := json.Marshal(keys) |
| + return s.tx.Create(&Revision{TaskID: t.ID, Revision: p.Revision, Plan: string(raw), ActorKind: "person", Actor: actor.Address, ChangedKeys: string(changed), CreatedAt: time.Now().UTC()}).Error |
| +} |
| +func (s *Store) persist(t Task, actor kernel.Actor, kind string) error { |
| + if err := s.tx.Model(&Task{}).Where("id=?", t.ID).Select("ProjectID", "Revision", "JobID", "State", "WaitCode", "BaseCommit", "CheckDefinitionHash", "BaselineTestSetHash", "MergeOwner", "Kind", "PlanRevision", "ApprovalRevision", "ReplacementID").Updates(&t).Error; err != nil { |
| + return err |
| + } |
| + if err := s.deps.Card(s.tx, t); err != nil { |
| + return err |
| + } |
| + return s.deps.Audit(s.tx, actor, kind, t.ID) |
| +} |
| +func (s *Store) Propose(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (taskplan.Plan, error) { |
| + return s.propose(actor, actor.Address, p, m) |
| +} |
| +func (s *Store) propose(actor kernel.Actor, requester string, p taskplan.Plan, m kernel.Mutation) (taskplan.Plan, error) { |
| + a, err := s.deps.Access(s.tx, actor, p.ProjectID) |
| + if err != nil { |
| + return taskplan.Plan{}, err |
| + } |
| + if p.TaskID != "" || p.Revision != 0 || m.Revision != 0 || taskplan.Validate(p) != nil { |
| + return taskplan.Plan{}, s.deps.Invalid |
| + } |
| + var result taskplan.Plan |
| + q, replayed, err := s.request(actor, "plan.propose", "", m, struct { |
| + Plan taskplan.Plan |
| + Mutation kernel.Mutation |
| + }{p, m}, &result) |
| + if err != nil || replayed { |
| + return result, err |
| + } |
| + t := Task{ID: rand.Text(), Requester: requester, RequestID: rand.Text(), Description: p.Steps[0].Instructions, ProjectID: p.ProjectID, Revision: 1, PlanRevision: 1, Kind: p.Kind, TeamID: a.TeamID, MergeOwner: a.MergeOwner, State: "proposed"} |
| + t.ReviewRef = "equipo/" + t.ID |
| + if err = s.tx.Create(&t).Error; err != nil { |
| + return result, err |
| + } |
| + if err = s.tx.Create(&Outbox{TaskID: t.ID, State: "plan", ProjectRevision: a.ProjectRevision}).Error; err != nil { |
| + return result, err |
| + } |
| + p = taskplan.Normalize(p) |
| + p.TaskID = t.ID |
| + p.Revision = 1 |
| + if err = s.history(&t, p, actor, nil); err != nil { |
| + return result, err |
| + } |
| + if err = s.persist(t, actor, "plan.propose"); err != nil { |
| + return result, err |
| + } |
| + return p, s.save(q, p) |
| +} |
| +func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (taskplan.Plan, error) { |
| + t, err := s.task(actor, p.TaskID) |
| + if err != nil { |
| + return taskplan.Plan{}, err |
| + } |
| + var result taskplan.Plan |
| + q, replayed, err := s.request(actor, "plan.edit", t.ID, m, struct { |
| + Plan taskplan.Plan |
| + Mutation kernel.Mutation |
| + }{p, m}, &result) |
| + if err != nil || replayed { |
| + return result, err |
| + } |
| + before, err := s.Plan(t) |
| + if err != nil { |
| + return result, err |
| + } |
| + if m.Revision <= 0 || m.Revision != before.Revision || p.Revision != before.Revision { |
| + return result, s.deps.Conflict |
| + } |
| + started := map[string]bool{} |
| + var steps []team.Step |
| + var job team.Job |
| + if t.JobID != 0 { |
| + if s.deps.Core == nil { |
| + return result, s.deps.Unavailable |
| + } |
| + scope := team.Scope{Account: team.AccountID(t.TeamID), Job: t.JobID} |
| + job, err = s.deps.Core.GetJob(s.ctx, scope) |
| + if err != nil { |
| + return result, err |
| + } |
| + steps, err = s.deps.Core.Steps(s.ctx, scope) |
| + if err != nil { |
| + return result, err |
| + } |
| + for _, st := range steps { |
| + started[st.Key] = st.Attempts > 0 || st.State != team.StepPending |
| + } |
| + } |
| + p = taskplan.Normalize(p) |
| + if t.JobID != 0 && p.Kind != before.Kind { |
| + return result, s.deps.Invalid |
| + } |
| + if err = taskplan.ValidateEdit(before, p, started); err != nil { |
| + return result, s.deps.Invalid |
| + } |
| + if t.JobID != 0 { |
| + change, err := GraphChange(p, steps) |
| + if err != nil { |
| + return result, s.deps.Invalid |
| + } |
| + if _, err = s.deps.Core.EditUnstarted(s.ctx, team.Scope{Account: job.Account, Job: job.ID}, job.Revision, change); err != nil { |
| + return result, err |
| + } |
| + } |
| + if err = s.deps.Fence(s.tx, t.ID); err != nil { |
| + return result, err |
| + } |
| + if t.PlanRevision == 0 { |
| + t.PlanRevision = 1 |
| + if err = s.history(&t, before, actor, nil); err != nil { |
| + return result, err |
| + } |
| + } |
| + t.Revision++ |
| + t.PlanRevision++ |
| + t.ApprovalRevision = 0 |
| + t.Kind = p.Kind |
| + p.Revision = t.PlanRevision |
| + if err = s.history(&t, p, actor, &before); err != nil { |
| + return result, err |
| + } |
| + if err = s.persist(t, actor, "plan.edit"); err != nil { |
| + return result, err |
| + } |
| + return p, s.save(q, p) |
| +} |
| + |
| +func (s *Store) Seed(t Task, actor kernel.Actor) error { |
| + if t.PlanRevision != 0 { |
| + return nil |
| + } |
| + p := taskplan.BugPlan(t.ID, t.ProjectID) |
| + t.PlanRevision = 1 |
| + t.Kind = taskplan.Bug |
| + if err := s.history(&t, p, actor, nil); err != nil { |
| + return err |
| + } |
| + return s.tx.Model(&Task{}).Where("id=? AND plan_revision=0", t.ID).Select("Kind", "PlanRevision").Updates(&t).Error |
| +} |
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go| new file mode 100644 |
| index 00000000..7cb84fc3 |
| --- /dev/null |
| +++ b/internal/equipo/plans.go |
| @@ -0,0 +1,226 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "context" |
| + "encoding/json" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type ApprovalMode = planning.ApprovalMode |
| + |
| +const ( |
| + ApprovalImmediate = planning.ApprovalImmediate |
| + ApprovalRequired = planning.ApprovalRequired |
| +) |
| + |
| +func (s *Store) planningAt(tx *gorm.DB) *planning.Store { |
| + deps := planning.Dependencies{ |
| + Access: func(tx *gorm.DB, a Actor, id int64) (planning.Access, error) { |
| + p, err := bugAuthority(tx, a, id) |
| + if err != nil { |
| + return planning.Access{}, err |
| + } |
| + var instance Team |
| + if err = tx.First(&instance).Error; err != nil { |
| + return planning.Access{}, err |
| + } |
| + var merge DecisionOwner |
| + if err = tx.Where("project_id=? AND decision='merge'", id).First(&merge).Error; err != nil { |
| + return planning.Access{}, storeError(err) |
| + } |
| + if _, err = currentRunnerMember(tx, merge.Address); err != nil { |
| + return planning.Access{}, err |
| + } |
| + return planning.Access{TeamID: instance.ID, MergeOwner: merge.Address, ProjectRevision: p.Revision}, nil |
| + }, |
| + Project: func(tx *gorm.DB, id int64) error { var p Project; return storeError(tx.First(&p, id).Error) }, |
| + Member: func(tx *gorm.DB, a Actor, owner bool) error { |
| + m, err := currentRunnerMember(tx, a.Address) |
| + if err != nil { |
| + return err |
| + } |
| + if owner && m.Role != RoleOwner { |
| + return ErrForbidden |
| + } |
| + return nil |
| + }, |
| + Audit: appendAudit, |
| + Card: func(tx *gorm.DB, t Task) error { |
| + return conversationAt(tx).TaskCard(Actor{Address: t.Requester}, conversation.TaskAccess{ID: t.ID, Requester: t.Requester, TeamID: t.TeamID, Revision: t.PlanRevision}) |
| + }, |
| + Started: func(tx *gorm.DB, id string) (bool, error) { |
| + var n int64 |
| + err := tx.Model(&runnerAssignment{}).Where("task_id=? AND claim_request<>''", id).Count(&n).Error |
| + return n > 0, err |
| + }, |
| + Stop: func(tx *gorm.DB, id string) error { |
| + return tx.Model(&runnerAssignment{}).Where("task_id=? AND state IN ?", id, []string{"pending", "claimed", "prepared"}).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error |
| + }, |
| + Fence: func(tx *gorm.DB, id string) error { |
| + return tx.Model(&runnerAssignment{}).Where("task_id=? AND state IN ?", id, []string{"pending", "prepared"}).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error |
| + }, |
| + Ready: s.planReady, |
| + Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, |
| + } |
| + if s.execution != nil { |
| + deps.Core = s.execution.Core |
| + } |
| + return planning.New(tx.Statement.Context, tx, deps) |
| +} |
| +func (s *Store) planReady(tx *gorm.DB, t Task, p taskplan.Plan) error { |
| + if _, err := bugAuthority(tx, Actor{Address: t.Requester}, t.ProjectID); err != nil { |
| + return err |
| + } |
| + if taskplan.Validate(p) != nil { |
| + return ErrInvalid |
| + } |
| + budget, err := bugBudget(tx, t.TeamID, t.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + policy, err := bugPolicy(tx, t) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := executionTx(tx) |
| + if err != nil { |
| + return err |
| + } |
| + if err = team.CheckPlanBudgetTx(tx.Statement.Context, raw, team.AccountID(t.TeamID), team.ProjectID(t.ProjectID), team.BudgetSet{Revision: budget.Revision, Team: budget.Team, Projects: budget.Projects}, team.PeriodLimits{Calls: 1, InputTokens: policy.PerCall.InputTokens, OutputTokens: policy.PerCall.OutputTokens, Seconds: int64(policy.AttemptSeconds)}, s.runnerClock.Now()); err != nil { |
| + return err |
| + } |
| + eng, rev, err := s.bugPair(tx, t.Requester, t.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + for _, st := range p.Steps { |
| + if st.Action == "checks" || st.Action == "publish" || st.Action == "person" { |
| + continue |
| + } |
| + sel := eng |
| + if st.Action == "review" { |
| + sel = rev |
| + } |
| + if (st.ConnectionID != "" && st.ConnectionID != sel.ConnectionID) || (st.Model != "" && st.Model != sel.Model) { |
| + return ErrConflict |
| + } |
| + } |
| + return nil |
| +} |
| +func (s *Store) ProposePlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) { |
| + actor.Address = normalizeAddress(actor.Address) |
| + var result taskplan.Plan |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + var err error |
| + result, err = s.planningAt(tx).Propose(actor, p, m) |
| + return err |
| + }) |
| + return result, err |
| +} |
| +func (s *Store) EditPlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) { |
| + actor.Address = normalizeAddress(actor.Address) |
| + var result taskplan.Plan |
| + err := s.write(ctx, func(tx *gorm.DB) error { var err error; result, err = s.planningAt(tx).Edit(actor, p, m); return err }) |
| + return result, err |
| +} |
| +func (s *Store) ApprovePlan(ctx context.Context, actor Actor, id string, m Mutation) (Task, error) { |
| + actor.Address = normalizeAddress(actor.Address) |
| + var result Task |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + var err error |
| + result, err = s.planningAt(tx).Approve(actor, id, m) |
| + return err |
| + }) |
| + return result, err |
| +} |
| +func (s *Store) CorrectTaskProject(ctx context.Context, actor Actor, id string, project int64, m Mutation) (Task, error) { |
| + actor.Address = normalizeAddress(actor.Address) |
| + var result Task |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + var err error |
| + result, err = s.planningAt(tx).Correct(actor, id, project, m) |
| + return err |
| + }) |
| + return result, err |
| +} |
| +func (s *Store) SetProjectApproval(ctx context.Context, actor Actor, project int64, mode ApprovalMode, m Mutation) error { |
| + actor.Address = normalizeAddress(actor.Address) |
| + return s.write(ctx, func(tx *gorm.DB) error { return s.planningAt(tx).SetApproval(actor, project, &mode, m, true) }) |
| +} |
| +func (s *Store) SetApprovalOverride(ctx context.Context, actor Actor, project int64, mode *ApprovalMode, m Mutation) error { |
| + actor.Address = normalizeAddress(actor.Address) |
| + return s.write(ctx, func(tx *gorm.DB) error { return s.planningAt(tx).SetApproval(actor, project, mode, m, false) }) |
| +} |
| +func (s *Store) PlanApproval(ctx context.Context, actor Actor, project int64) (ApprovalMode, error) { |
| + actor.Address = normalizeAddress(actor.Address) |
| + var result ApprovalMode |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + if _, err := currentRunnerMember(tx, actor.Address); err != nil { |
| + return err |
| + } |
| + var err error |
| + result, err = s.planningAt(tx).Approval(actor.Address, project) |
| + return err |
| + }) |
| + return result, err |
| +} |
| +func (s *Store) CheckPlanDispatch(ctx context.Context, actor Actor, id string) error { |
| + actor.Address = normalizeAddress(actor.Address) |
| + return s.write(ctx, func(tx *gorm.DB) error { return s.planningAt(tx).CheckDispatch(actor, id) }) |
| +} |
| +func (s *Store) TaskPlan(ctx context.Context, actor Actor, id string) (taskplan.Plan, error) { |
| + var result taskplan.Plan |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + if _, err := currentRunnerMember(tx, actor.Address); err != nil { |
| + return err |
| + } |
| + var t Task |
| + if err := tx.First(&t, "id=?", id).Error; err != nil { |
| + return storeError(err) |
| + } |
| + var err error |
| + result, err = s.planningAt(tx).Plan(t) |
| + return err |
| + }) |
| + return result, err |
| +} |
| + |
| +func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error { |
| + if err := s.planningAt(tx).CheckDispatch(Actor{Address: t.Requester}, t.ID); err != nil { |
| + return err |
| + } |
| + p, err := s.planningAt(tx).Plan(t) |
| + if err != nil { |
| + return err |
| + } |
| + // Other predicates and runner actions are installed by the later tasks. |
| + if p.Kind != taskplan.Bug { |
| + return ErrUnavailable |
| + } |
| + if _, err = planning.ExecutionSteps(p); err != nil { |
| + return ErrUnavailable |
| + } |
| + project, err := bugAuthority(tx, Actor{Address: t.Requester}, t.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + budget, err := bugBudget(tx, t.TeamID, t.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + eng, rev, err := s.bugPair(tx, t.Requester, t.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + eraw, _ := json.Marshal(eng) |
| + rraw, _ := json.Marshal(rev) |
| + out := taskOutbox{State: "prepare", ProjectRevision: project.Revision, BudgetRevision: budget.Revision, Engineering: string(eraw), Review: string(rraw)} |
| + if err = tx.Model(&taskOutbox{}).Where("task_id=? AND state='plan'", t.ID).Select("State", "ProjectRevision", "BudgetRevision", "Engineering", "Review").Updates(&out).Error; err != nil { |
| + return err |
| + } |
| + return tx.Model(&Task{}).Where("id=?", t.ID).Select("State").Updates(&Task{State: "preparing"}).Error |
| +} |
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go| index 70eefe55..01db82ed 100644 |
| --- a/internal/equipo/runner_execution.go |
| +++ b/internal/equipo/runner_execution.go |
| @@ -209,6 +209,18 @@ func (e *Execution) Sync(ctx context.Context) error { |
| return storeError(err) |
| } |
| } |
| + var proposed []Task |
| + if err := tx.Where("state='proposed'").Find(&proposed).Error; err != nil { |
| + return err |
| + } |
| + for _, task := range proposed { |
| + if err := e.store.preparePlanOutbox(tx, task); err != nil { |
| + if taskRefusal(err) { |
| + continue |
| + } |
| + return err |
| + } |
| + } |
| var prepared []Task |
| if err := tx.Where("state=?", "prepared").Find(&prepared).Error; err != nil { |
| return storeError(err) |
| @@ -258,6 +270,12 @@ func (e *Execution) Sync(ctx context.Context) error { |
| if task.WaitCode == "task.wait.reconcile" { |
| continue |
| } |
| + if err := e.store.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil { |
| + if taskRefusal(err) { |
| + continue |
| + } |
| + return err |
| + } |
| var out taskOutbox |
| if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil { |
| return storeError(err) |
| @@ -501,6 +519,9 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil { |
| return storeError(err) |
| } |
| + if err := e.store.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil { |
| + return err |
| + } |
| if _, err := specialistAt(tx, specialistFor(a.StepKey)); err != nil { |
| return err |
| } |
| @@ -535,6 +556,18 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| return err |
| } |
| brief := RunnerBrief{AttemptDeadline: e.store.runnerClock.Now().UTC().Add(time.Duration(policy.AttemptSeconds) * time.Second), Policy: policy, Target: team.TargetBinding{Kind: team.TargetRepository, Repository: project.Repository, DefaultRef: project.DefaultBranch, Ref: task.ReviewRef, BaseRevision: task.BaseCommit}, Instructions: task.Description, StandingInstructions: sp.StandingInstructions, ConfirmedPreferences: []string{}, Selection: value.Selection, ArtifactHashes: []string{}} |
| + plan, err := e.store.planningAt(tx).Plan(task) |
| + if err != nil { |
| + return err |
| + } |
| + for _, step := range plan.Steps { |
| + if step.Key == a.StepKey { |
| + brief.Instructions = step.Instructions |
| + if brief.Instructions == "" { |
| + brief.Instructions = task.Description |
| + } |
| + } |
| + } |
| if task.CheckDefinitionHash != "" { |
| var out taskOutbox |
| if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil { |
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go| index 54846919..c7d08bd4 100644 |
| --- a/internal/equipo/task_prepare.go |
| +++ b/internal/equipo/task_prepare.go |
| @@ -6,9 +6,12 @@ import ( |
| "encoding/hex" |
| "encoding/json" |
| "reflect" |
| + "strconv" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| "gorm.io/gorm" |
| ) |
| @@ -106,6 +109,9 @@ func (s *Store) PrepareBug(ctx context.Context, principal RunnerPrincipal, taskI |
| if err != nil { |
| return err |
| } |
| + if err := s.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil { |
| + return err |
| + } |
| if !validPreparedBug(prepared, project) { |
| return ErrInvalid |
| } |
| @@ -162,18 +168,14 @@ func (s *Store) PrepareBug(ctx context.Context, principal RunnerPrincipal, taskI |
| return result, nil |
| } |
| -// StartBug retries the durable job request, then acknowledges the app link. |
| -// Production boot never attaches execution until the runner supervisor exists. |
| +// StartBug links the validated plan and core graph in the same commit. |
| func (s *Store) StartBug(ctx context.Context, principal RunnerPrincipal, taskID string, expectedRevision int64) (Task, error) { |
| if s.execution == nil { |
| return Task{}, ErrUnavailable |
| } |
| - var task Task |
| - var spec team.JobSpec |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - var outbox taskOutbox |
| - var err error |
| - task, outbox, _, err = s.bugPreparationAt(tx, principal, taskID) |
| + var result Task |
| + err := s.execution.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + task, outbox, _, err := s.bugPreparationAt(tx, principal, taskID) |
| if err != nil { |
| return err |
| } |
| @@ -181,61 +183,58 @@ func (s *Store) StartBug(ctx context.Context, principal RunnerPrincipal, taskID |
| if expectedRevision != task.Revision && expectedRevision != task.Revision-1 { |
| return ErrConflict |
| } |
| + result = task |
| return nil |
| } |
| if outbox.State != "job" || task.Revision != expectedRevision { |
| return ErrConflict |
| } |
| - return storeError(json.Unmarshal([]byte(outbox.JobSpec), &spec)) |
| - }) |
| - if err != nil { |
| - return Task{}, err |
| - } |
| - if task.JobID != 0 { |
| - return task, nil |
| - } |
| - job, err := s.execution.Core.CreateJob(ctx, spec) |
| - if err != nil { |
| - return Task{}, err |
| - } |
| - err = s.write(ctx, func(tx *gorm.DB) error { |
| - current, outbox, _, err := s.bugPreparationAt(tx, principal, taskID) |
| + if err = s.planningAt(tx).CheckDispatch(Actor{Address: task.Requester}, task.ID); err != nil { |
| + return err |
| + } |
| + p, err := s.planningAt(tx).Plan(task) |
| if err != nil { |
| return err |
| } |
| - if outbox.State == "done" { |
| - if current.JobID != job.ID { |
| - return ErrConflict |
| - } |
| - task = current |
| - return nil |
| + if p.Kind != taskplan.Bug { |
| + return ErrUnavailable |
| } |
| - if current.Revision != expectedRevision || outbox.State != "job" { |
| - return ErrConflict |
| + var spec team.JobSpec |
| + if err = json.Unmarshal([]byte(outbox.JobSpec), &spec); err != nil { |
| + return err |
| + } |
| + spec.Steps, err = planning.ExecutionSteps(p) |
| + if err != nil { |
| + return ErrUnavailable |
| + } |
| + spec.RequestKey = task.ID + "/plan/" + strconv.FormatInt(p.Revision, 10) |
| + job, err := s.execution.Core.CreateJob(ctx, spec) |
| + if err != nil { |
| + return err |
| } |
| - current.JobID = job.ID |
| - current.Revision++ |
| - current.State = "queued" |
| - update := tx.Model(&Task{}).Where("id=? AND revision=?", taskID, expectedRevision).Select("JobID", "Revision", "State").Updates(¤t) |
| + task.JobID = job.ID |
| + task.Revision++ |
| + task.State = "queued" |
| + update := tx.Model(&Task{}).Where("id=? AND revision=?", taskID, expectedRevision).Select("JobID", "Revision", "State").Updates(&task) |
| if update.Error != nil { |
| - return storeError(update.Error) |
| + return update.Error |
| } |
| if update.RowsAffected != 1 { |
| return ErrConflict |
| } |
| - if err := tx.Model(&taskOutbox{}).Where("task_id=?", taskID).Select("State").Updates(&taskOutbox{State: "done"}).Error; err != nil { |
| - return storeError(err) |
| + if err = tx.Model(&taskOutbox{}).Where("task_id=?", taskID).Select("State").Updates(&taskOutbox{State: "done"}).Error; err != nil { |
| + return err |
| } |
| - if err := appendAudit(tx, Actor{Address: principal.Person}, "task.link", taskID); err != nil { |
| + if err = appendAudit(tx, Actor{Address: principal.Person}, "task.link", taskID); err != nil { |
| return err |
| } |
| - task = current |
| + result = task |
| return nil |
| }) |
| if err != nil { |
| return Task{}, err |
| } |
| - return task, nil |
| + return result, nil |
| } |
| func BugJobSpec(task Task, project Project, policy team.Policy, expectedSymptom string) (team.JobSpec, error) { |
| if task.ID == "" || task.TeamID == "" || task.ProjectID <= 0 || task.ProjectID != project.ID || task.ReviewRef != "equipo/"+task.ID || task.ReviewRef == project.DefaultBranch || !validBugDescription(expectedSymptom) || !validAddress(task.Requester) || !(hexDigest(task.BaseCommit, 40) || hexDigest(task.BaseCommit, 64)) || !hexDigest(task.CheckDefinitionHash, 64) || !hexDigest(task.BaselineTestSetHash, 64) { |
diff --git a/internal/equipo/tasks.go b/internal/equipo/tasks.go| index 23fd3bfd..760a7e2d 100644 |
| --- a/internal/equipo/tasks.go |
| +++ b/internal/equipo/tasks.go |
| @@ -9,6 +9,7 @@ import ( |
| "unicode/utf8" |
| "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "gorm.io/gorm" |
| ) |
| @@ -16,24 +17,8 @@ import ( |
| type JobID = team.JobID |
| type TargetBinding = team.TargetBinding |
| -type Task struct { |
| - ID string `gorm:"primaryKey"` |
| - Requester string `gorm:"uniqueIndex:task_request,priority:1"` |
| - Description string |
| - RequestID string `gorm:"uniqueIndex:task_request,priority:2"` |
| - ProjectID, Revision int64 |
| - JobID JobID |
| - State, WaitCode, BaseCommit, ReviewRef, CheckDefinitionHash string |
| - TeamID, MergeOwner, BaselineTestSetHash string |
| -} |
| -type taskOutbox struct { |
| - TaskID string `gorm:"primaryKey"` |
| - State string |
| - ProjectRevision, BudgetRevision int64 |
| - Engineering, Review, Prepared, JobSpec string |
| -} |
| - |
| -func (taskOutbox) TableName() string { return "task_outboxes" } |
| +type Task = planning.Task |
| +type taskOutbox = planning.Outbox |
| func validBugDescription(s string) bool { return utf8.ValidString(s) && len(s) >= 1 && len(s) <= 16384 } |
| func bugAuthority(tx *gorm.DB, actor Actor, projectID int64) (Project, error) { |
| @@ -138,6 +123,11 @@ func (s *Store) CreateBug(ctx context.Context, actor Actor, projectID int64, des |
| if err := tx.Create(&outbox).Error; err != nil { |
| return storeError(err) |
| } |
| + if err := s.planningAt(tx).Seed(task, actor); err != nil { |
| + return err |
| + } |
| + task.Kind = "bug" |
| + task.PlanRevision = 1 |
| return appendAudit(tx, actor, "task.create", task.ID) |
| }) |
| if err != nil { |
diff --git a/internal/equipo/team/jobs.go b/internal/equipo/team/jobs.go| index 3ff4bf40..27a9386d 100644 |
| --- a/internal/equipo/team/jobs.go |
| +++ b/internal/equipo/team/jobs.go |
| @@ -8,6 +8,7 @@ import ( |
| "errors" |
| "fmt" |
| "io" |
| + "reflect" |
| "sort" |
| "time" |
| ) |
| @@ -618,3 +619,188 @@ func jsonEnd(dec *json.Decoder) error { |
| } |
| return fmt.Errorf("trailing data: %w", err) |
| } |
| + |
| +type PlanChange struct { |
| + Append, Replace []StepSpec |
| + Cancel, Order []string |
| +} |
| + |
| +func (s *Store) EditUnstarted(ctx context.Context, scope Scope, expectedRevision int64, change PlanChange) (Job, error) { |
| + var result Job |
| + err := s.tx(ctx, func(tx *sql.Tx) error { |
| + j, err := loadJob(ctx, tx, scope) |
| + if err != nil { |
| + return err |
| + } |
| + if expectedRevision <= 0 || j.Revision != expectedRevision { |
| + return ErrRevision |
| + } |
| + if j.State.Terminal() { |
| + return ErrState |
| + } |
| + adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: j.Grant.Ref, Account: j.Account, Project: j.Project, Target: j.Target, Operation: OpJobContinue}) |
| + if err != nil { |
| + return err |
| + } |
| + if err = checkGrantFence(ctx, tx, adm); err != nil { |
| + return err |
| + } |
| + if err = checkAdmission(j, adm, s.clock.Now()); err != nil { |
| + return err |
| + } |
| + old, err := loadSteps(ctx, tx, j.ID) |
| + if err != nil { |
| + return err |
| + } |
| + specs := map[string]StepSpec{} |
| + existing := map[string]Step{} |
| + cancel := map[string]bool{} |
| + var order []string |
| + for _, st := range old { |
| + existing[st.Key] = st |
| + if st.State != StepCancelled { |
| + specs[st.Key] = StepSpec{Key: st.Key, Capability: st.Capability, Version: st.Version, DependsOn: st.DependsOn} |
| + order = append(order, st.Key) |
| + } |
| + } |
| + touched := map[string]bool{} |
| + for _, key := range change.Cancel { |
| + st, ok := existing[key] |
| + if st.Capability == CapReview || st.Capability == CapVerify || st.Capability == CapPublish { |
| + return ErrDependency |
| + } |
| + if !ok || st.State != StepPending || st.Attempts != 0 || touched[key] { |
| + return ErrState |
| + } |
| + touched[key] = true |
| + cancel[key] = true |
| + delete(specs, key) |
| + } |
| + for _, st := range change.Replace { |
| + prior, ok := existing[st.Key] |
| + if prior.Capability == CapReview || prior.Capability == CapVerify || prior.Capability == CapPublish { |
| + if st.Capability != prior.Capability { |
| + return ErrDependency |
| + } |
| + } |
| + if !ok || prior.State != StepPending || prior.Attempts != 0 || touched[st.Key] { |
| + return ErrState |
| + } |
| + touched[st.Key] = true |
| + specs[st.Key] = st |
| + } |
| + for _, st := range change.Append { |
| + if _, ok := existing[st.Key]; ok || touched[st.Key] { |
| + return ErrConflict |
| + } |
| + touched[st.Key] = true |
| + specs[st.Key] = st |
| + order = append(order, st.Key) |
| + } |
| + if len(old)+len(change.Append) > MaxSteps { |
| + return ErrQuota |
| + } |
| + if change.Order != nil { |
| + order = change.Order |
| + } |
| + var graph []StepSpec |
| + seen := map[string]bool{} |
| + for _, key := range order { |
| + if cancel[key] && change.Order == nil { |
| + continue |
| + } |
| + st, ok := specs[key] |
| + if !ok || seen[key] { |
| + return ErrDependency |
| + } |
| + seen[key] = true |
| + if change.Order != nil { |
| + st.DependsOn = nil |
| + if len(graph) > 0 { |
| + st.DependsOn = []string{graph[len(graph)-1].Key} |
| + } |
| + } |
| + if prior, ok := existing[key]; ok && (prior.Attempts > 0 || prior.State != StepPending) { |
| + a, b := append([]string{}, prior.DependsOn...), append([]string{}, st.DependsOn...) |
| + if prior.Capability != st.Capability || prior.Version != st.Version || !reflect.DeepEqual(a, b) { |
| + return ErrState |
| + } |
| + } |
| + graph = append(graph, st) |
| + } |
| + if len(graph) != len(specs) { |
| + return ErrDependency |
| + } |
| + if err = validateGraph(graph); err != nil { |
| + return err |
| + } |
| + if j.Target.Kind == TargetRepository { |
| + if err = validatePublicationGraph(graph); err != nil { |
| + return err |
| + } |
| + } |
| + for _, st := range graph { |
| + deps, _ := json.Marshal(append([]string{}, st.DependsOn...)) |
| + if _, ok := existing[st.Key]; ok { |
| + _, err = tx.ExecContext(ctx, `UPDATE steps SET capability=?,version=?,depends_on=? WHERE job_id=? AND key=?`, st.Capability, st.Version, string(deps), j.ID, st.Key) |
| + } else { |
| + _, err = tx.ExecContext(ctx, `INSERT INTO steps(job_id,key,capability,version,depends_on,state,fence,holder,attempts) VALUES(?,?,?,?,?,'pending',0,0,0)`, j.ID, st.Key, st.Capability, st.Version, string(deps)) |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + for key := range cancel { |
| + if _, err = tx.ExecContext(ctx, `UPDATE steps SET state='cancelled',fence=fence+1 WHERE job_id=? AND key=?`, j.ID, key); err != nil { |
| + return err |
| + } |
| + } |
| + j, err = bumpJob(ctx, tx, j, j.State, j.Wait, j.Outcome, s.clock.Now()) |
| + if err != nil { |
| + return err |
| + } |
| + result = j.Job |
| + return appendEvent(ctx, tx, scope, "plan.edited", j.Requester, change, s.clock.Now()) |
| + }) |
| + return result, err |
| +} |
| + |
| +func validatePublicationGraph(steps []StepSpec) error { |
| + byKey := map[string]StepSpec{} |
| + builders := []string{} |
| + review, checks, publish := "", "", "" |
| + for _, st := range steps { |
| + byKey[st.Key] = st |
| + switch st.Capability { |
| + case CapImplement: |
| + builders = append(builders, st.Key) |
| + case CapReview: |
| + review = st.Key |
| + case CapVerify: |
| + checks = st.Key |
| + case CapPublish: |
| + publish = st.Key |
| + } |
| + } |
| + if review == "" || checks == "" || publish == "" { |
| + return ErrDependency |
| + } |
| + var depends func(string, string) bool |
| + depends = func(key, ancestor string) bool { |
| + for _, dep := range byKey[key].DependsOn { |
| + if dep == ancestor || depends(dep, ancestor) { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + for _, builder := range builders { |
| + if !depends(review, builder) || !depends(checks, builder) { |
| + return ErrDependency |
| + } |
| + } |
| + if !depends(publish, review) || !depends(publish, checks) { |
| + return ErrDependency |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/team/periodbudget.go b/internal/equipo/team/periodbudget.go| index 0a4c5361..3e5dd25a 100644 |
| --- a/internal/equipo/team/periodbudget.go |
| +++ b/internal/equipo/team/periodbudget.go |
| @@ -282,31 +282,39 @@ func checkPeriodBudget(ctx context.Context, tx *sql.Tx, j jobRow, want PeriodLim |
| if err != nil || !configured { |
| return configured, err |
| } |
| - p, ok := b.Projects[j.Project] |
| - if !ok || j.Project <= 0 { |
| - return true, fail(CodeBudget, "job has no configured project") |
| + return true, CheckPlanBudgetTx(ctx, tx, j.Account, j.Project, b, want, now) |
| +} |
| + |
| +// CheckPlanBudgetTx reads the existing ledger without reserving or granting work. |
| +func CheckPlanBudgetTx(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, b BudgetSet, want PeriodLimits, now time.Time) error { |
| + if err := b.Validate(); err != nil { |
| + return err |
| + } |
| + p, ok := b.Projects[project] |
| + if !ok || project <= 0 { |
| + return fail(CodeBudget, "job has no configured project") |
| } |
| for _, limit := range []struct { |
| project ProjectID |
| cap PeriodLimits |
| - }{{0, b.Team}, {j.Project, p}} { |
| - sum, err := periodSum(ctx, tx, j.Account, limit.project, now) |
| + }{{0, b.Team}, {project, p}} { |
| + sum, err := periodSum(ctx, tx, account, limit.project, now) |
| if err != nil { |
| - return true, err |
| + return err |
| } |
| charged, err := sum.Reserved.add(sum.Spent) |
| if err != nil { |
| - return true, err |
| + return err |
| } |
| charged, err = charged.add(want) |
| if err != nil { |
| - return true, err |
| + return err |
| } |
| if !charged.within(limit.cap) { |
| - return true, fail(CodeBudget, "period ceiling exceeded for project %d", limit.project) |
| + return fail(CodeBudget, "period ceiling exceeded for project %d", limit.project) |
| } |
| } |
| - return true, nil |
| + return nil |
| } |
| func reserveTime(ctx context.Context, tx *sql.Tx, j jobRow, id AttemptID, now time.Time) error { |
| _, err := checkPeriodBudget(ctx, tx, j, PeriodLimits{Seconds: int64(j.Policy.AttemptSeconds)}, now) |
diff --git a/internal/equipo/team/plan_test.go b/internal/equipo/team/plan_test.go| new file mode 100644 |
| index 00000000..f0dc5ae3 |
| --- /dev/null |
| +++ b/internal/equipo/team/plan_test.go |
| @@ -0,0 +1,151 @@ |
| +package team |
| + |
| +import ( |
| + "database/sql" |
| + "slices" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +func TestPlanEditClaimRace(t *testing.T) { |
| + e := newEnv(t) |
| + j, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + start := make(chan struct{}) |
| + errs := make(chan error, 2) |
| + var wg sync.WaitGroup |
| + wg.Add(2) |
| + go func() { |
| + defer wg.Done() |
| + <-start |
| + _, err := e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{Replace: []StepSpec{{Key: "reproduce", Capability: CapReproduce, Version: 2}}}) |
| + errs <- err |
| + }() |
| + go func() { |
| + defer wg.Done() |
| + <-start |
| + _, err := e.store.ClaimRevision(e.ctx, scope, j.Revision, "reproduce", "runner", "workspace") |
| + errs <- err |
| + }() |
| + close(start) |
| + wg.Wait() |
| + close(errs) |
| + wins := 0 |
| + for err := range errs { |
| + if err == nil { |
| + wins++ |
| + } |
| + } |
| + if wins != 1 { |
| + t.Fatalf("want one revision winner, got %d", wins) |
| + } |
| + if got := e.job(scope).Revision; got != j.Revision+1 { |
| + t.Fatalf("partial revision: %d", got) |
| + } |
| +} |
| +func TestPlanStartedImmutable(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + e.claim(scope, "reproduce", "runner", "workspace") |
| + j := e.job(scope) |
| + for _, change := range []PlanChange{ |
| + {Replace: []StepSpec{{Key: "reproduce", Capability: CapImplement, Version: 1}}}, |
| + {Cancel: []string{"reproduce"}}, |
| + {Order: []string{"implement", "reproduce", "review", "verify", "publish"}}, |
| + } { |
| + if _, err := e.store.EditUnstarted(e.ctx, scope, j.Revision, change); err == nil { |
| + t.Fatal("started core step changed") |
| + } |
| + } |
| + if e.job(scope).Revision != j.Revision { |
| + t.Fatal("failed edit changed revision") |
| + } |
| + e.auth.Revoke(grant) |
| + if _, err := e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{}); err == nil { |
| + t.Fatal("revoked grant edited graph") |
| + } |
| +} |
| + |
| +func TestPlanRequiredSteps(t *testing.T) { |
| + for _, change := range []PlanChange{ |
| + {Cancel: []string{"review"}}, |
| + {Replace: []StepSpec{{Key: "review", Capability: CapImplement, Version: 1, DependsOn: []string{"implement"}}}}, |
| + {Replace: []StepSpec{{Key: "verify", Capability: CapVerify, Version: 1}}}, |
| + {Order: []string{"reproduce", "implement", "publish", "review", "verify"}}, |
| + } { |
| + e := newEnv(t) |
| + j, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + if _, err := e.store.EditUnstarted(e.ctx, scope, j.Revision, change); err == nil { |
| + t.Fatal("core publication guard bypassed") |
| + } |
| + } |
| +} |
| + |
| +func TestPlanBudgetReadiness(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + b.Team.Calls = 1 |
| + p := b.Projects[1] |
| + p.Calls = 1 |
| + b.Projects = map[ProjectID]PeriodLimits{1: p} |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| + scope, h := periodJob(e, 1) |
| + _, err := e.store.Intend(e.ctx, scope, h, intent("reserved", Usage{InputTokens: 1, OutputTokens: 1})) |
| + must(t, err) |
| + err = e.store.WithTransaction(e.ctx, func(tx *sql.Tx) error { |
| + return CheckPlanBudgetTx(e.ctx, tx, acctA, 1, b, PeriodLimits{Calls: 1}, e.clock.Now()) |
| + }) |
| + wantCode(t, err, CodeBudget) |
| +} |
| + |
| +func TestPlanGraphEdits(t *testing.T) { |
| + e := newEnv(t) |
| + j, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + j, err := e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{Append: []StepSpec{{Key: "second-builder", Capability: CapImplement, Version: 1}}, Order: []string{"reproduce", "implement", "second-builder", "review", "verify", "publish"}}) |
| + must(t, err) |
| + steps, err := e.store.Steps(e.ctx, scope) |
| + must(t, err) |
| + for _, st := range steps { |
| + if st.Key == "review" && !slices.Equal(st.DependsOn, []string{"second-builder"}) { |
| + t.Fatal("review misses new builder") |
| + } |
| + } |
| + j, err = e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{Cancel: []string{"second-builder"}, Order: []string{"reproduce", "implement", "review", "verify", "publish"}}) |
| + must(t, err) |
| + steps, err = e.store.Steps(e.ctx, scope) |
| + must(t, err) |
| + found := false |
| + for _, st := range steps { |
| + if st.Key == "second-builder" { |
| + found = true |
| + if st.State != StepCancelled { |
| + t.Fatal("cancelled step executable") |
| + } |
| + } |
| + } |
| + if !found { |
| + t.Fatal("cancel erased history") |
| + } |
| + before := j.Revision |
| + j, err = e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{}) |
| + must(t, err) |
| + if j.Revision != before+1 { |
| + t.Fatal("instruction-only core revision unchanged") |
| + } |
| + _, _, err = e.workflow(scope).Reproduce(e.ctx, []byte(FixtureBaseSource)) |
| + must(t, err) |
| + j = e.job(scope) |
| + if _, err = e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{Replace: []StepSpec{{Key: "reproduce", Capability: CapReproduce, Version: 2}}}); err == nil { |
| + t.Fatal("finished step changed") |
| + } |
| +} |
| + |
| +func TestPlanRevisionFences(t *testing.T) { |
| + e := newEnv(t) |
| + j, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + _, err := e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{}) |
| + must(t, err) |
| + _, err = e.store.EditUnstarted(e.ctx, scope, j.Revision, PlanChange{}) |
| + wantCode(t, err, CodeRevision) |
| + _, err = e.store.ClaimRevision(e.ctx, scope, j.Revision, "reproduce", "runner", "workspace") |
| + wantCode(t, err, CodeRevision) |
| +} |
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go| index cc67a877..aa41c7e6 100644 |
| --- a/internal/equipo/team/scheduler.go |
| +++ b/internal/equipo/team/scheduler.go |
| @@ -84,6 +84,10 @@ func current(ctx context.Context, tx *sql.Tx, scope Scope, h Handle, now time.Ti |
| // cap, the job and account concurrency caps and the workspace identity, |
| // then writes the attempt with a lease and the step's next fence. |
| func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspace string) (Handle, error) { |
| + return s.ClaimRevision(ctx, scope, 0, stepKey, runner, workspace) |
| +} |
| + |
| +func (s *Store) ClaimRevision(ctx context.Context, scope Scope, expectedRevision int64, stepKey, runner, workspace string) (Handle, error) { |
| if runner == "" || workspace == "" { |
| return Handle{}, fail(CodeInvalid, "claim needs runner and workspace identities") |
| } |
| @@ -97,6 +101,9 @@ func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspa |
| if err != nil { |
| return err |
| } |
| + if expectedRevision != 0 && j.Revision != expectedRevision { |
| + return ErrRevision |
| + } |
| if j.grantStale { |
| return fail(CodeGrantStale, "job grant needs reconciliation") |
| } |
| @@ -200,7 +207,7 @@ func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspa |
| if _, err := tx.ExecContext(ctx, `UPDATE steps SET state='running', fence=?, holder=?, attempts=attempts+1 WHERE id=? AND fence=?`, fence, id, int64(st.ID), st.Fence); err != nil { |
| return fail(CodeInvalid, "update step: %v", err) |
| } |
| - if j.State == JobQueued || j.State == JobWaiting { |
| + { |
| var err error |
| j, err = bumpJob(ctx, tx, j, JobRunning, WaitNone, j.Outcome, now) |
| if err != nil { |
diff --git a/internal/equipotest/tasks_test.go b/internal/equipotest/tasks_test.go| index ed76251d..a2b13763 100644 |
| --- a/internal/equipotest/tasks_test.go |
| +++ b/internal/equipotest/tasks_test.go |
| @@ -176,8 +176,8 @@ func TestBugPreparationCrash(t *testing.T) { |
| t.Fatal("link crash not injected") |
| } |
| executionMust(t, f.d.G.Callback().Create().Remove("task7_crash")) |
| - if scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 || scalar(t, f.d, "SELECT job_id FROM tasks WHERE id=?", task.ID) != 0 { |
| - t.Fatal("wrong crash boundary") |
| + if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 || scalar(t, f.d, "SELECT job_id FROM tasks WHERE id=?", task.ID) != 0 { |
| + t.Fatal("job creation escaped the failed task-link transaction") |
| } |
| reopen() |
| } |
diff --git a/internal/plan3test/plans_approval_test.go b/internal/plan3test/plans_approval_test.go| new file mode 100644 |
| index 00000000..2a46960c |
| --- /dev/null |
| +++ b/internal/plan3test/plans_approval_test.go |
| @@ -0,0 +1,162 @@ |
| +package plan3test |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func (f *fixture) planConnections(t *testing.T, project int64) { |
| + t.Helper() |
| + var tuples []team.IsolationTuple |
| + f.exec(t, "INSERT INTO runners(id,person,instance_id,revision) VALUES('fixture-runner',?,?,1)", owner.Address, f.TeamID) |
| + for _, v := range []struct{ provider, family, version string }{{"claude", "claude", "2.1.312"}, {"codex", "gpt", "0.165.0"}} { |
| + r := equipo.ConnectionReport{LocalID: v.provider, Provider: v.provider, Family: v.family, Model: "fixture-model", ProviderVersion: v.version, LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", PolicyVersion: "policy-v2", Kind: "subscription", Available: true, ReadIsolation: true, IsolationConfigHash: strings.Repeat("a", 64), Routing: equipo.ConnectionRouting{BindingID: v.provider, AccountID: v.provider, ObservedAccountID: v.provider, CredentialHomeHash: strings.Repeat("b", 64), AccountPinned: true, NoFailover: true, TimelineRecovery: true, ProcessOwnership: true}} |
| + tuples = append(tuples, team.IsolationTuple{Provider: r.Provider, ProviderVersion: r.ProviderVersion, LauncherVersion: r.LauncherVersion, BwrapVersion: r.BwrapVersion, PolicyVersion: r.PolicyVersion, IsolationConfigHash: r.IsolationConfigHash}) |
| + raw, err := json.Marshal([]equipo.ConnectionReport{r}) |
| + must(t, err) |
| + f.exec(t, "INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash) VALUES(?,'fixture-runner',?,?,1,?,?,'fixture')", v.provider, owner.Address, v.provider, time.Now().UTC(), string(raw)) |
| + } |
| + f.exec(t, `INSERT INTO connection_choices(person,project_id,revision,connection_ids_json,pinned_id) VALUES(?,?,1,'["claude","codex"]','claude')`, owner.Address, project) |
| + f.Store = equipo.NewStore(f.DB, equipo.WithVerifiedIsolationTuples(tuples)) |
| +} |
| +func TestPlanApprovalPrecedenceDispatch(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.ProjectID) |
| + must(t, f.Store.CheckPlanDispatch(ctx, owner, p.TaskID)) |
| + must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "require"})) |
| + if err := f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("switch to required did not stop dispatch", err) |
| + } |
| + m := equipo.Mutation{RequestID: "approve", Revision: 1} |
| + approved, err := f.Store.ApprovePlan(ctx, owner, p.TaskID, m) |
| + must(t, err) |
| + if approved.ApprovalRevision != 1 { |
| + t.Fatal("approval is not bound to plan") |
| + } |
| + must(t, f.Store.CheckPlanDispatch(ctx, owner, p.TaskID)) |
| + p.Steps[1].Instructions = "second revision" |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "edit-approved", Revision: 1}) |
| + must(t, err) |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("edited plan retained approval", err) |
| + } |
| + replay, err := f.Store.ApprovePlan(ctx, owner, p.TaskID, m) |
| + must(t, err) |
| + if replay.ApprovalRevision != 1 { |
| + t.Fatal("approval retry lost saved result") |
| + } |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("old approval replay authorized new revision", err) |
| + } |
| + _, err = f.Store.ApprovePlan(ctx, owner, p.TaskID, equipo.Mutation{RequestID: "approve-two", Revision: p.Revision}) |
| + must(t, err) |
| + must(t, f.Store.CheckPlanDispatch(ctx, owner, p.TaskID)) |
| + f.exec(t, "UPDATE specialists SET model_selection='fixed',provider='unavailable' WHERE key='engineering'") |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); err == nil { |
| + t.Fatal("dispatch ignored current model constraints") |
| + } |
| + if _, err = f.Store.ApprovePlan(ctx, owner, p.TaskID, equipo.Mutation{RequestID: "approve-model", Revision: p.Revision}); err == nil { |
| + t.Fatal("approval ignored current model constraints") |
| + } |
| + f.exec(t, "UPDATE specialists SET model_selection='best_fit' WHERE key='engineering'") |
| + f.exec(t, "DELETE FROM budget_records") |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); err == nil { |
| + t.Fatal("dispatch ignored missing budget") |
| + } |
| + if _, err = f.Store.ApprovePlan(ctx, owner, p.TaskID, equipo.Mutation{RequestID: "approve-budget", Revision: p.Revision}); err == nil { |
| + t.Fatal("approval ignored missing budget") |
| + } |
| +} |
| +func TestPlanApprovalOverrideAuthority(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.exec(t, "UPDATE members SET role='member' WHERE address=?", peer.Address) |
| + if err := f.Store.SetProjectApproval(ctx, peer, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "not-owner"}); !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatal("non-owner changed project approval", err) |
| + } |
| + mode := equipo.ApprovalRequired |
| + must(t, f.Store.SetApprovalOverride(ctx, peer, p.ProjectID, &mode, equipo.Mutation{RequestID: "own-override"})) |
| + must(t, f.Store.SetApprovalOverride(ctx, peer, p.ProjectID, nil, equipo.Mutation{RequestID: "own-inherit", Revision: 1})) |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", peer.Address) |
| + if err := f.Store.SetApprovalOverride(ctx, peer, p.ProjectID, nil, equipo.Mutation{RequestID: "own-inherit", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatal("removed member replay allowed", err) |
| + } |
| +} |
| + |
| +func TestPlanApprovalPrecedenceClaim(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.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)}) |
| + 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()) |
| + must(t, x.Sync(ctx)) |
| + var id string |
| + var revision int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &revision)) |
| + must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "require-before-claim"})) |
| + _, err = x.Claim(ctx, equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"}, equipo.ClaimRequest{Version: 2, AssignmentID: id, RequestID: "claim", Revision: revision}) |
| + if !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("claim ignored current approval mode", err) |
| + } |
| + if f.count(t, "SELECT count(*) FROM runner_cleanups") != 0 || f.count(t, "SELECT count(*) FROM attempts") != 0 || f.count(t, "SELECT count(*) FROM runner_assignments WHERE id=? AND state='pending'", id) != 1 { |
| + t.Fatal("denied claim partially committed") |
| + } |
| +} |
| + |
| +func TestPlanApprovalPrecedenceStart(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.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)}) |
| + 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()) |
| + principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| + must(t, x.Sync(ctx)) |
| + var project equipo.Project |
| + must(t, f.DB.G.First(&project, p.ProjectID).Error) |
| + definition := []byte("fixture check") |
| + hash := sha256.Sum256(definition) |
| + prepared := equipo.PreparedBug{Repository: project.Repository, DefaultBranch: project.DefaultBranch, BaseCommit: strings.Repeat("a", 40), CheckDefinition: definition, CheckDefinitionHash: hex.EncodeToString(hash[:]), BaselineTestSetHash: strings.Repeat("b", 64)} |
| + must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "require-prepare"})) |
| + if _, err = f.Store.PrepareBug(ctx, principal, p.TaskID, 1, prepared); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("prepare ignored current approval", err) |
| + } |
| + must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalImmediate, equipo.Mutation{RequestID: "immediate-prepare", Revision: 1})) |
| + task, err := f.Store.PrepareBug(ctx, principal, p.TaskID, 1, prepared) |
| + must(t, err) |
| + must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "require-start", Revision: 2})) |
| + if _, err = f.Store.StartBug(ctx, principal, p.TaskID, task.Revision); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("start ignored current approval", err) |
| + } |
| + if f.count(t, "SELECT count(*) FROM jobs") != 0 { |
| + t.Fatal("denied start left core job") |
| + } |
| + task, err = f.Store.ApprovePlan(ctx, owner, p.TaskID, equipo.Mutation{RequestID: "approve-start", Revision: 1}) |
| + must(t, err) |
| + task, err = f.Store.StartBug(ctx, principal, p.TaskID, task.Revision) |
| + must(t, err) |
| + if task.JobID == 0 { |
| + t.Fatal("approved plan not dispatched") |
| + } |
| +} |
diff --git a/internal/plan3test/plans_migration_test.go b/internal/plan3test/plans_migration_test.go| new file mode 100644 |
| index 00000000..6cb1f733 |
| --- /dev/null |
| +++ b/internal/plan3test/plans_migration_test.go |
| @@ -0,0 +1,77 @@ |
| +package plan3test |
| + |
| +import ( |
| + "encoding/json" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "reflect" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +func TestPlanMigrationUpgrade(t *testing.T) { |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + path := filepath.Join(t.TempDir(), "upgrade.db") |
| + d, err := db.Open(path, logger) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, d.Close()) }) |
| + old := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0020_plans" { |
| + old.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, d, old) |
| + must(t, err) |
| + f := &fixture{DB: d, Store: equipo.NewStore(d)} |
| + must(t, f.Store.Bootstrap(ctx, []string{owner.Address})) |
| + must(t, d.Writer().QueryRow("SELECT id FROM teams").Scan(&f.TeamID)) |
| + f.exec(t, "INSERT INTO tasks(id,requester,request_id,project_id,revision,job_id,state,description,team_id,merge_owner) VALUES('historical',?,'request',4,7,0,'merged','old bug',?,?)", owner.Address, f.TeamID, owner.Address) |
| + audits := f.count(t, "SELECT count(*) FROM audit_events") |
| + result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0020_plans"}) { |
| + t.Fatal("wrong migration", result.Applied) |
| + } |
| + var task equipo.Task |
| + must(t, d.G.First(&task, "id='historical'").Error) |
| + if task.Revision != 7 || task.State != "merged" || task.Description != "old bug" || task.Kind != taskplan.Bug || task.PlanRevision != 1 || task.ApprovalRevision != 0 || f.count(t, "SELECT count(*) FROM audit_events") != audits { |
| + t.Fatal("upgrade lost history", task) |
| + } |
| + var raw string |
| + must(t, d.Writer().QueryRow("SELECT plan FROM plan_revisions WHERE task_id='historical' AND revision=1").Scan(&raw)) |
| + var seeded taskplan.Plan |
| + must(t, json.Unmarshal([]byte(raw), &seeded)) |
| + if !reflect.DeepEqual(seeded, taskplan.BugPlan(task.ID, task.ProjectID)) { |
| + t.Fatal("migration did not seed BugPlan", seeded) |
| + } |
| + for i, st := range equipo.BugPlan(task) { |
| + if seeded.Steps[i].Key != st.Key { |
| + t.Fatal("seed changed legacy step identity") |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if f.count(t, "SELECT count(*) FROM plan_revisions WHERE task_id='historical'") != 1 { |
| + t.Fatal("history seeded twice") |
| + } |
| + for range 2 { |
| + x, err := team.OpenShared(ctx, d.Writer(), path, team.Options{Clock: team.RealClock{}, Authority: equipo.NewAuthority(f.Store, nil)}) |
| + must(t, err) |
| + must(t, x.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("upgraded schema differs from fresh", upgraded.Diff(baseline)) |
| + } |
| +} |
diff --git a/internal/plan3test/plans_test.go b/internal/plan3test/plans_test.go| new file mode 100644 |
| index 00000000..5183f240 |
| --- /dev/null |
| +++ b/internal/plan3test/plans_test.go |
| @@ -0,0 +1,263 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "errors" |
| + "gorm.io/gorm" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func proposed(t *testing.T, f *fixture) taskplan.Plan { |
| + task := f.createTask(t) |
| + p := taskplan.BugPlan(task.ID, task.ProjectID) |
| + p.Steps[0].Instructions = "fixture symptom" |
| + p.TaskID = "" |
| + p.Revision = 0 |
| + result, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| + must(t, err) |
| + if result.TaskID == "" || result.Revision != 1 { |
| + t.Fatal("proposal lacks server identity", result) |
| + } |
| + replay, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| + must(t, err) |
| + if replay.TaskID != result.TaskID { |
| + t.Fatal("proposal replay duplicated task") |
| + } |
| + if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", result.TaskID) != 1 || f.count(t, "SELECT count(*) FROM conversation_cards WHERE resource_id=?", result.TaskID) != 1 || f.count(t, "SELECT count(*) FROM task_outboxes WHERE task_id=?", result.TaskID) != 1 { |
| + t.Fatal("proposal incomplete") |
| + } |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Cards) != 1 || page.Cards[0].ResourceID != result.TaskID { |
| + t.Fatal("proposal card is not visible in conversation") |
| + } |
| + return result |
| +} |
| +func TestPlanApprovalPrecedence(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + mode, err := f.Store.PlanApproval(ctx, owner, p.ProjectID) |
| + must(t, err) |
| + if mode != equipo.ApprovalImmediate { |
| + t.Fatal("default is not immediate") |
| + } |
| + must(t, f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalRequired, equipo.Mutation{RequestID: "required", Revision: 0})) |
| + if err = f.Store.SetProjectApproval(ctx, owner, p.ProjectID, equipo.ApprovalImmediate, equipo.Mutation{RequestID: "stale", Revision: 0}); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("two tabs lost update", err) |
| + } |
| + mode, err = f.Store.PlanApproval(ctx, owner, p.ProjectID) |
| + must(t, err) |
| + if mode != equipo.ApprovalRequired { |
| + t.Fatal("project rule ignored") |
| + } |
| + immediate := equipo.ApprovalImmediate |
| + must(t, f.Store.SetApprovalOverride(ctx, owner, p.ProjectID, &immediate, equipo.Mutation{RequestID: "override"})) |
| + mode, err = f.Store.PlanApproval(ctx, owner, p.ProjectID) |
| + must(t, err) |
| + if mode != immediate { |
| + t.Fatal("override ignored") |
| + } |
| + mode, err = f.Store.PlanApproval(ctx, peer, p.ProjectID) |
| + must(t, err) |
| + if mode != equipo.ApprovalRequired { |
| + t.Fatal("override leaked") |
| + } |
| + must(t, f.Store.SetApprovalOverride(ctx, owner, p.ProjectID, nil, equipo.Mutation{RequestID: "inherit", Revision: 1})) |
| + mode, err = f.Store.PlanApproval(ctx, owner, p.ProjectID) |
| + must(t, err) |
| + if mode != equipo.ApprovalRequired { |
| + t.Fatal("inherit ignored") |
| + } |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, p.TaskID); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("required switch did not block dispatch", err) |
| + } |
| + p.Steps[1].Instructions = "new instructions" |
| + edited, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "edit", Revision: p.Revision}) |
| + must(t, err) |
| + if edited.Revision != 2 { |
| + t.Fatal("instruction edit did not advance revision") |
| + } |
| + if _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "stale-edit", Revision: 1}); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("stale edit accepted", err) |
| + } |
| + if f.count(t, "SELECT count(*) FROM plan_revisions WHERE task_id=?", p.TaskID) != 2 { |
| + t.Fatal("history missing") |
| + } |
| +} |
| +func TestPlanProjectCorrection(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + target := equipo.Project{Name: "other", Repository: "amadan.net/test/other", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| + must(t, f.DB.G.Create(&target).Error) |
| + must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: target.ID, Decision: "merge", Address: owner.Address}).Error) |
| + f.exec(t, "UPDATE tasks SET base_commit='old',approval_revision=1 WHERE id=?", p.TaskID) |
| + f.exec(t, "UPDATE task_outboxes SET engineering='old',review='old',prepared='old',job_spec='old' WHERE task_id=?", p.TaskID) |
| + got, err := f.Store.CorrectTaskProject(ctx, owner, p.TaskID, target.ID, equipo.Mutation{RequestID: "correct", Revision: 1}) |
| + must(t, err) |
| + if got.ProjectID != target.ID || got.ApprovalRevision != 0 || got.BaseCommit != "" { |
| + t.Fatal("correction retained preparation", got) |
| + } |
| + var prepared, eng, rev string |
| + must(t, f.DB.Writer().QueryRow("SELECT prepared,engineering,review FROM task_outboxes WHERE task_id=?", p.TaskID).Scan(&prepared, &eng, &rev)) |
| + if prepared != "" || eng != "" || rev != "" { |
| + t.Fatal("correction retained picks") |
| + } |
| + if _, err = f.Store.CorrectTaskProject(ctx, owner, p.TaskID, p.ProjectID, equipo.Mutation{RequestID: "stale", Revision: 1}); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("stale correction accepted", err) |
| + } |
| +} |
| + |
| +func (f *fixture) planCore(t *testing.T, p taskplan.Plan) (*equipo.Execution, equipo.Task, team.Scope) { |
| + t.Helper() |
| + 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)}) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, x.Core.Close()) }) |
| + _, err = x.Core.Resume(ctx) |
| + must(t, err) |
| + task, err := f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + var project equipo.Project |
| + must(t, f.DB.G.First(&project, p.ProjectID).Error) |
| + task.BaseCommit = strings.Repeat("a", 40) |
| + task.CheckDefinitionHash = strings.Repeat("b", 64) |
| + task.BaselineTestSetHash = strings.Repeat("c", 64) |
| + policy, err := team.RunnerPolicy("subscription", team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000}, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) |
| + must(t, err) |
| + spec, err := equipo.BugJobSpec(task, project, policy, "fixture symptom") |
| + must(t, err) |
| + job, err := x.Core.CreateJob(ctx, spec) |
| + must(t, err) |
| + task.JobID = job.ID |
| + task.State = "queued" |
| + must(t, x.Write(ctx, func(tx *gorm.DB) error { |
| + return tx.Model(&equipo.Task{}).Where("id=?", task.ID).Select("JobID", "State", "BaseCommit", "CheckDefinitionHash", "BaselineTestSetHash").Updates(&task).Error |
| + })) |
| + return x, task, team.Scope{Account: team.AccountID(task.TeamID), Job: task.JobID} |
| +} |
| +func TestPlanEditClaimRaceAtomic(t *testing.T) { |
| + for _, order := range []string{"edit_first", "claim_first", "audit_failure"} { |
| + t.Run(order, func(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + x, task, scope := f.planCore(t, p) |
| + original, err := x.Core.GetJob(ctx, scope) |
| + must(t, err) |
| + audits := f.count(t, "SELECT count(*) FROM audit_events") |
| + p.Steps[0].Instructions = "changed before start" |
| + switch order { |
| + case "claim_first": |
| + _, err = x.Core.ClaimRevision(ctx, scope, original.Revision, "reproduce", "runner", "workspace") |
| + must(t, err) |
| + if _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "race", Revision: 1}); err == nil { |
| + t.Fatal("claim lost started-step protection") |
| + } |
| + if f.count(t, "SELECT count(*) FROM plan_revisions WHERE task_id=?", task.ID) != 1 || f.count(t, "SELECT count(*) FROM audit_events") != audits { |
| + t.Fatal("losing edit partially committed") |
| + } |
| + case "edit_first": |
| + edited, err := f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "race", Revision: 1}) |
| + must(t, err) |
| + if _, err = x.Core.ClaimRevision(ctx, scope, original.Revision, "reproduce", "runner", "workspace"); !errors.Is(err, team.ErrRevision) { |
| + t.Fatal("stale claim accepted", err) |
| + } |
| + job, err := x.Core.GetJob(ctx, scope) |
| + must(t, err) |
| + if job.Revision != original.Revision+1 || edited.Revision != 2 || f.count(t, "SELECT revision FROM conversation_cards WHERE resource_id=?", task.ID) != 2 || f.count(t, "SELECT count(*) FROM audit_events") != audits+1 { |
| + t.Fatal("edit did not commit core/card/audit together") |
| + } |
| + case "audit_failure": |
| + f.exec(t, "CREATE TRIGGER fail_plan_audit BEFORE INSERT ON audit_events WHEN NEW.kind='plan.edit' BEGIN SELECT RAISE(ABORT,'fixture failure'); END") |
| + if _, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "race", Revision: 1}); err == nil { |
| + t.Fatal("audit failure ignored") |
| + } |
| + job, err := x.Core.GetJob(ctx, scope) |
| + must(t, err) |
| + if job.Revision != original.Revision || f.count(t, "SELECT count(*) FROM plan_revisions WHERE task_id=?", task.ID) != 1 || f.count(t, "SELECT revision FROM conversation_cards WHERE resource_id=?", task.ID) != 1 { |
| + t.Fatal("audit failure left partial changes") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestPlanProjectCorrectionStarted(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + x, task, scope := f.planCore(t, p) |
| + _, err := x.Core.Claim(ctx, scope, "reproduce", "runner", "workspace") |
| + must(t, err) |
| + target := equipo.Project{Name: "replacement", Repository: "amadan.net/test/replacement", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| + must(t, f.DB.G.Create(&target).Error) |
| + must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: target.ID, Decision: "merge", Address: owner.Address}).Error) |
| + result, err := f.Store.CorrectTaskProject(ctx, owner, task.ID, target.ID, equipo.Mutation{RequestID: "correct-started", Revision: 1}) |
| + must(t, err) |
| + if result.ProjectID != task.ProjectID || result.JobID != task.JobID || result.BaseCommit != task.BaseCommit || result.ReplacementID == "" { |
| + t.Fatal("started correction retargeted original", result) |
| + } |
| + replacement, err := f.Store.Task(ctx, owner, result.ReplacementID) |
| + must(t, err) |
| + if replacement.ReplacesID != task.ID || replacement.ProjectID != target.ID || replacement.JobID != 0 || replacement.ApprovalRevision != 0 || replacement.State != "proposed" { |
| + t.Fatal("unsafe replacement", replacement) |
| + } |
| + job, err := x.Core.GetJob(ctx, scope) |
| + must(t, err) |
| + if job.State != team.JobCancelled { |
| + t.Fatal("original job remains executable") |
| + } |
| + attempts, err := x.Core.Attempts(ctx, scope) |
| + must(t, err) |
| + if len(attempts) != 1 || attempts[0].State != team.AttemptStopping { |
| + t.Fatal("started worker not asked to stop") |
| + } |
| + again, err := f.Store.CorrectTaskProject(ctx, owner, task.ID, target.ID, equipo.Mutation{RequestID: "correct-started", Revision: 1}) |
| + must(t, err) |
| + if again.ReplacementID != result.ReplacementID { |
| + t.Fatal("duplicate replacement") |
| + } |
| +} |
| +func TestPlanAuthorityReplay(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + p.Steps[0].Instructions = "edited" |
| + m := equipo.Mutation{RequestID: "saved", Revision: 1} |
| + saved, err := f.Store.EditPlan(ctx, owner, p, m) |
| + must(t, err) |
| + replay, err := f.Store.EditPlan(ctx, owner, p, m) |
| + must(t, err) |
| + if replay.Revision != saved.Revision { |
| + t.Fatal("lost response retry changed result") |
| + } |
| + p.Steps[0].Instructions = "changed request" |
| + if _, err = f.Store.EditPlan(ctx, owner, p, m); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("changed replay accepted", err) |
| + } |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + p.Steps[0].Instructions = "edited" |
| + if _, err = f.Store.EditPlan(ctx, owner, p, m); !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatal("revoked replay accepted", err) |
| + } |
| +} |
| + |
| +func TestPlanProjectCorrectionPreparationStarted(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.exec(t, "INSERT INTO runner_assignments(id,task_id,step_key,revision,kind,state,claim_request,person) VALUES('prep',?,'prepare',1,'prepare','claimed','claim',?)", p.TaskID, owner.Address) |
| + target := equipo.Project{Name: "preparation replacement", Repository: "amadan.net/test/preparation", DefaultBranch: "main", Kind: equipo.ProjectRepository, Revision: 1, GrantVersion: 1} |
| + must(t, f.DB.G.Create(&target).Error) |
| + must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: target.ID, Decision: "merge", Address: owner.Address}).Error) |
| + got, err := f.Store.CorrectTaskProject(ctx, owner, p.TaskID, target.ID, equipo.Mutation{RequestID: "correct-preparation", Revision: 1}) |
| + must(t, err) |
| + if got.ProjectID != p.ProjectID || got.ReplacementID == "" || got.State != "cancel_requested" { |
| + t.Fatal("retargeted started preparation") |
| + } |
| + if f.count(t, "SELECT count(*) FROM runner_assignments WHERE id='prep' AND state='fenced'") != 1 { |
| + t.Fatal("preparation not fenced") |
| + } |
| + if err = f.Store.CheckPlanDispatch(ctx, owner, got.ReplacementID); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("replacement can auto-dispatch", err) |
| + } |
| +} |
diff --git a/internal/taskplan/budget_test.go b/internal/taskplan/budget_test.go| new file mode 100644 |
| index 00000000..5d901cfa |
| --- /dev/null |
| +++ b/internal/taskplan/budget_test.go |
| @@ -0,0 +1,10 @@ |
| +package taskplan |
| + |
| +import ( |
| + "os" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/taskplan/types.go b/internal/taskplan/types.go| new file mode 100644 |
| index 00000000..7f3d1e09 |
| --- /dev/null |
| +++ b/internal/taskplan/types.go |
| @@ -0,0 +1,43 @@ |
| +package taskplan |
| + |
| +type Kind string |
| + |
| +const ( |
| + Bug Kind = "bug" |
| + Feature Kind = "feature" |
| + RenderedChange Kind = "rendered_change" |
| + Recommendation Kind = "recommendation" |
| + Investigation Kind = "investigation" |
| + MaxSteps = 16 |
| +) |
| + |
| +type Step struct { |
| + Key, Specialist, Action, Instructions string |
| + ConnectionID, Model, SelectionReason string |
| + Required bool |
| + DependsOn []string |
| +} |
| +type Plan struct { |
| + TaskID string |
| + Revision int64 |
| + Kind Kind |
| + ProjectID int64 |
| + Steps []Step |
| + PlaybookID string |
| + PlaybookRevision int64 |
| +} |
| + |
| +func BugPlan(id string, project int64) Plan { |
| + return Plan{TaskID: id, Revision: 1, Kind: Bug, ProjectID: project, Steps: []Step{ |
| + {Key: "reproduce", Specialist: "engineering", Action: "reproduce"}, |
| + {Key: "implement", Specialist: "engineering", Action: "implement"}, |
| + {Key: "review", Specialist: "review", Action: "review", Required: true}, |
| + {Key: "verify", Action: "checks", Required: true}, |
| + {Key: "publish", Action: "publish"}, |
| + {Key: "merge", Action: "person", Required: true}, |
| + }} |
| +} |
| +func Publication(k Kind) bool { return k == Bug || k == Feature || k == RenderedChange } |
| +func Candidate(s Step) bool { |
| + return s.Action == "implement" || s.Action == "copy" || s.Action == "design" |
| +} |
diff --git a/internal/taskplan/validate.go b/internal/taskplan/validate.go| new file mode 100644 |
| index 00000000..c6f6c4d2 |
| --- /dev/null |
| +++ b/internal/taskplan/validate.go |
| @@ -0,0 +1,111 @@ |
| +package taskplan |
| + |
| +import ( |
| + "errors" |
| + "reflect" |
| + "strings" |
| + "unicode/utf8" |
| +) |
| + |
| +var ErrInvalid = errors.New("plan_invalid") |
| +var ErrLocked = errors.New("plan_locked_step") |
| + |
| +func Validate(p Plan) error { |
| + if p.ProjectID <= 0 || p.Revision < 0 || len(p.Steps) == 0 || len(p.Steps) > MaxSteps { |
| + return ErrInvalid |
| + } |
| + if !Publication(p.Kind) && p.Kind != Recommendation && p.Kind != Investigation { |
| + return ErrInvalid |
| + } |
| + seen := map[string]int{} |
| + review, checks, person, publish, lastCandidate := -1, -1, -1, -1, -1 |
| + for i, s := range p.Steps { |
| + if s.Key == "" || strings.TrimSpace(s.Key) != s.Key || len(s.Key) > 128 || !utf8.ValidString(s.Key) || len(s.Instructions) > 16384 || !utf8.ValidString(s.Instructions) { |
| + return ErrInvalid |
| + } |
| + if _, ok := seen[s.Key]; ok { |
| + return ErrInvalid |
| + } |
| + seen[s.Key] = i |
| + for _, dep := range s.DependsOn { |
| + if _, ok := seen[dep]; !ok || dep == s.Key { |
| + return ErrInvalid |
| + } |
| + } |
| + switch s.Action { |
| + case "review": |
| + if s.Key != "review" || s.Specialist != "review" { |
| + return ErrInvalid |
| + } |
| + review = i |
| + case "checks": |
| + if s.Key != "verify" || s.Model != "" || s.ConnectionID != "" { |
| + return ErrInvalid |
| + } |
| + checks = i |
| + case "person": |
| + if s.Key != "merge" || s.Model != "" || s.ConnectionID != "" { |
| + return ErrInvalid |
| + } |
| + person = i |
| + case "publish": |
| + if s.Key != "publish" || s.Model != "" || s.ConnectionID != "" { |
| + return ErrInvalid |
| + } |
| + publish = i |
| + case "implement", "copy", "design": |
| + lastCandidate = i |
| + case "reproduce", "scope", "investigate", "recommend": |
| + default: |
| + return ErrInvalid |
| + } |
| + if !Publication(p.Kind) && s.Action != "person" && s.Action != "scope" && s.Action != "investigate" && s.Action != "recommend" { |
| + return ErrInvalid |
| + } |
| + } |
| + if person != len(p.Steps)-1 { |
| + return ErrInvalid |
| + } |
| + if Publication(p.Kind) { |
| + if review < 0 || checks < 0 || review <= lastCandidate || checks <= lastCandidate { |
| + return ErrInvalid |
| + } |
| + if publish >= 0 && (publish < review || publish < checks) { |
| + return ErrInvalid |
| + } |
| + if publish < 0 && len(p.Steps)+1 > MaxSteps { |
| + return ErrInvalid |
| + } |
| + } |
| + return nil |
| +} |
| +func ValidateEdit(before, after Plan, started map[string]bool) error { |
| + if err := Validate(after); err != nil { |
| + return err |
| + } |
| + if before.TaskID != after.TaskID || before.ProjectID != after.ProjectID || before.Revision != after.Revision { |
| + return ErrInvalid |
| + } |
| + for i, s := range before.Steps { |
| + if started[s.Key] { |
| + if i >= len(after.Steps) || !reflect.DeepEqual(s, after.Steps[i]) { |
| + return ErrLocked |
| + } |
| + // Ordered plans depend on their complete prefix, including implicit edges. |
| + for j := 0; j < i; j++ { |
| + if before.Steps[j].Key != after.Steps[j].Key { |
| + return ErrLocked |
| + } |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| +func Normalize(p Plan) Plan { |
| + p.Steps = append([]Step(nil), p.Steps...) |
| + for i := range p.Steps { |
| + s := &p.Steps[i] |
| + s.Required = s.Action == "person" || (Publication(p.Kind) && (s.Action == "review" || s.Action == "checks")) |
| + } |
| + return p |
| +} |
diff --git a/internal/taskplan/validate_test.go b/internal/taskplan/validate_test.go| new file mode 100644 |
| index 00000000..d8aaba6e |
| --- /dev/null |
| +++ b/internal/taskplan/validate_test.go |
| @@ -0,0 +1,145 @@ |
| +package taskplan |
| + |
| +import ( |
| + "fmt" |
| + "testing" |
| +) |
| + |
| +func publication() Plan { |
| + return Plan{Kind: Bug, ProjectID: 1, Steps: []Step{ |
| + {Key: "reproduce", Specialist: "engineering", Action: "reproduce"}, |
| + {Key: "implement", Specialist: "engineering", Action: "implement"}, |
| + {Key: "review", Specialist: "review", Action: "review"}, |
| + {Key: "verify", Action: "checks"}, |
| + {Key: "publish", Action: "publish"}, |
| + {Key: "merge", Action: "person"}, |
| + }} |
| +} |
| +func TestPlanRequiredSteps(t *testing.T) { |
| + if err := Validate(publication()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, key := range []string{"review", "verify", "merge"} { |
| + for _, op := range []string{"delete", "rename", "substitute"} { |
| + t.Run(key+"/"+op, func(t *testing.T) { |
| + p := publication() |
| + for i := range p.Steps { |
| + if p.Steps[i].Key == key { |
| + switch op { |
| + case "delete": |
| + p.Steps = append(p.Steps[:i], p.Steps[i+1:]...) |
| + case "rename": |
| + p.Steps[i].Key = "other" |
| + case "substitute": |
| + p.Steps[i].Action = "implement" |
| + } |
| + break |
| + } |
| + } |
| + if Validate(p) == nil { |
| + t.Fatal("mandatory step bypassed") |
| + } |
| + }) |
| + } |
| + } |
| + for _, tc := range []string{"duplicate", "cycle", "early_publish", "late_builder", "model_checks", "limit", "fake_review"} { |
| + t.Run(tc, func(t *testing.T) { |
| + p := publication() |
| + switch tc { |
| + case "duplicate": |
| + p.Steps[1].Key = p.Steps[0].Key |
| + case "cycle": |
| + p.Steps[0].DependsOn = []string{"implement"} |
| + case "early_publish": |
| + p.Steps[2], p.Steps[4] = p.Steps[4], p.Steps[2] |
| + case "late_builder": |
| + p.Steps[1], p.Steps[3] = p.Steps[3], p.Steps[1] |
| + case "model_checks": |
| + p.Steps[3].Model = "model" |
| + case "limit": |
| + for len(p.Steps) <= 16 { |
| + p.Steps = append(p.Steps, Step{Key: "extra", Action: "scope"}) |
| + } |
| + case "fake_review": |
| + p.Steps[2].Specialist = "engineering" |
| + } |
| + if Validate(p) == nil { |
| + t.Fatal("invalid plan accepted") |
| + } |
| + }) |
| + } |
| + for _, kind := range []Kind{Recommendation, Investigation} { |
| + p := Plan{Kind: kind, ProjectID: 1, Steps: []Step{{Key: "read", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}}} |
| + if kind == Investigation { |
| + p.Steps[0].Action = "investigate" |
| + } |
| + if err := Validate(p); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.Steps[0].Action = "implement" |
| + if Validate(p) == nil { |
| + t.Fatal("read-only plan permits write") |
| + } |
| + } |
| +} |
| +func TestPlanStartedImmutable(t *testing.T) { |
| + before := publication() |
| + before.TaskID = "task" |
| + before.Revision = 1 |
| + for _, change := range []string{"order", "instructions", "model", "connection", "dependencies", "delete"} { |
| + t.Run(change, func(t *testing.T) { |
| + after := publication() |
| + after.TaskID = "task" |
| + after.Revision = 1 |
| + switch change { |
| + case "order": |
| + after.Steps[0], after.Steps[1] = after.Steps[1], after.Steps[0] |
| + case "instructions": |
| + after.Steps[1].Instructions = "changed" |
| + case "model": |
| + after.Steps[1].Model = "new" |
| + case "connection": |
| + after.Steps[1].ConnectionID = "new" |
| + case "dependencies": |
| + after.Steps[1].DependsOn = []string{"reproduce"} |
| + case "delete": |
| + after.Steps = append(after.Steps[:1], after.Steps[2:]...) |
| + } |
| + if ValidateEdit(before, after, map[string]bool{"implement": true}) == nil { |
| + t.Fatal("started step changed") |
| + } |
| + }) |
| + } |
| + after := publication() |
| + after.TaskID = "task" |
| + after.Revision = 1 |
| + after.Steps[1].Instructions = "new" |
| + if err := ValidateEdit(before, after, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestPlanExecutionLimit(t *testing.T) { |
| + for _, hidden := range []bool{false, true} { |
| + p := publication() |
| + if hidden { |
| + p.Steps = append(p.Steps[:4], p.Steps[5:]...) |
| + } |
| + for i := 0; len(p.Steps) < 16; i++ { |
| + p.Steps = append([]Step{{Key: fmt.Sprint("scope-", i), Action: "scope"}}, p.Steps...) |
| + } |
| + if hidden { |
| + if Validate(p) == nil { |
| + t.Fatal("hidden publication exceeds limit") |
| + } |
| + } else { |
| + if err := Validate(p); err != nil { |
| + t.Fatal(err) |
| + } |
| + p.Steps = append([]Step{{Key: "extra", Action: "scope"}}, p.Steps...) |
| + if Validate(p) == nil { |
| + t.Fatal("plan exceeds 16 steps") |
| + } |
| + } |
| + } |
| +} |