Skip to content
Closed
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
69 changes: 42 additions & 27 deletions packages/loopover-miner/lib/attempt-worktree.d.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,46 @@
import type { WorktreeExecFn } from "@loopover/engine";
import type { RunGitFn } from "./repo-clone.js";

export function createRealWorktreeExec(timeoutMs?: number): WorktreeExecFn;

export type PrepareAttemptWorktreeOptions = {
baseBranch?: string;
cloneBaseDir?: string;
env?: Record<string, string | undefined>;
exec?: WorktreeExecFn;
timeoutMs?: number;
remoteUrl?: string;
runGit?: RunGitFn;
baseBranch?: string;
cloneBaseDir?: string;
env?: Record<string, string | undefined>;
exec?: WorktreeExecFn;
timeoutMs?: number;
remoteUrl?: string;
runGit?: RunGitFn;
};

export type PrepareAttemptWorktreeResult =
| { ok: true; worktreePath: string; branchName: string; repoPath: string }
| { ok: false; repoPath?: string; error: string };

export function prepareAttemptWorktree(
repoFullName: string,
attemptId: string,
options?: PrepareAttemptWorktreeOptions,
): Promise<PrepareAttemptWorktreeResult>;

export function cleanupAttemptWorktree(
repoPath: string,
worktreePath: string,
attemptOk: boolean,
options?: { exec?: WorktreeExecFn; timeoutMs?: number },
): Promise<{ ok: boolean; removed: boolean; error?: string }>;
export type PrepareAttemptWorktreeResult = {
ok: true;
worktreePath: string;
branchName: string;
repoPath: string;
} | {
ok: false;
repoPath?: string;
error: string;
};
/**
* Real child_process-backed implementation of the engine's WorktreeExecFn contract. Resolves (never
* rejects) on error/timeout, mirroring coding-agent-construction.js's createRealCliSubprocessSpawn -- a
* failed `git worktree add`'s stderr is the diagnosable signal, not something to lose to an unhandled
* rejection.
*/
export declare function createRealWorktreeExec(timeoutMs?: number): WorktreeExecFn;
/**
* Prepare a real, isolated git worktree for one attempt: ensure the target repo's base clone exists and is
* current, then create a fresh `git worktree` off it on a deterministically-named branch. Fails closed
* (`ok: false`) on any step's failure rather than handing back a half-prepared directory.
*/
export declare function prepareAttemptWorktree(repoFullName: string, attemptId: string, options?: PrepareAttemptWorktreeOptions): Promise<PrepareAttemptWorktreeResult>;
/**
* Tear down an attempt's worktree once the attempt concludes, per the engine's own retention policy: a
* failed attempt's worktree is RETAINED for post-mortem inspection, a succeeded one is removed.
*/
export declare function cleanupAttemptWorktree(repoPath: string, worktreePath: string, attemptOk: boolean, options?: {
exec?: WorktreeExecFn;
timeoutMs?: number;
}): Promise<{
ok: boolean;
removed: boolean;
error?: string;
}>;
99 changes: 35 additions & 64 deletions packages/loopover-miner/lib/attempt-worktree.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

95 changes: 95 additions & 0 deletions packages/loopover-miner/lib/attempt-worktree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { spawn } from "node:child_process";
import { addWorktree, removeWorktree, shouldRetainWorktree } from "@loopover/engine";
import type { WorktreeExecFn, WorktreeExecResult } from "@loopover/engine";
import { ensureRepoCloned } from "./repo-clone.js";
import type { RunGitFn } from "./repo-clone.js";

// Real attempt-worktree preparation (#5132, Wave 3.5 follow-up). Composes ensureRepoCloned (repo-clone.js,
// the missing base-clone-management step) with @loopover/engine's already-built, already-tested
// addWorktree/removeWorktree primitives -- which existed but were never called from this package, so
// `workingDirectory` handed to runIterateLoop was always just an empty directory with no real git repo in
// it. This is the caller that finally exercises them for real.

const DEFAULT_TIMEOUT_MS = 120_000;

export type PrepareAttemptWorktreeOptions = {
baseBranch?: string;
cloneBaseDir?: string;
env?: Record<string, string | undefined>;
exec?: WorktreeExecFn;
timeoutMs?: number;
remoteUrl?: string;
runGit?: RunGitFn;
};

export type PrepareAttemptWorktreeResult =
| { ok: true; worktreePath: string; branchName: string; repoPath: string }
| { ok: false; repoPath?: string; error: string };

