@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
@@ -1,21 +1,133 @@
1
- import { normalize, resolve } from 'path'
1
+ import { normalize, resolve, join } from 'path'
2
2
  import { execFile as execFileCb } from 'child_process'
3
3
  import { promisify } from 'util'
4
+ import { writeFile, unlink } from 'fs/promises'
5
+ import { tmpdir } from 'os'
6
+ import { randomBytes } from 'crypto'
4
7
  import { GIT } from '../git.js'
5
8
  import { validateGitPath } from './common.js'
6
9
 
7
10
  const execFileAsync = promisify(execFileCb)
8
11
 
12
+ // #6876 — result sender for the git_create_pr flow. Every field is always
13
+ // present (present-and-nullable) so the wire payload satisfies
14
+ // ServerGitCreatePrResultSchema on every path. #6938 — `existingUrl` is a
15
+ // structured (non-null) field only on the "PR already exists" error path, so
16
+ // the dashboard can render it as a clickable link instead of parsing it back
17
+ // out of the `error` string.
18
+ function prResult({ url = null, number = null, branch = null, base = null, error = null, existingUrl = null } = {}) {
19
+ return { type: 'git_create_pr_result', url, number, branch, base, error, existingUrl }
20
+ }
21
+
22
+ /** Extract the first `.../pull/<n>` URL from gh output (stdout or stderr). */
23
+ function extractPrUrl(text) {
24
+ if (!text) return null
25
+ const m = String(text).match(/https?:\/\/\S*\/pull\/\d+/)
26
+ return m ? m[0] : null
27
+ }
28
+
29
+ /** Parse the numeric PR id out of a `.../pull/<n>` URL. */
30
+ function extractPrNumber(url) {
31
+ if (!url) return null
32
+ const m = String(url).match(/\/pull\/(\d+)/)
33
+ return m ? Number(m[1]) : null
34
+ }
35
+
9
36
  /**
10
- * Git operations: status, branches, stage, unstage, commit.
37
+ * Resolve the repo's default (base) branch from `origin/HEAD`. Returns '' when
38
+ * it can't be determined, in which case the caller omits `--base` and lets `gh`
39
+ * pick the repo default via the API.
40
+ */
41
+ async function resolveDefaultBase(execImpl, cwdReal) {
42
+ try {
43
+ const { stdout } = await execImpl(GIT, ['rev-parse', '--abbrev-ref', 'origin/HEAD'], { cwd: cwdReal, timeout: 5000 })
44
+ const ref = (stdout || '').trim() // e.g. "origin/main"
45
+ if (ref && ref !== 'origin/HEAD') {
46
+ return ref.startsWith('origin/') ? ref.slice('origin/'.length) : ref
47
+ }
48
+ } catch {
49
+ // origin/HEAD not set (fresh clone / no default) — fall through to gh's default.
50
+ }
51
+ return ''
52
+ }
53
+
54
+ /** First non-empty trimmed line of a multi-line error string. */
55
+ function firstLine(text) {
56
+ return String(text || '')
57
+ .split('\n')
58
+ .map(s => s.trim())
59
+ .filter(Boolean)[0] || ''
60
+ }
61
+
62
+ /** Map a `git push` failure to an operator-actionable message. */
63
+ function mapPushError(err) {
64
+ if (err && err.code === 'ENOENT') return 'git is not available on the daemon host'
65
+ const stderr = String((err && (err.stderr || err.message)) || '')
66
+ const lower = stderr.toLowerCase()
67
+ if (/does not appear to be a git repository|no configured push destination|no such remote|no remote/.test(lower)) {
68
+ return 'Cannot push — no `origin` remote is configured for this repository'
69
+ }
70
+ if (/permission denied|authentication failed|could not read|access rights|403|denied to|fatal: could not read/.test(lower)) {
71
+ return 'Cannot push — the daemon is not authorized to push to origin (check its git credentials)'
72
+ }
73
+ const line = firstLine(stderr)
74
+ return line ? `Failed to push branch: ${line}` : 'Failed to push the current branch to origin'
75
+ }
76
+
77
+ /**
78
+ * Map a `gh pr create` failure to an operator-actionable message.
79
+ *
80
+ * Returns `{ message, existingUrl }` — `existingUrl` is the pre-existing PR's
81
+ * `/pull/<n>` URL (non-null) only on the "PR already exists" path, so the
82
+ * caller can surface it as a structured field on `git_create_pr_result`
83
+ * (#6938) rather than the dashboard having to regex it back out of `message`.
84
+ */
85
+ function mapGhCreateError(err) {
86
+ if (err && err.code === 'ENOENT') {
87
+ return {
88
+ message: 'GitHub CLI (gh) is not installed on the daemon host — install it from https://cli.github.com to open PRs from Chroxy',
89
+ existingUrl: null,
90
+ }
91
+ }
92
+ const stderr = String((err && (err.stderr || err.message)) || '')
93
+ const lower = stderr.toLowerCase()
94
+ if (/already exists|a pull request for branch/.test(lower)) {
95
+ // gh sometimes writes the existing-PR URL to stdout rather than stderr —
96
+ // parse both streams (and the error message) the same way the success
97
+ // path does, so the URL isn't missed depending on which stream gh used.
98
+ const existing = extractPrUrl(err && err.stdout) || extractPrUrl(stderr)
99
+ return {
100
+ message: existing
101
+ ? `A pull request already exists for this branch: ${existing}`
102
+ : 'A pull request already exists for this branch',
103
+ existingUrl: existing,
104
+ }
105
+ }
106
+ if (/gh auth login|not logged in|authentication required|no credentials|requires authentication|http 401|gh auth status/.test(lower)) {
107
+ return {
108
+ message: 'GitHub CLI is not authenticated — run `gh auth login` on the daemon host to enable PR creation',
109
+ existingUrl: null,
110
+ }
111
+ }
112
+ if (/no git remotes found|not a git repository|does not appear to be a git repository|could not determine base repo/.test(lower)) {
113
+ return { message: 'No GitHub remote is configured for this repository', existingUrl: null }
114
+ }
115
+ const line = firstLine(stderr)
116
+ return { message: line || (err && err.message) || 'Failed to create pull request', existingUrl: null }
117
+ }
118
+
119
+ /**
120
+ * Git operations: status, branches, stage, unstage, commit, create PR.
11
121
  *
12
122
  * @param {Function} sendFn - (ws, message) => void
13
123
  * @param {Function} resolveSessionCwd - shared CWD resolver
14
124
  * @param {Function} validatePathWithinCwd - shared path validator
15
125
  * @param {string} workspaceRoot - workspace root directory; git ops are restricted to paths within it
126
+ * @param {Function} [execImpl] - injectable promisified execFile seam (defaults to the real one; the
127
+ * git_create_pr tests inject a mock so no real branch is pushed or PR opened)
16
128
  * @returns {Object} git operation methods
17
129
  */
