@chroxy/server 0.11.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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  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 +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  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 +69 -5
  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 +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -43,6 +43,51 @@
43
43
  *
44
44
  * On-disk formats are BYTE-COMPATIBLE with the pre-extraction files — existing
45
45
  * ledgers load unchanged and re-serialise to the same shape. No migration.
46
+ *
47
+ * Read-merge-write on flush (#8068): `binary-trust.json` gained a second
48
+ * writer PROCESS (the daemon and a standalone `chroxy resume` invocation, each
49
+ * a separate `BinaryProvenanceLedger` instance loaded once at construction) —
50
+ * see `flush()` for the merge rule. Every `PathHashTrustLedger` consumer
51
+ * inherits it; a subclass that mutates `_records` directly instead of through
52
+ * `approve`/`revoke` (skills' `inspect()`/`acceptHash`) must route those
53
+ * mutations through the protected `_setRecord`/`_deleteRecord` helpers so the
54
+ * merge can tell "this instance changed this key" from "unchanged since
55
+ * load" — see `skills-trust.js`. A subclass with its own sibling on-disk
56
+ * index (skills' `communityTrust`) overrides `_mergeExtra`/
57
+ * `_onFlushCommitted` to merge that index the same way.
58
+ *
59
+ * Refresh-on-miss (#8073): #8068 fixed WHAT a flush writes; it did not
60
+ * change WHEN each instance's own view of the world gets refreshed — that
61
+ * still only happened on this instance's own next flush. A trust decision
62
+ * made from `getRecord()`/`_records[key]` returning nothing was therefore
63
+ * still deciding "first sight" (or "nothing to revoke") from a snapshot that
64
+ * could be stale by an arbitrary amount, not from disk as of NOW. `reload()`
65
+ * re-reads and merges (via the same `_mergeLoaded()` flush() uses) without
66
+ * writing, so a caller that is about to treat a miss as meaningful —
67
+ * `verify-provenance.js`'s first-sight TOFU pin, `revoke()`'s "nothing to
68
+ * remove" check — can check disk first. See `reload()`.
69
+ *
70
+ * Merge safety, three properties (#8072 review):
71
+ * - every map the merge builds is created with `Object.assign(Object.
72
+ * create(null), …)`, never `{ ...spread }` — a plain object silently
73
+ * resurrects `constructor`/`toString`/`__proto__` as truthy prototype
74
+ * lookups the moment anything does a bracket-key membership check
75
+ * (`isCommunityTrusted`), which a repo-local `community/constructor/*.md`
76
+ * can reach.
77
+ * - a failed re-read (anything but ENOENT — malformed JSON, wrong shape,
78
+ * unreadable file) is NOT treated as "the ledger is empty": `flush()`
79
+ * falls back to THIS instance's own in-memory `_records` as the merge
80
+ * base, so a transient read failure can't drop every pin this instance
81
+ * didn't touch this flush. Only ENOENT (no file at all) is a real reset.
82
+ * - a change is tagged with WHY it happened, not just that it happened.
83
+ * `approve`/`revoke`/`acceptHash`/`grantCommunityTrust` are operator
84
+ * DECISIONS (`'set'`/`'delete'`) and always win. A trust-on-first-use
85
+ * first-sight pin (`'tofu'`) or a `lastVerified` bump (`'touch'`) are
86
+ * written from a possibly-stale snapshot, not decisions — the merge
87
+ * skips a `'tofu'` write when disk already has ANY record for that key,
88
+ * and skips a `'touch'` write when disk's hash no longer matches the one
89
+ * this instance verified against, so a stale instance can never overwrite
90
+ * a pin/decision it never saw. See `flush()`.
46
91
  */
47
92
  import { readFileSync } from 'fs'
48
93
  import { randomBytes } from 'crypto'
@@ -57,6 +102,33 @@ import { HEX64 } from './utils/validation-patterns.js'
57
102
  * @property {string} [approvalTs] The third timestamp (named per subclass)
58
103
  */
59
104
 
105
+ /**
106
+ * Priority of a tracked change, high to low: an explicit operator decision
107
+ * (`set`/`delete`) always outranks an implicit write (`tofu`/`touch`).
108
+ * `_recordChange` uses this so a key's tracked op can only ever be UPGRADED
109
+ * before the next flush, never downgraded (#8072 review C3) — e.g. once a
110
+ * key is tracked `'set'`, a later same-window `'touch'` on that key must not
111
+ * quietly demote it back to an implicit write.
112
+ *
113
+ * `'delete'` composing with a LATER `'tofu'` in the same window (a same-
114
+ * window delete-then-first-sight-again) resolves to `'delete'` at this
115
+ * priority tier — i.e. the revoke wins, not "apply the tofu value" and not
116
+ * "skip and forget." A true sequential replay of the same two operations
117
+ * one flush apart would instead land the tofu value (delete lands, THEN a
118
+ * later first sight finds nothing and pins). This composed-in-one-window
119
+ * result is stricter than that, not looser, and is unreachable in practice
120
+ * today: no production caller revokes from a `PathHashTrustLedger` subclass
121
+ * (#8072 review round 2 N1 — `session-manager.js`'s preset revoke is the
122
+ * only real caller and nothing re-inspects a revoked preset in the same
123
+ * window), and the two subclasses with a `'tofu'` op (skills, binary) have
124
+ * no revoke caller either.
125
+ *
126
+ * `'migrate'` (#8093 round 2, C2) sits at the same tier as `'tofu'`: a
127
+ * compare-and-swap write that is conditioned on disk, not an operator
128
+ * decision — see `approve()`'s `expect` option and the merge branch below.
129
+ */
130
+ const CHANGE_OP_PRIORITY = { touch: 1, tofu: 2, migrate: 2, set: 3, delete: 3 }
131
+
60
132
  export class PathHashTrustLedger {
61
133
  /**
62
134
  * @param {{
@@ -66,6 +138,11 @@ export class PathHashTrustLedger {
66
138
  * approvalField?: string, // name of the third timestamp field (default 'approvedAt')
67
139
  * wrapperKey?: string, // on-disk top-level key holding the records map (default 'records')
68
140
  * throwOnFlushError?: boolean, // re-throw persistence failures (default false — best-effort)
141
+ * extraFields?: string[], // additional string-valued record fields a subclass persists
142
+ * // (#8040 — BinaryProvenanceLedger's `kind`: 'file'|'tree').
143
+ * // Round-trips through _validateRecord/getRecord/approve; the
144
+ * // merge itself needs no special casing — it already carries
145
+ * // whole record objects, so an extra field on one rides along.
69
146
  * }} opts
70
147
  */
71
148
  constructor(opts = {}) {
@@ -78,52 +155,222 @@ export class PathHashTrustLedger {
78
155
  this._approvalField = opts.approvalField || 'approvedAt'
79
156
  this._wrapperKey = opts.wrapperKey || 'records'
80
157
  this._throwOnFlushError = opts.throwOnFlushError === true
158
+ this._extraFields = Array.isArray(opts.extraFields) ? opts.extraFields : []
81
159
  // Subclasses run their own _load() (which may parse extra sibling indexes
82
160
  // and set extra dirty state) — the base does not auto-load so a subclass
83
161
  // can wire its constructor in whatever order it needs.
84
162
  this._records = Object.create(null)
85
163
  this._dirty = false
164
+ // Tracks which keys THIS instance has changed since its last successful
165
+ // flush (or since construction) — key -> 'set' | 'delete' | 'tofu' |
166
+ // 'touch' | 'migrate' (#8072 review C3 added 'tofu'/'touch'; #8093 round
167
+ // 2 added 'migrate'). A `Map` so a key changed more than once before the
168
+ // next flush keeps only its latest (highest-priority — see
169
+ // `_recordChange`) op. Read by flush()'s merge (#8068); populated by
170
+ // `_setRecord`/`_deleteRecord`, which `approve`/`revoke` and any
171
+ // subclass that mutates `_records` directly must go through.
172
+ this._changedKeys = new Map()
173
+ // #8093 round 2 (C2): key -> the record `approve()` expected to still
174
+ // find on disk when it decided a `'migrate'` write was safe (`{ sha256,
175
+ // kind }`, or an object with `kind: undefined` for a legacy record that
176
+ // never had one). Populated only alongside a `'migrate'` entry in
177
+ // `_changedKeys`; consulted only by that op's merge branch. Kept as a
178
+ // separate map (rather than folding into `_changedKeys`'s value) so
179
+ // `_changedKeys`'s existing string-valued shape, and every other op's
180
+ // handling of it, is untouched.
181
+ //
182
+ // #8098: a WINNING CAS's entry is deleted only once `flush()`'s own
183
+ // write has actually succeeded, not inside the merge itself (the merge
184
+ // runs BEFORE the write is attempted) — mirroring how `_changedKeys` is
185
+ // itself only cleared post-write. Deleting it eagerly meant a failed
186
+ // persist's retry found no `expect` to compare against and silently
187
+ // reverted the still-valid migration. A LOSING CAS still deletes its
188
+ // entry immediately in the merge (see the `'migrate'` branch below) —
189
+ // that decision doesn't depend on this flush's write succeeding.
190
+ this._migrateExpectations = new Map()
191
+ }
192
+
193
+ /**
194
+ * Set `_records[key]` and mark it as changed by THIS instance since the
195
+ * last flush. Every mutation of `_records` — base or subclass — must go
196
+ * through this (or `_deleteRecord`) rather than assigning `_records[key]`
197
+ * directly, or flush()'s merge won't know to prefer it over what's on
198
+ * disk.
199
+ *
200
+ * @param {string} key Already-normalised key.
201
+ * @param {TrustRecord} record
202
+ * @param {'set'|'tofu'|'touch'|'migrate'} [op='set'] Why this key changed
203
+ * (#8072 review C3; `'migrate'` added #8093 round 2) — `'set'` for an
204
+ * explicit operator decision (default; always wins the merge), `'tofu'`
205
+ * for a trust-on-first-use first-sight pin (merge skips it if disk
206
+ * already has ANY record for this key — never overwrite a pin/decision
207
+ * this instance never saw), `'touch'` for an informational
208
+ * `lastVerified` bump (merge skips it if disk's hash no longer matches
209
+ * the one this instance verified against), `'migrate'` for a
210
+ * compare-and-swap write conditioned on an explicit `expect` snapshot
211
+ * (see `approve()`) rather than on `record` itself.
212
+ * @protected
213
+ */
214
+ _setRecord(key, record, op = 'set') {
215
+ this._records[key] = record
216
+ this._recordChange(key, op)
217
+ // A key changing to any op OTHER than 'migrate' has no business with a
218
+ // stale expectation from an earlier 'migrate' call on the same key
219
+ // before a flush ran — drop it so the merge never consults leftover
220
+ // state for the wrong op.
221
+ if (op !== 'migrate') this._migrateExpectations.delete(key)
222
+ this._dirty = true
223
+ }
224
+
225
+ /**
226
+ * Delete `_records[key]` and mark the deletion as a change THIS instance
227
+ * made since the last flush, so flush()'s merge keeps it removed instead
228
+ * of resurrecting whatever another process's flush wrote for that key.
229
+ * Always an explicit operator decision — there is no implicit delete.
230
+ *
231
+ * @param {string} key Already-normalised key.
232
+ * @protected
233
+ */
234
+ _deleteRecord(key) {
235
+ delete this._records[key]
236
+ this._recordChange(key, 'delete')
237
+ this._migrateExpectations.delete(key)
238
+ this._dirty = true
239
+ }
240
+
241
+ /**
242
+ * Track that THIS instance changed `key` via `op`, upgrading but never
243
+ * downgrading a key already tracked this window (#8072 review C3) — e.g.
244
+ * a `'touch'` bump must not demote a key already tracked `'set'` back to
245
+ * an implicit write that the merge would then treat as skippable.
246
+ *
247
+ * @param {string} key
248
+ * @param {'set'|'delete'|'tofu'|'touch'} op
249
+ * @private
250
+ */
251
+ _recordChange(key, op) {
252
+ const existing = this._changedKeys.get(key)
253
+ if (!existing || CHANGE_OP_PRIORITY[op] >= CHANGE_OP_PRIORITY[existing]) {
254
+ this._changedKeys.set(key, op)
255
+ }
256
+ }
257
+
258
+ /**
259
+ * Subclass hook: merge a sibling on-disk index (skills' `communityTrust`)
260
+ * with this instance's in-memory copy, using the freshly re-read `parsed`
261
+ * payload flush() just loaded. Called on every flush, right before
262
+ * `_serialize()`. Base no-op — only a subclass with extra persisted state
263
+ * needs it.
264
+ *
265
+ * @param {object|null} _parsed Raw parsed JSON flush() just re-read (or
266
+ * null on a read/parse failure — same fail-open shape `_loadRecords`
267
+ * returns).
268
+ * @protected
269
+ */
270
+ _mergeExtra(_parsed) {
271
+ // no-op by default
272
+ }
273
+
274
+ /**
275
+ * Subclass hook: called once a flush's write has actually SUCCEEDED, after
276
+ * the base has cleared its own `_changedKeys`. A subclass that tracks its
277
+ * own extra change-set (skills' community-trust grants) clears it here —
278
+ * not inside `_mergeExtra`, which also runs on a flush that goes on to
279
+ * fail, and must leave the subclass's change-set intact for the retry.
280
+ * Base no-op.
281
+ *
282
+ * @protected
283
+ */
284
+ _onFlushCommitted() {
285
+ // no-op by default
86
286
  }
87
287
 
88
288
  /**
89
289
  * Read + parse the ledger's records map, failing open to empty on any error.
90
- * Returns `{ records, parsed, migratedLegacy }` where:
91
- * - `records` is the validated, key-normalised path → record map
290
+ * Returns `{ records, parsed, migratedLegacy, readFailed, ioError }` where:
291
+ * - `records` is the validated, key-normalised path → record map (always
292
+ * a null-prototype object — see `flush()`/#8072 review C1)
92
293
  * - `parsed` is the raw parsed JSON object (so a subclass can pull sibling
93
294
  * indexes like communityTrust out of it) or null on a read/parse failure
94
295
  * - `migratedLegacy` is whether a subclass legacy-shape hook claimed the file
296
+ * - `readFailed` (#8072 review C2) is true when the file exists but could
297
+ * not be read/parsed/recognised — malformed JSON, a non-object root, an
298
+ * unreadable file (EACCES etc.), or an unrecognised shape. `false` for a
299
+ * genuinely EMPTY ledger: no file at all (ENOENT — ordinary first run,
300
+ * or an operator deleting the file to reset it), or a file that parses
301
+ * to `{}`. `flush()` uses this to tell "the file was reset" from "the
302
+ * re-read just failed" — the latter must NOT be treated as an empty
303
+ * merge base, or a transient read failure drops every pin this
304
+ * instance holds but didn't touch this flush.
305
+ * - `ioError` (#8072 review S4) narrows `readFailed` to specifically "the
306
+ * READ CALL ITSELF threw" (EACCES, EIO, EMFILE, …) rather than "the
307
+ * bytes came back but are known-bad" (malformed JSON / wrong shape).
308
+ * The distinction matters at flush time: known-bad bytes are safe to
309
+ * repair-overwrite with this instance's own records (disk is garbage
310
+ * either way), but an I/O error says NOTHING about whether disk's
311
+ * current content is good — a root-owned file or a too-many-open-files
312
+ * daemon can hit this on a perfectly healthy ledger. `flush()` skips
313
+ * the write entirely on `ioError` rather than repair-overwriting it
314
+ * (see `flush()`).
95
315
  *
96
316
  * The records map is sourced from `parsed[wrapperKey]` (v2-style nesting). A
97
317
  * subclass that supports a legacy flat-root format overrides `_extractLegacy`
98
318
  * to detect + return it (skills v1).
99
319
  *
100
- * @returns {{ records: object, parsed: object|null, migratedLegacy: boolean }}
320
+ * @param {{ atFlush?: boolean, atReload?: boolean }} [opts] `atFlush: true`
321
+ * or `atReload: true` only change the WARN wording on a failure (#8072
322
+ * review N1; `atReload` added #8073) — at flush OR reload time this
323
+ * instance's own in-memory records are what actually gets kept (or, on
324
+ * `ioError` at flush time, the flush is skipped outright — see
325
+ * `readFailed`/`ioError` above), so "starting fresh" would describe the
326
+ * wrong outcome. At construction (the default) there is nothing in
327
+ * memory yet, so "starting fresh" is accurate. `atFlush` gets its own
328
+ * ioError wording ("skipping this flush, will retry") because a flush
329
+ * really is about to skip a write; `reload()` never writes, so an
330
+ * `atReload` ioError uses the same "keeping this instance's own records"
331
+ * wording as every other reload failure.
332
+ * @returns {{ records: object, parsed: object|null, migratedLegacy: boolean, readFailed: boolean, ioError: boolean, ioErrorDetail: string|null }}
101
333
  * @protected
102
334
  */
103
- _loadRecords() {
104
- const empty = { records: Object.create(null), parsed: null, migratedLegacy: false }
335
+ _loadRecords({ atFlush = false, atReload = false } = {}) {
336
+ const outcome = (atFlush || atReload) ? 'keeping this instance\'s own records' : 'starting fresh'
337
+ const empty = (readFailed, ioError = false, ioErrorDetail = null) => ({
338
+ records: Object.create(null), parsed: null, migratedLegacy: false, readFailed, ioError, ioErrorDetail,
339
+ })
105
340
 
106
341
  let raw
107
342
  try {
108
343
  raw = readFileSync(this._filePath, 'utf8')
109
344
  } catch (err) {
110
345
  if (err && err.code !== 'ENOENT') {
111
- this._log.warn(`Could not read trust file (${err.code || err.message}); starting fresh`)
346
+ // #8072 review S4: this is an I/O error, not known-bad bytes — say
347
+ // so distinctly at flush time, since the outcome differs (skip the
348
+ // write, not "keep this instance's own records" — see flush()).
349
+ // `ioErrorDetail` carries the code/message forward so flush()'s own
350
+ // warn/throw names the SAME underlying failure a caller would have
351
+ // seen from the write attempt this replaces (EISDIR, EACCES, ...).
352
+ // reload() (#8073) has no write to skip, so it gets the ordinary
353
+ // `outcome` wording, not "skipping this flush".
354
+ const detail = (err && err.code) || (err && err.message) || 'read failed'
355
+ const ioOutcome = atFlush ? 'skipping this flush, will retry' : outcome
356
+ this._log.warn(`Could not read trust file (${detail}); ${ioOutcome}`)
357
+ return empty(true, true, detail)
112
358
  }
113
- return empty
359
+ // ENOENT: no file at all — a genuine empty ledger, not a failure.
360
+ return empty(false)
114
361
  }
115
362
 
116
363
  let parsed
117
364
  try {
118
365
  parsed = JSON.parse(raw)
119
366
  } catch (err) {
120
- this._log.warn(`Trust file is malformed JSON (${getErrorMessage(err, err)}); starting fresh`)
121
- return empty
367
+ this._log.warn(`Trust file is malformed JSON (${getErrorMessage(err, err)}); ${outcome}`)
368
+ return empty(true)
122
369
  }
123
370
 
124
371
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
125
- this._log.warn('Trust file root is not an object; starting fresh')
126
- return empty
372
+ this._log.warn(`Trust file root is not an object; ${outcome}`)
373
+ return empty(true)
127
374
  }
128
375
 
129
376
  // Locate the records map. v2 nesting under the wrapper key wins; otherwise
@@ -139,11 +386,11 @@ export class PathHashTrustLedger {
139
386
  rawMap = legacy.rawMap
140
387
  migratedLegacy = legacy.migratedLegacy === true
141
388
  } else if (Object.keys(parsed).length === 0) {
142
- // Empty object — treat as an empty ledger (fresh).
389
+ // Empty object — treat as an empty ledger (fresh, not a failure).
143
390
  rawMap = {}
144
391
  } else {
145
- this._log.warn('Trust file has unrecognised shape; starting fresh')
146
- return empty
392
+ this._log.warn(`Trust file has unrecognised shape; ${outcome}`)
393
+ return empty(true)
147
394
  }
148
395
  }
149
396
 
@@ -156,7 +403,7 @@ export class PathHashTrustLedger {
156
403
  records[this._normalizeKey(key)] = rec
157
404
  }
158
405
  }
159
- return { records, parsed, migratedLegacy }
406
+ return { records, parsed, migratedLegacy, readFailed: false, ioError: false }
160
407
  }
161
408
 
162
409
  /**
@@ -177,11 +424,19 @@ export class PathHashTrustLedger {
177
424
  const approval = typeof value[this._approvalField] === 'string'
178
425
  ? value[this._approvalField]
179
426
  : value.firstSeen
180
- return {
427
+ const rec = {
181
428
  sha256: value.sha256,
182
429
  firstSeen: value.firstSeen,
183
430
  [this._approvalField]: approval,
184
431
  }
432
+ // #8040: carry through any declared extra fields present on disk (e.g.
433
+ // BinaryProvenanceLedger's `kind`) — a record written before a subclass
434
+ // declared the field simply lacks it, which callers treat as a legacy
435
+ // default (see verify-provenance.js's migration branch).
436
+ for (const field of this._extraFields) {
437
+ if (typeof value[field] === 'string') rec[field] = value[field]
438
+ }
439
+ return rec
185
440
  }
186
441
  return null
187
442
  }
@@ -223,11 +478,15 @@ export class PathHashTrustLedger {
223
478
  getRecord(absPath) {
224
479
  const rec = this._records[this._normalizeKey(absPath)]
225
480
  if (!rec) return null
226
- return {
481
+ const out = {
227
482
  sha256: rec.sha256,
228
483
  firstSeen: rec.firstSeen,
229
484
  [this._approvalField]: rec[this._approvalField],
230
485
  }
486
+ for (const field of this._extraFields) {
487
+ if (rec[field] !== undefined) out[field] = rec[field]
488
+ }
489
+ return out
231
490
  }
232
491
 
233
492
  /**
@@ -237,20 +496,54 @@ export class PathHashTrustLedger {
237
496
  *
238
497
  * @param {string} absPath
239
498
  * @param {string} hash
240
- * @returns {boolean} true when the grant was recorded
499
+ * @param {{ firstSight?: boolean, fields?: object, expect?: { sha256: string, [field: string]: unknown } }} [opts]
500
+ * `firstSight: true` (#8072 review C3) marks this as a trust-on-first-use
501
+ * pin rather than an explicit operator decision — `verify-provenance.js`'s
502
+ * TOFU binary pin passes this so a stale instance's first-sight write of
503
+ * a possibly tampered hash can never override a pin/decision another
504
+ * process made that this instance never saw (see `flush()`'s merge).
505
+ * `expect` (#8093 round 2, C2) makes this write a COMPARE-AND-SWAP
506
+ * instead: tagged `'migrate'`, applied by the merge only when disk still
507
+ * holds a record matching `expect` exactly (compared field-by-field over
508
+ * every key `expect` names, `sha256` included) — otherwise disk's value
509
+ * is kept and this write is dropped entirely. For a legacy record with
510
+ * no `kind` at all, pass `expect: { sha256, kind: undefined }` (or simply
511
+ * omit `kind`) so the comparison requires the SAME absence, not a
512
+ * coincidental match against some other kind-less field. `firstSight`
513
+ * and `expect` are mutually exclusive; `expect` wins if both are given.
514
+ * Omit both for an operator-driven approval (default) — always wins the
515
+ * merge. `fields` (#8040) supplies a value for each subclass-declared
516
+ * `extraFields` key (e.g. `{ kind: 'tree' }`) — a key not present in
517
+ * `fields` carries forward the existing record's value for that field,
518
+ * if any, so an approval that doesn't mention an extra field never
519
+ * silently drops it.
520
+ * @returns {boolean} true when the write was accepted for merging — for a
521
+ * `'migrate'` write this means the CAS was attempted, not that it WON;
522
+ * call `getRecord()` after to see what the merge actually kept, exactly
523
+ * as every other conditional (`'tofu'`/`'touch'`) op already requires.
241
524
  */
242
- approve(absPath, hash) {
525
+ approve(absPath, hash, { firstSight = false, fields = {}, expect } = {}) {
243
526
  if (typeof absPath !== 'string' || !absPath) return false
244
527
  if (typeof hash !== 'string' || !HEX64.test(hash)) return false
245
528
  const key = this._normalizeKey(absPath)
246
529
  const now = new Date().toISOString()
247
530
  const existing = this._records[key]
248
- this._records[key] = {
531
+ const record = {
249
532
  sha256: hash,
250
533
  firstSeen: existing && typeof existing.firstSeen === 'string' ? existing.firstSeen : now,
251
534
  [this._approvalField]: now,
252
535
  }
253
- this._dirty = true
536
+ for (const field of this._extraFields) {
537
+ if (fields[field] !== undefined) {
538
+ record[field] = fields[field]
539
+ } else if (existing && existing[field] !== undefined) {
540
+ record[field] = existing[field]
541
+ }
542
+ }
543
+ const isMigrate = expect !== undefined
544
+ const op = isMigrate ? 'migrate' : (firstSight ? 'tofu' : 'set')
545
+ if (isMigrate) this._migrateExpectations.set(key, expect)
546
+ this._setRecord(key, record, op)
254
547
  this.flush()
255
548
  return true
256
549
  }
@@ -259,15 +552,27 @@ export class PathHashTrustLedger {
259
552
  * Revoke `absPath` — drops the record so the path goes inert again. Persists
260
553
  * synchronously.
261
554
  *
555
+ * #8073: a miss in THIS instance's memory used to end the call right there
556
+ * — `false`, nothing revoked — even when a DIFFERENT process/instance had
557
+ * pinned this exact path after this instance's own last load. That left a
558
+ * genuine on-disk pin un-revokable from any instance that did not
559
+ * personally load it. Refresh from disk before trusting a miss: `reload()`
560
+ * merges disk into memory (without writing), so a pin another instance
561
+ * wrote becomes visible here, and the delete that follows is tracked in
562
+ * `_changedKeys` and actually flushed — removing it from disk too, not
563
+ * merely masking it in this instance's own view.
564
+ *
262
565
  * @param {string} absPath
263
566
  * @returns {boolean} true when a record was removed
264
567
  */
265
568
  revoke(absPath) {
266
569
  if (typeof absPath !== 'string' || !absPath) return false
267
570
  const key = this._normalizeKey(absPath)
268
- if (!this._records[key]) return false
269
- delete this._records[key]
270
- this._dirty = true
571
+ if (!this._records[key]) {
572
+ this.reload()
573
+ if (!this._records[key]) return false
574
+ }
575
+ this._deleteRecord(key)
271
576
  this.flush()
272
577
  return true
273
578
  }
@@ -286,6 +591,190 @@ export class PathHashTrustLedger {
286
591
  return { [this._wrapperKey]: map }
287
592
  }
288
593
 
594
+ /**
595
+ * Merge a freshly re-read disk snapshot (a `_loadRecords()` result) with
596
+ * this instance's own pending `_changedKeys`, using the conflict rule
597
+ * documented on `flush()` below, and replace `this._records` with the
598
+ * result. Shared (#8073) by `flush()` (which then persists the merged
599
+ * result) and `reload()` (which never writes) — the two callers differ
600
+ * only in what happens AFTER this returns, not in how the merge itself
601
+ * works, so there is exactly one implementation of the conflict rule to
602
+ * keep correct.
603
+ *
604
+ * `readFailed` (from the same `_loadRecords()` call) controls the merge
605
+ * base: `false` uses the freshly re-read `records`; `true` (known-bad
606
+ * bytes OR an I/O error — both set `readFailed`) falls back to THIS
607
+ * instance's own current `_records`, which makes the merge a safe no-op —
608
+ * every already-applied change stays applied, nothing pending is
609
+ * resolved-and-forgotten (see the R2-C1 branches below), and no in-memory
610
+ * pin is ever dropped. `_mergeExtra` (the subclass sibling-index hook)
611
+ * only runs on a successful re-read, for the same reason `flush()` always
612
+ * skipped it on a failed one — merging a subclass index against `parsed:
613
+ * null` would have nothing real to merge against.
614
+ *
615
+ * @param {{ records: object, parsed: object|null, readFailed: boolean }} loaded
616
+ * A `_loadRecords()` result.
617
+ * @private
618
+ */
619
+ _mergeLoaded({ records: diskRecords, parsed: diskParsed, readFailed }) {
620
+ // C2: a failed re-read of known-bad bytes (or an I/O error) must not be
621
+ // treated as "the ledger is empty" — that would drop every pin this
622
+ // instance holds but didn't change this round. Fall back to this
623
+ // instance's own current records (already reflects every change it has
624
+ // made, applied immediately by `_setRecord`/`_deleteRecord`).
625
+ const base = readFailed ? this._records : diskRecords
626
+ // C1: null-prototype, not `{ ...base }` — a plain object lets a key
627
+ // named `constructor`/`toString`/`__proto__` resolve through the
628
+ // prototype chain instead of a real own-property miss.
629
+ const merged = Object.assign(Object.create(null), base)
630
+ for (const [key, op] of this._changedKeys) {
631
+ if (op === 'delete') {
632
+ delete merged[key]
633
+ continue
634
+ }
635
+ if (op === 'tofu') {
636
+ // C3: a first-sight pin is not a decision — never override a
637
+ // record another process/instance already holds for this path.
638
+ if (base[key]) {
639
+ // R2-C1: disk already resolved this key — forget the tracked op
640
+ // rather than risk replaying it against a LATER disk state where
641
+ // the key is gone (revoked/removed), which would resurrect it. On
642
+ // a `readFailed` base we didn't learn anything reliable about
643
+ // disk this time, so keep retrying instead of forgetting.
644
+ if (!readFailed) this._changedKeys.delete(key)
645
+ continue
646
+ }
647
+ merged[key] = this._records[key]
648
+ continue
649
+ }
650
+ if (op === 'touch') {
651
+ // C3: an informational bump is not a decision — only apply it when
652
+ // the base still agrees with the hash this instance verified
653
+ // against. If it doesn't (a real approve/acceptHash superseded this
654
+ // instance, or the record is gone), keep the base's value.
655
+ const baseRec = base[key]
656
+ const ourRec = this._records[key]
657
+ if (!baseRec || !ourRec || baseRec.sha256 !== ourRec.sha256) {
658
+ // R2-C1: same reasoning as the 'tofu' branch above.
659
+ if (!readFailed) this._changedKeys.delete(key)
660
+ continue
661
+ }
662
+ // #8072 review round 2 N2: apply ONLY the bumped approval
663
+ // timestamp on top of the BASE record, not this instance's whole
664
+ // (possibly stale) record. The hashes already match here, but
665
+ // `firstSeen` or a different approval timestamp on `baseRec` could
666
+ // reflect a revoke-then-re-approve this instance never saw — taking
667
+ // `this._records[key]` wholesale would silently revert those to
668
+ // this instance's own stale values.
669
+ merged[key] = { ...baseRec, [this._approvalField]: ourRec[this._approvalField] }
670
+ continue
671
+ }
672
+ if (op === 'migrate') {
673
+ // #8093 round 2 (C2): a compare-and-swap, not an unconditional
674
+ // write. The ORIGINAL migration fix reloaded once before DECIDING to
675
+ // migrate, then wrote with plain `'set'` priority — which always won
676
+ // this merge regardless of what a fresh re-read found, making the
677
+ // caller's own post-approve `getRecord()` re-read unable to ever
678
+ // observe a concurrent genuine write (it was always reading back
679
+ // its OWN just-applied value, since `_setRecord` already applied it
680
+ // to `_records` synchronously, before this merge ever runs). This
681
+ // branch is what actually closes that: apply our record ONLY when
682
+ // disk (`base`, i.e. THIS re-read — see the `readFailed` branch
683
+ // below for why that fallback is handled separately) still matches
684
+ // the `expect` snapshot the caller took before deciding this was
685
+ // safe.
686
+ if (readFailed) {
687
+ // We didn't learn anything reliable about disk this round. `base`
688
+ // has already fallen back to `this._records`, which by now holds
689
+ // OUR NEW record (applied synchronously by `_setRecord` before
690
+ // this ever runs) — comparing THAT against `expect` (the OLD,
691
+ // pre-migration snapshot) would almost never match and would
692
+ // wrongly read as "disk moved on" for a merely-transient read
693
+ // failure, indistinguishable from a real conflict. Keep retrying
694
+ // instead, exactly like every other conditional op's readFailed
695
+ // handling — `merged[key]` already defaults to `base[key]`
696
+ // (== our own record here), so nothing is lost by not deciding.
697
+ continue
698
+ }
699
+ const expect = this._migrateExpectations.get(key)
700
+ const baseRec = base[key]
701
+ // Match every field `expect` names (sha256 always among them) — not
702
+ // just sha256 — so a kind change alone (extremely unlikely without
703
+ // a hash change, but not impossible with a hand-edited ledger) also
704
+ // counts as "disk moved on". A `baseRec` field absent from `expect`
705
+ // is not compared: `expect` describes what this instance is
706
+ // conditioning on, not the record's entire shape.
707
+ const matches = !!baseRec && expect != null
708
+ && Object.entries(expect).every(([field, value]) => baseRec[field] === value)
709
+ if (!matches) {
710
+ // Disk no longer matches what we migrated FROM — a different
711
+ // process's write (very likely a genuine, already-migrated tree
712
+ // pin) resolved this key first. Drop our write outright; `merged`
713
+ // already defaults to `base[key]`, i.e. disk's real current
714
+ // value, so nothing further is needed to "keep" it. Forget the
715
+ // tracked op and its expectation — a LATER flush must not
716
+ // re-evaluate this against whatever disk shows THEN, which could
717
+ // wrongly resurrect a decision made against a since-superseded
718
+ // snapshot (the same R2-C1 reasoning as 'tofu'/'touch' above).
719
+ this._changedKeys.delete(key)
720
+ this._migrateExpectations.delete(key)
721
+ continue
722
+ }
723
+ // #8098: do NOT delete `_migrateExpectations` here. This merge runs
724
+ // BEFORE `flush()` attempts the physical write (see `flush()`) — if
725
+ // that write then fails, `_changedKeys` keeps `'migrate'` for this
726
+ // key so the next flush retries it, but deleting the expectation
727
+ // now would leave that retry with no `expect` to compare against:
728
+ // `expect` reads back `undefined`, `matches` above evaluates false,
729
+ // and the still-valid migration would be silently reverted to the
730
+ // legacy record it migrated FROM. Deferred to `flush()`'s own
731
+ // success branch instead — exactly like `_changedKeys.clear()`
732
+ // itself is deferred — so a retry can still re-derive this same
733
+ // win against a fresh disk read.
734
+ merged[key] = this._records[key]
735
+ continue
736
+ }
737
+ // 'set': an explicit operator decision — always wins.
738
+ merged[key] = this._records[key]
739
+ }
740
+ this._records = merged
741
+ if (!readFailed) this._mergeExtra(diskParsed)
742
+ }
743
+
744
+ /**
745
+ * Re-read the ledger file from disk and merge it with this instance's own
746
+ * pending changes, using the exact same conflict rule `flush()` uses (via
747
+ * the shared `_mergeLoaded()`) — but never writes (#8073).
748
+ *
749
+ * A trust decision that treats "nothing in MY memory" as "nothing exists
750
+ * anywhere" is exactly the bug this closes: `verifyProvenance()`'s
751
+ * first-sight check and `revoke()`'s "is there anything to remove" check
752
+ * both used to consult only `this._records`, which is a snapshot frozen at
753
+ * this instance's construction (or its own last flush) — not at NOW. A
754
+ * pin/decision a DIFFERENT process or instance persisted after that point
755
+ * was invisible until this instance's own next flush happened to run,
756
+ * which is exactly the daemon-exec-before-flush window the issue reports.
757
+ * `reload()` gives a caller that is about to treat a miss as meaningful a
758
+ * way to check disk FIRST.
759
+ *
760
+ * On any re-read failure — `readFailed` (malformed JSON / wrong shape) or
761
+ * `ioError` (EACCES/EIO/EMFILE/…, which also sets `readFailed` — see
762
+ * `_loadRecords`) — `_mergeLoaded` uses this instance's OWN `_records` as
763
+ * the merge base, so nothing in memory changes and nothing pending is
764
+ * resolved-and-forgotten: nothing this instance already holds is ever
765
+ * dropped by a failed reload. `_loadRecords` itself already logs the
766
+ * warn; `reload()` adds none of its own.
767
+ *
768
+ * @returns {boolean} true when the reload actually re-synced from a
769
+ * successfully re-read disk file; false when the read failed and
770
+ * memory was left exactly as it was.
771
+ */
772
+ reload() {
773
+ const loaded = this._loadRecords({ atReload: true })
774
+ this._mergeLoaded(loaded)
775
+ return !loaded.readFailed
776
+ }
777
+
289
778
  /**
290
779
  * Persist the ledger to disk. No-op when clean. Delegates to the shared
291
780
  * durable-write seam (`saveJsonState({ fsync: true })`, #5620) — atomic
@@ -294,15 +783,143 @@ export class PathHashTrustLedger {
294
783
  * #3238). The seam owns the fd/temp cleanup; this layer only adds the dirty
295
784
  * gate + the warn / conditional re-throw policy.
296
785
  *
786
+ * Read-merge-write (#8068): a flush used to re-serialise THIS instance's
787
+ * whole in-memory snapshot, clobbering any record a different writer
788
+ * process had persisted after this instance's own last load — exactly what
789
+ * happened once `chroxy resume` became a second `BinaryProvenanceLedger`
790
+ * writer alongside the daemon on the same `binary-trust.json`. `flush()`
791
+ * now re-reads the file right before writing and merges it with only the
792
+ * keys THIS instance actually changed (tracked in `_changedKeys` by
793
+ * `_setRecord`/`_deleteRecord`, which `approve`/`revoke` — and any
794
+ * subclass mutation of `_records` — must go through), rather than with the
795
+ * whole snapshot (see "Conflict rule" below).
796
+ *
797
+ * The merged result also replaces this instance's in-memory `_records` (and,
798
+ * via `_mergeExtra`, any subclass sibling index), so a later `isTrusted`/
799
+ * `getRecord` in this same process sees the other writer's pins too — not
800
+ * only the file.
801
+ *
802
+ * Four refinements on top of the base rule (#8072 review):
803
+ *
804
+ * - **Null-prototype merge (C1).** The merge target is built with
805
+ * `Object.assign(Object.create(null), base)`, never `{ ...base }`. A
806
+ * plain object silently resurrects `constructor`/`toString`/
807
+ * `__proto__` as truthy prototype lookups — a real security bypass
808
+ * for `SkillsTrustStore.isCommunityTrusted()`'s bracket-key check.
809
+ * - **A failed re-read is not "empty" (C2), and not every failure is the
810
+ * SAME kind of failed (S4, round 2).** `_loadRecords` distinguishes
811
+ * three outcomes: "no file" (ENOENT — a genuine reset, resets the
812
+ * merge base to empty); "the bytes came back but are known-bad"
813
+ * (malformed JSON, wrong shape — `readFailed: true`, `ioError: false`
814
+ * — falls back to THIS instance's own current `_records` and skips
815
+ * `_mergeExtra`, a safe repair-overwrite since disk is garbage
816
+ * either way); and "the READ CALL ITSELF failed" (EACCES/EIO/EMFILE —
817
+ * `ioError: true` — which says nothing about whether disk's current
818
+ * content is good, so repair-overwriting it would risk clobbering a
819
+ * healthy pin a different process just wrote. This flush's write is
820
+ * skipped ENTIRELY instead — see the `ioError` branch below.
821
+ * - **Implicit writes never outrank a decision this instance never saw
822
+ * (C3).** A change is tracked with WHY it happened (see `_setRecord`).
823
+ * `'set'`/`'delete'` are operator decisions and always win. `'tofu'`
824
+ * (a trust-on-first-use first-sight pin) is skipped when disk already
825
+ * has ANY record for that key — a stale instance's first sight of a
826
+ * possibly-tampered hash must not override a pin/decision it never
827
+ * saw. `'touch'` (a `lastVerified` bump) is skipped when disk's hash no
828
+ * longer matches the one this instance verified against — an
829
+ * informational timestamp bump must not revert a real approval.
830
+ * - **A resolved implicit op is forgotten, not retried (R2-C1, round 2).**
831
+ * When the merge skips a `'tofu'`/`'touch'` above because disk already
832
+ * resolved that key, the tracked op is deleted from `_changedKeys` (on
833
+ * a `readFailed` flush the op is instead KEPT, since we didn't learn
834
+ * anything reliable about disk this time — see the merge loop). Without
835
+ * this, a swallowed write failure on THIS flush leaves `_changedKeys`
836
+ * holding `key -> 'tofu'` while `_records[key]` already holds the OTHER
837
+ * process's record (adopted from `base` above). A LATER flush would
838
+ * then re-evaluate that stale `'tofu'` against whatever disk shows AT
839
+ * THAT POINT — if the key was since revoked or hand-removed, disk no
840
+ * longer has it, the skip condition ("disk already has a record") no
841
+ * longer holds, and the stale op writes back a pin someone else
842
+ * deliberately removed.
843
+ *
844
+ * Conflict rule for an explicit ('set'/'delete') change:
845
+ *
846
+ * - a path THIS instance changed: this instance's value wins (a revoke
847
+ * stays removed — it's a tracked deletion, not merely "absent from
848
+ * this instance's map"; see the R2-C1 bullet above for why an implicit
849
+ * `'tofu'`/`'touch'` needs its OWN, narrower guarantee here)
850
+ * - a path this instance did NOT change: whatever is on disk right now
851
+ * wins, including a pin/grant a different process wrote after this
852
+ * instance's own last load
853
+ * - the SAME path changed by two processes: the LATER flush wins,
854
+ * because it re-reads first (picking up the earlier flush's value)
855
+ * and then re-applies its own change on top of that
856
+ *
857
+ * Known remaining window: the re-read and the eventual rename are not one
858
+ * atomic step, so two processes can both re-read the same pre-flush file,
859
+ * each merge their own change on top, and then race the rename — the
860
+ * second rename wins outright, and the LOSING process's own changed keys
861
+ * (not the winner's — both racers read the same pre-flush bytes, so
862
+ * neither one's merge actually saw the other's write) are what's lost.
863
+ * That's strictly narrower than the bug this fixes — it needs two flushes
864
+ * inside the same read-to-rename window rather than merely two flushes
865
+ * ever — and this codebase has no file-lock helper to close it with
866
+ * (checked `src/utils`), so it's documented here rather than solved.
867
+ * Tracked as #8080; deliberately kept out of #8073's own scope (see
868
+ * `reload()`, which closes the DIFFERENT gap #8073 actually fixed — a
869
+ * stale in-memory snapshot deciding a trust question before this flush's
870
+ * own next merge runs).
871
+ *
872
+ * The merge itself (base selection + the per-key conflict rule above) is
873
+ * `_mergeLoaded()` — shared with `reload()` (#8073), which needs the exact
874
+ * same rule for its own "merge disk into memory, but never write" job.
875
+ *
297
876
  * On failure: either re-throw (subclass set `throwOnFlushError`) or swallow
298
- * with a warn. `_dirty` stays set on failure so a later flush retries.
877
+ * with a warn. `_dirty` and `_changedKeys` both stay set on failure so a
878
+ * later flush retries — this now also covers an `ioError` re-read (the
879
+ * write is never attempted, so there is nothing to catch; the same
880
+ * warn/throw policy is applied directly).
299
881
  */
300
882
  flush() {
301
883
  if (!this._dirty) return
302
884
  const tmpSuffix = `.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
885
+ const loaded = this._loadRecords({ atFlush: true })
886
+
887
+ // S4 (#8072 review, round 2): an I/O error on the re-read says nothing
888
+ // about whether disk's CURRENT bytes are good — unlike the known-bad-
889
+ // bytes case below, repair-overwriting here risks clobbering a healthy
890
+ // pin a different process just wrote (the #8068 loss again, scoped to
891
+ // this one flush). Skip the write outright: `_dirty`/`_changedKeys` stay
892
+ // set so the next flush retries, matching a failed WRITE's own policy.
893
+ // The thrown/warned message names the SAME underlying code a failed
894
+ // WRITE to this same broken path would have surfaced (EACCES, EISDIR,
895
+ // ...) in its MESSAGE, so a caller matching on the message text sees
896
+ // the same code. The thrown Error carries no `.code` property, unlike a
897
+ // re-thrown write failure; no current caller reads `.code`.
898
+ if (loaded.ioError) {
899
+ this._log.warn(`Could not persist trust file (${loaded.ioErrorDetail}); skipping this flush, will retry`)
900
+ if (this._throwOnFlushError) {
901
+ throw new Error(`Could not persist trust file: pre-write re-read failed (${loaded.ioErrorDetail})`)
902
+ }
903
+ return
904
+ }
905
+
906
+ this._mergeLoaded(loaded)
303
907
  try {
304
908
  saveJsonState(this._filePath, this._serialize(), { fsync: true, tmpSuffix })
305
909
  this._dirty = false
910
+ this._changedKeys.clear()
911
+ // #8098: a winning 'migrate' keeps its `_migrateExpectations` entry
912
+ // through the merge (see the 'migrate' branch in `_mergeLoaded()`) so
913
+ // a failed persist's retry can still re-derive the same CAS result
914
+ // against a fresh disk read. Only NOW, once the write has actually
915
+ // landed, is it safe to drop — `_records` (just serialised to disk)
916
+ // already holds every key's resolved value, including any winning
917
+ // migrate, so there is nothing left for a retry to protect. A losing
918
+ // CAS already deleted its own entry immediately inside the merge, so
919
+ // this is a no-op for it; only a still-pending winning migrate ever
920
+ // has real work left here.
921
+ this._migrateExpectations.clear()
922
+ this._onFlushCommitted()
306
923
  } catch (err) {
307
924
  this._log.warn(`Could not persist trust file (${err && err.code ? err.code : err.message || err})`)
308
925
  if (this._throwOnFlushError) throw err