@event4u/agent-config 14.8.0 → 14.10.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 (170) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +214 -237
  3. package/README.md +1 -1
  4. package/agents/templates/.ai-council.yml.example +34 -4
  5. package/dist/agent-src/commands/pr/merge.md +9 -5
  6. package/dist/agent-src/commands/review/changes.md +95 -14
  7. package/dist/agent-src/commands/roadmap/process-full.md +2 -2
  8. package/dist/agent-src/contexts/execution/host-capability-manifest.md +77 -0
  9. package/dist/agent-src/contexts/execution/roadmap-execution-contract.md +36 -0
  10. package/dist/agent-src/contexts/execution/subagent-response-contract.md +80 -0
  11. package/dist/agent-src/rules/untrusted-input-defense.md +9 -3
  12. package/dist/agent-src/skills/async-python-patterns/SKILL.md +1 -1
  13. package/dist/agent-src/skills/code-refactoring/SKILL.md +1 -1
  14. package/dist/agent-src/skills/code-review/evals/evals.json +87 -46
  15. package/dist/agent-src/skills/condense-memory/SKILL.md +1 -1
  16. package/dist/agent-src/skills/conventional-commits-writing/SKILL.md +1 -1
  17. package/dist/agent-src/skills/design-review/SKILL.md +1 -1
  18. package/dist/agent-src/skills/discovery-interview/SKILL.md +1 -1
  19. package/dist/agent-src/skills/doc-coauthoring/SKILL.md +1 -1
  20. package/dist/agent-src/skills/docx-authoring/SKILL.md +1 -1
  21. package/dist/agent-src/skills/editorial-calendar/SKILL.md +1 -1
  22. package/dist/agent-src/skills/github-ci/SKILL.md +1 -1
  23. package/dist/agent-src/skills/humanizer/SKILL.md +39 -0
  24. package/dist/agent-src/skills/humanizer/evals/strip_fixtures.json +57 -0
  25. package/dist/agent-src/skills/humanizer/references/fixtures.md +54 -0
  26. package/dist/agent-src/skills/judge-artifact-completeness/SKILL.md +1 -1
  27. package/dist/agent-src/skills/judge-injection-defense/SKILL.md +1 -1
  28. package/dist/agent-src/skills/judge-spec-compliance/SKILL.md +154 -0
  29. package/dist/agent-src/skills/judge-synthesis/SKILL.md +45 -0
  30. package/dist/agent-src/skills/laravel-validation/SKILL.md +1 -1
  31. package/dist/agent-src/skills/legal-intake-triage/SKILL.md +1 -1
  32. package/dist/agent-src/skills/legal-practice-profile/SKILL.md +1 -1
  33. package/dist/agent-src/skills/messaging-architecture/SKILL.md +1 -1
  34. package/dist/agent-src/skills/migration-architect/SKILL.md +1 -1
  35. package/dist/agent-src/skills/module-detect-on-the-fly/SKILL.md +1 -1
  36. package/dist/agent-src/skills/module-management/SKILL.md +1 -1
  37. package/dist/agent-src/skills/motion-choreographer/SKILL.md +1 -1
  38. package/dist/agent-src/skills/onboarding-program/SKILL.md +1 -1
  39. package/dist/agent-src/skills/perf-feedback-craft/SKILL.md +1 -1
  40. package/dist/agent-src/skills/prompt-optimizer/SKILL.md +1 -1
  41. package/dist/agent-src/skills/receiving-code-review/SKILL.md +1 -1
  42. package/dist/agent-src/skills/roadmap-writing/SKILL.md +18 -18
  43. package/dist/agent-src/skills/scene-expander/SKILL.md +1 -1
  44. package/dist/agent-src/skills/secrets-management/SKILL.md +1 -1
  45. package/dist/agent-src/skills/using-git-worktrees/SKILL.md +1 -1
  46. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  47. package/dist/agent-src/templates/roadmaps.md +8 -0
  48. package/dist/cli/registry.js +2 -0
  49. package/dist/cli/registry.js.map +1 -1
  50. package/dist/cli-delegate/{chunk-MMSGVZKV.js → chunk-77GR3VD4.js} +65 -40
  51. package/dist/cli-delegate/{chunk-Q26HT4QT.js → chunk-E46KPN6K.js} +251 -150
  52. package/dist/cli-delegate/{chunk-EEJUMCDZ.js → chunk-PLSG6UL5.js} +1 -1
  53. package/dist/cli-delegate/cmd_conformance.js +89 -13
  54. package/dist/cli-delegate/cmd_doctor.js +3 -3
  55. package/dist/cli-delegate/cmd_handoff.js +2 -2
  56. package/dist/cli-delegate/cmd_memory_get.js +1 -1
  57. package/dist/cli-delegate/cmd_route_audit.js +1 -1
  58. package/dist/cli-delegate/cmd_settings_get.js +1 -1
  59. package/dist/cli-delegate/cmd_settings_set.js +1 -1
  60. package/dist/discovery/deprecation-report.md +1 -1
  61. package/dist/discovery/discovery-manifest.json +64 -42
  62. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  63. package/dist/discovery/discovery-manifest.summary.md +3 -3
  64. package/dist/discovery/dormancy-report.md +1 -1
  65. package/dist/discovery/orphan-report.md +1 -1
  66. package/dist/discovery/packs.json +6 -5
  67. package/dist/discovery/trust-report.md +2 -2
  68. package/dist/discovery/workspaces.json +5 -4
  69. package/dist/hooks/dispatch.js +562 -204
  70. package/dist/mcp/registry-manifest.json +3 -3
  71. package/dist/mcp/server.json +2 -2
  72. package/dist/mcp/server.mjs +808 -331
  73. package/dist/scripts/_lib/claude_plugin.js +162 -0
  74. package/dist/scripts/_lib/claude_plugin.js.map +1 -0
  75. package/dist/scripts/_lib/environment_detector.js +397 -0
  76. package/dist/scripts/_lib/environment_detector.js.map +1 -0
  77. package/dist/scripts/_lib/spawn_env.js +129 -0
  78. package/dist/scripts/_lib/spawn_env.js.map +1 -0
  79. package/dist/scripts/ai_council/modes.js +199 -0
  80. package/dist/scripts/ai_council/modes.js.map +1 -0
  81. package/dist/scripts/ai_council/transport_resolver.js +418 -0
  82. package/dist/scripts/ai_council/transport_resolver.js.map +1 -0
  83. package/dist/server/routes/wizard.js +3 -2
  84. package/dist/server/routes/wizard.js.map +1 -1
  85. package/dist/ui/assets/index-Cxgy63kz.js +26 -0
  86. package/dist/ui/assets/index-Cxgy63kz.js.map +1 -0
  87. package/dist/ui/index.html +1 -1
  88. package/docs/guidelines/agent-infra/traceability-field-mechanics.md +50 -0
  89. package/docs/guidelines/agent-infra/untrusted-input-spotlighting.md +17 -0
  90. package/package.json +7 -3
  91. package/src/config/estate-count-budget.json +13 -744
  92. package/src/config/evaluator-budgets.json +4 -4
  93. package/src/config/gate-coverage.yml +267 -9
  94. package/src/config/gate-violation-baselines.json +72 -72
  95. package/src/config/preamble-payload-budget.json +71 -67
  96. package/src/config/publish-surface.json +60 -0
  97. package/src/config/requirements-trace-budget.json +32 -0
  98. package/src/config/rule-stub-ceilings.json +8 -1
  99. package/src/scripts/_dispatch.bash +7 -0
  100. package/src/scripts/_lib/base_tree.ts +175 -0
  101. package/src/scripts/_lib/billing_grant.ts +165 -0
  102. package/src/scripts/_lib/billing_grant_cli.ts +123 -0
  103. package/src/scripts/_lib/council_fallback_posture.ts +53 -6
  104. package/src/scripts/_lib/council_fallback_wiring.ts +61 -1
  105. package/src/scripts/_lib/host_capability.ts +59 -5
  106. package/src/scripts/_lib/quota_parked.ts +133 -0
  107. package/src/scripts/_lib/retrieval_sanitize.ts +62 -0
  108. package/src/scripts/_lib/review_telemetry.ts +196 -0
  109. package/src/scripts/_lib/subagent_response.ts +92 -0
  110. package/src/scripts/adr/regenerate_index.ts +14 -7
  111. package/src/scripts/ai_council/clients.ts +12 -1
  112. package/src/scripts/ai_council/config.ts +72 -115
  113. package/src/scripts/ai_council/fallback_config.ts +19 -7
  114. package/src/scripts/ai_council/mid_flight_fallback.ts +88 -7
  115. package/src/scripts/ai_council/orchestrator.ts +2 -2
  116. package/src/scripts/ai_council/py_format.ts +124 -0
  117. package/src/scripts/ai_council/seating.ts +211 -0
  118. package/src/scripts/ai_council/transport_resolver.ts +65 -2
  119. package/src/scripts/audit_adr_coverage.ts +33 -6
  120. package/src/scripts/check_council_pin_staleness.ts +300 -0
  121. package/src/scripts/check_estate_count.ts +420 -293
  122. package/src/scripts/check_gate_coverage.ts +91 -0
  123. package/src/scripts/check_no_stub_inventory_table.ts +292 -0
  124. package/src/scripts/check_pack_passport_reconciliation.ts +274 -0
  125. package/src/scripts/check_pack_size.ts +234 -1
  126. package/src/scripts/check_publish_surface.ts +297 -0
  127. package/src/scripts/check_requirements_trace.ts +378 -0
  128. package/src/scripts/check_secret_leak.ts +166 -12
  129. package/src/scripts/code_graph/cli.ts +44 -5
  130. package/src/scripts/code_graph/extract.ts +87 -0
  131. package/src/scripts/council_cli.ts +12 -16
  132. package/src/scripts/detect_ai_tells.ts +87 -0
  133. package/src/scripts/dispatch_r2_reviewer.ts +42 -0
  134. package/src/scripts/generate_capabilities_index.ts +41 -0
  135. package/src/scripts/generate_pack_manifests.ts +78 -0
  136. package/src/scripts/git_authorization_hook.ts +54 -4
  137. package/src/scripts/hooks/block_unauthorized_git.ts +19 -1
  138. package/src/scripts/hooks/run_continuation_hook.ts +3 -1
  139. package/src/scripts/hooks/subagent_ledger_hook.ts +76 -11
  140. package/src/scripts/injection_scan_hook.ts +120 -10
  141. package/src/scripts/lint_adr_sweep_routing.ts +365 -0
  142. package/src/scripts/lint_workflow_security.ts +53 -10
  143. package/src/scripts/lint_workflow_security_allowlist.json +2 -18
  144. package/src/scripts/report_envelope_rate.ts +166 -0
  145. package/src/scripts/review_axis_report.ts +218 -0
  146. package/src/scripts/run_supervise.ts +46 -1
  147. package/src/scripts/schemas/evals.schema.json +5 -0
  148. package/src/scripts/schemas/pack.schema.json +62 -4
  149. package/src/scripts/schemas/skill.schema.json +2 -2
  150. package/src/scripts/sync_pr_branch.ts +14 -7
  151. package/src/scripts/tighten_skill_descriptions.ts +264 -0
  152. package/dist/cli/commands/commands.candidates.test.js +0 -257
  153. package/dist/cli/commands/commands.candidates.test.js.map +0 -1
  154. package/dist/cli/commands/profiles.test.js +0 -88
  155. package/dist/cli/commands/profiles.test.js.map +0 -1
  156. package/dist/cli/commands/recordTriggerEval.test.js +0 -113
  157. package/dist/cli/commands/recordTriggerEval.test.js.map +0 -1
  158. package/dist/cli/configRoot.test.js +0 -97
  159. package/dist/cli/configRoot.test.js.map +0 -1
  160. package/dist/cli/mcp/content.test.js +0 -54
  161. package/dist/cli/mcp/content.test.js.map +0 -1
  162. package/dist/cli/mcp/dispatch.test.js +0 -108
  163. package/dist/cli/mcp/dispatch.test.js.map +0 -1
  164. package/dist/server/writeRoot.test.js +0 -91
  165. package/dist/server/writeRoot.test.js.map +0 -1
  166. package/dist/shared/capabilities.test.js +0 -39
  167. package/dist/shared/capabilities.test.js.map +0 -1
  168. package/dist/ui/assets/index-C1pBRm1f.js +0 -26
  169. package/dist/ui/assets/index-C1pBRm1f.js.map +0 -1
  170. /package/dist/cli-delegate/{chunk-N7CDDGI3.js → chunk-CYH5SP6M.js} +0 -0
