feat: execute revisioned plans with the direct runner
63 files changed,
+2,238
−260
.rastrillo/budgets.txt+2 −2docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+55 −0internal/directlive/driver.go+3 −3internal/directlive/driver_test.go+2 −2internal/directlive/turn.go+3 −0internal/equipo/connection_selection.go+16 −3internal/equipo/conversation/answer.go+36 −0internal/equipo/copy.go+7 −1internal/equipo/plan_answer.go+21 −0internal/equipo/plan_execution.go+139 −0internal/equipo/planning/execution.go+30 −0internal/equipo/planning/plans.go+16 −2internal/equipo/plans.go+21 −22internal/equipo/runner_api.go+1 −1internal/equipo/runner_execution.go+97 −29internal/equipo/runner_mutations.go+39 −2internal/equipo/runner_report_validation.go+22 −3internal/equipo/runner_supervision.go+21 −2internal/equipo/task_prepare.go+15 −21internal/equipo/task_wait.go+5 −1internal/equipo/team/model.go+1 −1internal/plan3test/plan_workflow_test.go+258 −0internal/release/manifest.go+1 −0internal/release/manifest.json+99 −1internal/release/manifest_test.go+40 −0internal/release/policy_inventory.go+54 −0internal/runner/certification_inputs.go+5 −9internal/runner/certified/policy.go+3 −0internal/runner/checks/definition.go+3 −0internal/runner/checks/render.go+17 −0internal/runner/checks/render_test.go+30 −0internal/runner/containment/mounts.go+1 −1internal/runner/direct_cli_test.go+11 −6internal/runner/direct_graph_test.go+190 −21internal/runner/direct_workflow.go+6 −3internal/runner/http.go+1 −1internal/runner/plan_render.go+76 −0internal/runner/plan_workflow_test.go+132 −0internal/runner/planflow/budget_test.go+9 −0internal/runner/planflow/prompt.go+82 −0internal/runner/planflow/types.go+32 −0internal/runner/planflow/workflow.go+28 −0internal/runner/provider/actions.go+45 −0internal/runner/provider/claude/launcher.go+17 −4internal/runner/provider/claude/launcher_test.go+5 −0internal/runner/provider/claude/plan_policy_test.go+78 −0internal/runner/provider/codex/answers.go+14 −1internal/runner/provider/codex/launcher.go+15 −2internal/runner/provider/codex/plan_policy_test.go+79 −0internal/runner/provider/direct_certification.go+6 −3internal/runner/provider/policy.go+24 −2internal/runner/runtime_direct.go+10 −3internal/runner/runtime_workflow.go+14 −2internal/runner/supervisor.go+8 −2internal/runner/tool_journal.go+25 −0internal/runner/tool_proxy.go+4 −1internal/runner/tool_socket.go+3 −10internal/runner/tools.go+28 −10internal/runner/turn_prompt.go+4 −51internal/runner/workflow.go+79 −22internal/runner/workspace/read.go+110 −0internal/runner/workspace/workspace.go+16 −1internal/runnerproto/types.go+24 −9
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index a9261bc3..96ac46fd 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -21,9 +21,9 @@ time internal/runner 330s Final corrected package rerun measured 152.897s; revie |
| perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen. |
| perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory. |
| -size internal/runner 7500 - Direct namespaces, capture, journal and tool relay share the mandated runner package. Offline cutover leaves 7437 source lines and 6100 test lines; the test exemption is removed. |
| +size internal/runner 8000 - Task 4 retains direct journal, proxy, attestation and supervisor hooks in runner; pure step contracts live in planflow. Measured 7627 source and 6592 test lines. Tests remain under the default size ceiling. |
| time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner. |
| time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.659s (prior attempt 11.464s) for schema, native approval and fsynced capture fixtures; 15s gives 29 percent headroom under shared-runner load. |
| -time internal/directlive 180s Certification driver builds isolated fake CLI workers and runs both adapters through real namespaces, journal and MCP helper. |
| +time internal/directlive 360s Task 4 expands the fake certification matrix from 7 to 17 cases. The targeted fixture measured 246.910s; 360s leaves 46 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch. |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 0cad70a7..4e14e4ce 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -261,3 +261,58 @@ The executor exports both immutable Git snapshots through the existing trusted e |
| | `evidence.before` | Before | |
| | `evidence.after` | After | |
| | `evidence.approved` | Approved | |
| + |
| +## Task 4 |
| + |
| +Initial RED, exit 1: |
| + |
| +`CGO_ENABLED=0 go test ./internal/runner/... ./internal/plan3test -run '^TestPlanWorkflow' -count=1` |
| + |
| +The runner failed to compile because `internal/runner/planflow` was absent; plan3test reported `undefined: equipo.PlanJobSpec`. Provider policy tests then failed with `unknown field Action in struct literal of type provider.PolicyInputs`. The trusted-render test failed with `RenderDefinition undefined`. `TestPlanWorkflowRenderedSpec` failed with `rendered reproduction cannot be frozen`, then passed after the execution compiler retained the required freeze flag. |
| + |
| +The same main command passed after implementation and guard restoration: runner 183.718s, plan3test 1.502s, Claude 2.835s, Codex 2.045s, checks 0.139s. It exercises feature scope/base failure/build/review/checks/publication, chained Copy/Design/Engineering candidates with trusted renders and approval, read-only recommendation execution, investigation checkpoints, actual connection preference, immutable selections, frozen artifact handoff, tool payloads, broker approval, recovery and unproven namespace cancellation. |
| + |
| +Additional passing targeted commands, all with exit 0: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/runner -run '^TestDirectBugWorkflow$' -count=1`: 81.148s. |
| +- `CGO_ENABLED=0 go test ./internal/release ./internal/equipo/team ./internal/runner/forge ./internal/equipotest -run '^Test(PlanWorkflowRelease|Feature|RenderedChange|ReadWorkNoPublication|EvidenceKindsPreserveBug|PublishDescriptionRecovery|BugPreparation|BugPreparedRetry|RunnerSelectionGuards|RunnerPrepareOutbox|RunnerClaimRetryAndRace)' -count=1`: release 0.004s, core 3.482s, forge 2.217s, application regressions 37.742s. |
| +- `CGO_ENABLED=0 go test ./internal/runner/provider ./internal/runner/provider/claude ./internal/runner/provider/codex -run '^Test(DirectLiveGate|EffectivePolicy|ClaudeLaunchPolicy|ClaudeNative|CodexAppServerPolicy|CodexApprovalResponse|PlanWorkflowProviderPolicies)' -count=1`: 4.604s, 5.335s and 6.105s. |
| +- `CGO_ENABLED=0 go test ./internal/runner ./internal/runner/checks ./internal/plan3test ./internal/release -run '^TestPlanWorkflow(SpecialistOrder|NoMidStepSwitch|FrozenArtifacts|ToolPayloads|RenderPair|AnswerRecovery|ProviderPoliciesBroker|RenderedSpec|Release|RenderDefinition|RecommendationDelivery|Investigation|ConnectionPreference)|^TestTurnPrompt' -count=1`: passes after the prompt extraction and rendered-spec correction. |
| +- `CGO_ENABLED=0 go test ./internal/directlive -run '^TestDirectDriverFakeCLI$' -count=1`: 246.910s, all 17 cases passed. The first expanded run exhausted the old fixture-only 180-second allowance at the final Codex cases (exit 1, 184.932s). Increasing the fixture allowance to 360 seconds fixed that limit. The package time exception is now 360s, with the measured targeted run and rationale recorded in `.rastrillo/budgets.txt`. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanWorkflowRenderedWait$' -count=1`: RED exit 1, `publication did not wait for evidence and rendered approval`; GREEN exit 0 after adding the existing core readiness check to dispatch. Its guard was then disabled separately and produced the same assertion before restoration. |
| +- Final application run: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPlanWorkflow' -count=1`, exit 0, 1.928s, including the final rendered-publication wait guard. |
| +- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/planning ./internal/equipo/conversation ./internal/equipo/team ./internal/runner/... ./internal/runnerproto ./internal/release ./internal/plan3test ./internal/directlive`: passes. |
| +- `gofmt -l` over all changed Go files: no output. `git diff --check`: no output. |
| +- `make budget`: 29 directories within budget. The runner source exception increases from 7,500 to 8,000 for retained supervisor, journal, proxy and attestation hooks. No default-valued exception was added. |
| + |
| +The earlier bug-preparation regression exposed a dropped comparison against the recorded review selection. Both `review` and `review_snapshot` subtests failed; the comparison was restored and the full targeted regression command above passed. The render-chain fixture initially used a stale candidate lookup and an unconditional publisher-denial callback; those fixture errors were corrected before the passing workflow run. |
| + |
| +No full test suite, `make ci`, migration change, live provider session, sign-in, enrolment, push, merge or deployment was run. |
| + |
| +## Guard mutations |
| + |
| +Each guard below was broken separately, its named test failed with exit 1, and its source file was restored in a `finally` block before the next mutation. The restored tests pass. |
| + |
| +| Guard | Command | Exit | Failed assertion | Restoration | |
| +| --- | --- | --- | --- | --- | |
| +| action mapping | `CGO_ENABLED=0 go test ./internal/runner -run ^TestPlanWorkflowSpecialistOrder$ -count=1` | 1 | action mapped to wrong submission scope submit_answer | Restored | |
| +| frozen artifact handoff | `CGO_ENABLED=0 go test ./internal/runner -run ^TestPlanWorkflowFrozenArtifacts$ -count=1` | 1 | changed frozen artifact accepted | Restored | |
| +| immutable selection | `CGO_ENABLED=0 go test ./internal/runner -run ^TestPlanWorkflowNoMidStepSwitch$ -count=1` | 1 | changed account accepted | Restored | |
| +| atomic answer delivery | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanWorkflowRecommendationDelivery$ -count=1` | 1 | delivery failure ignored | Restored | |
| +| answer replay input | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanWorkflowRecommendationDelivery$ -count=1` | 1 | changed answer replay accepted | Restored | |
| +| no-publish research | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanWorkflowRecommendation$ -count=1` | 1 | research gained write authority: {RequestKey:task/plan/1 Project:1 Account:team Parent:0 Requester:owner@example.com GrantRef:eyJ2ZXJzaW9uIjoxLCJwcm9qZWN0X2lkIjoxLCJhZGRyZXNzIjoib3duZXJAZXhhbXBsZS5jb20ifQ Target:{Kind:project_read Repository:amadan.net/test/fixture Ref:equipo/unwanted DefaultRef: BaseRevision:project/0 App: Subject:} Evidence:{FrozenAcceptanceHash: RenderedApprovalHash: RenderedApprovals:[] RequiredDecisions:[] RequireBugFreeze:false FrozenReproductionHash: BaselineTestSetHash: Predicate: ExpectedSymptom: CheckDefinitionHash: RequiredSources:0} Policy:{Version:2 UsageMode:subscription RequireDistinctReviewFamily:true Job:{Calls:24 InputTokens:200000 OutputTokens:40000 CostMicros:0} Account:{Calls:24 InputTokens:200000 OutputTokens:40000 CostMicros:0} PerCall:{Calls:1 InputTokens:32000 OutputTokens:4000 CostMicros:0} Rates:{Version:0 InputMicrosPer:0 OutputMicrosPer:0 CallMicrosPer:0 ForgeMicrosPer:0 TrackerMicrosPer:0} MaxAttemptsPerStep:2 MaxConcurrentAttempts:2 MaxDepth:0 LeaseSeconds:60 AdmissionSeconds:5 JobSeconds:2700 AttemptSeconds:1200 RequireDistinctReviewProvider:true} Steps:[{Key:research Capability:research Version:1 DependsOn:[]}]} | Restored | |
| +| read-only provider policy | `CGO_ENABLED=0 go test ./internal/runner/provider/codex -run ^TestPlanWorkflowProviderPolicies$ -count=1` | 1 | read-only profile writes | Restored | |
| +| changed inventory certification | `CGO_ENABLED=0 go test ./internal/release -run ^TestPlanWorkflowReleaseRejectsOldCertificate$ -count=1` | 1 | old certificate enabled changed inventory reproduce | Restored | |
| +| strict tool payload | `CGO_ENABLED=0 go test ./internal/runner -run ^TestPlanWorkflowToolPayloads$ -count=1` | 1 | submit_acceptance accepted fabricated attestation | Restored | |
| +| trusted render material | `CGO_ENABLED=0 go test ./internal/runner/checks -run ^TestPlanWorkflowRenderDefinition$ -count=1` | 1 | candidate replaced the trusted renderer | Restored | |
| +| single render request | `CGO_ENABLED=0 go test ./internal/runner -run ^TestPlanWorkflowRenderPair$ -count=1` | 1 | duplicate render accepted | Restored | |
| +| rendered publication wait | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPlanWorkflowRenderedWait$ -count=1` | 1 | publication did not wait for evidence and rendered approval | Restored | |
| + |
| + |
| +Task 4 compiles revisioned plans into the existing core, snapshots actions and actual selections, chains immutable candidates, freezes feature acceptance, renders through trusted executor material, and delivers sourced read-only answers atomically. Rendered publication waits for evidence and person approval before assignment. Investigation needs an explicit new plan revision to proceed to a build. |
| + |
| +The manifest contains 16 explicitly uncertified constructor inventory hashes. They are not account-bound executable certificates. Both release certification arrays remain empty, and pending profiles cannot inherit an old certificate. The fake certification matrix covers 17 cases. Live certification and the three pending tool descriptions remain release gates. |
| + |
| +Final measured source/test lines: runner 7627/6592 (source cap 8000); equipo 10747/437 (existing source cap 10800); team 9088/6353 (existing source cap 9500); planflow 142/9; plan3test 0/1437; directlive 1673/263. Full-package runtime was not measured under this targeted-only dispatch. |
| + |
| +Full report and copy inventory: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-4-report.md` (workspace-local, ignored by the repository). No live providers, sign-ins, enrolment, pushes, merges or deployment. No agents or copy-review server were started. |
diff --git a/internal/directlive/driver.go b/internal/directlive/driver.go| index 80438443..7814897f 100644 |
| --- a/internal/directlive/driver.go |
| +++ b/internal/directlive/driver.go |
| @@ -76,7 +76,7 @@ func run(ctx context.Context, c provider.DirectLiveConfig, config []byte, p Path |
| var records []provider.DirectEvidence |
| var failures []error |
| for _, b := range c.Bindings { |
| - for _, role := range []string{"Engineering", "Engineering-reproduction", "Review", "Product"} { |
| + for _, role := range []string{"Engineering", "Engineering-reproduction", "Review", "Product", "Scope", "Research", "Investigation", "Copy", "Design"} { |
| if b.Binding.Provider == "codex" && role == "Product" { |
| continue |
| } |
| @@ -235,8 +235,8 @@ func (d *driver) exercise(ctx context.Context, b provider.DirectLiveBinding, rol |
| if err != nil { |
| return e, err |
| } |
| - step := map[string]string{"Engineering": "implement", "Engineering-reproduction": "reproduce", "Review": "review", "Product": "reproduce"}[role] |
| - tool := map[string]string{"implement": "submit_candidate", "reproduce": "submit_reproduction", "review": "submit_review"}[step] |
| + step := map[string]string{"Engineering": "implement", "Engineering-reproduction": "reproduce", "Review": "review", "Product": "reproduce", "Scope": "scope", "Research": "recommend", "Investigation": "investigate", "Copy": "copy", "Design": "design"}[role] |
| + tool := map[string]string{"implement": "submit_candidate", "reproduce": "submit_reproduction", "review": "submit_review", "scope": "submit_acceptance", "recommend": "submit_answer", "investigate": "submit_answer", "copy": "submit_candidate", "design": "submit_candidate"}[step] |
| selection := provider.Selection{ConnectionID: b.Binding.ID, Provider: binding.Provider, Family: map[string]string{"claude": "claude", "codex": "gpt"}[binding.Provider], AccountID: binding.AccountID, Model: b.Model} |
| in, err := runner.CertificationInputs(ctx, d.policyPaths.config(d.paths), selection, binding, d.cfg.Repository, step, policyScratch) |
| if err != nil { |
diff --git a/internal/directlive/driver_test.go b/internal/directlive/driver_test.go| index e585d7c6..6f9b1177 100644 |
| --- a/internal/directlive/driver_test.go |
| +++ b/internal/directlive/driver_test.go |
| @@ -76,7 +76,7 @@ func TestDirectDriverFakeWorker(t *testing.T) { |
| if root == "" { |
| t.Skip("subprocess fixture only") |
| } |
| - c := provider.DirectLiveConfig{RunID: "fake", Disposable: true, Repository: filepath.Join(root, "repo"), EvidenceDir: filepath.Join(root, "evidence"), Origin: "http://127.0.0.1:1", MachineFingerprint: "fake", Sentinels: map[string]string{}, Funding: provider.LiveFunding{Calls: 1000, InputTokens: 100000, OutputTokens: 100000, Seconds: 180, JobInput: 23000, JobOutput: 23000, ProjectInputHeadroom: 23000, ProjectOutputHeadroom: 23000, TeamInputHeadroom: 23000, TeamOutputHeadroom: 23000}} |
| + c := provider.DirectLiveConfig{RunID: "fake", Disposable: true, Repository: filepath.Join(root, "repo"), EvidenceDir: filepath.Join(root, "evidence"), Origin: "http://127.0.0.1:1", MachineFingerprint: "fake", Sentinels: map[string]string{}, Funding: provider.LiveFunding{Calls: 1000, InputTokens: 100000, OutputTokens: 100000, Seconds: 360, JobInput: 23000, JobOutput: 23000, ProjectInputHeadroom: 23000, ProjectOutputHeadroom: 23000, TeamInputHeadroom: 23000, TeamOutputHeadroom: 23000}} |
| for _, name := range []string{"repo", "evidence", "home-claude", "home-codex", "other", "state"} { |
| if err := os.Mkdir(filepath.Join(root, name), 0700); err != nil { |
| t.Fatal(err) |
| @@ -142,7 +142,7 @@ func TestDirectDriverFakeWorker(t *testing.T) { |
| t.Fatal(err) |
| } |
| var index []string |
| - if json.Unmarshal(raw, &index) != nil || len(index) != 7 { |
| + if json.Unmarshal(raw, &index) != nil || len(index) != 17 { |
| t.Fatal("missing driver coverage") |
| } |
| for _, name := range index { |
diff --git a/internal/directlive/turn.go b/internal/directlive/turn.go| index f4dd6320..867589e3 100644 |
| --- a/internal/directlive/turn.go |
| +++ b/internal/directlive/turn.go |
| @@ -29,6 +29,9 @@ func (x *exercise) relay() runner.DirectQuestionRelay { |
| func (x *exercise) open(ctx context.Context, tool string) error { |
| deadline, _ := ctx.Deadline() |
| b := runner.ToolBinding{Copy: equipo.RunnerToolCopy(), InstanceID: x.d.cfg.MachineFingerprint, TaskID: x.launch.AttemptKey, Attempt: 1, Fence: 1, Tools: []string{tool, "ask_person"}, LeaseDeadline: deadline, Journal: x.journal, Isolation: team.IsolationSnapshot{Status: "confined"}, ReadPolicy: provider.ReadPolicy{ConfigHash: x.launch.Policy.Hash, DeniedPaths: []string{x.launch.Binding.CredentialHome}}, Current: func(ctx context.Context) error { return ctx.Err() }, Agent: provider.Agent{ServerID: "direct", Provider: x.launch.Selection.Provider, Family: x.launch.Selection.Family, AccountID: x.launch.Selection.AccountID, Model: x.launch.Selection.Model}} |
| + if tool == "submit_candidate" { |
| + b.Tools = append(b.Tools, "submit_render") |
| + } |
| b.Ask = func(ctx context.Context, bound runner.ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) { |
| q := runner.ToolSubmission{InstanceID: bound.InstanceID, TaskID: bound.TaskID, Attempt: bound.Attempt, Fence: bound.Fence, Agent: bound.Agent, Name: "ask_person", RequestID: id, Arguments: args} |
| if err := x.submissionGuards(ctx, q); err != nil { |
diff --git a/internal/equipo/connection_selection.go b/internal/equipo/connection_selection.go| index 842f9ec0..ada2f327 100644 |
| --- a/internal/equipo/connection_selection.go |
| +++ b/internal/equipo/connection_selection.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| "context" |
| "errors" |
| "time" |
| @@ -48,7 +49,10 @@ func specialistAt(tx *gorm.DB, key string) (Specialist, error) { |
| capabilities = []string{"review", "verify"} |
| } |
| var live int64 |
| - if err := tx.Table("attempts").Joins("JOIN steps ON steps.id = attempts.step_id").Where("attempts.containment = ? AND steps.capability IN ?", "pending", capabilities).Count(&live).Error; err != nil { |
| + if key == "product" { |
| + capabilities = []string{"scope", "research"} |
| + } |
| + if err := tx.Table("attempts").Joins("JOIN steps ON steps.id = attempts.step_id").Where("attempts.containment = ? AND (steps.capability IN ? OR EXISTS (SELECT 1 FROM runner_assignments ra WHERE ra.attempt_id=attempts.id AND json_extract(ra.brief,'$.step.SpecialistKey')=?))", "pending", capabilities, key).Count(&live).Error; err != nil { |
| return sp, storeError(err) |
| } |
| if live >= int64(sp.MaxConcurrent) { |
| @@ -77,6 +81,9 @@ func (s *Store) selectConnectionAt(tx *gorm.DB, person string, projectID int64, |
| return s.selectConnectionOnRunnerAt(tx, person, projectID, specialist, excludedFamily, "") |
| } |
| func (s *Store) selectConnectionOnRunnerAt(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily, runnerID string) (Selection, error) { |
| + return s.selectStepConnection(tx, person, projectID, specialist, excludedFamily, runnerID, taskplan.Step{}, true) |
| +} |
| +func (s *Store) selectStepConnection(tx *gorm.DB, person string, projectID int64, specialist, excludedFamily, runnerID string, step taskplan.Step, requirePair bool) (Selection, error) { |
| var result Selection |
| err := func() error { |
| m, err := currentRunnerMember(tx, person) |
| @@ -113,6 +120,12 @@ func (s *Store) selectConnectionOnRunnerAt(tx *gorm.DB, person string, projectID |
| } |
| now := s.runnerClock.Now().UTC() |
| pin := choice.PinnedID |
| + if step.ConnectionID != "" { |
| + if pin != "" && pin != step.ConnectionID && excludedFamily == "" { |
| + return ErrConflict |
| + } |
| + pin = step.ConnectionID |
| + } |
| // A builder-family pin cannot choose the reviewer. Within the other family, |
| // a pin still waits rather than silently moving to another account. |
| if excludedFamily != "" { |
| @@ -127,7 +140,7 @@ func (s *Store) selectConnectionOnRunnerAt(tx *gorm.DB, person string, projectID |
| continue |
| } |
| for _, r := range c.Reports { |
| - if !knownFamily(r.Family) || r.Family == excludedFamily || !specialistAllows(sp, r) { |
| + if !knownFamily(r.Family) || r.Family == excludedFamily || !specialistAllows(sp, r) || (step.Model != "" && step.Model != r.Model) { |
| continue |
| } |
| ok, _, err := s.eligible(tx, c, r, now) |
| @@ -137,7 +150,7 @@ func (s *Store) selectConnectionOnRunnerAt(tx *gorm.DB, person string, projectID |
| if !ok { |
| continue |
| } |
| - if specialist == "engineering" { |
| + if requirePair && specialist == "engineering" { |
| review, err := specialistAt(tx, "review") |
| if err != nil { |
| return err |
diff --git a/internal/equipo/conversation/answer.go b/internal/equipo/conversation/answer.go| new file mode 100644 |
| index 00000000..2a1fd629 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/answer.go |
| @@ -0,0 +1,36 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +// DeliverAnswer runs inside the same write transaction as read-work completion. |
| +func (s *Store) DeliverAnswer(actor kernel.Actor, taskID, author, requestID string, answer taskplan.AnswerResult) error { |
| + if taskplan.ValidateAnswer(answer) != nil { |
| + return s.deps.Invalid |
| + } |
| + thread, task, err := s.thread(actor, taskID) |
| + if err != nil { |
| + return err |
| + } |
| + hash, err := kernel.InputHash(answer) |
| + if err != nil { |
| + return err |
| + } |
| + req := requestRecord{Principal: actor.Address, Operation: "answer", Resource: taskID, RequestID: requestID, InputHash: hash} |
| + if _, ok, err := s.replay(req); ok || err != nil { |
| + return err |
| + } |
| + msg, err := s.appendMessage(thread.ID, "", thread.ID, "specialist", author, answer.Body, "discussion") |
| + if err != nil { |
| + return err |
| + } |
| + if err = s.TaskCard(actor, task); err != nil { |
| + return err |
| + } |
| + if err = s.deps.Audit(s.tx, actor, "answer.deliver", taskID); err != nil { |
| + return err |
| + } |
| + return s.save(req, msg) |
| +} |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 2def4ecd..8e2172b6 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -200,11 +200,17 @@ const CopyToolReview = "Submit a review of this task's candidate. Reuse the requ |
| const CopyToolReproduction = "Submit reproduction files and test names for this task. Encode file bytes as base64. The complete request must fit within 64 KiB. Reuse the request ID only for an identical retry." |
| func RunnerToolCopy() runner.ToolCopy { |
| - return runner.ToolCopy{Accepted: CopyToolAccepted, Rejected: CopyToolRejected, Ask: CopyToolAsk, Candidate: CopyToolCandidate, Review: CopyToolReview, Reproduction: CopyToolReproduction} |
| + return runner.ToolCopy{Acceptance: copyText("tool.acceptance"), Answer: copyText("tool.answer"), Render: copyText("tool.render"), Accepted: CopyToolAccepted, Rejected: CopyToolRejected, Ask: CopyToolAsk, Candidate: CopyToolCandidate, Review: CopyToolReview, Reproduction: CopyToolReproduction} |
| } |
| // runnerDraftCopy is the Task 16 runtime inventory. Each entry needs review. |
| var runnerDraftCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: tool.acceptance |
| + "tool.acceptance": "Submit acceptance tests for the requested behaviour. Encode file bytes as base64. Reuse the request ID only for an identical retry.", |
| + // COPY REVIEW REQUIRED: tool.answer |
| + "tool.answer": "Submit an answer with references to the supplied source snapshots. Reuse the request ID only for an identical retry.", |
| + // COPY REVIEW REQUIRED: tool.render |
| + "tool.render": "Request a trusted render of the submitted candidate commit. Reuse the request ID only for an identical retry.", |
| // COPY REVIEW REQUIRED: evidence.acceptance |
| "evidence.acceptance": "Acceptance tests", |
| // COPY REVIEW REQUIRED: evidence.frozen |
diff --git a/internal/equipo/plan_answer.go b/internal/equipo/plan_answer.go| new file mode 100644 |
| index 00000000..94ba1521 |
| --- /dev/null |
| +++ b/internal/equipo/plan_answer.go |
| @@ -0,0 +1,21 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func (e *Execution) deliverAnswerAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, q RunnerRequest) error { |
| + var answer team.AnswerResult |
| + if q.Artifact == nil || json.Unmarshal(q.Artifact.Payload, &answer) != nil { |
| + return ErrInvalid |
| + } |
| + if err := tx.Model(&Task{}).Where("id=?", a.TaskID).Select("Revision").Updates(map[string]any{"Revision": gorm.Expr("revision+1")}).Error; err != nil { |
| + return err |
| + } |
| + return conversationAt(tx).DeliverAnswer(Actor{Address: a.Person}, a.TaskID, a.StepKey, strconv.FormatInt(int64(q.Handle.Attempt), 10), answer) |
| +} |
diff --git a/internal/equipo/plan_execution.go b/internal/equipo/plan_execution.go| new file mode 100644 |
| index 00000000..bdb68a65 |
| --- /dev/null |
| +++ b/internal/equipo/plan_execution.go |
| @@ -0,0 +1,139 @@ |
| +package equipo |
| + |
| +import ( |
| + "encoding/json" |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/planning" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func PlanJobSpec(task Task, project Project, p taskplan.Plan, policy team.Policy) (team.JobSpec, error) { |
| + if task.TeamID == "" || !validAddress(task.Requester) || task.ProjectID != project.ID || project.ID <= 0 { |
| + return team.JobSpec{}, ErrInvalid |
| + } |
| + repository, err := canonicalRepository(project.Repository) |
| + if err != nil || repository != project.Repository { |
| + return team.JobSpec{}, ErrInvalid |
| + } |
| + target := team.TargetBinding{Kind: team.TargetProjectRead, Repository: project.Repository, BaseRevision: "project/" + strconv.FormatInt(project.Revision, 10)} |
| + if taskplan.Publication(p.Kind) { |
| + t := task |
| + if t.Description == "" { |
| + t.Description = t.ID |
| + } |
| + spec, err := BugJobSpec(t, project, policy, t.Description) |
| + if err != nil { |
| + return team.JobSpec{}, err |
| + } |
| + target = spec.Target |
| + } |
| + return planning.ExecutionSpec(task, p, target, policy, GrantRef(project.ID, task.Requester)) |
| +} |
| + |
| +// stepAt resolves persisted actions; step keys never choose capabilities. |
| +func (s *Store) stepAt(tx *gorm.DB, t Task, key string) (taskplan.Plan, taskplan.Step, error) { |
| + p, err := s.planningAt(tx).Plan(t) |
| + if err != nil { |
| + return p, taskplan.Step{}, err |
| + } |
| + if key == "prepare" { |
| + for _, st := range p.Steps { |
| + if st.Specialist != "" { |
| + return p, st, nil |
| + } |
| + } |
| + } |
| + for _, st := range p.Steps { |
| + if st.Key == key { |
| + return p, st, nil |
| + } |
| + } |
| + if key == "publish" && taskplan.Publication(p.Kind) { |
| + return p, taskplan.Step{Key: key, Action: "publish"}, nil |
| + } |
| + return p, taskplan.Step{}, ErrInvalid |
| +} |
| +func executionSpecialist(st taskplan.Step) string { |
| + if st.Specialist != "" { |
| + return st.Specialist |
| + } |
| + if st.Action == "checks" || st.Action == "publish" { |
| + return "review" |
| + } |
| + return "engineering" |
| +} |
| +func (s *Store) planPair(tx *gorm.DB, t Task, p taskplan.Plan) (Selection, Selection, error) { |
| + var first taskplan.Step |
| + for _, st := range p.Steps { |
| + if st.Specialist != "" { |
| + first = st |
| + break |
| + } |
| + } |
| + selected, err := s.selectStepConnection(tx, t.Requester, t.ProjectID, executionSpecialist(first), "", "", first, false) |
| + if err != nil { |
| + return selected, Selection{}, err |
| + } |
| + if err = subscriptionSelection(tx, selected); err != nil { |
| + return selected, Selection{}, err |
| + } |
| + // Scope and research can begin with one family. Builders require a reviewer. |
| + if !taskplan.Candidate(first) && first.Action != "reproduce" { |
| + return selected, Selection{}, nil |
| + } |
| + review, err := s.selectStepConnection(tx, t.Requester, t.ProjectID, "review", selected.Family, selected.RunnerID, taskplan.Step{}, false) |
| + if err == nil { |
| + err = subscriptionSelection(tx, review) |
| + } |
| + return selected, review, err |
| +} |
| +func (s *Store) dispatchSelection(tx *gorm.DB, t Task, st taskplan.Step, first Selection) (Selection, error) { |
| + runnerID := first.RunnerID |
| + var assignments []runnerAssignment |
| + if err := tx.Where("task_id=? AND claim_request<>''", t.ID).Order("id").Find(&assignments).Error; err != nil { |
| + return Selection{}, err |
| + } |
| + families := map[string]bool{} |
| + for _, a := range assignments { |
| + var b RunnerBrief |
| + if json.Unmarshal([]byte(a.Brief), &b) != nil { |
| + return Selection{}, ErrUnavailable |
| + } |
| + if a.RunnerID != runnerID { |
| + return Selection{}, ErrConflict |
| + } |
| + if taskplan.Candidate(taskplan.Step{Action: b.Step.Action}) { |
| + families[b.Selection.Family] = true |
| + } |
| + } |
| + excluded := "" |
| + if st.Action == "review" || st.Action == "checks" || st.Action == "publish" { |
| + if len(families) != 1 { |
| + return Selection{}, ErrUnavailable |
| + } |
| + for f := range families { |
| + excluded = f |
| + } |
| + } |
| + specialist := executionSpecialist(st) |
| + if st.Action == "publish" { |
| + specialist = "review" |
| + } |
| + sel, err := s.selectStepConnection(tx, t.Requester, t.ProjectID, specialist, excluded, runnerID, st, false) |
| + if err != nil { |
| + return sel, err |
| + } |
| + if taskplan.Candidate(st) || st.Action == "reproduce" { |
| + families[sel.Family] = true |
| + if len(families) > 1 { |
| + return sel, ErrUnavailable |
| + } |
| + if _, err = s.selectStepConnection(tx, t.Requester, t.ProjectID, "review", sel.Family, runnerID, taskplan.Step{}, false); err != nil { |
| + return sel, err |
| + } |
| + } |
| + return sel, subscriptionSelection(tx, sel) |
| +} |
diff --git a/internal/equipo/planning/execution.go b/internal/equipo/planning/execution.go| new file mode 100644 |
| index 00000000..eb3a3753 |
| --- /dev/null |
| +++ b/internal/equipo/planning/execution.go |
| @@ -0,0 +1,30 @@ |
| +package planning |
| + |
| +import ( |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +// ExecutionSpec accepts a validated target from the application boundary. |
| +func ExecutionSpec(t Task, p taskplan.Plan, target team.TargetBinding, policy team.Policy, grant string) (team.JobSpec, error) { |
| + if t.ID == "" || p.TaskID != t.ID || p.ProjectID != t.ProjectID || p.Revision != t.PlanRevision || p.Revision < 1 || policy.Validate() != nil { |
| + return team.JobSpec{}, taskplan.ErrInvalid |
| + } |
| + steps, err := ExecutionSteps(p) |
| + if err != nil { |
| + return team.JobSpec{}, err |
| + } |
| + e := team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: t.Description, CheckDefinitionHash: t.CheckDefinitionHash, BaselineTestSetHash: t.BaselineTestSetHash, RequireBugFreeze: true} |
| + if p.Kind != taskplan.Bug { |
| + e, err = EvidenceForPlan(p, t.CheckDefinitionHash, t.BaselineTestSetHash) |
| + } |
| + if err != nil { |
| + return team.JobSpec{}, err |
| + } |
| + if p.Kind == taskplan.RenderedChange { |
| + e.RequireBugFreeze = true |
| + } |
| + return team.JobSpec{Account: team.AccountID(t.TeamID), Project: team.ProjectID(t.ProjectID), Requester: t.Requester, RequestKey: t.ID + "/plan/" + strconv.FormatInt(p.Revision, 10), GrantRef: grant, Target: target, Evidence: e, Policy: policy, Steps: steps}, nil |
| +} |
diff --git a/internal/equipo/planning/plans.go b/internal/equipo/planning/plans.go| index b16fbccf..75e275e1 100644 |
| --- a/internal/equipo/planning/plans.go |
| +++ b/internal/equipo/planning/plans.go |
| @@ -255,13 +255,17 @@ func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (ta |
| } |
| } |
| p = taskplan.Normalize(p) |
| - if t.JobID != 0 && p.Kind != before.Kind { |
| + checkpoint := before.Kind == taskplan.Investigation && t.State == "waiting_checkpoint" && job.State == team.JobSucceeded && taskplan.Publication(p.Kind) |
| + if checkpoint { |
| + started = map[string]bool{} |
| + } |
| + if t.JobID != 0 && p.Kind != before.Kind && !checkpoint { |
| return result, s.deps.Invalid |
| } |
| if err = taskplan.ValidateEdit(before, p, started); err != nil { |
| return result, s.deps.Invalid |
| } |
| - if t.JobID != 0 { |
| + if t.JobID != 0 && !checkpoint { |
| change, err := GraphChange(p, steps) |
| if err != nil { |
| return result, s.deps.Invalid |
| @@ -279,6 +283,16 @@ func (s *Store) Edit(actor kernel.Actor, p taskplan.Plan, m kernel.Mutation) (ta |
| return result, err |
| } |
| } |
| + if checkpoint { |
| + t.JobID = 0 |
| + t.State = "proposed" |
| + t.BaseCommit = "" |
| + t.CheckDefinitionHash = "" |
| + t.BaselineTestSetHash = "" |
| + if err = s.tx.Model(&Outbox{}).Where("task_id=?", t.ID).Select("State", "Prepared", "JobSpec", "Engineering", "Review").Updates(&Outbox{State: "plan"}).Error; err != nil { |
| + return result, err |
| + } |
| + } |
| t.Revision++ |
| t.PlanRevision++ |
| t.ApprovalRevision = 0 |
diff --git a/internal/equipo/plans.go b/internal/equipo/plans.go| index c3867d90..28ca139c 100644 |
| --- a/internal/equipo/plans.go |
| +++ b/internal/equipo/plans.go |
| @@ -94,23 +94,8 @@ func (s *Store) planReady(tx *gorm.DB, t Task, p taskplan.Plan) error { |
| 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 |
| + _, _, err = s.planPair(tx, t, p) |
| + return err |
| } |
| func (s *Store) ProposePlan(ctx context.Context, actor Actor, p taskplan.Plan, m Mutation) (taskplan.Plan, error) { |
| actor.Address = normalizeAddress(actor.Address) |
| @@ -198,10 +183,6 @@ func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error { |
| 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 |
| } |
| @@ -213,7 +194,7 @@ func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error { |
| if err != nil { |
| return err |
| } |
| - eng, rev, err := s.bugPair(tx, t.Requester, t.ProjectID) |
| + eng, rev, err := s.planPair(tx, t, p) |
| if err != nil { |
| return err |
| } |
| @@ -223,5 +204,23 @@ func (s *Store) preparePlanOutbox(tx *gorm.DB, t Task) error { |
| 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 |
| } |
| + if !taskplan.Publication(p.Kind) { |
| + policy, err := bugPolicy(tx, t) |
| + if err != nil { |
| + return err |
| + } |
| + spec, err := PlanJobSpec(t, project, p, policy) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(spec) |
| + if err != nil { |
| + return err |
| + } |
| + if err = tx.Model(&taskOutbox{}).Where("task_id=?", t.ID).Select("State", "JobSpec").Updates(&taskOutbox{State: "job", JobSpec: string(raw)}).Error; err != nil { |
| + return err |
| + } |
| + return tx.Model(&Task{}).Where("id=?", t.ID).Select("State").Updates(&Task{State: "prepared"}).Error |
| + } |
| return tx.Model(&Task{}).Where("id=?", t.ID).Select("State").Updates(&Task{State: "preparing"}).Error |
| } |
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go| index afd81233..7d7cd7ee 100644 |
| --- a/internal/equipo/runner_api.go |
| +++ b/internal/equipo/runner_api.go |
| @@ -22,7 +22,7 @@ func (s *Store) runnerRouter() chi.Router { |
| r.Post("/blobs/read", s.runnerReadBlob) |
| r.Post("/claim", s.runnerClaim) |
| r.Post("/recover_claim", s.runnerRecoverClaim) |
| - for _, op := range []string{"validate", "evidence", "freeze", "conclude", "publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { |
| + for _, op := range []string{"validate", "evidence", "freeze", "freeze_feature", "conclude", "publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { |
| r.Post("/"+op, s.runnerMutation(op)) |
| } |
| r.Post("/connections", s.runnerConnections) |
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go| index 01db82ed..da4b988b 100644 |
| --- a/internal/equipo/runner_execution.go |
| +++ b/internal/equipo/runner_execution.go |
| @@ -13,6 +13,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| "gorm.io/gorm" |
| "gorm.io/plugin/dbresolver" |
| ) |
| @@ -44,14 +45,6 @@ func assignmentValue(a runnerAssignment) (Assignment, error) { |
| sel.Isolation = iso |
| return Assignment{ID: a.ID, TaskID: a.TaskID, StepKey: a.StepKey, WorkspaceKey: a.WorkspaceKey, Scope: Scope{Account: team.AccountID(a.TeamID), Job: team.JobID(a.JobID)}, Selection: sel, Revision: a.Revision, Kind: a.Kind}, nil |
| } |
| -func specialistFor(step string) string { |
| - switch step { |
| - case "review", "verify": |
| - return "review" |
| - default: |
| - return "engineering" |
| - } |
| -} |
| func mergeIsolation(a, b team.IsolationSnapshot) team.IsolationSnapshot { |
| a.ProfileApprovals = team.MergeProfileApprovals(a.ProfileApprovals, b.ProfileApprovals) |
| a.Trial = team.MergeTrial(a.Trial, b.Trial) |
| @@ -76,6 +69,14 @@ func mergeIsolation(a, b team.IsolationSnapshot) team.IsolationSnapshot { |
| return a |
| } |
| func (s *Store) selectionCurrent(tx *gorm.DB, task Task, step string, sel Selection) (Selection, error) { |
| + _, st, err := s.stepAt(tx, task, step) |
| + if err != nil { |
| + return sel, err |
| + } |
| + specialist := executionSpecialist(st) |
| + if st.Action == "publish" { |
| + specialist = "review" |
| + } |
| if _, err := bugAuthority(tx, Actor{Address: task.Requester}, task.ProjectID); err != nil { |
| return sel, err |
| } |
| @@ -86,11 +87,11 @@ func (s *Store) selectionCurrent(tx *gorm.DB, task Task, step string, sel Select |
| if err != nil { |
| return sel, err |
| } |
| - if !slices.Contains(ids, sel.ConnectionID) || (choice.Revision != sel.ChoiceRevision && choice.PinnedID != "" && choice.PinnedID != sel.ConnectionID && specialistFor(step) != "review") { |
| + if !slices.Contains(ids, sel.ConnectionID) || choice.Revision != sel.ChoiceRevision { |
| return sel, ErrConflict |
| } |
| var sp Specialist |
| - if err := tx.First(&sp, "key=?", specialistFor(step)).Error; err != nil { |
| + if err := tx.First(&sp, "key=?", specialist).Error; err != nil { |
| return sel, storeError(err) |
| } |
| if sp.Revision != sel.SpecialistRevision { |
| @@ -114,7 +115,7 @@ func (s *Store) selectionCurrent(tx *gorm.DB, task Task, step string, sel Select |
| if err != nil { |
| return sel, err |
| } |
| - if !ok { |
| + if !ok || !specialistAllows(sp, r) { |
| return sel, ErrForbidden |
| } |
| iso, err := s.isolationSnapshot(tx, c, r) |
| @@ -159,20 +160,34 @@ func (e *Execution) assignmentCurrent(ctx context.Context, tx *gorm.DB, p Runner |
| if err != nil { |
| return value, err |
| } |
| - // Both families must still be available before any provider spending. |
| - if specialistFor(a.StepKey) == "engineering" { |
| - var out taskOutbox |
| - if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil { |
| - return value, storeError(err) |
| + _, step, err := e.store.stepAt(tx, task, a.StepKey) |
| + if err != nil { |
| + return value, err |
| + } |
| + if a.Brief != "" { |
| + var frozen RunnerBrief |
| + if json.Unmarshal([]byte(a.Brief), &frozen) != nil { |
| + return value, ErrUnavailable |
| } |
| - var rev Selection |
| - if err := json.Unmarshal([]byte(out.Review), &rev); err != nil { |
| - return value, err |
| + if frozen.ProjectRevision > 0 { |
| + var project Project |
| + if err = tx.First(&project, task.ProjectID).Error; err != nil { |
| + return value, err |
| + } |
| + budget, err := bugBudget(tx, task.TeamID, task.ProjectID) |
| + if err != nil { |
| + return value, err |
| + } |
| + if project.Revision != frozen.ProjectRevision || budget.Revision != frozen.BudgetRevision { |
| + return value, ErrConflict |
| + } |
| } |
| - if rev.Family == sel.Family || rev.RunnerID != sel.RunnerID { |
| - return value, ErrForbidden |
| + if frozen.Step.PlanRevision > 0 && (frozen.Step.PlanRevision != task.PlanRevision || frozen.Step.Action != step.Action || frozen.Step.SpecialistKey != executionSpecialist(step)) { |
| + return value, ErrConflict |
| } |
| - if _, err := e.store.selectionCurrent(tx, task, "review", rev); err != nil { |
| + } |
| + if taskplan.Candidate(step) || step.Action == "reproduce" { |
| + if _, err = e.store.selectStepConnection(tx, task.Requester, task.ProjectID, "review", sel.Family, sel.RunnerID, taskplan.Step{}, false); err != nil { |
| return value, err |
| } |
| } |
| @@ -354,10 +369,34 @@ func (e *Execution) Sync(ctx context.Context) error { |
| if count > 0 { |
| continue |
| } |
| + plan, st, err := e.store.stepAt(tx, task, key) |
| + if err != nil { |
| + return err |
| + } |
| + if st.Action == "publish" && plan.Kind == taskplan.RenderedChange { |
| + ready, err := e.Core.ReadyToPublish(ctx, Scope{Account: team.AccountID(task.TeamID), Job: task.JobID}) |
| + if err != nil && !taskRefusal(err) && !errors.Is(err, team.ErrEvidence) { |
| + return err |
| + } |
| + if err != nil || !ready.Satisfied { |
| + if err = taskWait(tx, task.ID, "evidence.awaiting_person"); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + } |
| sel := eng |
| - if specialistFor(key) == "review" { |
| - sel = rev |
| + if key != "prepare" { |
| + sel, err = e.store.dispatchSelection(tx, task, st, eng) |
| + if err != nil { |
| + if taskRefusal(err) { |
| + continue |
| + } |
| + return err |
| + } |
| } |
| + frozen := RunnerBrief{ProjectRevision: out.ProjectRevision, BudgetRevision: out.BudgetRevision, Step: runnerproto.StepBrief{PlanRevision: plan.Revision, StepKey: key, Action: st.Action, SpecialistKey: executionSpecialist(st), SpecialistRevision: sel.SpecialistRevision}, Selection: sel} |
| + frozenRaw, _ := json.Marshal(frozen) |
| raw, _ := json.Marshal(sel) |
| iso, _ := json.Marshal(sel.Isolation) |
| kind := "step" |
| @@ -372,7 +411,7 @@ func (e *Execution) Sync(ctx context.Context) error { |
| if err := tx.Raw("SELECT COALESCE(MAX(CAST(id AS INTEGER)),0)+1 FROM runner_assignments").Scan(&sequence).Error; err != nil { |
| return storeError(err) |
| } |
| - a := runnerAssignment{ProtocolVersion: runnerproto.DirectVersion, ID: fmt.Sprintf("%020d", sequence), TaskID: task.ID, StepKey: key, WorkspaceKey: rand.Text(), TeamID: task.TeamID, RunnerID: sel.RunnerID, Person: task.Requester, Selection: string(raw), Isolation: string(iso), Kind: kind, State: "pending", Revision: revision, JobID: int64(task.JobID)} |
| + a := runnerAssignment{Brief: string(frozenRaw), ProtocolVersion: runnerproto.DirectVersion, ID: fmt.Sprintf("%020d", sequence), TaskID: task.ID, StepKey: key, WorkspaceKey: rand.Text(), TeamID: task.TeamID, RunnerID: sel.RunnerID, Person: task.Requester, Selection: string(raw), Isolation: string(iso), Kind: kind, State: "pending", Revision: revision, JobID: int64(task.JobID)} |
| if err := tx.Create(&a).Error; err != nil { |
| return storeError(err) |
| } |
| @@ -522,11 +561,19 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| 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 { |
| + _, resolved, err := e.store.stepAt(tx, task, a.StepKey) |
| + if err != nil { |
| + return err |
| + } |
| + specialist := executionSpecialist(resolved) |
| + if resolved.Action == "publish" { |
| + specialist = "review" |
| + } |
| + if _, err := specialistAt(tx, specialist); err != nil { |
| return err |
| } |
| // Only live Engineering preparations occupy an Engineering slot. |
| - if specialistFor(a.StepKey) == "engineering" { |
| + if specialist == "engineering" { |
| var preparing, running int64 |
| if err := tx.Model(&runnerAssignment{}).Where("team_id=? AND kind='prepare' AND state IN ('claimed','prepared') AND lease_deadline>?", task.TeamID, e.store.runnerClock.Now().UTC()).Count(&preparing).Error; err != nil { |
| return storeError(err) |
| @@ -548,14 +595,18 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| return storeError(err) |
| } |
| var sp Specialist |
| - if err := tx.First(&sp, "key=?", specialistFor(a.StepKey)).Error; err != nil { |
| + if err := tx.First(&sp, "key=?", specialist).Error; err != nil { |
| return storeError(err) |
| } |
| policy, err := bugPolicy(tx, task) |
| if err != nil { |
| 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{}} |
| + budget, err := bugBudget(tx, task.TeamID, task.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + brief := RunnerBrief{ProjectRevision: project.Revision, BudgetRevision: budget.Revision, Step: runnerproto.StepBrief{PlanRevision: task.PlanRevision, StepKey: a.StepKey, Action: resolved.Action, SpecialistKey: executionSpecialist(resolved), SpecialistRevision: sp.Revision}, 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 |
| @@ -568,6 +619,18 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| } |
| } |
| } |
| + if !taskplan.Publication(plan.Kind) { |
| + source, ref, err := projectSourceAt(tx, task.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(source) |
| + if err != nil { |
| + return err |
| + } |
| + brief.Sources = []runnerproto.SourceSnapshot{{Ref: ref, Payload: raw}} |
| + } |
| + |
| if task.CheckDefinitionHash != "" { |
| var out taskOutbox |
| if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil { |
| @@ -578,6 +641,10 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| return ErrUnavailable |
| } |
| brief.CheckDefinition = prepared.CheckDefinition |
| + var definition runnerproto.CheckDefinition |
| + if json.Unmarshal(prepared.CheckDefinition, &definition) == nil { |
| + brief.RenderRecipe = definition.Render |
| + } |
| brief.ArtifactHashes = append(brief.ArtifactHashes, task.CheckDefinitionHash) |
| } |
| deadline := e.store.runnerClock.Now().UTC().Add(60 * time.Second) |
| @@ -617,6 +684,7 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| brief.ArtifactHashes = append(brief.ArtifactHashes, art.Hash) |
| } |
| } |
| + brief.Step.ArtifactHashes = append([]string(nil), brief.ArtifactHashes...) |
| runner, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()) |
| if err != nil { |
| return err |
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go| index aec91edd..bd44d076 100644 |
| --- a/internal/equipo/runner_mutations.go |
| +++ b/internal/equipo/runner_mutations.go |
| @@ -66,6 +66,28 @@ func (e *Execution) Mutate(ctx context.Context, p RunnerPrincipal, op string, q |
| return err |
| } |
| } |
| + if (op == "complete" || (op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleAnswer)) && a.Kind == "step" { |
| + var state string |
| + if err = tx.Raw("SELECT state FROM attempts WHERE id=? AND fence=?", q.Handle.Attempt, q.Handle.Fence).Row().Scan(&state); err != nil { |
| + return err |
| + } |
| + if state == "succeeded" { |
| + var task Task |
| + if err = tx.First(&task, "id=?", a.TaskID).Error; err != nil { |
| + return err |
| + } |
| + if task.Kind == "recommendation" || task.Kind == "investigation" { |
| + if op == "complete" { |
| + if q.Result == nil || q.Result.Outcome != team.OutcomeSuccess { |
| + return ErrConflict |
| + } |
| + return nil |
| + } |
| + result, err = e.registerArtifactOnce(ctx, tx, a, q) |
| + return err |
| + } |
| + } |
| + } |
| if !historical { |
| if err := e.Core.AdmissionAvailable(ctx); err != nil { |
| return err |
| @@ -182,11 +204,14 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen |
| return e.Core.Artifact(ctx, q.Scope, q.ArtifactID) |
| } |
| return e.Core.Artifacts(ctx, q.Scope) |
| - case "freeze": |
| + case "freeze", "freeze_feature": |
| var frozen runnerproto.FreezeRequest |
| if a.Kind != "step" || runnerproto.DecodeLimit(strings.NewReader(string(q.Prepared)), &frozen, 8192) != nil { |
| return nil, ErrInvalid |
| } |
| + if op == "freeze_feature" { |
| + return nil, e.Core.FreezeFeatureEvidence(ctx, q.Scope, q.Handle, frozen.ReproductionHash, frozen.DefinitionHash) |
| + } |
| return nil, e.Core.FreezeBugEvidence(ctx, q.Scope, q.Handle, frozen.ExpectedSymptom, frozen.DefinitionHash, frozen.ReproductionHash) |
| case "question_resolved": |
| return nil, e.resolveQuestion(ctx, tx, a, value, q) |
| @@ -329,7 +354,19 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen |
| if a.Kind != "step" || q.Artifact == nil || len(q.Artifact.Payload) > runnerproto.MaxArtifactBytes { |
| return nil, ErrInvalid |
| } |
| - return e.registerArtifactOnce(ctx, tx, a, q) |
| + art, err := e.registerArtifactOnce(ctx, tx, a, q) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if q.Artifact.Role == team.RoleAnswer { |
| + if err = e.Core.Complete(ctx, q.Scope, q.Handle, team.AttemptResult{Outcome: team.OutcomeSuccess}); err != nil { |
| + return nil, err |
| + } |
| + if err = e.deliverAnswerAt(ctx, tx, a, q); err != nil { |
| + return nil, err |
| + } |
| + } |
| + return art, nil |
| } |
| return nil, ErrInvalid |
| } |
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go| index b55e1196..e22d4658 100644 |
| --- a/internal/equipo/runner_report_validation.go |
| +++ b/internal/equipo/runner_report_validation.go |
| @@ -148,6 +148,17 @@ func (s *Store) supervisedExecutorEvidence(ctx context.Context, raw *sql.Tx, sco |
| if err != nil { |
| return team.Provenance{}, err |
| } |
| + var brief RunnerBrief |
| + if json.Unmarshal([]byte(a.Brief), &brief) != nil { |
| + return team.Provenance{}, ErrInvalid |
| + } |
| + action := brief.Step.Action |
| + if action == "" { |
| + action = a.StepKey |
| + if action == "verify" { |
| + action = "checks" |
| + } |
| + } |
| var iso team.IsolationSnapshot |
| switch spec.Role { |
| case team.RoleBaseResult, team.RoleCandidateResult: |
| @@ -156,7 +167,7 @@ func (s *Store) supervisedExecutorEvidence(ctx context.Context, raw *sql.Tx, sco |
| return team.Provenance{}, ErrInvalid |
| } |
| iso = r.Isolation |
| - if (spec.Role == team.RoleBaseResult && a.StepKey != "reproduce" && a.StepKey != "scope") || (spec.Role == team.RoleCandidateResult && a.StepKey != "verify") { |
| + if (spec.Role == team.RoleBaseResult && action != "reproduce" && action != "scope") || (spec.Role == team.RoleCandidateResult && action != "checks") { |
| return team.Provenance{}, ErrForbidden |
| } |
| case team.RoleRender: |
| @@ -169,7 +180,15 @@ func (s *Store) supervisedExecutorEvidence(ctx context.Context, raw *sql.Tx, sco |
| if err := tx.Raw("SELECT capability FROM steps WHERE id=(SELECT step_id FROM attempts WHERE id=?)", h.Attempt).Scan(&capability).Error; err != nil { |
| return team.Provenance{}, err |
| } |
| - if capability != string(team.CapVerify) { |
| + if capability != string(team.CapVerify) && capability != string(team.CapImplement) { |
| + return team.Provenance{}, ErrForbidden |
| + } |
| + var brief RunnerBrief |
| + if json.Unmarshal([]byte(a.Brief), &brief) != nil || brief.RenderRecipe == nil { |
| + return team.Provenance{}, ErrForbidden |
| + } |
| + recipe, err := json.Marshal(brief.RenderRecipe) |
| + if err != nil || team.ContentDigest(recipe) != r.RecipeHash { |
| return team.Provenance{}, ErrForbidden |
| } |
| for _, hash := range []string{r.DiffHash, r.RenderHash} { |
| @@ -188,7 +207,7 @@ func (s *Store) supervisedExecutorEvidence(ctx context.Context, raw *sql.Tx, sco |
| iso = r.Isolation |
| case team.RoleRepositoryChecks: |
| var r team.RepositoryCheckResult |
| - if a.StepKey != "verify" || json.Unmarshal(spec.Payload, &r) != nil { |
| + if action != "checks" || json.Unmarshal(spec.Payload, &r) != nil { |
| return team.Provenance{}, ErrInvalid |
| } |
| iso = r.Isolation |
diff --git a/internal/equipo/runner_supervision.go b/internal/equipo/runner_supervision.go| index e933dd89..d4b8ef20 100644 |
| --- a/internal/equipo/runner_supervision.go |
| +++ b/internal/equipo/runner_supervision.go |
| @@ -23,16 +23,29 @@ func (s *Store) AttachSupervisedExecution(ctx context.Context, path string, opti |
| return e, nil |
| } |
| func (e *Execution) concludeAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, q RunnerRequest) (any, error) { |
| - if a.Kind != "step" || a.StepKey != "publish" || a.State != "contained" { |
| + if a.Kind != "step" || a.State != "contained" { |
| return nil, ErrForbidden |
| } |
| var task Task |
| if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil { |
| return nil, storeError(err) |
| } |
| - if task.State == "waiting_merge" { |
| + readWork := task.Kind == "recommendation" || task.Kind == "investigation" |
| + if !readWork && a.StepKey != "publish" { |
| + return nil, ErrForbidden |
| + } |
| + if task.State == "waiting_merge" || task.State == "waiting_checkpoint" || task.State == "answered" { |
| return nil, nil |
| } |
| + if readWork { |
| + var unfinished int64 |
| + if err := tx.Raw("SELECT count(*) FROM steps WHERE job_id=? AND state IN ('pending','running')", q.Scope.Job).Scan(&unfinished).Error; err != nil { |
| + return nil, err |
| + } |
| + if unfinished > 0 { |
| + return nil, nil |
| + } |
| + } |
| report, err := e.Core.Conclude(ctx, q.Scope, a.Person) |
| if err != nil { |
| return nil, err |
| @@ -40,6 +53,12 @@ func (e *Execution) concludeAt(ctx context.Context, tx *gorm.DB, a runnerAssignm |
| state := "failed" |
| if report.Satisfied { |
| state = "waiting_merge" |
| + if readWork { |
| + state = "answered" |
| + if task.Kind == "investigation" { |
| + state = "waiting_checkpoint" |
| + } |
| + } |
| } |
| if err = tx.Model(&Task{}).Where("id=?", a.TaskID).Select("State").Updates(&Task{State: state}).Error; err != nil { |
| return nil, storeError(err) |
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go| index c7d08bd4..fdc6c03c 100644 |
| --- a/internal/equipo/task_prepare.go |
| +++ b/internal/equipo/task_prepare.go |
| @@ -6,12 +6,9 @@ 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" |
| ) |
| @@ -71,24 +68,21 @@ func (s *Store) bugPreparationAt(tx *gorm.DB, principal RunnerPrincipal, id stri |
| if json.Unmarshal([]byte(outbox.Engineering), &eng) != nil || json.Unmarshal([]byte(outbox.Review), &rev) != nil { |
| return task, outbox, project, ErrUnavailable |
| } |
| - if eng.RunnerID != runner.ID || rev.RunnerID != runner.ID { |
| + if eng.RunnerID != runner.ID || (rev.RunnerID != "" && rev.RunnerID != runner.ID) { |
| return task, outbox, project, ErrForbidden |
| } |
| - currentEng, err := s.selectConnectionAt(tx, task.Requester, task.ProjectID, "engineering", "") |
| + p, err := s.planningAt(tx).Plan(task) |
| if err != nil { |
| return task, outbox, project, err |
| } |
| - currentRev, err := s.selectConnectionOnRunnerAt(tx, task.Requester, task.ProjectID, "review", eng.Family, eng.RunnerID) |
| + first, currentReview, err := s.planPair(tx, task, p) |
| if err != nil { |
| return task, outbox, project, err |
| } |
| - if !samePreparationSelection(eng, currentEng) || !samePreparationSelection(rev, currentRev) { |
| + if !samePreparationSelection(eng, first) || !samePreparationSelection(rev, currentReview) { |
| return task, outbox, project, ErrConflict |
| } |
| - if err := subscriptionSelection(tx, currentEng); err != nil { |
| - return task, outbox, project, err |
| - } |
| - if err := subscriptionSelection(tx, currentRev); err != nil { |
| + if err = subscriptionSelection(tx, eng); err != nil { |
| return task, outbox, project, err |
| } |
| return task, outbox, project, nil |
| @@ -138,7 +132,11 @@ func (s *Store) PrepareBug(ctx context.Context, principal RunnerPrincipal, taskI |
| if err != nil { |
| return err |
| } |
| - spec, err := BugJobSpec(task, project, policy, task.Description) |
| + p, err := s.planningAt(tx).Plan(task) |
| + if err != nil { |
| + return err |
| + } |
| + spec, err := PlanJobSpec(task, project, p, policy) |
| if err != nil { |
| return err |
| } |
| @@ -175,7 +173,7 @@ func (s *Store) StartBug(ctx context.Context, principal RunnerPrincipal, 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) |
| + task, outbox, project, err := s.bugPreparationAt(tx, principal, taskID) |
| if err != nil { |
| return err |
| } |
| @@ -196,18 +194,14 @@ func (s *Store) StartBug(ctx context.Context, principal RunnerPrincipal, taskID |
| if err != nil { |
| return err |
| } |
| - if p.Kind != taskplan.Bug { |
| - return ErrUnavailable |
| - } |
| - var spec team.JobSpec |
| - if err = json.Unmarshal([]byte(outbox.JobSpec), &spec); err != nil { |
| + policy, err := bugPolicy(tx, task) |
| + if err != nil { |
| return err |
| } |
| - spec.Steps, err = planning.ExecutionSteps(p) |
| + spec, err := PlanJobSpec(task, project, p, policy) |
| if err != nil { |
| - return ErrUnavailable |
| + return err |
| } |
| - spec.RequestKey = task.ID + "/plan/" + strconv.FormatInt(p.Revision, 10) |
| job, err := s.execution.Core.CreateJob(ctx, spec) |
| if err != nil { |
| return err |
diff --git a/internal/equipo/task_wait.go b/internal/equipo/task_wait.go| index 1bdca047..564cc757 100644 |
| --- a/internal/equipo/task_wait.go |
| +++ b/internal/equipo/task_wait.go |
| @@ -87,7 +87,11 @@ func (s *Store) refreshPendingPair(tx *gorm.DB, task Task, out *taskOutbox) erro |
| } |
| out.ProjectRevision, out.BudgetRevision = project.Revision, budget.Revision |
| } |
| - eng, rev, err := s.bugPair(tx, task.Requester, task.ProjectID) |
| + plan, err := s.planningAt(tx).Plan(task) |
| + if err != nil { |
| + return err |
| + } |
| + eng, rev, err := s.planPair(tx, task, plan) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go| index 048a9089..8646d467 100644 |
| --- a/internal/equipo/team/model.go |
| +++ b/internal/equipo/team/model.go |
| @@ -722,7 +722,7 @@ func roleAllowed(c Capability, r Role) bool { |
| case CapReproduce: |
| return r == RoleReproduction || r == RoleBaseResult |
| case CapImplement: |
| - return r == RoleCandidate |
| + return r == RoleRender || r == RoleCandidate |
| case CapReview: |
| return r == RoleReview |
| case CapVerify: |
diff --git a/internal/plan3test/plan_workflow_test.go b/internal/plan3test/plan_workflow_test.go| new file mode 100644 |
| index 00000000..0ddd7b82 |
| --- /dev/null |
| +++ b/internal/plan3test/plan_workflow_test.go |
| @@ -0,0 +1,258 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestPlanWorkflowRecommendation(t *testing.T) { |
| + task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1} |
| + project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} |
| + p := taskplan.Plan{TaskID: task.ID, Revision: 1, ProjectID: 1, Kind: taskplan.Recommendation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}}} |
| + pol, 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.PlanJobSpec(task, project, p, pol) |
| + must(t, err) |
| + if spec.Target.Kind != team.TargetProjectRead || spec.Target.Ref != "" || spec.Evidence.Predicate != "" || len(spec.Steps) != 1 || spec.Steps[0].Capability != team.CapResearch { |
| + t.Fatalf("research gained write authority: %+v", spec) |
| + } |
| +} |
| +func TestPlanWorkflowFeature(t *testing.T) { |
| + task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1, ReviewRef: "equipo/task", BaseCommit: strings.Repeat("a", 40), CheckDefinitionHash: strings.Repeat("b", 64), BaselineTestSetHash: strings.Repeat("c", 64)} |
| + project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} |
| + p := taskplan.BugPlan(task.ID, 1) |
| + p.Kind = taskplan.Feature |
| + p.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"} |
| + pol, 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.PlanJobSpec(task, project, p, pol) |
| + must(t, err) |
| + if spec.Evidence.Predicate != team.PredicateSoftwareFeature || spec.Steps[0].Capability != team.CapScope { |
| + t.Fatalf("feature used bug plan: %+v", spec) |
| + } |
| +} |
| +func TestPlanWorkflowInvestigation(t *testing.T) { |
| + p := taskplan.Plan{ProjectID: 1, Revision: 1, Kind: taskplan.Investigation, Steps: []taskplan.Step{{Key: "research", Specialist: "product", Action: "investigate"}, {Key: "merge", Action: "person"}}} |
| + must(t, taskplan.Validate(p)) |
| + p.Steps = append(p.Steps[:1], taskplan.Step{Key: "build", Specialist: "engineering", Action: "implement"}, p.Steps[1]) |
| + if taskplan.Validate(p) == nil { |
| + t.Fatal("investigation built without a new publication plan") |
| + } |
| +} |
| + |
| +func TestPlanWorkflowRecommendationDelivery(t *testing.T) { planReadDelivery(t, false) } |
| +func TestPlanWorkflowInvestigationCheckpoint(t *testing.T) { planReadDelivery(t, true) } |
| +func planReadDelivery(t *testing.T, investigation bool) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.ProjectID) |
| + p.Kind = taskplan.Recommendation |
| + if investigation { |
| + p.Kind = taskplan.Investigation |
| + } |
| + p.Steps = []taskplan.Step{{Key: "research", Specialist: "product", Action: "recommend"}, {Key: "merge", Action: "person"}} |
| + var err error |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "read-plan", Revision: p.Revision}) |
| + must(t, err) |
| + // One personal family can research; the other account is absent. |
| + if !investigation { |
| + f.exec(t, "DELETE FROM connections WHERE id='codex'") |
| + } |
| + 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), Provenance: func(context.Context, *sql.Tx, team.Scope, team.Handle) (team.Provenance, error) { |
| + return team.Provenance{Producer: "fixture", Provider: "claude", ModelFamily: "claude", Context: "session"}, nil |
| + }}) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, x.Core.Close()) }) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + _, 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 rev int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT id,revision FROM runner_assignments WHERE task_id=? AND state='pending'", p.TaskID).Scan(&id, &rev)) |
| + principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| + c, err := x.Claim(ctx, principal, equipo.ClaimRequest{Version: 2, AssignmentID: id, Revision: rev, RequestID: "claim"}) |
| + must(t, err) |
| + if c.Brief.Step.Action != "recommend" || c.Brief.Step.PlanRevision != p.Revision || len(c.Brief.Sources) != 1 || c.Brief.Target.Ref != "" { |
| + t.Fatalf("read brief: %+v", c.Brief) |
| + } |
| + answer := team.AnswerResult{Body: "An answer from verified project material", Sources: []team.SourceRef{c.Brief.Sources[0].Ref}} |
| + raw, _ := json.Marshal(answer) |
| + q := equipo.RunnerRequest{Version: 2, AssignmentID: id, Scope: c.Scope, Handle: c.Handle, RequestID: "answer", Artifact: &team.ArtifactSpec{Role: team.RoleAnswer, MediaType: "application/json", Payload: raw}} |
| + // A failed delivery must roll back artifact registration and step completion. |
| + f.exec(t, "CREATE TRIGGER answer_failure BEFORE INSERT ON conversation_messages BEGIN SELECT RAISE(ABORT,'fixture delivery failure'); END") |
| + if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { |
| + t.Fatal("delivery failure ignored") |
| + } |
| + if f.count(t, "SELECT count(*) FROM artifacts WHERE job_id=?", c.Scope.Job) != 0 || f.count(t, "SELECT count(*) FROM attempts WHERE id=? AND state='succeeded'", c.Handle.Attempt) != 0 { |
| + t.Fatal("answer partially committed") |
| + } |
| + f.exec(t, "DROP TRIGGER answer_failure") |
| + _, err = x.Mutate(ctx, principal, "artifacts", q) |
| + must(t, err) |
| + _, err = x.Mutate(ctx, principal, "artifacts", q) |
| + must(t, err) |
| + if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='specialist'") != 1 || f.count(t, "SELECT count(*) FROM artifacts WHERE job_id=? AND role='answer'", c.Scope.Job) != 1 || f.count(t, "SELECT count(*) FROM attempts WHERE id=? AND state='succeeded'", c.Handle.Attempt) != 1 { |
| + t.Fatal("answer was not delivered once with completion") |
| + } |
| + changed := q |
| + changedArtifact := *q.Artifact |
| + changedAnswer := answer |
| + changedAnswer.Body = "a different answer" |
| + changedArtifact.Payload, _ = json.Marshal(changedAnswer) |
| + changed.Artifact = &changedArtifact |
| + if _, err = x.Mutate(ctx, principal, "artifacts", changed); err == nil { |
| + t.Fatal("changed answer replay accepted") |
| + } |
| + if investigation { |
| + must(t, x.Core.ContainUntrusted(ctx, c.Scope, c.Handle)) |
| + f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE id=?", id) |
| + conclude := q |
| + conclude.RequestID = "conclude" |
| + conclude.Artifact = nil |
| + _, err = x.Mutate(ctx, principal, "conclude", conclude) |
| + must(t, err) |
| + task, err := f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + if task.State != "waiting_checkpoint" { |
| + t.Fatal("investigation skipped human checkpoint", task.State) |
| + } |
| + beforeJob := task.JobID |
| + next := taskplan.BugPlan(p.TaskID, p.ProjectID) |
| + next.Revision = p.Revision |
| + next.Kind = taskplan.Feature |
| + next.Steps[0] = taskplan.Step{Key: "scope", Specialist: "product", Action: "scope"} |
| + next, err = f.Store.EditPlan(ctx, owner, next, equipo.Mutation{RequestID: "explicit-build-revision", Revision: p.Revision}) |
| + must(t, err) |
| + task, err = f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + if next.Revision != p.Revision+1 || task.State != "proposed" || task.JobID != 0 { |
| + t.Fatal("checkpoint did not require fresh dispatch", task) |
| + } |
| + old, err := x.Core.GetJob(ctx, team.Scope{Account: team.AccountID(f.TeamID), Job: beforeJob}) |
| + must(t, err) |
| + if old.State != team.JobSucceeded { |
| + t.Fatal("historical research changed") |
| + } |
| + return |
| + } |
| + for _, column := range []string{"project", "budget", "plan", "choice"} { |
| + var undo string |
| + switch column { |
| + case "project": |
| + f.exec(t, "UPDATE projects SET revision=revision+1 WHERE id=?", p.ProjectID) |
| + undo = "UPDATE projects SET revision=revision-1" |
| + case "budget": |
| + f.exec(t, "UPDATE budget_records SET revision=revision+1") |
| + undo = "UPDATE budget_records SET revision=revision-1" |
| + case "plan": |
| + f.exec(t, "UPDATE tasks SET plan_revision=plan_revision+1 WHERE id=?", p.TaskID) |
| + undo = "UPDATE tasks SET plan_revision=plan_revision-1" |
| + case "choice": |
| + f.exec(t, "UPDATE connection_choices SET revision=revision+1") |
| + undo = "UPDATE connection_choices SET revision=revision-1" |
| + } |
| + if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { |
| + t.Fatal("changed dispatch identity accepted", column) |
| + } |
| + f.exec(t, undo) |
| + } |
| + f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'") |
| + if _, err = x.Mutate(ctx, principal, "artifacts", q); err == nil { |
| + t.Fatal("replay ignored revoked selection") |
| + } |
| +} |
| + |
| +func TestPlanWorkflowConnectionPreference(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.ProjectID) |
| + f.exec(t, `INSERT INTO connections(id,runner_id,person,local_id,revision,last_seen,reports_json,security_hash) SELECT 'other-claude',runner_id,person,'other-local',revision,last_seen,reports_json,security_hash FROM connections WHERE id='claude'`) |
| + f.exec(t, `UPDATE connection_choices SET pinned_id='',connection_ids_json='["claude","other-claude","codex"]'`) |
| + p.Steps[0].ConnectionID = "other-claude" |
| + var err error |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "different-account", Revision: p.Revision}) |
| + must(t, err) |
| + must(t, f.Store.CheckPlanDispatch(ctx, owner, p.TaskID)) |
| + 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 raw string |
| + must(t, f.DB.Writer().QueryRow("SELECT selection FROM runner_assignments WHERE task_id=?", p.TaskID).Scan(&raw)) |
| + var selected equipo.Selection |
| + must(t, json.Unmarshal([]byte(raw), &selected)) |
| + if selected.ConnectionID != "other-claude" { |
| + t.Fatal("eligible preferred personal connection ignored", selected.ConnectionID) |
| + } |
| +} |
| + |
| +func TestPlanWorkflowRenderedSpec(t *testing.T) { |
| + task := equipo.Task{ID: "task", TeamID: "team", Requester: owner.Address, ProjectID: 1, PlanRevision: 1, ReviewRef: "equipo/task", BaseCommit: strings.Repeat("a", 40), CheckDefinitionHash: strings.Repeat("b", 64), BaselineTestSetHash: strings.Repeat("c", 64)} |
| + project := equipo.Project{ID: 1, Repository: "amadan.net/test/fixture", DefaultBranch: "main"} |
| + p := taskplan.BugPlan(task.ID, 1) |
| + p.Kind = taskplan.RenderedChange |
| + p.Steps[1].Action = "copy" |
| + pol, 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.PlanJobSpec(task, project, p, pol) |
| + must(t, err) |
| + if !spec.Evidence.RequireBugFreeze { |
| + t.Fatal("rendered reproduction cannot be frozen") |
| + } |
| +} |
| + |
| +func TestPlanWorkflowRenderedWait(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + f.planConnections(t, p.ProjectID) |
| + p.Kind = taskplan.RenderedChange |
| + p.Steps[1].Action = "copy" |
| + var err error |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "rendered", Revision: p.Revision}) |
| + must(t, err) |
| + 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)) |
| + principal := equipo.RunnerPrincipal{RunnerID: "fixture-runner", Person: owner.Address, CredentialID: "fixture-credential"} |
| + var project equipo.Project |
| + must(t, f.DB.G.First(&project, p.ProjectID).Error) |
| + task, err := f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + raw := []byte("fixture definition") |
| + task, err = f.Store.PrepareBug(ctx, principal, p.TaskID, task.Revision, equipo.PreparedBug{Repository: project.Repository, DefaultBranch: project.DefaultBranch, BaseCommit: strings.Repeat("a", 40), CheckDefinition: raw, CheckDefinitionHash: team.ContentDigest(raw), BaselineTestSetHash: strings.Repeat("b", 64)}) |
| + must(t, err) |
| + task, err = f.Store.StartBug(ctx, principal, p.TaskID, task.Revision) |
| + must(t, err) |
| + // Only the publication-readiness gate is under test; no evidence or approval is fabricated. |
| + f.exec(t, "UPDATE steps SET state='succeeded' WHERE job_id=? AND key<>'publish'", task.JobID) |
| + f.exec(t, "UPDATE runner_assignments SET state='contained' WHERE task_id=?", task.ID) |
| + must(t, x.Sync(ctx)) |
| + task, err = f.Store.Task(ctx, owner, p.TaskID) |
| + must(t, err) |
| + if task.WaitCode != "evidence.awaiting_person" || f.count(t, "SELECT count(*) FROM runner_assignments WHERE task_id=? AND step_key='publish'", task.ID) != 0 { |
| + t.Fatal("publication did not wait for evidence and rendered approval", task.WaitCode) |
| + } |
| +} |
diff --git a/internal/release/manifest.go b/internal/release/manifest.go| index 02cc4e39..ea7a33f0 100644 |
| --- a/internal/release/manifest.go |
| +++ b/internal/release/manifest.go |
| @@ -46,6 +46,7 @@ type Certification struct { |
| } |
| type Manifest struct { |
| + UncertifiedPolicies []UncertifiedPolicy `json:"uncertified_policies,omitempty"` |
| Certifications []Certification `json:"certifications"` |
| LiveGateCopyReviewed bool `json:"live_gate_copy_reviewed"` |
| Binaries []BinaryDigest `json:"binaries"` |
diff --git a/internal/release/manifest.json b/internal/release/manifest.json| index cd31623b..8c54f759 100644 |
| --- a/internal/release/manifest.json |
| +++ b/internal/release/manifest.json |
| @@ -13,5 +13,103 @@ |
| "direct_policies": [], |
| "binaries": [], |
| "certifications": [], |
| - "live_gate_copy_reviewed": false |
| + "live_gate_copy_reviewed": false, |
| + "uncertified_policies": [ |
| + { |
| + "provider": "claude", |
| + "action": "reproduce", |
| + "inventory_hash": "25c685c3f62db7ef8d98bf57e7e4fc7291d06f9460d2793909186718ef85696d", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "scope", |
| + "inventory_hash": "db2f404a1537da507a843ff26ef8480ea8798f683567730d76036bedea3f4e91", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "recommend", |
| + "inventory_hash": "191c5aaa93fc9d992a40b68edcfdc37b9726691a0c9448a336c581100ada47ee", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "investigate", |
| + "inventory_hash": "bcc3d62e5c263c9e8e9b50e1844f8e96dc986250ae1ea053c147d2a7071f2920", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "implement", |
| + "inventory_hash": "c55fb7fead4a475289e8cb7feb84b8fac99eb3199adc2aced678cce961ad72a6", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "copy", |
| + "inventory_hash": "4624e65b9b1ca8ca020812901fc0196a051bcdc10a4ebee8fc7b8179482bab60", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "design", |
| + "inventory_hash": "d57b4129489fc93a51e36bacab34ec9d546098286a4f42e06459356d188a9e6f", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "claude", |
| + "action": "review", |
| + "inventory_hash": "6922d38617021c33af508bd42359a249a6276b1d8e296eaabd36e996870491ac", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "reproduce", |
| + "inventory_hash": "9ad48e21d06da65c0524e8190c6044da832cea0b0ea39233ee2a3f70f265f14f", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "scope", |
| + "inventory_hash": "0262b66b483af25860f011d5407b0cac6c737356878588810c45ae7993343e41", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "recommend", |
| + "inventory_hash": "4b441104c0b5ec0aa61a7726fea98e03a3748e9b0f5afb482702705d0d61a147", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "investigate", |
| + "inventory_hash": "b6bad7cec308d33257cd759a62d9481de0728e446b6fd71456f5336c9e7e7ad0", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "implement", |
| + "inventory_hash": "ef9bb6d923da032d8c5966161c1062645d1f0dba4a6638d9f2f7a010e91d62b2", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "copy", |
| + "inventory_hash": "ec9cf6a11839742f3bf8e79a005a8f8c09c1a2460559f95b27ced0b0176d501b", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "design", |
| + "inventory_hash": "fe600fac8a1b54e69107114e224165e926923b5b19f3bec7199484b6950e7c82", |
| + "status": "uncertified" |
| + }, |
| + { |
| + "provider": "codex", |
| + "action": "review", |
| + "inventory_hash": "89def32bc61ed02bc26dcba811c6d14e556932ec5570dfcd6b54dcf23f79446b", |
| + "status": "uncertified" |
| + } |
| + ] |
| } |
diff --git a/internal/release/manifest_test.go b/internal/release/manifest_test.go| index bf303ea3..e2ea15e6 100644 |
| --- a/internal/release/manifest_test.go |
| +++ b/internal/release/manifest_test.go |
| @@ -59,3 +59,43 @@ func TestToolProxyDigestPinned(t *testing.T) { |
| t.Fatal("changed tool proxy accepted") |
| } |
| } |
| + |
| +func TestPlanWorkflowReleasePolicyInventory(t *testing.T) { |
| + m := BuildManifest() |
| + for _, name := range []string{"claude", "codex"} { |
| + for _, action := range []string{"reproduce", "scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + hash, err := ActionInventoryHash(name, action) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + found := false |
| + for _, p := range m.UncertifiedPolicies { |
| + if p.Provider == name && p.Action == action && p.InventoryHash == hash && p.Status == "uncertified" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Errorf("pending %s %s %s", name, action, hash) |
| + } |
| + version := map[string]string{"claude": m.Claude, "codex": m.Codex}[name] |
| + if m.ActionCertified(name, action, version, hash) { |
| + t.Fatal("uncertified profile eligible") |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestPlanWorkflowReleaseRejectsOldCertificate(t *testing.T) { |
| + m := BuildManifest() |
| + for _, p := range m.UncertifiedPolicies { |
| + version := map[string]string{"claude": m.Claude, "codex": m.Codex}[p.Provider] |
| + m.DirectPolicies = []PolicyCertificate{{Provider: p.Provider, ProviderVersion: version, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyHash: p.InventoryHash, CertifiedRefresh: CertifiedRefresh{AuthHost: "auth.example.test", EvidenceSHA256: p.InventoryHash}}} |
| + m.Certifications = []Certification{{Provider: p.Provider, PolicyHash: p.InventoryHash, SHA256: p.InventoryHash, Path: "fixture"}} |
| + if m.CertifiedAuthHost(p.Provider, version, p.InventoryHash) == "" { |
| + t.Fatal("invalid synthetic old certificate fixture") |
| + } |
| + if m.ActionCertified(p.Provider, p.Action, version, p.InventoryHash) { |
| + t.Fatal("old certificate enabled changed inventory", p.Action) |
| + } |
| + } |
| +} |
diff --git a/internal/release/policy_inventory.go b/internal/release/policy_inventory.go| new file mode 100644 |
| index 00000000..f0d20cb1 |
| --- /dev/null |
| +++ b/internal/release/policy_inventory.go |
| @@ -0,0 +1,54 @@ |
| +package release |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| + "amadan.net/oficina/equipo/internal/runner/provider/codex" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| +) |
| + |
| +// UncertifiedPolicy records a portable constructor inventory, not live evidence. |
| +// Account paths, executable digests and live observations still require the |
| +// separate, exact DirectPolicies certificate before execution. |
| +type UncertifiedPolicy struct { |
| + Provider string `json:"provider"` |
| + Action string `json:"action"` |
| + InventoryHash string `json:"inventory_hash"` |
| + Status string `json:"status"` |
| +} |
| + |
| +func ActionInventoryHash(name, action string) (string, error) { |
| + profile, err := provider.Profile(action) |
| + if err != nil { |
| + return "", err |
| + } |
| + b := provider.Binding{Provider: name, CredentialHome: "/equipo/credential", Home: "/equipo/runtime/home", RuntimeRoot: "/equipo/runtime"} |
| + in := provider.PolicyInputs{Action: action, Tools: profile.MCPTools(), LauncherVersion: "direct-v2", BwrapVersion: "0.11.0", Workspace: "/workspace", Scratch: "/scratch"} |
| + switch name { |
| + case "claude": |
| + in, err = claude.PolicyInputs(b, in, profile.Specialist, "model") |
| + case "codex": |
| + in, err = codex.PolicyInputs(b, in, "model") |
| + default: |
| + return "", provider.ErrPolicy |
| + } |
| + if err != nil { |
| + return "", err |
| + } |
| + raw, err := json.Marshal(in) |
| + if err != nil { |
| + return "", err |
| + } |
| + hash := sha256.Sum256(raw) |
| + return hex.EncodeToString(hash[:]), nil |
| +} |
| +func (m Manifest) ActionCertified(name, action, version, hash string) bool { |
| + for _, p := range m.UncertifiedPolicies { |
| + if p.Provider == name && p.Action == action { |
| + return false |
| + } |
| + } |
| + return m.CertifiedAuthHost(name, version, hash) != "" |
| +} |
diff --git a/internal/runner/certification_inputs.go b/internal/runner/certification_inputs.go| index 01a6fe2b..9da493f2 100644 |
| --- a/internal/runner/certification_inputs.go |
| +++ b/internal/runner/certification_inputs.go |
| @@ -41,17 +41,13 @@ func CertificationInputs(ctx context.Context, c Config, s provider.Selection, bi |
| if s.Provider == "codex" { |
| runtimeFiles = append(runtimeFiles, provider.Mount{Source: r.cfg.CodexCodeModeHostPath, Target: "/opt/codex-code-mode-host", ReadOnly: true}) |
| } |
| - tool := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[step] |
| - if tool == "" { |
| - return provider.PolicyInputs{}, provider.ErrPolicy |
| + profile, err := provider.Profile(step) |
| + if err != nil { |
| + return provider.PolicyInputs{}, err |
| } |
| - in := provider.PolicyInputs{Workspace: work, Scratch: policyScratch, RuntimeFiles: runtimeFiles, DeniedPaths: denies.DeniedPaths, EgressHosts: network.Hosts, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", Tools: []string{"mcp__equipo__" + tool, "mcp__equipo__ask_person"}} |
| + in := provider.PolicyInputs{Action: step, Workspace: work, Scratch: policyScratch, RuntimeFiles: runtimeFiles, DeniedPaths: denies.DeniedPaths, EgressHosts: network.Hosts, LauncherVersion: directLauncherVersion(), BwrapVersion: "0.11.0", Tools: profile.MCPTools()} |
| if s.Provider == "claude" { |
| - specialist := "Engineering" |
| - if step == "review" { |
| - specialist = "Review" |
| - } |
| - in, err = claude.PolicyInputs(binding, in, specialist, s.Model) |
| + in, err = claude.PolicyInputs(binding, in, profile.Specialist, s.Model) |
| } else { |
| in, err = codex.PolicyInputs(binding, in, s.Model) |
| } |
diff --git a/internal/runner/certified/policy.go b/internal/runner/certified/policy.go| index e160d6e8..f813eeb7 100644 |
| --- a/internal/runner/certified/policy.go |
| +++ b/internal/runner/certified/policy.go |
| @@ -34,6 +34,9 @@ func BuildPolicy(b provider.Binding, in provider.PolicyInputs, m release.Manifes |
| if c.Provider != b.Provider || c.ProviderVersion != b.Expected.ProviderVersion { |
| continue |
| } |
| + if in.Action != "" && !m.ActionCertified(c.Provider, in.Action, c.ProviderVersion, c.PolicyHash) { |
| + continue |
| + } |
| host := m.CertifiedAuthHost(c.Provider, c.ProviderVersion, c.PolicyHash) |
| if host == "" { |
| continue |
diff --git a/internal/runner/checks/definition.go b/internal/runner/checks/definition.go| index 266ef073..2ecc603b 100644 |
| --- a/internal/runner/checks/definition.go |
| +++ b/internal/runner/checks/definition.go |
| @@ -90,6 +90,9 @@ func ParseDefinition(ctx context.Context, b []byte, repo, base string) (Definiti |
| if d.Version != 1 || repo == "" || d.Repository != repo || d.Base != base || !objectID(base) || len(d.Commands) == 0 || !commandValid(d.Reproduction, true) { |
| return d, provider.ErrContract |
| } |
| + if d.Render != nil && (d.Render.Version != 1 || d.Render.Command.Parser != "exit" || !commandValid(d.Render.Command, false) || !exitMaterialDeclared(d, d.Render.Command)) { |
| + return d, provider.ErrContract |
| + } |
| measured := false |
| for _, c := range d.Commands { |
| if !commandValid(c, false) || !exitMaterialDeclared(d, c) { |
diff --git a/internal/runner/checks/render.go b/internal/runner/checks/render.go| index cce732c1..3c6d65d6 100644 |
| --- a/internal/runner/checks/render.go |
| +++ b/internal/runner/checks/render.go |
| @@ -144,6 +144,18 @@ func renderDiff(base, work string) ([]byte, error) { |
| return raw, nil |
| } |
| func (e *Executor) Render(ctx context.Context, recipe runnerproto.RenderRecipe, candidateHash string) (team.RenderResult, error) { |
| + return e.render(ctx, recipe, candidateHash, nil) |
| +} |
| +func (e *Executor) RenderDefinition(ctx context.Context, d Definition, hash string) (team.RenderResult, error) { |
| + if d.Render == nil { |
| + return team.RenderResult{}, provider.ErrIdentity |
| + } |
| + if err := e.definition(ctx, d, true); err != nil { |
| + return team.RenderResult{}, err |
| + } |
| + return e.render(ctx, *d.Render, hash, &d) |
| +} |
| +func (e *Executor) render(ctx context.Context, recipe runnerproto.RenderRecipe, candidateHash string, d *Definition) (team.RenderResult, error) { |
| var result team.RenderResult |
| if recipe.Version != 1 || !commandValid(recipe.Command, false) || recipe.Command.Parser != "exit" || !hexID(e.cfg.RenderRecipeHash, 64) || Digest(encode(recipe)) != e.cfg.RenderRecipeHash { |
| return result, provider.ErrIdentity |
| @@ -166,6 +178,11 @@ func (e *Executor) Render(ctx context.Context, recipe runnerproto.RenderRecipe, |
| if err != nil { |
| return result, err |
| } |
| + if d != nil { |
| + if err = e.material(*d, work); err != nil { |
| + return result, err |
| + } |
| + } |
| if err = safeDir(work, recipe.Command.Dir); err != nil { |
| return result, err |
| } |
diff --git a/internal/runner/checks/render_test.go b/internal/runner/checks/render_test.go| index 0dd8d7be..4f455589 100644 |
| --- a/internal/runner/checks/render_test.go |
| +++ b/internal/runner/checks/render_test.go |
| @@ -55,3 +55,33 @@ func TestRenderedChangeExecutor(t *testing.T) { |
| t.Fatal("unpinned render recipe accepted") |
| } |
| } |
| + |
| +type frozenRenderSandbox struct{ t *testing.T } |
| + |
| +func (s frozenRenderSandbox) Run(ctx context.Context, c Command, w string, p provider.ReadPolicy, out, errout io.Writer) (int, error) { |
| + raw, err := os.ReadFile(filepath.Join(w, "render.sh")) |
| + must(s.t, err) |
| + if string(raw) != "trusted renderer" { |
| + s.t.Fatal("candidate replaced the trusted renderer") |
| + } |
| + return renderSandbox{s.t}.Run(ctx, c, w, p, out, errout) |
| +} |
| +func TestPlanWorkflowRenderDefinition(t *testing.T) { |
| + f := newFixture(t) |
| + put(t, f.base, "render.sh", "trusted renderer") |
| + put(t, f.candidate, "render.sh", "candidate-controlled renderer") |
| + f.d.TrustedPaths = []string{"render.sh"} |
| + f.d.Render = &runnerproto.RenderRecipe{Version: 1, Command: Command{Argv: []string{"sh", "render.sh"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}} |
| + var err error |
| + f.d, err = FreezeMaterial(context.Background(), f.d, f.base) |
| + must(t, err) |
| + f.e.cfg.DefinitionHash = Digest(raw(f.d)) |
| + f.e.cfg.RenderRecipeHash = Digest(raw(f.d.Render)) |
| + f.e.sandbox = frozenRenderSandbox{t} |
| + _, err = f.e.RenderDefinition(context.Background(), f.d, f.hash) |
| + must(t, err) |
| + f.d.Render.Command.Argv = []string{"sh", "other.sh"} |
| + if _, err = f.e.RenderDefinition(context.Background(), f.d, f.hash); err == nil { |
| + t.Fatal("changed render definition accepted") |
| + } |
| +} |
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go| index 6f8169bc..d799bf98 100644 |
| --- a/internal/runner/containment/mounts.go |
| +++ b/internal/runner/containment/mounts.go |
| @@ -111,7 +111,7 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error |
| } |
| p.args = append(p.args, "--overlay-src", "/etc", "--tmp-overlay", "/etc") |
| p.args = append(p.args, "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--dir", "/run", "--dir", "/sys", "--dir", "/home/runner", "--tmpfs", "/etc/claude-code", "--tmpfs", "/etc/codex") |
| - if err = p.bind(l.Workspace, "/workspace", false, true); err != nil { |
| + if err = p.bind(l.Workspace, "/workspace", l.Policy.ReadOnlyWorkspace(), true); err != nil { |
| return nil, err |
| } |
| runtimeHome := filepath.Join(dir, "home") |
diff --git a/internal/runner/direct_cli_test.go b/internal/runner/direct_cli_test.go| index f57918e1..e3762da1 100644 |
| --- a/internal/runner/direct_cli_test.go |
| +++ b/internal/runner/direct_cli_test.go |
| @@ -58,7 +58,7 @@ func fakeDirectGraph(t *testing.T, j *Journal, host provider.ProcessHost, root, |
| if err != nil { |
| return provider.Launch{}, lease.Close, err |
| } |
| - policy, err := provider.BuildPolicy(binding, provider.PolicyInputs{Workspace: ws.Path, Scratch: policyScratch, ProviderVersion: id.ProviderVersion, LauncherVersion: "fixture", BwrapVersion: "0.11.0", Argv: []string{"/opt/fake-cli", name}, RuntimeFiles: []provider.Mount{{Source: binary, Target: "/opt/fake-cli", ReadOnly: true}, {Source: helper, Target: "/opt/helper", ReadOnly: true}, {Source: "/usr/bin/bwrap", Target: "/opt/bwrap", ReadOnly: true}}, EgressHosts: network.Hosts}) |
| + policy, err := provider.BuildPolicy(binding, provider.PolicyInputs{Action: c.Brief.Step.Action, Workspace: ws.Path, Scratch: policyScratch, ProviderVersion: id.ProviderVersion, LauncherVersion: "fixture", BwrapVersion: "0.11.0", Argv: []string{"/opt/fake-cli", name}, RuntimeFiles: []provider.Mount{{Source: binary, Target: "/opt/fake-cli", ReadOnly: true}, {Source: helper, Target: "/opt/helper", ReadOnly: true}, {Source: "/usr/bin/bwrap", Target: "/opt/bwrap", ReadOnly: true}}, EgressHosts: network.Hosts}) |
| if err != nil { |
| return provider.Launch{}, lease.Close, err |
| } |
| @@ -170,13 +170,17 @@ def git(*args): |
| for line in sys.stdin: |
| v=json.loads(line) |
| message=json.loads(v['message']['content'] if sys.argv[1]=='claude' else v['params']['input'][0]['text']) |
| - step=message['Step'] |
| - if step=='reproduce': |
| + step=message.get('Action') or message['Step'] |
| + if step in ['reproduce','scope']: |
| print(json.dumps({'tool':'ask_person','arguments':{'question':'Which case?'}}),flush=True) |
| - tool='submit_reproduction' |
| + tool='submit_acceptance' if step=='scope' else 'submit_reproduction' |
| args={'expected_symptom':'wrong value','files':[{'path':'bug_test.go','bytes':base64.b64encode(b'package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').decode()}],'test_names':[{'package':'fixture','name':'TestBug'}]} |
| - elif step=='implement': |
| - open('value.go','w').write('package fixture\nfunc Value() int {return 2}\n') |
| + elif step=='recommend': |
| + assert not os.path.exists('.git') |
| + tool='submit_answer';args={'body':'recommendation','sources':[message['sources'][0]['ref']]} |
| + elif step in ['implement','copy','design']: |
| + if step=='implement': open('value.go','w').write('package fixture\nfunc Value() int {return 2}\n') |
| + else: open(step+'.txt','w').write(step+' captured artifact') |
| git('add','.') |
| git('commit','-m','fix') |
| tool='submit_candidate';args={'commit':git('rev-parse','HEAD')} |
| @@ -184,5 +188,6 @@ for line in sys.stdin: |
| tool='submit_review';args={'candidate':message['candidate_commit'],'decision':'approve','findings':[]} |
| for i in range(200): print(json.dumps({'progress':i}),flush=True) |
| print(json.dumps({'tool':tool,'arguments':args}),flush=True) |
| + if tool=='submit_candidate' and message.get('render_available'): print(json.dumps({'tool':'submit_render','arguments':args}),flush=True) |
| print(json.dumps({'final':True,'usage':{'input_tokens':2,'output_tokens':3}}),flush=True) |
| ` |
diff --git a/internal/runner/direct_graph_test.go b/internal/runner/direct_graph_test.go| index 0844bfb5..ca8483a9 100644 |
| --- a/internal/runner/direct_graph_test.go |
| +++ b/internal/runner/direct_graph_test.go |
| @@ -22,7 +22,11 @@ import ( |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| -func runDirectBugGraph(t *testing.T) { |
| +func runDirectBugGraph(t *testing.T) { runDirectPlanGraph(t, false, false, false) } |
| +func TestPlanWorkflowFeature(t *testing.T) { runDirectPlanGraph(t, true, false, false) } |
| +func TestPlanWorkflowCandidateOrder(t *testing.T) { runDirectPlanGraph(t, true, true, false) } |
| +func TestPlanWorkflowRecommendation(t *testing.T) { runDirectPlanGraph(t, false, false, true) } |
| +func runDirectPlanGraph(t *testing.T, feature, extra, readWork bool) { |
| ctx := context.Background() |
| root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-") |
| wfMust(t, err) |
| @@ -54,7 +58,13 @@ func runDirectBugGraph(t *testing.T) { |
| wfMust(t, os.WriteFile(filepath.Join(seed, "old_test.go"), []byte("package fixture\nimport \"testing\"\nfunc TestOld(t *testing.T) {}\n"), 0600)) |
| cmd := runnerproto.CheckCommand{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 120} |
| wfMust(t, os.Mkdir(filepath.Join(seed, ".equipo"), 0700)) |
| - wfMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), marshal(checks.Definition{Version: 1, Commands: []checks.Command{cmd}, Reproduction: cmd}), 0600)) |
| + definition := checks.Definition{Version: 1, Commands: []checks.Command{cmd}, Reproduction: cmd} |
| + if extra { |
| + definition.Render = &runnerproto.RenderRecipe{Version: 1, Command: checks.Command{Argv: []string{"sh", "render.sh"}, Dir: ".", Parser: "exit", TimeoutSeconds: 10}} |
| + definition.TrustedPaths = []string{"render.sh"} |
| + wfMust(t, os.WriteFile(filepath.Join(seed, "render.sh"), []byte("printf '%s' 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLttAAAAABJRU5ErkJggg==' | base64 -d\n"), 0600)) |
| + } |
| + wfMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), marshal(definition), 0600)) |
| wfGit(t, seed, "init", "-b", "main") |
| wfGit(t, seed, "add", ".") |
| wfGit(t, seed, "commit", "-m", "base") |
| @@ -77,11 +87,17 @@ func runDirectBugGraph(t *testing.T) { |
| var manager *workspace.Manager |
| var pinned checks.Definition |
| var repo string |
| + executorCalls := 0 |
| executor := func(ctx context.Context, c RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) { |
| + executorCalls++ |
| if c.Handle.Attempt > 0 && !deadline.Equal(c.AttemptDeadline) { |
| return nil, fmt.Errorf("executor got lease snapshot instead of attempt deadline") |
| } |
| - return checks.New(checks.Config{ScratchRoot: works, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(r)), Reproduction: func(context.Context, string) (checks.Reproduction, error) { return r, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return c.Brief.Selection.Isolation, nil }, ResolveCandidate: func(ctx context.Context, hash string) (team.GitCandidate, error) { |
| + recipeHash := "" |
| + if d.Render != nil { |
| + recipeHash = checks.Digest(marshal(d.Render)) |
| + } |
| + return checks.New(checks.Config{RenderRecipeHash: recipeHash, ScratchRoot: works, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(r)), Reproduction: func(context.Context, string) (checks.Reproduction, error) { return r, nil }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return c.Brief.Selection.Isolation, nil }, ResolveCandidate: func(ctx context.Context, hash string) (team.GitCandidate, error) { |
| arts, err := apiArtifacts(ctx, w, c) |
| if err != nil { |
| return team.GitCandidate{}, err |
| @@ -133,13 +149,22 @@ func runDirectBugGraph(t *testing.T) { |
| return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil |
| }}) |
| wfMust(t, err) |
| - prepared, err := manager.Prepare(ctx, target) |
| - wfMust(t, err) |
| + var prepared runnerproto.PreparedBug |
| + if !readWork { |
| + prepared, err = manager.Prepare(ctx, target) |
| + wfMust(t, err) |
| + } |
| + source := runnerproto.SourceSnapshot{Ref: team.SourceRef{Kind: "project", ID: "1", Revision: 1, Hash: team.ContentDigest([]byte(`{"name":"fixture"}`))}, Payload: json.RawMessage(`{"name":"fixture"}`)} |
| clock := team.RealClock{} |
| auth := team.NewFakeAuthority(clock, 5*time.Second) |
| auth.Issue("grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpProviderCall: true, team.OpForgePublish: true, team.OpJobContinue: true, team.OpAttemptContinue: true}}) |
| api := &directCoreAPI{coreWorkflowAPI: &coreWorkflowAPI{t: t, w: w, assignments: map[string]runnerproto.Assignment{}}} |
| - core, err := team.Open(ctx, filepath.Join(state, "core.db"), team.Options{Clock: clock, Authority: auth, ExecutorEvidence: w.ExecutorEvidence, Provenance: func(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) { |
| + core, err := team.Open(ctx, filepath.Join(state, "core.db"), team.Options{Clock: clock, Authority: auth, RenderedApproval: func(context.Context, *sql.Tx, team.ProjectID, team.RenderedApproval) error { return nil }, SourceReference: func(_ context.Context, _ *sql.Tx, _ team.Scope, ref team.SourceRef) error { |
| + if ref != source.Ref { |
| + return team.ErrEvidence |
| + } |
| + return nil |
| + }, ExecutorEvidence: w.ExecutorEvidence, Provenance: func(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) { |
| p, err := w.Provenance(ctx, tx, scope, h) |
| if err == nil { |
| for _, a := range api.assignments { |
| @@ -159,7 +184,27 @@ func runDirectBugGraph(t *testing.T) { |
| limits := team.Limits{Calls: 24, InputTokens: 200000, OutputTokens: 40000} |
| pol, err := team.RunnerPolicy("subscription", limits, team.Limits{Calls: 1, InputTokens: 32000, OutputTokens: 4000}, team.Rates{}) |
| wfMust(t, err) |
| - job, err := core.CreateJob(ctx, team.JobSpec{Account: "team", Requester: "person", GrantRef: "grant", Target: target, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true}, Policy: pol, Steps: []team.StepSpec{{Key: "reproduce", Version: 1, Capability: team.CapReproduce}, {Key: "implement", Version: 1, Capability: team.CapImplement, DependsOn: []string{"reproduce"}}, {Key: "review", Version: 1, Capability: team.CapReview, DependsOn: []string{"implement"}}, {Key: "verify", Version: 1, Capability: team.CapVerify, DependsOn: []string{"review"}}, {Key: "publish", Version: 1, Capability: team.CapPublish, DependsOn: []string{"verify"}}}}) |
| + spec := team.JobSpec{Account: "team", Requester: "person", GrantRef: "grant", Target: target, Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true}, Policy: pol, Steps: []team.StepSpec{{Key: "reproduce", Version: 1, Capability: team.CapReproduce}, {Key: "implement", Version: 1, Capability: team.CapImplement, DependsOn: []string{"reproduce"}}, {Key: "review", Version: 1, Capability: team.CapReview, DependsOn: []string{"implement"}}, {Key: "verify", Version: 1, Capability: team.CapVerify, DependsOn: []string{"review"}}, {Key: "publish", Version: 1, Capability: team.CapPublish, DependsOn: []string{"verify"}}}} |
| + if feature { |
| + spec.Evidence = team.EvidenceRequirement{Predicate: team.PredicateSoftwareFeature, CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash} |
| + spec.Steps[0].Key = "scope" |
| + spec.Steps[0].Capability = team.CapScope |
| + spec.Steps[1].DependsOn = []string{"scope"} |
| + } |
| + if extra { |
| + spec.Evidence = team.EvidenceRequirement{Predicate: team.PredicateRenderedChange, ExpectedSymptom: "wrong value", CheckDefinitionHash: prepared.CheckDefinitionHash, BaselineTestSetHash: prepared.BaselineTestSetHash, RequireBugFreeze: true, RequiredDecisions: []string{"copy", "design"}} |
| + spec.Steps[0].Key = "reproduce" |
| + spec.Steps[0].Capability = team.CapReproduce |
| + spec.Steps = append(spec.Steps[:1], append([]team.StepSpec{{Key: "words", Version: 1, Capability: team.CapImplement, DependsOn: []string{"reproduce"}}, {Key: "layout", Version: 1, Capability: team.CapImplement, DependsOn: []string{"words"}}}, spec.Steps[1:]...)...) |
| + spec.Steps[3].DependsOn = []string{"layout"} |
| + } |
| + if readWork { |
| + target = team.TargetBinding{Kind: team.TargetProjectRead, Repository: "amadan.net/test/fixture", BaseRevision: "project/1"} |
| + spec.Target = target |
| + spec.Evidence = team.EvidenceRequirement{} |
| + spec.Steps = []team.StepSpec{{Key: "research", Version: 1, Capability: team.CapResearch}} |
| + } |
| + job, err := core.CreateJob(ctx, spec) |
| wfMust(t, err) |
| scope := team.Scope{Account: job.Account, Job: job.ID} |
| @@ -169,13 +214,27 @@ func runDirectBugGraph(t *testing.T) { |
| wfMust(t, os.WriteFile(gitSpy, []byte("#!/bin/bash\nargs=()\nfor arg in \"$@\"; do\n if [[ \"$arg\" == https://amadan.net/test/fixture ]]; then args+=("+fmt.Sprintf("%q", remote)+"); else args+=(\"$arg\"); fi\ndone\nexec /usr/bin/git -c protocol.file.allow=always \"${args[@]}\"\n"), 0700)) |
| status, err := core.Status(ctx) |
| wfMust(t, err) |
| - publisher, err := forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: "runner", Incarnation: status.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error { |
| - return core.ValidateHandle(ctx, a.Ticket.Scope, a.Ticket.Handle) |
| - }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) { |
| - return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only"}, nil |
| - }, Description: &workflowDescription{}}) |
| - wfMust(t, err) |
| - workflow, err := NewBugWorkflow(BugWorkflowConfig{Publisher: publisher, Workspaces: manager, Launchers: registry, Namespaces: namespaces, Launch: launch, Witness: w, Policy: func(context.Context, provider.Selection) (provider.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "instance", Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}}) |
| + var publisher *forge.Publisher |
| + if !readWork { |
| + publisher, err = forge.New(forge.Config{Root: pubroot, GitPath: gitSpy, Runner: "runner", Incarnation: status.Incarnation, Clock: time.Now, Authorize: w.PublicationAuthorization, Revalidate: func(ctx context.Context, a forge.Authorization) error { |
| + return core.ValidateHandle(ctx, a.Ticket.Scope, a.Ticket.Handle) |
| + }, Export: manager.ExportCandidate, Credential: func(context.Context, string) (forge.Credential, error) { |
| + return forge.Credential{Remote: "https://amadan.net/test/fixture", Agent: "test~person@example.test", Bearer: "fixture-only"}, nil |
| + }, Description: &workflowDescription{}}) |
| + wfMust(t, err) |
| + } |
| + workflow, err := NewPlanWorkflow(BugWorkflowConfig{UploadBlob: func(_ context.Context, _ RunClaim, hash string, raw []byte) error { |
| + if team.ContentDigest(raw) != hash { |
| + return provider.ErrIdentity |
| + } |
| + return nil |
| + }, Publisher: publisher, PublisherFor: func(context.Context, runnerproto.PublicationAuthorization) (*forge.Publisher, error) { |
| + if !readWork { |
| + return publisher, nil |
| + } |
| + t.Fatal("research invoked publisher") |
| + return nil, provider.ErrPolicy |
| + }, Workspaces: manager, Launchers: registry, Namespaces: namespaces, Launch: launch, Witness: w, Policy: func(context.Context, provider.Selection) (provider.ReadPolicy, error) { return policy, nil }, Executor: executor, StateDir: state, Executable: "/bin/false", InstanceID: "instance", Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}}) |
| wfMust(t, err) |
| s, err := NewSupervisor(SupervisorConfig{Journal: j, Namespaces: namespaces, API: api, Workflow: workflow, CredentialsPath: filepath.Join(state, "credentials"), InstallCredentials: func(context.Context, runnerproto.CredentialRotation, string) error { return nil }}) |
| wfMust(t, err) |
| @@ -188,7 +247,34 @@ func runDirectBugGraph(t *testing.T) { |
| return fmt.Errorf("completion while lease watchdog was still live") |
| } |
| } |
| - for i, step := range []string{"reproduce", "implement", "review", "verify", "publish"} { |
| + keys := []string{"reproduce", "implement", "review", "verify", "publish"} |
| + if feature { |
| + keys[0] = "scope" |
| + } |
| + if extra { |
| + keys = []string{"reproduce", "words", "layout", "implement", "review", "verify", "publish"} |
| + } |
| + if readWork { |
| + keys = []string{"research"} |
| + } |
| + for i, step := range keys { |
| + if extra && step == "publish" { |
| + arts, err := core.Artifacts(ctx, scope) |
| + wfMust(t, err) |
| + var render team.RenderResult |
| + for _, a := range arts { |
| + if a.Role == team.RoleRender { |
| + full, err := core.Artifact(ctx, scope, a.ID) |
| + wfMust(t, err) |
| + wfMust(t, json.Unmarshal(full.Payload, &render)) |
| + } |
| + } |
| + for _, decision := range []string{"copy", "design"} { |
| + job, err := core.GetJob(ctx, scope) |
| + wfMust(t, err) |
| + wfMust(t, core.RecordRenderedApproval(ctx, scope, job.Revision, team.RenderedApproval{CandidateHash: render.CandidateHash, DiffHash: render.DiffHash, RenderHash: render.RenderHash, Decision: decision, Person: "person", DecisionRevision: 1})) |
| + } |
| + } |
| h, err := core.Claim(ctx, scope, step, "runner", fmt.Sprint(i+1)) |
| wfMust(t, err) |
| sel := runnerproto.Selection{ConnectionID: step, Provider: "claude", Family: "claude", Model: "model", AccountID: "account", Isolation: iso} |
| @@ -210,8 +296,32 @@ func runDirectBugGraph(t *testing.T) { |
| for _, art := range arts { |
| hashes = append(hashes, art.Hash) |
| } |
| - claim := RunClaim{Assignment: a, ClaimResponse: runnerproto.ClaimResponse{Scope: scope, Handle: h, Brief: runnerproto.RunnerBrief{Target: target, Selection: sel, Policy: pol, CheckDefinition: marshal(pinned), ArtifactHashes: hashes}, AttemptDeadline: time.Now().Add(20 * time.Minute), LeaseDeadline: time.Now().Add(60 * time.Second)}} |
| - if err = s.Run(ctx, claim); err != nil { |
| + claim := RunClaim{Assignment: a, ClaimResponse: runnerproto.ClaimResponse{Scope: scope, Handle: h, Brief: runnerproto.RunnerBrief{Target: target, Selection: sel, Policy: pol, CheckDefinition: marshal(pinned), RenderRecipe: pinned.Render, ArtifactHashes: hashes}, AttemptDeadline: time.Now().Add(20 * time.Minute), LeaseDeadline: time.Now().Add(60 * time.Second)}} |
| + if feature || readWork { |
| + action := step |
| + if readWork { |
| + action = "recommend" |
| + claim.Brief.CheckDefinition = nil |
| + claim.Brief.ArtifactHashes = nil |
| + hashes = nil |
| + claim.Brief.Sources = []runnerproto.SourceSnapshot{source} |
| + } |
| + if step == "verify" { |
| + action = "checks" |
| + } |
| + if step == "words" { |
| + action = "copy" |
| + } |
| + if step == "layout" { |
| + action = "design" |
| + } |
| + specialist := "engineering" |
| + if step == "review" { |
| + specialist = "review" |
| + } |
| + claim.Brief.Step = runnerproto.StepBrief{PlanRevision: 1, StepKey: step, Action: action, SpecialistKey: specialist, SpecialistRevision: 1, ArtifactHashes: hashes} |
| + } |
| + if err = workflow.Run(ctx, s, claim); err != nil { |
| t.Fatalf("%s (%s): %v", step, s.states[attemptKey(scope, h)].FailurePhase, err) |
| } |
| } |
| @@ -224,15 +334,45 @@ func runDirectBugGraph(t *testing.T) { |
| consumed++ |
| } |
| } |
| - if consumed != 4 { |
| + wantConsumed := len(keys) - 1 |
| + if readWork { |
| + wantConsumed = 1 |
| + } |
| + if consumed != wantConsumed { |
| t.Fatal("dispatch bypassed durable ticket consumption", consumed) |
| } |
| - if api.admissions != 3 { |
| + wantAdmissions := len(keys) - 2 |
| + if readWork { |
| + wantAdmissions = 1 |
| + } |
| + if api.admissions != wantAdmissions { |
| t.Fatal("model admission count", api.admissions) |
| } |
| - if api.questions != 1 { |
| + wantQuestions := 1 |
| + if readWork { |
| + wantQuestions = 0 |
| + } |
| + if api.questions != wantQuestions { |
| t.Fatal("ask_person produced duplicate questions", api.questions) |
| } |
| + if readWork { |
| + if executorCalls != 0 { |
| + t.Fatal("research invoked checks", executorCalls) |
| + } |
| + if _, err := os.Stat(pubroot); !os.IsNotExist(err) { |
| + t.Fatal("research invoked publisher") |
| + } |
| + entries, err := os.ReadDir(works) |
| + wfMust(t, err) |
| + for _, entry := range entries { |
| + if !strings.HasPrefix(entry.Name(), "read-") { |
| + t.Fatal("mutable checkout created", entry.Name()) |
| + } |
| + if _, err = os.Stat(filepath.Join(works, entry.Name(), ".git")); !os.IsNotExist(err) { |
| + t.Fatal("research created git ref") |
| + } |
| + } |
| + } |
| finished, err := core.GetJob(ctx, scope) |
| wfMust(t, err) |
| if finished.State != team.JobSucceeded { |
| @@ -240,7 +380,7 @@ func runDirectBugGraph(t *testing.T) { |
| } |
| attempts, err := core.Attempts(ctx, scope) |
| wfMust(t, err) |
| - if len(attempts) != 5 { |
| + if len(attempts) != len(keys) { |
| t.Fatal("attempt count", len(attempts)) |
| } |
| for _, a := range attempts { |
| @@ -257,11 +397,40 @@ type directCoreAPI struct { |
| } |
| func (a *directCoreAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| + if op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleCandidate { |
| + if err := a.coreWorkflowAPI.Call(ctx, op, q, out); err != nil { |
| + return err |
| + } |
| + arts, err := a.core.Artifacts(ctx, q.Scope) |
| + if err != nil { |
| + return err |
| + } |
| + for i, art := range arts { |
| + arts[i], err = a.core.Artifact(ctx, q.Scope, art.ID) |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + return a.w.record(ctx, "artifacts", attemptKey(q.Scope, q.Handle), arts) |
| + } |
| + if op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleAnswer { |
| + if err := a.coreWorkflowAPI.Call(ctx, op, q, out); err != nil { |
| + return err |
| + } |
| + return a.core.Complete(ctx, q.Scope, q.Handle, team.AttemptResult{Outcome: team.OutcomeSuccess}) |
| + } |
| if op == "complete" && a.beforeComplete != nil { |
| if err := a.beforeComplete(); err != nil { |
| return err |
| } |
| } |
| + if op == "freeze_feature" { |
| + var v runnerproto.FreezeRequest |
| + if err := json.Unmarshal(q.Prepared, &v); err != nil { |
| + return err |
| + } |
| + return a.core.FreezeFeatureEvidence(ctx, q.Scope, q.Handle, v.ReproductionHash, v.DefinitionHash) |
| + } |
| if op == "questions" { |
| a.questions++ |
| } |
diff --git a/internal/runner/direct_workflow.go b/internal/runner/direct_workflow.go| index 95f8934d..4a7b0356 100644 |
| --- a/internal/runner/direct_workflow.go |
| +++ b/internal/runner/direct_workflow.go |
| @@ -11,6 +11,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/planflow" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -21,7 +22,10 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt |
| if launcher == nil { |
| return provider.ErrProvider |
| } |
| - tool := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[r.Claim.Assignment.StepKey] |
| + profile, err := planflow.Validate(r.Claim.Assignment, r.Claim.Brief) |
| + if err != nil { |
| + return err |
| + } |
| var proxy *ToolProxy |
| ask := w.directAsk(s, r, l, current) |
| questionCurrent := func(ctx context.Context, q runnerproto.Question) (time.Time, error) { |
| @@ -32,7 +36,7 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt |
| saved, err := s.currentDirectQuestion(ctx, r, q, current) |
| return saved.AnsweredBy, err |
| } |
| - b := ToolBinding{ReadPolicy: policy, Copy: w.cfg.Copy, InstanceID: w.cfg.InstanceID, TaskID: r.Claim.Assignment.TaskID, Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, Tools: []string{tool, "ask_person"}, LeaseDeadline: l.bound(), Agent: provider.Agent{ServerID: "direct", Provider: r.Claim.Assignment.Selection.Provider, AccountID: r.Claim.Assignment.Selection.AccountID, Family: r.Claim.Assignment.Selection.Family, Model: r.Claim.Assignment.Selection.Model}, Isolation: r.Claim.Assignment.Selection.Isolation, Journal: s.journal, Current: current} |
| + b := ToolBinding{ReadPolicy: policy, Copy: w.cfg.Copy, InstanceID: w.cfg.InstanceID, TaskID: r.Claim.Assignment.TaskID, Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, Tools: profile.Tools(), LeaseDeadline: l.bound(), Agent: provider.Agent{ServerID: "direct", Provider: r.Claim.Assignment.Selection.Provider, AccountID: r.Claim.Assignment.Selection.AccountID, Family: r.Claim.Assignment.Selection.Family, Model: r.Claim.Assignment.Selection.Model}, Isolation: r.Claim.Assignment.Selection.Isolation, Journal: s.journal, Current: current} |
| b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) { |
| relay := DirectQuestionRelay{Binding: bound, Proxy: proxy, Launcher: launcher, Current: questionCurrent, Answerer: answerer} |
| answer, err := relay.Ask(ctx, id, args, ask) |
| @@ -65,7 +69,6 @@ func (w *BugWorkflow) directModel(ctx context.Context, s *Supervisor, r *attempt |
| return permission.Permission(ctx, session, raw) |
| } |
| } |
| - var err error |
| proxy, err = OpenToolProxy(ctx, b) |
| if err != nil { |
| return err |
diff --git a/internal/runner/http.go b/internal/runner/http.go| index e0a8bf14..6f2b890a 100644 |
| --- a/internal/runner/http.go |
| +++ b/internal/runner/http.go |
| @@ -97,7 +97,7 @@ func (c *HTTPInstance) Call(ctx context.Context, op string, q runnerproto.Runner |
| } |
| call := func() error { return c.post(ctx, op, q, token, out) } |
| switch op { |
| - case "evidence", "artifacts", "freeze", "complete", "questions", "prepare", "publication_ready", "publication_authorize", "receipts", "lost", "release", "stop", "contained", "events", "question_resolved", "conclude": |
| + case "evidence", "artifacts", "freeze", "freeze_feature", "complete", "questions", "prepare", "publication_ready", "publication_authorize", "receipts", "lost", "release", "stop", "contained", "events", "question_resolved", "conclude": |
| return retryAuthority(ctx, call) |
| default: |
| return call() |
diff --git a/internal/runner/plan_render.go b/internal/runner/plan_render.go| new file mode 100644 |
| index 00000000..72f787f1 |
| --- /dev/null |
| +++ b/internal/runner/plan_render.go |
| @@ -0,0 +1,76 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/checks" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +func (w *PlanWorkflow) renderRequested(ctx context.Context, s *Supervisor, r *attemptState, tools []ToolSubmission, candidate team.GitCandidate, hash string, d checks.Definition, repro checks.Reproduction, register func(team.Role, any) (team.Artifact, error)) error { |
| + var request *ToolSubmission |
| + for i := range tools { |
| + t := &tools[i] |
| + if t.TaskID != r.Claim.Assignment.TaskID || t.Attempt != int64(r.Claim.Handle.Attempt) || t.Fence != r.Claim.Handle.Fence || t.Agent != r.Agent || t.Name != "submit_render" { |
| + continue |
| + } |
| + var v CandidateSubmission |
| + if request != nil || validateToolArguments(t.Name, t.Arguments) != nil || json.Unmarshal(t.Arguments, &v) != nil || v.Commit != candidate.Commit { |
| + return provider.ErrIdentity |
| + } |
| + request = t |
| + } |
| + if request == nil { |
| + return nil |
| + } |
| + if r.Claim.Brief.RenderRecipe == nil || d.Render == nil || team.ContentDigest(marshal(d.Render)) != team.ContentDigest(marshal(r.Claim.Brief.RenderRecipe)) || w.cfg.UploadBlob == nil { |
| + return provider.ErrPolicy |
| + } |
| + e, err := w.cfg.Executor(ctx, r.Claim, d, repro, r.Claim.AttemptDeadline) |
| + if err != nil { |
| + return err |
| + } |
| + w.cfg.Witness.installExecutor(r.Claim, e) |
| + render, err := e.RenderDefinition(ctx, d, hash) |
| + if err != nil { |
| + return err |
| + } |
| + for _, hash := range []string{render.DiffHash, render.RenderHash} { |
| + raw, err := e.Log(ctx, hash) |
| + if err != nil { |
| + return err |
| + } |
| + if err = w.cfg.UploadBlob(ctx, r.Claim, hash, raw); err != nil { |
| + return err |
| + } |
| + } |
| + if _, err = register(team.RoleRender, render); err != nil { |
| + return err |
| + } |
| + return s.journal.AckTool(ctx, *request) |
| +} |
| + |
| +// The answer write also completes the core step and delivers the thread message. |
| +// Recover its recorded request without reopening a provider session. |
| +func (s *Supervisor) recoverReadAnswer(ctx context.Context, r *attemptState) error { |
| + w, err := NewWitness(s.journal) |
| + if err != nil { |
| + return err |
| + } |
| + var spec team.ArtifactSpec |
| + if err = w.read(ctx, "read-answer", attemptKey(r.Claim.Scope, r.Claim.Handle), &spec); err != nil { |
| + return err |
| + } |
| + if spec.Role != team.RoleAnswer { |
| + return provider.ErrIdentity |
| + } |
| + q := r.request("artifact-" + string(team.RoleAnswer)) |
| + q.Artifact = &spec |
| + if err = s.api.Call(ctx, "artifacts", q, nil); err != nil { |
| + return err |
| + } |
| + r.Phase = "completed" |
| + return s.save(ctx, r) |
| +} |
diff --git a/internal/runner/plan_workflow_test.go b/internal/runner/plan_workflow_test.go| new file mode 100644 |
| index 00000000..5992b021 |
| --- /dev/null |
| +++ b/internal/runner/plan_workflow_test.go |
| @@ -0,0 +1,132 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/planflow" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestPlanWorkflowSpecialistOrder(t *testing.T) { |
| + for _, action := range []string{"scope", "copy", "design", "implement", "review", "checks", "publish"} { |
| + b := runnerproto.StepBrief{PlanRevision: 2, StepKey: "custom-" + action, SpecialistKey: "custom", Action: action, SpecialistRevision: 3} |
| + p, err := planflow.Resolve(b) |
| + want := map[string]string{"scope": "submit_acceptance", "copy": "submit_candidate", "design": "submit_candidate", "implement": "submit_candidate", "review": "submit_review", "checks": "", "publish": ""}[action] |
| + if p.Submission != want { |
| + t.Fatal("action mapped to wrong submission", action, p.Submission) |
| + } |
| + if err != nil || p.Action != action { |
| + t.Fatalf("lost persisted action: %+v %v", p, err) |
| + } |
| + } |
| + if _, err := planflow.Resolve(runnerproto.StepBrief{PlanRevision: 1, StepKey: "implement", Action: "deploy"}); err == nil { |
| + t.Fatal("unknown action accepted") |
| + } |
| +} |
| +func TestPlanWorkflowNoMidStepSwitch(t *testing.T) { |
| + c := RunClaim{Assignment: runnerproto.Assignment{StepKey: "build", Selection: runnerproto.Selection{ConnectionID: "one"}}, ClaimResponse: runnerproto.ClaimResponse{Brief: runnerproto.RunnerBrief{Step: runnerproto.StepBrief{PlanRevision: 1, StepKey: "build", SpecialistKey: "engineering", SpecialistRevision: 1, Action: "implement"}, Selection: runnerproto.Selection{ConnectionID: "two"}}}} |
| + if _, err := planflow.Validate(c.Assignment, c.Brief); err == nil { |
| + t.Fatal("changed account accepted") |
| + } |
| + c.Brief.Selection = c.Assignment.Selection |
| + c.Brief.Step.StepKey = "different" |
| + if _, err := planflow.Validate(c.Assignment, c.Brief); err == nil { |
| + t.Fatal("changed step accepted") |
| + } |
| +} |
| +func TestPlanWorkflowFrozenArtifacts(t *testing.T) { |
| + raw := []byte(`{"expected_symptom":"acceptance"}`) |
| + a := team.Artifact{Role: team.RoleAcceptance, Payload: raw, Hash: team.ContentDigest(raw)} |
| + b := runnerproto.RunnerBrief{Step: runnerproto.StepBrief{PlanRevision: 1, ArtifactHashes: []string{a.Hash}}, ArtifactHashes: []string{a.Hash}} |
| + if err := planflow.Artifacts(b, []team.Artifact{a}); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.Payload = []byte(`{}`) |
| + if err := planflow.Artifacts(b, []team.Artifact{a}); err == nil { |
| + t.Fatal("changed frozen artifact accepted") |
| + } |
| +} |
| +func TestPlanWorkflowToolPayloads(t *testing.T) { |
| + for name, raw := range map[string]string{ |
| + "submit_answer": `{"body":"answer","sources":[{"kind":"project","id":"1","hash":"` + strings.Repeat("a", 64) + `","revision":1}]}`, |
| + "submit_acceptance": `{"expected_symptom":"missing behaviour","files":[{"path":"new_test.go","bytes":"dGVzdA=="}],"test_names":[{"package":"fixture","name":"TestNew"}]}`, |
| + "submit_render": `{"commit":"` + strings.Repeat("a", 40) + `"}`, |
| + } { |
| + if err := validateToolArguments(name, json.RawMessage(raw)); err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + raw = strings.TrimSuffix(raw, "}") + `,"attestation":"model-claim"}` |
| + if err := validateToolArguments(name, json.RawMessage(raw)); err == nil { |
| + t.Fatalf("%s accepted fabricated attestation", name) |
| + } |
| + } |
| +} |
| + |
| +func TestPlanWorkflowRenderPair(t *testing.T) { |
| + b := directToolFixture(t) |
| + b.Tools = []string{"submit_candidate", "submit_render"} |
| + proxy, err := OpenToolProxy(context.Background(), b) |
| + mustJournal(t, err) |
| + defer proxy.Close() |
| + args := json.RawMessage(`{"commit":"` + strings.Repeat("a", 40) + `"}`) |
| + mustJournal(t, proxy.submit(context.Background(), "submit_candidate", "candidate", args)) |
| + mustJournal(t, proxy.submit(context.Background(), "submit_render", "render", args)) |
| + if err = proxy.submit(context.Background(), "submit_render", "another", args); err == nil { |
| + t.Fatal("duplicate render accepted") |
| + } |
| +} |
| +func TestPlanWorkflowNoMidStepSwitchNamespaces(t *testing.T) { |
| + TestDirectCancelWaitsForNamespacesUnproven(t) |
| +} |
| + |
| +func TestPlanWorkflowAnswerRecovery(t *testing.T) { |
| + s, r, _, _ := cleanupFixture(t) |
| + r.Claim.Brief.Target.Kind = team.TargetProjectRead |
| + r.Phase = "delivering-answer" |
| + w, err := NewWitness(s.journal) |
| + mustJournal(t, err) |
| + spec := team.ArtifactSpec{Role: team.RoleAnswer, MediaType: "application/json", Payload: []byte(`{"body":"answer","sources":[]}`)} |
| + mustJournal(t, w.record(context.Background(), "read-answer", attemptKey(r.Claim.Scope, r.Claim.Handle), spec)) |
| + calls := 0 |
| + s.api = apiFuncR3(func(_ context.Context, op string, q runnerproto.RunnerRequest, _ any) error { |
| + calls++ |
| + if op != "artifacts" || q.Artifact == nil || string(q.Artifact.Payload) != string(spec.Payload) { |
| + t.Fatal("recovery replayed something other than the recorded answer", op) |
| + } |
| + return nil |
| + }) |
| + mustJournal(t, s.recoverReadAnswer(context.Background(), r)) |
| + if calls != 1 || r.Phase != "completed" { |
| + t.Fatal("answer was not recovered without a provider", calls, r.Phase) |
| + } |
| +} |
| +func TestPlanWorkflowProviderPoliciesBroker(t *testing.T) { |
| + for _, action := range []string{"scope", "recommend", "copy", "design", "review"} { |
| + t.Run(action, func(t *testing.T) { |
| + b := directToolFixture(t) |
| + profile, err := provider.Profile(action) |
| + mustJournal(t, err) |
| + b.Tools = profile.Tools() |
| + proxy, err := OpenToolProxy(context.Background(), b) |
| + mustJournal(t, err) |
| + defer proxy.Close() |
| + q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, RequestID: "submission", Name: "submit_candidate", Arguments: json.RawMessage(`{"commit":"` + strings.Repeat("a", 40) + `"}`)} |
| + if profile.Submission != "submit_candidate" { |
| + if proxy.ValidateApproval(context.Background(), q) == nil { |
| + t.Fatal("approval broadened tool inventory") |
| + } |
| + } else { |
| + mustJournal(t, proxy.ValidateApproval(context.Background(), q)) |
| + } |
| + q.Name = profile.Submission |
| + q.Arguments = json.RawMessage(`{"commit":"` + strings.Repeat("a", 40) + `","attestation":"claim"}`) |
| + if proxy.ValidateApproval(context.Background(), q) == nil { |
| + t.Fatal("broker approved invalid arguments") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/planflow/budget_test.go b/internal/runner/planflow/budget_test.go| new file mode 100644 |
| index 00000000..97f28724 |
| --- /dev/null |
| +++ b/internal/runner/planflow/budget_test.go |
| @@ -0,0 +1,9 @@ |
| +package planflow |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "os" |
| + "testing" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/runner/planflow/prompt.go b/internal/runner/planflow/prompt.go| new file mode 100644 |
| index 00000000..a01c4418 |
| --- /dev/null |
| +++ b/internal/runner/planflow/prompt.go |
| @@ -0,0 +1,82 @@ |
| +package planflow |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "unicode/utf8" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +var ErrPromptTooLarge = errors.New("runner.prompt_too_large") |
| + |
| +const MaxPromptBytes = 24 << 10 |
| + |
| +// LegacyStep preserves only the original fixed bug protocol. |
| +func LegacyStep(key string) runnerproto.StepBrief { |
| + action := key |
| + if key == "verify" { |
| + action = "checks" |
| + } |
| + specialist := "engineering" |
| + if key == "review" || key == "verify" { |
| + specialist = "review" |
| + } |
| + return runnerproto.StepBrief{PlanRevision: 1, StepKey: key, Action: action, SpecialistKey: specialist, SpecialistRevision: 1} |
| +} |
| + |
| +type promptFile struct { |
| + Path string `json:"path"` |
| + Text string `json:"text"` |
| +} |
| +type turnPrompt struct { |
| + RenderAvailable bool `json:"render_available,omitempty"` |
| + Action string |
| + Sources []runnerproto.SourceSnapshot `json:"sources,omitempty"` |
| + Step string |
| + Instructions string `json:"instructions"` |
| + StandingInstructions string `json:"standing_instructions"` |
| + Target team.TargetBinding `json:"target"` |
| + ExpectedSymptom string `json:"expected_symptom,omitempty"` |
| + Files []promptFile `json:"reproduction_files,omitempty"` |
| + Tests []team.TestIdentity `json:"reproduction_tests,omitempty"` |
| + CandidateCommit string `json:"candidate_commit,omitempty"` |
| +} |
| + |
| +func Prompt(assignment runnerproto.Assignment, brief runnerproto.RunnerBrief, artifacts []team.Artifact) (string, error) { |
| + p := turnPrompt{RenderAvailable: brief.RenderRecipe != nil, Action: brief.Step.Action, Sources: brief.Sources, Step: assignment.StepKey, Instructions: brief.Instructions, StandingInstructions: brief.StandingInstructions, Target: brief.Target} |
| + if brief.Target.Kind == team.TargetProjectRead && p.Action == "scope" { |
| + p.Action = "recommend" |
| + } |
| + for _, a := range artifacts { |
| + switch a.Role { |
| + case team.RoleReproduction, team.RoleAcceptance: |
| + var r runnerproto.Reproduction |
| + if err := json.Unmarshal(a.Payload, &r); err != nil { |
| + return "", err |
| + } |
| + p.ExpectedSymptom, p.Tests = r.ExpectedSymptom, r.TestNames |
| + for _, f := range r.Files { |
| + if !utf8.Valid(f.Bytes) { |
| + return "", runnerproto.ErrInvalid |
| + } |
| + p.Files = append(p.Files, promptFile{f.Path, string(f.Bytes)}) |
| + } |
| + case team.RoleCandidate: |
| + var candidate team.GitCandidate |
| + if err := json.Unmarshal(a.Payload, &candidate); err != nil { |
| + return "", err |
| + } |
| + p.CandidateCommit = candidate.Commit |
| + } |
| + } |
| + raw, err := json.Marshal(p) |
| + if err != nil { |
| + return "", err |
| + } |
| + if len(raw) > MaxPromptBytes { |
| + return "", ErrPromptTooLarge |
| + } |
| + return string(raw), nil |
| +} |
diff --git a/internal/runner/planflow/types.go b/internal/runner/planflow/types.go| new file mode 100644 |
| index 00000000..78edd85e |
| --- /dev/null |
| +++ b/internal/runner/planflow/types.go |
| @@ -0,0 +1,32 @@ |
| +package planflow |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "reflect" |
| +) |
| + |
| +type Profile = provider.ActionProfile |
| + |
| +func Resolve(b runnerproto.StepBrief) (Profile, error) { |
| + if b.PlanRevision < 1 || b.StepKey == "" || b.Action == "" { |
| + return Profile{}, provider.ErrIdentity |
| + } |
| + switch b.Action { |
| + case "checks", "publish": |
| + return Profile{Action: b.Action, ReadOnly: true}, nil |
| + } |
| + if b.SpecialistKey == "" || b.SpecialistRevision < 1 { |
| + return Profile{}, provider.ErrIdentity |
| + } |
| + return provider.Profile(b.Action) |
| +} |
| +func Validate(a runnerproto.Assignment, b runnerproto.RunnerBrief) (Profile, error) { |
| + if !reflect.DeepEqual(a.Selection, b.Selection) || a.StepKey != b.Step.StepKey { |
| + return Profile{}, provider.ErrIdentity |
| + } |
| + if b.Target.Kind == "project_read" && b.Step.Action == "scope" { |
| + return provider.Profile("recommend") |
| + } |
| + return Resolve(b.Step) |
| +} |
diff --git a/internal/runner/planflow/workflow.go b/internal/runner/planflow/workflow.go| new file mode 100644 |
| index 00000000..63db97be |
| --- /dev/null |
| +++ b/internal/runner/planflow/workflow.go |
| @@ -0,0 +1,28 @@ |
| +package planflow |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "slices" |
| +) |
| + |
| +// Artifacts rejects material outside the immutable dispatch snapshot. |
| +func Artifacts(b runnerproto.RunnerBrief, artifacts []team.Artifact) error { |
| + if !slices.Equal(b.Step.ArtifactHashes, b.ArtifactHashes) { |
| + return provider.ErrIdentity |
| + } |
| + seen := map[string]bool{} |
| + for _, a := range artifacts { |
| + if team.ContentDigest(a.Payload) != a.Hash || !slices.Contains(b.Step.ArtifactHashes, a.Hash) { |
| + return provider.ErrIdentity |
| + } |
| + seen[a.Hash] = true |
| + } |
| + for _, hash := range b.Step.ArtifactHashes { |
| + if !seen[hash] && hash != team.ContentDigest(b.CheckDefinition) { |
| + return provider.ErrIdentity |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/provider/actions.go b/internal/runner/provider/actions.go| new file mode 100644 |
| index 00000000..b68ca057 |
| --- /dev/null |
| +++ b/internal/runner/provider/actions.go |
| @@ -0,0 +1,45 @@ |
| +package provider |
| + |
| +// ActionProfile is an executable capability, independent of a specialist's name. |
| +type ActionProfile struct { |
| + Action, Specialist, Submission string |
| + ReadOnly bool |
| + Render bool |
| +} |
| + |
| +func Profile(action string) (ActionProfile, error) { |
| + p := ActionProfile{Action: action} |
| + switch action { |
| + case "reproduce": |
| + p.Specialist, p.Submission = "Engineering", "submit_reproduction" |
| + case "scope": |
| + p.Specialist, p.Submission, p.ReadOnly = "Scope", "submit_acceptance", true |
| + case "recommend", "investigate", "research": |
| + p.Specialist, p.Submission, p.ReadOnly = "Research", "submit_answer", true |
| + case "implement": |
| + p.Specialist, p.Submission, p.Render = "Engineering", "submit_candidate", true |
| + case "copy": |
| + p.Specialist, p.Submission, p.Render = "Copy", "submit_candidate", true |
| + case "design": |
| + p.Specialist, p.Submission, p.Render = "Design", "submit_candidate", true |
| + case "review": |
| + p.Specialist, p.Submission, p.ReadOnly = "Review", "submit_review", true |
| + default: |
| + return p, ErrPolicy |
| + } |
| + return p, nil |
| +} |
| +func (p ActionProfile) Tools() []string { |
| + tools := []string{p.Submission, "ask_person"} |
| + if p.Render { |
| + tools = append(tools, "submit_render") |
| + } |
| + return tools |
| +} |
| +func (p ActionProfile) MCPTools() []string { |
| + tools := p.Tools() |
| + for i := range tools { |
| + tools[i] = "mcp__equipo__" + tools[i] |
| + } |
| + return tools |
| +} |
diff --git a/internal/runner/provider/claude/launcher.go b/internal/runner/provider/claude/launcher.go| index f9093cb1..741fa1a3 100644 |
| --- a/internal/runner/provider/claude/launcher.go |
| +++ b/internal/runner/provider/claude/launcher.go |
| @@ -53,6 +53,7 @@ type sessionState struct { |
| } |
| type manifest struct { |
| + Action string |
| AuthHost string |
| CredentialHome string |
| Argv []string |
| @@ -98,9 +99,9 @@ func baseArgs(model, tools string) []string { |
| } |
| func nativeTools(role string) ([]string, error) { |
| switch role { |
| - case "Engineering": |
| + case "Engineering", "Copy", "Design": |
| return []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep"}, nil |
| - case "Review", "Product": |
| + case "Review", "Product", "Scope", "Research": |
| return []string{"Read", "Glob", "Grep", "Bash"}, nil |
| } |
| return nil, provider.ErrPolicy |
| @@ -109,13 +110,19 @@ func nativeTools(role string) ([]string, error) { |
| // PolicyInputs renders the provider policy before the runner calls BuildPolicy. |
| // Tools may contain additional explicitly registered Equipo MCP tool names. |
| func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, model string) (provider.PolicyInputs, error) { |
| + if in.Action != "" { |
| + profile, err := provider.Profile(in.Action) |
| + if err != nil || !reflect.DeepEqual(in.Tools, profile.MCPTools()) || (specialist != profile.Specialist && !(in.Action == "reproduce" && specialist == "Product")) { |
| + return in, provider.ErrPolicy |
| + } |
| + } |
| native, e := nativeTools(specialist) |
| if e != nil || model == "" || strings.HasPrefix(model, "-") { |
| return in, provider.ErrPolicy |
| } |
| tools := append(append([]string{}, native...), "mcp__equipo__permission") |
| for _, tool := range in.Tools { |
| - if !slices.Contains([]string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction"}, tool) { |
| + if !slices.Contains([]string{"mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction", "mcp__equipo__submit_acceptance", "mcp__equipo__submit_answer", "mcp__equipo__submit_render"}, tool) { |
| return in, provider.ErrPolicy |
| } |
| tools = append(tools, tool) |
| @@ -138,6 +145,12 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, specialist, mode |
| "sandbox": map[string]any{"enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "autoAllowBashIfSandboxed": false, "excludedCommands": []string{}, "filesystem": map[string]any{"denyRead": denied, "denyWrite": denied}, "network": map[string]any{"allowUnixSockets": []string{}}}, |
| "permissions": map[string]any{"deny": nativeDenies, "allow": append([]string{}, in.Tools...)}, |
| } |
| + if in.Action != "" { |
| + p, _ := provider.Profile(in.Action) |
| + if p.ReadOnly { |
| + settings["sandbox"].(map[string]any)["filesystem"].(map[string]any)["denyWrite"] = append(append([]string{}, denied...), "/workspace") |
| + } |
| + } |
| in.Settings, _ = json.Marshal(settings) |
| in.MCP = json.RawMessage(`{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}`) |
| in.ThreadPolicy, _ = json.Marshal(threadPolicy{specialist, model, "session-id", "resume"}) |
| @@ -162,7 +175,7 @@ func policyInputs(p provider.Policy) (provider.PolicyInputs, manifest, error) { |
| if !uniqueJSON(p.Manifest) || json.Unmarshal(p.Manifest, &m) != nil { |
| return provider.PolicyInputs{}, m, provider.ErrPolicy |
| } |
| - in := provider.PolicyInputs{AuthHost: m.AuthHost, Argv: append([]string{}, m.Argv...), DeniedPaths: m.DeniedPaths, EgressHosts: m.EgressHosts, ProviderVersion: m.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, Workspace: m.Workspace, Scratch: m.Scratch, Settings: m.Settings, MCP: m.MCP, ThreadPolicy: m.ThreadPolicy, TurnPolicy: m.TurnPolicy, Tools: m.Tools, Env: map[string]string{}} |
| + in := provider.PolicyInputs{Action: m.Action, AuthHost: m.AuthHost, Argv: append([]string{}, m.Argv...), DeniedPaths: m.DeniedPaths, EgressHosts: m.EgressHosts, ProviderVersion: m.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, Workspace: m.Workspace, Scratch: m.Scratch, Settings: m.Settings, MCP: m.MCP, ThreadPolicy: m.ThreadPolicy, TurnPolicy: m.TurnPolicy, Tools: m.Tools, Env: map[string]string{}} |
| for _, automatic := range []string{m.CredentialHome, "/home/runner"} { |
| for i, path := range in.DeniedPaths { |
| if path == automatic { |
diff --git a/internal/runner/provider/claude/launcher_test.go b/internal/runner/provider/claude/launcher_test.go| index e33a3a6f..28042b17 100644 |
| --- a/internal/runner/provider/claude/launcher_test.go |
| +++ b/internal/runner/provider/claude/launcher_test.go |
| @@ -42,6 +42,7 @@ for line in sys.stdin: |
| v=json.loads(line) |
| if v['type']!='user': sys.exit(2) |
| init={'type':'system','subtype':'init','session_id':sid,'claude_code_version':'2.1.312','model':args[args.index('--model')+1],'permissionMode':'manual','tools':args[args.index('--tools')+1].split(',')+['mcp__equipo__permission'],'mcp_servers':[{'name':'equipo','status':'connected'}],'skills':[],'plugins':[]} |
| + if os.environ.get('FAKE_TOOLS'): init['tools']=json.loads(os.environ['FAKE_TOOLS']) |
| if os.environ['FAKE_MODE']=='identity': init['session_id']='different' |
| if os.environ['FAKE_MODE']=='tools': init['tools'].append('WebFetch') |
| if os.environ['FAKE_MODE']=='plugins': init['plugins']=[{'name':'extra','path':'/untrusted','source':'extra'}] |
| @@ -113,6 +114,10 @@ func (h *fakeHost) Start(ctx context.Context, l provider.Launch, args []string) |
| } |
| cmd.Env = append(cmd.Env, k+"="+v) |
| } |
| + var manifest struct{ Tools []string } |
| + json.Unmarshal(l.Policy.Manifest, &manifest) |
| + toolJSON, _ := json.Marshal(manifest.Tools) |
| + cmd.Env = append(cmd.Env, "FAKE_TOOLS="+string(toolJSON)) |
| in, _ := cmd.StdinPipe() |
| out, outWrite, _ := os.Pipe() |
| errout, errWrite, _ := os.Pipe() |
diff --git a/internal/runner/provider/claude/plan_policy_test.go b/internal/runner/provider/claude/plan_policy_test.go| new file mode 100644 |
| index 00000000..3585ee11 |
| --- /dev/null |
| +++ b/internal/runner/provider/claude/plan_policy_test.go |
| @@ -0,0 +1,78 @@ |
| +package claude |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "slices" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| + for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + profile, err := provider.Profile(action) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + in := provider.PolicyInputs{Action: action, Tools: profile.MCPTools()} |
| + b := provider.Binding{Provider: "claude", CredentialHome: "/private/account", Home: "/private/run", RuntimeRoot: "/private/runtime"} |
| + got, err := PolicyInputs(b, in, profile.Specialist, "model") |
| + if err != nil { |
| + t.Fatalf("%s: %v", action, err) |
| + } |
| + for _, name := range profile.MCPTools() { |
| + if !slices.Contains(got.Tools, name) { |
| + t.Fatalf("%s missing %s", action, name) |
| + } |
| + } |
| + var settings map[string]any |
| + if json.Unmarshal(got.Settings, &settings) != nil { |
| + t.Fatal("invalid settings") |
| + } |
| + if (action == "scope" || action == "recommend" || action == "investigate" || action == "review") && (slices.Contains(got.Tools, "Write") || slices.Contains(got.Tools, "Edit")) { |
| + t.Fatal("read-only profile writes") |
| + } |
| + |
| + in.Tools = append(in.Tools, "mcp__equipo__submit_review") |
| + if _, err = PolicyInputs(b, in, profile.Specialist, "model"); err == nil { |
| + t.Fatal("broadened inventory accepted") |
| + } |
| + } |
| +} |
| + |
| +func TestPlanWorkflowProviderPoliciesLauncher(t *testing.T) { |
| + for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + t.Run(action, func(t *testing.T) { |
| + f := fixtureFor(t, "Engineering") |
| + p, _ := provider.Profile(action) |
| + in := f.inputs |
| + in.Action = action |
| + in.Tools = p.MCPTools() |
| + var err error |
| + in, err = PolicyInputs(f.lease.Binding(), in, p.Specialist, f.launch.Selection.Model) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.launch.Policy, err = provider.BuildPolicy(f.lease.Binding(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + session, events := openFixture(t, f) |
| + if err = f.l.StartTurn(context.Background(), session, provider.Turn{ID: "plan-turn", AdmissionID: "plan-admission", Prompt: "fixture"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for e := range events { |
| + if e.Kind == "turn.completed" { |
| + break |
| + } |
| + if e.Kind == "turn.failed" { |
| + t.Fatal("fixture failed") |
| + } |
| + } |
| + if err = f.l.Close(context.Background(), session); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/provider/codex/answers.go b/internal/runner/provider/codex/answers.go| index 963bc06f..fe67a996 100644 |
| --- a/internal/runner/provider/codex/answers.go |
| +++ b/internal/runner/provider/codex/answers.go |
| @@ -5,6 +5,7 @@ import ( |
| "context" |
| "encoding/json" |
| "fmt" |
| + "slices" |
| "sort" |
| "strings" |
| @@ -168,7 +169,19 @@ func (l *Launcher) respond(ctx context.Context, session provider.Session, a prov |
| decision := "decline" |
| if a.Behavior == "allow" { |
| _, nativeErr := NativeApproval(ev) |
| - _, _, mcpErr := MCPApproval(ev) |
| + tool, _, mcpErr := MCPApproval(ev) |
| + var m manifest |
| + if json.Unmarshal(s.launch.Policy.Manifest, &m) != nil { |
| + return provider.ErrPolicy |
| + } |
| + if m.Action != "" { |
| + if mcpErr == nil && !slices.Contains(m.Tools, "mcp__equipo__"+tool) { |
| + return provider.ErrPolicy |
| + } |
| + if nativeErr == nil && s.launch.Policy.ReadOnlyWorkspace() && (v.Method == "item/fileChange/requestApproval" || v.Method == "applyPatchApproval") { |
| + return provider.ErrPolicy |
| + } |
| + } |
| if a.Authorize == nil || (nativeErr != nil && mcpErr != nil) { |
| return provider.ErrPolicy |
| } |
diff --git a/internal/runner/provider/codex/launcher.go b/internal/runner/provider/codex/launcher.go| index 84681216..2ebe529a 100644 |
| --- a/internal/runner/provider/codex/launcher.go |
| +++ b/internal/runner/provider/codex/launcher.go |
| @@ -58,6 +58,7 @@ type sessionState struct { |
| used map[string]bool |
| } |
| type manifest struct { |
| + Action string |
| AuthHost string |
| Argv, DeniedPaths, EgressHosts, Tools []string |
| ProviderVersion, LauncherVersion, BwrapVersion, Workspace, Scratch, CredentialHome string |
| @@ -102,10 +103,22 @@ func token() string { |
| // PolicyInputs renders the policy before BuildPolicy hashes the launch manifest. |
| func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (provider.PolicyInputs, error) { |
| + if in.Action != "" { |
| + profile, err := provider.Profile(in.Action) |
| + if err != nil || !reflect.DeepEqual(in.Tools, profile.MCPTools()) { |
| + return in, provider.ErrPolicy |
| + } |
| + } |
| if b.Provider != "codex" || model == "" { |
| return in, provider.ErrIdentity |
| } |
| fs := map[string]any{":root": "read", "/workspace": "write", "/tmp": "write"} |
| + if in.Action != "" { |
| + p, _ := provider.Profile(in.Action) |
| + if p.ReadOnly { |
| + fs["/workspace"] = "read" |
| + } |
| + } |
| for _, path := range append(append([]string{}, in.DeniedPaths...), b.CredentialHome, b.Home, "/home/runner", "/egress", "/tool", "/tool/equipo.sock", "/config", "/proc", "/dev/fd") { |
| if !filepath.IsAbs(path) || filepath.Clean(path) != path || path == "/" || path == "/workspace" || path == "/tmp" { |
| return in, provider.ErrPolicy |
| @@ -119,7 +132,7 @@ func PolicyInputs(b provider.Binding, in provider.PolicyInputs, model string) (p |
| } |
| for _, tool := range in.Tools { |
| switch tool { |
| - case "mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction": |
| + case "mcp__equipo__ask_person", "mcp__equipo__submit_candidate", "mcp__equipo__submit_review", "mcp__equipo__submit_reproduction", "mcp__equipo__submit_acceptance", "mcp__equipo__submit_answer", "mcp__equipo__submit_render": |
| default: |
| return in, provider.ErrPolicy |
| } |
| @@ -174,7 +187,7 @@ func policyInputs(p provider.Policy) (provider.PolicyInputs, manifest, error) { |
| if !uniqueJSON(p.Manifest) || json.Unmarshal(p.Manifest, &m) != nil { |
| return provider.PolicyInputs{}, m, provider.ErrPolicy |
| } |
| - in := provider.PolicyInputs{AuthHost: m.AuthHost, Argv: m.Argv, DeniedPaths: append([]string{}, m.DeniedPaths...), EgressHosts: m.EgressHosts, Tools: m.Tools, ProviderVersion: m.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, Workspace: m.Workspace, Scratch: m.Scratch, Settings: m.Settings, MCP: m.MCP, ThreadPolicy: m.ThreadPolicy, TurnPolicy: m.TurnPolicy, Env: map[string]string{}} |
| + in := provider.PolicyInputs{Action: m.Action, AuthHost: m.AuthHost, Argv: m.Argv, DeniedPaths: append([]string{}, m.DeniedPaths...), EgressHosts: m.EgressHosts, Tools: m.Tools, ProviderVersion: m.ProviderVersion, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, Workspace: m.Workspace, Scratch: m.Scratch, Settings: m.Settings, MCP: m.MCP, ThreadPolicy: m.ThreadPolicy, TurnPolicy: m.TurnPolicy, Env: map[string]string{}} |
| for _, path := range []string{m.CredentialHome, "/home/runner"} { |
| for i, p := range in.DeniedPaths { |
| if p == path { |
diff --git a/internal/runner/provider/codex/plan_policy_test.go b/internal/runner/provider/codex/plan_policy_test.go| new file mode 100644 |
| index 00000000..521d09b5 |
| --- /dev/null |
| +++ b/internal/runner/provider/codex/plan_policy_test.go |
| @@ -0,0 +1,79 @@ |
| +package codex |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "slices" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +func TestPlanWorkflowProviderPolicies(t *testing.T) { |
| + for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + profile, err := provider.Profile(action) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + in := provider.PolicyInputs{Action: action, Tools: profile.MCPTools()} |
| + b := provider.Binding{Provider: "codex", CredentialHome: "/private/account", Home: "/private/run", RuntimeRoot: "/private/runtime"} |
| + got, err := PolicyInputs(b, in, "model") |
| + if err != nil { |
| + t.Fatalf("%s: %v", action, err) |
| + } |
| + for _, name := range profile.MCPTools() { |
| + if !slices.Contains(got.Tools, name) { |
| + t.Fatalf("%s missing %s", action, name) |
| + } |
| + } |
| + var settings map[string]any |
| + if json.Unmarshal(got.Settings, &settings) != nil { |
| + t.Fatal("invalid settings") |
| + } |
| + fs := settings["permissions"].(map[string]any)["equipo"].(map[string]any)["filesystem"].(map[string]any) |
| + if (action == "scope" || action == "recommend" || action == "investigate" || action == "review") && fs["/workspace"] != "read" { |
| + t.Fatal("read-only profile writes") |
| + } |
| + |
| + in.Tools = append(in.Tools, "mcp__equipo__submit_review") |
| + if _, err = PolicyInputs(b, in, "model"); err == nil { |
| + t.Fatal("broadened inventory accepted") |
| + } |
| + } |
| +} |
| + |
| +func TestPlanWorkflowProviderPoliciesLauncher(t *testing.T) { |
| + for _, action := range []string{"scope", "recommend", "investigate", "implement", "copy", "design", "review"} { |
| + t.Run(action, func(t *testing.T) { |
| + f := fixtureFor(t) |
| + p, _ := provider.Profile(action) |
| + in := f.inputs |
| + in.Action = action |
| + in.Tools = p.MCPTools() |
| + var err error |
| + in, err = PolicyInputs(f.lease.Binding(), in, f.launch.Selection.Model) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.launch.Policy, err = provider.BuildPolicy(f.lease.Binding(), in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + session, events := openFixture(t, f) |
| + if err = f.l.StartTurn(context.Background(), session, provider.Turn{ID: "plan-turn", AdmissionID: "plan-admission", Prompt: "fixture"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for e := range events { |
| + if e.Kind == "turn.completed" { |
| + break |
| + } |
| + if e.Kind == "turn.failed" { |
| + t.Fatal("fixture failed") |
| + } |
| + } |
| + if err = f.l.Close(context.Background(), session); err != nil { |
| + t.Fatal(err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/provider/direct_certification.go b/internal/runner/provider/direct_certification.go| index 50cfd5c4..b5b08c71 100644 |
| --- a/internal/runner/provider/direct_certification.go |
| +++ b/internal/runner/provider/direct_certification.go |
| @@ -228,19 +228,22 @@ func (e DirectEvidence) validateTools(root string, probes bool) error { |
| if e.Provider == "claude" { |
| expected := []string{"Read", "Glob", "Grep", "Bash"} |
| switch e.Specialist { |
| - case "Engineering": |
| + case "Engineering", "Copy", "Design": |
| expected = append(expected, "Write", "Edit") |
| - case "Review", "Product": |
| + case "Review", "Product", "Scope", "Research", "Investigation": |
| default: |
| return ErrPolicy |
| } |
| expected = append(expected, "mcp__equipo__permission", "mcp__equipo__ask_person") |
| - stepTool := map[string]string{"Engineering": "mcp__equipo__submit_candidate", "Review": "mcp__equipo__submit_review", "Product": "mcp__equipo__submit_reproduction"}[e.Specialist] |
| + stepTool := map[string]string{"Engineering": "mcp__equipo__submit_candidate", "Review": "mcp__equipo__submit_review", "Product": "mcp__equipo__submit_reproduction", "Scope": "mcp__equipo__submit_acceptance", "Research": "mcp__equipo__submit_answer", "Investigation": "mcp__equipo__submit_answer", "Copy": "mcp__equipo__submit_candidate", "Design": "mcp__equipo__submit_candidate"}[e.Specialist] |
| expected = append(expected, stepTool) |
| // Engineering's reproduction policy has a distinct hash and tool inventory. |
| if slices.Contains(exposed, "mcp__equipo__submit_reproduction") && e.Specialist == "Engineering" { |
| expected[len(expected)-1] = "mcp__equipo__submit_reproduction" |
| } |
| + if (e.Specialist == "Engineering" && !slices.Contains(exposed, "mcp__equipo__submit_reproduction")) || e.Specialist == "Copy" || e.Specialist == "Design" { |
| + expected = append(expected, "mcp__equipo__submit_render") |
| + } |
| slices.Sort(expected) |
| slices.Sort(exposed) |
| if !slices.Equal(expected, exposed) { |
diff --git a/internal/runner/provider/policy.go b/internal/runner/provider/policy.go| index a9a2a17b..9ff1ad96 100644 |
| --- a/internal/runner/provider/policy.go |
| +++ b/internal/runner/provider/policy.go |
| @@ -22,6 +22,7 @@ const SettingsPath = "/config/equipo-settings.json" |
| const MCPPath = "/config/equipo-mcp.json" |
| type PolicyInputs struct { |
| + Action string |
| AuthHost string |
| RuntimeFiles []Mount |
| DeniedPaths, EgressHosts []string |
| @@ -39,6 +40,7 @@ type fileDigest struct { |
| SHA256 string |
| } |
| type effectiveManifest struct { |
| + Action string `json:",omitempty"` |
| AuthHost string |
| OuterMounts, GeneratedMounts []Mount |
| NamespaceArgs []string |
| @@ -335,8 +337,16 @@ func BuildPolicy(b Binding, in PolicyInputs) (Policy, error) { |
| for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"} { |
| fullEnv[k] = "http://127.0.0.1:18080" |
| } |
| - m := effectiveManifest{AuthHost: in.AuthHost, Version: PolicyVersion, BindingID: b.ID, Provider: b.Provider, AccountID: b.AccountID, CredentialHome: b.CredentialHome, Identity: b.Expected, ProviderVersion: in.ProviderVersion, LauncherVersion: in.LauncherVersion, BwrapVersion: in.BwrapVersion, Argv: append([]string(nil), in.Argv...), Env: fullEnv, Files: files, DeniedPaths: denied, EgressHosts: hosts, Tools: tools, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: turn, Workspace: in.Workspace, Scratch: in.Scratch, RuntimeHome: b.Home, ConfigHome: b.provenance.config, Instructions: instructions, HooksDisabled: true, PluginsDisabled: true, TurnOverridesOmitted: true, MaskedDirectories: []string{"/etc/claude-code", "/etc/codex"}, Proxy: "http://127.0.0.1:18080"} |
| - m.OuterMounts = []Mount{{Source: "/usr", Target: "/usr", ReadOnly: true}, {Source: in.Workspace, Target: "/workspace"}, {Source: b.Home, Target: "/home/runner"}, {Source: in.Scratch, Target: "/tmp"}} |
| + m := effectiveManifest{Action: in.Action, AuthHost: in.AuthHost, Version: PolicyVersion, BindingID: b.ID, Provider: b.Provider, AccountID: b.AccountID, CredentialHome: b.CredentialHome, Identity: b.Expected, ProviderVersion: in.ProviderVersion, LauncherVersion: in.LauncherVersion, BwrapVersion: in.BwrapVersion, Argv: append([]string(nil), in.Argv...), Env: fullEnv, Files: files, DeniedPaths: denied, EgressHosts: hosts, Tools: tools, Settings: settings, MCP: mcp, ThreadPolicy: thread, TurnPolicy: turn, Workspace: in.Workspace, Scratch: in.Scratch, RuntimeHome: b.Home, ConfigHome: b.provenance.config, Instructions: instructions, HooksDisabled: true, PluginsDisabled: true, TurnOverridesOmitted: true, MaskedDirectories: []string{"/etc/claude-code", "/etc/codex"}, Proxy: "http://127.0.0.1:18080"} |
| + readOnly := false |
| + if in.Action != "" { |
| + profile, err := Profile(in.Action) |
| + if err != nil { |
| + return Policy{}, err |
| + } |
| + readOnly = profile.ReadOnly |
| + } |
| + m.OuterMounts = []Mount{{Source: "/usr", Target: "/usr", ReadOnly: true}, {Source: in.Workspace, Target: "/workspace", ReadOnly: readOnly}, {Source: b.Home, Target: "/home/runner"}, {Source: in.Scratch, Target: "/tmp"}} |
| m.GeneratedMounts = generatedMounts(b) |
| m.NamespaceArgs = NamespaceArguments() |
| raw, manifestHash, e := hashJSON(m) |
| @@ -675,3 +685,15 @@ func templatePath(s, path, role string) string { |
| } |
| return out.String() |
| } |
| + |
| +func (p Policy) ReadOnlyWorkspace() bool { |
| + var m effectiveManifest |
| + if json.Unmarshal(p.Manifest, &m) != nil { |
| + return true |
| + } |
| + if m.Action == "" { |
| + return false |
| + } |
| + profile, err := Profile(m.Action) |
| + return err != nil || profile.ReadOnly |
| +} |
diff --git a/internal/runner/runtime_direct.go b/internal/runner/runtime_direct.go| index 3676a424..65669ce8 100644 |
| --- a/internal/runner/runtime_direct.go |
| +++ b/internal/runner/runtime_direct.go |
| @@ -60,11 +60,18 @@ func (r *Runtime) constructDirectManifest(ctx context.Context, s provider.Select |
| } |
| func (r *Runtime) directLaunch(ctx context.Context, c RunClaim, ws workspace.Workspace, proxy *ToolProxy) (provider.Launch, func() error, error) { |
| - l, cleanup, err := r.constructDirect(ctx, selection(c.Assignment), ws.Path, c.Assignment.StepKey) |
| + action := c.Brief.Step.Action |
| + if action == "" { |
| + action = c.Assignment.StepKey |
| + } |
| + if action == "scope" && c.Brief.Target.Kind == "project_read" { |
| + action = "recommend" |
| + } |
| + l, cleanup, err := r.constructDirect(ctx, selection(c.Assignment), ws.Path, action) |
| if err != nil { |
| return l, cleanup, err |
| } |
| - if r.verifyRelease() != nil || c.Assignment.Selection.Isolation.Status != "confined" || !certifiedDirect(l.Selection.Provider, l.Binding.Expected.ProviderVersion, l.Policy.Hash) { |
| + if r.verifyRelease() != nil || c.Assignment.Selection.Isolation.Status != "confined" || !release.BuildManifest().ActionCertified(l.Selection.Provider, action, l.Binding.Expected.ProviderVersion, l.Policy.Hash) { |
| return l, cleanup, provider.ErrPolicy |
| } |
| l.AttemptKey = attemptKey(c.Scope, c.Handle) + "/model" |
| @@ -89,7 +96,7 @@ func (r *Runtime) discoverNamespaces(ctx context.Context) ([]runnerproto.Connect |
| if err == nil { |
| report.IsolationConfigHash = l.Policy.Hash |
| // Certification is a release gate. Do not advertise an uncertified route. |
| - if r.verifyRelease() == nil && certifiedDirect(b.Provider, b.ExpectedIdentity.ProviderVersion, l.Policy.Hash) { |
| + if r.verifyRelease() == nil && release.BuildManifest().ActionCertified(b.Provider, "implement", b.ExpectedIdentity.ProviderVersion, l.Policy.Hash) { |
| _, err = r.launchers[b.Provider].Preflight(ctx, l.Binding, l.Policy) |
| if err == nil { |
| report.Available = true |
diff --git a/internal/runner/runtime_workflow.go b/internal/runner/runtime_workflow.go| index 6dcdacd0..e97e59f0 100644 |
| --- a/internal/runner/runtime_workflow.go |
| +++ b/internal/runner/runtime_workflow.go |
| @@ -98,7 +98,11 @@ func (r *Runtime) wire(ctx context.Context) error { |
| } |
| return team.GitCandidate{}, provider.ErrIdentity |
| } |
| - return checks.New(checks.Config{ScratchRoot: r.cfg.WorkspaceRoot, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(repro)), Reproduction: func(_ context.Context, hash string) (checks.Reproduction, error) { |
| + recipeHash := "" |
| + if d.Render != nil { |
| + recipeHash = checks.Digest(marshal(d.Render)) |
| + } |
| + return checks.New(checks.Config{RenderRecipeHash: recipeHash, ScratchRoot: r.cfg.WorkspaceRoot, Scope: c.Scope, Handle: c.Handle, Deadline: deadline, Policy: policy, DefinitionHash: checks.Digest(marshal(d)), ReproductionHash: checks.Digest(marshal(repro)), Reproduction: func(_ context.Context, hash string) (checks.Reproduction, error) { |
| if hash != checks.Digest(marshal(repro)) { |
| return checks.Reproduction{}, provider.ErrIdentity |
| } |
| @@ -165,7 +169,15 @@ func (r *Runtime) wire(ctx context.Context) error { |
| return r.api.Call(ctx, "validate", claimRequest(c, "publish-validate"), nil) |
| }, Export: manager.ExportCandidate, Credential: credentials.credential, Description: forge.NewDescriptionTransport(nil, forge.NewCommandDescriptionWriter(r.cfg.AmadanPath, r.cfg.ScratchRoot))}) |
| } |
| - workflow, err := NewBugWorkflow(BugWorkflowConfig{Workspaces: manager, Launchers: r.launchers, Namespaces: r.namespaces, Launch: r.directLaunch, Witness: w, Policy: r.policy, Executor: executor, PublisherFor: publisherFor, StateDir: r.cfg.StateDir, Executable: r.cfg.Executable, InstanceID: r.cfg.InstanceID, Copy: r.cfg.Copy}) |
| + workflow, err := NewPlanWorkflow(BugWorkflowConfig{UploadBlob: func(ctx context.Context, c RunClaim, hash string, raw []byte) error { |
| + token, err := r.api.token(c.Assignment.ID, false) |
| + if err != nil { |
| + return err |
| + } |
| + return retryAuthority(ctx, func() error { |
| + return r.api.post(ctx, "blobs", runnerproto.BlobRequest{Version: 2, Scope: c.Scope, Handle: c.Handle, Digest: hash, Bytes: raw}, token, nil) |
| + }) |
| + }, Workspaces: manager, Launchers: r.launchers, Namespaces: r.namespaces, Launch: r.directLaunch, Witness: w, Policy: r.policy, Executor: executor, PublisherFor: publisherFor, StateDir: r.cfg.StateDir, Executable: r.cfg.Executable, InstanceID: r.cfg.InstanceID, Copy: r.cfg.Copy}) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go| index 76e8979c..c9fbc752 100644 |
| --- a/internal/runner/supervisor.go |
| +++ b/internal/runner/supervisor.go |
| @@ -187,7 +187,7 @@ func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, |
| } |
| } |
| _, cleanupErr := s.cleanup(cleanupCtx, r) |
| - if err == nil && cleanupErr == nil && r.Claim.Assignment.StepKey == "publish" { |
| + if err == nil && cleanupErr == nil && (r.Claim.Assignment.StepKey == "publish" || r.Claim.Brief.Target.Kind == team.TargetProjectRead) { |
| cleanupErr = s.api.Call(cleanupCtx, "conclude", r.request("conclude"), nil) |
| } |
| return errors.Join(err, bookkeepingErr, cleanupErr) |
| @@ -374,6 +374,12 @@ func (s *Supervisor) Recover(ctx context.Context) error { |
| if restore, ok := s.api.(interface{ RestoreClaim(RunClaim) error }); ok { |
| failures = errors.Join(failures, restore.RestoreClaim(r.Claim)) |
| } |
| + if r.Claim.Brief.Target.Kind == team.TargetProjectRead && r.Phase == "delivering-answer" { |
| + if err := s.recoverReadAnswer(ctx, r); err != nil { |
| + failures = errors.Join(failures, err) |
| + continue |
| + } |
| + } |
| if r.Phase != "contained" { |
| if r.Direct { |
| if r.InFlightAction != 0 { |
| @@ -394,7 +400,7 @@ func (s *Supervisor) Recover(ctx context.Context) error { |
| continue |
| } |
| } |
| - if r.Claim.Assignment.StepKey == "publish" && r.FailurePhase == "" { |
| + if (r.Claim.Assignment.StepKey == "publish" || r.Claim.Brief.Target.Kind == team.TargetProjectRead) && r.FailurePhase == "" { |
| failures = errors.Join(failures, s.api.Call(ctx, "conclude", r.request("conclude"), nil)) |
| } |
| } |
diff --git a/internal/runner/tool_journal.go b/internal/runner/tool_journal.go| index ffcca7ec..2b26f048 100644 |
| --- a/internal/runner/tool_journal.go |
| +++ b/internal/runner/tool_journal.go |
| @@ -168,3 +168,28 @@ func (j *Journal) validateToolReplay(ctx context.Context, v ToolSubmission) erro |
| } |
| return nil |
| } |
| + |
| +func (j *Journal) toolSlot(ctx context.Context, b ToolBinding, id, name string, args json.RawMessage) error { |
| + rows, err := j.db.QueryContext(ctx, `SELECT body FROM journal_tools WHERE acked=0 AND json_extract(body,'$.instance_id')=? AND json_extract(body,'$.task_id')=? AND json_extract(body,'$.attempt')=? AND json_extract(body,'$.fence')=? AND json_extract(body,'$.request_id')<>?`, b.InstanceID, b.TaskID, b.Attempt, b.Fence, id) |
| + if err != nil { |
| + return err |
| + } |
| + defer rows.Close() |
| + count := 0 |
| + for rows.Next() { |
| + count++ |
| + var raw []byte |
| + if err = rows.Scan(&raw); err != nil { |
| + return err |
| + } |
| + var old ToolSubmission |
| + if json.Unmarshal(raw, &old) != nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + var before, after CandidateSubmission |
| + if count > 1 || name != "submit_render" || old.Name != "submit_candidate" || old.Agent != b.Agent || json.Unmarshal(old.Arguments, &before) != nil || json.Unmarshal(args, &after) != nil || before != after { |
| + return runnerproto.ErrInvalid |
| + } |
| + } |
| + return rows.Err() |
| +} |
diff --git a/internal/runner/tool_proxy.go b/internal/runner/tool_proxy.go| index e9862db3..b1443b9b 100644 |
| --- a/internal/runner/tool_proxy.go |
| +++ b/internal/runner/tool_proxy.go |
| @@ -44,7 +44,7 @@ func openToolProxy(ctx context.Context, b ToolBinding, root string) (*ToolProxy, |
| return nil, runnerproto.ErrInvalid |
| } |
| for _, name := range b.Tools { |
| - if !slices.Contains([]string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction"}, name) { |
| + if !slices.Contains([]string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction", "submit_acceptance", "submit_answer", "submit_render"}, name) { |
| return nil, runnerproto.ErrInvalid |
| } |
| } |
| @@ -289,6 +289,9 @@ func (p *ToolProxy) ValidateApproval(ctx context.Context, q ToolSubmission) erro |
| if err := validateToolArguments(q.Name, q.Arguments); err != nil { |
| return err |
| } |
| + if err := b.Journal.toolSlot(ctx, b, q.RequestID, q.Name, q.Arguments); err != nil { |
| + return err |
| + } |
| if err := b.Journal.validateToolReplay(ctx, q); err != nil { |
| return err |
| } |
diff --git a/internal/runner/tool_socket.go b/internal/runner/tool_socket.go| index c7211b99..fe8fa152 100644 |
| --- a/internal/runner/tool_socket.go |
| +++ b/internal/runner/tool_socket.go |
| @@ -123,7 +123,7 @@ func serveAttemptSocket(ctx context.Context, path string, b ToolBinding, pending |
| return nil, runnerproto.ErrInvalid |
| } |
| for _, name := range b.Tools { |
| - if !slices.Contains([]string{"submit_reproduction", "submit_candidate", "submit_review", "ask_person"}, name) { |
| + if !slices.Contains([]string{"submit_reproduction", "submit_candidate", "submit_review", "submit_acceptance", "submit_answer", "submit_render", "ask_person"}, name) { |
| return nil, runnerproto.ErrInvalid |
| } |
| } |
| @@ -358,15 +358,8 @@ func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error { |
| s.invalidateLocked() |
| return err |
| } |
| - var pending int |
| - if err := b.Journal.db.QueryRowContext(ctx, `SELECT count(*) FROM journal_tools WHERE acked=0 |
| - AND json_extract(body,'$.instance_id')=? AND json_extract(body,'$.task_id')=? |
| - AND json_extract(body,'$.attempt')=? AND json_extract(body,'$.fence')=? |
| - AND json_extract(body,'$.request_id')<>?`, b.InstanceID, b.TaskID, b.Attempt, b.Fence, q.RequestID).Scan(&pending); err != nil { |
| - return b.Journal.storageFailure(ctx, err) |
| - } |
| - if pending > 0 { |
| - return runnerproto.ErrInvalid |
| + if err := b.Journal.toolSlot(ctx, b, q.RequestID, q.Name, q.Arguments); err != nil { |
| + return err |
| } |
| value := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, RequestID: q.RequestID, Name: q.Name, Arguments: RedactJSON(q.Arguments, []string{s.capability.Secret}), Agent: b.Agent, Isolation: b.Isolation} |
| if err := b.Journal.appendTool(ctx, value, runnerproto.EventHash(json.RawMessage(q.Arguments))); err != nil { |
diff --git a/internal/runner/tools.go b/internal/runner/tools.go| index 6df9f3f9..a16740a6 100644 |
| --- a/internal/runner/tools.go |
| +++ b/internal/runner/tools.go |
| @@ -13,15 +13,17 @@ import ( |
| "unicode/utf8" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| ) |
| type ToolCopy struct { |
| - Accepted string `json:"accepted"` |
| - Rejected string `json:"rejected"` |
| - Ask string `json:"ask"` |
| - Candidate string `json:"candidate"` |
| - Review string `json:"review"` |
| - Reproduction string `json:"reproduction"` |
| + Acceptance, Answer, Render string |
| + Accepted string `json:"accepted"` |
| + Rejected string `json:"rejected"` |
| + Ask string `json:"ask"` |
| + Candidate string `json:"candidate"` |
| + Review string `json:"review"` |
| + Reproduction string `json:"reproduction"` |
| } |
| type CandidateSubmission struct { |
| @@ -48,7 +50,12 @@ func validateToolArguments(name string, raw json.RawMessage) error { |
| if decode(&v) != nil || strings.TrimSpace(v.Question) == "" || len(v.Question) > 8192 || !utf8.ValidString(v.Question) { |
| return runnerproto.ErrInvalid |
| } |
| - case "submit_candidate": |
| + case "submit_answer": |
| + var v taskplan.AnswerResult |
| + if decode(&v) != nil || taskplan.ValidateAnswer(v) != nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + case "submit_candidate", "submit_render": |
| var v CandidateSubmission |
| if decode(&v) != nil || !commit(v.Commit) { |
| return runnerproto.ErrInvalid |
| @@ -63,7 +70,7 @@ func validateToolArguments(name string, raw json.RawMessage) error { |
| return runnerproto.ErrInvalid |
| } |
| } |
| - case "submit_reproduction": |
| + case "submit_reproduction", "submit_acceptance": |
| var v runnerproto.Reproduction |
| if decode(&v) != nil || strings.TrimSpace(v.ExpectedSymptom) == "" || len(v.ExpectedSymptom) > 8192 || len(v.Files) == 0 || len(v.Files) > 32 || len(v.TestNames) == 0 { |
| return runnerproto.ErrInvalid |
| @@ -247,19 +254,30 @@ func toolSchemas(names []string, copy ToolCopy) []any { |
| case "ask_person": |
| description = copy.Ask |
| field("question", text) |
| - case "submit_candidate": |
| + case "submit_candidate", "submit_render": |
| description = copy.Candidate |
| + if name == "submit_render" { |
| + description = copy.Render |
| + } |
| field("commit", commit) |
| case "submit_review": |
| description = copy.Review |
| field("candidate", commit) |
| field("decision", map[string]any{"type": "string", "enum": []string{"approve", "changes_requested"}}) |
| field("findings", map[string]any{"type": "array", "items": text}) |
| - case "submit_reproduction": |
| + case "submit_reproduction", "submit_acceptance": |
| description = copy.Reproduction |
| + if name == "submit_acceptance" { |
| + description = copy.Acceptance |
| + } |
| field("expected_symptom", text) |
| field("files", map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"path": text, "bytes": text}, "required": []string{"path", "bytes"}, "additionalProperties": false}}) |
| field("test_names", map[string]any{"type": "array", "items": map[string]any{"type": "object", "properties": map[string]any{"package": text, "name": text}, "required": []string{"package", "name"}, "additionalProperties": false}}) |
| + case "submit_answer": |
| + description = copy.Answer |
| + field("body", text) |
| + field("sources", map[string]any{"type": "array", "minItems": 1, "maxItems": 100, "items": map[string]any{"type": "object", "properties": map[string]any{"kind": text, "id": text, "hash": map[string]any{"type": "string", "pattern": "^[a-f0-9]{64}$"}, "revision": map[string]any{"type": "integer", "minimum": 1}}, "required": []string{"kind", "id", "hash", "revision"}, "additionalProperties": false}}) |
| + |
| default: |
| continue |
| } |
diff --git a/internal/runner/turn_prompt.go b/internal/runner/turn_prompt.go| index b1596625..405800da 100644 |
| --- a/internal/runner/turn_prompt.go |
| +++ b/internal/runner/turn_prompt.go |
| @@ -2,65 +2,18 @@ package runner |
| import ( |
| "encoding/json" |
| - "errors" |
| - "unicode/utf8" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/planflow" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| - "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| -var ErrPromptTooLarge = errors.New("runner.prompt_too_large") |
| +var ErrPromptTooLarge = planflow.ErrPromptTooLarge |
| -const maxTurnPromptBytes = 24 << 10 |
| - |
| -type promptFile struct { |
| - Path string `json:"path"` |
| - Text string `json:"text"` |
| -} |
| -type turnPrompt struct { |
| - Step string |
| - Instructions string `json:"instructions"` |
| - StandingInstructions string `json:"standing_instructions"` |
| - Target team.TargetBinding `json:"target"` |
| - ExpectedSymptom string `json:"expected_symptom,omitempty"` |
| - Files []promptFile `json:"reproduction_files,omitempty"` |
| - Tests []team.TestIdentity `json:"reproduction_tests,omitempty"` |
| - CandidateCommit string `json:"candidate_commit,omitempty"` |
| -} |
| +const maxTurnPromptBytes = planflow.MaxPromptBytes |
| func buildTurnPrompt(c RunClaim, artifacts []team.Artifact) (string, error) { |
| - p := turnPrompt{Step: c.Assignment.StepKey, Instructions: c.Brief.Instructions, StandingInstructions: c.Brief.StandingInstructions, Target: c.Brief.Target} |
| - for _, a := range artifacts { |
| - switch a.Role { |
| - case team.RoleReproduction: |
| - var r runnerproto.Reproduction |
| - if err := json.Unmarshal(a.Payload, &r); err != nil { |
| - return "", err |
| - } |
| - p.ExpectedSymptom, p.Tests = r.ExpectedSymptom, r.TestNames |
| - for _, f := range r.Files { |
| - if !utf8.Valid(f.Bytes) { |
| - return "", runnerproto.ErrInvalid |
| - } |
| - p.Files = append(p.Files, promptFile{f.Path, string(f.Bytes)}) |
| - } |
| - case team.RoleCandidate: |
| - var candidate team.GitCandidate |
| - if err := json.Unmarshal(a.Payload, &candidate); err != nil { |
| - return "", err |
| - } |
| - p.CandidateCommit = candidate.Commit |
| - } |
| - } |
| - raw, err := json.Marshal(p) |
| - if err != nil { |
| - return "", err |
| - } |
| - if len(raw) > maxTurnPromptBytes { |
| - return "", ErrPromptTooLarge |
| - } |
| - return string(raw), nil |
| + return planflow.Prompt(c.Assignment, c.Brief, artifacts) |
| } |
| func turnIntentPayload(providerName, model, prompt string) ([]byte, error) { |
| quoted, err := json.Marshal(prompt) |
diff --git a/internal/runner/workflow.go b/internal/runner/workflow.go| index e1c1e93b..9c661ef1 100644 |
| --- a/internal/runner/workflow.go |
| +++ b/internal/runner/workflow.go |
| @@ -13,12 +13,14 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/runner/planflow" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| type BugWorkflowConfig struct { |
| + UploadBlob func(context.Context, RunClaim, string, []byte) error |
| Launchers map[string]provider.Launcher |
| Namespaces *containment.Manager |
| Launch func(context.Context, RunClaim, workspace.Workspace, *ToolProxy) (provider.Launch, func() error, error) |
| @@ -32,9 +34,18 @@ type BugWorkflowConfig struct { |
| StateDir, Executable, InstanceID string |
| Copy ToolCopy |
| } |
| -type BugWorkflow struct{ cfg BugWorkflowConfig } |
| +type PlanWorkflow struct{ cfg BugWorkflowConfig } |
| +type BugWorkflow = PlanWorkflow |
| -func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) { |
| +func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) { return NewPlanWorkflow(c) } |
| +func (w *PlanWorkflow) Run(ctx context.Context, s *Supervisor, c RunClaim) error { |
| + if s == nil || s.workflow != w { |
| + return provider.ErrContract |
| + } |
| + return s.Run(ctx, c) |
| +} |
| + |
| +func NewPlanWorkflow(c BugWorkflowConfig) (*PlanWorkflow, error) { |
| if c.Workspaces == nil || (len(c.Launchers) != 2 || c.Launchers["claude"] == nil || c.Launchers["codex"] == nil || c.Namespaces == nil || c.Launch == nil) || c.Witness == nil || c.Policy == nil || c.Executor == nil || (c.Publisher == nil && c.PublisherFor == nil) || !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || !filepath.IsAbs(c.Executable) || filepath.Clean(c.Executable) != c.Executable || c.InstanceID == "" { |
| return nil, provider.ErrContract |
| } |
| @@ -78,6 +89,19 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| r.Phase = "prepared" |
| return s.save(ctx, r) |
| } |
| + if r.Claim.Brief.Step.PlanRevision == 0 { |
| + r.Claim.Brief.Step = planflow.LegacyStep(r.Claim.Assignment.StepKey) |
| + r.Claim.Brief.Step.ArtifactHashes = append([]string(nil), r.Claim.Brief.ArtifactHashes...) |
| + } |
| + profile, err := planflow.Validate(r.Claim.Assignment, r.Claim.Brief) |
| + if err != nil { |
| + return err |
| + } |
| + step := profile.Action |
| + readWork := r.Claim.Brief.Target.Kind == team.TargetProjectRead |
| + if readWork && profile.Submission != "submit_answer" { |
| + return provider.ErrPolicy |
| + } |
| r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: attemptKey(r.Claim.Scope, r.Claim.Handle), Workspace: provider.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}} |
| r.Phase = "creating-workspace" |
| if err := s.save(ctx, r); err != nil { |
| @@ -119,7 +143,6 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| s.mu.Lock() |
| s.activeCurrent = current |
| s.mu.Unlock() |
| - step := r.Claim.Assignment.StepKey |
| var artifacts []team.Artifact |
| if err = s.api.Call(ctx, "evidence", r.request("evidence"), &artifacts); err != nil { |
| return err |
| @@ -136,8 +159,11 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| } |
| artifacts[i] = full |
| } |
| + if err = planflow.Artifacts(r.Claim.Brief, artifacts); err != nil { |
| + return err |
| + } |
| var definition checks.Definition |
| - if json.Unmarshal(r.Claim.Brief.CheckDefinition, &definition) != nil { |
| + if !readWork && json.Unmarshal(r.Claim.Brief.CheckDefinition, &definition) != nil { |
| return provider.ErrIdentity |
| } |
| var reproduction checks.Reproduction |
| @@ -145,7 +171,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| var candidateHash string |
| for _, a := range artifacts { |
| switch a.Role { |
| - case team.RoleReproduction: |
| + case team.RoleReproduction, team.RoleAcceptance: |
| if json.Unmarshal(a.Payload, &reproduction) != nil { |
| return provider.ErrIdentity |
| } |
| @@ -156,16 +182,16 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| candidateHash = a.Hash |
| } |
| } |
| - if step == "review" { |
| + if step == "review" || (profile.Render && candidateHash != "") { |
| if candidateHash == "" { |
| return provider.ErrIdentity |
| } |
| - if err = w.cfg.Workspaces.CheckoutCandidate(ctx, ws, candidate); err != nil { |
| + if err = w.cfg.Workspaces.ContinueCandidate(ctx, ws, candidate, profile.Render); err != nil { |
| return err |
| } |
| } |
| - if step == "reproduce" || step == "implement" || step == "review" { |
| + if profile.Submission != "" { |
| if err = w.directModel(ctx, s, r, l, current, ws, policy, artifacts); err != nil { |
| return err |
| } |
| @@ -179,7 +205,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| return team.Artifact{}, err |
| } |
| spec := team.ArtifactSpec{Role: role, MediaType: "application/json", Payload: raw} |
| - if role == team.RoleBaseResult || role == team.RoleCandidateResult || role == team.RoleRepositoryChecks { |
| + if role == team.RoleRender || role == team.RoleBaseResult || role == team.RoleCandidateResult || role == team.RoleRepositoryChecks { |
| if _, err = w.cfg.Witness.ExecutorEvidence(ctx, nil, r.Claim.Scope, r.Claim.Handle, spec); err != nil { |
| return team.Artifact{}, err |
| } |
| @@ -187,6 +213,11 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if role == team.RoleCandidate { |
| spec.MediaType = team.GitCandidateMediaType |
| } |
| + if role == team.RoleAnswer { |
| + if err = w.cfg.Witness.record(ctx, "read-answer", attemptKey(r.Claim.Scope, r.Claim.Handle), spec); err != nil { |
| + return team.Artifact{}, err |
| + } |
| + } |
| if err = w.cfg.Witness.recordArtifact(ctx, r.Claim, spec); err != nil { |
| return team.Artifact{}, err |
| } |
| @@ -196,13 +227,13 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| err = s.api.Call(ctx, "artifacts", q, &result) |
| return result, err |
| } |
| - if step == "reproduce" || step == "implement" || step == "review" { |
| + if profile.Submission != "" { |
| tools, err := s.journal.ToolSubmissions(ctx, 128) |
| if err != nil { |
| return err |
| } |
| var submission *ToolSubmission |
| - want := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[step] |
| + want := profile.Submission |
| for i := range tools { |
| t := &tools[i] |
| if t.Attempt == int64(r.Claim.Handle.Attempt) && t.Fence == r.Claim.Handle.Fence && t.TaskID == r.Claim.Assignment.TaskID && t.Agent == r.Agent && t.Name == want { |
| @@ -215,21 +246,25 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if submission == nil { |
| return provider.ErrUncertain |
| } |
| - switch step { |
| - case "reproduce": |
| + switch profile.Submission { |
| + case "submit_reproduction", "submit_acceptance": |
| if err = json.Unmarshal(submission.Arguments, &reproduction); err != nil { |
| return err |
| } |
| - art, err := register(team.RoleReproduction, reproduction) |
| + role := team.RoleReproduction |
| + if step == "scope" { |
| + role = team.RoleAcceptance |
| + } |
| + art, err := register(role, reproduction) |
| if err != nil { |
| return err |
| } |
| q := r.request("freeze") |
| q.Prepared, _ = json.Marshal(runnerproto.FreezeRequest{ExpectedSymptom: reproduction.ExpectedSymptom, DefinitionHash: checks.Digest(marshal(definition)), ReproductionHash: art.Hash}) |
| - if err = s.api.Call(ctx, "freeze", q, nil); err != nil { |
| + if err = s.api.Call(ctx, map[bool]string{true: "freeze_feature", false: "freeze"}[step == "scope"], q, nil); err != nil { |
| return err |
| } |
| - case "implement": |
| + case "submit_candidate": |
| var submitted CandidateSubmission |
| if json.Unmarshal(submission.Arguments, &submitted) != nil { |
| return provider.ErrIdentity |
| @@ -241,10 +276,28 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if candidate.Commit != submitted.Commit { |
| return provider.ErrIdentity |
| } |
| - if _, err = register(team.RoleCandidate, candidate); err != nil { |
| + art, err := register(team.RoleCandidate, candidate) |
| + if err != nil { |
| + return err |
| + } |
| + if err = w.renderRequested(ctx, s, r, tools, candidate, art.Hash, definition, reproduction, register); err != nil { |
| + return err |
| + } |
| + case "submit_answer": |
| + r.Phase = "delivering-answer" |
| + if err = s.save(ctx, r); err != nil { |
| + return err |
| + } |
| + s.stopLeaseWatch() |
| + var answer team.AnswerResult |
| + if json.Unmarshal(submission.Arguments, &answer) != nil { |
| + return provider.ErrIdentity |
| + } |
| + if _, err = register(team.RoleAnswer, answer); err != nil { |
| return err |
| } |
| - case "review": |
| + |
| + case "submit_review": |
| var review ReviewSubmission |
| if json.Unmarshal(submission.Arguments, &review) != nil || review.Candidate != candidate.Commit { |
| return provider.ErrIdentity |
| @@ -259,14 +312,18 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if err = s.journal.AckTool(ctx, *submission); err != nil { |
| return err |
| } |
| + if readWork { |
| + r.Phase = "completed" |
| + return s.save(ctx, r) |
| + } |
| } |
| - if step == "verify" || step == "publish" { |
| + if step == "checks" || step == "publish" { |
| provenance := team.Provenance{Producer: "equipo-runner", Provider: r.Claim.Assignment.Selection.Provider, ModelFamily: r.Claim.Assignment.Selection.Family, Context: attemptKey(r.Claim.Scope, r.Claim.Handle)} |
| if err = w.cfg.Witness.record(ctx, "runner-provenance", attemptKey(r.Claim.Scope, r.Claim.Handle), provenance); err != nil { |
| return err |
| } |
| } |
| - if step == "reproduce" || step == "verify" { |
| + if step == "reproduce" || step == "scope" || step == "checks" { |
| executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, r.Claim.AttemptDeadline) |
| if err != nil { |
| @@ -275,7 +332,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| w.cfg.Witness.installExecutor(r.Claim, executor) |
| commit, subject := definition.Base, "" |
| role := team.RoleBaseResult |
| - if step == "verify" { |
| + if step == "checks" { |
| commit, subject, role = candidate.Commit, candidateHash, team.RoleCandidateResult |
| } |
| result, err := executor.Reproduce(ctx, definition, reproduction, commit, subject) |
| @@ -285,7 +342,7 @@ func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l |
| if _, err = register(role, result); err != nil { |
| return err |
| } |
| - if step == "verify" { |
| + if step == "checks" { |
| result, err := executor.RepositoryChecks(ctx, definition, candidate, candidateHash) |
| if err != nil { |
| return err |
diff --git a/internal/runner/workspace/read.go b/internal/runner/workspace/read.go| new file mode 100644 |
| index 00000000..38e89ea6 |
| --- /dev/null |
| +++ b/internal/runner/workspace/read.go |
| @@ -0,0 +1,110 @@ |
| +package workspace |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| +) |
| + |
| +func (m *Manager) createRead(ctx context.Context, a runnerproto.Assignment, b runnerproto.RunnerBrief) (Workspace, error) { |
| + if a.ID == "" || a.TaskID == "" || a.WorkspaceKey == "" || digest(a.Selection) != digest(b.Selection) { |
| + return Workspace{}, provider.ErrIdentity |
| + } |
| + policy, err := m.preflight(ctx, a) |
| + if err != nil { |
| + return Workspace{}, err |
| + } |
| + path := filepath.Join(m.cfg.WorkspaceRoot, "read-"+digest(a.WorkspaceKey)) |
| + dir := filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(a.WorkspaceKey)) |
| + if err = os.Mkdir(dir, 0700); err != nil { |
| + return Workspace{}, provider.ErrUncertain |
| + } |
| + if err = os.Mkdir(path, 0700); err != nil { |
| + return Workspace{}, err |
| + } |
| + if b.Target.Kind == team.TargetProjectRead { |
| + if b.Target.Ref != "" || len(b.Sources) == 0 { |
| + return Workspace{}, provider.ErrIdentity |
| + } |
| + for _, src := range b.Sources { |
| + if team.ContentDigest(src.Payload) != src.Ref.Hash { |
| + return Workspace{}, provider.ErrIdentity |
| + } |
| + } |
| + raw, err := json.Marshal(b.Sources) |
| + if err != nil { |
| + return Workspace{}, err |
| + } |
| + if err = os.WriteFile(filepath.Join(path, "sources.json"), raw, 0400); err != nil { |
| + return Workspace{}, err |
| + } |
| + } else { |
| + if !m.validTarget(ctx, b.Target, true) { |
| + return Workspace{}, provider.ErrIdentity |
| + } |
| + repo, _, err := m.fetch(ctx, b.Target) |
| + if err != nil { |
| + return Workspace{}, err |
| + } |
| + if err = m.init(ctx, path, objectFormat(b.Target.BaseRevision), false); err != nil { |
| + return Workspace{}, err |
| + } |
| + if err = copyObjects(filepath.Join(repo, "objects"), filepath.Join(path, ".git", "objects")); err != nil { |
| + return Workspace{}, err |
| + } |
| + if _, err = m.run(ctx, path, "checkout", "--detach", b.Target.BaseRevision); err != nil { |
| + return Workspace{}, err |
| + } |
| + if err = os.RemoveAll(filepath.Join(path, ".git")); err != nil { |
| + return Workspace{}, err |
| + } |
| + } |
| + hash, err := readHash(path) |
| + if err != nil { |
| + return Workspace{}, err |
| + } |
| + at := attempt{Local: true, ReadOnly: true, ContentHash: hash, AssignmentHash: digest(a), Hash: digest(b), Request: provider.WorkspaceRequest{Path: path, ReadPolicy: policy}, Workspace: provider.Workspace{WorkspaceID: a.WorkspaceKey, Path: path}, Target: b.Target, ArtifactHashes: b.ArtifactHashes, Isolation: a.Selection.Isolation} |
| + if err = save(filepath.Join(dir, "attempt.json"), at); err != nil { |
| + return Workspace{}, err |
| + } |
| + return localWorkspace(at, a.WorkspaceKey), nil |
| +} |
| +func readHash(root string) (string, error) { |
| + files := map[string]string{} |
| + err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + if d.IsDir() { |
| + return nil |
| + } |
| + if !d.Type().IsRegular() { |
| + return provider.ErrIdentity |
| + } |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return err |
| + } |
| + rel, err := filepath.Rel(root, path) |
| + if err != nil { |
| + return err |
| + } |
| + files[rel] = team.ContentDigest(raw) |
| + return nil |
| + }) |
| + return digest(files), err |
| +} |
| +func validateRead(at attempt) error { |
| + if !allowed(at.Workspace.Path, at.Request.ReadPolicy) { |
| + return provider.ErrPolicy |
| + } |
| + h, err := readHash(at.Workspace.Path) |
| + if err != nil || h != at.ContentHash { |
| + return provider.ErrIdentity |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go| index 128534de..04d117e4 100644 |
| --- a/internal/runner/workspace/workspace.go |
| +++ b/internal/runner/workspace/workspace.go |
| @@ -57,6 +57,8 @@ type Workspace struct { |
| key string |
| } |
| type attempt struct { |
| + ReadOnly bool |
| + ContentHash string |
| Local bool |
| ConfigHash string |
| AssignmentHash string |
| @@ -367,6 +369,9 @@ func (m *Manager) Create(ctx context.Context, a runnerproto.Assignment, brief ru |
| m.mu.Lock() |
| defer m.mu.Unlock() |
| var zero Workspace |
| + if brief.Target.Kind == team.TargetProjectRead || brief.Step.Action == "scope" { |
| + return m.createRead(ctx, a, brief) |
| + } |
| if a.ID == "" || a.TaskID == "" || a.WorkspaceKey == "" || a.StepKey == "" || !reflect.DeepEqual(a.Selection, brief.Selection) || !m.validTarget(ctx, brief.Target, true) { |
| return zero, provider.ErrContract |
| } |
| @@ -500,6 +505,9 @@ func (m *Manager) gitdir(at attempt) (string, error) { |
| } |
| func (m *Manager) validateWorkspace(at attempt) error { |
| + if at.ReadOnly { |
| + return validateRead(at) |
| + } |
| for _, p := range []string{at.Workspace.Path, at.Request.Path, filepath.Join(at.Request.Path, ".git")} { |
| r, e := canonical(p) |
| if e != nil || r != p || !allowed(p, at.Request.ReadPolicy) { |
| @@ -855,6 +863,9 @@ func (m *Manager) ValidateTurn(ctx context.Context, a runnerproto.Assignment, w |
| // CheckoutCandidate installs only a previously captured immutable candidate in |
| // a fresh review workspace before any agent is created. |
| func (m *Manager) CheckoutCandidate(ctx context.Context, w Workspace, c GitCandidate) error { |
| + return m.ContinueCandidate(ctx, w, c, false) |
| +} |
| +func (m *Manager) ContinueCandidate(ctx context.Context, w Workspace, c GitCandidate, build bool) error { |
| m.mu.Lock() |
| defer m.mu.Unlock() |
| var at attempt |
| @@ -872,7 +883,11 @@ func (m *Manager) CheckoutCandidate(ctx context.Context, w Workspace, c GitCandi |
| if err := copyObjects(filepath.Join(source, "objects"), filepath.Join(at.Request.Path, ".git", "objects")); err != nil { |
| return err |
| } |
| - if _, err := m.run(ctx, w.Path, "checkout", "--detach", c.Commit); err != nil { |
| + args := []string{"checkout", "--detach", c.Commit} |
| + if build { |
| + args = []string{"checkout", "-B", at.Target.Ref, c.Commit} |
| + } |
| + if _, err := m.run(ctx, w.Path, args...); err != nil { |
| return err |
| } |
| tree, err := m.run(ctx, w.Path, "rev-parse", "HEAD^{tree}") |
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go| index 3e530850..6051000b 100644 |
| --- a/internal/runnerproto/types.go |
| +++ b/internal/runnerproto/types.go |
| @@ -150,16 +150,30 @@ type Assignment struct { |
| Kind string `json:"kind"` |
| } |
| +type StepBrief struct { |
| + PlanRevision int64 |
| + StepKey, SpecialistKey, Action string |
| + SpecialistRevision int64 |
| + ArtifactHashes []string |
| +} |
| +type SourceSnapshot struct { |
| + Ref team.SourceRef `json:"ref"` |
| + Payload json.RawMessage `json:"payload"` |
| +} |
| type RunnerBrief struct { |
| - AttemptDeadline time.Time `json:"attempt_deadline"` |
| - CheckDefinition []byte `json:"check_definition"` |
| - Target team.TargetBinding `json:"target"` |
| - Instructions string `json:"instructions"` |
| - StandingInstructions string `json:"standing_instructions"` |
| - ConfirmedPreferences []string `json:"confirmed_preferences"` |
| - Selection Selection `json:"selection"` |
| - Policy team.Policy `json:"policy"` |
| - ArtifactHashes []string `json:"artifact_hashes"` |
| + ProjectRevision, BudgetRevision int64 |
| + Step StepBrief `json:"step"` |
| + Sources []SourceSnapshot `json:"sources,omitempty"` |
| + RenderRecipe *RenderRecipe `json:"render_recipe,omitempty"` |
| + AttemptDeadline time.Time `json:"attempt_deadline"` |
| + CheckDefinition []byte `json:"check_definition"` |
| + Target team.TargetBinding `json:"target"` |
| + Instructions string `json:"instructions"` |
| + StandingInstructions string `json:"standing_instructions"` |
| + ConfirmedPreferences []string `json:"confirmed_preferences"` |
| + Selection Selection `json:"selection"` |
| + Policy team.Policy `json:"policy"` |
| + ArtifactHashes []string `json:"artifact_hashes"` |
| } |
| type ClaimResponse struct { |
| @@ -203,6 +217,7 @@ type TestBaseline struct { |
| Hash string `json:"hash"` |
| } |
| type CheckDefinition struct { |
| + Render *RenderRecipe `json:"render,omitempty"` |
| TrustedPaths []string `json:"trusted_paths"` |
| Version int `json:"version"` |
| Repository string `json:"repository"` |