@sema-agent/server 7.146.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 (398) hide show
  1. package/MIGRATION.md +384 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/USAGE.md +170 -66
  5. package/deploy/facts/lanes.json +7 -0
  6. package/deploy/sema-up/README.md +2 -2
  7. package/deploy/sema-up/chart/templates/_helpers.tpl +22 -0
  8. package/deploy/sema-up/chart/templates/server-v4pro.yaml +5 -4
  9. package/deploy/sema-up/chart/templates/server.yaml +5 -4
  10. package/deploy/sema-up/chart/values.yaml +1 -1
  11. package/deploy/sema-up/cluster-up.sh +2 -1
  12. package/deploy/sema-up/lib/flagshape.sh +4 -0
  13. package/deploy/sema-up/lib/lanes.json +2 -5
  14. package/deploy/sema-up/sema-up.sh +12 -9
  15. package/deploy/sema-up/stack/compose.yaml +5 -4
  16. package/deploy/sema-up/stack/sema-stack-cluster.yaml +4 -3
  17. package/dist/approval-card.d.ts +4 -4
  18. package/dist/approval.d.ts +3 -3
  19. package/dist/audit.js +2 -2
  20. package/dist/bench/s1/live-deps.js +3 -1
  21. package/dist/boot/crash-last.js +2 -1
  22. package/dist/boot/device-lane.js +5 -5
  23. package/dist/boot/engine-lease.d.ts +12 -11
  24. package/dist/boot/execution-env.d.ts +2 -1
  25. package/dist/boot/execution-env.js +45 -33
  26. package/dist/boot/execution-lane.d.ts +37 -9
  27. package/dist/boot/execution-lane.js +74 -20
  28. package/dist/boot/exit-boundary.d.ts +1 -1
  29. package/dist/boot/exit-last.js +2 -1
  30. package/dist/boot/governance-seams.d.ts +2 -2
  31. package/dist/boot/leader.js +1 -1
  32. package/dist/boot/memory-boundary.d.ts +11 -11
  33. package/dist/boot/memory-boundary.js +3 -3
  34. package/dist/boot/memory-consolidation.d.ts +13 -24
  35. package/dist/boot/memory-consolidation.js +0 -13
  36. package/dist/boot/org-memory.js +3 -2
  37. package/dist/boot/parked-revive-gate.d.ts +1 -1
  38. package/dist/boot/parked-revive-gate.js +1 -1
  39. package/dist/boot/reapers.js +1 -1
  40. package/dist/boot/resolve-spec.js +91 -111
  41. package/dist/boot/retention-lane.d.ts +4 -42
  42. package/dist/boot/session-faces.d.ts +1 -0
  43. package/dist/boot/session-faces.js +8 -2
  44. package/dist/boot/stage-01-config.d.ts +1 -1
  45. package/dist/boot/stage-01-config.js +6 -2
  46. package/dist/boot/stage-02-web-admin-pull.d.ts +1 -1
  47. package/dist/boot/stage-02-web-admin-pull.js +10 -8
  48. package/dist/boot/stage-03-store-backend.d.ts +1 -1
  49. package/dist/boot/stage-04-stores.d.ts +1 -1
  50. package/dist/boot/stage-05-execution-env.d.ts +2 -2
  51. package/dist/boot/stage-05-execution-env.js +3 -3
  52. package/dist/boot/stage-06-runners.d.ts +3 -3
  53. package/dist/boot/stage-06-runners.js +1 -3
  54. package/dist/boot/stage-07-capability-layer.d.ts +3 -3
  55. package/dist/boot/stage-07-capability-layer.js +4 -9
  56. package/dist/boot/stage-08-reapers.d.ts +3 -3
  57. package/dist/boot/stage-09-leader.d.ts +4 -3
  58. package/dist/boot/stage-10-http-server.d.ts +4 -3
  59. package/dist/boot/stage-10-http-server.js +2 -1
  60. package/dist/boot/stores.d.ts +9 -0
  61. package/dist/boot/stores.js +18 -7
  62. package/dist/boot/web-admin.js +3 -3
  63. package/dist/capabilities/center-plugins.d.ts +2 -0
  64. package/dist/capabilities/center-plugins.js +6 -2
  65. package/dist/capabilities/composite-members.d.ts +1 -0
  66. package/dist/capabilities/composite-members.js +1 -0
  67. package/dist/capabilities/execution-lane.d.ts +7 -7
  68. package/dist/capabilities/execution-lane.js +2 -2
  69. package/dist/capabilities/hands-lane.d.ts +1 -1
  70. package/dist/capabilities/scenarios.d.ts +32 -18
  71. package/dist/capabilities/scenarios.js +13 -9
  72. package/dist/capabilities/settings-contract.d.ts +29 -0
  73. package/dist/capabilities/settings-contract.js +14 -0
  74. package/dist/capabilities/skills.d.ts +5 -5
  75. package/dist/capability-facts.d.ts +38 -0
  76. package/dist/capability-facts.js +34 -1
  77. package/dist/center-credential-renewer.js +3 -2
  78. package/dist/config-catalog.js +6 -5
  79. package/dist/config-invariants.d.ts +18 -3
  80. package/dist/config-invariants.js +36 -19
  81. package/dist/config-lkg.d.ts +1 -1
  82. package/dist/config-lkg.js +5 -6
  83. package/dist/config-provider.js +2 -0
  84. package/dist/config-types.d.ts +190 -186
  85. package/dist/config.d.ts +68 -5
  86. package/dist/config.js +80 -54
  87. package/dist/degenerate-instrument.js +1 -1
  88. package/dist/deploy-facts.js +3 -2
  89. package/dist/deployment-shape.d.ts +21 -12
  90. package/dist/deployment-shape.js +24 -6
  91. package/dist/env-facts.d.ts +7 -5
  92. package/dist/env-facts.js +10 -6
  93. package/dist/execution-config-root.d.ts +5 -5
  94. package/dist/execution-config-root.js +5 -5
  95. package/dist/execution-env-purpose.d.ts +14 -0
  96. package/dist/execution-env-purpose.js +29 -0
  97. package/dist/execution-lane-caps.d.ts +49 -86
  98. package/dist/execution-lane-caps.js +52 -62
  99. package/dist/execution-placement.d.ts +18 -2
  100. package/dist/execution-placement.js +19 -0
  101. package/dist/file-history-disclosure.d.ts +2 -2
  102. package/dist/fleet/drain-entry.d.ts +17 -10
  103. package/dist/fleet/drain-entry.js +1 -1
  104. package/dist/fleet/serving-lease.js +3 -4
  105. package/dist/history-anchor.d.ts +22 -0
  106. package/dist/history-anchor.js +14 -0
  107. package/dist/hooks/command-spawn.d.ts +1 -4
  108. package/dist/hooks/command-spawn.js +0 -11
  109. package/dist/hooks/hook-runner.d.ts +52 -8
  110. package/dist/hooks/hook-runner.js +160 -36
  111. package/dist/http/approval-sweeps.d.ts +2 -5
  112. package/dist/http/approval-sweeps.js +3 -2
  113. package/dist/http/checkpoint-ctx.d.ts +17 -0
  114. package/dist/http/checkpoint-ctx.js +6 -0
  115. package/dist/http/claim-latency.d.ts +10 -0
  116. package/dist/http/claim-latency.js +12 -0
  117. package/dist/http/dispatch.js +1 -1
  118. package/dist/http/durable-run-leg.js +2 -1
  119. package/dist/http/execution-context.d.ts +3 -1
  120. package/dist/http/execution-context.js +4 -0
  121. package/dist/http/memory-compliance-failure-reply.d.ts +1 -1
  122. package/dist/http/memory-compliance-failure-reply.js +3 -0
  123. package/dist/http/memory-store-refusal-reply.d.ts +3 -3
  124. package/dist/http/memory-store-refusal-reply.js +3 -0
  125. package/dist/http/owner-access.d.ts +11 -0
  126. package/dist/http/owner-access.js +7 -4
  127. package/dist/http/principal-gate.d.ts +3 -14
  128. package/dist/http/principal-gate.js +0 -13
  129. package/dist/http/request-guards.d.ts +1 -1
  130. package/dist/http/resume-legs.d.ts +7 -10
  131. package/dist/http/resume-legs.js +79 -50
  132. package/dist/http/rewind-files-reply.d.ts +34 -0
  133. package/dist/http/rewind-files-reply.js +36 -0
  134. package/dist/http/route-ctx.d.ts +32 -16
  135. package/dist/http/route-table.js +2 -0
  136. package/dist/http/routes/approvals-assistant.js +5 -25
  137. package/dist/http/routes/capabilities.js +8 -2
  138. package/dist/http/routes/devices.js +1 -1
  139. package/dist/http/routes/memory-origin.d.ts +1 -1
  140. package/dist/http/routes/notify-wake.js +2 -1
  141. package/dist/http/routes/projects.d.ts +70 -0
  142. package/dist/http/routes/projects.js +86 -0
  143. package/dist/http/routes/rules.js +30 -2
  144. package/dist/http/routes/runs.js +8 -8
  145. package/dist/http/routes/session-sync.js +27 -10
  146. package/dist/http/routes/sessions.d.ts +7 -1
  147. package/dist/http/routes/sessions.js +104 -2
  148. package/dist/http/routes/tasks.js +9 -3
  149. package/dist/http/server.d.ts +24 -10
  150. package/dist/http/server.js +17 -6
  151. package/dist/http/stored-body-replay.d.ts +5 -3
  152. package/dist/http/stored-body-replay.js +10 -1
  153. package/dist/http/wire-types.d.ts +19 -10
  154. package/dist/index.d.ts +2 -2
  155. package/dist/index.js +1 -1
  156. package/dist/instruction-source-notice.d.ts +1 -1
  157. package/dist/memory-embedder-reembed.d.ts +38 -0
  158. package/dist/memory-embedder-reembed.js +20 -0
  159. package/dist/memory-incident-sink.d.ts +0 -28
  160. package/dist/memory-incident-sink.js +5 -0
  161. package/dist/memory-scope.d.ts +2 -2
  162. package/dist/memory-scope.js +1 -1
  163. package/dist/memory-store-refusal.d.ts +17 -4
  164. package/dist/memory-store-refusal.js +1 -1
  165. package/dist/memory-sync-client.d.ts +2 -0
  166. package/dist/memory-sync-client.js +13 -11
  167. package/dist/memory-sync.js +1 -1
  168. package/dist/model-compat.d.ts +35 -21
  169. package/dist/model-compat.js +49 -21
  170. package/dist/model-entry-refusal.d.ts +11 -1
  171. package/dist/model-entry-refusal.js +7 -0
  172. package/dist/namespaced-rule-name.d.ts +18 -1
  173. package/dist/namespaced-rule-name.js +12 -0
  174. package/dist/observability/fail-open.d.ts +17 -9
  175. package/dist/observability/fail-open.js +17 -9
  176. package/dist/observability/metrics.d.ts +2 -0
  177. package/dist/observability/metrics.js +2 -0
  178. package/dist/observability/secret-env-scrub.d.ts +30 -4
  179. package/dist/observability/secret-env-scrub.js +15 -3
  180. package/dist/orchestration/workflow-agent-session-index.d.ts +7 -12
  181. package/dist/orchestration/workflow-agent-session-index.js +1 -6
  182. package/dist/orchestration/workflow-completion-inbox.d.ts +26 -6
  183. package/dist/orchestration/workflow-completion-inbox.js +63 -45
  184. package/dist/org-memory-admission.d.ts +5 -2
  185. package/dist/org-memory-admission.js +25 -10
  186. package/dist/parked-decide.d.ts +33 -26
  187. package/dist/parked-decide.js +36 -44
  188. package/dist/plugins/approval-ask-store-file.d.ts +10 -2
  189. package/dist/plugins/approval-ask-store-file.js +37 -4
  190. package/dist/plugins/approval-ask-store-memory.d.ts +5 -3
  191. package/dist/plugins/approval-ask-store-memory.js +11 -2
  192. package/dist/plugins/approval-ask-store-sql.d.ts +3 -0
  193. package/dist/plugins/approval-ask-store-sql.js +3 -1
  194. package/dist/plugins/blob-backend.d.ts +38 -195
  195. package/dist/plugins/blob-backend.js +33 -229
  196. package/dist/plugins/caching-session-store.d.ts +9 -4
  197. package/dist/plugins/checkpoint-index-columns.d.ts +1 -1
  198. package/dist/plugins/checkpoint-index-columns.js +3 -2
  199. package/dist/plugins/checkpoint-store-face.d.ts +1 -1
  200. package/dist/plugins/device-store-sql.d.ts +2 -2
  201. package/dist/plugins/device-store-sql.js +5 -10
  202. package/dist/plugins/execution-lane-rename-m40.d.ts +20 -0
  203. package/dist/plugins/execution-lane-rename-m40.js +10 -0
  204. package/dist/plugins/execution-placement-sql.d.ts +63 -88
  205. package/dist/plugins/execution-placement-sql.js +94 -54
  206. package/dist/plugins/file-run-store.d.ts +26 -12
  207. package/dist/plugins/file-run-store.js +63 -63
  208. package/dist/plugins/imported-layer-root-retirement.d.ts +17 -8
  209. package/dist/plugins/imported-layer-root-retirement.js +4 -8
  210. package/dist/plugins/inbox-payload-column.d.ts +14 -0
  211. package/dist/plugins/inbox-payload-column.js +13 -0
  212. package/dist/plugins/local-checkpoint-store.d.ts +5 -0
  213. package/dist/plugins/local-checkpoint-store.js +11 -7
  214. package/dist/plugins/local-data-dir-modes-m39.d.ts +48 -0
  215. package/dist/plugins/local-data-dir-modes-m39.js +182 -0
  216. package/dist/plugins/local-engine-high-water.d.ts +11 -0
  217. package/dist/plugins/local-engine-high-water.js +59 -0
  218. package/dist/plugins/local-session-store.d.ts +91 -25
  219. package/dist/plugins/local-session-store.js +124 -45
  220. package/dist/plugins/local-task-attachment-store.d.ts +2 -0
  221. package/dist/plugins/local-task-attachment-store.js +10 -11
  222. package/dist/plugins/memory-embedder-fingerprint.d.ts +33 -10
  223. package/dist/plugins/memory-embedder-fingerprint.js +52 -12
  224. package/dist/plugins/memory-embedder.d.ts +1 -1
  225. package/dist/plugins/memory-embedder.js +2 -2
  226. package/dist/plugins/memory-engine-pg.d.ts +4 -3
  227. package/dist/plugins/memory-engine-pg.js +4 -4
  228. package/dist/plugins/memory-engine-sql-apply.d.ts +13 -4
  229. package/dist/plugins/memory-engine-sql-apply.js +1 -1
  230. package/dist/plugins/memory-engine-tidb.d.ts +8 -5
  231. package/dist/plugins/memory-engine-tidb.js +7 -8
  232. package/dist/plugins/one-time-migrations.d.ts +145 -35
  233. package/dist/plugins/one-time-migrations.js +272 -120
  234. package/dist/plugins/owner-only-file-mode.d.ts +29 -0
  235. package/dist/plugins/owner-only-file-mode.js +141 -0
  236. package/dist/plugins/permission-rule-store-file.d.ts +8 -8
  237. package/dist/plugins/permission-rule-store-file.js +14 -2
  238. package/dist/plugins/pg-pool.d.ts +2 -1
  239. package/dist/plugins/pg-pool.js +11 -4
  240. package/dist/plugins/release-version.d.ts +20 -0
  241. package/dist/plugins/release-version.js +28 -0
  242. package/dist/plugins/remote-env-adb.d.ts +20 -4
  243. package/dist/plugins/remote-env-adb.js +39 -11
  244. package/dist/plugins/remote-env-e2b.d.ts +12 -3
  245. package/dist/plugins/remote-env-e2b.js +6 -4
  246. package/dist/plugins/remote-env-host.d.ts +9 -1
  247. package/dist/plugins/remote-env-host.js +6 -5
  248. package/dist/plugins/remote-env-k8s.d.ts +5 -2
  249. package/dist/plugins/remote-env-k8s.js +15 -4
  250. package/dist/plugins/remote-env-local-docker.d.ts +4 -1
  251. package/dist/plugins/remote-env-local-docker.js +3 -3
  252. package/dist/plugins/remote-env-ssh.d.ts +8 -2
  253. package/dist/plugins/remote-env-ssh.js +26 -24
  254. package/dist/plugins/remote-shell.d.ts +59 -30
  255. package/dist/plugins/remote-shell.js +175 -62
  256. package/dist/plugins/retention-declaration.d.ts +37 -0
  257. package/dist/plugins/retention-declaration.js +9 -0
  258. package/dist/plugins/retention-deployment.d.ts +126 -0
  259. package/dist/plugins/retention-deployment.js +88 -0
  260. package/dist/plugins/retention-lane-store-sql.d.ts +74 -4
  261. package/dist/plugins/retention-lane-store-sql.js +103 -1
  262. package/dist/plugins/retention-sql.d.ts +29 -0
  263. package/dist/plugins/retention-sql.js +8 -0
  264. package/dist/plugins/schema-consistency.d.ts +0 -6
  265. package/dist/plugins/schema-consistency.js +1 -2
  266. package/dist/plugins/schema-ensure-legs.d.ts +1 -1
  267. package/dist/plugins/schema-ensure-legs.js +11 -1
  268. package/dist/plugins/session-ext-table.d.ts +74 -0
  269. package/dist/plugins/session-ext-table.js +121 -0
  270. package/dist/plugins/session-fork.d.ts +1 -1
  271. package/dist/plugins/session-row-sql.d.ts +8 -7
  272. package/dist/plugins/session-row-sql.js +15 -7
  273. package/dist/plugins/session-store-sql.d.ts +131 -0
  274. package/dist/plugins/session-store-sql.js +298 -0
  275. package/dist/plugins/session-workspace-cell.d.ts +2 -2
  276. package/dist/plugins/session-workspace-cell.js +2 -2
  277. package/dist/plugins/shared-memory-store-sql.d.ts +10 -0
  278. package/dist/plugins/shared-memory-store-sql.js +13 -13
  279. package/dist/plugins/snapshot-bucket-presence.js +1 -1
  280. package/dist/plugins/sql-driver.d.ts +23 -7
  281. package/dist/plugins/sql-driver.js +41 -8
  282. package/dist/plugins/sql-errors.d.ts +5 -2
  283. package/dist/plugins/sql-errors.js +4 -0
  284. package/dist/plugins/store-backend.d.ts +35 -8
  285. package/dist/plugins/store-backend.js +184 -62
  286. package/dist/plugins/store-contracts.d.ts +9 -2
  287. package/dist/plugins/store-contracts.js +1 -0
  288. package/dist/plugins/task-attachment-store.d.ts +6 -8
  289. package/dist/plugins/task-attachment-store.js +15 -10
  290. package/dist/plugins/task-list-store-sql.d.ts +1 -1
  291. package/dist/plugins/text-column-capacity.d.ts +21 -0
  292. package/dist/plugins/text-column-capacity.js +5 -0
  293. package/dist/plugins/tidb-pool.d.ts +3 -2
  294. package/dist/plugins/tidb-pool.js +19 -31
  295. package/dist/plugins/user-input-ledger-sql.d.ts +1 -1
  296. package/dist/read-face-posture.d.ts +6 -6
  297. package/dist/read-face-posture.js +2 -2
  298. package/dist/request-value-closure.d.ts +5 -5
  299. package/dist/request-value-closure.js +1 -1
  300. package/dist/rules-consent.d.ts +41 -13
  301. package/dist/rules-consent.js +101 -53
  302. package/dist/run-local.js +17 -13
  303. package/dist/runs.d.ts +48 -30
  304. package/dist/runs.js +26 -16
  305. package/dist/runtime-caps-resolver.d.ts +15 -8
  306. package/dist/runtime-caps-resolver.js +14 -10
  307. package/dist/sealed-key-layout.d.ts +2 -3
  308. package/dist/sealed-key-layout.js +0 -1
  309. package/dist/sealed-key.js +7 -5
  310. package/dist/security.d.ts +5 -3
  311. package/dist/sema-config-dir.js +2 -2
  312. package/dist/server-secret-env.d.ts +2 -0
  313. package/dist/service-version.d.ts +2 -1
  314. package/dist/service-version.js +2 -2
  315. package/dist/session-error-wire.d.ts +1 -1
  316. package/dist/session-incarnation.d.ts +8 -5
  317. package/dist/session-resident-background.d.ts +85 -32
  318. package/dist/session-resident-background.js +75 -7
  319. package/dist/session-row.d.ts +1 -1
  320. package/dist/session-sync-kernel.d.ts +1 -1
  321. package/dist/session-workspace.d.ts +11 -2
  322. package/dist/session-workspace.js +5 -0
  323. package/dist/sighup-idle.d.ts +1 -1
  324. package/dist/store-posture.d.ts +2 -1
  325. package/dist/stored-request-hooks-m20.d.ts +3 -2
  326. package/dist/stored-request-hooks-m20.js +19 -14
  327. package/dist/stores-sql/blob-index-sql.d.ts +148 -0
  328. package/dist/stores-sql/blob-index-sql.js +154 -0
  329. package/dist/stores-sql/checkpoint-store-sql.d.ts +1 -1
  330. package/dist/stores-sql/checkpoint-store-sql.js +11 -27
  331. package/dist/{plugins → stores-sql}/file-history-store-sql.d.ts +23 -11
  332. package/dist/{plugins → stores-sql}/file-history-store-sql.js +23 -18
  333. package/dist/{plugins → stores-sql}/pg-session-storage.d.ts +23 -76
  334. package/dist/{plugins → stores-sql}/pg-session-storage.js +80 -209
  335. package/dist/{plugins → stores-sql}/retention-store-sql.d.ts +123 -217
  336. package/dist/{plugins → stores-sql}/retention-store-sql.js +66 -190
  337. package/dist/{plugins → stores-sql}/session-event-payload.d.ts +1 -1
  338. package/dist/{plugins → stores-sql}/session-event-payload.js +1 -1
  339. package/dist/stores-sql/session-policy-store-sql.d.ts +1 -1
  340. package/dist/stores-sql/session-write-hooks.d.ts +59 -0
  341. package/dist/stores-sql/session-write-hooks.js +2 -0
  342. package/dist/{plugins → stores-sql}/tidb-session-storage.d.ts +10 -11
  343. package/dist/{plugins → stores-sql}/tidb-session-storage.js +10 -21
  344. package/dist/{plugins → stores-sql}/tidb-session-store.d.ts +32 -122
  345. package/dist/{plugins → stores-sql}/tidb-session-store.js +71 -171
  346. package/dist/stores-sql/tool-result-store-sql.d.ts +1 -1
  347. package/dist/stores-sql/tool-result-store-sql.js +1 -1
  348. package/dist/stores-sql/windowed-session-storage.d.ts +56 -0
  349. package/dist/stores-sql/windowed-session-storage.js +61 -0
  350. package/dist/task-a2a.d.ts +7 -1
  351. package/dist/task-a2a.js +15 -14
  352. package/dist/task-cwd.d.ts +11 -3
  353. package/dist/task-cwd.js +17 -1
  354. package/dist/task-mcp.d.ts +10 -2
  355. package/dist/task-mcp.js +13 -16
  356. package/dist/task-settings.d.ts +9 -4
  357. package/dist/task-settings.js +17 -6
  358. package/dist/tool-approval.d.ts +21 -8
  359. package/dist/tool-approval.js +10 -6
  360. package/dist/trace/core-keyset-guard.d.ts +9 -3
  361. package/dist/trace/engine-notice-wire.d.ts +1 -1
  362. package/dist/trace/engine-notice-wire.js +2 -0
  363. package/dist/trace/exit-seat.d.ts +23 -1
  364. package/dist/trace/exit-seat.js +3 -0
  365. package/dist/trace/project.d.ts +33 -16
  366. package/dist/trace/project.js +12 -9
  367. package/dist/trace/redact.d.ts +1 -1
  368. package/dist/trace/redact.js +61 -73
  369. package/dist/trace/self-minted-wire.d.ts +263 -10
  370. package/dist/trace/self-minted-wire.js +90 -2
  371. package/dist/trace/sema-provenance.d.ts +45 -41
  372. package/dist/trace/sema-provenance.js +81 -10
  373. package/dist/trace/task-notification-facets.d.ts +70 -2
  374. package/dist/trace/task-notification-facets.js +71 -1
  375. package/dist/trace/wire-projection-faces.d.ts +38 -2
  376. package/dist/trace/wire-projection-faces.js +26 -1
  377. package/dist/unread-request-members.d.ts +66 -0
  378. package/dist/unread-request-members.js +41 -0
  379. package/dist/user-input-ledger.d.ts +2 -2
  380. package/dist/web-admin-client/apply-effective.js +22 -26
  381. package/dist/web-admin-client/candidate-gate.d.ts +35 -3
  382. package/dist/web-admin-client/candidate-gate.js +53 -5
  383. package/dist/web-admin-client/center-request.d.ts +4 -1
  384. package/dist/web-admin-client/center-request.js +2 -1
  385. package/dist/web-admin-client/effective-keys.js +0 -1
  386. package/dist/web-admin-client/facade.d.ts +1 -1
  387. package/dist/web-admin-client/http-client.d.ts +1 -0
  388. package/dist/web-admin-client/http-client.js +17 -9
  389. package/dist/web-admin-client/restart-signal.js +5 -2
  390. package/dist/web-admin-client/skills-mcp.d.ts +20 -6
  391. package/dist/web-admin-client/skills-mcp.js +26 -21
  392. package/dist/web-admin-client/types.d.ts +34 -49
  393. package/docs/DEVICE-EXECUTOR-PROTOCOL.md +2 -2
  394. package/package.json +13 -12
  395. package/scripts/drain-check-local.mjs +2 -28
  396. package/scripts/drain-check.mysql.sql +2 -18
  397. package/scripts/drain-check.pg.sql +2 -18
  398. package/wire-changes/server@7.147.0.json +813 -0
