exec

package
v0.2.0-rc3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 29 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	StoppedByArtifacts  = "artifacts"
	StoppedByIterations = "iterations"
	StoppedByWall       = "wall"
	StoppedByExit       = "exit"
	StoppedByCancelled  = "cancelled"
	// The agent declared a blocker (a BLOCKED: line in NOTES.md).
	StoppedByBlocked = "blocked"
	// Two iterations in a row changed nothing (ProgressFingerprint) and left
	// the same artifacts missing.
	StoppedByNoProgress = "no_progress"
	// The job's total agent cost reached Caps.AgentMaxCostUSD.
	StoppedByBudget = "budget"
)

Reasons the loop stopped. Only StoppedByArtifacts means the worker delivered what BRIEF.md asked for; the rest are caps and failures.

View Source
const (
	DefaultAgentMaxIters   = 8
	DefaultAgentMaxWallSec = 2700
)

Loop caps. Wall covers only the driver loop — never baseline or verify, which are 20 min per command on their own clock (verify.go).

View Source
const (
	DataDBFile       = "defect-drainer.db"
	DataJobsDir      = "jobs"
	DataBatchJobsDir = "batch-jobs"
	EvidenceDirName  = "evidence"
)

The layout of DD's data and inventory dirs, as internal/paths names it. Spelled out here because internal/paths reads DD settings (Resolve) and this package reads none; internal/jobs pins them equal (paths_parity_test).

View Source
const (
	DefaultReviewMaxTurns   = 8
	DefaultReviewMaxWallSec = 900

	// ReviewSocketError is the lens error when read-only refuses to start
	// because the runtime socket is a symlink. The phrases matched in stderr
	// are grok's own (probed 2026-09-26).
	ReviewSocketError = "read-only sandbox refused to start (runtime socket is a symlink, e.g. /var/run/docker.sock)"
)
View Source
const (
	KindBatchFix = "batch_fix"
	KindTestRun  = "test_run"
)

Job kinds.

View Source
const (
	ModeFresh  = "fresh"
	ModeRerun  = "rerun"
	ModeResume = "resume"
)

Spawn modes. A fresh run measures baseline and diff base; a rerun or resume reuses the first run's and adds to its agent record.

View Source
const (
	EventLog          = "log"
	EventStatus       = "status"
	EventAgentRun     = "agent_run"
	EventBaseline     = "baseline"
	EventVerification = "verification"
	EventDiffHygiene  = "diff_hygiene"
	EventReview       = "review"
	EventHarvest      = "harvest"
	EventTestResults  = "test_results"
	EventDone         = "done"
)

Event kinds.

View Source
const (
	// PhaseHandoff: the handoff files are written. The orchestrator gates the
	// adapter here.
	PhaseHandoff = "handoff"
	// PhasePrepared: the app's settings line is logged.
	PhasePrepared = "prepared"
	// PhaseReady: the agent is signed in. A host lease may park the job here.
	PhaseReady = "ready"
	// PhaseRunning: about to start the first agent iteration. Carries the
	// diff base and the spawn lines.
	PhaseRunning = "running"
	// PhaseStarted: the first child exists.
	PhaseStarted = "started"
	// PhaseLaunched: the first child is tracked; the driver loop is running.
	PhaseLaunched = "launched"
	// PhaseLoopEnded: no further child will start.
	PhaseLoopEnded = "loop_ended"
	// PhaseAgentExit: the loop's outcome. Error is set when the agent failed.
	PhaseAgentExit = "agent_exit"
	// PhaseReviewBegin / PhaseReviewEnd bracket the reviewer's read-only
	// window (manifest capture to compare).
	PhaseReviewBegin = "review_begin"
	PhaseReviewEnd   = "review_end"
	// PhaseExited: the run is over on this host.
	PhaseExited = "exited"
)

Status phases, in the order a run reaches them. Each is a point where the orchestrator updates the job or answers (see Sink.Apply).

View Source
const (
	ControlCancel      = "cancel"
	ControlResume      = "resume"
	ControlShipPreview = "ship_preview"
	ControlDiff        = "diff"
	ControlShip        = "ship"
	ControlDiscard     = "discard"
)

Control kinds. ShipPreview, Diff, Ship and Discard are carried by the remote transport only (worker protocol v1 §6.3); local shipping stays in internal/jobs and internal/api.

View Source
const DDShotName = "dd-shot"

DDShotName is the helper's file name in the handoff.

View Source
const DefaultManifestByteCap int64 = 2 << 30
View Source
const HarvestFileLimit = 26 << 20

HarvestFileLimit matches api.maxMultipartMem: a harvested file is stored and served like an upload, so it cannot be larger than an upload.

View Source
const VerifySkippedHostPolicy = "host policy"

VerifySkippedHostPolicy is VerifySkipped when a worker's policy has allow_verify_commands off.

Variables

View Source
var (
	ErrInactive = errors.New("job is no longer active")
	ErrParked   = errors.New("job parked")
)

Answers a Sink may give. ErrInactive: the job was cancelled or deleted, stop quietly. ErrParked: the job waits for a host lease and will be started again.

View Source
var ImageExts = map[string]bool{
	".png": true, ".jpg": true, ".jpeg": true,
	".webp": true, ".gif": true, ".heic": true,
}
View Source
var NO_TOOLCHAIN = ToolchainProvision{Env: map[string]string{}, Notes: []string{}, Ok: false}

NO_TOOLCHAIN is the skip result.

Functions

func AcceptanceCriteria

func AcceptanceCriteria(body string) []string

AcceptanceCriteria pulls the ## Acceptance checklist out of a defect body. Port of backend/src/batches.ts acceptanceCriteria — same heading, strip, and "next heading ends the block" rules.

func AlreadyFailingLines

func AlreadyFailingLines(run *VerificationRun) []string

func ArtifactsComplete

func ArtifactsComplete(handoff string, defectIDs []string, sandbox string, cutoff time.Time) (bool, []string)

ArtifactsComplete decides whether the driver loop may stop. It answers only "did the worker deliver the files BRIEF.md demands" — never "may this defect resolve". Harvest keeps its own gates: a loop that completes on NO-SCREENSHOT or UNFIXED still resolves nothing for those defects.

missing lists what was absent, in defect order, for the job log and for agentRun.missing when a cap ends the loop instead.

func BatchSQLitePath

func BatchSQLitePath(id string) string

BatchSQLitePath is the TS writeBatchManifest path: sqlite:batches/<id>.

func BindingAliases

func BindingAliases(b git.WorktreeBinding, entries []RepoEntry) map[string]struct{}

BindingAliases are names that legitimately refer to one worktree.

A binding is named by the app's repo ENTRY name on the entries path ("webapp") but by the git URL LEAF on the repo_urls path ("app"), so a verify row configured with either must still match — otherwise the command is silently skipped, which counts as a failure and blocks every resolve.

Cross-walk through the app's own entry->url mapping; never by substring.

func BlockedReason

func BlockedReason(handoff string, cutoff time.Time, startDigest string) (reason string, ok bool)

