@codeledger/cli 0.9.5 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/bin/codeledger-open.cjs +1 -1
  2. package/dist/commands/activate.d.ts.map +1 -1
  3. package/dist/commands/activate.js +36 -1
  4. package/dist/commands/activate.js.map +1 -1
  5. package/dist/commands/audit.d.ts.map +1 -1
  6. package/dist/commands/audit.js +48 -1
  7. package/dist/commands/audit.js.map +1 -1
  8. package/dist/commands/coach.d.ts +11 -0
  9. package/dist/commands/coach.d.ts.map +1 -0
  10. package/dist/commands/coach.js +169 -0
  11. package/dist/commands/coach.js.map +1 -0
  12. package/dist/commands/ecl.d.ts +11 -0
  13. package/dist/commands/ecl.d.ts.map +1 -0
  14. package/dist/commands/ecl.js +109 -0
  15. package/dist/commands/ecl.js.map +1 -0
  16. package/dist/commands/evidence.d.ts +2 -0
  17. package/dist/commands/evidence.d.ts.map +1 -0
  18. package/dist/commands/evidence.js +53 -0
  19. package/dist/commands/evidence.js.map +1 -0
  20. package/dist/commands/fleet.d.ts +17 -0
  21. package/dist/commands/fleet.d.ts.map +1 -0
  22. package/dist/commands/fleet.js +682 -0
  23. package/dist/commands/fleet.js.map +1 -0
  24. package/dist/commands/graph.d.ts +6 -0
  25. package/dist/commands/graph.d.ts.map +1 -1
  26. package/dist/commands/graph.js +77 -4
  27. package/dist/commands/graph.js.map +1 -1
  28. package/dist/commands/hotspots.d.ts +2 -0
  29. package/dist/commands/hotspots.d.ts.map +1 -0
  30. package/dist/commands/hotspots.js +20 -0
  31. package/dist/commands/hotspots.js.map +1 -0
  32. package/dist/commands/ledger.d.ts +2 -1
  33. package/dist/commands/ledger.d.ts.map +1 -1
  34. package/dist/commands/ledger.js +2 -1
  35. package/dist/commands/ledger.js.map +1 -1
  36. package/dist/commands/memory.d.ts.map +1 -1
  37. package/dist/commands/memory.js +88 -3
  38. package/dist/commands/memory.js.map +1 -1
  39. package/dist/commands/post-merge-outcome.d.ts +2 -0
  40. package/dist/commands/post-merge-outcome.d.ts.map +1 -0
  41. package/dist/commands/post-merge-outcome.js +32 -0
  42. package/dist/commands/post-merge-outcome.js.map +1 -0
  43. package/dist/commands/pr-comment.d.ts +2 -0
  44. package/dist/commands/pr-comment.d.ts.map +1 -0
  45. package/dist/commands/pr-comment.js +96 -0
  46. package/dist/commands/pr-comment.js.map +1 -0
  47. package/dist/commands/release-decision.d.ts +2 -0
  48. package/dist/commands/release-decision.d.ts.map +1 -0
  49. package/dist/commands/release-decision.js +26 -0
  50. package/dist/commands/release-decision.js.map +1 -0
  51. package/dist/commands/release-history.d.ts +2 -0
  52. package/dist/commands/release-history.d.ts.map +1 -0
  53. package/dist/commands/release-history.js +34 -0
  54. package/dist/commands/release-history.js.map +1 -0
  55. package/dist/commands/release-insights.d.ts +2 -0
  56. package/dist/commands/release-insights.d.ts.map +1 -0
  57. package/dist/commands/release-insights.js +34 -0
  58. package/dist/commands/release-insights.js.map +1 -0
  59. package/dist/commands/release-truth.d.ts +2 -0
  60. package/dist/commands/release-truth.d.ts.map +1 -0
  61. package/dist/commands/release-truth.js +15 -0
  62. package/dist/commands/release-truth.js.map +1 -0
  63. package/dist/commands/test-summary.d.ts +2 -0
  64. package/dist/commands/test-summary.d.ts.map +1 -0
  65. package/dist/commands/test-summary.js +53 -0
  66. package/dist/commands/test-summary.js.map +1 -0
  67. package/dist/commands/verify.d.ts.map +1 -1
  68. package/dist/commands/verify.js +103 -3
  69. package/dist/commands/verify.js.map +1 -1
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +221 -5
  72. package/dist/index.js.map +1 -1
  73. package/dist/pr-comment/renderer.d.ts +3 -0
  74. package/dist/pr-comment/renderer.d.ts.map +1 -0
  75. package/dist/pr-comment/renderer.js +32 -0
  76. package/dist/pr-comment/renderer.js.map +1 -0
  77. package/dist/pr-comment/templates.d.ts +4 -0
  78. package/dist/pr-comment/templates.d.ts.map +1 -0
  79. package/dist/pr-comment/templates.js +9 -0
  80. package/dist/pr-comment/templates.js.map +1 -0
  81. package/dist/pr-comment/types.d.ts +13 -0
  82. package/dist/pr-comment/types.d.ts.map +1 -0
  83. package/dist/pr-comment/types.js +2 -0
  84. package/dist/pr-comment/types.js.map +1 -0
  85. package/dist/prompt-coach/admission.d.ts +1 -1
  86. package/dist/prompt-coach/admission.d.ts.map +1 -1
  87. package/dist/prompt-coach/admission.js +4 -2
  88. package/dist/prompt-coach/admission.js.map +1 -1
  89. package/dist/prompt-coach/format.d.ts.map +1 -1
  90. package/dist/prompt-coach/format.js +28 -0
  91. package/dist/prompt-coach/format.js.map +1 -1
  92. package/dist/prompt-coach/policy.d.ts +19 -0
  93. package/dist/prompt-coach/policy.d.ts.map +1 -1
  94. package/dist/prompt-coach/policy.js +42 -9
  95. package/dist/prompt-coach/policy.js.map +1 -1
  96. package/dist/release-truth.d.ts +20 -0
  97. package/dist/release-truth.d.ts.map +1 -0
  98. package/dist/release-truth.js +114 -0
  99. package/dist/release-truth.js.map +1 -0
  100. package/package.json +17 -17
