@chroxy/server 0.10.0 → 0.11.10

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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,654 @@
1
+ /**
2
+ * Session → pull-request / CI status survey (#7344, display slice).
3
+ *
4
+ * A session that opened a PR has no durable knowledge of it: the PR number
5
+ * exists only as text the model happened to type, so nothing in the UI can show
6
+ * where the work stands and the agent is left to poll `gh pr checks` on its own
7
+ * schedule. This module answers, for ONE session, the question the user
8
+ * actually has while a session is in flight — *what is the state of the thing
9
+ * this session produced?*
10
+ *
11
+ * Auth: none is introduced. Exactly like the Control Room integrations survey
12
+ * (#5501/#5502), this shells out to the user's existing local `gh auth` and
13
+ * inherits that survey's degradation behaviour when `gh` is absent or the
14
+ * remote isn't GitHub.
15
+ *
16
+ * ## Three things this survey must never do
17
+ *
18
+ * 1. **Never fabricate a verdict.** A head commit with *no* checks at all is
19
+ * reported as `state: 'none'`, never as success — "no run for this SHA"
20
+ * and "run in progress" are distinct states with distinct counts, and a
21
+ * push can legitimately create no run at all. A rollup entry whose status
22
+ * or conclusion this module does not recognise lands in the `unknown`
23
+ * bucket and suppresses a `'success'` verdict; it is never counted as a
24
+ * pass.
25
+ * 2. **Never scrape.** Every GitHub read goes through `--json`. `gh pr checks`
26
+ * output is TAB-separated, and splitting it on whitespace carves up job
27
+ * *names* — which makes a poller report "settled" instantly.
28
+ * 3. **Never imply mergeability from CI.** `checks` and `merge` are separate
29
+ * fields and are never collapsed into a "ready?" boolean. The case that
30
+ * motivated this issue had 21/21 checks green while `mergeStateStatus` was
31
+ * `BLOCKED` on one unresolved review thread, so a combined badge would have
32
+ * been actively wrong in exactly the case the user needed it.
33
+ *
34
+ * ## Consistency of the reading
35
+ *
36
+ * `mergeStateStatus` and the check rollup are both functions of the head SHA, so
37
+ * a reading assembled from two calls can straddle a push. Everything except the
38
+ * branch/remote derivation therefore comes from a SINGLE `gh pr list` response,
39
+ * and the `headRefOid` it reported is carried on the snapshot: the caller can
40
+ * always see which commit the verdict describes. `mergeStateStatus: 'UNKNOWN'`
41
+ * means GitHub is still recomputing, not that a blocker exists, and is passed
42
+ * through verbatim rather than being interpreted here.
43
+ *
44
+ * ## Reading the result
45
+ *
46
+ * `pr: null` with `reason: null` is the quiet negative — this branch definitively
47
+ * has no open PR, on `origin` OR (when `origin` is a fork) on its upstream.
48
+ * `pr: null` with a `reason` means the survey could not find out. Those must
49
+ * render differently; "cannot determine" must never read as an implied green.
50
+ *
51
+ * `indeterminate: true` (#7435) is the third state, and it is SERVER-SIDE ONLY:
52
+ * a fork-widening lookup failed transiently, so absence was NOT established —
53
+ * but the display contract above is deliberately unchanged (still the quiet
54
+ * negative on the wire; a best-effort widening of an already-empty result must
55
+ * not downgrade a usable partial answer). The one consumer that must not read
56
+ * it as a fact is the CI watcher, whose `_reconcile` drops an armed watch on
57
+ * `pr: null` — the marker gets the same "changes nothing" treatment there that
58
+ * `reason` already gets.
59
+ *
60
+ * #7442: wire-only-ness is enforced HERE, at the field's definition, rather
61
+ * than at a single distant WS-handler call site — `markIndeterminate()` defines
62
+ * the property `enumerable: false`, so an ordinary `{ ...snapshot }` spread or
63
+ * `JSON.stringify(snapshot)` structurally cannot carry it, and no future sender
64
+ * of a survey snapshot needs to remember a strip. Read it back with
65
+ * `isIndeterminate()`, never `snapshot.indeterminate` directly, since a plain
66
+ * property access reads the same either way but an accessor keeps every caller
67
+ * one place if the mechanism ever changes again.
68
+ *
69
+ * Every external interaction is injectable so tests never touch real git/gh:
70
+ * - `_execFile(file, args, opts)` — async, resolves `{ stdout, stderr }`.
71
+ * - `_now()` — returns a `Date` (defaults to `new Date()`).
72
+ */
73
+
74
+ import { SESSION_PR_NOT_A_REPO_REASON as NOT_A_REPO_REASON } from '@chroxy/protocol'
75
+ import { execFile } from 'child_process'
76
+ import { promisify } from 'util'
77
+ import { parseGithubOwnerRepo } from './control-room/survey.js'
78
+ import { EXEC_TIMEOUT_MS } from './control-room/constants.js'
79
+ import { execFailureReason } from './utils/exec-failure-reason.js'
80
+ import { isSafeArgvValue } from './utils/argv-safety.js'
81
+
82
+ const execFileAsync = promisify(execFile)
83
+
84
+ /** Output cap: one PR's JSON, rollup included, is small. */
85
+ const EXEC_MAX_BUFFER = 8 * 1024 * 1024
86
+
87
+ /**
88
+ * Shared exec options for every probe (see EXEC_TIMEOUT_MS's rationale).
89
+ * Exported so the sibling review-thread survey (#7430) runs its one `gh api
90
+ * graphql` call under the SAME timeout and output cap rather than minting a
91
+ * second pair that can drift from these.
92
+ */
93
+ export const EXEC_OPTS = { timeout: EXEC_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
94
+
95
+ /**
96
+ * How many base-repo rows to consider when disambiguating a fork's PR by head
97
+ * owner. One branch name can be open from several forks at once, so this is
98
+ * deliberately more than 1 — but bounded, since it is a fallback path.
99
+ */
100
+ export const FORK_QUERY_LIMIT = 30
101
+
102
+ /** Reason when the session has no working directory to resolve a repo from. */
103
+ export const NO_CWD_REASON = 'session has no working directory'
104
+
105
+ /** Reason when the session's cwd is not inside a git repository. */
106
+ export { NOT_A_REPO_REASON }
107
+
108
+ /** Reason when the session's cwd no longer exists (e.g. a reaped worktree). */
109
+ export const CWD_MISSING_REASON = 'session working directory no longer exists'
110
+
111
+ /** Reason when the session's checkout is on a detached HEAD (no branch to match a PR to). */
112
+ export const DETACHED_HEAD_REASON = 'detached HEAD — no branch to resolve a pull request from'
113
+
114
+ /** Reason when the repo has no remote this module recognises as GitHub. */
115
+ export const NO_GITHUB_REMOTE_REASON = 'no GitHub remote'
116
+
117
+ /** Reason when `gh` is not installed (mirrors the Control Room integrations note). */
118
+ export const GH_MISSING_REASON = 'gh CLI not found on PATH — install GitHub CLI (gh) to see pull-request and CI status'
119
+
120
+ /**
121
+ * A row for THIS branch came back from `gh pr list` but cannot be normalised
122
+ * into a usable PR. One wording for the one condition, on both the same-repo
123
+ * and the fork path (#7441).
124
+ */
125
+ export const UNUSABLE_ROW_REASON = 'gh pr list returned a row without a usable pull-request number'
126
+
127
+ /** Reason when the branch name is not safe to place in an option-parsed argv slot. */
128
+ export const UNSAFE_BRANCH_REASON = 'branch name cannot be passed safely to gh'
129
+
130
+ /**
131
+ * The `--json` fields requested from `gh pr list`. One call, one head SHA.
132
+ *
133
+ * `headRepositoryOwner` is here for the fork path below: a base-repo query
134
+ * matches on the bare branch name, and two forks can both have a `fix-typos`
135
+ * branch open against the same base — so the row must be disambiguated by who
136
+ * owns the head, not taken on `--limit 1`.
137
+ */
138
+ export const PR_JSON_FIELDS = [
139
+ 'headRepositoryOwner',
140
+ 'number',
141
+ 'title',
142
+ 'url',
143
+ 'headRefOid',
144
+ 'isDraft',
145
+ 'mergeable',
146
+ 'mergeStateStatus',
147
+ 'reviewDecision',
148
+ 'statusCheckRollup',
149
+ ].join(',')
150
+
151
+ /**
152
+ * Reduce every absolute path in a degradation reason to its basename.
153
+ *
154
+ * This reply is session-scoped rather than host-scoped, so unlike the Control
155
+ * Room surveys it reaches a pairing-bound (share-a-session) client, which has no
156
+ * business learning host filesystem layout. `execFile`'s own error message is
157
+ * `Command failed: /Users/<name>/.../gh pr list …`.
158
+ *
159
+ * Deliberately NOT "strip the one path we resolved": that only removes the path
160
+ * it was told about, and a message can carry others (a cwd, a config path, a
161
+ * second binary). Rewriting every path-shaped token is the general form, and it
162
+ * cannot be defeated by a path the caller did not anticipate.
163
+ *
164
+ * @param {string} reason
165
+ * @returns {string}
166
+ */
167
+ export function redactAbsolutePaths(reason) {
168
+ if (typeof reason !== 'string') return reason
169
+ // Any run of non-space characters containing a '/' after a leading '/' —
170
+ // i.e. an absolute path with at least one directory — collapses to its
171
+ // basename. A bare '/' or a lone segment is left alone.
172
+ return reason.replace(/\/\S*\/\S*/g, match => {
173
+ const base = match.slice(match.lastIndexOf('/') + 1)
174
+ return base.length > 0 ? base : '/'
175
+ })
176
+ }
177
+
178
+ /** Zeroed check counts — also the shape returned for a head with no checks. */
179
+ function emptyCounts() {
180
+ return { total: 0, passed: 0, failed: 0, pending: 0, skipped: 0, unknown: 0 }
181
+ }
182
+
183
+ /**
184
+ * CheckRun `status` values that mean "not finished yet". Anything not in here
185
+ * and not `COMPLETED` is unrecognised and lands in `unknown` — the list is
186
+ * deliberately explicit so a new GitHub status is reported as unknown rather
187
+ * than silently absorbed into a pass.
188
+ */
189
+ const CHECK_RUN_PENDING_STATUS = new Set(['QUEUED', 'IN_PROGRESS', 'WAITING', 'PENDING', 'REQUESTED'])
190
+
191
+ /** CheckRun conclusions that count as a pass. `NEUTRAL` does not fail a rollup. */
192
+ const CHECK_RUN_PASS_CONCLUSION = new Set(['SUCCESS', 'NEUTRAL'])
193
+
194
+ /** CheckRun conclusions that count as a failure. */
195
+ const CHECK_RUN_FAIL_CONCLUSION = new Set([
196
+ 'FAILURE',
197
+ 'TIMED_OUT',
198
+ 'CANCELLED',
199
+ 'STARTUP_FAILURE',
200
+ 'ACTION_REQUIRED',
201
+ 'STALE',
202
+ ])
203
+
204
+ /** Legacy commit-status (`StatusContext`) states, by bucket. */
205
+ const STATUS_CONTEXT_BUCKET = new Map([
206
+ ['SUCCESS', 'passed'],
207
+ ['PENDING', 'pending'],
208
+ ['EXPECTED', 'pending'],
209
+ ['FAILURE', 'failed'],
210
+ ['ERROR', 'failed'],
211
+ ])
212
+
213
+ /**
214
+ * Bucket ONE `statusCheckRollup` entry.
215
+ *
216
+ * The rollup mixes two GraphQL types — modern `CheckRun`s (a `status` plus, once
217
+ * `COMPLETED`, a `conclusion`) and legacy `StatusContext` commit statuses (a
218
+ * single `state`). Both are handled; anything else is `'unknown'`.
219
+ *
220
+ * @param {unknown} entry
221
+ * @returns {'passed'|'failed'|'pending'|'skipped'|'unknown'}
222
+ */
223
+ export function bucketRollupEntry(entry) {
224
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return 'unknown'
225
+
226
+ // A StatusContext carries `state` and no `status`; a CheckRun is the converse.
227
+ // Dispatch on __typename when present, and fall back to which field exists so
228
+ // a response missing __typename still buckets correctly.
229
+ const typename = typeof entry.__typename === 'string' ? entry.__typename : null
230
+ const looksLikeStatusContext = typename === 'StatusContext' || (typename === null && typeof entry.state === 'string')
231
+
232
+ if (looksLikeStatusContext) {
233
+ return STATUS_CONTEXT_BUCKET.get(String(entry.state).toUpperCase()) || 'unknown'
234
+ }
235
+
236
+ if (typename !== null && typename !== 'CheckRun') return 'unknown'
237
+
238
+ const status = typeof entry.status === 'string' ? entry.status.toUpperCase() : null
239
+ if (status === null) return 'unknown'
240
+ if (CHECK_RUN_PENDING_STATUS.has(status)) return 'pending'
241
+ if (status !== 'COMPLETED') return 'unknown'
242
+
243
+ const conclusion = typeof entry.conclusion === 'string' ? entry.conclusion.toUpperCase() : null
244
+ if (conclusion === 'SKIPPED') return 'skipped'
245
+ if (conclusion !== null && CHECK_RUN_PASS_CONCLUSION.has(conclusion)) return 'passed'
246
+ if (conclusion !== null && CHECK_RUN_FAIL_CONCLUSION.has(conclusion)) return 'failed'
247
+ return 'unknown'
248
+ }
249
+
250
+ /**
251
+ * Summarise a `statusCheckRollup` array into a state + counts.
252
+ *
253
+ * The overall `state` follows GitHub's own rollup semantics — a run that is
254
+ * still going is `'pending'` even when something in it has already failed — so
255
+ * `state` alone never implies the run is settled. The `failed` count stays
256
+ * visible alongside it precisely so a UI can say "3 failed / 5 pending" rather
257
+ * than hiding a known failure behind a spinner.
258
+ *
259
+ * `'none'` (an absent or empty rollup) is NOT success: it means this head SHA
260
+ * produced no run, which a push can legitimately do.
261
+ *
262
+ * @param {unknown} rollup - the `statusCheckRollup` value from `gh pr list`.
263
+ * @returns {{ state: 'none'|'pending'|'failure'|'unknown'|'success', counts: object }}
264
+ */
265
+ export function summariseChecks(rollup) {
266
+ const counts = emptyCounts()
267
+ if (!Array.isArray(rollup) || rollup.length === 0) return { state: 'none', counts }
268
+
269
+ for (const entry of rollup) {
270
+ counts[bucketRollupEntry(entry)] += 1
271
+ counts.total += 1
272
+ }
273
+
274
+ // Order matters and is asserted by tests: pending outranks failure (the run is
275
+ // not settled), failure outranks unknown, and success is only claimed when
276
+ // every entry was recognised AND passed or was skipped.
277
+ let state
278
+ if (counts.pending > 0) state = 'pending'
279
+ else if (counts.failed > 0) state = 'failure'
280
+ else if (counts.unknown > 0) state = 'unknown'
281
+ else state = 'success'
282
+ return { state, counts }
283
+ }
284
+
285
+ /**
286
+ * Normalise one `gh pr list --json` row into the snapshot's `pr` / `checks` /
287
+ * `merge` fields. Exported for unit tests.
288
+ *
289
+ * `mergeable` / `mergeStateStatus` / `reviewDecision` are passed through as
290
+ * GitHub reports them (empty string normalised to null) — this module does not
291
+ * interpret them, and in particular does not turn them into a mergeability
292
+ * verdict alongside the check state.
293
+ *
294
+ * @param {unknown} row
295
+ * @returns {{ pr: object, checks: object, merge: object }|null} null when the
296
+ * row carries no usable PR number.
297
+ */
298
+ export function normalisePrRow(row) {
299
+ if (!row || typeof row !== 'object' || Array.isArray(row)) return null
300
+ if (!Number.isInteger(row.number) || row.number <= 0) return null
301
+
302
+ const str = v => (typeof v === 'string' && v.length > 0 ? v : null)
303
+ const { state, counts } = summariseChecks(row.statusCheckRollup)
304
+
305
+ return {
306
+ pr: {
307
+ number: row.number,
308
+ title: str(row.title),
309
+ url: str(row.url),
310
+ headRefOid: str(row.headRefOid),
311
+ isDraft: row.isDraft === true,
312
+ },
313
+ checks: { state, counts },
314
+ merge: {
315
+ mergeable: str(row.mergeable),
316
+ mergeStateStatus: str(row.mergeStateStatus),
317
+ reviewDecision: str(row.reviewDecision),
318
+ },
319
+ }
320
+ }
321
+
322
+ /** Build the snapshot skeleton, so every return path has the same shape. */
323
+ function baseSnapshot(sessionId, generatedAt) {
324
+ const snapshot = {
325
+ sessionId,
326
+ generatedAt,
327
+ branch: null,
328
+ repo: null,
329
+ pr: null,
330
+ checks: null,
331
+ merge: null,
332
+ reason: null,
333
+ }
334
+ // #7435 / #7442: server-side only, and defined non-enumerable so the field
335
+ // is structurally absent from any `{ ...snapshot }` spread or
336
+ // `JSON.stringify(snapshot)` — see markIndeterminate()/isIndeterminate() and
337
+ // the module doc above. `writable`/`configurable` stay true so
338
+ // markIndeterminate() below can flip the value without redefining it.
339
+ Object.defineProperty(snapshot, 'indeterminate', {
340
+ value: false,
341
+ writable: true,
342
+ enumerable: false,
343
+ configurable: true,
344
+ })
345
+ return snapshot
346
+ }
347
+
348
+ /**
349
+ * Mark a snapshot `indeterminate` (#7435: a fork-widening lookup failed
350
+ * transiently, so absence was NOT established). Every fork bail-out below
351
+ * calls this instead of assigning the field directly.
352
+ *
353
+ * Deliberately `Object.defineProperty`, not `snapshot.indeterminate = true`: a
354
+ * PLAIN assignment only preserves an existing property's non-enumerable
355
+ * descriptor when the property already exists on that exact object — creating
356
+ * the property fresh (no prior `baseSnapshot()`, e.g. a test fixture built by
357
+ * spreading a plain sample object) falls back to the default
358
+ * writable/enumerable/configurable attributes, silently reintroducing the leak
359
+ * this whole mechanism exists to close (#7442). Calling `defineProperty` here
360
+ * too means this function is correct regardless of the snapshot's origin.
361
+ *
362
+ * @param {object} snapshot
363
+ * @returns {object} the same snapshot, for a `return markIndeterminate(x)` style.
364
+ */
365
+ export function markIndeterminate(snapshot) {
366
+ Object.defineProperty(snapshot, 'indeterminate', {
367
+ value: true,
368
+ writable: true,
369
+ enumerable: false,
370
+ configurable: true,
371
+ })
372
+ return snapshot
373
+ }
374
+
375
+ /**
376
+ * Read the `indeterminate` marker without depending on its enumerability —
377
+ * property access sees a non-enumerable value exactly like an enumerable one,
378
+ * but going through this accessor keeps every reader (the CI watcher, tests)
379
+ * pointed at one definition rather than a repeated `?.indeterminate === true`.
380
+ *
381
+ * @param {object|null|undefined} snapshot
382
+ * @returns {boolean}
383
+ */
384
+ export function isIndeterminate(snapshot) {
385
+ return snapshot?.indeterminate === true
386
+ }
387
+
388
+ /**
389
+ * Resolve the session's branch. Returns `{ branch }`, or `{ reason }` when the
390
+ * cwd is not a repo / is on a detached HEAD.
391
+ *
392
+ * The cwd is passed via the `cwd` exec option rather than `git -C <cwd>`, so a
393
+ * path that begins with `-` never reaches git's option parser at all.
394
+ */
395
+ async function resolveBranch(execFn, cwd) {
396
+ let stdout
397
+ try {
398
+ ;({ stdout } = await execFn('git', ['branch', '--show-current'], { ...EXEC_OPTS, cwd }))
399
+ } catch (err) {
400
+ // A worktree can be reaped out from under a live session (the harness GCs
401
+ // `.claude/worktrees/` on its own schedule), and "not a git repository" would
402
+ // be a misleading way to say the directory is simply gone.
403
+ if (err && typeof err === 'object' && err.code === 'ENOENT') return { reason: CWD_MISSING_REASON }
404
+ return { reason: NOT_A_REPO_REASON }
405
+ }
406
+ const branch = String(stdout == null ? '' : stdout).trim()
407
+ // `branch --show-current` prints an empty line on a detached HEAD; it exits 0,
408
+ // so the empty result IS the signal and must not be mistaken for a failure.
409
+ if (branch.length === 0) return { reason: DETACHED_HEAD_REASON }
410
+ if (!isSafeArgvValue(branch)) return { reason: UNSAFE_BRANCH_REASON }
411
+ return { branch }
412
+ }
413
+
414
+ /** Resolve `origin` into `{ owner, repo }`, or null when it is not GitHub. */
415
+ async function resolveRepo(execFn, cwd) {
416
+ try {
417
+ const { stdout } = await execFn('git', ['remote', 'get-url', 'origin'], { ...EXEC_OPTS, cwd })
418
+ return parseGithubOwnerRepo(typeof stdout === 'string' ? stdout : '')
419
+ } catch {
420
+ return null
421
+ }
422
+ }
423
+
424
+ /**
425
+ * Resolve the upstream this repo was forked from.
426
+ *
427
+ * The caller needs the AUTHORITATIVE and the TRANSIENT outcome kept apart
428
+ * (#7435): "gh answered, and this repo has no parent" licenses the quiet
429
+ * negative, while "the lookup itself failed" establishes nothing and must not.
430
+ *
431
+ * @returns {Promise<{parent: {owner: string, repo: string}|null}|{failed: true}>}
432
+ * `{ parent }` when gh answered (`parent: null` = authoritatively not a
433
+ * fork); `{ failed: true }` when the lookup failed or answered in a shape
434
+ * that cannot be used (including a parent name that would be option-parsed —
435
+ * the upstream exists but cannot be queried, which is still not absence).
436
+ * The union is discriminated by key PRESENCE: `failed` exists only on the
437
+ * failure member, `parent` only on the answered one.
438
+ */
439
+ async function resolveParentRepo(execFn, ghPath, target, cwd) {
440
+ let stdout
441
+ try {
442
+ ;({ stdout } = await execFn(ghPath, ['repo', 'view', `${target.owner}/${target.repo}`, '--json', 'parent'], { ...EXEC_OPTS, cwd }))
443
+ } catch {
444
+ return { failed: true }
445
+ }
446
+ let parsed
447
+ try {
448
+ parsed = JSON.parse(String(stdout == null ? '' : stdout))
449
+ } catch {
450
+ return { failed: true }
451
+ }
452
+ if (!parsed || typeof parsed !== 'object' || !('parent' in parsed)) return { failed: true }
453
+ if (parsed.parent === null) return { parent: null }
454
+ const owner = parsed?.parent?.owner?.login
455
+ const repo = parsed?.parent?.name
456
+ if (typeof owner !== 'string' || typeof repo !== 'string') return { failed: true }
457
+ // These come from GitHub's own JSON rather than a client, but they go straight
458
+ // into an option-parsed `-R` slot, so they are checked like any other argv datum.
459
+ if (!isSafeArgvValue(owner) || !isSafeArgvValue(repo)) return { failed: true }
460
+ return { parent: { owner, repo } }
461
+ }
462
+
463
+ /**
464
+ * Probe the PATH for `gh`. Any failure resolves null (the survey then degrades).
465
+ *
466
+ * Exported for #7430: the review-thread survey needs the same binary and must
467
+ * degrade with the same `GH_MISSING_REASON`. Deliberately NOT memoised — the
468
+ * daemon outlives a `gh` install or removal, and a cached "absent" would keep
469
+ * degrading a host that has since installed it.
470
+ */
471
+ export async function probeGh(execFn) {
472
+ try {
473
+ const { stdout } = await execFn('which', ['gh'], EXEC_OPTS)
474
+ const path = String(stdout == null ? '' : stdout).split('\n')[0].trim()
475
+ return path.length > 0 ? path : null
476
+ } catch {
477
+ return null
478
+ }
479
+ }
480
+
481
+ /**
482
+ * Survey one session's pull-request and CI status.
483
+ *
484
+ * Never throws for an environmental cause: a missing `gh`, a non-GitHub remote,
485
+ * a cwd that is not a repo and a `gh` invocation that fails all resolve to a
486
+ * snapshot carrying a `reason`. Absence is signal.
487
+ *
488
+ * @param {object} opts
489
+ * @param {string} opts.sessionId - the session this snapshot describes.
490
+ * @param {string|null|undefined} opts.cwd - the session's working directory.
491
+ * @param {Function} [opts._execFile] - promisified execFile seam.
492
+ * @param {Function} [opts._now] - Date factory seam.
493
+ * @returns {Promise<object>} the snapshot (minus the wire `type`/`requestId`,
494
+ * which the handler adds).
495
+ */
496
+ export async function surveySessionPrStatus({ sessionId, cwd, _execFile = execFileAsync, _now = () => new Date() } = {}) {
497
+ const snapshot = baseSnapshot(sessionId ?? null, _now().toISOString())
498
+
499
+ if (typeof cwd !== 'string' || cwd.length === 0) {
500
+ snapshot.reason = NO_CWD_REASON
501
+ return snapshot
502
+ }
503
+
504
+ const branchResult = await resolveBranch(_execFile, cwd)
505
+ if (branchResult.reason) {
506
+ snapshot.reason = branchResult.reason
507
+ return snapshot
508
+ }
509
+ snapshot.branch = branchResult.branch
510
+
511
+ // Branch and remote are useful on their own, so they are resolved before the
512
+ // `gh` probe: a host without `gh` still shows which branch the session is on.
513
+ const target = await resolveRepo(_execFile, cwd)
514
+ if (!target) {
515
+ snapshot.reason = NO_GITHUB_REMOTE_REASON
516
+ return snapshot
517
+ }
518
+ snapshot.repo = { owner: target.owner, name: target.repo }
519
+
520
+ const ghPath = await probeGh(_execFile)
521
+ if (!ghPath) {
522
+ snapshot.reason = GH_MISSING_REASON
523
+ return snapshot
524
+ }
525
+
526
+ // `-R <owner>/<repo>` comes from the git remote via parseGithubOwnerRepo, never
527
+ // from a client; `--head` is the branch, rejected above if it could be
528
+ // option-parsed. One call, so every field below describes one head SHA.
529
+ const args = [
530
+ 'pr', 'list',
531
+ '-R', `${target.owner}/${target.repo}`,
532
+ '--head', snapshot.branch,
533
+ '--state', 'open',
534
+ '--limit', '1',
535
+ '--json', PR_JSON_FIELDS,
536
+ ]
537
+
538
+ let stdout
539
+ try {
540
+ ;({ stdout } = await _execFile(ghPath, args, { ...EXEC_OPTS, cwd }))
541
+ } catch (err) {
542
+ // Deliberately NOT the raw message fallback. Unlike the Control Room
543
+ // surveys, this reply reaches a pairing-bound (share-a-session) client, and
544
+ // execFile's own message is `Command failed: <absolute gh path> ...` — a
545
+ // host filesystem path, often including the operator's username. gh's first
546
+ // stderr line is the useful part and carries no such path.
547
+ snapshot.reason = redactAbsolutePaths(execFailureReason(err, 'gh pr list'))
548
+ return snapshot
549
+ }
550
+
551
+ let rows
552
+ try {
553
+ rows = JSON.parse(String(stdout == null ? '' : stdout))
554
+ } catch {
555
+ snapshot.reason = 'gh pr list produced unparseable output'
556
+ return snapshot
557
+ }
558
+ if (!Array.isArray(rows)) {
559
+ snapshot.reason = 'gh pr list produced unparseable output'
560
+ return snapshot
561
+ }
562
+
563
+ // An empty array is NOT yet the quiet negative — it is also what a FORK
564
+ // checkout looks like. A cross-repository PR is listed on the BASE repo, not
565
+ // on the head repo, so `origin` (the fork) legitimately reports nothing while
566
+ // an open PR with running CI exists. Reporting "no PR" there would be
567
+ // confidently wrong in exactly the "lost in no man's land" case #7344 exists
568
+ // to remove.
569
+ //
570
+ // Measured against gh 2.97.0 before writing this, because the obvious fix is
571
+ // wrong: `--head owner:branch` against the base repo returns NOTHING. The base
572
+ // repo must be queried with the BARE branch name, and the row then
573
+ // disambiguated by `headRepositoryOwner` — two forks can have the same branch
574
+ // name open against one base, so `--limit 1` alone could return someone
575
+ // else's PR.
576
+ //
577
+ // Only a fork pays these two extra calls; the common same-repo case still
578
+ // makes exactly one.
579
+ if (rows.length === 0) {
580
+ const parentResult = await resolveParentRepo(_execFile, ghPath, target, cwd)
581
+ // A FAILED lookup did not establish absence. The wire fields stay the quiet
582
+ // negative (the display posture: a best-effort widening of an already-empty
583
+ // result must not downgrade a usable answer to "cannot determine"), but the
584
+ // server-side marker keeps the CI watcher from reading it as a fact (#7435).
585
+ if (parentResult.failed) {
586
+ return markIndeterminate(snapshot)
587
+ }
588
+ // gh answered: not a fork, so the empty origin result IS the quiet negative.
589
+ if (!parentResult.parent) return snapshot
590
+ const parent = parentResult.parent
591
+
592
+ let parentRows
593
+ try {
594
+ const { stdout: parentOut } = await _execFile(ghPath, [
595
+ 'pr', 'list',
596
+ '-R', `${parent.owner}/${parent.repo}`,
597
+ '--head', snapshot.branch,
598
+ '--state', 'open',
599
+ '--limit', String(FORK_QUERY_LIMIT),
600
+ '--json', PR_JSON_FIELDS,
601
+ ], { ...EXEC_OPTS, cwd })
602
+ parentRows = JSON.parse(String(parentOut == null ? '' : parentOut))
603
+ } catch {
604
+ return markIndeterminate(snapshot)
605
+ }
606
+ if (!Array.isArray(parentRows)) {
607
+ return markIndeterminate(snapshot)
608
+ }
609
+
610
+ const mine = parentRows.find(row => row?.headRepositoryOwner?.login === target.owner)
611
+ // The upstream answered and no open PR has our fork as its head: this is the
612
+ // authoritative quiet negative, exactly like an answered-empty origin list.
613
+ if (!mine) return snapshot
614
+
615
+ const forkNormalised = normalisePrRow(mine)
616
+ // Our row exists but is unusable — the identical condition the same-repo
617
+ // path reports as a reason, reported the same way (#7441). Unlike the
618
+ // widening bail-outs above this is not a best-effort lookup failing: the
619
+ // upstream ANSWERED and returned OUR row, so no usable partial answer is
620
+ // being protected, and a `reason` keeps `branch` and `repo` exactly as the
621
+ // quiet negative would. The `reason` alone makes the CI watcher hold its
622
+ // arm (#7435), so this site needs no `indeterminate` marker.
623
+ if (!forkNormalised) {
624
+ snapshot.reason = UNUSABLE_ROW_REASON
625
+ return snapshot
626
+ }
627
+ // `repo` names the repo the PR actually lives on, which is what the user
628
+ // needs in order to find it — for a fork that is the base, not `origin`.
629
+ //
630
+ // #7442: this spread relies on `indeterminate` being non-enumerable to keep
631
+ // it off the result — which is safe HERE ONLY because every branch above
632
+ // that marks a snapshot indeterminate returns before reaching this line.
633
+ // `forkNormalised` is truthy in this branch precisely because absence was
634
+ // NOT what happened — a real PR row was found — so `snapshot.indeterminate`
635
+ // is still its `baseSnapshot()` default (`false`) whenever this spread runs.
636
+ // A future edit that marks-then-falls-through here would rely on the
637
+ // non-enumerable definition alone to keep the (now-true) marker off the
638
+ // wire, same as the WS handler's reply — see session-pr-status.test.js's
639
+ // "never indeterminate on a found PR" coverage.
640
+ return { ...snapshot, repo: { owner: parent.owner, name: parent.repo }, ...forkNormalised }
641
+ }
642
+
643
+ const normalised = normalisePrRow(rows[0])
644
+ if (!normalised) {
645
+ snapshot.reason = UNUSABLE_ROW_REASON
646
+ return snapshot
647
+ }
648
+
649
+ // #7442: same reasoning as the fork spread above — this same-repo path only
650
+ // runs when `normalised` is truthy (a real PR row), so `snapshot.indeterminate`
651
+ // is always still `false` here. Never add an indeterminate bail-out above this
652
+ // line without checking this comment first.
653
+ return { ...snapshot, ...normalised }
654
+ }