oficina / equipo Public

fix: retire contained attempts and settle failed creations

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev d09cc3e608dae55a05a387b6a46172bcae7dc858 parent 4bde370
25 files changed, +933 −92
  • internal/equipo/runner_receipt_r2_test.go +31 −0
  • internal/equipo/runner_report_validation.go +3 −0
  • internal/equipo/runner_supervision.go +2 −1
  • internal/equipotest/cancel_test.go +26 −0
  • internal/runner/containment_r1_test.go +4 −1
  • internal/runner/containment_r2_test.go +295 −0
  • internal/runner/creation_recovery.go +55 −11
  • internal/runner/http.go +3 −0
  • internal/runner/paseo/client.go +26 −3
  • internal/runner/paseo/client_test.go +19 −1
  • internal/runner/paseo/creation_r2_test.go +47 −0
  • internal/runner/paseo/types.go +21 −18
  • internal/runner/process_linux.go +124 −10
  • internal/runner/process_linux_test.go +2 −1
  • internal/runner/retry.go +1 −0
  • internal/runner/runtime.go +1 −1
  • internal/runner/service.go +1 −1
  • internal/runner/supervisor.go +28 −5
  • internal/runner/supervisor_r1_test.go +6 −5
  • internal/runner/supervisor_r2_test.go +149 −0
  • internal/runner/supervisor_test.go +2 −1
  • internal/runner/workflow_integration_test.go +1 −1
  • internal/runnerproto/types.go +1 −0
  • runner/paseo/bridge.mjs +48 −31
  • runner/paseo/bridge.test.mjs +37 −1

CI failed — run details

