@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
@@ -18,6 +18,7 @@ import { realpathSync, existsSync } from 'fs'
18
18
  import { USER_SHELL_PROVIDER } from '@chroxy/protocol'
19
19
  import { BaseSession, buildBaseSessionOpts } from './base-session.js'
20
20
  import { createLogger } from './logger.js'
21
+ import { isWindows, defaultShell, killProcessTree } from './platform.js'
21
22
  import { CHROXY_SECRET_DENYLIST } from './utils/spawn-env.js'
22
23
 
23
24
  const log = createLogger('user-shell-session')
@@ -28,20 +29,48 @@ const DEFAULT_COLS = 120
28
29
  const DEFAULT_ROWS = 30
29
30
  // Coalesce PTY bytes into one terminal_output per tick (bounds broadcast churn).
30
31
  const MIRROR_FLUSH_MS = 50
31
- // SIGTERM → grace → SIGKILL the process group on destroy.
32
+ // POSIX destroy() escalation window: SIGTERM → grace → SIGKILL the process
33
+ // group. Windows has no grace — destroy() reaps the whole tree at once via
34
+ // taskkill (#6646), so this constant is POSIX-only.
32
35
  const DESTROY_GRACE_MS = 3000
33
36
 
37
+ // Windows PowerShell 5.1 ships in-box at this fixed System32 path on every
38
+ // Windows install (the `v1.0` dir name is a historical constant, not the PS
39
+ // version). Preferred over cmd.exe for a real interactive terminal.
40
+ const WIN_POWERSHELL_RELATIVE = 'System32\\WindowsPowerShell\\v1.0\\powershell.exe'
41
+
34
42
  /**
35
- * Resolve the shell to spawn: `$SHELL` if it exists, then common fallbacks.
36
- * Returns the first path that exists; if none do (a truly unusual host), falls
37
- * back to `/bin/sh` as a last resort — start() then surfaces a clean spawn error
38
- * if that path is also missing.
43
+ * Resolve the interactive shell to spawn.
44
+ *
45
+ * POSIX: `$SHELL` if it exists, then `/bin/zsh|bash|sh`, then `/bin/sh` as a
46
+ * last resort (start() surfaces a clean spawn error if even that is missing).
47
+ *
48
+ * Windows (#6646): the POSIX candidates never exist, so the old code returned
49
+ * `/bin/sh` and node-pty's spawn always failed — the embedded shell never
50
+ * launched. Prefer a real interactive shell instead: an explicit `$SHELL` that
51
+ * exists wins (lets a user pin e.g. `pwsh.exe`), then Windows PowerShell 5.1 at
52
+ * its fixed System32 path, then `defaultShell()` (COMSPEC/cmd.exe).
53
+ *
54
+ * `platform`/`env`/`exists` are injectable so both platform branches are
55
+ * unit-testable on any CI host — the Windows path can't rely on a Windows
56
+ * runner being present. Production callers pass no args.
39
57
  */
