@clagentic/console 1.5.0-beta.4 → 1.6.0-beta.1

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.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * model-context-windows.js — shared source of truth for the model context-window
3
+ * map and beta-aware resolution. (lr-336f)
4
+ *
5
+ * This is the ES module (browser) copy. The CJS backend copy lives at
6
+ * lib/model-context-windows.js. A CI test (test/model-context-windows-parity.test.js)
7
+ * asserts both files produce identical resolution results so they cannot silently drift.
8
+ *
9
+ * When adding a new model: update BOTH this file and lib/model-context-windows.js.
10
+ * The parity test will fail if they disagree.
11
+ *
12
+ * The map is keyed by a lowercase model-name substring. Lookup is a linear scan so
13
+ * insertion order matters for overlapping substrings — more-specific keys should
14
+ * appear before less-specific ones.
15
+ */
16
+
17
+ export var KNOWN_CONTEXT_WINDOWS = {
18
+ "opus-4-6": 1000000,
19
+ "claude-sonnet-4": 1000000,
20
+ "gpt-5.5": 1048576,
21
+ "gpt-5.4": 1048576,
22
+ "gpt-5.3": 1048576,
23
+ "gpt-5.2": 1048576,
24
+ "gpt-4.1": 1047576,
25
+ "o3": 200000,
26
+ "o4-mini": 200000,
27
+ };
28
+
29
+ /**
30
+ * Resolve the context window for a model identifier, applying the beta-first
31
+ * rule for the context-1m beta.
32
+ *
33
+ * activeBetas: optional array of active beta strings. When any entry contains
34
+ * "context-1m", the true window is 1M regardless of the model — the SDK
35
+ * reports the model's base window in ModelUsage but the beta extends it.
36
+ *
37
+ * Returns the window size in tokens, or 0 when the model is not in
38
+ * KNOWN_CONTEXT_WINDOWS and no beta applies. Callers treat 0 as "unknown"
39
+ * and should degrade cleanly (skip any window-based guard rather than
40
+ * guessing a default).
41
+ *
42
+ * Note: the resolveContextWindow wrapper in app-panels.js adds an sdkValue
43
+ * fallback and a hasBeta() store accessor on top of this core function.
44
+ * This function itself is store-agnostic.
45
+ */
46
+ export function resolveModelContextWindow(model, activeBetas) {
47
+ // Beta check must come first — the SDK does not reflect the extended window.
48
+ if (Array.isArray(activeBetas)) {
49
+ for (var bi = 0; bi < activeBetas.length; bi++) {
50
+ if (activeBetas[bi].indexOf("context-1m") !== -1) return 1000000;
51
+ }
52
+ }
53
+ if (!model) return 0;
54
+ var lc = model.toLowerCase();
55
+ // UI beta-toggle appends [1m] to the model name
56
+ if (lc.indexOf("[1m]") !== -1) return 1000000;
57
+ var keys = Object.keys(KNOWN_CONTEXT_WINDOWS);
58
+ for (var i = 0; i < keys.length; i++) {
59
+ if (lc.indexOf(keys[i]) !== -1) return KNOWN_CONTEXT_WINDOWS[keys[i]];
60
+ }
61
+ return 0;
62
+ }
@@ -34,4 +34,5 @@
34
34
  @import url("css/debate.css");
35
35
  @import url("css/notifications-center.css");
36
36
  @import url("css/team-panel.css");
37
+ @import url("css/diagnostics.css");
37
38
 
package/lib/sdk-bridge.js CHANGED
@@ -11,6 +11,8 @@ 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
+ var { runPreflight } = require("./settings-preflight");
14
16
 
15
17
  // --- lr-29f9: Global concurrent-session ceiling ---
16
18
  // Counts queries that are actively running (startQuery entered, processQueryStream
@@ -33,6 +35,21 @@ var DEFAULT_MEM_AVAILABLE_MIN_MB = 1024;
33
35
  // yielding approximately 67 tokens per MB of headroom consumed.
