mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-19 22:54:36 +01:00
v1.94.14.0 stamp: merge main d69ba2c6fb into #3902 (land)
This commit is contained in:
commit
101201dba4
174 files changed
+8357
-425
No files matched your search
+12
-5
@@ -6,7 +6,7 @@
|
||||
* [--pending <text>] [--outcome approved|rejected|pending|standing]
|
||||
* [--date YYYY-MM-DD] [--source <ref>] [--branch <name>] [--json]
|
||||
* gstack-approvals import --autoplan <run dir> [--by <whose words>] [--branch <name> | --stack <b1,b2,...>] [--json]
|
||||
* gstack-approvals render [--no-heading] [--branch <name>]
|
||||
* gstack-approvals render [--no-heading] [--full] [--branch <name>]
|
||||
* gstack-approvals list [--json] [--branch <name>]
|
||||
* gstack-approvals sync [--branch <name>]
|
||||
* gstack-approvals path [--branch <name>]
|
||||
@@ -20,7 +20,7 @@
|
||||
*/
|
||||
import * as path from 'node:path';
|
||||
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
|
||||
import { appendRows, branchExists, buildRow, importAutoplan, locate, readRecord, renderRecord, syncRecord, type RecordError, type StoreLocation } from '../lib/approval-record';
|
||||
import { appendRows, branchExists, buildRow, importAutoplan, locate, readRecord, renderMode, renderRecord, repoVisibility, syncRecord, type RecordError, type StoreLocation } from '../lib/approval-record';
|
||||
import { resultLine } from '../lib/result-codes';
|
||||
|
||||
const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gstack/captain.md)
|
||||
@@ -29,7 +29,9 @@ const HELP = `gstack-approvals — the per-thread approval record (capy/skill/gs
|
||||
[--pending <text>] [--outcome approved|rejected|pending|standing] [--date YYYY-MM-DD] [--source <ref>]
|
||||
import --autoplan <run dir> [--by <whose words, e.g. Garry>] [--stack <b1,b2,...>]
|
||||
--stack writes the same rows to every branch of a stack; each branch is checked first, and one unknown branch writes none
|
||||
render [--no-heading] the ## Approvals section for a PR body or report
|
||||
render [--no-heading] [--full] the ## Approvals section for a PR body or report; a public repository, or one whose
|
||||
visibility gh cannot read, gets only "Approved: yes|no (record <id>)", because a PR description keeps
|
||||
its edit history; --full prints the rows when gh cannot read the visibility and you know the repo is private
|
||||
list [--json]
|
||||
sync re-mirror the record (GSTACK_APPROVALS_DIR, the Captain's drive approvals/, or the project-user Drive)
|
||||
path print the record and mirror paths, and which rule chose the mirror
|
||||
@@ -52,7 +54,7 @@ function parse(args: string[]): { flags: Record<string, string>; bools: Set<stri
|
||||
const v = args[i + 1];
|
||||
if (v === undefined) return { flags, bools, error: `${a} needs a value` };
|
||||
flags[a] = v; i++;
|
||||
} else if (a === '--json' || a === '--no-heading') bools.add(a);
|
||||
} else if (a === '--json' || a === '--no-heading' || a === '--full') bools.add(a);
|
||||
else return { flags, bools, error: `unknown argument ${a}` };
|
||||
}
|
||||
return { flags, bools };
|
||||
@@ -134,7 +136,12 @@ function main(argv: string[]): number {
|
||||
if (read.restored) process.stderr.write(`gstack-approvals: read the Drive mirror ${loc.mirror} (no local copy on this machine; gstack-approvals sync restores it)\n`);
|
||||
if (cmd === 'list' && json) process.stdout.write(JSON.stringify({ branch: loc.branch, state: read.state, rows: read.rows }) + '\n');
|
||||
else if (cmd === 'list') for (const r of read.rows) process.stdout.write(`${r.date} ${r.id} ${r.outcome} ${JSON.stringify(r.ask)} words=${JSON.stringify(r.words)} by=${JSON.stringify(r.by)}\n`);
|
||||
else process.stdout.write(renderRecord(read, loc, { heading: !bools.has('--no-heading') }));
|
||||
else {
|
||||
const visibility = repoVisibility(process.cwd());
|
||||
const mode = renderMode(visibility, bools.has('--full'));
|
||||
if (mode === 'redacted') process.stderr.write(`APPROVALS_RENDER: redacted (repository visibility ${visibility}${bools.has('--full') ? '; --full applies only to a private repository' : ''}); gstack-approvals list shows the full record\n`);
|
||||
process.stdout.write(renderRecord(read, loc, { heading: !bools.has('--no-heading'), mode }));
|
||||
}
|
||||
if (read.state === 'unavailable') return fail(cmd, { code: 'APPROVAL_RECORD_UNAVAILABLE', message: `no record at ${loc.file} and no mirror` });
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
+27
-5
@@ -2,7 +2,8 @@
|
||||
/**
|
||||
* gstack-autoplan — the unattended /autoplan runner as an explicit, durable state machine (plan B2).
|
||||
*
|
||||
* gstack-autoplan next --out <dir> [--plan <file>] [--plan-heading <text>] [--ui|--no-ui] [--developer-tool] [--agent-primary] [--docs-only] [--ceo-only]
|
||||
* gstack-autoplan next --kind fix a bug fix: no plan review (R65), status=skipped, nothing written (run --kind fix too)
|
||||
* gstack-autoplan next --out <dir> [--plan <file>] [--kind feature|--full] [--base <ref>] [--plan-heading <text>] [--ui|--no-ui] [--developer-tool] [--agent-primary] [--docs-only] [--ceo-only]
|
||||
* [--no-outside] [--light] [--spend-cap <usd>] [--estimate-usd <n>] [--deadline <min>] [--redispatch <attempt>] [--json]
|
||||
* gstack-autoplan submit --out <dir> --phase <p> --voice native|outside --result <file> | --record <file> [--attest <reason>]
|
||||
* --model <id> [--attempt <id>] [--runner <r>] [--usage-usd <n>] [--reconcile <jsonl>] [--json]
|
||||
@@ -45,6 +46,7 @@ import { capyRelayLine } from '../lib/captain-brief';
|
||||
import { exportPublic } from '../lib/autoplan-public';
|
||||
import { migrateRun } from '../lib/autoplan-migrate';
|
||||
import { reviseRun } from '../lib/autoplan-revise';
|
||||
import { FIX_LINES, KINDS, type AutoplanKind } from '../lib/autoplan-lean';
|
||||
import { pendingAmendments, type RunState, type Voice } from '../lib/autoplan-state';
|
||||
import { FILES, RunError, currentPhase, fitReservation, initRun, markOutside, markSent, nextStep, readState, resumeRun, retireAttempt, statusLines, submitResult, withRunLock, writeState, type NextOptions } from '../lib/autoplan-run';
|
||||
import { driverFile, type Phase } from '../lib/autoplan-prompts';
|
||||
@@ -61,9 +63,16 @@ import { exportShadow, renderShadowExport } from '../lib/autoplan-shadow-reader'
|
||||
const HELP = `gstack-autoplan — unattended /autoplan: next/submit loop, answer, resume (docs/unattended.md)
|
||||
DRIVER: ${driverFile()}
|
||||
|
||||
next --out <dir> [--plan <file>] [--plan-heading <text>] [--scaffold] [--ui|--no-ui] [--developer-tool] [--agent-primary] [--no-dx] [--docs-only] [--ceo-only]
|
||||
next --kind fix a bug fix needs no plan review (R65): prints AUTOPLAN: not needed and status=skipped, writes nothing (no --out or --plan);
|
||||
the PR still needs the bug's proof (a repro on current main or a failing test written first)
|
||||
next --out <dir> [--plan <file>] [--kind feature|--full] [--base <ref>] [--plan-heading <text>] [--scaffold] [--ui|--no-ui] [--developer-tool] [--agent-primary] [--no-dx] [--docs-only] [--ceo-only]
|
||||
[--no-outside] [--light] [--spend-cap <usd>] [--max-rounds <n>] [--estimate-usd <n>] [--deadline <min>] [--redispatch <attempt>] [--json]
|
||||
--max-rounds (first next): review rounds per phase (default 2 unattended); at the cap a phase closes accepted-with-findings
|
||||
--kind feature (first next; the default for an unattended Capy run, GSTACK_CAPY=1): the lean run (R65): the eng phase alone with one
|
||||
native reviewer whose brief merges the CEO and Eng lenses (Design/DX when scope detects them), reads the draft code (git diff of
|
||||
--base, default origin/HEAD, hashed into the snapshot; DRAFT: none when there is no code yet) and always asks about outside terms;
|
||||
no outside voice, one round, one gate revision (accepted changes apply without re-review), no carry check
|
||||
--full (first next): every phase and both voices, as before R65; off Capy, or in an interactive session, the default stays full
|
||||
--max-rounds (first next): review rounds per phase (default 2 unattended, 1 lean); at the cap a phase closes accepted-with-findings
|
||||
--docs-only (first next; also detected when every Implementation-plan path is docs-class): CEO (native voice only) + Eng
|
||||
--ceo-only (first next, command line only): the CEO phase alone, no gate; ends status=reviewed with <out>/ceo-review.md, never approved
|
||||
--estimate-usd: reserved per new attempt, kept for the rest of the run; with --spend-cap any run (or an unattended run on Capy) reserves a default so the cap binds
|
||||
@@ -88,6 +97,7 @@ DRIVER: ${driverFile()}
|
||||
--settle records a packaging/ordering change that needs no plan edit and reopens nothing (ids: decision id or d4)
|
||||
run --out <dir> --plan <file> --native-model <id> --outside-model <id> [--runner codex-cli|api] [--native-runner api] ...
|
||||
next in a loop, only when a runner executes both voices here (hosts without subagents: --native-runner api --runner api);
|
||||
the full run unless --kind feature (the lean run) or --kind fix (no review, nothing written);
|
||||
--deadline cancels the children it started; --max-tokens caps each api call's output (default 16384; OpenAI counts reasoning tokens in it), and a
|
||||
response cut off at that limit is reported truncated; submit's result checks judge every completed response
|
||||
answer --out <dir> --gate-rev <rev> --reply "<rec | rec except d3a | d3b uc1a | as-is>" --by <human|agent:<id>> [--json]
|
||||
@@ -247,7 +257,7 @@ function doNext(out: string, rest: string[], price?: NextOptions['price']): Repo
|
||||
if (carryCheckCapUsd !== undefined && !(carryCheckCapUsd >= 0)) throw new RunError('ARTIFACT_SCHEMA', '--carry-check-cap needs a number >= 0', 1);
|
||||
const shadow = shadowSwitch({ outsideEnabled: !rest.includes('--no-outside'), ceoOnly }, process.env);
|
||||
if (shadow.line) initLines.push(shadow.line);
|
||||
initRun({ plan, out, cwd, planHeading: flag(rest, '--plan-heading'), outsideEnabled: !rest.includes('--no-outside'), spendCap: num(rest, '--spend-cap') ?? null, maxRounds,
|
||||
initRun({ plan, out, cwd, kind: flag(rest, '--kind') as AutoplanKind | undefined, full: rest.includes('--full'), base: flag(rest, '--base'), planHeading: flag(rest, '--plan-heading'), outsideEnabled: !rest.includes('--no-outside'), spendCap: num(rest, '--spend-cap') ?? null, maxRounds,
|
||||
carryForward: !rest.includes('--no-carry-forward'), carryCheckCapUsd, ceoOnly, shadow: shadow.shadow,
|
||||
deadlineMin: num(rest, '--deadline'), light: rest.includes('--light'), scaffold: rest.includes('--scaffold'), scope: { ui, developerTool: rest.includes('--developer-tool'), agentPrimary: rest.includes('--agent-primary'), dx: rest.includes('--no-dx') ? false : undefined, ...(rest.includes('--docs-only') ? { docsOnly: true } : {}) } }, initLines);
|
||||
}
|
||||
@@ -342,7 +352,9 @@ function doBudget(out: string, rest: string[], json: boolean): number {
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
async function doRun(out: string, rest: string[], json: boolean): Promise<number> {
|
||||
async function doRun(out: string, args: string[], json: boolean): Promise<number> {
|
||||
// run pays for both voices, so it starts the full run unless --kind feature asks for the lean one (R65).
|
||||
const rest = args.includes('--kind') ? args : [...args, '--full'];
|
||||
const nativeModel = flag(rest, '--native-model'); const outsideModel = flag(rest, '--outside-model');
|
||||
const outsideRunner = (flag(rest, '--runner') ?? 'codex-cli') as RunnerId; const nativeRunner = (flag(rest, '--native-runner') ?? 'api') as RunnerId;
|
||||
if (!nativeModel || !outsideModel) return usage('run needs --native-model and --outside-model (a runner must execute both voices)');
|
||||
@@ -444,6 +456,16 @@ async function main(argv: string[]): Promise<number> {
|
||||
try { process.stdout.write(checkpointLines(from).join('\n') + '\n'); return EXIT.ok; }
|
||||
catch (e: any) { if (!(e instanceof RunError)) throw e; process.stderr.write(resultLine('gstack-autoplan checkpoints', e.code, e.detail) + '\n'); return EXIT.refused; }
|
||||
}
|
||||
if ((cmd === 'next' || cmd === 'run') && rest.includes('--kind')) {
|
||||
const kind = flag(rest, '--kind');
|
||||
if (!(KINDS as readonly string[]).includes(kind ?? '')) return usage(`--kind takes fix or feature (got ${JSON.stringify(kind ?? '')})`);
|
||||
if (kind === 'fix') {
|
||||
const live = flag(rest, '--out');
|
||||
if (live && fs.existsSync(path.join(path.resolve(live), FILES.run))) return usage(`--kind fix starts no run, but ${live} already holds a run: continue it without --kind, or pass another --out`);
|
||||
emit(json, FIX_LINES, { skill: 'autoplan', status: 'skipped', kind: 'fix', run: null, lines: FIX_LINES.slice(0, -1) });
|
||||
return EXIT.ok;
|
||||
}
|
||||
}
|
||||
const outFlag = flag(rest, '--out');
|
||||
if (!outFlag && cmd !== 'shadow') return usage(`${cmd} needs --out <dir>`);
|
||||
const out = path.resolve(outFlag ?? '.');
|
||||
|
||||
@@ -16,6 +16,7 @@ import { spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { BANNED_TERMS_PATH, addedLines, exampleBannedTermsJson, loadBannedTerms, renderBannedTerms, scanBannedTerms, validateBannedTerms, wholeFiles } from '../lib/banned-terms';
|
||||
import { baseArg } from '../lib/gate-diff/git';
|
||||
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
|
||||
import { resultLine } from '../lib/result-codes';
|
||||
import { resolveBaseBranch } from '../lib/ship-policy';
|
||||
@@ -75,7 +76,7 @@ function main(argv: string[]): number {
|
||||
let files;
|
||||
if (filesFlag) files = wholeFiles(repoRoot, filesFlag.split(',').map(s => s.trim()).filter(Boolean));
|
||||
else {
|
||||
const diffBase = flag(rest, '--diff-base') ?? (() => { const mb = spawnSync('git', ['merge-base', base, 'HEAD'], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); return mb.status === 0 ? mb.stdout.trim() : undefined; })();
|
||||
const diffBase = flag(rest, '--diff-base') ?? (() => { const mb = spawnSync('git', ['merge-base', baseArg('gstack-banned-terms', base, repoRoot), 'HEAD'], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000 }); return mb.status === 0 ? mb.stdout.trim() : undefined; })();
|
||||
if (!diffBase) { process.stderr.write(`gstack-banned-terms: no merge base with ${base}; pass --diff-base <sha> or --files <csv>\n`); return EXIT.usage; }
|
||||
const diff = spawnSync('git', ['diff', '--unified=0', '--no-color', diffBase], { cwd: repoRoot, encoding: 'utf8', timeout: 120_000, maxBuffer: 256 * 1024 * 1024 });
|
||||
if (diff.status !== 0) { process.stderr.write(`gstack-banned-terms: git diff ${diffBase} failed\n`); return EXIT.fail; }
|
||||
|
||||
Executable
+77
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/**
|
||||
* gstack-ci-carry — CI as the one full test run (GSTA-258; docs/pregate.md#ci-carry).
|
||||
*
|
||||
* gstack-ci-carry find [--base <branch>] [--profile <name>]... [--command <exact lane command> --allow-repo-commands] [--json]
|
||||
* gstack-ci-carry wait [--base <branch>] [--profile <name>] [--timeout <s>] [--interval <s>]
|
||||
*
|
||||
* find: the newest verified run of each profile (default: every profile the base branch's
|
||||
* ship_lanes_from names) at HEAD's clean tree. With --command, the base branch's mapping for that exact lane
|
||||
* command supplies the profiles and the inventory the runs must cover (a pin-file command, so it needs
|
||||
* --allow-repo-commands). Prints CI_CARRY: accepted <receipt> (exit 0) or CI_CARRY: none (<reason>) (exit 1).
|
||||
* wait: polls the newest run of the profile's workflow at HEAD until it completes (default timeout 1800 s),
|
||||
* prints CI_WAIT: green|red|running|none, and on green runs find. Exit 0 green and carried, 1 red or not
|
||||
* carried, 3 still running or no run. Logic: lib/ci-carry.ts; the run checks are lib/run-evidence.ts.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { findCarry, waitForRun } from '../lib/ci-carry';
|
||||
import { isConfigUnavailable, loadConfigFromBase } from '../lib/pregate/config';
|
||||
import { buildRunCheck } from '../lib/pregate/run-check';
|
||||
import { runInventory } from '../lib/run-evidence';
|
||||
import { wtreeFingerprint } from '../lib/script-invocation';
|
||||
import { resolveBaseBranch } from '../lib/ship-policy';
|
||||
|
||||
const HELP = `gstack-ci-carry — use a verified CI run at HEAD's exact tree instead of running the suite again (docs/pregate.md#ci-carry)
|
||||
|
||||
find [--base <branch>] [--profile <name>]... [--command <exact lane command> --allow-repo-commands] [--json]
|
||||
CI_CARRY: accepted <receipt> (exit 0) or CI_CARRY: none (<reason>) (exit 1)
|
||||
wait [--base <branch>] [--profile <name>] [--timeout <s>] [--interval <s>]
|
||||
poll the newest run at HEAD (default 1800 s, every 20 s): CI_WAIT: green|red|running|none, then find on green;
|
||||
exit 0 carried, 1 red or not carried, 3 still running or no run
|
||||
|
||||
Profiles and ship_lanes_from come from origin/<base>'s .gstack/pregate.json only. Only a clean, committed tree
|
||||
carries; fork runs, stale runs, a newer red or running run on HEAD and a tree.json that misses an inventory
|
||||
file never do. Exit 2 is usage.`;
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const cmd = argv[0];
|
||||
const all = (n: string) => argv.flatMap((a, i) => (a === n && argv[i + 1] !== undefined ? [argv[i + 1]!] : []));
|
||||
const flag = (n: string) => all(n).at(-1);
|
||||
const out = (s: string) => process.stdout.write(`${s}\n`);
|
||||
const usage = (m: string) => { process.stderr.write(`gstack-ci-carry: ${m}\n`); process.exit(2); };
|
||||
if (!cmd || argv.includes('--help') || argv.includes('-h')) { out(HELP); process.exit(cmd ? 0 : 2); }
|
||||
if (cmd !== 'find' && cmd !== 'wait') usage(`unknown command ${cmd}; run gstack-ci-carry --help`);
|
||||
const git = (args: string[]) => { const r = spawnSync('git', args, { encoding: 'utf8', timeout: 30_000 }); return r.status === 0 ? r.stdout.trim() : ''; };
|
||||
const root = git(['rev-parse', '--show-toplevel']);
|
||||
if (!root) usage('not inside a git repository');
|
||||
const base = resolveBaseBranch(root, flag('--base'));
|
||||
const loaded = loadConfigFromBase(root, base);
|
||||
if (isConfigUnavailable(loaded) || loaded.errors.length) { out(`CI_CARRY: none (profiles_unavailable: origin/${base}'s .gstack/pregate.json is unreadable or invalid)`); process.exit(1); }
|
||||
const command = flag('--command');
|
||||
const mapping = command !== undefined ? loaded.config.ship_lanes_from[command] : undefined;
|
||||
if (command !== undefined && !mapping) { out(`CI_CARRY: none (not_mapped: ${JSON.stringify(command)} is not a key of origin/${base}'s ship_lanes_from)`); process.exit(1); }
|
||||
if (mapping && !argv.includes('--allow-repo-commands')) usage('--command runs the mapping\'s inventory, a pin-file command: pass --allow-repo-commands');
|
||||
const profiles = all('--profile').length ? all('--profile') : mapping ? mapping.profiles : [...new Set(Object.values(loaded.config.ship_lanes_from).flatMap(m => m.profiles))];
|
||||
if (!profiles.length) { out(`CI_CARRY: none (no_profile: origin/${base} maps no lane in ship_lanes_from; pass --profile <name>)`); process.exit(1); }
|
||||
const check = buildRunCheck(root, null, argv.includes('--allow-repo-commands'), base);
|
||||
if ('error' in check) { out(`CI_CARRY: none (profiles_unavailable: ${check.error})`); process.exit(1); }
|
||||
const head = git(['rev-parse', 'HEAD']);
|
||||
const tree = git(['rev-parse', 'HEAD^{tree}']);
|
||||
|
||||
function find(): number {
|
||||
const wtree = () => { const fp = wtreeFingerprint({ cwd: root }); return 'tree' in fp ? fp.tree : null; };
|
||||
const v = findCarry(check as Exclude<typeof check, { error: string }>, { profiles, head, tree, wtree, ...(mapping ? { inventory: () => runInventory(mapping.inventory, root) } : {}) });
|
||||
if (argv.includes('--json')) out(JSON.stringify(v));
|
||||
else out(v.ok ? `CI_CARRY: accepted ${v.receipt}` : `CI_CARRY: none (${v.reason}: ${v.detail})`);
|
||||
return v.ok ? 0 : 1;
|
||||
}
|
||||
|
||||
if (cmd === 'find') process.exit(find());
|
||||
const timeout = Number(flag('--timeout') ?? '1800');
|
||||
const interval = Number(flag('--interval') ?? '20');
|
||||
if (!(timeout >= 0 && timeout <= 21_600) || !(interval >= 1 && interval <= 600)) usage('--timeout is 0-21600 seconds and --interval 1-600');
|
||||
const profile = check.profiles[profiles[0]!];
|
||||
if (!profile) usage(`${profiles[0]} is not a run_profiles name on origin/${base}`);
|
||||
const w = await waitForRun(check.deps, { workflow: profile!.workflow, events: profile!.events, head, timeoutMs: timeout * 1000, intervalMs: interval * 1000, sleep: ms => Bun.sleep(ms), clock: Date.now });
|
||||
out(`CI_WAIT: ${w.state} ${profiles[0]} ${'run' in w ? `run=${w.run.id}/${w.run.run_attempt}${w.state === 'red' ? ` failing=${w.failing.join(',') || '-'}` : ''}` : w.reason}`);
|
||||
process.exit(w.state === 'green' ? find() : w.state === 'red' ? 1 : 3);
|
||||
@@ -97,6 +97,7 @@ import { writeReceipt, writeOutcome } from '../lib/egress-receipt';
|
||||
import { readConfigKey, resolveStateRoot } from '../lib/state-root';
|
||||
import { DESIGN_SLOP_CATALOG, entryForImpeccableId } from '../lib/design-catalog';
|
||||
import { isFrontendPath } from '../lib/frontend-scope';
|
||||
import { baseArg } from '../lib/gate-diff/git';
|
||||
|
||||
// ── Environment ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -821,7 +822,7 @@ function resolveTargets(args: ScanArgs, p: Probe): { targets: string[]; refusedB
|
||||
for (const rel of r.stdout.toString('utf-8').split('\0')) if (rel) files.add(rel);
|
||||
return true;
|
||||
};
|
||||
if (!runZ(['diff', '-z', '--name-only', '--diff-filter=ACMR', `${base}...HEAD`])) {
|
||||
if (!runZ(['diff', '-z', '--name-only', '--diff-filter=ACMR', `${baseArg('gstack-design-detect', base, top)}...HEAD`])) {
|
||||
// A base that does not resolve must not read as "no frontend changes".
|
||||
refuse(base, 'git diff against this base failed (unknown ref or unfetched base)');
|
||||
return { targets: out, refusedBase: true };
|
||||
|
||||
+22
-1
@@ -128,6 +128,26 @@ _session_data() {
|
||||
return "$r"
|
||||
}
|
||||
|
||||
# An auth path holds a token, split the way lib/review-risk.ts tokens() splits
|
||||
# paths (camelCase, then every non-alphanumeric run), that contains auth
|
||||
# (GST-1065). It fails safe: every such token raises the class except the
|
||||
# authorship words below, so author-spec.md, AUTHORS, authority.ts and
|
||||
# coauthors.ts do not, while auth.ts, /auth/, nextauthmiddleware.ts,
|
||||
# noauthrequired.ts, unauthenticated.ts and HTTPAuthorization.ts do.
|
||||
_auth_path() {
|
||||
local s="$1" t r=1
|
||||
while [[ "$s" =~ ^(.*[a-z0-9])([A-Z].*)$ ]]; do s="${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"; done
|
||||
shopt -s nocasematch
|
||||
for t in ${s//[^a-zA-Z0-9]/ }; do
|
||||
case "$t" in
|
||||
author|authors|authored|authoring|authorship|authority|authorities|coauthor|coauthors) ;;
|
||||
*auth*) r=0; break ;;
|
||||
esac
|
||||
done
|
||||
shopt -u nocasematch
|
||||
return "$r"
|
||||
}
|
||||
|
||||
_print_flags() {
|
||||
echo "SCOPE_FRONTEND=$FRONTEND"
|
||||
echo "SCOPE_BACKEND=$BACKEND"
|
||||
@@ -293,9 +313,10 @@ for f in ${FILES_LIST[@]+"${FILES_LIST[@]}"}; do
|
||||
# named for sessions (recovered-sessions.jsonl, GST-911) holds rows, not
|
||||
# session handling, so it is not auth; session config still is.
|
||||
case "$f" in
|
||||
*auth*|*jwt*|*oauth*|*permission*|*role*) m_auth=true ;;
|
||||
*jwt*|*permission*|*role*) m_auth=true ;;
|
||||
*session*) _session_data "$f" || m_auth=true ;;
|
||||
esac
|
||||
_auth_path "$f" && m_auth=true
|
||||
|
||||
# Backend: code that isn't a frontend component/view file. Includes ESM/CJS
|
||||
# (.mjs/.cjs) and explicit-module TS (.mts/.cts) — #1810: these matched no
|
||||
|
||||
@@ -38,6 +38,7 @@ import { spawnSync } from 'child_process';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { baseContainsHead } from '../lib/default-base';
|
||||
import { baseArg } from '../lib/gate-diff/git';
|
||||
import { resultLine } from '../lib/result-codes';
|
||||
import { parseReceiptDocs, type ReceiptDocs } from '../lib/ship-receipt-docs';
|
||||
|
||||
@@ -138,7 +139,7 @@ function main(argv: string[]): void {
|
||||
if (out === top || out.startsWith(top + path.sep)) throw new Error('--out must be outside the repository');
|
||||
const mode = one(args, '--mode');
|
||||
if (mode !== 'edit' && mode !== 'read-only') throw new Error('--mode must be edit or read-only');
|
||||
const base = git(['rev-parse', '--verify', one(args, '--base') + '^{commit}']).trim();
|
||||
const base = git(['rev-parse', '--verify', baseArg('gstack-docs-candidate', one(args, '--base'), process.cwd()) + '^{commit}']).trim();
|
||||
const self = baseContainsHead(top, base);
|
||||
if (self) throw new Error(resultLine('snapshot', 'BASE_CONTAINS_HEAD', self));
|
||||
const exceptionFile = flag(args, '--exception')[0];
|
||||
|
||||
+162
-4
@@ -3,7 +3,9 @@
|
||||
* gstack-evidence — verification-evidence ledger: the mechanical arm of /ship's
|
||||
* IRON LAW ("no completion claims without fresh verification evidence").
|
||||
*
|
||||
* gstack-evidence run --label <L> -- <cmd...>
|
||||
* gstack-evidence run [--reuse [--max-age <hours>]] --label <L> -- <cmd...>
|
||||
* gstack-evidence record-ci --label <L> --base <base> -- <cmd>
|
||||
* gstack-evidence carried [--json]
|
||||
* gstack-evidence check [--label <L> [--expect-cmd <exact string>]]... | --all
|
||||
* [--max-age <hours>] [--allow-paths <csv>]
|
||||
* gstack-evidence bundle --out <file> [--label <L>]... [--require <csv>] [--selection L=<text>]...
|
||||
@@ -51,6 +53,21 @@
|
||||
* normalization — the same convention as bin/gstack-verify-gate (which hashes
|
||||
* for TRUST; this ledger hashes for FRESHNESS).
|
||||
*
|
||||
* `run --reuse` (GSTA-258, what gstack-ship-preflight and finish pass): before
|
||||
* running, the newest row for this label, command hash and working-tree
|
||||
* fingerprint decides. It is reused only when it passed with a counted run
|
||||
* (tests_ran > 0) under the same execution identity (bun and node versions,
|
||||
* OS, architecture and runner image; lockfiles and pins are tree content) within --max-age
|
||||
* hours (default 24); a newer failure on that tree vetoes an older pass. The
|
||||
* reuse appends a copy that keeps the original timestamp, so check's max age
|
||||
* still measures the real run.
|
||||
*
|
||||
* `record-ci` writes the explicit CI-sourced row for a lane CI carried: it
|
||||
* finds and verifies the run itself (lib/ci-carry.ts) for a command the base's
|
||||
* ship_lanes_from maps, then records source "ci", the runs and profiles, the
|
||||
* run's finish time as ts, bound to HEAD's clean tree; `carried` lists those
|
||||
* rows at the current tree for the ship receipt.
|
||||
*
|
||||
* MACHINE-LOCAL by design: neither the ledger nor the logs are brain-synced.
|
||||
* A synced record citing an unsynced log would grade FRESH on a machine where
|
||||
* the log doesn't exist.
|
||||
@@ -73,6 +90,10 @@ import { resultLine } from "../lib/result-codes";
|
||||
import { isUnavailable, loadPolicyFromBase, resolveBaseBranch } from "../lib/ship-policy";
|
||||
import { versionAtRef } from "../lib/restamp";
|
||||
import { bashCommandInvocation, runScriptSync, wtreeFingerprint } from "../lib/script-invocation";
|
||||
import { findCarry } from "../lib/ci-carry";
|
||||
import { isConfigUnavailable, loadConfigFromBase } from "../lib/pregate/config";
|
||||
import { buildRunCheck } from "../lib/pregate/run-check";
|
||||
import { runInventory } from "../lib/run-evidence";
|
||||
|
||||
const BIN_DIR = dirname(Bun.fileURLToPath(import.meta.url));
|
||||
const LOG_MAX_BYTES = 2 * 1024 * 1024;
|
||||
@@ -93,6 +114,16 @@ interface EvidenceRecord {
|
||||
wtree_changed?: string[];
|
||||
log_path?: string;
|
||||
redacted?: boolean;
|
||||
/** sha256 of the runtime the run had (identityDigest). */
|
||||
identity?: string;
|
||||
/** The original ts of the row a `run --reuse` copied. */
|
||||
reused_from?: string;
|
||||
/** "ci" for a lane CI carried (record-ci); absent for a local run. */
|
||||
source?: "ci";
|
||||
runs?: string[];
|
||||
profiles?: string[];
|
||||
/** The base policy that mapped a carried lane (record-ci), as `origin/<base>@<sha>:.gstack/pregate.json`. */
|
||||
policy?: string;
|
||||
/** The runner's own test count (executed for bun/jest/vitest/pytest/rspec; ran with skips included for gstack's shard runner and the remote gate), 0 for ZERO-RUN, or "unknown" when no supported summary was seen. */
|
||||
tests_ran?: number | "unknown";
|
||||
}
|
||||
@@ -369,7 +400,15 @@ async function cmdRun(argv: string[]): Promise<number> {
|
||||
const sep = argv.indexOf("--");
|
||||
if (li >= 0 && li + 1 < argv.length && (sep < 0 || li < sep)) label = argv[li + 1];
|
||||
if (sep < 0 || sep + 1 >= argv.length) {
|
||||
console.error("usage: gstack-evidence run --label <L> -- <cmd...>");
|
||||
console.error("usage: gstack-evidence run [--reuse [--max-age <hours>]] --label <L> -- <cmd...>");
|
||||
return 2;
|
||||
}
|
||||
const opts = argv.slice(0, sep);
|
||||
const reuse = opts.includes("--reuse") && !opts.includes("--no-reuse");
|
||||
const maxAgeAt = opts.indexOf("--max-age");
|
||||
const reuseMaxAge = maxAgeAt >= 0 ? Number(opts[maxAgeAt + 1]) : 24;
|
||||
if (!Number.isFinite(reuseMaxAge) || reuseMaxAge <= 0) {
|
||||
console.error(`gstack-evidence: --max-age must be a positive number of hours, got: ${JSON.stringify(opts[maxAgeAt + 1])}`);
|
||||
return 2;
|
||||
}
|
||||
const cmdArgv = argv.slice(sep + 1);
|
||||
@@ -388,6 +427,7 @@ async function cmdRun(argv: string[]): Promise<number> {
|
||||
} catch (e: any) {
|
||||
warn(`ledger setup failed (${e?.message ?? e}) — result will not be recorded`);
|
||||
}
|
||||
if (reuse && paths && reused(paths.file, label, cmdSha, reuseMaxAge)) return 0;
|
||||
const log = paths ? openLog(paths.logsDir, label, cmdSha) : undefined;
|
||||
|
||||
// Fingerprint the content BEFORE the child runs: a working-tree edit made
|
||||
@@ -525,6 +565,7 @@ function record(
|
||||
const wtreeAfter = currentWtree();
|
||||
if (wtreeBefore && wtreeAfter && wtreeBefore === wtreeAfter) {
|
||||
rec.wtree = wtreeAfter;
|
||||
rec.identity = identityDigest();
|
||||
} else if (wtreeBefore || wtreeAfter) {
|
||||
const changed = wtreeBefore && wtreeAfter ? (git(["diff", "--name-only", wtreeBefore, wtreeAfter]) ?? "").split("\n").map((s) => s.trim()).filter(Boolean) : [];
|
||||
if (changed.length) rec.wtree_changed = changed.slice(0, 5);
|
||||
@@ -545,6 +586,118 @@ function record(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* sha256 of the runtime a lane ran under: the bun and node on PATH, OS, architecture and runner image. The lockfiles and
|
||||
* pins the execution identity also names (lib/evidence-bundle.ts) are working-tree content, so the fingerprint binds them.
|
||||
*/
|
||||
function identityDigest(): string {
|
||||
const version = (b: string) => {
|
||||
const r = spawnSync(b, ["--version"], { encoding: "utf-8", timeout: 15000 });
|
||||
return r.status === 0 ? (r.stdout || "").trim().replace(/^v/, "") || null : null;
|
||||
};
|
||||
return sha256(JSON.stringify({ bun: version("bun"), node: version("node"), os: process.platform, arch: process.arch, image: process.env.GSTACK_RUNNER_IMAGE || null }));
|
||||
}
|
||||
|
||||
/**
|
||||
* `run --reuse`: the newest local row for this label, command and working tree decides. A counted pass under the same
|
||||
* identity within the max age is copied (original ts kept) and printed as a run would be; anything else runs the command.
|
||||
*/
|
||||
function reused(file: string, label: string, cmdSha: string, maxAgeHours: number): boolean {
|
||||
const wtree = currentWtree();
|
||||
if (!wtree) return false;
|
||||
let records: EvidenceRecord[] = [];
|
||||
try {
|
||||
records = readJsonl<EvidenceRecord>(file);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const newest = records.findLast((r) => r.label === label && r.cmd_sha256 === cmdSha && r.wtree === wtree && r.source === undefined);
|
||||
if (!newest || newest.exit !== 0 || typeof newest.tests_ran !== "number" || newest.tests_ran <= 0) return false;
|
||||
const age = Date.now() - Date.parse(newest.ts);
|
||||
if (!(age >= 0 && age <= maxAgeHours * 3600_000)) return false;
|
||||
if (newest.identity !== identityDigest()) return false;
|
||||
try {
|
||||
appendJsonl(file, { ...newest, reused_from: newest.reused_from ?? newest.ts }, { mode: 0o600 });
|
||||
} catch (e: any) {
|
||||
warn(`ledger append failed (${e?.message ?? e}) — running the command instead`);
|
||||
return false;
|
||||
}
|
||||
console.error(`gstack-evidence: reused label=${label} tree=${wtree.slice(0, 12)} from=${newest.ts}`);
|
||||
console.error(`gstack-evidence: recorded label=${label} exit=0 tests_ran=${newest.tests_ran} log=${newest.log_path ?? "-"}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* `record-ci`: carry a lane from CI. Its command must be a key of the base branch's ship_lanes_from; the run is found and
|
||||
* verified here (lib/ci-carry.ts) at HEAD's clean tree, so no caller supplies run ids, a test count or a tree. Never runs the lane.
|
||||
*/
|
||||
function cmdRecordCi(argv: string[]): number {
|
||||
const sep = argv.indexOf("--");
|
||||
const opts = sep < 0 ? argv : argv.slice(0, sep);
|
||||
const get = (name: string) => { const i = opts.indexOf(name); return i >= 0 ? opts[i + 1] : undefined; };
|
||||
const label = get("--label")?.replace(/[^a-zA-Z0-9._-]/g, "_");
|
||||
const base = get("--base");
|
||||
const command = sep < 0 ? "" : argv.slice(sep + 1).join(" ");
|
||||
if (!label || !base || !command || opts.length !== 4) {
|
||||
console.error("usage: gstack-evidence record-ci --label <L> --base <base> -- <command>");
|
||||
return 2;
|
||||
}
|
||||
const none = (reason: string, detail: string) => {
|
||||
console.error(`CARRY_NONE: ${reason}: ${detail}`);
|
||||
console.error(`gstack-evidence record-ci: label=${label} not carried; nothing recorded`);
|
||||
return 1;
|
||||
};
|
||||
const cwd = process.cwd();
|
||||
const loaded = loadConfigFromBase(cwd, base);
|
||||
if (isConfigUnavailable(loaded)) return none("config_unavailable", loaded.detail);
|
||||
if (loaded.errors.length) return none("config_invalid", loaded.errors.map((x) => `${x.path}: ${x.message}`).join("; "));
|
||||
const from = loaded.config.ship_lanes_from;
|
||||
if (!Object.prototype.hasOwnProperty.call(from, command)) return none("not_mapped", `the command is not a key of origin/${base}'s ship_lanes_from`);
|
||||
const m = from[command]!;
|
||||
const check = buildRunCheck(cwd, null, true, base);
|
||||
if ("error" in check) return none("profiles_unavailable", check.error);
|
||||
const head = git(["rev-parse", "HEAD"]);
|
||||
const tree = git(["rev-parse", "HEAD^{tree}"]);
|
||||
if (!head || !tree) return none("no_head", "HEAD is unreadable");
|
||||
const wtree = () => { const fp = wtreeFingerprint({ cwd, timeoutMs: 30000 }); return "tree" in fp ? fp.tree : null; };
|
||||
const v = findCarry(check, { profiles: m.profiles, head, tree, wtree, inventory: () => runInventory(m.inventory, cwd) });
|
||||
if (!v.ok) return none(v.reason, v.detail);
|
||||
let paths: ReturnType<typeof ledgerPath>;
|
||||
try {
|
||||
paths = ledgerPath();
|
||||
mkdirpSync(paths.dir);
|
||||
} catch (e: any) {
|
||||
console.error(`gstack-evidence record-ci: ledger setup failed (${e?.message ?? e}); nothing recorded`);
|
||||
return 1;
|
||||
}
|
||||
const runs = v.runs.map((r) => `${r.run_id}/${r.run_attempt}`);
|
||||
const rec: EvidenceRecord = {
|
||||
ts: new Date(v.runs.map((r) => r.finished_at).sort()[0]!).toISOString(), label, command, cmd_sha256: sha256(command), exit: 0, duration_s: 0,
|
||||
commit: head, tree, dirty: false, wtree: tree, tests_ran: v.tests, source: "ci", runs, profiles: m.profiles, policy: loaded.label,
|
||||
};
|
||||
appendJsonl(paths.file, rec, { mode: 0o600 });
|
||||
console.error(`gstack-evidence: recorded label=${label} exit=0 tests_ran=${v.tests} log=- source=ci runs=${runs.join(",")} policy=${loaded.label}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** `carried`: each label's newest row when it is a CI-sourced row at the current working tree, as the receipt's ci_carried entries. */
|
||||
function cmdCarried(argv: string[]): number {
|
||||
let records: EvidenceRecord[] = [];
|
||||
try {
|
||||
records = readJsonl<EvidenceRecord>(ledgerPath().file);
|
||||
} catch {
|
||||
records = [];
|
||||
}
|
||||
const wtree = currentWtree();
|
||||
const latest = new Map<string, EvidenceRecord>();
|
||||
for (const r of records) latest.set(r.label, r);
|
||||
const carried = [...latest.values()].filter((r) => r.source === "ci" && !!wtree && r.wtree === wtree && Array.isArray(r.runs))
|
||||
.flatMap((r) => r.runs!.map((ref) => { const [run, attempt] = ref.split("/").map(Number); return { lane: r.label, run, attempt, tree: r.wtree! }; }));
|
||||
if (argv.includes("--json")) console.log(JSON.stringify(carried));
|
||||
else for (const c of carried) console.log(`CI_CARRIED: ${c.lane} run=${c.run}/${c.attempt} tree=${c.tree.slice(0, 12)}`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
function cmdCheck(argv: string[]): number {
|
||||
// Parse: repeated --label, each optionally followed (anywhere later) by its
|
||||
// own --expect-cmd; pairing is positional — an --expect-cmd binds to the most
|
||||
@@ -605,7 +758,8 @@ function cmdCheck(argv: string[]): number {
|
||||
}
|
||||
const testsRan = typeof latest.tests_ran === "number" ? latest.tests_ran : "unknown";
|
||||
const changedDuringRun = Array.isArray(latest.wtree_changed) ? latest.wtree_changed.filter((p): p is string => typeof p === "string" && p !== "" && !/[\u0000-\u001f\u007f]/.test(p)).slice(0, 5) : [];
|
||||
const detail = `label=${label} exit=${latest.exit} tests_ran=${testsRan} ts=${latest.ts}${latest.log_path ? ` log=${latest.log_path}` : ""}`;
|
||||
const ci = latest.source === "ci" && Array.isArray(latest.runs) ? ` source=ci runs=${latest.runs.filter((s) => /^\d+\/\d+$/.test(s)).join(",")}` : "";
|
||||
const detail = `label=${label} exit=${latest.exit} tests_ran=${testsRan} ts=${latest.ts}${latest.log_path ? ` log=${latest.log_path}` : ""}${ci}`;
|
||||
let verdict: "FRESH" | "STALE" | "ZERO-RUN" = "FRESH";
|
||||
let reason = "";
|
||||
if (latest.exit !== 0) {
|
||||
@@ -756,6 +910,10 @@ const [, , sub, ...rest] = process.argv;
|
||||
try {
|
||||
if (sub === "run") {
|
||||
process.exit(await cmdRun(rest));
|
||||
} else if (sub === "record-ci") {
|
||||
process.exit(cmdRecordCi(rest));
|
||||
} else if (sub === "carried") {
|
||||
process.exit(cmdCarried(rest));
|
||||
} else if (sub === "check") {
|
||||
process.exit(cmdCheck(rest));
|
||||
} else if (sub === "bundle") {
|
||||
@@ -765,7 +923,7 @@ try {
|
||||
} else if (sub === "verify") {
|
||||
process.exit(cmdVerify(rest));
|
||||
} else {
|
||||
console.error("usage: gstack-evidence run|check|bundle|ancestor|verify ...");
|
||||
console.error("usage: gstack-evidence run|record-ci|carried|check|bundle|ancestor|verify ...");
|
||||
process.exit(2);
|
||||
}
|
||||
} catch (e: any) {
|
||||
|
||||
@@ -32,7 +32,7 @@ import * as path from 'node:path';
|
||||
import * as os from 'node:os';
|
||||
import { scanCandidate, parseGateIntegrityBlock, specDirectoryHoldsSpecs, type FileDiff, type CommitInfo } from '../lib/gate-diff/index';
|
||||
import {
|
||||
commitInfo, commitsInRange, defaultBase, diffCommit, diffWorkingTree, firstParent, headSha, mergeBase, noBaseFix, readClaudeMd, repoRoot,
|
||||
baseNote, commitInfo, commitsInRange, defaultBase, diffCommit, diffWorkingTree, firstParent, headSha, mergeBase, noBaseFix, readClaudeMd, repoRoot,
|
||||
resolveBase, resolvesToCommit, treePaths, untrackedAsAdded,
|
||||
} from '../lib/gate-diff/git';
|
||||
import { baseContainsHead, noDefaultBaseLine } from '../lib/default-base';
|
||||
@@ -162,8 +162,8 @@ function main(argv: string[]): number {
|
||||
process.stdout.write(`GATE_ERROR=no_base ref=${baseRef} fix=${noBaseFix(baseRef, root)}\n`);
|
||||
return 2;
|
||||
}
|
||||
if (base.local === 'fallback') console.error(`gstack-gate-diff: ${base.unrelatedRemote ? `${base.unrelatedRemote} shares no history with HEAD` : `no remote-tracking branch for ${baseRef}`}; base is the local ${baseRef}, which may lag its remote`);
|
||||
else if (base.local) console.error(`gstack-gate-diff: ${{ unrelated: `local ${baseRef} shares no history with HEAD`, missing: `no local branch ${baseRef}`, behind: `local ${baseRef} is behind ${base.ref}`, ahead: `local ${baseRef} is ahead of ${base.ref}`, diverged: `local ${baseRef} has diverged from ${base.ref}` }[base.local]}; base is ${base.ref}`);
|
||||
const note = baseNote(baseRef, base);
|
||||
if (note) console.error(`gstack-gate-diff: ${note}`);
|
||||
const mb = mergeBase(base.sha, head, root);
|
||||
if (!mb) {
|
||||
process.stdout.write(`GATE_ERROR=no_base ref=${baseRef} fix=${noBaseFix(baseRef, root)}\n`);
|
||||
|
||||
@@ -18,7 +18,9 @@
|
||||
# and named in the GSTACK_LAUNCH line as GSTACK_INSTALL_VERDICT=<path>. It is
|
||||
# the one record the bun shim, lib/pregate/runtime.ts and admission read.
|
||||
# Readers fall back to the schema 1 file keyed by the checkout alone,
|
||||
# <state root>/install-verdicts/<sha256(checkout realpath)>.json.
|
||||
# <state root>/install-verdicts/<sha256(checkout realpath)>.json. An install
|
||||
# profile's verdict (for=review-voice) at the keyed path yields to the launched
|
||||
# GSTACK_INSTALL_VERDICT, so a reviewer's install never shadows it (GST-1161).
|
||||
#
|
||||
# Admission (gstack-skill-start, after SESSION_KIND): an unattended session,
|
||||
# or an explicit GSTACK_SESSION_KIND=spawned session with GSTACK_CAPY=1,
|
||||
@@ -129,7 +131,10 @@ gstack_install_admission() {
|
||||
src=$(gstack_source_root "$bin") || src=""
|
||||
project=$(gstack_install_project "$src")
|
||||
file=$(gstack_install_verdict_path "${_GH:-$HOME/.gstack}" "$src" "$project")
|
||||
[ -f "$file" ] || [ -z "${GSTACK_INSTALL_VERDICT:-}" ] || file="$GSTACK_INSTALL_VERDICT"
|
||||
case "$(gstack_install_verdict_field "$file" schema_version 2>/dev/null)" in
|
||||
1|2) if gstack_doctor_install_profile "$(gstack_install_verdict_field "$file" for)" && [ -f "${GSTACK_INSTALL_VERDICT:-}" ]; then file="$GSTACK_INSTALL_VERDICT"; fi ;;
|
||||
esac
|
||||
[ -f "$file" ] || [ ! -f "${GSTACK_INSTALL_VERDICT:-}" ] || file="$GSTACK_INSTALL_VERDICT"
|
||||
[ -f "$file" ] || file=$(gstack_install_verdict_legacy_path "${_GH:-$HOME/.gstack}" "$src")
|
||||
code=INSTALL_UNVERIFIED
|
||||
fix="run the Capy skill installer (scripts/install.sh --for $skill) on this machine, then launch with the GSTACK_LAUNCH line it prints"
|
||||
|
||||
+32
-8
@@ -4,9 +4,10 @@
|
||||
*
|
||||
* gstack-pregate [run] [--stage preflight|tests|all] [--only <check,..>] [--base <branch>]
|
||||
* [--allow-repo-commands] [--policy-from base|head] [--out <pregate.json>]
|
||||
* [--timeout <s>] [--stall-timeout <s>] [--remote --spend-cap <usd>] [--run <id>] [--from-run <id|url>] [--explain] [--json]
|
||||
* [--timeout <s>] [--stall-timeout <s>] [--remote --spend-cap <usd>] [--run <id>] [--from-run <id|url>] [--no-ci-carry] [--explain] [--json]
|
||||
* gstack-pregate verify [--out <pregate.json>] [--json] publication check: current tree, no fail/incomplete, obligations cleared
|
||||
* gstack-pregate clear --remote <workflow.yml/job> --run-url <url> | --run <id|url> [--run …] [--allow-repo-commands] | --bundle-lane <label> | --receipt <file> [--out <pregate.json>]
|
||||
* [--flaky-exception "<test file>::<case>" … --pr <n> [--grant <approval id>]] a run with failures, under the owner's grant
|
||||
* gstack-pregate lanes [--explain] the lane list and platform tiers read from .github/workflows
|
||||
* gstack-pregate validate | init [--explain] [--force] the working-tree .gstack/pregate.json
|
||||
* gstack-pregate sealed [--range <a..b>] [--remote <name>] [--base <branch>] [--no-skip] [--json]
|
||||
@@ -36,6 +37,7 @@ import { CHECKS, CHECK_IDS, PREGATE_OUT_REL, PREGATE_TIER2, clearDecision, clear
|
||||
import { describeLane, discoverLanes } from '../lib/pregate/workflows';
|
||||
import { REMOTE_GATE_LANE } from '../lib/pregate/checks/lanes';
|
||||
import { describeSubstitution } from '../lib/pregate/remote-receipt';
|
||||
import { approvalGrants, describeExceptions, type FlakyInput } from '../lib/pregate/flaky-exception';
|
||||
import { ensureTmpExcluded } from '../lib/restamp';
|
||||
import { RESULT_CODES, resultCodeSuffix, resultLine } from '../lib/result-codes';
|
||||
import { DEFAULT_STALL_TIMEOUT_S } from '../lib/pregate/context';
|
||||
@@ -58,7 +60,10 @@ const HELP = `gstack-pregate — cheap checks before anything paid or remote (do
|
||||
verifies GitHub Actions runs against the base branch's run_profiles instead (docs/pregate.md#run-evidence):
|
||||
one run of the profile named after the lane, or for pregate.json/remote_gate one run per
|
||||
remote_gate_runs profile covering the gate's inventory (needs --allow-repo-commands); where a lane has a
|
||||
profile, --run-url is verified the same way
|
||||
profile, --run-url is verified the same way. --flaky-exception "<test file>::<case>" (at most 3) --pr <n>
|
||||
--grant <approval id> takes such runs with failures when every failure is named from the run's shard
|
||||
results and logs, outside the PR's diff and import closure, and an owner's gstack-approvals row binds
|
||||
them; without --grant it prints the row to record (pregate only; docs/pregate.md#flaky-exception)
|
||||
lanes print every CI lane with its platform tier (from .github/workflows/*.yml)
|
||||
validate | init the working-tree ${PREGATE_CONFIG_PATH}
|
||||
sealed [--range <a..b>] [--remote <name>] [--base <branch>] [--no-skip]
|
||||
@@ -94,6 +99,9 @@ const HELP = `gstack-pregate — cheap checks before anything paid or remote (do
|
||||
--from-run <id|url> a Free Tests run on this exact tree, verified against the base branch's run profile for this OS
|
||||
whose workflow holds a local lane (docs/pregate.md#from-run): the selected test files its tree.json lists count as passed and
|
||||
are recorded with its receipt; the rest still run. A refused run prints REUSE: refused and runs everything
|
||||
--no-ci-carry without --from-run, the tests stage looks up the newest verified CI run at HEAD's clean tree under
|
||||
those profiles itself and uses it (CI_CARRY: accepted <receipt> or CI_CARRY: none (<reason>);
|
||||
docs/pregate.md#ci-carry); this flag skips that lookup
|
||||
--explain print each selected test's provenance and each uncertain mapping
|
||||
--json one JSON object on stdout; a refusal before any check runs (unavailable base, invalid pin
|
||||
file, WTREE_UNAVAILABLE) is {ok:false,status:'refused',code,detail,fix,docs} with exit 3,
|
||||
@@ -112,9 +120,9 @@ function flag(args: string[], name: string): string | undefined { const i = args
|
||||
|
||||
/** Flags each verb accepts: `[flags that take a value, bare flags]`. Anything else is usage (exit 2), never a silent default run. */
|
||||
const VERB_FLAGS: Record<string, [string[], string[]]> = {
|
||||
run: [['--stage', '--only', '--base', '--policy-from', '--out', '--timeout', '--stall-timeout', '--spend-cap', '--run', '--from-run'], ['--allow-repo-commands', '--explain', '--json', '--remote']],
|
||||
run: [['--stage', '--only', '--base', '--policy-from', '--out', '--timeout', '--stall-timeout', '--spend-cap', '--run', '--from-run'], ['--allow-repo-commands', '--explain', '--json', '--remote', '--no-ci-carry']],
|
||||
verify: [['--out'], ['--json']],
|
||||
clear: [['--remote', '--run-url', '--run', '--bundle-lane', '--receipt', '--out'], ['--allow-repo-commands']],
|
||||
clear: [['--remote', '--run-url', '--run', '--bundle-lane', '--receipt', '--out', '--flaky-exception', '--pr', '--grant'], ['--allow-repo-commands']],
|
||||
lanes: [[], ['--explain', '--json']],
|
||||
validate: [[], ['--json']],
|
||||
init: [[], ['--explain', '--force']],
|
||||
@@ -179,6 +187,7 @@ async function cmdRun(root: string, rest: string[], json: boolean): Promise<numb
|
||||
}
|
||||
const ctx = loaded.ctx;
|
||||
if (fromRun !== undefined) ctx.fromRun = { ref: fromRun, check: buildRunCheck(root, null, allow, base) };
|
||||
if (rest.includes('--no-ci-carry')) ctx.ciCarry = false;
|
||||
ensureTmpExcluded(root);
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
process.once(signal, () => {
|
||||
@@ -219,7 +228,12 @@ function cmdVerify(root: string, rest: string[], json: boolean): number {
|
||||
if (!read.file) { for (const e of read.errors) process.stderr.write(resultLine('gstack-pregate verify', e.code, `${e.message} at ${e.path}`) + '\n'); return EXIT.fail; }
|
||||
const v = verifyPregate(root, read.file);
|
||||
if (json) { process.stdout.write(JSON.stringify({ ...v, verdict: read.file.verdict, tree: read.file.tree, head: read.file.head, out }) + '\n'); return v.ok ? EXIT.ok : EXIT.fail; }
|
||||
if (v.ok) { process.stdout.write(`PREGATE_VERIFY: ok ${v.message}\n`); return EXIT.ok; }
|
||||
if (v.ok) {
|
||||
const excepted = describeExceptions(read.file);
|
||||
if (excepted) process.stdout.write(`PREGATE: ${excepted}\n`);
|
||||
process.stdout.write(`PREGATE_VERIFY: ok ${v.message}\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
process.stderr.write(resultLine('gstack-pregate verify', v.code!, v.message) + '\n');
|
||||
for (const r of v.uncleared) process.stdout.write(`requires-remote: ${r.lane} (${r.platform}) ${r.tests.length} test(s) uncleared\n`);
|
||||
process.stdout.write(`PREGATE_VERIFY: refused ${v.code}\n`);
|
||||
@@ -229,6 +243,14 @@ function cmdVerify(root: string, rest: string[], json: boolean): number {
|
||||
function cmdClear(root: string, rest: string[]): number {
|
||||
const lane = flag(rest, '--remote');
|
||||
if (!lane) { process.stderr.write(`gstack-pregate clear: --remote <workflow.yml/job> with --run-url <url>, --bundle-lane <label> or (for ${REMOTE_GATE_LANE}) --receipt <file> is required\n`); return EXIT.usage; }
|
||||
const cases = rest.flatMap((a, i) => a === '--flaky-exception' ? [rest[i + 1]!] : []);
|
||||
let flaky: FlakyInput | undefined;
|
||||
if (cases.length) {
|
||||
if (!rest.includes('--run') && !rest.includes('--run-url')) { process.stderr.write('gstack-pregate clear: --flaky-exception needs --run <id|url>: an exception reads GitHub Actions runs\n'); return EXIT.usage; }
|
||||
const pr = Number(flag(rest, '--pr'));
|
||||
if (!Number.isInteger(pr) || pr <= 0) { process.stderr.write('gstack-pregate clear: --flaky-exception needs --pr <n>, the pull request the grant binds\n'); return EXIT.usage; }
|
||||
flaky = { cases, pr, grant: flag(rest, '--grant'), grantRow: approvalGrants(root) };
|
||||
} else if (flag(rest, '--pr') !== undefined || flag(rest, '--grant') !== undefined) { process.stderr.write('gstack-pregate clear: --pr and --grant apply only with --flaky-exception\n'); return EXIT.usage; }
|
||||
const out = outPath(root, rest);
|
||||
const read = fs.existsSync(out) ? readPregateFile(out) : { file: null, errors: [] };
|
||||
if (!read.file) { process.stderr.write(resultLine('gstack-pregate clear', 'PREGATE_STALE', `${out} is missing or invalid; run gstack-pregate first`) + '\n'); return EXIT.fail; }
|
||||
@@ -238,7 +260,7 @@ function cmdClear(root: string, rest: string[]): number {
|
||||
const checked = runs.length || runUrl || bundleLane ? buildRunCheck(root, lane, rest.includes('--allow-repo-commands')) : undefined;
|
||||
if (checked && 'error' in checked && (runs.length || checked.profiled)) { process.stderr.write(`gstack-pregate clear: ${checked.error}${checked.profiled ? `; ${lane} may have a run profile on the base branch, so it clears only with a verified --run` : ''}\n`); return EXIT.fail; }
|
||||
const evidence = checked && !('error' in checked) ? checked : undefined;
|
||||
const decision = clearDecision(read.file, lane, { runUrl, runs, bundleLane, receiptPath: flag(rest, '--receipt'), evidence }, root);
|
||||
const decision = clearDecision(read.file, lane, { runUrl, runs, bundleLane, receiptPath: flag(rest, '--receipt'), evidence, flaky }, root);
|
||||
if ('refused' in decision) {
|
||||
if (decision.refused === 'usage') { process.stderr.write(`gstack-pregate clear: ${decision.message}\n`); return EXIT.usage; }
|
||||
process.stderr.write(`gstack-pregate clear: receipt refused — ${decision.message}; fix: ${decision.fix ?? RESULT_CODES.PREGATE_RECEIPT_INVALID.fix} ${resultCodeSuffix('PREGATE_RECEIPT_INVALID')}\n`);
|
||||
@@ -246,9 +268,11 @@ function cmdClear(root: string, rest: string[]): number {
|
||||
}
|
||||
const current = readPregateFile(out).file;
|
||||
if (!current || current.tree !== read.file.tree || current.generated_at !== read.file.generated_at) { process.stderr.write(resultLine('gstack-pregate clear', 'PREGATE_STALE', `${out} changed while ${lane} was being verified; rerun the clear against the new file`) + '\n'); return EXIT.fail; }
|
||||
const file = clearObligation(current, lane, decision.receipt, `gstack-pregate clear ${new Date().toISOString()}`, decision.substitution);
|
||||
const file = clearObligation(current, lane, decision.receipt, `gstack-pregate clear ${new Date().toISOString()}`, decision.substitution, decision.exception);
|
||||
writePregateFile(root, out, file);
|
||||
if (/ runs=\S+ profiles=/.test(decision.receipt)) process.stdout.write(`REUSE: accepted ${lane} ${decision.receipt}\n`);
|
||||
const e = decision.exception;
|
||||
if (e) process.stdout.write(`FLAKY_EXCEPTION: accepted ${lane} cases=${e.cases.join(' | ')} run=${e.runs.join(',')} grant=${e.grant} by=${e.by} (pregate only; every required CI check still needs its own green run at this head)\n`);
|
||||
else if (/ runs=\S+ profiles=/.test(decision.receipt)) process.stdout.write(`REUSE: accepted ${lane} ${decision.receipt}\n`);
|
||||
if (decision.substitution) process.stdout.write(`PREGATE_RECEIPT_SUBSTITUTED: ${describeSubstitution(decision.substitution)}\n`);
|
||||
process.stdout.write(`PREGATE_CLEARED: ${lane} receipt=${decision.receipt} verdict=${file.verdict}${decision.attested ? ` (attested, not validated: ${lane} has no machine-checkable receipt)` : ''}\n`);
|
||||
if (checked && 'error' in checked) process.stderr.write(`gstack-pregate clear: run profiles unavailable (${checked.error}); ${lane} was recorded without run verification\n`);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
|
||||
import { baseArg } from '../lib/gate-diff/git';
|
||||
import { lintFiles, renderProseLint } from '../lib/prose-lint';
|
||||
import { resultLine } from '../lib/result-codes';
|
||||
|
||||
@@ -54,7 +55,7 @@ function main(argv: string[]): number {
|
||||
if ([base, sections, flags.has('--unreleased') || undefined].filter(Boolean).length > 1) { process.stderr.write('gstack-prose-lint: --unreleased, --base and --sections are different selections; pass one\n'); return EXIT.usage; }
|
||||
for (const f of files) if (!fs.existsSync(f) || fs.statSync(f).isDirectory()) { process.stderr.write(`gstack-prose-lint: cannot read ${f}\n`); return EXIT.usage; }
|
||||
let result;
|
||||
try { result = lintFiles(files, { unreleased: flags.has('--unreleased'), base, sections }); }
|
||||
try { result = lintFiles(files, { unreleased: flags.has('--unreleased'), base: base && baseArg('gstack-prose-lint', base, process.cwd()), sections }); }
|
||||
catch (e: any) { process.stderr.write(`gstack-prose-lint: ${e.message}\n`); return EXIT.usage; }
|
||||
if (sections && flags.has('--gate') && result.empty.length) {
|
||||
process.stderr.write(`gstack-prose-lint: no "## <section>" heading from --sections in ${result.empty.join(', ')}; nothing would be gated\n`);
|
||||
|
||||
@@ -414,8 +414,8 @@ function main(): number {
|
||||
const judged = flag('--judged');
|
||||
if (!merged || !judged) { process.stderr.write('gstack-review-dispatch judge: needs --merged <file> and --judged <file>\n'); return EXIT.usage; }
|
||||
const r = recordJudgment(ledger, readJsonl<MergedLine>(merged), readJsonl<JudgedLine>(judged), judged, merged);
|
||||
process.stdout.write(r.ok ? `JUDGMENT: ok added=${r.added.length} promoted=${r.promoted.length} folded=${r.folded.length}\n`
|
||||
: `JUDGMENT_REJECTED: dropped=${JSON.stringify(r.dropped)} downgraded=${JSON.stringify(r.downgraded)} unexplained=${JSON.stringify(r.unexplained)} invalid=${JSON.stringify(r.invalid)} (lead judgment may add or promote a finding, never drop or downgrade one)\n`);
|
||||
process.stdout.write(r.ok ? `JUDGMENT: ok added=${r.added.length} promoted=${r.promoted.length} folded=${r.folded.length}${r.dismissed.length ? ` dismissed=${r.dismissed.length}` : ''}\n`
|
||||
: `JUDGMENT_REJECTED: dropped=${JSON.stringify(r.dropped)} downgraded=${JSON.stringify(r.downgraded)} unexplained=${JSON.stringify(r.unexplained)} invalid=${JSON.stringify(r.invalid)} (lead judgment may add or promote a finding, never drop or downgrade one; a summary_candidate line may be lowered with a reason)\n`);
|
||||
return r.ok ? EXIT.ok : EXIT.fail;
|
||||
}
|
||||
if (cmd === 'verify') {
|
||||
|
||||
@@ -28,6 +28,7 @@ import { locate, readRecord } from '../lib/approval-record';
|
||||
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
|
||||
import { resultLine } from '../lib/result-codes';
|
||||
import { runScriptSync } from '../lib/script-invocation';
|
||||
import { baseNote } from '../lib/gate-diff/git';
|
||||
import { collectCommit, collectLive } from '../lib/review-collect';
|
||||
import { excludeLines, reviewExclude, type Exclusion } from '../lib/review-exclude';
|
||||
import { isUnavailable } from '../lib/ship-policy';
|
||||
@@ -126,8 +127,11 @@ function main(): number {
|
||||
for (const e of collected.errors) process.stderr.write(`gstack-review-plan: git could not list the diff (${e.input}: ${e.detail}); fix: ${e.repair}; no plan is safer than a plan for an empty diff\n`);
|
||||
return EXIT.fail;
|
||||
}
|
||||
const note = collected.base && baseNote(base, collected.base);
|
||||
if (note) process.stderr.write(`gstack-review-plan: ${note}\n`);
|
||||
const ref = collected.base?.ref ?? base;
|
||||
const head = git(['rev-parse', 'HEAD'])?.trim() ?? 'unknown';
|
||||
const self = collected.mergeBase === head ? baseContainsHead(root, git(['rev-parse', '--verify', '-q', `origin/${base}^{commit}`]) ? `origin/${base}` : base) : null;
|
||||
const self = collected.mergeBase === head ? baseContainsHead(root, ref) : null;
|
||||
if (self) { process.stderr.write(`${resultLine('gstack-review-plan', 'BASE_CONTAINS_HEAD', self)}; no plan is safer than a plan for a diff compared with itself\n`); return EXIT.fail; }
|
||||
const binDir = path.dirname(Bun.fileURLToPath(import.meta.url));
|
||||
const scopeOf = (args: string[]): Record<string, string> => {
|
||||
@@ -145,7 +149,6 @@ function main(): number {
|
||||
const gateTagsOf = (args: string[]): number | null => { const g = runGateDiff(args); return tagCount(g.stdout, g.status); };
|
||||
const diffBase = collected.mergeBase ?? base;
|
||||
const scope = scopeOf([diffBase]);
|
||||
const ref = git(['rev-parse', '--verify', '-q', `origin/${base}^{commit}`]) !== null ? `origin/${base}` : base;
|
||||
const baseSha = collected.registry.sha ?? git(['rev-parse', '--verify', '-q', `${ref}^{commit}`])?.trim() ?? '';
|
||||
const policy = baseSha ? loadPolicyAt(root, baseSha, ref) : null;
|
||||
const declares = !!policy && !isUnavailable(policy) && policy.policy.review_exclude_paths.length > 0;
|
||||
@@ -193,11 +196,11 @@ function main(): number {
|
||||
const gateScan = { tagged: gateTagged, head };
|
||||
if (has('--json')) {
|
||||
const { runtimeLines, stepDepth, depthReasons, ...rest } = plan;
|
||||
process.stdout.write(JSON.stringify({ ...rest, targeted: { ...targeted, brief, targeted_patch_id: patch }, step_depth: stepDepth, runtime_lines: runtimeLines, depth_reasons: depthReasons, depth_floor: floor ?? null, gate_scan: gateScan, fix_range: fixRange ?? null, registry: { sha: registry.sha, outputs: registry.outputs }, per_path: perPath, diff_lines: diffLines, pass, audit_effort: auditEffort, scope, gate_tagged: gateTagged, paths, deleted, stamp_only: stampOnly, consumed: collected.consumed, drawings: collected.drawings,
|
||||
process.stdout.write(JSON.stringify({ ...rest, targeted: { ...targeted, brief, targeted_patch_id: patch }, step_depth: stepDepth, runtime_lines: runtimeLines, depth_reasons: depthReasons, depth_floor: floor ?? null, gate_scan: gateScan, fix_range: fixRange ?? null, registry: { sha: registry.sha, outputs: registry.outputs }, per_path: perPath, diff_lines: diffLines, base: collected.base, pass, audit_effort: auditEffort, scope, gate_tagged: gateTagged, paths, deleted, stamp_only: stampOnly, consumed: collected.consumed, drawings: collected.drawings,
|
||||
...(exclusion.state === 'head-only' ? { review_exclude: exclusion } : active ? { review_exclude: { state: 'active', ...active.record, specs: active.specs, keep: active.keep, kept_files: active.kept, content: active.content, references: active.references } } : {}) }) + '\n');
|
||||
return EXIT.ok;
|
||||
}
|
||||
const out = [`REVIEW_CLASS: ${plan.class} (${plan.reasons.slice(0, 3).join('; ') || 'no signals'})`, reviewDepthLine(plan), `GATE_SCAN: ${gateTagged === null ? 'unavailable' : `tagged=${gateTagged}`} head=${head}`,
|
||||
const out = [`REVIEW_CLASS: ${plan.class} (${plan.reasons.slice(0, 3).join('; ') || 'no signals'})`, reviewDepthLine(plan), `GATE_SCAN: ${gateTagged === null ? 'unavailable' : `tagged=${gateTagged}`} head=${head}`, `REVIEW_BASE: ${ref} ${baseSha.slice(0, 12)}`,
|
||||
`TARGETED: classes=${classList(targeted.classes)} rules=${targeted.rules} brief=${brief} targeted_patch_id=${patch}${targeted.reasons.length ? ` reasons=${targeted.reasons.join('; ')}` : ''}`];
|
||||
out.push(...excludeLines(exclusion, base));
|
||||
if (fixRange) out.push(`FIX_RANGE: ${fixRange.runtime_lines === null ? `unread (${fixRange.error})` : `runtime_lines=${fixRange.runtime_lines}`} base=${fixRange.base}`);
|
||||
|
||||
@@ -127,7 +127,9 @@ var KNOWN_HOOKS = {
|
||||
"timeline-stop-hook": { source: "gstack-timeline-stop", event: "Stop", matcher: "", relpath: "hosts/claude/hooks/timeline-stop-hook" },
|
||||
"memorable-user-prompt-hook": { source: "gstack-memorable", event: "UserPromptSubmit", matcher: "", relpath: "hosts/claude/hooks/memorable-user-prompt-hook" },
|
||||
"gstack-session-update": { source: "gstack-session-update", event: "SessionStart", matcher: "", relpath: "bin/gstack-session-update" },
|
||||
"gstack-verify-gate": { source: "verify-gate", event: "Stop", matcher: "", relpath: "bin/gstack-verify-gate" }
|
||||
"gstack-verify-gate": { source: "verify-gate", event: "Stop", matcher: "", relpath: "bin/gstack-verify-gate" },
|
||||
"skill-route-hook": { source: "gstack-skill-route", event: "UserPromptSubmit", matcher: "", relpath: "hosts/claude/hooks/skill-route-hook" },
|
||||
"skill-contract-stop-hook": { source: "gstack-skill-contract", event: "Stop", matcher: "", relpath: "hosts/claude/hooks/skill-contract-stop-hook" }
|
||||
};
|
||||
function gsHadBashPrefix(c) { return String(c == null ? "" : c).trim().indexOf("bash ") === 0; }
|
||||
function gsStripWrap(c) {
|
||||
|
||||
+38
-10
@@ -37,9 +37,10 @@ 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 { branchSides, type BranchSide } from '../lib/stamp-only';
|
||||
import { branchSides, stampOnlyLine, type BranchSide } from '../lib/stamp-only';
|
||||
import { runScriptSync } from '../lib/script-invocation';
|
||||
import { readPregateFile, verifyPregate } from '../lib/pregate/index';
|
||||
import { exceptionConsumerProblem } from '../lib/pregate/flaky-exception';
|
||||
import { isUnavailable, loadPolicyFromBase, matchesAny, policyUnavailableLine, resolveBaseBranch, runningGstackVersion, stampFilesInTree, validatePolicy, type ShipPolicy } from '../lib/ship-policy';
|
||||
import { approvalForReceipt } from '../lib/approval-citations';
|
||||
import {
|
||||
@@ -174,6 +175,12 @@ function reviewedProduct(repoRoot: string, base: string, head: string, pregateFi
|
||||
return typeof id === 'string' ? { head_tree: tree, product_patch_id: id || 'none' } : { head_tree: tree };
|
||||
}
|
||||
|
||||
/** The lanes CI carried at the checked-out tree, from this machine's evidence ledger (gstack-evidence carried); undefined when none. */
|
||||
function ciCarried(): ShipReceipt['ci_carried'] {
|
||||
const r = runScriptSync(path.join(path.dirname(Bun.fileURLToPath(import.meta.url)), 'gstack-evidence'), ['carried', '--json'], { encoding: 'utf8', timeout: 60_000 });
|
||||
try { const list = JSON.parse(r.stdout); return Array.isArray(list) && list.length ? list : undefined; } catch { return undefined; }
|
||||
}
|
||||
|
||||
function cmdWrite(rest: string[], json: boolean): number {
|
||||
const repoRoot = git(['rev-parse', '--show-toplevel']) ?? process.cwd();
|
||||
const checkedOut = git(['rev-parse', 'HEAD'], repoRoot);
|
||||
@@ -264,7 +271,7 @@ function cmdWrite(rest: string[], json: boolean): number {
|
||||
version: flag(rest, '--version') ?? receiptVersion(repoRoot, head, base), 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')),
|
||||
gate: jsonArg(flag(rest, '--gate')), ci: jsonArg(flag(rest, '--ci')), ci_carried: ciCarried(),
|
||||
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'),
|
||||
@@ -468,15 +475,18 @@ function gitVersionBelow(repoRoot: string, minimum: string): string | null {
|
||||
return major > minMajor || (major === minMajor && minor >= minMinor) ? null : m[0];
|
||||
}
|
||||
|
||||
type PregateField = { pregate: string; requires_remote?: string[] };
|
||||
type PregateField = { pregate: string; requires_remote?: string[]; flaky_exception?: ShipReceipt['flaky_exception'] };
|
||||
/** A pregate result file → the receipt's pregate field, verified current for this checkout's tree (shared by write and carry). */
|
||||
function pregateFieldFor(repoRoot: string, file: string, head: string): { ok: true; field: PregateField } | { ok: false; errors: Array<{ code: string; message: string }> } {
|
||||
const read = readPregateFile(file);
|
||||
if (!read.file) return { ok: false, errors: read.errors.map(e => ({ code: e.code, message: `${e.message} at ${e.path}` })) };
|
||||
const v = verifyPregate(repoRoot, read.file);
|
||||
if (!v.ok) return { ok: false, errors: [{ code: v.code!, message: v.message ?? 'pregate is not current' }] };
|
||||
const foreign = exceptionConsumerProblem(read.file, head);
|
||||
if (foreign) return { ok: false, errors: [{ code: 'PREGATE_REMOTE_UNCLEARED', message: foreign }] };
|
||||
const remote = read.file.requires_remote ?? [];
|
||||
return { ok: true, field: { 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 exceptions = read.file.exceptions ?? [];
|
||||
return { ok: true, field: { 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, flaky_exception: exceptions.length ? exceptions.map(e => ({ lane: e.lane, runs: e.runs, cases: e.cases, grant: e.grant, by: e.by })) : undefined } };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -518,7 +528,7 @@ function productRules(repoRoot: string, base: string, outputs: readonly string[]
|
||||
* change, such as a CHANGELOG fragment next to the base's changelog.d/README.md
|
||||
* (GST-343, #3606), into the product patch-id at one head only.
|
||||
*/
|
||||
function productSpec(repoRoot: string, rules: ProductRules, from: string, to: string, branch?: { touched: ReadonlySet<string>; sides: ReadonlyArray<readonly [string, string]>; own: (rel: string) => BranchSide | undefined }): { changed: Array<{ path: string; class: ReturnType<typeof classifyCarryPath> }>; product: string[]; tests: string[] } | undefined {
|
||||
function productSpec(repoRoot: string, rules: ProductRules, from: string, to: string, branch?: { touched: ReadonlySet<string>; sides: ReadonlyArray<readonly [string, string]>; own: (rel: string) => BranchSide | undefined }): { changed: Array<{ path: string; class: ReturnType<typeof classifyCarryPath> }>; product: string[]; tests: string[]; demoted: string[]; ownRows: string[] } | undefined {
|
||||
const changedRaw = git(['diff', '--name-only', from, to], repoRoot);
|
||||
if (changedRaw === undefined) return undefined;
|
||||
const blobAt = (ref: string, p: string): string | null => { const r = spawnSync('git', ['show', `${ref}:${p}`], { cwd: repoRoot, encoding: 'utf8', timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }); return r.status === 0 ? r.stdout : null; };
|
||||
@@ -536,7 +546,19 @@ function productSpec(repoRoot: string, rules: ProductRules, from: string, to: st
|
||||
const demoted = !branch ? changed.filter(c => c.class === 'product' && matchesAny(rules.metadata, c.path)).map(c => c.path)
|
||||
: [...branch.touched].filter(p => stamped(p) && (changed.some(c => c.path === p && c.class === 'product') || branch.sides.some(([a, b]) => blobAt(a, p) !== blobAt(b, p) && classify(p, a, b) === 'product')));
|
||||
const metadataGlobs = rules.metadata.filter(g => !demoted.some(p => matchesAny([g], p)));
|
||||
return { changed, product: ['.', ...excludeGlobs(CARRY_TEST_GLOBS), ...excludeGlobs(metadataGlobs)], tests: [...CARRY_TEST_GLOBS.map(g => `:(glob)${g}`), ...excludeGlobs(metadataGlobs)] };
|
||||
// A demoted path whose from-to change is, line for line, a stamp on the branch's own rows (named by their position in
|
||||
// `from`), a regular file with the reviewed mode at both heads (GST-980): never the whole-text version swap.
|
||||
const ownRows = demoted.filter(p => {
|
||||
const side = branch?.own(p);
|
||||
const mode = (ref: string) => /^(100644|100755) blob /.exec(git(['ls-tree', ref, '--', p], repoRoot) ?? '')?.[1];
|
||||
const before = blobAt(from, p), after = blobAt(to, p), oldVersion = version(from), newVersion = version(to);
|
||||
if (!side || before === null || after === null || !oldVersion || !newVersion || !mode(from) || mode(from) !== mode(to)) return false;
|
||||
const was = before.split('\n');
|
||||
const now = after.split('\n');
|
||||
const lines = was.map((_, i) => i).filter(i => was[i] !== now[i]);
|
||||
return was.length === now.length && lines.length > 0 && lines.every(i => side.at.has(i + 1) && stampOnlyLine(was[i]!, now[i]!, oldVersion, newVersion, rules.templates, side, i + 1));
|
||||
});
|
||||
return { changed, product: ['.', ...excludeGlobs(CARRY_TEST_GLOBS), ...excludeGlobs(metadataGlobs)], tests: [...CARRY_TEST_GLOBS.map(g => `:(glob)${g}`), ...excludeGlobs(metadataGlobs)], demoted, ownRows };
|
||||
}
|
||||
|
||||
/** A commit's product patch-id against its merge base with the base ('' for no product diff), as write records it and a rewritten-history carry recomputes it. */
|
||||
@@ -667,6 +689,7 @@ function cmdCarry(rest: string[], json: boolean): number {
|
||||
const current = retarget ? headPatch : productHead;
|
||||
const changedProduct: string[] = [];
|
||||
const contextPaths: string[] = [];
|
||||
const stampOnly: string[] = [];
|
||||
if (retarget && reviewed !== current) changedProduct.push(`HEAD's product diff against ${base} is not the one reviewed against ${reviewedBase} (the parent has not fully landed on ${base}, or the branch changed since)`);
|
||||
else if (productFrom !== productHead && !retarget) {
|
||||
// planCarry names at most CARRY_NAMED_PATHS differing paths, so the walk stops there, and it reads only the paths the
|
||||
@@ -678,22 +701,27 @@ function cmdCarry(rest: string[], json: boolean): number {
|
||||
const moved = [touchedPaths(repoRoot, from, head), touchedPaths(repoRoot, fromBase, headBase)];
|
||||
if (moved.some(l => !l)) return refused('RECEIPT_CARRY_REFUSED', `git could not list the paths the branch touched against ${base}; run /ship on ${head.slice(0, 12)}`);
|
||||
const [movedHead, movedBase] = moved as Set<string>[];
|
||||
// A stamp file the branch changed as product (its own row) whose reviewed-to-current change is a stamp on its own lines
|
||||
// and that the base did not touch holds no unreviewed change, so the comparison leaves its bytes out (GST-980).
|
||||
for (const p of [...touched].filter(p => movedHead.has(p) || movedBase.has(p)).sort()) {
|
||||
if (changedProduct.length >= CARRY_NAMED_PATHS) break;
|
||||
const cls = changed.find(c => c.path === p)?.class ?? classifyCarryPath(p, rules.extra);
|
||||
if (cls === 'metadata' && spec.ownRows.includes(p) && !movedBase.has(p)) stampOnly.push(p);
|
||||
if (cls !== 'product') continue;
|
||||
const verdict = comparePath(repoRoot, sides, p);
|
||||
if (verdict === 'changed') changedProduct.push(p);
|
||||
else if (verdict === 'context') contextPaths.push(p);
|
||||
}
|
||||
if (!changedProduct.length && !contextPaths.length) changedProduct.push('(a product path outside the branch\'s touched files; compare the two base diffs)');
|
||||
const left = [...contextPaths, ...stampOnly];
|
||||
if (!changedProduct.length && !left.length) changedProduct.push('(a product path outside the branch\'s touched files; compare the two base diffs)');
|
||||
else if (!changedProduct.length) {
|
||||
const rest = [...spec.product, ...contextPaths.map(p => `:(exclude,literal)${p}`)];
|
||||
const rest = [...spec.product, ...left.map(p => `:(exclude,literal)${p}`)];
|
||||
const restFrom = patchId(repoRoot, fromBase, from, rest);
|
||||
const restHead = patchId(repoRoot, headBase, head, rest);
|
||||
if (typeof restFrom !== 'string' || typeof restHead !== 'string' || restFrom !== restHead) changedProduct.push(`(a product path outside ${contextPaths.join(', ')}; compare the two base diffs without them)`);
|
||||
if (typeof restFrom !== 'string' || typeof restHead !== 'string' || restFrom !== restHead) changedProduct.push(`(a product path outside ${left.join(', ')}; compare the two base diffs without them)`);
|
||||
}
|
||||
}
|
||||
const stampedRows = changedProduct.length ? [] : stampOnly;
|
||||
let scopedReview: string | undefined;
|
||||
const packetBody = !changedProduct.length && contextPaths.length ? contextPacket(repoRoot, { reviewedBase: fromBase, reviewed: from, currentBase: headBase, current: head }, contextPaths) : null;
|
||||
if (packetBody?.over.length) changedProduct.push(...packetBody.over.map(p => `${p} (too large for the scoped review: over ${PACKET_SECTION_CAP} lines in a section)`));
|
||||
@@ -723,7 +751,7 @@ function cmdCarry(rest: string[], json: boolean): number {
|
||||
// Evidence for the record, never the decision: a slow range-diff is reported unavailable rather than waited for.
|
||||
const rangeRaw = spawnSync('git', ['range-diff', '--no-color', `${fromBase}..${from}`, `${headBase}..${head}`], { cwd: repoRoot, encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024 * 1024 });
|
||||
const rangeDiff = rangeRaw.status === 0 ? (rangeRaw.stdout.trim().split('\n').slice(0, 20).join('\n') || '(empty: identical ranges)') : `unavailable: ${(rangeRaw.stderr ?? '').trim().split('\n')[0] || (rangeRaw.signal ? `range-diff killed by ${rangeRaw.signal} after 15 s` : 'range-diff failed')}`;
|
||||
plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(scopedReview ? { scopedReview } : {}) });
|
||||
plan = planCarry({ from, head, changed, productPatchId: { from: reviewed as string, head: current as string }, testPatchId: { from: testFrom, head: testHead }, changedProduct, mergeCommits: Number(mergeCommits) || 0, rangeDiff, ...(retarget ? { retargetedFrom: reviewedBase } : {}), ...(scopedReview ? { scopedReview } : {}), ...(stampedRows.length ? { stampedRows } : {}) });
|
||||
}
|
||||
if (!plan.ok) return refused(plan.code, plan.message);
|
||||
// Eligibility is not publication: a receipt that recorded a pregate is rebound only with a pregate current for HEAD,
|
||||
|
||||
Executable
+137
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/**
|
||||
* gstack-skill-contract — check a skill's contract against a Claude Code
|
||||
* transcript, list recorded misses, and acknowledge a waiver (GST-1088).
|
||||
*
|
||||
* Usage:
|
||||
* gstack-skill-contract check --transcript <path> --skill <name> [--skill-file <SKILL.md>] [--json]
|
||||
* gstack-skill-contract report [--json] [--session <id>]
|
||||
* gstack-skill-contract waive <item> --reason "<why>" [--skill <name>]
|
||||
* gstack-skill-contract --help
|
||||
*
|
||||
* check is a pure function of the transcript (lib/skill-contract.ts). waive is
|
||||
* stateless: it validates its arguments and prints an acknowledgement; check
|
||||
* finds the waiver by reading this Bash call in the transcript, and a waived
|
||||
* item counts as a miss for follow. Exit codes are stable:
|
||||
* 0 met (check) / done (report, waive) 1 unmet 2 usage
|
||||
* 3 state error 4 unknown transcript shape 5 no contract 6 skill not loaded
|
||||
* Each has an anchor in docs/skill-routing-and-contracts.md.
|
||||
*/
|
||||
import {
|
||||
EXIT, StateError, UnknownShape, blockMessage, checkContract, isMiss, lookupContract, parseTranscript, readAllRecords,
|
||||
readTranscriptFile, reportRows, type CheckResult,
|
||||
} from '../lib/skill-contract';
|
||||
import { installedSkillsDir } from '../lib/skill-route';
|
||||
|
||||
const USAGE = `Usage:
|
||||
gstack-skill-contract check --transcript <path> --skill <name> [--skill-file <SKILL.md>] [--json]
|
||||
gstack-skill-contract report [--json] [--session <id>]
|
||||
gstack-skill-contract waive <item> --reason "<why>" [--skill <name>]
|
||||
Exit: 0 met/done, 1 unmet, 2 usage, 3 state error, 4 unknown transcript shape, 5 no contract, 6 skill not loaded.
|
||||
Docs: docs/skill-routing-and-contracts.md`;
|
||||
const ITEM_ID = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
|
||||
|
||||
function die(code: number, line: string): never {
|
||||
process.stderr.write(`${line}\n`);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
/** --name value or --name=value; a missing value is a usage error. */
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === name) {
|
||||
const v = args[i + 1];
|
||||
if (v === undefined || v.startsWith('--')) die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: ${name} needs a value\n${USAGE}`);
|
||||
return v;
|
||||
}
|
||||
if (args[i].startsWith(`${name}=`)) return args[i].slice(name.length + 1);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function printCheck(result: CheckResult, json: boolean, code: number): void {
|
||||
if (json) {
|
||||
process.stdout.write(`${JSON.stringify({ exit: code, ...result }, null, 2)}\n`);
|
||||
return;
|
||||
}
|
||||
const head = result.met
|
||||
? `SKILL_CONTRACT_MET ${result.skill} (contract v1)${result.waived.length ? ` with waivers: ${result.waived.join(', ')} (misses for follow)` : ''}`
|
||||
: blockMessage(result);
|
||||
const lines = result.items.map(i => ` ${i.status.padEnd(7)} ${i.id}: ${i.detail}${i.reason ? ` (waived: ${i.reason})` : ''}`);
|
||||
process.stdout.write(`${[head, ...lines].join('\n')}\n`);
|
||||
}
|
||||
|
||||
function check(args: string[]): never {
|
||||
const transcriptPath = flag(args, '--transcript');
|
||||
const skill = flag(args, '--skill');
|
||||
const json = args.includes('--json');
|
||||
if (!transcriptPath || !skill) die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: check needs --transcript and --skill\n${USAGE}`);
|
||||
const found = lookupContract(skill, installedSkillsDir(), flag(args, '--skill-file'));
|
||||
if (!('contract' in found)) die(EXIT.NO_CONTRACT, `SKILL_CONTRACT_NO_CONTRACT ${skill}: ${found.error}`);
|
||||
let result: CheckResult;
|
||||
try {
|
||||
result = checkContract(parseTranscript(readTranscriptFile(transcriptPath)), skill, found.contract);
|
||||
} catch (e) {
|
||||
if (e instanceof StateError) die(EXIT.STATE_ERROR, `SKILL_CONTRACT_STATE_ERROR ${e.file}: ${e.why}`);
|
||||
if (e instanceof UnknownShape) die(EXIT.UNKNOWN_SHAPE, `SKILL_CONTRACT_UNKNOWN_SHAPE ${transcriptPath}: ${e.message}`);
|
||||
throw e;
|
||||
}
|
||||
if (!result.loaded) die(EXIT.NOT_LOADED, `SKILL_CONTRACT_NOT_LOADED ${skill}: ${transcriptPath} never loads it`);
|
||||
const code = result.met ? EXIT.MET : EXIT.UNMET;
|
||||
printCheck(result, json, code);
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
function report(args: string[]): never {
|
||||
const json = args.includes('--json');
|
||||
const session = flag(args, '--session');
|
||||
const { records, errors } = readAllRecords();
|
||||
const rows = reportRows(records.filter(r => !session || r.session_id === session), (rec, run) => {
|
||||
const found = lookupContract(run.skill, installedSkillsDir());
|
||||
if (!('contract' in found)) return null;
|
||||
try {
|
||||
const again = checkContract(parseTranscript(readTranscriptFile(rec.transcript_path)), run.skill, found.contract, { loadLine: run.load_line });
|
||||
return again.load ? again : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
const misses = rows.filter(isMiss);
|
||||
const byItem = new Map<string, number>();
|
||||
for (const row of misses) for (const id of [...row.missing, ...row.waived]) byItem.set(`${row.skill} ${id}`, (byItem.get(`${row.skill} ${id}`) ?? 0) + 1);
|
||||
if (json) {
|
||||
const items = [...byItem].map(([key, misses]) => ({ skill: key.split(' ')[0], item: key.split(' ')[1], misses }));
|
||||
process.stdout.write(`${JSON.stringify({ runs: rows.length, misses, items, errors }, null, 2)}\n`);
|
||||
process.exit(EXIT.MET);
|
||||
}
|
||||
const lines = [`SKILL_CONTRACT_REPORT runs=${rows.length} misses=${misses.length}`];
|
||||
for (const [key, n] of [...byItem].sort((a, b) => b[1] - a[1])) lines.push(` ${key}: ${n}`);
|
||||
for (const row of misses) {
|
||||
lines.push(` ${row.session} ${row.skill} ${row.outcome} missing=${row.missing.join(',') || '-'} waived=${row.waived.join(',') || '-'}`);
|
||||
}
|
||||
for (const err of errors) lines.push(` unreadable record: ${err}`);
|
||||
process.stdout.write(`${lines.join('\n')}\n`);
|
||||
process.exit(EXIT.MET);
|
||||
}
|
||||
|
||||
function waive(args: string[]): never {
|
||||
const item = args[0];
|
||||
const reason = (flag(args, '--reason') ?? '').trim();
|
||||
const skill = flag(args, '--skill');
|
||||
if (!item || item.startsWith('--') || !ITEM_ID.test(item)) die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: waive needs an item id matching ${ITEM_ID}\n${USAGE}`);
|
||||
if (!reason) die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: waive needs --reason "<why the item does not apply>"\n${USAGE}`);
|
||||
if (skill) {
|
||||
const found = lookupContract(skill, installedSkillsDir());
|
||||
if (!('contract' in found)) die(EXIT.NO_CONTRACT, `SKILL_CONTRACT_NO_CONTRACT ${skill}: ${found.error}`);
|
||||
if (!found.contract.items.some(i => i.id === item)) die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: ${skill}'s contract has no item ${item}`);
|
||||
}
|
||||
process.stdout.write(`SKILL_CONTRACT_WAIVED ${item}${skill ? ` (${skill})` : ''}: ${reason} (this session only; counted as a miss for follow)\n`);
|
||||
process.exit(EXIT.MET);
|
||||
}
|
||||
|
||||
const [cmd, ...rest] = process.argv.slice(2);
|
||||
if (cmd === 'check') check(rest);
|
||||
if (cmd === 'report') report(rest);
|
||||
if (cmd === 'waive') waive(rest);
|
||||
if (cmd === '--help' || cmd === '-h') { process.stdout.write(`${USAGE}\n`); process.exit(EXIT.MET); }
|
||||
die(EXIT.USAGE, `SKILL_CONTRACT_USAGE: unknown command ${JSON.stringify(cmd ?? '')}\n${USAGE}`);
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/**
|
||||
* gstack-skill-route — show how the skill-route hook scores a prompt (GST-1088).
|
||||
*
|
||||
* Usage:
|
||||
* gstack-skill-route --explain "<prompt>" [--json] [--threshold <n>]
|
||||
*
|
||||
* Prints the switch state, the threshold, every candidate skill with its
|
||||
* score and best trigger, the route the hook would take and the exact line it
|
||||
* would inject. Works with the switch off (a dry run): it never injects
|
||||
* anything. Exit 0, or 2 on a usage error. Docs: docs/skill-routing-and-contracts.md.
|
||||
*/
|
||||
import {
|
||||
ROUTE_THRESHOLD, hintLine, installedSkillsDir, readSkillSwitch, routePrompt, scanInstalledSkills,
|
||||
} from '../lib/skill-route';
|
||||
|
||||
const USAGE = 'Usage: gstack-skill-route --explain "<prompt>" [--json] [--threshold <n>]';
|
||||
const args = process.argv.slice(2);
|
||||
if (args[0] === '--help' || args[0] === '-h') { process.stdout.write(`${USAGE}\n`); process.exit(0); }
|
||||
const at = args.indexOf('--explain');
|
||||
const prompt = at >= 0 ? args[at + 1] : undefined;
|
||||
const tAt = args.indexOf('--threshold');
|
||||
const threshold = tAt >= 0 ? Number(args[tAt + 1]) : ROUTE_THRESHOLD;
|
||||
if (prompt === undefined || !Number.isFinite(threshold) || threshold <= 0 || threshold > 1) {
|
||||
process.stderr.write(`SKILL_ROUTE_USAGE: --explain needs a prompt; --threshold must be in (0, 1]\n${USAGE}\n`);
|
||||
process.exit(2);
|
||||
}
|
||||
const dir = installedSkillsDir();
|
||||
const { skills, problems } = scanInstalledSkills(dir);
|
||||
const decision = routePrompt(prompt, skills, threshold);
|
||||
const sw = readSkillSwitch('skill_routing');
|
||||
const hint = decision.route ? hintLine(decision.route) : null;
|
||||
if (args.includes('--json')) {
|
||||
process.stdout.write(`${JSON.stringify({
|
||||
switch: { on: sw.on, source: sw.source }, threshold, skills_dir: dir, skills: skills.length, problems,
|
||||
candidates: decision.candidates, route: decision.route?.skill ?? null, reason: decision.route ? null : decision.reason, hint,
|
||||
}, null, 2)}\n`);
|
||||
process.exit(0);
|
||||
}
|
||||
const lines = [
|
||||
`switch: skill_routing ${sw.on ? 'on' : 'off'} (${sw.source})${sw.invalid !== undefined ? `, unrecognized value ${JSON.stringify(sw.invalid)}` : ''}`,
|
||||
`threshold: ${threshold}`,
|
||||
`skills: ${skills.length} scanned in ${dir}${problems.length ? ` (${problems.join('; ')})` : ''}`,
|
||||
'candidates:',
|
||||
...(decision.candidates.length
|
||||
? decision.candidates.map(c => ` ${c.score.toFixed(2)} /${c.skill} "${c.trigger}" (${c.matched} words)`)
|
||||
: [' (none)']),
|
||||
decision.route ? `route: /${decision.route.skill}` : `route: none (${decision.reason})`,
|
||||
...(hint ? [`hint: ${hint}`] : []),
|
||||
];
|
||||
process.stdout.write(`${lines.join('\n')}\n`);
|
||||
Reference in new issue
Block a user