@event4u/agent-config 9.32.0 → 9.33.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 (76) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +96 -1
  3. package/dist/agent-src/commands/review/routing.md +3 -4
  4. package/dist/agent-src/contexts/communication/rules-auto/reply-close-mechanics.md +65 -0
  5. package/dist/agent-src/contexts/execution/orchestration-telemetry.md +3 -0
  6. package/dist/agent-src/rules/delegation-policy.md +6 -0
  7. package/dist/agent-src/scripts/roadmap_gates.ts +107 -3
  8. package/dist/agent-src/skills/docker/SKILL.md +11 -0
  9. package/dist/agent-src/skills/laravel/SKILL.md +11 -0
  10. package/dist/agent-src/skills/review-routing/SKILL.md +23 -6
  11. package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
  12. package/dist/agent-src/templates/scripts/ownership-map.example.yml +1 -1
  13. package/dist/cli/registry.js +4 -4
  14. package/dist/cli/registry.js.map +1 -1
  15. package/dist/cli-delegate/chunk-HTIU3W56.js +66 -0
  16. package/dist/cli-delegate/{chunk-ITIQSGOQ.js → chunk-MA4GFWDY.js} +7 -4
  17. package/dist/cli-delegate/{chunk-542DZR4P.js → chunk-PMQ6Z3T3.js} +1651 -144
  18. package/dist/cli-delegate/{chunk-PFBV6XRT.js → chunk-Q26HT4QT.js} +1 -63
  19. package/dist/cli-delegate/{chunk-LVRYBKTI.js → chunk-YPAWXXXR.js} +158 -0
  20. package/dist/cli-delegate/cmd_conformance.js +256 -226
  21. package/dist/cli-delegate/cmd_doctor.js +3 -2
  22. package/dist/cli-delegate/cmd_export.js +1 -1
  23. package/dist/cli-delegate/cmd_handoff.js +19 -26
  24. package/dist/cli-delegate/cmd_prune.js +1 -1
  25. package/dist/cli-delegate/cmd_session_recycle.js +13 -3
  26. package/dist/cli-delegate/cmd_settings_get.js +4 -2
  27. package/dist/cli-delegate/cmd_settings_migrate.js +1 -1
  28. package/dist/cli-delegate/cmd_settings_set.js +5 -3
  29. package/dist/cli-delegate/cmd_sync.js +1 -1
  30. package/dist/cli-delegate/cmd_uninstall.js +1 -1
  31. package/dist/cli-delegate/cmd_validate.js +1 -1
  32. package/dist/discovery/deprecation-report.md +1 -1
  33. package/dist/discovery/discovery-manifest.json +8 -8
  34. package/dist/discovery/discovery-manifest.json.sha256 +1 -1
  35. package/dist/discovery/discovery-manifest.summary.md +1 -1
  36. package/dist/discovery/orphan-report.md +1 -1
  37. package/dist/discovery/packs.json +2 -2
  38. package/dist/discovery/trust-report.md +1 -1
  39. package/dist/discovery/workspaces.json +2 -2
  40. package/dist/hooks/dispatch.js +18 -0
  41. package/dist/install/install.mjs +7 -4
  42. package/dist/mcp/registry-manifest.json +2 -2
  43. package/dist/mcp/server.json +2 -2
  44. package/dist/mcp/server.mjs +3637 -1158
  45. package/package.json +1 -1
  46. package/src/agent-src/scripts/roadmap_gates.ts +107 -3
  47. package/src/agent-src/templates/scripts/ownership-map.example.yml +1 -1
  48. package/src/config/cost-parity-budget.json +167 -0
  49. package/src/config/gate-coverage.yml +44 -5
  50. package/src/config/quorum-attendance-budget.json +39 -0
  51. package/src/scripts/_cli/cmd_doctor.ts +69 -1
  52. package/src/scripts/_cli/cmd_session_recycle.ts +19 -3
  53. package/src/scripts/_dispatch.bash +5 -3
  54. package/src/scripts/_lib/orchestration_record.ts +45 -0
  55. package/src/scripts/ai_council/clients.ts +31 -0
  56. package/src/scripts/ai_council/events_log.ts +128 -6
  57. package/src/scripts/ai_council/orchestrator.ts +12 -3
  58. package/src/scripts/ai_council/pricing.ts +48 -1
  59. package/src/scripts/ai_council/quorum.ts +20 -0
  60. package/src/scripts/ai_council/session.ts +11 -0
  61. package/src/scripts/ask_transport.ts +20 -1
  62. package/src/scripts/cache_realization_report.ts +38 -0
  63. package/src/scripts/check_release_highlights.ts +7 -1
  64. package/src/scripts/conformance_scan.ts +105 -0
  65. package/src/scripts/cost/track.mjs +39 -0
  66. package/src/scripts/cost_summary.ts +104 -1
  67. package/src/scripts/council_cli.ts +131 -13
  68. package/src/scripts/dispatch_economy_report.ts +5 -2
  69. package/src/scripts/install.ts +20 -6
  70. package/src/scripts/lint_budget_ownership.ts +81 -0
  71. package/src/scripts/lint_skill_frontmatter_safety.ts +55 -1
  72. package/src/scripts/lint_workflow_paths.ts +384 -0
  73. package/src/scripts/preamble_byte_census.ts +9 -1
  74. package/src/scripts/report_carrier_divergence.ts +10 -0
  75. package/src/scripts/report_conformance_funnel.ts +40 -0
  76. package/src/scripts/schemas/subagent.schema.json +3 -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,28 @@ __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
+ var SCHEMA_VERSION = 2;
185
1626
  var _VALID_ACTIONS = /* @__PURE__ */ new Set([
186
1627
  "proceed",
187
1628
  "skip_necessity",
188
- "block_quota"
1629
+ "block_quota",
1630
+ "quorum_result"
189
1631
  ]);
190
1632
  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(
1633
+ var _HERE5 = fileURLToPath5(import.meta.url);
1634
+ var _REPO_ROOT = path10.resolve(path10.dirname(_HERE5), "..", "..", "..");
1635
+ var _DEFAULT_LOG_PATH = path10.join(
194
1636
  _REPO_ROOT,
195
1637
  "agents",
196
1638
  "runtime",
@@ -291,9 +1733,9 @@ function appendEvent(event, opts = {}) {
291
1733
  }
292
1734
  }
293
1735
  const target = opts.logPath != null ? opts.logPath : _DEFAULT_LOG_PATH;
294
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
1736
+ fs7.mkdirSync(path10.dirname(target), { recursive: true });
295
1737
  const line = _pyJsonDumpsCompact(record);
296
- fs2.appendFileSync(target, line + "\n", { encoding: "utf-8" });
1738
+ fs7.appendFileSync(target, line + "\n", { encoding: "utf-8" });
297
1739
  return true;
298
1740
  }
299
1741
  function _isoSecondsZ(d) {
@@ -453,9 +1895,21 @@ function assertCacheBreakpointOrder(ttls) {
453
1895
  }
454
1896
  }
455
1897
  }