40
- function resolveShell() {
41
- const shell = process.env.SHELL
42
- if (typeof shell === 'string' && shell && existsSync(shell)) return shell
58
+ export function resolveShell({
59
+ platform = process.platform,
60
+ env = process.env,
61
+ exists = existsSync,
62
+ } = {}) {
63
+ const shell = env.SHELL
64
+ if (platform === 'win32') {
65
+ if (typeof shell === 'string' && shell && exists(shell)) return shell
66
+ const systemRoot = env.SystemRoot || env.windir || 'C:\\Windows'
67
+ const winPowerShell = `${systemRoot}\\${WIN_POWERSHELL_RELATIVE}`
68
+ if (exists(winPowerShell)) return winPowerShell
69
+ return defaultShell({ platform, env })
70
+ }
71
+ if (typeof shell === 'string' && shell && exists(shell)) return shell
43
72
  for (const cand of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
44
- if (existsSync(cand)) return cand
73
+ if (exists(cand)) return cand
45
74
  }
46
75
  return '/bin/sh'
47
76
  }
@@ -99,6 +128,9 @@ export class UserShellSession extends BaseSession {
99
128
  this._mirrorTimer = null
100
129
  this._terminalMirrorActive = false
101
130
  this._killTimer = null
131
+ // Windows tree-reaper for destroy() (taskkill /T /F). Injectable so a test
132
+ // can assert the Windows branch without spawning a real taskkill (#6646).
133
+ this._killProcessTree = killProcessTree
102
134
  }
103
135
 
104
136
  /**
@@ -168,9 +200,11 @@ export class UserShellSession extends BaseSession {
168
200
  }
169
201
 
170
202
  // destroy() can race the spawn (it set _destroying while we awaited the
171
- // import): kill the fresh PTY so it isn't orphaned, then bail.
203
+ // import): reap the fresh PTY so it isn't orphaned, then bail. Uses the same
204
+ // Windows tree-kill as destroy() (#6646) — a shell rc/profile can spawn a
205
+ // child immediately, so a direct kill on Windows would orphan it here too.
172
206
  if (this._destroying) {
173
- try { this._term.kill('SIGTERM') } catch { /* already gone */ }
207
+ this._reapTerm(this._term)
174
208
  this._term = null
175
209
  return
176
210
  }
@@ -351,10 +385,19 @@ export class UserShellSession extends BaseSession {
351
385
  }
352
386
 
353
387
  /**
354
- * Kill the PTY (no respawn) and clear all timers. SIGTERM, then after a grace
355
- * window SIGKILL the whole process group so backgrounded jobs die too. The
356
- * liveness probe + _ptyExited latch narrow escalation to a genuinely-hung
357
- * shell (never a recycled pid).
388
+ * Kill the PTY (no respawn) and clear all timers.
389
+ *
390
+ * POSIX: SIGTERM, then after a grace window SIGKILL the whole process GROUP so
391
+ * backgrounded jobs die too. The liveness probe + `_ptyExited` latch narrow
392
+ * escalation to a genuinely-hung shell (never a recycled pid).
393
+ *
394
+ * Windows (#6646): there is no graceful SIGTERM (node-pty maps `kill()` to
395
+ * `TerminateProcess` on the direct pid) and no process groups, so a direct
396
+ * kill would orphan the shell's children — acute here because a shell often
397
+ * launches `.cmd`/`.bat` wrappers whose real process is a grandchild. Reap the
398
+ * whole descendant tree at once with `taskkill /PID <pid> /T /F` (via
399
+ * killProcessTree); no grace window, since the shell can't run a SIGTERM
400
+ * handler on Windows anyway.
358
401
  */
