@sema-agent/server 1.322.0 → 2.0.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 (539) hide show
  1. package/dist/approval-hmac.d.ts +40 -0
  2. package/dist/approval-hmac.js +67 -0
  3. package/dist/approval.d.ts +31 -0
  4. package/dist/approval.js +72 -4
  5. package/dist/audit.d.ts +26 -0
  6. package/dist/audit.js +40 -1
  7. package/dist/auth-bridge.d.ts +10 -0
  8. package/dist/auth-bridge.js +47 -4
  9. package/dist/auth-keys.d.ts +19 -0
  10. package/dist/auth-keys.js +13 -0
  11. package/dist/bake-runner/main.d.ts +5 -0
  12. package/dist/bake-runner/main.js +43 -4
  13. package/dist/bake-runner/protocol.d.ts +57 -0
  14. package/dist/bake-runner/protocol.js +58 -3
  15. package/dist/bake-runner/runner.d.ts +54 -0
  16. package/dist/bake-runner/runner.js +87 -5
  17. package/dist/bench/l8/artifact.d.ts +63 -0
  18. package/dist/bench/l8/artifact.js +61 -2
  19. package/dist/bench/l8/escape.d.ts +36 -0
  20. package/dist/bench/l8/escape.js +25 -0
  21. package/dist/bench/l8/index.d.ts +14 -0
  22. package/dist/bench/l8/index.js +14 -0
  23. package/dist/bench/l8/probes.d.ts +74 -0
  24. package/dist/bench/l8/probes.js +60 -0
  25. package/dist/bench/l8/run-probes.d.ts +43 -0
  26. package/dist/bench/l8/run-probes.js +45 -2
  27. package/dist/bench/s1/arms.d.ts +126 -0
  28. package/dist/bench/s1/arms.js +188 -13
  29. package/dist/bench/s1/live-deps.d.ts +66 -0
  30. package/dist/bench/s1/live-deps.js +249 -11
  31. package/dist/bench/s1/oracle.d.ts +49 -0
  32. package/dist/bench/s1/oracle.js +36 -1
  33. package/dist/bench/s1/repair-oracle-adapter.d.ts +33 -0
  34. package/dist/bench/s1/repair-oracle-adapter.js +30 -0
  35. package/dist/bench/s1/reviewer.d.ts +38 -0
  36. package/dist/bench/s1/reviewer.js +34 -0
  37. package/dist/bench/s1/row.d.ts +77 -0
  38. package/dist/bench/s1/row.js +62 -0
  39. package/dist/bench/s1/run-firm.d.ts +47 -0
  40. package/dist/bench/s1/run-firm.js +70 -4
  41. package/dist/bench/s1/runner-ctx.d.ts +71 -0
  42. package/dist/bench/s1/runner-ctx.js +36 -0
  43. package/dist/bench/s1/tasks.d.ts +108 -0
  44. package/dist/bench/s1/tasks.js +115 -0
  45. package/dist/boot-reclaim.d.ts +19 -0
  46. package/dist/boot-reclaim.js +20 -0
  47. package/dist/brain.d.ts +25 -0
  48. package/dist/brain.js +61 -1
  49. package/dist/budget.d.ts +66 -0
  50. package/dist/budget.js +128 -4
  51. package/dist/capabilities/builtin-tools.d.ts +3 -0
  52. package/dist/capabilities/builtin-tools.js +3 -0
  53. package/dist/capabilities/center-plugins.d.ts +17 -1
  54. package/dist/capabilities/center-plugins.js +45 -4
  55. package/dist/capabilities/center-prompts.d.ts +46 -0
  56. package/dist/capabilities/center-prompts.js +57 -3
  57. package/dist/capabilities/code-review-council.d.ts +28 -0
  58. package/dist/capabilities/code-review-council.js +40 -7
  59. package/dist/capabilities/collab-wire.d.ts +2 -0
  60. package/dist/capabilities/collab-workflows.d.ts +7 -0
  61. package/dist/capabilities/collab-workflows.js +44 -1
  62. package/dist/capabilities/oa-tools.d.ts +6 -0
  63. package/dist/capabilities/oa-tools.js +10 -0
  64. package/dist/capabilities/prompt.d.ts +14 -0
  65. package/dist/capabilities/prompt.js +14 -0
  66. package/dist/capabilities/prompts/code-review.d.ts +14 -0
  67. package/dist/capabilities/prompts/code-review.js +14 -0
  68. package/dist/capabilities/prompts/identity.d.ts +6 -0
  69. package/dist/capabilities/prompts/identity.js +6 -0
  70. package/dist/capabilities/prompts/team.d.ts +4 -0
  71. package/dist/capabilities/prompts/team.js +4 -0
  72. package/dist/capabilities/repo-tools.d.ts +11 -0
  73. package/dist/capabilities/repo-tools.js +8 -0
  74. package/dist/capabilities/sandbox-file-send.d.ts +95 -0
  75. package/dist/capabilities/sandbox-file-send.js +91 -3
  76. package/dist/capabilities/scenarios.d.ts +130 -0
  77. package/dist/capabilities/scenarios.js +180 -7
  78. package/dist/capabilities/select-environment-tool.d.ts +7 -0
  79. package/dist/capabilities/select-environment-tool.js +30 -0
  80. package/dist/capabilities/send-user-file-tool.d.ts +33 -0
  81. package/dist/capabilities/send-user-file-tool.js +65 -1
  82. package/dist/capabilities/skills.d.ts +29 -0
  83. package/dist/capabilities/skills.js +13 -2
  84. package/dist/capabilities/team.d.ts +22 -0
  85. package/dist/capabilities/team.js +22 -2
  86. package/dist/capabilities/tool-defer.d.ts +26 -0
  87. package/dist/capabilities/tool-defer.js +3 -0
  88. package/dist/config-center/apply-effective.d.ts +65 -0
  89. package/dist/config-center/apply-effective.js +204 -12
  90. package/dist/config-center/http-client.d.ts +34 -0
  91. package/dist/config-center/http-client.js +68 -0
  92. package/dist/config-center/restart-signal.d.ts +22 -0
  93. package/dist/config-center/restart-signal.js +39 -0
  94. package/dist/config-center/skills-mcp.d.ts +20 -1
  95. package/dist/config-center/skills-mcp.js +42 -7
  96. package/dist/config-center/types.d.ts +92 -1
  97. package/dist/config-lkg.d.ts +12 -0
  98. package/dist/config-lkg.js +41 -0
  99. package/dist/config-provider.d.ts +78 -0
  100. package/dist/config-provider.js +165 -2
  101. package/dist/config-types.d.ts +546 -0
  102. package/dist/config.d.ts +64 -0
  103. package/dist/config.js +455 -60
  104. package/dist/degenerate-instrument.d.ts +38 -0
  105. package/dist/degenerate-instrument.js +55 -3
  106. package/dist/elicitation.d.ts +39 -0
  107. package/dist/elicitation.js +87 -3
  108. package/dist/env-facts.d.ts +61 -0
  109. package/dist/env-facts.js +73 -7
  110. package/dist/fleet/fleet-bus.d.ts +185 -0
  111. package/dist/fleet/fleet-bus.js +333 -27
  112. package/dist/fleet/subagent-tail-bus.d.ts +11 -0
  113. package/dist/fleet/subagent-tail-bus.js +33 -2
  114. package/dist/fleet-client.d.ts +38 -0
  115. package/dist/fleet-client.js +44 -9
  116. package/dist/fleet-lease.d.ts +46 -0
  117. package/dist/fleet-lease.js +73 -5
  118. package/dist/hooks/branch-transcript.d.ts +8 -0
  119. package/dist/hooks/branch-transcript.js +33 -0
  120. package/dist/hooks/cc-stop-prompt.d.ts +42 -0
  121. package/dist/hooks/cc-stop-prompt.js +43 -1
  122. package/dist/hooks/hook-llm.d.ts +15 -0
  123. package/dist/hooks/hook-llm.js +47 -0
  124. package/dist/hooks/hook-runner.d.ts +89 -0
  125. package/dist/hooks/hook-runner.js +327 -18
  126. package/dist/http/idempotency.d.ts +31 -0
  127. package/dist/http/idempotency.js +34 -0
  128. package/dist/http/principal-gate.d.ts +17 -0
  129. package/dist/http/principal-gate.js +35 -3
  130. package/dist/http/route-ctx.d.ts +36 -0
  131. package/dist/http/routes/approvals-assistant.d.ts +25 -0
  132. package/dist/http/routes/approvals-assistant.js +253 -23
  133. package/dist/http/routes/attachments.js +22 -4
  134. package/dist/http/routes/capabilities.d.ts +7 -0
  135. package/dist/http/routes/capabilities.js +202 -1
  136. package/dist/http/routes/fleet.d.ts +6 -0
  137. package/dist/http/routes/fleet.js +94 -5
  138. package/dist/http/routes/images.d.ts +17 -0
  139. package/dist/http/routes/images.js +222 -14
  140. package/dist/http/routes/leader.d.ts +7 -0
  141. package/dist/http/routes/leader.js +10 -0
  142. package/dist/http/routes/memory-policy.d.ts +6 -0
  143. package/dist/http/routes/memory-policy.js +38 -6
  144. package/dist/http/routes/notify-wake.d.ts +10 -0
  145. package/dist/http/routes/notify-wake.js +19 -3
  146. package/dist/http/routes/observability.d.ts +6 -0
  147. package/dist/http/routes/observability.js +19 -2
  148. package/dist/http/routes/runs.d.ts +15 -0
  149. package/dist/http/routes/runs.js +464 -41
  150. package/dist/http/routes/session-sync.d.ts +15 -0
  151. package/dist/http/routes/session-sync.js +229 -19
  152. package/dist/http/routes/sessions-list.d.ts +6 -0
  153. package/dist/http/routes/sessions-list.js +35 -4
  154. package/dist/http/routes/sessions.d.ts +14 -0
  155. package/dist/http/routes/sessions.js +176 -31
  156. package/dist/http/routes/side-query.d.ts +8 -0
  157. package/dist/http/routes/side-query.js +26 -1
  158. package/dist/http/routes/tasks.d.ts +18 -0
  159. package/dist/http/routes/tasks.js +501 -38
  160. package/dist/http/routes/trace-usage.d.ts +10 -0
  161. package/dist/http/routes/trace-usage.js +66 -14
  162. package/dist/http/routes/workflows.d.ts +12 -0
  163. package/dist/http/routes/workflows.js +180 -19
  164. package/dist/http/run-meta.d.ts +11 -0
  165. package/dist/http/run-meta.js +6 -0
  166. package/dist/http/send.d.ts +19 -0
  167. package/dist/http/send.js +11 -0
  168. package/dist/http/server.d.ts +255 -0
  169. package/dist/http/server.js +921 -75
  170. package/dist/http/sse-log.d.ts +15 -0
  171. package/dist/http/sse-log.js +16 -0
  172. package/dist/http/tar.d.ts +9 -0
  173. package/dist/http/tar.js +21 -5
  174. package/dist/http/wire-gate.d.ts +9 -0
  175. package/dist/http/wire-gate.js +9 -0
  176. package/dist/http/wire-types.d.ts +187 -0
  177. package/dist/http/workspace-content.d.ts +8 -0
  178. package/dist/http/workspace-content.js +10 -0
  179. package/dist/images/bake-validate.d.ts +63 -0
  180. package/dist/images/bake-validate.js +71 -1
  181. package/dist/images/manifest.d.ts +19 -0
  182. package/dist/images/manifest.js +6 -1
  183. package/dist/index.d.ts +1 -5
  184. package/dist/index.js +10 -5
  185. package/dist/key-resolver.d.ts +23 -0
  186. package/dist/key-resolver.js +27 -2
  187. package/dist/leader/diffout.d.ts +23 -0
  188. package/dist/leader/diffout.js +8 -1
  189. package/dist/leader/diffup.d.ts +32 -0
  190. package/dist/leader/diffup.js +43 -0
  191. package/dist/leader/endpoint.d.ts +20 -0
  192. package/dist/leader/endpoint.js +25 -2
  193. package/dist/leader/fanout.d.ts +60 -0
  194. package/dist/leader/fanout.js +29 -3
  195. package/dist/leader/grader-env-factory.d.ts +74 -0
  196. package/dist/leader/grader-env-factory.js +62 -3
  197. package/dist/leader/leader.d.ts +97 -0
  198. package/dist/leader/leader.js +151 -4
  199. package/dist/leader/merge.d.ts +94 -0
  200. package/dist/leader/merge.js +112 -9
  201. package/dist/leader/planner.d.ts +52 -0
  202. package/dist/leader/planner.js +47 -3
  203. package/dist/leader/repair-oracle.d.ts +61 -0
  204. package/dist/leader/repair-oracle.js +59 -1
  205. package/dist/leader/repair-wire.d.ts +78 -0
  206. package/dist/leader/repair-wire.js +79 -2
  207. package/dist/leader/wire.d.ts +79 -0
  208. package/dist/leader/wire.js +255 -8
  209. package/dist/lsp/e2b-bridge.d.ts +16 -0
  210. package/dist/lsp/e2b-bridge.js +32 -4
  211. package/dist/lsp/e2b-manager.d.ts +10 -0
  212. package/dist/lsp/e2b-manager.js +18 -2
  213. package/dist/lsp/lsp-frames.d.ts +12 -0
  214. package/dist/lsp/lsp-frames.js +12 -0
  215. package/dist/lsp/manager.d.ts +12 -0
  216. package/dist/lsp/manager.js +35 -2
  217. package/dist/lsp/types.d.ts +10 -0
  218. package/dist/lsp/ws-transport.d.ts +12 -0
  219. package/dist/lsp/ws-transport.js +53 -5
  220. package/dist/lsp-evict.d.ts +14 -0
  221. package/dist/lsp-evict.js +15 -1
  222. package/dist/main.js +2132 -96
  223. package/dist/memory-export.d.ts +1 -0
  224. package/dist/memory-export.js +4 -0
  225. package/dist/memory-scope.d.ts +49 -0
  226. package/dist/memory-scope.js +87 -4
  227. package/dist/memory-sync-client.d.ts +24 -0
  228. package/dist/memory-sync-client.js +41 -2
  229. package/dist/memory-sync.d.ts +23 -0
  230. package/dist/memory-sync.js +70 -1
  231. package/dist/model-select.d.ts +39 -0
  232. package/dist/model-select.js +42 -1
  233. package/dist/observability/cost-quota.d.ts +20 -0
  234. package/dist/observability/cost-quota.js +4 -0
  235. package/dist/observability/cost-taxonomy.d.ts +45 -0
  236. package/dist/observability/cost-taxonomy.js +34 -0
  237. package/dist/observability/logger.d.ts +1 -0
  238. package/dist/observability/logger.js +6 -0
  239. package/dist/observability/metrics.d.ts +13 -0
  240. package/dist/observability/metrics.js +63 -0
  241. package/dist/observability/otel-exporter.d.ts +9 -0
  242. package/dist/observability/otel-exporter.js +11 -3
  243. package/dist/observability/principal-context.d.ts +9 -0
  244. package/dist/observability/principal-context.js +9 -0
  245. package/dist/observability/prompt-manifest.d.ts +37 -0
  246. package/dist/observability/prompt-manifest.js +35 -1
  247. package/dist/observability/rate-limit.d.ts +10 -0
  248. package/dist/observability/rate-limit.js +1 -0
  249. package/dist/observability/tool-trace.d.ts +24 -0
  250. package/dist/observability/tool-trace.js +41 -1
  251. package/dist/orchestration/hardened-vm-runner.d.ts +107 -0
  252. package/dist/orchestration/hardened-vm-runner.js +119 -4
  253. package/dist/orchestration/hardened-vm-worker-runner.d.ts +14 -0
  254. package/dist/orchestration/hardened-vm-worker-runner.js +26 -1
  255. package/dist/orchestration/hardened-vm-worker.js +27 -0
  256. package/dist/orchestration/subagent-steer.d.ts +44 -0
  257. package/dist/orchestration/subagent-steer.js +45 -1
  258. package/dist/orchestration/workflow-agent-steer.d.ts +54 -0
  259. package/dist/orchestration/workflow-agent-steer.js +80 -1
  260. package/dist/orchestration/workflow-completion-inbox.d.ts +189 -2
  261. package/dist/orchestration/workflow-completion-inbox.js +283 -32
  262. package/dist/orchestration/workflow-notify-journal.d.ts +132 -1
  263. package/dist/orchestration/workflow-notify-journal.js +187 -13
  264. package/dist/parked-decide.d.ts +61 -0
  265. package/dist/parked-decide.js +58 -1
  266. package/dist/per-task-image.d.ts +54 -0
  267. package/dist/per-task-image.js +41 -0
  268. package/dist/plan-cache-probe.d.ts +35 -0
  269. package/dist/plan-cache-probe.js +18 -3
  270. package/dist/plugins/approval-exemption-store.d.ts +7 -0
  271. package/dist/plugins/approval-exemption-store.js +28 -2
  272. package/dist/plugins/approval-store-sql.d.ts +64 -0
  273. package/dist/plugins/approval-store-sql.js +32 -0
  274. package/dist/plugins/background-agent-store-sql.d.ts +55 -0
  275. package/dist/plugins/background-agent-store-sql.js +91 -4
  276. package/dist/plugins/background-shell-support.d.ts +98 -0
  277. package/dist/plugins/background-shell-support.js +117 -13
  278. package/dist/plugins/blob-backend.d.ts +104 -0
  279. package/dist/plugins/blob-backend.js +163 -6
  280. package/dist/plugins/breaker-state-sql.d.ts +65 -1
  281. package/dist/plugins/breaker-state-sql.js +46 -8
  282. package/dist/plugins/caching-session-store.d.ts +42 -0
  283. package/dist/plugins/caching-session-store.js +63 -3
  284. package/dist/plugins/checkpoint-store-sql.d.ts +179 -0
  285. package/dist/plugins/checkpoint-store-sql.js +239 -11
  286. package/dist/plugins/file-outcome-sink.d.ts +4 -0
  287. package/dist/plugins/file-outcome-sink.js +9 -0
  288. package/dist/plugins/file-resume-anchor-store.d.ts +20 -0
  289. package/dist/plugins/file-resume-anchor-store.js +43 -4
  290. package/dist/plugins/file-run-store.d.ts +90 -0
  291. package/dist/plugins/file-run-store.js +145 -13
  292. package/dist/plugins/file-snapshot-store-sql.d.ts +133 -1
  293. package/dist/plugins/file-snapshot-store-sql.js +178 -10
  294. package/dist/plugins/file-workflow-journal-store.d.ts +10 -0
  295. package/dist/plugins/file-workflow-journal-store.js +10 -0
  296. package/dist/plugins/fork-routing-session-store.d.ts +47 -0
  297. package/dist/plugins/fork-routing-session-store.js +51 -3
  298. package/dist/plugins/host-platform.d.ts +69 -0
  299. package/dist/plugins/host-platform.js +81 -2
  300. package/dist/plugins/image-bake-store-sql.d.ts +136 -1
  301. package/dist/plugins/image-bake-store-sql.js +241 -7
  302. package/dist/plugins/image-index-sql.d.ts +46 -0
  303. package/dist/plugins/image-index-sql.js +113 -4
  304. package/dist/plugins/k8s-bg-scripts.d.ts +34 -0
  305. package/dist/plugins/k8s-bg-scripts.js +88 -4
  306. package/dist/plugins/k8s-exec-protocol.d.ts +33 -0
  307. package/dist/plugins/k8s-exec-protocol.js +41 -0
  308. package/dist/plugins/local-checkpoint-store.d.ts +40 -0
  309. package/dist/plugins/local-checkpoint-store.js +86 -7
  310. package/dist/plugins/local-session-store.d.ts +157 -0
  311. package/dist/plugins/local-session-store.js +289 -34
  312. package/dist/plugins/local-task-attachment-store.js +14 -2
  313. package/dist/plugins/mailbox-store-sql.d.ts +38 -0
  314. package/dist/plugins/mailbox-store-sql.js +39 -6
  315. package/dist/plugins/memory-engine-pg.d.ts +30 -0
  316. package/dist/plugins/memory-engine-pg.js +122 -4
  317. package/dist/plugins/memory-engine-tidb.d.ts +26 -0
  318. package/dist/plugins/memory-engine-tidb.js +115 -5
  319. package/dist/plugins/memory-engine-vector-util.d.ts +5 -0
  320. package/dist/plugins/memory-engine-vector-util.js +5 -0
  321. package/dist/plugins/memory-resume-anchor-store.d.ts +8 -0
  322. package/dist/plugins/memory-resume-anchor-store.js +17 -0
  323. package/dist/plugins/memory-run-store.d.ts +63 -0
  324. package/dist/plugins/memory-run-store.js +73 -8
  325. package/dist/plugins/memory-session-policy-store.d.ts +17 -0
  326. package/dist/plugins/memory-session-policy-store.js +17 -0
  327. package/dist/plugins/memory-sync-store-pg.d.ts +42 -0
  328. package/dist/plugins/memory-sync-store-pg.js +45 -2
  329. package/dist/plugins/memory-sync-store-tidb.d.ts +9 -0
  330. package/dist/plugins/memory-sync-store-tidb.js +31 -1
  331. package/dist/plugins/outcome-ledger-sql.d.ts +63 -0
  332. package/dist/plugins/outcome-ledger-sql.js +97 -3
  333. package/dist/plugins/pg-approval-store.d.ts +7 -0
  334. package/dist/plugins/pg-approval-store.js +7 -0
  335. package/dist/plugins/pg-breaker-state.d.ts +6 -0
  336. package/dist/plugins/pg-breaker-state.js +6 -0
  337. package/dist/plugins/pg-checkpoint-store.d.ts +8 -0
  338. package/dist/plugins/pg-checkpoint-store.js +8 -0
  339. package/dist/plugins/pg-cost-quota.d.ts +17 -0
  340. package/dist/plugins/pg-cost-quota.js +6 -0
  341. package/dist/plugins/pg-file-snapshot-store.d.ts +6 -0
  342. package/dist/plugins/pg-file-snapshot-store.js +6 -0
  343. package/dist/plugins/pg-image-bake.d.ts +9 -0
  344. package/dist/plugins/pg-image-bake.js +9 -0
  345. package/dist/plugins/pg-image-index.d.ts +9 -0
  346. package/dist/plugins/pg-image-index.js +9 -0
  347. package/dist/plugins/pg-outcome-ledger.d.ts +9 -0
  348. package/dist/plugins/pg-outcome-ledger.js +9 -0
  349. package/dist/plugins/pg-pool.d.ts +50 -0
  350. package/dist/plugins/pg-pool.js +78 -0
  351. package/dist/plugins/pg-query.d.ts +11 -0
  352. package/dist/plugins/pg-rate-limiter.d.ts +23 -0
  353. package/dist/plugins/pg-rate-limiter.js +12 -2
  354. package/dist/plugins/pg-resume-anchor-store.d.ts +5 -0
  355. package/dist/plugins/pg-resume-anchor-store.js +5 -0
  356. package/dist/plugins/pg-run-store.d.ts +7 -0
  357. package/dist/plugins/pg-run-store.js +7 -0
  358. package/dist/plugins/pg-safe-json.d.ts +13 -0
  359. package/dist/plugins/pg-safe-json.js +40 -4
  360. package/dist/plugins/pg-session-policy-store.d.ts +5 -0
  361. package/dist/plugins/pg-session-policy-store.js +5 -0
  362. package/dist/plugins/pg-session-storage.d.ts +72 -0
  363. package/dist/plugins/pg-session-storage.js +152 -20
  364. package/dist/plugins/pg-session-store.d.ts +10 -0
  365. package/dist/plugins/pg-session-store.js +10 -0
  366. package/dist/plugins/pg-tool-result-store.d.ts +7 -0
  367. package/dist/plugins/pg-tool-result-store.js +7 -0
  368. package/dist/plugins/pg-workflow-journal-store.d.ts +7 -0
  369. package/dist/plugins/pg-workflow-journal-store.js +7 -0
  370. package/dist/plugins/pg-workflow-run-store.d.ts +7 -0
  371. package/dist/plugins/pg-workflow-run-store.js +7 -0
  372. package/dist/plugins/posix-shell-fs.d.ts +3 -0
  373. package/dist/plugins/posix-shell-fs.js +31 -1
  374. package/dist/plugins/remote-env-adb.d.ts +25 -0
  375. package/dist/plugins/remote-env-adb.js +95 -12
  376. package/dist/plugins/remote-env-e2b.d.ts +146 -0
  377. package/dist/plugins/remote-env-e2b.js +371 -40
  378. package/dist/plugins/remote-env-file-error.d.ts +34 -0
  379. package/dist/plugins/remote-env-file-error.js +37 -0
  380. package/dist/plugins/remote-env-host.d.ts +151 -0
  381. package/dist/plugins/remote-env-host.js +468 -70
  382. package/dist/plugins/remote-env-k8s.d.ts +135 -0
  383. package/dist/plugins/remote-env-k8s.js +318 -32
  384. package/dist/plugins/remote-env-local-docker.d.ts +65 -0
  385. package/dist/plugins/remote-env-local-docker.js +149 -24
  386. package/dist/plugins/remote-env-ssh.d.ts +35 -0
  387. package/dist/plugins/remote-env-ssh.js +117 -20
  388. package/dist/plugins/remote-scratchpad.d.ts +38 -0
  389. package/dist/plugins/remote-scratchpad.js +32 -2
  390. package/dist/plugins/remote-shell.d.ts +22 -0
  391. package/dist/plugins/remote-shell.js +27 -1
  392. package/dist/plugins/resume-anchor-store-sql.d.ts +28 -0
  393. package/dist/plugins/resume-anchor-store-sql.js +11 -0
  394. package/dist/plugins/roster-store-sql.d.ts +27 -0
  395. package/dist/plugins/roster-store-sql.js +54 -0
  396. package/dist/plugins/run-store-sql.d.ts +194 -0
  397. package/dist/plugins/run-store-sql.js +210 -9
  398. package/dist/plugins/s3-presign.d.ts +20 -0
  399. package/dist/plugins/s3-presign.js +49 -2
  400. package/dist/plugins/scheduler-support.d.ts +12 -0
  401. package/dist/plugins/scheduler-support.js +75 -3
  402. package/dist/plugins/send-file-ledger.d.ts +15 -0
  403. package/dist/plugins/send-file-ledger.js +53 -4
  404. package/dist/plugins/send-user-file.d.ts +77 -0
  405. package/dist/plugins/send-user-file.js +92 -4
  406. package/dist/plugins/session-policy-store-sql.d.ts +15 -0
  407. package/dist/plugins/session-policy-store-sql.js +75 -3
  408. package/dist/plugins/session-store.d.ts +45 -0
  409. package/dist/plugins/session-store.js +51 -0
  410. package/dist/plugins/sql-driver.d.ts +77 -0
  411. package/dist/plugins/sql-driver.js +4 -0
  412. package/dist/plugins/sql-escape.d.ts +8 -0
  413. package/dist/plugins/sql-escape.js +8 -0
  414. package/dist/plugins/sql-row-helpers.d.ts +25 -0
  415. package/dist/plugins/sql-row-helpers.js +25 -0
  416. package/dist/plugins/store-backend.d.ts +103 -0
  417. package/dist/plugins/store-backend.js +120 -27
  418. package/dist/plugins/store-contracts.d.ts +62 -0
  419. package/dist/plugins/store-contracts.js +3 -0
  420. package/dist/plugins/task-attachment-store.d.ts +60 -0
  421. package/dist/plugins/task-attachment-store.js +49 -3
  422. package/dist/plugins/task-list-store-sql.d.ts +25 -0
  423. package/dist/plugins/task-list-store-sql.js +21 -0
  424. package/dist/plugins/tidb-approval-store.d.ts +6 -0
  425. package/dist/plugins/tidb-approval-store.js +6 -0
  426. package/dist/plugins/tidb-breaker-state.d.ts +5 -0
  427. package/dist/plugins/tidb-breaker-state.js +5 -0
  428. package/dist/plugins/tidb-checkpoint-store.d.ts +7 -0
  429. package/dist/plugins/tidb-checkpoint-store.js +7 -0
  430. package/dist/plugins/tidb-cost-quota.d.ts +6 -0
  431. package/dist/plugins/tidb-cost-quota.js +1 -0
  432. package/dist/plugins/tidb-file-snapshot-store.d.ts +6 -0
  433. package/dist/plugins/tidb-file-snapshot-store.js +6 -0
  434. package/dist/plugins/tidb-image-bake.d.ts +8 -0
  435. package/dist/plugins/tidb-image-bake.js +8 -0
  436. package/dist/plugins/tidb-image-index.d.ts +8 -0
  437. package/dist/plugins/tidb-image-index.js +8 -0
  438. package/dist/plugins/tidb-outcome-ledger.d.ts +10 -0
  439. package/dist/plugins/tidb-outcome-ledger.js +10 -0
  440. package/dist/plugins/tidb-pool.d.ts +56 -0
  441. package/dist/plugins/tidb-pool.js +181 -1
  442. package/dist/plugins/tidb-rate-limiter.d.ts +11 -0
  443. package/dist/plugins/tidb-rate-limiter.js +5 -2
  444. package/dist/plugins/tidb-resume-anchor-store.d.ts +5 -0
  445. package/dist/plugins/tidb-resume-anchor-store.js +5 -0
  446. package/dist/plugins/tidb-run-store.d.ts +7 -0
  447. package/dist/plugins/tidb-run-store.js +7 -0
  448. package/dist/plugins/tidb-session-policy-store.d.ts +5 -0
  449. package/dist/plugins/tidb-session-policy-store.js +5 -0
  450. package/dist/plugins/tidb-session-storage.d.ts +43 -0
  451. package/dist/plugins/tidb-session-storage.js +62 -3
  452. package/dist/plugins/tidb-session-store.d.ts +142 -0
  453. package/dist/plugins/tidb-session-store.js +264 -16
  454. package/dist/plugins/tidb-tool-result-store.d.ts +5 -0
  455. package/dist/plugins/tidb-tool-result-store.js +7 -0
  456. package/dist/plugins/tidb-workflow-journal-store.d.ts +7 -0
  457. package/dist/plugins/tidb-workflow-journal-store.js +7 -0
  458. package/dist/plugins/tidb-workflow-run-store.d.ts +8 -0
  459. package/dist/plugins/tidb-workflow-run-store.js +8 -0
  460. package/dist/plugins/tool-result-store-sql.d.ts +58 -0
  461. package/dist/plugins/tool-result-store-sql.js +38 -2
  462. package/dist/plugins/web-search.d.ts +35 -0
  463. package/dist/plugins/web-search.js +45 -9
  464. package/dist/plugins/workflow-journal-limits.d.ts +10 -0
  465. package/dist/plugins/workflow-journal-limits.js +10 -0
  466. package/dist/plugins/workflow-journal-store-sql.d.ts +78 -0
  467. package/dist/plugins/workflow-journal-store-sql.js +59 -3
  468. package/dist/plugins/workflow-run-store-sql.d.ts +84 -0
  469. package/dist/plugins/workflow-run-store-sql.js +84 -6
  470. package/dist/plugins/worktree-isolation.d.ts +45 -0
  471. package/dist/plugins/worktree-isolation.js +105 -6
  472. package/dist/plugins/write-behind-counter.d.ts +56 -1
  473. package/dist/plugins/write-behind-counter.js +53 -14
  474. package/dist/principal-jwt.d.ts +24 -0
  475. package/dist/principal-jwt.js +60 -5
  476. package/dist/project-memory.d.ts +22 -0
  477. package/dist/project-memory.js +144 -15
  478. package/dist/prompts-domain-validate.d.ts +28 -0
  479. package/dist/prompts-domain-validate.js +42 -1
  480. package/dist/question.d.ts +33 -0
  481. package/dist/question.js +69 -2
  482. package/dist/resource-suspend.d.ts +21 -0
  483. package/dist/resource-suspend.js +16 -0
  484. package/dist/router/route-orchestration.d.ts +78 -0
  485. package/dist/router/route-orchestration.js +77 -0
  486. package/dist/run-local.d.ts +32 -0
  487. package/dist/run-local.js +172 -8
  488. package/dist/runs.d.ts +189 -4
  489. package/dist/runs.js +465 -24
  490. package/dist/runtime-caps-resolver.d.ts +106 -0
  491. package/dist/runtime-caps-resolver.js +89 -4
  492. package/dist/runtime-governance.d.ts +84 -0
  493. package/dist/runtime-governance.js +127 -1
  494. package/dist/sandbox-pkg-source.d.ts +23 -0
  495. package/dist/sandbox-pkg-source.js +37 -0
  496. package/dist/sealed-key.d.ts +54 -0
  497. package/dist/sealed-key.js +68 -3
  498. package/dist/security.d.ts +108 -0
  499. package/dist/security.js +145 -6
  500. package/dist/sema-registry.d.ts +21 -0
  501. package/dist/sema-registry.js +21 -0
  502. package/dist/session-leaf-bus.d.ts +31 -0
  503. package/dist/session-leaf-bus.js +32 -0
  504. package/dist/session-sync-content.d.ts +46 -0
  505. package/dist/session-sync-content.js +47 -1
  506. package/dist/session-sync-kernel.d.ts +89 -0
  507. package/dist/session-sync-kernel.js +48 -3
  508. package/dist/session-sync.d.ts +125 -0
  509. package/dist/session-sync.js +181 -8
  510. package/dist/session-titler.d.ts +26 -0
  511. package/dist/session-titler.js +41 -7
  512. package/dist/session-watch.d.ts +53 -1
  513. package/dist/session-watch.js +73 -9
  514. package/dist/sighup-idle.d.ts +30 -0
  515. package/dist/sighup-idle.js +12 -1
  516. package/dist/spec-fields.d.ts +91 -3
  517. package/dist/spec-fields.js +116 -4
  518. package/dist/task-cwd.d.ts +50 -0
  519. package/dist/task-cwd.js +68 -1
  520. package/dist/task-mcp.d.ts +47 -0
  521. package/dist/task-mcp.js +29 -0
  522. package/dist/task-settings.d.ts +175 -0
  523. package/dist/task-settings.js +226 -11
  524. package/dist/task-workflow.d.ts +67 -0
  525. package/dist/task-workflow.js +75 -8
  526. package/dist/tool-approval.d.ts +91 -0
  527. package/dist/tool-approval.js +215 -0
  528. package/dist/trace/artifacts.d.ts +9 -0
  529. package/dist/trace/artifacts.js +30 -5
  530. package/dist/trace/core-keyset-guard.d.ts +18 -0
  531. package/dist/trace/ledger-sink.d.ts +43 -0
  532. package/dist/trace/ledger-sink.js +64 -5
  533. package/dist/trace/project.d.ts +133 -0
  534. package/dist/trace/project.js +189 -2
  535. package/dist/trace/redact.d.ts +19 -0
  536. package/dist/trace/redact.js +66 -9
  537. package/dist/usage-analytics.d.ts +26 -0
  538. package/dist/usage-analytics.js +26 -3
  539. package/package.json +1 -1
