diff --git a/.claude/skills/pm-dispatch/references/contract-review.md b/.claude/skills/pm-dispatch/references/contract-review.md index 88ad6f373df..7cd9049a2f0 100644 --- a/.claude/skills/pm-dispatch/references/contract-review.md +++ b/.claude/skills/pm-dispatch/references/contract-review.md @@ -1,7 +1,5 @@ # 契约复核细则(按面) -见 landing-operations.md 〈入队与落地〉的条款②闸门;本文只放复核归属、资格与等复核标记。 - ## 复核归属与资格(按面;复核席章程见 `lanes/review.md`) - 欠不欠按面判 ⛔ 不按车道:diff 或认领申报碰下列任一面即欠达档复核,交付后当轮完成。 @@ -34,8 +32,10 @@ - 逾 24 小时条件未满的 hold 列入分诊轮次记录(`check-owed-reviews.mjs` 标出)。 - 复核记录 = 一条评论落 PR 或卡,席内与各子代理同形;散文、dev 自评、`os-dev-report` 不算。 - 同形 = `## Contract review` 题头之下 `Head-sha:` 行独占码段、①②③逐项、独立性对、PASS/FAIL。 -- 同形含首行 `Served-tier:`:值写该面所定档的常量名 `CONTRACT_REVIEW_TIER` 或 `TIER_DEFAULT`; - 无此行不成裁决;模板 `node scripts/pm/record-recognisers.mjs --template`,申报面加 `--face declaration`。 +- 同形含首行 `Served-tier:`:值为该面所定档常量名 `CONTRACT_REVIEW_TIER` 或 `TIER_DEFAULT`;无此行不 + 成裁决;模板 `node scripts/pm/record-recognisers.mjs --template`;前者只经写工具带 `--tier-evidence=` + 贴:子代理(调用显式传该档 model)给其输出文件,卡线程或席内复核给本会话 + `~/.claude/projects/*/.jsonl`;`verify-review-tier.mjs` 拒即重跑 ⛔ 不改档名。 - ④ 设计判断欠 schema、governed 规则文本、收窄三面,spec、skills、ADR 皆已在内 ⛔ 不另立面: 逐 `hits` 文件判改动对所引代码与验收场景是否成立,ADR 另判首个消费者与执行计划; 实现文件审合契约、diff 外只读;①–④ 合称完整复核,余面同形无 ④,⛔ 无第二条记录。 diff --git a/scripts/pm/label-write.mjs b/scripts/pm/label-write.mjs index e6f4dd05966..d3c23376a8c 100644 --- a/scripts/pm/label-write.mjs +++ b/scripts/pm/label-write.mjs @@ -164,7 +164,9 @@ * * judged by post-stamped's `judgeBody`, the ONE path its own `--comment` takes: the stamp contract with * `{{NOW}}` read by this act, the signature first line, a claim's keyed lines, a record's line, - * the decision facets. A refusal is exit 2 with zero writes, its text post-stamped's own. + * a record's tier (a record naming `CONTRACT_REVIEW_TIER` folds only with `--tier-evidence PATH`, + * the reviewing run's transcript `verify-review-tier.mjs` passes), the decision facets. A refusal + * is exit 2 with zero writes, its text post-stamped's own, naming this tool. * paced as every stroke: the dispatch POST behind `write-pace`, every write in it spaced by the executor. * read back after a success run, each part on its own line: `④ labels` and `④ assignees` against the ② * target; `④ comment` located on the board by its stored bytes (`pickRelayComment`) and judged by @@ -286,9 +288,11 @@ import process from 'node:process'; import { spawnSync } from 'node:child_process'; -import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +// The self-test's at-tier transcript fixture names the tier's value from the one place it is declared. +import { CONTRACT_REVIEW_TIER } from './dispatch-gates.mjs'; import { fileURLToPath } from 'node:url'; import { isEntrypoint } from '../invoked-as.mjs'; @@ -829,7 +833,7 @@ export function releaseTextRefusal(text) { * Returns `judgeBody`'s answer: `{ ok: true, rendered }` or `{ ok: false, * rendered, text }`. Pure given the instants. */ -export function composeReleaseBody({ text, resume, knock, serverNow, age, nowMs } = {}) { +export function composeReleaseBody({ text, resume, knock, serverNow, age, nowMs, tierEvidence = null } = {}) { // Both instants are READINGS taken off the board by this act, so they are // declared as `{{WAS:…}}` — the stamp contract's spelling for a quoted // clock — at seconds grain, beside whatever `{{NOW}}` the operator stamped. @@ -838,7 +842,7 @@ export function composeReleaseBody({ text, resume, knock, serverNow, age, nowMs `Released by \`label-write.mjs --release\`: re-check ${knock.id} ({{WAS:${seconds(knock.created_at)}}}) unanswered for ` + `${formatHoursMinutes(age.ageMs)} on the server clock {{WAS:${seconds(serverNow)}}}, at or past \`RECLAIM_AFTER_HOURS = ${RECLAIM_AFTER_HOURS}\`.`; const raw = `${String(text).replace(/\s+$/, '')}\n\n${resume.line}\n${provenance}`; - return judgeBody(raw, { mode: 'comment' }, nowMs, 'label-write'); + return judgeBody(raw, { mode: 'comment', tierEvidence }, nowMs, 'label-write'); } /** @@ -943,6 +947,7 @@ export function parseOptions(argv) { recheckComment: null, commentFile: null, resumeFrom: null, + tierEvidence: null, }; const collect = { '--add': 'add', '--remove': 'remove', '--assign': 'assign', '--unassign': 'unassign' }; @@ -965,6 +970,7 @@ export function parseOptions(argv) { else if (flag === '--recheck-comment') opts.recheckComment = value(); else if (flag === '--comment-file') opts.commentFile = value(); else if (flag === '--resume-from') opts.resumeFrom = value(); + else if (flag === '--tier-evidence') opts.tierEvidence = value() ?? ''; else return { ok: false, error: `unrecognised option \`${flag}\`` }; } @@ -1012,6 +1018,8 @@ export function parseOptions(argv) { if (opts.clearAssignees && (opts.assign.length || opts.unassign.length)) { return { ok: false, error: '--clear-assignees cannot be combined with --assign/--unassign' }; } + if (opts.tierEvidence !== null && !opts.commentFile) return { ok: false, error: '--tier-evidence PATH is the transcript behind a `## Contract review` record and travels with --comment-file PATH; alone it judges nothing' }; + if (opts.tierEvidence === '') return { ok: false, error: '--tier-evidence names no file: pass the reviewing run\'s transcript, --tier-evidence PATH' }; if (opts.land && !opts.commentFile) return { ok: false, error: '--land folds the landing into a verdict comment\'s stroke and needs --comment-file PATH; a bare landing is the relay actions file `rest-channel.md` spells' }; const planned = opts.add.length || opts.remove.length || opts.assign.length || opts.unassign.length || opts.clearAssignees; if (opts.commentFile && !planned && !opts.land) { @@ -1032,7 +1040,7 @@ const USAGE = [ ' [--allow-two-states] [--dry-run] [--json]', ' node scripts/pm/label-write.mjs --issue N --release --recheck-comment ID --comment-file PATH', ` --resume-from BRANCH@SHA|${RESUME_FROM_NONE} [--repo OWNER/NAME] [--dry-run] [--json]`, - ' node scripts/pm/label-write.mjs --issue N [label/assignee flags] --comment-file PATH [--land] [--dry-run] [--json]', + ' node scripts/pm/label-write.mjs --issue N [label/assignee flags] --comment-file PATH [--tier-evidence PATH] [--land] [--dry-run] [--json]', ' node scripts/pm/label-write.mjs --self-test', '', ` --release reclaims a SILENT claim: ${RELEASE_FROM} → ${RELEASE_TO}, every assignee cleared, behind the \`Release:\``, @@ -1044,6 +1052,8 @@ const USAGE = [ ' --comment-file PATH beside a label/assignee change folds the comment (a Claim:, a Release:, a verdict) into the', ' SAME stroke, comment first, judged by post-stamped\'s own path (stamp, signature, keyed lines); --land appends', ' pr_ready then automerge_enable on a pull request. RELAY-ONLY; every part is read back on its own ④ line.', + ' A `## Contract review` record naming CONTRACT_REVIEW_TIER folds only with --tier-evidence PATH, the reviewing run\'s', + ' transcript, passed by verify-review-tier.mjs (post-stamped\'s rule; the path stays local).', '', ' Additive `POST .../labels` and directed `DELETE .../labels/{name}` first — neither can strip a', ' label a concurrent seat wrote. A platform refusal falls back ONCE to `PATCH .../issues/{n}` with', @@ -1364,7 +1374,7 @@ async function foldStroke(c) { } catch (e) { return refuse(`cannot read --comment-file ${options.commentFile}: ${e?.message ?? e}`); } - const judged = judgeBody(text, { mode: 'comment' }, c.clock().getTime(), 'label-write'); + const judged = judgeBody(text, { mode: 'comment', tierEvidence: options.tierEvidence }, c.clock().getTime(), 'label-write'); if (!judged.ok) { record(judged.text); nothing(); @@ -1643,7 +1653,7 @@ export async function runRelease(options, deps = {}) { const why = releaseTextRefusal(text); if (why) return refuse(why, { stoppedAt: 2 }); // Judged on post-stamped's path, as `--comment-file` is (header): an unsigned body is exit 2 here, before the stroke. - const judged = composeReleaseBody({ text, resume, knock: { id: knock.id, created_at: knock.created_at }, serverNow, age, nowMs: clock().getTime() }); + const judged = composeReleaseBody({ text, resume, knock: { id: knock.id, created_at: knock.created_at }, serverNow, age, nowMs: clock().getTime(), tierEvidence: options.tierEvidence }); if (!judged.ok) { record(judged.text); record(nothing()); @@ -2118,7 +2128,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the CLI: what a typo must never be allowed to mean': 8, 'the relay transport: ONE dispatch carrying the whole stroke, the same read-back, and an accepted dispatch with no run UNCONFIRMED under auto too — never a direct write': 14, 'the release: a silent claim reclaimed in ONE relay stroke — Release: comment → pm:queue on → pm:dispatched off → unassign — on the knock\'s SERVER-clock age, RELAY-ONLY, never a direct write': 34, - [FOLD_BATTERY]: 24, + [FOLD_BATTERY]: 28, [REAL_TRANSPORT_BATTERY]: 5, [STATELESS_BATTERY]: 19, }); @@ -2518,7 +2528,7 @@ export async function selfTest() { const composeSource = own.slice(own.indexOf('export function composeReleaseBody('), own.indexOf('export function releaseActions(')); const releaseSource = own.slice(own.indexOf('export async function runRelease('), own.indexOf('function reportPrerequisite(')); t('structural: --release judges its composed body with post-stamped\'s judgeBody before it packs the stroke, and label-write defines no reader of its own', [ - /return judgeBody\(raw, \{ mode: 'comment' \}, nowMs, 'label-write'\)/u.test(composeSource), + /return judgeBody\(raw, \{ mode: 'comment', tierEvidence \}, nowMs, 'label-write'\)/u.test(composeSource), releaseSource.indexOf('composeReleaseBody(') > 0 && releaseSource.indexOf('composeReleaseBody(') < releaseSource.indexOf('packRequest('), /\brenderBody\(/u.test(own), /function\s+(renderBody|signatureRefusal|claimKeyedLineRefusals|recordKeyedLineRefusals|decisionFacetRefusals|vacantLedgerRefusals)\b/u.test(own), @@ -2640,11 +2650,34 @@ export async function selfTest() { const dry = await fold([...claimArgv, '--dry-run'], queued, 'success', { send: async () => { throw new Error('a dry run must not dispatch'); } }); t('a dry run judges and packs the stroke, sends nothing, and says the board was never read back', [dry.exit, dry.res.dryRun, dry.res.payload?.actions.map((a) => a.op), dry.text.includes('never the board')], [EXIT_OK, true, ['comment', 'labels_add', 'labels_remove', 'assign'], true]); + // A `## Contract review` record naming the tier folds only on --tier-evidence that verify-review-tier passes. + const RECORD_FILE = '/tmp/self-test/record.md'; + const RECORD = `${SIG}\n## Contract review\n\nServed-tier: \`CONTRACT_REVIEW_TIER\`\nHead-sha: \`${'0123456789abcdef'.repeat(2)}01234567\`\nLocal-runs: none\n\n**VERDICT: PASS**\n`; + const recordArgv = ['--repo', 'objectstack-ai/objectstack', '--issue', '7', '--remove', 'needs:contract-review', '--comment-file', RECORD_FILE]; + const tierDir = mkdtempSync(join(tmpdir(), 'label-write-tier-')); + try { + const turn = (model) => JSON.stringify({ type: 'assistant', requestedModel: model, message: { role: 'assistant', model, content: [] } }); + const atTier = join(tierDir, 'at-tier.output'); + const offTier = join(tierDir, 'off-tier.output'); + writeFileSync(atTier, [turn(CONTRACT_REVIEW_TIER), turn(CONTRACT_REVIEW_TIER)].join('\n')); + writeFileSync(offTier, [turn(CONTRACT_REVIEW_TIER), turn('other-model-for-the-self-test')].join('\n')); + const recBoard = { kind: 'pull', labels: ['needs:contract-review', 'domain:skills'], serverNow: at }; + const recFiles = { files: { ...files, [RECORD_FILE]: RECORD } }; + const bare = await fold(recordArgv, recBoard, 'success', recFiles); + t('⛔ an at-tier RECORD folded with no --tier-evidence is refused by post-stamped\'s judge, naming THIS tool: exit 2, zero sends', [bare.exit, bare.sent.length, bare.text.includes('label-write: REFUSED'), bare.text.includes('--tier-evidence')], [EXIT_USAGE, 0, true, true]); + const off = await fold([...recordArgv, '--tier-evidence', offTier], recBoard, 'success', recFiles); + t('⛔ …and with a transcript one turn of which was served off the tier: exit 2, zero sends, no path in the refusal', [off.exit, off.sent.length, off.text.includes(tierDir)], [EXIT_USAGE, 0, false]); + const good = await fold([...recordArgv, '--tier-evidence', atTier], recBoard, 'success', recFiles); + t('⭐ …while the same record with an at-tier transcript folds: the record and the label removal in ONE dispatch, exit 0', [good.exit, good.sent.length, good.sent[0]?.actions.map((a) => a.op)], [EXIT_OK, 1, ['comment', 'labels_remove']], good.text.slice(-600)); + } finally { + rmSync(tierDir, { recursive: true, force: true }); + } + t('the CLI: --tier-evidence rides a --comment-file stroke; alone, or naming no file, it is refused', [parseOptions([...recordArgv, '--tier-evidence', 'x.output']).ok, parseOptions(['--issue', '7', '--add', 'x', '--tier-evidence', 'x.output']).ok, parseOptions([...recordArgv, '--tier-evidence=']).ok], [true, false, false]); t('the CLI: a lone --comment-file is post-stamped\'s write; --land needs --comment-file; --land never rides a --release', [parseOptions(['--issue', '7', '--comment-file', 'c.md']).ok, parseOptions(['--issue', '7', '--land']).ok, parseOptions([...RELEASE_ARGV, '--land']).ok], [false, false, false]); t('…while a claim fold, a verdict fold and a release all parse', [parseOptions(claimArgv).ok, parseOptions(verdictArgv).ok, parseOptions(RELEASE_ARGV).ok], [true, true, true]); const own = readFileSync(SELF_PATH, 'utf8'); const foldSource = own.slice(own.indexOf('async function foldStroke('), own.indexOf('export async function runRelease(')); - t('structural: the fold judges its comment with post-stamped\'s judgeBody and sends exactly ONE dispatch', [/judgeBody\(text, \{ mode: 'comment' \}/u.test(foldSource), (foldSource.match(/c\.send\(/gu) ?? []).length, /\bdoCall\('(label-add|label-delete|assignee-add|assignee-remove|card-patch)'/u.test(foldSource)], [true, 1, false]); + t('structural: the fold judges its comment with post-stamped\'s judgeBody and sends exactly ONE dispatch', [/judgeBody\(text, \{ mode: 'comment', tierEvidence: options\.tierEvidence \}/u.test(foldSource), (foldSource.match(/c\.send\(/gu) ?? []).length, /\bdoCall\('(label-add|label-delete|assignee-add|assignee-remove|card-patch)'/u.test(foldSource)], [true, 1, false]); const duties = readFileSync(new URL('.claude/skills/pm-dispatch/references/execution-duties.md', REPO_ROOT), 'utf8'); const landing = readFileSync(new URL('.claude/skills/pm-dispatch/references/landing-operations.md', REPO_ROOT), 'utf8'); t('↔ the procedure text sends a claim and a landing through the fold, so a seat reads ONE stroke where it used to read two', [duties.includes('--comment-file'), landing.includes('--land')], [true, true]); diff --git a/scripts/pm/post-stamped.mjs b/scripts/pm/post-stamped.mjs index 0cd05b646a8..a0f0713609f 100644 --- a/scripts/pm/post-stamped.mjs +++ b/scripts/pm/post-stamped.mjs @@ -972,7 +972,10 @@ import { CONTRACT_REVIEW_TIER, CONTRACT_REVIEW_TIER_NAME, TIER_DEFAULT, TIER_FLO // The record's `Local-runs:` line is read by the file that owns the record's // every other line — judged when present, an absent line not re-judged. // The mailbox doorbell is read by the same file: a knock's `To:` seat and its key come from `readMailboxLine`. -import { localRunsStand, readLocalRuns, readMailboxLine } from './record-recognisers.mjs'; +import { localRunsStand, readLocalRuns, readMailboxLine, readServedTier } from './record-recognisers.mjs'; +// A record that names `CONTRACT_REVIEW_TIER` is written only on the reviewer's transcript showing every turn served +// there: the judge lives in the file that owns it, ⛔ never a copy here. +import { verdictText as tierVerdictText, verifyReviewTranscriptFile } from './verify-review-tier.mjs'; // The fleet's repository roster — the one place a repository joins the fleet — // is what a read-back may collapse a reference expansion against (header). import { GOVERNED_REPOS } from './check-governed-merges.mjs'; @@ -2132,6 +2135,42 @@ export function recordLineRefusalText(rows) { ); } +// --------------------------------------------------------------------------- +// The record's tier — a record naming `CONTRACT_REVIEW_TIER` is written only on evidence that the tier served it +// --------------------------------------------------------------------------- + +/** + * Why a `## Contract review` record that names `CONTRACT_REVIEW_TIER` on its `Served-tier:` line cannot be written, + * or `null` when it can. The name is the seat's own declaration and AGENTS.md keeps the model identifier out of the + * comment, so the evidence stays local: `--tier-evidence=PATH` names the reviewing run's transcript (a sub-agent's output file, or a session's own) and + * `verify-review-tier.mjs` must pass on it (every turn served at the tier, no fallback). ⛔ The path and every model + * identifier stay out of the comment, and out of this refusal too. A record naming another tier and every comment + * that is not a record are untouched. Reads the evidence file and nothing else. + */ +export function recordTierEvidenceRefusal(body, tierEvidence) { + const text = String(body ?? ''); + if (!CONTRACT_REVIEW_HEADING_MARKER.test(text)) return null; + const served = readServedTier(text); + if (served.state !== 'read' || served.value !== CONTRACT_REVIEW_TIER_NAME) return null; + if (tierEvidence === null || tierEvidence === undefined) return { why: `no --tier-evidence was given — nothing shows this review was served at ${CONTRACT_REVIEW_TIER_NAME}` }; + const verdict = verifyReviewTranscriptFile(tierEvidence); + return verdict.ok ? null : { why: tierVerdictText(verdict) }; +} + +/** The refusal a caller reads, from `recordTierEvidenceRefusal`; `tool` names the sender, as the signature refusal does. */ +export function recordTierEvidenceRefusalText(refusal, { tool = 'post-stamped' } = {}) { + return ( + `${tool}: REFUSED — this \`## Contract review\` record declares \`Served-tier: ${CONTRACT_REVIEW_TIER_NAME}\` without evidence that passes. Nothing was written.\n` + + ` ${refusal.why}\n\n` + + ` Pass the transcript of the run that REVIEWED, as --tier-evidence=PATH on this ${tool} call: a review sub-agent's\n` + + ' output file (the Agent tool names it when the agent starts), or, for a review this session ran itself (a card\n' + + ' thread, or in-seat), this session\'s own transcript under ~/.claude/projects/ (SESSION.jsonl, every turn of it).\n' + + ' The file stays local; neither it nor any model identifier enters the comment. `node scripts/pm/verify-review-tier.mjs\n' + + ' PATH` reads the same verdict. A transcript that refuses means the review did not run at the tier: rerun it with the\n' + + ' tier\'s model passed explicitly, ⛔ never post the record as at-tier and ⛔ never rename its tier to clear this.' + ); +} + // --------------------------------------------------------------------------- // A VACANT seat body's ledger — refused BEFORE the write (#23396, ruling 6162084315, letter A) // --------------------------------------------------------------------------- @@ -3460,7 +3499,7 @@ export function unreadPassText(check) { /** The flags this tool takes. An argument outside this set is a typo, and a typo is refused. */ export const KNOWN_FLAGS = Object.freeze(['--dry-run', '--json', '--self-test', '--help', '-h']); -export const KNOWN_OPTIONS = Object.freeze(['comment', 'body', 'file', 'repo', 'ack-through']); +export const KNOWN_OPTIONS = Object.freeze(['comment', 'body', 'file', 'repo', 'ack-through', 'tier-evidence']); export function readOption(argv, name) { const prefix = `--${name}=`; @@ -3508,6 +3547,13 @@ export function parseOptions(argv) { return { ok: false, error: `\`${ack}\` is not a comment id. --ack-through=ID takes the numeric id of the newest comment on the card.` }; } } + const tierEvidence = readOption(args, 'tier-evidence'); + if (tierEvidence !== null && comment === null) { + return { ok: false, error: '--tier-evidence belongs to a comment (--comment=N): it is the transcript behind a `## Contract review` record, and a record IS a comment.' }; + } + if (tierEvidence === '') { + return { ok: false, error: '--tier-evidence= names no file. Pass the reviewing run\'s transcript (a sub-agent\'s output file, or this session\'s own): --tier-evidence=PATH.' }; + } return { ok: true, options: { @@ -3516,6 +3562,7 @@ export function parseOptions(argv) { file: readOption(args, 'file'), repo: readOption(args, 'repo'), ackThrough, + tierEvidence, dryRun: args.includes('--dry-run'), json: args.includes('--json'), }, @@ -3856,7 +3903,8 @@ function rearmThroughProxy(args) { * sender that folds a comment into a wider stroke (`label-write.mjs --comment-file`) judges it on exactly the path * `main` does, never a copy. `options.mode` is `comment` or `body`; `nowMs` is the clock the stamp substitutes; * `tool` names the sender in the signature refusal. Answers `{ ok: true, rendered }`, or `{ ok: false, rendered, - * text }` — `text` is what the caller prints before it exits refused with nothing written. Pure. + * text }` — `text` is what the caller prints before it exits refused with nothing written. Pure but for one read: the + * `options.tierEvidence` transcript, read only when the body is a record that names `CONTRACT_REVIEW_TIER`. */ export function judgeBody(input, options = {}, nowMs = Date.now(), tool = 'post-stamped') { const rendered = renderBody(input, nowMs); @@ -3872,6 +3920,9 @@ export function judgeBody(input, options = {}, nowMs = Date.now(), tool = 'post- // The record's line, on the same act and with the same scope: a record IS a comment. const record = options.mode === 'comment' ? recordKeyedLineRefusals(rendered.body) : []; if (record.length > 0) return { ok: false, rendered, text: recordLineRefusalText(record) }; + // The record's tier, on the same act: a record naming `CONTRACT_REVIEW_TIER` carries local evidence that passes. + const tier = options.mode === 'comment' ? recordTierEvidenceRefusal(rendered.body, options.tierEvidence ?? null) : null; + if (tier !== null) return { ok: false, rendered, text: recordTierEvidenceRefusalText(tier, { tool }) }; // ⛔ Comments only: a decision analysis is anchored on its card AS A COMMENT, and the handover check reads comments. const facets = options.mode === 'comment' ? decisionFacetRefusals(rendered.body) : []; if (facets.length > 0) return { ok: false, rendered, text: decisionFacetRefusalText(facets) }; @@ -3887,7 +3938,7 @@ export function judgeBody(input, options = {}, nowMs = Date.now(), tool = 'post- const USAGE = [ 'post-stamped — write a seat artefact to GitHub with a stamp this act read, never one typed from memory.', '', - ' node scripts/pm/post-stamped.mjs --comment=N [--file=PATH] [--repo=OWNER/NAME] [--dry-run] [--json]', + ' node scripts/pm/post-stamped.mjs --comment=N [--file=PATH] [--repo=OWNER/NAME] [--tier-evidence=PATH] [--dry-run] [--json]', ' node scripts/pm/post-stamped.mjs --body=N [--file=PATH] [--repo=OWNER/NAME] [--ack-through=ID] [--dry-run] [--json]', ' node scripts/pm/post-stamped.mjs --self-test', '', @@ -3916,7 +3967,9 @@ const USAGE = [ ' checkers that OWN them, and the comment is REFUSED when one cannot be read — a ceiling tier citing neither the', ' MANDATORY hit `--tier` printed nor a `reason:` included — and the refusal prints the spelling that can.', ' A `## Contract review` comment\'s `Local-runs:` line is read the same way when it is present (`none`, or', - ' `probe — REASON`); a record without the line is not re-judged.', + ' `probe — REASON`); a record without the line is not re-judged. A record whose `Served-tier:` names', + ' `CONTRACT_REVIEW_TIER` is REFUSED unless --tier-evidence=PATH names the reviewing run\'s transcript and', + ' `verify-review-tier.mjs` passes on it; the path and the model stay local, out of the comment.', ' A comment that is a decision analysis — a decision frame, an options table or lettered options, and a', ` recommendation naming one — is REFUSED when it carries no \`${DECISION_FACET_MARKER}\` marker outside code; the`, ' refusal prints the four-facet block it owes. Card bodies and every other route are untouched.', @@ -4155,8 +4208,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the signature: every body opens with LANE#N · ACCOUNT · SESSION or is refused, beside the stamp contract; one leading signature changes no reading': 11, 'the one judge: every body refusal on ONE path — `main` and `label-write.mjs --comment-file` call `judgeBody`, never a copy': 8, 'the review route: a `Request: contract-review` knock addressed to triage is refused; to a review or sibling seat, and every other key to triage, it passes': 10, + 'the record tier: a record naming `CONTRACT_REVIEW_TIER` is written only on a transcript `verify-review-tier.mjs` passes; another tier and a non-record comment are untouched': 15, }); -const SELF_TEST_BATTERY_FLOOR = 18; +const SELF_TEST_BATTERY_FLOOR = 29; const UNATTRIBUTED_BATTERY = '(unattributed)'; let selfTestReachedVerdict = false; @@ -5691,7 +5745,7 @@ export function selfTest() { t('structural: main reaches every body refusal through judgeBody alone, ⛔ no inline copy beside it', (mainOnly.match(/judgeBody\(/gu) ?? []).length === 1 && !/signatureRefusal\(|claimKeyedLineRefusals\(|decisionFacetRefusals\(|vacantLedgerRefusals\(/u.test(mainOnly)); let lw = ''; try { lw = readFileSync(new URL('./label-write.mjs', import.meta.url), 'utf8'); } catch { lw = ''; } - t('↔ structural: label-write imports judgeBody and judges its folded comment with it, ⛔ no reader of its own', /\bjudgeBody\b[^;]*from '\.\/post-stamped\.mjs'/u.test(lw) && /judgeBody\(text, \{ mode: 'comment' \}/u.test(lw) && !/function\s+(signatureRefusal|claimKeyedLineRefusals|decisionFacetRefusals)\b/u.test(lw)); + t('↔ structural: label-write imports judgeBody and judges its folded comment with it, ⛔ no reader of its own', /\bjudgeBody\b[^;]*from '\.\/post-stamped\.mjs'/u.test(lw) && /judgeBody\(text, \{ mode: 'comment', tierEvidence: options\.tierEvidence \}/u.test(lw) && !/function\s+(signatureRefusal|claimKeyedLineRefusals|decisionFacetRefusals)\b/u.test(lw)); } battery('the review route: a `Request: contract-review` knock addressed to triage is refused; to a review or sibling seat, and every other key to triage, it passes'); @@ -5714,6 +5768,50 @@ export function selfTest() { t('structural: the doorbell reader is imported from the file that owns it, ⛔ never restated, and the check runs inside judgeBody on comments only', /import \{[^}]*\breadMailboxLine\b[^}]*\} from '\.\/record-recognisers\.mjs';/u.test(own) && !/function\s+readMailboxLine\b/u.test(own) && /const triageKnock = options\.mode === 'comment' \? triageContractReviewKnock\(rendered\.body\) : null;/u.test(own)); } + battery('the record tier: a record naming `CONTRACT_REVIEW_TIER` is written only on a transcript `verify-review-tier.mjs` passes; another tier and a non-record comment are untouched'); + { + const SIG = 'domain:skills#1 · os-project-manager · session_01QSeKYmhU5KEj1nukYhp1Tg'; + const OTHER = 'other-model-for-the-self-test'; + const REC = (tierName) => [SIG, '## Contract review', '', `Served-tier: \`${tierName}\``, `Head-sha: \`${'0123456789abcdef'.repeat(2)}01234567\``, 'Local-runs: none', '', '**VERDICT: PASS**'].join('\n'); + const turn = (model) => JSON.stringify({ type: 'assistant', requestedModel: model, message: { role: 'assistant', model, content: [] } }); + const dir = mkdtempSync(join(tmpdir(), 'post-stamped-tier-')); + try { + const atTier = join(dir, 'at-tier.output'); + const offTier = join(dir, 'off-tier.output'); + const empty = join(dir, 'empty.output'); + writeFileSync(atTier, [JSON.stringify({ type: 'user', message: { role: 'user', content: 'review' } }), turn(CONTRACT_REVIEW_TIER), turn(CONTRACT_REVIEW_TIER)].join('\n')); + writeFileSync(offTier, [turn(CONTRACT_REVIEW_TIER), turn(OTHER)].join('\n')); + writeFileSync(empty, ''); + const judged = (body, tierEvidence) => judgeBody(body, { mode: 'comment', tierEvidence }, NOW_MS); + const none = judged(REC(CONTRACT_REVIEW_TIER_NAME), null); + t('⛔ a record naming CONTRACT_REVIEW_TIER with no --tier-evidence is refused', !none.ok && none.text.includes('--tier-evidence')); + t('⭐ …and the same record passes on a transcript served at the tier throughout', judged(REC(CONTRACT_REVIEW_TIER_NAME), atTier).ok); + const sessionAtTier = join(dir, 'session.jsonl'); + writeFileSync(sessionAtTier, [JSON.stringify({ type: 'queue-operation' }), JSON.stringify({ type: 'attachment', attachment: { type: 'model', identity: { modelId: CONTRACT_REVIEW_TIER } } }), turn(CONTRACT_REVIEW_TIER), JSON.stringify({ type: 'system', subtype: 'stop_hook_summary' })].join('\n')); + t('⭐ …and on a SESSION transcript run wholly at the tier — the path a card-thread or in-seat reviewer passes', judged(REC(CONTRACT_REVIEW_TIER_NAME), sessionAtTier).ok); + t('the refusal names the sender it was handed, and both evidence paths a reviewer can follow', (() => { + const lw = judgeBody(REC(CONTRACT_REVIEW_TIER_NAME), { mode: 'comment' }, NOW_MS, 'label-write'); + return !lw.ok && lw.text.startsWith('label-write: REFUSED') && lw.text.includes('output file') && lw.text.includes('~/.claude/projects/'); + })()); + const off = judged(REC(CONTRACT_REVIEW_TIER_NAME), offTier); + t('⛔ a transcript with one turn served off the tier is refused', !off.ok && off.text.includes('REFUSED')); + t('⛔ an empty transcript is refused', !judged(REC(CONTRACT_REVIEW_TIER_NAME), empty).ok); + t('⛔ a transcript path that cannot be read is refused, never thrown', !judged(REC(CONTRACT_REVIEW_TIER_NAME), join(dir, 'missing.output')).ok); + t('⛔ no refusal text carries a model identifier or the evidence path', [none, off, judged(REC(CONTRACT_REVIEW_TIER_NAME), join(dir, 'missing.output'))].every((r) => !r.ok && !String(r.text).includes(CONTRACT_REVIEW_TIER) && !String(r.text).includes(OTHER) && !String(r.text).includes(dir))); + t('⭐ a record naming TIER_DEFAULT is untouched, with no evidence', judged(REC('TIER_DEFAULT'), null).ok); + t('⭐ a comment that is not a record is untouched, with no evidence', judged(`${SIG}\nThe seat's own note: Served-tier: \`${CONTRACT_REVIEW_TIER_NAME}\` is what records carry.`, null).ok); + t('⭐ a card BODY is untouched — the check is a record\'s, and a record is a comment', judgeBody(REC(CONTRACT_REVIEW_TIER_NAME), { mode: 'body' }, NOW_MS).ok); + t('the CLI carries --tier-evidence=PATH on a comment, and leaves it null when absent', parseOptions(['--comment=1', `--tier-evidence=${atTier}`]).options.tierEvidence === atTier && parseOptions(['--comment=1']).options.tierEvidence === null); + t('⛔ --tier-evidence with --body, or with no path, is refused', parseOptions(['--body=1', '--tier-evidence=x']).ok === false && parseOptions(['--comment=1', '--tier-evidence=']).ok === false); + const verifier = spawnSync(process.execPath, [fileURLToPath(new URL('./verify-review-tier.mjs', import.meta.url)), '--self-test'], { encoding: 'utf8' }); + t('the verifier\'s own --self-test runs HERE, so CI runs it inside check:pm-post-stamped: exit 0 and its success line', verifier.status === 0 && /✓ verify-review-tier self-test: \d+ cases pass/u.test(verifier.stdout)); + const own = readFileSync(SELF_PATH, 'utf8'); + t('structural: the transcript judge is imported from verify-review-tier.mjs, ⛔ never restated here', /import \{[^}]*\bverifyReviewTranscriptFile\b[^}]*\} from '\.\/verify-review-tier\.mjs';/u.test(own) && !/function\s+(judgeReviewTranscript|verifyReviewTranscriptFile)\b/u.test(own)); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + } + // The floor, evaluated last: a battery that stops running names itself here. const failed = cases.filter((c) => !c.ok); for (const c of cases) console.log(` ${c.ok ? '✓' : '✗'} ${c.name}`); diff --git a/scripts/pm/verify-review-tier.mjs b/scripts/pm/verify-review-tier.mjs new file mode 100644 index 00000000000..71b401ec27d --- /dev/null +++ b/scripts/pm/verify-review-tier.mjs @@ -0,0 +1,278 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * verify-review-tier — was a contract-review sub-agent SERVED at `CONTRACT_REVIEW_TIER`? + * + * A `## Contract review` record names its tier as the constant's NAME (`Served-tier: CONTRACT_REVIEW_TIER`), + * because no model identifier may land in a comment. The name is a declaration the seat writes; nothing in the + * record proves which model served the review. A sub-agent launched without its tier's model parameter, or one + * the harness switched to another model mid-run, writes a record that reads exactly like an at-tier one. This + * script reads the reviewer's own transcript — the evidence that never leaves the seat's container — and answers + * whether every turn of it was served at the tier. + * + * ## Usage — from the repo root + * + * node scripts/pm/verify-review-tier.mjs PATH # the transcript of the run that reviewed + * node scripts/pm/verify-review-tier.mjs --self-test + * + * `post-stamped.mjs --tier-evidence=PATH` runs the same check before it writes a record that names the tier. + * + * ## The transcript it reads (measured on this harness, both shapes) + * + * Two transcripts, one format: a review SUB-AGENT's output file (the Agent tool names it when the agent starts), and + * a SESSION's own transcript (`~/.claude/projects/SLUG/SESSION.jsonl`) for a review the session ran itself — a card + * thread, or a seat reviewing in-seat. The session form carries every turn of the session, so it passes only when + * the WHOLE session ran at the tier; a session that ran at another tier refuses, as it should. Measured: a session + * transcript adds `queue-operation`, `last-prompt`, `mode` and `system` (`stop_hook_summary`) entries beside the + * same `assistant` and `attachment` entries; none of the extra kinds carries a model, so they are not judged. + * + * JSON Lines, one entry per line. An entry with `type: 'assistant'` is one model turn: `message.model` is the + * model that SERVED it and `requestedModel` the one the harness asked for. An entry with `type: 'attachment'` + * whose `attachment.type` is `model` carries `attachment.identity.modelId`, the model the run was told it is. + * The model-fallback notice ("switched to … because its earlier model could not be used") was seen only in the + * parent's completion notification, never in the sub-agent's file; a mid-run switch shows in the file as a turn + * served by another model, which refuses on its own. The notice is still refused if a harness-written `system` + * entry carries it. ⛔ The notice is NOT searched in tool results, assistant text or attachments: a review that + * reads this file, the rulebook or a memory note quoting the notice would refuse itself. + * + * ## Verdict — passes ONLY when all of these hold + * + * - the file reads, is non-empty, and every non-blank line parses as a JSON object; + * - at least one assistant turn exists, and every one names a served model equal to `CONTRACT_REVIEW_TIER` + * (a turn with no model field refuses: a turn nobody can attribute is not a turn at the tier); + * - every `requestedModel` and every `model` attachment present names the same value; + * - no `system` entry carries the fallback notice. + * + * ⛔ Output carries no model identifier and no transcript content: a seat may quote it, and AGENTS.md keeps model + * identifiers out of every GitHub artefact. A turn served elsewhere is named by its line number only. + * + * Boundary: this catches honest failure (a missing model parameter, a mid-run fallback). It does not stop a seat + * writing a false record or passing another run's transcript; that is the post-merge audit's job. + * + * Exit: 0 served at the tier · 1 refused (the reason is printed) · 2 usage. + */ + +import { readFileSync } from 'node:fs'; +import process from 'node:process'; +import { isEntrypoint } from '../invoked-as.mjs'; +import { CONTRACT_REVIEW_TIER, CONTRACT_REVIEW_TIER_NAME } from './dispatch-gates.mjs'; + +export const EXIT_OK = 0; +export const EXIT_REFUSED = 1; +export const EXIT_USAGE = 2; + +/** The harness's model-fallback notice, as the completion notification words it. */ +export const FALLBACK_NOTICE = /\bswitched to\b[^\n]*\bbecause its earlier model could not be used\b/i; + +/** Every string inside a value, flattened — for the notice scan of a harness `system` entry. */ +function stringsOf(value, out = []) { + if (typeof value === 'string') out.push(value); + else if (Array.isArray(value)) for (const v of value) stringsOf(v, out); + else if (value !== null && typeof value === 'object') for (const v of Object.values(value)) stringsOf(v, out); + return out; +} + +/** + * Judge one transcript's text. Pure. + * @param {string} text the transcript file's contents + * @param {string} tier the model value every turn must equal; defaults to `CONTRACT_REVIEW_TIER` + * @returns {{ ok: true, turns: number } | { ok: false, reason: string }} + */ +export function judgeReviewTranscript(text, tier = CONTRACT_REVIEW_TIER) { + const name = CONTRACT_REVIEW_TIER_NAME; + const raw = String(text ?? ''); + if (raw.trim() === '') return { ok: false, reason: 'the transcript is empty — no turn can be read, so none is at the tier' }; + let turns = 0; + const lines = raw.split(/\r?\n/); + for (let i = 0; i < lines.length; i += 1) { + const line = lines[i].trim(); + if (line === '') continue; + const at = `line ${i + 1}`; + let entry; + try { + entry = JSON.parse(line); + } catch { + return { ok: false, reason: `${at} is not JSON — a transcript that does not parse whole cannot show every turn` }; + } + if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) { + return { ok: false, reason: `${at} is not a JSON object — not a transcript entry` }; + } + if (entry.type === 'assistant') { + turns += 1; + const served = entry.message?.model; + if (typeof served !== 'string' || served === '') { + return { ok: false, reason: `${at} is an assistant turn with no served model — a turn nobody can attribute is not at ${name}` }; + } + if (served !== tier) return { ok: false, reason: `${at} is an assistant turn served by a model other than ${name}` }; + if ('requestedModel' in entry && entry.requestedModel !== tier) { + return { ok: false, reason: `${at} is an assistant turn whose requested model is not ${name}` }; + } + } else if (entry.type === 'attachment' && entry.attachment?.type === 'model') { + if (entry.attachment?.identity?.modelId !== tier) { + return { ok: false, reason: `${at} tells the run it is a model other than ${name}` }; + } + } else if (entry.type === 'system' && stringsOf(entry).some((s) => FALLBACK_NOTICE.test(s))) { + return { ok: false, reason: `${at} carries the harness's model-fallback notice — the run left ${name}` }; + } + } + if (turns === 0) return { ok: false, reason: `no assistant turn names a served model — nothing shows the review ran at ${name}` }; + return { ok: true, turns }; +} + +/** Read a transcript file and judge it. Never throws: an unreadable file is a refusal. */ +export function verifyReviewTranscriptFile(path, tier = CONTRACT_REVIEW_TIER) { + if (typeof path !== 'string' || path === '') return { ok: false, reason: 'no transcript path was given' }; + let text; + try { + text = readFileSync(path, 'utf8'); + } catch (err) { + return { ok: false, reason: `the transcript could not be read (${err.code ?? 'read error'})` }; + } + return judgeReviewTranscript(text, tier); +} + +/** The one-line verdict a caller prints. ⛔ No model identifier, no path. */ +export function verdictText(verdict) { + return verdict.ok + ? `verify-review-tier: PASS — ${verdict.turns} assistant turn(s), every one served at ${CONTRACT_REVIEW_TIER_NAME}.` + : `verify-review-tier: REFUSED — ${verdict.reason}.`; +} + +// --------------------------------------------------------------------------- +// Self-test — pinned battery NAMES with floors, and a verdict handshake (AGENTS.md, Writing a `--self-test`). +// --------------------------------------------------------------------------- + +let selfTestReachedVerdict = false; + +const SELF_TEST_BATTERIES = Object.freeze({ + 'passes: every turn at the tier': 4, + 'refuses: a turn, a request or an identity off the tier': 5, + 'refuses: the fallback notice in a harness entry, and only there': 3, + 'refuses: no model field, empty, unparseable or unreadable': 6, + 'output: no model identifier and no path in any verdict line': 2, +}); +const SELF_TEST_BATTERY_FLOOR = 5; + +function selfTest() { + const TIER = CONTRACT_REVIEW_TIER; + const OTHER = 'other-model-for-the-self-test'; + const seen = new Map(); + let current = null; + let failed = 0; + const battery = (name) => { + current = name; + }; + const t = (label, ok) => { + seen.set(current, (seen.get(current) ?? 0) + 1); + if (ok) console.log(` ✓ ${label}`); + else { + failed += 1; + console.error(` ✗ ${label}`); + } + }; + const jl = (...entries) => entries.map((e) => (typeof e === 'string' ? e : JSON.stringify(e))).join('\n'); + const user = { type: 'user', message: { role: 'user', content: 'review this' } }; + const turn = (model, requested = model) => ({ type: 'assistant', requestedModel: requested, message: { role: 'assistant', model, content: [] } }); + const ident = (modelId) => ({ type: 'attachment', attachment: { type: 'model', identity: { modelId } } }); + const NOTICE = 'This agent switched to another model because its earlier model could not be used.'; + const toolResult = (text) => ({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', content: text }] } }); + + battery('passes: every turn at the tier'); + const pass = judgeReviewTranscript(jl(user, ident(TIER), turn(TIER), turn(TIER))); + t('all turns at the tier, with a matching identity attachment, pass and count the turns', pass.ok && pass.turns === 2); + t('a turn with no requestedModel key still passes on its served model', judgeReviewTranscript(jl(user, { type: 'assistant', message: { model: TIER } })).ok); + t('blank lines and a trailing newline are not entries', judgeReviewTranscript(`${jl(user, turn(TIER))}\n\n`).ok); + const session = (...turns) => jl({ type: 'queue-operation', operation: 'enqueue' }, user, { type: 'last-prompt' }, ident(TIER), ...turns, { type: 'system', subtype: 'stop_hook_summary', content: 'hooks ran' }, { type: 'mode', mode: 'auto' }); + t('⭐ a SESSION transcript (a card thread or in-seat review) run wholly at the tier passes: its extra entry kinds carry no model', judgeReviewTranscript(session(turn(TIER), turn(TIER))).ok); + + battery('refuses: a turn, a request or an identity off the tier'); + t('one off-tier turn among at-tier turns refuses, naming its line', (() => { + const v = judgeReviewTranscript(jl(user, turn(TIER), turn(OTHER), turn(TIER))); + return !v.ok && v.reason.startsWith('line 3 '); + })()); + t('a run served entirely off the tier refuses', !judgeReviewTranscript(jl(user, turn(OTHER), turn(OTHER))).ok); + t('a turn served at the tier but requested as another model refuses', !judgeReviewTranscript(jl(user, turn(TIER, OTHER))).ok); + t('a model attachment naming another model refuses', !judgeReviewTranscript(jl(user, ident(OTHER), turn(TIER))).ok); + t('⛔ a SESSION transcript with one turn at another tier (a session that switched, or ran its own work elsewhere) refuses', !judgeReviewTranscript(session(turn(TIER), turn(OTHER), turn(TIER))).ok); + + battery('refuses: the fallback notice in a harness entry, and only there'); + t('a system entry carrying the fallback notice refuses', !judgeReviewTranscript(jl(user, turn(TIER), { type: 'system', content: NOTICE })).ok); + t('the notice nested in a system entry still refuses', !judgeReviewTranscript(jl(user, turn(TIER), { type: 'system', data: { lines: [NOTICE] } })).ok); + t('⛔ the notice quoted in a tool result (a reviewer reading the rulebook) does NOT refuse', judgeReviewTranscript(jl(user, toolResult(NOTICE), turn(TIER))).ok); + + battery('refuses: no model field, empty, unparseable or unreadable'); + t('an assistant turn with no model field refuses', !judgeReviewTranscript(jl(user, { type: 'assistant', message: { role: 'assistant', content: [] } })).ok); + t('a transcript with no assistant turn refuses', !judgeReviewTranscript(jl(user, ident(TIER))).ok); + t('an empty transcript refuses', !judgeReviewTranscript('').ok && !judgeReviewTranscript(' \n\n').ok); + t('a line that is not JSON refuses (a torn last line too)', !judgeReviewTranscript(`${jl(user, turn(TIER))}\n{"type":"assis`).ok); + t('a JSON value that is not an object refuses', !judgeReviewTranscript(jl(user, '[1,2]', turn(TIER))).ok); + t('a path that does not exist refuses with a reason, never throws', (() => { + const v = verifyReviewTranscriptFile('/nonexistent/verify-review-tier-self-test.output'); + return !v.ok && v.reason.includes('could not be read') && !verifyReviewTranscriptFile('').ok; + })()); + + battery('output: no model identifier and no path in any verdict line'); + const lines = [ + verdictText(pass), + verdictText(judgeReviewTranscript(jl(user, turn(OTHER)))), + verdictText(judgeReviewTranscript(jl(user, ident(OTHER), turn(TIER)))), + verdictText(judgeReviewTranscript(jl(user, turn(TIER, OTHER)))), + verdictText(verifyReviewTranscriptFile('/nonexistent/verify-review-tier-self-test.output')), + ]; + t('no verdict line carries the tier value or the other model', lines.every((l) => !l.includes(TIER) && !l.includes(OTHER))); + t('no verdict line carries the path it read', lines.every((l) => !l.includes('/nonexistent/'))); + + const floorFailure = (message) => { + failed += 1; + console.error(`✗ self-test floor: ${message}`); + }; + const declared = Object.keys(SELF_TEST_BATTERIES); + if (declared.length < SELF_TEST_BATTERY_FLOOR) { + floorFailure(`SELF_TEST_BATTERIES declares ${declared.length} batteries, below the pinned ${SELF_TEST_BATTERY_FLOOR}.`); + } + for (const [name, count] of seen) { + if (!(name in SELF_TEST_BATTERIES)) floorFailure(`battery "${name}" registered ${count} case(s) but is not declared.`); + } + for (const name of declared) { + const count = seen.get(name) ?? 0; + if (count < SELF_TEST_BATTERIES[name]) { + floorFailure( + count === 0 + ? `battery "${name}" DID NOT RUN — 0 cases registered, ${SELF_TEST_BATTERIES[name]} pinned.` + : `battery "${name}" registered ${count} case(s), below its pinned floor of ${SELF_TEST_BATTERIES[name]}.`, + ); + } + } + if (failed > 0) { + console.error(`\n✗ verify-review-tier self-test: ${failed} failure(s) (cases and floor).`); + process.exit(1); + } + console.log(`\n✓ verify-review-tier self-test: ${[...seen.values()].reduce((a, b) => a + b, 0)} cases pass across ${declared.length} batteries.`); + selfTestReachedVerdict = true; + return 0; +} + +function main(argv) { + const args = argv.filter((a) => a !== ''); + if (args.length !== 1 || args[0].startsWith('-')) { + console.error('usage: node scripts/pm/verify-review-tier.mjs PATH (the reviewing run\'s transcript: a sub-agent output file, or a session\'s own .jsonl) · --self-test'); + return EXIT_USAGE; + } + const verdict = verifyReviewTranscriptFile(args[0]); + (verdict.ok ? console.log : console.error)(verdictText(verdict)); + return verdict.ok ? EXIT_OK : EXIT_REFUSED; +} + +if (isEntrypoint(import.meta.url)) { + if (process.argv.includes('--self-test')) { + const code = selfTest(); + if (!selfTestReachedVerdict) { + console.error('\n✗ verify-review-tier self-test: selfTest() returned without reaching its verdict, so no success line was printed.'); + process.exit(1); + } + process.exit(code); + } else { + process.exit(main(process.argv.slice(2))); + } +}