@clagentic/console 1.6.0 → 1.7.0

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 (85) hide show
  1. package/bin/cli.js +20 -102
  2. package/deploy/clagentic-console.service +10 -1
  3. package/lib/agents-favorites.js +0 -1
  4. package/lib/agents.js +0 -10
  5. package/lib/cli-sessions.js +0 -12
  6. package/lib/codex-defaults.js +4 -1
  7. package/lib/config.js +0 -8
  8. package/lib/daemon.js +88 -9
  9. package/lib/dm.js +0 -1
  10. package/lib/ipc.js +129 -59
  11. package/lib/loop-handoff.js +5 -1
  12. package/lib/memory-limits.js +214 -36
  13. package/lib/memory-shed.js +207 -0
  14. package/lib/notes.js +0 -20
  15. package/lib/os-users.js +0 -3
  16. package/lib/project-connection.js +31 -5
  17. package/lib/project-external-trigger.js +2 -1
  18. package/lib/project-filesystem.js +18 -11
  19. package/lib/project-knowledge.js +0 -8
  20. package/lib/project-loop.js +162 -9
  21. package/lib/project-sessions.js +87 -21
  22. package/lib/project-user-mention.js +2 -1
  23. package/lib/project-user-message.js +16 -5
  24. package/lib/project.js +14 -25
  25. package/lib/public/app.js +1 -2
  26. package/lib/public/css/channel-layout.css +25 -158
  27. package/lib/public/css/diagnostics.css +17 -1
  28. package/lib/public/css/icon-strip.css +1 -32
  29. package/lib/public/css/input.css +0 -56
  30. package/lib/public/css/loop.css +94 -0
  31. package/lib/public/css/messages.css +23 -4
  32. package/lib/public/css/mobile-nav.css +0 -124
  33. package/lib/public/index.html +11 -11
  34. package/lib/public/modules/app-connection.js +2 -1
  35. package/lib/public/modules/app-favicon.js +1 -1
  36. package/lib/public/modules/app-loop-ui.js +140 -4
  37. package/lib/public/modules/app-messages.js +17 -11
  38. package/lib/public/modules/app-projects.js +1 -1
  39. package/lib/public/modules/custom-icons.js +15 -1
  40. package/lib/public/modules/dom-refs.js +1 -2
  41. package/lib/public/modules/emoji-picker.js +6 -1
  42. package/lib/public/modules/filebrowser.js +33 -9
  43. package/lib/public/modules/input.js +39 -0
  44. package/lib/public/modules/scheduler.js +20 -6
  45. package/lib/public/modules/sidebar-mobile.js +0 -64
  46. package/lib/public/modules/sidebar-projects.js +90 -25
  47. package/lib/public/modules/sidebar-sessions.js +80 -13
  48. package/lib/public/modules/stt.js +2 -6
  49. package/lib/public/modules/tool-palette.js +0 -1
  50. package/lib/public/modules/tools.js +2 -6
  51. package/lib/public/style.css +0 -1
  52. package/lib/scheduler.js +0 -1
  53. package/lib/sdk-bridge.js +126 -194
  54. package/lib/sdk-message-processor.js +24 -9
  55. package/lib/sdk-permission-ownership.js +51 -0
  56. package/lib/server-auth.js +25 -18
  57. package/lib/server-dm.js +1 -1
  58. package/lib/server-skills.js +9 -1
  59. package/lib/server.js +18 -3
  60. package/lib/session-search.js +4 -299
  61. package/lib/sessions.js +467 -82
  62. package/lib/smtp.js +0 -15
  63. package/lib/user-presence.js +0 -12
  64. package/lib/users-preferences.js +2 -2
  65. package/lib/users.js +0 -5
  66. package/lib/utils.js +56 -0
  67. package/lib/ws-schema.js +3 -14
  68. package/lib/yoke/adapters/codex.js +96 -10
  69. package/lib/yoke/codex-local-image.js +79 -0
  70. package/package.json +1 -1
  71. package/scripts/postinstall.js +16 -11
  72. package/lib/ask-user-mcp-server.js +0 -121
  73. package/lib/project-memory.js +0 -39
  74. package/lib/public/console-icon.png +0 -0
  75. package/lib/public/css/debate.css +0 -1610
  76. package/lib/public/favicon-banded-32.png +0 -0
  77. package/lib/public/favicon-dark.svg +0 -32
  78. package/lib/public/favicon.svg +0 -32
  79. package/lib/public/icon-banded-96.png +0 -0
  80. package/lib/public/icons/email/gmail.svg +0 -7
  81. package/lib/public/icons/email/outlook.svg +0 -35
  82. package/lib/public/icons/email/yahoo.svg +0 -1
  83. package/lib/public/modules/events.js +0 -21
  84. package/lib/public/modules/state.js +0 -3
  85. package/lib/sdk-worker.js +0 -730
