codehere 0.8.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +37 -184
  2. package/dist/application/use-cases/check-claimed-tests.js +81 -0
  3. package/dist/application/use-cases/detect-test-weakening.js +237 -0
  4. package/dist/application/use-cases/rerun-tests.js +329 -0
  5. package/dist/index.js +74 -1004
  6. package/dist/infrastructure/orchestration/artifacts-extractor.js +2 -265
  7. package/dist/presentation/cli/commands/check-command.js +251 -0
  8. package/dist/presentation/cli/commands/help-command.js +22 -286
  9. package/dist/ui.js +19 -438
  10. package/dist/utils/version.js +0 -12
  11. package/package.json +18 -27
  12. package/dist/application/use-cases/domain-trust.js +0 -110
  13. package/dist/application/use-cases/generate-final-report.js +0 -134
  14. package/dist/application/use-cases/generate-narration.js +0 -128
  15. package/dist/application/use-cases/generate-thread-title.js +0 -178
  16. package/dist/application/use-cases/narrator-prompt-template.js +0 -158
  17. package/dist/application/use-cases/thread-export.js +0 -155
  18. package/dist/application/use-cases/verify-claim.js +0 -274
  19. package/dist/application/use-cases/write-pass.js +0 -277
  20. package/dist/domain/entities/task.js +0 -61
  21. package/dist/domain/services/codebase-detector.js +0 -91
  22. package/dist/error-handler.js +0 -251
  23. package/dist/infrastructure/completion/bash-completion.js +0 -25
  24. package/dist/infrastructure/completion/fish-completion.js +0 -22
  25. package/dist/infrastructure/completion/zsh-completion.js +0 -30
  26. package/dist/infrastructure/config/config-manager.js +0 -173
  27. package/dist/infrastructure/config/product-context.js +0 -67
  28. package/dist/infrastructure/context/adapters/drawio-source.js +0 -157
  29. package/dist/infrastructure/context/adapters/figma-source.js +0 -163
  30. package/dist/infrastructure/context/adapters/github-issue-source.js +0 -159
  31. package/dist/infrastructure/context/adapters/linear-source.js +0 -190
  32. package/dist/infrastructure/context/context-resolver.js +0 -144
  33. package/dist/infrastructure/context/context-source.js +0 -114
  34. package/dist/infrastructure/context/oauth-flow.js +0 -207
  35. package/dist/infrastructure/context/oauth-store.js +0 -119
  36. package/dist/infrastructure/context/registry-bootstrap.js +0 -99
  37. package/dist/infrastructure/context/write-pass-resolver.js +0 -106
  38. package/dist/infrastructure/cost/budget-config.js +0 -113
  39. package/dist/infrastructure/cost/cost-router.js +0 -104
  40. package/dist/infrastructure/cost/spend-aggregator.js +0 -147
  41. package/dist/infrastructure/hooks/claude-sdk-hook.js +0 -888
  42. package/dist/infrastructure/hooks/hook-mode.js +0 -71
  43. package/dist/infrastructure/hooks/mirror-tool-call-to-audit.js +0 -43
  44. package/dist/infrastructure/hooks/pre-prompt-scan.js +0 -122
  45. package/dist/infrastructure/hooks/session-analyzer.js +0 -177
  46. package/dist/infrastructure/observability/execution-tracer.js +0 -227
  47. package/dist/infrastructure/orchestration/agent-adapter.js +0 -13
  48. package/dist/infrastructure/orchestration/agent-installer.js +0 -101
  49. package/dist/infrastructure/orchestration/agents-config-seed.js +0 -56
  50. package/dist/infrastructure/orchestration/aider-adapter.js +0 -447
  51. package/dist/infrastructure/orchestration/cassette-recorder.js +0 -120
  52. package/dist/infrastructure/orchestration/claude-code-adapter.js +0 -478
  53. package/dist/infrastructure/orchestration/codex-adapter.js +0 -538
  54. package/dist/infrastructure/orchestration/conductor-adapter.js +0 -377
  55. package/dist/infrastructure/orchestration/context-handoff.js +0 -144
  56. package/dist/infrastructure/orchestration/control/codex-control-surface.js +0 -99
  57. package/dist/infrastructure/orchestration/control/control-surface.js +0 -15
  58. package/dist/infrastructure/orchestration/failover-classifier.js +0 -151
  59. package/dist/infrastructure/orchestration/failover-config.js +0 -77
  60. package/dist/infrastructure/orchestration/failover-policy.js +0 -106
  61. package/dist/infrastructure/orchestration/gemini-adapter.js +0 -583
  62. package/dist/infrastructure/orchestration/generic-cli-adapter.js +0 -558
  63. package/dist/infrastructure/orchestration/graphify-context.js +0 -254
  64. package/dist/infrastructure/orchestration/memory-injector.js +0 -380
  65. package/dist/infrastructure/orchestration/mocks/mock-agent-repl.js +0 -233
  66. package/dist/infrastructure/orchestration/mocks/mock-codex-app-server.js +0 -73
  67. package/dist/infrastructure/orchestration/mocks/mock-synthesis.js +0 -83
  68. package/dist/infrastructure/orchestration/mocks/resolve-agent-spawn.js +0 -37
  69. package/dist/infrastructure/orchestration/opencode-adapter.js +0 -510
  70. package/dist/infrastructure/orchestration/progress-aggregator.js +0 -689
  71. package/dist/infrastructure/orchestration/readiness.js +0 -103
  72. package/dist/infrastructure/orchestration/session-manager.js +0 -1091
  73. package/dist/infrastructure/orchestration/session-persistence.js +0 -258
  74. package/dist/infrastructure/orchestration/thread-key-store.js +0 -127
  75. package/dist/infrastructure/orchestration/write-pass-store.js +0 -46
  76. package/dist/infrastructure/protocols/cloud-sync.js +0 -207
  77. package/dist/infrastructure/protocols/mcp-helpers.js +0 -25
  78. package/dist/infrastructure/protocols/mcp-server-impl.js +0 -2853
  79. package/dist/infrastructure/protocols/probe-port.js +0 -36
  80. package/dist/infrastructure/protocols/thread-phase.js +0 -105
  81. package/dist/infrastructure/protocols/ui-page-v2.js +0 -4418
  82. package/dist/infrastructure/protocols/ui-page.js +0 -2377
  83. package/dist/infrastructure/protocols/verify-page.js +0 -983
  84. package/dist/infrastructure/security/file-collection.js +0 -118
  85. package/dist/infrastructure/security/input-validator.js +0 -152
  86. package/dist/infrastructure/security/permissions-config.js +0 -234
  87. package/dist/infrastructure/security/trust-scorer.js +0 -657
  88. package/dist/infrastructure/storage/cross-tool-agents.js +0 -268
  89. package/dist/infrastructure/storage/embeddings-path.js +0 -37
  90. package/dist/infrastructure/storage/project-thread-migration.js +0 -237
  91. package/dist/infrastructure/storage/project-thread-mirror.js +0 -524
  92. package/dist/infrastructure/storage/project-thread-reader.js +0 -172
  93. package/dist/infrastructure/storage/project-thread-title-backfill.js +0 -214
  94. package/dist/infrastructure/storage/task-repository.js +0 -206
  95. package/dist/monitoring.js +0 -212
  96. package/dist/presentation/cli/commands/audit-command.js +0 -126
  97. package/dist/presentation/cli/commands/budget-command.js +0 -79
  98. package/dist/presentation/cli/commands/config-command.js +0 -125
  99. package/dist/presentation/cli/commands/context-source-command.js +0 -198
  100. package/dist/presentation/cli/commands/hook-command.js +0 -265
  101. package/dist/presentation/cli/commands/init-command.js +0 -578
  102. package/dist/presentation/cli/commands/memory-command.js +0 -1031
  103. package/dist/presentation/cli/commands/narrator-command.js +0 -101
  104. package/dist/presentation/cli/commands/permission-command.js +0 -116
  105. package/dist/presentation/cli/commands/protocols-builder.js +0 -254
  106. package/dist/presentation/cli/commands/protocols-command.js +0 -84
  107. package/dist/presentation/cli/commands/repo-map-builder.js +0 -247
  108. package/dist/presentation/cli/commands/report-command.js +0 -387
  109. package/dist/presentation/cli/commands/scan-tool-command.js +0 -94
  110. package/dist/presentation/cli/commands/setup-command.js +0 -307
  111. package/dist/presentation/cli/commands/status-command.js +0 -661
  112. package/dist/presentation/cli/commands/thread-command.js +0 -288
  113. package/dist/presentation/cli/commands/trust-command.js +0 -306
  114. package/dist/presentation/cli/commands/verify-command.js +0 -233
  115. package/dist/presentation/cli/error-display.js +0 -336
  116. package/dist/presentation/cli/repl.js +0 -797
  117. package/dist/presentation/cli/task-deliverable.js +0 -127
  118. package/dist/testing/cassette.js +0 -125
  119. package/dist/testing/replay-adapter.js +0 -166
