Files
gstack/lib/ship-queue-gate.ts
T
cadbd0af15 v1.91.116.0 feat: field list 2 wave B: gstack-ship-queue, approval classes, state-machine review, pregate timing check, update-check main moves (#3235)
* fix(capy): the install trailer says behind=<n> and its fix, so a stale install shows in every relayed trailer (field list 2 item 13, #2378)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(capy): a lease records its holder's start identity, so a pid reused after a wake is reclaimed; a skipped session-start upgrade ends fail behind, never ok (GBRA-105, GBRA-106)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(lease): stale needs proof (unreadable or malformed identities keep the lease), ps identity is timezone-independent, and reclaim never deletes a concurrent renewal

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(autoplan): enforced round cap and spend budget, deferred close, public export without machine paths, opt-in durable checkpoints (field list 2 W5-W7)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(lease): one directory lock for publish, prune and reclaim; reclaim rereads the record judged stale, so a renewal is never deleted or hidden

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(lease): the directory lock names its holder; broken only when the holder is dead or its pid reused, unlock removes only its own lock, touch exits 3 under a live holder

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(lease): breakers serialize on .lock.break and reread the lock before removing it; gstack-skill-start reports a lease the held lock kept out

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs(lease): name the double-crash limit of breaking a dead lock

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(capy): --for review-voice install profile, no-Drive bootstrap command, reviewer prompt trailer (field list 2 W11)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 89bf556c11)

* test: pin review-voice row, helpers row and the no-Drive fallback in existing install tests

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 7f6c70459a)

* test: the DRIVER template names the reviewer trailer relay (pregate lane)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 2545d9a6d2)

* test(context-budget): capy skill eager ceiling for the review-voice subagent paragraph (W11; ratchet protocol, capture value)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(eval-plan): prereg diagnostics dry run (W8) and .gstack/eval-models.json lint (W9), WIP

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit b509096218)

* feat(eval-plan): W8/W9 tests, docs/eval-models.md, troubleshooting anchors, /eval-plan steps

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 9335e45de2)

* test(eval-plan): eval-plan/SKILL.md names only defined codes and accepted flags

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit a7a974d268)

* test(review-voice): the launch line points at the verdict's bun-only directory (#3233's launch contract)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(third-party-actions): the Aside drive-offer detector matches the product name, not the English idiom (paid run 38988927989 tpa-absent-linux false positive)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(autoplan): export refuses artifact paths outside the run before writing; a deferred close keeps earlier undecided findings; reopening CEO grants Eng its rerun (review of #3234)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(restamp): gate-ahead keeps the lane CHANGELOG entry when both PRs took the same tentative stamp (GBRA-102 diagnosis fixture)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 43c75a6bb6)

* test(tree-receipt): a real gbrain stamp pair is same-modulo-stamps under gbrain committed policy (W1 acceptance)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 6cf53f9fed)

* feat(ship-policy): gate_command, full_e2e and min_gstack_version; unknown keys stay fail-closed; validate prints introducing versions

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 878a7123d7)

* feat(ship-queue): gstack-ship-queue ready, stamp, verify and gate-ahead (WIP, tests next)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 409a5957ad)

* test(ship-queue): stamp journal and resume, verify from a separate clone, gate-ahead attempts, ready

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit ade554087b)

* docs(ship-policy): Run a shared merge queue; new keys and compatibility rule; troubleshooting anchors; /ship pointer

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 7fc73e8892)

* fix(ship): shared-queue pointer rides the show-effective ship: line (ship skeleton has 2 bytes of parity headroom)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 5b33d4a015)

* test(windows): curate the shared-queue tests out of the Windows subset (shebang spawns)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 8deee14728)

* test(fixtures): register the gbrain stamp-pair fixture as free-only

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 563a07aa03)

* test(ship-queue): receipt digest contract names lib/ship-queue.ts for its pregate lane

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 501637c258)

* feat(pregate): timing check flags elapsed-time bounds and sleep-then-assert in added test lines (W4)

lib/pregate/checks/timing.ts prints TIMING_ASSERTION: <file>:<line> <pattern>
and a TIMING_ASSERTIONS summary; gstack-timing-ok: <reason> in any comment
syntax on the line or the line above escapes one. It warns
(PREGATE_TIMING_ASSERTION): measured on gstack (9 of 47 test-touching
commits, 263 hits in the tree) and gbrain (37 of 95 commits; 31 of 38 sites
of the five timing-flake fixes), blocking would stop a fifth to two fifths
of test changes. Adds the /review checklist rule and the /investigate
timing-flake playbook.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit a3b86b10b2)

