@fenglimg/fabric-cli 2.0.0 → 2.1.0-rc.2

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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +6 -5
  3. package/dist/chunk-BATF4PEJ.js +361 -0
  4. package/dist/{chunk-OBQU6NHO.js → chunk-COI5VDFU.js} +0 -18
  5. package/dist/chunk-F46ORPOA.js +903 -0
  6. package/dist/chunk-HFQVXY6P.js +86 -0
  7. package/dist/chunk-L4Q55UC4.js +52 -0
  8. package/dist/chunk-LFIKMVY7.js +27 -0
  9. package/dist/chunk-MF3OTILQ.js +544 -0
  10. package/dist/chunk-PWLW3B57.js +18 -0
  11. package/dist/chunk-RYAFBNES.js +33 -0
  12. package/dist/chunk-T5RPGCCM.js +40 -0
  13. package/dist/chunk-WU6GAPKH.js +36 -0
  14. package/dist/config-XJIPZNUP.js +13 -0
  15. package/dist/doctor-QVNPHLJK.js +920 -0
  16. package/dist/index.js +23 -8
  17. package/dist/{init-BIRSIOXO.js → install-2HDO5FTQ.js} +807 -705
  18. package/dist/metrics-ACEQFPDU.js +122 -0
  19. package/dist/onboard-coverage-MFCAEBDO.js +220 -0
  20. package/dist/{plan-context-hint-QMUPAXIB.js → plan-context-hint-FC6P3WFE.js} +34 -28
  21. package/dist/scope-explain-2F2R5URO.js +33 -0
  22. package/dist/status-GLQWLWH6.js +23 -0
  23. package/dist/store-XTSE5TY6.js +105 -0
  24. package/dist/sync-BJCWDPNC.js +245 -0
  25. package/dist/uninstall-TAXSUSKH.js +1073 -0
  26. package/dist/whoami-B6AEMSEV.js +31 -0
  27. package/package.json +30 -5
  28. package/templates/hooks/cite-policy-evict.cjs +231 -0
  29. package/templates/hooks/configs/README.md +29 -6
  30. package/templates/hooks/configs/claude-code.json +14 -3
  31. package/templates/hooks/configs/codex-hooks.json +6 -3
  32. package/templates/hooks/configs/cursor-hooks.json +8 -10
  33. package/templates/hooks/fabric-hint.cjs +873 -105
  34. package/templates/hooks/knowledge-hint-broad.cjs +549 -135
  35. package/templates/hooks/knowledge-hint-narrow.cjs +830 -26
  36. package/templates/hooks/lib/banner-i18n.cjs +309 -0
  37. package/templates/hooks/lib/bindings-snapshot-reader.cjs +81 -0
  38. package/templates/hooks/lib/cite-contract-reminder.cjs +179 -0
  39. package/templates/hooks/lib/cite-line-parser.cjs +180 -0
  40. package/templates/hooks/lib/client-adapter.cjs +106 -0
  41. package/templates/hooks/lib/config-cache.cjs +107 -0
  42. package/templates/hooks/lib/state-store.cjs +84 -0
  43. package/templates/hooks/lib/summary-fallback.cjs +210 -0
  44. package/templates/skills/fabric-archive/SKILL.md +97 -419
  45. package/templates/skills/fabric-archive/ref/dry-run-scope.md +16 -0
  46. package/templates/skills/fabric-archive/ref/e5-cron-recap.md +58 -0
  47. package/templates/skills/fabric-archive/ref/i18n-policy.md +86 -0
  48. package/templates/skills/fabric-archive/ref/phase-0-range-resolution.md +156 -0
  49. package/templates/skills/fabric-archive/ref/phase-1-5-onboard.md +218 -0
  50. package/templates/skills/fabric-archive/ref/phase-1-cross-session.md +62 -0
  51. package/templates/skills/fabric-archive/ref/phase-2-5-viability.md +68 -0
  52. package/templates/skills/fabric-archive/ref/phase-3-5-scope.md +108 -0
  53. package/templates/skills/fabric-archive/ref/phase-3-classify.md +63 -0
  54. package/templates/skills/fabric-archive/ref/phase-4-5-emit.md +78 -0
  55. package/templates/skills/fabric-archive/ref/phase-4-mcp-persist.md +89 -0
  56. package/templates/skills/fabric-archive/ref/rc-history.md +38 -0
  57. package/templates/skills/fabric-archive/ref/worked-examples.md +78 -0
  58. package/templates/skills/fabric-import/SKILL.md +77 -514
  59. package/templates/skills/fabric-import/ref/checkpoint-state.md +85 -0
  60. package/templates/skills/fabric-import/ref/i18n-policy.md +79 -0
  61. package/templates/skills/fabric-import/ref/output-contract.md +61 -0
  62. package/templates/skills/fabric-import/ref/phase-2-mining.md +213 -0
  63. package/templates/skills/fabric-import/ref/phase-3-dedup.md +75 -0
  64. package/templates/skills/fabric-import/ref/state-recovery.md +57 -0
  65. package/templates/skills/fabric-import/ref/worked-examples.md +127 -0
  66. package/templates/skills/fabric-review/SKILL.md +90 -284
  67. package/templates/skills/fabric-review/ref/askuserquestion-policy.md +66 -0
  68. package/templates/skills/fabric-review/ref/i18n-policy.md +111 -0
  69. package/templates/skills/fabric-review/ref/modify-flow.md +103 -0
  70. package/templates/skills/fabric-review/ref/output-contract.md +58 -0
  71. package/templates/skills/fabric-review/ref/per-mode-flows.md +155 -0
  72. package/templates/skills/fabric-review/ref/semantic-check.md +26 -0
  73. package/templates/skills/fabric-review/ref/worked-examples.md +95 -0
  74. package/templates/skills/fabric-sync/SKILL.md +46 -0
  75. package/templates/skills/lib/shared-policy.md +69 -0
  76. package/dist/chunk-6ICJICVU.js +0 -10
  77. package/dist/chunk-74SZWYPH.js +0 -658
  78. package/dist/chunk-EYIDD2YS.js +0 -1000
  79. package/dist/doctor-T7JWODKG.js +0 -282
  80. package/dist/hooks-Y74Y5LQS.js +0 -12
  81. package/dist/scan-LMK3UCWL.js +0 -22
  82. package/dist/serve-H554BHLG.js +0 -124
  83. package/templates/agents-md/AGENTS.md.template +0 -59
  84. package/templates/bootstrap/CLAUDE.md +0 -8
  85. package/templates/bootstrap/codex-AGENTS-header.md +0 -6
  86. package/templates/bootstrap/cursor-fabric-bootstrap.mdc +0 -10
