rungate 0.2.1 → 0.4.0

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 (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,535 @@
1
+ /**
2
+ * #213 — the ship gate's auto-push, with every failure mode named.
3
+ *
4
+ * The code this replaces was five statements wrapped in `try { … } catch {}`.
5
+ * It ran at the very end of `generateShipEvidence`, which `runGate` calls only
6
+ * once the ship gate has already decided PASS — so nothing downstream looks at
7
+ * it, and four distinct ways for it to leave the work on the local machine all
8
+ * produced the same observable outcome as success:
9
+ *
10
+ * - the push was rejected (non-fast-forward, a pre-receive hook, no network);
11
+ * - the branch had no upstream, so `rev-list @{upstream}..HEAD` exited
12
+ * non-zero and the catch swallowed it before the push was even attempted;
13
+ * - `rev-list` printed something non-numeric, and `parseInt(x) > 0` is false
14
+ * for NaN, so the push was skipped as if there were nothing to push;
15
+ * - the push "succeeded" against a remote that did not end up carrying the
16
+ * commit, with `stdio: "pipe"` discarding whatever git said about it.
17
+ *
18
+ * This is not the same reading `unpushedViolations` in gates/workflow.test.ts
19
+ * takes for the `code-pushed` check, and it does not make that one redundant.
20
+ * That one runs during the gate and compares HEAD against `@{upstream}`, a
21
+ * LOCAL remote-tracking ref that only fetch and push update. This one runs
22
+ * after the gate's verdict and asks the remote directly, with `ls-remote`,
23
+ * because the question here is "did the commit leave the machine" and a local
24
+ * ref cannot answer it.
25
+ *
26
+ * ## Shape
27
+ *
28
+ * `classifyPush` is pure and total: it takes the readings and returns exactly
29
+ * one outcome. The git invocations live in `verifiedPush`, so every branch —
30
+ * including the ones a healthy repo never reaches — is reachable in a test
31
+ * without a network, and the interesting ones are additionally driven against
32
+ * a real temp repo with a real rejecting remote in test/gate-auto-push.test.ts.
33
+ *
34
+ * Nothing here throws. The caller is a post-verdict bookkeeping step and must
35
+ * not be able to crash a run that has already passed; the point of the change
36
+ * is that the failure is now RECORDED rather than that it is now fatal.
37
+ */
38
+
39
+ import { execFileSync } from "child_process";
40
+
41
+ /** One git invocation's result. `ok` is "exited zero", never "looks sensible". */
42
+ export interface Reading {
43
+ ok: boolean;
44
+ output: string;
45
+ }
46
+
47
+ /**
48
+ * Everything `classifyPush` is allowed to look at.
49
+ *
50
+ * `push` and `remote` are nullable because they describe steps that may never
51
+ * have been attempted — and "not attempted" has to be distinguishable from
52
+ * "attempted and came back empty", which is the distinction the empty catch
53
+ * destroyed.
54
+ */
55
+ export interface PushReadings {
56
+ /** `git symbolic-ref --short HEAD`, or a failed reading on a detached HEAD. */
57
+ branch: Reading;
58
+ /** `git config --get branch.<b>.remote` — absent means no upstream is configured. */
59
+ remoteName: Reading;
60
+ /** `git config --get branch.<b>.merge` — the full ref name on the remote. */
61
+ remoteRef: Reading;
62
+ /** `git rev-list --count @{upstream}..HEAD`. */
63
+ ahead: Reading;
64
+ /** `git rev-parse HEAD`. */
65
+ localSha: Reading;
66
+ /** The push itself, or null when it was never attempted. */
67
+ push: Reading | null;
68
+ /** `git ls-remote <remote> <ref>`, or null when it was never attempted. */
69
+ remote: Reading | null;
70
+ }
71
+
72
+ export type PushOutcome =
73
+ /** The remote was read back and carries the local HEAD. The only success. */
74
+ | { kind: "pushed"; sha: string; remote: string; detail: string }
75
+ /** The upstream already had HEAD. Nothing was pushed and nothing is missing. */
76
+ | { kind: "nothing-to-push"; sha: string; detail: string }
77
+ /** No upstream is configured, so nothing on this branch has been pushed. */
78
+ | { kind: "no-upstream"; detail: string }
79
+ /** A git read failed or printed something that is not a count. UNMEASURED. */
80
+ | { kind: "unmeasured"; detail: string }
81
+ /** Commits are ahead and no push was attempted. */
82
+ | { kind: "not-attempted"; sha: string; ahead: number; detail: string }
83
+ /** The push ran and exited non-zero. */
84
+ | { kind: "rejected"; detail: string }
85
+ /** The push exited zero and the remote does not carry HEAD. */
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 };
91
+
92
+ /**
93
+ * The outcomes that mean a commit this run reported on may not be on the
94
+ * remote. Exported so the caller states the rule once rather than spelling out
95
+ * a list of string literals that drifts the first time a kind is added.
96
+ */
97
+ export const OUTCOMES_LEAVING_WORK_LOCAL: ReadonlySet<PushOutcome["kind"]> = new Set([
98
+ "no-upstream",
99
+ "unmeasured",
100
+ "not-attempted",
101
+ "rejected",
102
+ "unconfirmed",
103
+ "ref-mismatch",
104
+ "repo-mismatch",
105
+ ]);
106
+
107
+ export function leftWorkLocal(outcome: PushOutcome): boolean {
108
+ return OUTCOMES_LEAVING_WORK_LOCAL.has(outcome.kind);
109
+ }
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
+
219
+ /** The sha `ls-remote` reports for a ref, or null if its output names none. */
220
+ export function parseLsRemoteSha(output: string, ref: string): string | null {
221
+ for (const line of output.split("\n")) {
222
+ const [sha, name] = line.split("\t");
223
+ if (!sha || !name) continue;
224
+ if (name.trim() === ref) return sha.trim();
225
+ }
226
+ return null;
227
+ }
228
+
229
+ /**
230
+ * Turn the readings into exactly one outcome.
231
+ *
232
+ * Order matters and is the opposite of the original's: the cheap reads that
233
+ * can invalidate everything downstream are checked first, so a missing
234
+ * upstream is reported as a missing upstream rather than surfacing later as a
235
+ * confusing push failure.
236
+ */
237
+ export function classifyPush(raw: PushReadings): PushOutcome {
238
+ // Every `detail` below interpolates git's own output, and every `detail`
239
+ // ends up in ship-evidence.json. Redacting once here rather than at each
240
+ // interpolation means a `detail` added later cannot forget to do it — and
241
+ // it holds for callers that build readings by hand, not only for the ones
242
+ // that came through `runner`.
243
+ const r = redactReadings(raw);
244
+
245
+ if (!r.localSha.ok || !/^[0-9a-f]{7,64}$/i.test(r.localSha.output.trim())) {
246
+ return {
247
+ kind: "unmeasured",
248
+ detail: `HEAD could not be read (${r.localSha.output.trim() || "no output"}), so there is ` +
249
+ `nothing to compare the remote against. UNMEASURED is not PASS.`,
250
+ };
251
+ }
252
+ const sha = r.localSha.output.trim();
253
+
254
+ if (!r.branch.ok || r.branch.output.trim() === "") {
255
+ return {
256
+ kind: "no-upstream",
257
+ detail: "HEAD is detached, so there is no branch to push and nothing on it has been " +
258
+ "pushed. This is the worst case for this check, not an exemption from it.",
259
+ };
260
+ }
261
+ const branch = r.branch.output.trim();
262
+
263
+ if (!r.remoteName.ok || r.remoteName.output.trim() === "" ||
264
+ !r.remoteRef.ok || r.remoteRef.output.trim() === "") {
265
+ return {
266
+ kind: "no-upstream",
267
+ detail: `branch ${branch} has no upstream configured, so nothing on it has been pushed. ` +
268
+ `A remediation re-push uses \`git push origin HEAD:<branch>\`, which does not set ` +
269
+ `upstream, so this is reachable on any run that needed one (#174).`,
270
+ };
271
+ }
272
+ const remoteName = r.remoteName.output.trim();
273
+ const remoteRef = r.remoteRef.output.trim();
274
+ const upstream = `${remoteName} ${remoteRef}`;
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
+
303
+ if (!r.ahead.ok) {
304
+ return {
305
+ kind: "unmeasured",
306
+ detail: `branch ${branch} tracks ${upstream} but the ahead-count could not be read ` +
307
+ `(${r.ahead.output.trim() || "no output"}). A git invocation that fails for an unknown ` +
308
+ `reason says nothing about whether work is unpushed.`,
309
+ };
310
+ }
311
+ // `parseInt("") === NaN` and `NaN > 0 === false`, so the original read an
312
+ // empty or garbled count as "nothing to push" and skipped the push entirely.
313
+ // An exact-digits test is the whole fix for that path.
314
+ const aheadRaw = r.ahead.output.trim();
315
+ if (!/^\d+$/.test(aheadRaw)) {
316
+ return {
317
+ kind: "unmeasured",
318
+ detail: `the ahead-count against ${upstream} is not a number (${JSON.stringify(aheadRaw)}). ` +
319
+ `The previous code ran this through parseInt and compared NaN > 0, which is false, so ` +
320
+ `an unreadable count was indistinguishable from nothing to push.`,
321
+ };
322
+ }
323
+
324
+ if (aheadRaw === "0") {
325
+ return {
326
+ kind: "nothing-to-push",
327
+ sha,
328
+ detail: `HEAD (${sha}) is not ahead of ${upstream}; nothing to push.`,
329
+ };
330
+ }
331
+
332
+ if (r.push === null) {
333
+ return {
334
+ kind: "not-attempted",
335
+ sha,
336
+ ahead: Number(aheadRaw),
337
+ detail: `${aheadRaw} commit(s) are ahead of ${upstream} and no push was attempted.`,
338
+ };
339
+ }
340
+
341
+ if (!r.push.ok) {
342
+ return {
343
+ kind: "rejected",
344
+ detail: `git push to ${upstream} was rejected: ${r.push.output.trim() || "no output"}`,
345
+ };
346
+ }
347
+
348
+ // The push exited zero. That is a claim by git, not a reading of the remote,
349
+ // and this issue exists because the two were treated as the same thing.
350
+ if (r.remote === null || !r.remote.ok) {
351
+ return {
352
+ kind: "unconfirmed",
353
+ sha,
354
+ remoteSha: null,
355
+ detail: `git push to ${upstream} exited 0 and the remote could not be read back ` +
356
+ `(${r.remote ? r.remote.output.trim() || "no output" : "not attempted"}). An unconfirmed ` +
357
+ `push is not a successful push.`,
358
+ };
359
+ }
360
+
361
+ const remoteSha = parseLsRemoteSha(r.remote.output, remoteRef);
362
+ if (remoteSha !== sha) {
363
+ return {
364
+ kind: "unconfirmed",
365
+ sha,
366
+ remoteSha,
367
+ detail: `git push to ${upstream} exited 0 but ${remoteName} ${remoteRef} is at ` +
368
+ `${remoteSha ?? "no such ref"}, not the local HEAD ${sha}. The commit this run reported ` +
369
+ `on is not on the remote.`,
370
+ };
371
+ }
372
+
373
+ return {
374
+ kind: "pushed",
375
+ sha,
376
+ remote: upstream,
377
+ detail: `pushed ${aheadRaw} commit(s); ${upstream} confirmed at ${sha}.`,
378
+ };
379
+ }
380
+
381
+ /**
382
+ * Strip credentials out of anything git says before it is recorded.
383
+ *
384
+ * The push outcome's `detail` is written into ship-evidence.json, which is a
385
+ * durable artefact, and printed. git's failure output quotes the remote URL —
386
+ * `fatal: Authentication failed for 'https://user:ghp_…@github.com/o/r.git'`
387
+ * — so a push that fails to authenticate against an HTTPS remote with an
388
+ * embedded token would write that token into the artefact. The remote name
389
+ * read from `branch.<b>.remote` can be a URL for the same reason.
390
+ *
391
+ * Two independent rules rather than one, because they fail differently: the
392
+ * userinfo rule catches the structured case and the token rule catches a bare
393
+ * token that reached the output some other way.
394
+ */
395
+ export function redactSecrets(text: string): string {
396
+ return text
397
+ // scheme://user:secret@host — the password is what matters, but the
398
+ // username is dropped too: a PAT is often supplied AS the username.
399
+ .replace(/([a-z][a-z0-9+.-]*:\/\/)[^/\s@]+@/gi, "$1<redacted>@")
400
+ // Bare GitHub token forms, in case one arrives outside a URL.
401
+ .replace(/\b(gh[pousr]|github_pat)_[A-Za-z0-9_]{10,}/g, "<redacted-token>");
402
+ }
403
+
404
+ const redactReading = (x: Reading | null): Reading | null =>
405
+ x === null ? null : { ok: x.ok, output: redactSecrets(x.output) };
406
+
407
+ function redactReadings(r: PushReadings): PushReadings {
408
+ return {
409
+ branch: redactReading(r.branch)!,
410
+ remoteName: redactReading(r.remoteName)!,
411
+ remoteRef: redactReading(r.remoteRef)!,
412
+ ahead: redactReading(r.ahead)!,
413
+ localSha: redactReading(r.localSha)!,
414
+ push: redactReading(r.push),
415
+ remote: redactReading(r.remote),
416
+ };
417
+ }
418
+
419
+ function runner(cwd: string, env: NodeJS.ProcessEnv) {
420
+ return (args: string[], timeout: number): Reading => {
421
+ try {
422
+ const output = execFileSync("git", args, {
423
+ cwd,
424
+ env,
425
+ encoding: "utf-8",
426
+ timeout,
427
+ stdio: ["ignore", "pipe", "pipe"],
428
+ });
429
+ return { ok: true, output: redactSecrets(output ?? "") };
430
+ } catch (e: any) {
431
+ // stderr is where git explains a rejection, and the original threw it
432
+ // away. Both streams are kept because which one carries the reason
433
+ // depends on the subcommand.
434
+ const parts = [e?.stdout, e?.stderr, e?.message].filter(Boolean).map(String);
435
+ return { ok: false, output: redactSecrets(parts.join("\n").trim()) };
436
+ }
437
+ };
438
+ }
439
+
440
+ /**
441
+ * Push, then read the remote back, then say what happened.
442
+ *
443
+ * `env` is injectable so a test can place a `git` shim ahead of the real one
444
+ * on PATH. That is how test/gate-auto-push.test.ts performs the mutation this
445
+ * change has to survive — a `git push` that exits 0 without doing anything —
446
+ * as a measurement on every run rather than a sentence in a PR body.
447
+ *
448
+ * It resolves the `git` binary, so it is worth saying what it is not: it is
449
+ * not a widening of trust. The only production caller passes `process.env`
450
+ * plus one flag, and anyone who can set `process.env` already controls PATH
451
+ * for the whole process. The shape of that call site is asserted in
452
+ * test/gate-auto-push.test.ts, so a later caller that funnels a value from a
453
+ * state file or an issue body into `env` is caught rather than assumed away.
454
+ *
455
+ * It does not throw. Every git invocation's failure becomes a `Reading` with
456
+ * `ok: false`, and `classifyPush` is total, so the worst case is an outcome of
457
+ * `unmeasured` — which `leftWorkLocal` counts as "work may be local". There is
458
+ * no input for which this reports success without having read the remote.
459
+ */
460
+ export function verifiedPush(
461
+ cwd: string,
462
+ opts: { env?: NodeJS.ProcessEnv; expectRepo?: string } = {},
463
+ ): PushOutcome {
464
+ const env = opts.env ?? process.env;
465
+ const git = runner(cwd, env);
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
+
503
+ const localSha = git(["rev-parse", "HEAD"], 5000);
504
+ const branch = git(["symbolic-ref", "--short", "HEAD"], 5000);
505
+ const b = branch.output.trim();
506
+ const remoteName = b
507
+ ? git(["config", "--get", `branch.${b}.remote`], 5000)
508
+ : { ok: false, output: "" };
509
+ const remoteRef = b
510
+ ? git(["config", "--get", `branch.${b}.merge`], 5000)
511
+ : { ok: false, output: "" };
512
+ const ahead = git(["rev-list", "--count", "@{upstream}..HEAD"], 5000);
513
+
514
+ const base: PushReadings = {
515
+ branch, remoteName, remoteRef, ahead, localSha, push: null, remote: null,
516
+ };
517
+
518
+ // Classify once with no push attempted. Everything that rules the push out —
519
+ // a detached HEAD, no upstream, an unreadable count, nothing to push — is
520
+ // already decided here, and re-deriving those conditions below is how two
521
+ // copies of the same rule drift apart. `not-attempted` is the one outcome
522
+ // this call cannot be sure of, because it is the one a push would change.
523
+ const before = classifyPush(base);
524
+ if (before.kind !== "not-attempted") return before;
525
+
526
+ const push = git(
527
+ ["push", "--", remoteName.output.trim(), `HEAD:${remoteRef.output.trim()}`],
528
+ 30_000,
529
+ );
530
+ const remote = push.ok
531
+ ? git(["ls-remote", "--", remoteName.output.trim(), remoteRef.output.trim()], 20_000)
532
+ : null;
533
+
534
+ return classifyPush({ ...base, push, remote });
535
+ }