18
- export function createGitOps(sendFn, resolveSessionCwd, validatePathWithinCwd, workspaceRoot) {
130
+ export function createGitOps(sendFn, resolveSessionCwd, validatePathWithinCwd, workspaceRoot, execImpl = execFileAsync) {
19
131
 
20
132
  /** Get git status (branch, staged, unstaged, untracked) for a session CWD */
21
133
  async function gitStatus(ws, sessionCwd) {
@@ -288,11 +400,117 @@ export function createGitOps(sendFn, resolveSessionCwd, validatePathWithinCwd, w
288
400
  }
289
401
  }
290
402
 
403
+ /**
404
+ * #6876 — open a PR for the session's current branch without leaving Chroxy.
405
+ * Pushes the branch (creating/updating its `origin` upstream; a no-op when it
406
+ * is already current) then shells out to `gh pr create`. Returns the created
407
+ * PR URL + number to the client, or a clear, operator-actionable error on any
408
+ * failure (gh missing / not authenticated / no origin remote / PR already
409
+ * exists / detached HEAD / base === head). Never claims success on failure.
410
+ *
411
+ * @param {WebSocket} ws
412
+ * @param {{ title?: string, body?: string, base?: string, draft?: boolean }} opts
413
+ * @param {string|null} sessionCwd
414
+ */
415
+ async function gitCreatePR(ws, opts, sessionCwd) {
416
+ const title = typeof opts?.title === 'string' ? opts.title.trim() : ''
417
+ const body = typeof opts?.body === 'string' ? opts.body : ''
418
+ const requestedBase = typeof opts?.base === 'string' ? opts.base.trim() : ''
419
+ const draft = opts?.draft === true
420
+
421
+ if (!sessionCwd) {
422
+ sendFn(ws, prResult({ error: 'PR creation is not available in this mode' }))
423
+ return
424
+ }
425
+ if (!title) {
426
+ sendFn(ws, prResult({ error: 'Pull request title cannot be empty' }))
427
+ return
428
+ }
429
+
430
+ try {
431
+ await validateGitPath(sessionCwd, workspaceRoot)
432
+ const cwdReal = await resolveSessionCwd(sessionCwd)
433
+
434
+ // 1. Current branch (reject detached HEAD / not-a-repo).
435
+ let branch = null
436
+ try {
437
+ const { stdout } = await execImpl(GIT, ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: cwdReal, timeout: 5000 })
438
+ branch = (stdout || '').trim()
439
+ } catch {
440
+ sendFn(ws, prResult({ error: 'Not a git repository' }))
441
+ return
442
+ }
443
+ if (!branch || branch === 'HEAD') {
444
+ sendFn(ws, prResult({ error: 'Cannot open a PR from a detached HEAD — check out a branch first' }))
445
+ return
446
+ }
447
+
448
+ // 2. Base branch — explicit, else the repo default (origin/HEAD).
449
+ const base = requestedBase || (await resolveDefaultBase(execImpl, cwdReal))
450
+ if (base && base === branch) {
451
+ sendFn(ws, prResult({ branch, base, error: `The current branch (${branch}) is the base branch — create a feature branch before opening a PR` }))
452
+ return
453
+ }
454
+
455
+ // 3. Push the branch (set upstream). No-op when already up to date.
456
+ try {
457
+ await execImpl(GIT, ['push', '--set-upstream', 'origin', branch], { cwd: cwdReal, timeout: 120000 })
458
+ } catch (err) {
459
+ sendFn(ws, prResult({ branch, base: base || null, error: mapPushError(err) }))
460
+ return
461
+ }
462
+
463
+ // 4. gh pr create. Pass the body via a temp `--body-file` rather than an
464
+ // inline `--body <text>` argv element: the client schema permits a body up
465
+ // to 50k chars, which can blow past Windows' command-line length limit when
466
+ // inlined. A body-file sidesteps the limit entirely and keeps the body out
467
+ // of argv. The empty-body case writes an empty file (gh reads it as an
468
+ // empty body without opening an editor). (#6934)
469
+ const bodyFile = join(tmpdir(), `chroxy-pr-body-${randomBytes(8).toString('hex')}.md`)
470
+ let stdout = ''
471
+ let stderr = ''
472
+ try {
473
+ await writeFile(bodyFile, body, 'utf8')
474
+
475
+ const args = ['pr', 'create', '--title', title, '--body-file', bodyFile, '--head', branch]
476
+ if (base) args.push('--base', base)
477
+ if (draft) args.push('--draft')
478
+
479
+ try {
480
+ const res = await execImpl('gh', args, { cwd: cwdReal, timeout: 120000 })
481
+ stdout = res?.stdout || ''
482
+ stderr = res?.stderr || ''
483
+ } catch (err) {
484
+ const mapped = mapGhCreateError(err)
485
+ sendFn(ws, prResult({ branch, base: base || null, error: mapped.message, existingUrl: mapped.existingUrl }))
486
+ return
487
+ }
488
+ } finally {
489
+ // Best-effort cleanup — never fail the create because the temp body-file
490
+ // couldn't be removed.
491
+ await unlink(bodyFile).catch(() => {})
492
+ }
493
+
494
+ // gh prints the created PR URL on stdout, but can emit it on stderr (or
495
+ // split its output). Parse both streams so a stderr-only URL still yields a
496
+ // success. (#6934)
497
+ const url = extractPrUrl(stdout) || extractPrUrl(stderr)
498
+ if (!url) {
499
+ sendFn(ws, prResult({ branch, base: base || null, error: 'PR command succeeded but gh returned no pull-request URL' }))
500
+ return
501
+ }
502
+ sendFn(ws, prResult({ url, number: extractPrNumber(url), branch, base: base || null, error: null }))
503
+ } catch (err) {
504
+ sendFn(ws, prResult({ error: err.message || 'Failed to create pull request' }))
505
+ }
506
+ }
507
+
291
508
  return {
292
509
  gitStatus,
293
510
  gitBranches,
294
511
  gitStage,
295
512
  gitUnstage,
296
513
  gitCommit,
514
+ gitCreatePR,
297
515
  }
298
516
  }
