@event4u/agent-config 9.32.0 → 9.34.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 (109) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +85 -72
  3. package/dist/agent-src/commands/agent-handoff.md +15 -3
  4. package/dist/agent-src/commands/review/routing.md +3 -4
  5. package/dist/agent-src/contexts/communication/rules-auto/reply-close-mechanics.md +65 -0
  6. package/dist/agent-src/contexts/execution/orchestration-telemetry.md +3 -0
  7. package/dist/agent-src/rules/delegation-policy.md +6 -0
  8. package/dist/agent-src/scripts/archive_completed_roadmaps.ts +35 -1
  9. package/dist/agent-src/scripts/roadmap_gates.ts +107 -3
  10. package/dist/agent-src/skills/corpus-grounding/SKILL.md +21 -12
  11. package/dist/agent-src/skills/design-tokens/SKILL.md +15 -0
  12. package/dist/agent-src/skills/docker/SKILL.md +11 -0
  13. package/dist/agent-src/skills/laravel/SKILL.md +11 -0
  14. package/dist/agent-src/skills/react-shadcn-ui/SKILL.md +24 -0
  15. package/dist/agent-src/skills/review-routing/SKILL.md +23 -6
  16. package/dist/agent-src/skills/rule-writing/SKILL.md +23 -0
  17. package/dist/agent-src/skills/skill-writing/SKILL.md +80 -2
  18. package/dist/agent-src/skills/systematic-debugging/SKILL.md +5 -3
  19. package/dist/agent-src/skills/tailwind-engineer/SKILL.md +24 -0
  20. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  21. package/dist/agent-src/templates/scripts/ownership-map.example.yml +1 -1
  22. package/dist/cli/registry.js +4 -4
  23. package/dist/cli/registry.js.map +1 -1
  24. package/dist/cli-delegate/chunk-HTIU3W56.js +66 -0
  25. package/dist/cli-delegate/{chunk-2WELHO3P.js → chunk-I5EAFRII.js} +35 -0
  26. package/dist/cli-delegate/{chunk-ITIQSGOQ.js → chunk-MA4GFWDY.js} +7 -4
  27. package/dist/cli-delegate/{chunk-PFBV6XRT.js → chunk-Q26HT4QT.js} +1 -63
  28. package/dist/cli-delegate/{chunk-542DZR4P.js → chunk-REMEZSVP.js} +1660 -146
  29. package/dist/cli-delegate/{chunk-3EWYC3YK.js → chunk-UEZ7D35A.js} +4 -3
  30. package/dist/cli-delegate/{chunk-LVRYBKTI.js → chunk-YPAWXXXR.js} +158 -0
  31. package/dist/cli-delegate/cmd_conformance.js +256 -226
  32. package/dist/cli-delegate/cmd_doctor.js +3 -2
  33. package/dist/cli-delegate/cmd_export.js +1 -1
  34. package/dist/cli-delegate/cmd_handoff.js +21 -28
  35. package/dist/cli-delegate/cmd_memory_get.js +1 -1
  36. package/dist/cli-delegate/cmd_prune.js +1 -1
  37. package/dist/cli-delegate/cmd_route_audit.js +1 -1
  38. package/dist/cli-delegate/cmd_session_recycle.js +20 -5
  39. package/dist/cli-delegate/cmd_settings_get.js +4 -2
  40. package/dist/cli-delegate/cmd_settings_migrate.js +1 -1
  41. package/dist/cli-delegate/cmd_settings_set.js +5 -3
  42. package/dist/cli-delegate/cmd_sync.js +1 -1
  43. package/dist/cli-delegate/cmd_uninstall.js +1 -1
  44. package/dist/cli-delegate/cmd_validate.js +1 -1
  45. package/dist/discovery/deprecation-report.md +1 -1
  46. package/dist/discovery/discovery-manifest.json +17 -17
  47. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  48. package/dist/discovery/discovery-manifest.summary.md +2 -2
  49. package/dist/discovery/dormancy-report.md +17 -0
  50. package/dist/discovery/orphan-report.md +1 -1
  51. package/dist/discovery/packs.json +3 -3
  52. package/dist/discovery/trust-report.md +1 -1
  53. package/dist/discovery/workspaces.json +3 -3
  54. package/dist/hooks/dispatch.js +114 -7
  55. package/dist/install/install.mjs +7 -4
  56. package/dist/mcp/registry-manifest.json +3 -3
  57. package/dist/mcp/server.json +2 -2
  58. package/dist/mcp/server.mjs +3755 -1168
  59. package/docs/guidelines/agent-infra/failure-signatures.md +47 -12
  60. package/package.json +2 -2
  61. package/src/agent-src/scripts/archive_completed_roadmaps.ts +35 -1
  62. package/src/agent-src/scripts/roadmap_gates.ts +107 -3
  63. package/src/agent-src/templates/scripts/ownership-map.example.yml +1 -1
  64. package/src/config/cost-parity-budget.json +167 -0
  65. package/src/config/gate-coverage.yml +44 -5
  66. package/src/config/quorum-attendance-budget.json +39 -0
  67. package/src/scripts/_cli/cmd_doctor.ts +69 -1
  68. package/src/scripts/_cli/cmd_session_recycle.ts +25 -4
  69. package/src/scripts/_dispatch.bash +5 -3
  70. package/src/scripts/_lib/env_kill_switch.ts +37 -0
  71. package/src/scripts/_lib/orchestration_record.ts +45 -0
  72. package/src/scripts/_lib/security_lint.ts +18 -4
  73. package/src/scripts/_lib/self_repair.ts +60 -0
  74. package/src/scripts/_lib/self_repair_store.ts +65 -5
  75. package/src/scripts/_lib/subagent_capsule.ts +78 -1
  76. package/src/scripts/ai_council/clients.ts +31 -0
  77. package/src/scripts/ai_council/events_log.ts +130 -8
  78. package/src/scripts/ai_council/orchestrator.ts +50 -3
  79. package/src/scripts/ai_council/pricing.ts +48 -1
  80. package/src/scripts/ai_council/prompts.ts +165 -3
  81. package/src/scripts/ai_council/quorum.ts +30 -0
  82. package/src/scripts/ai_council/session.ts +11 -0
  83. package/src/scripts/ai_team/review_gate.ts +2 -2
  84. package/src/scripts/ask_transport.ts +20 -1
  85. package/src/scripts/build_discovery_manifest.ts +165 -0
  86. package/src/scripts/cache_realization_report.ts +38 -0
  87. package/src/scripts/check_claims.ts +51 -2
  88. package/src/scripts/check_release_highlights.ts +7 -1
  89. package/src/scripts/ci_time_ratio.ts +3 -1
  90. package/src/scripts/conformance_scan.ts +105 -0
  91. package/src/scripts/cost/track.mjs +39 -0
  92. package/src/scripts/cost_summary.ts +104 -1
  93. package/src/scripts/council_cli.ts +131 -13
  94. package/src/scripts/discovery_graph.ts +201 -27
  95. package/src/scripts/dispatch_economy_report.ts +5 -2
  96. package/src/scripts/dispatch_r2_reviewer.ts +102 -1
  97. package/src/scripts/install.ts +20 -6
  98. package/src/scripts/lint_budget_ownership.ts +81 -0
  99. package/src/scripts/lint_handoffs.ts +92 -2
  100. package/src/scripts/lint_hedge_words.ts +317 -0
  101. package/src/scripts/lint_mcp_config_security.ts +1 -1
  102. package/src/scripts/lint_skill_frontmatter_safety.ts +56 -2
  103. package/src/scripts/lint_workflow_paths.ts +384 -0
  104. package/src/scripts/preamble_byte_census.ts +9 -1
  105. package/src/scripts/report_carrier_divergence.ts +10 -0
  106. package/src/scripts/report_conformance_funnel.ts +40 -0
  107. package/src/scripts/schemas/subagent.schema.json +3 -2
  108. package/src/scripts/self_repair_cli.ts +26 -1
  109. package/src/scripts/skill_linter.ts +58 -2
@@ -11,9 +11,14 @@ import {
11
11
  codex_plugin_identity
12
12
  } from "./chunk-FTAISGDQ.js";
13
13
  import {
14
+ DEFAULT_PROJECTS_ROOT,
15
+ aggregateByBucket,
16
+ billableInputTokens,
14
17
  config_exports,
15
- hardenedSpawnEnv
16
- } from "./chunk-LVRYBKTI.js";
18
+ hardenedSpawnEnv,
19
+ scanTranscripts,
20
+ weightedInputUnits
21
+ } from "./chunk-YPAWXXXR.js";
17
22
  import {
18
23
  git_common_dir
19
24
  } from "./chunk-PZWRPRWP.js";
@@ -65,13 +70,13 @@ import {
65
70
  } from "./chunk-J55WI3RR.js";
66
71
 
67
72
  // src/scripts/_cli/cmd_doctor.ts
68
- var YAML = __toESM(require_dist(), 1);
73
+ var YAML2 = __toESM(require_dist(), 1);
69
74
  import * as crypto3 from "node:crypto";
70
- import * as fs6 from "node:fs";
75
+ import * as fs11 from "node:fs";
71
76
  import * as os3 from "node:os";
72
- import * as path7 from "node:path";
77
+ import * as path15 from "node:path";
73
78
  import process2 from "node:process";
74
- import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
79
+ import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL4 } from "node:url";
75
80
 
76
81
  // src/scripts/_lib/duplicate_scope_census.ts
77
82
  import * as fs from "node:fs";
@@ -112,6 +117,1442 @@ function censusDuplicateScope(userRulesDir, projectRulesDir) {
112
117
  };
113
118
  }
114
119
 
