@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,418 @@
1
+ // Worktree garbage-collector core (#5158).
2
+ //
3
+ // Reclaims git worktrees that were created + locked by an agent/orchestrator
4
+ // (e.g. Claude Code's `.claude/worktrees/agent-XXX`, locked with a reason like
5
+ // `claude agent agent-XXX (pid 45492)`) and then orphaned when that process
6
+ // died without cleaning up. Such locks survive the process forever, so without
7
+ // a reaper they pile up across runs (the issue observed 162 worktrees / ~15 GB
8
+ // in one repo).
9
+ //
10
+ // Safety contract (do NOT relax — these are the guardrails from #5158):
11
+ // - Never `git worktree remove --force`. A worktree with uncommitted /
12
+ // untracked / gitignored content is preserved (skipped), never deleted —
13
+ // `git worktree remove` (no --force) still deletes the whole directory
14
+ // INCLUDING gitignored files (node_modules, build/, a local .env), so the
15
+ // clean check counts ignored entries as not-clean (#5244).
16
+ // - Only auto-unlock locks held by a VERIFIED-DEAD pid. A live pid, or a
17
+ // lock whose reason has no parseable pid, is skipped (could be the user's
18
+ // own deliberate lock).
19
+ // - Never touch the main worktree (the primary checkout).
20
+ // - Removing a worktree only deletes its working directory + admin refs; it
21
+ // never deletes commits or branches. We still log a manifest of what was
22
+ // reclaimed.
23
+ //
24
+ // This module is pure + dependency-injected (git exec, process.kill, fs) so it
25
+ // is fully testable against real temp repos without poking the real home dir.
26
+
27
+ import { execFileSync } from 'node:child_process'
28
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
29
+ import { isAbsolute, join as joinPath, resolve as resolvePath } from 'node:path'
30
+ import { chroxyWorktreeRepoPath } from '@chroxy/protocol/project'
31
+ import { GIT } from './git.js'
32
+
33
+ // #5706: absolute-age fallback for the PID-liveness check. A dead agent's pid
34
+ // can be RECYCLED by an unrelated process after uptime/PID reuse — then
35
+ // `isPidAlive` reports "live", GC skips the orphaned worktree forever, and the
36
+ // disk slowly fills. The fallback reclaims a lock whose pid LOOKS alive but
37
+ // whose worktree mtime is older than `maxLockAgeMs` (treating the pid as
38
+ // recycled) — still subject to the clean-tree guard, so no uncommitted/ignored
39
+ // content is ever deleted.
40
+ //
41
+ // DEFAULT IS 0 (DISABLED): opt-in via `config.worktreeGc.maxLockAgeMs`. It's
42
+ // off by default because the age signal is imperfect — directory mtime bumps
43
+ // only on TOP-LEVEL entry add/remove (and top-level git ops), NOT on in-place or
44
+ // nested-subdir edits. So a genuinely-live, clean, long-running agent that only
45
+ // touches existing/nested files could read "stale" and have its working dir
46
+ // reclaimed out from under it (no committed-work loss thanks to the clean-tree
47
+ // guard, but a disruptive mid-run rug-pull). Operators who hit the recycled-pid
48
+ // disk leak set a generous threshold (e.g. 14–30 days, well beyond any real
49
+ // agent-session lifetime); the clean-tree guard remains the hard safety net.
50
+ const DEFAULT_MAX_LOCK_AGE_MS = 0
51
+
52
+ /**
53
+ * Existence check for a pid without sending a real signal.
54
+ * Signal 0 only probes for the process; EPERM means it exists but we can't
55
+ * signal it (still alive), ESRCH means it's gone.
56
+ */
57
+ export function isPidAlive(pid, kill = process.kill) {
58
+ if (!Number.isInteger(pid) || pid <= 0) return false
59
+ try {
60
+ kill(pid, 0)
61
+ return true
62
+ } catch (err) {
63
+ return err && err.code === 'EPERM'
64
+ }
65
+ }
66
+
67
+ /**
68
+ * Extract a pid from a worktree lock reason. Handles the agent format
69
+ * `... (pid 45492)` and a looser `pid: 45492` / `pid 45492` fallback.
70
+ * Returns a positive integer or null when no pid is present.
71
+ */
72
+ export function parsePid(reason) {
73
+ if (!reason || typeof reason !== 'string') return null
74
+ const m = /\(pid\s+(\d+)\)/i.exec(reason) || /\bpid[\s:=]+(\d+)/i.exec(reason)
75
+ if (!m) return null
76
+ const pid = Number(m[1])
77
+ return Number.isInteger(pid) && pid > 0 ? pid : null
78
+ }
79
+
80
+ /**
81
+ * Parse `git worktree list --porcelain` output into structured entries.
82
+ * The first entry is always the main worktree. `locked`/`prunable` may carry
83
+ * an inline reason (git >= ~2.36); older git emits the bare keyword, in which
84
+ * case the lock reason is read from the admin file as a fallback.
85
+ */
86
+ export function parseWorktreeList(porcelain) {
87
+ const entries = []
88
+ let cur = null
89
+ const flush = () => { if (cur) entries.push(cur) }
90
+ for (const raw of String(porcelain == null ? '' : porcelain).split('\n')) {
91
+ const line = raw.replace(/\r$/, '')
92
+ if (line.startsWith('worktree ')) {
93
+ flush()
94
+ cur = { path: line.slice('worktree '.length), locked: false, lockReason: '', prunable: false, detached: false }
95
+ } else if (!cur) {
96
+ continue
97
+ } else if (line === 'bare') {
98
+ cur.bare = true
99
+ } else if (line.startsWith('HEAD ')) {
100
+ cur.head = line.slice('HEAD '.length)
101
+ } else if (line.startsWith('branch ')) {
102
+ cur.branch = line.slice('branch '.length)
103
+ } else if (line === 'detached') {
104
+ cur.detached = true
105
+ } else if (line === 'locked') {
106
+ cur.locked = true
107
+ } else if (line.startsWith('locked ')) {
108
+ cur.locked = true
109
+ cur.lockReason = line.slice('locked '.length)
110
+ } else if (line === 'prunable') {
111
+ cur.prunable = true
112
+ } else if (line.startsWith('prunable ')) {
113
+ cur.prunable = true
114
+ cur.prunableReason = line.slice('prunable '.length)
115
+ }
116
+ }
117
+ flush()
118
+ return entries
119
+ }
120
+
121
+ /**
122
+ * Fallback lock-reason reader for older git that omits the inline reason in
123
+ * porcelain output. A linked worktree's `<path>/.git` is a file containing
124
+ * `gitdir: <maindir>/.git/worktrees/<id>`; the lock reason lives in
125
+ * `<that dir>/locked`. Returns '' when unavailable.
126
+ */
127
+ export function readLockReasonFromAdmin(worktreePath, deps = {}) {
128
+ const { exists = existsSync, read = readFileSync } = deps
129
+ try {
130
+ const dotGit = `${worktreePath}/.git`
131
+ if (!exists(dotGit)) return ''
132
+ const pointer = String(read(dotGit, 'utf8')).trim()
133
+ const m = /^gitdir:\s*(.+)$/m.exec(pointer)
134
+ if (!m) return ''
135
+ // git may write the gitdir pointer as a path RELATIVE to the worktree dir
136
+ // (e.g. with extensions.relativeWorktrees); resolve it against worktreePath
137
+ // so we read the right `locked` file rather than one off the cwd.
138
+ const gitdir = m[1].trim()
139
+ const adminDir = isAbsolute(gitdir) ? gitdir : resolvePath(worktreePath, gitdir)
140
+ const lockedFile = `${adminDir}/locked`
141
+ if (!exists(lockedFile)) return ''
142
+ return String(read(lockedFile, 'utf8')).trim()
143
+ } catch {
144
+ return ''
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Decide what to do with every linked worktree of `repoPath`. Returns a plan:
150
+ * { repo, error?, items: [{ path, action, ... }] }
151
+ * where action is one of:
152
+ * - 'remove' : dead-pid lock, dir present, clean → unlock + `worktree remove` (no --force)
153
+ * - 'prune' : dir gone (dead-pid lock or unlocked) → unlock if needed + `worktree prune`
154
+ * - 'skip' : anything we must not touch (live pid, dirty, no pid, unlocked-present, main)
155
+ *
156
+ * Pure aside from the injected `git`/`kill`/`exists` seams.
157
+ */
158
+ export function planRepoGc(repoPath, deps = {}) {
159
+ const {
160
+ git = (cwd, args) => execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' }),
161
+ kill = process.kill,
162
+ exists = existsSync,
163
+ readLockReason = (wtPath) => readLockReasonFromAdmin(wtPath),
164
+ // #5706: age-fallback seams. `now`/`mtimeMs` are injectable for tests.
165
+ // `maxLockAgeMs` defaults to 30d; 0 (or negative) disables the fallback.
166
+ now = () => Date.now(),
167
+ mtimeMs = (p) => { try { return statSync(p).mtimeMs } catch { return null } },
168
+ maxLockAgeMs = DEFAULT_MAX_LOCK_AGE_MS,
169
+ } = deps
170
+
171
+ let porcelain
172
+ try {
173
+ porcelain = git(repoPath, ['worktree', 'list', '--porcelain'])
174
+ } catch (err) {
175
+ return { repo: repoPath, error: (err && err.message) || String(err), items: [] }
176
+ }
177
+
178
+ const entries = parseWorktreeList(porcelain)
179
+ const items = []
180
+
181
+ entries.forEach((e, i) => {
182
+ if (i === 0) return // main worktree — never GC the primary checkout
183
+ const dirGone = e.prunable || !exists(e.path)
184
+
185
+ if (e.locked) {
186
+ const reason = e.lockReason || readLockReason(e.path) || ''
187
+ const pid = parsePid(reason)
188
+ if (pid == null) {
189
+ items.push({ path: e.path, action: 'skip', skipReason: 'locked with no pid in reason (not an abandoned agent worktree)', lockReason: reason })
190
+ return
191
+ }
192
+ // pid liveness, with the #5706 absolute-age fallback: a "live" pid whose
193
+ // worktree has been untouched longer than maxLockAgeMs is treated as a
194
+ // recycled pid (the original agent is long gone) so the orphan can be
195
+ // reclaimed instead of leaking forever.
196
+ let pidNote = 'lock held by dead pid'
197
+ if (isPidAlive(pid, kill)) {
198
+ const m = maxLockAgeMs > 0 ? mtimeMs(e.path) : null
199
+ const ageMs = m != null ? now() - m : null
200
+ if (ageMs == null || ageMs <= maxLockAgeMs) {
201
+ items.push({ path: e.path, action: 'skip', skipReason: `locked by a live process (pid ${pid})`, pid, lockReason: reason })
202
+ return
203
+ }
204
+ // pid looks alive but the tree is stale → recycled pid; reclaim.
205
+ const ageDays = Math.round(ageMs / 86_400_000)
206
+ pidNote = `pid ${pid} appears live but worktree untouched ${ageDays}d — treating as a recycled pid (#5706)`
207
+ }
208
+ // reclaimable (dead pid, or recycled-pid stale), subject to the clean-tree guard.
209
+ if (dirGone) {
210
+ items.push({ path: e.path, action: 'prune', pid, lockReason: reason, reason: `directory gone; ${pidNote}`, locked: true })
211
+ return
212
+ }
213
+ const clean = isClean(git, e.path)
214
+ if (clean === null) {
215
+ items.push({ path: e.path, action: 'skip', skipReason: 'could not determine working-tree state; left untouched for safety', pid, lockReason: reason })
216
+ return
217
+ }
218
+ if (!clean) {
219
+ items.push({ path: e.path, action: 'skip', skipReason: 'has uncommitted/untracked/gitignored content (preserved)', pid, lockReason: reason })
220
+ return
221
+ }
222
+ items.push({ path: e.path, action: 'remove', pid, lockReason: reason, reason: `clean worktree; ${pidNote}`, locked: true })
223
+ return
224
+ }
225
+
226
+ // Not locked.
227
+ if (dirGone) {
228
+ items.push({ path: e.path, action: 'prune', reason: 'directory gone (stale admin ref)', locked: false })
229
+ return
230
+ }
231
+ items.push({ path: e.path, action: 'skip', skipReason: 'present and unlocked (not an abandoned agent worktree)' })
232
+ })
233
+
234
+ return { repo: repoPath, items }
235
+ }
236
+
237
+ /**
238
+ * `git -C <worktree> status --porcelain --ignored` → clean? null when it can't
239
+ * be run. The `--ignored` flag is load-bearing (#5244): `git worktree remove`
240
+ * (run here WITHOUT --force) deletes the entire worktree directory including
241
+ * gitignored content — node_modules, build artifacts, a local `.env` — so a
242
+ * worktree that reads clean by tracked status alone can still hold precious
243
+ * un-versioned files. Treating any ignored entry (`!! ...`) as not-clean keeps
244
+ * such worktrees in the skip set instead of silently deleting their contents.
245
+ */
246
+ function isClean(git, worktreePath) {
247
+ try {
248
+ return git(worktreePath, ['status', '--porcelain', '--ignored']).trim().length === 0
249
+ } catch {
250
+ return null
251
+ }
252
+ }
253
+
254
+
255
+ /**
256
+ * #5859 (audit P1-7): boot-time sweep of ORPHANED chroxy session worktrees.
257
+ *
258
+ * Unlike the agent worktrees this module's reaper handles, chroxy's OWN session
259
+ * worktrees (`~/.chroxy/worktrees/<sessionId>`, created `git worktree add
260
+ * --detach`, NO lock) are never reclaimed by the lock/dead-pid reaper. When a
261
+ * session vanishes without a clean destroy (SIGKILL, crash, or a dropped
262
+ * state file) its worktree dir leaks forever.
263
+ *
264
+ * Removes a worktree dir ONLY when BOTH hold:
265
+ * - its basename (the sessionId) is NOT in `liveSessionIds` (the set
266
+ * restoreState rebuilt) — so a live session's worktree is never touched, AND
267
+ * - the tree is CLEAN including ignored files — the same hard guard as the
268
+ * reaper (`git worktree remove` without --force still deletes gitignored
269
+ * content, so any uncommitted/untracked/ignored work means SKIP).
270
+ * A dirty orphan, or one whose repo/clean-state can't be determined, is skipped
271
+ * and reported. Never throws; never uses --force.
272
+ *
273
+ * Pure + dependency-injected.
274
+ *
275
+ * @param {object} args
276
+ * @param {string} args.worktreeBase - e.g. ~/.chroxy/worktrees
277
+ * @param {Set<string>} args.liveSessionIds - currently-live session ids (off-limits)
278
+ * @param {object} [args.deps] - { git, readdir, exists }
279
+ * @returns {{ removed: string[], skippedDirty: object[], skippedError: object[], scanned: number }}
280
+ */
281
+ export function sweepOrphanChroxyWorktrees({ worktreeBase, liveSessionIds, deps = {} } = {}) {
282
+ const {
283
+ git = (cwd, args) => execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' }),
284
+ readdir = (p) => readdirSync(p, { withFileTypes: true }),
285
+ exists = existsSync,
286
+ } = deps
287
+ const report = { removed: [], skippedDirty: [], skippedError: [], scanned: 0 }
288
+ if (!worktreeBase || !exists(worktreeBase)) return report
289
+ const live = liveSessionIds instanceof Set ? liveSessionIds : new Set(liveSessionIds || [])
290
+ let entries
291
+ try { entries = readdir(worktreeBase) } catch (err) { report.skippedError.push({ path: worktreeBase, error: (err && err.message) || String(err) }); return report }
292
+ for (const ent of entries) {
293
+ if (!ent || typeof ent.isDirectory !== 'function' || !ent.isDirectory()) continue
294
+ const id = ent.name
295
+ // Defense-in-depth: chroxy session ids are 32 lowercase hex (matching the
296
+ // /^[a-f0-9]{32}$/ constraint in session-manager.js). A dir under the base
297
+ // whose name isn't that shape was never created by chroxy (e.g. a user-placed
298
+ // directory) — never a removal candidate, even if it somehow looked clean.
299
+ if (!/^[a-f0-9]{32}$/.test(id)) continue
300
+ if (live.has(id)) continue // owned by a live session — never touch
301
+ report.scanned++
302
+ const wtPath = joinPath(worktreeBase, id)
303
+ const clean = isClean(git, wtPath)
304
+ if (clean !== true) {
305
+ report.skippedDirty.push({ path: wtPath, reason: clean === null ? 'status-unknown' : 'dirty' })
306
+ continue
307
+ }
308
+ const repo = chroxyWorktreeRepoPath(wtPath)
309
+ if (!repo) { report.skippedError.push({ path: wtPath, error: 'repo-unrecoverable' }); continue }
310
+ try {
311
+ git(repo, ['worktree', 'remove', wtPath]) // NO --force; clean-checked above
312
+ report.removed.push(wtPath)
313
+ } catch (err) {
314
+ report.skippedError.push({ path: wtPath, error: (err && err.message) || String(err) })
315
+ }
316
+ }
317
+ return report
318
+ }
319
+
320
+ /**
321
+ * Execute a plan's reclaimable items. Returns per-item results
322
+ * ({ path, action, ok, error? }). `git worktree remove` is run WITHOUT
323
+ * --force; the plan already excluded dirty trees, so a clean removal succeeds
324
+ * and a surprise-dirty one fails loudly (and is reported) rather than nuking
325
+ * changes. A single `git worktree prune` reclaims all dir-gone admin refs.
326
+ */
327
+ export function applyPlan(repoPath, plan, deps = {}) {
328
+ const { git = (cwd, args) => execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' }) } = deps
329
+ const results = []
330
+ const pruneItems = []
331
+ const unlockErrors = new Map() // item.path -> error message when its pre-prune unlock failed
332
+
333
+ for (const item of plan.items) {
334
+ if (item.action === 'remove') {
335
+ let unlocked = false
336
+ try {
337
+ if (item.locked) { git(repoPath, ['worktree', 'unlock', item.path]); unlocked = true }
338
+ git(repoPath, ['worktree', 'remove', item.path]) // NO --force
339
+ results.push({ path: item.path, action: 'remove', ok: true })
340
+ } catch (err) {
341
+ // #5245 — if we unlocked but the remove then failed (e.g. the tree went
342
+ // dirty between plan and apply, so `worktree remove` refuses), re-lock
343
+ // with the original reason so a failed reclaim leaves the worktree's
344
+ // lock state — and its dead-pid provenance — exactly as we found it.
345
+ // Best-effort: a re-lock failure must not mask the original error.
346
+ if (unlocked) {
347
+ try {
348
+ const lockArgs = item.lockReason
349
+ ? ['worktree', 'lock', '--reason', item.lockReason, item.path]
350
+ : ['worktree', 'lock', item.path]
351
+ git(repoPath, lockArgs)
352
+ } catch { /* best-effort re-lock */ }
353
+ }
354
+ results.push({ path: item.path, action: 'remove', ok: false, error: (err && err.message) || String(err) })
355
+ }
356
+ } else if (item.action === 'prune') {
357
+ // A locked, dir-gone worktree must be unlocked before prune will reclaim
358
+ // it. If the unlock fails the entry stays locked and prune cannot reclaim
359
+ // it, so record the failure and report this item as not-ok rather than
360
+ // claiming success off the back of a prune that skipped it.
361
+ if (item.locked) {
362
+ try {
363
+ git(repoPath, ['worktree', 'unlock', item.path])
364
+ } catch (err) {
365
+ unlockErrors.set(item.path, (err && err.message) || String(err))
366
+ }
367
+ }
368
+ pruneItems.push(item)
369
+ }
370
+ }
371
+
372
+ if (pruneItems.length > 0) {
373
+ let pruneError = null
374
+ try {
375
+ git(repoPath, ['worktree', 'prune'])
376
+ } catch (err) {
377
+ pruneError = (err && err.message) || String(err)
378
+ }
379
+
380
+ // #5246: verify per-entry that prune actually reclaimed the worktree. The
381
+ // plan classifies an unlocked worktree as 'prune' when `dirGone` is true,
382
+ // and `dirGone` includes `!exists(e.path)` — but `existsSync` returns false
383
+ // on ANY stat error (an unmounted/temporarily-unavailable mount, a TOCTOU
384
+ // race), not only genuine absence. `git worktree prune` correctly leaves a
385
+ // still-present worktree intact, so reporting ok:true off the back of the
386
+ // single global prune would over-count reclamations. Re-list the worktrees
387
+ // and only claim success for items whose admin ref is genuinely gone.
388
+ let remaining = null
389
+ if (!pruneError) {
390
+ try {
391
+ remaining = new Set(parseWorktreeList(git(repoPath, ['worktree', 'list', '--porcelain'])).map(e => e.path))
392
+ } catch {
393
+ // Can't verify — fall back to best-effort (the prune call succeeded).
394
+ remaining = null
395
+ }
396
+ }
397
+
398
+ for (const item of pruneItems) {
399
+ const unlockErr = unlockErrors.get(item.path)
400
+ if (unlockErr) {
401
+ results.push({ path: item.path, action: 'prune', ok: false, error: `unlock failed (entry still locked): ${unlockErr}` })
402
+ } else if (pruneError) {
403
+ results.push({ path: item.path, action: 'prune', ok: false, error: pruneError })
404
+ } else if (remaining && remaining.has(item.path)) {
405
+ results.push({
406
+ path: item.path,
407
+ action: 'prune',
408
+ ok: false,
409
+ error: 'still present after prune (not reclaimed) — a transient stat failure likely misclassified a present worktree as dir-gone',
410
+ })
411
+ } else {
412
+ results.push({ path: item.path, action: 'prune', ok: true })
413
+ }
414
+ }
415
+ }
416
+
417
+ return results
418
+ }
@@ -0,0 +1,168 @@
1
+ // Opt-in worktree auto-reaper (#5158).
2
+ //
3
+ // When `config.worktreeGc.autoReap` is true, the server reclaims orphaned,
4
+ // dead-pid-locked agent worktrees once on startup. It reuses the GC core
5
+ // (planRepoGc/applyPlan), so the full safety contract holds unchanged: only
6
+ // clean worktrees locked by a verified-dead pid (plus dir-gone stale refs) are
7
+ // reclaimed, never --force, never the main worktree, never a dirty/live one.
8
+ //
9
+ // Default is OFF. The manual `chroxy worktree gc` CLI (dry-run by default) is
10
+ // always available regardless of this setting.
11
+ //
12
+ // Scope mirrors the CLI: the resolved repo set (config.repos ∪ auto-discover
13
+ // under config.controlRoomRoot). To keep an opt-in startup sweep from starving
14
+ // the freshly-booted server's event loop, the orchestrator yields between
15
+ // repos (each repo's git calls are still synchronous, but bounded).
16
+
17
+ import { resolveRepoSet } from './control-room/repo-set.js'
18
+ import { planRepoGc, applyPlan } from './worktree-gc.js'
19
+
20
+ // #5326 (WP-5.4): how often the periodic auto-reaper re-sweeps after the
21
+ // boot sweep. 30 min is a balance — short enough that a long-running daemon
22
+ // reclaims mid-run agent worktrees without a restart, long enough that the
23
+ // (synchronous-per-repo) git scans don't add meaningful steady-state load.
24
+ const DEFAULT_REAP_INTERVAL_MS = 30 * 60 * 1000
25
+
26
+ /**
27
+ * Reap one repo into the running summary. Sync (the GC core uses execFileSync).
28
+ */
29
+ function reapOneRepo(repoPath, summary, planDeps) {
30
+ const plan = planRepoGc(repoPath, planDeps)
31
+ if (plan.error) {
32
+ summary.errors.push({ repo: repoPath, error: plan.error })
33
+ return
34
+ }
35
+ const reclaimable = plan.items.filter((it) => it.action === 'remove' || it.action === 'prune')
36
+ summary.skipped += plan.items.filter((it) => it.action === 'skip').length
37
+ if (reclaimable.length === 0) return
38
+ const results = applyPlan(repoPath, { items: reclaimable }, planDeps)
39
+ for (const res of results) {
40
+ if (res.ok) {
41
+ summary.reclaimed += 1
42
+ summary.removed.push(res.path)
43
+ } else {
44
+ summary.failed += 1
45
+ summary.errors.push({ repo: repoPath, path: res.path, error: res.error })
46
+ }
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Reap a set of repos. `repos` is `[{ name, path }]`. Yields to the event loop
52
+ * between repos so a large sweep doesn't block a freshly-booted server.
53
+ * Returns a manifest summary. Pure aside from the injected GC seams (planDeps).
54
+ */
55
+ export async function reapWorktrees({ repos = [], planDeps = {}, yieldFn } = {}) {
56
+ const summary = { repos: repos.length, reclaimed: 0, failed: 0, skipped: 0, removed: [], errors: [] }
57
+ const yieldToLoop = yieldFn || (() => new Promise((resolve) => setImmediate(resolve)))
58
+ for (const r of repos) {
59
+ await yieldToLoop()
60
+ reapOneRepo(r.path, summary, planDeps)
61
+ }
62
+ return summary
63
+ }
64
+
65
+ /**
66
+ * Startup entry point. No-op (returns null) unless `config.worktreeGc.autoReap`
67
+ * is true. Resolves the repo set the same way the CLI does, reaps, and logs a
68
+ * manifest. Best-effort: callers should fire-and-forget and not let a failure
69
+ * here affect boot.
70
+ *
71
+ * @param {object} config - merged server config
72
+ * @param {{ info: Function, warn: Function }} log - server logger
73
+ * @param {object} [deps] - test seams: resolveRepoSet, repoSetSeams, planDeps, yieldFn
74
+ */
75
+ export async function maybeAutoReapWorktrees(config, log, deps = {}) {
76
+ if (!config || !config.worktreeGc || config.worktreeGc.autoReap !== true) return null
77
+
78
+ const resolve = deps.resolveRepoSet || resolveRepoSet
79
+ let repos
80
+ try {
81
+ repos = resolve({
82
+ repos: config.repos,
83
+ root: config.controlRoomRoot,
84
+ ...(deps.repoSetSeams || {}),
85
+ })
86
+ } catch (err) {
87
+ log.warn(`worktree auto-reap: repo discovery failed: ${(err && err.message) || err}`)
88
+ return null
89
+ }
90
+
91
+ // #5706: pass the configured absolute-age fallback through to the GC core.
92
+ // A test's `deps.planDeps` still wins (spread last) so seams override config.
93
+ const cfgMaxAge = config.worktreeGc.maxLockAgeMs
94
+ const planDeps = {
95
+ ...(Number.isFinite(cfgMaxAge) && cfgMaxAge >= 0 ? { maxLockAgeMs: cfgMaxAge } : {}),
96
+ ...(deps.planDeps || {}),
97
+ }
98
+ const summary = await reapWorktrees({ repos, planDeps, yieldFn: deps.yieldFn })
99
+
100
+ const base = `worktree auto-reap: reclaimed ${summary.reclaimed} worktree(s) across ${summary.repos} repo(s); ${summary.skipped} preserved (live/dirty/unknown)`
101
+ // Warn whenever anything went wrong — both per-item failures (counted in
102
+ // `failed`) and repo-level discovery/plan errors (recorded in `errors`
103
+ // without incrementing `failed`). Otherwise an unscannable repo would log a
104
+ // misleading "nothing to reclaim" info line and hide the failure.
105
+ if (summary.failed > 0 || summary.errors.length > 0) {
106
+ log.warn(`${base}; ${summary.failed} failed, ${summary.errors.length} error(s)`)
107
+ for (const e of summary.errors) {
108
+ log.warn(` - ${e.path || e.repo}: ${e.error}`)
109
+ }
110
+ } else if (summary.reclaimed > 0) {
111
+ log.info(base)
112
+ } else {
113
+ log.info('worktree auto-reap: nothing to reclaim')
114
+ }
115
+ return summary
116
+ }
117
+
118
+ /**
119
+ * #5326 (WP-5.4): start the worktree auto-reaper for the lifetime of the
120
+ * daemon. Runs once immediately (the original boot sweep) and then on a
121
+ * recurring interval so a long-running server reclaims agent worktrees
122
+ * created MID-RUN — previously the sweep ran once at boot only, so a worktree
123
+ * orphaned an hour into a session was never reclaimed without a restart.
124
+ *
125
+ * No-op (returns null) unless `config.worktreeGc.autoReap === true`. Each sweep
126
+ * is fire-and-forget: a failure is logged and never propagates (so a transient
127
+ * git error can't tear down the interval or the daemon). The interval is
128
+ * `unref()`'d so it never keeps the process alive on its own.
129
+ *
130
+ * @param {object} config - merged server config
131
+ * @param {{ info: Function, warn: Function }} log - server logger
132
+ * @param {object} [deps] - test seams: run, setIntervalFn, plus maybeAutoReapWorktrees deps
133
+ * @returns {ReturnType<typeof setInterval>|null} the interval handle (for clearInterval on shutdown), or null when disabled
134
+ */
135
+ export function startPeriodicAutoReap(config, log, deps = {}) {
136
+ if (!config || !config.worktreeGc || config.worktreeGc.autoReap !== true) return null
137
+
138
+ const run = deps.run || maybeAutoReapWorktrees
139
+ // Reentrancy guard: if a sweep runs longer than the interval (e.g. a tiny
140
+ // reapIntervalMs over a huge repo set), skip the tick rather than letting two
141
+ // sweeps run concurrently. Each sweep already builds its own summary and the
142
+ // GC core re-plans live, so an overlap wouldn't corrupt state — but skipping
143
+ // is cheaper and clearer than racing two scans (#5363 review).
144
+ let sweeping = false
145
+ const sweep = () => {
146
+ if (sweeping) {
147
+ log.info('worktree auto-reaper: previous sweep still running, skipping this tick')
148
+ return
149
+ }
150
+ sweeping = true
151
+ Promise.resolve()
152
+ .then(() => run(config, log, deps))
153
+ .catch((err) => log.warn(`worktree auto-reaper failed: ${(err && err.message) || err}`))
154
+ .finally(() => { sweeping = false })
155
+ }
156
+
157
+ // Boot sweep — same behavior as before this WP.
158
+ sweep()
159
+
160
+ const configured = config.worktreeGc.reapIntervalMs
161
+ const intervalMs = Number.isFinite(configured) && configured > 0
162
+ ? configured
163
+ : DEFAULT_REAP_INTERVAL_MS
164
+ const setIntervalFn = deps.setIntervalFn || setInterval
165
+ const timer = setIntervalFn(sweep, intervalMs)
166
+ if (timer && typeof timer.unref === 'function') timer.unref()
167
+ return timer
168
+ }