/**
* Real child_process-backed implementation of the engine's WorktreeExecFn contract. Resolves (never
* rejects) on error/timeout, mirroring coding-agent-construction.js's createRealCliSubprocessSpawn -- a
* failed `git worktree add`'s stderr is the diagnosable signal, not something to lose to an unhandled
* rejection.
*/
export function createRealWorktreeExec(timeoutMs = DEFAULT_TIMEOUT_MS): WorktreeExecFn {
return (cmd, args, opts) =>
new Promise<WorktreeExecResult>((resolve) => {
const child = spawn(cmd, [...args], { cwd: opts.cwd, stdio: ["ignore", "pipe", "pipe"] });
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill("SIGKILL");
resolve({ code: null, stdout, stderr: `${stderr}\ntimed_out_after_${timeoutMs}ms`.trim() });
}, timeoutMs);
child.stdout?.on("data", (chunk) => {
stdout += chunk.toString("utf8");
});
child.stderr?.on("data", (chunk) => {
stderr += chunk.toString("utf8");
});
child.on("error", (err) => {
clearTimeout(timer);
resolve({ code: null, stdout, stderr: err.message });
});
child.on("close", (code) => {
clearTimeout(timer);
resolve({ code, stdout, stderr });
});
});
}

/**
* Prepare a real, isolated git worktree for one attempt: ensure the target repo's base clone exists and is
* current, then create a fresh `git worktree` off it on a deterministically-named branch. Fails closed
* (`ok: false`) on any step's failure rather than handing back a half-prepared directory.
*/
export async function prepareAttemptWorktree(
repoFullName: string,
attemptId: string,
options: PrepareAttemptWorktreeOptions = {},
): Promise<PrepareAttemptWorktreeResult> {
const cloneResult = await ensureRepoCloned(repoFullName, options);
if (!cloneResult.ok) return { ok: false, error: cloneResult.error ?? "ensure_repo_cloned_failed" };

const exec = options.exec ?? createRealWorktreeExec(options.timeoutMs);
const baseBranch = typeof options.baseBranch === "string" && options.baseBranch.trim() ? options.baseBranch.trim() : "main";
const added = await addWorktree({ exec, repoPath: cloneResult.repoPath, baseBranch, attemptId });
if (!added.ok) return { ok: false, repoPath: cloneResult.repoPath, error: added.error ?? "git_worktree_add_failed" };

return { ok: true, worktreePath: added.plan.worktreePath, branchName: added.plan.branchName, repoPath: cloneResult.repoPath };
}

/**
* Tear down an attempt's worktree once the attempt concludes, per the engine's own retention policy: a
* failed attempt's worktree is RETAINED for post-mortem inspection, a succeeded one is removed.
*/
export function cleanupAttemptWorktree(
repoPath: string,
worktreePath: string,
attemptOk: boolean,
options: { exec?: WorktreeExecFn; timeoutMs?: number } = {},
): Promise<{ ok: boolean; removed: boolean; error?: string }> {
const exec = options.exec ?? createRealWorktreeExec(options.timeoutMs);
return removeWorktree({ exec, repoPath, worktreePath, retain: shouldRetainWorktree(attemptOk) });
}
34 changes: 22 additions & 12 deletions packages/loopover-miner/lib/claim-adjudication.d.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
/** An observed claim on an issue: a PR/claimant number plus when it claimed the linked issue (if known). */
export type ObservedClaim = {
number: number;
claimedAt?: string | null | undefined;
number: number;
claimedAt?: string | null | undefined;
};

/** The engine `DuplicateClaimMember` shape this module bridges an {@link ObservedClaim} to. */
export type ClaimMember = {
number: number;
linkedIssueClaimedAt: string | null;
number: number;
linkedIssueClaimedAt: string | null;
};

/** The adjudication result: the go/no-go `isWinner`, plus a DISPLAY-only `winnerNumber` (null when not determinable). */
export type ClaimAdjudication = {
isWinner: boolean;
winnerNumber: number | null;
isWinner: boolean;
winnerNumber: number | null;
};

export function toClaimMember(claim: ObservedClaim): ClaimMember;

export function adjudicateSoftClaim(self: ObservedClaim, competing?: readonly ObservedClaim[]): ClaimAdjudication;
/**
* Map an observed claim record to the engine's `DuplicateClaimMember`. The field names deliberately DIFFER — the
* local ledger / observed data expose `claimedAt`, the engine election reads `linkedIssueClaimedAt` — so the bridge
* is explicit (they are not interchangeable by accident of naming). `createdAt` is intentionally omitted: the
* election ignores it (an older PR can claim a linked issue later by editing its body). Pure.
*/
export declare function toClaimMember(claim: ObservedClaim): ClaimMember;
/**
* Adjudicate whether THIS miner's soft-claim wins a contested issue. `self` is this miner's claim and `competing`
* is the publicly-observable set of OTHER open PRs linking the same issue; each entry is `{ number, claimedAt }`.
* Returns the go/no-go `isWinner` (driven ONLY by `isDuplicateClusterWinnerByClaim`) plus a DISPLAY-only
* `winnerNumber` (from `resolveDuplicateClusterWinnerNumber`, for surfacing "you lost this claim to PR #N" to the
* operator — never for the decision). Pure — no IO. Fail-closed: a missing/sparse claim time loses; the winner is
* `null` when the ordering is too sparse to be sure (it never guesses). An empty `competing` list ⇒ trivial winner.
*/
export declare function adjudicateSoftClaim(self: ObservedClaim, competing?: readonly ObservedClaim[]): ClaimAdjudication;
Loading
Loading