package thin import ( "bytes" "context" "database/sql" "errors" "fmt" "io" "io/fs" "os" "os/exec" "path/filepath" "slices" "strings" "time" "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/runner/workspace" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/forgekey" ) // A worker's store for Engineering (Mac runners spec §8.4): one bare // repository per hub repository, holding the commits the primary relays // (each a shallow boundary: their parents never come) and the candidates // the worker made, each pinned by its ref until its task is forgotten. // candidatesSchema records each pinned candidate and, once its task is // forgotten, until when it stays (a stamp; ” while the task is open). const candidatesSchema = ` CREATE TABLE IF NOT EXISTS candidates (ref TEXT NOT NULL, repo TEXT NOT NULL, task_id TEXT NOT NULL, person TEXT NOT NULL, expires_at TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, PRIMARY KEY (repo, ref)); CREATE INDEX IF NOT EXISTS candidates_task ON candidates(task_id, person); ` // objectFormat names the object format of a full object id. func objectFormat(sha string) string { if len(sha) == 64 { return "sha256" } return "sha1" } // initStore makes the repository's store if it is missing. func (w *Worker) initStore(ctx context.Context, store, sha string) error { if _, err := os.Stat(store); err == nil { return nil } if err := os.MkdirAll(store, 0700); err != nil { return err } _, err := w.git(ctx, nil, "init", "-q", "--bare", "--template=", "--object-format="+objectFormat(sha), store) return err } // indexEngineering checks an Engineering pack's own inventory, alone in // a repository of its own (scratch/inventory.git): exactly the commits // the header names, each with its whole tree, and nothing else. Only then // does it go into the store, its commits marked shallow there. func (w *Worker) indexEngineering(ctx context.Context, store, scratch string, pack []byte, h wire.TransferHeader) error { commits := h.Commits() look := filepath.Join(scratch, "inventory.git") if err := os.RemoveAll(look); err != nil { return err } if err := os.MkdirAll(look, 0700); err != nil { return err } defer os.RemoveAll(look) if _, err := w.git(ctx, nil, "init", "-q", "--bare", "--template=", "--object-format="+objectFormat(h.BaseSHA), look); err != nil { return err } out, err := w.git(ctx, bytes.NewReader(pack), "--git-dir="+look, "index-pack", "--stdin") if err != nil { return err } fields := strings.Fields(out) if len(fields) == 0 || !wire.ValidCommitSHA(fields[len(fields)-1]) { return errPackRefused } listed, err := w.git(ctx, nil, "verify-pack", "-v", filepath.Join(look, "objects", "pack", "pack-"+fields[len(fields)-1]+".idx")) if err != nil { return err } inPack, packed := map[string]bool{}, []string{} for _, line := range strings.Split(listed, "\n") { f := strings.Fields(line) if len(f) < 3 || !wire.ValidCommitSHA(f[0]) { continue } inPack[f[0]] = true if f[1] == "commit" { packed = append(packed, f[0]) } } walk, err := w.git(ctx, nil, append([]string{"--git-dir=" + look, "rev-list", "--objects", "--no-walk", "--end-of-options"}, commits...)...) if err != nil { return err } whole := map[string]bool{} for _, line := range strings.Split(walk, "\n") { if f := strings.Fields(line); len(f) > 0 { 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 } if err := w.initStore(ctx, store, h.BaseSHA); err != nil { return err } if _, err := w.git(ctx, bytes.NewReader(pack), "--git-dir="+store, "index-pack", "--stdin"); err != nil { return err } return markShallow(store, commits) } // markShallow adds commits to the store's shallow file (merged with what // is there, sorted), so log and rev-list stop at them. func markShallow(store string, commits []string) error { path := filepath.Join(store, "shallow") raw, err := os.ReadFile(path) if err != nil && !errors.Is(err, fs.ErrNotExist) { return err } all := slices.Clone(commits) for _, line := range strings.Split(string(raw), "\n") { if line = strings.TrimSpace(line); line != "" { all = append(all, line) } } slices.Sort(all) all = slices.Compact(all) tmp := path + ".new" if err := os.WriteFile(tmp, []byte(strings.Join(all, "\n")+"\n"), 0600); err != nil { return err } return os.Rename(tmp, path) } // retain copies the candidate's new objects from the task tree's private // repository into the store and pins it with its ref, recorded with its // task so a forget_task releases it. func (w *Worker) retain(ctx context.Context, tree workspace.TaskTree, store, dir string, r stepRow, base, sha string) error { file := filepath.Join(dir, "candidate.pack") f, err := os.OpenFile(file, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600) if err != nil { return err } defer os.Remove(file) cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, "--git-dir="+tree.GitDir, "pack-objects", "--revs", "--stdout", "-q") cmd.Stdin, cmd.Stdout, cmd.Env = strings.NewReader(sha+"\n^"+base+"\n"), f, w.gitEnv() err = mac.StartOwn(cmd) if err == nil { err = cmd.Wait() } if cerr := f.Close(); err == nil { err = cerr } if err != nil { return err } in, err := os.Open(file) if err != nil { return err } defer in.Close() if _, err := w.git(ctx, in, "--git-dir="+store, "index-pack", "--stdin"); err != nil { return err } ref := candidateRef(r) if _, err := w.git(ctx, nil, "--git-dir="+store, "update-ref", ref, sha); err != nil { return err } _, err = w.State.db.ExecContext(ctx, "INSERT INTO candidates(ref, repo, task_id, person, created_at) VALUES(?,?,?,?,?) ON CONFLICT DO NOTHING", ref, r.Repo, r.TaskID, r.Person, now()) return err } // dropCandidate removes a candidate's ref and its record. func (w *Worker) dropCandidate(ctx context.Context, repo, ref string) error { if _, err := os.Stat(w.objects(repo)); err == nil { if _, err := w.git(ctx, nil, "--git-dir="+w.objects(repo), "update-ref", "-d", ref); err != nil { return err } } _, err := w.State.db.ExecContext(ctx, "DELETE FROM candidates WHERE repo=? AND ref=?", repo, ref) return err } // gitEnv is the environment of the worker's own git: no config, no // home, the attempt's marker. func (w *Worker) gitEnv() []string { var env []string for k, v := range workspace.GitEnvironment() { env = append(env, k+"="+v) } return append(env, "HOME=/nonexistent", "EQUIPO_ATTEMPT="+w.marker) } // candidatePack is the thin pack (against the base) of a committed // attempt's candidate, for an outbound transfer: the attempt must be on // record committed with exactly this base and candidate, which only a // passed scan records, and its ref must pin the candidate. It is answered // as often as the instance asks (a Retry after the primary was replaced // sends a second send_pack), from the store alone. errPackRefused: never. func (w *Worker) candidatePack(ctx context.Context, h wire.TransferHeader) ([]byte, error) { if h.Direction != wire.TransferOutbound || h.Kind != "" || !forgekey.ValidHub(h.Repo) || !h.Valid() || !wire.ValidCommitSHA(h.BaseSHA) || !wire.ValidCommitSHA(h.CandidateSHA) || !refName.MatchString(h.TaskID) || !refName.MatchString(h.StepID) || h.Attempt < 1 { return nil, errPackRefused } var task, phase, base, cand string err := w.State.db.QueryRowContext(ctx, "SELECT task_id, phase, base_sha, candidate_sha FROM steps WHERE step_id=? AND attempt=?", h.StepID, h.Attempt).Scan(&task, &phase, &base, &cand) if errors.Is(err, sql.ErrNoRows) { return nil, errPackRefused } if err != nil { return nil, err } if task != h.TaskID || !committed(phase) || base != h.BaseSHA || cand != h.CandidateSHA { return nil, errPackRefused } 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 } var out bytes.Buffer if err := w.thinPack(ctx, store, base, cand, &limitWriter{w: &out, n: wire.MaxTransferBytes + 1}); err != nil { return nil, err } return out.Bytes(), nil } // thinPack writes the thin pack of cand against base from store to out: // what an outbound transfer carries. func (w *Worker) thinPack(ctx context.Context, store, base, cand string, out io.Writer) error { cmd := exec.CommandContext(ctx, w.Engine.O.Runner.GitPath, "--git-dir="+store, "pack-objects", "--revs", "--thin", "--stdout", "-q") cmd.Stdin, cmd.Stdout, cmd.Env = strings.NewReader(cand+"\n^"+base+"\n"), out, w.gitEnv() if err := mac.StartOwn(cmd); err != nil { return err } return cmd.Wait() } // packSize is the size of the thin pack an outbound transfer of cand // would carry. func (w *Worker) packSize(ctx context.Context, store, base, cand string) (int64, error) { var n counter err := w.thinPack(ctx, store, base, cand, &n) return int64(n), err } // counter counts what is written to it. type counter int64 func (c *counter) Write(p []byte) (int, error) { *c += counter(len(p)); return len(p), nil } // 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; // 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 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) return } var gone [][2]string for rows.Next() { var repo, ref string if rows.Scan(&repo, &ref) == nil { gone = append(gone, [2]string{repo, ref}) } } rows.Close() for _, g := range gone { w.Engine.log("worker candidates", w.dropCandidate(ctx, g[0], g[1])) } } // workerSecrets are a Mac worker's known secrets: its runner credential, // every Claude token connection's token, and its enrolment key (whose // seed the seal key is made from) with the seal key's private half. A // token or key that is not there is skipped; any other failure to read // one is an error (nothing is scanned against a list with a hole). func workerSecrets(c runner.Config, bearer string) ([]string, error) { out := []string{bearer} bindings, err := runner.LoadBindings(c.AccountBindingsPath) if err != nil && !errors.Is(err, fs.ErrNotExist) { return nil, err } for _, b := range bindings { if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken { continue } raw, err := provider.ReadToken(b.ProviderHome) if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return nil, err } out = append(out, string(raw)) clear(raw) } key, err := runner.ReadMachineKey(c.StateDir) switch { case errors.Is(err, fs.ErrNotExist): case err != nil: return nil, err default: out = append(out, string(key), string(key.Seed())) if keys, err := sealbox.FromEd25519(key); err == nil { out = append(out, string(keys.PrivateHalf())) } clear(key) } 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) }) }