@@ -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 都不调)。
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { PG_MEMORY_ENGINE_TABLES } from "./memory-engine-pg.js";
3
3
  import { createZodColumnReader, decodeJsonColumn, jsonColumnText, SqlJsonColumnError } from "./sql-json-column.js";
4
4
  import { echoCallerText } from "../caller-text-echo.js";
5
+ import { MEMORY_EMBEDDER_REEMBED_ENV, formatEmbedderIdentityToken, formatReembedAssignment } from "../memory-embedder-reembed.js";
5
6
  export const PG_MEMORY_ENGINE_META_TABLE = "agent_memory_engine_meta";
6
7
  export const EMBEDDER_IDENTITY_META_KEY = "embedder_identity";
7
8
  export const CAS_MAX_ROUNDS = 3;
@@ -18,12 +19,12 @@ export async function ensurePgMemoryEmbedderMetaSchema(query) {
18
19
  const readEmbedderIdentityColumn = createZodColumnReader(EmbedderIdentitySchema);
19
20
  function parseStoredText(text) {
20
21
  try {
21
- return { kind: "ok", value: decodeJsonColumn(text, readEmbedderIdentityColumn, `${PG_MEMORY_ENGINE_META_TABLE}.meta_value for key ${EMBEDDER_IDENTITY_META_KEY}`) };
22
+ return { kind: "ok", value: decodeJsonColumn(text, readEmbedderIdentityColumn, `${PG_MEMORY_ENGINE_META_TABLE}.meta_value for key ${EMBEDDER_IDENTITY_META_KEY}`), text };
22
23
  }
23
24
  catch (err) {
24
25
  if (!(err instanceof SqlJsonColumnError))
25
26
  throw err;
26
- return { kind: "unreadable", raw: `${echoCallerText(text, { maxChars: 160 })} [${err.problem}: ${echoCallerText(err.message, { maxChars: 120 })}]` };
27
+ return { kind: "unreadable", raw: `${echoCallerText(text, { maxChars: 160 })} [${err.problem}: ${echoCallerText(err.message, { maxChars: 120 })}]`, text };
27
28
  }
28
29
  }
29
30
  async function readStored(query) {
@@ -32,8 +33,9 @@ async function readStored(query) {
32
33
  if (row === undefined)
33
34
  return { kind: "absent" };
34
35
  const text = row.meta_value;
35
- if (typeof text !== "string")
36
- return { kind: "unreadable", raw: `[meta_value::text did not return text: ${typeof text}]` };
36
+ if (typeof text !== "string") {
37
+ throw new Error(`reconcileEmbedderFingerprint: ${PG_MEMORY_ENGINE_META_TABLE}.meta_value::text did not return text (${typeof text}) — the read leg is broken; refusing to start`);
38
+ }
37
39
  return parseStoredText(text);
38
40
  }
39
41
  async function hasUnattributedVectors(query) {
@@ -45,16 +47,51 @@ async function clearEmbeddings(query) {
45
47
  SELECT count(*)::int AS n FROM c`);
46
48
  return Number(r.rows[0]?.n ?? 0);
47
49
  }
48
- async function writeIdentity(query, identity) {
49
- await query(`INSERT INTO ${PG_MEMORY_ENGINE_META_TABLE} (meta_key, meta_value) VALUES ($1, $2::jsonb)
50
- ON CONFLICT (meta_key) DO UPDATE SET meta_value = EXCLUDED.meta_value`, [EMBEDDER_IDENTITY_META_KEY, JSON.stringify(identity)]);
50
+ async function writeIdentity(query, identity, judged) {
51
+ if (judged.kind === "absent") {
52
+ await query(`INSERT INTO ${PG_MEMORY_ENGINE_META_TABLE} (meta_key, meta_value) VALUES ($1, $2::jsonb)
53
+ ON CONFLICT (meta_key) DO NOTHING`, [EMBEDDER_IDENTITY_META_KEY, JSON.stringify(identity)]);
54
+ return;
55
+ }
56
+ await query(`UPDATE ${PG_MEMORY_ENGINE_META_TABLE} SET meta_value = $2::jsonb WHERE meta_key = $1 AND meta_value::text = $3`, [
57
+ EMBEDDER_IDENTITY_META_KEY,
58
+ JSON.stringify(identity),
59
+ judged.text,
60
+ ]);
51
61
  }
52
62
  function sameIdentity(a, b) {
53
63
  return a.model === b.model && a.dimensions === b.dimensions;
54
64
  }
55
65
  const SCALE_ZERO_NOTE = "change the embedder identity with the fleet stopped (scale to 0, then start): during a ROLLING window the old replicas keep writing vectors in the OLD space after this gate cleared the column";
66
+ export function buildEmbedderIdentityRefusal(state, recorded, want) {
67
+ const configured = formatEmbedderIdentityToken(want);
68
+ let what;
69
+ switch (state) {
70
+ case "changed":
71
+ what = `${PG_MEMORY_ENGINE_META_TABLE} records the embedder identity ${recorded !== null && "model" in recorded ? formatEmbedderIdentityToken(recorded) : "(none)"} but the configured embedder is ${configured}`;
72
+ break;
73
+ case "unattributed":
74
+ what = `${PG_MEMORY_ENGINE_META_TABLE} records no embedder identity while ${PG_MEMORY_ENGINE_TABLES.entry}.embedding holds vectors — their origin cannot be proven to be the configured embedder ${configured}`;
75
+ break;
76
+ case "unreadable":
77
+ what = `the embedder identity recorded in ${PG_MEMORY_ENGINE_META_TABLE} cannot be read (${recorded !== null && "unreadable" in recorded ? recorded.unreadable : "unreadable"}), so the vectors cannot be proven to come from the configured embedder ${configured}`;
78
+ break;
79
+ default: {
80
+ const unknown = state;
81
+ throw new Error(`unknown embedder mismatch state ${JSON.stringify(unknown)}`);
82
+ }
83
+ }
84
+ return (`memory embedder identity mismatch (state: ${state}) — refusing to start: ${what}. ` +
85
+ `The gate refuses on each of three states (changed: the recorded identity differs; unattributed: no recorded identity while vectors exist; unreadable: the recorded identity cannot be read) ` +
86
+ `and never clears the vector column on its own — clearing is irreversible (rows re-embed only when next written), refusing is not. Ways out: ` +
87
+ (state === "changed" ? "configure the recorded identity again (MEMORY_EMBEDDER_MODEL / MEMORY_EMBEDDER_DIM); or " : "") +
88
+ `confirm the re-embed — set ${formatReembedAssignment(want)} and restart with the fleet stopped (scale to 0): the column is cleared once and ${configured} recorded, after which the confirmation is inert; ` +
89
+ "or unset MEMORY_EMBEDDER_* to start on the lexical floor with the stored vectors left untouched.");
90
+ }
91
+ const CONFIRMED_NOTE = `re-embed confirmed by ${MEMORY_EMBEDDER_REEMBED_ENV} (inert from now on: this identity is recorded, so the next boot matches)`;
56
92
  export async function reconcileEmbedderFingerprint(query, identity, opts = {}) {
57
93
  const { log } = opts;
94
+ const confirmed = opts.reembedConfirmed === true;
58
95
  const now = opts.now ?? Date.now;
59
96
  const want = EmbedderIdentitySchema.parse(identity);
60
97
  const firstStartedAt = now();
@@ -71,7 +108,7 @@ export async function reconcileEmbedderFingerprint(query, identity, opts = {}) {
71
108
  reason: firstClear?.reason ?? firstChange?.reason ?? terminalState,
72
109
  rounds,
73
110
  elapsedMs,
74
- note: `${SCALE_ZERO_NOTE}; cleared vectors are NOT backfilled — rows re-embed only as they are next written, and until then each cleared row is reachable ONLY by a query sharing a literal term with it (the lexical floor drops a row with zero term overlap, whereas a row that still has a vector is scored by cosine as long as the query embeds too) — rewrite the corpus to restore vector reach immediately`,
111
+ note: `${CONFIRMED_NOTE}; ${SCALE_ZERO_NOTE}; cleared vectors are NOT backfilled — rows re-embed only as they are next written, and until then each cleared row is reachable ONLY by a query sharing a literal term with it (the lexical floor drops a row with zero term overlap, whereas a row that still has a vector is scored by cosine as long as the query embeds too) — rewrite the corpus to restore vector reach immediately`,
75
112
  });
76
113
  return;
77
114
  }
@@ -83,7 +120,7 @@ export async function reconcileEmbedderFingerprint(query, identity, opts = {}) {
83
120
  reason: firstChange.reason,
84
121
  rounds,
85
122
  elapsedMs,
86
- note: `${SCALE_ZERO_NOTE}; no vectors existed to clear on this boot — the identity itself changed, which is the event`,
123
+ note: `${CONFIRMED_NOTE}; ${SCALE_ZERO_NOTE}; no vectors existed to clear on this boot — the identity itself changed, which is the event`,
87
124
  });
88
125
  return;
89
126
  }
@@ -114,15 +151,18 @@ export async function reconcileEmbedderFingerprint(query, identity, opts = {}) {
114
151
  else {
115
152
  state = (await hasUnattributedVectors(query)) ? "unattributed" : "armed";
116
153
  }
154
+ const recorded = previous ?? (stored.kind === "unreadable" ? { unreadable: stored.raw } : null);
155
+ if (state !== "armed" && !confirmed)
156
+ throw new Error(buildEmbedderIdentityRefusal(state, recorded, want));
117
157
  if (state !== "armed" && firstChange === undefined) {
118
- firstChange = { reason: state, previous: previous ?? (stored.kind === "unreadable" ? { unreadable: stored.raw } : null) };
158
+ firstChange = { reason: state, previous: recorded };
119
159
  }
120
160
  const cleared = state === "armed" ? 0 : await clearEmbeddings(query);
121
161
  if (cleared > 0 && firstClear === undefined) {
122
- firstClear = { reason: state, previous: previous ?? (stored.kind === "unreadable" ? { unreadable: stored.raw } : null) };
162
+ firstClear = { reason: state, previous: recorded };
123
163
  }
124
164
  clearedTotal += cleared;
125
- await writeIdentity(query, want);
165
+ await writeIdentity(query, want, stored);
126
166
  const after = await readStored(query);
127
167
  if (after.kind === "ok" && sameIdentity(after.value, want)) {
128
168
  emitOutcome(state, round);
@@ -1,7 +1,7 @@
1
1
  import type { MemoryEmbedderConfig } from "../config-types.js";
2
2
  import type { PgEmbedder } from "./pg-query.js";
3
3
  /** 工厂入参 = 配置坐标(单一属主 `config-types.ts`)+ 部署腿(观测/注入)。 */
4
- export interface OpenAiCompatEmbedderOptions extends MemoryEmbedderConfig {
4
+ export interface OpenAiCompatEmbedderOptions extends Omit<MemoryEmbedderConfig, "reembedConfirmed"> {
5
5
  /** 注入 fetch(测试/代理场景);缺省全局 `fetch`。 */
6
6
  fetchImpl?: typeof fetch;
7
7
  /**
@@ -94,9 +94,9 @@ export function createOpenAiCompatEmbedder(opts) {
94
94
  };
95
95
  }
96
96
  export function memoryEmbedderFor(config, deps = {}) {
97
- const cfg = config.memoryEmbedder;
98
- if (cfg === undefined)
97
+ if (config.memoryEmbedder === undefined)
99
98
  return undefined;
99
+ const { reembedConfirmed: _confirmation, ...cfg } = config.memoryEmbedder;
100
100
  return createOpenAiCompatEmbedder({
101
101
  ...cfg,
102
102
  ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),
@@ -86,9 +86,10 @@ export declare class PgMemoryEngineBackend implements MemoryBackend {
86
86
  /** 写不落之后的现读:这个 id 的行此刻的 rev 与投影(没了 ⇒ undefined)。 */
87
87
  private freshRow;
88
88
  /**
89
- * add:`INSERT … ON CONFLICT (id)`,冲突靶 = 仅主键。计划时这个 id 已有行 ⇒ `DO UPDATE … WHERE` 行仍在计划的投影上(同 scope re-add 的幂等
90
- * 覆盖;行被挪走就不覆盖 —— 被挪去的那个拼写没问过);计划时没有 ⇒ `DO NOTHING`(同 id 的行在判与写之间被别的副本插入就不覆盖)。
91
- * 两种「不覆盖」都让 `RETURNING` 交零行 ⇒ 现读确认后答 `moved`(驱动器按现状重判)。剩下能撞的唯一键只有 `(scope, slug)` ⇒ `slug-taken`。
89
+ * add:`INSERT … ON CONFLICT (id)`,冲突靶 = 仅主键。计划时这个 id 已有行 ⇒ `DO UPDATE … WHERE` 行仍在计划的投影上(同 scope re-add 的
90
+ * 幂等覆盖;行被挪走就不覆盖 —— 被挪去的那个拼写没问过),add-if-absent 再绑计划读到的 rev(行被改写就不覆盖 —— 它判的是那一份内容);
91
+ * 计划时没有 ⇒ `DO NOTHING`(同 id 的行在判与写之间被别的副本插入就不覆盖)。两种「不覆盖」都让 `RETURNING` 交零行 ⇒ 现读确认后答
92
+ * `moved`(驱动器按现状重判)。剩下能撞的唯一键只有 `(scope, slug)` ⇒ `slug-taken`。
92
93
  */
93
94
  private writeAdd;
94
95
  /** update:条件 = 判过的 rev **且**判过的投影(rev 是内容哈希、不含 scope / slug)。零行 ⇒ 现读:内容未变而投影变了 = `moved`;其余 =
@@ -222,10 +222,10 @@ export class PgMemoryEngineBackend {
222
222
  const T = PG_MEMORY_ENGINE_TABLES.entry;
223
223
  const params = [stored.id, stored.scope, stored.slug, pgSafeJsonStringify(stored.frontmatter), stored.body, rev, this.clock(), Buffer.byteLength(serializeEntryFile(stored), "utf8"), embedding];
224
224
  const onConflict = prior !== undefined
225
- ? `ON CONFLICT (id) DO UPDATE SET scope = $2, slug = $3, frontmatter = $4, body = $5, rev = $6, mtime_ms = $7, size_bytes = $8, embedding = $9 WHERE ${T}.scope = $10 AND ${T}.slug = $11`
225
+ ? `ON CONFLICT (id) DO UPDATE SET scope = $2, slug = $3, frontmatter = $4, body = $5, rev = $6, mtime_ms = $7, size_bytes = $8, embedding = $9 WHERE ${T}.scope = $10 AND ${T}.slug = $11${prior.rev !== undefined ? ` AND ${T}.rev = $12` : ""}`
226
226
  : "ON CONFLICT (id) DO NOTHING";
227
227
  if (prior !== undefined)
228
- params.push(prior.scope, prior.slug);
228
+ params.push(prior.scope, prior.slug, ...(prior.rev !== undefined ? [prior.rev] : []));
229
229
  confirm();
230
230
  let landed;
231
231
  try {
@@ -243,9 +243,9 @@ export class PgMemoryEngineBackend {
243
243
  if (landed)
244
244
  return { kind: "committed" };
245
245
  const fresh = await this.freshRow(stored.id);
246
- if (fresh !== undefined && (prior === undefined || fresh.scope !== prior.scope || fresh.slug !== prior.slug))
246
+ if (fresh !== undefined && (prior === undefined || fresh.scope !== prior.scope || fresh.slug !== prior.slug || (prior.rev !== undefined && fresh.rev !== prior.rev)))
247
247
  return { kind: "moved" };
248
- throw new Error(`memory-engine: the add of ${JSON.stringify(stored.id)} wrote no row, yet the row is ${fresh === undefined ? "absent" : "still at the planned projection"} — refusing to report it either way`);
248
+ throw new Error(`memory-engine: the add of ${JSON.stringify(stored.id)} wrote no row, yet the row is ${fresh === undefined ? "absent" : "still where the write condition holds"} — refusing to report it either way`);
249
249
  }
250
250
  async writeUpdate({ entry, rev, currentRev, current, baseRev }, embedding, confirm) {
251
251
  const params = [entry.id, entry.scope, entry.slug, pgSafeJsonStringify(entry.frontmatter), entry.body, rev, this.clock(), Buffer.byteLength(serializeEntryFile(entry), "utf8"), embedding, currentRev, current.scope, current.slug];
@@ -34,7 +34,10 @@
34
34
  * · 「已经写过」按**可能写过**算:一条写语句发出之后以 I/O 失败收场,库里落没落不知道 ⇒ 当作写过(此后不再问),否则后面一次被拒的重问
35
35
  * 就可能发生在一笔其实已落下的写之后。写语句的三种「没落」结局(唯一键冲突 / 零行 + 现读)是库给的确答,不算写过。
36
36
  * · 不传 opts ⇒ 没有计划阶段、`confirm` 是空操作;常规路径与改前逐字同。只在并发竞争路径上收紧:行在判与写之间被挪走 ⇒ 按现状重判
37
- * 再写(此前按 id 盲写);同 id 的行在判与写之间被别的副本插入 ⇒ 重判(guard / 跨 scope 拒照判,此前按 id 盲覆盖)。
37
+ * 再写(此前按 id 盲写);同 id 的行在判与写之间被别的副本插入或改写 ⇒ 重判(guard / 跨 scope 拒照判,此前按 id 盲覆盖)。
38
+ * · 写条件只有一条律:写语句绑住**判据用到的那一份** —— update / delete 判的是 rev(CAS)与投影 ⇒ 两者都绑;add 覆盖判的是投影
39
+ * (落点),`guard: "absent"` 再判「恰是这一份」⇒ 再绑 rev;add 插入判的是「没有这一行」⇒ 只插入。裸 add 的判不看内容(幂等覆盖现值),
40
+ * 写也不绑 rev。库给的「没落」一律回到判(update / delete 的 rev 变了 = CAS 输,add = 重判)。
38
41
  */
39
42
  import { type MemoryBackend, type MemoryEntry, type MemoryEntryFrontmatter, type NotePatch, type PatchReport } from "@sema-agent/core";
40
43
  import type { MemoryHistoryAppendRow } from "./memory-sync-store-pg.js";
@@ -59,12 +62,18 @@ export interface SqlProjection {
59
62
  readonly scope: string;
60
63
  readonly slug: string;
61
64
  }
62
- /** add 的写入单:`stored` = 终拼形(含后缀)。`prior` = 计划时这个 id 的行所在的投影(缺席 = 计划时没有这一行):写语句只覆盖仍在那里的行,
63
- * 没有 prior 时只插入 —— 行在判与写之间被挪走 / 被别的副本插入都答 `moved`。 */
65
+ /** add 覆盖的写条件:投影恒绑;`rev` 只在判据用到了它时在场(`guard: "absent"` 判的是「恰是这一份」),裸 add 的判不看内容 ⇒ `undefined`。 */
66
+ export interface SqlAddPrior extends SqlProjection {
67
+ readonly rev: string | undefined;
68
+ }
69
+ /** add 的写入单:`stored` = 终拼形(含后缀)。`prior` = 计划时这个 id 的那一行要绑住的部分(缺席 = 计划时没有这一行):写语句只覆盖仍在
70
+ * 那里(且带 `rev` 时仍是那一份内容)的行,没有 prior 时只插入 —— 行在判与写之间被挪走 / 被改写(带 `rev` 时)/ 被别的副本插入都答 `moved`
71
+ * (驱动器按现状重判:`guard: "absent"` 照判 —— 行已在且不是这一份内容 ⇒ `add_guard_absent_conflict`)。add-if-absent 因此是原子的:
72
+ * 「判时没有」与「判时恰是这一份」两个前提都随写语句一起交给库判,判与写之间的并发写者不会被静默覆盖。 */
64
73
  export interface SqlAddWrite {
65
74
  readonly stored: MemoryEntry;
66
75
  readonly rev: string;
67
- readonly prior: SqlProjection | undefined;
76
+ readonly prior: SqlAddPrior | undefined;
68
77
  }
69
78
  /** update 的写入单:条件 = 判过的 rev **且**判过的投影 `current`。 */
70
79
  export interface SqlUpdateWrite {
@@ -94,7 +94,7 @@ async function planSqlPatch(patch, reads, baseline, claims, unstorableReason, su
94
94
  kind: "add",
95
95
  stored,
96
96
  rev: computeEntryRev(stored),
97
- prior: prior !== undefined ? { scope: prior.scope, slug: prior.slug } : undefined,
97
+ prior: prior !== undefined ? { scope: prior.scope, slug: prior.slug, rev: patch.guard === "absent" ? prior.rev : undefined } : undefined,
98
98
  frontmatter: entry.frontmatter,
99
99
  suffixAt: n,
100
100
  landings,
@@ -67,11 +67,14 @@ export declare class TiDBMemoryEngineBackend implements MemoryBackend {
67
67
  private freshRow;
68
68
  /**
69
69
  * add:拆成「计划时有行 ⇒ UPDATE by id / 没有 ⇒ INSERT」(见文件头:MySQL 的 ON DUPLICATE KEY UPDATE 会被 `(scope, slug)` 键抢占、改写他人行,
70
- * 禁用)。UPDATE 腿只覆盖仍在计划投影上的行;零 AFFECTED 行 ⇒ 现读:行没了 = 被并发删掉 ⇒ 转 INSERT 腿、同一拼写(改前同);
71
- * 行在别处 ⇒ `moved`;行还在计划的投影上且已是这一份内容 = 匹配但值逐字相同(连接未开 FOUND_ROWS 时只数改动行)⇒ 已落;
72
- * 行还在计划的投影上却不是这一份内容 = 判与现读之间行被挪走又挪回 ⇒ 响亮抛(记成这一条的 io error 冲突,与 PG 孪生同答)。INSERT 腿的 ER_DUP_ENTRY 按键名分诊:
73
- * PRIMARY = 同 id 的行在判与写之间被别的副本插入 ⇒ `moved`(驱动器按现状重判,guard / 跨 scope 拒照判);`uq_…scope_slug` = 名在计划之后
74
- * 被占 ⇒ `slug-taken`。每次重发写语句前都调 confirm(它是检查,幂等)。
70
+ * 禁用)。UPDATE 腿只覆盖仍在计划投影上的行,add-if-absent 再绑计划读到的 rev(与 PG 孪生同一条件);零 AFFECTED 行 ⇒ 现读:行没了 = 被并发
71
+ * 删掉 ⇒ 转 INSERT 腿、同一拼写(改前同);行在别处、或(绑了 rev 时)已被改写 ⇒ `moved`(驱动器按现状重判:add-if-absent 照判);行仍满足写条件且
72
+ * 已是这一份内容 = 匹配但值逐字相同(连接未开 FOUND_ROWS 时只数改动行)⇒ 已落;仍满足写条件却不是这一份内容 = 判与现读之间行被改走又改回
73
+ * ⇒ 响亮抛(记成这一条的 io error 冲突,与 PG 孪生同答)。ER_DUP_ENTRY 按**现读**分诊,不按报文里的键名:INSERT 腿撞键之后这个 id 的行在 ⇒
74
+ * 同 id 的行在判与写之间被别的副本插入 ⇒ `moved`(驱动器按现状重判,guard / 跨 scope 拒照判;与 PG 孪生 `ON CONFLICT (id)` 的仲裁同答);不在 ⇒
75
+ * 名在计划之后被占 ⇒ `slug-taken`;UPDATE 腿按 id 改、只撞得上 `(scope, slug)` ⇒ `slug-taken`。键名不可作判据:对手以同 id **同拼写**插入时
76
+ * 两只唯一键同时撞上,引擎报哪一只由它自己定(TiDB 报 `uq_…scope_slug`)—— 按键名会把「同 id 已在」读成「名被占」、退到 `-2` 拼写去覆盖。
77
+ * 每次重发写语句前都调 confirm(它是检查,幂等)。
75
78
  */
76
79
  private writeAdd;
77
80
  /** update:条件 = 判过的 rev **且**判过的投影(rev 是内容哈希、不含 scope / slug)。零 AFFECTED 行 ⇒ 这一条的 CAS 按 **rev** 判(core 契约:stale
@@ -37,9 +37,6 @@ export async function ensureTiDBMemoryEngineSchema(pool) {
37
37
  await ensureIndexes((text, params) => pool.query(text, params), "mysql", MEMORY_ENGINE_INDEXES);
38
38
  }
39
39
  const isDupEntry = isMysqlDupKeyError;
40
- function isPrimaryKeyDup(err) {
41
- return isDupEntry(err) && /for key '[^']*PRIMARY'/i.test(String(err.message ?? ""));
42
- }
43
40
  const AT_PLANNED_PROJECTION = "CAST(scope AS BINARY) = CAST(? AS BINARY) AND CAST(slug AS BINARY) = CAST(? AS BINARY)";
44
41
  function inPlaceholders(count) {
45
42
  return Array.from({ length: count }, () => "?").join(", ");
@@ -182,19 +179,19 @@ export class TiDBMemoryEngineBackend {
182
179
  for (;;) {
183
180
  try {
184
181
  if (overwrite !== undefined) {
185
- const params = [stored.scope, stored.slug, JSON.stringify(stored.frontmatter), stored.body, rev, this.clock(), sizeBytes, stored.id, overwrite.scope, overwrite.slug];
182
+ const params = [stored.scope, stored.slug, JSON.stringify(stored.frontmatter), stored.body, rev, this.clock(), sizeBytes, stored.id, ...(overwrite.rev !== undefined ? [overwrite.rev] : []), overwrite.scope, overwrite.slug];
186
183
  confirm();
187
- const res = await this.write(`UPDATE ${T} SET scope = ?, slug = ?, frontmatter = ?, body = ?, rev = ?, mtime_ms = ?, size_bytes = ?, embedding = NULL WHERE id = ? AND ${AT_PLANNED_PROJECTION}`, params);
184
+ const res = await this.write(`UPDATE ${T} SET scope = ?, slug = ?, frontmatter = ?, body = ?, rev = ?, mtime_ms = ?, size_bytes = ?, embedding = NULL WHERE id = ? AND ${overwrite.rev !== undefined ? "rev = ? AND " : ""}${AT_PLANNED_PROJECTION}`, params);
188
185
  if (res.affectedRows === 0) {
189
186
  const fresh = await this.freshRow(stored.id);
190
187
  if (fresh === undefined) {
191
188
  overwrite = undefined;
192
189
  continue;
193
190
  }
194
- if (fresh.scope !== overwrite.scope || fresh.slug !== overwrite.slug)
191
+ if (fresh.scope !== overwrite.scope || fresh.slug !== overwrite.slug || (overwrite.rev !== undefined && fresh.rev !== overwrite.rev))
195
192
  return { kind: "moved" };
196
193
  if (fresh.rev !== rev) {
197
- throw new Error(`memory-engine: the add of ${JSON.stringify(stored.id)} wrote no row, yet the row is still at the planned projection with other content — refusing to report it either way`);
194
+ throw new Error(`memory-engine: the add of ${JSON.stringify(stored.id)} wrote no row, yet the row still meets the write condition with other content — refusing to report it either way`);
198
195
  }
199
196
  }
200
197
  }
@@ -207,7 +204,9 @@ export class TiDBMemoryEngineBackend {
207
204
  catch (err) {
208
205
  if (!isDupEntry(err))
209
206
  throw err;
210
- return isPrimaryKeyDup(err) ? { kind: "moved" } : { kind: "slug-taken" };
207
+ if (overwrite !== undefined)
208
+ return { kind: "slug-taken" };
209
+ return (await this.freshRow(stored.id)) !== undefined ? { kind: "moved" } : { kind: "slug-taken" };
211
210
  }
212
211
  return { kind: "committed" };
213
212
  }