package thin import ( "context" "encoding/json" "errors" "os" "path/filepath" "slices" "strings" "sync" "time" "unicode/utf8" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/forgekey" ) // Ask the implementer on a Mac worker (Mac runners slice F, task 13). // The worker kept each Engineering attempt's session (kept_sessions, one // per step and attempt, with its account and session id) and pinned its // candidate in its store (candidateRef). A question resumes exactly the // session the instance froze on it: that step, attempt, account and // session id, on the commit it made; anything else is refused before // anything runs. It runs in the Mac's turn (OpAsk), through the darwin // launch with the read-only answer settings (task 8), in a fresh tree of // the candidate under the scratch root, and git_log, git_diff and // git_show read the change from the store (its shallow boundaries end // the history at the base). The answer passes the known-secret redaction // before it leaves. // ask answers one question attempt about an Engineering step this worker // ran; terminated is false only when its launch started and its end was // not proven. func (w *Worker) ask(ctx context.Context, a askRow, progress func(wire.AnswerReport)) askResult { terminated := true rep := w.answer(ctx, a, progress, &terminated) return askResult{Report: rep, Terminated: terminated} } func (w *Worker) answer(ctx context.Context, a askRow, progress func(wire.AnswerReport), terminated *bool) (rep wire.AnswerReport) { e := w.Engine received := time.Now() rep = wire.AnswerReport{TaskID: a.TaskID, QuestionID: a.QuestionID, Attempt: a.Attempt} fail := func(reason string) wire.AnswerReport { rep.State, rep.Reason = wire.QuestionFailed, reason if ctx.Err() != nil { rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" } return rep } // The instance's pinning, whole: a worker answers only about the // Engineering it ran, and only for the attempt, account and session // frozen on the question. if !slices.Contains(e.Owners, a.Person) || !forgekey.ValidHub(a.Repo) || !wire.ValidTaskBranch(a.Branch) || !refName.MatchString(a.TaskID) || !refName.MatchString(a.StepID) || !wire.ValidCommitSHA(a.CandidateSHA) || !wire.ValidCommitSHA(a.BaseSHA) || a.Specialist != wire.SpecialistEngineering || a.EngAttempt < 1 || a.EngAccount == "" || a.EngSession == "" { return fail("policy_rejected") } kept, found, err := w.State.keptAttempt(ctx, a.StepID, a.EngAttempt) if err != nil { e.log("ask session", err) return fail("provider_failed") } if !found || kept.TaskID != a.TaskID || kept.Person != a.Person || kept.Specialist != wire.SpecialistEngineering { return fail("session_gone") } if kept.Account != a.EngAccount || kept.SessionID != a.EngSession || kept.Candidate != a.CandidateSHA { return fail("policy_rejected") } if _, err := os.Stat(keptTranscript(kept.Dir, kept.SessionID)); err != nil { return fail("session_gone") } if w.Eng == nil || w.Eng.Creds == nil || w.Eng.Status == nil || w.Eng.Secrets == nil || e.Conns == nil { return fail("account_unavailable") } // The session's own connection, while it can run; never another. One // reading of the bindings: a sign-out meanwhile cannot shift another // connection into its place. mine := e.Conns.Mine if w.mine != nil { mine = w.mine } var b runner.AccountBinding bs := mine(a.Person) if i := slices.IndexFunc(bs, func(c runner.AccountBinding) bool { return c.Provider == wire.ProviderClaude && c.LocalID == kept.Account }); i >= 0 { b = bs[i] } if b.ID == "" || e.Healthy != nil && !e.Healthy(b.ID) { return fail("account_unavailable") } // Only an instance that pins questions (protocol 37), and only under // its lease. if e.Spoken == nil || e.Spoken() < wire.ProtocolMacEngineering || e.Authorize == nil { return fail("policy_rejected") } r := stepRow{DispatchCommand: wire.DispatchCommand{Person: a.Person, TaskID: a.TaskID, StepID: a.QuestionID, Attempt: a.Attempt, Specialist: wire.SpecialistEngineering, Repo: a.Repo, Branch: a.Branch, BaseSHA: a.BaseSHA, CandidateSHA: a.CandidateSHA}, Question: true} w.mu.Lock() defer w.mu.Unlock() if ctx.Err() != nil { return fail("cancelled") } m := w.Eng.Creds if m.turns != nil { u, err := m.turns.Take(ctx, mac.OpAsk) if err != nil { e.log("worker ask turn", err) return fail("account_unavailable") } defer u.Give() ctx = u.Context(ctx) } // The runner's current lease, confirmed as a question's, in the turn // and before anything is prepared: a runner (or person) that lost its // authority while the question waited runs nothing. if err := e.lease(ctx, r); err != nil { if errors.Is(err, ErrWithdrawn) { return fail("superseded") } return fail("cancelled") } secrets, err := w.Eng.Secrets(ctx) if err != nil { // What it cannot name it cannot keep from leaving: nothing runs. e.log("worker secrets", err) return fail("account_unavailable") } known := secretForms(secrets) defer func() { rep.Text = redactText(rep.Text, known) }() marker := engineeringMarker("ask/" + a.QuestionID + "/" + itoa(a.Attempt)) w.marker = marker defer func() { w.marker = "" }() if err := w.State.setAskNamespace(ctx, a, mac.RecordID(0, marker)); err != nil { e.log("worker record", err) return fail("provider_failed") } // The candidate as the store pins it for that attempt. store := w.objects(a.Repo) ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: a.TaskID, StepID: a.StepID, Attempt: a.EngAttempt}}) if tip, err := w.git(ctx, nil, "--git-dir="+store, "rev-parse", "--verify", "--end-of-options", ref+"^{commit}"); err != nil || tip != a.CandidateSHA { return fail("candidate_unavailable") } dir := filepath.Join(w.stepsDir(), "ask-"+stepKey(r)) defer os.RemoveAll(dir) tree, err := workspace.PrepareTaskTree(ctx, e.O.Runner.GitPath, store, a.CandidateSHA, a.Branch, filepath.Join(dir, "tree"), filepath.Join(dir, "git")) if err != nil { e.log("worker ask tree", err) return fail("candidate_unavailable") } rep.State = wire.QuestionRunning progress(rep) stream := &answerStream{} if e.Delta != nil { // A secret can arrive split across chunks: the text is redacted // whole as it grows (redactedStream). held := newRedactedStream(known, func(offset int64, text string) { e.Delta(wire.DeltaReport{TurnID: a.QuestionID, Attempt: a.Attempt, Offset: offset, Text: text}) }) stream.delta = func(_ int64, text string) { held.add(text) } defer held.flush() } if e.Activity != nil { stream.activity = func(kind, tool string) { e.Activity(wire.ActivityReport{TurnID: a.QuestionID, Attempt: a.Attempt, Kind: kind, Tool: tool}) } } var mu sync.Mutex call := func(cctx context.Context, name, _ string, args json.RawMessage) (string, bool) { mu.Lock() defer mu.Unlock() return answerGit(cctx, tree.Git, tree.GitDir, a.BaseSHA, a.CandidateSHA, name, args) } limit := e.MaxAnswer if limit <= 0 { limit = maxAnswer } res := w.launch(ctx, r, tree, specialistRun{action: "answer", binding: b, tools: answerTools, names: []string{"git_log", "git_diff", "git_show"}, permission: claude.ReadPermission, call: call, prompt: e.askPrompt(a, tree.Dir), resume: kept.SessionID, keep: kept.Dir, stream: stream, limit: limit, noLog: true, record: func(ctx context.Context, id string) error { return w.State.setAskNamespace(ctx, a, id) }}, marker, known) *terminated = res.terminated if res.kept > 0 { e.log("kept sessions", w.State.touchKept(context.WithoutCancel(ctx), kept, res.kept)) } switch { case ctx.Err() != nil: rep.State, rep.Reason = wire.QuestionCancelled, "cancelled" case res.reason == "step_timeout": rep.State, rep.Reason = wire.QuestionFailed, "turn_timeout" case res.reason != "": if !wire.AnswerReasons[res.reason] { res.reason = "provider_failed" } rep.State, rep.Reason = wire.QuestionFailed, res.reason case strings.TrimSpace(res.summary) == "": rep.State, rep.Reason = wire.QuestionFailed, "provider_failed" default: // Redacted whole, then cut: a secret crossing the bound is still // whole when the redaction looks for it. rep.State, rep.Text = wire.QuestionAnswered, clip(strings.TrimSpace(redactText(res.summary, known)), wire.MaxAnswerText) t := stream.timing t.Cold = true if !stream.stdin.IsZero() { t.StartMs = stream.stdin.Sub(received).Milliseconds() } rep.Timing = &t } outcome := wire.OutcomeFailed switch rep.State { case wire.QuestionAnswered: outcome = wire.OutcomeReplied case wire.QuestionCancelled: outcome = wire.OutcomeCancelled } rep.Usage = usageRows(res.tokens, b, a.Attempt, outcome) return rep } // redactedStream sends a session's streamed text with every known secret // redacted, whichever chunks it arrives in: the text so far is redacted // whole, and its last hold bytes (room for the longest form of a secret // to complete) wait for the next chunk or the flush. A form can only // match where new text ends it, so what was sent stays a prefix of what // the whole text redacts to. Offsets are the redacted text's. type redactedStream struct { forms [][]byte hold int raw strings.Builder sent int send func(offset int64, text string) } func newRedactedStream(forms [][]byte, send func(offset int64, text string)) *redactedStream { hold := 64 for _, f := range forms { hold = max(hold, len(f)) } return &redactedStream{forms: forms, hold: hold, send: send} } func (r *redactedStream) add(text string) { r.raw.WriteString(text) r.emit(false) } // flush sends what is held, once the session has said everything. func (r *redactedStream) flush() { r.emit(true) } func (r *redactedStream) emit(all bool) { out := redactText(r.raw.String(), r.forms) end := len(out) if !all { end -= r.hold } for end > r.sent && end < len(out) && !utf8.RuneStart(out[end]) { end-- } if end <= r.sent { return } r.send(int64(r.sent), out[r.sent:end]) r.sent = end }