@event4u/agent-config 9.7.0 → 9.8.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 (185) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +144 -0
  3. package/README.md +5 -5
  4. package/dist/agent-src/commands/commit/in-chunks.md +8 -0
  5. package/dist/agent-src/commands/commit.md +17 -0
  6. package/dist/agent-src/commands/pr/create.md +4 -0
  7. package/dist/agent-src/contexts/override-system.md +75 -5
  8. package/dist/agent-src/rules/context-hygiene.md +2 -0
  9. package/dist/agent-src/rules/doc-screenshot-hygiene.md +97 -0
  10. package/dist/agent-src/rules/domain-safety-pii.md +1 -0
  11. package/dist/agent-src/rules/external-code-graph-interop.md +13 -3
  12. package/dist/agent-src/rules/framework-neutrality-in-generic-skills.md +2 -0
  13. package/dist/agent-src/rules/git-history-discipline.md +2 -0
  14. package/dist/agent-src/rules/language-and-tone.md +2 -0
  15. package/dist/agent-src/rules/lethal-trifecta-guard.md +3 -0
  16. package/dist/agent-src/rules/media-governance-routing.md +2 -0
  17. package/dist/agent-src/rules/minimal-safe-diff.md +2 -0
  18. package/dist/agent-src/rules/no-roadmap-references.md +3 -0
  19. package/dist/agent-src/rules/non-destructive-by-default.md +20 -0
  20. package/dist/agent-src/rules/onboarding-gate.md +2 -0
  21. package/dist/agent-src/rules/output-discipline.md +2 -0
  22. package/dist/agent-src/rules/persona-governance.md +2 -0
  23. package/dist/agent-src/rules/preservation-guard.md +3 -0
  24. package/dist/agent-src/rules/roadmap-progress-sync.md +2 -0
  25. package/dist/agent-src/rules/secret-vcs-guard.md +106 -0
  26. package/dist/agent-src/rules/security-sensitive-stop.md +1 -1
  27. package/dist/agent-src/rules/skill-quality.md +2 -0
  28. package/dist/agent-src/rules/source-confidentiality.md +2 -0
  29. package/dist/agent-src/rules/source-of-truth.md +2 -0
  30. package/dist/agent-src/rules/telegraph-speak.md +2 -0
  31. package/dist/agent-src/rules/token-optimizer-maintenance.md +2 -0
  32. package/dist/agent-src/rules/tool-safety.md +1 -0
  33. package/dist/agent-src/rules/verify-before-complete.md +2 -0
  34. package/dist/agent-src/skills/adr-create/SKILL.md +17 -1
  35. package/dist/agent-src/skills/code-intelligence/SKILL.md +94 -0
  36. package/dist/agent-src/skills/gated-reach/SKILL.md +185 -0
  37. package/dist/agent-src/skills/gated-reach/evals/triggers.json +72 -0
  38. package/dist/agent-src/skills/image-analyser/SKILL.md +14 -12
  39. package/dist/agent-src/skills/image-editing/SKILL.md +1 -0
  40. package/dist/agent-src/skills/readme-writing/SKILL.md +6 -1
  41. package/dist/agent-src/skills/screenshot-hygiene/SKILL.md +171 -0
  42. package/dist/agent-src/skills/secrets-management/SKILL.md +44 -1
  43. package/dist/agent-src/skills/subagent-orchestration/prompts/adversarial-verification-council.md +29 -0
  44. package/dist/agent-src/skills/subagent-orchestration/prompts/do-and-judge-two-stage.md +29 -0
  45. package/dist/agent-src/skills/subagent-orchestration/prompts/do-and-judge.md +29 -0
  46. package/dist/agent-src/skills/subagent-orchestration/prompts/do-competitively.md +29 -0
  47. package/dist/agent-src/skills/subagent-orchestration/prompts/do-in-parallel.md +29 -0
  48. package/dist/agent-src/skills/subagent-orchestration/prompts/do-in-steps.md +29 -0
  49. package/dist/agent-src/skills/subagent-orchestration/prompts/do-in-worktrees.md +29 -0
  50. package/dist/agent-src/skills/subagent-orchestration/prompts/judge-with-debate.md +29 -0
  51. package/dist/agent-src/skills/verify-repair-loop/SKILL.md +4 -0
  52. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  53. package/dist/agent-src/templates/github-workflows/secret-scan.yml +65 -0
  54. package/dist/cli/configRoot.js +112 -0
  55. package/dist/cli/configRoot.js.map +1 -0
  56. package/dist/cli/configRoot.test.js +97 -0
  57. package/dist/cli/configRoot.test.js.map +1 -0
  58. package/dist/cli/help.js +4 -1
  59. package/dist/cli/help.js.map +1 -1
  60. package/dist/cli/main.js +19 -2
  61. package/dist/cli/main.js.map +1 -1
  62. package/dist/cli/registry.js +1 -0
  63. package/dist/cli/registry.js.map +1 -1
  64. package/dist/discovery/deprecation-report.md +1 -1
  65. package/dist/discovery/discovery-manifest.json +161 -44
  66. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  67. package/dist/discovery/discovery-manifest.summary.md +4 -4
  68. package/dist/discovery/orphan-report.md +1 -1
  69. package/dist/discovery/packs.json +13 -8
  70. package/dist/discovery/trust-report.md +11 -11
  71. package/dist/discovery/workspaces.json +11 -6
  72. package/dist/install/install.mjs +16 -0
  73. package/dist/mcp/registry-manifest.json +3 -3
  74. package/dist/router.json +1 -1
  75. package/dist/server/app.js +10 -0
  76. package/dist/server/app.js.map +1 -1
  77. package/dist/server/routes/ping.js +18 -0
  78. package/dist/server/routes/ping.js.map +1 -1
  79. package/dist/server/schemas/settings.js +8 -0
  80. package/dist/server/schemas/settings.js.map +1 -1
  81. package/dist/server/serverInfo.js +6 -2
  82. package/dist/server/serverInfo.js.map +1 -1
  83. package/dist/server/token.js +11 -4
  84. package/dist/server/token.js.map +1 -1
  85. package/dist/server/writeRoot.js +15 -1
  86. package/dist/server/writeRoot.js.map +1 -1
  87. package/dist/shared/capabilities.js +33 -0
  88. package/dist/shared/capabilities.js.map +1 -0
  89. package/dist/shared/capabilities.test.js +39 -0
  90. package/dist/shared/capabilities.test.js.map +1 -0
  91. package/dist/ui/assets/{index-BiEZiZ31.js → index-CrmZ34Rg.js} +16 -16
  92. package/dist/ui/assets/index-CrmZ34Rg.js.map +1 -0
  93. package/dist/ui/index.html +14 -5
  94. package/docs/CLAIMS.md +62 -37
  95. package/docs/architecture.md +2 -2
  96. package/docs/benchmark.md +137 -0
  97. package/docs/catalog.md +8 -3
  98. package/docs/comparison.yaml +44 -2
  99. package/docs/contracts/local-server-ports.md +53 -0
  100. package/docs/contracts/no-runtime-boundary.md +1 -1
  101. package/docs/contracts/subagent-boundary.md +15 -0
  102. package/docs/customization.md +14 -3
  103. package/docs/decisions/ADR-016-installer-architecture.md +2 -0
  104. package/docs/decisions/ADR-088-no-external-runtime-federation.md +1 -1
  105. package/docs/decisions/ADR-094-agent-memory-layer-removal.md +1 -1
  106. package/docs/decisions/ADR-109-subagent-v1-contract.md +2 -0
  107. package/docs/decisions/ADR-110-discipline-profile-resolution-locus.md +2 -0
  108. package/docs/decisions/ADR-113-ci-native-release-label-trigger.md +11 -3
  109. package/docs/decisions/ADR-124-embedded-engine-doctrine.md +255 -0
  110. package/docs/decisions/ADR-125-doc-screenshot-anonymization.md +131 -0
  111. package/docs/decisions/ADR-126-internet-reach-operator-tooling.md +254 -0
  112. package/docs/decisions/ADR-127-enforcement-claims-must-resolve.md +150 -0
  113. package/docs/decisions/ADR-128-executable-evidence-and-measured-escalation.md +201 -0
  114. package/docs/decisions/INDEX.md +21 -0
  115. package/docs/decisions/engine-reclassification-2026-07.md +104 -0
  116. package/docs/distribution/awesome-list-submission.md +1 -1
  117. package/docs/distribution/registries.md +36 -27
  118. package/docs/enforcement-by-host.md +7 -0
  119. package/docs/featured-skills.md +2 -2
  120. package/docs/getting-started-by-role.md +1 -1
  121. package/docs/getting-started.md +1 -1
  122. package/docs/governance-advantage.md +1 -1
  123. package/docs/guides/gated-platform-reads.md +221 -0
  124. package/docs/positioning-evidence.md +1 -1
  125. package/docs/proof.md +92 -16
  126. package/docs/threat-model.md +1 -0
  127. package/package.json +5 -2
  128. package/src/config/agent-settings.template.yml +43 -0
  129. package/src/config/reach-channels.yml +217 -0
  130. package/src/config/reach-prescriptions-intake.yml +200 -0
  131. package/src/scripts/_dispatch.bash +15 -0
  132. package/src/scripts/_lib/exec_evidence.ts +251 -0
  133. package/src/scripts/_lib/fixtures/secret-detector/negatives.txt +10 -0
  134. package/src/scripts/_lib/fixtures/secret-detector/positives.txt +11 -0
  135. package/src/scripts/_lib/kernel_rules.ts +46 -0
  136. package/src/scripts/_lib/reddit_thread_parse.ts +598 -0
  137. package/src/scripts/_lib/risk_paths.ts +160 -0
  138. package/src/scripts/_lib/secret_detector.test.ts +103 -0
  139. package/src/scripts/_lib/secret_detector.ts +319 -0
  140. package/src/scripts/_lib/tool_probe.ts +359 -0
  141. package/src/scripts/adr/regenerate_index.ts +81 -6
  142. package/src/scripts/audit_adr_coverage.ts +33 -0
  143. package/src/scripts/build_proof.ts +162 -0
  144. package/src/scripts/check_adr_frontmatter.ts +195 -0
  145. package/src/scripts/check_artefact_count_messaging.ts +4 -0
  146. package/src/scripts/check_backstop_debt.ts +200 -0
  147. package/src/scripts/check_claims.ts +188 -8
  148. package/src/scripts/check_comparison.ts +12 -0
  149. package/src/scripts/check_enforcement_coverage.ts +592 -0
  150. package/src/scripts/check_kernel_rule_bundle.ts +16 -12
  151. package/src/scripts/check_reach_channels.ts +407 -0
  152. package/src/scripts/check_reach_staleness.ts +364 -0
  153. package/src/scripts/check_secret_leak.test.ts +47 -0
  154. package/src/scripts/check_secret_leak.ts +290 -0
  155. package/src/scripts/code_graph/build.ts +0 -0
  156. package/src/scripts/code_graph/cli.ts +207 -0
  157. package/src/scripts/code_graph/detect.ts +134 -0
  158. package/src/scripts/code_graph/extract.ts +386 -0
  159. package/src/scripts/code_graph/loader.ts +123 -0
  160. package/src/scripts/code_graph/query.ts +176 -0
  161. package/src/scripts/code_graph/sanitize.ts +30 -0
  162. package/src/scripts/code_graph/types.ts +83 -0
  163. package/src/scripts/code_graph/validate.ts +63 -0
  164. package/src/scripts/external_sources_denylist.json +3 -1
  165. package/src/scripts/generate_subagent_floor.ts +194 -0
  166. package/src/scripts/hook_manifest.yaml +13 -3
  167. package/src/scripts/hooks/code_graph_nudge_hook.ts +184 -0
  168. package/src/scripts/iron_law_sha.ts +3 -12
  169. package/src/scripts/lint_override_kernel_guard.ts +219 -0
  170. package/src/scripts/measure_rule_budget.ts +3 -12
  171. package/src/scripts/postinstall_gui.ts +129 -0
  172. package/src/scripts/reach_doctor.ts +1651 -0
  173. package/src/scripts/release.ts +24 -3
  174. package/src/scripts/risk_escalation_shadow.ts +160 -0
  175. package/src/scripts/schemas/agent-settings.schema.json +23 -0
  176. package/src/scripts/schemas/reach-channels.schema.json +134 -0
  177. package/src/scripts/schemas/reach-doctor-payload.schema.json +220 -0
  178. package/src/scripts/schemas/rule.schema.json +10 -0
  179. package/src/scripts/skill_linter.ts +55 -0
  180. package/src/scripts/validate_reach_prescriptions.ts +751 -0
  181. package/src/server/schemas/settings.ts +16 -0
  182. package/src/shared/capabilities.test.ts +43 -0
  183. package/src/shared/capabilities.ts +75 -0
  184. package/src/templates/minimal/agents-overrides-readme.md +20 -0
  185. package/dist/ui/assets/index-BiEZiZ31.js.map +0 -1
