@sema-agent/server 7.140.0 → 7.142.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 (296) hide show
  1. package/MIGRATION.md +505 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/USAGE.md +142 -25
  5. package/dist/approval-ask-audit-store.d.ts +54 -38
  6. package/dist/approval-ask-audit-store.js +58 -39
  7. package/dist/approval-batch-census.d.ts +27 -0
  8. package/dist/approval-batch-census.js +27 -0
  9. package/dist/approval-card.d.ts +39 -24
  10. package/dist/approval-card.js +6 -3
  11. package/dist/approval-crash-convergence.d.ts +17 -7
  12. package/dist/approval-crash-convergence.js +94 -22
  13. package/dist/approval-deny-reasons.d.ts +34 -30
  14. package/dist/approval-deny-reasons.js +21 -6
  15. package/dist/approval-policy-settlement.d.ts +1 -1
  16. package/dist/approval-reconciler.d.ts +33 -1
  17. package/dist/approval-reconciler.js +43 -40
  18. package/dist/approval.d.ts +15 -0
  19. package/dist/approval.js +10 -0
  20. package/dist/audit.d.ts +4 -2
  21. package/dist/audit.js +2 -2
  22. package/dist/auth-bridge.d.ts +9 -6
  23. package/dist/auth-bridge.js +9 -3
  24. package/dist/boot/adoption.js +2 -1
  25. package/dist/boot/budget-tracing.d.ts +16 -0
  26. package/dist/boot/budget-tracing.js +10 -6
  27. package/dist/boot/device-lane.d.ts +11 -0
  28. package/dist/boot/device-lane.js +16 -0
  29. package/dist/boot/engine-lease.d.ts +24 -3
  30. package/dist/boot/engine-lease.js +9 -2
  31. package/dist/boot/execution-env.d.ts +24 -4
  32. package/dist/boot/execution-env.js +34 -27
  33. package/dist/boot/execution-lane.js +2 -1
  34. package/dist/boot/exit-boundary.js +5 -4
  35. package/dist/boot/memory-boundary.d.ts +2 -2
  36. package/dist/boot/memory-consolidation.d.ts +1 -1
  37. package/dist/boot/memory-consolidation.js +3 -2
  38. package/dist/boot/parked-revive-gate.js +2 -1
  39. package/dist/boot/permission-rules-audit.d.ts +0 -28
  40. package/dist/boot/permission-rules-audit.js +2 -1
  41. package/dist/boot/read-deny-anchor-audit.js +2 -1
  42. package/dist/boot/reapers.d.ts +2 -2
  43. package/dist/boot/reapers.js +4 -3
  44. package/dist/boot/resolve-spec.js +18 -6
  45. package/dist/boot/retention-lane.js +5 -3
  46. package/dist/boot/runner-deps.js +16 -13
  47. package/dist/boot/runtime-caps.js +3 -2
  48. package/dist/boot/session-faces.d.ts +1 -1
  49. package/dist/boot/session-faces.js +8 -6
  50. package/dist/boot/shutdown.js +8 -2
  51. package/dist/boot/stage-04-stores.js +3 -2
  52. package/dist/boot/stage-05-execution-env.d.ts +1 -1
  53. package/dist/boot/stage-05-execution-env.js +11 -7
  54. package/dist/boot/stage-06-runners.d.ts +1 -3
  55. package/dist/boot/stage-06-runners.js +3 -2
  56. package/dist/boot/stage-07-capability-layer.d.ts +1 -2
  57. package/dist/boot/stage-07-capability-layer.js +10 -11
  58. package/dist/boot/stage-08-reapers.d.ts +1 -2
  59. package/dist/boot/stage-08-reapers.js +3 -2
  60. package/dist/boot/stage-09-leader.d.ts +1 -2
  61. package/dist/boot/stage-10-http-server.d.ts +1 -2
  62. package/dist/boot/stage-10-http-server.js +6 -4
  63. package/dist/boot/stores.js +13 -6
  64. package/dist/boot/web-admin.js +18 -17
  65. package/dist/boot/webfetch-summarize-lane.js +2 -1
  66. package/dist/boot/workflow-orchestration.js +3 -2
  67. package/dist/capabilities/builtin-tools.d.ts +2 -1
  68. package/dist/capabilities/builtin-tools.js +2 -4
  69. package/dist/capabilities/composite-members.d.ts +2 -1
  70. package/dist/capabilities/composite-members.js +2 -1
  71. package/dist/capabilities/scenarios.d.ts +1 -1
  72. package/dist/capability-facts.d.ts +33 -0
  73. package/dist/capability-facts.js +32 -0
  74. package/dist/card-void.d.ts +38 -0
  75. package/dist/card-void.js +23 -0
  76. package/dist/config-catalog.js +12 -8
  77. package/dist/config-provider.d.ts +13 -13
  78. package/dist/config-provider.js +19 -33
  79. package/dist/config-types.d.ts +39 -10
  80. package/dist/config.d.ts +6 -0
  81. package/dist/config.js +72 -49
  82. package/dist/delegated-session-owner.d.ts +21 -19
  83. package/dist/delegated-session-owner.js +1 -1
  84. package/dist/device-store.d.ts +7 -0
  85. package/dist/device-store.js +3 -0
  86. package/dist/execution-config-root.d.ts +22 -0
  87. package/dist/execution-config-root.js +35 -0
  88. package/dist/execution-lane-caps.d.ts +50 -2
  89. package/dist/execution-lane-caps.js +90 -13
  90. package/dist/execution-placement.d.ts +3 -0
  91. package/dist/execution-placement.js +7 -0
  92. package/dist/fleet/drain-entry.d.ts +3 -0
  93. package/dist/fleet/fleet-bus.d.ts +6 -3
  94. package/dist/hooks/hook-runner.d.ts +6 -0
  95. package/dist/hooks/hook-runner.js +30 -1
  96. package/dist/hosted-posture.d.ts +8 -0
  97. package/dist/hosted-posture.js +4 -0
  98. package/dist/http/admission.js +3 -3
  99. package/dist/http/caller-trust.d.ts +3 -2
  100. package/dist/http/caller-trust.js +2 -1
  101. package/dist/http/dispatch.js +8 -2
  102. package/dist/http/execution-context.d.ts +2 -2
  103. package/dist/http/idempotency.d.ts +1 -1
  104. package/dist/http/live-frame.d.ts +24 -0
  105. package/dist/http/live-frame.js +16 -0
  106. package/dist/http/principal-gate.d.ts +3 -1
  107. package/dist/http/principal-gate.js +17 -8
  108. package/dist/http/resume-legs.js +42 -29
  109. package/dist/http/route-table.js +4 -0
  110. package/dist/http/routes/approvals-assistant.js +1 -0
  111. package/dist/http/routes/attachments.js +18 -0
  112. package/dist/http/routes/capabilities.js +10 -6
  113. package/dist/http/routes/diagnostics.d.ts +0 -19
  114. package/dist/http/routes/diagnostics.js +16 -2
  115. package/dist/http/routes/memory-bundle.d.ts +2 -2
  116. package/dist/http/routes/memory-bundle.js +1 -1
  117. package/dist/http/routes/memory-compliance.js +1 -1
  118. package/dist/http/routes/memory-policy.js +27 -7
  119. package/dist/http/routes/run-permission-mode.d.ts +75 -0
  120. package/dist/http/routes/run-permission-mode.js +170 -0
  121. package/dist/http/routes/runs.js +3 -3
  122. package/dist/http/routes/session-memory-sync.d.ts +63 -0
  123. package/dist/http/routes/session-memory-sync.js +157 -0
  124. package/dist/http/routes/session-sync.d.ts +3 -6
  125. package/dist/http/routes/session-sync.js +7 -2
  126. package/dist/http/routes/sessions-list.d.ts +2 -1
  127. package/dist/http/routes/sessions.js +5 -4
  128. package/dist/http/routes/tasks.js +70 -71
  129. package/dist/http/run-read-face.d.ts +7 -0
  130. package/dist/http/run-read-face.js +10 -4
  131. package/dist/http/send.d.ts +6 -1
  132. package/dist/http/send.js +10 -3
  133. package/dist/http/server.d.ts +20 -7
  134. package/dist/http/server.js +2 -4
  135. package/dist/http/sse-log.d.ts +3 -8
  136. package/dist/http/stored-body-replay.d.ts +3 -3
  137. package/dist/http/stored-body-replay.js +3 -1
  138. package/dist/http/submit-replay.d.ts +4 -3
  139. package/dist/http/submit-replay.js +2 -2
  140. package/dist/http/sync-submit-body.d.ts +21 -4
  141. package/dist/http/sync-submit-body.js +13 -0
  142. package/dist/identity-source.d.ts +21 -2
  143. package/dist/identity-source.js +6 -0
  144. package/dist/instruction-source-notice.d.ts +7 -0
  145. package/dist/instruction-source-notice.js +6 -6
  146. package/dist/mcp-assertion-header.d.ts +4 -0
  147. package/dist/mcp-assertion-header.js +5 -0
  148. package/dist/memory-incident-sink.d.ts +19 -6
  149. package/dist/memory-incident-sink.js +8 -4
  150. package/dist/memory-posture.d.ts +1 -1
  151. package/dist/memory-scope.d.ts +4 -4
  152. package/dist/memory-scope.js +1 -1
  153. package/dist/memory-sync-client.d.ts +35 -23
  154. package/dist/memory-sync-client.js +122 -52
  155. package/dist/memory-sync-identity.d.ts +24 -0
  156. package/dist/memory-sync-identity.js +57 -0
  157. package/dist/memory-sync.d.ts +7 -1
  158. package/dist/memory-sync.js +6 -3
  159. package/dist/observability/fail-open.d.ts +57 -12
  160. package/dist/observability/fail-open.js +50 -9
  161. package/dist/observability/metrics.js +0 -1
  162. package/dist/observability/run-terminal.d.ts +93 -31
  163. package/dist/observability/run-terminal.js +175 -171
  164. package/dist/observability/secret-env-scrub.d.ts +20 -1
  165. package/dist/observability/secret-env-scrub.js +14 -0
  166. package/dist/orchestration/workflow-completion-inbox.d.ts +5 -2
  167. package/dist/orchestration/workflow-completion-inbox.js +13 -5
  168. package/dist/orchestration/workflow-notify-journal.d.ts +5 -3
  169. package/dist/orchestration/workflow-notify-journal.js +2 -1
  170. package/dist/permission-mode-admission.d.ts +68 -0
  171. package/dist/permission-mode-admission.js +23 -0
  172. package/dist/permission-rule-list.d.ts +55 -6
  173. package/dist/permission-rule-list.js +52 -5
  174. package/dist/plugins/approval-ask-store-file.d.ts +14 -4
  175. package/dist/plugins/approval-ask-store-file.js +48 -7
  176. package/dist/plugins/approval-ask-store-memory.d.ts +2 -1
  177. package/dist/plugins/approval-ask-store-memory.js +9 -8
  178. package/dist/plugins/approval-ask-store-sql.d.ts +42 -10
  179. package/dist/plugins/approval-ask-store-sql.js +49 -19
  180. package/dist/plugins/caching-session-store.d.ts +6 -0
  181. package/dist/plugins/caching-session-store.js +3 -0
  182. package/dist/plugins/checkpoint-store-sql.d.ts +65 -17
  183. package/dist/plugins/checkpoint-store-sql.js +74 -3
  184. package/dist/plugins/device-store-sql.d.ts +5 -2
  185. package/dist/plugins/device-store-sql.js +4 -1
  186. package/dist/plugins/execution-placement-sql.d.ts +11 -1
  187. package/dist/plugins/execution-placement-sql.js +12 -1
  188. package/dist/plugins/file-run-store.d.ts +7 -2
  189. package/dist/plugins/file-run-store.js +12 -2
  190. package/dist/plugins/fork-routing-session-store.d.ts +10 -32
  191. package/dist/plugins/fork-routing-session-store.js +2 -61
  192. package/dist/plugins/k8s-exec-protocol.d.ts +4 -1
  193. package/dist/plugins/k8s-exec-protocol.js +6 -1
  194. package/dist/plugins/local-checkpoint-store.d.ts +10 -1
  195. package/dist/plugins/local-checkpoint-store.js +22 -0
  196. package/dist/plugins/local-session-store.d.ts +260 -39
  197. package/dist/plugins/local-session-store.js +582 -57
  198. package/dist/plugins/local-session-window.d.ts +17 -3
  199. package/dist/plugins/local-session-window.js +7 -13
  200. package/dist/plugins/local-task-attachment-store.d.ts +12 -2
  201. package/dist/plugins/local-task-attachment-store.js +67 -43
  202. package/dist/plugins/memory-key-guards.d.ts +3 -3
  203. package/dist/plugins/memory-run-store.d.ts +7 -2
  204. package/dist/plugins/memory-run-store.js +12 -2
  205. package/dist/plugins/one-time-migrations.d.ts +68 -2
  206. package/dist/plugins/one-time-migrations.js +120 -4
  207. package/dist/plugins/pg-pool.js +3 -2
  208. package/dist/plugins/pg-session-storage.d.ts +2 -0
  209. package/dist/plugins/pg-session-storage.js +3 -2
  210. package/dist/plugins/remote-env-e2b.d.ts +47 -7
  211. package/dist/plugins/remote-env-e2b.js +242 -46
  212. package/dist/plugins/remote-env-k8s.d.ts +51 -6
  213. package/dist/plugins/remote-env-k8s.js +234 -44
  214. package/dist/plugins/remote-env-local-docker.d.ts +40 -14
  215. package/dist/plugins/remote-env-local-docker.js +127 -33
  216. package/dist/plugins/run-store-sql.d.ts +11 -3
  217. package/dist/plugins/run-store-sql.js +13 -4
  218. package/dist/plugins/sandbox-read-floor.d.ts +273 -0
  219. package/dist/plugins/sandbox-read-floor.js +608 -0
  220. package/dist/plugins/session-ownership.d.ts +2 -1
  221. package/dist/plugins/session-placement.d.ts +17 -4
  222. package/dist/plugins/session-placement.js +2 -1
  223. package/dist/plugins/session-store.d.ts +18 -20
  224. package/dist/plugins/session-store.js +4 -12
  225. package/dist/plugins/store-backend.d.ts +41 -7
  226. package/dist/plugins/store-backend.js +22 -4
  227. package/dist/plugins/store-contracts.d.ts +35 -3
  228. package/dist/plugins/store-contracts.js +3 -0
  229. package/dist/plugins/task-attachment-store.d.ts +112 -14
  230. package/dist/plugins/task-attachment-store.js +221 -28
  231. package/dist/plugins/tidb-pool.js +2 -1
  232. package/dist/plugins/tidb-session-store.d.ts +4 -1
  233. package/dist/plugins/tidb-session-store.js +3 -2
  234. package/dist/plugins/workspace-fill.d.ts +60 -0
  235. package/dist/plugins/workspace-fill.js +106 -0
  236. package/dist/project-bundle.d.ts +38 -0
  237. package/dist/project-bundle.js +609 -0
  238. package/dist/run-cancel-context.d.ts +34 -0
  239. package/dist/run-cancel-context.js +7 -0
  240. package/dist/run-local.js +2 -8
  241. package/dist/runs.d.ts +39 -12
  242. package/dist/runs.js +69 -55
  243. package/dist/sandbox-egress-policy.d.ts +4 -1
  244. package/dist/sandbox-egress-policy.js +3 -1
  245. package/dist/sandbox-git-plane.d.ts +31 -12
  246. package/dist/sandbox-git-plane.js +24 -4
  247. package/dist/security.d.ts +11 -2
  248. package/dist/security.js +8 -0
  249. package/dist/server-secret-env.d.ts +2 -1
  250. package/dist/server-secret-env.js +2 -4
  251. package/dist/session-error-wire.d.ts +46 -4
  252. package/dist/session-error-wire.js +23 -0
  253. package/dist/session-incarnation.d.ts +9 -3
  254. package/dist/session-sync-kernel.d.ts +42 -1
  255. package/dist/session-sync-kernel.js +17 -0
  256. package/dist/session-sync.js +16 -4
  257. package/dist/sql-engine-coordinates.d.ts +49 -0
  258. package/dist/sql-engine-coordinates.js +27 -0
  259. package/dist/standing-answer-grant.d.ts +31 -2
  260. package/dist/standing-answer-grant.js +14 -2
  261. package/dist/store-posture.d.ts +1 -1
  262. package/dist/task-a2a.d.ts +1 -1
  263. package/dist/task-mcp.d.ts +1 -1
  264. package/dist/task-settings.d.ts +62 -27
  265. package/dist/task-settings.js +105 -29
  266. package/dist/terminal.d.ts +97 -20
  267. package/dist/terminal.js +107 -18
  268. package/dist/tool-approval.d.ts +4 -3
  269. package/dist/tool-approval.js +12 -14
  270. package/dist/trace/core-keyset-guard.d.ts +196 -2
  271. package/dist/trace/engine-notice-wire.d.ts +8 -2
  272. package/dist/trace/engine-notice-wire.js +4 -2
  273. package/dist/trace/exit-seat.d.ts +9 -1
  274. package/dist/trace/exit-seat.js +1 -0
  275. package/dist/trace/ledger-sink.d.ts +8 -4
  276. package/dist/trace/ledger-sink.js +2 -2
  277. package/dist/trace/model-segment.d.ts +2 -2
  278. package/dist/trace/project.d.ts +18 -1
  279. package/dist/trace/project.js +16 -0
  280. package/dist/trace/redact.js +323 -90
  281. package/dist/trace/self-minted-wire.d.ts +419 -4
  282. package/dist/trace/self-minted-wire.js +145 -0
  283. package/dist/trace/wire-projection-faces.d.ts +1 -1
  284. package/dist/trace/wire-projection-faces.js +1 -1
  285. package/dist/verifier-pause-card.d.ts +8 -0
  286. package/dist/verifier-pause-card.js +19 -0
  287. package/dist/web-admin-client/apply-effective.d.ts +5 -7
  288. package/dist/web-admin-client/apply-effective.js +22 -2
  289. package/dist/web-admin-client/candidate-gate.d.ts +1 -1
  290. package/dist/web-admin-client/effective-keys.js +2 -0
  291. package/dist/web-admin-client/read-warnings.d.ts +2 -2
  292. package/dist/web-admin-client/types.d.ts +4 -0
  293. package/docs/DEVICE-EXECUTOR-PROTOCOL.md +3 -2
  294. package/package.json +2 -2
  295. package/wire-changes/server@7.141.0.json +367 -0
  296. package/wire-changes/server@7.142.0.json +639 -0
