rungate 0.4.1 → 0.5.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 (42) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/cli-commands.ts +7 -1
  11. package/lib/conformity.ts +965 -30
  12. package/lib/github.ts +195 -0
  13. package/lib/js-top-level-code.ts +27 -2
  14. package/lib/package-closure.ts +278 -2
  15. package/lib/release-preflight.ts +196 -0
  16. package/lib/scaffold/defaults.ts +40 -0
  17. package/lib/scaffold/managed-workflow.ts +125 -27
  18. package/lib/scaffold/owned-files.ts +6 -0
  19. package/lib/scaffold/profiles.ts +94 -0
  20. package/lib/scaffold/rehearsal.ts +27 -2
  21. package/lib/scaffold/steps.ts +654 -84
  22. package/lib/scaffold/write-steps.ts +50 -9
  23. package/lib/source-anchor.ts +144 -0
  24. package/lib/success-doc.ts +779 -0
  25. package/lib/suite-run-reading.ts +194 -0
  26. package/lib/test-census.ts +199 -0
  27. package/lib/trajectory.ts +377 -0
  28. package/lib/validators/spec-validators.ts +32 -4
  29. package/lib/workflow-security.ts +101 -0
  30. package/lib/workflow-test-harness.ts +349 -0
  31. package/package.json +6 -1
  32. package/scripts/create-success.ts +162 -0
  33. package/scripts/scaffold-project.ts +27 -3
  34. package/specs/SPEC-TEMPLATE.md +200 -0
  35. package/templates/SUCCESS-TEMPLATE.md +72 -0
  36. package/templates/agent-briefs/_shared.md +9 -0
  37. package/templates/agent-briefs/aditi.md +46 -0
  38. package/templates/agent-briefs/discovery.md +37 -0
  39. package/templates/agent-briefs/marcus.md +39 -0
  40. package/templates/agent-briefs/quinn.md +67 -0
  41. package/templates/agent-briefs/rook.md +40 -0
  42. package/templates/agent-briefs/serena.md +39 -0
