mirror of
https://github.com/garrytan/gstack.git
synced 2026-10-31 22:14:25 +01:00
* feat(ship-queue): require a current /ship receipt before READY, train build and train merge Garry, 2026-10-25: use the gstack ship skill before merging PRs. ready printed SHIP_RECEIPT: none as information and returned ok, so the pool was READY'd without /ship. Now ready, train build (dry run included) and verify --train refuse with QUEUE_RECEIPT_MISSING or QUEUE_RECEIPT_STALE from the PR body alone; verify accepts the receipt written for the pinned head when the current head is its stamp commit. gstack-ship-receipt result is /ship's terminal step (GSTACK_RESULT: skill=ship, run dir with the head and receipt), unattended /ship may update an existing PR's body, and INSTALL_UNVERIFIED with no verdict names the project directory to install from (GSTA-85). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(ship): pin Step 22 in workflow-required-steps and tighten the ship skeleton Gate edit: test/fixtures/workflow-required-steps.json pins the new "## Step 22: Terminal line (every run)" heading (strengthens: a later edit that drops the terminal line turns the required-steps test red). Steps 14, 16, 18, 20 and 22 prose tightened so the carve-guards raise shrinks to 81,600 / 1.6740 (measured skeleton 81,535, union 314,027). Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: pre-landing review fixes (ready at the stamp commit, screen on a stale merge ref, ship-run.json) - ready accepts the pin's receipt at a slot's stamp commit (plus the slot-2 merge of main), as verify --train already did; a real edit stays STALE - ready --screen refuses QUEUE_SCREEN_STALE_REF when refs/pull/<n>/merge is missing or merges an older head; a finished screen that planned 0 cases is never followed, and train build seats that slot unscreened (GSTA-95 on #3431) - gstack-ship-receipt result writes ship-run.json (a /ship record, not a run v1 manifest), validates --head, and prints status=incomplete on gh failures - bindReceipt takes an optional pr and renders one-line SHIP_RECEIPT lines - tests for every state-matrix cell the review named; the train fixture's merge ref is a real merge commit Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: cycle-2 review fixes (private screen scratch, no bare-merge receipt reuse, 12-hex --head, one receipt scrub) and align the unattended hook text with the GSTACK_RESULT writers (GSTA-91) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: adversarial-review fixes (result refuses an unpushed HEAD, resolves --out and reports unwritable records; ready names a failed merge-ref fetch; unattended /ship never runs gh pr ready) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: close review-cycle gaps (a stamp must change a stamp file, result requires a full --head and fails closed without headRefOid, digits-only --pr) with tests for every cycle-3 branch Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test: give the fsck-rejected merge-ref spawns a timeout (spawnsync tripwire) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: detect a hollow screen from the plan it uploads (no paid-plan artifact or nothing planned), correct two troubleshooting facts, and normalise result --pr Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(hollow-screen): read manifest.json by name, list artifacts by name, say when the plan is unreadable; lowercase result --head Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test(hollow-screen): expired and unreadable run rows, uppercase --head; docs name every SCREEN: literal Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix(train build): say when the repository slug is unreadable instead of counting the screen silently Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: name an ls-remote failure in ready --screen, refuse result --pr with --body, cap echoed receipt errors, tell an unreadable install verdict from a missing one Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * test: ls-remote refusal, --pr with --body, capped receipt errors, unreadable slug and verdict (both twins); docs name the new literals Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * fix: scrub Unicode line separators from receipt text, report an unreadable --body as incomplete, refuse unsupported verdict schemas in the bash twin 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>
301 lines
21 KiB
TypeScript
Executable File
301 lines
21 KiB
TypeScript
Executable File
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
|
/**
|
|
* gstack-ship-receipt — the handoff record, identifiers first (plan C5).
|
|
*
|
|
* gstack-ship-receipt write [--pr <n>] [--head <sha>] [--base <ref>] [--version <X>] [--gated-tree <sha>]
|
|
* [--predecessor <sha>] [--gate <json|@file>] [--ci <json|@file>] [--spend-usd <n>]
|
|
* [--session-kind <k>] [--artifacts-consumed <n>/<m>] [--run <id>] [--thread <id>]
|
|
* [--receipt <tree-receipt.json>] [--policy <label>] [--preregistration <text>] [--history <text>]
|
|
* [--pregate <pregate.json>] [--issues <json|@file>] [--approval <line>]... [--approval-run <dir>]...
|
|
* [--out <file>] [--body <pr-body.md>] [--json]
|
|
* gstack-ship-receipt read --pr <n> [--repo <owner/repo>] [--json]
|
|
* gstack-ship-receipt read --body <file> [--json]
|
|
* gstack-ship-receipt result (--pr <n> [--repo <owner/repo>] | --body <file>) [--head <sha>] [--out <dir>] [--json]
|
|
* gstack-ship-receipt census --repo <owner/repo> --since <tag|YYYY-MM-DD> [--cohort <file>] [--limit <n>] [--json]
|
|
*
|
|
* `write` validates against `gstack-artifact schema ship-receipt`, prints the
|
|
* fenced block (and SHIP_RECEIPT: <identifiers> on stderr), writes it to --out,
|
|
* and with --body makes it the first section of that PR body file.
|
|
* `result` is /ship's terminal step: it binds the receipt to HEAD, writes the
|
|
* run record under <state>/ship/runs/ (ship-run.json: a /ship record, not a
|
|
* `run` v1 manifest, so `gstack-artifact validate` does not apply to it) and
|
|
* prints GSTACK_RESULT: skill=ship. A gh failure prints status=incomplete.
|
|
* Query commands: no GSTACK_RESULT line. Logic: lib/ship-receipt.ts.
|
|
*/
|
|
import { spawnSync } from 'node:child_process';
|
|
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import { EXIT, exitTableHelp, type ShipReceipt } from '../lib/headless-artifacts';
|
|
import { resultLine, resultLineWithDocs } from '../lib/result-codes';
|
|
import { versionAtRef } from '../lib/restamp';
|
|
import { readPregateFile, verifyPregate } from '../lib/pregate/index';
|
|
import { resolveBaseBranch } from '../lib/ship-policy';
|
|
import { approvalForReceipt } from '../lib/approval-citations';
|
|
import {
|
|
bindReceipt, computeCensus, extractReceipt, missingIssueLines, orderReceipt, placeReceiptFirst, receiptIssuesFrom, receiptSummaryLine, renderCensus,
|
|
renderReceiptBlock, validateReceipt, type CensusPr,
|
|
} from '../lib/ship-receipt';
|
|
import { resolveStateRoot } from '../lib/state-root';
|
|
|
|
const HELP = `gstack-ship-receipt — the \`\`\`gstack-ship-receipt\`\`\` block (docs/ship-policy.md#ship-receipt)
|
|
|
|
write [flags] compose, validate and print the block; --body <file> puts it first in that PR body
|
|
read --pr <n> [--repo <r>] parse the block from the PR body through gh (RECEIPT_MISSING / RECEIPT_INVALID)
|
|
read --body <file> parse the block from a file
|
|
result --pr <n> [--repo <r>] | --body <file> [--head <sha>] [--out <dir>]
|
|
/ship's terminal line: binds the receipt to HEAD (QUEUE_RECEIPT_MISSING / QUEUE_RECEIPT_STALE),
|
|
writes <state>/ship/runs/<utc>-<head12>/{ship-run.json,ship-receipt.md} and prints
|
|
GSTACK_RESULT: skill=ship status=complete run=<dir> (refused: status=refused run=-)
|
|
census --repo <r> --since <tag|date> [--cohort <file>]
|
|
the P7 adoption number over merged PRs (deduplicated by run and thread)
|
|
|
|
write flags: --pr --head --base --version --gated-tree --predecessor --gate <json|@file> --ci <json|@file> --spend-usd
|
|
--session-kind --artifacts-consumed <n>/<m> --run --thread --receipt <tree-receipt.json> --policy --preregistration
|
|
--history --queue-mode --pregate <pregate.json> (C8: refused unless current, green and every requires-remote obligation
|
|
carries a receipt: PREGATE_STALE / PREGATE_LANE_FAILED / PREGATE_INCOMPLETE / PREGATE_REMOTE_UNCLEARED) --issues <json|@file>
|
|
(C6: gstack-issue-links --out/--json; with --body, refused with ISSUE_LINKS_MISSING unless the body carries every Fixes/Refs/Flake/Related line)
|
|
--approval <"Approved by <owner> <YYYY-MM-DD> via <ref> [for <class>@<digest12>]"> (repeatable; the --body file's lines count too)
|
|
--approval-run <autoplan run dir> (repeatable; resolves plan-sha citations) (W2: a class declared in origin/<base>'s
|
|
.gstack/approval-classes.json with hits needs a citation that resolves and binds to its effects: APPROVAL_CITATION_MISSING)
|
|
--out <file> --body <pr-body.md>. Defaults: head=HEAD, base=origin/HEAD's branch, version=the
|
|
version source at HEAD, session_kind=$GSTACK_SESSION_KIND (gstack-session-kind), tree/gate_reuse/gated_tree/predecessor
|
|
from --receipt when given.
|
|
--json: JSON only on stdout.
|
|
${exitTableHelp()}`;
|
|
|
|
function flag(args: string[], name: string): string | undefined {
|
|
const i = args.indexOf(name);
|
|
return i >= 0 ? args[i + 1] : undefined;
|
|
}
|
|
function flags(args: string[], name: string): string[] {
|
|
return args.flatMap((a, i) => (a === name && args[i + 1] !== undefined ? [args[i + 1]!] : []));
|
|
}
|
|
function jsonArg(raw: string | undefined): Record<string, unknown> | undefined {
|
|
if (raw === undefined) return undefined;
|
|
const text = raw.startsWith('@') ? fs.readFileSync(raw.slice(1), 'utf8') : raw;
|
|
const parsed = JSON.parse(text);
|
|
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('expected a JSON object');
|
|
return parsed;
|
|
}
|
|
function git(args: string[], cwd?: string): string | undefined {
|
|
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 30_000 });
|
|
return r.status === 0 ? r.stdout.trim() : undefined;
|
|
}
|
|
function gh(args: string[]): { ok: boolean; out: string; err: string } {
|
|
const r = spawnSync('gh', args, { encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024 });
|
|
return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr ?? '').trim() };
|
|
}
|
|
|
|
function cmdWrite(rest: string[], json: boolean): number {
|
|
const repoRoot = git(['rev-parse', '--show-toplevel']) ?? process.cwd();
|
|
const head = flag(rest, '--head') ?? git(['rev-parse', 'HEAD'], repoRoot);
|
|
if (!head) { process.stderr.write('gstack-ship-receipt write: --head is required outside a git repository\n'); return EXIT.usage; }
|
|
const atHead = versionAtRef(repoRoot, head);
|
|
const receiptFile = flag(rest, '--receipt');
|
|
const tree = receiptFile ? JSON.parse(fs.readFileSync(receiptFile, 'utf8')) : null;
|
|
let sessionKind = flag(rest, '--session-kind') ?? process.env.GSTACK_SESSION_KIND;
|
|
if (!sessionKind) {
|
|
const r = spawnSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-session-kind'), [], { encoding: 'utf8', timeout: 15_000 });
|
|
sessionKind = r.status === 0 ? r.stdout.trim() || undefined : undefined;
|
|
}
|
|
let pregate: { pregate: string; requires_remote?: string[] } | undefined;
|
|
const pregateFile = flag(rest, '--pregate');
|
|
if (pregateFile) {
|
|
const read = readPregateFile(pregateFile);
|
|
if (!read.file) {
|
|
for (const e of read.errors) process.stderr.write(resultLine('gstack-ship-receipt write', e.code, `${e.message} at ${e.path}`) + '\n');
|
|
return EXIT.fail;
|
|
}
|
|
const v = verifyPregate(repoRoot, read.file);
|
|
if (!v.ok) { process.stderr.write(resultLine('gstack-ship-receipt write', v.code!, `${v.message}; nothing written`) + '\n'); return EXIT.fail; }
|
|
const remote = read.file.requires_remote ?? [];
|
|
pregate = { pregate: `${read.file.verdict ?? 'pass'} @${read.file.tree.slice(0, 12)} (${read.file.checks.length} checks, current for ${head.slice(0, 12)})`, requires_remote: remote.length ? remote.map(r => `${r.lane}: ${r.receipt}`) : undefined };
|
|
}
|
|
const base = flag(rest, '--base') ?? resolveBaseBranch(repoRoot);
|
|
const bodyFile = flag(rest, '--body');
|
|
const bodyText = bodyFile && fs.existsSync(bodyFile) ? fs.readFileSync(bodyFile, 'utf8').replace(/```gstack-ship-receipt[\s\S]*?\n```/g, '') : '';
|
|
const approval = approvalForReceipt({ repoRoot, base, head, citationText: [bodyText, ...flags(rest, '--approval')].join('\n'), runDirs: flags(rest, '--approval-run') });
|
|
if (approval.kind === 'invalid') {
|
|
for (const line of approval.lines) process.stderr.write(resultLine('gstack-ship-receipt write', 'APPROVAL_CLASSES_INVALID', line) + '\n');
|
|
return EXIT.fail;
|
|
}
|
|
if (approval.kind === 'error' && approval.code) { process.stderr.write(resultLine('gstack-ship-receipt write', approval.code, `${approval.message}; nothing written`) + '\n'); return EXIT.fail; }
|
|
if (approval.kind === 'error') { process.stderr.write(`gstack-ship-receipt write: approval classes: ${approval.message}; nothing written\n`); return EXIT.fail; }
|
|
if (approval.kind === 'missing') {
|
|
for (const m of approval.missing) process.stderr.write(resultLine('gstack-ship-receipt write', 'APPROVAL_CITATION_MISSING', `${m.class} (${m.token}; effects in ${m.files.join(', ')}): ${m.reasons.join('; ')}`) + '\n');
|
|
process.stderr.write('gstack-ship-receipt write: nothing written\n');
|
|
return EXIT.fail;
|
|
}
|
|
if (approval.kind === 'ok' && approval.note) process.stderr.write(approval.note + '\n');
|
|
let input: Partial<ShipReceipt>;
|
|
try {
|
|
const issuesFile = jsonArg(flag(rest, '--issues'));
|
|
input = {
|
|
schema_version: 1, pr: flag(rest, '--pr') !== undefined ? Number(flag(rest, '--pr')) : undefined, head,
|
|
version: flag(rest, '--version') ?? ('version' in atHead ? atHead.version : undefined), base,
|
|
gated_tree: flag(rest, '--gated-tree') ?? tree?.gated_tree, predecessor: flag(rest, '--predecessor') ?? tree?.predecessor?.recorded_head ?? undefined,
|
|
tree: tree?.tree, gate_reuse: tree ? `${tree.gate_reuse} (${tree.gate_reuse_reason})` : undefined,
|
|
gate: jsonArg(flag(rest, '--gate')), ci: jsonArg(flag(rest, '--ci')),
|
|
spend_usd: flag(rest, '--spend-usd') !== undefined ? (Number.isFinite(Number(flag(rest, '--spend-usd'))) ? Number(flag(rest, '--spend-usd')) : flag(rest, '--spend-usd')) : undefined,
|
|
session_kind: sessionKind, artifacts_consumed: flag(rest, '--artifacts-consumed'), run: flag(rest, '--run'), thread: flag(rest, '--thread'),
|
|
policy: flag(rest, '--policy') ?? tree?.policy, queue_mode: flag(rest, '--queue-mode'), preregistration: flag(rest, '--preregistration'), history: flag(rest, '--history'),
|
|
...pregate, issues: issuesFile ? receiptIssuesFrom(issuesFile) : undefined, approval: approval.kind === 'ok' ? approval.approval : undefined,
|
|
};
|
|
} catch (e: any) { process.stderr.write(`gstack-ship-receipt write: ${e.message}\n`); return EXIT.usage; }
|
|
if (input.pr !== undefined && !Number.isInteger(input.pr)) { process.stderr.write('gstack-ship-receipt write: --pr must be an integer\n'); return EXIT.usage; }
|
|
const receipt = orderReceipt(input);
|
|
const errors = validateReceipt(receipt);
|
|
if (errors.length) {
|
|
for (const e of errors) process.stderr.write(resultLine('gstack-ship-receipt write', 'RECEIPT_INVALID', `${e.message} at ${e.path}`) + '\n');
|
|
process.stderr.write('gstack-ship-receipt write: nothing written\n');
|
|
return EXIT.fail;
|
|
}
|
|
const body = bodyFile;
|
|
const missing = body && receipt.issues ? missingIssueLines(fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : '', receipt.issues) : [];
|
|
if (missing.length) {
|
|
process.stderr.write(resultLineWithDocs('gstack-ship-receipt write', 'ISSUE_LINKS_MISSING', `${body} lacks ${missing.map(l => JSON.stringify(l)).join(', ')}`) + '\n');
|
|
return EXIT.fail;
|
|
}
|
|
const block = renderReceiptBlock(receipt);
|
|
const out = flag(rest, '--out');
|
|
if (out) fs.writeFileSync(out, block);
|
|
if (body) fs.writeFileSync(body, placeReceiptFirst(fs.existsSync(body) ? fs.readFileSync(body, 'utf8') : '', receipt));
|
|
process.stderr.write(receiptSummaryLine(receipt) + '\n');
|
|
process.stdout.write(json ? JSON.stringify(receipt) + '\n' : block);
|
|
return EXIT.ok;
|
|
}
|
|
|
|
function cmdRead(rest: string[], json: boolean): number {
|
|
const bodyFile = flag(rest, '--body');
|
|
const pr = flag(rest, '--pr');
|
|
let body: string;
|
|
if (bodyFile) body = fs.readFileSync(bodyFile, 'utf8');
|
|
else if (pr) {
|
|
const repo = flag(rest, '--repo');
|
|
const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'body']);
|
|
if (!r.ok) { process.stderr.write(`gstack-ship-receipt read: gh pr view failed: ${r.err}\n`); return EXIT.fail; }
|
|
try { body = JSON.parse(r.out).body ?? ''; } catch { process.stderr.write('gstack-ship-receipt read: gh returned no JSON body\n'); return EXIT.fail; }
|
|
} else { process.stderr.write(`gstack-ship-receipt read: --pr <n> or --body <file> is required\n${HELP}\n`); return EXIT.usage; }
|
|
const ex = extractReceipt(body);
|
|
if (!ex.found) {
|
|
process.stderr.write(resultLine('gstack-ship-receipt read', 'RECEIPT_MISSING', pr ? `PR #${pr}` : bodyFile!) + '\n');
|
|
if (json) process.stdout.write(JSON.stringify({ found: false, errors: [] }) + '\n');
|
|
return EXIT.fail;
|
|
}
|
|
if (ex.errors.length) {
|
|
for (const e of ex.errors) process.stderr.write(resultLine('gstack-ship-receipt read', 'RECEIPT_INVALID', `${e.message} at ${e.path}`) + '\n');
|
|
if (json) process.stdout.write(JSON.stringify({ found: true, valid: false, errors: ex.errors, raw: ex.raw }) + '\n');
|
|
return EXIT.fail;
|
|
}
|
|
process.stderr.write(receiptSummaryLine(ex.receipt!) + '\n');
|
|
process.stdout.write(json ? JSON.stringify(ex.receipt) + '\n' : renderReceiptBlock(ex.receipt!));
|
|
return EXIT.ok;
|
|
}
|
|
|
|
/**
|
|
* /ship's terminal line (docs/unattended.md#the-terminal-line). The receipt in
|
|
* the PR body (or the handoff file) must bind to HEAD: then the run record
|
|
* goes under <state>/ship/runs/ with the head, the PR and the receipt, and
|
|
* the last stdout line is GSTACK_RESULT: skill=ship status=complete run=<dir>.
|
|
* A missing or stale receipt is status=refused run=- (exit 3), so a parent
|
|
* never has to parse the PR body to know whether /ship finished at this head.
|
|
*/
|
|
function cmdResult(rest: string[], json: boolean): number {
|
|
const bodyFile = flag(rest, '--body');
|
|
const prFlag = flag(rest, '--pr');
|
|
if (prFlag !== undefined && !/^[1-9]\d*$/.test(prFlag)) { process.stderr.write(`gstack-ship-receipt result: --pr must be a PR number, got ${JSON.stringify(prFlag.slice(0, 40))}\n`); return EXIT.usage; }
|
|
const pr = prFlag;
|
|
if (prFlag !== undefined && flag(rest, '--body') !== undefined) { process.stderr.write('gstack-ship-receipt result: pass --pr <n> (the PR body, checked against its pushed head) or --body <file> (the handoff receipt), not both\n'); return EXIT.usage; }
|
|
const repoRoot = git(['rev-parse', '--show-toplevel']);
|
|
const head = (flag(rest, '--head') ?? (repoRoot ? git(['rev-parse', 'HEAD'], repoRoot) : undefined))?.toLowerCase();
|
|
const refused = (code: 'QUEUE_RECEIPT_MISSING' | 'QUEUE_RECEIPT_STALE', message: string) => {
|
|
process.stderr.write(resultLineWithDocs('gstack-ship-receipt result', code, message) + '\n');
|
|
process.stdout.write(json ? JSON.stringify({ skill: 'ship', status: 'refused', run: '-', code, message }) + '\n' : 'GSTACK_RESULT: skill=ship status=refused run=-\n');
|
|
return EXIT.refused;
|
|
};
|
|
if (!head) { process.stderr.write('gstack-ship-receipt result: --head <sha> is required outside a git repository\n'); return EXIT.usage; }
|
|
if (!/^[0-9a-f]{40,64}$/i.test(head)) { process.stderr.write(`gstack-ship-receipt result: --head must be a full hex commit id, got ${JSON.stringify(head.slice(0, 40))}\n`); return EXIT.usage; }
|
|
const incomplete = (why: string) => {
|
|
process.stderr.write(`gstack-ship-receipt result: ${why}\n`);
|
|
process.stdout.write(json ? JSON.stringify({ skill: 'ship', status: 'incomplete', run: '-', message: why }) + '\n' : 'GSTACK_RESULT: skill=ship status=incomplete run=-\n');
|
|
return EXIT.fail;
|
|
};
|
|
let body: string;
|
|
let source: string;
|
|
if (bodyFile) {
|
|
if (!fs.existsSync(bodyFile)) return refused('QUEUE_RECEIPT_MISSING', `${bodyFile} does not exist; /ship did not write its receipt`);
|
|
try { body = fs.readFileSync(bodyFile, 'utf8'); } catch (e) { return incomplete(`cannot read ${bodyFile}: ${e instanceof Error ? e.message : String(e)}`); }
|
|
source = path.resolve(bodyFile);
|
|
} else if (pr) {
|
|
const repo = flag(rest, '--repo');
|
|
const r = gh(['pr', 'view', pr, ...(repo ? ['--repo', repo] : []), '--json', 'body,headRefOid']);
|
|
if (!r.ok) return incomplete(`gh pr view failed: ${r.err.trim()}`);
|
|
let pushed: unknown;
|
|
try { const v = JSON.parse(r.out); body = v.body ?? ''; pushed = v.headRefOid; } catch { return incomplete('gh returned no JSON body'); }
|
|
if (typeof pushed !== 'string' || !/^[0-9a-f]{12,64}$/i.test(pushed)) return incomplete(`gh pr view returned no headRefOid for PR #${pr}`);
|
|
if (!pushed.toLowerCase().startsWith(head.toLowerCase())) {
|
|
return refused('QUEUE_RECEIPT_STALE', `HEAD ${head.slice(0, 12)} is not PR #${pr}'s pushed head ${pushed.slice(0, 12)}; push it, then rerun gstack-ship-receipt result`);
|
|
}
|
|
source = `PR #${pr}${repo ? ` (${repo})` : ''}`;
|
|
} else { process.stderr.write(`gstack-ship-receipt result: --pr <n> or --body <file> is required\n${HELP}\n`); return EXIT.usage; }
|
|
const bound = bindReceipt(body, pr, [head]);
|
|
if (!bound.ok) return refused(bound.code, bound.message);
|
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
const out = flag(rest, '--out');
|
|
const dir = out ? path.resolve(out) : path.join(resolveStateRoot(), 'ship', 'runs', `${stamp}-${head.slice(0, 12)}`);
|
|
const receiptPath = path.join(dir, 'ship-receipt.md');
|
|
try {
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
fs.writeFileSync(receiptPath, renderReceiptBlock(bound.receipt));
|
|
} catch (e) { return incomplete(`cannot write the run record under ${dir}: ${e instanceof Error ? e.message : String(e)}`); }
|
|
const run = {
|
|
schema_version: 1, skill: 'ship', status: 'complete', head, pr: bound.receipt.pr ?? (pr ? Number(pr) : null), base: bound.receipt.base, version: bound.receipt.version ?? null,
|
|
queue_mode: bound.receipt.queue_mode ?? null, session_kind: bound.receipt.session_kind ?? process.env.GSTACK_SESSION_KIND ?? null,
|
|
receipt: receiptPath, receipt_source: source, branch: repoRoot ? git(['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot) ?? null : null, created_at: new Date().toISOString(),
|
|
};
|
|
try { fs.writeFileSync(path.join(dir, 'ship-run.json'), JSON.stringify(run, null, 2) + '\n'); } catch (e) { return incomplete(`cannot write ${path.join(dir, 'ship-run.json')}: ${e instanceof Error ? e.message : String(e)}`); }
|
|
process.stderr.write(bound.line + '\n');
|
|
process.stdout.write(json ? JSON.stringify({ ...run, run: dir }) + '\n' : `GSTACK_RESULT: skill=ship status=complete run=${dir}\n`);
|
|
return EXIT.ok;
|
|
}
|
|
|
|
function sinceDate(repo: string, since: string): string | undefined {
|
|
if (/^\d{4}-\d{2}-\d{2}/.test(since)) return since.slice(0, 10);
|
|
const local = git(['log', '-1', '--format=%cI', since]);
|
|
if (local) return local.slice(0, 10);
|
|
const r = gh(['api', `repos/${repo}/commits/${since}`, '--jq', '.commit.committer.date']);
|
|
return r.ok && r.out.trim() ? r.out.trim().slice(0, 10) : undefined;
|
|
}
|
|
|
|
function cmdCensus(rest: string[], json: boolean): number {
|
|
const repo = flag(rest, '--repo');
|
|
const since = flag(rest, '--since');
|
|
if (!repo || !since) { process.stderr.write(`gstack-ship-receipt census: --repo <owner/repo> and --since <tag|date> are required\n${HELP}\n`); return EXIT.usage; }
|
|
const date = sinceDate(repo, since);
|
|
if (!date) { process.stderr.write(`gstack-ship-receipt census: cannot resolve --since ${since} to a date (not a local tag, and gh could not read it)\n`); return EXIT.fail; }
|
|
const limit = flag(rest, '--limit') ?? '500';
|
|
const r = gh(['pr', 'list', '--repo', repo, '--state', 'merged', '--search', `merged:>=${date}`, '--limit', limit, '--json', 'number,body,mergedAt,title']);
|
|
if (!r.ok) { process.stderr.write(`gstack-ship-receipt census: gh pr list failed: ${r.err}\n`); return EXIT.fail; }
|
|
let prs: CensusPr[];
|
|
try { prs = JSON.parse(r.out); } catch { process.stderr.write('gstack-ship-receipt census: gh returned no JSON\n'); return EXIT.fail; }
|
|
const cohortFile = flag(rest, '--cohort');
|
|
const cohort = cohortFile ? fs.readFileSync(cohortFile, 'utf8').split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#')) : null;
|
|
const census = computeCensus(repo, date, prs, cohort);
|
|
process.stdout.write(json ? JSON.stringify(census) + '\n' : renderCensus(census));
|
|
return EXIT.ok;
|
|
}
|
|
|
|
function main(argv: string[]): number {
|
|
const [cmd, ...rest] = argv;
|
|
const json = rest.includes('--json');
|
|
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }
|
|
if (cmd === 'write') return cmdWrite(rest, json);
|
|
if (cmd === 'read') return cmdRead(rest, json);
|
|
if (cmd === 'result') return cmdResult(rest, json);
|
|
if (cmd === 'census') return cmdCensus(rest, json);
|
|
process.stderr.write(`gstack-ship-receipt: unknown command ${cmd}\n${HELP}\n`);
|
|
return EXIT.usage;
|
|
}
|
|
|
|
process.exitCode = main(process.argv.slice(2));
|