@@ -3,8 +3,8 @@ import { createHash } from "node:crypto";
3
3
  import { CHECKPOINT_FACET_SQL, CHECKPOINT_SWEEP_ORDER_SQL, CheckpointIndexRefusedError, judgeCheckpointIndexCells } from "./checkpoint-index-columns.js";
4
4
  import { CheckpointError, isGateKind, MAX_RULE_TEXT_CHARS, validatePendingSteer, appendPendingSteer, winnerFromOutcome, summarizeCheckpoint, checkpointRevOf, MAX_SUPPORTED_CHECKPOINT_VERSION, ExecutionOutcomeConflictError, executionRecordDisposition, executionVerdict, } from "@sema-agent/core";
5
5
  import { redactDeep, redactSecrets } from "../trace/redact.js";
6
- import { MAX_RULE_OFFERS, MAX_RULE_OFFER_BATCH_MEMBERS, parkRowCarriesSkillCardFacts, parkRowFacts, readRuleOfferList, skillCardFacts } from "../approval-card.js";
7
- import { assertJsonColumnWritable, createObjectColumnReader, decodeJsonColumn, decodeNullableJsonColumn, foldJsonColumn, isJsonColumnBodyProblem, jsonColumnText, readJsonArrayColumn, readJsonObjectColumn, readNonNullJsonValueColumn, } from "./sql-json-column.js";
6
+ import { MAX_RULE_OFFERS, MAX_RULE_OFFER_BATCH_MEMBERS, countKindlessBatchOffers, parkRowCarriesSkillCardFacts, parkRowFacts, readRuleOfferList, skillCardFacts } from "../approval-card.js";
7
+ import { assertJsonColumnWritable, createObjectColumnReader, decodeJsonColumn, decodeNullableJsonColumn, foldJsonColumn, isJsonColumnBodyProblem, jsonColumnText, jsonColumnTextExpr, readJsonArrayColumn, readJsonObjectColumn, readNonNullJsonValueColumn, } from "./sql-json-column.js";
8
8
  import { recordFailOpen } from "../observability/fail-open.js";
