@clagentic/console 1.5.0-beta.1 → 1.5.0-beta.3

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.
package/README.md CHANGED
@@ -35,6 +35,16 @@ npx @clagentic/console
35
35
 
36
36
  **Requirements:** Node.js 20+. Authenticated Claude Code CLI, Codex CLI, or both.
37
37
 
38
+ ### Postinstall / systemd
39
+
40
+ On Linux, a global npm install runs a postinstall script that registers and enables a `clagentic-console.service` systemd unit. The script never restarts an already-running daemon — active sessions are not interrupted. Self-updates triggered from inside the app skip the restart entirely and let systemd's `Restart=always` handle the handoff after graceful shutdown.
41
+
42
+ To skip the postinstall script:
43
+
44
+ ```bash
45
+ npm install -g @clagentic/console --ignore-scripts
46
+ ```
47
+
38
48
  ## What it does
39
49
 
40
50
  - **Named agent sessions.** Type `@` in the session input to launch any agent defined in `.claude/agents/` or `~/.claude/agents/` into its own session — with its own conversation history, context window, and state. Pick agents by name, switch mid-conversation.
@@ -124,6 +134,39 @@ graph LR
124
134
 
125
135
  For architecture details, sequence diagrams, and key design decisions, see [docs/guides/architecture.md](docs/guides/architecture.md).
126
136
 
137
+ ## Security
138
+
139
+ These are implementation-level properties, not configuration options — they apply to every installation.
140
+
141
+ - **Token TTL.** Multi-user auth tokens expire after 30 days (`TOKEN_TTL_MS`). Tokens issued before TTL support was added are migrated on first use to a fresh 30-day window, avoiding forced logouts on upgrade.
142
+
143
+ - **Atomic writes, mode 0o600.** All config and state files (`users.json`, `auth-tokens.json`, and similar) are written via rename-after-write: data goes to a `.tmp.<pid>` path, then `rename()` atomically replaces the target. After rename, `chmod 0o600` is applied. Concurrent writes to the same file are serialized in call order.
144
+
145
+ - **Append-only audit log.** Privileged actions — user creation, lockouts, token revocation, multi-user enable/disable — are written as newline-delimited JSON to `~/.clagentic/audit.log` (mode 0o600, opened with `O_APPEND`).
146
+
147
+ - **Progressive lockout.** Failed login attempts trigger escalating per-username backoff: 1s, 5s, 30s, 5 min. Reaching the threshold results in permanent lockout until an admin explicitly unlocks the account. Per-IP rate limiting runs in parallel.
148
+
149
+ - **OS-level isolation (Linux, multi-user mode).** Each app user maps to a real system account. File ACLs are set via `setfacl`; processes spawn under the correct UID/GID.
150
+
151
+ ## Testing
152
+
153
+ The test suite covers 12 areas across 26 test files:
154
+
155
+ - **Boot / smoke** — daemon startup, config bootstrap, guard checks
156
+ - **Security gates** — auth token TTL, lockout thresholds, PIN rate limiting, audit log entries
157
+ - **WebSocket permission gates** — per-user RBAC enforcement on WS message types
158
+ - **Session lifecycle** — session open, resume, shutdown, and reaper behavior
159
+ - **External triggers** — v1 and v2 trigger processing, file archival, restart survival
160
+ - **Scheduler** — cron parsing, loop execution, run accounting
161
+ - **Store atomicity** — concurrent write serialization, atomic rename, 0o600 mode
162
+ - **XSS escaping** — output sanitization for user-controlled strings rendered in HTML
163
+ - **YOKE robustness** — vendor adapter error handling and fallback paths
164
+ - **SDK bridge** — slot counter, message processor, slash command enrichment, workflow and skill discovery, worker shutdown
165
+ - **Replay** — session replay correctness
166
+ - **ESM import check** — verifies the package is importable as an ES module
167
+
168
+ Run the suite: `npm test`
169
+
127
170
  ## FAQ
128
171
 
129
172
  **"Is this a Claude Code wrapper?"**
package/bin/cli.js CHANGED
@@ -31,7 +31,7 @@ if (_isDev || process.argv.includes("--debug")) {
31
31
  }
32
32
 
33
33
  var crypto = require("crypto");
34
- var { loadConfig, saveConfig, configPath, socketPath, oldSocketPath, logPath, ensureConfigDir, isDaemonAlive, isDaemonAliveAsync, checkOldDaemon, generateSlug, clearStaleConfig, loadClayrc, saveClayrc, readCrashInfo, REAL_HOME } = require("../lib/config");
34
+ var { loadConfig, saveConfig, configPath, socketPath, oldSocketPath, logPath, ensureConfigDir, isDaemonAlive, isDaemonAliveAsync, checkOldDaemon, generateSlug, clearStaleConfig, loadClayrc, saveClayrc, readCrashInfo, REAL_HOME, CONFIG_DIR, CLAGENTIC_HOME } = require("../lib/config");
35
35
  var { sendIPCCommand } = require("../lib/ipc");