34
36
  var DEFAULT_TOKENS_PER_MB_HEADROOM = 67;
35
37
 
38
+ // Configurable warn fractions for context guards (lr-1f7e).
39
+ // cgroupWarnFraction: warn when context tokens exceed this fraction of the
40
+ // cgroup-headroom-derived ceiling (configurable via getConfig().cgroupWarnFraction).
41
+ // contextWindowWarnFraction: proactively warn when context tokens exceed this
42
+ // fraction of the model's context window (configurable via
43
+ // getConfig().contextWindowWarnFraction). 0/null → skip window-based warn.
44
+ var DEFAULT_CGROUP_WARN_FRACTION = 0.8;
45
+ var DEFAULT_CONTEXT_WINDOW_WARN_FRACTION = 0.8;
46
+
47
+ // Known context windows for models the backend may encounter (lr-1f7e, lr-336f).
48
+ // Imported from lib/model-context-windows.js — shared source of truth with the frontend.
49
+ // The alias preserves backward compatibility for any callers that reference this name.
50
+ var BACKEND_KNOWN_CONTEXT_WINDOWS = _BACKEND_KNOWN_CONTEXT_WINDOWS;
51
+ // resolveModelContextWindow imported from lib/model-context-windows.js above.
52
+
36
53
  // Read Linux MemAvailable from /proc/meminfo synchronously.
37
54
  // Returns available memory in MB, or null on non-Linux or read failure.
38
55
  // Sub-millisecond on Linux; the synchronous read is correct here — this is a
@@ -1295,24 +1312,51 @@ function createSDKBridge(opts) {
1295
1312
  return;
1296
1313
  }
1297
1314
  }
1298
- // lr-2d91: cgroup context token guard — applies to ALL turns because long-running
1315
+ // lr-2d91 / lr-1f7e: context token guards — apply to ALL turns because long-running
1299
1316
  // sessions accumulate context across turns and each new turn will load the full
1300
1317
  // accumulated context into memory. Placed after the memAvailableMinMB gate and
1301
1318
  // before the slot is claimed so a rejected query never increments the live counter.
1302
1319
  var contextTokens = session.lastStreamInputTokens || 0;
