@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,271 @@
1
+ /**
2
+ * Session → unresolved review-thread count (#7430, on-demand follow-on to #7344).
3
+ *
4
+ * #7423's prefill line wants "0 unresolved threads" beside the check rollup,
5
+ * because that number is what explains a `BLOCKED` merge state when CI is
6
+ * 21/21 green. `session_pr_status` cannot carry it: `gh pr list --json` has no
7
+ * thread count, and reading one needs a GraphQL `reviewThreads` query.
8
+ *
9
+ * ## Why this is a separate survey and not two more fields on that one
10
+ *
11
+ * Since #7426 `surveySessionPrStatus` runs on a daemon-side SWEEP across every
12
+ * session (`SessionCiWatcher`, on `tickIntervalMs`/`discoveryIntervalMs`), not
13
+ * only when a dashboard asks. Adding a second `gh` invocation there doubles the
14
+ * subprocess and network cost of a background poll — on every session, on every
15
+ * tick — to enrich a string that is only ever built when a user clicks. So the
16
+ * count is paid for at CLICK time, through its own request/reply pair that the
17
+ * sweep never sends. #7422's one-`gh`-call-per-head consistency rule is
18
+ * untouched: the sweep's survey still makes exactly the calls it made before.
19
+ *
20
+ * ## Resolution is DELEGATED, never re-derived
21
+ *
22
+ * Which repo, which branch, which PR number — that is `session-pr-status.js`'s
23
+ * question, and it has a lot of hard-won behaviour in it (a reaped worktree, a
24
+ * detached HEAD, a branch name that would be option-parsed, and the fork path
25
+ * where a cross-repository PR is listed on the BASE repo and must be
26
+ * disambiguated by head owner). A second implementation of that would drift, so
27
+ * this module CALLS it and inherits its degradation table wholesale: every
28
+ * reason `surveySessionPrStatus` can produce passes through here verbatim.
29
+ *
30
+ * The cost is one extra `gh pr list` per counted click. That is the deliberate
31
+ * trade against duplicating resolution logic, and the per-session throttle on
32
+ * the handler bounds how often it can be paid.
33
+ *
34
+ * ## Never a fabricated zero
35
+ *
36
+ * The one contract worth stating twice. A count that was not taken is
37
+ * `unresolvedCount: null` with a `reason` — never `0`. The two are not
38
+ * interchangeable and a consumer must render them differently: "0 unresolved
39
+ * threads" printed for a reading that never happened says "nothing is blocking
40
+ * this PR", which is the exact false green #7344 exists to prevent. The same
41
+ * applies to a TRUNCATED page: 100 resolved threads on page one with every
42
+ * unresolved one past it must not report a flat 0, so `truncated` rides along
43
+ * and a truncated count is a LOWER BOUND.
44
+ *
45
+ * Every external interaction is injectable so tests never touch real git/gh:
46
+ * - `_execFile(file, args, opts)` — async, resolves `{ stdout, stderr }`.
47
+ * - `_now()` — returns a `Date` (defaults to `new Date()`).
48
+ * - `_survey(opts)` — the PR resolution, defaults to `surveySessionPrStatus`.
49
+ */
50
+
51
+ import { execFile } from 'child_process'
52
+ import { promisify } from 'util'
53
+ import {
54
+ surveySessionPrStatus,
55
+ probeGh,
56
+ redactAbsolutePaths,
57
+ EXEC_OPTS,
58
+ GH_MISSING_REASON,
59
+ } from './session-pr-status.js'
60
+ import { execFailureReason } from './utils/exec-failure-reason.js'
61
+ import { isSafeArgvValue } from './utils/argv-safety.js'
62
+
63
+ const execFileAsync = promisify(execFile)
64
+
65
+ /**
66
+ * How many review threads one page reads.
67
+ *
68
+ * 100 is GitHub's per-connection maximum for a single `first:` argument, so
69
+ * this is the most one call can see. Beyond it the reading is a lower bound and
70
+ * says so (`truncated`) rather than paginating: a PR with >100 review threads
71
+ * is far outside the case this line serves, and a paging loop would put an
72
+ * unbounded number of `gh` calls behind one click.
73
+ */
74
+ export const REVIEW_THREAD_PAGE_SIZE = 100
75
+
76
+ /**
77
+ * The GraphQL document. Written with variables (never string-interpolated), so
78
+ * the owner/name/number data cannot alter the query's shape.
79
+ *
80
+ * `totalCount` and `pageInfo.hasNextPage` are both requested deliberately —
81
+ * either one alone establishes whether the page is complete, and a reading that
82
+ * has NEITHER is treated as unusable rather than as complete.
83
+ */
84
+ export const REVIEW_THREADS_QUERY = [
85
+ 'query($owner: String!, $name: String!, $number: Int!, $first: Int!) {',
86
+ ' repository(owner: $owner, name: $name) {',
87
+ ' pullRequest(number: $number) {',
88
+ ' reviewThreads(first: $first) {',
89
+ ' totalCount',
90
+ ' pageInfo { hasNextPage }',
91
+ ' nodes { isResolved }',
92
+ ' }',
93
+ ' }',
94
+ ' }',
95
+ '}',
96
+ ].join('\n')
97
+
98
+ /** Reason when the branch definitively has no open PR to count threads on. */
99
+ export const NO_OPEN_PR_REASON = 'no open pull request for this branch — no review threads to count'
100
+
101
+ /** Reason when the resolved repo owner/name is not safe for an option-parsed argv slot. */
102
+ export const UNSAFE_REPO_REASON = 'repository owner or name cannot be passed safely to gh'
103
+
104
+ /** Reason when `gh api graphql` answered with something that is not JSON. */
105
+ export const UNPARSEABLE_REASON = 'gh api graphql produced unparseable output'
106
+
107
+ /** Reason when the response parsed but carried no usable review-thread data. */
108
+ export const NO_THREAD_DATA_REASON = 'gh api graphql returned no usable review-thread data'
109
+
110
+ /**
111
+ * Reduce a `gh api graphql` response to `{ unresolvedCount, totalCount, truncated }`,
112
+ * or `null` when the response cannot be trusted to answer the question.
113
+ *
114
+ * Returning `null` is not a formality — it is the only alternative to guessing,
115
+ * and every guess available here is a guess in the dangerous direction (an
116
+ * unreadable node absorbed as "resolved", a partial response counted as whole,
117
+ * an unknown page state read as complete). Each of those under-reports
118
+ * unresolved threads, i.e. manufactures the green.
119
+ *
120
+ * @param {unknown} payload - the parsed `gh api graphql` JSON.
121
+ * @returns {{ unresolvedCount: number, totalCount: number|null, truncated: boolean }|null}
122
+ */
123
+ export function summariseReviewThreads(payload) {
124
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null
125
+ // GitHub can answer with data AND errors; the data is then partial, and
126
+ // counting what survived under-reports. Refuse the whole reading.
127
+ if (Array.isArray(payload.errors) && payload.errors.length > 0) return null
128
+
129
+ const threads = payload?.data?.repository?.pullRequest?.reviewThreads
130
+ if (!threads || typeof threads !== 'object' || Array.isArray(threads)) return null
131
+ const nodes = threads.nodes
132
+ if (!Array.isArray(nodes)) return null
133
+
134
+ let unresolvedCount = 0
135
+ for (const node of nodes) {
136
+ // `isResolved` is `Boolean!` in GitHub's schema, so anything else means the
137
+ // response is not what was asked for. Treating it as resolved would hide a
138
+ // thread; treating it as unresolved would invent one.
139
+ if (!node || typeof node !== 'object' || typeof node.isResolved !== 'boolean') return null
140
+ if (!node.isResolved) unresolvedCount += 1
141
+ }
142
+
143
+ const rawTotal = threads.totalCount
144
+ const totalCount = Number.isInteger(rawTotal) && rawTotal >= 0 ? rawTotal : null
145
+ const hasNextPage = threads?.pageInfo?.hasNextPage
146
+
147
+ let truncated
148
+ if (hasNextPage === true) truncated = true
149
+ else if (hasNextPage === false) truncated = totalCount !== null && totalCount > nodes.length
150
+ else if (totalCount !== null) truncated = totalCount > nodes.length
151
+ // Neither signal is readable: completeness was never established, so it must
152
+ // not be assumed. "Cannot check" is not "nothing to check".
153
+ else return null
154
+
155
+ return { unresolvedCount, totalCount, truncated }
156
+ }
157
+
158
+ /** The skeleton every return path shares — a count-shaped nothing. */
159
+ function baseSnapshot(sessionId, countedAt) {
160
+ return {
161
+ sessionId,
162
+ countedAt,
163
+ prNumber: null,
164
+ unresolvedCount: null,
165
+ totalCount: null,
166
+ truncated: false,
167
+ reason: null,
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Count the session PR's unresolved review threads.
173
+ *
174
+ * Never throws for an environmental cause: an unresolvable PR, a missing `gh`,
175
+ * a failed or unparseable call all resolve to a snapshot carrying a `reason`
176
+ * and a null count.
177
+ *
178
+ * @param {object} opts
179
+ * @param {string} opts.sessionId - the session this reading describes.
180
+ * @param {string|null|undefined} opts.cwd - the session's working directory.
181
+ * @param {Function} [opts._execFile] - promisified execFile seam.
182
+ * @param {Function} [opts._now] - Date factory seam.
183
+ * @param {Function} [opts._survey] - PR resolution seam.
184
+ * @returns {Promise<object>} the reading (minus the wire `type`/`requestId`,
185
+ * which the handler adds).
186
+ */
187
+ export async function surveySessionPrThreads({
188
+ sessionId,
189
+ cwd,
190
+ _execFile = execFileAsync,
191
+ _now = () => new Date(),
192
+ _survey = surveySessionPrStatus,
193
+ } = {}) {
194
+ // Stamped when the reading STARTS, matching `generatedAt`'s convention on the
195
+ // status snapshot — but a field of its own, because the two go stale on
196
+ // different schedules and one timestamp over both would claim a consistency
197
+ // neither message has.
198
+ const snapshot = baseSnapshot(sessionId ?? null, _now().toISOString())
199
+
200
+ const status = await _survey({ sessionId, cwd, _execFile, _now })
201
+
202
+ // Resolution failed and already said why, in the vocabulary the status chip
203
+ // uses. Repeating it in different words here would make the same condition
204
+ // read as two different problems.
205
+ if (status?.reason) {
206
+ snapshot.reason = status.reason
207
+ return snapshot
208
+ }
209
+ if (!status?.pr || !status?.repo) {
210
+ snapshot.reason = NO_OPEN_PR_REASON
211
+ return snapshot
212
+ }
213
+
214
+ const { owner, name } = status.repo
215
+ const number = status.pr.number
216
+ // Named even when the count fails, so a consumer can tell WHICH PR it has no
217
+ // count for — and refuse to print a count next to a different PR's number.
218
+ snapshot.prNumber = number
219
+
220
+ // These come from the git remote via parseGithubOwnerRepo rather than from a
221
+ // client, but they go into option-parsed argv slots, so they are checked like
222
+ // any other argv datum (argv-safety.js, fix shape 1).
223
+ if (!isSafeArgvValue(owner) || !isSafeArgvValue(name)) {
224
+ snapshot.reason = UNSAFE_REPO_REASON
225
+ return snapshot
226
+ }
227
+
228
+ const ghPath = await probeGh(_execFile)
229
+ if (!ghPath) {
230
+ snapshot.reason = GH_MISSING_REASON
231
+ return snapshot
232
+ }
233
+
234
+ // Every datum rides in a `key=value` token, so none of them can begin with a
235
+ // `-` even in principle, and the query itself is a constant.
236
+ const args = [
237
+ 'api', 'graphql',
238
+ '-f', `query=${REVIEW_THREADS_QUERY}`,
239
+ '-f', `owner=${owner}`,
240
+ '-f', `name=${name}`,
241
+ '-F', `number=${number}`,
242
+ '-F', `first=${REVIEW_THREAD_PAGE_SIZE}`,
243
+ ]
244
+
245
+ let stdout
246
+ try {
247
+ ;({ stdout } = await _execFile(ghPath, args, { ...EXEC_OPTS, cwd }))
248
+ } catch (err) {
249
+ // This reply reaches a pairing-bound (share-a-session) client, which has no
250
+ // business learning host filesystem layout — and execFile's own message is
251
+ // `Command failed: <absolute gh path> …`.
252
+ snapshot.reason = redactAbsolutePaths(execFailureReason(err, 'gh api graphql'))
253
+ return snapshot
254
+ }
255
+
256
+ let parsed
257
+ try {
258
+ parsed = JSON.parse(String(stdout == null ? '' : stdout))
259
+ } catch {
260
+ snapshot.reason = UNPARSEABLE_REASON
261
+ return snapshot
262
+ }
263
+
264
+ const summary = summariseReviewThreads(parsed)
265
+ if (!summary) {
266
+ snapshot.reason = NO_THREAD_DATA_REASON
267
+ return snapshot
268
+ }
269
+
270
+ return { ...snapshot, ...summary }
271
+ }
@@ -38,11 +38,11 @@
38
38
  import { existsSync } from 'fs'
39
39
  import { createLogger } from './logger.js'
40
40
  import { PathHashTrustLedger } from './path-hash-trust-ledger.js'
41
- import { DEFAULT_PRESET_TRUST_FILE, _normalizePathKey } from './session-preset.js'
41
+ import { defaultPresetTrustFile, _normalizePathKey } from './session-preset.js'
42
42
 
43
43
  const log = createLogger('session-preset-trust')
44
44
 
45
- export { DEFAULT_PRESET_TRUST_FILE }
45
+ export { defaultPresetTrustFile }
46
46
 
47
47
  /**
48
48
  * In-memory + on-disk trust ledger for repo-local session presets. One
@@ -55,7 +55,7 @@ export class SessionPresetTrustStore extends PathHashTrustLedger {
55
55
  */
56
56
  constructor({ filePath } = {}) {
57
57
  super({
58
- filePath: filePath || DEFAULT_PRESET_TRUST_FILE,
58
+ filePath: filePath || defaultPresetTrustFile(),
59
59
  log,
60
60
  normalizeKey: _normalizePathKey,
61
61
  approvalField: 'approvedAt',
@@ -39,6 +39,7 @@ import { dirname, join, resolve, basename } from 'path'
39
39
  import { homedir } from 'os'
40
40
  import { createHash } from 'crypto'
41
41
  import { createLogger } from './logger.js'
42
+ import { configPath } from './config-dir.js'
42
43
 
43
44
  const log = createLogger('session-preset')
44
45
 
@@ -63,8 +64,12 @@ const MAX_PRESET_FILE_BYTES = 64 * 1024
63
64
  // Cap walk-up iterations — a safety belt; real repos are nowhere near this deep.
64
65
  const REPO_DISCOVERY_MAX_DEPTH = 100
65
66
 
66
- export const DEFAULT_CONFIG_PATH = join(homedir(), '.chroxy', 'config.json')
67
- export const DEFAULT_PRESET_TRUST_FILE = join(homedir(), '.chroxy', 'session-preset-trust.json')
67
+ export function defaultConfigPath() {
68
+ return configPath('config.json')
69
+ }
70
+ export function defaultPresetTrustFile() {
71
+ return configPath('session-preset-trust.json')
72
+ }
68
73
 
69
74
  const _PATH_COMPARE_CASE_INSENSITIVE =
70
75
  process.platform === 'darwin' || process.platform === 'win32'
@@ -321,7 +326,7 @@ export function readRepoPresetFile(absPath) {
321
326
  * @param {string} [configPath]
322
327
  * @returns {object|null}
323
328
  */
324
- export function _findRepoConfigEntry(repoPath, configPath = DEFAULT_CONFIG_PATH) {
329
+ export function _findRepoConfigEntry(repoPath, configPath = defaultConfigPath()) {
325
330
  if (!repoPath || typeof repoPath !== 'string') return null
326
331
  let raw
327
332
  try {
@@ -351,7 +356,7 @@ function _resolveSafe(p) {
351
356
  * @param {string} [configPath]
352
357
  * @returns {null | ReturnType<typeof validatePreset>}
353
358
  */
354
- export function readDaemonOverride(repoPath, configPath = DEFAULT_CONFIG_PATH) {
359
+ export function readDaemonOverride(repoPath, configPath = defaultConfigPath()) {
355
360
  const entry = _findRepoConfigEntry(repoPath, configPath)
356
361
  if (!entry || !entry.sessionPreset) return null
357
362
  return validatePreset(entry.sessionPreset)
@@ -393,7 +398,7 @@ export function readDaemonOverride(repoPath, configPath = DEFAULT_CONFIG_PATH) {
393
398
  */
394
399
  export function resolveSessionPreset(cwd, opts = {}) {
395
400
  const trustStore = opts.trustStore || null
396
- const configPath = opts.configPath || DEFAULT_CONFIG_PATH
401
+ const configPath = opts.configPath || defaultConfigPath()
397
402
 
398
403
  // 1. Locate the repo root (the dir holding `.chroxy/session.json`) via the
399
404
  // walk-up. We need it for BOTH the repo-file read and the daemon override
@@ -1,7 +1,9 @@
1
1
  import fs from 'fs'
2
+ import { performance } from 'perf_hooks'
2
3
  import { dirname } from 'path'
3
4
  import { isWindows, writeFileRestricted } from './platform.js'
4
5
  import { createLogger } from './logger.js'
6
+ import { savedHasHistory } from './session-archive-limits.js'
5
7
 
6
8
  const log = createLogger('session-state-persistence')
7
9
 
@@ -21,14 +23,24 @@ export class SessionStatePersistence {
21
23
  * @param {string} options.stateFilePath - Path to session state JSON file
22
24
  * @param {number} [options.stateTtlMs=86400000] - Max age of persisted state before discard (default: 24 hours)
23
25
  * @param {number} [options.persistDebounceMs=2000] - Debounce interval for state file writes
26
+ * @param {number} [options.persistMaxWaitMs=10000] - Upper bound on how long a pending write may be postponed by a continuous stream of schedulePersist calls
27
+ * @param {() => number} [options.now] - Monotonic millisecond clock for the max-wait window (default: performance.now). Must not be wall-clock time: setTimeout is monotonic, so a wall-clock rollback would otherwise stretch the window
24
28
  * @param {boolean} [options.isWindowsOverride] - Test-only: force Windows-specific branches regardless of host platform
25
29
  */
26
- constructor({ stateFilePath, stateTtlMs, persistDebounceMs = 2000, isWindowsOverride } = {}) {
30
+ constructor({ stateFilePath, stateTtlMs, persistDebounceMs = 2000, persistMaxWaitMs = 10_000, now = () => performance.now(), isWindowsOverride } = {}) {
27
31
  this._stateFilePath = stateFilePath
28
32
  this._stateTtlMs = stateTtlMs ?? 24 * 60 * 60 * 1000
29
33
  this._persistDebounceMs = persistDebounceMs
34
+ this._persistMaxWaitMs = persistMaxWaitMs
35
+ this._now = now
30
36
  this._persistTimer = null
37
+ /** @type {number|null} monotonic time at which the armed timer is due */
38
+ this._persistDueAt = null
39
+ /** @type {number|null} when the oldest unwritten schedulePersist call arrived (max-wait anchor) */
40
+ this._persistPendingSince = null
31
41
  this._isWindows = isWindowsOverride ?? isWindows
42
+ /** @type {string|null} the last write's unconfirmed-durability verdict (see serializeState) */
43
+ this.lastDurabilityUnconfirmed = null
32
44
  }
33
45
 
34
46
  /**
@@ -66,9 +78,13 @@ export class SessionStatePersistence {
66
78
  * `.bak` (rotate failed). `writeFileSync` on Windows overwrites either way.
67
79
  *
68
80
  * @param {object} state - The complete state object to write (version, timestamp, sessions, costs, etc.)
81
+ * @param {{ durable?: boolean }} [opts] - `durable` fsyncs the temp file before the rename, for
82
+ * a caller about to drop its only other copy of the data (#8866)
69
83
  * @returns {object} The state that was written
70
84
  */
71
- serializeState(state) {
85
+ serializeState(state, { durable = false } = {}) {
86
+ // Reset first: a throw before the write must not leave a previous verdict.
87
+ this.lastDurabilityUnconfirmed = null
72
88
  const dir = dirname(this._stateFilePath)
73
89
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
74
90
  const bakPath = this._stateFilePath + '.bak'
@@ -91,7 +107,11 @@ export class SessionStatePersistence {
91
107
  // hard-kill mid-write (between writeFileSync and renameSync) is never
92
108
  // reused by a later process and no sweeper reclaims it. Accepted: such
93
109
  // mid-write hard-kills are rare and the sidecar is tiny (matches models.js).
94
- writeFileRestricted(this._stateFilePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}` })
110
+ const written = writeFileRestricted(this._stateFilePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}`, durable })
111
+ // A post-rename directory-fsync failure does NOT throw: the file is live but
112
+ // its durability is unproven. Keep the verdict for callers that drop another
113
+ // copy on the strength of this write (`SessionManager._flushPersistConfirmedDurable`).
114
+ this.lastDurabilityUnconfirmed = written?.durabilityUnconfirmed ?? null
95
115
  log.info(`Serialized ${state.sessions?.length ?? 0} session(s) to ${this._stateFilePath}`)
96
116
  return state
97
117
  }
@@ -207,12 +227,28 @@ export class SessionStatePersistence {
207
227
  const now = Date.now()
208
228
  const fresh = []
209
229
  const dropped = []
230
+ // #7627 — the stale ENTRIES, not just their names. They are SET ASIDE, not
231
+ // deleted: the log below says so, because "Dropped" described the old
232
+ // behaviour and reading it as deletion is what made this defect invisible. A stale session is still
233
+ // not restored (that is the policy this filter exists for), but this layer
234
+ // cannot tell a session that would restore fine from one whose restore will
235
+ // REFUSE and whose history the #2954 contract promises to preserve. Only
236
+ // SessionManager knows that, so hand the entries over instead of deleting
237
+ // them here and let it decide. Deleting them here made the failed-restore
238
+ // TTL (30 days) unreachable for anything last active more than 24h ago.
239
+ const stale = []
210
240
  for (const saved of state.sessions) {
211
241
  const activityAt = (typeof saved.lastActivityAt === 'number' && saved.lastActivityAt > 0)
212
242
  ? saved.lastActivityAt
213
243
  : state.timestamp
214
- if (activityAt && now - activityAt > this._stateTtlMs) {
244
+ // #8870 — a session with no history is restored at any age. Setting it
245
+ // aside would end in the archive skipping it (nothing to read), so it
246
+ // left the list with no record: the startup "Default" vanished after a
247
+ // restart. It holds only its name, cwd, provider and settings, so it is
248
+ // restored like a recent session and leaves the way any live one does.
249
+ if (activityAt && now - activityAt > this._stateTtlMs && savedHasHistory(saved)) {
215
250
  dropped.push(saved.name || saved.id || '<unknown>')
251
+ stale.push(saved)
216
252
  } else {
217
253
  fresh.push(saved)
218
254
  }
@@ -225,18 +261,29 @@ export class SessionStatePersistence {
225
261
  const MAX_NAMES = 10
226
262
  const sample = dropped.slice(0, MAX_NAMES).map((n) => JSON.stringify(String(n)))
227
263
  const more = dropped.length > MAX_NAMES ? `, …+${dropped.length - MAX_NAMES} more` : ''
228
- log.warn(`Dropped ${dropped.length} stale session(s) (>${Math.round(this._stateTtlMs / 60000)}min since last activity): ${sample.join(', ')}${more}`)
229
- }
230
- if (fresh.length === 0) {
231
- log.info('All restored sessions are stale, starting fresh')
232
- return null
264
+ log.warn(`Set aside ${dropped.length} stale session(s), not restored (>${Math.round(this._stateTtlMs / 60000)}min since last activity): ${sample.join(', ')}${more}`)
233
265
  }
266
+ // NOTE: there is deliberately no `fresh.length === 0` early return here.
267
+ // #7627 made one unreachable — the guard above returns for an empty
268
+ // `state.sessions`, and the loop partitions a non-empty one into
269
+ // `fresh ∪ stale` — so it would have been dead code, and the all-stale case
270
+ // is now a legitimate result carrying entries for SessionManager to
271
+ // adjudicate. The warn above already reports it.
234
272
  state.sessions = fresh
273
+ // #7627: carried separately so the normal restore path sees EXACTLY what it
274
+ // saw before — `state.sessions` is still the fresh set and nothing downstream
275
+ // has to learn about staleness to keep working.
276
+ state.staleSessions = stale
235
277
  return state
236
278
  }
237
279
 
238
280
  /**
239
- * Schedule a debounced persist. Multiple rapid calls reset the timer.
281
+ * Schedule a debounced persist with a max-wait. Calls arriving within
282
+ * persistDebounceMs of each other coalesce into one trailing write, but the
283
+ * write is never postponed past persistMaxWaitMs after the FIRST unwritten
284
+ * call (#8954). Without the max-wait a pure trailing debounce was reset by
285
+ * every append, so a long continuously-streaming turn wrote nothing until it
286
+ * ended.
240
287
  *
241
288
  * #5309 (WP-0.3) — durability boundary, by design: this debounce backs
242
289
  * high-frequency message-history appends only. Session-LIST mutations
@@ -244,25 +291,53 @@ export class SessionStatePersistence {
244
291
  * every CLEAN exit path serializes immediately — SIGINT/SIGTERM (server-cli.js)
245
292
  * and the supervised IPC shutdown + crash handlers (server-cli-child.js, #5308)
246
293
  * all call serializeState() directly (followed by destroyAll(), which cancels
247
- * this timer and no-ops any stray fire). So the only way to lose up to
248
- * persistDebounceMs (2s) of
249
- * message history is an abrupt kill that runs NO handler at all — SIGKILL,
250
- * OOM-kill, or power loss. That window is accepted as best-effort: shrinking
251
- * it trades constant write amplification on every token for protection against
252
- * an unrecoverable kill we can't flush before anyway.
294
+ * this timer and no-ops any stray fire). So the only way to lose message
295
+ * history is an abrupt kill that runs NO handler at all — SIGKILL, OOM-kill,
296
+ * or power loss. The real bound on that loss is persistMaxWaitMs (default 10s)
297
+ * of history, NOT persistDebounceMs: during a continuous stream the debounce
298
+ * alone never fires, and the max-wait is what forces a write. That window is
299
+ * accepted as best-effort: shrinking it further trades constant write
300
+ * amplification on every token for protection against a kill we can't flush
301
+ * before anyway.
302
+ *
303
+ * Implemented with a single timer (delay = min(debounce, time left until the
304
+ * max-wait deadline), clamped at 0), so clearing `_persistTimer` cancels
305
+ * everything.
306
+ * Elapsed time comes from a MONOTONIC clock (`now`), the same time base as
307
+ * setTimeout, so a wall-clock rollback cannot stretch the window. A timer
308
+ * that is already due is never cancelled and re-armed: a call that runs
309
+ * before the overdue callback would otherwise keep pushing it back by Node's
310
+ * minimum delay and starve the write.
311
+ *
312
+ * The max-wait bounds postponement BY SCHEDULING CALLS only. It is not an
313
+ * absolute data-loss bound: the write still depends on the event loop running
314
+ * the callback and on serializeFn succeeding.
253
315
  *
254
316
  * @param {() => void} serializeFn - Function to call when the debounce fires
255
317
  */
256
318
  schedulePersist(serializeFn) {
319
+ const now = this._now()
320
+ if (this._persistTimer === null || this._persistPendingSince === null) {
321
+ this._persistPendingSince = now
322
+ this._persistDueAt = null
323
+ }
324
+ // Already due (or due at/after the deadline): leave it alone.
325
+ if (this._persistTimer !== null && this._persistDueAt !== null && this._persistDueAt <= now) return
326
+ const deadline = this._persistPendingSince + this._persistMaxWaitMs
327
+ if (this._persistTimer !== null && now >= deadline) return
257
328
  clearTimeout(this._persistTimer)
329
+ const delay = Math.max(0, Math.min(this._persistDebounceMs, deadline - now))
330
+ this._persistDueAt = now + delay
258
331
  this._persistTimer = setTimeout(() => {
259
332
  this._persistTimer = null
333
+ this._persistPendingSince = null
334
+ this._persistDueAt = null
260
335
  try {
261
336
  serializeFn()
262
337
  } catch (err) {
263
338
  log.error(`Failed to persist session state: ${err?.stack || err}`)
264
339
  }
265
- }, this._persistDebounceMs)
340
+ }, delay)
266
341
  }
267
342
 
268
343
  /**
@@ -271,6 +346,8 @@ export class SessionStatePersistence {
271
346
  cancelPersist() {
272
347
  clearTimeout(this._persistTimer)
273
348
  this._persistTimer = null
349
+ this._persistPendingSince = null
350
+ this._persistDueAt = null
274
351
  }
275
352
 
276
353
  /**
@@ -18,6 +18,26 @@ export function formatIdleDuration(ms) {
18
18
  return minutes > 0 ? `${hPart} ${minutes} minute${minutes !== 1 ? 's' : ''}` : hPart
19
19
  }
20
20
 
21
+ /**
22
+ * #8223: like `formatIdleDuration`, but for a duration a message states as a FACT
23
+ * ("no response within …") rather than a rough idle window. `formatIdleDuration`
24
+ * rounds to the nearest minute, so the 90s first-output watchdog read "2 minutes"
25
+ * — a 33% overstatement. Here a value between a minute and an hour that is not a
26
+ * whole number of minutes keeps its seconds ("90 seconds"); whole minutes ("5
27
+ * minutes"), sub-minute values and hours format exactly as `formatIdleDuration`
28
+ * does, so the two only disagree where the rounding was wrong.
29
+ *
30
+ * `formatIdleDuration` itself is left alone: it has ~20 call sites and
31
+ * session-manager.test.js pins 90000 -> "2 minutes" for the idle-timeout copy.
32
+ */
33
+ export function formatWatchdogDuration(ms) {
34
+ const totalSeconds = Math.round(ms / 1000)
35
+ if (totalSeconds > 60 && totalSeconds < 3600 && totalSeconds % 60 !== 0) {
36
+ return `${totalSeconds} seconds`
37
+ }
38
+ return formatIdleDuration(ms)
39
+ }
40
+
21
41
  /**
22
42
  * Manages session idle timeouts independently of session lifecycle.
23
43
  *