@hncode/hncode 0.8.1 → 0.8.3

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 (52) hide show
  1. package/README.md +18 -0
  2. package/README_CN.md +14 -0
  3. package/bin/hncode +54 -8
  4. package/package.json +1 -1
  5. package/src/agent-task.js +356 -337
  6. package/src/agent.js +1465 -1405
  7. package/src/animate.js +56 -0
  8. package/src/colors.js +615 -593
  9. package/src/config.js +50 -7
  10. package/src/context-bar.js +280 -278
  11. package/src/doctor.js +4 -3
  12. package/src/file-tree.js +4 -3
  13. package/src/highlight.js +20 -6
  14. package/src/i18n.js +1432 -389
  15. package/src/image-row.js +11 -2
  16. package/src/index.js +218 -6
  17. package/src/keybindings.js +2 -1
  18. package/src/llm.js +146 -21
  19. package/src/log-file.js +112 -0
  20. package/src/markdown.js +646 -567
  21. package/src/mcp-server.js +409 -0
  22. package/src/mcp.js +279 -29
  23. package/src/memory-profile.js +19 -16
  24. package/src/migrate-index.js +175 -0
  25. package/src/migrate.js +392 -0
  26. package/src/panels.js +9 -7
  27. package/src/plan.js +7 -5
  28. package/src/plugin.js +37 -21
  29. package/src/registry-browser.js +17 -15
  30. package/src/rows-plan-bg.js +3 -2
  31. package/src/rows-status.js +20 -6
  32. package/src/rows-tool-result.js +242 -208
  33. package/src/screen-paint.js +153 -128
  34. package/src/session-recover.js +317 -0
  35. package/src/session.js +203 -13
  36. package/src/settings-schema.js +9 -0
  37. package/src/swarm-progress.js +6 -2
  38. package/src/tasks-browser.js +37 -36
  39. package/src/team-panel.js +12 -11
  40. package/src/term.js +57 -21
  41. package/src/text.js +254 -149
  42. package/src/tool-line.js +7 -2
  43. package/src/tool-result.js +400 -327
  44. package/src/tools/agent.js +7 -2
  45. package/src/tools/ask-user-question.js +1 -2
  46. package/src/tools/bash.js +446 -434
  47. package/src/tools/edit.js +653 -665
  48. package/src/tools/goal.js +130 -93
  49. package/src/tools/read.js +141 -133
  50. package/src/tools/tasks.js +214 -214
  51. package/src/tools/utils.js +143 -104
  52. package/src/tui.js +20887 -19942
package/src/mcp.js CHANGED
@@ -28,9 +28,26 @@ import os from 'node:os';
28
28
  import path from 'node:path';
29
29
  import cp from 'node:child_process';
30
30
 
31
- // The protocol revision this client speaks. Servers negotiate down if needed.
32
- export const PROTOCOL_VERSION = '2024-11-05';
33
- export const CLIENT_INFO = { name: 'hncode', version: '0.3.1' };
31
+ // The protocol revisions this client speaks, newest first.
32
+ //
33
+ // The version used to be pinned to '2024-11-05'. That is still understood by most
34
+ // servers, but a server that only speaks a newer revision rejects the handshake outright,
35
+ // and the client had no way to try the next one. The handshake now OFFERS this list and
36
+ // the server picks — or names the one it wants, which is then used for the rest of the
37
+ // session.
38
+ export const SUPPORTED_PROTOCOL_VERSIONS = [
39
+ '2025-06-18',
40
+ '2025-03-26',
41
+ '2024-11-05',
42
+ ];
43
+
44
+ // The revision sent in `initialize` when the server has not told us otherwise. The
45
+ // newest is tried first, because a server that supports only the old one will say so in
46
+ // its reply and the client then falls back.
47
+ export const PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
48
+
49
+ export const CLIENT_INFO = { name: 'hncode', version: '0.8.2' };
50
+
34
51
 
35
52
  // How long a server gets to complete the initialize + tools/list handshake. This
36
53
  // runs BEFORE the TUI opens, so it is deliberately short: a wedged server should
