@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
@@ -0,0 +1,130 @@
1
+ /**
2
+ * 两只 SQL 记忆腿(`memory-engine-pg.ts` / `memory-engine-tidb.ts`)的 `applyPatches` —— **一份判、一个驱动器**。
3
+ *
4
+ * ## 为什么是一个共享模块
5
+ *
6
+ * 两腿此前各抄一份 `applyOne`(op 闭集 / 键宽 / 歧义 origin / 不可变律 / guard / 跨 scope / 撞名后缀 / rev CAS),逐段「Pg 版同注」,
7
+ * 且「判」与「写」交织在一条循环里。core 的落点问询协议(`MemoryBackend.applyPatches` 的 `opts.admit` / `opts.confirm` 与能力位
8
+ * `admitsLandings`,协议原文 = core `landing-admission.d.ts` 头注)要求后端**先判出整批的落点、问过、再写** —— 交织形做不到,两份
9
+ * 各拆一遍就是两个写者写同一条协议。所以判只有一份({@link planSqlPatch},只读,产出决定 + 落点),驱动器只有一个
10
+ * ({@link applySqlPatches}),两腿各自只剩**读口**(两只 SELECT)、**方言写口**(add / update / delete 的 CAS 写)与 history 冲刷。
11
+ *
12
+ * ## 协议在 SQL 上的读法
13
+ *
14
+ * 与 core File 腿(`file-backend.js` 的 `applyPatches` / `applyPatchesLocked`)的差别都出自「SQL 腿没有事务锁」这一个结构事实:
15
+ * ① File 在锁内计划、出锁问、再进锁重计划,直到整批每个落点都问过才开始提交;这里没有锁可出,计划是对库的只读预测,问过之后
16
+ * **再整批预测一遍**(File 的「再计划」),仍有没问过的就再问 —— 所以 `admit` 的每一次调用都在本次 apply 的第一笔写之前,拒 ⇒ 一字未写。
17
+ * 「问、记下问过的、轮数预算、超限的码与句」整圈是 core 的 `admittingLandings`(File 腿同一只),本模块只交它一次尝试(预测 + 提交);
18
+ * 「这些落点问过没有」只问 core 的 `requireLandingsAdmitted`(问过的集合与它的键都是 core 的,本模块不持第二份);
19
+ * ② 提交恒为一 patch 一条写语句(两态都不会一次提交两个 patch 的落点)。每条写之前现判一次:落点在最后一次预测之后才变(并发写者抢名 /
20
+ * 挪走行)且变出了没问过的拼写 ⇒ 本次 apply 还一笔没写时回去再问;已经写过 ⇒ 不再问(再问就可能「拒了却已写了前缀」),这一条报冲突、
21
+ * 一字不写,下次 apply 再问 —— 与 File「崩在两个落点之间,后一个留给下次 apply 再问」同一语义(变去的拼写都问过 ⇒ 照写);
22
+ * ③ File 的 confirm 在事务锁下调;这里在写语句之前同步调,不持锁。
23
+ *
24
+ * · LANDING = 一个 patch 写下或移走的每个拼写 `{ id, scope, slug }`:add 的终拼(含撞名后缀)、同 scope 改名留下的旧拼、update 的目标
25
+ * 与移走的旧拼、delete 移走的拼。
26
+ * · 写语句把**计划的投影**也绑进条件(rev 是内容哈希、不含 scope / slug,单靠 `WHERE id AND rev` 绑不住落点):行在计划之后被挪到别的拼写
27
+ * ⇒ 写不落,方言写口按现读答 `moved`,驱动器重判(新拼写同样要问过才写);名被占(唯一键冲突)⇒ `slug-taken`,重判从下一个后缀起
28
+ * (与改前「撞键即退下一个后缀」同一序列)。
29
+ * · 问的次数有上限(core `MAX_LANDING_ADMISSION_ROUNDS`),超了 core 抛 `memory.landing_unstable`(此时恒一字未写)。
30
+ * · `confirm` = 调用方的最后一句话:方言写口在**每条** entry 写语句发出之前同步调它(与写语句之间没有 await)。SQL 腿不持事务锁 ——
31
+ * confirm 与写语句之间仍有一段竞争窗,这是两腿「单语句 CAS、无事务」的既有结构事实(MIGRATION / USAGE 的已知限制一句)。
32
+ * · 抛错分诊:per-patch 的 catch 只把读 / 写 I/O 失败记成 `io error` 冲突(改前同);`confirm` 的抛被包成 {@link CallerThrow} 越过这道
33
+ * catch,出驱动器时还原成调用方抛出的**同一个值**;`admit` 根本不在 catch 内。已提交 patch 的 history 在 `finally` 里照冲刷。
34
+ * · 「已经写过」按**可能写过**算:一条写语句发出之后以 I/O 失败收场,库里落没落不知道 ⇒ 当作写过(此后不再问),否则后面一次被拒的重问
35
+ * 就可能发生在一笔其实已落下的写之后。写语句的三种「没落」结局(唯一键冲突 / 零行 + 现读)是库给的确答,不算写过。
36
+ * · 不传 opts ⇒ 没有计划阶段、`confirm` 是空操作;常规路径与改前逐字同。只在并发竞争路径上收紧:行在判与写之间被挪走 ⇒ 按现状重判
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 = 重判)。
41
+ */
42
+ import { type MemoryBackend, type MemoryEntry, type MemoryEntryFrontmatter, type NotePatch, type PatchReport } from "@sema-agent/core";
43
+ import type { MemoryHistoryAppendRow } from "./memory-sync-store-pg.js";
44
+ /** `applyPatches` 的第二参 —— 从 core 的 `MemoryBackend` 接口推导,不手抄。 */
45
+ export type SqlApplyOpts = NonNullable<Parameters<MemoryBackend["applyPatches"]>[1]>;
46
+ export type SqlPatchConflict = PatchReport["conflicts"][number];
47
+ /** 计划读到的一行已提交 entry(frontmatter 已解码)。 */
48
+ export interface SqlEntryRow {
49
+ readonly scope: string;
50
+ readonly slug: string;
51
+ readonly rev: string;
52
+ readonly frontmatter: MemoryEntryFrontmatter;
53
+ }
54
+ /** 判的两只读口(方言自供)。 */
55
+ export interface SqlEntryReads {
56
+ rowOf(id: string): Promise<SqlEntryRow | undefined>;
57
+ /** 占着 `(scope, slug)` 的 id(唯一键 ⇒ 至多一个;数组形让叠层视图能并入计划中的行)。 */
58
+ idsAt(scope: string, slug: string): Promise<readonly string[]>;
59
+ }
60
+ /** 一个拼写在库里的位置(写语句绑定的投影)。 */
61
+ export interface SqlProjection {
62
+ readonly scope: string;
63
+ readonly slug: string;
64
+ }
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
+ * 「判时没有」与「判时恰是这一份」两个前提都随写语句一起交给库判,判与写之间的并发写者不会被静默覆盖。 */
73
+ export interface SqlAddWrite {
74
+ readonly stored: MemoryEntry;
75
+ readonly rev: string;
76
+ readonly prior: SqlAddPrior | undefined;
77
+ }
78
+ /** update 的写入单:条件 = 判过的 rev **且**判过的投影 `current`。 */
79
+ export interface SqlUpdateWrite {
80
+ readonly entry: MemoryEntry;
81
+ readonly rev: string;
82
+ readonly currentRev: string;
83
+ readonly current: SqlProjection;
84
+ readonly baseRev: string | undefined;
85
+ }
86
+ /** delete 的写入单:条件同 update。 */
87
+ export interface SqlDeleteWrite {
88
+ readonly id: string;
89
+ readonly currentRev: string;
90
+ readonly current: SqlProjection;
91
+ readonly baseRev: string | undefined;
92
+ }
93
+ /**
94
+ * 一次写的结局:`committed` = 落了;`slug-taken` = 唯一键 `(scope, slug)` 冲突(名在计划之后被别的副本占了);`moved` = 写不落而现读显示
95
+ * 这个 id 的行已不在计划的投影上(或计划时没有、现在有了);`lost` = rev CAS 输了(冲突里的 currentRev 是现值)。
96
+ */
97
+ export type SqlWriteOutcome = {
98
+ readonly kind: "committed";
99
+ } | {
100
+ readonly kind: "slug-taken";
101
+ } | {
102
+ readonly kind: "moved";
103
+ } | {
104
+ readonly kind: "lost";
105
+ readonly conflict: SqlPatchConflict;
106
+ };
107
+ /**
108
+ * 方言写口。每只都必须在它发出的**每条** entry 写语句之前同步调 `confirm()`(中间不许有 await);只把「这条写没落成」的形翻译成结局,
109
+ * 其余 I/O 失败原样抛。`prepare` 在一个 patch 第一次要写之前调一次,结果交给它的每一次写(撞名 / 被挪重试不重算 —— PG 的向量)。
110
+ */
111
+ export interface SqlEntryWrites<P> {
112
+ prepare(entry: MemoryEntry): Promise<P>;
113
+ add(w: SqlAddWrite, prepared: P, confirm: () => void): Promise<SqlWriteOutcome>;
114
+ update(w: SqlUpdateWrite, prepared: P, confirm: () => void): Promise<SqlWriteOutcome>;
115
+ remove(w: SqlDeleteWrite, confirm: () => void): Promise<SqlWriteOutcome>;
116
+ }
117
+ /** 一只 SQL 腿交给驱动器的全部东西。 */
118
+ export interface SqlMemoryLeg<P> {
119
+ readonly reads: SqlEntryReads;
120
+ readonly writes: SqlEntryWrites<P>;
121
+ /** 本方言的 `unstorable_bytes` 拒绝文案(两方言措辞不同,判据同一只 `pgHasUnstorable`)。 */
122
+ readonly unstorableReason: string;
123
+ /** history 行的落笔时刻(只在 `appendHistory` 在场时调,与改前的时钟调用次数同)。 */
124
+ readonly now: () => number;
125
+ /** best-effort history 冲刷(自己吞错计数,永不抛);缺席 ⇒ 不攒 history 行。 */
126
+ readonly appendHistory?: (rows: readonly MemoryHistoryAppendRow[]) => Promise<void>;
127
+ }
128
+ /** 两只 SQL 腿的 `applyPatches`。读法见文件头注。 */
129
+ export declare function applySqlPatches<P>(patches: readonly NotePatch[], opts: SqlApplyOpts | undefined, leg: SqlMemoryLeg<P>): Promise<PatchReport>;
130
+ //# sourceMappingURL=memory-engine-sql-apply.d.ts.map
@@ -0,0 +1,358 @@
1
+ import { LandingsNeedAdmission, admittingLandings, computeEntryRev, requireLandingsAdmitted, } from "@sema-agent/core";
2
+ import { memoryEntryKeyWidthRefusal } from "./memory-key-guards.js";
3
+ import { pgHasUnstorable } from "./pg-safe-json.js";
4
+ import { ambiguousOriginRefusal, createBatchCommittedBaseline, distilledWhitewashRefusal, originWhitewashRefusal, rememberBatchCommitted, unknownPatchOpRefusal, } from "./memory-origin-law.js";
5
+ const FIRST_SUFFIX_STEP = 2;
6
+ const candidateAt = (slug, n) => (n === FIRST_SUFFIX_STEP ? slug : `${slug}-${n - 1}`);
7
+ const slugKey = (scope, slug) => JSON.stringify([scope, slug]);
8
+ const distinctLandings = (ls) => {
9
+ const seen = new Set();
10
+ return ls.filter((l) => {
11
+ const key = slugKey(l.scope, l.slug);
12
+ if (seen.has(key))
13
+ return false;
14
+ seen.add(key);
15
+ return true;
16
+ });
17
+ };
18
+ const unadmittedOf = (admitted, landings) => {
19
+ try {
20
+ requireLandingsAdmitted(admitted, landings);
21
+ return [];
22
+ }
23
+ catch (err) {
24
+ if (err instanceof LandingsNeedAdmission)
25
+ return err.landings;
26
+ throw err;
27
+ }
28
+ };
29
+ async function planSqlPatch(patch, reads, baseline, claims, unstorableReason, suffixFrom) {
30
+ const conflict = (c) => ({ kind: "conflict", conflict: c });
31
+ const unknownOp = unknownPatchOpRefusal(patch.op);
32
+ if (unknownOp !== undefined)
33
+ return conflict({ op: patch.op, id: patch.id, reason: unknownOp });
34
+ if (patch.op !== "delete" && patch.entry !== undefined && patch.entry.id !== patch.id) {
35
+ return conflict({ op: patch.op, id: patch.id, reason: `patch id ${JSON.stringify(patch.id)} != entry id ${JSON.stringify(patch.entry.id)} (malformed patch refused)` });
36
+ }
37
+ if (patch.op !== "delete" && patch.entry !== undefined) {
38
+ const refusal = memoryEntryKeyWidthRefusal(patch.entry.scope, patch.entry.slug);
39
+ if (refusal !== undefined)
40
+ return conflict({ op: patch.op, id: patch.id, reason: refusal });
41
+ }
42
+ if (patch.op !== "delete" && patch.entry !== undefined) {
43
+ const refusal = ambiguousOriginRefusal(patch.entry.frontmatter);
44
+ if (refusal !== undefined)
45
+ return conflict({ op: patch.op, id: patch.id, reason: refusal });
46
+ }
47
+ if (patch.op === "add") {
48
+ const entry = patch.entry;
49
+ if (!entry)
50
+ return conflict({ op: "add", id: patch.id, reason: "add patch without an entry" });
51
+ if (pgHasUnstorable(entry.frontmatter) || pgHasUnstorable(entry.body) || pgHasUnstorable(entry.slug)) {
52
+ return conflict({ op: "add", id: entry.id, reason: unstorableReason });
53
+ }
54
+ const prior = await reads.rowOf(entry.id);
55
+ const baseFm = rememberBatchCommitted(baseline, entry.id, prior?.frontmatter);
56
+ const originRefusal = originWhitewashRefusal("add", baseFm, entry.frontmatter);
57
+ if (originRefusal !== undefined)
58
+ return conflict({ op: "add", id: entry.id, reason: originRefusal });
59
+ const distilledRefusal = distilledWhitewashRefusal("add", baseFm, entry.frontmatter);
60
+ if (distilledRefusal !== undefined)
61
+ return conflict({ op: "add", id: entry.id, reason: distilledRefusal });
62
+ if (patch.guard === "absent" && prior !== undefined) {
63
+ if (prior.rev !== computeEntryRev(entry)) {
64
+ return conflict({ op: "add", id: entry.id, reason: "add_guard_absent_conflict (id already exists at a different rev; add-if-absent refuses to overwrite)", currentRev: prior.rev });
65
+ }
66
+ if (prior.scope !== entry.scope || prior.slug !== entry.slug) {
67
+ return conflict({
68
+ op: "add",
69
+ id: entry.id,
70
+ reason: `add_guard_absent_conflict (id already exists at the same rev but a different projection ${JSON.stringify(`${prior.scope}/${prior.slug}`)}; add-if-absent refuses to duplicate)`,
71
+ currentRev: prior.rev,
72
+ });
73
+ }
74
+ }
75
+ if (prior !== undefined && prior.scope !== entry.scope) {
76
+ return conflict({ op: "add", id: entry.id, reason: `id already exists in scope ${JSON.stringify(prior.scope)} (cross-scope add refused)` });
77
+ }
78
+ let n = suffixFrom;
79
+ let slug = candidateAt(entry.slug, n);
80
+ for (;; n++, slug = candidateAt(entry.slug, n)) {
81
+ const derivedRefusal = memoryEntryKeyWidthRefusal(entry.scope, slug);
82
+ if (derivedRefusal !== undefined) {
83
+ return conflict({ op: "add", id: entry.id, reason: `${derivedRefusal} (slug collision suffix "-${n - 1}" no longer fits the column — shorten the entry name)` });
84
+ }
85
+ if (!claims.has(slugKey(entry.scope, slug)) && !(await reads.idsAt(entry.scope, slug)).some((id) => id !== entry.id))
86
+ break;
87
+ }
88
+ const stored = { ...entry, slug };
89
+ const landings = [];
90
+ if (prior !== undefined && prior.slug !== slug)
91
+ landings.push({ id: entry.id, scope: prior.scope, slug: prior.slug });
92
+ landings.push({ id: entry.id, scope: entry.scope, slug });
93
+ return {
94
+ kind: "add",
95
+ stored,
96
+ rev: computeEntryRev(stored),
97
+ prior: prior !== undefined ? { scope: prior.scope, slug: prior.slug, rev: patch.guard === "absent" ? prior.rev : undefined } : undefined,
98
+ frontmatter: entry.frontmatter,
99
+ suffixAt: n,
100
+ landings,
101
+ };
102
+ }
103
+ const current = await reads.rowOf(patch.id);
104
+ if (current === undefined)
105
+ return conflict({ op: patch.op, id: patch.id, reason: "unknown id (entry not found in backend)" });
106
+ const baseFm = rememberBatchCommitted(baseline, patch.id, current.frontmatter);
107
+ if (patch.op === "update" && patch.entry !== undefined) {
108
+ if (current.frontmatter.provenance?.kind === "repo_file") {
109
+ const next = patch.entry.frontmatter;
110
+ const stripsProvenance = next.provenance === undefined;
111
+ const stripsTrust = current.frontmatter.trust !== undefined && next.trust === undefined;
112
+ if (stripsProvenance || stripsTrust) {
113
+ return conflict({
114
+ op: "update",
115
+ id: patch.id,
116
+ reason: `repo_file provenance whitewash refused: update drops ${stripsProvenance ? "provenance" : "trust"} from a repo-ingested entry (malformed patch refused)`,
117
+ });
118
+ }
119
+ }
120
+ const originRefusal = originWhitewashRefusal("update", baseFm, patch.entry.frontmatter);
121
+ if (originRefusal !== undefined)
122
+ return conflict({ op: "update", id: patch.id, reason: originRefusal });
123
+ const distilledRefusal = distilledWhitewashRefusal("update", baseFm, patch.entry.frontmatter);
124
+ if (distilledRefusal !== undefined)
125
+ return conflict({ op: "update", id: patch.id, reason: distilledRefusal });
126
+ }
127
+ if (patch.baseRev !== undefined && patch.baseRev !== current.rev) {
128
+ return conflict({ op: patch.op, id: patch.id, reason: "rev mismatch (concurrent change)", baseRev: patch.baseRev, currentRev: current.rev });
129
+ }
130
+ const at = { scope: current.scope, slug: current.slug };
131
+ if (patch.op === "delete") {
132
+ return { kind: "delete", id: patch.id, currentRev: current.rev, current: at, baseRev: patch.baseRev, landings: [{ id: patch.id, ...at }] };
133
+ }
134
+ const entry = patch.entry;
135
+ if (!entry)
136
+ return conflict({ op: "update", id: patch.id, reason: "update patch without an entry" });
137
+ if (pgHasUnstorable(entry.frontmatter) || pgHasUnstorable(entry.body) || pgHasUnstorable(entry.slug)) {
138
+ return conflict({ op: "update", id: patch.id, reason: unstorableReason });
139
+ }
140
+ const moves = current.scope !== entry.scope || current.slug !== entry.slug;
141
+ return {
142
+ kind: "update",
143
+ entry,
144
+ rev: computeEntryRev(entry),
145
+ currentRev: current.rev,
146
+ current: at,
147
+ baseRev: patch.baseRev,
148
+ landings: [...(moves ? [{ id: patch.id, ...at }] : []), { id: entry.id, scope: entry.scope, slug: entry.slug }],
149
+ };
150
+ }
151
+ class CallerThrow extends Error {
152
+ thrown;
153
+ constructor(thrown) {
154
+ super("caller confirm threw");
155
+ this.thrown = thrown;
156
+ }
157
+ }
158
+ function duplicatePositions(patches) {
159
+ const seen = new Set();
160
+ const dup = new Set();
161
+ patches.forEach((p, i) => {
162
+ if (p.op === "delete")
163
+ return;
164
+ if (seen.has(p.id))
165
+ dup.add(i);
166
+ else
167
+ seen.add(p.id);
168
+ });
169
+ return dup;
170
+ }
171
+ async function predictLandings(patches, from, duplicateAt, reads, unstorableReason, baseline, claims, suffixFloor) {
172
+ const overlay = new Map();
173
+ const view = {
174
+ rowOf: async (id) => (overlay.has(id) ? (overlay.get(id) ?? undefined) : reads.rowOf(id)),
175
+ idsAt: async (scope, slug) => {
176
+ const ids = (await reads.idsAt(scope, slug)).filter((id) => !overlay.has(id));
177
+ for (const [id, row] of overlay)
178
+ if (row !== null && row.scope === scope && row.slug === slug)
179
+ ids.push(id);
180
+ return ids;
181
+ },
182
+ };
183
+ const scratchBaseline = new Map(baseline);
184
+ const scratchClaims = new Set(claims);
185
+ const landings = [];
186
+ for (let i = from; i < patches.length; i++) {
187
+ if (duplicateAt.has(i))
188
+ continue;
189
+ let plan;
190
+ let targetHeld = false;
191
+ try {
192
+ plan = await planSqlPatch(patches[i], view, scratchBaseline, scratchClaims, unstorableReason, suffixFloor.get(i) ?? FIRST_SUFFIX_STEP);
193
+ if (plan.kind === "update") {
194
+ const { id, scope, slug } = plan.entry;
195
+ targetHeld = (await view.idsAt(scope, slug)).some((holder) => holder !== id);
196
+ }
197
+ }
198
+ catch {
199
+ continue;
200
+ }
201
+ if (plan.kind === "conflict")
202
+ continue;
203
+ landings.push(...plan.landings);
204
+ if (plan.kind === "add") {
205
+ overlay.set(plan.stored.id, { scope: plan.stored.scope, slug: plan.stored.slug, rev: plan.rev, frontmatter: plan.frontmatter });
206
+ scratchClaims.add(slugKey(plan.stored.scope, plan.stored.slug));
207
+ }
208
+ else if (plan.kind === "update") {
209
+ if (!targetHeld)
210
+ overlay.set(plan.entry.id, { scope: plan.entry.scope, slug: plan.entry.slug, rev: plan.rev, frontmatter: plan.entry.frontmatter });
211
+ }
212
+ else {
213
+ overlay.set(plan.id, null);
214
+ }
215
+ }
216
+ return landings;
217
+ }
218
+ function movedAfterAdmission(patch, unasked) {
219
+ const l = unasked[0];
220
+ return {
221
+ op: patch.op,
222
+ id: patch.id,
223
+ reason: `landing moved after admission (${JSON.stringify(`${l.scope}/${l.slug}`)} was not admitted: a concurrent writer moved the entry or took the name after this batch was asked about and began writing); not written — the next apply asks about it again`,
224
+ };
225
+ }
226
+ export async function applySqlPatches(patches, opts, leg) {
227
+ const report = { applied: [], conflicts: [] };
228
+ const duplicateAt = duplicatePositions(patches);
229
+ const baseline = createBatchCommittedBaseline();
230
+ const claims = new Set();
231
+ const suffixFloor = new Map();
232
+ const history = [];
233
+ const preparedAt = new Map();
234
+ const admit = opts?.admit;
235
+ let mayHaveWritten = false;
236
+ const callerConfirm = opts?.confirm;
237
+ const confirm = () => {
238
+ if (callerConfirm === undefined)
239
+ return;
240
+ try {
241
+ callerConfirm();
242
+ }
243
+ catch (thrown) {
244
+ throw new CallerThrow(thrown);
245
+ }
246
+ };
247
+ const record = (plan) => {
248
+ if (plan.kind === "add") {
249
+ claims.add(slugKey(plan.stored.scope, plan.stored.slug));
250
+ report.applied.push({ op: "add", id: plan.stored.id, slug: plan.stored.slug });
251
+ if (leg.appendHistory)
252
+ history.push({ id: plan.stored.id, rev: plan.rev, op: "add", scope: plan.stored.scope, snapshot: { ...plan.stored, rev: plan.rev }, writtenAtMs: leg.now() });
253
+ }
254
+ else if (plan.kind === "update") {
255
+ report.applied.push({ op: "update", id: plan.entry.id, slug: plan.entry.slug });
256
+ if (leg.appendHistory)
257
+ history.push({ id: plan.entry.id, rev: plan.rev, prevRev: plan.currentRev, op: "update", scope: plan.entry.scope, snapshot: { ...plan.entry, rev: plan.rev }, writtenAtMs: leg.now() });
258
+ }
259
+ else {
260
+ report.applied.push({ op: "delete", id: plan.id, slug: plan.current.slug });
261
+ if (leg.appendHistory)
262
+ history.push({ id: plan.id, rev: `tombstone:${plan.currentRev}`, prevRev: plan.currentRev, op: "delete", scope: plan.current.scope, writtenAtMs: leg.now() });
263
+ }
264
+ };
265
+ const predictFrom = (from) => predictLandings(patches, from, duplicateAt, leg.reads, leg.unstorableReason, baseline, claims, suffixFloor);
266
+ const commitOne = async (patch, k, admitted) => {
267
+ let issued = false;
268
+ const confirmThenIssue = () => {
269
+ confirm();
270
+ issued = true;
271
+ };
272
+ try {
273
+ for (;;) {
274
+ issued = false;
275
+ const plan = await planSqlPatch(patch, leg.reads, baseline, claims, leg.unstorableReason, suffixFloor.get(k) ?? FIRST_SUFFIX_STEP);
276
+ if (plan.kind === "conflict") {
277
+ report.conflicts.push(plan.conflict);
278
+ return [];
279
+ }
280
+ if (admitted !== undefined) {
281
+ const unasked = unadmittedOf(admitted, plan.landings);
282
+ if (unasked.length > 0)
283
+ return unasked;
284
+ }
285
+ let outcome;
286
+ if (plan.kind === "delete")
287
+ outcome = await leg.writes.remove(plan, confirmThenIssue);
288
+ else {
289
+ let prepared = preparedAt.get(k);
290
+ if (prepared === undefined) {
291
+ prepared = { value: await leg.writes.prepare(patch.entry) };
292
+ preparedAt.set(k, prepared);
293
+ }
294
+ outcome = plan.kind === "add" ? await leg.writes.add(plan, prepared.value, confirmThenIssue) : await leg.writes.update(plan, prepared.value, confirmThenIssue);
295
+ }
296
+ switch (outcome.kind) {
297
+ case "committed":
298
+ mayHaveWritten = true;
299
+ record(plan);
300
+ return [];
301
+ case "lost":
302
+ report.conflicts.push(outcome.conflict);
303
+ return [];
304
+ case "slug-taken":
305
+ if (plan.kind === "add")
306
+ suffixFloor.set(k, plan.suffixAt + 1);
307
+ continue;
308
+ case "moved":
309
+ continue;
310
+ default: {
311
+ const unknown = outcome;
312
+ throw new Error(`unknown write outcome ${JSON.stringify(unknown)}`);
313
+ }
314
+ }
315
+ }
316
+ }
317
+ catch (err) {
318
+ if (err instanceof CallerThrow)
319
+ throw err;
320
+ if (issued)
321
+ mayHaveWritten = true;
322
+ report.conflicts.push({ op: patch.op, id: patch.id, reason: `io error: ${err instanceof Error ? err.message : String(err)}` });
323
+ return [];
324
+ }
325
+ };
326
+ let k = 0;
327
+ const attempt = async (admitted) => {
328
+ if (admitted !== undefined)
329
+ requireLandingsAdmitted(admitted, await predictFrom(k));
330
+ while (k < patches.length) {
331
+ const patch = patches[k];
332
+ if (duplicateAt.has(k)) {
333
+ report.conflicts.push({ op: patch.op, id: patch.id, reason: "duplicate id in batch: another add/update for this id is already planned (copied file keeping its frontmatter id?)" });
334
+ k++;
335
+ continue;
336
+ }
337
+ const unasked = await commitOne(patch, k, admitted);
338
+ if (unasked.length > 0 && admitted !== undefined && !mayHaveWritten) {
339
+ throw new LandingsNeedAdmission(distinctLandings([...unasked, ...unadmittedOf(admitted, await predictFrom(k))]));
340
+ }
341
+ if (unasked.length > 0)
342
+ report.conflicts.push(movedAfterAdmission(patch, unasked));
343
+ k++;
344
+ }
345
+ };
346
+ try {
347
+ await admittingLandings(admit, attempt);
348
+ }
349
+ catch (err) {
350
+ throw err instanceof CallerThrow ? err.thrown : err;
351
+ }
352
+ finally {
353
+ if (leg.appendHistory && history.length > 0)
354
+ await leg.appendHistory(history);
355
+ }
356
+ return report;
357
+ }
358
+ //# sourceMappingURL=memory-engine-sql-apply.js.map
@@ -1,5 +1,6 @@
1
1
  import type { MemoryHistoryAppendRow } from "./memory-sync-store-pg.js";
