@clagentic/console 1.9.0 → 1.10.0-beta.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.
Files changed (172) hide show
  1. package/LICENSE +117 -12
  2. package/LICENSES/MIT-legacy.txt +22 -0
  3. package/LICENSES/README.md +15 -0
  4. package/README.md +9 -3
  5. package/bin/cli.js +40 -5
  6. package/deploy/clagentic-console.service +10 -6
  7. package/lib/agent-dispatch-tool.js +20 -0
  8. package/lib/audit.js +3 -2
  9. package/lib/build-changes.js +79 -0
  10. package/lib/build-identity.js +192 -0
  11. package/lib/build-monitor.js +125 -0
  12. package/lib/build-sha.json +2 -2
  13. package/lib/build-update-check.js +138 -0
  14. package/lib/build-update-offer.js +141 -0
  15. package/lib/build-update-restart.js +142 -0
  16. package/lib/build-update-standing.js +184 -0
  17. package/lib/cli/daemon-launch.js +25 -22
  18. package/lib/cli/ipc-subcommands.js +6 -0
  19. package/lib/cli/session-subcommands.js +122 -0
  20. package/lib/cli-sessions.js +8 -1
  21. package/lib/codex-defaults.js +8 -2
  22. package/lib/config.js +32 -20
  23. package/lib/daemon-env-settings.js +84 -0
  24. package/lib/daemon-projects.js +57 -0
  25. package/lib/daemon.js +288 -205
  26. package/lib/drain.js +74 -17
  27. package/lib/env-compat.js +61 -0
  28. package/lib/extension-commands.js +45 -0
  29. package/lib/history-visibility.js +4 -0
  30. package/lib/idle-adapter-reaper.js +71 -0
  31. package/lib/link-trap.js +78 -0
  32. package/lib/mcp-local.js +8 -6
  33. package/lib/mcp-tool-input.js +116 -0
  34. package/lib/mcp-tool-schema.js +179 -0
  35. package/lib/memory-limits.js +61 -5
  36. package/lib/memory-setting-validate.js +65 -0
  37. package/lib/memory-shed.js +13 -32
  38. package/lib/new-work-gate.js +47 -0
  39. package/lib/os-users.js +5 -3
  40. package/lib/project-access.js +139 -0
  41. package/lib/project-connection.js +37 -22
  42. package/lib/project-external-trigger.js +166 -105
  43. package/lib/project-file-scope.js +172 -0
  44. package/lib/project-file-watch.js +86 -61
  45. package/lib/project-filesystem.js +144 -128
  46. package/lib/project-git.js +119 -0
  47. package/lib/project-http.js +44 -28
  48. package/lib/project-loop.js +17 -9
  49. package/lib/project-mcp.js +53 -72
  50. package/lib/project-message-gate.js +70 -0
  51. package/lib/project-notifications.js +31 -4
  52. package/lib/project-prompt-responses.js +217 -0
  53. package/lib/project-sessions.js +192 -355
  54. package/lib/project-user-message.js +27 -15
  55. package/lib/project.js +212 -147
  56. package/lib/projects-dir.js +90 -0
  57. package/lib/prompt-access.js +22 -0
  58. package/lib/prompt-kinds/answer-limits.js +15 -0
  59. package/lib/prompt-kinds/ask-user.js +58 -0
  60. package/lib/prompt-kinds/codecs.js +97 -0
  61. package/lib/prompt-kinds/elicitation.js +77 -0
  62. package/lib/prompt-kinds/extension.js +39 -0
  63. package/lib/prompt-kinds/index.js +68 -0
  64. package/lib/prompt-kinds/permission.js +114 -0
  65. package/lib/prompt-kinds/plan.js +79 -0
  66. package/lib/prompt-kinds/tool-call.js +38 -0
  67. package/lib/prompt-registry.js +680 -0
  68. package/lib/public/app.js +1 -1
  69. package/lib/public/css/diagnostics.css +80 -0
  70. package/lib/public/css/input.css +17 -3
  71. package/lib/public/css/menus.css +10 -0
  72. package/lib/public/css/messages.css +5 -0
  73. package/lib/public/css/rewind.css +22 -0
  74. package/lib/public/index.html +4 -12
  75. package/lib/public/modules/agent-dispatch-tool.js +9 -0
  76. package/lib/public/modules/app-connection.js +7 -0
  77. package/lib/public/modules/app-cursors.js +7 -5
  78. package/lib/public/modules/app-messages.js +52 -47
  79. package/lib/public/modules/app-notifications.js +47 -71
  80. package/lib/public/modules/app-panels.js +61 -59
  81. package/lib/public/modules/app-projects.js +2 -1
  82. package/lib/public/modules/app-rendering.js +4 -10
  83. package/lib/public/modules/build-update-detail.js +54 -0
  84. package/lib/public/modules/diagnostics.js +170 -20
  85. package/lib/public/modules/filebrowser.js +18 -16
  86. package/lib/public/modules/history-visibility.js +4 -0
  87. package/lib/public/modules/mention.js +3 -2
  88. package/lib/public/modules/mode-options.js +38 -0
  89. package/lib/public/modules/project-settings.js +19 -8
  90. package/lib/public/modules/prompt-banner.js +78 -0
  91. package/lib/public/modules/prompt-card.js +201 -0
  92. package/lib/public/modules/prompt-kinds/ask-user-codec.js +131 -0
  93. package/lib/public/modules/prompt-kinds/ask-user.js +213 -0
  94. package/lib/public/modules/prompt-kinds/elicitation-codec.js +343 -0
  95. package/lib/public/modules/prompt-kinds/elicitation.js +176 -0
  96. package/lib/public/modules/prompt-kinds/index.js +18 -0
  97. package/lib/public/modules/prompt-kinds/own-key.js +29 -0
  98. package/lib/public/modules/prompt-kinds/package.json +3 -0
  99. package/lib/public/modules/prompt-kinds/permission-choices.js +31 -0
  100. package/lib/public/modules/prompt-kinds/permission.js +209 -0
  101. package/lib/public/modules/prompt-kinds/plan.js +102 -0
  102. package/lib/public/modules/prompt-state.js +142 -0
  103. package/lib/public/modules/prompts.js +134 -0
  104. package/lib/public/modules/rewind.js +4 -1
  105. package/lib/public/modules/server-settings.js +2 -4
  106. package/lib/public/modules/sidebar-mobile.js +19 -9
  107. package/lib/public/modules/sidebar-sessions.js +21 -14
  108. package/lib/public/modules/sticky-notes.js +3 -2
  109. package/lib/public/modules/team-panel.js +5 -4
  110. package/lib/public/modules/tools.js +81 -906
  111. package/lib/public/modules/vendor-picker.js +53 -0
  112. package/lib/public/modules/vendor-registry.js +142 -0
  113. package/lib/public/sw.js +3 -1
  114. package/lib/rc-migrate.js +44 -0
  115. package/lib/runtime-env-keys.js +109 -0
  116. package/lib/runtime-env.js +236 -0
  117. package/lib/sdk-bridge.js +348 -284
  118. package/lib/sdk-message-processor.js +117 -146
  119. package/lib/sdk-skill-discovery.js +65 -60
  120. package/lib/server-hub-sessions.js +13 -10
  121. package/lib/server-palette.js +28 -19
  122. package/lib/server.js +156 -115
  123. package/lib/service-install.js +96 -0
  124. package/lib/session-capabilities.js +76 -0
  125. package/lib/session-id.js +33 -0
  126. package/lib/session-input-ipc.js +32 -0
  127. package/lib/session-input.js +379 -0
  128. package/lib/session-reclaim.js +284 -0
  129. package/lib/session-resume.js +172 -0
  130. package/lib/sessions.js +61 -30
  131. package/lib/supervisor.js +39 -0
  132. package/lib/turn-initiator.js +108 -0
  133. package/lib/users-permissions.js +9 -6
  134. package/lib/users.js +9 -0
  135. package/lib/utils.js +4 -2
  136. package/lib/vendor-auth.js +22 -0
  137. package/lib/vendor-registry-message.js +66 -0
  138. package/lib/ws-origin.js +99 -0
  139. package/lib/ws-schema.js +36 -23
  140. package/lib/yoke/adapters/claude-capabilities.js +38 -0
  141. package/lib/yoke/adapters/claude-vendor.js +34 -0
  142. package/lib/yoke/adapters/claude-worker.js +57 -87
  143. package/lib/yoke/adapters/claude.js +182 -88
  144. package/lib/yoke/adapters/codex-capabilities.js +40 -0
  145. package/lib/yoke/adapters/codex-vendor.js +46 -0
  146. package/lib/yoke/adapters/codex.js +462 -211
  147. package/lib/yoke/adapters/effort-control.js +34 -0
  148. package/lib/yoke/adapters/permission-relay.js +58 -0
  149. package/lib/yoke/adapters/worker-mcp-servers.js +81 -0
  150. package/lib/yoke/auth-checks.js +91 -0
  151. package/lib/yoke/capabilities.js +49 -0
  152. package/lib/yoke/codex-app-server.js +30 -56
  153. package/lib/yoke/codex-binary.js +254 -0
  154. package/lib/yoke/codex-command.js +122 -0
  155. package/lib/yoke/codex-protocol.js +96 -0
  156. package/lib/yoke/codex-version.js +135 -0
  157. package/lib/yoke/env-ownership.js +40 -0
  158. package/lib/yoke/index.js +84 -174
  159. package/lib/yoke/install-probe.js +136 -0
  160. package/lib/yoke/instructions.js +7 -11
  161. package/lib/yoke/interface.js +206 -4
  162. package/lib/yoke/package.json +1 -1
  163. package/lib/yoke/provider-credentials.js +96 -0
  164. package/lib/yoke/registry.js +377 -0
  165. package/package.json +12 -9
  166. package/scripts/check-sdk-lock-drift.js +160 -0
  167. package/scripts/check-test-count.js +76 -1
  168. package/scripts/postinstall.js +218 -136
  169. package/scripts/prompt-harness-history.js +202 -0
  170. package/scripts/verify-installed-build.js +59 -17
  171. package/scripts/verify-installed.js +67 -0
  172. package/lib/sdk-permission-ownership.js +0 -136
