@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
package/src/statusline.js CHANGED
@@ -1,21 +1,23 @@
1
1
  /**
2
- * statusLine — read the user's Claude Code `statusLine` command from their own
3
- * settings.json, execute it the way Claude Code does, and surface its stdout.
2
+ * statusLine — read the user's Claude Code `statusLine` command from their
3
+ * user-level settings, execute it the way Claude Code does, and surface its stdout.
4
4
  *
5
5
  * Feature #6791. A user who has configured a `statusLine` script (git branch,
6
6
  * model, a cost tracker, …) sees none of it in Chroxy today; this module reads
7
7
  * the effective config and runs it so its output can be broadcast to clients.
8
8
  *
9
- * ── Trust + security model (this EXECUTES a shell command) ────────────────────
10
- * The command is ONLY ever the one in the user's OWN settings.json — the same
11
- * trust boundary Claude Code itself honours when it runs the script. There is
12
- * NO client-supplied command and NO client-supplied path: the settings files
9
+ * ── Which command runs (this EXECUTES a shell command) ───────────────────────
10
+ * The command is ONLY ever the one in the user's own user-level settings. There
11
+ * is NO client-supplied command and NO client-supplied path: the settings files
13
12
  * are read from fixed, server-chosen locations only
14
- * - <sessionCwd>/.claude/settings.json (project — highest precedence)
15
13
  * - ~/.claude/project-settings.json (user project-settings)
16
14
  * - ~/.claude/settings.json (user — lowest precedence)
17
- * (mirrors Claude Code's precedence — see docs.claude.com "statusline").
18
- * `sessionCwd` comes from the server's session record, never from the wire.
15
+ * (`CLAUDE_CONFIG_DIR` replaces `~/.claude`). The session's working directory
16
+ * is consulted for `<sessionCwd>/.claude/settings.json` only when the folder is
17
+ * trusted AND that file's bytes are exactly the ones in the trust record
18
+ * (`readTrustedProjectSettings`, folder-trust.js): read once, verified, parsed and
19
+ * executed from the same buffer, never cached. `sessionCwd` comes from the
20
+ * server's session record, never from the wire.
19
21
  *
20
22
  * Robustness hardening, none of which Claude Code documents but all of which a
21
23
  * long-lived daemon needs so a slow/hostile script can't wedge it:
@@ -31,6 +33,7 @@
31
33
  import { spawn } from 'node:child_process'
32
34
  import { readFile } from 'node:fs/promises'
33
35
  import { claudeConfigDir } from './utils/claude-config-dir.js'
36
+ import { readTrustedProjectSettings } from './folder-trust.js'
34
37
  import { join } from 'node:path'
35
38
  import { EventEmitter } from 'node:events'
36
39
  import { createLogger } from './logger.js'
@@ -62,9 +65,11 @@ export const STATUSLINE_CONFIG_CACHE_TTL_MS = 5_000
62
65
  * @param {string} claudeDir - claude's user-level config dir (`CLAUDE_CONFIG_DIR`, else `~/.claude`)
63
66
  * @returns {string[]} absolute settings.json paths, highest precedence first
64
67
  */