@@ -1,12 +1,39 @@
1
+ // ⚠️ ORIGIN: @sema-agent/core 1.267.0 `src/core/memory-engine/pg-backend.ts`(core commit 3071dd3)——
2
+ // 边界重切整段移交:core 从此只养 File backend+MemoryBackend seam+memoryBackendContract
3
+ // 契约套件;Pg/TiDB 方言实现归 service(数据面方言=deployment 半场,TiDBRunStore/PgRunStore 先例)。
4
+ // 移交纪律:保留此头注双向可追;core 下版撤 PgMemoryEngineBackend 公开导出。
5
+ // 改动 vs origin:import 面重指(types/frontmatter 从 @sema-agent/core 公开面;memory-vector 三函数+
6
+ // isUniqueViolation 内联于 memory-engine-vector-util.ts(core 1.424 示例适配器退包面后回归内联,勿再切 re-export)。
7
+ // design/138 S3-core — PgMemoryEngineBackend: the SECOND MemoryBackend implementation (TOB/multi-tenant
8
+ // authority disk), proving the S1 entry-transactional seam holds off the file plane. Same contract as
9
+ // FileMemoryEngineBackend; radically simpler internals, because Postgres retires the file backend's
10
+ // control-plane machinery instead of porting it (S3 拍板, design/138 §S3-core):
11
+ // - committed-rev ledger → the row's `rev` column IS the committed rev (no zero-copy problem: the
12
+ // model edits file PROJECTIONS, never DB rows, so "read current rev" cannot self-conflict);
13
+ // - redo journal → per-statement conditional writes (`UPDATE … WHERE rev = $expected
14
+ // RETURNING`, the pg.ts checkpoint OCC template) — the DB's atomicity replaces staging/journaling;
15
+ // - shadow/ quarantine/ → dropped: a DB row cannot go "missing" outside an explicit delete patch,
16
+ // so the "缺失≠删除" recovery axis has no Pg counterpart; inbound writes are engine-only (a
17
+ // deployment sharing the tables with other writers owns validation — same posture as stores/pg.ts);
18
+ // - scope registry → dropped: `scope` is a plain column; tenant keying is the deployment's.
19
+ // Vector rungs (design/81, re-mounted here per §4): lexical (jaccard, byte-equal to FileBackend) →
20
+ // portable (jsonb vectors, in-process cosine) → native (pgvector `<=>` SQL). All three share the
21
+ // cosine-distance contract score ∈ [0,2] — upgrading recall is a config change, not a recalibration.
1
22
  import { cosineDistance, jaccardDistance, termSet, isUniqueViolation } from "./memory-engine-vector-util.js";
