@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
package/lib/daemon.js CHANGED
@@ -23,25 +23,42 @@ delete process.env.CLAUDECODE;
23
23
 
24
24
  var fs = require("fs");
25
25
  var path = require("path");
26
+ // What this process loaded is recorded before anything else is required from
27
+ // lib/, so an install landing during startup is seen as a change afterwards.
28
+ var buildIdentity = require("./build-identity").createBuildIdentity(__dirname);
26
29
  var { loadConfig, saveConfig, socketPath, ensureConfigDir, generateSlug, syncClayrc, removeFromClayrc, writeCrashInfo, readCrashInfo, clearCrashInfo, isPidAlive, clearStaleConfig, REAL_HOME, CONFIG_DIR, CLAGENTIC_HOME } = require("./config");
27
30
  var { createIPCServer } = require("./ipc");
31
+ var { createEnvSettings, removeEnvrcOnOwnerChange } = require("./daemon-env-settings");
32
+ var { startIdleAdapterReaper } = require("./idle-adapter-reaper");
28
33
  var { createServer } = require("./server");
34
+ var promptRegistry = require("./prompt-registry");
29
35
  var { checkAclSupport, grantProjectAccess, revokeProjectAccess, provisionAllUsers, provisionLinuxUser, grantAllUsersAccess, deactivateLinuxUser, ensureProjectsDir } = require("./os-users");
30
36
  var usersModule = require("./users");
31
37
  var { createWorktree, removeWorktree, isWorktree } = require("./worktree");
32
- var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug } = require("./daemon-projects");
38
+ var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, stopWorktreeRescans, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug, getProjectAccessRecord } = require("./daemon-projects");
33
39
  var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
34
40
  var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, buildActivityDiagnosticsResponse } = require("./sdk-bridge");
41
+ var { validateMemAvailableThresholdMB, validateTokensPerMbHeadroom } = require("./memory-setting-validate");
35
42
  var { startMemoryHighWatcher, checkAppliedMemoryCeiling } = require("./memory-limits");
36
43
  var { createDrain } = require("./drain");
44
+ var { setNewWorkGate } = require("./new-work-gate");
37
45
  var { shedMemory } = require("./memory-shed");
38
46
  var { dropSkillsCache } = require("./server-skills");
47
+ var { waitForIdleThenAct } = require("./build-update-check");
48
+ var { createBuildMonitor } = require("./build-monitor");
49
+ var { createBuildUpdateRestart } = require("./build-update-restart");
50
+ var { buildOffer, summarizeOffer } = require("./build-update-offer");
51
+ var { createStandingOffer } = require("./build-update-standing");
52
+ var { listBuildChanges, resolveHistoryRepo } = require("./build-changes");
53
+ var { RESTART_EXIT_CODE, isSupervised, unsupervisedEnv } = require("./supervisor");
39
54
  var liteDetect = require("./lite-detect");
40
55
  var { execFile: liteExecFile } = require("child_process");
41
56
  var { SLUG_RE: CUSTOM_ICON_SLUG_RE, CUSTOM_EMOJI_CT } = require("./server-settings");
42
57
 
43
58
  var daemonVersion = require("../package.json").version;
44
- var configFile = process.env.CLAGENTIC_CONFIG || process.env.CLAY_CONFIG || require("./config").configPath();
59
+ var { readConsoleEnv } = require("./env-compat");
60
+ var { resolveProjectsDir, legacyNotice } = require("./projects-dir");
61
+ var configFile = readConsoleEnv("CLAGENTIC_CONSOLE_CONFIG") || require("./config").configPath();
45
62
  var config;
46
63
 
47
64
  // Ensure dirs exist before any file access — daemon must be self-sufficient when