@@ -0,0 +1,592 @@
1
+ #!/usr/bin/env tsx
2
+ /**
3
+ * Enforcement-coverage gate — how many rules have a backstop that actually runs.
4
+ *
5
+ * This package's positioning is falsifiability, and its own doctrine says a MUST
6
+ * that depends on agent self-report is honor-system theatre. That doctrine had
7
+ * no instrument: 107 rules carry `type / tier / description / …` and not one
8
+ * field said what enforces them. This script is that instrument.
9
+ *
10
+ * The load-bearing design choice is **resolution over declaration**. A rule that
11
+ * declares `validator:src/scripts/lint_x.ts` is NOT counted as enforced merely
12
+ * because the file exists — the script must also be *reachable*: referenced from
13
+ * a taskfile, a GitHub workflow, or the hook manifest. A linter that ships and
14
+ * runs nowhere is exactly the defect this gate exists to surface, and a
15
+ * declaration-only checker would rate it green. (Found on the first run:
16
+ * `lint_output_slop.ts` is wired nowhere while `output-discipline` asserts in
17
+ * shipped prose that violations cause a CI exit-code-2.)
18
+ *
19
+ * Second choice: **blocking and instrumenting are different tiers.** A hook
20
+ * registered `fail_closed: false` cannot fail a build; it writes evidence. It
21
+ * resolves to `observer`, never `validator`, and declaring it as one is reported
22
+ * as a misdeclaration rather than silently accepted.
23
+ *
24
+ * `none` is a legal, counted value. An honest recorded gap is worth more than a
25
+ * false claim of coverage — that is the whole point of the exercise.
26
+ *
27
+ * Usage:
28
+ * ./scripts-run src/scripts/check_enforcement_coverage # report
29
+ * ./scripts-run src/scripts/check_enforcement_coverage --json # machine
30
+ * ./scripts-run src/scripts/check_enforcement_coverage --check # ratchet
31
+ * ./scripts-run src/scripts/check_enforcement_coverage --write-baseline
32
+ *
33
+ * Exit codes: 0 ok · 1 ratchet regression (--check) · 2 usage/env error.
34
+ */
35
+
36
+ import * as fs from 'node:fs';
37
+ import * as path from 'node:path';
38
+ import { fileURLToPath, pathToFileURL } from 'node:url';
39
+
40
+ const _HERE = path.dirname(fileURLToPath(import.meta.url));
41
+ const REPO_ROOT = path.resolve(_HERE, '..', '..');
42
+ const RULES_DIR = path.join(REPO_ROOT, 'src', 'rules');
43
+ const HOOK_MANIFEST = path.join(REPO_ROOT, 'src', 'scripts', 'hook_manifest.yaml');
44
+ const BASELINE = path.join(REPO_ROOT, 'internal', 'reports', 'enforcement-coverage.json');
45
+
46
+ /**
47
+ * Two wiring corpora, deliberately separate.
48
+ *
49
+ * The first version treated `taskfiles/` and `.github/workflows/` as one bag, so
50
+ * "named in a taskfile" resolved to `validator` and counted under a headline that
51
+ * read "can actually fail a build". Which build? **No workflow invokes `task ci`,
52
+ * `ci-strict`, or `ci-fast`** — only the narrow `ci-cloud-bundle` and
53
+ * `ci-linear-digest`. So for a taskfile-only validator the honest answer was
54
+ * "a local run someone starts by hand", and the number said otherwise.
55
+ *
56
+ * That is the same defect the coverage gate was built to catch — a check whose
57
+ * wiring is weaker than the claim about it — committed by the gate itself. Hence
58
+ * the split: `validator` means CI runs it, `validator-local` means a human does.
59
+ */
60
+ const WORKFLOW_DIRS = [path.join(REPO_ROOT, '.github', 'workflows')];
61
+ const TASK_DIRS = [path.join(REPO_ROOT, 'taskfiles')];
62
+ const TASK_FILES = [path.join(REPO_ROOT, 'Taskfile.yml'), HOOK_MANIFEST];
63
+
64
+ export type Resolution =
65
+ | 'validator' // reachable from a WORKFLOW — CI fails without a human
66
+ | 'validator-local' // reachable only from a taskfile — fails a run someone starts
67
+ | 'test' // test file exists; the suite runs it
68
+ | 'hook' // registered in the hook manifest with fail_closed: true
69
+ | 'observer' // instruments only — never blocks
70
+ | 'unwired' // declared script exists but nothing runs it ← the D1 class
71
+ | 'missing' // declared target does not exist at all
72
+ | 'none'; // honest, recorded gap
73
+
74
+ export interface RuleCoverage {
75
+ id: string;
76
+ tier: string;
77
+ type: string;
78
+ declared: string[];
79
+ resolutions: Resolution[];
80
+ /** Strongest resolution, by the ordering in `RANK`. */
81
+ effective: Resolution;
82
+ notes: string[];
83
+ }
84
+
85
+ /** Strength order — a rule is credited with its strongest resolving backstop. */
86
+ const RANK: Resolution[] = [
87
+ 'validator',
88
+ 'test',
89
+ 'hook',
90
+ 'validator-local',
91
+ 'observer',
92
+ 'unwired',
93
+ 'missing',
94
+ 'none',
95
+ ];
96
+
97
+ /**
98
+ * A resolution that fails a CI build — the headline number.
99
+ *
100
+ * `validator-local` is NOT here, and that is the whole correction. It ranks above
101
+ * `observer` (it does block *something*) and below `hook` (which fires in the
102
+ * agent runtime without anyone asking), but a gate only a human can start is not
103
+ * what "can fail a build" means to a reader.
104
+ */
105
+ const BLOCKING: ReadonlySet<Resolution> = new Set<Resolution>(['validator', 'test', 'hook']);
106
+
107
+ // ---------------------------------------------------------------- frontmatter
108
+
109
+ /**
110
+ * Read frontmatter, keeping list values as arrays.
111
+ *
112
+ * `measure_rule_budget.strip_frontmatter` is scalar-only by design; `enforced_by`
113
+ * is a list, so this reader handles both `key: [a, b]` and block `- item` form.
114
+ * Deliberately not a general YAML parser: the accepted shape is exactly what the
115
+ * rule schema permits, and anything else is left for the schema validator to
116
+ * reject rather than silently coerced here.
117
+ */
118
+ export function read_frontmatter(text: string): Record<string, string | string[]> {
119
+ if (!text.startsWith('---\n')) return {};
120
+ const end = text.indexOf('\n---\n', 4);
121
+ if (end === -1) return {};
122
+ const out: Record<string, string | string[]> = {};
123
+ const lines = text.slice(4, end).split('\n');
124
+
125
+ let pending_key: string | null = null;
126
+ let pending_list: string[] = [];
127
+
128
+ const flush = (): void => {
129
+ if (pending_key !== null) {
130
+ out[pending_key] = pending_list;
131
+ pending_key = null;
132
+ pending_list = [];
133
+ }
134
+ };
135
+
136
+ for (const raw of lines) {
137
+ const line = raw.replace(/\s+$/, '');
138
+ if (!line || line.trimStart().startsWith('#')) continue;
139
+
140
+ const block_item = /^\s+-\s+(.*)$/.exec(line);
141
+ const item_value = block_item?.[1];
142
+ if (item_value !== undefined && pending_key !== null) {
143
+ pending_list.push(unquote(item_value.trim()));
144
+ continue;
145
+ }
146
+ flush();
147
+
148
+ const idx = line.indexOf(':');
149
+ if (idx === -1) continue;
150
+ const key = line.slice(0, idx).trim();
151
+ const val = line.slice(idx + 1).trim();
152
+
153
+ if (val === '') {
154
+ // Either a block list follows, or an empty scalar. Assume list; if no
155
+ // item follows, flush() records an empty array, which reads as absent.
156
+ pending_key = key;
157
+ pending_list = [];
158
+ continue;
159
+ }
160
+ if (val.startsWith('[') && val.endsWith(']')) {
161
+ const inner = val.slice(1, -1).trim();
162
+ out[key] = inner === '' ? [] : inner.split(',').map((s) => unquote(s.trim()));
163
+ continue;
164
+ }
165
+ out[key] = unquote(val);
166
+ }
167
+ flush();
168
+ return out;
169
+ }
170
+
171
+ function unquote(s: string): string {
172
+ if (s.length >= 2 && ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'")))) {
173
+ return s.slice(1, -1);
174
+ }
175
+ return s;
176
+ }
177
+
178
+ // ------------------------------------------------------------------- wiring
179
+
180
+ /**
181
+ * Every file whose text decides whether a script is reachable.
182
+ *
183
+ * Read once and concatenated: the question is only ever "does this path appear
184
+ * anywhere that runs things", so a single haystack is both correct and cheap.
185
+ */
186
+ function load_corpus(dirs: readonly string[], files: readonly string[] = []): string {
187
+ const parts: string[] = [];
188
+ for (const f of files) {
189
+ if (fs.existsSync(f)) parts.push(fs.readFileSync(f, 'utf-8'));
190
+ }
191
+ for (const dir of dirs) {
192
+ if (!fs.existsSync(dir)) continue;
193
+ for (const entry of walk(dir)) {
194
+ if (/\.(ya?ml)$/.test(entry)) parts.push(fs.readFileSync(entry, 'utf-8'));
195
+ }
196
+ }
197
+ return parts.join('\n');
198
+ }
199
+
200
+ /**
201
+ * Scripts reachable from a CI entry point, following umbrella indirection.
202
+ *
203
+ * A direct-mention test is not sufficient and the miss is not hypothetical:
204
+ * `lint_skill_frontmatter_safety.ts` is never named in a taskfile, yet it runs on
205
+ * every CI pass as a sub-check of the `lint_agent_security` umbrella, which is.
206
+ * Reporting it unwired would be a false alarm — the same defect class, pointed
207
+ * the other way. So reachability is transitive: seed with the scripts CI names
208
+ * directly, then expand through the scripts those name, to a fixed point.
209
+ *
210
+ * Deliberately NOT part of the seed: `_dispatch.bash`. A CLI subcommand is
211
+ * something a human or agent may invoke; enforcement is something that runs
212
+ * whether or not anyone chooses to. Conflating the two is how a package ends up
213
+ * believing an on-demand tool is a gate.
214
+ */
215
+ function reachable_scripts(wiring: string): Set<string> {
216
+ const scripts_dir = path.join(REPO_ROOT, 'src', 'scripts');
217
+ const all: string[] = fs.existsSync(scripts_dir)
218
+ ? walk(scripts_dir).filter((p) => p.endsWith('.ts'))
219
+ : [];
220
+
221
+ const rel = (abs: string): string => path.relative(REPO_ROOT, abs);
222
+ const stem = (abs: string): string => path.basename(abs).replace(/\.ts$/, '');
223
+
224
+ const reached = new Set<string>();
225
+ for (const abs of all) {
226
+ if (wiring.includes(rel(abs)) || wiring.includes(stem(abs))) reached.add(rel(abs));
227
+ }
228
+
229
+ let grew = true;
230
+ while (grew) {
231
+ grew = false;
232
+ const frontier = [...reached];
233
+ const bodies = frontier
234
+ .map((r) => {
235
+ const abs = path.join(REPO_ROOT, r);
236
+ return fs.existsSync(abs) ? strip_comments(fs.readFileSync(abs, 'utf-8')) : '';
237
+ })
238
+ .join('\n');
239
+ for (const abs of all) {
240
+ const r = rel(abs);
241
+ if (reached.has(r)) continue;
242
+ if (mentions_as_code(bodies, path.basename(abs), stem(abs))) {
243
+ reached.add(r);
244
+ grew = true;
245
+ }
246
+ }
247
+ }
248
+ return reached;
249
+ }
250
+
251
+ /**
252
+ * Drop comments before deciding whether one script invokes another.
253
+ *
254
+ * This function exists because its absence produced a live false negative. The
255
+ * first version matched any textual occurrence, so the moment THIS file's own
256
+ * docstring named `lint_output_slop.ts` as an example of an unwired linter, the
257
+ * closure "reached" it and the gate reported the very defect it was built to
258
+ * catch as fixed. A prose mention is not a call.
259
+ *
260
+ * That is the general class: a check that matches on substring presence rather
261
+ * than on the resolved structure is fail-open by construction. Stripping
262
+ * comments and requiring a quoted specifier is the narrow structural test —
263
+ * invocation always goes through a path string or an import specifier.
264
+ */
265
+ export function strip_comments(src: string): string {
266
+ return src
267
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
268
+ .split('\n')
269
+ .map((l) => l.replace(/(^|[^:])\/\/.*$/, '$1'))
270
+ .join('\n');
271
+ }
272
+
273
+ /** True when `base`/`stem` appears inside a quoted specifier — an invocation shape. */
274
+ export function mentions_as_code(haystack: string, base: string, stem: string): boolean {
275
+ for (const needle of [base, stem]) {
276
+ const q = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
277
+ if (new RegExp(`['"\`][^'"\`]*${q}[^'"\`]*['"\`]`).test(haystack)) return true;
278
+ }
279
+ return false;
280
+ }
281
+
282
+ function walk(dir: string): string[] {
283
+ const out: string[] = [];
284
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
285
+ const p = path.join(dir, e.name);
286
+ if (e.isDirectory()) out.push(...walk(p));
287
+ else out.push(p);
288
+ }
289
+ return out;
290
+ }
291
+
292
+ /**
293
+ * Hook name → whether it can fail a build.
294
+ *
295
+ * Parsed with a narrow reader rather than a YAML dependency: the manifest's
296
+ * `concerns:` block is a fixed two-level shape, and the only fact needed is the
297
+ * `fail_closed` flag per concern.
298
+ */
299
+ export function parse_hook_manifest(text: string): Map<string, boolean> {
300
+ const out = new Map<string, boolean>();
301
+ let in_concerns = false;
302
+ let current: string | null = null;
303
+ for (const raw of text.split('\n')) {
304
+ const line = raw.replace(/\s+$/, '');
305
+ if (/^concerns:\s*$/.test(line)) { in_concerns = true; continue; }
306
+ if (!in_concerns) continue;
307
+ if (/^\S/.test(line)) break; // left the concerns block
308
+
309
+ const concern_name = /^ {2}([a-z0-9_-]+):\s*$/.exec(line)?.[1];
310
+ if (concern_name !== undefined) {
311
+ current = concern_name;
312
+ out.set(current, false);
313
+ continue;
314
+ }
315
+ const fc = /^\s+fail_closed:\s*(true|false)\s*$/.exec(line)?.[1];
316
+ if (fc !== undefined && current !== null) out.set(current, fc === 'true');
317
+ }
318
+ return out;
319
+ }
320
+
321
+ // ---------------------------------------------------------------- resolution
322
+
323
+ export function resolve_one(
324
+ decl: string,
325
+ ctx: {
326
+ /** Scripts reachable from a GitHub workflow (transitively). */
327
+ reachable_ci: Set<string>;
328
+ /** Scripts reachable from a taskfile or the hook manifest (transitively). */
329
+ reachable_local: Set<string>;
330
+ hooks: Map<string, boolean>;
331
+ exists: (rel: string) => boolean;
332
+ },
333
+ ): { resolution: Resolution; note?: string } {
334
+ if (decl === 'none') return { resolution: 'none' };
335
+
336
+ const idx = decl.indexOf(':');
337
+ const kind = decl.slice(0, idx);
338
+ const target = decl.slice(idx + 1);
339
+
340
+ if (kind === 'observer') return { resolution: 'observer' };
341
+
342
+ if (kind === 'hook') {
343
+ if (!ctx.hooks.has(target)) {
344
+ return { resolution: 'missing', note: `hook '${target}' is not registered in hook_manifest.yaml` };
345
+ }
346
+ if (!ctx.hooks.get(target)) {
347
+ // Registered but non-blocking. It instruments; it does not enforce.
348
+ return {
349
+ resolution: 'observer',
350
+ note: `hook '${target}' is fail_closed: false — it instruments, it cannot block; counted as observer`,
351
+ };
352
+ }
353
+ return { resolution: 'hook' };
354
+ }
355
+
356
+ if (kind === 'test') {
357
+ return ctx.exists(target)
358
+ ? { resolution: 'test' }
359
+ : { resolution: 'missing', note: `test path does not exist: ${target}` };
360
+ }
361
+
362
+ if (kind === 'validator') {
363
+ if (!ctx.exists(target)) {
364
+ return { resolution: 'missing', note: `validator script does not exist: ${target}` };
365
+ }
366
+ // Resolution, not declaration — and now: reachable from WHAT.
367
+ if (ctx.reachable_ci.has(target)) return { resolution: 'validator' };
368
+ if (ctx.reachable_local.has(target)) {
369
+ return {
370
+ resolution: 'validator-local',
371
+ note: `validator '${target}' is reachable only from a taskfile — no workflow runs it, so it fails a local run someone starts, not a CI build`,
372
+ };
373
+ }
374
+ return {
375
+ resolution: 'unwired',
376
+ note: `validator '${target}' exists but is referenced by no taskfile, workflow, or hook manifest — it runs nowhere`,
377
+ };
378
+ }
379
+
380
+ return { resolution: 'missing', note: `unrecognised enforced_by form: ${decl}` };
381
+ }
382
+
383
+ export function strongest(resolutions: Resolution[]): Resolution {
384
+ if (resolutions.length === 0) return 'none';
385
+ let best: Resolution = 'none';
386
+ let best_rank = Number.POSITIVE_INFINITY;
387
+ for (const r of resolutions) {
388
+ const rank = RANK.indexOf(r);
389
+ if (rank < best_rank) {
390
+ best = r;
391
+ best_rank = rank;
392
+ }
393
+ }
394
+ return best;
395
+ }
396
+
397
+ // -------------------------------------------------------------------- report
398
+
399
+ export function collect(): RuleCoverage[] {
400
+ const ci_corpus = load_corpus(WORKFLOW_DIRS);
401
+ const local_corpus = load_corpus(TASK_DIRS, TASK_FILES);
402
+ const hooks = fs.existsSync(HOOK_MANIFEST)
403
+ ? parse_hook_manifest(fs.readFileSync(HOOK_MANIFEST, 'utf-8'))
404
+ : new Map<string, boolean>();
405
+ const exists = (rel: string): boolean => fs.existsSync(path.join(REPO_ROOT, rel));
406
+ // Seeded separately so the umbrella expansion answers "reachable from CI"
407
+ // rather than "reachable from anything". The expansion itself was correct;
408
+ // it was the seed that conflated the two.
409
+ const reachable_ci = reachable_scripts(ci_corpus);
410
+ const reachable_local = reachable_scripts(`${ci_corpus}\n${local_corpus}`);
411
+
412
+ const out: RuleCoverage[] = [];
413
+ for (const name of fs.readdirSync(RULES_DIR).sort()) {
414
+ if (!name.endsWith('.md')) continue;
415
+ const fm = read_frontmatter(fs.readFileSync(path.join(RULES_DIR, name), 'utf-8'));
416
+ const raw = fm['enforced_by'];
417
+ const declared = Array.isArray(raw) ? raw : typeof raw === 'string' && raw ? [raw] : [];
418
+
419
+ const resolutions: Resolution[] = [];
420
+ const notes: string[] = [];
421
+ for (const d of declared) {
422
+ const { resolution, note } = resolve_one(d, { reachable_ci, reachable_local, hooks, exists });
423
+ resolutions.push(resolution);
424
+ if (note) notes.push(note);
425
+ }
426
+ out.push({
427
+ id: name.replace(/\.md$/, ''),
428
+ tier: String(fm['tier'] ?? '—'),
429
+ type: String(fm['type'] ?? '—'),
430
+ declared,
431
+ resolutions,
432
+ effective: strongest(resolutions),
433
+ notes,
434
+ });
435
+ }
436
+ return out;
437
+ }
438
+
439
+ export interface Summary {
440
+ total: number;
441
+ declared: number;
442
+ /** Fails a CI build without a human starting anything. The headline. */
443
+ blocking: number;
444
+ /** Reachable only from a taskfile — reported beside the headline, never folded in. */
445
+ local_only: number;
446
+ observer: number;
447
+ unwired: number;
448
+ missing: number;
449
+ undeclared: number;
450
+ blocking_pct: number;
451
+ }
452
+
453
+ export function summarise(rows: RuleCoverage[]): Summary {
454
+ const declared = rows.filter((r) => r.declared.length > 0);
455
+ const count = (p: (r: RuleCoverage) => boolean): number => rows.filter(p).length;
456
+ const blocking = count((r) => BLOCKING.has(r.effective));
457
+ return {
458
+ total: rows.length,
459
+ declared: declared.length,
460
+ blocking,
461
+ local_only: count((r) => r.effective === 'validator-local'),
462
+ observer: count((r) => r.effective === 'observer'),
463
+ unwired: count((r) => r.effective === 'unwired'),
464
+ missing: count((r) => r.effective === 'missing'),
465
+ undeclared: rows.length - declared.length,
466
+ blocking_pct: rows.length === 0 ? 0 : Math.round((blocking / rows.length) * 1000) / 10,
467
+ };
468
+ }
469
+
470
+ function main(argv: string[]): number {
471
+ const as_json = argv.includes('--json');
472
+ const check = argv.includes('--check');
473
+ const write = argv.includes('--write-baseline');
474
+
475
+ if (!fs.existsSync(RULES_DIR)) {
476
+ process.stderr.write(`❌ check_enforcement_coverage: no rules dir at ${RULES_DIR}\n`);
477
+ return 2;
478
+ }
479
+
480
+ const rows = collect();
481
+ const summary = summarise(rows);
482
+
483
+ if (as_json) {
484
+ process.stdout.write(JSON.stringify({ summary, rules: rows }, null, 2) + '\n');
485
+ return 0;
486
+ }
487
+
488
+ if (write) {
489
+ fs.mkdirSync(path.dirname(BASELINE), { recursive: true });
490
+ fs.writeFileSync(
491
+ BASELINE,
492
+ JSON.stringify(
493
+ {
494
+ _doc:
495
+ 'Enforcement-coverage baseline. `blocking` counts rules whose strongest ' +
496
+ 'enforced_by resolves to something that can fail a build. Coverage is a ' +
497
+ 'ratchet: --check fails when blocking falls or unwired rises. Regenerate ' +
498
+ 'intentionally with --write-baseline when the change is the point.',
499
+ summary,
500
+ },
501
+ null,
502
+ 2,
503
+ ) + '\n',
504
+ );
505
+ process.stdout.write(`✅ wrote baseline → ${path.relative(REPO_ROOT, BASELINE)}\n`);
506
+ return 0;
507
+ }
508
+
509
+ // Human report.
510
+ const lines: string[] = [];
511
+ lines.push(
512
+ `enforcement coverage · ${summary.blocking}/${summary.total} rules (${summary.blocking_pct}%) ` +
513
+ `have a backstop that fails a CI build`,
514
+ );
515
+ lines.push(
516
+ ` declared ${summary.declared} · local-only ${summary.local_only} · observer ${summary.observer} · ` +
517
+ `unwired ${summary.unwired} · missing ${summary.missing} · undeclared ${summary.undeclared}`,
518
+ );
519
+ if (summary.local_only > 0) {
520
+ lines.push(
521
+ ` local-only = a validator no workflow runs. It fails \`task ci\` if someone types it; ` +
522
+ `it does not fail the build. Counted separately, never in the headline.`,
523
+ );
524
+ }
525
+
526
+ const problems = rows.filter((r) => r.notes.length > 0);
527
+ if (problems.length > 0) {
528
+ lines.push('');
529
+ lines.push(' resolution findings:');
530
+ for (const r of problems) {
531
+ for (const n of r.notes) lines.push(` · ${r.id}: ${n}`);
532
+ }
533
+ }
534
+ process.stdout.write(lines.join('\n') + '\n');
535
+
536
+ if (check) {
537
+ if (!fs.existsSync(BASELINE)) {
538
+ process.stderr.write(
539
+ `❌ check_enforcement_coverage --check: no baseline at ${path.relative(REPO_ROOT, BASELINE)}; ` +
540
+ `run --write-baseline first\n`,
541
+ );
542
+ return 2;
543
+ }
544
+ const base = JSON.parse(fs.readFileSync(BASELINE, 'utf-8')).summary as Summary;
545
+ const regressions: string[] = [];
546
+ if (summary.blocking < base.blocking) {
547
+ regressions.push(`blocking coverage fell: ${base.blocking} → ${summary.blocking}`);
548
+ }
549
+ if (summary.unwired > base.unwired) {
550
+ regressions.push(`unwired declarations rose: ${base.unwired} → ${summary.unwired}`);
551
+ }
552
+ // A validator dropping out of a workflow back into taskfile-only is the
553
+ // exact regression this split was built to name. Without this line the
554
+ // headline would fall and only the `blocking` check would notice, which
555
+ // reports the symptom rather than the cause.
556
+ if (summary.local_only > (base.local_only ?? 0)) {
557
+ regressions.push(
558
+ `validators fell back to taskfile-only: ${base.local_only ?? 0} → ${summary.local_only} ` +
559
+ `(a gate left .github/workflows/ — add it back to rule-backstops.yml)`,
560
+ );
561
+ }
562
+ if (summary.missing > base.missing) {
563
+ regressions.push(`missing targets rose: ${base.missing} → ${summary.missing}`);
564
+ }
565
+ if (regressions.length > 0) {
566
+ process.stderr.write('❌ enforcement-coverage ratchet:\n');
567
+ for (const r of regressions) process.stderr.write(` · ${r}\n`);
568
+ process.stderr.write(
569
+ ' Raise coverage, or regenerate the baseline with --write-baseline if the drop is the point.\n',
570
+ );
571
+ return 1;
572
+ }
573
+ process.stdout.write('✅ enforcement-coverage ratchet holds\n');
574
+ }
575
+ return 0;
576
+ }
577
+
578
+ // Main-guard (realpath-compared, mirrors the repo convention).
579
+ if (process.argv[1] !== undefined) {
580
+ try {
581
+ const here = fs.realpathSync(fileURLToPath(import.meta.url));
582
+ const argv1 = fs.realpathSync(path.resolve(process.argv[1]));
583
+ if (here === argv1) {
584
+ process.exit(main(process.argv.slice(2)));
585
+ }
586
+ } catch {
587
+ const argvUrl = pathToFileURL(path.resolve(process.argv[1])).href;
588
+ if (import.meta.url === argvUrl) {
589
+ process.exit(main(process.argv.slice(2)));
590
+ }
591
+ }
592
+ }
@@ -35,20 +35,24 @@ import { spawnSync } from 'node:child_process';
35
35
  import * as fs from 'node:fs';