BlockedReason is the reason on the first `BLOCKED: <reason>` line of NOTES.md. It counts only when NOTES.md's content differs from startDigest (NotesDigest before this run's first iteration), so a line left from before a Resume or Rerun does not stop that run at once. Content, not mtime: Linux stamps mtimes from a coarse clock that lags time.Now (PR #3 CI). The reason is the agent's text: control characters are dropped and it is cut to 200 characters. ok is false when there is no such line.

func BuildBatchFixBrief

func BuildBatchFixBrief(input BatchFixBriefInput) string

BuildBatchFixBrief ports backend/src/batches.ts buildBatchFixBrief.

func BuildReviewMD

func BuildReviewMD(lens, brief string, wts []git.WorktreeBinding, diffBase map[string]string, defectIDs []string) string

func BuildSkillsMarkdown

func BuildSkillsMarkdown(worktrees []git.WorktreeBinding) string

BuildSkillsMarkdown emits one stanza per worktree with absolute paths and names only. Bodies are never copied (K11).

func BuildTestBrief

func BuildTestBrief(in TestBriefInput) string

func BuildTestPrompt

func BuildTestPrompt(label, handoff, defectsRoot, sandbox string, wts []git.WorktreeBinding, base *git.CodingAgentOpts) string

func CheckSimulatorSandboxProfile

func CheckSimulatorSandboxProfile(handoffAbs string, want []byte) error

CheckSimulatorSandboxProfile runs before every agent iteration, Resume's first included. The job profile must be exactly what DD wrote, through no symlink; and the user-level sandbox.toml must not mention the profile name, because grok lets a user profile replace a project one wholesale — deny included. The name check is a plain substring match, deliberately conservative: even a comment naming it refuses. Every failure refuses the start rather than repair and go on: with the deny in place, a changed profile means something defeated it.

func DiffManifestLists

func DiffManifestLists(before, after []WtManifest) string

DiffManifestLists reports the first repo that is missing on one side or whose manifest differs. A repo that vanished from the second capture is a change even when capture itself returned no error.

func FileBirthTime

func FileBirthTime(f *os.File, _ *syscall.Stat_t) (time.Time, bool)

FileBirthTime uses statx(2) STATX_BTIME via golang.org/x/sys/unix (already in go.mod through modernc.org/sqlite). The frozen syscall package only exposes SYS_STATX on loong64, so a raw syscall.SYS_STATX is not portable across linux/amd64 and linux/arm64. Fail open when the syscall or the BTIME bit is unavailable (old kernel, tmpfs, etc.).

func FormatAgentExit

func FormatAgentExit(a agentadapter.Adapter, err error) string

FormatAgentExit is the job error for a failed iteration. Grok keeps its historical text; the others name the adapter.

func FormatGrokExit

func FormatGrokExit(err error) string

FormatGrokExit is grok's historical job error for a failed iteration.

func GitCAbs

func GitCAbs(abs string, args ...string) (string, error)

func HarvestableImageName

func HarvestableImageName(name string, isDir bool) bool

HarvestableImageName is the name-level half of harvest's evidence predicate. Both CollectFixHarvest and ArtifactsComplete call it so the loop can never stop on a file harvest would then skip. ReadRegularFile is the other half and each caller applies it to the same path.

func HygieneChanged

func HygieneChanged(h DiffHygieneReport) bool

func IntPtr

func IntPtr(n int) *int

func IsBlockMarker

func IsBlockMarker(v string) bool

IsBlockMarker reports a YAML block scalar header — `|` or `>`, with the optional chomping and indent indicators (`|-`, `>+`, `>2`). Anything else after the marker means it is ordinary text, not a block.

func IsRealDir

func IsRealDir(p string) bool

IsRealDir reports whether p is a directory itself, not a symlink to one.

func LoopIterationLine

func LoopIterationLine(iter int, exitErr error, sawMaxTurns, complete bool, stoppedBy string, missing []string) string

LoopIterationLine is the operator-facing summary of one iteration. It always says what the child did and what, if anything, is still missing, so a capped run reads as "ran out of budget with X absent" rather than just "completed".

func LoopLevel

func LoopLevel(stoppedBy string) string

func NextLoopStop

func NextLoopStop(st LoopState) string

NextLoopStop decides whether the driver loop stops, and why. Empty means iterate again. First match wins:

exit → artifacts → blocked → no_progress → budget → wall → iterations

The exit-code rule is the subtle one. Turn exhaustion also exits non-zero (verified on Grok Build 1.0.40: exit 1, stopReason "cancelled", plus a max_turns_reached event), so breaking on any non-zero exit would treat every turn cap as a job failure and never resume — which is the whole point of the loop. sawMaxTurns is the positive signal that separates the two.

complete is checked before the other rules: if the worker delivered the artifacts on its last legal iteration, that is why the loop stopped, and the operator should not see it reported as having run out of budget. The agent's own blocker comes next because it says the most; budget precedes the wall and iteration caps because it is the money rule.

func NotRunKeys

func NotRunKeys(handoff string, cutoff time.Time, secret string) map[string]string

func NotesDigest

func NotesDigest(handoff string, cutoff time.Time) string

NotesDigest is NOTES.md's content as the loop sees it: its SHA-256, or "absent" or "unreadable". It is read like harvest reads it (cutoff is the job's harvest cutoff). The loop takes it before iteration 1 spawns.

func NotesForHarvest

func NotesForHarvest(handoff string, defectIDs []string, cutoff time.Time) (unfixed map[string]bool, unreadable bool)

NotesForHarvest separates a missing NOTES.md from one the reader refuses. Missing means no markers. Present but unreadable (too large, a symlink, a hardlink, another device) must not look like an empty decline list.

func NotesMarkers

func NotesMarkers(handoff string, defectIDs []string, cutoff time.Time) (unfixed, noShot map[string]bool, ok bool)

NotesMarkers scans NOTES.md once for the two loop markers. A missing or unreadable NOTES.md yields no markers and ok=false — the loop then cannot be complete, which is the fail-closed direction.

func ParsePositiveInt

func ParsePositiveInt(s string, def int) int

ParsePositiveInt falls back to def for empty, non-numeric, and n <= 0 so a typo'd env var cannot silently disable a cap.

func ParseResultStatus

func ParseResultStatus(raw string) (status, body string, ok bool)

func PathLooksLikeUI

func PathLooksLikeUI(rel string) bool

PathLooksLikeUI reports whether rel, relative to a worktree, looks like a UI file. It matches when a directory segment is lib or src and some segment (directory or file) contains "widget" or "component", case-insensitive. A file sitting directly under lib/ with neither word in its name does not match. Symlinks are not followed by the walker.

func ProgressFingerprint

func ProgressFingerprint(handoff string, wts []git.WorktreeBinding) string