2
2
  import type { PgEmbedder } from "./pg-query.js";
3
+ import { type SqlApplyOpts } from "./memory-engine-sql-apply.js";
3
4
  import type { MemoryBackend, MemoryEntry, MemoryEntryHeader, NotePatch, PatchReport, ScoredMemoryEntry } from "@sema-agent/core";
4
5
  import type { Pool } from "mysql2/promise";
5
6
  /** Table names (single source) — SAME names as PG_MEMORY_ENGINE_TABLES (the two dialects never share
@@ -38,6 +39,8 @@ export declare class TiDBMemoryEngineBackend implements MemoryBackend {
38
39
  private readonly history?;
39
40
  /** Cumulative lost-row count — audit-line breakage must itself be auditable. */
40
41
  private historyRowsLost;
42
+ /** 交给共享驱动器的读口 / 写口 / history 冲刷(构造末尾铸一次)。 */
43
+ private readonly leg;
41
44
  /** [ref] rung indicator — TiDB v1 sits on the lexical floor (Pg twin parity surface). */
42
45
  get vectorMode(): "lexical";
43
46
  constructor(pool: Pool, opts?: TiDBMemoryEngineBackendOptions);
@@ -53,15 +56,41 @@ export declare class TiDBMemoryEngineBackend implements MemoryBackend {
53
56
  limit?: number;
54
57
  exposureBands?: boolean;
55
58
  }): Promise<ScoredMemoryEntry[]>;
