@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,685 @@
1
+ /**
2
+ * Control Room v2 (#5173) — host/repo git + gh survey + verdict engine.
3
+ *
4
+ * Given the resolved repo set (see `repo-set.js`), produces one `RepoStatus`
5
+ * per repo plus aggregate `summary` counts, shaped to the A1
6
+ * `host_status_snapshot` wire contract (minus the `type` field, which the WS
7
+ * handler in #5174 adds). The result conforms exactly to
8
+ * `ServerHostStatusSnapshotSchema` from `@chroxy/protocol`.
9
+ *
10
+ * Every external interaction is injectable so tests never touch real git / gh
11
+ * or the user's home directory:
12
+ * - `_execFile(file, args, opts)` — async, resolves `{ stdout, stderr }`
13
+ * (the promisified `child_process.execFile` shape). Rejected promises are
14
+ * tolerated per-command.
15
+ * - `_now()` — returns a `Date` (defaults to `new Date()`), for deterministic
16
+ * verdict/threshold tests.
17
+ * - `_readFile(path)` — async, resolves a string (for `.claude/settings.json`
18
+ * attribution detection).
19
+ *
20
+ * Verdict classification (`'live' | 'investigate' | 'abandoned' | 'recent' |
21
+ * 'onboarded'`):
22
+ * - live — a live agent is present (chroxy session bound to the repo,
23
+ * or the dirty-tree-recently-touched heuristic).
24
+ * - investigate — an excessive worktree count (likely a leak).
25
+ * - recent — dirty tree touched within the recent window, not live.
26
+ * - abandoned — dirty tree last touched long ago, not live.
27
+ * - onboarded — clean tree on the pull model.
28
+ */
29
+
30
+ import { execFile } from 'child_process'
31
+ import { promisify } from 'util'
32
+ import { readFile } from 'fs/promises'
33
+ import { join } from 'path'
34
+ import { resolveRepoSet } from './repo-set.js'
35
+ import { getErrorMessage } from '../utils/error-message.js'
36
+ import { DEFAULT_CONCURRENCY, EXEC_TIMEOUT_MS } from './constants.js'
37
+
38
+ const execFileAsync = promisify(execFile)
39
+
40
+ /**
41
+ * stdout cap for every git/gh probe (#5241). Node's execFile default is 1 MB,
42
+ * and overflow REJECTS — which `tryExec` turns into `null`, mislabelling a real
43
+ * repo with a large dirty/untracked tree (>1 MB of `git status --porcelain`) as
44
+ * "not a git repo". 16 MB is far beyond any realistic porcelain output.
45
+ */
46
+ const EXEC_MAX_BUFFER = 16 * 1024 * 1024
47
+
48
+ /**
49
+ * Cap for `gh pr list` (#5240). `gh pr list` defaults to 30, silently capping
50
+ * the open-PR count AND the CI/review rollup. 200 covers even bot-heavy repos;
51
+ * a repo past it is undercounted, but far less often than at the 30 default.
52
+ */
53
+ const GH_PR_LIST_LIMIT = 200
54
+
55
+ /**
56
+ * Default verdict thresholds. All durations are in milliseconds.
57
+ * - liveMs — a dirty tree touched more recently than this is treated
58
+ * as having a live agent (heuristic). Default 15 min.
59
+ * - recentMs — a dirty tree touched more recently than this (but not
60
+ * live) is `recent`; older than this is `abandoned`.
61
+ * Default ~3 days.
62
+ * - worktreeLeak — a worktree count at or above this is `investigate`.
63
+ */
64
+ export const DEFAULT_THRESHOLDS = {
65
+ liveMs: 15 * 60 * 1000,
66
+ recentMs: 3 * 24 * 60 * 60 * 1000,
67
+ worktreeLeak: 4,
68
+ }
69
+
70
+ /**
71
+ * Run a git/gh command, tolerating failure. Resolves trimmed stdout on success
72
+ * or `null` on any error (non-zero exit, missing binary, etc.).
73
+ *
74
+ * @param {Function} execFn - promisified execFile seam.
75
+ * @param {string} file - executable (e.g. 'git', 'gh').
76
+ * @param {string[]} args - argument vector.
77
+ * @param {string} cwd - working directory.
78
+ * @returns {Promise<string|null>} trimmed stdout, or null on error.
79
+ */
80
+ async function tryExec(execFn, file, args, cwd) {
81
+ try {
82
+ const { stdout } = await execFn(file, args, { cwd, maxBuffer: EXEC_MAX_BUFFER, timeout: EXEC_TIMEOUT_MS })
83
+ return typeof stdout === 'string' ? stdout.trim() : ''
84
+ } catch {
85
+ return null
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Parse `git status --porcelain` output into a tree summary.
91
+ *
92
+ * Porcelain v1 lines are `XY <path>` where X is the index (staged) status and Y
93
+ * is the working-tree (unstaged) status. `??` marks an untracked file. A file
94
+ * may be counted in both staged and modified when it has changes in both the
95
+ * index and the working tree (e.g. `MM`).
96
+ *
97
+ * @param {string} porcelain - raw `git status --porcelain` stdout.
98
+ * @returns {{ state: 'clean'|'dirty', untracked: number, modified: number, staged: number }}
99
+ */
100
+ export function parseTree(porcelain) {
101
+ const lines = (porcelain || '')
102
+ .split('\n')
103
+ .map(l => l.replace(/\r$/, ''))
104
+ .filter(l => l.length > 0)
105
+
106
+ let untracked = 0
107
+ let modified = 0
108
+ let staged = 0
109
+
110
+ for (const line of lines) {
111
+ if (line.startsWith('??')) {
112
+ untracked++
113
+ continue
114
+ }
115
+ const x = line[0]
116
+ const y = line[1]
117
+ if (x && x !== ' ' && x !== '?') staged++
118
+ if (y && y !== ' ' && y !== '?') modified++
119
+ }
120
+
121
+ const state = lines.length === 0 ? 'clean' : 'dirty'
122
+ return { state, untracked, modified, staged }
123
+ }
124
+
125
+ /**
126
+ * Count worktree entries from `git worktree list --porcelain` output.
127
+ *
128
+ * Each worktree is a record beginning with a `worktree <path>` line; records
129
+ * are separated by blank lines. The count includes the main worktree, so a
130
+ * repo with no extra worktrees reports 1.
131
+ *
132
+ * @param {string} porcelain - raw `git worktree list --porcelain` stdout.
133
+ * @returns {number} number of worktrees (>= 0).
134
+ */
135
+ export function countWorktrees(porcelain) {
136
+ if (!porcelain) return 0
137
+ return porcelain.split('\n').filter(l => l.startsWith('worktree ')).length
138
+ }
139
+
140
+ /**
141
+ * Count open PRs from `gh pr list --json number` output.
142
+ *
143
+ * @param {string|null} json - raw stdout, or null if the command failed.
144
+ * @returns {number|null} count, or null when undeterminable (gh missing /
145
+ * unauth / errored / unparseable).
146
+ */
147
+ export function parseOpenPRs(json) {
148
+ if (json === null || json === undefined) return null
149
+ try {
150
+ const arr = JSON.parse(json)
151
+ return Array.isArray(arr) ? arr.length : null
152
+ } catch {
153
+ return null
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Derive a repo's GitHub `{ owner, repo }` from its `origin` remote URL.
159
+ *
160
+ * Handles the three forms `git remote get-url origin` can return for a GitHub
161
+ * remote — SCP-style SSH (`git@github.com:owner/repo.git`), `ssh://` URLs, and
162
+ * `https://` URLs — with or without a trailing `.git`. Returns null for a
163
+ * non-GitHub remote, an empty/failed lookup, or anything that doesn't match.
164
+ *
165
+ * Shared derivation: this survey builds the PR rollup link from it (see
166
+ * {@link parseGithubPrsUrl}); the Integrations survey (#5501) reuses it to
167
+ * target `gh run list -R <owner>/<repo>` and the Actions deep link.
168
+ *
169
+ * @param {string|null} remote - raw `git remote get-url origin` stdout.
170
+ * @returns {{ owner: string, repo: string }|null}
171
+ */
172
+ export function parseGithubOwnerRepo(remote) {
173
+ if (!remote || typeof remote !== 'string') return null
174
+ const trimmed = remote.trim()
175
+ // owner + repo are each a single path segment ([^/]+) so an extra segment
176
+ // (e.g. `owner/repo/extra`) does NOT match (returns null rather than minting
177
+ // a bogus target). The ssh URL form allows an optional port (e.g. the
178
+ // common ssh-over-:443 remote).
179
+ const patterns = [
180
+ /^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?$/, // scp-style ssh
181
+ /^ssh:\/\/git@github\.com(?::\d+)?\/([^/]+)\/([^/]+?)(?:\.git)?$/, // ssh url (optional port)
182
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+?)(?:\.git)?$/, // https
183
+ ]
184
+ for (const re of patterns) {
185
+ const m = re.exec(trimmed)
186
+ if (m) return { owner: m[1], repo: m[2] }
187
+ }
188
+ return null
189
+ }
190
+
191
+ /**
192
+ * Derive a repo's GitHub pull-requests URL from its `origin` remote URL —
193
+ * `https://github.com/<owner>/<repo>/pulls`, or null when the remote isn't a
194
+ * recognisable GitHub repo (see {@link parseGithubOwnerRepo}).
195
+ *
196
+ * @param {string|null} remote - raw `git remote get-url origin` stdout.
197
+ * @returns {string|null}
198
+ */
199
+ export function parseGithubPrsUrl(remote) {
200
+ const target = parseGithubOwnerRepo(remote)
201
+ return target ? `https://github.com/${target.owner}/${target.repo}/pulls` : null
202
+ }
203
+
204
+ /**
205
+ * Conclusions/states from a `gh` statusCheckRollup entry that count as a failed
206
+ * check. `gh pr list --json statusCheckRollup` mixes two node shapes: CheckRun
207
+ * (GitHub Actions etc., carries `status` + `conclusion`) and StatusContext
208
+ * (legacy commit statuses, carries `state`). We treat either field uniformly.
209
+ */
210
+ const CI_FAIL_VALUES = new Set([
211
+ 'FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE',
212
+ ])
213
+ const CI_PENDING_STATUSES = new Set(['QUEUED', 'IN_PROGRESS', 'WAITING', 'PENDING', 'REQUESTED'])
214
+
215
+ /**
216
+ * Reduce one PR's `statusCheckRollup` array to a single CI state.
217
+ *
218
+ * @param {Array|undefined} rollup
219
+ * @returns {'failing'|'pending'|'passing'|'none'} 'none' when there are no checks.
220
+ */
221
+ function rollupCiState(rollup) {
222
+ if (!Array.isArray(rollup) || rollup.length === 0) return 'none'
223
+ let anyPending = false
224
+ for (const c of rollup) {
225
+ const conclusion = (c && (c.conclusion || c.state)) || ''
226
+ const status = (c && c.status) || ''
227
+ if (CI_FAIL_VALUES.has(conclusion)) return 'failing'
228
+ if (CI_PENDING_STATUSES.has(status) || conclusion === 'PENDING') anyPending = true
229
+ }
230
+ return anyPending ? 'pending' : 'passing'
231
+ }
232
+
233
+ /**
234
+ * Roll up CI + review state across a repo's open PRs from
235
+ * `gh pr list --json number,reviewDecision,statusCheckRollup` output.
236
+ *
237
+ * Returns counts of open PRs that are CI-failing, CI-pending, review-approved,
238
+ * and changes-requested, or `null` when the command failed / output is
239
+ * unparseable (same null semantics as `parseOpenPRs`). All-zero counts mean
240
+ * none of these tracked signals are present — which covers the no-open-PRs case
241
+ * AND PRs that only carry untracked states (e.g. passing CI with a
242
+ * `REVIEW_REQUIRED` decision). `null` ≠ all-zero.
243
+ *
244
+ * @param {string|null} json
245
+ * @returns {{ failing: number, pending: number, approved: number, changesRequested: number }|null}
246
+ */
247
+ export function parsePrChecks(json) {
248
+ if (json === null || json === undefined) return null
249
+ let arr
250
+ try {
251
+ arr = JSON.parse(json)
252
+ } catch {
253
+ return null
254
+ }
255
+ if (!Array.isArray(arr)) return null
256
+ let failing = 0
257
+ let pending = 0
258
+ let approved = 0
259
+ let changesRequested = 0
260
+ for (const pr of arr) {
261
+ if (!pr || typeof pr !== 'object') continue
262
+ const ci = rollupCiState(pr.statusCheckRollup)
263
+ if (ci === 'failing') failing++
264
+ else if (ci === 'pending') pending++
265
+ if (pr.reviewDecision === 'APPROVED') approved++
266
+ else if (pr.reviewDecision === 'CHANGES_REQUESTED') changesRequested++
267
+ }
268
+ return { failing, pending, approved, changesRequested }
269
+ }
270
+
271
+ /**
272
+ * Parse `git rev-list --left-right --count @{u}...HEAD` output into ahead/behind
273
+ * counts relative to the upstream tracking branch.
274
+ *
275
+ * The command prints `<left>\t<right>` where, for `@{u}...HEAD`, the left side
276
+ * counts commits the upstream has that HEAD lacks (= BEHIND) and the right side
277
+ * counts commits HEAD has that the upstream lacks (= AHEAD).
278
+ *
279
+ * Returns `{ ahead: null, behind: null }` when the input is null (no upstream /
280
+ * detached HEAD / command failed) or doesn't match the expected two-number
281
+ * shape — never throws.
282
+ *
283
+ * @param {string|null} raw - raw stdout, or null on command failure.
284
+ * @returns {{ ahead: number|null, behind: number|null }}
285
+ */
286
+ export function parseAheadBehind(raw) {
287
+ if (raw === null || raw === undefined) return { ahead: null, behind: null }
288
+ const m = /^(\d+)\s+(\d+)$/.exec(String(raw).trim())
289
+ if (!m) return { ahead: null, behind: null }
290
+ return { behind: Number(m[1]), ahead: Number(m[2]) }
291
+ }
292
+
293
+ /**
294
+ * Detect project-level attribution policy from `.claude/settings.json`.
295
+ *
296
+ * @param {string|null} contents - raw settings.json text, or null if absent.
297
+ * @returns {boolean|null} `true` when `includeCoAuthoredBy` is explicitly
298
+ * `false` (attribution suppressed — the expected pull-model setup),
299
+ * `false` when explicitly `true`, `null` when the file is missing,
300
+ * unparseable, or the key is absent.
301
+ */
302
+ export function detectAttribution(contents) {
303
+ if (contents === null || contents === undefined) return null
304
+ let parsed
305
+ try {
306
+ parsed = JSON.parse(contents)
307
+ } catch {
308
+ return null
309
+ }
310
+ if (!parsed || typeof parsed !== 'object') return null
311
+ if (typeof parsed.includeCoAuthoredBy !== 'boolean') return null
312
+ // `includeCoAuthoredBy: false` ⇒ attribution suppressed ⇒ true (expected).
313
+ return parsed.includeCoAuthoredBy === false
314
+ }
315
+
316
+ /**
317
+ * Normalise a repo path into a canonical comparison key for matching against
318
+ * active session cwds. Converts Windows backslashes to forward slashes (a
319
+ * session `cwd` on Windows uses `\\` separators) and strips a single trailing
320
+ * slash so prefix comparisons are separator-agnostic.
321
+ *
322
+ * @param {string} p - a path.
323
+ * @returns {string} comparison key.
324
+ */
325
+ function pathKey(p) {
326
+ if (typeof p !== 'string') return ''
327
+ const slashed = p.replace(/\\/g, '/')
328
+ return slashed.length > 1 && slashed.endsWith('/') ? slashed.slice(0, -1) : slashed
329
+ }
330
+
331
+ /**
332
+ * Whether any active chroxy-session cwd is bound to this repo path (exact match
333
+ * or a descendant of the repo directory).
334
+ *
335
+ * @param {string} repoPath - the repo's absolute path.
336
+ * @param {string[]} activeSessionCwds - cwds of active chroxy sessions.
337
+ * @returns {boolean}
338
+ */
339
+ function hasBoundSession(repoPath, activeSessionCwds) {
340
+ const key = pathKey(repoPath)
341
+ if (!key) return false
342
+ for (const cwd of activeSessionCwds) {
343
+ const c = pathKey(cwd)
344
+ if (!c) continue
345
+ if (c === key || c.startsWith(key + '/')) return true
346
+ }
347
+ return false
348
+ }
349
+
350
+ /**
351
+ * Classify a repo into a verdict + derived `live`, `onboarding`, and `note`.
352
+ *
353
+ * @param {object} args
354
+ * @param {{ state: string }} args.tree
355
+ * @param {number} args.worktrees
356
+ * @param {Date|null} args.lastTouchedDate
357
+ * @param {boolean} args.sessionBound
358
+ * @param {Date} args.now
359
+ * @param {object} args.thresholds
360
+ * @returns {{ verdict: string, live: boolean, onboarding: string, note?: string }}
361
+ */
362
+ function classify({ tree, worktrees, lastTouchedDate, sessionBound, now, thresholds }) {
363
+ const dirty = tree.state === 'dirty'
364
+ const ageMs = lastTouchedDate ? now.getTime() - lastTouchedDate.getTime() : null
365
+
366
+ // Live-agent detection: a bound chroxy session, OR the dirty-tree-recently-
367
+ // touched heuristic.
368
+ const heuristicLive = dirty && ageMs !== null && ageMs < thresholds.liveMs
369
+ const live = sessionBound || heuristicLive
370
+
371
+ if (live) {
372
+ const note = sessionBound
373
+ ? 'Active session here right now'
374
+ : 'Uncommitted work touched moments ago — likely a live agent'
375
+ return { verdict: 'live', live: true, onboarding: 'deferred (live)', note }
376
+ }
377
+
378
+ // Worktree leak takes precedence for a non-live repo — it's the clearest
379
+ // "needs a human look" signal.
380
+ if (worktrees >= thresholds.worktreeLeak) {
381
+ return {
382
+ verdict: 'investigate',
383
+ live: false,
384
+ onboarding: 'skipped — worktree leak',
385
+ note: `${worktrees} worktrees — likely a leak`,
386
+ }
387
+ }
388
+
389
+ if (dirty) {
390
+ const recent = ageMs !== null && ageMs < thresholds.recentMs
391
+ if (recent) {
392
+ return {
393
+ verdict: 'recent',
394
+ live: false,
395
+ onboarding: 'skipped — dirty tree',
396
+ note: `Uncommitted work last touched ${humanizeAge(ageMs)} ago, no live agent`,
397
+ }
398
+ }
399
+ return {
400
+ verdict: 'abandoned',
401
+ live: false,
402
+ onboarding: 'skipped — dirty tree',
403
+ note: `Uncommitted work last touched ${humanizeAge(ageMs)} ago, no live agent`,
404
+ }
405
+ }
406
+
407
+ // Clean tree, not live, no leak → onboarded on the pull model.
408
+ return { verdict: 'onboarded', live: false, onboarding: '✓ onboarded' }
409
+ }
410
+
411
+ /**
412
+ * Render a coarse human-readable age for a `↳` note. Best-effort, not exact.
413
+ *
414
+ * @param {number|null} ageMs
415
+ * @returns {string}
416
+ */
417
+ function humanizeAge(ageMs) {
418
+ if (ageMs === null || ageMs === undefined) return 'an unknown time'
419
+ const sec = Math.floor(ageMs / 1000)
420
+ if (sec < 60) return `${sec}s`
421
+ const min = Math.floor(sec / 60)
422
+ if (min < 60) return `${min}m`
423
+ const hr = Math.floor(min / 60)
424
+ if (hr < 24) return `${hr}h`
425
+ const days = Math.floor(hr / 24)
426
+ if (days < 7) return `${days}d`
427
+ const weeks = Math.floor(days / 7)
428
+ return `${weeks}w`
429
+ }
430
+
431
+ /**
432
+ * Survey one repo. A per-repo failure is contained: the worst case still
433
+ * returns a schema-valid degraded `RepoStatus` with a note.
434
+ *
435
+ * @param {{ name: string, path: string }} repo
436
+ * @param {object} ctx - { execFn, readFn, now, activeSessionCwds, thresholds }
437
+ * @returns {Promise<object>} a `RepoStatus`-shaped object.
438
+ */
439
+ async function surveyOne(repo, ctx) {
440
+ const { execFn, readFn, now, activeSessionCwds, thresholds } = ctx
441
+ const cwd = repo.path
442
+
443
+ try {
444
+ const sessionBound = hasBoundSession(repo.path, activeSessionCwds)
445
+
446
+ // Run the independent git probes concurrently.
447
+ const [branchRaw, statusRaw, worktreeRaw, lastRaw, aheadBehindRaw, remoteRaw, prRaw, settingsRaw] = await Promise.all([
448
+ tryExec(execFn, 'git', ['rev-parse', '--abbrev-ref', 'HEAD'], cwd),
449
+ tryExec(execFn, 'git', ['status', '--porcelain'], cwd),
450
+ tryExec(execFn, 'git', ['worktree', 'list', '--porcelain'], cwd),
451
+ tryExec(execFn, 'git', ['log', '-1', '--format=%cI'], cwd),
452
+ // No upstream / detached HEAD makes this fail → null → ahead/behind null.
453
+ tryExec(execFn, 'git', ['rev-list', '--left-right', '--count', '@{u}...HEAD'], cwd),
454
+ // origin remote → GitHub PRs URL (null for a non-GitHub / missing remote).
455
+ tryExec(execFn, 'git', ['remote', 'get-url', 'origin'], cwd),
456
+ // One gh call serves both the open-PR count and the CI/review rollup.
457
+ // `--limit` is explicit: gh defaults to 30, which would silently cap both.
458
+ tryExec(execFn, 'gh', ['pr', 'list', '--limit', String(GH_PR_LIST_LIMIT), '--json', 'number,reviewDecision,statusCheckRollup'], cwd),
459
+ readSettings(readFn, repo.path),
460
+ ])
461
+
462
+ // `git status --porcelain` is the authoritative tree probe. A null here
463
+ // means the command FAILED (path isn't a git repo, git unavailable, etc.)
464
+ // — distinct from a successful empty string (a genuinely clean tree). We
465
+ // must NOT fall back to parseTree('') in that case: it would paint a
466
+ // false `clean`/`onboarded` row. Surface it as a degraded `investigate`
467
+ // row instead so the Control Room flags it for a human look.
468
+ if (statusRaw === null) {
469
+ return degradedRepo(repo, now, new Error('git status probe failed (not a git repo or git unavailable)'))
470
+ }
471
+
472
+ const branch = branchRaw && branchRaw.length > 0 ? branchRaw : 'unknown'
473
+ const tree = parseTree(statusRaw)
474
+ const worktrees = countWorktrees(worktreeRaw || '')
475
+ const { ahead, behind } = parseAheadBehind(aheadBehindRaw)
476
+ const openPRs = parseOpenPRs(prRaw)
477
+ const prChecks = parsePrChecks(prRaw)
478
+ const prsUrl = parseGithubPrsUrl(remoteRaw)
479
+ const attribution = detectAttribution(settingsRaw)
480
+
481
+ const lastTouchedDate = lastRaw ? parseIsoDate(lastRaw) : null
482
+ const lastTouched = lastTouchedDate ? lastTouchedDate.toISOString() : now.toISOString()
483
+
484
+ const { verdict, live, onboarding, note } = classify({
485
+ tree,
486
+ worktrees,
487
+ lastTouchedDate,
488
+ sessionBound,
489
+ now,
490
+ thresholds,
491
+ })
492
+
493
+ const status = {
494
+ name: repo.name,
495
+ path: repo.path,
496
+ branch,
497
+ verdict,
498
+ live,
499
+ tree,
500
+ worktrees,
501
+ ahead,
502
+ behind,
503
+ openPRs,
504
+ prChecks,
505
+ prsUrl,
506
+ attribution,
507
+ onboarding,
508
+ lastTouched,
509
+ }
510
+ if (note) status.note = note
511
+ return status
512
+ } catch (err) {
513
+ // Degraded — never fail the whole survey on one repo.
514
+ return degradedRepo(repo, now, err)
515
+ }
516
+ }
517
+
518
+ /**
519
+ * Read `.claude/settings.json` for a repo, tolerating absence/errors.
520
+ *
521
+ * @param {Function} readFn - async readFile seam.
522
+ * @param {string} repoPath
523
+ * @returns {Promise<string|null>}
524
+ */
525
+ async function readSettings(readFn, repoPath) {
526
+ try {
527
+ const contents = await readFn(join(repoPath, '.claude', 'settings.json'), 'utf8')
528
+ return typeof contents === 'string' ? contents : null
529
+ } catch {
530
+ return null
531
+ }
532
+ }
533
+
534
+ /**
535
+ * Parse an ISO date string into a `Date`, or null if invalid.
536
+ *
537
+ * @param {string} raw
538
+ * @returns {Date|null}
539
+ */
540
+ function parseIsoDate(raw) {
541
+ const t = Date.parse(raw)
542
+ return Number.isFinite(t) ? new Date(t) : null
543
+ }
544
+
545
+ /**
546
+ * Build a schema-valid degraded `RepoStatus` for a repo whose survey threw.
547
+ *
548
+ * @param {{ name: string, path: string }} repo
549
+ * @param {Date} now
550
+ * @param {Error} [err]
551
+ * @returns {object}
552
+ */
553
+ function degradedRepo(repo, now, err) {
554
+ return {
555
+ name: repo.name,
556
+ path: repo.path,
557
+ branch: 'unknown',
558
+ verdict: 'investigate',
559
+ live: false,
560
+ tree: { state: 'clean', untracked: 0, modified: 0, staged: 0 },
561
+ worktrees: 0,
562
+ ahead: null,
563
+ behind: null,
564
+ openPRs: null,
565
+ prChecks: null,
566
+ prsUrl: null,
567
+ attribution: null,
568
+ onboarding: 'skipped — survey failed',
569
+ lastTouched: now.toISOString(),
570
+ note: `Survey failed: ${getErrorMessage(err, 'unknown error')}`,
571
+ }
572
+ }
573
+
574
+ /**
575
+ * Run `tasks` with a concurrency cap, preserving input order in the result.
576
+ *
577
+ * @template T
578
+ * @param {Array<() => Promise<T>>} tasks
579
+ * @param {number} cap
580
+ * @returns {Promise<T[]>}
581
+ */
582
+ async function mapWithCap(tasks, cap) {
583
+ const results = new Array(tasks.length)
584
+ let cursor = 0
585
+ const limit = Math.max(1, Math.min(cap, tasks.length || 1))
586
+
587
+ async function worker() {
588
+ while (cursor < tasks.length) {
589
+ const i = cursor++
590
+ results[i] = await tasks[i]()
591
+ }
592
+ }
593
+
594
+ const workers = []
595
+ for (let i = 0; i < limit; i++) workers.push(worker())
596
+ await Promise.all(workers)
597
+ return results
598
+ }
599
+
600
+ /**
601
+ * Tally per-verdict summary counts across surveyed repos.
602
+ *
603
+ * @param {object[]} repos - `RepoStatus[]`.
604
+ * @returns {{ live, onboarded, abandoned, investigate, recent }}
605
+ */
606
+ function summarize(repos) {
607
+ const summary = { live: 0, onboarded: 0, abandoned: 0, investigate: 0, recent: 0 }
608
+ for (const r of repos) {
609
+ if (r.verdict in summary) summary[r.verdict]++
610
+ }
611
+ return summary
612
+ }
613
+
614
+ /**
615
+ * Survey a list of repos and produce a `host_status_snapshot`-shaped result
616
+ * (minus the `type` field, which the WS handler adds).
617
+ *
618
+ * @param {Array<{ name: string, path: string }>} repoSet - resolved repo set.
619
+ * @param {object} [opts]
620
+ * @param {string[]} [opts.activeSessionCwds] - cwds of active chroxy sessions,
621
+ * supplied by the WS handler (#5174) from SessionManager.
622
+ * @param {string} [opts.root] - the discovery root to report in the snapshot.
623
+ * @param {object} [opts.thresholds] - verdict thresholds (see DEFAULT_THRESHOLDS).
624
+ * @param {number} [opts.concurrency] - per-repo concurrency cap.
625
+ * @param {Function} [opts._execFile] - promisified execFile seam.
626
+ * @param {Function} [opts._now] - returns a `Date` for "now".
627
+ * @param {Function} [opts._readFile] - async readFile seam.
628
+ * @returns {Promise<{ generatedAt: string, root: string, summary: object, repos: object[] }>}
629
+ */
630
+ export async function surveyRepos(repoSet, opts = {}) {
631
+ const {
632
+ activeSessionCwds = [],
633
+ root = '',
634
+ thresholds: thresholdOverrides = {},
635
+ concurrency = DEFAULT_CONCURRENCY,
636
+ _execFile = execFileAsync,
637
+ _now = () => new Date(),
638
+ _readFile = readFile,
639
+ } = opts
640
+
641
+ const now = _now()
642
+ const thresholds = { ...DEFAULT_THRESHOLDS, ...thresholdOverrides }
643
+ const ctx = {
644
+ execFn: _execFile,
645
+ readFn: _readFile,
646
+ now,
647
+ activeSessionCwds: Array.isArray(activeSessionCwds) ? activeSessionCwds : [],
648
+ thresholds,
649
+ }
650
+
651
+ const list = Array.isArray(repoSet) ? repoSet : []
652
+ const tasks = list.map(repo => () => surveyOne(repo, ctx))
653
+ const repos = await mapWithCap(tasks, concurrency)
654
+
655
+ return {
656
+ generatedAt: now.toISOString(),
657
+ root,
658
+ summary: summarize(repos),
659
+ repos,
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Convenience: resolve the repo set (via `resolveRepoSet`) and survey it in one
665
+ * call. The WS handler (#5174) will typically call `resolveRepoSet` and
666
+ * `surveyRepos` separately so it can inject live session cwds, but this wrapper
667
+ * is handy for a one-shot survey from config.
668
+ *
669
+ * @param {object} [opts] - merged options for `resolveRepoSet` + `surveyRepos`.
670
+ * @returns {Promise<object>} snapshot-shaped result.
671
+ */
672
+ export async function surveyHost(opts = {}) {
673
+ const repoSet = resolveRepoSet({
674
+ repos: opts.repos,
675
+ root: opts.root,
676
+ _readdir: opts._readdir,
677
+ _stat: opts._stat,
678
+ _exists: opts._exists,
679
+ _realpath: opts._realpath,
680
+ })
681
+ return surveyRepos(repoSet, {
682
+ ...opts,
683
+ root: opts.root || '',
684
+ })
685
+ }