@@ -1,797 +0,0 @@
1
- /**
2
- * Interactive REPL · raw-mode live command palette.
3
- *
4
- * Faithful port of v0.2.2's session.ts (commit f4828c2 · "REPL fixes,
5
- * Palette Enter completes selected command, stdin multi-char chunk
6
- * processing"). Same banner with state badges, same `> ` prompt with
7
- * brand color, same filter-as-you-type palette under the prompt, same
8
- * escape-buffering keystroke handler, same Tab/Enter complete, same
9
- * arrow-key palette navigation when palette is visible / history when not.
10
- *
11
- * Backends adapted to v0.3 (chat/edit/review/planner removed in D7):
12
- * - Task slash commands (ask, explain, fix, review, plan, test, refactor,
13
- * orchestrate, run) → spawn via Conductor
14
- * - Subcommand slash (trust, report, hook, status, health, serve, setup,
15
- * config) → invoke `node dist/index.js <cmd>` inline
16
- * - /undo → "queued for v0.5 (F3 memory layer)"
17
- *
18
- * Citing f4828c2 for lineage. Don't redesign.
19
- */
20
- import { existsSync, readdirSync, readFileSync } from 'fs';
21
- import { join, basename } from 'path';
22
- import { spawn as childSpawn } from 'child_process';
23
- import { fileURLToPath } from 'url';
24
- import { dirname } from 'path';
25
- import { colors, success, error, warning, newline, createCodehereLogo } from '../../ui.js';
26
- import { getVersion } from '../../utils/version.js';
27
- import { SessionManager, availableAgents } from '../../infrastructure/orchestration/session-manager.js';
28
- import { collectCodeFiles } from '../../infrastructure/security/file-collection.js';
29
- import chalk from 'chalk';
30
- const brandBlue = chalk.rgb(74, 144, 226);
31
- const stdin = process.stdin;
32
- const stdout = process.stdout;
33
- const SLASH_COMMANDS = [
34
- // Tasks · delegate via Conductor
35
- {
36
- name: 'ask',
37
- args: '<question>',
38
- description: 'Ask anything about your codebase',
39
- kind: 'task',
40
- promptTemplate: (a) => a,
41
- },
42
- {
43
- name: 'explain',
44
- args: '<file>',
45
- description: 'Explain a file',
46
- kind: 'task',
47
- promptTemplate: (a) => `Explain this file in plain English: ${a}`,
48
- },
49
- {
50
- name: 'fix',
51
- args: '<file> <hint>',
52
- description: 'Apply a targeted fix',
53
- kind: 'task',
54
- promptTemplate: (a) => {
55
- const parts = a.split(/\s+/);
56
- const file = parts[0];
57
- const hint = parts.slice(1).join(' ');
58
- return `fix ${file}: ${hint}`;
59
- },
60
- },
61
- {
62
- name: 'review',
63
- args: '<file>',
64
- description: 'Code review with findings',
65
- kind: 'task',
66
- promptTemplate: (a) => `Review ${a} for bugs, security issues, and risks. Concrete findings only.`,
67
- },
68
- {
69
- name: 'plan',
70
- args: '<goal>',
71
- description: 'Break a goal into steps',
72
- kind: 'task',
73
- promptTemplate: (a) => `Plan: ${a}. Break into concrete steps before any execution.`,
74
- },
75
- {
76
- name: 'test',
77
- args: '<file>',
78
- description: 'Generate tests for a file',
79
- kind: 'task',
80
- promptTemplate: (a) => `add tests for ${a}. Cover edge cases and likely failure modes.`,
81
- },
82
- {
83
- name: 'refactor',
84
- args: '<pattern> <instr>',
85
- description: 'Refactor across files',
86
- kind: 'task',
87
- promptTemplate: (a) => `refactor: ${a}`,
88
- },
89
- // Subcommands · run an existing CLI subcommand inline
90
- {
91
- name: 'trust',
92
- args: '[path]',
93
- description: 'Scan for vulnerabilities',
94
- kind: 'sub',
95
- noKey: true,
96
- subcommand: 'trust',
97
- },
98
- {
99
- name: 'report',
100
- args: '[path]',
101
- description: 'Security audit report',
102
- kind: 'sub',
103
- noKey: true,
104
- subcommand: 'report',
105
- },
106
- {
107
- name: 'hook',
108
- args: '[install|status]',
109
- description: 'Safety hook management',
110
- kind: 'sub',
111
- noKey: true,
112
- subcommand: 'hook',
113
- },
114
- {
115
- name: 'status',
116
- args: '',
117
- description: 'Dashboard — hook activity',
118
- kind: 'sub',
119
- noKey: true,
120
- subcommand: 'status',
121
- },
122
- {
123
- name: 'verify',
124
- args: '[session-id]',
125
- description: "Verify a session's Final Report against recorded reality",
126
- kind: 'sub',
127
- noKey: true,
128
- subcommand: 'verify',
129
- },
130
- {
131
- name: 'audit',
132
- args: '[verify|show]',
133
- description: 'Inspect the hash-chained audit log',
134
- kind: 'sub',
135
- noKey: true,
136
- subcommand: 'audit',
137
- },
138
- {
139
- name: 'context-source',
140
- args: '[list|connect|disconnect]',
141
- description: 'Connect Linear/Figma via OAuth',
142
- kind: 'sub',
143
- noKey: true,
144
- subcommand: 'context-source',
145
- },
146
- {
147
- name: 'thread',
148
- args: '<sub> [arg]',
149
- description: 'Share or import a signed session bundle',
150
- kind: 'sub',
151
- noKey: true,
152
- subcommand: 'thread',
153
- },
154
- { name: 'health', args: '', description: 'System health check', kind: 'sub', noKey: true, subcommand: 'health' },
155
- {
156
- name: 'setup',
157
- args: '',
158
- description: 'Configure first-run preferences',
159
- kind: 'sub',
160
- noKey: true,
161
- subcommand: 'setup',
162
- },
163
- {
164
- name: 'config',
165
- args: '[key] [value]',
166
- description: 'Manage preferences',
167
- kind: 'sub',
168
- noKey: true,
169
- subcommand: 'config',
170
- },
171
- { name: 'agents', args: '', description: 'List installed specialists', kind: 'session', noKey: true },
172
- { name: 'undo', args: '<file>', description: 'Undo file changes (queued for v0.5)', kind: 'session', noKey: true },
173
- { name: 'history', args: '', description: 'Show command history', kind: 'session', noKey: true },
174
- // Helpers
175
- { name: 'help', args: '', description: 'Command reference', kind: 'session', noKey: true },
176
- { name: 'clear', args: '', description: 'Clear the screen', kind: 'session', noKey: true },
177
- { name: 'exit', args: '', description: 'Leave the session', kind: 'session', noKey: true },
178
- ];
179
- const PALETTE_CMDS = SLASH_COMMANDS.map((c) => ({
180
- sig: `/${c.name}${c.args ? ' ' + c.args : ''}`,
181
- name: c.name,
182
- desc: c.description,
183
- noKey: c.noKey,
184
- }));
185
- function maxPalette() {
186
- const rows = process.stdout.rows || 24;
187
- return Math.min(rows - 8, 20);
188
- }
189
- // ── State detection (badges in welcome) ──────────────────────────────────
190
- function detectState() {
191
- const cwd = process.cwd();
192
- const name = basename(cwd);
193
- const settingsPath = join(process.env.HOME || '', '.claude', 'settings.json');
194
- let hasHooks = false;
195
- try {
196
- hasHooks = existsSync(settingsPath) && readFileSync(settingsPath, 'utf-8').includes('codehere');
197
- }
198
- catch {
199
- /* ignore */
200
- }
201
- const hasAnyAgent = availableAgents().some((a) => a.installed && a.id !== 'conductor');
202
- const isGitRepo = existsSync(join(cwd, '.git'));
203
- let fileCount = 0;
204
- let scannableCount = 0;
205
- try {
206
- const count = (dir, d) => {
207
- if (d > 3)
208
- return 0;
209
- let n = 0;
210
- for (const e of readdirSync(dir, { withFileTypes: true })) {
211
- if (e.name.startsWith('.') || e.name === 'node_modules' || e.name === 'dist')
212
- continue;
213
- if (e.isDirectory())
214
- n += count(join(dir, e.name), d + 1);
215
- else
216
- n++;
217
- }
218
- return n;
219
- };
220
- fileCount = count(cwd, 0);
221
- // rc.21: surface the scannable count — code files that trust/scan
222
- // would actually look at. Honest count beats a single inflated number.
223
- // UX_OBSERVATIONS P3. Static ESM import (rc.20 used `require()` which is
224
- // undefined in this package's ESM runtime — Codex caught the silent fail).
225
- try {
226
- scannableCount = collectCodeFiles(cwd).length;
227
- }
228
- catch {
229
- /* ignore — banner stays silent rather than crashes */
230
- }
231
- }
232
- catch {
233
- /* ignore */
234
- }
235
- return { name, hasHooks, hasAgents: hasAnyAgent, isGitRepo, fileCount, scannableCount };
236
- }
237
- /**
238
- * Format the banner's "X files (Y scannable)" line.
239
- *
240
- * Pure function (no I/O) so the rc.20 silent-fail regression that Codex
241
- * caught — banner falling back to total-only when scannable load fails —
242
- * has a tight unit test.
243
- *
244
- * Contract:
245
- * - scannable > 0 AND scannable < total → "<total> files (<scannable> scannable)"
246
- * - otherwise → "<total> files"
247
- *
248
- * Exported for test/cli/rc15-fixes.test.ts banner integration test.
249
- */
250
- export function formatFileLine(total, scannable) {
251
- if (scannable > 0 && scannable < total) {
252
- return `${total} files (${scannable} scannable)`;
253
- }
254
- return `${total} files`;
255
- }
256
- export function buildWelcomeLines(state, version) {
257
- const logo = createCodehereLogo();
258
- const ver = colors.dim(`v${version}`);
259
- const badges = [
260
- state.hasHooks ? colors.green('● hooks') : colors.dim('○ hooks'),
261
- state.hasAgents ? colors.green('● agents') : colors.dim('○ agents'),
262
- ];
263
- const lines = [
264
- '',
265
- ` ${logo} ${ver}`,
266
- '',
267
- ' ' + badges.join(' '),
268
- '',
269
- colors.dim(` ${state.name}`) +
270
- colors.dim(` · ${state.isGitRepo ? 'git' : 'dir'} · ${formatFileLine(state.fileCount, state.scannableCount)}`),
271
- '',
272
- ];
273
- if (!state.hasHooks) {
274
- lines.push(' ' + colors.yellow('→') + ' ' + colors.cyan('/hook install') + colors.dim(' to activate safety scanning'));
275
- }
276
- else if (!state.hasAgents) {
277
- lines.push(' ' +
278
- colors.yellow('→') +
279
- ' Install ' +
280
- colors.cyan('claude-code') +
281
- colors.dim(' / ') +
282
- colors.cyan('codex') +
283
- colors.dim(' / aider / opencode to delegate tasks'));
284
- }
285
- lines.push(colors.dim(' Type / for commands, or ask anything'));
286
- lines.push('');
287
- return lines;
288
- }
289
- function printWelcome() {
290
- const state = detectState();
291
- for (const line of buildWelcomeLines(state, getVersion())) {
292
- console.log(line);
293
- }
294
- }
295
- // ── Main session ─────────────────────────────────────────────────────────
296
- export async function runInteractiveRepl() {
297
- printWelcome();
298
- if (stdin.isTTY)
299
- stdin.setRawMode(true);
300
- stdin.resume();
301
- stdin.setEncoding('utf8');
302
- const state = { history: [] };
303
- const historyBuf = [];
304
- let historyIdx = -1;
305
- let line = '';
306
- let selected = 0;
307
- let pLines = 0;
308
- let processing = false;
309
- let escBuf = '';
310
- let escTimer = null;
311
- const cols = () => stdout.columns || 80;
312
- function truncate(s, maxWidth) {
313
- const visible = s.replace(/\x1b\[[0-9;]*m/g, '');
314
- if (visible.length <= maxWidth)
315
- return s;
316
- let vis = 0;
317
- let cut = 0;
318
- for (let i = 0; i < s.length; i++) {
319
- if (s[i] === '\x1b') {
320
- const end = s.indexOf('m', i);
321
- if (end !== -1) {
322
- i = end;
323
- continue;
324
- }
325
- }
326
- vis++;
327
- if (vis >= maxWidth - 1) {
328
- cut = i + 1;
329
- break;
330
- }
331
- }
332
- return cut > 0 ? s.slice(0, cut) + '\x1b[0m' : s;
333
- }
334
- function render() {
335
- stdout.write('\r\x1b[J');
336
- stdout.write(brandBlue('> ') + line);
337
- if (line.startsWith('/') && !line.includes(' ')) {
338
- const filter = line.slice(1).toLowerCase();
339
- const allMatching = PALETTE_CMDS.filter((c) => c.name.startsWith(filter));
340
- const limit = maxPalette();
341
- const filtered = allMatching.slice(0, limit);
342
- const overflow = allMatching.length - filtered.length;
343
- if (filtered.length > 0) {
344
- const maxLen = Math.max(...filtered.map((c) => c.sig.length));
345
- const w = cols();
346
- let drawnLines = 0;
347
- for (let i = 0; i < filtered.length; i++) {
348
- const c = filtered[i];
349
- const pad = ' '.repeat(Math.max(1, maxLen - c.sig.length + 2));
350
- const badge = c.noKey ? colors.dim(' (free)') : '';
351
- const prefix = i === selected ? brandBlue('▸') : ' ';
352
- const text = i === selected ? brandBlue(c.sig) : c.sig;
353
- const row = ` ${prefix} ${text}${pad}${colors.dim(c.desc)}${badge}`;
354
- stdout.write('\n' + truncate(row, w));
355
- drawnLines++;
356
- }
357
- if (overflow > 0) {
358
- stdout.write('\n' + colors.dim(` ... +${overflow} more (type to filter)`));
359
- drawnLines++;
360
- }
361
- stdout.write(`\x1b[${drawnLines}A`);
362
- stdout.write(`\x1b[${line.length + 3}G`);
363
- pLines = drawnLines;
364
- }
365
- else {
366
- stdout.write('\n' + colors.dim(' No matching commands'));
367
- stdout.write('\x1b[1A');
368
- stdout.write(`\x1b[${line.length + 3}G`);
369
- pLines = 1;
370
- }
371
- }
372
- else {
373
- pLines = 0;
374
- }
375
- }
376
- function handle(key) {
377
- if (processing)
378
- return;
379
- // Ctrl+C
380
- if (key === '\x03') {
381
- if (line.length > 0) {
382
- line = '';
383
- selected = 0;
384
- stdout.write('\r\x1b[J\n');
385
- render();
386
- }
387
- else {
388
- stdout.write('\r\x1b[J\n');
389
- process.exit(0);
390
- }
391
- return;
392
- }
393
- // Ctrl+D
394
- if (key === '\x04') {
395
- stdout.write('\r\x1b[J\n' + colors.dim(' See you.') + '\n');
396
- process.exit(0);
397
- }
398
- // Ctrl+L
399
- if (key === '\x0c') {
400
- line = '';
401
- selected = 0;
402
- stdout.write('\x1b[2J\x1b[H');
403
- printWelcome();
404
- render();
405
- return;
406
- }
407
- // Arrow up
408
- if (key === '\x1b[A') {
409
- if (pLines > 0) {
410
- selected = Math.max(0, selected - 1);
411
- }
412
- else if (historyBuf.length > 0 && historyIdx < historyBuf.length - 1) {
413
- historyIdx++;
414
- line = historyBuf[historyIdx];
415
- }
416
- render();
417
- return;
418
- }
419
- // Arrow down
420
- if (key === '\x1b[B') {
421
- if (pLines > 0) {
422
- selected = Math.min(pLines - 1, selected + 1);
423
- }
424
- else {
425
- if (historyIdx > 0) {
426
- historyIdx--;
427
- line = historyBuf[historyIdx];
428
- }
429
- else {
430
- historyIdx = -1;
431
- line = '';
432
- }
433
- }
434
- render();
435
- return;
436
- }
437
- // Tab
438
- if (key === '\t' && pLines > 0) {
439
- const filter = line.slice(1).toLowerCase();
440
- const filtered = PALETTE_CMDS.filter((c) => c.name.startsWith(filter)).slice(0, maxPalette());
441
- if (filtered[selected]) {
442
- line = `/${filtered[selected].name} `;
443
- selected = 0;
444
- }
445
- render();
446
- return;
447
- }
448
- // Enter
449
- if (key === '\r' || key === '\n') {
450
- if (pLines > 0 && line.startsWith('/') && !line.includes(' ')) {
451
- const filter = line.slice(1).toLowerCase();
452
- const filtered = PALETTE_CMDS.filter((c) => c.name.startsWith(filter)).slice(0, maxPalette());
453
- if (filtered[selected]) {
454
- line = `/${filtered[selected].name}`;
455
- }
456
- }
457
- stdout.write('\r\x1b[J\n');
458
- const trimmed = line.trim();
459
- if (trimmed) {
460
- historyBuf.unshift(trimmed);
461
- historyIdx = -1;
462
- }
463
- line = '';
464
- selected = 0;
465
- pLines = 0;
466
- if (!trimmed) {
467
- render();
468
- return;
469
- }
470
- processing = true;
471
- executeInput(trimmed, state)
472
- .catch((err) => {
473
- console.log(error(' ' + (err instanceof Error ? err.message : String(err))));
474
- })
475
- .finally(() => {
476
- processing = false;
477
- stdin.resume();
478
- stdin.ref();
479
- if (stdin.isTTY && !stdin.isRaw)
480
- stdin.setRawMode(true);
481
- console.log();
482
- render();
483
- });
484
- return;
485
- }
486
- // Backspace
487
- if (key === '\x7f' || key === '\b') {
488
- if (line.length > 0) {
489
- line = line.slice(0, -1);
490
- selected = 0;
491
- render();
492
- }
493
- return;
494
- }
495
- // Ignore stray escape sequences
496
- if (key.startsWith('\x1b'))
497
- return;
498
- // Regular character
499
- line += key;
500
- selected = 0;
501
- render();
502
- }
503
- render();
504
- stdin.on('data', (raw) => {
505
- if (processing)
506
- return;
507
- if (raw.startsWith('\x1b') && raw.length >= 2) {
508
- handle(raw);
509
- return;
510
- }
511
- for (let i = 0; i < raw.length; i++) {
512
- if (processing)
513
- return;
514
- const ch = raw[i];
515
- if (escBuf.length > 0) {
516
- escBuf += ch;
517
- if (escTimer)
518
- clearTimeout(escTimer);
519
- if (escBuf.length >= 3) {
520
- const seq = escBuf;
521
- escBuf = '';
522
- handle(seq);
523
- }
524
- else {
525
- escTimer = setTimeout(() => {
526
- const seq = escBuf;
527
- escBuf = '';
528
- handle(seq);
529
- }, 50);
530
- }
531
- continue;
532
- }
533
- if (ch === '\x1b') {
534
- escBuf = ch;
535
- escTimer = setTimeout(() => {
536
- const seq = escBuf;
537
- escBuf = '';
538
- handle(seq);
539
- }, 50);
540
- continue;
541
- }
542
- handle(ch);
543
- }
544
- });
545
- }
546
- /** One-shot · `codehere "review src/auth.ts"` runs that task and exits. */
547
- export async function runOneShot(prompt) {
548
- const installed = availableAgents().filter((a) => a.installed);
549
- if (installed.length === 0) {
550
- console.log(warning('No specialist installed. Run `codehere setup` and try again.'));
551
- process.exit(1);
552
- }
553
- try {
554
- await spawnViaConductor(prompt);
555
- }
556
- catch (err) {
557
- console.error(error('Error:'), err instanceof Error ? err.message : String(err));
558
- process.exit(1);
559
- }
560
- }
561
- // ── Dispatch ─────────────────────────────────────────────────────────────
562
- async function executeInput(input, state) {
563
- const lower = input.toLowerCase();
564
- if (lower.startsWith('/')) {
565
- const parts = input.substring(1).trim().split(/\s+/);
566
- const cmd = parts[0].toLowerCase();
567
- const args = parts.slice(1).join(' ');
568
- await handleSlash(cmd, args, state);
569
- return;
570
- }
571
- // Legacy non-slash syntax (v0.2 backwards compat)
572
- if (lower.startsWith('explain '))
573
- return runTask(`Explain this file in plain English: ${input.substring(8).trim()}`, state);
574
- if (lower.startsWith('e '))
575
- return runTask(`Explain this file in plain English: ${input.substring(2).trim()}`, state);
576
- if (lower.startsWith('fix ')) {
577
- const rest = input.substring(4).trim();
578
- const parts = rest.split(/\s+/);
579
- return runTask(`fix ${parts[0]}: ${parts.slice(1).join(' ')}`, state);
580
- }
581
- if (lower.startsWith('review '))
582
- return runTask(`Review ${input.substring(7).trim()} for bugs, security, and risks.`, state);
583
- if (lower.startsWith('plan '))
584
- return runTask(`Plan: ${input.substring(5).trim()}. Break into steps.`, state);
585
- // Default: ask via Conductor
586
- await runTask(input, state);
587
- }
588
- async function handleSlash(cmd, args, state) {
589
- if (cmd === 'help' || cmd === '?') {
590
- showSlashCommandMenu();
591
- return;
592
- }
593
- if (cmd === 'clear') {
594
- stdout.write('\x1b[2J\x1b[H');
595
- printWelcome();
596
- return;
597
- }
598
- if (cmd === 'exit' || cmd === 'quit' || cmd === 'q') {
599
- console.log(colors.dim('Goodbye! 👋'));
600
- process.exit(0);
601
- }
602
- if (cmd === 'agents') {
603
- const all = availableAgents();
604
- newline();
605
- console.log(colors.bold(' Installed specialists:'));
606
- for (const a of all) {
607
- const tag = a.installed ? colors.green(' ✓ ') : colors.dim(' · ');
608
- const status = a.installed ? '' : colors.dim(' (not installed)');
609
- console.log(tag + colors.cyan(a.id.padEnd(14)) + colors.dim(a.label) + status);
610
- }
611
- newline();
612
- return;
613
- }
614
- if (cmd === 'history' || cmd === 'h') {
615
- if (state.history.length === 0) {
616
- console.log(colors.dim('No command history yet.'));
617
- }
618
- else {
619
- console.log(colors.bold('Recent Commands:'));
620
- state.history.slice(-10).forEach((h, i) => {
621
- const preview = h.command.length > 60 ? h.command.slice(0, 57) + '…' : h.command;
622
- console.log(colors.dim(` ${i + 1}. ${preview}`));
623
- });
624
- }
625
- return;
626
- }
627
- if (cmd === 'undo') {
628
- console.log(colors.dim(' /undo is queued for v0.5 (F3 memory layer).'));
629
- console.log(colors.dim(' For now: ') + colors.cyan('git diff') + colors.dim(' / ') + colors.cyan('git checkout -- <file>'));
630
- return;
631
- }
632
- const def = SLASH_COMMANDS.find((c) => c.name === cmd);
633
- if (!def) {
634
- console.log(warning(`Unknown command: /${cmd}`));
635
- console.log(colors.dim('Type /help to see available commands'));
636
- return;
637
- }
638
- if (def.kind === 'task' && def.promptTemplate) {
639
- if (!args && def.args) {
640
- console.log(warning(`Usage: /${def.name} ${def.args}`));
641
- return;
642
- }
643
- await runTask(def.promptTemplate(args), state);
644
- return;
645
- }
646
- if (def.kind === 'sub' && def.subcommand) {
647
- await runSubcommand(def.subcommand, args ? args.split(/\s+/) : []);
648
- return;
649
- }
650
- }
651
- function showSlashCommandMenu() {
652
- newline();
653
- console.log(colors.bold(' Slash commands'));
654
- newline();
655
- const maxNameLen = Math.max(...SLASH_COMMANDS.map((c) => c.name.length + c.args.length)) + 1;
656
- for (const cmd of SLASH_COMMANDS) {
657
- const signature = `/${cmd.name}${cmd.args ? ' ' + cmd.args : ''}`;
658
- const pad = ' '.repeat(Math.max(0, maxNameLen + 2 - signature.length + 8));
659
- const badge = cmd.noKey ? colors.dim(' (free)') : '';
660
- console.log(` ${colors.cyan(signature)}${pad}${colors.dim(cmd.description)}${badge}`);
661
- }
662
- newline();
663
- console.log(colors.dim(' Type any command with / prefix, or just ask a question directly.'));
664
- newline();
665
- }
666
- // ── Run-task / Run-subcommand helpers ────────────────────────────────────
667
- async function runTask(prompt, state) {
668
- await spawnViaConductor(prompt, state);
669
- }
670
- async function runSubcommand(name, extraArgs) {
671
- const here = fileURLToPath(import.meta.url);
672
- const cliPath = join(dirname(here), '..', '..', 'index.js');
673
- await new Promise((resolve) => {
674
- const child = childSpawn('node', [cliPath, name, ...extraArgs], { stdio: 'inherit' });
675
- child.on('close', () => resolve());
676
- child.on('error', (err) => {
677
- console.log(error(' ' + err.message));
678
- resolve();
679
- });
680
- });
681
- }
682
- /**
683
- * UAT-002 — exit-intent words typed at the REPL prompt without a leading
684
- * slash should leave the session, not get routed to a Conductor spawn.
685
- *
686
- * Pre-fix: typing bare `exit` (no `/`) fell through to spawnViaConductor,
687
- * which booted Conductor, picked claude-code under default routing, made
688
- * a real API call (network or quota), and emitted a confusing Final Report
689
- * echoing the provider error verbatim. First-impression UX bug found by
690
- * UAT 2026-05-19.
691
- */
692
- const EXIT_INTENT_WORDS = new Set(['exit', 'quit', 'q', 'bye', 'goodbye', 'logout', ':q']);
693
- async function spawnViaConductor(prompt, state) {
694
- // UAT-002 guard — exit-intent before any spawn / API call.
695
- const trimmed = prompt.trim().toLowerCase();
696
- if (EXIT_INTENT_WORDS.has(trimmed)) {
697
- console.log(colors.dim('Goodbye! 👋'));
698
- process.exit(0);
699
- }
700
- const installed = availableAgents().filter((a) => a.installed);
701
- if (installed.length === 0) {
702
- console.log(warning('No specialist installed — install one and try again.'));
703
- return;
704
- }
705
- const manager = SessionManager.getInstance();
706
- const session = manager.spawn(prompt, 'conductor', { cwd: process.cwd() });
707
- console.log(colors.dim(' ┌─ ') +
708
- colors.bold(session.sessionId.slice(0, 8)) +
709
- colors.dim(' · ' + new Date(session.startedAt).toLocaleTimeString()));
710
- let captured = '';
711
- await new Promise((resolve) => {
712
- const unsubscribe = session.subscribe((event) => {
713
- const text = renderEvent(event);
714
- if (text)
715
- captured += text + '\n';
716
- if (event.type === 'codehere:complete' || event.type === 'codehere:error' || event.type === 'exit') {
717
- unsubscribe();
718
- resolve();
719
- }
720
- });
721
- });
722
- const status = session.status;
723
- const verdict = status === 'completed'
724
- ? success(' └─ done')
725
- : status === 'killed'
726
- ? warning(' └─ killed')
727
- : error(' └─ ' + status);
728
- console.log(verdict);
729
- if (state) {
730
- state.history.push({ command: prompt, response: captured, timestamp: new Date().toISOString() });
731
- }
732
- }
733
- function renderEvent(event) {
734
- switch (event.type) {
735
- case 'codehere:conductor-routing': {
736
- const data = event.data;
737
- console.log(colors.dim(' │ ') +
738
- colors.bold('routing → ') +
739
- colors.cyan(data.delegatedTo ?? '?') +
740
- colors.dim(' · ' + (data.reason ?? '')));
741
- return null;
742
- }
743
- case 'codehere:steps': {
744
- const data = event.data;
745
- const steps = data?.steps;
746
- if (!steps || steps.length === 0)
747
- return null;
748
- const lastStep = steps[steps.length - 1];
749
- if (!lastStep)
750
- return null;
751
- const state = lastStep.state || 'pending';
752
- const label = String(lastStep.label || '');
753
- if (state === 'active') {
754
- console.log(colors.dim(' │ ') + colors.cyan('●') + ' ' + label);
755
- return label;
756
- }
757
- if (state === 'done' || state === 'failed') {
758
- const icon = state === 'done' ? colors.green('✓') : colors.red('✗');
759
- console.log(colors.dim(' │ ') + icon + ' ' + label);
760
- // P22 / Track B #8 — render last 3 lines of step output for done/failed
761
- if (lastStep.output && String(lastStep.output).trim()) {
762
- const outLines = String(lastStep.output)
763
- .split(String.fromCharCode(10))
764
- .filter((l) => l.trim());
765
- const preview = outLines.slice(-3);
766
- for (const ln of preview) {
767
- console.log(colors.dim(' │ ') + colors.gray(ln));
768
- }
769
- }
770
- return label;
771
- }
772
- return null;
773
- }
774
- case 'stdout':
775
- case 'stderr': {
776
- const data = event.data;
777
- const line = data?.line;
778
- if (line) {
779
- const text = String(line).trimEnd();
780
- if (text) {
781
- console.log(colors.dim(' │ ') + text);
782
- return text;
783
- }
784
- }
785
- return null;
786
- }
787
- case 'error': {
788
- const data = event.data;
789
- if (data?.message)
790
- console.log(colors.red(' │ ✗ ') + data.message);
791
- return null;
792
- }
793
- default:
794
- return null;
795
- }
796
- }
797
- //# sourceMappingURL=repl.js.map