package/lib/ipc.js CHANGED
@@ -1,85 +1,154 @@
1
1
  var net = require("net");
2
2
  var fs = require("fs");
3
3
 
4
+ /**
5
+ * Connect-probe a Unix domain socket to see whether a live process is
6
+ * listening on it. Mirrors config.js's checkOldDaemon/isDaemonAliveAsync
7
+ * pattern: absence of the socket file, a connect error, or a timeout are all
8
+ * treated as "not alive" so a genuinely stale socket can still be reclaimed.
9
+ * Resolves true only on a successful TCP-level connect to the socket.
10
+ */
11
+ function probeSocket(sockPath, timeoutMs) {
12
+ return new Promise(function (resolve) {
13
+ if (!fs.existsSync(sockPath)) return resolve(false);
14
+
15
+ var client = net.connect(sockPath);
16
+ var done = false;
17
+ var timer = setTimeout(function () {
18
+ if (done) return;
19
+ done = true;
20
+ client.destroy();
21
+ resolve(false);
22
+ }, timeoutMs || 1000);
23
+
24
+ client.on("connect", function () {
25
+ if (done) return;
26
+ done = true;
27
+ clearTimeout(timer);
28
+ client.destroy();
29
+ resolve(true);
30
+ });
31
+
32
+ client.on("error", function () {
33
+ if (done) return;
34
+ done = true;
35
+ clearTimeout(timer);
36
+ resolve(false);
37
+ });
38
+ });
39
+ }
40
+
4
41
  /**
5
42
  * Create IPC server on a Unix domain socket.
6
43
  * handler(msg) should return a response object (or a Promise of one).
44
+ *
45
+ * Before binding, connect-probes sockPath (like checkOldDaemon). If a live
46
+ * process answers, this refuses to start rather than unlinking the socket
47
+ * out from under it — stealing a live daemon's socket left --shutdown/
48
+ * --restart/--add all "not responding" against the orphaned original process
49
+ * (lr-1bdb item A). onLiveDaemon (optional) is invoked in that case instead
50
+ * of binding; callers should treat it as a fatal startup condition. A socket
51
+ * file that exists but nothing answers on is genuinely stale and is unlinked
52
+ * as before.
7
53
  */