359
402
  destroy() {
360
403
  // Idempotent: a second destroy() (or a destroy racing the exit path) is a
@@ -370,27 +413,32 @@ export class UserShellSession extends BaseSession {
370
413
  }
371
414
  this._mirrorBuffer = ''
372
415
 
416
+ const onWindows = this._isWindowsOverride ?? isWindows
373
417
  const term = this._term
374
418
  const pid = term?.pid
375
419
  if (term && !this._ptyExited) {
376
- try { term.kill('SIGTERM') } catch { /* already gone */ }
377
- if (Number.isInteger(pid) && pid > 0) {
378
- this._killTimer = setTimeout(() => {
379
- this._killTimer = null
380
- if (this._ptyExited) return
381
- try { process.kill(pid, 0) } catch { return /* already exited */ }
382
- log.warn(`user-shell PTY (pid=${pid}) did not exit ${DESTROY_GRACE_MS}ms after SIGTERM — escalating to SIGKILL`)
383
- let killed = false
384
- if (process.platform !== 'win32') {
385
- try { process.kill(-pid, 'SIGKILL'); killed = true } catch { /* group gone */ }
386
- }
387
- if (!killed) {
388
- try { term.kill('SIGKILL') } catch {
389
- try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }
420
+ if (onWindows) {
421
+ this._killProcessTree(term, { force: true })
422
+ } else {
423
+ try { term.kill('SIGTERM') } catch { /* already gone */ }
424
+ if (Number.isInteger(pid) && pid > 0) {
425
+ this._killTimer = setTimeout(() => {
426
+ this._killTimer = null
427
+ if (this._ptyExited) return
428
+ try { process.kill(pid, 0) } catch { return /* already exited */ }
429
+ log.warn(`user-shell PTY (pid=${pid}) did not exit ${DESTROY_GRACE_MS}ms after SIGTERM — escalating to SIGKILL`)
430
+ // SIGKILL the whole process group so backgrounded jobs die too; fall
431
+ // back to the direct pid if the group is already gone.
432
+ try {
433
+ process.kill(-pid, 'SIGKILL')
434
+ } catch {
435
+ try { term.kill('SIGKILL') } catch {
436
+ try { process.kill(pid, 'SIGKILL') } catch { /* already gone */ }
437
+ }
390
438
  }
391
- }
392
- }, DESTROY_GRACE_MS)
393
- if (typeof this._killTimer.unref === 'function') this._killTimer.unref()
439
+ }, DESTROY_GRACE_MS)
440
+ if (typeof this._killTimer.unref === 'function') this._killTimer.unref()
441
+ }
394
442
  }
395
443
  }
396
444
  this._term = null
@@ -408,4 +456,22 @@ export class UserShellSession extends BaseSession {
408
456
  this._killTimer = null
409
457
  }
410
458
  }
459
+
460
+ /**
461
+ * One-shot teardown of a term with no grace window — used by the start()
462
+ * destroy-race path where the shell was just spawned. POSIX: a direct SIGTERM
463
+ * (nothing is running in the fresh shell to gracefully save). Windows (#6646):
464
+ * the whole descendant tree via taskkill /T /F (a shell rc/profile may already
465
+ * have spawned a child, and node-pty's kill() would orphan it). destroy()'s
466
+ * own kill path stays separate because it adds the POSIX grace-escalation.
467
+ */
468
+ _reapTerm(term) {
469
+ if (!term) return
470
+ const onWindows = this._isWindowsOverride ?? isWindows
471
+ if (onWindows) {
472
+ this._killProcessTree(term, { force: true })
473
+ } else {
474
+ try { term.kill('SIGTERM') } catch { /* already gone */ }
475
+ }
476
+ }
411
477
  }