@@ -0,0 +1,682 @@
1
+ /**
2
+ * `codeledger fleet <sub>` — cross-repo enterprise insights.
3
+ *
4
+ * Phase 1: enterprise customers with multiple CodeLedger-instrumented repos
5
+ * can aggregate per-repo metrics, hotspots, and pattern adoption into a
6
+ * single fleet-wide view. The manifest is the source of truth for which
7
+ * repos belong; data is read from each repo's local `.codeledger/` directory.
8
+ *
9
+ * Subcommands:
10
+ * sync Pull manifest from a GitHub source (or local --from path)
11
+ * into the local cache at ~/.codeledger/fleet.cache.json
12
+ * status Quick per-repo health line (reachable, ECL count, FPS rate)
13
+ * aggregate Walk every repo, produce a FleetAggregateReport [--json]
14
+ */
15
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync, } from 'node:fs';
16
+ import { execFileSync } from 'node:child_process';
17
+ import { join } from 'node:path';
18
+ import { appendReleaseTruthEventSafe } from '../release-truth.js';
19
+ import { homedir } from 'node:os';
20
+ import { parseFleetManifest, aggregateFleet, aggregateReleaseTruthAcrossFleet, detectFleetAlerts } from '@codeledger/engine';
21
+ // ── Paths ─────────────────────────────────────────────────────────────────
22
+ function defaultCachePath() {
23
+ return join(homedir(), '.codeledger', 'fleet.cache.json');
24
+ }
25
+ function localManifestCandidates(cwd) {
26
+ return [
27
+ join(cwd, 'codeledger-fleet.json'),
28
+ join(cwd, '.codeledger', 'fleet.json'),
29
+ defaultCachePath(),
30
+ ];
31
+ }
32
+ function loadManifestFromPath(path) {
33
+ if (!existsSync(path)) {
34
+ return { error: `Manifest file not found: ${path}` };
35
+ }
36
+ let raw;
37
+ try {
38
+ raw = JSON.parse(readFileSync(path, 'utf-8'));
39
+ }
40
+ catch (err) {
41
+ return { error: `Failed to parse JSON at ${path}: ${err.message}` };
42
+ }
43
+ const parsed = parseFleetManifest(raw);
44
+ if (!parsed.ok) {
45
+ return { error: `Invalid manifest at ${path}: ${parsed.error}` };
46
+ }
47
+ return { manifest: parsed.manifest, source: path };
48
+ }
49
+ /**
50
+ * Resolve a fleet manifest by trying, in order:
51
+ * 1. --manifest <path> (explicit override)
52
+ * 2. ./codeledger-fleet.json
53
+ * 3. ./.codeledger/fleet.json
54
+ * 4. ~/.codeledger/fleet.cache.json (the GitHub-synced cache)
55
+ */
56
+ function resolveManifest(cwd, flags) {
57
+ if (flags['manifest']) {
58
+ return loadManifestFromPath(flags['manifest']);
59
+ }
60
+ for (const candidate of localManifestCandidates(cwd)) {
61
+ if (existsSync(candidate)) {
62
+ return loadManifestFromPath(candidate);
63
+ }
64
+ }
65
+ return {
66
+ error: 'No fleet manifest found. Provide one with --manifest <path>, ' +
67
+ 'place a codeledger-fleet.json in the current directory, or run ' +
68
+ '`codeledger fleet sync --from-github <owner/repo>` to fetch from GitHub.',
69
+ };
70
+ }
71
+ // ── Dispatcher ────────────────────────────────────────────────────────────
72
+ export async function runFleet(cwd, flags) {
73
+ const sub = flags['_sub'] ?? 'help';
74
+ switch (sub) {
75
+ case 'sync':
76
+ return runSync(cwd, flags);
77
+ case 'status':
78
+ return runStatus(cwd, flags);
79
+ case 'aggregate':
80
+ return runAggregate(cwd, flags);
81
+ case 'compare':
82
+ return runCompare(cwd, flags);
83
+ case 'hotspots':
84
+ return runHotspots(cwd, flags);
85
+ case 'dashboard':
86
+ return runDashboard(cwd, flags);
87
+ case 'insights':
88
+ return runInsights(cwd, flags);
89
+ case 'alerts':
90
+ return runAlerts(cwd, flags);
91
+ case 'help':
92
+ default:
93
+ printFleetHelp();
94
+ return;
95
+ }
96
+ }
97
+ // ── sync ──────────────────────────────────────────────────────────────────
98
+ async function runSync(_cwd, flags) {
99
+ const cachePath = defaultCachePath();
100
+ mkdirSync(join(homedir(), '.codeledger'), { recursive: true });
101
+ // Local file copy mode: --from <path>
102
+ const fromLocal = flags['from']?.trim();
103
+ if (fromLocal) {
104
+ if (!existsSync(fromLocal)) {
105
+ console.error(`Source file not found: ${fromLocal}`);
106
+ process.exit(1);
107
+ }
108
+ // Validate before copying
109
+ const validation = loadManifestFromPath(fromLocal);
110
+ if ('error' in validation) {
111
+ console.error(validation.error);
112
+ process.exit(1);
113
+ }
114
+ copyFileSync(fromLocal, cachePath);
115
+ console.log(`✓ Synced fleet manifest from ${fromLocal}`);
116
+ console.log(` Cache: ${cachePath}`);
117
+ console.log(` Repos: ${validation.manifest.repos.length}`);
118
+ return;
119
+ }
120
+ // GitHub mode: --from-github <owner/repo>[:<path>]
121
+ const fromGithub = flags['from-github']?.trim();
122
+ if (fromGithub) {
123
+ const [ownerRepo, manifestPathInRepo] = fromGithub.split(':');
124
+ if (!ownerRepo || !ownerRepo.includes('/')) {
125
+ console.error(`Invalid --from-github value "${fromGithub}". Expected "<owner>/<repo>" or "<owner>/<repo>:<path/to/manifest.json>".`);
126
+ process.exit(1);
127
+ }
128
+ const inRepoPath = manifestPathInRepo?.trim() || 'codeledger-fleet.json';
129
+ // Use `gh api` to fetch the file contents (GitHub's contents API returns base64).
130
+ let raw;
131
+ try {
132
+ const apiPath = `repos/${ownerRepo}/contents/${inRepoPath}`;
133
+ const response = execFileSync('gh', ['api', apiPath], {
134
+ encoding: 'utf-8',
135
+ stdio: ['ignore', 'pipe', 'pipe'],
136
+ });
137
+ const parsed = JSON.parse(response);
138
+ if (parsed.encoding !== 'base64' || typeof parsed.content !== 'string') {
139
+ console.error(`Unexpected GitHub contents API response shape for ${apiPath}. Expected base64-encoded content.`);
140
+ process.exit(1);
141
+ }
142
+ raw = Buffer.from(parsed.content, 'base64').toString('utf-8');
143
+ }
144
+ catch (err) {
145
+ console.error(`Failed to fetch manifest from GitHub via \`gh api\`: ${err.message}\n` +
146
+ 'Make sure the GitHub CLI is installed (`brew install gh`) and authenticated (`gh auth login`),\n' +
147
+ 'and that you have read access to the repo.');
148
+ process.exit(1);
149
+ }
150
+ // Validate before writing
151
+ let parsedRaw;
152
+ try {
153
+ parsedRaw = JSON.parse(raw);
154
+ }
155
+ catch (err) {
156
+ console.error(`Manifest at ${ownerRepo}:${inRepoPath} is not valid JSON: ${err.message}`);
157
+ process.exit(1);
158
+ }
159
+ const validation = parseFleetManifest(parsedRaw);
160
+ if (!validation.ok) {
161
+ console.error(`Invalid manifest fetched from GitHub: ${validation.error}`);
162
+ process.exit(1);
163
+ }
164
+ writeFileSync(cachePath, raw);
165
+ console.log(`✓ Synced fleet manifest from github.com/${ownerRepo}:${inRepoPath}`);
166
+ console.log(` Cache: ${cachePath}`);
167
+ console.log(` Repos: ${validation.manifest.repos.length}`);
168
+ console.log(` Name: ${validation.manifest.name}`);
169
+ return;
170
+ }
171
+ console.error('Usage:\n' +
172
+ ' codeledger fleet sync --from <path> # copy a local manifest into the cache\n' +
173
+ ' codeledger fleet sync --from-github <owner>/<repo> # fetch from <repo>/codeledger-fleet.json\n' +
174
+ ' codeledger fleet sync --from-github <owner>/<repo>:<path> # fetch from a custom path inside the repo\n' +
175
+ '\n' +
176
+ 'Recommended: keep your fleet manifest at <your-org>/.github/codeledger-fleet.json so it is\n' +
177
+ 'PR-reviewable, version-controlled, and the canonical source of truth for your enterprise fleet.');
178
+ process.exit(1);
179
+ }
180
+ // ── status ────────────────────────────────────────────────────────────────
181
+ function runStatus(cwd, flags) {
182
+ const loaded = resolveManifest(cwd, flags);
183
+ if ('error' in loaded) {
184
+ console.error(loaded.error);
185
+ process.exit(1);
186
+ }
187
+ const report = aggregateFleet(loaded.manifest);
188
+ if (flags['json'] === 'true') {
189
+ console.log(JSON.stringify({
190
+ fleet: report.fleet_name,
191
+ source: loaded.source,
192
+ repos: report.repos.map((r) => ({
193
+ id: r.id,
194
+ name: r.name,
195
+ team: r.team ?? null,
196
+ reachable: r.reachable,
197
+ unreachable_reason: r.unreachable_reason,
198
+ ecl_entries: r.ecl_entry_count,
199
+ success: r.ecl_success_count,
200
+ failure: r.ecl_failure_count,
201
+ golden_patterns: r.golden_pattern_count,
202
+ })),
203
+ }, null, 2));
204
+ return;
205
+ }
206
+ console.log('');
207
+ console.log(` CodeLedger · Fleet: ${report.fleet_name}`);
208
+ console.log(` Source: ${loaded.source}`);
209
+ console.log(` Repos: ${report.totals.total_repos} (reachable: ${report.reachable_count}, unreachable: ${report.unreachable_count})`);
210
+ console.log('');
211
+ console.log(' Per-repo status');
212
+ console.log(' ───────────────');
213
+ for (const r of report.repos) {
214
+ const icon = r.reachable ? '✓' : '✗';
215
+ const team = r.team ? `[${r.team}]` : '[_unassigned]';
216
+ if (r.reachable) {
217
+ const fps = r.ecl_entry_count > 0
218
+ ? `${Math.round((r.ecl_success_count / r.ecl_entry_count) * 100)}%`
219
+ : '—';
220
+ console.log(` ${icon} ${r.id.padEnd(20)} ${team.padEnd(24)} ECL: ${String(r.ecl_entry_count).padStart(5)} FPS: ${fps.padStart(4)} patterns: ${r.golden_pattern_count}`);
221
+ }
222
+ else {
223
+ console.log(` ${icon} ${r.id.padEnd(20)} ${team.padEnd(24)} unreachable: ${r.unreachable_reason ?? 'unknown'}`);
224
+ }
225
+ }
226
+ console.log('');
227
+ console.log(` Fleet first-pass success rate: ${(report.totals.fleet_first_pass_success_rate * 100).toFixed(1)}%`);
228
+ console.log(` Total golden patterns: ${report.totals.total_golden_patterns}`);
229
+ console.log(` Total prevented issues: ${report.totals.total_prevented_issues}`);
230
+ console.log('');
231
+ }
232
+ // ── aggregate ─────────────────────────────────────────────────────────────
233
+ function runAggregate(cwd, flags) {
234
+ const loaded = resolveManifest(cwd, flags);
235
+ if ('error' in loaded) {
236
+ console.error(loaded.error);
237
+ process.exit(1);
238
+ }
239
+ const report = aggregateFleet(loaded.manifest);
240
+ // Optional --out <path>
241
+ const outPath = flags['out']?.trim();
242
+ if (outPath) {
243
+ writeFileSync(outPath, JSON.stringify(report, null, 2));
244
+ if (flags['json'] !== 'true') {
245
+ console.log(`✓ Wrote fleet aggregate report to ${outPath}`);
246
+ console.log(` Repos: ${report.totals.total_repos}`);
247
+ console.log(` Teams: ${report.teams.length}`);
248
+ }
249
+ else {
250
+ console.log(JSON.stringify({ wrote: outPath, totals: report.totals }, null, 2));
251
+ }
252
+ return;
253
+ }
254
+ if (flags['json'] === 'true') {
255
+ console.log(JSON.stringify(report, null, 2));
256
+ return;
257
+ }
258
+ // Human-readable text output
259
+ console.log('');
260
+ console.log('══════════════════════════════════════════════════════════');
261
+ console.log(` CodeLedger · Fleet Aggregate — ${report.fleet_name}`);
262
+ console.log('══════════════════════════════════════════════════════════');
263
+ console.log('');
264
+ console.log(` Generated at: ${report.generated_at}`);
265
+ console.log(` Source: ${loaded.source}`);
266
+ console.log('');
267
+ console.log(' Totals');
268
+ console.log(' ──────');
269
+ console.log(` Repos: ${report.totals.total_repos} (reachable: ${report.reachable_count})`);
270
+ console.log(` ECL entries: ${report.totals.total_ecl_entries}`);
271
+ console.log(` Successes: ${report.totals.total_success}`);
272
+ console.log(` Failures: ${report.totals.total_failure}`);
273
+ console.log(` First-pass success rate: ${(report.totals.fleet_first_pass_success_rate * 100).toFixed(1)}%`);
274
+ console.log(` Golden patterns: ${report.totals.total_golden_patterns}`);
275
+ console.log(` Prevented issues: ${report.totals.total_prevented_issues}`);
276
+ console.log('');
277
+ console.log(' Per-team rollup');
278
+ console.log(' ───────────────');
279
+ for (const t of report.teams) {
280
+ console.log(` ${t.team.padEnd(28)} repos: ${String(t.repo_count).padStart(2)} ECL: ${String(t.total_ecl_entries).padStart(5)} FPS: ${(t.first_pass_success_rate * 100).toFixed(1).padStart(5)}% patterns: ${String(t.golden_pattern_count).padStart(4)}`);
281
+ }
282
+ console.log('');
283
+ if (report.fleet_hotspots.length > 0) {
284
+ console.log(' Top fleet hotspots');
285
+ console.log(' ──────────────────');
286
+ for (const h of report.fleet_hotspots.slice(0, 10)) {
287
+ console.log(` [${h.repo_id}] ${h.file} failures=${h.failureCount} rate=${(h.implicationRate * 100).toFixed(0)}%`);
288
+ }
289
+ console.log('');
290
+ }
291
+ }
292
+ // ── compare ───────────────────────────────────────────────────────────────
293
+ function runCompare(cwd, flags) {
294
+ const teamA = flags['team-a']?.trim() || flags['a']?.trim();
295
+ const teamB = flags['team-b']?.trim() || flags['b']?.trim();
296
+ if (!teamA || !teamB) {
297
+ console.error('Usage: codeledger fleet compare --team-a <name> --team-b <name> [--json]');
298
+ process.exit(1);
299
+ }
300
+ const loaded = resolveManifest(cwd, flags);
301
+ if ('error' in loaded) {
302
+ console.error(loaded.error);
303
+ process.exit(1);
304
+ }
305
+ const report = aggregateFleet(loaded.manifest);
306
+ const a = report.teams.find((t) => t.team === teamA);
307
+ const b = report.teams.find((t) => t.team === teamB);
308
+ if (!a || !b) {
309
+ const known = report.teams.map((t) => t.team).join(', ') || '(none)';
310
+ console.error(`One or both teams not found in fleet. Known teams: ${known}`);
311
+ process.exit(1);
312
+ }
313
+ // Build a deterministic delta table
314
+ const deltas = [
315
+ { metric: 'repos', a: a.repo_count, b: b.repo_count },
316
+ { metric: 'ECL entries', a: a.total_ecl_entries, b: b.total_ecl_entries },
317
+ { metric: 'successes', a: a.total_success, b: b.total_success },
318
+ { metric: 'failures', a: a.total_failure, b: b.total_failure },
319
+ { metric: 'first-pass success', a: a.first_pass_success_rate, b: b.first_pass_success_rate },
320
+ { metric: 'avg team score', a: a.avg_team_score, b: b.avg_team_score },
321
+ { metric: 'golden patterns', a: a.golden_pattern_count, b: b.golden_pattern_count },
322
+ { metric: 'prevented issues', a: a.prevented_issue_count, b: b.prevented_issue_count },
323
+ ];
324
+ if (flags['json'] === 'true') {
325
+ console.log(JSON.stringify({
326
+ fleet: report.fleet_name,
327
+ team_a: a,
328
+ team_b: b,
329
+ deltas: deltas.map((d) => ({ ...d, delta: d.a - d.b })),
330
+ }, null, 2));
331
+ return;
332
+ }
333
+ console.log('');
334
+ console.log(` CodeLedger · Fleet Compare — ${report.fleet_name}`);
335
+ console.log(` ${a.team} vs ${b.team}`);
336
+ console.log('');
337
+ const colW = 22;
338
+ console.log(` ${'metric'.padEnd(colW)}${a.team.padStart(14)}${b.team.padStart(14)}${'Δ (A−B)'.padStart(14)}`);
339
+ console.log(` ${'─'.repeat(colW + 14 + 14 + 14)}`);
340
+ for (const d of deltas) {
341
+ const fmt = (v) => Number.isInteger(v) ? String(v) : (v * (d.metric.includes('rate') || d.metric.includes('success') ? 100 : 1)).toFixed(1) + (d.metric.includes('success') ? '%' : '');
342
+ const isPct = d.metric === 'first-pass success';
343
+ const aVal = isPct ? `${(d.a * 100).toFixed(1)}%` : fmt(d.a);
344
+ const bVal = isPct ? `${(d.b * 100).toFixed(1)}%` : fmt(d.b);
345
+ const delta = d.a - d.b;
346
+ const deltaStr = isPct ? `${(delta * 100).toFixed(1)}%` : fmt(delta);
347
+ const sign = delta > 0 ? '+' : '';
348
+ console.log(` ${d.metric.padEnd(colW)}${aVal.padStart(14)}${bVal.padStart(14)}${(sign + deltaStr).padStart(14)}`);
349
+ }
350
+ console.log('');
351
+ // Headline insight
352
+ const fpsDelta = a.first_pass_success_rate - b.first_pass_success_rate;
353
+ if (Math.abs(fpsDelta) >= 0.05) {
354
+ const winner = fpsDelta > 0 ? a.team : b.team;
355
+ const margin = Math.abs(fpsDelta) * 100;
356
+ console.log(` ▲ ${winner} has ${margin.toFixed(1)} pp higher first-pass success rate.`);
357
+ console.log('');
358
+ }
359
+ }
360
+ // ── hotspots ──────────────────────────────────────────────────────────────
361
+ function runHotspots(cwd, flags) {
362
+ const top = parseInt(flags['top'] ?? '10', 10);
363
+ if (!Number.isFinite(top) || top <= 0) {
364
+ console.error('--top must be a positive integer.');
365
+ process.exit(1);
366
+ }
367
+ const loaded = resolveManifest(cwd, flags);
368
+ if ('error' in loaded) {
369
+ console.error(loaded.error);
370
+ process.exit(1);
371
+ }
372
+ const report = aggregateFleet(loaded.manifest);
373
+ const slice = report.fleet_hotspots.slice(0, top);
374
+ if (flags['json'] === 'true') {
375
+ console.log(JSON.stringify({ fleet: report.fleet_name, top, hotspots: slice }, null, 2));
376
+ return;
377
+ }
378
+ console.log('');
379
+ console.log(` CodeLedger · Fleet Hotspots — ${report.fleet_name} (top ${top})`);
380
+ console.log('');
381
+ if (slice.length === 0) {
382
+ console.log(' No hotspots detected across the fleet.');
383
+ console.log('');
384
+ return;
385
+ }
386
+ const fileW = Math.max(20, Math.min(60, Math.max(...slice.map((h) => h.file.length))));
387
+ console.log(` ${'#'.padStart(3)} ${'repo'.padEnd(20)} ${'file'.padEnd(fileW)} ${'fail'.padStart(5)} ${'rate'.padStart(6)}`);
388
+ console.log(` ${'─'.repeat(3 + 2 + 20 + 2 + fileW + 2 + 5 + 2 + 6)}`);
389
+ for (const [i, h] of slice.entries()) {
390
+ const file = h.file.length > fileW ? '…' + h.file.slice(-fileW + 1) : h.file;
391
+ console.log(` ${String(i + 1).padStart(3)} ${h.repo_id.padEnd(20)} ${file.padEnd(fileW)} ${String(h.failureCount).padStart(5)} ${(h.implicationRate * 100).toFixed(0).padStart(5)}%`);
392
+ }
393
+ console.log('');
394
+ }
395
+ // ── dashboard ─────────────────────────────────────────────────────────────
396
+ function runDashboard(cwd, flags) {
397
+ const loaded = resolveManifest(cwd, flags);
398
+ if ('error' in loaded) {
399
+ console.error(loaded.error);
400
+ process.exit(1);
401
+ }
402
+ const report = aggregateFleet(loaded.manifest);
403
+ const outPath = (flags['out']?.trim()) || join(cwd, '.codeledger', 'fleet-dashboard.html');
404
+ mkdirSync(join(outPath, '..'), { recursive: true });
405
+ const html = renderFleetDashboardHtml(report);
406
+ writeFileSync(outPath, html);
407
+ console.log(`✓ Wrote fleet dashboard to ${outPath}`);
408
+ console.log(` Open with: open ${outPath}`);
409
+ }
410
+ export function renderFleetDashboardHtml(report) {
411
+ const esc = (s) => s
412
+ .replace(/&/g, '&amp;')
413
+ .replace(/</g, '&lt;')
414
+ .replace(/>/g, '&gt;')
415
+ .replace(/"/g, '&quot;')
416
+ .replace(/'/g, '&#39;');
417
+ const pct = (n) => `${(n * 100).toFixed(1)}%`;
418
+ const t = report.totals;
419
+ const manifest = { schema_version: 'codeledger/fleet/v1', name: report.fleet_name, repos: report.repos.map((repo) => ({ id: repo.id, local_path: repo.local_path, team: repo.team })) };
420
+ const releaseInsights = aggregateReleaseTruthAcrossFleet(manifest, '7d');
421
+ const releaseAlerts = detectFleetAlerts(aggregateReleaseTruthAcrossFleet(manifest, '24h'), aggregateReleaseTruthAcrossFleet(manifest, '7d'), aggregateReleaseTruthAcrossFleet(manifest, '7d'), aggregateReleaseTruthAcrossFleet(manifest, '30d'));
422
+ const repoRows = report.repos
423
+ .map((r) => {
424
+ const fps = r.ecl_entry_count > 0 ? pct(r.ecl_success_count / r.ecl_entry_count) : '—';
425
+ const status = r.reachable
426
+ ? '<span class="tag tag-ok">reachable</span>'
427
+ : '<span class="tag tag-bad">unreachable</span>';
428
+ return `<tr>
429
+ <td>${esc(r.id)}</td>
430
+ <td>${esc(r.team ?? '_unassigned')}</td>
431
+ <td>${status}</td>
432
+ <td class="num">${r.ecl_entry_count}</td>
433
+ <td class="num">${fps}</td>
434
+ <td class="num">${r.golden_pattern_count}</td>
435
+ <td class="num">${r.prevented_issue_count}</td>
436
+ </tr>`;
437
+ })
438
+ .join('\n');
439
+ const teamRows = report.teams
440
+ .map((tm) => `<tr>
441
+ <td>${esc(tm.team)}</td>
442
+ <td class="num">${tm.repo_count}</td>
443
+ <td class="num">${tm.total_ecl_entries}</td>
444
+ <td class="num">${pct(tm.first_pass_success_rate)}</td>
445
+ <td class="num">${tm.golden_pattern_count}</td>
446
+ <td class="num">${tm.prevented_issue_count}</td>
447
+ </tr>`)
448
+ .join('\n');
449
+ const hotspotRows = report.fleet_hotspots
450
+ .slice(0, 25)
451
+ .map((h, i) => `<tr>
452
+ <td class="num">${i + 1}</td>
453
+ <td>${esc(h.repo_id)}</td>
454
+ <td><code>${esc(h.file)}</code></td>
455
+ <td class="num">${h.failureCount}</td>
456
+ <td class="num">${pct(h.implicationRate)}</td>
457
+ </tr>`)
458
+ .join('\n');
459
+ return `<!doctype html>
460
+ <html lang="en">
461
+ <head>
462
+ <meta charset="utf-8">
463
+ <title>CodeLedger Fleet — ${esc(report.fleet_name)}</title>
464
+ <style>
465
+ :root {
466
+ --bg: #0b0e14;
467
+ --panel: #161b22;
468
+ --border: #2a313c;
469
+ --fg: #e6edf3;
470
+ --muted: #8b949e;
471
+ --accent: #58a6ff;
472
+ --ok: #3fb950;
473
+ --bad: #f85149;
474
+ }
475
+ * { box-sizing: border-box; }
476
+ body { margin: 0; padding: 2rem; background: var(--bg); color: var(--fg);
477
+ font: 14px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; }
478
+ h1 { margin: 0 0 0.25rem; font-size: 1.5rem; }
479
+ h2 { margin: 2rem 0 0.5rem; font-size: 1.05rem; color: var(--muted);
480
+ text-transform: uppercase; letter-spacing: 0.05em; }
481
+ .meta { color: var(--muted); font-size: 12px; margin-bottom: 1.5rem; }
482
+ .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.75rem;
483
+ margin: 1rem 0 0.5rem; }
484
+ .card { background: var(--panel); border: 1px solid var(--border);
485
+ border-radius: 8px; padding: 0.85rem 1rem; }
486
+ .card .label { color: var(--muted); font-size: 11px; text-transform: uppercase;
487
+ letter-spacing: 0.05em; }
488
+ .card .value { font-size: 1.75rem; font-weight: 600; margin-top: 0.25rem; }
489
+ table { width: 100%; border-collapse: collapse; background: var(--panel);
490
+ border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
491
+ th, td { padding: 0.5rem 0.75rem; text-align: left; border-bottom: 1px solid var(--border); }
492
+ th { background: #1a212b; color: var(--muted); font-weight: 500;
493
+ text-transform: uppercase; font-size: 11px; letter-spacing: 0.05em; }
494
+ td.num { text-align: right; font-variant-numeric: tabular-nums; }
495
+ tr:last-child td { border-bottom: none; }
496
+ code { font: 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--accent); }
497
+ .tag { display: inline-block; padding: 1px 8px; border-radius: 999px;
498
+ font-size: 11px; font-weight: 500; }
499
+ .tag-ok { background: rgba(63, 185, 80, 0.15); color: var(--ok); }
500
+ .tag-bad { background: rgba(248, 81, 73, 0.15); color: var(--bad); }
501
+ footer { margin-top: 2rem; color: var(--muted); font-size: 11px; }
502
+ </style>
503
+ </head>
504
+ <body>
505
+ <h1>CodeLedger Fleet · ${esc(report.fleet_name)}</h1>
506
+ <div class="meta">Generated ${esc(report.generated_at)} · ${t.total_repos} repos (${report.reachable_count} reachable, ${report.unreachable_count} unreachable)</div>
507
+
508
+ <div class="grid">
509
+ <div class="card"><div class="label">Total Repos</div><div class="value">${t.total_repos}</div></div>
510
+ <div class="card"><div class="label">ECL Entries</div><div class="value">${t.total_ecl_entries.toLocaleString()}</div></div>
511
+ <div class="card"><div class="label">First-Pass Success</div><div class="value">${pct(t.fleet_first_pass_success_rate)}</div></div>
512
+ <div class="card"><div class="label">Prevented Issues</div><div class="value">${t.total_prevented_issues}</div></div>
513
+ </div>
514
+
515
+ <h2>Per-team rollup</h2>
516
+ <table>
517
+ <thead><tr>
518
+ <th>team</th><th>repos</th><th>ECL</th><th>FPS</th><th>patterns</th><th>prevented</th>
519
+ </tr></thead>
520
+ <tbody>${teamRows || '<tr><td colspan="6">No teams.</td></tr>'}</tbody>
521
+ </table>
522
+
523
+ <h2>Per-repo status</h2>
524
+ <table>
525
+ <thead><tr>
526
+ <th>id</th><th>team</th><th>status</th><th>ECL</th><th>FPS</th><th>patterns</th><th>prevented</th>
527
+ </tr></thead>
528
+ <tbody>${repoRows || '<tr><td colspan="7">No repos.</td></tr>'}</tbody>
529
+ </table>
530
+
531
+ <h2>Top fleet hotspots</h2>
532
+ <table>
533
+ <thead><tr>
534
+ <th>#</th><th>repo</th><th>file</th><th>failures</th><th>rate</th>
535
+ </tr></thead>
536
+ <tbody>${hotspotRows || '<tr><td colspan="5">No hotspots detected.</td></tr>'}</tbody>
537
+ </table>
538
+
539
+ <h2>Release Truth Insights (7d)</h2>
540
+ <p>${esc(releaseInsights.narrative.summary)}</p>
541
+ <table>
542
+ <thead><tr><th>Pass</th><th>Warn</th><th>Fail</th><th>High risk repos</th></tr></thead>
543
+ <tbody><tr><td class="num">${pct(releaseInsights.rollup.overall_pass_rate)}</td><td class="num">${pct(releaseInsights.rollup.overall_warn_rate)}</td><td class="num">${pct(releaseInsights.rollup.overall_fail_rate)}</td><td class="num">${releaseInsights.rollup.repos_high_risk}</td></tr></tbody>
544
+ </table>
545
+
546
+ <h2>Manager recommendations</h2>
547
+ <ul>${releaseInsights.narrative.recommendations.map((item) => `<li>${esc(item)}</li>`).join('')}</ul>
548
+
549
+ <h2>Risk Alerts</h2>
550
+ <table>
551
+ <thead><tr><th>severity</th><th>type</th><th>scope</th><th>reason</th></tr></thead>
552
+ <tbody>${releaseAlerts.map((a) => `<tr><td>${esc(a.severity)}</td><td>${esc(a.alert_type)}</td><td>${esc(a.scope.repo)}</td><td>${esc(a.reason)}</td></tr>`).join('') || '<tr><td colspan="4">No active alerts.</td></tr>'}</tbody>
553
+ </table>
554
+
555
+ <footer>CodeLedger Fleet · cross-repo enterprise insights · schema ${esc(report.schema_version)}</footer>
556
+ </body>
557
+ </html>
558
+ `;
559
+ }
560
+ function runInsights(cwd, flags) {
561
+ const loaded = resolveManifest(cwd, flags);
562
+ if ('error' in loaded) {
563
+ console.error(loaded.error);
564
+ process.exit(1);
565
+ }
566
+ const window = flags['window'] ?? '7d';
567
+ const insights = aggregateReleaseTruthAcrossFleet(loaded.manifest, window);
568
+ if (flags['json'] === 'true') {
569
+ console.log(JSON.stringify(insights, null, 2));
570
+ return;
571
+ }
572
+ console.log('');
573
+ console.log(` Fleet Release Insights (${window})`);
574
+ console.log(` Repos: ${insights.rollup.repo_count}`);
575
+ console.log(` PASS: ${(insights.rollup.overall_pass_rate * 100).toFixed(1)}%`);
576
+ console.log(` WARN: ${(insights.rollup.overall_warn_rate * 100).toFixed(1)}%`);
577
+ console.log(` FAIL: ${(insights.rollup.overall_fail_rate * 100).toFixed(1)}%`);
578
+ console.log(` High risk repos: ${insights.rollup.repos_high_risk}`);
579
+ console.log('');
580
+ }
581
+ function runAlerts(cwd, flags) {
582
+ const loaded = resolveManifest(cwd, flags);
583
+ if ('error' in loaded) {
584
+ console.error(loaded.error);
585
+ process.exit(1);
586
+ }
587
+ const current24h = aggregateReleaseTruthAcrossFleet(loaded.manifest, '24h');
588
+ const baseline7d = aggregateReleaseTruthAcrossFleet(loaded.manifest, '7d');
589
+ const current7d = baseline7d;
590
+ const baseline30d = aggregateReleaseTruthAcrossFleet(loaded.manifest, '30d');
591
+ const alerts = detectFleetAlerts(current24h, baseline7d, current7d, baseline30d);
592
+ for (const alert of alerts) {
593
+ const targetRepo = loaded.manifest.repos.find((repo) => repo.id === alert.scope.repo);
594
+ if (targetRepo) {
595
+ appendReleaseTruthEventSafe(targetRepo.local_path, {
596
+ event_type: 'RISK_ALERT',
597
+ timestamp: alert.timestamp,
598
+ repo_id: alert.scope.repo,
599
+ alert,
600
+ });
601
+ }
602
+ }
603
+ if (flags['json'] === 'true') {
604
+ console.log(JSON.stringify({ count: alerts.length, alerts }, null, 2));
605
+ return;
606
+ }
607
+ console.log('');
608
+ console.log(' Fleet Risk Alerts');
609
+ if (alerts.length === 0) {
610
+ console.log(' No active alerts.');
611
+ console.log('');
612
+ return;
613
+ }
614
+ for (const alert of alerts) {
615
+ console.log(` - [${alert.severity}] ${alert.alert_type} (${alert.scope.repo}) ${alert.reason}`);
616
+ }
617
+ console.log('');
618
+ }
619
+ // ── help ──────────────────────────────────────────────────────────────────
620
+ function printFleetHelp() {
621
+ console.log(`
622
+ codeledger fleet <subcommand>
623
+
624
+ Cross-repo enterprise insights. Aggregates per-repo CodeLedger metrics
625
+ into a single fleet-wide view (Phase 1: same trust boundary, multiple repos).
626
+
627
+ Subcommands:
628
+ sync Pull a fleet manifest into the local cache
629
+ --from <path> Copy a local manifest
630
+ --from-github <owner>/<repo> Fetch via gh api
631
+ --from-github <owner>/<repo>:<path> Custom path in repo
632
+ Cache: ~/.codeledger/fleet.cache.json
633
+ Recommended: store at <your-org>/.github/codeledger-fleet.json
634
+
635
+ status Per-repo health line (reachable, ECL count, FPS, patterns)
636
+ [--manifest <path>] Override manifest resolution
637
+ [--json]
638
+
639
+ aggregate Walk every repo, produce a FleetAggregateReport
640
+ [--manifest <path>]
641
+ [--out <path>] Write report to file
642
+ [--json]
643
+
644
+ compare Side-by-side comparison of two teams in the fleet
645
+ --team-a <name> --team-b <name>
646
+ [--manifest <path>] [--json]
647
+ Surfaces deltas in ECL volume, first-pass success
648
+ rate, golden patterns, and prevented issues.
649
+
650
+ hotspots Top failing files unioned across the entire fleet
651
+ [--top N] Default: 10
652
+ [--manifest <path>] [--json]
653
+
654
+ dashboard Render a static HTML fleet dashboard
655
+ [--manifest <path>]
656
+ [--out <path>] Default: .codeledger/fleet-dashboard.html
657
+
658
+ insights Release-truth fleet rollup (24h|7d|30d)
659
+ [--window 24h|7d|30d] [--json]
660
+
661
+ alerts Deterministic risk spike + concentration alerts
662
+ [--json]
663
+
664
+ Manifest resolution order:
665
+ 1. --manifest <path>
666
+ 2. ./codeledger-fleet.json
667
+ 3. ./.codeledger/fleet.json
668
+ 4. ~/.codeledger/fleet.cache.json (synced from GitHub)
669
+
670
+ Manifest schema:
671
+ {
672
+ "schema_version": "codeledger/fleet/v1",
673
+ "name": "Acme Engineering",
674
+ "repos": [
675
+ { "id": "payments", "local_path": "/repos/payments-service", "team": "fintech-alpha", "github_url": "..." },
676
+ { "id": "checkout", "local_path": "/repos/checkout-service", "team": "fintech-alpha" },
677
+ { "id": "design-sys", "local_path": "/repos/design-system", "team": "frontend-platform" }
678
+ ]
679
+ }
680
+ `);
681
+ }
682
+ //# sourceMappingURL=fleet.js.map