@@ -0,0 +1,920 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ paint,
4
+ symbol
5
+ } from "./chunk-WWNXR34K.js";
6
+ import {
7
+ resolveDevMode
8
+ } from "./chunk-COI5VDFU.js";
9
+ import {
10
+ getDoctorTranslator,
11
+ t
12
+ } from "./chunk-PWLW3B57.js";
13
+ import {
14
+ missingRequiredStores
15
+ } from "./chunk-HFQVXY6P.js";
16
+ import {
17
+ loadProjectConfig
18
+ } from "./chunk-LFIKMVY7.js";
19
+ import {
20
+ loadGlobalConfig,
21
+ resolveGlobalRoot
22
+ } from "./chunk-RYAFBNES.js";
23
+
24
+ // src/commands/doctor.ts
25
+ import { confirm, isCancel } from "@clack/prompts";
26
+ import { defineCommand } from "citty";
27
+ import {
28
+ appendEventLedgerEvent,
29
+ enrichDescriptions,
30
+ runDoctorApplyLint as runDoctorFixKnowledge,
31
+ runDoctorArchiveHistory,
32
+ runDoctorCiteCoverage,
33
+ runDoctorFix,
34
+ runDoctorHistoryAll,
35
+ runDoctorReport
36
+ } from "@fenglimg/fabric-server";
37
+
38
+ // src/store/doctor-checks.ts
39
+ import { join } from "path";
40
+ import { findStoreExecutableViolations, storeRelativePath } from "@fenglimg/fabric-shared";
41
+ function storeDoctorChecks(projectRoot, globalRoot = resolveGlobalRoot()) {
42
+ const diagnostics = [];
43
+ const global = loadGlobalConfig(globalRoot);
44
+ if (global === null) {
45
+ diagnostics.push({
46
+ code: "no_global_config",
47
+ severity: "warn",
48
+ message: "no global Fabric config \u2014 run `fabric install --global <url>`"
49
+ });
50
+ return diagnostics;
51
+ }
52
+ for (const missing of missingRequiredStores(projectRoot, globalRoot)) {
53
+ diagnostics.push({
54
+ code: "missing_required_store",
55
+ severity: "warn",
56
+ ref: missing.id,
57
+ message: `required store '${missing.id}' is not mounted; run \`fabric store add\``
58
+ });
59
+ }
60
+ for (const store of global.stores) {
61
+ if (store.remote === void 0 && store.personal !== true) {
62
+ diagnostics.push({
63
+ code: "local_only_store",
64
+ severity: "info",
65
+ ref: store.alias,
66
+ message: `store '${store.alias}' is local-only; add a git remote to back it up`
67
+ });
68
+ }
69
+ const violations = findStoreExecutableViolations(join(globalRoot, storeRelativePath(store.store_uuid)));
70
+ if (violations.length > 0) {
71
+ diagnostics.push({
72
+ code: "executable_in_store",
73
+ severity: "warn",
74
+ ref: store.alias,
75
+ message: `store '${store.alias}' contains executable/script files (${violations.slice(0, 3).join(", ")}${violations.length > 3 ? ", \u2026" : ""}) \u2014 stores are data-only; Fabric never runs them (S65)`
76
+ });
77
+ }
78
+ }
79
+ return diagnostics;
80
+ }
81
+
82
+ // src/commands/doctor.ts
83
+ import { buildDebugBundle } from "@fenglimg/fabric-shared";
84
+ var FIX_KNOWLEDGE_CODE_LABELS = {
85
+ knowledge_orphan_demote_required: "demote (maturity)",
86
+ knowledge_stale_archive_required: "archive (git mv)",
87
+ knowledge_pending_auto_archive: "archive (git mv, pending)",
88
+ knowledge_index_drift: "counter bump (agents.meta)",
89
+ knowledge_session_hints_stale: "cache delete"
90
+ };
91
+ var PLAN_PREVIEW_LIMIT = 12;
92
+ var doctorCommand = defineCommand({
93
+ meta: {
94
+ name: "doctor",
95
+ description: t("cli.doctor.description")
96
+ },
97
+ args: {
98
+ target: {
99
+ type: "string",
100
+ description: t("cli.doctor.args.target.description")
101
+ },
102
+ fix: {
103
+ type: "boolean",
104
+ description: t("cli.doctor.args.fix.description"),
105
+ default: false
106
+ },
107
+ "fix-knowledge": {
108
+ type: "boolean",
109
+ description: t("cli.doctor.args.fix-knowledge.description"),
110
+ default: false
111
+ },
112
+ json: {
113
+ type: "boolean",
114
+ description: t("cli.doctor.args.json.description"),
115
+ default: false
116
+ },
117
+ strict: {
118
+ type: "boolean",
119
+ description: t("cli.doctor.args.strict.description"),
120
+ default: false
121
+ },
122
+ // v2.1.0-rc.1 P6 (S40): emit a redacted diagnostic bundle (config + store
123
+ // diagnostics; events excluded by default). Every string is secret-redacted
124
+ // so the bundle is safe to paste into a bug report. Read-only.
125
+ "debug-bundle": {
126
+ type: "boolean",
127
+ description: "Emit a redacted diagnostic bundle (config + store health) for bug reports",
128
+ default: false
129
+ },
130
+ // rc.7 T11: skip the safety confirm before mutations. Required for any
131
+ // non-tty invocation that wants to run --fix-knowledge without setting
132
+ // FABRIC_NONINTERACTIVE=1 in the environment.
133
+ yes: {
134
+ type: "boolean",
135
+ description: t("cli.doctor.args.yes.description"),
136
+ default: false
137
+ },
138
+ // rc.35 TASK-12 (P0-11): expose maintainer-audience actionHints. By
139
+ // default the renderer folds remediation strings that target Fabric
140
+ // contributors (edit `packages/cli/templates/...`, interpret G1-G5
141
+ // cite-goodhart codes, etc.) since npm end users have no actionable
142
+ // lever for them. --verbose shows them.
143
+ verbose: {
144
+ type: "boolean",
145
+ description: t("cli.doctor.args.verbose.description"),
146
+ default: false
147
+ },
148
+ // rc.20 TASK-05: cite policy adherence report (read-only). Skips standard
149
+ // inspections entirely — different output surface. Mutually exclusive
150
+ // with --fix / --fix-knowledge (enforced in run()).
151
+ "cite-coverage": {
152
+ type: "boolean",
153
+ description: t("cli.doctor.args.cite-coverage.description"),
154
+ default: false
155
+ },
156
+ since: {
157
+ type: "string",
158
+ description: t("cli.doctor.args.since.description"),
159
+ default: "7d"
160
+ },
161
+ client: {
162
+ type: "string",
163
+ description: t("cli.doctor.args.client.description"),
164
+ default: "all",
165
+ valueHint: "cc|codex|cursor|all"
166
+ },
167
+ // v2.0.0-rc.24 TASK-10: --layer filter for the cite contract audit. Pairs
168
+ // with --cite-coverage. Validated against {'team','personal','all'} at
169
+ // command entry; rejects 'both' (rc.20 plan-context vocabulary) explicitly.
170
+ layer: {
171
+ type: "string",
172
+ description: t("cli.doctor.args.layer.description"),
173
+ default: "all",
174
+ valueHint: "team|personal|all"
175
+ },
176
+ // rc.23 TASK-007 (a-C2): description-grade back-fill flag set. Read-side
177
+ // by default; `--auto` flips the writer arm on. Mutually exclusive with
178
+ // --fix / --fix-knowledge / --cite-coverage (different mutation surfaces).
179
+ "enrich-descriptions": {
180
+ type: "boolean",
181
+ description: t("cli.doctor.args.enrich-descriptions.description"),
182
+ default: false
183
+ },
184
+ auto: {
185
+ type: "boolean",
186
+ description: t("cli.doctor.args.auto.description"),
187
+ default: false
188
+ },
189
+ "dry-run": {
190
+ type: "boolean",
191
+ description: t("cli.doctor.args.dry-run.description"),
192
+ default: false
193
+ },
194
+ // v2.0.0-rc.25 TASK-10: --archive-history flag (parallel to rc.20
195
+ // --cite-coverage). Read-only; reads session_archive_attempted events
196
+ // and renders a per-session table. Pairs with the shared `--since` flag.
197
+ "archive-history": {
198
+ type: "boolean",
199
+ description: t("cli.doctor.args.archive-history.description"),
200
+ default: false
201
+ },
202
+ // rc.37 NEW-33: unified history view across archive / fix / all surfaces.
203
+ // Mode = `archive | fix | all` (the `archive` mode delegates to the
204
+ // existing runDoctorArchiveHistory; `fix` aggregates doctor_run events;
205
+ // `all` rolls up both into a per-day count table). Read-only; mutex
206
+ // with the mutation arms.
207
+ history: {
208
+ type: "string",
209
+ description: t("cli.doctor.args.history.description"),
210
+ valueHint: "archive|fix|all"
211
+ }
212
+ },
213
+ async run({ args }) {
214
+ const workspaceRoot = process.cwd();
215
+ const resolution = resolveDevMode(args.target, workspaceRoot);
216
+ const dt = getDoctorTranslator(resolution.target);
217
+ const fixKnowledge = args["fix-knowledge"] === true;
218
+ const fix = args.fix === true;
219
+ const citeCoverage = args["cite-coverage"] === true;
220
+ const enrichDesc = args["enrich-descriptions"] === true;
221
+ const archiveHistory = args["archive-history"] === true;
222
+ if (args["debug-bundle"] === true) {
223
+ const globalRoot = resolveGlobalRoot();
224
+ let config = {};
225
+ try {
226
+ config = {
227
+ global: loadGlobalConfig(globalRoot) ?? null,
228
+ project: loadProjectConfig(resolution.target) ?? null
229
+ };
230
+ } catch {
231
+ config = {};
232
+ }
233
+ const bundle = buildDebugBundle({
234
+ config,
235
+ diagnostics: collectStoreDiagnostics(resolution.target)
236
+ });
237
+ writeStdout(JSON.stringify(bundle, null, 2));
238
+ return;
239
+ }
240
+ if (args.since !== void 0) {
241
+ try {
242
+ parseSinceDuration(args.since);
243
+ } catch {
244
+ writeStderr(dt("cli.doctor.errors.invalid-since", { input: args.since }));
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+ }
249
+ const historyMode = args.history;
250
+ if (typeof historyMode === "string" && historyMode.length > 0) {
251
+ if (fix || fixKnowledge || citeCoverage || enrichDesc || archiveHistory) {
252
+ writeStderr(dt("cli.doctor.errors.history-mutex"));
253
+ process.exitCode = 1;
254
+ return;
255
+ }
256
+ if (historyMode !== "archive" && historyMode !== "fix" && historyMode !== "all") {
257
+ writeStderr(dt("cli.doctor.errors.invalid-history-mode", { input: historyMode }));
258
+ process.exitCode = 1;
259
+ return;
260
+ }
261
+ const sinceInput = args.since ?? "7d";
262
+ let sinceMs;
263
+ try {
264
+ sinceMs = parseSinceDuration(sinceInput);
265
+ } catch {
266
+ writeStderr(dt("cli.doctor.errors.invalid-since", { input: sinceInput }));
267
+ process.exitCode = 1;
268
+ return;
269
+ }
270
+ if (historyMode === "archive") {
271
+ const report3 = await runDoctorArchiveHistory(resolution.target, { since: sinceMs });
272
+ if (args.json === true) {
273
+ writeStdout(JSON.stringify(report3, null, 2));
274
+ } else {
275
+ renderArchiveHistoryReport(report3, sinceInput, dt);
276
+ }
277
+ return;
278
+ }
279
+ const report2 = await runDoctorHistoryAll(resolution.target, { since: sinceMs });
280
+ if (args.json === true) {
281
+ writeStdout(JSON.stringify(report2, null, 2));
282
+ } else {
283
+ renderHistoryAllReport(report2, sinceInput, historyMode, dt);
284
+ }
285
+ return;
286
+ }
287
+ if (archiveHistory) {
288
+ if (fix || fixKnowledge || citeCoverage || enrichDesc) {
289
+ writeStderr(dt("cli.doctor.errors.archive-history-mutex"));
290
+ process.exitCode = 1;
291
+ return;
292
+ }
293
+ const sinceInput = args.since ?? "7d";
294
+ let sinceMs;
295
+ try {
296
+ sinceMs = parseSinceDuration(sinceInput);
297
+ } catch {
298
+ writeStderr(dt("cli.doctor.errors.invalid-since", { input: sinceInput }));
299
+ process.exitCode = 1;
300
+ return;
301
+ }
302
+ const report2 = await runDoctorArchiveHistory(resolution.target, {
303
+ since: sinceMs
304
+ });
305
+ if (args.json === true) {
306
+ writeStdout(JSON.stringify(report2, null, 2));
307
+ } else {
308
+ renderArchiveHistoryReport(report2, sinceInput, dt);
309
+ }
310
+ return;
311
+ }
312
+ if (enrichDesc) {
313
+ if (fix || fixKnowledge || citeCoverage) {
314
+ writeStderr(dt("cli.doctor.errors.enrich-descriptions-mutex"));
315
+ process.exitCode = 1;
316
+ return;
317
+ }
318
+ const autoFlag = args.auto === true;
319
+ const dryRun = args["dry-run"] === true;
320
+ const report2 = await enrichDescriptions(resolution.target, {
321
+ auto: autoFlag,
322
+ dryRun
323
+ });
324
+ if (args.json === true) {
325
+ writeStdout(JSON.stringify(report2, null, 2));
326
+ } else {
327
+ renderEnrichDescriptionsReport(report2, dt);
328
+ }
329
+ return;
330
+ }
331
+ if (citeCoverage) {
332
+ if (fix || fixKnowledge) {
333
+ writeStderr(dt("cli.doctor.errors.cite-coverage-mutex"));
334
+ process.exitCode = 1;
335
+ return;
336
+ }
337
+ let sinceMs;
338
+ try {
339
+ sinceMs = parseSinceDuration(args.since ?? "7d");
340
+ } catch {
341
+ writeStderr(dt("cli.doctor.errors.invalid-since", { input: args.since ?? "7d" }));
342
+ process.exitCode = 1;
343
+ return;
344
+ }
345
+ const clientFilter = args.client ?? "all";
346
+ if (!isValidClientFilter(clientFilter)) {
347
+ writeStderr(dt("cli.doctor.errors.invalid-client", { input: clientFilter }));
348
+ process.exitCode = 1;
349
+ return;
350
+ }
351
+ const layerFilter = args.layer ?? "all";
352
+ if (!isValidLayerFilter(layerFilter)) {
353
+ writeStderr(dt("cli.doctor.errors.invalid-layer", { input: layerFilter }));
354
+ process.exitCode = 1;
355
+ return;
356
+ }
357
+ const report2 = await runDoctorCiteCoverage(resolution.target, {
358
+ since: sinceMs,
359
+ client: clientFilter,
360
+ layer: layerFilter
361
+ });
362
+ renderCiteCoverageReport(report2, args.json === true, dt);
363
+ return;
364
+ }
365
+ if (fixKnowledge && fix) {
366
+ writeStderr(dt("cli.doctor.errors.fix-knowledge-fix-mutually-exclusive"));
367
+ process.exitCode = 1;
368
+ return;
369
+ }
370
+ let fixKnowledgeReport = null;
371
+ let fixReport = null;
372
+ let report;
373
+ if (fixKnowledge) {
374
+ const preReport = await runDoctorReport(resolution.target);
375
+ const plan = computeFixKnowledgePlan(preReport);
376
+ const yesFlag = args.yes === true;
377
+ const envBypass = process.env.FABRIC_NONINTERACTIVE === "1";
378
+ if (plan.totalCount === 0) {
379
+ } else {
380
+ renderFixKnowledgePlan(plan);
381
+ const decision = await resolveFixKnowledgeConsent({
382
+ yesFlag,
383
+ envBypass,
384
+ plan
385
+ });
386
+ if (decision === "abort") {
387
+ process.exitCode = 1;
388
+ return;
389
+ }
390
+ }
391
+ fixKnowledgeReport = await runDoctorFixKnowledge(resolution.target);
392
+ report = fixKnowledgeReport.report;
393
+ } else if (fix) {
394
+ if (args["dry-run"] === true) {
395
+ report = await runDoctorReport(resolution.target);
396
+ } else {
397
+ fixReport = await runDoctorFix(resolution.target);
398
+ report = fixReport.report;
399
+ }
400
+ } else {
401
+ report = await runDoctorReport(resolution.target);
402
+ }
403
+ const storeDiagnostics = collectStoreDiagnostics(resolution.target);
404
+ if (args.json === true) {
405
+ writeStdout(
406
+ JSON.stringify(
407
+ { ...fixKnowledgeReport ?? fixReport ?? report, store_diagnostics: storeDiagnostics },
408
+ null,
409
+ 2
410
+ )
411
+ );
412
+ } else {
413
+ if (fixKnowledgeReport !== null) {
414
+ writeStdout(fixKnowledgeReport.message);
415
+ if (fixKnowledgeReport.aborted && fixKnowledgeReport.abort_reason !== void 0) {
416
+ writeStderr(fixKnowledgeReport.abort_reason);
417
+ }
418
+ renderFixKnowledgeMutations(fixKnowledgeReport, dt);
419
+ } else if (fixReport !== null) {
420
+ writeStdout(fixReport.message);
421
+ } else if (fix && args["dry-run"] === true) {
422
+ writeStdout(dt("cli.doctor.fix-dry-run-banner"));
423
+ }
424
+ renderHumanReport(report, dt, args.verbose === true);
425
+ renderStoreDiagnostics(storeDiagnostics);
426
+ }
427
+ await emitDoctorRunEventBestEffort(resolution.target, {
428
+ mode: fixKnowledge ? "fix-knowledge" : "lint",
429
+ issues: report.fixable_errors.length + report.manual_errors.length + report.warnings.length,
430
+ mutations: fixKnowledgeReport !== null ? fixKnowledgeReport.mutations.filter((m) => m.applied).length : void 0
431
+ });
432
+ if (fixKnowledgeReport !== null) {
433
+ if (fixKnowledgeReport.aborted) {
434
+ process.exitCode = 1;
435
+ return;
436
+ }
437
+ if (fixKnowledgeReport.mutations.some((m) => !m.applied)) {
438
+ process.exitCode = 1;
439
+ return;
440
+ }
441
+ }
442
+ if (report.status === "error" || args.strict === true && (report.status === "warn" || report.warnings.length > 0)) {
443
+ process.exitCode = 1;
444
+ }
445
+ }
446
+ });
447
+ var doctor_default = doctorCommand;
448
+ function renderHumanReport(report, dt, verbose) {
449
+ writeStdout(`${renderStatus(report.status)} ${paint.ai("fabric doctor")} ${paint.human(report.summary.target)}`);
450
+ renderTldrHeader(report);
451
+ for (const check of report.checks) {
452
+ writeStdout(`${renderStatus(check.status)} ${check.name}: ${check.message}`);
453
+ }
454
+ const opts = { verbose, dt };
455
+ writeIssueSection(dt("doctor.section.fixable"), report.fixable_errors, opts);
456
+ writeIssueSection(dt("doctor.section.manual"), report.manual_errors, opts);
457
+ writeIssueSection(dt("doctor.section.warnings"), report.warnings, opts);
458
+ renderPayloadLimits(report, dt);
459
+ }
460
+ function collectStoreDiagnostics(projectRoot) {
461
+ try {
462
+ return storeDoctorChecks(projectRoot);
463
+ } catch {
464
+ return [];
465
+ }
466
+ }
467
+ function renderStoreDiagnostics(diagnostics) {
468
+ if (diagnostics.length === 0) {
469
+ return;
470
+ }
471
+ writeStdout("");
472
+ writeStdout(paint.ai("store health"));
473
+ for (const diagnostic of diagnostics) {
474
+ const mark = diagnostic.severity === "warn" ? symbol.warn : "[info]";
475
+ const ref = diagnostic.ref === void 0 ? "" : ` [${diagnostic.ref}]`;
476
+ writeStdout(`${mark}${ref} ${diagnostic.message}`);
477
+ }
478
+ }
479
+ function renderPayloadLimits(report, dt) {
480
+ const limits = report.summary.payload_limits;
481
+ if (limits === void 0) {
482
+ return;
483
+ }
484
+ writeStdout("");
485
+ writeStdout(dt("doctor.section.payload-limits"));
486
+ writeStdout(
487
+ `- ${dt("doctor.payload-limits.line", {
488
+ warnKb: String(Math.round(limits.warn_bytes / 1024)),
489
+ hardKb: String(Math.round(limits.hard_bytes / 1024)),
490
+ source: limits.source
491
+ })}`
492
+ );
493
+ }
494
+ function renderFixKnowledgeMutations(fixKnowledgeReport, dt) {
495
+ if (fixKnowledgeReport.mutations.length === 0) {
496
+ return;
497
+ }
498
+ writeStdout("");
499
+ writeStdout(dt("doctor.section.fix-knowledge-mutations"));
500
+ for (const mutation of fixKnowledgeReport.mutations) {
501
+ const marker = mutation.applied ? symbol.ok : symbol.error;
502
+ const errSuffix = mutation.applied || mutation.error === void 0 ? "" : ` (${mutation.error})`;
503
+ writeStdout(`${marker} ${mutation.kind}: ${mutation.path} [${mutation.detail}]${errSuffix}`);
504
+ }
505
+ }
506
+ function writeIssueSection(title, issues, options) {
507
+ if (issues.length === 0) {
508
+ return;
509
+ }
510
+ writeStdout("");
511
+ writeStdout(title);
512
+ for (const issue of issues) {
513
+ writeStdout(`- ${issue.code}: ${issue.message}`);
514
+ if (issue.actionHint !== void 0 && issue.actionHint.length > 0) {
515
+ if (issue.audience === "maintainer" && !options.verbose) {
516
+ writeStdout(` \u2192 ${options.dt("doctor.maintainer-hint-folded")}`);
517
+ } else {
518
+ writeStdout(` \u2192 ${issue.actionHint}`);
519
+ }
520
+ }
521
+ }
522
+ }
523
+ function renderTldrHeader(report) {
524
+ const ranked = [];
525
+ for (const issue of report.fixable_errors) {
526
+ ranked.push({ severity: "fixable", code: issue.code, message: issue.message });
527
+ }
528
+ for (const issue of report.manual_errors) {
529
+ ranked.push({ severity: "manual", code: issue.code, message: issue.message });
530
+ }
531
+ for (const issue of report.warnings) {
532
+ ranked.push({ severity: "warn", code: issue.code, message: issue.message });
533
+ }
534
+ if (ranked.length === 0) {
535
+ writeStdout(`${symbol.ok} TL;DR: all 48 checks green \u2014 nothing to fix.`);
536
+ return;
537
+ }
538
+ const top3 = ranked.slice(0, 3);
539
+ writeStdout(
540
+ `TL;DR (top ${top3.length} of ${ranked.length}, severity order: fixable\u2192manual\u2192warn):`
541
+ );
542
+ for (const item of top3) {
543
+ const marker = item.severity === "fixable" ? symbol.error : item.severity === "manual" ? symbol.error : symbol.warn;
544
+ const truncated = item.message.length > 140 ? `${item.message.slice(0, 137)}...` : item.message;
545
+ writeStdout(` ${marker} ${item.code}: ${truncated}`);
546
+ }
547
+ }
548
+ function renderStatus(status) {
549
+ if (status === "ok") {
550
+ return symbol.ok;
551
+ }
552
+ if (status === "warn") {
553
+ return symbol.warn;
554
+ }
555
+ return symbol.error;
556
+ }
557
+ function writeStdout(message) {
558
+ process.stdout.write(`${message}
559
+ `);
560
+ }
561
+ async function emitDoctorRunEventBestEffort(projectRoot, payload) {
562
+ try {
563
+ await appendEventLedgerEvent(projectRoot, {
564
+ event_type: "doctor_run",
565
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
566
+ mode: payload.mode,
567
+ issues: payload.issues,
568
+ ...payload.mutations !== void 0 ? { mutations: payload.mutations } : {}
569
+ });
570
+ } catch {
571
+ }
572
+ }
573
+ function writeStderr(message) {
574
+ process.stderr.write(`${message}
575
+ `);
576
+ }
577
+ function computeFixKnowledgePlan(report) {
578
+ const buckets = {};
579
+ const sources = [
580
+ ...report.fixable_errors,
581
+ ...report.warnings
582
+ ];
583
+ for (const issue of sources) {
584
+ if (FIX_KNOWLEDGE_CODE_LABELS[issue.code] === void 0) continue;
585
+ if (!Array.isArray(buckets[issue.code])) {
586
+ buckets[issue.code] = [];
587
+ }
588
+ buckets[issue.code].push(issue);
589
+ }
590
+ const codes = Object.keys(buckets).sort(
591
+ (a, b) => FIX_KNOWLEDGE_CODE_LABELS[a].localeCompare(FIX_KNOWLEDGE_CODE_LABELS[b])
592
+ );
593
+ const perCodeLines = [];
594
+ let totalCount = 0;
595
+ for (const code of codes) {
596
+ const items = buckets[code];
597
+ totalCount += items.length;
598
+ perCodeLines.push(` - ${FIX_KNOWLEDGE_CODE_LABELS[code]}: ${items.length}`);
599
+ }
600
+ const previewLines = [];
601
+ const flattened = codes.flatMap((c) => buckets[c]);
602
+ for (const item of flattened.slice(0, PLAN_PREVIEW_LIMIT)) {
603
+ const where = item.path !== void 0 && item.path.length > 0 ? `${item.path}` : "(no path)";
604
+ previewLines.push(` \u2022 ${where} \u2014 ${item.message}`);
605
+ }
606
+ if (flattened.length > PLAN_PREVIEW_LIMIT) {
607
+ previewLines.push(` \u2022 ... and ${flattened.length - PLAN_PREVIEW_LIMIT} more`);
608
+ }
609
+ return { totalCount, perCodeLines, previewLines };
610
+ }
611
+ function renderFixKnowledgePlan(plan) {
612
+ writeStdout("");
613
+ writeStdout(`${paint.warn("fix-knowledge mutation plan")} (${plan.totalCount} total)`);
614
+ for (const line of plan.perCodeLines) {
615
+ writeStdout(line);
616
+ }
617
+ if (plan.previewLines.length > 0) {
618
+ writeStdout("");
619
+ writeStdout(" preview:");
620
+ for (const line of plan.previewLines) {
621
+ writeStdout(line);
622
+ }
623
+ }
624
+ }
625
+ async function resolveFixKnowledgeConsent(options) {
626
+ if (options.yesFlag || options.envBypass) {
627
+ return "proceed";
628
+ }
629
+ if (process.stdin.isTTY !== true) {
630
+ writeStderr(
631
+ "doctor --fix-knowledge: stdin is not a TTY and neither --yes nor FABRIC_NONINTERACTIVE=1 is set. Refusing to mutate."
632
+ );
633
+ return "abort";
634
+ }
635
+ const message = `About to apply ${options.plan.totalCount} mutation(s) to knowledge entries (frontmatter writes + git mv + cache deletes). Proceed?`;
636
+ const answer = await confirm({
637
+ message,
638
+ initialValue: false
639
+ });
640
+ if (isCancel(answer) || answer !== true) {
641
+ writeStderr("doctor --fix-knowledge: aborted by user.");
642
+ return "abort";
643
+ }
644
+ return "proceed";
645
+ }
646
+ var CITE_COVERAGE_CLIENT_FILTERS = /* @__PURE__ */ new Set([
647
+ "cc",
648
+ "codex",
649
+ "cursor",
650
+ "all"
651
+ ]);
652
+ function isValidClientFilter(input) {
653
+ return CITE_COVERAGE_CLIENT_FILTERS.has(input);
654
+ }
655
+ var CITE_COVERAGE_LAYER_FILTERS = /* @__PURE__ */ new Set([
656
+ "team",
657
+ "personal",
658
+ "all"
659
+ ]);
660
+ function isValidLayerFilter(input) {
661
+ return CITE_COVERAGE_LAYER_FILTERS.has(input);
662
+ }
663
+ function renderCiteCoverageReport(report, jsonMode, dt) {
664
+ if (jsonMode) {
665
+ writeStdout(JSON.stringify(report, null, 2));
666
+ return;
667
+ }
668
+ if (report.status === "skipped") {
669
+ writeStdout(dt("doctor.cite.status.skipped"));
670
+ return;
671
+ }
672
+ const lines = [];
673
+ lines.push(dt("doctor.section.cite-coverage"));
674
+ lines.push(
675
+ dt("doctor.cite.header", {
676
+ since: new Date(report.since_ts).toISOString(),
677
+ marker: new Date(report.marker_ts).toISOString()
678
+ })
679
+ );
680
+ if (report.marker_emitted_now) {
681
+ lines.push(dt("doctor.cite.warning.justActivated"));
682
+ }
683
+ lines.push("");
684
+ lines.push(` ${dt("doctor.cite.metric.editsTouched")}: ${report.metrics.edits_touched}`);
685
+ lines.push(` ${dt("doctor.cite.metric.qualifyingCites")}: ${report.metrics.qualifying_cites}`);
686
+ lines.push(` ${dt("doctor.cite.metric.recalledUnverified")}: ${report.metrics.recalled_unverified}`);
687
+ lines.push(` ${dt("doctor.cite.metric.expectedButMissed")}: ${report.metrics.expected_but_missed}`);
688
+ lines.push(` ${dt("doctor.cite.metric.totalTurns")}: ${report.metrics.total_turns}`);
689
+ const complianceRate = report.metrics.cite_compliance_rate;
690
+ const complianceStr = complianceRate === null || complianceRate === void 0 ? dt("doctor.cite.metric.complianceNA") : `${(complianceRate * 100).toFixed(1)}% (${report.metrics.compliant_cites ?? 0}/${(report.metrics.compliant_cites ?? 0) + (report.metrics.noncompliant_cites ?? 0)})`;
691
+ lines.push(` ${dt("doctor.cite.metric.complianceRate")}: ${complianceStr}`);
692
+ const uncorrelatable = report.metrics.uncorrelatable_edits ?? 0;
693
+ if (uncorrelatable > 0) {
694
+ lines.push(` ${dt("doctor.cite.metric.uncorrelatableEdits")}: ${uncorrelatable}`);
695
+ }
696
+ if (report.per_client !== void 0 && Object.keys(report.per_client).length > 1) {
697
+ lines.push("");
698
+ lines.push(`### ${dt("doctor.cite.section.perClient")}`);
699
+ for (const [client, metrics] of Object.entries(report.per_client)) {
700
+ const summary = Object.entries(metrics).map(([k, v]) => `${k}=${v}`).join(" / ");
701
+ lines.push(` ${client}: ${summary}`);
702
+ }
703
+ }
704
+ if (report.dismissed_reason_histogram !== void 0 && Object.keys(report.dismissed_reason_histogram).length > 0) {
705
+ lines.push("");
706
+ lines.push(`### ${dt("doctor.cite.section.dismissedReasons")}`);
707
+ for (const [reason, count] of Object.entries(report.dismissed_reason_histogram)) {
708
+ const label = dt(`doctor.cite.dismissed.${reason}`);
709
+ lines.push(` ${label}: ${count}`);
710
+ }
711
+ }
712
+ if (report.none_reason_histogram !== void 0 && Object.keys(report.none_reason_histogram).length > 0) {
713
+ lines.push("");
714
+ lines.push(`### ${dt("doctor.cite.section.noneReasons")}`);
715
+ for (const [reason, count] of Object.entries(report.none_reason_histogram)) {
716
+ const label = dt(`doctor.cite.none.${reason}`);
717
+ lines.push(` ${label}: ${count}`);
718
+ }
719
+ }
720
+ appendContractSection(lines, report, dt);
721
+ writeStdout(lines.join("\n"));
722
+ }
723
+ function appendContractSection(lines, report, dt) {
724
+ const status = report.contract_metrics_status;
725
+ if (status === void 0) {
726
+ return;
727
+ }
728
+ const metrics = report.contract_metrics;
729
+ const perLayerType = report.per_layer_type;
730
+ const allCountsZero = metrics === void 0 || metrics.decisions_cited === 0 && metrics.pitfalls_cited === 0 && metrics.contract_with === 0 && metrics.contract_missing === 0 && metrics.hard_violated === 0 && metrics.cite_id_unresolved === 0 && Object.keys(metrics.skip_count).length === 0;
731
+ if (status === "awaiting_marker" && allCountsZero) {
732
+ return;
733
+ }
734
+ lines.push("");
735
+ lines.push(`### ${dt("cite-coverage.contract.header")}`);
736
+ if (status === "skipped:bootstrap_drift") {
737
+ lines.push(` ${dt("cite-coverage.contract.status.skipped_bootstrap_drift")}`);
738
+ return;
739
+ }
740
+ const statusKey = status === "ok" ? "cite-coverage.contract.status.ok" : "cite-coverage.contract.status.awaiting_marker";
741
+ lines.push(` status: ${dt(statusKey)}`);
742
+ if (typeof report.contract_marker_ts === "number" && report.contract_marker_ts > 0) {
743
+ lines.push(` since: ${new Date(report.contract_marker_ts).toISOString()}`);
744
+ }
745
+ if (report.layer_filter !== void 0) {
746
+ lines.push(` layer filter: ${report.layer_filter}`);
747
+ }
748
+ if (metrics !== void 0) {
749
+ lines.push(` ${dt("cite-coverage.contract.decisions_cited")}: ${metrics.decisions_cited}`);
750
+ lines.push(` ${dt("cite-coverage.contract.pitfalls_cited")}: ${metrics.pitfalls_cited}`);
751
+ lines.push(` ${dt("cite-coverage.contract.with")}: ${metrics.contract_with}`);
752
+ lines.push(` ${dt("cite-coverage.contract.missing")}: ${metrics.contract_missing}`);
753
+ if (metrics.hard_violated > 0) {
754
+ const layerSuffix = report.layer_filter === "personal" ? dt("cite-coverage.layer.personal_fyi") : dt("cite-coverage.layer.team_review");
755
+ lines.push(
756
+ ` ${dt("cite-coverage.contract.hard_violated")} ${layerSuffix}: ${metrics.hard_violated}`
757
+ );
758
+ }
759
+ }
760
+ if (perLayerType !== void 0) {
761
+ const teamKeys = Object.keys(perLayerType.team).filter(
762
+ (k) => perLayerType.team[k] > 0
763
+ );
764
+ const personalKeys = Object.keys(perLayerType.personal).filter(
765
+ (k) => perLayerType.personal[k] > 0
766
+ );
767
+ if (teamKeys.length > 0 || personalKeys.length > 0) {
768
+ lines.push("");
769
+ lines.push(`#### ${dt("cite-coverage.layer.team")} \xD7 ${dt("cite-coverage.layer.personal")}`);
770
+ for (const key of teamKeys) {
771
+ const label = dt(`cite-coverage.contract.type.${key}`);
772
+ lines.push(` ${dt("cite-coverage.layer.team")} \u2014 ${label}: ${perLayerType.team[key]}`);
773
+ }
774
+ for (const key of personalKeys) {
775
+ const label = dt(`cite-coverage.contract.type.${key}`);
776
+ lines.push(
777
+ ` ${dt("cite-coverage.layer.personal")} \u2014 ${label}: ${perLayerType.personal[key]}`
778
+ );
779
+ }
780
+ }
781
+ }
782
+ if (metrics !== void 0 && Object.keys(metrics.skip_count).length > 0) {
783
+ lines.push("");
784
+ lines.push(`#### ${dt("cite-coverage.contract.skip_count")}`);
785
+ for (const [reason, count] of Object.entries(metrics.skip_count)) {
786
+ const label = dt(`cite-coverage.skip.${reason}`);
787
+ lines.push(` ${label}: ${count}`);
788
+ }
789
+ }
790
+ if (metrics !== void 0 && metrics.cite_id_unresolved > 0) {
791
+ lines.push("");
792
+ lines.push(
793
+ `${symbol.warn} ${dt("cite-coverage.contract.cite_id_unresolved")}: ${metrics.cite_id_unresolved}`
794
+ );
795
+ }
796
+ }
797
+ function renderEnrichDescriptionsReport(report, dt) {
798
+ const header = `${symbol.ok} ${paint.ai("fabric doctor --enrich-descriptions")} mode=${report.mode}${report.dryRun ? " (dry-run)" : ""} scanned=${report.scanned} modified=${report.modified} skipped=${report.skipped}`;
799
+ writeStdout(header);
800
+ if (report.candidates.length === 0) {
801
+ writeStdout(dt("doctor.enrich.allComplete"));
802
+ return;
803
+ }
804
+ writeStdout("");
805
+ for (const candidate of report.candidates) {
806
+ if (candidate.error !== void 0) {
807
+ writeStdout(`${symbol.error} ${candidate.path} \u2014 ${candidate.error}`);
808
+ continue;
809
+ }
810
+ const missing = candidate.missing.join(", ");
811
+ if (candidate.modified) {
812
+ const added = candidate.added_fields.join(", ");
813
+ writeStdout(
814
+ `${symbol.ok} ${candidate.path} \u2014 missing: ${missing} \u2192 added: ${added}`
815
+ );
816
+ } else {
817
+ writeStdout(`${symbol.warn} ${candidate.path} \u2014 missing: ${missing}`);
818
+ }
819
+ }
820
+ }
821
+ function parseSinceDuration(input) {
822
+ const trimmed = input.trim();
823
+ if (trimmed.length === 0) {
824
+ throw new Error(`invalid --since value: ${input}`);
825
+ }
826
+ const durationMatch = /^(\d+)([dhm])$/.exec(trimmed);
827
+ if (durationMatch !== null) {
828
+ const value = Number.parseInt(durationMatch[1], 10);
829
+ const unit = durationMatch[2];
830
+ if (!Number.isFinite(value) || value <= 0) {
831
+ throw new Error(`invalid --since value: ${input}`);
832
+ }
833
+ const unitMs = unit === "d" ? 864e5 : unit === "h" ? 36e5 : 6e4;
834
+ return Date.now() - value * unitMs;
835
+ }
836
+ if (/^\d+$/.test(trimmed)) {
837
+ const value = Number.parseInt(trimmed, 10);
838
+ if (!Number.isFinite(value) || value < 0) {
839
+ throw new Error(`invalid --since value: ${input}`);
840
+ }
841
+ return value;
842
+ }
843
+ throw new Error(`invalid --since value: ${input}`);
844
+ }
845
+ function renderArchiveHistoryReport(report, sinceLabel, dt) {
846
+ if (report.entries.length === 0) {
847
+ writeStdout(dt("doctor.archive-history.empty", { sinceLabel }));
848
+ return;
849
+ }
850
+ const lines = [];
851
+ lines.push(
852
+ dt("doctor.archive-history.header", {
853
+ sinceLabel,
854
+ count: String(report.total),
855
+ plural: report.total === 1 ? "" : "s"
856
+ })
857
+ );
858
+ lines.push("");
859
+ lines.push(
860
+ `| ${dt("doctor.archive-history.table.session")} | ${dt(
861
+ "doctor.archive-history.table.lastAttempt"
862
+ )} | ${dt("doctor.archive-history.table.outcome")} | ${dt(
863
+ "doctor.archive-history.table.candidates"
864
+ )} | ${dt("doctor.archive-history.table.coveredGap")} |`
865
+ );
866
+ lines.push("| ------- | ---------------- | -------- | ---------- | ----------- |");
867
+ for (const entry of report.entries) {
868
+ const lastAttempt = formatTimestampForTable(entry.last_attempted_at);
869
+ lines.push(
870
+ `| ${entry.session_id_short} | ${lastAttempt} | ${entry.outcome} | ${entry.candidates_proposed} | ${entry.age_since_covered_hours}h |`
871
+ );
872
+ }
873
+ writeStdout(lines.join("\n"));
874
+ }
875
+ function renderHistoryAllReport(report, sinceLabel, mode, dt) {
876
+ if (report.rows.length === 0) {
877
+ writeStdout(dt("doctor.history.empty", { sinceLabel, mode }));
878
+ return;
879
+ }
880
+ const lines = [];
881
+ lines.push(
882
+ dt("doctor.history.header", {
883
+ sinceLabel,
884
+ mode,
885
+ days: String(report.rows.length)
886
+ })
887
+ );
888
+ lines.push("");
889
+ if (mode === "fix") {
890
+ lines.push("| date | lint | fix | issues | mutations |");
891
+ lines.push("| ---------- | ---- | --- | ------ | --------- |");
892
+ for (const row of report.rows) {
893
+ lines.push(
894
+ `| ${row.date} | ${row.doctor_runs_lint} | ${row.doctor_runs_fix} | ${row.doctor_total_issues} | ${row.doctor_total_mutations} |`
895
+ );
896
+ }
897
+ } else {
898
+ lines.push("| date | lint | fix | issues | mutations | archive | proposed |");
899
+ lines.push("| ---------- | ---- | --- | ------ | --------- | ------- | -------- |");
900
+ for (const row of report.rows) {
901
+ lines.push(
902
+ `| ${row.date} | ${row.doctor_runs_lint} | ${row.doctor_runs_fix} | ${row.doctor_total_issues} | ${row.doctor_total_mutations} | ${row.archive_attempts} | ${row.archive_proposed} |`
903
+ );
904
+ }
905
+ }
906
+ writeStdout(lines.join("\n"));
907
+ }
908
+ function formatTimestampForTable(iso) {
909
+ const d = new Date(iso);
910
+ if (Number.isNaN(d.getTime())) return iso;
911
+ const pad = (n) => n < 10 ? `0${n}` : `${n}`;
912
+ return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(
913
+ d.getUTCHours()
914
+ )}:${pad(d.getUTCMinutes())}`;
915
+ }
916
+ export {
917
+ doctor_default as default,
918
+ doctorCommand,
919
+ parseSinceDuration
920
+ };