@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
@@ -201,6 +201,38 @@ export function parseGithubPrsUrl(remote) {
201
201
  return target ? `https://github.com/${target.owner}/${target.repo}/pulls` : null
202
202
  }
203
203
 
204
+ /**
205
+ * #6539 — resolve the EXACT active-repo set for repo-events scoping. For each
206
+ * distinct active-session cwd, read its `origin` remote (`git remote get-url
207
+ * origin`, failure-tolerant) and map it to `owner/repo` via
208
+ * {@link parseGithubOwnerRepo}. A cwd that isn't a git repo, has no origin, or
209
+ * has a non-GitHub remote resolves to null and is dropped — so a session without
210
+ * a recognizable GitHub remote is simply absent from the set (the dashboard
211
+ * degrades to "show all" for it rather than scoping it out). Deduped + sorted so
212
+ * the snapshot field is deterministic.
213
+ *
214
+ * @param {string[]} cwds - active-session working directories.
215
+ * @param {object} [opts]
216
+ * @param {Function} [opts.execFn] - promisified execFile seam (tests inject a stub).
217
+ * @param {number} [opts.concurrency]
218
+ * @returns {Promise<string[]>} sorted, deduped `owner/repo` full names.
219
+ */
220
+ export async function resolveActiveRepos(cwds, { execFn = execFileAsync, concurrency = 4 } = {}) {
221
+ const distinct = [...new Set((Array.isArray(cwds) ? cwds : []).filter((c) => typeof c === 'string' && c.length > 0))]
222
+ if (distinct.length === 0) return []
223
+ const tasks = distinct.map((cwd) => async () => {
224
+ const remote = await tryExec(execFn, 'git', ['remote', 'get-url', 'origin'], cwd)
225
+ const parsed = parseGithubOwnerRepo(remote)
226
+ // Lowercase: GitHub owner/repo are case-insensitive, but a manually-edited
227
+ // remote ('BlameChris/Chroxy') can differ in case from the canonical
228
+ // `full_name` the webhook stamps on `ev.repo` ('blamechris/chroxy'). Normalize
229
+ // so the dashboard's exact match doesn't erroneously hide events (#6539).
230
+ return parsed ? `${parsed.owner}/${parsed.repo}`.toLowerCase() : null
231
+ })
232
+ const names = await mapWithCap(tasks, concurrency)
233
+ return [...new Set(names.filter(Boolean))].sort()
234
+ }
235
+
204
236
  /**
205
237
  * Conclusions/states from a `gh` statusCheckRollup entry that count as a failed
206
238
  * check. `gh pr list --json statusCheckRollup` mixes two node shapes: CheckRun
@@ -48,6 +48,7 @@ import { randomBytes } from 'crypto'
48
48
  import { maskApiKey } from './byok-credentials.js'
49
49
  import * as realKeychain from './keychain.js'
50
50
  import { createLogger } from './logger.js'
51
+ import { fsyncForDurability, confirmRenameDurable } from './platform.js'
51
52
  import {
52
53
  CRED_KEY_SERVICE,
53
54
  isEncryptedEnvelope,
@@ -137,6 +138,21 @@ export function _setCredentialKeychainForTests(keychain) {
137
138
  _keychainOverride = keychain || null
138
139
  }
139
140
 
141
+ // #6964: the durable-write hook used by `writeStoreAtomically({ durable: true })`.
142
+ // Defaults to platform.js's `fsyncForDurability` (the same helper #6914 gave
143
+ // `writeFileRestricted`, including its benign-fsync-code handling). Injectable so
144
+ // the durable + durability-FAILURE branches are testable without provoking a real
145
+ // disk fault, and without mocking `fs` globally for the whole process.
146
+ let _durabilityFsync = fsyncForDurability
147
+
148
+ /**
149
+ * Test seam (#6964): inject the durability hook — `(target, { isDir }) => void` —
150
+ * or pass null to restore the real `fsyncForDurability`.
151
+ */
152
+ export function _setCredentialDurabilityForTests(fn) {
153
+ _durabilityFsync = fn || fsyncForDurability
154
+ }
155
+
140
156
  /**
141
157
  * The credential env vars the store manages, with display metadata. The order
142
158
  * here is the order the dashboard renders rows in.
@@ -370,8 +386,42 @@ export function replaceFileAtomically(tmp, target, deps = {}) {
370
386
  * plaintext. Preserves the temp-file → chmod 0600 → rename crash-safety and the
371
387
  * post-write mode re-check (POSIX). `dir` is assumed to already exist (callers
372
388
  * mkdir it). Shared by the set/delete/migrate paths.
389
+ *
390
+ * `durable` (default `false`, #6964) mirrors `writeFileRestricted({ durable: true })`
391
+ * from #6914: fsync the temp file BEFORE the rename, and on POSIX fsync the
392
+ * containing DIRECTORY AFTER it (a rename is not durable until its directory entry
393
+ * is) — the standard atomic-durable-write recipe. It stays OFF for the ordinary
394
+ * set/delete paths: an fsync per write would add blocking disk I/O for no security
395
+ * gain when the pre-write state is harmless. Acute credential ROTATION opts in, so
396
+ * an operator who is told a shared secret was rotated cannot lose that rotation to
397
+ * a power loss inside the OS writeback window. The benign "this filesystem cannot
398
+ * sync" codes are swallowed inside `fsyncForDurability`.
399
+ *
400
+ * The two fsync limbs fail DIFFERENTLY, and conflating them was its own false report:
401
+ *
402
+ * - PRE-RENAME (temp file): a genuine failure (EIO / ENOSPC) THROWS. Nothing was
403
+ * published — the live target still holds the prior value — so "the write failed"
404
+ * is exactly true, and the orphaned temp file is cleaned up by the `finally` below.
405
+ * - POST-RENAME (containing directory): the rename has ALREADY published the new
406
+ * value and its bytes are already fsynced; only the durability of the new
407
+ * directory ENTRY is unproven (a power loss could roll the rename back). Throwing
408
+ * here would report a failed write for a write that LANDED — the caller would
409
+ * keep the OLD value in its in-process cache while the NEW value is live on disk
410
+ * (split brain), and an operator told "rotation failed" would leave the old secret
411
+ * configured at the far end. So it does NOT throw: it logs at error level and is
412
+ * returned to the caller as `durabilityUnconfirmed`, a distinct outcome from a
413
+ * failed write. The caller must adopt the new value (it IS the live one) and
414
+ * surface the caveat.
415
+ *
416
+ * On Windows the directory fsync is skipped entirely (no such call;
417
+ * `replaceFileAtomically`'s rename already goes through MOVEFILE_WRITE_THROUGH).
418
+ *
419
+ * @returns {{ durabilityUnconfirmed: string | null }} `durabilityUnconfirmed` is the
420
+ * post-rename fsync error message when the value is live but its directory entry's
421
+ * durability could not be confirmed; `null` otherwise (including every non-durable
422
+ * write, which makes no durability claim at all).
373
423
  */