9
9
  import { durableRowIdentity, withoutCheckpointToken } from "../checkpoint-identity.js";
10
10
  import { mysqlDriver, pgDriver, dialectProtocolJsonEncoder } from "./sql-driver.js";
@@ -13,6 +13,7 @@ import { describeProbedTableDrift } from "./schema-drift-sentence.js";
13
13
  import { MANAGED_RETENTION, UNMANAGED_RETENTION } from "./retention-store-sql.js";
14
14
  import { approvalPayloadFingerprint } from "./approval-payload-fingerprint.js";
15
15
  const CTX_REWRITE_PAGE = 500;
16
+ const KINDLESS_SCAN_PAGE = 200;
16
17
  export { approvalPayloadFingerprint } from "./approval-payload-fingerprint.js";
17
18
  const MAX_TOOL_INPUT_CHARS = 8192;
18
19
  export const TERMINAL_BACKSTOP_MS = Math.max(60_000, (Number.isFinite(Number(process.env.APPROVAL_TERMINAL_BACKSTOP_MS)) ? Number(process.env.APPROVAL_TERMINAL_BACKSTOP_MS) : 0) || 30 * 86_400_000);
@@ -78,10 +79,13 @@ function preboundBatchMembers(item) {
78
79
  return item;
79
80
  return { ...candidate, rules: candidate.rules.slice(0, MAX_RULE_OFFER_BATCH_MEMBERS) };
80
81
  }
