rungate 0.2.1 → 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 (119) 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 +24 -2
  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
@@ -0,0 +1,348 @@
1
+ import { readdirSync, readFileSync, existsSync, statSync } from "fs";
2
+ import { collectSpecFiles } from "./spec-files";
3
+ import { join } from "path";
4
+ import { execSync } from "child_process";
5
+
6
+ export interface GapResult {
7
+ check: string;
8
+ status: "PASS" | "WARN" | "SKIP";
9
+ detail: string;
10
+ }
11
+
12
+ export interface GapScanResult {
13
+ results: GapResult[];
14
+ warnings: number;
15
+ passes: number;
16
+ }
17
+
18
+ export function scanGaps(
19
+ projectRoot: string,
20
+ workDir?: string
21
+ ): GapScanResult {
22
+ const runGateWorkDir =
23
+ workDir || process.env.RUNGATE_WORK_DIR || join(process.env.HOME!, ".rungate");
24
+
25
+ const results: GapResult[] = [];
26
+
27
+ // 1. orphaned-workdirs
28
+ results.push(checkOrphanedWorkdirs(runGateWorkDir));
29
+
30
+ // 2. stale-doc-refs
31
+ results.push(checkStaleDocRefs(projectRoot));
32
+
33
+ // 3. no-new-todos-without-issue
34
+ results.push(checkTodosWithoutIssue(projectRoot));
35
+
36
+ // 4. spec-sc-unchecked-ratio
37
+ results.push(checkSpecScRatio(projectRoot));
38
+
39
+ // 5. hook-line-budget
40
+ results.push(checkHookLineBudget(projectRoot));
41
+
42
+ // 6. test-suite-health
43
+ results.push(checkTestSuiteHealth(projectRoot));
44
+
45
+ const warnings = results.filter((r) => r.status === "WARN").length;
46
+ const passes = results.filter((r) => r.status === "PASS").length;
47
+
48
+ return { results, warnings, passes };
49
+ }
50
+
51
+ function checkOrphanedWorkdirs(workDir: string): GapResult {
52
+ if (!existsSync(workDir)) {
53
+ return {
54
+ check: "orphaned-workdirs",
55
+ status: "SKIP",
56
+ detail: "Work directory does not exist",
57
+ };
58
+ }
59
+
60
+ try {
61
+ const dirs = readdirSync(workDir).filter((entry) => {
62
+ const fullPath = join(workDir, entry);
63
+ try {
64
+ return statSync(fullPath).isDirectory();
65
+ } catch {
66
+ return false;
67
+ }
68
+ });
69
+
70
+ const orphaned = dirs.filter((dir) => {
71
+ const stateFile = join(workDir, dir, "workflow-state.json");
72
+ return !existsSync(stateFile);
73
+ });
74
+
75
+ const count = orphaned.length;
76
+ if (count > 5) {
77
+ return {
78
+ check: "orphaned-workdirs",
79
+ status: "WARN",
80
+ detail: `${count} orphaned work directories without workflow-state.json`,
81
+ };
82
+ }
83
+
84
+ return {
85
+ check: "orphaned-workdirs",
86
+ status: "PASS",
87
+ detail: `${count} orphaned work directories (threshold: 5)`,
88
+ };
89
+ } catch (error) {
90
+ return {
91
+ check: "orphaned-workdirs",
92
+ status: "SKIP",
93
+ detail: `Error checking work directories: ${error}`,
94
+ };
95
+ }
96
+ }
97
+
98
+ function checkStaleDocRefs(projectRoot: string): GapResult {
99
+ const docFiles = ["CLAUDE.md", "AGENTS.md"];
100
+ const missing: string[] = [];
101
+
102
+ for (const docFile of docFiles) {
103
+ const docPath = join(projectRoot, docFile);
104
+ if (!existsSync(docPath)) {
105
+ continue;
106
+ }
107
+
108
+ try {
109
+ const content = readFileSync(docPath, "utf-8");
110
+ const lines = content.split("\n");
111
+
112
+ // Look for markdown table rows with file references
113
+ for (const line of lines) {
114
+ // Match table rows: | filename | ...
115
+ const match = line.match(/^\|\s*([^|]+?)\s*\|/);
116
+ if (match && match[1]) {
117
+ const potentialFile = match[1].trim();
118
+
119
+ // Skip headers, separators, non-file entries, and prose descriptions
120
+ if (
121
+ potentialFile === "File" ||
122
+ potentialFile.includes("---") ||
123
+ potentialFile.length === 0 ||
124
+ potentialFile.startsWith("**") ||
125
+ potentialFile.startsWith("I ") ||
126
+ potentialFile.includes("...") ||
127
+ /^[A-Z][a-z]+ [a-z]/.test(potentialFile)
128
+ ) {
129
+ continue;
130
+ }
131
+
132
+ // Strip backticks from paths like `CODE-MAP.md`
133
+ const cleanFile = potentialFile.replace(/`/g, "").trim();
134
+ if (!cleanFile || cleanFile.includes("---")) continue;
135
+
136
+ // Check if it looks like a file reference (has extension or is a directory)
137
+ if (cleanFile.includes(".") || cleanFile.endsWith("/")) {
138
+ // Try the path as-is, then with common prefixes
139
+ const candidates = [
140
+ join(projectRoot, cleanFile),
141
+ join(projectRoot, "specs", cleanFile),
142
+ join(projectRoot, "test", cleanFile),
143
+ join(projectRoot, "docs", cleanFile),
144
+ join(projectRoot, "reference", cleanFile),
145
+ ];
146
+ const found = candidates.some((p) => existsSync(p));
147
+ if (!found) {
148
+ // Skip glob patterns like *.md
149
+ if (cleanFile.includes("*")) continue;
150
+ missing.push(cleanFile);
151
+ }
152
+ }
153
+ }
154
+ }
155
+ } catch (error) {
156
+ // Continue to next file on error
157
+ }
158
+ }
159
+
160
+ if (missing.length > 0) {
161
+ return {
162
+ check: "stale-doc-refs",
163
+ status: "WARN",
164
+ detail: `Missing file references: ${missing.join(", ")}`,
165
+ };
166
+ }
167
+
168
+ return {
169
+ check: "stale-doc-refs",
170
+ status: "PASS",
171
+ detail: "All file references exist",
172
+ };
173
+ }
174
+
175
+ function checkTodosWithoutIssue(projectRoot: string): GapResult {
176
+ try {
177
+ const diff = execSync("git diff HEAD~5 --unified=0", {
178
+ cwd: projectRoot,
179
+ encoding: "utf-8",
180
+ stdio: "pipe",
181
+ });
182
+
183
+ const lines = diff.split("\n");
184
+ const todosWithoutIssue: string[] = [];
185
+
186
+ for (const line of lines) {
187
+ if (line.startsWith("+") && !line.startsWith("+++")) {
188
+ const content = line.slice(1).trim();
189
+ if (
190
+ /\/\/.*\b(TODO|FIXME|HACK)\b/.test(content) &&
191
+ !/#\d+/.test(content) &&
192
+ !/["'`].*\b(TODO|FIXME|HACK)\b.*["'`]/.test(content)
193
+ ) {
194
+ todosWithoutIssue.push(content);
195
+ }
196
+ }
197
+ }
198
+
199
+ if (todosWithoutIssue.length > 0) {
200
+ return {
201
+ check: "no-new-todos-without-issue",
202
+ status: "WARN",
203
+ detail: `${todosWithoutIssue.length} new code comments with TODO/FIXME/HACK (missing #NNN)`,
204
+ };
205
+ }
206
+
207
+ return {
208
+ check: "no-new-todos-without-issue",
209
+ status: "PASS",
210
+ detail: "No new code comments with TODO/FIXME/HACK missing issue reference",
211
+ };
212
+ } catch (error) {
213
+ return {
214
+ check: "no-new-todos-without-issue",
215
+ status: "SKIP",
216
+ detail: "Not in a git repository or insufficient history",
217
+ };
218
+ }
219
+ }
220
+
221
+ function checkSpecScRatio(projectRoot: string): GapResult {
222
+ const specsDir = join(projectRoot, "specs");
223
+
224
+ if (!existsSync(specsDir)) {
225
+ return {
226
+ check: "spec-sc-unchecked-ratio",
227
+ status: "SKIP",
228
+ detail: "No specs directory found",
229
+ };
230
+ }
231
+
232
+ let totalChecked = 0;
233
+ let totalUnchecked = 0;
234
+
235
+ try {
236
+ const specFiles = collectSpecFiles(specsDir); // #225 — subdirectories too
237
+
238
+ for (const file of specFiles) {
239
+ const content = readFileSync(join(specsDir, file), "utf-8");
240
+ const lines = content.split("\n");
241
+
242
+ for (const line of lines) {
243
+ if (/^- \[x\] SC-/i.test(line)) {
244
+ totalChecked++;
245
+ } else if (/^- \[ \] SC-/i.test(line)) {
246
+ totalUnchecked++;
247
+ }
248
+ }
249
+ }
250
+
251
+ const total = totalChecked + totalUnchecked;
252
+ if (total === 0) {
253
+ return {
254
+ check: "spec-sc-unchecked-ratio",
255
+ status: "SKIP",
256
+ detail: "No SCs found in spec files",
257
+ };
258
+ }
259
+
260
+ const uncheckedPercent = Math.round((totalUnchecked / total) * 100);
261
+
262
+ if (uncheckedPercent > 60) {
263
+ return {
264
+ check: "spec-sc-unchecked-ratio",
265
+ status: "WARN",
266
+ detail: `${uncheckedPercent}% unchecked SCs (${totalUnchecked}/${total})`,
267
+ };
268
+ }
269
+
270
+ return {
271
+ check: "spec-sc-unchecked-ratio",
272
+ status: "PASS",
273
+ detail: `${uncheckedPercent}% unchecked SCs (${totalUnchecked}/${total})`,
274
+ };
275
+ } catch (error) {
276
+ return {
277
+ check: "spec-sc-unchecked-ratio",
278
+ status: "SKIP",
279
+ detail: `Error checking spec files: ${error}`,
280
+ };
281
+ }
282
+ }
283
+
284
+ function checkHookLineBudget(projectRoot: string): GapResult {
285
+ const hooksDir = join(projectRoot, "hooks");
286
+
287
+ if (!existsSync(hooksDir)) {
288
+ return {
289
+ check: "hook-line-budget",
290
+ status: "SKIP",
291
+ detail: "No hooks directory found",
292
+ };
293
+ }
294
+
295
+ try {
296
+ const hookFiles = readdirSync(hooksDir).filter((f) => f.endsWith(".hook.ts"));
297
+ const violations: string[] = [];
298
+
299
+ for (const file of hookFiles) {
300
+ const content = readFileSync(join(hooksDir, file), "utf-8");
301
+ const lines = content.split("\n").length;
302
+
303
+ if (lines > 150) {
304
+ violations.push(`${file} (${lines} lines)`);
305
+ }
306
+ }
307
+
308
+ if (violations.length > 0) {
309
+ return {
310
+ check: "hook-line-budget",
311
+ status: "WARN",
312
+ detail: `Hooks exceeding 150 lines: ${violations.join(", ")}`,
313
+ };
314
+ }
315
+
316
+ return {
317
+ check: "hook-line-budget",
318
+ status: "PASS",
319
+ detail: `All ${hookFiles.length} hooks under 150 lines`,
320
+ };
321
+ } catch (error) {
322
+ return {
323
+ check: "hook-line-budget",
324
+ status: "SKIP",
325
+ detail: `Error checking hook files: ${error}`,
326
+ };
327
+ }
328
+ }
329
+
330
+ function checkTestSuiteHealth(projectRoot: string): GapResult {
331
+ const packageJsonPath = join(projectRoot, "package.json");
332
+
333
+ if (!existsSync(packageJsonPath)) {
334
+ return {
335
+ check: "test-suite-health",
336
+ status: "SKIP",
337
+ detail: "No package.json found",
338
+ };
339
+ }
340
+
341
+ // For now, just return SKIP since running the full test suite is expensive
342
+ // This check would need more sophisticated implementation in real usage
343
+ return {
344
+ check: "test-suite-health",
345
+ status: "SKIP",
346
+ detail: "Test suite health check not implemented (would run bun test)",
347
+ };
348
+ }
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Gate enforcement logic — extracted from GateEnforcement.hook.ts
3
+ *
4
+ * Deep module: exports enforcement decision logic, workflow gate failure
5
+ * scanning, and signal logging. The hook file is a thin trigger that
6
+ * delegates all logic here.
7
+ *
8
+ * Issue: #544
9
+ */
10
+
11
+ import {
12
+ appendFileSync,
13
+ existsSync,
14
+ mkdirSync,
15
+ readFileSync,
16
+ readdirSync,
17
+ unlinkSync,
18
+ writeFileSync,
19
+ } from 'fs';
20
+ import { checkDocHygiene } from './doc-hygiene';
21
+
22
+ export interface GateFailure {
23
+ check: string;
24
+ detail: string;
25
+ }
26
+
27
+ export interface WorkflowGateFailure {
28
+ gate: string;
29
+ issue: number;
30
+ slug: string;
31
+ failures: GateFailure[];
32
+ hasOutcomeAcFailure: boolean;
33
+ }
34
+
35
+ export interface GatePending {
36
+ session_id: string;
37
+ gate: string;
38
+ issue: number;
39
+ slug: string;
40
+ failures: GateFailure[];
41
+ strike_count: number;
42
+ max_strikes: number;
43
+ outcome_ac_failure: boolean;
44
+ created_at: string;
45
+ expires_ts: number;
46
+ }
47
+
48
+ export type EnforcementAction = 'block' | 'nag' | 'pass';
49
+
50
+ export interface EnforcementDecision {
51
+ action: EnforcementAction;
52
+ decision?: string;
53
+ reason?: string;
54
+ reminder?: string;
55
+ newStrikeCount: number;
56
+ }
57
+
58
+ /**
59
+ * Format gate failures into human-readable text.
60
+ */
61
+ export function formatFailures(failures: GateFailure[]): string {
62
+ return failures.map(f => ` - ${f.check}: ${f.detail}`).join('\n');
63
+ }
64
+
65
+ /**
66
+ * Scan workflow-state.json files under workDir for active gate failures.
67
+ * Returns the first failure found (scope > verify > ship priority).
68
+ * Checks both direct children and nested subdirectories.
69
+ */
70
+ export function findWorkflowGateFailure(workDir: string): WorkflowGateFailure | null {
71
+ if (!existsSync(workDir)) return null;
72
+
73
+ try {
74
+ const dirs = readdirSync(workDir, { withFileTypes: true })
75
+ .filter(d => d.isDirectory());
76
+
77
+ for (const d of dirs) {
78
+ // Level 1: direct children
79
+ const result = checkWorkflowFile(`${workDir}/${d.name}/workflow-state.json`, d.name);
80
+ if (result) return result;
81
+
82
+ // Level 2: nested subdirectories
83
+ try {
84
+ const subDirs = readdirSync(`${workDir}/${d.name}`, { withFileTypes: true })
85
+ .filter(sd => sd.isDirectory());
86
+ for (const sd of subDirs) {
87
+ const nestedResult = checkWorkflowFile(
88
+ `${workDir}/${d.name}/${sd.name}/workflow-state.json`,
89
+ `${d.name}/${sd.name}`,
90
+ );
91
+ if (nestedResult) return nestedResult;
92
+ }
93
+ } catch { /* skip */ }
94
+ }
95
+ } catch { /* skip */ }
96
+
97
+ return null;
98
+ }
99
+
100
+ /**
101
+ * Check a single workflow-state.json file for gate failures.
102
+ */
103
+ function checkWorkflowFile(wfPath: string, slug: string): WorkflowGateFailure | null {
104
+ if (!existsSync(wfPath)) return null;
105
+
106
+ try {
107
+ const wf = JSON.parse(readFileSync(wfPath, 'utf-8'));
108
+ if (wf.phase === 'DONE') return null;
109
+
110
+ const gates = wf.gates || {};
111
+ for (const gateName of ['scope', 'verify', 'ship']) {
112
+ const gate = gates[gateName];
113
+ if (gate?.result === 'FAIL' && Array.isArray(gate.failures) && gate.failures.length > 0) {
114
+ const acs = Array.isArray(wf.acs) ? wf.acs : [];
115
+ const hasOutcomeAcFailure = acs.some(
116
+ (ac: { type?: string; verdict?: string }) => ac.type === 'OUTCOME' && ac.verdict === 'FAIL',
117
+ );
118
+ return {
119
+ gate: gateName,
120
+ issue: wf.issue,
121
+ slug: wf.slug || slug,
122
+ failures: gate.failures.map(
123
+ (f: { check?: string; id?: string; detail?: string; message?: string }) => ({
124
+ check: f.check || f.id || 'unknown',
125
+ detail: f.detail || f.message || JSON.stringify(f),
126
+ }),
127
+ ),
128
+ hasOutcomeAcFailure,
129
+ };
130
+ }
131
+ }
132
+ } catch { /* skip malformed */ }
133
+
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * Determine the enforcement action (block/nag/pass) for a given gate state and tool call.
139
+ */
140
+ export function makeEnforcementDecision(pending: GatePending, toolName: string): EnforcementDecision {
141
+ const isSkillCall = toolName === 'Skill';
142
+ const failureText = formatFailures(pending.failures);
143
+
144
+ // OUTCOME AC failure -> immediate block on Skill calls
145
+ if (pending.outcome_ac_failure && isSkillCall) {
146
+ return {
147
+ action: 'block',
148
+ decision: 'block',
149
+ reason: `OUTCOME AC failed — must fix before proceeding. Gate: ${pending.gate}, issue #${pending.issue}.\n${failureText}`,
150
+ newStrikeCount: pending.strike_count,
151
+ };
152
+ }
153
+
154
+ // Strike-based block on Skill calls
155
+ if (isSkillCall && pending.strike_count >= pending.max_strikes) {
156
+ return {
157
+ action: 'block',
158
+ decision: 'block',
159
+ reason: `Gate blocked after ${pending.strike_count} strikes: ${pending.gate} (issue #${pending.issue}).\n${failureText}\nFix the failures or post skip-reason to the issue.`,
160
+ newStrikeCount: pending.strike_count,
161
+ };
162
+ }
163
+
164
+ // Nag — only count strikes for Skill calls
165
+ const newStrikeCount = isSkillCall ? pending.strike_count + 1 : pending.strike_count;
166
+
167
+ const reminder = [
168
+ '<system-reminder>',
169
+ `⚠️ GATE FAIL (${pending.gate}): issue #${pending.issue}`,
170
+ failureText,
171
+ `Strike ${newStrikeCount}/${pending.max_strikes}. Fix before proceeding or post skip-reason to issue.`,
172
+ '</system-reminder>',
173
+ ].join('\n');
174
+
175
+ return {
176
+ action: 'nag',
177
+ reminder,
178
+ newStrikeCount,
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Load cached strike count from gate-pending.json if it matches the current failure.
184
+ */
185
+ export function loadStrikeCount(pendingFile: string, issue: number, gate: string): number {
186
+ if (!existsSync(pendingFile)) return 0;
187
+ try {
188
+ const cached = JSON.parse(readFileSync(pendingFile, 'utf-8'));
189
+ if (cached.issue === issue && cached.gate === gate) {
190
+ return cached.strike_count || 0;
191
+ }
192
+ } catch {}
193
+ return 0;
194
+ }
195
+
196
+ /**
197
+ * Build a GatePending object from a workflow gate failure and session context.
198
+ */
199
+ export function buildGatePending(
200
+ wfFailure: WorkflowGateFailure,
201
+ sessionId: string,
202
+ strikeCount: number,
203
+ ): GatePending {
204
+ return {
205
+ session_id: sessionId,
206
+ gate: wfFailure.gate,
207
+ issue: wfFailure.issue,
208
+ slug: wfFailure.slug,
209
+ failures: wfFailure.failures,
210
+ strike_count: strikeCount,
211
+ max_strikes: 3,
212
+ outcome_ac_failure: wfFailure.hasOutcomeAcFailure,
213
+ created_at: new Date().toISOString(),
214
+ expires_ts: Date.now() + (4 * 60 * 60 * 1000),
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Log an enforcement signal event to the signals file.
220
+ *
221
+ * SC-504: appendFileSync creates the file if absent — the previous
222
+ * existence guard silently dropped signals on first write.
223
+ */
224
+ export function logSignal(signalsDir: string, signalsFile: string, event: Record<string, unknown>): void {
225
+ try {
226
+ if (!existsSync(signalsDir)) mkdirSync(signalsDir, { recursive: true });
227
+ appendFileSync(signalsFile, JSON.stringify(event) + '\n', 'utf-8');
228
+ } catch (err) {
229
+ console.error(`[GateEnforcement] Signal log write failed: ${err}`);
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Everything the hook needs from its environment. Passed in rather than
235
+ * read from module scope so the whole decision path is callable from a test.
236
+ */
237
+ export interface GateEnforcementInput {
238
+ /** Directory holding the per-issue workflow-state.json files. */
239
+ workDir: string;
240
+ /** Directory for the signals log; created on demand. */
241
+ signalsDir: string;
242
+ /** Signals JSONL path. */
243
+ signalsFile: string;
244
+ /** gate-pending.json path — the strike counter's home. */
245
+ pendingFile: string;
246
+ /** Project root, scanned for doc-hygiene findings (SC-508). */
247
+ projectRoot: string;
248
+ sessionId: string;
249
+ toolName: string;
250
+ }
251
+
252
+ export interface GateEnforcementResult {
253
+ /** What the hook should print on stdout, or null to stay silent. */
254
+ stdout: string | null;
255
+ action: EnforcementAction;
256
+ }
257
+
258
+ /**
259
+ * The whole GateEnforcement decision, extracted from the hook (SC-369).
260
+ *
261
+ * The hook is now a trigger: parse stdin, call this, print, exit 0. Keeping
262
+ * the logic here is what makes it reachable by test/gate-enforcement.test.ts
263
+ * without simulating a PreToolUse payload.
264
+ */
265
+ /**
266
+ * One emitter for both enforcement outcomes, so a block and a nag cannot drift
267
+ * into different event shapes. `reason` is attributed only for a block: a nag
268
+ * has no reason, and emitting one anyway would make every nag look like a
269
+ * near-block in the signal history.
270
+ */
271
+ export function logEnforcementSignal(
272
+ signalsDir: string,
273
+ signalsFile: string,
274
+ pending: GatePending,
275
+ tool: string,
276
+ action: 'block' | 'nag',
277
+ strike: number,
278
+ ): void {
279
+ logSignal(signalsDir, signalsFile, {
280
+ ts: new Date().toISOString(),
281
+ type: 'gate_enforcement',
282
+ gate: pending.gate,
283
+ issue: pending.issue,
284
+ strike,
285
+ tool,
286
+ action,
287
+ ...(action === 'block'
288
+ ? { reason: pending.outcome_ac_failure ? 'outcome_ac_failure' : 'max_strikes' }
289
+ : {}),
290
+ });
291
+ }
292
+
293
+ export function runGateEnforcement(input: GateEnforcementInput): GateEnforcementResult {
294
+ const wfFailure = findWorkflowGateFailure(input.workDir);
295
+ if (!wfFailure) {
296
+ if (existsSync(input.pendingFile)) {
297
+ try {
298
+ unlinkSync(input.pendingFile);
299
+ } catch (err) {
300
+ console.error(`[GateEnforcement] Could not clear ${input.pendingFile}: ${err}`);
301
+ }
302
+ }
303
+ return { stdout: null, action: 'pass' };
304
+ }
305
+
306
+ const strikeCount = loadStrikeCount(input.pendingFile, wfFailure.issue, wfFailure.gate);
307
+ const pending = buildGatePending(wfFailure, input.sessionId, strikeCount);
308
+ const decision = makeEnforcementDecision(pending, input.toolName);
309
+
310
+ if (decision.action === 'block') {
311
+ logEnforcementSignal(
312
+ input.signalsDir, input.signalsFile, pending, input.toolName, 'block', pending.strike_count,
313
+ );
314
+ return {
315
+ stdout: JSON.stringify({ decision: 'block', reason: decision.reason }),
316
+ action: 'block',
317
+ };
318
+ }
319
+
320
+ if (input.toolName === 'Skill') {
321
+ try {
322
+ writeFileSync(
323
+ input.pendingFile,
324
+ JSON.stringify({ ...pending, strike_count: decision.newStrikeCount }, null, 2),
325
+ 'utf-8',
326
+ );
327
+ } catch (err) {
328
+ console.error(`[GateEnforcement] Strike count write failed: ${err}`);
329
+ }
330
+ }
331
+
332
+ logEnforcementSignal(
333
+ input.signalsDir, input.signalsFile, pending, input.toolName, 'nag', decision.newStrikeCount,
334
+ );
335
+ logDocHygieneSignals(input.signalsDir, input.signalsFile, input.projectRoot);
336
+
337
+ return { stdout: decision.reminder ?? null, action: 'nag' };
338
+ }
339
+
340
+ /**
341
+ * SC-508: doc-hygiene findings ride along as signals for promotion tracking.
342
+ * Best-effort by design — a hygiene scan failure must not block a tool call —
343
+ * but it says so on stderr rather than vanishing.
344
+ */
345
+ export function logDocHygieneSignals(
346
+ signalsDir: string,
347
+ signalsFile: string,
348
+ projectRoot: string,
349
+ check: typeof checkDocHygiene = checkDocHygiene,
350
+ ): number {
351
+ try {
352
+ const result = check(projectRoot);
353
+ if (result.pass) return 0;
354
+ for (const finding of result.findings) {
355
+ logSignal(signalsDir, signalsFile, {
356
+ ts: new Date().toISOString(), type: 'doc-hygiene',
357
+ checkId: finding.checkId, file: finding.file,
358
+ level: finding.level, message: finding.message,
359
+ });
360
+ }
361
+ return result.findings.length;
362
+ } catch (err) {
363
+ console.error(`[GateEnforcement] doc-hygiene signal sweep skipped: ${err}`);
364
+ return 0;
365
+ }
366
+ }