@clagentic/console 1.5.0 → 1.6.0-beta.1

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,436 @@
1
+ // memory-limits.js — daemon.json advanced-settings override for systemd memory limits
2
+ // and MemoryHigh watermark detection (lr-de07).
3
+ //
4
+ // DESIGN: The shipped unit file (deploy/clagentic-console.service) carries
5
+ // percentage-based defaults (MemoryHigh=70%, MemoryMax=85%) that auto-scale when
6
+ // RAM is added. This module handles OPTIONAL operator overrides only: when
7
+ // config.memoryMax / config.memoryHigh are absent, the shipped defaults win and
8
+ // nothing here changes any behavior.
9
+ //
10
+ // Override reach: a systemd drop-in written to
11
+ // /etc/systemd/system/clagentic-console.service.d/memory-overrides.conf
12
+ // overrides only the MemoryMax and MemoryHigh [Service] lines. All other unit
13
+ // settings remain exactly as shipped.
14
+
15
+ 'use strict';
16
+
17
+ var fs = require('fs');
18
+ var path = require('path');
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Constants
22
+ // ---------------------------------------------------------------------------
23
+
24
+ var DROP_IN_DIR = '/etc/systemd/system/clagentic-console.service.d';
25
+ var DROP_IN_FILE = path.join(DROP_IN_DIR, 'memory-overrides.conf');
26
+
27
+ // Accepted units for absolute memory values.
28
+ // Systemd accepts K, M, G, T (case-insensitive) and bare bytes.
29
+ var ABS_PATTERN = /^(\d+(?:\.\d+)?)\s*([KMGT]?)B?$/i;
30
+ var PCT_PATTERN = /^(\d+(?:\.\d+)?)\s*%$/;
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // Validation
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Parse and validate a memory limit value accepted by systemd MemoryMax/MemoryHigh.
38
+ *
39
+ * Accepts:
40
+ * - Percentage string: '70%', '85%' (0 < value <= 100)
41
+ * - Absolute with suffix: '6G', '512M', '2T', '1024K', '8192'
42
+ *
43
+ * Returns { ok: true, value: <normalized-string> } on success, where the
44
+ * normalized value is the canonical string to write into the drop-in.
45
+ * Returns { ok: false, error: <string> } on failure.
46
+ *
47
+ * @param {string} raw
48
+ * @returns {{ ok: boolean, value?: string, error?: string }}
49
+ */
50
+ function parseMemoryLimit(raw) {
51
+ if (typeof raw !== 'string' || !raw.trim()) {
52
+ return { ok: false, error: 'memory limit must be a non-empty string' };
53
+ }
54
+ var s = raw.trim();
55
+
56
+ // Percentage
57
+ var pctMatch = s.match(PCT_PATTERN);
58
+ if (pctMatch) {
59
+ var pct = parseFloat(pctMatch[1]);
60
+ if (isNaN(pct) || pct <= 0 || pct > 100) {
61
+ return { ok: false, error: 'percentage must be between 0 (exclusive) and 100 (inclusive), got: ' + raw };
62
+ }
63
+ // Systemd requires integer percentages in unit files; reject fractional.
64
+ if (pct !== Math.floor(pct)) {
65
+ return { ok: false, error: 'percentage must be a whole number, got: ' + raw };
66
+ }
67
+ return { ok: true, value: Math.round(pct) + '%' };
68
+ }
69
+
70
+ // Absolute value with optional suffix
71
+ var absMatch = s.match(ABS_PATTERN);
72
+ if (absMatch) {
73
+ var num = parseFloat(absMatch[1]);
74
+ var suffix = (absMatch[2] || '').toUpperCase();
75
+ if (isNaN(num) || num <= 0) {
76
+ return { ok: false, error: 'absolute memory value must be positive, got: ' + raw };
77
+ }
78
+ // Reject fractional bytes (no suffix) — ambiguous.
79
+ if (!suffix && num !== Math.floor(num)) {
80
+ return { ok: false, error: 'bare byte count must be a whole number, got: ' + raw };
81
+ }
82
+ // Normalize: integer + suffix, e.g. '6G', '512M'
83
+ var normalized = (Number.isInteger(num) ? num : num) + suffix;
84
+ return { ok: true, value: normalized };
85
+ }
86
+
87
+ return { ok: false, error: 'unrecognized memory limit format (expected NNN%, NG, NM, NK, or bare bytes): ' + raw };
88
+ }
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // Drop-in rendering
92
+ // ---------------------------------------------------------------------------
93
+
94
+ /**
95
+ * Render the content of the systemd drop-in file for memory overrides.
96
+ *
97
+ * Only MemoryHigh and/or MemoryMax are emitted — one or both depending on
98
+ * which overrides are present. If neither is set, returns null (no drop-in
99
+ * should be written).
100
+ *
101
+ * The drop-in first resets each directive to empty (clears the shipped default)
102
+ * then sets the operator-supplied value, per systemd drop-in semantics.
103
+ *
104
+ * @param {{ memoryHigh?: string, memoryMax?: string }} opts
105
+ * @returns {string|null}
106
+ */
107
+ function renderDropIn(opts) {
108
+ var lines = ['# Generated by Clagentic: Console (lr-de07). Do not edit manually.',
109
+ '# Remove this file and run systemctl daemon-reload to restore shipped defaults.',
110
+ '[Service]'];
111
+ var hasAny = false;
112
+
113
+ if (opts.memoryHigh) {
114
+ var hRes = parseMemoryLimit(opts.memoryHigh);
115
+ if (!hRes.ok) throw new Error('memoryHigh: ' + hRes.error);
116
+ // Reset then set (systemd drop-in semantics: empty value clears inherited).
117
+ lines.push('MemoryHigh=');
118
+ lines.push('MemoryHigh=' + hRes.value);
119
+ hasAny = true;
120
+ }
121
+
122
+ if (opts.memoryMax) {
123
+ var mRes = parseMemoryLimit(opts.memoryMax);
124
+ if (!mRes.ok) throw new Error('memoryMax: ' + mRes.error);
125
+ lines.push('MemoryMax=');
126
+ lines.push('MemoryMax=' + mRes.value);
127
+ hasAny = true;
128
+ }
129
+
130
+ if (!hasAny) return null;
131
+ return lines.join('\n') + '\n';
132
+ }
133
+
134
+ // ---------------------------------------------------------------------------
135
+ // Drop-in apply (called from postinstall.js after root check)
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * Write (or remove) the memory-overrides drop-in based on daemon.json config.
140
+ *
141
+ * When neither config.memoryHigh nor config.memoryMax is set, any existing
142
+ * drop-in is removed so shipped defaults take effect after daemon-reload.
143
+ *
144
+ * Validates values before writing — throws on invalid input so postinstall
145
+ * can log and abort rather than silently writing a broken unit.
146
+ *
147
+ * @param {{ memoryHigh?: string, memoryMax?: string }} cfg — subset of daemon.json
148
+ * @param {function(string): void} [log] — optional logger (defaults to console.log)
149
+ */
150
+ function applyDropIn(cfg, log) {
151
+ var _log = log || function (msg) { console.log(msg); };
152
+
153
+ var hasOverride = cfg && (cfg.memoryHigh || cfg.memoryMax);
154
+ if (!hasOverride) {
155
+ // Remove drop-in if present so shipped defaults take over.
156
+ try {
157
+ if (fs.existsSync(DROP_IN_FILE)) {
158
+ fs.unlinkSync(DROP_IN_FILE);
159
+ _log('[memory-limits] Removed ' + DROP_IN_FILE + ' (no overrides configured — shipped defaults apply)');
160
+ }
161
+ } catch (e) {
162
+ _log('[memory-limits] WARNING: could not remove drop-in ' + DROP_IN_FILE + ': ' + e.message);
163
+ }
164
+ return;
165
+ }
166
+
167
+ // Render — throws on invalid format.
168
+ var content = renderDropIn({ memoryHigh: cfg.memoryHigh, memoryMax: cfg.memoryMax });
169
+ if (!content) return; // shouldn't happen given hasOverride check
170
+
171
+ try {
172
+ fs.mkdirSync(DROP_IN_DIR, { recursive: true });
173
+ } catch (e) {
174
+ throw new Error('Cannot create drop-in dir ' + DROP_IN_DIR + ': ' + e.message);
175
+ }
176
+
177
+ // Atomic write via tmp-rename.
178
+ var tmp = DROP_IN_FILE + '.tmp';
179
+ try {
180
+ fs.writeFileSync(tmp, content, { mode: 0o644 });
181
+ fs.renameSync(tmp, DROP_IN_FILE);
182
+ _log('[memory-limits] Wrote memory-overrides drop-in to ' + DROP_IN_FILE);
183
+ if (cfg.memoryHigh) _log('[memory-limits] MemoryHigh=' + cfg.memoryHigh);
184
+ if (cfg.memoryMax) _log('[memory-limits] MemoryMax=' + cfg.memoryMax);
185
+ } catch (e) {
186
+ try { fs.unlinkSync(tmp); } catch (_) {}
187
+ throw new Error('Cannot write drop-in ' + DROP_IN_FILE + ': ' + e.message);
188
+ }
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // MemoryHigh watermark watcher
193
+ // ---------------------------------------------------------------------------
194
+
195
+ // How often to poll for the MemoryHigh watermark (ms).
196
+ // Long enough to avoid hot-loop cost; short enough to catch a crossing quickly.
197
+ var POLL_INTERVAL_MS = 5000;
198
+
199
+ /**
200
+ * Derive the MemoryHigh threshold in bytes from config and the live cgroup.
201
+ *
202
+ * Priority:
203
+ * 1. config.memoryHigh (operator override, parsed to bytes)
204
+ * 2. The live cgroup v2 memory.high value (covers both shipped % default and drop-in)
205
+ * 3. null (no threshold determinable)
206
+ *
207
+ * @param {{ memoryHigh?: string }} cfg
208
+ * @returns {number|null} threshold in bytes, or null
209
+ */
210
+ function resolveMemoryHighBytes(cfg) {
211
+ // 1. Operator override in config.
212
+ if (cfg && cfg.memoryHigh) {
213
+ var parsed = parseMemoryLimit(cfg.memoryHigh);
214
+ if (parsed.ok) {
215
+ var b = memoryValueToBytes(parsed.value);
216
+ if (b !== null) return b;
217
+ }
218
+ }
219
+
220
+ // 2. Live cgroup v2 value (covers percentage defaults and already-applied drop-ins).
221
+ try {
222
+ var cgDir = '/sys/fs/cgroup/system.slice/clagentic-console.service';
223
+ var highRaw = fs.readFileSync(cgDir + '/memory.high', 'utf8').trim();
224
+ if (highRaw !== 'max' && highRaw !== '') {
225
+ var highBytes = parseInt(highRaw, 10);
226
+ if (!isNaN(highBytes) && highBytes > 0) return highBytes;
227
+ }
228
+ } catch (_) {}
229
+
230
+ return null;
231
+ }
232
+
233
+ /**
234
+ * Convert a normalized memory limit string to bytes.
235
+ * Returns null if it cannot be resolved to a byte count at runtime
236
+ * (e.g. a percentage string — percentage resolution requires total RAM).
237
+ *
238
+ * @param {string} value — e.g. '6G', '512M', '70%'
239
+ * @returns {number|null}
240
+ */
241
+ function memoryValueToBytes(value) {
242
+ if (!value) return null;
243
+
244
+ // Percentage: resolve against /proc/meminfo MemTotal.
245
+ var pctMatch = value.match(/^(\d+(?:\.\d+)?)%$/);
246
+ if (pctMatch) {
247
+ try {
248
+ var raw = fs.readFileSync('/proc/meminfo', 'utf8');
249
+ var match = raw.match(/^MemTotal:\s+(\d+)\s+kB/m);
250
+ if (!match) return null;
251
+ var totalBytes = parseInt(match[1], 10) * 1024;
252
+ return Math.floor(totalBytes * parseFloat(pctMatch[1]) / 100);
253
+ } catch (_) {
254
+ return null;
255
+ }
256
+ }
257
+
258
+ // Absolute with suffix.
259
+ var absMatch = value.match(/^(\d+(?:\.\d+)?)([KMGT]?)$/i);
260
+ if (!absMatch) return null;
261
+ var n = parseFloat(absMatch[1]);
262
+ var unit = (absMatch[2] || '').toUpperCase();
263
+ var multipliers = { '': 1, K: 1024, M: 1024 * 1024, G: 1024 * 1024 * 1024, T: 1024 * 1024 * 1024 * 1024 };
264
+ var mul = multipliers[unit];
265
+ if (mul === undefined) return null;
266
+ return Math.floor(n * mul);
267
+ }
268
+
269
+ /**
270
+ * Read the cgroup v2 memory.events 'high' counter for the service cgroup.
271
+ * Returns the counter value as a number, or null if unavailable.
272
+ *
273
+ * @returns {number|null}
274
+ */
275
+ function readCgroupHighCounter() {
276
+ try {
277
+ var cgDir = '/sys/fs/cgroup/system.slice/clagentic-console.service';
278
+ var raw = fs.readFileSync(cgDir + '/memory.events', 'utf8');
279
+ var match = raw.match(/^high\s+(\d+)/m);
280
+ if (match) return parseInt(match[1], 10);
281
+ } catch (_) {}
282
+ return null;
283
+ }
284
+
285
+ /**
286
+ * Read the current cgroup v2 RSS (memory.current) in bytes, or null.
287
+ *
288
+ * @returns {number|null}
289
+ */
290
+ function readCgroupCurrentBytes() {
291
+ try {
292
+ var cgDir = '/sys/fs/cgroup/system.slice/clagentic-console.service';
293
+ var raw = fs.readFileSync(cgDir + '/memory.current', 'utf8').trim();
294
+ var n = parseInt(raw, 10);
295
+ return isNaN(n) ? null : n;
296
+ } catch (_) {}
297
+ return null;
298
+ }
299
+
300
+ /**
301
+ * Start polling for MemoryHigh watermark crossings and emit a structured log
302
+ * event when the soft memory ceiling is breached.
303
+ *
304
+ * Detection strategy (in priority order):
305
+ * A. cgroup v2 memory.events 'high' counter increment — most accurate;
306
+ * fired by the kernel when the service's memory usage exceeds MemoryHigh.
307
+ * B. memory.current vs resolved MemoryHigh threshold — fallback when the
308
+ * cgroup path is not accessible (e.g. running outside systemd in dev).
309
+ *
310
+ * De-duplication: once a watermark-crossing event is emitted, no further events
311
+ * are emitted until the memory drops back below the threshold and rises again
312
+ * (for counter-based detection: until the last-seen counter value changes again
313
+ * after a reset; for RSS-based: until RSS drops below threshold by a 5% hysteresis
314
+ * before re-alerting).
315
+ *
316
+ * The emitted log line is a JSON object on stderr so that structured log
317
+ * consumers (lr-6b30 and friends) can parse it without log-parsing fragility.
318
+ *
319
+ * @param {{ memoryHigh?: string, memoryMax?: string }} cfg — subset of daemon.json
320
+ * @param {object} [opts]
321
+ * @param {number} [opts.pollIntervalMs] — polling interval (default 5000)
322
+ * @param {function(object): void} [opts.onCrossing] — called with the same
323
+ * detail object that is written to the log whenever a watermark crossing is
324
+ * detected. Consumers (lr-6b30 drain) use this instead of parsing stderr.
325
+ * @returns {{ stop: function(): void }} handle to stop the watcher
326
+ */
327
+ function startMemoryHighWatcher(cfg, opts) {
328
+ var pollMs = (opts && opts.pollIntervalMs) || POLL_INTERVAL_MS;
329
+ var onCrossing = (opts && typeof opts.onCrossing === 'function') ? opts.onCrossing : null;
330
+
331
+ // State for de-duplication.
332
+ var lastHighCounter = null; // last 'high' counter value seen (strategy A)
333
+ var isAboveThreshold = false; // for strategy B hysteresis
334
+ var HYSTERESIS_FRACTION = 0.05; // 5% drop required before re-alerting
335
+
336
+ var handle = setInterval(function () {
337
+ try {
338
+ _poll(cfg);
339
+ } catch (e) {
340
+ // Polling must never crash the daemon.
341
+ }
342
+ }, pollMs);
343
+
344
+ // Unref so the watcher doesn't keep the process alive if everything else exits.
345
+ if (handle && typeof handle.unref === 'function') handle.unref();
346
+
347
+ function _emitWarning(detail) {
348
+ var event = {
349
+ event: 'memory_high_watermark',
350
+ source: detail.source,
351
+ timestamp: new Date().toISOString(),
352
+ };
353
+ if (detail.highCounter !== undefined) event.highCounter = detail.highCounter;
354
+ if (detail.currentBytes !== undefined) event.currentBytes = detail.currentBytes;
355
+ if (detail.thresholdBytes !== undefined) event.thresholdBytes = detail.thresholdBytes;
356
+ // Emit as a prefixed JSON line on stderr (journald captures stderr to the journal).
357
+ process.stderr.write('[memory-limits] WARN memory_high_watermark ' + JSON.stringify(event) + '\n');
358
+ // Notify any registered crossing consumer (e.g. lr-6b30 drain controller).
359
+ if (onCrossing) {
360
+ try { onCrossing(event); } catch (_) {}
361
+ }
362
+ }
363
+
364
+ function _poll(c) {
365
+ // Strategy A: cgroup v2 memory.events high counter.
366
+ var highCounter = readCgroupHighCounter();
367
+ if (highCounter !== null) {
368
+ if (lastHighCounter === null) {
369
+ // First observation — record baseline, do not alert.
370
+ lastHighCounter = highCounter;
371
+ return;
372
+ }
373
+ if (highCounter > lastHighCounter) {
374
+ // Counter advanced — kernel confirmed a MemoryHigh crossing.
375
+ var currentBytes = readCgroupCurrentBytes();
376
+ _emitWarning({
377
+ source: 'cgroup.memory.events',
378
+ highCounter: highCounter,
379
+ currentBytes: currentBytes !== null ? currentBytes : undefined,
380
+ });
381
+ lastHighCounter = highCounter;
382
+ }
383
+ // Counter-based path is definitive — skip RSS fallback.
384
+ return;
385
+ }
386
+
387
+ // Strategy B: compare RSS against resolved threshold.
388
+ var threshold = resolveMemoryHighBytes(c);
389
+ if (threshold === null) return; // no threshold determinable
390
+
391
+ var currentB = readCgroupCurrentBytes();
392
+ if (currentB === null) {
393
+ // Fallback: use process.memoryUsage().rss when cgroup current is unavailable.
394
+ currentB = process.memoryUsage().rss;
395
+ }
396
+
397
+ var hysteresisBytes = Math.floor(threshold * HYSTERESIS_FRACTION);
398
+ if (!isAboveThreshold && currentB > threshold) {
399
+ isAboveThreshold = true;
400
+ _emitWarning({
401
+ source: 'rss_vs_threshold',
402
+ currentBytes: currentB,
403
+ thresholdBytes: threshold,
404
+ });
405
+ } else if (isAboveThreshold && currentB < threshold - hysteresisBytes) {
406
+ // Memory dropped back below threshold (with hysteresis) — reset so a
407
+ // future crossing triggers another warning.
408
+ isAboveThreshold = false;
409
+ }
410
+ }
411
+
412
+ return {
413
+ stop: function () {
414
+ clearInterval(handle);
415
+ },
416
+ };
417
+ }
418
+
419
+ // ---------------------------------------------------------------------------
420
+ // Exports
421
+ // ---------------------------------------------------------------------------
422
+
423
+ module.exports = {
424
+ DROP_IN_DIR: DROP_IN_DIR,
425
+ DROP_IN_FILE: DROP_IN_FILE,
426
+ parseMemoryLimit: parseMemoryLimit,
427
+ renderDropIn: renderDropIn,
428
+ applyDropIn: applyDropIn,
429
+ resolveMemoryHighBytes: resolveMemoryHighBytes,
430
+ memoryValueToBytes: memoryValueToBytes,
431
+ readCgroupHighCounter: readCgroupHighCounter,
432
+ readCgroupCurrentBytes: readCgroupCurrentBytes,
433
+ startMemoryHighWatcher: startMemoryHighWatcher,
434
+ // Exposed for testing only.
435
+ _POLL_INTERVAL_MS: POLL_INTERVAL_MS,
436
+ };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * model-context-windows.js — shared source of truth for the model context-window
3
+ * map and beta-aware resolution. (lr-336f)
4
+ *
5
+ * This is the CJS backend copy. The ES module (browser) copy lives at
6
+ * lib/public/modules/model-context-windows.js. A CI test
7
+ * (test/model-context-windows-parity.test.js) asserts both files produce
8
+ * identical resolution results so they cannot silently drift.
9
+ *
10
+ * When adding a new model: update BOTH this file and
11
+ * lib/public/modules/model-context-windows.js.
12
+ * The parity test will fail if they disagree.
13
+ *
14
+ * Keep this module dependency-light: no project imports, no Node built-ins.
15
+ * That constraint is what lets it stay close to the browser copy.
16
+ *
17
+ * The map is keyed by a lowercase model-name substring. Lookup is a linear scan so
18
+ * insertion order matters for overlapping substrings — more-specific keys should
19
+ * appear before less-specific ones.
20
+ */
21
+
22
+ var KNOWN_CONTEXT_WINDOWS = {
23
+ "opus-4-6": 1000000,
24
+ "claude-sonnet-4": 1000000,
25
+ "gpt-5.5": 1048576,
26
+ "gpt-5.4": 1048576,
27
+ "gpt-5.3": 1048576,
28
+ "gpt-5.2": 1048576,
29
+ "gpt-4.1": 1047576,
30
+ "o3": 200000,
31
+ "o4-mini": 200000,
32
+ };
33
+
34
+ /**
35
+ * Resolve the context window for a model identifier, applying the beta-first
36
+ * rule for the context-1m beta.
37
+ *
38
+ * activeBetas: optional array of active beta strings. When any entry contains
39
+ * "context-1m", the true window is 1M regardless of the model — the SDK
40
+ * reports the model's base window in ModelUsage but the beta extends it.
41
+ *
42
+ * Returns the window size in tokens, or 0 when the model is not in
43
+ * KNOWN_CONTEXT_WINDOWS and no beta applies. Callers treat 0 as "unknown"
44
+ * and should degrade cleanly (skip any window-based guard rather than
45
+ * guessing a default).
46
+ */
47
+ function resolveModelContextWindow(model, activeBetas) {
48
+ // Beta check must come first — the SDK does not reflect the extended window.
49
+ if (Array.isArray(activeBetas)) {
50
+ for (var bi = 0; bi < activeBetas.length; bi++) {
51
+ if (activeBetas[bi].indexOf("context-1m") !== -1) return 1000000;
52
+ }
53
+ }
54
+ if (!model) return 0;
55
+ var lc = model.toLowerCase();
56
+ // UI beta-toggle appends [1m] to the model name
57
+ if (lc.indexOf("[1m]") !== -1) return 1000000;
58
+ var keys = Object.keys(KNOWN_CONTEXT_WINDOWS);
59
+ for (var i = 0; i < keys.length; i++) {
60
+ if (lc.indexOf(keys[i]) !== -1) return KNOWN_CONTEXT_WINDOWS[keys[i]];
61
+ }
62
+ return 0;
63
+ }
64
+
65
+ module.exports = { KNOWN_CONTEXT_WINDOWS: KNOWN_CONTEXT_WINDOWS, resolveModelContextWindow: resolveModelContextWindow };
@@ -5,6 +5,7 @@ var { execFileSync } = require("child_process");
5
5
  var { createLoopRegistry } = require("./scheduler");
6
6
  var store = require("./store");
7
7
  var usersModule = require("./users");
8
+ var { writeHandoff, buildHandoffPreamble } = require("./loop-handoff");
8
9
 
9
10
  var LOOP_ID_RE = /^loop_[A-Za-z0-9_-]+$/;
10
11
 
@@ -64,6 +65,10 @@ function attachLoop(ctx) {
64
65
  startedAt: null,
65
66
  loopId: null,
66
67
  loopFilesId: null,
68
+ // Monotonic counter incremented each time startLoop() runs.
69
+ // Lets stopLoop() snapshot the identity at stop-time and guard its
70
+ // fallback timer against a concurrently restarted loop. (lr-e823)
71
+ _loopSeq: 0,
67
72
  };
68
73
 
69
74
  function loopDir() {
@@ -395,6 +400,7 @@ function attachLoop(ctx) {
395
400
  } catch (e) {}
396
401
 
397
402
  var isSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
403
+ loopState._loopSeq++; // unique identity for this run; read by stopLoop() fallback guard (lr-e823)
398
404
  loopState.active = true;
399
405
  loopState.phase = "executing";
400
406
  loopState.promptText = promptText;
@@ -484,6 +490,10 @@ function attachLoop(ctx) {
484
490
  setTimeout(function() { runNextIteration(); }, 2000);
485
491
  return;
486
492
  }
493
+ // lr-ed10: Write handoff-to-disk at the iteration boundary (opt-in).
494
+ // writeHandoff is a no-op when compactHandoff is not enabled in loopSettings.
495
+ writeHandoff({ loopState: loopState, session: completedSession, verdict: null });
496
+
487
497
  var _isSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
488
498
  if (_isSimple) {
489
499
  // Simple mode: no judge, proceed to next iteration or finish
@@ -519,7 +529,14 @@ function attachLoop(ctx) {
519
529
  }
520
530
  }, 10 * 60 * 1000);
521
531
 
522
- var userMsg = { type: "user_message", text: loopState.promptText };
532
+ // lr-ed10: Prepend handoff preamble from prior iteration when compaction is enabled.
533
+ // buildHandoffPreamble returns null on first iteration or when disabled — no-op.
534
+ var _handoffPreamble = buildHandoffPreamble({ loopState: loopState });
535
+ var _iterationPrompt = _handoffPreamble
536
+ ? _handoffPreamble + loopState.promptText
537
+ : loopState.promptText;
538
+
539
+ var userMsg = { type: "user_message", text: _iterationPrompt };
523
540
  session.history.push(userMsg);
524
541
  sm.appendToSessionFile(session, userMsg);
525
542
 
@@ -530,7 +547,7 @@ function attachLoop(ctx) {
530
547
  session.acceptEditsAfterStart = true;
531
548
  session.singleTurn = true;
532
549
  if (loopState.settings) session.loopSettings = loopState.settings;
533
- sdk.startQuery(session, loopState.promptText, undefined, getLinuxUserForSession(session));
550
+ sdk.startQuery(session, _iterationPrompt, undefined, getLinuxUserForSession(session));
534
551
  }
535
552
 
536
553
  function runJudge() {
@@ -610,6 +627,11 @@ function attachLoop(ctx) {
610
627
  summary: verdict.explanation,
611
628
  });
612
629
 
630
+ // lr-ed10: Update the iteration handoff with the judge verdict (opt-in).
631
+ // This overwrites the handoff written at the coder boundary with the verdict included.
632
+ // writeHandoff is a no-op when compactHandoff is not enabled.
633
+ writeHandoff({ loopState: loopState, session: completedSession, verdict: verdict.pass ? "pass" : "fail" });
634
+
613
635
  if (verdict.pass) {
614
636
  finishLoop("pass");
615
637
  } else {
@@ -812,9 +834,15 @@ function attachLoop(ctx) {
812
834
 
813
835
  send({ type: "loop_stopping" });
814
836
 
837
+ // Capture loop identity before the async gap so the fallback timer can
838
+ // verify it is still operating on the same loop run — not a restarted one.
839
+ // Without this snapshot a rapid stop/restart causes the timer to fire and
840
+ // terminate the newly started loop. (lr-e823)
841
+ var stoppingSeq = loopState._loopSeq;
842
+
815
843
  // Fallback: force finish if onQueryComplete hasn't fired after 5s
816
844
  setTimeout(function() {
817
- if (loopState.active && loopState.stopping) {
845
+ if (loopState._loopSeq === stoppingSeq && loopState.active && loopState.stopping) {
818
846
  console.log("[ralph-loop] Stop fallback triggered — forcing finishLoop");
819
847
  finishLoop("stopped");
820
848
  }
@@ -349,8 +349,11 @@ function attachTeam(ctx) {
349
349
  };
350
350
 
351
351
  // Wire up JSONL tails for each member
352
+ // sessionsBase must match lib/sessions.js which reads from CONFIG_DIR/sessions.
353
+ // The old path (REAL_HOME/.clagentic/sessions) was a bug: team tails read from a
354
+ // different directory than where sessions were actually written. (lr-6204)
352
355
  if (cliSessionId && cwd) {
353
- var sessionsBase = path.join(config.REAL_HOME, ".clagentic", "sessions");
356
+ var sessionsBase = path.join(config.CONFIG_DIR, "sessions");
354
357
  var encodedCwd = utils.resolveEncodedDir(sessionsBase, cwd);
355
358
  var subagentDir = path.join(
356
359
  config.REAL_HOME,
package/lib/project.js CHANGED
@@ -1214,8 +1214,16 @@ function createProjectContext(opts) {
1214
1214
  session.worker = null;
1215
1215
  }
1216
1216
  });
1217
+ // Deregister the process-level exit listener added by createSessionManager
1218
+ // so it does not accumulate across project open/close cycles (lr-daca).
1219
+ sm.destroy();
1217
1220
  // Kill all terminals
1218
1221
  tm.destroyAll();
1222
+ // Shut down local MCP stdio child processes to prevent zombie processes
1223
+ // and port conflicts when the project is re-created (lr-4078).
1224
+ if (_localMcp && typeof _localMcp.shutdown === "function") {
1225
+ try { _localMcp.shutdown(); } catch (e) {}
1226
+ }
1219
1227
  for (var ws of clients) {
1220
1228
  try { ws.close(); } catch (e) {}
1221
1229
  }
package/lib/public/app.js CHANGED
@@ -66,6 +66,7 @@ import { initRendering, addToMessages as _renAddToMessages, scrollToBottom as _r
66
66
  import { initDm, openDm as _dmOpenDm, enterDmMode as _dmEnterDmMode, exitDmMode as _dmExitDmMode, appendDmMessage as _dmAppendDmMessage, showDmTypingIndicator as _dmShowDmTypingIndicator, handleDmSend as _dmHandleDmSend } from './modules/app-dm.js';
67
67
  import { initMention, handleMentionStart, handleMentionStream, handleMentionDone, handleMentionError, handleMentionActivity, renderMentionUser, renderMentionResponse } from './modules/mention.js';
68
68
  import { initTeamPanel } from './modules/team-panel.js';
69
+ import { initDiagnostics } from './modules/diagnostics.js';
69
70
 
70
71
  // --- Base path for multi-project routing ---
71
72
  var slugMatch = location.pathname.match(/^\/p\/([a-z0-9_-]+)/);
@@ -1028,6 +1029,9 @@ import { initTeamPanel } from './modules/team-panel.js';
1028
1029
  // --- DM module ---
1029
1030
  initDm();
1030
1031
 
1032
+ // --- Diagnostics panel (lr-8294, epic lr-1a52) ---
1033
+ initDiagnostics();
1034
+
1031
1035
  // --- Messages module (uses direct imports, no ctx injection needed) ---
1032
1036
 
1033
1037
  // --- Connection module ---