@chroxy/server 0.10.0 → 0.11.0

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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
package/src/logger.js CHANGED
@@ -15,7 +15,10 @@
15
15
  * // => 2026-02-22T12:34:56.789Z [INFO] [supervisor] Server ready
16
16
  */
17
17
 
18
- import { appendFileSync, statSync, renameSync, mkdirSync, chmodSync } from 'fs'
18
+ import {
19
+ appendFileSync, statSync, renameSync, mkdirSync, chmodSync,
20
+ openSync, readSync, closeSync, writeFileSync, truncateSync,
21
+ } from 'fs'
19
22
  import { join } from 'path'
20
23
  import { homedir } from 'os'
21
24
  import { SENSITIVE_PATTERNS, API_KEY_PATTERNS, redactValue } from './redaction.js'
@@ -25,6 +28,22 @@ const MAX_LOG_SIZE = 5 * 1024 * 1024 // 5MB
25
28
  const MAX_LOG_FILES = 3
26
29
  const ROTATION_CHECK_INTERVAL = 100 // check every N writes
27
30
 
31
+ // #7162: audit retention floor (discord-return-path.md §9.1). [AUDIT] lines are
32
+ // dual-written to a dedicated chroxy-audit.log with its own rotation budget, so
33
+ // the audit trail's lifetime is bounded by AUDIT volume alone — a noisy debug
34
+ // period churning chroxy.log through its 5MB×3 cascade can never displace an
35
+ // audit line. Budget: 10MB live + 4 archives ≈ 50MB ceiling; §9.1's rate
36
+ // ceilings and reject-collapse bound audit volume, so this is years of trail.
37
+ const AUDIT_LOG_NAME = 'chroxy-audit.log'
38
+ const MAX_AUDIT_LOG_SIZE = 10 * 1024 * 1024 // 10MB
39
+ const MAX_AUDIT_LOG_FILES = 4
40
+
41
+ // #7162: bounds for the service-manager stdout/stderr capture files
42
+ // (launchd StandardOutPath / systemd StandardOutput=file: / cmd `>>`), which
43
+ // no service manager rotates. Capped at daemon boot by capStdioCaptureLogs().
44
+ const STDIO_CAPTURE_MAX_SIZE = 5 * 1024 * 1024 // 5MB
45
+ const STDIO_CAPTURE_TAIL_KEEP = 1 * 1024 * 1024 // preserved to *.old.log
46
+
28
47
  const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }
29
48
 
30
49
  // #6029: the value-SHAPE patterns (SENSITIVE_PATTERNS / API_KEY_PATTERNS) and
@@ -112,7 +131,9 @@ let _jsonMode = false
112
131
  let _logToFile = false
113
132
  let _logDir = DEFAULT_LOG_DIR
114
133
  let _logPath = null
134
+ let _auditLogPath = null
115
135
  let _writeCount = 0
136
+ let _quietConsole = false
116
137
 
117
138
  /** Set of callbacks for broadcasting log entries (supports multiple WsServer instances) */
118
139
  const _logListeners = new Set()
@@ -179,6 +200,24 @@ export function initFileLogging({ level = 'info', logDir } = {}) {
179
200
  // we keep going. The mkdir mode bit covers fresh-create.
180
201
  }
181
202
  _logPath = join(_logDir, 'chroxy.log')
203
+ _auditLogPath = join(_logDir, AUDIT_LOG_NAME)
204
+ }
205
+
206
+ /**
207
+ * #7162: quiet the console mirror in daemon mode. Under a service manager the
208
+ * console streams are captured to chroxy-stdout/stderr.log, which nothing
209
+ * rotates — mirroring every file-logged line there is how the capture reached
210
+ * 32MB in a month. When quiet, info/debug/audit lines skip the console (the
211
+ * rotated file log is authoritative); warn/error still print, so crash-adjacent
212
+ * output keeps landing in chroxy-stderr.log.
213
+ *
214
+ * Fail-safe: quieting only ever suppresses a line that was ALSO written to the
215
+ * file log — if file logging is off or the path is unset, the console mirror
216
+ * stays on regardless of this flag (see write()).
217
+ * @param {boolean} enabled
218
+ */
219
+ export function setConsoleQuiet(enabled) {
220
+ _quietConsole = !!enabled
182
221
  }
183
222
 
