rungate 0.2.0 → 0.3.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 (282) 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/canary.ts +117 -0
  11. package/lib/check-registry.ts +226 -0
  12. package/lib/ci-checkout.ts +400 -0
  13. package/lib/cli-commands.ts +137 -0
  14. package/lib/compliance-backfill.ts +220 -0
  15. package/lib/compliance-report.ts +504 -0
  16. package/lib/compliance.ts +361 -0
  17. package/lib/config-loader.ts +255 -0
  18. package/lib/conformity.ts +1818 -131
  19. package/lib/container-provenance.ts +230 -0
  20. package/lib/create-brief.ts +150 -0
  21. package/lib/create-sc.ts +272 -0
  22. package/lib/deep-merge.ts +69 -0
  23. package/lib/dev-liveness.ts +214 -0
  24. package/lib/directive-extractor.ts +210 -0
  25. package/lib/distribution-standing.ts +113 -0
  26. package/lib/doc-hygiene.ts +238 -0
  27. package/lib/eval-criteria.ts +6 -0
  28. package/lib/evidence-portability.ts +123 -0
  29. package/lib/evidence-prevalidator.ts +390 -0
  30. package/lib/evidence-required.ts +150 -0
  31. package/lib/evidence-satisfiability.ts +288 -0
  32. package/lib/frontmatter.ts +163 -0
  33. package/lib/gap-scanner.ts +348 -0
  34. package/lib/gate-enforcement.ts +366 -0
  35. package/lib/generators/agent-briefs.ts +136 -0
  36. package/lib/generators/agents-md.ts +506 -0
  37. package/lib/generators/code-map.ts +60 -0
  38. package/lib/generators/types.ts +184 -0
  39. package/lib/git-ref-normalizer.ts +107 -0
  40. package/lib/github.ts +539 -0
  41. package/lib/harness-identity.ts +63 -0
  42. package/lib/hill-climb.ts +164 -0
  43. package/lib/instruction-effectiveness.ts +131 -0
  44. package/lib/issue-closure-audit.ts +225 -0
  45. package/lib/issue-create-override.ts +343 -0
  46. package/lib/js-top-level-code.ts +250 -0
  47. package/lib/liveness-contradiction.ts +149 -0
  48. package/lib/organize.ts +505 -0
  49. package/lib/paths.ts +197 -6
  50. package/lib/post-fix-verify.ts +157 -0
  51. package/lib/prior-branch.ts +489 -0
  52. package/lib/project-state-shape.ts +166 -0
  53. package/lib/promote-outputs.ts +156 -0
  54. package/lib/prove-label-gate.ts +35 -0
  55. package/lib/reachability.ts +302 -0
  56. package/lib/release-preflight.ts +186 -0
  57. package/lib/rule-health-pipeline.ts +264 -0
  58. package/lib/rule-health-trend.ts +161 -0
  59. package/lib/rule-provenance.ts +149 -0
  60. package/lib/rule-registry.ts +128 -0
  61. package/lib/rungate-schema.ts +114 -4
  62. package/lib/sc-claim-forms.ts +179 -0
  63. package/lib/sc-cover.ts +150 -0
  64. package/lib/sc-guard.ts +157 -0
  65. package/lib/sc-ids.ts +344 -0
  66. package/lib/scaffold/defaults.ts +165 -0
  67. package/lib/scaffold/managed-workflow.ts +370 -0
  68. package/lib/scaffold/owned-files.ts +265 -0
  69. package/lib/scaffold/steps.ts +2680 -0
  70. package/lib/scanner.ts +701 -0
  71. package/lib/screenshot-upload.ts +73 -0
  72. package/lib/secret-patterns.ts +112 -0
  73. package/lib/security-verdict.ts +616 -0
  74. package/lib/signal-phrases.ts +1 -0
  75. package/lib/spec-change-conformity.ts +80 -0
  76. package/lib/spec-files.ts +62 -0
  77. package/lib/spec-registry.ts +133 -0
  78. package/lib/spec-updater.ts +96 -0
  79. package/lib/stale-cleanup.ts +224 -0
  80. package/lib/stale-issue-scanner.ts +36 -0
  81. package/lib/strip-js-comments.ts +269 -0
  82. package/lib/suite-measurement.ts +228 -0
  83. package/lib/task-completion-checks.ts +177 -0
  84. package/lib/test-suite-lock.ts +1136 -0
  85. package/lib/transcript-checker.ts +1140 -0
  86. package/lib/validators/spec-validators.ts +171 -0
  87. package/lib/verdict-capture.ts +73 -0
  88. package/lib/verified-push.ts +358 -0
  89. package/lib/workflow-security.ts +174 -0
  90. package/lib/worktree-cleanup.ts +250 -0
  91. package/lib/worktree-collect.ts +283 -0
  92. package/lib/worktree-isolation.ts +82 -0
  93. package/package.json +36 -3
  94. package/prompts/ac-adversary.md +14 -2
  95. package/prompts/aditi.md +5 -0
  96. package/prompts/blast-radius.md +5 -0
  97. package/prompts/container-verify.md +5 -0
  98. package/prompts/discovery.md +4 -0
  99. package/prompts/environment.md +5 -0
  100. package/prompts/evidence-hierarchy.md +5 -0
  101. package/prompts/evidence-validator.md +11 -0
  102. package/prompts/marcus.md +5 -0
  103. package/prompts/prevention.md +5 -0
  104. package/prompts/prove-reproducer.md +12 -0
  105. package/prompts/quinn-decision-tree.md +5 -0
  106. package/prompts/quinn-ui-brief.md +5 -0
  107. package/prompts/quinn.md +5 -0
  108. package/prompts/rca.md +5 -0
  109. package/prompts/read-before-write.md +4 -0
  110. package/prompts/regression.md +5 -0
  111. package/prompts/serena.md +5 -0
  112. package/scripts/audit-specs.ts +464 -0
  113. package/scripts/convert-spec.ts +293 -0
  114. package/scripts/create-sc.ts +92 -0
  115. package/scripts/create-spec.ts +166 -0
  116. package/scripts/extract-constraints.ts +4 -3
  117. package/scripts/generate-code-map.ts +1 -1
  118. package/scripts/scaffold-project.ts +138 -1426
  119. package/scripts/sync-spec-tests.ts +211 -126
  120. package/.claude/agents/aditi.md +0 -47
  121. package/.claude/agents/marcus.md +0 -50
  122. package/.claude/agents/quinn.md +0 -58
  123. package/.claude/agents/rook.md +0 -47
  124. package/.claude/agents/serena.md +0 -46
  125. package/.claude/rungate.json +0 -11
  126. package/.fallowrc.json +0 -28
  127. package/.github/copilot-instructions.md +0 -20
  128. package/.rungate/conformity-findings.json +0 -648
  129. package/AGENTS.md +0 -106
  130. package/CODE-MAP.md +0 -50
  131. package/HARNESS.md +0 -88
  132. package/bun.lock +0 -26
  133. package/bunfig.toml +0 -2
  134. package/config/brief-policies.json +0 -28
  135. package/config/ceremony-profiles.json +0 -212
  136. package/config/consumer-cascade-map.json +0 -24
  137. package/config/doc-cascade-map.json +0 -24
  138. package/config/eval.json +0 -84
  139. package/config/profiles/account-plan.yaml +0 -36
  140. package/config/profiles/campaign.yaml +0 -94
  141. package/config/prove-evidence.schema.json +0 -65
  142. package/config/spec-policies.json +0 -36
  143. package/config/workflow-schema.json +0 -281
  144. package/gates/SCHEMA-GUIDE.md +0 -121
  145. package/gates/ac-quality.test.ts +0 -106
  146. package/gates/adversarial.test.ts +0 -274
  147. package/gates/brief-assembler.test.ts +0 -429
  148. package/gates/brief-assembler.ts +0 -334
  149. package/gates/bunfig.toml +0 -2
  150. package/gates/chain.test.ts +0 -91
  151. package/gates/e2e-smoke.test.ts +0 -234
  152. package/gates/error-classifier.test.ts +0 -249
  153. package/gates/error-classifier.ts +0 -89
  154. package/gates/orchestrator.test.ts +0 -950
  155. package/gates/orchestrator.ts +0 -569
  156. package/gates/preload.ts +0 -77
  157. package/gates/prompts/ac-adversary.md +0 -20
  158. package/gates/prompts/evidence-validator.md +0 -22
  159. package/gates/prompts/prove-reproducer.md +0 -53
  160. package/gates/prove.test.ts +0 -164
  161. package/gates/run-gate.ts +0 -936
  162. package/gates/schema-parity.test.ts +0 -197
  163. package/gates/schema.ts +0 -362
  164. package/gates/self-heal.test.ts +0 -511
  165. package/gates/self-heal.ts +0 -121
  166. package/gates/ship-orchestrator.test.ts +0 -379
  167. package/gates/ship-orchestrator.ts +0 -363
  168. package/gates/test-fixtures/broken-no-environments.json +0 -60
  169. package/gates/test-fixtures/valid-standard.json +0 -54
  170. package/gates/test-utils.ts +0 -43
  171. package/gates/witness.ts +0 -220
  172. package/gates/workflow.test.ts +0 -1053
  173. package/hooks/AgentBriefGuard.hook.ts +0 -586
  174. package/hooks/AgentVerdictCapture.hook.ts +0 -134
  175. package/hooks/AutoVerifyGate.hook.ts +0 -76
  176. package/hooks/GateEnforcement.hook.ts +0 -273
  177. package/hooks/IssueCloseGuard.hook.ts +0 -116
  178. package/hooks/MergeGuard.hook.ts +0 -55
  179. package/hooks/StaleTTLCleanup.hook.ts +0 -133
  180. package/hooks/VerifyPhaseLock.hook.ts +0 -81
  181. package/hooks/WorkflowStateGuard.hook.ts +0 -37
  182. package/hooks/lib/agentDetection.ts +0 -70
  183. package/hooks/lib/findWorkflow.ts +0 -101
  184. package/hooks/lib/parseStdin.ts +0 -37
  185. package/hooks/lib/paths.ts +0 -111
  186. package/hooks/lib/utils.ts +0 -81
  187. package/reference/migration-manifest.json +0 -554
  188. package/reference/prompts/agent-aditi.md +0 -38
  189. package/reference/prompts/agent-marcus.md +0 -38
  190. package/reference/prompts/agent-quinn.md +0 -38
  191. package/reference/prompts/agent-rook.md +0 -37
  192. package/reference/prompts/agent-serena.md +0 -37
  193. package/reference/prompts/council-skill.md +0 -170
  194. package/reference/prompts/goal-skill.md +0 -235
  195. package/reference/prompts/prove-skill.md +0 -283
  196. package/reference/prompts/quinn-standard.md +0 -246
  197. package/reference/prompts/ship-convergence.md +0 -65
  198. package/reference/prompts/ship-escalation.md +0 -43
  199. package/reference/prompts/ship-iteration.md +0 -382
  200. package/reference/prompts/ship-pending-patches.md +0 -246
  201. package/reference/prompts/ship-reference.md +0 -250
  202. package/reference/prompts/ship-skill.md +0 -347
  203. package/reference/prompts/ship-templates.md +0 -215
  204. package/reference/scripts/batch-status.sh +0 -68
  205. package/reference/scripts/chain-compat-check.sh +0 -67
  206. package/reference/scripts/context-audit.sh +0 -314
  207. package/reference/scripts/dead-export-check.sh +0 -61
  208. package/reference/scripts/generate-qc-tables.sh +0 -92
  209. package/reference/scripts/harness-init.sh +0 -111
  210. package/reference/scripts/pai-054-baseline-check.sh +0 -40
  211. package/reference/scripts/prove-smoke-test.sh +0 -112
  212. package/reference/scripts/setup-keychain-salt.sh +0 -12
  213. package/reference/scripts/skill-optimizer-friday.sh +0 -88
  214. package/reference/scripts/skill-qc-test.sh +0 -351
  215. package/reference/scripts/skill-synthesize-tonight.sh +0 -66
  216. package/reference/specs/HARNESS-EXTRACTION-SPEC.md +0 -263
  217. package/reference/specs/harness-v3-bash-deletion-plan.md +0 -65
  218. package/reference/specs/harness-v3-migration-plan.md +0 -188
  219. package/scripts/decision-reconcile.sh +0 -74
  220. package/scripts/decision-reconcile.ts +0 -152
  221. package/scripts/git-hooks/pre-commit +0 -76
  222. package/scripts/git-hooks/pre-push +0 -271
  223. package/scripts/harness-skill-check.sh +0 -52
  224. package/scripts/lib/gap-emit.sh +0 -65
  225. package/scripts/lib/jq-update.sh +0 -30
  226. package/scripts/lib/resolve-slug.sh +0 -30
  227. package/scripts/lib/verify-spec-compliance.sh +0 -102
  228. package/scripts/prove-backfill.sh +0 -87
  229. package/scripts/scaffold-rungate-config.ts +0 -91
  230. package/scripts/self-containment-check.sh +0 -109
  231. package/scripts/skill-qc-validator.sh +0 -402
  232. package/scripts/slug-resolver.sh +0 -14
  233. package/specs/BOOTSTRAP-DATA-FLOW-SPEC.md +0 -2493
  234. package/specs/BOOTSTRAP-TEST-PLAN.md +0 -571
  235. package/specs/HARNESS-GATES.md +0 -256
  236. package/specs/HARNESS-SKILL-CHAIN.md +0 -286
  237. package/specs/HARNESS-SKILL-CONTRACT.md +0 -93
  238. package/specs/HARNESS-STANDARD.md +0 -488
  239. package/specs/SPEC-TEMPLATE.md +0 -53
  240. package/specs/bootstrap-data-flow.png +0 -0
  241. package/specs/harness-automation-matrix.md +0 -314
  242. package/specs/harness-automation-matrix.rules.json +0 -64
  243. package/test/anti.test.ts +0 -80
  244. package/test/contract-negative.test.ts +0 -86
  245. package/test/contract.test.ts +0 -158
  246. package/test/external-deps.test.ts +0 -48
  247. package/test/fixtures/golden-project/.env.example +0 -3
  248. package/test/fixtures/golden-project/Makefile +0 -7
  249. package/test/fixtures/golden-project/docs/adr/ADR-001-framework.md +0 -23
  250. package/test/fixtures/golden-project/docs/setup-guide.md +0 -10
  251. package/test/fixtures/golden-project/package.json +0 -10
  252. package/test/fixtures/golden-project/specs/api-spec.md +0 -20
  253. package/test/fixtures/golden-project/src/auth.ts +0 -8
  254. package/test/fixtures/golden-project/src/db.ts +0 -11
  255. package/test/fixtures/golden-project/src/index.ts +0 -19
  256. package/test/fixtures/golden-project/src/utils/format.ts +0 -3
  257. package/test/fixtures/golden-project/test/auth.test.ts +0 -15
  258. package/test/fixtures/golden-project/tsconfig.json +0 -12
  259. package/test/meta-sc-coverage.test.ts +0 -159
  260. package/test/phase-0.test.ts +0 -846
  261. package/test/phase-1.test.ts +0 -617
  262. package/test/phase-2.test.ts +0 -620
  263. package/test/phase-3.test.ts +0 -99
  264. package/test/scaffold-conformity.test.ts +0 -8
  265. package/test/schema-canary.test.ts +0 -51
  266. package/test/spec-compliance-auto.test.ts +0 -64
  267. package/test/spec-compliance.test.ts +0 -295
  268. package/test/spec-discovery.test.ts +0 -68
  269. package/test/spec-drift.test.ts +0 -5
  270. package/test/structure.test.ts +0 -165
  271. package/test/unit/agent-brief-guard-ship.test.ts +0 -293
  272. package/test/unit/extract-constraints.test.ts +0 -145
  273. package/test/unit/issue-close-guard.test.ts +0 -204
  274. package/test/unit/scaffold-project.test.ts +0 -417
  275. package/test/unit/skill-cooccurrence.test.ts +0 -177
  276. package/test/unit/skill-sequence-logger.test.ts +0 -244
  277. package/test/unit/workflow-state-guard.test.ts +0 -95
  278. package/workflows/batch-ship.js +0 -295
  279. package/workflows/council.js +0 -481
  280. package/workflows/prove.js +0 -560
  281. package/workflows/ship.js +0 -789
  282. package/workflows/verify.js +0 -236
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Result of deep-merging `U` (the override) into `T` (the base).
3
+ *
4
+ * Mirrors the runtime rules below:
5
+ * - arrays are replaced wholesale, so an array override wins outright
6
+ * - two plain objects merge key-by-key, keeping base-only keys
7
+ * - anything else (primitives, null) is replaced by the override value
8
+ */
9
+ export type DeepMerge<T, U> = U extends readonly unknown[]
10
+ ? U
11
+ : T extends readonly unknown[]
12
+ ? U
13
+ : [T, U] extends [object, object]
14
+ ? {
15
+ [K in keyof T | keyof U]: K extends keyof U
16
+ ? K extends keyof T
17
+ ? DeepMerge<T[K], U[K]>
18
+ : U[K]
19
+ : K extends keyof T
20
+ ? T[K]
21
+ : never;
22
+ }
23
+ : U;
24
+
25
+ function isMergeableObject(value: unknown): value is Record<string, unknown> {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+
29
+ /**
30
+ * Deep merge two objects. Arrays are replaced, not concatenated.
31
+ * Objects are recursively merged. Primitives in override win.
32
+ *
33
+ * The override is typed independently of the base so partial nested overrides
34
+ * (and overrides that change a key's type, e.g. null -> number) are accepted,
35
+ * and the return type describes the actual merged shape.
36
+ */
37
+ export function deepMerge<
38
+ T extends Record<string, unknown>,
39
+ U extends Record<string, unknown>,
40
+ >(base: T, override: U): DeepMerge<T, U> {
41
+ const result: Record<string, unknown> = { ...base };
42
+ const overrideRecord: Record<string, unknown> = override;
43
+
44
+ for (const key in overrideRecord) {
45
+ const overrideValue = overrideRecord[key];
46
+ const baseValue = result[key];
47
+
48
+ if (overrideValue === undefined) {
49
+ continue;
50
+ }
51
+
52
+ // Arrays: replace, don't concat
53
+ if (Array.isArray(overrideValue)) {
54
+ result[key] = overrideValue;
55
+ continue;
56
+ }
57
+
58
+ // Objects: recurse
59
+ if (isMergeableObject(overrideValue) && isMergeableObject(baseValue)) {
60
+ result[key] = deepMerge(baseValue, overrideValue);
61
+ continue;
62
+ }
63
+
64
+ // Primitives and null: override wins
65
+ result[key] = overrideValue;
66
+ }
67
+
68
+ return result as DeepMerge<T, U>;
69
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * #304 — the dev-server liveness probe had a consumer's route baked into it.
3
+ *
4
+ * `gates/gate-executor.ts` curled a literal:
5
+ *
6
+ * execSync(`curl -sf ${apiBase}/api/admin/health`, …)
7
+ *
8
+ * `apiBase` came from config. `/api/admin/health` did not — it is one
9
+ * consumer's endpoint, written into the harness. The probe only runs for a
10
+ * project that sets `dev.apiBase` and has a server-dependent OUTCOME AC, and
11
+ * rungate sets no `dev` key at all, so it has never executed on a self-run.
12
+ * The only project that has reached the line is the one whose route it
13
+ * happens to be. (The consumer is named in #304, not here: `test/anti.test.ts`
14
+ * SC-A1 refuses the name anywhere under `lib/`, and it is right to.)
15
+ *
16
+ * The first consumer with a different health route would get:
17
+ *
18
+ * dev-server-liveness: OUTCOME ACs require running dev server — FAIL
19
+ * <apiBase> not responding — run 'make dev-all' first
20
+ *
21
+ * on a server that is up. A false FAIL naming the wrong cause is worse than
22
+ * no check, because the stated remedy is to start something already running.
23
+ *
24
+ * ## No default path
25
+ *
26
+ * The temptation is `dev.healthPath ?? "/health"`, and it is the wrong
27
+ * instinct for the same reason the hardcoded route was. A guessed path on a
28
+ * healthy server 404s, `curl -sf` exits non-zero, and the probe reports DOWN.
29
+ * **Unconfigured has to mean UNMEASURED**, which here means "do not probe and
30
+ * say so" — the distinction #185 drew for `mergedIntoBase`, in the direction
31
+ * that matters: reporting DOWN looks fail-closed and is simply wrong, and it
32
+ * blocks a correct run.
33
+ *
34
+ * ## Shape
35
+ *
36
+ * `livenessPlan` is pure: config in, decision out, no network. Every branch
37
+ * — including the ones DDB's config never reaches — is exercisable without a
38
+ * server. `probeLiveness` performs the one it returns.
39
+ */
40
+
41
+ import { redactSecrets } from "./verified-push";
42
+
43
+ export type LivenessPlan =
44
+ /** Nothing to probe: no server-dependent OUTCOME AC in this run. */
45
+ | { kind: "not-applicable"; detail: string }
46
+ /** A probe is wanted and the config does not say where to look. */
47
+ | { kind: "unmeasured"; detail: string }
48
+ /** Probe `url`; print and record `safeUrl`, which never carries credentials. */
49
+ | { kind: "probe"; url: string; safeUrl: string; startHint: string };
50
+
51
+ /** True when any AC's evidence needs a server standing up to produce it. */
52
+ export const SERVER_DEPENDENT_EVIDENCE = ["PLAYWRIGHT", "HTTP", "CURL", "SCREENSHOT"] as const;
53
+
54
+ export function hasServerDependentOutcomeAC(acs: unknown): boolean {
55
+ if (!Array.isArray(acs)) return false;
56
+ return acs.some((ac: any) => {
57
+ const type = ac?.evidenceMethod?.type;
58
+ return ac?.type === "OUTCOME" && typeof type === "string" &&
59
+ (SERVER_DEPENDENT_EVIDENCE as readonly string[]).includes(type.toUpperCase());
60
+ });
61
+ }
62
+
63
+ /**
64
+ * A URL this module is willing to hand to a subprocess.
65
+ *
66
+ * Both halves come out of the consumer's own `rungate.json`, and the old call
67
+ * site interpolated them into a shell string. The invocation is argv-form
68
+ * now, so this is the second defence rather than the only one — but a probe
69
+ * that follows a `file://` or an arbitrary scheme is a different problem from
70
+ * quoting, and this is where it is refused.
71
+ */
72
+ const ALLOWED_SCHEMES = new Set(["http:", "https:"]);
73
+
74
+ export function livenessUrl(apiBase: string, healthPath: string): string | null {
75
+ let base: URL;
76
+ try {
77
+ base = new URL(apiBase);
78
+ } catch {
79
+ return null;
80
+ }
81
+ if (!ALLOWED_SCHEMES.has(base.protocol)) return null;
82
+ if (!healthPath.startsWith("/")) return null;
83
+ // A `//`-prefixed path is protocol-relative, not a path. Refused by name
84
+ // rather than caught by the origin check below, because the two differ in
85
+ // what they would do with it and only one of them is obvious to a reader.
86
+ if (healthPath.startsWith("//")) return null;
87
+
88
+ // Appended to the base's own path, NOT resolved against it.
89
+ //
90
+ // `new URL("/health", "http://host/base/api")` yields `http://host/health`
91
+ // — the base path is silently discarded. A consumer whose API is mounted
92
+ // under a prefix would be probed at the wrong place and reported DOWN on a
93
+ // healthy server, which is the bug this whole module exists to remove,
94
+ // reintroduced by URL resolution semantics. Found by the security review
95
+ // of the first version of this fix, which did resolve.
96
+ const joined = base.pathname.replace(/\/+$/, "") + healthPath;
97
+ let url: URL;
98
+ try {
99
+ url = new URL(joined, base);
100
+ } catch {
101
+ return null;
102
+ }
103
+ // Still checked, because `..` in the path can climb and a stray scheme can
104
+ // appear. Appending removes the protocol-relative case, not every case.
105
+ if (url.origin !== base.origin) return null;
106
+ if (!url.pathname.startsWith(base.pathname.replace(/\/+$/, "") + "/")) return null;
107
+ return url.toString();
108
+ }
109
+
110
+ /**
111
+ * Where to probe a given tier, or why not.
112
+ *
113
+ * This exists because `checkDevServerLiveness` was not the only site. The
114
+ * prove gate curled the same hardcoded route twice more — once against
115
+ * `dev.apiBase` behind a `process.exit(1)`, once against `prod.apiBase`
116
+ * behind a warning — and neither was named in #304. The grep in
117
+ * test/dev-liveness.test.ts found them, which is the whole argument for
118
+ * writing it. Fixing one call site and leaving two would have left the issue
119
+ * closed and the bug shipping.
120
+ *
121
+ * One function so "unconfigured is UNMEASURED, never DOWN" is decided once.
122
+ */
123
+ /**
124
+ * Everything that may be printed or recorded goes through this, never through
125
+ * `redactSecrets` alone.
126
+ *
127
+ * Second security round. `redactSecrets` covers userinfo and bare GitHub
128
+ * tokens; it does not touch a query string, and a health route is exactly
129
+ * where a consumer puts `?access_token=…`. Both the probe URL and the
130
+ * "these do not combine" detail quoted `healthPath` verbatim.
131
+ *
132
+ * Every query VALUE is blanked rather than the ones whose key looks secret.
133
+ * A key list is a detector narrower than what it detects — it needs updating
134
+ * for the next consumer's naming, and nothing goes red when it is not. The
135
+ * query is never needed to identify which URL was probed; origin and path
136
+ * are, and they survive.
137
+ */
138
+ export function safeForRecord(text: string): string {
139
+ return redactSecrets(text).replace(
140
+ /([?&][A-Za-z0-9_.\[\]%-]+=)[^&\s)'"`]+/g,
141
+ "$1<redacted>",
142
+ );
143
+ }
144
+
145
+ export type ProbeTarget =
146
+ | { kind: "unmeasured"; detail: string }
147
+ | { kind: "probe"; url: string; safeUrl: string };
148
+
149
+ export function probeTarget(
150
+ tier: string,
151
+ cfg: { apiBase?: string | null; healthPath?: string | null } | undefined,
152
+ ): ProbeTarget {
153
+ const apiBase = cfg?.apiBase;
154
+ const healthPath = cfg?.healthPath;
155
+ if (!apiBase) {
156
+ return {
157
+ kind: "unmeasured",
158
+ detail: `the project sets no \`${tier}.apiBase\`, so liveness was not checked. This is UNMEASURED, not UP.`,
159
+ };
160
+ }
161
+ if (!healthPath) {
162
+ return {
163
+ kind: "unmeasured",
164
+ detail: safeForRecord(
165
+ `the project sets no \`${tier}.healthPath\`, so liveness at ${apiBase} was not ` +
166
+ `checked. No path is guessed on purpose (#304): a guessed route 404s on a healthy ` +
167
+ `server, and reporting DOWN for a server that is up blocks a correct run and names ` +
168
+ `the wrong cause. This is UNMEASURED, not DOWN.`,
169
+ ),
170
+ };
171
+ }
172
+ const url = livenessUrl(apiBase, healthPath);
173
+ if (!url) {
174
+ return {
175
+ kind: "unmeasured",
176
+ detail: safeForRecord(
177
+ `\`${tier}.apiBase\` (${apiBase}) and \`${tier}.healthPath\` (${healthPath}) do not ` +
178
+ `combine into an http(s) URL on the same origin, so liveness was not checked.`,
179
+ ),
180
+ };
181
+ }
182
+ // Two fields on purpose. `url` is what curl is handed and may carry
183
+ // credentials the consumer put in `apiBase` deliberately; `safeUrl` is the
184
+ // only one that may be printed or recorded. The gate's `detail` lands in
185
+ // ship-evidence.json, which is durable and gets attached to issues — the
186
+ // same leak #213 found in push `detail`, and the reason redactSecrets is
187
+ // imported rather than written again here.
188
+ return { kind: "probe", url, safeUrl: safeForRecord(url) };
189
+ }
190
+
191
+ export function livenessPlan(
192
+ acs: unknown,
193
+ dev: { apiBase?: string; healthPath?: string; start?: string } | undefined,
194
+ ): LivenessPlan {
195
+ if (!hasServerDependentOutcomeAC(acs)) {
196
+ return {
197
+ kind: "not-applicable",
198
+ detail: "no OUTCOME AC needs a running server, so there is nothing to probe.",
199
+ };
200
+ }
201
+ const target = probeTarget("dev", dev);
202
+ if (target.kind === "unmeasured") {
203
+ return {
204
+ kind: "unmeasured",
205
+ detail: `this run has OUTCOME ACs that need a running server and ${target.detail}`,
206
+ };
207
+ }
208
+ return {
209
+ kind: "probe",
210
+ url: target.url,
211
+ safeUrl: target.safeUrl,
212
+ startHint: dev?.start || "the project's dev-server start command",
213
+ };
214
+ }
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Directive extractor — parses agent brief markdown for actionable instructions.
3
+ *
4
+ * Extracts Read X, Run Y, Never Z, Always W patterns mechanically
5
+ * from brief markdown content and applicable .claude/rules/ files.
6
+ *
7
+ * SC-401: Directive extractor parses brief mechanically
8
+ */
9
+ import { existsSync, readFileSync, readdirSync } from "fs";
10
+ import { join } from "path";
11
+
12
+ export type DirectiveType = "read" | "run" | "never" | "always";
13
+ export type DirectiveCategory = "quality" | "process";
14
+
15
+ export interface Directive {
16
+ text: string;
17
+ type: DirectiveType;
18
+ category: DirectiveCategory;
19
+ line: number;
20
+ section: string;
21
+ target?: string;
22
+ }
23
+
24
+ const PROCESS_SECTIONS = new Set([
25
+ "context",
26
+ "always do",
27
+ "ask first",
28
+ ]);
29
+
30
+ function sectionCategory(section: string, processOverrides: string[]): (text: string) => DirectiveCategory {
31
+ const sectionKey = section.toLowerCase().replace(/\s*\(.*\)/, "").trim();
32
+ const isProcessSection = PROCESS_SECTIONS.has(sectionKey);
33
+ return (text: string): DirectiveCategory => {
34
+ if (isProcessSection) return "process";
35
+ const normalizedText = text.toLowerCase().replace(/[`*"']/g, "");
36
+ if (processOverrides.some(o => normalizedText.includes(o.toLowerCase().replace(/[`*"']/g, "")))) return "process";
37
+ return "quality";
38
+ };
39
+ }
40
+
41
+ function parseProcessOverrides(content: string): string[] {
42
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
43
+ if (!fmMatch) return [];
44
+ const lines = fmMatch[1].split("\n");
45
+ let inOverrides = false;
46
+ const overrides: string[] = [];
47
+ for (const line of lines) {
48
+ if (/^process_overrides:\s*$/.test(line)) { inOverrides = true; continue; }
49
+ if (inOverrides && /^\s+-\s+/.test(line)) {
50
+ overrides.push(line.replace(/^\s+-\s+["']?/, "").replace(/["']?\s*$/, ""));
51
+ } else if (inOverrides && !/^\s+/.test(line)) {
52
+ inOverrides = false;
53
+ }
54
+ }
55
+ return overrides;
56
+ }
57
+
58
+ // ── Pattern matchers ──────────────────────────────────────
59
+
60
+ const FILE_EXT = /\.(?:md|ts|json|yml|yaml|js|toml|sh)$/;
61
+ const READ_PATTERN = /(?:Read|read)\s+[`"*]*([^\s`"*]+(?:\.(?:md|ts|json|yml|yaml|js|toml|sh)))[`"*]*/;
62
+ const BOLD_FILE_PATTERN = /\*\*([^\s*]+(?:\.(?:md|ts|json)))\*\*/;
63
+ const BACKTICK_PATH_PATTERN = /[`]([^\s`]+(?:\.(?:md|ts|json|yml|yaml)))[`]/;
64
+ const RUN_PATTERN = /(?:Run|run)\s+[`]([^`]+)[`]/;
65
+ const BUN_TEST_PATTERN = /`(bun test[^`]*)`/;
66
+ const TSC_PATTERN = /`(bunx? tsc[^`]*)`/;
67
+
68
+ function isFilePath(s: string): boolean {
69
+ return s.includes("/") || FILE_EXT.test(s);
70
+ }
71
+
72
+ // ── Extraction ────────────────────────────────────────────
73
+
74
+ export function extractDirectives(briefContent: string): Directive[] {
75
+ const directives: Directive[] = [];
76
+ const lines = briefContent.split("\n");
77
+ let currentSection = "top";
78
+ const processOverrides = parseProcessOverrides(briefContent);
79
+ let getCategory = sectionCategory("top", processOverrides);
80
+
81
+ for (let i = 0; i < lines.length; i++) {
82
+ const line = lines[i];
83
+ const lineNum = i + 1;
84
+
85
+ // Track sections
86
+ if (line.startsWith("## ")) {
87
+ currentSection = line.replace("## ", "").trim();
88
+ getCategory = sectionCategory(currentSection, processOverrides);
89
+ continue;
90
+ }
91
+
92
+ // Skip comments and blank lines
93
+ if (line.startsWith("//") || line.startsWith("#") || !line.trim()) continue;
94
+
95
+ const sectionLower = currentSection.toLowerCase();
96
+ const trimmedLine = line.trim().replace(/^[-\d.]+\s*/, "");
97
+ const plainLine = trimmedLine.replace(/^\*{1,2}/, "");
98
+
99
+ // ── Never classification (HIGHEST PRIORITY — before all content patterns) ──
100
+ // Priority 1: Lines starting with "Never" regardless of section or content
101
+ // Strip leading bold markers (**) so "**NEVER use cat..." still matches
102
+ if (/^never\b/i.test(plainLine) && !directives.some(d => d.line === lineNum)) {
103
+ directives.push({ text: trimmedLine, type: "never", category: getCategory(trimmedLine), line: lineNum, section: currentSection });
104
+ continue;
105
+ }
106
+
107
+ // Priority 2: All bullet items in "Never Do" or "Additional Never Do" sections
108
+ if ((sectionLower.includes("never") || sectionLower.includes("additional never")) && line.trim().startsWith("- ")) {
109
+ if (!directives.some(d => d.line === lineNum)) {
110
+ directives.push({ text: trimmedLine, type: "never", category: getCategory(trimmedLine), line: lineNum, section: currentSection });
111
+ continue;
112
+ }
113
+ }
114
+
115
+ // ── Read patterns ──
116
+ // Read X patterns — "Read `file`", "Read file.md", numbered items with file refs
117
+ const readMatch = line.match(READ_PATTERN);
118
+ if (readMatch) {
119
+ const target = readMatch[1].replace(/[`"*]/g, "");
120
+ if (isFilePath(target)) {
121
+ directives.push({ text: trimmedLine, type: "read", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target });
122
+ }
123
+ }
124
+
125
+ // Context section numbered items — "1. **AGENTS.md** — MANDATORY"
126
+ if (sectionLower.includes("context") && /^\d+\./.test(line.trim())) {
127
+ const boldMatch = line.match(BOLD_FILE_PATTERN);
128
+ const pathMatch = line.match(BACKTICK_PATH_PATTERN);
129
+ const target = boldMatch?.[1] || pathMatch?.[1];
130
+ if (target && !directives.some(d => d.line === lineNum)) {
131
+ directives.push({ text: trimmedLine, type: "read", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target });
132
+ }
133
+ }
134
+
135
+ // Before writing code / Before reporting done sections with file refs
136
+ if ((sectionLower.includes("before") || sectionLower.includes("reference")) && /^\d+\./.test(line.trim())) {
137
+ const boldMatch = line.match(BOLD_FILE_PATTERN);
138
+ const pathMatch = line.match(BACKTICK_PATH_PATTERN);
139
+ const target = boldMatch?.[1] || pathMatch?.[1];
140
+ if (target && !directives.some(d => d.line === lineNum)) {
141
+ directives.push({ text: trimmedLine, type: "read", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target });
142
+ }
143
+ }
144
+
145
+ // ── Run patterns (only after never checks pass) ──
146
+ const runMatch = line.match(RUN_PATTERN);
147
+ if (runMatch && !directives.some(d => d.line === lineNum)) {
148
+ directives.push({ text: trimmedLine, type: "run", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target: runMatch[1] });
149
+ }
150
+
151
+ // Inline bun test pattern
152
+ const bunTestMatch = line.match(BUN_TEST_PATTERN);
153
+ if (bunTestMatch && !directives.some(d => d.line === lineNum)) {
154
+ directives.push({ text: trimmedLine, type: "run", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target: bunTestMatch[1] });
155
+ }
156
+
157
+ // tsc --noEmit pattern
158
+ const tscMatch = line.match(TSC_PATTERN);
159
+ if (tscMatch && !directives.some(d => d.line === lineNum)) {
160
+ directives.push({ text: trimmedLine, type: "run", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target: tscMatch[1] });
161
+ }
162
+
163
+ // Always patterns — in "Always Do" or "Always" sections
164
+ if (sectionLower.includes("always") && line.trim().startsWith("- ")) {
165
+ if (!directives.some(d => d.line === lineNum)) {
166
+ directives.push({ text: trimmedLine, type: "always", category: getCategory(trimmedLine), line: lineNum, section: currentSection });
167
+ }
168
+ }
169
+
170
+ // Core Principles section — treat as "always"
171
+ if (sectionLower.includes("core principles") && line.trim().startsWith("- ")) {
172
+ if (!directives.some(d => d.line === lineNum)) {
173
+ directives.push({ text: trimmedLine, type: "always", category: getCategory(trimmedLine), line: lineNum, section: currentSection });
174
+ }
175
+ }
176
+
177
+ // Rules section — treat bullet points as "always"
178
+ if (sectionLower.includes("rules") && line.trim().startsWith("- ")) {
179
+ if (!directives.some(d => d.line === lineNum)) {
180
+ directives.push({ text: trimmedLine, type: "always", category: getCategory(trimmedLine), line: lineNum, section: currentSection });
181
+ }
182
+ }
183
+
184
+ // Items in "Before writing code" or "Before reporting done" sections
185
+ if (sectionLower.includes("before") && /^\d+\.\s/.test(line.trim())) {
186
+ const match = line.match(RUN_PATTERN) || line.match(BUN_TEST_PATTERN) || line.match(TSC_PATTERN);
187
+ if (match && !directives.some(d => d.line === lineNum)) {
188
+ directives.push({ text: trimmedLine, type: "run", category: getCategory(trimmedLine), line: lineNum, section: currentSection, target: match[1] });
189
+ }
190
+ }
191
+ }
192
+
193
+ return directives;
194
+ }
195
+
196
+ export function extractDirectivesWithRules(briefContent: string, projectRoot: string): Directive[] {
197
+ const rulesDir = join(projectRoot, ".claude", "rules");
198
+ let combined = briefContent;
199
+ if (existsSync(rulesDir)) {
200
+ for (const f of readdirSync(rulesDir).filter(f => f.endsWith(".md"))) {
201
+ const content = readFileSync(join(rulesDir, f), "utf-8");
202
+ const hasPaths = /^paths:/m.test(content);
203
+ if (!hasPaths) {
204
+ const body = content.replace(/^---[\s\S]*?---\n*/, "");
205
+ combined += "\n" + body;
206
+ }
207
+ }
208
+ }
209
+ return extractDirectives(combined);
210
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * What `SUCCESS.md` claims about the distributed artifact, and whether it is
3
+ * still true (#366).
4
+ *
5
+ * Every mutation count, gate measurement and standing verdict in `SUCCESS.md`
6
+ * was taken against the working tree at `main`. The published artifact is
7
+ * `rungate@0.2.1`, and `main` is several hundred commits past it. **The
8
+ * evidence base and the installable artifact are different software**, and
9
+ * nothing in the file said so.
10
+ *
11
+ * It matters most where the file is weakest. `SUCCESS.md`'s consumer survey
12
+ * of 2026-10-08 returned a verdict of *not ready* — against code no consumer
13
+ * can obtain. That is the one deliberate attempt to assess claim 5, and it
14
+ * is unattributable to any shippable version. The claim-5 row argues, of the
15
+ * distribution path among others, that *"a path nothing has executed is not
16
+ * a path anyone understands."*
17
+ *
18
+ * `SUCCESS.md` is also the measure for filing issues, reviewing PRs and
19
+ * running audits, so a standing table that silently describes unpublished
20
+ * code hands that gap to every decision routed through it.
21
+ *
22
+ * ## Why two numbers and not one
23
+ *
24
+ * The issue named the vacuous form by name: *"An assertion that merely finds
25
+ * **a** version string in the file is the vacuous form and passes over this
26
+ * defect today."* It also named the mutation that has to turn it red —
27
+ * *"bumping `package.json` without publishing must turn it red"* — and that
28
+ * one is only catchable if the file records BOTH versions. Checking the
29
+ * recorded published version against the registry alone stays green through
30
+ * a version bump, because the bump does not move either of those two values.
31
+ */
32
+ export interface DistributionStanding {
33
+ /** The version the standing measurements were taken against. */
34
+ tree: string;
35
+ /** The version a consumer can actually install. */
36
+ published: string;
37
+ /** The date the line was written, `YYYY-MM-DD`. */
38
+ measured: string;
39
+ }
40
+
41
+ /**
42
+ * The one line in `SUCCESS.md` that records it, in the form the file writes.
43
+ *
44
+ * Anchored to a list item so prose discussing a version cannot be mistaken
45
+ * for the record — the same reason `.claude/rules/claiming-sc-coverage.md`
46
+ * asks for a declaring position. A file is allowed to talk about 0.2.1 in a
47
+ * sentence without that becoming the standing.
48
+ */
49
+ const STANDING_LINE =
50
+ /^-\s+\*\*Distribution standing\s*\((\d{4}-\d{2}-\d{2})\)\*\*\s*—\s*tree `([^`]+)`, published `rungate@([^`]+)`/m;
51
+
52
+ export function parseDistributionStanding(successMd: string): DistributionStanding | null {
53
+ const m = STANDING_LINE.exec(successMd);
54
+ return m ? { measured: m[1], tree: m[2], published: m[3] } : null;
55
+ }
56
+
57
+ /**
58
+ * What the registry says is installable right now.
59
+ *
60
+ * Deliberately not `npm view`: the registry's own JSON endpoint needs no npm
61
+ * CLI on the path and no lockfile, so the check measures the same thing on a
62
+ * laptop and on CI. A failure here THROWS rather than returning a fallback —
63
+ * an unreachable registry is an unmeasured check, and a check that reports
64
+ * "no problems found" when it could not look is the fail-open shape
65
+ * `.claude/rules/checks-must-be-able-to-fail.md` opens with.
66
+ */
67
+ export async function publishedVersion(
68
+ pkg: string,
69
+ fetchImpl: typeof fetch = fetch,
70
+ ): Promise<string> {
71
+ const res = await fetchImpl(`https://registry.npmjs.org/${pkg}/latest`);
72
+ if (!res.ok) throw new Error(`registry returned ${res.status} for ${pkg}`);
73
+ const body = (await res.json()) as { version?: unknown };
74
+ if (typeof body.version !== "string") {
75
+ throw new Error(`registry returned no version for ${pkg}`);
76
+ }
77
+ return body.version;
78
+ }
79
+
80
+ /**
81
+ * The single place that turns the three readings into a list of violations.
82
+ *
83
+ * One exported function on purpose, so there is one binding to mutate. A
84
+ * second comparison of the same facts elsewhere would survive any mutation
85
+ * of this one and the guard would go green for a reason unrelated to it
86
+ * working.
87
+ */
88
+ export function distributionViolations(
89
+ standing: DistributionStanding | null,
90
+ treeVersion: string,
91
+ publishedNow: string,
92
+ ): string[] {
93
+ if (standing === null) {
94
+ return [
95
+ "SUCCESS.md records no distribution standing — every number in it describes " +
96
+ "a tree, and nothing says which tree a consumer can install",
97
+ ];
98
+ }
99
+ const out: string[] = [];
100
+ if (standing.tree !== treeVersion) {
101
+ out.push(
102
+ `SUCCESS.md says its measurements were taken against ${standing.tree}, ` +
103
+ `package.json says the tree is ${treeVersion} — the standing describes code that moved`,
104
+ );
105
+ }
106
+ if (standing.published !== publishedNow) {
107
+ out.push(
108
+ `SUCCESS.md says rungate@${standing.published} is published, the registry says ` +
109
+ `${publishedNow} — the file's account of what a consumer can install is stale`,
110
+ );
111
+ }
112
+ return out;
113
+ }