82
+ export function boundedReaderInput(raw) {
83
+ return Array.isArray(raw) ? raw.slice(0, MAX_RULE_OFFER_SCAN).map(preboundBatchMembers) : raw;
84
+ }
81
85
  export function boundedRuleOffers(raw, opts = {}) {
82
86
  const observe = opts.countRedactions ?? true;
83
87
  const scrub = (text) => redactSecrets(text, { observe }).slice(0, MAX_RULE_TEXT_CHARS);
84
- const read = readRuleOfferList(Array.isArray(raw) ? raw.slice(0, MAX_RULE_OFFER_SCAN).map(preboundBatchMembers) : raw);
88
+ const read = readRuleOfferList(boundedReaderInput(raw));
85
89
  const out = [];
86
90
  for (const { offer } of read) {
87
91
  if (out.length >= MAX_RULE_OFFERS)
@@ -331,6 +335,7 @@ export function readPendingSteerQueueColumn(queueRaw) {
331
335
  }
332
336
  const STEER_CAS_ATTEMPTS = 8;
333
337
  const EXECUTION_RECORD_CAS_ATTEMPTS = 8;
338
+ export const CTX_CLAIM_REWRITES = ["written", "claim_released", "context_absent"];
334
339
  export class SqlCheckpointStore {
335
340
  db;
336
341
  logger;
@@ -338,10 +343,12 @@ export class SqlCheckpointStore {
338
343
  durability = "durable";
339
344
  fidelity = "json";
340
345
  execution = { outcome: true };
346
+ claims;
341
347
  constructor(db, logger, opts = {}) {
342
348
  this.db = db;
343
349
  this.logger = logger;
344
350
  this.retention = opts.retention ?? UNMANAGED_RETENTION;
351
+ this.claims = opts.claims;
345
352
  }
346
353
  q(mysql, pg) {
347
354
  return this.db.dialect === "mysql" ? mysql : pg;
@@ -736,6 +743,29 @@ export class SqlCheckpointStore {
736
743
  const { rows } = await this.db.query(this.q(`SELECT ${jsonColumnText("mysql", "ctx")} FROM checkpoint_ctx WHERE session_id=?`, `SELECT ${jsonColumnText("pg", "ctx")} FROM checkpoint_ctx WHERE session_id=$1`), [sessionId]);
737
744
  return rows[0] ? refusing("a resume context nobody can read", () => decodeCtxColumn(rows[0].ctx, `for session ${JSON.stringify(sessionId)}`)) : null;
738
745
  }
746
+ async rewriteCtxWhileClaimed(sessionId, taskId, ctx, legHolds) {
747
+ const claims = this.claims;
748
+ if (claims === undefined)
749
+ throw new Error("SqlCheckpointStore.rewriteCtxWhileClaimed: no claim fence is bound to this store (wiring defect: the backend binds its own run store)");
750
+ const text = this.json(ctx, "checkpoint ctx");
751
+ assertJsonColumnWritable(text, createObjectColumnReader(), `checkpoint_ctx.ctx for session ${JSON.stringify(sessionId)} (claim-fenced rewrite)`);
752
+ let fenced;
753
+ try {
754
+ fenced = await claims.whileHoldingClaim(sessionId, taskId, async (tx, run) => {
755
+ if (!legHolds(run))
756
+ return "claim_released";
757
+ const row = await tx.query(this.q("SELECT session_id FROM checkpoint_ctx WHERE session_id = ? FOR UPDATE", "SELECT session_id FROM checkpoint_ctx WHERE session_id = $1 FOR UPDATE"), [sessionId]);
758
+ if (row.rows.length === 0)
759
+ return "context_absent";
760
+ await tx.query(this.q("UPDATE checkpoint_ctx SET ctx = ?, updated_at_ms = ? WHERE session_id = ?", "UPDATE checkpoint_ctx SET ctx = $1::jsonb, updated_at_ms = $2 WHERE session_id = $3"), [text, Date.now(), sessionId]);
761
+ return "written";
762
+ });
763
+ }
764
+ catch (e) {
765
+ throw rowTooLargeOrSelf(this.db.dialect, e, `checkpoint_ctx.ctx for session ${JSON.stringify(sessionId)} (claim-fenced rewrite)`);
766
+ }
767
+ return fenced.held ? fenced.value : "claim_released";
768
+ }
739
769
  async rewriteCtxRows(rewrite) {
740
770
  const out = { scanned: 0, rewritten: 0, valuesRewritten: 0, unreadable: 0, tooLarge: 0 };
741
771
  let after = "";
@@ -779,6 +809,47 @@ export class SqlCheckpointStore {
779
809
  }
780
810
  return out;
781
811
  }
812
+ async scanKindlessBatchRows() {
813
+ const out = [];
814
+ let unreadableCells = 0;
815
+ const tolerant = (read) => {
816
+ try {
817
+ return read();
818
+ }
819
+ catch (e) {
820
+ if (!isJsonColumnBodyProblem(e))
821
+ throw e;
822
+ unreadableCells += 1;
823
+ return undefined;
824
+ }
825
+ };
826
+ const prefilter = (d) => `(rule_suggestions IS NOT NULL OR ${jsonColumnTextExpr(d, "checkpoint", PARK_ROW_PENDING_ACTION.key)} LIKE '%"batch"%')`;
827
+ let after = "";
828
+ for (;;) {
829
+ const { rows } = await this.db.query(this.q(`SELECT token, ${jsonColumnText("mysql", "rule_suggestions")}, ${jsonColumnText("mysql", "checkpoint", PARK_ROW_PENDING_ACTION)} FROM checkpoint WHERE token > ? AND ${prefilter("mysql")} ORDER BY token LIMIT ${KINDLESS_SCAN_PAGE}`, `SELECT token, ${jsonColumnText("pg", "rule_suggestions")}, ${jsonColumnText("pg", "checkpoint", PARK_ROW_PENDING_ACTION)} FROM checkpoint WHERE token > $1 AND ${prefilter("pg")} ORDER BY token LIMIT ${KINDLESS_SCAN_PAGE}`), [after]);
830
+ for (const row of rows) {
831
+ const token = String(row.token);
832
+ after = token;
833
+ const carriers = [];
834
+ const column = tolerant(() => decodeNullableJsonColumn(row.rule_suggestions, readJsonArrayColumn, "checkpoint.rule_suggestions (kind-less batch census)"));
835
+ if (countKindlessBatchOffers(boundedReaderInput(column)) > 0)
836
+ carriers.push("rule_suggestions");
837
+ const pendingAction = tolerant(() => decodeNullableJsonColumn(row[PARK_ROW_PENDING_ACTION.as], readJsonObjectColumn, "checkpoint.checkpoint pendingAction member (kind-less batch census)"));
838
+ if (typeof pendingAction === "object" && pendingAction !== null) {
839
+ const blobOffers = Reflect.get(pendingAction, "ruleOffers");
840
+ if (blobOffers !== undefined && !Array.isArray(blobOffers))
841
+ unreadableCells += 1;
842
+ else if (countKindlessBatchOffers(blobOffers) > 0)
843
+ carriers.push("pendingAction.ruleOffers");
844
+ }
845
+ if (carriers.length > 0)
846
+ out.push({ ref: tokenFingerprint(token), carriers });
847
+ }
848
+ if (rows.length < KINDLESS_SCAN_PAGE)
849
+ break;
850
+ }
851
+ return { rows: out, unreadableCells };
852
+ }
782
853
  async reapCtx(cutoff) {
783
854
  const res = await this.db.query(this.q("DELETE FROM checkpoint_ctx WHERE updated_at_ms < ? " +
784
855
  "AND session_id NOT IN (SELECT session_id FROM checkpoint WHERE status='pending') " +
@@ -9,8 +9,9 @@
9
9
  * · `device_enroll_tokens` —— 一次性 enrollment 凭据(明文一现,落库只有 sha256)
10
10
  * · `device_audit` —— 安全轴事件审计(§4.8 标「审计行」的 8 个 event)
11
11
  * **根会话 ↔ 设备绑定不在本店的表里**:它是根会话行(`session_meta`)上这一位住客的执行格 writer(device, D)(列与语句的唯一属主 =
12
- * `execution-placement-sql.ts`;规则在 `../execution-placement.ts` 头注)。读只经会话店的执行席 `seat.read(root)`;本店只有两只写 ——
13
- * 首绑 {@link SqlDeviceStore.placeDeviceExecution} 与换绑 {@link SqlDeviceStore.rebindDeviceExecution},各是一只事务,锁序全局一条:设备行 → 根 `session_meta` → `task_*`。
12
+ * `execution-placement-sql.ts`;规则在 `../execution-placement.ts` 头注)。按根的读只经会话店的执行席 `seat.read(root)`;本店有两只写 ——
13
+ * 首绑 {@link SqlDeviceStore.placeDeviceExecution} 与换绑 {@link SqlDeviceStore.rebindDeviceExecution},各是一只事务,锁序全局一条:设备行 → 根 `session_meta` → `task_*` ——
14
+ * 与一只聚合读 {@link SqlDeviceStore.countDeviceBindings}(绑定数,池级一读、不锁,只交一个数)。
14
15
  * 刻意**没有** `device_instructions` 表:指令 pending 表是内存态(§6 注③——指令比 run 短命,落库只会
15
16
  * 造「表里 pending、run 已死」的僵尸行;at-most-once 靠 §5.3 投递边界,不靠指令落库)。
16
17
  *
@@ -157,6 +158,8 @@ export declare class SqlDeviceStore implements DeviceStore {
157
158
  * 审计写不进去 = 整次换绑失败(fail-closed,[ref])。持锁判过之后 CAS 不可能 0 行 —— 0 行即引擎异常,响亮抛。三形语义 oracle = `InMemoryDeviceStore.rebindDeviceExecution`。
158
159
  */
159
160
  rebindDeviceExecution(input: RebindDeviceExecutionInput): Promise<RebindDeviceExecutionResult>;
161
+ /** 绑定数(契约注见 `DeviceStore.countDeviceBindings`):池级一读,读与判的唯一属主 = `execution-placement-sql.ts` 的 `countDeviceBindingsOn`(行过唯一解码 + `boundDeviceOf`)。 */
162
+ countDeviceBindings(): Promise<number>;
160
163
  appendAudit(input: AppendAuditInput): Promise<void>;
161
164
  /** 审计写的**唯一**语句(池级与事务内共用;`SqlExec` 是两者的公共面)。 */
162
165
  private insertAuditOn;
@@ -2,7 +2,7 @@ import { mysqlDriver, pgDriver, dialectJsonEncoder } from "./sql-driver.js";
2
2
  import { isDupKeyError, isCheckViolationError } from "./sql-errors.js";
3
3
  import { DEVICE_AUDIT_EVENTS, assertAcquireShape, assertDeviceIdShape, assertDeviceOwnerShape, assertEnrollTokenHashShape, assertIssueTokenShape, assertNewDeviceShape, assertPlaceDeviceShape, assertRebindShape, assertRevokeShape, assertWholeSeconds, parseDeviceAuditEvent, parseDevicePlatformOs, parseDeviceStatus, } from "../device-store.js";
4
4
  import { WRITABLE, boundDeviceOf, settledDeviceBindOutcome, settledDeviceRebindOutcome } from "../execution-placement.js";
5
- import { bindDeviceStatement, lockRootAndReadClaim, placeWriterStatement, readPlacementOn, rebindDeviceStatement, rowsOnSqlExec } from "./execution-placement-sql.js";
5
+ import { bindDeviceStatement, countDeviceBindingsOn, lockRootAndReadClaim, placeWriterStatement, readPlacementOn, rebindDeviceStatement, rowsOnSqlExec } from "./execution-placement-sql.js";
6
6
  import { ensureIndexes } from "./ensure-index.js";
7
7
  import { decodeJsonColumn, foldJsonColumn, jsonColumnText, readJsonObjectColumn } from "./sql-json-column.js";
8
8
  export const DEVICES_TABLE = "device";
@@ -581,6 +581,9 @@ export class SqlDeviceStore {
581
581
  conn.release();
582
582
  }
583
583
  }
584
+ async countDeviceBindings() {
585
+ return countDeviceBindingsOn(rowsOnSqlExec(this.db));
586
+ }
584
587
  async appendAudit(input) {
585
588
  await this.insertAuditOn(this.db, input);
586
589
  }
@@ -6,7 +6,7 @@
6
6
  * · **列定义唯一属主**(两方言):中央 DDL(`tidb-pool.ts` 的 `CREATE TABLE session_meta`、`pg-session-storage.ts` 的 `PG_SESSION_SCHEMA`)内插
7
7
  * {@link sessionMetaPlacementColumnsDdl}(先例:`SESSION_META_INCARNATION_COLUMN`);起服列册对账(`schema-consistency.ts`)从同一份建表文本解析期望列集。
8
8
  * 存量库的加列只由一次性迁移做,`ensureSchema` 不 ALTER(SCHEMA POLICY)。
9
- * · **语句唯一属主**:会话店(执行席、导入写口)与设备店(首绑 / 换绑)、一次性迁移(搬绑定 / 回填)的事务都借这里的语句,别处零手写。
9
+ * · **语句唯一属主**:会话店(执行席、导入写口)与设备店(首绑 / 换绑 / 绑定数)、一次性迁移(搬绑定 / 回填)的事务都借这里的语句,别处零手写。
10
10
  * 语句是方言无关的 `{ text, values }`(调用方用自己的连接跑:SqlDriver 的 `SqlTxConn`、node-pg 的客户端、mysql2 的连接都行)。
11
11
  *
12
12
  * ## 住客谓词(写与 judged 复核的唯一定址)
@@ -100,6 +100,16 @@ export declare function bindDeviceStatement(dialect: SqlDialect, root: string, o
100
100
  }, now: Date): PlacementStatement;
101
101
  /** rebind:writer(device, D) → writer(device, D'),按住客 ∧ 两属主列 ∧ rev 定址,`execution_rev + 1`(恒变列)。属主两列不动(换绑只在同一属主的设备之间)。 */
102
102
  export declare function rebindDeviceStatement(dialect: SqlDialect, root: string, occupant: SessionFace, owner: DeviceOwner, expectedRev: number, targetDeviceId: string, now: Date): PlacementStatement;
103
+ /**
104
+ * 带设备列的根会话行(非委派分区行上 `execution_device_id` 非空):绑定数的读只用它**缩小**读的行 —— 一条绑定必有设备列,反之不然;
105
+ * 是不是一条绑定只由行的唯一解码 {@link placementCellFromRow} + `boundDeviceOf` 判(SQL 不另判一遍)。两方言同一句。
106
+ */
107
+ export declare function deviceCellRowsStatement(): PlacementStatement;
108
+ /**
109
+ * 绑定数:根会话行上 writer(device, D) 的格数(设备店 `countDeviceBindings` 的读;只交一个数)。逐行过唯一解码 ⇒ 解码器拒的行
110
+ * (设备在而属主 / rev / 时刻缺、设备落在别的车道)原样抛 {@link ExecutionPlacementRowError},不当一条绑定数进去,也不当没有。
111
+ */
112
+ export declare function countDeviceBindingsOn(conn: PlacementRowsOn): Promise<number>;
103
113
  /** identical 臂补 mirror:absent / mirror → mirror,WHERE 住客谓词 ∧ 不是 writer。 */
104
114
  export declare function markMirrorStatement(dialect: SqlDialect, root: string, occupant: SessionFace): PlacementStatement;
105
115
  /** 回填(一次性迁移):无执行格、非委派分区、有 run 行的会话行 ⇒ writer(表唯一项)。幂等(第二次跑零行)。 */
@@ -1,7 +1,7 @@
1
1
  import { isExecutionLane } from "../execution-lane-caps.js";
2
2
  import { sessionFaceFromRow } from "../session-incarnation.js";
3
3
  import { toIso } from "./sql-row-helpers.js";
4
- import { WRITABLE, assertPlaceableLane, settledMirrorOutcome, settledPlaceOutcome, } from "../execution-placement.js";
4
+ import { WRITABLE, assertPlaceableLane, boundDeviceOf, settledMirrorOutcome, settledPlaceOutcome, } from "../execution-placement.js";
5
5
  export const SESSION_META_PLACEMENT_COLUMNS = [
6
6
  { name: "execution_role", mysql: "execution_role VARCHAR(16) NULL", pg: `execution_role VARCHAR(16) COLLATE "C"` },
7
7
  { name: "execution_lane", mysql: "execution_lane VARCHAR(32) NULL", pg: `execution_lane VARCHAR(32) COLLATE "C"` },
@@ -64,6 +64,17 @@ export function rebindDeviceStatement(dialect, root, occupant, owner, expectedRe
64
64
  `AND execution_device_owner_tenant = ${b.p(owner.tenant)} AND execution_device_owner_subject = ${b.p(owner.subject)} AND execution_rev = ${b.p(expectedRev)}`;
65
65
  return { text: `UPDATE session_meta SET ${set} WHERE ${where}`, values: b.values };
66
66
  }
67
+ export function deviceCellRowsStatement() {
68
+ return { text: `SELECT session_id, ${SESSION_META_PLACEMENT_READ_COLUMNS} FROM session_meta WHERE execution_device_id IS NOT NULL AND placement_kind IS NULL`, values: [] };
69
+ }
70
+ export async function countDeviceBindingsOn(conn) {
71
+ const s = deviceCellRowsStatement();
72
+ let bindings = 0;
73
+ for (const row of await conn(s.text, s.values))
74
+ if (boundDeviceOf(placementCellFromRow(text(row.session_id), row)) !== undefined)
75
+ bindings += 1;
76
+ return bindings;
77
+ }
67
78
  export function markMirrorStatement(dialect, root, occupant) {
68
79
  const b = binder(dialect);
69
80
  return { text: `UPDATE session_meta SET execution_role = '${MIRROR}' WHERE ${occupantPredicate(dialect, b.p, root, occupant)} AND ${NOT_WRITER}`, values: b.values };
@@ -1,6 +1,6 @@
1
1
  import { type UsageRow } from "../usage-analytics.js";
2
2
  import type { TaskStatus } from "@sema-agent/core";
3
- import { StoreBootRefusalError, type FenceLanded, type InProcessClaimFence, type CreateRunOutcome, type NewRunMeta, type RunIdemBinding, type RunListQuery, type RunRecord, type SessionSummary, type RunEvent, type PersistedTaskResult, type LatestRunRef } from "./store-contracts.js";
3
+ import { StoreBootRefusalError, type FenceLanded, type FencedRun, type InProcessClaimFence, type CreateRunOutcome, type NewRunMeta, type RunIdemBinding, type RunListQuery, type RunRecord, type SessionSummary, type RunEvent, type PersistedTaskResult, type LatestRunRef, type SettledLegMemoryObservation } from "./store-contracts.js";
4
4
  import type { RunStoreCheckpointProbe } from "./memory-run-store.js";
5
5
  import type { LedgerEventType } from "../trace/ledger-events.js";
6
6
  import { type SpaceCommitClaim, type SpaceCommitReading, type SpaceCommitState } from "../workspace-space-commit.js";
@@ -149,7 +149,7 @@ export declare class FileRunStore implements InProcessClaimFence {
149
149
  markResuming(taskId: string, instanceId: string): Promise<boolean>;
150
150
  getActiveTaskId(sessionId: string): Promise<string | undefined>;
151
151
  /** 认领当写栅栏用(契约 = `store-contracts.ts` 的 `InProcessClaimFence`):判、刷新活性(同步落盘)与 `write` 是同一个同步段。 */
152
- whileHoldingClaim(sessionId: string, taskId: string, write: () => FenceLanded): boolean;
152
+ whileHoldingClaim(sessionId: string, taskId: string, write: (run: FencedRun) => FenceLanded): boolean;
153
153
  getRun(taskId: string): Promise<RunRecord | undefined>;
154
154
  /** Undo THIS submission's binding (key + body fingerprint → null) — called only where the submit surface refuses the submission
155
155
  * before any work and terminalizes the row it just claimed (the sync leg's zero-work refusal, an execution-placement reject):
@@ -169,6 +169,11 @@ export declare class FileRunStore implements InProcessClaimFence {
169
169
  * `createdAt DESC, taskId DESC`,与本店 {@link FileRunStore.listSessions} 挑 `rn=1` 那一行的比较器逐字同一份)。
170
170
  */
171
171
  latestRunForSession(sessionId: string): Promise<LatestRunRef | undefined>;
172
+ /**
173
+ * [ref] —— 这个会话**最近一条已结腿**与它的记忆观测(规则属主 = `store-contracts.ts` 的 {@link SettledLegMemoryObservation};
174
+ * {@link SqlRunStore.latestMemoryObservationForSession} 的孪生:同一只已结谓词(`isTerminalRunStatus`)、同一个排序口径 —— 与本店 {@link FileRunStore.latestRunForSession} 的比较器逐字同一份)。
175
+ */
176
+ latestMemoryObservationForSession(sessionId: string): Promise<SettledLegMemoryObservation | undefined>;
172
177
  /** DISTINCT sessions newest-first by last activity (the CC /resume picker): latest run's preview/status + first/last/count. */
173
178
  listSessions(opts: {
174
179
  owner?: string;
@@ -7,7 +7,7 @@ import { randomBytes } from "node:crypto";
7
7
  import { AppendLog, atomicWriteFile, ensureDir, isProcessLive, processFingerprint, sanitizePathComponent, writeThenLink } from "@sema-agent/core";
8
8
  import { recordFailOpen } from "../observability/fail-open.js";
9
9
  import { replayJsonlSkipping } from "../observability/corrupt-read-seat.js";
10
- import { RUN_HOLDER_DEATH_CODES, RUN_ORPHANED_ERROR, RUN_STALLED_ERROR, StoreBootRefusalError, buildRunOrphanedError, readLegacyHolderDeathCode } from "./store-contracts.js";
10
+ import { RUN_HOLDER_DEATH_CODES, RUN_ORPHANED_ERROR, RUN_STALLED_ERROR, StoreBootRefusalError, buildRunOrphanedError, readLegacyHolderDeathCode, isTerminalRunStatus, settledLegObservationOf } from "./store-contracts.js";
11
11
  import { notifyRunTerminal } from "../observability/run-terminal.js";
12
12
  import { readRunIdentityCells, runIdentityCells } from "../identity-source.js";
13
13
  import { createInProcessSpaceCommitTable, fenceSpaceCommitAtTerminal, SPACE_COMMIT_RECORD_SCHEMA } from "../workspace-space-commit.js";
@@ -538,7 +538,7 @@ export class FileRunStore {
538
538
  return false;
539
539
  r.updatedAt = new Date();
540
540
  this.persist(r);
541
- write();
541
+ write({ instanceId: r.instanceId });
542
542
  return true;
543
543
  }
544
544
  async getRun(taskId) {
@@ -595,6 +595,16 @@ export class FileRunStore {
595
595
  }
596
596
  return latest === undefined ? undefined : { taskId: latest.taskId, owner: latest.owner, createdAt: latest.createdAt.toISOString() };
597
597
  }
598
+ async latestMemoryObservationForSession(sessionId) {
599
+ let latest;
600
+ for (const r of this.runs.values()) {
601
+ if (r.sessionId !== sessionId || !isTerminalRunStatus(r.status))
602
+ continue;
603
+ if (latest === undefined || r.createdAt.getTime() > latest.createdAt.getTime() || (r.createdAt.getTime() === latest.createdAt.getTime() && r.taskId > latest.taskId))
604
+ latest = r;
605
+ }
606
+ return latest === undefined ? undefined : settledLegObservationOf(latest.taskId, latest.result);
607
+ }
598
608
  async listSessions(opts) {
599
609
  const bySession = new Map();
600
610
  for (const r of this.runs.values()) {
@@ -19,12 +19,20 @@
19
19
  * 绝不打到 durable 店——那是 authorizer 的职权)。
20
20
  * - `fork(sourceId)` → 源在哪店在哪店 fork(路由未知时 host 先试,null 再 transient);新 id 记路由。
21
21
  * - `list`/`size`/`dispose` = transient 侧(host 店归 main runner 所有;不双列、不双清)。
22
+ * - 带 placement 的建(受信 spawner:后台子代,host 声明了委派分区)→ **host**(分区住 durable 店,名册钉住,见 {@link placed})。
23
+ *
24
+ * 规则一条:**一只后台子代的 durable 行在,它的转录就是 host 店委派分区里的一只 placed 行**(活过重启、随行同亡);transient 店只装
25
+ * 没有任何 durable 记录指着的会话(普通子任务、前台子代)。所以停驻不搬家:声明了分区的部署上,能停驻的后台子代生来就在 host 店
26
+ * (停驻挂点只验它在不在,`plugins/session-store.ts` 的 `attestChildSessionDurable`);host 不声明分区的部署没有停驻挂点(core 如实答 `no_park_lane`)。
27
+ *
28
+ * 声明面两条各读各的(引擎 `SessionStore.durability` / `placements` 两条注的分工,本类就是那条注里「瞬态车道与持久分区不同的路由店」):`placements` 从 host 逐字转发(分区的耐久);
29
+ * 顶层 `durability` **不转发、不声明** —— 它只说**未 placed** 的会话,而本店自己铸的未 placed 会话(无 id 的普通子任务、claim-create)住进程内短 TTL 店,
30
+ * 转发 host 的 `durable` 等于对子 Runner 的接线清单谎报「重启不丢」(引擎对缺席读 fail-closed 的 `process_local`,这里读法就是如实)。
22
31
  *
23
32
  * 路由表 LRU 上限 {@link ROUTE_MAX}:满额逐最老(refresh-on-use);被逐后下次 `acquire` 按上述规则重derive
24
33
  * (requireExisting 的 host-first 重试仍落对店),中途 touch/noteTaskRun 缺路由=落 transient(no-op 级)。
25
34
  */
26
35
  import { type SessionStore, type AcquiredSession, type SessionStoreSummary, type SessionPlacement, type PlacedSessionRow } from "@sema-agent/core";
27
- import { type DelegationTree } from "../delegated-session-owner.js";
28
36
  import type { ExecutionPlacementSeat } from "../execution-placement.js";
29
37
  import type { ForkToFn } from "./session-fork.js";
30
38
  /** acquire 选项形(core 5.48 SessionStore 契约):[ref] placement=受信 spawner 的分区建会话声明。 */
@@ -38,12 +46,7 @@ export declare class ForkRoutingSessionStore implements SessionStore {
38
46
  private readonly route;
39
47
  /** pin 时的店归属——unpin 恒回同店(LRU 逐出不拆对,见 pin/unpin)。 */
40
48
  private readonly pinnedAt;
41
- /** [ref] 晋升名册(探针 Finding A 修):已 promoteToHost 的 id **永久**钉 host——路由表会被 LRU
42
- * 逐出,而私店的 forget 只清 entries 缓存行、底层 repo 行不清且 sweep 扫不到(core session-store.js
43
- * 亲读),逐出后 transient-first 的 requireExisting 会把陈旧快照端回给 revive。本集不逐出(上界=
44
- * parked 子代数,天然小);pick/acquire 首查。 */
45
- private readonly promoted;
46
- /** [ref] placement 半场:placed id 名册(与 promoted 同姿势——不随路由 LRU 逐出)。placed 会话的
49
+ /** [ref] placement 半场:placed id 名册(不随路由 LRU 逐出)。placed 会话的
47
50
  * 真居所恒=host(分区在 durable 店),任何形的 acquire/touch/release 都不得落 transient——
48
51
  * 否则 transient 的 claim-create 会铸出同 id 影子会话,requireExisting 的 transient-first 顺序
49
52
  * 会让影子遮蔽真转录(F-7 顺序对 placed 反向成害)。 */
@@ -76,31 +79,6 @@ export declare class ForkRoutingSessionStore implements SessionStore {
76
79
  unpin(sessionId: string): void | Promise<void>;
77
80
  noteTaskRun(sessionId: string, taskId: string, runId?: string): void | Promise<void>;
78
81
  list(): Promise<SessionStoreSummary[]>;
79
- /**
80
- * [ref] 子代 park 晋升:把住在 transient(TTL)店的子会话**整树拷贝**进 host durable 店,然后
81
- * 让该 id 从此路由到 host——`ensureChildSessionDurable` 的「主动晋升」半场(1.263 的只查不迁形在
82
- * 拆店生产形下恒否决 park:子会话从不在 host 店,core 收 veto 即 expire checkpoint + settle failed,
83
- * cli 真机 14ms~2s expired 即此)。
84
- *
85
- * 三步缺一不可:
86
- * 1. 拷贝:transient 读整树(getEntries)+ 源 leaf → host 店 acquire(id)(durable 店的 acquire
87
- * 缺行即建行)→ storage.appendEntry 逐条 verbatim(重复 id 容忍=幂等续迁:上次晋升半途崩的
88
- * 残留行跳过)→ setLeafId(源 leaf)(分支树以源为准,不信 append 推进的 leaf)。
89
- * 2. transient.forget(id):`requireExisting` 的 acquire 是 **transient-first**(F-7 裁定)——私店
90
- * 副本不移除,revive 会续写进 1h TTL 副本,durable park 名存实亡。
91
- * 3. 路由记 host(此后 touch/pin/release 全走 host;pinnedAt 若记着 transient 一并改写,
92
- * unpin 不落错店)。
93
- *
94
- * 已在 host(路由或真行)⇒ 幂等直返。两店都无此会话 ⇒ 抛(调用方=park veto,诚实 fail-closed)。
95
- *
96
- * [ref]:宿主行**在建行那一笔里**带属主 `owner` —— 调用方按委派继承律算好(`delegated-session-owner.ts`:委派树根的属主,
97
- * 推不出 ⇒ 孤行哨兵;`tree` = 判据读到的委派树,判断用:宿主行记着别的树 ⇒ 拒),这里经宿主店的首写登记写下、再按律定夺(core `register` 契约:登记不判授权,判在复读)。
98
- * 宿主店里同 id 已有一行:记着这一棵委派树且无主 ⇒ 按同一条律认领(只有记录委派树的店);别的树的 / 属主不是它(别人先认领的空壳,或 local 店的无主空壳)⇒ 抛(停驻否决),
99
- * 转录不拷进别人的行;宿主店记不了 / 读不回属主 ⇒ 同样抛 —— 晋升出一只无主的转录行就是把它交给任何拿到 id 的人。
100
- */
101
- promoteToHost(sessionId: string, owner: string | null, tree: DelegationTree): Promise<void>;
102
- /** 晋升的建行那一笔([ref],规则见 {@link promoteToHost} 头注):宿主店首写登记 `owner`,然后按律定下宿主行的属主(与停驻快路同一只 `settleDelegatedOwner`)。 */
103
- private registerPromotedOwner;
104
82
  fork(sourceId: string, owner?: string | null): Promise<string | null>;
105
83
  get size(): number;
106
84
  dispose(): void | Promise<void>;
@@ -1,13 +1,11 @@
1
1
  import { SessionError } from "@sema-agent/core";
2
2
  import { recordFailOpen } from "../observability/fail-open.js";
3
- import { delegatedOwnerHostOf, settleDelegatedOwner } from "../delegated-session-owner.js";
4
3
  const ROUTE_MAX = 8192;
5
4
  export class ForkRoutingSessionStore {
6
5
  host;
7
6
  transient;
8
7
  route = new Map();
9
8
  pinnedAt = new Map();
10
- promoted = new Set();
11
9
  placed = new Set();
12
10
  placements;
13
11
  listPlaced;
@@ -50,7 +48,7 @@ export class ForkRoutingSessionStore {
50
48
  }
51
49
  }
52
50
  pick(id) {
53
- if (this.promoted.has(id) || this.placed.has(id))
51
+ if (this.placed.has(id))
54
52
  return this.host;
55
53
  const r = this.route.get(id);
56
54
  if (r !== undefined)
@@ -94,7 +92,7 @@ export class ForkRoutingSessionStore {
94
92
  this.remember(sessionId, "host");
95
93
  return a;
96
94
  }
97
- if (this.promoted.has(sessionId) || this.placed.has(sessionId)) {
95
+ if (this.placed.has(sessionId)) {
98
96
  const a = await this.host.acquire(sessionId, opts);
99
97
  this.remember(sessionId, "host");
100
98
  return a;
@@ -187,63 +185,6 @@ export class ForkRoutingSessionStore {
187
185
  list() {
188
186
  return this.transient.list?.() ?? Promise.resolve([]);
189
187
  }
190
- async promoteToHost(sessionId, owner, tree) {
191
- if (this.promoted.has(sessionId))
192
- return;
193
- if (this.route.get(sessionId) === "host") {
194
- this.promoted.add(sessionId);
195
- return;
196
- }
197
- let src;
198
- try {
199
- src = await this.transient.acquire(sessionId, { requireExisting: true });
200
- }
201
- catch {
202
- const probe = await this.host.acquire(sessionId, { requireExisting: true });
203
- await this.host.forget?.(probe.sessionId);
204
- this.promoted.add(sessionId);
205
- this.remember(sessionId, "host");
206
- return;
207
- }
208
- const entries = await src.session.getEntries();
209
- const leaf = await src.session.getLeafId();
210
- await this.registerPromotedOwner(sessionId, owner, tree);
211
- const dst = await this.host.acquire(sessionId);
212
- try {
213
- const storage = dst.session.getStorage();
214
- const existing = new Set((await dst.session.getEntries()).map((e) => e.id));
215
- for (const entry of entries) {
216
- if (existing.has(entry.id))
217
- continue;
218
- await storage.appendEntry(entry);
219
- }
220
- await storage.setLeafId(leaf);
221
- const verifyLeaf = await dst.session.getLeafId();
222
- if (verifyLeaf !== leaf)
223
- throw new Error(`session "${sessionId}" promotion verification failed (leaf mismatch after import)`);
224
- }
225
- finally {
226
- await this.host.forget?.(sessionId);
227
- }
228
- try {
229
- await this.transient.forget?.(sessionId);
230
- }
231
- catch {
232
- }
233
- if (this.pinnedAt.get(sessionId) === "transient")
234
- this.pinnedAt.set(sessionId, "host");
235
- this.promoted.add(sessionId);
236
- this.remember(sessionId, "host");
237
- }
238
- async registerPromotedOwner(sessionId, owner, tree) {
239
- const register = this.host.register;
240
- const host = delegatedOwnerHostOf(this.host);
241
- if (register === undefined || host === undefined) {
242
- throw new Error(`session "${sessionId}" cannot be promoted: the host session store cannot record or read back a session owner (register / headOf; placementOf and claimOwnerless together or neither), so the promoted transcript would land ownerless`);
243
- }
244
- await register.call(this.host, sessionId, owner);
245
- await settleDelegatedOwner(host, sessionId, owner, tree);
246
- }
247
188
  async fork(sourceId, owner) {
248
189
  const routed = this.route.get(sourceId);
249
190
  const tryFork = async (store, where) => {
@@ -40,11 +40,14 @@ export declare function isLabelValue(v: string): boolean;
40
40
  /**
41
41
  * The volume names the adapter itself mints on a sandbox pod — the ONE table (a patch volume / volumeMount must not reuse one: it would collide
42
42
  * with, or mount, the adapter's own volume). Today: the space's build-cache claim and the member-credential broker's lease volume. A volume the
43
- * adapter adds later is added HERE, and the patch judge below refuses it with no second guard.
43
+ * adapter adds later is added HERE, and the patch judge below refuses it with no second guard. The two read-floor volumes carry the
44
+ * supervisor binary per architecture (read-only ConfigMap volumes; `sandbox-read-floor.ts`).
44
45
  */
45
46
  export declare const ADAPTER_VOLUME_NAMES: {
46
47
  readonly cache: "ws-cache";
47
48
  readonly brokerLease: "sema-broker-lease";
49
+ readonly floorX86_64: "sema-floor-x86-64";
50
+ readonly floorAarch64: "sema-floor-aarch64";
48
51
  };
49
52
  /**
50
53
  * The confined, ADDITIVE pod-spec patch. Every field is purely additive —
@@ -8,7 +8,12 @@ const LABEL_VALUE = /^(?:[A-Za-z0-9](?:[-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$/;
8
8
  export function isLabelValue(v) {
9
9
  return LABEL_VALUE.test(v);
10
10
  }
11
- export const ADAPTER_VOLUME_NAMES = { cache: "ws-cache", brokerLease: BROKER_VOLUME_NAME };
11
+ export const ADAPTER_VOLUME_NAMES = {
12
+ cache: "ws-cache",
13
+ brokerLease: BROKER_VOLUME_NAME,
14
+ floorX86_64: "sema-floor-x86-64",
15
+ floorAarch64: "sema-floor-aarch64",
16
+ };
12
17
  const RESERVED_VOLUME_NAMES = new Set(Object.values(ADAPTER_VOLUME_NAMES));
13
18
  const agentContainerOf = (pod) => pod.spec.containers?.[0];
14
19
  const POD_SPEC_PATCH_FIELDS = {
@@ -1,5 +1,6 @@
1
1
  import { type Checkpoint, type CheckpointSummary, type CheckpointToken, type PendingSteerInput, type ReopenReason, type ResolveExpectation, type ExecutionOutcomeRecordWord, type GateOutcome, type ResumeOutcome, type StoreDurability, type StoreFidelity } from "@sema-agent/core";
2
- import { type CheckpointAskCandidate, type CtxRowRewrite, type CtxRowsRewrite, type DecidedApprovalRecord, type PendingCheckpoint, type PendingRowBinding } from "./checkpoint-store-sql.js";
2
+ import { type CheckpointAskCandidate, type CtxClaimRewrite, type CtxRowRewrite, type CtxRowsRewrite, type DecidedApprovalRecord, type PendingCheckpoint, type PendingRowBinding } from "./checkpoint-store-sql.js";
3
+ import { type FencedRun, type InProcessClaimFence } from "./store-contracts.js";
3
4
  import type { SealedCheckpointCtx } from "../http/checkpoint-ctx.js";
4
5
  export interface LocalCheckpointStoreOptions {
5
6
  /** taskId join for the pending card (the local FileRunStore's `getActiveTaskId`). Absent ⇒ `taskId: null`. */
@@ -7,6 +8,8 @@ export interface LocalCheckpointStoreOptions {
7
8
  /** E21 owner guard (the LocalSessionStore's owner read, `headOf(id)?.owner`: `undefined` = no session row). Absent ⇒ owner guard degrades
8
9
  * to null-owner-only (a non-null owner with no owner source purges NOTHING — fail-closed, mirrors the SQL EXISTS guard). */
9
10
  readSessionOwner?: (sessionId: string) => Promise<string | null | undefined>;
11
+ /** ctx 改写的认领栅栏({@link LocalCheckpointStore.rewriteCtxWhileClaimed}):同一数据根上的文件 run 店(进程内栅栏形)。缺席 ⇒ 那一口响亮抛(装配缺陷)。 */
12
+ claims?: InProcessClaimFence;
10
13
  }
11
14
  export declare class LocalCheckpointStore {
12
15
  /** [ref] 车1:托管留存声明 —— **诚实的 none**(与 local session 店同一条判据:本店的行没有按期删除的腿;
@@ -202,6 +205,12 @@ export declare class LocalCheckpointStore {
202
205
  * 只收对象,读腿只认对象,两条腿一个类型。
203
206
  */
204
207
  getCtx<T extends object = object>(sessionId: string): Promise<T | null>;
208
+ /**
209
+ * **认领栅栏下改写既有 ctx 行** —— 规则、结局闭集与 SQL 孪生 `SqlCheckpointStore.rewriteCtxWhileClaimed` 逐条同(那里是全文)。
210
+ * 本孪生的栅栏是进程内形(`store-contracts.ts` `InProcessClaimFence`):判认领、刷新活性、问腿判据与本口的落盘是**同一个同步段**(原子写本就同步),
211
+ * 中间没有让出,所以认领在写落定之前挪不动。只改既有档(档不在 ⇒ `context_absent`,不建档);形闸同 {@link LocalCheckpointStore.putCtx},在栅栏之前判。
212
+ */
213
+ rewriteCtxWhileClaimed(sessionId: string, taskId: string, ctx: SealedCheckpointCtx, legHolds: (run: FencedRun) => boolean): Promise<CtxClaimRewrite>;
205
214
  /**
206
215
  * 🔴 **一次性迁移的 ctx 行改写店腿**(local 孪生;`checkpoint-store-sql.ts` `CheckpointCtxRowsRewriter`,判词与 SQL 孪生 `rewriteCtxRows` 逐条同):
207
216
  * 逐档读(信封经读腿**同一只**判形 —— 读不出 ⇒ 计数、跳过、**不删**),`rewrite` 交回新体 ⇒ 信封原样(`sessionId` / `updatedAt` 不动:收割按 `updatedAt` 判)
@@ -11,6 +11,7 @@ import { quarantineUnreadableSidecar } from "./local-sidecar-quarantine.js";
11
11
  import { createZodColumnReader, decodeJsonColumn, foldJsonColumn, readStringArrayColumn } from "./sql-json-column.js";
12
12
  import { UNMANAGED_RETENTION } from "./retention-store-sql.js";
13
13
  import { assertJsonColumnWritable, createObjectColumnReader } from "./sql-json-column.js";
14
+ import { FENCE_LANDED } from "./store-contracts.js";
14
15
  function terminalAtOf(cp) {
15
16
  return Math.max(cp.createdAt + TERMINAL_BACKSTOP_MS, (cp.deadline ?? 0) + TERMINAL_GRACE_MS);
16
17
  }
@@ -326,6 +327,27 @@ export class LocalCheckpointStore {
326
327
  const rec = refusingCtx(sessionId, () => decodeJsonColumn(readFileSync(p, "utf8"), createCtxRecordReader(), `checkpoint-ctx ${ctxFileOf(sessionId)} for session ${JSON.stringify(sessionId)}`));
327
328
  return rec.sessionId === sessionId ? rec.ctx : null;
328
329
  }
330
+ async rewriteCtxWhileClaimed(sessionId, taskId, ctx, legHolds) {
331
+ const claims = this.opts.claims;
332
+ if (claims === undefined)
333
+ throw new Error("LocalCheckpointStore.rewriteCtxWhileClaimed: no claim fence is bound to this store (wiring defect: the local backend binds its own run store)");
334
+ const rec = { sessionId, updatedAt: Date.now(), ctx };
335
+ const text = JSON.stringify(rec);
336
+ assertJsonColumnWritable(text, createCtxRecordReader(), `checkpoint ctx for session ${JSON.stringify(sessionId)} (local claim-fenced rewrite)`);
337
+ const path = join(this.ctxDir, ctxFileOf(sessionId));
338
+ let outcome = "context_absent";
339
+ const held = claims.whileHoldingClaim(sessionId, taskId, (run) => {
340
+ if (!legHolds(run)) {
341
+ outcome = "claim_released";
342
+ }
343
+ else if (existsSync(path)) {
344
+ atomicWriteFile(this.tmpDir, path, text);
345
+ outcome = "written";
346
+ }
347
+ return FENCE_LANDED;
348
+ });
349
+ return held ? outcome : "claim_released";
350
+ }
329
351
  async rewriteCtxRows(rewrite) {
330
352
  const out = { scanned: 0, rewritten: 0, valuesRewritten: 0, unreadable: 0, tooLarge: 0 };
331
353
  for (const f of readdirSync(this.ctxDir)) {