1303
1320
  if (contextTokens > 0) {
1321
+ // Read configurable fractions once so they are available to both checks below.
1322
+ var _guardCfg = typeof opts.getConfig === "function" ? opts.getConfig() : null;
1323
+ var cgWarnFraction = DEFAULT_CGROUP_WARN_FRACTION;
1324
+ var ctxWinWarnFraction = DEFAULT_CONTEXT_WINDOW_WARN_FRACTION;
1325
+ if (_guardCfg) {
1326
+ if (typeof _guardCfg.cgroupWarnFraction === "number" && _guardCfg.cgroupWarnFraction >= 0) {
1327
+ // 0 is a valid value meaning "disabled" — allow it to override the default
1328
+ cgWarnFraction = _guardCfg.cgroupWarnFraction;
1329
+ }
1330
+ if (typeof _guardCfg.contextWindowWarnFraction === "number" && _guardCfg.contextWindowWarnFraction >= 0) {
1331
+ // 0 is a valid value meaning "disabled" — allow it to override the default
1332
+ ctxWinWarnFraction = _guardCfg.contextWindowWarnFraction;
1333
+ }
1334
+ }
1335
+
1336
+ // lr-1f7e: proactive model context-window warn.
1337
+ // Fires before the cgroup hard gate so the user gets an early signal.
1338
+ // Degrades cleanly when the model window is unknown (resolveModelContextWindow returns 0)
1339
+ // or when ctxWinWarnFraction is 0 (disabled via config).
1340
+ // Pass sm.currentBetas so context-1m beta is respected (mirrors app-panels.js logic).
1341
+ var _sessionModel = session.model || sm.currentModel || null;
1342
+ var _modelWindow = resolveModelContextWindow(_sessionModel, sm.currentBetas || []);
1343
+ if (_modelWindow > 0 && ctxWinWarnFraction > 0) {
1344
+ var _winWarnTokens = Math.floor(_modelWindow * ctxWinWarnFraction);
1345
+ if (contextTokens >= _winWarnTokens) {
1346
+ console.warn("[sdk-bridge] context-window warn: " + Math.round(contextTokens / 1000) + "K tokens >= " + Math.round(_winWarnTokens / 1000) + "K (" + Math.round(ctxWinWarnFraction * 100) + "% of " + Math.round(_modelWindow / 1000) + "K window) for session " + session.localId);
1347
+ send({ type: "toast", level: "warn", message: "Session context is " + Math.round((contextTokens / _modelWindow) * 100) + "% full (" + Math.round(contextTokens / 1000) + "K / " + Math.round(_modelWindow / 1000) + "K tokens). Consider starting a new session.", duration: 8000 });
1348
+ }
1349
+ }
1350
+
1351
+ // lr-2d91: cgroup hard gate — block the query if context exceeds headroom.
1304
1352
  var cgHeadroomMB = readCgroupHeadroomMB();
1305
1353
  if (cgHeadroomMB !== null) {
1306
1354
  var tokensPerMb = DEFAULT_TOKENS_PER_MB_HEADROOM;
1307
- var _getConfig = opts.getConfig;
1308
- if (typeof _getConfig === "function") {
1309
- var _cgCfg = _getConfig();
1310
- if (_cgCfg && typeof _cgCfg.tokensPerMbHeadroom === "number" && _cgCfg.tokensPerMbHeadroom > 0) {
1311
- tokensPerMb = _cgCfg.tokensPerMbHeadroom;
1312
- }
1355
+ if (_guardCfg && typeof _guardCfg.tokensPerMbHeadroom === "number" && _guardCfg.tokensPerMbHeadroom > 0) {
1356
+ tokensPerMb = _guardCfg.tokensPerMbHeadroom;
1313
1357
  }
1314
1358
  var allowedTokens = cgHeadroomMB * tokensPerMb;
1315
- var warnTokens = Math.floor(allowedTokens * 0.8);
1359
+ var warnTokens = Math.floor(allowedTokens * cgWarnFraction);
1316
1360
  if (contextTokens >= allowedTokens) {
1317
1361
  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);
1318
1362
  session.isProcessing = false;
@@ -1323,7 +1367,8 @@ function createSDKBridge(opts) {
1323
1367
  send({ type: "toast", level: "error", message: "Session blocked — context too large for available memory.", duration: 7000 });
1324
1368
  sm.broadcastSessionList();
1325
1369
  return;
1326
- } else if (contextTokens >= warnTokens) {
1370
+ } else if (cgWarnFraction > 0 && contextTokens >= warnTokens) {
1371
+ // cgWarnFraction === 0 means the warn is disabled; skip it.
1327
1372
  send({ type: "toast", level: "warn", message: "Large session context (" + Math.round(contextTokens / 1000) + "K tokens). Consider starting a new session to avoid memory pressure.", duration: 8000 });
1328
1373
  }
1329
1374
  }
@@ -1803,6 +1848,20 @@ function createSDKBridge(opts) {
1803
1848
  sm.modelsByVendor[defaultVendor] = result.models || [];
1804
1849
  sm.capabilitiesByVendor = sm.capabilitiesByVendor || {};
1805
1850
  sm.capabilitiesByVendor[defaultVendor] = result.capabilities || {};
1851
+
1852
+ // lr-1a26: Console-side settings preflight (epic lr-1a52 stage 5/5).
1853
+ // Non-blocking: runs after warmup succeeds, errors are swallowed so
1854
+ // preflight never blocks or fails the init path. Results are sent as
1855
+ // diagnostic events through the same pipeline stages 2-4 established.
1856
+ try {
1857
+ var preflightDiags = runPreflight({ projectDir: cwd });
1858
+ for (var _pi = 0; _pi < preflightDiags.length; _pi++) {
1859
+ send(preflightDiags[_pi]);
1860
+ }
1861
+ } catch (preflightErr) {
1862
+ // Swallow all preflight errors — preflight must never affect init.
1863
+ console.warn("[sdk-bridge] settings preflight failed (non-fatal):", preflightErr && preflightErr.message || preflightErr);
1864
+ }
1806
1865
  } catch (e) {
1807
1866
  if (e && e.name !== "AbortError" && !(e.message && e.message.indexOf("aborted") !== -1)) {
1808
1867
  send({ type: "error", text: "Failed to load " + defaultVendor + " SDK: " + (e.message || e) });
@@ -2115,5 +2174,11 @@ function createSDKBridge(opts) {
2115
2174
  };
2116
2175
  }
2117
2176
 
2118
- module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM };
2177
+ // Return the current number of active live queries across ALL bridge instances.
2178
+ // Used by the drain controller (lr-6b30) to decide when it is safe to exit.
2179
+ function getActiveLiveCount() {
2180
+ return _activeLiveCount;
2181
+ }
2182
+
2183
+ module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, resolveModelContextWindow, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount };
2119
2184
 
@@ -769,6 +769,18 @@ function attachMessageProcessor(ctx) {
769
769
  var retryText = parsed.message || parsed.error || "Retrying API request...";
770
770
  sendToSession(session, { type: "system_info", text: retryText });
771
771
 
772
+ } else if (parsed.yokeType === "diagnostic") {
773
+ // Diagnostic events captured from CLI stderr (stage 3/5, lr-0868, epic lr-1a52).
774
+ // These are NOT errors — they are informational/warning signals from the CLI
775
+ // (e.g. unknown hook events, settings warnings, deprecation notices).
776
+ // Stage 4/5 (lr-8294) renders this message as a toast + Diagnostics panel entry.
777
+ sendAndRecord(session, {
778
+ type: "diagnostic",
779
+ severity: parsed.severity,
780
+ source: parsed.source,
781
+ message: parsed.message,
782
+ });
783
+
772
784
  } else if (parsed.yokeType === "system") {
773
785
  // Catch-all for unhandled system subtypes (e.g. hook-block errors).
774
786
  // Extract any error text and surface it in the UI.
package/lib/sdk-worker.js CHANGED
@@ -370,7 +370,10 @@ async function handleQueryStart(msg) {
370
370
  if (_mcpServers) options.mcpServers = _mcpServers;
371
371
  options.abortController = abortController;
372
372
  if (process.env.CLAGENTIC_DEBUG === "1") {
373
- var _logDir = path.join(os.homedir(), ".clagentic", "worker-logs");
373
+ // worker-logs lives under CONFIG_DIR (= ~/.clagentic/console/); old path was ~/.clagentic/worker-logs/.
374
+ // No migration needed — these are ephemeral debug logs, not persistent data.
375
+ var _configDir = process.env.CLAGENTIC_HOME ? path.join(process.env.CLAGENTIC_HOME, "console") : path.join(os.homedir(), ".clagentic", "console");
376
+ var _logDir = path.join(_configDir, "worker-logs");
374
377
  fs.mkdirSync(_logDir, { recursive: true, mode: 0o700 });
375
378
  var _logFile = path.join(_logDir, process.pid + ".log");
376
379
  // Create with 0o600 before passing to the SDK so the file is never world-readable
package/lib/server.js CHANGED
@@ -365,7 +365,7 @@ function createServer(opts) {
365
365
  return;
366
366
  }
367
367
 
368
- // PWA install guide (builtin cert mode, no CA step needed)
368
+ // PWA install guide
369
369
  if (fullUrl === "/pwa" && req.method === "GET") {
370
370
  var host = req.headers.host || "localhost";
371
371
  var hostname = host.split(":")[0];
@@ -732,6 +732,14 @@ function createServer(opts) {
732
732
  });
733
733
  }
734
734
 
735
+ // --- Drain state (lr-6b30) ---
736
+ // Injected by daemon.js via setDrain() after the drain controller is created.
737
+ var _drainController = null;
738
+
739
+ function setDrain(drainController) {
740
+ _drainController = drainController;
741
+ }
742
+
735
743
  // --- WebSocket ---
736
744
  var wss = new WebSocketServer({ noServer: true });
737
745
 
@@ -771,6 +779,23 @@ function createServer(opts) {
771
779
  return;
772
780
  }
773
781
 
782
+ // Drain gate (lr-6b30): reject new sessions while draining so in-flight
783
+ // sessions can complete before the daemon exits.
784
+ if (_drainController && _drainController.isDraining()) {
785
+ socket.write(
786
+ "HTTP/1.1 503 Service Unavailable\r\n" +
787
+ "Content-Type: application/json\r\n" +
788
+ "Connection: close\r\n" +
789
+ "\r\n"
790
+ );
791
+ socket.end(JSON.stringify({
792
+ type: "error",
793
+ code: "server_draining",
794
+ message: "Server is draining for restart. Please reconnect in a moment.",
795
+ }));
796
+ return;
797
+ }
798
+
774
799
  // Extract slug from WS URL: /p/{slug}/ws
775
800
  var wsSlug = extractSlug(req.url);
776
801
  if (!wsSlug) {
@@ -1410,6 +1435,8 @@ function createServer(opts) {
1410
1435
  forEachProject: forEachProject,
1411
1436
  destroyProject: removeProject,
1412
1437
  destroyAll: destroyAll,
1438
+ // Drain controller injection (lr-6b30).
1439
+ setDrain: setDrain,
1413
1440
  };
1414
1441
  }
1415
1442
 
package/lib/sessions.js CHANGED
@@ -313,11 +313,14 @@ function createSessionManager(opts) {
313
313
 
314
314
  // Drain all write buffers synchronously on process exit to prevent trailing
315
315
  // event loss when the daemon shuts down cleanly.
316
- process.on("exit", function() {
316
+ // Named so it can be deregistered via sm.destroy() when the project is torn
317
+ // down — avoids accumulating one listener per project open (lr-daca).
318
+ function _onProcessExit() {
317
319
  sessions.forEach(function(session) {
318
320
  flushSessionBuffer(session);
319
321
  });
320
- });
322
+ }
323
+ process.on("exit", _onProcessExit);
321
324
 
322
325
  function getActiveSession() {
323
326
  return sessions.get(activeSessionId) || null;
@@ -1163,6 +1166,12 @@ function createSessionManager(opts) {
1163
1166
  return { ok: true };
1164
1167
  },
1165
1168
  permissionRequestIndex: permissionRequestIndex,
1169
+ // Remove the process-level exit listener registered above.
1170
+ // Must be called when the project owning this session manager is destroyed
1171
+ // so listeners do not accumulate across project open/close cycles (lr-daca).
1172
+ destroy: function() {
1173
+ process.removeListener("exit", _onProcessExit);
1174
+ },
1166
1175
  };
1167
1176
  }
1168
1177
 
@@ -0,0 +1,212 @@
1
+ // settings-preflight.js — Console-side settings.json preflight validator.
2
+ //
3
+ // Part of epic lr-1a52 stage 5/5 (lr-1a26): deterministic, version-independent
4
+ // preflight that validates ~/.claude/settings.json and project .claude/settings.json
5
+ // without relying on CLI stderr pattern matching.
6
+ //
7
+ // Public surface:
8
+ // validateSettingsObject(obj, filePath) — pure: settings obj → diagnostic[]
9
+ // runPreflight(opts) — IO: reads files, validates, returns diagnostic[]
10
+ // VALID_HOOK_EVENTS — exported for tests
11
+ //
12
+ // Diagnostic shape (conforms to validateDiagnosticEvent from YOKE interface):
13
+ // { type: 'diagnostic', severity, source: 'preflight', message }
14
+
15
+ "use strict";
16
+
17
+ var fs = require("fs");
18
+ var path = require("path");
19
+ var os = require("os");
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Hook event allowlist
23
+ //
24
+ // SOURCE: This list was derived from the Claude Code CLI documentation and SDK
25
+ // source as of 2026-06-30 (claude@1.x). The hooks.AgentTeams case (the
26
+ // motivating screenshot for this stage) is a real example of an unknown key
27
+ // that surfaces as a silent no-op in the CLI but clutters the warnings stream.
28
+ //
29
+ // IMPORTANT: This list is the ONLY place the valid hook events are defined in
30
+ // the Console codebase. Do not duplicate it elsewhere — drift between copies
31
+ // is exactly the parity bug we are fixing.
32
+ //
33
+ // TODO(lr-1a26): Sync this list whenever the Claude Code CLI releases new hook
34
+ // event types. The authoritative upstream is the CLI's hook documentation or
35
+ // source (search for "hook" + "event" in the @anthropic-ai/claude-code package).
36
+ // Consider scripting a CI check against the installed CLI version's known events
37
+ // if the CLI exposes a machine-readable list in a future release.
38
+ // ---------------------------------------------------------------------------
39
+ var VALID_HOOK_EVENTS = [
40
+ "PreToolUse",
41
+ "PostToolUse",
42
+ "Notification",
43
+ "Stop",
44
+ "SubagentStop",
45
+ ];
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Pure validator
49
+ // ---------------------------------------------------------------------------
50
+
51
+ /**
52
+ * Validate a parsed settings object for known structural problems.
53
+ *
54
+ * Pure function — no IO, no side effects. Suitable for unit testing.
55
+ *
56
+ * @param {object} obj - Parsed settings JSON (any shape; we check what we know)
57
+ * @param {string} filePath - Path string used only in diagnostic messages
58
+ * @returns {Array<{type,severity,source,message}>} Diagnostics (empty = no issues)
59
+ */
60
+ function validateSettingsObject(obj, filePath) {
61
+ var diagnostics = [];
62
+ var label = filePath || "settings.json";
63
+
64
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
65
+ // Nothing meaningful to validate — caller should have caught this at parse time
66
+ return diagnostics;
67
+ }
68
+
69
+ // (b) Known-hook-event allowlist check.
70
+ // The hooks field is expected to be an object whose keys are hook event names.
71
+ // Unknown keys silently no-op in the CLI but should warn operators.
72
+ if (obj.hooks !== null && obj.hooks !== undefined) {
73
+ if (typeof obj.hooks !== "object" || Array.isArray(obj.hooks)) {
74
+ diagnostics.push({
75
+ type: "diagnostic",
76
+ severity: "warning",
77
+ source: "preflight",
78
+ message: label + ": 'hooks' field is not an object — expected { EventName: [...] }.",
79
+ });
80
+ } else {
81
+ var hookKeys = Object.keys(obj.hooks);
82
+ for (var i = 0; i < hookKeys.length; i++) {
83
+ var key = hookKeys[i];
84
+ if (VALID_HOOK_EVENTS.indexOf(key) === -1) {
85
+ diagnostics.push({
86
+ type: "diagnostic",
87
+ severity: "warning",
88
+ source: "preflight",
89
+ message: label + ": unknown hook event '" + key + "'. Valid events: " + VALID_HOOK_EVENTS.join(", ") + ". This hook will be silently ignored by the CLI.",
90
+ });
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ return diagnostics;
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // IO layer
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /**
104
+ * Validate a single settings.json file.
105
+ *
106
+ * Returns an array of diagnostic objects:
107
+ * - Empty array → file absent, or file is clean (silence is success)
108
+ * - error entry → file exists but failed JSON.parse
109
+ * - warning entries → file parsed but has structural problems
110
+ *
111
+ * Never throws — all errors are surfaced as diagnostics or swallowed
112
+ * per the non-blocking preflight contract.
113
+ *
114
+ * @param {string} filePath - Absolute path to settings.json
115
+ * @returns {Array<object>} diagnostics
116
+ */
117
+ function validateSettingsFile(filePath) {
118
+ var diagnostics = [];
119
+
120
+ // Missing file → nothing to validate. Not an error.
121
+ var raw;
122
+ try {
123
+ raw = fs.readFileSync(filePath, "utf8");
124
+ } catch (e) {
125
+ if (e.code === "ENOENT") return diagnostics;
126
+ // Unreadable file (permissions etc.) → low-severity, not user-facing error
127
+ diagnostics.push({
128
+ type: "diagnostic",
129
+ severity: "info",
130
+ source: "preflight",
131
+ message: filePath + ": could not read settings file (" + e.code + " — " + (e.message || String(e)) + ").",
132
+ });
133
+ return diagnostics;
134
+ }
135
+
136
+ // (a) JSON parse check
137
+ var obj;
138
+ try {
139
+ obj = JSON.parse(raw);
140
+ } catch (e) {
141
+ diagnostics.push({
142
+ type: "diagnostic",
143
+ severity: "error",
144
+ source: "preflight",
145
+ message: filePath + ": settings.json is not valid JSON — " + (e.message || String(e)) + ".",
146
+ });
147
+ return diagnostics;
148
+ }
149
+
150
+ // (b) Structural validation
151
+ var structural = validateSettingsObject(obj, filePath);
152
+ for (var i = 0; i < structural.length; i++) {
153
+ diagnostics.push(structural[i]);
154
+ }
155
+
156
+ return diagnostics;
157
+ }
158
+
159
+ /**
160
+ * Run the full preflight check against both user and project settings files.
161
+ *
162
+ * @param {object} opts
163
+ * @param {string} [opts.userHome] - Home directory to find ~/.claude/settings.json.
164
+ * Resolved via REAL_HOME from config.js when absent.
165
+ * @param {string} [opts.projectDir] - Project working directory to find .claude/settings.json.
166
+ * When absent (or empty), project settings are skipped.
167
+ * @returns {Array<object>} All diagnostics across both files (empty = all clean)
168
+ */
169
+ function runPreflight(opts) {
170
+ opts = opts || {};
171
+
172
+ var diagnostics = [];
173
+
174
+ // Resolve the user home from config.js (honours SUDO_USER resolution),
175
+ // falling back to os.homedir() if the module is unavailable.
176
+ // The REAL_HOME constant in config.js is already resolved on module load —
177
+ // reading it here is free (no IO, no side effect).
178
+ var userHome = opts.userHome;
179
+ if (!userHome) {
180
+ try {
181
+ userHome = require("./config").REAL_HOME;
182
+ } catch (e) {
183
+ userHome = os.homedir();
184
+ }
185
+ }
186
+
187
+ // User global: ~/.claude/settings.json
188
+ var userSettingsPath = path.join(userHome, ".claude", "settings.json");
189
+ var userDiags = validateSettingsFile(userSettingsPath);
190
+ for (var i = 0; i < userDiags.length; i++) {
191
+ diagnostics.push(userDiags[i]);
192
+ }
193
+
194
+ // Project-local: <projectDir>/.claude/settings.json (optional)
195
+ var projectDir = opts.projectDir;
196
+ if (projectDir && typeof projectDir === "string" && projectDir.length > 0) {
197
+ var projectSettingsPath = path.join(projectDir, ".claude", "settings.json");
198
+ var projectDiags = validateSettingsFile(projectSettingsPath);
199
+ for (var j = 0; j < projectDiags.length; j++) {
200
+ diagnostics.push(projectDiags[j]);
201
+ }
202
+ }
203
+
204
+ return diagnostics;
205
+ }
206
+
207
+ module.exports = {
208
+ VALID_HOOK_EVENTS: VALID_HOOK_EVENTS,
209
+ validateSettingsObject: validateSettingsObject,
210
+ validateSettingsFile: validateSettingsFile,
211
+ runPreflight: runPreflight,
212
+ };
@@ -18,6 +18,7 @@ var crypto = require("crypto");
18
18
  var path = require("path");
19
19
  var fs = require("fs");
20
20
  var os = require("os");
21
+ var parseDiagnosticLine = require("./diagnostic-patterns").parseDiagnosticLine;
21
22
 
22
23
  var socketPath = process.argv[2];
23
24
  if (!socketPath) {
@@ -463,13 +464,24 @@ async function handleQueryStart(msg) {
463
464
  });
464
465
  // Track the child so cleanup() can terminate it on worker shutdown.
465
466
  _claudeChildProcess = cp;
466
- // Capture ALL CLI stderr
467
+ // Capture ALL CLI stderr. Known diagnostic lines are also emitted as
468
+ // 'diagnostic' YOKE events (stage 2/5, lr-28ee) so they can be routed to
469
+ // the Console UI. The raw [CLI-STDERR] log is always kept regardless.
467
470
  if (cp.stderr) {
468
471
  cp.stderr.on("data", function(chunk) {
469
472
  var lines = chunk.toString().split("\n");
470
473
  for (var li = 0; li < lines.length; li++) {
471
474
  var line = lines[li].trim();
472
- if (line) console.log("[CLI-STDERR] " + line.substring(0, 500));
475
+ if (!line) continue;
476
+ console.log("[CLI-STDERR] " + line.substring(0, 500));
477
+ var diag = parseDiagnosticLine(line);
478
+ if (diag) {
479
+ // Emit as sdk_event so the existing IPC path (createWorkerQueryHandle
480
+ // → flattenEvent) carries it through unchanged. flattenEvent will
481
+ // tag it yokeType:"unknown"/rawType:"diagnostic" until stage 3/5
482
+ // (lr-0868) adds the explicit branch in flattenEvent().
483
+ sendToDaemon({ type: "sdk_event", event: diag });
484
+ }
473
485
  }
474
486
  });
475
487
  }
@@ -259,6 +259,19 @@ function flattenEvent(raw) {
259
259
  return raw;
260
260
  }
261
261
 
262
+ // --- diagnostic events (stage 2/5, lr-28ee / stage 3/5, lr-0868) ---
263
+ // Emitted by claude-worker.js via sdk_event when parseDiagnosticLine matches
264
+ // a CLI stderr line. Shape: { type:'diagnostic', severity, source, message }.
265
+ // Must NOT fall through to the unknown catch-all — the processor routes on
266
+ // yokeType:'diagnostic' to produce a distinct frontend message (not 'error').
267
+ if (raw.type === "diagnostic") {
268
+ base.yokeType = "diagnostic";
269
+ base.severity = raw.severity;
270
+ base.source = raw.source;
271
+ base.message = raw.message;
272
+ return base;
273
+ }
274
+
262
275
  // --- fallback: unknown event type ---
263
276
  base.yokeType = "unknown";
264
277
  base.rawType = raw.type;
@@ -1600,5 +1613,8 @@ module.exports = {
1600
1613
  createClaudeAdapter: createClaudeAdapter,
1601
1614
  createMessageQueue: createMessageQueue,
1602
1615
  _test_handleWorkerEarlyExit: _test_handleWorkerEarlyExit,
1616
+ // Test seam for hop-A diagnostic routing (lr-0868): allows test/diagnostic-routing-lr-0868.test.js
1617
+ // to call flattenEvent directly without spawning a worker process.
1618
+ _test_flattenEvent: flattenEvent,
1603
1619
  };
1604
1620