@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,48 @@
1
+ /**
2
+ * Request authority for work that outlives the frame that asked for it.
3
+ *
4
+ * A handler (or a manager it calls) that waits — on a lock, a scan, a trust
5
+ * prompt, a subprocess — keeps the connection record it started with after the
6
+ * connection's credential has been revoked or has expired. `isAuthorized` is the
7
+ * ONE mechanism for carrying that authority into such deferred work: a
8
+ * zero-argument function, true while the requesting connection is still
9
+ * authenticated with a valid credential. Code that has waited calls
10
+ * `assertAuthorized(isAuthorized)` IMMEDIATELY before starting each mutation.
11
+ * Absent (internal callers, timers, tests) means "not tied to a connection".
12
+ *
13
+ * A function rather than an abort signal because expiry is time-based: a token
14
+ * can lapse between sweeps, with no event to abort on, and the check must see it.
15
+ */
16
+
17
+ export const AUTHORITY_REVOKED = 'CONNECTION_AUTHORITY_REVOKED'
18
+
19
+ export class AuthorityRevokedError extends Error {
20
+ constructor() {
21
+ super('The requesting connection is no longer authorized; the operation was not started')
22
+ this.name = 'AuthorityRevokedError'
23
+ this.code = AUTHORITY_REVOKED
24
+ }
25
+ }
26
+
27
+ /** True when `isAuthorized` is absent or reports the connection still authorized. */
28
+ export function stillAuthorized(isAuthorized) {
29
+ return typeof isAuthorized !== 'function' || isAuthorized() !== false
30
+ }
31
+
32
+ /** Throw AuthorityRevokedError unless the requesting connection is still authorized. */
33
+ export function assertAuthorized(isAuthorized) {
34
+ if (!stillAuthorized(isAuthorized)) throw new AuthorityRevokedError()
35
+ }
36
+
37
+ export function isAuthorityRevoked(err) {
38
+ return err?.code === AUTHORITY_REVOKED
39
+ }
40
+
41
+ /**
42
+ * The `isAuthorized` function for the connection behind `client`, built from the
43
+ * handler context. A hand-built context without the hook (tests) is never
44
+ * revoked; the production context always carries it (assertCtxShape).
45
+ */
46
+ export function authorizedFor(ctx, client) {
47
+ return () => ctx?.transport?.isConnectionAuthorized?.(client) ?? true
48
+ }
@@ -1,20 +1,16 @@
1
- import { homedir } from 'os'
2
1
  import { join } from 'path'
3
2
  import { existsSync, readFileSync, unlinkSync, mkdirSync } from 'fs'
4
3
  import { writeFileRestricted } from './platform.js'
5
-
6
- function getConfigDir() {
7
- return process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
8
- }
4
+ import { configDir, configPath } from './config-dir.js'
9
5
 
10
6
  export function getConnectionInfoPath() {
11
- return join(getConfigDir(), 'connection.json')
7
+ return configPath('connection.json')
12
8
  }
13
9
 
14
10
  export function writeConnectionInfo(info) {
15
- const configDir = getConfigDir()
16
- mkdirSync(configDir, { recursive: true })
17
- writeFileRestricted(join(configDir, 'connection.json'), JSON.stringify(info, null, 2))
11
+ const dir = configDir()
12
+ mkdirSync(dir, { recursive: true })
13
+ writeFileRestricted(join(dir, 'connection.json'), JSON.stringify(info, null, 2))
18
14
  }
19
15
 
