@hncode/hncode 0.8.1 → 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,317 @@
1
+ // Recovering a session file that a broken save left unparseable.
2
+ //
3
+ // WHAT BROKE
4
+ // ----------
5
+ // `stringifySession` spliced the message array into a placeholder with
6
+ // `String.replace(pattern, messagesJson)`. A replacement STRING is not literal text:
7
+ // `$&`, `` $` ``, `$'` and `$$` are expansions. A conversation that merely mentioned
8
+ // `sed s/x/$&/g` therefore corrupted its own file on save, and because the write is
9
+ // tmp-then-rename with no verification, the damaged bytes replaced the good ones. The
10
+ // next load failed, `latestSession` fell back to the metadata head, and the next save
11
+ // wrote `messages: []` over the history.
12
+ //
13
+ // Only two of those expansions break the STRUCTURE, and both insert whole copies of text
14
+ // that is already present:
15
+ //
16
+ // `$&` -> the matched placeholder, quotes and all
17
+ // `` $` `` -> a copy of everything before the match, which is the metadata head
18
+ //
19
+ // `$'` inserts the `}` that follows the match and `$$` inserts a `$`: both damage the
20
+ // conversation TEXT, not the JSON around it, so the file still loads.
21
+ //
22
+ // A file saved once can be undone exactly. A file saved repeatedly has the copies
23
+ // interleaved with conversation text that was streaming at the time, so the boundaries
24
+ // are gone and the offset is unrecoverable — the salvager then reads each surviving
25
+ // message OBJECT out of the array and keeps every one that still parses.
26
+ //
27
+ // Nothing here guesses at text. A message whose bytes no longer form a valid object is
28
+ // dropped and counted, never repaired by inference.
29
+
30
+ import fs from 'node:fs';
31
+
32
+ // The literal placeholder as it appears inside a JSON string, quotes included. It can
33
+ // only ever have come from a `$&` expansion: no message the user writes contains a NUL,
34
+ // and JSON.stringify escapes it, so this exact sequence is the marker itself.
35
+ const PLACE_QUOTED = '"\\u0000HNCODE_PLACEHOLDER\\u0000"';
36
+
37
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
38
+
39
+ /** Index of the `[` that opens the array value of `"messages"`, or -1. */
40
+ function messagesArrayStart(text) {
41
+ const key = text.indexOf('"messages"');
42
+ if (key < 0) return -1;
43
+ return text.indexOf('[', key);
44
+ }
45
+
46
+ /**
47
+ * The metadata block, parsed on its own.
48
+ *
49
+ * Everything before the messages array is written by `JSON.stringify` alone — it is the
50
+ * SEARCH side of the broken replace, never the replacement — so it is intact even in a
51
+ * file whose array is shredded. Closing it with an empty array yields the whole session
52
+ * minus its messages: title, workspace, todos, usage, shell history, all of it.
53
+ */
54
+ function parseHead(text) {
55
+ const open = messagesArrayStart(text);
56
+ if (open < 0) return null;
57
+ const head = text.slice(0, open);
58
+ for (const tail of ['[]}', '[]'] ) {
59
+ try {
60
+ const obj = JSON.parse(head + tail);
61
+ if (isObj(obj)) return obj;
62
+ } catch { /* try the next closing form */ }
63
+ }
64
+ return null;
65
+ }
66
+
67
+ // End index (exclusive) of the JSON value starting at `at`, or -1 when it is incomplete.
68
+ // Strings are skipped whole, so braces inside a message body cannot be miscounted.
69
+ function valueEnd(text, at) {
70
+ const c = text[at];
71
+ if (c !== '{' && c !== '[') return -1;
72
+ let depth = 0;
73
+ for (let i = at; i < text.length; i++) {
74
+ const ch = text[i];
75
+ if (ch === '"') {
76
+ let j = i + 1;
77
+ while (j < text.length) {
78
+ if (text[j] === '\\') { j += 2; continue; }
79
+ if (text[j] === '"') break;
80
+ j++;
81
+ }
82
+ if (j >= text.length) return -1;
83
+ i = j;
84
+ continue;
85
+ }
86
+ if (ch === '{' || ch === '[') depth++;
87
+ else if (ch === '}' || ch === ']') {
88
+ depth--;
89
+ if (depth === 0) return i + 1;
90
+ }
91
+ }
92
+ return -1;
93
+ }
94
+
95
+ /**
96
+ * Read every message object that still parses, out of a damaged `messages` array.
97
+ *
98
+ * A damaged array is a series of JSON objects with rubbish BETWEEN them, so the scan looks
99
+ * for the next `{"role":` and tries to parse an object there. When that object runs into an
100
+ * inserted copy of the head its own strings still close correctly, so a failed parse means
101
+ * the walk steps INSIDE it instead of skipping past the whole thing — which is what keeps
102
+ * the messages that follow a damaged one.
103
+ */
104
+ export function salvageMessages(text) {
105
+ const open = messagesArrayStart(text);
106
+ if (open < 0) return { messages: [], dropped: 0 };
107
+ const end = text.indexOf('"transcript"', open);
108
+ const limit = end > 0 ? end : text.length;
109
+ const messages = [];
110
+ let dropped = 0;
111
+ let i = open + 1;
112
+ while (i < limit) {
113
+ const at = text.indexOf('{"role":', i);
114
+ if (at < 0 || at >= limit) break;
115
+ const stop = valueEnd(text, at);
116
+ let ok = null;
117
+ if (stop > 0) {
118
+ try { ok = JSON.parse(text.slice(at, stop)); } catch { ok = null; }
119
+ }
120
+ if (isObj(ok) && typeof ok.role === 'string') {
121
+ messages.push(ok);
122
+ i = stop;
123
+ continue;
124
+ }
125
+ dropped++;
126
+ // The object at `at` is damaged. Its damage may span several messages, so resume the
127
+ // search just after its opening key rather than after its (misleading) end.
128
+ i = at + '{"role":'.length;
129
+ }
130
+ return { messages, dropped };
131
+ }
132
+
133
+ /**
134
+ * Make a recovered list safe to SEND, not merely parsed.
135
+ *
136
+ * A salvage can drop the assistant message that ISSUED a tool call while keeping its
137
+ * result, or the other way round. Every provider rejects both: a `tool` row with no call,
138
+ * and a call with no result. The pair rule is the protocol's own — results follow their
139
+ * call immediately — so an assistant keeps only the calls that a following `tool` run
140
+ * answers, and a `tool` row is kept only when the call it answers was kept.
141
+ *
142
+ * Nothing else is touched. Returns `{ messages, orphaned }`.
143
+ */
144
+ export function sanitizeToolPairs(messages) {
145
+ const out = [];
146
+ let orphaned = 0;
147
+ let i = 0;
148
+ while (i < messages.length) {
149
+ const m = messages[i];
150
+ if (!isObj(m)) { i++; continue; }
151
+ if (m.role === 'assistant') {
152
+ const calls = Array.isArray(m.toolCalls) ? m.toolCalls.filter((tc) => tc && tc.id) : [];
153
+ let j = i + 1;
154
+ const results = [];
155
+ while (j < messages.length && isObj(messages[j]) && messages[j].role === 'tool') {
156
+ results.push(messages[j]);
157
+ j++;
158
+ }
159
+ const answered = new Set(results.map((r) => r.toolCallId));
160
+ const keptCalls = calls.filter((tc) => answered.has(tc.id));
161
+ const hasText = typeof m.content === 'string' && m.content.trim();
162
+ if (hasText || keptCalls.length) {
163
+ const copy = { ...m };
164
+ if (calls.length) {
165
+ if (keptCalls.length) copy.toolCalls = keptCalls;
166
+ else delete copy.toolCalls;
167
+ orphaned += calls.length - keptCalls.length;
168
+ }
169
+ out.push(copy);
170
+ const keepIds = new Set(keptCalls.map((tc) => tc.id));
171
+ for (const r of results) {
172
+ if (keepIds.has(r.toolCallId)) out.push(r);
173
+ else orphaned++;
174
+ }
175
+ } else {
176
+ orphaned += 1 + calls.length + results.length;
177
+ }
178
+ i = j;
179
+ continue;
180
+ }
181
+ if (m.role === 'tool') { orphaned++; i++; continue; }
182
+ out.push(m);
183
+ i++;
184
+ }
185
+ return { messages: out, orphaned };
186
+ }
187
+
188
+ /**
189
+ * Delete the copies `` $` `` injected, keeping the first occurrence because the first one
190
+ * IS the file's real head.
191
+ *
192
+ * A saved-once file becomes valid JSON again. A file saved repeatedly usually will not —
193
+ * the copies were spliced around text that was streaming at the time — so the caller
194
+ * falls back to `salvageMessages`.
195
+ */
196
+ function stripInjectedHeadCopies(text) {
197
+ const open = messagesArrayStart(text);
198
+ if (open < 0) return text;
199
+ const head = text.slice(0, open);
200
+ if (head.length < 64) return text;
201
+ let out = text;
202
+ let at = out.indexOf(head, head.length);
203
+ if (at < 0) return out;
204
+ while (at >= 0) {
205
+ out = out.slice(0, at) + out.slice(at + head.length);
206
+ at = out.indexOf(head, head.length);
207
+ }
208
+ return out;
209
+ }
210
+
211
+ /**
212
+ * Salvage the display-only `transcript` array, which follows `messages` in the file.
213
+ *
214
+ * The real key is the LAST unescaped `"transcript":` in the file — an inserted head copy
215
+ * can carry its own, earlier one. The array is written after the messages, so on a file
216
+ * damaged mid-history it is normally intact, but it can be cut too, so every candidate is
217
+ * walked with the same object salvage and the first one that yields rows wins.
218
+ */
219
+ function salvageTranscript(text) {
220
+ const key = '"transcript":';
221
+ let at = text.lastIndexOf(key);
222
+ while (at >= 0) {
223
+ const open = text.indexOf('[', at);
224
+ if (open < 0) return [];
225
+ const got = salvageArrayAt(text, open);
226
+ if (got.length) return got;
227
+ at = text.lastIndexOf(key, at - 1);
228
+ }
229
+ return [];
230
+ }
231
+
232
+ /** Every object in the array starting at `open` that still parses. */
233
+ function salvageArrayAt(text, open) {
234
+ const out = [];
235
+ let i = open + 1;
236
+ while (i < text.length) {
237
+ const start = text.indexOf('{', i);
238
+ if (start < 0) break;
239
+ const stop = valueEnd(text, start);
240
+ if (stop < 0) break;
241
+ try { out.push(JSON.parse(text.slice(start, stop))); } catch { /* skip the damaged one */ }
242
+ i = stop;
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /**
248
+ * Recover a session from a file that does not parse.
249
+ *
250
+ * Returns `{ session, report }`, or null when nothing of value could be read back. The
251
+ * report says which route worked and how many messages were lost, so the caller can tell
252
+ * the user the truth instead of presenting a silently shortened history.
253
+ */
254
+ export function recoverSessionText(text) {
255
+ if (typeof text !== 'string' || !text) return null;
256
+ const head = parseHead(text);
257
+ if (!head) return null;
258
+
259
+ // Route 1, exact: remove what the expansions inserted and reparse.
260
+ let exact = null;
261
+ try {
262
+ const cleaned = stripInjectedHeadCopies(text.split(PLACE_QUOTED).join(''));
263
+ exact = JSON.parse(cleaned);
264
+ } catch { exact = null; }
265
+ if (isObj(exact) && Array.isArray(exact.messages)) {
266
+ const clean = sanitizeToolPairs(exact.messages);
267
+ return {
268
+ session: { ...exact, messages: clean.messages },
269
+ report: { route: 'exact', kept: clean.messages.length, dropped: 0, orphaned: clean.orphaned },
270
+ };
271
+ }
272
+
273
+ // Route 2, salvage: keep every message object that still parses, then make the result
274
+ // safe to send — a salvaged list can hold half of a tool exchange, which every provider
275
+ // rejects with a 400 the moment the session is resumed.
276
+ const salvaged = salvageMessages(text.split(PLACE_QUOTED).join(''));
277
+ const clean = sanitizeToolPairs(salvaged.messages);
278
+ if (!clean.messages.length) return null;
279
+ const session = { ...head, messages: clean.messages };
280
+ // The on-screen rows live after `messages`, so the parsed head does not carry them.
281
+ // Losing them would make a resumed session show less than it had.
282
+ const transcript = salvageTranscript(text);
283
+ if (transcript.length) session.transcript = transcript;
284
+ return {
285
+ session,
286
+ report: {
287
+ route: 'salvage',
288
+ kept: clean.messages.length,
289
+ dropped: salvaged.dropped,
290
+ orphaned: clean.orphaned,
291
+ },
292
+ };
293
+ }
294
+
295
+ /**
296
+ * Recover a session file in place, keeping the damaged original as `<file>.bak`.
297
+ *
298
+ * The backup is written BEFORE the repair, so a wrong recovery is never the only copy
299
+ * left on disk.
300
+ */
301
+ export function recoverSessionFile(file, knownText) {
302
+ let text = typeof knownText === 'string' ? knownText : null;
303
+ if (text === null) {
304
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return null; }
305
+ }
306
+ const got = recoverSessionText(text);
307
+ if (!got) return null;
308
+ try {
309
+ fs.writeFileSync(`${file}.bak`, text, 'utf8');
310
+ const tmp = `${file}.${process.pid}.recover.tmp`;
311
+ fs.writeFileSync(tmp, JSON.stringify(got.session), 'utf8');
312
+ fs.renameSync(tmp, file);
313
+ } catch (e) {
314
+ return { ...got, wrote: false, error: e && e.message ? e.message : String(e) };
315
+ }
316
+ return { ...got, wrote: true, backup: `${file}.bak` };
317
+ }
package/src/session.js CHANGED
@@ -6,6 +6,8 @@ import os from 'node:os';
6
6
  import path from 'node:path';
7
7
  import fs from 'node:fs';
8
8
  import crypto from 'node:crypto';
9
+ import { recoverSessionFile } from './session-recover.js';
10
+ import { appendLog } from './log-file.js';
9
11
 
10
12
  const DEFAULT_DIR = () => path.join(os.homedir(), '.hncode', 'sessions');
11
13
  function dir(custom) { return custom || process.env.HNCODE_SESSIONS_DIR || DEFAULT_DIR(); }
@@ -36,18 +38,15 @@ export function invalidateSessionCache(storeDir) {
36
38
  // if external state is suspected. Our own save/delete already invalidate.
37
39
 
38
40
  // FIX: single place for the error log so save/load failures are never silent.
41
+ //
42
+ // Rotation-bounded: this file is written by every failed save, so an unattended session
43
+ // that keeps failing one would otherwise grow without limit — and the failure it records
44
+ // is the one thing the user needs to read, so it must not bury itself.
39
45
  function errorLogFile() {
40
46
  return path.join(os.homedir(), '.hncode', 'session-errors.log');
41
47
  }
42
48
  function logSessionError(op, detail) {
43
- try {
44
- fs.mkdirSync(path.dirname(errorLogFile()), { recursive: true });
45
- fs.appendFileSync(
46
- errorLogFile(),
47
- `[${new Date().toISOString()}] ${op}: ${detail}\n`,
48
- 'utf8',
49
- );
50
- } catch { /* logging must never throw */ }
49
+ appendLog(errorLogFile(), `[${new Date().toISOString()}] ${op}: ${detail}\n`);
51
50
  }
52
51
 
53
52
  export function newId() {
@@ -113,6 +112,10 @@ function serializableSession(session) {
113
112
  for (const k of Object.keys(session)) {
114
113
  if (k in out) continue;
115
114
  if (k === 'messages' || k === 'transcript') continue;
115
+ // `_`-prefixed keys are runtime markers, never session data. `_unrecoverable` says the
116
+ // file could not be read back; persisting it would make the NEXT load treat a healthy
117
+ // session as damaged.
118
+ if (k.startsWith('_')) continue;
116
119
  out[k] = session[k];
117
120
  }
118
121
  out.messages = Array.isArray(session.messages) ? session.messages : [];
@@ -120,7 +123,104 @@ function serializableSession(session) {
120
123
  return out;
121
124
  }
122
125
 
123
- export function saveSession(session, storeDir) {
126
+ // ---- saving -----------------------------------------------------------------
127
+ //
128
+ // SAVING IS ON THE PER-TURN PATH, SO IT MUST NOT BLOCK THE FRAME.
129
+ //
130
+ // `saveSession` used to do the whole thing synchronously: `JSON.stringify` of the entire history, then `writeFileSync`,
131
+ // then `renameSync`. On a 2.5 MB session that is a visible stall between the user pressing Enter and anything appearing
132
+ // on screen — and it is paid TWICE per turn, once for the user message and once at each step boundary
133
+ // (`persistTurnProgress`). A slow disk multiplies all of it.
134
+ //
135
+ // The write is now scheduled, and calls that land in the same tick coalesce into ONE write: the session object is the
136
+ // same reference every time, so the last call is the one worth writing.
137
+ //
138
+ // ORDERING IS KEPT. `serialize` runs INSIDE the scheduled callback, not at call time, so the bytes written always
139
+ // describe the session as it is when the write happens — never an older snapshot queued behind a newer one.
140
+ //
141
+ // A CALLER THAT MUST HAVE THE BYTES ON DISK uses `saveSessionNow` (used on exit).
142
+ let pendingSave = null; // { session, storeDir }
143
+ let pendingScheduled = false;
144
+ let saveTimer = null;
145
+
146
+ /**
147
+ * How long a queued save may wait.
148
+ *
149
+ * A turn saves once per step boundary plus once at the end, a few seconds apart — long enough that `setImmediate` never
150
+ * coalesced any of them. Three seconds is short enough that a crash loses at most the last step, and long enough that a
151
+ * burst of steps becomes one write.
152
+ */
153
+ const SAVE_DELAY_MS = 3000;
154
+
155
+ // Declared before its first use: `writeSessionSync` records a failure, and a `let` further down the file would
156
+ // put it in the temporal dead zone.
157
+ let saveFailure = null;
158
+
159
+ // ---- incremental serialisation ------------------------------------------------
160
+ //
161
+ // A SAVE USED TO RE-SERIALISE EVERY MESSAGE, WHICH IS THE WHOLE HISTORY EVERY TIME.
162
+ //
163
+ // Measured on the real session: 19.8ms of JSON.stringify per save, 43ms including the write, and a turn saves several
164
+ // times. Deferring it only moved the stall to a later frame — during streaming, which is the worst moment for one.
165
+ //
166
+ // A turn appends a few messages and leaves the rest untouched, so each message's JSON is worth keeping. `WeakMap` on
167
+ // the message object is the right home for it: the entry dies with the message, and a message that is REPLACED (a
168
+ // compaction rebuilds the array, /undo swaps objects) simply misses. A message that is MUTATED IN PLACE is the one case
169
+ // a WeakMap cannot see — that is what `bumpMessage` is for, and the call sites that edit an existing message use it.
170
+ //
171
+ // Measured: 15.97ms cold for the whole array, 0.14ms once the cache is warm. That is the difference between a stall the
172
+ // user can see and one they cannot.
173
+ const messageJson = new WeakMap();
174
+
175
+ /** JSON for one message, cached on the object. */
176
+ function jsonOf(m) {
177
+ let j = messageJson.get(m);
178
+ if (j === undefined) { j = JSON.stringify(m); messageJson.set(m, j); }
179
+ return j;
180
+ }
181
+
182
+ /**
183
+ * Forget a message's cached JSON. Call after editing one IN PLACE.
184
+ *
185
+ * A rename of the field itself would be a compile error; this cannot be, so the discipline is: anything that writes to
186
+ * a message that may already have been saved calls this. Missing one means that edit is not persisted until the message
187
+ * object is replaced — not corruption, but a stale field on the next resume.
188
+ */
189
+ export function bumpMessage(m) {
190
+ if (m && typeof m === 'object') messageJson.delete(m);
191
+ }
192
+
193
+ /**
194
+ * `JSON.stringify(session)` without re-serialising messages that have not changed.
195
+ *
196
+ * The outer object is small (a dozen scalars), so it is rebuilt every time; only `messages` — and a `transcript` array,
197
+ * when there is one — come from the per-message cache. The result is byte-identical to one `JSON.stringify` call, which
198
+ * is what the reader on the other side expects.
199
+ */
200
+ function stringifySession(session) {
201
+ const obj = serializableSession(session);
202
+ const messages = obj.messages;
203
+ // The rest of the object is tiny, so it is serialised normally with a placeholder standing in for the arrays.
204
+ const PLACE = '\u0000HNCODE_PLACEHOLDER\u0000';
205
+ const shallow = { ...obj, messages: PLACE };
206
+ if (Array.isArray(obj.transcript)) shallow.transcript = PLACE;
207
+ const text = JSON.stringify(shallow);
208
+ // A REPLACEMENT STRING IS NOT LITERAL. `String.replace` expands `$&`, `` $` ``, `$'` and
209
+ // `$$` inside it, so a message that merely MENTIONED `sed s/x/$&/g` spliced a copy of the
210
+ // session's own metadata head into its own JSON — every save corrupted the file, the file
211
+ // would not parse, and the next save wrote an empty history over it. Returning the value
212
+ // from a function is the only form that is not expanded.
213
+ const messagesJson = '[' + messages.map((m) => (m && typeof m === 'object' ? jsonOf(m) : JSON.stringify(m))).join(',') + ']';
214
+ let out = text.replace(JSON.stringify(PLACE), () => messagesJson);
215
+ if (Array.isArray(obj.transcript)) {
216
+ const tr = obj.transcript;
217
+ const trJson = '[' + tr.map((m) => (m && typeof m === 'object' ? jsonOf(m) : JSON.stringify(m))).join(',') + ']';
218
+ out = out.replace(JSON.stringify(PLACE), () => trJson);
219
+ }
220
+ return out;
221
+ }
222
+
223
+ function writeSessionSync(session, storeDir) {
124
224
  if (!session || !session.id) return session;
125
225
  // Keep the live object's updatedAt in sync for callers that read it back.
126
226
  session.updatedAt = Date.now();
@@ -133,8 +233,8 @@ export function saveSession(session, storeDir) {
133
233
  // Compact JSON, no indentation. `null, 2` made the file ~30% larger for a
134
234
  // human who never reads it (the reader is JSON.parse), and the pretty-printer
135
235
  // itself costs real time on a large transcript — measured ~22ms for 5.7MB, all
136
- // of it spent inserting whitespace. Saving is on the per-turn path.
137
- const json = JSON.stringify(serializableSession(session));
236
+ // of it spent inserting whitespace.
237
+ const json = stringifySession(session);
138
238
  fs.writeFileSync(tmp, json, 'utf8');
139
239
  // Atomic replace. If this throws (EXDEV etc.) the temp is cleaned up below.
140
240
  fs.renameSync(tmp, target);
@@ -158,9 +258,79 @@ export function saveSession(session, storeDir) {
158
258
  return session;
159
259
  }
160
260
 
261
+ /**
262
+ * Queue a save for the next event-loop tick, coalescing with any other call that lands before then.
263
+ *
264
+ * THIS IS THE ONE THE TUI USES. `saveSession` stays synchronous because its contract is "the file is on disk when
265
+ * this returns", and several callers depend on that — the store-integrity tests among them. On the per-turn path that
266
+ * contract is what costs a visible stall: a 1.3 MB session measured 38 ms of `JSON.stringify` + `writeFileSync`
267
+ * between Enter and the first frame, paid twice a turn, on a slow disk much worse.
268
+ *
269
+ * The session object is the same reference every time, so the last call is the one worth writing. `serialize` runs
270
+ * inside the scheduled callback, never at call time, so the bytes written always describe the session as it is when
271
+ * the write happens.
272
+ */
273
+ export function saveSessionSoon(session, storeDir) {
274
+ if (!session || !session.id) return session;
275
+ // Update the timestamp NOW so the object a caller reads back is already stamped — the same
276
+ // guarantee the synchronous version gave.
277
+ session.updatedAt = Date.now();
278
+ pendingSave = { session, storeDir };
279
+ // A SHORT DELAY, NOT THE NEXT TICK.
280
+ //
281
+ // `setImmediate` coalesced calls made in one tick, which is not what a turn looks like: a turn's saves are spread
282
+ // across seconds (one per step boundary, then the turn end), so every one of them ran a full `JSON.stringify` plus
283
+ // write on the main thread — 17-38 ms each on a real session, and each one is a frame the user sees stop.
284
+ //
285
+ // Nothing reads a session file while the program is running: `loadSession` is called at startup and from `/sessions`,
286
+ // both by the same process that already holds the live object. So the file only has to be CURRENT ENOUGH for a crash,
287
+ // and a few seconds of coalescing costs at most the last couple of steps of a session that died — against a stall the
288
+ // user pays on every single turn.
289
+ //
290
+ // `flushSaves` (exit) and `saveSession` (callers that need the bytes now) still write immediately.
291
+ if (!pendingScheduled) {
292
+ pendingScheduled = true;
293
+ saveTimer = setTimeout(() => {
294
+ saveTimer = null;
295
+ pendingScheduled = false;
296
+ const job = pendingSave;
297
+ pendingSave = null;
298
+ if (job) writeSessionSync(job.session, job.storeDir);
299
+ }, SAVE_DELAY_MS);
300
+ // The timer must not hold the process open by itself.
301
+ if (saveTimer.unref) saveTimer.unref();
302
+ }
303
+ return session;
304
+ }
305
+
306
+ /** Write any queued save NOW and wait for it. For exit paths, where there is no next tick. */
307
+ export function flushSaves() {
308
+ const job = pendingSave;
309
+ pendingSave = null;
310
+ pendingScheduled = false;
311
+ // The timer would fire into an empty queue anyway; clearing it keeps the process from lingering for its sake.
312
+ if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; }
313
+ if (job) writeSessionSync(job.session, job.storeDir);
314
+ }
315
+
316
+ /**
317
+ * Save the session, synchronously. The file is on disk when this returns.
318
+ *
319
+ * Kept as the default because that is its documented contract and callers rely on it — reading the file straight
320
+ * back, listing sessions right after a rename, and asserting on a write failure all need the bytes to be there. The
321
+ * per-turn path uses `saveSessionSoon` instead; see it for why that matters on a large session.
322
+ */
323
+ export function saveSession(session, storeDir) {
324
+ return writeSessionSync(session, storeDir);
325
+ }
326
+
327
+ /** Save synchronously. Only for callers that cannot wait for the next tick (exit). */
328
+ export function saveSessionNow(session, storeDir) {
329
+ return writeSessionSync(session, storeDir);
330
+ }
331
+
161
332
  // The most recent save failure, or null. Set once per failure so a caller can report it
162
333
  // (the TUI shows a warning) without this module reaching into the UI.
163
- let saveFailure = null;
164
334
 
165
335
  /** The last save failure `{ at, id, detail }`, or null when saving has been clean. */
166
336
  export function lastSaveFailure() { return saveFailure; }
@@ -180,6 +350,19 @@ export function loadSession(id, storeDir) {
180
350
  try {
181
351
  return JSON.parse(text);
182
352
  } catch (e) {
353
+ // A file that no longer parses is RECOVERED, not written off. An older hncode wrote
354
+ // session files through a `String.replace`, and a message that happened to contain
355
+ // `$&` or `` $` `` spliced a copy of the file's own metadata into it — which then
356
+ // failed to parse here, fell back to the metadata head in `latestSession`, and was
357
+ // overwritten with an empty history by the next save. See session-recover.js.
358
+ const fixed = recoverSessionFile(file, text);
359
+ if (fixed && fixed.session) {
360
+ logSessionError('recover', `${id}: ${e.message} -> ${fixed.report.route}, `
361
+ + `${fixed.report.kept} kept, ${fixed.report.dropped} dropped`
362
+ + (fixed.wrote ? `, original kept as ${fixed.backup}` : ', file NOT rewritten'));
363
+ cacheFor(storeDir, false)?.delete(file);
364
+ return fixed.session;
365
+ }
183
366
  // FIX: a corrupt file is NOT the same as a missing session. Log it so the
184
367
  // user can find the damaged file instead of silently "losing" the session.
185
368
  logSessionError('parse', `${id}: ${e.message} (file: ${file})`);
@@ -216,7 +399,14 @@ export function latestSession(cwd, storeDir, opts = {}) {
216
399
  if (loaded) return loaded;
217
400
  // If the full load failed (corrupt), fall back to the metadata we already have
218
401
  // so the caller still gets an id/title/workspace instead of null.
219
- return pick.meta;
402
+ //
403
+ // It is a LAST RESORT, not a session: it carries no `messages`, and the TUI's next save
404
+ // would write that emptiness to disk. Marked so the caller can refuse the resume instead
405
+ // — three real conversations were lost this way, each one an apparently healthy session
406
+ // with 700 rounds and no history.
407
+ return pick.meta && typeof pick.meta === 'object'
408
+ ? { ...pick.meta, messages: [], _unrecoverable: true }
409
+ : pick.meta;
220
410
  }
221
411
 
222
412
  // Enumerate the session directory, reading each file's metadata head ONCE per
@@ -23,6 +23,7 @@
23
23
 
24
24
  import { C } from './colors.js';
25
25
  import { visualWidth } from './term.js';
26
+ import { uiText } from './i18n.js';
26
27
 
27
28
  const ESC = '\x1b';
28
29
  function visWidth(s) { return visualWidth(String(s).replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')); }
@@ -43,7 +44,10 @@ const PHASE = {
43
44
  failed: { label: 'Failed.', color: C.red },
44
45
  cancelled: { label: 'Cancelled.', color: C.gray },
45
46
  };
46
- export function phaseInfo(phase) { return PHASE[phase] || PHASE.working; }
47
+ export function phaseInfo(phase) {
48
+ const p = PHASE[phase] || PHASE.working;
49
+ return { ...p, label: uiText(p.label) };
50
+ }
47
51
 
48
52
  const BAR_EMPTY = '-';
49
53
  const BAR_FULL = '#';
@@ -15,6 +15,7 @@
15
15
  import { C } from './colors.js';
16
16
  import { visualWidth } from './term.js';
17
17
  import { STATUS_LABEL } from './agent-task.js';
18
+ import { uiText } from './i18n.js';
18
19
 
19
20
  const ELLIPSIS = '\u2026';
20
21
  const ESC = '\x1b';
@@ -127,11 +128,11 @@ export function renderTasksBrowser(state, cols, rows) {
127
128
  const visible = visibleTasks(state.tasks, state.filter);
128
129
  const counts = countByStatus(visible);
129
130
 
130
- const segs = [C.cyan + C.bold + ' TASK BROWSER ' + C.reset, C.gray + ' filter=' + (state.filter === 'all' ? 'ALL' : 'ACTIVE') + ' ' + C.reset];
131
- if (counts.running) segs.push(C.green + ' ' + counts.running + ' running ' + C.reset);
132
- if (counts.completed) segs.push(C.gray + ' ' + counts.completed + ' completed ' + C.reset);
133
- if (counts.failed) segs.push(C.red + ' ' + counts.failed + ' interrupted ' + C.reset);
134
- segs.push(C.gray + ' ' + visible.length + ' total ' + C.reset);
131
+ const segs = [C.cyan + C.bold + uiText(' TASK BROWSER ') + C.reset, C.gray + ' filter=' + uiText(state.filter === 'all' ? 'ALL' : 'ACTIVE') + ' ' + C.reset];
132
+ if (counts.running) segs.push(C.green + ' ' + counts.running + uiText(' running ') + C.reset);
133
+ if (counts.completed) segs.push(C.gray + ' ' + counts.completed + uiText(' completed ') + C.reset);
134
+ if (counts.failed) segs.push(C.red + ' ' + counts.failed + uiText(' interrupted ') + C.reset);
135
+ segs.push(C.gray + ' ' + visible.length + uiText(' total ') + C.reset);
135
136
  const header = fitExactly(segs.join(''), cols);
136
137
 
137
138
  const key = (s) => C.cyan + C.bold + s + C.reset;
@@ -191,7 +192,7 @@ export function renderTasksBrowser(state, cols, rows) {
191
192
  const listInnerW = listW - 2;
192
193
  let listLines;
193
194
  if (!visible.length) {
194
- listLines = [C.gray + (state.filter === 'active' ? 'No active tasks. Tab = show all.' : 'No background tasks in this session.') + C.reset];
195
+ listLines = [C.gray + uiText(state.filter === 'active' ? 'No active tasks. Tab = show all.' : 'No background tasks in this session.') + C.reset];
195
196
  } else {
196
197
  listLines = visible.map((t, i) => {
197
198
  const selected = i === state.selectedIndex;
@@ -206,7 +207,7 @@ export function renderTasksBrowser(state, cols, rows) {
206
207
  const idCol = t.kind === 'agent' ? C.green : t.kind === 'question' ? C.orange : C.blue;
207
208
  const idText = selected ? idCol + C.bold + t.taskId + C.reset : idCol + t.taskId + C.reset;
208
209
  const pad = ' '.repeat(Math.max(0, 20 - visWidth(t.taskId)));
209
- const badge = statusColorToken(t.status) + (STATUS_LABEL[t.status] || t.status) + C.reset;
210
+ const badge = statusColorToken(t.status) + uiText(STATUS_LABEL[t.status] || t.status) + C.reset;
210
211
  const prefix = lead + ptr + idText + pad + ' ' + badge;
211
212
  const budget = Math.max(0, listInnerW - visWidth(prefix) - 1);
212
213
  if (budget < 4) return fitExactly(prefix, listInnerW);
@@ -243,7 +244,7 @@ export function renderTasksBrowser(state, cols, rows) {
243
244
  const val = (s) => C.white + String(s) + C.reset;
244
245
  detailLines.push(label('Task ID:') + val(task.taskId));
245
246
  detailLines.push(label('Kind:') + val(task.kind));
246
- detailLines.push(label('Status:') + statusColorToken(task.status) + (STATUS_LABEL[task.status] || task.status) + C.reset);
247
+ detailLines.push(label(uiText('Status:')) + statusColorToken(task.status) + uiText(STATUS_LABEL[task.status] || task.status) + C.reset);
247
248
  detailLines.push(label('Description:') + val(singleLine(task.description) || '-'));
248
249
  if (task.kind === 'process') {
249
250
  if (task.command && task.command !== task.description) detailLines.push(label('Command:') + val(singleLine(task.command)));