@hncode/hncode 0.8.0 → 0.8.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.
@@ -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
+ }
package/src/migrate.js ADDED
@@ -0,0 +1,392 @@
1
+ // Export and import every piece of hncode state a person would want on another machine.
2
+ //
3
+ // WHAT TRAVELS AND WHAT DOES NOT
4
+ // ------------------------------
5
+ // The distinction is not size, it is MEANING. A session or a skill is something the user made; a paint log or a Chromium
6
+ // cache is something this machine produced on their behalf and can produce again. So the list is explicit rather than
7
+ // "everything under ~/.hncode", which would ship 174 MB of paint.log and 16 MB of browser profile.
8
+ //
9
+ // CROSS-MACHINE PATHS
10
+ // -------------------
11
+ // A session records `workspace` as an absolute path, and one saved on another machine points at a directory that does not
12
+ // exist here. The import therefore does not silently keep it: it either keeps the old path (for a machine with the same
13
+ // layout) or maps it onto a directory the user names. `tool-results` is dropped for the same reason — those files are
14
+ // referred to by absolute path from inside session histories, so copying the directory alone would leave every pointer
15
+ // aimed at a path that no longer exists.
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import { execFileSync } from 'node:child_process';
20
+ import { INDEX_ENTRY, renderIndex, parseIndex, mapPath } from './migrate-index.js';
21
+
22
+ /** The root every path here is relative to. `HNCODE_HOME` wins, like everywhere else in the program. */
23
+ // The last four bytes of an archive. Latin-1 rather than UTF-8 so a reader does not have to agree with a decoder about
24
+ // how many bytes a character took — this is a tag, not text.
25
+ export const MARKER = 'HNB1';
26
+
27
+ export function hncodeHome() {
28
+ return process.env.HNCODE_HOME || path.join(process.env.USERPROFILE || process.env.HOME || '.', '.hncode');
29
+ }
30
+
31
+ /**
32
+ * What a migration carries.
33
+ *
34
+ * `dir` entries are copied whole; `file` entries only when they exist. `config*.toml*` is matched by pattern so the
35
+ * rolling backups a user may want to come back to travel with the live file.
36
+ */
37
+ export const PORTABLE = [
38
+ { name: 'config.toml', kind: 'file', what: 'settings, providers, models' },
39
+ { name: 'config.toml.backup', kind: 'file', what: 'previous settings' },
40
+ { name: 'sessions', kind: 'dir', what: 'conversations' },
41
+ { name: 'history.json', kind: 'file', what: 'prompt history' },
42
+ { name: 'history', kind: 'dir', what: 'prompt history, per session' },
43
+ { name: 'MEMORY.md', kind: 'file', what: 'agent memory' },
44
+ { name: 'PERSONAL.md', kind: 'file', what: 'personal preferences' },
45
+ { name: 'mcp.json', kind: 'file', what: 'MCP servers' },
46
+ { name: 'skills', kind: 'dir', what: 'installed skills' },
47
+ { name: 'plugins', kind: 'dir', what: 'installed plugins' },
48
+ { name: 'teams', kind: 'dir', what: 'team rosters' },
49
+ { name: 'file-history', kind: 'dir', what: 'snapshots for /undo' },
50
+ ];
51
+
52
+ /** Entries that are deliberately left behind, with the reason, so a report can say why. */
53
+ export const EXCLUDED = [
54
+ { name: 'browser-profile', why: 'the plugin browser\'s Chromium profile — machine-local, rebuilt on use' },
55
+ { name: 'tool-results', why: 'spilled tool output, addressed by absolute paths from inside the sessions' },
56
+ { name: '*.log', why: 'debug logs (paint.log alone is over 170 MB)' },
57
+ { name: 'teleport', why: 'sessions already exported as standalone files' },
58
+ ];
59
+
60
+ /** Every config backup this machine has, since `/reload` can restore one. */
61
+ function configBackups(home) {
62
+ try {
63
+ return fs.readdirSync(home)
64
+ .filter((f) => /^config\.toml\.(bak.*|backup)$/.test(f))
65
+ .map((f) => ({ name: f, kind: 'file', what: 'settings backup' }));
66
+ } catch { return []; }
67
+ }
68
+
69
+ /** Size of a file or a directory tree, in bytes, without following symlinks. */
70
+ export function sizeOf(p) {
71
+ let total = 0;
72
+ const walk = (q) => {
73
+ let st;
74
+ try { st = fs.lstatSync(q); } catch { return; }
75
+ if (st.isSymbolicLink()) return;
76
+ if (st.isDirectory()) {
77
+ let entries = [];
78
+ try { entries = fs.readdirSync(q); } catch { return; }
79
+ for (const e of entries) walk(path.join(q, e));
80
+ } else {
81
+ total += st.size;
82
+ }
83
+ };
84
+ walk(p);
85
+ return total;
86
+ }
87
+
88
+ /** Human-readable bytes, at the precision a migration report needs. */
89
+ export function fmtBytes(n) {
90
+ const v = Number(n) || 0;
91
+ if (v < 1024) return `${v} B`;
92
+ if (v < 1024 * 1024) return `${(v / 1024).toFixed(0)} KB`;
93
+ if (v < 1024 * 1024 * 1024) return `${(v / 1024 / 1024).toFixed(1)} MB`;
94
+ return `${(v / 1024 / 1024 / 1024).toFixed(2)} GB`;
95
+ }
96
+
97
+ /**
98
+ * What an export WOULD include: one entry per portable item that exists, with its size.
99
+ *
100
+ * Returned rather than printed so a caller can show a summary before writing anything — a 190 MB archive is worth
101
+ * confirming.
102
+ */
103
+ export function planExport(home = hncodeHome()) {
104
+ const items = [];
105
+ const all = [...PORTABLE, ...configBackups(home)];
106
+ const seen = new Set();
107
+ for (const item of all) {
108
+ if (seen.has(item.name)) continue;
109
+ seen.add(item.name);
110
+ const p = path.join(home, item.name);
111
+ let st;
112
+ try { st = fs.lstatSync(p); } catch { continue; }
113
+ if (item.kind === 'dir' && !st.isDirectory()) continue;
114
+ if (item.kind === 'file' && !st.isFile()) continue;
115
+ items.push({ ...item, size: sizeOf(p) });
116
+ }
117
+ return items;
118
+ }
119
+
120
+
121
+ /**
122
+ * Write a migration archive.
123
+ *
124
+ * FORMAT: a one-line JSON manifest followed by a newline, then every file's bytes back to back. No dependency, no
125
+ * compression, and the manifest is readable with `head -1` — which matters when the only thing available on the target
126
+ * machine is the hncode that is not installed yet.
127
+ *
128
+ * {"version":1,"createdAt":...,"home":...,"items":[{name,kind,size}],"files":[{path,size,offset}]}
129
+ * <bytes><bytes><bytes>…
130
+ *
131
+ * `offset` is absolute from the start of the file, so a reader can seek straight to one entry without walking the rest.
132
+ *
133
+ * @param {string} out path to write
134
+ * @param {object} [opts] `home`, `items` (from planExport), `onProgress(done, total, name)`
135
+ * @returns {{path: string, files: number, bytes: number, items: object[]}}
136
+ */
137
+ /**
138
+ * Write a migration archive.
139
+ *
140
+ * FORMAT: the files' bytes back to back, then a JSON manifest, then an 8-byte little-endian length and the marker
141
+ * `HNB1`. The manifest goes LAST on purpose — its offsets are from the start of the file, so writing it first would
142
+ * mean knowing every size before a single byte was copied, and padding the numbers to a guessed width so the header
143
+ * length could not move. Writing it last makes both problems disappear.
144
+ *
145
+ * <file bytes><file bytes>…<manifest json><8-byte length><HNB1>
146
+ *
147
+ * @param {string} out path to write
148
+ * @param {object} [opts] `home`, `items` (from planExport), `onProgress(done, total, name)`
149
+ * @returns {{path: string, files: number, bytes: number, items: object[]}}
150
+ */
151
+ export function writeArchive(out, opts = {}) {
152
+ const home = opts.home || hncodeHome();
153
+ const items = opts.items || planExport(home);
154
+ const files = [];
155
+ const collect = (abs, rel) => {
156
+ let st;
157
+ try { st = fs.lstatSync(abs); } catch { return; }
158
+ if (st.isSymbolicLink()) return;
159
+ if (st.isDirectory()) {
160
+ let entries = [];
161
+ try { entries = fs.readdirSync(abs); } catch { return; }
162
+ for (const e of entries) collect(path.join(abs, e), rel ? rel + '/' + e : e);
163
+ } else if (st.isFile()) {
164
+ files.push({ abs, rel, size: st.size });
165
+ }
166
+ };
167
+ for (const item of items) collect(path.join(home, item.name), item.name);
168
+
169
+ // THE INDEX TRAVELS AS AN ORDINARY ENTRY, so it can be extracted and edited with nothing but a text editor. It is
170
+ // built from the sessions that were just collected rather than from a second walk of the store.
171
+ const sessionIndex = [];
172
+ for (const f of files) {
173
+ const m = /^sessions\/([^/]+)\.json$/.exec(f.rel);
174
+ if (!m) continue;
175
+ let meta = { id: m[1], title: '', workspace: '' };
176
+ try {
177
+ // The file is small enough to read whole here — this is the export, not a frame.
178
+ const s = JSON.parse(fs.readFileSync(f.abs, 'utf8'));
179
+ meta = { id: s.id || m[1], title: s.title || '', workspace: s.workspace || '' };
180
+ } catch { /* a session that will not parse is still listed by id */ }
181
+ sessionIndex.push({ ...meta, file: f.rel });
182
+ }
183
+ const indexBody = Buffer.from(renderIndex({
184
+ home,
185
+ createdAt: opts.createdAt || Date.now(),
186
+ mapping: opts.mapping || [],
187
+ sessions: sessionIndex,
188
+ }), 'utf8');
189
+ files.unshift({ abs: null, rel: INDEX_ENTRY, size: indexBody.length, body: indexBody });
190
+
191
+ const fd = fs.openSync(out, 'w');
192
+ let offset = 0;
193
+ const records = [];
194
+ try {
195
+ const buf = Buffer.allocUnsafe(1024 * 1024);
196
+ for (let i = 0; i < files.length; i++) {
197
+ const f = files[i];
198
+ records.push({ path: f.rel, size: f.size, offset });
199
+ // A GENERATED ENTRY HAS ITS BYTES IN MEMORY. `index.yml` is not on disk to read from, so it is written
200
+ // straight from the buffer the caller handed over; everything else streams from its file.
201
+ if (f.body) {
202
+ fs.writeSync(fd, f.body, 0, f.body.length);
203
+ offset += f.body.length;
204
+ if (typeof opts.onProgress === 'function') opts.onProgress(i + 1, files.length, f.rel);
205
+ continue;
206
+ }
207
+
208
+ const src = fs.openSync(f.abs, 'r');
209
+ try {
210
+ let left = f.size;
211
+ let pos = 0;
212
+ while (left > 0) {
213
+ const n = fs.readSync(src, buf, 0, Math.min(buf.length, left), pos);
214
+ if (n <= 0) break;
215
+ fs.writeSync(fd, buf, 0, n);
216
+ pos += n;
217
+ left -= n;
218
+ offset += n;
219
+ }
220
+ } finally {
221
+ fs.closeSync(src);
222
+ }
223
+ if (typeof opts.onProgress === 'function') opts.onProgress(i + 1, files.length, f.rel);
224
+ }
225
+
226
+ const manifest = Buffer.from(JSON.stringify({
227
+ version: 1,
228
+ createdAt: Date.now(),
229
+ home,
230
+ items: items.map((i) => ({ name: i.name, kind: i.kind, size: i.size })),
231
+ files: records,
232
+ }), 'utf8');
233
+ fs.writeSync(fd, manifest);
234
+ const tail = Buffer.alloc(12);
235
+ tail.writeBigUInt64LE(BigInt(manifest.length), 0);
236
+ tail.write(MARKER, 8, 'latin1');
237
+ fs.writeSync(fd, tail);
238
+ offset += manifest.length + tail.length;
239
+ } finally {
240
+ fs.closeSync(fd);
241
+ }
242
+ return { path: out, files: files.length, bytes: offset, items };
243
+ }
244
+
245
+ /**
246
+ * Read an archive's manifest without extracting anything.
247
+ *
248
+ * Used to SHOW the user what they are about to import, and to refuse a file that is not one of ours before anything is
249
+ * written over their state.
250
+ */
251
+ /**
252
+ * Read an archive's manifest without extracting anything.
253
+ *
254
+ * The manifest is the last thing in the file, immediately before a 12-byte tail holding its length and the marker, so
255
+ * it is found by seeking to the end rather than by scanning.
256
+ */
257
+ export function readArchiveManifest(from) {
258
+ const fd = fs.openSync(from, 'r');
259
+ try {
260
+ const size = fs.fstatSync(fd).size;
261
+ if (size < 12) throw new Error('not a hncode archive: too short');
262
+ const tail = Buffer.alloc(12);
263
+ fs.readSync(fd, tail, 0, 12, size - 12);
264
+ if (tail.subarray(8).toString('latin1') !== MARKER) throw new Error('not a hncode archive: the end marker is missing');
265
+ const len = Number(tail.readBigUInt64LE(0));
266
+ if (!Number.isFinite(len) || len <= 0 || len > size - 12) throw new Error('not a hncode archive: the manifest length is wrong');
267
+ const body = Buffer.alloc(len);
268
+ fs.readSync(fd, body, 0, len, size - 12 - len);
269
+ let m;
270
+ try { m = JSON.parse(body.toString('utf8')); } catch { throw new Error('not a hncode archive: the manifest is not JSON'); }
271
+ if (!m || m.version !== 1 || !Array.isArray(m.files)) throw new Error('not a hncode archive: unsupported version');
272
+ return { manifest: m };
273
+ } finally {
274
+ fs.closeSync(fd);
275
+ }
276
+ }
277
+
278
+
279
+ /**
280
+ * Extract an archive into a hncode home.
281
+ *
282
+ * SAFE BY DEFAULT. Nothing is overwritten unless `overwrite` is set: an existing session with the same id is kept and
283
+ * reported, because importing is often "bring my other machine's history in beside this one", not "replace it".
284
+ *
285
+ * PATH REWRITING. A session stores its `workspace` as an absolute path. Imported from another machine that path almost
286
+ * certainly does not exist here, and leaving it means every session opens onto a directory that is not there. Two
287
+ * choices, both explicit:
288
+ *
289
+ * `workspace: "/some/dir"` every imported session is pointed at that directory
290
+ * omitted the original paths are kept (right for a machine with the same layout)
291
+ *
292
+ * Only `workspace` is rewritten. Everything else a session holds — messages, tool arguments, todos — is conversation,
293
+ * and rewriting paths inside it would corrupt what the model was told.
294
+ *
295
+ * @param {string} from archive path
296
+ * @param {object} [opts] `home`, `overwrite`, `workspace`, `dryRun`, `onProgress(done, total, path)`
297
+ * @returns {{written: number, skipped: number, bytes: number, sessionsRewritten: number, errors: string[]}}
298
+ */
299
+ export function readArchive(from, opts = {}) {
300
+ const home = opts.home || hncodeHome();
301
+ const { manifest } = readArchiveManifest(from);
302
+ const result = {
303
+ written: 0, skipped: 0, bytes: 0, sessionsRewritten: 0, errors: [],
304
+ indexFound: false, mapped: 0,
305
+ };
306
+ // `--workspace` still wins when given: it is the blunt "put everything here" the user typed on this command line.
307
+ const rewriteTo = typeof opts.workspace === 'string' && opts.workspace.trim() ? path.resolve(opts.workspace.trim()) : null;
308
+
309
+ const fd = fs.openSync(from, 'r');
310
+ const readEntry = (f) => {
311
+ const buf = Buffer.allocUnsafe(Math.max(1, f.size));
312
+ let read = 0;
313
+ while (read < f.size) {
314
+ const n = fs.readSync(fd, buf, read, f.size - read, f.offset + read);
315
+ if (n <= 0) break;
316
+ read += n;
317
+ }
318
+ return buf.subarray(0, read);
319
+ };
320
+ try {
321
+ // THE INDEX IS READ FIRST, because it decides where every session lands. It travels as an ordinary entry, so a
322
+ // person can extract it, correct the paths and put it back — or hand `--index <file>` an edited copy from outside.
323
+ let index = null;
324
+ if (opts.index !== false) {
325
+ const entry = manifest.files.find((f) => f.path === INDEX_ENTRY);
326
+ if (entry) {
327
+ try {
328
+ index = parseIndex(readEntry(entry).toString('utf8'));
329
+ result.indexFound = !!index;
330
+ } catch { /* a damaged index must not stop the import */ }
331
+ }
332
+ if (typeof opts.indexFile === 'string' && opts.indexFile.trim()) {
333
+ try { index = parseIndex(fs.readFileSync(path.resolve(opts.indexFile.trim()), 'utf8')); result.indexFound = !!index; }
334
+ catch (e) { result.errors.push(`could not read --index file: ${(e && e.message) || e}`); }
335
+ }
336
+ }
337
+ const mapping = (index && index.mapping) || [];
338
+
339
+ for (const f of manifest.files) {
340
+ // A path in the manifest is data from a file, so it is checked before it is joined to anything: an entry holding
341
+ // `..` would otherwise write outside the hncode home.
342
+ const rel = String(f.path || '');
343
+ if (!rel || rel.startsWith('/') || rel.includes('..') || /^[A-Za-z]:/.test(rel)) {
344
+ result.errors.push(`refused an unsafe path: ${rel}`);
345
+ continue;
346
+ }
347
+ const dest = path.join(home, rel);
348
+ const isSession = /(^|\/)sessions\/[^/]+\.json$/.test(rel);
349
+ if (!opts.overwrite && fs.existsSync(dest)) { result.skipped++; continue; }
350
+ if (opts.dryRun) {
351
+ result.written++;
352
+ result.bytes += f.size;
353
+ if (isSession && (rewriteTo || mapping.length)) result.sessionsRewritten++;
354
+ continue;
355
+ }
356
+
357
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
358
+ const buf = readEntry(f);
359
+ // A SESSION IS REWRITTEN, NOT COPIED VERBATIM — its `workspace` is an absolute path from another machine.
360
+ if (isSession && (rewriteTo || mapping.length)) {
361
+ try {
362
+ const s = JSON.parse(buf.toString('utf8'));
363
+ if (s && typeof s === 'object') {
364
+ if (rewriteTo) {
365
+ s.workspace = rewriteTo;
366
+ if (s.cwd) s.cwd = rewriteTo;
367
+ } else {
368
+ const before = s.workspace;
369
+ if (s.workspace) s.workspace = mapPath(s.workspace, mapping);
370
+ if (s.cwd) s.cwd = mapPath(s.cwd, mapping);
371
+ if (s.workspace && s.workspace !== before) result.mapped++;
372
+ }
373
+ const out = Buffer.from(JSON.stringify(s), 'utf8');
374
+ fs.writeFileSync(dest, out);
375
+ result.written++;
376
+ result.bytes += out.length;
377
+ result.sessionsRewritten++;
378
+ if (typeof opts.onProgress === 'function') opts.onProgress(result.written, manifest.files.length, rel);
379
+ continue;
380
+ }
381
+ } catch { /* not JSON we can rewrite; fall through and copy it as-is */ }
382
+ }
383
+ fs.writeFileSync(dest, buf);
384
+ result.written++;
385
+ result.bytes += buf.length;
386
+ if (typeof opts.onProgress === 'function') opts.onProgress(result.written, manifest.files.length, rel);
387
+ }
388
+ } finally {
389
+ fs.closeSync(fd);
390
+ }
391
+ return result;
392
+ }
package/src/panels.js CHANGED
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { C } from './colors.js';
7
7
  import { col, fitAnsi, wrapWords } from './text.js';