36
36
  var { generateAuthToken } = require("../lib/server");
37
37
  var { enableMultiUser, disableMultiUser, hasAdmin, isMultiUser, getSetupCode } = require("../lib/users");
@@ -349,6 +349,7 @@ var a = {
349
349
  green: "\x1b[32m",
350
350
  yellow: "\x1b[33m",
351
351
  red: "\x1b[31m",
352
+ cyan: "\x1b[36m",
352
353
  };
353
354
 
354
355
  function gradient(text) {
@@ -523,6 +524,7 @@ async function restartDaemonFromConfig() {
523
524
  // Debug mode: run in foreground with logs to stdout
524
525
  if (debugMode) {
525
526
  process.env.CLAGENTIC_CONFIG = configPath();
527
+ process.env.CLAGENTIC_HOME = CLAGENTIC_HOME;
526
528
  newConfig.pid = process.pid;
527
529
  saveConfig(newConfig);
528
530
  require(daemonScript);
@@ -538,6 +540,7 @@ async function restartDaemonFromConfig() {
538
540
  stdio: ["ignore", logFd, logFd],
539
541
  env: Object.assign({}, process.env, {
540
542
  CLAGENTIC_CONFIG: configPath(),
543
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
541
544
  }),
542
545
  });
543
546
  child.unref();
@@ -1624,6 +1627,7 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers) {
1624
1627
  // Debug mode: run in foreground with logs to stdout
1625
1628
  if (debugMode) {
1626
1629
  process.env.CLAGENTIC_CONFIG = configPath();
1630
+ process.env.CLAGENTIC_HOME = CLAGENTIC_HOME;
1627
1631
  config.pid = process.pid;
1628
1632
  saveConfig(config);
1629
1633
  require(daemonScript);
@@ -1639,6 +1643,7 @@ async function forkDaemon(mode, keepAwake, extraProjects, addCwd, wantOsUsers) {
1639
1643
  stdio: ["ignore", logFd, logFd],
1640
1644
  env: Object.assign({}, process.env, {
1641
1645
  CLAGENTIC_CONFIG: configPath(),
1646
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
1642
1647
  }),
1643
1648
  });
1644
1649
  child.unref();
@@ -1827,6 +1832,7 @@ async function devMode(mode, keepAwake, existingPinHash, wantOsUsers) {
1827
1832
  stdio: ["ignore", "inherit", "inherit"],
1828
1833
  env: Object.assign({}, process.env, {
1829
1834
  CLAGENTIC_CONFIG: configPath(),
1835
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
1830
1836
  }),
1831
1837
  });
1832
1838
 
@@ -1988,6 +1994,7 @@ async function restartDaemonWithTLS(config, callback) {
1988
1994
  stdio: ["ignore", logFd, logFd],
1989
1995
  env: Object.assign({}, process.env, {
1990
1996
  CLAGENTIC_CONFIG: configPath(),
1997
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
1991
1998
  }),
1992
1999
  });
1993
2000
  child.unref();
@@ -2014,6 +2021,7 @@ async function restartDaemonWithTLS(config, callback) {
2014
2021
  stdio: ["ignore", logFd2, logFd2],
2015
2022
  env: Object.assign({}, process.env, {
2016
2023
  CLAGENTIC_CONFIG: configPath(),
2024
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
2017
2025
  }),
2018
2026
  });
2019
2027
  child2.unref();
package/lib/audit.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // audit.js — Append-only audit log for privileged actions.
2
- // Writes JSON lines to ~/.clagentic/audit.log (mode 0o600).
2
+ // Writes JSON lines to ~/.clagentic/console/audit.log (CONFIG_DIR/audit.log, mode 0o600).
3
3
  // Never throws into callers: all errors are logged to stderr only.
4
4
 
5
5
  var fs = require("fs");
@@ -7,6 +7,24 @@ var path = require("path");
7
7
  var config = require("./config");
8
8
 
9
9
  var AUDIT_LOG_PATH = path.join(config.CONFIG_DIR, "audit.log");
10
+ var OLD_AUDIT_LOG_PATH = path.join(config.CONFIG_DIR, "..", "audit.log");
11
+
12
+ // One-time migration: copy old audit.log to new location if new is absent.
13
+ // Copy-not-rename so rollback still finds the old file.
14
+ // Only runs if CLAGENTIC_HOME is not explicitly set (default layout).
15
+ // Note: this runs at module load time, potentially before ensureConfigDir() creates
16
+ // console/ — so we ensure the parent dir exists ourselves before copying.
17
+ if (!process.env.CLAGENTIC_HOME && !fs.existsSync(AUDIT_LOG_PATH) && fs.existsSync(OLD_AUDIT_LOG_PATH)) {
18
+ try {
19
+ fs.mkdirSync(path.dirname(AUDIT_LOG_PATH), { recursive: true });
20
+ fs.copyFileSync(OLD_AUDIT_LOG_PATH, AUDIT_LOG_PATH);
21
+ try { fs.chmodSync(AUDIT_LOG_PATH, 0o600); } catch (_) {}
22
+ console.warn("[audit] Migrated audit.log to ~/.clagentic/console/audit.log");
23
+ } catch (e) {
24
+ console.error("[audit] Migration of audit.log failed (non-fatal):", e.message);
25
+ }
26
+ }
27
+
10
28
  var _logFd = null;
