@clagentic/console 1.9.0-beta.1 → 1.9.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.
Files changed (61) hide show
  1. package/bin/cli.js +23 -1
  2. package/lib/agents.js +13 -3
  3. package/lib/build-sha.json +2 -2
  4. package/lib/cli/ipc-subcommands.js +84 -4
  5. package/lib/daemon.js +111 -7
  6. package/lib/effective-protocol.js +82 -0
  7. package/lib/project-connection.js +21 -8
  8. package/lib/project-filesystem.js +4 -4
  9. package/lib/project-http.js +4 -4
  10. package/lib/project-loop.js +49 -5
  11. package/lib/project-sessions.js +166 -68
  12. package/lib/project-user-mention.js +7 -7
  13. package/lib/project-user-message.js +81 -14
  14. package/lib/project.js +28 -22
  15. package/lib/public/app.js +18 -4
  16. package/lib/public/css/base.css +14 -0
  17. package/lib/public/css/filebrowser.css +6 -0
  18. package/lib/public/css/home-hub.css +28 -8
  19. package/lib/public/css/icon-strip.css +17 -0
  20. package/lib/public/css/messages.css +11 -0
  21. package/lib/public/css/mobile-nav.css +22 -0
  22. package/lib/public/css/server-settings.css +9 -0
  23. package/lib/public/css/sidebar.css +15 -0
  24. package/lib/public/css/title-bar.css +10 -1
  25. package/lib/public/index.html +9 -2
  26. package/lib/public/modules/activity-latch.js +45 -0
  27. package/lib/public/modules/activity-state.js +195 -0
  28. package/lib/public/modules/app-connection.js +31 -6
  29. package/lib/public/modules/app-favicon.js +75 -1
  30. package/lib/public/modules/app-home-hub.js +14 -11
  31. package/lib/public/modules/app-loop-ui.js +86 -2
  32. package/lib/public/modules/app-messages.js +178 -54
  33. package/lib/public/modules/app-panels.js +91 -32
  34. package/lib/public/modules/app-projects.js +46 -9
  35. package/lib/public/modules/app-rate-limit.js +13 -1
  36. package/lib/public/modules/server-settings.js +256 -21
  37. package/lib/public/modules/sidebar-mobile.js +32 -22
  38. package/lib/public/modules/sidebar-projects.js +42 -14
  39. package/lib/public/modules/sidebar-sessions.js +168 -48
  40. package/lib/public/modules/theme.js +2 -2
  41. package/lib/public/modules/tools.js +11 -39
  42. package/lib/sdk-bridge.js +375 -33
  43. package/lib/sdk-message-processor.js +98 -15
  44. package/lib/sdk-skill-discovery.js +46 -6
  45. package/lib/sdk-slash-enrichment.js +5 -2
  46. package/lib/server-dm.js +5 -5
  47. package/lib/server-hub-sessions.js +70 -0
  48. package/lib/server.js +78 -43
  49. package/lib/session-activity.js +9 -2
  50. package/lib/sessions.js +64 -18
  51. package/lib/smtp.js +10 -1
  52. package/lib/terminal-manager.js +6 -6
  53. package/lib/ws-schema.js +16 -0
  54. package/lib/yoke/adapters/claude.js +7 -1
  55. package/lib/yoke/adapters/codex.js +219 -31
  56. package/package.json +2 -2
  57. package/scripts/check-test-count.js +397 -0
  58. package/scripts/test-file-completion-reporter.js +43 -0
  59. package/scripts/verify-installed-build.js +242 -15
  60. package/lib/model-context-windows.js +0 -74
  61. package/lib/public/modules/model-context-windows.js +0 -71
package/lib/sdk-bridge.js CHANGED
@@ -11,7 +11,6 @@ var { attachMessageProcessor } = require("./sdk-message-processor");
11
11
  var { readAgentToolsFromFile, parseFrontmatter, slugifyAgentName, AGENTS_SOURCE_DIR } = require("./agents");
12
12
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
13
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
14
- var { KNOWN_CONTEXT_WINDOWS: _BACKEND_KNOWN_CONTEXT_WINDOWS, resolveModelContextWindow } = require("./model-context-windows");
15
14
  var { runPreflight } = require("./settings-preflight");
16
15
  var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping, sweepClearedPermissionIndex } = require("./sdk-permission-ownership");
17
16
  var { permissionGrantKey } = require("./utils");
@@ -28,15 +27,166 @@ var MAX_CONCURRENT_SESSIONS = (function () {
28
27
  return (env > 0) ? env : 50;
29
28
  })();
30
29
 
