oficina / equipo Public

Mac slice F task 12 fix 1: preflight, paths, logs, turn, commit, keep

Astra round 1 (NOT READY, 8 Important), fixed tests-first:

1. The runtime copy's auth status ending ErrUnproven or ErrRecord ends
   the attempt unproven; ErrLoginRequired there fails over (auth).
2. gitleaks scans the changed files at their own paths (moved files'
   contents included), so filename rules fire; no path is logged.
3. The step log is redacted as written; a scan refusal removes the
   attempts' step logs and kept session; the sweep removes finished
   step logs.
4. Engineering readiness and the trusted Xcode proof are asked again in
   the held turn, before the auth status and before the step's launch.
5. committed, the outcome, the redacted final report and the kept
   session's candidate binding are one transaction; a restart returns
   that report.
6. A pack is served only for a retained candidate whose keep has not
   passed (lookup errors fail closed); the sweep runs at the next keep.
7. On a Mac, gitleaks runs in the sandboxed checks gate (srt with the
   checks profile P2 proves), only when P2's trusted verdict picks it.
8. Missing mutations run: owner, ValidHub, ValidTaskBranch, base,
   inbound header (both sites), scan bound; all killed.

Recorded exceptions (tests written after their code in round 0), each
backed by a killed mutation: TestWorkerEngineeringRefusesPacks (M10,
G5), TestWorkerEngineeringGatedPerLaunch (M15/R15),
TestWorkerUnfinishedOutcomeField (M17/R17),
TestWorkerEngineeringLostRecordUnproven (M19/R19), the forgotten-upload
case (F6a, R20), the wrong-base case (M14/R14).