8
- function createIPCServer(sockPath, handler) {
54
+ function createIPCServer(sockPath, handler, onLiveDaemon) {
9
55
  // Ensure the socket's parent directory exists (e.g. ~/.clagentic/console/).
10
56
  // The daemon may start without a prior CLI invocation, so it must be self-sufficient.
11
57
  if (process.platform !== "win32") {
12
58
  try { fs.mkdirSync(require("path").dirname(sockPath), { recursive: true }); } catch (e) {}
13
59
  }
14
60
 
15
- // Remove stale socket file (not needed for Windows named pipes)
16
- if (process.platform !== "win32") {
17
- try { fs.unlinkSync(sockPath); } catch (e) {}
18
- }
61
+ // Returned synchronously so callers (e.g. daemon.js's gracefulShutdown) can
62
+ // always call .close() safely, even if invoked before the async probe below
63
+ // resolves and the real server binds.
64
+ var _server = null;
65
+ var handle = {
66
+ close: function () {
67
+ if (_server) _server.close();
68
+ if (process.platform !== "win32") {
69
+ try { fs.unlinkSync(sockPath); } catch (e) {}
70
+ }
71
+ },
72
+ };
19
73
 
20
- var server = net.createServer(function (conn) {
21
- var buffer = "";
22
- conn.setEncoding("utf8");
74
+ function doBind() {
75
+ var server = net.createServer(function (conn) {
76
+ var buffer = "";
77
+ conn.setEncoding("utf8");
23
78
 
24
- conn.on("data", function (chunk) {
25
- buffer += chunk;
26
- var lines = buffer.split("\n");
27
- buffer = lines.pop(); // keep incomplete line
79
+ conn.on("data", function (chunk) {
80
+ buffer += chunk;
81
+ var lines = buffer.split("\n");
82
+ buffer = lines.pop(); // keep incomplete line
28
83
 
29
- for (var i = 0; i < lines.length; i++) {
30
- if (!lines[i].trim()) continue;
31
- try {
32
- var msg = JSON.parse(lines[i]);
33
- var result = handler(msg);
34
- // Support both sync and async handlers
35
- if (result && typeof result.then === "function") {
36
- (function (c) {
37
- result.then(function (res) {
38
- try { c.write(JSON.stringify(res) + "\n"); } catch (e) {}
39
- }).catch(function (err) {
40
- try { c.write(JSON.stringify({ ok: false, error: err.message }) + "\n"); } catch (e) {}
41
- });
42
- })(conn);
43
- } else {
44
- conn.write(JSON.stringify(result) + "\n");
84
+ for (var i = 0; i < lines.length; i++) {
85
+ if (!lines[i].trim()) continue;
86
+ try {
87
+ var msg = JSON.parse(lines[i]);
88
+ var result = handler(msg);
89
+ // Support both sync and async handlers
90
+ if (result && typeof result.then === "function") {
91
+ (function (c) {
92
+ result.then(function (res) {
93
+ try { c.write(JSON.stringify(res) + "\n"); } catch (e) {}
94
+ }).catch(function (err) {
95
+ try { c.write(JSON.stringify({ ok: false, error: err.message }) + "\n"); } catch (e) {}
96
+ });
97
+ })(conn);
98
+ } else {
99
+ conn.write(JSON.stringify(result) + "\n");
100
+ }
101
+ } catch (e) {
102
+ try { conn.write(JSON.stringify({ ok: false, error: "parse error" }) + "\n"); } catch (e2) {}
45
103
  }
46
- } catch (e) {
47
- try { conn.write(JSON.stringify({ ok: false, error: "parse error" }) + "\n"); } catch (e2) {}
48
104
  }
49
- }
105
+ });
106
+
107
+ conn.on("error", function () {});
50
108
  });
51
109
 
52
- conn.on("error", function () {});
53
- });
110
+ var retried = false;
111
+ server.on("error", function (err) {
112
+ if (err.code === "EADDRINUSE" && !retried) {
113
+ retried = true;
114
+ console.log("[ipc] Socket in use, removing stale socket and retrying...");
115
+ try { fs.unlinkSync(sockPath); } catch (e) {}
116
+ server.listen(sockPath);
117
+ } else if (err.code === "ENOENT" && !retried) {
118
+ // Parent directory missing — create it and retry once.
119
+ retried = true;
120
+ console.log("[ipc] Socket directory missing, creating and retrying...");
121
+ try { fs.mkdirSync(require("path").dirname(sockPath), { recursive: true }); } catch (e) {}
122
+ server.listen(sockPath);
123
+ } else {
124
+ console.error("[ipc] Failed to bind socket:", err.message);
125
+ process.exit(1);
126
+ }
127
+ });
128
+ server.listen(sockPath);
129
+ _server = server;
130
+ }
54
131
 
55
- var retried = false;
56
- server.on("error", function (err) {
57
- if (err.code === "EADDRINUSE" && !retried) {
58
- retried = true;
59
- console.log("[ipc] Socket in use, removing stale socket and retrying...");
132
+ if (process.platform !== "win32") {
133
+ probeSocket(sockPath).then(function (alive) {
134
+ if (alive) {
135
+ console.error("[ipc] Refusing to start: a live daemon is already listening on " + sockPath);
136
+ if (typeof onLiveDaemon === "function") {
137
+ onLiveDaemon();
138
+ } else {
139
+ process.exit(1);
140
+ }
141
+ return;
142
+ }
143
+ // Socket file (if any) is genuinely stale — safe to remove before binding.
60
144
  try { fs.unlinkSync(sockPath); } catch (e) {}
61
- server.listen(sockPath);
62
- } else if (err.code === "ENOENT" && !retried) {
63
- // Parent directory missing — create it and retry once.
64
- retried = true;
65
- console.log("[ipc] Socket directory missing, creating and retrying...");
66
- try { fs.mkdirSync(require("path").dirname(sockPath), { recursive: true }); } catch (e) {}
67
- server.listen(sockPath);
68
- } else {
69
- console.error("[ipc] Failed to bind socket:", err.message);
70
- process.exit(1);
71
- }
72
- });
73
- server.listen(sockPath);
145
+ doBind();
146
+ });
147
+ } else {
148
+ doBind();
149
+ }
74
150
 
75
- return {
76
- close: function () {
77
- server.close();
78
- if (process.platform !== "win32") {
79
- try { fs.unlinkSync(sockPath); } catch (e) {}
80
- }
81
- },
82
- };
151
+ return handle;
83
152
  }
84
153
 
85
154
  /**
@@ -134,4 +203,5 @@ function sendIPCCommand(sockPath, message, timeout) {
134
203
  module.exports = {
135
204
  createIPCServer: createIPCServer,
136
205
  sendIPCCommand: sendIPCCommand,
206
+ probeSocket: probeSocket,
137
207
  };
@@ -64,6 +64,11 @@ function handoffFilePath(loopId, iteration) {
64
64
  * Returns a string up to ~1 000 chars — enough for a continuation frame
65
65
  * without re-inflating the context.
66
66
  *
67
+ * lr-2ea2a7: iterates the heap array backward from its end — tolerant of a
68
+ * trimmed head by construction (only ever wants the most recent ~800 chars,
69
+ * which live in the retained tail window regardless of how much of the
70
+ * session's full history has been trimmed off the front).
71
+ *
67
72
  * @param {Array} history session.history array
68
73
  * @returns {string}
69
74
  */
@@ -276,7 +281,6 @@ module.exports = {
276
281
  buildHandoffPreamble: buildHandoffPreamble,
277
282
  getHandoffDir: getHandoffDir,
278
283
  // Exported for unit tests only
279
- _handoffFilePath: handoffFilePath,
280
284
  _extractSessionSummary: extractSessionSummary,
281
285
  _parseDecisionsAndThreads: parseDecisionsAndThreads,
282
286
  };
@@ -1,16 +1,25 @@
1
1
  // memory-limits.js — daemon.json advanced-settings override for systemd memory limits
2
- // and MemoryHigh watermark detection (lr-de07).
2
+ // and MemoryHigh watermark detection (lr-de07, lr-c10f6d).
3
3
  //
4
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.
5
+ // percentage-based defaults (MemoryHigh=70%, MemoryMax=85%) as a documentation
6
+ // fallback only. Inside an LXC container, systemd resolves a `%` directive
7
+ // against the cgroup-visible MemTotal at the HOST layer, not the container's
8
+ // true RAM — only userspace (via lxcfs) sees the container-true /proc/meminfo
9
+ // value. A `%` unit-file directive is therefore silently miscalibrated inside
10
+ // a container (lr-c10f6d). To make the ceiling actually operative, this module
11
+ // computes ABSOLUTE byte values from /proc/meminfo MemTotal in userspace and
12
+ // writes them into the drop-in unconditionally on every postinstall, so the
13
+ // applied cgroup limit always tracks the container-true RAM.
9
14
  //
10
15
  // Override reach: a systemd drop-in written to
11
16
  // /etc/systemd/system/clagentic-console.service.d/memory-overrides.conf
12
17
  // overrides only the MemoryMax and MemoryHigh [Service] lines. All other unit
13
18
  // settings remain exactly as shipped.
19
+ //
20
+ // Precedence (unchanged semantics from lr-de07): an explicit operator
21
+ // config.memoryHigh / config.memoryMax in daemon.json always wins over the
22
+ // computed default.
14
23
 
15
24
  'use strict';
16
25
 
@@ -24,6 +33,14 @@ var path = require('path');
24
33
  var DROP_IN_DIR = '/etc/systemd/system/clagentic-console.service.d';
25
34
  var DROP_IN_FILE = path.join(DROP_IN_DIR, 'memory-overrides.conf');
26
35
 
36
+ // Computed-default fractions (lr-c10f6d) — applied when the operator has not
37
+ // set an explicit memoryHigh/memoryMax override in daemon.json. Values are
38
+ // resolved against /proc/meminfo MemTotal (lxcfs-correct inside a container)
39
+ // and written as absolute bytes, since a `%` unit-file directive is resolved
40
+ // by systemd at the host cgroup layer and is wrong inside an LXC container.
41
+ var DEFAULT_MEMORY_HIGH_FRACTION = 0.60;
42
+ var DEFAULT_MEMORY_MAX_FRACTION = 0.75;
43
+
27
44
  // Accepted units for absolute memory values.
28
45
  // Systemd accepts K, M, G, T (case-insensitive) and bare bytes.
29
46
  var ABS_PATTERN = /^(\d+(?:\.\d+)?)\s*([KMGT]?)B?$/i;
@@ -136,37 +153,105 @@ function renderDropIn(opts) {
136
153
  // ---------------------------------------------------------------------------
137
154
 
138
155
  /**
139
- * Write (or remove) the memory-overrides drop-in based on daemon.json config.
156
+ * Read /proc/meminfo MemTotal in bytes.
157
+ *
158
+ * Inside an LXC container, lxcfs virtualizes this path so it reports the
159
+ * container-true total rather than the host's — this is the value systemd's
160
+ * own `%` resolution gets wrong (lr-c10f6d), so all default-limit computation
161
+ * must read it directly in userspace rather than rely on a unit-file `%`.
162
+ *
163
+ * @param {string} [procMeminfoPath] — override for testing (default '/proc/meminfo')
164
+ * @returns {number|null} MemTotal in bytes, or null if unreadable/unparsable
165
+ */
166
+ function readMemTotalBytes(procMeminfoPath) {
167
+ try {
168
+ var raw = fs.readFileSync(procMeminfoPath || '/proc/meminfo', 'utf8');
169
+ var match = raw.match(/^MemTotal:\s+(\d+)\s+kB/m);
170
+ if (!match) return null;
171
+ return parseInt(match[1], 10) * 1024;
172
+ } catch (_) {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Compute the default absolute MemoryHigh/MemoryMax values (as systemd
179
+ * byte-suffix strings) from the container-true MemTotal.
180
+ *
181
+ * MemoryHigh = floor(60% of MemTotal), MemoryMax = floor(75% of MemTotal).
182
+ * Returns null if MemTotal cannot be determined — callers must fall back to
183
+ * leaving the shipped unit-file `%` defaults in place rather than writing a
184
+ * bogus drop-in.
185
+ *
186
+ * @param {string} [procMeminfoPath] — override for testing
187
+ * @returns {{ memoryHigh: string, memoryMax: string, memTotalBytes: number }|null}
188
+ */
189
+ function computeDefaultAbsoluteLimits(procMeminfoPath) {
190
+ var memTotalBytes = readMemTotalBytes(procMeminfoPath);
191
+ if (memTotalBytes === null || memTotalBytes <= 0) return null;
192
+
193
+ var highBytes = Math.floor(memTotalBytes * DEFAULT_MEMORY_HIGH_FRACTION);
194
+ var maxBytes = Math.floor(memTotalBytes * DEFAULT_MEMORY_MAX_FRACTION);
195
+
196
+ return {
197
+ memoryHigh: String(highBytes),
198
+ memoryMax: String(maxBytes),
199
+ memTotalBytes: memTotalBytes,
200
+ };
201
+ }
202
+
203
+ /**
204
+ * Write the memory-overrides drop-in based on daemon.json config.
140
205
  *
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.
206
+ * Precedence (unchanged from lr-de07): an explicit operator config.memoryHigh
207
+ * / config.memoryMax always wins. When neither is set, a computed-absolute
208
+ * default is written instead (lr-c10f6d) — floor(60%) / floor(75%) of the
209
+ * container-true /proc/meminfo MemTotal, resolved in userspace because a `%`
210
+ * unit-file directive is resolved by systemd against the wrong MemTotal
211
+ * inside an LXC container. The drop-in is written unconditionally (every
212
+ * postinstall) so it tracks RAM changes; if MemTotal cannot be determined,
213
+ * any existing drop-in is removed so the shipped unit-file `%` lines apply
214
+ * as a last-resort fallback.
143
215
  *
144
216
  * Validates values before writing — throws on invalid input so postinstall
145
217
  * can log and abort rather than silently writing a broken unit.
146
218
  *
147
219
  * @param {{ memoryHigh?: string, memoryMax?: string }} cfg — subset of daemon.json
148
220
  * @param {function(string): void} [log] — optional logger (defaults to console.log)
221
+ * @param {string} [procMeminfoPath] — override for testing (default '/proc/meminfo')
149
222
  */
150
- function applyDropIn(cfg, log) {
223
+ function applyDropIn(cfg, log, procMeminfoPath) {
151
224
  var _log = log || function (msg) { console.log(msg); };
152
225
 
153
226
  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)');
227
+ var effective;
228
+ if (hasOverride) {
229
+ effective = { memoryHigh: cfg.memoryHigh, memoryMax: cfg.memoryMax };
230
+ } else {
231
+ var computed = computeDefaultAbsoluteLimits(procMeminfoPath);
232
+ if (!computed) {
233
+ // MemTotal undeterminable — remove any stale drop-in so the shipped
234
+ // unit-file % defaults apply (best available fallback).
235
+ try {
236
+ if (fs.existsSync(DROP_IN_FILE)) {
237
+ fs.unlinkSync(DROP_IN_FILE);
238
+ _log('[memory-limits] Removed ' + DROP_IN_FILE + ' (MemTotal undeterminable — shipped % defaults apply)');
239
+ } else {
240
+ _log('[memory-limits] WARNING: could not read /proc/meminfo MemTotal — shipped % defaults apply (inoperative inside a container, see lr-c10f6d)');
241
+ }
242
+ } catch (e) {
243
+ _log('[memory-limits] WARNING: could not remove drop-in ' + DROP_IN_FILE + ': ' + e.message);
160
244
  }
161
- } catch (e) {
162
- _log('[memory-limits] WARNING: could not remove drop-in ' + DROP_IN_FILE + ': ' + e.message);
245
+ return;
163
246
  }
164
- return;
247
+ effective = { memoryHigh: computed.memoryHigh, memoryMax: computed.memoryMax };
248
+ _log('[memory-limits] No operator override — computing absolute defaults from MemTotal=' + computed.memTotalBytes + ' bytes '
249
+ + '(MemoryHigh=' + computed.memoryHigh + ', MemoryMax=' + computed.memoryMax + ')');
165
250
  }
166
251
 
167
252
  // 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
253
+ var content = renderDropIn({ memoryHigh: effective.memoryHigh, memoryMax: effective.memoryMax });
254
+ if (!content) return; // shouldn't happen given effective always sets both
170
255
 
171
256
  try {
172
257
  fs.mkdirSync(DROP_IN_DIR, { recursive: true });
@@ -180,8 +265,8 @@ function applyDropIn(cfg, log) {
180
265
  fs.writeFileSync(tmp, content, { mode: 0o644 });
181
266
  fs.renameSync(tmp, DROP_IN_FILE);
182
267
  _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);
268
+ if (effective.memoryHigh) _log('[memory-limits] MemoryHigh=' + effective.memoryHigh);
269
+ if (effective.memoryMax) _log('[memory-limits] MemoryMax=' + effective.memoryMax);
185
270
  } catch (e) {
186
271
  try { fs.unlinkSync(tmp); } catch (_) {}
187
272
  throw new Error('Cannot write drop-in ' + DROP_IN_FILE + ': ' + e.message);
@@ -244,15 +329,9 @@ function memoryValueToBytes(value) {
244
329
  // Percentage: resolve against /proc/meminfo MemTotal.
245
330
  var pctMatch = value.match(/^(\d+(?:\.\d+)?)%$/);
246
331
  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
- }
332
+ var totalBytes = readMemTotalBytes();
333
+ if (totalBytes === null) return null;
334
+ return Math.floor(totalBytes * parseFloat(pctMatch[1]) / 100);
256
335
  }
257
336
 
258
337
  // Absolute with suffix.
@@ -297,6 +376,105 @@ function readCgroupCurrentBytes() {
297
376
  return null;
298
377
  }
299
378
 
379
+ // ---------------------------------------------------------------------------
380
+ // Startup sanity check: applied cgroup ceiling vs container-true RAM (lr-c10f6d)
381
+ // ---------------------------------------------------------------------------
382
+
383
+ /**
384
+ * Compare the applied cgroup memory.max ceiling against /proc/meminfo MemTotal.
385
+ *
386
+ * The postinstall drop-in computes MemoryMax from MemTotal itself, so under
387
+ * normal operation this check always passes. It exists as a last-line-of-defense
388
+ * sanity check for any host where the drop-in was not applied, was hand-edited,
389
+ * or is stale relative to a MemTotal that changed without a re-run of postinstall
390
+ * (e.g. hot RAM resize) — in any of those cases the ceiling is 'max' (unset) or
391
+ * greater than the container's actual RAM, meaning OOMPolicy=kill can never fire
392
+ * before the kernel host-level OOM killer wedges the box (the lr-2ea2a7 failure
393
+ * mode this task exists to close off).
394
+ *
395
+ * @param {object} [opts]
396
+ * @param {string} [opts.cgroupMemoryMaxPath] — override for testing
397
+ * (default '/sys/fs/cgroup/system.slice/clagentic-console.service/memory.max')
398
+ * @param {string} [opts.procMeminfoPath] — override for testing (default '/proc/meminfo')
399
+ * @returns {{
400
+ * ok: boolean,
401
+ * inoperative: boolean,
402
+ * reason: string|null,
403
+ * appliedMaxBytes: number|null,
404
+ * appliedMaxRaw: string|null,
405
+ * memTotalBytes: number|null
406
+ * }}
407
+ * ok=false when either value could not be determined (nothing to compare —
408
+ * not itself a fault). inoperative=true when the applied ceiling is 'max'
409
+ * (unset) or >= MemTotal.
410
+ */
411
+ function checkAppliedMemoryCeiling(opts) {
412
+ var o = opts || {};
413
+ var cgPath = o.cgroupMemoryMaxPath
414
+ || '/sys/fs/cgroup/system.slice/clagentic-console.service/memory.max';
415
+
416
+ var appliedRaw = null;
417
+ try {
418
+ appliedRaw = fs.readFileSync(cgPath, 'utf8').trim();
419
+ } catch (e) {
420
+ return {
421
+ ok: false,
422
+ inoperative: false,
423
+ reason: 'cgroup memory.max unreadable at ' + cgPath + ': ' + e.message,
424
+ appliedMaxBytes: null,
425
+ appliedMaxRaw: null,
426
+ memTotalBytes: null,
427
+ };
428
+ }
429
+
430
+ var memTotalBytes = readMemTotalBytes(o.procMeminfoPath);
431
+ if (memTotalBytes === null) {
432
+ return {
433
+ ok: false,
434
+ inoperative: false,
435
+ reason: 'MemTotal unreadable from /proc/meminfo',
436
+ appliedMaxBytes: null,
437
+ appliedMaxRaw: appliedRaw,
438
+ memTotalBytes: null,
439
+ };
440
+ }
441
+
442
+ if (appliedRaw === 'max') {
443
+ return {
444
+ ok: true,
445
+ inoperative: true,
446
+ reason: 'applied memory.max is \'max\' (no cgroup ceiling set) — OOM protection inoperative',
447
+ appliedMaxBytes: null,
448
+ appliedMaxRaw: appliedRaw,
449
+ memTotalBytes: memTotalBytes,
450
+ };
451
+ }
452
+
453
+ var appliedMaxBytes = parseInt(appliedRaw, 10);
454
+ if (isNaN(appliedMaxBytes)) {
455
+ return {
456
+ ok: false,
457
+ inoperative: false,
458
+ reason: 'applied memory.max value is not parsable: ' + appliedRaw,
459
+ appliedMaxBytes: null,
460
+ appliedMaxRaw: appliedRaw,
461
+ memTotalBytes: memTotalBytes,
462
+ };
463
+ }
464
+
465
+ var inoperative = appliedMaxBytes >= memTotalBytes;
466
+ return {
467
+ ok: true,
468
+ inoperative: inoperative,
469
+ reason: inoperative
470
+ ? 'applied memory.max (' + appliedMaxBytes + ' bytes) >= container MemTotal (' + memTotalBytes + ' bytes) — OOM protection inoperative'
471
+ : null,
472
+ appliedMaxBytes: appliedMaxBytes,
473
+ appliedMaxRaw: appliedRaw,
474
+ memTotalBytes: memTotalBytes,
475
+ };
476
+ }
477
+
300
478
  /**
301
479
  * Start polling for MemoryHigh watermark crossings and emit a structured log
302
480
  * event when the soft memory ceiling is breached.
@@ -421,16 +599,16 @@ function startMemoryHighWatcher(cfg, opts) {
421
599
  // ---------------------------------------------------------------------------
422
600
 
423
601
  module.exports = {
424
- DROP_IN_DIR: DROP_IN_DIR,
425
602
  DROP_IN_FILE: DROP_IN_FILE,
603
+ DEFAULT_MEMORY_HIGH_FRACTION: DEFAULT_MEMORY_HIGH_FRACTION,
604
+ DEFAULT_MEMORY_MAX_FRACTION: DEFAULT_MEMORY_MAX_FRACTION,
426
605
  parseMemoryLimit: parseMemoryLimit,
427
606
  renderDropIn: renderDropIn,
428
607
  applyDropIn: applyDropIn,
608
+ readMemTotalBytes: readMemTotalBytes,
609
+ computeDefaultAbsoluteLimits: computeDefaultAbsoluteLimits,
429
610
  resolveMemoryHighBytes: resolveMemoryHighBytes,
430
611
  memoryValueToBytes: memoryValueToBytes,
431
- readCgroupHighCounter: readCgroupHighCounter,
432
- readCgroupCurrentBytes: readCgroupCurrentBytes,
433
612
  startMemoryHighWatcher: startMemoryHighWatcher,
434
- // Exposed for testing only.
435
- _POLL_INTERVAL_MS: POLL_INTERVAL_MS,
613
+ checkAppliedMemoryCeiling: checkAppliedMemoryCeiling,
436
614
  };