184
223
  /**
@@ -191,6 +230,87 @@ export function getLogPath() {
191
230
  return _logToFile ? _logPath : null
192
231
  }
193
232
 
233
+ /**
234
+ * Return the on-disk audit log path (#7162), or `null` if file logging is
235
+ * disabled. #7169's fail-closed audit writer gates on this being non-null —
236
+ * it is the "file-backed logging" precondition §9.1 requires `enable` to check.
237
+ * @returns {string|null}
238
+ */
239
+ export function getAuditLogPath() {
240
+ return _logToFile ? _auditLogPath : null
241
+ }
242
+
243
+ /**
244
+ * #7162: bound the service-manager capture files (launchd StandardOutPath /
245
+ * systemd StandardOutput=file: / the Windows wrapper's `>>`), which no service
246
+ * manager rotates. Called once at daemon boot.
247
+ *
248
+ * Mechanics are copy-tail-then-truncate, NEVER rename: the service manager
249
+ * (and this process, as fd 1/2) holds an open descriptor on the inode, so a
250
+ * rename would silently divert the live stream into the archive until the next
251
+ * restart. launchd opens the capture with O_APPEND, so writes after the
252
+ * truncate land at the new end. On systemd (`file:` — non-append fd) the
253
+ * truncate is safe ONLY while the fd offset is ~0, which is why the single
254
+ * call site is the `start` command (server-cmd.js), in the process the
255
+ * service manager spawned, BEFORE any supervisor fork — a supervised child
256
+ * restart re-entering this would truncate under the supervisor's live
257
+ * offset. Windows is excluded outright: the Task Scheduler wrapper redirects
258
+ * with cmd `>>`, whose handle does not have POSIX append semantics, and the
259
+ * next write would re-extend the file with a NUL-padded gap — the generated
260
+ * .cmd wrapper rotates the captures itself before the redirect handle exists
261
+ * (see generateWindowsServiceWrapper).
262
+ *
263
+ * @param {object} [options]
264
+ * @param {string} [options.logDir] - defaults to DEFAULT_LOG_DIR: the capture
265
+ * location is baked into the plist/unit by `service install` (always
266
+ * `~/.chroxy/logs`), so it deliberately does NOT follow a custom
267
+ * CHROXY_LOG_DIR, which only moves the logger's own files
268
+ * @param {number} [options.maxSize] - cap before truncation kicks in
269
+ * @param {number} [options.tailKeep] - bytes preserved to `<name>.old.log`
270
+ * @returns {Array<{file: string, archive: string, preservedBytes: number}>}
271
+ * one entry per file that was capped (empty when nothing exceeded the cap)
272
+ */
273
+ export function capStdioCaptureLogs({
274
+ logDir,
275
+ maxSize = STDIO_CAPTURE_MAX_SIZE,
276
+ tailKeep = STDIO_CAPTURE_TAIL_KEEP,
277
+ } = {}) {
278
+ if (process.platform === 'win32') return []
279
+ const dir = logDir || DEFAULT_LOG_DIR
280
+ const capped = []
281
+ for (const name of ['chroxy-stdout.log', 'chroxy-stderr.log']) {
282
+ const filePath = join(dir, name)
283
+ try {
284
+ const stats = statSync(filePath)
285
+ if (stats.size <= maxSize) continue
286
+ const archive = filePath.replace(/\.log$/, '.old.log')
287
+ const keep = Math.min(tailKeep, stats.size)
288
+ const fd = openSync(filePath, 'r')
289
+ let tail
290
+ try {
291
+ const buf = Buffer.alloc(keep)
292
+ const read = readSync(fd, buf, 0, keep, stats.size - keep)
293
+ tail = buf.subarray(0, read)
294
+ } finally {
295
+ closeSync(fd)
296
+ }
297
+ // Start the archive on a whole line when the tail begins mid-line
298
+ // (when keep < size, byte 0 is almost certainly a truncated line).
299
+ if (keep < stats.size) {
300
+ const nl = tail.indexOf(0x0a)
301
+ if (nl !== -1 && nl < tail.length - 1) tail = tail.subarray(nl + 1)
302
+ }
303
+ writeFileSync(archive, tail)
304
+ truncateSync(filePath, 0)
305
+ capped.push({ file: filePath, archive, preservedBytes: tail.length })
306
+ } catch {
307
+ // Capture file absent, or unreadable — nothing to bound. Never let a
308
+ // capping failure interfere with boot (#746 spirit).
309
+ }
310
+ }
311
+ return capped
312
+ }
313
+
194
314
  /**
195
315
  * Close file logging. Used in tests for cleanup.
196
316
  */
