oficina / equipo Public

feat: supervise bug steps and verify cancellation containment

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 8e29ee261bcf5a802e748e794c3c7fb440571a13 parent 4b6afd6
37 files changed, +4,300 −25
  • .rastrillo/budgets.txt +3 −3
  • internal/equipo/app.go +1 −0
  • internal/equipo/cancel.go +81 −0
  • internal/equipo/runner_api.go +23 −1
  • internal/equipo/runner_execution.go +66 −5
  • internal/equipo/runner_mutations.go +34 −3
  • internal/equipo/runner_rotation.go +69 −0
  • internal/equipo/runner_supervision.go +94 −0
  • internal/equipo/task_handlers.go +20 −0
  • internal/equipo/team/scheduler.go +9 −1
  • internal/equipotest/cancel_test.go +140 −0
  • internal/equipotest/preparation_integration_test.go +177 −0
  • internal/equipotest/runner_api_test.go +2 −2
  • internal/runner/checks/ownership.go +11 −0
  • internal/runner/checks/sandbox.go +28 −2
  • internal/runner/http.go +158 −0
  • internal/runner/journal.go +1 −0
  • internal/runner/lease_linux.go +85 −0
  • internal/runner/paseo/client.go +46 −0
  • internal/runner/process_linux.go +513 −0
  • internal/runner/process_linux_test.go +302 −0
  • internal/runner/service.go +105 −0
  • internal/runner/supervisor.go +426 −0
  • internal/runner/supervisor_test.go +338 −0
  • internal/runner/tool_socket.go +38 −3
  • internal/runner/witness.go +182 −0
  • internal/runner/workflow.go +398 −0
  • internal/runner/workflow_integration_test.go +419 −0
  • internal/runner/workflow_turn.go +368 −0
  • internal/runner/workspace/workspace.go +36 −0
  • internal/runner/workspace/workspace_test.go +3 −2
  • internal/runnerproto/containment.go +45 −0
  • internal/runnerproto/ownership.go +17 −0
  • internal/runnerproto/questions.go +17 −2
  • internal/runnerproto/types.go +4 −0
  • runner/paseo/bridge.mjs +21 −1
  • runner/paseo/bridge.test.mjs +20 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 8c4b732b..be72007d 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr
time internal/equipo/team 15s Copied core crash, recovery and concurrency tests take about 7.7s idle and 13.6s on the loaded shared machine.
time internal/equipotest 25s Task 6 keeps the mandated connections tests in this package; its focused authority, isolation, atomic-write and real-session checks took 15.5s on the shared machine, above the prior 15s allowance.
-size internal/equipo 7400 - Task 14 raises 7000 after adding the mandated runner adapters, validated durable receipt lookup and publication protocol routes beside the existing runner API (7087 lines).
-size internal/equipotest - 9400 Task 13 fix round 1 keeps question renewal and stale-answer batch regressions beside the existing activation fixtures (9169 test lines).
+size internal/equipo 7700 - Task 15 adds supervisor validators, cancellation, immutable claim deadlines and lost-rotation recovery beside the existing runner API (7415 lines before final checks).
+size internal/equipotest - 9900 Task 15 keeps cancellation, real-protocol preparation crash tests and rotation recovery beside the existing activation fixtures (9455 lines before final checks).
time internal/runner/checks 15s Task 11 runs real Go fixtures and Codex sandbox sentinels, including timeout and child-process cleanup; the targeted suite took 10.710s on the shared machine.
-time internal/runner 15s Task 13 fix round 1 tests renewed socket expiry, 128 durable pending submissions and the real tool binary; its focused suite took 10.015s on the shared machine.
+time internal/runner 75s Task 15 keeps local Git workflow, real sandbox checks, publication, Linux containment and 130 fsynced report drains in this package. The supervisor group took 49.269s on the loaded shared machine, plus 12.542s for separate journal/tool regressions.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 1f1f11e5..bc320e23 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -124,6 +124,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Get("/people", a.people)
r.Get("/runners/enrol", a.enrolmentPage)
r.Post("/tasks", a.createBug)
+ r.Post("/tasks/{id}/cancel", a.cancelTask)
r.Post("/tasks/{id}/questions/{question}/answer", a.answerQuestion)
r.Post("/runners/enrol", a.approveEnrolment)
r.Post("/runners/{id}/revoke", a.revokeRunner)
diff --git a/internal/equipo/cancel.go b/internal/equipo/cancel.go
new file mode 100644
index 00000000..f43d3e54
--- /dev/null
+++ b/internal/equipo/cancel.go
@@ -0,0 +1,81 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "context"
+ "gorm.io/gorm"
+)
+
+type TaskCancellation struct {
+ Contained bool
+ InFlight int
+ Report team.CancelReport
+}
+
+func (s *Store) CancelTask(ctx context.Context, actor Actor, id string) (TaskCancellation, error) {
+ var result TaskCancellation
+ if s.execution == nil {
+ return result, ErrUnavailable
+ }
+ err := s.execution.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ member, err := currentRunnerMember(tx, actor.Address)
+ if err != nil {
+ return err
+ }
+ var task Task
+ if err = tx.First(&task, "id=?", id).Error; err != nil {
+ return storeError(err)
+ }
+ if member.Address != task.Requester && member.Role != RoleOwner {
+ return ErrForbidden
+ }
+ result.Contained = true
+ if task.JobID != 0 {
+ result.Report, err = s.execution.Core.Cancel(ctx, Scope{Account: team.AccountID(task.TeamID), Job: task.JobID}, actor.Address, "person_cancelled")
+ if err != nil {
+ return err
+ }
+ result.InFlight = len(result.Report.InFlight)
+ attempts, err := s.execution.Core.Attempts(ctx, Scope{Account: team.AccountID(task.TeamID), Job: task.JobID})
+ if err != nil {
+ return err
+ }
+ result.Contained = true
+ for _, a := range attempts {
+ if a.Containment != team.ContainmentContained {
+ result.Contained = false
+ }
+ }
+ }
+ var pending int64
+ if err = tx.Model(&runnerAssignment{}).Where("task_id=? AND state!='contained' AND claim_request!=''", id).Count(&pending).Error; err != nil {
+ return storeError(err)
+ }
+ if pending > 0 {
+ result.Contained = false
+ }
+ if err = tx.Model(&runnerAssignment{}).Where("task_id=? AND state IN ?", id, []string{"pending", "claimed", "prepared"}).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error; err != nil {
+ return storeError(err)
+ }
+ state := "cancel_requested"
+ if result.Contained {
+ state = "cancelled"
+ }
+ if err = tx.Model(&Task{}).Where("id=?", id).Select("State").Updates(&Task{State: state}).Error; err != nil {
+ return storeError(err)
+ }
+ return appendAudit(tx, actor, "task.cancel", id)
+ })
+ return result, err
+}
+
+func finishTaskCancellation(tx *gorm.DB, taskID string) error {
+ var pending int64
+ if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND state!='contained' AND claim_request!=''", taskID).Count(&pending).Error; err != nil {
+ return storeError(err)
+ }
+ if pending > 0 {
+ return nil
+ }
+ return storeError(tx.Model(&Task{}).Where("id=? AND state='cancel_requested'", taskID).Select("State").Updates(&Task{State: "cancelled"}).Error)
+}
diff --git a/internal/equipo/runner_api.go b/internal/equipo/runner_api.go
index 11661ff7..c5510327 100644
--- a/internal/equipo/runner_api.go
+++ b/internal/equipo/runner_api.go
@@ -19,7 +19,8 @@ func (s *Store) RunnerHandler() http.Handler {
r.Post("/blobs", s.runnerPutBlob)
r.Post("/blobs/read", s.runnerReadBlob)
r.Post("/claim", s.runnerClaim)
- for _, op := range []string{"publication_ready", "publication_authorize", "question_resolved", "questions", "answers", "renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} {
+ 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"} {
r.Post("/"+op, s.runnerMutation(op))
}
r.Post("/connections", s.runnerConnections)
@@ -255,3 +256,24 @@ func (s *Store) runnerReadBlob(w http.ResponseWriter, r *http.Request) {
}
runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: b})
}
+
+func (s *Store) runnerRecoverClaim(w http.ResponseWriter, r *http.Request) {
+ p, _, ok := s.runnerBearer(w, r)
+ if !ok {
+ return
+ }
+ var q ClaimRequest
+ if !runnerBody(w, r, &q, 8192) {
+ return
+ }
+ if s.execution == nil {
+ runnerFailure(w, ErrUnavailable)
+ return
+ }
+ value, err := s.execution.RecoverClaim(r.Context(), p, q)
+ if err != nil {
+ runnerFailure(w, err)
+ return
+ }
+ runnerJSON(w, 200, runnerproto.WorkResponse{Version: 1, Result: value})
+}
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go
index 9f63cd76..d0915420 100644
--- a/internal/equipo/runner_execution.go
+++ b/internal/equipo/runner_execution.go
@@ -204,6 +204,13 @@ func (e *Execution) Sync(ctx context.Context) error {
return storeError(err)
}
for _, task := range prepared {
+ var activePreparation int64
+ if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND kind='prepare' AND state!='contained' AND claim_request!=''", task.ID).Count(&activePreparation).Error; err != nil {
+ return storeError(err)
+ }
+ if activePreparation > 0 {
+ continue
+ }
var out taskOutbox
if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil {
return storeError(err)
@@ -261,6 +268,15 @@ func (e *Execution) Sync(ctx context.Context) error {
if other.Key == dep && other.State != team.StepSucceeded {
ready = false
}
+ if other.Key == dep && other.State == team.StepSucceeded {
+ var live int64
+ if err := tx.Raw("SELECT count(*) FROM attempts WHERE step_id=? AND containment='pending'", other.ID).Scan(&live).Error; err != nil {
+ return storeError(err)
+ }
+ if live > 0 {
+ ready = false
+ }
+ }
}
}
if ready {
@@ -402,7 +418,11 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest
if err := tx.Model(&runnerCleanup{}).Where("id=?", c.ID).Select("TokenHash").Updates(&runnerCleanup{TokenHash: runnerHash(runnerproto.CleanupAudience, token)}).Error; err != nil {
return storeError(err)
}
- result = ClaimResponse{Scope: value.Scope, Handle: h, Brief: brief, LeaseDeadline: a.LeaseDeadline, CleanupToken: token, CleanupExpiresAt: c.ExpiresAt, RenewSeconds: 15}
+ attemptDeadline, err := e.attemptDeadline(ctx, value.Scope, h, brief, a.LeaseDeadline)
+ if err != nil {
+ return err
+ }
+ result = ClaimResponse{AttemptDeadline: attemptDeadline, Scope: value.Scope, Handle: h, Brief: brief, LeaseDeadline: a.LeaseDeadline, CleanupToken: token, CleanupExpiresAt: c.ExpiresAt, RenewSeconds: 15}
return nil
}
if a.State != "pending" {
@@ -417,7 +437,7 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest
}
// Preparation occupies the same specialist slot before it has a core attempt.
var preparing int64
- if err := tx.Model(&runnerAssignment{}).Where("kind='prepare' AND state='claimed'").Count(&preparing).Error; err != nil {
+ if err := tx.Model(&runnerAssignment{}).Where("kind='prepare' AND state!='contained' AND claim_request!=''").Count(&preparing).Error; err != nil {
return storeError(err)
}
if preparing > 0 {
@@ -435,11 +455,20 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest
if err != nil {
return err
}
- brief := RunnerBrief{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{}}
+ 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{}}
if task.CheckDefinitionHash != "" {
+ var out taskOutbox
+ if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil {
+ return storeError(err)
+ }
+ var prepared PreparedBug
+ if json.Unmarshal([]byte(out.Prepared), &prepared) != nil {
+ return ErrUnavailable
+ }
+ brief.CheckDefinition = prepared.CheckDefinition
brief.ArtifactHashes = append(brief.ArtifactHashes, task.CheckDefinitionHash)
}
- deadline := e.store.runnerClock.Now().UTC().Add(30 * time.Second)
+ deadline := e.store.runnerClock.Now().UTC().Add(60 * time.Second)
h := team.Handle{Revision: task.Revision, Fence: a.Revision, Runner: p.RunnerID}
if a.Kind == "step" {
h, err = e.Core.Claim(ctx, value.Scope, a.StepKey, p.RunnerID, a.WorkspaceKey)
@@ -489,7 +518,11 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest
if err := tx.Model(&runnerAssignment{}).Where("id=? AND state='pending'", a.ID).Select("Brief", "AttemptID", "Fence", "LeaseDeadline", "State", "ClaimRequest").Updates(&a).Error; err != nil {
return storeError(err)
}
- result = ClaimResponse{Scope: value.Scope, Handle: h, Brief: brief, LeaseDeadline: deadline, CleanupToken: token, CleanupExpiresAt: cleanup.ExpiresAt, RenewSeconds: 15}
+ attemptDeadline, err := e.attemptDeadline(ctx, value.Scope, h, brief, deadline)
+ if err != nil {
+ return err
+ }
+ result = ClaimResponse{AttemptDeadline: attemptDeadline, Scope: value.Scope, Handle: h, Brief: brief, LeaseDeadline: deadline, CleanupToken: token, CleanupExpiresAt: cleanup.ExpiresAt, RenewSeconds: 15}
return appendAudit(tx, Actor{Address: p.Person}, "runner.claim", a.ID)
})
if err != nil {
@@ -497,3 +530,31 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest
}
return result, nil
}
+
+func (e *Execution) attemptDeadline(ctx context.Context, scope Scope, h team.Handle, brief RunnerBrief, lease time.Time) (time.Time, error) {
+ if h.Attempt == 0 {
+ if brief.AttemptDeadline.IsZero() {
+ return time.Time{}, ErrUnavailable
+ }
+ return brief.AttemptDeadline, nil
+ }
+ job, err := e.Core.GetJob(ctx, scope)
+ if err != nil {
+ return time.Time{}, err
+ }
+ attempts, err := e.Core.Attempts(ctx, scope)
+ if err != nil {
+ return time.Time{}, err
+ }
+ for _, a := range attempts {
+ if a.ID == h.Attempt {
+ end := a.CreatedAt.Add(time.Duration(brief.Policy.AttemptSeconds) * time.Second)
+ jobEnd := job.CreatedAt.Add(time.Duration(brief.Policy.JobSeconds) * time.Second)
+ if jobEnd.Before(end) {
+ end = jobEnd
+ }
+ return end, nil
+ }
+ }
+ return time.Time{}, ErrUnavailable
+}
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go
index 12216056..e728bc56 100644
--- a/internal/equipo/runner_mutations.go
+++ b/internal/equipo/runner_mutations.go
@@ -48,7 +48,7 @@ func (e *Execution) Mutate(ctx context.Context, p RunnerPrincipal, op string, q
if !binding(a, q) {
return ErrForbidden
}
- historical := op == "receipts" || op == "lost" || op == "contained"
+ historical := op == "conclude" || op == "receipts" || op == "lost" || op == "contained"
value, err := assignmentValue(a)
if err != nil {
return err
@@ -94,6 +94,10 @@ func (e *Execution) Cleanup(ctx context.Context, token, op string, q RunnerReque
return nil, ErrForbidden
}
if op == "contained" {
+ rotation, found, err := e.recoverRotation(ctx, token, q)
+ if found || err != nil {
+ return rotation, err
+ }
if err := e.containmentBarrier(ctx, RunnerPrincipal{}, token, q); err != nil {
return nil, err
}
@@ -166,6 +170,24 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
}
}
switch op {
+ case "validate":
+ return value.Selection, nil
+ case "conclude":
+ return e.concludeAt(ctx, tx, a, q)
+ case "evidence":
+ if a.Kind != "step" {
+ return nil, ErrInvalid
+ }
+ if q.ArtifactID > 0 {
+ return e.Core.Artifact(ctx, q.Scope, q.ArtifactID)
+ }
+ return e.Core.Artifacts(ctx, q.Scope)
+ case "freeze":
+ var frozen runnerproto.FreezeRequest
+ if a.Kind != "step" || runnerproto.DecodeLimit(strings.NewReader(string(q.Prepared)), &frozen, 8192) != nil {
+ return nil, ErrInvalid
+ }
+ 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)
case "questions":
@@ -173,7 +195,7 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
case "answers":
return e.questionAnswers(ctx, tx, a)
case "renew":
- deadline := now.Add(30 * time.Second)
+ deadline := now.Add(60 * time.Second)
if a.Kind == "step" {
var err error
deadline, err = e.Core.Renew(ctx, q.Scope, q.Handle)
@@ -253,6 +275,9 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
if err := tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "contained"}).Error; err != nil {
return nil, storeError(err)
}
+ if err := finishTaskCancellation(tx, a.TaskID); err != nil {
+ return nil, err
+ }
if value.Selection.Isolation.RunnerTainted || value.Selection.Isolation.Status == "unconfined" {
return e.rotateContained(tx, a, q, now)
}
@@ -271,7 +296,13 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen
if a.Kind != "step" || q.Result == nil {
return nil, ErrInvalid
}
- return nil, e.Core.Complete(ctx, q.Scope, q.Handle, *q.Result)
+ if err := e.Core.Complete(ctx, q.Scope, q.Handle, *q.Result); err != nil {
+ return nil, err
+ }
+ if q.Result.Outcome == team.OutcomeFailure {
+ return nil, storeError(tx.Model(&Task{}).Where("id=?", a.TaskID).Select("State").Updates(&Task{State: "failed"}).Error)
+ }
+ return nil, nil
case "prepare":
if a.Kind != "prepare" || e.validators.Prepare == nil {
return nil, ErrUnavailable
diff --git a/internal/equipo/runner_rotation.go b/internal/equipo/runner_rotation.go
index 758545af..2d505689 100644
--- a/internal/equipo/runner_rotation.go
+++ b/internal/equipo/runner_rotation.go
@@ -2,6 +2,9 @@ package equipo
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
"errors"
"time"
@@ -56,6 +59,16 @@ func (e *Execution) rotateContained(tx *gorm.DB, a runnerAssignment, q RunnerReq
return result, storeError(err)
}
for _, c := range cleanups {
+ if c.AssignmentID == a.ID {
+ raw, err := json.Marshal(c)
+ if err != nil {
+ return result, err
+ }
+ recovery := runnerObservation{AssignmentID: a.ID, RequestID: "rotation/" + q.RequestID, Operation: "rotation_recovery", Payload: string(raw), At: now}
+ if err = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&recovery).Error; err != nil {
+ return result, storeError(err)
+ }
+ }
token := runnerSecret()
if err := tx.Model(&runnerCleanup{}).Where("id=?", c.ID).Select("TokenHash").Updates(&runnerCleanup{TokenHash: runnerHash(runnerproto.CleanupAudience, token)}).Error; err != nil {
return result, storeError(err)
@@ -152,3 +165,59 @@ func (e *Execution) containmentBarrier(ctx context.Context, p RunnerPrincipal, t
return appendAudit(tx, Actor{Address: a.Person}, "runner.containment.pending", a.ID)
})
}
+
+// A lost rotation reply may be recovered with the predecessor cleanup token,
+// only for the original containment request while admission remains blocked.
+func (e *Execution) recoverRotation(ctx context.Context, token string, q RunnerRequest) (CredentialRotation, bool, error) {
+ var result CredentialRotation
+ found := false
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ var rotation runnerRotation
+ err := tx.First(&rotation, "assignment_id=? AND request_id=? AND state IN ?", q.AssignmentID, q.RequestID, []string{"pending", "cleanup_only"}).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return storeError(err)
+ }
+ var recovery runnerObservation
+ err = tx.First(&recovery, "assignment_id=? AND request_id=? AND operation=?", q.AssignmentID, "rotation/"+q.RequestID, "rotation_recovery").Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return storeError(err)
+ }
+ var saved runnerCleanup
+ if json.Unmarshal([]byte(recovery.Payload), &saved) != nil {
+ return ErrUnavailable
+ }
+ if saved.TokenHash != runnerHash(runnerproto.CleanupAudience, token) {
+ return nil
+ }
+ found = true
+ now := e.store.runnerClock.Now().UTC()
+ if !now.Before(saved.ExpiresAt) || saved.AttemptID != int64(q.Handle.Attempt) || saved.Fence != q.Handle.Fence {
+ return ErrForbidden
+ }
+ var a runnerAssignment
+ if err = tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if !binding(a, q) || a.State != "contained" || rotation.RunnerID != a.RunnerID || saved.RunnerID != a.RunnerID {
+ return ErrForbidden
+ }
+ var original runnerObservation
+ if err = tx.First(&original, "assignment_id=? AND request_id=? AND operation='contained'", a.ID, q.RequestID).Error; err != nil {
+ return storeError(err)
+ }
+ raw, _ := json.Marshal(q)
+ sum := sha256.Sum256(raw)
+ if hex.EncodeToString(sum[:]) != original.PayloadHash {
+ return ErrConflict
+ }
+ result, err = e.rotateContained(tx, a, q, now)
+ return err
+ })
+ return result, found, err
+}
diff --git a/internal/equipo/runner_supervision.go b/internal/equipo/runner_supervision.go
new file mode 100644
index 00000000..7a839db6
--- /dev/null
+++ b/internal/equipo/runner_supervision.go
@@ -0,0 +1,94 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "encoding/json"
+ "gorm.io/gorm"
+)
+
+// AttachSupervisedExecution installs the real journal, executor and question
+// validators as one startup operation. Ordinary construction remains closed.
+func (s *Store) AttachSupervisedExecution(ctx context.Context, path string, options team.Options, w *runner.Witness) (*Execution, error) {
+ if w == nil {
+ return nil, ErrInvalid
+ }
+ options.Provenance = w.Provenance
+ options.ExecutorEvidence = w.ExecutorEvidence
+ options.Adapters = map[team.Operation]team.Adapter{team.OpProviderCall: s.RunnerAdapter(team.OpProviderCall), team.OpForgePublish: s.RunnerAdapter(team.OpForgePublish)}
+ e, err := s.AttachExecution(ctx, path, options)
+ if err != nil {
+ return nil, err
+ }
+ e.SetRunnerValidators(RunnerValidators{Question: w.Question, Receipt: w.Receipt, Containment: w.Containment, Prepare: w.Prepare, Events: w.Events, Artifact: w.Artifact})
+ 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" {
+ 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" {
+ return nil, nil
+ }
+ report, err := e.Core.Conclude(ctx, q.Scope, a.Person)
+ if err != nil {
+ return nil, err
+ }
+ state := "failed"
+ if report.Satisfied {
+ state = "waiting_merge"
+ }
+ if err = tx.Model(&Task{}).Where("id=?", a.TaskID).Select("State").Updates(&Task{State: state}).Error; err != nil {
+ return nil, storeError(err)
+ }
+ return report, appendAudit(tx, Actor{Address: a.Person}, "task.conclude", a.TaskID)
+}
+
+// RecoverClaim returns cleanup authority for an exact journaled claim. Zero
+// deadlines prevent the reply from being reused as dispatch authority.
+func (e *Execution) RecoverClaim(ctx context.Context, p RunnerPrincipal, q ClaimRequest) (ClaimResponse, error) {
+ var result ClaimResponse
+ if q.Version != 1 || q.AssignmentID == "" || q.RequestID == "" || len(q.RequestID) > 256 {
+ return result, ErrInvalid
+ }
+ err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error {
+ if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil {
+ return err
+ }
+ var a runnerAssignment
+ if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil {
+ return storeError(err)
+ }
+ if a.RunnerID != p.RunnerID || a.Person != p.Person || a.ClaimRequest != q.RequestID || a.Revision != q.Revision || a.State == "pending" {
+ return ErrForbidden
+ }
+ var cleanup runnerCleanup
+ if err := tx.First(&cleanup, "assignment_id=?", a.ID).Error; err != nil {
+ return storeError(err)
+ }
+ if !e.store.runnerClock.Now().Before(cleanup.ExpiresAt) {
+ return ErrForbidden
+ }
+ value, err := assignmentValue(a)
+ if err != nil {
+ return err
+ }
+ var brief RunnerBrief
+ if json.Unmarshal([]byte(a.Brief), &brief) != nil {
+ return ErrUnavailable
+ }
+ token := runnerSecret()
+ if err := tx.Model(&runnerCleanup{}).Where("id=?", cleanup.ID).Select("TokenHash").Updates(&runnerCleanup{TokenHash: runnerHash(runnerproto.CleanupAudience, token)}).Error; err != nil {
+ return storeError(err)
+ }
+ result = ClaimResponse{Scope: value.Scope, Handle: team.Handle{Attempt: team.AttemptID(a.AttemptID), Fence: a.Fence, Runner: a.RunnerID}, Brief: brief, CleanupToken: token, CleanupExpiresAt: cleanup.ExpiresAt}
+ return appendAudit(tx, Actor{Address: p.Person}, "runner.recover_claim", a.ID)
+ })
+ return result, err
+}
diff --git a/internal/equipo/task_handlers.go b/internal/equipo/task_handlers.go
index db6e8168..e9873b87 100644
--- a/internal/equipo/task_handlers.go
+++ b/internal/equipo/task_handlers.go
@@ -2,6 +2,7 @@ package equipo
import (
"amadan.net/rastrillo/rastrillo/auth"
+ "github.com/go-chi/chi/v5"
"net/http"
"strconv"
)
@@ -35,3 +36,22 @@ func (a *application) createBug(w http.ResponseWriter, r *http.Request) {
}
http.Redirect(w, r, "/projects/"+strconv.FormatInt(task.ProjectID, 10), http.StatusSeeOther)
}
+
+func (a *application) cancelTask(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 8192)
+ if r.ParseForm() != nil || len(r.URL.Query()) != 0 || len(r.PostForm) != 0 {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ actor, ok := auth.From(r)
+ if !ok {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ id := chi.URLParam(r, "id")
+ if _, err := a.store.CancelTask(r.Context(), Actor{Address: actor.Address}, id); err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, "/tasks/"+id, http.StatusSeeOther)
+}
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go
index 9a9d62f7..69875f37 100644
--- a/internal/equipo/team/scheduler.go
+++ b/internal/equipo/team/scheduler.go
@@ -152,6 +152,14 @@ func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspa
if d.State != StepSucceeded {
return fail(CodeDependency, "step %q waits for %q (%s)", st.Key, dep, d.State)
}
+ var uncontained int
+ if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM attempts WHERE step_id=? AND containment='pending'", d.ID).Scan(&uncontained); err != nil {
+ return err
+ }
+ if uncontained > 0 {
+ return ErrContainment
+ }
+
}
if st.Attempts >= j.Policy.MaxAttemptsPerStep {
return fail(CodeQuota, "step %q used its %d attempts", st.Key, j.Policy.MaxAttemptsPerStep)
@@ -315,7 +323,7 @@ func (s *Store) Complete(ctx context.Context, scope Scope, h Handle, r AttemptRe
aState, sState := AttemptSucceeded, StepSucceeded
if r.Outcome == OutcomeFailure {
aState, sState = AttemptFailed, StepPending
- if hd.step.Attempts >= hd.job.Policy.MaxAttemptsPerStep {
+ if hd.job.Evidence.RequireBugFreeze || hd.step.Attempts >= hd.job.Policy.MaxAttemptsPerStep {
sState = StepFailed
}
// Intents never dispatched hold budget for nothing; in-flight
diff --git a/internal/equipotest/cancel_test.go b/internal/equipotest/cancel_test.go
new file mode 100644
index 00000000..3cdb9768
--- /dev/null
+++ b/internal/equipotest/cancel_test.go
@@ -0,0 +1,140 @@
+package equipotest
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestCancelTaskFencesBeforeAcknowledgement(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ report, err := f.s.CancelTask(connectionContext, ownerActor, f.a.TaskID)
+ executionMust(t, err)
+ if report.Contained {
+ t.Fatal("cancel acknowledged before process verification")
+ }
+ if err := f.x.Core.ValidateHandle(connectionContext, f.claim.Scope, f.claim.Handle); err == nil {
+ t.Fatal("cancel retained authority")
+ }
+ attempts, err := f.x.Core.Attempts(connectionContext, f.claim.Scope)
+ executionMust(t, err)
+ if len(attempts) != 1 || attempts[0].Containment == team.ContainmentContained {
+ t.Fatal("cancel fabricated containment")
+ }
+ if _, err = f.s.CancelTask(connectionContext, equipo.Actor{Address: "stranger@example.com"}, f.a.TaskID); err == nil {
+ t.Fatal("stranger cancelled")
+ }
+}
+func TestBugPreparationIntegration(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ if len(f.claim.Brief.CheckDefinition) == 0 {
+ t.Fatal("immutable check definition missing from runner claim")
+ }
+}
+
+func TestRunnerBugFailureEndsFixedRun(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ q := f.request()
+ q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure}
+ _, err := f.x.Mutate(connectionContext, f.principal, "complete", q)
+ executionMust(t, err)
+ job, err := f.x.Core.GetJob(connectionContext, f.claim.Scope)
+ executionMust(t, err)
+ if job.State != team.JobFailed {
+ t.Fatal("fixed run invented another attempt", job.State)
+ }
+}
+
+func TestCancelLostRotationReply(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(_ context.Context, _ equipo.Assignment, _ equipo.RunnerRequest) error { return nil }})
+ q := f.request()
+ q.RequestID = "lost-rotation"
+ q.Proof = []byte(`{}`)
+ _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ altered := q
+ altered.Proof = []byte(`{"changed":true}`)
+ if _, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", altered); err == nil {
+ t.Fatal("changed containment recovered credentials")
+ }
+ value, err := f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q)
+ executionMust(t, err)
+ rotated := value.(equipo.CredentialRotation)
+ if rotated.Bearer.Token == "" {
+ t.Fatal("lost rotation did not recover")
+ }
+ principal, err := f.s.AuthenticateRunner(connectionContext, rotated.Bearer.Token)
+ executionMust(t, err)
+ if _, err = f.x.Mutate(connectionContext, principal, "renew", q); err == nil {
+ t.Fatal("rotation opened admission before journal acknowledgement")
+ }
+ executionMust(t, f.x.AcknowledgeRotation(connectionContext, principal, q.RequestID))
+ if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
+ t.Fatal("old cleanup recovered after acknowledgement")
+ }
+}
+
+func TestCancelHTTPRunnerLosesAuthority(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ token := runnerBearerFor(t, f)
+ server := httptest.NewServer(f.s.RunnerHandler())
+ defer server.Close()
+ dir := t.TempDir()
+ executionMust(t, os.Chmod(dir, 0700))
+ journal, err := runner.OpenJournal(connectionContext, filepath.Join(dir, "journal.db"))
+ executionMust(t, err)
+ defer journal.Close()
+ api, err := runner.NewHTTPInstance(server.URL, journal, runnerproto.RunnerCredential{Token: token, ExpiresAt: time.Now().Add(time.Hour)})
+ executionMust(t, err)
+ assignments, err := api.Poll(connectionContext)
+ executionMust(t, err)
+ if len(assignments) != 1 {
+ t.Fatal("HTTP assignment count", len(assignments))
+ }
+ claim, err := api.Claim(connectionContext, runnerproto.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "http-claim"})
+ executionMust(t, err)
+ if claim.AttemptDeadline.IsZero() || !claim.LeaseDeadline.Before(claim.AttemptDeadline) {
+ t.Fatal("missing attempt deadline")
+ }
+ q := runnerproto.RunnerRequest{Version: 1, AssignmentID: f.a.ID, Scope: claim.Scope, Handle: claim.Handle, RequestID: "validate"}
+ executionMust(t, api.Call(connectionContext, "validate", q, nil))
+ _, err = f.s.CancelTask(connectionContext, ownerActor, f.a.TaskID)
+ executionMust(t, err)
+ if err = api.Call(connectionContext, "validate", q, nil); err == nil {
+ t.Fatal("HTTP authority survived cancellation")
+ }
+}
+
+func TestCancelUnstartedTaskComplete(t *testing.T) {
+ f := runnerFixtureNew(t, false)
+ report, err := f.s.CancelTask(connectionContext, ownerActor, f.a.TaskID)
+ executionMust(t, err)
+ task, err := f.s.Task(connectionContext, ownerActor, f.a.TaskID)
+ executionMust(t, err)
+ if !report.Contained || task.State != "cancelled" {
+ t.Fatal("unstarted task retained stop request", report.Contained, task.State)
+ }
+}
+
+func TestRunnerRestartLostClaimReply(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.clock.Advance(61 * time.Second)
+ q := runnerproto.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
+ recovered, err := f.x.RecoverClaim(connectionContext, f.principal, q)
+ executionMust(t, err)
+ if recovered.CleanupToken == "" || !recovered.LeaseDeadline.IsZero() || !recovered.AttemptDeadline.IsZero() || recovered.Handle.Attempt != f.claim.Handle.Attempt {
+ t.Fatal("recovery restored dispatch authority")
+ }
+ q.RequestID = "other"
+ if _, err = f.x.RecoverClaim(connectionContext, f.principal, q); err == nil {
+ t.Fatal("foreign claim request recovered")
+ }
+}
diff --git a/internal/equipotest/preparation_integration_test.go b/internal/equipotest/preparation_integration_test.go
new file mode 100644
index 00000000..fffdd619
--- /dev/null
+++ b/internal/equipotest/preparation_integration_test.go
@@ -0,0 +1,177 @@
+package equipotest
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "gorm.io/gorm"
+)
+
+type preparationRemote struct{ path string }
+
+func (r preparationRemote) Resolve(context.Context, string) (workspace.Remote, error) {
+ return workspace.Remote{URL: r.path}, nil
+}
+func TestBugPreparationCrashRealProtocolLocalGit(t *testing.T) {
+ f := bugFixture(t)
+ task := bugTask(t, f)
+ ctx := connectionContext
+ root := t.TempDir()
+ state := filepath.Join(root, "state")
+ executionMust(t, os.Mkdir(state, 0700))
+ journal, err := runner.OpenJournal(ctx, filepath.Join(state, "journal.db"))
+ executionMust(t, err)
+ defer journal.Close()
+ w, err := runner.NewWitness(journal)
+ executionMust(t, err)
+ var path string
+ executionMust(t, f.d.Writer().QueryRow(`SELECT file FROM pragma_database_list WHERE name='main'`).Scan(&path))
+ x, err := f.s.AttachSupervisedExecution(ctx, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)}, w)
+ executionMust(t, err)
+ defer x.Core.Close()
+ _, err = x.Core.Resume(ctx)
+ executionMust(t, err)
+ executionMust(t, x.Sync(ctx))
+ assignments, err := x.Poll(ctx, f.principal, "")
+ executionMust(t, err)
+ if len(assignments) != 1 || assignments[0].Kind != "prepare" {
+ t.Fatal("preparation assignment missing")
+ }
+ a := assignments[0]
+ claim, err := x.Claim(ctx, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: a.ID, Revision: a.Revision, RequestID: "prepare-claim"})
+ executionMust(t, err)
+ seed := filepath.Join(root, "seed")
+ executionMust(t, os.Mkdir(seed, 0700))
+ executionMust(t, os.Mkdir(filepath.Join(seed, ".equipo"), 0700))
+ git := func(dir string, args ...string) string {
+ t.Helper()
+ c := exec.Command("/usr/bin/git", args...)
+ c.Dir = dir
+ c.Env = []string{"PATH=/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=fixture", "GIT_AUTHOR_EMAIL=fixture@example.test", "GIT_COMMITTER_NAME=fixture", "GIT_COMMITTER_EMAIL=fixture@example.test"}
+ b, e := c.CombinedOutput()
+ if e != nil {
+ t.Fatalf("git: %v %s", e, b)
+ }
+ return strings.TrimSpace(string(b))
+ }
+ for p, s := range map[string]string{"go.mod": "module prepfixture\n\ngo 1.26.0\n", "old_test.go": "package prepfixture\nimport \"testing\"\nfunc TestOld(t *testing.T){}\n"} {
+ executionMust(t, os.WriteFile(filepath.Join(seed, p), []byte(s), 0600))
+ }
+ command := runnerproto.CheckCommand{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", Parser: "go-test-json", TimeoutSeconds: 120}
+ raw, _ := json.Marshal(runnerproto.CheckDefinition{Version: 1, Commands: []runnerproto.CheckCommand{command}, Reproduction: command})
+ executionMust(t, os.WriteFile(filepath.Join(seed, ".equipo/checks.json"), raw, 0600))
+ git(seed, "init", "-b", claim.Brief.Target.DefaultRef)
+ git(seed, "add", ".")
+ git(seed, "commit", "-m", "base")
+ base := git(seed, "rev-parse", "HEAD")
+ remote := filepath.Join(root, "remote.git")
+ git(root, "clone", "--bare", seed, remote)
+ private := filepath.Join(root, "private")
+ scratch := filepath.Join(root, "scratch")
+ executionMust(t, os.Mkdir(scratch, 0700))
+ protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: state + "/config", Journal: state + "/journal.db", Bearer: state + "/bearer", Cleanup: state + "/cleanup", ForgeCredential: state + "/forge", PaseoHome: state + "/paseo", ProviderHomes: []string{state + "/provider"}, SSH: state + "/ssh"}
+ policy := paseo.ReadPolicy{ConfigHash: strings.Repeat("a", 64), DeniedPaths: []string{state, private}}
+ binary, err := exec.LookPath("codex")
+ executionMust(t, err)
+ sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: binary, ScratchRoot: scratch, GoRoot: runtime.GOROOT(), GoBinary: filepath.Join(runtime.GOROOT(), "bin/go"), Protected: protected})
+ executionMust(t, err)
+ m, err := workspace.New(workspace.Config{PrivateRoot: private, WorkspaceRoot: filepath.Join(root, "work"), GitPath: "/usr/bin/git", Forge: preparationRemote{remote}, Protected: protected, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Definitions: func(ctx context.Context, target team.TargetBinding, repo string) (runnerproto.PreparedBug, error) {
+ d, err := checks.LoadBaseDefinition(ctx, repo, target.Repository, target.BaseRevision, scratch)
+ if err != nil {
+ return runnerproto.PreparedBug{}, err
+ }
+ e, err := checks.New(checks.Config{ScratchRoot: scratch, Deadline: time.Now().Add(2 * time.Minute), Policy: policy, Export: func(ctx context.Context, commit, dest string) error {
+ return checks.ExportBase(ctx, repo, commit, dest)
+ }, ResolveCandidate: func(context.Context, string) (team.GitCandidate, error) {
+ return team.GitCandidate{}, paseo.ErrIdentity
+ }, Reproduction: func(context.Context, string) (checks.Reproduction, error) {
+ return checks.Reproduction{}, paseo.ErrIdentity
+ }, Isolation: func(context.Context) (team.IsolationSnapshot, error) { return a.Selection.Isolation, nil }}, sandbox)
+ if err != nil {
+ return runnerproto.PreparedBug{}, err
+ }
+ d.Baseline, err = e.CaptureBaseline(ctx, d)
+ if err != nil {
+ return runnerproto.PreparedBug{}, err
+ }
+ b, _ := json.Marshal(d)
+ return runnerproto.PreparedBug{CheckDefinition: b, CheckDefinitionHash: checks.Digest(b), BaselineTestSetHash: d.Baseline.Hash}, nil
+ }}, &paseo.Client{})
+ executionMust(t, err)
+ prepared, err := w.PrepareBug(ctx, m, a, claim.Brief.Target)
+ executionMust(t, err)
+ if prepared.BaseCommit != base {
+ t.Fatal("preparation did not pin Git base")
+ }
+ token := strings.Repeat("A", 43)
+ sum := sha256.Sum256([]byte(runnerproto.RunnerAudience + "\x00" + token))
+ mustSQL(t, f.d, "UPDATE runner_credentials SET token_hash=? WHERE id=?", fmt.Sprintf("%x", sum), f.principal.CredentialID)
+ q := runnerproto.RunnerRequest{Version: 1, AssignmentID: a.ID, Scope: claim.Scope, Handle: claim.Handle, RequestID: "prepared"}
+ q.Prepared, _ = json.Marshal(prepared)
+ send := func() int {
+ raw, err := runnerproto.Marshal(q)
+ executionMust(t, err)
+ req := httptest.NewRequest("POST", "/prepare", bytes.NewReader(raw))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+token)
+ rec := httptest.NewRecorder()
+ f.s.RunnerHandler().ServeHTTP(rec, req)
+ return rec.Code
+ }
+ injected := false
+ executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task15_prepare_crash", func(tx *gorm.DB) {
+ if event, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && event.Kind == "task.prepare" {
+ injected = true
+ tx.AddError(errors.New("crash before acknowledgement"))
+ }
+ }))
+ if code := send(); code < 400 || !injected {
+ t.Fatal("crash accepted", code)
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("task15_prepare_crash"))
+ if code := send(); code != 200 {
+ t.Fatal("real protocol preparation failed", code)
+ }
+ executionMust(t, x.Sync(ctx))
+ if scalar(t, f.d, "SELECT count(*) FROM jobs") != 0 {
+ t.Fatal("StartBug ran before preparation containment")
+ }
+ // No process or workspace was created by this metadata-only fixture after baseline capture.
+ // The separate supervisor tests prove the real containment validator and cleanup ordering.
+ mustSQL(t, f.d, "UPDATE runner_assignments SET state='contained' WHERE id=?", a.ID)
+ executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task15_link_crash", func(tx *gorm.DB) {
+ if event, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && event.Kind == "task.link" {
+ tx.AddError(errors.New("crash before link acknowledgement"))
+ }
+ }))
+ if err = x.Sync(ctx); err == nil {
+ t.Fatal("link crash not observed")
+ }
+ executionMust(t, f.d.G.Callback().Create().Remove("task15_link_crash"))
+ executionMust(t, x.Sync(ctx))
+ executionMust(t, x.Sync(ctx))
+ saved, err := f.s.Task(ctx, ownerActor, task.ID)
+ executionMust(t, err)
+ if saved.JobID == 0 || scalar(t, f.d, "SELECT count(*) FROM jobs") != 1 {
+ t.Fatal("preparation duplicated job")
+ }
+}
diff --git a/internal/equipotest/runner_api_test.go b/internal/equipotest/runner_api_test.go
index 65d5f66a..2d6a129e 100644
--- a/internal/equipotest/runner_api_test.go
+++ b/internal/equipotest/runner_api_test.go
@@ -189,8 +189,8 @@ func TestUnconfinedContainmentRotatesTokens(t *testing.T) {
if rotation.Bearer.Token == "" || len(rotation.CleanupTokens) != 1 {
t.Fatal("missing replacement credentials")
}
- if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "contained", q); err == nil {
- t.Fatal("old cleanup token survived")
+ if _, err = f.x.Cleanup(connectionContext, f.claim.CleanupToken, "receipts", q); err == nil {
+ t.Fatal("old cleanup token retained general cleanup authority")
}
if _, err = f.s.AuthenticateRunner(connectionContext, rotation.Bearer.Token); err != nil {
t.Fatal(err)
diff --git a/internal/runner/checks/ownership.go b/internal/runner/checks/ownership.go
new file mode 100644
index 00000000..367272e5
--- /dev/null
+++ b/internal/runner/checks/ownership.go
@@ -0,0 +1,11 @@
+package checks
+
+import (
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+)
+
+// WithProcessOwnership binds executor children to the supervisor's attempt.
+func WithProcessOwnership(ctx context.Context, marker string, track func(context.Context, int) error) context.Context {
+ return runnerproto.WithProcessOwnership(ctx, marker, track)
+}
diff --git a/internal/runner/checks/sandbox.go b/internal/runner/checks/sandbox.go
index 4ea63acd..eab95e00 100644
--- a/internal/runner/checks/sandbox.go
+++ b/internal/runner/checks/sandbox.go
@@ -16,6 +16,7 @@ import (
"amadan.net/oficina/equipo/internal/runner/paseo"
"amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
)
const CodexVersion = "codex-cli 0.165.0"
@@ -158,7 +159,16 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
}
denies[cfgHome] = true
for p := range denies {
- roots[p] = "deny"
+ covered := false
+ for parent := range denies {
+ if parent != p && within(parent, p) {
+ covered = true
+ break
+ }
+ }
+ if !covered {
+ roots[p] = "deny"
+ }
}
keys := make([]string, 0, len(roots))
for k := range roots {
@@ -182,6 +192,10 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
cmd := exec.CommandContext(ctx, s.binary, args...)
cmd.Dir = control
cmd.Env = []string{"PATH=" + filepath.Join(s.goRoot, "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "GOCACHE=" + cache, "GOTMPDIR=" + goTemp, "GOROOT=" + s.goRoot, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"}
+ marker, track := runnerproto.ProcessOwnership(ctx)
+ if marker != "" {
+ cmd.Env = append(cmd.Env, "EQUIPO_ATTEMPT_MARKER="+marker)
+ }
cmd.Stdout = stdout
cmd.Stderr = stderr
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
@@ -190,12 +204,24 @@ func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy p
if cmd.Process == nil {
return nil
}
+ if track != nil {
+ return cmd.Process.Kill()
+ }
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
if err = cmd.Start(); err != nil {
return -1, paseo.ErrContract
}
- defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
+ if track == nil {
+ defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
+ }
+ if track != nil {
+ if err = track(ctx, cmd.Process.Pid); err != nil {
+ _ = cmd.Cancel()
+ _ = cmd.Wait()
+ return -1, err
+ }
+ }
err = cmd.Wait()
if ctx.Err() != nil {
return -1, ctx.Err()
diff --git a/internal/runner/http.go b/internal/runner/http.go
new file mode 100644
index 00000000..5fbec762
--- /dev/null
+++ b/internal/runner/http.go
@@ -0,0 +1,158 @@
+package runner
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type HTTPInstance struct {
+ origin string
+ client *http.Client
+ journal *Journal
+ mu sync.Mutex
+ bearer runnerproto.RunnerCredential
+ cleanup map[string]string
+}
+
+func NewHTTPInstance(origin string, j *Journal, credential runnerproto.RunnerCredential) (*HTTPInstance, error) {
+ u, err := url.Parse(origin)
+ if err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Host == "" || u.Scheme != "https" && (u.Scheme != "http" || u.Hostname() != "127.0.0.1") || j == nil || credential.Token == "" {
+ return nil, paseo.ErrContract
+ }
+ return &HTTPInstance{origin: strings.TrimRight(origin, "/"), journal: j, bearer: credential, cleanup: map[string]string{}, client: &http.Client{Timeout: 35 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
+}
+func (c *HTTPInstance) post(ctx context.Context, op string, body any, token string, out any) error {
+ raw, err := runnerproto.Marshal(body)
+ if err != nil {
+ return err
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.origin+"/"+op, bytes.NewReader(raw))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Authorization", token)
+ req.Header.Set("Content-Type", "application/json")
+ response, err := c.client.Do(req)
+ if err != nil {
+ return paseo.ErrUncertain
+ }
+ defer response.Body.Close()
+ if response.StatusCode != http.StatusOK {
+ return paseo.ErrUncertain
+ }
+ var envelope struct {
+ Version int `json:"version"`
+ Result json.RawMessage `json:"result"`
+ }
+ if err = runnerproto.DecodeLimit(io.LimitReader(response.Body, 3<<20), &envelope, 3<<20); err != nil || envelope.Version != 1 {
+ return paseo.ErrContract
+ }
+ if out == nil || bytes.Equal(envelope.Result, []byte("null")) {
+ return nil
+ }
+ return runnerproto.DecodeLimit(bytes.NewReader(envelope.Result), out, 3<<20)
+}
+func (c *HTTPInstance) token(assignment string, cleanup bool) (string, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if cleanup {
+ v := c.cleanup[assignment]
+ if v == "" {
+ return "", paseo.ErrIdentity
+ }
+ return "Cleanup " + v, nil
+ }
+ if c.bearer.Token == "" || !time.Now().Before(c.bearer.ExpiresAt) {
+ return "", paseo.ErrIdentity
+ }
+ return "Bearer " + c.bearer.Token, nil
+}
+func (c *HTTPInstance) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ token, err := c.token(q.AssignmentID, op == "contained")
+ if err != nil {
+ return err
+ }
+ return c.post(ctx, op, q, token, out)
+}
+func (c *HTTPInstance) Poll(ctx context.Context) ([]runnerproto.Assignment, error) {
+ token, err := c.token("", false)
+ if err != nil {
+ return nil, err
+ }
+ var assignments []runnerproto.Assignment
+ err = c.post(ctx, "poll", runnerproto.PollRequest{Version: 1}, token, &assignments)
+ return assignments, err
+}
+func (c *HTTPInstance) Claim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) {
+ return c.claim(ctx, "claim", q)
+}
+func (c *HTTPInstance) RecoverClaim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) {
+ return c.claim(ctx, "recover_claim", q)
+}
+func (c *HTTPInstance) claim(ctx context.Context, op string, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) {
+ token, err := c.token("", false)
+ if err != nil {
+ return runnerproto.ClaimResponse{}, err
+ }
+ var claim runnerproto.ClaimResponse
+ if err = c.post(ctx, op, q, token, &claim); err != nil {
+ return claim, err
+ }
+ if claim.CleanupToken == "" || claim.Handle.Runner == "" {
+ return runnerproto.ClaimResponse{}, paseo.ErrIdentity
+ }
+ if err = c.journal.saveState(ctx, "cleanup", q.AssignmentID, claim.CleanupToken); err != nil {
+ return runnerproto.ClaimResponse{}, err
+ }
+ c.mu.Lock()
+ c.cleanup[q.AssignmentID] = claim.CleanupToken
+ c.mu.Unlock()
+ return claim, nil
+}
+func (c *HTTPInstance) InstallCredentials(ctx context.Context, rotation runnerproto.CredentialRotation, requestID string) error {
+ if rotation.Bearer.Token == "" || requestID == "" {
+ return paseo.ErrIdentity
+ }
+ for id, token := range rotation.CleanupTokens {
+ if err := c.journal.saveState(ctx, "cleanup", id, token); err != nil {
+ return err
+ }
+ }
+ c.mu.Lock()
+ c.bearer = rotation.Bearer
+ for id, token := range rotation.CleanupTokens {
+ c.cleanup[id] = token
+ }
+ c.mu.Unlock()
+ token, err := c.token("", false)
+ if err != nil {
+ return err
+ }
+ return c.post(ctx, "heartbeat", runnerproto.HeartbeatRequest{Version: 1, RequestID: requestID + "/ack", RotationRequestID: requestID}, token, nil)
+}
+
+func (c *HTTPInstance) RestoreClaim(claim RunClaim) error {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ var raw []byte
+ err := c.journal.db.QueryRow("SELECT body FROM journal_supervisor WHERE kind='cleanup' AND state_key=?", claim.Assignment.ID).Scan(&raw)
+ if err != nil {
+ return paseo.ErrUncertain
+ }
+ var token string
+ if json.Unmarshal(raw, &token) != nil || token == "" {
+ return paseo.ErrIdentity
+ }
+ c.cleanup[claim.Assignment.ID] = token
+ return nil
+}
diff --git a/internal/runner/journal.go b/internal/runner/journal.go
index 5985a72b..40e6b4f5 100644
--- a/internal/runner/journal.go
+++ b/internal/runner/journal.go
@@ -93,6 +93,7 @@ func OpenJournal(ctx context.Context, path string) (*Journal, error) {
CREATE TABLE IF NOT EXISTS journal_tools (request_key TEXT PRIMARY KEY, content_hash TEXT NOT NULL, body BLOB NOT NULL, acked INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS journal_intents (intent_key TEXT PRIMARY KEY, body BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS journal_streams (stream TEXT PRIMARY KEY, epoch TEXT NOT NULL, sequence INTEGER NOT NULL, ready INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS journal_supervisor (kind TEXT NOT NULL,state_key TEXT NOT NULL,body BLOB NOT NULL,PRIMARY KEY(kind,state_key));
CREATE TABLE IF NOT EXISTS journal_state (id INTEGER PRIMARY KEY, blocked INTEGER NOT NULL);
INSERT OR IGNORE INTO journal_state VALUES(1,0);
UPDATE journal_streams SET ready=0;
diff --git a/internal/runner/lease_linux.go b/internal/runner/lease_linux.go
new file mode 100644
index 00000000..a829d92d
--- /dev/null
+++ b/internal/runner/lease_linux.go
@@ -0,0 +1,85 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "golang.org/x/sys/unix"
+ "os"
+ "strings"
+ "sync"
+ "time"
+)
+
+type ClockReading struct {
+ Wall time.Time
+ Elapsed time.Duration
+ BootID string
+}
+type ElapsedClock interface{ Read() (ClockReading, error) }
+type linuxClock struct{}
+
+func (linuxClock) Read() (ClockReading, error) {
+ var ts unix.Timespec
+ if err := unix.ClockGettime(unix.CLOCK_BOOTTIME, &ts); err != nil {
+ return ClockReading{}, err
+ }
+ b, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ if err != nil {
+ return ClockReading{}, err
+ }
+ return ClockReading{Wall: time.Now(), Elapsed: time.Duration(ts.Nano()), BootID: strings.TrimSpace(string(b))}, nil
+}
+
+type leaseGuard struct {
+ mu sync.Mutex
+ last ClockReading
+ end, attemptEnd time.Duration
+ deadline time.Time
+ expired bool
+}
+
+func newLease(now ClockReading, deadline, attempt time.Time) (*leaseGuard, error) {
+ l := &leaseGuard{last: now, attemptEnd: now.Elapsed + attempt.Sub(now.Wall)}
+ if now.BootID == "" || !now.Wall.Before(attempt) || !now.Wall.Before(deadline) {
+ return nil, paseo.ErrIdentity
+ }
+ if err := l.renew(now, deadline); err != nil {
+ return nil, err
+ }
+ return l, nil
+}
+func (l *leaseGuard) check(now ClockReading) error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.checkLocked(now)
+}
+func (l *leaseGuard) checkLocked(now ClockReading) error {
+ if l.expired || now.BootID != l.last.BootID || now.Elapsed < l.last.Elapsed || now.Wall.Before(l.last.Wall) || (l.end > 0 && now.Elapsed >= l.end) || now.Elapsed >= l.attemptEnd {
+ l.expired = true
+ return paseo.ErrUncertain
+ }
+ l.last = now
+ return nil
+}
+func (l *leaseGuard) renew(now ClockReading, deadline time.Time) error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if err := l.checkLocked(now); err != nil {
+ return err
+ }
+ remaining := deadline.Sub(now.Wall)
+ if remaining > 60*time.Second {
+ remaining = 60 * time.Second
+ }
+ remaining -= 10 * time.Second
+ if remaining <= 0 {
+ l.expired = true
+ return paseo.ErrUncertain
+ }
+ l.end = now.Elapsed + remaining
+ if l.end > l.attemptEnd {
+ l.end = l.attemptEnd
+ }
+ l.deadline = now.Wall.Add(l.end - now.Elapsed)
+ return nil
+}
+func (l *leaseGuard) bound() time.Time { l.mu.Lock(); defer l.mu.Unlock(); return l.deadline }
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go
index 02bdaf7e..620129d8 100644
--- a/internal/runner/paseo/client.go
+++ b/internal/runner/paseo/client.go
@@ -633,3 +633,49 @@ func (c *Client) RegisterProject(ctx context.Context, r ProjectRequest) (Project
}
return p, nil
}
+
+func (c *Client) ListTerminals(ctx context.Context, w Workspace) ([]string, error) {
+ if w.ServerID != c.cfg.ServerID || w.WorkspaceID == "" || !filepath.IsAbs(w.Path) {
+ return nil, ErrIdentity
+ }
+ var ids []string
+ err := c.call(ctx, "list_terminals", struct {
+ Workspace Workspace `json:"workspace"`
+ }{w}, &ids)
+ if err != nil {
+ return nil, err
+ }
+ for _, id := range ids {
+ if id == "" {
+ return nil, ErrUncertain
+ }
+ }
+ return ids, nil
+}
+func (c *Client) KillTerminal(ctx context.Context, w Workspace, id string) error {
+ if w.ServerID != c.cfg.ServerID || w.WorkspaceID == "" || id == "" {
+ return ErrIdentity
+ }
+ return c.call(ctx, "kill_terminal", struct {
+ Workspace Workspace `json:"workspace"`
+ ID string `json:"id"`
+ }{w, id}, nil)
+}
+
+func (c *Client) ProviderPolicy(ctx context.Context, s Selection, p ReadPolicy) (json.RawMessage, error) {
+ if !validPolicy(p) {
+ return nil, ErrPolicy
+ }
+ var result json.RawMessage
+ err := c.call(ctx, "provider_policy", struct {
+ Selection Selection `json:"selection"`
+ ReadPolicy ReadPolicy `json:"read_policy"`
+ }{s, p}, &result)
+ if err != nil {
+ return nil, err
+ }
+ if len(result) == 0 || string(result) == "null" {
+ return nil, ErrPolicy
+ }
+ return result, nil
+}
diff --git a/internal/runner/process_linux.go b/internal/runner/process_linux.go
new file mode 100644
index 00000000..9bb88c20
--- /dev/null
+++ b/internal/runner/process_linux.go
@@ -0,0 +1,513 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "golang.org/x/sys/unix"
+)
+
+type ProcessIdentity = runnerproto.ProcessIdentity
+type ProcessOwner = runnerproto.ProcessOwner
+type ProcessInventory = runnerproto.ProcessInventory
+type ContainmentProof = runnerproto.ContainmentProof
+type ProcessInspector interface {
+ Track(context.Context, ProcessOwner) error
+ Remaining(context.Context, ProcessOwner) (ProcessInventory, error)
+ Stop(context.Context, ProcessIdentity) error
+}
+type TerminalClient interface {
+ ListTerminals(context.Context, paseo.Workspace) ([]string, error)
+ KillTerminal(context.Context, paseo.Workspace, string) error
+}
+type processRecord struct {
+ LastScanElapsed time.Duration
+ Owner ProcessOwner
+ Known []ProcessIdentity
+ Baseline []ProcessIdentity
+ Started bool
+ Unknown bool
+ UnknownStage int
+ UnknownPID int
+}
+type LinuxProcessInspector struct {
+ root, boot string
+ client TerminalClient
+ journal *Journal
+ mu sync.Mutex
+ records map[string]*processRecord
+ stopped map[int]ProcessIdentity
+ beforeTrackPID func(int)
+}
+
+func NewLinuxProcessInspector(procRoot string, client TerminalClient, journal *Journal) (*LinuxProcessInspector, error) {
+ if !filepath.IsAbs(procRoot) || filepath.Clean(procRoot) != procRoot || client == nil || journal == nil {
+ return nil, paseo.ErrContract
+ }
+ b, err := os.ReadFile(filepath.Join(procRoot, "sys/kernel/random/boot_id"))
+ if err != nil || strings.TrimSpace(string(b)) == "" {
+ return nil, paseo.ErrUncertain
+ }
+ p := &LinuxProcessInspector{root: procRoot, boot: strings.TrimSpace(string(b)), client: client, journal: journal, records: map[string]*processRecord{}, stopped: map[int]ProcessIdentity{}}
+ // A restarted monitor cannot assert uninterrupted ownership coverage.
+ var records []processRecord
+ if err := journal.readStates(context.Background(), "process", &records); err != nil {
+ return nil, err
+ }
+ for i := range records {
+ r := records[i]
+ r.Unknown = true
+ p.records[ownerKey(r.Owner)] = &r
+ }
+ return p, nil
+}
+func ownerKey(o ProcessOwner) string {
+ return runnerproto.EventHash([]any{o.Attempt, o.Fence, o.Marker, o.Workspace})
+}
+func validOwner(o ProcessOwner) bool {
+ return (o.Attempt > 0 || o.LocalOnly && o.Attempt == 0) && o.Fence > 0 && o.Marker != "" && (o.LocalOnly || o.Workspace.ServerID != "" && o.Workspace.WorkspaceID != "") && filepath.IsAbs(o.Workspace.Path) && filepath.Clean(o.Workspace.Path) == o.Workspace.Path && o.Workspace.Path != "/"
+}
+func (p *LinuxProcessInspector) Track(ctx context.Context, o ProcessOwner) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if !validOwner(o) {
+ return paseo.ErrIdentity
+ }
+ canonical, err := filepath.EvalSymlinks(o.Workspace.Path)
+ if err != nil || canonical != o.Workspace.Path {
+ return paseo.ErrIdentity
+ }
+ key := ownerKey(o)
+ if p.records[key] == nil {
+ p.records[key] = &processRecord{Owner: o}
+ } else {
+ p.records[key].Owner = o
+ }
+ if err = p.save(ctx, p.records[key]); err != nil {
+ return err
+ }
+ inv, err := p.scan(ctx, p.records[key])
+ if err != nil {
+ return err
+ }
+ if !inv.CoverageKnown {
+ return paseo.ErrUncertain
+ }
+ return nil
+}
+func (p *LinuxProcessInspector) save(ctx context.Context, r *processRecord) error {
+ return p.journal.saveState(ctx, "process", ownerKey(r.Owner), r)
+}
+func (p *LinuxProcessInspector) Remaining(ctx context.Context, o ProcessOwner) (ProcessInventory, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ r := p.records[ownerKey(o)]
+ if r == nil {
+ return ProcessInventory{}, paseo.ErrIdentity
+ }
+ return p.scan(ctx, r)
+}
+
+type procEntry struct {
+ id ProcessIdentity
+ parent, group int
+ cwd, env string
+ dead bool
+}
+
+func (p *LinuxProcessInspector) entry(pid int) (procEntry, error) {
+ var e procEntry
+ raw, err := os.ReadFile(filepath.Join(p.root, strconv.Itoa(pid), "stat"))
+ if err != nil {
+ return e, err
+ }
+ start := strings.IndexByte(string(raw), '(')
+ if start < 1 || strings.TrimSpace(string(raw[:start])) != strconv.Itoa(pid) {
+ return e, paseo.ErrIdentity
+ }
+ end := strings.LastIndexByte(string(raw), ')')
+ if end < 0 {
+ return e, paseo.ErrUncertain
+ }
+ fields := strings.Fields(string(raw)[end+1:])
+ if len(fields) < 20 {
+ return e, paseo.ErrUncertain
+ }
+ e.parent, err = strconv.Atoi(fields[1])
+ if err != nil {
+ return e, err
+ }
+ e.group, err = strconv.Atoi(fields[2])
+ if err != nil {
+ return e, err
+ }
+ ticks, err := strconv.ParseUint(fields[19], 10, 64)
+ if err != nil || ticks == 0 {
+ return e, paseo.ErrUncertain
+ }
+ e.id = ProcessIdentity{PID: pid, StartTicks: ticks, BootID: p.boot}
+ e.dead = fields[0] == "Z" || fields[0] == "X"
+ return e, nil
+}
+func (p *LinuxProcessInspector) identity(pid int) (ProcessIdentity, error) {
+ e, err := p.entry(pid)
+ return e.id, err
+}
+func identityKey(id ProcessIdentity) string {
+ return fmt.Sprintf("%s/%d/%d", id.BootID, id.PID, id.StartTicks)
+}
+func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord) (ProcessInventory, error) {
+ inv := ProcessInventory{BootID: p.boot, CoverageKnown: !r.Unknown, CheckedAt: time.Now().UTC()}
+ stage, pidAt := 0, 0
+ unknown := func() { r.Unknown = true; r.UnknownStage = stage; r.UnknownPID = pidAt; inv.CoverageKnown = false }
+ reading, clockErr := (linuxClock{}).Read()
+ if clockErr != nil || reading.BootID != p.boot || r.LastScanElapsed > 0 && (reading.Elapsed < r.LastScanElapsed || reading.Elapsed-r.LastScanElapsed > 2*time.Second) {
+ unknown()
+ }
+ r.LastScanElapsed = reading.Elapsed
+
+ entries, err := os.ReadDir(p.root)
+ if err != nil {
+ unknown()
+ _ = p.save(context.WithoutCancel(ctx), r)
+ return inv, err
+ }
+ boot, err := os.ReadFile(filepath.Join(p.root, "sys/kernel/random/boot_id"))
+ if err != nil || strings.TrimSpace(string(boot)) != p.boot {
+ unknown()
+ }
+ known := map[string]bool{}
+ knownPID := map[int]bool{}
+ for _, id := range r.Known {
+ known[identityKey(id)] = true
+ knownPID[id.PID] = true
+ }
+ for _, record := range p.records {
+ for _, id := range record.Known {
+ knownPID[id.PID] = true
+ }
+ }
+ all := map[int]procEntry{}
+ owned := map[int]bool{}
+ for _, d := range entries {
+ if ctx.Err() != nil {
+ unknown()
+ break
+ }
+ pid, err := strconv.Atoi(d.Name())
+ if err != nil || pid <= 0 {
+ continue
+ }
+ pidAt = pid
+ stage = 1
+ var st unix.Stat_t
+ if err = unix.Stat(filepath.Join(p.root, d.Name()), &st); err != nil {
+ if os.IsNotExist(err) && (p.stopped[pid].PID == pid || knownPID[pid]) {
+ continue
+ }
+ unknown()
+ continue
+ }
+ if st.Uid != uint32(os.Getuid()) {
+ continue
+ }
+ stage = 2
+ e, err := p.entry(pid)
+ if err != nil {
+ if os.IsNotExist(err) && (p.stopped[pid].PID == pid || knownPID[pid]) {
+ continue
+ }
+ unknown()
+ continue
+ }
+ if e.dead {
+ continue
+ }
+ stage = 3
+ env, envErr := os.ReadFile(filepath.Join(p.root, d.Name(), "environ"))
+ cwd, cwdErr := os.Readlink(filepath.Join(p.root, d.Name(), "cwd"))
+ if envErr != nil || cwdErr != nil {
+ after, e2 := p.entry(pid)
+ if (e2 == nil && after.id == e.id && after.dead) || (os.IsNotExist(e2) && (p.stopped[pid] == e.id || known[identityKey(e.id)])) {
+ continue
+ }
+ unknown()
+ continue
+ }
+ // Check identity after collecting attributes; a recycled or vanished PID is not a coherent observation.
+ stage = 4
+ after, err := p.identity(pid)
+ if err != nil || after != e.id {
+ if os.IsNotExist(err) && (p.stopped[pid] == e.id || known[identityKey(e.id)]) {
+ continue
+ }
+ unknown()
+ continue
+ }
+ e.cwd = cwd
+ e.env = string(env)
+ all[pid] = e
+ marker := false
+ for _, v := range strings.Split(e.env, "\x00") {
+ marker = marker || v == "EQUIPO_ATTEMPT_MARKER="+r.Owner.Marker
+ }
+ path := e.cwd == r.Owner.Workspace.Path || strings.HasPrefix(e.cwd, r.Owner.Workspace.Path+"/")
+ if known[identityKey(e.id)] || marker || path {
+ owned[pid] = true
+ }
+ for _, id := range r.Owner.ExecutorGroups {
+ if id == e.id {
+ owned[pid] = true
+ }
+ }
+ }
+ for changed := true; changed; {
+ changed = false
+ for pid, e := range all {
+ if !owned[pid] && owned[e.parent] && all[e.parent].id.StartTicks <= e.id.StartTicks {
+ owned[pid] = true
+ changed = true
+ }
+ }
+ }
+ stage = 5
+ if r.Started {
+ unrelated := map[int]bool{}
+ for _, id := range r.Baseline {
+ if e, ok := all[id.PID]; ok && e.id == id && !owned[id.PID] {
+ unrelated[id.PID] = true
+ }
+ }
+ for changed := true; changed; {
+ changed = false
+ for pid, e := range all {
+ if !owned[pid] && !unrelated[pid] && unrelated[e.parent] {
+ unrelated[pid] = true
+ changed = true
+ }
+ }
+ }
+ for pid := range all {
+ if !owned[pid] && !unrelated[pid] {
+ unknown()
+ }
+ }
+ } else {
+ for pid, e := range all {
+ if !owned[pid] {
+ r.Baseline = append(r.Baseline, e.id)
+ }
+ }
+ r.Started = true
+ }
+ for pid := range owned {
+ id := all[pid].id
+ inv.Processes = append(inv.Processes, id)
+ if !known[identityKey(id)] {
+ r.Known = append(r.Known, id)
+ known[identityKey(id)] = true
+ }
+ }
+ sort.Slice(inv.Processes, func(i, j int) bool { return inv.Processes[i].PID < inv.Processes[j].PID })
+ stage = 6
+ if !r.Owner.LocalOnly {
+ ids, err := p.client.ListTerminals(ctx, r.Owner.Workspace)
+ if err != nil {
+ unknown()
+ } else {
+ inv.TerminalIDs = ids
+ }
+ }
+ inv.Observed = append([]ProcessIdentity(nil), r.Known...)
+ inv.ExecutorGroups = append([]ProcessIdentity(nil), r.Owner.ExecutorGroups...)
+ if err := p.save(context.WithoutCancel(ctx), r); err != nil {
+ return ProcessInventory{}, err
+ }
+ if ctx.Err() != nil {
+ return inv, ctx.Err()
+ }
+ return inv, nil
+}
+func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ // Recheck against the host proc mount and use a pidfd so PID reuse cannot redirect a signal.
+ boot, bootErr := os.ReadFile("/proc/sys/kernel/random/boot_id")
+ if bootErr != nil || strings.TrimSpace(string(boot)) != id.BootID {
+ return paseo.ErrIdentity
+ }
+ if id.PID <= 1 || id.PID == os.Getpid() || id.BootID != p.boot {
+ return paseo.ErrIdentity
+ }
+ owned := false
+ for _, r := range p.records {
+ for _, known := range r.Known {
+ owned = owned || known == id
+ }
+ }
+ if !owned {
+ return paseo.ErrIdentity
+ }
+ status, err := os.ReadFile(filepath.Join(p.root, strconv.Itoa(id.PID), "status"))
+ if err != nil {
+ return err
+ }
+ host := false
+ for _, line := range strings.Split(string(status), "\n") {
+ if strings.HasPrefix(line, "NSpid:") {
+ f := strings.Fields(line)
+ host = len(f) == 2 && f[1] == strconv.Itoa(id.PID)
+ }
+ }
+ if !host {
+ return paseo.ErrIdentity
+ }
+ var st unix.Stat_t
+ if unix.Stat(filepath.Join(p.root, strconv.Itoa(id.PID)), &st) != nil || st.Uid != uint32(os.Getuid()) {
+ return paseo.ErrIdentity
+ }
+ fd, err := unix.PidfdOpen(id.PID, 0)
+ if err != nil {
+ return err
+ }
+ defer unix.Close(fd)
+ hostInspector := &LinuxProcessInspector{root: "/proc", boot: p.boot}
+ current, err := hostInspector.identity(id.PID)
+ if err != nil || current != id {
+ return paseo.ErrIdentity
+ }
+ if err = p.journal.saveState(ctx, "signal", identityKey(id), id); err != nil {
+ return err
+ }
+ current, err = hostInspector.identity(id.PID)
+ if err != nil || current != id {
+ return paseo.ErrIdentity
+ }
+ if err = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0); err != nil {
+ return err
+ }
+ p.stopped[id.PID] = id
+ fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
+ n, err := unix.Poll(fds, 1000)
+ if err != nil || n != 1 {
+ return paseo.ErrUncertain
+ }
+ return nil
+}
+
+// Persistent supervisor state shares the journal's FULL synchronous commits.
+func (j *Journal) saveState(ctx context.Context, kind, key string, v any) error {
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ if len(raw) > 3<<20 {
+ return ErrJournal
+ }
+ _, err = j.db.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES(?,?,?) ON CONFLICT(kind,state_key) DO UPDATE SET body=excluded.body", kind, key, raw)
+ if err != nil {
+ return j.fail()
+ }
+ return nil
+}
+func (j *Journal) readStates(ctx context.Context, kind string, out any) error {
+ rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_supervisor WHERE kind=? ORDER BY state_key", kind)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ list := []json.RawMessage{}
+ for rows.Next() {
+ var b []byte
+ if err = rows.Scan(&b); err != nil {
+ return err
+ }
+ list = append(list, b)
+ }
+ if err = rows.Err(); err != nil {
+ return err
+ }
+ raw, _ := json.Marshal(list)
+ return json.Unmarshal(raw, out)
+}
+
+func (p *LinuxProcessInspector) TrackPID(ctx context.Context, o ProcessOwner, pid int) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ r := p.records[ownerKey(o)]
+ if r == nil {
+ return paseo.ErrIdentity
+ }
+ if p.beforeTrackPID != nil {
+ p.beforeTrackPID(pid)
+ }
+ e, err := p.entry(pid)
+ if err != nil || e.dead {
+ return paseo.ErrUncertain
+ }
+ var st unix.Stat_t
+ if unix.Stat(filepath.Join(p.root, strconv.Itoa(pid)), &st) != nil || st.Uid != uint32(os.Getuid()) {
+ return paseo.ErrIdentity
+ }
+ r.Known = append(r.Known, e.id)
+ r.Owner.ExecutorGroups = append(r.Owner.ExecutorGroups, e.id)
+ return p.save(ctx, r)
+}
+
+// InspectProcesses is the preflight gate before a workspace exists. Track then
+// binds continuous inventory to the actual workspace before the first prompt.
+func (p *LinuxProcessInspector) InspectProcesses(ctx context.Context, _ paseo.Selection) (bool, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ entries, err := os.ReadDir(p.root)
+ if err != nil {
+ return false, err
+ }
+ for _, d := range entries {
+ if ctx.Err() != nil {
+ return false, ctx.Err()
+ }
+ pid, err := strconv.Atoi(d.Name())
+ if err != nil {
+ continue
+ }
+ var st unix.Stat_t
+ if unix.Stat(filepath.Join(p.root, d.Name()), &st) != nil {
+ return false, paseo.ErrUncertain
+ }
+ if st.Uid != uint32(os.Getuid()) {
+ continue
+ }
+ e, err := p.entry(pid)
+ if err != nil {
+ return false, err
+ }
+ if e.dead {
+ continue
+ }
+ if _, err = os.ReadFile(filepath.Join(p.root, d.Name(), "environ")); err != nil {
+ return false, err
+ }
+ if _, err = os.Readlink(filepath.Join(p.root, d.Name(), "cwd")); err != nil {
+ return false, err
+ }
+ id, err := p.identity(pid)
+ if err != nil || id != e.id {
+ return false, paseo.ErrUncertain
+ }
+ }
+ return true, nil
+}
diff --git a/internal/runner/process_linux_test.go b/internal/runner/process_linux_test.go
new file mode 100644
index 00000000..a5eca4a7
--- /dev/null
+++ b/internal/runner/process_linux_test.go
@@ -0,0 +1,302 @@
+package runner
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "golang.org/x/sys/unix"
+)
+
+type terminalFixture struct {
+ ids []string
+ err error
+}
+
+func (f *terminalFixture) ListTerminals(context.Context, paseo.Workspace) ([]string, error) {
+ return f.ids, f.err
+}
+func (f *terminalFixture) KillTerminal(_ context.Context, w paseo.Workspace, id string) error {
+ for i, v := range f.ids {
+ if v == id {
+ f.ids = append(f.ids[:i], f.ids[i+1:]...)
+ return nil
+ }
+ }
+ return paseo.ErrIdentity
+}
+func processFixture(t *testing.T) (*LinuxProcessInspector, ProcessOwner) {
+ t.Helper()
+ dir := t.TempDir()
+ os.Chmod(dir, 0700)
+ j, err := OpenJournal(context.Background(), filepath.Join(dir, "journal.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { j.Close() })
+ p, err := NewLinuxProcessInspector(isolatedProc(t), &terminalFixture{}, j)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := t.TempDir()
+ owner := ProcessOwner{Attempt: 1, Fence: 1, Marker: "test-" + filepath.Base(w), Workspace: paseo.Workspace{ServerID: "server", WorkspaceID: "workspace", Path: w}, AgentID: "agent"}
+ return p, owner
+}
+func childProcess(t *testing.T, dir, marker string) *exec.Cmd {
+ t.Helper()
+ c := exec.Command("/bin/sleep", "60")
+ c.Dir = dir
+ c.Env = []string{"EQUIPO_ATTEMPT_MARKER=" + marker}
+ c.SysProcAttr = &unix.SysProcAttr{Setsid: true}
+ if err := c.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { c.Process.Kill(); c.Wait() })
+ return c
+}
+func TestLinuxInspectorEnvironmentStrippedChild(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ // The marked parent exits after launching a detached child without its environment.
+ c := exec.Command("/bin/sh", "-c", "env -i /usr/bin/setsid /bin/sleep 60 >/dev/null 2>&1 & echo $!")
+ c.Dir = o.Workspace.Path
+ c.Env = []string{"PATH=/usr/bin:/bin", "EQUIPO_ATTEMPT_MARKER=" + o.Marker}
+ raw, err := c.Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ linkProcess(t, p.root, pid)
+ childID, err := p.identity(pid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = p.Stop(context.Background(), childID) })
+ inv, err := p.Remaining(ctx, o)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !inv.CoverageKnown || len(inv.Processes) != 1 || inv.Processes[0].PID != pid {
+ t.Fatalf("detached child missing: %+v", inv)
+ }
+ if err := p.Stop(ctx, inv.Processes[0]); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 100; i++ {
+ inv, err = p.Remaining(ctx, o)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(inv.Processes) == 0 {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !inv.CoverageKnown || len(inv.Processes) != 0 {
+ t.Fatalf("owned child survived: %+v", inv)
+ }
+}
+func TestProcessIdentityReuse(t *testing.T) {
+ p, o := processFixture(t)
+ control := childProcess(t, t.TempDir(), "control")
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ linkProcess(t, p.root, control.Process.Pid)
+ id, err := p.identity(control.Process.Pid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ id.StartTicks++
+ if err := p.Stop(ctx, id); err == nil {
+ t.Fatal("reused PID accepted")
+ }
+ if err := control.Process.Signal(unix.Signal(0)); err != nil {
+ t.Fatal("control killed", err)
+ }
+ id.PID = 1
+ if err := p.Stop(ctx, id); err == nil {
+ t.Fatal("namespace/control PID accepted")
+ }
+}
+func TestLinuxInspectorUnknownCoverage(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ cancelled, cancel := context.WithCancel(ctx)
+ cancel()
+ _, _ = p.Remaining(cancelled, o)
+ inv, _ := p.Remaining(ctx, o)
+ if inv.CoverageKnown {
+ t.Fatal("interrupted inventory became known")
+ }
+}
+func TestLinuxInspectorTrackedChildChangesCWD(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ ready := filepath.Join(t.TempDir(), "go")
+ c := exec.Command("/bin/sh", "-c", `while [ ! -f "$1" ]; do /bin/sleep 0.01; done; cd /; exec /bin/sleep 60`, "sh", ready)
+ c.Dir = o.Workspace.Path
+ c.Env = []string{"PATH=/usr/bin:/bin"}
+ if err := c.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { c.Process.Kill(); c.Wait() })
+ linkProcess(t, p.root, c.Process.Pid)
+ inv, err := p.Remaining(ctx, o)
+ if err != nil || len(inv.Processes) == 0 {
+ t.Fatalf("not tracked: %+v %v", inv, err)
+ }
+ os.WriteFile(ready, []byte("go"), 0600)
+ time.Sleep(50 * time.Millisecond)
+ inv, err = p.Remaining(ctx, o)
+ found := false
+ for _, id := range inv.Processes {
+ found = found || id.PID == c.Process.Pid
+ }
+ if err != nil || !found {
+ t.Fatalf("lost tracked child: %+v %v", inv, err)
+ }
+}
+
+// A proc fixture exposes actual kernel entries for only test-owned processes.
+// The host-wide test below separately proves inaccessible peers deny coverage.
+func isolatedProc(t *testing.T) string {
+ t.Helper()
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, "sys/kernel/random"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink("/proc/sys/kernel/random/boot_id", filepath.Join(root, "sys/kernel/random/boot_id")); err != nil {
+ t.Fatal(err)
+ }
+ return root
+}
+func linkProcess(t *testing.T, root string, pid int) {
+ t.Helper()
+ if err := os.Symlink("/proc/"+strconv.Itoa(pid), filepath.Join(root, strconv.Itoa(pid))); err != nil {
+ t.Fatal(err)
+ }
+}
+func TestLinuxInspectorHostCoverage(t *testing.T) {
+ p, o := processFixture(t)
+ p.root = "/proc"
+ err := p.Track(context.Background(), o)
+ inv, _ := p.Remaining(context.Background(), o)
+ if err != nil && inv.CoverageKnown {
+ t.Fatal("failed scan reported known")
+ }
+}
+
+func TestLinuxInspectorLostAttribution(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ c := childProcess(t, t.TempDir(), "stripped")
+ linkProcess(t, p.root, c.Process.Pid)
+ inv, err := p.Remaining(ctx, o)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if inv.CoverageKnown {
+ t.Fatal("unattributed new process treated as unrelated")
+ }
+}
+
+func TestLinuxInspectorUnreadableSameUser(t *testing.T) {
+ p, o := processFixture(t)
+ pid := 12345
+ dir := filepath.Join(p.root, strconv.Itoa(pid))
+ if err := os.Mkdir(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ stat, err := os.ReadFile("/proc/self/stat")
+ if err != nil {
+ t.Fatal(err)
+ }
+ stat = []byte(strconv.Itoa(pid) + string(stat[strings.IndexByte(string(stat), ' '):]))
+ if err = os.WriteFile(filepath.Join(dir, "stat"), stat, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(dir, "environ"), []byte{}, 0000); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Symlink(o.Workspace.Path, filepath.Join(dir, "cwd")); err != nil {
+ t.Fatal(err)
+ }
+ if err = p.Track(context.Background(), o); err == nil {
+ t.Fatal("unreadable same-user process admitted")
+ }
+ inv, _ := p.Remaining(context.Background(), o)
+ if inv.CoverageKnown {
+ t.Fatal("unreadable inventory acknowledged")
+ }
+}
+
+func TestLinuxInspectorMonitoringGap(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ p.records[ownerKey(o)].LastScanElapsed -= 3 * time.Second
+ inv, err := p.Remaining(ctx, o)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if inv.CoverageKnown {
+ t.Fatal("monitoring gap accepted as coverage")
+ }
+}
+
+func TestProcessIdentityNamespacePID(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ control := childProcess(t, o.Workspace.Path, o.Marker)
+ pid := control.Process.Pid
+ dir := filepath.Join(p.root, strconv.Itoa(pid))
+ if err := os.Mkdir(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"stat", "environ", "cwd"} {
+ if err := os.Symlink(filepath.Join("/proc", strconv.Itoa(pid), name), filepath.Join(dir, name)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(dir, "status"), []byte("NSpid:\t"+strconv.Itoa(pid)+"\t7\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ id, err := p.identity(pid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = p.Stop(ctx, id); err == nil {
+ t.Fatal("namespace PID signalled host control")
+ }
+ if err = control.Process.Signal(unix.Signal(0)); err != nil {
+ t.Fatal("host control did not survive", err)
+ }
+}
diff --git a/internal/runner/service.go b/internal/runner/service.go
new file mode 100644
index 00000000..3658a556
--- /dev/null
+++ b/internal/runner/service.go
@@ -0,0 +1,105 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+)
+
+type AssignmentSource interface {
+ Poll(context.Context) ([]runnerproto.Assignment, error)
+ Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error)
+}
+type Service struct {
+ Supervisor *Supervisor
+ Source AssignmentSource
+}
+
+func (s *Service) Run(ctx context.Context) error {
+ if s.Supervisor == nil || s.Source == nil {
+ return paseo.ErrContract
+ }
+ claimErr := s.recoverClaims(ctx)
+ cleanupErr := s.Supervisor.Recover(ctx)
+ if err := errors.Join(claimErr, cleanupErr); err != nil {
+ s.Supervisor.ready = false
+ return err
+ }
+ for {
+ if ctx.Err() != nil {
+ return ctx.Err()
+ }
+ assignments, err := s.Source.Poll(ctx)
+ if err != nil {
+ return err
+ }
+ for _, a := range assignments {
+ if err = s.Supervisor.journal.saveState(ctx, "assignment", a.ID, a); err != nil {
+ return err
+ }
+ request := runnerproto.ClaimRequest{Version: 1, AssignmentID: a.ID, Revision: a.Revision, RequestID: rand.Text()}
+ if err = s.Supervisor.journal.saveState(ctx, "claim", a.ID, request); err != nil {
+ return err
+ }
+ claim, err := s.Source.Claim(ctx, request)
+ if err != nil {
+ return err
+ }
+ if err = s.Supervisor.Run(ctx, RunClaim{Assignment: a, ClaimResponse: claim}); err != nil {
+ return err
+ }
+ }
+ }
+}
+
+func (s *Service) recoverClaims(ctx context.Context) error {
+ var claims []runnerproto.ClaimRequest
+ var attempts []attemptState
+ if err := s.Supervisor.journal.readStates(ctx, "claim", &claims); err != nil {
+ return err
+ }
+ if err := s.Supervisor.journal.readStates(ctx, "attempt", &attempts); err != nil {
+ return err
+ }
+ saved := map[string]bool{}
+ for _, a := range attempts {
+ saved[a.Claim.Assignment.ID] = true
+ }
+ for _, q := range claims {
+ if saved[q.AssignmentID] {
+ continue
+ }
+ source, ok := s.Source.(interface {
+ RecoverClaim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error)
+ })
+ if !ok || s.Supervisor.workflow == nil {
+ return paseo.ErrUncertain
+ }
+ reply, err := source.RecoverClaim(ctx, q)
+ if err != nil {
+ return err
+ }
+ if !reply.LeaseDeadline.IsZero() || !reply.AttemptDeadline.IsZero() {
+ return paseo.ErrIdentity
+ }
+ var assignment runnerproto.Assignment
+ var raw []byte
+ if err = s.Supervisor.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_supervisor WHERE kind='assignment' AND state_key=?", q.AssignmentID).Scan(&raw); err != nil {
+ return err
+ }
+ if json.Unmarshal(raw, &assignment) != nil {
+ return paseo.ErrIdentity
+ }
+ record := &attemptState{Claim: RunClaim{Assignment: assignment, ClaimResponse: reply}, Phase: "recovering", Owner: ProcessOwner{LocalOnly: true, Attempt: reply.Handle.Attempt, Fence: reply.Handle.Fence, Marker: assignment.ID, Workspace: paseo.Workspace{Path: s.Supervisor.workflow.cfg.Workspaces.PreparationDirectory()}}}
+ if err = s.Supervisor.save(ctx, record); err != nil {
+ return err
+ }
+ if err = s.Supervisor.inspector.Track(ctx, record.Owner); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go
new file mode 100644
index 00000000..1c9597e4
--- /dev/null
+++ b/internal/runner/supervisor.go
@@ -0,0 +1,426 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "golang.org/x/sys/unix"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type InstanceAPI interface {
+ Call(context.Context, string, runnerproto.RunnerRequest, any) error
+}
+type CleanupClient interface {
+ TerminalClient
+ Stop(context.Context, paseo.Agent) error
+ Archive(context.Context, paseo.Agent) error
+ ArchiveWorkspace(context.Context, paseo.Workspace) error
+}
+type RunClaim struct {
+ Assignment runnerproto.Assignment
+ runnerproto.ClaimResponse
+}
+type attemptState struct {
+ Claim RunClaim
+ Owner ProcessOwner
+ Agent paseo.Agent
+ Phase string
+ FailurePhase string
+ SocketPath, CapabilityPath string
+ Proof *ContainmentProof
+ Rotation *runnerproto.CredentialRotation
+ // Authority is deliberately not restored from this record.
+}
+type SupervisorConfig struct {
+ Journal *Journal
+ Client *paseo.Client
+ Inspector *LinuxProcessInspector
+ API InstanceAPI
+ Workflow *BugWorkflow
+ CredentialsPath string
+ InstallCredentials func(context.Context, runnerproto.CredentialRotation, string) error
+}
+type Supervisor struct {
+ journal *Journal
+ client CleanupClient
+ inspector ProcessInspector
+ api InstanceAPI
+ workflow *BugWorkflow
+ clock ElapsedClock
+ credentialsPath string
+ installCredentials func(context.Context, runnerproto.CredentialRotation, string) error
+ mu sync.Mutex
+ runMu sync.Mutex
+ activeKey string
+ activeCancel context.CancelFunc
+ activeSocket *AttemptSocket
+ activeStop runnerproto.RunnerRequest
+ states map[string]*attemptState
+ ready bool
+}
+
+func NewSupervisor(c SupervisorConfig) (*Supervisor, error) {
+ if c.Journal == nil || c.Client == nil || c.Inspector == nil || c.API == nil || c.Workflow == nil || !filepath.IsAbs(c.CredentialsPath) || filepath.Clean(c.CredentialsPath) != c.CredentialsPath || c.InstallCredentials == nil {
+ return nil, paseo.ErrContract
+ }
+ if c.Workflow.cfg.Witness == nil || c.Workflow.cfg.Workspaces == nil || c.Workflow.cfg.Client != c.Client || c.Inspector.client != c.Client || c.Inspector.journal != c.Journal || c.Workflow.cfg.Witness.journal != c.Journal {
+ return nil, paseo.ErrContract
+ }
+ return &Supervisor{journal: c.Journal, client: c.Client, inspector: c.Inspector, api: c.API, workflow: c.Workflow, clock: linuxClock{}, credentialsPath: c.CredentialsPath, installCredentials: c.InstallCredentials, states: map[string]*attemptState{}}, nil
+}
+func attemptKey(scope team.Scope, h team.Handle) string {
+ return runnerproto.EventHash([]any{scope, h.Attempt, h.Fence, h.Runner})
+}
+func (s *Supervisor) save(ctx context.Context, r *attemptState) error {
+ return s.journal.saveState(ctx, "attempt", attemptKey(r.Claim.Scope, r.Claim.Handle), r)
+}
+func (r *attemptState) request(op string) runnerproto.RunnerRequest {
+ return runnerproto.RunnerRequest{Version: 1, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, RequestID: attemptKey(r.Claim.Scope, r.Claim.Handle) + "/" + op}
+}
+func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error {
+ // One active attempt also serializes runner-wide credential rotation.
+ s.runMu.Lock()
+ defer s.runMu.Unlock()
+ if !s.ready {
+ return paseo.ErrUncertain
+ }
+ key := attemptKey(claim.Scope, claim.Handle)
+ if _, exists := s.states[key]; exists {
+ return paseo.ErrUncertain
+ }
+ if err := s.journal.AdmissionAllowed(ctx); err != nil {
+ return err
+ }
+ for _, old := range s.states {
+ if old.Phase != "contained" {
+ return paseo.ErrUncertain
+ }
+ }
+ now, err := s.clock.Read()
+ if err != nil {
+ return err
+ }
+ lease, err := newLease(now, claim.LeaseDeadline, claim.AttemptDeadline)
+ if err != nil {
+ return err
+ }
+ r := &attemptState{Claim: claim, Phase: "claimed"}
+ s.states[key] = r
+ raw, err := json.Marshal(r)
+ if err != nil {
+ return err
+ }
+ if _, err = s.journal.db.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('attempt',?,?)", key, raw); err != nil {
+ return paseo.ErrUncertain
+ }
+ active, cancel := context.WithCancel(ctx)
+ defer cancel()
+ s.mu.Lock()
+ s.activeKey = key
+ s.activeCancel = cancel
+ s.activeStop = r.request("stop")
+ s.mu.Unlock()
+ defer func() { s.mu.Lock(); s.activeKey = ""; s.activeCancel = nil; s.activeSocket = nil; s.mu.Unlock() }()
+ done := make(chan struct{})
+ go s.watchLease(active, cancel, r, lease, done)
+ err = s.workflow.run(active, s, r, lease)
+ if err != nil {
+ r.FailurePhase = r.Phase
+ }
+ cancel()
+ <-done
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
+ defer cleanupCancel()
+ if err != nil {
+ q := r.request("failed")
+ q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure}
+ _ = s.api.Call(cleanupCtx, "complete", q, nil)
+ }
+ _, cleanupErr := s.cleanup(cleanupCtx, r)
+ if err == nil && cleanupErr == nil && r.Claim.Assignment.StepKey == "publish" {
+ cleanupErr = s.api.Call(cleanupCtx, "conclude", r.request("conclude"), nil)
+ }
+ return errors.Join(err, cleanupErr)
+}
+func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, r *attemptState, l *leaseGuard, done chan struct{}) {
+ defer close(done)
+ tick := time.NewTicker(100 * time.Millisecond)
+ defer tick.Stop()
+ last, err := s.clock.Read()
+ if err != nil {
+ cancel()
+ return
+ }
+ renewAt := last.Elapsed + 15*time.Second
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-tick.C:
+ now, err := s.clock.Read()
+ if err != nil || l.check(now) != nil {
+ cancel()
+ return
+ }
+ if now.Elapsed < renewAt {
+ continue
+ }
+ // A blocked renewal never pauses the local lease watchdog.
+ reply := make(chan error, 1)
+ go func() {
+ var deadline time.Time
+ err := s.api.Call(ctx, "renew", r.request("renew"), &deadline)
+ if err == nil {
+ n, e := s.clock.Read()
+ if e != nil {
+ err = e
+ } else {
+ err = l.renew(n, deadline)
+ }
+ }
+ reply <- err
+ }()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case err := <-reply:
+ if err != nil {
+ cancel()
+ return
+ }
+ s.mu.Lock()
+ socket := s.activeSocket
+ s.mu.Unlock()
+ if socket != nil {
+ if err = socket.RenewLease(ctx, l.bound()); err != nil {
+ cancel()
+ return
+ }
+ }
+ renewAt = now.Elapsed + 15*time.Second
+ goto renewed
+ case <-tick.C:
+ n, e := s.clock.Read()
+ if e != nil || l.check(n) != nil {
+ cancel()
+ return
+ }
+ }
+ }
+ renewed:
+ }
+ }
+}
+func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle) (ContainmentProof, error) {
+ key := attemptKey(scope, h)
+ s.mu.Lock()
+ active := s.activeKey == key && s.activeCancel != nil
+ cancel := s.activeCancel
+ stop := s.activeStop
+ s.mu.Unlock()
+ if active {
+ _ = s.api.Call(ctx, "stop", stop, nil)
+ cancel()
+ }
+ s.runMu.Lock()
+ defer s.runMu.Unlock()
+ r := s.states[key]
+ if r == nil {
+ return ContainmentProof{}, paseo.ErrIdentity
+ }
+ // Instance fences first; failure never prevents local stopping.
+ if !active {
+ _ = s.api.Call(ctx, "stop", r.request("stop"), nil)
+ }
+ return s.cleanup(ctx, r)
+}
+func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentProof, error) {
+ proof := ContainmentProof{Scope: r.Claim.Scope, Handle: r.Claim.Handle, Owner: r.Owner}
+ if r.Phase == "contained" && r.Proof != nil {
+ return *r.Proof, nil
+ }
+ if r.Rotation != nil {
+ return s.finishRotation(ctx, r)
+ }
+ if r.Phase == "verified" && r.Proof != nil {
+ return s.reportContainment(ctx, r)
+ }
+ r.Phase = "stopping"
+ if err := s.save(ctx, r); err != nil {
+ return proof, err
+ }
+ if !validOwner(r.Owner) {
+ return proof, paseo.ErrUncertain
+ }
+ var failures error
+ if r.Agent.AgentID != "" {
+ failures = errors.Join(failures, s.client.Stop(ctx, r.Agent))
+ failures = errors.Join(failures, s.client.Archive(ctx, r.Agent))
+ }
+ inventory, err := s.inspector.Remaining(ctx, r.Owner)
+ failures = errors.Join(failures, err)
+ proof.Observed = append(proof.Observed, inventory.Observed...)
+ proof.Owner.ExecutorGroups = inventory.ExecutorGroups
+ for _, id := range inventory.Processes {
+ failures = errors.Join(failures, s.inspector.Stop(ctx, id))
+ }
+ for _, id := range inventory.TerminalIDs {
+ failures = errors.Join(failures, s.client.KillTerminal(ctx, r.Owner.Workspace, id))
+ }
+ if !r.Owner.LocalOnly {
+ failures = errors.Join(failures, s.client.ArchiveWorkspace(ctx, r.Owner.Workspace))
+ }
+ inventory, err = s.inspector.Remaining(ctx, r.Owner)
+ proof.Inventory = inventory
+ failures = errors.Join(failures, err)
+ if failures != nil {
+ return proof, failures
+ }
+ if !inventory.CoverageKnown || len(inventory.Processes) != 0 || len(inventory.TerminalIDs) != 0 || inventory.BootID == "" {
+ return proof, paseo.ErrUncertain
+ }
+ proof.Empty = true
+ r.Proof = &proof
+ r.Phase = "verified"
+ if err = s.save(ctx, r); err != nil {
+ return proof, err
+ }
+ return s.reportContainment(ctx, r)
+}
+func (s *Supervisor) reportContainment(ctx context.Context, r *attemptState) (ContainmentProof, error) {
+ if r.Proof == nil || !r.Proof.Empty {
+ return ContainmentProof{}, paseo.ErrUncertain
+ }
+ if err := s.cleanupSocket(ctx, r); err != nil {
+ return *r.Proof, err
+ }
+ q := r.request("contained")
+ raw, err := json.Marshal(r.Proof)
+ if err != nil {
+ return *r.Proof, err
+ }
+ q.Proof = raw
+ var rotation runnerproto.CredentialRotation
+ if err = s.api.Call(ctx, "contained", q, &rotation); err != nil {
+ return *r.Proof, err
+ }
+ r.Rotation = &rotation
+ if err = s.save(ctx, r); err != nil {
+ return *r.Proof, err
+ }
+ return s.finishRotation(ctx, r)
+}
+func (s *Supervisor) finishRotation(ctx context.Context, r *attemptState) (ContainmentProof, error) {
+ if r.Proof == nil || r.Rotation == nil {
+ return ContainmentProof{}, paseo.ErrUncertain
+ }
+ if r.Rotation.Bearer.Token != "" {
+ if s.credentialsPath == "" || s.installCredentials == nil {
+ return *r.Proof, paseo.ErrContract
+ }
+ if err := runnerproto.JournalCredentials(s.credentialsPath, r.Rotation); err != nil {
+ return *r.Proof, err
+ }
+ if err := s.installCredentials(ctx, *r.Rotation, r.request("contained").RequestID); err != nil {
+ return *r.Proof, err
+ }
+ }
+ r.Phase = "contained"
+ return *r.Proof, s.save(ctx, r)
+}
+func (s *Supervisor) Recover(ctx context.Context) error {
+ s.runMu.Lock()
+ defer s.runMu.Unlock()
+ s.ready = false
+ var states []attemptState
+ if err := s.journal.readStates(ctx, "attempt", &states); err != nil {
+ return err
+ }
+ var failures error
+ for i := range states {
+ r := &states[i]
+ s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] = r
+ if restore, ok := s.api.(interface{ RestoreClaim(RunClaim) error }); ok {
+ failures = errors.Join(failures, restore.RestoreClaim(r.Claim))
+ }
+ if r.Phase != "contained" {
+ _ = s.api.Call(ctx, "stop", r.request("stop"), nil)
+ if _, err := s.cleanup(ctx, r); err != nil {
+ failures = errors.Join(failures, err)
+ continue
+ }
+ }
+ if r.Claim.Assignment.StepKey == "publish" && r.FailurePhase == "" {
+ failures = errors.Join(failures, s.api.Call(ctx, "conclude", r.request("conclude"), nil))
+ }
+ }
+ for {
+ pending, err := s.journal.Pending(ctx, 128)
+ if err != nil {
+ failures = errors.Join(failures, err)
+ break
+ }
+ if len(pending) == 0 {
+ break
+ }
+ var batchErr error
+ for _, e := range pending {
+ q := runnerproto.RunnerRequest{Version: 1, AssignmentID: e.AssignmentID, Scope: e.Scope, Handle: e.Handle, RequestID: e.ID, ActionID: e.ActionID, Event: marshal(e)}
+ if err := s.api.Call(ctx, "events", q, nil); err != nil {
+ batchErr = errors.Join(batchErr, err)
+ continue
+ }
+ batchErr = errors.Join(batchErr, s.journal.Ack(ctx, e.ID))
+ }
+ if batchErr != nil {
+ failures = errors.Join(failures, batchErr)
+ break
+ }
+ }
+ s.ready = failures == nil
+ return failures
+}
+
+func (s *Supervisor) cleanupSocket(ctx context.Context, r *attemptState) error {
+ if r.SocketPath == "" {
+ return nil
+ }
+ s.mu.Lock()
+ socket := s.activeSocket
+ s.mu.Unlock()
+ if socket != nil && socket.SocketPath == r.SocketPath {
+ return socket.Cleanup(ctx, func(context.Context) error { return nil })
+ }
+ if s.workflow == nil {
+ return paseo.ErrIdentity
+ }
+ dir := filepath.Dir(r.SocketPath)
+ if filepath.Base(r.SocketPath) != "tool.sock" || r.CapabilityPath != filepath.Join(dir, "capability.json") || filepath.Dir(dir) != filepath.Join(s.workflow.cfg.StateDir, "attempts") {
+ return paseo.ErrIdentity
+ }
+ if _, err := os.Lstat(dir); os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ return err
+ }
+ parent, err := openPrivateDir(dir)
+ if err != nil {
+ return err
+ }
+ defer parent.Close()
+ for _, name := range []string{"tool.sock", "capability.json"} {
+ if err := unix.Unlinkat(int(parent.Fd()), name, 0); err != nil && err != unix.ENOENT {
+ return err
+ }
+ }
+ return os.Remove(dir)
+}
diff --git a/internal/runner/supervisor_test.go b/internal/runner/supervisor_test.go
new file mode 100644
index 00000000..1400d91b
--- /dev/null
+++ b/internal/runner/supervisor_test.go
@@ -0,0 +1,338 @@
+package runner
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "errors"
+ "golang.org/x/sys/unix"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strconv"
+ "testing"
+ "time"
+)
+
+type cleanupClient struct {
+ archiveErr error
+ terminalFixture
+ order *[]string
+}
+
+func (c *cleanupClient) Stop(context.Context, paseo.Agent) error {
+ *c.order = append(*c.order, "stop")
+ return nil
+}
+func (c *cleanupClient) Archive(context.Context, paseo.Agent) error {
+ *c.order = append(*c.order, "archive-agent")
+ return c.archiveErr
+}
+func (c *cleanupClient) ArchiveWorkspace(context.Context, paseo.Workspace) error {
+ *c.order = append(*c.order, "archive-workspace")
+ return nil
+}
+
+type cleanupInspector struct {
+ order *[]string
+ survivor, unknown bool
+}
+
+func (p *cleanupInspector) Track(context.Context, ProcessOwner) error { return nil }
+func (p *cleanupInspector) Remaining(context.Context, ProcessOwner) (ProcessInventory, error) {
+ *p.order = append(*p.order, "scan")
+ v := ProcessInventory{CoverageKnown: !p.unknown, BootID: "boot", CheckedAt: time.Now().UTC()}
+ if p.survivor {
+ v.Processes = []ProcessIdentity{{PID: 44, StartTicks: 5, BootID: "boot"}}
+ }
+ return v, nil
+}
+func (p *cleanupInspector) Stop(context.Context, ProcessIdentity) error {
+ *p.order = append(*p.order, "stop-check")
+ return nil
+}
+
+type supervisorAPI struct {
+ order *[]string
+ fail bool
+}
+
+func (a *supervisorAPI) Call(_ context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ *a.order = append(*a.order, op)
+ if a.fail {
+ return paseo.ErrUncertain
+ }
+ return nil
+}
+func cleanupFixture(t *testing.T) (*Supervisor, *attemptState, *cleanupInspector, *[]string) {
+ t.Helper()
+ dir := t.TempDir()
+ os.Chmod(dir, 0700)
+ j, err := OpenJournal(context.Background(), filepath.Join(dir, "journal.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { j.Close() })
+ order := []string{}
+ p := &cleanupInspector{order: &order}
+ client := &cleanupClient{order: &order}
+ api := &supervisorAPI{order: &order}
+ s := &Supervisor{journal: j, client: client, inspector: p, api: api, clock: linuxClock{}, states: map[string]*attemptState{}}
+ r := &attemptState{Claim: RunClaim{Assignment: runnerproto.Assignment{ID: "assignment", Kind: "step", StepKey: "reproduce"}, ClaimResponse: runnerproto.ClaimResponse{Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}}}, Owner: ProcessOwner{Attempt: 1, Fence: 1, Marker: "marker", AgentID: "agent", Workspace: paseo.Workspace{ServerID: "server", WorkspaceID: "workspace", Path: t.TempDir()}}, Agent: paseo.Agent{ServerID: "server", AgentID: "agent"}, Phase: "completed"}
+ s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] = r
+ if err := s.save(context.Background(), r); err != nil {
+ t.Fatal(err)
+ }
+ return s, r, p, &order
+}
+func TestCancelStopsArchivesThenVerifies(t *testing.T) {
+ s, r, _, order := cleanupFixture(t)
+ proof, err := s.Cancel(context.Background(), r.Claim.Scope, r.Claim.Handle)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !proof.Empty || !reflect.DeepEqual(*order, []string{"stop", "stop", "archive-agent", "scan", "archive-workspace", "scan", "contained"}) {
+ t.Fatalf("cleanup order/proof: %v %+v", *order, proof)
+ }
+}
+func TestCancelUnprovenInventory(t *testing.T) {
+ s, r, p, order := cleanupFixture(t)
+ p.survivor = true
+ proof, err := s.Cancel(context.Background(), r.Claim.Scope, r.Claim.Handle)
+ if err == nil || proof.Empty {
+ t.Fatal("survivor acknowledged")
+ }
+ for _, v := range *order {
+ if v == "contained" {
+ t.Fatal("reclaimed with survivor")
+ }
+ }
+ p.survivor = false
+ p.unknown = true
+ if proof, err = s.Cancel(context.Background(), r.Claim.Scope, r.Claim.Handle); err == nil || proof.Empty {
+ t.Fatal("unknown acknowledged")
+ }
+}
+func TestRunnerRestartDoesNotDuplicate(t *testing.T) {
+ s, r, _, order := cleanupFixture(t)
+ s.states = map[string]*attemptState{}
+ if err := s.Recover(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if r.Phase == "" || len(*order) == 0 {
+ t.Fatal("recovery omitted cleanup")
+ }
+ for _, v := range *order {
+ if v == "create" || v == "complete" {
+ t.Fatal("completion replayed", v)
+ }
+ }
+}
+func TestRunnerLeaseLoss(t *testing.T) {
+ start := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"}
+ cases := map[string]ClockReading{"rollback": {Wall: start.Wall.Add(-time.Second), Elapsed: start.Elapsed + time.Second, BootID: "boot"}, "suspend": {Wall: start.Wall.Add(time.Second), Elapsed: start.Elapsed + 50*time.Second, BootID: "boot"}, "reboot": {Wall: start.Wall, Elapsed: start.Elapsed, BootID: "new"}}
+ for name, v := range cases {
+ t.Run(name, func(t *testing.T) {
+ l, err := newLease(start, start.Wall.Add(60*time.Second), start.Wall.Add(20*time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if l.check(v) == nil {
+ t.Fatal("expired authority survived", v)
+ }
+ })
+ }
+ l, err := newLease(start, start.Wall.Add(60*time.Second), start.Wall.Add(20*time.Minute))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if l.renew(ClockReading{Wall: start.Wall.Add(51 * time.Second), Elapsed: start.Elapsed + 51*time.Second, BootID: "boot"}, start.Wall.Add(100*time.Second)) == nil {
+ t.Fatal("outage revived expired authority")
+ }
+}
+func TestRunnerSupervisorClosedConstructor(t *testing.T) {
+ if _, err := NewSupervisor(SupervisorConfig{}); !errors.Is(err, paseo.ErrContract) {
+ t.Fatal("missing production workflow accepted", err)
+ }
+}
+
+func TestRunnerBugPersonQuestion(t *testing.T) {
+ q := runnerproto.Question{Kind: "person", RawRequest: []byte(`{"id":"ask","kind":"person","question":"Which case?"}`)}
+ answer := runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: []byte(`{"answers":{"answer":"The first case"}}`)}
+ if err := q.ValidateAnswer(answer); err != nil {
+ t.Fatal("typed person answer rejected", err)
+ }
+ answer.UpdatedInput = []byte(`{"answers":{"arbitrary_permission":"allow"}}`)
+ if err := q.ValidateAnswer(answer); err == nil {
+ t.Fatal("person answer relaxed a permission")
+ }
+}
+
+func TestRunnerLeaseAttemptDeadline(t *testing.T) {
+ start := ClockReading{Wall: time.Now(), Elapsed: time.Hour, BootID: "boot"}
+ l, err := newLease(start, start.Wall.Add(60*time.Second), start.Wall.Add(30*time.Second))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if l.bound().After(start.Wall.Add(30 * time.Second)) {
+ t.Fatal("lease exceeded attempt deadline")
+ }
+ if err = l.renew(ClockReading{Wall: start.Wall.Add(15 * time.Second), Elapsed: start.Elapsed + 15*time.Second, BootID: "boot"}, start.Wall.Add(75*time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if l.bound().After(start.Wall.Add(30 * time.Second)) {
+ t.Fatal("renewal exceeded attempt deadline")
+ }
+}
+func TestRunnerRestartVerifiedProofDoesNotRescan(t *testing.T) {
+ s, r, p, _ := cleanupFixture(t)
+ api := s.api.(*supervisorAPI)
+ api.fail = true
+ _, err := s.cleanup(context.Background(), r)
+ if err == nil || r.Phase != "verified" {
+ t.Fatal("lost containment reply was not persisted", err)
+ }
+ api.fail = false
+ p.unknown = true
+ if err = s.Recover(context.Background()); err != nil {
+ t.Fatal("verified proof could not be retried after restart", err)
+ }
+}
+func TestCancelWitnessRejectsForgedProof(t *testing.T) {
+ s, r, _, _ := cleanupFixture(t)
+ proof, err := s.Cancel(context.Background(), r.Claim.Scope, r.Claim.Handle)
+ if err != nil {
+ t.Fatal(err)
+ }
+ witness, err := NewWitness(s.journal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := r.request("contained")
+ q.Proof = marshal(proof)
+ if err = witness.Containment(context.Background(), r.Claim.Assignment, q); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"empty", "coverage", "scope", "workspace", "agent", "time"} {
+ t.Run(name, func(t *testing.T) {
+ v := proof
+ switch name {
+ case "empty":
+ v.Empty = false
+ case "coverage":
+ v.Inventory.CoverageKnown = false
+ case "scope":
+ v.Scope.Job++
+ case "workspace":
+ v.Owner.Workspace.WorkspaceID = "other"
+ case "agent":
+ v.Owner.AgentID = "other"
+ case "time":
+ v.Inventory.CheckedAt = v.Inventory.CheckedAt.Add(time.Second)
+ }
+ q.Proof = marshal(v)
+ if err = witness.Containment(context.Background(), r.Claim.Assignment, q); err == nil {
+ t.Fatal("forged containment accepted", name)
+ }
+ })
+ }
+}
+
+func TestCancelArchiveFailureStillStopsChecks(t *testing.T) {
+ s, r, p, order := cleanupFixture(t)
+ p.survivor = true
+ s.client.(*cleanupClient).archiveErr = paseo.ErrUncertain
+ if _, err := s.Cancel(context.Background(), r.Claim.Scope, r.Claim.Handle); err == nil {
+ t.Fatal("archive failure acknowledged")
+ }
+ stopped := false
+ for _, step := range *order {
+ stopped = stopped || step == "stop-check"
+ }
+ if !stopped {
+ t.Fatal("archive failure skipped owned check cleanup")
+ }
+}
+func TestRunnerRestartCleansEveryAttempt(t *testing.T) {
+ s, r, p, order := cleanupFixture(t)
+ second := *r
+ second.Claim.Handle.Attempt = 2
+ second.Owner.Attempt = 2
+ second.Claim.Assignment.ID = "second"
+ if err := s.save(context.Background(), &second); err != nil {
+ t.Fatal(err)
+ }
+ p.unknown = true
+ if err := s.Recover(context.Background()); err == nil {
+ t.Fatal("unknown recovery acknowledged")
+ }
+ count := 0
+ for _, step := range *order {
+ if step == "archive-agent" {
+ count++
+ }
+ }
+ if count != 2 {
+ t.Fatal("recovery abandoned another attempt", count)
+ }
+}
+
+func TestCancelSurvivingBackgroundChild(t *testing.T) {
+ p, o := processFixture(t)
+ control := childProcess(t, t.TempDir(), "control")
+ linkProcess(t, p.root, control.Process.Pid)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ child := childProcess(t, o.Workspace.Path, "")
+ linkProcess(t, p.root, child.Process.Pid)
+ inv, err := p.Remaining(ctx, o)
+ if err != nil || !inv.CoverageKnown || len(inv.Processes) != 1 {
+ t.Fatalf("child attribution: %+v %v", inv, err)
+ }
+ s, r, _, _ := cleanupFixture(t)
+ s.inspector = p
+ r.Owner = o
+ r.Proof = nil
+ if err = s.save(ctx, r); err != nil {
+ t.Fatal(err)
+ }
+ witness, err := NewWitness(s.journal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := r.request("contained")
+ q.Proof = marshal(ContainmentProof{Scope: r.Claim.Scope, Handle: r.Claim.Handle, Owner: o, Inventory: inv, Empty: true})
+ if err = witness.Containment(ctx, r.Claim.Assignment, q); err == nil {
+ t.Fatal("surviving child accepted as empty")
+ }
+ proof, err := s.Cancel(ctx, r.Claim.Scope, r.Claim.Handle)
+ if err != nil || !proof.Empty {
+ t.Fatalf("exact stop did not contain child: %+v %v", proof, err)
+ }
+ if err = control.Process.Signal(unix.Signal(0)); err != nil {
+ t.Fatal("unrelated control killed", err)
+ }
+}
+
+func TestRunnerRestartDrainsReports(t *testing.T) {
+ s, _, _, _ := cleanupFixture(t)
+ ctx := context.Background()
+ for i := int64(1); i <= 130; i++ {
+ if err := s.journal.Append(ctx, journalEvent(strconv.FormatInt(i, 10), i)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.Recover(ctx); err != nil {
+ t.Fatal(err)
+ }
+ pending, err := s.journal.Pending(ctx, 128)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(pending) != 0 {
+ t.Fatal("restart left acknowledged reports pending", len(pending))
+ }
+}
diff --git a/internal/runner/tool_socket.go b/internal/runner/tool_socket.go
index 0b825ae1..8a9de2d9 100644
--- a/internal/runner/tool_socket.go
+++ b/internal/runner/tool_socket.go
@@ -65,12 +65,16 @@ type AttemptSocket struct {
capability toolCapability
mu sync.Mutex
invalid bool
+ pending bool
done chan struct{}
renewed chan struct{}
workers sync.WaitGroup
}
func NewAttemptSocket(ctx context.Context, stateDir string, b ToolBinding) (*AttemptSocket, error) {
+ return newAttemptSocket(ctx, stateDir, b, false)
+}
+func newAttemptSocket(ctx context.Context, stateDir string, b ToolBinding, pending bool) (*AttemptSocket, error) {
if !filepath.IsAbs(stateDir) || filepath.Clean(stateDir) != stateDir {
return nil, runnerproto.ErrInvalid
}
@@ -96,13 +100,16 @@ func NewAttemptSocket(ctx context.Context, stateDir string, b ToolBinding) (*Att
if err := os.Mkdir(dir, 0700); err != nil {
return nil, runnerproto.ErrInvalid
}
- s, err := ServeAttemptSocket(ctx, filepath.Join(dir, "tool.sock"), b)
+ s, err := serveAttemptSocket(ctx, filepath.Join(dir, "tool.sock"), b, pending)
if err != nil {
_ = os.Remove(dir)
}
return s, err
}
func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*AttemptSocket, error) {
+ return serveAttemptSocket(ctx, path, b, false)
+}
+func serveAttemptSocket(ctx context.Context, path string, b ToolBinding, pending bool) (*AttemptSocket, error) {
if len(path) > 107 || !filepath.IsAbs(path) || filepath.Clean(path) != path || b.Journal == nil || b.Current == nil || b.InstanceID == "" || b.TaskID == "" || b.Attempt <= 0 || b.Fence <= 0 || !time.Now().Before(b.LeaseDeadline) || b.Agent.ServerID == "" || b.Agent.AgentID == "" || b.Agent.ProviderSessionID == "" || len(b.Tools) == 0 || (b.Isolation.Status != "confined" && b.Isolation.Status != "unconfined") {
return nil, runnerproto.ErrInvalid
}
@@ -139,7 +146,7 @@ func ServeAttemptSocket(ctx context.Context, path string, b ToolBinding) (*Attem
}
defer parent.Close()
b.Tools = slices.Clone(b.Tools)
- s := &AttemptSocket{SocketPath: path, CapabilityPath: filepath.Join(filepath.Dir(path), "capability.json"), binding: b, done: make(chan struct{}), renewed: make(chan struct{}, 1)}
+ s := &AttemptSocket{pending: pending, SocketPath: path, CapabilityPath: filepath.Join(filepath.Dir(path), "capability.json"), binding: b, done: make(chan struct{}), renewed: make(chan struct{}, 1)}
s.capability = toolCapability{Copy: b.Copy, Secret: rand.Text() + rand.Text(), InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Tools: b.Tools, ExpiresAt: b.LeaseDeadline}
// Never overwrite an old socket or capability: restart needs a fresh directory.
if _, err := os.Lstat(path); !os.IsNotExist(err) {
@@ -323,7 +330,7 @@ func (s *AttemptSocket) submit(ctx context.Context, q toolRequest) error {
if subtle.ConstantTimeCompare([]byte(q.Capability), []byte(s.capability.Secret)) != 1 || q.InstanceID != b.InstanceID || q.TaskID != b.TaskID || q.Attempt != b.Attempt || q.Fence != b.Fence || !slices.Contains(b.Tools, q.Name) || q.RequestID == "" || len(q.RequestID) > 256 {
return runnerproto.ErrInvalid
}
- if s.invalid || !time.Now().Before(b.LeaseDeadline) {
+ if s.pending || s.invalid || !time.Now().Before(b.LeaseDeadline) {
s.invalidateLocked()
return runnerproto.ErrInvalid
}
@@ -445,3 +452,31 @@ func (s *AttemptSocket) MCPConfig(executable string) (paseo.MCPServer, error) {
}
func toolOwner(uid uint32) bool { return uid == uint32(os.Getuid()) }
+
+// NewPendingAttemptSocket reserves the MCP address before agent creation. No
+// request is accepted until the returned observed identity is bound.
+func NewPendingAttemptSocket(ctx context.Context, stateDir string, b ToolBinding) (*AttemptSocket, error) {
+ provider := b.Agent.Provider
+ b.Agent.ServerID = "pending"
+ b.Agent.AgentID = "pending"
+ b.Agent.ProviderSessionID = "pending"
+ s, err := newAttemptSocket(ctx, stateDir, b, true)
+ if err != nil {
+ return nil, err
+ }
+ s.mu.Lock()
+ s.pending = true
+ s.binding.Agent = paseo.Agent{Provider: provider}
+ s.mu.Unlock()
+ return s, nil
+}
+func (s *AttemptSocket) BindAgent(a paseo.Agent) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.pending || s.invalid || a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" || a.Provider != s.binding.Agent.Provider {
+ return paseo.ErrIdentity
+ }
+ s.binding.Agent = a
+ s.pending = false
+ return nil
+}
diff --git a/internal/runner/witness.go b/internal/runner/witness.go
new file mode 100644
index 00000000..eca0db4b
--- /dev/null
+++ b/internal/runner/witness.go
@@ -0,0 +1,182 @@
+package runner
+
+import (
+ "bytes"
+ "context"
+ "database/sql"
+ "encoding/json"
+ "sync"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+// Witness validates against supervisor observations, never submitted labels.
+// Its journal must be provided by the trusted runner transport at startup.
+type Witness struct {
+ journal *Journal
+ mu sync.Mutex
+ executors map[string]*checks.Executor
+}
+
+func NewWitness(j *Journal) (*Witness, error) {
+ if j == nil {
+ return nil, paseo.ErrContract
+ }
+ return &Witness{journal: j, executors: map[string]*checks.Executor{}}, nil
+}
+func (w *Witness) record(ctx context.Context, kind, key string, v any) error {
+ return w.journal.saveState(ctx, "witness-"+kind, key, v)
+}
+func (w *Witness) read(ctx context.Context, kind, key string, out any) error {
+ var b []byte
+ if err := w.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_supervisor WHERE kind=? AND state_key=?", "witness-"+kind, key).Scan(&b); err != nil {
+ return paseo.ErrUncertain
+ }
+ if json.Unmarshal(b, out) != nil {
+ return paseo.ErrUncertain
+ }
+ return nil
+}
+func (w *Witness) recordArtifact(ctx context.Context, c RunClaim, spec team.ArtifactSpec) error {
+ return w.record(ctx, "artifact", artifactKey(c.Scope, c.Handle, spec), spec)
+}
+func artifactKey(scope team.Scope, h team.Handle, spec team.ArtifactSpec) string {
+ return runnerproto.EventHash([]any{attemptKey(scope, h), spec.Role, team.ContentDigest(spec.Payload)})
+}
+func (w *Witness) Artifact(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) error {
+ if q.Artifact == nil || a.ID != q.AssignmentID {
+ return paseo.ErrIdentity
+ }
+ var saved team.ArtifactSpec
+ if err := w.read(ctx, "artifact", artifactKey(q.Scope, q.Handle, *q.Artifact), &saved); err != nil {
+ return err
+ }
+ if saved.Role != q.Artifact.Role || !bytes.Equal(saved.Payload, q.Artifact.Payload) {
+ return paseo.ErrIdentity
+ }
+ return nil
+}
+func (w *Witness) Prepare(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) (runnerproto.PreparedBug, error) {
+ var p runnerproto.PreparedBug
+ if a.ID != q.AssignmentID {
+ return p, paseo.ErrIdentity
+ }
+ if err := w.read(ctx, "prepare", a.ID, &p); err != nil {
+ return p, err
+ }
+ var submitted runnerproto.PreparedBug
+ if json.Unmarshal(q.Prepared, &submitted) != nil || !bytes.Equal(marshal(p), marshal(submitted)) {
+ return p, paseo.ErrIdentity
+ }
+ return p, nil
+}
+func (w *Witness) Provenance(ctx context.Context, _ *sql.Tx, scope team.Scope, h team.Handle) (team.Provenance, error) {
+ var a paseo.Agent
+ if err := w.read(ctx, "session", attemptKey(scope, h), &a); err != nil {
+ var p team.Provenance
+ if err = w.read(ctx, "runner-provenance", attemptKey(scope, h), &p); err != nil {
+ return p, err
+ }
+ return p, nil
+ }
+ return team.Provenance{Producer: a.AgentID, Provider: a.Provider, ModelFamily: a.Family, Context: a.ProviderSessionID}, nil
+}
+func (w *Witness) installExecutor(c RunClaim, e *checks.Executor) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.executors[attemptKey(c.Scope, c.Handle)] = e
+}
+func (w *Witness) ExecutorEvidence(ctx context.Context, tx *sql.Tx, scope team.Scope, h team.Handle, spec team.ArtifactSpec) (team.Provenance, error) {
+ w.mu.Lock()
+ e := w.executors[attemptKey(scope, h)]
+ w.mu.Unlock()
+ if e == nil {
+ return team.Provenance{}, paseo.ErrUncertain
+ }
+ return e.ValidateEvidence(ctx, tx, scope, h, spec)
+}
+func (w *Witness) Events(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) error {
+ var e runnerproto.Event
+ if json.Unmarshal(q.Event, &e) != nil || e.Validate() != nil || e.AssignmentID != a.ID {
+ return paseo.ErrIdentity
+ }
+ var raw []byte
+ err := w.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE event_key=?", e.DedupKey()).Scan(&raw)
+ if err != nil {
+ return paseo.ErrUncertain
+ }
+ var saved runnerproto.Event
+ if json.Unmarshal(raw, &saved) != nil || saved.ContentHash() != e.ContentHash() {
+ return paseo.ErrIdentity
+ }
+ return nil
+}
+func (w *Witness) Receipt(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) (team.Receipt, error) {
+ var receipt team.Receipt
+ key := runnerproto.EventHash([]any{q.Scope, q.Handle.Attempt, q.Handle.Fence, q.ActionID})
+ if err := w.read(ctx, "receipt", key, &receipt); err != nil {
+ return receipt, err
+ }
+ if q.Receipt != nil && !bytes.Equal(marshal(receipt), marshal(q.Receipt)) {
+ return receipt, paseo.ErrIdentity
+ }
+ return receipt, nil
+}
+func (w *Witness) Question(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) error {
+ if q.Question == nil || q.Question.AssignmentID != a.ID {
+ return paseo.ErrIdentity
+ }
+ var saved runnerproto.Question
+ if err := w.read(ctx, "question", q.Question.ID, &saved); err != nil {
+ return err
+ }
+ if saved.AgentID != q.Question.AgentID || saved.SessionID != q.Question.SessionID || saved.PermissionID != q.Question.PermissionID || !bytes.Equal(saved.RawRequest, q.Question.RawRequest) {
+ return paseo.ErrIdentity
+ }
+ return nil
+}
+func (w *Witness) Containment(ctx context.Context, a runnerproto.Assignment, q runnerproto.RunnerRequest) error {
+ var proof ContainmentProof
+ if json.Unmarshal(q.Proof, &proof) != nil || !proof.Empty || proof.Scope != q.Scope || proof.Handle != q.Handle || proof.Owner.Attempt != q.Handle.Attempt || proof.Owner.Fence != q.Handle.Fence || !proof.Inventory.CoverageKnown || len(proof.Inventory.Processes) != 0 || len(proof.Inventory.TerminalIDs) != 0 || proof.Inventory.BootID == "" || proof.Inventory.CheckedAt.IsZero() {
+ return paseo.ErrIdentity
+ }
+ var states []attemptState
+ if err := w.journal.readStates(ctx, "attempt", &states); err != nil {
+ return err
+ }
+ for _, s := range states {
+ if s.Claim.Assignment.ID == a.ID && s.Proof != nil && bytes.Equal(marshal(s.Proof), marshal(proof)) {
+ return nil
+ }
+ }
+ return paseo.ErrIdentity
+}
+
+func (w *Witness) PublicationAuthorization(ctx context.Context, d team.Dispatch) (runnerproto.PublicationAuthorization, error) {
+ var auth runnerproto.PublicationAuthorization
+ if err := w.read(ctx, "publication", runnerproto.EventHash(d), &auth); err != nil {
+ return auth, err
+ }
+ if !bytes.Equal(marshal(auth.Ticket.Dispatch), marshal(d)) {
+ return auth, paseo.ErrIdentity
+ }
+ return auth, nil
+}
+
+func (w *Witness) PrepareBug(ctx context.Context, m *workspace.Manager, a runnerproto.Assignment, target team.TargetBinding) (runnerproto.PreparedBug, error) {
+ if m == nil || a.ID == "" || a.Kind != "prepare" {
+ return runnerproto.PreparedBug{}, paseo.ErrContract
+ }
+ prepared, err := m.Prepare(ctx, target)
+ if err != nil {
+ return prepared, err
+ }
+ if err = w.record(ctx, "prepare", a.ID, prepared); err != nil {
+ return runnerproto.PreparedBug{}, err
+ }
+ return prepared, nil
+}
diff --git a/internal/runner/workflow.go b/internal/runner/workflow.go
new file mode 100644
index 00000000..66585891
--- /dev/null
+++ b/internal/runner/workflow.go
@@ -0,0 +1,398 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type BugWorkflowConfig struct {
+ UsageProfile func(paseo.Selection) (UsageProfile, error)
+ Workspaces *workspace.Manager
+ Client *paseo.Client
+ Witness *Witness
+ Policy func(context.Context, paseo.Selection) (paseo.ReadPolicy, error)
+ Executor func(context.Context, RunClaim, checks.Definition, checks.Reproduction, time.Time) (*checks.Executor, error)
+ Publisher *forge.Publisher
+ StateDir, Executable, InstanceID string
+ Copy ToolCopy
+}
+type BugWorkflow struct{ cfg BugWorkflowConfig }
+
+func NewBugWorkflow(c BugWorkflowConfig) (*BugWorkflow, error) {
+ if c.Workspaces == nil || c.Client == nil || c.Witness == nil || c.Policy == nil || c.Executor == nil || c.Publisher == 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, paseo.ErrContract
+ }
+ return &BugWorkflow{cfg: c}, nil
+}
+func selection(a runnerproto.Assignment) paseo.Selection {
+ return paseo.Selection{ConnectionID: a.Selection.ConnectionID, Provider: a.Selection.Provider, Family: a.Selection.Family, Model: a.Selection.Model, AccountID: a.Selection.AccountID}
+}
+func (w *BugWorkflow) run(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard) error {
+ if r.Claim.Assignment.Kind == "prepare" {
+ r.Owner = ProcessOwner{LocalOnly: true, Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: r.Claim.Assignment.ID, Workspace: paseo.Workspace{Path: w.cfg.Workspaces.PreparationDirectory()}}
+ if err := s.save(ctx, r); err != nil {
+ return err
+ }
+ if err := s.inspector.Track(ctx, r.Owner); err != nil {
+ return err
+ }
+ ctx, stopMonitoring := monitorOwnership(ctx, s.inspector, r.Owner)
+ defer stopMonitoring()
+
+ inspector, ok := s.inspector.(*LinuxProcessInspector)
+ if !ok {
+ return paseo.ErrContract
+ }
+ ctx = checks.WithProcessOwnership(ctx, r.Owner.Marker, func(ctx context.Context, pid int) error { return inspector.TrackPID(ctx, r.Owner, pid) })
+ prepared, err := w.cfg.Witness.PrepareBug(ctx, w.cfg.Workspaces, r.Claim.Assignment, r.Claim.Brief.Target)
+ if err != nil {
+ return err
+ }
+ q := r.request("prepare")
+ q.Prepared, err = json.Marshal(prepared)
+ if err != nil {
+ return err
+ }
+ if err = s.api.Call(ctx, "prepare", q, nil); err != nil {
+ return err
+ }
+ r.Phase = "prepared"
+ return s.save(ctx, r)
+ }
+ r.Phase = "creating-workspace"
+ if err := s.save(ctx, r); err != nil {
+ return err
+ }
+ ws, err := w.cfg.Workspaces.Create(ctx, r.Claim.Assignment, r.Claim.Brief)
+ if err != nil {
+ return err
+ }
+ r.Owner = ProcessOwner{Attempt: r.Claim.Handle.Attempt, Fence: r.Claim.Handle.Fence, Marker: attemptKey(r.Claim.Scope, r.Claim.Handle), Workspace: ws.Paseo}
+ r.Phase = "workspace"
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ if err = s.inspector.Track(ctx, r.Owner); err != nil {
+ return err
+ }
+ ctx, stopMonitoring := monitorOwnership(ctx, s.inspector, r.Owner)
+ defer stopMonitoring()
+ owner := r.Owner
+ policy, err := w.cfg.Policy(ctx, selection(r.Claim.Assignment))
+ if err != nil {
+ return err
+ }
+ var socket *AttemptSocket
+ current := func(ctx context.Context) error {
+ now, err := s.clock.Read()
+ if err != nil {
+ return err
+ }
+ if err = l.check(now); err != nil {
+ return err
+ }
+ if err = w.cfg.Workspaces.ValidateTurn(ctx, r.Claim.Assignment, ws); err != nil {
+ return err
+ }
+ if err = s.api.Call(ctx, "validate", r.request("validate"), nil); err != nil {
+ return err
+ }
+ if r.Agent.AgentID != "" {
+ if err = s.journal.Ready(ctx, r.Agent); err != nil {
+ return err
+ }
+ }
+ inv, err := s.inspector.Remaining(ctx, owner)
+ if err != nil {
+ return err
+ }
+ if !inv.CoverageKnown {
+ return paseo.ErrUncertain
+ }
+ return nil
+ }
+ step := r.Claim.Assignment.StepKey
+ var artifacts []team.Artifact
+ if err = s.api.Call(ctx, "evidence", r.request("evidence"), &artifacts); err != nil {
+ return err
+ }
+ for i, art := range artifacts {
+ q := r.request("evidence")
+ q.ArtifactID = art.ID
+ var full team.Artifact
+ if err = s.api.Call(ctx, "evidence", q, &full); err != nil {
+ return err
+ }
+ if full.ID != art.ID || full.Hash != art.Hash || team.ContentDigest(full.Payload) != art.Hash {
+ return paseo.ErrIdentity
+ }
+ artifacts[i] = full
+ }
+ var definition checks.Definition
+ if json.Unmarshal(r.Claim.Brief.CheckDefinition, &definition) != nil {
+ return paseo.ErrIdentity
+ }
+ var reproduction checks.Reproduction
+ var candidate team.GitCandidate
+ var candidateHash string
+ for _, a := range artifacts {
+ switch a.Role {
+ case team.RoleReproduction:
+ if json.Unmarshal(a.Payload, &reproduction) != nil {
+ return paseo.ErrIdentity
+ }
+ case team.RoleCandidate:
+ if json.Unmarshal(a.Payload, &candidate) != nil {
+ return paseo.ErrIdentity
+ }
+ candidateHash = a.Hash
+ }
+ }
+ if step == "review" {
+ if candidateHash == "" {
+ return paseo.ErrIdentity
+ }
+ if err = w.cfg.Workspaces.CheckoutCandidate(ctx, ws, candidate); err != nil {
+ return err
+ }
+ }
+
+ if step == "reproduce" || step == "implement" || step == "review" {
+ tool := map[string]string{"reproduce": "submit_reproduction", "implement": "submit_candidate", "review": "submit_review"}[step]
+ r.Phase = "creating-socket"
+ socket, err = NewPendingAttemptSocket(ctx, w.cfg.StateDir, 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: paseo.Agent{Provider: r.Claim.Assignment.Selection.Provider}, Isolation: r.Claim.Assignment.Selection.Isolation, Journal: s.journal, Current: current})
+ if err != nil {
+ return err
+ }
+ defer socket.Invalidate()
+ s.mu.Lock()
+ s.activeSocket = socket
+ s.mu.Unlock()
+ r.SocketPath = socket.SocketPath
+ r.CapabilityPath = socket.CapabilityPath
+ mcp, err := socket.MCPConfig(w.cfg.Executable)
+ if err != nil {
+ return err
+ }
+ mcp.Env["EQUIPO_ATTEMPT_MARKER"] = r.Owner.Marker
+ r.Phase = "creating-agent"
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ env := ws.Environment()
+ env["EQUIPO_ATTEMPT_MARKER"] = r.Owner.Marker
+ options, err := w.cfg.Client.ProviderPolicy(ctx, selection(r.Claim.Assignment), policy)
+ if err != nil {
+ return err
+ }
+ agent, err := w.cfg.Client.CreateAgent(ctx, paseo.AgentRequest{ProviderOptions: options, Workspace: ws.Paseo, Selection: selection(r.Claim.Assignment), IdempotencyKey: r.request("agent").RequestID, ModeID: "default", ReadPolicy: policy, Env: env, MCPServers: map[string]paseo.MCPServer{"equipo": mcp}})
+ if err != nil {
+ return err
+ }
+ r.Agent = agent
+ r.Owner.AgentID = agent.AgentID
+ r.Phase = "tracking-agent"
+ if err = s.inspector.Track(ctx, r.Owner); err != nil {
+ return err
+ }
+ // Keep the ownership key stable across creation; the agent identity is saved separately.
+ r.Phase = "agent"
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ if err = socket.BindAgent(agent); err != nil {
+ return err
+ }
+ if err = w.cfg.Witness.record(ctx, "session", attemptKey(r.Claim.Scope, r.Claim.Handle), agent); err != nil {
+ return err
+ }
+ r.Phase = "turn"
+ if err = w.modelTurn(ctx, s, r, l, current, socket, artifacts); err != nil {
+ return err
+ }
+ }
+ if err = current(ctx); err != nil {
+ return err
+ }
+ register := func(role team.Role, value any) (team.Artifact, error) {
+ raw, err := json.Marshal(value)
+ if err != nil {
+ return team.Artifact{}, err
+ }
+ spec := team.ArtifactSpec{Role: role, MediaType: "application/json", Payload: raw}
+ if role == team.RoleCandidate {
+ spec.MediaType = team.GitCandidateMediaType
+ }
+ if err = w.cfg.Witness.recordArtifact(ctx, r.Claim, spec); err != nil {
+ return team.Artifact{}, err
+ }
+ q := r.request("artifact-" + string(role))
+ q.Artifact = &spec
+ var result team.Artifact
+ err = s.api.Call(ctx, "artifacts", q, &result)
+ return result, err
+ }
+ if step == "reproduce" || step == "implement" || step == "review" {
+ 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]
+ 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 {
+ if submission != nil {
+ return paseo.ErrIdentity
+ }
+ submission = t
+ }
+ }
+ if submission == nil {
+ return paseo.ErrUncertain
+ }
+ switch step {
+ case "reproduce":
+ if err = json.Unmarshal(submission.Arguments, &reproduction); err != nil {
+ return err
+ }
+ art, err := register(team.RoleReproduction, 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 {
+ return err
+ }
+ case "implement":
+ var submitted CandidateSubmission
+ if json.Unmarshal(submission.Arguments, &submitted) != nil {
+ return paseo.ErrIdentity
+ }
+ candidate, err = w.cfg.Workspaces.CaptureCandidate(ctx, ws, r.Claim.Brief.Target)
+ if err != nil {
+ return err
+ }
+ if candidate.Commit != submitted.Commit {
+ return paseo.ErrIdentity
+ }
+ if _, err = register(team.RoleCandidate, candidate); err != nil {
+ return err
+ }
+ case "review":
+ var review ReviewSubmission
+ if json.Unmarshal(submission.Arguments, &review) != nil || review.Candidate != candidate.Commit {
+ return paseo.ErrIdentity
+ }
+ if _, err = register(team.RoleReview, team.Review{SubjectHash: candidateHash, Verdict: reviewVerdict(review.Decision), Notes: strings.Join(review.Findings, "\n")}); err != nil {
+ return err
+ }
+ if review.Decision != string(team.VerdictApprove) {
+ return team.ErrEvidence
+ }
+ }
+ if err = s.journal.AckTool(ctx, *submission); err != nil {
+ return err
+ }
+ }
+ if step == "verify" || 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" {
+ inspector, ok := s.inspector.(*LinuxProcessInspector)
+ if !ok {
+ return paseo.ErrContract
+ }
+ ctx = checks.WithProcessOwnership(ctx, r.Owner.Marker, func(ctx context.Context, pid int) error { return inspector.TrackPID(ctx, r.Owner, pid) })
+ executor, err := w.cfg.Executor(ctx, r.Claim, definition, reproduction, l.bound())
+ if err != nil {
+ return err
+ }
+ w.cfg.Witness.installExecutor(r.Claim, executor)
+ commit, subject := definition.Base, ""
+ role := team.RoleBaseResult
+ if step == "verify" {
+ commit, subject, role = candidate.Commit, candidateHash, team.RoleCandidateResult
+ }
+ result, err := executor.Reproduce(ctx, definition, reproduction, commit, subject)
+ if err != nil {
+ return err
+ }
+ if _, err = register(role, result); err != nil {
+ return err
+ }
+ if step == "verify" {
+ result, err := executor.RepositoryChecks(ctx, definition, candidate, candidateHash)
+ if err != nil {
+ return err
+ }
+ if _, err = register(team.RoleRepositoryChecks, result); err != nil {
+ return err
+ }
+ }
+ }
+ if step == "publish" {
+ if err = w.publish(ctx, s, r, current); err != nil {
+ return err
+ }
+ }
+ if err = current(ctx); err != nil {
+ return err
+ }
+ r.Phase = "completing"
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
+ q := r.request("complete")
+ q.Result = &team.AttemptResult{Outcome: team.OutcomeSuccess}
+ if err = s.api.Call(ctx, "complete", q, nil); err != nil {
+ return err
+ }
+ r.Phase = "completed"
+ return s.save(ctx, r)
+}
+func marshal(v any) []byte { b, _ := json.Marshal(v); return b }
+
+func reviewVerdict(decision string) team.Verdict {
+ if decision == "approve" {
+ return team.VerdictApprove
+ }
+ return team.VerdictReject
+}
+
+func monitorOwnership(parent context.Context, inspector ProcessInspector, owner ProcessOwner) (context.Context, func()) {
+ ctx, cancel := context.WithCancel(parent)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ inv, err := inspector.Remaining(context.WithoutCancel(ctx), owner)
+ if err != nil || !inv.CoverageKnown {
+ cancel()
+ return
+ }
+ }
+ }
+ }()
+ return ctx, func() { cancel(); <-done }
+}
diff --git a/internal/runner/workflow_integration_test.go b/internal/runner/workflow_integration_test.go
new file mode 100644
index 00000000..3e22077a
--- /dev/null
+++ b/internal/runner/workflow_integration_test.go
@@ -0,0 +1,419 @@
+package runner
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/checks"
+ "amadan.net/oficina/equipo/internal/runner/forge"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runner/workspace"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+type localRead struct{ path string }
+
+func (r localRead) Resolve(context.Context, string) (workspace.Remote, error) {
+ return workspace.Remote{URL: r.path}, nil
+}
+func wfMust(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+func wfGit(t *testing.T, dir string, args ...string) string {
+ t.Helper()
+ cmd := exec.Command("/usr/bin/git", args...)
+ cmd.Dir = dir
+ cmd.Env = []string{"PATH=/usr/bin:/bin", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@example.test", "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@example.test"}
+ b, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("git %v: %v %s", args, err, b)
+ }
+ return string(bytesTrim(b))
+}
+func bytesTrim(b []byte) []byte {
+ for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r') {
+ b = b[:len(b)-1]
+ }
+ return b
+}
+
+type coreWorkflowAPI struct {
+ t *testing.T
+ question *runnerproto.Question
+ admissions int
+ core *team.Store
+ w *Witness
+ assignments map[string]runnerproto.Assignment
+}
+
+func (a *coreWorkflowAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ assignment := a.assignments[q.AssignmentID]
+ var result any
+ var err error
+ switch op {
+ case "questions":
+ err = a.w.Question(ctx, assignment, q)
+ if err == nil {
+ copy := *q.Question
+ a.question = &copy
+ result = copy
+ }
+ case "answers":
+ if a.question == nil {
+ return paseo.ErrIdentity
+ }
+ copy := *a.question
+ copy.Answer = &runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: []byte(`{"answers":{"answer":"Use the failing value case"}}`)}
+ result = []runnerproto.Question{copy}
+ case "question_resolved":
+ err = a.w.Question(ctx, assignment, q)
+ case "validate":
+ err = a.core.ValidateHandle(ctx, q.Scope, q.Handle)
+ case "publication_ready":
+ result, err = a.core.Publication(ctx, q.Scope, q.Handle)
+ case "publication_authorize":
+ result, err = a.core.AuthorizePublication(ctx, q.Scope, q.Handle, q.ActionID, q.RequestID)
+ case "receipts":
+ var receipt team.Receipt
+ receipt, err = a.w.Receipt(ctx, assignment, q)
+ if err == nil {
+ err = a.core.Record(ctx, q.Scope, q.ActionID, receipt)
+ }
+ case "conclude":
+ result, err = a.core.Conclude(ctx, q.Scope, "runner")
+ case "renew":
+ result, err = a.core.Renew(ctx, q.Scope, q.Handle)
+ case "evidence":
+ if q.ArtifactID > 0 {
+ result, err = a.core.Artifact(ctx, q.Scope, q.ArtifactID)
+ } else {
+ result, err = a.core.Artifacts(ctx, q.Scope)
+ }
+ case "intend":
+ result, err = a.core.Intend(ctx, q.Scope, q.Handle, *q.Intent)
+ case "admit":
+ a.admissions++
+ result, err = a.core.AdmitOnce(ctx, q.Scope, q.Handle, q.ActionID, q.RequestID)
+ case "artifacts":
+ err = a.w.Artifact(ctx, assignment, q)
+ if err == nil {
+ result, err = a.core.Register(ctx, q.Scope, q.Handle, *q.Artifact)
+ }
+ case "events":
+ err = a.w.Events(ctx, assignment, q)
+ if err == nil {
+ var e Event
+ json.Unmarshal(q.Event, &e)
+ if e.Kind == "turn_completed" || e.Kind == "turn_failed" {
+ var receipt team.Receipt
+ receipt, err = a.w.Receipt(ctx, assignment, q)
+ if err == nil {
+ err = a.core.Record(ctx, q.Scope, q.ActionID, receipt)
+ }
+ }
+ }
+ case "freeze":
+ var f runnerproto.FreezeRequest
+ json.Unmarshal(q.Prepared, &f)
+ err = a.core.FreezeBugEvidence(ctx, q.Scope, q.Handle, f.ExpectedSymptom, f.DefinitionHash, f.ReproductionHash)
+ case "complete":
+ err = a.core.Complete(ctx, q.Scope, q.Handle, *q.Result)
+ case "stop":
+ err = a.core.StopAttempt(ctx, q.Scope, q.Handle, "test_stop")
+ case "contained":
+ if assignment.StepKey == "reproduce" {
+ if _, e := a.core.Claim(ctx, q.Scope, "implement", "runner", "too-early"); e == nil {
+ return fmt.Errorf("dependent claimed before containment")
+ }
+ }
+ err = a.w.Containment(ctx, assignment, q)
+ if err == nil {
+ err = a.core.ContainUntrusted(ctx, q.Scope, q.Handle)
+ }
+ default:
+ return fmt.Errorf("unexpected operation %s", op)
+ }
+ if err != nil {
+ return fmt.Errorf("%s: %w", op, err)
+ }
+ if out != nil && result != nil {
+ return json.Unmarshal(marshal(result), out)
+ }
+ return nil
+}
+func TestRunnerBugWorkflow(t *testing.T) {
+ ctx := context.Background()
+ root, err := os.MkdirTemp(os.Getenv("TMPDIR"), "e15-")
+ wfMust(t, err)
+ t.Cleanup(func() { os.RemoveAll(root) })
+ state := filepath.Join(root, "s")
+ private := filepath.Join(root, "p")
+ works := filepath.Join(root, "w")
+ scratch := filepath.Join(root, "c")
+ seed := filepath.Join(root, "seed")
+ for _, p := range []string{state, private, works, scratch, seed} {
+ wfMust(t, os.Mkdir(p, 0700))
+ }
+ j, err := OpenJournal(ctx, filepath.Join(state, "j.db"))
+ wfMust(t, err)
+ defer j.Close()
+ w, err := NewWitness(j)
+ wfMust(t, err)
+ proc := isolatedProc(t)
+ bridge := filepath.Join(root, "bridge.mjs")
+ script := fmt.Sprintf(workflowBridge, proc)
+ wfMust(t, os.WriteFile(bridge, []byte(script), 0600))
+ policy := paseo.ReadPolicy{ConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", DeniedPaths: []string{state, private}}
+ client, err := paseo.Start(ctx, paseo.Config{NodePath: "/usr/local/bin/node", BridgePath: bridge, DaemonHome: state, Endpoint: "127.0.0.1:1", ServerID: "server", RecordIntent: j.RecordIntent, InspectProcesses: func(context.Context, paseo.Selection) (bool, error) { return true, nil }, AuthorizeUnconfined: func(context.Context, paseo.Selection, paseo.Capabilities) error { return nil }, VerifiedTuples: []paseo.VerifiedTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", ConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}})
+ wfMust(t, err)
+ defer client.Close()
+ wfMust(t, os.WriteFile(filepath.Join(seed, "go.mod"), []byte("module fixture\n\ngo 1.26.0\n"), 0600))
+ wfMust(t, os.WriteFile(filepath.Join(seed, "value.go"), []byte("package fixture\nfunc Value() int {return 1}\n"), 0600))
+ 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))
+ wfGit(t, seed, "init", "-b", "main")
+ wfGit(t, seed, "add", ".")
+ wfGit(t, seed, "commit", "-m", "base")
+ base := wfGit(t, seed, "rev-parse", "HEAD")
+ remote := filepath.Join(root, "remote.git")
+ wfGit(t, root, "clone", "--bare", seed, remote)
+ protected := workspace.SecurityPaths{RunnerState: state, RunnerConfig: filepath.Join(state, "config"), Journal: filepath.Join(state, "j.db"), Bearer: filepath.Join(state, "bearer"), Cleanup: filepath.Join(state, "cleanup"), ForgeCredential: filepath.Join(state, "forge"), PaseoHome: filepath.Join(state, "paseo"), ProviderHomes: []string{filepath.Join(state, "provider")}, SSH: filepath.Join(state, "ssh")}
+ codex, err := exec.LookPath("codex")
+ wfMust(t, err)
+ goRoot := runtime.GOROOT()
+ sandbox, err := checks.NewCodexSandbox(ctx, checks.SandboxConfig{Binary: codex, ScratchRoot: scratch, GoRoot: goRoot, GoBinary: filepath.Join(goRoot, "bin/go"), Protected: protected})
+ wfMust(t, err)
+ iso := team.IsolationSnapshot{Status: "confined", ObservedTuples: []team.IsolationTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", IsolationConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}
+ target := team.TargetBinding{Kind: team.TargetRepository, Repository: "amadan.net/test/fixture", DefaultRef: "main", Ref: "equipo/test", BaseRevision: base}
+ var manager *workspace.Manager
+ var pinned checks.Definition
+ var repo string
+ executor := func(ctx context.Context, c RunClaim, d checks.Definition, r checks.Reproduction, deadline time.Time) (*checks.Executor, error) {
+ return checks.New(checks.Config{ScratchRoot: scratch, 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
+ }
+ for _, a := range arts {
+ var v team.GitCandidate
+ if a.Role == team.RoleCandidate && checks.CandidateHash(decodeCandidate(a.Payload)) == hash {
+ json.Unmarshal(a.Payload, &v)
+ return v, nil
+ }
+ }
+ return team.GitCandidate{}, paseo.ErrIdentity
+ }, Export: func(ctx context.Context, commit, dest string) error {
+ if commit == base {
+ return checks.ExportBase(ctx, repo, base, dest)
+ }
+ arts, err := apiArtifacts(ctx, w, c)
+ if err != nil {
+ return err
+ }
+ for _, a := range arts {
+ v := decodeCandidate(a.Payload)
+ if a.Role == team.RoleCandidate && v.Commit == commit {
+ return manager.ExportCandidate(ctx, v, dest)
+ }
+ }
+ return paseo.ErrIdentity
+ }}, sandbox)
+ }
+ manager, err = workspace.New(workspace.Config{Protected: protected, PrivateRoot: private, WorkspaceRoot: works, GitPath: "/usr/bin/git", Forge: localRead{remote}, Policy: func(context.Context, paseo.Selection) (paseo.ReadPolicy, error) { return policy, nil }, Definitions: func(ctx context.Context, tgt team.TargetBinding, repository string) (runnerproto.PreparedBug, error) {
+ repo = repository
+ d, err := checks.LoadBaseDefinition(ctx, repository, tgt.Repository, tgt.BaseRevision, scratch)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ e, err := executor(ctx, RunClaim{ClaimResponse: runnerproto.ClaimResponse{Brief: runnerproto.RunnerBrief{Selection: runnerproto.Selection{Isolation: iso}}}}, d, checks.Reproduction{}, time.Now().Add(2*time.Minute))
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ d.Baseline, err = e.CaptureBaseline(ctx, d)
+ if err != nil {
+ t.Log("preparation callback", err)
+ return runnerproto.PreparedBug{}, err
+ }
+ pinned = d
+ raw := marshal(d)
+ return runnerproto.PreparedBug{CheckDefinition: raw, CheckDefinitionHash: checks.Digest(raw), BaselineTestSetHash: d.Baseline.Hash}, nil
+ }}, client)
+ wfMust(t, err)
+ prepared, err := manager.Prepare(ctx, target)
+ wfMust(t, err)
+ 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 := &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) {
+ p, err := w.Provenance(ctx, tx, scope, h)
+ if err == nil {
+ for _, a := range api.assignments {
+ if a.WorkspaceKey == fmt.Sprint(h.Attempt) {
+ p.Isolation = a.Selection.Isolation
+ p.ConnectionID = a.Selection.ConnectionID
+ }
+ }
+ }
+ return p, err
+ }, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("claude", "model", nil), team.OpForgePublish: team.NewFakeForge()}})
+ wfMust(t, err)
+ defer core.Close()
+ api.core = core
+ _, err = core.Resume(ctx)
+ wfMust(t, err)
+ 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"}}}})
+ wfMust(t, err)
+ scope := team.Scope{Account: job.Account, Job: job.ID}
+ inspector, err := NewLinuxProcessInspector(proc, client, j)
+ wfMust(t, err)
+ inspector.beforeTrackPID = func(pid int) { linkProcess(t, proc, pid) }
+ defer func() {
+ for _, record := range inspector.records {
+ for _, id := range record.Known {
+ _ = inspector.Stop(context.Background(), id)
+ }
+ }
+ }()
+
+ pubroot := filepath.Join(root, "pub")
+ policy.DeniedPaths = append(policy.DeniedPaths, pubroot)
+ gitSpy := filepath.Join(root, "publish-git")
+ 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, Client: client, Witness: w, Policy: func(context.Context, paseo.Selection) (paseo.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, Client: client, Inspector: inspector, API: api, Workflow: workflow, CredentialsPath: filepath.Join(state, "credentials"), InstallCredentials: func(context.Context, runnerproto.CredentialRotation, string) error { return nil }})
+ wfMust(t, err)
+ wfMust(t, s.Recover(ctx))
+ for i, step := range []string{"reproduce", "implement", "review", "verify", "publish"} {
+ 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}
+ if step == "review" || step == "verify" {
+ sel.Provider = "codex"
+ sel.Family = "gpt"
+ sel.Isolation = team.IsolationSnapshot{Status: "unconfined", RunnerTainted: true, AcknowledgementIDs: []string{"ack"}, ObservedTuples: []team.IsolationTuple{{Provider: "codex", ProviderVersion: "0.165.0", PaseoVersion: "0.14.0", IsolationConfigHash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}}
+ }
+ a := runnerproto.Assignment{ID: step, TaskID: "task", StepKey: step, WorkspaceKey: fmt.Sprint(h.Attempt), Scope: scope, Kind: "step", Selection: sel}
+ api.assignments[step] = a
+ arts, err := core.Artifacts(ctx, scope)
+ wfMust(t, err)
+ for i, art := range arts {
+ arts[i], err = core.Artifact(ctx, scope, art.ID)
+ wfMust(t, err)
+ }
+ wfMust(t, w.record(ctx, "artifacts", attemptKey(scope, h), arts))
+ hashes := []string{prepared.CheckDefinitionHash}
+ 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 {
+ for _, v := range inspector.records {
+ t.Log("coverage", v.Owner.Attempt, v.Unknown, v.UnknownStage, v.UnknownPID)
+ }
+ b, _ := os.ReadFile(filepath.Join(proc, "failure"))
+ t.Fatalf("%s (%s): %v %s", step, s.states[attemptKey(scope, h)].FailurePhase, err, b)
+ }
+ }
+ entries, err := os.ReadDir(filepath.Join(state, "admissions"))
+ wfMust(t, err)
+ consumed := 0
+ for _, entry := range entries {
+ if strings.HasSuffix(entry.Name(), ".consumed") {
+ consumed++
+ }
+ }
+ if consumed != 5 {
+ t.Fatal("dispatch bypassed durable ticket consumption", consumed)
+ }
+ if api.admissions != 4 {
+ t.Fatal("follow-up did not get fresh admission", api.admissions)
+ }
+ finished, err := core.GetJob(ctx, scope)
+ wfMust(t, err)
+ if finished.State != team.JobSucceeded {
+ t.Fatal("publication not concluded", finished.State)
+ }
+ attempts, err := core.Attempts(ctx, scope)
+ wfMust(t, err)
+ if len(attempts) != 5 {
+ t.Fatal("attempt count", len(attempts))
+ }
+ for _, a := range attempts {
+ if a.State != team.AttemptSucceeded || a.Containment != team.ContainmentContained {
+ t.Fatalf("unfinished %+v", a)
+ }
+ }
+}
+func decodeCandidate(b []byte) (v team.GitCandidate) { json.Unmarshal(b, &v); return }
+func apiArtifacts(ctx context.Context, w *Witness, c RunClaim) ([]team.Artifact, error) {
+ var arts []team.Artifact
+ err := w.read(ctx, "artifacts", attemptKey(c.Scope, c.Handle), &arts)
+ return arts, err
+}
+
+const workflowBridge = `
+import fs from 'node:fs';import readline from 'node:readline';import net from 'node:net';import {execFileSync,spawn} from 'node:child_process';
+const proc=%q, agents=new Map(),subs=new Map();let n=0,turn=0;
+const write=x=>process.stdout.write(JSON.stringify({version:1,...x})+'\n');
+const git=(path,args)=>execFileSync('/usr/bin/git',args,{cwd:path,env:{PATH:'/usr/bin:/bin',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_AUTHOR_NAME:'test',GIT_AUTHOR_EMAIL:'test@example.test',GIT_COMMITTER_NAME:'test',GIT_COMMITTER_EMAIL:'test@example.test'}}).toString().trim();
+const event=(a,kind,extra={})=>write({type:'event',subscription_id:subs.get(a.agent_id),event:{kind,server_id:a.server_id,agent_id:a.agent_id,provider_session_id:a.provider_session_id,epoch:'epoch',payload:{},...extra}});
+readline.createInterface({input:process.stdin}).on('line',async line=>{const q=JSON.parse(line),p=q.params;let result={};try{switch(q.op){
+case 'provider_policy':result={fixture:true};break;
+case 'preflight':result={version:'0.14.0',server_id:'server',provider_version:p.selection.provider==='claude'?'2.1.312':'0.165.0',paseo_version:'0.14.0',account_pinning:true,observed_account:'account',no_failover:true,recoverable_timeline:true,process_ownership:true,mcp_at_create:true,read_isolation:true,isolation_config_hash:'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'};break;
+case 'register_project':result={server_id:'server',project_id:p.path,path:p.path};break;
+case 'create_workspace':{const path=p.path+'-work';git(p.path,['worktree','add','-b',p.branch,path,p.base_commit]);result={server_id:'server',project_id:p.project_id,workspace_id:p.idempotency_key,path};break;}
+case 'create_agent':{if(!p.provider_options?.fixture) throw Error('missing creation policy');const a={server_id:'server',agent_id:'agent'+(++n),provider_session_id:'session'+n,workspace_id:p.workspace.workspace_id,account_id:'account',provider:p.selection.provider,family:p.selection.family,model:p.selection.model};const child=spawn('/bin/sleep',['60'],{cwd:p.workspace.path,env:p.env,stdio:'ignore'});fs.symlinkSync('/proc/'+child.pid,proc+'/'+child.pid);agents.set(a.agent_id,{request:p,child});result=a;break;}
+case 'subscribe':subs.set(p.agent.agent_id,p.subscription_id);event(p.agent,'timeline_replacement');break;
+case 'send':{const a=p.agent,request=agents.get(a.agent_id).request,message=JSON.parse(p.message),step=message.Step;let name,args;++turn;
+if(step==='reproduce'){name='submit_reproduction';args={expected_symptom:'wrong value',files:[{path:'bug_test.go',bytes:Buffer.from('package fixture\nimport "testing"\nfunc TestBug(t *testing.T){if Value()!=2 {t.Fatal("wrong value")}}\n').toString('base64')}],test_names:[{package:'fixture',name:'TestBug'}]};}
+if(step==='implement'){fs.writeFileSync(request.workspace.path+'/value.go','package fixture\nfunc Value() int {return 2}\n');git(request.workspace.path,['add','.']);git(request.workspace.path,['commit','-m','fix']);name='submit_candidate';args={commit:git(request.workspace.path,['rev-parse','HEAD'])};}
+if(step==='review'){name='submit_review';args={candidate:JSON.parse(Buffer.from(message.Evidence.find(x=>x.Role==='candidate').Payload,'base64')).commit,decision:'approve',findings:[]};}
+if(step==='reproduce' && !message.person_answer){name='ask_person';args={question:'Which value case should be checked?'};}
+const env=request.mcp_servers.equipo.env,cap=JSON.parse(fs.readFileSync(env.EQUIPO_TOOL_CAPABILITY_FILE));
+await new Promise((resolve,reject)=>{const c=net.createConnection(env.EQUIPO_TOOL_SOCKET,()=>c.write(JSON.stringify({capability:cap.secret,instance_id:cap.instance_id,task_id:cap.task_id,attempt:cap.attempt,fence:cap.fence,request_id:name,name,arguments:args})+'\n'));c.on('data',raw=>{const v=JSON.parse(raw);c.end();v.ok?resolve():reject(Error('tool rejected'));});c.on('error',reject);});
+event(a,'turn_completed',{turn_id:'turn'+a.agent_id+turn});break;}
+case 'list_terminals':result=[];break;
+}
+write({type:'result',id:q.id,result});}catch(e){fs.writeFileSync(proc+'/failure',e.stack);write({type:'result',id:q.id,error:'uncertain'});}});
+`
+
+type workflowDescription struct{ value forge.Description }
+
+func (*workflowDescription) BeforePush() bool { return true }
+func (d *workflowDescription) Set(_ context.Context, _ forge.Credential, v forge.Description) error {
+ d.value = v
+ return nil
+}
+func (d *workflowDescription) Read(_ context.Context, _ forge.Credential, repository, ref string) (forge.Description, error) {
+ return d.value, nil
+}
diff --git a/internal/runner/workflow_turn.go b/internal/runner/workflow_turn.go
new file mode 100644
index 00000000..72e49b23
--- /dev/null
+++ b/internal/runner/workflow_turn.go
@@ -0,0 +1,368 @@
+package runner
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "strconv"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func (w *BugWorkflow) modelTurn(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error, socket *AttemptSocket, artifacts []team.Artifact) error {
+ if err := s.journal.BeginReplay(ctx, r.Agent); err != nil {
+ return err
+ }
+ sub, err := w.cfg.Client.Subscribe(ctx, r.Agent, paseo.Cursor{})
+ if err != nil {
+ return err
+ }
+ defer sub.Close(context.WithoutCancel(ctx))
+ var usage *UsageAccumulator
+ if w.cfg.UsageProfile != nil {
+ profile, err := w.cfg.UsageProfile(selection(r.Claim.Assignment))
+ if err != nil {
+ return err
+ }
+ usage = NewUsageAccumulator(profile)
+ }
+ var action team.ActionID
+ pump := EventPump{Journal: s.journal, Upload: func(ctx context.Context, e Event) error {
+ q := r.request(e.ID)
+ q.RequestID = e.ID
+ q.Event = marshal(e)
+ q.ActionID = e.ActionID
+ return s.api.Call(ctx, "events", q, nil)
+ }, Contain: func(context.Context) error { return paseo.ErrUncertain }}
+ observed := func(e paseo.Event) error {
+ if e.ServerID != r.Agent.ServerID || e.AgentID != r.Agent.AgentID || e.ProviderSessionID != r.Agent.ProviderSessionID {
+ return paseo.ErrIdentity
+ }
+ event := Event{Version: 1, ID: runnerproto.EventHash(e), TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, ServerID: e.ServerID, AgentID: e.AgentID, SessionID: e.ProviderSessionID, Epoch: e.Epoch, Kind: e.Kind, TurnID: e.TurnID, RequestID: e.PermissionID, Sequence: e.Sequence, Scope: r.Claim.Scope, Handle: r.Claim.Handle, ActionID: action, Payload: e.Payload, SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
+ var prior []byte
+ if err := s.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_events WHERE event_key=?", event.DedupKey()).Scan(&prior); err == nil {
+ var saved Event
+ if json.Unmarshal(prior, &saved) != nil {
+ return ErrJournal
+ }
+ event.SourceTime = saved.SourceTime
+ }
+ if event.Kind == "turn_completed" || event.Kind == "turn_failed" {
+ if action == 0 {
+ return paseo.ErrUncertain
+ }
+ outcome := team.OutcomeSuccess
+ if event.Kind == "turn_failed" {
+ outcome = team.OutcomeFailure
+ }
+ // Unknown token counts retain their reservation. No inferred usage receipt.
+ receipt := team.Receipt{ID: e.TurnID, Outcome: outcome, Provider: r.Agent.Provider, Model: r.Agent.Model}
+ if usage != nil {
+ receipt.Usage = usage.Observe(e)
+ }
+ key := runnerproto.EventHash([]any{r.Claim.Scope, r.Claim.Handle.Attempt, r.Claim.Handle.Fence, action})
+ if err := w.cfg.Witness.record(ctx, "receipt", key, receipt); err != nil {
+ return err
+ }
+ }
+ if err := pump.Append(ctx, event, nil); err != nil {
+ return err
+ }
+ return pump.Flush(ctx, 128)
+ }
+ ready := false
+ for !ready {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case err, ok := <-sub.Ready:
+ if !ok || err != nil {
+ return paseo.ErrNotReady
+ }
+ ready = true
+ case e, ok := <-sub.Events:
+ if !ok {
+ return paseo.ErrUncertain
+ }
+ if err := observed(e); err != nil {
+ return err
+ }
+ }
+ }
+ // Drain the refetch before marking the subscription ready.
+ for {
+ select {
+ case e, ok := <-sub.Events:
+ if !ok {
+ return paseo.ErrUncertain
+ }
+ if err := observed(e); err != nil {
+ return err
+ }
+ default:
+ goto drained
+ }
+ }
+drained:
+ cursor, err := s.journal.Cursor(ctx, r.Agent)
+ if err != nil || cursor.Epoch == "" {
+ return paseo.ErrNotReady
+ }
+ if err = s.journal.BeginReplay(ctx, r.Agent); err != nil {
+ return err
+ }
+ if err = s.journal.Recovered(ctx, r.Agent, cursor); err != nil {
+ return err
+ }
+ event := Event{Version: 1, ID: r.request("ready").RequestID, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, ServerID: r.Agent.ServerID, AgentID: r.Agent.AgentID, SessionID: r.Agent.ProviderSessionID, Epoch: cursor.Epoch, Kind: "timeline_ready", Scope: r.Claim.Scope, Handle: r.Claim.Handle, Payload: json.RawMessage(`{}`), SourceTime: time.Now().UTC(), Isolation: r.Claim.Assignment.Selection.Isolation}
+ if err = pump.Append(ctx, event, nil); err != nil {
+ return err
+ }
+ if err = pump.Flush(ctx, 128); err != nil {
+ return err
+ }
+ message := string(marshal(struct {
+ Step string
+ Brief runnerproto.RunnerBrief
+ Evidence []team.Artifact
+ }{r.Claim.Assignment.StepKey, r.Claim.Brief, artifacts}))
+ turn := 0
+ dispatch := func() error {
+ if turn >= 24 {
+ return team.ErrQuota
+ }
+ if err := current(ctx); err != nil {
+ return err
+ }
+ suffix := strconv.Itoa(turn)
+ q := r.request("turn-intent-" + suffix)
+ q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpProviderCall, Payload: marshal(map[string]string{"provider": r.Agent.Provider, "model": r.Agent.Model, "prompt": message}), Reserve: team.Usage{Calls: 1, InputTokens: 32000, OutputTokens: 4000, CostUnavailable: true}}
+ var intent team.ActionID
+ if err := s.api.Call(ctx, "intend", q, &intent); err != nil {
+ return err
+ }
+ action = intent
+ q = r.request("turn-admit-" + suffix)
+ q.ActionID = action
+ dir := filepath.Join(w.cfg.StateDir, "admissions")
+ if err := runnerproto.JournalAdmission(dir, q); err != nil {
+ return err
+ }
+ var ticket team.AdmissionTicket
+ if err := s.api.Call(ctx, "admit", q, &ticket); err != nil {
+ return err
+ }
+ if err := current(ctx); err != nil {
+ return err
+ }
+ if err := runnerproto.ConsumeTicket(dir, q.RequestID, ticket, time.Now().UTC(), ticket.Incarnation); err != nil {
+ return err
+ }
+ return w.cfg.Client.Send(ctx, r.Agent, message, q.RequestID)
+ }
+ if err = dispatch(); err != nil {
+ return err
+ }
+ refresh := time.NewTicker(100 * time.Millisecond)
+ defer refresh.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-refresh.C:
+ if err = current(ctx); err != nil {
+ return err
+ }
+ if err = socket.RenewLease(ctx, l.bound()); err != nil {
+ return err
+ }
+ case e, ok := <-sub.Events:
+ if !ok {
+ return paseo.ErrUncertain
+ }
+ if err = observed(e); err != nil {
+ return err
+ }
+ if e.Kind == "permission_requested" {
+ question, err := QuestionFromEvent(e, runnerproto.EventHash(e), r.Claim.Assignment.TaskID, nil)
+ if err != nil {
+ return err
+ }
+ question.AssignmentID = r.Claim.Assignment.ID
+ question.Attempt = int64(r.Claim.Handle.Attempt)
+ question.Fence = r.Claim.Handle.Fence
+ question.ExpiresAt = l.bound()
+ if err = w.cfg.Witness.record(ctx, "question", question.ID, question); err != nil {
+ return err
+ }
+ q := r.request("question-" + question.ID)
+ q.Question = &question
+ var saved runnerproto.Question
+ if err = s.api.Call(ctx, "questions", q, &saved); err != nil {
+ return err
+ }
+ relay := QuestionRelay{Journal: s.journal, Client: w.cfg.Client, Agent: r.Agent, Current: func(ctx context.Context, _ runnerproto.Question) (time.Time, error) {
+ err := current(ctx)
+ return l.bound(), err
+ }}
+ if err = relay.Wait(ctx, saved, func(ctx context.Context) (*runnerproto.QuestionAnswer, error) {
+ var answers []runnerproto.Question
+ err := s.api.Call(ctx, "answers", r.request("answers"), &answers)
+ if err != nil {
+ return nil, err
+ }
+ for _, a := range answers {
+ if a.ID == saved.ID {
+ return a.Answer, nil
+ }
+ }
+ return nil, nil
+ }, func(context.Context) error { return paseo.ErrUncertain }); err != nil {
+ return err
+ }
+ }
+ if e.Kind == "turn_failed" {
+ return team.ErrEvidence
+ }
+ if e.Kind == "turn_completed" {
+ answer, asked, err := w.personFollowup(ctx, s, r, l, current)
+ if err != nil {
+ return err
+ }
+ if !asked {
+ return nil
+ }
+ var prompt map[string]any
+ if json.Unmarshal([]byte(message), &prompt) != nil {
+ return paseo.ErrContract
+ }
+ prompt["person_answer"] = answer
+ message = string(marshal(prompt))
+ turn++
+ if err = dispatch(); err != nil {
+ return err
+ }
+ }
+ }
+ }
+}
+func (w *BugWorkflow) publish(ctx context.Context, s *Supervisor, r *attemptState, current func(context.Context) error) error {
+ var publication team.Publication
+ if err := s.api.Call(ctx, "publication_ready", r.request("publication-ready"), &publication); err != nil {
+ return err
+ }
+ q := r.request("publish-intent")
+ q.Intent = &team.IntentSpec{Key: q.RequestID, Operation: team.OpForgePublish, Payload: marshal(publication)}
+ var action team.ActionID
+ if err := s.api.Call(ctx, "intend", q, &action); err != nil {
+ return err
+ }
+ q = r.request("publish-admit")
+ q.ActionID = action
+ dir := filepath.Join(w.cfg.StateDir, "admissions")
+ if err := runnerproto.JournalAdmission(dir, q); err != nil {
+ return err
+ }
+ var auth runnerproto.PublicationAuthorization
+ if err := s.api.Call(ctx, "publication_authorize", q, &auth); err != nil {
+ return err
+ }
+ if err := current(ctx); err != nil {
+ return err
+ }
+ if err := runnerproto.ConsumeTicket(dir, q.RequestID, auth.Ticket, time.Now().UTC(), auth.Ticket.Incarnation); err != nil {
+ return err
+ }
+ if err := w.cfg.Witness.record(ctx, "publication", runnerproto.EventHash(auth.Ticket.Dispatch), auth); err != nil {
+ return err
+ }
+ receipt, err := w.cfg.Publisher.Execute(ctx, auth.Ticket.Dispatch)
+ if err != nil {
+ return err
+ }
+ key := runnerproto.EventHash([]any{r.Claim.Scope, r.Claim.Handle.Attempt, r.Claim.Handle.Fence, action})
+ if err = w.cfg.Witness.record(ctx, "receipt", key, receipt); err != nil {
+ return err
+ }
+ q = r.request("publish-receipt")
+ q.ActionID = action
+ q.Receipt = &receipt
+ return s.api.Call(ctx, "receipts", q, nil)
+}
+
+func (w *BugWorkflow) personFollowup(ctx context.Context, s *Supervisor, r *attemptState, l *leaseGuard, current func(context.Context) error) (string, bool, error) {
+ submissions, err := s.journal.ToolSubmissions(ctx, 128)
+ if err != nil {
+ return "", false, err
+ }
+ var selected *ToolSubmission
+ for i := range submissions {
+ v := &submissions[i]
+ if v.TaskID == r.Claim.Assignment.TaskID && v.Attempt == int64(r.Claim.Handle.Attempt) && v.Fence == r.Claim.Handle.Fence && v.Agent == r.Agent && v.Name == "ask_person" {
+ if selected != nil {
+ return "", false, paseo.ErrIdentity
+ }
+ selected = v
+ }
+ }
+ if selected == nil {
+ return "", false, nil
+ }
+ var person PersonQuestion
+ if json.Unmarshal(selected.Arguments, &person) != nil {
+ return "", true, paseo.ErrIdentity
+ }
+ id := runnerproto.EventHash(selected)
+ q := runnerproto.Question{ID: id, TaskID: r.Claim.Assignment.TaskID, AssignmentID: r.Claim.Assignment.ID, ServerID: r.Agent.ServerID, AgentID: r.Agent.AgentID, SessionID: r.Agent.ProviderSessionID, PermissionID: id, Kind: "person", Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, Revision: 1, ExpiresAt: l.bound(), RawRequest: marshal(map[string]string{"id": id, "kind": "person", "question": person.Question})}
+ if err = w.cfg.Witness.record(ctx, "question", id, q); err != nil {
+ return "", true, err
+ }
+ request := r.request("person-" + id)
+ request.Question = &q
+ var saved runnerproto.Question
+ if err = s.api.Call(ctx, "questions", request, &saved); err != nil {
+ return "", true, err
+ }
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ if err = current(ctx); err != nil {
+ return "", true, err
+ }
+ var answers []runnerproto.Question
+ if err = s.api.Call(ctx, "answers", r.request("answers"), &answers); err != nil {
+ return "", true, err
+ }
+ for _, answer := range answers {
+ if answer.ID != saved.ID || answer.Answer == nil {
+ continue
+ }
+ if saved.ValidateAnswer(*answer.Answer) != nil || answer.Answer.Behavior != "allow" {
+ return "", true, paseo.ErrIdentity
+ }
+ var input struct {
+ Answers map[string]string `json:"answers"`
+ }
+ if json.Unmarshal(answer.Answer.UpdatedInput, &input) != nil {
+ return "", true, paseo.ErrIdentity
+ }
+ request = r.request("person-resolved-" + id)
+ request.Question = &q
+ if err = s.api.Call(ctx, "question_resolved", request, nil); err != nil {
+ return "", true, err
+ }
+ if err = s.journal.AckTool(ctx, *selected); err != nil {
+ return "", true, err
+ }
+ return input.Answers["answer"], true, nil
+ }
+ select {
+ case <-ctx.Done():
+ return "", true, ctx.Err()
+ case <-ticker.C:
+ }
+ }
+}
diff --git a/internal/runner/workspace/workspace.go b/internal/runner/workspace/workspace.go
index adebb030..2c90b209 100644
--- a/internal/runner/workspace/workspace.go
+++ b/internal/runner/workspace/workspace.go
@@ -166,6 +166,10 @@ func (m *Manager) git(ctx context.Context, dir string, input []byte, extra map[s
cmd := exec.CommandContext(ctx, m.cfg.GitPath, args...)
cmd.Dir = dir
env := safeEnv()
+ marker, _ := runnerproto.ProcessOwnership(ctx)
+ if marker != "" {
+ env["EQUIPO_ATTEMPT_MARKER"] = marker
+ }
env["HOME"] = "/nonexistent"
for k, v := range extra {
env[k] = v
@@ -867,3 +871,35 @@ func (m *Manager) ValidateTurn(ctx context.Context, a runnerproto.Assignment, w
}
return m.validateWorkspace(at)
}
+
+// 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 {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var at attempt
+ if w.key == "" || load(filepath.Join(m.cfg.PrivateRoot, "attempt-"+digest(w.key), "attempt.json"), &at) != nil || at.Workspace != w.Paseo || at.Target.Repository != c.Repository || at.Target.BaseRevision != c.BaseCommit {
+ return paseo.ErrIdentity
+ }
+ if err := m.validateWorkspace(at); err != nil {
+ return err
+ }
+ source := filepath.Join(m.cfg.PrivateRoot, "candidate-"+digest(c))
+ var saved GitCandidate
+ if load(filepath.Join(source, "candidate.json"), &saved) != nil || saved != c {
+ return paseo.ErrIdentity
+ }
+ if err := copyObjects(filepath.Join(source, "objects"), filepath.Join(at.Request.Path, ".git", "objects")); err != nil {
+ return err
+ }
+ if _, err := m.run(ctx, w.Paseo.Path, "checkout", "--detach", c.Commit); err != nil {
+ return err
+ }
+ tree, err := m.run(ctx, w.Paseo.Path, "rev-parse", "HEAD^{tree}")
+ if err != nil || tree != c.Tree {
+ return paseo.ErrIdentity
+ }
+ return m.clean(ctx, at.Request.Path, w.Paseo.Path, c.Commit)
+}
+
+func (m *Manager) PreparationDirectory() string { return m.cfg.PrivateRoot }
diff --git a/internal/runner/workspace/workspace_test.go b/internal/runner/workspace/workspace_test.go
index 9ab5a49f..5c28f3d0 100644
--- a/internal/runner/workspace/workspace_test.go
+++ b/internal/runner/workspace/workspace_test.go
@@ -14,7 +14,6 @@ import (
"strings"
"testing"
- "amadan.net/oficina/equipo/internal/equipo"
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runner/paseo"
"amadan.net/oficina/equipo/internal/runnerproto"
@@ -668,7 +667,9 @@ func TestWorkspaceRetryIdentityPartialPreparation(t *testing.T) {
}
}
-var _ equipo.BugPreparer = (*Manager)(nil)
+var _ interface {
+ Prepare(context.Context, team.TargetBinding) (runnerproto.PreparedBug, error)
+} = (*Manager)(nil)
func TestCandidateCaptureSHA256(t *testing.T) {
f := setupWithFormat(t, "sha256")
diff --git a/internal/runnerproto/containment.go b/internal/runnerproto/containment.go
new file mode 100644
index 00000000..8315495f
--- /dev/null
+++ b/internal/runnerproto/containment.go
@@ -0,0 +1,45 @@
+package runnerproto
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "time"
+)
+
+type ProcessIdentity struct {
+ PID int `json:"pid"`
+ StartTicks uint64 `json:"start_ticks"`
+ BootID string `json:"boot_id"`
+}
+type ProcessOwner struct {
+ LocalOnly bool `json:"local_only"`
+ Attempt team.AttemptID `json:"attempt"`
+ Fence int64 `json:"fence"`
+ Marker string `json:"marker"`
+ AgentID string `json:"agent_id"`
+ Workspace paseo.Workspace `json:"workspace"`
+ ExecutorGroups []ProcessIdentity `json:"executor_groups"`
+}
+type ProcessInventory struct {
+ Observed []ProcessIdentity `json:"observed"`
+ ExecutorGroups []ProcessIdentity `json:"executor_groups"`
+ Processes []ProcessIdentity `json:"processes"`
+ TerminalIDs []string `json:"terminal_ids"`
+ CoverageKnown bool `json:"coverage_known"`
+ BootID string `json:"boot_id"`
+ CheckedAt time.Time `json:"checked_at"`
+}
+type ContainmentProof struct {
+ Scope team.Scope `json:"scope"`
+ Handle team.Handle `json:"handle"`
+ Owner ProcessOwner `json:"owner"`
+ Inventory ProcessInventory `json:"inventory"`
+ Observed []ProcessIdentity `json:"observed"`
+ Empty bool `json:"empty"`
+}
+
+type FreezeRequest struct {
+ ExpectedSymptom string `json:"expected_symptom"`
+ DefinitionHash string `json:"definition_hash"`
+ ReproductionHash string `json:"reproduction_hash"`
+}
diff --git a/internal/runnerproto/ownership.go b/internal/runnerproto/ownership.go
new file mode 100644
index 00000000..35873f60
--- /dev/null
+++ b/internal/runnerproto/ownership.go
@@ -0,0 +1,17 @@
+package runnerproto
+
+import "context"
+
+type ownershipKey struct{}
+type ownership struct {
+ marker string
+ track func(context.Context, int) error
+}
+
+func WithProcessOwnership(ctx context.Context, marker string, track func(context.Context, int) error) context.Context {
+ return context.WithValue(ctx, ownershipKey{}, ownership{marker, track})
+}
+func ProcessOwnership(ctx context.Context) (string, func(context.Context, int) error) {
+ v, _ := ctx.Value(ownershipKey{}).(ownership)
+ return v.marker, v.track
+}
diff --git a/internal/runnerproto/questions.go b/internal/runnerproto/questions.go
index 31a4a4f6..8016045c 100644
--- a/internal/runnerproto/questions.go
+++ b/internal/runnerproto/questions.go
@@ -43,13 +43,13 @@ func (q Question) Validate() error {
return nil
}
func (a QuestionAnswer) Validate(kind string) error {
- if !slices.Contains([]string{"question", "tool", "plan", "mode", "other"}, kind) {
+ if !slices.Contains([]string{"person", "question", "tool", "plan", "mode", "other"}, kind) {
return ErrInvalid
}
if a.Behavior == "deny" && len(a.UpdatedInput) == 0 {
return nil
}
- if kind != "question" || a.Behavior != "allow" {
+ if (kind != "question" && kind != "person") || a.Behavior != "allow" {
return ErrInvalid
}
var updated struct {
@@ -75,6 +75,21 @@ func (q Question) ValidateAnswer(a QuestionAnswer) error {
if a.Behavior == "deny" {
return nil
}
+ if q.Kind == "person" {
+ var request struct {
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Question string `json:"question"`
+ }
+ var input struct {
+ Answers map[string]string `json:"answers"`
+ }
+ if DecodeLimit(bytes.NewReader(q.RawRequest), &request, MaxEventBytes) != nil || request.Kind != "person" || strings.TrimSpace(request.Question) == "" || json.Unmarshal(a.UpdatedInput, &input) != nil || len(input.Answers) != 1 || strings.TrimSpace(input.Answers["answer"]) == "" {
+ return ErrInvalid
+ }
+ return nil
+ }
+
var raw struct {
Provider string `json:"provider"`
Name string `json:"name"`
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index 9a29a3a6..9294bdba 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -79,6 +79,7 @@ type PollRequest struct {
After string `json:"after"`
}
type RunnerRequest struct {
+ ArtifactID team.ArtifactID `json:"artifact_id,omitempty"`
Question *Question `json:"question,omitempty"`
Version int `json:"version"`
AssignmentID string `json:"assignment_id"`
@@ -144,6 +145,8 @@ type Assignment struct {
}
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"`
@@ -154,6 +157,7 @@ type RunnerBrief struct {
}
type ClaimResponse struct {
+ AttemptDeadline time.Time `json:"attempt_deadline"`
Scope Scope `json:"scope"`
Handle team.Handle `json:"handle"`
Brief RunnerBrief `json:"brief"`
diff --git a/runner/paseo/bridge.mjs b/runner/paseo/bridge.mjs
index 20e6bc53..112ba55e 100644
--- a/runner/paseo/bridge.mjs
+++ b/runner/paseo/bridge.mjs
@@ -166,6 +166,10 @@ export class Bridge {
allowedPath(w.workspaceDirectory, r.read_policy);
return { server_id: status.serverId, project_id: w.projectId, workspace_id: w.id, path: w.workspaceDirectory };
}
+ async providerPolicy({ selection, read_policy }) {
+ const status = await this.status();
+ return providerPolicy(selection.provider, status.version, read_policy);
+ }
async createAgent(r) {
keys(r, ['workspace', 'selection', 'idempotency_key', 'mode_id', 'read_policy', 'env', 'provider_options', 'mcp_servers']);
const status = await this.status(r.workspace.server_id);
@@ -278,6 +282,22 @@ export class Bridge {
}
async stop({ agent }) { await this.status(agent.server_id); await this.client.cancelAgent(agent.agent_id); return {}; }
async archive({ agent }) { await this.status(agent.server_id); await this.client.archiveAgent(agent.agent_id); return {}; }
+ async listTerminals({ workspace }) {
+ await this.status(workspace.server_id);
+ const result = await this.client.listTerminals(workspace.path, undefined, { workspaceId: workspace.workspace_id });
+ if (!Array.isArray(result.terminals)) fail('uncertain');
+ const ids = [];
+ for (const terminal of result.terminals) {
+ if (!text(terminal.id) || !text(terminal.workspaceId)) fail('uncertain');
+ if (terminal.workspaceId === workspace.workspace_id) ids.push(terminal.id);
+ }
+ return ids;
+ }
+ async killTerminal({ workspace, id }) {
+ if (!text(id) || !(await this.listTerminals({ workspace })).includes(id)) fail('identity_mismatch');
+ if (!(await this.client.killTerminal(id)).success) fail('uncertain');
+ return {};
+ }
async archiveWorkspace({ workspace }) {
await this.status(workspace.server_id);
const result = await this.client.listTerminals(workspace.path, undefined, { workspaceId: workspace.workspace_id });
@@ -323,7 +343,7 @@ export async function run(input, output, diagnostic) {
bridge = new Bridge(await connectLocal(q.params, await loadSDK()), write); result = {};
} else {
if (!bridge) fail('invalid_request');
- const methods = { preflight: 'preflight', register_project: 'registerProject', create_workspace: 'createWorkspace', create_agent: 'createAgent', subscribe: 'subscribe', unsubscribe: 'unsubscribe', send: 'send', respond: 'respond', stop: 'stop', archive: 'archive', archive_workspace: 'archiveWorkspace' };
+ const methods = { preflight: 'preflight', provider_policy: 'providerPolicy', register_project: 'registerProject', create_workspace: 'createWorkspace', create_agent: 'createAgent', subscribe: 'subscribe', unsubscribe: 'unsubscribe', send: 'send', respond: 'respond', stop: 'stop', archive: 'archive', archive_workspace: 'archiveWorkspace', list_terminals: 'listTerminals', kill_terminal: 'killTerminal' };
if (!Object.hasOwn(methods, q.op)) fail('invalid_request');
result = await bridge[methods[q.op]](q.params);
}
diff --git a/runner/paseo/bridge.test.mjs b/runner/paseo/bridge.test.mjs
index 63967c18..550f7afa 100644
--- a/runner/paseo/bridge.test.mjs
+++ b/runner/paseo/bridge.test.mjs
@@ -309,3 +309,23 @@ test('project registration', async () => {
f.daemon.addProject = async () => ({ project: { projectId: 'other', projectRootPath: '/wrong' }, error: null });
await assert.rejects(f.bridge.registerProject(r), /identity_mismatch/);
});
+
+test('terminal cleanup uses exact workspace IDs and unknown lists fail closed', async () => {
+ const f = fake();
+ assert.deepEqual(await f.bridge.listTerminals({ workspace }), ['own-terminal']);
+ await assert.rejects(f.bridge.killTerminal({ workspace, id: 'other-terminal' }), /identity_mismatch/);
+ assert.deepEqual(f.calls.filter(x => x[0] === 'kill'), []);
+ await f.bridge.killTerminal({ workspace, id: 'own-terminal' });
+ assert.deepEqual(f.calls.filter(x => x[0] === 'kill'), [['kill', 'own-terminal']]);
+ f.daemon.listTerminals = async () => ({});
+ await assert.rejects(f.bridge.listTerminals({ workspace }), /uncertain/);
+ f.daemon.listTerminals = async () => ({ terminals: [{ id: 'unknown' }] });
+ await assert.rejects(f.bridge.listTerminals({ workspace }), /uncertain/);
+});
+
+test('runner obtains the pinned creation policy before recording creation', async () => {
+ const f = fake();
+ assert.deepEqual(await f.bridge.providerPolicy({ selection, read_policy: policy }), providerPolicy(selection.provider, '0.14.0', policy));
+ f.daemon.getDaemonStatus = async () => ({ serverId: workspace.server_id, version: '0.15.0' });
+ await assert.rejects(f.bridge.providerPolicy({ selection, read_policy: policy }), /unsupported_daemon_version/);
+});