11
29
 
12
30
  function _getLogFd() {
@@ -54,4 +72,7 @@ function log(action, ctx) {
54
72
  });
55
73
  }
56
74
 
57
- module.exports = { log: log };
75
+ module.exports = {
76
+ log: log,
77
+ auditLogPath: function () { return AUDIT_LOG_PATH; },
78
+ };
package/lib/config.js CHANGED
@@ -44,15 +44,53 @@ var CLAGENTIC_HOME = process.env.CLAGENTIC_HOME
44
44
  var OLD_CLAY_HOME = path.join(REAL_HOME, ".clay");
45
45
  if (!fs.existsSync(CLAGENTIC_HOME) && fs.existsSync(OLD_CLAY_HOME)) {
46
46
  try {
47
- fs.cpSync(OLD_CLAY_HOME, CLAGENTIC_HOME, { recursive: true });
47
+ fs.cpSync(OLD_CLAY_HOME, CLAGENTIC_HOME, { recursive: true, preserveTimestamps: true });
48
48
  console.log("[config] Migrated " + OLD_CLAY_HOME + " → " + CLAGENTIC_HOME + " — ~/.clay/ can be deleted when verified");
49
49
  } catch (e) {
50
50
  console.error("[config] Migration failed:", e.message);
51
51
  }
52
52
  }
53
53
 
54
- var CONFIG_DIR = CLAGENTIC_HOME;
54
+ // One-time migration: copy all Console data from ~/.clagentic/ root into
55
+ // ~/.clagentic/console/ if not yet done.
56
+ //
57
+ // Sentinel: console/.migrated marker file. Using sessions/ directory existence
58
+ // as the sentinel is wrong — partial earlier migrations (lr-5dca, lr-eb5a)
59
+ // created console/sessions/ before this full sweep ran, causing the sentinel
60
+ // to fire too early and leaving any sessions written after that point orphaned.
61
+ // A marker file written only at sweep completion is the correct pattern
62
+ // (same as how ~/.clay/ → ~/.clagentic/ worked: gated on destination absence).
63
+ //
64
+ // Skip-if-dest-exists for each entry so files already in console/ from
65
+ // earlier partial migrations are preserved.
66
+ var _consoleMigrated = path.join(CLAGENTIC_HOME, "console", ".migrated");
67
+ if (!fs.existsSync(_consoleMigrated) && fs.existsSync(CLAGENTIC_HOME)) {
68
+ try {
69
+ fs.mkdirSync(path.join(CLAGENTIC_HOME, "console"), { recursive: true });
70
+ // cpSync cannot copy a dir into one of its own subdirs — iterate entries
71
+ // individually and skip the console/ subdir itself to avoid recursion.
72
+ var _rootEntries = fs.readdirSync(CLAGENTIC_HOME);
73
+ for (var _ri = 0; _ri < _rootEntries.length; _ri++) {
74
+ if (_rootEntries[_ri] === "console") continue;
75
+ var _src = path.join(CLAGENTIC_HOME, _rootEntries[_ri]);
76
+ var _dst = path.join(CLAGENTIC_HOME, "console", _rootEntries[_ri]);
77
+ if (!fs.existsSync(_dst)) {
78
+ try { fs.cpSync(_src, _dst, { recursive: true, preserveTimestamps: true }); } catch (_ce) {}
79
+ }
80
+ }
81
+ // Write sentinel only after the sweep completes so a crash mid-sweep
82
+ // causes a retry on next start rather than silently leaving data behind.
83
+ fs.writeFileSync(_consoleMigrated, "");
84
+ console.log("[config] Migrated ~/.clagentic/ → ~/.clagentic/console/ — root files can be cleaned up when verified");
85
+ } catch (e) {
86
+ console.error("[config] Migration to console/ subdir failed:", e.message);
87
+ }
88
+ }
89
+
90
+ var CONSOLE_DIR = path.join(CLAGENTIC_HOME, "console");
91
+ var CONFIG_DIR = CONSOLE_DIR;
55
92
  var EXTERNAL_TRIGGERS_DIR = path.join(CONFIG_DIR, "external-triggers");
93
+ var OLD_EXTERNAL_TRIGGERS_DIR = path.join(CLAGENTIC_HOME, "external-triggers");
56
94
  var OLD_CLAYRC = path.join(REAL_HOME, ".clayrc");
57
95
  var CLAGENTIC_RC_PATH = path.join(REAL_HOME, ".clagentic-rc");
58
96
  // One-time migration: copy .clayrc → .clagentic-rc if new file absent
