rungate 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
@@ -0,0 +1,233 @@
1
+ /**
2
+ * One fact, one decider: "is this a TypeScript project, and what type-checks it?" (#87)
3
+ *
4
+ * Four places answered the first question and three answered the second, and
5
+ * they disagreed — which is the whole of #87:
6
+ *
7
+ * | Site | Asked | Answered |
8
+ * |---|---|---|
9
+ * | `createTsconfig` | is there TypeScript source? | skip the tsconfig if not |
10
+ * | `createCiWorkflows` | is there a tsconfig? | skip the CI step if not |
11
+ * | `generateAgentsMd` | is there a tsconfig? | skip the doc row if not |
12
+ * | `scanProject` → `dev.typeCheck` | nothing | `bunx tsc --noEmit`, always |
13
+ * | `runTsconfigValidation` (TSC-1) | nothing | the tsconfig MUST exist |
14
+ *
15
+ * So a consumer with no TypeScript source got no tsconfig from the generator
16
+ * that decided it did not need one, no CI step and no doc row from the two
17
+ * that agreed — and then a conformity suite that hard-failed TSC-1 over the
18
+ * absent file, plus a `dev.typeCheck` of `bunx tsc --noEmit` written into its
19
+ * config, which `gates/gate-executor.ts` runs. Without a tsconfig tsc prints
20
+ * 147 lines of help text and exits 1, so that is #65/#76 reintroduced in the
21
+ * one place #65/#76 never looked.
22
+ *
23
+ * THE DECISION #87 ASKED FOR
24
+ *
25
+ * > Either consumers are allowed to be non-TypeScript projects (then TSC-1
26
+ * > must become conditional or a warning), or they are not (then the scaffold
27
+ * > should generate a tsconfig and TSC-1 is right). Pick one; today both are
28
+ * > asserted.
29
+ *
30
+ * Consumers ARE allowed to be non-TypeScript projects. Two generators had
31
+ * already voted that way and shipped, and writing a tsconfig into a project
32
+ * with no TypeScript in it produces `include: []` — tsc error TS18003, a type
33
+ * check that reads as broken rather than as "nothing to check". So TSC-1
34
+ * becomes conditional on the predicate `createTsconfig` already used, and the
35
+ * conditional arm RECORDS why it did not measure instead of passing quietly:
36
+ * `.claude/rules/config-access.md` calls the silent form out by name, and a
37
+ * check that cannot fail is indistinguishable from a check that is satisfied.
38
+ *
39
+ * WHY THE COMMAND LIVES HERE TOO
40
+ *
41
+ * `typecheckDecision` exists because the three command sites were a worse
42
+ * version of the same problem: they agreed on the question and still produced
43
+ * different answers, and one of their branches was unreachable. `files:` in
44
+ * package.json ships neither `scripts/typecheck.ts` nor `tsconfig.json`, so no
45
+ * consumer could ever land on the ratchet branch — it was dead code that read
46
+ * as a supported configuration. A consumer's own `package.json` `scripts.
47
+ * typecheck` is checked first, which is the escape hatch that was missing: the
48
+ * ratchet is reachable by any project that writes one, and a project with a
49
+ * tsconfig full of pre-existing errors is no longer handed a CI step that can
50
+ * only be red over a generated file it is told not to edit.
51
+ */
52
+
53
+ import { existsSync, readdirSync, readFileSync } from "fs";
54
+ import { join } from "path";
55
+
56
+ /**
57
+ * Where a consumer keeps hand-written TypeScript.
58
+ *
59
+ * The scanner's source directories plus `scripts/` — a consumer keeps real
60
+ * TypeScript there and nothing else would check it.
61
+ *
62
+ * `test/` is deliberately absent. The conformity test rungate generates into
63
+ * every consumer imports `bun:test` and `rungate/lib/conformity`, and neither
64
+ * resolves for tsc without `@types/bun` and an installed `rungate` — so
65
+ * including the test tree would hand a freshly scaffolded project a type check
66
+ * that reports 4 errors it did not cause and cannot fix. That is the #65/#76
67
+ * defect again in the other direction: a documented command whose result says
68
+ * nothing about the project's code.
69
+ */
70
+ export const TS_SOURCE_DIRS = ["src", "lib", "scripts", "gates", "hooks", "workflows"] as const;
71
+
72
+ /** True when `dir` holds at least one hand-written .ts/.tsx file. */
73
+ export function containsTypeScript(dir: string): boolean {
74
+ let stack = [dir];
75
+ while (stack.length > 0) {
76
+ const current = stack.pop()!;
77
+ let entries;
78
+ try {
79
+ entries = readdirSync(current, { withFileTypes: true });
80
+ } catch {
81
+ continue;
82
+ }
83
+ for (const entry of entries) {
84
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
85
+ if (entry.isDirectory()) {
86
+ stack.push(join(current, entry.name));
87
+ } else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
88
+ return true;
89
+ }
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ /**
96
+ * The source directories that actually hold TypeScript, in TS_SOURCE_DIRS order.
97
+ *
98
+ * The include list and the "is this a TypeScript project" test are the same
99
+ * question, answered once. Deriving them separately is how you get a tsconfig
100
+ * whose include matches no files — tsc error TS18003, which reads as a broken
101
+ * type check rather than as "nothing to check".
102
+ */
103
+ export function typeScriptSourceDirs(root: string): string[] {
104
+ return TS_SOURCE_DIRS.filter(dir => containsTypeScript(join(root, dir)));
105
+ }
106
+
107
+ /** True when the project has hand-written TypeScript anywhere a type check would look. */
108
+ export function isTypeScriptProject(root: string): boolean {
109
+ return typeScriptSourceDirs(root).length > 0;
110
+ }
111
+
112
+ export interface TsconfigVerdict {
113
+ /** Does this project need a tsconfig.json at all? */
114
+ applicable: boolean;
115
+ /** Is one there? */
116
+ present: boolean;
117
+ /** The source directories that made it applicable — empty when it is not. */
118
+ dirs: string[];
119
+ /** Why, in the words the finding and the failure message both use. */
120
+ reason: string;
121
+ }
122
+
123
+ /**
124
+ * Whether TSC-1 has anything to assert, and why.
125
+ *
126
+ * Never returns a bare boolean: a check that skips has to be able to say what
127
+ * it skipped over, or its silence is indistinguishable from a pass.
128
+ */
129
+ export function tsconfigVerdict(root: string): TsconfigVerdict {
130
+ const dirs = typeScriptSourceDirs(root);
131
+ const present = existsSync(join(root, "tsconfig.json"));
132
+ const applicable = dirs.length > 0;
133
+
134
+ if (!applicable) {
135
+ return {
136
+ applicable,
137
+ present,
138
+ dirs,
139
+ reason:
140
+ `NOT APPLICABLE: no hand-written TypeScript in ${TS_SOURCE_DIRS.join("/, ")}/, ` +
141
+ `so no tsconfig.json is required and the scaffold did not write one (#87)`,
142
+ };
143
+ }
144
+ if (!present) {
145
+ return {
146
+ applicable,
147
+ present,
148
+ dirs,
149
+ reason:
150
+ `TypeScript source in ${dirs.join("/, ")}/ and no tsconfig.json — ` +
151
+ `\`bunx tsc --noEmit\` would print its help text and exit 1 (#65/#76). ` +
152
+ `Run \`bunx rungate scaffold .\` to create one`,
153
+ };
154
+ }
155
+ return {
156
+ applicable,
157
+ present,
158
+ dirs,
159
+ reason: `tsconfig.json is present and ${dirs.length} source director${dirs.length === 1 ? "y" : "ies"} need it`,
160
+ };
161
+ }
162
+
163
+ /** Where the type-check command came from. `none` means there is nothing to run. */
164
+ export type TypecheckSource = "package-script" | "ratchet" | "tsc" | "none";
165
+
166
+ export interface TypecheckDecision {
167
+ /** The shell command, or null when the project has nothing to type-check. */
168
+ command: string | null;
169
+ source: TypecheckSource;
170
+ /** Why this command and not another. Carried into the generated comment. */
171
+ reason: string;
172
+ }
173
+
174
+ /**
175
+ * The one type-check command for a project — CI step, AGENTS.md row and
176
+ * `dev.typeCheck` all read this.
177
+ *
178
+ * Order matters and each step earns its place:
179
+ *
180
+ * 1. **No tsconfig → no command.** Not a default, an absence. `bunx tsc
181
+ * --noEmit` without one prints help and exits 1, and three of the four
182
+ * former call sites had already learned that separately.
183
+ * 2. **The project's own `scripts.typecheck`.** A project that has thought
184
+ * about its type check has said so in package.json; overriding that with a
185
+ * guess is the thing `scanProject` was doing wrong in the other direction.
186
+ * This is also what makes the ratchet form reachable at all — `files:`
187
+ * ships neither `scripts/typecheck.ts` nor `tsconfig.json`, so a consumer
188
+ * gets a ratchet only by writing one, and then only this branch sees it.
189
+ * 3. **`scripts/typecheck.ts` on disk.** How the harness itself and anyone who
190
+ * copied its ratchet is served when package.json does not mention it.
191
+ * 4. **Plain `bunx tsc --noEmit`.** Honest for a project with a clean tree.
192
+ */
193
+ export function typecheckDecision(root: string): TypecheckDecision {
194
+ if (!existsSync(join(root, "tsconfig.json"))) {
195
+ return {
196
+ command: null,
197
+ source: "none",
198
+ reason: "no tsconfig.json — tsc would print its help text and check nothing (#65/#76)",
199
+ };
200
+ }
201
+
202
+ const pkgPath = join(root, "package.json");
203
+ if (existsSync(pkgPath)) {
204
+ try {
205
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
206
+ if (typeof pkg?.scripts?.typecheck === "string" && pkg.scripts.typecheck.trim() !== "") {
207
+ return {
208
+ command: "bun run typecheck",
209
+ source: "package-script",
210
+ reason: "the project declares its own `typecheck` script, which beats anything inferred",
211
+ };
212
+ }
213
+ } catch {
214
+ // An unreadable package.json is not a reason to lose the type check. The
215
+ // two branches below need no package.json at all, and `createTsconfig`'s
216
+ // neighbours already shrug at this rather than killing the scaffold (#380).
217
+ }
218
+ }
219
+
220
+ if (existsSync(join(root, "scripts", "typecheck.ts"))) {
221
+ return {
222
+ command: "bun scripts/typecheck.ts",
223
+ source: "ratchet",
224
+ reason: "the project has a ratchet script, which fails in both directions",
225
+ };
226
+ }
227
+
228
+ return {
229
+ command: "bunx tsc --noEmit",
230
+ source: "tsc",
231
+ reason: "a tsconfig.json exists and the project declares no type-check script of its own",
232
+ };
233
+ }
@@ -44,12 +44,16 @@ export function checkGovernsAlignment(specsDir: string, actions: string[]): void
44
44
  /**
45
45
  * Add or complete frontmatter on spec files.
46
46
  * Injects doc-type, testable, governs fields if missing.
47
- * When opts.fix is false, reports gaps without modifying files.
47
+ *
48
+ * Always writes. The `opts.fix` parameter and its gap-reporting branch were
49
+ * removed in #398: audit no longer predicts what this would do, it runs this
50
+ * against a throwaway clone, so a second non-writing code path has nothing
51
+ * left to serve. Unreachable from the only caller for its whole life, and an
52
+ * unreachable branch reporting gaps is a report nothing can contradict.
48
53
  */
49
- export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?: { fix?: boolean }): void {
54
+ export function addFrontmatterToSpecs(specsDir: string, actions: string[]): void {
50
55
  if (!existsSync(specsDir)) return;
51
56
 
52
- const fixMode = opts?.fix ?? true;
53
57
  const today = new Date().toISOString().split("T")[0];
54
58
 
55
59
  for (const file of readdirSync(specsDir).filter(f => f.endsWith(".md"))) {
@@ -57,13 +61,9 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?
57
61
  const content = readFileSync(filePath, "utf-8");
58
62
 
59
63
  if (!content.startsWith("---\n")) {
60
- if (fixMode) {
61
- const frontmatter = `---\ndoc-type: spec\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\ngoverns: TODO — describe what this spec governs\ntestable: false\n---\n\n`;
62
- writeFileSync(filePath, frontmatter + content);
63
- actions.push(`UPDATED: specs/${file} (added frontmatter)`);
64
- } else {
65
- actions.push(`GAP: specs/${file} missing frontmatter — run with --fix to add`);
66
- }
64
+ const frontmatter = `---\ndoc-type: spec\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\ngoverns: TODO — describe what this spec governs\ntestable: false\n---\n\n`;
65
+ writeFileSync(filePath, frontmatter + content);
66
+ actions.push(`UPDATED: specs/${file} (added frontmatter)`);
67
67
  } else {
68
68
  // Validate existing frontmatter has required fields
69
69
  const fmEnd = content.indexOf("\n---", 4);
@@ -74,13 +74,9 @@ export function addFrontmatterToSpecs(specsDir: string, actions: string[], opts?
74
74
  if (!fm.includes("created:")) missing.push(`created: ${today}`);
75
75
  if (!fm.includes("governs:")) missing.push(`governs: TODO`);
76
76
  if (missing.length > 0) {
77
- if (fixMode) {
78
- const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
79
- writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
80
- actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
81
- } else {
82
- actions.push(`GAP: specs/${file} missing fields: ${missing.map(m => m.split(":")[0]).join(", ")} — run with --fix to add`);
83
- }
77
+ const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
78
+ writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
79
+ actions.push(`UPDATED: specs/${file} (added missing frontmatter fields: ${missing.map(m => m.split(":")[0]).join(", ")})`);
84
80
  }
85
81
  // SC-269: WARN for specs with missing or TODO governs
86
82
  const governsMatch = fm.match(/governs:\s*(.+)/);
@@ -130,12 +126,13 @@ export function detectUnconvertedSpecs(specsDir: string, actions: string[]): voi
130
126
  /**
131
127
  * Add or complete frontmatter on ADR files.
132
128
  * Injects doc-type, created fields if missing.
133
- * When opts.fix is false, reports gaps without modifying files.
129
+ *
130
+ * Always writes — see `addFrontmatterToSpecs` for why the non-fix branch is
131
+ * gone (#398).
134
132
  */
135
- export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: { fix?: boolean }): void {
133
+ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
136
134
  if (!existsSync(adrDir)) return;
137
135
 
138
- const fixMode = opts?.fix ?? true;
139
136
  const today = new Date().toISOString().split("T")[0];
140
137
 
141
138
  for (const file of readdirSync(adrDir).filter(f => f.endsWith(".md"))) {
@@ -143,13 +140,9 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: {
143
140
  const content = readFileSync(filePath, "utf-8");
144
141
 
145
142
  if (!content.startsWith("---\n")) {
146
- if (fixMode) {
147
- const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
148
- writeFileSync(filePath, frontmatter + content);
149
- actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
150
- } else {
151
- actions.push(`GAP: docs/adr/${file} missing frontmatter — run with --fix to add`);
152
- }
143
+ const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
144
+ writeFileSync(filePath, frontmatter + content);
145
+ actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
153
146
  } else {
154
147
  const fmEnd = content.indexOf("\n---", 4);
155
148
  if (fmEnd === -1) continue;
@@ -158,13 +151,9 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[], opts?: {
158
151
  if (!fm.includes("doc-type:")) missing.push(`doc-type: adr`);
159
152
  if (!fm.includes("created:")) missing.push(`created: ${today}`);
160
153
  if (missing.length > 0) {
161
- if (fixMode) {
162
- const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
163
- writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
164
- actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
165
- } else {
166
- actions.push(`GAP: docs/adr/${file} missing fields: ${missing.map(m => m.split(":")[0]).join(", ")} — run with --fix to add`);
167
- }
154
+ const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
155
+ writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
156
+ actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
168
157
  }
169
158
  }
170
159
  }
@@ -83,7 +83,11 @@ export type PushOutcome =
83
83
  /** The push ran and exited non-zero. */
84
84
  | { kind: "rejected"; detail: string }
85
85
  /** The push exited zero and the remote does not carry HEAD. */
86
- | { kind: "unconfirmed"; sha: string; remoteSha: string | null; detail: string };
86
+ | { kind: "unconfirmed"; sha: string; remoteSha: string | null; detail: string }
87
+ /** The upstream names a ref other than the branch's own. Nothing was pushed. */
88
+ | { kind: "ref-mismatch"; branch: string; remoteRef: string; detail: string }
89
+ /** The caller expected a different repository than the tree's origin. */
90
+ | { kind: "repo-mismatch"; expected: string; actual: string | null; detail: string };
87
91
 
88
92
  /**
89
93
  * The outcomes that mean a commit this run reported on may not be on the
@@ -96,12 +100,122 @@ export const OUTCOMES_LEAVING_WORK_LOCAL: ReadonlySet<PushOutcome["kind"]> = new
96
100
  "not-attempted",
97
101
  "rejected",
98
102
  "unconfirmed",
103
+ "ref-mismatch",
104
+ "repo-mismatch",
99
105
  ]);
100
106
 
101
107
  export function leftWorkLocal(outcome: PushOutcome): boolean {
102
108
  return OUTCOMES_LEAVING_WORK_LOCAL.has(outcome.kind);
103
109
  }
104
110
 
111
+ /**
112
+ * The `owner/name` a git remote URL points at, or `null` if it names none.
113
+ *
114
+ * Returns `null` rather than a best guess for anything it cannot parse —
115
+ * including the filesystem paths every fixture in the suite uses as its
116
+ * origin. `repoMatches` turns `null` into "does not match", so an
117
+ * unrecognised remote refuses a push instead of permitting one, which is the
118
+ * direction this is allowed to be wrong in (#430).
119
+ */
120
+ export function parseRemoteSlug(url: string): string | null {
121
+ const trimmed = url.trim();
122
+ if (!trimmed) return null;
123
+ // scp-style (`git@host:owner/name.git`) and URL-style, with any userinfo —
124
+ // which is where a token lives on an HTTPS remote — discarded.
125
+ const m = trimmed.match(/^(?:[a-z+]+:\/\/)?(?:[^@/]*@)?[^/:]+[:/](.+?)(?:\.git)?\/?$/i);
126
+ const path = m?.[1];
127
+ if (!path) return null;
128
+ const parts = path.split("/").filter(Boolean);
129
+ if (parts.length !== 2) return null;
130
+ return `${parts[0]}/${parts[1]}`.toLowerCase();
131
+ }
132
+
133
+ /** Whether a remote URL names the given `owner/name`. Unparseable matches nothing. */
134
+ export function repoMatches(url: string, slug: string): boolean {
135
+ const parsed = parseRemoteSlug(url);
136
+ return parsed !== null && parsed === slug.trim().toLowerCase();
137
+ }
138
+
139
+ /**
140
+ * The `owner/name` of a tree's `origin`, or `null` when it cannot be read.
141
+ *
142
+ * Reads the CONFIGURED url. `originPushUrl` reads the effective one, and
143
+ * `originIdentity` requires them to agree — see there for why one alone is
144
+ * not enough.
145
+ */
146
+ export function originSlug(cwd: string, env: NodeJS.ProcessEnv = process.env): string | null {
147
+ const r = runner(cwd, env)(["config", "--get", "remote.origin.url"], 5000);
148
+ return r.ok ? parseRemoteSlug(r.output) : null;
149
+ }
150
+
151
+ /** The url a push to `origin` would actually use, rewrites applied. */
152
+ export function originPushUrl(cwd: string, env: NodeJS.ProcessEnv = process.env): string | null {
153
+ const r = runner(cwd, env)(["remote", "get-url", "--push", "origin"], 5000);
154
+ return r.ok && r.output.trim() !== "" ? r.output.trim() : null;
155
+ }
156
+
157
+ /**
158
+ * Whether this tree is `expected`, judged on the url the push will use.
159
+ *
160
+ * ## Why two urls and not one
161
+ *
162
+ * The first version of this read only `config --get remote.origin.url`, on
163
+ * the reasoning that `url.<base>.insteadOf` rewrites are a local transport
164
+ * alias — a mirror, a proxy, a cache — and not a statement about which
165
+ * project you are shipping. That reasoning is fine and the conclusion was
166
+ * wrong, because it made the authorisation check read a different value than
167
+ * the action uses: `git push` resolves rewrites, so a rewrite pointing
168
+ * `https://github.com/owner/name` at some other repository would satisfy
169
+ * this check and then write that other repository. A guard that approves one
170
+ * destination and permits a push to another is not a guard.
171
+ *
172
+ * So both are read and both must agree. A rewrite in play is a refusal, not
173
+ * an approval — the mirror user loses an auto-push and runs `git push`
174
+ * themselves, which is the cost this file is allowed to impose
175
+ * (`leftWorkLocal` already reports the work may be local).
176
+ *
177
+ * ## What this does NOT check
178
+ *
179
+ * The host. `issueRepo` is `owner/name` and carries no host, so there is
180
+ * nothing here to compare one against: `https://example.invalid/owner/name`
181
+ * and `https://github.com/owner/name` are the same slug to this function.
182
+ * That is a real limit and is stated rather than papered over. It is not the
183
+ * only thing standing between a run and the wrong forge — the GitHub client
184
+ * in `lib/github.ts` has its own base url and credentials, and a push to an
185
+ * unexpected host needs credentials for that host. Hardcoding `github.com`
186
+ * here would bind the harness to one forge for a check that is about repo
187
+ * identity, which is the wrong place to make that decision.
188
+ */
189
+ export function originIdentity(
190
+ cwd: string,
191
+ expected: string,
192
+ env: NodeJS.ProcessEnv = process.env,
193
+ ): { ok: true; slug: string } | { ok: false; detail: string } {
194
+ const configured = originSlug(cwd, env);
195
+ if (configured === null) {
196
+ return { ok: false, detail: "this tree's origin url is unreadable or names no owner/name" };
197
+ }
198
+ const want = expected.trim().toLowerCase();
199
+ if (configured !== want) {
200
+ return { ok: false, detail: `this tree's origin is ${configured}` };
201
+ }
202
+
203
+ const pushUrl = originPushUrl(cwd, env);
204
+ if (pushUrl === null) {
205
+ return { ok: false, detail: `this tree's origin is ${configured} but its push url is unreadable` };
206
+ }
207
+ const pushSlug = parseRemoteSlug(pushUrl);
208
+ if (pushSlug !== configured) {
209
+ return {
210
+ ok: false,
211
+ detail: `this tree's origin is configured as ${configured} but a push would go to ` +
212
+ `${redactSecrets(pushUrl)} — a \`url.<base>.insteadOf\` rewrite is in play, so the ` +
213
+ `repository this check approved is not the one the push would write`,
214
+ };
215
+ }
216
+ return { ok: true, slug: configured };
217
+ }
218
+
105
219
  /** The sha `ls-remote` reports for a ref, or null if its output names none. */
106
220
  export function parseLsRemoteSha(output: string, ref: string): string | null {
107
221
  for (const line of output.split("\n")) {
@@ -159,6 +273,33 @@ export function classifyPush(raw: PushReadings): PushOutcome {
159
273
  const remoteRef = r.remoteRef.output.trim();
160
274
  const upstream = `${remoteName} ${remoteRef}`;
161
275
 
276
+ // #429 — the push below is `HEAD:${remoteRef}`, and `remoteRef` is whatever
277
+ // `branch.<b>.merge` says. `git checkout -b <name> origin/main`, the
278
+ // ordinary way to start work here, sets that to `refs/heads/main` — so an
279
+ // unattended auto-push on a feature branch wrote `main` and reported a
280
+ // verified success, which it was, to the wrong ref. Four `wip:` commits
281
+ // reached origin/main that way on 2026-10-15 from a session that never ran
282
+ // `git push`.
283
+ //
284
+ // Refusing rather than rewriting the target: a branch whose upstream names
285
+ // a different ref may well be deliberate — this repo has several — and
286
+ // guessing which the operator meant is the kind of repair
287
+ // `.claude/rules/checks-must-be-able-to-fail.md` warns about. This is
288
+ // bookkeeping, not a gate, so the refusal costs a manual `git push` and
289
+ // `leftWorkLocal` already says the work may be local.
290
+ if (remoteRef !== `refs/heads/${branch}`) {
291
+ return {
292
+ kind: "ref-mismatch",
293
+ branch,
294
+ remoteRef,
295
+ detail: `branch ${branch} is configured to track ${upstream}, so an auto-push would write ` +
296
+ `${remoteRef} from a branch that is not it. Nothing was pushed. This is usually a branch ` +
297
+ `created with \`git checkout -b ${branch} origin/main\`, which sets the upstream to main ` +
298
+ `rather than to a ref of its own name (#429). Push explicitly with ` +
299
+ `\`git push -u origin ${branch}\` if that is what you meant.`,
300
+ };
301
+ }
302
+
162
303
  if (!r.ahead.ok) {
163
304
  return {
164
305
  kind: "unmeasured",
@@ -318,11 +459,47 @@ function runner(cwd: string, env: NodeJS.ProcessEnv) {
318
459
  */
319
460
  export function verifiedPush(
320
461
  cwd: string,
321
- opts: { env?: NodeJS.ProcessEnv } = {},
462
+ opts: { env?: NodeJS.ProcessEnv; expectRepo?: string } = {},
322
463
  ): PushOutcome {
323
464
  const env = opts.env ?? process.env;
324
465
  const git = runner(cwd, env);
325
466
 
467
+ // #430 — the caller says which repository it believes it is shipping, and
468
+ // that belief is compared against the tree rather than assumed to match it.
469
+ //
470
+ // `gates/orchestrator.ts` pushes `process.cwd()` and guards on
471
+ // `issueRepo && issue > 0`. `test/contract.test.ts` runs the ship gate with
472
+ // `issueRepo: "test/repo"` and `issue: 9998` — both truthy — from inside
473
+ // the real rungate checkout, so running the test suite pushed to origin.
474
+ // The cwd choice is right and stays; what was missing is this comparison.
475
+ //
476
+ // Checked FIRST, before any other reading, because "this is not the repo
477
+ // you meant" invalidates everything downstream — an ahead-count against the
478
+ // wrong tree's upstream is not a fact worth reporting.
479
+ //
480
+ // The opt-in is `!== undefined` and nothing more. The first draft also
481
+ // required `.trim() !== ""`, which made a blank `expectRepo` SKIP the
482
+ // check — malformed input disabling the guard, which is the fail-open
483
+ // shape this repo keeps finding (`.claude/rules/checks-must-be-able-to-
484
+ // fail.md`). A caller that passed `""` because its config was empty would
485
+ // have got the old unconditional push back, silently. Asking the question
486
+ // is the caller's decision; once asked, an unanswerable version of it is a
487
+ // refusal.
488
+ if (opts.expectRepo !== undefined) {
489
+ const identity = originIdentity(cwd, opts.expectRepo, env);
490
+ if (!identity.ok) {
491
+ return {
492
+ kind: "repo-mismatch",
493
+ expected: opts.expectRepo,
494
+ actual: originSlug(cwd, env),
495
+ detail: `the caller is shipping ${JSON.stringify(opts.expectRepo)} and ${identity.detail}. ` +
496
+ `Nothing was pushed. A run whose issue repository and working tree disagree is either a ` +
497
+ `fixture pointed at a real checkout or a real run in the wrong directory, and both are ` +
498
+ `reasons not to write a remote (#430).`,
499
+ };
500
+ }
501
+ }
502
+
326
503
  const localSha = git(["rev-parse", "HEAD"], 5000);
327
504
  const branch = git(["symbolic-ref", "--short", "HEAD"], 5000);
328
505
  const b = branch.output.trim();
@@ -4,6 +4,56 @@ const SHELL_METACHARACTERS = /[;&|$`\n\r"'\\(){}[\]<>!~*?#]/;
4
4
  const PATH_TRAVERSAL = /\.\.($|[/\\])/;
5
5
  const NULL_BYTE = /\x00/;
6
6
 
7
+ /**
8
+ * Why a path may not be contributed by an agent, or `null` if it may.
9
+ *
10
+ * ONE table, ONE decider (#400). Before this there were two: a regex set here,
11
+ * checked at staging time, and a segment walk in `workflows/ship.js`'s
12
+ * `escapesWorktree`, checked at collection time. They agreed on traversal and
13
+ * on nothing else, so the audit accepted a reported path carrying a shell
14
+ * metacharacter, a null byte or 500+ characters, declared the run clean, and
15
+ * staging refused it two phases later with a different message.
16
+ *
17
+ * `boundary` separates the two reasons a path can be refused, because they are
18
+ * different things to tell an operator:
19
+ *
20
+ * true — the path does not name a location inside the worktree at all.
21
+ * false — it does, and still cannot be handled safely.
22
+ *
23
+ * "not inside its own worktree" is a wrong sentence to print about
24
+ * `lib/a;rm.ts`, and an operator who reads it goes looking for a path that is
25
+ * not there.
26
+ *
27
+ * The order is the order the reasons are reported in. Absoluteness first
28
+ * because it is the least ambiguous, then the segment walk, then the regexes.
29
+ *
30
+ * The two traversal rules are deliberately both present and deliberately
31
+ * separate. `p.split("/").includes("..")` is the real boundary question; the
32
+ * regex also matches a segment merely ENDING in `..` (`lib/foo..`), which is a
33
+ * legal filename that staging has always refused. Folding it into the boundary
34
+ * rule would label a legal file an escape; dropping it would make the audit
35
+ * permit something staging rejects, which is the whole defect.
36
+ */
37
+ const CONTRIBUTABLE_PATH_RULES: ReadonlyArray<
38
+ readonly [rule: string, boundary: boolean, fails: (p: string) => boolean]
39
+ > = [
40
+ ["an absolute path", true, (p) => p.startsWith("/")],
41
+ ["a `..` segment", true, (p) => p.split("/").includes("..")],
42
+ ["a segment ending in `..`", false, (p) => PATH_TRAVERSAL.test(p)],
43
+ ["a shell metacharacter", false, (p) => SHELL_METACHARACTERS.test(p)],
44
+ ["a null byte", false, (p) => NULL_BYTE.test(p)],
45
+ ["over 500 characters", false, (p) => p.length > 500],
46
+ ];
47
+
48
+ export function pathRefusal(
49
+ p: string,
50
+ ): { rule: string; boundary: boolean } | null {
51
+ for (const [rule, boundary, fails] of CONTRIBUTABLE_PATH_RULES) {
52
+ if (fails(p)) return { rule, boundary };
53
+ }
54
+ return null;
55
+ }
56
+
7
57
  export function buildSafeGitAdd(filesChanged: string[]): string {
8
58
  const validated = validateFilePaths(filesChanged);
9
59
  if (validated.rejected.length > 0) {
@@ -21,13 +71,7 @@ export function validateFilePaths(
21
71
  const valid: string[] = [];
22
72
  const rejected: string[] = [];
23
73
  for (const p of paths) {
24
- if (
25
- SHELL_METACHARACTERS.test(p) ||
26
- PATH_TRAVERSAL.test(p) ||
27
- NULL_BYTE.test(p) ||
28
- p.startsWith("/") ||
29
- p.length > 500
30
- ) {
74
+ if (pathRefusal(p)) {
31
75
  rejected.push(p);
32
76
  } else {
33
77
  valid.push(p);