@@ -38,6 +38,7 @@ import * as path from 'node:path';
38
38
  import { fileURLToPath, pathToFileURL } from 'node:url';
39
39
 
40
40
  import { assertScanned, DeadScopeError } from './_lib/scan_scope.js';
41
+ import { runSelfTest } from './_lib/gate_self_test.js';
41
42
  import { scanText, type SecretFinding } from './_lib/secret_detector.js';
42
43
 
43
44
  const _HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -107,8 +108,34 @@ function isAllowed(rel: string, lineno: number, allow: readonly AllowEntry[]): b
107
108
  return allow.some((a) => a.file === rel && (a.line === null || a.line === lineno));
108
109
  }
109
110
 
110
- function isExcluded(rel: string): boolean {
111
- return DEFAULT_EXCLUDE.some((rx) => rx.test(rel));
111
+ /** `dist/` — excluded everywhere EXCEPT the pack scope. See `isExcluded`. */
112
+ const DIST_EXCLUDE: RegExp = /(^|\/)dist(\/|$)/;
113
+
114
+ function isExcluded(rel: string, mode: Mode = 'diff'): boolean {
115
+ return DEFAULT_EXCLUDE.some((rx) => {
116
+ // The `dist/` exclusion is the SECOND reason this gate could not see
117
+ // what ships, and it fires regardless of mode. Mode enumeration was the
118
+ // first: every git-backed mode walks the git tree, and `dist/cli/**` is
119
+ // gitignored while `dist/` is a `files[]` root. Adding the pack scope
120
+ // alone fixed nothing measurable — the payload resolved and then this
121
+ // filter threw away exactly the paths the scope exists to reach.
122
+ // Verified: a key-shaped string planted at `dist/zzcanary/leak.txt`
123
+ // (`git check-ignore -v` names `.gitignore:206`, and `npm pack` ships
124
+ // it) was missed by the new mode until this branch existed.
125
+ //
126
+ // Kept for every OTHER mode, because there the exclusion is right:
127
+ // `dist/` is a byte-for-byte projection of `src/`, which is scanned at
128
+ // its own path, so scanning the copy adds no coverage. In the pack scope
129
+ // the question is different — not "is this content somewhere else in the
130
+ // repo" but "does this content SHIP" — and for an untracked shipped path
131
+ // there is no other path to have scanned it at.
132
+ //
133
+ // The cost is a duplicate finding for a TRACKED dist file. That is not a
134
+ // false positive: a projection is byte-identical to its source, so a
135
+ // finding there is a finding in `src/` too.
136
+ if (mode === 'pack' && rx.source === DIST_EXCLUDE.source) return false;
137
+ return rx.test(rel);
138
+ });
112
139
  }
113
140
 
114
141
  /** Fast binary sniff — a NUL byte in the first 8 KiB means "not text". */
@@ -132,7 +159,48 @@ function gitLines(root: string, args: readonly string[]): string[] {
132
159
  return res.stdout.split('\n').filter((l) => l.trim() !== '');
133
160
  }
134
161
 
135
- export type Mode = 'diff' | 'all' | 'explicit';
162
+ export type Mode = 'diff' | 'all' | 'explicit' | 'pack';
163
+
164
+ /**
165
+ * `pack` exists because the other three cannot see a large part of what ships.
166
+ *
167
+ * Every one of them enumerates the GIT tree — `git diff`, `git ls-files`, or an
168
+ * explicit path list a caller derived from one. `dist/` is a `files[]` root and
169
+ * `dist/cli/**` is gitignored (`.gitignore:206` is `/dist/*`, and
170
+ * `git check-ignore -v dist/cli/agent-config.js` names that line), so those
171
+ * paths are shipped and untracked at the same time and this gate could not
172
+ * reach them **by construction** — not by misconfiguration.
173
+ *
174
+ * Additive on purpose: no existing caller changes behaviour, and the three
175
+ * git-backed modes are untouched.
176
+ */
177
+ export function packPayloadFiles(root: string): string[] {
178
+ const out = spawnSync('npm', ['pack', '--dry-run', '--ignore-scripts', '--json'], {
179
+ cwd: root,
180
+ encoding: 'utf-8',
181
+ maxBuffer: 64 * 1024 * 1024,
182
+ });
183
+ if (out.status !== 0 || typeof out.stdout !== 'string') {
184
+ // Returning [] would hand the scope assertion an empty set, which it
185
+ // already treats as a gate that could not run — the right verdict, and
186
+ // reached without inventing a second failure path.
187
+ return [];
188
+ }
189
+ const i = out.stdout.indexOf('[');
190
+ if (i < 0) return [];
191
+ let parsed: unknown;
192
+ try {
193
+ parsed = JSON.parse(out.stdout.slice(i));
194
+ } catch {
195
+ return [];
196
+ }
197
+ if (!Array.isArray(parsed) || parsed.length === 0) return [];
198
+ const first = parsed[0] as { files?: { path?: unknown }[] };
199
+ const files = Array.isArray(first.files) ? first.files : [];
200
+ return files
201
+ .map((f) => (typeof f.path === 'string' ? f.path : ''))
202
+ .filter((pth) => pth !== '');
203
+ }
136
204
 
137
205
  /**
138
206
  * Resolve the file set.
@@ -155,6 +223,9 @@ export function resolveFiles(
155
223
  if (mode === 'all') {
156
224
  return gitLines(root, ['ls-files']);
157
225
  }
226
+ if (mode === 'pack') {
227
+ return packPayloadFiles(root);
228
+ }
158
229
  const base = opts.base ?? 'origin/main';
159
230
  // An unresolvable base is a scan of NOTHING, not a clean scan.
160
231
  //
@@ -191,7 +262,7 @@ export function scanRepo(
191
262
  const applyExcludes = mode !== 'explicit';
192
263
  const hits: LeakHit[] = [];
193
264
  for (const rel of resolveFiles(root, mode, opts)) {
194
- if (applyExcludes && isExcluded(rel)) {
265
+ if (applyExcludes && isExcluded(rel, mode)) {
195
266
  continue;
196
267
  }
197
268
  const abs = path.join(root, rel);
@@ -220,6 +291,7 @@ export function scanRepo(
220
291
  interface Args {
221
292
  json: boolean;
222
293
  all: boolean;
294
+ pack: boolean;
223
295
  base: string | undefined;
224
296
  paths: string[];
225
297
  }
@@ -228,6 +300,7 @@ function parseArgs(argv: readonly string[]): Args {
228
300
  const paths: string[] = [];
229
301
  let json = false;
230
302
  let all = false;
303
+ let pack = false;
231
304
  let base: string | undefined;
232
305
  for (let i = 0; i < argv.length; i++) {
233
306
  const a = argv[i] as string;
@@ -235,13 +308,17 @@ function parseArgs(argv: readonly string[]): Args {
235
308
  json = true;
236
309
  } else if (a === '--all') {
237
310
  all = true;
311
+ } else if (a === '--pack') {
312
+ pack = true;
238
313
  } else if (a === '--base') {
239
314
  base = argv[++i];
240
315
  } else if (a === '-h' || a === '--help') {
241
316
  _stdout(
242
- 'usage: check_secret_leak [paths...] [--all] [--base <ref>] [--json]\n' +
317
+ 'usage: check_secret_leak [paths...] [--all] [--pack] [--base <ref>] [--json]\n' +
243
318
  ' default → scans files changed vs origin/main + untracked (shift-left).\n' +
244
319
  ' --all → scans the whole tracked tree.\n' +
320
+ ' --pack → scans the npm pack payload, INCLUDING shipped-but-gitignored\n' +
321
+ ' paths the three git-backed modes cannot reach.\n' +
245
322
  ' paths → scans exactly those paths (excludes skipped).\n' +
246
323
  ' Exit 1 on a high-confidence leak.\n',
247
324
  );
@@ -253,7 +330,7 @@ function parseArgs(argv: readonly string[]): Args {
253
330
  paths.push(a);
254
331
  }
255
332
  }
256
- return { json, all, base, paths };
333
+ return { json, all, pack, base, paths };
257
334
  }
258
335
 
259
336
  function _stdout(s: string): void {
@@ -263,9 +340,73 @@ function _stderr(s: string): void {
263
340
  process.stderr.write(s);
264
341
  }
265
342
 
343
+ /**
344
+ * Discrimination, over the one property this branch added.
345
+ *
346
+ * The pack scope's whole value is that it reaches paths the git-backed modes
347
+ * cannot, and it was measurably INERT when first written: the mode resolved the
348
+ * payload and `DEFAULT_EXCLUDE`'s `dist/` rule then filtered away exactly those
349
+ * paths. A self-test over `isExcluded` is therefore not a formality here — it
350
+ * pins the difference between the mode working and the mode existing.
351
+ *
352
+ * Deliberately over the pure predicate rather than over a spawned `npm pack`:
353
+ * the canary in `gate-coverage.yml` already drives the real binary end to end
354
+ * with a real plant, and duplicating that here would add a pack run per case
355
+ * for no additional evidence.
356
+ */
357
+ function selfTest(): number {
358
+ return runSelfTest({
359
+ gate: 'check_secret_leak',
360
+ minCases: 7,
361
+ minRejectCases: 3,
362
+ cases: [
363
+ {
364
+ name: 'pack scope does NOT exclude dist/ — the blind spot it exists for',
365
+ expect: 'reject',
366
+ run: () => (isExcluded('dist/cli/agent-config.js', 'pack') ? 0 : 1),
367
+ },
368
+ {
369
+ name: 'diff scope DOES exclude dist/ — a projection scanned at its source',
370
+ expect: 'accept',
371
+ run: () => (isExcluded('dist/cli/agent-config.js', 'diff') ? 0 : 1),
372
+ },
373
+ {
374
+ name: 'all scope also still excludes dist/ — untouched by this change',
375
+ expect: 'accept',
376
+ run: () => (isExcluded('dist/agent-src/rules/x.md', 'all') ? 0 : 1),
377
+ },
378
+ {
379
+ // The exclusion carve-out is `dist/` ONLY. If it leaked into the
380
+ // other rules the pack scope would start reading test fixtures,
381
+ // which legitimately hold secret-shaped strings.
382
+ name: 'pack scope still excludes tests/ — the carve-out is dist-only',
383
+ expect: 'accept',
384
+ run: () => (isExcluded('tests/fixtures/x.txt', 'pack') ? 0 : 1),
385
+ },
386
+ {
387
+ name: 'pack scope still excludes node_modules/',
388
+ expect: 'accept',
389
+ run: () => (isExcluded('node_modules/x/index.js', 'pack') ? 0 : 1),
390
+ },
391
+ {
392
+ name: 'pack scope reaches a second dist subtree, not just dist/cli',
393
+ expect: 'reject',
394
+ run: () => (isExcluded('dist/hooks/dispatch.js', 'pack') ? 0 : 1),
395
+ },
396
+ {
397
+ name: 'a shipped non-dist path is scanned in every mode',
398
+ expect: 'reject',
399
+ run: () => (isExcluded('src/scripts/x.ts', 'pack') || isExcluded('src/scripts/x.ts', 'diff') ? 0 : 1),
400
+ },
401
+ ],
402
+ });
403
+ }
404
+
266
405
  export function main(argv?: readonly string[]): number {
267
- const args = parseArgs(argv ?? process.argv.slice(2));
268
- const mode: Mode = args.paths.length > 0 ? 'explicit' : args.all ? 'all' : 'diff';
406
+ const rawArgv = argv ?? process.argv.slice(2);
407
+ if (rawArgv.includes('--self-test')) return selfTest();
408
+ const args = parseArgs(rawArgv);
409
+ const mode: Mode = args.pack ? 'pack' : args.paths.length > 0 ? 'explicit' : args.all ? 'all' : 'diff';
269
410
 
270
411
  // Scope assertion, deliberately here and not inside `scanRepo`: that export
271
412
  // is called directly by tests and other callers against arbitrary roots, and
@@ -280,6 +421,11 @@ export function main(argv?: readonly string[]): number {
280
421
  // re-thrown untouched to preserve it.
281
422
  try {
282
423
  const targets = resolveFiles(REPO_ROOT, mode, { explicit: args.paths, base: args.base });
424
+ // The coverage register requires an enforced gate to report what it
425
+ // inspected. Printed before the assertion so a dead scope still tells
426
+ // the reader the number it died on, which is the one number that
427
+ // distinguishes "resolved nothing" from "resolved and filtered".
428
+ _stdout(`scanned: ${String(targets.length)}\n`);
283
429
  assertScanned({
284
430
  gate: 'check_secret_leak',
285
431
  scanned: targets.length,
@@ -289,9 +435,15 @@ export function main(argv?: readonly string[]): number {
289
435
  ? ['git ls-files']
290
436
  : mode === 'explicit'
291
437
  ? ['<explicit path arguments>']
292
- : [`git diff --name-only --diff-filter=ACMR ${args.base ?? 'origin/main'}`, 'git ls-files --others --exclude-standard'],
293
- // `all` and `explicit` carry no reason: zero tracked files, or zero
294
- // named paths, is blindness in a repo that has content.
438
+ : mode === 'pack'
439
+ ? ['npm pack --dry-run --ignore-scripts payload (package.json files[])']
440
+ : [`git diff --name-only --diff-filter=ACMR ${args.base ?? 'origin/main'}`, 'git ls-files --others --exclude-standard'],
441
+ // `all`, `explicit` and `pack` carry no reason: zero tracked files,
442
+ // zero named paths, or an empty pack payload is blindness in a repo
443
+ // that has content. `pack` inherits the strict path by omission
444
+ // rather than by a new branch — an empty payload means a botched
445
+ // `files[]` or a pack that resolved nothing, which is the loudest
446
+ // possible signal and the opposite of a clean bill.
295
447
  ...(mode === 'diff'
296
448
  ? {
297
449
  allowEmpty:
@@ -317,7 +469,9 @@ export function main(argv?: readonly string[]): number {
317
469
  if (args.json) {
318
470
  _stdout(JSON.stringify({ check: 'secret-leak', count: hits.length, hits }, null, 2) + '\n');
319
471
  } else if (hits.length === 0) {
320
- _stdout('✅ check_secret_leak: no high-confidence secret found in the tracked tree.\n');
472
+ _stdout(
473
+ `✅ check_secret_leak: no high-confidence secret found in ${mode === 'pack' ? 'the npm pack payload' : 'the tracked tree'}.\n`,
474
+ );
321
475
  } else {
322
476
  _stderr(`❌ check_secret_leak: ${hits.length} high-confidence secret finding(s):\n`);
323
477
  for (const h of hits) {
@@ -77,8 +77,47 @@ function flag(argv: string[], name: string): string | null {
77
77
  return i >= 0 && i + 1 < argv.length ? (argv[i + 1] as string) : null;
78
78
  }
79
79
 
80
+ /**
81
+ * Resolve the repository to operate on. `--root` > `AGENT_CONFIG_PROJECT_ROOT` >
82
+ * this module's own tree.
83
+ *
84
+ * The middle rung is the whole point, and its absence was a confused deputy:
85
+ * `_dispatch.bash` parses `--root` GLOBALLY, strips it from argv, and exports
86
+ * `AGENT_CONFIG_PROJECT_ROOT` (`:1655`) — then this engine read neither and fell
87
+ * back to its own module path. So `agent-config code-graph build --root <other
88
+ * repo>` silently indexed THIS package. The dispatcher made the decision and the
89
+ * engine substituted its own, which is why every consumer-facing invocation was
90
+ * wrong about which repository it had just read.
91
+ *
92
+ * `realpathSync` rather than `resolve` alone: a symlinked root must normalise to
93
+ * what will actually be walked, or the path a caller sees in the output is not
94
+ * the path that was indexed. Fail-loud on a root that does not exist — a silent
95
+ * fallback to the package tree is the defect this function exists to remove, and
96
+ * reintroducing it for a typo'd path would be the same bug wearing a smaller
97
+ * hat.
98
+ *
99
+ * Deliberately NOT touching `DEFAULT_CACHE`, which is anchored to `REPO_ROOT`
100
+ * for the same reason and is a separate decision: it is a WRITE path, with its
101
+ * own ownership, cleanup, concurrency and multi-repo namespacing questions.
102
+ * Council 2026-08-22, both seats, explicitly out of scope here.
103
+ */
104
+ function resolveRoot(argv: string[]): string {
105
+ const explicit = flag(argv, '--root');
106
+ const fromDispatcher = process.env['AGENT_CONFIG_PROJECT_ROOT'];
107
+ const candidate =
108
+ explicit ?? (fromDispatcher !== undefined && fromDispatcher !== '' ? fromDispatcher : REPO_ROOT);
109
+ try {
110
+ return fs.realpathSync(path.resolve(candidate));
111
+ } catch {
112
+ // Returned unresolved on purpose: every caller checks existence and
113
+ // prints the path it was given, which is more useful in the error than
114
+ // a normalised form of a path that does not exist.
115
+ return path.resolve(candidate);
116
+ }
117
+ }
118
+
80
119
  async function cmdBuild(argv: string[]): Promise<number> {
81
- const root = flag(argv, '--root') ?? REPO_ROOT;
120
+ const root = resolveRoot(argv);
82
121
  const out = argv.includes('--out') ? flag(argv, '--out') : DEFAULT_CACHE;
83
122
  if (!fs.existsSync(root)) {
84
123
  process.stderr.write(`code-graph: root not found: ${root}\n`);
@@ -122,7 +161,7 @@ function cmdValidate(argv: string[]): number {
122
161
 
123
162
  function resolveGraph(argv: string[]): { g: LoadedGraph; note: string } | { err: string } {
124
163
  const explicit = flag(argv, '--graph');
125
- const root = flag(argv, '--root') ?? REPO_ROOT;
164
+ const root = resolveRoot(argv);
126
165
  if (explicit) {
127
166
  if (!fs.existsSync(explicit)) return { err: `graph not found: ${explicit}` };
128
167
  return { g: loadGraph(explicit, path.relative(REPO_ROOT, explicit)), note: '' };
@@ -179,7 +218,7 @@ function cmdQuery(kind: 'query' | 'explain' | 'affected' | 'path', argv: string[
179
218
  const positional = argv.filter((a) => !a.startsWith('--') && !isFlagValue(argv, a));
180
219
  const budget = budgetOf(argv);
181
220
  if (kind === 'affected' && flag(argv, '--since')) {
182
- const root = flag(argv, '--root') ?? REPO_ROOT;
221
+ const root = resolveRoot(argv);
183
222
  const seeds = changedNodeSeeds(r.g, root, flag(argv, '--since') as string);
184
223
  const merged: QueryResult = { source: r.g.source, seeds: [], lines: [], truncated: false, recommended_reads: [] };
185
224
  const perSeed: QueryResult[] = [];
@@ -216,7 +255,7 @@ function isFlagValue(argv: string[], token: string): boolean {
216
255
  }
217
256
 
218
257
  function cmdDetect(argv: string[]): number {
219
- const root = flag(argv, '--root') ?? REPO_ROOT;
258
+ const root = resolveRoot(argv);
220
259
  if (flag(argv, '--format') === 'json') {
221
260
  // Machine-readable three-state verdict (Phase 2). Existing human-text
222
261
  // output below is unchanged for existing consumers.
@@ -316,7 +355,7 @@ function runBudgetedBuild(root: string, out: string, update: boolean, budgetSeco
316
355
  }
317
356
 
318
357
  function cmdRefresh(argv: string[]): number {
319
- const root = flag(argv, '--root') ?? REPO_ROOT;
358
+ const root = resolveRoot(argv);
320
359
  const out = flag(argv, '--out') ?? DEFAULT_CACHE;
321
360
  const budgetSeconds = budgetSecondsOf(argv);
322
361
  if (!fs.existsSync(root)) {
@@ -306,6 +306,93 @@ function extractTsJs(root: TsNode, file: string, out: FileExtract): void {
306
306
  if (body) for (const c of namedChildren(body)) walk(c, classId, id);
307
307
  return;
308
308
  }
309
+ // Modern TS declares most of its functions as bindings, not as
310
+ // `function` statements. Before this case the extractor produced
311
+ // NO node for `export const f = () => {}` or
312
+ // `const g = function () {}`, which is the measured cause of the
313
+ // 170-vs-13,428 TS/PHP symbol gap: the six handled kinds simply do
314
+ // not cover the dominant declaration form.
315
+ //
316
+ // Scoped deliberately to bindings whose value IS a function. A
317
+ // `const x = 3` is data, not a symbol this graph answers questions
318
+ // about, and emitting a node per constant would inflate the count
319
+ // without improving recall — which is the cosmetic-improvement
320
+ // failure the phase falsifier exists to catch.
321
+ case 'lexical_declaration':
322
+ case 'variable_declaration': {
323
+ for (const d of namedChildren(n)) {
324
+ if (d.type !== 'variable_declarator') continue;
325
+ const value = d.childForFieldName('value');
326
+ if (!value || (value.type !== 'arrow_function' && value.type !== 'function_expression')) {
327
+ continue;
328
+ }
329
+ const nm = nameField(d) ?? '<anon>';
330
+ const id = classId ? `${classId}::${nm}` : `${file}#${nm}`;
331
+ out.nodes.push({
332
+ id,
333
+ label: nm,
334
+ kind: classId ? 'method' : 'function',
335
+ source_file: file,
336
+ source_location: loc(d),
337
+ });
338
+ out.rawEdges.push({
339
+ sourceId: classId ?? fileId,
340
+ relation: 'member',
341
+ targetName: nm,
342
+ confidenceHint: 'EXTRACTED',
343
+ });
344
+ // Walk the body under the BINDING's scope, so a call inside
345
+ // an arrow function attributes to that function rather than
346
+ // to the enclosing file — the same treatment
347
+ // `function_declaration` gets.
348
+ //
349
+ // `walk(body)` and not `namedChildren(body)`: an
350
+ // expression-bodied arrow (`() => helper()`) has the CALL
351
+ // itself as its body, so descending one level first steps
352
+ // straight past it and the edge is lost. The sibling cases
353
+ // can iterate children because a `statement_block` is never
354
+ // the interesting node; here it often is.
355
+ const body = value.childForFieldName('body');
356
+ if (body) walk(body, classId, id);
357
+ }
358
+ // Non-function declarators still need walking for their calls.
359
+ for (const d of namedChildren(n)) {
360
+ if (d.type !== 'variable_declarator') continue;
361
+ const value = d.childForFieldName('value');
362
+ if (value && (value.type === 'arrow_function' || value.type === 'function_expression')) {
363
+ continue;
364
+ }
365
+ walk(d, classId, scopeId);
366
+ }
367
+ return;
368
+ }
369
+ // `class C { m = () => 1 }` — a class property holding a function.
370
+ // Emitted as a `method`, the same kind `method_definition` emits,
371
+ // because it is one to every caller.
372
+ case 'public_field_definition': {
373
+ const value = n.childForFieldName('value');
374
+ const nm = nameField(n) ?? '<anon>';
375
+ if (value && (value.type === 'arrow_function' || value.type === 'function_expression')) {
376
+ const id = classId ? `${classId}::${nm}` : `${file}#${nm}`;
377
+ out.nodes.push({
378
+ id,
379
+ label: nm,
380
+ kind: 'method',
381
+ source_file: file,
382
+ source_location: loc(n),
383
+ });
384
+ out.rawEdges.push({
385
+ sourceId: classId ?? fileId,
386
+ relation: 'member',
387
+ targetName: nm,
388
+ confidenceHint: 'EXTRACTED',
389
+ });
390
+ const body = value.childForFieldName('body');
391
+ if (body) walk(body, classId, id);
392
+ return;
393
+ }
394
+ break;
395
+ }
309
396
  case 'new_expression': {
310
397
  const ctor = n.childForFieldName('constructor');
311
398
  if (ctor && (ctor.type === 'identifier' || ctor.type === 'type_identifier' || ctor.type === 'member_expression'))
@@ -106,7 +106,8 @@ import {
106
106
  renderPostureLines,
107
107
  type FallbackPosture,
108
108
  } from './_lib/council_fallback_posture.js';
109
- import { buildFallbackOptions } from './_lib/council_fallback_wiring.js';
109
+ import { wireCouncilFallback } from './_lib/council_fallback_wiring.js';
110
+ import { BILLING_SUBCOMMANDS, billingArgSpec, handleBillingCommand, printBillingGate } from './_lib/billing_grant_cli.js';
110
111
  import {
111
112
  type ClassificationResult,
112
113
  type SizeFitVerdict,
@@ -880,19 +881,11 @@ function build_members(settings: Dict, opts: BuildMembersOptions = {}): External
880
881
  'prints the resolved path.',
881
882
  );
882
883
  }
883
- if (fallback_out !== null) {
884
- // Absent/malformed block means `false`, never a throw. Why quota
885
- // fall-through is opt-in: `FallbackPolicy.apiOnQuota`.
886
- const fallback_cfg = _isDict(ai['fallback']) ? (ai['fallback'] as Dict) : {};
887
- fallback_out.options = buildFallbackOptions({
888
- apiOnQuota: _pyBool(fallback_cfg['api_on_quota']),
889
- hasApiRung: (p) => _API_PROVIDERS.has(p),
890
- memberConfig: (p) => ((members_cfg[p] as Dict) || {}) as Dict,
891
- modelOverride: (p) => (overrides[p] as string | undefined) ?? null,
892
- constructApi: _construct_api_member,
893
- emit: appendEvent,
894
- });
895
- }
884
+ wireCouncilFallback(fallback_out, ai, {
885
+ repoRoot: REPO_ROOT, isDict: _isDict, membersCfg: members_cfg, overrides,
886
+ hasApiRung: (p) => _API_PROVIDERS.has(p),
887
+ constructApi: _construct_api_member, emit: appendEvent,
888
+ });
896
889
  return members;
897
890
  }
898
891
 
@@ -2668,6 +2661,7 @@ function cmd_run(
2668
2661
  quorum_out.result = post_run.quorum;
2669
2662
  skipped.push(...post_run.absent);
2670
2663
  recordRoundObservations(REPO_ROOT, members, responses, classifyCliFailure);
2664
+ printBillingGate(fallback_out.options?.parked ?? [], { repoRoot: REPO_ROOT, stdout: _stdout, stderr: _stderr });
2671
2665
  // Attendance telemetry for the reading that actually decided the pass.
2672
2666
  // `post_run.absent` is the mid-flight set only; the construction-time
2673
2667
  // skips already went out under `phase: 'pre_run'` from `build_members`,
@@ -3509,7 +3503,7 @@ interface Args {
3509
3503
  json: boolean;
3510
3504
  }
3511
3505
 
3512
- const _SUBCOMMANDS = ['estimate', 'run', 'debate', 'render', 'replay', 'quota', 'shadow-report', 'status'];
3506
+ const _SUBCOMMANDS = ['estimate', 'run', 'debate', 'render', 'replay', 'quota', 'shadow-report', 'status', ...BILLING_SUBCOMMANDS];
3513
3507
 
3514
3508
  const _TOP_USAGE =
3515
3509
  `usage: ${_PROG} [-h]\n` +
@@ -3698,7 +3692,7 @@ function _specsFor(cmd: string): { positionals: string[]; opts: OptSpec[]; requi
3698
3692
  requiredOpts: [],
3699
3693
  };
3700
3694
  default:
3701
- return { positionals: [], opts: [], requiredOpts: [] };
3695
+ return billingArgSpec(cmd) ?? { positionals: [], opts: [], requiredOpts: [] };
3702
3696
  }
3703
3697
  }
3704
3698
 
@@ -3902,6 +3896,8 @@ function main(argv: string[] | null = null): number {
3902
3896
  if (args.cmd === 'status') {
3903
3897
  return cmd_status(args);
3904
3898
  }
3899
+ const billing = handleBillingCommand(String(args.cmd), _getattr(args, 'run_id', null), { repoRoot: REPO_ROOT, stdout: _stdout, stderr: _stderr });
3900
+ if (billing !== null) return billing;
3905
3901
  } catch (exc) {
3906
3902
  if (exc instanceof CouncilDisabledError) {
3907
3903
  _stderr(`❌ council:${args.cmd}: ${exc.message}\n`);
@@ -111,6 +111,93 @@ export function scanHiddenUnicode(text: string): HiddenUnicodeFinding[] {
111
111
  }));
112
112
  }
113
113
 
114
+ /** One codepoint the strip considered, and what it decided. */
115
+ export interface CarrierRecord {
116
+ /** `U+XXXX` form, so a record is readable without decoding. */
117
+ codepoint: string;
118
+ /** The class `_classify` returned — never a second class list. */
119
+ cls: string;
120
+ /** Codepoint index (not UTF-16 index) in the input. */
121
+ offset: number;
122
+ disposition: "removed" | "preserved";
123
+ /** Why it was preserved. `null` when removed. */
124
+ reason: string | null;
125
+ }
126
+
127
+ export interface CarrierStripResult {
128
+ out: string;
129
+ removed: number;
130
+ preserved: number;
131
+ records: CarrierRecord[];
132
+ }
133
+
134
+ /**
135
+ * Remove hidden-Unicode carriers from OUTPUT prose — context-aware, opt-in.
136
+ *
137
+ * ## Why this is not `_sanitize`
138
+ *
139
+ * `lint_hidden_unicode._sanitize` drops every `_classify`-flagged codepoint
140
+ * unconditionally and then applies `NFKC`. That is correct for its own callers —
141
+ * it repairs a source FILE — and it is wrong for a deliverable, because
142
+ * `_ZERO_WIDTH` contains `0x200C` and `0x200D`. A blind pass therefore destroys
143
+ * emoji ZWJ sequences and complex-script joiners, which are legitimate content.
144
+ * This function keeps `_classify` as the single source of truth for *what is a
145
+ * candidate* and adds exactly one predicate for *whether to remove it*.
146
+ *
147
+ * ## The predicate
148
+ *
149
+ * A flagged codepoint is removed only when the codepoints on BOTH sides are
150
+ * ASCII (`< 0x80`) or absent. A carrier between two ASCII characters is doing
151
+ * no linguistic work; one adjacent to any non-ASCII character might be a
152
+ * joiner, so it stays.
153
+ *
154
+ * Deliberately conservative, and the asymmetry is the point: the failure mode
155
+ * is a preserved carrier, never a corrupted word. That makes this a HYGIENE
156
+ * pass and not a security control — the injection vector is covered on the
157
+ * INGESTION side by `scanHiddenUnicode`, whose contract is to warn and never
158
+ * strip, and which this function does not touch.
159
+ *
160
+ * Not a detector-evasion tool: it removes invisible characters and alters no
161
+ * visible prose. That exclusion is permanent.
162
+ */
163
+ export function stripCarrierUnicode(text: string): CarrierStripResult {
164
+ const cps = [...text].map((ch) => ch.codePointAt(0) ?? 0);
165
+ const kept: string[] = [];
166
+ const records: CarrierRecord[] = [];
167
+ let removed = 0;
168
+ let preserved = 0;
169
+
170
+ for (let i = 0; i < cps.length; i += 1) {
171
+ const cp = cps[i] as number;
172
+ const cls = _classify(cp);
173
+ if (cls === null) {
174
+ kept.push(String.fromCodePoint(cp));
175
+ continue;
176
+ }
177
+ // `undefined` at either end is "absent", which counts as ASCII-side: a
178
+ // carrier at a boundary has no neighbour to be joining.
179
+ const before = cps[i - 1];
180
+ const after = cps[i + 1];
181
+ const asciiSide = (n: number | undefined): boolean => n === undefined || n < 0x80;
182
+ const strip = asciiSide(before) && asciiSide(after);
183
+ records.push({
184
+ codepoint: `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`,
185
+ cls,
186
+ offset: i,
187
+ disposition: strip ? "removed" : "preserved",
188
+ reason: strip ? null : "adjacent to a non-ASCII codepoint — may be a joiner",
189
+ });
190
+ if (strip) {
191
+ removed += 1;
192
+ } else {
193
+ preserved += 1;
194
+ kept.push(String.fromCodePoint(cp));
195
+ }
196
+ }
197
+
198
+ return { out: kept.join(""), removed, preserved, records };
199
+ }
200
+
114
201
  interface Thresholds {
115
202
  maxHard: number;
116
203
  maxScore: number;
@@ -698,6 +698,44 @@ function isoSeconds(d: Date): string {
698
698
  return d.toISOString().replace(/\.\d{3}Z$/, 'Z');
699
699
  }
700
700
 
701
+ /**
702
+ * The return-envelope POINTER — one line-shaped field, delivered on the
703
+ * dominant dispatch path.
704
+ *
705
+ * ## Why a pointer and not the contract
706
+ *
707
+ * 240 chars is not a round number: it is `MAX_RESPONSE_LINE_CHARS`
708
+ * (`_lib/subagent_response.ts`), so the pointer is one line-shaped field by the
709
+ * contract's own measure. Inlining the shape would put a fourth copy of it in
710
+ * the tree, and a fourth copy is how the contract came to have three
711
+ * inconsistent states.
712
+ *
713
+ * ## Why THIS dispatcher
714
+ *
715
+ * `road-to-subagent-envelope-adoption` step 1.1 says the dominant path, "and it
716
+ * does not fan out to both". The dominant path is **not answerable from the
717
+ * ledger** — 1,725 of 1,845 post-split stops carry a null `agent_type`, which is
718
+ * the 8 % start↔stop join rate recorded elsewhere, so no stop can be attributed
719
+ * to a dispatcher. Decided on invocation surface instead: this file is wired
720
+ * into `/create-pr` and read by three gates (`check_completion_review`,
721
+ * `lint_evidence_artifacts`, `probe_review_binding_drift`), while
722
+ * `team_dispatch` sits behind an ai_team host flag and one `/team delegate`
723
+ * command. It is also the leg with ZERO prior contract hits, so the dominant
724
+ * path and the absent one are the same file.
725
+ *
726
+ * ## What it does not change
727
+ *
728
+ * The findings table stays the artefact — the gates read the file, not the
729
+ * envelope. Per the four-boundary separation in the response contract, this
730
+ * touches the DELIVERY boundary only: what the final message is. It adds no
731
+ * lifecycle status and does not alter the body schema.
732
+ */
733
+ export const RETURN_ENVELOPE_POINTER =
734
+ 'Final message = the return envelope and nothing else: ' +
735
+ '{summary, handoff, confidence, findings, risks}. Shape + the ' +
736
+ 'write-to-disk-first rule: contexts/execution/subagent-response-contract.md. ' +
737
+ 'The findings table stays a file.';
738
+
701
739
  function reviewerPrompt(args: {
702
740
  slug: string;
703
741
  headSha: string;
@@ -781,6 +819,10 @@ function reviewerPrompt(args: {
781
819
  `**Honest-null:** 0 findings, scope ${args.scopeHash}, reviewed <YYYY-MM-DD>`,
782
820
  '```',
783
821
  '',
822
+ '## Return channel',
823
+ '',
824
+ RETURN_ENVELOPE_POINTER,
825
+ '',
784
826
  ].join('\n');
785
827
  }
786
828