* feat(update-check): an equal VERSION with a moved main is an upgrade, via the compare API (W12)

When VERSION matches but ls-remote's main SHA differs from this checkout's
HEAD, bin/gstack-update-check asks the GitHub compare API (status, ahead_by)
through the existing receipted curl and prints
UPGRADE_AVAILABLE <ver> <ver>+<n> <sha>; a diverged or unreadable compare is
CHECK_FAILED (unknown), and behind/identical is up to date. Never fetches.

The cache gains an IDENTITY line (head, compared remote SHA, upstream): an
outcome replays only for the same HEAD and upstream, a same-remote refresh
reuses it without another compare, and a git checkout ignores a legacy
one-line cache (non-git installs keep the one-line format). The snooze is
keyed by the SHA. gstack-upgrade's question, snooze note and What's New step
handle the four-field line; gstack-skill-end reports it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 421e66d2a4)

* fix(pregate): treat planning and evidence markdown as an empty lane

A docs-only diff with no .gstack/pregate.json failed lanes as
PREGATE_NO_LANE. Planning and evidence Markdown is now a docs/no-tests
empty lane. Unmapped source files still fail closed.

Co-authored-by: Nick <surlymo@apache.org>
(cherry picked from commit e8793e59e8)

* fix(pregate): keep test-read markdown on its test lane

Unmarked Markdown that no test depends on is a docs/no-tests empty lane.
A file a test reads, including a fixture, still selects that test through
the import graph. Unmapped source and unreferenced test-tree files still
fail closed.

Co-authored-by: Nick <surlymo@apache.org>
(cherry picked from commit 7aabbddf3d)

* test(pregate): reviewer edges for the docs/no-tests empty lane (#3215)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 2fb3fa8613)

* test(pregate): requires-remote on a gbrain-shaped repo (ci:ubicloud, UBI_OWNER) (W10)

A base pregate.json with gbrain's dependencies and remote_gate
"bun run ci:ubicloud" (a package script whose stub needs UBICLOUD_API_KEY,
names VMs from UBI_OWNER and prints PREGATE_REMOTE). Under 8 cores the test
tier is one obligation naming the command; --remote passes the caller's
UBI_OWNER and key through and clears it on the report; without the key the
gate's own error shows and the obligation stays uncleared. #3190's path
needed no change.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 4d69ff02df)

* test(pregate): the ship receipt counts the timing check (7 checks)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit cb03ef67e7)

* test(context-budget): gstack-upgrade eager ceiling for the W12 equal-version upgrade question (ratchet protocol, capture value)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* feat(approval-classes): gstack-approval-classes and ship-receipt citation enforcement (W2, WIP)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 847c7dae3d)

* feat(approval-classes): tests, docs, /review and /ship wiring (W2)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 269bd5b8b5)

* feat(review): state-machines specialist and gstack-state-matrix round-trip check with a captured #6792 regression (W3)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 1a634979c6)

* fix(review-army): keep the --simplification force flag pinned; approval test timeouts

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 789d392bce)

* test(free-fixtures): register the state-matrix-6792 fixture

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 1bacef296d)

* test(state-matrix): cover state-machines NEVER_GATE in gstack-specialist-stats

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
(cherry picked from commit 859063d56f)