2
23
  import { computeEntryRev, serializeEntryFile } from "@sema-agent/core";
3
24
  import { pgSafeJsonStringify, pgHasUnstorable } from "./pg-safe-json.js";
25
+ /** Table names (single source). Deliberately DISJOINT from the legacy `agent_memory*` tables —
26
+ * the retired MemoryStore plane and this entry plane must never cross-write. */
4
27
  export const PG_MEMORY_ENGINE_TABLES = {
5
28
  entries: "agent_memory_engine_entries",
6
29
  cursors: "agent_memory_engine_cursors",
7
30
  };
31
+ /** Idempotent DDL for the entry plane. Call once at startup (or run through your migration tool). */
8
32
  export async function ensurePgMemoryEngineSchema(query, opts = {}) {
9
33
  const vec = opts.memoryVector;
34
+ // dimensions must be a finite positive integer — NaN/Infinity would interpolate
35
+ // invalid DDL (`vector(NaN)`), and a silent fractional truncation could disagree with the embedder's
36
+ // declared dimensions. Boot-time config error ⇒ throw loudly, never emit broken DDL.
10
37
  if (vec !== undefined && (!Number.isInteger(vec.dimensions) || vec.dimensions < 1)) {
11
38
  throw new Error(`ensurePgMemoryEngineSchema: memoryVector.dimensions must be a positive integer (got ${String(vec.dimensions)})`);
12
39
  }
@@ -28,16 +55,27 @@ export async function ensurePgMemoryEngineSchema(query, opts = {}) {
28
55
  await query(`CREATE INDEX IF NOT EXISTS ${PG_MEMORY_ENGINE_TABLES.entries}_scope_idx ON ${PG_MEMORY_ENGINE_TABLES.entries} (scope)`);
29
56
  }
30
57
  catch {
58
+ /* pg-mem: partial CREATE INDEX support — the index is a perf add-on, never correctness */
31
59
  }
60
+ // The (scope, slug) UNIQUE constraint is CORRECTNESS, not perf — two
61
+ // instances racing an add of the same scope+slug (different ids) could both probe "free" and both
62
+ // insert, leaving two entries whose file projections overwrite each other at materialize. The DB
63
+ // constraint is the only true arbiter; the add path catches the violation and retries the next
64
+ // suffix. NOT wrapped in try/catch — if this constraint cannot be created, the backend is unsafe.
32
65
  await query(`CREATE UNIQUE INDEX IF NOT EXISTS ${PG_MEMORY_ENGINE_TABLES.entries}_scope_slug_uq ON ${PG_MEMORY_ENGINE_TABLES.entries} (scope, slug)`);
33
66
  await query(`CREATE TABLE IF NOT EXISTS ${PG_MEMORY_ENGINE_TABLES.cursors} (
34
67
  scope text PRIMARY KEY,
35
68
  cursor text NOT NULL
36
69
  )`);
37
70
  }