374
- function writeStoreAtomically(target, nextObj) {
424
+ function writeStoreAtomically(target, nextObj, { durable = false } = {}) {
375
425
  const key = getOrCreateMasterKey(activeKeychain())
376
426
  const payload = key ? encryptJson(nextObj, key) : nextObj
377
427
 
@@ -380,9 +430,14 @@ function writeStoreAtomically(target, nextObj) {
380
430
  // costs nothing here and matches the pattern in path-hash-trust-ledger.js.
381
431
  const tmp = `${target}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`
382
432
  let renamed = false
433
+ let durabilityUnconfirmed = null
383
434
  try {
384
435
  writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 })
385
436
  if (process.platform !== 'win32') chmodSync(tmp, 0o600)
437
+ // #6964: force the new bytes to disk BEFORE the rename makes them the live
438
+ // credentials, so a crash can never publish a half-written envelope nor roll
439
+ // a reported-successful rotation back.
440
+ if (durable) _durabilityFsync(tmp, { isDir: false })
386
441
  // #5243: atomic replace — never unlink the live target first.
387
442
  replaceFileAtomically(tmp, target)
388
443
  renamed = true
@@ -393,11 +448,21 @@ function writeStoreAtomically(target, nextObj) {
393
448
  throw new Error(`credentials file ended up with mode ${perms.toString(8)} after write; refused`)
394
449
  }
395
450
  }
451
+ // #6964: the rename is a directory-metadata change of its own — fsync the
452
+ // containing directory so the new entry survives a power loss too. POSIX only.
453
+ //
454
+ // POST-RENAME: the new value is already live and its bytes are already
455
+ // fsynced, so a failure here is NOT a failed write — it is reported as a
456
+ // distinct outcome rather than thrown, keeping the caller's cache in step
457
+ // with disk while still surfacing the error. That verdict is #7054's shared
458
+ // implementation; only the injected seam is local.
459
+ ;({ durabilityUnconfirmed } = _confirmDirDurability(target, durable))
396
460
  } finally {
397
461
  if (!renamed && existsSync(tmp)) {
398
462
  try { unlinkSync(tmp) } catch { /* */ }
399
463
  }
400
464
  }
465
+ return { durabilityUnconfirmed }
401
466
  }
402
467
 