diff --git a/internal/equipo/runner_receipt_r2_test.go b/internal/equipo/runner_receipt_r2_test.go
new file mode 100644
index 00000000..11ac3db1
--- /dev/null
+++ b/internal/equipo/runner_receipt_r2_test.go
@@ -0,0 +1,31 @@
+package equipo
+
+import (
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "context"
+ "testing"
+)
+
+func TestRunnerReceiptBindsSelection(t *testing.T) {
+ a := Assignment{ID: "assignment", Selection: runnerproto.Selection{Provider: "claude", Model: "assigned-model"}}
+ for _, field := range []string{"provider", "model", "matching"} {
+ t.Run(field, func(t *testing.T) {
+ r := team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess, Provider: a.Selection.Provider, Model: a.Selection.Model}
+ if field == "provider" {
+ r.Provider = "other"
+ }
+ if field == "model" {
+ r.Model = "other"
+ }
+ got, err := instanceValidators().Receipt(context.Background(), a, RunnerRequest{AssignmentID: a.ID, Receipt: &r})
+ if field == "matching" {
+ if err != nil || got.Model != r.Model || got.Provider != r.Provider {
+ t.Fatal(got, err)
+ }
+ } else if err == nil {
+ t.Fatal("receipt accepted mismatched", field)
+ }
+ })
+ }
+}
diff --git a/internal/equipo/runner_report_validation.go b/internal/equipo/runner_report_validation.go
index 7571c3d4..10532dbc 100644
--- a/internal/equipo/runner_report_validation.go
+++ b/internal/equipo/runner_report_validation.go
@@ -62,6 +62,9 @@ func instanceValidators() RunnerValidators {
return team.Receipt{}, ErrForbidden
}
if q.Receipt != nil {
+ if q.Receipt.Provider != a.Selection.Provider || q.Receipt.Model != a.Selection.Model {
+ return team.Receipt{}, ErrForbidden
+ }
return *q.Receipt, nil
}
var event runnerproto.Event
diff --git a/internal/equipo/runner_supervision.go b/internal/equipo/runner_supervision.go
index c84d4516..db519016 100644
--- a/internal/equipo/runner_supervision.go
+++ b/internal/equipo/runner_supervision.go
@@ -73,7 +73,8 @@ func (e *Execution) RecoverClaim(ctx context.Context, p RunnerPrincipal, q Claim
return storeError(err)
}
if !e.store.runnerClock.Now().Before(cleanup.ExpiresAt) {
- return ErrForbidden
+ result.CleanupExpired = true
+ return nil
}
value, err := assignmentValue(a)
if err != nil {
diff --git a/internal/equipotest/cancel_test.go b/internal/equipotest/cancel_test.go
index 863f460b..b522e5a6 100644
--- a/internal/equipotest/cancel_test.go
+++ b/internal/equipotest/cancel_test.go
@@ -169,3 +169,29 @@ func TestRunnerHTTPNeverAppliedClaim(t *testing.T) {
t.Fatal("never-applied claim not distinguished", err)
}
}
+
+func TestRunnerRestartExpiredCleanupClaim(t *testing.T) {
+ f := runnerFixtureNew(t, true)
+ f.clock.Advance(f.claim.CleanupExpiresAt.Sub(f.clock.Now()) + time.Second)
+ mustSQL(t, f.d, "UPDATE runner_credentials SET expires_at=? WHERE id=?", f.clock.Now().Add(time.Hour), f.principal.CredentialID)
+ q := runnerproto.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}
+ reply, err := f.x.RecoverClaim(connectionContext, f.principal, q)
+ executionMust(t, err)
+ if !reply.CleanupExpired || reply.CleanupToken != "" || !reply.LeaseDeadline.IsZero() {
+ t.Fatal("expired recovery not distinguished", reply)
+ }
+ token := runnerBearerFor(t, f)
+ server := httptest.NewServer(f.s.RunnerHandler())
+ defer server.Close()
+ dir := t.TempDir()
+ executionMust(t, os.Chmod(dir, 0700))
+ j, err := runner.OpenJournal(connectionContext, filepath.Join(dir, "journal.db"))
+ executionMust(t, err)
+ defer j.Close()
+ api, err := runner.NewHTTPInstance(server.URL, j, runnerproto.RunnerCredential{Token: token, ExpiresAt: time.Now().Add(time.Hour)})
+ executionMust(t, err)
+ if _, err = api.RecoverClaim(connectionContext, q); !errors.Is(err, runner.ErrCleanupExpired) {
+ t.Fatal("HTTP lost cleanup expiry", err)
+ }
+
+}
diff --git a/internal/runner/containment_r1_test.go b/internal/runner/containment_r1_test.go
index e7d56c94..bdbccc8d 100644
--- a/internal/runner/containment_r1_test.go
+++ b/internal/runner/containment_r1_test.go
@@ -148,7 +148,8 @@ func TestLinuxInspectorRealRunnerControlAndOtherAttempt(t *testing.T) {
if err = control.Start(); err != nil {
t.Fatal(err)
}
- t.Cleanup(func() { input.Close(); control.Process.Kill(); control.Wait() })
+ stopControl := stopFixturePID(t, control.Process.Pid)
+ t.Cleanup(func() { input.Close(); stopControl(); control.Wait() })
inv, err := p.Remaining(ctx, o)
if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 {
t.Fatalf("runner child not excluded: %+v %v", inv, err)
@@ -176,6 +177,8 @@ func TestLinuxInspectorRealRunnerControlAndOtherAttempt(t *testing.T) {
if err = control.Process.Signal(unix.Signal(0)); err != nil {
t.Fatal(err)
}
+
+ assertClosedAttemptUnknown(t, p, o, other)
}
func TestProcessIdentityOwnedPIDReuse(t *testing.T) {
diff --git a/internal/runner/containment_r2_test.go b/internal/runner/containment_r2_test.go
new file mode 100644
index 00000000..3daf756b
--- /dev/null
+++ b/internal/runner/containment_r2_test.go
@@ -0,0 +1,295 @@
+package runner
+
+import (
+ "context"
+ "fmt"
+ "os/exec"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "golang.org/x/sys/unix"
+)
+
+func stopFixturePID(t *testing.T, pid int) func() {
+ t.Helper()
+ fd, err := unix.PidfdOpen(pid, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stop := func() { _ = unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) }
+ t.Cleanup(func() { stop(); unix.Close(fd) })
+ return stop
+}
+
+func retiredFixture(t *testing.T, p *LinuxProcessInspector, o ProcessOwner) {
+ t.Helper()
+ s, r, _, _ := cleanupFixture(t)
+ s.journal, s.inspector, r.Owner = p.journal, p, o
+ r.Claim.Handle.Attempt, r.Claim.Handle.Fence = o.Attempt, o.Fence
+ if _, err := s.cleanup(context.Background(), r); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func assertClosedAttemptUnknown(t *testing.T, p *LinuxProcessInspector, open, closed ProcessOwner) {
+ t.Helper()
+ ctx := context.Background()
+ retiredFixture(t, p, closed)
+ // Reconstruct from the journal so retirement must be durable.
+ p, err := NewLinuxProcessInspector("/proc", p.client, p.journal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, mode := range []string{"marker", "cwd"} {
+ t.Run(mode, func(t *testing.T) {
+ dir, marker := "/", ""
+ if mode == "cwd" {
+ dir = closed.Workspace.Path
+ } else {
+ marker = "EQUIPO_ATTEMPT_MARKER=" + closed.Marker
+ }
+ cmd := exec.Command("/bin/sh", "-c", "env -i "+marker+" /usr/bin/setsid /bin/sleep 60 >/dev/null 2>&1 & echo $!")
+ cmd.Dir = dir
+ raw, err := cmd.Output()
+ if err != nil {
+ t.Fatal(err)
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ stop := stopFixturePID(t, pid)
+ time.Sleep(20 * time.Millisecond)
+ inv, err := p.Remaining(ctx, open)
+ if err != nil || inv.CoverageKnown || len(inv.Processes) != 0 {
+ t.Fatalf("closed attempt still hides late %s process: %+v %v", mode, inv, err)
+ }
+ id, err := p.identity(pid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if p.Stop(ctx, id) == nil {
+ t.Fatal("closed record authorized a signal")
+ }
+ s, r, _, _ := cleanupFixture(t)
+ s.journal, s.inspector, r.Owner = p.journal, p, open
+ if proof, err := s.cleanup(ctx, r); err == nil || proof.Empty {
+ t.Fatal("late process allowed containment")
+ }
+ stop()
+ })
+ }
+}
+
+func TestLinuxInspectorSequentialJobsRunnerGit(t *testing.T) {
+ if privateProcTest(t) {
+ return
+ }
+ p, base := realInspector(t)
+ ctx := context.Background()
+ for job := 0; job < 3; job++ {
+ prep := base
+ prep.Attempt += 2 * team.AttemptID(job)
+ prep.Marker = fmt.Sprintf("prepare-%d", job)
+ prep.LocalOnly = true
+ if err := p.Track(ctx, prep); err != nil {
+ t.Fatal(err)
+ }
+ retiredFixture(t, p, prep)
+ step := prep
+ step.Attempt++
+ step.Marker = fmt.Sprintf("step-%d", job)
+ step.Workspace.Path = t.TempDir()
+ if err := p.Track(ctx, step); err != nil {
+ t.Fatal(err)
+ }
+ git := exec.Command("/usr/bin/git", "hash-object", "--stdin")
+ git.Dir = prep.Workspace.Path
+ git.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"}
+ input, err := git.StdinPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = git.Start(); err != nil {
+ t.Fatal(err)
+ }
+ stop := stopFixturePID(t, git.Process.Pid)
+ t.Cleanup(func() { input.Close(); stop(); git.Wait() })
+ inv, err := p.Remaining(ctx, step)
+ if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 {
+ t.Fatalf("job %d runner git blocked: %+v %v", job, inv, err)
+ }
+ retiredFixture(t, p, step)
+ stop()
+ }
+}
+
+func TestLinuxInspectorUnchangedScanDoesNotWrite(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ for _, sql := range []string{
+ "CREATE TABLE process_writes(n INTEGER)",
+ "CREATE TRIGGER count_process_writes AFTER UPDATE ON journal_supervisor WHEN NEW.kind='process' BEGIN INSERT INTO process_writes VALUES(1); END",
+ } {
+ if _, err := p.journal.db.Exec(sql); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < 3; i++ {
+ if _, err := p.Remaining(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ }
+ var count int
+ if err := p.journal.db.QueryRow("SELECT count(*) FROM process_writes").Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if count != 0 {
+ t.Fatalf("unchanged scans wrote %d records", count)
+ }
+}
+
+func TestRunnerRestartBeforeTrackContainsEmpty(t *testing.T) {
+ p, o := processFixture(t)
+ s, r, _, _ := cleanupFixture(t)
+ s.journal, s.inspector = p.journal, p
+ r.Owner = o
+ r.Owner.LocalOnly, r.Owner.AgentID = true, ""
+ r.Owner.Workspace = paseo.Workspace{Path: o.Workspace.Path}
+ r.Agent = paseo.Agent{}
+ r.Phase = "creating-workspace"
+ if err := s.save(context.Background(), r); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Recover(context.Background()); err != nil {
+ t.Fatalf("pre-Track crash blocks recovery: %v", err)
+ }
+ if !s.ready || s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)].Phase != "contained" {
+ t.Fatal("unstarted attempt not contained")
+ }
+}
+
+type retirementAPI struct {
+ *supervisorAPI
+ inspector *LinuxProcessInspector
+ closed ProcessOwner
+}
+
+func (a *retirementAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error {
+ if op == "contained" && !a.inspector.records[ownerKey(a.closed)].Closed {
+ return paseo.ErrUncertain
+ }
+ return a.supervisorAPI.Call(ctx, op, q, out)
+}
+func TestRunnerRestartRetiresBeforeRecovery(t *testing.T) {
+ p, o := processFixture(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ s, old, _, _ := cleanupFixture(t)
+ s.journal, s.inspector, old.Owner = p.journal, p, o
+ old.Phase = "contained"
+ if err := s.save(ctx, old); err != nil {
+ t.Fatal(err)
+ }
+ next := *old
+ next.Phase = "completed"
+ for {
+ next.Claim.Handle.Attempt++
+ if attemptKey(next.Claim.Scope, next.Claim.Handle) < attemptKey(old.Claim.Scope, old.Claim.Handle) {
+ break
+ }
+ }
+ next.Owner.Attempt = next.Claim.Handle.Attempt
+ next.Owner.Marker = "next"
+ if err := p.Track(ctx, next.Owner); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.save(ctx, &next); err != nil {
+ t.Fatal(err)
+ }
+ s.api = &retirementAPI{supervisorAPI: s.api.(*supervisorAPI), inspector: p, closed: o}
+ if err := s.Recover(ctx); err != nil {
+ t.Fatal("legacy contained record remained open during recovery", err)
+ }
+}
+
+func TestLinuxInspectorKnownMembersStayLive(t *testing.T) {
+ if privateProcTest(t) {
+ return
+ }
+ p, o := realInspector(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 3; i++ {
+ c := childProcess(t, o.Workspace.Path, o.Marker)
+ inv, err := p.Remaining(ctx, o)
+ if err != nil || len(inv.Processes) != 1 {
+ t.Fatal(inv, err)
+ }
+ if err = p.Stop(ctx, inv.Processes[0]); err != nil {
+ t.Fatal(err)
+ }
+ c.Wait()
+ inv, err = p.Remaining(ctx, o)
+ if err != nil || !inv.CoverageKnown || len(p.records[ownerKey(o)].Known) != 0 {
+ t.Fatal("dead process identities retained", inv, err)
+ }
+ }
+}
+
+func TestLinuxInspectorRunnerControlPrecedesOtherPaths(t *testing.T) {
+ if privateProcTest(t) {
+ return
+ }
+ p, o := realInspector(t)
+ ctx := context.Background()
+ if err := p.Track(ctx, o); err != nil {
+ t.Fatal(err)
+ }
+ other := o
+ other.Attempt++
+ other.Marker = "other"
+ other.LocalOnly = true
+ other.Workspace.Path = t.TempDir()
+ if err := p.Track(ctx, other); err != nil {
+ t.Fatal(err)
+ }
+ other.Attempt++
+ other.Marker = "another"
+ if err := p.Track(ctx, other); err != nil {
+ t.Fatal(err)
+ }
+ git := exec.Command("/usr/bin/git", "hash-object", "--stdin")
+ git.Dir = other.Workspace.Path
+ git.Env = []string{"GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"}
+ input, err := git.StdinPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = git.Start(); err != nil {
+ t.Fatal(err)
+ }
+ stop := stopFixturePID(t, git.Process.Pid)
+ defer func() { input.Close(); stop(); git.Wait() }()
+ inv, err := p.Remaining(ctx, o)
+ if err != nil || !inv.CoverageKnown || len(inv.Processes) != 0 {
+ t.Fatal("runner git lost to other paths", inv, err)
+ }
+ for _, r := range p.records {
+ if len(r.Known) != 0 {
+ t.Fatal("runner control attributed to another attempt")
+ }
+ }
+}
diff --git a/internal/runner/creation_recovery.go b/internal/runner/creation_recovery.go
index eaf4a4d7..edf9a2df 100644
--- a/internal/runner/creation_recovery.go
+++ b/internal/runner/creation_recovery.go
@@ -25,6 +25,7 @@ func (j *Journal) creationIntent(ctx context.Context, kind, key string, out any)
}
return true, json.Unmarshal(intent.Request, out)
}
+
func (s *Supervisor) recoverCreation(ctx context.Context, r *attemptState) error {
if r.Claim.Assignment.Kind == "prepare" {
return nil
@@ -44,14 +45,16 @@ func (s *Supervisor) recoverCreation(ctx context.Context, r *attemptState) error
return paseo.ErrUncertain
}
ws, err := client.RecoverWorkspace(ctx, request)
- if err != nil {
+ if err = s.settleCreation(ctx, "workspace", r.Claim.Assignment.WorkspaceKey, err); err != nil {
return err
}
- r.Owner.Workspace = ws
- r.Owner.LocalOnly = false
- changed = true
- if err = s.save(ctx, r); err != nil {
- return err
+ if ws.WorkspaceID != "" {
+ r.Owner.Workspace = ws
+ r.Owner.LocalOnly = false
+ changed = true
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
}
}
}
@@ -69,13 +72,15 @@ func (s *Supervisor) recoverCreation(ctx context.Context, r *attemptState) error
return paseo.ErrUncertain
}
r.Agent, err = client.RecoverAgent(ctx, request)
- if err != nil {
+ if err = s.settleCreation(ctx, "agent", r.request("agent").RequestID, err); err != nil {
return err
}
- r.Owner.AgentID = r.Agent.AgentID
- changed = true
- if err = s.save(ctx, r); err != nil {
- return err
+ if r.Agent.AgentID != "" {
+ r.Owner.AgentID = r.Agent.AgentID
+ changed = true
+ if err = s.save(ctx, r); err != nil {
+ return err
+ }
}
}
}
@@ -84,3 +89,42 @@ func (s *Supervisor) recoverCreation(ctx context.Context, r *attemptState) error
}
return nil
}
+
+func (j *Journal) RecordCreationRefusal(ctx context.Context, i paseo.Intent) error {
+ if i.Kind != "agent" && i.Kind != "workspace" {
+ return paseo.ErrContract
+ }
+ var raw []byte
+ if err := j.db.QueryRowContext(ctx, "SELECT body FROM journal_intents WHERE intent_key=?", runnerproto.EventHash([]string{i.Kind, i.Key})).Scan(&raw); err != nil {
+ return err
+ }
+ var intent paseo.Intent
+ i.Request = RedactJSON(i.Request, nil)
+ if json.Unmarshal(raw, &intent) != nil || intent.Kind != i.Kind || intent.Key != i.Key || intent.RequestHash != i.RequestHash || string(intent.Request) != string(i.Request) {
+ return paseo.ErrIdentity
+ }
+ return j.saveState(ctx, "creation-refused", runnerproto.EventHash([]string{i.Kind, i.Key}), i)
+}
+
+// Absence alone cannot settle a lost reply. Only a durable definitive refusal
+// plus a complete lookup of the preassigned ID proves nothing was created.
+func (s *Supervisor) settleCreation(ctx context.Context, kind, key string, createErr error) error {
+ if !errors.Is(createErr, paseo.ErrCreationAbsent) {
+ return createErr
+ }
+ var raw, refusal []byte
+ id := runnerproto.EventHash([]string{kind, key})
+ if err := s.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_intents WHERE intent_key=?", id).Scan(&raw); err != nil {
+ return err
+ }
+ if err := s.journal.db.QueryRowContext(ctx, "SELECT body FROM journal_supervisor WHERE kind='creation-refused' AND state_key=?", id).Scan(&refusal); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return paseo.ErrUncertain
+ }
+ return err
+ }
+ if string(raw) != string(refusal) {
+ return paseo.ErrIdentity
+ }
+ return nil
+}
diff --git a/internal/runner/http.go b/internal/runner/http.go
index 92fbdf6f..53658dfd 100644
--- a/internal/runner/http.go
+++ b/internal/runner/http.go
@@ -118,6 +118,9 @@ func (c *HTTPInstance) claim(ctx context.Context, op string, q runnerproto.Claim
if err = c.post(ctx, op, q, token, &claim); err != nil {
return claim, err
}
+ if op == "recover_claim" && claim.CleanupExpired {
+ return claim, ErrCleanupExpired
+ }
if claim.NotClaimed {
return claim, ErrNotClaimed
}
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go
index e04e29dd..7b6ebc1e 100644
--- a/internal/runner/paseo/client.go
+++ b/internal/runner/paseo/client.go
@@ -7,6 +7,7 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "errors"
"fmt"
"io"
"net"
@@ -64,7 +65,7 @@ type Subscription struct {
func Start(ctx context.Context, cfg Config) (*Client, error) {
host, port, err := net.SplitHostPort(cfg.Endpoint)
- if err != nil || host != "127.0.0.1" || port == "" || !filepath.IsAbs(cfg.DaemonHome) || !filepath.IsAbs(cfg.BridgePath) || cfg.ServerID == "" || cfg.RecordIntent == nil {
+ if err != nil || host != "127.0.0.1" || port == "" || !filepath.IsAbs(cfg.DaemonHome) || !filepath.IsAbs(cfg.BridgePath) || cfg.ServerID == "" || cfg.RecordIntent == nil || cfg.RecordCreationRefusal == nil {
return nil, ErrContract
}
if cfg.NodePath == "" {
@@ -266,6 +267,10 @@ func bridgeError(code string) error {
switch code {
case "subscription_not_ready":
return ErrNotReady
+ case "creation_absent":
+ return ErrCreationAbsent
+ case "create_refused":
+ return ErrCreateRefused
case "policy_mismatch":
return ErrPolicy
case "wrong_server", "identity_mismatch":
@@ -409,6 +414,18 @@ func (c *Client) intent(ctx context.Context, kind, key string, request any) erro
sum := sha256.Sum256(b)
return c.cfg.RecordIntent(ctx, Intent{Kind: kind, Key: key, RequestHash: hex.EncodeToString(sum[:]), Request: b})
}
+func (c *Client) creationRefused(ctx context.Context, kind, key string, request any, cause error) error {
+ if c.cfg.RecordCreationRefusal == nil {
+ return errors.Join(cause, ErrContract)
+ }
+ b, err := json.Marshal(request)
+ if err != nil {
+ return errors.Join(cause, err)
+ }
+ sum := sha256.Sum256(b)
+ err = c.cfg.RecordCreationRefusal(context.WithoutCancel(ctx), Intent{Kind: kind, Key: key, RequestHash: hex.EncodeToString(sum[:]), Request: b})
+ return errors.Join(cause, err)
+}
func (c *Client) CreateWorkspace(ctx context.Context, r WorkspaceRequest) (Workspace, error) {
var w Workspace
if r.Isolation != "worktree" || !pathAllowed(r.Path, r.ReadPolicy) || r.ProjectID == "" || r.BaseCommit == "" || r.Branch == "" {
@@ -421,6 +438,9 @@ func (c *Client) CreateWorkspace(ctx context.Context, r WorkspaceRequest) (Works
return w, err
}
if err := c.call(ctx, "create_workspace", r, &w); err != nil {
+ if errors.Is(err, ErrCreateRefused) {
+ err = c.creationRefused(ctx, "workspace", r.IdempotencyKey, r, err)
+ }
return w, err
}
if (r.ResourceID != "" && w.WorkspaceID != r.ResourceID) || w.ServerID != c.cfg.ServerID || w.ProjectID != r.ProjectID || w.WorkspaceID == "" || !pathAllowed(w.Path, r.ReadPolicy) {
@@ -438,14 +458,17 @@ func (c *Client) CreateAgent(ctx context.Context, r AgentRequest) (Agent, error)
return a, err
}
if r.Workspace.ServerID != c.cfg.ServerID || r.Workspace.WorkspaceID == "" || !pathAllowed(r.Workspace.Path, r.ReadPolicy) || r.ModeID != "default" {
- return a, ErrPolicy
+ return a, c.creationRefused(ctx, "agent", r.IdempotencyKey, r, ErrPolicy)
}
for _, m := range r.MCPServers {
if m.Type != "stdio" || !filepath.IsAbs(m.Command) {
- return a, ErrPolicy
+ return a, c.creationRefused(ctx, "agent", r.IdempotencyKey, r, ErrPolicy)
}
}
if err := c.call(ctx, "create_agent", r, &a); err != nil {
+ if errors.Is(err, ErrCreateRefused) {
+ err = c.creationRefused(ctx, "agent", r.IdempotencyKey, r, err)
+ }
return a, err
}
if (r.ResourceID != "" && a.AgentID != r.ResourceID) || a.ServerID != c.cfg.ServerID || a.WorkspaceID != r.Workspace.WorkspaceID || a.AgentID == "" || a.ProviderSessionID == "" || a.AccountID != caps.ObservedAccount || a.Provider != r.Selection.Provider || a.Model != r.Selection.Model || a.Family != r.Selection.Family {
diff --git a/internal/runner/paseo/client_test.go b/internal/runner/paseo/client_test.go
index d9b1e2e2..c06f01f3 100644
--- a/internal/runner/paseo/client_test.go
+++ b/internal/runner/paseo/client_test.go
@@ -31,7 +31,7 @@ func fixtureAgent() Agent {
}
func testClient(t *testing.T, mode string, change func(*Config)) *Client {
t.Helper()
- cfg := Config{ServerID: "server", VerifiedTuples: []VerifiedTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", ConfigHash: "hash"}}, RecordIntent: func(context.Context, Intent) error { return nil }, InspectProcesses: func(context.Context, Selection) (bool, error) { return true, nil }}
+ cfg := Config{ServerID: "server", VerifiedTuples: []VerifiedTuple{{Provider: "claude", ProviderVersion: "2.1.312", PaseoVersion: "0.14.0", ConfigHash: "hash"}}, RecordIntent: func(context.Context, Intent) error { return nil }, RecordCreationRefusal: func(context.Context, Intent) error { return nil }, InspectProcesses: func(context.Context, Selection) (bool, error) { return true, nil }}
if change != nil {
change(&cfg)
}
@@ -260,8 +260,26 @@ func TestPaseoHelper(t *testing.T) {
case "register_project":
result = Project{ServerID: "server", ProjectID: "project", Path: "/repo"}
case "create_workspace":
+ if mode == "refused" {
+ code = "create_refused"
+ }
+ if mode == "uncertain" {
+ code = "uncertain"
+ }
+ if mode == "policy-after-create" {
+ code = "policy_mismatch"
+ }
result = fixtureWorkspace()
case "create_agent":
+ if mode == "refused" {
+ code = "create_refused"
+ }
+ if mode == "uncertain" {
+ code = "uncertain"
+ }
+ if mode == "policy-after-create" {
+ code = "policy_mismatch"
+ }
if mode == "lost-create" {
os.Exit(0)
}
diff --git a/internal/runner/paseo/creation_r2_test.go b/internal/runner/paseo/creation_r2_test.go
new file mode 100644
index 00000000..8f77c45f
--- /dev/null
+++ b/internal/runner/paseo/creation_r2_test.go
@@ -0,0 +1,47 @@
+package paseo
+
+import (
+ "context"
+ "errors"
+ "testing"
+)
+
+func TestPaseoCreationRefusalRecorded(t *testing.T) {
+ for _, kind := range []string{"agent", "workspace"} {
+ for _, mode := range []string{"local", "refused", "uncertain", "policy-after-create"} {
+ if kind == "workspace" && mode == "local" {
+ continue
+ }
+ t.Run(kind+"/"+mode, func(t *testing.T) {
+ var intent, refusal Intent
+ c := testClient(t, mode, func(cfg *Config) {
+ cfg.RecordIntent = func(_ context.Context, i Intent) error { intent = i; return nil }
+ cfg.RecordCreationRefusal = func(_ context.Context, i Intent) error { refusal = i; return nil }
+ })
+ var err error
+ if kind == "agent" {
+ r := AgentRequest{ResourceID: "agent", Workspace: fixtureWorkspace(), Selection: fixtureSelection(), IdempotencyKey: "intent", ModeID: "default", ReadPolicy: fixturePolicy()}
+ if mode == "local" {
+ r.ModeID = "invalid"
+ }
+ _, err = c.CreateAgent(context.Background(), r)
+ } else {
+ _, err = c.CreateWorkspace(context.Background(), WorkspaceRequest{ResourceID: "workspace", Isolation: "worktree", ProjectID: "project", Path: "/repo", BaseCommit: "base", Branch: "review", IdempotencyKey: "intent", Selection: fixtureSelection(), ReadPolicy: fixturePolicy()})
+ }
+ if err == nil {
+ t.Fatal("creation unexpectedly succeeded")
+ }
+ definite := mode == "local" || mode == "refused"
+ if (refusal.Key != "") != definite {
+ t.Fatal("wrong definitive creation outcome", refusal, err)
+ }
+ if definite && (refusal.Kind != kind || refusal.Key != intent.Key || refusal.RequestHash != intent.RequestHash) {
+ t.Fatal("refusal not bound to original intent")
+ }
+ if mode == "uncertain" && !errors.Is(err, ErrUncertain) {
+ t.Fatal(err)
+ }
+ })
+ }
+ }
+}
diff --git a/internal/runner/paseo/types.go b/internal/runner/paseo/types.go
index 7b944228..95a3d0ab 100644
--- a/internal/runner/paseo/types.go
+++ b/internal/runner/paseo/types.go
@@ -16,14 +16,16 @@ type Error string
func (e Error) Error() string { return string(e) }
const (
- ErrContract Error = "paseo_contract"
- ErrClosed Error = "paseo_closed"
- ErrUncertain Error = "paseo_uncertain"
- ErrNotReady Error = "subscription_not_ready"
- ErrCapability Error = "unsupported_capability"
- ErrIsolation Error = "read_isolation_required"
- ErrPolicy Error = "policy_mismatch"
- ErrIdentity Error = "identity_mismatch"
+ ErrContract Error = "paseo_contract"
+ ErrClosed Error = "paseo_closed"
+ ErrUncertain Error = "paseo_uncertain"
+ ErrNotReady Error = "subscription_not_ready"
+ ErrCapability Error = "unsupported_capability"
+ ErrIsolation Error = "read_isolation_required"
+ ErrCreationAbsent Error = "creation_absent"
+ ErrCreateRefused Error = "create_refused"
+ ErrPolicy Error = "policy_mismatch"
+ ErrIdentity Error = "identity_mismatch"
)
type Selection struct {
@@ -134,16 +136,17 @@ type Intent struct {
Request json.RawMessage
}
type Config struct {
- VerifyRouting func(context.Context, Selection, Capabilities) error
- NodePath string
- BridgePath string
- DaemonHome string
- Endpoint string
- ServerID string
- VerifiedTuples []VerifiedTuple
- RecordIntent func(context.Context, Intent) error
- InspectProcesses func(context.Context, Selection) (bool, error)
- AuthorizeUnconfined func(context.Context, Selection, Capabilities) error
+ VerifyRouting func(context.Context, Selection, Capabilities) error
+ NodePath string
+ BridgePath string
+ DaemonHome string
+ Endpoint string
+ ServerID string
+ VerifiedTuples []VerifiedTuple
+ RecordIntent func(context.Context, Intent) error
+ RecordCreationRefusal func(context.Context, Intent) error
+ InspectProcesses func(context.Context, Selection) (bool, error)
+ AuthorizeUnconfined func(context.Context, Selection, Capabilities) error
}
type ProjectRequest struct {
diff --git a/internal/runner/process_linux.go b/internal/runner/process_linux.go
index fc28178d..b675513c 100644
--- a/internal/runner/process_linux.go
+++ b/internal/runner/process_linux.go
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "slices"
"sort"
"strconv"
"strings"
@@ -26,12 +27,14 @@ type ProcessInspector interface {
Track(context.Context, ProcessOwner) error
Remaining(context.Context, ProcessOwner) (ProcessInventory, error)
Stop(context.Context, ProcessIdentity) error
+ Retire(context.Context, ProcessOwner) error
}
type TerminalClient interface {
ListTerminals(context.Context, paseo.Workspace) ([]string, error)
KillTerminal(context.Context, paseo.Workspace, string) error
}
type processRecord struct {
+ Closed bool
Owner ProcessOwner
Known []ProcessIdentity
Commands map[string][]ProcessIdentity
@@ -44,6 +47,7 @@ type LinuxProcessInspector struct {
journal *Journal
mu sync.Mutex
records map[string]*processRecord
+ persisted map[string]string
beforeTrackPID func(int)
}
@@ -55,7 +59,7 @@ func NewLinuxProcessInspector(procRoot string, client TerminalClient, journal *J
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{}}
+ p := &LinuxProcessInspector{root: procRoot, boot: strings.TrimSpace(string(b)), client: client, journal: journal, records: map[string]*processRecord{}, persisted: map[string]string{}}
// The durable Track boundary remains valid across sampling gaps and restarts.
var records []processRecord
if err := journal.readStates(context.Background(), "process", &records); err != nil {
@@ -64,6 +68,11 @@ func NewLinuxProcessInspector(procRoot string, client TerminalClient, journal *J
for i := range records {
r := records[i]
p.records[ownerKey(r.Owner)] = &r
+ raw, err := json.Marshal(r)
+ if err != nil {
+ return nil, err
+ }
+ p.persisted[ownerKey(r.Owner)] = string(raw)
}
return p, nil
}
@@ -92,6 +101,9 @@ func (p *LinuxProcessInspector) Track(ctx context.Context, o ProcessOwner) error
// Linux exposes stat starttime in USER_HZ (100 ticks per second).
p.records[key] = &processRecord{Owner: o, TrackTicks: uint64(reading.Elapsed / (10 * time.Millisecond)), TrackBoot: p.boot}
} else {
+ if p.records[key].Closed {
+ return paseo.ErrIdentity
+ }
p.records[key].Owner = o
}
if err = p.save(ctx, p.records[key]); err != nil {
@@ -107,7 +119,19 @@ func (p *LinuxProcessInspector) Track(ctx context.Context, o ProcessOwner) error
return nil
}
func (p *LinuxProcessInspector) save(ctx context.Context, r *processRecord) error {
- return p.journal.saveState(ctx, "process", ownerKey(r.Owner), r)
+ raw, err := json.Marshal(r)
+ if err != nil {
+ return err
+ }
+ key := ownerKey(r.Owner)
+ if p.persisted[key] == string(raw) {
+ return nil
+ }
+ if err = p.journal.saveState(ctx, "process", key, r); err != nil {
+ return err
+ }
+ p.persisted[key] = string(raw)
+ return nil
}
func (p *LinuxProcessInspector) Remaining(ctx context.Context, o ProcessOwner) (ProcessInventory, error) {
p.mu.Lock()
@@ -119,6 +143,34 @@ func (p *LinuxProcessInspector) Remaining(ctx context.Context, o ProcessOwner) (
return p.scan(ctx, r, true)
}
+func (p *LinuxProcessInspector) Retire(ctx context.Context, o ProcessOwner) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ r := p.records[ownerKey(o)]
+ if r == nil {
+ // No Track means no process could have started.
+ return nil
+ }
+ r.Closed = true
+ r.Known, r.Commands, r.Owner.ExecutorGroups = nil, nil, nil
+ return p.save(ctx, r)
+}
+
+// Effects may start only after Track has committed. Recovery can therefore
+// prove an unstarted local owner empty without inventing a historical boundary.
+func (p *LinuxProcessInspector) cleanupInventory(ctx context.Context, o ProcessOwner) (ProcessInventory, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.records[ownerKey(o)] == nil && o.LocalOnly && o.AgentID == "" {
+ return ProcessInventory{CoverageKnown: true, BootID: p.boot, CheckedAt: time.Now().UTC()}, nil
+ }
+ r := p.records[ownerKey(o)]
+ if r == nil {
+ return ProcessInventory{}, paseo.ErrIdentity
+ }
+ return p.scan(ctx, r, true)
+}
+
type procEntry struct {
id ProcessIdentity
parent, group int
@@ -177,12 +229,18 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
entries, err := os.ReadDir(p.root)
if err != nil {
unknown()
- return inv, errors.Join(err, p.save(context.WithoutCancel(ctx), r))
+ return inv, err
}
all := map[int]procEntry{}
attributed := map[int]string{}
known := map[string]string{}
+ pathsByPID := map[int][]string{}
+ closedMatch := map[int]bool{}
+ closedMarker := map[int]bool{}
for key, record := range p.records {
+ if record.Closed {
+ continue
+ }
for _, id := range record.Known {
known[identityKey(id)] = key
}
@@ -260,6 +318,11 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
}
}
path := cwdErr == nil && (cwd == record.Owner.Workspace.Path || strings.HasPrefix(cwd, record.Owner.Workspace.Path+"/"))
+ if record.Closed {
+ closedMatch[pid] = closedMatch[pid] || marker || path
+ closedMarker[pid] = closedMarker[pid] || marker
+ continue
+ }
if marker {
markers = append(markers, key)
}
@@ -271,10 +334,10 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
attributed[pid] = markers[0]
} else if len(markers) > 1 {
unknown()
- } else if len(paths) == 1 {
- attributed[pid] = paths[0]
- } else if len(paths) > 1 {
- unknown()
+ }
+ pathsByPID[pid] = paths
+ if closedMarker[pid] {
+ delete(attributed, pid)
}
}
@@ -283,7 +346,7 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
changed = false
for pid, e := range all {
parent, ok := all[e.parent]
- if attributed[pid] == "" && ok && attributed[e.parent] != "" && parent.id.StartTicks <= e.id.StartTicks {
+ if !closedMatch[pid] && attributed[pid] == "" && ok && attributed[e.parent] != "" && parent.id.StartTicks <= e.id.StartTicks {
attributed[pid] = attributed[e.parent]
changed = true
}
@@ -298,12 +361,37 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
for changed := true; changed; {
changed = false
for pid, e := range all {
- if !controls[pid] && attributed[pid] == "" && controls[e.parent] && all[e.parent].id.StartTicks <= e.id.StartTicks {
+ if !closedMarker[pid] && !slices.Contains(pathsByPID[pid], ownerKey(r.Owner)) && !controls[pid] && attributed[pid] == "" && controls[e.parent] && all[e.parent].id.StartTicks <= e.id.StartTicks {
controls[pid] = true
changed = true
}
}
}
+ // Explicit ownership wins first. Runner ancestry wins over path matches,
+ // including stale preparation paths. Closed records confer no ownership.
+ for pid, paths := range pathsByPID {
+ if controls[pid] || attributed[pid] != "" {
+ continue
+ }
+ if closedMatch[pid] {
+ continue
+ }
+ if len(paths) == 1 {
+ attributed[pid] = paths[0]
+ } else if len(paths) > 1 {
+ unknown()
+ }
+ }
+ for changed := true; changed; {
+ changed = false
+ for pid, e := range all {
+ parent, ok := all[e.parent]
+ if !closedMatch[pid] && !controls[pid] && attributed[pid] == "" && ok && attributed[e.parent] != "" && parent.id.StartTicks <= e.id.StartTicks {
+ attributed[pid] = attributed[e.parent]
+ changed = true
+ }
+ }
+ }
for pid, e := range all {
if r.TrackBoot != p.boot && r.TrackBoot != "" {
continue
@@ -326,6 +414,11 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
}
}
for _, record := range p.records {
+ if record.Closed {
+ continue
+ }
+ record.Known = liveIdentities(record.Known, all)
+ record.Owner.ExecutorGroups = liveIdentities(record.Owner.ExecutorGroups, all)
for command, ids := range record.Commands {
members := map[int]bool{}
for _, id := range ids {
@@ -349,6 +442,7 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
}
}
}
+ record.Commands[command] = liveIdentities(ids, all)
saved := map[string]bool{}
for _, id := range ids {
saved[identityKey(id)] = true
@@ -359,6 +453,7 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
record.Commands[command] = append(record.Commands[command], id)
}
}
+ record.Commands[command] = liveIdentities(record.Commands[command], all)
}
}
@@ -408,6 +503,9 @@ func (p *LinuxProcessInspector) scan(ctx context.Context, r *processRecord, term
inv.Observed = append([]ProcessIdentity(nil), r.Known...)
inv.ExecutorGroups = append([]ProcessIdentity(nil), r.Owner.ExecutorGroups...)
for _, record := range p.records {
+ if record.Closed {
+ continue
+ }
if err := p.save(context.WithoutCancel(ctx), record); err != nil {
return inv, err
}
@@ -430,6 +528,9 @@ func (p *LinuxProcessInspector) Stop(ctx context.Context, id ProcessIdentity) er
}
owned := false
for _, r := range p.records {
+ if r.Closed {
+ continue
+ }
for _, known := range r.Known {
owned = owned || known == id
}
@@ -538,7 +639,7 @@ func (p *LinuxProcessInspector) TrackPID(ctx context.Context, o ProcessOwner, pi
p.mu.Lock()
defer p.mu.Unlock()
r := p.records[ownerKey(o)]
- if r == nil {
+ if r == nil || r.Closed {
return paseo.ErrIdentity
}
if p.beforeTrackPID != nil {
@@ -664,3 +765,16 @@ func (p *LinuxProcessInspector) EndCommand(ctx context.Context, o ProcessOwner,
}
return failures
}
+
+func liveIdentities(ids []ProcessIdentity, all map[int]procEntry) []ProcessIdentity {
+ var live []ProcessIdentity
+ seen := map[ProcessIdentity]bool{}
+ for _, id := range ids {
+ if e, ok := all[id.PID]; ok && e.id == id && !seen[id] {
+ live = append(live, id)
+ seen[id] = true
+ }
+ }
+ sort.Slice(live, func(i, j int) bool { return live[i].PID < live[j].PID })
+ return live
+}
diff --git a/internal/runner/process_linux_test.go b/internal/runner/process_linux_test.go
index b47753f4..ba63dc59 100644
--- a/internal/runner/process_linux_test.go
+++ b/internal/runner/process_linux_test.go
@@ -57,7 +57,8 @@ func childProcess(t *testing.T, dir, marker string) *exec.Cmd {
if err := c.Start(); err != nil {
t.Fatal(err)
}
- t.Cleanup(func() { c.Process.Kill(); c.Wait() })
+ stop := stopFixturePID(t, c.Process.Pid)
+ t.Cleanup(func() { stop(); c.Wait() })
return c
}
func TestLinuxInspectorEnvironmentStrippedChild(t *testing.T) {
diff --git a/internal/runner/retry.go b/internal/runner/retry.go
index 057d90d9..51da63a8 100644
--- a/internal/runner/retry.go
+++ b/internal/runner/retry.go
@@ -9,6 +9,7 @@ import (
)
var ErrTransient = errors.New("runner_transient")
+var ErrCleanupExpired = errors.New("runner_cleanup_expired")
var ErrNotClaimed = errors.New("runner_not_claimed")
var ErrClaimRefused = errors.New("runner_claim_refused")
diff --git a/internal/runner/runtime.go b/internal/runner/runtime.go
index 818dc2be..bd2b6f80 100644
--- a/internal/runner/runtime.go
+++ b/internal/runner/runtime.go
@@ -75,7 +75,7 @@ func openRuntime(ctx context.Context, c Config) (r *Runtime, err error) {
for _, v := range release.BuildManifest().VerifiedIsolationTuples {
tuples = append(tuples, paseo.VerifiedTuple{Provider: v.Provider, ProviderVersion: v.ProviderVersion, PaseoVersion: v.PaseoVersion, ConfigHash: v.IsolationConfigHash})
}
- r.client, err = paseo.Start(ctx, paseo.Config{VerifyRouting: r.verifyRouting, VerifiedTuples: tuples, NodePath: c.NodePath, BridgePath: c.BridgePath, DaemonHome: c.PaseoHome, Endpoint: c.PaseoEndpoint, ServerID: c.PaseoServerID, RecordIntent: r.journal.RecordIntent, InspectProcesses: r.coverage, AuthorizeUnconfined: r.authorizeUnconfined})
+ r.client, err = paseo.Start(ctx, paseo.Config{VerifyRouting: r.verifyRouting, VerifiedTuples: tuples, NodePath: c.NodePath, BridgePath: c.BridgePath, DaemonHome: c.PaseoHome, Endpoint: c.PaseoEndpoint, ServerID: c.PaseoServerID, RecordIntent: r.journal.RecordIntent, RecordCreationRefusal: r.journal.RecordCreationRefusal, InspectProcesses: r.coverage, AuthorizeUnconfined: r.authorizeUnconfined})
if err != nil {
return r, err
}
diff --git a/internal/runner/service.go b/internal/runner/service.go
index 10a38977..65f3512e 100644
--- a/internal/runner/service.go
+++ b/internal/runner/service.go
@@ -91,7 +91,7 @@ func (s *Service) recoverClaims(ctx context.Context) error {
}
var reply runnerproto.ClaimResponse
err := retryAuthority(ctx, func() error { var e error; reply, e = source.RecoverClaim(ctx, q); return e })
- if errors.Is(err, ErrNotClaimed) {
+ if errors.Is(err, ErrNotClaimed) || errors.Is(err, ErrCleanupExpired) {
if err = s.clearClaim(ctx, q); err != nil {
return err
}
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go
index 12fa589f..d63b1a60 100644
--- a/internal/runner/supervisor.go
+++ b/internal/runner/supervisor.go
@@ -155,11 +155,15 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error {
<-done
cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cleanupCancel()
- outcome := "accepted"
+ return s.finishAttempt(cleanupCtx, r, err)
+}
+
+func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, err error) error {
+ outcome := "unprocessed"
if err != nil {
outcome = "rejected"
}
- err = errors.Join(err, s.journal.finishTools(cleanupCtx, r.Claim, outcome))
+ bookkeepingErr := s.journal.finishTools(cleanupCtx, r.Claim, outcome)
if err != nil {
q := r.request("failed")
q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure}
@@ -169,7 +173,7 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error {
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)
+ return errors.Join(err, bookkeepingErr, cleanupErr)
}
func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelFunc, r *attemptState, l *leaseGuard, done chan struct{}) {
defer close(done)
@@ -312,7 +316,7 @@ func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentP
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)
+ inventory, err := s.cleanupInventory(ctx, r.Owner)
failures = errors.Join(failures, err)
proof.Observed = append(proof.Observed, inventory.Observed...)
proof.Owner.ExecutorGroups = inventory.ExecutorGroups
@@ -325,7 +329,7 @@ func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentP
if !r.Owner.LocalOnly {
failures = errors.Join(failures, s.client.ArchiveWorkspace(ctx, r.Owner.Workspace))
}
- inventory, err = s.inspector.Remaining(ctx, r.Owner)
+ inventory, err = s.cleanupInventory(ctx, r.Owner)
proof.Inventory = inventory
failures = errors.Join(failures, err)
if failures != nil {
@@ -374,6 +378,9 @@ func (s *Supervisor) finishRotation(ctx context.Context, r *attemptState) (Conta
if r.Proof == nil || r.Rotation == nil {
return ContainmentProof{}, paseo.ErrUncertain
}
+ if err := s.inspector.Retire(ctx, r.Owner); err != nil {
+ return *r.Proof, err
+ }
if r.Rotation.Bearer.Token != "" {
if s.credentialsPath == "" || s.installCredentials == nil {
return *r.Proof, paseo.ErrContract
@@ -397,6 +404,15 @@ func (s *Supervisor) Recover(ctx context.Context) error {
return err
}
var failures error
+ // Close historical records before scanning any unfinished attempt.
+ for _, r := range states {
+ if r.Phase == "contained" || r.Rotation != nil {
+ failures = errors.Join(failures, s.inspector.Retire(ctx, r.Owner))
+ }
+ }
+ if failures != nil {
+ return failures
+ }
for i := range states {
r := &states[i]
failures = errors.Join(failures, s.journal.finishTools(ctx, r.Claim, "interrupted"))
@@ -487,3 +503,10 @@ func (s *Supervisor) cleanupSocket(ctx context.Context, r *attemptState) error {
}
return os.Remove(dir)
}
+
+func (s *Supervisor) cleanupInventory(ctx context.Context, o ProcessOwner) (ProcessInventory, error) {
+ if p, ok := s.inspector.(*LinuxProcessInspector); ok {
+ return p.cleanupInventory(ctx, o)
+ }
+ return s.inspector.Remaining(ctx, o)
+}
diff --git a/internal/runner/supervisor_r1_test.go b/internal/runner/supervisor_r1_test.go
index 765d0cda..024d2236 100644
--- a/internal/runner/supervisor_r1_test.go
+++ b/internal/runner/supervisor_r1_test.go
@@ -134,18 +134,19 @@ func TestRunnerRejectedToolsDrainWindow(t *testing.T) {
type creationRecoveryClient struct {
*cleanupClient
- workspace paseo.Workspace
- agent paseo.Agent
- lookups int
+ workspace paseo.Workspace
+ agent paseo.Agent
+ lookups int
+ recoveryErr error
}
func (c *creationRecoveryClient) RecoverWorkspace(context.Context, paseo.WorkspaceRequest) (paseo.Workspace, error) {
c.lookups++
- return c.workspace, nil
+ return c.workspace, c.recoveryErr
}
func (c *creationRecoveryClient) RecoverAgent(context.Context, paseo.AgentRequest) (paseo.Agent, error) {
c.lookups++
- return c.agent, nil
+ return c.agent, c.recoveryErr
}
func TestRunnerRestartCreationIntents(t *testing.T) {
s, r, _, _ := cleanupFixture(t)
diff --git a/internal/runner/supervisor_r2_test.go b/internal/runner/supervisor_r2_test.go
new file mode 100644
index 00000000..10c3e4f7
--- /dev/null
+++ b/internal/runner/supervisor_r2_test.go
@@ -0,0 +1,149 @@
+package runner
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/runner/paseo"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func TestRunnerRestartExpiredUnstartedClaim(t *testing.T) {
+ s, _, _, _ := cleanupFixture(t)
+ s.workflow = &BugWorkflow{}
+ q := runnerproto.ClaimRequest{Version: 1, AssignmentID: "expired", RequestID: "same-request", Revision: 3}
+ ctx := context.Background()
+ if err := s.journal.saveState(ctx, "claim", q.AssignmentID, q); err != nil {
+ t.Fatal(err)
+ }
+ source := &claimSourceR1{recovery: ErrCleanupExpired}
+ service := Service{Supervisor: s, Source: source}
+ if err := service.recoverClaims(ctx); err != nil {
+ t.Fatal("expired unstarted claim blocks startup", err)
+ }
+ var pending []runnerproto.ClaimRequest
+ if err := s.journal.readStates(ctx, "claim", &pending); err != nil || len(pending) != 0 {
+ t.Fatal("expired claim retained", pending, err)
+ }
+}
+
+func TestRunnerFinishToolsDoesNotChangeCompletion(t *testing.T) {
+ for _, broken := range []bool{false, true} {
+ t.Run(map[bool]string{false: "unprocessed", true: "ack-error"}[broken], func(t *testing.T) {
+ s, r, _, order := cleanupFixture(t)
+ r.Claim.Assignment.TaskID = "task"
+ sub := ToolSubmission{InstanceID: "instance", TaskID: "task", Attempt: int64(r.Claim.Handle.Attempt), Fence: r.Claim.Handle.Fence, RequestID: "leftover", Name: "submit_review", Arguments: []byte(`{"decision":"reject"}`), Agent: r.Agent}
+ ctx := context.Background()
+ if err := s.journal.appendTool(ctx, sub, "hash"); err != nil {
+ t.Fatal(err)
+ }
+ if broken {
+ if _, err := s.journal.db.Exec("CREATE TRIGGER fail_ack BEFORE UPDATE ON journal_tools BEGIN SELECT RAISE(FAIL, 'ack failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ err := s.finishAttempt(ctx, r, nil)
+ if (err != nil) != broken {
+ t.Fatal("bookkeeping error not reported", err)
+ }
+ if slices.Contains(*order, "complete") {
+ t.Fatal("ACK bookkeeping flipped successful completion to failure")
+ }
+ if r.Phase != "contained" {
+ t.Fatal("bookkeeping stopped cleanup", r.Phase)
+ }
+ if !broken {
+ var outcome string
+ if err := s.journal.db.QueryRow("SELECT json_extract(body,'$.outcome') FROM journal_supervisor WHERE kind='tool-outcome'").Scan(&outcome); err != nil {
+ t.Fatal(err)
+ }
+ if outcome != "unprocessed" {
+ t.Fatal("unprocessed submission labelled", outcome)
+ }
+ }
+ })
+ }
+}
+
+func TestRunnerRestartDefinitiveAndUncertainCreation(t *testing.T) {
+ for _, kind := range []string{"agent", "workspace"} {
+ for _, definitive := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%s/definitive=%v", kind, definitive), func(t *testing.T) {
+ s, r, _, _ := cleanupFixture(t)
+ ctx := context.Background()
+ c := &creationRecoveryClient{cleanupClient: s.client.(*cleanupClient), recoveryErr: paseo.ErrCreationAbsent}
+ s.client = c
+ r.Claim.Assignment.WorkspaceKey = "workspace-key"
+ r.Agent = paseo.Agent{}
+ r.Owner.AgentID = ""
+ key := r.request("agent").RequestID
+ var req any = paseo.AgentRequest{ResourceID: "preassigned-agent", IdempotencyKey: key, Workspace: r.Owner.Workspace}
+ if kind == "workspace" {
+ key = r.Claim.Assignment.WorkspaceKey
+ r.Owner.Workspace = paseo.Workspace{Path: r.Owner.Workspace.Path}
+ r.Owner.LocalOnly = true
+ req = paseo.WorkspaceRequest{ResourceID: "preassigned-workspace", IdempotencyKey: key}
+ }
+ intent := paseo.Intent{Kind: kind, Key: key, RequestHash: "hash", Request: marshal(req)}
+ if err := s.journal.RecordIntent(ctx, intent); err != nil {
+ t.Fatal(err)
+ }
+ if definitive {
+ if err := s.journal.RecordCreationRefusal(ctx, intent); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := s.save(ctx, r); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.journal.Close(); err != nil {
+ t.Fatal(err)
+ }
+ j, err := OpenJournal(ctx, s.journal.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer j.Close()
+ s.journal = j
+ err = s.Recover(ctx)
+ if definitive {
+ if err != nil || !s.ready {
+ t.Fatal("definitive refusal blocks cleanup", err)
+ }
+ if c.lookups != 1 {
+ t.Fatal("missing complete creation lookup", c.lookups)
+ }
+ } else if err == nil || s.ready {
+ t.Fatal("uncertain creation allowed containment")
+ }
+ })
+ }
+ }
+}
+
+func TestRunnerCreationRefusalBindsIntent(t *testing.T) {
+ s, _, _, _ := cleanupFixture(t)
+ ctx := context.Background()
+ i := paseo.Intent{Kind: "agent", Key: "create", RequestHash: "exact-hash", Request: marshal(paseo.AgentRequest{ResourceID: "assigned-agent"})}
+ if err := s.journal.RecordIntent(ctx, i); err != nil {
+ t.Fatal(err)
+ }
+ wrong := i
+ wrong.RequestHash = "wrong-hash"
+ if s.journal.RecordCreationRefusal(ctx, wrong) == nil {
+ t.Fatal("refusal accepted for different request hash")
+ }
+ wrong = i
+ wrong.Request = marshal(paseo.AgentRequest{ResourceID: "other-agent"})
+ if s.journal.RecordCreationRefusal(ctx, wrong) == nil {
+ t.Fatal("refusal accepted for different resource")
+ }
+ if err := s.journal.RecordCreationRefusal(ctx, i); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.settleCreation(ctx, i.Kind, i.Key, paseo.ErrUncertain); err == nil {
+ t.Fatal("incomplete lookup settled refusal")
+ }
+}
diff --git a/internal/runner/supervisor_test.go b/internal/runner/supervisor_test.go
index 501d5636..433d4dd2 100644
--- a/internal/runner/supervisor_test.go
+++ b/internal/runner/supervisor_test.go
@@ -39,7 +39,8 @@ type cleanupInspector struct {
survivor, unknown bool
}
-func (p *cleanupInspector) Track(context.Context, ProcessOwner) error { return nil }
+func (p *cleanupInspector) Retire(context.Context, ProcessOwner) error { return nil }
+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()}
diff --git a/internal/runner/workflow_integration_test.go b/internal/runner/workflow_integration_test.go
index 6bb0af87..f98abbc1 100644
--- a/internal/runner/workflow_integration_test.go
+++ b/internal/runner/workflow_integration_test.go
@@ -196,7 +196,7 @@ func runBugWorkflowMode(t *testing.T, reject bool, failover string) {
}
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"}}})
+ 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, RecordCreationRefusal: j.RecordCreationRefusal, 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))
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go
index fd9f75e5..80993025 100644
--- a/internal/runnerproto/types.go
+++ b/internal/runnerproto/types.go
@@ -157,6 +157,7 @@ type RunnerBrief struct {
}
type ClaimResponse struct {
+ CleanupExpired bool `json:"cleanup_expired,omitempty"`
NotClaimed bool `json:"not_claimed,omitempty"`
AttemptDeadline time.Time `json:"attempt_deadline"`
Scope Scope `json:"scope"`
diff --git a/runner/paseo/bridge.mjs b/runner/paseo/bridge.mjs
index d728f555..4a8583a9 100644
--- a/runner/paseo/bridge.mjs
+++ b/runner/paseo/bridge.mjs
@@ -152,13 +152,16 @@ export class Bridge {
return { server_id: status.serverId, project_id: result.project.projectId, path: result.project.projectRootPath };
}
async createWorkspace(r) {
- keys(r, ['resource_id', 'project_id', 'path', 'base_commit', 'branch', 'idempotency_key', 'selection', 'read_policy', 'isolation']);
- if (r.isolation !== 'worktree') fail('invalid_request');
- allowedPath(r.path, r.read_policy);
- const status = await this.status();
- if (status.version !== VERSION) fail('unsupported_daemon_version');
- if (!text(r.project_id) || !text(r.idempotency_key) || !/^[a-f0-9]{40,64}$/.test(r.base_commit) || !text(r.branch)) fail('invalid_request');
- this.creationReceipts();
+ let status;
+ try {
+ keys(r, ['resource_id', 'project_id', 'path', 'base_commit', 'branch', 'idempotency_key', 'selection', 'read_policy', 'isolation']);
+ if (r.isolation !== 'worktree') fail('invalid_request');
+ allowedPath(r.path, r.read_policy);
+ status = await this.status();
+ if (status.version !== VERSION) fail('unsupported_daemon_version');
+ if (!text(r.project_id) || !text(r.idempotency_key) || !/^[a-f0-9]{40,64}$/.test(r.base_commit) || !text(r.branch)) fail('invalid_request');
+ this.creationReceipts();
+ } catch (error) { error.definitiveCreateFailure = true; throw error; }
const result = await this.client.createWorkspace({ workspaceId: r.resource_id, source: { kind: 'worktree', cwd: r.path, projectId: r.project_id, action: 'branch-off', refName: r.base_commit, branchName: r.branch }, idempotencyKey: r.idempotency_key });
if (result.error || !result.workspace) fail('uncertain');
const w = result.workspace;
@@ -171,18 +174,21 @@ export class Bridge {
return providerPolicy(selection.provider, status.version, read_policy);
}
async createAgent(r) {
- keys(r, ['resource_id', 'workspace', 'selection', 'idempotency_key', 'mode_id', 'read_policy', 'env', 'provider_options', 'mcp_servers']);
- const status = await this.status(r.workspace.server_id);
- allowedPath(r.workspace.path, r.read_policy);
- if (!text(r.workspace.workspace_id) || !text(r.idempotency_key) || r.mode_id !== 'default') fail('invalid_request');
- if (!isDeepStrictEqual(r.provider_options, providerPolicy(r.selection.provider, status.version, r.read_policy))) fail('policy_mismatch');
- validateEnv(r.env ?? {});
- if (!record(r.mcp_servers)) fail('invalid_mcp');
- for (const server of Object.values(r.mcp_servers)) {
- if (!record(server) || server.type !== 'stdio' || !text(server.command) || !isAbsolute(server.command) || !Array.isArray(server.args) || server.args.some(a => typeof a !== 'string')) fail('invalid_mcp');
- keys(server, ['type', 'command', 'args', 'env']); validateEnv(server.env ?? {});
- }
- this.creationReceipts();
+ let status;
+ try {
+ keys(r, ['resource_id', 'workspace', 'selection', 'idempotency_key', 'mode_id', 'read_policy', 'env', 'provider_options', 'mcp_servers']);
+ status = await this.status(r.workspace.server_id);
+ allowedPath(r.workspace.path, r.read_policy);
+ if (!text(r.workspace.workspace_id) || !text(r.idempotency_key) || r.mode_id !== 'default') fail('invalid_request');
+ if (!isDeepStrictEqual(r.provider_options, providerPolicy(r.selection.provider, status.version, r.read_policy))) fail('policy_mismatch');
+ validateEnv(r.env ?? {});
+ if (!record(r.mcp_servers)) fail('invalid_mcp');
+ for (const server of Object.values(r.mcp_servers)) {
+ if (!record(server) || server.type !== 'stdio' || !text(server.command) || !isAbsolute(server.command) || !Array.isArray(server.args) || server.args.some(a => typeof a !== 'string')) fail('invalid_mcp');
+ keys(server, ['type', 'command', 'args', 'env']); validateEnv(server.env ?? {});
+ }
+ this.creationReceipts();
+ } catch (error) { error.definitiveCreateFailure = true; throw error; }
const a = await this.client.createAgent({ agentId: r.resource_id, workspaceId: r.workspace.workspace_id, cwd: r.workspace.path, provider: r.selection.provider, model: r.selection.model, idempotencyKey: r.idempotency_key, modeId: r.mode_id, env: r.env ?? {}, providerOptions: r.provider_options, mcpServers: r.mcp_servers });
if ((r.resource_id && a.id !== r.resource_id) || !text(a.id) || a.workspaceId !== r.workspace.workspace_id || a.cwd !== r.workspace.path || a.provider !== r.selection.provider || a.model !== r.selection.model) fail('identity_mismatch');
return { server_id: status.serverId, agent_id: a.id, provider_session_id: a.runtimeInfo?.sessionId ?? a.persistence?.sessionId ?? '', workspace_id: a.workspaceId, account_id: '', provider: a.provider, model: a.model, family: r.selection.family };
@@ -190,14 +196,24 @@ export class Bridge {
async recoverWorkspace(r) {
if (!text(r.resource_id)) fail('uncertain');
const status = await this.status();
- const result = await this.client.fetchWorkspaces({ includeBackground: true, filter: { projectId: r.project_id, idPrefix: r.resource_id, includeInternal: true, includeBackground: true }, page: { limit: 10 } });
- if (!Array.isArray(result.entries)) fail('uncertain');
- const matches = result.entries.filter(w => w.id === r.resource_id);
- if (matches.length !== 1) fail('uncertain');
- const w = matches[0];
- if (w.projectId !== r.project_id || !text(w.workspaceDirectory)) fail('identity_mismatch');
- allowedPath(w.workspaceDirectory, r.read_policy);
- return { server_id: status.serverId, project_id: w.projectId, workspace_id: w.id, path: w.workspaceDirectory };
+ let cursor;
+ const seen = new Set();
+ for (let page = 0; page < 100; page++) {
+ const result = await this.client.fetchWorkspaces({ includeBackground: true, filter: { projectId: r.project_id, idPrefix: r.resource_id, includeInternal: true, includeBackground: true }, page: { limit: 10, ...(cursor ? { cursor } : {}) } });
+ if (result.error || !Array.isArray(result.entries)) fail('uncertain');
+ const matches = result.entries.filter(w => w.id === r.resource_id);
+ if (matches.length > 1) fail('identity_mismatch');
+ if (matches.length === 1) {
+ const w = matches[0];
+ if (w.projectId !== r.project_id || !text(w.workspaceDirectory)) fail('identity_mismatch');
+ allowedPath(w.workspaceDirectory, r.read_policy);
+ return { server_id: status.serverId, project_id: w.projectId, workspace_id: w.id, path: w.workspaceDirectory };
+ }
+ if (result.pageInfo?.hasMore === false) fail('creation_absent');
+ if (result.pageInfo?.hasMore !== true || !text(result.pageInfo.nextCursor) || seen.has(result.pageInfo.nextCursor)) fail('uncertain');
+ cursor = result.pageInfo.nextCursor; seen.add(cursor);
+ }
+ fail('uncertain');
}
async recoverAgent(r) {
if (!text(r.resource_id)) fail('uncertain');
@@ -206,7 +222,7 @@ export class Bridge {
const seen = new Set();
for (let page = 0; page < 100; page++) {
const result = await this.client.fetchAgents({ includeBackground: true, filter: { includeArchived: true, includeInternal: true, includeBackground: true }, page: { limit: 100, ...(cursor ? { cursor } : {}) } });
- if (!Array.isArray(result.entries)) fail('uncertain');
+ if (result.error || !Array.isArray(result.entries)) fail('uncertain');
const matches = result.entries.filter(e => e.agent?.id === r.resource_id);
if (matches.length > 1) fail('identity_mismatch');
if (matches.length === 1) {
@@ -214,7 +230,8 @@ export class Bridge {
if (a.workspaceId !== r.workspace.workspace_id || a.cwd !== r.workspace.path || a.provider !== r.selection.provider || a.model !== r.selection.model) fail('identity_mismatch');
return { server_id: status.serverId, agent_id: a.id, provider_session_id: a.runtimeInfo?.sessionId ?? a.persistence?.sessionId ?? '', workspace_id: a.workspaceId, account_id: '', provider: a.provider, model: a.model, family: r.selection.family };
}
- if (!result.pageInfo?.hasMore || !text(result.pageInfo.nextCursor) || seen.has(result.pageInfo.nextCursor)) fail('uncertain');
+ if (result.pageInfo?.hasMore === false) fail('creation_absent');
+ if (result.pageInfo?.hasMore !== true || !text(result.pageInfo.nextCursor) || seen.has(result.pageInfo.nextCursor)) fail('uncertain');
cursor = result.pageInfo.nextCursor; seen.add(cursor);
}
fail('uncertain');
@@ -358,7 +375,7 @@ function validateEnv(env) {
export async function run(input, output, diagnostic) {
let bridge, buffer = Buffer.alloc(0), stopped = false, connecting = false;
const pending = new Set();
- const codes = new Set(['creation_receipts_required', 'invalid_request', 'frame_too_large', 'invalid_event', 'local_daemon_required', 'wrong_server', 'daemon_credential_unavailable', 'unsupported_client_version', 'unsupported_daemon_version', 'unsupported_provider', 'invalid_mcp', 'invalid_env', 'policy_mismatch', 'identity_mismatch', 'uncertain', 'timeline_gap', 'subscription_not_ready', 'invalid_permission', 'unknown_permission']);
+ const codes = new Set(['creation_absent', 'creation_receipts_required', 'invalid_request', 'frame_too_large', 'invalid_event', 'local_daemon_required', 'wrong_server', 'daemon_credential_unavailable', 'unsupported_client_version', 'unsupported_daemon_version', 'unsupported_provider', 'invalid_mcp', 'invalid_env', 'policy_mismatch', 'identity_mismatch', 'uncertain', 'timeline_gap', 'subscription_not_ready', 'invalid_permission', 'unknown_permission']);
const write = value => {
if (stopped) return;
if (output.writableLength > MAX_FRAME * 8) fail('frame_too_large');
@@ -381,7 +398,7 @@ export async function run(input, output, diagnostic) {
}
write({ version: 1, type: 'result', id: q.id, result });
} catch (error) {
- const code = codes.has(error.message) ? error.message : 'uncertain';
+ const code = error.definitiveCreateFailure ? 'create_refused' : codes.has(error.message) ? error.message : 'uncertain';
diagnostic.write('paseo_bridge_error\n');
write({ version: 1, type: 'result', id: typeof q?.id === 'string' ? q.id : '', error: code, result: {} });
}
diff --git a/runner/paseo/bridge.test.mjs b/runner/paseo/bridge.test.mjs
index aec98259..ceba4517 100644
--- a/runner/paseo/bridge.test.mjs
+++ b/runner/paseo/bridge.test.mjs
@@ -339,7 +339,7 @@ test('recovery looks up preassigned IDs without creating resources', async () =>
assert.equal(w.workspace_id, workspace.workspace_id);
assert.equal(a.agent_id, agent.agent_id);
assert.equal(f.calls.filter(x => x[0] === 'create' || x[0] === 'workspace').length, 0);
- await assert.rejects(f.bridge.recoverWorkspace({ resource_id: 'other', project_id: workspace.project_id, read_policy: policy }), /uncertain/);
+ await assert.rejects(f.bridge.recoverWorkspace({ resource_id: 'other', project_id: workspace.project_id, read_policy: policy }), /creation_absent/);
});
test('creation sends preassigned resource IDs', async () => {
@@ -349,3 +349,39 @@ test('creation sends preassigned resource IDs', async () => {
await f.bridge.createWorkspace({ resource_id: workspace.workspace_id, project_id: workspace.project_id, path: workspace.path, base_commit: 'a'.repeat(40), branch: 'equipo/test', idempotency_key: 'workspace-intent', selection, read_policy: policy, isolation: 'worktree' });
assert.equal(f.calls.find(x => x[0] === 'workspace')[1].workspaceId, workspace.workspace_id);
});
+
+test('definitive create failures are only tagged before effects', async () => {
+ for (const field of ['mode_id', 'provider_options', 'mcp_servers']) {
+ const f = fake();
+ const r = request();
+ r[field] = null;
+ await assert.rejects(f.bridge.createAgent(r), e => e.definitiveCreateFailure === true);
+ assert.equal(f.calls.filter(x => x[0] === 'create').length, 0);
+ }
+ const f = fake();
+ await assert.rejects(f.bridge.createWorkspace({isolation:'none'}), e => e.definitiveCreateFailure === true);
+ f.daemon.createAgent = async () => { throw new Error('policy_mismatch'); };
+ await assert.rejects(f.bridge.createAgent(request()), e => !e.definitiveCreateFailure);
+ f.daemon.createWorkspace = async () => ({workspace:{id:workspace.workspace_id, projectId:workspace.project_id, workspaceDirectory:'/protected/path'}});
+ await assert.rejects(f.bridge.createWorkspace({ resource_id:workspace.workspace_id, project_id:workspace.project_id, path:workspace.path, base_commit:'a'.repeat(40), branch:'review', idempotency_key:'intent', selection, read_policy:policy, isolation:'worktree' }), e=>!e.definitiveCreateFailure);
+});
+
+test('creation absence requires a complete lookup', async () => {
+ const f = fake();
+ const w = {resource_id:'missing',project_id:workspace.project_id,read_policy:policy};
+ const a = {...request(),resource_id:'missing'};
+ for (const [method,fetch,r] of [['recoverAgent','fetchAgents',a],['recoverWorkspace','fetchWorkspaces',w]]) {
+ f.daemon[fetch] = async () => ({entries:[],pageInfo:{hasMore:false}});
+ await assert.rejects(f.bridge[method](r), /creation_absent/);
+ f.daemon[fetch] = async () => ({entries:[],pageInfo:{hasMore:false},error:'lookup failed'});
+ await assert.rejects(f.bridge[method](r), /uncertain/);
+ f.daemon[fetch] = async () => ({entries:[]});
+ await assert.rejects(f.bridge[method](r), /uncertain/);
+ f.daemon[fetch] = async () => ({entries:[],pageInfo:{hasMore:true}});
+ await assert.rejects(f.bridge[method](r), /uncertain/);
+ let calls=0;
+ f.daemon[fetch] = async () => (++calls===1 ? {entries:[],pageInfo:{hasMore:true,nextCursor:'next'}} : {entries:[],pageInfo:{hasMore:false}});
+ await assert.rejects(f.bridge[method](r), /creation_absent/);
+ assert.equal(calls,2);
+ }
+});