@@ -58,6 +75,15 @@ export function projectMcpFile(workspace) {
58
75
  // REPO's .hncode/mcp.json names, so a cloned repository would otherwise get
59
76
  // arbitrary code execution the moment hncode opens the workspace; connectAll
60
77
  // refuses them without an explicit approval (see the gate there).
78
+ //
79
+ // THE KEY NAMES DIFFER BETWEEN CLIENTS, so all of them are read:
80
+ // mcpServers Claude Desktop, Cursor, Claude Code, most of the ecosystem
81
+ // servers VS Code and a few others
82
+ // mcp_servers the snake_case spelling some tools write
83
+ // A file may hold more than one of them; they are merged, first spelling wins on a
84
+ // name clash.
85
+ const SERVER_KEYS = ['mcpServers', 'servers', 'mcp_servers'];
86
+
61
87
  export function loadMcpConfig(workspace) {
62
88
  const out = { servers: {}, errors: [] };
63
89
  const projectFile = workspace ? path.resolve(projectMcpFile(workspace)) : null;
@@ -72,16 +98,64 @@ export function loadMcpConfig(workspace) {
72
98
  try { text = fs.readFileSync(abs, 'utf8'); } catch { continue; }
73
99
  let doc;
74
100
  try { doc = JSON.parse(text); } catch (e) { out.errors.push(`${abs}: invalid JSON (${e.message})`); continue; }
75
- const servers = (doc && doc.mcpServers) || {};
101
+ const servers = {};
102
+ for (const key of SERVER_KEYS) {
103
+ const group = doc && doc[key];
104
+ if (!group || typeof group !== 'object') continue;
105
+ for (const [name, def] of Object.entries(group)) {
106
+ if (!servers[name]) servers[name] = def;
107
+ }
108
+ }
76
109
  for (const [name, def] of Object.entries(servers)) {
77
110
  if (!def || typeof def !== 'object') { out.errors.push(`${abs}: server "${name}" must be an object`); continue; }
78
- if (!def.command && !def.url) { out.errors.push(`${abs}: server "${name}" needs "command" or "url"`); continue; }
79
- out.servers[name] = { ...def, _source: abs, ...(isProject ? { _project: true } : {}) };
111
+ // The transport may be named explicitly: `type: "http"`, `"sse"`,
112
+ // `"streamable-http"` or `"stdio"`. A `url` with no type is a streamable-HTTP
113
+ // server unless it says otherwise.
114
+ const normalised = normaliseServerDef(def);
115
+ if (!normalised.command && !normalised.url) {
116
+ out.errors.push(`${abs}: server "${name}" needs "command" or "url"`);
117
+ continue;
118
+ }
119
+ out.servers[name] = { ...normalised, _source: abs, ...(isProject ? { _project: true } : {}) };
80
120
  }
81
121
  }
82
122
  return out;
83
123
  }
84
124
 
125
+ // The transport a server definition names, normalised to one of three words.
126
+ //
127
+ // "http" and "streamable-http" are the same thing (the newer transport). "sse" is the
128
+ // older one: the client opens a GET stream and POSTs its messages to a separate
129
+ // endpoint the server hands back. A definition with a `url` and no `type` is
130
+ // streamable-HTTP, which is what every current client writes.
131
+ export function transportOf(def) {
132
+ const t = String((def && (def.type || def.transport)) || '').toLowerCase();
133
+ if (t === 'sse' || t === 'sse-server') return 'sse';
134
+ if (t === 'stdio' || t === 'command') return 'stdio';
135
+ if (t === 'http' || t === 'streamable-http' || t === 'streamablehttp') return 'http';
136
+ return def && def.url ? 'http' : 'stdio';
137
+ }
138
+
139
+ // A server definition with its transport and its arguments in the shape the code uses.
140
+ export function normaliseServerDef(def) {
141
+ const out = { ...def };
142
+ out._transport = transportOf(def);
143
+ // An `args` that is a STRING is what some clients write for a single argument;
144
+ // the spawn needs an array.
145
+ if (typeof out.args === 'string') out.args = [out.args];
146
+ if (!Array.isArray(out.args)) out.args = out.args ? [out.args] : [];
147
+ // `env` may be a list of "KEY=value" strings in some tools' configs.
148
+ if (Array.isArray(out.env)) {
149
+ const env = {};
150
+ for (const entry of out.env) {
151
+ const i = String(entry).indexOf('=');
152
+ if (i > 0) env[String(entry).slice(0, i)] = String(entry).slice(i + 1);
153
+ }
154
+ out.env = env;
155
+ }
156
+ return out;
157
+ }
158
+
85
159
  // ---- JSON-RPC framing -------------------------------------------------------
86
160
 
87
161
  // A stdio connection: newline-delimited JSON-RPC over the child's stdin/stdout.
@@ -197,6 +271,130 @@ export function createHttpTransport(url, headers) {
197
271
  };
198
272
  }
199
273
 
