fix(plan-reality): a receipt per measured number, the rule text for a rule claim, dot-path receipts

Each clause stating a measured quantity (a unit, or a number after measured/costs/
takes/took) needs its own receipt; misses print unreceipted_numbers=<n> and one
NUMBER_UNRECEIPTED: <clause> line each. A line claiming a decision rule must quote
it or link its file:line (unquoted=<n>). Either miss maps to the existing verdict
(incomplete unattended, repair otherwise). RECEIPT_RE accepts dot paths and needs
a hex letter or a commit/backtick context for a sha. New pure checkPlanReality(planText)
runs the same checks over plan prose for gstack-autoplan submit (field wave item 12).
The unreceipted= text token is now pinned as well as the JSON.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-10-13 00:47:24 +00:00
1 parent b743b7280c
commit 2f65e8a810
3 files changed
+172 -8

No files matched your search

+6 -2
View File
@@ -20,7 +20,9 @@ const HELP = `gstack-plan-reality — reality rows for plan reviews
Row line: \`${REALITY_LINE_SHAPE}\` (receipt: path:line, path:line-line or a commit sha).
Scopes: ${REALITY_SCOPES.filter(s => s !== 'always').join(', ')}. Session kind unattended → verdict=incomplete; else verdict=repair.
Prints \`PLAN_REALITY: phase=<p> rows=<n>/<m> missing=<ids|none> [unverified=<n>] verdict=complete|incomplete|repair\`.
Prints \`PLAN_REALITY: phase=<p> rows=<n>/<m> missing=<ids|none> [unreceipted=<ids>] [unreceipted_numbers=<n>] [unquoted=<n>] [unverified=<n>] verdict=complete|incomplete|repair\`,
then one \`NUMBER_UNRECEIPTED: <clause>\` per measured number (unit or measured/costs/took) without its own receipt.
A line claiming a decision rule must quote it (\`"..."\`, a fenced or > block after it) or link it (file:line).
${exitTableHelp()}`;
function flag(args: string[], name: string): string | undefined {
@@ -55,10 +57,12 @@ function main(argv: string[]): number {
const sessionKind = flag(rest, '--session-kind') ?? process.env.GSTACK_SESSION_KIND;
const result = checkRealityRows(text, { phase, scopes, sessionKind });
if (json) process.stdout.write(JSON.stringify(result) + '\n');
else process.stdout.write(result.line + '\n');
else process.stdout.write([result.line, ...result.numberLines].join('\n') + '\n');
for (const id of result.unknownRows) process.stderr.write(`gstack-plan-reality: ${file}: REALITY row ${JSON.stringify(id)} is not a known row; it was ignored\n`);
if (result.missing.length) process.stderr.write(resultLine('gstack-plan-reality check', 'REALITY_ROW_MISSING', `phase ${phase}: ${result.missing.join(', ')}`) + '\n');
if (result.unreceipted.length) process.stderr.write(resultLine('gstack-plan-reality check', 'REALITY_RECEIPT_MISSING', `phase ${phase}: ${result.unreceipted.join(', ')}`) + '\n');
if (result.unreceipted_numbers.length) process.stderr.write(resultLine('gstack-plan-reality check', 'REALITY_RECEIPT_MISSING', `phase ${phase}: ${result.unreceipted_numbers.length} measured number(s) share or lack a receipt; give each clause its own file:line, script path or command`) + '\n');
for (const claim of result.unquoted) process.stderr.write(resultLine('gstack-plan-reality check', 'REALITY_RECEIPT_MISSING', `phase ${phase}: a decision rule is claimed without its text; quote it or link its file:line: ${claim}`) + '\n');
return result.verdict === 'complete' ? EXIT.ok : EXIT.fail;
}
return usage(`unknown command ${cmd}`);
+87 -5
View File
@@ -156,8 +156,8 @@ export function parseScopes(csv: string | undefined): { scopes: RealityScope[];
return { scopes, unknown };
}
/** `path:line`, `path:line-line` (the path has a letter and no spaces) or a 7–40 hex sha. */
export const RECEIPT_RE = /(?:(?<![\w./-])[A-Za-z~$][\w./~$@-]*:\d+(?:-\d+)?)|(?<![0-9a-f])[0-9a-f]{7,40}(?![0-9a-f])/;
/** `path:line` or `path:line-line` (the path has a letter, may start with a dot, no spaces), or a 7–40 hex sha with a hex letter, or digits-only after `commit ` or in backticks. */
export const RECEIPT_RE = /(?:(?<![\w./-])\.?[A-Za-z~$][\w./~$@-]*:\d+(?:-\d+)?)|(?<![0-9a-f])(?=[0-9]*[a-f])[0-9a-f]{7,40}(?![0-9a-f])|\bcommit [0-9]{7,40}\b|`[0-9]{7,40}`/;
export const REALITY_LINE_RE = /^\s*(?:[-*>|]\s*)?`?REALITY:\s+(?<id>[a-z][a-z0-9-]*)\s+(?<status>pass|finding|n\/a)\b(?<rest>.*)$/;
export interface RealityLine { id: string; status: RealityStatus; rest: string; receipt: string | null; line: number; metrics: Record<string, string> }
@@ -185,6 +185,12 @@ export interface RealityCheck {
missing: string[];
/** Required rows whose line carries no receipt. */
unreceipted: string[];
/** Clauses stating a measured number without a receipt of their own. */
unreceipted_numbers: string[];
/** Lines claiming a decision rule exists without quoting or linking its text. */
unquoted: string[];
/** One `NUMBER_UNRECEIPTED: <clause>` line per unreceipted number. */
numberLines: string[];
/** Lines naming a row id the table does not define. */
unknownRows: string[];
metrics: Record<string, string>;
@@ -192,6 +198,52 @@ export interface RealityCheck {
line: string;
}
/**
* A measured quantity: a number with a unit (s, ms, %, $, USD, tokens, ×, MB, GB) or a number shortly after
* measured/costs/takes/took. Receipts, versions and ids are removed before matching, so they never count.
*/
const MEASURED_RE = /\$\s?\d|\b\d[\d,]*(?:\.\d+)?\s?[kKM]?\s?(?:ms|s|%|USD|tokens?|MB|GB)(?![\w])|\b\d[\d,]*(?:\.\d+)?\s?[×x](?![\w])|\b(?:measured|costs?|takes|take|took)\b\W+(?:[A-Za-z]+\W+){0,3}?\$?\d/i;
const NOT_A_QUANTITY_RE = new RegExp(`${RECEIPT_RE.source}|\\bv?\\d+(?:\\.\\d+){2,}\\b|#\\d+|\\b[A-Za-z]+\\d+[a-z]?\\b`, 'g');
const EXEMPT_TAG_RE = /\[(?:estimated|re-measure before gate)\]/i;
const SCRIPT_RE = /(?:^|[\s(`"'])(?:\.?[\w-]+\/)*[\w.-]+\.(?:ts|js|mjs|cjs|sh|py|rb|go)\b|(?:^|[\s(`"'])(?:bin|scripts)\/[\w.-]+/;
const COMMAND_RE = /`[^`]*\s[^`]*`/;
const RULE_CLAIM_RE = /\b(?:decision rule|rules? (?:was |were )?written first|pre-?registered rule)\b/i;
const QUOTED_RULE_RE = /"[^"]{8,}"|\u201c[^\u201d]{8,}\u201d/;
const LINK_RE = /(?<![\w./-])\.?[A-Za-z~$][\w./~$@-]*:\d+/;
/** Split on `;`, `, ` and sentence ends, never inside brackets, parentheses or backticks. */
export function splitClauses(text: string): string[] {
const out: string[] = [];
let depth = 0, tick = false, start = 0;
for (let i = 0; i < text.length; i++) {
const c = text[i]!;
if (c === '`') tick = !tick;
else if (!tick && '([{'.includes(c)) depth++;
else if (!tick && ')]}'.includes(c)) depth = Math.max(0, depth - 1);
else if (!tick && depth === 0 && (c === ';' || ((c === ',' || c === '.') && /\s/.test(text[i + 1] ?? '')))) {
out.push(text.slice(start, c === '.' ? i + 1 : i)); start = i + 1;
}
}
out.push(text.slice(start));
return out.map(c => c.trim()).filter(Boolean);
}
/** Clauses of one line that state a measured number and carry no receipt of their own. */
export function unreceiptedNumbers(line: string): string[] {
return splitClauses(line).filter(c => MEASURED_RE.test(c.replace(NOT_A_QUANTITY_RE, ' '))
&& !RECEIPT_RE.test(c) && !SCRIPT_RE.test(c) && !COMMAND_RE.test(c) && !EXEMPT_TAG_RE.test(c));
}
/** A rule claim needs the rule: a quoted span, a file:line link on the line, or a fenced or quoted block right after it. */
function ruleUnquoted(lines: string[], i: number): boolean {
const line = lines[i]!;
if (!RULE_CLAIM_RE.test(line) || QUOTED_RULE_RE.test(line) || LINK_RE.test(line)) return false;
const after = lines.slice(i + 1).find(l => l.trim());
return !after || !/^\s*(?:```|~~~|>)/.test(after);
}
const verdictFor = (ok: boolean, sessionKind?: string): RealityVerdict => (ok ? 'complete' : sessionKind === 'unattended' ? 'incomplete' : 'repair');
export interface CheckOptions { phase: string; scopes?: readonly string[]; sessionKind?: string }
/** Deterministic: which required rows the review carries. The verdict word depends on the session kind only. */
@@ -214,14 +266,44 @@ export function checkRealityRows(reviewText: string, o: CheckOptions): RealityCh
const metric = rowById(id)!.metric;
if (metric && l.metrics[metric] !== undefined) metrics[metric] = l.metrics[metric]!;
}
const ok = missing.length === 0 && unreceipted.length === 0;
const verdict: RealityVerdict = ok ? 'complete' : o.sessionKind === 'unattended' ? 'incomplete' : 'repair';
const rows = lines.filter(l => rowById(l.id) && l.status !== 'n/a');
const numbers = rows.flatMap(l => unreceiptedNumbers(l.rest));
const rawLines = reviewText.split('\n');
const unquoted = rows.filter(l => ruleUnquoted(rawLines, l.line - 1)).map(l => rawLines[l.line - 1]!.trim());
const verdict = verdictFor(missing.length === 0 && unreceipted.length === 0 && numbers.length === 0 && unquoted.length === 0, o.sessionKind);
const parts = [`PLAN_REALITY: phase=${o.phase}`, `rows=${present.length}/${required.length}`,
`missing=${missing.length ? missing.join(',') : 'none'}`];
if (unreceipted.length) parts.push(`unreceipted=${unreceipted.join(',')}`);
if (numbers.length) parts.push(`unreceipted_numbers=${numbers.length}`);
if (unquoted.length) parts.push(`unquoted=${unquoted.length}`);
for (const [k, v] of Object.entries(metrics)) parts.push(`${k}=${v}`);
parts.push(`verdict=${verdict}`);
return { phase: o.phase, required, present, missing, unreceipted, unknownRows, metrics, verdict, line: parts.join(' ') };
return { phase: o.phase, required, present, missing, unreceipted, unreceipted_numbers: numbers, unquoted,
numberLines: numbers.map(c => `NUMBER_UNRECEIPTED: ${c}`), unknownRows, metrics, verdict, line: parts.join(' ') };
}
/** Bumped whenever checkPlanReality's rules change, so a cached verdict keyed on the plan hash is recomputed. */
export const PLAN_REALITY_CHECKER = 'plan-reality/2';
export interface PlanRealityCheck { checker: string; unreceipted_numbers: string[]; unquoted: string[]; numberLines: string[]; verdict: RealityVerdict; line: string }
/**
* The same number and rule checks over plan prose (the Implementation plan the caller passes), outside fenced blocks.
* Pure: reads nothing, writes nothing. `gstack-autoplan submit` records it per plan hash; it never refuses a submit.
*/
export function checkPlanReality(planText: string, o: { sessionKind?: string } = {}): PlanRealityCheck {
const lines = planText.split('\n');
const numbers: string[] = [], unquoted: string[] = [];
let fence: string | null = null;
lines.forEach((line, i) => {
const delimiter = /^\s{0,3}(`{3,}|~{3,})/.exec(line)?.[1];
if (delimiter && (!fence || delimiter.startsWith(fence))) { fence = fence ? null : delimiter; return; }
if (fence || /^\s*<!--/.test(line)) return;
numbers.push(...unreceiptedNumbers(line));
if (ruleUnquoted(lines, i)) unquoted.push(line.trim());
});
const verdict = verdictFor(numbers.length === 0 && unquoted.length === 0, o.sessionKind);
return { checker: PLAN_REALITY_CHECKER, unreceipted_numbers: numbers, unquoted, numberLines: numbers.map(c => `NUMBER_UNRECEIPTED: ${c}`), verdict,
line: `PLAN_REALITY: scope=plan unreceipted_numbers=${numbers.length} unquoted=${unquoted.length} verdict=${verdict}` };
}
/** The example line every template quotes; one grammar, stated once. */
+79 -1
View File
@@ -13,7 +13,8 @@ import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { EXIT } from '../lib/headless-artifacts';
import { REALITY_ROWS, REALITY_SCOPES, TIER1_ROW_IDS, checkRealityRows, parseRealityLines, parseScopes, renderIncidentTable, renderRows, requiredRows } from '../lib/plan-reality';
import { REALITY_ROWS, REALITY_SCOPES, TIER1_ROW_IDS, checkPlanReality, checkRealityRows, parseRealityLines, parseScopes, renderIncidentTable, renderRows, requiredRows } from '../lib/plan-reality';
import { extractHeading } from '../lib/autoplan-prompts';
import { RESULT_CODES } from '../lib/result-codes';
import { generatePlanRealityRows } from '../scripts/resolvers/plan-reality';
import type { TemplateContext } from '../scripts/resolvers/types';
@@ -175,6 +176,8 @@ describe('gstack-plan-reality bin', () => {
const parsed = JSON.parse(unreceipted.out);
expect(parsed.unreceipted).toEqual(['premise-table']);
expect(unreceipted.err).toContain('(REALITY_RECEIPT_MISSING)');
const unreceiptedText = run(['check', '--phase', 'ceo', '-'], `${partial}\n${FIXTURE.rows['premise-table']!.decoy}`);
expect(unreceiptedText.out).toMatch(/^PLAN_REALITY: phase=ceo .*\bunreceipted=premise-table\b.* verdict=repair$/m);
expect(run(['check', '--phase', 'ceo', path.join(tmp, 'absent.md')]).code).toBe(EXIT.fail);
fs.rmSync(tmp, { recursive: true, force: true });
});
@@ -233,3 +236,78 @@ describe('rendered templates carry the contract', () => {
}
});
});
describe('field wave item 12: a receipt per measured number, the rule text for a rule claim', () => {
const others = (id: string) => Object.entries(FIXTURE.rows).filter(([k]) => k !== id).map(([, r]) => r.positive).join('\n');
const FIVE = 'REALITY: numbers pass p50 120ms, p95 340ms, 13% faster, 28k tokens, cost $41 [measured: test/bench.ts:10]';
test('five measured numbers sharing one receipt leave four unreceipted, each printed with its clause', () => {
const r = checkRealityRows(`${others('numbers')}\n${FIVE}`, { phase: 'eng', sessionKind: 'unattended' });
expect(r.missing).toEqual([]);
expect(r.unreceipted).toEqual([]);
expect(r.unreceipted_numbers).toEqual(['p50 120ms', 'p95 340ms', '13% faster', '28k tokens']);
expect(r.numberLines).toEqual(['NUMBER_UNRECEIPTED: p50 120ms', 'NUMBER_UNRECEIPTED: p95 340ms', 'NUMBER_UNRECEIPTED: 13% faster', 'NUMBER_UNRECEIPTED: 28k tokens']);
expect(r.verdict).toBe('incomplete');
expect(r.line).toContain(' unreceipted_numbers=4 ');
expect(checkRealityRows(`${others('numbers')}\n${FIVE}`, { phase: 'eng' }).verdict).toBe('repair');
});
test('each clause with its own receipt (file:line, script path or a command in backticks) passes; unmeasured counts, versions and ids need none', () => {
const own = 'REALITY: numbers pass p95 340ms lib/x.ts:4, 13% faster `bun run bench --json`, 28k tokens scripts/count-tokens.ts, recall 0.82 vs 0.79 on gstack 1.91.95.0 per F2 and #3160 [estimated]';
const r = checkRealityRows(`${others('numbers')}\n${own}`, { phase: 'eng' });
expect(r.unreceipted_numbers).toEqual([]);
expect(r.verdict).toBe('complete');
});
test('a rule claim without the rule text is unquoted; the quoted rule or a file:line link to it passes', () => {
const bare = 'REALITY: binding-decisions pass the decision rule was written first 91bbd9e';
const r = checkRealityRows(`${others('binding-decisions')}\n${bare}`, { phase: 'eng', sessionKind: 'unattended' });
expect(r.unreceipted).toEqual([]);
expect(r.unquoted).toEqual([bare]);
expect(r.line).toContain(' unquoted=1 ');
expect(r.verdict).toBe('incomplete');
const quoted = 'REALITY: binding-decisions pass the decision rule was written first: "stop if recall drops below the base on any bucket" 91bbd9e';
expect(checkRealityRows(`${others('binding-decisions')}\n${quoted}`, { phase: 'eng' }).verdict).toBe('complete');
const linked = 'REALITY: binding-decisions pass the decision rule was written first, see docs/plan.md:4';
expect(checkRealityRows(`${others('binding-decisions')}\n${linked}`, { phase: 'eng' }).unquoted).toEqual([]);
});
test('receipts on dot paths count; a sha receipt needs a hex letter or a commit/backtick context', () => {
expect(parseRealityLines('REALITY: pr-count pass one PR .gstack/ship-policy.json:1')[0]!.receipt).toBe('.gstack/ship-policy.json:1');
expect(parseRealityLines('REALITY: pr-count pass ci lane .github/workflows/ci.yml:12-20')[0]!.receipt).toBe('.github/workflows/ci.yml:12-20');
expect(parseRealityLines('REALITY: numbers pass run took 20261012 cycles')[0]!.receipt).toBeNull();
expect(parseRealityLines('REALITY: already-done pass base clean at commit 1234567')[0]!.receipt).toBe('commit 1234567');
expect(parseRealityLines('REALITY: already-done pass base clean at `7654321` today')[0]!.receipt).toBe('`7654321`');
});
test('bin: NUMBER_UNRECEIPTED lines follow the PLAN_REALITY line and the verdict exits 1 with a fix', () => {
const r = run(['check', '--phase', 'eng', '-', '--session-kind', 'unattended'], `${others('numbers')}\n${FIVE}`);
expect(r.code).toBe(EXIT.fail);
expect(r.out.split('\n').filter(Boolean)).toEqual([
expect.stringMatching(/^PLAN_REALITY: phase=eng rows=7\/7 missing=none unreceipted_numbers=4 .*verdict=incomplete$/),
'NUMBER_UNRECEIPTED: p50 120ms', 'NUMBER_UNRECEIPTED: p95 340ms', 'NUMBER_UNRECEIPTED: 13% faster', 'NUMBER_UNRECEIPTED: 28k tokens',
]);
expect(r.err).toContain('(REALITY_RECEIPT_MISSING)');
expect(r.err).toContain('fix:');
});
test('checkPlanReality(planText): plan prose gets the same number and rule checks, pure and session-kind mapped', () => {
const plan = 'Cold install measured 32.5 s; the warm rerun takes 13 s (bin/gstack-capy-install:91).\n```\nlatency 900 ms in a fenced example\n```\nThe decision rule was written first.\nThe preregistered rule is below.\n> stop when recall drops below the base\n';
const r = checkPlanReality(plan, { sessionKind: 'unattended' });
expect(r.unreceipted_numbers).toEqual(['Cold install measured 32.5 s']);
expect(r.unquoted).toEqual(['The decision rule was written first.']);
expect(r.verdict).toBe('incomplete');
expect(r.line).toBe('PLAN_REALITY: scope=plan unreceipted_numbers=1 unquoted=1 verdict=incomplete');
expect(r.numberLines).toEqual(['NUMBER_UNRECEIPTED: Cold install measured 32.5 s']);
expect(checkPlanReality('Add a retry with a 30 s cap (lib/worker.ts:12).\n').line).toBe('PLAN_REALITY: scope=plan unreceipted_numbers=0 unquoted=0 verdict=complete');
expect(checkPlanReality(plan).verdict).toBe('repair');
});
test('false-positive bound: the field-wave plan itself raises only a small, pinned count', () => {
const text = fs.readFileSync(path.join(ROOT, 'docs', 'designs', 'GSTACK_FIELD_WAVE_2026_10_12.md'), 'utf8');
const r = checkPlanReality(extractHeading(text, 'Implementation plan')!);
expect(r.unquoted).toEqual([]);
expect(r.unreceipted_numbers.length).toBeGreaterThan(0);
expect(r.unreceipted_numbers.length).toBeLessThanOrEqual(6);
});
});