* test(fixtures): register the pregate-timing fixtures as free-only (W4)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(ship-queue): full_e2e needs bound gate evidence in ready and verify, CI reads every check-run page and commit status, next: quotes its paths (review #3235 P1-1, P1-5, P2-1)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(pregate): timing reads a native diff and never passes an unread one

The timing check's git diff honored diff.external, textconv and
diff.noprefix, so a configured driver hid every added line and the check
passed. Run it with --no-ext-diff --no-textconv and explicit a/ b/
prefixes, and report a git diff that fails or does not finish as
incomplete (PREGATE_INCOMPLETE), which a warn downgrade does not soften.

Review of #3235, sibling of P1-4 (lib/pregate/checks/timing.ts:189).

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(approval-classes): only affirmative APPROVED evidence counts, explicit tokens are authoritative, native diffs fail closed (review #3235 P1-2, P1-3, P1-4)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(state-matrix): detect reads the native diff, ignoring diff.external and textconv (review #3235 P1-4)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(e2e): review-army-state-matrix behavior case on the #6792 fixture (field list 2, W3)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(review-army): tighten the State Machines dispatch line so /ship stays under its parity size ratio with main's #3231 review-army text

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(approval-classes): only top-level approval lines count; quoted, fenced, indented-code and commented text never does (review #3235 r2)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(approval-classes): approval evidence is the first non-blank line only, at column 0 (review #3235 r3)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test(autoplan-budget): bind the reservation expectation to lib/autoplan-budget's default estimate (test-of-test ratchet)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: keep gstack-upgrade under its size budget, exempt state-matrix's fetch hint, fit the periodic plan's 37 slices

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(evals): the docs observer accepts the spawned-prefixed gstack-skill-start --help read

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(windows): curate capy-review-voice out of the Windows subset (POSIX launcher contract)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: changelog entry for field list 2 wave A

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: stamp v1.91.115.0

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: the scope-signal clarity check follows helper-printed signals; the hermetic update-check fixture writes the identity cache

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* refactor: move the release-path result codes to lib/result-codes-release.ts (module-size ratchet); fit the periodic plan's 38 slices

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: changelog entry for field list 2 wave B

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* chore: stamp v1.91.116.0

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: copy lib/result-codes-release.ts wherever a fixture copies lib/result-codes.ts; the scope-signal check requires the helper's computed emission

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: state-matrix stats test resolves its slug under its own state root (home containment)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(windows): curate pregate-docs-lane-review out of the Windows subset (runBin shebang, like the other pregate fixtures)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix(windows): curate pregate-remote-gbrain out of the Windows subset (runBin shebang, like pregate-remote)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Nick <surlymo@apache.org>
2026-10-17 03:32:16 +00:00

233 lines
14 KiB
TypeScript

/**
* ship-queue-gate — gate-ahead attempts for bin/gstack-ship-queue (field list
* 2, W1), over gstack-restamp's --after primitive (lib/restamp.ts).
*
* Each preparation is an attempt with an immutable id and its own worktree
* under .gstack/tmp/ship-queue/gate-ahead/<pr>/<attempt>/, so concurrent
* preparations never share or delete each other's trees. The record binds
* the predecessor and branch heads, the merge tree (recomputed with
* `git merge-tree --write-tree` and refused unless it equals the worktree's
* merge), the gated head and tree, the stamp patch between them and the gate
* command. `--record` binds a gate result to that attempt only after its
* worktree still holds the gated commit, retains the log beside the record,
* then removes the attempt's own worktree. The current attempt for a PR is the
* newest preparation; recording an older one never replaces it. The
* coordinator's verify reproduces merge tree and gated tree from the record
* alone (recomputeMergeTree, applyStampPatch), so the gated commit never has
* to leave the lane's machine.
*/
import { createHash, randomBytes } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { mergeChangelogs } from './changelog-check';
import { ensureTmpExcluded, restamp, versionFiles } from './restamp';
import type { ResultCodeName } from './result-codes';
import type { ShipPolicy } from './ship-policy';
export const QUEUE_DIR_REL = '.gstack/tmp/ship-queue';
export const GATE_AHEAD_DIR_REL = `${QUEUE_DIR_REL}/gate-ahead`;
export interface GateResult { exit: number; log: string; log_sha256: string; recorded_at: string }
export interface AttemptRecord {
schema_version: 1; kind: 'gate-ahead'; attempt: string; pr: string; predecessor_pr: string; predecessor_head: string; branch_head: string;
merge_tree: string; gated_head: string; gated_tree: string; version: string; base: { ref: string; sha: string }; policy: string;
gate_command: string | null; command_sha256: string | null; worktree: string; prepared_at: string; stamp_patch: string;
state: 'prepared' | 'recorded'; result?: GateResult;
}
export interface QueueFailure { code: ResultCodeName; message: string; fix?: string }
export function sha256(buf: Buffer | string): string { return createHash('sha256').update(buf).digest('hex'); }
export function git(cwd: string, args: string[], env?: NodeJS.ProcessEnv, input?: string | Buffer): { ok: boolean; out: string; err: string; status: number | null } {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 120_000, env: env ?? process.env, input, maxBuffer: 64 * 1024 * 1024 });
return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim(), status: r.status };
}
export function writeJsonAtomic(file: string, value: unknown): void {
fs.mkdirSync(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n');
fs.renameSync(tmp, file);
}
function prDir(repoRoot: string, pr: string): string { return path.join(repoRoot, GATE_AHEAD_DIR_REL, pr); }
export function attemptFile(repoRoot: string, pr: string, attempt: string): string { return path.join(prDir(repoRoot, pr), `${attempt}.json`); }
export function readAttempt(file: string): AttemptRecord | null {
try { const r = JSON.parse(fs.readFileSync(file, 'utf8')); return r?.kind === 'gate-ahead' && r.schema_version === 1 ? r : null; } catch { return null; }
}
/** Every attempt recorded for a PR, oldest preparation first. */
export function listAttempts(repoRoot: string, pr: string): AttemptRecord[] {
const dir = prDir(repoRoot, pr);
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir).filter(f => f.endsWith('.json')).map(f => readAttempt(path.join(dir, f))).filter((r): r is AttemptRecord => !!r)
.sort((a, b) => a.prepared_at.localeCompare(b.prepared_at) || a.attempt.localeCompare(b.attempt));
}
export function currentAttempt(repoRoot: string, pr: string): AttemptRecord | null {
return listAttempts(repoRoot, pr).at(-1) ?? null;
}
/**
* The gate-ahead merge as `git merge --no-ff` of the branch and the
* predecessor would leave it after restamp's conflict rules: version files
* take the predecessor's side, the CHANGELOG merges through mergeChangelogs,
* any other conflict is unresolvable. Computed in object storage only.
*/
export function recomputeMergeTree(repoRoot: string, branchHead: string, predecessorHead: string, policy: ShipPolicy, versionRel: string): { tree: string } | { error: string } {
const r = git(repoRoot, ['merge-tree', '--write-tree', branchHead, predecessorHead]);
const lines = r.out.split('\n');
const tree = lines[0]?.trim() ?? '';
if (r.status === 0 && /^[0-9a-f]{40,64}$/.test(tree)) return { tree };
if (r.status !== 1 || !/^[0-9a-f]{40,64}$/.test(tree)) return { error: `git merge-tree failed: ${r.err || r.out.slice(0, 200)}` };
const stages = new Map<string, Map<number, string>>();
for (const line of lines.slice(1)) {
if (!line.trim()) break;
const m = /^(\d{6}) ([0-9a-f]{40,64}) ([123])\t(.+)$/.exec(line);
if (!m) continue;
const entry = stages.get(m[4]!) ?? new Map<number, string>();
entry.set(Number(m[3]), m[2]!);
stages.set(m[4]!, entry);
}
const stampFiles = versionFiles(repoRoot, versionRel);
const resolved: Array<{ path: string; blob: string }> = [];
for (const [file, entry] of stages) {
const ours = entry.get(2);
const theirs = entry.get(3);
if (!ours || !theirs) return { error: `${file} conflicts beyond a content merge (added or deleted on one side)` };
if (file === policy.changelog) {
const text = (sha: string) => git(repoRoot, ['cat-file', 'blob', sha]).out + '\n';
const merged = mergeChangelogs(text(ours), text(theirs));
if (merged === null) return { error: `${file} conflicts beyond a heading move` };
const blob = git(repoRoot, ['hash-object', '-w', '--stdin'], undefined, merged);
if (!blob.ok) return { error: `cannot write the merged ${file}: ${blob.err}` };
resolved.push({ path: file, blob: blob.out });
} else if (stampFiles.includes(file)) resolved.push({ path: file, blob: theirs });
else return { error: `${file} conflicts outside the version files and the CHANGELOG` };
}
return withIndex(repoRoot, tree, index => {
for (const { path: p, blob } of resolved) {
const mode = git(repoRoot, ['ls-tree', tree, '--', p], index).out.split(/\s/)[0] || '100644';
const u = git(repoRoot, ['update-index', '--add', '--cacheinfo', `${mode},${blob},${p}`], index);
if (!u.ok) return { error: `cannot stage the resolved ${p}: ${u.err}` };
}
const w = git(repoRoot, ['write-tree'], index);
return w.ok ? { tree: w.out } : { error: `write-tree failed: ${w.err}` };
});
}
/** The gated tree from a merge tree and the recorded stamp patch, in a throwaway index. */
export function applyStampPatch(repoRoot: string, mergeTree: string, patch: string): { tree: string } | { error: string } {
if (!patch.trim()) return { tree: mergeTree };
return withIndex(repoRoot, mergeTree, index => {
const a = git(repoRoot, ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'], index, patch);
if (!a.ok) return { error: `the recorded stamp patch does not apply to the recomputed merge: ${a.err.slice(0, 200)}` };
const w = git(repoRoot, ['write-tree'], index);
return w.ok ? { tree: w.out } : { error: `write-tree failed: ${w.err}` };
});
}
function withIndex<T>(repoRoot: string, tree: string, fn: (env: NodeJS.ProcessEnv) => T): T | { error: string } {
const gitDir = git(repoRoot, ['rev-parse', '--absolute-git-dir']).out;
const indexFile = path.join(gitDir, `gstack-ship-queue-${process.pid}-${randomBytes(4).toString('hex')}.index`);
const env = { ...process.env, GIT_INDEX_FILE: indexFile };
try {
const rt = git(repoRoot, ['read-tree', tree], env);
if (!rt.ok) return { error: `read-tree ${tree} failed: ${rt.err}` };
return fn(env);
} finally { fs.rmSync(indexFile, { force: true }); }
}
/** A commit object for a bare tree (fixed identity and date), so tree-receipt can compare it. */
export function commitForTree(repoRoot: string, tree: string, message: string): string | null {
const env = { ...process.env, GIT_AUTHOR_NAME: 'gstack-ship-queue', GIT_AUTHOR_EMAIL: 'ship-queue@gstack.local', GIT_COMMITTER_NAME: 'gstack-ship-queue',
GIT_COMMITTER_EMAIL: 'ship-queue@gstack.local', GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z', GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z' };
const c = git(repoRoot, ['commit-tree', tree, '-m', message], env);
return c.ok ? c.out : null;
}
export interface PrepareOptions {
repoRoot: string; base: string; pr: string; after: string; predecessorRef?: string; allowRepoCommands: boolean;
policy: ShipPolicy; versionRel: string; now?: Date;
}
/** Prepare one attempt: restamp --after into the attempt's own worktree, then bind and verify its record. */
export function prepareGateAhead(o: PrepareOptions): { record: AttemptRecord; file: string } | QueueFailure {
const now = o.now ?? new Date();
const attempt = `${now.toISOString().replace(/[-:.]/g, '')}-${randomBytes(3).toString('hex')}`;
const dir = path.join(prDir(o.repoRoot, o.pr), attempt);
const worktree = path.join(dir, 'worktree');
ensureTmpExcluded(o.repoRoot);
fs.mkdirSync(dir, { recursive: true });
const r = restamp({
repoRoot: o.repoRoot, base: o.base, after: { pr: o.after, ref: o.predecessorRef }, pr: o.pr, policyFrom: 'base',
allowRepoCommands: o.allowRepoCommands, dryRun: false, gateWorktree: worktree, now,
});
if (r.status !== 'gate-ahead' || !r.gateAhead) {
fs.rmSync(dir, { recursive: true, force: true });
return { code: r.code ?? 'RESTAMP_CONFLICT', message: `${r.message ?? `gstack-restamp --after returned ${r.status}`}`, fix: r.fix };
}
const ga = r.gateAhead;
const drop = (code: ResultCodeName, message: string): QueueFailure => {
git(o.repoRoot, ['worktree', 'remove', '--force', worktree]);
fs.rmSync(dir, { recursive: true, force: true });
git(o.repoRoot, ['worktree', 'prune']);
return { code, message };
};
const mergeTree = git(o.repoRoot, ['rev-parse', `${ga.gated_head}^^{tree}`]).out;
const recomputed = recomputeMergeTree(o.repoRoot, ga.branch_head, ga.predecessor_head, o.policy, o.versionRel);
if ('error' in recomputed) return drop('QUEUE_PROOF_MISSING', `the gate-ahead merge cannot be recomputed with git merge-tree (${recomputed.error}); nothing recorded`);
if (recomputed.tree !== mergeTree) return drop('QUEUE_PROOF_MISSING', `git merge-tree gives ${recomputed.tree.slice(0, 12)} but the gate-ahead merge is ${mergeTree.slice(0, 12)}; a coordinator could not reproduce it, so nothing is recorded`);
const patch = git(o.repoRoot, ['diff', '--binary', '--full-index', '--no-color', '--no-ext-diff', '--no-renames', mergeTree, ga.gated_tree]).out;
const replay = applyStampPatch(o.repoRoot, mergeTree, patch ? patch + '\n' : '');
if ('error' in replay || replay.tree !== ga.gated_tree) return drop('QUEUE_PROOF_MISSING', `the stamp patch does not reproduce the gated tree ${ga.gated_tree.slice(0, 12)}; nothing recorded`);
const record: AttemptRecord = {
schema_version: 1, kind: 'gate-ahead', attempt, pr: o.pr, predecessor_pr: ga.predecessor_pr, predecessor_head: ga.predecessor_head,
branch_head: ga.branch_head, merge_tree: mergeTree, gated_head: ga.gated_head, gated_tree: ga.gated_tree, version: ga.version,
base: { ref: r.base?.ref ?? `origin/${o.base}`, sha: r.base?.sha ?? '' }, policy: r.policy ?? '', gate_command: o.policy.gate_command,
command_sha256: o.policy.gate_command ? sha256(o.policy.gate_command) : null, worktree, prepared_at: now.toISOString(),
stamp_patch: patch ? patch + '\n' : '', state: 'prepared',
};
const file = attemptFile(o.repoRoot, o.pr, attempt);
writeJsonAtomic(file, record);
return { record, file };
}
export interface RecordOptions { repoRoot: string; pr: string; attempt: string; exit: number; log: string; now?: Date }
/**
* Bind a gate result to one attempt: its worktree must still hold the gated
* commit with no tracked edit; the log is copied beside the record before the
* attempt's own worktree is removed. An identical retry returns the stored
* result; a different result for a recorded attempt is refused.
*/
export function recordGateAhead(o: RecordOptions): { record: AttemptRecord; file: string; current: AttemptRecord | null; repeated: boolean } | QueueFailure {
const file = attemptFile(o.repoRoot, o.pr, o.attempt);
const rec = readAttempt(file);
if (!rec || rec.pr !== o.pr || rec.attempt !== o.attempt) return { code: 'GATE_AHEAD_ATTEMPT_INVALID', message: `no gate-ahead attempt ${o.attempt} for #${o.pr}` };
if (!fs.existsSync(o.log)) return { code: 'GATE_AHEAD_ATTEMPT_INVALID', message: `log ${o.log} does not exist` };
const logSha = sha256(fs.readFileSync(o.log));
const current = currentAttempt(o.repoRoot, o.pr);
if (rec.state === 'recorded') {
if (rec.result?.exit === o.exit && rec.result.log_sha256 === logSha) return { record: rec, file, current, repeated: true };
return { code: 'GATE_AHEAD_ATTEMPT_INVALID', message: `attempt ${o.attempt} already recorded exit ${rec.result?.exit} (log ${rec.result?.log_sha256.slice(0, 12)}); a different result is refused` };
}
if (!fs.existsSync(rec.worktree)) return { code: 'GATE_AHEAD_ATTEMPT_INVALID', message: `attempt ${o.attempt}'s worktree ${rec.worktree} is gone` };
const head = git(rec.worktree, ['rev-parse', 'HEAD']).out;
const dirty = git(rec.worktree, ['status', '--porcelain', '--untracked-files=no']).out;
if (head !== rec.gated_head || dirty) {
return { code: 'GATE_AHEAD_ATTEMPT_INVALID', message: `attempt ${o.attempt}'s worktree no longer holds the gated commit ${rec.gated_head.slice(0, 12)} (HEAD ${head.slice(0, 12)}${dirty ? ', tracked edits' : ''}); the gate result is not bound to the gated tree` };
}
const kept = path.join(prDir(o.repoRoot, o.pr), `${o.attempt}.log`);
fs.copyFileSync(o.log, kept);
rec.result = { exit: o.exit, log: path.relative(o.repoRoot, kept), log_sha256: logSha, recorded_at: (o.now ?? new Date()).toISOString() };
rec.state = 'recorded';
writeJsonAtomic(file, rec);
git(o.repoRoot, ['worktree', 'remove', '--force', rec.worktree]);
fs.rmSync(path.dirname(rec.worktree), { recursive: true, force: true });
git(o.repoRoot, ['worktree', 'prune']);
return { record: rec, file, current, repeated: false };
}