rungate 0.5.0 → 0.7.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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
package/lib/create-sc.ts CHANGED
@@ -9,7 +9,19 @@ import { join, dirname } from "path";
9
9
  import { fileURLToPath } from "url";
10
10
 
11
11
  import type { ScRegistry } from "./sc-ids";
12
- import { isFixtureScId } from "./sc-ids";
12
+ import { isFixtureScId, scIdsSpelledInSourceReading, SC_SOURCE_DIRS } from "./sc-ids";
13
+ import type { ScNamespaceReading, SourceReading } from "./sc-id-cross-tree";
14
+ import { readScNamespace } from "./sc-id-cross-tree";
15
+ import type { ScReservation, ScReservationReading } from "./sc-reservations";
16
+ import {
17
+ lowestFreeInBlock,
18
+ readScReservations,
19
+ RESERVATION_REFUSAL,
20
+ reservationFor,
21
+ reservedCeiling,
22
+ reservedIdCount,
23
+ SC_RESERVATIONS_PATH,
24
+ } from "./sc-reservations";
13
25
  import { tryLoadRungateConfig } from "./config-loader";
14
26
 
15
27
  // ── Types ─────────────────────────────────────────────────────
@@ -267,6 +279,18 @@ export function listPatterns(): string {
267
279
  * collision this function exists to prevent. The reservation is enforced
268
280
  * against specs by SC-1524, not by making the allocator pretend.
269
281
  */
282
+ /**
283
+ * The ids a spec's own text spells, as one binding.
284
+ *
285
+ * The allocator counts them and the reading reports how many it counted; two
286
+ * scans of the same string would be two deciders that agree, and a reading
287
+ * whose numbers come from a different pattern than the allocation used is a
288
+ * reading of something else.
289
+ */
290
+ function idsInSpecContent(specContent: string): string[] {
291
+ return [...specContent.matchAll(/SC-(\d+)/g)].map(m => m[0]);
292
+ }
293
+
270
294
  export function nextSCNumber(
271
295
  specContent: string,
272
296
  reg?: ScRegistry,
@@ -277,15 +301,310 @@ export function nextSCNumber(
277
301
  const n = Number(raw.replace(/^SC-[A-Z]?/, ""));
278
302
  if (Number.isFinite(n)) ids.push(n);
279
303
  };
280
- const pattern = /SC-(\d+)/g;
281
- let match;
282
- while ((match = pattern.exec(specContent)) !== null) take(match[0]);
304
+ for (const raw of idsInSpecContent(specContent)) take(raw);
283
305
  for (const id of reg?.declaredById.keys() ?? []) take(id);
284
306
  for (const id of spelledInSource ?? []) if (!isFixtureScId(id)) take(id);
285
307
  if (ids.length === 0) return 1;
286
308
  return Math.max(...ids) + 1;
287
309
  }
288
310
 
311
+ /**
312
+ * The same three widths `nextSCNumber` reads, as a SET rather than a maximum.
313
+ *
314
+ * It exists because a reserved block is allocated from the bottom, not from
315
+ * the top: `max + 1` cannot answer "is 2174 free" when the block runs
316
+ * 2170..2189 and the tree's maximum is 2400. Both derive from one list
317
+ * comprehension so the two cannot come to disagree about which ids count — a
318
+ * second scan with a different fixture rule would be two deciders for one
319
+ * question (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
320
+ */
321
+ export function takenScNumbers(
322
+ specContent: string,
323
+ reg?: ScRegistry,
324
+ spelledInSource?: Iterable<string>,
325
+ ): Set<number> {
326
+ const taken = new Set<number>();
327
+ const take = (raw: string): void => {
328
+ const n = Number(raw.replace(/^SC-[A-Z]?/, ""));
329
+ if (Number.isFinite(n)) taken.add(n);
330
+ };
331
+ for (const raw of idsInSpecContent(specContent)) take(raw);
332
+ for (const id of reg?.declaredById.keys() ?? []) take(id);
333
+ for (const id of spelledInSource ?? []) if (!isFixtureScId(id)) take(id);
334
+ return taken;
335
+ }
336
+
337
+ /**
338
+ * The reservation store as a `SourceReading`, in one place.
339
+ *
340
+ * One binding for all three states, so a mutation has one site and a caller
341
+ * cannot assemble a leg that says `read` over a store it never opened. `found`
342
+ * is the number of ids the store declares OCCUPIED — the size of the space it
343
+ * removes from the allocator — and it is `0` under `absent` and `unreadable`
344
+ * for the same reason every other leg reports `0` when it did not run:
345
+ * `status` is what tells those apart, never the count.
346
+ */
347
+ export function scReservationLeg(reading: ScReservationReading): SourceReading {
348
+ const label = `SC reservation store (${SC_RESERVATIONS_PATH})`;
349
+ if (reading.status === "read") {
350
+ return {
351
+ label: `${label}: ${reading.blocks.length} block(s)`,
352
+ kind: "reservations",
353
+ status: "read",
354
+ found: reservedIdCount(reading.blocks),
355
+ };
356
+ }
357
+ return {
358
+ label,
359
+ kind: "reservations",
360
+ status: "skipped",
361
+ reason: reading.reason ?? `the store is ${reading.status}`,
362
+ found: 0,
363
+ };
364
+ }
365
+
366
+ /**
367
+ * Thrown when the caller's own reserved block has no id left in it.
368
+ *
369
+ * A distinct error rather than a fall-through to "allocate above the block",
370
+ * because that fall-through is the cheapest wrong fix and it silently undoes
371
+ * the separation the block was handed out to provide, on the one day it
372
+ * matters. Widening the block is a decision a person makes in the store.
373
+ */
374
+ export class ScReservationExhaustedError extends Error {}
375
+
376
+ /**
377
+ * The number, given the floor, the store and who is asking.
378
+ *
379
+ * Exported because it is the single binding a mutation battery points at:
380
+ * every reservation-aware decision this module makes happens here and nowhere
381
+ * else, so there is no second copy to hold a case up when this one is broken.
382
+ */
383
+ export function allocateAgainstReservations(
384
+ floor: number,
385
+ blocks: ScReservation[],
386
+ owner: string | null,
387
+ taken: ReadonlySet<number>,
388
+ ): number {
389
+ const mine = reservationFor(blocks, owner);
390
+ if (mine !== null) {
391
+ const free = lowestFreeInBlock(mine, taken);
392
+ if (free === null) {
393
+ throw new ScReservationExhaustedError(
394
+ `the SC block reserved to ${mine.owner} (${mine.from}-${mine.to}) is spent — ` +
395
+ `widen it in ${SC_RESERVATIONS_PATH} rather than allocating outside it`,
396
+ );
397
+ }
398
+ return free;
399
+ }
400
+ // No block of your own. The floor is still correct about what is WRITTEN;
401
+ // it knows nothing about what is DECLARED, so it is raised past every block
402
+ // in the store. This is the row that covers the renumber case — the one
403
+ // where nobody thought of themselves as allocating.
404
+ return Math.max(floor, reservedCeiling(blocks) + 1);
405
+ }
406
+
407
+ /**
408
+ * The next free SC number for a project, over every namespace this machine
409
+ * can see (#503).
410
+ *
411
+ * `nextSCNumber` answers the question for the arguments it is handed, and
412
+ * three widths of that question have each been wrong in turn: one spec's
413
+ * content (#392), the spec registry without test fixtures (#399), and the
414
+ * registry of whichever working tree the command ran in (#503). This is the
415
+ * composition, in one place, so a caller cannot assemble two of the three and
416
+ * believe it asked.
417
+ *
418
+ * It returns the reading alongside the number because the number is a FLOOR:
419
+ * a clone on another machine is outside anything this process can reach, and
420
+ * a caller that printed only the number would be claiming a guarantee the
421
+ * reading explicitly does not give.
422
+ *
423
+ * ## `reg` is REQUIRED, and was optional for two issues (#593)
424
+ *
425
+ * Omit it and `nextSCNumber` skips `reg.declaredById` entirely: the answer is
426
+ * assembled from the spec's own content, source-spelled fixtures and the
427
+ * cross-tree namespace, and the spec registry — the width #392 was filed
428
+ * over — is not consulted at all. The number comes back looking exactly like
429
+ * one that had asked everything, which is the composition failure the
430
+ * paragraph above says this function exists to make impossible. A caller
431
+ * with no registry to hand has `buildScRegistry([])`, which states "this
432
+ * tree declares nothing" instead of defaulting to it.
433
+ *
434
+ * The two readings agree whenever every spec-declared id is also spelled in
435
+ * a source file, which is most of the time and is why nothing noticed. They
436
+ * diverged the day a spec declared eight criteria no test mentioned yet.
437
+ *
438
+ * ## The reading names every leg, not just the cross-tree ones
439
+ *
440
+ * `readScNamespace` accounts for the worktrees and refs it read. The other
441
+ * three widths were invisible in the returned reading, so a CLI could print
442
+ * the number and a complete-looking account of where it came from while one
443
+ * of the legs behind it had never run. They are appended as sources of their
444
+ * own, with the count each contributed — `0` from a leg that was consulted
445
+ * and `0` from a leg that was skipped are the same number and opposite
446
+ * facts (`.claude/rules/config-access.md`).
447
+ *
448
+ * ## …and for two issues all three said `read` without asking (#606)
449
+ *
450
+ * The sentence above was the docstring of a function that hardcoded
451
+ * `status: "read"` on every one of the three. Measured on a tree holding one
452
+ * spec and none of the four source directories: `source-mentions` reported
453
+ * `read, found 0` — which is also the output for a tree whose four
454
+ * directories were walked and held no ids. A consumer whose tests live in
455
+ * `tests/` or `src/` was in the second case on every single run.
456
+ *
457
+ * Two of the three are now derived, and one is not:
458
+ *
459
+ * | Leg | Source of `found` | Can it have failed to read? |
460
+ * |---|---|---|
461
+ * | `spec-content` | `idsInSpecContent(specContent)` | **No.** `specContent` is a string parameter, already in memory. `0` here is a reading |
462
+ * | `registry` | `reg.declaredById.size` | Yes — `reg` may have been built from a `specs/` the caller could not enumerate, which `ScRegistry.enumeration` now states |
463
+ * | `source-mentions` | the source walk | Yes — four directories, any of which the walk returns silently from |
464
+ *
465
+ * `spec-content` stays `read` deliberately. Rewriting all three uniformly is
466
+ * the cheap-looking repair and it adds an unreachable branch to the one leg
467
+ * that was right, which no case can go red over.
468
+ *
469
+ * A leg that could not be fully read also appends to `namespace.unmeasured`,
470
+ * because `status` is a per-leg fact and `unmeasured` is the list a caller
471
+ * prints. A gap in only one of them is a gap a reader can miss.
472
+ *
473
+ * ## …and all six legs read ids that have already been WRITTEN (#725)
474
+ *
475
+ * Every width above answers "which ids can this machine find typed somewhere
476
+ * right now". None of them can see an id another session has decided to take
477
+ * and not yet typed, which is the window `.claude/rules/parallel-sessions.md`
478
+ * says people sit in for an hour. Four collisions on 2026-10-19 came out of
479
+ * it, and in three of them the allocator was never run at all — a renumber
480
+ * during a repair, two individually-correct branch allocations, and ids
481
+ * hand-written into a test file.
482
+ *
483
+ * `lib/sc-reservations.ts` is the seventh leg and the only one that is a
484
+ * reading of a DECLARATION rather than of the tree. `opts.owner` — a branch
485
+ * name or issue ref — selects the caller's own block:
486
+ *
487
+ * | The caller | What it gets |
488
+ * |---|---|
489
+ * | owns a block with room in it | the lowest free id INSIDE that block |
490
+ * | owns a block that is spent | a refusal naming the block |
491
+ * | owns no block | an id above every block in the store, so it cannot land in someone else's |
492
+ *
493
+ * The no-owner row is the one that makes the store work for the renumber
494
+ * case: a session that never declared anything still cannot be handed an id
495
+ * out of a block somebody else declared.
496
+ *
497
+ * A store that is present and could not be read is a REFUSAL, not an empty
498
+ * reading — see `lib/sc-reservations.ts`. A store that is genuinely absent is
499
+ * a skipped leg with a named `unmeasured` entry, because every scaffolded
500
+ * consumer project is in that state and a refusal they cannot act on is a
501
+ * gate everyone learns to click past.
502
+ */
503
+ export function allocateScNumber(
504
+ root: string,
505
+ specContent: string,
506
+ reg: ScRegistry,
507
+ opts?: { owner?: string | null },
508
+ ): { number: number; namespace: ScNamespaceReading } {
509
+ const namespace = readScNamespace(root);
510
+ const source = scIdsSpelledInSourceReading(root);
511
+ const spelled = [...source.ids.keys()];
512
+ const floor = nextSCNumber(specContent, reg, [...spelled, ...namespace.ids.keys()]);
513
+
514
+ const unmeasured: string[] = [];
515
+
516
+ const reservations = readScReservations(root);
517
+ // The refusal, before the number exists. Returning a floor computed without
518
+ // a store that is sitting right there, unreadable, is the pre-#725
519
+ // behaviour: `0`, `{}` and silence are indistinguishable from success
520
+ // (`.claude/rules/config-access.md`).
521
+ if (reservations.status === "unreadable") {
522
+ throw new Error(`${RESERVATION_REFUSAL} (${reservations.path}): ${reservations.reason}`);
523
+ }
524
+ const reservationLeg = scReservationLeg(reservations);
525
+ if (reservations.status !== "read") {
526
+ unmeasured.push(
527
+ `the SC reservation store could not be consulted: ${reservations.reason ?? "no reason given"}`,
528
+ );
529
+ }
530
+ const taken = takenScNumbers(specContent, reg, [...spelled, ...namespace.ids.keys()]);
531
+ const number = allocateAgainstReservations(floor, reservations.blocks, opts?.owner ?? null, taken);
532
+
533
+ const registryLabel = "spec registry (every declared id, checkbox and heading)";
534
+ const registryLeg: SourceReading = reg.enumeration.status === "enumerated"
535
+ ? { label: registryLabel, kind: "registry", status: "read", found: reg.declaredById.size }
536
+ : {
537
+ label: registryLabel,
538
+ kind: "registry",
539
+ status: "skipped",
540
+ reason: reg.enumeration.reason ?? "the spec registry was not enumerated",
541
+ found: 0,
542
+ };
543
+ if (reg.enumeration.status === "unenumerated") {
544
+ unmeasured.push(
545
+ `the spec registry was not enumerated: ${reg.enumeration.reason ?? "no reason given"}`,
546
+ );
547
+ }
548
+
549
+ const sourceLabel = `SC ids spelled under ${SC_SOURCE_DIRS.join(", ")}`;
550
+ const unreached = source.unwalkable.map(u => `${u.dir} (${u.reason})`).join("; ");
551
+ let sourceLeg: SourceReading;
552
+ if (source.walked.length === 0) {
553
+ // None of them opened. There is no reading here at all, and the count is
554
+ // the count of a walk that never happened.
555
+ sourceLeg = {
556
+ label: sourceLabel,
557
+ kind: "source-mentions",
558
+ status: "skipped",
559
+ reason: `none of ${SC_SOURCE_DIRS.join(", ")} could be walked: ${unreached}`,
560
+ found: 0,
561
+ };
562
+ } else if (source.unwalkable.length > 0) {
563
+ // Partially read, and the count is real for the part that was. Saying
564
+ // `skipped` here would swap the two cases rather than separate them.
565
+ sourceLeg = {
566
+ label: `${sourceLabel} (walked ${source.walked.join(", ")})`,
567
+ kind: "source-mentions",
568
+ status: "read",
569
+ reason: `could not walk ${unreached}`,
570
+ found: new Set(spelled).size,
571
+ };
572
+ } else {
573
+ sourceLeg = {
574
+ label: sourceLabel,
575
+ kind: "source-mentions",
576
+ status: "read",
577
+ found: new Set(spelled).size,
578
+ };
579
+ }
580
+ for (const u of source.unwalkable) {
581
+ unmeasured.push(`source directory ${u.dir} could not be walked: ${u.reason}`);
582
+ }
583
+
584
+ const legs: SourceReading[] = [
585
+ {
586
+ // Not derived, and the table above says why: there is no state in which
587
+ // this one could have failed to read a string it was handed.
588
+ label: "the spec's own content",
589
+ kind: "spec-content",
590
+ status: "read",
591
+ found: new Set(idsInSpecContent(specContent)).size,
592
+ },
593
+ registryLeg,
594
+ sourceLeg,
595
+ reservationLeg,
596
+ ];
597
+
598
+ return {
599
+ number,
600
+ namespace: {
601
+ ...namespace,
602
+ sources: [...legs, ...namespace.sources],
603
+ unmeasured: [...unmeasured, ...namespace.unmeasured],
604
+ },
605
+ };
606
+ }
607
+
289
608
  /**
290
609
  * Format an SC line for appending to a spec file.
291
610
  */
@@ -188,6 +188,186 @@ export function probeTarget(
188
188
  return { kind: "probe", url, safeUrl: safeForRecord(url) };
189
189
  }
190
190
 
191
+ /**
192
+ * Where to reach the test container, or why not (#312 SC-A15, harness half).
193
+ *
194
+ * `probeTarget` was written so "unconfigured is UNMEASURED, never DOWN" is
195
+ * decided once (SC-733). It covers `dev` and `prod`. The container is the
196
+ * third tier and never went through it: `workflows/ship.js` built its own URL
197
+ * at two sites, from `(container.hosts || [])[0]` and `container.port || 3000`.
198
+ *
199
+ * Nothing reached either site until now. `ProjectHarnessSchema` did not
200
+ * declare `container`, so the validator deleted the key and both sites took
201
+ * their no-container arm on every run that has ever happened. #307 SC-A1
202
+ * declared it, and SC-A15 is a consumer putting a value there — at which
203
+ * point the first consumer with a `rebuildCommand` and no `hosts` gets:
204
+ *
205
+ * curl -s -o /dev/null -w "%{http_code}" http://undefined:3000/
206
+ *
207
+ * interpolated into an agent prompt, no 200 back, and
208
+ * `prod.smoke = SKIP, smokeSkipReason = test container not running` written
209
+ * into the artefact. That reason is a positive claim about a container
210
+ * nothing contacted, and it is indistinguishable in the record from a probe
211
+ * that ran and found the container down. Every field of `ContainerSchema` is
212
+ * optional, so that config validates.
213
+ *
214
+ * So there are three outcomes and not two, and the difference between the two
215
+ * new ones is which verdict the run has earned:
216
+ *
217
+ * - `unconfigured` — no container. Nothing to measure; the run may SKIP.
218
+ * - `unmeasured` — a container is declared and the config does not say where
219
+ * to reach it. The run measured nothing and must not say otherwise; its
220
+ * caller records FAIL, because SKIP here reads exactly like success.
221
+ * - `probe` — a URL built from values that were all present and well-formed.
222
+ *
223
+ * No default host and no default port. `|| 3000` is the same instinct as the
224
+ * `?? "/health"` this module already refuses: a guessed port is answered by
225
+ * whatever else holds it, and the run reports on a container it never found.
226
+ */
227
+ export type ContainerProbe =
228
+ | { kind: "unconfigured"; detail: string }
229
+ | { kind: "unmeasured"; detail: string }
230
+ | {
231
+ kind: "probe";
232
+ host: string;
233
+ port: number;
234
+ healthPath: string;
235
+ url: string;
236
+ safeUrl: string;
237
+ };
238
+
239
+ /**
240
+ * Hostname or IP literal, and nothing else.
241
+ *
242
+ * The host is interpolated into a `curl` command inside an agent prompt and
243
+ * is never shell-quoted there. This charset has no shell metacharacter, no
244
+ * `@` (so no userinfo can ride in) and no `:` (so no second port), which is
245
+ * also why `redactSecrets` has nothing to find in the authority half of the
246
+ * URL this builds. A host that does not match is not sanitised — it is
247
+ * refused, and the run says it was not probed.
248
+ */
249
+ export const CONTAINER_HOST = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
250
+
251
+ /**
252
+ * A character in `healthPath` that means something to a shell (#1031).
253
+ *
254
+ * Same set as `SHELL_METACHARACTERS` in `lib/workflow-security.ts`, and
255
+ * deliberately so: that is the set this project already decided reaches a
256
+ * shell unsafely, and a second, kinder set here would be a second answer to
257
+ * the same question.
258
+ *
259
+ * ## Why `healthPath` needs this when the config file is trusted
260
+ *
261
+ * `.claude/rungate/config.json` IS trusted. It is the operator's own file,
262
+ * `scripts/resolve-config.ts` is the only thing that reads it, and
263
+ * `container.rebuildCommand` is arbitrary command execution by design — a
264
+ * consumer who puts a destructive command behind that key has configured
265
+ * their own run to do that. Gating a trusted file against its own author is
266
+ * theatre, and #1031 names it as the cheapest wrong fix on offer.
267
+ *
268
+ * But the value that reaches the shell is not that file. `workflows/ship.js`
269
+ * cannot read files — the Workflow sandbox has no module loading (#69) — so
270
+ * the block it hands this function is `setupResult.config.container`: the
271
+ * **setup agent's restatement** of a file ship.js never sees, filtered on
272
+ * the way back by a JSON schema that constrains types and no values, and
273
+ * produced in a prompt that also carries issue-authored text. ship.js
274
+ * already names that channel for its neighbouring fields — *the reply agrees
275
+ * with whatever was put in it*, the #530 shape — and routes `harnessSha`
276
+ * through `rookReviewSha` rather than interpolating it, for this reason.
277
+ *
278
+ * So the trusted object and the interpolated object are different objects,
279
+ * and `healthPath` is the one free-form component of the URL this builds.
280
+ * `host` is already charset-filtered above and `port` is already a number;
281
+ * without this rule `/h;id` is an absolute path that is not `//`, so it
282
+ * becomes a `probe` and `;id` runs.
283
+ *
284
+ * REFUSED as `unmeasured`, never sanitised: a quietly repaired path probes a
285
+ * URL nobody configured and records the answer as the container's.
286
+ *
287
+ * ## Why this is narrower than `SHELL_METACHARACTERS`
288
+ *
289
+ * That set refuses `?`, `#`, `*`, `[`, `~` and `!`, and a health path is
290
+ * allowed all of them: `/h?token=…` is a shape this module already supports
291
+ * on purpose — `safeForRecord` exists to redact exactly that query string,
292
+ * and `SC-2485` asserts it. Refusing `?` here would delete a documented
293
+ * consumer shape to block a glob that the quoting added by #1031 at both
294
+ * `curl` sites already makes inert.
295
+ *
296
+ * What stays refused is the set no URL path needs and that ends a quoted
297
+ * shell word or starts a substitution: `;` `&` `|` `$` `` ` `` `"` `'` `\`
298
+ * `<` `>` `{` `}`, whitespace, and control characters. Every payload #1031
299
+ * named — `/h;id`, `/$(id)`, a backtick, `/h'` — is in it.
300
+ */
301
+ // eslint-disable-next-line no-control-regex
302
+ const CONTAINER_HEALTH_PATH_UNSAFE = /[;&|$`"'\\<>{}\s\u0000-\u001f]/;
303
+
304
+ export function containerProbeTarget(
305
+ container:
306
+ | { port?: unknown; healthPath?: unknown; hosts?: unknown; rebuildCommand?: unknown }
307
+ | null
308
+ | undefined,
309
+ ): ContainerProbe {
310
+ if (!container || typeof container !== "object") {
311
+ return {
312
+ kind: "unconfigured",
313
+ detail: "no container is configured for this project",
314
+ };
315
+ }
316
+ const hosts = Array.isArray(container.hosts) ? container.hosts : [];
317
+ const host = hosts.find(
318
+ (h: unknown) => typeof h === "string" && CONTAINER_HOST.test(h),
319
+ ) as string | undefined;
320
+ if (!host) {
321
+ return {
322
+ kind: "unmeasured",
323
+ detail:
324
+ "a container is configured and container.hosts names no host to reach it at, " +
325
+ "so nothing was probed. No host is guessed. This is UNMEASURED, not DOWN",
326
+ };
327
+ }
328
+ const port = container.port;
329
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) {
330
+ return {
331
+ kind: "unmeasured",
332
+ detail:
333
+ `a container is configured at ${host} and container.port is not a port number, ` +
334
+ "so nothing was probed. No default port is invented: a guessed port is answered " +
335
+ "by whatever else holds it. This is UNMEASURED, not DOWN",
336
+ };
337
+ }
338
+ const raw = container.healthPath;
339
+ const healthPath = raw === undefined || raw === null || raw === "" ? "/" : raw;
340
+ // The value is never quoted back. It is the one free-form component here,
341
+ // it reaches a durable artefact, and naming the key is what a reader needs.
342
+ if (
343
+ typeof healthPath !== "string" ||
344
+ !healthPath.startsWith("/") ||
345
+ healthPath.startsWith("//")
346
+ ) {
347
+ return {
348
+ kind: "unmeasured",
349
+ detail:
350
+ `a container is configured at ${host} port ${port} and container.healthPath is not ` +
351
+ "an absolute path, so nothing was probed. This is UNMEASURED, not DOWN",
352
+ };
353
+ }
354
+ // #1031 — see CONTAINER_HEALTH_PATH_UNSAFE. The refused value is NOT echoed
355
+ // into the detail: this string is interpolated into a `bun -e` program in an
356
+ // agent prompt and written to a durable artefact, which is the last place
357
+ // the thing we just refused should turn up.
358
+ if (healthPath.length > 200 || CONTAINER_HEALTH_PATH_UNSAFE.test(healthPath)) {
359
+ return {
360
+ kind: "unmeasured",
361
+ detail:
362
+ `a container is configured at ${host} port ${port} and container.healthPath carries ` +
363
+ "whitespace, a shell metacharacter or over 200 characters, so nothing was probed. " +
364
+ "It reaches a curl command an agent runs. This is UNMEASURED, not DOWN",
365
+ };
366
+ }
367
+ const url = `http://${host}:${port}${healthPath}`;
368
+ return { kind: "probe", host, port, healthPath, url, safeUrl: safeForRecord(url) };
369
+ }
370
+
191
371
  export function livenessPlan(
192
372
  acs: unknown,
193
373
  dev: { apiBase?: string; healthPath?: string; start?: string } | undefined,