@@ -60,6 +98,7 @@ if (!fs.existsSync(CLAGENTIC_RC_PATH) && fs.existsSync(OLD_CLAYRC)) {
60
98
  try { fs.copyFileSync(OLD_CLAYRC, CLAGENTIC_RC_PATH); } catch (e) {}
61
99
  }
62
100
  var CRASH_INFO_PATH = path.join(CONFIG_DIR, "crash.json");
101
+ var OLD_CRASH_INFO_PATH = path.join(CLAGENTIC_HOME, "crash.json");
63
102
 
64
103
  // Dev mode uses separate daemon files so dev and prod can run simultaneously
65
104
  var _devMode = !!(process.env.CLAGENTIC_DEV || process.env.CLAY_DEV);
@@ -68,25 +107,35 @@ function configPath() {
68
107
  return path.join(CONFIG_DIR, _devMode ? "daemon-dev.json" : "daemon.json");
69
108
  }
70
109
 
110
+ // Path used before lr-12d0 moved CONFIG_DIR to console/ (was CLAGENTIC_HOME root).
111
+ function oldConfigPath() {
112
+ return path.join(CLAGENTIC_HOME, _devMode ? "daemon-dev.json" : "daemon.json");
113
+ }
114
+
71
115
  function socketPath() {
72
116
  if (process.platform === "win32") {
73
117
  var pipeName = _devMode ? "clagentic-daemon-dev" : "clagentic-daemon";
74
118
  return "\\\\.\\pipe\\" + pipeName;
75
119
  }
76
- return path.join(CONFIG_DIR, "console", _devMode ? "daemon-dev.sock" : "daemon.sock");
120
+ return path.join(CONFIG_DIR, _devMode ? "daemon-dev.sock" : "daemon.sock");
77
121
  }
78
122
 
79
- // Path used by pre-1.5 daemons (before lr-88fe moved the socket into console/).
80
- // Only meaningful on Unix — Windows named pipes were unchanged by lr-88fe.
123
+ // Path used by pre-lr-12d0 daemons (before CONFIG_DIR moved to console/).
124
+ // Only meaningful on Unix — Windows named pipes were unchanged.
81
125
  function oldSocketPath() {
82
126
  if (process.platform === "win32") return null;
83
- return path.join(CONFIG_DIR, _devMode ? "daemon-dev.sock" : "daemon.sock");
127
+ return path.join(CLAGENTIC_HOME, _devMode ? "daemon-dev.sock" : "daemon.sock");
84
128
  }
85
129
 
86
130
  function logPath() {
87
131
  return path.join(CONFIG_DIR, _devMode ? "daemon-dev.log" : "daemon.log");
88
132
  }
89
133
 
134
+ // Path used by pre-lr-12d0 daemons (before CONFIG_DIR moved to console/).
135
+ function oldLogPath() {
136
+ return path.join(CLAGENTIC_HOME, _devMode ? "daemon-dev.log" : "daemon.log");
137
+ }
138
+
90
139
  function chmodSafe(filePath, mode) {
91
140
  if (process.platform === "win32") return;
92
141
  try { fs.chmodSync(filePath, mode); } catch (e) {}
@@ -95,8 +144,128 @@ function chmodSafe(filePath, mode) {
95
144
  function ensureConfigDir() {
96
145
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
97
146
  chmodSafe(CONFIG_DIR, 0o700);
98
- fs.mkdirSync(path.join(CONFIG_DIR, "console"), { recursive: true });
99
- chmodSafe(path.join(CONFIG_DIR, "console"), 0o700);
147
+ // One-time migrations: copy Console-owned runtime files to console/ subdir.
148
+ // Rules: copy-not-rename (rollback safety), never overwrite newer dest,
149
+ // non-fatal on permission errors, skip when CLAGENTIC_HOME is custom.
150
+ if (!process.env.CLAGENTIC_HOME) {
151
+ // daemon.log / daemon-dev.log
152
+ var oldLog = oldLogPath();
153
+ var newLog = logPath();
154
+ if (fs.existsSync(oldLog) && !fs.existsSync(newLog)) {
155
+ try {
156
+ fs.copyFileSync(oldLog, newLog);
157
+ console.warn("[config] Migrated " + oldLog + " → " + newLog);
158
+ } catch (e) {
159
+ console.error("[config] Migration of daemon log failed (non-fatal):", e.message);
160
+ }
161
+ }
162
+ // crash.json
163
+ if (fs.existsSync(OLD_CRASH_INFO_PATH) && !fs.existsSync(CRASH_INFO_PATH)) {
164
+ try {
165
+ fs.copyFileSync(OLD_CRASH_INFO_PATH, CRASH_INFO_PATH);
166
+ try { fs.chmodSync(CRASH_INFO_PATH, 0o600); } catch (_) {}
167
+ console.warn("[config] Migrated crash.json → " + CRASH_INFO_PATH);
168
+ } catch (e) {
169
+ console.error("[config] Migration of crash.json failed (non-fatal):", e.message);
170
+ }
171
+ }
172
+ // external-triggers/
173
+ // Use lstatSync (not existsSync) so a pre-existing symlink at the old path is
174
+ // detected and skipped — we only act on a real directory.
175
+ var _oldTriggersIsRealDir = false;
176
+ try {
177
+ var _oldStat = fs.lstatSync(OLD_EXTERNAL_TRIGGERS_DIR);
178
+ _oldTriggersIsRealDir = _oldStat.isDirectory() && !_oldStat.isSymbolicLink();
179
+ } catch (_) {}
180
+ if (_oldTriggersIsRealDir) {
181
+ if (!fs.existsSync(EXTERNAL_TRIGGERS_DIR)) {
182
+ // Case 1: new dir absent — simple copy (existing behavior).
183
+ try {
184
+ fs.cpSync(OLD_EXTERNAL_TRIGGERS_DIR, EXTERNAL_TRIGGERS_DIR, { recursive: true });
185
+ console.warn("[config] Migrated external-triggers/ → " + EXTERNAL_TRIGGERS_DIR);
186
+ } catch (e) {
187
+ console.error("[config] Migration of external-triggers/ failed (non-fatal):", e.message);
188
+ }
189
+ } else {
190
+ // Case 2: both old and new exist — merge .json files from old that are not
191
+ // already present in new (by filename), then replace the old dir with a
192
+ // symlink → EXTERNAL_TRIGGERS_DIR so stale writers (e.g. an un-updated relay
193
+ // binary still writing to the old root path) are silently redirected.
194
+ try {
195
+ // Merge top-level .json files.
196
+ var _oldFiles = fs.readdirSync(OLD_EXTERNAL_TRIGGERS_DIR);
197
+ for (var _oi = 0; _oi < _oldFiles.length; _oi++) {
198
+ var _oldFile = _oldFiles[_oi];
199
+ if (_oldFile === "processed") continue; // handled separately below
200
+ if (path.extname(_oldFile) !== ".json") continue;
201
+ var _oldFilePath = path.join(OLD_EXTERNAL_TRIGGERS_DIR, _oldFile);
202
+ var _newFilePath = path.join(EXTERNAL_TRIGGERS_DIR, _oldFile);
203
+ if (!fs.existsSync(_newFilePath)) {
204
+ try {
205
+ fs.copyFileSync(_oldFilePath, _newFilePath);
206
+ console.warn("[config] Merged external-triggers/" + _oldFile + " → " + _newFilePath);
207
+ } catch (_ce) {
208
+ console.error("[config] Merge of " + _oldFile + " failed (non-fatal):", _ce.message);
209
+ }
210
+ }
211
+ }
212
+ // Merge processed/ subdir files.
213
+ var _oldProcessedDir = path.join(OLD_EXTERNAL_TRIGGERS_DIR, "processed");
214
+ var _newProcessedDir = path.join(EXTERNAL_TRIGGERS_DIR, "processed");
215
+ if (fs.existsSync(_oldProcessedDir)) {
216
+ try { fs.mkdirSync(_newProcessedDir, { recursive: true }); } catch (_) {}
217
+ var _oldProcessed = fs.readdirSync(_oldProcessedDir);
218
+ for (var _pi = 0; _pi < _oldProcessed.length; _pi++) {
219
+ var _pf = _oldProcessed[_pi];
220
+ if (path.extname(_pf) !== ".json") continue;
221
+ var _oldPfPath = path.join(_oldProcessedDir, _pf);
222
+ var _newPfPath = path.join(_newProcessedDir, _pf);
223
+ if (!fs.existsSync(_newPfPath)) {
224
+ try {
225
+ fs.copyFileSync(_oldPfPath, _newPfPath);
226
+ console.warn("[config] Merged external-triggers/processed/" + _pf + " → " + _newPfPath);
227
+ } catch (_ce2) {
228
+ console.error("[config] Merge of processed/" + _pf + " failed (non-fatal):", _ce2.message);
229
+ }
230
+ }
231
+ }
232
+ }
233
+ // Replace old dir with a symlink → EXTERNAL_TRIGGERS_DIR. Rename to a temp
234
+ // name first, create the symlink, then remove the temp. Non-fatal: on any
235
+ // failure we best-effort restore the original name and leave for manual cleanup.
236
+ var _oldTriggersTmp = OLD_EXTERNAL_TRIGGERS_DIR + ".migration-tmp";
237
+ try {
238
+ fs.renameSync(OLD_EXTERNAL_TRIGGERS_DIR, _oldTriggersTmp);
239
+ fs.symlinkSync(EXTERNAL_TRIGGERS_DIR, OLD_EXTERNAL_TRIGGERS_DIR);
240
+ fs.rmSync(_oldTriggersTmp, { recursive: true, force: true });
241
+ console.warn("[config] Replaced " + OLD_EXTERNAL_TRIGGERS_DIR + " with symlink → " + EXTERNAL_TRIGGERS_DIR);
242
+ } catch (_se) {
243
+ console.error("[config] Symlink replacement of external-triggers/ failed (non-fatal):", _se.message);
244
+ try {
245
+ if (!fs.existsSync(OLD_EXTERNAL_TRIGGERS_DIR)) {
246
+ fs.renameSync(_oldTriggersTmp, OLD_EXTERNAL_TRIGGERS_DIR);
247
+ }
248
+ } catch (_re) {}
249
+ }
250
+ } catch (e) {
251
+ console.error("[config] Migration merge of external-triggers/ failed (non-fatal):", e.message);
252
+ }
253
+ }
254
+ }
255
+ // daemon.json / daemon-dev.json (lr-eb5a: moved into console/)
256
+ var oldCfg = oldConfigPath();
257
+ var newCfg = configPath();
258
+ if (fs.existsSync(oldCfg) && !fs.existsSync(newCfg)) {
259
+ try {
260
+ fs.copyFileSync(oldCfg, newCfg);
261
+ try { fs.chmodSync(newCfg, 0o600); } catch (_) {}
262
+ console.warn("[config] Migrated " + oldCfg + " → " + newCfg);
263
+ } catch (e) {
264
+ console.error("[config] Migration of daemon.json failed (non-fatal):", e.message);
265
+ }
266
+ }
267
+ }
268
+
100
269
  // Guard stale old socket cleanup: only unlink when the old-path daemon is
101
270
  // dead. If a live pre-1.5 daemon is still on that path we must not yank its
102
271
  // socket out from under it — warn instead so the operator can shut it down
@@ -377,11 +546,14 @@ function removeFromClayrc(projectPath) {
377
546
 
378
547
  module.exports = {
379
548
  CONFIG_DIR: CONFIG_DIR,
549
+ CLAGENTIC_HOME: CLAGENTIC_HOME,
380
550
  EXTERNAL_TRIGGERS_DIR: EXTERNAL_TRIGGERS_DIR,
381
551
  configPath: configPath,
552
+ oldConfigPath: oldConfigPath,
382
553
  socketPath: socketPath,
383
554
  oldSocketPath: oldSocketPath,
384
555
  logPath: logPath,
556
+ oldLogPath: oldLogPath,
385
557
  ensureConfigDir: ensureConfigDir,
386
558
  loadConfig: loadConfig,
387
559
  saveConfig: saveConfig,
@@ -99,7 +99,7 @@ function rescanWorktrees(relay, parentPath, parentSlug, parentIcon, parentOwnerI
99
99
  relay.broadcastAll({
100
100
  type: "projects_updated",
101
101
  projects: relay.getProjects(),
102
- projectCount: config ? config.projects.length : 0,
102
+ projectCount: relay.getProjects().length,
103
103
  });
104
104
  }
105
105
  } finally {
package/lib/daemon.js CHANGED
@@ -31,7 +31,7 @@ var usersModule = require("./users");
31
31
  var { createWorktree, removeWorktree, isWorktree } = require("./worktree");
32
32
  var { isWorktreeSlug, scanAndRegisterWorktrees, rescanWorktrees, cleanupWorktreesForParent, getFilteredRemovedProjects, registerWorktreeSlug, unregisterWorktreeSlug } = require("./daemon-projects");
33
33
  var { validateCloneUrl, buildCloneArgs } = require("./clone-validate");
34
- var { DEFAULT_MEM_AVAILABLE_MIN_MB } = require("./sdk-bridge");
34
+ var { DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM } = require("./sdk-bridge");
35
35
  var liteDetect = require("./lite-detect");
36
36
  var { execFile: liteExecFile } = require("child_process");
37
37
 
@@ -47,25 +47,22 @@ try {
47
47
  config = JSON.parse(fs.readFileSync(configFile, "utf8"));
48
48
  } catch (e) {
49
49
  if (e.code === "ENOENT") {
50
- // Guard: detect CLAGENTIC_HOME mis-pointed at the socket subdirectory.
51
- //
52
- // Symptom: CLAGENTIC_HOME=~/.clagentic/console → CONFIG_DIR ends in
53
- // ".clagentic/console" and configFile = CONFIG_DIR/daemon.json (absent),
54
- // but the real config lives one level up at ../daemon.json. If we
55
- // bootstrap here we silently write projects:[] and the user loses all
56
- // their projects with no obvious error. Refuse loudly instead. (lr-dec3)
57
- var _configBasename = path.basename(path.dirname(configFile));
58
- var _configGrandparent = path.basename(path.dirname(path.dirname(configFile)));
59
- var _siblingConfig = path.join(path.dirname(path.dirname(configFile)), path.basename(configFile));
60
- if (_configBasename === "console" && _configGrandparent === ".clagentic" && fs.existsSync(_siblingConfig)) {
61
- console.error("[daemon] ERROR: config file not found at " + configFile + " but a config exists at " + _siblingConfig + ".");
62
- console.error("[daemon] CLAGENTIC_HOME appears to be set to the socket subdirectory (~/.clagentic/console).");
63
- console.error("[daemon] Do NOT set CLAGENTIC_HOME to ~/.clagentic/console — that directory holds the");
64
- console.error("[daemon] Unix socket, not the config. Relocating CLAGENTIC_HOME there moves daemon.json");
65
- console.error("[daemon] out of reach and causes your project list to be wiped on next bootstrap.");
66
- console.error("[daemon] Fix: unset CLAGENTIC_HOME (or set it back to ~/.clagentic) and restart.");
67
- process.exit(78); // EX_CONFIG — fatal config error, don't auto-restart
68
- }
50
+ // Guard: if CLAGENTIC_HOME was erroneously set to the socket subdirectory
51
+ // (e.g. ~/.clagentic/console instead of ~/.clagentic), a real daemon.json
52
+ // will exist one level above CLAGENTIC_HOME. Detect this and refuse to
53
+ // bootstrap an empty config — that would silently discard all projects.
54
+ var { CLAGENTIC_HOME: _cgHome } = require("./config");
55
+ var _siblingConfig = path.join(path.dirname(_cgHome), "daemon.json");
56
+ try {
57
+ var _sibling = JSON.parse(fs.readFileSync(_siblingConfig, "utf8"));
58
+ if (_sibling && Array.isArray(_sibling.projects) && _sibling.projects.length > 0) {
59
+ console.error("[daemon] ERROR: CLAGENTIC_HOME appears to point at the console/ socket subdirectory (" + _cgHome + ").");
60
+ console.error("[daemon] A populated daemon.json with " + _sibling.projects.length + " project(s) exists at " + _siblingConfig + ".");
61
+ console.error("[daemon] Set CLAGENTIC_HOME to the parent directory (" + path.dirname(_cgHome) + ") to use the correct config.");
62
+ process.exit(78); // EX_CONFIG — do not auto-restart
63
+ }
64
+ } catch (_e) { /* sibling check is best-effort; fall through to normal bootstrap */ }
65
+
69
66
  // No config file yet (fresh install, systemd-only start). Bootstrap minimal defaults.
70
67
  console.warn("[daemon] No config file found at " + configFile + " — bootstrapping defaults. Run clagentic-console to configure projects.");
71
68
  var _isDev = !!(process.env.CLAGENTIC_DEV || process.env.CLAY_DEV);
@@ -89,6 +86,28 @@ console.log("[daemon] Users: " + usersModule.USERS_FILE);
89
86
  if (process.env.SUDO_USER) console.log("[daemon] SUDO_USER: " + process.env.SUDO_USER);
90
87
  console.log("[daemon] UID: " + (typeof process.getuid === "function" ? process.getuid() : "N/A"));
91
88
 
89
+ // Stale-code check: if this process holds deleted inodes, the on-disk JS was
90
+ // replaced by a newer install while we were running. Warn loudly so operators
91
+ // know a restart is needed to load the new code.
92
+ function checkStaleInodes() {
93
+ if (process.platform !== 'linux') return false;
94
+ try {
95
+ var mapsContent = fs.readFileSync('/proc/self/maps', 'utf8');
96
+ return mapsContent.split('\n').some(function(line) {
97
+ return line.includes(' (deleted)');
98
+ });
99
+ } catch (_) {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ if (checkStaleInodes()) {
105
+ console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
106
+ console.warn('[daemon] WARNING: restart the daemon to load the new build:');
107
+ console.warn('[daemon] WARNING: systemctl restart clagentic-console');
108
+ console.warn('[daemon] WARNING: — or — clagentic-console --restart');
109
+ }
110
+
92
111
 
93
112
  // --- Single-user migration hint ---
94
113
  if (config.pinHash && !usersModule.isMultiUser()) {
@@ -924,6 +943,7 @@ var relay = createServer({
924
943
  updateChannel: config.updateChannel || "stable",
925
944
  imageRetentionDays: config.imageRetentionDays !== undefined ? config.imageRetentionDays : 7,
926
945
  memAvailableMinMB: config.memAvailableMinMB !== undefined ? config.memAvailableMinMB : DEFAULT_MEM_AVAILABLE_MIN_MB,
946
+ tokensPerMbHeadroom: config.tokensPerMbHeadroom !== undefined ? config.tokensPerMbHeadroom : DEFAULT_TOKENS_PER_MB_HEADROOM,
927
947
  liteAutoEnroll: !!config.liteAutoEnroll,
928
948
  };
929
949
  },
@@ -1001,6 +1021,15 @@ var relay = createServer({
1001
1021
  console.log("[daemon] MemAvailable threshold:", val, "MB (web)");
1002
1022
  return { ok: true, memAvailableMinMB: val };
1003
1023
  },
1024
+ onSetTokensPerMbHeadroom: function (tpm) {
1025
+ var val = parseInt(tpm, 10);
1026
+ // Valid range: 10–500 tokens/MB; outside that range reset to default.
1027
+ if (isNaN(val) || val < 10 || val > 500) val = DEFAULT_TOKENS_PER_MB_HEADROOM;
1028
+ config.tokensPerMbHeadroom = val;
1029
+ saveConfig(config);
1030
+ console.log("[daemon] Tokens per MB headroom:", val, "(web)");
1031
+ return { ok: true, tokensPerMbHeadroom: val };
1032
+ },
1004
1033
  onGetToolPalettes: function () {
1005
1034
  return config.toolPalettes || {};
1006
1035
  },
@@ -1166,6 +1195,20 @@ var relay = createServer({
1166
1195
  },
1167
1196
  });
1168
1197
 
1198
+ // Periodic stale-code check: re-emit the warning every 60 s so it appears in
1199
+ // journalctl even if the operator wasn't watching at startup time.
1200
+ var staleCheckHandle = setInterval(function () {
1201
+ if (checkStaleInodes()) {
1202
+ console.warn('[daemon] WARNING: this process is serving STALE code — on-disk JS has been replaced');
1203
+ console.warn('[daemon] WARNING: restart the daemon to load the new build:');
1204
+ console.warn('[daemon] WARNING: systemctl restart clagentic-console');
1205
+ console.warn('[daemon] WARNING: — or — clagentic-console --restart');
1206
+ }
1207
+ }, 60 * 1000);
1208
+ if (staleCheckHandle && typeof staleCheckHandle.unref === "function") {
1209
+ staleCheckHandle.unref();
1210
+ }
1211
+
1169
1212
  var IDLE_MS = Number(process.env.CLAY_CODEX_IDLE_MS) || 5 * 60 * 1000;
1170
1213
  var REAP_MS = Number(process.env.CLAY_CODEX_REAPER_MS) || 60 * 1000;
1171
1214
  var reaperHandle = setInterval(function () {
@@ -1192,6 +1235,10 @@ function stopCodexReaper() {
1192
1235
  clearInterval(reaperHandle);
1193
1236
  reaperHandle = null;
1194
1237
  }
1238
+ if (staleCheckHandle) {
1239
+ clearInterval(staleCheckHandle);
1240
+ staleCheckHandle = null;
1241
+ }
1195
1242
  }
1196
1243
 
1197
1244
  function shutdownProjects() {
@@ -1409,6 +1456,15 @@ var ipc = createIPCServer(socketPath(), function (msg) {
1409
1456
  return { ok: true, memAvailableMinMB: memMB };
1410
1457
  }
1411
1458
 
1459
+ case "set_tokens_per_mb_headroom": {
1460
+ var tpmVal = parseInt(msg.value, 10);
1461
+ if (isNaN(tpmVal) || tpmVal < 10 || tpmVal > 500) tpmVal = DEFAULT_TOKENS_PER_MB_HEADROOM;
1462
+ config.tokensPerMbHeadroom = tpmVal;
1463
+ saveConfig(config);
1464
+ console.log("[daemon] Tokens per MB headroom:", tpmVal, "(cli)");
1465
+ return { ok: true, tokensPerMbHeadroom: tpmVal };
1466
+ }
1467
+
1412
1468
  case "enable_recovery": {
1413
1469
  if (!msg.urlPath || !msg.password) return { ok: false, error: "missing urlPath or password" };
1414
1470
  relay.setRecovery(msg.urlPath, msg.password);
@@ -1630,7 +1686,7 @@ function spawnAndRestart() {
1630
1686
  relay.server.close(function () {
1631
1687
  try {
1632
1688
  var { spawn: spawnRestart } = require("child_process");
1633
- var { logPath: restartLogPath, configPath: restartConfigPath } = require("./config");
1689
+ var { logPath: restartLogPath, configPath: restartConfigPath, CLAGENTIC_HOME: restartClagenticHome } = require("./config");
1634
1690
  var daemonScript = path.join(__dirname, "daemon.js");
1635
1691
  var logFd = fs.openSync(restartLogPath(), "a");
1636
1692
  var child = spawnRestart(process.execPath, [daemonScript], {
@@ -1639,12 +1695,22 @@ function spawnAndRestart() {
1639
1695
  stdio: ["ignore", logFd, logFd],
1640
1696
  env: Object.assign({}, process.env, {
1641
1697
  CLAGENTIC_CONFIG: restartConfigPath(),
1698
+ CLAGENTIC_HOME: restartClagenticHome,
1642
1699
  }),
1643
1700
  });
1644
1701
  child.unref();
1645
1702
  fs.closeSync(logFd);
1646
1703
  config.pid = child.pid;
1647
- saveConfig(config);
1704
+ // Write PID synchronously before exit so the config file is not
1705
+ // left with a stale PID during the restart window. saveConfig() is
1706
+ // async (fire-and-forget) and is frequently not flushed before
1707
+ // process.exit(120) fires.
1708
+ try {
1709
+ fs.writeFileSync(restartConfigPath(), JSON.stringify(config, null, 2), { mode: 0o600 });
1710
+ } catch (syncErr) {
1711
+ console.error("[daemon] Sync PID write failed (non-fatal):", syncErr.message);
1712
+ saveConfig(config);
1713
+ }
1648
1714
  console.log("[daemon] Spawned new daemon (PID " + child.pid + "), exiting.");
1649
1715
  process.exit(120);
1650
1716
  } catch (e) {