8
+ import { uiText } from './i18n.js';
8
9
 
9
10
  // ---- title strip ----------------------------------------------------------
10
11
 
@@ -167,7 +168,7 @@ export function renderTodoPanel(state, w, hoverTop, dragTop) {
167
168
  const out = [];
168
169
  const ruleColor = dragTop ? C.scrollThumbActive : (hoverTop ? C.hover : C.border);
169
170
  out.push(col('─'.repeat(w), ruleColor));
170
- out.push(col(' Todo', C.cyan + C.bold));
171
+ out.push(col(uiText(' Todo'), C.cyan + C.bold));
171
172
  const want = todoRowCount(state);
172
173
  // CREATION ORDER, ALWAYS. Which rows fit is still the panel's decision — it takes the first `want` in order.
173
174
  const rows = todos.slice(0, want);
@@ -177,10 +178,10 @@ export function renderTodoPanel(state, w, hoverTop, dragTop) {
177
178
  const counts = { done: 0, in_progress: 0, pending: 0 };
178
179
  for (const t of todos) if (!rows.includes(t)) counts[t.status] = (counts[t.status] || 0) + 1;
179
180
  const dist = [['done', 'done'], ['in_progress', 'in progress'], ['pending', 'pending']]
180
- .filter(([k]) => counts[k] > 0).map(([k, label]) => `${counts[k]} ${label}`).join(', ');
181
+ .filter(([k]) => counts[k] > 0).map(([k, label]) => `${counts[k]} ${uiText(label)}`).join(', ');
181
182
  // The hint appears exactly when rows are hidden — which is exactly when Ctrl+T is useful — so this is where the key
182
183
  // has to be discoverable.
183
- out.push(col(` … +${hidden} more${dist ? ` (${dist})` : ''} · ctrl+t to expand · drag the top rule to resize`, C.gray));
184
+ out.push(col(` ${uiText(`… +${hidden} more`)}${dist ? ` (${dist})` : ''} ${uiText('· ctrl+t to expand · drag the top rule to resize')}`, C.gray));
184
185
  }
185
186
  return out;
186
187
  }