120
+ // src/scripts/preamble_byte_census.ts
121
+ var preamble_byte_census_exports = {};
122
+ __export(preamble_byte_census_exports, {
123
+ buildByteCensus: () => buildByteCensus,
124
+ buildReport: () => buildReport2,
125
+ censusClaudeMdHierarchy: () => censusClaudeMdHierarchy,
126
+ censusGlobalProfile: () => censusGlobalProfile,
127
+ censusRuleDir: () => censusRuleDir,
128
+ censusSkillsCatalog: () => censusSkillsCatalog,
129
+ main: () => main2,
130
+ parseArgs: () => parseArgs2,
131
+ renderText: () => renderText2,
132
+ topRulesByCost: () => topRulesByCost
133
+ });
134
+ var YAML = __toESM(require_dist(), 1);
135
+ import * as fs5 from "node:fs";
136
+ import { homedir as homedir2 } from "node:os";
137
+ import * as path8 from "node:path";
138
+ import { fileURLToPath as fileURLToPath3, pathToFileURL as pathToFileURL2 } from "node:url";
139
+
140
+ // src/scripts/_lib/agent_user_profile.ts
141
+ import * as path4 from "node:path";
142
+
143
+ // src/scripts/_lib/user_global_revocations.ts
144
+ import * as path2 from "node:path";
145
+ var REVOCATIONS_RELATIVE = path2.join("user", ".revocations.jsonl");
146
+
147
+ // src/scripts/_lib/user_memory_gate_counters.ts
148
+ import * as path3 from "node:path";
149
+ var GATE_COUNTERS_RELATIVE = path3.join("user", "promotion-gate-counters.json");
150
+
151
+ // src/scripts/_lib/agent_user_profile.ts
152
+ var GLOBAL_PROFILE_RELATIVE = path4.join("user", "profile.md");
153
+ function resolveGlobalProfilePath(env) {
154
+ return resolve_with_fallback(GLOBAL_PROFILE_RELATIVE, { env: env ?? null });
155
+ }
156
+
157
+ // src/scripts/_lib/carrier_divergence.ts
158
+ import * as fs2 from "node:fs";
159
+ import * as path5 from "node:path";
160
+ var OWNERSHIP_KEYS = ["package", "source_path"];
161
+ function stripOwnershipKeys(text) {
162
+ return text.split("\n").filter((line) => !OWNERSHIP_KEYS.some((k) => line.startsWith(`${k}:`))).join("\n");
163
+ }
164
+ function comparePair(a, b) {
165
+ if (a.equals(b)) {
166
+ return "identical";
167
+ }
168
+ if (stripOwnershipKeys(a.toString("utf-8")) === stripOwnershipKeys(b.toString("utf-8"))) {
169
+ return "provenance-only";
170
+ }
171
+ return "body-diff";
172
+ }
173
+ function splitFrontmatter(text) {
174
+ if (!text.startsWith("---")) return { hadFrontmatter: false, frontmatter: "", body: text };
175
+ const end = text.indexOf("\n---", 3);
176
+ if (end === -1) return { hadFrontmatter: false, frontmatter: "", body: text };
177
+ const afterFence = text.indexOf("\n", end + 1);
178
+ return {
179
+ hadFrontmatter: true,
180
+ frontmatter: text.slice(3, end),
181
+ body: afterFence === -1 ? "" : text.slice(afterFence + 1)
182
+ };
183
+ }
184
+ function proseEqual(a, b) {
185
+ const sa = splitFrontmatter(a);
186
+ const sb = splitFrontmatter(b);
187
+ if (!sa.hadFrontmatter && !sb.hadFrontmatter) return false;
188
+ const leading = /^\n+/;
189
+ return sa.body.replace(leading, "") === sb.body.replace(leading, "");
190
+ }
191
+ function frontmatterPaths(text) {
192
+ const { hadFrontmatter, frontmatter } = splitFrontmatter(text);
193
+ if (!hadFrontmatter) return null;
194
+ const lines = frontmatter.split("\n");
195
+ const start = lines.findIndex((l) => /^paths:/.test(l));
196
+ if (start === -1) return null;
197
+ const block = [lines[start]];
198
+ for (const line of lines.slice(start + 1)) {
199
+ if (/^\s/.test(line) && line.trim() !== "") block.push(line);
200
+ else break;
201
+ }
202
+ return block.map((l) => l.trim()).join(" ");
203
+ }
204
+ function censusRuleDir(dir) {
205
+ let files = 0;
206
+ let chars = 0;
207
+ let entries;
208
+ try {
209
+ entries = fs2.readdirSync(dir);
210
+ } catch {
211
+ return { files: 0, chars: 0 };
212
+ }
213
+ for (const name of entries) {
214
+ if (!name.endsWith(".md")) continue;
215
+ try {
216
+ chars += fs2.statSync(path5.join(dir, name)).size;
217
+ files += 1;
218
+ } catch {
219
+ }
220
+ }
221
+ return { files, chars };
222
+ }
223
+
224
+ // src/scripts/cache_realization_report.ts
225
+ import { execFileSync } from "node:child_process";
226
+ import * as fs4 from "node:fs";
227
+ import { homedir } from "node:os";
228
+ import * as path7 from "node:path";
229
+ import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
230
+
231
+ // src/scripts/ai_council/pricing.ts
232
+ import * as fs3 from "node:fs";
233
+ import * as path6 from "node:path";
234
+ import { fileURLToPath } from "node:url";
235
+
236
+ // src/scripts/ai_council/_default_prices.ts
237
+ var LAST_UPDATED = "2026-05-14";
238
+ var DEFAULT_PRICES_ENTRIES = [
239
+ // ── Anthropic ────────────────────────────────────────────────────
240
+ ["anthropic", "claude-sonnet-4-5", 3, 15],
241
+ ["anthropic", "claude-opus-4-1", 15, 75],
242
+ ["anthropic", "claude-haiku-4-5", 1, 5],
243
+ // ── OpenAI ───────────────────────────────────────────────────────
244
+ ["openai", "gpt-4o", 2.5, 10],
245
+ ["openai", "gpt-4o-mini", 0.15, 0.6],
246
+ ["openai", "o1", 15, 60],
247
+ ["openai", "o3-mini", 1.1, 4.4],
248
+ // ── Google Gemini ────────────────────────────────────────────────
249
+ ["gemini", "gemini-2.5-pro", 1.25, 10],
250
+ ["gemini", "gemini-2.5-flash", 0.3, 2.5],
251
+ // ── xAI Grok ─────────────────────────────────────────────────────
252
+ ["xai", "grok-4", 3, 15],
253
+ ["xai", "grok-3-mini", 0.3, 0.5],
254
+ // ── Perplexity ───────────────────────────────────────────────────
255
+ ["perplexity", "sonar-pro", 3, 15],
256
+ ["perplexity", "sonar", 1, 1]
257
+ ];
258
+ function priceKey(provider, model) {
259
+ return `${provider} ${model}`;
260
+ }
261
+ var DEFAULT_PRICES = new Map(
262
+ DEFAULT_PRICES_ENTRIES.map(([p, m, i, o]) => [priceKey(p, m), [i, o]])
263
+ );
264
+ function as_rows() {
265
+ return [...DEFAULT_PRICES_ENTRIES].map(([p, m, i, o]) => [p, m, i, o]).sort((a, b) => {
266
+ if (a[0] !== b[0]) {
267
+ return a[0] < b[0] ? -1 : 1;
268
+ }
269
+ if (a[1] !== b[1]) {
270
+ return a[1] < b[1] ? -1 : 1;
271
+ }
272
+ return 0;
273
+ });
274
+ }
275
+
276
+ // src/scripts/ai_council/pricing.ts
277
+ var _HERE = fileURLToPath(import.meta.url);
278
+ var REPO_ROOT = path6.resolve(path6.dirname(_HERE), "..", "..", "..");
279
+ var PRICES_FILE = path6.join(REPO_ROOT, "agents", "runtime", ".agent-prices.md");
280
+ function lookup(table, provider, model) {
281
+ const exact = table.prices.get(priceKey(provider, model));
282
+ if (exact !== void 0) {
283
+ return exact;
284
+ }
285
+ const prefix = priceKey(provider, "");
286
+ let best = null;
287
+ let bestLen = -1;
288
+ for (const [key, price] of table.prices) {
289
+ if (!key.startsWith(prefix)) {
290
+ continue;
291
+ }
292
+ const candidate = key.slice(prefix.length);
293
+ if (!candidate || !model.startsWith(candidate)) {
294
+ continue;
295
+ }
296
+ const next = model.charAt(candidate.length);
297
+ if (next !== "" && next !== "-" && next !== "." && next !== ":" && next !== "@") {
298
+ continue;
299
+ }
300
+ if (candidate.length > bestLen) {
301
+ best = price;
302
+ bestLen = candidate.length;
303
+ }
304
+ }
305
+ return best;
306
+ }
307
+ var CACHE_READ_MULTIPLIER = 0.1;
308
+ var CACHE_WRITE_MULTIPLIER_5M = 1.25;
309
+ var CACHE_WRITE_MULTIPLIER_1H = 2;
310
+ function reprice_with_cache(provider, model, tokens, table, ttl = "5m") {
311
+ const price = lookup(table, provider, model);
312
+ const read = tokens.cache_read_input_tokens ?? 0;
313
+ const write = tokens.cache_creation_input_tokens ?? 0;
314
+ const totalInput = tokens.input_tokens + read + write;
315
+ if (price === null) {
316
+ return {
317
+ provider,
318
+ model,
319
+ input_tokens: totalInput,
320
+ output_tokens: tokens.output_tokens,
321
+ input_usd: 0,
322
+ output_usd: 0
323
+ };
324
+ }
325
+ const writeMult = ttl === "1h" ? CACHE_WRITE_MULTIPLIER_1H : CACHE_WRITE_MULTIPLIER_5M;
326
+ const inputUsd = tokens.input_tokens / 1e6 * price.input_per_1m_usd + read / 1e6 * price.input_per_1m_usd * CACHE_READ_MULTIPLIER + write / 1e6 * price.input_per_1m_usd * writeMult;
327
+ const outputUsd = tokens.output_tokens / 1e6 * price.output_per_1m_usd;
328
+ return {
329
+ provider,
330
+ model,
331
+ input_tokens: totalInput,
332
+ output_tokens: tokens.output_tokens,
333
+ input_usd: inputUsd,
334
+ output_usd: outputUsd
335
+ };
336
+ }
337
+ function load_prices(p = PRICES_FILE) {
338
+ if (!fs3.existsSync(p)) {
339
+ bootstrap_from_defaults(p);
340
+ }
341
+ return _parse(fs3.readFileSync(p, "utf-8"));
342
+ }
343
+ function bootstrap_from_defaults(p = PRICES_FILE) {
344
+ fs3.mkdirSync(path6.dirname(p), { recursive: true });
345
+ const rows = as_rows();
346
+ const body = _render_markdown(LAST_UPDATED, "shipped-default", rows);
347
+ fs3.writeFileSync(p, body, "utf-8");
348
+ }
349
+ function _fmt62f(x) {
350
+ const s = x.toFixed(2);
351
+ return s.length >= 6 ? s : " ".repeat(6 - s.length) + s;
352
+ }
353
+ function _ljust(s, width) {
354
+ return s.length >= width ? s : s + " ".repeat(width - s.length);
355
+ }
356
+ function _render_markdown(lastUpdated, source, rows) {
357
+ const lines = [
358
+ "---",
359
+ `last_updated: ${lastUpdated}`,
360
+ "currency: USD",
361
+ "unit: per_1M_tokens",
362
+ `source: ${source}`,
363
+ "---",
364
+ "",
365
+ "# Agent prices",
366
+ "",
367
+ "| provider | model | input | output |",
368
+ "|-----------|---------------------|--------|--------|"
369
+ ];
370
+ for (const [provider, model, inp, outp] of rows) {
371
+ lines.push(`| ${_ljust(provider, 9)} | ${_ljust(model, 19)} | ${_fmt62f(inp)} | ${_fmt62f(outp)} |`);
372
+ }
373
+ lines.push("");
374
+ return lines.join("\n");
375
+ }
376
+ function _parse(text) {
377
+ const [front, body] = _split_frontmatter(text);
378
+ const meta = _parse_frontmatter(front);
379
+ const prices = _parse_table(body);
380
+ return {
381
+ last_updated: meta.last_updated ?? "1970-01-01",
382
+ currency: meta.currency ?? "USD",
383
+ unit: meta.unit ?? "per_1M_tokens",
384
+ source: meta.source ?? "unknown",
385
+ prices
386
+ };
387
+ }
388
+ function _split_frontmatter(text) {
389
+ if (!text.startsWith("---")) {
390
+ return ["", text];
391
+ }
392
+ const parts = _pySplit(text, "---", 2);
393
+ if (parts.length < 3) {
394
+ return ["", text];
395
+ }
396
+ return [parts[1], parts[2]];
397
+ }
398
+ function _pySplit(s, sep3, maxsplit) {
399
+ const out = [];
400
+ let rest = s;
401
+ let n = 0;
402
+ while (n < maxsplit) {
403
+ const idx = rest.indexOf(sep3);
404
+ if (idx === -1) {
405
+ break;
406
+ }
407
+ out.push(rest.slice(0, idx));
408
+ rest = rest.slice(idx + sep3.length);
409
+ n++;
410
+ }
411
+ out.push(rest);
412
+ return out;
413
+ }
414
+ function _parse_frontmatter(front) {
415
+ const out = {};
416
+ for (let line of front.split("\n")) {
417
+ line = line.trim();
418
+ if (!line || !line.includes(":")) {
419
+ continue;
420
+ }
421
+ const idx = line.indexOf(":");
422
+ out[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();
423
+ }
424
+ return out;
425
+ }
426
+ function _parse_table(body) {
427
+ const out = /* @__PURE__ */ new Map();
428
+ for (let line of body.split("\n")) {
429
+ line = line.trim();
430
+ if (!line.startsWith("|") || line.startsWith("|--") || line.startsWith("|-")) {
431
+ continue;
432
+ }
433
+ const stripped = line.replace(/^\|+/, "").replace(/\|+$/, "");
434
+ const cells = stripped.split("|").map((c) => c.trim());
435
+ if (cells.length !== 4) {
436
+ continue;
437
+ }
438
+ const [provider, model, inp, outp] = cells;
439
+ if (provider === "provider") {
440
+ continue;
441
+ }
442
+ const inV = _pyFloat(inp);
443
+ const outV = _pyFloat(outp);
444
+ if (inV === null || outV === null) {
445
+ continue;
446
+ }
447
+ out.set(priceKey(provider, model), {
448
+ provider,
449
+ model,
450
+ input_per_1m_usd: inV,
451
+ output_per_1m_usd: outV
452
+ });
453
+ }
454
+ return out;
455
+ }
456
+ function _pyFloat(s) {
457
+ const t = s.trim();
458
+ if (t === "") {
459
+ return null;
460
+ }
461
+ const n = Number(t);
462
+ return Number.isNaN(n) ? null : n;
463
+ }
464
+
465
+ // src/scripts/cache_realization_report.ts
466
+ var _HERE2 = fileURLToPath2(import.meta.url);
467
+ var REPO_ROOT2 = path7.resolve(path7.dirname(_HERE2), "..", "..");
468
+ var C1_COLD_START_DOMINANCE_THRESHOLD = 0.5;
469
+ var C2_DUPLICATE_SCOPE_THRESHOLD = 0.25;
470
+ var C4_COUNCIL_MISPRICING_THRESHOLD = 0.05;
471
+ var C5_CONFIRM_RATIO = 0.1;
472
+ var C5_FALSIFY_RATIO = 0.5;
473
+ var DRIFT_READ_SHARE_FLOOR = 0.9;
474
+ var DRIFT_COLD_START_SHARE_FLOOR = 0.5;
475
+ function median(nums) {
476
+ if (nums.length === 0) return 0;
477
+ const sorted = [...nums].sort((a, b) => a - b);
478
+ const mid = Math.floor(sorted.length / 2);
479
+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
480
+ }
481
+ function mean(nums) {
482
+ if (nums.length === 0) return 0;
483
+ return nums.reduce((a, b) => a + b, 0) / nums.length;
484
+ }
485
+ function firstCallsByLeg(records) {
486
+ const byAgent = /* @__PURE__ */ new Map();
487
+ for (const r of records) {
488
+ if (r.bucket !== "subagent" || r.agentId === null) continue;
489
+ const arr = byAgent.get(r.agentId) ?? [];
490
+ arr.push(r);
491
+ byAgent.set(r.agentId, arr);
492
+ }
493
+ const firstCalls = [];
494
+ for (const arr of byAgent.values()) {
495
+ const sorted = arr.map((r, idx) => ({ r, idx })).sort((a, b) => {
496
+ const ta = a.r.timestamp;
497
+ const tb = b.r.timestamp;
498
+ if (ta !== null && tb !== null && ta !== tb) return ta < tb ? -1 : 1;
499
+ if (ta !== null && tb === null) return -1;
500
+ if (ta === null && tb !== null) return 1;
501
+ return a.idx - b.idx;
502
+ }).map((x) => x.r);
503
+ firstCalls.push(sorted[0]);
504
+ }
505
+ return firstCalls;
506
+ }
507
+ function computeColdStarts(records) {
508
+ const subagentRecords = records.filter((r) => r.bucket === "subagent");
509
+ const totalWriteVolume = subagentRecords.reduce((s, r) => s + r.usage.cache_creation_input_tokens, 0);
510
+ const firstCalls = firstCallsByLeg(records);
511
+ const writtenOrUncached = firstCalls.map((r) => r.usage.cache_creation_input_tokens + r.usage.input_tokens);
512
+ const sumFirstCallRead = firstCalls.reduce((s, r) => s + r.usage.cache_read_input_tokens, 0);
513
+ const sumFirstCallBillable = firstCalls.reduce((s, r) => s + billableInputTokens(r.usage), 0);
514
+ const sumFirstCallWrite = firstCalls.reduce((s, r) => s + r.usage.cache_creation_input_tokens, 0);
515
+ const sumBillable = subagentRecords.reduce((s, r) => s + billableInputTokens(r.usage), 0);
516
+ const sumWrite = totalWriteVolume;
517
+ const sumRead = subagentRecords.reduce((s, r) => s + r.usage.cache_read_input_tokens, 0);
518
+ const sumUncached = subagentRecords.reduce((s, r) => s + r.usage.input_tokens, 0);
519
+ return {
520
+ legs: firstCalls.length,
521
+ median_first_call_written_or_uncached: median(writtenOrUncached),
522
+ mean_first_call_written_or_uncached: mean(writtenOrUncached),
523
+ first_call_cache_read_share: sumFirstCallBillable > 0 ? sumFirstCallRead / sumFirstCallBillable : 0,
524
+ cold_start_share_of_write_volume: totalWriteVolume > 0 ? sumFirstCallWrite / totalWriteVolume : 0,
525
+ write_share_of_billable: sumBillable > 0 ? sumWrite / sumBillable : 0,
526
+ read_share_of_billable: sumBillable > 0 ? sumRead / sumBillable : 0,
527
+ uncached_share_of_billable: sumBillable > 0 ? sumUncached / sumBillable : 0
528
+ };
529
+ }
530
+ function aggregateByAgent(records) {
531
+ const byAgent = /* @__PURE__ */ new Map();
532
+ for (const r of records) {
533
+ if (r.bucket !== "subagent" || r.agentId === null) continue;
534
+ const arr = byAgent.get(r.agentId) ?? [];
535
+ arr.push(r);
536
+ byAgent.set(r.agentId, arr);
537
+ }
538
+ const out = [];
539
+ for (const [agentId, recs] of byAgent) {
540
+ const agg = aggregateByBucket(recs).subagent;
541
+ out.push({ ...agg, agentId });
542
+ }
543
+ return out;
544
+ }
545
+ function computeDuplicateScope(userRulesDir, projectRulesDir, subagentWriteVolume, spawnCount) {
546
+ const census = censusDuplicateScope(userRulesDir, projectRulesDir);
547
+ if (!census.evaluable) {
548
+ return {
549
+ evaluable: false,
550
+ reason: census.reason,
551
+ shared_filenames: census.shared_filenames.length,
552
+ duplicate_tokens_per_spawn: 0,
553
+ spawn_count: spawnCount,
554
+ duplicate_token_estimate_total: 0,
555
+ share_of_subagent_write_volume: 0
556
+ };
557
+ }
558
+ const duplicateTokensPerSpawn = census.duplicate_chars / 4;
559
+ const totalEstimate = duplicateTokensPerSpawn * spawnCount;
560
+ const evaluable = spawnCount > 0 && subagentWriteVolume > 0;
561
+ return {
562
+ evaluable,
563
+ reason: evaluable ? void 0 : "no subagent legs or no subagent write volume observed in the window",
564
+ shared_filenames: census.shared_filenames.length,
565
+ duplicate_tokens_per_spawn: duplicateTokensPerSpawn,
566
+ spawn_count: spawnCount,
567
+ duplicate_token_estimate_total: totalEstimate,
568
+ share_of_subagent_write_volume: subagentWriteVolume > 0 ? totalEstimate / subagentWriteVolume : 0
569
+ };
570
+ }
571
+ function findDebateRoundFiles(councilRoot) {
572
+ const base = path7.join(councilRoot, "agents", "runtime", "council", "responses");
573
+ if (!fs4.existsSync(base)) return [];
574
+ const out = [];
575
+ const stack = [base];
576
+ while (stack.length > 0) {
577
+ const dir = stack.pop();
578
+ let entries;
579
+ try {
580
+ entries = fs4.readdirSync(dir, { withFileTypes: true });
581
+ } catch {
582
+ continue;
583
+ }
584
+ for (const entry of entries) {
585
+ const full = path7.join(dir, entry.name);
586
+ if (entry.isDirectory()) {
587
+ stack.push(full);
588
+ continue;
589
+ }
590
+ if (entry.isFile() && /^debate-round-\d+\.json$/.test(entry.name)) out.push(full);
591
+ }
592
+ }
593
+ return out;
594
+ }
595
+ function numOrUndef(v) {
596
+ return typeof v === "number" && Number.isFinite(v) ? v : void 0;
597
+ }
598
+ function computeCouncilMispricing(councilRoot) {
599
+ const files = findDebateRoundFiles(councilRoot);
600
+ if (files.length === 0) {
601
+ return {
602
+ status: "pending",
603
+ reason: "no agents/runtime/council/responses/**/debate-round-*.json artefact found under this root"
604
+ };
605
+ }
606
+ const groups = /* @__PURE__ */ new Map();
607
+ for (const f of files) {
608
+ const dir = path7.dirname(f);
609
+ const arr = groups.get(dir) ?? [];
610
+ arr.push(f);
611
+ groups.set(dir, arr);
612
+ }
613
+ let table;
614
+ try {
615
+ table = load_prices();
616
+ } catch {
617
+ return { status: "pending", reason: "could not load the local price table (.agent-prices.md)" };
618
+ }
619
+ let best = null;
620
+ for (const [dir, groupFiles] of groups) {
621
+ let rounds = 0;
622
+ let recorded = 0;
623
+ let cacheAware = 0;
624
+ let tokens = 0;
625
+ let cacheVolume = 0;
626
+ for (const f of groupFiles) {
627
+ let data;
628
+ try {
629
+ data = JSON.parse(fs4.readFileSync(f, "utf-8"));
630
+ } catch {
631
+ continue;
632
+ }
633
+ rounds = Math.max(rounds, numOrUndef(data.debate_total_rounds) ?? 0);
634
+ recorded += numOrUndef(data.cost_usd_actual) ?? 0;
635
+ for (const r of data.responses ?? []) {
636
+ if (r.error) continue;
637
+ const input = numOrUndef(r.input_tokens) ?? 0;
638
+ const output = numOrUndef(r.output_tokens) ?? 0;
639
+ const read = numOrUndef(r.cache_read_input_tokens) ?? 0;
640
+ const write = numOrUndef(r.cache_creation_input_tokens) ?? 0;
641
+ tokens += input + read + write;
642
+ cacheVolume += read + write;
643
+ if (typeof r.provider !== "string" || typeof r.model !== "string") continue;
644
+ const est = reprice_with_cache(
645
+ r.provider,
646
+ r.model,
647
+ { input_tokens: input, cache_read_input_tokens: read, cache_creation_input_tokens: write, output_tokens: output },
648
+ table,
649
+ "5m"
650
+ );
651
+ cacheAware += est.input_usd + est.output_usd;
652
+ }
653
+ }
654
+ if (rounds < 2 || tokens === 0 || recorded === 0) continue;
655
+ if (best === null || cacheVolume > best.cacheVolume || cacheVolume === best.cacheVolume && rounds > best.rounds || cacheVolume === best.cacheVolume && rounds === best.rounds && tokens > best.tokens) {
656
+ best = { dir, rounds, recorded, cacheAware, tokens, cacheVolume };
657
+ }
658
+ }
659
+ if (best === null) {
660
+ return {
661
+ status: "pending",
662
+ reason: "found debate-round artefacts, but none had \u22652 recorded rounds with non-error usage and a non-zero recorded cost"
663
+ };
664
+ }
665
+ const deltaPct = (best.cacheAware - best.recorded) / best.recorded;
666
+ const status = Math.abs(deltaPct) >= C4_COUNCIL_MISPRICING_THRESHOLD ? "confirmed" : "falsified";
667
+ return {
668
+ status,
669
+ session: path7.relative(councilRoot, best.dir) || "(top-level)",
670
+ rounds: best.rounds,
671
+ recorded_cost_usd: best.recorded,
672
+ cache_aware_cost_usd: best.cacheAware,
673
+ delta_pct: deltaPct
674
+ };
675
+ }
676
+ function encodeProjectPath(cwd) {
677
+ return cwd.replace(/[/.]/g, "-");
678
+ }
679
+ function listGitWorktrees(cwd) {
680
+ try {
681
+ const out = execFileSync("git", ["worktree", "list", "--porcelain"], { cwd, encoding: "utf-8", timeout: 1e4 });
682
+ const paths = [];
683
+ for (const line of out.split("\n")) {
684
+ if (line.startsWith("worktree ")) paths.push(line.slice("worktree ".length).trim());
685
+ }
686
+ return paths;
687
+ } catch {
688
+ return [];
689
+ }
690
+ }
691
+ function computeWorktreeFragmentation(projectsRoot, worktreePaths, maxAgeDays) {
692
+ if (worktreePaths.length < 2) {
693
+ return { status: "pending", reason: "fewer than 2 git worktrees found for this repo \u2014 nothing to compare" };
694
+ }
695
+ const established = worktreePaths[0];
696
+ const encodedEstablished = encodeProjectPath(established);
697
+ const worktreeDirs = worktreePaths.slice(1).map(encodeProjectPath).filter((d) => fs4.existsSync(path7.join(projectsRoot, d)));
698
+ if (!fs4.existsSync(path7.join(projectsRoot, encodedEstablished)) || worktreeDirs.length === 0) {
699
+ return {
700
+ status: "pending",
701
+ reason: "no transcript directory found for both an established and a fresh-worktree checkout of this repo"
702
+ };
703
+ }
704
+ const establishedScan = scanTranscripts({ root: projectsRoot, projectDir: encodedEstablished, maxAgeDays });
705
+ const establishedColdStart = computeColdStarts(establishedScan.records);
706
+ let worktreeRecords = [];
707
+ for (const d of worktreeDirs) {
708
+ worktreeRecords = worktreeRecords.concat(scanTranscripts({ root: projectsRoot, projectDir: d, maxAgeDays }).records);
709
+ }
710
+ const worktreeColdStart = computeColdStarts(worktreeRecords);
711
+ if (establishedColdStart.legs === 0 || worktreeColdStart.legs === 0) {
712
+ return {
713
+ status: "pending",
714
+ reason: `insufficient subagent legs in the ${maxAgeDays}-day window (established: ${establishedColdStart.legs}, worktrees: ${worktreeColdStart.legs})`,
715
+ established_project_dir: encodedEstablished,
716
+ worktree_project_dirs: worktreeDirs
717
+ };
718
+ }
719
+ const establishedShare = establishedColdStart.first_call_cache_read_share;
720
+ const worktreeShare = worktreeColdStart.first_call_cache_read_share;
721
+ const ratio = establishedShare > 0 ? worktreeShare / establishedShare : worktreeShare === 0 ? 0 : Number.POSITIVE_INFINITY;
722
+ if (!Number.isFinite(ratio)) {
723
+ return {
724
+ status: "pending",
725
+ reason: "established directory shows a zero first-call cache-read share \u2014 the comparison ratio is undefined",
726
+ established_project_dir: encodedEstablished,
727
+ worktree_project_dirs: worktreeDirs,
728
+ established_first_call_read_share: establishedShare,
729
+ worktree_first_call_read_share: worktreeShare
730
+ };
731
+ }
732
+ let status;
733
+ let reason;
734
+ if (ratio >= C5_FALSIFY_RATIO) {
735
+ status = "falsified";
736
+ } else if (ratio < C5_CONFIRM_RATIO) {
737
+ status = "confirmed";
738
+ } else {
739
+ status = "pending";
740
+ reason = `ratio ${(ratio * 100).toFixed(1)}% falls between the confirm (<10%) and falsify (>=50%) thresholds`;
741
+ }
742
+ return {
743
+ status,
744
+ reason,
745
+ established_project_dir: encodedEstablished,
746
+ worktree_project_dirs: worktreeDirs,
747
+ established_first_call_read_share: establishedShare,
748
+ worktree_first_call_read_share: worktreeShare,
749
+ ratio
750
+ };
751
+ }
752
+ function hostVersion() {
753
+ try {
754
+ const out = execFileSync("claude", ["--version"], { encoding: "utf-8", timeout: 5e3 }).trim();
755
+ return out.length > 0 ? out : "unknown";
756
+ } catch {
757
+ return "unknown";
758
+ }
759
+ }
760
+ function buildClaims(opts) {
761
+ const claims = [];
762
+ const c1Value = opts.subagentColdStart.cold_start_share_of_write_volume;
763
+ claims.push({
764
+ id: "C-1",
765
+ description: "cold-start dominance: cold starts are \u226550% of subagent write volume (baseline 69.4%)",
766
+ threshold: ">= 0.50",
767
+ verdict: opts.subagentColdStart.legs === 0 ? "pending" : c1Value >= C1_COLD_START_DOMINANCE_THRESHOLD ? "confirmed" : "falsified",
768
+ measured: opts.subagentColdStart.legs === 0 ? void 0 : c1Value,
769
+ reason: opts.subagentColdStart.legs === 0 ? "no subagent legs observed in the window" : void 0
770
+ });
771
+ const d = opts.duplicateScope;
772
+ claims.push({
773
+ id: "C-2",
774
+ description: "duplicate-scope share: the redundant rule-set copy is \u226525% of subagent write volume (baseline \u224837%)",
775
+ threshold: ">= 0.25",
776
+ verdict: !d.evaluable ? "pending" : d.share_of_subagent_write_volume >= C2_DUPLICATE_SCOPE_THRESHOLD ? "confirmed" : "falsified",
777
+ measured: d.evaluable ? d.share_of_subagent_write_volume : void 0,
778
+ reason: !d.evaluable ? d.reason : void 0
779
+ });
780
+ claims.push({
781
+ id: "C-3",
782
+ description: "preamble reducibility: a shipped reduction moves median cold-start tokens by \u226515% with no eval regression",
783
+ threshold: ">= 0.15",
784
+ verdict: "pending",
785
+ reason: "requires an implemented preamble-reduction intervention (Phase 3) \u2014 none has landed yet"
786
+ });
787
+ const c = opts.councilMispricing;
788
+ claims.push({
789
+ id: "C-4",
790
+ description: "council mispricing magnitude: cache-aware repricing changes a real multi-round debate\u2019s realized cost by \u22655%",
791
+ threshold: ">= 0.05 (absolute delta)",
792
+ verdict: c.status,
793
+ measured: c.delta_pct,
794
+ reason: c.reason
795
+ });
796
+ const w = opts.worktreeFragmentation;
797
+ claims.push({
798
+ id: "C-5",
799
+ description: "worktree fragmentation: a fresh worktree's first-call cache_read share is <10% of an established directory's (falsified at >=50%)",
800
+ threshold: "< 0.10 confirmed / >= 0.50 falsified",
801
+ verdict: w.status,
802
+ measured: w.ratio,
803
+ reason: w.reason
804
+ });
805
+ return claims;
806
+ }
807
+ function defaultOptions() {
808
+ return {
809
+ format: "text",
810
+ root: DEFAULT_PROJECTS_ROOT,
811
+ maxAgeDays: 14,
812
+ repoRoot: REPO_ROOT2,
813
+ councilRoot: REPO_ROOT2,
814
+ userRulesDir: path7.join(homedir(), ".claude", "rules"),
815
+ projectRulesDir: path7.join(REPO_ROOT2, "dist", "agent-src", "rules")
816
+ };
817
+ }
818
+ function parseArgs(argv) {
819
+ const opts = defaultOptions();
820
+ for (let i = 0; i < argv.length; i++) {
821
+ const a = argv[i];
822
+ if (a === void 0) continue;
823
+ if (a === "--format") opts.format = argv[++i] ?? opts.format;
824
+ else if (a.startsWith("--format=")) opts.format = a.slice("--format=".length);
825
+ else if (a === "--root") opts.root = argv[++i] ?? opts.root;
826
+ else if (a.startsWith("--root=")) opts.root = a.slice("--root=".length);
827
+ else if (a === "--max-age-days") opts.maxAgeDays = Number(argv[++i]) || opts.maxAgeDays;
828
+ else if (a.startsWith("--max-age-days=")) opts.maxAgeDays = Number(a.slice("--max-age-days=".length)) || opts.maxAgeDays;
829
+ else if (a === "--repo-root") opts.repoRoot = argv[++i] ?? opts.repoRoot;
830
+ else if (a.startsWith("--repo-root=")) opts.repoRoot = a.slice("--repo-root=".length);
831
+ else if (a === "--council-root") opts.councilRoot = argv[++i] ?? opts.councilRoot;
832
+ else if (a.startsWith("--council-root=")) opts.councilRoot = a.slice("--council-root=".length);
833
+ else if (a === "--user-rules-dir") opts.userRulesDir = argv[++i] ?? opts.userRulesDir;
834
+ else if (a.startsWith("--user-rules-dir=")) opts.userRulesDir = a.slice("--user-rules-dir=".length);
835
+ else if (a === "--project-rules-dir") opts.projectRulesDir = argv[++i] ?? opts.projectRulesDir;
836
+ else if (a.startsWith("--project-rules-dir=")) opts.projectRulesDir = a.slice("--project-rules-dir=".length);
837
+ }
838
+ if (opts.format !== "text" && opts.format !== "json") opts.format = "text";
839
+ return opts;
840
+ }
841
+ function buildReport(opts) {
842
+ const scan = scanTranscripts({ root: opts.root, maxAgeDays: opts.maxAgeDays });
843
+ const buckets = aggregateByBucket(scan.records);
844
+ const subagentColdStart = computeColdStarts(scan.records);
845
+ const byAgent = aggregateByAgent(scan.records);
846
+ const duplicateScope = computeDuplicateScope(
847
+ opts.userRulesDir,
848
+ opts.projectRulesDir,
849
+ buckets.subagent.cache_creation_input_tokens,
850
+ subagentColdStart.legs
851
+ );
852
+ const councilMispricing = computeCouncilMispricing(opts.councilRoot);
853
+ const worktreePaths = listGitWorktrees(opts.repoRoot);
854
+ const worktreeFragmentation = computeWorktreeFragmentation(opts.root, worktreePaths, opts.maxAgeDays);
855
+ const claims = buildClaims({ subagentColdStart, duplicateScope, councilMispricing, worktreeFragmentation });
856
+ return {
857
+ schema: "cache-realization-report/v1",
858
+ host_version: hostVersion(),
859
+ window_days: opts.maxAgeDays,
860
+ root: opts.root,
861
+ metric_definition: {
862
+ billable_input: "input_tokens + cache_read_input_tokens + cache_creation_input_tokens",
863
+ note: "Anthropic's usage.input_tokens EXCLUDES cache tokens \u2014 it is only the uncached portion of the prompt."
864
+ },
865
+ dedup_ratio: scan.dedup_ratio,
866
+ total_seen: scan.totalSeen,
867
+ deduped_count: scan.dedupedCount,
868
+ buckets,
869
+ subagent_cold_start: subagentColdStart,
870
+ by_agent: byAgent,
871
+ duplicate_scope: duplicateScope,
872
+ council_mispricing: councilMispricing,
873
+ worktree_fragmentation: worktreeFragmentation,
874
+ claims
875
+ };
876
+ }
877
+ function pct(v) {
878
+ return `${(v * 100).toFixed(1)}%`;
879
+ }
880
+ function renderText(r) {
881
+ const out = [];
882
+ out.push("Cache-realization report");
883
+ out.push(` host_version: ${r.host_version}`);
884
+ out.push(` window: last ${r.window_days} days`);
885
+ out.push(` root: ${r.root}`);
886
+ out.push(` metric: billable_input = ${r.metric_definition.billable_input}`);
887
+ out.push(` ${r.metric_definition.note}`);
888
+ out.push(` dedup: ${r.deduped_count}/${r.total_seen} unique records kept (dedup_ratio ${pct(r.dedup_ratio)})`);
889
+ out.push("");
890
+ out.push("By bucket:");
891
+ for (const bucket of ["main", "subagent"]) {
892
+ const b = r.buckets[bucket];
893
+ out.push(` ${bucket}: calls=${b.calls} read_share=${pct(b.read_share)} weighted_input_units=${Math.round(b.weighted_input_units)}`);
894
+ out.push(
895
+ ` input=${b.input_tokens} cache_read=${b.cache_read_input_tokens} cache_creation=${b.cache_creation_input_tokens} (5m=${b.ephemeral_5m_input_tokens} 1h=${b.ephemeral_1h_input_tokens}) output=${b.output_tokens}`
896
+ );
897
+ }
898
+ out.push("");
899
+ const cs = r.subagent_cold_start;
900
+ out.push("Subagent cold start (first call per leg):");
901
+ out.push(
902
+ ` legs=${cs.legs} median_written_or_uncached=${Math.round(cs.median_first_call_written_or_uncached)} mean=${Math.round(cs.mean_first_call_written_or_uncached)}`
903
+ );
904
+ out.push(` first_call_cache_read_share=${pct(cs.first_call_cache_read_share)}`);
905
+ out.push(` cold_start_share_of_subagent_write_volume=${pct(cs.cold_start_share_of_write_volume)}`);
906
+ out.push(
907
+ ` write_share=${pct(cs.write_share_of_billable)} read_share=${pct(cs.read_share_of_billable)} uncached_share=${pct(cs.uncached_share_of_billable)} (of billable input, all subagent records)`
908
+ );
909
+ out.push("");
910
+ out.push(`Per-agent breakdown: ${r.by_agent.length} distinct subagent legs (--format json carries all; top 10 by weighted_input_units below)`);
911
+ const top10 = [...r.by_agent].sort((a, b) => b.weighted_input_units - a.weighted_input_units).slice(0, 10);
912
+ for (const a of top10) {
913
+ out.push(` ${a.agentId}: calls=${a.calls} read_share=${pct(a.read_share)} weighted_input_units=${Math.round(a.weighted_input_units)}`);
914
+ }
915
+ out.push("");
916
+ out.push("Pre-registered claims:");
917
+ for (const c of r.claims) {
918
+ const measured = c.measured !== void 0 ? ` (measured ${pct(c.measured)})` : "";
919
+ const reasonSuffix = c.verdict === "pending" && c.reason ? ` \u2014 ${c.reason}` : "";
920
+ out.push(` ${c.id} [${c.verdict}]${measured}: ${c.description}${reasonSuffix}`);
921
+ }
922
+ out.push("");
923
+ out.push("Re-verification:");
924
+ out.push(" command: ./scripts-run src/scripts/cache_realization_report --format text");
925
+ out.push(` host_version at this run: ${r.host_version}`);
926
+ out.push(
927
+ ` re-run + restamp this report if: read_share drops below ${pct(DRIFT_READ_SHARE_FLOOR)}, OR cold-start share drops below ${pct(DRIFT_COLD_START_SHARE_FLOOR)}`
928
+ );
929
+ return out.join("\n");
930
+ }
931
+ function main(argv = process.argv.slice(2)) {
932
+ const opts = parseArgs(argv);
933
+ const report = buildReport(opts);
934
+ if (opts.format === "json") {
935
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
936
+ } else {
937
+ process.stdout.write(renderText(report) + "\n");
938
+ }
939
+ return 0;
940
+ }
941
+ if (process.argv[1] !== void 0) {
942
+ const invokedUrl = pathToFileURL(path7.resolve(process.argv[1])).href;
943
+ if (import.meta.url === invokedUrl) process.exit(main());
944
+ }
945
+
946
+ // src/scripts/preamble_byte_census.ts
947
+ var _HERE3 = fileURLToPath3(import.meta.url);
948
+ var REPO_ROOT3 = path8.resolve(path8.dirname(_HERE3), "..", "..");
949
+ var CHARS_PER_TOKEN = 4;
950
+ var SUM_TOLERANCE_PCT = 0.1;
951
+ function tokensFromChars(chars) {
952
+ return chars / CHARS_PER_TOKEN;
953
+ }
954
+ function readCharsIfExists(p) {
955
+ try {
956
+ return fs5.statSync(p).size;
957
+ } catch {
958
+ return 0;
959
+ }
960
+ }
961
+ function topRulesByCost(dir, limit = 10) {
962
+ if (!fs5.existsSync(dir)) return [];
963
+ const entries = [];
964
+ for (const name of fs5.readdirSync(dir)) {
965
+ if (!name.endsWith(".md")) continue;
966
+ let chars;
967
+ try {
968
+ chars = fs5.statSync(path8.join(dir, name)).size;
969
+ } catch {
970
+ continue;
971
+ }
972
+ entries.push({ file: name, chars, tokens_estimate: tokensFromChars(chars) });
973
+ }
974
+ entries.sort((a, b) => b.chars - a.chars || a.file.localeCompare(b.file));
975
+ return entries.slice(0, limit);
976
+ }
977
+ var IMPORT_LINE_RE = /^@(\S+)\s*$/;
978
+ function parseClaudeMdImports(claudeMdPath) {
979
+ let text;
980
+ try {
981
+ text = fs5.readFileSync(claudeMdPath, "utf-8");
982
+ } catch {
983
+ return [];
984
+ }
985
+ const base = path8.dirname(claudeMdPath);
986
+ const out = [];
987
+ for (const line of text.split("\n")) {
988
+ const m = IMPORT_LINE_RE.exec(line.trim());
989
+ if (!m) continue;
990
+ const rel = m[1];
991
+ const resolved = path8.isAbsolute(rel) ? rel : path8.join(base, rel);
992
+ const chars = readCharsIfExists(resolved);
993
+ if (chars > 0) out.push({ file: rel, chars });
994
+ }
995
+ return out;
996
+ }
997
+ function censusClaudeMdHierarchy(repoRoot, userHome) {
998
+ const projectClaudeMd = path8.join(repoRoot, "CLAUDE.md");
999
+ const projectClaudeLocalMd = path8.join(repoRoot, "CLAUDE.local.md");
1000
+ const userClaudeMd = path8.join(userHome, ".claude", "CLAUDE.md");
1001
+ return {
1002
+ project_claude_md_chars: readCharsIfExists(projectClaudeMd),
1003
+ project_claude_md_present: fs5.existsSync(projectClaudeMd),
1004
+ project_claude_local_md_chars: readCharsIfExists(projectClaudeLocalMd),
1005
+ project_claude_local_md_present: fs5.existsSync(projectClaudeLocalMd),
1006
+ user_claude_md_chars: readCharsIfExists(userClaudeMd),
1007
+ user_claude_md_present: fs5.existsSync(userClaudeMd),
1008
+ user_imports: parseClaudeMdImports(userClaudeMd)
1009
+ };
1010
+ }
1011
+ function censusGlobalProfile(env) {
1012
+ const p = resolveGlobalProfilePath(env);
1013
+ if (p === null) return { present: false, chars: 0, path: null };
1014
+ return { present: true, chars: readCharsIfExists(p), path: p };
1015
+ }
1016
+ function parseFrontmatter(text) {
1017
+ if (!text.startsWith("---")) return {};
1018
+ const end = text.indexOf("\n---", 3);
1019
+ if (end === -1) return {};
1020
+ const block = text.slice(3, end);
1021
+ try {
1022
+ const parsed = YAML.parse(block);
1023
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
1024
+ } catch {
1025
+ return {};
1026
+ }
1027
+ }
1028
+ function censusSkillsCatalog(skillsDir) {
1029
+ if (!fs5.existsSync(skillsDir)) return { skills: 0, chars: 0 };
1030
+ let skills = 0;
1031
+ let chars = 0;
1032
+ for (const entry of fs5.readdirSync(skillsDir, { withFileTypes: true })) {
1033
+ if (!entry.isDirectory()) continue;
1034
+ const skillMd = path8.join(skillsDir, entry.name, "SKILL.md");
1035
+ let text;
1036
+ try {
1037
+ text = fs5.readFileSync(skillMd, "utf-8");
1038
+ } catch {
1039
+ continue;
1040
+ }
1041
+ const fm = parseFrontmatter(text);
1042
+ const name = typeof fm.name === "string" && fm.name.length > 0 ? fm.name : entry.name;
1043
+ const description = typeof fm.description === "string" ? fm.description : "";
1044
+ chars += `- ${name}: ${description}
1045
+ `.length;
1046
+ skills += 1;
1047
+ }
1048
+ return { skills, chars };
1049
+ }
1050
+ function defaultOptions2() {
1051
+ const userHome = homedir2();
1052
+ return {
1053
+ format: "text",
1054
+ repoRoot: REPO_ROOT3,
1055
+ userHome,
1056
+ userRulesDir: path8.join(userHome, ".claude", "rules"),
1057
+ projectRulesDir: path8.join(REPO_ROOT3, "dist", "agent-src", "rules"),
1058
+ skillsDir: path8.join(REPO_ROOT3, "dist", "agent-src", "skills"),
1059
+ root: DEFAULT_PROJECTS_ROOT,
1060
+ maxAgeDays: 14
1061
+ };
1062
+ }
1063
+ function parseArgs2(argv) {
1064
+ const opts = defaultOptions2();
1065
+ for (let i = 0; i < argv.length; i++) {
1066
+ const a = argv[i];
1067
+ if (a === void 0) continue;
1068
+ if (a === "--format") opts.format = argv[++i] ?? opts.format;
1069
+ else if (a.startsWith("--format=")) opts.format = a.slice("--format=".length);
1070
+ else if (a === "--repo-root") opts.repoRoot = argv[++i] ?? opts.repoRoot;
1071
+ else if (a.startsWith("--repo-root=")) opts.repoRoot = a.slice("--repo-root=".length);
1072
+ else if (a === "--user-home") opts.userHome = argv[++i] ?? opts.userHome;
1073
+ else if (a.startsWith("--user-home=")) opts.userHome = a.slice("--user-home=".length);
1074
+ else if (a === "--user-rules-dir") opts.userRulesDir = argv[++i] ?? opts.userRulesDir;
1075
+ else if (a.startsWith("--user-rules-dir=")) opts.userRulesDir = a.slice("--user-rules-dir=".length);
1076
+ else if (a === "--project-rules-dir") opts.projectRulesDir = argv[++i] ?? opts.projectRulesDir;
1077
+ else if (a.startsWith("--project-rules-dir=")) opts.projectRulesDir = a.slice("--project-rules-dir=".length);
1078
+ else if (a === "--skills-dir") opts.skillsDir = argv[++i] ?? opts.skillsDir;
1079
+ else if (a.startsWith("--skills-dir=")) opts.skillsDir = a.slice("--skills-dir=".length);
1080
+ else if (a === "--root") opts.root = argv[++i] ?? opts.root;
1081
+ else if (a.startsWith("--root=")) opts.root = a.slice("--root=".length);
1082
+ else if (a === "--max-age-days") opts.maxAgeDays = Number(argv[++i]) || opts.maxAgeDays;
1083
+ else if (a.startsWith("--max-age-days=")) opts.maxAgeDays = Number(a.slice("--max-age-days=".length)) || opts.maxAgeDays;
1084
+ }
1085
+ if (opts.format !== "text" && opts.format !== "json") opts.format = "text";
1086
+ return opts;
1087
+ }
1088
+ function buildByteCensus(opts) {
1089
+ const claudeMdChars = opts.claudeMd.project_claude_md_chars + opts.claudeMd.project_claude_local_md_chars + opts.claudeMd.user_claude_md_chars + opts.claudeMd.user_imports.reduce((s, i) => s + i.chars, 0);
1090
+ const claudeMdFiles = (opts.claudeMd.project_claude_md_present ? 1 : 0) + (opts.claudeMd.project_claude_local_md_present ? 1 : 0) + (opts.claudeMd.user_claude_md_present ? 1 : 0) + opts.claudeMd.user_imports.length;
1091
+ const sources = [
1092
+ {
1093
+ name: "user-scope rules (~/.claude/rules/*.md)",
1094
+ files: opts.userRules.files,
1095
+ chars: opts.userRules.chars,
1096
+ tokens_estimate: tokensFromChars(opts.userRules.chars),
1097
+ provenance: "measured_local_file",
1098
+ basis: "\u03A3 byte size of every .md file in the user-scope rules directory, chars/4."
1099
+ },
1100
+ {
1101
+ name: "project-scope rules (dist/agent-src/rules/*.md)",
1102
+ files: opts.projectRules.files,
1103
+ chars: opts.projectRules.chars,
1104
+ tokens_estimate: tokensFromChars(opts.projectRules.chars),
1105
+ provenance: "measured_local_file",
1106
+ basis: "\u03A3 byte size of every .md file in the project-scope rules directory, chars/4."
1107
+ },
1108
+ {
1109
+ name: "CLAUDE.md hierarchy (project + project-local + user + user @-imports)",
1110
+ files: claudeMdFiles,
1111
+ chars: claudeMdChars,
1112
+ tokens_estimate: tokensFromChars(claudeMdChars),
1113
+ provenance: "measured_local_file",
1114
+ basis: 'Byte size of project CLAUDE.md + project CLAUDE.local.md (if present) + user ~/.claude/CLAUDE.md + every file pulled in by a top-level "@<path>" import line in the user CLAUDE.md, chars/4.'
1115
+ },
1116
+ {
1117
+ name: "global user profile.md (road-to-global-user-memory)",
1118
+ files: opts.globalProfile.present ? 1 : 0,
1119
+ chars: opts.globalProfile.chars,
1120
+ tokens_estimate: tokensFromChars(opts.globalProfile.chars),
1121
+ provenance: "measured_local_file",
1122
+ basis: opts.globalProfile.present ? `Byte size of ${opts.globalProfile.path}, chars/4.` : "Layer not written yet on this machine (resolveGlobalProfilePath() returned null) \u2014 treated as 0, per the roadmap's own honesty caveat."
1123
+ },
1124
+ {
1125
+ name: "preloaded skills catalog (name + description, dist/agent-src/skills)",
1126
+ files: opts.skillsCatalog.skills,
1127
+ chars: opts.skillsCatalog.chars,
1128
+ tokens_estimate: tokensFromChars(opts.skillsCatalog.chars),
1129
+ provenance: "measured_local_file",
1130
+ basis: `\u03A3 "- <name>: <description>\\n" over every SKILL.md frontmatter, chars/4 \u2014 the description-text component only; the host's exact on-wire catalog format is not independently file-measurable.`
1131
+ }
1132
+ ];
1133
+ const measurableTokensTotal = sources.reduce((s, src) => s + src.tokens_estimate, 0);
1134
+ const median3 = opts.measuredColdStartMedian;
1135
+ const residualTokens = median3 !== null ? Math.max(0, median3 - measurableTokensTotal) : null;
1136
+ if (residualTokens !== null) {
1137
+ sources.push({
1138
+ name: "tool definitions + dispatch prompt (residual)",
1139
+ files: 0,
1140
+ chars: 0,
1141
+ tokens_estimate: residualTokens,
1142
+ provenance: "residual",
1143
+ basis: "measured_cold_start_median minus the sum of the file-measurable buckets above. No local transcript or file carries the request's raw tool-definition JSON or the per-spawn dispatch-prompt text (verified: ~/.claude/projects/**/*.jsonl records only message.usage counts and response content, never the request system/tool payload) \u2014 this bucket exists so the gap is named rather than silently dropped."
1144
+ });
1145
+ }
1146
+ const grandTotal = sources.reduce((s, src) => s + src.tokens_estimate, 0);
1147
+ const measurableShare = median3 !== null && median3 > 0 ? measurableTokensTotal / median3 : null;
1148
+ const withinTolerance = median3 !== null ? Math.abs(grandTotal - median3) / Math.max(1, median3) <= SUM_TOLERANCE_PCT : null;
1149
+ const dup = opts.duplicateScope;
1150
+ let modelledNewMedian = null;
1151
+ let modelledReductionPct = null;
1152
+ let modelledApplicable = false;
1153
+ let modelledReason;
1154
+ if (median3 === null) {
1155
+ modelledReason = "no measured cold-start median available in this window";
1156
+ } else if (!dup.evaluable) {
1157
+ modelledReason = dup.reason ?? "duplicate-scope census not evaluable";
1158
+ } else {
1159
+ modelledApplicable = true;
1160
+ modelledNewMedian = Math.max(0, median3 - dup.duplicate_chars / CHARS_PER_TOKEN);
1161
+ modelledReductionPct = median3 > 0 ? (median3 - modelledNewMedian) / median3 : 0;
1162
+ }
1163
+ return {
1164
+ sources,
1165
+ measurable_tokens_total: measurableTokensTotal,
1166
+ grand_total_tokens: grandTotal,
1167
+ measured_cold_start_median: median3,
1168
+ cold_start_legs: opts.coldStartLegs,
1169
+ measurable_share_of_median: measurableShare,
1170
+ within_tolerance: withinTolerance,
1171
+ top_rules_by_cost: opts.topRules,
1172
+ duplicate_scope: {
1173
+ evaluable: dup.evaluable,
1174
+ reason: dup.reason,
1175
+ shared_filenames: dup.shared_filenames.length,
1176
+ duplicate_tokens_per_spawn: dup.evaluable ? dup.duplicate_chars / CHARS_PER_TOKEN : 0
1177
+ },
1178
+ modelled_duplicate_removal: {
1179
+ applicable: modelledApplicable,
1180
+ reason: modelledReason,
1181
+ modelled_new_median: modelledNewMedian,
1182
+ modelled_reduction_pct: modelledReductionPct
1183
+ }
1184
+ };
1185
+ }
1186
+ function buildReport2(opts) {
1187
+ const userRules = censusRuleDir(opts.userRulesDir);
1188
+ const projectRules = censusRuleDir(opts.projectRulesDir);
1189
+ const claudeMd = censusClaudeMdHierarchy(opts.repoRoot, opts.userHome);
1190
+ const globalProfile = censusGlobalProfile();
1191
+ const skillsCatalog = censusSkillsCatalog(opts.skillsDir);
1192
+ const topRules = topRulesByCost(opts.projectRulesDir, 10);
1193
+ const duplicateScope = censusDuplicateScope(opts.userRulesDir, opts.projectRulesDir);
1194
+ const scan = scanTranscripts({ root: opts.root, maxAgeDays: opts.maxAgeDays });
1195
+ const coldStart = computeColdStarts(scan.records);
1196
+ const measuredColdStartMedian = coldStart.legs > 0 ? coldStart.median_first_call_written_or_uncached : null;
1197
+ return buildByteCensus({
1198
+ userRules,
1199
+ projectRules,
1200
+ claudeMd,
1201
+ globalProfile,
1202
+ skillsCatalog,
1203
+ topRules,
1204
+ duplicateScope,
1205
+ measuredColdStartMedian,
1206
+ coldStartLegs: coldStart.legs
1207
+ });
1208
+ }
1209
+ function pct2(v) {
1210
+ return `${(v * 100).toFixed(1)}%`;
1211
+ }
1212
+ function renderText2(r) {
1213
+ const out = [];
1214
+ out.push("Preamble byte census (road-to-cache-economy Phase 3, steps 1-2)");
1215
+ out.push("");
1216
+ out.push("Sources:");
1217
+ for (const s of r.sources) {
1218
+ out.push(` ${s.name}`);
1219
+ out.push(` files=${s.files} chars=${s.chars} tokens_estimate=${Math.round(s.tokens_estimate)} [${s.provenance}]`);
1220
+ out.push(` basis: ${s.basis}`);
1221
+ }
1222
+ out.push("");
1223
+ out.push(`measurable_tokens_total (excludes residual): ${Math.round(r.measurable_tokens_total)}`);
1224
+ out.push(`grand_total_tokens (includes residual): ${Math.round(r.grand_total_tokens)}`);
1225
+ if (r.measured_cold_start_median !== null) {
1226
+ out.push(`measured_cold_start_median: ${Math.round(r.measured_cold_start_median)} (${r.cold_start_legs} legs, this window)`);
1227
+ out.push(`measurable_share_of_median: ${pct2(r.measurable_share_of_median)} (the honest, non-tautological number)`);
1228
+ out.push(
1229
+ `sum check (grand_total vs median, \xB110%): ${r.within_tolerance ? "PASS" : "FAIL"} \u2014 trivially PASS by construction once the residual bucket exists; see the module doc comment for why.`
1230
+ );
1231
+ } else {
1232
+ out.push("measured_cold_start_median: pending \u2014 no subagent legs observed in this window; no residual computed.");
1233
+ }
1234
+ out.push("");
1235
+ out.push("Top-10 project-scope rules by per-spawn token cost:");
1236
+ for (const rule of r.top_rules_by_cost) {
1237
+ out.push(` ${rule.file}: chars=${rule.chars} tokens_estimate=${Math.round(rule.tokens_estimate)}`);
1238
+ }
1239
+ out.push("");
1240
+ out.push("Duplicate-scope census (C-2):");
1241
+ if (r.duplicate_scope.evaluable) {
1242
+ out.push(
1243
+ ` ${r.duplicate_scope.shared_filenames} shared filename(s), ${Math.round(r.duplicate_scope.duplicate_tokens_per_spawn)} redundant tokens per spawn.`
1244
+ );
1245
+ } else {
1246
+ out.push(` not evaluable \u2014 ${r.duplicate_scope.reason ?? "unknown reason"}`);
1247
+ }
1248
+ out.push("");
1249
+ out.push("Modelled duplicate-copy removal (MODELLED, not measured):");
1250
+ if (r.modelled_duplicate_removal.applicable) {
1251
+ out.push(` modelled_new_median: ${Math.round(r.modelled_duplicate_removal.modelled_new_median)}`);
1252
+ out.push(` modelled_reduction_pct: ${pct2(r.modelled_duplicate_removal.modelled_reduction_pct)}`);
1253
+ } else {
1254
+ out.push(` not applicable \u2014 ${r.modelled_duplicate_removal.reason ?? "unknown reason"}`);
1255
+ }
1256
+ out.push("");
1257
+ out.push("The per-spawn payload ceiling (median \u2264 40k / p95 \u2264 50k) is a DOCUMENTED CANDIDATE, gated on C-3");
1258
+ out.push("(preamble reducibility, still pending \u2014 no reduction intervention has landed). See");
1259
+ out.push("docs/contracts/load-context-budget-model.md. This report does NOT enforce it.");
1260
+ return out.join("\n");
1261
+ }
1262
+ function main2(argv = process.argv.slice(2)) {
1263
+ const opts = parseArgs2(argv);
1264
+ const report = buildReport2(opts);
1265
+ if (opts.format === "json") {
1266
+ process.stdout.write(JSON.stringify(report, null, 2) + "\n");
1267
+ } else {
1268
+ process.stdout.write(renderText2(report) + "\n");
1269
+ }
1270
+ return 0;
1271
+ }
1272
+ var _isBundled = true;
1273
+ if (!_isBundled && process.argv[1] !== void 0) {
1274
+ const invokedUrl = pathToFileURL2(path8.resolve(process.argv[1])).href;
1275
+ if (import.meta.url === invokedUrl) process.exit(main2());
1276
+ }
1277
+
1278
+ // src/scripts/dispatch_economy_report.ts
1279
+ var dispatch_economy_report_exports = {};
1280
+ __export(dispatch_economy_report_exports, {
1281
+ DEFAULT_AUDIT_DIR: () => DEFAULT_AUDIT_DIR,
1282
+ DEFAULT_PROJECTS_ROOT: () => DEFAULT_PROJECTS_ROOT,
1283
+ buildReport: () => buildReport3,
1284
+ computeLegs: () => computeLegs,
1285
+ main: () => main3,
1286
+ median: () => median2,
1287
+ readAuditOrchestrations: () => readAuditOrchestrations,
1288
+ renderText: () => renderText3
1289
+ });
1290
+ import * as fs6 from "node:fs";
1291
+ import * as path9 from "node:path";
1292
+ import { fileURLToPath as fileURLToPath4, pathToFileURL as pathToFileURL3 } from "node:url";
1293
+ var _HERE4 = fileURLToPath4(import.meta.url);
1294
+ var REPO_ROOT4 = path9.resolve(path9.dirname(_HERE4), "..", "..");
1295
+ var REGISTRATION_FILE = path9.join(REPO_ROOT4, "src", "config", "dispatch-economy-metrics.json");
1296
+ var DEFAULT_AUDIT_DIR = path9.join("agents", "runtime", "state", "audit");
1297
+ var REVIEWER_TYPE_RE = /review|judge|validator/i;
1298
+ function median2(values) {
1299
+ if (values.length === 0) return null;
1300
+ const s = [...values].sort((a, b) => a - b);
1301
+ const mid = Math.floor(s.length / 2);
1302
+ const lo = s[mid - 1];
1303
+ const hi = s[mid];
1304
+ if (s.length % 2 === 1) return hi ?? null;
1305
+ return lo !== void 0 && hi !== void 0 ? (lo + hi) / 2 : null;
1306
+ }
1307
+ function computeLegs(records) {
1308
+ const byAgent = /* @__PURE__ */ new Map();
1309
+ for (const r of records) {
1310
+ if (r.bucket !== "subagent" || r.agentId === null) continue;
1311
+ const list = byAgent.get(r.agentId) ?? [];
1312
+ list.push(r);
1313
+ byAgent.set(r.agentId, list);
1314
+ }
1315
+ const legs = [];
1316
+ for (const [agentId, recs] of byAgent) {
1317
+ const sorted = [...recs].sort((a, b) => {
1318
+ if (a.timestamp === null || b.timestamp === null) return 0;
1319
+ return a.timestamp < b.timestamp ? -1 : a.timestamp > b.timestamp ? 1 : 0;
1320
+ });
1321
+ const first = sorted[0];
1322
+ if (first === void 0) continue;
1323
+ const init = billableInputTokens(first.usage);
1324
+ const total = sorted.reduce((acc, r) => acc + billableInputTokens(r.usage), 0);
1325
+ const work = total - init;
1326
+ const initUnits = weightedInputUnits(first.usage);
1327
+ const workUnits = sorted.slice(1).reduce((acc, r) => acc + weightedInputUnits(r.usage), 0);
1328
+ legs.push({
1329
+ agentId,
1330
+ calls: sorted.length,
1331
+ init_tokens: init,
1332
+ work_tokens: work,
1333
+ ratio: workUnits > 0 ? initUnits / workUnits : null
1334
+ });
1335
+ }
1336
+ return legs.sort((a, b) => a.agentId < b.agentId ? -1 : 1);
1337
+ }
1338
+ function isFiniteNonNegInt(v) {
1339
+ return typeof v === "number" && Number.isInteger(v) && v >= 0;
1340
+ }
1341
+ function readAuditOrchestrations(auditDir, opts = {}) {
1342
+ if (!fs6.existsSync(auditDir)) return [];
1343
+ const out = [];
1344
+ const cutoffMs = opts.maxAgeDays !== void 0 ? (opts.now ?? /* @__PURE__ */ new Date()).getTime() - opts.maxAgeDays * 24 * 60 * 60 * 1e3 : null;
1345
+ let entries;
1346
+ try {
1347
+ entries = fs6.readdirSync(auditDir).filter((f) => f.endsWith(".jsonl")).sort();
1348
+ } catch {
1349
+ return [];
1350
+ }
1351
+ if (cutoffMs !== null) {
1352
+ entries = entries.filter((f) => {
1353
+ try {
1354
+ return fs6.statSync(path9.join(auditDir, f)).mtimeMs >= cutoffMs;
1355
+ } catch {
1356
+ return false;
1357
+ }
1358
+ });
1359
+ }
1360
+ for (const f of entries) {
1361
+ let text;
1362
+ try {
1363
+ text = fs6.readFileSync(path9.join(auditDir, f), "utf8");
1364
+ } catch {
1365
+ continue;
1366
+ }
1367
+ for (const line of text.split("\n")) {
1368
+ if (line.trim().length === 0) continue;
1369
+ try {
1370
+ const parsed = JSON.parse(line);
1371
+ if (!parsed.orchestration || typeof parsed.orchestration !== "object") continue;
1372
+ if (cutoffMs !== null && typeof parsed.ts === "string") {
1373
+ const t = Date.parse(parsed.ts);
1374
+ if (Number.isFinite(t) && t < cutoffMs) continue;
1375
+ }
1376
+ out.push(parsed.orchestration);
1377
+ } catch {
1378
+ continue;
1379
+ }
1380
+ }
1381
+ }
1382
+ return out;
1383
+ }
1384
+ function buildReport3(opts) {
1385
+ const registrationRaw = fs6.readFileSync(REGISTRATION_FILE, "utf8");
1386
+ const registration = JSON.parse(registrationRaw);
1387
+ const scanOpts = {
1388
+ root: opts.root,
1389
+ maxAgeDays: opts.maxAgeDays,
1390
+ ...opts.now !== void 0 ? { now: opts.now } : {}
1391
+ };
1392
+ const scan = scanTranscripts(scanOpts);
1393
+ const legs = computeLegs(scan.records);
1394
+ const finiteRatios = legs.map((l) => l.ratio).filter((r) => r !== null);
1395
+ const singleCall = legs.filter((l) => l.ratio === null).length;
1396
+ const orchestrations = readAuditOrchestrations(opts.auditDir, {
1397
+ maxAgeDays: opts.maxAgeDays,
1398
+ ...opts.now !== void 0 ? { now: opts.now } : {}
1399
+ });
1400
+ const reviewerMeasured = [];
1401
+ const quotas = [];
1402
+ let askLines = 0;
1403
+ let askAdopted = 0;
1404
+ let askEscalated = 0;
1405
+ const returnChars = [];
1406
+ for (const o of orchestrations) {
1407
+ if (o.route_taken === "ask") {
1408
+ askLines += 1;
1409
+ if (o.outcome === "DONE") askAdopted += 1;
1410
+ }
1411
+ if (o.route_taken === "subagent" && o.escalated === true && o.origin === "dispatch-economy-2026") {
1412
+ askEscalated += 1;
1413
+ }
1414
+ if (isFiniteNonNegInt(o.return_channel_chars)) {
1415
+ returnChars.push(o.return_channel_chars);
1416
+ }
1417
+ if (isFiniteNonNegInt(o.rules_carried) && isFiniteNonNegInt(o.rules_used) && o.rules_carried > 0) {
1418
+ quotas.push(o.rules_used / o.rules_carried);
1419
+ }
1420
+ const isReviewer = Array.isArray(o.agent_combo) && o.agent_combo.some((t2) => typeof t2 === "string" && REVIEWER_TYPE_RE.test(t2));
1421
+ if (isReviewer && o.floor_provenance === "measured" && isFiniteNonNegInt(o.init_tokens) && isFiniteNonNegInt(o.work_tokens)) {
1422
+ reviewerMeasured.push({ init: o.init_tokens, work: o.work_tokens });
1423
+ }
1424
+ }
1425
+ const workerFloor = {
1426
+ role: "worker",
1427
+ attribution: "transcript-leg (role axis not shipped \u2014 all legs report as worker)",
1428
+ legs: legs.length,
1429
+ single_call_legs: singleCall,
1430
+ median_init_tokens: median2(legs.map((l) => l.init_tokens)),
1431
+ median_ratio_finite: median2(finiteRatios)
1432
+ };
1433
+ const reviewerRatios = reviewerMeasured.filter((p) => p.work > 0).map((p) => p.init / p.work);
1434
+ const reviewerFloor = {
1435
+ role: "reviewer",
1436
+ attribution: "audit-line agent_combo",
1437
+ legs: reviewerMeasured.length,
1438
+ single_call_legs: reviewerMeasured.filter((p) => p.work === 0).length,
1439
+ median_init_tokens: median2(reviewerMeasured.map((p) => p.init)),
1440
+ median_ratio_finite: median2(reviewerRatios)
1441
+ };
1442
+ const t = registration.metrics.dispatch_floor.thresholds;
1443
+ const lowQuota = registration.metrics.rules_efficiency.thresholds.low_quota_signal;
1444
+ const medianQuota = median2(quotas);
1445
+ const medianWorkerRatio = workerFloor.median_ratio_finite;
1446
+ const notes = [
1447
+ `dedup: ${scan.totalSeen} raw assistant records \u2192 ${scan.dedupedCount} (replay inflation removed)`,
1448
+ "single_call_legs are floor-only legs (all init, zero work) \u2014 they are excluded from the finite-ratio median and support, never dilute, the projection-mandatory reading",
1449
+ "projection_mandatory_signal is a single-run reading; the registered verdict is a sustained-window call at review date (dispatch-economy-metrics.json)"
1450
+ ];
1451
+ return {
1452
+ schema: "dispatch-economy-report/v1",
1453
+ registration: { registered_at: registration.registered_at, review_by: registration.review_by },
1454
+ window: { max_age_days: opts.maxAgeDays, transcript_records: scan.dedupedCount, legs: legs.length },
1455
+ dispatch_floor: {
1456
+ roles: [workerFloor, reviewerFloor],
1457
+ thresholds: t,
1458
+ projection_mandatory_signal: medianWorkerRatio === null ? null : medianWorkerRatio > t.projection_mandatory_ratio
1459
+ },
1460
+ rules_efficiency: {
1461
+ envelopes_with_pair: quotas.length,
1462
+ median_quota: medianQuota,
1463
+ threshold_low_quota: lowQuota,
1464
+ low_quota_signal: medianQuota === null ? null : medianQuota < lowQuota
1465
+ },
1466
+ ask_economy: {
1467
+ ask_lines: askLines,
1468
+ adopted: askAdopted,
1469
+ escalated: askEscalated,
1470
+ threshold_escalation_kill: registration.metrics.ask_economy.thresholds.escalation_kill,
1471
+ escalation_kill_signal: askLines === 0 ? null : askEscalated / askLines > registration.metrics.ask_economy.thresholds.escalation_kill
1472
+ },
1473
+ return_channel: {
1474
+ lines_with_field: returnChars.length,
1475
+ median_chars: median2(returnChars),
1476
+ envelope_cap_chars: registration.metrics.return_channel.thresholds.envelope_cap_chars,
1477
+ cap_breach_signal: returnChars.length === 0 ? null : (median2(returnChars) ?? 0) > registration.metrics.return_channel.thresholds.envelope_cap_chars
1478
+ },
1479
+ notes
1480
+ };
1481
+ }
1482
+ function fmtTokens(n) {
1483
+ if (n === null) return "\u2014";
1484
+ return n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(Math.round(n));
1485
+ }
1486
+ function renderText3(r) {
1487
+ const lines = [];
1488
+ lines.push("dispatch-economy report (registered: " + r.registration.registered_at + " \xB7 review by: " + r.registration.review_by + ")");
1489
+ lines.push(`window: ${r.window.max_age_days}d \xB7 ${r.window.transcript_records} deduped records \xB7 ${r.window.legs} legs`);
1490
+ lines.push("");
1491
+ lines.push("dispatch_floor:");
1492
+ for (const role of r.dispatch_floor.roles) {
1493
+ lines.push(
1494
+ ` ${role.role.padEnd(8)} legs=${role.legs} (single-call: ${role.single_call_legs}) \xB7 median init=${fmtTokens(role.median_init_tokens)} \xB7 median init/work=${role.median_ratio_finite === null ? "\u2014" : role.median_ratio_finite.toFixed(2)}`
1495
+ );
1496
+ lines.push(` attribution: ${role.attribution}`);
1497
+ }
1498
+ lines.push(
1499
+ ` projection-mandatory signal (ratio > ${r.dispatch_floor.thresholds.projection_mandatory_ratio}): ${r.dispatch_floor.projection_mandatory_signal === null ? "no data" : String(r.dispatch_floor.projection_mandatory_signal)}`
1500
+ );
1501
+ lines.push("");
1502
+ lines.push("rules_efficiency:");
1503
+ lines.push(
1504
+ ` envelopes with pair=${r.rules_efficiency.envelopes_with_pair} \xB7 median quota=${r.rules_efficiency.median_quota === null ? "\u2014" : r.rules_efficiency.median_quota.toFixed(2)} \xB7 low-quota signal (< ${r.rules_efficiency.threshold_low_quota}): ${r.rules_efficiency.low_quota_signal === null ? "no data" : String(r.rules_efficiency.low_quota_signal)}`
1505
+ );
1506
+ lines.push("");
1507
+ lines.push("return_channel:");
1508
+ lines.push(
1509
+ ` lines=${r.return_channel.lines_with_field} \xB7 median chars=${r.return_channel.median_chars === null ? "\u2014" : Math.round(r.return_channel.median_chars)} \xB7 cap-breach signal (> ${r.return_channel.envelope_cap_chars}): ${r.return_channel.cap_breach_signal === null ? "no data" : String(r.return_channel.cap_breach_signal)}`
1510
+ );
1511
+ lines.push("");
1512
+ lines.push("ask_economy:");
1513
+ lines.push(
1514
+ ` ask lines=${r.ask_economy.ask_lines} \xB7 adopted=${r.ask_economy.adopted} \xB7 escalated=${r.ask_economy.escalated} \xB7 escalation-kill signal (> ${r.ask_economy.threshold_escalation_kill}): ${r.ask_economy.escalation_kill_signal === null ? "no data" : String(r.ask_economy.escalation_kill_signal)}`
1515
+ );
1516
+ lines.push("");
1517
+ for (const n of r.notes) lines.push(`note: ${n}`);
1518
+ return lines.join("\n") + "\n";
1519
+ }
1520
+ function main3(argv) {
1521
+ let format = "text";
1522
+ let root = DEFAULT_PROJECTS_ROOT;
1523
+ let auditDir = path9.join(process.cwd(), DEFAULT_AUDIT_DIR);
1524
+ let maxAgeDays = 14;
1525
+ for (let i = 0; i < argv.length; i++) {
1526
+ const a = argv[i];
1527
+ if (a === "--format") format = argv[++i] === "json" ? "json" : "text";
1528
+ else if (a === "--root") root = argv[++i] ?? root;
1529
+ else if (a === "--audit-dir") auditDir = argv[++i] ?? auditDir;
1530
+ else if (a === "--max-age-days") maxAgeDays = Number(argv[++i] ?? maxAgeDays) || maxAgeDays;
1531
+ }
1532
+ let report;
1533
+ try {
1534
+ report = buildReport3({ root, auditDir, maxAgeDays });
1535
+ } catch (err) {
1536
+ process.stderr.write(`dispatch_economy_report: ${err instanceof Error ? err.message : String(err)}
1537
+ `);
1538
+ return 2;
1539
+ }
1540
+ process.stdout.write(format === "json" ? JSON.stringify(report, null, 2) + "\n" : renderText3(report));
1541
+ return 0;
1542
+ }
1543
+ function _isCliEntry() {
1544
+ if (true) return false;
1545
+ if (process.argv[1] === void 0) return false;
1546
+ const argvUrl = pathToFileURL3(path9.resolve(process.argv[1])).href;
1547
+ if (import.meta.url === argvUrl) return true;
1548
+ try {
1549
+ return fs6.realpathSync(fileURLToPath4(import.meta.url)) === fs6.realpathSync(path9.resolve(process.argv[1]));
1550
+ } catch {
1551
+ return false;
1552
+ }
1553
+ }
1554
+ if (_isCliEntry()) process.exit(main3(process.argv.slice(2)));
1555
+
115
1556
  // src/scripts/ai_council/clients.ts
116
1557
  var clients_exports = {};
117
1558
  __export(clients_exports, {
@@ -170,27 +1611,36 @@ __export(clients_exports, {
170
1611
  reset_cli_call_counts: () => reset_cli_call_counts
171
1612
  });
172
1613
  import { spawnSync } from "node:child_process";
173
- import * as fs3 from "node:fs";
174
- import * as path3 from "node:path";
1614
+ import * as fs8 from "node:fs";
1615
+ import * as path11 from "node:path";
175
1616
 
176
1617
  // src/scripts/_lib/session_role.ts
177
1618
  var SESSION_ROLE_ENV = "AGENT_CONFIG_SESSION_ROLE";
178
1619
 
179
1620
  // src/scripts/ai_council/events_log.ts
180
1621
  import * as crypto from "node:crypto";
181
- import * as fs2 from "node:fs";
182
- import * as path2 from "node:path";
183
- import { fileURLToPath } from "node:url";
184
- var SCHEMA_VERSION = 1;
1622
+ import * as fs7 from "node:fs";
1623
+ import * as path10 from "node:path";
1624
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
1625
+
1626
+ // src/scripts/_lib/env_kill_switch.ts
1627
+ var _OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "False"]);
1628
+ function isEnvKillSwitchActive(name) {
1629
+ return !_OFF_VALUES.has(process.env[name] ?? "");
1630
+ }
1631
+
1632
+ // src/scripts/ai_council/events_log.ts
1633
+ var SCHEMA_VERSION = 2;
185
1634
  var _VALID_ACTIONS = /* @__PURE__ */ new Set([
186
1635
  "proceed",
187
1636
  "skip_necessity",
188
- "block_quota"
1637
+ "block_quota",
1638
+ "quorum_result"
189
1639
  ]);
190
1640
  var _KILL_SWITCH_ENV = "AGENT_CONFIG_NO_EVENTS_LOG";
191
- var _HERE = fileURLToPath(import.meta.url);
192
- var _REPO_ROOT = path2.resolve(path2.dirname(_HERE), "..", "..", "..");
193
- var _DEFAULT_LOG_PATH = path2.join(
1641
+ var _HERE5 = fileURLToPath5(import.meta.url);
1642
+ var _REPO_ROOT = path10.resolve(path10.dirname(_HERE5), "..", "..", "..");
1643
+ var _DEFAULT_LOG_PATH = path10.join(
194
1644
  _REPO_ROOT,
195
1645
  "agents",
196
1646
  "runtime",
@@ -248,8 +1698,7 @@ function _utf8Bytes(cp) {
248
1698
  );
249
1699
  }
250
1700
  function _kill_switch_active() {
251
- const value = process.env[_KILL_SWITCH_ENV] ?? "";
252
- return !(value === "" || value === "0" || value === "false" || value === "False");
1701
+ return isEnvKillSwitchActive(_KILL_SWITCH_ENV);
253
1702
  }
254
1703
  function appendEvent(event, opts = {}) {
255
1704
  if (_kill_switch_active()) {
@@ -291,9 +1740,9 @@ function appendEvent(event, opts = {}) {
291
1740
  }
292
1741
  }
293
1742
  const target = opts.logPath != null ? opts.logPath : _DEFAULT_LOG_PATH;
294
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
1743
+ fs7.mkdirSync(path10.dirname(target), { recursive: true });
295
1744
  const line = _pyJsonDumpsCompact(record);
296
- fs2.appendFileSync(target, line + "\n", { encoding: "utf-8" });
1745
+ fs7.appendFileSync(target, line + "\n", { encoding: "utf-8" });
297
1746
  return true;
298
1747
  }
299
1748
  function _isoSecondsZ(d) {
@@ -453,9 +1902,21 @@ function assertCacheBreakpointOrder(ttls) {
453
1902
  }
454
1903
  }
455
1904
  }
1905
+ function _servedModel(response, field = "model") {
1906
+ const value = _getattr(response, field, "");
1907
+ return typeof value === "string" ? value : "";
1908
+ }
456
1909
  var CouncilResponse = class {
457
1910
  provider;
458
1911
  model;
1912
+ // The model id the provider reported serving, when it reports one. NEVER
1913
+ // overwrites `model`: that is the REQUESTED id, and it is what the tier
1914
+ // decision was made against — keeping both is what makes a silent alias or
1915
+ // provider substitution detectable at all. Attribution-only; no consumer
1916
+ // may route on it. Defaults to '' (the honest value for a transport that
1917
+ // reports no served id, e.g. every CLI client) so existing callers and the
1918
+ // persisted response JSON stay backward-compatible.
1919
+ model_served;
459
1920
  text;
460
1921
  input_tokens;
461
1922
  output_tokens;
@@ -471,6 +1932,7 @@ var CouncilResponse = class {
471
1932
  constructor(opts) {
472
1933
  this.provider = opts.provider;
473
1934
  this.model = opts.model;
1935
+ this.model_served = opts.model_served ?? "";
474
1936
  this.text = opts.text;
475
1937
  this.input_tokens = opts.input_tokens ?? 0;
476
1938
  this.output_tokens = opts.output_tokens ?? 0;
@@ -496,13 +1958,13 @@ function _setMonotonicSource(fn) {
496
1958
  return prev;
497
1959
  }
498
1960
  function _loadKey(p, prefix, installScript) {
499
- if (!fs3.existsSync(p)) {
1961
+ if (!fs8.existsSync(p)) {
500
1962
  throw new KeyGateError(
501
1963
  `Key not found at ${p}.
502
1964
  Install it with: bash ${installScript}`
503
1965
  );
504
1966
  }
505
- const st = fs3.statSync(p);
1967
+ const st = fs8.statSync(p);
506
1968
  const mode = st.mode & 511;
507
1969
  if (mode !== 384) {
508
1970
  throw new KeyGateError(
@@ -510,7 +1972,7 @@ function _loadKey(p, prefix, installScript) {
510
1972
  Fix: chmod 600 ${p}`
511
1973
  );
512
1974
  }
513
- const key = fs3.readFileSync(p, { encoding: "utf-8" }).trim();
1975
+ const key = fs8.readFileSync(p, { encoding: "utf-8" }).trim();
514
1976
  if (!key) {
515
1977
  throw new KeyGateError(`${p} is empty.`);
516
1978
  }
@@ -717,6 +2179,7 @@ var AnthropicClient = class extends ExternalAIClient {
717
2179
  return new CouncilResponse({
718
2180
  provider: this.name,
719
2181
  model: this.model,
2182
+ model_served: _servedModel(response),
720
2183
  text,
721
2184
  input_tokens: usage ? _getattr(usage, "input_tokens", 0) : 0,
722
2185
  output_tokens: usage ? _getattr(usage, "output_tokens", 0) : 0,
@@ -804,6 +2267,7 @@ ${user_prompt}` }
804
2267
  return new CouncilResponse({
805
2268
  provider: this.name,
806
2269
  model: this.model,
2270
+ model_served: _servedModel(response),
807
2271
  text: text || "",
808
2272
  input_tokens: usage ? _getattr(usage, "prompt_tokens", 0) : 0,
809
2273
  output_tokens: usage ? _getattr(usage, "completion_tokens", 0) : 0,
@@ -864,6 +2328,8 @@ ${user_prompt}`;
864
2328
  return new CouncilResponse({
865
2329
  provider: this.name,
866
2330
  model: this.model,
2331
+ // Gemini names it `model_version`, not `model`.
2332
+ model_served: _servedModel(response, "model_version"),
867
2333
  text,
868
2334
  input_tokens: usage ? _getattr(usage, "prompt_token_count", 0) : 0,
869
2335
  output_tokens: usage ? _getattr(usage, "candidates_token_count", 0) : 0,
@@ -929,6 +2395,7 @@ var _OpenAICompatibleClient = class extends ExternalAIClient {
929
2395
  return new CouncilResponse({
930
2396
  provider: this.name,
931
2397
  model: this.model,
2398
+ model_served: _servedModel(response),
932
2399
  text: text || "",
933
2400
  input_tokens: usage ? _getattr(usage, "prompt_tokens", 0) : 0,
934
2401
  output_tokens: usage ? _getattr(usage, "completion_tokens", 0) : 0,
@@ -968,12 +2435,12 @@ function _today_utc_iso() {
968
2435
  }
969
2436
  function load_cli_call_counts(p = null) {
970
2437
  const target = p !== null ? p : _cliCallsStatePath();
971
- if (!fs3.existsSync(target)) {
2438
+ if (!fs8.existsSync(target)) {
972
2439
  return {};
973
2440
  }
974
2441
  let data;
975
2442
  try {
976
- data = JSON.parse(fs3.readFileSync(target, { encoding: "utf-8" }));
2443
+ data = JSON.parse(fs8.readFileSync(target, { encoding: "utf-8" }));
977
2444
  } catch {
978
2445
  return {};
979
2446
  }
@@ -1000,8 +2467,8 @@ function record_cli_call(provider, p = null) {
1000
2467
  const target = p !== null ? p : _cliCallsStatePath();
1001
2468
  const counts = load_cli_call_counts(target);
1002
2469
  counts[provider] = (counts[provider] ?? 0) + 1;
1003
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
1004
- fs3.writeFileSync(
2470
+ fs8.mkdirSync(path11.dirname(target), { recursive: true });
2471
+ fs8.writeFileSync(
1005
2472
  target,
1006
2473
  _jsonDumpsIndent2({ date: _today_utc_iso(), counts }),
1007
2474
  { encoding: "utf-8" }
@@ -1016,8 +2483,8 @@ function reset_cli_call_counts(provider = null, p = null) {
1016
2483
  } else {
1017
2484
  delete counts[provider];
1018
2485
  }
1019
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
1020
- fs3.writeFileSync(
2486
+ fs8.mkdirSync(path11.dirname(target), { recursive: true });
2487
+ fs8.writeFileSync(
1021
2488
  target,
1022
2489
  _jsonDumpsIndent2({ date: _today_utc_iso(), counts }),
1023
2490
  { encoding: "utf-8" }
@@ -2085,7 +3552,7 @@ function _pyJsonStringAscii(s) {
2085
3552
  return out + '"';
2086
3553
  }
2087
3554
  function _which(name) {
2088
- if (name.includes(path3.sep) || path3.sep !== "/" && name.includes("/")) {
3555
+ if (name.includes(path11.sep) || path11.sep !== "/" && name.includes("/")) {
2089
3556
  return _isExecutable(name) ? name : null;
2090
3557
  }
2091
3558
  const pathEnv = process.env.PATH ?? "";
@@ -2093,12 +3560,12 @@ function _which(name) {
2093
3560
  return null;
2094
3561
  }
2095
3562
  const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
2096
- for (const dir of pathEnv.split(path3.delimiter)) {
3563
+ for (const dir of pathEnv.split(path11.delimiter)) {
2097
3564
  if (!dir) {
2098
3565
  continue;
2099
3566
  }
2100
3567
  for (const ext of exts) {
2101
- const candidate = path3.join(dir, name + ext);
3568
+ const candidate = path11.join(dir, name + ext);
2102
3569
  if (_isExecutable(candidate)) {
2103
3570
  return candidate;
2104
3571
  }
@@ -2108,7 +3575,7 @@ function _which(name) {
2108
3575
  }
2109
3576
  function _isExecutable(p) {
2110
3577
  try {
2111
- const st = fs3.statSync(p);
3578
+ const st = fs8.statSync(p);
2112
3579
  if (!st.isFile()) {
2113
3580
  return false;
2114
3581
  }
@@ -2135,7 +3602,7 @@ function _defaultStdin() {
2135
3602
  function ensure() {
2136
3603
  if (buffer === null) {
2137
3604
  try {
2138
- buffer = fs3.readFileSync(0, { encoding: "utf-8" });
3605
+ buffer = fs8.readFileSync(0, { encoding: "utf-8" });
2139
3606
  } catch {
2140
3607
  buffer = "";
2141
3608
  }
@@ -2177,14 +3644,14 @@ function _defaultStdin() {
2177
3644
 
2178
3645
  // src/scripts/_lib/environment_detector.ts
2179
3646
  import { spawnSync as spawnSync2 } from "node:child_process";
2180
- import * as fs4 from "node:fs";
3647
+ import * as fs9 from "node:fs";
2181
3648
  import * as os from "node:os";
2182
- import * as path4 from "node:path";
3649
+ import * as path12 from "node:path";
2183
3650
 
2184
3651
  // src/install/toolDetection.ts
2185
- import { existsSync as existsSync3 } from "node:fs";
2186
- import { homedir } from "node:os";
2187
- import { delimiter as delimiter2, join as join4 } from "node:path";
3652
+ import { existsSync as existsSync7 } from "node:fs";
3653
+ import { homedir as homedir3 } from "node:os";
3654
+ import { delimiter as delimiter2, join as join12 } from "node:path";
2188
3655
  var TOOL_SIGNALS = {
2189
3656
  "claude-code": { bins: ["claude"], homePaths: [".claude", ".claude.json", ".config/claude"] },
2190
3657
  "claude-desktop": { absPaths: ["/Applications/Claude.app"], homePaths: ["Library/Application Support/Claude", ".config/Claude"] },
@@ -2229,8 +3696,8 @@ function resolveBinaryPath(name, pathEnv) {
2229
3696
  for (const dir of pathEnv.split(delimiter2)) {
2230
3697
  if (dir.length === 0) continue;
2231
3698
  for (const candidate of [name, `${name}.exe`, `${name}.cmd`]) {
2232
- const full = join4(dir, candidate);
2233
- if (existsSync3(full)) return full;
3699
+ const full = join12(dir, candidate);
3700
+ if (existsSync7(full)) return full;
2234
3701
  }
2235
3702
  }
2236
3703
  return null;
@@ -2240,10 +3707,10 @@ function binOnPath(name, pathEnv) {
2240
3707
  }
2241
3708
  function isToolInstalled(signal, home, pathEnv) {
2242
3709
  for (const rel of signal.homePaths ?? []) {
2243
- if (existsSync3(join4(home, rel))) return true;
3710
+ if (existsSync7(join12(home, rel))) return true;
2244
3711
  }
2245
3712
  for (const abs of signal.absPaths ?? []) {
2246
- if (existsSync3(abs)) return true;
3713
+ if (existsSync7(abs)) return true;
2247
3714
  }
2248
3715
  for (const bin of signal.bins ?? []) {
2249
3716
  if (binOnPath(bin, pathEnv)) return true;
@@ -2251,7 +3718,7 @@ function isToolInstalled(signal, home, pathEnv) {
2251
3718
  return false;
2252
3719
  }
2253
3720
  function detectInstalledTools(opts = {}) {
2254
- const home = opts.home ?? homedir();
3721
+ const home = opts.home ?? homedir3();
2255
3722
  const pathEnv = opts.pathEnv ?? process.env["PATH"] ?? "";
2256
3723
  const out = {};
2257
3724
  for (const [id, signal] of Object.entries(TOOL_SIGNALS)) {
@@ -2302,7 +3769,7 @@ function classifyBilling(provider, source) {
2302
3769
  function codexHome(env) {
2303
3770
  const map = env ?? process.env;
2304
3771
  const override = (map["CODEX_HOME"] ?? "").trim();
2305
- return override !== "" ? override : path4.join(homeOf(env), ".codex");
3772
+ return override !== "" ? override : path12.join(homeOf(env), ".codex");
2306
3773
  }
2307
3774
  function homeOf(env) {
2308
3775
  const map = env ?? process.env;
@@ -2327,14 +3794,14 @@ ${res.stderr ?? ""}`;
2327
3794
  }
2328
3795
  function isFile(p) {
2329
3796
  try {
2330
- return fs4.statSync(p).isFile();
3797
+ return fs9.statSync(p).isFile();
2331
3798
  } catch {
2332
3799
  return false;
2333
3800
  }
2334
3801
  }
2335
3802
  function exists(p) {
2336
3803
  try {
2337
- return fs4.existsSync(p);
3804
+ return fs9.existsSync(p);
2338
3805
  } catch {
2339
3806
  return false;
2340
3807
  }
@@ -2342,7 +3809,7 @@ function exists(p) {
2342
3809
  function classifyCodexAuth(authPath) {
2343
3810
  let data;
2344
3811
  try {
2345
- data = JSON.parse(fs4.readFileSync(authPath, "utf-8"));
3812
+ data = JSON.parse(fs9.readFileSync(authPath, "utf-8"));
2346
3813
  } catch {
2347
3814
  return "cli-api-key";
2348
3815
  }
@@ -2359,18 +3826,18 @@ function cliSubscriptionEvidence(provider, home, env, claudeConfigDir) {
2359
3826
  if (provider === "anthropic") {
2360
3827
  const configDir = claudeConfigDir;
2361
3828
  for (const rel of [".credentials.json", "credentials.json"]) {
2362
- const p = path4.join(configDir, rel);
3829
+ const p = path12.join(configDir, rel);
2363
3830
  if (isFile(p)) return { source: "cli-subscription", evidence: p };
2364
3831
  }
2365
3832
  return null;
2366
3833
  }
2367
3834
  if (provider === "openai") {
2368
- const p = path4.join(codexHome(env), "auth.json");
3835
+ const p = path12.join(codexHome(env), "auth.json");
2369
3836
  if (isFile(p)) return { source: classifyCodexAuth(p), evidence: p };
2370
3837
  return null;
2371
3838
  }
2372
3839
  if (provider === "gemini") {
2373
- const p = path4.join(home, ".gemini", "oauth_creds.json");
3840
+ const p = path12.join(home, ".gemini", "oauth_creds.json");
2374
3841
  if (isFile(p)) return { source: "cli-subscription", evidence: p };
2375
3842
  return null;
2376
3843
  }
@@ -2402,7 +3869,7 @@ function detectHosts(opts) {
2402
3869
  function detectAuth(opts) {
2403
3870
  const env = opts.env ?? process.env;
2404
3871
  const home = opts.home ?? homeOf(opts.env);
2405
- const claudeConfigDir = opts.home === void 0 && opts.env === void 0 ? claude_config_dir() : (env["CLAUDE_CONFIG_DIR"] ?? "").trim() || path4.join(home, ".claude");
3872
+ const claudeConfigDir = opts.home === void 0 && opts.env === void 0 ? claude_config_dir() : (env["CLAUDE_CONFIG_DIR"] ?? "").trim() || path12.join(home, ".claude");
2406
3873
  const auth = [];
2407
3874
  const keys = [];
2408
3875
  for (const provider of knownProviders()) {
@@ -2456,7 +3923,7 @@ function detectEnvironment(opts = {}) {
2456
3923
  }
2457
3924
 
2458
3925
  // src/scripts/_cli/detection_report.ts
2459
- import * as path5 from "node:path";
3926
+ import * as path13 from "node:path";
2460
3927
 
2461
3928
  // src/scripts/ai_council/transport_resolver.ts
2462
3929
  var VALID_TRANSPORT_MODES = /* @__PURE__ */ new Set([
@@ -2658,7 +4125,7 @@ function cliBinaryPresent(environment, provider, binaryOverride) {
2658
4125
  const expected = PROVIDER_CLI_META[provider]?.[0];
2659
4126
  if (expected === void 0) return false;
2660
4127
  return environment.hosts.some(
2661
- (h) => h.binary !== null && stripExe(path5.basename(h.binary)) === expected
4128
+ (h) => h.binary !== null && stripExe(path13.basename(h.binary)) === expected
2662
4129
  );
2663
4130
  }
2664
4131
  function stripExe(name) {
@@ -2819,9 +4286,9 @@ function absentCouncilFacts(configPath) {
2819
4286
 
2820
4287
  // src/scripts/ai_team/review_gate.ts
2821
4288
  import * as crypto2 from "node:crypto";
2822
- import * as fs5 from "node:fs";
4289
+ import * as fs10 from "node:fs";
2823
4290
  import * as os2 from "node:os";
2824
- import * as path6 from "node:path";
4291
+ import * as path14 from "node:path";
2825
4292
 
2826
4293
  // src/scripts/ai_team/config.ts
2827
4294
  var AI_TEAM_REVIEW_GATE_DEFAULTS = Object.freeze({
@@ -2837,16 +4304,16 @@ var AI_TEAM_DEFAULTS = Object.freeze({
2837
4304
  });
2838
4305
 
2839
4306
  // src/scripts/ai_team/review_gate.ts
2840
- var GATE_LEDGER_RELPATH = path6.join("agents", "runtime", "team", "events.log");
4307
+ var GATE_LEDGER_RELPATH = path14.join("agents", "runtime", "team", "events.log");
2841
4308
  var _CODEX_PLUGIN_DATA_DIRNAME = `${CODEX_PLUGIN_ID}-${CODEX_MARKETPLACE_NAME}`;
2842
4309
  function _workspace_state_segment(workspace_root) {
2843
4310
  let canonical = workspace_root;
2844
4311
  try {
2845
- canonical = fs5.realpathSync.native(workspace_root);
4312
+ canonical = fs10.realpathSync.native(workspace_root);
2846
4313
  } catch {
2847
4314
  canonical = workspace_root;
2848
4315
  }
2849
- const slug_source = path6.basename(workspace_root) || "workspace";
4316
+ const slug_source = path14.basename(workspace_root) || "workspace";
2850
4317
  const slug = slug_source.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "workspace";
2851
4318
  const hash = crypto2.createHash("sha256").update(canonical).digest("hex").slice(0, 16);
2852
4319
  return `${slug}-${hash}`;
@@ -2856,19 +4323,19 @@ function upstream_state_dir_candidates(workspace_root) {
2856
4323
  const candidates = [];
2857
4324
  const env = (process.env["CLAUDE_PLUGIN_DATA"] ?? "").trim();
2858
4325
  if (env !== "") {
2859
- candidates.push(path6.join(env, "state", segment));
4326
+ candidates.push(path14.join(env, "state", segment));
2860
4327
  }
2861
4328
  candidates.push(
2862
- path6.join(claude_config_dir(), "plugins", "data", _CODEX_PLUGIN_DATA_DIRNAME, "state", segment)
4329
+ path14.join(claude_config_dir(), "plugins", "data", _CODEX_PLUGIN_DATA_DIRNAME, "state", segment)
2863
4330
  );
2864
- candidates.push(path6.join(os2.tmpdir(), "codex-companion", segment));
4331
+ candidates.push(path14.join(os2.tmpdir(), "codex-companion", segment));
2865
4332
  return candidates;
2866
4333
  }
2867
4334
  function upstream_gate_enabled(workspace_root) {
2868
4335
  for (const dir of upstream_state_dir_candidates(workspace_root)) {
2869
4336
  let parsed;
2870
4337
  try {
2871
- parsed = JSON.parse(fs5.readFileSync(path6.join(dir, "state.json"), "utf-8"));
4338
+ parsed = JSON.parse(fs10.readFileSync(path14.join(dir, "state.json"), "utf-8"));
2872
4339
  } catch {
2873
4340
  continue;
2874
4341
  }
@@ -2917,7 +4384,7 @@ function review_gate_doctor_signal(project_root, gate_raw) {
2917
4384
  }
2918
4385
 
2919
4386
  // src/scripts/_cli/cmd_doctor.ts
2920
- var _HERE2 = fileURLToPath2(import.meta.url);
4387
+ var _HERE6 = fileURLToPath6(import.meta.url);
2921
4388
  var ArgparseExit = class extends Error {
2922
4389
  constructor(code) {
2923
4390
  super(`argparse-exit-${code}`);
@@ -2928,13 +4395,13 @@ var ArgparseExit = class extends Error {
2928
4395
  function expanduser(p) {
2929
4396
  if (p === "~") return os3.homedir();
2930
4397
  if (p.startsWith("~/") || p.startsWith("~\\")) {
2931
- return path7.join(os3.homedir(), p.slice(2));
4398
+ return path15.join(os3.homedir(), p.slice(2));
2932
4399
  }
2933
4400
  return p;
2934
4401
  }
2935
4402
  function pathExists(p) {
2936
4403
  try {
2937
- fs6.statSync(p);
4404
+ fs11.statSync(p);
2938
4405
  return true;
2939
4406
  } catch {
2940
4407
  return false;
@@ -2942,27 +4409,27 @@ function pathExists(p) {
2942
4409
  }
2943
4410
  function isFile2(p) {
2944
4411
  try {
2945
- return fs6.statSync(p).isFile();
4412
+ return fs11.statSync(p).isFile();
2946
4413
  } catch {
2947
4414
  return false;
2948
4415
  }
2949
4416
  }
2950
4417
  function isDir(p) {
2951
4418
  try {
2952
- return fs6.statSync(p).isDirectory();
4419
+ return fs11.statSync(p).isDirectory();
2953
4420
  } catch {
2954
4421
  return false;
2955
4422
  }
2956
4423
  }
2957
4424
  function resolvePath(p) {
2958
4425
  try {
2959
- return fs6.realpathSync(path7.resolve(p));
4426
+ return fs11.realpathSync(path15.resolve(p));
2960
4427
  } catch {
2961
- return path7.resolve(p);
4428
+ return path15.resolve(p);
2962
4429
  }
2963
4430
  }
2964
4431
  function readText(p) {
2965
- return fs6.readFileSync(p, "utf-8");
4432
+ return fs11.readFileSync(p, "utf-8");
2966
4433
  }
2967
4434
  function _jsonStrAscii(s) {
2968
4435
  let out = '"';
@@ -3050,11 +4517,11 @@ function _jsonDumpsIndentAscii(value, indent) {
3050
4517
  return _dumpIndentAscii(value, indent, 0);
3051
4518
  }
3052
4519
  function yamlSafeLoad(text) {
3053
- if (YAML === void 0 || YAML === null) {
4520
+ if (YAML2 === void 0 || YAML2 === null) {
3054
4521
  return null;
3055
4522
  }
3056
4523
  try {
3057
- return YAML.parse(text, { version: "1.1" });
4524
+ return YAML2.parse(text, { version: "1.1" });
3058
4525
  } catch {
3059
4526
  return void 0;
3060
4527
  }
@@ -3073,7 +4540,7 @@ function _resolve_project_root(arg) {
3073
4540
  }
3074
4541
  var _INSTALL_MODE_MARKER_REL = "agents/.agent-state/install-mode.txt";
3075
4542
  function _detect_install_mode(project_root) {
3076
- const marker = path7.join(project_root, _INSTALL_MODE_MARKER_REL);
4543
+ const marker = path15.join(project_root, _INSTALL_MODE_MARKER_REL);
3077
4544
  if (isFile2(marker)) {
3078
4545
  let value;
3079
4546
  try {
@@ -3085,9 +4552,9 @@ function _detect_install_mode(project_root) {
3085
4552
  return [value, "marker-file"];
3086
4553
  }
3087
4554
  }
3088
- const has_agents_md = pathExists(path7.join(project_root, "AGENTS.md"));
4555
+ const has_agents_md = pathExists(path15.join(project_root, "AGENTS.md"));
3089
4556
  const has_copilot = pathExists(
3090
- path7.join(project_root, ".github", "copilot-instructions.md")
4557
+ path15.join(project_root, ".github", "copilot-instructions.md")
3091
4558
  );
3092
4559
  if (has_agents_md && has_copilot) {
3093
4560
  return ["full", "heuristic"];
@@ -3107,7 +4574,7 @@ function _settings_layer_chain(project_root) {
3107
4574
  return layers;
3108
4575
  }
3109
4576
  function _detect_wrapper(project_root) {
3110
- const wrapper = path7.join(project_root, "agent-config");
4577
+ const wrapper = path15.join(project_root, "agent-config");
3111
4578
  if (!pathExists(wrapper)) {
3112
4579
  return { path: String(wrapper), exists: false, embedded_root: null };
3113
4580
  }
@@ -3174,14 +4641,14 @@ function _emit_context_text(ctx) {
3174
4641
  }
3175
4642
  function _resolve_path(project_root, raw) {
3176
4643
  let p = expanduser(raw);
3177
- if (!path7.isAbsolute(p)) {
3178
- p = path7.join(project_root, p);
4644
+ if (!path15.isAbsolute(p)) {
4645
+ p = path15.join(project_root, p);
3179
4646
  }
3180
4647
  return p;
3181
4648
  }
3182
4649
  function _sha256(p) {
3183
4650
  try {
3184
- const data = fs6.readFileSync(p);
4651
+ const data = fs11.readFileSync(p);
3185
4652
  return crypto3.createHash("sha256").update(data).digest("hex");
3186
4653
  } catch {
3187
4654
  return null;
@@ -3190,7 +4657,7 @@ function _sha256(p) {
3190
4657
  var PACKAGE_TAG_ID = "event4u/agent-config";
3191
4658
  var _FRONTMATTER_PACKAGE_RE = /^package:\s*(.+?)\s*$/m;
3192
4659
  function _read_inline_package_tag(p) {
3193
- if (path7.extname(p) !== ".md") {
4660
+ if (path15.extname(p) !== ".md") {
3194
4661
  return NO_FRONTMATTER;
3195
4662
  }
3196
4663
  let text;
@@ -3319,13 +4786,13 @@ function rglob(root) {
3319
4786
  const walk = (dir) => {
3320
4787
  let entries;
3321
4788
  try {
3322
- entries = fs6.readdirSync(dir, { withFileTypes: true });
4789
+ entries = fs11.readdirSync(dir, { withFileTypes: true });
3323
4790
  } catch {
3324
4791
  return;
3325
4792
  }
3326
4793
  entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3327
4794
  for (const ent of entries) {
3328
- const full = path7.join(dir, ent.name);
4795
+ const full = path15.join(dir, ent.name);
3329
4796
  out.push(full);
3330
4797
  let dirLike = ent.isDirectory();
3331
4798
  if (ent.isSymbolicLink()) {
@@ -3400,9 +4867,9 @@ function _foreign_records(project_root, foreign) {
3400
4867
  return out;
3401
4868
  }
3402
4869
  function relativeTo(p, base) {
3403
- const rel = path7.relative(base, p);
4870
+ const rel = path15.relative(base, p);
3404
4871
  if (rel === "") return rel;
3405
- if (rel.startsWith("..") || path7.isAbsolute(rel)) {
4872
+ if (rel.startsWith("..") || path15.isAbsolute(rel)) {
3406
4873
  return null;
3407
4874
  }
3408
4875
  return rel;
@@ -3466,7 +4933,7 @@ var MANIFEST_REQUIRED_CHECK_IDS = /* @__PURE__ */ new Set([
3466
4933
  ]);
3467
4934
  var INSTALL_MODE_MARKER_RELATIVE = "agents/.agent-state/install-mode.txt";
3468
4935
  function _is_global_only_consumer(project_root) {
3469
- return isFile2(path7.join(project_root, INSTALL_MODE_MARKER_RELATIVE)) || isDir(path7.join(project_root, "agents", "overrides"));
4936
+ return isFile2(path15.join(project_root, INSTALL_MODE_MARKER_RELATIVE)) || isDir(path15.join(project_root, "agents", "overrides"));
3470
4937
  }
3471
4938
  var REPAIR_IDS = ["wizard-state"];
3472
4939
  var MCP_BETA_GATES = [
@@ -3486,7 +4953,7 @@ var STATUS_SYMBOLS = {
3486
4953
  var MIN_PYTHON = [3, 10];
3487
4954
  function _check_scope(project_root) {
3488
4955
  for (const marker of ["pnpm-workspace.yaml", "lerna.json"]) {
3489
- if (pathExists(path7.join(project_root, marker))) {
4956
+ if (pathExists(path15.join(project_root, marker))) {
3490
4957
  return {
3491
4958
  id: "scope",
3492
4959
  status: "warn",
@@ -3495,7 +4962,7 @@ function _check_scope(project_root) {
3495
4962
  };
3496
4963
  }
3497
4964
  }
3498
- const pkg = path7.join(project_root, "package.json");
4965
+ const pkg = path15.join(project_root, "package.json");
3499
4966
  if (pathExists(pkg)) {
3500
4967
  try {
3501
4968
  const data = JSON.parse(readText(pkg));
@@ -3521,7 +4988,7 @@ var _PLACEHOLDER_EMAIL_RE = /^(t@t\.t|.*@example\.(com|org)|.*@localhost)$/i;
3521
4988
  var _PLACEHOLDER_NAME_RE = /^(t|test|user|nobody|x)$/i;
3522
4989
  function _git_config_path(project_root) {
3523
4990
  const common = git_common_dir(project_root);
3524
- return common === null ? null : path7.join(common, "config");
4991
+ return common === null ? null : path15.join(common, "config");
3525
4992
  }
3526
4993
  function _parse_git_user(configText) {
3527
4994
  let inUser = false;
@@ -3551,7 +5018,7 @@ function _check_git_identity(project_root) {
3551
5018
  }
3552
5019
  let ident = _parse_git_user(readText(cfgPath));
3553
5020
  if (ident.name === null && ident.email === null) {
3554
- const globalCfg = path7.join(os3.homedir(), ".gitconfig");
5021
+ const globalCfg = path15.join(os3.homedir(), ".gitconfig");
3555
5022
  if (pathExists(globalCfg)) {
3556
5023
  ident = _parse_git_user(readText(globalCfg));
3557
5024
  }
@@ -3612,7 +5079,7 @@ function _package_root() {
3612
5079
  }
3613
5080
  function _current_package_version() {
3614
5081
  try {
3615
- const data = JSON.parse(readText(path7.join(_package_root(), "package.json")));
5082
+ const data = JSON.parse(readText(path15.join(_package_root(), "package.json")));
3616
5083
  const v = data["version"];
3617
5084
  if (typeof v === "string" && v.trim()) {
3618
5085
  return v.trim();
@@ -3656,7 +5123,7 @@ function _check_lockfile_freshness(manifest) {
3656
5123
  };
3657
5124
  }
3658
5125
  function shutilWhich(name) {
3659
- if (path7.dirname(name) !== "." && (name.includes("/") || name.includes("\\"))) {
5126
+ if (path15.dirname(name) !== "." && (name.includes("/") || name.includes("\\"))) {
3660
5127
  return isExecutableFile(name) ? name : null;
3661
5128
  }
3662
5129
  const pathEnv = process2.env["PATH"] || "";
@@ -3669,12 +5136,12 @@ function shutilWhich(name) {
3669
5136
  if (seenDirs.has(d)) continue;
3670
5137
  seenDirs.add(d);
3671
5138
  for (const ext of exts) {
3672
- const candidate = path7.join(d, name + (ext === "" ? "" : ext.toLowerCase() === ext ? ext : ext));
5139
+ const candidate = path15.join(d, name + (ext === "" ? "" : ext.toLowerCase() === ext ? ext : ext));
3673
5140
  if (isExecutableFile(candidate)) {
3674
5141
  return candidate;
3675
5142
  }
3676
5143
  if (ext !== "") {
3677
- const upper = path7.join(d, name + ext);
5144
+ const upper = path15.join(d, name + ext);
3678
5145
  if (isExecutableFile(upper)) return upper;
3679
5146
  }
3680
5147
  }
@@ -3683,10 +5150,10 @@ function shutilWhich(name) {
3683
5150
  }
3684
5151
  function isExecutableFile(p) {
3685
5152
  try {
3686
- const st = fs6.statSync(p);
5153
+ const st = fs11.statSync(p);
3687
5154
  if (!st.isFile()) return false;
3688
5155
  if (process2.platform === "win32") return true;
3689
- fs6.accessSync(p, fs6.constants.X_OK);
5156
+ fs11.accessSync(p, fs11.constants.X_OK);
3690
5157
  return true;
3691
5158
  } catch {
3692
5159
  return false;
@@ -3750,7 +5217,7 @@ function _check_claude_plugin() {
3750
5217
  remedy: ""
3751
5218
  };
3752
5219
  }
3753
- const projection = path7.join(os3.homedir(), ".claude", "skills");
5220
+ const projection = path15.join(os3.homedir(), ".claude", "skills");
3754
5221
  const projection_present = isDir(projection);
3755
5222
  if (projection_present) {
3756
5223
  return {
@@ -3787,8 +5254,8 @@ function _check_claude_command_wrappers() {
3787
5254
  remedy: ""
3788
5255
  };
3789
5256
  }
3790
- const anchor = path7.join(os3.homedir(), ".claude");
3791
- const commands_dir = path7.join(anchor, "commands");
5257
+ const anchor = path15.join(os3.homedir(), ".claude");
5258
+ const commands_dir = path15.join(anchor, "commands");
3792
5259
  if (!isDir(commands_dir)) {
3793
5260
  return {
3794
5261
  id: "claude-command-wrappers",
@@ -3797,8 +5264,8 @@ function _check_claude_command_wrappers() {
3797
5264
  remedy: ""
3798
5265
  };
3799
5266
  }
3800
- const flat_probe = fs6.existsSync(path7.join(commands_dir, "commit.md"));
3801
- const wrapper_probe = fs6.existsSync(path7.join(anchor, "skills", "commit", "SKILL.md"));
5267
+ const flat_probe = fs11.existsSync(path15.join(commands_dir, "commit.md"));
5268
+ const wrapper_probe = fs11.existsSync(path15.join(anchor, "skills", "commit", "SKILL.md"));
3802
5269
  if (wrapper_probe) {
3803
5270
  return {
3804
5271
  id: "claude-command-wrappers",
@@ -3823,7 +5290,7 @@ function _check_claude_command_wrappers() {
3823
5290
  };
3824
5291
  }
3825
5292
  function _check_surface_state() {
3826
- const matrix_path = path7.join(_package_root(), "src", "config", "surface-matrix.yml");
5293
+ const matrix_path = path15.join(_package_root(), "src", "config", "surface-matrix.yml");
3827
5294
  if (!isFile2(matrix_path)) {
3828
5295
  return {
3829
5296
  id: "surface-state",
@@ -3834,7 +5301,7 @@ function _check_surface_state() {
3834
5301
  }
3835
5302
  let tools = {};
3836
5303
  try {
3837
- const raw = YAML.parse(readText(matrix_path), { version: "1.1" });
5304
+ const raw = YAML2.parse(readText(matrix_path), { version: "1.1" });
3838
5305
  const t = raw["tools"];
3839
5306
  if (t && typeof t === "object" && !Array.isArray(t)) {
3840
5307
  tools = t;
@@ -3847,7 +5314,7 @@ function _check_surface_state() {
3847
5314
  remedy: "agent-config upgrade (reinstalls the package data files)"
3848
5315
  };
3849
5316
  }
3850
- const _expand = (p) => p.startsWith("~/") ? path7.join(os3.homedir(), p.slice(2)) : path7.join(_package_root(), p);
5317
+ const _expand = (p) => p.startsWith("~/") ? path15.join(os3.homedir(), p.slice(2)) : path15.join(_package_root(), p);
3851
5318
  const violations = [];
3852
5319
  const remedies = [];
3853
5320
  let checked = 0;
@@ -3889,7 +5356,7 @@ function _check_surface_state() {
3889
5356
  }
3890
5357
  function pathExistsAny(p) {
3891
5358
  try {
3892
- fs6.statSync(p);
5359
+ fs11.statSync(p);
3893
5360
  return true;
3894
5361
  } catch {
3895
5362
  return false;
@@ -3905,13 +5372,13 @@ function _check_hook_wiring() {
3905
5372
  remedy: ""
3906
5373
  };
3907
5374
  }
3908
- const settings_path = path7.join(os3.homedir(), ".claude", "settings.json");
5375
+ const settings_path = path15.join(os3.homedir(), ".claude", "settings.json");
3909
5376
  let missing;
3910
5377
  try {
3911
5378
  const matrix = build_claude_hook_matrix(
3912
- path7.join(_package_root(), "src", "scripts", "hook_manifest.yaml")
5379
+ path15.join(_package_root(), "src", "scripts", "hook_manifest.yaml")
3913
5380
  );
3914
- const settings = pathExists(settings_path) ? JSON.parse(fs6.readFileSync(settings_path, "utf8")) : {};
5381
+ const settings = pathExists(settings_path) ? JSON.parse(fs11.readFileSync(settings_path, "utf8")) : {};
3915
5382
  const hooks = (settings["hooks"] ?? {}) || {};
3916
5383
  missing = Object.keys(matrix).filter((ev) => {
3917
5384
  const groups = hooks[ev];
@@ -3986,7 +5453,7 @@ function _check_mcp_mode(project_root) {
3986
5453
  ];
3987
5454
  const found = [];
3988
5455
  for (const [rel, label] of candidates) {
3989
- const p = path7.join(project_root, rel);
5456
+ const p = path15.join(project_root, rel);
3990
5457
  if (!pathExists(p)) {
3991
5458
  continue;
3992
5459
  }
@@ -4018,7 +5485,7 @@ function _check_mcp_mode(project_root) {
4018
5485
  };
4019
5486
  }
4020
5487
  function _check_offline_readiness() {
4021
- const script = path7.join(_package_root(), "src", "scripts", "hermetic-install.sh");
5488
+ const script = path15.join(_package_root(), "src", "scripts", "hermetic-install.sh");
4022
5489
  if (!pathExists(script)) {
4023
5490
  return {
4024
5491
  id: "offline-readiness",
@@ -4076,7 +5543,7 @@ function _check_stale_orphans() {
4076
5543
  (a, b) => a < b ? -1 : a > b ? 1 : 0
4077
5544
  );
4078
5545
  for (const root_name of ownedSorted) {
4079
- const root = path7.join(anchor, root_name);
5546
+ const root = path15.join(anchor, root_name);
4080
5547
  if (!isDir(root)) {
4081
5548
  continue;
4082
5549
  }
@@ -4091,7 +5558,7 @@ function _check_stale_orphans() {
4091
5558
  if (rel === null) {
4092
5559
  continue;
4093
5560
  }
4094
- const relPosix = rel.split(path7.sep).join("/");
5561
+ const relPosix = rel.split(path15.sep).join("/");
4095
5562
  if (recorded_set.has(relPosix)) {
4096
5563
  continue;
4097
5564
  }
@@ -4146,14 +5613,14 @@ function _check_rule_scope_drift(project_root) {
4146
5613
  let rules_dir = null;
4147
5614
  let found = 0;
4148
5615
  for (const rel of _RULE_PROJECTION_DIRS) {
4149
- const cand = path7.join(project_root, rel);
5616
+ const cand = path15.join(project_root, rel);
4150
5617
  if (!isDir(cand)) {
4151
5618
  continue;
4152
5619
  }
4153
5620
  let count = 0;
4154
5621
  try {
4155
- for (const name of fs6.readdirSync(cand)) {
4156
- if (name.endsWith(".md") && isFile2(path7.join(cand, name))) {
5622
+ for (const name of fs11.readdirSync(cand)) {
5623
+ if (name.endsWith(".md") && isFile2(path15.join(cand, name))) {
4157
5624
  count += 1;
4158
5625
  }
4159
5626
  }
@@ -4207,14 +5674,14 @@ function _check_rule_scope_drift(project_root) {
4207
5674
  };
4208
5675
  }
4209
5676
  function _check_duplicate_scope_rules(project_root, userRulesDirOverride) {
4210
- const user_rules_dir = userRulesDirOverride ?? path7.join(os3.homedir(), ".claude", "rules");
5677
+ const user_rules_dir = userRulesDirOverride ?? path15.join(os3.homedir(), ".claude", "rules");
4211
5678
  let project_rules_dir = null;
4212
5679
  if (_is_source_repo(project_root)) {
4213
- const cand = path7.join(project_root, "dist", "agent-src", "rules");
5680
+ const cand = path15.join(project_root, "dist", "agent-src", "rules");
4214
5681
  if (isDir(cand)) project_rules_dir = cand;
4215
5682
  } else {
4216
5683
  for (const rel of _RULE_PROJECTION_DIRS) {
4217
- const cand = path7.join(project_root, rel);
5684
+ const cand = path15.join(project_root, rel);
4218
5685
  if (isDir(cand)) {
4219
5686
  project_rules_dir = cand;
4220
5687
  break;
@@ -4283,7 +5750,7 @@ function _check_mcp_beta_readiness(project_root) {
4283
5750
  }
4284
5751
  const pending = [];
4285
5752
  for (const [gate_id, rel] of MCP_BETA_GATES) {
4286
- if (!pathExists(path7.join(project_root, rel))) {
5753
+ if (!pathExists(path15.join(project_root, rel))) {
4287
5754
  pending.push(`${gate_id} (${rel})`);
4288
5755
  }
4289
5756
  }
@@ -4304,7 +5771,7 @@ function _check_mcp_beta_readiness(project_root) {
4304
5771
  }
4305
5772
  function _check_tier_usage_readiness(project_root) {
4306
5773
  const settings_file = project_settings_path(project_root);
4307
- let log_path = path7.join(project_root, ".agent-tier-usage.jsonl");
5774
+ let log_path = path15.join(project_root, ".agent-tier-usage.jsonl");
4308
5775
  let enabled = false;
4309
5776
  if (isFile2(settings_file)) {
4310
5777
  let raw;
@@ -4323,7 +5790,7 @@ function _check_tier_usage_readiness(project_root) {
4323
5790
  const outputRaw = tu["output"];
4324
5791
  const output = typeof outputRaw === "object" && outputRaw !== null && !Array.isArray(outputRaw) ? outputRaw : {};
4325
5792
  if (typeof output["path"] === "string" && output["path"].trim()) {
4326
- log_path = path7.join(project_root, output["path"].trim());
5793
+ log_path = path15.join(project_root, output["path"].trim());
4327
5794
  }
4328
5795
  const val = tu["enabled"];
4329
5796
  if (typeof val === "boolean") {
@@ -4348,7 +5815,7 @@ function _check_tier_usage_readiness(project_root) {
4348
5815
  return {
4349
5816
  id: "tier-usage-readiness",
4350
5817
  status: "warn",
4351
- message: `tier-usage telemetry on but ${path7.basename(log_path)} not yet written \u2014 no signal accumulated`,
5818
+ message: `tier-usage telemetry on but ${path15.basename(log_path)} not yet written \u2014 no signal accumulated`,
4352
5819
  remedy: "run any tracked command to seed the log; the dispatcher writes one record per invocation"
4353
5820
  };
4354
5821
  }
@@ -4363,7 +5830,7 @@ function _check_tier_usage_readiness(project_root) {
4363
5830
  return {
4364
5831
  id: "tier-usage-readiness",
4365
5832
  status: "fail",
4366
- message: `cannot read ${path7.basename(log_path)}: ${osErrorStr(exc)}`,
5833
+ message: `cannot read ${path15.basename(log_path)}: ${osErrorStr(exc)}`,
4367
5834
  remedy: "fix permissions on the tier-usage log"
4368
5835
  };
4369
5836
  }
@@ -4394,7 +5861,7 @@ function _check_tier_usage_readiness(project_root) {
4394
5861
  return {
4395
5862
  id: "tier-usage-readiness",
4396
5863
  status: "fail",
4397
- message: `${total} record(s) in ${path7.basename(log_path)} but 0 passed the privacy floor \u2014 report would refuse to render`,
5864
+ message: `${total} record(s) in ${path15.basename(log_path)} but 0 passed the privacy floor \u2014 report would refuse to render`,
4398
5865
  remedy: "inspect the log; the dispatcher is writing records the contract forbids (paths, argv, message bodies)"
4399
5866
  };
4400
5867
  }
@@ -4402,19 +5869,19 @@ function _check_tier_usage_readiness(project_root) {
4402
5869
  return {
4403
5870
  id: "tier-usage-readiness",
4404
5871
  status: "warn",
4405
- message: `${path7.basename(log_path)} present but empty \u2014 no signal yet`,
5872
+ message: `${path15.basename(log_path)} present but empty \u2014 no signal yet`,
4406
5873
  remedy: "run any tracked command to seed the log"
4407
5874
  };
4408
5875
  }
4409
5876
  return {
4410
5877
  id: "tier-usage-readiness",
4411
5878
  status: "ok",
4412
- message: `${valid} record(s) past the privacy floor in ${path7.basename(log_path)} \u2014 retiering signal available`,
5879
+ message: `${valid} record(s) past the privacy floor in ${path15.basename(log_path)} \u2014 retiering signal available`,
4413
5880
  remedy: ""
4414
5881
  };
4415
5882
  }
4416
5883
  function readText0(p) {
4417
- return fs6.readFileSync(p, "utf-8");
5884
+ return fs11.readFileSync(p, "utf-8");
4418
5885
  }
4419
5886
  function osErrorStr(exc) {
4420
5887
  if (exc && typeof exc === "object" && "message" in exc) {
@@ -4587,7 +6054,7 @@ function _epoch_seconds(value) {
4587
6054
  function _codex_auth_expiry(auth_path) {
4588
6055
  let data;
4589
6056
  try {
4590
- data = JSON.parse(fs6.readFileSync(auth_path, "utf-8"));
6057
+ data = JSON.parse(fs11.readFileSync(auth_path, "utf-8"));
4591
6058
  } catch {
4592
6059
  return null;
4593
6060
  }
@@ -4733,7 +6200,7 @@ function _check_team(project_root) {
4733
6200
  if (binary_missing) {
4734
6201
  remedies.push("install the codex CLI: `npm install -g @openai/codex`");
4735
6202
  }
4736
- const auth_path = path7.join(_codex_home(), "auth.json");
6203
+ const auth_path = path15.join(_codex_home(), "auth.json");
4737
6204
  const authed = pathExists(auth_path);
4738
6205
  let auth_str;
4739
6206
  if (!authed) {
@@ -4821,7 +6288,7 @@ function _check_unsupported_combos(manifest) {
4821
6288
  };
4822
6289
  }
4823
6290
  function _wizard_state_path() {
4824
- return path7.join(event4u_root(), "state", "wizard-state.json");
6291
+ return path15.join(event4u_root(), "state", "wizard-state.json");
4825
6292
  }
4826
6293
  function _check_wizard_state() {
4827
6294
  const state_pth = _wizard_state_path();
@@ -4901,7 +6368,7 @@ function _check_wizard_state() {
4901
6368
  };
4902
6369
  }
4903
6370
  function _check_settings_review_pending() {
4904
- const delta_pth = path7.join(event4u_root(), "state", "settings-delta.json");
6371
+ const delta_pth = path15.join(event4u_root(), "state", "settings-delta.json");
4905
6372
  if (!pathExists(delta_pth)) {
4906
6373
  return {
4907
6374
  id: "settings-review-pending",
@@ -4927,7 +6394,7 @@ function _check_settings_review_pending() {
4927
6394
  }
4928
6395
  function _check_memory_merge_union(project_root) {
4929
6396
  const remedy = "run: npx tsx src/scripts/sync_gitattributes.ts (or `agent-config refresh --project`)";
4930
- const target = path7.join(project_root, DEFAULT_GITATTRIBUTES);
6397
+ const target = path15.join(project_root, DEFAULT_GITATTRIBUTES);
4931
6398
  if (!pathExists(target)) {
4932
6399
  return {
4933
6400
  id: "memory-merge-union",
@@ -5254,13 +6721,15 @@ function _emit_text(project_root, missing, modified, foreign, tag_drift) {
5254
6721
  }
5255
6722
  var PROG = "agent-config doctor";
5256
6723
  var USAGE = `usage: ${PROG} [-h] [--project PROJECT] [--json] [--ci] [--check ID]
5257
- [--trace-root] [--context] [--repair ID]
6724
+ [--trace-root] [--context] [--anatomy]
6725
+ [--repair ID]
5258
6726
  `;
5259
6727
  var _STORE_TRUE_FLAGS = {
5260
6728
  "--json": "json",
5261
6729
  "--ci": "ci",
5262
6730
  "--trace-root": "trace_root",
5263
- "--context": "context"
6731
+ "--context": "context",
6732
+ "--anatomy": "anatomy"
5264
6733
  };
5265
6734
  var _VALUE_FLAGS = {
5266
6735
  "--project": "project",
@@ -5273,7 +6742,7 @@ function _argError(msg) {
5273
6742
  `);
5274
6743
  throw new ArgparseExit(2);
5275
6744
  }
5276
- function _parse(argv) {
6745
+ function _parse2(argv) {
5277
6746
  const opts = {
5278
6747
  project: null,
5279
6748
  json: false,
@@ -5281,6 +6750,7 @@ function _parse(argv) {
5281
6750
  check: null,
5282
6751
  trace_root: false,
5283
6752
  context: false,
6753
+ anatomy: false,
5284
6754
  repair: null
5285
6755
  };
5286
6756
  const positionals = [];
@@ -5397,6 +6867,42 @@ function _run_context(opts) {
5397
6867
  }
5398
6868
  return 0;
5399
6869
  }
6870
+ function _run_anatomy(opts) {
6871
+ const census = preamble_byte_census_exports;
6872
+ const economy = dispatch_economy_report_exports;
6873
+ const byteCensus = census.buildReport(census.parseArgs([]));
6874
+ let economyReport = null;
6875
+ let economyError = null;
6876
+ try {
6877
+ economyReport = economy.buildReport({
6878
+ root: economy.DEFAULT_PROJECTS_ROOT,
6879
+ auditDir: path15.join(process2.cwd(), economy.DEFAULT_AUDIT_DIR),
6880
+ maxAgeDays: 14
6881
+ });
6882
+ } catch (err) {
6883
+ economyError = err instanceof Error ? err.message : String(err);
6884
+ }
6885
+ if (opts.json) {
6886
+ print(
6887
+ _jsonDumpsIndentAscii(
6888
+ {
6889
+ preamble_byte_census: byteCensus,
6890
+ dispatch_economy: economyReport,
6891
+ dispatch_economy_unavailable: economyError
6892
+ },
6893
+ 2
6894
+ )
6895
+ );
6896
+ return 0;
6897
+ }
6898
+ print("\u2500\u2500 injection anatomy \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
6899
+ print(census.renderText(byteCensus));
6900
+ print("");
6901
+ print(
6902
+ economyReport !== null ? economy.renderText(economyReport) : `dispatch-economy report unavailable: ${economyError}`
6903
+ );
6904
+ return 0;
6905
+ }
5400
6906
  function _run_repair(opts) {
5401
6907
  const target = opts.repair;
5402
6908
  if (target === "wizard-state") {
@@ -5409,7 +6915,7 @@ function _run_repair(opts) {
5409
6915
  };
5410
6916
  if (exists2) {
5411
6917
  try {
5412
- fs6.unlinkSync(state_pth);
6918
+ fs11.unlinkSync(state_pth);
5413
6919
  } catch (exc) {
5414
6920
  payload["action"] = "error";
5415
6921
  payload["error"] = osErrorStr(exc);
@@ -5435,8 +6941,8 @@ function _run_repair(opts) {
5435
6941
  eprint(`\u274C doctor: unknown repair target ${pyRepr(target)}`);
5436
6942
  return 2;
5437
6943
  }
5438
- function main(argv = null) {
5439
- const opts = _parse(argv !== null ? Array.from(argv) : process2.argv.slice(2));
6944
+ function main4(argv = null) {
6945
+ const opts = _parse2(argv !== null ? Array.from(argv) : process2.argv.slice(2));
5440
6946
  if (opts.ci) {
5441
6947
  opts.json = true;
5442
6948
  }
@@ -5449,6 +6955,9 @@ function main(argv = null) {
5449
6955
  if (opts.context) {
5450
6956
  return _run_context(opts);
5451
6957
  }
6958
+ if (opts.anatomy) {
6959
+ return _run_anatomy(opts);
6960
+ }
5452
6961
  let project_root;
5453
6962
  let origin;
5454
6963
  try {
@@ -5500,25 +7009,25 @@ function main(argv = null) {
5500
7009
  }
5501
7010
  return drift_present ? 1 : 0;
5502
7011
  }
5503
- function _isCliEntry() {
7012
+ function _isCliEntry2() {
5504
7013
  if (process2.argv[1] === void 0) {
5505
7014
  return false;
5506
7015
  }
5507
- const argvUrl = pathToFileURL(path7.resolve(process2.argv[1])).href;
7016
+ const argvUrl = pathToFileURL4(path15.resolve(process2.argv[1])).href;
5508
7017
  if (import.meta.url === argvUrl) {
5509
7018
  return true;
5510
7019
  }
5511
7020
  try {
5512
- const here = fs6.realpathSync(fileURLToPath2(import.meta.url));
5513
- const argv = fs6.realpathSync(path7.resolve(process2.argv[1]));
7021
+ const here = fs11.realpathSync(fileURLToPath6(import.meta.url));
7022
+ const argv = fs11.realpathSync(path15.resolve(process2.argv[1]));
5514
7023
  return here === argv;
5515
7024
  } catch {
5516
7025
  return false;
5517
7026
  }
5518
7027
  }
5519
- if (_isCliEntry() || process2.argv[1] === _HERE2) {
7028
+ if (_isCliEntry2() || process2.argv[1] === _HERE6) {
5520
7029
  try {
5521
- process2.exitCode = main(process2.argv.slice(2));
7030
+ process2.exitCode = main4(process2.argv.slice(2));
5522
7031
  } catch (e) {
5523
7032
  if (e instanceof ArgparseExit) {
5524
7033
  process2.exitCode = e.code;
@@ -5529,6 +7038,11 @@ if (_isCliEntry() || process2.argv[1] === _HERE2) {
5529
7038
  }
5530
7039
 
5531
7040
  export {
7041
+ comparePair,
7042
+ splitFrontmatter,
7043
+ proseEqual,
7044
+ frontmatterPaths,
7045
+ censusRuleDir,
5532
7046
  ArgparseExit,
5533
7047
  _jsonDumpsIndentAscii,
5534
7048
  NO_FRONTMATTER,
@@ -5589,9 +7103,9 @@ export {
5589
7103
  _emit_json,
5590
7104
  _emit_checks_text,
5591
7105
  _emit_text,
5592
- _parse,
7106
+ _parse2 as _parse,
5593
7107
  _run_trace_root,
5594
7108
  _run_context,
5595
7109
  _run_repair,
5596
- main
7110
+ main4 as main
5597
7111
  };