274
+ // The OLD SSE transport, still in use by tools that predate streamable-HTTP.
275
+ //
276
+ // The shape is different and the difference is the whole point of supporting it:
277
+ // the client opens a GET and the server keeps THAT connection open, streaming
278
+ // server-initiated messages down it. The first event carries the endpoint the client
279
+ // must POST its own messages to — a separate URL, usually ending in /messages/.
280
+ //
281
+ // So a request here is: POST to the endpoint, and WAIT for the reply to come back
282
+ // down the open stream. The reply is matched by its JSON-RPC id, which is why the
283
+ // stream keeps a map of pending requests instead of answering the POST directly.
284
+ export function createSseTransport(url, headers) {
285
+ return {
286
+ kind: 'sse',
287
+ url,
288
+ headers: { accept: 'text/event-stream', ...(headers || {}) },
289
+ endpoint: null,
290
+ pending: new Map(),
291
+ nextId: 1,
292
+ controller: null,
293
+ };
294
+ }
295
+
296
+ // Open the event stream and learn the endpoint the messages go to.
297
+ //
298
+ // The endpoint event is the first thing on the wire, and everything else waits for
299
+ // it. A server that never sends one leaves the transport unable to send anything,
300
+ // which is why the open has a timeout: without it a broken server hangs the
301
+ // handshake for the whole connect budget.
302
+ export async function openSseStream(state, timeoutMs = 10_000) {
303
+ const ctrl = new AbortController();
304
+ state.controller = ctrl;
305
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
306
+ let settled = false;
307
+ const endpointReady = new Promise((resolve, reject) => {
308
+ state._resolveEndpoint = resolve;
309
+ state._rejectEndpoint = reject;
310
+ });
311
+ try {
312
+ const res = await fetch(state.url, {
313
+ method: 'GET',
314
+ headers: state.headers,
315
+ signal: ctrl.signal,
316
+ });
317
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
318
+ const reader = res.body.getReader();
319
+ const decoder = new TextDecoder();
320
+ let buf = '';
321
+ (async () => {
322
+ try {
323
+ for (;;) {
324
+ const { done, value } = await reader.read();
325
+ if (done) break;
326
+ buf += decoder.decode(value, { stream: true });
327
+ let i;
328
+ while ((i = buf.indexOf('\n\n')) >= 0) {
329
+ const frame = buf.slice(0, i);
330
+ buf = buf.slice(i + 2);
331
+ handleSseFrame(state, frame);
332
+ }
333
+ }
334
+ } catch { /* the stream ended */ }
335
+ })();
336
+ await endpointReady;
337
+ settled = true;
338
+ return state.endpoint;
339
+ } finally {
340
+ clearTimeout(timer);
341
+ if (!settled) {
342
+ try { ctrl.abort(); } catch { /* already gone */ }
343
+ throw new Error('the SSE server did not announce an endpoint');
344
+ }
345
+ }
346
+ }
347
+
348
+ // One SSE frame: either the endpoint announcement or a JSON-RPC reply.
349
+ function handleSseFrame(state, frame) {
350
+ let event = 'message';
351
+ let data = '';
352
+ for (const line of String(frame).split('\n')) {
353
+ if (line.startsWith('event:')) event = line.slice(6).trim();
354
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
355
+ }
356
+ if (event === 'endpoint') {
357
+ // The endpoint is often a RELATIVE path; the server's own URL is the base.
358
+ const ep = String(data || '');
359
+ state.endpoint = /^https?:\/\//i.test(ep) ? ep : new URL(ep, state.url).toString();
360
+ if (state._resolveEndpoint) { state._resolveEndpoint(state.endpoint); state._resolveEndpoint = null; }
361
+ return;
362
+ }
363
+ if (!data) return;
364
+ let msg;
365
+ try { msg = JSON.parse(data); } catch { return; }
366
+ if (msg && msg.id != null && state.pending.has(msg.id)) {
367
+ const p = state.pending.get(msg.id);
368
+ state.pending.delete(msg.id);
369
+ clearTimeout(p.timer);
370
+ if (msg.error) p.reject(new Error(msg.error.message || JSON.stringify(msg.error)));
371
+ else p.resolve(msg.result);
372
+ }
373
+ }
374
+
375
+ // Send one message on the SSE transport and wait for its reply on the open stream.
376
+ export async function sseRequest(state, method, params, timeoutMs = 30_000) {
377
+ if (!state.endpoint) await openSseStream(state);
378
+ const id = state.nextId++;
379
+ const body = JSON.stringify({ jsonrpc: '2.0', id, method, params: params || {} });
380
+ const post = fetch(state.endpoint, {
381
+ method: 'POST',
382
+ headers: { 'content-type': 'application/json', ...state.headers },
383
+ body,
384
+ }).then((res) => {
385
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
386
+ });
387
+ const reply = new Promise((resolve, reject) => {
388
+ const timer = setTimeout(() => {
389
+ state.pending.delete(id);
390
+ reject(new Error(`the SSE server did not answer "${method}" within ${timeoutMs}ms`));
391
+ }, timeoutMs);
392
+ state.pending.set(id, { resolve, reject, timer });
393
+ });
394
+ await post;
395
+ return reply;
396
+ }
397
+
200
398
  export async function httpRequest(state, method, params, timeoutMs = 30_000) {
201
399
  const id = state.nextId++;
202
400
  const ctrl = new AbortController();
@@ -251,28 +449,76 @@ export async function connectServer(name, def, opts = {}) {
251
449
  // handshake while keeping a dead server's cost to single-digit seconds.
252
450
  const timeoutMs = opts.timeoutMs || CONNECT_TIMEOUT_MS;
253
451
  let transport;
254
- const isHttp = !!def.url;
452
+ // The transport comes from the definition, not from "does it have a url".
453
+ //
454
+ // A definition may say `type: "sse"`, and an SSE server is reached by a URL just
455
+ // like a streamable-HTTP one — so the presence of a url says nothing about which
456
+ // protocol is spoken. `transportOf` reads the type, defaulting to streamable-HTTP
457
+ // for a url and stdio for a command, which is what every current client writes.
458
+ const kind = transportOf(def);
459
+ const isHttp = kind === 'http';
460
+ const isSse = kind === 'sse';
255
461
  try {
256
- transport = isHttp
257
- ? createHttpTransport(def.url, def.headers)
258
- : createStdioTransport(def.command, def.args, { env: def.env, cwd: def.cwd });
462
+ transport = isSse
463
+ ? createSseTransport(def.url, def.headers)
464
+ : isHttp
465
+ ? createHttpTransport(def.url, def.headers)
466
+ : createStdioTransport(def.command, def.args, { env: def.env, cwd: def.cwd });
259
467
  } catch (e) {
260
468
  return { ok: false, tools: [], error: `could not start "${name}": ${e.message}` };
261
469
  }
262
470
 
263
- const send = (method, params) => (isHttp
264
- ? httpRequest(transport, method, params, timeoutMs)
265
- : request(transport, method, params, timeoutMs));
471
+ const send = (method, params) => (isSse
472
+ ? sseRequest(transport, method, params, timeoutMs)
473
+ : isHttp
474
+ ? httpRequest(transport, method, params, timeoutMs)
475
+ : request(transport, method, params, timeoutMs));
266
476
 
267
477
  try {
268
- const init = await send('initialize', {
269
- protocolVersion: PROTOCOL_VERSION,
270
- capabilities: { tools: {} },
271
- clientInfo: CLIENT_INFO,
272
- });
478
+ // THE VERSION IS NEGOTIATED, NOT ASSUMED.
479
+ //
480
+ // A server that speaks only a revision this client did not offer rejects the
481
+ // handshake, and the client used to have no way to try the next one — one version
482
+ // was hard-coded. Each attempt is a fresh handshake, because a server that has
483
+ // already answered `initialize` will not answer it again on the same connection.
484
+ let init = null;
485
+ let lastError = null;
486
+ for (const version of SUPPORTED_PROTOCOL_VERSIONS) {
487
+ try {
488
+ init = await send('initialize', {
489
+ protocolVersion: version,
490
+ capabilities: { tools: {} },
491
+ clientInfo: CLIENT_INFO,
492
+ });
493
+ break;
494
+ } catch (e) {
495
+ lastError = e;
496
+ // A transport that has died cannot be retried on; only a REJECTED VERSION
497
+ // is worth another attempt, and that needs a fresh connection.
498
+ if (!/protocol|version|unsupported/i.test(String((e && e.message) || e))) break;
499
+ }
500
+ }
501
+ if (!init) throw lastError || new Error('the server did not answer initialize');
273
502
  if (!isHttp) notify(transport, 'notifications/initialized', {});
274
- const list = await send('tools/list', {});
275
- const tools = Array.isArray(list && list.tools) ? list.tools : [];
503
+ // THE TOOL LIST IS PAGINATED, AND THE CURSOR IS FOLLOWED.
504
+ //
505
+ // A server with more tools than it wants to send at once returns a page and a
506
+ // `nextCursor`; the client is expected to ask for the rest. Not following it meant
507
+ // that only the first page was ever registered — the bug Claude Code and Cursor both
508
+ // have. The loop stops on a missing cursor, an empty page, or a cursor that
509
+ // repeats, so a server that always returns one cannot spin forever.
510
+ const tools = [];
511
+ const seenCursors = new Set();
512
+ let cursor = undefined;
513
+ for (let page = 0; page < 50; page++) {
514
+ const list = await send('tools/list', cursor ? { cursor } : {});
515
+ const batch = Array.isArray(list && list.tools) ? list.tools : [];
516
+ tools.push(...batch);
517
+ const next = list && list.nextCursor;
518
+ if (!next || seenCursors.has(next)) break;
519
+ seenCursors.add(next);
520
+ cursor = next;
521
+ }
276
522
  return { ok: true, tools, error: null, serverInfo: (init && init.serverInfo) || {}, transport, isHttp };
277
523
  } catch (e) {
278
524
  try { if (!isHttp) transport.child.kill(); } catch { /* already gone */ }
@@ -281,11 +527,15 @@ export async function connectServer(name, def, opts = {}) {
281
527
  }
282
528
 
283
529
  // Call one tool on a connected server. Returns { ok, text, error, raw }.
284
- export async function callTool(transport, isHttp, toolName, args, timeoutMs = 60_000) {
530
+ export async function callTool(transport, toolName, args, timeoutMs = 60_000) {
531
+ const kind = (transport && transport.kind) || 'stdio';
285
532
  try {
286
- const result = isHttp
287
- ? await httpRequest(transport, 'tools/call', { name: toolName, arguments: args || {} }, timeoutMs)
288
- : await request(transport, 'tools/call', { name: toolName, arguments: args || {} }, timeoutMs);
533
+ const params = { name: toolName, arguments: args || {} };
534
+ const result = kind === 'sse'
535
+ ? await sseRequest(transport, 'tools/call', params, timeoutMs)
536
+ : kind === 'http'
537
+ ? await httpRequest(transport, 'tools/call', params, timeoutMs)
538
+ : await request(transport, 'tools/call', params, timeoutMs);
289
539
  return { ok: true, text: flattenContent(result), error: null, raw: result };
290
540
  } catch (e) {
291
541
  return { ok: false, text: '', error: e.message, raw: null };
@@ -320,7 +570,7 @@ export function mcpToolName(server, tool) {
320
570
 
321
571
  // Convert an MCP tool definition into an hncode tool spec whose execute() calls
322
572
  // back into the server.
323
- export function toHncodeSpec(server, tool, transport, isHttp) {
573
+ export function toHncodeSpec(server, tool, transport) {
324
574
  return {
325
575
  name: mcpToolName(server, tool.name),
326
576
  description: (tool.description || `MCP tool ${tool.name} from ${server}.`).slice(0, 4000),
@@ -329,7 +579,7 @@ export function toHncodeSpec(server, tool, transport, isHttp) {
329
579
  : { type: 'object', properties: {} },
330
580
  _mcp: { server, tool: tool.name },
331
581
  async execute(args) {
332
- const r = await callTool(transport, isHttp, tool.name, args);
582
+ const r = await callTool(transport, tool.name, args);
333
583
  if (!r.ok) return `Error calling ${server}/${tool.name}: ${r.error}`;
334
584
  // MCP signals tool-level failure with isError, not a JSON-RPC error.
335
585
  if (r.raw && r.raw.isError) return `Error from ${server}/${tool.name}: ${r.text}`;
@@ -362,8 +612,8 @@ export async function connectAll(config, registerTool, opts = {}) {
362
612
  if (!approved) {
363
613
  return { name, ok: false, toolCount: 0, skipped: true,
364
614
  error: 'not approved — the project-scope server was not started' };
365
- }
366
615
  }
616
+ }
367
617
  const conn = await connectServer(name, def, opts);
368
618
  if (!conn.ok) return { name, ok: false, toolCount: 0, error: conn.error, serverInfo: {} };
369
619
  let registered = 0;
@@ -371,13 +621,13 @@ export async function connectAll(config, registerTool, opts = {}) {
371
621
  for (const tool of conn.tools) {
372
622
  if (!tool || !tool.name) continue;
373
623
  try {
374
- registerTool(toHncodeSpec(name, tool, conn.transport, conn.isHttp));
624
+ registerTool(toHncodeSpec(name, tool, conn.transport));
375
625
  registered++;
376
626
  } catch (e) {
377
627
  // A name clash with a built-in is reported, not fatal: keep the rest.
378
628
  err = err || `tool "${tool.name}": ${e.message}`;
379
- }
380
629
  }
630
+ }
381
631
  return { name, ok: true, toolCount: registered, error: err, serverInfo: conn.serverInfo, transport: conn.transport, isHttp: conn.isHttp };
382
632
  }));
383
633
  const toolCount = results.reduce((n, r) => n + (r.toolCount || 0), 0);
@@ -24,6 +24,8 @@
24
24
  //
25
25
  // Pure and read-only: it measures, it never trims, loads or rewrites anything.
26
26
 
27
+ import { uiText } from './i18n.js';
28
+
27
29
  /** Content larger than this is counted separately — a single 16 KB block is the shape of
28
30
  * a runaway, while 16 KB spread evenly is nothing. */
29
31
  const LARGE_BLOB_BYTES = 16 * 1024;
@@ -184,25 +186,26 @@ export function renderMemoryProfile(p, opts = {}) {
184
186
  return ` ${v.toFixed(1)}%`.padStart(7);
185
187
  };
186
188
  const row = (label, b, n, share = true) => {
187
- lines.push(` ${label.padEnd(18)} ${mb(b).padStart(9)} MB${n != null ? ` x${n}` : ''}${share ? pct(b) : ''}`);
189
+ const text = uiText(label);
190
+ lines.push(` ${text.padEnd(18)} ${mb(b).padStart(9)} MB${n != null ? ` x${n}` : ''}${share ? pct(b) : ''}`);
188
191
  };
189
192
 
190
- lines.push(`Memory profile — ${mb(total)} MB across the forms a session holds`);
193
+ lines.push(uiText(`Memory profile — ${mb(total)} MB across the forms a session holds`));
191
194
  lines.push('');
192
- lines.push(' content (session.messages)');
195
+ lines.push(uiText(' content (session.messages)'));
193
196
  row('text', p.messages.text.bytes, p.messages.text.count);
194
- row('tool results', p.messages.toolResults.bytes, p.messages.toolResults.count);
195
- row('tool arguments', p.messages.toolArgs.bytes, p.messages.toolArgs.count);
197
+ row(uiText('tool results'), p.messages.toolResults.bytes, p.messages.toolResults.count);
198
+ row(uiText('tool arguments'), p.messages.toolArgs.bytes, p.messages.toolArgs.count);
196
199
  if (p.messages.images.bytes) row('images', p.messages.images.bytes, p.messages.images.count);
197
200
 
198
201
  if (p.transcript.count) {
199
202
  lines.push('');
200
- lines.push(' transcript (display-only, on disk)');
201
- row('all rows', p.transcript.bytes, p.transcript.count);
203
+ lines.push(uiText(' transcript (display-only, on disk)'));
204
+ row(uiText('all rows'), p.transcript.bytes, p.transcript.count);
202
205
  if (p.transcript.largeBytes) {
203
- lines.push(` of which >=16 KB: ${mb(p.transcript.largeBytes).padStart(9)} MB`);
206
+ lines.push(` ${uiText('of which >=16 KB:')} ${mb(p.transcript.largeBytes).padStart(9)} MB`);
204
207
  }
205
- lines.push(` largest row: ${mb(p.transcript.maxRowBytes).padStart(9)} MB`);
208
+ lines.push(` ${uiText('largest row:').padEnd(17)}${mb(p.transcript.maxRowBytes).padStart(9)} MB`);
206
209
  if (opts.verbose) {
207
210
  for (const [role, b] of [...p.transcript.byRole].sort((a, c) => c[1].bytes - a[1].bytes)) {
208
211
  row(` ${role}`, b.bytes, b.count);
@@ -211,22 +214,22 @@ export function renderMemoryProfile(p, opts = {}) {
211
214
  }
212
215
 
213
216
  lines.push('');
214
- lines.push(' other copies held at the same time');
215
- row('state.chat (render)', p.chat.bytes, p.chat.count);
217
+ lines.push(uiText(' other copies held at the same time'));
218
+ row(uiText('state.chat (render)'), p.chat.bytes, p.chat.count);
216
219
 
217
220
  lines.push('');
218
- lines.push(' as one JSON document (a different measure of the same data)');
221
+ lines.push(uiText(' as one JSON document (a different measure of the same data)'));
219
222
  // Measured against the CONTENT, not the content-plus-content the base holds, so these
220
223
  // two rows carry no share: they re-measure what the rows above already report.
221
- row('serialised size', p.messages.jsonBytes, null, false);
222
- row('structure + escapes', p.messages.structuralBytes, null, false);
224
+ row(uiText('serialised size'), p.messages.jsonBytes, null, false);
225
+ row(uiText('structure + escapes'), p.messages.structuralBytes, null, false);
223
226
  if (p.messages.structuralBytes > p.messages.contentBytes) {
224
- lines.push(' (structure is larger than the content — that is normal for many short messages)');
227
+ lines.push(uiText(' (structure is larger than the content — that is normal for many short messages)'));
225
228
  }
226
229
 
227
230
  if (opts.verbose && p.messages.argsByTool.size) {
228
231
  lines.push('');
229
- lines.push(' tool arguments by tool');
232
+ lines.push(uiText(' tool arguments by tool'));
230
233
  const rows = [...p.messages.argsByTool].sort((a, b) => b[1].bytes - a[1].bytes);
231
234
  for (const [name, b] of (opts.top ? rows.slice(0, opts.top) : rows)) {
232
235
  row(name, b.bytes, b.count);
@@ -0,0 +1,175 @@
1
+ // A hand-editable map of what a migration archive holds, and where each session came from.
2
+ //
3
+ // WHY A SEPARATE FILE INSIDE THE ARCHIVE
4
+ // --------------------------------------
5
+ // The archive's manifest answers "which bytes, at which offset". It cannot answer the question a person actually has
6
+ // when they move machines: "this session was `/home/me/proj` over there — where is it here?" `hncode restore
7
+ // --workspace <dir>` can only give every session the SAME answer, which is wrong the moment a person worked in more
8
+ // than one directory.
9
+ //
10
+ // so `index.yml` travels as an ordinary entry in the archive. That matters: it can be extracted with the archive, read
11
+ // with a text editor, corrected, and put back — without a tool that understands the format.
12
+ //
13
+ // NO YAML DEPENDENCY. The project has none, and adding one for fifteen lines of output is not a trade worth making. The
14
+ // writer emits a deliberately narrow subset; the reader accepts anything that subset could produce plus the hand edits a
15
+ // person is likely to make (comments, blank lines, quoting either way, a missing section). What it does not understand it
16
+ // skips, and the caller falls back to the manifest instead of failing an import.
17
+
18
+ export const INDEX_ENTRY = 'index.yml';
19
+
20
+ /**
21
+ * Quote a scalar only when YAML would otherwise misread it.
22
+ *
23
+ * A bare `D:\work\proj` is fine; `/home/me/proj` is fine; `""` is an empty string; and something holding `#` or `,` or
24
+ * starting with a dash has to be quoted or the parser takes part of it for a comment or a list marker.
25
+ */
26
+ function yamlScalar(v) {
27
+ const s = String(v == null ? '' : v);
28
+ if (s === '') return '""';
29
+ if (/^(true|false|null|yes|no|on|off|~)$/i.test(s)) return JSON.stringify(s);
30
+ if (/^[-?:,[\]{}#&*!|>'"%@`]/.test(s)) return JSON.stringify(s);
31
+ if (/[:#]\s|\s$/.test(s)) return JSON.stringify(s);
32
+ return s;
33
+ }
34
+
35
+ /**
36
+ * Render `index.yml`.
37
+ *
38
+ * @param {{home?: string, createdAt?: number, mapping?: Array<{from: string, to: string}>,
39
+ * sessions?: Array<{id: string, title?: string, workspace?: string, file: string}>}} data
40
+ * @returns {string}
41
+ */
42
+ export function renderIndex(data) {
43
+ const out = [];
44
+ out.push('# HNCode migration index');
45
+ out.push('#');
46
+ out.push('# WHERE THE SESSIONS CAME FROM, AND WHERE THEY SHOULD LAND.');
47
+ out.push('#');
48
+ out.push('# sessions: one entry per session in the archive. `workspace` is the directory that session was');
49
+ out.push('# opened on, on the machine the archive was made.');
50
+ out.push('# mapping: rewrites applied to a workspace on import. The LONGEST matching prefix wins, so a');
51
+ out.push('# nested rule beats its parent.');
52
+ out.push('#');
53
+ out.push('# Restoring without --index keeps the workspaces as written below. `hncode restore <archive> --index`');
54
+ out.push('# applies `mapping`. Edit either to move a project: /home/me/proj -> D:\\work\\proj');
55
+ out.push('');
56
+ out.push('version: 1');
57
+ out.push('created: ' + yamlScalar(new Date(data.createdAt || Date.now()).toISOString()));
58
+ out.push('source: ' + yamlScalar(data.home || ''));
59
+ out.push('');
60
+ out.push('# Rewrites applied on import, longest `from` first.');
61
+ out.push('mapping:');
62
+ if (data.mapping && data.mapping.length) {
63
+ for (const m of data.mapping) {
64
+ out.push(' - from: ' + yamlScalar(m.from));
65
+ out.push(' to: ' + yamlScalar(m.to));
66
+ }
67
+ } else {
68
+ out.push(' []');
69
+ }
70
+ out.push('');
71
+ const sessions = data.sessions || [];
72
+ out.push('# ' + sessions.length + ' session(s).');
73
+ out.push('sessions:');
74
+ if (sessions.length) {
75
+ for (const s of sessions) {
76
+ out.push(' - id: ' + yamlScalar(s.id));
77
+ out.push(' title: ' + yamlScalar(s.title || ''));
78
+ out.push(' workspace: ' + yamlScalar(s.workspace || ''));
79
+ out.push(' file: ' + yamlScalar(s.file));
80
+ }
81
+ } else {
82
+ out.push(' []');
83
+ }
84
+ out.push('');
85
+ return out.join('\n');
86
+ }
87
+
88
+ /**
89
+ * Parse `index.yml`.
90
+ *
91
+ * Tolerant by design: this file is meant to be edited by hand, so a comment, a trailing space, single quotes instead of
92
+ * double, or a section left out entirely must not break an import.
93
+ *
94
+ * @returns {{mapping: Array<{from: string, to: string}>, sessions: Array<{id, title, workspace, file}>}|null}
95
+ * null when the text holds neither a mapping nor a session.
96
+ */
97
+ export function parseIndex(text) {
98
+ const mapping = [];
99
+ const sessions = [];
100
+ let section = '';
101
+ let cur = null;
102
+
103
+ const unquote = (v) => {
104
+ const s = String(v == null ? '' : v).trim();
105
+ if (!s) return '';
106
+ if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
107
+ if (s.startsWith('"')) { try { return JSON.parse(s); } catch { /* fall through */ } }
108
+ return s.slice(1, -1);
109
+ }
110
+ return s;
111
+ };
112
+
113
+ for (const raw of String(text || '').split(/\r?\n/)) {
114
+ // A `#` outside quotes starts a comment. The subset this reads never puts one inside a value.
115
+ const line = raw.replace(/\s+#.*$/, '');
116
+ const t = line.trim();
117
+ if (!t || t.startsWith('#')) continue;
118
+
119
+ // A TOP-LEVEL KEY IS NOT INDENTED. Testing the trimmed line alone made ` to: /b` look like a section header, which
120
+ // ended the `mapping` block after its first entry and left the parser with nothing.
121
+ const indented = /^\s/.test(line);
122
+ const top = indented ? null : /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(t);
123
+ if (top) {
124
+ const key = top[1];
125
+ section = (key === 'mapping' || key === 'sessions') ? key : '';
126
+ cur = null;
127
+ continue;
128
+ }
129
+ if (!section) continue;
130
+ if (t === '[]') continue;
131
+
132
+ if (t.startsWith('-')) {
133
+ cur = {};
134
+ (section === 'mapping' ? mapping : sessions).push(cur);
135
+ const rest = t.slice(1).trim();
136
+ if (rest) {
137
+ const i = rest.indexOf(':');
138
+ if (i > 0) cur[rest.slice(0, i).trim()] = unquote(rest.slice(i + 1));
139
+ }
140
+ continue;
141
+ }
142
+ if (!cur) continue;
143
+ const i = t.indexOf(':');
144
+ if (i <= 0) continue;
145
+ cur[t.slice(0, i).trim()] = unquote(t.slice(i + 1));
146
+ }
147
+
148
+ if (!mapping.length && !sessions.length) return null;
149
+ return {
150
+ mapping: mapping.filter((m) => m && m.from && m.to).map((m) => ({ from: String(m.from), to: String(m.to) })),
151
+ sessions: sessions.filter((s) => s && s.file).map((s) => ({
152
+ id: s.id || '', title: s.title || '', workspace: s.workspace || '', file: s.file,
153
+ })),
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Apply a mapping to a path, longest `from` first so a nested rule wins over its parent.
159
+ *
160
+ * Separators are normalised for the COMPARISON only — an archive made on Windows and restored on Linux has to match
161
+ * `D:\work` against `D:/work` — and the caller gets its own path back when nothing matches.
162
+ */
163
+ export function mapPath(p, mapping) {
164
+ if (!p || !Array.isArray(mapping) || !mapping.length) return p;
165
+ const norm = (s) => String(s).replace(/\\/g, '/').replace(/\/+$/, '');
166
+ const target = norm(p);
167
+ const sorted = [...mapping].sort((a, b) => norm(b.from).length - norm(a.from).length);
168
+ for (const m of sorted) {
169
+ const from = norm(m.from);
170
+ if (!from) continue;
171
+ if (target === from) return m.to;
172
+ if (target.startsWith(from + '/')) return String(m.to).replace(/\/+$/, '') + target.slice(from.length);
173
+ }
174
+ return p;
175
+ }