403
468
  /**
@@ -498,6 +563,151 @@ export function readStoredField(field) {
498
563
  return { value, fileExists, error: null, keychainUnavailable: false }
499
564
  }
500
565
 
566
+ /**
567
+ * #6540 — persist an arbitrary NON-`KNOWN_CREDENTIALS` string field into the
568
+ * same encrypted-at-rest store (mode 0600, OS-keychain-backed cipher when
569
+ * available), the write counterpart to `readStoredField`. Used for secrets that
570
+ * live in the credentials file but are not provider env-var keys injected into a
571
+ * spawned child — e.g. the GitHub webhook HMAC secret (`githubWebhookSecret`).
572
+ *
573
+ * Trims whitespace, refuses an empty value, and (optionally) validates via the
574
+ * caller-supplied `validate(value) -> string|null` rule. Merges into the existing
575
+ * store (a read error aborts rather than clobbering sibling fields) and writes
576
+ * atomically. The raw value is NEVER logged.
577
+ *
578
+ * `durable: true` (#6964) makes the write power-loss durable (fsync of the temp
579
+ * file before the rename + of the containing directory after it). Acute ROTATION of
580
+ * a shared secret opts in — the operator is told the rotation succeeded, so it must
581
+ * not be recoverable to the old value by a crash. Ordinary sets leave it off (no
582
+ * fsync in the hot path).
583
+ *
584
+ * Durability failures split by limb (see `writeStoreAtomically`): a PRE-rename fsync
585
+ * failure THROWS (nothing was published, the prior value stands), while a POST-rename
586
+ * DIRECTORY fsync failure does NOT — the new value is already live, so it is returned
587
+ * as `durabilityUnconfirmed` and the caller must adopt the new value and surface the
588
+ * caveat rather than report a failed write.
589
+ *
590
+ * @param {string} field - the JSON field name (e.g. 'githubWebhookSecret')
591
+ * @param {string} rawValue
592
+ * @param {{ validate?: (v: string) => (string|null), durable?: boolean }} [opts]
593
+ * @returns {{ durabilityUnconfirmed: string | null }} the write outcome — see
594
+ * `writeStoreAtomically`. `durabilityUnconfirmed` is non-null only for a
595
+ * `durable: true` write whose value LANDED but whose directory entry could not be
596
+ * fsynced; the value is in effect either way.
597
+ * @throws {Error} on empty field/value, validation failure, a read/write error, or a
598
+ * PRE-rename fsync failure (in which case nothing was written)
599
+ */
600
+ export function setStoredField(field, rawValue, { validate, durable = false } = {}) {
601
+ if (typeof field !== 'string' || field.length === 0) throw new Error('field is required')
602
+ const value = typeof rawValue === 'string' ? rawValue.trim() : ''
603
+ if (value.length === 0) throw new Error(`${field} is required (non-empty string)`)
604
+ if (typeof validate === 'function') {
605
+ const validationError = validate(value)
606
+ if (validationError) throw new Error(validationError)
607
+ }
608
+
609
+ const target = credentialsFilePath()
610
+ const dir = dirname(target)
611
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
612
+ if (process.platform !== 'win32') {
613
+ try { chmodSync(dir, 0o700) } catch { /* best-effort */ }
614
+ }
615
+
616
+ // Merge with the existing store so we don't clobber sibling keys. A read
617
+ // error (bad mode / corrupt) aborts the write with a clear message rather than
618
+ // overwriting unknown content.
619
+ const { data, error } = readStore()
620
+ if (error) throw new Error(error)
621
+ return writeStoreAtomically(target, { ...data, [field]: value }, { durable })
622
+ }
623
+
624
+ /**
625
+ * #7056 — confirm that a REMOVAL (or a no-op standing in for one) is durable.
626
+ *
627
+ * A file's bytes and its directory entry are separate durability concerns: an
628
+ * `unlink` changes only the entry, so there is no file to fsync — the containing
629
+ * directory is the only thing that can confirm it. Never throws: by the time this
630
+ * runs the live filesystem already reflects the removal, so a failure means the
631
+ * effect is real but its crash-durability is unproven, which is reported rather
632
+ * than raised (throwing would send the operator to re-clear an already-cleared
633
+ * value — and that retry would itself no-op).
634
+ *
635
+ * Windows has no directory-fsync primitive reachable from Node (`FlushFileBuffers`
636
+ * on a directory needs FILE_FLAG_BACKUP_SEMANTICS, which `fs.openSync` cannot
637
+ * request), so the confirmation is skipped there — matching #6964's posture.
638
+ *
639
+ * @returns {{ durabilityUnconfirmed: string | null }}
640
+ */
641
+ function _confirmDirDurability(target, durable) {
642
+ // #7054: the VERDICT (report, never throw) is now the shared implementation in
643
+ // platform.js — this policy drifted across three copies, and #7067 was the bug
644
+ // that drift produced. Only the injected SEAM stays local: credential-store's
645
+ // hook replaces `fsyncForDurability` wholesale so its tests can assert ORDERING
646
+ // (target, isDir, and whether the file still existed at fsync time), which a
647
+ // raw fd-level hook cannot express.
648
+ return confirmRenameDurable(target, {
649
+ durable,
650
+ fsync: (t, opts) => _durabilityFsync(t, opts),
651
+ })
652
+ }
653
+
654
+ /**
655
+ * #6540 — remove an arbitrary NON-`KNOWN_CREDENTIALS` field written by
656
+ * `setStoredField`. No-op when the field (or the whole file) is absent. Deletes
657
+ * the file entirely when it would be left empty. Mirrors `deleteStoredCredential`
658
+ * for the non-provider-key case.
659
+ *
660
+ * #7056 — `durable` opts the CLEAR path into the same durability guarantee
661
+ * `setStoredField` got in #6964. Clearing a shared secret is as acute as rotating
662
+ * it: an operator clears precisely because they believe the value leaked, so a
663
+ * clear that is acked but not on disk can resurrect the leaked secret on the next
664
+ * start after a power loss.
665
+ *
666
+ * The two limbs need different fsyncs:
667
+ * - REWRITE (siblings survive) — the ordinary atomic temp-file + rename, so it
668
+ * delegates to `writeStoreAtomically({ durable })` unchanged.
669
+ * - UNLINK (the field was the last key) — there is no new file to fsync. The
670
+ * removal lives entirely in the containing DIRECTORY's entry, so only that
671
+ * directory is fsynced, and only AFTER the unlink. As with a post-rename
672
+ * failure, a failed fsync here is NOT a failed clear: the secret is already
673
+ * gone from the live filesystem, so it is reported as `durabilityUnconfirmed`
674
+ * rather than thrown (throwing would send the operator to re-clear a secret
675
+ * that is already cleared).
676
+ *
677
+ * @param {string} field
678
+ * @param {{ durable?: boolean }} [opts]
679
+ * @returns {{ durabilityUnconfirmed: string | null }}
680
+ */
681
+ export function deleteStoredField(field, { durable = false } = {}) {
682
+ if (typeof field !== 'string' || field.length === 0) throw new Error('field is required')
683
+ const target = credentialsFilePath()
684
+ const { data, fileExists, error } = readStore()
685
+ // #7056: `error` MUST be checked before `fileExists`. readStore() reports a
686
+ // non-ENOENT stat failure (EACCES/EIO/ELOOP) as `{ fileExists: false, error }`,
687
+ // so testing `fileExists` first turned an unreadable credentials file into a
688
+ // silent no-op SUCCESS — the caller acked a clear that cleared nothing while
689
+ // the secret was still on disk. ENOENT keeps `error: null`, so a genuinely
690
+ // absent file still takes the no-op path below.
691
+ if (error) throw new Error(error)
692
+ // A durable no-op still confirms: the retry after an unconfirmed clear lands
693
+ // on exactly these two branches (an unlinked file -> !fileExists, a rewritten
694
+ // one -> !(field in data)), and in both the outstanding doubt is the
695
+ // containing DIRECTORY's entry. Acking for free here would convert
696
+ // "unconfirmed" into false comfort.
697
+ if (!fileExists) return _confirmDirDurability(target, durable)
698
+ if (!(field in data)) return _confirmDirDurability(target, durable)
699
+
700
+ const next = { ...data }
701
+ delete next[field]
702
+
703
+ if (Object.keys(next).length === 0) {
704
+ try { unlinkSync(target) } catch (err) { if (err.code !== 'ENOENT') throw err }
705
+ return _confirmDirDurability(target, durable)
706
+ }
707
+
708
+ return writeStoreAtomically(target, next, { durable })
709
+ }
710
+
501
711
  /**
502
712
  * Resolution order: process.env > store > unset.
503
713
  *
@@ -561,23 +771,59 @@ export function setStoredCredential(key, rawValue) {
561
771
  }
562
772
 
563
773
  /**
564
- * Remove a single credential from the store. No-op when absent. Rewrites the
565
- * file atomically with the remaining keys (and removes the legacy alias too).
566
- * Deletes the file entirely when it would be left empty.
774
+ * Remove a single credential from the store. No-op when the file or the key is
775
+ * genuinely absent. Rewrites the file atomically with the remaining keys (and
776
+ * removes the legacy alias too). Deletes the file entirely when it would be
777
+ * left empty.
778
+ *
779
+ * Throws rather than returning quietly when the store cannot be READ (#7056) —
780
+ * an unreadable file is not an absent one, and acking a deletion that could not
781
+ * be performed would leave the credential on disk while the caller believes it
782
+ * is gone. Callers surface this as a clear/delete failure.
783
+ *
784
+ * #7062 — `durable` opts this path into the same guarantee `deleteStoredField`
785
+ * got in #7056, and for the same reason: an operator deletes a provider API key
786
+ * precisely because they believe it leaked, so a delete that is acked but still
787
+ * sitting in the OS writeback window can restore the leaked key on the next
788
+ * start after a power loss.
789
+ *
790
+ * The two limbs need different fsyncs:
791
+ * - REWRITE (siblings survive) — the ordinary atomic temp-file + rename, so it
792
+ * delegates to `writeStoreAtomically({ durable })` unchanged.
793
+ * - UNLINK (this was the last key) — there is no new file to fsync. The removal
794
+ * lives entirely in the containing DIRECTORY's entry, so only that directory
795
+ * is fsynced, and only AFTER the unlink. A failed fsync here is NOT a failed
796
+ * delete: the key is already gone from the live filesystem, so it is reported
797
+ * as `durabilityUnconfirmed` rather than thrown (throwing would send the
798
+ * operator to re-delete a key that is already deleted).
567
799
  *
568
800
  * @param {string} key
801
+ * @param {{ durable?: boolean }} [opts]
802
+ * @returns {{ durabilityUnconfirmed: string | null }}
803
+ * @throws {Error} when the credentials file exists but cannot be read
569
804
  */