@@ -52,25 +69,25 @@ try {
52
69
  config = JSON.parse(fs.readFileSync(configFile, "utf8"));
53
70
  } catch (e) {
54
71
  if (e.code === "ENOENT") {
55
- // Guard: if CLAGENTIC_HOME was erroneously set to the socket subdirectory
72
+ // Guard: if CLAGENTIC_CONSOLE_HOME was erroneously set to the socket subdirectory
56
73
  // (e.g. ~/.clagentic/console instead of ~/.clagentic), a real daemon.json
57
- // will exist one level above CLAGENTIC_HOME. Detect this and refuse to
74
+ // will exist one level above CLAGENTIC_CONSOLE_HOME. Detect this and refuse to
58
75
  // bootstrap an empty config — that would silently discard all projects.
59
76
  var { CLAGENTIC_HOME: _cgHome } = require("./config");
60
77
  var _siblingConfig = path.join(path.dirname(_cgHome), "daemon.json");
61
78
  try {
62
79
  var _sibling = JSON.parse(fs.readFileSync(_siblingConfig, "utf8"));
63
80
  if (_sibling && Array.isArray(_sibling.projects) && _sibling.projects.length > 0) {
64
- console.error("[daemon] ERROR: CLAGENTIC_HOME appears to point at the console/ socket subdirectory (" + _cgHome + ").");
81
+ console.error("[daemon] ERROR: CLAGENTIC_CONSOLE_HOME appears to point at the console/ socket subdirectory (" + _cgHome + ").");
65
82
  console.error("[daemon] A populated daemon.json with " + _sibling.projects.length + " project(s) exists at " + _siblingConfig + ".");
66
- console.error("[daemon] Set CLAGENTIC_HOME to the parent directory (" + path.dirname(_cgHome) + ") to use the correct config.");
83
+ console.error("[daemon] Set CLAGENTIC_CONSOLE_HOME to the parent directory (" + path.dirname(_cgHome) + ") to use the correct config.");
67
84
  process.exit(78); // EX_CONFIG — do not auto-restart
68
85
  }
69
86
  } catch (_e) { /* sibling check is best-effort; fall through to normal bootstrap */ }
70
87
 
71
88
  // No config file yet (fresh install, systemd-only start). Bootstrap minimal defaults.
72
89
  console.warn("[daemon] No config file found at " + configFile + " — bootstrapping defaults. Run clagentic-console to configure projects.");
73
- var _isDev = !!(process.env.CLAGENTIC_DEV || process.env.CLAY_DEV);
90
+ var _isDev = !!readConsoleEnv("CLAGENTIC_CONSOLE_DEV");
74
91
  config = { port: _isDev ? 2635 : 2633, projects: [], mode: "single", setupCompleted: false };
75
92
  // Persist so subsequent reads succeed.
76
93
  try {
@@ -88,12 +105,16 @@ console.log("[daemon] v" + daemonVersion + " PID " + process.pid + " config " +
88
105
 
89
106
  console.log("[daemon] Config: " + configFile);
90
107
  console.log("[daemon] Users: " + usersModule.USERS_FILE);
108
+ var _projectsDirNotice = legacyNotice(resolveProjectsDir({ config: config, realHome: REAL_HOME }), configFile);
109
+ if (_projectsDirNotice) console.log(_projectsDirNotice);
91
110
  if (process.env.SUDO_USER) console.log("[daemon] SUDO_USER: " + process.env.SUDO_USER);
92
111
  console.log("[daemon] UID: " + (typeof process.getuid === "function" ? process.getuid() : "N/A"));
93
112
 
94
- // Stale-code check: if this process holds deleted inodes, the on-disk JS was
95
- // replaced by a newer install while we were running. Warn loudly so operators
96
- // know a restart is needed to load the new code.
113
+ // Whether this process maps a file an install has since unlinked. Reported by
114
+ // get_build_status for diagnosis only: an identical reinstall also unlinks the
115
+ // native module this process keeps mapped, and the marker never clears, so it
116
+ // cannot say whether the installed build differs from the loaded one. That
117
+ // verdict comes from buildIdentity (sha plus content hash).
97
118
  function checkStaleInodes() {
98
119
  if (process.platform !== 'linux') return false;
99
120
  try {
@@ -106,31 +127,15 @@ function checkStaleInodes() {
106
127
  }
107
128
  }
108
129
 
109
- // lr-dc9a3b: the SHA this process actually loaded lib/build-sha.json with at
110
- // startup, captured once here so a later re-read of the on-disk file (after
111
- // an install replaces it) can never be confused with what THIS process is
112
- // running. Read defensively — a dev checkout that has never run `npm pack`
113
- // (prepack writes this file, and it is gitignored) will not have it, and
114
- // that is a legitimate "no build-identity signal available" state, not an
115
- // error.
130
+ // The SHA this process loaded lib/build-sha.json with at startup (captured by
131
+ // buildIdentity at the top of this file), never re-read, so a later install
132
+ // replacing the file on disk can never be confused with what THIS process is
133
+ // running. null for a checkout that has never run `npm pack` (prepack writes
134
+ // the file and it is gitignored): "no build-identity signal", not an error.
116
135
  var loadedBuildSha = null;
117
- try {
118
- var _buildShaContents = fs.readFileSync(path.join(__dirname, 'build-sha.json'), 'utf8');
119
- var _buildShaParsed = JSON.parse(_buildShaContents);
120
- if (_buildShaParsed && typeof _buildShaParsed.sha === 'string') {
121
- loadedBuildSha = _buildShaParsed.sha;
122
- }
123
- } catch (_) {
124
- // lib/build-sha.json missing/unreadable/malformed — loadedBuildSha stays
125
- // null, which get_build_status reports honestly rather than guessing.
126
- }
127
-
128
- if (checkStaleInodes()) {
129
- console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
130
- console.warn('[daemon] WARNING: restart the daemon to load the new build:');
131
- console.warn('[daemon] WARNING: systemctl restart clagentic-console');
132
- console.warn('[daemon] WARNING: — or — clagentic-console --restart');
133
- }
136
+ loadedBuildSha = buildIdentity.loaded.sha;
137
+ console.log("[daemon] Build: sha=" + (loadedBuildSha || "(none)") +
138
+ " files=" + (buildIdentity.loaded.contentHash ? buildIdentity.loaded.contentHash.slice(0, 12) : "(unreadable)"));
134
139
 
135
140
 
136
141
  // --- Single-user to multi-user migration (lr-ec2d) ---
@@ -272,6 +277,14 @@ var lanIp = (function () {
272
277
 
273
278
  // getFilteredRemovedProjects extracted to daemon-projects.js
274
279
 
280
+ // --- Environment variables saved in Settings (shared and per project) ---
281
+ // A saved change reaches the runtimes started after it; a runtime already
282
+ // running keeps the environment it started with.
283
+ var envSettings = createEnvSettings({
284
+ getConfig: function () { return config; },
285
+ saveConfig: saveConfig,
286
+ });
287
+
275
288
  // --- Create multi-project server ---
276
289
  var listenHost = config.host || "0.0.0.0";
277
290
 
@@ -283,6 +296,9 @@ var relay = createServer({
283
296
  // from a reverse proxy (e.g. Caddy). Never read the header unconditionally —
284
297
  // see lib/effective-protocol.js.
285
298
  trustedProxy: !!config.trustedProxy,
299
+ // Origins besides the daemon's own host that may open a WebSocket
300
+ // (daemon.json allowedOrigins, e.g. ["https://console.example.com"]).
301
+ allowedOrigins: Array.isArray(config.allowedOrigins) ? config.allowedOrigins : [],
286
302
  port: config.port,
287
303
  debug: config.debug || false,
288
304
  dangerouslySkipPermissions: config.dangerouslySkipPermissions || false,
@@ -354,26 +370,7 @@ var relay = createServer({
354
370
  console.log("[daemon] onCreateProject wsUser:", JSON.stringify(wsUser ? { id: wsUser.id, role: wsUser.role, username: wsUser.username, linuxUser: wsUser.linuxUser } : null));
355
371
  var os = require("os");
356
372
  var execFileSync = require("child_process").execFileSync;
357
- var baseDir;
358
- if (config.osUsers) {
359
- baseDir = "/var/clagentic/projects";
360
- } else {
361
- baseDir = config.projectsDir || (function () {
362
- var newDir = path.join(REAL_HOME, "clagentic-projects");
363
- var oldDir = path.join(REAL_HOME, "clay-projects");
364
- // One-time migration: if new dir absent but old dir exists, rename it
365
- if (!fs.existsSync(newDir) && fs.existsSync(oldDir)) {
366
- try {
367
- fs.renameSync(oldDir, newDir);
368
- console.log("[config] Renamed " + oldDir + " → " + newDir);
369
- } catch (e) {
370
- // rename failed (e.g. cross-device) — fall back to old dir to avoid data loss
371
- return oldDir;
372
- }
373
- }
374
- return newDir;
375
- })();
376
- }
373
+ var baseDir = resolveProjectsDir({ config: config, realHome: REAL_HOME }).dir;
377
374
  try { fs.mkdirSync(baseDir, { recursive: true }); } catch (e) {}
378
375
  // Generate slug and deduplicate
379
376
  var slugs = config.projects.map(function (p) { return p.slug; });
@@ -451,26 +448,7 @@ var relay = createServer({
451
448
  var os = require("os");
452
449
  var spawn = require("child_process").spawn;
453
450
  var execFileSync = require("child_process").execFileSync;
454
- var baseDir;
455
- if (config.osUsers) {
456
- baseDir = "/var/clagentic/projects";
457
- } else {
458
- baseDir = config.projectsDir || (function () {
459
- var newDir = path.join(REAL_HOME, "clagentic-projects");
460
- var oldDir = path.join(REAL_HOME, "clay-projects");
461
- // One-time migration: if new dir absent but old dir exists, rename it
462
- if (!fs.existsSync(newDir) && fs.existsSync(oldDir)) {
463
- try {
464
- fs.renameSync(oldDir, newDir);
465
- console.log("[config] Renamed " + oldDir + " → " + newDir);
466
- } catch (e) {
467
- // rename failed (e.g. cross-device) — fall back to old dir to avoid data loss
468
- return oldDir;
469
- }
470
- }
471
- return newDir;
472
- })();
473
- }
451
+ var baseDir = resolveProjectsDir({ config: config, realHome: REAL_HOME }).dir;
474
452
  try { fs.mkdirSync(baseDir, { recursive: true }); } catch (e) {}
475
453
  // Derive slug from repo URL
476
454
  var repoName = cloneUrl.replace(/\.git$/, "").split("/").pop() || "project";
@@ -911,6 +889,7 @@ var relay = createServer({
911
889
  } else {
912
890
  delete config.projects[oi].ownerId;
913
891
  }
892
+ removeEnvrcOnOwnerChange(config.projects[oi], oldOwnerId, ownerId);
914
893
  break;
915
894
  }
916
895
  }
@@ -944,40 +923,10 @@ var relay = createServer({
944
923
  });
945
924
  return { ok: true };
946
925
  },
947
- onGetProjectEnv: function (slug) {
948
- for (var ei = 0; ei < config.projects.length; ei++) {
949
- if (config.projects[ei].slug === slug) {
950
- return { envrc: config.projects[ei].envrc || "" };
951
- }
952
- }
953
- return { envrc: "" };
954
- },
955
- onSetProjectEnv: function (slug, envrc) {
956
- for (var ei = 0; ei < config.projects.length; ei++) {
957
- if (config.projects[ei].slug === slug) {
958
- if (envrc) {
959
- config.projects[ei].envrc = envrc;
960
- } else {
961
- delete config.projects[ei].envrc;
962
- }
963
- saveConfig(config);
964
- return { ok: true };
965
- }
966
- }
967
- return { ok: false, error: "Project not found" };
968
- },
969
- onGetSharedEnv: function () {
970
- return { envrc: config.sharedEnv || "" };
971
- },
972
- onSetSharedEnv: function (envrc) {
973
- if (envrc) {
974
- config.sharedEnv = envrc;
975
- } else {
976
- delete config.sharedEnv;
977
- }
978
- saveConfig(config);
979
- return { ok: true };
980
- },
926
+ onGetProjectEnv: envSettings.onGetProjectEnv,
927
+ onSetProjectEnv: envSettings.onSetProjectEnv,
928
+ onGetSharedEnv: envSettings.onGetSharedEnv,
929
+ onSetSharedEnv: envSettings.onSetSharedEnv,
981
930
  onGetServerDefaultEffort: function () {
982
931
  return { effort: config.defaultEffort || null };
983
932
  },
@@ -1225,34 +1174,36 @@ var relay = createServer({
1225
1174
  return { ok: true, autoContinueOnRateLimit: want };
1226
1175
  },
1227
1176
  onSetMemAvailableThreshold: function (mb) {
1228
- var val = parseInt(mb, 10);
1229
1177
  // lr-93e3c8 (item 6): out-of-range used to silently reset to the
1230
1178
  // default and still report ok:true -- a UX trap on the exact knob an
1231
1179
  // operator reaches for while already blocked by this same guard.
1232
1180
  // Reject and report instead of silently substituting a value the
1233
- // caller didn't ask for.
1234
- if (isNaN(val) || val < 0) {
1235
- console.warn("[daemon] MemAvailable threshold rejected: " + mb + " (must be a number >= 0)");
1236
- return { ok: false, error: "Value must be a number >= 0", memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB };
1237
- }
1238
- config.memAvailableMinMB = val;
1181
+ // caller didn't ask for. Validation lives in memory-setting-validate.js
1182
+ // so this contract can't drift from the raw IPC path (lr-553d27).
1183
+ var result = validateMemAvailableThresholdMB(mb);
1184
+ if (!result.ok) {
1185
+ console.warn("[daemon] MemAvailable threshold rejected: " + mb + " (" + result.error + ")");
1186
+ return { ok: false, error: result.error, memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB };
1187
+ }
1188
+ config.memAvailableMinMB = result.value;
1239
1189
  saveConfig(config);
1240
- console.log("[daemon] MemAvailable threshold:", val, "MB (web)");
1241
- return { ok: true, memAvailableMinMB: val };
1190
+ console.log("[daemon] MemAvailable threshold:", result.value, "MB (web)");
1191
+ return { ok: true, memAvailableMinMB: result.value };
1242
1192
  },
1243
1193
  onSetTokensPerMbHeadroom: function (tpm) {
1244
- var val = parseInt(tpm, 10);
1245
1194
  // lr-93e3c8 (item 6): valid range 10-500 tokens/MB. Out-of-range used to
1246
1195
  // silently clamp to the default and still report ok:true -- see comment
1247
- // on onSetMemAvailableThreshold above; same trap, same fix.
1248
- if (isNaN(val) || val < 10 || val > 500) {
1249
- console.warn("[daemon] Tokens per MB headroom rejected: " + tpm + " (must be 10-500)");
1250
- return { ok: false, error: "Value must be 10-500", tokensPerMbHeadroom: config.tokensPerMbHeadroom !== undefined ? config.tokensPerMbHeadroom : DEFAULT_TOKENS_PER_MB_HEADROOM };
1251
- }
1252
- config.tokensPerMbHeadroom = val;
1196
+ // on onSetMemAvailableThreshold above; same trap, same fix. Validation
1197
+ // lives in memory-setting-validate.js (lr-553d27).
1198
+ var result = validateTokensPerMbHeadroom(tpm);
1199
+ if (!result.ok) {
1200
+ console.warn("[daemon] Tokens per MB headroom rejected: " + tpm + " (" + result.error + ")");
1201
+ return { ok: false, error: result.error, tokensPerMbHeadroom: config.tokensPerMbHeadroom !== undefined ? config.tokensPerMbHeadroom : DEFAULT_TOKENS_PER_MB_HEADROOM };
1202
+ }
1203
+ config.tokensPerMbHeadroom = result.value;
1253
1204
  saveConfig(config);
1254
- console.log("[daemon] Tokens per MB headroom:", val, "(web)");
1255
- return { ok: true, tokensPerMbHeadroom: val };
1205
+ console.log("[daemon] Tokens per MB headroom:", result.value, "(web)");
1206
+ return { ok: true, tokensPerMbHeadroom: result.value };
1256
1207
  },
1257
1208
  onGetToolPalettes: function () {
1258
1209
  return config.toolPalettes || {};
@@ -1297,6 +1248,20 @@ var relay = createServer({
1297
1248
  console.log("[daemon] Restart requested via web UI");
1298
1249
  spawnAndRestart();
1299
1250
  },
1251
+ // The operator's click on "Restart to apply update". Without a token it
1252
+ // answers with the offer (both builds, the commits between them, what a
1253
+ // restart would end) and restarts nothing; with the token of an offer the
1254
+ // operator was shown it schedules the restart, which waits a bounded time
1255
+ // for running turns and re-checks that nothing unseen is live. See
1256
+ // lib/build-update-restart.js. Resolves { status, offer?, note? }.
1257
+ onRestartForBuildUpdate: function (token) {
1258
+ return buildUpdateRestart.request(token);
1259
+ },
1260
+ // The standing offer state for a client that connects: the held offer, or an
1261
+ // explicit "no offer" so a client that missed a retraction drops a dead action.
1262
+ onGetBuildUpdateDiagnostic: function () {
1263
+ return buildStandingOffer.forNewClient();
1264
+ },
1300
1265
  onSetProjectVisibility: function (slug, visibility) {
1301
1266
  for (var i = 0; i < config.projects.length; i++) {
1302
1267
  if (config.projects[i].slug === slug) {
@@ -1365,17 +1330,7 @@ var relay = createServer({
1365
1330
  return { error: "Project not found" };
1366
1331
  },
1367
1332
  onGetProjectAccess: function (slug) {
1368
- for (var i = 0; i < config.projects.length; i++) {
1369
- if (config.projects[i].slug === slug) {
1370
- return {
1371
- slug: slug,
1372
- visibility: config.projects[i].visibility || (config.osUsers ? "private" : "public"),
1373
- allowedUsers: config.projects[i].allowedUsers || [],
1374
- ownerId: config.projects[i].ownerId || null,
1375
- };
1376
- }
1377
- }
1378
- return { error: "Project not found" };
1333
+ return getProjectAccessRecord(config, slug);
1379
1334
  },
1380
1335
  onUserProvisioned: function (userId, linuxUser) {
1381
1336
  // Grant ACL on all public projects to the newly provisioned user
@@ -1419,49 +1374,103 @@ var relay = createServer({
1419
1374
  },
1420
1375
  });
1421
1376
 
1422
- // Periodic stale-code check: re-emit the warning every 60 s so it appears in
1423
- // journalctl even if the operator wasn't watching at startup time.
1424
- var staleCheckHandle = setInterval(function () {
1425
- if (checkStaleInodes()) {
1426
- console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
1427
- console.warn('[daemon] WARNING: restart the daemon to load the new build:');
1428
- console.warn('[daemon] WARNING: systemctl restart clagentic-console');
1429
- console.warn('[daemon] WARNING: — or — clagentic-console --restart');
1430
- }
1431
- }, 60 * 1000);
1432
- if (staleCheckHandle && typeof staleCheckHandle.unref === "function") {
1433
- staleCheckHandle.unref();
1377
+ // --- Build adoption: is the installed build the one this process loaded? ---
1378
+ // The verdict is buildIdentity.assess() (sha plus content hash), not the
1379
+ // kernel's deleted-mapping marker. Only a stale verdict seen on consecutive
1380
+ // checks is announced: in the journal, and as an offer in the UI. Announcing
1381
+ // restarts nothing; the one path to a restart is the operator's confirmed
1382
+ // click handled by buildUpdateRestart (lib/build-update-restart.js).
1383
+ var buildHistoryRepo = resolveHistoryRepo(config.buildSourceRepo, path.join(__dirname, ".."));
1384
+
1385
+ function listChangesBetweenBuilds(range) {
1386
+ return listBuildChanges({ repo: buildHistoryRepo, fromSha: range.fromSha, toSha: range.toSha });
1434
1387
  }
1435
1388
 
1436
- var IDLE_MS = Number(process.env.CLAY_CODEX_IDLE_MS) || 5 * 60 * 1000;
1437
- var REAP_MS = Number(process.env.CLAY_CODEX_REAPER_MS) || 60 * 1000;
1438
- var reaperHandle = setInterval(function () {
1439
- if (!relay || typeof relay.forEachProject !== "function") return;
1440
- relay.forEachProject(function (ctx) {
1441
- try {
1442
- if (ctx && ctx.adapters && ctx.adapters.codex && typeof ctx.adapters.codex.shutdownIfIdle === "function") {
1443
- var result = ctx.adapters.codex.shutdownIfIdle(IDLE_MS);
1444
- if (result && typeof result.catch === "function") {
1445
- result.catch(function (e) {
1446
- console.error("[daemon] Codex idle reclaim failed:", e && e.message ? e.message : e);
1447
- });
1448
- }
1449
- }
1450
- } catch (e) {}
1389
+ function liveProjectsForOffer() {
1390
+ var out = [];
1391
+ relay.forEachProject(function (ctx, slug) {
1392
+ if (ctx && ctx.sm) out.push({ slug: slug, sm: ctx.sm });
1451
1393
  });
1452
- }, REAP_MS);
1453
- if (reaperHandle && typeof reaperHandle.unref === "function") {
1454
- reaperHandle.unref();
1394
+ return out;
1455
1395
  }
1456
1396
 
1397
+ var BUILD_CHECK_MS = Number(readConsoleEnv("CLAGENTIC_CONSOLE_BUILD_CHECK_MS")) || 60 * 1000;
1398
+ // A failed change-list read is retried no more often than the journal reminder.
1399
+ var BUILD_REMINDER_EVERY = 30;
1400
+
1401
+ // The offer clients hold is reconciled against the monitor's confirmed stale
1402
+ // assessment after every poll (lib/build-update-standing.js): it is shown,
1403
+ // refreshed or retracted to match, and only when that differs from what was
1404
+ // last shown.
1405
+ var buildStandingOffer = createStandingOffer({
1406
+ listChanges: listChangesBetweenBuilds,
1407
+ desired: function () { return buildMonitor.confirmedStale(); },
1408
+ retryAfterMs: BUILD_CHECK_MS * BUILD_REMINDER_EVERY,
1409
+ broadcast: function (message) { relay.broadcastAll(message); },
1410
+ compose: function (a, changes) {
1411
+ return {
1412
+ type: "diagnostic",
1413
+ severity: "warning",
1414
+ source: "build-update",
1415
+ message: summarizeOffer(a) + " Restart to apply it when it suits you; nothing restarts on its own.",
1416
+ buildUpdate: buildOffer({ assessment: a, changes: changes }),
1417
+ actionable: { label: "Restart to apply update", action: "restart_for_build_update" },
1418
+ };
1419
+ },
1420
+ log: function (line) { console.log("[daemon] " + line); },
1421
+ });
1422
+
1423
+ var buildUpdateRestart = createBuildUpdateRestart({
1424
+ assess: function () { return buildIdentity.assess(); },
1425
+ getProjects: liveProjectsForOffer,
1426
+ listChanges: listChangesBetweenBuilds,
1427
+ restart: function () {
1428
+ console.log("[daemon] Restarting to adopt the installed build, as the operator confirmed");
1429
+ spawnAndRestart();
1430
+ },
1431
+ waitForIdleThenAct: waitForIdleThenAct,
1432
+ announce: function (message) {
1433
+ relay.broadcastAll({ type: "diagnostic", severity: "warning", source: "build-update", message: message });
1434
+ },
1435
+ log: function (line) { console.log("[daemon] " + line); },
1436
+ });
1437
+
1438
+ var buildMonitor = createBuildMonitor({
1439
+ assess: function () { return buildIdentity.assess(); },
1440
+ log: function (line) { console.log("[daemon] " + line); },
1441
+ reminderEvery: BUILD_REMINDER_EVERY,
1442
+ });
1443
+
1444
+ function runBuildCheck() {
1445
+ try {
1446
+ buildMonitor.check();
1447
+ } catch (e) {
1448
+ // A failed check is only a missed nudge; it must never take the daemon down.
1449
+ console.error("[daemon] Build check failed (non-fatal):", e && e.message ? e.message : e);
1450
+ }
1451
+ // Reconciled after every poll, including one whose check failed: the desired
1452
+ // state is whatever the monitor last confirmed. It does not throw.
1453
+ buildStandingOffer.reconcile(buildMonitor.confirmedStale());
1454
+ }
1455
+ var buildCheckHandle = setInterval(runBuildCheck, BUILD_CHECK_MS);
1456
+ var buildFirstCheckHandle = setTimeout(runBuildCheck, Math.min(10000, BUILD_CHECK_MS));
1457
+ [buildCheckHandle, buildFirstCheckHandle].forEach(function (h) {
1458
+ if (h && typeof h.unref === "function") h.unref();
1459
+ });
1460
+
1461
+ var IDLE_MS = Number(readConsoleEnv("CLAGENTIC_CONSOLE_IDLE_RUNTIME_MS")) || 5 * 60 * 1000;
1462
+ var REAP_MS = Number(readConsoleEnv("CLAGENTIC_CONSOLE_IDLE_REAPER_MS")) || 60 * 1000;
1463
+ var stopIdleReaper = startIdleAdapterReaper(function () { return relay; }, { idleMs: IDLE_MS, intervalMs: REAP_MS });
1464
+
1457
1465
  function stopCodexReaper() {
1458
- if (reaperHandle) {
1459
- clearInterval(reaperHandle);
1460
- reaperHandle = null;
1466
+ if (stopIdleReaper) {
1467
+ stopIdleReaper();
1468
+ stopIdleReaper = null;
1461
1469
  }
1462
- if (staleCheckHandle) {
1463
- clearInterval(staleCheckHandle);
1464
- staleCheckHandle = null;
1470
+ if (buildCheckHandle) {
1471
+ clearInterval(buildCheckHandle);
1472
+ clearTimeout(buildFirstCheckHandle);
1473
+ buildCheckHandle = null;
1465
1474
  }
1466
1475
  if (_memoryWatcher) {
1467
1476
  _memoryWatcher.stop();
@@ -1470,6 +1479,9 @@ function stopCodexReaper() {
1470
1479
  }
1471
1480
 
1472
1481
  function shutdownProjects() {
1482
+ // First, before any project is destroyed: a rescan firing mid-shutdown would
1483
+ // re-add worktrees to projects that are being torn down.
1484
+ stopWorktreeRescans();
1473
1485
  stopCodexReaper();
1474
1486
  try {
1475
1487
  var result = relay.destroyAll();
@@ -1643,13 +1655,34 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1643
1655
  //
1644
1656
  // Read-only, mutates nothing, same OS-level socket gate as every other
1645
1657
  // command on this connection (CONFIG_DIR is chmod 0700).
1646
- case "get_build_status":
1658
+ case "get_build_status": {
1659
+ // state is exactly one of adopted / stale / inconclusive (with the
1660
+ // reason), from the sha and a content hash of the installed files. An
1661
+ // identical reinstall over this process is adopted; staleInodes is
1662
+ // reported for diagnosis and is not what decides it.
1663
+ var buildAssessment = buildIdentity.assess();
1647
1664
  return {
1648
1665
  ok: true,
1649
1666
  loadedBuildSha: loadedBuildSha,
1667
+ installedBuildSha: buildAssessment.installedBuildSha,
1668
+ state: buildAssessment.state,
1669
+ reason: buildAssessment.reason,
1670
+ detail: buildAssessment.detail,
1671
+ loadedContentHash: buildAssessment.loadedContentHash,
1672
+ installedContentHash: buildAssessment.installedContentHash,
1650
1673
  staleInodes: checkStaleInodes(),
1651
1674
  pid: process.pid,
1652
1675
  };
1676
+ }
1677
+
1678
+ // Open a session, or send input to one, from a caller that is not the
1679
+ // browser. The same lib/session-input.js code the external-trigger file
1680
+ // drop runs, so a request gets the same result either way. Same OS-level
1681
+ // socket gate as every command here (CONFIG_DIR is chmod 0700); input never
1682
+ // counts as a human turn (session-input.js refuses that initiator).
1683
+ case "open_session":
1684
+ case "send_session_input":
1685
+ return require("./session-input-ipc").handleSessionCommand(relay.sessionInput, msg);
1653
1686
 
1654
1687
  case "set_pin": {
1655
1688
  config.pinHash = msg.pinHash || null;
@@ -1726,22 +1759,37 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1726
1759
  return { ok: true };
1727
1760
  }
1728
1761
 
1762
+ // lr-553d27: this case used to silently clamp an out-of-range value to
1763
+ // the default and still report ok:true, diverging from the WS/web path
1764
+ // (onSetMemAvailableThreshold above), which lr-93e3c8 already fixed to
1765
+ // reject-and-report. This is the documented operator escape hatch used
1766
+ // when the UI can't save (see architecture.md "CLI <-> Daemon"), so a
1767
+ // lying ok:true here is worse than no escape hatch at all -- brought to
1768
+ // parity via the SAME validator both paths now share
1769
+ // (memory-setting-validate.js), instead of carrying a second,
1770
+ // independently-maintained copy of the range check.
1729
1771
  case "set_mem_available_threshold": {
1730
- var memMB = parseInt(msg.value, 10);
1731
- if (isNaN(memMB) || memMB < 0) memMB = DEFAULT_MEM_AVAILABLE_MIN_MB;
1732
- config.memAvailableMinMB = memMB;
1772
+ var memResult = validateMemAvailableThresholdMB(msg.value);
1773
+ if (!memResult.ok) {
1774
+ console.warn("[daemon] MemAvailable threshold rejected: " + msg.value + " (" + memResult.error + ") (cli)");
1775
+ return { ok: false, error: memResult.error, memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB };
1776
+ }
1777
+ config.memAvailableMinMB = memResult.value;
1733
1778
  saveConfig(config);
1734
- console.log("[daemon] MemAvailable threshold:", memMB, "MB (cli)");
1735
- return { ok: true, memAvailableMinMB: memMB };
1779
+ console.log("[daemon] MemAvailable threshold:", memResult.value, "MB (cli)");
1780
+ return { ok: true, memAvailableMinMB: memResult.value };
1736
1781
  }
1737
1782
 
1738
1783
  case "set_tokens_per_mb_headroom": {
1739
- var tpmVal = parseInt(msg.value, 10);
1740
- if (isNaN(tpmVal) || tpmVal < 10 || tpmVal > 500) tpmVal = DEFAULT_TOKENS_PER_MB_HEADROOM;
1741
- config.tokensPerMbHeadroom = tpmVal;
1784
+ var tpmResult = validateTokensPerMbHeadroom(msg.value);
1785
+ if (!tpmResult.ok) {
1786
+ console.warn("[daemon] Tokens per MB headroom rejected: " + msg.value + " (" + tpmResult.error + ") (cli)");
1787
+ return { ok: false, error: tpmResult.error, tokensPerMbHeadroom: config.tokensPerMbHeadroom !== undefined ? config.tokensPerMbHeadroom : DEFAULT_TOKENS_PER_MB_HEADROOM };
1788
+ }
1789
+ config.tokensPerMbHeadroom = tpmResult.value;
1742
1790
  saveConfig(config);
1743
- console.log("[daemon] Tokens per MB headroom:", tpmVal, "(cli)");
1744
- return { ok: true, tokensPerMbHeadroom: tpmVal };
1791
+ console.log("[daemon] Tokens per MB headroom:", tpmResult.value, "(cli)");
1792
+ return { ok: true, tokensPerMbHeadroom: tpmResult.value };
1745
1793
  }
1746
1794
 
1747
1795
  case "enable_recovery": {
@@ -1783,10 +1831,10 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1783
1831
  }
1784
1832
 
1785
1833
  // Production: install to global npm, then shut down so the process manager
1786
- // (systemd / clagentic-daemon.sh) restarts from the updated global install.
1787
- // This is the only reliable path — npx installs to a cache location that the
1788
- // restart wrapper does not consult, so npx-spawned daemons get replaced by the
1789
- // old global version on the next supervised restart.
1834
+ // (systemd, whose ExecStart is the global `clagentic-console daemon`) restarts
1835
+ // from the updated global install. This is the only reliable path — npx
1836
+ // installs to a cache location the unit does not consult, so npx-spawned
1837
+ // daemons get replaced by the old global version on the next supervised restart.
1790
1838
  // Resolve + install asynchronously. ipc.js awaits a returned Promise, so
1791
1839
  // returning an async IIFE here is safe without changing the outer handler.
1792
1840
  return (async function () {
@@ -1824,9 +1872,9 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1824
1872
  stdio: ["ignore", "pipe", "pipe"],
1825
1873
  timeout: 120000,
1826
1874
  encoding: "utf8",
1827
- // CLAGENTIC_SELF_UPDATE=1 tells postinstall.js not to restart the
1875
+ // CLAGENTIC_CONSOLE_SELF_UPDATE=1 tells postinstall.js not to restart the
1828
1876
  // service — gracefulShutdown() below hands off to systemd Restart=always.
1829
- env: Object.assign({}, process.env, { CLAGENTIC_SELF_UPDATE: "1" }),
1877
+ env: Object.assign({}, process.env, { CLAGENTIC_CONSOLE_SELF_UPDATE: "1" }),
1830
1878
  });
1831
1879
  console.log("[daemon] Global install complete. Shutting down for supervised restart.");
1832
1880
  updOk = true;
@@ -1886,8 +1934,20 @@ function startListening() {
1886
1934
  gracefulShutdown: gracefulShutdown,
1887
1935
  getActiveCount: getActiveLiveCount,
1888
1936
  drainTimeoutMs: drainTimeoutMs,
1937
+ onPressureChange: function (underPressure, detail) {
1938
+ relay.broadcastAll({
1939
+ type: "diagnostic",
1940
+ severity: underPressure ? "warning" : "info",
1941
+ source: "memory-pressure",
1942
+ message: underPressure
1943
+ ? "Clagentic: Console is over its memory soft limit. New sessions and agent work are paused; existing sessions keep running."
1944
+ : "Clagentic: Console memory is back under the soft limit. New sessions and agent work are accepted again.",
1945
+ detail: detail && detail.currentBytes ? "memory.current " + detail.currentBytes + " bytes" : undefined,
1946
+ });
1947
+ },
1889
1948
  });
1890
1949
  _drain.registerSignals();
1950
+ setNewWorkGate(_drain.isRefusingNewWork);
1891
1951
  // Expose the drain controller on the relay so server.js can gate new connections.
1892
1952
  relay.setDrain(_drain);
1893
1953
 
@@ -1895,11 +1955,13 @@ function startListening() {
1895
1955
  // Detects soft memory ceiling crossings and emits structured log events;
1896
1956
  // onCrossing runs an in-process shedding pass (lr-5e70) FIRST — an
1897
1957
  // immediate attempt to reduce RSS via retrim/evict/cache-drop — then
1898
- // notifies the drain controller (lr-6b30), which independently decides
1899
- // whether to refuse new connections and eventually exit. Shedding and
1900
- // drain are deliberately independent responses to the same signal: a
1901
- // shedding pass that fails or is rate-limited must never block drain
1902
- // from entering, and drain entering must never skip a shedding attempt.
1958
+ // notifies the drain controller (lr-6b30), which starts refusing new
1959
+ // sessions and agent work until onRecovery reports usage back under the
1960
+ // limit. Pressure never exits the daemon: the memory belongs to session
1961
+ // child processes a restart would only kill. Shedding and pressure are
1962
+ // deliberately independent responses to the same signal: a shedding pass
1963
+ // that fails or is rate-limited must never block pressure from entering,
1964
+ // and pressure entering must never skip a shedding attempt.
1903
1965
  if (process.platform === "linux") {
1904
1966
  _memoryWatcher = startMemoryHighWatcher(config, {
1905
1967
  onCrossing: function (detail) {
@@ -1919,6 +1981,9 @@ function startListening() {
1919
1981
  }
1920
1982
  _drain.onMemoryHighCrossing(detail);
1921
1983
  },
1984
+ onRecovery: function (detail) {
1985
+ _drain.onMemoryHighRecovery(detail);
1986
+ },
1922
1987
  });
1923
1988
 
1924
1989
  // Startup sanity check (lr-c10f6d): verify the applied cgroup memory.max
@@ -1954,7 +2019,7 @@ function startListening() {
1954
2019
  // ACLs are set when: projects are added, users are added, or visibility changes.
1955
2020
  if (config.osUsers) {
1956
2021
  setTimeout(function () {
1957
- try { ensureProjectsDir(); } catch (e) {}
2022
+ try { ensureProjectsDir(resolveProjectsDir({ config: config, realHome: REAL_HOME }).dir); } catch (e) {}
1958
2023
  try {
1959
2024
  var provResult = provisionAllUsers(usersModule);
1960
2025
  if (provResult.provisioned.length > 0) {
@@ -2016,7 +2081,12 @@ relay.server.on("error", function (err) {
2016
2081
  process.exit(1);
2017
2082
  });
2018
2083
 
2019
- startListening();
2084
+ // Every prompt is parsed and keyed by modules the registry imports, so no
2085
+ // client is served until they are in; a daemon that cannot load them stops.
2086
+ promptRegistry.ready().then(startListening, function (err) {
2087
+ console.error("[daemon] " + (err && err.message ? err.message : err));
2088
+ process.exit(1);
2089
+ });
2020
2090
 
2021
2091
  // --- HTTP onboarding server (only when TLS is active) ---
2022
2092
  if (relay.onboardingServer) {
@@ -2047,6 +2117,17 @@ if (config.keepAwake && process.platform === "darwin") {
2047
2117
 
2048
2118
  // --- Spawn new daemon and graceful restart ---
2049
2119
  function spawnAndRestart() {
2120
+ // Under a supervisor the restart is an exit and nothing more. A replacement
2121
+ // spawned here is not the unit's main process, so the unit kills it with the
2122
+ // rest of its cgroup and then starts its own: one extra process killed, the
2123
+ // restart working only by accident. Self-respawn is for unsupervised starts.
2124
+ if (isSupervised()) {
2125
+ console.log("[daemon] Running under a supervisor: exiting with code " + RESTART_EXIT_CODE +
2126
+ " for it to start the replacement; not spawning one");
2127
+ updateHandoff = true;
2128
+ gracefulShutdown();
2129
+ return;
2130
+ }
2050
2131
  try {
2051
2132
  updateHandoff = true;
2052
2133
  ipc.close();
@@ -2064,13 +2145,14 @@ function spawnAndRestart() {
2064
2145
  detached: true,
2065
2146
  windowsHide: true,
2066
2147
  stdio: ["ignore", logFd, logFd],
2067
- env: Object.assign({}, process.env, {
2068
- CLAGENTIC_CONFIG: restartConfigPath(),
2069
- CLAGENTIC_HOME: restartClagenticHome,
2148
+ env: Object.assign(unsupervisedEnv(), {
2149
+ CLAGENTIC_CONSOLE_CONFIG: restartConfigPath(),
2150
+ CLAGENTIC_CONSOLE_HOME: restartClagenticHome,
2070
2151
  }),
2071
2152
  });
2072
2153
  child.unref();
2073
2154
  fs.closeSync(logFd);
2155
+ successorSpawned = true;
2074
2156
  config.pid = child.pid;
2075
2157
  // Write PID synchronously before exit so the config file is not
2076
2158
  // left with a stale PID during the restart window. saveConfig() is
@@ -2083,7 +2165,7 @@ function spawnAndRestart() {
2083
2165
  saveConfig(config);
2084
2166
  }
2085
2167
  console.log("[daemon] Spawned new daemon (PID " + child.pid + "), exiting.");
2086
- process.exit(120);
2168
+ process.exit(RESTART_EXIT_CODE);
2087
2169
  } catch (e) {
2088
2170
  console.error("[daemon] Restart failed:", e.message);
2089
2171
  process.exit(1);
@@ -2110,14 +2192,15 @@ function spawnAndRestart() {
2110
2192
  }
2111
2193
 
2112
2194
  // --- Graceful shutdown ---
2113
- var updateHandoff = false; // true when shutting down for update (new daemon already spawned)
2195
+ var updateHandoff = false; // true when shutting down to be replaced (exit code RESTART_EXIT_CODE)
2196
+ var successorSpawned = false; // true once a self-spawned replacement has its pid saved in the config
2114
2197
  var shutdownStarted = false;
2115
2198
 
2116
2199
  function gracefulShutdown() {
2117
2200
  try { console.log("[daemon] Shutting down..."); } catch (e) {}
2118
2201
  if (shutdownStarted) return;
2119
2202
  shutdownStarted = true;
2120
- var exitCode = updateHandoff ? 120 : 0; // 120 = update handoff, don't auto-restart
2203
+ var exitCode = updateHandoff ? RESTART_EXIT_CODE : 0;
2121
2204
 
2122
2205
  if (caffeinateProc) {
2123
2206
  try { caffeinateProc.kill(); } catch (e) {}
@@ -2125,8 +2208,8 @@ function gracefulShutdown() {
2125
2208
 
2126
2209
  ipc.close();
2127
2210
 
2128
- // Remove PID from config (skip if update handoff — new daemon PID is already saved)
2129
- if (!updateHandoff) {
2211
+ // Remove PID from config (skip when a self-spawned replacement's PID is already saved)
2212
+ if (!successorSpawned) {
2130
2213
  try {
2131
2214
  var c = loadConfig();
2132
2215
  if (c && c.pid === process.pid) {