@@ -231,7 +232,7 @@ export function renderQueuePanel(state, w, hoverTop, dragTop) {
231
232
  const out = [];
232
233
  const ruleColor = dragTop ? C.scrollThumbActive : (hoverTop ? C.hover : C.border);
233
234
  out.push(col('─'.repeat(w), ruleColor));
234
- out.push(col(' Queue', C.cyan + C.bold));
235
+ out.push(col(uiText(' Queue'), C.cyan + C.bold));
235
236
 
236
237
  const want = queueRowCount(state);
237
238
  const rows = queued.slice(0, want);
@@ -243,12 +244,13 @@ export function renderQueuePanel(state, w, hoverTop, dragTop) {
243
244
 
244
245
  const hidden = queued.length - rows.length;
245
246
  if (hidden > 0) {
247
+ const more = uiText(`… +${hidden} more`);
246
248
  const hint = state.running
247
- ? `… +${hidden} more · ↑ to edit · ctrl-s to steer immediately · drag top rule to resize`
248
- : `… +${hidden} more · ↑ to edit · will send now · drag top rule to resize`;
249
+ ? `${more} · ${uiText('↑ to edit · ctrl-s to steer immediately')} · ${uiText('drag top rule to resize')}`
250
+ : `${more} · ${uiText('↑ to edit · will send now')} · ${uiText('drag top rule to resize')}`;
249
251
  out.push(col(' ' + hint, C.gray));
250
252
  } else {
251
- const hint = state.running ? '↑ to edit · ctrl-s to steer immediately' : '↑ to edit · will send now';
253
+ const hint = state.running ? uiText('↑ to edit · ctrl-s to steer immediately') : uiText('↑ to edit · will send now');
252
254
  out.push(col(' ' + hint, C.gray));
253
255
  }
254
256
 
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { C } from './colors.js';
7
7
  import { col, fitAnsi, visualCol, wrapWords } from './text.js';
8
+ import { uiText } from './i18n.js';
8
9
  import { renderMdText } from './markdown.js';
9
10
 
10
11
  /**
@@ -24,7 +25,7 @@ export function planRows(msg, width) {
24
25
  const full = (l, r) => bar(l + '─'.repeat(inner) + r);
25
26
  // Header: the card's single column is captioned "Plan".
26
27
  out.push({ text: full('╭', '╮'), ind: '', raw: true });
27
- out.push({ text: bar('│') + fitAnsi(col(' Plan', C.cyan + C.bold), inner) + bar('│'), ind: '', raw: true });
28
+ out.push({ text: bar('│') + fitAnsi(col(' ' + uiText('Plan'), C.cyan + C.bold), inner) + bar('│'), ind: '', raw: true });
28
29
  out.push({ text: bar('├' + '─'.repeat(inner) + '┤'), ind: '', raw: true });
29
30
  const lines = String(msg.text || '').replace(/\r\n/g, '\n').split('\n');
30
31
  while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
@@ -76,7 +77,7 @@ export function bgTaskRows(msg, width, expanded) {
76
77
  }
77
78
  if (lines.length > MAX) {
78
79
  // Only reachable while COLLAPSED: expanded, `MAX` is the whole list and this cannot fire.
79
- out.push({ text: col(`… ${lines.length - MAX} more lines, ctrl+o to expand`, C.gray), ind: indent, raw: true });
80
+ out.push({ text: col(uiText(`… ${lines.length - MAX} more lines, ctrl+o to expand`), C.gray), ind: indent, raw: true });
80
81
  }
81
82
  }
82
83
  return out;