570
- export function deleteStoredCredential(key) {
805
+ export function deleteStoredCredential(key, { durable = false } = {}) {
571
806
  if (!isKnownCredentialKey(key)) throw new Error(`Unknown credential key: ${key}`)
572
807
  const target = credentialsFilePath()
573
808
  const { data, fileExists, error } = readStore()
574
- if (!fileExists) return
575
809
  // A bad-mode/JSON file can't be safely rewritten without risking clobber of
576
- // unknown content; surface the error rather than guess.
810
+ // unknown content; surface the error rather than guess. #7056: this MUST come
811
+ // before the `fileExists` test — readStore() reports a non-ENOENT stat failure
812
+ // (EACCES/EIO/ELOOP) as { fileExists: false, error }, so checking `fileExists`
813
+ // first turned an unreadable store into a silent no-op SUCCESS while the
814
+ // credential was still on disk. ENOENT keeps `error: null`, so a genuinely
815
+ // absent file still no-ops below.
577
816
  if (error) throw new Error(error)
817
+ // A durable no-op still confirms. The retry after an unconfirmed delete lands
818
+ // on exactly these two branches (an unlinked file -> !fileExists, a rewritten
819
+ // one -> the key already absent), and in both the outstanding doubt is the
820
+ // containing DIRECTORY's entry. Acking for free here would convert
821
+ // "unconfirmed" into false comfort.
822
+ if (!fileExists) return _confirmDirDurability(target, durable)
578
823
 
579
824
  const legacyField = LEGACY_FIELD_BY_KEY[key]
580
- if (!(key in data) && !(legacyField && legacyField in data)) return // nothing to remove
825
+ // nothing to remove
826
+ if (!(key in data) && !(legacyField && legacyField in data)) return _confirmDirDurability(target, durable)
581
827
 
582
828
  const next = { ...data }
583
829
  delete next[key]
@@ -586,10 +832,10 @@ export function deleteStoredCredential(key) {
586
832
  // If the store is now empty, remove the file entirely.
587
833
  if (Object.keys(next).length === 0) {
588
834
  try { unlinkSync(target) } catch (err) { if (err.code !== 'ENOENT') throw err }
589
- return
835
+ return _confirmDirDurability(target, durable)
590
836
  }
591
837
 
592
- writeStoreAtomically(target, next)
838
+ return writeStoreAtomically(target, next, { durable })
593
839
  }
594
840
 
595
841
  /**
@@ -0,0 +1 @@
1
+ {"version":"4.0.18","results":[[":src/components/Sidebar.test.tsx",{"duration":289.79666599999996,"failed":false}],[":src/components/SessionBar.test.tsx",{"duration":229.947,"failed":false}],[":src/components/InputBar.test.tsx",{"duration":806.5306249999999,"failed":false}],[":src/store/store.test.ts",{"duration":191.3694999999999,"failed":false}],[":src/components/ChatView.test.tsx",{"duration":90.92337500000008,"failed":false}],[":src/utils/image-utils.test.ts",{"duration":67.891209,"failed":false}],[":src/lib/markdown.test.ts",{"duration":33.488249999999994,"failed":false}],[":src/components/FilePicker.test.tsx",{"duration":656.5540419999999,"failed":false}],[":src/components/CommandPalette.test.tsx",{"duration":505.46120800000006,"failed":false}],[":src/components/Modal.test.tsx",{"duration":261.76254200000005,"failed":false}],[":src/hooks/useGlobalShortcuts.test.ts",{"duration":19.508625000000052,"failed":false}],[":src/components/MultiTerminalView.test.tsx",{"duration":66.95945800000004,"failed":false}],[":src/theme/theme.test.ts",{"duration":87.53537500000004,"failed":false}],[":src/components/PermissionPrompt.test.tsx",{"duration":78.22554100000002,"failed":false}],[":src/components/TerminalView.test.tsx",{"duration":29.097499999999968,"failed":false}],[":src/components/QuestionPrompt.test.tsx",{"duration":256.2959169999999,"failed":false}],[":src/components/ChatMessage.test.tsx",{"duration":99.87383299999999,"failed":false}],[":src/components/ConversationSearch.test.tsx",{"duration":51.832958000000076,"failed":false}],[":src/hooks/useTauriEvents.test.ts",{"duration":54.16720799999996,"failed":false}],[":src/components/CreateSessionPanel.test.tsx",{"duration":251.86516699999993,"failed":false}],[":src/lib/syntax.test.ts",{"duration":4.716042000000016,"failed":false}],[":src/components/ToolBubble.test.tsx",{"duration":270.952,"failed":false}],[":src/components/WelcomeScreen.test.tsx",{"duration":38.4052079999999,"failed":false}],[":src/components/SlashCommandPicker.test.tsx",{"duration":247.68491599999993,"failed":false}],[":src/store/commands.test.ts",{"duration":11.501875000000041,"failed":false}],[":src/App.test.tsx",{"duration":555.5264999999999,"failed":false}],[":src/components/LoadingScreen.test.tsx",{"duration":197.46125000000006,"failed":false}],[":src/components/ErrorScreen.test.tsx",{"duration":174.52308300000004,"failed":false}],[":src/components/AttachmentChip.test.tsx",{"duration":133.119416,"failed":false}],[":src/components/ImageThumbnail.test.tsx",{"duration":225.656292,"failed":false}],[":src/utils/attachment-utils.test.ts",{"duration":1.9936669999999594,"failed":false}],[":src/components/SessionLoadingSkeleton.test.tsx",{"duration":20.297208999999953,"failed":false}],[":src/components/CreateSessionModal.test.tsx",{"duration":1.2709169999999403,"failed":false}],[":src/hooks/useGlobalShortcuts-integration.test.ts",{"duration":3.6664590000000317,"failed":false}],[":src/components/SidebarKeyboard.test.tsx",{"duration":263.6836659999999,"failed":false}],[":src/components/ConversationSearchKeyboard.test.tsx",{"duration":284.583625,"failed":false}],[":src/components/CommandPaletteMru.test.tsx",{"duration":223.312458,"failed":false}],[":src/components/CreateSessionModalCombobox.test.tsx",{"duration":283.13045899999986,"failed":false}],[":src/components/CreateSessionModalA11y.test.tsx",{"duration":283.1391249999999,"failed":false}],[":src/components/CreateSessionModalPaths.test.tsx",{"duration":1.161916999999903,"failed":false}],[":src/components/FocusIndicators.test.tsx",{"duration":4.090167000000065,"failed":false}],[":src/components/CreateSessionModalSubmit.test.tsx",{"duration":265.530583,"failed":false}],[":src/components/FooterBar.test.tsx",{"duration":53.23287499999992,"failed":false}],[":src/components/SidebarResize.test.tsx",{"duration":28.179208000000017,"failed":false}],[":src/hooks/useGlobalShortcuts-comprehensive.test.ts",{"duration":2.034582999999998,"failed":false}],[":src/components/InputBarBusy.test.tsx",{"duration":1.4036250000000337,"failed":false}],[":src/components/ProviderPicker.test.tsx",{"duration":5.629709000000048,"failed":false}],[":src/hooks/TauriIPC.test.ts",{"duration":2.5598340000000235,"failed":false}],[":src/components/QrModal.test.tsx",{"duration":297.325292,"failed":false}],[":src/hooks/usePathAutocomplete.test.ts",{"duration":20.195791999999983,"failed":false}],[":src/theme/theme-engine.test.ts",{"duration":14.554124999999999,"failed":false}],[":src/components/SettingsPanel.test.tsx",{"duration":267.083834,"failed":false}],[":src/components/ShortcutHelp.test.tsx",{"duration":145.37741699999992,"failed":false}],[":src/hooks/usePermissionNotification.test.ts",{"duration":19.722958999999946,"failed":false}],[":src/components/NotificationBanners.test.tsx",{"duration":287.66600000000005,"failed":false}],[":src/components/DirectoryBrowser.test.tsx",{"duration":358.52987499999995,"failed":false}],[":src/store/permission-expired-dismiss.test.ts",{"duration":3.085124999999948,"failed":false}],[":src/components/DirectoryBrowserGuard.test.tsx",{"duration":1.0922500000000355,"failed":false}],[":src/components/CreateSessionModalBrowse.test.tsx",{"duration":277.1455000000001,"failed":false}],[":src/components/DirectoryBrowserPathNormalize.test.tsx",{"duration":1.4816250000000082,"failed":false}],[":src/components/CreateSessionModalNativePicker.test.tsx",{"duration":1.3864579999999478,"failed":false}],[":src/hooks/TauriPickDirectory.test.ts",{"duration":1.115083000000027,"failed":false}],[":src/components/SplitPane.test.tsx",{"duration":208.34645799999998,"failed":false}],[":src/components/FileBrowserPanel.test.tsx",{"duration":118.79291699999999,"failed":false}],[":src/components/CheckpointTimeline.test.tsx",{"duration":72.18912499999999,"failed":false}],[":src/components/DiffViewerPanel.test.tsx",{"duration":98.47979099999998,"failed":false}],[":src/components/AgentMonitorPanel.test.tsx",{"duration":25.710958000000005,"failed":false}],[":src/store/server-registry.test.ts",{"duration":4.949459000000047,"failed":false}],[":src/store/server-registry-store.test.ts",{"duration":27.445875,"failed":false}],[":src/components/ServerPicker.test.tsx",{"duration":101.76858299999992,"failed":false}],[":src/store/server-auth-persistence.test.ts",{"duration":2.8949170000000777,"failed":false}],[":src/components/SidebarDotAnimation.test.ts",{"duration":2.169167000000016,"failed":false}],[":src/components/ProviderBillingCSS.test.ts",{"duration":1.3143340000000308,"failed":false}],[":src/components/ProviderBilling.test.tsx",{"duration":85.27125000000001,"failed":false}],[":src/store/token-crypto.test.ts",{"duration":3.602583999999979,"failed":false}],[":src/store/persistence-scoped.test.ts",{"duration":4.493417000000022,"failed":false}],[":src/components/ReconnectBanner.test.tsx",{"duration":26.06458299999997,"failed":false}],[":src/components/Toast.test.tsx",{"duration":171.62745900000004,"failed":false}],[":src/components/StatusBar.test.tsx",{"duration":109.21304199999997,"failed":false}],[":src/components/css-audit.test.ts",{"duration":3.858416000000034,"failed":false}],[":src/components/CheckpointTimeline.edge.test.tsx",{"duration":55.475415999999996,"failed":false}],[":src/components/ConsolePage.test.tsx",{"duration":133.438584,"failed":false}],[":src/components/LogPanel.test.tsx",{"duration":69.34970899999996,"failed":false}],[":src/utils/tauri.test.ts",{"duration":1.0379580000000033,"failed":false}],[":src/components/StartupErrorScreen.test.tsx",{"duration":154.33329199999991,"failed":false}],[":src/components/HeaderOverflow.test.tsx",{"duration":1.751792000000023,"failed":false}],[":src/components/ChatSettingsDropdown.test.tsx",{"duration":99.36116700000002,"failed":false}],[":src/theme/ChatSettingsPanelOverflow.test.tsx",{"duration":1.1831250000000182,"failed":false}]]}
@@ -101,6 +101,9 @@ function collectRateLimiters(server) {
101
101
  // The HTTP-permission limiter lives inside the permission handler
102
102
  // closure and is re-exported on the handler object for this purpose.
103
103
  server?._permissions?._httpPermissionLimiter,
104
+ // #7004 — the /permission-floor probe's own (much larger) limiter, same
105
+ // closure-re-export pattern.
106
+ server?._permissions?._httpFloorLimiter,
104
107
  ]
105
108
  for (const limiter of candidates) {
106
109
  if (limiter && typeof limiter.getEvictionStats === 'function') {
@@ -32,7 +32,22 @@ const log = createLogger('docker-sdk')
32
32
  */
33
33
  export class DockerSdkSession extends SdkSession {
34
34
  static get capabilities() {
35
- return { ...SdkSession.capabilities, containerized: true }
35
+ // #6767: the transcript for a containerized session lives inside the
36
+ // container, so the host-side conversation fork can't reach it — restore
37
+ // degrades to files-only here (mirrors the instance-level
38
+ // `supportsConversationFork` getter below). Advertise conversationFork:false
39
+ // so the checkpoint UI disables the "Conversation" restore-mode option.
40
+ return { ...SdkSession.capabilities, containerized: true, conversationFork: false }
41
+ }
42
+
43
+ /**
44
+ * #6766: the SDK transcript for a containerized session lives inside the
45
+ * container (`~/.claude/projects` in the container's filesystem), not on the
46
+ * host where the standalone `forkSession` reads. So a host-side conversation
47
+ * fork can't reach it — restore degrades to a files-only rewind here.
48
+ */
49
+ get supportsConversationFork() {
50
+ return false
36
51
  }
37
52
 
38
53
  /**
@@ -3,6 +3,7 @@ import { createInterface } from 'readline'
3
3
  import { CliSession } from './cli-session.js'
4
4
  import { createLogger } from './logger.js'
5
5
  import { BILLING_CLASSES } from './billing-class.js'
6
+ import { getChroxyHostEnv } from './chroxy-host-metadata.js'
6
7
 
7
8
  const log = createLogger('docker-session')
8
9
 
@@ -284,6 +285,14 @@ export class DockerSession extends CliSession {
284
285
  if (env.CHROXY_HOST) {
285
286
  dockerArgs.push('--env', `CHROXY_HOST=${env.CHROXY_HOST}`)
286
287
  }
288
+ // #6633: forward Chroxy's own (non-sensitive) host identity so an agent
289
+ // INSIDE the container can still answer "what build am I in?". Sourced from
290
+ // the authoritative computed block; the `CHROXY_HOST_` prefix (trailing
291
+ // underscore) is distinct from the permission-hook `CHROXY_HOST` routing var
292
+ // above.
293
+ for (const [key, val] of Object.entries(getChroxyHostEnv())) {
294
+ dockerArgs.push('--env', `${key}=${val}`)
295
+ }
287
296
 
288
297
  dockerArgs.push(this._containerId, 'claude', ...claudeArgs)
289
298
 
package/src/doctor.js CHANGED
@@ -2,11 +2,13 @@ import { execFileSync } from 'child_process'
2
2
  import { existsSync, readFileSync } from 'fs'
3
3
  import { dirname, isAbsolute, join, resolve } from 'path'
4
4
  import { fileURLToPath } from 'url'
5
- import { homedir, platform } from 'os'
5
+ import { homedir } from 'os'
6
6
  import { createServer } from 'net'
7
7
  import { validateConfig } from './config.js'
8
8
  import { resolveBinary } from './utils/resolve-binary.js'
9
+ import { verifyBinary as defaultVerifyBinary, BINARY_STATUS, describeBinaryHealth } from './utils/verify-binary.js'
9
10
  import { prepareSpawn } from './utils/win-spawn.js'
11
+ import { cloudflaredInstallHint } from './platform.js'
10
12
  import { getProvider, DEFAULT_PROVIDER } from './providers.js'
11
13
  import { registerAnthropicCompatibleProviders } from './anthropic-compatible-session.js'
12
14
  import { registerOpenAiCompatibleProviders } from './openai-compatible-session.js'
@@ -292,8 +294,6 @@ export async function checkTunnelRoutability(deps = {}) {
292
294
  */
293
295
  export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgDir = SERVER_PKG_DIR, now = Date.now(), tunnelProbe } = {}) {
294
296
  const checks = []
295
- const isMac = platform() === 'darwin'
296
- const isLinux = platform() === 'linux'
297
297
 
298
298
  // 1. Node.js version
299
299
  const nodeVersion = process.versions.node
@@ -315,9 +315,7 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
315
315
  '/usr/local/bin/cloudflared',
316
316
  join(homedir(), '.local/bin/cloudflared'),
317
317
  ],
318
- installHint: isMac ? 'brew install cloudflared'
319
- : isLinux ? 'see https://pkg.cloudflare.com/ for installation'
320
- : 'see https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/',
318
+ installHint: cloudflaredInstallHint(),
321
319
  }))