@@ -3,6 +3,7 @@ import { resolveSessionCwd, validatePathWithinCwd } from './common.js'
3
3
  import { createBrowserOps } from './browser.js'
4
4
  import { createReaderOps } from './reader.js'
5
5
  import { createGitOps } from './git.js'
6
+ import { createMemoryOps } from './memory.js'
6
7
 
7
8
  /**
8
9
  * Create file operation handlers for the WsServer.
@@ -29,12 +30,15 @@ export function createFileOps(sendFn, workspaceRoot) {
29
30
  const browser = createBrowserOps(sendFn, boundResolve, boundValidate)
30
31
  const reader = createReaderOps(sendFn, boundResolve, boundValidate)
31
32
  const git = createGitOps(sendFn, boundResolve, boundValidate, gitWorkspaceRoot)
33
+ const memory = createMemoryOps(sendFn, boundResolve)
32
34
 
33
35
  return {
34
36
  listDirectory: browser.listDirectory,
35
37
  browseFiles: browser.browseFiles,
36
38
  readFile: reader.readFile,
37
39
  writeFile: reader.writeFile,
40
+ appendMemory: reader.appendMemory,
41
+ readMemory: memory.readMemory,
38
42
  getDiff: reader.getDiff,
39
43
  listSlashCommands: browser.listSlashCommands,
40
44
  listAgents: browser.listAgents,
@@ -48,5 +52,6 @@ export function createFileOps(sendFn, workspaceRoot) {
48
52
  gitStage: git.gitStage,
49
53
  gitUnstage: git.gitUnstage,
50
54
  gitCommit: git.gitCommit,
55
+ gitCreatePR: git.gitCreatePR,
51
56
  }
52
57
  }
@@ -0,0 +1,358 @@
1
+ import { stat, open } from 'fs/promises'
2
+ import { constants as fsConstants } from 'fs'
3
+ import { resolve, dirname, normalize, sep, extname } from 'path'
4
+ import { homedir } from 'os'
5
+ import { realpathOfDeepestAncestor } from './common.js'
6
+ import { encodeProjectPath } from '../jsonl-reader.js'
7
+
8
+ /** stat-size ceiling before attempting a read (matches readFileContent) */
9
+ const MAX_FILE_SIZE = 512 * 1024
10
+ /** returned content is truncated past this (matches readFileContent) */
11
+ const MAX_CONTENT_SIZE = 100 * 1024
12
+ /** max recursive @import hops — matches Claude Code's own import recursion cap */
13
+ const MAX_IMPORT_DEPTH = 4
14
+ /** hard ceiling on total import entries per read — defence against import fan-out */
15
+ const MAX_IMPORT_ENTRIES = 50
16
+ /**
17
+ * Extensions an `@import` target may resolve to. Memory `@import`s are meant to
18
+ * pull in MARKDOWN memory files, not arbitrary files — restricting the resolved
19
+ * target to this allowlist blocks the sensitive-file class under an allowed root
20
+ * (`~/.claude/.credentials.json`, `~/.claude/settings.json`, identity keys,
21
+ * other projects' `~/.claude/projects/**` `.jsonl` transcripts, extensionless
22
+ * files) that would otherwise resolve IN-BOUNDS and be surfaced to the client.
23
+ * More robust than a filename blocklist — it closes the whole class. (#6971)
24
+ */
25
+ const IMPORT_ALLOWED_EXTS = ['.md', '.markdown']
26
+ /**
27
+ * Single "not readable — skipped" reason string shared by EVERY skip branch
28
+ * (out-of-bounds, non-markdown `@import`, resolution failure). Reusing ONE
29
+ * message keeps the skip entries byte-identical so a client cannot distinguish
30
+ * "outside allowed roots" from "not a markdown file" from "couldn't resolve" —
31
+ * no error-string oracle. (#6971)
32
+ */
33
+ const MEMORY_SKIP_ERROR = 'Outside allowed memory roots — read skipped'
34
+
35
+ // Matches an `@path` memory-import reference (Claude Code's CLAUDE.md import
36
+ // syntax — see docs.claude.com "Manage Claude's memory" / "Import additional
37
+ // files"). Requires a non-word/non-@ character (or start-of-string) before the
38
+ // `@` so `user@example.com` / `foo@bar` prose is never mistaken for an import.
39
+ const IMPORT_RE = /(^|[^\w@])@([\w./~-][\w./~-]*)/g
40
+
41
+ /**
42
+ * Strip fenced code blocks and inline code spans before import scanning — the
43
+ * real @import syntax explicitly does NOT resolve inside code spans/blocks (a
44
+ * backtick-wrapped `@README` stays literal). We only need the SET of import
45
+ * paths, not their offsets, so stripped content is simply discarded.
46
+ */
47
+ function stripCodeForImportScan(content) {
48
+ return content
49
+ .replace(/```[\s\S]*?```/g, '')
50
+ .replace(/`[^`\n]*`/g, '')
51
+ }
52
+
53
+ function extractImportPaths(content) {
54
+ const stripped = stripCodeForImportScan(content)
55
+ const paths = []
56
+ for (const m of stripped.matchAll(IMPORT_RE)) {
57
+ // Trim common trailing sentence punctuation a markdown author would have
58
+ // typed right after the path (period, comma, colon, closing paren).
59
+ const p = m[2].replace(/[.,:;)]+$/, '')
60
+ if (p) paths.push(p)
61
+ }
62
+ return paths
63
+ }
64
+
65
+ /**
66
+ * Resolve an @import target to an absolute LEXICAL path.
67
+ * - `~/...` / `~` -> resolved against the user's home directory
68
+ * - `/...` -> already absolute
69
+ * - anything else -> resolved relative to the DIRECTORY of the file that
70
+ * contained the @import (matches real Claude Code semantics: imports
71
+ * resolve relative to the importing file, not the session cwd).
72
+ */
73
+ function resolveImportTarget(rawPath, importingFileAbsPath) {
74
+ if (rawPath === '~' || rawPath.startsWith('~/')) {
75
+ return normalize(resolve(homedir(), rawPath.slice(1).replace(/^\//, '')))
76
+ }
77
+ if (rawPath.startsWith('/')) {
78
+ return normalize(rawPath)
79
+ }
80
+ return normalize(resolve(dirname(importingFileAbsPath), rawPath))
81
+ }
82
+
83
+ /**
84
+ * True iff `p`'s extension is in the `@import` markdown allowlist
85
+ * (case-insensitive) — see IMPORT_ALLOWED_EXTS. An extensionless path
86
+ * (`extname` → '') is NOT markdown and is rejected.
87
+ */
88
+ function hasMarkdownExt(p) {
89
+ return IMPORT_ALLOWED_EXTS.includes(extname(p).toLowerCase())
90
+ }
91
+
92
+ /**
93
+ * Phase 1 of the confined-memory-file read: resolve + validate a LEXICAL
94
+ * target path within one of the given allowed roots WITHOUT touching file
95
+ * content — no `stat`/`open`/read, just the markdown-extension gate,
96
+ * symlink-safe realpath resolution, and the containment check. Split out
97
+ * from `readConfinedMemoryFile` so a caller (namely `collectImports`) can
98
+ * compute a target's cycle-guard identity — the resolved real path — and
99
+ * consult the `visited` set BEFORE paying for the actual read, so a
100
+ * duplicate/cyclical `@import` short-circuits before any I/O beyond this
101
+ * lightweight resolution (#6971 perf follow-up).
102
+ *
103
+ * Symlink-safe: resolves the deepest existing real ancestor before the
104
+ * containment check (same helper reader.js uses), so a symlinked parent
105
+ * directory can't smuggle the target outside the allowed roots.
106
+ *
107
+ * With `{ requireMarkdownExt: true }` (the `@import` path passes this; the fixed
108
+ * root files do NOT), a resolved target whose extension is not in
109
+ * IMPORT_ALLOWED_EXTS is rejected up front — same skip shape as out-of-bounds —
110
+ * closing the "@import a non-markdown sensitive file under ~/.claude" class (#6971).
111
+ *
112
+ * Never throws — every failure mode folds into a ready-to-push `skipEntry`
113
+ * (byte-identical MEMORY_SKIP_ERROR shape, echoing the LEXICAL request path —
114
+ * no distinguishing oracle) instead of a resolved path.
115
+ *
116
+ * @param {string} lexicalAbsPath - Absolute LEXICAL (pre-realpath) target path
117
+ * @param {string[]} allowedRoots - Real-path roots the target must resolve within
118
+ * @param {{requireMarkdownExt?: boolean}} [opts] - `@import`-only markdown-extension gate
119
+ * @returns {Promise<{resolvedPath: string|null, skipEntry: object|null}>}
120
+ */
121
+ async function resolveConfinedMemoryPath(lexicalAbsPath, allowedRoots, { requireMarkdownExt = false } = {}) {
122
+ const base = { path: lexicalAbsPath, exists: false, content: null, truncated: false, skipped: false, error: null }
123
+
124
+ // `@import` markdown allowlist (import path ONLY; the fixed root files are
125
+ // exempt). A non-markdown target — `~/.claude/.credentials.json`,
126
+ // `~/.claude/settings.json`, an identity key, a `.jsonl` transcript, an
127
+ // extensionless file — is rejected with the SAME shape an out-of-bounds path
128
+ // gets, so there's no distinguishing oracle between "out of bounds", "not
129
+ // markdown", and "doesn't exist". Purely LEXICAL and BEFORE any realpath/stat,
130
+ // so a non-markdown import never even touches the filesystem. (#6971)
131
+ if (requireMarkdownExt && !hasMarkdownExt(lexicalAbsPath)) {
132
+ return { resolvedPath: null, skipEntry: { ...base, skipped: true, error: MEMORY_SKIP_ERROR } }
133
+ }
134
+
135
+ let resolvedPath
136
+ try {
137
+ resolvedPath = await realpathOfDeepestAncestor(lexicalAbsPath)
138
+ } catch {
139
+ // Resolution failed (EACCES on an ancestor dir, symlink-depth ceiling, …).
140
+ // Normalize to the identical clean-skip shape rather than echoing the raw
141
+ // error message — no error-string oracle, no content leak. (#6971)
142
+ return { resolvedPath: null, skipEntry: { ...base, skipped: true, error: MEMORY_SKIP_ERROR } }
143
+ }
144
+
145
+ const withinRoot = allowedRoots.some((root) => resolvedPath === root || resolvedPath.startsWith(root + sep))
146
+ if (!withinRoot) {
147
+ // Outside every allowed root — reject WITHOUT stat'ing (no existence oracle).
148
+ // Echo the LEXICAL request path (base.path), NOT the realpath-resolved path,
149
+ // so a skipped entry can't be used as a symlink-target oracle. (#6971)
150
+ return { resolvedPath: null, skipEntry: { ...base, skipped: true, error: MEMORY_SKIP_ERROR } }
151
+ }
152
+
153
+ return { resolvedPath, skipEntry: null }
154
+ }
155
+
156
+ /**
157
+ * Phase 2 of the confined-memory-file read: `stat`/`open`/read an ALREADY
158
+ * resolved+validated real path (see `resolveConfinedMemoryPath`). The final
159
+ * open uses O_NOFOLLOW to close the post-validation TOCTOU window (a symlink
160
+ * swapped in at the target between validation and open is rejected, not
161
+ * followed).
162
+ *
163
+ * @param {string} resolvedPath - Real (post-realpath, already containment-checked) path
164
+ * @returns {Promise<{path: string, exists: boolean, content: string|null, truncated: boolean, skipped: boolean, error: string|null}>}
165
+ */
166
+ async function readResolvedMemoryFile(resolvedPath) {
167
+ const base = { path: resolvedPath, exists: false, content: null, truncated: false, skipped: false, error: null }
168
+
169
+ let fileStat
170
+ try {
171
+ fileStat = await stat(resolvedPath)
172
+ } catch (err) {
173
+ if (err.code === 'ENOENT') return { ...base, exists: false }
174
+ return { ...base, error: err.code === 'EACCES' ? 'Permission denied' : (err.message || 'Unknown error') }
175
+ }
176
+
177
+ if (!fileStat.isFile()) {
178
+ return { ...base, exists: true, error: 'Not a regular file' }
179
+ }
180
+ if (fileStat.size > MAX_FILE_SIZE) {
181
+ return { ...base, exists: true, error: 'File too large (max 512KB)' }
182
+ }
183
+
184
+ let buf
185
+ let fh
186
+ try {
187
+ fh = await open(resolvedPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
188
+ buf = await fh.readFile()
189
+ } catch (err) {
190
+ if (err.code === 'ELOOP') {
191
+ // Symlink appeared at the canonical path after validation — reject.
192
+ return { ...base, exists: true, skipped: true, error: 'Access denied: possible symlink race — read skipped' }
193
+ }
194
+ return { ...base, exists: true, error: err.message || 'Unknown error' }
195
+ } finally {
196
+ await fh?.close()
197
+ }
198
+
199
+ let content = buf.toString('utf-8')
200
+ let truncated = false
201
+ if (content.length > MAX_CONTENT_SIZE) {
202
+ content = content.slice(0, MAX_CONTENT_SIZE)
203
+ truncated = true
204
+ }
205
+
206
+ return { ...base, exists: true, content, truncated }
207
+ }
208
+
209
+ /**
210
+ * Read+validate a single memory file that MUST resolve within one of the
211
+ * given allowed roots — the read-only path-confinement guard for #6864.
212
+ * Thin composition of `resolveConfinedMemoryPath` (validate, no I/O beyond
213
+ * resolution) + `readResolvedMemoryFile` (stat/open/read) — kept as a single
214
+ * entry point for callers (the three fixed root files, the MEMORY.md
215
+ * descriptor) that don't need to consult a cycle guard before reading.
216
+ *
217
+ * @param {string} lexicalAbsPath - Absolute LEXICAL (pre-realpath) target path
218
+ * @param {string[]} allowedRoots - Real-path roots the target must resolve within
219
+ * @param {{requireMarkdownExt?: boolean}} [opts] - `@import`-only markdown-extension gate
220
+ * @returns {Promise<{path: string|null, exists: boolean, content: string|null, truncated: boolean, skipped: boolean, error: string|null}>}
221
+ */
222
+ async function readConfinedMemoryFile(lexicalAbsPath, allowedRoots, opts = {}) {
223
+ const { resolvedPath, skipEntry } = await resolveConfinedMemoryPath(lexicalAbsPath, allowedRoots, opts)
224
+ if (skipEntry) return skipEntry
225
+ return readResolvedMemoryFile(resolvedPath)
226
+ }
227
+
228
+ /**
229
+ * Recursively resolve @imports referenced FROM `content`, appending entries
230
+ * (depth-first, matching the order Claude Code itself would inline them) to
231
+ * `outEntries`. `visited` is the whole-read cycle guard (keyed by resolved
232
+ * real path, falling back to the lexical target for a skipped/unresolvable
233
+ * one); `depth` enforces the same import-recursion ceiling Claude Code uses.
234
+ */
235
+ async function collectImports(content, importingFileAbsPath, allowedRoots, visited, depth, outEntries) {
236
+ if (depth > MAX_IMPORT_DEPTH) return
237
+ for (const rawPath of extractImportPaths(content)) {
238
+ if (outEntries.length >= MAX_IMPORT_ENTRIES) return
239
+ const lexicalTarget = resolveImportTarget(rawPath, importingFileAbsPath)
240
+ // Import targets are confined to the same roots AND restricted to markdown
241
+ // memory files (the root files themselves are not) — see #6971. Resolve
242
+ // the target's identity FIRST (no stat/open/read yet) so a duplicate
243
+ // `@import` of an already-visited file — or a cycle back to one — hits
244
+ // the `visited` check and short-circuits BEFORE the read, instead of
245
+ // paying for a redundant stat/open/read only to discard it.
246
+ const { resolvedPath, skipEntry } = await resolveConfinedMemoryPath(lexicalTarget, allowedRoots, { requireMarkdownExt: true })
247
+ const key = resolvedPath || lexicalTarget
248
+ if (visited.has(key)) continue // cycle/dup guard — before any read
249
+ visited.add(key)
250
+ const entry = skipEntry ?? await readResolvedMemoryFile(resolvedPath)
251
+ outEntries.push({ ...entry, scope: 'import', importedFrom: importingFileAbsPath })
252
+ if (entry.exists && entry.content && !entry.skipped && !entry.error) {
253
+ await collectImports(entry.content, entry.path, allowedRoots, visited, depth + 1, outEntries)
254
+ }
255
+ }
256
+ }
257
+
258
+ /**
259
+ * File reading operations for the effective merged CLAUDE.md memory stack.
260
+ *
261
+ * @param {Function} sendFn - (ws, message) => void
262
+ * @param {Function} resolveSessionCwd - shared, cached CWD resolver (same one createReaderOps uses)
263
+ * @returns {Object} memory operation methods
264
+ */
265
+ export function createMemoryOps(sendFn, resolveSessionCwd) {
266
+ /**
267
+ * Resolve the effective merged CLAUDE.md memory stack for a session
268
+ * (#6864, epic #6760) — the SERVER-side read counterpart to `appendMemory`
269
+ * (#6861).
270
+ *
271
+ * Scopes, in Claude Code's own load/precedence order — see
272
+ * https://code.claude.com/docs/en/memory ("content is ordered from the
273
+ * filesystem root down to your working directory"; within one directory,
274
+ * CLAUDE.local.md is read right after that directory's CLAUDE.md):
275
+ * 1. global — ~/.claude/CLAUDE.md (loaded first, lowest precedence)
276
+ * 2. project — <sessionCwd>/CLAUDE.md
277
+ * 3. local — <sessionCwd>/CLAUDE.local.md (loaded last, highest precedence)
278
+ * Managed/enterprise policy memory is out of scope — chroxy has no managed-
279
+ * policy surface today. Chroxy also does not walk from the session cwd UP to
280
+ * the filesystem root the way the real CLI does (every intermediate
281
+ * directory's CLAUDE.md) — only the session cwd's own root files are read,
282
+ * matching this slice's explicit path-confinement requirement.
283
+ *
284
+ * Every path here is SERVER-chosen — the request carries no client-supplied
285
+ * path at all (mirrors `appendMemory`'s "target is chosen server-side"
286
+ * design), so there is no client-controlled traversal surface for the three
287
+ * root files. The ONLY variable input is @import references found INSIDE
288
+ * those files' own content, which are confined to the same two roots
289
+ * (session cwd, user's ~/.claude) via `readConfinedMemoryFile` AND restricted
290
+ * to markdown targets (`.md`/`.markdown`) — an import resolving outside both
291
+ * roots, or to a non-markdown file (e.g. `~/.claude/.credentials.json`), is
292
+ * reported (for provenance/transparency) with `skipped: true` and is never
293
+ * opened. #6971 added the markdown restriction so a malicious project
294
+ * CLAUDE.md can't `@import` a sensitive non-memory file that happens to sit
295
+ * under the ~/.claude allowed root.
296
+ *
297
+ * Also resolves the project's auto-generated MEMORY.md descriptor, keyed by
298
+ * the SAME per-cwd path encoding `resolveJsonlPath` uses for transcript
299
+ * storage (`encodeProjectPath` in jsonl-reader.js) — confirmed empirically
300
+ * against a live `~/.claude/projects/` tree to be keyed by the literal
301
+ * session cwd, not the git repository root (each worktree gets its own,
302
+ * separate memory directory).
303
+ */
304
+ async function readMemoryStack(ws, sessionCwd, requestId) {
305
+ const send = (payload) => sendFn(ws, requestId === undefined ? payload : { ...payload, requestId })
306
+
307
+ if (!sessionCwd) {
308
+ send({ type: 'memory_stack_result', entries: [], memoryFile: null, error: 'Memory is not available in this mode' })
309
+ return
310
+ }
311
+
312
+ let cwdReal
313
+ try {
314
+ cwdReal = await resolveSessionCwd(sessionCwd)
315
+ } catch (err) {
316
+ send({ type: 'memory_stack_result', entries: [], memoryFile: null, error: err.message || 'Failed to resolve session directory' })
317
+ return
318
+ }
319
+
320
+ let claudeHomeReal
321
+ try {
322
+ claudeHomeReal = await realpathOfDeepestAncestor(resolve(homedir(), '.claude'))
323
+ } catch {
324
+ claudeHomeReal = normalize(resolve(homedir(), '.claude'))
325
+ }
326
+
327
+ const allowedRoots = [cwdReal, claudeHomeReal]
328
+ const visited = new Set()
329
+ const entries = []
330
+
331
+ const roots = [
332
+ { scope: 'global', lexicalPath: resolve(claudeHomeReal, 'CLAUDE.md') },
333
+ { scope: 'project', lexicalPath: resolve(cwdReal, 'CLAUDE.md') },
334
+ { scope: 'local', lexicalPath: resolve(cwdReal, 'CLAUDE.local.md') },
335
+ ]
336
+
337
+ for (const { scope, lexicalPath } of roots) {
338
+ const entry = await readConfinedMemoryFile(lexicalPath, allowedRoots)
339
+ visited.add(entry.path || lexicalPath)
340
+ entries.push({ ...entry, scope, importedFrom: null })
341
+ if (entry.exists && entry.content && !entry.skipped && !entry.error) {
342
+ await collectImports(entry.content, entry.path, allowedRoots, visited, 1, entries)
343
+ }
344
+ }
345
+
346
+ // Auto-generated project memory (MEMORY.md) — restricted to the
347
+ // ~/.claude root only (it never lives under the session cwd).
348
+ const encoded = encodeProjectPath(cwdReal)
349
+ const memoryFilePath = resolve(claudeHomeReal, 'projects', encoded, 'memory', 'MEMORY.md')
350
+ const memoryFile = await readConfinedMemoryFile(memoryFilePath, [claudeHomeReal])
351
+
352
+ send({ type: 'memory_stack_result', entries, memoryFile, error: null })
353
+ }
354
+
355
+ return {
356
+ readMemory: readMemoryStack,
357
+ }
358
+ }