Write PR titles, commit messages and branch names in plain English (GST-1825) (#4146)

* Add a check that keeps tracker codes and internal jargon out of PR titles and branch names

gstack-plain-title checks the readable front of a title, branch name, PR opening or changelog entry against the repository's .gstack/plain-titles.json; one trailing issue code stays allowed. A Plain title workflow runs it on every new pull request, and /ship's push refuses a never-pushed branch whose name fails it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Move the PR body's machine-read lines into a closing Agent notes section

The ship receipt, its runs block and the Plan line now live in one collapsed section at the end of the body, and every reader looks there first while still accepting the old receipt-at-top layout. gstack-post refuses to post a title the plain-title check refuses, and land uses the checked PR title as main's commit title.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Teach /ship to write plain titles, PR openings, commit messages and changelog entries

The README now lists what gstack is for, so a PR opening can name the goal it serves.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Keep tests, size budgets and generated files in step with plain titles and Agent notes

Copy lists that install result-code modules now include the plain-title codes, the ship goldens and size ledger are refreshed, the new workflow is classified, and the pinned prose tests read the new title and body layout.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Record the test-profile list change as non-behavioral for the shared test harness

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Keep text people add below the PR notes, and fix three smaller review findings

The notes section now ends at its own closing tag, so a collapsible added after it survives the next post. The opening check splits the body the same way the notes reader does. Wave PR titles no longer name the area, which the plain-title check could refuse. The Capy line in the PR-body steps now puts Approvals in the notes.

Review-Finding: p1/specialist-batched#1 reader=testing
Review-Finding: p1/red-team#1 reader=red-team
Review-Finding: p1/red-team#2 reader=red-team
Review-Finding: p1/red-team#3 reader=red-team
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Mask credentials in refused-title lines and keep older PRs' plan lines readable

A refused title's printed match is masked by the secret scanner first. The Plan line reader falls back to the whole body when the Agent notes section has none, so a body written before this change keeps its plan when its first receipt lands. The notes section also ends at its own closing tag when its opener is split or marked open, or when a collapsible inside it is left unclosed.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Print a fixed placeholder when a credential in a refused title cannot be masked

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Keep a plain-title policy edit from scheduling every paid eval

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Record the paid-eval list change as non-behavioral for the shared test harness

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Recheck the PR title on every edit so a base change cannot turn a refused title green

Review-Finding: s11/targeted#1 reader=targeted
Review-Finding: s11/adversarial-native#1 reader=adversarial-native
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-08 00:59:38 +00:00
1 parent 892c3b13cd
commit 914e7b6fb3
78 files changed
+1770 -174

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
/**
* The Agent notes section (lib/agent-notes.ts, GST-1825): the collapsed block at the end of a PR body that holds the
* lines gstack's tools read. Covers where the receipt goes, which receipt binds (legacy top, inside the notes, a quoted
* example in the readable part, none), and that the Plan line and issue lines are found inside the notes.
*/
import { describe, expect, test } from 'bun:test';
import { AGENT_NOTES_MARKER, agentNotesOrBody, renderAgentNotes, splitAgentNotes, withAgentNotes } from '../lib/agent-notes';
import { parsePlanLine } from '../lib/plan-record';
import { bindReceipt, computeCensus, extractReceipt, missingIssueLines, orderReceipt, placeReceipt, receiptRuns, renderReceiptBlock } from '../lib/ship-receipt';
import type { ShipReceipt } from '../lib/headless-artifacts';
const HEAD = 'a'.repeat(40);
const OTHER = 'b'.repeat(40);
const receipt = (head: string, pr = 7): ShipReceipt => orderReceipt({ schema_version: 1, pr, head, base: 'main' });
const notes = (content: string) => renderAgentNotes(content);
describe('splitAgentNotes and withAgentNotes', () => {
test('a body with a section splits into the readable part and the content; one without has no notes', () => {
const body = 'Opening sentence.\n\n## Summary\n\nx\n\n' + notes('Plan: exempt: docs-only\nFixes #14');
expect(splitAgentNotes(body)).toEqual({ readable: 'Opening sentence.\n\n## Summary\n\nx\n\n', notes: 'Plan: exempt: docs-only\nFixes #14' });
expect(splitAgentNotes('Opening.\n')).toEqual({ readable: 'Opening.\n', notes: null });
expect(agentNotesOrBody('Opening.\n')).toBe('Opening.\n');
});
test('the marker inside a code fence opens no section, and </details> inside a fence in the notes does not close it', () => {
const quoted = 'Example:\n\n```md\n' + AGENT_NOTES_MARKER + '\n```\n';
expect(splitAgentNotes(quoted).notes).toBeNull();
const inner = 'Plan: exempt: x\n\n```text\n</details>\n```';
expect(splitAgentNotes('Body.\n\n' + notes(inner)).notes).toBe(inner);
});
test('withAgentNotes appends a section, replaces an existing one in place, keeps a trailing badge after it, and is stable', () => {
const once = withAgentNotes('Opening.\n\n## Summary\n\nx\n', 'Fixes #1');
expect(once).toBe('Opening.\n\n## Summary\n\nx\n\n' + notes('Fixes #1'));
const badge = '<!-- capy-badge:start -->\nB\n<!-- capy-badge:end -->\n';
const twice = withAgentNotes(once + '\n' + badge, 'Fixes #2');
expect(twice).toBe('Opening.\n\n## Summary\n\nx\n\n' + notes('Fixes #2') + '\n' + badge);
expect(withAgentNotes(twice, 'Fixes #2')).toBe(twice);
});
test('a collapsible a person adds after the section stays after it, and one nested inside the notes stays inside', () => {
const shots = '<details><summary>Screenshots</summary>\n\n![a](a.png)\n\n</details>\n';
const body = 'Opening.\n\n' + notes('Fixes #1') + '\n' + shots;
expect(splitAgentNotes(body).notes).toBe('Fixes #1');
expect(withAgentNotes(body, 'Fixes #2')).toBe('Opening.\n\n' + notes('Fixes #2') + '\n' + shots);
expect(placeReceipt(body, receipt(HEAD)).endsWith('</details>\n\n' + shots)).toBe(true);
const nested = 'Fixes #1\n\n<details><summary>Runs</summary>\n\nr\n\n</details>';
expect(splitAgentNotes('Opening.\n\n' + notes(nested) + '\n' + shots).notes).toBe(nested);
});
test('an open or two-line opener and an unclosed collapsible inside the notes keep text added after the section outside it', () => {
const after = '\nA note a person added.\n';
for (const opener of ['<details open><summary>Agent notes</summary>', '<details>\n<summary>Agent notes</summary>']) {
const body = `Opening.\n\n${AGENT_NOTES_MARKER}\n${opener}\n\nFixes #1\n\n</details>\n${after}`;
expect(splitAgentNotes(body).notes).toBe('Fixes #1');
expect(withAgentNotes(body, 'Fixes #2').endsWith('</details>\n' + after)).toBe(true);
}
const unclosed = 'Opening.\n\n' + notes('Fixes #1\n\n<details><summary>Runs</summary>\n\nr') + '\n' + after;
expect(splitAgentNotes(unclosed).notes).toBe('Fixes #1\n\n<details><summary>Runs</summary>\n\nr');
expect(withAgentNotes(unclosed, 'Fixes #2').endsWith('</details>\n' + after)).toBe(true);
});
});
describe('placeReceipt: the receipt lives in the Agent notes section', () => {
test('a body with no receipt gets a section holding the receipt; the other notes content stays above it', () => {
const fresh = placeReceipt('Opening.\n\n## Summary\n\nx\n', receipt(HEAD));
expect(fresh).toBe('Opening.\n\n## Summary\n\nx\n\n' + notes(renderReceiptBlock(receipt(HEAD))));
const withLines = placeReceipt('Opening.\n\n' + notes('Plan: exempt: docs-only\nFixes #14'), receipt(HEAD));
expect(splitAgentNotes(withLines).notes).toBe('Plan: exempt: docs-only\nFixes #14\n\n' + renderReceiptBlock(receipt(HEAD)).trim());
expect(placeReceipt(withLines, receipt(HEAD))).toBe(withLines);
});
test('a new receipt replaces the one in the notes, the old one joins the runs block there, and a quoted example fence in the readable part is removed', () => {
const example = 'Here is what the record looks like:\n\n' + renderReceiptBlock(receipt(OTHER, 1)) + '\nMore prose.\n';
const first = placeReceipt(example + '\n' + notes('Fixes #14'), receipt(HEAD));
const second = placeReceipt(first, receipt(OTHER));
expect(second.match(/```gstack-ship-receipt/g)).toHaveLength(1);
expect(splitAgentNotes(second).readable).toBe('Here is what the record looks like:\n\nMore prose.\n\n');
expect(extractReceipt(second).receipt!.head).toBe(OTHER);
expect(receiptRuns(second).map(r => r.head)).toEqual([HEAD]);
expect(splitAgentNotes(second).notes).toStartWith('Fixes #14\n\n```gstack-ship-receipt');
});
test('a legacy body (receipt at the top, no section) keeps its layout, so its Plan and issue lines stay readable', () => {
const legacy = renderReceiptBlock(receipt(HEAD)) + '\nOpening.\n\n## Approvals\n\nPlan: exempt: docs-only\n';
const placed = placeReceipt(legacy, receipt(OTHER));
expect(placed).toStartWith('```gstack-ship-receipt\n');
expect(placed).not.toContain(AGENT_NOTES_MARKER);
expect(extractReceipt(placed).receipt!.head).toBe(OTHER);
expect(receiptRuns(placed).map(r => r.head)).toEqual([HEAD]);
expect(parsePlanLine(placed)?.line).toBe('Plan: exempt: docs-only');
});
});
describe('which receipt binds', () => {
test('(a) a legacy receipt at the top of a body with no section binds', () => {
const body = renderReceiptBlock(receipt(HEAD)) + '\nOpening.\n\n## Summary\n\nx\n';
expect(bindReceipt(body, '7', [HEAD])).toMatchObject({ ok: true, head: HEAD });
});
test('(b) a receipt inside the Agent notes section binds', () => {
const body = 'Opening.\n\n## Summary\n\nx\n\n' + notes('Fixes #14\n\n' + renderReceiptBlock(receipt(HEAD)));
expect(bindReceipt(body, '7', [HEAD])).toMatchObject({ ok: true, head: HEAD });
});
test('(c) an example fence in the readable part never binds when the body has a section; the real one in the notes does', () => {
const body = 'Opening.\n\n' + renderReceiptBlock(receipt(OTHER)) + '\n## Summary\n\nx\n\n' + notes(renderReceiptBlock(receipt(HEAD)));
expect(extractReceipt(body).receipt!.head).toBe(HEAD);
expect(bindReceipt(body, '7', [HEAD])).toMatchObject({ ok: true, head: HEAD });
expect(bindReceipt(body, '7', [OTHER])).toMatchObject({ ok: false, code: 'QUEUE_RECEIPT_STALE' });
const quotedOnly = 'Opening.\n\n' + renderReceiptBlock(receipt(OTHER)) + '\n' + notes('Fixes #14');
expect(bindReceipt(quotedOnly, '7', [OTHER])).toMatchObject({ ok: false, code: 'QUEUE_RECEIPT_MISSING' });
});
test('(d) a body with no receipt binds nothing, with or without a section', () => {
expect(bindReceipt('Opening.\n', '7', [HEAD])).toMatchObject({ ok: false, code: 'QUEUE_RECEIPT_MISSING' });
expect(bindReceipt('Opening.\n\n' + notes('Fixes #14'), '7', [HEAD])).toMatchObject({ ok: false, code: 'QUEUE_RECEIPT_MISSING' });
});
test('the census counts the receipt in the notes and ignores a quoted one in the readable part', () => {
const body = 'Opening.\n\n' + renderReceiptBlock(orderReceipt({ schema_version: 1, head: OTHER, base: 'main', run: 'quoted' })) + '\n'
+ notes(renderReceiptBlock(orderReceipt({ schema_version: 1, head: HEAD, base: 'main', run: 'real', session_kind: 'unattended' })));
const census = computeCensus('acme/widget', '2026-11-01', [{ number: 1, mergedAt: '2026-11-02T00:00:00Z', body }], null);
expect(census.runs).toEqual(['real']);
expect(census.unattended_prs).toBe(1);
});
});
describe('readers find their lines inside the Agent notes section', () => {
test('the Plan line is read from the notes first; with none there, the readable part still counts', () => {
const body = 'Opening.\n\n## Summary\n\nx\n\n' + notes('Plan: exempt: docs-only\n\n' + renderReceiptBlock(receipt(HEAD)));
expect(parsePlanLine(body)).toEqual({ kind: 'exempt', line: 'Plan: exempt: docs-only', reason: 'docs-only' });
expect(parsePlanLine('Plan: approved: r-1\n\n' + notes('Plan: exempt: docs-only'))?.kind).toBe('exempt');
const readableOnly = 'Plan: approved: r-1\n\n' + notes('Fixes #14');
expect(parsePlanLine(readableOnly)).toEqual({ kind: 'approved', line: 'Plan: approved: r-1', token: 'r-1' });
const older = 'Opening.\n\n## Approvals\n\nPlan: exempt: docs-only\n';
expect(parsePlanLine(placeReceipt(older, receipt(HEAD)))).toEqual(parsePlanLine(older));
expect(parsePlanLine('## Approvals\n\nPlan: exempt: docs-only\n')?.kind).toBe('exempt');
});
test('issue lines count inside the notes, in the readable part, and in a legacy body', () => {
const issues = { fixes: [14], refs: [30], flakes: [] };
expect(missingIssueLines('Opening.\n\n' + notes('Fixes #14\nRefs #30'), issues)).toEqual([]);
expect(missingIssueLines('## Issues\nFixes #14\n\n' + notes('Refs #30'), issues)).toEqual([]);
expect(missingIssueLines('Opening.\n\n' + notes('Fixes #14'), issues)).toEqual(['Refs #30']);
});
});
+3 -3
View File
@@ -14,7 +14,7 @@ import * as os from 'node:os';
import * as path from 'node:path';
import { classifyBaseRed, parseEvidence, pausePath, readPause, receiptBaseRed, shellRunner, waitBaseGreen, writePause, type FailureEvidence, type Runner } from '../lib/base-red';
import { EXIT } from '../lib/headless-artifacts';
import { bindReceipt, extractReceipt, placeReceiptFirst, receiptSummaryLine } from '../lib/ship-receipt';
import { bindReceipt, extractReceipt, placeReceipt, receiptSummaryLine } from '../lib/ship-receipt';
import { BASE_RED_KEY_VERSION, validatePolicy, type BaseRedPolicy } from '../lib/ship-policy';
const ROOT = path.resolve(import.meta.dir, '..');
@@ -121,7 +121,7 @@ describe('pause, receipt and wait', () => {
if (typeof pause === 'string') throw new Error(pause);
expect(pause.expires_at).toBe('2026-10-30T00:00:00.000Z');
const head = git('rev-parse', 'HEAD');
const body = placeReceiptFirst('## Summary\n', { schema_version: 1, pr: 7, head, base: 'main', base_red: receiptBaseRed(pause) } as any);
const body = placeReceipt('## Summary\n', { schema_version: 1, pr: 7, head, base: 'main', base_red: receiptBaseRed(pause) } as any);
expect(extractReceipt(body).errors).toEqual([]);
const refused = bindReceipt(body, '7', [head]);
expect(refused.ok ? 'bound' : refused.code).toBe('QUEUE_RECEIPT_CONDITIONAL');
@@ -141,7 +141,7 @@ describe('pause, receipt and wait', () => {
if (typeof pause === 'string') throw new Error(pause);
const head = git('rev-parse', 'HEAD');
const bodyFile = path.join(root, 'body.md');
fs.writeFileSync(bodyFile, placeReceiptFirst('## Summary\n', { schema_version: 1, pr: 7, head, base: 'main', base_red: receiptBaseRed(pause) } as any));
fs.writeFileSync(bodyFile, placeReceipt('## Summary\n', { schema_version: 1, pr: 7, head, base: 'main', base_red: receiptBaseRed(pause) } as any));
const res = bin('gstack-ship-receipt', ['result', '--body', bodyFile, '--head', head, '--out', path.join(root, 'run')]);
expect(res.status).toBe(EXIT.fail);
expect(res.stdout.trim()).toBe(`GSTACK_RESULT: skill=ship status=incomplete head=${head} run=${path.join(root, 'run')}`);
+2 -2
View File
@@ -645,8 +645,8 @@ Make bisectable commits; if already committed, continue to Step 16. Never create
migrations may stand alone. Under 50 lines across fewer than 4 files may be one commit.
2. Order dependencies first: infrastructure → models/services → controllers/views.
Each commit works alone (no broken imports or missing code).
3. Use `<type>: <summary>` (feat/fix/chore/refactor/docs) and a brief body; fixing a
user-named issue adds a `Fixes: #<n>` trailer. Leave VERSION, CHANGELOG/fragment, TODOS.md
3. Subject: the change for a user in plain words, issue code last; brief body;
trailers last (a user-named issue: `Fixes: #<n>`). Leave VERSION, CHANGELOG/fragment, TODOS.md
and the digest uncommitted: Step 16's `finish` commits them last with
`--trailer 'Co-Authored-By: Claude <noreply@anthropic.com>'`. Do not add a Git tag.
+2 -2
View File
@@ -644,8 +644,8 @@ Make bisectable commits; if already committed, continue to Step 16. Never create
migrations may stand alone. Under 50 lines across fewer than 4 files may be one commit.
2. Order dependencies first: infrastructure → models/services → controllers/views.
Each commit works alone (no broken imports or missing code).
3. Use `<type>: <summary>` (feat/fix/chore/refactor/docs) and a brief body; fixing a
user-named issue adds a `Fixes: #<n>` trailer. Leave VERSION, CHANGELOG/fragment, TODOS.md
3. Subject: the change for a user in plain words, issue code last; brief body;
trailers last (a user-named issue: `Fixes: #<n>`). Leave VERSION, CHANGELOG/fragment, TODOS.md
and the digest uncommitted: Step 16's `finish` commits them last with
`--trailer 'Co-Authored-By: Claude <noreply@anthropic.com>'`. Do not add a Git tag.
+2 -2
View File
@@ -647,8 +647,8 @@ Make bisectable commits; if already committed, continue to Step 16. Never create
migrations may stand alone. Under 50 lines across fewer than 4 files may be one commit.
2. Order dependencies first: infrastructure → models/services → controllers/views.
Each commit works alone (no broken imports or missing code).
3. Use `<type>: <summary>` (feat/fix/chore/refactor/docs) and a brief body; fixing a
user-named issue adds a `Fixes: #<n>` trailer. Leave VERSION, CHANGELOG/fragment, TODOS.md
3. Subject: the change for a user in plain words, issue code last; brief body;
trailers last (a user-named issue: `Fixes: #<n>`). Leave VERSION, CHANGELOG/fragment, TODOS.md
and the digest uncommitted: Step 16's `finish` commits them last with
`--trailer 'Co-Authored-By: OpenAI Codex <noreply@openai.com>'`. Do not add a Git tag.
+2 -2
View File
@@ -649,8 +649,8 @@ Make bisectable commits; if already committed, continue to Step 16. Never create
migrations may stand alone. Under 50 lines across fewer than 4 files may be one commit.
2. Order dependencies first: infrastructure → models/services → controllers/views.
Each commit works alone (no broken imports or missing code).
3. Use `<type>: <summary>` (feat/fix/chore/refactor/docs) and a brief body; fixing a
user-named issue adds a `Fixes: #<n>` trailer. Leave VERSION, CHANGELOG/fragment, TODOS.md
3. Subject: the change for a user in plain words, issue code last; brief body;
trailers last (a user-named issue: `Fixes: #<n>`). Leave VERSION, CHANGELOG/fragment, TODOS.md
and the digest uncommitted: Step 16's `finish` commits them last with
`--trailer 'Co-Authored-By: Factory Droid <droid@users.noreply.github.com>'`. Do not add a Git tag.
+4 -1
View File
@@ -202,7 +202,10 @@
{ "file": "lib/pr-wait.ts", "movedFrom": "(new: gstack-pr-wait event logic, GSTA-115 item 1; design ported from tstack pr-wait)" },
{ "file": "lib/pr-wait-github.ts", "movedFrom": "(new: gstack-pr-wait gh reads, GSTA-115 item 1; design ported from tstack pr-wait)" },
{ "file": "lib/repo-state-clean.ts", "movedFrom": "(new: per-repo .gstack cleanup behind bin/gstack-clean, #2627)" },
{ "file": "lib/result-codes-clean.ts", "movedFrom": "lib/result-codes.ts (the gstack-clean rows, #2627)" }
{ "file": "lib/result-codes-clean.ts", "movedFrom": "lib/result-codes.ts (the gstack-clean rows, #2627)" },
{ "file": "lib/plain-title.ts", "movedFrom": "(new: the plain-English title, branch, opening and changelog check behind bin/gstack-plain-title, R76)" },
{ "file": "lib/result-codes-plain.ts", "movedFrom": "lib/result-codes.ts (the plain-title rows, R76)" },
{ "file": "lib/agent-notes.ts", "movedFrom": "(new: the PR body's closing Agent notes section, read by the receipt and Plan-line readers)" }
],
"residualFiles": [
{ "file": "scripts/test-free-shards.ts", "maxLines": 2361, "reason": "free lane policy after the shard engine took spawn, sandbox, logs, seeds and flags" },
+99 -1
View File
@@ -7,6 +7,9 @@
* the real executable against stub gh/glab on POSIX.
*/
import { describe, expect, test } from "bun:test";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { EXIT, attributionCallout, mergeBodySections, runPost, type PostEnv } from "../lib/gstack-post";
interface Call { cmd: string; args: string[]; input?: string }
@@ -738,7 +741,7 @@ describe("gstack-post pr-body merges the PR body by section", () => {
expect(() => mergeBodySections(current, RECEIPT("cccc") + "\n## A\n\nnew\n")).toThrow('holds "ship receipt" more than once');
});
// Value: protects=the body /ship composes (lib/ship-receipt.ts placeReceiptFirst: the receipt block, one blank line, then the sections) reposts
// Value: protects=the body /ship composes (lib/ship-receipt.ts placeReceipt: the receipt block, one blank line, then the sections) reposts
// idempotently: merged into a PR body of the same shape it yields the file's bytes, the receipt stays byte-first, and the stderr line reports no
// addition; fails_when=the blank line after the receipt is read as new leading text and prepended before the receipt (one more leading newline per
// repost, "added leading text" on every /ship re-READY), or a kept blank line is counted as added; why_new=the merge tests above post a receipt-only
@@ -774,3 +777,98 @@ describe("gstack-post pr-body merges the PR body by section", () => {
expect(afterReceipt.dropped).toEqual([]);
});
});
describe("gstack-post keeps the Agent notes section last", () => {
const RECEIPT = (head: string) => "```gstack-ship-receipt\n{\n \"head\": \"" + head + "\"\n}\n```\n";
const NOTES = (content: string) => "<!-- gstack:agent-notes -->\n<details><summary>Agent notes</summary>\n\n" + content + "\n\n</details>\n";
const composed = (head: string, summary: string) => "Opening sentence.\n\n## Summary\n\n" + summary + "\n\n## Test plan\n\n- [x] bun test\n\n" + NOTES("Plan: exempt: docs-only\n\n" + RECEIPT(head).trim());
// Value: protects=the body /ship composes since GST-1825 (opening, sections, Agent notes last) reposts byte for byte and replaces the notes as one
// section; fails_when=the receipt inside the notes is split out as its own section, or the notes stop being last; why_new=the notes section is new;
// seam=none (mergeBodySections); no_claim=the gh round trip
test("a full post whose notes section is last reposts byte for byte and replaces the notes, receipt included, as one section", () => {
const first = mergeBodySections(composed("aaaa", "old"), composed("bbbb", "new"));
expect(first.body).toBe(composed("bbbb", "new"));
expect([first.replaced, first.kept, first.added, first.dropped]).toEqual([["leading text", "Summary", "Test plan", "Agent notes"], [], [], []]);
expect(mergeBodySections(first.body, composed("bbbb", "new")).body).toBe(composed("bbbb", "new"));
});
// Value: protects=a partial post keeps the current notes and they stay last, above a Capy badge that ends the body; fails_when=a new section is
// appended after the notes or the badge moves above them; why_new=the notes section is new; seam=none; no_claim=the gh round trip
test("a partial post appends new sections above the kept notes, and a trailing Capy badge stays after them", () => {
const badge = "<!-- capy-badge:start -->\nB\n<!-- capy-badge:end -->\n";
const current = composed("aaaa", "old") + "\n" + badge;
const m = mergeBodySections(current, "## Why\n\nBecause.\n");
expect(m.body).toBe("Opening sentence.\n\n## Summary\n\nold\n\n## Test plan\n\n- [x] bun test\n\n## Why\n\nBecause.\n\n" + NOTES("Plan: exempt: docs-only\n\n" + RECEIPT("aaaa").trim()) + "\n" + badge);
expect(m.added).toEqual(["Why"]);
expect(m.kept).toContain("Agent notes");
});
// Value: protects=a PR posted before the notes section (receipt at the top) still merges: a partial post keeps the legacy receipt where it is, and a
// full post with notes last replaces it, so one receipt remains and it is the notes' one; fails_when=the legacy receipt survives a full post (two
// receipts, the stale one first) or a partial post drops it; why_new=the legacy layout meets the new one; seam=none; no_claim=the gh round trip
test("a legacy receipt-at-top body still merges: a partial post keeps it, a full post with notes last replaces it", () => {
const legacy = RECEIPT("aaaa") + "\n## Summary\n\nold\n\n## Approvals\n\nPlan: exempt: docs-only\n";
const partial = mergeBodySections(legacy, "## Summary\n\nnew\n");
expect(partial.body).toBe(RECEIPT("aaaa") + "\n## Summary\n\nnew\n\n## Approvals\n\nPlan: exempt: docs-only\n");
const full = mergeBodySections(legacy, composed("bbbb", "new"));
expect(full.body).toBe("Opening sentence.\n\n## Summary\n\nnew\n\n## Approvals\n\nPlan: exempt: docs-only\n\n## Test plan\n\n- [x] bun test\n\n" + NOTES("Plan: exempt: docs-only\n\n" + RECEIPT("bbbb").trim()));
expect(full.body.match(/```gstack-ship-receipt/g)).toHaveLength(1);
expect(full.replaced).toEqual(["ship receipt", "Summary"]);
});
});
describe("gstack-post refuses a title that is not in plain words (exit 4)", () => {
const repoWith = (policy: string | null) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "gstack-post-plain-"));
if (policy !== null) { fs.mkdirSync(path.join(root, ".gstack")); fs.writeFileSync(path.join(root, ".gstack", "plain-titles.json"), policy); }
return root;
};
const POLICY = JSON.stringify({ codes: ["\\bGST-\\d+\\b"], terms: ["pregate"], allow: [], since: "2026-11-08", exempt_branch_prefixes: [] });
// Value: protects=pr-title and pr-create post nothing (no title edit, no PR, no body) when the repository's plain-title policy refuses the title,
// print the PLAIN_TITLE lines and exit 4; a plain title with one trailing code posts; fails_when=the check runs after a post or not at all;
// why_new=R76 adds the check; seam=a real policy file under the fake root; no_claim=real gh
test("a refused title posts nothing, prints PLAIN_TITLE lines and exits 4; a plain title posts", () => {
const root = repoWith(POLICY);
try {
const bad = fakeEnv({ root, files: { "/t": "Make the pregate quieter\n", "/b": "Body.\n" } });
expect(run(["pr-title", "7", "--title-file", "/t"], bad)).toBe(EXIT.plainTitle);
expect(EXIT.plainTitle).toBe(4);
expect(bad.posts()).toEqual([]);
expect(bad.stdout()).toContain('PLAIN_TITLE: PLAIN_TITLE_REFUSED term "pregate"');
expect(bad.stdout()).toContain("PLAIN_TITLE: refused=1\n");
expect(bad.stderr()).toContain("nothing was posted");
const create = fakeEnv({ root, files: { "/t": "Fix GST-1713 retries", "/b": "Body.\n" } });
expect(run(["pr-create", "--base", "main", "--title-file", "/t", "--body-file", "/b"], create)).toBe(EXIT.plainTitle);
expect(create.calls.filter(c => c.cmd === "gh" || c.cmd === "glab")).toEqual([]);
const good = fakeEnv({ root, files: { "/t": "Stop gstack from hitting GitHub's rate limit (GST-1713)", "/b": "Body.\n" } });
expect(run(["pr-create", "--base", "main", "--title-file", "/t", "--body-file", "/b"], good)).toBe(EXIT.posted);
expect(good.posts()).toHaveLength(1);
const comment = fakeEnv({ root, files: { "/b": "The pregate passed.\n" } });
expect(run(["pr-comment", "7", "--body-file", "/b"], comment)).toBe(EXIT.posted);
} finally { fs.rmSync(root, { recursive: true, force: true }); }
});
// Value: protects=a repository without the policy file is never checked, and an invalid policy refuses rather than posting unchecked;
// fails_when=the missing file refuses every title or a broken file is ignored; why_new=R76 adds the check; seam=a real file; no_claim=real gh
test("no policy file posts unchecked; an invalid policy file refuses with exit 4 and posts nothing", () => {
const none = repoWith(null);
const broken = repoWith("{ not json");
try {
const f = fakeEnv({ root: none, files: { "/t": "Make the pregate quieter" } });
expect(run(["pr-title", "7", "--title-file", "/t"], f)).toBe(EXIT.posted);
const g = fakeEnv({ root: broken, files: { "/t": "Make the pregate quieter" } });
expect(run(["pr-title", "7", "--title-file", "/t"], g)).toBe(EXIT.plainTitle);
expect(g.posts()).toEqual([]);
expect(g.stderr()).toContain("(PLAIN_POLICY_INVALID); nothing was posted");
} finally { fs.rmSync(none, { recursive: true, force: true }); fs.rmSync(broken, { recursive: true, force: true }); }
});
test("the help names exit 4", () => {
const f = fakeEnv();
expect(run(["--help"], f)).toBe(EXIT.posted);
expect(f.stdout()).toContain("4 the title is not plain words");
});
});
+26 -26
View File
@@ -9,7 +9,7 @@ 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 { bindReceipt, classifyCarryPath, computeCensus, extractReceipt, parseReviewLoop, placeReceiptFirst, planCarry, receiptSummaryLine, renderReceiptBlock, stampOnlyText } from '../lib/ship-receipt';
import { bindReceipt, classifyCarryPath, computeCensus, extractReceipt, parseReviewLoop, placeReceipt, planCarry, receiptSummaryLine, renderReceiptBlock, stampOnlyText } from '../lib/ship-receipt';
import { cleanup, ghShim, makeFixtureRepo, makePr, recordAndBundle, restamp, runBin, type FixtureRepo } from './helpers/restamp-fixture';
const repos: FixtureRepo[] = [];
@@ -20,7 +20,7 @@ const HEAD = 'a'.repeat(40);
const block = (receipt: Record<string, unknown>) => renderReceiptBlock(receipt as any);
describe('gstack-ship-receipt write', () => {
test('writes the block identifiers-first, validates it against the ship-receipt schema, and puts it at the top of the PR body', () => {
test('writes the block identifiers-first, validates it against the ship-receipt schema, and puts it in the Agent notes section at the end of the PR body', () => {
const repo = fixture();
makePr(repo, 'pr-a', { expects: '1.2.4.0' });
expect(restamp(repo, ['--version', '1.2.4.0']).status).toBe(EXIT.ok);
@@ -54,8 +54,8 @@ describe('gstack-ship-receipt write', () => {
expect(parsed.receipt!.product_patch_id).toMatch(/^([0-9a-f]{40}|none)$/);
expect(parsed.receipt!.policy).toMatch(/^origin\/main@[0-9a-f]{12}:\.gstack\/ship-policy\.json$/);
const written = fs.readFileSync(body, 'utf8');
expect(written.startsWith('```gstack-ship-receipt\n{\n "schema_version": 1,\n "pr": 42,\n "head": "' + head + '"')).toBe(true);
expect(written).toContain('\n```\n\n## Summary\n\nProse that a truncated message may lose.\n');
expect(written.startsWith('## Summary\n\nProse that a truncated message may lose.\n\n<!-- gstack:agent-notes -->\n<details><summary>Agent notes</summary>\n\n```gstack-ship-receipt\n{\n "schema_version": 1,\n "pr": 42,\n "head": "' + head + '"')).toBe(true);
expect(written.endsWith('\n```\n\n</details>\n')).toBe(true);
expect(fs.readFileSync(path.join(repo.root, 'receipt.md'), 'utf8')).toBe(ok.out);
const art = runBin(repo, 'gstack-artifact', ['validate', path.join(repo.root, 'receipt.json'), '--as', 'ship-receipt']);
expect(art.status).not.toBe(EXIT.ok);
@@ -94,7 +94,7 @@ describe('gstack-ship-receipt read', () => {
const repo = fixture();
const receipt = { schema_version: 1, pr: 5, head: HEAD, version: '1.2.4.0', base: 'main', session_kind: 'unattended', artifacts_consumed: '1/1', run: 'run-5', thread: 'jam_5' };
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('Prose.\n', receipt as any));
fs.writeFileSync(body, placeReceipt('Prose.\n', receipt as any));
const b = runBin(repo, 'gstack-ship-receipt', ['read', '--body', body, '--json']);
expect(b.status).toBe(EXIT.ok);
expect(JSON.parse(b.out)).toEqual(receipt);
@@ -156,11 +156,11 @@ describe('gstack-ship-receipt result (/ship terminal line, GBRA-108)', () => {
const head = repo.git('rev-parse', 'HEAD');
const state = path.join(repo.root, 'state');
const env = { ...ghShim(repo, {
5: { headRefOid: head, body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 5, head, base: 'main', queue_mode: 'stamp-at-merge' } as any) },
6: { headRefOid: head, body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 6, head: 'b'.repeat(40), base: 'main' } as any) },
5: { headRefOid: head, body: placeReceipt('Prose.\n', { schema_version: 1, pr: 5, head, base: 'main', queue_mode: 'stamp-at-merge' } as any) },
6: { headRefOid: head, body: placeReceipt('Prose.\n', { schema_version: 1, pr: 6, head: 'b'.repeat(40), base: 'main' } as any) },
7: { headRefOid: head, body: 'No receipt here.\n' },
9: { headRefOid: 'd'.repeat(40), body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 9, head, base: 'main' } as any) },
10: { body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 10, head, base: 'main' } as any) },
9: { headRefOid: 'd'.repeat(40), body: placeReceipt('Prose.\n', { schema_version: 1, pr: 9, head, base: 'main' } as any) },
10: { body: placeReceipt('Prose.\n', { schema_version: 1, pr: 10, head, base: 'main' } as any) },
}), GSTACK_STATE_ROOT: state, GSTACK_SESSION_KIND: 'unattended' };
const ok = runBin(repo, 'gstack-ship-receipt', ['result', '--pr', '5'], env);
expect(ok.status).toBe(EXIT.ok);
@@ -245,7 +245,7 @@ describe('gstack-ship-receipt result (/ship terminal line, GBRA-108)', () => {
const invalid = runBin(repo, 'gstack-ship-receipt', ['result', '--body', invalidFile], env);
expect([invalid.status, invalid.out.trim()]).toEqual([EXIT.refused, 'GSTACK_RESULT: skill=ship status=refused run=-']);
expect(invalid.err).toMatch(/the receipt's ship receipt is invalid \(.*\).*\(QUEUE_RECEIPT_MISSING/);
const otherPrEnv = { ...env, ...ghShim(repo, { 8: { headRefOid: head, body: placeReceiptFirst('Prose.\n', { schema_version: 1, pr: 99, head, base: 'main' } as any) } }) };
const otherPrEnv = { ...env, ...ghShim(repo, { 8: { headRefOid: head, body: placeReceipt('Prose.\n', { schema_version: 1, pr: 99, head, base: 'main' } as any) } }) };
const otherPr = runBin(repo, 'gstack-ship-receipt', ['result', '--pr', '8'], otherPrEnv);
expect([otherPr.status, otherPr.out.trim()]).toEqual([EXIT.refused, 'GSTACK_RESULT: skill=ship status=refused run=-']);
expect(otherPr.err).toContain("PR #8's ship receipt names pr=99, not this PR");
@@ -303,7 +303,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
const head = repo.git('rev-parse', 'HEAD');
const state = path.join(repo.root, 'state');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 5, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', review_loop: { passes: 2, blocking_found: 1, deferred: 1 } } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 5, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', review_loop: { passes: 2, blocking_found: 1, deferred: 1 } } as any));
const env = { GSTACK_STATE_ROOT: state, GSTACK_SESSION_KIND: 'unattended' };
const dry = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--dry-run'], env);
expect(dry.status).toBe(EXIT.ok);
@@ -323,7 +323,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
expect(after.receipt!.carry!.product_patch_id).toMatch(/^[0-9a-f]{40}$/);
expect(after.receipt!.carry!.changed_paths.sort()).toEqual(['product:src/other.ts', 'test:test/app.test.ts']);
expect(after.receipt!.carry!.range_diff).not.toMatch(/^unavailable/);
expect(fs.readFileSync(body, 'utf8')).toContain('\n## Summary\n\nProse.\n');
expect(fs.readFileSync(body, 'utf8')).toStartWith('## Summary\n\nProse.\n\n<!-- gstack:agent-notes -->\n');
const run = JSON.parse(fs.readFileSync(path.join(repo.root, 'carry-run', 'ship-run.json'), 'utf8'));
expect(run).toMatchObject({ skill: 'ship', status: 'complete', head, pr: 5, carried_from: reviewed, carry_reason: 'base merge + test-only change' });
expect(bindReceipt(fs.readFileSync(body, 'utf8'), '5', [head]).ok).toBe(true);
@@ -351,7 +351,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
const reviewed = repo.git('rev-parse', 'HEAD');
const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state') };
const foreign = path.join(repo.root, 'foreign.md');
fs.writeFileSync(foreign, placeReceiptFirst('x\n', { schema_version: 1, pr: 5, head: 'c'.repeat(40), base: 'main' } as any));
fs.writeFileSync(foreign, placeReceipt('x\n', { schema_version: 1, pr: 5, head: 'c'.repeat(40), base: 'main' } as any));
repo.git('commit', '-q', '--allow-empty', '-m', 'empty follow-up');
const notAncestor = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', foreign], env);
expect(notAncestor.status).toBe(EXIT.refused);
@@ -367,7 +367,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
const shimDir = path.join(repo.root, 'gh2');
fs.mkdirSync(shimDir);
const posted = path.join(shimDir, 'posted.md');
const prBody = placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 8, head: reviewed, base: 'main' } as any);
const prBody = placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 8, head: reviewed, base: 'main' } as any);
fs.writeFileSync(path.join(shimDir, 'pr.json'), JSON.stringify({ body: prBody, headRefOid: head }));
fs.writeFileSync(path.join(shimDir, 'gh'), [
'#!/bin/sh',
@@ -462,7 +462,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
repo.git('commit', '-qam', 'stamp 1.2.4.0');
const head = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: reviewed, base: 'main', version: '1.2.3.0' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: reviewed, base: 'main', version: '1.2.3.0' } as any));
const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_SESSION_KIND: 'unattended' };
const carried = runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--out', path.join(repo.root, 'carry-run'), '--json'], env);
expect(carried.status).toBe(EXIT.ok);
@@ -544,7 +544,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
for (const [rel, text] of Object.entries(extra)) put(rel, text);
repo.git('add', '-A'); repo.git('commit', '-qm', 'merge main; entry into a fragment');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: reviewed, base: 'main', version: '1.2.3.0' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: reviewed, base: 'main', version: '1.2.3.0' } as any));
const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_SESSION_KIND: 'unattended' };
return { reviewed, head: repo.git('rev-parse', 'HEAD'), out: runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body, '--dry-run'], env) };
};
@@ -575,7 +575,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
repo.git('commit', '-qam', 'reviewed');
const reviewed = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: reviewed, base: 'main' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: reviewed, base: 'main' } as any));
const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_SESSION_KIND: 'unattended' };
// a carry-able commit (a test) with a pending product edit beside it: the pending edit is not in what the carry compares
fs.mkdirSync(path.join(repo.work, 'test'), { recursive: true });
@@ -615,7 +615,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
repo.git('checkout', '-q', 'feat'); repo.git('merge', '-q', '--no-edit', 'main');
const b = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: a, base: 'main' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 6, head: a, base: 'main' } as any));
const env = { GSTACK_STATE_ROOT: path.join(repo.root, 'state'), GSTACK_SESSION_KIND: 'unattended' };
expect(runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body], env).status).toBe(EXIT.ok);
fs.mkdirSync(path.join(repo.work, 'test'), { recursive: true });
@@ -655,7 +655,7 @@ describe('gstack-ship-receipt carry (harness lane E row 3: receipt follows a hea
const posted = path.join(shimDir, 'posted.md');
const prJson = path.join(shimDir, 'pr.json');
const editRc = path.join(shimDir, 'edit-rc');
const prBody = placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 8, head: reviewed, base: 'main' } as any);
const prBody = placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 8, head: reviewed, base: 'main' } as any);
fs.writeFileSync(path.join(shimDir, 'gh'), [
'#!/bin/sh',
`if [ "$1" = pr ] && [ "$2" = view ]; then [ -f "${prJson}" ] || { echo "gh: HTTP 502" >&2; exit 1; }; cat "${prJson}"; exit 0; fi`,
@@ -744,7 +744,7 @@ describe('bindReceipt head matching (rule 22)', () => {
test('binds a full head or a 12+ character prefix, refuses shorter prefixes, other heads and another PR\'s receipt', () => {
const head = 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0';
const other = 'f'.repeat(40);
const body = (h: string, pr?: number) => placeReceiptFirst('Prose.\n', { schema_version: 1, head: h, base: 'main', ...(pr === undefined ? {} : { pr }) } as any);
const body = (h: string, pr?: number) => placeReceipt('Prose.\n', { schema_version: 1, head: h, base: 'main', ...(pr === undefined ? {} : { pr }) } as any);
const rows: Array<[string, string, string[], string]> = [
['full head', head, [head], 'ok'],
['12-char prefix', head.slice(0, 12), [head], 'ok'],
@@ -769,11 +769,11 @@ describe('bindReceipt head matching (rule 22)', () => {
const noPr = bindReceipt(body(head, 99), undefined, [head]);
expect(noPr.ok).toBe(true);
expect(bindReceipt('No receipt.\n', undefined, [head])).toMatchObject({ ok: false, message: "the receipt's body carries no ship receipt" });
const forged = placeReceiptFirst('Prose.\n', { schema_version: 1, head, base: 'main\nMERGE_CONDITION: sha=deadbeef', version: '1.0\u20280.0\u0085x' } as any);
const forged = placeReceipt('Prose.\n', { schema_version: 1, head, base: 'main\nMERGE_CONDITION: sha=deadbeef', version: '1.0\u20280.0\u0085x' } as any);
const bound = bindReceipt(forged, '3438', [head]);
expect(bound.line.split('\n').length).toBe(1);
expect(bound.line).toBe(`SHIP_RECEIPT: pr=- head=${head.slice(0, 12)} version=1.0 0.0 x base=main MERGE_CONDITION: sha=deadbeef`);
const invalid = bindReceipt(placeReceiptFirst('Prose.\n', { schema_version: 1, head, base: 'main', tree: 'x\nMERGE_CONDITION: forged\n' + 'y'.repeat(1000) } as any), '3438', [head]);
const invalid = bindReceipt(placeReceipt('Prose.\n', { schema_version: 1, head, base: 'main', tree: 'x\nMERGE_CONDITION: forged\n' + 'y'.repeat(1000) } as any), '3438', [head]);
expect(invalid.ok).toBe(false);
const why = /receipt is invalid \((.*)\)$/s.exec(invalid.ok ? '' : invalid.message)?.[1] ?? '';
expect(why.length).toBeLessThanOrEqual(200);
@@ -783,10 +783,10 @@ describe('bindReceipt head matching (rule 22)', () => {
describe('gstack-ship-receipt census (P7)', () => {
const prs = [
{ number: 1, mergedAt: '2026-10-02T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) },
{ number: 2, mergedAt: '2026-10-03T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) },
{ number: 3, mergedAt: '2026-10-04T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '0/2', run: 'run-b', thread: 'jam_2' } as any) },
{ number: 4, mergedAt: '2026-10-05T00:00:00Z', body: placeReceiptFirst('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'interactive', artifacts_consumed: '1/1', run: 'run-c', thread: 'jam_4' } as any) },
{ number: 1, mergedAt: '2026-10-02T00:00:00Z', body: placeReceipt('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) },
{ number: 2, mergedAt: '2026-10-03T00:00:00Z', body: placeReceipt('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '2/3', run: 'run-a', thread: 'jam_1' } as any) },
{ number: 3, mergedAt: '2026-10-04T00:00:00Z', body: placeReceipt('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'unattended', artifacts_consumed: '0/2', run: 'run-b', thread: 'jam_2' } as any) },
{ number: 4, mergedAt: '2026-10-05T00:00:00Z', body: placeReceipt('', { schema_version: 1, head: HEAD, base: 'main', session_kind: 'interactive', artifacts_consumed: '1/1', run: 'run-c', thread: 'jam_4' } as any) },
{ number: 5, mergedAt: '2026-10-06T00:00:00Z', body: 'A PR shipped without gstack.\n' },
{ number: 6, mergedAt: '2026-10-07T00:00:00Z', body: block({ schema_version: 1, base: 'main' }) },
];
+1 -1
View File
@@ -433,7 +433,7 @@ describe('gstack-skill-start behavior', () => {
}, 60_000);
test('unattended /ship alone prints the UNATTENDED_SHIP status line naming the receipt file, the existing-PR body update and the result line (GSTA-88, rule 22)', () => {
const line = /^UNATTENDED_SHIP: no push, no new PR; an open PR at HEAD gets its body updated \(pr-body section, receipt first\), else Step 18 takes the handoff section; receipt at \.gstack\/tmp\/ship-receipt\.md; end with gstack-ship-receipt result$/gm;
const line = /^UNATTENDED_SHIP: no push, no new PR; an open PR at HEAD gets its body updated \(pr-body section, receipt in Agent notes\), else Step 18 takes the handoff section; receipt at \.gstack\/tmp\/ship-receipt\.md; end with gstack-ship-receipt result$/gm;
const ship = runStart(['--skill', 'ship'], { GSTACK_SESSION_KIND: 'unattended' });
expect(ship.match(line)).toHaveLength(1);
expect((ship.match(/^GSTACK_INSTRUCTION_BEGIN: (\S+)/gm) ?? []).map((h) => h.replace(/^GSTACK_INSTRUCTION_BEGIN: /, ''))).toEqual(['unattended-session']);
+1 -1
View File
@@ -23,7 +23,7 @@ const COPIED = [
'autoplan/SKILL.md', // its frontmatter registers the autoplan hook the hooks-row test breaks
'bin/gstack-launch-probe.sh',
'bin/gstack-doctor-check.sh', 'bin/gstack-doctor-components.sh', 'bin/gstack-runtime-pins.ts', 'lib/runtime-pins.ts',
'bin/gstack-windows-bash.ts', 'lib/script-invocation.ts', 'lib/bun-isolation.ts', 'lib/result-codes.ts', 'lib/result-codes-release.ts', 'lib/result-codes-capy.ts', 'lib/result-codes-budget.ts', 'lib/result-codes-eval.ts', 'lib/result-codes-plan.ts', 'lib/result-codes-autoplan.ts', 'lib/result-codes-browse.ts', 'lib/result-codes-clean.ts', // the windows bash row
'bin/gstack-windows-bash.ts', 'lib/script-invocation.ts', 'lib/bun-isolation.ts', 'lib/result-codes.ts', 'lib/result-codes-release.ts', 'lib/result-codes-capy.ts', 'lib/result-codes-budget.ts', 'lib/result-codes-eval.ts', 'lib/result-codes-plan.ts', 'lib/result-codes-autoplan.ts', 'lib/result-codes-browse.ts', 'lib/result-codes-clean.ts', 'lib/result-codes-plain.ts', // the windows bash row
];
const bases: string[] = [];
/** Registers the per-test fixture cleanup; each test file calls it at top level (a hook in this module would bind to the first importing file only). */
+2 -2
View File
@@ -106,7 +106,7 @@ export function openPr(fx: TrainFixture, pr: string, opts: { file?: string; text
repo.git('commit', '-q', '-m', `feat #${pr}`);
const head = repo.git('rev-parse', 'HEAD');
repo.git('push', '-q', '-f', 'origin', `HEAD:refs/pull/${pr}/head`, `${mergeRefCommit(fx, head)}:refs/pull/${pr}/merge`);
fx.write(d => { d.prs[pr] = { headRefOid: head, isCrossRepository: !!opts.cross, state: 'OPEN', headRefName: `pr-${pr}`, url: `https://github.com/fixture/repo/pull/${pr}`, body: opts.shipped === false ? '' : shippedBody(pr, head) }; });
fx.write(d => { d.prs[pr] = { headRefOid: head, isCrossRepository: !!opts.cross, state: 'OPEN', headRefName: `pr-${pr}`, title: `Change from #${pr}`, url: `https://github.com/fixture/repo/pull/${pr}`, body: opts.shipped === false ? '' : shippedBody(pr, head) }; });
return head;
}
@@ -160,7 +160,7 @@ export function wrapLand(fx: TrainFixture): void {
"const rev=r=>{try{return g('rev-parse','--verify','--quiet',r)}catch{return ''}};",
"if(a[0]==='pr'&&a[1]==='view'&&d.prs[a[2]]){const p=d.prs[a[2]];const h=rev('refs/heads/'+p.headRefName);if(h)p.headRefOid=h;save();console.log(JSON.stringify(p));process.exit(0)}",
"if(a[0]==='pr'&&a[1]==='edit'){(d.labels=d.labels||{})[a[2]]=a[a.indexOf('--add-label')+1];save();process.exit(0)}",
"if(a[0]==='pr'&&a[1]==='merge'){const p=d.prs[a[2]];const want=a[a.indexOf('--match-head-commit')+1];if(rev('refs/heads/'+p.headRefName)!==want){console.error('Head branch was modified');process.exit(1)}",
"if(a[0]==='pr'&&a[1]==='merge'){const p=d.prs[a[2]];const want=a[a.indexOf('--match-head-commit')+1];if(rev('refs/heads/'+p.headRefName)!==want){console.error('Head branch was modified');process.exit(1)}(d.mergeArgs=d.mergeArgs||{})[a[2]]=a.slice(3);",
" const before=rev('main');let tree=rev(want+'^{tree}');",
" if(d.outsideOnMerge){const blob=cp.execFileSync('git',['--git-dir',d.origin,'hash-object','-w','--stdin'],{input:'outside\\n',encoding:'utf8',timeout:30000}).trim();",
" const ls=g('ls-tree',before+'^{tree}')+'\\n100644 blob '+blob+'\\toutside.txt';const ot=cp.execFileSync('git',['--git-dir',d.origin,'mktree'],{input:ls+'\\n',encoding:'utf8',timeout:30000}).trim();",
+96
View File
@@ -0,0 +1,96 @@
/**
* plain-title.yml runs on pull_request_target, so it is held to the same static
* tripwire as pr-title-sync.yml (test/pr-title-sync-workflow-safety.test.ts):
* the job checks out the base repo only (no ref:), every PR field reaches the
* shell through env:, never as an inlined ${{ github.event.pull_request.* }}
* inside run:, the token is read-only, and every action is pinned to a commit.
* The job name "Plain title" is what ship-policy's required_checks will name.
*/
import { describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
const WORKFLOW = path.resolve(import.meta.dir, '..', '.github/workflows/plain-title.yml');
const content = fs.readFileSync(WORKFLOW, 'utf8');
const indent = (line: string) => line.match(/^( *)/)![1]!.length;
/** The lines inside every run: block (inline or block scalar), with 1-based line numbers. */
function runBlockLines(text: string): Array<{ n: number; text: string }> {
const out: Array<{ n: number; text: string }> = [];
let runIndent = -1;
text.split('\n').forEach((line, i) => {
const inline = line.match(/^\s*(?:-\s*)?run:\s*(\S.*)$/);
if (runIndent >= 0 && line.trim() !== '' && indent(line) <= runIndent) runIndent = -1;
if (runIndent >= 0) { out.push({ n: i + 1, text: line }); return; }
if (inline && !/^[|>]/.test(inline[1]!)) { out.push({ n: i + 1, text: inline[1]! }); return; }
if (/^\s*(?:-\s*)?run:\s*[|>][+-]?\s*$/.test(line)) runIndent = indent(line);
});
return out;
}
describe('plain-title.yml pull_request_target safety', () => {
test('runs on pull_request_target for the PR events that change a title, body or head', () => {
expect(content).toMatch(/^on:\s*\n\s+pull_request_target:/m);
expect(content).toMatch(/types:\s*\[opened, edited, synchronize, reopened, ready_for_review\]/);
});
test('the job is named "Plain title" and cancels older runs for the same PR', () => {
expect(content).toMatch(/^\s+name: Plain title\s*$/m);
expect(content).toMatch(/group: plain-title-\$\{\{ github\.event\.pull_request\.number \}\}/);
expect(content).toMatch(/cancel-in-progress: true/);
});
test('checks out the base repo only: no ref: anywhere', () => {
expect(content.split('\n').filter(l => /^\s*ref:/.test(l))).toEqual([]);
expect(content).toMatch(/uses: actions\/checkout@/);
});
test('no ${{ github.event.pull_request.* }} inside any run: block', () => {
const lines = runBlockLines(content);
expect(lines.length).toBeGreaterThan(3);
expect(lines.filter(l => /\$\{\{\s*github\.event\.pull_request/.test(l.text)).map(l => `L${l.n}: ${l.text.trim()}`)).toEqual([]);
});
test('the tripwire itself catches an inlined PR field', () => {
const planted = 'steps:\n - name: x\n run: |\n echo "${{ github.event.pull_request.title }}"\n - run: echo ${{ github.event.pull_request.body }}\n';
expect(runBlockLines(planted).filter(l => /\$\{\{\s*github\.event\.pull_request/.test(l.text)).length).toBe(2);
});
test('PR text reaches files through env: and printf, and is never echoed', () => {
expect(content).toMatch(/PR_TITLE: \$\{\{ github\.event\.pull_request\.title \}\}/);
expect(content).toMatch(/PR_BODY: \$\{\{ github\.event\.pull_request\.body \}\}/);
expect(content).toMatch(/printf '%s' "\$PR_TITLE" >/);
expect(content).toMatch(/printf '%s' "\$PR_BODY" >/);
const run = runBlockLines(content).map(l => l.text).join('\n');
expect(run).not.toMatch(/\becho\b[^\n]*\$\{?PR_/);
expect(run).not.toMatch(/\bcat\b/);
});
test('permissions are read-only', () => {
const perms = content.match(/^permissions:\n((?:\s+.+\n)+)/m)?.[1] ?? '';
expect(perms).toMatch(/contents: read/);
expect(perms).toMatch(/pull-requests: read/);
expect(content).not.toMatch(/:\s*write\b/);
});
test('the title is refused against created_at; branch, opening and commits only warn', () => {
expect(content).toMatch(/--title-file "\$RUNNER_TEMP\/pr-title\.txt" --created-at "\$PR_CREATED_AT" --mode refuse/);
expect(content).toMatch(/--commits-file "\$RUNNER_TEMP\/pr-commits\.txt" --created-at "\$PR_CREATED_AT" --mode warn/);
});
test('every action runs at a reviewed commit SHA, not a movable tag', () => {
const uses = [...content.matchAll(/^\s*(?:-\s*)?uses:\s*(\S+)/gm)].map(m => m[1]!);
expect(uses.length).toBeGreaterThan(0);
for (const ref of uses) expect(ref).toMatch(/^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/);
});
// Value: protects=a base-only edit reruns the title check and never posts a skipped "Plain title" run that ciAtHead and
// branch protection count as passing over an earlier refusal; fails_when=a job-level if: can skip the whole job;
// why_new=review finding plain-title.yml:34 (fail-open); seam=the workflow text; no_claim=GitHub's check ranking
test('the job has no job-level if:, so a skipped run never replaces a refused title', () => {
const job = content.split(/^ plain-title:\s*$/m)[1]!.split(/^ steps:\s*$/m)[0]!;
expect(job).toMatch(/name: Plain title/);
expect(job).not.toMatch(/^ if:/m);
});
});
+292
View File
@@ -0,0 +1,292 @@
/**
* lib/plain-title.ts and bin/gstack-plain-title (R76): titles, branch names, PR
* openings, changelog entries and commit subjects read in everyday words. The
* fixtures are real squash subjects from main for 2026-10-31..2026-11-07, frozen
* here without GitHub's " (#n)" squash suffix, since a PR title never carries it.
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { bunIsolationArgs } from '../lib/bun-isolation';
import { PLAIN_TITLE_POLICY_PATH, checkBranch, checkChangelogEntry, checkCommitSubject, checkOpening, checkTitle, loadPlainTitlePolicy, splitTitle, type PlainFinding } from '../lib/plain-title';
const ROOT = path.resolve(import.meta.dir, '..');
const BIN = path.join(ROOT, 'bin/gstack-plain-title');
const policy = loadPlainTitlePolicy(ROOT)!;
const brief = (f: PlainFinding[]) => f.map(x => `${x.kind}:${x.match}`);
const MAIN_SUBJECTS: Array<[string, string[]]> = [
['Let the design lint check one section of a running app for crowded rows, cramped help text, loud notes and small tap targets', []],
['Outside reviews that mention a problem no longer pass as clean', []],
['fix(autoplan): bind rec_hash to its run and plan; keep legacy gates answerable (GST-1819)', ['scope-prefix:fix(autoplan):']],
['fix: /autoplan gate makes each phase publish in order after its report (GST-1814)', []],
['fix(outside-review): a check-results sign-off keeps the no-findings conclusion (#3469)', ['scope-prefix:fix(outside-review):']],
['fix(ship): record-ci reuses its own CI row at the same tree, run and selection (GST-1795)', ['scope-prefix:fix(ship):']],
['v1.98.0.0 release: fold the changelog fragments', []],
['ship tooling: post-review voices dispatch, same-tree pregate clears, fix-check p<N> ledgers (GST-1775)', ['term:voices', 'term:pregate', 'term:fix-check', 'term:ledgers']],
["feat: crew PRs carry their brief's Plan line; ship-queue ready and land check it (GST-1751)", []],
['Require the daemon secret and loopback Host/Origin on the design and iOS QA daemons', []],
["browse: keep tunnel-paired agents on web URLs and away from the daemon's disk", []],
['feat(diff-scope): template UI in .ts/.js counts as frontend; receipt records the static design pass (GST-1718)', ['scope-prefix:feat(diff-scope):', 'term:receipt']],
["fix: gstack's GitHub waits poll REST at most once a minute and wait out rate limits (GST-1713)", []],
['fix(ship-receipt): name the non-ancestor targeted-read commit in RECEIPT_INVALID (GST-1700)', ['scope-prefix:fix(ship-receipt):', 'term:receipt']],
['fix: release stamps and a docs-audit edit after the last fix-check are no gate-class edit (GST-1702)', ['term:fix-check']],
["fix(ship): a cleared remote gate for HEAD's exact tree satisfies a lane whose inventory refuses that tree (GST-1688)", ['scope-prefix:fix(ship):', 'term:lane']],
['fix: the receipt and the review plan agree on stamp and docs carry for review_targeted (GST-1689)', ['term:receipt']],
['Capy session: defer the upgrade while a /ship or review run is open; upgrade-path fixes (GST-1677, GST-1658)', []],
['Playwright 1.65.0: bundled Chromium 158 drops the distrusted eMudhra root (#3338)', []],
['changelog.d: a second GST-1631 fragment names what the audit redaction does not cover yet (GST-1635)', ['code:GST-1631']],
['ship finish chains granted fix-check rows; a pregate rerun at the same tree keeps its clears (GST-1627)', ['term:pregate', 'term:fix-check']],
['release: daily stable check: important gated changes reach stable within a day, forced cut at 7 days (GST-1646, R74)', []],
];
describe('checkTitle', () => {
test.each(MAIN_SUBJECTS)('main subject: %s', (subject, expected) => {
expect(brief(checkTitle(subject, policy))).toEqual(expected);
});
test("R76's example passes with and without one trailing issue code", () => {
const good = "Stop gstack from hitting GitHub's rate limit while it waits on PRs";
expect(checkTitle(good, policy)).toEqual([]);
expect(checkTitle(`${good} (GST-1713)`, policy)).toEqual([]);
expect(checkTitle(`${good} (GST-1808, GST-1809)`, policy)).toEqual([]);
expect(checkTitle(`${good} (#4122)`, policy)).toEqual([]);
});
test('a code in the front is refused, wherever it sits', () => {
const f = checkTitle("Stop GST-1713 from hitting GitHub's rate limit", policy);
expect(f).toEqual([{ code: 'PLAIN_TITLE_REFUSED', kind: 'code', match: 'GST-1713', hint: expect.any(String) }]);
expect(brief(checkTitle('Apply R76 to titles (GST-1825)', policy))).toEqual(['code:R76']);
expect(brief(checkTitle('GSTA-36 lands PRs alone', policy))).toEqual(['code:GSTA-36']);
});
test("GitHub's squash suffix is a second group, so a code before it stays in the front", () => {
expect(brief(checkTitle('Fix the wait loop (GST-1713) (#4109)', policy))).toEqual(['code:GST-1713']);
});
test('UTF-8 and Cloudflare R2 are not read as codes', () => {
expect(checkTitle('Store UTF-8 uploads in Cloudflare R2', policy)).toEqual([]);
});
test('allow entries suppress only the match they contain', () => {
const p = { ...policy, allow: [...policy.allow, { text: 'merge train', reason: 'test' }] };
expect(checkTitle('Speed up the merge train', p)).toEqual([]);
expect(brief(checkTitle('Speed up the train', p))).toEqual(['term:train']);
});
test('terms match whole words, case-insensitive, multi-word terms included', () => {
expect(brief(checkTitle('Ask the Outside Voice once', policy))).toEqual(['term:Outside Voice']);
expect(checkTitle('Training runs no longer time out', policy)).toEqual([]);
expect(brief(checkTitle('Report to the CAPTAIN', policy))).toEqual(['term:CAPTAIN']);
});
test('a scope prefix is refused; a bare type prefix and a version prefix are allowed', () => {
expect(brief(checkTitle('docs(readme): explain setup', policy))).toEqual(['scope-prefix:docs(readme):']);
expect(checkTitle('fix: explain setup', policy)).toEqual([]);
expect(checkTitle('docs: explain setup', policy)).toEqual([]);
expect(checkTitle('v1.98.0.0 release', policy)).toEqual([]);
});
test('a credential in a refused title is masked in the finding, so no printed line carries it', () => {
const key = 'ghp_' + 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8';
const [f] = checkTitle(`fix(${key}): explain setup`, policy);
expect(f?.kind).toBe('scope-prefix');
expect(f?.match).not.toContain(key);
});
test('a credential the redactor cannot mask in place prints as a fixed placeholder, never the raw match', () => {
const header = '-----BEGIN ' + 'PRIVATE KEY-----';
const [f] = checkTitle(`fix(${header}): explain setup`, policy);
expect(f?.kind).toBe('scope-prefix');
expect(f?.match).toBe('<REDACTED>');
});
test('the titles gstack generates pass', () => {
expect(checkTitle('v1.98.0.0 release', policy)).toEqual([]);
expect(checkTitle('Add a changelog entry for changes merged by hand next to #4122', policy)).toEqual([]);
expect(checkTitle('Merge 2 related changes together (#4120, #4121)', policy)).toEqual([]);
});
test('splitTitle keeps only a trailing group made of references', () => {
expect(splitTitle('Fix waits (GST-1713)')).toEqual({ front: 'Fix waits', refs: 'GST-1713' });
expect(splitTitle('Fix waits (#4122, R76)')).toEqual({ front: 'Fix waits', refs: '#4122, R76' });
expect(splitTitle('Fix waits (on macOS)')).toEqual({ front: 'Fix waits (on macOS)', refs: null });
expect(splitTitle('Fix waits')).toEqual({ front: 'Fix waits', refs: null });
});
test('commit subjects use the title rule under their own code', () => {
expect(checkCommitSubject('fix(ship): pregate', policy).map(f => f.code)).toEqual(['PLAIN_COMMIT_REFUSED', 'PLAIN_COMMIT_REFUSED']);
});
});
describe('checkBranch', () => {
test('one trailing code is fine; a code in front is refused; generated branches are exempt', () => {
expect(checkBranch('capy/github-rate-limit-gst-1713', policy)).toEqual([]);
expect(checkBranch('capy/plain-english-pr-titles-gst-1825', policy)).toEqual([]);
expect(brief(checkBranch('capy/gst-1814-autoplan-gate-order', policy))).toEqual(['code:gst-1814']);
expect(checkBranch('release/1.98.0.0', policy)).toEqual([]);
expect(checkBranch('wave/ab12-r12', policy)).toEqual([]);
expect(checkBranch('gstack-land-repair/4122', policy)).toEqual([]);
});
test('hyphens and underscores separate words', () => {
expect(brief(checkBranch('capy/fix-check-loop', policy))).toEqual(['term:fix check']);
expect(brief(checkBranch('capy/faster_pregate', policy))).toEqual(['term:pregate']);
expect(checkBranch('capy/r2-uploads_r76', policy)).toEqual([]);
expect(checkBranch('capy/trainings-page', policy)).toEqual([]);
});
test("the exempt prefixes are the ones gstack's own tools generate", () => {
const src = (f: string) => fs.readFileSync(path.join(ROOT, f), 'utf8');
expect(src('lib/release-stamp.ts')).toContain('`release/${version}`');
expect(src('lib/ship-queue-wave.ts')).toContain("startsWith('wave/')");
expect(src('lib/ship-queue-land.ts')).toContain('`gstack-land-repair/${j.pr}`');
expect(policy.exempt_branch_prefixes).toEqual(['release/', 'wave/', 'gstack-land-repair/']);
});
});
describe('checkOpening', () => {
const NOTES = '<!-- gstack:agent-notes -->\n<details><summary>Agent notes</summary>\n\n```gstack-ship-receipt\n{"pr": 1}\n```\nRefs: GST-1713, pregate receipts\n\n</details>\n';
test('two plain sentences pass, and the Agent notes section is never read', () => {
const body = '\n\nWaits on GitHub now poll at most once a minute. This keeps gstack from hitting rate limits.\n\n## What changed\n\nGST-1713 pregate\n\n';
expect(checkOpening(body, policy)).toEqual([]);
expect(checkOpening(`${body}${NOTES}`, policy)).toEqual([]);
});
test('a receipt fence, heading, list, table, HTML or image first is refused', () => {
for (const [first, shape] of [['```gstack-ship-receipt\n{}\n```', 'fenced block'], ['## Summary', 'heading'], ['- one', 'list'], ['| a | b |', 'table'], ['<details>', 'HTML'], ['![shot](x.png)', 'image']]) {
expect(brief(checkOpening(`${first}\n\nPlain words.\n`, policy))).toEqual([`opening-shape:${shape} first`]);
}
expect(brief(checkOpening(NOTES, policy))).toEqual(['opening-shape:no opening paragraph']);
});
test('more than two sentences, or a code or term in the opening, is refused', () => {
expect(brief(checkOpening('One thing. Two things. Three things.', policy))).toEqual(['opening-shape:3 sentences']);
expect(checkOpening('This changes the setup, e.g. the default. It is plain.', policy)).toEqual([]);
expect(brief(checkOpening('The pregate clears faster (GST-1713).', policy))).toEqual(['code:GST-1713', 'term:pregate']);
});
test('a marker quoted inline in the opening does not end it; only the section marker on its own line does', () => {
const opening = 'Readers find the `<!-- gstack:agent-notes -->` section at the end. It holds the checks. It stays collapsed.\n\n';
expect(brief(checkOpening(opening + NOTES, policy))).toEqual(['opening-shape:3 sentences']);
});
});
describe('checkChangelogEntry', () => {
test('no code anywhere; terms only in the bold lead; code spans, URLs and quotes skipped', () => {
expect(brief(checkChangelogEntry('**The plan check works on public repos (GST-1774).** It reads the record.', policy))).toEqual(['code:GST-1774']);
expect(checkChangelogEntry('**The plan check works on public repos.** The receipt and the train now agree.', policy)).toEqual([]);
expect(brief(checkChangelogEntry('**A faster pregate.** Plain words.', policy))).toEqual(['term:pregate']);
expect(brief(checkChangelogEntry('**Plain lead.** Fixed in GST-12.', policy))).toEqual(['code:GST-12']);
expect(checkChangelogEntry('**Plain lead "pregate".** See `GST-12` and https://example.com/GST-12.\n\n```\nGST-13\n```\n', policy)).toEqual([]);
});
});
describe('policy', () => {
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'plain-title-'));
const withPolicy = (text: string) => { const dir = tmp(); fs.mkdirSync(path.join(dir, '.gstack')); fs.writeFileSync(path.join(dir, PLAIN_TITLE_POLICY_PATH), text); return dir; };
test('no policy file means no findings anywhere', () => {
expect(loadPlainTitlePolicy(tmp())).toBeNull();
expect(checkTitle('fix(ship): pregate GST-1', null)).toEqual([]);
expect(checkBranch('capy/gst-1-pregate', null)).toEqual([]);
expect(checkOpening('## heading', null)).toEqual([]);
expect(checkChangelogEntry('**GST-1 pregate**', null)).toEqual([]);
expect(checkCommitSubject('GST-1', null)).toEqual([]);
});
test('an invalid policy throws with the bad key named', () => {
const base = { codes: ['\\bX-\\d+\\b'], terms: ['a'], allow: [], since: '2026-11-08', exempt_branch_prefixes: [] };
expect(() => loadPlainTitlePolicy(withPolicy('{'))).toThrow(/not valid JSON/);
expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, codes: ['('] })))).toThrow(/codes\[0\] is not a valid regex/);
expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, codes: ['x?'] })))).toThrow(/matches empty text/);
expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, allow: [{ text: 'R2' }] })))).toThrow(/allow\[0\]\.reason/);
expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, since: 'soon' })))).toThrow(/since/);
expect(() => loadPlainTitlePolicy(withPolicy(JSON.stringify({ ...base, extra: 1 })))).toThrow(/extra is not a known key/);
expect(loadPlainTitlePolicy(withPolicy(JSON.stringify(base)))).toEqual(base);
});
test("gstack's policy loads and every allow entry says why", () => {
expect(PLAIN_TITLE_POLICY_PATH).toBe('.gstack/plain-titles.json');
expect(policy.since).toBe('2026-11-08');
expect(policy.allow.length).toBeGreaterThan(0);
for (const a of policy.allow) expect(a.reason.length).toBeGreaterThan(10);
});
});
describe('bin/gstack-plain-title', () => {
const dirs = { policy: fs.mkdtempSync(path.join(os.tmpdir(), 'plain-title-bin-')), none: fs.mkdtempSync(path.join(os.tmpdir(), 'plain-title-bin-')), invalid: fs.mkdtempSync(path.join(os.tmpdir(), 'plain-title-bin-')) };
fs.mkdirSync(path.join(dirs.policy, '.gstack'));
fs.copyFileSync(path.join(ROOT, PLAIN_TITLE_POLICY_PATH), path.join(dirs.policy, PLAIN_TITLE_POLICY_PATH));
fs.mkdirSync(path.join(dirs.invalid, '.gstack'));
fs.writeFileSync(path.join(dirs.invalid, PLAIN_TITLE_POLICY_PATH), '{"codes": [}');
const run = (dir: string, args: string[]) => {
const r = spawnSync(process.execPath, [...bunIsolationArgs(), BIN, ...args], { cwd: dir, encoding: 'utf8', timeout: 30_000, env: { ...process.env, GIT_CEILING_DIRECTORIES: path.dirname(dir) } });
const lines = r.stdout.trim().split('\n');
return { status: r.status, stdout: r.stdout, stderr: r.stderr, last: lines[lines.length - 1] };
};
const file = (name: string, text: string) => { const f = path.join(dirs.policy, name); fs.writeFileSync(f, text); return f; };
test('a refused title exits 1 with one line per finding and never echoes the title', () => {
const r = run(dirs.policy, ['check', '--title', 'fix(ship): the pregate secret-words-here']);
expect(r.status).toBe(1);
expect(r.stdout).toContain('PLAIN_TITLE: PLAIN_TITLE_REFUSED scope-prefix "fix(ship):" — ');
expect(r.stdout).toContain('PLAIN_TITLE: PLAIN_TITLE_REFUSED term "pregate" — ');
expect(r.stdout).not.toContain('secret-words-here');
expect(r.last).toBe('PLAIN_TITLE: refused=2');
});
test('a plain title and branch exit 0 with ok', () => {
const r = run(dirs.policy, ['check', '--title-file', file('t.txt', "Stop gstack from hitting GitHub's rate limit (GST-1713)\n"), '--branch', 'capy/github-rate-limit-gst-1713']);
expect([r.status, r.last]).toEqual([0, 'PLAIN_TITLE: ok']);
});
test('warn mode and commit subjects only warn', () => {
const warn = run(dirs.policy, ['check', '--branch', 'capy/gst-1814-autoplan-gate-order', '--body-file', file('b.md', '## Heading\n'), '--mode', 'warn']);
expect([warn.status, warn.last]).toEqual([0, 'PLAIN_TITLE: warned=2']);
const commits = run(dirs.policy, ['check', '--title', 'Plain title', '--commits-file', file('c.txt', 'fix(ship): pregate\nPlain subject\n\n')]);
expect([commits.status, commits.last]).toEqual([0, 'PLAIN_TITLE: warned=2']);
expect(commits.stdout).toContain('(warning only)');
const both = run(dirs.policy, ['check', '--title', 'pregate', '--commits-file', file('c2.txt', 'GST-1 done\n')]);
expect([both.status, both.last]).toEqual([1, 'PLAIN_TITLE: refused=1 warned=1']);
});
test('a changelog entry is checked', () => {
const r = run(dirs.policy, ['check', '--changelog', file('frag.md', '**Plain lead (GST-1774).**\n')]);
expect([r.status, r.last]).toEqual([1, 'PLAIN_TITLE: refused=1']);
});
test('a PR created before since is exempt; no policy is none', () => {
expect(run(dirs.policy, ['check', '--title', 'pregate', '--created-at', '2026-11-01T10:00:00Z'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: exempt (created before 2026-11-08)' });
expect(run(dirs.policy, ['check', '--title', 'pregate', '--created-at', '2026-11-08T10:00:00Z']).status).toBe(1);
expect(run(dirs.none, ['check', '--title', 'pregate GST-1'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: none (no policy)' });
});
test('an invalid policy exits 3; usage errors exit 2', () => {
const bad = run(dirs.invalid, ['check', '--title', 'x']);
expect(bad.status).toBe(3);
expect(bad.stderr).toContain('(PLAIN_POLICY_INVALID)');
expect(run(dirs.invalid, ['validate']).status).toBe(3);
expect(run(dirs.policy, ['check']).status).toBe(2);
expect(run(dirs.policy, ['check', '--nope']).status).toBe(2);
expect(run(dirs.policy, ['check', '--title', 'x', '--mode', 'loud']).status).toBe(2);
expect(run(dirs.policy, ['check', '--title', 'x', '--title-file', 'y']).status).toBe(2);
expect(run(dirs.policy, ['frobnicate']).status).toBe(2);
});
test('--json, validate, init and --help', () => {
const j = run(dirs.policy, ['check', '--title', 'pregate', '--json']);
expect(j.status).toBe(1);
expect(JSON.parse(j.stdout)).toMatchObject({ status: 'refused=1', refused: 1, warned: 0, findings: [{ code: 'PLAIN_TITLE_REFUSED', kind: 'term', match: 'pregate', severity: 'refused' }] });
expect(run(dirs.policy, ['validate'])).toMatchObject({ status: 0, last: expect.stringMatching(/^PLAIN_TITLE: valid \.gstack\/plain-titles\.json/) });
expect(run(dirs.none, ['validate'])).toMatchObject({ status: 0, last: 'PLAIN_TITLE: none (no policy)' });
expect(run(dirs.policy, ['init']).status).toBe(1);
const fresh = fs.mkdtempSync(path.join(os.tmpdir(), 'plain-title-bin-'));
expect(run(fresh, ['init']).status).toBe(0);
expect(loadPlainTitlePolicy(fresh)).not.toBeNull();
expect(run(dirs.policy, ['--help']).stdout).toContain('Exit codes: 0 ok');
});
});
+1 -1
View File
@@ -71,7 +71,7 @@ function scaffoldFixture(workDir: string): { workDir: string; stateRoot: string;
// These imports are resolved relative to the copied install, not the source checkout.
const libDir = path.join(workDir, 'lib');
fs.mkdirSync(libDir, { recursive: true });
for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts', 'bin-context.ts', 'remote-identity.ts', 'script-invocation.ts', 'bun-isolation.ts', 'result-codes.ts', 'result-codes-release.ts', 'result-codes-capy.ts', 'result-codes-budget.ts', 'result-codes-eval.ts', 'result-codes-plan.ts', 'result-codes-autoplan.ts', 'result-codes-browse.ts', 'result-codes-clean.ts']) {
for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts', 'bin-context.ts', 'remote-identity.ts', 'script-invocation.ts', 'bun-isolation.ts', 'result-codes.ts', 'result-codes-release.ts', 'result-codes-capy.ts', 'result-codes-budget.ts', 'result-codes-eval.ts', 'result-codes-plan.ts', 'result-codes-autoplan.ts', 'result-codes-browse.ts', 'result-codes-clean.ts', 'result-codes-plain.ts']) {
fs.copyFileSync(path.join(ROOT, 'lib', file), path.join(libDir, file));
}
+1 -1
View File
@@ -162,7 +162,7 @@ describe('safe classification (A1-2)', () => {
});
test('repository config read only by free lanes or GitHub stays in the PR profile', () => {
const files = ['.github/dependabot.yml', '.osv-scanner.toml', 'setup.ps1', '.gitlab-ci.yml', '.github/ISSUE_TEMPLATE/bug_report.md', '.gstack/ship-policy.example.json'];
const files = ['.github/dependabot.yml', '.osv-scanner.toml', 'setup.ps1', '.gitlab-ci.yml', '.github/ISSUE_TEMPLATE/bug_report.md', '.gstack/ship-policy.example.json', '.gstack/plain-titles.json'];
for (const file of files) expect(real.tracked.has(file), file).toBe(true);
const result = computePaidCaseSelection({ profile: 'pr', env: {}, changedFiles: files, packageVersionOnly: true });
expect(result.coverage?.mode).toBe('pr');
+1 -1
View File
@@ -327,7 +327,7 @@ describe('wiring', () => {
expect(summary).not.toContain('/investigate');
expect(prBody).toContain('names what the user gets, not the mechanism');
const capy = read('ship/sections/capy-pr.md.tmpl');
expect(capy).toContain('`## Why`, `## Blast radius` and `## Approvals`');
expect(capy).toContain('`## What changed`, `## Why` and `## Blast radius`');
expect(capy).toMatch(/\*\*`## Why`:\*\* two or three sentences\. The first states the problem in the person's words/);
expect(capy).toMatch(/BAD "[\s\S]+" GOOD "/);
expect(capy).toContain("**`## Blast radius`:** the body template's item, written once");
+2 -2
View File
@@ -11,7 +11,7 @@ import * as path from 'node:path';
import { EXIT } from '../lib/headless-artifacts';
import { checkoutTree } from '../lib/review-brief';
import { TARGETED_RULES, targetedBriefSha } from '../lib/review-targeted';
import { extractReceipt, placeReceiptFirst } from '../lib/ship-receipt';
import { extractReceipt, placeReceipt } from '../lib/ship-receipt';
import { receiptDepthAtHead, targetedClassesSince } from '../lib/ship-receipt-depth';
import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture';
@@ -255,7 +255,7 @@ describe('write and carry refuse a receipt the queue\'s targeted verdict refuses
let n = 0;
const carry = (receipt: object) => {
const body = path.join(repo.root, `body-${++n}.md`);
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', receipt as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', receipt as any));
return { ...runBin(repo, 'gstack-ship-receipt', ['carry', '--body', body], { GSTACK_STATE_ROOT: path.join(repo.root, 'state') }), body };
};
const uncovered = carry(versioned);
+3 -1
View File
@@ -7,6 +7,7 @@
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { splitAgentNotes } from '../lib/agent-notes';
import { EXIT } from '../lib/headless-artifacts';
import { lineSources, mentionsIn, promotionCandidates, relatedPrs, renderIssueLines, resolveLinks, selectFlakes, type ClosingPr, type IssueRow } from '../lib/issue-links';
import { cleanup, commit, ghShim, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture';
@@ -240,7 +241,8 @@ describe('gstack-issue-links (bin): related PRs, flake validation, lookup failur
const ok = runBin(repo, 'gstack-ship-receipt', args, env);
expect(ok.status).toBe(EXIT.ok);
expect(JSON.parse(ok.out).issues).toEqual({ fixes: [14], refs: [30], flakes: [], related: [{ pr: 7, author: 'alice', closes: [14] }] });
expect(fs.readFileSync(body, 'utf8').startsWith('```gstack-ship-receipt')).toBe(true);
expect(fs.readFileSync(body, 'utf8').startsWith('## Summary')).toBe(true);
expect(splitAgentNotes(fs.readFileSync(body, 'utf8')).notes).toStartWith('```gstack-ship-receipt');
});
});
+2 -1
View File
@@ -16,12 +16,13 @@ function writeDrafts(root: string, top = '## Summary\n\n## Documentation', rest
}
const POST = resolve(import.meta.dir, '../bin/gstack-post');
const PROSE_LINT = resolve(import.meta.dir, '../bin/gstack-prose-lint');
const PLAIN_TITLE = resolve(import.meta.dir, '../bin/gstack-plain-title');
/** The two real bins the blocks call, at the installed path under a HOME of `root`. */
function installBins(root: string): void {
const bin = join(root, '.claude/skills/gstack/bin');
mkdirSync(bin, { recursive: true });
for (const [name, target] of [['gstack-post', POST], ['gstack-prose-lint', PROSE_LINT]] as const) {
for (const [name, target] of [['gstack-post', POST], ['gstack-prose-lint', PROSE_LINT], ['gstack-plain-title', PLAIN_TITLE]] as const) {
writeFileSync(join(bin, name), `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(target)} "$@"\n`, { mode: 0o755 });
}
}
+6 -5
View File
@@ -141,7 +141,7 @@ describe('land --pin: direct merge at the PR\'s own green head', () => {
const r = land(fx, '7', pin);
expect(r.err).toBe('');
expect(r.status).toBe(EXIT.ok);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin]);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin, '--subject', 'PR 7 (#7)']);
const main = remote(fx, 'main');
expect(fx.repo.git('rev-parse', main + '^1')).toBe(base);
expect(r.out).toContain('MERGED: #7 as ' + main);
@@ -580,6 +580,7 @@ describe('land --pin: refusals (nothing merged)', () => {
const missing = land(fx, '17', pin);
refused(fx, missing, 'QUEUE_LAND_CHECKS');
expect(missing.err).toContain('Check VERSION is not stale vs queue');
expect(missing.out + missing.err).toContain('cannot be dispatched, so edit the PR title or body to rerun it');
}, 90_000);
test('QUEUE_LAND_NOT_CLEAN: GitHub does not report the PR mergeable and clean', () => {
@@ -658,7 +659,7 @@ describe('land --pin: fail closed and merge methods', () => {
fx.write(d => { d.prs['25'].baseRefName = 'main'; });
const r = land(fx, '25', pin);
expect(r.err).toBe('');
expect(fx.read().mergeArgs).toEqual(['25', '--merge', '--match-head-commit', pin]);
expect(fx.read().mergeArgs).toEqual(['25', '--merge', '--match-head-commit', pin, '--subject', 'PR 25 (#25)']);
}, 90_000);
test('land reads the policy after fetching the base: a required check main added since the last fetch is enforced', () => {
@@ -961,7 +962,7 @@ describe('land --pin --repair: the one way through a backstop freeze under merge
expect(r.err).toBe('');
expect(r.status).toBe(EXIT.ok);
expect(r.out).toMatch(/^FREEZE: warn only: train backstop froze main \(backstop red on main [0-9a-f]{12}: .*\); the base policy declares release_gate/m);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin]);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin, '--subject', 'PR 7 (#7)']);
expect(freezeOf(fx)).toMatchObject({ train: 'backstop', repair: null, cleared_at: null });
}, 90_000);
@@ -996,7 +997,7 @@ describe('land --pin --repair: the one way through a backstop freeze under merge
expect(r.err).toBe('');
expect(r.status).toBe(EXIT.ok);
expect(r.out).toContain(`REPAIR: #7@${pin7.slice(0, 12)} admitted under the land lock`);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin7]);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin7, '--subject', 'PR 7 (#7)']);
expect(fx.read().lockAtMerge).toMatchObject({ pr: '7', journal: 'land-pin:' + pin7 });
expect(freezeOf(fx)).toMatchObject({ train: 'backstop', repair: { pr: '7', head: pin7, train: null }, cleared_at: null, cleared_by: null });
expect(landNotes(fx)).toEqual([expect.objectContaining({ pr: '7', pin: pin7, merge_sha: remote(fx, 'main') })]);
@@ -1004,7 +1005,7 @@ describe('land --pin --repair: the one way through a backstop freeze under merge
expect(second.err).toContain('(QUEUE_TRAIN_FROZEN)');
expect(second.err).toContain(`repair #7@${pin7.slice(0, 12)}`);
expect(land(fx, '8', pin8).err).toContain('(QUEUE_TRAIN_FROZEN)');
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin7]);
expect(fx.read().mergeArgs).toEqual(['7', '--squash', '--match-head-commit', pin7, '--subject', 'PR 7 (#7)']);
}, 120_000);
test('a recorded repair that never merged at its pin gives way to the next --repair; a repair train holding the freeze does not', () => {
+3 -2
View File
@@ -247,7 +247,7 @@ describe('generic trains end to end (fixture repos)', () => {
expect(origin('rev-parse', 'main^{tree}')).toBe(t.gated[2].tree);
expect(trainJson(fx, nonce)).toMatchObject({ state: 'merged', landing: { 1: { mode: 'direct', update: null }, 2: { mode: 'direct' } } });
const merges = fx.read().log.filter(l => l.cmd === 'pr merge').map(l => (l.args as string[]).join(' '));
expect(merges[0]).toMatch(/^pr merge 1 --squash --match-head-commit [0-9a-f]{40}$/);
expect(merges[0]).toMatch(/^pr merge 1 --squash --match-head-commit [0-9a-f]{40} --subject Change from #1 \(#1\)$/);
}, 300_000);
test('strict protection forces update; a rebase method refuses it; a fork head is refused', () => {
@@ -653,6 +653,7 @@ describe('a pin whose own checks are red (round-2 High 2)', () => {
expect(merged.status, merged.err + merged.out).toBe(EXIT.ok);
const t = trainJson(fx, nonce);
expect(t.landing['1']).toMatchObject({ mode: 'update' });
expect((fx.read().log.find(l => l.cmd === 'pr merge')!.args as string[]).at(-1)).toBe(t.landing['1'].update);
const mergeArgs = fx.read().log.find(l => l.cmd === 'pr merge')!.args as string[];
expect(mergeArgs[mergeArgs.indexOf('--match-head-commit') + 1]).toBe(t.landing['1'].update);
}, 300_000);
});
+1
View File
@@ -62,6 +62,7 @@ describe('stamped trains: build and land', () => {
expect(trainJson(fx, nonce)).toMatchObject({ state: 'merged' });
expect(fx.read().prs['2']).toMatchObject({ state: 'MERGED' });
expect((fx.read() as any).labels).toEqual({ 1: 'evals-no-debounce', 2: 'evals-no-debounce' });
expect((fx.read() as any).mergeArgs['1']).toEqual(['--squash', '--match-head-commit', stamp, '--subject', 'Change from #1 (#1)']);
void h2;
}, 300_000);
+15 -12
View File
@@ -3,37 +3,40 @@
* schema carries K1's no_stop records for L5.
*/
import { describe, expect, test } from 'bun:test';
import { extractReceipt, orderReceipt, placeReceiptFirst, readyTailLines, receiptRuns, RECEIPT_RUNS_KEPT, validateReceipt } from '../lib/ship-receipt';
import { extractReceipt, orderReceipt, placeReceipt, readyTailLines, receiptRuns, RECEIPT_RUNS_KEPT, validateReceipt } from '../lib/ship-receipt';
import type { ShipReceipt } from '../lib/headless-artifacts';
const receipt = (head: string, loop: Partial<NonNullable<ShipReceipt['review_loop']>> = {}): ShipReceipt =>
orderReceipt({ schema_version: 1, head, base: 'main', version: '1.94.1.0', review_loop: { passes: 1, blocking_found: 0, deferred: 0, ...loop } });
describe('receipt runs block', () => {
test('a write over a different receipt keeps the old run, oldest first, after the current block', () => {
let body = placeReceiptFirst('## Summary\nprose\n', receipt('a'.repeat(40), { passes: 2, blocking_found: 3, fixed: 3 }));
body = placeReceiptFirst(body, receipt('b'.repeat(40)));
body = placeReceiptFirst(body, receipt('c'.repeat(40), { passes: 1 }));
test('a write over a different receipt keeps the old run, oldest first, after the current block in the Agent notes section', () => {
let body = placeReceipt('## Summary\nprose\n', receipt('a'.repeat(40), { passes: 2, blocking_found: 3, fixed: 3 }));
body = placeReceipt(body, receipt('b'.repeat(40)));
body = placeReceipt(body, receipt('c'.repeat(40), { passes: 1 }));
expect(extractReceipt(body).receipt!.head).toBe('c'.repeat(40));
expect(receiptRuns(body).map(r => [r.head[0], r.review_loop?.blocking_found])).toEqual([['a', 3], ['b', 0]]);
expect(body.indexOf('gstack-receipt-runs')).toBeLessThan(body.indexOf('## Summary'));
expect(body.indexOf('gstack-receipt-runs')).toBeGreaterThan(body.indexOf('<!-- gstack:agent-notes -->'));
expect(body.indexOf('gstack-receipt-runs')).toBeGreaterThan(body.indexOf('```gstack-ship-receipt'));
expect(body.indexOf('<!-- gstack:agent-notes -->')).toBeGreaterThan(body.indexOf('## Summary'));
expect(body.match(/## Summary/g)!.length).toBe(1);
});
test('a fence inside a recorded reason never closes the runs block (adversarial p-voices #1)', () => {
const withReason = (head: string) => orderReceipt({ ...receipt(head, { fix_checks: 1 }), review_loop_exception: { accepted_by: 'Garry', date: '2026-11-03', via: 'x', reason: 'the \x60\x60\x60retry\x60\x60\x60 block is fine', fix_check: { head, findings: 0 } } });
let body = placeReceiptFirst('## Summary\nprose\n', withReason('b'.repeat(40)));
body = placeReceiptFirst(body, withReason('c'.repeat(40)));
body = placeReceiptFirst(body, withReason('d'.repeat(40)));
let body = placeReceipt('## Summary\nprose\n', withReason('b'.repeat(40)));
body = placeReceipt(body, withReason('c'.repeat(40)));
body = placeReceipt(body, withReason('d'.repeat(40)));
expect(receiptRuns(body).map(r => r.head[0])).toEqual(['b', 'c']);
expect(body.endsWith('## Summary\nprose\n')).toBe(true);
expect(body.startsWith('## Summary\nprose\n\n<!-- gstack:agent-notes -->\n')).toBe(true);
expect(body.endsWith('```\n\n</details>\n')).toBe(true);
});
test('rewriting the same receipt adds no run, and the block keeps the newest RECEIPT_RUNS_KEPT', () => {
const same = receipt('d'.repeat(40));
expect(receiptRuns(placeReceiptFirst(placeReceiptFirst('', same), same))).toEqual([]);
expect(receiptRuns(placeReceipt(placeReceipt('', same), same))).toEqual([]);
let body = '';
for (let i = 0; i < RECEIPT_RUNS_KEPT + 5; i++) body = placeReceiptFirst(body, receipt(i.toString(16).padStart(40, '0')));
for (let i = 0; i < RECEIPT_RUNS_KEPT + 5; i++) body = placeReceipt(body, receipt(i.toString(16).padStart(40, '0')));
const runs = receiptRuns(body);
expect(runs.length).toBe(RECEIPT_RUNS_KEPT);
expect(runs.at(-1)!.head).toBe((RECEIPT_RUNS_KEPT + 3).toString(16).padStart(40, '0'));
+2 -2
View File
@@ -10,7 +10,7 @@ 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 { extractReceipt, placeReceiptFirst } from '../lib/ship-receipt';
import { extractReceipt, placeReceipt } from '../lib/ship-receipt';
import { planRecheck, readRecheck, RECHECK_PACKET_BYTES, RECHECK_RANGE_DIFF_CAP } from '../lib/ship-recheck';
import { cleanup, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/restamp-fixture';
@@ -125,7 +125,7 @@ describe('carry with a scoped re-check (CLI)', () => {
test('a legacy receipt, more changed paths than the walk names, and moved base context print RECHECK: not eligible', () => {
const legacy = reviewed();
fs.writeFileSync(legacy.body, placeReceiptFirst('## Summary\n', { schema_version: 1, pr: 5, head: legacy.from, base: 'main' } as any));
fs.writeFileSync(legacy.body, placeReceipt('## Summary\n', { schema_version: 1, pr: 5, head: legacy.from, base: 'main' } as any));
legacy.commit({ 'src/app.ts': 'export const a = 3;\n' }, 'fix');
expect(runBin(legacy.repo, 'gstack-ship-receipt', ['carry', '--body', legacy.body], legacy.env).err).toContain('RECHECK: not eligible (the receipt records no review_depth');
+17
View File
@@ -311,6 +311,23 @@ describe('push (Step 17)', () => {
expect(r.stdout).toContain('STOP: non-fast-forward');
expect(r.stdout).toContain('never force-push');
});
// Value: protects=a never-pushed branch whose name breaks the repo's plain-words policy stops before the push, and a plain name pushes; fails_when=a coded or jargon branch name reaches origin, or a plain one is refused;
// why_new=plain public record (docs/ship-policy.md#plain-titles); seam=.gstack/plain-titles.json, git ls-remote; no_claim=branches already on origin
test('a never-pushed branch name with a tracker code or coined term in its front stops; a plain name pushes', () => {
const f = fx();
f.write({ '.gstack/plain-titles.json': JSON.stringify({ codes: ['\\bGST-\\d+\\b'], terms: ['pregate'], allow: [], since: '2026-11-08', exempt_branch_prefixes: ['release/'] }) });
f.commit('policy');
f.git('branch', '-m', 'gst-1825-pregate-fix');
const r = f.run(RELEASE, ['push', '--branch', 'gst-1825-pregate-fix'], { GSTACK_SESSION_KIND: 'unattended' });
expect(r.status, r.stdout + r.stderr).toBe(3);
expect(lineOf(r.stdout, 'BRANCH')).toContain('BRANCH: refused');
expect(r.stdout).toContain('is not plain words');
f.git('branch', '-m', 'faster-checks-gst-1825');
const ok = f.run(RELEASE, ['push', '--branch', 'faster-checks-gst-1825'], { GSTACK_SESSION_KIND: 'unattended' });
expect(ok.status, ok.stdout + ok.stderr).toBe(0);
expect(lineOf(ok.stdout, 'PUSH')).toMatch(/^PUSH: pushed [0-9a-f]{12} to origin\/faster-checks-gst-1825$/);
});
});
describe('gstack-ship-release push: branch names', () => {
+8 -8
View File
@@ -10,7 +10,7 @@ import * as path from 'node:path';
import { EXIT } from '../lib/headless-artifacts';
import { comparePath } from '../lib/ship-patch';
import { STAMP_PLACEHOLDERS_KEY_VERSION } from '../lib/ship-policy';
import { extractReceipt, placeReceiptFirst } from '../lib/ship-receipt';
import { extractReceipt, placeReceipt } from '../lib/ship-receipt';
import { cleanup, makeFixtureRepo, runBin, write, type FixtureRepo } from './helpers/pregate-fixture';
import { lineOf, PREFLIGHT, RELEASE, shipFixture, type ShipFx } from './helpers/ship-bin-fixture';
@@ -354,7 +354,7 @@ describe('adjacent base edits (GST-384, #3631, founderstar#441)', () => {
write(repo.work, 'lib/rows.js', src({ 6: 'exports.v6 = 600;' })); repo.git('commit', '-qam', 'feat: v6');
const reviewed = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any));
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src({ 5: 'exports.v5 = "five";' })); repo.git('commit', '-qam', 'main: v5'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature');
@@ -382,7 +382,7 @@ describe('adjacent base edits (GST-384, #3631, founderstar#441)', () => {
const guard = (text: string, after: string) => text.replace('authorize();\n', '').replace(after + '\n', after + '\nauthorize();\n');
const rows = () => fs.readFileSync(path.join(repo.work, 'lib/rows.js'), 'utf8');
write(repo.work, 'lib/rows.js', guard(rows(), 'exports.v2 = 2;')); repo.git('commit', '-qam', 'feat: guard v2');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
write(repo.work, 'lib/rows.js', guard(rows(), 'exports.v4 = 4;')); repo.git('commit', '-qam', 'feat: move the guard');
const moved = carry();
expect(moved.status).toBe(EXIT.refused);
@@ -408,7 +408,7 @@ describe('carry with a context path and a gap elsewhere (GST-407 cycle 5)', () =
write(repo.work, 'lib/rows.js', src({ 6: 'exports.v6 = 600;' })); write(repo.work, 'plugin/b.json', json('b2')); repo.git('commit', '-qam', 'feat: v6, b2');
const reviewed = repo.git('rev-parse', 'HEAD');
const body = path.join(repo.root, 'body.md');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any));
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src({ 5: 'exports.v5 = "five";' })); write(repo.work, 'plugin/b.json', json('b2')); write(repo.work, 'plugin/a.json', json('a2'));
repo.git('commit', '-qam', 'main: v5, b2 landed, a2'); repo.git('push', '-q', 'origin', 'main');
@@ -418,7 +418,7 @@ describe('carry with a context path and a gap elsewhere (GST-407 cycle 5)', () =
expect([gap.status, gap.out.trim().split('\n')[0]]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_PRODUCT_CHANGED)']);
write(repo.work, 'plugin/b.json', json('b')); write(repo.work, 'lib/rows.js', src({ 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' }) + Array.from({ length: 220 }, (_, i) => `exports.w${i} = ${i};\n`).join(''));
repo.git('commit', '-qam', 'feat: many rows');
fs.writeFileSync(body, placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
fs.writeFileSync(body, placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: repo.git('rev-parse', 'HEAD'), base: 'main', queue_mode: 'stamp-at-merge' } as any));
repo.git('checkout', '-q', 'main');
write(repo.work, 'lib/rows.js', src({ 5: 'exports.v5 = "5";' })); repo.git('commit', '-qam', 'main: v5 again'); repo.git('push', '-q', 'origin', 'main');
repo.git('checkout', '-q', 'feature');
@@ -595,7 +595,7 @@ describe('preflight carry route for an adjacent base edit (GST-442)', () => {
mergeMain(f, { 'lib/rows.js': src({ 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' }) });
const head = f.git('rev-parse', 'HEAD').stdout.trim();
const view = path.join(f.root, 'view.json');
fs.writeFileSync(view, JSON.stringify({ body: placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any), headRefOid: head }));
fs.writeFileSync(view, JSON.stringify({ body: placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any), headRefOid: head }));
f.gh(`case "$1 $2" in "pr list") echo 9 ;; "pr view") cat '${view}' ;; *) exit 1 ;; esac`);
const r = f.run(PREFLIGHT, ['--base', 'main']);
expect(lineOf(r.stdout, 'CARRY')).toBe('CARRY: refused (RECEIPT_CARRY_SCOPED_REVIEW)');
@@ -616,7 +616,7 @@ describe('preflight carry route for an adjacent base edit (GST-442)', () => {
mergeMain(f);
const head = f.git('rev-parse', 'HEAD').stdout.trim();
const view = path.join(f.root, 'view.json');
fs.writeFileSync(view, JSON.stringify({ body: placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any), headRefOid: head }));
fs.writeFileSync(view, JSON.stringify({ body: placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge' } as any), headRefOid: head }));
f.gh(`case "$1 $2" in "pr list") echo 9 ;; "pr view") cat '${view}' ;; *) exit 1 ;; esac`);
const r = f.run(PREFLIGHT, ['--base', 'main']);
expect(lineOf(r.stdout, 'CARRY')).toMatch(/^CARRY: would carry/);
@@ -634,7 +634,7 @@ describe('preflight carry route for an adjacent base edit (GST-442)', () => {
mergeMain(f, { 'lib/rows.js': src({ 5: 'exports.v5 = "five";', 6: 'exports.v6 = 600;' }) });
const head = f.git('rev-parse', 'HEAD').stdout.trim();
const view = path.join(f.root, 'view.json');
fs.writeFileSync(view, JSON.stringify({ body: placeReceiptFirst('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', gstack_version: '1.0.0' } as any), headRefOid: head }));
fs.writeFileSync(view, JSON.stringify({ body: placeReceipt('## Summary\n\nProse.\n', { schema_version: 1, pr: 9, head: reviewed, base: 'main', queue_mode: 'stamp-at-merge', gstack_version: '1.0.0' } as any), headRefOid: head }));
f.gh(`case "$1 $2" in "pr list") echo 9 ;; "pr view") cat '${view}' ;; *) exit 1 ;; esac`);
const r = f.run(path.join(BIN, 'gstack-ship-receipt'), ['carry', '--pr', '9', '--base', 'main', '--dry-run']);
expect([r.status, lineOf(r.stdout, 'CARRY')]).toEqual([EXIT.refused, 'CARRY: refused (RECEIPT_CARRY_REFUSED)']);
+1 -1
View File
@@ -175,7 +175,7 @@ test('Step 18 resolves open PR state before preparing the title file Step 19 pos
expectTokens(lookup, ['glab mr list --source-branch <branch-name> --output json'], 'ship Step 18');
const title = compact(between(prTemplate, '### Prepare the title (Step 18)', '## Step 19:'));
expectOrdered(title, ['{{FREE_TEXT_FILE:TITLE_FILE=pr-title}}', 'gstack-pr-title-rewrite.sh <new-version> --stdin > "$TITLE_FILE"'], 'ship Step 18 title');
expectTokens(title, ['`v<NEW_VERSION> <type>: <summary>`', '`v$NEW_VERSION `', "grep -Eq '^v<new-version>( |$)' \"$TITLE_FILE\""], 'ship Step 18 title');
expectTokens(title, ['`v<NEW_VERSION> <plain change>`', '`v$NEW_VERSION `', "grep -Eq '^v<new-version>( |$)' \"$TITLE_FILE\""], 'ship Step 18 title');
expectAbsent(compact(entryTemplate + prTemplate), ['"<current title>"', 'NEW_TITLE'], 'ship Steps 18-19');
expectTokens(prTemplate, ['--title-file "$TITLE_FILE"', 'exit 1', '**3**'], 'ship pr-body');
const generated = readTemplate('ship/sections/pr-body.md');
@@ -0,0 +1,4 @@
{
"bytes": 2758,
"why": "/ship writes plain titles, a plain PR opening and a closing Agent notes section, and checks titles before posting"
}
+1
View File
@@ -38,6 +38,7 @@ const HOOK_FILES = [
'lib/result-codes-autoplan.ts',
'lib/result-codes-browse.ts',
'lib/result-codes-clean.ts',
'lib/result-codes-plain.ts',
];
const SLUG = 'stop-hook-slug-test';
const BUDGET_MS = 2000;