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,230 @@
1
+ /**
2
+ * Is the promoted container built from the commit under test? (#341)
3
+ *
4
+ * `container-has-fix` in `gates/workflow.test.ts` asked that, and every way
5
+ * of failing to find out returned a pass:
6
+ *
7
+ * const runtime = exec("command -v podman").ok ? "podman" : "docker";
8
+ * const inspect = execArgvOf(runtime, ["inspect", "--format=…revision", "--", name]);
9
+ * if (!inspect.ok || !inspect.output) return; // container absent, daemon down,
10
+ * const head = exec("git rev-parse HEAD", root); // no revision label,
11
+ * if (!head.ok) return; // neither runtime installed
12
+ *
13
+ * Four separate unmeasurable states, one observable outcome: PASS.
14
+ *
15
+ * Two of them are *more likely* exactly when the check matters. An image that
16
+ * was never rebuilt may not exist under the expected name; a stopped runtime
17
+ * is the normal state on a machine where promotion did not happen. The check
18
+ * was quietest in precisely the situation it exists to catch — shape one in
19
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
20
+ *
21
+ * The runtime was also chosen by probe rather than by config: absent podman
22
+ * silently fell through to docker, and with neither installed the inspect
23
+ * failed and the check passed. A consumer with no container runtime at all
24
+ * got a green `container-has-fix` on every run, for ever.
25
+ *
26
+ * ## What this does and deliberately does not do
27
+ *
28
+ * It makes the states **distinguishable and recorded** (#341 criteria 2 and 3)
29
+ * and resolves the runtime from config with the probe as a fallback
30
+ * (criterion 4).
31
+ *
32
+ * The criteria are written out longhand rather than as `SC-2`, `SC-4` and so
33
+ * on, because the registry owns those ids: every single-digit `SC-N` is a real
34
+ * entry in `specs/`, and `scripts/sync-sc-status.ts` credits any comment
35
+ * mentioning one as coverage of it. A sentence about this issue's second
36
+ * criterion would certify an unrelated bootstrap criterion as tested.
37
+ *
38
+ * It does **not** decide that an unreadable inspect FAILS the run. That is
39
+ * criterion 1's question — how often each state is taken across real runs on a real
40
+ * consumer — and #341 exists as a separate issue precisely because turning
41
+ * runs red on a consumer whose runtime happens to be down is a behaviour
42
+ * change that needs its blast radius measured rather than guessed. The
43
+ * verdicts below carry `blocking: false` for every unmeasurable state, and
44
+ * the day criterion 1 is answered that is the one field to change.
45
+ *
46
+ * Recording without deciding is normally the failure mode #346 was about —
47
+ * a reading nothing consumes. The difference is that here the reading is the
48
+ * deliverable: criterion 1 cannot be answered without it, and the issue says so.
49
+ */
50
+
51
+ export type ProvenanceOutcome =
52
+ | "MATCH"
53
+ | "BEHIND"
54
+ | "NO_RUNTIME"
55
+ | "RUNTIME_DOWN"
56
+ | "CONTAINER_ABSENT"
57
+ | "INSPECT_FAILED"
58
+ | "NO_REVISION_LABEL"
59
+ | "HEAD_UNREADABLE";
60
+
61
+ export interface ProvenanceVerdict {
62
+ outcome: ProvenanceOutcome;
63
+ /** Does this stop the run? Only BEHIND does, pending #341 criterion 1. */
64
+ blocking: boolean;
65
+ /** Was anything actually measured? */
66
+ measured: boolean;
67
+ detail: string;
68
+ }
69
+
70
+ /** The runtimes this knows how to inspect, in probe order. */
71
+ export const KNOWN_RUNTIMES = ["podman", "docker"] as const;
72
+
73
+ export type RuntimeResolution =
74
+ | { kind: "resolved"; runtime: string; source: "config" | "probe" }
75
+ | { kind: "none"; detail: string };
76
+
77
+ /**
78
+ * Which container runtime to ask, config first.
79
+ *
80
+ * The old line was `exec("command -v podman").ok ? "podman" : "docker"`,
81
+ * which has no way to say "neither" — docker was the answer whether docker
82
+ * was installed or not, and the resulting inspect failure read as a pass.
83
+ */
84
+ export function resolveContainerRuntime(
85
+ configured: string | null | undefined,
86
+ available: (name: string) => boolean,
87
+ ): RuntimeResolution {
88
+ if (typeof configured === "string" && configured.trim() !== "") {
89
+ const name = configured.trim();
90
+ if (available(name)) return { kind: "resolved", runtime: name, source: "config" };
91
+ return {
92
+ kind: "none",
93
+ detail:
94
+ `the project configures \`prod.containerRuntime: "${name}"\` and it is not on PATH, ` +
95
+ `so the container could not be inspected. Nothing was measured.`,
96
+ };
97
+ }
98
+ for (const name of KNOWN_RUNTIMES) {
99
+ if (available(name)) return { kind: "resolved", runtime: name, source: "probe" };
100
+ }
101
+ return {
102
+ kind: "none",
103
+ detail:
104
+ `no container runtime is available (looked for ${KNOWN_RUNTIMES.join(", ")}) and the ` +
105
+ `project configures none, so the container could not be inspected. Nothing was ` +
106
+ `measured — this is UNMEASURED, not a container that matches.`,
107
+ };
108
+ }
109
+
110
+ /**
111
+ * Tell "there is no such container" from "the daemon is not answering".
112
+ *
113
+ * Both used to be one silent return, and they mean opposite things: the
114
+ * first is evidence the promotion never happened, the second is evidence
115
+ * about the machine. Matching on the runtime's own words is a narrow
116
+ * detector, so an unrecognised failure stays `INSPECT_FAILED` and keeps its
117
+ * stderr rather than being filed under whichever branch is closer.
118
+ */
119
+ export function classifyInspectFailure(stderr: string): "CONTAINER_ABSENT" | "RUNTIME_DOWN" | "INSPECT_FAILED" {
120
+ const s = stderr.toLowerCase();
121
+ if (/no such (object|container|image)|unable to find|not found/.test(s)) return "CONTAINER_ABSENT";
122
+ if (/cannot connect|connection refused|daemon|is the docker daemon running|dial unix|service not available/.test(s)) {
123
+ return "RUNTIME_DOWN";
124
+ }
125
+ return "INSPECT_FAILED";
126
+ }
127
+
128
+ export interface ProvenanceReading {
129
+ runtime: RuntimeResolution;
130
+ containerName: string;
131
+ /** The inspect result, absent when no runtime resolved. */
132
+ inspect?: { ok: boolean; output: string; stderr: string };
133
+ /** `git rev-parse HEAD` in the tree under test. */
134
+ head?: { ok: boolean; output: string };
135
+ /** The `environments.prod.rebuild` verdict the run recorded. */
136
+ prodRebuild?: unknown;
137
+ }
138
+
139
+ /**
140
+ * One reading in, one named outcome out.
141
+ *
142
+ * Every branch produces a verdict. There is no path that returns nothing,
143
+ * which is the whole change: the previous body had four, and they were
144
+ * indistinguishable from a container that matched.
145
+ */
146
+ export function classifyContainerProvenance(r: ProvenanceReading): ProvenanceVerdict {
147
+ if (r.runtime.kind === "none") {
148
+ return { outcome: "NO_RUNTIME", blocking: false, measured: false, detail: r.runtime.detail };
149
+ }
150
+ const runtime = r.runtime.runtime;
151
+
152
+ if (!r.inspect) {
153
+ return {
154
+ outcome: "INSPECT_FAILED",
155
+ blocking: false,
156
+ measured: false,
157
+ detail: `${runtime} inspect was never run for ${r.containerName}. Nothing was measured.`,
158
+ };
159
+ }
160
+
161
+ if (!r.inspect.ok) {
162
+ const outcome = classifyInspectFailure(r.inspect.stderr);
163
+ const detail =
164
+ outcome === "CONTAINER_ABSENT"
165
+ ? `${runtime} has no container named ${r.containerName}. An image that was never ` +
166
+ `rebuilt does not exist under the expected name, so this is the state the check ` +
167
+ `exists to catch — recorded, not yet blocking (#341 criterion 1).`
168
+ : outcome === "RUNTIME_DOWN"
169
+ ? `${runtime} is installed but not answering, so ${r.containerName} could not be ` +
170
+ `inspected. This says nothing about the container.`
171
+ : `${runtime} inspect of ${r.containerName} failed for a reason this does not ` +
172
+ `recognise: ${r.inspect.stderr.trim().slice(0, 200)}`;
173
+ return { outcome, blocking: false, measured: false, detail };
174
+ }
175
+
176
+ const sha = r.inspect.output.replace(/'/g, "").trim();
177
+ if (sha === "") {
178
+ return {
179
+ outcome: "NO_REVISION_LABEL",
180
+ blocking: false,
181
+ measured: false,
182
+ detail:
183
+ `${r.containerName} carries no org.opencontainers.image.revision label, so the ` +
184
+ `commit it was built from is unknown. The image exists; its provenance does not.`,
185
+ };
186
+ }
187
+
188
+ if (!r.head?.ok || !r.head.output.trim()) {
189
+ return {
190
+ outcome: "HEAD_UNREADABLE",
191
+ blocking: false,
192
+ measured: false,
193
+ detail:
194
+ `the tree under test did not yield a HEAD commit, so there is nothing to compare ` +
195
+ `${r.containerName}'s revision ${sha.slice(0, 8)} against.`,
196
+ };
197
+ }
198
+
199
+ const head = r.head.output.trim();
200
+ if (sha === head) {
201
+ return {
202
+ outcome: "MATCH",
203
+ blocking: false,
204
+ measured: true,
205
+ detail: `${r.containerName} is built from ${head.slice(0, 8)}, the commit under test.`,
206
+ };
207
+ }
208
+
209
+ // The one blocking case, unchanged from before: a measured mismatch with
210
+ // no recorded rebuild. Narrowed to `blocking` so #341 criterion 1 has exactly one
211
+ // field to flip when the blast radius of the others is known.
212
+ const rebuilt = r.prodRebuild === "PASS";
213
+ return {
214
+ outcome: "BEHIND",
215
+ blocking: !rebuilt,
216
+ measured: true,
217
+ detail:
218
+ `${r.containerName} is built from ${sha.slice(0, 8)} and the commit under test is ` +
219
+ `${head.slice(0, 8)}` +
220
+ (rebuilt
221
+ ? `, but the run records prod.rebuild PASS, so the promotion is accounted for.`
222
+ : `, and the run records no prod.rebuild PASS. The promoted container does not ` +
223
+ `contain the change being shipped.`),
224
+ };
225
+ }
226
+
227
+ /** The gate's refusal: empty unless something measured and blocking was found. */
228
+ export function containerProvenanceViolations(v: ProvenanceVerdict): string[] {
229
+ return v.blocking ? [`container-has-fix: ${v.detail}`] : [];
230
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * create-brief — Generate agent brief templates and register roles in config.
3
+ *
4
+ * Deep module: all logic here, CLI is a thin consumer.
5
+ */
6
+
7
+ import { readFileSync, writeFileSync, existsSync } from "fs";
8
+ import type { AgentMeta } from "./generators/types";
9
+
10
+ /**
11
+ * Generate an agent brief markdown template with standard sections and variable placeholders.
12
+ */
13
+ export function generateBriefTemplate(
14
+ roleName: string,
15
+ description: string,
16
+ forbiddenCommands?: string[],
17
+ ): string {
18
+ const today = new Date().toISOString().split("T")[0];
19
+ const displayName = roleName.charAt(0).toUpperCase() + roleName.slice(1);
20
+
21
+ return `---
22
+ doc-type: reference
23
+ status: active
24
+ owner: TODO
25
+ updated: ${today}
26
+ ---
27
+
28
+ You are ${displayName}, ${description}.
29
+
30
+ ## Context (READ THIS FIRST)
31
+
32
+ 1. **PROJECT-STATE.md** — current priorities, session handoff
33
+ 2. **Governing spec** — look up in specs-routing rule for the area you're changing
34
+
35
+ ## Workflow
36
+
37
+ 1. Read the governing spec if your task touches a spec'd area
38
+ 3. Execute your task following project conventions
39
+ 4. Report results with evidence
40
+
41
+ ## Never Do
42
+
43
+ - Read the same file twice — get what you need in one pass
44
+ - Use \`cat\`, \`head\`, or \`tail\` via Bash — use the Read tool instead
45
+ - Run \`pwd\` or \`ls -la\` for orientation — your CWD is always the project root
46
+ - Guess at file structure — use AGENTS.md routing table
47
+
48
+ ## Report
49
+
50
+ - PASS/FAIL per AC with evidence (command output or screenshots)
51
+ - Any new findings flagged as blocking or non-blocking
52
+
53
+ ## Rules
54
+
55
+ ${forbiddenRules(forbiddenCommands)}- Verify before asserting — try it first, report what actually happened
56
+ `;
57
+ }
58
+
59
+ /**
60
+ * #343 — this template hardcoded "Never run \`make rebuild\`".
61
+ *
62
+ * That is one consumer's rule, emitted into every consumer's brief template.
63
+ * It comes from the project's own \`forbiddenCommands\` now, and nothing is
64
+ * emitted when none is configured: a guessed prohibition is worse than
65
+ * silence, because the agent obeys it and nobody finds out it was invented.
66
+ */
67
+ function forbiddenRules(commands: string[] | undefined): string {
68
+ if (!commands || commands.length === 0) return "";
69
+ return commands.map(c => `- Never run \\\`${c}\\\` — only the DA does that\n`).join("");
70
+ }
71
+
72
+ /**
73
+ * Write a generated brief template to the templates directory.
74
+ * Returns the file path written to.
75
+ */
76
+ export function writeBriefTemplate(templatesDir: string, roleName: string, description: string): string {
77
+ const filePath = `${templatesDir}/${roleName}.md`;
78
+ if (existsSync(filePath)) {
79
+ throw new Error(`Template already exists: ${filePath}`);
80
+ }
81
+ const content = generateBriefTemplate(roleName, description);
82
+ writeFileSync(filePath, content);
83
+ return filePath;
84
+ }
85
+
86
+ /**
87
+ * Add a new role to the project's rungate.json config.
88
+ * Adds brief path, isolation: worktree, and a standardTask.
89
+ */
90
+ export function addRoleToConfig(configPath: string, roleName: string, description: string): void {
91
+ if (!existsSync(configPath)) {
92
+ throw new Error(`Config file not found: ${configPath}`);
93
+ }
94
+ const config = JSON.parse(readFileSync(configPath, "utf-8"));
95
+ if (!config.roles) {
96
+ config.roles = {};
97
+ }
98
+ if (config.roles[roleName]) {
99
+ throw new Error(`Role '${roleName}' already exists in ${configPath}`);
100
+ }
101
+ config.roles[roleName] = {
102
+ brief: `.claude/agents/${roleName}.md`,
103
+ isolation: "worktree",
104
+ standardTask: `Perform ${description.toLowerCase()} tasks as assigned`,
105
+ description,
106
+ tools: "[Bash, Read]",
107
+ model: "sonnet",
108
+ };
109
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + "\n");
110
+ }
111
+
112
+ export const DEFAULT_AGENT_META: Record<string, AgentMeta> = {
113
+ // discovery and marcus run opus: discovery authors the ACs and evidence
114
+ // commands (the "unwinnable AC" pattern that SHIP_FAILED #42/#43/#45
115
+ // originates there), and marcus does multi-file TDD implementation. Both
116
+ // clear the "multi-file architectural reasoning" bar in the model routing
117
+ // guidance; the read-only and checklist roles below stay on sonnet.
118
+ discovery: { description: "Discovery agent — reads issue, sizes work, writes ACs with evidence methods", tools: "[Bash, Read]", model: "opus", effort: "low", disallowedTools: ["Write", "Edit"], omitClaudeMd: true, tiers: { reinforcement: ["Discovery Rules"] } },
119
+ marcus: { description: "Principal engineer — implements code changes with TDD, writes tests, commits", tools: "[Bash, Read, Write, Edit]", model: "opus", memory: "project", maxTurns: 30, effort: "high", isolation: "worktree", tiers: { reinforcement: ["Testing Rules"], mechanical: ["Workflow"] } },
120
+ quinn: { description: "QA engineer — tests as a brand-new user using Playwright MCP tools", tools: "[Bash, Read, mcp__playwright__*]", model: "sonnet", effort: "high", disallowedTools: ["Write", "Edit"], omitClaudeMd: true, tiers: { reinforcement: ["Project Type Detection", "CLI Testing Mode"] } },
121
+ rook: { description: "Security engineer — scans changed files for vulnerabilities", tools: "[Bash, Read]", model: "sonnet", effort: "low", disallowedTools: ["Write", "Edit"], omitClaudeMd: true },
122
+ serena: { description: "Software architect — structural decisions, ADRs, module boundary review", tools: "[Read]", model: "sonnet", disallowedTools: ["Write", "Edit"] },
123
+ aditi: { description: "UX/UI designer — component specs, visual review, accessibility", tools: "[Read]", model: "sonnet", disallowedTools: ["Write", "Edit"], tiers: { reinforcement: ["Project Type Detection"] } },
124
+ };
125
+
126
+ /**
127
+ * Build agentMeta record from harness roles config.
128
+ * Returns only config-sourced entries — callers merge with DEFAULT_AGENT_META if needed.
129
+ */
130
+ export function buildAgentMeta(harnessConfig: Record<string, any> | null): Record<string, AgentMeta> {
131
+ const result: Record<string, AgentMeta> = {};
132
+ if (!harnessConfig?.roles) return result;
133
+
134
+ for (const [roleName, roleConfig] of Object.entries(harnessConfig.roles as Record<string, any>)) {
135
+ result[roleName] = {
136
+ description: roleConfig.description || `${roleName} agent`,
137
+ tools: roleConfig.tools || "[Bash, Read]",
138
+ model: roleConfig.model || "sonnet",
139
+ ...(roleConfig.tiers ? { tiers: roleConfig.tiers } : {}),
140
+ ...(roleConfig.memory ? { memory: roleConfig.memory } : {}),
141
+ ...(roleConfig.maxTurns ? { maxTurns: roleConfig.maxTurns } : {}),
142
+ ...(roleConfig.effort ? { effort: roleConfig.effort } : {}),
143
+ ...(roleConfig.disallowedTools ? { disallowedTools: roleConfig.disallowedTools } : {}),
144
+ ...(roleConfig.omitClaudeMd ? { omitClaudeMd: roleConfig.omitClaudeMd } : {}),
145
+ ...(roleConfig.isolation ? { isolation: roleConfig.isolation } : {}),
146
+ ...(roleConfig.hooks ? { hooks: roleConfig.hooks } : {}),
147
+ };
148
+ }
149
+ return result;
150
+ }
@@ -0,0 +1,267 @@
1
+ /**
2
+ * create-sc — Generate matchable SC lines from structured input.
3
+ *
4
+ * Deep module: all pattern-to-text logic lives here.
5
+ * Thin consumer: scripts/create-sc.ts is the CLI wrapper.
6
+ */
7
+ import { readFileSync, existsSync } from "fs";
8
+ import { join, dirname } from "path";
9
+ import { fileURLToPath } from "url";
10
+
11
+ import type { ScRegistry } from "./sc-ids";
12
+ import { tryLoadRungateConfig } from "./config-loader";
13
+
14
+ // ── Types ─────────────────────────────────────────────────────
15
+
16
+ export interface RegistryEntry {
17
+ name: string;
18
+ syntax: string;
19
+ regex: string;
20
+ example: string;
21
+ notes: string;
22
+ }
23
+
24
+ interface ParamDef {
25
+ required: string[];
26
+ generate: (params: Record<string, string>) => string;
27
+ }
28
+
29
+ // ── Registry loading ──────────────────────────────────────────
30
+
31
+ const _registryCache = new Map<string, RegistryEntry[]>();
32
+
33
+ function loadBuiltInRegistry(): RegistryEntry[] {
34
+ const key = "__builtin__";
35
+ if (_registryCache.has(key)) return _registryCache.get(key)!;
36
+ const configPath = join(dirname(fileURLToPath(import.meta.url)), "..", "config", "matcher-registry.json");
37
+ const entries: RegistryEntry[] = JSON.parse(readFileSync(configPath, "utf-8"));
38
+ _registryCache.set(key, entries);
39
+ return entries;
40
+ }
41
+
42
+ /**
43
+ * Load the matcher registry, optionally merging consumer-defined custom matchers.
44
+ *
45
+ * When projectRoot is provided, resolves that project's config through
46
+ * `lib/config-loader.ts` and merges any `customMatchers` array entries with the
47
+ * built-in registry. Consumer entries with the same `name` as a built-in entry
48
+ * override the built-in.
49
+ */
50
+ export function loadRegistry(projectRoot?: string): RegistryEntry[] {
51
+ const cacheKey = projectRoot ?? "__builtin__";
52
+ if (_registryCache.has(cacheKey)) return _registryCache.get(cacheKey)!;
53
+
54
+ const builtIn = loadBuiltInRegistry();
55
+ if (!projectRoot) {
56
+ return builtIn;
57
+ }
58
+
59
+ // Through the loader, so a consumer on the directory layout can supply
60
+ // custom matchers at all — this read was monolith-only, which is #212/#90.
61
+ // The parse failure is NOT caught: the old `catch` returned the built-in
62
+ // registry, so a consumer whose config had a trailing comma silently got
63
+ // rungate's matchers and no indication their own had been dropped.
64
+ const config = tryLoadRungateConfig(projectRoot);
65
+ const customMatchers = (config?.customMatchers ?? []) as RegistryEntry[];
66
+ if (customMatchers.length === 0) {
67
+ _registryCache.set(cacheKey, builtIn);
68
+ return builtIn;
69
+ }
70
+
71
+ // Merge: consumer entries override built-in entries with same name
72
+ const merged = builtIn.filter(
73
+ (entry) => !customMatchers.some((c) => c.name === entry.name)
74
+ );
75
+ merged.push(...customMatchers);
76
+
77
+ _registryCache.set(cacheKey, merged);
78
+ return merged;
79
+ }
80
+
81
+ // ── Pattern param definitions ─────────────────────────────────
82
+
83
+ const patternDefs: Record<string, ParamDef> = {
84
+ "file-exists": {
85
+ required: ["file"],
86
+ generate: (p) => `${p.file} exists`,
87
+ },
88
+ "dir-exists": {
89
+ required: ["dir"],
90
+ generate: (p) => `${p.dir}/ directory exists`,
91
+ },
92
+ "all-specs-frontmatter": {
93
+ required: [],
94
+ generate: () => "all specs have frontmatter",
95
+ },
96
+ "paths-resolve": {
97
+ required: ["file"],
98
+ generate: (p) => `all paths referenced in ${p.file} resolve`,
99
+ },
100
+ "root-clean": {
101
+ required: [],
102
+ generate: () => "root is clean",
103
+ },
104
+ "pointer-exists": {
105
+ required: ["file", "target"],
106
+ generate: (p) => `${p.file} exists with pointer to ${p.target}`,
107
+ },
108
+ "canary": {
109
+ required: [],
110
+ generate: () => "canary test exists",
111
+ },
112
+ "content-contains": {
113
+ required: ["file", "items"],
114
+ generate: (p) => `${p.file} contains [${p.items}]`,
115
+ },
116
+ "content-not-contains": {
117
+ required: ["file", "items"],
118
+ generate: (p) => `${p.file} must NOT contain [${p.items}]`,
119
+ },
120
+ "count-threshold": {
121
+ required: ["file", "count", "unit"],
122
+ generate: (p) => `${p.file} is under [${p.count}] ${p.unit}`,
123
+ },
124
+ "json-field-equals": {
125
+ required: ["file", "field", "value"],
126
+ generate: (p) => `${p.file} ${p.field} field equals [${p.value}]`,
127
+ },
128
+ "section-exists": {
129
+ required: ["file", "section"],
130
+ generate: (p) => `${p.file} has section [${p.section}]`,
131
+ },
132
+ "regex-match": {
133
+ required: ["file", "pattern"],
134
+ generate: (p) => `${p.file} matches /${p.pattern}/${p.flags ?? ""}`,
135
+ },
136
+ "source-contains": {
137
+ required: ["file", "keywords"],
138
+ generate: (p) => `harness ${p.file} contains [${p.keywords}]`,
139
+ },
140
+ "json-has-field": {
141
+ required: ["file", "field"],
142
+ generate: (p) => `${p.file} has field ${p.field}`,
143
+ },
144
+ "scaffold-produces": {
145
+ required: ["file"],
146
+ generate: (p) => `scaffold output ${p.file} exists`,
147
+ },
148
+ "frontmatter-field": {
149
+ required: ["file", "field"],
150
+ generate: (p) => p.value
151
+ ? `${p.file} frontmatter has ${p.field} = ${p.value}`
152
+ : `${p.file} frontmatter has ${p.field}`,
153
+ },
154
+ "file-line-range": {
155
+ required: ["file", "min", "max"],
156
+ generate: (p) => `${p.file} is between [${p.min}] and [${p.max}] lines`,
157
+ },
158
+ "command-output": {
159
+ required: ["command", "expected"],
160
+ generate: (p) => `command-output \`${p.command}\` contains [${p.expected}]`,
161
+ },
162
+ };
163
+
164
+ // ── Core functions ────────────────────────────────────────────
165
+
166
+ function validatePattern(name: string): RegistryEntry {
167
+ const registry = loadRegistry();
168
+ const entry = registry.find(e => e.name === name);
169
+ if (!entry) {
170
+ const validNames = registry.map(e => e.name).join(", ");
171
+ throw new Error(`Unknown pattern: "${name}". Valid patterns: ${validNames}`);
172
+ }
173
+ return entry;
174
+ }
175
+
176
+ function validateParams(patternName: string, params: Record<string, string>): void {
177
+ const def = patternDefs[patternName];
178
+ if (!def) {
179
+ throw new Error(`No parameter definition for pattern: "${patternName}"`);
180
+ }
181
+ const missing = def.required.filter(k => !params[k]);
182
+ if (missing.length > 0) {
183
+ throw new Error(
184
+ `Missing required params for "${patternName}": ${missing.join(", ")}. ` +
185
+ `Required: ${def.required.join(", ")}`
186
+ );
187
+ }
188
+ }
189
+
190
+ export function generateSCText(patternName: string, params: Record<string, string>): string {
191
+ // Validate pattern exists in registry
192
+ const entry = validatePattern(patternName);
193
+
194
+ // Validate required params
195
+ validateParams(patternName, params);
196
+
197
+ // Generate the statement text
198
+ const def = patternDefs[patternName];
199
+ const statement = def.generate(params);
200
+
201
+ // Validate round-trip: generated text must match the pattern's regex
202
+ const regex = new RegExp(entry.regex, "i");
203
+ if (!regex.test(statement)) {
204
+ throw new Error(
205
+ `Internal error: generated text "${statement}" does not match pattern regex /${entry.regex}/i`
206
+ );
207
+ }
208
+
209
+ return statement;
210
+ }
211
+
212
+ export function listPatterns(): string {
213
+ const registry = loadRegistry();
214
+ const lines: string[] = ["Available patterns:", ""];
215
+ for (const entry of registry) {
216
+ const def = patternDefs[entry.name];
217
+ const required = def ? def.required : [];
218
+ lines.push(` ${entry.name}`);
219
+ lines.push(` Syntax: ${entry.syntax}`);
220
+ lines.push(` Example: ${entry.example}`);
221
+ lines.push(` Required: ${required.length > 0 ? required.join(", ") : "(none)"}`);
222
+ lines.push("");
223
+ }
224
+ return lines.join("\n");
225
+ }
226
+
227
+ /**
228
+ * The next free SC number.
229
+ *
230
+ * `SC-<n>` is a GLOBAL id — `lib/sc-ids.ts` says so, and
231
+ * `test/spec-sc-ids-unique.test.ts` enforces it. This function read ONE
232
+ * spec's content, which in a global namespace is not an allocator but a
233
+ * collision generator, and it generated ten (#392): GATE-CONTRACTS-SPEC.md
234
+ * counted up to 378 in its own file and took 379..388 for its per-gate
235
+ * subsections, while CONFIG-DRIVEN-TESTING-SPEC.md independently counted up
236
+ * to 378 in ITS own file and took 379 next. Both were locally correct and
237
+ * neither could see the other.
238
+ *
239
+ * Pass the registry and the whole namespace is consulted, headings included —
240
+ * a number owned by a `### SC-N:` section is just as taken as a tracked one.
241
+ *
242
+ * `reg` is optional so the one-argument answer is unchanged for any caller
243
+ * that has no registry to hand; silently changing that would be a different
244
+ * bug. It is the wrong answer in a shared namespace, which is why
245
+ * `scripts/create-sc.ts` passes one.
246
+ */
247
+ export function nextSCNumber(specContent: string, reg?: ScRegistry): number {
248
+ const ids: number[] = [];
249
+ const pattern = /SC-(\d+)/g;
250
+ let match;
251
+ while ((match = pattern.exec(specContent)) !== null) {
252
+ ids.push(parseInt(match[1]));
253
+ }
254
+ for (const id of reg?.declaredById.keys() ?? []) {
255
+ const n = Number(id.replace(/^SC-[A-Z]?/, ""));
256
+ if (Number.isFinite(n)) ids.push(n);
257
+ }
258
+ if (ids.length === 0) return 1;
259
+ return Math.max(...ids) + 1;
260
+ }
261
+
262
+ /**
263
+ * Format an SC line for appending to a spec file.
264
+ */
265
+ export function formatSCLine(scNumber: number, statement: string): string {
266
+ return `- [ ] SC-${scNumber}: ${statement}`;
267
+ }