rungate 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Dependency order for decomposed sub-issues (#189).
3
+ *
4
+ * `workflows/ship.js` asked the decomposer for "sub-issues in dependency order
5
+ * (foundations first)", gave it nowhere in the schema to record the answer,
6
+ * and dispatched every sub-issue at once. The ordering was produced, accepted
7
+ * and discarded — #166's shape exactly: **an instruction the agent can follow
8
+ * perfectly without its output changing anything.**
9
+ *
10
+ * ## The run this comes from
11
+ *
12
+ * `wf_92dbb346-949` (#105) decomposed into four sub-issues with genuinely
13
+ * disjoint file claims, which is all `ship.js` validated. The dependency was
14
+ * not in the files — it was in the API. Sub-issue 1 was building
15
+ * `harnessRootFor()` in `lib/paths.ts`; sub-issue 4 needed to call it and
16
+ * could not see sub-issue 1, so it wrote its own:
17
+ *
18
+ * | worktree | signature | behaviour |
19
+ * |---|---|---|
20
+ * | `-5` | `harnessRootFor(root: string)` | resolves the root the caller names |
21
+ * | `-8` | `harnessRootFor(dir: string)` | walks up looking for `HARNESS.md` |
22
+ *
23
+ * Two functions, one name, one file, opposite contracts. Both defensible,
24
+ * both carefully commented, neither author aware of the other. Eight agents,
25
+ * 77 minutes, four worktrees of good work that cannot be combined.
26
+ *
27
+ * ## Why file-disjointness is the wrong test
28
+ *
29
+ * File overlap detects MERGE conflicts. It does not detect SEMANTIC
30
+ * dependencies, and two sub-issues can hold disjoint files and still be
31
+ * ordered whenever one creates something the other consumes: a function, an
32
+ * exported type, a config key one writes and the other reads, a test helper,
33
+ * a CLI flag. The overlap check stays — it catches a different thing and both
34
+ * are needed (#189 AC-3).
35
+ *
36
+ * ## The direction this is allowed to be wrong in
37
+ *
38
+ * Toward REFUSING, never toward running anyway. A cycle, a reference to a
39
+ * sub-issue that does not exist, and a self-dependency all refuse. Falling
40
+ * back to parallel on a dependency it could not read is the fail-open shape
41
+ * `.claude/rules/checks-must-be-able-to-fail.md` opens with, and it would
42
+ * reproduce `wf_92dbb346-949` exactly while reporting that it had scheduled
43
+ * the work.
44
+ */
45
+
46
+ export interface WaveSubIssue {
47
+ title: string;
48
+ /** Titles of sub-issues that must finish first. Absent means none. */
49
+ dependsOn?: string[] | null;
50
+ }
51
+
52
+ export interface WavePlan {
53
+ /** Indexes into the input array, grouped. Everything in a wave is parallel. */
54
+ waves: number[][];
55
+ /** One line per wave that is not the first, saying what it waited for. */
56
+ reasons: string[];
57
+ /** Non-null when no order exists; `waves` is empty and nothing may run. */
58
+ refusal: string | null;
59
+ }
60
+
61
+ /** Titles are matched after trimming and case-folding; agents are inconsistent. */
62
+ function key(title: unknown): string {
63
+ return String(title ?? "").trim().toLowerCase();
64
+ }
65
+
66
+ /**
67
+ * Group sub-issues into waves. Everything in a wave runs concurrently; wave
68
+ * N+1 does not start until wave N is done.
69
+ *
70
+ * Kahn's algorithm, with every failure mode a refusal rather than a dropped
71
+ * edge:
72
+ *
73
+ * - a `dependsOn` naming a sub-issue that is not in the list — the agent
74
+ * invented a dependency or misspelled one, and ignoring it would schedule
75
+ * the work as if the dependency did not exist
76
+ * - a self-dependency, which can never be satisfied
77
+ * - two sub-issues with the same title, because then an edge has two possible
78
+ * targets and picking one is a guess
79
+ * - a cycle, named by the sub-issues still unscheduled
80
+ *
81
+ * The all-independent case returns ONE wave containing everything, which is
82
+ * the positive control: a scheduler that serialised everything would satisfy
83
+ * every ordering case and throw away the whole benefit of decomposition
84
+ * (#189 AC-1).
85
+ */
86
+ export function dependencyWaves(subIssues: readonly WaveSubIssue[] | null | undefined): WavePlan {
87
+ const list = Array.isArray(subIssues) ? subIssues : [];
88
+ if (list.length === 0) return { waves: [], reasons: [], refusal: null };
89
+
90
+ const byTitle = new Map<string, number>();
91
+ for (let i = 0; i < list.length; i++) {
92
+ const k = key(list[i]?.title);
93
+ if (!k) {
94
+ return {
95
+ waves: [],
96
+ reasons: [],
97
+ refusal: `sub-issue ${i + 1} has no title, so nothing can declare a dependency on it (#189)`,
98
+ };
99
+ }
100
+ if (byTitle.has(k)) {
101
+ return {
102
+ waves: [],
103
+ reasons: [],
104
+ refusal:
105
+ `two sub-issues are both titled ${JSON.stringify(String(list[i]!.title).trim())} — a dependency ` +
106
+ `naming that title has two possible targets and picking one is a guess (#189)`,
107
+ };
108
+ }
109
+ byTitle.set(k, i);
110
+ }
111
+
112
+ const needs: number[][] = list.map(() => []);
113
+ for (let i = 0; i < list.length; i++) {
114
+ for (const raw of list[i]?.dependsOn ?? []) {
115
+ const k = key(raw);
116
+ if (!k) continue;
117
+ const target = byTitle.get(k);
118
+ if (target === undefined) {
119
+ return {
120
+ waves: [],
121
+ reasons: [],
122
+ refusal:
123
+ `sub-issue ${JSON.stringify(String(list[i]!.title).trim())} depends on ` +
124
+ `${JSON.stringify(String(raw).trim())}, which is not one of the sub-issues — ` +
125
+ `scheduling around a dependency this run cannot see is how ${"wf_92dbb346-949"} ` +
126
+ `produced two functions with one name (#189)`,
127
+ };
128
+ }
129
+ if (target === i) {
130
+ return {
131
+ waves: [],
132
+ reasons: [],
133
+ refusal:
134
+ `sub-issue ${JSON.stringify(String(list[i]!.title).trim())} depends on itself (#189)`,
135
+ };
136
+ }
137
+ if (!needs[i]!.includes(target)) needs[i]!.push(target);
138
+ }
139
+ }
140
+
141
+ const waves: number[][] = [];
142
+ const reasons: string[] = [];
143
+ const done = new Set<number>();
144
+
145
+ while (done.size < list.length) {
146
+ const ready = [];
147
+ for (let i = 0; i < list.length; i++) {
148
+ if (done.has(i)) continue;
149
+ if (needs[i]!.every(d => done.has(d))) ready.push(i);
150
+ }
151
+ if (ready.length === 0) {
152
+ const stuck = list
153
+ .map((s, i) => (done.has(i) ? null : String(s.title).trim()))
154
+ .filter(Boolean);
155
+ return {
156
+ waves: [],
157
+ reasons: [],
158
+ refusal:
159
+ `the dependsOn graph has a cycle — ${JSON.stringify(stuck)} can never start, because each ` +
160
+ `waits on another of them. Refusing rather than falling back to parallel: a fallback would ` +
161
+ `run exactly the schedule this field exists to prevent, and report that it had ordered the ` +
162
+ `work (#189)`,
163
+ };
164
+ }
165
+ if (waves.length > 0) {
166
+ const waited = [...new Set(ready.flatMap(i => needs[i]!))]
167
+ .map(d => String(list[d]!.title).trim())
168
+ .sort();
169
+ reasons.push(
170
+ `wave ${waves.length + 1} (${ready.map(i => String(list[i]!.title).trim()).join(", ")}) ` +
171
+ `waited for ${waited.join(", ")} — a declared dependsOn, not a file overlap`,
172
+ );
173
+ }
174
+ waves.push(ready);
175
+ for (const i of ready) done.add(i);
176
+ }
177
+
178
+ return { waves, reasons, refusal: null };
179
+ }
180
+
181
+ /**
182
+ * Was this plan serialised, and how much?
183
+ *
184
+ * A run that quietly takes four times as long is a bug report nobody files
185
+ * (#189 AC-5), so the dispatcher logs this whether or not anything waited.
186
+ */
187
+ export function wavePlanSummary(plan: WavePlan, total: number): string {
188
+ if (plan.refusal) return plan.refusal;
189
+ if (plan.waves.length <= 1) {
190
+ return `${total} sub-issue(s) declared no dependsOn — dispatching all of them concurrently`;
191
+ }
192
+ return (
193
+ `${total} sub-issues in ${plan.waves.length} dependency waves ` +
194
+ `(${plan.waves.map(w => w.length).join(" then ")}) — this run is serialised by ` +
195
+ `${plan.waves.length - 1} barrier(s) and will take correspondingly longer`
196
+ );
197
+ }
@@ -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
+ }