@@ -0,0 +1,205 @@
1
+ import { lstatSync, readlinkSync } from 'node:fs'
2
+ import { lstat, readlink } from 'node:fs/promises'
3
+ import { dirname, isAbsolute, join, parse } from 'node:path'
4
+
5
+ /**
6
+ * open(2)-faithful, component-by-component path resolver — the SINGLE SOURCE for
7
+ * both security floors that need it:
8
+ * - the SYNCHRONOUS protected-path floor (`permission-manager.js`, #6921), which
9
+ * runs inside the sync `handlePermission` hot-path and cannot await; and
10
+ * - the ASYNC BYOK file-ops confinement (`ws-file-ops/common.js`, #6923), which
11
+ * walks a raw tool-supplied path before a subprocess write.
12
+ *
13
+ * Both were introduced as near-identical twins (a sync copy and an async copy) and
14
+ * PROMPTLY DRIFTED: #6928 was a bug present in BOTH — a `target.split(path.sep)`
15
+ * that, on Windows, left a forward-slash path as ONE component and fell back to a
16
+ * lexical `join()`, reopening the exact `..`-after-symlink escape the walk exists to
17
+ * close. It had to be patched in two places. This module exists so the drift-prone
18
+ * logic — the separator-agnostic split, the per-component lexical classification,
19
+ * and the symlink splice — lives ONCE; the sync and async entry points are thin fs
20
+ * drivers over that shared core, and `componentwise-resolver.test.js` pins them to
21
+ * IDENTICAL results across a battery of on-disk topologies so they cannot diverge
22
+ * again.
23
+ *
24
+ * ---------------------------------------------------------------------------------
25
+ * WHY A COMPONENT WALK (and not `realpath(resolve(base, target))`):
26
+ *
27
+ * BOTH `path.resolve()` AND Node's `fs.realpath` collapse `..` LEXICALLY — textually,
28
+ * before/instead of following symlinks. `realpath('link/..')` yields the symlink's
29
+ * LEXICAL parent; `open(2)` follows `link` to its TARGET and applies `..` from THERE.
30
+ * So `work/agent-x/../../settings.local.json` (with `work -> .claude/worktrees`)
31
+ * lexically cancels to a benign in-cwd `settings.local.json`, but a raw write really
32
+ * lands on `.claude/settings.local.json`. Only a walk that applies `..` AFTER
33
+ * resolving the symlinks so far — as the kernel does — sees the true destination.
34
+ * ---------------------------------------------------------------------------------
35
+ */
36
+
37
+ // #6921/#6923 — symlink-expansion cap, matching the kernel's typical MAXSYMLINKS.
38
+ // A chain deeper than this — or a cycle — THROWS `ELOOP`, which every caller's
39
+ // `catch` treats as protected / rejected (fail closed).
40
+ export const COMPONENTWISE_MAX_SYMLINKS = 40
41
+
42
+ /**
43
+ * #6928 — split a raw path into the components BELOW its parsed root, separating on
44
+ * BOTH `/` and `\` regardless of platform. Node accepts forward slashes on Windows,
45
+ * so a platform-`sep`-only split (`\` on Windows) would leave a forward-slash path
46
+ * as ONE component — the walk would then break and fall back to a lexical `join()`,
47
+ * reopening the exact `..`-after-symlink escape this resolver exists to close.
48
+ * `root` (already parsed by the caller, which starts `resolved` there) is sliced off
49
+ * first so a drive/UNC/`/` root is never walked as an ordinary component (a Windows
50
+ * `C:\` would otherwise appear as a `C:` component and `join` straight back onto the
51
+ * drive root).
52
+ * @param {string} p
53
+ * @param {string} root the already-`parse`d root of `p` (`''` for a relative path)
54
+ * @returns {string[]}
55
+ */
56
+ export function splitPathBelowRoot(p, root) {
57
+ return (root ? p.slice(root.length) : p).split(/[/\\]+/)
58
+ }
59
+
60
+ /**
61
+ * Pure: initialise the walk. An absolute target ignores the base (as `open`/`resolve`
62
+ * do) and starts at its parsed root so its own leading components are walked (and
63
+ * symlink-resolved) too; a relative target (empty root) starts at `realBase`. The
64
+ * root is stripped BEFORE splitting so it is never re-walked as an ordinary
65
+ * component (#6928).
66
+ * @param {string} realBase the session cwd, already resolved to its real path
67
+ * @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
68
+ * @returns {{ resolved: string, pending: string[] }}
69
+ */
70
+ function beginWalk(realBase, target) {
71
+ const targetRoot = isAbsolute(target) ? parse(target).root : ''
72
+ return { resolved: targetRoot || realBase, pending: splitPathBelowRoot(target, targetRoot) }
73
+ }
74
+
75
+ /**
76
+ * Pure: resolve a single component AS FAR AS POSSIBLE without touching the
77
+ * filesystem. This is the ordering that must never drift between the sync and async
78
+ * drivers, so it lives here exactly once:
79
+ * - `''` / `.` → skip (resolved unchanged, no stat).
80
+ * - `..` → pop to the PARENT of the resolved-so-far real path (`dirname`),
81
+ * i.e. apply `..` AFTER following symlinks so far — NOT lexically
82
+ * on the pre-resolution path. No stat.
83
+ * - tail-only → once a component was ENOENT, everything after it is a
84
+ * to-be-created tail: append by `join` with no stat.
85
+ * - otherwise → return the `candidate` to lstat; `resolved` is left UNCHANGED
86
+ * (it is committed only after the driver confirms `candidate` is
87
+ * not a symlink).
88
+ * @param {string} resolved resolved-so-far real path
89
+ * @param {string} comp the raw component
90
+ * @param {boolean} tailOnly true once a prior component was ENOENT
91
+ * @returns {{ resolved: string, stat: string|null }} `stat` is the path to lstat,
92
+ * or `null` when the component was fully consumed lexically (skip / `..` / tail).
93
+ */
94
+ function resolveComponentLexically(resolved, comp, tailOnly) {
95
+ if (comp === '' || comp === '.') return { resolved, stat: null }
96
+ if (comp === '..') return { resolved: dirname(resolved), stat: null }
97
+ const candidate = join(resolved, comp)
98
+ if (tailOnly) return { resolved: candidate, stat: null }
99
+ return { resolved, stat: candidate }
100
+ }
101
+
102
+ /**
103
+ * Pure: a symlink was found at the cursor. Splice the link's own components (below
104
+ * its root) into `pending` AT the cursor so they — and any `..` they contain — are
105
+ * walked next, before the tail. Returns the resolved base to continue from: an
106
+ * ABSOLUTE link restarts resolution from its parsed root; a RELATIVE link continues
107
+ * from the symlink's PARENT (`resolved`, since the symlink component itself was not
108
+ * appended). Mutates `pending`.
109
+ * @param {string[]} pending
110
+ * @param {number} i cursor (index of the NEXT component to walk)
111
+ * @param {string} resolved resolved-so-far real path (the symlink's parent)
112
+ * @param {string} link the raw `readlink` target
113
+ * @returns {string}
114
+ */
115
+ function spliceSymlink(pending, i, resolved, link) {
116
+ const linkRoot = isAbsolute(link) ? parse(link).root : ''
117
+ pending.splice(i, 0, ...splitPathBelowRoot(link, linkRoot))
118
+ return linkRoot || resolved
119
+ }
120
+
121
+ function symlinkBudgetError(fnName) {
122
+ return Object.assign(
123
+ new Error(`${fnName}: symlink depth exceeds ${COMPONENTWISE_MAX_SYMLINKS}`),
124
+ { code: 'ELOOP' },
125
+ )
126
+ }
127
+
128
+ /**
129
+ * #6921 — SYNC open(2)-faithful resolver (protected-path floor hot-path). A thin
130
+ * `lstatSync`/`readlinkSync` driver over the shared core above. A non-ENOENT
131
+ * `lstat`/`readlink` error (EACCES, ELOOP) PROPAGATES so the caller's `catch` fails
132
+ * closed; ENOENT stops filesystem resolution (nothing deeper can be a symlink) and
133
+ * the remaining tail — INCLUDING any `..` — is applied against the resolved-so-far
134
+ * REAL path by the same pop/append rules.
135
+ * @param {string} realBase the session cwd, already resolved to its real path
136
+ * @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
137
+ * @returns {string} the open(2)-faithful resolved absolute real path
138
+ */
139
+ export function resolveTargetComponentwiseSync(realBase, target) {
140
+ const { resolved: base, pending } = beginWalk(realBase, target)
141
+ let resolved = base
142
+ let symlinks = 0
143
+ let tailOnly = false
144
+ let i = 0
145
+ while (i < pending.length) {
146
+ const comp = pending[i]
147
+ i++
148
+ const step = resolveComponentLexically(resolved, comp, tailOnly)
149
+ resolved = step.resolved
150
+ if (step.stat === null) continue
151
+ let st
152
+ try {
153
+ st = lstatSync(step.stat)
154
+ } catch (err) {
155
+ if (err.code === 'ENOENT') { tailOnly = true; resolved = step.stat; continue }
156
+ throw err // EACCES etc. — fail closed via the caller's catch
157
+ }
158
+ if (st.isSymbolicLink()) {
159
+ if (++symlinks > COMPONENTWISE_MAX_SYMLINKS) throw symlinkBudgetError('resolveTargetComponentwiseSync')
160
+ resolved = spliceSymlink(pending, i, resolved, readlinkSync(step.stat))
161
+ } else {
162
+ resolved = step.stat
163
+ }
164
+ }
165
+ return resolved
166
+ }
167
+
168
+ /**
169
+ * #6923 — ASYNC open(2)-faithful resolver (BYOK file-ops confinement). The async
170
+ * sibling of {@link resolveTargetComponentwiseSync} over the SAME shared core, so
171
+ * the two cannot diverge (pinned by `componentwise-resolver.test.js`). Same
172
+ * fail-closed contract: EACCES/ELOOP propagate; ENOENT applies the remaining tail
173
+ * (including `..`) by pop/append.
174
+ * @param {string} realBase the session cwd, already resolved to its real path
175
+ * @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
176
+ * @returns {Promise<string>} the open(2)-faithful resolved absolute real path
177
+ */
178
+ export async function resolveTargetComponentwiseAsync(realBase, target) {
179
+ const { resolved: base, pending } = beginWalk(realBase, target)
180
+ let resolved = base
181
+ let symlinks = 0
182
+ let tailOnly = false
183
+ let i = 0
184
+ while (i < pending.length) {
185
+ const comp = pending[i]
186
+ i++
187
+ const step = resolveComponentLexically(resolved, comp, tailOnly)
188
+ resolved = step.resolved
189
+ if (step.stat === null) continue
190
+ let st
191
+ try {
192
+ st = await lstat(step.stat)
193
+ } catch (err) {
194
+ if (err.code === 'ENOENT') { tailOnly = true; resolved = step.stat; continue }
195
+ throw err // EACCES etc. — fail closed via the caller
196
+ }
197
+ if (st.isSymbolicLink()) {
198
+ if (++symlinks > COMPONENTWISE_MAX_SYMLINKS) throw symlinkBudgetError('resolveTargetComponentwiseAsync')
199
+ resolved = spliceSymlink(pending, i, resolved, await readlink(step.stat))
200
+ } else {
201
+ resolved = step.stat
202
+ }
203
+ }
204
+ return resolved
205
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Build an unambiguous Map key from several string parts (#7103).
3
+ *
4
+ * Two aggregates key their in-memory Maps on `(source, sessionId)`
5
+ * ({@link TurnTracker}, {@link ExternalSessionRegistry}). Both used to flatten
6
+ * the pair with a single separator, and both wrote that separator as a LITERAL
7
+ * NUL byte in the source file. That was wrong twice over:
8
+ *
9
+ * 1. **Search visibility.** A raw NUL makes the whole file invisible to any
10
+ * code search that passes grep's `-I` or otherwise sniffs for NUL — and
11
+ * it fails SILENTLY, returning an empty result indistinguishable from
12
+ * "the string isn't there". `scripts/lint-no-nul-bytes.sh` now guards it.
13
+ *
14
+ * 2. **Aliasing.** `a + SEP + b` is only injective while no part can contain
15
+ * SEP. That held for these two callers by accident — `IngestEventSchema`
16
+ * charset-restricts `source` to `[a-zA-Z0-9._-]` — but it is a
17
+ * CALLER-side invariant neither aggregate can enforce, and `sessionId` is
18
+ * NOT charset-restricted. Under a bare separator, `('a<SEP>b', 'c')` and
19
+ * `('a', 'b<SEP>c')` collapse onto one entry: one session's stop clears
20
+ * another's turn, and one `session_end` evicts the wrong registry row.
21
+ *
22
+ * The encoding is length-prefixed — `<len>:<part>` per part, joined with `|`:
23
+ *
24
+ * compositeKey('claude-hooks', 'abc') -> '12:claude-hooks|3:abc'
25
+ *
26
+ * Decoding is deterministic (read the digit run, take exactly that many chars,
27
+ * expect `|` or end-of-string), so the encoding is injective for ANY part
28
+ * contents — including parts that contain `:`, `|`, digits, or a NUL. The
29
+ * delimiters are plain ASCII, so the key is also readable in a log line or a
30
+ * debugger, which a control-character separator never was.
31
+ *
32
+ * Keys are in-memory only and never persisted or sent on the wire, so the
33
+ * format is free to change; nothing decodes it today.
34
+ *
35
+ * @param {...unknown} parts - Key components, coerced to string.
36
+ * @returns {string} Collision-free key for the ordered part list.
37
+ */
38
+ export function compositeKey(...parts) {
39
+ return parts
40
+ .map((part) => {
41
+ const s = String(part)
42
+ return `${s.length}:${s}`
43
+ })
44
+ .join('|')
45
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * #7081 — epoch-ms → wire-legal ISO 8601, or null.
3
+ *
4
+ * Several outbound fields are `z.string().datetime()` in @chroxy/protocol
5
+ * (`skills.ts` `lastUsed`, control-room `RepoMemoryCache.lastModified`, …) and are
6
+ * produced by `new Date(ms).toISOString()` from a number read off disk. Those
7
+ * loaders guarded the number for TYPE (finite, positive) while the schema
8
+ * constrains RANGE, which leaves a band where `toISOString()` succeeds but emits
9
+ * something the wire rejects:
10
+ *
11
+ * 253402300799999 -> '9999-12-31T23:59:59.999Z' accepted
12
+ * 253402300800000 -> '+010000-01-01T00:00:00.000Z' REJECTED by .datetime()
13
+ * 8640000000000000 -> '+275760-09-13T00:00:00.000Z' REJECTED by .datetime()
14
+ * 8640000000000001 -> RangeError
15
+ *
16
+ * ES2015+ requires the expanded-year form (`±YYYYYY`) once the year leaves
17
+ * [0, 9999], and `z.string().datetime()` only accepts a 4-digit year. So the
18
+ * usable ceiling is the last instant of year 9999 — NOT `Date`'s ±8.64e15 limit,
19
+ * which is the bound `scheduled-task-store.js` uses for a different purpose
20
+ * (representable-as-a-Date, not representable-on-the-wire). Do not conflate them.
21
+ *
22
+ * Returns `null` rather than clamping. Every consuming field is `.nullable()`, and
23
+ * a clamped timestamp is a LIE rendered to the operator: "last used in the year
24
+ * 9999" is not more truthful than "never recorded", it is just harder to notice.
25
+ */
26
+
27
+ /** Last epoch-ms whose ISO form keeps a 4-digit year (`9999-12-31T23:59:59.999Z`). */
28
+ export const MAX_WIRE_DATETIME_MS = 253402300799999
29
+
30
+ /**
31
+ * Convert an epoch-ms value to an ISO string the wire can carry.
32
+ *
33
+ * @param {unknown} ms - candidate epoch-ms; anything non-numeric yields null
34
+ * @param {{ allowEpoch?: boolean }} [opts] - `allowEpoch` permits 0 (the Unix
35
+ * epoch). Off by default because the existing callers treat 0 as "never
36
+ * recorded" rather than as 1970-01-01.
37
+ * @returns {string|null} an ISO 8601 string with a 4-digit year, or null
38
+ */
39
+ export function isoFromEpochMs(ms, { allowEpoch = false } = {}) {
40
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return null
41
+ if (allowEpoch ? ms < 0 : ms <= 0) return null
42
+ if (ms > MAX_WIRE_DATETIME_MS) return null
43
+ // Defensive: a fractional value is legal here (Date accepts it and truncates),
44
+ // so this cannot throw after the range check above — but a future caller
45
+ // passing something exotic should degrade to null rather than crash a snapshot.
46
+ try {
47
+ return new Date(ms).toISOString()
48
+ } catch {
49
+ return null
50
+ }
51
+ }