@@ -0,0 +1,377 @@
1
+ /**
2
+ * The run's trajectory: one JSONL artifact, one short line per event, read
3
+ * back as an ordered timeline (#60).
4
+ *
5
+ * WHY THIS IS NOT A NEW ARTIFACT
6
+ *
7
+ * #60 asked for `{workDir}/trajectory.jsonl` holding agent calls, phases,
8
+ * gates and state mutations, written by wrapping `agent()` and `phase()` in
9
+ * `workflows/ship.js`. The workflow cannot do that: it runs in the Workflow
10
+ * sandbox with no filesystem, no subprocess and no `Date.now()` (#69). Every
11
+ * artifact it produces crosses that boundary through a script an agent is
12
+ * instructed to run — which is exactly what `scripts/record-agent-timings.ts`
13
+ * already is, and it already writes one short line per event to
14
+ * `${WORK_DIR}/agent-timings.jsonl` (#227, #239).
15
+ *
16
+ * So the trajectory is that file, widened. A second JSONL beside it would be a
17
+ * second source of truth for when an agent ran, and the two would disagree the
18
+ * first time one of them lost a line.
19
+ *
20
+ * WHAT A LINE LOOKS LIKE
21
+ *
22
+ * {"label":"discovery","event":"start","at":1,"phase":"Discovery"}
23
+ * {"type":"mutation","at":2,"fields":["acs","sizing"],"source":"scope-1"}
24
+ * {"type":"gate","at":3,"gate":"scope","result":"PASS","failures":[]}
25
+ *
26
+ * An agent bracket carries NO `type`, because thousands of them are already on
27
+ * disk in in-flight runs and a reader that called those malformed would be
28
+ * reporting a defect it had just introduced. `type` is absent ⇒ agent bracket;
29
+ * present ⇒ one of the kinds below.
30
+ *
31
+ * WHAT IT DOES NOT CLAIM
32
+ *
33
+ * Phase spans are DERIVED from the agent records that carry a phase, so a
34
+ * phase's measured span is "from the first agent that reported in it to the
35
+ * last". The gap between two phases — gate runs, sandbox logic, the workflow
36
+ * thinking — is visible as a gap and is not attributed to either.
37
+ *
38
+ * **A phase with no agent records is not a zero-length phase, and this module
39
+ * will not say that it is.** It is absent from `phaseSpans` entirely, and
40
+ * `scripts/view-trajectory.ts` prints a line saying the timeline reports what
41
+ * recorded rather than what ran. `0`, `{}` and silence are indistinguishable
42
+ * from success; absence that announces itself is not
43
+ * (`.claude/rules/config-access.md`, Silent Default Substitution).
44
+ */
45
+
46
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
47
+ import { dirname, join } from "path";
48
+
49
+ /** The artifact every run writes, named for what it has always been called. */
50
+ export const TRAJECTORY_FILENAME = "agent-timings.jsonl";
51
+
52
+ /** The artifact for a run whose state file is at `sf`. */
53
+ export function trajectoryFor(stateFile: string): string {
54
+ return join(dirname(stateFile), TRAJECTORY_FILENAME);
55
+ }
56
+
57
+ export interface AgentRecord {
58
+ kind: "agent";
59
+ label: string;
60
+ event: "start" | "end" | "queued";
61
+ at: number;
62
+ waitedMs?: number;
63
+ /** The ship.js phase this call site belongs to. Absent on pre-#60 lines. */
64
+ phase?: string;
65
+ }
66
+
67
+ export interface MutationRecord {
68
+ kind: "mutation";
69
+ at: number;
70
+ /** Dotted paths that changed, one level into `gates` and `environments`. */
71
+ fields: string[];
72
+ /**
73
+ * Who wrote it, when that is knowable.
74
+ *
75
+ * It usually is not: `writeWorkflowState` is called from an agent's `bun -e`
76
+ * one-liner and nothing in that process knows which call site spawned it.
77
+ * #60 asked for "by which agent" and this is the honest half of it — the
78
+ * field is omitted rather than filled with a guess, and the viewer prints
79
+ * `unattributed`, which is a different word from a name.
80
+ */
81
+ source?: string;
82
+ }
83
+
84
+ export interface GateRecord {
85
+ kind: "gate";
86
+ at: number;
87
+ gate: string;
88
+ result: string;
89
+ failures: string[];
90
+ }
91
+
92
+ export type TrajectoryRecord = AgentRecord | MutationRecord | GateRecord;
93
+
94
+ export interface TrajectoryRead {
95
+ records: TrajectoryRecord[];
96
+ /** Lines that did not parse as any known record, verbatim. Never discarded. */
97
+ malformed: string[];
98
+ /** The artifact does not exist. Distinct from "it exists and is empty". */
99
+ missing: boolean;
100
+ }
101
+
102
+ // ── writing ──────────────────────────────────────────────────
103
+
104
+ /**
105
+ * Append one record. One `JSON.stringify` and one `appendFileSync`, under the
106
+ * pipe-buffer size, which is what keeps concurrent agents from interleaving
107
+ * mid-line — the same discipline `recordEvent` has always used.
108
+ */
109
+ export function appendTrajectory(artifact: string, record: TrajectoryRecord): void {
110
+ mkdirSync(dirname(artifact), { recursive: true });
111
+ const { kind, ...rest } = record;
112
+ const line = kind === "agent" ? rest : { type: kind, ...rest };
113
+ appendFileSync(artifact, `${JSON.stringify(line)}\n`);
114
+ }
115
+
116
+ // ── reading ──────────────────────────────────────────────────
117
+
118
+ function parseAgent(v: Record<string, unknown>): AgentRecord | null {
119
+ const { label, event, at, waitedMs, phase } = v;
120
+ if (typeof label !== "string" || label.length === 0) return null;
121
+ if (event !== "start" && event !== "end" && event !== "queued") return null;
122
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
123
+ // A queued record with no readable duration is MALFORMED, never a zero wait:
124
+ // reading it as zero makes the one record whose job is to say "this call
125
+ // waited" report that it did not (#239).
126
+ if (event === "queued" && (typeof waitedMs !== "number" || !Number.isFinite(waitedMs) || waitedMs < 0)) {
127
+ return null;
128
+ }
129
+ return {
130
+ kind: "agent",
131
+ label,
132
+ event,
133
+ at,
134
+ ...(event === "queued" ? { waitedMs: waitedMs as number } : {}),
135
+ ...(typeof phase === "string" && phase.length > 0 ? { phase } : {}),
136
+ };
137
+ }
138
+
139
+ function parseMutation(v: Record<string, unknown>): MutationRecord | null {
140
+ const { at, fields, source } = v;
141
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
142
+ if (!Array.isArray(fields)) return null;
143
+ const clean = fields.filter((f): f is string => typeof f === "string" && f.length > 0);
144
+ // A mutation that changed nothing is not a mutation, and recording one would
145
+ // put a row in the timeline saying a write happened with no content — the
146
+ // shape a reader would treat as "something changed and we lost what".
147
+ if (clean.length !== fields.length || clean.length === 0) return null;
148
+ return {
149
+ kind: "mutation",
150
+ at,
151
+ fields: clean,
152
+ ...(typeof source === "string" && source.length > 0 ? { source } : {}),
153
+ };
154
+ }
155
+
156
+ function parseGate(v: Record<string, unknown>): GateRecord | null {
157
+ const { at, gate, result, failures } = v;
158
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
159
+ if (typeof gate !== "string" || gate.length === 0) return null;
160
+ if (typeof result !== "string" || result.length === 0) return null;
161
+ const lines = Array.isArray(failures) ? failures.filter((f): f is string => typeof f === "string") : [];
162
+ return { kind: "gate", at, gate, result, failures: lines };
163
+ }
164
+
165
+ export function parseTrajectoryLine(line: string): TrajectoryRecord | null {
166
+ let value: unknown;
167
+ try {
168
+ value = JSON.parse(line);
169
+ } catch {
170
+ return null;
171
+ }
172
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
173
+ const v = value as Record<string, unknown>;
174
+ if (v.type === undefined) return parseAgent(v);
175
+ if (v.type === "mutation") return parseMutation(v);
176
+ if (v.type === "gate") return parseGate(v);
177
+ // A `type` this version does not know is MALFORMED rather than skipped. A
178
+ // reader that quietly drops record kinds it has not been taught reports a
179
+ // complete timeline over a file it only partly understood.
180
+ return null;
181
+ }
182
+
183
+ export function readTrajectory(artifact: string): TrajectoryRead {
184
+ if (!existsSync(artifact)) return { records: [], malformed: [], missing: true };
185
+ const records: TrajectoryRecord[] = [];
186
+ const malformed: string[] = [];
187
+ for (const line of readFileSync(artifact, "utf-8").split("\n")) {
188
+ if (line.trim() === "") continue;
189
+ const record = parseTrajectoryLine(line);
190
+ if (record) records.push(record);
191
+ else malformed.push(line);
192
+ }
193
+ return { records, malformed, missing: false };
194
+ }
195
+
196
+ // ── phase spans ──────────────────────────────────────────────
197
+
198
+ export interface PhaseSpan {
199
+ phase: string;
200
+ /** First agent event observed in this phase. */
201
+ startedAt: number;
202
+ /** Last agent event observed in this phase. */
203
+ endedAt: number;
204
+ seconds: number;
205
+ /** How many agent brackets contributed. One is a span of one call, not a phase. */
206
+ agents: number;
207
+ }
208
+
209
+ /**
210
+ * The span of each phase that recorded anything, in first-seen order.
211
+ *
212
+ * Derived rather than written, because nothing can write it: a phase boundary
213
+ * in `workflows/ship.js` is a `phase('Goal')` call inside the sandbox, with no
214
+ * clock and no filesystem. The agents inside the phase are the only
215
+ * participants that can report, so the phase is as wide as its agents and no
216
+ * wider.
217
+ *
218
+ * Phases that recorded nothing do not appear. That is the honest answer and it
219
+ * is why `scripts/view-trajectory.ts` prints the caveat rather than listing a
220
+ * phase at zero seconds.
221
+ */
222
+ export function phaseSpans(records: TrajectoryRecord[]): PhaseSpan[] {
223
+ const order: string[] = [];
224
+ const byPhase = new Map<string, { first: number; last: number; labels: Set<string> }>();
225
+ for (const r of records) {
226
+ if (r.kind !== "agent" || !r.phase) continue;
227
+ const seen = byPhase.get(r.phase);
228
+ if (!seen) {
229
+ order.push(r.phase);
230
+ byPhase.set(r.phase, { first: r.at, last: r.at, labels: new Set([r.label]) });
231
+ continue;
232
+ }
233
+ // `min`/`max` rather than first-and-last-in-file: parallel agents append
234
+ // out of order, so the last line of a phase is not always its latest
235
+ // event.
236
+ seen.first = Math.min(seen.first, r.at);
237
+ seen.last = Math.max(seen.last, r.at);
238
+ seen.labels.add(r.label);
239
+ }
240
+ return order.map((phase) => {
241
+ const s = byPhase.get(phase)!;
242
+ return {
243
+ phase,
244
+ startedAt: s.first,
245
+ endedAt: s.last,
246
+ seconds: Math.round(((s.last - s.first) / 1000) * 1000) / 1000,
247
+ agents: s.labels.size,
248
+ };
249
+ });
250
+ }
251
+
252
+ // ── the merged timeline ──────────────────────────────────────
253
+
254
+ export interface TimelineRow {
255
+ at: number;
256
+ kind: TrajectoryRecord["kind"];
257
+ /** One line, already formatted. The viewer adds the clock column. */
258
+ text: string;
259
+ }
260
+
261
+ /**
262
+ * Every record as one ordered list of rows.
263
+ *
264
+ * Sorted by `at`, with ties keeping file order — several events inside one
265
+ * millisecond are common on a fast machine, and reordering them would make the
266
+ * timeline disagree with the artifact for no gain.
267
+ */
268
+ export function timeline(records: TrajectoryRecord[]): TimelineRow[] {
269
+ return records
270
+ .map((r, i) => ({ r, i }))
271
+ .sort((a, b) => a.r.at - b.r.at || a.i - b.i)
272
+ .map(({ r }) => {
273
+ if (r.kind === "agent") {
274
+ const where = r.phase ? ` [${r.phase}]` : "";
275
+ const waited = r.event === "queued" ? ` waited ${r.waitedMs}ms` : "";
276
+ return { at: r.at, kind: r.kind, text: `agent ${r.label} ${r.event}${waited}${where}` };
277
+ }
278
+ if (r.kind === "mutation") {
279
+ return {
280
+ at: r.at,
281
+ kind: r.kind,
282
+ text: `state ${r.source ?? "unattributed"} wrote ${r.fields.join(", ")}`,
283
+ };
284
+ }
285
+ const detail = r.failures.length > 0 ? ` — ${r.failures.join("; ")}` : "";
286
+ return { at: r.at, kind: r.kind, text: `gate ${r.gate} ${r.result}${detail}` };
287
+ });
288
+ }
289
+
290
+ // ── state mutations ──────────────────────────────────────────
291
+
292
+ /**
293
+ * Which field paths differ between two states.
294
+ *
295
+ * Top level, plus one level into the containers a run actually mutates during
296
+ * a pipeline — `gates`, `environments` and `gateContract`. Deeper than that is
297
+ * noise: every AC verdict edit would print a path per AC and the timeline
298
+ * would stop being readable, which is the one thing #60 is for.
299
+ *
300
+ * Compared by serialised value rather than by reference, because callers read
301
+ * the state, mutate it in place, and write the same object back — a reference
302
+ * comparison would report that nothing ever changed.
303
+ */
304
+ const NESTED = ["gates", "environments", "gateContract"];
305
+
306
+ export function changedFields(
307
+ before: Record<string, unknown> | null,
308
+ after: Record<string, unknown>,
309
+ ): string[] {
310
+ if (before === null) return ["<initial write>"];
311
+ const changed: string[] = [];
312
+ const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
313
+ for (const key of [...keys].sort()) {
314
+ const a = before[key];
315
+ const b = after[key];
316
+ if (stable(a) === stable(b)) continue;
317
+ if (!NESTED.includes(key) || !isRecord(a) || !isRecord(b)) {
318
+ changed.push(key);
319
+ continue;
320
+ }
321
+ const sub = new Set([...Object.keys(a), ...Object.keys(b)]);
322
+ for (const k of [...sub].sort()) {
323
+ if (stable(a[k]) !== stable(b[k])) changed.push(`${key}.${k}`);
324
+ }
325
+ }
326
+ return changed;
327
+ }
328
+
329
+ function isRecord(v: unknown): v is Record<string, unknown> {
330
+ return typeof v === "object" && v !== null && !Array.isArray(v);
331
+ }
332
+
333
+ function stable(v: unknown): string {
334
+ // `undefined` and absent are the same fact here, and JSON.stringify returns
335
+ // `undefined` (the value, not the string) for both — which would compare
336
+ // equal to itself and unequal to nothing, so it is normalised first.
337
+ if (v === undefined) return "\u0000absent";
338
+ return JSON.stringify(v, (_k, x) =>
339
+ isRecord(x)
340
+ ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, (x as Record<string, unknown>)[k]]))
341
+ : x,
342
+ );
343
+ }
344
+
345
+ /**
346
+ * Record a state write on the run's trajectory.
347
+ *
348
+ * **Never throws.** A trajectory line is a record OF a state write and must
349
+ * not be able to prevent one: losing the line costs a row in a timeline,
350
+ * losing the write costs the run. The failure goes to stderr rather than being
351
+ * swallowed — there is no channel left to record it on, since the thing that
352
+ * failed is the recorder.
353
+ *
354
+ * Returns the fields it recorded, or `null` when it recorded nothing, so a
355
+ * caller that wants to assert on the recording can.
356
+ */
357
+ export function recordStateWrite(
358
+ stateFile: string,
359
+ before: Record<string, unknown> | null,
360
+ after: Record<string, unknown>,
361
+ source?: string,
362
+ at: number = Date.now(),
363
+ ): string[] | null {
364
+ try {
365
+ const fields = changedFields(before, after);
366
+ if (fields.length === 0) return null;
367
+ appendTrajectory(trajectoryFor(stateFile), { kind: "mutation", at, fields, ...(source ? { source } : {}) });
368
+ return fields;
369
+ } catch (err) {
370
+ process.stderr.write(
371
+ `trajectory: could not record the state write to ${stateFile} — ` +
372
+ `${err instanceof Error ? err.message : String(err)}. The write itself is unaffected; ` +
373
+ `this run's timeline is missing a row (#60).\n`,
374
+ );
375
+ return null;
376
+ }
377
+ }
@@ -142,7 +142,7 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
142
142
  if (!content.startsWith("---\n")) {
143
143
  const frontmatter = `---\ndoc-type: adr\nstatus: draft\nowner: TODO\ncreated: ${today}\nupdated: ${today}\n---\n\n`;
144
144
  writeFileSync(filePath, frontmatter + content);
145
- actions.push(`UPDATED: docs/adr/${file} (added frontmatter)`);
145
+ actions.push(`AUTO-FIXED: docs/adr/${file} (added frontmatter)`);
146
146
  } else {
147
147
  const fmEnd = content.indexOf("\n---", 4);
148
148
  if (fmEnd === -1) continue;
@@ -150,10 +150,38 @@ export function addFrontmatterToAdrs(adrDir: string, actions: string[]): void {
150
150
  const missing: string[] = [];
151
151
  if (!fm.includes("doc-type:")) missing.push(`doc-type: adr`);
152
152
  if (!fm.includes("created:")) missing.push(`created: ${today}`);
153
- if (missing.length > 0) {
154
- const newFm = `---\n${fm}\n${missing.join("\n")}\n---`;
153
+
154
+ // A doc-type that is present but WRONG (#42).
155
+ //
156
+ // The fixer used to key on whether the field existed while HYGIENE-10
157
+ // keys on its VALUE (`lib/conformity.ts`: `fm["doc-type"] !== "adr"`).
158
+ // So an ADR carrying `doc-type: guide` satisfied `fm.includes` and was
159
+ // never touched — re-scaffold ran, reported nothing, and the warning
160
+ // came back every single time. Two readers of one field disagreeing
161
+ // about what it means is why the auto-fix could not clear the finding
162
+ // it was written to clear.
163
+ //
164
+ // Corrected in place rather than appended: adding a second `doc-type:`
165
+ // line would leave a document with two, and a parser taking the first
166
+ // would keep the wrong one forever.
167
+ const wrongType = fm.match(/^(\s*doc-type:\s*)(.+?)\s*$/m);
168
+ let corrected = fm;
169
+ let retyped: string | null = null;
170
+ if (wrongType && wrongType[2] !== "adr") {
171
+ retyped = wrongType[2];
172
+ corrected = fm.replace(/^(\s*doc-type:\s*).+?\s*$/m, `$1adr`);
173
+ }
174
+
175
+ if (missing.length > 0 || retyped !== null) {
176
+ const newFm = missing.length > 0
177
+ ? `---\n${corrected}\n${missing.join("\n")}\n---`
178
+ : `---\n${corrected}\n---`;
155
179
  writeFileSync(filePath, newFm + content.substring(fmEnd + 4));
156
- actions.push(`UPDATED: docs/adr/${file} (added missing: ${missing.map(m => m.split(":")[0]).join(", ")})`);
180
+ const what = [
181
+ ...(missing.length > 0 ? [`added missing: ${missing.map(m => m.split(":")[0]).join(", ")}`] : []),
182
+ ...(retyped !== null ? [`doc-type was "${retyped}", set to adr`] : []),
183
+ ];
184
+ actions.push(`AUTO-FIXED: docs/adr/${file} (${what.join("; ")})`);
157
185
  }
158
186
  }
159
187
  }
@@ -108,6 +108,107 @@ export function isSafeBranchName(name: unknown): name is string {
108
108
  return true;
109
109
  }
110
110
 
111
+ /**
112
+ * Why a repo slug may not reach a shell command, or null if it may (#533).
113
+ *
114
+ * `ship.js` interpolates `repo` and `issueRepo` UNQUOTED into shell text
115
+ * inside agent prompts — six and eleven sites respectively — and checked only
116
+ * that `repo` was present. One function away, the same file validates a
117
+ * branch name before it reaches a `git push`, and `scripts/github-op.ts` has
118
+ * `--title-from-issue` precisely so an issue title never crosses a shell. So
119
+ * the project had already decided that values reaching a shell get checked
120
+ * first, and this is the one that missed.
121
+ *
122
+ * The shape is `parseOwnerRepo`'s in `lib/github.ts`, which is what the
123
+ * GitHub API layer will accept anyway: exactly two segments of
124
+ * `[A-Za-z0-9._-]`, neither of them `.` or `..`. A slug this refuses would
125
+ * have failed at the API boundary regardless — the difference is that it now
126
+ * fails before a shell has seen it, with a sentence naming the argument.
127
+ *
128
+ * REFUSED, never sanitised. Stripping characters out of a repo slug produces
129
+ * a run filed under a different project, which is the defect #114 already
130
+ * cost this repo once.
131
+ */
132
+ const REPO_SLUG_SEGMENT = /^[A-Za-z0-9._-]+$/;
133
+
134
+ /**
135
+ * The refusals that are about what a slug MEANS rather than which characters
136
+ * it uses — the same shape `isSafeBranchName` takes below, where the regex
137
+ * is followed by git's own rules.
138
+ *
139
+ * A leading `-` is the one that matters and it is the reason that function
140
+ * gives: git and gh both read it as a flag. No GitHub owner or repository
141
+ * name may begin with `-` or `.` or end with `.` anyway, so refusing them
142
+ * costs nothing a real slug needs.
143
+ */
144
+ function illegalSlugSegment(p: string): boolean {
145
+ if (!REPO_SLUG_SEGMENT.test(p)) return true;
146
+ return p === "." || p === ".." || p.startsWith("-") || p.startsWith(".") || p.endsWith(".");
147
+ }
148
+
149
+ export function repoSlugRefusal(argName: string, value: unknown): string | null {
150
+ if (typeof value !== "string" || value.length === 0) {
151
+ return `${argName} must be a non-empty string of the form "owner/name"; got ${describeArg(value)}`;
152
+ }
153
+ if (value.length > 255) return `${argName} is ${value.length} characters, which is not a repository slug`;
154
+ const parts = value.split("/");
155
+ if (parts.length !== 2 || parts.some(illegalSlugSegment)) {
156
+ return (
157
+ `${argName} must be "owner/name" using only letters, digits, dot, dash and underscore; ` +
158
+ `got ${describeArg(value)} — it is interpolated unquoted into shell commands`
159
+ );
160
+ }
161
+ return null;
162
+ }
163
+
164
+ /**
165
+ * Why a root directory may not reach a shell command, or null if it may.
166
+ *
167
+ * Deliberately NOT `pathRefusal`, and the difference is the first rule in
168
+ * each: that table refuses an absolute path, because it answers "may an agent
169
+ * contribute this file from inside its worktree". This one REQUIRES an
170
+ * absolute path, because it answers "may the run `cd` here". Same word, two
171
+ * questions, opposite answers — folding them together would make one of the
172
+ * two wrong.
173
+ *
174
+ * Whitespace is refused along with the metacharacters, which `pathRefusal`
175
+ * does not do. A space is harmless in a path and fatal in `cd ${ROOT} && …`
176
+ * unquoted, and these values reach seventy-seven such sites. The honest fix
177
+ * is to quote all of them; until then a run on a path with a space in it
178
+ * silently `cd`s somewhere else, and refusing is the reading an operator can
179
+ * act on.
180
+ */
181
+ export function rootPathRefusal(argName: string, value: unknown): string | null {
182
+ if (typeof value !== "string" || value.length === 0) {
183
+ return `${argName} must be a non-empty absolute path; got ${describeArg(value)}`;
184
+ }
185
+ if (value.length > 500) return `${argName} is ${value.length} characters, which is not a directory path`;
186
+ if (!value.startsWith("/")) return `${argName} must be an absolute path; got ${describeArg(value)}`;
187
+ if (NULL_BYTE.test(value)) return `${argName} contains a null byte`;
188
+ if (value.split("/").includes("..")) return `${argName} contains a \`..\` segment: ${describeArg(value)}`;
189
+ if (/\s/.test(value)) {
190
+ return (
191
+ `${argName} contains whitespace: ${describeArg(value)} — it is interpolated unquoted into ` +
192
+ `shell commands, so the run would cd somewhere other than where you meant`
193
+ );
194
+ }
195
+ if (SHELL_METACHARACTERS.test(value)) {
196
+ return `${argName} contains a shell metacharacter: ${describeArg(value)} — it is interpolated unquoted into shell commands`;
197
+ }
198
+ return null;
199
+ }
200
+
201
+ /**
202
+ * An argument value, quoted and truncated, for a refusal message.
203
+ *
204
+ * Truncated because the value is attacker-shaped by assumption at the point
205
+ * this runs, and a refusal is printed, logged and pasted into issues.
206
+ */
207
+ function describeArg(value: unknown): string {
208
+ if (typeof value !== "string") return value === undefined ? "nothing" : JSON.stringify(value) ?? String(value);
209
+ return JSON.stringify(value.length > 80 ? value.slice(0, 80) + "…" : value);
210
+ }
211
+
111
212
  export function resolveEvidencePath(
112
213
  basePath: string,
113
214
  evidencePath: string,