20
16
  export function readConnectionInfo() {
@@ -21,6 +21,7 @@
21
21
  * this classification — it's a pure transport-efficiency hint.
22
22
  */
23
23
 
24
+ import { isIPv4 } from 'node:net'
24
25
  import { isLoopbackHost } from './bind-host.js'
25
26
  import { isPrivateOrSpecialIp } from './ssrf-guard.js'
26
27
 
@@ -53,3 +54,62 @@ export function isLocalOrLanPeer(req) {
53
54
  if (isPrivateOrSpecialIp(socketIp)) return true
54
55
  return false
55
56
  }
57
+
58
+ /**
59
+ * Strict loopback parse for AUTHORIZATION use. Not `isLoopbackHost`, which is a
60
+ * bind-host helper that accepts anything starting `::ffff:7f` — so
61
+ * `::ffff:7f00:1:2`, which is not an address at all, would pass. Accepts exactly:
62
+ * - a dotted IPv4 literal in 127.0.0.0/8,
63
+ * - `::1`,
64
+ * - an IPv4-mapped `::ffff:a.b.c.d` whose dotted part is in 127.0.0.0/8.
65
+ */
66
+ function isStrictLoopbackAddress(ip) {
67
+ const addr = ip.toLowerCase()
68
+ if (isIPv4(addr)) return addr.split('.')[0] === '127'
69
+ if (addr === '::1') return true
70
+ const mapped = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(addr)
71
+ return !!mapped && isIPv4(mapped[1]) && mapped[1].split('.')[0] === '127'
72
+ }
73
+
74
+ /**
75
+ * Any header a tunnel, CDN or reverse proxy leaves behind. Wider than
76
+ * `hasProxyHeaders` on purpose: Cloudflare can strip the visitor-IP headers
77
+ * (a managed transform), and then `cf-connecting-ip` is absent on a request
78
+ * that very much came through the tunnel. What survives is the rest of the
79
+ * family — `cf-ray`, `cf-visitor`, `cdn-loop`, `x-forwarded-proto`. Presence of
80
+ * the NAME is the test; the value is never trusted.
81
+ */
82
+ function hasAnyProxyHint(headers) {
83
+ if (!headers) return false
84
+ for (const name of Object.keys(headers)) {
85
+ const n = name.toLowerCase()
86
+ if (n.startsWith('cf-') || n.startsWith('cdn-loop') || n.startsWith('forwarded') ||
87
+ n.startsWith('x-forwarded-') || n === 'x-real-ip') return true
88
+ }
89
+ return false
90
+ }
91
+
92
+ /**
93
+ * Is this request a loopback peer that carries no sign of a proxy? (#8324)
94
+ *
95
+ * It does NOT prove direct local origin. It rejects a request whose socket is
96
+ * not loopback, and any request carrying a proxy-family header (see
97
+ * `hasAnyProxyHint`); a proxy that strips EVERY such header, or a local process
98
+ * that forwards traffic for a remote party without adding one, passes it. So it
99
+ * is defence in depth for the local-only `/api/daemon/idle` probe, and the
100
+ * primary bearer token is the authority.
101
+ *
102
+ * Stricter than `isLocalOrLanPeer`, which is a transport-efficiency hint with
103
+ * no security property riding on it: the socket address is parsed strictly, and
104
+ * ANY proxy-family header disqualifies the request. cloudflared connects to the
105
+ * daemon from 127.0.0.1, so the socket address alone proves nothing.
106
+ *
107
+ * @param {object} req - Node IncomingMessage.
108
+ * @returns {boolean}
109
+ */
110
+ export function isLoopbackPeer(req) {
111
+ const socketIp = req?.socket?.remoteAddress
112
+ if (typeof socketIp !== 'string' || socketIp.length === 0) return false
113
+ if (hasAnyProxyHint(req.headers)) return false
114
+ return isStrictLoopbackAddress(socketIp)
115
+ }
@@ -0,0 +1,189 @@
1
+ import { createLogger } from './logger.js'
2
+
3
+ const log = createLogger('container-liveness')
4
+
5
+ /**
6
+ * #7601 — how often the proactive poll inspects each live containerized session's
7
+ * container. The reactive #7599 paths already catch a vanish that happens
8
+ * DURING a turn (SDK query reject) or that closes a live exec child (CLI); this
9
+ * poll is the ONLY thing that catches an IDLE session whose container was stopped
10
+ * EXTERNALLY (a plain `docker stop`, which emits no chroxy event), and it is what
11
+ * gives a no-long-lived-process session (docker-byok, #7600) any idle
12
+ * detection at all. 30s balances "surface before the user's
13
+ * next turn" against the cost of one `docker inspect` per distinct container.
14
+ */
15
+ export const DEFAULT_LIVENESS_INTERVAL_MS = 30_000
16
+
17
+ /**
18
+ * #7620 — describe an out-of-contract verdict for the log WITHOUT trusting it.
19
+ *
20
+ * The verdict comes from the very injection seam the guard below exists to
21
+ * distrust, so a bare `JSON.stringify` is not safe: it THROWS on a circular
22
+ * object (the raw `docker inspect` blob a mis-implemented seam is most likely to
23
+ * forward) and on a BigInt. That throw would escape the per-target try into the
24
+ * tick's outer catch — replacing the diagnostic that justifies warning at all
25
+ * with a generic line, AND releasing the `_ticking` latch while other
26
+ * containers' inspects are still in flight, so the next tick re-inspects them.
27
+ * Total by construction: every branch returns a string and none can throw.
28
+ */
29
+ function describeVerdict(verdict) {
30
+ try {
31
+ return JSON.stringify(verdict) ?? String(verdict)
32
+ } catch {
33
+ return `[unserialisable ${typeof verdict}]`
34
+ }
35
+ }
36
+
37
+ /**
38
+ * ContainerLivenessMonitor — a periodic, unref'd `docker inspect` poll over the
39
+ * live containerized sessions, surfacing CONTAINER_VANISHED (#7599) on any whose
40
+ * container has been stopped or removed underneath it.
41
+ *
42
+ * Deliberately docker-agnostic: it takes an `enumerate` fn (the live targets)
43
+ * and an `inspect` fn (containerId → 'running' | 'gone' | 'unknown'), so the
44
+ * SessionManager owns lifecycle without depending on a Docker backend, and the
45
+ * daemon-down guard lives with the injected inspect (see inspectContainerLiveness).
46
+ *
47
+ * Batching: multiple sessions in one container environment share a containerId,
48
+ * so the tick inspects each DISTINCT container once and fans the verdict to every
49
+ * session bound to it. An env with no sessions contributes no target and is never
50
+ * inspected (the #7601 negative control).
51
+ */
52
+ export class ContainerLivenessMonitor {
53
+ /**
54
+ * @param {object} opts
55
+ * @param {() => Array<{sessionId: string, containerId: string, session: object}>} opts.enumerate
56
+ * live containerized poll targets (session exposes notifyContainerVanished + holds a containerId)
57
+ * @param {(containerId: string) => Promise<'running'|'gone'|'unknown'>} opts.inspect
58
+ * @param {(target: {sessionId: string, containerId: string, session: object}) => any} [opts.onRecovered]
59
+ * #7602 — called once per RECOVERY EDGE (see _tick). Optional: without it the
60
+ * poll only clears the latch, exactly as in #7601.
61
+ * @param {number} [opts.intervalMs]
62
+ * @param {object} [opts.logger]
63
+ */
64
+ constructor({ enumerate, inspect, onRecovered = null, intervalMs = DEFAULT_LIVENESS_INTERVAL_MS, logger = log } = {}) {
65
+ this._enumerate = enumerate
66
+ this._inspect = inspect
67
+ this._onRecovered = onRecovered
68
+ this._intervalMs = intervalMs
69
+ this._log = logger
70
+ this._timer = null
71
+ // Skip a tick if the prior one is still awaiting inspects (each inspect can
72
+ // block up to the docker exec/inspect timeout), so a slow Docker daemon can't
73
+ // stack overlapping ticks.
74
+ this._ticking = false
75
+ }
76
+
77
+ /**
78
+ * Start the poll. No-op if already running or if the required fns are missing
79
+ * (so a deployment that never wired a Docker inspect simply never polls).
80
+ */
81
+ start() {
82
+ if (this._timer) return
83
+ if (typeof this._enumerate !== 'function' || typeof this._inspect !== 'function') return
84
+ this._timer = setInterval(() => { this._tick() }, this._intervalMs)
85
+ // Never keep the event loop (and thus the daemon process) alive for a poll.
86
+ if (typeof this._timer.unref === 'function') this._timer.unref()
87
+ this._log.info(`Container liveness poll enabled (every ${this._intervalMs}ms)`)
88
+ }
89
+
90
+ stop() {
91
+ if (this._timer) {
92
+ clearInterval(this._timer)
93
+ this._timer = null
94
+ }
95
+ }
96
+
97
+ destroy() {
98
+ this.stop()
99
+ }
100
+
101
+ /**
102
+ * One poll pass. Enumerate live containerized sessions, inspect each distinct
103
+ * container once, and surface CONTAINER_VANISHED on the sessions whose
104
+ * container is gone (or clear the latch on the ones whose container is running
105
+ * again). Every failure is contained: one bad inspect or one throwing session
106
+ * must not abort the whole pass or wedge the interval.
107
+ *
108
+ * #7602 — the RECOVERY EDGE. `clearContainerVanished()` returns true only when
109
+ * it actually flipped the latch, i.e. exactly on the gone→running transition of
110
+ * a session that HAD vanished. `onRecovered` is invoked on that edge and only
111
+ * there, which is what keeps the re-attach from re-running on every healthy
112
+ * tick of a session that never vanished (30s apart, that would re-resolve the
113
+ * environment binding of every idle containerized session forever). A provider
114
+ * whose `clearContainerVanished` returns nothing — an older stub, or one that
115
+ * predates the boolean — yields NO edge, so the failure direction is "no
116
+ * reconnect attempted", never "reconnect attempted spuriously". #7620 holds
117
+ * that same direction for a broken INSPECT seam: only 'running' reaches the
118
+ * clear/recovery branch, and an unrecognised verdict no-ops like 'unknown'.
119
+ */
120
+ async _tick() {
121
+ if (this._ticking) return
122
+ this._ticking = true
123
+ try {
124
+ const targets = this._enumerate() || []
125
+ if (targets.length === 0) return // negative control: nothing to poll
126
+
127
+ // Batch by containerId: one inspect per DISTINCT container, fanned to every
128
+ // session bound to it (env-backed sessions share a container).
129
+ const byContainer = new Map()
130
+ for (const t of targets) {
131
+ if (!t || !t.containerId || !t.session) continue
132
+ const list = byContainer.get(t.containerId)
133
+ // #7602: the whole TARGET is carried, not just the session — the
134
+ // recovery edge hands `sessionId` to onRecovered, which is what the
135
+ // SessionManager needs to find the entry's `environmentId`.
136
+ if (list) list.push(t)
137
+ else byContainer.set(t.containerId, [t])
138
+ }
139
+
140
+ await Promise.all([...byContainer.entries()].map(async ([containerId, targets]) => {
141
+ let status
142
+ try {
143
+ status = await this._inspect(containerId)
144
+ } catch (err) {
145
+ // The inspect fn owns the gone/unknown classification; a throw here is
146
+ // unexpected. Treat it as 'unknown' — never surface a vanish on an
147
+ // inspect that failed in a way we didn't classify.
148
+ this._log.warn(`container-liveness inspect threw for ${String(containerId).slice(0, 12)}: ${err?.message || err}`)
149
+ status = 'unknown'
150
+ }
151
+ if (status === 'unknown') return // transient (daemon down / timeout) — leave the latch as-is
152
+ // #7620 — the fan-out is CLOSED over the three-value contract. `inspect`
153
+ // is an INJECTION SEAM, so 'running' is tested explicitly here and every
154
+ // unrecognised verdict degrades to the SAME no-op as 'unknown' rather
155
+ // than falling through to the clear/recovery branch below. A broken seam
156
+ // must fail in the "no reconnect attempted" direction, exactly as a
157
+ // provider whose clearContainerVanished returns nothing does — not clear
158
+ // a vanish latch and trigger a re-attach. Warned once per CONTAINER (the
159
+ // verdict is a property of the container, not of each bound session)
160
+ // because an unrecognised verdict means the seam itself is broken.
161
+ if (status !== 'running' && status !== 'gone') {
162
+ this._log.warn(`container-liveness: unrecognised verdict ${describeVerdict(status)} for ${String(containerId).slice(0, 12)} — treating as unknown`)
163
+ return
164
+ }
165
+ for (const target of targets) {
166
+ const session = target.session
167
+ try {
168
+ if (status === 'gone') {
169
+ session.notifyContainerVanished?.()
170
+ continue
171
+ }
172
+ // #7602: only a genuine gone→running transition is a recovery edge.
173
+ // A throwing re-attach is contained by this loop's own catch below,
174
+ // like every other per-session call here — it must not abort the
175
+ // fan-out to the other sessions sharing this container.
176
+ if (session.clearContainerVanished?.() !== true) continue
177
+ if (this._onRecovered) await this._onRecovered(target)
178
+ } catch (err) {
179
+ this._log.warn(`container-liveness surface failed: ${err?.message || err}`)
180
+ }
181
+ }
182
+ }))
183
+ } catch (err) {
184
+ this._log.warn(`container-liveness tick failed: ${err?.message || err}`)
185
+ } finally {
186
+ this._ticking = false
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,17 @@
1
+ // Isolated metadata only: no seed body reads. Parent owns deadline and concurrency.
2
+ import { statSync } from 'node:fs'
3
+
4
+ let input = ''
5
+ process.stdin.setEncoding('utf8')
6
+ process.stdin.on('data', (chunk) => { input += chunk })
7
+ process.stdin.on('end', () => {
8
+ const results = {}
9
+ for (const { id, seedPath, cwd } of JSON.parse(input)) {
10
+ try {
11
+ const seed = statSync(seedPath)
12
+ results[id] = seed.isFile() && statSync(cwd).isDirectory()
13
+ ? `${seed.dev}:${seed.ino}:${seed.size}:${seed.mtimeMs}:${seed.ctimeMs}` : null
14
+ } catch { results[id] = null }
15
+ }
16
+ process.stdout.write(JSON.stringify(results))
17
+ })
@@ -0,0 +1,114 @@
1
+ /** Path-only, daemon-lifetime opportunities. Filesystem probes run in a child. */
2
+ import { createHash } from 'node:crypto'
3
+ import { spawn } from 'node:child_process'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ export const CONTINUATION_TTL_MS = 30 * 60_000
7
+ const MAX_CONTINUATIONS = 50
8
+
9
+ /** One killable worker globally; a stuck syscall cannot fill libuv's pool or
10
+ * create an unbounded process queue. Keep the slot until child close. The worker
11
+ * path seam is direct-test-only, never populated from HTTP input. */
12
+ export function createContinuationProbe({ workerPath = fileURLToPath(new URL('./continuation-metadata-worker.js', import.meta.url)), timeoutMs = 1000 } = {}) {
13
+ let active = false
14
+ return (entries) => {
15
+ if (active || entries.length === 0) return Promise.resolve(null)
16
+ active = true
17
+ return new Promise((resolve) => {
18
+ let child, timer, settled = false, output = ''
19
+ const finish = (result) => {
20
+ if (settled) return
21
+ settled = true
22
+ clearTimeout(timer)
23
+ resolve(result)
24
+ }
25
+ try {
26
+ child = spawn(process.execPath, ['--', workerPath], { stdio: ['pipe', 'pipe', 'ignore'] })
27
+ timer = setTimeout(() => { finish(null); child.kill('SIGKILL') }, timeoutMs)
28
+ child.on('error', () => { active = false; finish(null) })
29
+ child.on('close', (code) => {
30
+ active = false
31
+ let result = null
32
+ if (code === 0) {
33
+ try { result = JSON.parse(output) } catch { /* unavailable */ }
34
+ }
35
+ finish(result)
36
+ })
37
+ child.stdout.on('data', (chunk) => {
38
+ output += chunk
39
+ if (output.length > 65_536) { finish(null); child.kill('SIGKILL') }
40
+ })
41
+ child.stdin.on('error', () => { finish(null); child.kill('SIGKILL') })
42
+ child.stdin.end(JSON.stringify(entries.map(({ id, seedPath, cwd }) => ({ id, seedPath, cwd }))))
43
+ } catch {
44
+ if (child) child.kill('SIGKILL')
45
+ else active = false
46
+ finish(null)
47
+ }
48
+ })
49
+ }
50
+ }
51
+
52
+ const probeMetadata = createContinuationProbe()
53
+ function expired(entry, now) {
54
+ return now - entry.ts > CONTINUATION_TTL_MS || entry.ts > now + 60_000
55
+ }
56
+
57
+ async function refreshMetadata(server, now, probe) {
58
+ if (server._continuationRefresh) return server._continuationRefresh
59
+ const entries = [...(server._continuations?.values() || [])].filter((entry) => !expired(entry, now) && !entry.baselineFailed)
60
+ if (entries.length === 0) return
61
+ const refresh = (async () => {
62
+ const results = await probe(entries)
63
+ for (const entry of entries) {
64
+ if (server._continuations?.get(entry.id) !== entry) continue
65
+ if (!results || !Object.hasOwn(results, entry.id)) {
66
+ // Without the announcement's initial snapshot we cannot tell whether a
67
+ // later successful check sees the original file or a replacement. Only
68
+ // a newer announcement may establish another baseline in that case.
69
+ if (entry.fingerprint === undefined) {
70
+ entry.fingerprint = null
71
+ entry.baselineFailed = true
72
+ }
73
+ entry.unavailable = 'metadata timeout'
74
+ continue
75
+ }
76
+ const current = results[entry.id]
77
+ if (entry.fingerprint === undefined) entry.fingerprint = current
78
+ entry.unavailable = !current || !entry.fingerprint ? 'missing' : current !== entry.fingerprint ? 'changed' : null
79
+ }
80
+ })()
81
+ server._continuationRefresh = refresh
82
+ try { await refresh } finally { if (server._continuationRefresh === refresh) server._continuationRefresh = null }
83
+ }
84
+
85
+ export function recordContinuation(server, event, now = Date.now(), probe = probeMetadata) {
86
+ const { seedPath, cwd } = event.data
87
+ const id = createHash('sha256').update(JSON.stringify([cwd, seedPath])).digest('hex')
88
+ if (!server._continuations) server._continuations = new Map()
89
+ const previous = server._continuations.get(id)
90
+ if (previous && event.ts <= previous.ts) return { opportunity: previous, duplicate: true }
91
+ const opportunity = { id, seedPath, cwd, ts: event.ts, fingerprint: undefined, unavailable: 'checking metadata' }
92
+ server._continuations.delete(id)
93
+ server._continuations.set(id, opportunity)
94
+ while (server._continuations.size > MAX_CONTINUATIONS) server._continuations.delete(server._continuations.keys().next().value)
95
+ // The isolated probe never delays the ingest acknowledgement.
96
+ if (server._continuationRefresh) {
97
+ // That batch already captured its entries. Joining its promise would leave
98
+ // this announcement unexamined until a later refresh could adopt a new file.
99
+ opportunity.fingerprint = null
100
+ opportunity.baselineFailed = true
101
+ opportunity.unavailable = 'metadata timeout'
102
+ } else {
103
+ void refreshMetadata(server, now, probe).catch(() => {})
104
+ }
105
+ return { opportunity, duplicate: false }
106
+ }
107
+
108
+ export async function listContinuations(server, now = Date.now(), probe = probeMetadata) {
109
+ await refreshMetadata(server, now, probe)
110
+ return [...(server._continuations?.values() || [])].reverse().map((entry) => {
111
+ const unavailable = expired(entry, now) ? 'expired' : entry.unavailable
112
+ return { id: entry.id, seedPath: entry.seedPath, cwd: entry.cwd, ts: entry.ts, available: unavailable === null, unavailable }
113
+ })
114
+ }
@@ -32,6 +32,7 @@
32
32
  */
33
33
 
34
34
  import { execFile } from 'child_process'
35
+ import { assertAuthorized } from '../connection-authority.js'
35
36
  import { promisify } from 'util'
36
37
  import { parseByteSize } from './containers.js'
37
38
  import { listSnapshots } from '../snapshots-store.js'
@@ -347,6 +348,7 @@ export async function runHostPrune(opts = {}) {
347
348
  listByokSnapshots = () => listSnapshots(),
348
349
  _execFile = execFileAsync,
349
350
  _now = () => new Date(),
351
+ isAuthorized,
350
352
  } = opts
351
353
  const selected = PRUNE_KINDS.includes(kind) ? kind : 'all'
352
354
  const survey = await surveyHostPrune({ listEnvironments, listByokSnapshots, _execFile, _now })
@@ -360,9 +362,11 @@ export async function runHostPrune(opts = {}) {
360
362
  failures: [],
361
363
  }
362
364
  if (!survey.dockerAvailable) return result
365
+ assertAuthorized(isAuthorized)
363
366
 
364
367
  if (selected === 'containers' || selected === 'all') {
365
368
  for (const c of survey.containers) {
369
+ assertAuthorized(isAuthorized)
366
370
  try {
367
371
  await _execFile('docker', ['rm', c.id], EXEC_OPTS)
368
372
  result.removedContainers += 1
@@ -374,6 +378,7 @@ export async function runHostPrune(opts = {}) {
374
378
  }
375
379
  if (selected === 'images' || selected === 'all') {
376
380
  for (const img of survey.images) {
381
+ assertAuthorized(isAuthorized)
377
382
  try {
378
383
  await _execFile('docker', ['rmi', img.id], EXEC_OPTS)
379
384
  result.removedImages += 1
@@ -49,11 +49,14 @@
49
49
  */
50
50
 
51
51
  import { execFile } from 'child_process'
52
+ import { assertAuthorized } from '../connection-authority.js'
52
53
  import { promisify } from 'util'
53
54
  import { readFile, stat } from 'fs/promises'
54
55
  import { join } from 'path'
55
56
  import { parseGithubOwnerRepo } from './survey.js'
56
57
  import { DEFAULT_CONCURRENCY, EXEC_TIMEOUT_MS } from './constants.js'
58
+ import { isoFromEpochMs } from '../utils/iso-datetime.js'
59
+ import { execFailureReason } from '../utils/exec-failure-reason.js'
57
60
 
58
61
  const execFileAsync = promisify(execFile)
59
62
 
@@ -127,16 +130,16 @@ export function parseRepoMemoryConfig(text) {
127
130
  */
128
131
  function deriveLastActivity(parsed) {
129
132
  const raw = parsed.lastEventAt ?? parsed.lastActivityAt ?? parsed.lastActivity
130
- if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
131
- try {
132
- return new Date(raw).toISOString()
133
- } catch {
134
- return null
135
- }
136
- }
133
+ // #7081: both branches go through isoFromEpochMs. The destination is
134
+ // `z.string().datetime()`, and this input is repo-memory's own report JSON —
135
+ // arbitrary third-party output, so weaker protection than the mtime site below.
136
+ if (typeof raw === 'number') return isoFromEpochMs(raw)
137
137
  if (typeof raw === 'string' && raw.length > 0) {
138
+ // Date.parse ROUND-TRIPS the expanded-year form, so parsing a
139
+ // '+058851-…' string and re-emitting it reproduces the same wire-illegal
140
+ // value. The string branch needs the range check just as much as the number one.
138
141
  const ms = Date.parse(raw)
139
- if (!Number.isNaN(ms)) return new Date(ms).toISOString()
142
+ if (!Number.isNaN(ms)) return isoFromEpochMs(ms)
140
143
  }
141
144
  return null
142
145
  }
@@ -247,27 +250,14 @@ async function surveyCache(statFn, repoPath) {
247
250
  }
248
251
  const sizeBytes = Math.max(0, Math.trunc(nonNegNumber(db?.size, 0) + nonNegNumber(wal?.size, 0)))
249
252
  const mtimes = [db?.mtimeMs, wal?.mtimeMs].filter(m => typeof m === 'number' && Number.isFinite(m) && m > 0)
250
- const lastModified = mtimes.length > 0 ? new Date(Math.max(...mtimes)).toISOString() : null
253
+ // #7081: same unbounded epoch->ISO shape as skills `lastUsed`. Unreachable on
254
+ // APFS/ext4 (neither can store a year > 9999) but a network/FUSE mount or a
255
+ // deliberately-set mtime can, and the adjacent sizeBytes above is already
256
+ // bounded — so the rule gets applied here rather than relying on the filesystem.
257
+ const lastModified = mtimes.length > 0 ? isoFromEpochMs(Math.max(...mtimes)) : null
251
258
  return { present: true, sizeBytes, lastModified }
252
259
  }
253
260
 
254
- /**
255
- * First meaningful line of a subprocess failure, for the per-repo `reason` /
256
- * the reindex error message. `label` names the failing command ("repo-memory
257
- * report" for the survey cell, "repo-memory index" for the #5500 action).
258
- *
259
- * @param {unknown} err
260
- * @param {string} [label]
261
- * @returns {string}
262
- */
263
- function execFailureReason(err, label = 'repo-memory report') {
264
- const stderr = err && typeof err === 'object' && typeof err.stderr === 'string' ? err.stderr : ''
265
- const firstLine = stderr.split('\n').map(l => l.trim()).find(l => l.length > 0)
266
- if (firstLine) return `${label} failed: ${firstLine}`
267
- const message = err && typeof err === 'object' && typeof err.message === 'string' ? err.message : 'unknown error'
268
- return `${label} failed: ${message}`
269
- }
270
-
271
261
  /**
272
262
  * #5500: parse the human-readable `repo-memory index <root>` report into the
273
263
  * `IntegrationActionCountsSchema` shape. The CLI has no `--json` for index —
@@ -324,9 +314,10 @@ export function parseRepoMemoryIndexCounts(stdout) {
324
314
  * @returns {Promise<{ counts: object|null }>}
325
315
  */
326
316
  export async function runRepoMemoryIndex(repoPath, opts = {}) {
327
- const { bin, _execFile = execFileAsync } = opts
317
+ const { bin, _execFile = execFileAsync, isAuthorized } = opts
328
318
  const binPath = await resolveRepoMemoryBin(_execFile, bin)
329
319
  if (!binPath) throw new Error(CLI_MISSING_NOTE)
320
+ assertAuthorized(isAuthorized)
330
321
  let stdout
331
322
  try {
332
323
  ;({ stdout } = await _execFile(binPath, ['index', repoPath], INDEX_EXEC_OPTS))
@@ -386,7 +377,7 @@ function rerunFailure(reason, message) {
386
377
  * @returns {Promise<{ runId: number }>}
387
378
  */
388
379
  export async function runRepoRelayRerun(repoPath, runId, opts = {}) {
389
- const { _execFile = execFileAsync } = opts
380
+ const { _execFile = execFileAsync, isAuthorized } = opts
390
381
 
391
382
  const ghPath = await probeBinOnPath(_execFile, 'gh')
392
383
  if (!ghPath) throw rerunFailure('gh-missing', GH_MISSING_NOTE)
@@ -429,6 +420,7 @@ export async function runRepoRelayRerun(repoPath, runId, opts = {}) {
429
420
  `run ${runId} did not fail (${state}) — only failed runs can be re-run`)
430
421
  }
431
422
 
423
+ assertAuthorized(isAuthorized)
432
424
  try {
433
425
  await _execFile(ghPath, ['run', 'rerun', String(runId), '-R', slug], RERUN_EXEC_OPTS)
434
426
  } catch (err) {
@@ -524,7 +516,8 @@ export function parseRelayRuns(json) {
524
516
  status: str(r.status),
525
517
  conclusion: str(r.conclusion),
526
518
  event: str(r.event),
527
- createdAt: Number.isNaN(createdMs) ? null : new Date(createdMs).toISOString(),
519
+ // #7081: same bound — gh run JSON is third-party input.
520
+ createdAt: Number.isNaN(createdMs) ? null : isoFromEpochMs(createdMs),
528
521
  })
529
522
  }
530
523
  return runs
@@ -827,7 +820,7 @@ async function surveyRepoMemory(ctx, repo) {
827
820
  report = parseRepoMemoryReport(typeof stdout === 'string' ? stdout : '')
828
821
  if (report === null) reason = 'repo-memory report produced unparseable output'
829
822
  } catch (err) {
830
- reason = execFailureReason(err)
823
+ reason = execFailureReason(err, 'repo-memory report')
831
824
  }
832
825
  }
833
826
 
@@ -45,8 +45,9 @@
45
45
 
46
46
  import { readFileSync } from 'fs'
47
47
  import { join, dirname } from 'path'
48
- import { loadActiveSkills, findRepoSkillsDir, DEFAULT_SKILLS_DIR } from '../skills-loader.js'
48
+ import { loadActiveSkills, findRepoSkillsDir, defaultSkillsDir } from '../skills-loader.js'
49
49
  import { DEFAULT_CONCURRENCY } from './constants.js'
50
+ import { isoFromEpochMs } from '../utils/iso-datetime.js'
50
51
 
51
52
  /**
52
53
  * Parse a `skills.lock` file into a name → { hash, installed } map. The lock
@@ -163,7 +164,11 @@ export function toInventoryEntry(skill, lock, usage, globalNames) {
163
164
  hash: lockRec ? lockRec.hash : null,
164
165
  installed: lockRec ? lockRec.installed : null,
165
166
  // Usage rollup (#5554 Phase 2). Null when never recorded.
166
- lastUsed: usageRec && typeof usageRec.lastUsed === 'number' ? new Date(usageRec.lastUsed).toISOString() : null,
167
+ // #7081: via the shared helper, which returns null for anything that would
168
+ // render as an expanded-year (>year 9999) string the wire cannot carry.
169
+ // skills-usage.js already bounds what it PERSISTS; this covers any other path
170
+ // that reaches here with an unbounded number.
171
+ lastUsed: isoFromEpochMs(usageRec?.lastUsed),
167
172
  useCount: usageRec ? usageRec.count : 0,
168
173
  usedRepos: usageRec && Array.isArray(usageRec.repos) ? usageRec.repos.slice() : [],
169
174
  }
@@ -244,7 +249,7 @@ function failureReason(err) {
244
249
  */
245
250
  export async function surveySkillsInventory(repoSet, opts = {}) {
246
251
  const {
247
- globalDir = DEFAULT_SKILLS_DIR,
252
+ globalDir = defaultSkillsDir(),
248
253
  root = '',
249
254
  usage = null,
250
255
  concurrency = DEFAULT_CONCURRENCY,