@luanpdd/kit-mcp 1.34.0 → 1.36.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 (118) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +2 -2
  3. package/bin/mcp.js +6 -6
  4. package/bin/ui.js +74 -74
  5. package/gates/ai-prompt-stability.md +120 -120
  6. package/gates/budget-description.md +68 -68
  7. package/gates/confidence.md +29 -29
  8. package/gates/dependency-check.md +33 -33
  9. package/gates/dept-cycle-prevention.md +179 -179
  10. package/gates/golden-signals-coverage.md +133 -133
  11. package/gates/legacy-refactor-safety.md +178 -178
  12. package/gates/multi-tenant-rls-coverage.md +102 -102
  13. package/gates/no-personal-uuid.md +72 -72
  14. package/gates/obs-agents-mcp-supabase.md +86 -86
  15. package/gates/obs-skills-frontmatter.md +76 -76
  16. package/gates/observability-coverage.md +151 -151
  17. package/gates/omm-no-regression.md +83 -83
  18. package/gates/postmortem-template-required.md +127 -127
  19. package/gates/prr-checklist-coverage.md +128 -128
  20. package/gates/regression.md +32 -32
  21. package/gates/release-pipeline-policy.md +132 -132
  22. package/gates/secrets-scan.md +33 -33
  23. package/gates/service-role-not-in-user-facing.md +113 -113
  24. package/gates/skill-must-include.md +71 -71
  25. package/gates/sync-idempotent.md +62 -62
  26. package/gates/verify-phase-goal.md +34 -34
  27. package/kit/agents/designer-ui.md +216 -216
  28. package/kit/agents/workflow-generator.md +537 -0
  29. package/kit/commands/adicionar-backlog.md +1 -1
  30. package/kit/commands/adicionar-fase.md +1 -1
  31. package/kit/commands/adicionar-tarefa.md +1 -1
  32. package/kit/commands/auditar-observabilidade.md +103 -103
  33. package/kit/commands/auditar-toil.md +129 -129
  34. package/kit/commands/caracterizar-prompt.md +195 -195
  35. package/kit/commands/criar-workflow.md +158 -0
  36. package/kit/commands/definir-perfil.md +1 -1
  37. package/kit/commands/definir-slo.md +108 -108
  38. package/kit/commands/fio.md +1 -1
  39. package/kit/commands/golden-signals.md +142 -142
  40. package/kit/commands/instrumentar-fase.md +200 -200
  41. package/kit/commands/investigar-producao.md +162 -162
  42. package/kit/commands/observabilidade.md +118 -118
  43. package/kit/commands/postmortem.md +179 -179
  44. package/kit/commands/prr.md +205 -205
  45. package/kit/commands/publicar-rapido.md +207 -207
  46. package/kit/commands/risk-budget.md +220 -220
  47. package/kit/commands/sre.md +230 -230
  48. package/kit/file-manifest.json +5 -2
  49. package/kit/framework/references/output-style.md +22 -22
  50. package/kit/hooks/post-apply-migration.js +199 -199
  51. package/kit/hooks/sidecar-tool-publisher.js +210 -210
  52. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
  53. package/kit/skills/_shared-legacy/glossary.md +389 -389
  54. package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
  55. package/kit/skills/_shared-observability/glossary.md +396 -396
  56. package/kit/skills/_shared-sre/glossary.md +712 -712
  57. package/kit/skills/_shared-supabase/glossary.md +234 -234
  58. package/kit/skills/blameless-postmortems/SKILL.md +340 -340
  59. package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
  60. package/kit/skills/cascading-failures/SKILL.md +311 -311
  61. package/kit/skills/core-analysis-loop/SKILL.md +352 -352
  62. package/kit/skills/distributed-tracing/SKILL.md +362 -362
  63. package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -0
  64. package/kit/skills/eliminating-toil/SKILL.md +243 -243
  65. package/kit/skills/event-based-slos/SKILL.md +296 -296
  66. package/kit/skills/four-golden-signals/SKILL.md +314 -314
  67. package/kit/skills/hermetic-builds/SKILL.md +323 -323
  68. package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
  69. package/kit/skills/llm-as-dependency/SKILL.md +436 -436
  70. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
  71. package/kit/skills/observability-driven-development/SKILL.md +315 -315
  72. package/kit/skills/observability-maturity-model/SKILL.md +222 -222
  73. package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
  74. package/kit/skills/production-readiness-review/SKILL.md +305 -305
  75. package/kit/skills/release-engineering/SKILL.md +367 -367
  76. package/kit/skills/retry-strategies/SKILL.md +372 -372
  77. package/kit/skills/sre-risk-management/SKILL.md +221 -221
  78. package/kit/skills/structured-events/SKILL.md +265 -265
  79. package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
  80. package/kit/skills/supabase-database-functions/SKILL.md +332 -332
  81. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
  82. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
  83. package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
  84. package/kit/skills/supabase-storage/SKILL.md +234 -234
  85. package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
  86. package/kit/skills/telemetry-sampling/SKILL.md +256 -256
  87. package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
  88. package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
  89. package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
  90. package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
  91. package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
  92. package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
  93. package/kit/skills/ui-tipografia/SKILL.md +211 -211
  94. package/package.json +1 -1
  95. package/src/cli/index.js +1114 -1114
  96. package/src/cli/render.js +194 -194
  97. package/src/cli/upgrade-check.js +135 -135
  98. package/src/core/error-redaction.js +76 -76
  99. package/src/core/failures.js +153 -153
  100. package/src/core/gate-runner.js +205 -205
  101. package/src/core/gates.js +82 -82
  102. package/src/core/logger.js +170 -170
  103. package/src/core/manifest-verify.js +174 -174
  104. package/src/core/metrics.js +268 -268
  105. package/src/core/notify.js +60 -60
  106. package/src/core/path-safety.js +141 -141
  107. package/src/core/replays.js +120 -120
  108. package/src/core/ui.js +185 -185
  109. package/src/mcp-server/install.js +149 -149
  110. package/src/mcp-server/roots.js +124 -124
  111. package/src/ui/auto-spawn.js +113 -113
  112. package/src/ui/browser.js +78 -78
  113. package/src/ui/client.js +130 -130
  114. package/src/ui/events.js +65 -65
  115. package/src/ui/lockfile.js +191 -191
  116. package/src/ui/port.js +67 -67
  117. package/src/ui/server.js +547 -547
  118. package/src/ui/wrapper.js +129 -129