1898
+ function _servedModel(response, field = "model") {
1899
+ const value = _getattr(response, field, "");
1900
+ return typeof value === "string" ? value : "";
1901
+ }
456
1902
  var CouncilResponse = class {
457
1903
  provider;
458
1904
  model;
1905
+ // The model id the provider reported serving, when it reports one. NEVER
1906
+ // overwrites `model`: that is the REQUESTED id, and it is what the tier
1907
+ // decision was made against — keeping both is what makes a silent alias or
1908
+ // provider substitution detectable at all. Attribution-only; no consumer
1909
+ // may route on it. Defaults to '' (the honest value for a transport that
1910
+ // reports no served id, e.g. every CLI client) so existing callers and the
1911
+ // persisted response JSON stay backward-compatible.
1912
+ model_served;
459
1913
  text;
460
1914
  input_tokens;
461
1915
  output_tokens;
@@ -471,6 +1925,7 @@ var CouncilResponse = class {
471
1925
  constructor(opts) {
472
1926
  this.provider = opts.provider;
473
1927
  this.model = opts.model;
1928
+ this.model_served = opts.model_served ?? "";
474
1929
  this.text = opts.text;
475
1930
  this.input_tokens = opts.input_tokens ?? 0;
476
1931
  this.output_tokens = opts.output_tokens ?? 0;
@@ -496,13 +1951,13 @@ function _setMonotonicSource(fn) {
496
1951
  return prev;
497
1952
  }
498
1953
  function _loadKey(p, prefix, installScript) {
499
- if (!fs3.existsSync(p)) {
1954
+ if (!fs8.existsSync(p)) {
500
1955
  throw new KeyGateError(
501
1956
  `Key not found at ${p}.
502
1957
  Install it with: bash ${installScript}`
503
1958
  );
504
1959
  }
505
- const st = fs3.statSync(p);
1960
+ const st = fs8.statSync(p);
506
1961
  const mode = st.mode & 511;
507
1962
  if (mode !== 384) {
508
1963
  throw new KeyGateError(
@@ -510,7 +1965,7 @@ function _loadKey(p, prefix, installScript) {
510
1965
  Fix: chmod 600 ${p}`
511
1966
  );
512
1967
  }
513
- const key = fs3.readFileSync(p, { encoding: "utf-8" }).trim();
1968
+ const key = fs8.readFileSync(p, { encoding: "utf-8" }).trim();
514
1969
  if (!key) {
515
1970
  throw new KeyGateError(`${p} is empty.`);
516
1971
  }
@@ -717,6 +2172,7 @@ var AnthropicClient = class extends ExternalAIClient {
717
2172
  return new CouncilResponse({
718
2173
  provider: this.name,
719
2174
  model: this.model,
2175
+ model_served: _servedModel(response),
720
2176
  text,
721
2177
  input_tokens: usage ? _getattr(usage, "input_tokens", 0) : 0,
722
2178
  output_tokens: usage ? _getattr(usage, "output_tokens", 0) : 0,
@@ -804,6 +2260,7 @@ ${user_prompt}` }
804
2260
  return new CouncilResponse({
805
2261
  provider: this.name,
806
2262
  model: this.model,
2263
+ model_served: _servedModel(response),
807
2264
  text: text || "",
808
2265
  input_tokens: usage ? _getattr(usage, "prompt_tokens", 0) : 0,
809
2266
  output_tokens: usage ? _getattr(usage, "completion_tokens", 0) : 0,
@@ -864,6 +2321,8 @@ ${user_prompt}`;
864
2321
  return new CouncilResponse({
865
2322
  provider: this.name,
866
2323
  model: this.model,
2324
+ // Gemini names it `model_version`, not `model`.
2325
+ model_served: _servedModel(response, "model_version"),
867
2326
  text,
868
2327
  input_tokens: usage ? _getattr(usage, "prompt_token_count", 0) : 0,
869
2328
  output_tokens: usage ? _getattr(usage, "candidates_token_count", 0) : 0,
@@ -929,6 +2388,7 @@ var _OpenAICompatibleClient = class extends ExternalAIClient {
929
2388
  return new CouncilResponse({
930
2389
  provider: this.name,
931
2390
  model: this.model,
2391
+ model_served: _servedModel(response),
932
2392
  text: text || "",
933
2393
  input_tokens: usage ? _getattr(usage, "prompt_tokens", 0) : 0,
934
2394
  output_tokens: usage ? _getattr(usage, "completion_tokens", 0) : 0,
@@ -968,12 +2428,12 @@ function _today_utc_iso() {
968
2428
  }
969
2429
  function load_cli_call_counts(p = null) {
970
2430
  const target = p !== null ? p : _cliCallsStatePath();
971
- if (!fs3.existsSync(target)) {
2431
+ if (!fs8.existsSync(target)) {
972
2432
  return {};
973
2433
  }
974
2434
  let data;
975
2435
  try {
976
- data = JSON.parse(fs3.readFileSync(target, { encoding: "utf-8" }));
2436
+ data = JSON.parse(fs8.readFileSync(target, { encoding: "utf-8" }));
977
2437
  } catch {
978
2438
  return {};
979
2439
  }
@@ -1000,8 +2460,8 @@ function record_cli_call(provider, p = null) {
1000
2460
  const target = p !== null ? p : _cliCallsStatePath();
1001
2461
  const counts = load_cli_call_counts(target);
1002
2462
  counts[provider] = (counts[provider] ?? 0) + 1;
1003
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
1004
- fs3.writeFileSync(
2463
+ fs8.mkdirSync(path11.dirname(target), { recursive: true });
2464
+ fs8.writeFileSync(
1005
2465
  target,
1006
2466
  _jsonDumpsIndent2({ date: _today_utc_iso(), counts }),
1007
2467
  { encoding: "utf-8" }
@@ -1016,8 +2476,8 @@ function reset_cli_call_counts(provider = null, p = null) {
1016
2476
  } else {
1017
2477
  delete counts[provider];
1018
2478
  }
1019
- fs3.mkdirSync(path3.dirname(target), { recursive: true });
1020
- fs3.writeFileSync(
2479
+ fs8.mkdirSync(path11.dirname(target), { recursive: true });
2480
+ fs8.writeFileSync(
1021
2481
  target,
1022
2482
  _jsonDumpsIndent2({ date: _today_utc_iso(), counts }),
1023
2483
  { encoding: "utf-8" }
@@ -2085,7 +3545,7 @@ function _pyJsonStringAscii(s) {
2085
3545
  return out + '"';
2086
3546
  }
2087
3547
  function _which(name) {
2088
- if (name.includes(path3.sep) || path3.sep !== "/" && name.includes("/")) {
3548
+ if (name.includes(path11.sep) || path11.sep !== "/" && name.includes("/")) {
2089
3549
  return _isExecutable(name) ? name : null;
2090
3550
  }
2091
3551
  const pathEnv = process.env.PATH ?? "";
@@ -2093,12 +3553,12 @@ function _which(name) {
2093
3553
  return null;
2094
3554
  }
2095
3555
  const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
2096
- for (const dir of pathEnv.split(path3.delimiter)) {
3556
+ for (const dir of pathEnv.split(path11.delimiter)) {
2097
3557
  if (!dir) {
2098
3558
  continue;
2099
3559
  }
2100
3560
  for (const ext of exts) {
2101
- const candidate = path3.join(dir, name + ext);
3561
+ const candidate = path11.join(dir, name + ext);
2102
3562
  if (_isExecutable(candidate)) {
2103
3563
  return candidate;
2104
3564
  }
@@ -2108,7 +3568,7 @@ function _which(name) {
2108
3568
  }
2109
3569
  function _isExecutable(p) {
2110
3570
  try {
2111
- const st = fs3.statSync(p);
3571
+ const st = fs8.statSync(p);
2112
3572
  if (!st.isFile()) {
2113
3573
  return false;
2114
3574
  }
@@ -2135,7 +3595,7 @@ function _defaultStdin() {
2135
3595
  function ensure() {
2136
3596
  if (buffer === null) {
2137
3597
  try {
2138
- buffer = fs3.readFileSync(0, { encoding: "utf-8" });
3598
+ buffer = fs8.readFileSync(0, { encoding: "utf-8" });
2139
3599
  } catch {
2140
3600
  buffer = "";
2141
3601
  }
@@ -2177,14 +3637,14 @@ function _defaultStdin() {
2177
3637
 
2178
3638
  // src/scripts/_lib/environment_detector.ts
2179
3639
  import { spawnSync as spawnSync2 } from "node:child_process";
2180
- import * as fs4 from "node:fs";
3640
+ import * as fs9 from "node:fs";
2181
3641
  import * as os from "node:os";
2182
- import * as path4 from "node:path";
3642
+ import * as path12 from "node:path";
2183
3643
 
2184
3644
  // 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";
3645
+ import { existsSync as existsSync7 } from "node:fs";
3646
+ import { homedir as homedir3 } from "node:os";
3647
+ import { delimiter as delimiter2, join as join12 } from "node:path";
2188
3648
  var TOOL_SIGNALS = {
2189
3649
  "claude-code": { bins: ["claude"], homePaths: [".claude", ".claude.json", ".config/claude"] },
2190
3650
  "claude-desktop": { absPaths: ["/Applications/Claude.app"], homePaths: ["Library/Application Support/Claude", ".config/Claude"] },
@@ -2229,8 +3689,8 @@ function resolveBinaryPath(name, pathEnv) {
2229
3689
  for (const dir of pathEnv.split(delimiter2)) {
2230
3690
  if (dir.length === 0) continue;
2231
3691
  for (const candidate of [name, `${name}.exe`, `${name}.cmd`]) {
2232
- const full = join4(dir, candidate);
2233
- if (existsSync3(full)) return full;
3692
+ const full = join12(dir, candidate);
3693
+ if (existsSync7(full)) return full;
2234
3694
  }
2235
3695
  }
2236
3696
  return null;
@@ -2240,10 +3700,10 @@ function binOnPath(name, pathEnv) {
2240
3700
  }
2241
3701
  function isToolInstalled(signal, home, pathEnv) {
2242
3702
  for (const rel of signal.homePaths ?? []) {
2243
- if (existsSync3(join4(home, rel))) return true;
3703
+ if (existsSync7(join12(home, rel))) return true;
2244
3704
  }
2245
3705
  for (const abs of signal.absPaths ?? []) {
2246
- if (existsSync3(abs)) return true;
3706
+ if (existsSync7(abs)) return true;
2247
3707
  }
2248
3708
  for (const bin of signal.bins ?? []) {
2249
3709
  if (binOnPath(bin, pathEnv)) return true;
@@ -2251,7 +3711,7 @@ function isToolInstalled(signal, home, pathEnv) {
2251
3711
  return false;
2252
3712
  }
2253
3713
  function detectInstalledTools(opts = {}) {
2254
- const home = opts.home ?? homedir();
3714
+ const home = opts.home ?? homedir3();
2255
3715
  const pathEnv = opts.pathEnv ?? process.env["PATH"] ?? "";
2256
3716
  const out = {};
2257
3717
  for (const [id, signal] of Object.entries(TOOL_SIGNALS)) {
@@ -2302,7 +3762,7 @@ function classifyBilling(provider, source) {
2302
3762
  function codexHome(env) {
2303
3763
  const map = env ?? process.env;
2304
3764
  const override = (map["CODEX_HOME"] ?? "").trim();
2305
- return override !== "" ? override : path4.join(homeOf(env), ".codex");
3765
+ return override !== "" ? override : path12.join(homeOf(env), ".codex");
2306
3766
  }
2307
3767
  function homeOf(env) {
2308
3768
  const map = env ?? process.env;
@@ -2327,14 +3787,14 @@ ${res.stderr ?? ""}`;
2327
3787
  }
2328
3788
  function isFile(p) {
2329
3789
  try {
2330
- return fs4.statSync(p).isFile();
3790
+ return fs9.statSync(p).isFile();
2331
3791
  } catch {
2332
3792
  return false;
2333
3793
  }
2334
3794
  }
2335
3795
  function exists(p) {
2336
3796
  try {
2337
- return fs4.existsSync(p);
3797
+ return fs9.existsSync(p);
2338
3798
  } catch {
2339
3799
  return false;
2340
3800
  }
@@ -2342,7 +3802,7 @@ function exists(p) {
2342
3802
  function classifyCodexAuth(authPath) {
2343
3803
  let data;
2344
3804
  try {
2345
- data = JSON.parse(fs4.readFileSync(authPath, "utf-8"));
3805
+ data = JSON.parse(fs9.readFileSync(authPath, "utf-8"));
2346
3806
  } catch {
2347
3807
  return "cli-api-key";
2348
3808
  }
@@ -2359,18 +3819,18 @@ function cliSubscriptionEvidence(provider, home, env, claudeConfigDir) {
2359
3819
  if (provider === "anthropic") {
2360
3820
  const configDir = claudeConfigDir;
2361
3821
  for (const rel of [".credentials.json", "credentials.json"]) {
2362
- const p = path4.join(configDir, rel);
3822
+ const p = path12.join(configDir, rel);
2363
3823
  if (isFile(p)) return { source: "cli-subscription", evidence: p };
2364
3824
  }
2365
3825
  return null;
2366
3826
  }
2367
3827
  if (provider === "openai") {
2368
- const p = path4.join(codexHome(env), "auth.json");
3828
+ const p = path12.join(codexHome(env), "auth.json");
2369
3829
  if (isFile(p)) return { source: classifyCodexAuth(p), evidence: p };
2370
3830
  return null;
2371
3831
  }
2372
3832
  if (provider === "gemini") {
2373
- const p = path4.join(home, ".gemini", "oauth_creds.json");
3833
+ const p = path12.join(home, ".gemini", "oauth_creds.json");
2374
3834
  if (isFile(p)) return { source: "cli-subscription", evidence: p };
2375
3835
  return null;
2376
3836
  }
@@ -2402,7 +3862,7 @@ function detectHosts(opts) {
2402
3862
  function detectAuth(opts) {
2403
3863
  const env = opts.env ?? process.env;
2404
3864
  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");
3865
+ const claudeConfigDir = opts.home === void 0 && opts.env === void 0 ? claude_config_dir() : (env["CLAUDE_CONFIG_DIR"] ?? "").trim() || path12.join(home, ".claude");
2406
3866
  const auth = [];
2407
3867
  const keys = [];
2408
3868
  for (const provider of knownProviders()) {
@@ -2456,7 +3916,7 @@ function detectEnvironment(opts = {}) {
2456
3916
  }
2457
3917
 
2458
3918
  // src/scripts/_cli/detection_report.ts
2459
- import * as path5 from "node:path";
3919
+ import * as path13 from "node:path";
2460
3920
 
2461
3921
  // src/scripts/ai_council/transport_resolver.ts
2462
3922
  var VALID_TRANSPORT_MODES = /* @__PURE__ */ new Set([
@@ -2658,7 +4118,7 @@ function cliBinaryPresent(environment, provider, binaryOverride) {
2658
4118
  const expected = PROVIDER_CLI_META[provider]?.[0];
2659
4119
  if (expected === void 0) return false;
2660
4120
  return environment.hosts.some(
2661
- (h) => h.binary !== null && stripExe(path5.basename(h.binary)) === expected
4121
+ (h) => h.binary !== null && stripExe(path13.basename(h.binary)) === expected
2662
4122
  );
2663
4123
  }
2664
4124
  function stripExe(name) {
@@ -2819,9 +4279,9 @@ function absentCouncilFacts(configPath) {
2819
4279
 
2820
4280
  // src/scripts/ai_team/review_gate.ts
2821
4281
  import * as crypto2 from "node:crypto";
2822
- import * as fs5 from "node:fs";
4282
+ import * as fs10 from "node:fs";
2823
4283
  import * as os2 from "node:os";
2824
- import * as path6 from "node:path";
4284
+ import * as path14 from "node:path";
2825
4285
 
2826
4286
  // src/scripts/ai_team/config.ts
2827
4287
  var AI_TEAM_REVIEW_GATE_DEFAULTS = Object.freeze({
@@ -2837,16 +4297,16 @@ var AI_TEAM_DEFAULTS = Object.freeze({
2837
4297
  });
2838
4298
 
2839
4299
  // src/scripts/ai_team/review_gate.ts
2840
- var GATE_LEDGER_RELPATH = path6.join("agents", "runtime", "team", "events.log");
4300
+ var GATE_LEDGER_RELPATH = path14.join("agents", "runtime", "team", "events.log");
2841
4301
  var _CODEX_PLUGIN_DATA_DIRNAME = `${CODEX_PLUGIN_ID}-${CODEX_MARKETPLACE_NAME}`;
2842
4302
  function _workspace_state_segment(workspace_root) {
2843
4303
  let canonical = workspace_root;
2844
4304
  try {
2845
- canonical = fs5.realpathSync.native(workspace_root);
4305
+ canonical = fs10.realpathSync.native(workspace_root);
2846
4306
  } catch {
2847
4307
  canonical = workspace_root;
2848
4308
  }
2849
- const slug_source = path6.basename(workspace_root) || "workspace";
4309
+ const slug_source = path14.basename(workspace_root) || "workspace";
2850
4310
  const slug = slug_source.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "workspace";
2851
4311
  const hash = crypto2.createHash("sha256").update(canonical).digest("hex").slice(0, 16);
2852
4312
  return `${slug}-${hash}`;
@@ -2856,19 +4316,19 @@ function upstream_state_dir_candidates(workspace_root) {
2856
4316
  const candidates = [];
2857
4317
  const env = (process.env["CLAUDE_PLUGIN_DATA"] ?? "").trim();
2858
4318
  if (env !== "") {
2859
- candidates.push(path6.join(env, "state", segment));
4319
+ candidates.push(path14.join(env, "state", segment));
2860
4320
  }
2861
4321
  candidates.push(
2862
- path6.join(claude_config_dir(), "plugins", "data", _CODEX_PLUGIN_DATA_DIRNAME, "state", segment)
4322
+ path14.join(claude_config_dir(), "plugins", "data", _CODEX_PLUGIN_DATA_DIRNAME, "state", segment)
2863
4323
  );
2864
- candidates.push(path6.join(os2.tmpdir(), "codex-companion", segment));
4324
+ candidates.push(path14.join(os2.tmpdir(), "codex-companion", segment));
2865
4325
  return candidates;
2866
4326
  }
2867
4327
  function upstream_gate_enabled(workspace_root) {
2868
4328
  for (const dir of upstream_state_dir_candidates(workspace_root)) {
2869
4329
  let parsed;
2870
4330
  try {
2871
- parsed = JSON.parse(fs5.readFileSync(path6.join(dir, "state.json"), "utf-8"));
4331
+ parsed = JSON.parse(fs10.readFileSync(path14.join(dir, "state.json"), "utf-8"));
2872
4332
  } catch {
2873
4333
  continue;
2874
4334
  }
@@ -2917,7 +4377,7 @@ function review_gate_doctor_signal(project_root, gate_raw) {
2917
4377
  }
2918
4378
 
2919
4379
  // src/scripts/_cli/cmd_doctor.ts
2920
- var _HERE2 = fileURLToPath2(import.meta.url);
4380
+ var _HERE6 = fileURLToPath6(import.meta.url);
2921
4381
  var ArgparseExit = class extends Error {
2922
4382
  constructor(code) {
2923
4383
  super(`argparse-exit-${code}`);
@@ -2928,13 +4388,13 @@ var ArgparseExit = class extends Error {
2928
4388
  function expanduser(p) {
2929
4389
  if (p === "~") return os3.homedir();
2930
4390
  if (p.startsWith("~/") || p.startsWith("~\\")) {
2931
- return path7.join(os3.homedir(), p.slice(2));
4391
+ return path15.join(os3.homedir(), p.slice(2));
2932
4392
  }
2933
4393
  return p;
2934
4394
  }
2935
4395
  function pathExists(p) {
2936
4396
  try {
2937
- fs6.statSync(p);
4397
+ fs11.statSync(p);
2938
4398
  return true;
2939
4399
  } catch {
2940
4400
  return false;
@@ -2942,27 +4402,27 @@ function pathExists(p) {
2942
4402
  }
2943
4403
  function isFile2(p) {
2944
4404
  try {
2945
- return fs6.statSync(p).isFile();
4405
+ return fs11.statSync(p).isFile();
2946
4406
  } catch {
2947
4407
  return false;
2948
4408
  }
2949
4409
  }
2950
4410
  function isDir(p) {
2951
4411
  try {
2952
- return fs6.statSync(p).isDirectory();
4412
+ return fs11.statSync(p).isDirectory();
2953
4413
  } catch {
2954
4414
  return false;
2955
4415
  }
2956
4416
  }
2957
4417
  function resolvePath(p) {
2958
4418
  try {
2959
- return fs6.realpathSync(path7.resolve(p));
4419
+ return fs11.realpathSync(path15.resolve(p));
2960
4420
  } catch {
2961
- return path7.resolve(p);
4421
+ return path15.resolve(p);
2962
4422
  }
2963
4423
  }
2964
4424
  function readText(p) {
2965
- return fs6.readFileSync(p, "utf-8");
4425
+ return fs11.readFileSync(p, "utf-8");
2966
4426
  }
2967
4427
  function _jsonStrAscii(s) {
2968
4428
  let out = '"';
@@ -3050,11 +4510,11 @@ function _jsonDumpsIndentAscii(value, indent) {
3050
4510
  return _dumpIndentAscii(value, indent, 0);
3051
4511
  }
3052
4512
  function yamlSafeLoad(text) {
3053
- if (YAML === void 0 || YAML === null) {
4513
+ if (YAML2 === void 0 || YAML2 === null) {
3054
4514
  return null;
3055
4515
  }
3056
4516
  try {
3057
- return YAML.parse(text, { version: "1.1" });
4517
+ return YAML2.parse(text, { version: "1.1" });
3058
4518
  } catch {
3059
4519
  return void 0;
3060
4520
  }
@@ -3073,7 +4533,7 @@ function _resolve_project_root(arg) {
3073
4533
  }
3074
4534
  var _INSTALL_MODE_MARKER_REL = "agents/.agent-state/install-mode.txt";
3075
4535
  function _detect_install_mode(project_root) {
3076
- const marker = path7.join(project_root, _INSTALL_MODE_MARKER_REL);
4536
+ const marker = path15.join(project_root, _INSTALL_MODE_MARKER_REL);
3077
4537
  if (isFile2(marker)) {
3078
4538
  let value;
3079
4539
  try {
@@ -3085,9 +4545,9 @@ function _detect_install_mode(project_root) {
3085
4545
  return [value, "marker-file"];
3086
4546
  }
3087
4547
  }
3088
- const has_agents_md = pathExists(path7.join(project_root, "AGENTS.md"));
4548
+ const has_agents_md = pathExists(path15.join(project_root, "AGENTS.md"));
3089
4549
  const has_copilot = pathExists(
3090
- path7.join(project_root, ".github", "copilot-instructions.md")
4550
+ path15.join(project_root, ".github", "copilot-instructions.md")
3091
4551
  );
3092
4552
  if (has_agents_md && has_copilot) {
3093
4553
  return ["full", "heuristic"];
@@ -3107,7 +4567,7 @@ function _settings_layer_chain(project_root) {
3107
4567
  return layers;
3108
4568
  }
3109
4569
  function _detect_wrapper(project_root) {
3110
- const wrapper = path7.join(project_root, "agent-config");
4570
+ const wrapper = path15.join(project_root, "agent-config");
3111
4571
  if (!pathExists(wrapper)) {
3112
4572
  return { path: String(wrapper), exists: false, embedded_root: null };
3113
4573
  }
@@ -3174,14 +4634,14 @@ function _emit_context_text(ctx) {
3174
4634
  }
3175
4635
  function _resolve_path(project_root, raw) {
3176
4636
  let p = expanduser(raw);
3177
- if (!path7.isAbsolute(p)) {
3178
- p = path7.join(project_root, p);
4637
+ if (!path15.isAbsolute(p)) {
4638
+ p = path15.join(project_root, p);
3179
4639
  }
3180
4640
  return p;
3181
4641
  }
3182
4642
  function _sha256(p) {
3183
4643
  try {
3184
- const data = fs6.readFileSync(p);
4644
+ const data = fs11.readFileSync(p);
3185
4645
  return crypto3.createHash("sha256").update(data).digest("hex");
3186
4646
  } catch {
3187
4647
  return null;
@@ -3190,7 +4650,7 @@ function _sha256(p) {
3190
4650
  var PACKAGE_TAG_ID = "event4u/agent-config";
3191
4651
  var _FRONTMATTER_PACKAGE_RE = /^package:\s*(.+?)\s*$/m;
3192
4652
  function _read_inline_package_tag(p) {
3193
- if (path7.extname(p) !== ".md") {
4653
+ if (path15.extname(p) !== ".md") {
3194
4654
  return NO_FRONTMATTER;
3195
4655
  }
3196
4656
  let text;
@@ -3319,13 +4779,13 @@ function rglob(root) {
3319
4779
  const walk = (dir) => {
3320
4780
  let entries;
3321
4781
  try {
3322
- entries = fs6.readdirSync(dir, { withFileTypes: true });
4782
+ entries = fs11.readdirSync(dir, { withFileTypes: true });
3323
4783
  } catch {
3324
4784
  return;
3325
4785
  }
3326
4786
  entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
3327
4787
  for (const ent of entries) {
3328
- const full = path7.join(dir, ent.name);
4788
+ const full = path15.join(dir, ent.name);
3329
4789
  out.push(full);
3330
4790
  let dirLike = ent.isDirectory();
3331
4791
  if (ent.isSymbolicLink()) {
@@ -3400,9 +4860,9 @@ function _foreign_records(project_root, foreign) {
3400
4860
  return out;
3401
4861
  }
3402
4862
  function relativeTo(p, base) {
3403
- const rel = path7.relative(base, p);
4863
+ const rel = path15.relative(base, p);
3404
4864
  if (rel === "") return rel;
3405
- if (rel.startsWith("..") || path7.isAbsolute(rel)) {
4865
+ if (rel.startsWith("..") || path15.isAbsolute(rel)) {
3406
4866
  return null;
3407
4867
  }
3408
4868
  return rel;
@@ -3466,7 +4926,7 @@ var MANIFEST_REQUIRED_CHECK_IDS = /* @__PURE__ */ new Set([
3466
4926
  ]);
3467
4927
  var INSTALL_MODE_MARKER_RELATIVE = "agents/.agent-state/install-mode.txt";
3468
4928
  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"));
4929
+ return isFile2(path15.join(project_root, INSTALL_MODE_MARKER_RELATIVE)) || isDir(path15.join(project_root, "agents", "overrides"));
3470
4930
  }
3471
4931
  var REPAIR_IDS = ["wizard-state"];
3472
4932
  var MCP_BETA_GATES = [
@@ -3486,7 +4946,7 @@ var STATUS_SYMBOLS = {
3486
4946
  var MIN_PYTHON = [3, 10];
3487
4947
  function _check_scope(project_root) {
3488
4948
  for (const marker of ["pnpm-workspace.yaml", "lerna.json"]) {
3489
- if (pathExists(path7.join(project_root, marker))) {
4949
+ if (pathExists(path15.join(project_root, marker))) {
3490
4950
  return {
3491
4951
  id: "scope",
3492
4952
  status: "warn",
@@ -3495,7 +4955,7 @@ function _check_scope(project_root) {
3495
4955
  };
3496
4956
  }
3497
4957
  }
3498
- const pkg = path7.join(project_root, "package.json");
4958
+ const pkg = path15.join(project_root, "package.json");
3499
4959
  if (pathExists(pkg)) {
3500
4960
  try {
3501
4961
  const data = JSON.parse(readText(pkg));
@@ -3521,7 +4981,7 @@ var _PLACEHOLDER_EMAIL_RE = /^(t@t\.t|.*@example\.(com|org)|.*@localhost)$/i;
3521
4981
  var _PLACEHOLDER_NAME_RE = /^(t|test|user|nobody|x)$/i;
3522
4982
  function _git_config_path(project_root) {
3523
4983
  const common = git_common_dir(project_root);
3524
- return common === null ? null : path7.join(common, "config");
4984
+ return common === null ? null : path15.join(common, "config");
3525
4985
  }
3526
4986
  function _parse_git_user(configText) {
3527
4987
  let inUser = false;
@@ -3551,7 +5011,7 @@ function _check_git_identity(project_root) {
3551
5011
  }
3552
5012
  let ident = _parse_git_user(readText(cfgPath));
3553
5013
  if (ident.name === null && ident.email === null) {
3554
- const globalCfg = path7.join(os3.homedir(), ".gitconfig");
5014
+ const globalCfg = path15.join(os3.homedir(), ".gitconfig");
3555
5015
  if (pathExists(globalCfg)) {
3556
5016
  ident = _parse_git_user(readText(globalCfg));
3557
5017
  }
@@ -3612,7 +5072,7 @@ function _package_root() {
3612
5072
  }
3613
5073
  function _current_package_version() {
3614
5074
  try {
3615
- const data = JSON.parse(readText(path7.join(_package_root(), "package.json")));
5075
+ const data = JSON.parse(readText(path15.join(_package_root(), "package.json")));
3616
5076
  const v = data["version"];
3617
5077
  if (typeof v === "string" && v.trim()) {
3618
5078
  return v.trim();
@@ -3656,7 +5116,7 @@ function _check_lockfile_freshness(manifest) {
3656
5116
  };
3657
5117
  }
3658
5118
  function shutilWhich(name) {
3659
- if (path7.dirname(name) !== "." && (name.includes("/") || name.includes("\\"))) {
5119
+ if (path15.dirname(name) !== "." && (name.includes("/") || name.includes("\\"))) {
3660
5120
  return isExecutableFile(name) ? name : null;
3661
5121
  }
3662
5122
  const pathEnv = process2.env["PATH"] || "";
@@ -3669,12 +5129,12 @@ function shutilWhich(name) {
3669
5129
  if (seenDirs.has(d)) continue;
3670
5130
  seenDirs.add(d);
3671
5131
  for (const ext of exts) {
3672
- const candidate = path7.join(d, name + (ext === "" ? "" : ext.toLowerCase() === ext ? ext : ext));
5132
+ const candidate = path15.join(d, name + (ext === "" ? "" : ext.toLowerCase() === ext ? ext : ext));
3673
5133
  if (isExecutableFile(candidate)) {
3674
5134
  return candidate;
3675
5135
  }
3676
5136
  if (ext !== "") {
3677
- const upper = path7.join(d, name + ext);
5137
+ const upper = path15.join(d, name + ext);
3678
5138
  if (isExecutableFile(upper)) return upper;
3679
5139
  }
3680
5140
  }
@@ -3683,10 +5143,10 @@ function shutilWhich(name) {
3683
5143
  }
3684
5144
  function isExecutableFile(p) {
3685
5145
  try {
3686
- const st = fs6.statSync(p);
5146
+ const st = fs11.statSync(p);
3687
5147
  if (!st.isFile()) return false;
3688
5148
  if (process2.platform === "win32") return true;
3689
- fs6.accessSync(p, fs6.constants.X_OK);
5149
+ fs11.accessSync(p, fs11.constants.X_OK);
3690
5150
  return true;
3691
5151
  } catch {
3692
5152
  return false;
@@ -3750,7 +5210,7 @@ function _check_claude_plugin() {
3750
5210
  remedy: ""
3751
5211
  };
3752
5212
  }
3753
- const projection = path7.join(os3.homedir(), ".claude", "skills");
5213
+ const projection = path15.join(os3.homedir(), ".claude", "skills");
3754
5214
  const projection_present = isDir(projection);
3755
5215
  if (projection_present) {
3756
5216
  return {
@@ -3787,8 +5247,8 @@ function _check_claude_command_wrappers() {
3787
5247
  remedy: ""
3788
5248
  };
3789
5249
  }
3790
- const anchor = path7.join(os3.homedir(), ".claude");
3791
- const commands_dir = path7.join(anchor, "commands");
5250
+ const anchor = path15.join(os3.homedir(), ".claude");
5251
+ const commands_dir = path15.join(anchor, "commands");
3792
5252
  if (!isDir(commands_dir)) {
3793
5253
  return {
3794
5254
  id: "claude-command-wrappers",
@@ -3797,8 +5257,8 @@ function _check_claude_command_wrappers() {
3797
5257
  remedy: ""
3798
5258
  };
3799
5259
  }
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"));
5260
+ const flat_probe = fs11.existsSync(path15.join(commands_dir, "commit.md"));
5261
+ const wrapper_probe = fs11.existsSync(path15.join(anchor, "skills", "commit", "SKILL.md"));
3802
5262
  if (wrapper_probe) {
3803
5263
  return {
3804
5264
  id: "claude-command-wrappers",
@@ -3823,7 +5283,7 @@ function _check_claude_command_wrappers() {
3823
5283
  };
3824
5284
  }
3825
5285
  function _check_surface_state() {
3826
- const matrix_path = path7.join(_package_root(), "src", "config", "surface-matrix.yml");
5286
+ const matrix_path = path15.join(_package_root(), "src", "config", "surface-matrix.yml");
3827
5287
  if (!isFile2(matrix_path)) {
3828
5288
  return {
3829
5289
  id: "surface-state",
@@ -3834,7 +5294,7 @@ function _check_surface_state() {
3834
5294
  }
3835
5295
  let tools = {};
3836
5296
  try {
3837
- const raw = YAML.parse(readText(matrix_path), { version: "1.1" });
5297
+ const raw = YAML2.parse(readText(matrix_path), { version: "1.1" });
3838
5298
  const t = raw["tools"];
3839
5299
  if (t && typeof t === "object" && !Array.isArray(t)) {
3840
5300
  tools = t;
@@ -3847,7 +5307,7 @@ function _check_surface_state() {
3847
5307
  remedy: "agent-config upgrade (reinstalls the package data files)"
3848
5308
  };
3849
5309
  }
3850
- const _expand = (p) => p.startsWith("~/") ? path7.join(os3.homedir(), p.slice(2)) : path7.join(_package_root(), p);
5310
+ const _expand = (p) => p.startsWith("~/") ? path15.join(os3.homedir(), p.slice(2)) : path15.join(_package_root(), p);
3851
5311
  const violations = [];
3852
5312
  const remedies = [];
3853
5313
  let checked = 0;
@@ -3889,7 +5349,7 @@ function _check_surface_state() {
3889
5349
  }
3890
5350
  function pathExistsAny(p) {
3891
5351
  try {
3892
- fs6.statSync(p);
5352
+ fs11.statSync(p);
3893
5353
  return true;
3894
5354
  } catch {
3895
5355
  return false;
@@ -3905,13 +5365,13 @@ function _check_hook_wiring() {
3905
5365
  remedy: ""
3906
5366
  };
3907
5367
  }
3908
- const settings_path = path7.join(os3.homedir(), ".claude", "settings.json");
5368
+ const settings_path = path15.join(os3.homedir(), ".claude", "settings.json");
3909
5369
  let missing;
3910
5370
  try {
3911
5371
  const matrix = build_claude_hook_matrix(
3912
- path7.join(_package_root(), "src", "scripts", "hook_manifest.yaml")
5372
+ path15.join(_package_root(), "src", "scripts", "hook_manifest.yaml")
3913
5373
  );
3914
- const settings = pathExists(settings_path) ? JSON.parse(fs6.readFileSync(settings_path, "utf8")) : {};
5374
+ const settings = pathExists(settings_path) ? JSON.parse(fs11.readFileSync(settings_path, "utf8")) : {};
3915
5375
  const hooks = (settings["hooks"] ?? {}) || {};
3916
5376
  missing = Object.keys(matrix).filter((ev) => {
3917
5377
  const groups = hooks[ev];
@@ -3986,7 +5446,7 @@ function _check_mcp_mode(project_root) {
3986
5446
  ];
3987
5447
  const found = [];
3988
5448
  for (const [rel, label] of candidates) {
3989
- const p = path7.join(project_root, rel);
5449
+ const p = path15.join(project_root, rel);
3990
5450
  if (!pathExists(p)) {
3991
5451
  continue;
3992
5452
  }
@@ -4018,7 +5478,7 @@ function _check_mcp_mode(project_root) {
4018
5478
  };
4019
5479
  }
4020
5480
  function _check_offline_readiness() {
4021
- const script = path7.join(_package_root(), "src", "scripts", "hermetic-install.sh");
5481
+ const script = path15.join(_package_root(), "src", "scripts", "hermetic-install.sh");
4022
5482
  if (!pathExists(script)) {
4023
5483
  return {
4024
5484
  id: "offline-readiness",
@@ -4076,7 +5536,7 @@ function _check_stale_orphans() {
4076
5536
  (a, b) => a < b ? -1 : a > b ? 1 : 0
4077
5537
  );
4078
5538
  for (const root_name of ownedSorted) {
4079
- const root = path7.join(anchor, root_name);
5539
+ const root = path15.join(anchor, root_name);
4080
5540
  if (!isDir(root)) {
4081
5541
  continue;
4082
5542
  }
@@ -4091,7 +5551,7 @@ function _check_stale_orphans() {
4091
5551
  if (rel === null) {
4092
5552
  continue;
4093
5553
  }
4094
- const relPosix = rel.split(path7.sep).join("/");
5554
+ const relPosix = rel.split(path15.sep).join("/");
4095
5555
  if (recorded_set.has(relPosix)) {
4096
5556
  continue;
4097
5557
  }
@@ -4146,14 +5606,14 @@ function _check_rule_scope_drift(project_root) {
4146
5606
  let rules_dir = null;
4147
5607
  let found = 0;
4148
5608
  for (const rel of _RULE_PROJECTION_DIRS) {
4149
- const cand = path7.join(project_root, rel);
5609
+ const cand = path15.join(project_root, rel);
4150
5610
  if (!isDir(cand)) {
4151
5611
  continue;
4152
5612
  }
4153
5613
  let count = 0;
4154
5614
  try {
4155
- for (const name of fs6.readdirSync(cand)) {
4156
- if (name.endsWith(".md") && isFile2(path7.join(cand, name))) {
5615
+ for (const name of fs11.readdirSync(cand)) {
5616
+ if (name.endsWith(".md") && isFile2(path15.join(cand, name))) {
4157
5617
  count += 1;
4158
5618
  }
4159
5619
  }
@@ -4207,14 +5667,14 @@ function _check_rule_scope_drift(project_root) {
4207
5667
  };
4208
5668
  }
4209
5669
  function _check_duplicate_scope_rules(project_root, userRulesDirOverride) {
4210
- const user_rules_dir = userRulesDirOverride ?? path7.join(os3.homedir(), ".claude", "rules");
5670
+ const user_rules_dir = userRulesDirOverride ?? path15.join(os3.homedir(), ".claude", "rules");
4211
5671
  let project_rules_dir = null;
4212
5672
  if (_is_source_repo(project_root)) {
4213
- const cand = path7.join(project_root, "dist", "agent-src", "rules");
5673
+ const cand = path15.join(project_root, "dist", "agent-src", "rules");
4214
5674
  if (isDir(cand)) project_rules_dir = cand;
4215
5675
  } else {
4216
5676
  for (const rel of _RULE_PROJECTION_DIRS) {
4217
- const cand = path7.join(project_root, rel);
5677
+ const cand = path15.join(project_root, rel);
4218
5678
  if (isDir(cand)) {
4219
5679
  project_rules_dir = cand;
4220
5680
  break;
@@ -4283,7 +5743,7 @@ function _check_mcp_beta_readiness(project_root) {
4283
5743
  }
4284
5744
  const pending = [];
4285
5745
  for (const [gate_id, rel] of MCP_BETA_GATES) {
4286
- if (!pathExists(path7.join(project_root, rel))) {
5746
+ if (!pathExists(path15.join(project_root, rel))) {
4287
5747
  pending.push(`${gate_id} (${rel})`);
4288
5748
  }
4289
5749
  }
@@ -4304,7 +5764,7 @@ function _check_mcp_beta_readiness(project_root) {
4304
5764
  }
4305
5765
  function _check_tier_usage_readiness(project_root) {
4306
5766
  const settings_file = project_settings_path(project_root);
4307
- let log_path = path7.join(project_root, ".agent-tier-usage.jsonl");
5767
+ let log_path = path15.join(project_root, ".agent-tier-usage.jsonl");
4308
5768
  let enabled = false;
4309
5769
  if (isFile2(settings_file)) {
4310
5770
  let raw;
@@ -4323,7 +5783,7 @@ function _check_tier_usage_readiness(project_root) {
4323
5783
  const outputRaw = tu["output"];
4324
5784
  const output = typeof outputRaw === "object" && outputRaw !== null && !Array.isArray(outputRaw) ? outputRaw : {};
4325
5785
  if (typeof output["path"] === "string" && output["path"].trim()) {
4326
- log_path = path7.join(project_root, output["path"].trim());
5786
+ log_path = path15.join(project_root, output["path"].trim());
4327
5787
  }
4328
5788
  const val = tu["enabled"];
4329
5789
  if (typeof val === "boolean") {
@@ -4348,7 +5808,7 @@ function _check_tier_usage_readiness(project_root) {
4348
5808
  return {
4349
5809
  id: "tier-usage-readiness",
4350
5810
  status: "warn",
4351
- message: `tier-usage telemetry on but ${path7.basename(log_path)} not yet written \u2014 no signal accumulated`,
5811
+ message: `tier-usage telemetry on but ${path15.basename(log_path)} not yet written \u2014 no signal accumulated`,
4352
5812
  remedy: "run any tracked command to seed the log; the dispatcher writes one record per invocation"
4353
5813
  };
4354
5814
  }
@@ -4363,7 +5823,7 @@ function _check_tier_usage_readiness(project_root) {
4363
5823
  return {
4364
5824
  id: "tier-usage-readiness",
4365
5825
  status: "fail",
4366
- message: `cannot read ${path7.basename(log_path)}: ${osErrorStr(exc)}`,
5826
+ message: `cannot read ${path15.basename(log_path)}: ${osErrorStr(exc)}`,
4367
5827
  remedy: "fix permissions on the tier-usage log"
4368
5828
  };
4369
5829
  }
@@ -4394,7 +5854,7 @@ function _check_tier_usage_readiness(project_root) {
4394
5854
  return {
4395
5855
  id: "tier-usage-readiness",
4396
5856
  status: "fail",
4397
- message: `${total} record(s) in ${path7.basename(log_path)} but 0 passed the privacy floor \u2014 report would refuse to render`,
5857
+ message: `${total} record(s) in ${path15.basename(log_path)} but 0 passed the privacy floor \u2014 report would refuse to render`,
4398
5858
  remedy: "inspect the log; the dispatcher is writing records the contract forbids (paths, argv, message bodies)"
4399
5859
  };
4400
5860
  }
@@ -4402,19 +5862,19 @@ function _check_tier_usage_readiness(project_root) {
4402
5862
  return {
4403
5863
  id: "tier-usage-readiness",
4404
5864
  status: "warn",
4405
- message: `${path7.basename(log_path)} present but empty \u2014 no signal yet`,
5865
+ message: `${path15.basename(log_path)} present but empty \u2014 no signal yet`,
4406
5866
  remedy: "run any tracked command to seed the log"
4407
5867
  };
4408
5868
  }
4409
5869
  return {
4410
5870
  id: "tier-usage-readiness",
4411
5871
  status: "ok",
4412
- message: `${valid} record(s) past the privacy floor in ${path7.basename(log_path)} \u2014 retiering signal available`,
5872
+ message: `${valid} record(s) past the privacy floor in ${path15.basename(log_path)} \u2014 retiering signal available`,
4413
5873
  remedy: ""
4414
5874
  };
4415
5875
  }
4416
5876
  function readText0(p) {
4417
- return fs6.readFileSync(p, "utf-8");
5877
+ return fs11.readFileSync(p, "utf-8");
4418
5878
  }
4419
5879
  function osErrorStr(exc) {
4420
5880
  if (exc && typeof exc === "object" && "message" in exc) {
@@ -4587,7 +6047,7 @@ function _epoch_seconds(value) {
4587
6047
  function _codex_auth_expiry(auth_path) {
4588
6048
  let data;
4589
6049
  try {
4590
- data = JSON.parse(fs6.readFileSync(auth_path, "utf-8"));
6050
+ data = JSON.parse(fs11.readFileSync(auth_path, "utf-8"));
4591
6051
  } catch {
4592
6052
  return null;
4593
6053
  }
@@ -4733,7 +6193,7 @@ function _check_team(project_root) {
4733
6193
  if (binary_missing) {
4734
6194
  remedies.push("install the codex CLI: `npm install -g @openai/codex`");
4735
6195
  }
4736
- const auth_path = path7.join(_codex_home(), "auth.json");
6196
+ const auth_path = path15.join(_codex_home(), "auth.json");
4737
6197
  const authed = pathExists(auth_path);
4738
6198
  let auth_str;
4739
6199
  if (!authed) {
@@ -4821,7 +6281,7 @@ function _check_unsupported_combos(manifest) {
4821
6281
  };
4822
6282
  }
4823
6283
  function _wizard_state_path() {
4824
- return path7.join(event4u_root(), "state", "wizard-state.json");
6284
+ return path15.join(event4u_root(), "state", "wizard-state.json");
4825
6285
  }
4826
6286
  function _check_wizard_state() {
4827
6287
  const state_pth = _wizard_state_path();
@@ -4901,7 +6361,7 @@ function _check_wizard_state() {
4901
6361
  };
4902
6362
  }
4903
6363
  function _check_settings_review_pending() {
4904
- const delta_pth = path7.join(event4u_root(), "state", "settings-delta.json");
6364
+ const delta_pth = path15.join(event4u_root(), "state", "settings-delta.json");
4905
6365
  if (!pathExists(delta_pth)) {
4906
6366
  return {
4907
6367
  id: "settings-review-pending",
@@ -4927,7 +6387,7 @@ function _check_settings_review_pending() {
4927
6387
  }
4928
6388
  function _check_memory_merge_union(project_root) {
4929
6389
  const remedy = "run: npx tsx src/scripts/sync_gitattributes.ts (or `agent-config refresh --project`)";
4930
- const target = path7.join(project_root, DEFAULT_GITATTRIBUTES);
6390
+ const target = path15.join(project_root, DEFAULT_GITATTRIBUTES);
4931
6391
  if (!pathExists(target)) {
4932
6392
  return {
4933
6393
  id: "memory-merge-union",
@@ -5254,13 +6714,15 @@ function _emit_text(project_root, missing, modified, foreign, tag_drift) {
5254
6714
  }
5255
6715
  var PROG = "agent-config doctor";
5256
6716
  var USAGE = `usage: ${PROG} [-h] [--project PROJECT] [--json] [--ci] [--check ID]
5257
- [--trace-root] [--context] [--repair ID]
6717
+ [--trace-root] [--context] [--anatomy]
6718
+ [--repair ID]
5258
6719
  `;
5259
6720
  var _STORE_TRUE_FLAGS = {
5260
6721
  "--json": "json",
5261
6722
  "--ci": "ci",
5262
6723
  "--trace-root": "trace_root",
5263
- "--context": "context"
6724
+ "--context": "context",
6725
+ "--anatomy": "anatomy"
5264
6726
  };
5265
6727
  var _VALUE_FLAGS = {
5266
6728
  "--project": "project",
@@ -5273,7 +6735,7 @@ function _argError(msg) {
5273
6735
  `);
5274
6736
  throw new ArgparseExit(2);
5275
6737
  }
5276
- function _parse(argv) {
6738
+ function _parse2(argv) {
5277
6739
  const opts = {
5278
6740
  project: null,
5279
6741
  json: false,
@@ -5281,6 +6743,7 @@ function _parse(argv) {
5281
6743
  check: null,
5282
6744
  trace_root: false,
5283
6745
  context: false,
6746
+ anatomy: false,
5284
6747
  repair: null
5285
6748
  };
5286
6749
  const positionals = [];
@@ -5397,6 +6860,42 @@ function _run_context(opts) {
5397
6860
  }
5398
6861
  return 0;
5399
6862
  }
6863
+ function _run_anatomy(opts) {
6864
+ const census = preamble_byte_census_exports;
6865
+ const economy = dispatch_economy_report_exports;
6866
+ const byteCensus = census.buildReport(census.parseArgs([]));
6867
+ let economyReport = null;
6868
+ let economyError = null;
6869
+ try {
6870
+ economyReport = economy.buildReport({
6871
+ root: economy.DEFAULT_PROJECTS_ROOT,
6872
+ auditDir: path15.join(process2.cwd(), economy.DEFAULT_AUDIT_DIR),
6873
+ maxAgeDays: 14
6874
+ });
6875
+ } catch (err) {
6876
+ economyError = err instanceof Error ? err.message : String(err);
6877
+ }
6878
+ if (opts.json) {
6879
+ print(
6880
+ _jsonDumpsIndentAscii(
6881
+ {
6882
+ preamble_byte_census: byteCensus,
6883
+ dispatch_economy: economyReport,
6884
+ dispatch_economy_unavailable: economyError
6885
+ },
6886
+ 2
6887
+ )
6888
+ );
6889
+ return 0;
6890
+ }
6891
+ 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");
6892
+ print(census.renderText(byteCensus));
6893
+ print("");
6894
+ print(
6895
+ economyReport !== null ? economy.renderText(economyReport) : `dispatch-economy report unavailable: ${economyError}`
6896
+ );
6897
+ return 0;
6898
+ }
5400
6899
  function _run_repair(opts) {
5401
6900
  const target = opts.repair;
5402
6901
  if (target === "wizard-state") {
@@ -5409,7 +6908,7 @@ function _run_repair(opts) {
5409
6908
  };
5410
6909
  if (exists2) {
5411
6910
  try {
5412
- fs6.unlinkSync(state_pth);
6911
+ fs11.unlinkSync(state_pth);
5413
6912
  } catch (exc) {
5414
6913
  payload["action"] = "error";
5415
6914
  payload["error"] = osErrorStr(exc);
@@ -5435,8 +6934,8 @@ function _run_repair(opts) {
5435
6934
  eprint(`\u274C doctor: unknown repair target ${pyRepr(target)}`);
5436
6935
  return 2;
5437
6936
  }
5438
- function main(argv = null) {
5439
- const opts = _parse(argv !== null ? Array.from(argv) : process2.argv.slice(2));
6937
+ function main4(argv = null) {
6938
+ const opts = _parse2(argv !== null ? Array.from(argv) : process2.argv.slice(2));
5440
6939
  if (opts.ci) {
5441
6940
  opts.json = true;
5442
6941
  }
@@ -5449,6 +6948,9 @@ function main(argv = null) {
5449
6948
  if (opts.context) {
5450
6949
  return _run_context(opts);
5451
6950
  }
6951
+ if (opts.anatomy) {
6952
+ return _run_anatomy(opts);
6953
+ }
5452
6954
  let project_root;
5453
6955
  let origin;
5454
6956
  try {
@@ -5500,25 +7002,25 @@ function main(argv = null) {
5500
7002
  }
5501
7003
  return drift_present ? 1 : 0;
5502
7004
  }
5503
- function _isCliEntry() {
7005
+ function _isCliEntry2() {
5504
7006
  if (process2.argv[1] === void 0) {
5505
7007
  return false;
5506
7008
  }
5507
- const argvUrl = pathToFileURL(path7.resolve(process2.argv[1])).href;
7009
+ const argvUrl = pathToFileURL4(path15.resolve(process2.argv[1])).href;
5508
7010
  if (import.meta.url === argvUrl) {
5509
7011
  return true;
5510
7012
  }
5511
7013
  try {
5512
- const here = fs6.realpathSync(fileURLToPath2(import.meta.url));
5513
- const argv = fs6.realpathSync(path7.resolve(process2.argv[1]));
7014
+ const here = fs11.realpathSync(fileURLToPath6(import.meta.url));
7015
+ const argv = fs11.realpathSync(path15.resolve(process2.argv[1]));
5514
7016
  return here === argv;
5515
7017
  } catch {
5516
7018
  return false;
5517
7019
  }
5518
7020
  }
5519
- if (_isCliEntry() || process2.argv[1] === _HERE2) {
7021
+ if (_isCliEntry2() || process2.argv[1] === _HERE6) {
5520
7022
  try {
5521
- process2.exitCode = main(process2.argv.slice(2));
7023
+ process2.exitCode = main4(process2.argv.slice(2));
5522
7024
  } catch (e) {
5523
7025
  if (e instanceof ArgparseExit) {
5524
7026
  process2.exitCode = e.code;
@@ -5529,6 +7031,11 @@ if (_isCliEntry() || process2.argv[1] === _HERE2) {
5529
7031
  }
5530
7032
 
5531
7033
  export {
7034
+ comparePair,
7035
+ splitFrontmatter,
7036
+ proseEqual,
7037
+ frontmatterPaths,
7038
+ censusRuleDir,
5532
7039
  ArgparseExit,
5533
7040
  _jsonDumpsIndentAscii,
5534
7041
  NO_FRONTMATTER,
@@ -5589,9 +7096,9 @@ export {
5589
7096
  _emit_json,
5590
7097
  _emit_checks_text,
5591
7098
  _emit_text,
5592
- _parse,
7099
+ _parse2 as _parse,
5593
7100
  _run_trace_root,
5594
7101
  _run_context,
5595
7102
  _run_repair,
5596
- main
7103
+ main4 as main
5597
7104
  };