Round 0's M10, M10b and M13 had died by build error; re-run compiling:
M10 and M13 killed; M10b's loop was dead code and is removed, as is a
redundant bound check (G6b).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 24a53f2eaa356f07006851cbdf0fe7f66c2eb2b1 parent 64e6432
14 files changed, +726 −106
  • .rastrillo/budgets.txt +1 −1
  • internal/fakeclaude/fake.go +14 −0
  • internal/runner/thin/ask.go +18 −0
  • internal/runner/thin/mac.go +13 −1
  • internal/runner/thin/preview_security.go +22 −7
  • internal/runner/thin/run.go +5 −10
  • internal/runner/thin/state.go +3 −2
  • internal/runner/thin/step.go +33 −17
  • internal/runner/thin/worker.go +3 −0
  • internal/runner/thin/worker_engineering.go +60 −21
  • internal/runner/thin/worker_engineering_test.go +326 −17
  • internal/runner/thin/worker_launch.go +53 −4
  • internal/runner/thin/worker_scan.go +127 −18
  • internal/runner/thin/worker_store.go +48 −8
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index b2991c65..20bae02c 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s;
-size internal/runner/thin 33020 29590 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, worker Engineering; measured 33020/29590.
+size internal/runner/thin 33317 29899 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials, worker conns, worker Engineering; measured 33317/29899.
time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes.
time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s).
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index 4fa7568a..a0b223b7 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -71,6 +71,7 @@
// asks for Write and writes the decoded bytes (a binary file);
// "symlink:<path>|<target>" asks for Write and makes a symbolic link;
// "say:<text>" (to ";" or the line's end) adds the text to the reply;
+// "move:<from>|<to>" asks for Write on <to> and renames the file;
// with "steplimit:<email>", "limitleave:<path>" writes the file before
// the refusal (a refused attempt that changed its tree). On a darwin
// launch (it pins the project directory) the workspace is the CLI's own
@@ -573,6 +574,7 @@ var stepSleep = regexp.MustCompile(`stepsleep:([0-9]+)`)
var bytesWord = regexp.MustCompile(`bytes:([^|\s]+)\|([A-Za-z0-9+/=]+)`)
var symlinkWord = regexp.MustCompile(`symlink:([^|\s]+)\|([^;\s]+)`)
var sayWord = regexp.MustCompile(`say:([^;\n]*)`)
+var moveWord = regexp.MustCompile(`move:([^|\s]+)\|([^;\s]+)`)
var limitLeave = regexp.MustCompile(`limitleave:([^;\s]+)`)
// workspaceRoot is the workspace the model's paths name: /workspace in
@@ -736,6 +738,18 @@ func (f *fake) engineer(prompt string, turn int, emit func(any)) string {
}
done = append(done, "Linked "+rel+".")
}
+ for i, m := range moveWord.FindAllStringSubmatch(prompt, -1) {
+ from, to := filepath.Clean("/" + m[1])[1:], filepath.Clean("/" + m[2])[1:]
+ if !ask(800+i, "Write", map[string]any{"file_path": filepath.Join(root, to), "content": "(moved)"}) {
+ done = append(done, "Write of "+to+" was denied.")
+ continue
+ }
+ if os.MkdirAll(filepath.Dir(to), 0755) != nil || os.Rename(from, to) != nil {
+ done = append(done, "Could not move "+from+".")
+ continue
+ }
+ done = append(done, "Moved "+from+" to "+to+".")
+ }
for _, m := range sayWord.FindAllStringSubmatch(prompt, -1) {
done = append(done, strings.TrimSpace(m[1]))
}
diff --git a/internal/runner/thin/ask.go b/internal/runner/thin/ask.go
index 829a0f6c..b3582b08 100644
--- a/internal/runner/thin/ask.go
+++ b/internal/runner/thin/ask.go
@@ -61,6 +61,24 @@ func (s *State) keepSession(ctx context.Context, r stepRow, specialist, account,
return err
}
+// dropKept forgets an attempt's kept session, returning its directory
+// ("" for none).
+func (s *State) dropKept(ctx context.Context, r stepRow) (string, error) {
+ var dir string
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ err := t.QueryRow("SELECT dir FROM kept_sessions WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&dir)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ _, err = t.Exec("DELETE FROM kept_sessions WHERE step_id=? AND attempt=?", r.StepID, r.Attempt)
+ return err
+ })
+ return dir, err
+}
+
// setKeptCandidate records the commit an Engineering step made, once made.
func (s *State) setKeptCandidate(ctx context.Context, r stepRow, sha string) error {
_, err := s.db.ExecContext(ctx, "UPDATE kept_sessions SET candidate_sha=? WHERE step_id=? AND attempt=?", sha, r.StepID, r.Attempt)
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go
index 8faa9342..69c28aa4 100644
--- a/internal/runner/thin/mac.go
+++ b/internal/runner/thin/mac.go
@@ -793,7 +793,7 @@ func (h *macHost) engineering() *WorkerEngineering {
dev = v
}
}
- return &WorkerEngineering{XcodeExec: &mac.Executor{Turns: h.turns, UserTemp: h.paths.UserTemp, QuietSimulators: h.quietSimulators}, DeveloperDir: dev,
+ return &WorkerEngineering{XcodeExec: &mac.Executor{Turns: h.turns, UserTemp: h.paths.UserTemp, QuietSimulators: h.quietSimulators}, DeveloperDir: dev, Leaks: h.leaks,
Xcode: func() bool {
r, ok := h.probes.trusted()
return ok && r.Sandboxed() && r.Probe("F5").Verdict == wire.ProbeDenied && h.paths.UserTemp != "" && !h.taint.Tainted()
@@ -1043,3 +1043,15 @@ func fetchLimited(ctx context.Context, url string, limit int64) ([]byte, error)
}
return b, nil
}
+
+// leaks scans stage with the pinned gitleaks beside the runner, in the
+// Mac's checks gate, and only in the sandboxed one: the gate that P2's
+// trusted verdict picks for checks, on a runner never tainted. Anything
+// else cannot confine it, so it cannot scan and nothing leaves.
+func (h *macHost) leaks(ctx context.Context, stage, marker string, record func(string) error) (bool, error) {
+ if g := h.checks.pick(); g != h.checks.sandboxed {
+ return false, errScanner
+ }
+ binary, pin := previewScannerTool(runner.Config{Executable: filepath.Join(h.paths.InstallDir, "equipo-runner")})
+ return gateLeaks(ctx, h.checks.sandboxed, binary, pin, stage, marker, record)
+}
diff --git a/internal/runner/thin/preview_security.go b/internal/runner/thin/preview_security.go
index b3a850e9..f23b4e6c 100644
--- a/internal/runner/thin/preview_security.go
+++ b/internal/runner/thin/preview_security.go
@@ -128,6 +128,20 @@ func (e *Engineer) gitleaks(ctx context.Context, stage string) (bool, error) {
if clipped || scanCtx.Err() != nil {
return false, errScanner
}
+ found, err := readFindings(report)
+ if err != nil || found {
+ return found, err
+ }
+ if scanErr != nil {
+ return false, errScanner
+ }
+ return false, nil
+}
+
+// readFindings reads a gitleaks report for whether it has any finding;
+// errScanner when it is missing, too large or not a report. No
+// finding's text is kept.
+func readFindings(report string) (bool, error) {
info, err := os.Stat(report)
if err != nil || !info.Mode().IsRegular() || info.Size() > 2<<20 {
return false, errScanner
@@ -137,13 +151,14 @@ func (e *Engineer) gitleaks(ctx context.Context, stage string) (bool, error) {
if err != nil || json.Unmarshal(raw, &findings) != nil || findings == nil {
return false, errScanner
}
- if len(findings) > 0 {
- return true, nil
- }
- if scanErr != nil {
- return false, errScanner
- }
- return false, nil
+ return len(findings) > 0, nil
+}
+
+// workerLeaks is the worker's scanner off a Mac (the test build's fake
+// worker on Linux): the preview scanner's bubblewrap; marker and record
+// are not needed there.
+func (e *Engineer) workerLeaks(ctx context.Context, stage, _ string, _ func(string) error) (bool, error) {
+ return e.gitleaks(ctx, stage)
}
type previewRefusalError struct{ reason string }
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index 029d7d9e..8adb2256 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -790,7 +790,10 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl
worker := &Worker{State: state, Engine: engineer, Gate: w.gate, MaxStep: o.MaxStep, StepRoot: filepath.Join(c.ScratchRoot, "worker-steps"), Find: w.find, Ready: w.ready}
if w.engineering != nil && w.creds != nil && own != nil {
eng := *w.engineering
- eng.Creds, eng.Leaks = w.creds, engineer.gitleaks
+ eng.Creds = w.creds
+ if eng.Leaks == nil {
+ eng.Leaks = engineer.workerLeaks
+ }
// The status the capability report says now: until every part of
// it is ready (task 14 composes it), no Engineering runs here.
eng.Status = func(ctx context.Context) *wire.EngineeringStatus { return caps.Get(ctx).Engineering }
@@ -824,15 +827,7 @@ func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Pl
}
tags := func() []string { return caps.Get(ctx).Tags }
steps := &StepEngine{State: state, Exec: placementGuard(tags, caps.Stale, worker.Exec), Notify: link.Notify, Logger: o.Logger,
- Sweep: func(ctx context.Context) {
- keys, err := state.finishedSteps(ctx)
- if err == nil {
- for _, r := range keys {
- _ = os.RemoveAll(filepath.Join(worker.stepsDir(), stepKey(r)))
- }
- }
- worker.sweep(ctx)
- },
+ Sweep: worker.sweep,
Verify: func(_ context.Context, id string) bool { return w.gate.Verify(workerRecord(id)) }, TerminationKind: wire.TerminationProcessGroup}
link.Steps = steps
if err := steps.Start(ctx); err != nil {
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index f1952bd1..9c41bf06 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -102,8 +102,9 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
// outcome: what a worker's Engineering commit is (wire.Outcome*), kept
- // apart from its progress phase (Mac runners slice F).
- for _, col := range []string{"ns_id", "final_state", "final_reason", "not_before", "deferred_since", "outcome"} {
+ // apart from its progress phase, and worker_report the final report a
+ // restart sends again (Mac runners slice F).
+ for _, col := range []string{"ns_id", "final_state", "final_reason", "not_before", "deferred_since", "outcome", "worker_report"} {
if _, err = d.ExecContext(ctx, "ALTER TABLE steps ADD COLUMN "+col+" TEXT NOT NULL DEFAULT ''"); err != nil && !strings.Contains(err.Error(), "duplicate column") {
d.Close()
return nil, err
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go
index b38a3542..f3f1c01b 100644
--- a/internal/runner/thin/step.go
+++ b/internal/runner/thin/step.go
@@ -215,29 +215,45 @@ func (s *State) setStepPhase(ctx context.Context, r stepRow, phase, base, candid
}
// setWorkerCommitted records a worker's Engineering attempt committed,
-// durably: progress phase committed (only the upload is left), its base
-// and candidate, and the commit's outcome in its own field. Only a
-// candidate whose scan passed is recorded so, and only such a one is
-// uploaded (Worker.candidatePack).
-func (s *State) setWorkerCommitted(ctx context.Context, r stepRow, base, candidate, outcome string) error {
- res, err := s.db.ExecContext(ctx, "UPDATE steps SET phase=?, base_sha=?, candidate_sha=?, outcome=? WHERE step_id=? AND attempt=? AND state=?", phaseCommitted, base, candidate, outcome, r.StepID, r.Attempt, runRunning)
+// durably and in one transaction: progress phase committed (only the
+// upload is left), its base and candidate, the commit's outcome in its
+// own field, the final report a restart sends again (redacted already),
+// and, when the attempt kept its session, that session's binding to the
+// candidate. Only a candidate whose scan passed is recorded so, and only
+// such a one is uploaded (Worker.candidatePack).
+func (s *State) setWorkerCommitted(ctx context.Context, r stepRow, base, candidate, outcome string, final wire.StepReport, kept bool) error {
+ raw, err := json.Marshal(final)
if err != nil {
return err
}
- if n, _ := res.RowsAffected(); n != 1 {
- return errors.New("step not held")
- }
- return nil
+ return s.tx(ctx, func(t *sql.Tx) error {
+ res, err := t.Exec("UPDATE steps SET phase=?, base_sha=?, candidate_sha=?, outcome=?, worker_report=? WHERE step_id=? AND attempt=? AND state=?", phaseCommitted, base, candidate, outcome, string(raw), r.StepID, r.Attempt, runRunning)
+ if err != nil {
+ return err
+ }
+ if n, _ := res.RowsAffected(); n != 1 {
+ return errors.New("step not held")
+ }
+ if kept {
+ _, err = t.Exec("UPDATE kept_sessions SET candidate_sha=? WHERE step_id=? AND attempt=?", candidate, r.StepID, r.Attempt)
+ }
+ return err
+ })
}
-// stepOutcome is a worker attempt's recorded outcome ("" for none).
-func (s *State) stepOutcome(ctx context.Context, stepID string, attempt int64) (string, error) {
- var outcome string
- err := s.db.QueryRowContext(ctx, "SELECT outcome FROM steps WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&outcome)
- if errors.Is(err, sql.ErrNoRows) {
- return "", nil
+// workerCommitted is a worker attempt's recorded outcome and final
+// report ("" outcome for none).
+func (s *State) workerCommitted(ctx context.Context, stepID string, attempt int64) (string, wire.StepReport, error) {
+ var outcome, raw string
+ var rep wire.StepReport
+ err := s.db.QueryRowContext(ctx, "SELECT outcome, worker_report FROM steps WHERE step_id=? AND attempt=?", stepID, attempt).Scan(&outcome, &raw)
+ if errors.Is(err, sql.ErrNoRows) || err == nil && outcome == "" {
+ return "", rep, nil
+ }
+ if err != nil {
+ return "", rep, err
}
- return outcome, err
+ return outcome, rep, json.Unmarshal([]byte(raw), &rep)
}
// ReportStep queues a step report. A final one (done, failed, cancelled)
diff --git a/internal/runner/thin/worker.go b/internal/runner/thin/worker.go
index 379af4e7..ce7699b2 100644
--- a/internal/runner/thin/worker.go
+++ b/internal/runner/thin/worker.go
@@ -76,6 +76,9 @@ type Worker struct {
// attempt waiting for Ready does not hold it.
mu sync.Mutex
marker string
+ // sweepTimer runs the sweep at the next candidate keep's end.
+ sweepMu sync.Mutex
+ sweepTimer *time.Timer
}
// hold waits until no attempt runs and keeps the next one from starting
diff --git a/internal/runner/thin/worker_engineering.go b/internal/runner/thin/worker_engineering.go
index 58fb16ea..4f5402aa 100644
--- a/internal/runner/thin/worker_engineering.go
+++ b/internal/runner/thin/worker_engineering.go
@@ -14,6 +14,7 @@ import (
"amadan.net/oficina/equipo/internal/runner"
"amadan.net/oficina/equipo/internal/runner/checks"
"amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/runner/provider/claude"
"amadan.net/oficina/equipo/internal/runner/workspace"
"amadan.net/oficina/equipo/internal/wire"
@@ -53,12 +54,20 @@ type WorkerEngineering struct {
// Secrets are the worker's known secrets now: every connection's
// token, its runner credential, the seal key's private half.
Secrets func(context.Context) ([]string, error)
- // Leaks runs the pinned gitleaks over a directory, offline and
- // confined: whether it found a secret, or an error when it could not
- // tell.
- Leaks func(ctx context.Context, dir string) (bool, error)
+ // Leaks runs the pinned gitleaks over a directory of changed files,
+ // offline and confined (on a Mac, the checks gate: srt under the
+ // profile P2 proves), recording its process as marker: whether it
+ // found a secret, or an error when it could not tell
+ // (errScanUnproven when its end is not proven).
+ Leaks func(ctx context.Context, dir, marker string, record func(string) error) (bool, error)
+ // refresh, in tests, stands in for the runtime copy's auth status.
+ refresh func(context.Context, provider.Binding) (provider.Identity, error)
}
+// workerFault, in tests, stops an attempt at a named point ("retained",
+// "committed") as a crash there would.
+var workerFault func(point string) bool
+
// refName is a task or step id a ref may carry whole.
var refName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
@@ -197,9 +206,11 @@ func (w *Worker) engineering(ctx context.Context, r stepRow, progress func(wire.
os.RemoveAll(d)
}
}()
+ // keys are the attempts this run went through (a failover moves on).
+ var keys []stepRow
attemptDir := func() string {
d := filepath.Join(w.stepsDir(), stepKey(r))
- dirs = append(dirs, d)
+ dirs, keys = append(dirs, d), append(keys, r)
return d
}
if err := w.indexEngineering(ctx, store, attemptDir(), pack, want); err != nil {
@@ -267,7 +278,7 @@ func (w *Worker) engineering(ctx context.Context, r stepRow, progress func(wire.
if resume {
spec.prompt, spec.resume, spec.from = handoff.with(e.fixPrompt(r, tree.Dir), e.Note), prior.SessionID, prior.Dir
}
- res = w.launch(ctx, r, tree, spec, marker)
+ res = w.launch(ctx, r, tree, spec, marker, known)
if resume && res.reason == "session_gone" && res.terminated {
resumable = false
continue
@@ -342,28 +353,53 @@ func (w *Worker) engineering(ctx context.Context, r stepRow, progress func(wire.
e.log("worker retain", err)
return fail("workspace_refused", true)
}
+ if workerFault != nil && workerFault("retained") {
+ return wire.StepReport{}
+ }
// The scan, before anything leaves. A hit, a scanner that could not
// tell, an object past the bound or a list that cannot be read: the
// step ends secret_in_candidate, the ref goes, and nothing names the
// object but its id and kind (a file name can be the secret).
- if hit := w.scan(ctx, store, filepath.Join(w.stepsDir(), stepKey(r)), base, sha, known); hit != nil {
+ if hit := w.scan(ctx, store, filepath.Join(w.stepsDir(), stepKey(r)), base, sha, known, func(id string) error {
+ return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id)
+ }); hit != nil {
if e.O.Logger != nil {
e.O.Logger.Warn("secret in candidate: nothing uploaded", "object", hit.object, "kind", hit.kind)
}
e.log("worker candidate ref", w.dropCandidate(context.WithoutCancel(ctx), r.Repo, ref))
- rep.Headline, rep.Summary, rep.LogTail, rep.Apple = "", "", "", false
- return fail(wire.ReasonSecretInCandidate, true)
- }
- if err := w.State.setWorkerCommitted(ctx, r, base, sha, outcome); err != nil {
+ // What names its files goes too: the step logs and the session
+ // of the attempts that made it.
+ w.discard(context.WithoutCancel(ctx), keys)
+ rep.Headline, rep.Summary, rep.LogTail, rep.Apple, rep.SessionID = "", "", "", false, ""
+ return fail(wire.ReasonSecretInCandidate, !hit.unproven)
+ }
+ rep.CandidateSHA, rep.Phase, rep.OutcomePhase, rep.Askable = sha, wire.OutcomeCommitted, outcome, kept
+ final := redactReport(workerDone(rep, outcome), known)
+ // One transition: committed, the outcome, the final report a restart
+ // sends, and the kept session's binding to the candidate.
+ if err := w.State.setWorkerCommitted(ctx, r, base, sha, outcome, final, kept); err != nil {
return fail("provider_failed", true)
}
- if kept {
- e.log("kept sessions", w.State.setKeptCandidate(context.WithoutCancel(ctx), r, sha))
+ if workerFault != nil && workerFault("committed") {
+ return wire.StepReport{}
}
- rep.CandidateSHA, rep.Phase, rep.OutcomePhase = sha, wire.OutcomeCommitted, outcome
+ rep.Askable = false
say(rep)
- rep.Askable = kept
- return workerDone(rep, outcome)
+ return final
+}
+
+// discard removes the step logs of the attempts keys name and their kept
+// sessions (a refused candidate's: they name its files).
+func (w *Worker) discard(ctx context.Context, rows []stepRow) {
+ e := w.Engine
+ for _, r := range rows {
+ e.log("worker step log", os.RemoveAll(filepath.Join(e.root(), stepKey(r))))
+ dir, err := w.State.dropKept(ctx, r)
+ e.log("kept sessions", err)
+ if dir != "" {
+ e.log("kept sessions", e.removeKept(dir))
+ }
+ }
}
// workerDone is a committed attempt's final report: done, never pushed
@@ -386,13 +422,16 @@ func workerDone(rep wire.StepReport, outcome string) wire.StepReport {
// committed report again (a crash may have lost it) and done; the relay
// answers the upload from the store.
func (w *Worker) committedEngineering(ctx context.Context, r stepRow, rep wire.StepReport, say func(wire.StepReport)) wire.StepReport {
- outcome, err := w.State.stepOutcome(ctx, r.StepID, r.Attempt)
- if err != nil || outcome == "" || !wire.ValidCommitSHA(r.Candidate) {
+ outcome, final, err := w.State.workerCommitted(ctx, r.StepID, r.Attempt)
+ if err != nil || outcome == "" || !wire.ValidCommitSHA(r.Candidate) || final.CandidateSHA != r.Candidate {
w.Engine.log("worker resume", errors.Join(err, errors.New("no recorded outcome")))
rep.State, rep.Reason, rep.Termination = wire.StepFailed, "candidate_unavailable", true
return rep
}
- rep.BaseSHA, rep.CandidateSHA, rep.Phase, rep.OutcomePhase = r.Base, r.Candidate, wire.OutcomeCommitted, outcome
- say(rep)
- return workerDone(rep, outcome)
+ // The committed report again (a crash may have lost it), then the
+ // final report as the attempt made it.
+ committed := final
+ committed.State, committed.Reason, committed.Phase, committed.OutcomePhase, committed.Askable = "", "", wire.OutcomeCommitted, outcome, false
+ say(committed)
+ return final
}
diff --git a/internal/runner/thin/worker_engineering_test.go b/internal/runner/thin/worker_engineering_test.go
index c482b3a0..93fc665e 100644
--- a/internal/runner/thin/worker_engineering_test.go
+++ b/internal/runner/thin/worker_engineering_test.go
@@ -16,11 +16,15 @@ import (
"path/filepath"
"strings"
"sync"
+ "sync/atomic"
+ "syscall"
"testing"
"time"
"amadan.net/oficina/equipo/internal/fakeclaude"
"amadan.net/oficina/equipo/internal/runner"
+ "amadan.net/oficina/equipo/internal/runner/mac"
+ "amadan.net/oficina/equipo/internal/runner/provider"
"amadan.net/oficina/equipo/internal/wire"
)
@@ -41,16 +45,20 @@ type engRig struct {
w *Worker
relay *Relay
r stepRow
- // tokens are the connections' tokens, in the order they were pasted.
- tokens []string
- mu sync.Mutex
- said []wire.StepReport
- opened int
+ // tokens are the connections' tokens, in the order they were pasted,
+ // and homes their dedicated homes.
+ tokens, homes []string
+ mu sync.Mutex
+ said []wire.StepReport
+ opened int
// noUpload: the instance does not ask for the upload (yet).
noUpload bool
}
-func newEngRig(t *testing.T, emails ...string) *engRig {
+func newEngRig(t *testing.T, emails ...string) *engRig { return newEngRigWith(t, nil, emails...) }
+
+// newEngRigWith is the rig whose base also holds the files before.
+func newEngRigWith(t *testing.T, before map[string]string, emails ...string) *engRig {
t.Helper()
asLaunch(t, true)
if len(emails) == 0 {
@@ -65,8 +73,9 @@ func newEngRig(t *testing.T, emails ...string) *engRig {
home, _ := d.paste(c, id, token)
d.healthy(id, home, token, email)
x.tokens = append(x.tokens, token)
+ x.homes = append(x.homes, home)
}
- x.pri = newRelayRig(t)
+ x.pri = newRelayRigFiles(t, before, nil, nil)
x.pri.e.Owners = []string{connPerson}
// The pinned gitleaks beside the runner binary, as on a Mac.
scanner := filepath.Join(filepath.Dir(previewScannerFixture(t)), "gitleaks")
@@ -87,7 +96,7 @@ func newEngRig(t *testing.T, emails ...string) *engRig {
},
Xcode: func() bool { return false },
Secrets: func(context.Context) ([]string, error) { return workerSecrets(d.cfg, engBearer) },
- Leaks: e.gitleaks}}
+ Leaks: e.workerLeaks}}
x.relay = &Relay{State: d.state, Engine: e, Worker: x.w}
x.r = x.dispatch("s1", x.pri.base, "Swipe back")
return x
@@ -289,8 +298,8 @@ func (x *engRig) moveMain(t *testing.T, file, text string) string {
return gitOut(t, work, "rev-parse", "HEAD")
}
-// clean fails if any frame the worker queued, or its log, holds one of
-// words (raw, or in base64).
+// clean fails if any frame the worker queued, its log, or a step log it
+// keeps on disk (<state>/steps) holds one of words (raw, or in base64).
func (x *engRig) clean(t *testing.T, words ...string) {
t.Helper()
var all bytes.Buffer
@@ -298,6 +307,13 @@ func (x *engRig) clean(t *testing.T, words ...string) {
all.Write(f.Data)
}
all.WriteString(x.logs.String())
+ _ = filepath.WalkDir(x.w.Engine.root(), func(path string, d os.DirEntry, err error) error {
+ if err == nil && !d.IsDir() {
+ raw, _ := os.ReadFile(path)
+ all.Write(raw)
+ }
+ return nil
+ })
for _, w := range words {
for _, form := range []string{w, base64.StdEncoding.EncodeToString([]byte(w))} {
if strings.Contains(all.String(), form) {
@@ -523,7 +539,12 @@ func TestWorkerObjectScan(t *testing.T) {
note string
names []string
before func(*testing.T, *engRig)
+ // base: files the base already holds; kind: the diagnostic's kind.
+ base map[string]string
+ kind string
}{
+ "gitleaks by file name": {note: "create:nuget.config|<configuration><packageSourceCredentials><feed><add key=\"Username\" value=\"me\" /><add key=\"ClearTextPassword\" value=\"Xk9pQ2vR7sLm4TzWq8Ny\" /></feed></packageSourceCredentials></configuration>", names: []string{"nuget.config"}, kind: "gitleaks"},
+ "gitleaks in a renamed file": {base: map[string]string{"old-settings.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, note: "move:old-settings.txt|moved-settings.txt", names: []string{"moved-settings.txt"}, kind: "gitleaks"},
"raw in a text file": {note: "create:notes.txt|key " + token, names: []string{"notes.txt"}},
"base64 in a binary file": {note: "bytes:blob.bin|" + base64.StdEncoding.EncodeToString(binary), names: []string{"blob.bin"}},
"in a file name": {note: "create:" + token + ".txt|hello"},
@@ -544,14 +565,14 @@ func TestWorkerObjectScan(t *testing.T) {
previewScannerTool = func(c runner.Config) (string, string) { return script, hex.EncodeToString(sum[:]) }
t.Cleanup(func() { previewScannerTool = old })
}},
- "an object past the bound": {note: "edit:Swipe.swift|false|true", before: func(t *testing.T, x *engRig) {
+ "an object past the bound": {note: "edit:Swipe.swift|false|true", kind: "too_large", before: func(t *testing.T, x *engRig) {
old := workerScanBound
workerScanBound = 64
t.Cleanup(func() { workerScanBound = old })
}},
} {
t.Run(name, func(t *testing.T) {
- x := newEngRig(t)
+ x := newEngRigWith(t, c.base)
if c.before != nil {
c.before(t, x)
}
@@ -572,8 +593,15 @@ func TestWorkerObjectScan(t *testing.T) {
t.Fatalf("the refused candidate is pinned: %s", refs)
}
x.clean(t, append([]string{token, engBearer, hex.EncodeToString([]byte(token))}, c.names...)...)
- if !strings.Contains(x.logs.String(), "secret in candidate") {
- t.Fatalf("no diagnostic: %s", x.logs.String())
+ if !strings.Contains(x.logs.String(), "secret in candidate") || c.kind != "" && !strings.Contains(x.logs.String(), "kind="+c.kind) {
+ t.Fatalf("no diagnostic (kind %q): %s", c.kind, x.logs.String())
+ }
+ // The step log, which names files, is gone; so is the session.
+ if _, err := os.Stat(filepath.Join(x.w.Engine.root(), stepKey(x.r), "log.jsonl")); !os.IsNotExist(err) {
+ t.Fatalf("the refused attempt's step log stayed: %v", err)
+ }
+ if n := x.keptRows(t); n != 0 {
+ t.Fatalf("%d kept sessions of a refused attempt", n)
}
})
}
@@ -632,6 +660,23 @@ func TestWorkerCandidateRetained(t *testing.T) {
if blobs := x.uploaded(t, x.sendPack(t, wrong)); len(blobs) != 0 {
t.Fatal("a pack on another base was uploaded")
}
+ // A ref that no longer pins the candidate: nothing goes.
+ if _, err := x.store(t, "update-ref", candidateRef(x.r), x.pri.base); err != nil {
+ t.Fatal(err)
+ }
+ if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
+ t.Fatal("uploaded what its ref no longer pins")
+ }
+ if _, err := x.store(t, "update-ref", candidateRef(x.r), cand); err != nil {
+ t.Fatal(err)
+ }
+ // A retention record that cannot be read: nothing goes.
+ if _, err := x.state.db.Exec("ALTER TABLE candidates RENAME TO candidates_gone"); err != nil {
+ t.Fatal(err)
+ }
+ if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
+ t.Fatal("uploaded without its retention record")
+ }
}
// forget_task: with no KeepUntil the candidate's ref and the kept
@@ -669,12 +714,30 @@ func TestWorkerForgetTask(t *testing.T) {
}
return
}
- x.w.sweep(ctx)
if gone() {
t.Fatal("forgotten before its keep")
}
+ // Past its keep with nothing swept yet (a runner that was down at
+ // the deadline): the ref is still there, and nothing goes.
+ if _, err := x.state.db.Exec("UPDATE candidates SET expires_at=?", stamp(time.Now().Add(-time.Second))); err != nil {
+ t.Fatal(err)
+ }
+ if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
+ t.Fatal("a candidate past its keep, not yet swept, was uploaded")
+ }
+ if _, err := x.store(t, "rev-parse", "--verify", candidateRef(x.r)); err != nil {
+ t.Fatal("the ref went before the sweep: the case shows nothing")
+ }
time.Sleep(1100 * time.Millisecond)
- x.w.sweep(ctx)
+ // Past its keep, never uploaded again, sweep or not.
+ if blobs := x.uploaded(t, x.sendPack(t, x.committed())); len(blobs) != 0 {
+ t.Fatal("a candidate past its keep was uploaded")
+ }
+ // The cleanup was scheduled at the deadline: nobody sweeps here.
+ deadline := time.Now().Add(5 * time.Second)
+ for !gone() && time.Now().Before(deadline) {
+ time.Sleep(100 * time.Millisecond)
+ }
if !gone() {
t.Fatal("kept past its keep")
}
@@ -714,6 +777,9 @@ func TestWorkerEngineeringRestartAfterCommit(t *testing.T) {
if c := x.committed(); c.CandidateSHA != cand || c.OutcomePhase != wire.OutcomeCommitted {
t.Fatalf("committed again %+v", c)
}
+ if again.SessionID == "" || again.SessionID != rep.SessionID || !again.Askable || again.Apple != rep.Apple || again.Summary != rep.Summary || again.Headline != rep.Headline {
+ t.Fatalf("resumed without the attempt's report: %+v, was %+v", again, rep)
+ }
if pub := x.publish(t, x.uploaded(t, fmt.Sprintf("out-s1-%d", x.opened)), cand); !pub.Pushed {
t.Fatalf("published %+v", pub)
}
@@ -875,7 +941,7 @@ func TestWorkerUnfinishedOutcomeField(t *testing.T) {
if err := x.state.AcceptDispatch(ctx, "d-u", x.r.DispatchCommand); err != nil {
t.Fatal(err)
}
- if err := x.state.setWorkerCommitted(ctx, x.r, x.pri.base, cand, wire.OutcomeUnfinished); err != nil {
+ if err := x.state.setWorkerCommitted(ctx, x.r, x.pri.base, cand, wire.OutcomeUnfinished, wire.StepReport{}, false); err != nil {
t.Fatal(err)
}
var phase string
@@ -919,3 +985,246 @@ func TestWorkerEngineeringLostRecordUnproven(t *testing.T) {
t.Fatalf("report %+v, %d launches", rep, x.steps()-before)
}
}
+
+// keptRows counts the worker's kept sessions.
+func (x *engRig) keptRows(t *testing.T) int {
+ t.Helper()
+ var n int
+ if err := x.state.db.QueryRow("SELECT count(*) FROM kept_sessions").Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+// authLaunches counts the CLI's auth status reads so far.
+func (x *engRig) authLaunches() int {
+ n := 0
+ for _, l := range x.launches() {
+ if strings.HasPrefix(l.argv, "auth status") {
+ n++
+ }
+ }
+ return n
+}
+
+// Fix round 1, #1: the runtime copy's auth status can end unproven; the
+// attempt then ends unproven too, never terminated.
+func TestWorkerEngineeringPreflightUnproven(t *testing.T) {
+ x := newEngRig(t)
+ x.note("edit:Swipe.swift|false|true")
+ // The next auth status leaves a child that outlives a short settle.
+ if err := os.WriteFile(filepath.Join(x.dir, "linger"), []byte("auth"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ x.m.exec.Settle = 300 * time.Millisecond
+ before := x.steps()
+ rep := x.run(t)
+ if rep.State != wire.StepFailed || rep.Termination || x.steps() != before {
+ t.Fatalf("report %+v, %d launches", rep, x.steps()-before)
+ }
+ if pid := waitPid(t, filepath.Join(x.dir, "linger.pid")); pid > 0 {
+ _ = syscall.Kill(pid, syscall.SIGKILL)
+ }
+}
+
+// Fix round 1, #1: an auth status that says sign in again fails over to
+// the next connection, as a refusal of the step's own run does.
+func TestWorkerEngineeringPreflightSignInFailsOver(t *testing.T) {
+ x := newEngRig(t, "a@example.com", "b@example.com")
+ x.note("edit:Swipe.swift|false|true")
+ first := filepath.Base(x.homes[0])
+ x.w.Eng.refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
+ if filepath.Base(b.Home) == first || strings.Contains(b.Home, first) {
+ return provider.Identity{}, provider.ErrLoginRequired
+ }
+ return x.m.authStatus(ctx, b)
+ }
+ rep := x.run(t)
+ if rep.State != wire.StepDone || rep.Attempt != 2 || rep.Switched == nil || rep.CandidateSHA == "" {
+ t.Fatalf("report %+v", rep)
+ }
+}
+
+// Fix round 1, #4: readiness and the Xcode proof are asked again inside
+// the held turn: a proof lost while the attempt waited for the turn
+// launches nothing, not even the auth status.
+func TestWorkerEngineeringReadinessInTheTurn(t *testing.T) {
+ for _, xcode := range []bool{false, true} {
+ t.Run(fmt.Sprintf("xcode=%v", xcode), func(t *testing.T) {
+ x := newEngRig(t)
+ x.note("edit:Swipe.swift|false|true")
+ var lost atomic.Bool
+ x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus {
+ if !xcode && lost.Load() {
+ return &wire.EngineeringStatus{State: wire.EngineeringProbesPending}
+ }
+ return &wire.EngineeringStatus{State: wire.EngineeringReady}
+ }
+ if xcode {
+ x.r.XcodeAccess = wire.XcodeAccessSandboxed
+ x.w.Eng.Xcode = func() bool { return !lost.Load() }
+ }
+ u, err := x.m.turns.Take(context.Background(), mac.OpProbe)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := x.state.AcceptDispatch(context.Background(), "d-w", x.r.DispatchCommand); err != nil {
+ t.Fatal(err)
+ }
+ x.inbound(t)
+ auth, steps := x.authLaunches(), x.steps()
+ done := make(chan wire.StepReport, 1)
+ go func() { done <- x.exec(t, x.r) }()
+ time.Sleep(500 * time.Millisecond)
+ lost.Store(true)
+ u.Give()
+ rep := <-done
+ if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || x.authLaunches() != auth || x.steps() != steps {
+ t.Fatalf("report %+v, %d auth, %d step launches", rep, x.authLaunches()-auth, x.steps()-steps)
+ }
+ })
+ }
+}
+
+// Fix round 1, #4: readiness lost while the runtime copy's auth status
+// ran, in the same turn, still launches no step.
+func TestWorkerEngineeringReadinessBeforeTheStep(t *testing.T) {
+ x := newEngRig(t)
+ x.note("edit:Swipe.swift|false|true")
+ var lost atomic.Bool
+ x.w.Eng.Status = func(context.Context) *wire.EngineeringStatus {
+ if lost.Load() {
+ return &wire.EngineeringStatus{State: wire.EngineeringSignedOut}
+ }
+ return &wire.EngineeringStatus{State: wire.EngineeringReady}
+ }
+ x.w.Eng.refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
+ id, err := x.m.authStatus(ctx, b)
+ lost.Store(true)
+ return id, err
+ }
+ before := x.steps()
+ rep := x.run(t)
+ if rep.State != wire.StepFailed || rep.Reason != wire.ReasonEngineeringUnavailable || x.steps() != before {
+ t.Fatalf("report %+v, %d step launches", rep, x.steps()-before)
+ }
+}
+
+// Fix round 1, #5: a crash on either side of the committed transition.
+// Before it, the attempt ends runner_restarted and nothing is uploaded;
+// after it, the restart reports what the attempt reported (session,
+// askable, Apple, words) and the kept session is bound to the candidate.
+func TestWorkerEngineeringCrashAroundCommitted(t *testing.T) {
+ for _, point := range []string{"retained", "committed"} {
+ t.Run(point, func(t *testing.T) {
+ x := newEngRig(t)
+ x.noUpload = true
+ x.note("edit:Swipe.swift|false|true")
+ old := workerFault
+ workerFault = func(p string) bool { return p == point }
+ t.Cleanup(func() { workerFault = old })
+ if err := x.state.AcceptDispatch(context.Background(), "d-c", x.r.DispatchCommand); err != nil {
+ t.Fatal(err)
+ }
+ x.inbound(t)
+ x.exec(t, x.r)
+ workerFault = old
+ ctx := context.Background()
+ if err := x.state.RecoverSteps(ctx, func(context.Context, string) bool { return true }); err != nil {
+ t.Fatal(err)
+ }
+ if point == "retained" {
+ var state, reason string
+ x.state.db.QueryRow("SELECT state, final_reason FROM steps WHERE step_id=?", x.r.StepID).Scan(&state, &reason)
+ if reason != "runner_restarted" {
+ t.Fatalf("after a crash before committed: %s %s", state, reason)
+ }
+ refs, _ := x.store(t, "for-each-ref", "--format=%(objectname)", "refs/equipo/")
+ p := wire.StepReport{TaskID: "tk1", StepID: x.r.StepID, Attempt: 1, BaseSHA: x.pri.base, CandidateSHA: refs}
+ if refs == "" || len(x.uploaded(t, x.sendPack(t, p))) != 0 {
+ t.Fatalf("an uncommitted candidate (%q) was uploaded", refs)
+ }
+ return
+ }
+ r, ok, err := x.state.nextStep(ctx)
+ if err != nil || !ok || !committed(r.Phase) {
+ t.Fatalf("after the restart: %+v %v %v", r, ok, err)
+ }
+ rep := x.exec(t, r)
+ if rep.State != wire.StepDone || rep.SessionID == "" || !rep.Askable || !rep.Apple || rep.Summary == "" || rep.Account == "" {
+ t.Fatalf("recovered report %+v", rep)
+ }
+ if _, found, _ := x.state.keptCommit(ctx, "tk1", connPerson, wire.SpecialistEngineering, r.Candidate); !found {
+ t.Fatal("the kept session is not bound to the candidate")
+ }
+ })
+ }
+}
+
+// Fix round 1, #3: finished attempts' step logs go with the sweep.
+func TestWorkerSweepRemovesStepLogs(t *testing.T) {
+ x := newEngRig(t)
+ x.note("edit:Swipe.swift|false|true")
+ x.run(t)
+ log := filepath.Join(x.w.Engine.root(), stepKey(x.r), "log.jsonl")
+ if _, err := os.Stat(log); err != nil {
+ t.Fatalf("no step log: %v", err)
+ }
+ if _, err := x.state.db.Exec("UPDATE steps SET state=? WHERE step_id=?", runDone, x.r.StepID); err != nil {
+ t.Fatal(err)
+ }
+ x.w.sweep(context.Background())
+ if _, err := os.Stat(log); !os.IsNotExist(err) {
+ t.Fatalf("the step log stayed: %v", err)
+ }
+}
+
+// Fix round 1, #7: on a Mac gitleaks runs in the checks gate (srt with
+// the checks profile P2 proves); the gate's run is read the same way.
+// Here the gate has no srt (Linux), and the scanner is the pinned one.
+func TestGateLeaks(t *testing.T) {
+ runnerPath := previewScannerFixture(t)
+ binary, pin := previewScannerTool(runner.Config{Executable: runnerPath})
+ g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin", "LANG=C"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone}
+ for name, c := range map[string]struct {
+ files map[string]string
+ found bool
+ }{
+ "clean": {map[string]string{"a.swift": "let a = 1\n"}, false},
+ "a key": {map[string]string{"keys.txt": "token = \"ghp_" + "R4nd0mT0k3nW1thH1ghEntr0pyXyZ987654321\"\n"}, true},
+ "by name": {map[string]string{"nuget.config": "<configuration><packageSourceCredentials><feed><add key=\"ClearTextPassword\" value=\"Xk9pQ2vR7sLm4TzWq8Ny\" /></feed></packageSourceCredentials></configuration>\n"}, true},
+ } {
+ t.Run(name, func(t *testing.T) {
+ stage := filepath.Join(t.TempDir(), "scan", "files")
+ for p, body := range c.files {
+ os.MkdirAll(filepath.Dir(filepath.Join(stage, p)), 0o700)
+ os.WriteFile(filepath.Join(stage, p), []byte(body), 0o600)
+ }
+ found, err := gateLeaks(context.Background(), g, binary, pin, stage, "scan-test", nil)
+ if err != nil || found != c.found {
+ t.Fatalf("found %v, %v", found, err)
+ }
+ })
+ }
+ // Not the pinned scanner: it cannot tell.
+ if _, err := gateLeaks(context.Background(), g, binary, strings.Repeat("0", 64), t.TempDir(), "scan-test", nil); err == nil {
+ t.Fatal("an unpinned scanner was run")
+ }
+}
+
+// Fix round 1, #7: a Mac whose checks gate is not the proven sandboxed
+// one cannot scan: the candidate does not leave.
+func TestMacLeaksNeedTheProvenGate(t *testing.T) {
+ install := filepath.Dir(previewScannerFixture(t))
+ // Both gates can run the scanner here (no srt on Linux); only the one
+ // P2's trusted verdict picks for checks may.
+ sandboxed := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxSeatbelt}
+ bare := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, ScratchHome: true, Lines: 10, Sandbox: wire.SandboxNone}
+ h := &macHost{paths: mac.Paths{InstallDir: install}, checks: &macChecks{probes: newMacProbes("v", "", nil, func() bool { return true }), taint: &macTaint{}, srt: "/nonexistent/srt", sandboxed: sandboxed, unproven: bare, bare: bare}}
+ stage := filepath.Join(t.TempDir(), "scan", "files")
+ os.MkdirAll(stage, 0o700)
+ os.WriteFile(filepath.Join(stage, "a.swift"), []byte("let a = 1\n"), 0o600)
+ if _, err := h.leaks(context.Background(), stage, "scan-test", nil); err == nil {
+ t.Fatal("scanned without the proven gate")
+ }
+}
diff --git a/internal/runner/thin/worker_launch.go b/internal/runner/thin/worker_launch.go
index c6e37585..8b5fa475 100644
--- a/internal/runner/thin/worker_launch.go
+++ b/internal/runner/thin/worker_launch.go
@@ -31,7 +31,7 @@ var macStopLimit = 30*time.Second + simShutdownLimit + 30*time.Second
// holds the Mac's turn. A start whose record was lost (ErrRecord) or
// whose stop was not proven (ErrUnproven) ends unproven: not terminated,
// no Retry until a restart proves it.
-func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun, marker string) stepResult {
+func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree, spec specialistRun, marker string, forms [][]byte) stepResult {
e, m := w.Engine, w.Eng.Creds
o := e.O
b := spec.binding
@@ -44,13 +44,31 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
e.log("worker guard", err)
return done(wire.ReasonEngineeringUnavailable)
}
+ // Readiness and the Xcode proof may have changed while the attempt
+ // waited for the turn (a probe run holds it): asked again in it.
+ if reason := w.readyNow(ctx, r); reason != "" {
+ return done(reason)
+ }
direct, err := o.Runner.DirectBinding(b)
if err != nil {
return done("account_unavailable")
}
- lease, err := provider.OpenRuntimeCopy(ctx, direct, m.authStatus, o.LockWait)
+ refresh := m.authStatus
+ if w.Eng.refresh != nil {
+ refresh = w.Eng.refresh
+ }
+ lease, err := provider.OpenRuntimeCopy(ctx, direct, refresh, o.LockWait)
if err != nil {
e.log("worker account", err)
+ switch {
+ case errors.Is(err, mac.ErrUnproven), errors.Is(err, mac.ErrRecord):
+ // The auth status read's end is not proven: neither is the
+ // attempt's.
+ return stepResult{reason: wire.ReasonEngineeringUnavailable}
+ case errors.Is(err, provider.ErrLoginRequired):
+ // Sign in again: the step fails over as on a refused run.
+ return stepResult{reason: "sign_in_again", auth: true, terminated: true}
+ }
return done(reasonFor(err))
}
defer lease.Close()
@@ -112,6 +130,9 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
}
token := []byte(env[provider.OAuthTokenEnv])
defer clear(token)
+ if reason := w.readyNow(ctx, r); reason != "" {
+ return done(reason)
+ }
// Watched as a sign-in is: the Keychain listed before the CLI starts,
// looked at again once its end is proven.
if err = m.keychain.Before(ctx, marker, in.ConfigDir); err != nil {
@@ -153,8 +174,10 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
}
}
}()
- logFile := e.openLog(r)
- defer logFile.Close()
+ // The step log keeps only redacted frames.
+ raw := e.openLog(r)
+ defer raw.Close()
+ logFile := redactingWriter{w: raw, forms: forms}
var shell shellUse
res := e.converse(ctx, proc, session, policy, model, frames, logFile, limit, spec.prompt, nil, nil, spec.activity, &shell)
res.session, res.refused, res.noShell = session, refused.Load(), shell.none()
@@ -177,3 +200,29 @@ func (w *Worker) launch(ctx context.Context, r stepRow, tree workspace.TaskTree,
}
return res
}
+
+// readyNow is why the Mac cannot launch the attempt now ("" when it
+// can): its Engineering status is not ready, or sandboxed Xcode access
+// that its trusted report no longer allows.
+func (w *Worker) readyNow(ctx context.Context, r stepRow) string {
+ if s := w.Eng.Status(ctx); s == nil || s.State != wire.EngineeringReady {
+ return wire.ReasonEngineeringUnavailable
+ }
+ if r.XcodeAccess != "" && (w.Eng.Xcode == nil || !w.Eng.Xcode()) {
+ return wire.ReasonEngineeringUnavailable
+ }
+ return ""
+}
+
+// redactingWriter writes each frame with every known secret redacted.
+type redactingWriter struct {
+ w io.Writer
+ forms [][]byte
+}
+
+func (r redactingWriter) Write(p []byte) (int, error) {
+ if _, err := io.WriteString(r.w, redactText(string(p), r.forms)); err != nil {
+ return 0, err
+ }
+ return len(p), nil
+}
diff --git a/internal/runner/thin/worker_scan.go b/internal/runner/thin/worker_scan.go
index 724a088e..a04b8210 100644
--- a/internal/runner/thin/worker_scan.go
+++ b/internal/runner/thin/worker_scan.go
@@ -1,6 +1,9 @@
package thin
import (
+ "time"
+
+ "amadan.net/oficina/equipo/internal/release"
"bufio"
"bytes"
"context"
@@ -41,7 +44,12 @@ const minSecret = 16
// scanHit is why the scan refused: the object and its kind ("" object
// for gitleaks, which scans the blobs together; kind "scanner" when the
// scan could not tell).
-type scanHit struct{ object, kind string }
+type scanHit struct {
+ object, kind string
+ // unproven: the scanner's end is not proven (the attempt stays
+ // unterminated).
+ unproven bool
+}
// secretForms are the byte strings each secret is searched as: raw, hex
// (both cases), and base64 standard and URL at each of the three
@@ -107,7 +115,7 @@ func redactReport(rep wire.StepReport, forms [][]byte) wire.StepReport {
// scan reads every new object of the candidate in the store; nil when
// none holds a known secret and gitleaks found nothing.
-func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [][]byte) *scanHit {
+func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [][]byte, record func(string) error) *scanHit {
unreadable := &scanHit{kind: "scanner"}
list, err := w.git(ctx, nil, "--git-dir="+store, "rev-list", "--objects", "--end-of-options", sha, "^"+base)
if err != nil {
@@ -124,14 +132,6 @@ func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [
if len(ids) == 0 {
return unreadable
}
- stage := filepath.Join(dir, "scan", "blobs")
- if err := os.RemoveAll(filepath.Dir(stage)); err != nil {
- return unreadable
- }
- if err := os.MkdirAll(stage, 0700); err != nil {
- return unreadable
- }
- defer os.RemoveAll(filepath.Dir(stage))
var hit *scanHit
err = w.readObjects(ctx, store, ids, func(id, kind string, body []byte) error {
for _, f := range forms {
@@ -140,9 +140,6 @@ func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [
return errScanHit
}
}
- if kind == "blob" {
- return os.WriteFile(filepath.Join(stage, id), body, 0600)
- }
return nil
})
switch {
@@ -154,10 +151,30 @@ func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [
w.Engine.log("worker scan read", err)
return unreadable
}
- found, err := w.Eng.Leaks(ctx, stage)
+ // gitleaks reads the changed files at their own paths (some rules go
+ // by the file's name), a renamed file's contents included. The paths
+ // stay in the stage: nothing logs them.
+ stage := filepath.Join(dir, "scan", "files")
+ if err := os.RemoveAll(filepath.Dir(stage)); err != nil {
+ return unreadable
+ }
+ if err := os.MkdirAll(stage, 0700); err != nil {
+ return unreadable
+ }
+ defer os.RemoveAll(filepath.Dir(stage))
+ if err := w.stageChanged(ctx, store, base, sha, stage); err != nil {
+ if errors.Is(err, errScanBound) {
+ return &scanHit{object: boundObject(err), kind: "too_large"}
+ }
+ w.Engine.log("worker scan stage", err)
+ return unreadable
+ }
+ found, err := w.Eng.Leaks(ctx, stage, engineeringMarker(stage), record)
switch {
case found:
return &scanHit{kind: "gitleaks"}
+ case errors.Is(err, errScanUnproven):
+ return &scanHit{kind: "scanner", unproven: true}
case err != nil:
w.Engine.log("worker scan gitleaks", err)
return unreadable
@@ -165,9 +182,64 @@ func (w *Worker) scan(ctx context.Context, store, dir, base, sha string, forms [
return nil
}
+// stageChanged writes every file the candidate adds or changes against
+// the base (no rename detection: a moved file is a new path) under stage
+// at its path, its contents the blob's (a symbolic link's target as a
+// plain file); a gitlink has no contents here. A path with an empty, "."
+// or ".." part is refused.
+func (w *Worker) stageChanged(ctx context.Context, store, base, sha, stage string) error {
+ out, err := w.git(ctx, nil, "--git-dir="+store, "diff-tree", "-r", "-z", "--no-renames", "--no-commit-id", "--no-ext-diff", "--no-textconv", "--end-of-options", base, sha)
+ if err != nil {
+ return err
+ }
+ paths := map[string][]string{}
+ var ids []string
+ fields := strings.Split(strings.Trim(out, "\x00"), "\x00")
+ for i := 0; i+1 < len(fields); i += 2 {
+ meta, path := strings.Fields(strings.TrimPrefix(fields[i], ":")), fields[i+1]
+ if len(meta) != 5 {
+ return errors.New("the changed files could not be read")
+ }
+ mode, id, status := meta[1], meta[3], meta[4]
+ if status == "D" || mode == "160000" {
+ continue
+ }
+ for _, part := range strings.Split(path, "/") {
+ if part == "" || part == "." || part == ".." {
+ return errors.New("a changed path the stage cannot hold")
+ }
+ }
+ if !wire.ValidCommitSHA(id) {
+ return errors.New("the changed files could not be read")
+ }
+ if paths[id] == nil {
+ ids = append(ids, id)
+ }
+ paths[id] = append(paths[id], path)
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ return w.readObjects(ctx, store, ids, func(id, kind string, body []byte) error {
+ for _, p := range paths[id] {
+ target := filepath.Join(stage, filepath.FromSlash(p))
+ if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil {
+ return err
+ }
+ if err := os.WriteFile(target, body, 0600); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
var (
- errScanHit = errors.New("a known secret in the candidate")
- errScanBound = errors.New("an object past the scan bound")
+ // errScanUnproven: the scanner ran in the gate and its end is not
+ // proven.
+ errScanUnproven = errors.New("the secret scanner's end is not proven")
+ errScanHit = errors.New("a known secret in the candidate")
+ errScanBound = errors.New("an object past the scan bound")
)
// boundError names the object past the bound.
@@ -185,7 +257,8 @@ func boundObject(err error) string {
}
// readObjects reads each object whole with cat-file --batch, sizes first
-// (--batch-check): one past workerScanBound stops the read.
+// (--batch-check): one past workerScanBound stops the read before any
+// is read (objects are content-addressed: the sizes cannot change).
func (w *Worker) readObjects(ctx context.Context, store string, ids []string, each func(id, kind string, body []byte) error) error {
input := strings.Join(ids, "\n") + "\n"
check, err := w.git(ctx, strings.NewReader(input), "--git-dir="+store, "cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)")
@@ -223,7 +296,7 @@ func (w *Worker) readObjects(ctx context.Context, store string, ids []string, ea
}
var got, kind string
var size int64
- if n, err := fmt.Sscanf(header, "%s %s %d\n", &got, &kind, &size); n != 3 || err != nil || got != id || size > workerScanBound {
+ if n, err := fmt.Sscanf(header, "%s %s %d\n", &got, &kind, &size); n != 3 || err != nil || got != id || size < 0 {
return errors.New("an object could not be read")
}
body := make([]byte, size+1)
@@ -243,3 +316,39 @@ func (w *Worker) readObjects(ctx context.Context, store string, ids []string, ea
_, _ = io.Copy(io.Discard, out)
return errors.Join(err, cmd.Wait())
}
+
+// gateLeaks runs the pinned gitleaks over stage in the gate g: on a Mac
+// the checks gate, srt with the checks profile probe P2 proves (no
+// network, reads kept from §4.2's places, writes only to the gate's tree
+// and scratch). The tree is stage's parent, which holds the trusted
+// rules, the empty ignore file and the report; marker and record are the
+// scan's process record, as a check's.
+func gateLeaks(ctx context.Context, g *mac.Gate, binary, pin, stage, marker string, record func(string) error) (bool, error) {
+ if !release.VerifyGitleaks(binary, pin) {
+ return false, errScanner
+ }
+ root := filepath.Dir(stage)
+ config, ignore, report := filepath.Join(root, "trusted.toml"), filepath.Join(root, "empty.ignore"), filepath.Join(root, "findings.json")
+ if os.WriteFile(config, []byte(previewSecretRules), 0600) != nil || os.WriteFile(ignore, nil, 0600) != nil {
+ return false, errScanner
+ }
+ if record == nil {
+ record = func(string) error { return nil }
+ }
+ argv := []string{binary, "dir", "--config", config, "--gitleaks-ignore-path", ignore, "--ignore-gitleaks-allow", "--no-banner", "--redact", "--log-level", "error", "--max-archive-depth", "10", "--max-decode-depth", "5", "--report-format", "json", "--report-path", report, stage}
+ res := g.Run(ctx, marker, root, argv, 2*time.Minute, record)
+ switch {
+ case !res.Terminated:
+ return false, errScanUnproven
+ case res.Reason != "":
+ return false, errScanner
+ }
+ found, err := readFindings(report)
+ if err != nil || found {
+ return found, err
+ }
+ if res.Code != 0 {
+ return false, errScanner
+ }
+ return false, nil
+}
diff --git a/internal/runner/thin/worker_store.go b/internal/runner/thin/worker_store.go
index d7dd5ed4..246342c6 100644
--- a/internal/runner/thin/worker_store.go
+++ b/internal/runner/thin/worker_store.go
@@ -5,6 +5,7 @@ import (
"context"
"database/sql"
"errors"
+ "fmt"
"io/fs"
"os"
"os/exec"
@@ -104,16 +105,13 @@ func (w *Worker) indexEngineering(ctx context.Context, store, scratch string, pa
whole[f[0]] = true
}
}
+ // The walk ran where only the pack's objects are, so every object it
+ // listed is in the pack: equal counts are equal sets.
slices.Sort(packed)
named := slices.Sorted(slices.Values(commits))
if !slices.Equal(packed, named) || len(whole) != len(inPack) {
return errPackRefused
}
- for id := range whole {
- if !inPack[id] {
- return errPackRefused
- }
- }
if err := w.initStore(ctx, store, h.BaseSHA); err != nil {
return err
}
@@ -228,6 +226,19 @@ func (w *Worker) candidatePack(ctx context.Context, h wire.TransferHeader) ([]by
}
store := w.objects(h.Repo)
ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: h.TaskID, StepID: h.StepID, Attempt: h.Attempt}})
+ // Retained, and not past its keep: a forgotten candidate never goes,
+ // whether or not its ref is gone yet.
+ var expires string
+ err = w.State.db.QueryRowContext(ctx, "SELECT expires_at FROM candidates WHERE repo=? AND ref=?", h.Repo, ref).Scan(&expires)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, errPackRefused
+ }
+ if err != nil {
+ return nil, err
+ }
+ if expires != "" && expires <= stamp(time.Now()) {
+ return nil, errPackRefused
+ }
if got, err := w.git(ctx, nil, "--git-dir="+store, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}"); err != nil || got != cand {
return nil, errPackRefused
}
@@ -244,16 +255,27 @@ func (w *Worker) candidatePack(ctx context.Context, h wire.TransferHeader) ([]by
}
// forget is the worker's forget_task: the kept sessions it released go,
-// and so do the task's candidates whose keep (none, or passed) is over.
+// and so do the task's candidates whose keep (none, or passed) is over;
+// the next keep's end is swept when it comes.
func (w *Worker) forget(ctx context.Context, dirs []string) {
w.Engine.RemoveKept(dirs)
w.sweep(ctx)
}
-// sweep removes kept sessions past their keep or retention, and the refs
-// of candidates whose task was forgotten and whose keep has passed.
+// sweep removes what finished attempts left (their trees and their step
+// logs, once the instance acked their final report), kept sessions past
+// their keep or retention, and the refs of candidates whose task was
+// forgotten and whose keep has passed; then it sets itself to run again
+// at the next candidate's keep.
func (w *Worker) sweep(ctx context.Context) {
+ if keys, err := w.State.finishedSteps(ctx); err == nil {
+ for _, r := range keys {
+ _ = os.RemoveAll(filepath.Join(w.stepsDir(), stepKey(r)))
+ _ = os.RemoveAll(filepath.Join(w.Engine.root(), stepKey(r)))
+ }
+ }
w.Engine.sweepKept(ctx, w.State)
+ defer w.sweepAtNextKeep(ctx)
rows, err := w.State.db.QueryContext(ctx, "SELECT repo, ref FROM candidates WHERE expires_at<>'' AND expires_at<=?", stamp(time.Now()))
if err != nil {
w.Engine.log("worker candidates", err)
@@ -311,3 +333,21 @@ func workerSecrets(c runner.Config, bearer string) ([]string, error) {
}
return out, nil
}
+
+// sweepAtNextKeep runs the sweep when the soonest candidate keep ends.
+func (w *Worker) sweepAtNextKeep(ctx context.Context) {
+ var next sql.NullString
+ if err := w.State.db.QueryRowContext(ctx, "SELECT MIN(expires_at) FROM candidates WHERE expires_at>?", stamp(time.Now())).Scan(&next); err != nil || !next.Valid {
+ return
+ }
+ var ms int64
+ if _, err := fmt.Sscanf(next.String, "%d", &ms); err != nil {
+ return
+ }
+ w.sweepMu.Lock()
+ defer w.sweepMu.Unlock()
+ if w.sweepTimer != nil {
+ w.sweepTimer.Stop()
+ }
+ w.sweepTimer = time.AfterFunc(time.Until(time.UnixMilli(ms))+10*time.Millisecond, func() { w.sweep(ctx) })
+}