package/src/cli/index.js CHANGED
@@ -1,1114 +1,1114 @@
1
- // CLI mirror of the MCP tools. Same operations, terminal-friendly.
2
- //
3
- // kit kit list-agents
4
- // kit kit get agent planner
5
- // kit sync targets
6
- // kit sync install claude-code --mode reference
7
- // kit gates list
8
- // kit forensics collect --project-root /path/to/project
9
- // kit install dry-run claude-code
10
- //
11
- // Default output: human-readable colored panels + summaries.
12
- // `--json` flag (global) restores the v1.0 JSON-to-stdout behavior for
13
- // programmatic consumers.
14
-
15
- import { Command } from 'commander';
16
- import { readFileSync } from 'node:fs';
17
- import { fileURLToPath } from 'node:url';
18
- import path from 'node:path';
19
- import { listKit, searchKit, findItem } from '../core/kit.js';
20
- import { listTargets } from '../core/registry.js';
21
- import { syncTo, statusOf, removeFrom, summarize } from '../core/sync.js';
22
- import { watchKit, detectExistingTargets } from '../core/watch.js';
23
- import { listGates, getGate, gatesForStage } from '../core/gates.js';
24
- import { runGate } from '../core/gate-runner.js';
25
- import { detectReverse, applyReverse } from '../core/reverse-sync.js';
26
- import { collectFailures, summarizeByAgent, writeLearnings } from '../core/failures.js';
27
- import { reflect } from '../core/reflect.js';
28
- import { listReplays, loadReplay } from '../core/replays.js';
29
- import { installMcp, listInstallTargets } from '../mcp-server/install.js';
30
- import { listLogs, tailLogs, logDir, currentLogPath } from '../core/logger.js';
31
- import * as render from './render.js';
32
- import { c, icons, spinner, progress, select, confirm } from '../core/ui.js';
33
- import { readLock, lockPathFor } from '../ui/lockfile.js';
34
- import { checkUpgrade } from './upgrade-check.js';
35
- // PERF-16-04: ui/server.js, ui/wrapper.js, ui/browser.js are loaded LAZILY
36
- // inside the subcommand handlers that need them. See:
37
- // - maybeWrapForUi (gated on lockfile presence)
38
- // - ui.start (createServer + openBrowser)
39
- // - ui.open (openBrowser)
40
- // This trims ~700 LOC + transitive deps off the cold-start path of non-UI
41
- // commands like `kit kit list-agents --terse`. lockfile.js stays eager because
42
- // readLock() is called by every withProgress() invocation and is dep-free.
43
- import http from 'node:http';
44
- import fs from 'node:fs';
45
- import os from 'node:os';
46
-
47
- // Read package.json version at boot so `--version` is always accurate. Falls
48
- // back to a string if the file lookup fails (e.g. unusual install layout).
49
- function readPkgVersion() {
50
- try {
51
- const here = path.dirname(fileURLToPath(import.meta.url));
52
- const pkgPath = path.resolve(here, '..', '..', 'package.json');
53
- return JSON.parse(readFileSync(pkgPath, 'utf8')).version;
54
- } catch {
55
- return 'unknown';
56
- }
57
- }
58
-
59
- const program = new Command()
60
- .name('kit')
61
- .description('Personal kit (agents/commands/skills) — CLI mirror of the kit-mcp server.')
62
- .version(readPkgVersion())
63
- .option('--kit-root <path>', 'Override the kit root (default: bundled example kit, or KIT_MCP_KIT_ROOT env)')
64
- .option('--json', 'Output JSON to stdout (machine-readable, restores pre-1.1 default)')
65
- .option('--no-ui', 'Suppress sidecar event publishing for this run (default: auto-detect lockfile)');
66
-
67
- program.hook('preAction', (thisCommand, actionCommand) => {
68
- const opts = program.opts();
69
- if (opts.kitRoot) process.env.KIT_MCP_KIT_ROOT = opts.kitRoot;
70
- });
71
-
72
- // `out(value, humanRenderer)` — uses the human renderer unless --json is set.
73
- function out(value, humanRenderer) {
74
- const opts = program.opts();
75
- if (opts.json) {
76
- process.stdout.write(JSON.stringify(value, null, 2) + '\n');
77
- } else if (typeof humanRenderer === 'function') {
78
- process.stdout.write(humanRenderer(value));
79
- } else {
80
- process.stdout.write(render.renderFallback(value));
81
- }
82
- }
83
-
84
- // withSpinner wraps a short opaque op with a spinner; auto-disabled in --json mode.
85
- async function withSpinner(text, fn) {
86
- const opts = program.opts();
87
- if (opts.json) return fn();
88
- const sp = spinner({ text });
89
- try {
90
- const r = await fn();
91
- sp.succeed();
92
- return r;
93
- } catch (e) {
94
- sp.fail(e.message);
95
- throw e;
96
- }
97
- }
98
-
99
- // withProgress wraps a long op; passes onProgress callback to the core fn.
100
- // Also auto-detects a running sidecar (via lockfile) and multiplexes events to
101
- // it when present. Opt-out via --no-ui or KIT_MCP_NO_UI=1.
102
- async function withProgress(label, total, fn, { tool, projectRoot } = {}) {
103
- const opts = program.opts();
104
- let onProgress;
105
- let p = null;
106
- if (opts.json) {
107
- onProgress = () => {};
108
- } else {
109
- p = progress({ total, label });
110
- let last = '';
111
- onProgress = ({ current, label }) => { last = label || last; p.tick({ label: last }); };
112
- }
113
-
114
- // Auto-wrap if a sidecar is running for this projectRoot.
115
- const wrapper = await maybeWrapForUi(onProgress, { tool, projectRoot });
116
- try {
117
- const r = await fn(wrapper);
118
- if (p) p.finish(label);
119
- if (wrapper.done) wrapper.done({ ok: true });
120
- return r;
121
- } catch (e) {
122
- if (p) p.finish();
123
- if (wrapper.error) wrapper.error(e);
124
- throw e;
125
- }
126
- }
127
-
128
- // maybeWrapForUi — returns the original callback unchanged when no sidecar is up
129
- // or the user opted out. Otherwise returns a wrapped callback with .done/.error.
130
- //
131
- // PERF-16-04: this is async because we lazy-load ../ui/wrapper.js only when a
132
- // sidecar lockfile is detected. Common path (no sidecar) returns synchronously
133
- // via passthroughWrapper without touching wrapper.js or its transitive deps.
134
- async function maybeWrapForUi(onProgress, { tool, projectRoot } = {}) {
135
- const globalOpts = program.opts();
136
- // commander stores `--no-ui` as opts.ui === false
137
- if (globalOpts.ui === false || process.env.KIT_MCP_NO_UI === '1') {
138
- return passthroughWrapper(onProgress);
139
- }
140
- const root = projectRoot || process.cwd();
141
- if (!readLock(root)) {
142
- return passthroughWrapper(onProgress);
143
- }
144
- // Lazy import — only paid when a sidecar IS up for this project.
145
- const { wrapProgressForUi } = await import('../ui/wrapper.js');
146
- return wrapProgressForUi(onProgress, { projectRoot: root, tool: tool ?? null });
147
- }
148
-
149
- function passthroughWrapper(onProgress) {
150
- const cb = (p) => { if (typeof onProgress === 'function') onProgress(p); };
151
- cb.done = () => {};
152
- cb.error = () => {};
153
- cb.emit = () => {};
154
- return cb;
155
- }
156
-
157
- function fail(msg) {
158
- process.stderr.write(`${c.red(icons.cross)} ${msg}\n`);
159
- process.exit(1);
160
- }
161
-
162
- function slim(x) {
163
- // PERF-13-01: cap description at SUMMARY_MAX_CHARS via shared summarize()
164
- // helper from src/core/sync.js — keeps cross-surface behavior identical
165
- // (CLI listing == MCP listing). Full text remains in each item's source file.
166
- return { kind: x.kind, name: x.name, description: summarize(x.description) };
167
- }
168
-
169
- // PERF-15-01: terse variant — paridade com mcp-server slimTerse. CLI flag --terse
170
- // controla seleção. Mantém o mesmo shape {kind, name} para programmatic consumers
171
- // que parseiam --json output (consistência cross-surface).
172
- function slimTerse(x) {
173
- return { kind: x.kind, name: x.name };
174
- }
175
-
176
- // --- kit ---
177
- const kit = program.command('kit').description('Browse the canonical kit.');
178
- kit.command('list-agents')
179
- .option('--terse', 'Omit description; return only {kind, name} (PERF-15-01)')
180
- .action(async (opts) => {
181
- const k = await withSpinner('Loading kit...', () => listKit());
182
- const variant = opts.terse ? slimTerse : slim;
183
- out(k.agents.map(variant), v => render.renderKitList(v, 'agent'));
184
- });
185
- kit.command('list-commands')
186
- .option('--terse', 'Omit description; return only {kind, name} (PERF-15-01)')
187
- .action(async (opts) => {
188
- const k = await withSpinner('Loading kit...', () => listKit());
189
- const variant = opts.terse ? slimTerse : slim;
190
- out(k.commands.map(variant), v => render.renderKitList(v, 'command'));
191
- });
192
- kit.command('list-skills')
193
- .option('--terse', 'Omit description; return only {kind, name} (PERF-15-01)')
194
- .action(async (opts) => {
195
- const k = await withSpinner('Loading kit...', () => listKit());
196
- const variant = opts.terse ? slimTerse : slim;
197
- out([...k.skills, ...k.skillsExtras].map(variant), v => render.renderKitList(v, 'skill'));
198
- });
199
- kit.command('get <kind> <name>').action(async (kind, name) => {
200
- const k = await listKit();
201
- const item = findItem(k, kind, name);
202
- if (!item) return fail(`Not found: ${kind}/${name}`);
203
- // Always raw for `kit get` — it's intended to be cat-like
204
- process.stdout.write(item.content ?? item.skillContent);
205
- });
206
- kit.command('search <query>').action(async (q) => out(searchKit(await listKit(), q), render.renderKitSearch));
207
-
208
- // --- sync ---
209
- const sync = program.command('sync').description('Project the kit into an IDE.');
210
- sync.command('targets').action(async () => {
211
- const targets = await withSpinner('Loading capability matrix...', async () => listTargets());
212
- out(targets, render.renderSyncTargets);
213
- });
214
- sync.command('status <target>')
215
- .option('--project-root <path>')
216
- .action(async (target, opts) => out(await statusOf(target, { projectRoot: opts.projectRoot }), render.renderSyncStatus));
217
- sync.command('install [target]')
218
- .option('--project-root <path>')
219
- .option('--mode <mode>', 'reference | copy', 'reference')
220
- .option('--dry-run')
221
- .option('--quiet', 'Suppress per-file progress; keep final summary')
222
- .action(async (target, opts) => {
223
- if (!target) target = await pickTarget(listTargets(), 'Which IDE do you want to sync the kit into?');
224
- // Phase 160 (v1.28): count written vs skipped so the post-sync summary
225
- // can render "X new/updated, Y unchanged".
226
- const tally = { written: 0, skipped: 0 };
227
- const wrapOnProgress = (orig) => (ev) => {
228
- if (ev?.skipped) tally.skipped += 1;
229
- else tally.written += 1;
230
- if (orig) orig(ev);
231
- };
232
- const runSync = (onProgress) => syncTo(target, {
233
- projectRoot: opts.projectRoot,
234
- mode: opts.mode,
235
- dryRun: opts.dryRun,
236
- onProgress: wrapOnProgress(opts.quiet ? null : onProgress),
237
- });
238
- const result = opts.quiet
239
- ? await runSync()
240
- : await withProgress(`Syncing kit → ${target}`, 300, runSync,
241
- { tool: 'sync.install', projectRoot: opts.projectRoot });
242
- result._tally = tally; // surfaced by renderSyncInstall (v1.28)
243
- out(result, render.renderSyncInstall);
244
- });
245
- sync.command('remove <target>')
246
- .option('--project-root <path>')
247
- .action(async (target, opts) => out(await removeFrom(target, { projectRoot: opts.projectRoot }), render.renderSyncRemove));
248
- sync.command('watch [targets...]')
249
- .description('Watch kit/ and re-sync to one or more IDEs on every change. Use --all to pick up every IDE that already has files in the project.')
250
- .option('--project-root <path>')
251
- .option('--mode <mode>', 'reference | copy', 'reference')
252
- .option('--debounce <ms>', 'Debounce window in ms', '300')
253
- .option('--all', 'Auto-detect every IDE target that currently has files in --project-root')
254
- .action(async (targets, opts) => {
255
- let list = targets ?? [];
256
- if (opts.all) {
257
- const detected = await detectExistingTargets({ projectRoot: opts.projectRoot });
258
- list = [...new Set([...list, ...detected])];
259
- }
260
- if (list.length === 0) return fail('No targets given. Pass <targets...> or --all.');
261
- const log = (s) => process.stderr.write(`[watch] ${s}\n`);
262
- const w = await watchKit(list, {
263
- projectRoot: opts.projectRoot,
264
- mode: opts.mode,
265
- debounceMs: parseInt(opts.debounce, 10),
266
- onLog: log,
267
- });
268
- log(`watching kit/ → ${list.join(', ')} (Ctrl+C to stop)`);
269
- const shutdown = async () => { log('shutting down...'); await w.stop(); process.exit(0); };
270
- process.on('SIGINT', shutdown);
271
- process.on('SIGTERM', shutdown);
272
- });
273
-
274
- // --- reverse-sync ---
275
- const reverse = program.command('reverse-sync').description('Detect and apply edits made directly in an IDE back to the canonical kit/.');
276
- reverse.command('detect <target>')
277
- .option('--project-root <path>')
278
- .action(async (target, opts) => out(await detectReverse(target, { projectRoot: opts.projectRoot }), render.renderReverseDetect));
279
- reverse.command('apply <target>')
280
- .option('--project-root <path>')
281
- .option('--strategy <s>', 'skip | overwrite | merge | rename', 'skip')
282
- .option('--only <items...>', 'Limit to these kind/name pairs (e.g. agent/planner skill/paperclip framework/workflows/foo.md)')
283
- .option('--dry-run')
284
- .action(async (target, opts) => {
285
- const result = await withProgress(
286
- `Applying reverse-sync (${opts.strategy})`,
287
- 50,
288
- (onProgress) => applyReverse(target, { projectRoot: opts.projectRoot, strategy: opts.strategy, only: opts.only, dryRun: opts.dryRun, onProgress }),
289
- { tool: 'reverse-sync.apply', projectRoot: opts.projectRoot },
290
- );
291
- out(result, render.renderReverseApply);
292
- });
293
-
294
- // --- gates ---
295
- const gates = program.command('gates').description('Reusable workflow gates.');
296
- gates.command('list').action(async () => out(await listGates(), render.renderGatesList));
297
- gates.command('get <id>').action(async (id) => process.stdout.write((await getGate(id)).content));
298
- gates.command('for-stage <stage>').action(async (stage) => out(await gatesForStage(stage), render.renderGatesList));
299
- gates.command('run <id>')
300
- .description('Execute a gate (with confirmation in interactive mode). Returns a structured verdict.')
301
- .option('--project-root <path>')
302
- .option('--yes', 'Skip confirmation (CI/non-interactive)')
303
- .option('--no-interactive', 'Never prompt; manual gates return verdict=manual')
304
- .action(async (id, opts) => out(await runGate(id, {
305
- projectRoot: opts.projectRoot,
306
- yes: opts.yes,
307
- interactive: opts.interactive !== false,
308
- }), render.renderGateRun));
309
-
310
- // --- forensics ---
311
- const forensics = program.command('forensics').description('Failure dataset & replays.');
312
- forensics.command('collect')
313
- .option('--project-root <path>')
314
- .action(async (opts) => out(await collectFailures({ projectRoot: opts.projectRoot }), render.renderForensicsCollect));
315
- forensics.command('summarize')
316
- .option('--project-root <path>')
317
- .action(async (opts) => {
318
- const f = await collectFailures({ projectRoot: opts.projectRoot });
319
- out(await summarizeByAgent(f), render.renderForensicsSummarize);
320
- });
321
- forensics.command('write-learnings')
322
- .option('--project-root <path>')
323
- .action(async (opts) => {
324
- const f = await collectFailures({ projectRoot: opts.projectRoot });
325
- out(await writeLearnings(f, { projectRoot: opts.projectRoot }), render.renderFallback);
326
- });
327
- forensics.command('list-replays')
328
- .option('--project-root <path>')
329
- .action(async (opts) => out(await listReplays({ projectRoot: opts.projectRoot }), render.renderListReplays));
330
- forensics.command('reflect')
331
- .description('LLM-pass: read learnings + current agent, propose minimal prompt edits, optionally apply.')
332
- .requiredOption('--agent <name>', 'Agent name (matches kit/agents/<name>.md)')
333
- .option('--project-root <path>')
334
- .option('--dry-run', 'Save the assembled prompt without calling the LLM')
335
- .option('--apply', 'Skip confirmation; apply the proposal directly')
336
- .option('--no-interactive', 'Save proposal but never prompt to apply')
337
- .action(async (opts) => out(await reflect({
338
- agent: opts.agent,
339
- projectRoot: opts.projectRoot,
340
- dryRun: opts.dryRun,
341
- apply: opts.apply,
342
- interactive: opts.interactive !== false,
343
- }), render.renderFallback));
344
- forensics.command('load-replay <id>')
345
- .option('--project-root <path>')
346
- .action(async (id, opts) => out(await loadReplay(id, { projectRoot: opts.projectRoot }), render.renderFallback));
347
-
348
- // --- install (the MCP server itself into an IDE) ---
349
- const install = program.command('install').description('Register kit-mcp into an IDE\'s MCP config.');
350
- install.command('targets').action(async () => out(listInstallTargets(), render.renderInstallTargets));
351
- install.command('dry-run <target>')
352
- .option('--scope <scope>', 'user | project', 'user')
353
- .option('--name <name>', 'Server name in IDE config', 'kit')
354
- .option('--via <via>', 'local | npx | global (how the IDE will invoke the server)', 'local')
355
- .option('--pkg <name>', 'npm package name (only with --via npx)', '@luanpdd/kit-mcp')
356
- .option('--project-root <path>')
357
- .action(async (target, opts) => out(await installMcp(target, { ...opts, dryRun: true }), render.renderInstallResult));
358
- install.command('write [target]')
359
- .option('--scope <scope>', 'user | project', 'user')
360
- .option('--name <name>', 'Server name in IDE config', 'kit')
361
- .option('--via <via>', 'local | npx | global', 'local')
362
- .option('--pkg <name>', 'npm package name (only with --via npx)', '@luanpdd/kit-mcp')
363
- .option('--force')
364
- .option('--project-root <path>')
365
- .option('--yes', 'Skip confirmation prompt (CI mode)')
366
- .action(async (target, opts) => {
367
- const globalOpts = program.opts();
368
- if (!target) target = await pickTarget(listInstallTargets(), 'Where do you want to register kit-mcp?');
369
-
370
- // Preview first (dry-run)
371
- const preview = await installMcp(target, { ...opts, dryRun: true });
372
- if (!preview.ok) {
373
- out(preview, render.renderInstallResult);
374
- process.exit(1);
375
- }
376
-
377
- // Show the preview unless --json
378
- if (!globalOpts.json) {
379
- process.stdout.write(`\n${c.bold('Preview:')} ${c.dim(preview.configPath)}\n\n`);
380
- if (preview.preview) {
381
- process.stdout.write(c.dim(JSON.stringify(preview.preview, null, 2)) + '\n');
382
- } else if (preview.snippet) {
383
- process.stdout.write(c.dim(preview.snippet) + '\n');
384
- }
385
- }
386
-
387
- // Confirm unless --yes or --json (programmatic consumers must pass --yes)
388
- if (!opts.yes && !globalOpts.json) {
389
- let proceed;
390
- try {
391
- proceed = await confirm({ message: 'Apply these changes?', default: false });
392
- } catch (e) {
393
- return fail(`${e.message} (use --yes to skip)`);
394
- }
395
- if (!proceed) {
396
- process.stdout.write(`${c.yellow(icons.warn)} Aborted by user.\n`);
397
- process.exit(0);
398
- }
399
- }
400
-
401
- out(await installMcp(target, opts), render.renderInstallResult);
402
- });
403
-
404
- // pickTarget — interactive selector for IDE targets, falls back to error in non-TTY/--json
405
- async function pickTarget(targets, message) {
406
- const globalOpts = program.opts();
407
- if (globalOpts.json) {
408
- return fail('--target is required when using --json mode');
409
- }
410
- try {
411
- return await select({
412
- message,
413
- choices: targets.map(t => ({
414
- name: `${t.label.padEnd(22)} ${c.dim(`(${t.id})`)}`,
415
- value: t.id,
416
- })),
417
- });
418
- } catch (e) {
419
- return fail(`${e.message} (or pass <target> as argument)`);
420
- }
421
- }
422
-
423
- // --- ui (sidecar process viewer) ---
424
- const ui = program.command('ui').description('Live process viewer in a localhost browser tab.');
425
-
426
- ui.command('start')
427
- .description('Start the sidecar HTTP server in foreground (Ctrl+C to stop). Prints URL on stderr.')
428
- .option('--project-root <path>', 'Project root for lockfile keying (default: cwd)')
429
- .option('--port <n>', 'Bind to a specific port (default: auto-pick 7100-7199)')
430
- .option('--idle-ms <ms>', 'Idle shutdown timeout (default 0 = never; e.g. 1800000 for 30min)')
431
- .option('--no-open', 'Skip auto-opening the browser')
432
- .action(async (opts) => {
433
- const projectRoot = opts.projectRoot || process.cwd();
434
- const port = opts.port ? Number(opts.port) : undefined;
435
- const idleMs = opts.idleMs !== undefined ? Number(opts.idleMs) : undefined;
436
- // PERF-16-04: lazy-load the sidecar HTTP server module only when starting it.
437
- const { createServer } = await import('../ui/server.js');
438
- const srv = createServer({ projectRoot, idleMs });
439
- try {
440
- const { port: actualPort } = await srv.start({ port });
441
- const url = `http://127.0.0.1:${actualPort}/`;
442
- process.stderr.write(`${c.cyan(icons.info)} kit-mcp ui listening on ${url}\n`);
443
- process.stderr.write(`${c.dim(` project: ${projectRoot}`)}\n`);
444
- // U4: non-blocking upgrade check. Warns if local install is behind npm latest.
445
- // Cached for 24h via ~/.kit-mcp/version-check.json so we don't hit npm on every start.
446
- checkUpgrade().then((info) => {
447
- if (info?.behind) {
448
- process.stderr.write(`${c.yellow(icons.warn)} kit-mcp v${info.local} → v${info.latest} disponível\n`);
449
- process.stderr.write(`${c.dim(' atualize com: npm i -g @luanpdd/kit-mcp@latest')}\n`);
450
- }
451
- }).catch(() => { /* offline / silent */ });
452
- if (opts.open !== false) {
453
- // PERF-16-04: lazy-load browser-opener (it lazy-loads `open` package itself).
454
- const { openBrowser } = await import('../ui/browser.js');
455
- await openBrowser(url);
456
- }
457
- // The server's own SIGINT handler will perform shutdown + cleanup.
458
- // We just stay alive — server is foreground.
459
- } catch (err) {
460
- if (err.code === 'ELIVE') {
461
- process.stderr.write(`${c.yellow(icons.warn)} sidecar already running for this project\n`);
462
- process.stderr.write(` pid: ${err.lock?.pid}, port: ${err.lock?.port}\n`);
463
- process.stderr.write(` use 'kit ui status' or 'kit ui open' to inspect\n`);
464
- process.exit(2);
465
- }
466
- fail(err.message);
467
- }
468
- });
469
-
470
- ui.command('stop')
471
- .description('Stop the sidecar running for this project (POST /shutdown).')
472
- .option('--project-root <path>')
473
- .action(async (opts) => {
474
- const projectRoot = opts.projectRoot || process.cwd();
475
- const lock = readLock(projectRoot);
476
- if (!lock) return out({ ok: false, reason: 'no_sidecar' }, () => `${icons.warn} no sidecar running for this project\n`);
477
- try {
478
- await postShutdown(lock.port, lock.token);
479
- out({ ok: true, port: lock.port }, () => `${icons.check} sidecar at port ${lock.port} stopped\n`);
480
- } catch (err) {
481
- fail(`could not stop sidecar at port ${lock.port}: ${err.message}`);
482
- }
483
- });
484
-
485
- ui.command('status')
486
- .description('Show whether a sidecar is running for this project.')
487
- .option('--project-root <path>')
488
- .action(async (opts) => {
489
- const projectRoot = opts.projectRoot || process.cwd();
490
- const lock = readLock(projectRoot);
491
- if (!lock) {
492
- out({ running: false, reason: 'no_lockfile' }, () => `${icons.warn} no sidecar running\n`);
493
- process.exit(1);
494
- }
495
- try {
496
- const health = await getHealthz(lock.port);
497
- out({ running: true, ...health, lockfile: lockPathFor(projectRoot) }, render.renderUiStatus ?? renderUiStatusFallback);
498
- } catch (err) {
499
- out({ running: false, reason: 'unreachable', lockfile: lockPathFor(projectRoot), error: err.message },
500
- () => `${icons.cross} lockfile present but sidecar unreachable: ${err.message}\n`);
501
- process.exit(1);
502
- }
503
- });
504
-
505
- ui.command('open')
506
- .description('Open the running sidecar in a browser. Fails if no sidecar is up.')
507
- .option('--project-root <path>')
508
- .action(async (opts) => {
509
- const projectRoot = opts.projectRoot || process.cwd();
510
- const lock = readLock(projectRoot);
511
- if (!lock) return fail('no sidecar running — start one with `kit ui start`');
512
- const url = `http://127.0.0.1:${lock.port}/`;
513
- // PERF-16-04: lazy-load browser-opener.
514
- const { openBrowser } = await import('../ui/browser.js');
515
- const r = await openBrowser(url, { force: true });
516
- if (!r.opened) {
517
- process.stderr.write(`${c.yellow(icons.warn)} could not open browser (${r.reason}); copy the URL above\n`);
518
- process.exit(1);
519
- }
520
- });
521
-
522
- // --- doctor (DX diagnostic) ---
523
- program.command('doctor')
524
- .description('Diagnose kit-mcp setup: version, sidecar, hook, settings.json, lockfile, .planning/.')
525
- .option('--project-root <path>', 'Project to diagnose (default: cwd)')
526
- .action(async (opts) => {
527
- const projectRoot = opts.projectRoot || process.cwd();
528
- const checks = await runDoctorChecks(projectRoot);
529
- const failed = checks.filter(c => c.status === 'fail').length;
530
- const warned = checks.filter(c => c.status === 'warn').length;
531
-
532
- if (program.opts().json) {
533
- out({ checks, failed, warned }, () => '');
534
- process.exit(failed > 0 ? 1 : 0);
535
- }
536
-
537
- process.stdout.write(`\n${c.bold('kit-mcp doctor')} — ${projectRoot}\n\n`);
538
- for (const check of checks) {
539
- const sym = check.status === 'pass' ? c.green(icons.check)
540
- : check.status === 'warn' ? c.yellow(icons.warn)
541
- : c.red(icons.cross);
542
- process.stdout.write(`${sym} ${c.bold(check.label)}\n`);
543
- if (check.detail) process.stdout.write(` ${c.dim(check.detail)}\n`);
544
- if (check.fix) process.stdout.write(` ${c.cyan('fix:')} ${check.fix}\n`);
545
- }
546
- process.stdout.write('\n');
547
- if (failed > 0) {
548
- process.stdout.write(`${c.red(icons.cross)} ${failed} check(s) failed\n`);
549
- process.exit(1);
550
- } else if (warned > 0) {
551
- process.stdout.write(`${c.yellow(icons.warn)} ${warned} warning(s) — kit-mcp is functional\n`);
552
- } else {
553
- process.stdout.write(`${c.green(icons.check)} all checks passed\n`);
554
- }
555
- });
556
-
557
- async function runDoctorChecks(projectRoot) {
558
- const checks = [];
559
-
560
- // 1. Version + upgrade availability
561
- const upgrade = await checkUpgrade();
562
- if (!upgrade) {
563
- checks.push({ label: 'version', status: 'fail',
564
- detail: 'could not read local package.json',
565
- fix: 'reinstall via `npm i -g @luanpdd/kit-mcp@latest`' });
566
- } else if (upgrade.latest === null) {
567
- checks.push({ label: 'version', status: 'warn',
568
- detail: `local v${upgrade.local} (offline — could not check npm)` });
569
- } else if (upgrade.behind) {
570
- checks.push({ label: 'version', status: 'warn',
571
- detail: `local v${upgrade.local}, latest v${upgrade.latest}`,
572
- fix: 'npm i -g @luanpdd/kit-mcp@latest' });
573
- } else {
574
- checks.push({ label: 'version', status: 'pass',
575
- detail: `v${upgrade.local} (latest)` });
576
- }
577
-
578
- // 2. Sidecar lockfile + healthz
579
- const lock = readLock(projectRoot);
580
- if (!lock) {
581
- checks.push({ label: 'sidecar', status: 'warn',
582
- detail: 'not running for this project',
583
- fix: 'kit ui start (or omit if you don\'t need the live viewer)' });
584
- } else {
585
- try {
586
- await getHealthz(lock.port);
587
- checks.push({ label: 'sidecar', status: 'pass',
588
- detail: `running on port ${lock.port} (pid ${lock.pid})` });
589
- } catch (err) {
590
- checks.push({ label: 'sidecar', status: 'fail',
591
- detail: `lockfile says port ${lock.port} but unreachable: ${err.message}`,
592
- fix: 'kit ui stop && kit ui start' });
593
- }
594
- }
595
-
596
- // 3. ~/.claude/settings.json — exists + valid JSON + hooks present?
597
- const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
598
- let settings = null;
599
- try {
600
- settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
601
- checks.push({ label: 'settings.json', status: 'pass',
602
- detail: settingsPath });
603
- } catch (err) {
604
- if (err.code === 'ENOENT') {
605
- checks.push({ label: 'settings.json', status: 'warn',
606
- detail: 'not found (expected for fresh Claude Code)',
607
- fix: 'will be created automatically by Claude Code' });
608
- } else {
609
- checks.push({ label: 'settings.json', status: 'fail',
610
- detail: `invalid JSON at ${settingsPath}: ${err.message}`,
611
- fix: 'edit the file or restore from .claude/settings.json.bak' });
612
- }
613
- }
614
-
615
- // 4. Hook installed?
616
- if (settings) {
617
- const hooks = settings.hooks?.PostToolUse;
618
- const hasHook = Array.isArray(hooks) && hooks.some((h) =>
619
- Array.isArray(h.hooks) && h.hooks.some((cmd) =>
620
- typeof cmd.command === 'string' && cmd.command.includes('sidecar-tool-publisher')));
621
- if (hasHook) {
622
- checks.push({ label: 'observability hook', status: 'pass',
623
- detail: 'sidecar-tool-publisher registered as PostToolUse' });
624
- } else {
625
- checks.push({ label: 'observability hook', status: 'warn',
626
- detail: 'sidecar-tool-publisher not registered',
627
- fix: 'see kit/hooks/sidecar-tool-publisher.js for installation snippet' });
628
- }
629
- }
630
-
631
- // 5. Bundled kit dirs exist
632
- const here = path.dirname(fileURLToPath(import.meta.url));
633
- const kitRoot = path.resolve(here, '..', '..', 'kit');
634
- const expected = ['agents', 'commands', 'skills'];
635
- const missing = expected.filter((d) => {
636
- try { return !fs.statSync(path.join(kitRoot, d)).isDirectory(); }
637
- catch { return true; }
638
- });
639
- if (missing.length === 0) {
640
- checks.push({ label: 'bundled kit', status: 'pass',
641
- detail: `agents/, commands/, skills/ found in ${kitRoot}` });
642
- } else {
643
- checks.push({ label: 'bundled kit', status: 'fail',
644
- detail: `missing: ${missing.join(', ')} in ${kitRoot}`,
645
- fix: 'reinstall via `npm i -g @luanpdd/kit-mcp@latest`' });
646
- }
647
-
648
- // 6. .planning/ in projectRoot — only warn if absent (not all projects use the framework)
649
- const planningDir = path.join(projectRoot, '.planning');
650
- if (fs.existsSync(planningDir)) {
651
- const stateOk = fs.existsSync(path.join(planningDir, 'STATE.md'));
652
- const roadmapOk = fs.existsSync(path.join(planningDir, 'ROADMAP.md'));
653
- if (stateOk && roadmapOk) {
654
- checks.push({ label: '.planning/', status: 'pass',
655
- detail: 'STATE.md + ROADMAP.md present' });
656
- } else {
657
- checks.push({ label: '.planning/', status: 'warn',
658
- detail: `present but missing ${[!stateOk && 'STATE.md', !roadmapOk && 'ROADMAP.md'].filter(Boolean).join(', ')}`,
659
- fix: 'run `kit saude` to repair, or `/novo-marco` if mid-cycle' });
660
- }
661
- } else {
662
- checks.push({ label: '.planning/', status: 'warn',
663
- detail: 'no framework state in this project',
664
- fix: 'run `/novo-projeto` to bootstrap, or skip if not using the framework' });
665
- }
666
-
667
- // 7. Stale lockfile cleanup hint
668
- try {
669
- const tmpdir = os.tmpdir();
670
- const orphans = fs.readdirSync(tmpdir).filter(n => /^kit-mcp-ui-[0-9a-f]{16}\.lock$/.test(n));
671
- const stale = [];
672
- for (const name of orphans) {
673
- try {
674
- const lock = JSON.parse(fs.readFileSync(path.join(tmpdir, name), 'utf8'));
675
- try { process.kill(lock.pid, 0); } catch (err) {
676
- if (err.code === 'ESRCH') stale.push(name);
677
- }
678
- } catch { /* skip unreadable */ }
679
- }
680
- if (stale.length > 0) {
681
- checks.push({ label: 'orphan lockfiles', status: 'warn',
682
- detail: `${stale.length} stale lockfile(s) in ${tmpdir}`,
683
- fix: stale.map(n => `rm "${path.join(tmpdir, n)}"`).join(' && ') });
684
- }
685
- } catch { /* tmpdir scan is best-effort */ }
686
-
687
- // 8. (v1.28) log dir writable — required for kit logs
688
- try {
689
- const dir = logDir();
690
- fs.mkdirSync(dir, { recursive: true });
691
- const probe = path.join(dir, `.doctor-probe-${process.pid}`);
692
- fs.writeFileSync(probe, '', 'utf8');
693
- fs.unlinkSync(probe);
694
- const files = listLogs();
695
- checks.push({ label: 'log dir', status: 'pass',
696
- detail: `${dir} writable (${files.length} log file${files.length === 1 ? '' : 's'})` });
697
- } catch (err) {
698
- checks.push({ label: 'log dir', status: 'fail',
699
- detail: `${logDir()} not writable: ${err.message}`,
700
- fix: 'check permissions or set KIT_MCP_LOG_DIR to a writable path' });
701
- }
702
-
703
- // 9. (v1.28) sidecar auto-spawn config — informational
704
- const noUi = process.env.KIT_MCP_NO_UI === '1' || process.env.KIT_MCP_NO_UI === 'true';
705
- checks.push({ label: 'sidecar auto-spawn', status: noUi ? 'warn' : 'pass',
706
- detail: noUi
707
- ? 'KIT_MCP_NO_UI=1 — sidecar will NOT auto-start on MCP boot'
708
- : 'enabled (default) — sidecar starts when MCP server boots',
709
- fix: noUi ? 'unset KIT_MCP_NO_UI if you want live tool-call visibility' : undefined });
710
-
711
- // 10. (v1.29) auto-install drift check — is .claude/.kit-mcp-version aligned
712
- // with the running kit-mcp package version?
713
- try {
714
- const versionMarker = path.join(projectRoot, '.claude', '.kit-mcp-version');
715
- const restartMarker = path.join(projectRoot, '.claude', '.kit-mcp-restart-required');
716
- let installedVersion = null;
717
- try { installedVersion = fs.readFileSync(versionMarker, 'utf8').trim(); } catch { /* not installed */ }
718
- const currentVersion = readPkgVersion();
719
-
720
- if (!installedVersion) {
721
- checks.push({ label: 'auto-install', status: 'warn',
722
- detail: '.claude/.kit-mcp-version not found — kit not auto-installed in this project',
723
- fix: 'call kit:auto-install MCP tool, or run: kit init' });
724
- } else if (installedVersion !== currentVersion) {
725
- checks.push({ label: 'auto-install', status: 'warn',
726
- detail: `kit installed v${installedVersion}, MCP server is v${currentVersion}`,
727
- fix: 'call kit:auto-install (idempotent) or rerun: kit sync claude-code' });
728
- } else {
729
- checks.push({ label: 'auto-install', status: 'pass',
730
- detail: `v${installedVersion} (in sync)` });
731
- }
732
-
733
- if (fs.existsSync(restartMarker)) {
734
- let payload = {};
735
- try { payload = JSON.parse(fs.readFileSync(restartMarker, 'utf8')); } catch { /* malformed */ }
736
- checks.push({ label: 'restart pending', status: 'warn',
737
- detail: payload.reason
738
- ? `${payload.reason} (written ${payload.writtenAt || 'unknown'})`
739
- : 'restart marker present — IDE not yet reloaded since last auto-install',
740
- fix: 'restart your IDE session, then call kit:ack-restart MCP tool (or just close/reopen)' });
741
- }
742
- } catch { /* .claude/ check is best-effort */ }
743
-
744
- return checks;
745
- }
746
-
747
- // Helpers for kit ui (live in cli/ — stdout/console allowed here)
748
- // SEC-14-02: /shutdown now requires Authorization Bearer <token>. Caller must
749
- // pass the per-process token read from the lockfile (lock.token from readLock).
750
- async function postShutdown(port, token) {
751
- return new Promise((resolve, reject) => {
752
- const headers = {
753
- host: `127.0.0.1:${port}`,
754
- origin: `http://127.0.0.1:${port}`,
755
- 'content-length': 0,
756
- connection: 'close',
757
- };
758
- if (token) headers.authorization = `Bearer ${token}`;
759
- const req = http.request({
760
- method: 'POST',
761
- host: '127.0.0.1',
762
- port,
763
- path: '/shutdown',
764
- agent: false,
765
- headers,
766
- }, (res) => {
767
- res.resume();
768
- res.on('end', () => res.statusCode < 400 ? resolve() : reject(new Error(`http_${res.statusCode}`)));
769
- });
770
- req.on('error', reject);
771
- req.setTimeout(2000, () => { try { req.destroy(); } catch {} ; reject(new Error('timeout')); });
772
- req.end();
773
- });
774
- }
775
-
776
- async function getHealthz(port) {
777
- return new Promise((resolve, reject) => {
778
- const req = http.request({
779
- method: 'GET',
780
- host: '127.0.0.1',
781
- port,
782
- path: '/healthz',
783
- agent: false,
784
- headers: { host: `127.0.0.1:${port}`, connection: 'close' },
785
- }, (res) => {
786
- const chunks = [];
787
- res.on('data', (c) => chunks.push(c));
788
- res.on('end', () => {
789
- if (res.statusCode >= 400) return reject(new Error(`http_${res.statusCode}`));
790
- try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
791
- catch (e) { reject(e); }
792
- });
793
- });
794
- req.on('error', reject);
795
- req.setTimeout(2000, () => { try { req.destroy(); } catch {} ; reject(new Error('timeout')); });
796
- req.end();
797
- });
798
- }
799
-
800
- function renderUiStatusFallback(v) {
801
- if (!v.running) return `${icons.warn} not running\n`;
802
- return [
803
- `${icons.check} sidecar running`,
804
- ` port: ${v.port}`,
805
- ` pid (sdcr): ${v.lockfile ? readLock(process.cwd())?.pid : '?'}`,
806
- ` uptime: ${Math.round((v.uptime || 0) / 1000)}s`,
807
- ` events: ${v.eventsTotal}`,
808
- ` subscribers: ${v.subscribers}`,
809
- ` url: http://127.0.0.1:${v.port}/`,
810
- '',
811
- ].join('\n');
812
- }
813
-
814
- // --- status (Phase 162, v1.28: live metrics snapshot + log file path) ---
815
- program.command('status')
816
- .description('Show MCP server metrics (p50/p95/p99/error rate) + log file path.')
817
- .option('--project-root <path>', 'Default: cwd')
818
- .action(async (opts) => {
819
- const { snapshot, loadSnapshots } = await import('../core/metrics.js');
820
- const projectRoot = opts.projectRoot || process.cwd();
821
- const live = snapshot(); // current-process metrics (only useful when called from inside the MCP process)
822
- const persisted = await loadSnapshots(projectRoot, 60 * 60 * 1000).catch(() => []); // last hour
823
-
824
- if (program.opts().json) {
825
- out({ live, persistedCount: persisted.length, latest: persisted[persisted.length - 1] || null, logPath: currentLogPath() }, () => '');
826
- return;
827
- }
828
-
829
- process.stdout.write(`\n${c.bold('kit-mcp status')}\n\n`);
830
-
831
- // Sidecar
832
- const lock = readLock(projectRoot);
833
- process.stdout.write(`${c.bold('sidecar:')} ${lock ? c.green(`running on port ${lock.port}`) : c.dim('not running')}\n`);
834
-
835
- // Log file
836
- const files = listLogs();
837
- process.stdout.write(`${c.bold('log:')} ${currentLogPath()}\n`);
838
- process.stdout.write(` ${c.dim(`${files.length} file(s) in ${logDir()}`)}\n`);
839
-
840
- // Latency from latest persisted snapshot (last hour window)
841
- const latest = persisted[persisted.length - 1];
842
- const lat = latest?.latency || live.latency || {};
843
- const tools = Object.keys(lat);
844
- process.stdout.write(`\n${c.bold('latency (last hour, or current process):')}\n`);
845
- if (tools.length === 0) {
846
- process.stdout.write(` ${c.dim('no samples yet')}\n`);
847
- } else {
848
- const w = Math.max(...tools.map((t) => t.length));
849
- for (const t of tools) {
850
- const s = lat[t];
851
- process.stdout.write(` ${t.padEnd(w)} p50 ${c.cyan(s.p50 + 'ms').padEnd(20)} p95 ${c.cyan(s.p95 + 'ms').padEnd(20)} p99 ${c.cyan(s.p99 + 'ms').padEnd(20)} n=${s.count}\n`);
852
- }
853
- }
854
-
855
- // Error rate from counters
856
- const counters = latest?.counters || live.counters || {};
857
- let okTotal = 0, errTotal = 0;
858
- for (const [k, v] of Object.entries(counters)) {
859
- if (k.endsWith(':ok')) okTotal += v;
860
- if (k.endsWith(':error')) errTotal += v;
861
- }
862
- const total = okTotal + errTotal;
863
- const rate = total === 0 ? 0 : (errTotal / total) * 100;
864
- process.stdout.write(`\n${c.bold('errors:')} ${errTotal}/${total} (${rate.toFixed(2)}%)\n\n`);
865
- });
866
-
867
- // --- init (Phase 161, v1.28: guided onboarding — install + sync + doctor) ---
868
- program.command('init')
869
- .description('Onboard: register kit-mcp into an IDE, sync the kit, run doctor.')
870
- .option('--ide <id>', 'Skip the IDE picker (e.g. claude-code, cursor, codex)')
871
- .option('--project-root <path>', 'Default: cwd')
872
- .option('--non-interactive', 'Fail fast if --ide is missing instead of prompting')
873
- .option('--mode <mode>', 'sync mode: reference | copy', 'reference')
874
- .action(async (opts) => {
875
- const projectRoot = opts.projectRoot || process.cwd();
876
- const targets = listInstallTargets();
877
- const targetIds = targets.map(t => t.id);
878
-
879
- let ide = opts.ide;
880
- if (!ide) {
881
- if (opts.nonInteractive) {
882
- process.stderr.write(`${c.red(icons.cross)} --non-interactive requires --ide=<${targetIds.join('|')}>\n`);
883
- process.exit(2);
884
- }
885
- ide = await pickTarget(targets, 'Which IDE should kit-mcp register with?');
886
- }
887
- if (!targetIds.includes(ide)) {
888
- process.stderr.write(`${c.red(icons.cross)} unknown IDE "${ide}" — valid: ${targetIds.join(', ')}\n`);
889
- process.exit(2);
890
- }
891
-
892
- process.stdout.write(`\n${c.bold('kit init')} → ${ide}\n\n`);
893
-
894
- // 1. Register MCP server in IDE config
895
- process.stdout.write(`${c.cyan('1/3')} registering MCP server...\n`);
896
- try {
897
- const r = await installMcp(ide, { projectRoot });
898
- process.stdout.write(` ${c.green(icons.check)} ${r.path || 'config updated'}\n`);
899
- } catch (e) {
900
- process.stdout.write(` ${c.red(icons.cross)} ${e.message}\n`);
901
- process.exit(1);
902
- }
903
-
904
- // 2. Sync kit content
905
- process.stdout.write(`\n${c.cyan('2/3')} syncing kit content...\n`);
906
- const tally = { written: 0, skipped: 0 };
907
- try {
908
- const r = await syncTo(ide, {
909
- projectRoot,
910
- mode: opts.mode,
911
- onProgress: (ev) => { if (ev?.skipped) tally.skipped += 1; else tally.written += 1; },
912
- });
913
- const total = (r.written || []).length;
914
- process.stdout.write(` ${c.green(icons.check)} ${total} files (${tally.written} new/updated, ${tally.skipped} unchanged)\n`);
915
- } catch (e) {
916
- process.stdout.write(` ${c.red(icons.cross)} ${e.message}\n`);
917
- process.exit(1);
918
- }
919
-
920
- // 3. Doctor
921
- process.stdout.write(`\n${c.cyan('3/3')} running diagnostic...\n`);
922
- const checks = await runDoctorChecks(projectRoot);
923
- const failed = checks.filter(c => c.status === 'fail').length;
924
- const warned = checks.filter(c => c.status === 'warn').length;
925
- const passed = checks.length - failed - warned;
926
- process.stdout.write(` ${failed === 0 ? c.green(icons.check) : c.red(icons.cross)} `
927
- + `${passed} pass · ${warned} warn · ${failed} fail\n`);
928
-
929
- // 4. Final confirmation
930
- try {
931
- const kit = await listKit();
932
- process.stdout.write(`\n${c.green(icons.check)} ${c.bold(ide)} now sees `
933
- + `${c.cyan(kit.skills.length)} skills, `
934
- + `${c.cyan(kit.agents.length)} agents, `
935
- + `${c.cyan(kit.commands.length)} commands\n\n`);
936
- } catch { /* non-fatal */ }
937
-
938
- if (failed > 0) {
939
- process.stdout.write(`${c.yellow(icons.warn)} doctor reported failures — run ${c.cyan('kit doctor')} for details\n`);
940
- process.exit(1);
941
- }
942
- });
943
-
944
- // --- replay (Phase 165, v1.28: inspect recorded agent Task() payloads) ---
945
- const replay = program.command('replay').description('List or inspect recorded agent replays.');
946
-
947
- replay.command('list')
948
- .description('List replays in <project-root>/.planning/replays/')
949
- .option('--project-root <path>', 'Default: cwd')
950
- .action(async (opts) => {
951
- const projectRoot = opts.projectRoot || process.cwd();
952
- const items = await listReplays({ projectRoot });
953
- if (program.opts().json) {
954
- out(items, () => '');
955
- return;
956
- }
957
- if (items.length === 0) {
958
- process.stderr.write(`${c.yellow(icons.warn)} no replays at ${path.join(projectRoot, '.planning', 'replays')}\n`);
959
- return;
960
- }
961
- process.stdout.write(`\n${c.bold(items.length + ' replay(s)')}\n\n`);
962
- for (const r of items) {
963
- process.stdout.write(` ${c.cyan(r.id)}\n`);
964
- process.stdout.write(` agent: ${c.bold(r.agent || '?')} phase: ${r.phase || '?'} plan: ${r.plan || '?'}\n`);
965
- process.stdout.write(` ${c.dim(r.recorded_at || '?')}\n\n`);
966
- }
967
- });
968
-
969
- replay.command('show <id>')
970
- .description('Show the full recorded payload for a replay id.')
971
- .option('--project-root <path>', 'Default: cwd')
972
- .action(async (id, opts) => {
973
- const projectRoot = opts.projectRoot || process.cwd();
974
- try {
975
- const r = await loadReplay(id, { projectRoot });
976
- if (program.opts().json) {
977
- out(r, () => '');
978
- return;
979
- }
980
- process.stdout.write(`\n${c.bold(r.id)}\n`);
981
- process.stdout.write(`${c.dim('recorded:')} ${r.recorded_at}\n`);
982
- process.stdout.write(`${c.dim('agent:')} ${c.bold(r.agent || '?')}\n`);
983
- process.stdout.write(`${c.dim('phase:')} ${r.phase || '?'}\n`);
984
- process.stdout.write(`${c.dim('plan:')} ${r.plan || '?'}\n`);
985
- if (r.outcome) {
986
- process.stdout.write(`${c.dim('outcome:')} ${JSON.stringify(r.outcome)}\n`);
987
- }
988
- process.stdout.write(`\n${c.bold('payload:')}\n`);
989
- const { id: _id, recorded_at: _rec, agent: _a, phase: _p, plan: _pl, outcome: _o, ...rest } = r;
990
- process.stdout.write(JSON.stringify(rest, null, 2) + '\n');
991
- } catch (e) {
992
- process.stderr.write(`${c.red(icons.cross)} replay "${id}" not found: ${e.message}\n`);
993
- process.exit(1);
994
- }
995
- });
996
-
997
- replay.command('diff <id>')
998
- .description('Compare a replay payload against its most recent re-record (if any).')
999
- .option('--project-root <path>', 'Default: cwd')
1000
- .action(async (id, opts) => {
1001
- const projectRoot = opts.projectRoot || process.cwd();
1002
- try {
1003
- const target = await loadReplay(id, { projectRoot });
1004
- const all = await listReplays({ projectRoot });
1005
- // Find newest replay with same agent that isn't the target itself.
1006
- const candidate = all.find((r) => r.id !== id && r.agent === target.agent);
1007
- if (!candidate) {
1008
- process.stdout.write(`${c.yellow(icons.warn)} no peer replay for agent "${target.agent}" — nothing to diff\n`);
1009
- return;
1010
- }
1011
- const newer = await loadReplay(candidate.id, { projectRoot });
1012
- const a = JSON.stringify(target, null, 2).split('\n');
1013
- const b = JSON.stringify(newer, null, 2).split('\n');
1014
- process.stdout.write(`\n${c.bold(`diff ${id} ↔ ${candidate.id}`)}\n\n`);
1015
- const max = Math.max(a.length, b.length);
1016
- for (let i = 0; i < max; i++) {
1017
- if (a[i] !== b[i]) {
1018
- if (a[i] !== undefined) process.stdout.write(c.red('-') + ' ' + a[i] + '\n');
1019
- if (b[i] !== undefined) process.stdout.write(c.green('+') + ' ' + b[i] + '\n');
1020
- }
1021
- }
1022
- } catch (e) {
1023
- process.stderr.write(`${c.red(icons.cross)} ${e.message}\n`);
1024
- process.exit(1);
1025
- }
1026
- });
1027
-
1028
- // --- inspect (Phase 163, v1.28: live TUI mirror of MCP request/response) ---
1029
- program.command('inspect')
1030
- .description('Live request/response mirror — pretty-print MCP tool calls as they happen.')
1031
- .option('--tail <n>', 'show last N events (default 20)', '20')
1032
- .action(async (opts) => {
1033
- const lines = parseInt(opts.tail, 10) || 20;
1034
- if (process.env.KIT_MCP_INSPECT !== '1' && process.env.KIT_MCP_INSPECT !== 'true') {
1035
- process.stderr.write(`${c.yellow(icons.warn)} verbose payload capture is OFF\n`);
1036
- process.stderr.write(`${c.dim('set KIT_MCP_INSPECT=1 in the env where kit-mcp runs to capture args/result')}\n`);
1037
- process.stderr.write(`${c.dim('(events are still tailed; just without payloads)')}\n\n`);
1038
- }
1039
-
1040
- const render = (raw) => {
1041
- try {
1042
- const ev = JSON.parse(raw);
1043
- const t = ev.ts ? ev.ts.replace('T', ' ').replace('Z', '') : '?';
1044
- const status = ev.status === 'ok' ? c.green('●') : c.red('●');
1045
- const tool = c.bold(ev.tool || '?');
1046
- const action = ev.action ? c.cyan(ev.action) : '';
1047
- const dur = ev.duration_ms !== undefined ? c.dim(`(${ev.duration_ms}ms)`) : '';
1048
- process.stdout.write(`\n${status} ${c.dim(t)} ${tool} ${action} ${dur}\n`);
1049
- if (ev.args !== undefined) {
1050
- process.stdout.write(` ${c.dim('req:')} ${JSON.stringify(ev.args)}\n`);
1051
- }
1052
- if (ev.result !== undefined && ev.result !== null) {
1053
- const pretty = JSON.stringify(ev.result);
1054
- process.stdout.write(` ${c.dim('res:')} ${pretty.length > 200 ? pretty.slice(0, 200) + '…' : pretty}\n`);
1055
- }
1056
- if (ev.error_type) {
1057
- process.stdout.write(` ${c.red('err:')} ${ev.error_type}\n`);
1058
- }
1059
- } catch {
1060
- process.stdout.write(raw + '\n');
1061
- }
1062
- };
1063
-
1064
- const t = tailLogs({ lines, follow: true, onLine: render });
1065
- process.stdout.write(`${c.dim(`-- inspecting ${currentLogPath()} (Ctrl-C to stop) --`)}\n`);
1066
- process.on('SIGINT', () => { t.stop(); process.exit(0); });
1067
- await new Promise(() => {});
1068
- });
1069
-
1070
- // --- logs (Phase 158, v1.28: tail kit-mcp tool-call log) ---
1071
- program.command('logs')
1072
- .description('Tail JSONL logs of MCP tool invocations (~/.kit-mcp/logs/).')
1073
- .option('--tail <n>', 'show last N lines (default 50)', '50')
1074
- .option('--follow', 'keep streaming new events as they arrive')
1075
- .option('--path', 'print the current log file path and exit')
1076
- .action(async (opts) => {
1077
- if (opts.path) {
1078
- process.stdout.write(`${currentLogPath()}\n`);
1079
- return;
1080
- }
1081
- const lines = parseInt(opts.tail, 10) || 50;
1082
- const files = listLogs();
1083
- if (files.length === 0) {
1084
- process.stderr.write(`${c.yellow(icons.warn)} no logs yet at ${logDir()}\n`);
1085
- process.stderr.write(`${c.dim('logs are appended when the MCP server handles a tool call')}\n`);
1086
- process.exit(0);
1087
- }
1088
- const isJson = program.opts().json;
1089
- const render = (raw) => {
1090
- if (isJson) { process.stdout.write(raw + '\n'); return; }
1091
- try {
1092
- const ev = JSON.parse(raw);
1093
- const t = ev.ts ? ev.ts.replace('T', ' ').replace('Z', '') : '?';
1094
- const status = ev.status === 'ok' ? c.green(icons.check) : c.red(icons.cross);
1095
- const tool = c.bold(ev.tool || '?');
1096
- const action = ev.action ? c.dim(`[${ev.action}]`) : '';
1097
- const dur = ev.duration_ms !== undefined ? c.cyan(`${ev.duration_ms}ms`) : '';
1098
- const err = ev.error_type ? c.red(` (${ev.error_type})`) : '';
1099
- process.stdout.write(`${c.dim(t)} ${status} ${tool} ${action} ${dur}${err}\n`);
1100
- } catch {
1101
- process.stdout.write(raw + '\n');
1102
- }
1103
- };
1104
-
1105
- const t = tailLogs({ lines, follow: !!opts.follow, onLine: render });
1106
- if (opts.follow) {
1107
- process.stdout.write(`${c.dim(`-- following ${currentLogPath()} (Ctrl-C to stop) --`)}\n`);
1108
- process.on('SIGINT', () => { t.stop(); process.exit(0); });
1109
- // keep process alive
1110
- await new Promise(() => {});
1111
- }
1112
- });
1113
-
1114
- program.parseAsync(process.argv);
1
+ // CLI mirror of the MCP tools. Same operations, terminal-friendly.
2
+ //
3
+ // kit kit list-agents
4
+ // kit kit get agent planner
5
+ // kit sync targets
6
+ // kit sync install claude-code --mode reference
7
+ // kit gates list
8
+ // kit forensics collect --project-root /path/to/project
9
+ // kit install dry-run claude-code
10
+ //
11
+ // Default output: human-readable colored panels + summaries.
12
+ // `--json` flag (global) restores the v1.0 JSON-to-stdout behavior for
13
+ // programmatic consumers.
14
+
15
+ import { Command } from 'commander';
16
+ import { readFileSync } from 'node:fs';
17
+ import { fileURLToPath } from 'node:url';
18
+ import path from 'node:path';
19
+ import { listKit, searchKit, findItem } from '../core/kit.js';
20
+ import { listTargets } from '../core/registry.js';
21
+ import { syncTo, statusOf, removeFrom, summarize } from '../core/sync.js';
22
+ import { watchKit, detectExistingTargets } from '../core/watch.js';
23
+ import { listGates, getGate, gatesForStage } from '../core/gates.js';
24
+ import { runGate } from '../core/gate-runner.js';
25
+ import { detectReverse, applyReverse } from '../core/reverse-sync.js';
26
+ import { collectFailures, summarizeByAgent, writeLearnings } from '../core/failures.js';
27
+ import { reflect } from '../core/reflect.js';
28
+ import { listReplays, loadReplay } from '../core/replays.js';
29
+ import { installMcp, listInstallTargets } from '../mcp-server/install.js';
30
+ import { listLogs, tailLogs, logDir, currentLogPath } from '../core/logger.js';
31
+ import * as render from './render.js';
32
+ import { c, icons, spinner, progress, select, confirm } from '../core/ui.js';
33
+ import { readLock, lockPathFor } from '../ui/lockfile.js';
34
+ import { checkUpgrade } from './upgrade-check.js';
35
+ // PERF-16-04: ui/server.js, ui/wrapper.js, ui/browser.js are loaded LAZILY
36
+ // inside the subcommand handlers that need them. See:
37
+ // - maybeWrapForUi (gated on lockfile presence)
38
+ // - ui.start (createServer + openBrowser)
39
+ // - ui.open (openBrowser)
40
+ // This trims ~700 LOC + transitive deps off the cold-start path of non-UI
41
+ // commands like `kit kit list-agents --terse`. lockfile.js stays eager because
42
+ // readLock() is called by every withProgress() invocation and is dep-free.
43
+ import http from 'node:http';
44
+ import fs from 'node:fs';
45
+ import os from 'node:os';
46
+
47
+ // Read package.json version at boot so `--version` is always accurate. Falls
48
+ // back to a string if the file lookup fails (e.g. unusual install layout).
49
+ function readPkgVersion() {
50
+ try {
51
+ const here = path.dirname(fileURLToPath(import.meta.url));
52
+ const pkgPath = path.resolve(here, '..', '..', 'package.json');
53
+ return JSON.parse(readFileSync(pkgPath, 'utf8')).version;
54
+ } catch {
55
+ return 'unknown';
56
+ }
57
+ }
58
+
59
+ const program = new Command()
60
+ .name('kit')
61
+ .description('Personal kit (agents/commands/skills) — CLI mirror of the kit-mcp server.')
62
+ .version(readPkgVersion())
63
+ .option('--kit-root <path>', 'Override the kit root (default: bundled example kit, or KIT_MCP_KIT_ROOT env)')
64
+ .option('--json', 'Output JSON to stdout (machine-readable, restores pre-1.1 default)')
65
+ .option('--no-ui', 'Suppress sidecar event publishing for this run (default: auto-detect lockfile)');
66
+
67
+ program.hook('preAction', (thisCommand, actionCommand) => {
68
+ const opts = program.opts();
69
+ if (opts.kitRoot) process.env.KIT_MCP_KIT_ROOT = opts.kitRoot;
70
+ });
71
+
72
+ // `out(value, humanRenderer)` — uses the human renderer unless --json is set.
73
+ function out(value, humanRenderer) {
74
+ const opts = program.opts();
75
+ if (opts.json) {
76
+ process.stdout.write(JSON.stringify(value, null, 2) + '\n');
77
+ } else if (typeof humanRenderer === 'function') {
78
+ process.stdout.write(humanRenderer(value));
79
+ } else {
80
+ process.stdout.write(render.renderFallback(value));
81
+ }
82
+ }
83
+
84
+ // withSpinner wraps a short opaque op with a spinner; auto-disabled in --json mode.
85
+ async function withSpinner(text, fn) {
86
+ const opts = program.opts();
87
+ if (opts.json) return fn();
88
+ const sp = spinner({ text });
89
+ try {
90
+ const r = await fn();
91
+ sp.succeed();
92
+ return r;
93
+ } catch (e) {
94
+ sp.fail(e.message);
95
+ throw e;
96
+ }
97
+ }
98
+
99
+ // withProgress wraps a long op; passes onProgress callback to the core fn.
100
+ // Also auto-detects a running sidecar (via lockfile) and multiplexes events to
101
+ // it when present. Opt-out via --no-ui or KIT_MCP_NO_UI=1.
102
+ async function withProgress(label, total, fn, { tool, projectRoot } = {}) {
103
+ const opts = program.opts();
104
+ let onProgress;
105
+ let p = null;
106
+ if (opts.json) {
107
+ onProgress = () => {};
108
+ } else {
109
+ p = progress({ total, label });
110
+ let last = '';
111
+ onProgress = ({ current, label }) => { last = label || last; p.tick({ label: last }); };
112
+ }
113
+
114
+ // Auto-wrap if a sidecar is running for this projectRoot.
115
+ const wrapper = await maybeWrapForUi(onProgress, { tool, projectRoot });
116
+ try {
117
+ const r = await fn(wrapper);
118
+ if (p) p.finish(label);
119
+ if (wrapper.done) wrapper.done({ ok: true });
120
+ return r;
121
+ } catch (e) {
122
+ if (p) p.finish();
123
+ if (wrapper.error) wrapper.error(e);
124
+ throw e;
125
+ }
126
+ }
127
+
128
+ // maybeWrapForUi — returns the original callback unchanged when no sidecar is up
129
+ // or the user opted out. Otherwise returns a wrapped callback with .done/.error.
130
+ //
131
+ // PERF-16-04: this is async because we lazy-load ../ui/wrapper.js only when a
132
+ // sidecar lockfile is detected. Common path (no sidecar) returns synchronously
133
+ // via passthroughWrapper without touching wrapper.js or its transitive deps.
134
+ async function maybeWrapForUi(onProgress, { tool, projectRoot } = {}) {
135
+ const globalOpts = program.opts();
136
+ // commander stores `--no-ui` as opts.ui === false
137
+ if (globalOpts.ui === false || process.env.KIT_MCP_NO_UI === '1') {
138
+ return passthroughWrapper(onProgress);
139
+ }
140
+ const root = projectRoot || process.cwd();
141
+ if (!readLock(root)) {
142
+ return passthroughWrapper(onProgress);
143
+ }
144
+ // Lazy import — only paid when a sidecar IS up for this project.
145
+ const { wrapProgressForUi } = await import('../ui/wrapper.js');
146
+ return wrapProgressForUi(onProgress, { projectRoot: root, tool: tool ?? null });
147
+ }
148
+
149
+ function passthroughWrapper(onProgress) {
150
+ const cb = (p) => { if (typeof onProgress === 'function') onProgress(p); };
151
+ cb.done = () => {};
152
+ cb.error = () => {};
153
+ cb.emit = () => {};
154
+ return cb;
155
+ }
156
+
157
+ function fail(msg) {
158
+ process.stderr.write(`${c.red(icons.cross)} ${msg}\n`);
159
+ process.exit(1);
160
+ }
161
+
162
+ function slim(x) {
163
+ // PERF-13-01: cap description at SUMMARY_MAX_CHARS via shared summarize()
164
+ // helper from src/core/sync.js — keeps cross-surface behavior identical
165
+ // (CLI listing == MCP listing). Full text remains in each item's source file.
166
+ return { kind: x.kind, name: x.name, description: summarize(x.description) };
167
+ }
168
+
169
+ // PERF-15-01: terse variant — paridade com mcp-server slimTerse. CLI flag --terse
170
+ // controla seleção. Mantém o mesmo shape {kind, name} para programmatic consumers
171
+ // que parseiam --json output (consistência cross-surface).
172
+ function slimTerse(x) {
173
+ return { kind: x.kind, name: x.name };
174
+ }
175
+
176
+ // --- kit ---
177
+ const kit = program.command('kit').description('Browse the canonical kit.');
178
+ kit.command('list-agents')
179
+ .option('--terse', 'Omit description; return only {kind, name} (PERF-15-01)')
180
+ .action(async (opts) => {
181
+ const k = await withSpinner('Loading kit...', () => listKit());
182
+ const variant = opts.terse ? slimTerse : slim;
183
+ out(k.agents.map(variant), v => render.renderKitList(v, 'agent'));
184
+ });
185
+ kit.command('list-commands')
186
+ .option('--terse', 'Omit description; return only {kind, name} (PERF-15-01)')
187
+ .action(async (opts) => {
188
+ const k = await withSpinner('Loading kit...', () => listKit());
189
+ const variant = opts.terse ? slimTerse : slim;
190
+ out(k.commands.map(variant), v => render.renderKitList(v, 'command'));
191
+ });
192
+ kit.command('list-skills')
193
+ .option('--terse', 'Omit description; return only {kind, name} (PERF-15-01)')
194
+ .action(async (opts) => {
195
+ const k = await withSpinner('Loading kit...', () => listKit());
196
+ const variant = opts.terse ? slimTerse : slim;
197
+ out([...k.skills, ...k.skillsExtras].map(variant), v => render.renderKitList(v, 'skill'));
198
+ });
199
+ kit.command('get <kind> <name>').action(async (kind, name) => {
200
+ const k = await listKit();
201
+ const item = findItem(k, kind, name);
202
+ if (!item) return fail(`Not found: ${kind}/${name}`);
203
+ // Always raw for `kit get` — it's intended to be cat-like
204
+ process.stdout.write(item.content ?? item.skillContent);
205
+ });
206
+ kit.command('search <query>').action(async (q) => out(searchKit(await listKit(), q), render.renderKitSearch));
207
+
208
+ // --- sync ---
209
+ const sync = program.command('sync').description('Project the kit into an IDE.');
210
+ sync.command('targets').action(async () => {
211
+ const targets = await withSpinner('Loading capability matrix...', async () => listTargets());
212
+ out(targets, render.renderSyncTargets);
213
+ });
214
+ sync.command('status <target>')
215
+ .option('--project-root <path>')
216
+ .action(async (target, opts) => out(await statusOf(target, { projectRoot: opts.projectRoot }), render.renderSyncStatus));
217
+ sync.command('install [target]')
218
+ .option('--project-root <path>')
219
+ .option('--mode <mode>', 'reference | copy', 'reference')
220
+ .option('--dry-run')
221
+ .option('--quiet', 'Suppress per-file progress; keep final summary')
222
+ .action(async (target, opts) => {
223
+ if (!target) target = await pickTarget(listTargets(), 'Which IDE do you want to sync the kit into?');
224
+ // Phase 160 (v1.28): count written vs skipped so the post-sync summary
225
+ // can render "X new/updated, Y unchanged".
226
+ const tally = { written: 0, skipped: 0 };
227
+ const wrapOnProgress = (orig) => (ev) => {
228
+ if (ev?.skipped) tally.skipped += 1;
229
+ else tally.written += 1;
230
+ if (orig) orig(ev);
231
+ };
232
+ const runSync = (onProgress) => syncTo(target, {
233
+ projectRoot: opts.projectRoot,
234
+ mode: opts.mode,
235
+ dryRun: opts.dryRun,
236
+ onProgress: wrapOnProgress(opts.quiet ? null : onProgress),
237
+ });
238
+ const result = opts.quiet
239
+ ? await runSync()
240
+ : await withProgress(`Syncing kit → ${target}`, 300, runSync,
241
+ { tool: 'sync.install', projectRoot: opts.projectRoot });
242
+ result._tally = tally; // surfaced by renderSyncInstall (v1.28)
243
+ out(result, render.renderSyncInstall);
244
+ });
245
+ sync.command('remove <target>')
246
+ .option('--project-root <path>')
247
+ .action(async (target, opts) => out(await removeFrom(target, { projectRoot: opts.projectRoot }), render.renderSyncRemove));
248
+ sync.command('watch [targets...]')
249
+ .description('Watch kit/ and re-sync to one or more IDEs on every change. Use --all to pick up every IDE that already has files in the project.')
250
+ .option('--project-root <path>')
251
+ .option('--mode <mode>', 'reference | copy', 'reference')
252
+ .option('--debounce <ms>', 'Debounce window in ms', '300')
253
+ .option('--all', 'Auto-detect every IDE target that currently has files in --project-root')
254
+ .action(async (targets, opts) => {
255
+ let list = targets ?? [];
256
+ if (opts.all) {
257
+ const detected = await detectExistingTargets({ projectRoot: opts.projectRoot });
258
+ list = [...new Set([...list, ...detected])];
259
+ }
260
+ if (list.length === 0) return fail('No targets given. Pass <targets...> or --all.');
261
+ const log = (s) => process.stderr.write(`[watch] ${s}\n`);
262
+ const w = await watchKit(list, {
263
+ projectRoot: opts.projectRoot,
264
+ mode: opts.mode,
265
+ debounceMs: parseInt(opts.debounce, 10),
266
+ onLog: log,
267
+ });
268
+ log(`watching kit/ → ${list.join(', ')} (Ctrl+C to stop)`);
269
+ const shutdown = async () => { log('shutting down...'); await w.stop(); process.exit(0); };
270
+ process.on('SIGINT', shutdown);
271
+ process.on('SIGTERM', shutdown);
272
+ });
273
+
274
+ // --- reverse-sync ---
275
+ const reverse = program.command('reverse-sync').description('Detect and apply edits made directly in an IDE back to the canonical kit/.');
276
+ reverse.command('detect <target>')
277
+ .option('--project-root <path>')
278
+ .action(async (target, opts) => out(await detectReverse(target, { projectRoot: opts.projectRoot }), render.renderReverseDetect));
279
+ reverse.command('apply <target>')
280
+ .option('--project-root <path>')
281
+ .option('--strategy <s>', 'skip | overwrite | merge | rename', 'skip')
282
+ .option('--only <items...>', 'Limit to these kind/name pairs (e.g. agent/planner skill/paperclip framework/workflows/foo.md)')
283
+ .option('--dry-run')
284
+ .action(async (target, opts) => {
285
+ const result = await withProgress(
286
+ `Applying reverse-sync (${opts.strategy})`,
287
+ 50,
288
+ (onProgress) => applyReverse(target, { projectRoot: opts.projectRoot, strategy: opts.strategy, only: opts.only, dryRun: opts.dryRun, onProgress }),
289
+ { tool: 'reverse-sync.apply', projectRoot: opts.projectRoot },
290
+ );
291
+ out(result, render.renderReverseApply);
292
+ });
293
+
294
+ // --- gates ---
295
+ const gates = program.command('gates').description('Reusable workflow gates.');
296
+ gates.command('list').action(async () => out(await listGates(), render.renderGatesList));
297
+ gates.command('get <id>').action(async (id) => process.stdout.write((await getGate(id)).content));
298
+ gates.command('for-stage <stage>').action(async (stage) => out(await gatesForStage(stage), render.renderGatesList));
299
+ gates.command('run <id>')
300
+ .description('Execute a gate (with confirmation in interactive mode). Returns a structured verdict.')
301
+ .option('--project-root <path>')
302
+ .option('--yes', 'Skip confirmation (CI/non-interactive)')
303
+ .option('--no-interactive', 'Never prompt; manual gates return verdict=manual')
304
+ .action(async (id, opts) => out(await runGate(id, {
305
+ projectRoot: opts.projectRoot,
306
+ yes: opts.yes,
307
+ interactive: opts.interactive !== false,
308
+ }), render.renderGateRun));
309
+
310
+ // --- forensics ---
311
+ const forensics = program.command('forensics').description('Failure dataset & replays.');
312
+ forensics.command('collect')
313
+ .option('--project-root <path>')
314
+ .action(async (opts) => out(await collectFailures({ projectRoot: opts.projectRoot }), render.renderForensicsCollect));
315
+ forensics.command('summarize')
316
+ .option('--project-root <path>')
317
+ .action(async (opts) => {
318
+ const f = await collectFailures({ projectRoot: opts.projectRoot });
319
+ out(await summarizeByAgent(f), render.renderForensicsSummarize);
320
+ });
321
+ forensics.command('write-learnings')
322
+ .option('--project-root <path>')
323
+ .action(async (opts) => {
324
+ const f = await collectFailures({ projectRoot: opts.projectRoot });
325
+ out(await writeLearnings(f, { projectRoot: opts.projectRoot }), render.renderFallback);
326
+ });
327
+ forensics.command('list-replays')
328
+ .option('--project-root <path>')
329
+ .action(async (opts) => out(await listReplays({ projectRoot: opts.projectRoot }), render.renderListReplays));
330
+ forensics.command('reflect')
331
+ .description('LLM-pass: read learnings + current agent, propose minimal prompt edits, optionally apply.')
332
+ .requiredOption('--agent <name>', 'Agent name (matches kit/agents/<name>.md)')
333
+ .option('--project-root <path>')
334
+ .option('--dry-run', 'Save the assembled prompt without calling the LLM')
335
+ .option('--apply', 'Skip confirmation; apply the proposal directly')
336
+ .option('--no-interactive', 'Save proposal but never prompt to apply')
337
+ .action(async (opts) => out(await reflect({
338
+ agent: opts.agent,
339
+ projectRoot: opts.projectRoot,
340
+ dryRun: opts.dryRun,
341
+ apply: opts.apply,
342
+ interactive: opts.interactive !== false,
343
+ }), render.renderFallback));
344
+ forensics.command('load-replay <id>')
345
+ .option('--project-root <path>')
346
+ .action(async (id, opts) => out(await loadReplay(id, { projectRoot: opts.projectRoot }), render.renderFallback));
347
+
348
+ // --- install (the MCP server itself into an IDE) ---
349
+ const install = program.command('install').description('Register kit-mcp into an IDE\'s MCP config.');
350
+ install.command('targets').action(async () => out(listInstallTargets(), render.renderInstallTargets));
351
+ install.command('dry-run <target>')
352
+ .option('--scope <scope>', 'user | project', 'user')
353
+ .option('--name <name>', 'Server name in IDE config', 'kit')
354
+ .option('--via <via>', 'local | npx | global (how the IDE will invoke the server)', 'local')
355
+ .option('--pkg <name>', 'npm package name (only with --via npx)', '@luanpdd/kit-mcp')
356
+ .option('--project-root <path>')
357
+ .action(async (target, opts) => out(await installMcp(target, { ...opts, dryRun: true }), render.renderInstallResult));
358
+ install.command('write [target]')
359
+ .option('--scope <scope>', 'user | project', 'user')
360
+ .option('--name <name>', 'Server name in IDE config', 'kit')
361
+ .option('--via <via>', 'local | npx | global', 'local')
362
+ .option('--pkg <name>', 'npm package name (only with --via npx)', '@luanpdd/kit-mcp')
363
+ .option('--force')
364
+ .option('--project-root <path>')
365
+ .option('--yes', 'Skip confirmation prompt (CI mode)')
366
+ .action(async (target, opts) => {
367
+ const globalOpts = program.opts();
368
+ if (!target) target = await pickTarget(listInstallTargets(), 'Where do you want to register kit-mcp?');
369
+
370
+ // Preview first (dry-run)
371
+ const preview = await installMcp(target, { ...opts, dryRun: true });
372
+ if (!preview.ok) {
373
+ out(preview, render.renderInstallResult);
374
+ process.exit(1);
375
+ }
376
+
377
+ // Show the preview unless --json
378
+ if (!globalOpts.json) {
379
+ process.stdout.write(`\n${c.bold('Preview:')} ${c.dim(preview.configPath)}\n\n`);
380
+ if (preview.preview) {
381
+ process.stdout.write(c.dim(JSON.stringify(preview.preview, null, 2)) + '\n');
382
+ } else if (preview.snippet) {
383
+ process.stdout.write(c.dim(preview.snippet) + '\n');
384
+ }
385
+ }
386
+
387
+ // Confirm unless --yes or --json (programmatic consumers must pass --yes)
388
+ if (!opts.yes && !globalOpts.json) {
389
+ let proceed;
390
+ try {
391
+ proceed = await confirm({ message: 'Apply these changes?', default: false });
392
+ } catch (e) {
393
+ return fail(`${e.message} (use --yes to skip)`);
394
+ }
395
+ if (!proceed) {
396
+ process.stdout.write(`${c.yellow(icons.warn)} Aborted by user.\n`);
397
+ process.exit(0);
398
+ }
399
+ }
400
+
401
+ out(await installMcp(target, opts), render.renderInstallResult);
402
+ });
403
+
404
+ // pickTarget — interactive selector for IDE targets, falls back to error in non-TTY/--json
405
+ async function pickTarget(targets, message) {
406
+ const globalOpts = program.opts();
407
+ if (globalOpts.json) {
408
+ return fail('--target is required when using --json mode');
409
+ }
410
+ try {
411
+ return await select({
412
+ message,
413
+ choices: targets.map(t => ({
414
+ name: `${t.label.padEnd(22)} ${c.dim(`(${t.id})`)}`,
415
+ value: t.id,
416
+ })),
417
+ });
418
+ } catch (e) {
419
+ return fail(`${e.message} (or pass <target> as argument)`);
420
+ }
421
+ }
422
+
423
+ // --- ui (sidecar process viewer) ---
424
+ const ui = program.command('ui').description('Live process viewer in a localhost browser tab.');
425
+
426
+ ui.command('start')
427
+ .description('Start the sidecar HTTP server in foreground (Ctrl+C to stop). Prints URL on stderr.')
428
+ .option('--project-root <path>', 'Project root for lockfile keying (default: cwd)')
429
+ .option('--port <n>', 'Bind to a specific port (default: auto-pick 7100-7199)')
430
+ .option('--idle-ms <ms>', 'Idle shutdown timeout (default 0 = never; e.g. 1800000 for 30min)')
431
+ .option('--no-open', 'Skip auto-opening the browser')
432
+ .action(async (opts) => {
433
+ const projectRoot = opts.projectRoot || process.cwd();
434
+ const port = opts.port ? Number(opts.port) : undefined;
435
+ const idleMs = opts.idleMs !== undefined ? Number(opts.idleMs) : undefined;
436
+ // PERF-16-04: lazy-load the sidecar HTTP server module only when starting it.
437
+ const { createServer } = await import('../ui/server.js');
438
+ const srv = createServer({ projectRoot, idleMs });
439
+ try {
440
+ const { port: actualPort } = await srv.start({ port });
441
+ const url = `http://127.0.0.1:${actualPort}/`;
442
+ process.stderr.write(`${c.cyan(icons.info)} kit-mcp ui listening on ${url}\n`);
443
+ process.stderr.write(`${c.dim(` project: ${projectRoot}`)}\n`);
444
+ // U4: non-blocking upgrade check. Warns if local install is behind npm latest.
445
+ // Cached for 24h via ~/.kit-mcp/version-check.json so we don't hit npm on every start.
446
+ checkUpgrade().then((info) => {
447
+ if (info?.behind) {
448
+ process.stderr.write(`${c.yellow(icons.warn)} kit-mcp v${info.local} → v${info.latest} disponível\n`);
449
+ process.stderr.write(`${c.dim(' atualize com: npm i -g @luanpdd/kit-mcp@latest')}\n`);
450
+ }
451
+ }).catch(() => { /* offline / silent */ });
452
+ if (opts.open !== false) {
453
+ // PERF-16-04: lazy-load browser-opener (it lazy-loads `open` package itself).
454
+ const { openBrowser } = await import('../ui/browser.js');
455
+ await openBrowser(url);
456
+ }
457
+ // The server's own SIGINT handler will perform shutdown + cleanup.
458
+ // We just stay alive — server is foreground.
459
+ } catch (err) {
460
+ if (err.code === 'ELIVE') {
461
+ process.stderr.write(`${c.yellow(icons.warn)} sidecar already running for this project\n`);
462
+ process.stderr.write(` pid: ${err.lock?.pid}, port: ${err.lock?.port}\n`);
463
+ process.stderr.write(` use 'kit ui status' or 'kit ui open' to inspect\n`);
464
+ process.exit(2);
465
+ }
466
+ fail(err.message);
467
+ }
468
+ });
469
+
470
+ ui.command('stop')
471
+ .description('Stop the sidecar running for this project (POST /shutdown).')
472
+ .option('--project-root <path>')
473
+ .action(async (opts) => {
474
+ const projectRoot = opts.projectRoot || process.cwd();
475
+ const lock = readLock(projectRoot);
476
+ if (!lock) return out({ ok: false, reason: 'no_sidecar' }, () => `${icons.warn} no sidecar running for this project\n`);
477
+ try {
478
+ await postShutdown(lock.port, lock.token);
479
+ out({ ok: true, port: lock.port }, () => `${icons.check} sidecar at port ${lock.port} stopped\n`);
480
+ } catch (err) {
481
+ fail(`could not stop sidecar at port ${lock.port}: ${err.message}`);
482
+ }
483
+ });
484
+
485
+ ui.command('status')
486
+ .description('Show whether a sidecar is running for this project.')
487
+ .option('--project-root <path>')
488
+ .action(async (opts) => {
489
+ const projectRoot = opts.projectRoot || process.cwd();
490
+ const lock = readLock(projectRoot);
491
+ if (!lock) {
492
+ out({ running: false, reason: 'no_lockfile' }, () => `${icons.warn} no sidecar running\n`);
493
+ process.exit(1);
494
+ }
495
+ try {
496
+ const health = await getHealthz(lock.port);
497
+ out({ running: true, ...health, lockfile: lockPathFor(projectRoot) }, render.renderUiStatus ?? renderUiStatusFallback);
498
+ } catch (err) {
499
+ out({ running: false, reason: 'unreachable', lockfile: lockPathFor(projectRoot), error: err.message },
500
+ () => `${icons.cross} lockfile present but sidecar unreachable: ${err.message}\n`);
501
+ process.exit(1);
502
+ }
503
+ });
504
+
505
+ ui.command('open')
506
+ .description('Open the running sidecar in a browser. Fails if no sidecar is up.')
507
+ .option('--project-root <path>')
508
+ .action(async (opts) => {
509
+ const projectRoot = opts.projectRoot || process.cwd();
510
+ const lock = readLock(projectRoot);
511
+ if (!lock) return fail('no sidecar running — start one with `kit ui start`');
512
+ const url = `http://127.0.0.1:${lock.port}/`;
513
+ // PERF-16-04: lazy-load browser-opener.
514
+ const { openBrowser } = await import('../ui/browser.js');
515
+ const r = await openBrowser(url, { force: true });
516
+ if (!r.opened) {
517
+ process.stderr.write(`${c.yellow(icons.warn)} could not open browser (${r.reason}); copy the URL above\n`);
518
+ process.exit(1);
519
+ }
520
+ });
521
+
522
+ // --- doctor (DX diagnostic) ---
523
+ program.command('doctor')
524
+ .description('Diagnose kit-mcp setup: version, sidecar, hook, settings.json, lockfile, .planning/.')
525
+ .option('--project-root <path>', 'Project to diagnose (default: cwd)')
526
+ .action(async (opts) => {
527
+ const projectRoot = opts.projectRoot || process.cwd();
528
+ const checks = await runDoctorChecks(projectRoot);
529
+ const failed = checks.filter(c => c.status === 'fail').length;
530
+ const warned = checks.filter(c => c.status === 'warn').length;
531
+
532
+ if (program.opts().json) {
533
+ out({ checks, failed, warned }, () => '');
534
+ process.exit(failed > 0 ? 1 : 0);
535
+ }
536
+
537
+ process.stdout.write(`\n${c.bold('kit-mcp doctor')} — ${projectRoot}\n\n`);
538
+ for (const check of checks) {
539
+ const sym = check.status === 'pass' ? c.green(icons.check)
540
+ : check.status === 'warn' ? c.yellow(icons.warn)
541
+ : c.red(icons.cross);
542
+ process.stdout.write(`${sym} ${c.bold(check.label)}\n`);
543
+ if (check.detail) process.stdout.write(` ${c.dim(check.detail)}\n`);
544
+ if (check.fix) process.stdout.write(` ${c.cyan('fix:')} ${check.fix}\n`);
545
+ }
546
+ process.stdout.write('\n');
547
+ if (failed > 0) {
548
+ process.stdout.write(`${c.red(icons.cross)} ${failed} check(s) failed\n`);
549
+ process.exit(1);
550
+ } else if (warned > 0) {
551
+ process.stdout.write(`${c.yellow(icons.warn)} ${warned} warning(s) — kit-mcp is functional\n`);
552
+ } else {
553
+ process.stdout.write(`${c.green(icons.check)} all checks passed\n`);
554
+ }
555
+ });
556
+
557
+ async function runDoctorChecks(projectRoot) {
558
+ const checks = [];
559
+
560
+ // 1. Version + upgrade availability
561
+ const upgrade = await checkUpgrade();
562
+ if (!upgrade) {
563
+ checks.push({ label: 'version', status: 'fail',
564
+ detail: 'could not read local package.json',
565
+ fix: 'reinstall via `npm i -g @luanpdd/kit-mcp@latest`' });
566
+ } else if (upgrade.latest === null) {
567
+ checks.push({ label: 'version', status: 'warn',
568
+ detail: `local v${upgrade.local} (offline — could not check npm)` });
569
+ } else if (upgrade.behind) {
570
+ checks.push({ label: 'version', status: 'warn',
571
+ detail: `local v${upgrade.local}, latest v${upgrade.latest}`,
572
+ fix: 'npm i -g @luanpdd/kit-mcp@latest' });
573
+ } else {
574
+ checks.push({ label: 'version', status: 'pass',
575
+ detail: `v${upgrade.local} (latest)` });
576
+ }
577
+
578
+ // 2. Sidecar lockfile + healthz
579
+ const lock = readLock(projectRoot);
580
+ if (!lock) {
581
+ checks.push({ label: 'sidecar', status: 'warn',
582
+ detail: 'not running for this project',
583
+ fix: 'kit ui start (or omit if you don\'t need the live viewer)' });
584
+ } else {
585
+ try {
586
+ await getHealthz(lock.port);
587
+ checks.push({ label: 'sidecar', status: 'pass',
588
+ detail: `running on port ${lock.port} (pid ${lock.pid})` });
589
+ } catch (err) {
590
+ checks.push({ label: 'sidecar', status: 'fail',
591
+ detail: `lockfile says port ${lock.port} but unreachable: ${err.message}`,
592
+ fix: 'kit ui stop && kit ui start' });
593
+ }
594
+ }
595
+
596
+ // 3. ~/.claude/settings.json — exists + valid JSON + hooks present?
597
+ const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
598
+ let settings = null;
599
+ try {
600
+ settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
601
+ checks.push({ label: 'settings.json', status: 'pass',
602
+ detail: settingsPath });
603
+ } catch (err) {
604
+ if (err.code === 'ENOENT') {
605
+ checks.push({ label: 'settings.json', status: 'warn',
606
+ detail: 'not found (expected for fresh Claude Code)',
607
+ fix: 'will be created automatically by Claude Code' });
608
+ } else {
609
+ checks.push({ label: 'settings.json', status: 'fail',
610
+ detail: `invalid JSON at ${settingsPath}: ${err.message}`,
611
+ fix: 'edit the file or restore from .claude/settings.json.bak' });
612
+ }
613
+ }
614
+
615
+ // 4. Hook installed?
616
+ if (settings) {
617
+ const hooks = settings.hooks?.PostToolUse;
618
+ const hasHook = Array.isArray(hooks) && hooks.some((h) =>
619
+ Array.isArray(h.hooks) && h.hooks.some((cmd) =>
620
+ typeof cmd.command === 'string' && cmd.command.includes('sidecar-tool-publisher')));
621
+ if (hasHook) {
622
+ checks.push({ label: 'observability hook', status: 'pass',
623
+ detail: 'sidecar-tool-publisher registered as PostToolUse' });
624
+ } else {
625
+ checks.push({ label: 'observability hook', status: 'warn',
626
+ detail: 'sidecar-tool-publisher not registered',
627
+ fix: 'see kit/hooks/sidecar-tool-publisher.js for installation snippet' });
628
+ }
629
+ }
630
+
631
+ // 5. Bundled kit dirs exist
632
+ const here = path.dirname(fileURLToPath(import.meta.url));
633
+ const kitRoot = path.resolve(here, '..', '..', 'kit');
634
+ const expected = ['agents', 'commands', 'skills'];
635
+ const missing = expected.filter((d) => {
636
+ try { return !fs.statSync(path.join(kitRoot, d)).isDirectory(); }
637
+ catch { return true; }
638
+ });
639
+ if (missing.length === 0) {
640
+ checks.push({ label: 'bundled kit', status: 'pass',
641
+ detail: `agents/, commands/, skills/ found in ${kitRoot}` });
642
+ } else {
643
+ checks.push({ label: 'bundled kit', status: 'fail',
644
+ detail: `missing: ${missing.join(', ')} in ${kitRoot}`,
645
+ fix: 'reinstall via `npm i -g @luanpdd/kit-mcp@latest`' });
646
+ }
647
+
648
+ // 6. .planning/ in projectRoot — only warn if absent (not all projects use the framework)
649
+ const planningDir = path.join(projectRoot, '.planning');
650
+ if (fs.existsSync(planningDir)) {
651
+ const stateOk = fs.existsSync(path.join(planningDir, 'STATE.md'));
652
+ const roadmapOk = fs.existsSync(path.join(planningDir, 'ROADMAP.md'));
653
+ if (stateOk && roadmapOk) {
654
+ checks.push({ label: '.planning/', status: 'pass',
655
+ detail: 'STATE.md + ROADMAP.md present' });
656
+ } else {
657
+ checks.push({ label: '.planning/', status: 'warn',
658
+ detail: `present but missing ${[!stateOk && 'STATE.md', !roadmapOk && 'ROADMAP.md'].filter(Boolean).join(', ')}`,
659
+ fix: 'run `kit saude` to repair, or `/novo-marco` if mid-cycle' });
660
+ }
661
+ } else {
662
+ checks.push({ label: '.planning/', status: 'warn',
663
+ detail: 'no framework state in this project',
664
+ fix: 'run `/novo-projeto` to bootstrap, or skip if not using the framework' });
665
+ }
666
+
667
+ // 7. Stale lockfile cleanup hint
668
+ try {
669
+ const tmpdir = os.tmpdir();
670
+ const orphans = fs.readdirSync(tmpdir).filter(n => /^kit-mcp-ui-[0-9a-f]{16}\.lock$/.test(n));
671
+ const stale = [];
672
+ for (const name of orphans) {
673
+ try {
674
+ const lock = JSON.parse(fs.readFileSync(path.join(tmpdir, name), 'utf8'));
675
+ try { process.kill(lock.pid, 0); } catch (err) {
676
+ if (err.code === 'ESRCH') stale.push(name);
677
+ }
678
+ } catch { /* skip unreadable */ }
679
+ }
680
+ if (stale.length > 0) {
681
+ checks.push({ label: 'orphan lockfiles', status: 'warn',
682
+ detail: `${stale.length} stale lockfile(s) in ${tmpdir}`,
683
+ fix: stale.map(n => `rm "${path.join(tmpdir, n)}"`).join(' && ') });
684
+ }
685
+ } catch { /* tmpdir scan is best-effort */ }
686
+
687
+ // 8. (v1.28) log dir writable — required for kit logs
688
+ try {
689
+ const dir = logDir();
690
+ fs.mkdirSync(dir, { recursive: true });
691
+ const probe = path.join(dir, `.doctor-probe-${process.pid}`);
692
+ fs.writeFileSync(probe, '', 'utf8');
693
+ fs.unlinkSync(probe);
694
+ const files = listLogs();
695
+ checks.push({ label: 'log dir', status: 'pass',
696
+ detail: `${dir} writable (${files.length} log file${files.length === 1 ? '' : 's'})` });
697
+ } catch (err) {
698
+ checks.push({ label: 'log dir', status: 'fail',
699
+ detail: `${logDir()} not writable: ${err.message}`,
700
+ fix: 'check permissions or set KIT_MCP_LOG_DIR to a writable path' });
701
+ }
702
+
703
+ // 9. (v1.28) sidecar auto-spawn config — informational
704
+ const noUi = process.env.KIT_MCP_NO_UI === '1' || process.env.KIT_MCP_NO_UI === 'true';
705
+ checks.push({ label: 'sidecar auto-spawn', status: noUi ? 'warn' : 'pass',
706
+ detail: noUi
707
+ ? 'KIT_MCP_NO_UI=1 — sidecar will NOT auto-start on MCP boot'
708
+ : 'enabled (default) — sidecar starts when MCP server boots',
709
+ fix: noUi ? 'unset KIT_MCP_NO_UI if you want live tool-call visibility' : undefined });
710
+
711
+ // 10. (v1.29) auto-install drift check — is .claude/.kit-mcp-version aligned
712
+ // with the running kit-mcp package version?
713
+ try {
714
+ const versionMarker = path.join(projectRoot, '.claude', '.kit-mcp-version');
715
+ const restartMarker = path.join(projectRoot, '.claude', '.kit-mcp-restart-required');
716
+ let installedVersion = null;
717
+ try { installedVersion = fs.readFileSync(versionMarker, 'utf8').trim(); } catch { /* not installed */ }
718
+ const currentVersion = readPkgVersion();
719
+
720
+ if (!installedVersion) {
721
+ checks.push({ label: 'auto-install', status: 'warn',
722
+ detail: '.claude/.kit-mcp-version not found — kit not auto-installed in this project',
723
+ fix: 'call kit:auto-install MCP tool, or run: kit init' });
724
+ } else if (installedVersion !== currentVersion) {
725
+ checks.push({ label: 'auto-install', status: 'warn',
726
+ detail: `kit installed v${installedVersion}, MCP server is v${currentVersion}`,
727
+ fix: 'call kit:auto-install (idempotent) or rerun: kit sync claude-code' });
728
+ } else {
729
+ checks.push({ label: 'auto-install', status: 'pass',
730
+ detail: `v${installedVersion} (in sync)` });
731
+ }
732
+
733
+ if (fs.existsSync(restartMarker)) {
734
+ let payload = {};
735
+ try { payload = JSON.parse(fs.readFileSync(restartMarker, 'utf8')); } catch { /* malformed */ }
736
+ checks.push({ label: 'restart pending', status: 'warn',
737
+ detail: payload.reason
738
+ ? `${payload.reason} (written ${payload.writtenAt || 'unknown'})`
739
+ : 'restart marker present — IDE not yet reloaded since last auto-install',
740
+ fix: 'restart your IDE session, then call kit:ack-restart MCP tool (or just close/reopen)' });
741
+ }
742
+ } catch { /* .claude/ check is best-effort */ }
743
+
744
+ return checks;
745
+ }
746
+
747
+ // Helpers for kit ui (live in cli/ — stdout/console allowed here)
748
+ // SEC-14-02: /shutdown now requires Authorization Bearer <token>. Caller must
749
+ // pass the per-process token read from the lockfile (lock.token from readLock).
750
+ async function postShutdown(port, token) {
751
+ return new Promise((resolve, reject) => {
752
+ const headers = {
753
+ host: `127.0.0.1:${port}`,
754
+ origin: `http://127.0.0.1:${port}`,
755
+ 'content-length': 0,
756
+ connection: 'close',
757
+ };
758
+ if (token) headers.authorization = `Bearer ${token}`;
759
+ const req = http.request({
760
+ method: 'POST',
761
+ host: '127.0.0.1',
762
+ port,
763
+ path: '/shutdown',
764
+ agent: false,
765
+ headers,
766
+ }, (res) => {
767
+ res.resume();
768
+ res.on('end', () => res.statusCode < 400 ? resolve() : reject(new Error(`http_${res.statusCode}`)));
769
+ });
770
+ req.on('error', reject);
771
+ req.setTimeout(2000, () => { try { req.destroy(); } catch {} ; reject(new Error('timeout')); });
772
+ req.end();
773
+ });
774
+ }
775
+
776
+ async function getHealthz(port) {
777
+ return new Promise((resolve, reject) => {
778
+ const req = http.request({
779
+ method: 'GET',
780
+ host: '127.0.0.1',
781
+ port,
782
+ path: '/healthz',
783
+ agent: false,
784
+ headers: { host: `127.0.0.1:${port}`, connection: 'close' },
785
+ }, (res) => {
786
+ const chunks = [];
787
+ res.on('data', (c) => chunks.push(c));
788
+ res.on('end', () => {
789
+ if (res.statusCode >= 400) return reject(new Error(`http_${res.statusCode}`));
790
+ try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); }
791
+ catch (e) { reject(e); }
792
+ });
793
+ });
794
+ req.on('error', reject);
795
+ req.setTimeout(2000, () => { try { req.destroy(); } catch {} ; reject(new Error('timeout')); });
796
+ req.end();
797
+ });
798
+ }
799
+
800
+ function renderUiStatusFallback(v) {
801
+ if (!v.running) return `${icons.warn} not running\n`;
802
+ return [
803
+ `${icons.check} sidecar running`,
804
+ ` port: ${v.port}`,
805
+ ` pid (sdcr): ${v.lockfile ? readLock(process.cwd())?.pid : '?'}`,
806
+ ` uptime: ${Math.round((v.uptime || 0) / 1000)}s`,
807
+ ` events: ${v.eventsTotal}`,
808
+ ` subscribers: ${v.subscribers}`,
809
+ ` url: http://127.0.0.1:${v.port}/`,
810
+ '',
811
+ ].join('\n');
812
+ }
813
+
814
+ // --- status (Phase 162, v1.28: live metrics snapshot + log file path) ---
815
+ program.command('status')
816
+ .description('Show MCP server metrics (p50/p95/p99/error rate) + log file path.')
817
+ .option('--project-root <path>', 'Default: cwd')
818
+ .action(async (opts) => {
819
+ const { snapshot, loadSnapshots } = await import('../core/metrics.js');
820
+ const projectRoot = opts.projectRoot || process.cwd();
821
+ const live = snapshot(); // current-process metrics (only useful when called from inside the MCP process)
822
+ const persisted = await loadSnapshots(projectRoot, 60 * 60 * 1000).catch(() => []); // last hour
823
+
824
+ if (program.opts().json) {
825
+ out({ live, persistedCount: persisted.length, latest: persisted[persisted.length - 1] || null, logPath: currentLogPath() }, () => '');
826
+ return;
827
+ }
828
+
829
+ process.stdout.write(`\n${c.bold('kit-mcp status')}\n\n`);
830
+
831
+ // Sidecar
832
+ const lock = readLock(projectRoot);
833
+ process.stdout.write(`${c.bold('sidecar:')} ${lock ? c.green(`running on port ${lock.port}`) : c.dim('not running')}\n`);
834
+
835
+ // Log file
836
+ const files = listLogs();
837
+ process.stdout.write(`${c.bold('log:')} ${currentLogPath()}\n`);
838
+ process.stdout.write(` ${c.dim(`${files.length} file(s) in ${logDir()}`)}\n`);
839
+
840
+ // Latency from latest persisted snapshot (last hour window)
841
+ const latest = persisted[persisted.length - 1];
842
+ const lat = latest?.latency || live.latency || {};
843
+ const tools = Object.keys(lat);
844
+ process.stdout.write(`\n${c.bold('latency (last hour, or current process):')}\n`);
845
+ if (tools.length === 0) {
846
+ process.stdout.write(` ${c.dim('no samples yet')}\n`);
847
+ } else {
848
+ const w = Math.max(...tools.map((t) => t.length));
849
+ for (const t of tools) {
850
+ const s = lat[t];
851
+ process.stdout.write(` ${t.padEnd(w)} p50 ${c.cyan(s.p50 + 'ms').padEnd(20)} p95 ${c.cyan(s.p95 + 'ms').padEnd(20)} p99 ${c.cyan(s.p99 + 'ms').padEnd(20)} n=${s.count}\n`);
852
+ }
853
+ }
854
+
855
+ // Error rate from counters
856
+ const counters = latest?.counters || live.counters || {};
857
+ let okTotal = 0, errTotal = 0;
858
+ for (const [k, v] of Object.entries(counters)) {
859
+ if (k.endsWith(':ok')) okTotal += v;
860
+ if (k.endsWith(':error')) errTotal += v;
861
+ }
862
+ const total = okTotal + errTotal;
863
+ const rate = total === 0 ? 0 : (errTotal / total) * 100;
864
+ process.stdout.write(`\n${c.bold('errors:')} ${errTotal}/${total} (${rate.toFixed(2)}%)\n\n`);
865
+ });
866
+
867
+ // --- init (Phase 161, v1.28: guided onboarding — install + sync + doctor) ---
868
+ program.command('init')
869
+ .description('Onboard: register kit-mcp into an IDE, sync the kit, run doctor.')
870
+ .option('--ide <id>', 'Skip the IDE picker (e.g. claude-code, cursor, codex)')
871
+ .option('--project-root <path>', 'Default: cwd')
872
+ .option('--non-interactive', 'Fail fast if --ide is missing instead of prompting')
873
+ .option('--mode <mode>', 'sync mode: reference | copy', 'reference')
874
+ .action(async (opts) => {
875
+ const projectRoot = opts.projectRoot || process.cwd();
876
+ const targets = listInstallTargets();
877
+ const targetIds = targets.map(t => t.id);
878
+
879
+ let ide = opts.ide;
880
+ if (!ide) {
881
+ if (opts.nonInteractive) {
882
+ process.stderr.write(`${c.red(icons.cross)} --non-interactive requires --ide=<${targetIds.join('|')}>\n`);
883
+ process.exit(2);
884
+ }
885
+ ide = await pickTarget(targets, 'Which IDE should kit-mcp register with?');
886
+ }
887
+ if (!targetIds.includes(ide)) {
888
+ process.stderr.write(`${c.red(icons.cross)} unknown IDE "${ide}" — valid: ${targetIds.join(', ')}\n`);
889
+ process.exit(2);
890
+ }
891
+
892
+ process.stdout.write(`\n${c.bold('kit init')} → ${ide}\n\n`);
893
+
894
+ // 1. Register MCP server in IDE config
895
+ process.stdout.write(`${c.cyan('1/3')} registering MCP server...\n`);
896
+ try {
897
+ const r = await installMcp(ide, { projectRoot });
898
+ process.stdout.write(` ${c.green(icons.check)} ${r.path || 'config updated'}\n`);
899
+ } catch (e) {
900
+ process.stdout.write(` ${c.red(icons.cross)} ${e.message}\n`);
901
+ process.exit(1);
902
+ }
903
+
904
+ // 2. Sync kit content
905
+ process.stdout.write(`\n${c.cyan('2/3')} syncing kit content...\n`);
906
+ const tally = { written: 0, skipped: 0 };
907
+ try {
908
+ const r = await syncTo(ide, {
909
+ projectRoot,
910
+ mode: opts.mode,
911
+ onProgress: (ev) => { if (ev?.skipped) tally.skipped += 1; else tally.written += 1; },
912
+ });
913
+ const total = (r.written || []).length;
914
+ process.stdout.write(` ${c.green(icons.check)} ${total} files (${tally.written} new/updated, ${tally.skipped} unchanged)\n`);
915
+ } catch (e) {
916
+ process.stdout.write(` ${c.red(icons.cross)} ${e.message}\n`);
917
+ process.exit(1);
918
+ }
919
+
920
+ // 3. Doctor
921
+ process.stdout.write(`\n${c.cyan('3/3')} running diagnostic...\n`);
922
+ const checks = await runDoctorChecks(projectRoot);
923
+ const failed = checks.filter(c => c.status === 'fail').length;
924
+ const warned = checks.filter(c => c.status === 'warn').length;
925
+ const passed = checks.length - failed - warned;
926
+ process.stdout.write(` ${failed === 0 ? c.green(icons.check) : c.red(icons.cross)} `
927
+ + `${passed} pass · ${warned} warn · ${failed} fail\n`);
928
+
929
+ // 4. Final confirmation
930
+ try {
931
+ const kit = await listKit();
932
+ process.stdout.write(`\n${c.green(icons.check)} ${c.bold(ide)} now sees `
933
+ + `${c.cyan(kit.skills.length)} skills, `
934
+ + `${c.cyan(kit.agents.length)} agents, `
935
+ + `${c.cyan(kit.commands.length)} commands\n\n`);
936
+ } catch { /* non-fatal */ }
937
+
938
+ if (failed > 0) {
939
+ process.stdout.write(`${c.yellow(icons.warn)} doctor reported failures — run ${c.cyan('kit doctor')} for details\n`);
940
+ process.exit(1);
941
+ }
942
+ });
943
+
944
+ // --- replay (Phase 165, v1.28: inspect recorded agent Task() payloads) ---
945
+ const replay = program.command('replay').description('List or inspect recorded agent replays.');
946
+
947
+ replay.command('list')
948
+ .description('List replays in <project-root>/.planning/replays/')
949
+ .option('--project-root <path>', 'Default: cwd')
950
+ .action(async (opts) => {
951
+ const projectRoot = opts.projectRoot || process.cwd();
952
+ const items = await listReplays({ projectRoot });
953
+ if (program.opts().json) {
954
+ out(items, () => '');
955
+ return;
956
+ }
957
+ if (items.length === 0) {
958
+ process.stderr.write(`${c.yellow(icons.warn)} no replays at ${path.join(projectRoot, '.planning', 'replays')}\n`);
959
+ return;
960
+ }
961
+ process.stdout.write(`\n${c.bold(items.length + ' replay(s)')}\n\n`);
962
+ for (const r of items) {
963
+ process.stdout.write(` ${c.cyan(r.id)}\n`);
964
+ process.stdout.write(` agent: ${c.bold(r.agent || '?')} phase: ${r.phase || '?'} plan: ${r.plan || '?'}\n`);
965
+ process.stdout.write(` ${c.dim(r.recorded_at || '?')}\n\n`);
966
+ }
967
+ });
968
+
969
+ replay.command('show <id>')
970
+ .description('Show the full recorded payload for a replay id.')
971
+ .option('--project-root <path>', 'Default: cwd')
972
+ .action(async (id, opts) => {
973
+ const projectRoot = opts.projectRoot || process.cwd();
974
+ try {
975
+ const r = await loadReplay(id, { projectRoot });
976
+ if (program.opts().json) {
977
+ out(r, () => '');
978
+ return;
979
+ }
980
+ process.stdout.write(`\n${c.bold(r.id)}\n`);
981
+ process.stdout.write(`${c.dim('recorded:')} ${r.recorded_at}\n`);
982
+ process.stdout.write(`${c.dim('agent:')} ${c.bold(r.agent || '?')}\n`);
983
+ process.stdout.write(`${c.dim('phase:')} ${r.phase || '?'}\n`);
984
+ process.stdout.write(`${c.dim('plan:')} ${r.plan || '?'}\n`);
985
+ if (r.outcome) {
986
+ process.stdout.write(`${c.dim('outcome:')} ${JSON.stringify(r.outcome)}\n`);
987
+ }
988
+ process.stdout.write(`\n${c.bold('payload:')}\n`);
989
+ const { id: _id, recorded_at: _rec, agent: _a, phase: _p, plan: _pl, outcome: _o, ...rest } = r;
990
+ process.stdout.write(JSON.stringify(rest, null, 2) + '\n');
991
+ } catch (e) {
992
+ process.stderr.write(`${c.red(icons.cross)} replay "${id}" not found: ${e.message}\n`);
993
+ process.exit(1);
994
+ }
995
+ });
996
+
997
+ replay.command('diff <id>')
998
+ .description('Compare a replay payload against its most recent re-record (if any).')
999
+ .option('--project-root <path>', 'Default: cwd')
1000
+ .action(async (id, opts) => {
1001
+ const projectRoot = opts.projectRoot || process.cwd();
1002
+ try {
1003
+ const target = await loadReplay(id, { projectRoot });
1004
+ const all = await listReplays({ projectRoot });
1005
+ // Find newest replay with same agent that isn't the target itself.
1006
+ const candidate = all.find((r) => r.id !== id && r.agent === target.agent);
1007
+ if (!candidate) {
1008
+ process.stdout.write(`${c.yellow(icons.warn)} no peer replay for agent "${target.agent}" — nothing to diff\n`);
1009
+ return;
1010
+ }
1011
+ const newer = await loadReplay(candidate.id, { projectRoot });
1012
+ const a = JSON.stringify(target, null, 2).split('\n');
1013
+ const b = JSON.stringify(newer, null, 2).split('\n');
1014
+ process.stdout.write(`\n${c.bold(`diff ${id} ↔ ${candidate.id}`)}\n\n`);
1015
+ const max = Math.max(a.length, b.length);
1016
+ for (let i = 0; i < max; i++) {
1017
+ if (a[i] !== b[i]) {
1018
+ if (a[i] !== undefined) process.stdout.write(c.red('-') + ' ' + a[i] + '\n');
1019
+ if (b[i] !== undefined) process.stdout.write(c.green('+') + ' ' + b[i] + '\n');
1020
+ }
1021
+ }
1022
+ } catch (e) {
1023
+ process.stderr.write(`${c.red(icons.cross)} ${e.message}\n`);
1024
+ process.exit(1);
1025
+ }
1026
+ });
1027
+
1028
+ // --- inspect (Phase 163, v1.28: live TUI mirror of MCP request/response) ---
1029
+ program.command('inspect')
1030
+ .description('Live request/response mirror — pretty-print MCP tool calls as they happen.')
1031
+ .option('--tail <n>', 'show last N events (default 20)', '20')
1032
+ .action(async (opts) => {
1033
+ const lines = parseInt(opts.tail, 10) || 20;
1034
+ if (process.env.KIT_MCP_INSPECT !== '1' && process.env.KIT_MCP_INSPECT !== 'true') {
1035
+ process.stderr.write(`${c.yellow(icons.warn)} verbose payload capture is OFF\n`);
1036
+ process.stderr.write(`${c.dim('set KIT_MCP_INSPECT=1 in the env where kit-mcp runs to capture args/result')}\n`);
1037
+ process.stderr.write(`${c.dim('(events are still tailed; just without payloads)')}\n\n`);
1038
+ }
1039
+
1040
+ const render = (raw) => {
1041
+ try {
1042
+ const ev = JSON.parse(raw);
1043
+ const t = ev.ts ? ev.ts.replace('T', ' ').replace('Z', '') : '?';
1044
+ const status = ev.status === 'ok' ? c.green('●') : c.red('●');
1045
+ const tool = c.bold(ev.tool || '?');
1046
+ const action = ev.action ? c.cyan(ev.action) : '';
1047
+ const dur = ev.duration_ms !== undefined ? c.dim(`(${ev.duration_ms}ms)`) : '';
1048
+ process.stdout.write(`\n${status} ${c.dim(t)} ${tool} ${action} ${dur}\n`);
1049
+ if (ev.args !== undefined) {
1050
+ process.stdout.write(` ${c.dim('req:')} ${JSON.stringify(ev.args)}\n`);
1051
+ }
1052
+ if (ev.result !== undefined && ev.result !== null) {
1053
+ const pretty = JSON.stringify(ev.result);
1054
+ process.stdout.write(` ${c.dim('res:')} ${pretty.length > 200 ? pretty.slice(0, 200) + '…' : pretty}\n`);
1055
+ }
1056
+ if (ev.error_type) {
1057
+ process.stdout.write(` ${c.red('err:')} ${ev.error_type}\n`);
1058
+ }
1059
+ } catch {
1060
+ process.stdout.write(raw + '\n');
1061
+ }
1062
+ };
1063
+
1064
+ const t = tailLogs({ lines, follow: true, onLine: render });
1065
+ process.stdout.write(`${c.dim(`-- inspecting ${currentLogPath()} (Ctrl-C to stop) --`)}\n`);
1066
+ process.on('SIGINT', () => { t.stop(); process.exit(0); });
1067
+ await new Promise(() => {});
1068
+ });
1069
+
1070
+ // --- logs (Phase 158, v1.28: tail kit-mcp tool-call log) ---
1071
+ program.command('logs')
1072
+ .description('Tail JSONL logs of MCP tool invocations (~/.kit-mcp/logs/).')
1073
+ .option('--tail <n>', 'show last N lines (default 50)', '50')
1074
+ .option('--follow', 'keep streaming new events as they arrive')
1075
+ .option('--path', 'print the current log file path and exit')
1076
+ .action(async (opts) => {
1077
+ if (opts.path) {
1078
+ process.stdout.write(`${currentLogPath()}\n`);
1079
+ return;
1080
+ }
1081
+ const lines = parseInt(opts.tail, 10) || 50;
1082
+ const files = listLogs();
1083
+ if (files.length === 0) {
1084
+ process.stderr.write(`${c.yellow(icons.warn)} no logs yet at ${logDir()}\n`);
1085
+ process.stderr.write(`${c.dim('logs are appended when the MCP server handles a tool call')}\n`);
1086
+ process.exit(0);
1087
+ }
1088
+ const isJson = program.opts().json;
1089
+ const render = (raw) => {
1090
+ if (isJson) { process.stdout.write(raw + '\n'); return; }
1091
+ try {
1092
+ const ev = JSON.parse(raw);
1093
+ const t = ev.ts ? ev.ts.replace('T', ' ').replace('Z', '') : '?';
1094
+ const status = ev.status === 'ok' ? c.green(icons.check) : c.red(icons.cross);
1095
+ const tool = c.bold(ev.tool || '?');
1096
+ const action = ev.action ? c.dim(`[${ev.action}]`) : '';
1097
+ const dur = ev.duration_ms !== undefined ? c.cyan(`${ev.duration_ms}ms`) : '';
1098
+ const err = ev.error_type ? c.red(` (${ev.error_type})`) : '';
1099
+ process.stdout.write(`${c.dim(t)} ${status} ${tool} ${action} ${dur}${err}\n`);
1100
+ } catch {
1101
+ process.stdout.write(raw + '\n');
1102
+ }
1103
+ };
1104
+
1105
+ const t = tailLogs({ lines, follow: !!opts.follow, onLine: render });
1106
+ if (opts.follow) {
1107
+ process.stdout.write(`${c.dim(`-- following ${currentLogPath()} (Ctrl-C to stop) --`)}\n`);
1108
+ process.on('SIGINT', () => { t.stop(); process.exit(0); });
1109
+ // keep process alive
1110
+ await new Promise(() => {});
1111
+ }
1112
+ });
1113
+
1114
+ program.parseAsync(process.argv);