@@ -185,6 +185,73 @@ function emitAnnotation(message) {
185
185
  writeFullySync(1, "::error::" + escaped + "\n");
186
186
  }
187
187
 
188
+ // Caps keep the annotation inside GitHub's message size limits and readable
189
+ // when a systemic failure (e.g. a broken fixture) fails hundreds of tests.
190
+ var MAX_NAMED_FAILURES = 25;
191
+ var MAX_FAILURE_NAME_LENGTH = 200;
192
+
193
+ // extractFailedTests(tap) — every `not ok` line of a TAP stream, in order,
194
+ // with nesting indentation dropped. Subtests and their enclosing suite both
195
+ // report `not ok`, so a leaf failure is listed alongside its parents; that is
196
+ // deliberate, the parent chain locates the leaf. A `# SKIP`/`# TODO` directive
197
+ // is not a failure and is ignored.
198
+ function extractFailedTests(tap) {
199
+ return extractFailures(tap).map(function (f) { return f.name; });
200
+ }
201
+
202
+ // extractFailures(tap) — like extractFailedTests but each entry also carries
203
+ // `detail`: the error/expected/actual lines from the YAML block node's TAP
204
+ // reporter prints under a failing test, so the annotation says WHY it failed
205
+ // and not only which test did. Multi-line values (`error: |-`) contribute
206
+ // their first content line.
207
+ var MAX_FAILURE_DETAIL_LENGTH = 600;
208
+ var DETAIL_KEY = /^\s+(error|expected|actual|failureType|code):\s*(.*)$/;
209
+
210
+ function extractFailures(tap) {
211
+ var failures = [];
212
+ var current = null;
213
+ var lines = String(tap || "").split("\n");
214
+ for (var i = 0; i < lines.length; i++) {
215
+ var line = lines[i];
216
+ var match = /^\s*not ok \d+(?: - (.*))?$/.exec(line);
217
+ if (match) {
218
+ var name = (match[1] || "(unnamed)").trim();
219
+ if (/#\s*(SKIP|TODO)\b/i.test(name)) { current = null; continue; }
220
+ current = { name: name, detail: "" };
221
+ failures.push(current);
222
+ continue;
223
+ }
224
+ if (/^\s*(ok \d+|# Subtest:)/.test(line)) { current = null; continue; }
225
+ if (!current) continue;
226
+ var detailMatch = DETAIL_KEY.exec(line);
227
+ if (!detailMatch) continue;
228
+ var value = detailMatch[2].trim();
229
+ if ((value === "|-" || value === "|") && i + 1 < lines.length) {
230
+ value = lines[i + 1].trim();
231
+ }
232
+ if (current.detail.length < MAX_FAILURE_DETAIL_LENGTH) {
233
+ current.detail += (current.detail ? "; " : "") + detailMatch[1] + ": " + value;
234
+ }
235
+ }
236
+ return failures;
237
+ }
238
+
239
+ function clip(text, max) {
240
+ return text.length > max ? text.slice(0, max) + "..." : text;
241
+ }
242
+
243
+ function formatFailedTests(failures) {
244
+ var shown = [];
245
+ failures.slice(0, MAX_NAMED_FAILURES).forEach(function (f) {
246
+ shown.push(" not ok - " + clip(f.name, MAX_FAILURE_NAME_LENGTH));
247
+ if (f.detail) shown.push(" " + clip(f.detail, MAX_FAILURE_DETAIL_LENGTH));
248
+ });
249
+ if (failures.length > MAX_NAMED_FAILURES) {
250
+ shown.push(" ... and " + (failures.length - MAX_NAMED_FAILURES) + " more");
251
+ }
252
+ return shown.join("\n");
253
+ }
254
+
188
255
  // classifyRun() is the pure decision core of this script: given the raw
189
256
  // spawnSync() result plus the bucketed RESULT-line data, decide whether the
190
257
  // run passes and, if not, exactly WHY. Pulled out of the top-level script
@@ -285,13 +352,19 @@ function classifyRun(result, files, resultsByFile, totalTests, floor) {
285
352
  }
286
353
 
287
354
  if (result.status !== 0) {
355
+ // Name the failing tests in the verdict itself: the annotation is the only
356
+ // channel a crew agent can read from CI, and "see the TAP above" points at
357
+ // a log it cannot fetch.
358
+ var failed = extractFailures(result.stdout);
359
+ var named = formatFailedTests(failed);
288
360
  return {
289
361
  ok: false,
290
362
  exitCode: result.status,
291
363
  kind: "test-failure",
292
364
  reason: (
293
365
  "node --test exited " + result.status + " with a named test failure above (see the TAP `not ok` " +
294
- "line(s)) — this is an ordinary test failure, not a wrapper-level condition."
366
+ "line(s)) — this is an ordinary test failure, not a wrapper-level condition." +
367
+ (named ? "\nFailing tests (" + failed.length + "):\n" + named : "")
295
368
  ),
296
369
  };
297
370
  }
@@ -302,6 +375,8 @@ function classifyRun(result, files, resultsByFile, totalTests, floor) {
302
375
  module.exports = {
303
376
  classifyRun: classifyRun,
304
377
  emitAnnotation: emitAnnotation,
378
+ extractFailedTests: extractFailedTests,
379
+ extractFailures: extractFailures,
305
380
  writeFullySync: writeFullySync,
306
381
  };
307
382
 
@@ -3,162 +3,94 @@
3
3
 
4
4
  // postinstall.js — installs/updates the systemd service unit on Linux global npm installs.
5
5
  // Runs automatically after `npm install -g @clagentic/console`.
6
- // Silently exits on non-Linux platforms and non-root invocations.
6
+ // Does nothing on non-Linux platforms, on non-global installs (a local `npm ci` /
7
+ // `npm install` in a dev checkout or worktree must never touch /etc/systemd or
8
+ // /usr/local/bin), and for non-root invocations.
9
+ //
10
+ // All host effects go through the `deps` object so tests can stub the filesystem,
11
+ // systemctl and the environment; the exported run() is what main() calls with real ones.
7
12
 
8
13
  const { execFileSync } = require('child_process');
9
14
  const fs = require('fs');
10
15
  const path = require('path');
11
16
 
12
- const PREFIX = '[clagentic-console postinstall]';
13
- const { applyDropIn, parseMemoryLimit } = require('../lib/memory-limits');
14
-
15
- function log(msg) {
16
- console.log(`${PREFIX} ${msg}`);
17
- }
18
-
19
- function runCmd(cmd, args) {
20
- // Returns stdout string on success, throws on failure.
21
- // stderr is captured in err.stderr on failure.
22
- return execFileSync(cmd, args, { stdio: 'pipe' }).toString().trim();
23
- }
24
-
25
- function errMsg(err) {
26
- // execFileSync puts detail in err.stderr; fall back to err.message.
27
- const stderr = err.stderr && err.stderr.toString().trim();
28
- return stderr || err.message;
29
- }
30
-
31
- // Skip silently on non-Linux platforms.
32
- if (process.platform !== 'linux') {
33
- process.exit(0);
34
- }
17
+ const {
18
+ LEGACY_WRAPPER_PATH,
19
+ isLegacyWrapperContent,
20
+ isGlobalInstall,
21
+ resolveCliBin,
22
+ renderUnit,
23
+ } = require('../lib/service-install');
35
24
 
36
- // Skip silently when not running as root — cannot write to /etc/systemd/system/.
37
- if (process.getuid() !== 0) {
38
- log('skipping (not root)');
39
- process.exit(0);
40
- }
41
-
42
- // When the daemon triggers its own in-app update it passes CLAGENTIC_SELF_UPDATE=1.
43
- // In that case, skip restarting the service — the daemon calls gracefulShutdown()
44
- // immediately after npm install completes, and systemd Restart=always handles the
45
- // supervised restart. Issuing systemctl restart here would race with gracefulShutdown
46
- // and tear down sessions before state is flushed.
47
- const selfUpdate = process.env.CLAGENTIC_SELF_UPDATE === '1';
48
- if (selfUpdate) {
49
- log('self-update detected (CLAGENTIC_SELF_UPDATE=1) — skipping service restart');
50
- }
25
+ const PREFIX = '[clagentic-console postinstall]';
51
26
 
52
27
  const SYSTEMD_DIR = '/etc/systemd/system';
53
28
  const NEW_UNIT = 'clagentic-console.service';
54
29
  const OLD_UNIT = 'clagentic.service';
55
- const NEW_UNIT_DEST = path.join(SYSTEMD_DIR, NEW_UNIT);
56
- const OLD_UNIT_PATH = path.join(SYSTEMD_DIR, OLD_UNIT);
57
30
  const UNIT_SRC = path.join(__dirname, '..', 'deploy', 'clagentic-console.service');
31
+ const PKG_DIR = path.join(__dirname, '..');
58
32
 
59
- // Step 1: Copy the new unit file.
60
- log(`installing unit file -> ${NEW_UNIT_DEST}`);
61
- try {
62
- fs.copyFileSync(UNIT_SRC, NEW_UNIT_DEST);
63
- } catch (err) {
64
- log(`ERROR copying unit file: ${errMsg(err)}`);
65
- // Cannot continue without the unit file in place.
66
- process.exit(0);
67
- }
68
-
69
- // Step 2: daemon-reload to pick up the new unit file.
70
- log('running systemctl daemon-reload');
71
- try {
72
- runCmd('systemctl', ['daemon-reload']);
73
- } catch (err) {
74
- log(`WARNING: daemon-reload failed: ${errMsg(err)}`);
33
+ function errMsg(err) {
34
+ // execFileSync puts detail in err.stderr; fall back to err.message.
35
+ const stderr = err.stderr && err.stderr.toString().trim();
36
+ return stderr || err.message;
75
37
  }
76
38
 
77
- // Step 3: Enable the new unit if not already enabled.
78
- log(`enabling ${NEW_UNIT}`);
79
- try {
80
- runCmd('systemctl', ['enable', NEW_UNIT]);
81
- } catch (err) {
82
- log(`WARNING: enable ${NEW_UNIT} failed: ${errMsg(err)}`);
39
+ function realDeps() {
40
+ return {
41
+ fs,
42
+ env: process.env,
43
+ platform: process.platform,
44
+ getuid: () => process.getuid(),
45
+ systemdDir: SYSTEMD_DIR,
46
+ legacyWrapperPath: LEGACY_WRAPPER_PATH,
47
+ pkgDir: PKG_DIR,
48
+ unitSrc: UNIT_SRC,
49
+ log: (msg) => console.log(`${PREFIX} ${msg}`),
50
+ // Returns stdout string on success, throws on failure.
51
+ runCmd: (cmd, args) => execFileSync(cmd, args, { stdio: 'pipe' }).toString().trim(),
52
+ loadConfig: () => require('../lib/config').loadConfig(),
53
+ applyDropIn: (limits, logFn) => require('../lib/memory-limits').applyDropIn(limits, logFn),
54
+ parseMemoryLimit: (v) => require('../lib/memory-limits').parseMemoryLimit(v),
55
+ };
83
56
  }
84
57
 
85
- // Step 4: Handle rename — migrate from old clagentic.service if present.
86
- let wasRunningUnderOldUnit = false;
87
- if (fs.existsSync(OLD_UNIT_PATH)) {
88
- log(`old unit file detected: ${OLD_UNIT_PATH} — performing rename cutover`);
89
-
90
- // Detect whether the old unit is currently active before stopping it.
91
- try {
92
- const activeState = runCmd('systemctl', ['is-active', OLD_UNIT]);
93
- if (activeState === 'active') {
94
- wasRunningUnderOldUnit = true;
95
- }
96
- } catch (_) {
97
- // is-active exits non-zero when not active — not an error.
98
- }
99
-
100
- // Disable the old unit.
101
- log(`disabling ${OLD_UNIT}`);
58
+ // Removes the hand-placed legacy wrapper only when it is byte-for-byte the known
59
+ // legacy content; an operator-modified file is left alone.
60
+ function removeLegacyWrapper(deps) {
61
+ const { fs: fsx, log, legacyWrapperPath } = deps;
62
+ let content;
102
63
  try {
103
- runCmd('systemctl', ['disable', OLD_UNIT]);
64
+ content = fsx.readFileSync(legacyWrapperPath, 'utf8');
104
65
  } catch (err) {
105
- log(`WARNING: disable ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
66
+ if (err.code === 'ENOENT') return 'absent';
67
+ log(`WARNING: could not read ${legacyWrapperPath}: ${errMsg(err)}`);
68
+ return 'unreadable';
106
69
  }
107
-
108
- // Stop the old unit.
109
- log(`stopping ${OLD_UNIT}`);
110
- try {
111
- runCmd('systemctl', ['stop', OLD_UNIT]);
112
- } catch (err) {
113
- log(`WARNING: stop ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
70
+ if (!isLegacyWrapperContent(content)) {
71
+ log(`${legacyWrapperPath} differs from the known legacy wrapper — leaving it in place`);
72
+ return 'modified';
114
73
  }
115
-
116
- // Remove the old unit file.
117
- log(`removing ${OLD_UNIT_PATH}`);
118
74
  try {
119
- fs.unlinkSync(OLD_UNIT_PATH);
75
+ fsx.unlinkSync(legacyWrapperPath);
76
+ log(`removed legacy wrapper ${legacyWrapperPath} (the unit now runs "clagentic-console daemon")`);
77
+ return 'removed';
120
78
  } catch (err) {
121
- log(`WARNING: remove ${OLD_UNIT_PATH} failed: ${errMsg(err)}`);
122
- }
123
-
124
- // daemon-reload again to clear the old unit from systemd's view.
125
- log('running systemctl daemon-reload (post-rename)');
126
- try {
127
- runCmd('systemctl', ['daemon-reload']);
128
- } catch (err) {
129
- log(`WARNING: daemon-reload (post-rename) failed: ${errMsg(err)}`);
79
+ log(`WARNING: remove ${legacyWrapperPath} failed: ${errMsg(err)}`);
80
+ return 'failed';
130
81
  }
131
82
  }
132
83
 
133
- // Step 5: Start clagentic-console.service only if it was running under the old unit
134
- // and needs to be moved to the new one. Never restart a running service — that kills
135
- // live sessions. Never auto-start on a fresh install — the daemon needs configuration.
136
- // Self-updates use gracefulShutdown() + Restart=always; postinstall must not interfere.
137
- if (selfUpdate) {
138
- log('skipping start (self-update — gracefulShutdown will hand off to systemd)');
139
- } else if (wasRunningUnderOldUnit) {
140
- // Stopped the old unit during rename cutover — start under the new one now.
141
- log(`starting ${NEW_UNIT} (was running under ${OLD_UNIT})`);
142
- try {
143
- runCmd('systemctl', ['start', NEW_UNIT]);
144
- } catch (err) {
145
- log(`WARNING: start ${NEW_UNIT} failed: ${errMsg(err)}`);
146
- }
147
- } else {
148
- log(`skipping start (daemon was not running or is already running — operator controls restarts)`);
149
- }
150
-
151
- // Step 6: Apply the memory-limit drop-in (lr-c10f6d).
152
- // When the operator has NOT set memoryHigh/memoryMax in daemon.json, the
153
- // drop-in is still written — with ABSOLUTE byte values computed from
154
- // /proc/meminfo MemTotal (floor(60%) / floor(75%)) — because a `%` directive
155
- // in the shipped unit file is resolved by systemd against the wrong MemTotal
156
- // inside an LXC container; only userspace sees the lxcfs-corrected value.
157
- // Recomputed on every postinstall so it tracks RAM changes. Operator
158
- // overrides in daemon.json always keep precedence (unchanged from lr-de07).
159
- (function applyMemoryDropIn() {
160
- const { loadConfig } = require('../lib/config');
161
- const cfg = loadConfig();
84
+ function applyMemoryDropIn(deps) {
85
+ const { log, runCmd } = deps;
86
+ // When the operator has NOT set memoryHigh/memoryMax in daemon.json, the
87
+ // drop-in is still written — with ABSOLUTE byte values computed from
88
+ // /proc/meminfo MemTotal (floor(60%) / floor(75%)) — because a `%` directive
89
+ // in the shipped unit file is resolved by systemd against the wrong MemTotal
90
+ // inside an LXC container; only userspace sees the lxcfs-corrected value.
91
+ // Recomputed on every postinstall so it tracks RAM changes. Operator
92
+ // overrides in daemon.json always keep precedence.
93
+ const cfg = deps.loadConfig();
162
94
  const memoryHigh = cfg && cfg.memoryHigh ? String(cfg.memoryHigh) : null;
163
95
  const memoryMax = cfg && cfg.memoryMax ? String(cfg.memoryMax) : null;
164
96
 
@@ -166,14 +98,14 @@ if (selfUpdate) {
166
98
  // (Computed defaults are always well-formed bare-byte strings, so no
167
99
  // validation is needed for that path.)
168
100
  if (memoryHigh) {
169
- const vr = parseMemoryLimit(memoryHigh);
101
+ const vr = deps.parseMemoryLimit(memoryHigh);
170
102
  if (!vr.ok) {
171
103
  log(`WARNING: ignoring invalid memoryHigh value in daemon.json: ${vr.error}`);
172
104
  return;
173
105
  }
174
106
  }
175
107
  if (memoryMax) {
176
- const vr = parseMemoryLimit(memoryMax);
108
+ const vr = deps.parseMemoryLimit(memoryMax);
177
109
  if (!vr.ok) {
178
110
  log(`WARNING: ignoring invalid memoryMax value in daemon.json: ${vr.error}`);
179
111
  return;
@@ -181,7 +113,7 @@ if (selfUpdate) {
181
113
  }
182
114
 
183
115
  try {
184
- applyDropIn({ memoryHigh, memoryMax }, (msg) => log(msg.replace(/^\[memory-limits\] /, '')));
116
+ deps.applyDropIn({ memoryHigh, memoryMax }, (msg) => log(msg.replace(/^\[memory-limits\] /, '')));
185
117
  log('running systemctl daemon-reload (memory drop-in updated)');
186
118
  try {
187
119
  runCmd('systemctl', ['daemon-reload']);
@@ -191,6 +123,156 @@ if (selfUpdate) {
191
123
  } catch (err) {
192
124
  log(`WARNING: memory drop-in apply failed: ${err.message}`);
193
125
  }
194
- })();
126
+ }
127
+
128
+ function run(deps) {
129
+ const { fs: fsx, env, log, runCmd } = deps;
130
+
131
+ // Skip silently on non-Linux platforms.
132
+ if (deps.platform !== 'linux') return 'skipped-platform';
133
+
134
+ // A local install (npm ci / npm install in a checkout, a crew worktree, or an npx
135
+ // cache) is not the production install. Acting on it as root rewrote the live unit
136
+ // and ran daemon-reload on the production host.
137
+ if (!isGlobalInstall(env)) {
138
+ log('skipping (not a global install: npm_config_global/npm_config_location not set)');
139
+ return 'skipped-not-global';
140
+ }
141
+
142
+ // Skip when not running as root — cannot write to /etc/systemd/system/.
143
+ if (deps.getuid() !== 0) {
144
+ log('skipping (not root)');
145
+ return 'skipped-not-root';
146
+ }
147
+
148
+ // When the daemon triggers its own in-app update it passes CLAGENTIC_CONSOLE_SELF_UPDATE=1.
149
+ // In that case, skip restarting the service — the daemon calls gracefulShutdown()
150
+ // immediately after npm install completes, and systemd Restart=always handles the
151
+ // supervised restart. Issuing systemctl restart here would race with gracefulShutdown
152
+ // and tear down sessions before state is flushed.
153
+ const { readConsoleEnv } = require('../lib/env-compat');
154
+ const selfUpdate = readConsoleEnv('CLAGENTIC_CONSOLE_SELF_UPDATE', { env }) === '1';
155
+ if (selfUpdate) {
156
+ log('self-update detected (CLAGENTIC_CONSOLE_SELF_UPDATE=1) — skipping service restart');
157
+ }
158
+
159
+ const newUnitDest = path.join(deps.systemdDir, NEW_UNIT);
160
+ const oldUnitPath = path.join(deps.systemdDir, OLD_UNIT);
161
+
162
+ // Step 0: Resolve the installed bin the unit will run; refuse to write a unit that
163
+ // points nowhere.
164
+ const cliBin = resolveCliBin({ env, pkgDir: deps.pkgDir });
165
+ if (!cliBin) {
166
+ log(`ERROR: cannot determine the global clagentic-console bin path from ${deps.pkgDir}; unit not installed`);
167
+ return 'error-no-bin';
168
+ }
169
+
170
+ // Step 1: Render and write the new unit file.
171
+ log(`installing unit file -> ${newUnitDest} (ExecStart=${cliBin} daemon)`);
172
+ try {
173
+ const rendered = renderUnit(fsx.readFileSync(deps.unitSrc, 'utf8'), cliBin);
174
+ fsx.writeFileSync(newUnitDest, rendered);
175
+ } catch (err) {
176
+ log(`ERROR installing unit file: ${errMsg(err)}`);
177
+ // Cannot continue without the unit file in place.
178
+ return 'error-unit';
179
+ }
180
+
181
+ // Step 2: daemon-reload to pick up the new unit file.
182
+ log('running systemctl daemon-reload');
183
+ try {
184
+ runCmd('systemctl', ['daemon-reload']);
185
+ } catch (err) {
186
+ // systemd still holds the previous ExecStart, which points at the legacy
187
+ // wrapper. Removing the wrapper now would make the next Restart=always fail,
188
+ // so keep it, stop here and fail the install step with the reason.
189
+ log(`ERROR: daemon-reload failed: ${errMsg(err)}; the new unit is written but not loaded, the legacy wrapper ${deps.legacyWrapperPath} is kept. Run "systemctl daemon-reload" and reinstall.`);
190
+ return 'error-reload';
191
+ }
192
+
193
+ // Step 3: Enable the new unit if not already enabled.
194
+ log(`enabling ${NEW_UNIT}`);
195
+ try {
196
+ runCmd('systemctl', ['enable', NEW_UNIT]);
197
+ } catch (err) {
198
+ log(`WARNING: enable ${NEW_UNIT} failed: ${errMsg(err)}`);
199
+ }
200
+
201
+ // Step 3b: The reload above succeeded, so systemd now runs the new ExecStart and the
202
+ // hand-placed wrapper is unreferenced; clean it up if untouched.
203
+ removeLegacyWrapper(deps);
204
+
205
+ // Step 4: Handle rename — migrate from old clagentic.service if present.
206
+ let wasRunningUnderOldUnit = false;
207
+ if (fsx.existsSync(oldUnitPath)) {
208
+ log(`old unit file detected: ${oldUnitPath} — performing rename cutover`);
209
+
210
+ // Detect whether the old unit is currently active before stopping it.
211
+ try {
212
+ const activeState = runCmd('systemctl', ['is-active', OLD_UNIT]);
213
+ if (activeState === 'active') {
214
+ wasRunningUnderOldUnit = true;
215
+ }
216
+ } catch (_) {
217
+ // is-active exits non-zero when not active — not an error.
218
+ }
219
+
220
+ log(`disabling ${OLD_UNIT}`);
221
+ try {
222
+ runCmd('systemctl', ['disable', OLD_UNIT]);
223
+ } catch (err) {
224
+ log(`WARNING: disable ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
225
+ }
226
+
227
+ log(`stopping ${OLD_UNIT}`);
228
+ try {
229
+ runCmd('systemctl', ['stop', OLD_UNIT]);
230
+ } catch (err) {
231
+ log(`WARNING: stop ${OLD_UNIT} failed (ignored): ${errMsg(err)}`);
232
+ }
233
+
234
+ log(`removing ${oldUnitPath}`);
235
+ try {
236
+ fsx.unlinkSync(oldUnitPath);
237
+ } catch (err) {
238
+ log(`WARNING: remove ${oldUnitPath} failed: ${errMsg(err)}`);
239
+ }
240
+
241
+ // daemon-reload again to clear the old unit from systemd's view.
242
+ log('running systemctl daemon-reload (post-rename)');
243
+ try {
244
+ runCmd('systemctl', ['daemon-reload']);
245
+ } catch (err) {
246
+ log(`WARNING: daemon-reload (post-rename) failed: ${errMsg(err)}`);
247
+ }
248
+ }
249
+
250
+ // Step 5: Start clagentic-console.service only if it was running under the old unit
251
+ // and needs to be moved to the new one. Never restart a running service — that kills
252
+ // live sessions. Never auto-start on a fresh install — the daemon needs configuration.
253
+ // Self-updates use gracefulShutdown() + Restart=always; postinstall must not interfere.
254
+ if (selfUpdate) {
255
+ log('skipping start (self-update — gracefulShutdown will hand off to systemd)');
256
+ } else if (wasRunningUnderOldUnit) {
257
+ log(`starting ${NEW_UNIT} (was running under ${OLD_UNIT})`);
258
+ try {
259
+ runCmd('systemctl', ['start', NEW_UNIT]);
260
+ } catch (err) {
261
+ log(`WARNING: start ${NEW_UNIT} failed: ${errMsg(err)}`);
262
+ }
263
+ } else {
264
+ log('skipping start (daemon was not running or is already running — operator controls restarts)');
265
+ }
266
+
267
+ // Step 6: Apply the memory-limit drop-in.
268
+ applyMemoryDropIn(deps);
269
+
270
+ log('done');
271
+ return 'installed';
272
+ }
273
+
274
+ module.exports = { run, realDeps, removeLegacyWrapper };
195
275
 
196
- log('done');
276
+ if (require.main === module) {
277
+ if (run(realDeps()) === 'error-reload') process.exitCode = 1;
278
+ }