71
+ /** pgvector input literal — the same `[…]` string JSON.parse reads back from jsonb (one format, two columns). */
38
72
  function vectorLiteral(v) {
39
73
  return `[${v.join(",")}]`;
40
74
  }
75
+ /** `$k, $k+1, …` for a dynamic IN list. Used instead of `= ANY($1)` — pg-mem (the offline test rig)
76
+ * silently returns ZERO rows for `ANY(param)` on an INDEXED column (index-path bug, verified
77
+ * 2026-07-11: unindexed ANY works, indexed ANY is empty, indexed `=` works). IN-lists are plain SQL
78
+ * on both engines, so the production path never bends toward the emulator. */
41
79
  function inPlaceholders(first, count) {
42
80
  return Array.from({ length: count }, (_, i) => `$${first + i}`).join(", ");
43
81
  }
@@ -50,7 +88,9 @@ export class PgMemoryEngineBackend {
50
88
  pgvectorSql;
51
89
  clock;
52
90
  history;
91
+ /** Cumulative lost-row count — audit-line breakage must itself be auditable. */
53
92
  historyRowsLost = 0;
93
+ /** design/81 rung indicator — same semantics as PgMemoryStore.vectorMode. */
54
94
  get vectorMode() {
55
95
  return this.pgvectorSql ? "native" : this.embedder ? "portable" : "lexical";
56
96
  }
@@ -63,9 +103,12 @@ export class PgMemoryEngineBackend {
63
103
  if (this.pgvectorSql && !this.embedder)
64
104
  throw new Error("PgMemoryEngineBackend: pgvectorSql requires an embedder");
65
105
  }
106
+ /** The embed/search haystack — BYTE-EQUAL to FileBackend's lexical haystack (file-backend search). */
66
107
  haystackOf(slug, fm, body) {
67
108
  return `${fm.name ?? slug} ${fm.description ?? ""} ${body}`;
68
109
  }
110
+ /** Dimension-guarded embedding parameter (mirrors PgMemoryStore.embeddingParam — wrong-length ⇒ null,
111
+ * the row falls open to the lexical stand-in instead of poisoning reads). */
69
112
  async embeddingParam(text) {
70
113
  if (!this.embedder)
71
114
  return null;
@@ -99,6 +142,9 @@ export class PgMemoryEngineBackend {
99
142
  };
100
143
  }
101
144
  async listHeaders(scopes) {
145
+ // Dedupe (all three read paths): a repeated key must not repeat rows — real Postgres IN-lists
146
+ // don't, but pg-mem duplicates matches per repeated placeholder value; dedupe is also the honest
147
+ // semantic (a caller repeating an id asks about ONE entry).
102
148
  const uniq = [...new Set(scopes)];
103
149
  if (uniq.length === 0)
104
150
  return [];
@@ -110,16 +156,24 @@ export class PgMemoryEngineBackend {
110
156
  if (uniq.length === 0)
111
157
  return [];
112
158
  const res = await this.query(`SELECT id, scope, slug, frontmatter, body, rev, mtime_ms, size_bytes FROM ${PG_MEMORY_ENGINE_TABLES.entries} WHERE id IN (${inPlaceholders(1, uniq.length)}) ORDER BY id`, uniq);
113
- return res.rows.map((r) => this.entryFromRow(r));
159
+ return res.rows.map((r) => this.entryFromRow(r)); // unknown ids: silently absent
114
160
  }
115
161
  async search(query, scopes, opts) {
162
+ // Normalize the limit ONCE for all three rungs — `Math.floor`
163
+ // makes a fractional limit (0.5) behave like File's `slice` (→ 0 → empty), `!(lim > 0)` also
164
+ // rejects NaN (NaN > 0 is false — it previously reached the native rung's interpolated LIMIT as
165
+ // a SQL syntax error). Infinity stays legal ("no cap") and is clamped before interpolation.
116
166
  const rawLimit = opts?.limit ?? 20;
117
167
  const limit = Number.isFinite(rawLimit) ? Math.floor(rawLimit) : rawLimit;
118
168
  if (scopes.length === 0 || !(limit > 0))
119
169
  return [];
170
+ // The EMPTY-QUERY contract is backend-uniform — File returns [] when the
171
+ // query has no terms, so the vector rungs must not answer it either (an embedder may happily
172
+ // embed "" and score every row). One guard ahead of ALL rungs.
120
173
  const q = termSet(query);
121
174
  if (q.size === 0)
122
175
  return [];
176
+ // Native rung: rank in SQL. Excludes embedding-less rows (documented migration note).
123
177
  if (this.pgvectorSql && this.embedder) {
124
178
  const qv = await this.embedder.embed(query);
125
179
  if (Array.isArray(qv) && qv.length === this.embedder.dimensions) {
@@ -131,6 +185,7 @@ export class PgMemoryEngineBackend {
131
185
  LIMIT ${Math.min(limit, 100_000)}`, [...scopes, vectorLiteral(qv)]);
132
186
  return res.rows.map((r) => ({ ...this.headerFromRow(r), score: Number(r.dist) }));
133
187
  }
188
+ // Wrong-dimension query vector (transient embedder fault) — fall open to the in-process path.
134
189
  }
135
190
  const res = await this.query(`SELECT id, scope, slug, frontmatter, body, rev, mtime_ms, size_bytes, embedding FROM ${PG_MEMORY_ENGINE_TABLES.entries} WHERE scope IN (${inPlaceholders(1, scopes.length)})`, [...scopes]);
136
191
  const queryVec = this.embedder ? await this.embedder.embed(query).catch(() => null) : null;
@@ -139,6 +194,8 @@ export class PgMemoryEngineBackend {
139
194
  for (const raw of res.rows) {
140
195
  const r = raw;
141
196
  const fm = fromJson(r.frontmatter);
197
+ // Portable rung: cosine over the stored jsonb vector when both sides are dimension-valid;
198
+ // any missing/invalid side falls open to the lexical floor for THIS row (never dropped).
142
199
  if (queryVec && Array.isArray(queryVec) && queryVec.length === dims && r.embedding != null) {
143
200
  const stored = fromJson(r.embedding);
144
201
  if (Array.isArray(stored) && stored.length === dims) {
@@ -151,13 +208,19 @@ export class PgMemoryEngineBackend {
151
208
  continue;
152
209
  scored.push({ ...this.headerFromRow(r), score: d });
153
210
  }
211
+ // opus 审 C4: deterministic id tie-break — tied scores must not order by row-arrival accident
212
+ // (the cross-backend equivalence assertion compares ordered projections; File mirrors this).
154
213
  scored.sort((a, b) => a.score - b.score || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
155
214
  return scored.slice(0, limit);
156
215
  }
157
216
  async applyPatches(patches) {
158
217
  const report = { applied: [], conflicts: [] };
218
+ // At most ONE non-delete op per id per batch (file-backend parity — a COPY keeping its frontmatter
219
+ // id would leave the projection↔applied binding ambiguous; refuse the later one).
159
220
  const nonDeleteIds = new Set();
221
+ // In-batch (scope, slug) claims so two adds of one slug in one batch suffix deterministically.
160
222
  const plannedSlugs = new Set();
223
+ // 142-S5.1: one history row per APPLIED patch, flushed as one batch below (append-only audit face).
161
224
  const historyRows = [];
162
225
  for (const patch of patches) {
163
226
  try {
@@ -174,11 +237,17 @@ export class PgMemoryEngineBackend {
174
237
  report.conflicts.push({ op: patch.op, id: patch.id, reason: `io error: ${err instanceof Error ? err.message : String(err)}` });
175
238
  }
176
239
  }
240
+ // BEST-EFFORT history append (see PgMemoryEngineBackendOptions.history for the honest trade-off:
241
+ // the entry writes above are already committed; a failed audit append must not fail the report —
242
+ // swallow + warn, never throw. appendHistory is (id,rev)-idempotent, so a caller retry is safe.
177
243
  if (this.history && historyRows.length > 0) {
178
244
  try {
179
245
  await this.history.appendHistory(historyRows);
180
246
  }
181
247
  catch (err) {
248
+ // Every warn carries the CUMULATIVE lost count — a persistent silent failure
249
+ // (history table dropped, grant flipped) shows as a growing number, not a one-off line.
250
+ // The metrics counter leg lives in the main.ts sink wrapper (memory_history_append_failed_total).
182
251
  this.historyRowsLost += historyRows.length;
183
252
  console.warn(`PgMemoryEngineBackend: best-effort history append failed (${historyRows.length} row(s) lost, ${this.historyRowsLost} cumulative — audit face only, entries committed): ${err instanceof Error ? err.message : String(err)}`);
184
253
  }
@@ -187,6 +256,9 @@ export class PgMemoryEngineBackend {
187
256
  }
188
257
  async applyOne(patch, report, plannedSlugs, historyRows) {
189
258
  const T = PG_MEMORY_ENGINE_TABLES.entries;
259
+ // A patch whose entry carries a DIFFERENT id than the patch addresses is
260
+ // malformed — the two backends would otherwise diverge (File writes the entry's id, Pg would
261
+ // key the SELECT on patch.id but the write on entry.id). Refused up front, both backends alike.
190
262
  if (patch.op !== "delete" && patch.entry !== undefined && patch.entry.id !== patch.id) {
191
263
  report.conflicts.push({ op: patch.op, id: patch.id, reason: `patch id ${JSON.stringify(patch.id)} != entry id ${JSON.stringify(patch.entry.id)} (malformed patch refused)` });
192
264
  return;
@@ -197,13 +269,28 @@ export class PgMemoryEngineBackend {
197
269
  report.conflicts.push({ op: "add", id: patch.id, reason: "add patch without an entry" });
198
270
  return;
199
271
  }
272
+ // codex R2-H3→R3(终形):**拒绝式**——sync 协议的 rev/CAS/幂等全部对拍原文,存储层任何改写
273
+ // (有损或 canonical)都让 ack rev≠库内 rev(响应丢失重试=假冲突,R3 实锚)。含不可存字节的
274
+ // entry 在 PG 后端 fail-loud 报 conflict(reason 指路客户端清源);File 后端能存=后端能力差,
275
+ // 诚实暴露优于静默改写。重试恒同答=幂等成立。
200
276
  if (pgHasUnstorable(rawEntry.frontmatter) || pgHasUnstorable(rawEntry.body) || pgHasUnstorable(rawEntry.slug)) {
201
277
  report.conflicts.push({ op: "add", id: rawEntry.id, reason: "unstorable_bytes (PG cannot store NUL/lone surrogates; strip them at the source — the store never rewrites content)" });
202
278
  return;
203
279
  }
204
280
  const entry = rawEntry;
281
+ // opus 审 C3: an add whose id already lives in a DIFFERENT scope is refused explicitly — the bare
282
+ // `ON CONFLICT (id) DO UPDATE SET scope=…` would silently MOVE the row across scopes (and diverge
283
+ // from the File backend, which never scans other scopes on add). The engine's call surface never
284
+ // produces this input (harvest/materialize are scope-local); a conflict report is the honest
285
+ // fail-closed answer. Same-scope re-add stays the idempotent overwrite (File parity).
286
+ // One probe serves BOTH the E-02 guard below and the cross-scope refusal (File-backend parity).
205
287
  const prior = await this.query(`SELECT scope, slug, rev FROM ${T} WHERE id = $1`, [entry.id]);
206
288
  const priorRow = prior.rows.length > 0 ? prior.rows[0] : undefined;
289
+ // E-02 add-if-absent guard (core 1.275.1/1.276.0 contract clause, design/142 S2.5): a
290
+ // `guard:"absent"` add must NEVER blind-overwrite an existing id — same rev AND same
291
+ // (scope, slug) projection = idempotent fall-through; different rev OR different projection =
292
+ // REPORTED `add_guard_absent_conflict` carrying currentRev (File backend semantics verbatim;
293
+ // caught live by the contract suite on real TiDB 2026-07-13 — the twins had no guard leg).
207
294
  if (patch.guard === "absent" && priorRow) {
208
295
  const currentRev = String(priorRow.rev);
209
296
  if (currentRev !== computeEntryRev(entry)) {
@@ -214,6 +301,7 @@ export class PgMemoryEngineBackend {
214
301
  report.conflicts.push({ op: "add", id: entry.id, reason: `add_guard_absent_conflict (id already exists at the same rev but a different projection ${JSON.stringify(`${String(priorRow.scope)}/${String(priorRow.slug)}`)}; add-if-absent refuses to duplicate)`, currentRev });
215
302
  return;
216
303
  }
304
+ // same rev AND same projection ⇒ idempotent; fall through to the normal add (no-op re-write).
217
305
  }
218
306
  if (priorRow) {
219
307
  const held = String(priorRow.scope);
@@ -222,7 +310,13 @@ export class PgMemoryEngineBackend {
222
310
  return;
223
311
  }
224
312
  }
225
- const cEntry = entry;
313
+ // Slug collision with a DIFFERENT entry (same scope+slug, other id) → deterministic `-n` suffix
314
+ // (file-backend parity). In-batch planned slugs count as taken too.
315
+ // The SELECT probe alone is a race window — two instances can both observe "free" and both
316
+ // insert one slug. The INSERT itself sits INSIDE the loop: a (scope,slug) unique-violation from
317
+ // the concurrent loser retries the next suffix, so the DB constraint (ensureSchema) is the one
318
+ // true arbiter and the probe is only an optimization.
319
+ const cEntry = entry; // R3 终形:拒绝式守卫后恒干净
226
320
  const embedding = await this.embeddingParam(this.haystackOf(cEntry.slug, cEntry.frontmatter, cEntry.body));
227
321
  let slug = cEntry.slug;
228
322
  for (let n = 2;; n++) {
@@ -241,12 +335,14 @@ export class PgMemoryEngineBackend {
241
335
  catch (err) {
242
336
  if (isUniqueViolation(err)) {
243
337
  slug = `${entry.slug}-${n}`;
244
- continue;
338
+ continue; // concurrent winner took this (scope,slug) — try the next suffix
245
339
  }
246
340
  throw err;
247
341
  }
248
342
  plannedSlugs.add(key);
249
343
  report.applied.push({ op: "add", id: stored.id, slug: stored.slug });
344
+ // History: chain head — prevRev absent by contract (a same-scope idempotent re-add of
345
+ // identical content dedupes on the (id, rev) PK; changed content starts a fresh head).
250
346
  if (this.history)
251
347
  historyRows.push({ id: stored.id, rev, op: "add", scope: stored.scope, snapshot: { ...stored, rev }, writtenAtMs: this.clock() });
252
348
  return;
@@ -255,6 +351,8 @@ export class PgMemoryEngineBackend {
255
351
  slug = `${entry.slug}-${n}`;
256
352
  }
257
353
  }
354
+ // update/delete address an EXISTING entry by immutable id. (scope in the projection = the
355
+ // history row's scope for delete — a tombstone can't be joined back to the deleted row.)
258
356
  const cur = await this.query(`SELECT slug, rev, scope, frontmatter FROM ${PG_MEMORY_ENGINE_TABLES.entries} WHERE id = $1`, [patch.id]);
259
357
  if (cur.rows.length === 0) {
260
358
  report.conflicts.push({ op: patch.op, id: patch.id, reason: "unknown id (entry not found in backend)" });
@@ -263,6 +361,10 @@ export class PgMemoryEngineBackend {
263
361
  const currentRev = String(cur.rows[0].rev);
264
362
  const currentSlug = String(cur.rows[0].slug);
265
363
  const currentScope = String(cur.rows[0].scope);
364
+ // Read-side whitewash refusal (core 1.302 contract I-2, File-backend parity incl. ordering: judged
365
+ // BEFORE the rev CAS): an update may not strip provenance/trust off a repo-ingested entry. Judged on
366
+ // the committed frontmatter of THIS SELECT — a write racing past it flips rev and the conditional
367
+ // write below re-reports as a CAS conflict, so the window stays closed.
266
368
  if (patch.op === "update" && patch.entry !== undefined) {
267
369
  const committedFm = fromJson(cur.rows[0].frontmatter);
268
370
  if (committedFm.provenance?.kind === "repo_file") {
@@ -280,16 +382,28 @@ export class PgMemoryEngineBackend {
280
382
  }
281
383
  }
282
384
  if (patch.baseRev !== undefined && patch.baseRev !== currentRev) {
385
+ // Per-id CAS (§2.4 并发): NEVER blind-write over a concurrent change. No shadow-restore leg here —
386
+ // the DB row IS the committed state; nothing on a disk projection can shadow it.
387
+ // ABA note (opus 审 C1): rev is a CONTENT hash, so an A→B→A round-trip by another writer makes a
388
+ // stale baseRev "current" again and this CAS passes. Benign by construction — same hash ⇒ same
389
+ // canonical content, the overwrite is idempotent; only the intervening-write SIGNAL is lost.
390
+ // Shared with the File backend (same computeEntryRev), inherent to content-hash CAS.
283
391
  report.conflicts.push({ op: patch.op, id: patch.id, reason: "rev mismatch (concurrent change)", baseRev: patch.baseRev, currentRev });
284
392
  return;
285
393
  }
286
394
  if (patch.op === "delete") {
395
+ // Conditional on the rev we just judged — a write that lands between the SELECT and this DELETE
396
+ // re-reports as the same CAS conflict instead of silently deleting the newer committed state.
287
397
  const res = await this.query(`DELETE FROM ${PG_MEMORY_ENGINE_TABLES.entries} WHERE id = $1 AND rev = $2 RETURNING id`, [patch.id, currentRev]);
288
398
  if (res.rows.length === 0) {
289
399
  report.conflicts.push({ op: "delete", id: patch.id, reason: "rev mismatch (concurrent change)", baseRev: patch.baseRev, currentRev: await this.freshRev(patch.id, currentRev) });
290
400
  return;
291
401
  }
292
402
  report.applied.push({ op: "delete", id: patch.id, slug: currentSlug });
403
+ // History tombstone. rev must be DISTINCT from the deleted version's rev — the (id, rev) PK
404
+ // already holds a row for currentRev (the add/update that committed it), and ON CONFLICT DO
405
+ // NOTHING would silently drop a colliding tombstone. Deterministic derived key: revs are
406
+ // 16-hex content hashes (computeEntryRev), so the prefixed form stays well under varchar(128).
293
407
  if (this.history)
294
408
  historyRows.push({ id: patch.id, rev: `tombstone:${currentRev}`, prevRev: currentRev, op: "delete", scope: currentScope, writtenAtMs: this.clock() });
295
409
  return;
@@ -303,7 +417,7 @@ export class PgMemoryEngineBackend {
303
417
  report.conflicts.push({ op: "update", id: patch.id, reason: "unstorable_bytes (PG cannot store NUL/lone surrogates; strip them at the source — the store never rewrites content)" });
304
418
  return;
305
419
  }
306
- const cEntry = entry;
420
+ const cEntry = entry; // R3 终形:拒绝式后恒干净,rev 对拍原文
307
421
  const rev = computeEntryRev(cEntry);
308
422
  const embedding = await this.embeddingParam(this.haystackOf(cEntry.slug, cEntry.frontmatter, cEntry.body));
309
423
  const res = await this.query(`UPDATE ${PG_MEMORY_ENGINE_TABLES.entries}
@@ -315,9 +429,13 @@ export class PgMemoryEngineBackend {
315
429
  return;
316
430
  }
317
431
  report.applied.push({ op: "update", id: entry.id, slug: entry.slug });
432
+ // History: rev-chain link — snapshot carries the committed entry (rev = the NEW content hash).
318
433
  if (this.history)
319
434
  historyRows.push({ id: entry.id, rev, prevRev: currentRev, op: "update", scope: entry.scope, snapshot: { ...entry, rev }, writtenAtMs: this.clock() });
320
435
  }
436
+ /** When the conditional write returns zero rows (a write landed inside the
437
+ * SELECT→write window), the report's `currentRev` must be the rev NOW — re-reporting the pre-race
438
+ * SELECT value could claim `baseRev === currentRev` alongside a "rev mismatch" reason. */
321
439
  async freshRev(id, fallback) {
322
440
  const res = await this.query(`SELECT rev FROM ${PG_MEMORY_ENGINE_TABLES.entries} WHERE id = $1`, [id]);
323
441
  return res.rows.length > 0 ? String(res.rows[0].rev) : fallback;
@@ -2,14 +2,32 @@ import type { MemoryHistoryAppendRow } from "./memory-sync-store-pg.js";
2
2
  import type { PgEmbedder } from "./pg-query.js";
3
3
  import type { MemoryBackend, MemoryEntry, MemoryEntryHeader, NotePatch, PatchReport, ScoredMemoryEntry } from "@sema-agent/core";
4
4
  import type { Pool } from "mysql2/promise";
5
+ /** Table names (single source) — SAME names as PG_MEMORY_ENGINE_TABLES (the two dialects never share
6
+ * one database), deliberately DISJOINT from the legacy `agent_memory*` MemoryStore plane. */
5
7
  export declare const TIDB_MEMORY_ENGINE_TABLES: {
6
8
  readonly entries: "agent_memory_engine_entries";
7
9
  readonly cursors: "agent_memory_engine_cursors";
8
10
  };
11
+ /** Idempotent DDL for the entry plane (TiDB dialect). Call once at startup.
12
+ * Key lengths: utf8mb4 = 4 bytes/char and the default index-key cap is 3072 bytes, so the
13
+ * (scope, slug) unique key budget is scope 190 + slug 512 = 702 chars ⇒ 2808 bytes ≤ 3072. */
9
14
  export declare function ensureTiDBMemoryEngineSchema(pool: Pool): Promise<void>;
15
+ /** Options for {@link TiDBMemoryEngineBackend}. Signature-parity with the Pg twin, but v1 is
16
+ * LEXICAL ONLY — there is no TiDB vector rung yet; passing an embedder is refused loudly
17
+ * (no-stopgap: never silently ignore a caller's recall-quality expectation). */
10
18
  export interface TiDBMemoryEngineBackendOptions {
19
+ /** NOT SUPPORTED in v1 (lexical only) — present for signature parity; a value throws at construction. */
11
20
  embedder?: PgEmbedder;
21
+ /** Clock injection (file-backend precedent) — drives `mtime_ms`. Default `Date.now`. */
12
22
  now?: () => number;
23
+ /** 142-S5.1 history write point — OPTIONAL audit sink, one history row per APPLIED patch, appended
24
+ * AFTER the entry write. Absent → byte-equal legacy behavior (additive). 同事务诚实记档(Pg 版同注,
25
+ * posture 对称保持):this backend does hold a Pool (a getConnection+txn wrap IS possible), but the
26
+ * entry plane itself is deliberately NON-transactional (single-statement CAS is the correctness
27
+ * mechanism), and the Pg twin's bare-PgQueryFn seam cannot cheaply transact — wrapping only the
28
+ * TiDB side would fork the twins' semantics. Chosen trade-off on BOTH dialects: entry write commits
29
+ * first, history append is BEST-EFFORT (failure = swallow + console.warn) — history is the AUDIT
30
+ * face, not the correctness face: a lost history row loses an audit line, never data. */
13
31
  history?: {
14
32
  appendHistory(rows: readonly MemoryHistoryAppendRow[]): Promise<void>;
15
33
  };
@@ -18,11 +36,14 @@ export declare class TiDBMemoryEngineBackend implements MemoryBackend {
18
36
  private readonly pool;
19
37
  private readonly clock;
20
38
  private readonly history?;
39
+ /** Cumulative lost-row count — audit-line breakage must itself be auditable. */
21
40
  private historyRowsLost;
41
+ /** design/81 rung indicator — TiDB v1 sits on the lexical floor (Pg twin parity surface). */
22
42
  get vectorMode(): "lexical";
23
43
  constructor(pool: Pool, opts?: TiDBMemoryEngineBackendOptions);
24
44
  private selectRows;
25
45
  private write;
46
+ /** The search haystack — BYTE-EQUAL to the File/Pg backends' lexical haystack (contract equivalence). */
26
47
  private haystackOf;
27
48
  private headerFromRow;
28
49
  private entryFromRow;
@@ -33,7 +54,12 @@ export declare class TiDBMemoryEngineBackend implements MemoryBackend {
33
54
  }): Promise<ScoredMemoryEntry[]>;
34
55
  applyPatches(patches: readonly NotePatch[]): Promise<PatchReport>;
35
56
  private applyOne;
57
+ /** The row's rev NOW, or undefined if the row is gone. The existence distinction is the whole point
58
+ * (codex lens-3): a concurrent delete must not be mistaken for an idempotent already-at-target write. */
36
59
  private freshRevOrMissing;
60
+ /** When the conditional write reports zero rows (a write landed inside the SELECT→write window), the
61
+ * report's `currentRev` must be the rev NOW — re-reporting the pre-race SELECT value could claim
62
+ * `baseRev === currentRev` alongside a "rev mismatch" reason. Row gone ⇒ fallback (Pg parity). */
37
63
  private freshRev;
38
64
  getConsolidationCursor(scope: string): Promise<string | undefined>;
39
65
  setConsolidationCursor(scope: string, cursor: string): Promise<void>;