diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index d480b01c6..efe200ebc 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -32,7 +32,7 @@ import { gateOutcomeLine } from '../lib/gate-outcomes'; import { runScriptSync } from '../lib/script-invocation'; import { baseNote } from '../lib/gate-diff/git'; import { collectCommit, collectLive, reviewPlanTimeoutMs } from '../lib/review-collect'; -import { excludeLines, reviewExclude, type Exclusion } from '../lib/review-exclude'; +import { excludeLines, fallbackLine, reviewExclude, type Exclusion } from '../lib/review-exclude'; import { isUnavailable } from '../lib/ship-policy'; import { reviewPolicy } from '../lib/ship-policy-review'; import { platformReviewAt } from '../lib/review-platform'; @@ -249,6 +249,7 @@ function main(): number { if (gateTagged !== null && !Number.isFinite(gateTagged)) gateTagged = null; const exclusion: Exclusion = !baseSha || !collected.mergeBase ? { state: 'none' } : reviewExclude({ root, baseSha, ref, mergeBase: collected.mergeBase, perPath: collected.perPath, added: collected.added, classRoot: root, gateTagged: tagged, context: 'gstack-review-plan' }); if (exclusion.state === 'refused') { for (const l of exclusion.lines) process.stderr.write(l + '\n'); return exclusion.code === 'REVIEW_DIFF_UNREADABLE' ? EXIT.fail : EXIT.refused; } + if (exclusion.state === 'fallback') process.stderr.write(`gstack-review-plan: ${fallbackLine(exclusion, base)}\n`); const active = exclusion.state === 'active' ? exclusion : null; const kept = (rec: Record) => (active ? Object.fromEntries(Object.entries(rec).filter(([p]) => !active.excluded.has(p))) : rec); const exclusionInput = active ? { excluded: active.excluded, exclusion: { specs: active.specs, keep: active.keep } } : {}; @@ -310,7 +311,7 @@ function main(): number { if (has('--json')) { const { runtimeLines, stepDepth, depthReasons, ...rest } = plan; process.stdout.write(JSON.stringify({ ...rest, review_policy: review, platform_review: platform ? (platform.ok ? platform.review : { none: platform.reason }) : null, readers, 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, targeted_delta: targetedDeltaOut, 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, executables: collected.executables, - ...(exclusion.state === 'head-only' ? { review_exclude: exclusion } : active ? { review_exclude: { state: 'active', ...active.record, specs: active.specs, keep: active.keep, excerpt: active.excerpt, kept_files: active.kept, content: active.content, references: active.references } } : {}) }) + '\n'); + ...(exclusion.state === 'head-only' || exclusion.state === 'fallback' ? { review_exclude: exclusion } : active ? { review_exclude: { state: 'active', ...active.record, specs: active.specs, keep: active.keep, excerpt: active.excerpt, 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}`, `REVIEW_BASE: ${ref} ${baseSha.slice(0, 12)}`, diff --git a/bin/gstack-ship-policy b/bin/gstack-ship-policy index aa39e97dd..376099ffc 100755 --- a/bin/gstack-ship-policy +++ b/bin/gstack-ship-policy @@ -17,6 +17,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { EXIT, exitTableHelp } from '../lib/headless-artifacts'; import { resultLine } from '../lib/result-codes'; +import { fallbackLine } from '../lib/review-exclude'; import { BUMP_NEVER_KEY_VERSION, POLICY_KEYS, POLICY_KEY_INTRODUCED, SHIP_POLICY_PATH, examplePolicyJson, explainPolicy, isUnavailable, loadPolicyFromBase, loadPolicyFromHead, minimumReader, policyUnavailableLine, renderEffective, resolveBaseBranch, type LoadedPolicy, @@ -91,6 +92,8 @@ function main(argv: string[]): number { if (cmd === 'validate' || cmd === 'show-effective') { const loaded = load(root, rest, cmd === 'validate' ? 'head' : 'base'); if (typeof loaded === 'number') return loaded; + if (loaded.setAside && cmd === 'validate') loaded.errors = loaded.setAside; + else if (loaded.setAside) process.stderr.write(`gstack-ship-policy: ${fallbackLine({ state: 'fallback', source: loaded.source.label, errors: loaded.setAside.map(e => `${e.path}: ${e.message}`) }, flag(rest, '--base') ?? resolveBaseBranch(root))}\n`); const floor: ReturnType = cmd === 'validate' && loaded.present ? floorAgainstStable(loaded.policy.min_gstack_version, newestStableRelease()) : {}; if (floor.error) loaded.errors.push(floor.error); const set = POLICY_KEYS.filter(k => loaded.values[k] && loaded.values[k] !== 'default'); diff --git a/bin/gstack-ship-receipt b/bin/gstack-ship-receipt index e41c4aa62..e8d18e323 100755 --- a/bin/gstack-ship-receipt +++ b/bin/gstack-ship-receipt @@ -57,7 +57,7 @@ import { import { checkDocsCaps, docsCapLine, docsExceptionLine, parseReceiptDocs } from '../lib/ship-receipt-docs'; import { comparePath, contextPacket, PACKET_SECTION_CAP, readScopedReview, touchedPaths } from '../lib/ship-patch'; import { planRecheck, recheckPacket } from '../crew/lib/ship-recheck'; -import { carryExcludeBinds, deeper, depthBelow, exceptionHead, exceptionLoopProblem, exceptionProblems, parseReviewLoopException, parseReviewTargeted, plainDocsSince, platformReceiptDepth, receiptExclude, receiptReviewAtHead, receiptTargetedAtHead, reviewLoopExceptionLine, targetedClassesSince, writeExcludeBinds } from '../lib/ship-receipt-depth'; +import { carryExcludeBinds, deeper, depthBelow, exceptionHead, exceptionLoopProblem, exceptionProblems, parseReviewLoopException, parseReviewTargeted, plainDocsSince, platformReceiptDepth, receiptExclude, receiptExcludeFallback, receiptReviewAtHead, receiptTargetedAtHead, reviewLoopExceptionLine, targetedClassesSince, writeExcludeBinds } from '../lib/ship-receipt-depth'; import { RISK_CLASSES, type RiskClass } from '../lib/review-risk'; import { checkReceiptProse, proseLine } from '../lib/ship-receipt-prose'; import { resolveStateRoot } from '../lib/state-root'; @@ -390,6 +390,7 @@ function cmdWrite(rest: string[], json: boolean): number { design: review.frontend ? { mode: 'static', reason: 'no preview declared' } : undefined, base_red: pause ? receiptBaseRed(pause) : undefined, review_exclude: receiptExclude(review.exclude), + review_exclude_fallback: receiptExcludeFallback(review.exclude), no_stop: noStopArg(flag(rest, '--no-stop')), }; } catch (e: any) { process.stderr.write(`gstack-ship-receipt write: ${e.message}\n`); return EXIT.usage; } @@ -824,7 +825,7 @@ function cmdCarry(rest: string[], json: boolean): number { const digest = review.exclude.state === 'active' ? review.exclude.record.digest : 'none'; if (!carryExcludeBinds(review.exclude, receipt)) return refused('RECEIPT_CARRY_REFUSED', `review_exclude changed: recorded=${receipt.review_exclude?.digest ?? 'none'} now=${digest} source=${review.exclude.state === 'active' ? review.exclude.record.source : `${base} (no review_exclude_paths)`}; the receipt's digest is the --review-exclude argument write was given, and it names another selection than HEAD ${head.slice(0, 12)} has under the base policy and the two give the PR's files different selections (carry compares those, not the review ledger), so carry does not apply; run /ship on ${head.slice(0, 12)}`); if (depthBelow(receipt.review_depth.depth, now.depth)) return refused('RECEIPT_CARRY_REFUSED', `HEAD ${head.slice(0, 12)} needs ${now.depth} review depth (${now.reasons.join(', ')}), above the receipt's ${receipt.review_depth.depth}; run /ship on ${head.slice(0, 12)}`); - depthField = { review_depth: { ...now, depth: deeper(receipt.review_depth.depth, now.depth) }, review_exclude: receiptExclude(review.exclude) }; + depthField = { review_depth: { ...now, depth: deeper(receipt.review_depth.depth, now.depth) }, review_exclude: receiptExclude(review.exclude), review_exclude_fallback: receiptExcludeFallback(review.exclude) }; } // The rebound product_patch_id is HEAD's diff against the carry's base, so a retargeted receipt names that base from now on. // A receipt that records a version names HEAD's, read as write reads it: a restamp after a base merge moves it (GST-1030). diff --git a/changelog.d/base-policy-exclusion-fallback.md b/changelog.d/base-policy-exclusion-fallback.md new file mode 100644 index 000000000..cc41eeba6 --- /dev/null +++ b/changelog.d/base-policy-exclusion-fallback.md @@ -0,0 +1 @@ +**A base branch whose `review_exclude_paths` list breaks the policy schema no longer stops every /ship.** When the only errors in the base's `.gstack/ship-policy.json` are in `review_exclude_paths` or `review_content_patterns` (such as 65 patterns, past the limit of 64), `gstack-review-plan` sets both keys aside and reviews every file, applies every other key as committed, and prints `REVIEW_EXCLUDE: fallback (WARNING: …)` with each error and the fix; the ship receipt records it as `review_exclude_fallback`, and every other step that reads the base policy reads it the same way, so the PR that corrects the list can be reviewed and land; `gstack-ship-policy validate` still reports the list as invalid. Before, every plan on that repository refused with `POLICY_INVALID`, the fixing PR's included. Any other invalid key still stops the plan, and a branch's own policy still never counts before it lands. (GST-3399) diff --git a/docs/ship-policy.md b/docs/ship-policy.md index 059694176..3152f777d 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1464,9 +1464,21 @@ whose content files `/ship`'s reviewers leave out: the base commit it already resolved (`origin/`, or ``), never the branch's copy, so a branch cannot exclude its own files. A branch that adds the key gets `REVIEW_EXCLUDE: none (head sets review_exclude_paths; it applies -after it lands on )` and a normal review. A base policy that does not -validate stops the plan (`POLICY_INVALID`), and a base git cannot read stops it -(`POLICY_SOURCE_UNAVAILABLE`); neither turns exclusion off quietly. +after it lands on )` and a normal review. A base policy whose only errors +are in `review_exclude_paths` or `review_content_patterns` (65 patterns, say, +past the limit of 64) does not stop the plan: both keys are set aside, every +file is reviewed as if the base excluded nothing, and every other key, the +readers' `forbid_paths` included, applies as committed. The plan prints +`REVIEW_EXCLUDE: fallback (WARNING: …)` naming each error and the fix, on +stdout and stderr, `--json` carries `review_exclude.state: "fallback"`, the +ship receipt records it as `review_exclude_fallback`, and every other step that +reads the base policy (`gstack-ship-policy show-effective`, which prints the +same warning on stderr, the pregate, the receipts, the merge step) reads it the +same way, so the PR that corrects the list can be reviewed and land. +`gstack-ship-policy validate` still reports the list as invalid. The PR's own +list still doesn't count until it lands (GST-3399). Any other +error in a base policy stops the plan (`POLICY_INVALID`), and a base git cannot +read stops it (`POLICY_SOURCE_UNAVAILABLE`); neither turns exclusion off quietly. **Land the setting first.** Because the branch's copy doesn't count, a PR that adds bulk data lands its `review_exclude_paths` entry, and any secrets `allowlist` entries it needs diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index a924cb088..b115dea9d 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -3842,6 +3842,14 @@ a typo never silently means "default". **Fix.** `gstack-ship-policy validate` lists every problem; `gstack-ship-policy init --explain` prints each key, its meaning and default. +When the invalid file is the base branch's and its only errors are in +`review_exclude_paths` or `review_content_patterns` (for example `more than 64 +patterns`), /ship does not stop: `gstack-review-plan` prints `REVIEW_EXCLUDE: +fallback (WARNING: …)`, reviews every file and applies the base's other keys, +so open a PR that corrects the list and ship it as usual +([review_exclude_paths](ship-policy.md#review-exclude-paths)). Any other error +on the base stops the plan and the merge step until a PR fixes it. + ### `POLICY_CONTAINMENT` diff --git a/lib/headless-artifacts.ts b/lib/headless-artifacts.ts index 737bce565..f3e0f4ead 100644 --- a/lib/headless-artifacts.ts +++ b/lib/headless-artifacts.ts @@ -144,6 +144,8 @@ export interface ShipReceipt { flaky_exception?: Array<{ lane: string; runs: string[]; cases: string[]; grant: string; by: string }>; /** The base policy's review_exclude_paths at the reviewed head (lib/review-exclude.ts); absent when the base declares none. Carry and the queue compare `digest`. */ review_exclude?: { source: string; patterns: string[]; applied: string[]; excluded: number; excluded_bytes: number; kept: number; gate_tagged: string[]; patterns_sha256: string; list_sha256: string; digest: string }; + /** The base policy failed only on its exclusion keys, so they were set aside and every file was reviewed (GST-3399): the policy's source and its errors. */ + review_exclude_fallback?: { source: string; errors: string[] }; /** Routine stops the run recorded and went on past instead of waiting for a Captain (plan K1; GSTA-258 L5 writes them): one record per stop. */ no_stop?: Array<{ class: NoStopClass; reason: string; evidence: string }>; } @@ -282,6 +284,7 @@ export const ARTIFACT_SCHEMAS = { review_depth: { type: 'object', required: ['depth', 'class', 'runtime_lines', 'rules', 'base', 'gate_scan'], properties: { depth: { enum: ['platform', 'light', 'standard', 'full'] }, mode: { enum: ['lean', 'panel', 'platform'] }, platform_review: { type: 'object', required: ['id', 'head', 'reviewer'], properties: { id: str, head: str, reviewer: str } }, class: { enum: ['docs', 'tests', 'code', 'gate'] }, runtime_lines: { type: 'integer', minimum: 0 }, rules: str, base: str, registry: nullableStr, gate_scan: { type: 'object', required: ['tagged', 'head'], properties: { tagged: { type: ['integer', 'null'], minimum: 0 }, head: str } }, reasons: strList, risk: { type: 'array', items: { enum: ['money', 'auth', 'secret', 'security', 'data', 'eval', 'policy'] } }, declared: { type: 'array', items: { enum: ['money', 'auth', 'secret', 'security', 'data', 'eval', 'policy'] } }, detected: { type: 'array', items: { enum: ['money', 'auth', 'secret', 'security', 'data', 'eval', 'policy'] } } } }, review_targeted: { type: 'object', required: ['classes', 'rules', 'brief_sha', 'product_patch_id', 'status', 'findings', 'raised_by'], properties: { classes: { type: 'array', items: { enum: ['money', 'gate', 'auth', 'secret'] } }, rules: str, brief_sha: str, product_patch_id: str, status: { enum: ['done', 'failed', 'not-run'] }, findings: { type: 'integer', minimum: 0 }, raised_by: str } }, review_exclude: { type: 'object', required: ['source', 'patterns', 'applied', 'excluded', 'excluded_bytes', 'kept', 'gate_tagged', 'patterns_sha256', 'list_sha256', 'digest'], properties: { source: str, patterns: strList, applied: strList, excluded: { type: 'integer', minimum: 0 }, excluded_bytes: { type: 'integer', minimum: 0 }, kept: { type: 'integer', minimum: 0 }, gate_tagged: strList, patterns_sha256: str, list_sha256: str, digest: str } }, + review_exclude_fallback: { type: 'object', required: ['source', 'errors'], properties: { source: str, errors: strList } }, review_loop_exception: { type: 'object', required: ['accepted_by', 'date', 'via', 'reason'], properties: { accepted_by: str, date: str, via: str, reason: str, fix_check: { type: 'object', required: ['head', 'findings'], properties: { head: str, findings: { type: 'integer', minimum: 0 }, files: strList } }, second_pass: { type: 'object', required: ['head', 'deferred'], properties: { head: str, deferred: strList } } } }, review_round_grants: { type: 'array', items: { type: 'object', required: ['kind', 'head', 'pr', 'by', 'reason', 'at', 'approval'], properties: { kind: { enum: ['extra-round', 'fix-check'] }, head: str, pr: { type: 'integer', minimum: 1 }, by: str, reason: str, at: str, approval: str, stop_run: str, findings: { type: 'array', items: str } } } }, ruled_notes: { type: 'array', items: { type: 'object', required: ['finding', 'head', 'by', 'reason', 'at', 'approval'], properties: { finding: str, head: str, by: str, reason: str, at: str, approval: str, relayed: str, not_security: { const: true } } } }, diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts index ae36bb50e..caaaa6461 100644 --- a/lib/result-codes-release.ts +++ b/lib/result-codes-release.ts @@ -613,8 +613,8 @@ export const RELEASE_RESULT_CODES = { }, REVIEW_PLAN_STOPPED: { anchor: 'review-plan-stopped', - summary: 'gstack-review-plan did not finish inside the pass (reason=timeout after timeout_ms, reason=signal when something killed it, reason=spawn when it could not start), so the review stopped before any reader ran: gstack-review-dispatch pass writes no manifest, and a plan run by itself prints no plan', - fix: 'rerun once unchanged; if it stops again, report this line and the repository\'s file count (git ls-files | wc -l) to your Captain; reason=signal: check the machine\'s free memory first', + summary: 'gstack-review-plan did not finish inside its limit (reason=timeout after timeout_ms, reason=signal when something killed it, reason=spawn when it could not start), so the review stopped before any reader ran: gstack-review-dispatch pass writes no manifest, render writes no brief, and a plan run by itself prints no plan', + fix: 'rerun once unchanged; if reason=timeout again on a large repository (git ls-files | wc -l in the hundreds of thousands), set GSTACK_REVIEW_PLAN_TIMEOUT_MS (milliseconds, default 180000) to about twice the plan\'s time and rerun; otherwise report this line and the file count to your Captain; reason=signal: check the machine\'s free memory first', }, REVIEW_EXCLUDE_REFERENCE: { anchor: 'review-exclude-reference', diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index d46e38997..2a9981a33 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -71,6 +71,7 @@ export interface ActiveExclusion { export type Exclusion = | { state: 'none' } | { state: 'head-only'; patterns: string[]; source: string } + | { state: 'fallback'; source: string; errors: string[] } | { state: 'refused'; code: 'POLICY_SOURCE_UNAVAILABLE' | 'POLICY_INVALID' | 'REVIEW_DIFF_UNREADABLE' | 'REVIEW_EXCLUDE_KEEP_TOO_LARGE'; lines: string[] } | ActiveExclusion; @@ -425,7 +426,8 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet /** * The base policy's exclusion for one range. `none` when neither side declares a pattern (callers then print and change - * nothing); `head-only` when only the head does (a notice, never applied); `refused` when the base policy cannot be read or + * nothing); `head-only` when only the head does (a notice, never applied); `fallback` when the base policy fails only on its + * exclusion keys, which finish (lib/ship-policy.ts) then sets aside so every file is reviewed; `refused` when the base policy cannot be read or * does not validate, or git cannot list the matches; `active` otherwise. Named-by-code keeps a file only when a kept code * file names its full repository path (never its basename: receipt trees reuse result.json thousands of times); a git grep * failure keeps every candidate (consumer-scan-unavailable), and so does an unknown gate scan (gate-scan-unavailable) or a @@ -439,6 +441,7 @@ export function reviewExclude(i: ExcludeInput): Exclusion { if (load.errors.length) { return { state: 'refused', code: 'POLICY_INVALID', lines: load.errors.map(e => `${i.context}: the base policy ${source}:${SHIP_POLICY_PATH} does not validate, so its review_exclude_paths cannot be read (${e.path || SHIP_POLICY_PATH}: ${e.message}); fix: run ` + '`' + `gstack-ship-policy validate --policy-from base --base ${base}` + '`' + ` and fix the file on ${base} with its own PR; nothing was planned (${e.code})`) }; } + if (load.setAside) return { state: 'fallback', source, errors: load.setAside.map(e => `${e.path}: ${e.message}`) }; const patterns = load.policy.review_exclude_paths; if (!patterns.length) { const head = headPatterns(i); return head.length ? { state: 'head-only', patterns: head, source } : { state: 'none' }; } const sel = select(i, patterns); @@ -519,10 +522,16 @@ function excludedBytes(i: ExcludeInput, excluded: readonly string[], files: Read return r.out.split('\n').reduce((n, l) => n + (Number(l) || 0), 0); } +/** The loud line for a base policy whose exclusion keys were set aside: what failed, that every file is reviewed, and the fix. */ +export function fallbackLine(x: Extract, base: string): string { + return `REVIEW_EXCLUDE: fallback (WARNING: the base policy ${x.source} does not validate: ${x.errors.join('; ')}; its review_exclude_paths and review_content_patterns are set aside and every file is reviewed, as with no exclusion; every other key applies as committed; fix: correct the list on ${base} with its own PR, which this plan reviews in full; docs/ship-policy.md#review-exclude-paths)`; +} + /** The plan's lines for an exclusion: none prints nothing, so a repository without the key plans byte for byte as before. */ export function excludeLines(x: Exclusion, base: string): string[] { if (x.state === 'none' || x.state === 'refused') return []; if (x.state === 'head-only') return [`REVIEW_EXCLUDE: none (head sets review_exclude_paths; it applies after it lands on ${base}) patterns=${x.patterns.length} source=${x.source}`]; + if (x.state === 'fallback') return [fallbackLine(x, base)]; const r = x.record; const out = [`REVIEW_EXCLUDE: patterns=${r.applied.length}/${r.patterns.length} excluded=${r.excluded} bytes=${r.excluded_bytes} kept=${r.kept} content=${Object.entries(x.content).filter(([, n]) => n).map(([k, n]) => `${k}:${n}`).join(',') || 'none'} source=${r.source} digest=${r.digest}${r.unmatched.length ? ` unmatched=${r.unmatched.join(',')}` : ''}`]; for (const k of x.kept.slice(0, 20)) out.push(`REVIEW_EXCLUDE_KEPT: ${k.reason} ${k.path}`); @@ -672,5 +681,6 @@ export function ceilingContext(root: string, base: string, known?: PlanExclude): const floor = read?.policy.min_gstack_version ?? null; if (!x) return { state: 'none', base: b, source, floor }; if (x.state === 'head-only') return { state: 'head-only', base: b, source, floor, headPatterns: x.patterns ?? [] }; + if (x.state !== 'active') return { state: 'none', base: b, source, floor }; return { state: 'active', base: b, source, floor, record: { patterns: x.patterns ?? [], excluded: x.excluded ?? 0 } }; } diff --git a/lib/ship-policy.ts b/lib/ship-policy.ts index ba70f9049..bafd4bf08 100644 --- a/lib/ship-policy.ts +++ b/lib/ship-policy.ts @@ -653,6 +653,8 @@ export interface LoadedPolicy { errors: PolicyError[]; /** Unknown keys under land and docs_only (policyWarnings): ignored, never errors. */ warnings: PolicyWarning[]; + /** A base policy's errors when all are in review_exclude_paths or review_content_patterns: both keys are dropped, which only widens review, and the rest applies (GST-3399). */ + setAside?: PolicyError[]; values: Record; } export type PolicyLoad = LoadedPolicy | { unavailable: true; base: string; detail: string }; @@ -679,10 +681,11 @@ export function finish(rawText: string | null, source: PolicySource): LoadedPoli let raw: unknown; try { raw = JSON.parse(rawText); } catch (e: any) { return { policy: JSON.parse(JSON.stringify(DEFAULT_POLICY)), present: true, source, errors: [{ code: 'POLICY_INVALID', path: SHIP_POLICY_PATH, message: `not valid JSON: ${e.message}` }], warnings: [], values: {} }; } - const errors = validatePolicy(raw); - const merged = mergePolicy(errors.length ? null : (raw as Record), source.label); + const all = validatePolicy(raw), exclusion = /^review_(exclude_paths|content_patterns)(\[|$)/; + const rest = source.kind === 'base' && all.length && all.every(e => exclusion.test(e.path)) ? Object.fromEntries(Object.entries(raw as Record).filter(([k]) => !exclusion.test(k))) : null; + const errors = rest && !validatePolicy(rest).length ? [] : all, read = errors.length ? null : (rest ?? raw) as Record, merged = mergePolicy(read, source.label); const warnings = raw && typeof raw === 'object' && !Array.isArray(raw) ? policyWarnings(raw as Record) : []; - return { policy: merged.policy, present: true, source, errors, warnings, values: merged.values }; + return { policy: merged.policy, present: true, source, errors, warnings, values: merged.values, ...(rest && !errors.length ? { setAside: all } : {}) }; } /** diff --git a/lib/ship-receipt-depth.ts b/lib/ship-receipt-depth.ts index 1caa468f3..66128dca0 100644 --- a/lib/ship-receipt-depth.ts +++ b/lib/ship-receipt-depth.ts @@ -66,6 +66,11 @@ function scopeOfRange(root: string, binDir: string, base: string, head: string, export type ReceiptExclude = NonNullable; +/** The receipt's record of a base policy whose exclusion keys were set aside (GST-3399), or undefined when none were. */ +export function receiptExcludeFallback(x: Exclusion): ShipReceipt['review_exclude_fallback'] { + return x.state === 'fallback' ? { source: x.source, errors: x.errors } : undefined; +} + /** The receipt's copy of an active exclusion: counts and hashes, plus the gate-tagged kept paths the queue cannot recompute. */ export function receiptExclude(x: Exclusion): ReceiptExclude | undefined { if (x.state !== 'active') return undefined; diff --git a/lib/ship-receipt.ts b/lib/ship-receipt.ts index 2b6731ba2..499845df1 100644 --- a/lib/ship-receipt.ts +++ b/lib/ship-receipt.ts @@ -25,7 +25,7 @@ const KEY_ORDER: Array = [ 'schema_version', 'pr', 'head', 'version', 'base', 'gated_tree', 'predecessor', 'tree', 'gate_reuse', 'gate', 'ci', 'ci_carried', 'spend_usd', 'calls', 'session_kind', 'artifacts_consumed', 'run', 'thread', 'policy', 'queue_mode', 'preregistration', 'history', 'head_tree', 'product_patch_id', 'gstack_version', 'review_depth', 'pregate', 'requires_remote', 'issues', 'approval', 'docs', 'review_loop', - 'review_loop_exception', 'review_round_grants', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'carry', 'base_red', 'flaky_exception', 'no_stop', + 'review_loop_exception', 'review_round_grants', 'ruled_notes', 'gate_dispositions', 'mechanical', 'review_targeted', 'design', 'review_exclude', 'review_exclude_fallback', 'carry', 'base_red', 'flaky_exception', 'no_stop', ]; /** Keys in the fixed order so identifiers lead; undefined values are dropped. */ diff --git a/test/review-dispatch-plan-timeout.test.ts b/test/review-dispatch-plan-timeout.test.ts index c5bb51301..f1fd59b2a 100644 --- a/test/review-dispatch-plan-timeout.test.ts +++ b/test/review-dispatch-plan-timeout.test.ts @@ -36,7 +36,7 @@ describe('pass names the plan step and its limit when the plan does not finish ( const out = path.join(root, 'run'); const r = spawnSync(DISPATCH, ['pass', '--base', 'main', '--out', out, '--pass', 'timeout-p1'], { cwd: work, env: { ...env, GSTACK_REVIEW_PLAN_TIMEOUT_MS: '1' }, encoding: 'utf8', timeout: 120_000 }); expect(r.status, r.stdout + r.stderr).toBe(1); - expect(r.stderr).toContain('gstack-review-dispatch pass: gstack-review-plan did not finish inside the pass'); + expect(r.stderr).toContain('gstack-review-dispatch pass: gstack-review-plan did not finish inside its limit'); expect(r.stderr).toContain('step="gstack-review-plan --base main" reason=timeout timeout_ms=1 signal=SIGTERM'); expect(r.stderr.trimEnd().endsWith('(REVIEW_PLAN_STOPPED)')).toBe(true); expect(r.stdout).not.toContain('MANIFEST:'); @@ -89,7 +89,7 @@ describe('render reads the plan limit from GSTACK_REVIEW_PLAN_TIMEOUT_MS too (GS }; const stopped = render('o-stopped', '1'); expect(stopped.status, stopped.err).toBe(EXIT.fail); - expect(stopped.err).toContain('gstack-review-dispatch render: gstack-review-plan did not finish inside the pass'); + expect(stopped.err).toContain('gstack-review-dispatch render: gstack-review-plan did not finish inside its limit'); expect(stopped.err).toContain('step="gstack-review-plan --base main --json" reason=timeout timeout_ms=1 signal=SIGTERM'); expect(stopped.err).toContain('(REVIEW_PLAN_STOPPED)'); expect(fs.existsSync(stopped.diff)).toBe(false); diff --git a/test/review-exclude-base-fallback.test.ts b/test/review-exclude-base-fallback.test.ts new file mode 100644 index 000000000..8bc44602b --- /dev/null +++ b/test/review-exclude-base-fallback.test.ts @@ -0,0 +1,127 @@ +/** + * A base policy that fails only on its review_exclude_paths or review_content_patterns sets those keys aside instead of + * stopping every /ship (GST-3399): harness-evals main went to 65 patterns, past the schema's 64, and every plan there refused + * POLICY_INVALID, the PR that shortens the list included. The keys' removal only widens review, every other base key still + * applies, the head's copy still never counts, and any other error still refuses. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { EXIT } from '../lib/headless-artifacts'; +import { receiptExcludeFallback } from '../lib/ship-receipt-depth'; +import { loadBasePolicy } from '../lib/ship-queue'; +import { READERS_KEY_VERSION } from '../lib/ship-policy-keys'; +import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +const patterns = (n: number) => Array.from({ length: n }, (_, i) => `data/p${i}/**`); +const policyText = (p: Record) => JSON.stringify({ min_gstack_version: READERS_KEY_VERSION, readers: { forbid_paths: ['private/**'] }, ...p }) + '\n'; +/** A repository whose main holds `policy`, and a branch that changes a data file, a code file and `head` (extra files, the policy included). */ +function repoWith(policy: Record, head: Record = {}) { + const repo = makeFixtureRepo({ prefix: 'gstack-xfb-', baseFiles: { '.gstack/ship-policy.json': policyText(policy), 'data/p0/keep.json': '{}\n' } }); + repos.push(repo); + commit(repo, { 'data/p0/r.json': '{"n": 1}\n', 'lib/a.ts': 'export const a = 1;\n', ...head }); + return repo; +} +const plan = (repo: FixtureRepo) => runBin(repo, 'gstack-review-plan', ['--base', 'main']); +const planJson = (repo: FixtureRepo) => { const r = runBin(repo, 'gstack-review-plan', ['--base', 'main', '--json']); expect(r.status, r.err).toBe(EXIT.ok); return JSON.parse(r.out); }; + +describe('an invalid exclusion list on the base is set aside, never loosened (GST-3399)', () => { + // Value: protects=a base whose only error is review_exclude_paths' length plans with every file reviewed and its other keys + // applied, with a loud line on stdout and stderr and the record in --json; fails_when=the plan refuses POLICY_INVALID (the + // harness-evals deadlock), applies some of the 65 patterns, or drops the base's readers.forbid_paths with the bad key; + // why_new=GST-3399; seam=gstack-review-plan on a real repository; no_claim=what reviewers do with the files + test('65 patterns on the base: the plan reviews every file, keeps forbid_paths and says why', () => { + const repo = repoWith({ review_exclude_paths: patterns(65) }); + const r = plan(repo); + expect(r.status, r.err).toBe(EXIT.ok); + expect(r.out).toContain('REVIEW_EXCLUDE: fallback (WARNING: the base policy origin/main@'); + expect(r.out).toContain('review_exclude_paths: more than 64 patterns'); + expect(r.out).toContain('every file is reviewed'); + expect(r.err).toContain('gstack-review-plan: REVIEW_EXCLUDE: fallback (WARNING'); + expect(r.out).toMatch(/READERS: forbid_fetch=0 forbid_paths=1 /); + const j = planJson(repo); + expect(j.review_exclude.state).toBe('fallback'); + expect(j.review_exclude.errors).toEqual(['review_exclude_paths: more than 64 patterns']); + expect(j.paths).toContain('data/p0/r.json'); + expect(j.readers.forbid_paths).toEqual(['private/**']); + expect(receiptExcludeFallback(j.review_exclude)).toEqual({ source: j.review_exclude.source, errors: ['review_exclude_paths: more than 64 patterns'] }); + }, 120_000); + + // Value: protects=the PR that fixes the list is planned under the base's (set-aside) list, not its own valid one; fails_when= + // the head's 61 patterns are applied before they land; seam=gstack-review-plan --json; no_claim=the land step + test('the PR that shortens the list is still planned with nothing excluded', () => { + const repo = repoWith({ review_exclude_paths: patterns(65) }, { '.gstack/ship-policy.json': policyText({ review_exclude_paths: patterns(61) }) }); + const j = planJson(repo); + expect(j.review_exclude.state).toBe('fallback'); + expect(j.paths).toContain('data/p0/r.json'); + }, 120_000); + + // Value: protects=a valid base list plans exactly as before (negative control); fails_when=a valid list falls back or stops + // excluding; seam=gstack-review-plan; no_claim=the excluded file count beyond this fixture + test('a valid base list still excludes its files', () => { + const repo = repoWith({ review_exclude_paths: patterns(64) }); + const r = plan(repo); + expect(r.status, r.err).toBe(EXIT.ok); + expect(r.out).not.toContain('fallback'); + expect(r.out).toMatch(/REVIEW_EXCLUDE: patterns=1\/64 excluded=1 /); + expect(planJson(repo).review_exclude.state).toBe('active'); + }, 120_000); + + // Value: protects=a branch that adds a list still gets the head-only notice and a normal review (negative control); fails_when= + // the head's policy is read; seam=gstack-review-plan; no_claim=other head-only keys + test('a list only the head declares is still ignored', () => { + const repo = repoWith({}, { '.gstack/ship-policy.json': policyText({ review_exclude_paths: patterns(3) }) }); + const r = plan(repo); + expect(r.status, r.err).toBe(EXIT.ok); + expect(r.out).toContain('REVIEW_EXCLUDE: none (head sets review_exclude_paths; it applies after it lands on main) patterns=3'); + expect(r.out).not.toContain('fallback'); + }, 120_000); + + // Value: protects=only exclusion errors are set aside: a base with any other invalid key still refuses before any reader; + // fails_when=the fallback swallows an error in a key whose default would loosen review or readers; seam=gstack-review-plan + // and gstack-ship-queue's loadBasePolicy; no_claim=the wording of the refusal + test('a base with another invalid key still refuses, in the plan and in the queue', () => { + const repo = repoWith({ review_exclude_paths: patterns(65), review: { panel: 'some' } }); + const r = plan(repo); + expect(r.status).toBe(EXIT.refused); + expect(r.err).toContain('POLICY_INVALID'); + expect(r.out).not.toContain('REVIEW_EXCLUDE: fallback'); + const q = loadBasePolicy({ repoRoot: repo.work, base: 'main', gh: () => ({ ok: false, out: '' }) }); + expect('code' in q && q.code).toBe('POLICY_INVALID'); + }, 120_000); + + // Value: protects=the merge step reads a base that fails only on its exclusion list, with its other keys, so the PR that fixes + // the list can land; fails_when=gstack-ship-queue refuses POLICY_INVALID on it; seam=loadBasePolicy; no_claim=land's checks + test('the queue reads such a base with its other keys', () => { + const repo = repoWith({ review_exclude_paths: patterns(65) }); + const q = loadBasePolicy({ repoRoot: repo.work, base: 'main', gh: () => ({ ok: false, out: '' }) }); + expect('code' in q ? q : null).toBeNull(); + expect('policy' in q && q.policy.review_exclude_paths).toEqual([]); + expect('policy' in q && q.policy.readers?.forbid_paths).toEqual(['private/**']); + }, 120_000); + + // Value: protects=the setting aside is for reading the base, never for checking it: validate still names the bad list so the + // owner fixes it; fails_when=gstack-ship-policy validate --policy-from base reports such a base valid; seam=the validate CLI; + // no_claim=validate's other output + test('validate still reports the base list as invalid', () => { + const repo = repoWith({ review_exclude_paths: patterns(65) }); + const r = runBin(repo, 'gstack-ship-policy', ['validate', '--policy-from', 'base', '--base', 'main']); + expect(r.status).toBe(EXIT.fail); + expect(r.out).toContain('POLICY_INVALID: 1 error(s)'); + expect(r.err).toContain('more than 64 patterns at review_exclude_paths'); + }, 120_000); + + // Value: protects=show-effective, which /ship's POLICY line and /land-and-deploy's stamp check read, reports such a base valid + // with its other keys and the loud fallback line; fails_when=it exits 1 with valid:false (land-and-deploy then reads no + // queue_mode) or drops the warning; seam=the show-effective CLI; no_claim=renderEffective's other lines + test('show-effective reads the base with its other keys and warns', () => { + const repo = repoWith({ review_exclude_paths: patterns(65), queue_mode: 'stamp-at-merge' }); + const r = runBin(repo, 'gstack-ship-policy', ['show-effective', '--base', 'main', '--json']); + expect(r.status, r.err).toBe(EXIT.ok); + const j = JSON.parse(r.out); + expect({ valid: j.valid, queue_mode: j.policy.queue_mode, excluded: j.policy.review_exclude_paths }).toEqual({ valid: true, queue_mode: 'stamp-at-merge', excluded: [] }); + expect(r.err).toContain('gstack-ship-policy: REVIEW_EXCLUDE: fallback (WARNING'); + expect(r.err).not.toContain('POLICY_INVALID'); + }, 120_000); +}); diff --git a/test/review-exclude.test.ts b/test/review-exclude.test.ts index 67bb9434a..703ec4661 100644 --- a/test/review-exclude.test.ts +++ b/test/review-exclude.test.ts @@ -215,6 +215,7 @@ describe('the base policy read', () => { expect(r.err).toContain('POLICY_SOURCE_UNAVAILABLE'); const bad = census([':(icase)receipts/**']); + onBase(bad, { '.gstack/ship-policy.json': JSON.stringify({ review_exclude_paths: [':(icase)receipts/**'], review: { panel: 'some' }, min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n' }); const b = plan(bad); expect(b.status).toBe(EXIT.refused); expect(b.err).toContain('review_exclude_paths[0]'); @@ -472,7 +473,7 @@ describe('the receipt binds the selection the reviewers read', () => { test('an unreadable base policy still refuses a receipt with no digest or an older one', () => { for (const basePolicy of [null, ['receipts/**']]) { const { repo, body } = shipped(CODE, basePolicy); - policyOnBaseOnly(repo, '{ "review_exclude_paths": "receipts/**" }\n'); + policyOnBaseOnly(repo, '{ "review_exclude_paths": "receipts/**", "review": { "panel": "some" } }\n'); const b = bind(repo, body); expect({ basePolicy, ok: b.ok, code: b.ok ? '' : b.code }).toEqual({ basePolicy, ok: false, code: 'POLICY_INVALID' }); } @@ -541,7 +542,7 @@ describe('the receipt binds the selection the reviewers read', () => { }, 240_000); test('an unreadable or malformed base policy still refuses carry', () => { - for (const text of [JSON.stringify({ review_exclude_paths: 'receipts/**', min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n', '{ not json\n']) { + for (const text of [JSON.stringify({ review_exclude_paths: 'receipts/**', review: { panel: 'some' }, min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n', '{ not json\n']) { const { repo, body } = shipped(CODE, null); onBase(repo, { '.gstack/ship-policy.json': text }); const refused = carry(repo, body); @@ -600,6 +601,23 @@ describe('the receipt binds the selection the reviewers read', () => { expect(receiptIn(body).review_exclude!.digest).toBe(now); }, 240_000); + // Value: protects=a base whose list no longer validates writes the fallback record and never carries a receipt whose review + // left a PR file out; fails_when=write drops review_exclude_fallback or carry accepts the narrower review (GST-3399); + // seam=gstack-ship-receipt write and carry; no_claim=the queue's reading of the field + test('a base list that is set aside writes the fallback record and refuses carry of the narrower review', () => { + const { repo, body } = reviewed(); + policyOnBaseOnly(repo, policyText(Array.from({ length: 65 }, (_, i) => `data/p${i}/**`))); + const w = writeWith(repo, []); + expect({ status: w.status, err: w.status === EXIT.ok ? '' : w.err }).toEqual({ status: EXIT.ok, err: '' }); + const written = receiptIn(path.join(repo.root, 'body-w.md')); + expect(written.review_exclude).toBeUndefined(); + expect(written.review_exclude_fallback!.errors).toEqual(['review_exclude_paths: more than 64 patterns']); + repo.git('merge', '-q', '--no-edit', 'origin/main'); + const refused = carry(repo, body); + expect(refused.status).toBe(EXIT.refused); + expect(refused.err).toContain('review_exclude changed: recorded='); + }, 240_000); + test('a policy edit that changes the selection over the PR files still refuses write, ready and carry', () => { const changes: Array<{ name: string; after: string[] }> = [ { name: 'a new pattern keeps a PR file', after: ['receipts/**', 'lib/**'] }, @@ -630,7 +648,7 @@ describe('the receipt binds the selection the reviewers read', () => { expect({ extra, status: w.status }).toEqual({ extra, status: EXIT.fail }); expect(w.err).toContain('field=review_exclude expected='); } - policyOnBaseOnly(repo, '{ "review_exclude_paths": "receipts/**" }\n'); + policyOnBaseOnly(repo, '{ "review_exclude_paths": "receipts/**", "review": { "panel": "some" } }\n'); const unreadable = writeWith(repo, ['--review-exclude', digest]); expect(unreadable.status).toBe(EXIT.refused); expect(unreadable.err).toContain('so its review_exclude_paths cannot be read');