65
- export function statusLineSettingsPaths(cwd, claudeDir) {
68
+ export function statusLineSettingsPaths(_cwd, claudeDir) {
69
+ // The session folder's own file is not in this list: it goes through
70
+ // `readTrustedProjectSettings`, which reads it once and checks it against the
71
+ // owner's trust record before anything in it can run.
66
72
  const paths = []
67
- if (cwd) paths.push(join(cwd, '.claude', 'settings.json'))
68
73
  if (claudeDir) {
69
74
  paths.push(join(claudeDir, 'project-settings.json'))
70
75
  paths.push(join(claudeDir, 'settings.json'))
@@ -363,6 +368,7 @@ export class StatusLineManager extends EventEmitter {
363
368
  minRefreshIntervalMs = STATUSLINE_MIN_REFRESH_INTERVAL_MS,
364
369
  defaultRefreshIntervalMs = STATUSLINE_DEFAULT_REFRESH_INTERVAL_MS,
365
370
  configCacheTtlMs = STATUSLINE_CONFIG_CACHE_TTL_MS,
371
+ readProjectSettingsFn = readTrustedProjectSettings,
366
372
  } = {}) {
367
373
  super()
368
374
  // The user-level dir follows CLAUDE_CONFIG_DIR (#8974). `claudeDir` pins it;
@@ -370,6 +376,7 @@ export class StatusLineManager extends EventEmitter {
370
376
  // resolveConfig() call resolves `claudeConfigDir()` from the daemon's process.env.
371
377
  this._claudeDir = claudeDir ?? (homeDir ? join(homeDir, '.claude') : null)
372
378
  this._readFileFn = readFileFn
379
+ this._readProjectSettingsFn = readProjectSettingsFn
373
380
  this._spawnFn = spawnFn
374
381
  this._buildEnv = buildEnv
375
382
  this._now = now
@@ -383,7 +390,7 @@ export class StatusLineManager extends EventEmitter {
383
390
 
384
391
  /** @type {Map<string, {config: object|null, expiresAt: number}>} keyed by cwd */
385
392
  this._configCache = new Map()
386
- /** @type {Map<string, {getContext: Function, timer: any, lastRunAt: number, running: boolean, lastText: string|null}>} */
393
+ /** @type {Map<string, {getContext: Function, timer: any, lastRunAt: number, running: boolean, lastText: string|null, fromProject: boolean, epoch: number}>} */
387
394
  this._sessions = new Map()
388
395
  this._stopped = false
389
396
  }
@@ -398,8 +405,18 @@ export class StatusLineManager extends EventEmitter {
398
405
  * @returns {Promise<{command:string, refreshIntervalMs:number|null}|null>}
399
406
  */
400
407
  async resolveConfig(cwd) {
408
+ return (await this._resolve(cwd)).config
409
+ }
410
+
411
+ /** `resolveConfig`, also saying whether the config came from the trusted folder's own file. */
412
+ async _resolve(cwd) {
413
+ // The folder's own file first, and never from the cache: it is verified against
414
+ // the trust record on every call, so a trust change or an edit takes effect at once.
415
+ const projectConfig = this._projectConfig(cwd)
416
+ if (projectConfig) return { config: projectConfig, fromProject: true }
417
+
401
418
  const cached = this._configCache.get(cwd)
402
- if (cached && cached.expiresAt > this._now()) return cached.config
419
+ if (cached && cached.expiresAt > this._now()) return { config: cached.config, fromProject: false }
403
420
 
404
421
  let config = null
405
422
  for (const path of statusLineSettingsPaths(cwd, this._claudeDir ?? claudeConfigDir())) {
@@ -423,7 +440,18 @@ export class StatusLineManager extends EventEmitter {
423
440
  }
424
441
 
425
442
  this._configCache.set(cwd, { config, expiresAt: this._now() + this._configCacheTtlMs })
426
- return config
443
+ return { config, fromProject: false }
444
+ }
445
+
446
+ /** The verified project statusLine config, or null. Never throws. */
447
+ _projectConfig(cwd) {
448
+ try {
449
+ const raw = this._readProjectSettingsFn(cwd)
450
+ if (raw === null || raw === undefined) return null
451
+ return parseStatusLineConfig(JSON.parse(raw))
452
+ } catch {
453
+ return null
454
+ }
427
455
  }
428
456
 
429
457
  /** Drop any cached config (e.g. session ended) so a re-read is forced. */
@@ -440,8 +468,8 @@ export class StatusLineManager extends EventEmitter {
440
468
  * @returns {Promise<{active:boolean, text:string, result:object|null}>}
441
469
  */
442
470
  async run(ctx) {
443
- const config = await this.resolveConfig(ctx?.cwd)
444
- if (!config) return { active: false, text: '', result: null }
471
+ const { config, fromProject } = await this._resolve(ctx?.cwd)
472
+ if (!config) return { active: false, text: '', result: null, fromProject: false }
445
473
 
446
474
  let env
447
475
  try {
@@ -462,7 +490,7 @@ export class StatusLineManager extends EventEmitter {
462
490
  setTimer: this._setTimer,
463
491
  clearTimer: this._clearTimer,
464
492
  })
465
- return { active: true, text: statusLineDisplayText(result), result }
493
+ return { active: true, text: statusLineDisplayText(result), result, fromProject }
466
494
  }
467
495
 
468
496
  /**
@@ -482,7 +510,7 @@ export class StatusLineManager extends EventEmitter {
482
510
  if (!session) {
483
511
  // Refresh for a session we aren't tracking a loop for is still valid
484
512
  // (event-driven trigger before startSession); create a lightweight record.
485
- session = { getContext: null, timer: null, lastRunAt: 0, running: false, lastText: null }
513
+ session = { getContext: null, timer: null, lastRunAt: 0, running: false, lastText: null, fromProject: false, epoch: 0 }
486
514
  this._sessions.set(sessionId, session)
487
515
  }
488
516
  if (session.running) return null
@@ -492,6 +520,7 @@ export class StatusLineManager extends EventEmitter {
492
520
 
493
521
  session.running = true
494
522
  session.lastRunAt = this._now()
523
+ const epoch = session.epoch
495
524
  let outcome
496
525
  try {
497
526
  outcome = await this.run(ctx)
@@ -507,7 +536,12 @@ export class StatusLineManager extends EventEmitter {
507
536
  const still = this._sessions.get(sessionId)
508
537
  if (!still) return outcome ? { ...outcome, emitted: false } : null
509
538
 
539
+ // A run that began before the folder stopped being trusted must not bring the
540
+ // folder's own output back (see clearProjectOutput).
541
+ if (still.epoch !== epoch && outcome.fromProject) return { ...outcome, emitted: false }
542
+
510
543
  let emitted = false
544
+ still.fromProject = outcome.active && outcome.fromProject === true
511
545
  if (outcome.active) {
512
546
  if (outcome.text !== still.lastText) {
513
547
  still.lastText = outcome.text
@@ -530,6 +564,31 @@ export class StatusLineManager extends EventEmitter {
530
564
  return { active: outcome.active, text: outcome.text, emitted }
531
565
  }
532
566
 
567
+ /**
568
+ * The session's folder stopped being trusted (the owner stopped trusting it, or an edit
569
+ * revoked it). If the status line last shown came from the folder's own settings,
570
+ * clear it now with one empty `output`, instead of leaving that text up until the next
571
+ * refresh, then refresh at once so a user-level status line, if any, takes its place.
572
+ * Output from the user's own settings is left alone.
573
+ * @param {string} sessionId
574
+ * @returns {boolean} true when a cleared output was emitted
575
+ */
576
+ clearProjectOutput(sessionId) {
577
+ const session = this._sessions.get(sessionId)
578
+ if (!session || this._stopped) return false
579
+ session.epoch += 1 // a run already in flight began while the folder was trusted
580
+ if (!session.fromProject) return false
581
+ session.fromProject = false
582
+ const hadText = session.lastText !== null
583
+ session.lastText = null
584
+ if (hadText) this.emit('output', { sessionId, active: false, text: '', truncated: false, timedOut: false, exitCode: null })
585
+ try {
586
+ const ctx = session.getContext ? session.getContext() : null
587
+ if (ctx) this.refresh(sessionId, ctx, { force: true }).catch(() => {})
588
+ } catch { /* the periodic tick will refresh */ }
589
+ return hadText
590
+ }
591
+
533
592
  /**
534
593
  * Begin tracking a session: store its context provider and start the periodic
535
594
  * refresh loop (a self-rescheduling, unref'd timer — never setInterval, so an
@@ -543,7 +602,7 @@ export class StatusLineManager extends EventEmitter {
543
602
  if (this._stopped) return
544
603
  let session = this._sessions.get(sessionId)
545
604
  if (!session) {
546
- session = { getContext, timer: null, lastRunAt: 0, running: false, lastText: null }
605
+ session = { getContext, timer: null, lastRunAt: 0, running: false, lastText: null, fromProject: false, epoch: 0 }
547
606
  this._sessions.set(sessionId, session)
548
607
  } else {
549
608
  session.getContext = getContext
@@ -228,6 +228,8 @@ export async function defaultRunOneShot({ prompt, model, cwd, signal, queryFn =
228
228
  permissionMode: 'bypassPermissions',
229
229
  allowDangerouslySkipPermissions: true,
230
230
  includePartialMessages: false,
231
+ // A one-shot summary needs no settings files.
232
+ settingSources: [],
231
233
  maxTurns: 1,
232
234
  // #7986 / #8030: the desktop bundle does not ship the Agent SDK's platform
233
235
  // binary, and query() throws if pathToClaudeCodeExecutable is unset and
@@ -13,8 +13,11 @@
13
13
  * provider `stopReason` / `stop_reason` strings this module maps FROM (ACP,
14
14
  * Anthropic, and BYOK's own `result.stopReason`).
15
15
  *
16
- * This module is the ONE place those signals are mapped onto the four-value
17
- * vocabulary that rides the `result` wire frame (`turnOutcome`):
16
+ * This module is the ONE place those signals are mapped onto the four provider-derived
17
+ * values of the vocabulary that rides the `result` wire frame (`turnOutcome`). The full
18
+ * vocabulary is @chroxy/protocol's TURN_OUTCOMES; `interrupted` (#8259) and
19
+ * `stopped_before_output` (#9241) are written by the daemon's own turn bookkeeping, not
20
+ * mapped from a provider signal here:
18
21
  *
19
22
  * completed — the model finished on its own.
20
23
  * truncated — the turn was cut short by a limit (tokens, turns, budget, context).
@@ -259,6 +259,11 @@ export const AUDITED_SINKS = [
259
259
  },
260
260
 
261
261
  // ── claude-tui-session.js ──
262
+ {
263
+ file: 'claude-tui-session.js',
264
+ match: 'claudeSettingSourcesValueFor(projectAllowed)',
265
+ reason: "the value is claudeSettingSourcesValueFor() from claude-setting-sources.js: one of two fixed server-side strings ('user' or 'user,project', chosen by the folder-trust decision for the session's own cwd), built from no client input.",
266
+ },
262
267
  {
263
268
  file: 'claude-tui-session.js',
264
269
  // The full call text is 200+ chars, so this is the exact 200-char PREFIX
@@ -296,6 +301,11 @@ export const AUDITED_SINKS = [
296
301
  match: "spawn(spawnSpec.command, spawnSpec.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'], env: this._buildChildEnv(), ...spawnSpec.options, })",
297
302
  reason: '_spawnPersistentProcess(args) has one caller (start()), which passes args = buildClaudeCliArgs({...}) — audited below, at buildClaudeCliArgs itself.',
298
303
  },
304
+ {
305
+ file: 'cli-session.js',
306
+ match: 'claudeSettingSourcesValueFor(allowed)',
307
+ reason: "the value is claudeSettingSourcesValueFor() from claude-setting-sources.js: one of two fixed server-side strings ('user' or 'user,project', chosen by the folder-trust decision for the session's own cwd), built from no client input.",
308
+ },
299
309
  {
300
310
  file: 'cli-session.js',
301
311
  match: 'model',
@@ -677,6 +687,16 @@ export const AUDITED_SINKS = [
677
687
  },
678
688
 
679
689
  // ── web-task-manager.js ──
690
+ {
691
+ file: 'web-task-manager.js',
692
+ match: 'claudeSettingSourcesValueFor(projectAllowed === true)',
693
+ reason: "the value is claudeSettingSourcesValueFor() from claude-setting-sources.js: one of two fixed server-side strings ('user' or 'user,project', chosen by the folder-trust decision for the session's own cwd), built from no client input.",
694
+ },
695
+ {
696
+ file: 'web-task-manager.js',
697
+ match: "execFile(cmd, args, { timeout: 15_000, ...opts }, (err, stdout) => { this._childProcesses.delete(child) if (err) return reject(err) resolve(stdout) })",
698
+ reason: "the same generic exec wrapper as above, with its child tracked so destroy() can stop it: its one caller passes ['--setting-sources', <one of two fixed strings>, '--teleport', task.taskId], where task.taskId is a server-generated randomUUID() looked up from the task map.",
699
+ },
680
700
  {
681
701
  file: 'web-task-manager.js',
682
702
  match: "execFile(cmd, args, { timeout: 15_000, ...opts }, (err, stdout) => { if (err) return reject(err) resolve(stdout) })",
@@ -698,6 +718,15 @@ export const AUDITED_SINKS = [
698
718
  match: "execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' })",
699
719
  reason: 'cwd is always an absolute repo/worktree path from server config or resolveRepoSet discovery; the only variable positionals pushed through args are absolute paths reported by `git worktree list --porcelain` itself, or a --reason-bound lockReason value — never remote/WS-supplied text.',
700
720
  },
721
+ {
722
+ file: 'worktree-gc.js',
723
+ // #9242: the scheduler's removal guard (worktreeHasUnsavedWork) runner. Same shape
724
+ // as the entry above with a bigger buffer and a timeout; its only callers pass
725
+ // fully literal argv arrays (status / rev-list / ls-files) and the cwd of a
726
+ // session's own worktree path.
727
+ match: "execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 30_000 })",
728
+ reason: "strictGit's callers (worktreeHasUnsavedWork/isClean) pass literal argv arrays only; cwd is a session worktree path under the daemon's worktree base, never remote text.",
729
+ },
701
730
  ]
702
731
 
703
732
  /**
@@ -31,8 +31,14 @@
31
31
  * two bytes are `#!` (a shebang). A native binary's magic bytes (ELF
32
32
  * `\x7fELF`, Mach-O `\xcf\xfa\xed\xfe` / `\xca\xfe\xba\xbe`, PE `MZ`)
33
33
  * never collide with `#!`, so this never misclassifies a native binary.
34
- * 2. It has an ENCLOSING PACKAGE ROOT — the nearest ancestor directory
35
- * whose `package.json` declares a non-empty `name` AND whose `bin`
34
+ * 2. It has an ENCLOSING PACKAGE ROOT — prefer the root of the nearest
35
+ * containing `node_modules/<name>` or `node_modules/@scope/<name>`
36
+ * install layout, so a closer claiming package.json cannot narrow a
37
+ * valid npm package's tree (#8097). That root must have a non-empty
38
+ * `name` AND a `bin` (string or map) or `main` claiming this entry.
39
+ * If the layout root is invalid, or outside an npm layout, keep the
40
+ * nearest claiming ancestor fallback. Its `package.json` needs a
41
+ * non-empty `name` AND its `bin`
36
42
  * (string or map) or `main` field actually resolves to this entry file
37
43
  * (#8093 review S3). Climbing skips a name-less marker file (e.g. a bare
38
44
  * `{"type":"module"}` some build tooling drops partway up a tree), a
@@ -236,9 +242,13 @@ function packageClaimsEntry(root, pkg, entryPath, realpath) {
236
242
  }
237
243
 
238
244
  /**
239
- * Find the nearest ancestor directory of `entryPath` whose `package.json`
240
- * declares a non-empty `name` AND claims `entryPath` as one of its own `bin`
241
- * targets or its `main` (#8093 review S3 — see {@link packageClaimsEntry}).
245
+ * Prefer a package root in a containing node_modules layout (innermost to
246
+ * outermost),
247
+ * provided its named package.json claims the canonical entry (#8097). Use
248
+ * that root's metadata, not a closer decoy's optionalDependencies. Aliased
249
+ * installs may have a different package name than the directory spelling.
250
+ * For an invalid layout root or a non-npm path, retain the nearest claiming
251
+ * ancestor fallback (#8093 review S3 — see {@link packageClaimsEntry}).
242
252
  * Skips a name-less marker file, a malformed one, and a named-but-non-
243
253
  * claiming one — none of those are a real package boundary for THIS entry —
244
254
  * and keeps climbing past any of them.
@@ -254,23 +264,55 @@ export function findEnclosingPackageRoot(
254
264
  entryPath,
255
265
  { readFileSync: readFile = readFileSync, existsSync: exists = existsSync, realpathSync: realpath = realpathSync } = {},
256
266
  ) {
257
- let dir = dirname(entryPath)
258
- let prev = null
259
- while (dir !== prev) {
260
- const pkgPath = join(dir, 'package.json')
267
+ function readOwner(root) {
268
+ const pkgPath = join(root, 'package.json')
261
269
  if (exists(pkgPath)) {
262
270
  try {
263
271
  const pkg = JSON.parse(readFile(pkgPath, 'utf8'))
264
- if (pkg && typeof pkg.name === 'string' && pkg.name.length > 0 && packageClaimsEntry(dir, pkg, entryPath, realpath)) {
265
- return { root: dir, packageJson: pkg }
272
+ if (pkg && typeof pkg.name === 'string' && pkg.name.length > 0 && packageClaimsEntry(root, pkg, entryPath, realpath)) {
273
+ return { root, packageJson: pkg }
266
274
  }
267
- // name-less marker (e.g. `{"type":"module"}`), or a named package
268
- // that doesn't claim this entry as its own bin/main — neither is a
269
- // boundary for THIS entry — keep climbing.
270
275
  } catch {
271
- // malformed JSON — not a boundary either, keep climbing.
276
+ // Malformed JSON is not a package boundary.
272
277
  }
273
278
  }
279
+ return null
280
+ }
281
+
282
+ // Use components rather than a substring. Collect EVERY containing npm
283
+ // install root (a non-claiming inner package must not hide a valid outer
284
+ // owner), then try them innermost to outermost.
285
+ const parts = dirname(entryPath).split(sep)
286
+ const npmRoots = []
287
+ for (let index = 0; index < parts.length; index += 1) {
288
+ if (parts[index] !== 'node_modules') continue
289
+ const scope = parts[index + 1]
290
+ const rootLength = index + (scope?.startsWith('@') ? 3 : 2)
291
+ // A malformed scope or the reserved unscoped package name node_modules
292
+ // does not describe a valid npm install. Keep the old fallback there.
293
+ const valid = parts.length >= rootLength
294
+ && scope !== '@' && !scope?.includes('@', 1) && scope !== 'node_modules'
295
+ if (valid) npmRoots.push(parts.slice(0, rootLength).join(sep))
296
+ // Package-name components are not install containers themselves, even
297
+ // when a scoped package's own directory is named node_modules.
298
+ index += scope?.startsWith('@') ? 2 : 1
299
+ }
300
+ const tried = new Set()
301
+ for (let i = npmRoots.length - 1; i >= 0; i -= 1) {
302
+ tried.add(npmRoots[i])
303
+ const owner = readOwner(npmRoots[i])
304
+ if (owner) return owner
305
+ }
306
+
307
+ // Keep the existing nearest-claim fallback for non-npm and invalid roots.
308
+ // The npm candidates were already read, so do not read them a second time.
309
+ let dir = dirname(entryPath)
310
+ let prev = null
311
+ while (dir !== prev) {
312
+ if (!tried.has(dir)) {
313
+ const owner = readOwner(dir)
314
+ if (owner) return owner
315
+ }
274
316
  prev = dir
275
317
  dir = dirname(dir)
276
318
  }
@@ -23,3 +23,7 @@ parentPort.on('message', ({ id, source, text }) => {
23
23
  const re = compile(source)
24
24
  parentPort.postMessage({ id, matched: re ? re.test(text) : false })
25
25
  })
26
+
27
+ // Tell the owner the handler above is attached. The thread is 'online' before
28
+ // this module has loaded, and a match deadline must not include that load.
29
+ parentPort.postMessage({ ready: true })
@@ -46,7 +46,7 @@ export function createBoundedRegexMatcher({
46
46
  workerUrl = new URL('./bounded-regex-worker.js', import.meta.url),
47
47
  } = {}) {
48
48
  let worker = null
49
- let online = null // Promise<boolean> for the current worker
49
+ let ready = null // Promise<boolean> for the current worker: true once it can answer
50
50
  let seq = 0
51
51
  let chain = Promise.resolve()
52
52
  let timeouts = 0
@@ -61,27 +61,36 @@ export function createBoundedRegexMatcher({
61
61
  // Referenced while a match is pending (so an awaiting caller keeps the loop
62
62
  // alive), unreferenced when idle (see finish).
63
63
  worker = w
64
- online = new Promise((resolve) => {
64
+ // 'online' only means the thread started running JS, possibly before its
65
+ // module has attached the message handler, so wait for the worker's own
66
+ // ready message. A job posted earlier would sit queued while its deadline ran.
67
+ ready = new Promise((resolve) => {
65
68
  const timer = setTimeout(() => resolve(false), STARTUP_TIMEOUT_MS)
66
- w.once('online', () => { clearTimeout(timer); resolve(true) })
69
+ const onReady = (m) => {
70
+ if (m?.ready !== true) return
71
+ w.off('message', onReady)
72
+ clearTimeout(timer)
73
+ resolve(true)
74
+ }
75
+ w.on('message', onReady)
67
76
  w.once('error', () => { clearTimeout(timer); resolve(false) })
68
77
  w.once('exit', () => { clearTimeout(timer); resolve(false) })
69
78
  })
70
- const forget = () => { if (worker === w) { worker = null; online = null } }
79
+ const forget = () => { if (worker === w) { worker = null; ready = null } }
71
80
  w.on('error', forget)
72
81
  w.on('exit', forget)
73
82
  return w
74
83
  }
75
84
 
76
85
  function drop(w) {
77
- if (worker === w) { worker = null; online = null }
86
+ if (worker === w) { worker = null; ready = null }
78
87
  w.terminate().catch(() => {})
79
88
  }
80
89
 
81
90
  async function run(source, text) {
82
91
  const w = worker || spawn()
83
- // The deadline is for the MATCH: it starts once the worker is up.
84
- if (!(await online)) { drop(w); return false }
92
+ // The deadline is for the MATCH: it starts once the worker can answer.
93
+ if (!(await ready)) { drop(w); return false }
85
94
  return new Promise((resolve) => {
86
95
  const id = ++seq
87
96
  let settled = false
@@ -0,0 +1,47 @@
1
+ /**
2
+ * PID liveness, classified honestly (#9074).
3
+ *
4
+ * `process.kill(pid, 0)` sends no signal; it only asks the OS whether `pid` can be
5
+ * signalled by this caller. Only one of its outcomes is conclusive:
6
+ *
7
+ * ESRCH -> 'dead' no process has this PID. The only proof of absence.
8
+ * succeeds -> 'alive' some process with this PID exists and this caller
9
+ * may signal it. That is all it shows. It does NOT
10
+ * prove the process is the daemon that wrote the
11
+ * record (a PID can be reused after an unclean exit),
12
+ * nor that anything is listening on the record's port.
13
+ * EPERM -> 'unverified' the probe was not permitted. This often means a
14
+ * process exists that this caller may not signal
15
+ * (another user's, or one a sandbox hides), but a
16
+ * sandbox may also deny the probe outright, so it
17
+ * proves neither existence nor absence.
18
+ * any other -> 'unverified' the probe failed for a reason that proves nothing.
19
+ *
20
+ * A PID that is not a positive safe integer is never probed and is 'unverified':
21
+ * `kill(0, 0)` and `kill(-n, 0)` address process GROUPS (the caller's own, for 0),
22
+ * so a malformed record with pid 0 would otherwise read as alive.
23
+ *
24
+ * Callers must treat 'unverified' as "do not know": never as healthy (do not send
25
+ * credentials on it) and never as dead (do not delete what it describes).
26
+ */
27
+
28
+ export const PID_ALIVE = 'alive'
29
+ export const PID_DEAD = 'dead'
30
+ export const PID_UNVERIFIED = 'unverified'
31
+
32
+ /**
33
+ * @param {unknown} pid
34
+ * @param {{ kill?: (pid: number, signal: number) => void }} [deps] - probe seam for
35
+ * tests; defaults to `process.kill`, looked up at call time
36
+ * @returns {'alive' | 'dead' | 'unverified'}
37
+ */
38
+ export function probePidLiveness(pid, deps = {}) {
39
+ if (!Number.isSafeInteger(pid) || pid <= 0) return PID_UNVERIFIED
40
+ const kill = typeof deps.kill === 'function' ? deps.kill : (p, s) => process.kill(p, s)
41
+ try {
42
+ kill(pid, 0)
43
+ return PID_ALIVE
44
+ } catch (err) {
45
+ return err && err.code === 'ESRCH' ? PID_DEAD : PID_UNVERIFIED
46
+ }
47
+ }
@@ -4,6 +4,7 @@ import { buildClaudeLaunchEnv } from './utils/spawn-env.js'
4
4
  import { randomUUID } from 'crypto'
5
5
  import { cliHelpAdvertisesFlag, cliHelpFlagArity, isSafeArgvValue } from './utils/argv-safety.js'
6
6
  import { CliSession } from './cli-session.js'
7
+ import { claudeSettingSourcesValueFor, projectSettingsAllowedAsync, projectSettingsDecidedWithoutScan } from './claude-setting-sources.js'
7
8
  import { createLogger } from './logger.js'
8
9
 
9
10
  const log = createLogger('web-task-manager')
@@ -303,7 +304,10 @@ export class WebTaskManager extends EventEmitter {
303
304
 
304
305
  try {
305
306
  const bin = this._verifyBinary()
306
- const stdout = await execFileAsync(bin, ['--teleport', task.taskId], { cwd: task.cwd, env: buildClaudeLaunchEnv() })
307
+ const projectAllowed = await projectSettingsAllowedAsync(task.cwd)
308
+ // The manager may have been destroyed while the folder was being verified.
309
+ if (this._destroyed) throw new Error('the task manager was shut down')
310
+ const stdout = await this._execTracked(bin, ['--setting-sources', claudeSettingSourcesValueFor(projectAllowed), '--teleport', task.taskId], { cwd: task.cwd, env: buildClaudeLaunchEnv() })
307
311
  return { success: true, output: stdout }
308
312
  } catch (err) {
309
313
  // #8060 review nitpick: only a GATE refusal gets a `(code=…)` suffix —
@@ -361,8 +365,44 @@ export class WebTaskManager extends EventEmitter {
361
365
  this.emit('task_error', { taskId: task.taskId, message: task.error })
362
366
  return
363
367
  }
368
+ // One project-settings decision per launch. A folder with no trust record is decided
369
+ // at once; a trusted one is verified by a fresh scan off the main thread first.
370
+ const decided = projectSettingsDecidedWithoutScan(task.cwd)
371
+ if (decided !== null) {
372
+ this._execRemoteTask(task, bin, decided)
373
+ return
374
+ }
375
+ projectSettingsAllowedAsync(task.cwd).then((allowed) => {
376
+ // Not if the manager was destroyed, or the task was removed or is no longer pending.
377
+ if (this._destroyed || this._tasks.get(task.taskId) !== task || task.status !== 'pending') return
378
+ this._execRemoteTask(task, bin, allowed)
379
+ }).catch((err) => {
380
+ if (this._destroyed || this._tasks.get(task.taskId) !== task) return
381
+ log.warn(`web task launch failed: ${err?.message || err}`)
382
+ task.status = 'failed'
383
+ task.error = err?.message || 'launch failed'
384
+ task.updatedAt = Date.now()
385
+ this.emit('task_updated', { ...task })
386
+ this.emit('task_error', { taskId: task.taskId, message: task.error })
387
+ })
388
+ }
389
+
390
+ /** execFile whose child is tracked, so destroy() stops it. @private */
391
+ _execTracked(cmd, args, opts) {
392
+ return new Promise((resolve, reject) => {
393
+ const child = execFile(cmd, args, { timeout: 15_000, ...opts }, (err, stdout) => {
394
+ this._childProcesses.delete(child)
395
+ if (err) return reject(err)
396
+ resolve(stdout)
397
+ })
398
+ this._childProcesses.add(child)
399
+ })
400
+ }
401
+
402
+ /** Run the remote CLI for a task with the decided project-settings scope. @private */
403
+ _execRemoteTask(task, bin, projectAllowed) {
364
404
  // Use execFile with args array to prevent command injection
365
- const child = execFile(bin, buildRemoteTaskArgs(task.prompt), { cwd: task.cwd, timeout: 300_000, env: buildClaudeLaunchEnv() }, (err, stdout, stderr) => {
405
+ const child = execFile(bin, buildRemoteTaskArgs(task.prompt, projectAllowed), { cwd: task.cwd, timeout: 300_000, env: buildClaudeLaunchEnv() }, (err, stdout, stderr) => {
366
406
  this._childProcesses.delete(child)
367
407
  // #7299: this callback runs asynchronously and can fire AFTER
368
408
  // destroy() has already cleared _pollTimer and cleared _tasks — a late
@@ -577,10 +617,11 @@ export class WebTaskUnavailableError extends Error {
577
617
  * `claude -- --nonexistent-flag-xyz` does not.
578
618
  *
579
619
  * @param {string} prompt - client-supplied task text.
620
+ * @param {boolean} [projectAllowed] - the project-settings launch decision for the task folder; absent means not allowed
580
621
  * @returns {string[]}
581
622
  */
582
- export function buildRemoteTaskArgs(prompt) {
583
- return ['--remote', '--', prompt]
623
+ export function buildRemoteTaskArgs(prompt, projectAllowed) {
624
+ return ['--setting-sources', claudeSettingSourcesValueFor(projectAllowed === true), '--remote', '--', prompt]
584
625
  }
585
626
 
586
627
  /**