Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 154 additions & 11 deletions scripts/architecture-baseline.json

Large diffs are not rendered by default.

4,580 changes: 4,080 additions & 500 deletions scripts/code-standards-baseline.json

Large diffs are not rendered by default.

97 changes: 76 additions & 21 deletions src/cloud/__tests__/execution-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ import {
} from "../provider.js"
import { runMain } from "../../test-runner.js"

interface MappingCase {
label: string
run: () => void
}

async function testResolveExecutionProviderName(): Promise<void> {
assert.equal(resolveExecutionProviderName("docker"), "docker")
assert.equal(resolveExecutionProviderName("openshell"), "openshell")
Expand All @@ -27,31 +32,81 @@ async function testResolveExecutionProviderName(): Promise<void> {
assert.equal(resolveExecutionProviderName("bogus"), "local")
}

async function testCreateCloudProviderMapping(): Promise<void> {
const docker = createCloudProvider("docker", {
docker: {
run: () => ({ exitCode: 0, output: "" }),
listContainers: () => [],
function dockerMappingCase(): MappingCase {
return {
label: "docker is mapped",
run: () => {
const docker = createCloudProvider("docker", {
docker: {
run: () => ({ exitCode: 0, output: "" }),
listContainers: () => [],
},
})
assert.ok(
docker instanceof DockerSessionProvider,
"docker is mapped",
)
assert.equal(docker.name, "docker")
},
})
assert.ok(docker instanceof DockerSessionProvider, "docker is mapped")
assert.equal(docker.name, "docker")
}
}

function localMappingCase(): MappingCase {
return {
label: "local is kept",
run: () => {
const local = createCloudProvider(
"local",
{ local: { dryRun: true } },
)
assert.ok(
local instanceof LocalProcessProvider,
"local is kept",
)
assert.equal(local.name, "local")
},
}
}

const local = createCloudProvider("local", { local: { dryRun: true } })
assert.ok(local instanceof LocalProcessProvider, "local is kept")
assert.equal(local.name, "local")
function defaultMappingCase(): MappingCase {
return {
label: "defaults map without the environment",
run: () => {
const docker = createCloudProvider("docker")
assert.ok(
docker instanceof DockerSessionProvider,
"docker default maps",
)
const local = createCloudProvider("local")
assert.ok(
local instanceof LocalProcessProvider,
"local default maps",
)
},
}
}

// The default (no options) also maps without touching the environment.
assert.ok(createCloudProvider("docker") instanceof DockerSessionProvider)
assert.ok(createCloudProvider("local") instanceof LocalProcessProvider)
function openshellMappingCase(): MappingCase {
return {
label: "openshell refuses its own path",
run: () => {
assert.throws(
() => createCloudProvider("openshell"),
/openshell-provider\.ts/,
"openshell routes to its own path",
)
},
}
}

// openshell keeps its own construction path — the factory refuses rather
// than silently dropping OpenShellSessionProviderOptions.
assert.throws(
() => createCloudProvider("openshell"),
/openshell-provider\.ts/,
"openshell routes to its own provider path",
)
async function testCreateCloudProviderMapping(): Promise<void> {
const entries = [
dockerMappingCase(),
localMappingCase(),
defaultMappingCase(),
openshellMappingCase(),
]
for (const entry of entries) entry.run()
}

async function testDockerPreflightHealthy(): Promise<void> {
Expand Down
228 changes: 228 additions & 0 deletions src/orchestrator/__tests__/resume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
runReviewStep,
runReworkStep,
resolveTargetGroups,
type ResumeGroupResult,
type ResumeTarget,
} from "../resume.js"
import { defaultState, loadStateSync, saveStateSync, type OrchestratorGroup, type OrchestratorState } from "../state.js"
Expand Down Expand Up @@ -1091,6 +1092,228 @@ async function testResumeMainDryRunPlansContinuation(): Promise<void> {
}
}

// ─── operator retry --retry-failed / --retry-group (issue #201) ───────

async function testParseResumeArgsRetryFlags(): Promise<void> {
const target = ["--repo", "/tmp/x", "--group", "w8"]
const repoArgs = (fl: string[]): string[] => [...target, ...fl]
const retry = parseResumeArgs(repoArgs(["--retry-failed"]))
assert.equal(retry.error, undefined)
assert.equal(retry.options.retryFailed, true)
assert.equal(retry.options.forceRetry, false)
const alias = parseResumeArgs(repoArgs(["--retry-group"]))
assert.equal(alias.error, undefined)
assert.equal(alias.options.retryFailed, true)
const force = parseResumeArgs(repoArgs(["--retry-failed", "--force-retry"]))
assert.equal(force.error, undefined)
assert.equal(force.options.retryFailed, true)
assert.equal(force.options.forceRetry, true)
}

/** `git -C <repo>` with output ignored. */
function gitQuiet(repo: string, args: string[]): void {
execFileSync("git", ["-C", repo, ...args], { stdio: "ignore" })
}

/** Commit a file on the current branch of `repo`, then add a linked
* worktree for `branch` — the real worktree shape the review/resume
* gates resolve git state against (no bare-subdir fixtures). */
async function setupRepoWithBranchWorktree(
repo: string,
branch: string,
workFiles: Array<[string, string, string]>,
): Promise<string> {
initGitRepo(repo)
configureGit(repo)
await fs.writeFile(path.join(repo, "base.txt"), "base\n", "utf-8")
commitFile(repo, "base.txt", "base\n", "base")
gitQuiet(repo, ["checkout", "-qb", branch])
for (const [rel, content, message] of workFiles) {
await fs.writeFile(path.join(repo, rel), content, "utf-8")
commitFile(repo, rel, content, message)
}
gitQuiet(repo, ["checkout", "-q", "main"])
const wtPath = path.join(repo, ".worktrees", "w1")
gitQuiet(repo, ["worktree", "add", "-q", wtPath, branch])
return wtPath
}

/** Fake the tracked upstream a linked worktree resolves in a real round
* (a bare fixture repo has no origin): committed progress is then
* salvageable via the committed-diff leg of hasRealWorktreeChanges. */
function fakeWorktreeUpstream(
repo: string,
wtPath: string,
branch: string,
): void {
const fetchspec = "+refs/heads/*:refs/remotes/origin/*"
gitQuiet(repo, ["update-ref", "refs/remotes/origin/master", "main"])
gitQuiet(repo, ["config", "remote.origin.url", repo])
gitQuiet(repo, ["config", "remote.origin.fetch", fetchspec])
gitQuiet(wtPath, ["config", `branch.${branch}.remote`, "origin"])
gitQuiet(wtPath, ["config", `branch.${branch}.merge`, "refs/heads/master"])
}

async function runRetryMain(
repo: string,
args: string[],
): Promise<{ exit: number; stdout: string }> {
return withCapturedStdout(() => resumeMain(["--repo", repo, ...args]))
}

async function writeFailedGroup(
repo: string,
branch: string,
summary: string,
): Promise<void> {
const group = baseGroup({ branch, status: "failed", exit_code: 1, summary })
writeState(repo, [group])
}

/** A failed group through runRetryMain, asserting the planned outcome. */
async function expectRetryMain(
repo: string,
args: string[],
exit: number,
needles: string[],
): Promise<string> {
const { exit: got, stdout } = await runRetryMain(repo, args)
assert.equal(got, exit)
for (const needle of needles) {
assert.ok(stdout.includes(needle), `expected ${needle}, got: ${stdout}`)
}
return stdout
}

/** Plain resume refuses a generic failure; --retry-failed plans it. */
async function assertRetryPlansContinuation(
repo: string,
branch: string,
wt: string,
): Promise<void> {
fakeWorktreeUpstream(repo, wt, branch)
// A generic failure (NOT iteration exhaustion, NOT a provider
// failure) with salvageable progress: plain resume refuses it, but
// --retry-failed forces the continuation spawn plan.
await writeFailedGroup(repo, branch, "headlesscode: task failed")
const plainArgs = ["--issue", "14", "--dry-run"]
await expectRetryMain(repo, plainArgs, 1, ["not continuable"])
const retryArgs = [...plainArgs, "--retry-failed"]
const wants = ["continuation 1", "run-worker.sh", "operator retry"]
await expectRetryMain(repo, retryArgs, 0, wants)
}

async function testRetryFailedPlansContinuation(): Promise<void> {
const repo = await tmpRepo()
const branch = "issues/w1-2026-08-28"
type WorkFile = [string, string, string]
const work: WorkFile[] = [["work.md", "partial work\n", "salvage"]]
const wt = await setupRepoWithBranchWorktree(repo, branch, work)
try {
await assertRetryPlansContinuation(repo, branch, wt)
} finally {
await fs.rm(repo, { recursive: true, force: true })
}
}

async function testRefusesEmptyWorktree(): Promise<void> {
const repo = await tmpRepo()
const branch = "issues/w1-2026-08-28"
await setupRepoWithBranchWorktree(repo, branch, [])
try {
// Empty worktree: checked out on its own branch with no divergence
// from base — the retry is refused instead of spawning a worker
// that would start from scratch.
await writeFailedGroup(repo, branch, "headlesscode: boom")
const noProgress = ["no salvageable progress", "--force-retry"]
const wantsOne = ["continuation 1"]
const issueArgs = ["--issue", "14"]
const retryArgs = [...issueArgs, "--retry-failed", "--dry-run"]
await expectRetryMain(repo, retryArgs, 1, noProgress)
await expectRetryMain(repo, [...retryArgs, "--force-retry"], 0, wantsOne)
} finally {
await fs.rm(repo, { recursive: true, force: true })
}
}

/** Minimal resumeGroup call: the caller sets status + retry flags. */
type RetryFlags = { retryFailed?: boolean; forceRetry?: boolean }
interface RetryCall {
repo: string
statePath: string
group: OrchestratorGroup
extra: RetryFlags
}
function retryCallFor(
repo: string,
group: OrchestratorGroup,
extra: RetryFlags,
): RetryCall {
return { repo, statePath: writeState(repo, [group]), group, extra }
}
type RetryOutcome = Pick<ResumeGroupResult, "outcome" | "message">
/** Shared resumeGroup options for the --retry-failed tests. */
const RETRY_GROUP_BASE = {
reviewMode: "deepseek-reviewer",
qaMode: "qa-agent",
reviewEnabled: false,
qaEnabled: false,
mode: "code",
maxReworkCycles: 3,
maxContinuations: 3,
forceReview: false,
dryRun: true,
} as const
async function runRetryGroup(c: RetryCall): Promise<RetryOutcome> {
const lines: string[] = []
const { repo, statePath, group } = c
const { retryFailed, forceRetry } = c.extra
const result = await resumeGroup({
...RETRY_GROUP_BASE,
repo,
statePath,
group,
retryFailed,
forceRetry,
write: (t) => lines.push(t),
})
return { outcome: result.outcome, message: result.message }
}

async function testRefusesDoneGroup(): Promise<void> {
const repo = await tmpRepo()
try {
initGitRepo(repo)
const group = baseGroup({ status: "done" })
const call = retryCallFor(repo, group, { retryFailed: true })
const result = await runRetryGroup(call)
assert.equal(result.outcome, "error")
const msg = result.message
const note = `explicit refusal, got: ${msg}`
assert.ok(msg.includes("not terminal-failed"), note)
} finally {
await fs.rm(repo, { recursive: true, force: true })
}
}

async function testMissingWorktreeNeverSpawns(): Promise<void> {
const repo = await tmpRepo()
try {
initGitRepo(repo)
// No worktree dir at all and no recorded branch that could be
// re-checked out: the retry must refuse, never spawn into the void.
const boom = "headlesscode: boom"
const group = baseGroup({ status: "failed", exit_code: 1, summary: boom })
const branchless = { ...group, branch: undefined }
const flags = { retryFailed: true, forceRetry: true }
const call = retryCallFor(repo, branchless, flags)
const result = await runRetryGroup(call)
assert.equal(result.outcome, "orphaned")
} finally {
await fs.rm(repo, { recursive: true, force: true })
}
}

// ─── resumeGroup real (non-dry-run) rebuild + cost recording (no LLM) ────────

async function testResumeGroupRebuildsAndRecordsCostWithoutReview(): Promise<void> {
Expand Down Expand Up @@ -1335,6 +1558,11 @@ const tests: Array<[string, () => Promise<void>]> = [
["resumeMain --dry-run: rebuild then review plan", testResumeMainDryRunRebuildThenReviewPlan],
["resumeMain --dry-run: reworks a recorded finding without re-review", testResumeMainDryRunReworksRecordedFinding],
["resumeMain --dry-run: plans a continuation on iteration exhaustion", testResumeMainDryRunPlansContinuation],
["parseRetryFlags (#201)", testParseResumeArgsRetryFlags],
["retryGenericFailure (#201)", testRetryFailedPlansContinuation],
["retryEmptyWorktree (#201)", testRefusesEmptyWorktree],
["retryDoneGroup (#201)", testRefusesDoneGroup],
["retryMissingWorktree (#201)", testMissingWorktreeNeverSpawns],
["resumeGroup (real): rebuilds stale running → done and records cost", testResumeGroupRebuildsAndRecordsCostWithoutReview],
["resumeGroup --dry-run leaves state untouched", testResumeGroupDryRunLeavesStateUntouched],
["resumeGroup reports in-flight for a genuinely running group", testResumeGroupInFlightWhenWorkerRunning],
Expand Down
Loading