30
+ // --- lr-58c813: activity-source divergence probe (instrumentation only) ---
31
+ // Baseline measurement for the lr-5edd64 redesign: session.isProcessing (the
32
+ // plain mutable boolean, ~14 raw writers) is DERIVED at exactly one site
33
+ // (sdk-bridge.js's "lr-9bcd7b" comment above) from
34
+ // sessionActivity.isSessionActive(session) (the token registry). This counts
35
+ // how often the two disagree at runtime -- READ ONLY, never corrects or
36
+ // mutates either value, never gates a renderer, never changes what a client
37
+ // sees. Sizes the redesign; does not implement it.
38
+ //
39
+ // Genuinely read-only means never triggering session.activity's own lazy
40
+ // initialization either (session-activity.js's ensureRegistry assigns
41
+ // session.activity on first call, and lib/sessions.js's constructors never
42
+ // set it) -- see _peekIsSessionActive below, which this probe uses instead
43
+ // of sessionActivity.isSessionActive for exactly that reason.
44
+ //
45
+ // Bounded by construction: sampled once per session per idle-reaper tick
46
+ // (IDLE_CHECK_INTERVAL_MS = 60s below), not per tool call/message -- the
47
+ // reaper's own setInterval is the sampling clock, so this adds zero new
48
+ // per-event hot-path cost. A ring buffer caps the retained detail so a
49
+ // daemon that runs for weeks cannot grow this unboundedly; the total count
50
+ // is exact (increments forever), only the per-event detail is capped.
51
+ var _activityDivergenceCount = 0;
52
+ var _activityDivergenceSamples = []; // ring buffer, most-recent-first
53
+ var ACTIVITY_DIVERGENCE_SAMPLE_CAP = 20;
54
+
55
+ /**
56
+ * Non-mutating read of "does this session have at least one live activity
57
+ * token", WITHOUT going through sessionActivity.isSessionActive/
58
+ * getActiveCount -- both of those call ensureRegistry(session), which
59
+ * lazily creates and ASSIGNS session.activity on first call
60
+ * (lib/session-activity.js). Session objects from lib/sessions.js's two
61
+ * constructors never initialize session.activity, so calling the mutating
62
+ * path here would create it on every session's first idle-reaper tick --
63
+ * a real write this probe must never cause (PEACHES lr-58c813 finding).
64
+ *
65
+ * A session with no session.activity has, by construction, acquired zero
66
+ * tokens, so "absent" and "present but empty/stale-generation" both mean
67
+ * not-active -- this mirrors isSessionActive's own semantics exactly, it
68
+ * just never creates the registry to get there. Does not read/write
69
+ * anything in lib/session-activity.js, which is out of scope and proven
70
+ * correct twice already; this adapts the caller to the existing API
71
+ * instead of changing it.
72
+ */
73
+ function _peekIsSessionActive(session) {
74
+ var registry = session.activity;
75
+ if (!registry) return false;
76
+ for (var token in registry.tokens) {
77
+ if (registry.tokens[token].generation === registry.generation) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ /**
83
+ * Read-only comparison of the two activity sources for one session. Does not
84
+ * write session.isProcessing, does not call onProcessingChanged, does not
85
+ * touch the registry -- including never triggering the registry's own lazy
86
+ * initialization (see _peekIsSessionActive above). Call site (idle reaper,
87
+ * see startIdleReaper) observes BEFORE any reaper-driven correction runs in
88
+ * the same tick, so a divergence caused by a leaked token that the reaper is
89
+ * about to sweep is still counted -- the point is measuring how often
90
+ * production state actually disagrees, not how often it disagrees net of
91
+ * self-healing.
92
+ */
93
+ function _recordActivityDivergenceIfAny(session) {
94
+ var rawIsProcessing = !!session.isProcessing;
95
+ var derivedIsActive = _peekIsSessionActive(session);
96
+ if (rawIsProcessing === derivedIsActive) return;
97
+ _activityDivergenceCount++;
98
+ // lr-58c813 (BOBBIE finding): no sessionId here. process_stats (the
99
+ // handler that folds these samples into its response, see
100
+ // project-sessions.js) has no admin/role gate -- any authenticated
101
+ // client on a shared project could otherwise read another user's
102
+ // session ids through this counter. The measurement goal (how often the
103
+ // two sources disagree, and roughly under what conditions) survives
104
+ // without a per-session identifier, so the identifier is dropped rather
105
+ // than gating process_stats (which would widen this PR's scope into a
106
+ // pre-existing, unrelated auth gap -- see PR body).
107
+ var sample = {
108
+ ts: Date.now(),
109
+ rawIsProcessing: rawIsProcessing,
110
+ derivedIsActive: derivedIsActive,
111
+ hasQueryInstance: !!session.queryInstance,
112
+ };
113
+ _activityDivergenceSamples.unshift(sample);
114
+ if (_activityDivergenceSamples.length > ACTIVITY_DIVERGENCE_SAMPLE_CAP) {
115
+ _activityDivergenceSamples.length = ACTIVITY_DIVERGENCE_SAMPLE_CAP;
116
+ }
117
+ // lr-58c813 (PEACHES nit): no console.warn here. MILLER's diagnosis
118
+ // predicts divergence may be common, and this fires once per diverging
119
+ // session per idle-reaper tick (60s) forever -- an unbounded, unrated
120
+ // log volume risk on the operator's own machine for a value that isn't
121
+ // actionable as a log line anyway. The counter + bounded sample ring
122
+ // (both above) are the actual deliverable; dropping the warn and
123
+ // relying on getActivityDivergenceStats()/process_stats for visibility
124
+ // avoids the flood risk entirely rather than trying to rate-limit it.
125
+ }
126
+
127
+ // Module-scope accessor so tests and other bridge instances (this counter is
128
+ // intentionally shared across ALL project bridge instances, same as
129
+ // _activeLiveCount above) can read the current totals without reaching into
130
+ // closure state.
131
+ function getActivityDivergenceStats() {
132
+ return {
133
+ count: _activityDivergenceCount,
134
+ recentSamples: _activityDivergenceSamples.slice(),
135
+ };
136
+ }
137
+
138
+ // lr-8b476f: shared response builder for the agent-readable retrieval path
139
+ // (daemon.js's "get_activity_diagnostics" IPC command, over the existing
140
+ // daemon.sock Unix socket). Pulled out here — rather than inlined in
141
+ // daemon.js, which has no module.exports and cannot be safely required by a
142
+ // test without binding real sockets/HTTP servers — so this is unit-testable
143
+ // the same way getActivityDivergenceStats()/getActiveLiveCount() already
144
+ // are. Read-only: calls only the two existing module-level accessors above,
145
+ // writes nothing.
146
+ function buildActivityDiagnosticsResponse() {
147
+ var divergence = getActivityDivergenceStats();
148
+ return {
149
+ ok: true,
150
+ activeLiveCount: getActiveLiveCount(),
151
+ activityDivergenceCount: divergence.count,
152
+ activityDivergenceRecentSamples: divergence.recentSamples,
153
+ };
154
+ }
155
+
31
156
  // --- lr-2d91: MemAvailable gate ---
32
157
  // Default minimum available memory threshold in MB. Referenced by sdk-bridge
33
158
  // and daemon.js — changing this constant is the single place to adjust the default.
34
159
  var DEFAULT_MEM_AVAILABLE_MIN_MB = 1024;
35
160
 
36
- // --- lr-2d91: cgroup context token guard ---
37
- // Empirical calibration: claude-opus-4 at 1M context peaks at ~15 GB RSS,
38
- // yielding approximately 67 tokens per MB of headroom consumed.
39
- var DEFAULT_TOKENS_PER_MB_HEADROOM = 67;
161
+ // --- lr-5450ef: pendingMessages bound ---
162
+ // session.pendingMessages (pushMessage's between-turns buffer, lr-b61b) was
163
+ // unbounded — a session stuck with isProcessing pinned true (e.g. by a
164
+ // leaked activity token) would accept every subsequent message into this
165
+ // array forever with no UI signal. Bounding it turns an unbounded silent
166
+ // leak into a bounded, OBSERVABLE one: once full, the oldest buffered
167
+ // message is dropped to make room, and a diagnostic is emitted either way
168
+ // (see pushMessage) so the user sees SOMETHING went sideways instead of
169
+ // nothing.
170
+ var MAX_PENDING_MESSAGES = 20;
171
+
172
+ // --- lr-2d91 / lr-93e3c8: cgroup context token guard ---
173
+ // Recalibrated (lr-93e3c8, fnd-0ca818): the original 67 tok/MB figure was
174
+ // derived from ONE pathological 17M-cache-read-tokens/turn session that
175
+ // caused two real OOM kills, generalized to a claude-opus-4-at-1M-context
176
+ // assumption of ~15 GB RSS. That generalization does not hold for this
177
+ // daemon's actual cgroup: this service's own all-time memory.peak
178
+ // (readable at /sys/fs/cgroup/system.slice/<unit>.service/memory.peak,
179
+ // same directory as memory.current/memory.max already read below) was
180
+ // observed at 2732 MB while carrying a confirmed ~661K-token session --
181
+ // i.e. this real workload's worst-case-to-date density is roughly
182
+ // 661000 / 2732 =~ 242 tokens/MB, not 67. 240 is used here (rounded down,
183
+ // the conservative direction: assuming slightly MORE memory per token than
184
+ // observed keeps the guard's allowance slightly lower than the measured
185
+ // ceiling, never higher). This is still a single data point, not a
186
+ // distribution -- operators with a different workload shape should tune
187
+ // tokensPerMbHeadroom in Server Settings > Advanced > Memory rather than
188
+ // relying on this default being right for their traffic.
189
+ var DEFAULT_TOKENS_PER_MB_HEADROOM = 240;
40
190
 
41
191
  // Configurable warn fractions for context guards (lr-1f7e).
42
192
  // cgroupWarnFraction: warn when context tokens exceed this fraction of the
@@ -47,11 +197,36 @@ var DEFAULT_TOKENS_PER_MB_HEADROOM = 67;
47
197
  var DEFAULT_CGROUP_WARN_FRACTION = 0.8;
48
198
  var DEFAULT_CONTEXT_WINDOW_WARN_FRACTION = 0.8;
49
199
 
50
- // Known context windows for models the backend may encounter (lr-1f7e, lr-336f).
51
- // Imported from lib/model-context-windows.js — shared source of truth with the frontend.
52
- // The alias preserves backward compatibility for any callers that reference this name.
53
- var BACKEND_KNOWN_CONTEXT_WINDOWS = _BACKEND_KNOWN_CONTEXT_WINDOWS;
54
- // resolveModelContextWindow imported from lib/model-context-windows.js above.
200
+ // Resolve the effective MemAvailable gate threshold (MB) from daemon config.
201
+ // Pulled out as a pure function so the accept/honor agreement between this
202
+ // consumer and daemon.js's onSetMemAvailableThreshold setter (both must treat
203
+ // 0 as "disable the gate", not "unset -- use the default") can be unit
204
+ // tested directly, without needing to fake /proc/meminfo through startQuery.
205
+ function resolveMemAvailableThresholdMB(config) {
206
+ if (config && typeof config.memAvailableMinMB === "number" && config.memAvailableMinMB >= 0) {
207
+ return config.memAvailableMinMB;
208
+ }
209
+ return DEFAULT_MEM_AVAILABLE_MIN_MB;
210
+ }
211
+
212
+ // Build the operator-facing "why was this blocked" clause for the cgroup
213
+ // context hard gate, given the freshly-read host MemAvailable (MB, or null
214
+ // if unreadable) and the cgroup headroom (MB) that triggered the block.
215
+ // Pulled out as a pure function (lr-93e3c8 fold-in, PEACHES finding 2) so the
216
+ // boundary condition and the null-host-read fallback can be unit tested
217
+ // directly -- readMemAvailableMB()/readCgroupHeadroomMB() read real
218
+ // /proc/meminfo and /sys/fs/cgroup, which is not host-independently
219
+ // mockable, but this decision is pure once those two numbers are in hand.
220
+ function computeCgroupBlockCauseMessage(hostMemAvailMB, cgHeadroomMB) {
221
+ var hostIsGenerous = hostMemAvailMB !== null && hostMemAvailMB >= cgHeadroomMB * 2;
222
+ if (hostIsGenerous) {
223
+ return "This daemon's service memory cap (systemd MemoryMax) is the limiting factor, not host memory (" + hostMemAvailMB + " MB free on the host). Raise 'Context tokens per MB headroom' in Server Settings > Advanced > Memory, or raise MemoryMax in the clagentic-console systemd unit, if this is a false positive.";
224
+ }
225
+ if (hostMemAvailMB !== null) {
226
+ return "Available memory (host and service cap alike) is genuinely low right now.";
227
+ }
228
+ return "Could not read host memory to determine the cause; the service memory cap (" + cgHeadroomMB + " MB headroom) is the limiting factor measured here.";
229
+ }
55
230
 
56
231
  // Read Linux MemAvailable from /proc/meminfo synchronously.
57
232
  // Returns available memory in MB, or null on non-Linux or read failure.
@@ -101,6 +276,22 @@ function readCgroupHeadroomMB() {
101
276
  }
102
277
  }
103
278
 
279
+ // lr-3ccc78 — resolve the effective global skills/agents home for a query.
280
+ // On a shared multi-user daemon (linuxUser set), skill/agent discovery must
281
+ // read the SESSION OWNER's own ~/.claude/, not the daemon process's
282
+ // REAL_HOME (lib/config.js's REAL_HOME is a module-level constant computed
283
+ // once at process load and is never per-user). Falls back to REAL_HOME when
284
+ // linuxUser is absent — the single-user / no-OS-isolation case is unchanged.
285
+ function resolveEffectiveHome(linuxUser) {
286
+ if (!linuxUser) return null;
287
+ try {
288
+ var home = require("./os-users").getLinuxUserHome(linuxUser);
289
+ return home || null;
290
+ } catch (e) {
291
+ return null;
292
+ }
293
+ }
294
+
104
295
  // Extract serializable tool descriptors from MCP server instances.
105
296
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
106
297
  function extractMcpDescriptors(mcpServers) {
@@ -372,6 +563,14 @@ function createSDKBridge(opts) {
372
563
  // liveChildReclaims handling).
373
564
  var IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
374
565
  var IDLE_CHECK_INTERVAL_MS = 60 * 1000; // check every 60 seconds
566
+ // lr-5450ef: BACKSTOP staleness window for the activity registry's leak
567
+ // resistance (see lib/session-activity.js header, layer 3). Deliberately
568
+ // shorter than IDLE_TIMEOUT_MS — this is recovering a session pinned by a
569
+ // leaked token (no live query, no way for the user to self-heal by typing
570
+ // again, since every message they send just buffers), not reaping a
571
+ // genuinely-idle-but-live session, so it should not make an operator wait
572
+ // a full 30 minutes to get their session back.
573
+ var ACTIVITY_STALE_MS = 5 * 60 * 1000; // 5 minutes
375
574
  var _idleReaperTimer = null;
376
575
 
377
576
  function startIdleReaper() {
@@ -379,12 +578,44 @@ function createSDKBridge(opts) {
379
578
  _idleReaperTimer = setInterval(function () {
380
579
  var now = Date.now();
381
580
  sm.sessions.forEach(function (session) {
581
+ if (session.destroying) return;
582
+
583
+ // lr-58c813: divergence probe, READ ONLY — observe the raw/derived
584
+ // activity values exactly as production has them right now, before
585
+ // any reaper-driven correction below runs this tick. See the
586
+ // _recordActivityDivergenceIfAny doc comment for why "before" matters.
587
+ _recordActivityDivergenceIfAny(session);
588
+
589
+ // lr-5450ef: sweepStaleTokens BACKSTOP — recover a session pinned by
590
+ // a leaked activity token (isProcessing derives true from the
591
+ // registry, but there is no live queryInstance left to ever call
592
+ // startQuery/bumpGeneration again). This is the "sweepStaleTokens
593
+ // has ZERO production call sites" gap: the registry's own PRIMARY
594
+ // layer (bumpGeneration) only runs from inside startQuery, which a
595
+ // pinned isProcessing prevents from ever being reached — nothing
596
+ // upstream of this reaper can self-heal that state. Runs BEFORE the
597
+ // "skip if isProcessing" idle-query check below on purpose, since a
598
+ // session with a leaked token and no queryInstance would otherwise
599
+ // never reach any reaper logic at all (lr-5450ef diagnosis: "the
600
+ // trap is self-sealing").
601
+ if (session.isProcessing && !session.queryInstance) {
602
+ var sweepResult = sessionActivity.sweepStaleTokens(session, ACTIVITY_STALE_MS);
603
+ if (sweepResult.changed) {
604
+ console.log("[sdk-bridge] Idle reaper: swept " + sweepResult.swept +
605
+ " stale activity token(s) for session " + session.localId +
606
+ ", recovering isProcessing=false" +
607
+ (session.title ? " title=" + JSON.stringify(session.title) : ""));
608
+ session.isProcessing = false;
609
+ onProcessingChanged();
610
+ sm.broadcastSessionList();
611
+ }
612
+ }
613
+
382
614
  // Skip sessions that are actively processing, have no query,
383
615
  // or are single-turn (Ralph Loop — managed by onQueryComplete).
384
616
  if (session.isProcessing) return;
385
617
  if (!session.queryInstance) return;
386
618
  if (session.singleTurn) return;
387
- if (session.destroying) return;
388
619
 
389
620
  var lastActivity = session.lastActivityAt || 0;
390
621
  if (now - lastActivity > IDLE_TIMEOUT_MS) {
@@ -463,12 +694,26 @@ function createSDKBridge(opts) {
463
694
  }
464
695
  console.log("[auto-title] Calling adapter.generateTitle with " + userMessages.length + " messages for session " + session.localId);
465
696
 
466
- sessionAdapter.generateTitle(userMessages, { cwd: cwd }).then(function(title) {
697
+ // lr-62157d: returns the promise chain (previously fire-and-forget) so
698
+ // this is directly awaitable in tests via _test_autoGenerateTitle; the
699
+ // real onAutoTitle callers (sdk-message-processor.js) call this
700
+ // fire-and-forget already and are unaffected by a function now
701
+ // returning a value they don't use.
702
+ return sessionAdapter.generateTitle(userMessages, { cwd: cwd }).then(function(title) {
467
703
  if (!title || title.length < 2) return;
468
704
  title = title.substring(0, 100);
469
- if (!session.titleManuallySet) {
705
+ // lr-62157d: overwrite whenever the current title is provisional (the
706
+ // raw first-message truncation from project-user-message.js, or no
707
+ // title at all) and the user hasn't manually renamed the session.
708
+ // Before titleProvisional existed, the first-message fallback looked
709
+ // exactly like a real title, so this guard had nothing that let it
710
+ // tell "already properly titled" apart from "still carrying the raw
711
+ // 50-char truncation" — this is what actually lets a real LLM title
712
+ // replace that truncation.
713
+ if ((session.titleProvisional || !session.title) && !session.titleManuallySet) {
470
714
  session.title = title;
471
715
  session.titleAutoGenerated = true;
716
+ session.titleProvisional = false;
472
717
  sm.saveSessionFile(session);
473
718
  sm.broadcastSessionList();
474
719
  if (session.cliSessionId && typeof adapter.renameSession === "function") {
@@ -497,8 +742,18 @@ function createSDKBridge(opts) {
497
742
  opts: opts,
498
743
  discoverSkillDirs: discoverSkillDirs,
499
744
  mergeSkills: mergeSkills,
500
- discoverSkillsWithMeta: function(cwdArg) { return discoverSkillsWithMeta(cwdArg); },
745
+ discoverSkillsWithMeta: function(cwdArg, homeOverride) { return discoverSkillsWithMeta(cwdArg, homeOverride); },
501
746
  mergeSkillsWithMeta: mergeSkillsWithMeta,
747
+ // lr-3ccc78 — session-owner home resolution for skill/agent discovery on
748
+ // a shared multi-user daemon. usersModule.findUserById(session.ownerId)
749
+ // is the same pattern already used elsewhere in this file (getFreshAuthState).
750
+ resolveSessionHome: function(session) {
751
+ var ownerId = session && session.ownerId;
752
+ if (!ownerId) return null;
753
+ var owner = usersModule.findUserById(ownerId);
754
+ var ownerLinuxUser = owner && owner.linuxUser ? owner.linuxUser : null;
755
+ return resolveEffectiveHome(ownerLinuxUser);
756
+ },
502
757
  });
503
758
  var processSDKMessage = msgProcessor.processSDKMessage;
504
759
  var sendAndRecord = msgProcessor.sendAndRecord;
@@ -1019,6 +1274,19 @@ function createSDKBridge(opts) {
1019
1274
  if (session.isProcessing && session.taskStopRequested) {
1020
1275
  session.isProcessing = false;
1021
1276
  onProcessingChanged();
1277
+ // lr-5450ef: an interrupted turn can leave an activity token
1278
+ // acquired (block_stop, sdk-message-processor.js \u2014 Task originally,
1279
+ // widened to every tool_use block by lr-6e20f7) with no later
1280
+ // tool_result/task_notification ever arriving to release it \u2014 the
1281
+ // stream that would have delivered those events just ended here.
1282
+ // Bump the generation so that leaked token (and any other from this
1283
+ // turn) is immediately invisible to isSessionActive, same as the
1284
+ // PRIMARY leak-resistance layer already does at startQuery. Without
1285
+ // this, the finally block below re-derives isProcessing=true from
1286
+ // the leaked token and every later user message is silently
1287
+ // buffered (pushMessage) into a queue only startQuery ever drains \u2014
1288
+ // and startQuery is precisely what a pinned isProcessing prevents.
1289
+ sessionActivity.bumpGeneration(session);
1022
1290
  send({ type: "status", processing: false });
1023
1291
  sendAndRecord(session, { type: "thinking_stop" });
1024
1292
  var interruptMsg = (session.vendor === "codex")
@@ -1032,6 +1300,11 @@ function createSDKBridge(opts) {
1032
1300
  if (session.isProcessing) {
1033
1301
  session.isProcessing = false;
1034
1302
  onProcessingChanged();
1303
+ // lr-5450ef: same leak-resistance bump as the taskStopRequested
1304
+ // branch above \u2014 an aborted/errored stream can also leave an
1305
+ // activity token acquired (any tool_use block since lr-6e20f7, not
1306
+ // only Task) with no terminal event left to release it.
1307
+ sessionActivity.bumpGeneration(session);
1035
1308
  if (err.name === "AbortError" || (myAbortController && myAbortController.signal.aborted) || session.taskStopRequested) {
1036
1309
  if (!session.destroying) {
1037
1310
  sendAndRecord(session, { type: "thinking_stop" });
@@ -1490,13 +1763,7 @@ function createSDKBridge(opts) {
1490
1763
  if (isNewQuery) {
1491
1764
  var memAvailMB = readMemAvailableMB();
1492
1765
  var getConfig = opts.getConfig;
1493
- var memThresholdMB = DEFAULT_MEM_AVAILABLE_MIN_MB;
1494
- if (typeof getConfig === "function") {
1495
- var dc = getConfig();
1496
- if (dc && typeof dc.memAvailableMinMB === "number" && dc.memAvailableMinMB > 0) {
1497
- memThresholdMB = dc.memAvailableMinMB;
1498
- }
1499
- }
1766
+ var memThresholdMB = resolveMemAvailableThresholdMB(typeof getConfig === "function" ? getConfig() : null);
1500
1767
  if (memAvailMB !== null && memAvailMB < memThresholdMB) {
1501
1768
  console.warn("[sdk-bridge] MemAvailable gate: " + memAvailMB + " MB available, " + memThresholdMB + " MB required — rejecting new query for session " + session.localId);
1502
1769
  session.isProcessing = false;
@@ -1532,11 +1799,13 @@ function createSDKBridge(opts) {
1532
1799
 
1533
1800
  // lr-1f7e: proactive model context-window warn.
1534
1801
  // Fires before the cgroup hard gate so the user gets an early signal.
1535
- // Degrades cleanly when the model window is unknown (resolveModelContextWindow returns 0)
1536
- // or when ctxWinWarnFraction is 0 (disabled via config).
1537
- // Pass sm.currentBetas so context-1m beta is respected (mirrors app-panels.js logic).
1538
- var _sessionModel = session.model || sm.currentModel || null;
1539
- var _modelWindow = resolveModelContextWindow(_sessionModel, sm.currentBetas || []);
1802
+ // lr-3af675: vendor-first — the hardcoded model->window table is gone.
1803
+ // The only window figure trusted here is the vendor's own last-reported
1804
+ // value (session.lastContextUsage.maxTokens, set from getContextUsage()
1805
+ // at the end of the previous turn — see sdk-message-processor.js). When
1806
+ // no such value is available yet (no prior turn, or the vendor never
1807
+ // reported one), the warn simply degrades to skipped rather than guessing.
1808
+ var _modelWindow = (session.lastContextUsage && session.lastContextUsage.maxTokens) || 0;
1540
1809
  if (_modelWindow > 0 && ctxWinWarnFraction > 0) {
1541
1810
  var _winWarnTokens = Math.floor(_modelWindow * ctxWinWarnFraction);
1542
1811
  if (contextTokens >= _winWarnTokens) {
@@ -1558,7 +1827,31 @@ function createSDKBridge(opts) {
1558
1827
  console.warn("[sdk-bridge] cgroup context guard: " + Math.round(contextTokens / 1000) + "K tokens >= " + Math.round(allowedTokens / 1000) + "K allowed (" + cgHeadroomMB + " MB headroom) — blocking session " + session.localId);
1559
1828
  session.isProcessing = false;
1560
1829
  onProcessingChanged();
1561
- var blockMsg = "Session context too large for available memory (" + Math.round(contextTokens / 1000) + "K tokens, " + cgHeadroomMB + " MB headroom). Start a new session or wait for other sessions to complete.";
1830
+ // lr-93e3c8 (fnd-0ca818): the guard reads exactly two inputs — cgroup
1831
+ // headroom and this session's own context tokens — and never
1832
+ // consults _activeLiveCount. The old message unconditionally
1833
+ // suggested "wait for other sessions to complete" even when
1834
+ // _activeLiveCount was 0, asserting a cause the code never
1835
+ // evaluates. _activeLiveCount here reflects OTHER currently-running
1836
+ // sessions only: this session's own slot is claimed later (see
1837
+ // "Claim the slot now" below), so it has not incremented the
1838
+ // counter yet at this point in the flow.
1839
+ var otherLiveSessions = _activeLiveCount;
1840
+ // lr-93e3c8 (item 3): distinguish "this daemon's service cgroup is
1841
+ // capped low" from "the machine itself is out of memory" -- these
1842
+ // call for different operator actions (raise MemoryMax in the
1843
+ // unit file / raise tokensPerMbHeadroom, vs. actually free host
1844
+ // RAM) and the prior message conflated them under one generic
1845
+ // "available memory" phrase. readMemAvailableMB() (host-wide
1846
+ // /proc/meminfo) is already read earlier in this function for the
1847
+ // separate MemAvailable gate; read fresh here so it reflects
1848
+ // current state at block time, not whatever it was at query start.
1849
+ var _hostMemAvailMB = readMemAvailableMB();
1850
+ var causeMsg = computeCgroupBlockCauseMessage(_hostMemAvailMB, cgHeadroomMB);
1851
+ var blockMsg = "Session context too large for available memory (" + Math.round(contextTokens / 1000) + "K tokens, " + cgHeadroomMB + " MB service headroom). " +
1852
+ (otherLiveSessions > 0
1853
+ ? "Start a new session, or wait for " + otherLiveSessions + " other active session" + (otherLiveSessions === 1 ? "" : "s") + " to complete to free up headroom."
1854
+ : "Start a new session. " + causeMsg);
1562
1855
  sendAndRecord(session, { type: "error", text: blockMsg });
1563
1856
  sendAndRecord(session, { type: "done", code: 1 });
1564
1857
  send({ type: "toast", level: "error", message: "Session blocked — context too large for available memory.", duration: 7000 });
@@ -1665,7 +1958,15 @@ function createSDKBridge(opts) {
1665
1958
 
1666
1959
  if (session.agentName && sessionAdapter.vendor !== 'codex') {
1667
1960
  claudeOpts.agent = session.agentName;
1668
- var agentTools = readAgentToolsFromFile(session.agentName);
1961
+
1962
+ // lr-3ccc78 — on a shared multi-user daemon (linuxUser set), read the
1963
+ // session owner's own ~/.claude/agents, not the daemon process's
1964
+ // REAL_HOME (AGENTS_SOURCE_DIR is a module-level constant computed
1965
+ // once at process load — same defect class as skill discovery).
1966
+ var effectiveHome = resolveEffectiveHome(linuxUser);
1967
+ var effectiveAgentsDir = effectiveHome ? path.join(effectiveHome, ".claude", "agents") : AGENTS_SOURCE_DIR;
1968
+
1969
+ var agentTools = readAgentToolsFromFile(session.agentName, effectiveAgentsDir);
1669
1970
  if (agentTools) {
1670
1971
  claudeOpts.tools = agentTools;
1671
1972
  console.log("[sdk-bridge] agent tools enforced for " + session.agentName + ": " + agentTools.join(", "));
@@ -1678,7 +1979,7 @@ function createSDKBridge(opts) {
1678
1979
  // and ensures the model receives the agent persona directly.
1679
1980
  // We keep claudeOpts.agent set — it still applies tool restrictions via settingSources.
1680
1981
  var agentSlug = slugifyAgentName(session.agentName);
1681
- var agentFilePath = path.join(AGENTS_SOURCE_DIR, agentSlug + ".md");
1982
+ var agentFilePath = path.join(effectiveAgentsDir, agentSlug + ".md");
1682
1983
  var agentRaw;
1683
1984
  try {
1684
1985
  agentRaw = fs.readFileSync(agentFilePath, "utf8");
@@ -1826,6 +2127,12 @@ function createSDKBridge(opts) {
1826
2127
  approvalPolicy: codexConfig.approval,
1827
2128
  sandboxMode: codexConfig.sandbox,
1828
2129
  webSearchMode: codexConfig.webSearch,
2130
+ // lr-3ccc78 — mirrors CLAUDE.linuxUser above. The Codex adapter
2131
+ // resolves this into the session owner's own home for skill
2132
+ // discovery (discoverClaudeSkills); it does not (yet) route the
2133
+ // app-server process itself through OS-level uid/gid isolation —
2134
+ // see the PR body for why that's deliberately out of scope here.
2135
+ linuxUser: linuxUser || undefined,
1829
2136
  },
1830
2137
  },
1831
2138
  };
@@ -1930,8 +2237,26 @@ function createSDKBridge(opts) {
1930
2237
  // startQuery has not been called yet). Buffer the message so it is not
1931
2238
  // silently dropped; startQuery will flush it after the handle is created.
1932
2239
  if (!session.pendingMessages) session.pendingMessages = [];
2240
+ // lr-5450ef: bound the buffer and make buffering itself OBSERVABLE.
2241
+ // Before this fix, a session wedged with isProcessing pinned true (no
2242
+ // way to reach the only drain, startQuery) accepted every message a
2243
+ // user typed into this array with nothing but a server-log line —
2244
+ // the message looked "sent" in the UI and was never delivered, with
2245
+ // no error surfaced. Silence-to-UI, not just this specific pinning
2246
+ // mechanism, is the deeper defect: emit a diagnostic on every buffer
2247
+ // so any candidate cause that lands a message here is visible.
2248
+ var wasFull = session.pendingMessages.length >= MAX_PENDING_MESSAGES;
2249
+ if (wasFull) session.pendingMessages.shift();
1933
2250
  session.pendingMessages.push({ text: text, images: images });
1934
2251
  console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
2252
+ sendAndRecord(session, {
2253
+ type: "diagnostic",
2254
+ severity: "warning",
2255
+ source: "message-buffer",
2256
+ message: wasFull
2257
+ ? "Clagentic: Console couldn't start a new turn for this message — it replaced the oldest buffered message and is still waiting. Try reloading this session."
2258
+ : "Clagentic: Console couldn't start a new turn for this message yet — it's buffered and waiting. If this persists, try reloading this session.",
2259
+ });
1935
2260
  }
1936
2261
  }
1937
2262
 
@@ -2034,17 +2359,21 @@ function createSDKBridge(opts) {
2034
2359
  slug: slug,
2035
2360
  });
2036
2361
 
2037
- var fsSkills = discoverSkillDirs();
2362
+ // lr-3ccc78 — resolve the session owner's own home on a shared
2363
+ // multi-user daemon so global skill discovery isn't the daemon's
2364
+ // REAL_HOME for every user.
2365
+ var _warmupHome = resolveEffectiveHome(linuxUser);
2366
+ var fsSkills = discoverSkillDirs(_warmupHome);
2038
2367
  sm.skillNames = mergeSkills(result.skills, fsSkills);
2039
2368
  sm.workflowMeta = discoverWorkflows(cwd);
2040
2369
  // Enriched skill metadata (lr-7d8d)
2041
- var fsSkillsMeta = discoverSkillsWithMeta(cwd);
2370
+ var fsSkillsMeta = discoverSkillsWithMeta(cwd, _warmupHome);
2042
2371
  sm.skillMeta = mergeSkillsWithMeta(result.skills, fsSkillsMeta);
2043
2372
  if (result.slashCommands) {
2044
2373
  // Build enriched {name,desc,type}[] using the shared helper (lr-cf84).
2045
2374
  // Applies skill/workflow priority chain at warmup time, matching the
2046
2375
  // live-query init path so the UI receives enriched objects on connect.
2047
- var combined = buildEnrichedSlashCommands(result.slashCommands, cwd);
2376
+ var combined = buildEnrichedSlashCommands(result.slashCommands, cwd, { homeOverride: _warmupHome });
2048
2377
  sm.slashCommands = combined;
2049
2378
  sm.setSlashCommandsForVendor(defaultVendor, combined);
2050
2379
  send({ type: "slash_commands", commands: combined, vendor: defaultVendor });
@@ -2208,10 +2537,17 @@ function createSDKBridge(opts) {
2208
2537
 
2209
2538
  // lr-2d91: Expose live concurrency stats for process_stats WS response.
2210
2539
  // Called by project-sessions.js when building the process_stats payload.
2540
+ // lr-58c813: also folds in the activity-source divergence probe totals —
2541
+ // same "instance function reads module-shared counter" shape as
2542
+ // activeLiveCount above, so process_stats gets both without a second round
2543
+ // trip. See getActivityDivergenceStats() module-scope doc comment.
2211
2544
  function getMemoryStats() {
2545
+ var divergence = getActivityDivergenceStats();
2212
2546
  return {
2213
2547
  activeLiveCount: _activeLiveCount,
2214
2548
  maxConcurrentSessions: MAX_CONCURRENT_SESSIONS,
2549
+ activityDivergenceCount: divergence.count,
2550
+ activityDivergenceRecentSamples: divergence.recentSamples,
2215
2551
  };
2216
2552
  }
2217
2553
 
@@ -2240,6 +2576,12 @@ function createSDKBridge(opts) {
2240
2576
  startIdleReaper: startIdleReaper,
2241
2577
  stopIdleReaper: stopIdleReaper,
2242
2578
  getMemoryStats: getMemoryStats,
2579
+ // lr-62157d: exposed for direct unit testing of the provisional-title
2580
+ // overwrite guard, following the _test_-prefixed exposure convention
2581
+ // already used by lib/yoke/adapters/codex.js's resolveTitleModel. Not
2582
+ // part of the bridge's real call surface (project.js never calls it by
2583
+ // this name) — it is the same closure onAutoTitle wraps internally.
2584
+ _test_autoGenerateTitle: autoGenerateTitle,
2243
2585
  };
2244
2586
  }
2245
2587
 
@@ -2249,5 +2591,5 @@ function getActiveLiveCount() {
2249
2591
  return _activeLiveCount;
2250
2592
  }
2251
2593
 
2252
- module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, resolveModelContextWindow, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount };
2594
+ module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, resolveMemAvailableThresholdMB, computeCgroupBlockCauseMessage, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, getActivityDivergenceStats, buildActivityDiagnosticsResponse };
2253
2595