56
- applyPatches(patches: readonly NotePatch[]): Promise<PatchReport>;
57
- private applyOne;
58
- /** The row's rev NOW, or undefined if the row is gone. The existence distinction is the whole point
59
- * (codex lens-3): a concurrent delete must not be mistaken for an idempotent already-at-target write. */
60
- private freshRevOrMissing;
61
- /** When the conditional write reports zero rows (a write landed inside the SELECT→write window), the
62
- * report's `currentRev` must be the rev NOW — re-reporting the pre-race SELECT value could claim
63
- * `baseRev === currentRev` alongside a "rev mismatch" reason. Row gone ⇒ fallback (Pg parity). */
64
- private freshRev;
59
+ /** core 落点问询协议的能力位:`applyPatches` 兑现 `opts.admit` / `opts.confirm`(读法见 `memory-engine-sql-apply.ts` 头注)。 */
60
+ readonly admitsLandings: true;
61
+ /** 判与驱动器只在 `memory-engine-sql-apply.ts` 一处(Pg 孪生同注);本腿只供读口、MySQL 协议方言写口(写语句绑定计划的投影)与 history 冲刷。
62
+ * `opts.anchoredRoot` 是带目录的后端的事,本腿没有目录 ⇒ 不读。 */
63
+ applyPatches(patches: readonly NotePatch[], opts?: SqlApplyOpts): Promise<PatchReport>;
64
+ private rowOf;
65
+ private idsAt;
66
+ /** 写不落之后的现读:这个 id 的行此刻的 rev 与投影(没了 ⇒ undefined)。 */
67
+ private freshRow;
68
+ /**
69
+ * add:拆成「计划时有行 ⇒ UPDATE by id / 没有 ⇒ INSERT」(见文件头:MySQL 的 ON DUPLICATE KEY UPDATE 会被 `(scope, slug)` 键抢占、改写他人行,
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(它是检查,幂等)。
78
+ */
79
+ private writeAdd;
80
+ /** update:条件 = 判过的 rev **且**判过的投影(rev 是内容哈希、不含 scope / slug)。零 AFFECTED 行 ⇒ 这一条的 CAS 按 **rev** 判(core 契约:stale
81
+ * `baseRev` 的 update 是报告的冲突、带 `currentRev`,不按字节 —— 对手把行写成与本次 update 逐字节相同的目标态,这一条也是冲突,Pg 孪生 RETURNING
82
+ * 零行同答):
83
+ * · 一条什么都没改的 update(新 rev == 判过的 rev 且投影不动)在没开 FOUND_ROWS 的连接上匹配了也数 0 ⇒ 现读行仍在判过的 rev + 投影上 = 条件成立 = 已落;
84
+ * 这是零行唯一能是 applied 的形 —— 目标 rev 与判过的 rev 不同的 update 一定改动行(rev 列本身变了),零行即未匹配;
85
+ * 行被对手改走又改回判过的 rev 时,按 rev 它没变过(与 File 腿的比对、与共享判里「A→B→A 让 stale baseRev 重新当前」同一读法),这一条本来就是什么都没改 ⇒ 照样已落;
86
+ * · 内容未变而投影变了 = `moved`;其余 = CAS 冲突,`currentRev` 报现值。
87
+ * 🔴 行存在性是承重的:判与写之间行被并发删掉时 affectedRows 也是 0,现读对没了的行答 undefined ⇒ 落冲突(逐字相同的 update 也一样),两方言同答。 */
88
+ private writeUpdate;
89
+ /** delete:条件同 update;DELETE 的 affectedRows 数的是删掉的行(FOUND_ROWS 只影响 UPDATE):0 = 行变了 / 挪了 / 没了。 */
90
+ private writeDelete;
91
+ /** BEST-EFFORT history append(见 TiDBMemoryEngineBackendOptions.history 的如实取舍):entry 写已提交,审计行追加失败不许让报告
92
+ * 失败 —— 吞 + warn,永不抛;appendHistory 按 (id, rev) 幂等,调用方重试安全。 */
93
+ private appendHistory;
65
94
  getConsolidationCursor(scope: string): Promise<string | undefined>;
66
95
  setConsolidationCursor(scope: string, cursor: string): Promise<void>;
67
96
  }