rungate 0.3.0 → 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.
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Which repository is an isolated agent actually standing in? (#218)
3
+ *
4
+ * On run `wf_5e3ed885-98c` the first Marcus was spawned in a worktree of the
5
+ * repository the run targets, and the remediation Marcus in a worktree of
6
+ * ANOTHER project entirely — a different checkout, with a different `origin`,
7
+ * for an issue targeting this one. The operator had changed directory
8
+ * mid-run, and `isolation: "worktree"` is resolved by the agent runtime
9
+ * against the session's cwd rather than the workflow's `projectRoot`.
10
+ *
11
+ * (The two repositories are named in the issue and in
12
+ * `test/worktree-repo.test.ts`'s replay, not here: the harness must not name
13
+ * one of its consumers — see `test/anti.test.ts` SC-A1 and #304.)
14
+ *
15
+ * `workflows/ship.js:674` already pins `opts.cwd = PROJECT_ROOT` for every
16
+ * isolated spawn and has since 2026-09-23 — three weeks BEFORE the incident.
17
+ * The pin did not hold, so the fix cannot be another way of deriving the path.
18
+ * It has to be a reading of where the agent actually ended up.
19
+ *
20
+ * ## Why a slug comparison and not a path comparison
21
+ *
22
+ * A path prefix check answers "is this under the directory I expected", which
23
+ * is the question whose answer was already wrong: the run's idea of the
24
+ * directory is the thing that drifted. `git remote get-url origin` is a fact
25
+ * about the checkout, read from the checkout, and it is the same identity the
26
+ * run was given in its `repo` argument. Comparing those two cannot be
27
+ * satisfied by a path that merely looks right.
28
+ *
29
+ * ## Fail-closed, with the two "no answer" cases kept apart
30
+ *
31
+ * An unreadable remote and an absent one are both refusals. They are not the
32
+ * same refusal: "the worktree has no origin" is a detached or bare checkout,
33
+ * and "nothing reported a remote" means the reading never happened. A guard
34
+ * that collapsed them would let a reading that never ran read as a checkout
35
+ * with no remote, which is this repo's defining defect
36
+ * (`.claude/rules/checks-must-be-able-to-fail.md`).
37
+ */
38
+
39
+ import { spawnSync } from "child_process";
40
+
41
+ /** Returned by `readWorktreeRemote`, so a failure carries its own reason. */
42
+ export interface RemoteReading {
43
+ /** The raw URL git printed, or null if it printed nothing usable. */
44
+ url: string | null;
45
+ /** Non-null when the read itself failed — git missing, path gone, non-zero exit. */
46
+ error: string | null;
47
+ }
48
+
49
+ /** How a worktree's identity reading can go wrong. One value per refusal kind. */
50
+ export type IdentityVerdict = "match" | "mismatch" | "unreadable" | "unreported";
51
+
52
+ export interface IdentityResult {
53
+ verdict: IdentityVerdict;
54
+ /** The slug the worktree reports, when one could be parsed. */
55
+ actual: string | null;
56
+ /** The slug the run expects, normalised the same way. */
57
+ expected: string | null;
58
+ /** Null when the verdict is `match`; otherwise an operator-facing sentence. */
59
+ refusal: string | null;
60
+ }
61
+
62
+ /**
63
+ * `owner/name`, from any remote URL form git hands back.
64
+ *
65
+ * Handles the three this repo actually sees, and normalises case because
66
+ * GitHub slugs are case-insensitive while a clone URL may not match the
67
+ * canonical casing:
68
+ *
69
+ * git@github.com:owner/name.git
70
+ * https://github.com/owner/name.git
71
+ * https://x-access-token:TOKEN@github.com/owner/name
72
+ *
73
+ * Returns null rather than a guess for anything else. A guessed slug compared
74
+ * against a real one produces a refusal nobody can act on, and a guessed slug
75
+ * that happens to match is worse.
76
+ */
77
+ export function repoSlug(remote: string | null | undefined): string | null {
78
+ if (typeof remote !== "string") return null;
79
+ let s = remote.trim();
80
+ if (!s) return null;
81
+
82
+ // Strip a trailing `.git` and any trailing slashes, in that order — a URL
83
+ // can carry both (`…/name.git/`).
84
+ s = s.replace(/\/+$/, "").replace(/\.git$/i, "").replace(/\/+$/, "");
85
+
86
+ // scp-style: `git@host:owner/name`. The colon is the separator, and there
87
+ // is no `//` after it, which is what distinguishes this from a URL.
88
+ const scp = s.match(/^[^/]*@[^/:]+:(.+)$/);
89
+ if (scp) return normaliseSlug(scp[1]!);
90
+
91
+ // URL-style, with or without credentials in the authority.
92
+ const url = s.match(/^[a-z][a-z0-9+.-]*:\/\/[^/]*\/(.+)$/i);
93
+ if (url) return normaliseSlug(url[1]!);
94
+
95
+ // Already a bare slug — this is how the run's own `repo` argument arrives.
96
+ if (/^[^/\s]+\/[^/\s]+$/.test(s)) return normaliseSlug(s);
97
+
98
+ return null;
99
+ }
100
+
101
+ /**
102
+ * Exactly two segments, lowercased.
103
+ *
104
+ * EXACTLY two, not "the last two". Taking the tail of a longer path is a
105
+ * parser differential: `https://github.com/evil/repo/owner/name` is a path
106
+ * git reads as the repository `evil/repo/owner/name`, and a tail-taking
107
+ * parser reads it as `owner/name` and reports a MATCH. The remote being
108
+ * compared originates in an agent reply, so a parser that can be talked into
109
+ * agreeing is the whole guard.
110
+ *
111
+ * The cost is a self-hosted layout with a group prefix, which returns null
112
+ * and lands in the `unreadable` refusal. That is a loud, visible outcome
113
+ * naming the string it could not read — the right direction for a check to
114
+ * be wrong in.
115
+ */
116
+ function normaliseSlug(path: string): string | null {
117
+ const parts = path.split("/").filter(Boolean);
118
+ if (parts.length !== 2) return null;
119
+ return parts.join("/").toLowerCase();
120
+ }
121
+
122
+ /**
123
+ * A remote URL with every credential-bearing part replaced.
124
+ *
125
+ * Refusals are logged, and a CI checkout's origin is
126
+ * `https://x-access-token:TOKEN@host/owner/name`. Quoting the raw string
127
+ * into a run log writes a live token somewhere it will be read, copied into
128
+ * an issue, and kept.
129
+ *
130
+ * Three places, not one. The first draft redacted only the authority, which
131
+ * the push security review flagged as incomplete sanitisation, and it was
132
+ * right — a remote is not always well formed, and these strings reach the
133
+ * redactor precisely BECAUSE they could not be parsed:
134
+ *
135
+ * - the authority's userinfo, `user:pass@` or a bare `token@`
136
+ * - a query string, `?access_token=…` — git accepts one, and an
137
+ * `insteadOf` rewrite is a common way for one to end up there
138
+ * - anything left that is shaped like a key, anywhere in the string. A
139
+ * deny-list of parameter names is a list someone has to keep; the shape
140
+ * check is what covers the form nobody listed
141
+ *
142
+ * The control arm is the point of the third rule being narrow: a redactor
143
+ * that mangled every URL would satisfy every token case and make every
144
+ * refusal unreadable, which is a worse outcome than the leak for the 99% of
145
+ * refusals that quote an ordinary string.
146
+ */
147
+ const KEY_SHAPED = /\b(?:gh[pousr]_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9]{16,}|AKIA[A-Z0-9]{12,})\b/g;
148
+
149
+ export function redactRemote(remote: string): string {
150
+ return String(remote)
151
+ .replace(/(^[a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i, "$1<redacted>@")
152
+ .replace(/^([^/\s]*):[^/\s@]*@/, "$1:<redacted>@")
153
+ .replace(/([?&][^=&\s]*(?:token|auth|key|secret|password|pat)[^=&\s]*=)[^&\s]+/gi, "$1<redacted>")
154
+ .replace(KEY_SHAPED, "<redacted>");
155
+ }
156
+
157
+ /**
158
+ * Read a worktree's `origin` URL.
159
+ *
160
+ * `spawnSync` with an argument array and `-C`, never a shell string: the path
161
+ * originates in an agent reply (#155) and a shell would read whatever is in
162
+ * it. The timeout is short because this runs on a path that is already
163
+ * suspected of being wrong, and a hang here would stall the run at exactly
164
+ * the moment it needs to refuse.
165
+ */
166
+ export function readWorktreeRemote(worktreePath: string): RemoteReading {
167
+ if (typeof worktreePath !== "string" || !worktreePath.trim()) {
168
+ return { url: null, error: "no worktree path was given" };
169
+ }
170
+ const got = spawnSync("git", ["-C", worktreePath, "remote", "get-url", "origin"], {
171
+ timeout: 10_000,
172
+ encoding: "utf-8",
173
+ });
174
+ // Redacted on the way out, not at the call site. git's own stderr quotes
175
+ // the remote back at you — "fatal: 'https://user:TOKEN@host/x' does not
176
+ // appear to be a git repository" — so the error string is a second channel
177
+ // for the same credential the URL carries, and a caller that redacted only
178
+ // `url` would leak it through `error`.
179
+ if (got.error) return { url: null, error: redactRemote(got.error.message) };
180
+ if (got.status !== 0) {
181
+ const said = String(got.stderr || "").trim().split("\n")[0] || `git exited ${got.status}`;
182
+ return { url: null, error: redactRemote(said) };
183
+ }
184
+ const url = String(got.stdout || "").trim();
185
+ return url ? { url, error: null } : { url: null, error: "git printed no url" };
186
+ }
187
+
188
+ /**
189
+ * Does the worktree belong to the repository this run is for?
190
+ *
191
+ * `reported` is the remote URL as the worktree stated it — read in-process by
192
+ * `readWorktreeRemote`, or carried back in an agent's reply where the caller
193
+ * cannot run git (`workflows/ship.js` has no subprocess access, #69).
194
+ *
195
+ * Every non-match is a refusal that NAMES both sides. The #218 incident was
196
+ * recoverable only because the agent's own findings said which repo it was in
197
+ * and which the issue targeted; a refusal that omits either is one an
198
+ * operator has to go to the transcript for.
199
+ */
200
+ export function worktreeIdentity(
201
+ worktreePath: string,
202
+ expectedRepo: string | null | undefined,
203
+ reported: string | null | undefined,
204
+ ): IdentityResult {
205
+ const expected = repoSlug(expectedRepo);
206
+ const where = worktreePath || "(no path reported)";
207
+
208
+ if (!expected) {
209
+ // The run does not know its own repo, so there is nothing to compare
210
+ // against. Refusing is the only honest answer: passing here would make
211
+ // the guard silently inert for exactly the misconfigured run most likely
212
+ // to need it.
213
+ return {
214
+ verdict: "unreported",
215
+ actual: null,
216
+ expected: null,
217
+ refusal:
218
+ `${where} could not be checked — the run did not state a repository to compare against ` +
219
+ // Redacted too. `repo` is normally a bare slug, but this branch fires
220
+ // precisely when it was NOT one, and "whatever was passed instead"
221
+ // is exactly the value that might be a URL with a token in it.
222
+ `(repo was ${JSON.stringify(expectedRepo == null ? null : redactRemote(String(expectedRepo)))}), ` +
223
+ `so a worktree in any repository would pass (#218)`,
224
+ };
225
+ }
226
+
227
+ if (reported === null || reported === undefined || String(reported).trim() === "") {
228
+ return {
229
+ verdict: "unreported",
230
+ actual: null,
231
+ expected,
232
+ refusal:
233
+ `${where} reported no origin remote, so there is nothing to compare against ${expected} — ` +
234
+ `a reading that never happened is not a checkout that matched (#218)`,
235
+ };
236
+ }
237
+
238
+ const actual = repoSlug(reported);
239
+ if (!actual) {
240
+ return {
241
+ verdict: "unreadable",
242
+ actual: null,
243
+ expected,
244
+ refusal:
245
+ `${where} reported an origin this run cannot read as owner/name ` +
246
+ `(${JSON.stringify(redactRemote(String(reported).trim()))}), ` +
247
+ `so it cannot be compared against ${expected} (#218)`,
248
+ };
249
+ }
250
+
251
+ if (actual === expected) return { verdict: "match", actual, expected, refusal: null };
252
+
253
+ return {
254
+ verdict: "mismatch",
255
+ actual,
256
+ expected,
257
+ refusal:
258
+ `${where} is a worktree of ${actual}, but this run targets ${expected} — ` +
259
+ `an isolated agent resolved its worktree from ambient cwd rather than the run's projectRoot. ` +
260
+ `Work done there would be written into the wrong repository (#218).`,
261
+ };
262
+ }
263
+
264
+ /** One result row as the workflow reports them: a path and the remote it read. */
265
+ export interface WorktreeReport {
266
+ worktreePath?: string | null;
267
+ worktreeRepo?: string | null;
268
+ }
269
+
270
+ /**
271
+ * Every refusal across a run's agent results, in reported order.
272
+ *
273
+ * By default a row with no `worktreePath` is SKIPPED rather than refused: an
274
+ * agent that ran without isolation has no worktree to check, and refusing
275
+ * those would fire the guard on every non-isolated spawn in a run. A row that
276
+ * HAS a path and no remote is the `unreported` refusal — the agent was asked
277
+ * and did not answer, which is a different state.
278
+ *
279
+ * `requirePath` closes that default where it is a bypass. The push security
280
+ * review called it an authorization bypass and it is one: at a collection
281
+ * boundary, every row WILL be committed from, so "no path" is not "nothing to
282
+ * check" — it is a row claiming files with no checkable origin, and omitting
283
+ * one field would skip the guard entirely. Callers that are about to act on
284
+ * the rows pass `true`; callers merely surveying them do not.
285
+ */
286
+ export function worktreeIdentityViolations(
287
+ reports: readonly WorktreeReport[] | null | undefined,
288
+ expectedRepo: string | null | undefined,
289
+ opts: { requirePath?: boolean } = {},
290
+ ): string[] {
291
+ if (!Array.isArray(reports)) return [];
292
+ const out: string[] = [];
293
+ for (const r of reports) {
294
+ const path = r && typeof r.worktreePath === "string" ? r.worktreePath.trim() : "";
295
+ if (!path && !opts.requirePath) continue;
296
+ const got = worktreeIdentity(path, expectedRepo, r?.worktreeRepo);
297
+ if (got.refusal) out.push(got.refusal);
298
+ }
299
+ return out;
300
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rungate",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Ship harness — conformity tests, scaffold, and agent briefs for AI-first development",
6
6
  "repository": {
@@ -36,6 +36,7 @@
36
36
  "test": "bun test",
37
37
  "posttest": "bun scripts/sync-sc-status.ts",
38
38
  "sync-scs": "bun scripts/sync-sc-status.ts",
39
+ "typecheck": "bun scripts/typecheck.ts",
39
40
  "test:structure": "bun test test/structure.test.ts",
40
41
  "test:external-deps": "bun test test/external-deps.test.ts"
41
42
  },
@@ -45,7 +46,8 @@
45
46
  "zod": "^3.23.0"
46
47
  },
47
48
  "devDependencies": {
48
- "@types/bun": "latest"
49
+ "@types/bun": "latest",
50
+ "typescript": "5.9.3"
49
51
  },
50
52
  "bin": {
51
53
  "rungate": "bin/rungate.ts"