36
36
  import * as path from 'node:path';
37
37
  import { fileURLToPath, pathToFileURL } from 'node:url';
38
+ import { KERNEL_RULE_FILENAMES } from './_lib/kernel_rules.js';
38
39
 
39
- const KERNEL_RULES: ReadonlySet<string> = new Set([
40
- 'agent-authority.md',
41
- 'ask-when-uncertain.md',
42
- 'commit-policy.md',
43
- 'direct-answers.md',
44
- 'language-and-tone.md',
45
- 'no-cheap-questions.md',
46
- 'non-destructive-by-default.md',
47
- 'scope-control.md',
48
- 'verify-before-complete.md',
49
- ]);
40
+ const KERNEL_RULES: ReadonlySet<string> = KERNEL_RULE_FILENAMES;
50
41
 
51
- const KERNEL_DIR = '.agent-src.uncondensed/rules';
42
+ /**
43
+ * Kernel-rule source directory.
44
+ *
45
+ * This gate was watching a retired tree — the pre-ADR-051 source root — and a
46
+ * directory that no longer exists can never match a changed path. So the
47
+ * one-kernel-rule-per-PR slow-rollout guarantee reported "no kernel rule
48
+ * touched" for every kernel-rule edit, silently and indefinitely. Found by
49
+ * editing a kernel rule and noticing the gate stayed green.
50
+ *
51
+ * The first fix kept the old path as a fallback; CI's ADR-051 guard rejected
52
+ * that, correctly. Retaining a dead path is the bug, not the safety net — a
53
+ * second root that cannot exist is exactly what made this gate inert.
54
+ */
55
+ const KERNEL_DIR = 'src/rules';
52
56
  const DEFAULT_LABEL = 'bundled-always-rules-acknowledged';
53
57
 
54
58
  function _git_changed_files(base_ref: string): string[] {