ProgressFingerprint is what an iteration could have changed: per worktree one `git status --porcelain=v2 --branch` (HEAD, every changed and untracked path with its index state) plus a stamp of each of those paths; and a stamp of NOTES.md, fix-notes/* and fix-evidence/** in the handoff. A stamp is the name and the SHA-256 of the content, so a file re-saved with the same bytes is no progress and a second edit to a changed or new file is (spec §4.1.6, amended 2026-11-20); a file over 10 MB falls back to name, size and mtime. Nothing else in the handoff (logs, agent state) is stamped. Two equal fingerprints in a row mean the iteration did nothing (stop no_progress).

Git runs as the worker, outside the agent's sandbox, through the pinned binding (never the worktree's own .git): one call per worktree, whose cost is mostly the pinning itself. Any git error makes the result unique, so an error can never look like "no progress".

func ReadEvidence

func ReadEvidence(events [][]byte, wts []git.WorktreeBinding) bool

ReadEvidence reports whether a grok stream shows a completed git diff of one of this job's worktrees. Test-only: production calls the adapter.

func ReadFirstNote

func ReadFirstNote(root string, notBefore time.Time, cands ...string) (note string, oversized []string)

func ReadRegularFile

func ReadRegularFile(root, p string, notBefore time.Time) (data []byte, tooLarge, ok bool)

ReadRegularFile reads p only when p is a regular file reached without traversing a symlink. The agent that populates the handoff directory is sandboxed precisely so it cannot read host secrets; harvest is not. Following a link the agent planted would make this process read the secret on its behalf, so every harvest read is confined to real files under root.

tooLarge is true when the file exceeds HarvestFileLimit; callers must skip and log rather than persist a truncated prefix. A mismatched birthtime (inode created before notBefore) is a silent skip — same as Nlink/Dev.

func RedactCut

func RedactCut(s, secret string) string

func RedactRaw

func RedactRaw(s, secret string) string

RedactRaw replaces the secret before newline normalization, so a value that itself contains CR LF is one match rather than two lines.

func ReviewBlockReason

func ReviewBlockReason(rev *ReviewRun) string

ReviewBlockReason is set when harvest must not resolve because a required review is not ok. The reason names the blocking finding count when there is one. Empty means the review gate does not apply.

func ReviewLenses

func ReviewLenses(wts []git.WorktreeBinding) []string

ReviewLenses is the spawn list. ui is added only when a worktree holds a UI-looking file; see PathLooksLikeUI.

func ReviewReadOnly

func ReviewReadOnly(handoff string) []string

ReviewReadOnly is what a reviewer may read in the job's handoff besides its own lens dir: the brief, the agent's notes and evidence. Never review/, so one lens cannot read another's output.

func ReviewSummary

func ReviewSummary(rev *ReviewRun) (string, string)

func SamePath

func SamePath(a, b string) bool

func SnapshotGitDirs

func SnapshotGitDirs(wts []git.WorktreeBinding) map[string]string

SnapshotGitDirs records each worktree's git dir before the implementer runs. A later rewrite of the handoff's .git file must not retarget it.

func SnapshotWorktreeReals

func SnapshotWorktreeReals(worktrees []git.WorktreeBinding) map[string]string

func StripSecretRef

func StripSecretRef(v any) any

func SummarizeVerdict

func SummarizeVerdict(v VerificationVerdict) string

func SummarizeVerification

func SummarizeVerification(run VerificationRun) string

func TruncateUTF8

func TruncateUTF8(s string, max int) string

TruncateUTF8 cuts s to at most max bytes without splitting a rune.

func UnixSignalName

func UnixSignalName(sig os.Signal) string

func ValidResultFile

func ValidResultFile(handoff, key string, cutoff time.Time) bool

func ValidStepKey

func ValidStepKey(k string) bool

ValidStepKey reports whether k is a plan or run step key.

func WorktreeDirty

func WorktreeDirty(wts []git.WorktreeBinding) bool

func WorktreeGit

func WorktreeGit(b git.WorktreeBinding, args ...string) (string, error)

WorktreeGit is one git command in b's worktree after an agent has had it: pinned (git.PinnedBindingGit, docs/worker-w3.md §3.5), never discovering the repo through the agent-writable <wt>/.git. It returns stdout.

func WorktreeHasDiff

func WorktreeHasDiff(wt, base, gitDir string) bool

WorktreeHasDiff is true when the worktree is a checkout and it is not provably identical to base, including uncommitted and untracked files. A missing base or a git error counts as a diff so a review is not skipped on a command we could not run. A directory that is not a checkout is not a diff.

func WorktreeHead

func WorktreeHead(b git.WorktreeBinding) string

WorktreeHead is the current commit of a worktree, for use as the later diff base.

func WorktreeStillReal

func WorktreeStillReal(abs, wantReal string) bool

RunVerification runs every command in its worktree. Always returns a record — a command whose repo has no worktree is reported as skipped, not silently dropped.

func WriteDDShot

func WriteDDShot(handoff string, c DDShot) error

WriteDDShot writes dd-shot into handoff with c's values baked in, so it works even where the env does not reach the agent's shell. None is a secret: the agent can read every one of them anyway.

func WriteHandoffBrief

func WriteHandoffBrief(handoff string, input BatchFixBriefInput) error

WriteHandoffBrief writes BRIEF.md, the DD-owned PROCESS.md worker contract, the generated SKILLS.md path listing, and the sandbox-writable harvest dirs.

func WriteTestHandoff

func WriteTestHandoff(handoff string, in TestBriefInput) error

WriteTestHandoff writes a test job's handoff: results/, evidence/, PROCESS.md, SKILLS.md and BRIEF.md.

Types

type AgentRun

type AgentRun struct {
	Iterations           int    `json:"iterations"`
	CompletedByArtifacts bool   `json:"completedByArtifacts"`
	StoppedBy            string `json:"stoppedBy,omitempty"`
	// StopReason is the agent's own words for a "blocked" stop (its
	// BLOCKED: line, at most 200 characters). Additive.
	StopReason   string   `json:"stopReason,omitempty"`
	StopReasons  []string `json:"stopReasons,omitempty"`
	Turns        int      `json:"turns,omitempty"`
	TotalCostUSD float64  `json:"totalCostUsd,omitempty"`
	SessionID    string   `json:"sessionId,omitempty"`
	Missing      []string `json:"missing,omitempty"`
	// Resumes counts operator Resumes. Iterations, turns and cost above are
	// cumulative across every run of the job, not just the latest.
	Resumes int `json:"resumes,omitempty"`
	// Runner is the agent adapter that ran the job (grok, claude,
	// antigravity). Additive; older jobs have none, which means grok.
	Runner string `json:"runner,omitempty"`
	// Tokens is the cumulative token count from adapters that report no cost
	// (antigravity).
	Tokens int `json:"tokens,omitempty"`
}

AgentRun records what the driver loop did. Completion is measured in artifacts on disk, not in the child's exit code or its prose (K6), so this is where an operator sees why the loop stopped.

type AgentRunAcc

type AgentRunAcc struct {
	// contains filtered or unexported fields
}

AgentRunAcc accumulates streaming-json events. OnEnd fires on the exec package's stdout copy goroutine while the loop goroutine reads the totals, so every field is behind the mutex.

func (*AgentRunAcc) AuthReason

func (a *AgentRunAcc) AuthReason() string

AuthReason is the auth failure to report as the job reason.

func (*AgentRunAcc) CostUSD

func (a *AgentRunAcc) CostUSD() float64

CostUSD is the job's total agent cost so far, Resumes included.

func (*AgentRunAcc) End

func (a *AgentRunAcc) End(stopReason, sessionID string, turns int, cost float64)

func (*AgentRunAcc) EndDetail

func (a *AgentRunAcc) EndDetail(e agentadapter.End)

EndDetail records what only some adapters report: tokens, the CLI's own error flag and an auth failure. Grok sets none of them.

func (*AgentRunAcc) LastError

func (a *AgentRunAcc) LastError() string

LastError is the CLI's latest error text ("" when none).

func (*AgentRunAcc) LastSession

func (a *AgentRunAcc) LastSession() string

LastSession is the session id to resume (seeded from a prior run).

func (*AgentRunAcc) MaxTurnsReached

func (a *AgentRunAcc) MaxTurnsReached()

MaxTurnsReached latches per iteration; the loop clears it before each start.

func (*AgentRunAcc) Seed

func (a *AgentRunAcc) Seed(prior *AgentRun)

Seed carries a prior run's totals into this one, so a Re-run or Resume adds to the job's record instead of replacing it.

func (*AgentRunAcc) Snapshot

func (a *AgentRunAcc) Snapshot(iter int, stoppedBy string, missing []string) *AgentRun

func (*AgentRunAcc) TakeError

func (a *AgentRunAcc) TakeError() (string, bool)

TakeError returns and clears this iteration's CLI error flag.

func (*AgentRunAcc) TakeMaxTurns

func (a *AgentRunAcc) TakeMaxTurns() bool

type AppSettings

type AppSettings struct {
	Sandbox         string          `json:"sandbox"`
	Toolchain       string          `json:"toolchain"`
	SimulatorWrites bool            `json:"simulatorWrites,omitempty"`
	MaxTurns        int             `json:"maxTurns,omitempty"`
	VerifyCommands  []VerifyCommand `json:"verifyCommands,omitempty"`
	RepoEntries     []RepoEntry     `json:"repoEntries,omitempty"`
	// VerifySkipped is why VerifyCommands were dropped before the run
	// ("host policy"), and VerifySkippedCommands how many there were. Set
	// only by a worker at offer; a run with VerifySkipped never resolves a
	// defect (spec D6).
	VerifySkipped         string `json:"verifySkipped,omitempty"`
	VerifySkippedCommands int    `json:"verifySkippedCommands,omitempty"`

	// Worker browser (additive, browser.v1). The console's per-app requests;
	// a worker applies only what its policy also allows and clears Browser
	// when it does not, so the brief and prompt see the effective value.
	//   - Browser: after-fix screenshots with the host browser (dd-shot).
	//   - PreviewCmd: the app's dev server, run in the first worktree.
	//   - PreviewURL: where it answers, loopback only (http://127.0.0.1:5173).
	//   - AgentHosts: network hosts requested for the agent's sandbox; empty
	//     means the host policy's list, as before.
	Browser    bool     `json:"browser,omitempty"`
	PreviewCmd string   `json:"previewCmd,omitempty"`
	PreviewURL string   `json:"previewUrl,omitempty"`
	AgentHosts []string `json:"agentHosts,omitempty"`
}

AppSettings are the app's agent settings, normalised by the orchestrator.

type Batch

type Batch struct {
	ID        string   `json:"id"`
	AppID     string   `json:"app_id"`
	Title     string   `json:"title"`
	Goal      string   `json:"goal"`
	Status    string   `json:"status"`
	DefectIDs []string `json:"defect_ids"`
	Mode      string   `json:"mode,omitempty"`
	Created   string   `json:"created"`
	UpdatedAt string   `json:"updated_at"`
	Path      string   `json:"path"`
}

Batch mirrors jobs.BatchRecord, the batch row a fix brief names.

type BatchFixBriefInput

type BatchFixBriefInput struct {
	Batch       Batch
	Defects     []Defect
	DefectsRoot string
	GrokSandbox string
	Worktrees   []git.WorktreeBinding
	// AllowedDomains are the hosts the agent's sandbox may reach; nil
	// writes no network section (grok, local serve without a list).
	AllowedDomains []string
	// NoNetwork says the agent's sandbox has no network at all (a
	// non-grok adapter with no allowed hosts).
	NoNetwork bool
	// Browser, when set, adds the Screenshots section and narrows
	// NO-SCREENSHOT (worker-browser B3, B6). Nil writes rc2's brief.
	Browser *BrowserBrief
}

BatchFixBriefInput is the TS buildBatchFixBrief argument.

type BrowserBrief

type BrowserBrief struct {
	PreviewCmd string
	PreviewURL string
}

BrowserBrief is the app's preview as the brief states it; both empty means the app has no preview.

type Caps

type Caps struct {
	AgentMaxIters    int  `json:"agentMaxIters"`
	AgentMaxWallSec  int  `json:"agentMaxWallSec"`
	ReviewOff        bool `json:"reviewOff,omitempty"`
	ReviewMaxTurns   int  `json:"reviewMaxTurns"`
	ReviewMaxWallSec int  `json:"reviewMaxWallSec"`
	// AgentMaxCostUSD stops the loop once the job's total agent cost (every
	// run of it, Resumes included) reaches it. Zero or less: no cost rule.
	AgentMaxCostUSD float64 `json:"agentMaxCostUsd,omitempty"`

	// The host's grok knobs, read by the orchestrator so this package reads
	// no DD setting (W1a deviation Q1, moved in W2b). AgentMaxTurnsArg is the
	// turn-cap override passed to grok verbatim when the app sets no cap. A
	// remote spec leaves all three empty: a worker's own policy decides.
	AgentMaxTurnsArg      string `json:"agentMaxTurnsArg,omitempty"`
	GrokBypassPermissions bool   `json:"grokBypassPermissions,omitempty"`
	GrokTools             string `json:"grokTools,omitempty"`
}

Caps are the loop and review budgets.

type CollectedFix

type CollectedFix struct {
	Defects         []HarvestedDefect
	Unfixed         map[string]bool
	NotesUnreadable bool
}

CollectedFix is a batch fix's handoff as the harvest reads it.

func CollectFixHarvest

func CollectFixHarvest(handoff string, defectIDs, harvestIDs []string, cutoff, imgCutoff time.Time) CollectedFix

CollectFixHarvest reads each harvestable defect's fix images and note. defectIDs is every defect in the job (the UNFIXED markers are read for all); harvestIDs are the ones whose directories may be read. Reads are confined to real files under the handoff (ReadRegularFile).

type Control

type Control struct {
	Kind  string   `json:"kind"`
	JobID string   `json:"jobId"`
	Spec  *JobSpec `json:"spec,omitempty"`
	// RequestID makes a remote control idempotent; SpecURL replaces Spec for
	// a remote resume; Repo is the diff target; Repos the ship list (worker
	// protocol v1 §6.3, §8.5). The local transport uses none of them.
	RequestID string     `json:"requestId,omitempty"`
	SpecURL   string     `json:"specUrl,omitempty"`
	Repo      string     `json:"repo,omitempty"`
	Repos     []ShipRepo `json:"repos,omitempty"`
}

Control is an instruction for a running job. Resume carries the spec of the next run; Cancel stops the current one.

type DDShot

type DDShot struct {
	Browser    string
	Dir        string
	PreviewCmd string
	PreviewURL string
}

DDShot is what dd-shot needs: the host browser (policy agent_browser), the worktree the preview runs in, and the app's preview command and URL.

type Defect

type Defect struct {
	ID           string   `json:"id"`
	AppID        string   `json:"app_id"`
	Title        string   `json:"title"`
	Severity     string   `json:"severity"`
	Status       string   `json:"status"`
	Area         string   `json:"area"`
	Client       string   `json:"client"`
	Surface      string   `json:"surface"`
	Repos        []string `json:"repos"`
	Labels       []string `json:"labels"`
	Related      []string `json:"related"`
	Source       string   `json:"source"`
	Reporter     string   `json:"reporter"`
	KeyFiles     []string `json:"key_files"`
	Evidence     []string `json:"evidence"`
	FixEvidence  []string `json:"fix_evidence"`
	Reported     string   `json:"reported"`
	Summary      string   `json:"summary"`
	ResolvedDate string   `json:"resolved_date,omitempty"`
	Resolution   string   `json:"resolution,omitempty"`
	DuplicateOf  string   `json:"duplicate_of,omitempty"`
	Body         string   `json:"body"`
	Bucket       string   `json:"bucket"`
	CreatedAt    string   `json:"created_at"`
	Path         string   `json:"path"`
}

Defect mirrors store.DefectRecord: the defect text a brief is built from.

type DiffHunk

type DiffHunk struct {
	File    string   `json:"file"`
	Header  string   `json:"header"`
	Removed []string `json:"removed"`
	Added   []string `json:"added"`
	Reflow  bool     `json:"reflow"`
}

DiffHunk is one parsed unified-0 hunk. A hunk is reflow iff added and removed text are identical once all whitespace is stripped. Not `git diff -w`: `-w` compares line by line, so a formatter joining three lines into one still reads as three deletions and one addition.

func CollectHunks

func CollectHunks(w git.WorktreeBinding, baseSha, kind string, limit int) (hunks []DiffHunk, total int, truncated bool, err error)

func ParseDiffHunks

func ParseDiffHunks(diff string) []DiffHunk

ParseDiffHunks parses a `git diff --unified=0` payload. Tests feed a fixture here; they must not call `git diff -w`.

type DiffHygieneReport

type DiffHygieneReport struct {
	Repos []RepoDiffHygiene `json:"repos"`
	Noisy bool              `json:"noisy"`
}

DiffHygieneReport is job.diffHygiene.

func MeasureDiffHygiene

func MeasureDiffHygiene(worktrees []git.WorktreeBinding, baseByRepo map[string]string, onLog hygieneLog) DiffHygieneReport

type Done

type Done struct {
	State string `json:"state"`
	Line  string `json:"line,omitempty"`
}

Done is the job's outcome.

type Event

type Event struct {
	Kind  string    `json:"kind"`
	JobID string    `json:"jobId"`
	Lines []LogLine `json:"lines,omitempty"`

	Status       *Status            `json:"status,omitempty"`
	AgentRun     *AgentRun          `json:"agentRun,omitempty"`
	Baseline     *VerificationRun   `json:"baseline,omitempty"`
	Verification *VerificationRun   `json:"verification,omitempty"`
	DiffHygiene  *DiffHygieneReport `json:"diffHygiene,omitempty"`
	Review       *ReviewRun         `json:"review,omitempty"`
	Harvest      *FixHarvest        `json:"harvest,omitempty"`
	TestResults  *TestHarvest       `json:"testResults,omitempty"`
	Done         *Done              `json:"done,omitempty"`
}

Event is one thing that happened. Kind says which payload is set. Lines are applied after the payload, in the same update.

type EvidenceRef

type EvidenceRef struct {
	Path   string `json:"path"`
	SHA256 string `json:"sha256,omitempty"`
}

EvidenceRef is one evidence file, by inventory-relative path.

type FixHarvest

type FixHarvest struct {
	Defects         []HarvestedDefect `json:"defects"`
	Unfixed         map[string]bool   `json:"unfixed,omitempty"`
	NotesUnreadable bool              `json:"notesUnreadable,omitempty"`
	// AllowResolve is false for a failed run; it then imports and resolves
	// nothing beyond what the gates allow (HarvestOpts).
	AllowResolve bool             `json:"allowResolve,omitempty"`
	Verification *VerificationRun `json:"verification,omitempty"`
	Review       *ReviewRun       `json:"review,omitempty"`
}

FixHarvest is what a batch fix left in the handoff, read by the executor and judged by the orchestrator.

type FixSpec

type FixSpec struct {
	Batch   Batch    `json:"batch"`
	Defects []Defect `json:"defects"`
	// Evidence lists the defects' evidence files. Local runs read them under
	// DefectsRoot; SHA256 is set when the file travels as a blob (W2).
	Evidence []EvidenceRef `json:"evidence,omitempty"`
}

FixSpec is what a batch fix's brief is built from.

type HarvestFile

type HarvestFile struct {
	Filename string `json:"filename"`
	Data     []byte `json:"data,omitempty"`
	// SHA256 and Size name the bytes as a blob (worker protocol v1 §7, §8.4).
	// A remote event omits Data; a local one keeps Data inline.
	SHA256 string `json:"sha256,omitempty"`
	Size   int64  `json:"size,omitempty"`
}

HarvestFile is one harvested file. Data travels inline in W1; W2 moves it to a content-addressed blob.

func HarvestStepImages

func HarvestStepImages(handoff, key string, cutoff time.Time) ([]HarvestFile, int, []string)

type HarvestedDefect

type HarvestedDefect struct {
	DefectID string        `json:"defectId"`
	Images   []HarvestFile `json:"images,omitempty"`
	// OversizedImages are image names skipped for size, in directory order.
	OversizedImages []string `json:"oversizedImages,omitempty"`
	Note            string   `json:"note,omitempty"`
	// OversizedNotes are note paths skipped for size.
	OversizedNotes []string `json:"oversizedNotes,omitempty"`
	// NoteSHA256 and NoteSize name the note as a blob when a remote worker
	// sends it by reference (worker protocol v1 §8.4). Local runs leave them
	// empty and keep Note inline.
	NoteSHA256 string `json:"noteSha256,omitempty"`
	NoteSize   int64  `json:"noteSize,omitempty"`
}

HarvestedDefect is one defect's fix images and note.

type Hooks

type Hooks struct {
	// AfterStart runs after the first child starts and before it is
	// tracked: a live child exists but nothing can reach it yet.
	AfterStart func()
	// BeforeNext runs after an iteration is reaped and the loop decided to
	// continue, before the next child starts: the gap with no process.
	BeforeNext func()
	// LensStarted runs once that lens's child is tracked, before Wait.
	LensStarted func(lens string)
	// LensFinished runs once that lens has been applied.
	LensFinished func(lens string)
	// Manifest returns the reviewer's manifest reader, read at capture time.
	Manifest func() ManifestIO
}

Hooks are test seams. Nil in production.

type Host

type Host struct {
	// DataRoot is the host's data directory (handoffs, agent state).
	DataRoot string
	// Adapter is the CLI. Nil means grok, resolved per use from the process
	// env (git.DefaultAdapter), exactly as before adapters.
	Adapter agentadapter.Adapter
	// Credential is the host's credential for that adapter.
	Credential agentadapter.Credential
	// PerJobConfigDir gives each job its own CLI config dir under the job's
	// state dir (Claude in API-key mode).
	PerJobConfigDir bool
	// EnvFiles are the host's env files; the agent may not read them.
	EnvFiles []string
	// DefectsRoot is the inventory root whose evidence an agent may not read.
	DefectsRoot string
	// ReadOnly are paths every agent of the job (implementer and reviewers)
	// may read but never edit. A worker sets the job's repo clone .git dirs
	// and its per-job report evidence; local serve sets none. A DenyRead
	// entry equal to or inside one of them is dropped; an ancestor stays
	// denied and the adapter re-allows only these paths.
	ReadOnly []string
	// AllowedDomains are the hosts the implementer's sandbox may reach
	// (empty: no network).
	AllowedDomains []string
	// DenyWrite are paths every agent of the job may not write (a worker's
	// status.json, readiness dir and $HOME, spec §4.1.11). Local serve sets
	// none.
	DenyWrite []string
	// Browser is the worker's headless browser when the job's Browser is
	// effective (worker-browser B1); "" otherwise and in local serve.
	// MaskedSockets are the host sockets the implementer's sandbox hides
	// once it has unix sockets (B2).
	Browser       string
	MaskedSockets []string
}

Host is this machine's coding-agent setup. It never travels in a JobSpec: the adapter, its credential and the paths an agent may not read belong to the host that runs the agent.

func (Host) AgentAdapter

func (h Host) AgentAdapter() agentadapter.Adapter

AgentAdapter is the host's adapter.

func (Host) CheckReady

func (h Host) CheckReady(ctx context.Context, jobID, handoff string, strip []string) error

CheckReady runs the adapter's login/key check under the child env the first iteration will get. A failure is the job reason agent_auth.

func (Host) CredentialFor

func (h Host) CredentialFor(jobID string) agentadapter.Credential

CredentialFor is the host credential with a per-job config dir when the adapter runs in API-key mode.

func (Host) DenyRead

func (h Host) DenyRead() []string

DenyRead is every path an agent child must not read: the host owner's secrets, DD's data (database, evidence, intake jobs, clones, agent state and every handoff, this job's own re-allowed by the adapter), the host's env files, and the CLI config and login dirs. Fail closed: a path that does not exist is still listed.

func (Host) LogSource

func (h Host) LogSource() string

LogSource is the job-log source for agent output, without resolving grok's binary on every line.

func (Host) StateDir

func (h Host) StateDir(jobID string) string

StateDir is the job's adapter state: settings files and, in Claude API-key mode, the CLI config dir. It sits beside the handoff, never in it, so the agent cannot rewrite its own permission rules.

type JobSpec

type JobSpec struct {
	JobID string `json:"jobId"`
	Kind  string `json:"kind"`
	AppID string `json:"appId"`
	// Label names the job in log lines, the sandbox profile and the prompt:
	// the batch id, or the test run id for a test job.
	Label   string `json:"label"`
	BatchID string `json:"batchId,omitempty"`
	Mode    string `json:"mode"`
	// ResumeSession is the agent session iteration 1 continues (Resume).
	ResumeSession string `json:"resumeSession,omitempty"`

	// Handoff is the job's working directory on the host; DefectsRoot is the
	// inventory root the brief points at.
	Handoff     string                `json:"handoff"`
	DefectsRoot string                `json:"defectsRoot"`
	Worktrees   []git.WorktreeBinding `json:"worktrees"`
	DefectIDs   []string              `json:"defectIds,omitempty"`
	// HarvestIDs are the defect ids whose fix-evidence/ and fix-notes/ the
	// harvest reads: DefectIDs that passed the orchestrator's id check.
	HarvestIDs []string `json:"harvestIds,omitempty"`

	// The first run's measurements, reused by a rerun or resume.
	DiffBase      map[string]string `json:"diffBase,omitempty"`
	Baseline      *VerificationRun  `json:"baseline,omitempty"`
	PriorAgentRun *AgentRun         `json:"priorAgentRun,omitempty"`

	// CreatedAt and RunStartedAt (RFC 3339) are the harvest cutoffs: files
	// older than the job do not count, and fix images older than this run are
	// not imported.
	CreatedAt    string `json:"createdAt,omitempty"`
	RunStartedAt string `json:"runStartedAt,omitempty"`

	App     AppSettings  `json:"app"`
	Fix     *FixSpec     `json:"fix,omitempty"`
	TestRun *TestRunSpec `json:"testRun,omitempty"`

	// StripEnv are host variables removed from every child (every app's
	// test-account secret names), read when the run starts.
	StripEnv []string `json:"stripEnv,omitempty"`
	Caps     Caps     `json:"caps"`

	// Adapter and Model are the app's agent setting (worker spec Q4). Empty
	// Adapter means "the host's first ready adapter". Resume and Rerun carry
	// the adapter that started the job. The local transport ignores both and
	// uses the host's DEFECT_DRAINER_AGENT_RUNNER (worker protocol v1 §8.6).
	Adapter string `json:"adapter,omitempty"`
	Model   string `json:"model,omitempty"`
}

JobSpec is one run of one job.

type LogLine

type LogLine struct {
	Text    string `json:"text"`
	Level   string `json:"level"`
	Source  string `json:"source"`
	Guarded bool   `json:"guarded,omitempty"`
}

LogLine is one job-log line. Guarded lines (and every payload) are dropped once the job is cancelled; unguarded ones, such as agent output still draining, are kept until the job is deleted.

type LoopState

type LoopState struct {
	Iter, MaxIters   int
	Elapsed, MaxWall time.Duration
	ExitErr          error
	SawMaxTurns      bool
	Complete         bool
	// Blocked: NOTES.md has a fresh BLOCKED: line.
	Blocked bool
	// NoProgress: this iteration's fingerprint and missing list equal the
	// previous iteration's.
	NoProgress bool
	// CostUSD is the job's total so far (Resumes included); MaxCostUSD <= 0
	// disables the budget rule.
	CostUSD, MaxCostUSD float64
}

LoopState is what NextLoopStop judges after one iteration.

type ManifestIO

type ManifestIO struct {
	Open           func(name string) (io.ReadCloser, error)
	ByteCap        int64
	BeforeSnapshot func()
}

ManifestIO is how a manifest capture reads files. The zero value is production: os.Open, a 2 GiB byte cap and no hook. Tests lower the cap, substitute a counting reader, and use BeforeSnapshot to check that implementer descendants are already gone.

type Outcome

type Outcome struct {
	Launched bool
	Parked   bool
}

Outcome is how Start ended. Launched: the driver loop is running on its own goroutine. Parked: the job waits for a host lease and will be started again. Neither: the run stopped before an agent started (job gone, or an error).

func Start

func Start(ctx context.Context, h Host, spec JobSpec, sink Sink, hooks Hooks) (Outcome, error)

Start runs one job on this host: handoff, readiness, toolchain, baseline, then the first agent iteration. It returns once that iteration is running, or when the run stops before it. The driver loop, verify, review and harvest go on in the background and report through sink. ctx cancels baseline and verify.

type Proc

type Proc struct {
	Cmd *exec.Cmd

	// Group is set for a reviewer. Stop and Delete kill its process group.
	// The implementer stays a normal process.
	Group bool
	// contains filtered or unexported fields
}

Proc is one live child. Wait is once-only so a delete and the completion goroutine can both reap without racing exec.Cmd.Wait.

func (*Proc) Kill

func (p *Proc) Kill()

Kill stops a live child. A reviewer is a process-group leader; SIGKILL the group so git and shell grandchildren die with it.

func (*Proc) Reap

func (p *Proc) Reap() error

Reap waits for the child once.

type RepoDiffHygiene

type RepoDiffHygiene struct {
	Repo                string  `json:"repo"`
	BaseSha             string  `json:"baseSha"`
	FilesChanged        int     `json:"filesChanged"`
	ChangedLines        int     `json:"changedLines"`
	EffectiveLines      int     `json:"effectiveLines"`
	FormattingOnlyLines int     `json:"formattingOnlyLines"`
	Hunks               int     `json:"hunks"`
	EffectiveHunks      int     `json:"effectiveHunks"`
	FormattingOnlyHunks int     `json:"formattingOnlyHunks"`
	FormattingRatio     float64 `json:"formattingRatio"`
	Error               string  `json:"error,omitempty"`
}

RepoDiffHygiene is one worktree's hygiene numbers. baseSha is required so GET /api/batch-jobs/{id}/diff/{repo} can recompute hunks on demand.

type RepoEntry

type RepoEntry struct {
	Name       string `json:"name"`
	URL        string `json:"url"`
	BaseSource string `json:"base_source,omitempty"`
	BaseBranch string `json:"base_branch,omitempty"`
}

RepoEntry mirrors store.AppRepoEntry.

type ReviewFinding

type ReviewFinding struct {
	Severity     string `json:"severity"`
	Lens         string `json:"lens"`
	DefectID     string `json:"defect_id,omitempty"`
	Location     string `json:"location,omitempty"`
	Finding      string `json:"finding"`
	Reasoning    string `json:"reasoning,omitempty"`
	SuggestedFix string `json:"suggested_fix,omitempty"`
}

ReviewFinding is one row of a dd.review.v1 payload. suggested_fix is text for a human; nothing in this process executes it.

type ReviewLens

type ReviewLens struct {
	Lens      string          `json:"lens"`
	OK        bool            `json:"ok"`
	Error     string          `json:"error,omitempty"`
	Turns     int             `json:"turns,omitempty"`
	CostUSD   float64         `json:"costUsd,omitempty"`
	SessionID string          `json:"sessionId,omitempty"`
	Findings  []ReviewFinding `json:"findings"`
}

ReviewLens is one fresh reviewer process.

func ParseLensText

func ParseLensText(lens, text string, tooLarge bool, defectIDs []string) ReviewLens

type ReviewRun

type ReviewRun struct {
	OK            bool         `json:"ok"`
	Required      bool         `json:"required"`
	SkippedReason string       `json:"skippedReason,omitempty"`
	Error         string       `json:"error,omitempty"`
	Lenses        []ReviewLens `json:"lenses,omitempty"`
	TotalCostUSD  float64      `json:"totalCostUsd,omitempty"`
}

ReviewRun is job.review. Required is false when the pass was skipped; harvest gates resolve only when Required && !OK.

func CloneReview

func CloneReview(r *ReviewRun) *ReviewRun

func (*ReviewRun) Finish

func (rev *ReviewRun) Finish()

type RunRef

type RunRef struct {
	Repo string `json:"repo"`
	Ref  string `json:"ref"`
	SHA  string `json:"sha,omitempty"`
}

RunRef mirrors store.RunRef.

type RunStep

type RunStep struct {
	Key          string   `json:"key"`
	Position     int      `json:"position"`
	Section      string   `json:"section"`
	Action       string   `json:"action"`
	Expected     string   `json:"expected"`
	Exploratory  bool     `json:"exploratory"`
	Status       string   `json:"status"`
	Actual       string   `json:"actual"`
	Evidence     []string `json:"evidence"`
	DefectID     *string  `json:"defect_id"`
	DefectStatus *string  `json:"defect_status"`
	Review       string   `json:"review"`
	ReviewNote   string   `json:"review_note"`
	UpdatedAt    string   `json:"updated_at"`
}

RunStep mirrors store.RunStep.

type SandboxProfileResult

type SandboxProfileResult struct {
	Profile string
	Body    []byte
	Notes   []string
}

SandboxProfileResult is the --sandbox name plus prompt notes. Body is the exact file written, for CheckSimulatorSandboxProfile.

func WriteSimulatorSandboxProfile

func WriteSimulatorSandboxProfile(handoffAbs, base, batchID string) (SandboxProfileResult, error)

WriteSimulatorSandboxProfile writes a job-scoped profile granting Simulator writes on top of base (`workspace` or `strict`). read_write takes literal directory grants (no globs). Never creates or edits ~/.grok/sandbox.toml.

`.grok` is replaced, never written through: DD is unsandboxed, and an agent from an earlier run (or one without this profile) may have left a symlink there aimed at a host file.

type ShipRepo

type ShipRepo struct {
	Repo    string   `json:"repo"`
	Files   []string `json:"files"`
	Message string   `json:"message"`
	Title   string   `json:"title"`
	Body    string   `json:"body"`
}

ShipRepo is one repo of a ship control: the files the operator confirmed and the commit message and pull request text.

type Sink

type Sink interface {
	// Apply takes one event, in order. An error stops the run where it is:
	// ErrInactive quietly, ErrParked to be started again later, anything
	// else as the run's failure.
	Apply(Event) error
	// Gone reports the job deleted; Cancelled reports it deleted or
	// stopped. Neither starts work.
	Gone() bool
	Cancelled() bool
	// Track installs the live child so Stop and Delete can reach it. It
	// returns false when the job is gone or stopped: the caller kills it.
	Track(p *Proc) bool
	// Untrack removes p if it is still the installed child.
	Untrack(p *Proc)
}

Sink is the transport's side of a run: where events go and where control comes from. The local transport is the orchestrator itself; W2's remote one is the worker's spool and its control frames.

type Status

type Status struct {
	Phase string `json:"phase"`
	// DiffBase is set on PhaseRunning: each repo's diff base for this run.
	DiffBase map[string]string `json:"diffBase,omitempty"`
	// Failed and Error are set on PhaseAgentExit.
	Failed bool   `json:"failed,omitempty"`
	Error  string `json:"error,omitempty"`
}

Status is a phase change.

type TestBriefInput

type TestBriefInput struct {
	TestRunID string
	AppID     string
	Worktrees []git.WorktreeBinding
	Run       TestRun
	// SecretEnv is set when the run's account password is injected.
	SecretEnv string
	// Failure is set when spawn did not start.
	Failure string
}

TestBriefInput is what a test job's BRIEF.md is built from.

type TestHarvest

type TestHarvest struct {
	Steps   []TestStepResult `json:"steps"`
	Warns   []string         `json:"warns,omitempty"`
	Ignored int              `json:"ignored,omitempty"`
	Finish  bool             `json:"finish,omitempty"`
}

TestHarvest is a test run's results, parsed and redacted.

func CollectTestResults

func CollectTestResults(handoff string, steps []RunStep, cutoff, imgCutoff time.Time, secret string) TestHarvest

CollectTestResults reads RUN.md, results/ and evidence/ for the run's steps. Everything the agent wrote is redacted with secret. imgCutoff is the stricter cutoff for screenshots (this run's start).

type TestRun

type TestRun struct {
	ID          string         `json:"id"`
	AppID       string         `json:"app_id"`
	PlanID      *string        `json:"plan_id"`
	PlanVersion *int           `json:"plan_version"`
	Title       string         `json:"title"`
	Env         map[string]any `json:"env"`
	Refs        []RunRef       `json:"refs"`
	Status      string         `json:"status"`
	Steps       []RunStep      `json:"steps,omitempty"`
}

TestRun is the part of store.TestRun a test job reads.

type TestRunSpec

type TestRunSpec struct {
	RunID string  `json:"runId"`
	Run   TestRun `json:"run"`
	// Loaded is false when the orchestrator could not read the run. The
	// loop then never stops on artifacts ("test run missing").
	Loaded bool `json:"loaded"`
	// SecretEnv names the host variable holding the account password, when
	// the run's account has an env:NAME reference. The value never travels.
	SecretEnv string `json:"secretEnv,omitempty"`
}

TestRunSpec is the test run a test job executes.

type TestStepResult

type TestStepResult struct {
	Key         string        `json:"key"`
	Status      string        `json:"status"`
	Actual      string        `json:"actual"`
	Exploratory bool          `json:"exploratory,omitempty"`
	Action      string        `json:"action,omitempty"`
	Expected    string        `json:"expected,omitempty"`
	HasExpected bool          `json:"hasExpected,omitempty"`
	Section     string        `json:"section,omitempty"`
	Images      []HarvestFile `json:"images,omitempty"`
}

TestStepResult mirrors store.HarvestedStep.

func ParseHarvestResult

func ParseHarvestResult(raw string, exploratory bool) (TestStepResult, string)

type ToolchainProvision

type ToolchainProvision struct {
	Env map[string]string
	// VerifyEnv is PATH for DD's unsandboxed runner. It must NOT include the
	// handoff clone: the agent can replace .tooling/bin after spawn.
	VerifyEnv map[string]string
	Notes     []string
	Ok        bool
}

ToolchainProvision is extra env + prompt notes for a job-scoped SDK.

func ProvisionFlutterToolchain

func ProvisionFlutterToolchain(handoffAbs string, worktrees []git.WorktreeBinding, onLog VerifyLog, strip []string) ToolchainProvision

type VerificationRun

type VerificationRun struct {
	Ran        bool           `json:"ran"`
	Ok         bool           `json:"ok"`
	Results    []VerifyResult `json:"results"`
	StartedAt  string         `json:"startedAt"`
	FinishedAt string         `json:"finishedAt"`
	// SkippedReason says why verification did not run when it was
	// configured ("host policy"). Additive.
	SkippedReason string `json:"skippedReason,omitempty"`
}

VerificationRun is job.verification / job.baseline.

func RunVerification

func RunVerification(ctx context.Context, commands []VerifyCommand, worktrees []git.WorktreeBinding, handoffAbs string, repoEntries []RepoEntry, extraEnv map[string]string, realByRepo map[string]string, onLog VerifyLog, strip []string) VerificationRun

type VerificationVerdict

type VerificationVerdict struct {
	Ok          bool
	Verdicts    []judgedRow
	Regressions int
	PreExisting int
	Fixed       int
	Blocked     int
}

VerificationVerdict is the harvest gate.

func JudgeVerification

func JudgeVerification(run, baseline *VerificationRun) VerificationVerdict

type VerifyCommand

type VerifyCommand struct {
	Repo    string `json:"repo"`
	Command string `json:"command"`
}

VerifyCommand mirrors store.VerifyCommand: one operator-authored check.

type VerifyLog

type VerifyLog func(line string, level string)

type VerifyResult

type VerifyResult struct {
	Repo          string  `json:"repo"`
	Command       string  `json:"command"`
	Cwd           string  `json:"cwd"`
	ExitCode      *int    `json:"exit_code"`
	Signal        *string `json:"signal"`
	Ok            bool    `json:"ok"`
	DurationMs    int64   `json:"duration_ms"`
	OutputTail    string  `json:"output_tail"`
	SkippedReason string  `json:"skipped_reason,omitempty"`
}

VerifyResult is one operator-defined check DD re-ran. Field names match console BatchJobVerification / VerifyResult.

type VerifyVerdict

type VerifyVerdict string

How a post-fix result compares to the same command before the agent ran.

  • pass — green now
  • regression — was green at baseline, red now: this job broke it
  • pre-existing — was red at baseline too: not this job's doing
  • blocked — could not run (bad repo name), or no baseline to compare to

Only `regression` and `blocked` stop a defect resolving. Without this, long-standing red (e.g. `flutter analyze` exiting 1 on 5 old infos) would block every resolve and read as damage the agent did.

const (
	VerdictPass        VerifyVerdict = "pass"
	VerdictRegression  VerifyVerdict = "regression"
	VerdictPreExisting VerifyVerdict = "pre-existing"
	VerdictBlocked     VerifyVerdict = "blocked"
)

func ClassifyResult

func ClassifyResult(result VerifyResult, baseline *VerificationRun) VerifyVerdict

type WtManifest

type WtManifest struct {
	// contains filtered or unexported fields
}

func CaptureWorktreeManifests

func CaptureWorktreeManifests(wts []git.WorktreeBinding, realByRepo, gitDirByRepo map[string]string, mio ManifestIO) ([]WtManifest, error)

func ManifestHead

func ManifestHead(repo, head, symRef string, detached bool) WtManifest

ManifestHead is a worktree manifest with HEAD state and no files.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL