@sema-agent/server 7.145.0 → 7.147.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (526) hide show
  1. package/MIGRATION.md +876 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/USAGE.md +374 -99
  5. package/deploy/facts/CHANGES.json +25 -0
  6. package/deploy/facts/README.md +57 -0
  7. package/deploy/facts/lanes.json +61 -0
  8. package/deploy/facts/lanes.schema.json +57 -0
  9. package/deploy/facts/sandbox-rbac.json +113 -0
  10. package/deploy/facts/sandbox-rbac.schema.json +74 -0
  11. package/deploy/facts/sealed-key.json +9 -0
  12. package/deploy/facts/sealed-key.schema.json +52 -0
  13. package/deploy/sema-up/README.md +2 -2
  14. package/deploy/sema-up/chart/templates/_helpers.tpl +41 -0
  15. package/deploy/sema-up/chart/templates/sandbox-rbac.yaml +47 -7
  16. package/deploy/sema-up/chart/templates/server-v4pro.yaml +9 -4
  17. package/deploy/sema-up/chart/templates/server.yaml +9 -4
  18. package/deploy/sema-up/chart/values.yaml +8 -1
  19. package/deploy/sema-up/cluster-up.sh +2 -1
  20. package/deploy/sema-up/lib/flagshape.sh +4 -0
  21. package/deploy/sema-up/lib/lanes.json +2 -5
  22. package/deploy/sema-up/sema-up.sh +12 -9
  23. package/deploy/sema-up/stack/compose.yaml +5 -4
  24. package/deploy/sema-up/stack/sema-stack-cluster.yaml +34 -17
  25. package/dist/adoption/import-limits.d.ts +6 -0
  26. package/dist/adoption/import-limits.js +7 -0
  27. package/dist/adoption/import.d.ts +62 -0
  28. package/dist/adoption/import.js +107 -0
  29. package/dist/adoption/wire.d.ts +52 -0
  30. package/dist/adoption/wire.js +9 -0
  31. package/dist/approval-ask-machine.d.ts +2 -2
  32. package/dist/approval-card.d.ts +7 -16
  33. package/dist/approval-card.js +0 -4
  34. package/dist/approval-gate-currency.d.ts +1 -1
  35. package/dist/approval-gate-currency.js +1 -1
  36. package/dist/approval-reconciler.d.ts +1 -1
  37. package/dist/approval.d.ts +3 -3
  38. package/dist/audit.js +2 -2
  39. package/dist/bench/s1/live-deps.js +3 -1
  40. package/dist/boot/crash-last.js +2 -1
  41. package/dist/boot/deployment-mods.d.ts +11 -1
  42. package/dist/boot/deployment-mods.js +15 -2
  43. package/dist/boot/device-lane.js +7 -5
  44. package/dist/boot/engine-lease.d.ts +195 -22
  45. package/dist/boot/engine-lease.js +146 -20
  46. package/dist/boot/execution-env.d.ts +5 -0
  47. package/dist/boot/execution-env.js +57 -33
  48. package/dist/boot/execution-lane.d.ts +37 -9
  49. package/dist/boot/execution-lane.js +74 -20
  50. package/dist/boot/exit-boundary.d.ts +50 -0
  51. package/dist/boot/exit-boundary.js +32 -0
  52. package/dist/boot/exit-last.d.ts +20 -4
  53. package/dist/boot/exit-last.js +23 -5
  54. package/dist/boot/governance-seams.d.ts +2 -2
  55. package/dist/boot/governance-seams.js +1 -0
  56. package/dist/boot/leader.js +1 -1
  57. package/dist/boot/memory-boundary.d.ts +11 -11
  58. package/dist/boot/memory-boundary.js +3 -3
  59. package/dist/boot/memory-consolidation.d.ts +42 -41
  60. package/dist/boot/memory-consolidation.js +26 -28
  61. package/dist/boot/org-memory.js +3 -2
  62. package/dist/boot/parked-revive-gate.d.ts +1 -1
  63. package/dist/boot/parked-revive-gate.js +1 -1
  64. package/dist/boot/reapers.d.ts +12 -4
  65. package/dist/boot/reapers.js +40 -16
  66. package/dist/boot/resolve-spec.d.ts +2 -0
  67. package/dist/boot/resolve-spec.js +126 -123
  68. package/dist/boot/retention-lane.d.ts +4 -42
  69. package/dist/boot/runner-deps.js +1 -1
  70. package/dist/boot/session-faces.d.ts +1 -0
  71. package/dist/boot/session-faces.js +11 -3
  72. package/dist/boot/shutdown.js +27 -9
  73. package/dist/boot/stage-01-config.d.ts +1 -1
  74. package/dist/boot/stage-01-config.js +7 -3
  75. package/dist/boot/stage-02-web-admin-pull.d.ts +1 -1
  76. package/dist/boot/stage-02-web-admin-pull.js +10 -8
  77. package/dist/boot/stage-03-store-backend.d.ts +2 -1
  78. package/dist/boot/stage-03-store-backend.js +2 -2
  79. package/dist/boot/stage-04-stores.d.ts +2 -1
  80. package/dist/boot/stage-05-execution-env.d.ts +4 -1
  81. package/dist/boot/stage-05-execution-env.js +6 -6
  82. package/dist/boot/stage-06-runners.d.ts +5 -2
  83. package/dist/boot/stage-06-runners.js +12 -13
  84. package/dist/boot/stage-07-capability-layer.d.ts +5 -2
  85. package/dist/boot/stage-07-capability-layer.js +7 -7
  86. package/dist/boot/stage-08-reapers.d.ts +5 -2
  87. package/dist/boot/stage-08-reapers.js +3 -3
  88. package/dist/boot/stage-09-leader.d.ts +6 -2
  89. package/dist/boot/stage-10-http-server.d.ts +6 -2
  90. package/dist/boot/stage-10-http-server.js +5 -3
  91. package/dist/boot/stores.d.ts +10 -0
  92. package/dist/boot/stores.js +53 -26
  93. package/dist/boot/web-admin.js +3 -3
  94. package/dist/boot/workflow-orchestration.d.ts +1 -1
  95. package/dist/boot/workflow-orchestration.js +2 -1
  96. package/dist/capabilities/center-plugins.d.ts +2 -0
  97. package/dist/capabilities/center-plugins.js +6 -2
  98. package/dist/capabilities/composite-members.d.ts +4 -1
  99. package/dist/capabilities/composite-members.js +4 -1
  100. package/dist/capabilities/execution-lane.d.ts +7 -7
  101. package/dist/capabilities/execution-lane.js +2 -2
  102. package/dist/capabilities/hands-lane.d.ts +1 -1
  103. package/dist/capabilities/scenarios.d.ts +34 -20
  104. package/dist/capabilities/scenarios.js +13 -9
  105. package/dist/capabilities/settings-contract.d.ts +29 -0
  106. package/dist/capabilities/settings-contract.js +14 -0
  107. package/dist/capabilities/skills.d.ts +5 -5
  108. package/dist/capability-facts.d.ts +56 -1
  109. package/dist/capability-facts.js +59 -8
  110. package/dist/center-credential-renewer.js +3 -2
  111. package/dist/checkpoint-ctx-seal-m28.d.ts +1 -1
  112. package/dist/config-catalog.js +19 -9
  113. package/dist/config-invariants.d.ts +18 -3
  114. package/dist/config-invariants.js +36 -19
  115. package/dist/config-lkg.d.ts +1 -1
  116. package/dist/config-lkg.js +5 -6
  117. package/dist/config-provider.d.ts +2 -2
  118. package/dist/config-provider.js +2 -0
  119. package/dist/config-types.d.ts +228 -185
  120. package/dist/config.d.ts +74 -6
  121. package/dist/config.js +146 -64
  122. package/dist/degenerate-instrument.js +1 -1
  123. package/dist/deleted-session-ids.d.ts +19 -0
  124. package/dist/deleted-session-ids.js +26 -0
  125. package/dist/deploy-facts.d.ts +155 -0
  126. package/dist/deploy-facts.js +95 -0
  127. package/dist/deployment-shape.d.ts +21 -12
  128. package/dist/deployment-shape.js +24 -6
  129. package/dist/device-ws-hub.d.ts +48 -3
  130. package/dist/device-ws-hub.js +48 -2
  131. package/dist/env-facts.d.ts +7 -5
  132. package/dist/env-facts.js +10 -6
  133. package/dist/error-code-family.d.ts +35 -0
  134. package/dist/error-code-family.js +26 -0
  135. package/dist/execution-config-root.d.ts +5 -5
  136. package/dist/execution-config-root.js +5 -5
  137. package/dist/execution-env-purpose.d.ts +14 -0
  138. package/dist/execution-env-purpose.js +29 -0
  139. package/dist/execution-lane-caps.d.ts +49 -86
  140. package/dist/execution-lane-caps.js +52 -62
  141. package/dist/execution-placement.d.ts +18 -2
  142. package/dist/execution-placement.js +19 -0
  143. package/dist/file-history-disclosure.d.ts +2 -2
  144. package/dist/fleet/drain-entry.d.ts +46 -3
  145. package/dist/fleet/drain-entry.js +6 -0
  146. package/dist/fleet/fleet-bus.d.ts +2 -1
  147. package/dist/fleet/serving-lease.js +3 -4
  148. package/dist/history-anchor.d.ts +22 -0
  149. package/dist/history-anchor.js +14 -0
  150. package/dist/hooks/branch-transcript.d.ts +1 -1
  151. package/dist/hooks/branch-transcript.js +1 -0
  152. package/dist/hooks/classic-stations.d.ts +25 -8
  153. package/dist/hooks/classic-stations.js +29 -3
  154. package/dist/hooks/command-spawn.d.ts +1 -4
  155. package/dist/hooks/command-spawn.js +0 -11
  156. package/dist/hooks/hook-runner.d.ts +85 -24
  157. package/dist/hooks/hook-runner.js +326 -109
  158. package/dist/hooks/hook-source.d.ts +14 -2
  159. package/dist/hooks/hook-source.js +8 -0
  160. package/dist/http/active-run-conflict.d.ts +1 -1
  161. package/dist/http/active-run-conflict.js +1 -1
  162. package/dist/http/admission.js +11 -1
  163. package/dist/http/approval-sweeps.d.ts +2 -5
  164. package/dist/http/approval-sweeps.js +3 -2
  165. package/dist/http/checkpoint-ctx.d.ts +76 -71
  166. package/dist/http/checkpoint-ctx.js +40 -40
  167. package/dist/http/claim-latency.d.ts +10 -0
  168. package/dist/http/claim-latency.js +12 -0
  169. package/dist/http/dispatch.js +19 -3
  170. package/dist/http/durable-run-leg.d.ts +5 -0
  171. package/dist/http/durable-run-leg.js +3 -1
  172. package/dist/http/execution-context.d.ts +7 -1
  173. package/dist/http/execution-context.js +13 -0
  174. package/dist/http/health-self-report.d.ts +6 -2
  175. package/dist/http/health-self-report.js +3 -2
  176. package/dist/http/memory-compliance-failure-reply.d.ts +2 -2
  177. package/dist/http/memory-compliance-failure-reply.js +5 -15
  178. package/dist/http/memory-control-plane-corrupt-reply.d.ts +25 -0
  179. package/dist/http/memory-control-plane-corrupt-reply.js +19 -0
  180. package/dist/http/memory-store-refusal-reply.d.ts +3 -3
  181. package/dist/http/memory-store-refusal-reply.js +3 -0
  182. package/dist/http/owner-access.d.ts +11 -0
  183. package/dist/http/owner-access.js +7 -4
  184. package/dist/http/principal-gate.d.ts +28 -16
  185. package/dist/http/principal-gate.js +10 -19
  186. package/dist/http/request-guards.d.ts +2 -2
  187. package/dist/http/request-guards.js +5 -5
  188. package/dist/http/resume-legs.d.ts +29 -10
  189. package/dist/http/resume-legs.js +94 -56
  190. package/dist/http/rewind-files-reply.d.ts +34 -0
  191. package/dist/http/rewind-files-reply.js +36 -0
  192. package/dist/http/route-ctx.d.ts +43 -26
  193. package/dist/http/route-table.js +4 -0
  194. package/dist/http/routes/adoption.d.ts +11 -0
  195. package/dist/http/routes/adoption.js +80 -6
  196. package/dist/http/routes/agents-roster.js +1 -0
  197. package/dist/http/routes/approvals-assistant.js +7 -26
  198. package/dist/http/routes/background.js +1 -0
  199. package/dist/http/routes/capabilities.js +12 -3
  200. package/dist/http/routes/devices.js +1 -1
  201. package/dist/http/routes/diagnostics.d.ts +9 -14
  202. package/dist/http/routes/diagnostics.js +10 -20
  203. package/dist/http/routes/engine.d.ts +31 -0
  204. package/dist/http/routes/engine.js +81 -0
  205. package/dist/http/routes/memory-bundle.js +3 -0
  206. package/dist/http/routes/memory-consolidation.js +3 -5
  207. package/dist/http/routes/memory-origin.d.ts +2 -2
  208. package/dist/http/routes/memory-origin.js +2 -4
  209. package/dist/http/routes/memory-policy.js +5 -1
  210. package/dist/http/routes/notify-wake.js +2 -1
  211. package/dist/http/routes/observability.js +3 -6
  212. package/dist/http/routes/projects.d.ts +70 -0
  213. package/dist/http/routes/projects.js +86 -0
  214. package/dist/http/routes/rules.js +30 -2
  215. package/dist/http/routes/runs.js +15 -11
  216. package/dist/http/routes/session-sync.js +39 -35
  217. package/dist/http/routes/sessions-list.d.ts +1 -1
  218. package/dist/http/routes/sessions.d.ts +7 -1
  219. package/dist/http/routes/sessions.js +108 -2
  220. package/dist/http/routes/tasks.js +32 -8
  221. package/dist/http/routes/trace-usage.js +1 -1
  222. package/dist/http/run-concurrency-cap.d.ts +86 -0
  223. package/dist/http/run-concurrency-cap.js +54 -0
  224. package/dist/http/server.d.ts +31 -14
  225. package/dist/http/server.js +29 -3
  226. package/dist/http/stored-body-replay.d.ts +12 -7
  227. package/dist/http/stored-body-replay.js +28 -5
  228. package/dist/http/wire-types.d.ts +27 -13
  229. package/dist/index.d.ts +2 -2
  230. package/dist/index.js +1 -1
  231. package/dist/instruction-source-notice.d.ts +1 -1
  232. package/dist/json-body-limit.d.ts +8 -0
  233. package/dist/json-body-limit.js +2 -0
  234. package/dist/leader/diffout.d.ts +1 -1
  235. package/dist/local-data-root.d.ts +2 -2
  236. package/dist/memory-embedder-reembed.d.ts +38 -0
  237. package/dist/memory-embedder-reembed.js +20 -0
  238. package/dist/memory-incident-sink.d.ts +0 -28
  239. package/dist/memory-incident-sink.js +5 -0
  240. package/dist/memory-operator-faces.d.ts +9 -4
  241. package/dist/memory-scope-stores.d.ts +9 -7
  242. package/dist/memory-scope-stores.js +3 -14
  243. package/dist/memory-scope.d.ts +38 -2
  244. package/dist/memory-scope.js +33 -2
  245. package/dist/memory-store-refusal.d.ts +17 -4
  246. package/dist/memory-store-refusal.js +1 -1
  247. package/dist/memory-sync-client.d.ts +2 -0
  248. package/dist/memory-sync-client.js +13 -11
  249. package/dist/memory-sync.js +1 -1
  250. package/dist/model-compat.d.ts +35 -21
  251. package/dist/model-compat.js +49 -21
  252. package/dist/model-entry-refusal.d.ts +11 -1
  253. package/dist/model-entry-refusal.js +7 -0
  254. package/dist/namespaced-rule-name.d.ts +18 -1
  255. package/dist/namespaced-rule-name.js +12 -0
  256. package/dist/net-address.d.ts +53 -0
  257. package/dist/net-address.js +111 -0
  258. package/dist/observability/fail-open.d.ts +29 -17
  259. package/dist/observability/fail-open.js +29 -17
  260. package/dist/observability/metrics.d.ts +2 -0
  261. package/dist/observability/metrics.js +2 -0
  262. package/dist/observability/secret-env-scrub.d.ts +30 -4
  263. package/dist/observability/secret-env-scrub.js +15 -3
  264. package/dist/orchestration/workflow-agent-session-index.d.ts +7 -12
  265. package/dist/orchestration/workflow-agent-session-index.js +1 -6
  266. package/dist/orchestration/workflow-completion-inbox.d.ts +26 -6
  267. package/dist/orchestration/workflow-completion-inbox.js +63 -45
  268. package/dist/orchestration/workflow-notify-journal.js +2 -3
  269. package/dist/org-delivery-gate.js +1 -1
  270. package/dist/org-memory-admission.d.ts +5 -2
  271. package/dist/org-memory-admission.js +25 -10
  272. package/dist/parked-decide.d.ts +33 -26
  273. package/dist/parked-decide.js +36 -44
  274. package/dist/peer-directory.d.ts +6 -12
  275. package/dist/peer-directory.js +5 -1
  276. package/dist/plugins/approval-ask-store-file.d.ts +10 -2
  277. package/dist/plugins/approval-ask-store-file.js +37 -4
  278. package/dist/plugins/approval-ask-store-memory.d.ts +5 -3
  279. package/dist/plugins/approval-ask-store-memory.js +11 -2
  280. package/dist/plugins/approval-ask-store-sql.d.ts +3 -0
  281. package/dist/plugins/approval-ask-store-sql.js +3 -1
  282. package/dist/plugins/blob-backend.d.ts +38 -195
  283. package/dist/plugins/blob-backend.js +33 -229
  284. package/dist/plugins/caching-session-store.d.ts +12 -5
  285. package/dist/plugins/caching-session-store.js +3 -0
  286. package/dist/plugins/checkpoint-index-columns.d.ts +1 -1
  287. package/dist/plugins/checkpoint-index-columns.js +3 -2
  288. package/dist/plugins/checkpoint-store-face.d.ts +426 -0
  289. package/dist/plugins/checkpoint-store-face.js +152 -0
  290. package/dist/plugins/device-store-sql.d.ts +2 -2
  291. package/dist/plugins/device-store-sql.js +5 -10
  292. package/dist/plugins/execution-lane-rename-m40.d.ts +20 -0
  293. package/dist/plugins/execution-lane-rename-m40.js +10 -0
  294. package/dist/plugins/execution-placement-sql.d.ts +63 -88
  295. package/dist/plugins/execution-placement-sql.js +94 -54
  296. package/dist/plugins/file-run-store.d.ts +26 -18
  297. package/dist/plugins/file-run-store.js +64 -75
  298. package/dist/plugins/fork-routing-session-store.d.ts +6 -2
  299. package/dist/plugins/fork-routing-session-store.js +2 -2
  300. package/dist/plugins/imported-layer-root-retirement.d.ts +22 -11
  301. package/dist/plugins/imported-layer-root-retirement.js +4 -8
  302. package/dist/plugins/inbox-payload-column.d.ts +14 -0
  303. package/dist/plugins/inbox-payload-column.js +13 -0
  304. package/dist/plugins/local-checkpoint-store.d.ts +7 -2
  305. package/dist/plugins/local-checkpoint-store.js +13 -8
  306. package/dist/plugins/local-data-dir-modes-m39.d.ts +48 -0
  307. package/dist/plugins/local-data-dir-modes-m39.js +182 -0
  308. package/dist/plugins/local-engine-high-water.d.ts +11 -0
  309. package/dist/plugins/local-engine-high-water.js +59 -0
  310. package/dist/plugins/local-session-store.d.ts +119 -30
  311. package/dist/plugins/local-session-store.js +156 -53
  312. package/dist/plugins/local-task-attachment-store.d.ts +2 -0
  313. package/dist/plugins/local-task-attachment-store.js +10 -11
  314. package/dist/plugins/memory-embedder-fingerprint.d.ts +33 -10
  315. package/dist/plugins/memory-embedder-fingerprint.js +52 -12
  316. package/dist/plugins/memory-embedder.d.ts +1 -1
  317. package/dist/plugins/memory-embedder.js +2 -2
  318. package/dist/plugins/memory-engine-pg.d.ts +30 -6
  319. package/dist/plugins/memory-engine-pg.js +96 -214
  320. package/dist/plugins/memory-engine-sql-apply.d.ts +130 -0
  321. package/dist/plugins/memory-engine-sql-apply.js +358 -0
  322. package/dist/plugins/memory-engine-tidb.d.ts +38 -9
  323. package/dist/plugins/memory-engine-tidb.js +99 -230
  324. package/dist/plugins/memory-key-guards.d.ts +1 -1
  325. package/dist/plugins/memory-origin-law.d.ts +3 -3
  326. package/dist/plugins/one-time-migrations.d.ts +169 -83
  327. package/dist/plugins/one-time-migrations.js +295 -235
  328. package/dist/plugins/owner-only-file-mode.d.ts +29 -0
  329. package/dist/plugins/owner-only-file-mode.js +141 -0
  330. package/dist/plugins/permission-rule-store-file.d.ts +17 -3
  331. package/dist/plugins/permission-rule-store-file.js +20 -1
  332. package/dist/plugins/pg-pool.d.ts +2 -1
  333. package/dist/plugins/pg-pool.js +12 -5
  334. package/dist/plugins/release-version.d.ts +20 -0
  335. package/dist/plugins/release-version.js +28 -0
  336. package/dist/plugins/remote-env-adb.d.ts +20 -4
  337. package/dist/plugins/remote-env-adb.js +39 -11
  338. package/dist/plugins/remote-env-e2b.d.ts +12 -3
  339. package/dist/plugins/remote-env-e2b.js +6 -4
  340. package/dist/plugins/remote-env-host.d.ts +9 -1
  341. package/dist/plugins/remote-env-host.js +6 -5
  342. package/dist/plugins/remote-env-k8s.d.ts +5 -2
  343. package/dist/plugins/remote-env-k8s.js +15 -4
  344. package/dist/plugins/remote-env-local-docker.d.ts +4 -1
  345. package/dist/plugins/remote-env-local-docker.js +3 -3
  346. package/dist/plugins/remote-env-ssh.d.ts +8 -2
  347. package/dist/plugins/remote-env-ssh.js +26 -24
  348. package/dist/plugins/remote-shell.d.ts +59 -30
  349. package/dist/plugins/remote-shell.js +175 -62
  350. package/dist/plugins/retention-declaration.d.ts +37 -0
  351. package/dist/plugins/retention-declaration.js +9 -0
  352. package/dist/plugins/retention-deployment.d.ts +126 -0
  353. package/dist/plugins/retention-deployment.js +88 -0
  354. package/dist/plugins/retention-lane-store-sql.d.ts +74 -4
  355. package/dist/plugins/retention-lane-store-sql.js +103 -1
  356. package/dist/plugins/retention-sql.d.ts +29 -0
  357. package/dist/plugins/retention-sql.js +8 -0
  358. package/dist/plugins/run-store-sql.js +2 -2
  359. package/dist/plugins/schema-consistency.d.ts +0 -6
  360. package/dist/plugins/schema-consistency.js +1 -2
  361. package/dist/plugins/schema-ensure-legs.d.ts +1 -1
  362. package/dist/plugins/schema-ensure-legs.js +13 -3
  363. package/dist/plugins/session-ext-table.d.ts +74 -0
  364. package/dist/plugins/session-ext-table.js +121 -0
  365. package/dist/plugins/session-fork.d.ts +31 -9
  366. package/dist/plugins/session-fork.js +3 -2
  367. package/dist/plugins/session-placement.d.ts +4 -2
  368. package/dist/plugins/session-row-sql.d.ts +8 -7
  369. package/dist/plugins/session-row-sql.js +15 -7
  370. package/dist/plugins/session-store-sql.d.ts +131 -0
  371. package/dist/plugins/session-store-sql.js +298 -0
  372. package/dist/plugins/session-workspace-cell.d.ts +2 -2
  373. package/dist/plugins/session-workspace-cell.js +2 -2
  374. package/dist/plugins/shared-memory-store-sql.d.ts +10 -0
  375. package/dist/plugins/shared-memory-store-sql.js +13 -13
  376. package/dist/plugins/snapshot-bucket-presence.js +1 -1
  377. package/dist/plugins/sql-driver.d.ts +23 -7
  378. package/dist/plugins/sql-driver.js +41 -8
  379. package/dist/plugins/sql-errors.d.ts +5 -2
  380. package/dist/plugins/sql-errors.js +4 -0
  381. package/dist/plugins/sql-json-column.d.ts +5 -1
  382. package/dist/plugins/store-backend.d.ts +46 -16
  383. package/dist/plugins/store-backend.js +192 -69
  384. package/dist/plugins/store-contracts.d.ts +10 -13
  385. package/dist/plugins/store-contracts.js +1 -9
  386. package/dist/plugins/store-sweep.d.ts +63 -0
  387. package/dist/plugins/store-sweep.js +48 -0
  388. package/dist/plugins/task-attachment-store.d.ts +6 -8
  389. package/dist/plugins/task-attachment-store.js +15 -10
  390. package/dist/plugins/task-list-store-sql.d.ts +1 -1
  391. package/dist/plugins/text-column-capacity.d.ts +21 -0
  392. package/dist/plugins/text-column-capacity.js +5 -0
  393. package/dist/plugins/tidb-pool.d.ts +3 -2
  394. package/dist/plugins/tidb-pool.js +20 -32
  395. package/dist/plugins/user-input-ledger-sql.d.ts +1 -1
  396. package/dist/prompt-screen.d.ts +6 -9
  397. package/dist/prompt-screen.js +2 -5
  398. package/dist/read-face-posture.d.ts +6 -6
  399. package/dist/read-face-posture.js +2 -2
  400. package/dist/request-value-closure.d.ts +5 -5
  401. package/dist/request-value-closure.js +1 -1
  402. package/dist/rules-consent.d.ts +48 -27
  403. package/dist/rules-consent.js +147 -23
  404. package/dist/run-cancel-context.d.ts +4 -1
  405. package/dist/run-cancel-context.js +2 -1
  406. package/dist/run-local.js +17 -13
  407. package/dist/runs.d.ts +48 -30
  408. package/dist/runs.js +27 -17
  409. package/dist/runtime-caps-resolver.d.ts +15 -8
  410. package/dist/runtime-caps-resolver.js +14 -10
  411. package/dist/sandbox-egress-policy.js +6 -11
  412. package/dist/sandbox-rbac-rules.d.ts +88 -0
  413. package/dist/sandbox-rbac-rules.js +80 -0
  414. package/dist/sealed-key-layout.d.ts +16 -0
  415. package/dist/sealed-key-layout.js +3 -0
  416. package/dist/sealed-key.js +8 -6
  417. package/dist/security.d.ts +43 -9
  418. package/dist/security.js +9 -2
  419. package/dist/sema-config-dir.js +2 -2
  420. package/dist/server-secret-env.d.ts +2 -0
  421. package/dist/service-version.d.ts +2 -1
  422. package/dist/service-version.js +2 -2
  423. package/dist/session-error-wire.d.ts +1 -1
  424. package/dist/session-incarnation.d.ts +8 -5
  425. package/dist/session-notify-door.d.ts +5 -3
  426. package/dist/session-resident-background.d.ts +110 -0
  427. package/dist/session-resident-background.js +88 -0
  428. package/dist/session-row.d.ts +1 -1
  429. package/dist/session-sync-kernel.d.ts +53 -14
  430. package/dist/session-sync-kernel.js +70 -1
  431. package/dist/session-sync.d.ts +5 -3
  432. package/dist/session-workspace.d.ts +12 -2
  433. package/dist/session-workspace.js +6 -0
  434. package/dist/sighup-idle.d.ts +9 -7
  435. package/dist/sighup-idle.js +4 -5
  436. package/dist/spec-fields.d.ts +16 -0
  437. package/dist/spec-fields.js +7 -0
  438. package/dist/store-posture.d.ts +2 -1
  439. package/dist/stored-request-env-credentials-m38.d.ts +3 -0
  440. package/dist/stored-request-env-credentials-m38.js +8 -0
  441. package/dist/stored-request-hooks-m20.d.ts +3 -2
  442. package/dist/stored-request-hooks-m20.js +19 -14
  443. package/dist/stored-request-prompt-profile-m30.d.ts +1 -1
  444. package/dist/stores-sql/blob-index-sql.d.ts +148 -0
  445. package/dist/stores-sql/blob-index-sql.js +154 -0
  446. package/dist/{plugins → stores-sql}/checkpoint-store-sql.d.ts +14 -428
  447. package/dist/{plugins → stores-sql}/checkpoint-store-sql.js +43 -220
  448. package/dist/{plugins → stores-sql}/file-history-store-sql.d.ts +23 -11
  449. package/dist/{plugins → stores-sql}/file-history-store-sql.js +23 -18
  450. package/dist/{plugins → stores-sql}/mailbox-store-sql.d.ts +2 -2
  451. package/dist/{plugins → stores-sql}/mailbox-store-sql.js +4 -4
  452. package/dist/{plugins → stores-sql}/pg-session-storage.d.ts +27 -67
  453. package/dist/{plugins → stores-sql}/pg-session-storage.js +82 -207
  454. package/dist/{plugins → stores-sql}/retention-store-sql.d.ts +123 -217
  455. package/dist/{plugins → stores-sql}/retention-store-sql.js +66 -190
  456. package/dist/{plugins → stores-sql}/roster-store-sql.d.ts +2 -2
  457. package/dist/{plugins → stores-sql}/roster-store-sql.js +1 -1
  458. package/dist/{plugins → stores-sql}/session-event-payload.d.ts +1 -1
  459. package/dist/{plugins → stores-sql}/session-event-payload.js +1 -1
  460. package/dist/stores-sql/session-policy-store-sql.d.ts +1 -1
  461. package/dist/stores-sql/session-write-hooks.d.ts +59 -0
  462. package/dist/stores-sql/session-write-hooks.js +2 -0
  463. package/dist/{plugins → stores-sql}/tidb-session-storage.d.ts +10 -11
  464. package/dist/{plugins → stores-sql}/tidb-session-storage.js +10 -21
  465. package/dist/{plugins → stores-sql}/tidb-session-store.d.ts +35 -112
  466. package/dist/{plugins → stores-sql}/tidb-session-store.js +73 -169
  467. package/dist/{plugins → stores-sql}/tool-result-store-sql.d.ts +3 -3
  468. package/dist/{plugins → stores-sql}/tool-result-store-sql.js +6 -6
  469. package/dist/stores-sql/windowed-session-storage.d.ts +56 -0
  470. package/dist/stores-sql/windowed-session-storage.js +61 -0
  471. package/dist/{plugins → stores-sql}/workflow-journal-store-sql.d.ts +7 -12
  472. package/dist/{plugins → stores-sql}/workflow-journal-store-sql.js +3 -8
  473. package/dist/task-a2a.d.ts +7 -1
  474. package/dist/task-a2a.js +15 -14
  475. package/dist/task-cwd.d.ts +11 -3
  476. package/dist/task-cwd.js +17 -1
  477. package/dist/task-mcp.d.ts +10 -2
  478. package/dist/task-mcp.js +13 -16
  479. package/dist/task-settings.d.ts +68 -8
  480. package/dist/task-settings.js +63 -6
  481. package/dist/tool-approval.d.ts +23 -10
  482. package/dist/tool-approval.js +10 -6
  483. package/dist/trace/core-keyset-guard.d.ts +17 -10
  484. package/dist/trace/engine-notice-wire.d.ts +1 -1
  485. package/dist/trace/engine-notice-wire.js +4 -0
  486. package/dist/trace/exit-seat.d.ts +29 -1
  487. package/dist/trace/exit-seat.js +4 -0
  488. package/dist/trace/project.d.ts +33 -16
  489. package/dist/trace/project.js +21 -9
  490. package/dist/trace/redact.d.ts +13 -2
  491. package/dist/trace/redact.js +347 -78
  492. package/dist/trace/self-minted-wire.d.ts +587 -16
  493. package/dist/trace/self-minted-wire.js +215 -9
  494. package/dist/trace/sema-provenance.d.ts +45 -41
  495. package/dist/trace/sema-provenance.js +81 -10
  496. package/dist/trace/task-notification-facets.d.ts +70 -2
  497. package/dist/trace/task-notification-facets.js +71 -1
  498. package/dist/trace/wire-projection-faces.d.ts +39 -3
  499. package/dist/trace/wire-projection-faces.js +27 -2
  500. package/dist/unread-request-members.d.ts +66 -0
  501. package/dist/unread-request-members.js +41 -0
  502. package/dist/usage-analytics.d.ts +4 -0
  503. package/dist/user-input-ledger.d.ts +2 -2
  504. package/dist/web-admin-client/apply-effective.js +22 -26
  505. package/dist/web-admin-client/candidate-gate.d.ts +35 -3
  506. package/dist/web-admin-client/candidate-gate.js +53 -5
  507. package/dist/web-admin-client/center-request.d.ts +4 -1
  508. package/dist/web-admin-client/center-request.js +2 -1
  509. package/dist/web-admin-client/effective-keys.js +0 -1
  510. package/dist/web-admin-client/facade.d.ts +1 -1
  511. package/dist/web-admin-client/http-client.d.ts +1 -0
  512. package/dist/web-admin-client/http-client.js +17 -9
  513. package/dist/web-admin-client/restart-signal.js +5 -2
  514. package/dist/web-admin-client/skills-mcp.d.ts +20 -6
  515. package/dist/web-admin-client/skills-mcp.js +26 -21
  516. package/dist/web-admin-client/types.d.ts +34 -49
  517. package/docs/DEVICE-EXECUTOR-PROTOCOL.md +2 -2
  518. package/package.json +22 -13
  519. package/scripts/drain-check-local.mjs +8 -55
  520. package/scripts/drain-check.mysql.sql +3 -40
  521. package/scripts/drain-check.pg.sql +3 -40
  522. package/skills/update-config.md +1 -1
  523. package/wire-changes/server@7.146.0.json +3221 -0
  524. package/wire-changes/server@7.147.0.json +813 -0
  525. package/dist/approval-batch-census.d.ts +0 -27
  526. package/dist/approval-batch-census.js +0 -27
@@ -1,26 +1,27 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, unlinkSync } from "node:fs";
1
+ import { lstat, readFile } from "node:fs/promises";
2
+ import { closeSync, existsSync, fsyncSync, lstatSync, openSync, readdirSync, readFileSync, unlinkSync } from "node:fs";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { isDeepStrictEqual } from "node:util";
5
5
  import { dirname, join, resolve } from "node:path";
6
+ import { atomicWriteFileAsync } from "./owner-only-file-mode.js";
6
7
  import { assertFirstOwnerWritable, forkOwnerOf, importerOwnerOf, placedSessionOwnerOf } from "./session-ownership.js";
7
8
  import { SessionOwnerUnreadableError, StampedSessionArchiveError, sessionUnreadableOf } from "../session-error-wire.js";
8
- import { FileSessionRepo, SessionError, StoredSession, admitSessionPlacement, atomicWriteFile, sessionLogMarkOf, settledForkOptions, uuidv7, validateEntriesForImport } from "@sema-agent/core";
9
+ import { FileSessionRepo, SessionError, StoredSession, admitSessionPlacement, atomicWriteFile, ensureDir, sessionLogMarkOf, settledForkOptions, uuidv7, validateEntriesForImport } from "@sema-agent/core";
9
10
  import { placementCapabilityOf } from "./session-placement.js";
10
11
  import { z } from "zod";
11
12
  import { contentForkRelation, fastForwardSharedContentDiverged, identicalIdsAlsoIdenticalContent } from "../session-sync-content.js";
12
- import { StoreBootRefusalError } from "./store-contracts.js";
13
+ import { SCHEMA_MISMATCH_ERROR_CODE, StoreBootRefusalError } from "./store-contracts.js";
13
14
  import { judgeSessionRowWrite, sessionRowTagKey, settleSessionRowWrite, } from "../session-row.js";
14
15
  import { quarantineUnreadableSidecar } from "./local-sidecar-quarantine.js";
15
- import { createZodColumnReader, decodeJsonColumn, isJsonColumnBodyProblem, readStringRecordColumn, SqlJsonColumnError } from "./sql-json-column.js";
16
- import { SCHEMA_MISMATCH_ERROR_CODE } from "./schema-consistency.js";
17
- import { ONE_TIME_MIGRATIONS, migrationWindowOpen } from "./one-time-migrations.js";
16
+ import { createZodColumnReader, decodeJsonColumn, isJsonColumnBodyProblem, isJsonObject, readJsonObjectColumn, readStringRecordColumn, SqlJsonColumnError } from "./sql-json-column.js";
17
+ import { RENAMED_EXECUTION_LANE_M40, RETIRED_EXECUTION_LANE_WORD_M40 } from "./execution-lane-rename-m40.js";
18
+ import { ExecutionLaneRenameWriteRefusedError, ONE_TIME_MIGRATIONS, migrationWindowOpen } from "./one-time-migrations.js";
18
19
  import { recordFailOpen } from "../observability/fail-open.js";