@@ -200,24 +320,33 @@ export function closeFileLogging() {
200
320
  _logLevel = LOG_LEVELS.info
201
321
  _logDir = DEFAULT_LOG_DIR
202
322
  _logPath = null
323
+ _auditLogPath = null
203
324
  _writeCount = 0
325
+ _quietConsole = false
204
326
  _logListeners.clear()
205
327
  }
206
328
 
207
- function _maybeRotate() {
208
- if (!_logPath) return
329
+ /**
330
+ * Size-gated rename-cascade rotation, shared by the main log and the audit log.
331
+ * Rotate: base.N.log (overwritten) <- ... <- base.1.log <- base.log
332
+ */
333
+ function _maybeRotateAt(logPath, maxSize, maxFiles) {
334
+ if (!logPath) return
209
335
  try {
210
- const stats = statSync(_logPath)
211
- if (stats.size < MAX_LOG_SIZE) return
336
+ const stats = statSync(logPath)
337
+ if (stats.size < maxSize) return
212
338
  } catch (err) {
213
339
  if (err?.code !== 'ENOENT') console.error('[logger] stat failed:', err?.message)
214
340
  return
215
341
  }
216
342
 
217
- // Rotate: chroxy.3.log (overwritten) <- chroxy.2.log <- chroxy.1.log <- chroxy.log
218
- for (let i = MAX_LOG_FILES; i >= 1; i--) {
219
- const from = i === 1 ? _logPath : _logPath.replace('.log', `.${i - 1}.log`)
220
- const to = _logPath.replace('.log', `.${i}.log`)
343
+ // #7162: anchored to the FINAL '.log' — a first-occurrence string replace
344
+ // would rewrite a '.log' embedded in the directory path (e.g. a log dir
345
+ // named 'my.logs'), aiming every rename at a nonexistent sibling dir and
346
+ // silently disabling rotation (the ENOENT is swallowed below by design).
347
+ for (let i = maxFiles; i >= 1; i--) {
348
+ const from = i === 1 ? logPath : logPath.replace(/\.log$/, `.${i - 1}.log`)
349
+ const to = logPath.replace(/\.log$/, `.${i}.log`)
221
350
  try {
222
351
  renameSync(from, to)
223
352
  } catch (err) {
@@ -226,6 +355,10 @@ function _maybeRotate() {
226
355
  }
227
356
  }
228
357
 
358
+ function _maybeRotate() {
359
+ _maybeRotateAt(_logPath, MAX_LOG_SIZE, MAX_LOG_FILES)
360
+ }
361
+
229
362
  /**
230
363
  * Change the minimum log level at runtime.
231
364
  * Useful for --verbose CLI flags to enable debug output. (#747)
@@ -270,11 +403,36 @@ export function createLogger(component, context = {}) {
270
403
  ? JSON.stringify({ ts: timestamp, level, component, msg: safeMsg })
271
404
  : `${timestamp} [${level.toUpperCase()}] [${component}] ${safeMsg}`
272
405
 
406
+ // #7162: the file write happens FIRST so console quieting can key on this
407
+ // line's ACTUAL fate rather than on configuration: a quieted line whose
408
+ // file append fails (disk full, permissions) falls back to the console
409
+ // mirror, so no line — audit lines above all — is ever lost to both
410
+ // sinks at once.
411
+ let fileWriteOk = false
412
+ if (_logToFile && _logPath) {
413
+ try {
414
+ appendFileSync(_logPath, line + '\n')
415
+ fileWriteOk = true
416
+ _writeCount++
417
+ if (_writeCount % ROTATION_CHECK_INTERVAL === 0) {
418
+ _maybeRotate()
419
+ }
420
+ } catch {
421
+ // Silently ignore write failures (disk full, permission denied, etc.)
422
+ // to prevent logging errors from crashing the server (#746).
423
+ // fileWriteOk stays false, which re-enables the console mirror below.
424
+ }
425
+ }
426
+
273
427
  // Write to console (for foreground mode). #6566: `toConsole:false` suppresses
274
428
  // the console write while keeping the file + listener paths — used by the
275
429
  // supervisor to log a REDACTED connect-block line to disk while printing the
276
430
  // un-redacted line to the operator's terminal separately under --show-token.
277
- if (toConsole) {
431
+ // #7162: daemon-mode quieting drops info/debug/audit console mirrors, but
432
+ // only for a line the file log verifiably recorded (fileWriteOk).
433
+ const quieted = _quietConsole && fileWriteOk
434
+ && level !== 'warn' && level !== 'error'
435
+ if (toConsole && !quieted) {
278
436
  if (level === 'error') console.error(line)
279
437
  else if (level === 'warn') console.warn(line)
280
438
  else console.log(line)
@@ -293,17 +451,22 @@ export function createLogger(component, context = {}) {
293
451
  }
294
452
  }
295
453
 
296
- // Write to file in daemon mode
297
- if (_logToFile && _logPath) {
454
+ // #7162: audit lines additionally land in the dedicated audit log — the
455
+ // §9.1 retention floor. Gated on the level itself (only audit() produces
456
+ // it), NOT on `always`, so a future caller passing {always:true} to
457
+ // info()/warn() cannot write non-audit content into the forensic file.
458
+ // Rotation is size-checked on every audit write (audit volume is
459
+ // rate-ceiling-bounded, so the per-write stat is cheap). The line stays
460
+ // in chroxy.log above ("in the daemon log", §9.1); this copy is the one
461
+ // whose retention noise can't touch. Kept fire-and-forget here — #7169's
462
+ // fail-closed audit writer layers its success-reporting on top of this
463
+ // sink rather than replacing the level-independent path.
464
+ if (level === 'audit' && _logToFile && _auditLogPath) {
298
465
  try {
299
- appendFileSync(_logPath, line + '\n')
300
- _writeCount++
301
- if (_writeCount % ROTATION_CHECK_INTERVAL === 0) {
302
- _maybeRotate()
303
- }
466
+ appendFileSync(_auditLogPath, line + '\n')
467
+ _maybeRotateAt(_auditLogPath, MAX_AUDIT_LOG_SIZE, MAX_AUDIT_LOG_FILES)
304
468
  } catch {
305
- // Silently ignore write failures (disk full, permission denied, etc.)
306
- // to prevent logging errors from crashing the server (#746)
469
+ // Same #746 rationale as above.
307
470
  }
308
471
  }
309
472
  }
@@ -119,6 +119,26 @@ export const CATEGORY_DEFAULTS = Object.freeze(
119
119
  */
120
120
  export const DEFAULT_BYPASS_CATEGORIES = Object.freeze(['permission', 'activity_error'])
121
121
 
122
+ /**
123
+ * #7080 — wire bounds mirroring `ServerNotificationPrefsSchema` in @chroxy/protocol
124
+ * (schemas/server/billing.ts): a bypass entry is `min(1).max(64)`, the list is
125
+ * `.max(64)` items, and a device token is a record key of `min(1).max(512)`.
126
+ *
127
+ * The loader used to enforce TYPE only (`typeof s === 'string' && s.length > 0`)
128
+ * while the schema constrains RANGE, so a hand-edited prefs file produced a
129
+ * message the clients could not parse. The failure is unusually bad for a
130
+ * "cosmetic" cap: the client safeParses the WHOLE message, so `notificationPrefs`
131
+ * stays null and the dashboard renders "Loading preferences…" indefinitely on both
132
+ * clients — and `push.js` re-persists the offending value on the next patch, so it
133
+ * never self-heals. Refusing the value here is what keeps the panel alive.
134
+ *
135
+ * Pinned by a test that safeParses the REAL schema, so these cannot drift silently.
136
+ * (#7085 tracks exporting these from @chroxy/protocol so loaders stop retyping them.)
137
+ */
138
+ const MAX_BYPASS_CATEGORY_CHARS = 64
139
+ const MAX_BYPASS_CATEGORIES = 64
140
+ const MAX_DEVICE_TOKEN_CHARS = 512
141
+
122
142
  const _ALL_CATEGORIES_SET = new Set(ALL_CATEGORIES)
123
143
  // Two-digit zero-padded HH:MM with HH in 00-23 and MM in 00-59 (#4566).
124
144
  // The narrower regex replaces the older `/^\d{2}:\d{2}$/`, which accepted
@@ -179,6 +199,22 @@ function sanitizeDevices(raw, { log } = {}) {
179
199
  const out = {}
180
200
  for (const [token, entry] of Object.entries(raw)) {
181
201
  if (typeof token !== 'string' || token.length === 0) continue
202
+ // #7080: DROP an over-cap token, symmetric with the non-string/empty cases
203
+ // above. A push token is an ADDRESS: truncating it to 512 yields a token that
204
+ // addresses nothing and is then re-persisted by the next patch, permanently
205
+ // corrupting the file. Dropping self-heals on the next register_push_token.
206
+ if (token.length > MAX_DEVICE_TOKEN_CHARS) {
207
+ // NOTE this is DESTRUCTIVE on the next write: loadPrefs' output is also what
208
+ // savePrefs persists, and push.js `touchDevice` re-persists the whole
209
+ // sanitized object on every register_push_token — so one phone reconnecting
210
+ // erases this entry from disk. Accepted deliberately: a >512-char key cannot
211
+ // be a real push token, so nothing addressable is lost, and the alternative
212
+ // (preserving it) needs a load-for-wire / load-for-persistence split that
213
+ // does not exist here. Unlike a scheduled task (#7050), there is no operator
214
+ // data in an unrouteable token worth keeping.
215
+ log?.warn?.(`notification-prefs: dropped a device entry whose token exceeds ${MAX_DEVICE_TOKEN_CHARS} chars (unrepresentable on the wire; it will not survive the next save)`)
216
+ continue
217
+ }
182
218
  if (!entry || typeof entry !== 'object') continue
183
219
  const cleaned = { categories: sanitizeCategoryMap(entry.categories) }
184
220
  // Tri-state: present-as-null means "explicitly disable muting on this
@@ -196,7 +232,7 @@ function sanitizeDevices(raw, { log } = {}) {
196
232
  }
197
233
  }
198
234
  if (Object.prototype.hasOwnProperty.call(entry, 'bypassCategories')) {
199
- const bypass = sanitizeBypassList(entry.bypassCategories)
235
+ const bypass = sanitizeBypassList(entry.bypassCategories, { log, context: `device ${token} bypassCategories` })
200
236
  if (bypass !== null) cleaned.bypassCategories = bypass
201
237
  }
202
238
  // #4587: non-critical metadata for the per-device list UI. Operators
@@ -260,17 +296,63 @@ function sanitizeQuietHours(raw) {
260
296
  * (older binary, newer prefs file mentioning a category the binary hasn't
261
297
  * shipped yet) preserves the stored value.
262
298
  */
263
- function sanitizeBypassList(raw) {
299
+ function sanitizeBypassList(raw, { log, context = 'bypassCategories' } = {}) {
264
300
  if (raw == null) return null
265
301
  if (!Array.isArray(raw)) return []
266
- const seen = new Set()
302
+ // Retain KNOWN categories (a fixed set of ALL_CATEGORIES.length) and at most
303
+ // MAX_BYPASS_CATEGORIES unknowns, so a hostile file with a huge array cannot make
304
+ // the loader hold the whole thing. Deliberately NOT "keep the first N while
305
+ // iterating": that bounds memory but is positional, which is exactly what dropped
306
+ // a real `permission` entry past the cap (see the clamp comment below).
307
+ const knownSeen = new Set()
308
+ const unknownSeen = new Set()
309
+ let droppedLong = 0
310
+ let droppedOverflow = 0
267
311
  for (const item of raw) {
268
312
  if (typeof item !== 'string') continue
269
313
  const trimmed = item.trim()
270
314
  if (trimmed.length === 0) continue
271
- seen.add(trimmed)
315
+ // #7080: REJECT the element rather than truncating it. A category name is an
316
+ // identifier matched against ALL_CATEGORIES, so a truncated name matches
317
+ // nothing AND gets re-persisted — strictly worse than dropping it. This does
318
+ // narrow the forward-compat intent above: a future category longer than the
319
+ // wire cap will not be preserved by an older binary. That trade is
320
+ // deliberate — one un-bypassed category beats a dead notification panel.
321
+ if (trimmed.length > MAX_BYPASS_CATEGORY_CHARS) {
322
+ droppedLong += 1
323
+ continue
324
+ }
325
+ if (ALL_CATEGORIES.includes(trimmed)) {
326
+ knownSeen.add(trimmed)
327
+ continue
328
+ }
329
+ // Unknowns are the only unbounded input, so they are the only thing capped
330
+ // during iteration. A known category can never be lost this way.
331
+ if (unknownSeen.size >= MAX_BYPASS_CATEGORIES) {
332
+ droppedOverflow += 1
333
+ continue
334
+ }
335
+ unknownSeen.add(trimmed)
336
+ }
337
+ if (droppedLong > 0) {
338
+ log?.warn?.(`notification-prefs: dropped ${droppedLong} ${context} entr${droppedLong === 1 ? 'y' : 'ies'} longer than ${MAX_BYPASS_CATEGORY_CHARS} chars (unrepresentable on the wire)`)
272
339
  }
273
- return [...seen]
340
+ const list = [...knownSeen, ...unknownSeen]
341
+ if (list.length <= MAX_BYPASS_CATEGORIES && droppedOverflow === 0) return list
342
+ // CLAMP the length — but NOT positionally. A plain slice(0, N) drops whatever
343
+ // sits past the cap, which can be a REAL category: losing `permission` from the
344
+ // bypass list suppresses a blocking permission prompt during quiet hours and the
345
+ // agent stalls indefinitely (the #4544 rationale above). That is a worse failure
346
+ // than the unparseable snapshot this bound exists to prevent.
347
+ //
348
+ // So keep every RECOGNISED category first, then fill the remaining slots with
349
+ // unrecognised ones (preserving their relative order). This also serves the
350
+ // forward-compat intent better than a slice: the entries at risk of being
351
+ // dropped are now exactly the ones this binary cannot act on anyway.
352
+ const kept = list.slice(0, MAX_BYPASS_CATEGORIES)
353
+ const dropped = (list.length - kept.length) + droppedOverflow
354
+ log?.warn?.(`notification-prefs: ${context} exceeded ${MAX_BYPASS_CATEGORIES} entries; keeping ${kept.length} (recognised categories first, ${dropped} unrecognised dropped)`)
355
+ return kept
274
356
  }
275
357
 
276
358
  /**
@@ -289,7 +371,7 @@ export function loadPrefs(filePath = defaultNotificationPrefsPath(), { log } = {
289
371
  // coerced to defaults so the gate never misbehaves.
290
372
  let bypass = base.bypassCategories
291
373
  if (Object.prototype.hasOwnProperty.call(raw ?? {}, 'bypassCategories')) {
292
- const cleaned = sanitizeBypassList(raw.bypassCategories)
374
+ const cleaned = sanitizeBypassList(raw.bypassCategories, { log })
293
375
  bypass = cleaned ?? [...DEFAULT_BYPASS_CATEGORIES]
294
376
  }
295
377
  const cleanedQuietHours = sanitizeQuietHours(raw?.quietHours)
@@ -64,6 +64,7 @@ import {
64
64
  DEFAULT_OFFLINE_COLOR,
65
65
  isValidColor,
66
66
  escapeAndCap,
67
+ truncate,
67
68
  formatDuration,
68
69
  apiBase,
69
70
  fetchWithDiscordRetry,
@@ -148,6 +149,19 @@ const STATE_TITLES = {
148
149
  offline: (project) => `\u{1F534} ${project} — Session Offline`,
149
150
  }
150
151
 
152
+ /**
153
+ * Discord's hard embed-title limit (#7105).
154
+ *
155
+ * Past it the ENTIRE webhook POST/PATCH comes back 400, so the project's status
156
+ * embed silently stops updating — the failure is logged and invisible to the
157
+ * user. Every other field `_buildPayload` emits already goes through
158
+ * `escapeAndCap` for exactly this reason; the title did not, and it is the one
159
+ * that costs the whole embed rather than one field.
160
+ *
161
+ * https://discord.com/developers/docs/resources/message#embed-object-embed-limits
162
+ */
163
+ export const MAX_EMBED_TITLE_CHARS = 256
164
+
151
165
  export class DiscordWebhookSink extends NotificationSink {
152
166
  /**
153
167
  * @param {object} [opts]
@@ -637,6 +651,21 @@ export class DiscordWebhookSink extends NotificationSink {
637
651
 
638
652
  _buildPayload(project, entry) {
639
653
  const titleFor = STATE_TITLES[entry.state] || STATE_TITLES.idle
654
+ // #7105: `project` is only as bounded as whoever minted it — the ingest
655
+ // path derives it from a path basename, and `_projectKey` sanitizes its
656
+ // charset, not its length. Budget the PROJECT against this state's own
657
+ // decoration (emoji + separator + state text, measured from the template
658
+ // itself so a wordier state can't silently overflow) so the state suffix —
659
+ // the title's entire information content — survives the truncation instead
660
+ // of being cut off the end. The outer cap is the belt-and-braces guarantee
661
+ // that whatever a title template does, the embed stays Discord-legal.
662
+ //
663
+ // `truncate`, not `escapeAndCap`: Discord does not render markdown in embed
664
+ // TITLES (only in descriptions and field values), so escaping here would
665
+ // put a visible backslash in front of every `_` — a character `_projectKey`
666
+ // deliberately allows in a project name. Length is the only hazard here.
667
+ const projectBudget = MAX_EMBED_TITLE_CHARS - titleFor('').length
668
+ const title = truncate(titleFor(truncate(project, projectBudget)), MAX_EMBED_TITLE_CHARS)
640
669
  const fields = []
641
670
  // Free-text user/transcript fields (#5475): escape markdown so a body like
642
671
  // `watch dist/*_test.js` renders literally. escapeAndCap truncates first,
@@ -658,7 +687,7 @@ export class DiscordWebhookSink extends NotificationSink {
658
687
  return {
659
688
  username: this._botName,
660
689
  embeds: [{
661
- title: titleFor(project),
690
+ title,
662
691
  color: this._colorFor(project, entry.state),
663
692
  fields,
664
693
  footer: { text: `${this._botName} · ${formatDuration(elapsedSec)}` },
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Boot-time factory for the OrchestrationManager (epic #6691, E-4). Isolated so
3
+ * the daemon-boot wiring in server-cli.js is testable: it returns a fully-wired
4
+ * manager when the feature is on, null when it's off, and — critically — null
5
+ * (never a throw) when construction fails, so the orchestration feature can
6
+ * NEVER break daemon boot.
7
+ */
8
+
9
+ import { join } from 'node:path'
10
+ import { isOrchestrationEnabled } from '../config.js'
11
+ import { validateCwdAllowed } from '../handler-utils.js'
12
+ import { OrchestrationManager } from './orchestration-manager.js'
13
+ import { RunLedger } from './run-ledger.js'
14
+ import { TurnDriver } from './turn-driver.js'
15
+ import { createGitOps } from './git-ops.js'
16
+ import { OrchestrationPermissionGate } from './permission-gate.js'
17
+
18
+ export function buildOrchestrationManager({ sessionManager, config, chroxyDir, log = null } = {}) {
19
+ if (!isOrchestrationEnabled(config)) return null
20
+ try {
21
+ const ledger = new RunLedger({ baseDir: join(chroxyDir, 'orchestration') })
22
+ // Load prior runs from disk BEFORE anything writes: without this, the first
23
+ // post-restart createRun would rewrite runs-index.json from the empty
24
+ // in-memory map, clobbering the durable index. Pure load + journal replay —
25
+ // no run is auto-resumed (in-flight runs stay at their last persisted
26
+ // status; full restart-reconcile — suspend/interrupted marking, orphan
27
+ // worktree sweep — is tracked in #6743).
28
+ const recovered = ledger.recoverRuns()
29
+ if (recovered.length) log?.info?.(`Orchestration: recovered ${recovered.length} run record(s) from disk`)
30
+ const turnDriver = new TurnDriver({ sessionManager, log })
31
+ const manager = new OrchestrationManager({
32
+ sessionManager,
33
+ ledger,
34
+ turnDriver,
35
+ gitOps: createGitOps(),
36
+ config,
37
+ roles: config?.orchestration?.roles || null,
38
+ validateCwd: (cwd) => validateCwdAllowed(cwd, config),
39
+ permissionGateFactory: (opts) => new OrchestrationPermissionGate(opts),
40
+ log,
41
+ })
42
+ // The factory owns construction, so it owns teardown: extend dispose() to
43
+ // also stop the turn driver (SessionManager listeners) and flush the ledger.
44
+ const managerDispose = manager.dispose.bind(manager)
45
+ manager.dispose = () => {
46
+ managerDispose()
47
+ try { turnDriver.dispose() } catch { /* idempotent best-effort */ }
48
+ try { ledger.dispose() } catch { /* flushes pending snapshot writes */ }
49
+ }
50
+ log?.info?.('Orchestration engine enabled (features.orchestration)')
51
+ return manager
52
+ } catch (err) {
53
+ log?.warn?.(`Orchestration engine failed to initialize — feature disabled for this boot: ${err?.message || err}`)
54
+ return null
55
+ }
56
+ }