322
320
 
323
321
  // 3. Load config (once) — used for both the Config check and provider resolution.
@@ -367,7 +365,7 @@ export async function runDoctorChecks({ port, providers, verbose: _verbose, pkgD
367
365
  }
368
366
  }
369
367
  } else {
370
- configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'npx chroxy init' to create` }
368
+ configCheck = { name: 'Config', status: 'warn', message: `Not found — run 'chroxy init' to create` }
371
369
  }
372
370
 
373
371
  // 4. Provider-specific checks. Each configured provider contributes its
@@ -602,8 +600,21 @@ function checkProvider(providerName) {
602
600
  *
603
601
  * Exported for tests — callers in production should use `runDoctorChecks`.
604
602
  */
605
- export function checkBinary(name, args, { parseVersion, required, installHint, candidates = [], minVersion = null }) {
603
+ export function checkBinary(name, args, { parseVersion, required, installHint, candidates = [], minVersion = null, verify = defaultVerifyBinary }) {
606
604
  const resolved = resolveBinary(name, candidates)
605
+ // #6708 — integrity gate BEFORE we try to exec for a version. A macOS
606
+ // Gatekeeper-quarantined binary keeps its X bit, and a present-but-non-
607
+ // executable binary throws EACCES in the version probe — in both cases the
608
+ // catch below would mislabel it "Not found — install …". Detect them up front
609
+ // so doctor reports "quarantined/blocked" and "not executable" distinctly from
610
+ // "not installed", each with its own fix-it hint. The quarantine step is a
611
+ // no-op off darwin; NOT_FOUND still falls through to the version probe (whose
612
+ // catch owns the install message).
613
+ const health = verify(resolved)
614
+ if (health.status === BINARY_STATUS.QUARANTINED || health.status === BINARY_STATUS.NOT_EXECUTABLE) {
615
+ const { message } = describeBinaryHealth(health, { binary: name, installHint })
616
+ return { name, status: required ? 'fail' : 'warn', message }
617
+ }
607
618
  try {
608
619
  // #6484 — a resolved `.cmd` shim (npm-only Windows host) can't be spawned
609
620
  // directly on Node 24; route it through cmd.exe via prepareSpawn. No-op for
@@ -1,6 +1,7 @@
1
1
  import { execFile, spawn } from 'child_process'
2
2
  import { createLogger } from '../../logger.js'
3
3
  import { VALID_USERNAME_RE } from '../../utils/validation-patterns.js'
4
+ import { getChroxyHostEnv } from '../../chroxy-host-metadata.js'
4
5
 
5
6
  const log = createLogger('docker-backend')
6
7
 
@@ -515,6 +516,13 @@ export class DockerBackend {
515
516
  }
516
517
  }
517
518
  }
519
+ // #6633: also forward Chroxy's own (non-sensitive) host identity so an agent
520
+ // INSIDE the container can answer "what build am I in?". Sourced from the
521
+ // authoritative computed block (not `env`), so it lands regardless of how the
522
+ // caller built its env.
523
+ for (const [key, val] of Object.entries(getChroxyHostEnv())) {
524
+ dockerArgs.push('--env', `${key}=${val}`)
525
+ }
518
526
 
519
527
  // Override HOME and PATH for the container user.
520
528
  dockerArgs.push('--env', `HOME=/home/${containerUser}`)
@@ -4,6 +4,7 @@ import { PassThrough } from 'stream'
4
4
  import { KubeConfig, CoreV1Api, PortForward } from '@kubernetes/client-node'
5
5
  import WebSocket from 'ws'
6
6
  import { createLogger } from '../../logger.js'
7
+ import { getChroxyHostEnv } from '../../chroxy-host-metadata.js'
7
8
 
8
9
  const log = createLogger('k8s-backend')
9
10
 
@@ -1230,6 +1231,14 @@ export class K8sBackend {
1230
1231
  }
1231
1232
  }
1232
1233
 
1234
+ // #6633: Chroxy's own (non-sensitive) host identity, so an agent exec'd into
1235
+ // the pod can answer "what build am I in?" — pod-spec env is inherited by
1236
+ // `kubectl exec` processes. Added after containerEnv so the computed identity
1237
+ // is authoritative.
1238
+ for (const [name, value] of Object.entries(getChroxyHostEnv())) {
1239
+ env.push({ name, value: String(value) })
1240
+ }
1241
+
1233
1242
  // 4. Resolve imagePullPolicy: per-call opt > constructor opt > omit (K8s default)
1234
1243
  const imagePullPolicy = callImagePullPolicy || this._imagePullPolicy
1235
1244
 
@@ -36,6 +36,10 @@ import { createLogger } from './logger.js'
36
36
  import { RateLimiter, getRateLimitKey } from './rate-limiter.js'
37
37
  import { SubagentCounter } from './subagent-counter.js'
38
38
  import { TurnTracker } from './turn-tracker.js'
39
+ // The cap the external-session registry already enforces on `project` (#7104).
40
+ // Shared so the clamp at the derivation site below and the registry's own
41
+ // defence-in-depth clamp stay one number, not two that can drift.
42
+ import { MAX_EXTERNAL_PROJECT_CHARS } from './external-session-registry.js'
39
43
  import { IngestEventSchema } from '@chroxy/protocol'
40
44
  // deriveProjectFromCwd + the chroxy-worktree helpers moved to the shared,
41
45
  // Zod-free @chroxy/protocol/project subpath (audit P2-2, #5850) so the hook
@@ -442,8 +446,22 @@ export function handleEventIngest(server, req, res) {
442
446
  if (event.type === 'notification' && data.notificationType === 'idle_prompt') {
443
447
  mapping = INGEST_IDLE_PROMPT_MAPPING
444
448
  }
445
- const project = event.project
449
+ // #7105: bound the derived project HERE, at the single site that mints
450
+ // it, rather than per-consumer. An explicit `event.project` is already
451
+ // wire-capped at 256 by IngestEventSchema, but the derived branch is a
452
+ // path BASENAME off a `cwd` capped at 4096 — so the same field arrives ~16x
453
+ // over its own inbound contract, and the path need not exist on disk, so
454
+ // NAME_MAX does not bound it either. Four consumers read this value
455
+ // (SubagentCounter, TurnTracker, recordExternalSessionEvent, and
456
+ // pushManager.send → the Discord embed title); #7104 clamped exactly one,
457
+ // from the inside. Clamping at the derivation site bounds all four and
458
+ // leaves the registry's own clamp as defence-in-depth for callers that
459
+ // bypass ingest validation.
460
+ const derivedProject = event.project
446
461
  || (typeof data.cwd === 'string' ? deriveProjectFromCwd(data.cwd) : null)
462
+ const project = typeof derivedProject === 'string' && derivedProject.length > MAX_EXTERNAL_PROJECT_CHARS
463
+ ? derivedProject.slice(0, MAX_EXTERNAL_PROJECT_CHARS)
464
+ : derivedProject
447
465
 
448
466
  // Server-side subagent counting (#5413 Phase 4): fold subagent_start/
449
467
  // subagent_stop into the per-(source, sessionId) aggregate (session_end