19
20
  import { createLogger } from "../observability/logger.js";
20
- import { UNMANAGED_RETENTION } from "./retention-store-sql.js";
21
+ import { UNMANAGED_RETENTION } from "./retention-declaration.js";
21
22
  import { UnreadableLeaf, carriedRowCells, headFromRow, incarnationFromCell, mintSessionIncarnation, sessionFaceFromRow } from "../session-incarnation.js";
22
23
  import { isExecutionLane } from "../execution-lane-caps.js";
23
- import { SessionForkInProgressError, SessionWriterPresentError, WRITABLE, assertPlaceableLane, isUnusableArchive, settledMirrorOutcome, settledPlaceOutcome, } from "../execution-placement.js";
24
+ import { SessionForkInProgressError, WRITABLE, assertPlaceableLane, isUnusableArchive, judgeImportWrite, settledMirrorOutcome, settledPlaceOutcome, } from "../execution-placement.js";
24
25
  import { classifyForkTarget, forkByFreshId } from "./session-fork.js";
25
26
  import { decodeInstructionSource, encodeInstructionSource, sameInstructionSourceBaseline } from "../instruction-source-notice.js";
26
27
  import { decodeSessionWorkspaceCell, encodeSessionWorkspaceCell } from "./session-workspace-cell.js";
@@ -126,9 +127,13 @@ function rowMetadataOf(sessionId, meta) {
126
127
  return { id: sessionId, createdAt: rowCreatedAtOf(sessionId, meta), owner: face.owner, incarnation: face.incarnation, ...(meta.forkedFrom !== undefined ? { forkedFrom: meta.forkedFrom } : {}) };
127
128
  }
128
129
  const isForkCreatedCell = (meta) => meta !== undefined && meta.forkKey !== undefined && meta.execution === undefined;
130
+ function placementCellOf(meta, forking) {
131
+ return forking ? { role: "forking" } : (meta?.execution ?? { role: "absent" });
132
+ }
129
133
  function readingOfCell(sessionId, meta, forking) {
130
- return { occupant: sessionFaceFromRow(sessionId, meta.owner ?? null, meta.incarnation), cell: forking ? { role: "forking" } : (meta.execution ?? { role: "absent" }) };
134
+ return { occupant: sessionFaceFromRow(sessionId, meta.owner ?? null, meta.incarnation), cell: placementCellOf(meta, forking) };
131
135
  }
136
+ const SESSION_META_SIDECAR_FILE = "session-incarnations.json";
132
137
  const LOCAL_EXECUTION_CELL = z.discriminatedUnion("role", [
133
138
  z.object({ role: z.literal("writer"), lane: z.custom((v) => typeof v === "string" && isExecutionLane(v), { message: "not an execution lane" }) }).strict(),
134
139
  z.object({ role: z.literal("mirror") }).strict(),
@@ -154,18 +159,23 @@ function ownerClaimWindowOpen() {
154
159
  const SIDECAR_MAP_STATE_BY_PATH = new Map();
155
160
  const SESSION_WRITE_LOCKS_BY_ROOT = new Map();
156
161
  const quotedFieldNames = (names) => `${names.slice(0, 8).map((name) => JSON.stringify(name.slice(0, 64))).join(", ")}${names.length > 8 ? `, … (${names.length} in all)` : ""}`;
162
+ function describeDataRootFinding(f) {
163
+ if (f.problem === "newer-engine") {
164
+ return ` ${f.label} at ${f.path}: engine high-water ${f.engineHighWater.highWater} — the data root has been opened by server ${f.engineHighWater.highWater}, NEWER than this build (${f.engineHighWater.engine}).`;
165
+ }
166
+ return f.unknownFields.length > 0
167
+ ? ` ${f.label} at ${f.path}: UNKNOWN field(s) ${quotedFieldNames(f.unknownFields)} — the data root is NEWER than this build (a newer server engine wrote it).`
168
+ : ` ${f.label} at ${f.path}: unreadable (${f.problem}) — this build cannot read it, and an unreadable file is treated as a mismatch, not as empty.`;
169
+ }
157
170
  function describeLocalDataRootMismatch(findings, when) {
158
171
  const lines = [
159
172
  when === "boot"
160
173
  ? `${SCHEMA_MISMATCH_ERROR_CODE}: the local data root does not match this build's shape — refusing to start.`
161
174
  : `${SCHEMA_MISMATCH_ERROR_CODE}: the local data root does not match this build's shape — refusing to read or write the file(s) named below until this process is restarted.`,
162
175
  ];
163
- for (const f of findings) {
164
- lines.push(f.unknownFields.length > 0
165
- ? ` ${f.label} at ${f.path}: UNKNOWN field(s) ${quotedFieldNames(f.unknownFields)} — the data root is NEWER than this build (a newer server engine wrote it).`
166
- : ` ${f.label} at ${f.path}: unreadable (${f.problem}) — this build cannot read it, and an unreadable file is treated as a mismatch, not as empty.`);
167
- }
168
- lines.push("This build never reads such a file as empty and never writes over it: either would silently change what the file records.", "", " Ways out (these three and no others):", " (1) the data root is NEWER than this build (unknown fields): deploy the build that wrote it;", " (2) roll back: restore the data-root backup taken before the upgrade, then start this build — also the way out when the file's bytes are damaged (not-json / malformed);", " (3) the file could not be read at all (an I/O error such as EACCES): repair access to it (permissions, mount, disk) and restart — nothing in the file needs changing.", "The check behind this refusal only reads: the file was left in place and nothing in the data root was changed.");
176
+ for (const f of findings)
177
+ lines.push(describeDataRootFinding(f));
178
+ lines.push("This build never reads such a file as empty and never writes over it: either would silently change what the file records.", "", " Ways out (these three and no others):", " (1) the data root is NEWER than this build (unknown fields, or an engine high-water above this build): deploy the build that wrote it (for a high-water: server at or above it) — to run an older build on this machine, give it its own data root (LOCAL_DATA_ROOT);", " (2) roll back: restore the data-root backup taken before the upgrade, then start this build — also the way out when the file's bytes are damaged (not-json / malformed);", " (3) the file could not be read at all (an I/O error such as EACCES): repair access to it (permissions, mount, disk) and restart — nothing in the file needs changing.", "The check behind this refusal only reads: the file(s) named above were left in place, unchanged.");
169
179
  return lines.join("\n");
170
180
  }
171
181
  export class LocalDataRootSchemaMismatchError extends StoreBootRefusalError {
@@ -179,6 +189,56 @@ export class LocalDataRootSchemaMismatchError extends StoreBootRefusalError {
179
189
  this.name = "LocalDataRootSchemaMismatchError";
180
190
  }
181
191
  }
192
+ export async function readDataRootFileText(path) {
193
+ try {
194
+ return { state: "text", text: await readFile(path, "utf8") };
195
+ }
196
+ catch (e) {
197
+ if (e?.code !== "ENOENT")
198
+ return { state: "unreadable", fault: e };
199
+ return judgedAfterEnoent(e, await lstat(path).then(() => ENTRY_PRESENT, (fault) => ({ fault })));
200
+ }
201
+ }
202
+ export function readDataRootFileTextSync(path) {
203
+ try {
204
+ return { state: "text", text: readFileSync(path, "utf8") };
205
+ }
206
+ catch (e) {
207
+ if (e?.code !== "ENOENT")
208
+ return { state: "unreadable", fault: e };
209
+ let probe = ENTRY_PRESENT;
210
+ try {
211
+ lstatSync(path);
212
+ }
213
+ catch (fault) {
214
+ probe = { fault };
215
+ }
216
+ return judgedAfterEnoent(e, probe);
217
+ }
218
+ }
219
+ const ENTRY_PRESENT = { present: true };
220
+ function judgedAfterEnoent(readFault, probe) {
221
+ if ("present" in probe)
222
+ return { state: "unreadable", fault: readFault };
223
+ return probe.fault?.code === "ENOENT" ? { state: "absent" } : { state: "unreadable", fault: probe.fault };
224
+ }
225
+ export function dataRootMismatchOf(path, label, fault) {
226
+ if (fault instanceof SqlJsonColumnError)
227
+ return { path, label, problem: fault.problem, unknownFields: fault.unknownKeys };
228
+ const code = fault?.code;
229
+ return { path, label, problem: typeof code === "string" && /^E[A-Z0-9_]+$/.test(code) ? code : "unreadable", unknownFields: [] };
230
+ }
231
+ async function readSessionMetaForM40(path) {
232
+ const raw = await readDataRootFileText(path);
233
+ if (raw.state !== "text")
234
+ return raw;
235
+ try {
236
+ return { state: "read", entries: decodeJsonColumn(raw.text, readJsonObjectColumn, `${SESSION_META_SIDECAR_FILE} (one-time migration M40)`) };
237
+ }
238
+ catch (e) {
239
+ return { state: "unreadable", fault: e };
240
+ }
241
+ }
182
242
  class SidecarMap {
183
243
  path;
184
244
  label;
@@ -244,15 +304,11 @@ class SidecarMap {
244
304
  throw this.refuse(path, disk);
245
305
  }
246
306
  async readDisk(path) {
247
- let text;
307
+ const raw = await readDataRootFileText(path);
308
+ if (raw.state !== "text")
309
+ return raw;
248
310
  try {
249
- text = await readFile(path, "utf8");
250
- }
251
- catch (e) {
252
- return e?.code === "ENOENT" ? { state: "absent" } : { state: "unreadable", fault: e };
253
- }
254
- try {
255
- return { state: "read", entries: decodeJsonColumn(text, this.read, this.label) };
311
+ return { state: "read", entries: decodeJsonColumn(raw.text, this.read, this.label) };
256
312
  }
257
313
  catch (e) {
258
314
  return { state: "unreadable", fault: e };
@@ -260,9 +316,7 @@ class SidecarMap {
260
316
  }
261
317
  refuse(path, disk) {
262
318
  const shape = isJsonColumnBodyProblem(disk.fault);
263
- const problem = disk.fault instanceof SqlJsonColumnError ? disk.fault.problem : (disk.fault?.code ?? "unreadable");
264
- const unknownFields = disk.fault instanceof SqlJsonColumnError ? disk.fault.unknownKeys : [];
265
- const refusal = new LocalDataRootSchemaMismatchError([{ path, label: this.label, problem, unknownFields }], "serving");
319
+ const refusal = new LocalDataRootSchemaMismatchError([dataRootMismatchOf(path, this.label, disk.fault)], "serving");
266
320
  if (shape)
267
321
  this.state.refused = refusal;
268
322
  return refusal;
@@ -300,9 +354,7 @@ class SidecarMap {
300
354
  }
301
355
  }
302
356
  try {
303
- const tmp = `${path}.tmp-${process.pid}-${Date.now()}`;
304
- await writeFile(tmp, JSON.stringify(Object.fromEntries(draft)), "utf8");
305
- await rename(tmp, path);
357
+ await atomicWriteFileAsync(path, JSON.stringify(Object.fromEntries(draft)), { durability: "best-effort" });
306
358
  }
307
359
  catch (e) {
308
360
  this.onWriteFailed(e);
@@ -435,7 +487,6 @@ export class LocalSessionStore {
435
487
  flushTimer;
436
488
  writeChain = Promise.resolve();
437
489
  dirty = false;
438
- writeSeq = 0;
439
490
  lastWarnAt = 0;
440
491
  sidecarPath;
441
492
  titles;
@@ -493,7 +544,7 @@ export class LocalSessionStore {
493
544
  this.pinned = sidecar("session-pinned.json", "pinned", readPinnedSidecar);
494
545
  this.instructionSources = sidecar("session-instruction-sources.json", "instruction-source", readStringRecordColumn);
495
546
  this.workspaces = sidecar("session-workspaces.json", "workspace", readStringRecordColumn);
496
- this.meta = sidecar("session-incarnations.json", "session-meta", readSessionMetaSidecar, true);
547
+ this.meta = sidecar(SESSION_META_SIDECAR_FILE, "session-meta", readSessionMetaSidecar, true);
497
548
  const root = dataDir ? resolve(dataDir) : undefined;
498
549
  this.dataRoot = root;
499
550
  if (root !== undefined && !SESSION_WRITE_LOCKS_BY_ROOT.has(root))
@@ -509,6 +560,33 @@ export class LocalSessionStore {
509
560
  place: (sessionId, occupant, cell) => this.placeExecution(sessionId, occupant, cell),
510
561
  };
511
562
  }
563
+ async renameRetiredExecutionLaneWordM40() {
564
+ if (this.dataRoot === undefined)
565
+ return 0;
566
+ const path = join(this.dataRoot, SESSION_META_SIDECAR_FILE);
567
+ const disk = await readSessionMetaForM40(path);
568
+ if (disk.state !== "read")
569
+ return 0;
570
+ let renamed = 0;
571
+ for (const cell of Object.values(disk.entries)) {
572
+ if (!isJsonObject(cell))
573
+ continue;
574
+ const execution = cell["execution"];
575
+ if (!isJsonObject(execution) || execution["role"] !== "writer" || execution["lane"] !== RETIRED_EXECUTION_LANE_WORD_M40)
576
+ continue;
577
+ execution["lane"] = RENAMED_EXECUTION_LANE_M40;
578
+ renamed += 1;
579
+ }
580
+ if (renamed === 0)
581
+ return 0;
582
+ try {
583
+ await atomicWriteFileAsync(path, JSON.stringify(disk.entries), { durability: "best-effort" });
584
+ }
585
+ catch (e) {
586
+ throw new ExecutionLaneRenameWriteRefusedError(path, e);
587
+ }
588
+ return renamed;
589
+ }
512
590
  async assertStrictSidecarsReadable() {
513
591
  const loads = await Promise.allSettled(this.strictSidecars.map((map) => map.reconcile()));
514
592
  const findings = [];
@@ -943,10 +1021,8 @@ export class LocalSessionStore {
943
1021
  this.dirty = false;
944
1022
  const snapshot = Object.fromEntries(this.lastActivity);
945
1023
  try {
946
- await mkdir(join(path, ".."), { recursive: true });
947
- const tmp = `${path}.${process.pid}.${++this.writeSeq}.tmp`;
948
- await writeFile(tmp, JSON.stringify(snapshot), "utf8");
949
- await rename(tmp, path);
1024
+ ensureDir(dirname(path));
1025
+ await atomicWriteFileAsync(path, JSON.stringify(snapshot), { durability: "best-effort" });
950
1026
  }
951
1027
  catch (e) {
952
1028
  this.warnSidecar("write", e);
@@ -1106,6 +1182,9 @@ export class LocalSessionStore {
1106
1182
  });
1107
1183
  }
1108
1184
  async listSessions(opts) {
1185
+ return (await this.listSessionRows(opts)).map((a) => a.row);
1186
+ }
1187
+ async listSessionRows(opts) {
1109
1188
  await this.loadRowSidecars();
1110
1189
  const rows = [];
1111
1190
  for (const header of await this.rowHeaders())
@@ -1116,16 +1195,18 @@ export class LocalSessionStore {
1116
1195
  const owner = this.ownerCellOf(row.sessionId);
1117
1196
  if (opts.owner !== undefined && owner !== opts.owner && !(opts.includeUnowned === true && owner === null))
1118
1197
  continue;
1119
- all.push(await this.summaryOf(row, rollups));
1198
+ const meta = this.metaCellOf(row.sessionId);
1199
+ const incarnation = meta === undefined ? undefined : incarnationFromCell(row.sessionId, meta.incarnation, "absent");
1200
+ all.push({ row: await this.summaryOf(row, rollups), occupant: { owner, incarnation } });
1120
1201
  }
1121
1202
  const qlc = opts.q?.toLowerCase();
1122
- const filtered = qlc ? all.filter((r) => r.objectivePreview?.toLowerCase().includes(qlc)) : all;
1123
- filtered.sort((a, b) => a.lastActivityAt !== b.lastActivityAt
1203
+ const filtered = qlc ? all.filter(({ row: r }) => r.objectivePreview?.toLowerCase().includes(qlc)) : all;
1204
+ filtered.sort(({ row: a }, { row: b }) => a.lastActivityAt !== b.lastActivityAt
1124
1205
  ? (a.lastActivityAt < b.lastActivityAt ? 1 : -1)
1125
1206
  : (a.sessionId < b.sessionId ? 1 : -1));
1126
1207
  const c = opts.cursor;
1127
1208
  const after = c
1128
- ? filtered.filter((r) => r.lastActivityAt < c.lastActivityAt || (r.lastActivityAt === c.lastActivityAt && r.sessionId < c.sessionId))
1209
+ ? filtered.filter(({ row: r }) => r.lastActivityAt < c.lastActivityAt || (r.lastActivityAt === c.lastActivityAt && r.sessionId < c.sessionId))
1129
1210
  : filtered;
1130
1211
  return after.slice(0, opts.limit);
1131
1212
  }
@@ -1189,8 +1270,8 @@ export class LocalSessionStore {
1189
1270
  return null;
1190
1271
  }
1191
1272
  }
1192
- async fork(sourceId, owner) {
1193
- return forkByFreshId((s, o, t) => this.forkTo(s, o, t), sourceId, owner);
1273
+ async fork(sourceId, owner, opts) {
1274
+ return forkByFreshId((s, o, t) => this.forkTo(s, o, t), sourceId, owner, opts);
1194
1275
  }
1195
1276
  async forkTo(sourceId, owner, target) {
1196
1277
  await this.meta.ensureLoaded();
@@ -1215,20 +1296,24 @@ export class LocalSessionStore {
1215
1296
  const forkOwner = forkOwnerOf(owner, this.metaCellOf(sourceId)?.owner);
1216
1297
  const existing = this.metaCellOf(target.id);
1217
1298
  const targetArchived = await this.existsInRepo(target.id);
1218
- const copy = () => this.repo.fork(sourceMeta, { ...forkOptions, id: target.id });
1299
+ const placement = this.placements !== undefined ? target.placement : undefined;
1300
+ const copy = () => this.repo.fork(sourceMeta, { ...forkOptions, id: target.id, ...(placement !== undefined ? { placement } : {}) });
1219
1301
  if (existing === undefined && !targetArchived) {
1220
1302
  const created = await this.writeMeta(target.id, (before) => before !== undefined
1221
1303
  ? undefined
1222
1304
  : { incarnation: mintSessionIncarnation(), ...(forkOwner !== undefined ? { owner: forkOwner } : {}), ...(target.key !== undefined ? { forkKey: target.key } : {}), createdAt: rowBornNow(), forkedFrom: sourceId });
1223
1305
  if (!created)
1224
1306
  throw new SessionError("storage", `LocalSessionStore: fork target ${target.id} gained a session-meta cell under its own write lock — refusing to guess`);
1307
+ let forked;
1225
1308
  try {
1226
- await copy();
1309
+ forked = await copy();
1227
1310
  }
1228
1311
  catch (err) {
1229
1312
  await this.withdrawCreatedCell(target.id, err, (cause, drop) => `LocalSessionStore: fork into ${target.id} failed while copying (${cause}) and its target cell could not be withdrawn (${drop}) — the target stays in the fork-in-progress state; retry the same fork or delete the session`);
1230
1313
  throw err;
1231
1314
  }
1315
+ if (placement !== undefined)
1316
+ await this.admitForkedPlacement(target.id, forked, placement);
1232
1317
  return { outcome: "created", id: target.id };
1233
1318
  }
1234
1319
  const out = classifyForkTarget(target, { owner: existing?.owner, forkKey: existing?.forkKey }, forkOwner);
@@ -1236,6 +1321,21 @@ export class LocalSessionStore {
1236
1321
  await copy();
1237
1322
  return out;
1238
1323
  }
1324
+ async admitForkedPlacement(sessionId, forked, placement) {
1325
+ try {
1326
+ admitSessionPlacement(sessionId, (await forked.getMetadata()).placement, { placement }, placementCapabilityOf(this));
1327
+ }
1328
+ catch (refusal) {
1329
+ try {
1330
+ await this.repo.delete({ id: sessionId, createdAt: "" });
1331
+ }
1332
+ catch (left) {
1333
+ throw new SessionError("placement_refused", `${refusal instanceof Error ? refusal.message : String(refusal)} — and the copy ${sessionId} this fork created could not be removed (${left instanceof Error ? left.message : String(left)}); delete the session by id`, refusal instanceof Error ? refusal : undefined);
1334
+ }
1335
+ await this.withdrawCreatedCell(sessionId, refusal, (cause, drop) => `LocalSessionStore: a placed fork into ${sessionId} was refused (${cause}); its copy was removed but its session-meta cell could not be withdrawn (${drop}) — the cell stays on disk, inert; delete the session to clear it`);
1336
+ throw refusal;
1337
+ }
1338
+ }
1239
1339
  async exportEntries(sessionId) {
1240
1340
  if (!this.repo.exportEntries)
1241
1341
  return null;
@@ -1282,10 +1382,8 @@ export class LocalSessionStore {
1282
1382
  await this.assertNotPlacedHeld(sessionId);
1283
1383
  validateEntriesForImport(entries);
1284
1384
  const current = this.metaCellOf(sessionId);
1285
- if (current?.execution?.role === "writer")
1286
- throw new SessionWriterPresentError(sessionId, current.execution.lane);
1287
- if (await this.forkingOf(sessionId, current))
1288
- throw new SessionForkInProgressError(sessionId);
1385
+ if (landing !== "judged")
1386
+ await this.admitImportHeld(sessionId, current);
1289
1387
  if (!(await this.importMayLand(sessionId, current, owner, landing)))
1290
1388
  throw importRowRefused(sessionId, landing);
1291
1389
  const prior = await this.landImportCell(sessionId, owner);
@@ -1324,6 +1422,14 @@ export class LocalSessionStore {
1324
1422
  throw new SessionError("placement_refused", `session ${sessionId} belongs to the ${placed.kind} placement partition (a delegated agent's transcript) — a session import cannot replace its log`);
1325
1423
  }
1326
1424
  }
1425
+ async admitImportHeld(sessionId, current) {
1426
+ const verdict = await judgeImportWrite(sessionId, {
1427
+ claim: () => this.runs.getActiveTaskId(sessionId),
1428
+ cell: async () => placementCellOf(current, await this.forkingOf(sessionId, current)),
1429
+ });
1430
+ if (verdict !== "proceed")
1431
+ throw verdict.refuse;
1432
+ }
1327
1433
  async importMayLand(sessionId, current, owner, landing) {
1328
1434
  switch (landing) {
1329
1435
  case "create":
@@ -1380,8 +1486,6 @@ export class LocalSessionStore {
1380
1486
  const current = await this.metaOf(sessionId);
1381
1487
  if (!ownerCellIs(opts.expectedOwner, current === undefined ? undefined : (current.owner ?? null)))
1382
1488
  throw new StagedCommitOwnerChangedError(sessionId);
1383
- if (await this.forkingOf(sessionId, current))
1384
- throw new SessionForkInProgressError(sessionId);
1385
1489
  await this.assertNotPlacedHeld(sessionId);
1386
1490
  const dstEntries = await this.exportEntries(sessionId);
1387
1491
  const rel = classifySyncRelationshipByIds(staged.map((e) => e.id), dstEntries === null ? null : dstEntries.map((e) => e.id));
@@ -1397,8 +1501,7 @@ export class LocalSessionStore {
1397
1501
  if (diverged)
1398
1502
  throw new SyncConflictError(sessionId, contentForkRelation(diverged, rel.newEntryIds));
1399
1503
  }
1400
- if (current?.execution?.role === "writer")
1401
- throw new SessionWriterPresentError(sessionId, current.execution.lane);
1504
+ await this.admitImportHeld(sessionId, current);
1402
1505
  if (rel.relation !== "identical" || !contentEqual) {
1403
1506
  await this.importHeld(sessionId, importer, staged, "judged");
1404
1507
  }
@@ -1565,7 +1668,7 @@ export class LocalSessionStore {
1565
1668
  this.meta.syncToDisk();
1566
1669
  let anonymized = 0;
1567
1670
  if (listed.some((row) => (row.owner ?? null) !== null)) {
1568
- mkdirSync(dir, { recursive: true, mode: 0o700 });
1671
+ ensureDir(dir);
1569
1672
  fsyncPaths(dir, dirname(dir));
1570
1673
  }
1571
1674
  const keptStamped = [];
@@ -1,4 +1,6 @@
1
1
  import { type AttachmentStoreBindOutcome, type TaskAttachmentStore, type TaskAttachmentRecord } from "./task-attachment-store.js";
2
+ /** 附件店在数据根下的目录(构造器与一次性迁移 M39 的名册同读这一只)。 */
3
+ export declare function attachmentStoreDirFor(rootDir: string): string;
2
4
  export declare class LocalTaskAttachmentStore implements TaskAttachmentStore {
3
5
  private readonly dir;
4
6
  private metas;
@@ -1,16 +1,21 @@
1
1
  import { promises as fsp } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { ensureDir } from "@sema-agent/core";
3
4
  import { bindRowsInProcess, TaskAttachmentRecordSchema } from "./task-attachment-store.js";
4
5
  import { createZodColumnReader, decodeJsonColumn } from "./sql-json-column.js";
6
+ import { atomicWriteFileAsync } from "./owner-only-file-mode.js";
5
7
  const ID_RE = /^[0-9a-f-]{16,64}$/i;
6
8
  const readAttachmentMeta = createZodColumnReader(TaskAttachmentRecordSchema);
9
+ export function attachmentStoreDirFor(rootDir) {
10
+ return join(rootDir, "attachments");
11
+ }
7
12
  export class LocalTaskAttachmentStore {
8
13
  dir;
9
14
  metas;
10
15
  hydration;
11
16
  mutationTail = Promise.resolve();
12
17
  constructor(rootDir) {
13
- this.dir = join(rootDir, "attachments");
18
+ this.dir = attachmentStoreDirFor(rootDir);
14
19
  }
15
20
  hydrate() {
16
21
  this.hydration ??= (async () => {
@@ -46,14 +51,10 @@ export class LocalTaskAttachmentStore {
46
51
  put(rec) {
47
52
  return this.serialized(async () => {
48
53
  const metas = await this.hydrate();
49
- await fsp.mkdir(this.dir, { recursive: true });
54
+ ensureDir(this.dir);
50
55
  const { content, ...meta } = rec;
51
- const binTmp = join(this.dir, `${rec.id}.bin.tmp`);
52
- const metaTmp = join(this.dir, `${rec.id}.json.tmp`);
53
- await fsp.writeFile(binTmp, Buffer.from(content));
54
- await fsp.rename(binTmp, join(this.dir, `${rec.id}.bin`));
55
- await fsp.writeFile(metaTmp, JSON.stringify(meta));
56
- await fsp.rename(metaTmp, join(this.dir, `${rec.id}.json`));
56
+ await atomicWriteFileAsync(join(this.dir, `${rec.id}.bin`), Buffer.from(content), { durability: "best-effort" });
57
+ await atomicWriteFileAsync(join(this.dir, `${rec.id}.json`), JSON.stringify(meta), { durability: "best-effort" });
57
58
  metas.set(rec.id, { ...meta });
58
59
  });
59
60
  }
@@ -73,9 +74,7 @@ export class LocalTaskAttachmentStore {
73
74
  }
74
75
  }
75
76
  async persistMeta(m) {
76
- const tmp = join(this.dir, `${m.id}.json.tmp`);
77
- await fsp.writeFile(tmp, JSON.stringify(m));
78
- await fsp.rename(tmp, join(this.dir, `${m.id}.json`));
77
+ await atomicWriteFileAsync(join(this.dir, `${m.id}.json`), JSON.stringify(m), { durability: "best-effort" });
79
78
  }
80
79
  bind(owner, ids, sessionId, boundAtMs) {
81
80
  return this.serialized(async () => {
@@ -25,29 +25,37 @@
25
25
  * 文件**(server 侧),移入文件零改动;表名常量本文件自有(`PG_MEMORY_ENGINE_TABLES` 不动)。
26
26
  * 列名 `meta_key`/`meta_value`:`key` 是 MySQL 保留字,将来若补 TiDB 腿零反引号坑(K2)。
27
27
  *
28
- * ## 六态(v2 总表)
28
+ * ## 六态(v2 总表)与处置律
29
29
  *
30
30
  * | 态 | 判定 | 动作 |
31
31
  * |---|---|---|
32
32
  * | A | embedder 配置缺席 | **门不装**(连 ensure 都不调),元表不动——装配点的事,不在本文件 |
33
33
  * | B | 元表有行、identity 逐键相等 | 照常,**零写** |
34
- * | C | 元表有行、不等 | 清列 → upsert 新 identity(`reason:"changed"`) |
35
- * | D | 元表无行、库内**有**非 NULL 向量 | 同 C 清(存量库无法证明同源=保守清,`reason:"unattributed"`) |
34
+ * | C | 元表有行、不等(`changed`) | 对不上 |
35
+ * | D | 元表无行、库内**有**非 NULL 向量(`unattributed`:存量无法证明同源) | 对不上 |
36
36
  * | E | 元表无行、零向量行 | 只写 identity,不清(`memory_embedder_identity_armed`) |
37
- * | F | 元表有行但 value 解析失败 | 走清空臂(`reason:"unreadable"`)——**绝不当成匹配**(边界必 schema) |
37
+ * | F | 元表有行但 value 解析失败(`unreadable`)——**绝不当成匹配**(边界必 schema) | 对不上 |
38
38
  *
39
39
  * (F 的判据是 `model`/`dimensions` 缺失或类型不对;**多出来的未知键不算坏**,见 schema 处的注。)
40
40
  *
41
+ * **处置律(一句)**:门从不凭自己的判断清列。「对不上」(C / D / F)⇒ **拒启**,拒句点名所处的态、记下的与配置的身份、
42
+ * 出路;唯一会清列的路径是运维**显式确认**这一次重嵌 —— `opts.reembedConfirmed`(装配点读 config 的
43
+ * `memoryEmbedder.reembedConfirmed`,即 env `MEMORY_EMBEDDER_REEMBED=<model>/<dimensions>`,config 层已判过它恰好点名本次配置的
44
+ * 身份)⇒ 清列 → upsert 新 identity,`memory_embedder_identity_changed` 照旧响亮。理由:清列不可逆(行只在下次被写时才重嵌),
45
+ * 拒启可逆(改回配置 / 确认 / 撤掉 embedder 走词面档,向量原样不动)。确认口令绑定身份 ⇒ 记下这个身份之后它判 B、不再有东西可确认。
46
+ *
41
47
  * ## 三条不可动的判据
42
48
  *
43
49
  * 1. **次序:先清列、后写元表**。反序若中间崩溃 = 新 identity 已记而旧向量还在 = 正是被修的病(此后
44
50
  * 每次 boot 恒判 B,残留态永不复检);正序中间崩溃 = 下次 boot 无元表行、向量已 NULL ⇒ E 态补记,
45
51
  * 幂等安全。
46
- * 2. **CAS 循环**(v2 C1-2):元表写后**重读**,读回≠自写 ⇒ 另一副本并发写了**不同** identity(部署
47
- * 配置漂移)⇒ 响亮 `memory_embedder_identity_conflict`(两值并示)+ 重跑比对,上限
48
- * {@link CAS_MAX_ROUNDS} 轮,超限抛(拒启)。运行期旧副本混写非 CAS 可拦 ⇒ 归停机纪律(USAGE)。
52
+ * 2. **CAS 循环**(v2 C1-2):元表的写是**条件写** —— 只落在本轮判出的那一份上(判时没有行 ⇒ 只插入;判时有行 ⇒ 只在值仍是
53
+ * 读到的那段文本时改写),写后**重读**,读回≠自写 ⇒ 另一副本在判与写之间写了**不同** identity(部署配置漂移)⇒ 响亮
54
+ * `memory_embedder_identity_conflict`(两值并示)+ 重跑比对(下一轮按别人的值判:未确认 ⇒ 拒启),上限 {@link CAS_MAX_ROUNDS} 轮,
55
+ * 超限抛(拒启)。条件写让「判与写之间被别人抢先」恒被读回看见 —— 盲 upsert 会把别人刚写下的身份(连同其后写进列里的另一空间向量)
56
+ * 静默盖成自己的。运行期旧副本混写非 CAS 可拦 ⇒ 归停机纪律(USAGE)。
49
57
  * 3. **门自身失败 = 抛(拒启)**。吞掉 = 元表停留旧值 = 下次 boot 再清一次,把一次性代价变成每次 boot
50
- * 的代价;且「门在场但没跑成」静默 = fail-open。
58
+ * 的代价;且「门在场但没跑成」静默 = fail-open。「对不上而未确认」同样是抛(处置律),先于任何写。
51
59
  *
52
60
  * ## 两条已知残余(codex 交叉复审 R1-F1/R1-F3,均判为真;处置=成文,不落码面)
53
61
  *
@@ -118,8 +126,13 @@ export interface EmbedderFingerprintReport {
118
126
  /** 收敛用了几轮(1 = 一次过;>1 = 中途撞到并发不同 identity)。 */
119
127
  rounds: number;
120
128
  }
121
- /** 比对腿的部署腿注入(日志 + 时钟)。日志缺席 = 纯静默跑(测试/脚本形),装配点必传。 */
129
+ /** 比对腿的部署腿注入(日志 + 时钟 + 确认位)。日志缺席 = 纯静默跑(测试/脚本形),装配点必传。 */
122
130
  export interface ReconcileEmbedderFingerprintOptions {
131
+ /**
132
+ * 运维已确认「对不上时清掉向量列、按 `identity` 重嵌」(装配点 = config `memoryEmbedder.reembedConfirmed`)。
133
+ * 缺席 / `false` ⇒ 对不上(changed / unattributed / unreadable)一律拒启,一行不清、元表不写。
134
+ */
135
+ reembedConfirmed?: boolean;
123
136
  /** boot logger(`info` 报换模型/首装,`error` 报并发 identity 冲突)。 */
124
137
  log?: Pick<Logger, "info" | "error">;
125
138
  /** 耗时读数的时钟(默认 `Date.now`)——**整次调用**的耗时进日志(含 CAS 重试轮),
@@ -131,8 +144,18 @@ export interface ReconcileEmbedderFingerprintOptions {
131
144
  * 幂等,与其余 `ensurePg*Schema` 同姿势;新腿已注册 `PG_LEGS` + `docs/schema/baseline-pg.sql`。
132
145
  */
133
146
  export declare function ensurePgMemoryEmbedderMetaSchema(query: PgQueryFn): Promise<void>;
147
+ /** 「对不上」的三态(处置律:未确认 ⇒ 拒启)。 */
148
+ type MismatchState = Extract<EmbedderFingerprintState, "changed" | "unattributed" | "unreadable">;
149
+ /**
150
+ * 「对不上而未确认」的拒句(纯数据:一条字符串)。点名所处的态 + 三态的闭集、记下的与配置的身份、出路(确认口令逐字可抄)。
151
+ * 每一态的「记下了什么」各一句;出路对三态同一张表,只有 changed 多一条「改回记下的身份」。
152
+ */
153
+ export declare function buildEmbedderIdentityRefusal(state: MismatchState, recorded: EmbedderIdentity | {
154
+ unreadable: string;
155
+ } | null, want: EmbedderIdentity): string;
134
156
  /**
135
- * 指纹比对腿 —— boot 一次(env 族是 boot 快照,运行中不热换)。**门自身失败一律抛**(拒启)。
157
+ * 指纹比对腿 —— boot 一次(env 族是 boot 快照,运行中不热换)。**门自身失败一律抛**(拒启);「对不上」而 `opts.reembedConfirmed`
158
+ * 不为真 ⇒ 抛 {@link buildEmbedderIdentityRefusal} 的拒句(处置律,先于任何写)。
136
159
  *
137
160
  * ⚠️ 调用姿势:`ensurePgMemoryEmbedderMetaSchema` 之后、memory backend 构造之前;embedder 配置**在场**
138
161
  * 才调(A 态连 ensure 都不调)。