@sema-agent/server 7.140.0 → 7.141.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 (200) hide show
  1. package/MIGRATION.md +290 -0
  2. package/README.md +1 -1
  3. package/README.zh-CN.md +1 -1
  4. package/USAGE.md +75 -13
  5. package/dist/approval-batch-census.d.ts +27 -0
  6. package/dist/approval-batch-census.js +27 -0
  7. package/dist/approval-card.d.ts +31 -16
  8. package/dist/approval-card.js +6 -3
  9. package/dist/approval.d.ts +15 -0
  10. package/dist/approval.js +10 -0
  11. package/dist/audit.d.ts +4 -2
  12. package/dist/audit.js +2 -2
  13. package/dist/boot/device-lane.d.ts +11 -0
  14. package/dist/boot/device-lane.js +16 -0
  15. package/dist/boot/engine-lease.d.ts +24 -3
  16. package/dist/boot/engine-lease.js +9 -2
  17. package/dist/boot/execution-env.js +8 -4
  18. package/dist/boot/memory-boundary.d.ts +2 -2
  19. package/dist/boot/memory-consolidation.d.ts +1 -1
  20. package/dist/boot/memory-consolidation.js +1 -1
  21. package/dist/boot/reapers.d.ts +2 -2
  22. package/dist/boot/resolve-spec.js +7 -4
  23. package/dist/boot/session-faces.d.ts +1 -1
  24. package/dist/boot/session-faces.js +4 -3
  25. package/dist/boot/shutdown.js +5 -0
  26. package/dist/boot/stage-05-execution-env.js +3 -1
  27. package/dist/boot/stage-06-runners.d.ts +0 -2
  28. package/dist/boot/stage-06-runners.js +1 -1
  29. package/dist/boot/stage-07-capability-layer.d.ts +0 -1
  30. package/dist/boot/stage-07-capability-layer.js +8 -10
  31. package/dist/boot/stage-08-reapers.d.ts +0 -1
  32. package/dist/boot/stage-09-leader.d.ts +0 -1
  33. package/dist/boot/stage-10-http-server.d.ts +0 -1
  34. package/dist/boot/stage-10-http-server.js +1 -0
  35. package/dist/boot/stores.js +10 -4
  36. package/dist/boot/web-admin.js +1 -0
  37. package/dist/capabilities/scenarios.d.ts +1 -1
  38. package/dist/capability-facts.d.ts +9 -0
  39. package/dist/capability-facts.js +9 -0
  40. package/dist/card-void.d.ts +38 -0
  41. package/dist/card-void.js +23 -0
  42. package/dist/config-catalog.js +11 -8
  43. package/dist/config-provider.d.ts +13 -13
  44. package/dist/config-provider.js +19 -33
  45. package/dist/config-types.d.ts +26 -8
  46. package/dist/config.js +55 -46
  47. package/dist/delegated-session-owner.d.ts +21 -19
  48. package/dist/delegated-session-owner.js +1 -1
  49. package/dist/device-store.d.ts +7 -0
  50. package/dist/device-store.js +3 -0
  51. package/dist/execution-config-root.d.ts +22 -0
  52. package/dist/execution-config-root.js +35 -0
  53. package/dist/execution-lane-caps.d.ts +49 -2
  54. package/dist/execution-lane-caps.js +90 -13
  55. package/dist/execution-placement.d.ts +3 -0
  56. package/dist/execution-placement.js +7 -0
  57. package/dist/fleet/drain-entry.d.ts +3 -0
  58. package/dist/hosted-posture.d.ts +8 -0
  59. package/dist/hosted-posture.js +4 -0
  60. package/dist/http/admission.js +3 -3
  61. package/dist/http/caller-trust.d.ts +3 -2
  62. package/dist/http/caller-trust.js +2 -1
  63. package/dist/http/dispatch.js +4 -0
  64. package/dist/http/live-frame.d.ts +24 -0
  65. package/dist/http/live-frame.js +16 -0
  66. package/dist/http/resume-legs.js +37 -20
  67. package/dist/http/route-table.js +2 -0
  68. package/dist/http/routes/approvals-assistant.js +1 -0
  69. package/dist/http/routes/capabilities.js +5 -4
  70. package/dist/http/routes/diagnostics.d.ts +0 -19
  71. package/dist/http/routes/diagnostics.js +16 -2
  72. package/dist/http/routes/memory-bundle.d.ts +2 -2
  73. package/dist/http/routes/memory-bundle.js +1 -1
  74. package/dist/http/routes/memory-compliance.js +1 -1
  75. package/dist/http/routes/memory-policy.js +2 -2
  76. package/dist/http/routes/run-permission-mode.d.ts +75 -0
  77. package/dist/http/routes/run-permission-mode.js +170 -0
  78. package/dist/http/routes/session-sync.d.ts +3 -6
  79. package/dist/http/routes/session-sync.js +7 -2
  80. package/dist/http/routes/sessions.js +5 -4
  81. package/dist/http/routes/tasks.js +63 -66
  82. package/dist/http/run-read-face.js +3 -3
  83. package/dist/http/send.d.ts +1 -1
  84. package/dist/http/send.js +2 -2
  85. package/dist/http/server.d.ts +9 -2
  86. package/dist/http/sse-log.d.ts +3 -8
  87. package/dist/http/stored-body-replay.d.ts +3 -3
  88. package/dist/http/stored-body-replay.js +3 -1
  89. package/dist/instruction-source-notice.d.ts +7 -0
  90. package/dist/instruction-source-notice.js +6 -6
  91. package/dist/mcp-assertion-header.d.ts +4 -0
  92. package/dist/mcp-assertion-header.js +5 -0
  93. package/dist/memory-posture.d.ts +1 -1
  94. package/dist/memory-scope.d.ts +4 -4
  95. package/dist/memory-scope.js +1 -1
  96. package/dist/memory-sync-client.d.ts +14 -2
  97. package/dist/memory-sync-client.js +80 -18
  98. package/dist/observability/fail-open.d.ts +30 -2
  99. package/dist/observability/fail-open.js +30 -2
  100. package/dist/observability/metrics.js +0 -1
  101. package/dist/observability/run-terminal.d.ts +6 -2
  102. package/dist/observability/run-terminal.js +25 -26
  103. package/dist/observability/secret-env-scrub.d.ts +20 -1
  104. package/dist/observability/secret-env-scrub.js +14 -0
  105. package/dist/orchestration/workflow-completion-inbox.d.ts +5 -2
  106. package/dist/orchestration/workflow-completion-inbox.js +13 -5
  107. package/dist/orchestration/workflow-notify-journal.d.ts +5 -3
  108. package/dist/orchestration/workflow-notify-journal.js +2 -1
  109. package/dist/permission-mode-admission.d.ts +68 -0
  110. package/dist/permission-mode-admission.js +23 -0
  111. package/dist/permission-rule-list.d.ts +55 -6
  112. package/dist/permission-rule-list.js +52 -5
  113. package/dist/plugins/caching-session-store.d.ts +6 -0
  114. package/dist/plugins/caching-session-store.js +3 -0
  115. package/dist/plugins/checkpoint-store-sql.d.ts +65 -17
  116. package/dist/plugins/checkpoint-store-sql.js +74 -3
  117. package/dist/plugins/device-store-sql.d.ts +5 -2
  118. package/dist/plugins/device-store-sql.js +4 -1
  119. package/dist/plugins/execution-placement-sql.d.ts +11 -1
  120. package/dist/plugins/execution-placement-sql.js +12 -1
  121. package/dist/plugins/file-run-store.d.ts +2 -2
  122. package/dist/plugins/file-run-store.js +1 -1
  123. package/dist/plugins/fork-routing-session-store.d.ts +10 -32
  124. package/dist/plugins/fork-routing-session-store.js +2 -61
  125. package/dist/plugins/k8s-exec-protocol.d.ts +4 -1
  126. package/dist/plugins/k8s-exec-protocol.js +6 -1
  127. package/dist/plugins/local-checkpoint-store.d.ts +10 -1
  128. package/dist/plugins/local-checkpoint-store.js +22 -0
  129. package/dist/plugins/local-session-store.d.ts +227 -35
  130. package/dist/plugins/local-session-store.js +518 -37
  131. package/dist/plugins/local-session-window.d.ts +17 -3
  132. package/dist/plugins/local-session-window.js +7 -13
  133. package/dist/plugins/memory-run-store.d.ts +2 -2
  134. package/dist/plugins/memory-run-store.js +1 -1
  135. package/dist/plugins/one-time-migrations.d.ts +42 -2
  136. package/dist/plugins/one-time-migrations.js +65 -3
  137. package/dist/plugins/pg-pool.js +3 -2
  138. package/dist/plugins/pg-session-storage.d.ts +2 -0
  139. package/dist/plugins/pg-session-storage.js +3 -2
  140. package/dist/plugins/remote-env-e2b.d.ts +24 -3
  141. package/dist/plugins/remote-env-e2b.js +131 -18
  142. package/dist/plugins/remote-env-k8s.d.ts +20 -1
  143. package/dist/plugins/remote-env-k8s.js +148 -25
  144. package/dist/plugins/remote-env-local-docker.d.ts +25 -11
  145. package/dist/plugins/remote-env-local-docker.js +87 -21
  146. package/dist/plugins/run-store-sql.d.ts +3 -3
  147. package/dist/plugins/run-store-sql.js +4 -3
  148. package/dist/plugins/sandbox-read-floor.d.ts +273 -0
  149. package/dist/plugins/sandbox-read-floor.js +608 -0
  150. package/dist/plugins/session-ownership.d.ts +2 -1
  151. package/dist/plugins/session-placement.d.ts +17 -4
  152. package/dist/plugins/session-placement.js +2 -1
  153. package/dist/plugins/session-store.d.ts +18 -20
  154. package/dist/plugins/session-store.js +4 -12
  155. package/dist/plugins/store-backend.d.ts +31 -0
  156. package/dist/plugins/store-backend.js +21 -4
  157. package/dist/plugins/store-contracts.d.ts +9 -2
  158. package/dist/plugins/tidb-pool.js +2 -1
  159. package/dist/plugins/tidb-session-store.d.ts +4 -1
  160. package/dist/plugins/tidb-session-store.js +3 -2
  161. package/dist/run-cancel-context.d.ts +34 -0
  162. package/dist/run-cancel-context.js +7 -0
  163. package/dist/runs.d.ts +39 -12
  164. package/dist/runs.js +68 -53
  165. package/dist/security.d.ts +2 -2
  166. package/dist/server-secret-env.d.ts +2 -1
  167. package/dist/server-secret-env.js +2 -4
  168. package/dist/session-error-wire.d.ts +22 -4
  169. package/dist/session-error-wire.js +16 -0
  170. package/dist/session-incarnation.d.ts +9 -3
  171. package/dist/session-sync-kernel.d.ts +42 -1
  172. package/dist/session-sync-kernel.js +17 -0
  173. package/dist/session-sync.js +16 -4
  174. package/dist/sql-engine-coordinates.d.ts +49 -0
  175. package/dist/sql-engine-coordinates.js +27 -0
  176. package/dist/standing-answer-grant.d.ts +31 -2
  177. package/dist/standing-answer-grant.js +14 -2
  178. package/dist/store-posture.d.ts +1 -1
  179. package/dist/task-a2a.d.ts +1 -1
  180. package/dist/task-mcp.d.ts +1 -1
  181. package/dist/task-settings.d.ts +52 -25
  182. package/dist/task-settings.js +91 -28
  183. package/dist/terminal.d.ts +77 -20
  184. package/dist/terminal.js +66 -20
  185. package/dist/trace/core-keyset-guard.d.ts +79 -2
  186. package/dist/trace/exit-seat.d.ts +7 -0
  187. package/dist/trace/exit-seat.js +1 -0
  188. package/dist/trace/model-segment.d.ts +2 -2
  189. package/dist/trace/redact.js +323 -90
  190. package/dist/trace/self-minted-wire.d.ts +168 -2
  191. package/dist/trace/self-minted-wire.js +63 -0
  192. package/dist/verifier-pause-card.d.ts +8 -0
  193. package/dist/verifier-pause-card.js +19 -0
  194. package/dist/web-admin-client/apply-effective.d.ts +5 -7
  195. package/dist/web-admin-client/apply-effective.js +2 -2
  196. package/dist/web-admin-client/candidate-gate.d.ts +1 -1
  197. package/dist/web-admin-client/read-warnings.d.ts +2 -2
  198. package/docs/DEVICE-EXECUTOR-PROTOCOL.md +3 -2
  199. package/package.json +2 -2
  200. package/wire-changes/server@7.141.0.json +367 -0
@@ -2,7 +2,10 @@ import type { Pool as MySqlPool } from "mysql2/promise";
2
2
  import type { Pool as PgPool } from "pg";
3
3
  import { type ExecutionOutcomeRecordWord, type GateOutcome, type Checkpoint, type CheckpointGate, type CheckpointState, type CheckpointStore, type CheckpointSummary, type CheckpointToken, type PendingSteerInput, type ResumeOutcome, type ResolvedOutcome, type ResolveExpectation, type ReopenReason, type RiskDescriptor, type StoreDurability, type StoreFidelity, type ToolApprovalCard } from "@sema-agent/core";
4
4
  import { type ParkRowFacts, type RuleOfferProjection, type SkillCardFacts } from "../approval-card.js";
5
+ import type { KindlessBatchRowSource, KindlessBatchScan } from "../approval-batch-census.js";
5
6
  import { type SqlDialect, type SqlDriver } from "./sql-driver.js";
7
+ import type { SqlRunStore } from "./run-store-sql.js";
8
+ import type { FencedRun } from "./store-contracts.js";
6
9
  import type { RetentionDeclaration } from "@sema-agent/core";
7
10
  import type { SealedCheckpointCtx } from "../http/checkpoint-ctx.js";
8
11
  /** ctx 行改写店腿的读数(两孪生同形):扫到的可读行 · 回写成的行 · 回写成的行里改写函数报的改动数 · 读不出的行 · 改写之后一行装不下的行。 */
@@ -59,7 +62,8 @@ export declare function tokenFingerprint(token: string): string;
59
62
  * 型与值都只有一个来源:`approval-card.ts` 的 {@link parkRowFacts}(两只店各读自己手里的那只寄存行 `pendingAction`,
60
63
  * 交给它、原样展开)。继承而不是在这里逐键再写一遍:core 给这一臂再加一位同类事实时,改的只有那张 Pick 表。
61
64
  *
62
- * 技能卡三位({@link SkillCardFacts}:`boundGrantDigest` / `boundGrants` / `classifierNoRuling`)另有一只投影 {@link skillCardFacts},输入是 core 的检查点摘要而不是
65
+ * [ref]:授予绑定那一臂(`boundGrantDigest` / `boundGrantAbsence` 恰带其一)是 {@link ParkRowFacts} 的一部分,同样读自寄存行。
66
+ * 技能卡两位({@link SkillCardFacts}:`boundGrants` / `classifierNoRuling`)另有一只投影 {@link skillCardFacts},输入是 core 的检查点摘要而不是
63
67
  * 寄存行原值(清单只在哈希等于摘要时才配上 wire,校验点单点在 core —— 见 {@link skillCardFacts} 顶注);同一张行上与收件箱行逐字同值,在场才带。 */
64
68
  export interface PendingCheckpoint extends ParkRowFacts, SkillCardFacts {
65
69
  sessionId: string;
@@ -271,6 +275,12 @@ export declare const CHECKPOINT_ADDED_COLUMNS: ReadonlyArray<{
271
275
  export declare function assertCheckpointColumnSchema(query: (sql: string) => Promise<{
272
276
  rows: Record<string, unknown>[];
273
277
  }>, dialect: SqlDialect): Promise<void>;
278
+ /**
279
+ * 本店读者({@link boundedRuleOffers})**交给 core 读者的那份输入**:offer 扫描窗 {@link MAX_RULE_OFFER_SCAN} 与成员前缀帽({@link preboundBatchMembers})都扣在读之前,
280
+ * 不是列表的值原样透传。**唯一写法**:回读 / 铸行 / LOCAL 孪生三条腿与起服普查({@link SqlCheckpointStore.scanKindlessBatchRows} 的 `rule_suggestions` 载体)读同一份输入 ——
281
+ * 普查若对整只数组另判,「前 8 个成员合法、第 9 个是垃圾」的行本店读者读得出(走存量臂)而普查读不出,会把仍靠存量臂的行报成零。
282
+ */
283
+ export declare function boundedReaderInput(raw: unknown): unknown;
274
284
  /**
275
285
  * `pendingAction.ruleOffers` 的**铸行侧**投影(mint 面,与 {@link boundedToolInput} 同位同待遇)。
276
286
  *
@@ -460,8 +470,17 @@ interface SteerColumnRead {
460
470
  * 列有内容却读不出 ⇒ `lossy`(两个调用点对它的处置见 {@link SteerColumnRead})。
461
471
  */
462
472
  export declare function readPendingSteerQueueColumn(queueRaw: unknown): SteerColumnRead;
473
+ /** 认领栅栏下改写一行 ctx 的结局(闭集;SQL / local 两孪生同词):`written` 写了;`claim_released` 接下改写的那条腿此刻已不持有这条 run(认领放了 / 不在跑 / 腿判据答否)⇒ 零写;
474
+ * `context_absent` 持有、但会话没有 ctx 行 ⇒ 零写(不建行)。 */
475
+ export declare const CTX_CLAIM_REWRITES: readonly ["written", "claim_released", "context_absent"];
476
+ export type CtxClaimRewrite = (typeof CTX_CLAIM_REWRITES)[number];
477
+ /** SQL checkpoint 店的装配选项:托管留存声明 + ctx 改写的认领栅栏(同一只池上的 run 店)。 */
478
+ export interface SqlCheckpointStoreOptions {
479
+ readonly retention?: RetentionDeclaration;
480
+ readonly claims?: SqlRunStore;
481
+ }
463
482
  /** Dual-dialect durable CheckpointStore. See the file header for the dialect-delta ledger. */
464
- export declare class SqlCheckpointStore implements CheckpointStore {
483
+ export declare class SqlCheckpointStore implements CheckpointStore, KindlessBatchRowSource {
465
484
  protected readonly db: SqlDriver;
466
485
  protected readonly logger?: {
467
486
  info?(msg: string, meta?: unknown): void;
@@ -514,11 +533,12 @@ export declare class SqlCheckpointStore implements CheckpointStore {
514
533
  readonly execution: {
515
534
  readonly outcome: true;
516
535
  };
536
+ /** ctx 改写的认领栅栏({@link SqlCheckpointStore.rewriteCtxWhileClaimed}):后端装配绑**同一只池**上的 run 店(`plugins/store-backend.ts` 的 `checkpoint()`)。
537
+ * 缺席 ⇒ 那一口响亮抛(装配缺陷),其余口不读它。 */
538
+ private readonly claims;
517
539
  constructor(db: SqlDriver, logger?: {
518
540
  info?(msg: string, meta?: unknown): void;
519
- } | undefined, opts?: {
520
- readonly retention?: RetentionDeclaration;
521
- });
541
+ } | undefined, opts?: SqlCheckpointStoreOptions);
522
542
  /** Pick the dialect's SQL text. Both statements stay written out at the call site ON PURPOSE. */
523
543
  private q;
524
544
  /** JSON column binding. TiDB: plain `JSON.stringify`, stored verbatim. PG: `pgProtocolJsonStringify` —
@@ -691,18 +711,19 @@ export declare class SqlCheckpointStore implements CheckpointStore {
691
711
  */
692
712
  listPending(scope?: string): Promise<PendingCheckpoint[]>;
693
713
  /**
694
- * 🔴 [ref] —— 运维队列行的**技能卡三位**({@link SkillCardFacts})。值与收件箱行同源:core `summarizeCheckpoint` 对同一行投的摘要,经 {@link skillCardFacts} 这一只投影。
714
+ * 🔴 [ref] —— 运维队列行的**技能卡两位**({@link SkillCardFacts}:清单 / 成因词)。值与收件箱行同源:core `summarizeCheckpoint` 对同一行投的摘要,经 {@link skillCardFacts} 这一只投影。
715
+ * (授予绑定那一臂 —— 摘要 / 缺席词 —— 不在这里:[ref] 起由 {@link parkRowFacts} 读子树投出,本读口失败时它照在。)
695
716
  *
696
- * 为什么不像 {@link parkRowFacts} 那几位一样直接读 `pendingAction` 子树原值:三位里的**清单** `boundGrants` 在寄存行上是未经哈希校验的原值,core 只在摘要里「哈希等于摘要」
717
+ * 为什么不像 {@link parkRowFacts} 那几位一样直接读 `pendingAction` 子树原值:**清单** `boundGrants` 在寄存行上是未经哈希校验的原值,core 只在摘要里「哈希等于摘要」
697
718
  * 才发布它(「never a list beside a digest that binds another」);校验读口与哈希函数都不在 core 的公开导出面上,本仓既算不出也不该再写一份 ——
698
719
  * 于是要拿到校验过的清单,只有对这一行跑 core 的 `summarizeCheckpoint`,而它吃的是整只 {@link Checkpoint}(不是子树)。
699
720
  *
700
- * 读放大(如实):**只对行上真带三位之一的行**(摘要是串,或成因词键在场 —— {@link parkRowCarriesSkillCardFacts})多读该行一次整只快照;普通卡(绝大多数行)零额外读,
701
- * 主 SELECT 仍只取 `pendingAction` 子树(NP-3 不退)。这是一个**只增不改的代价**:带三位之一的待决行数 × 读次数(`/stream` 每连接每 3s 一拍)。
702
- * 🚧 清单校验读口成为 core 公开导出的那一版,本读口与门一并退役,三位改走 `parkRowFacts` 读原值经 core 的读口 —— 零额外读。
721
+ * 读放大(如实):**只对行上可能带两位之一的行**(摘要是串,或成因词键在场 —— {@link parkRowCarriesSkillCardFacts})多读该行一次整只快照;普通卡(绝大多数行)零额外读,
722
+ * 主 SELECT 仍只取 `pendingAction` 子树(NP-3 不退)。这是一个**只增不改的代价**:带两位之一的待决行数 × 读次数(`/stream` 每连接每 3s 一拍)。
723
+ * 🚧 清单校验读口成为 core 公开导出的那一版,本读口与门一并退役,两位改走 `parkRowFacts` 读原值经 core 的读口 —— 零额外读。
703
724
  *
704
725
  * 失败方向与 {@link readParkRowActionCell} 逐字同一条判据(展示/分诊材料、行级容忍 + 响亮、同一个 tag):整只快照在场却不是一只合法的检查点(读回的体坏了,或 core 的摘要读不动它)
705
- * ⇒ 只丢**这一行**的三位;行已不在待决(两次读之间被决/过期)⇒ 三位缺席;`not-text`(读腿漏了投影)原样抛。
726
+ * ⇒ 只丢**这一行**的两位(授予绑定那一臂照在);行已不在待决(两次读之间被决/过期)⇒ 两位缺席;`not-text`(读腿漏了投影)原样抛。
706
727
  */
707
728
  private readParkedSkillCardFacts;
708
729
  /**
@@ -836,6 +857,23 @@ export declare class SqlCheckpointStore implements CheckpointStore {
836
857
  * reader the read leg uses — BEFORE the statement runs: refuse loudly, leave the row on disk untouched. */
837
858
  putCtx(sessionId: string, ctx: SealedCheckpointCtx): Promise<void>;
838
859
  getCtx<T extends object = object>(sessionId: string): Promise<T | null>;
860
+ /**
861
+ * **认领栅栏下改写既有 ctx 行** —— 在飞 run 的切档口(`http/routes/run-permission-mode.ts`)把准入的模式词写回存储体的唯一写口。
862
+ *
863
+ * 规则:只有**接下这笔改写的那条腿**此刻仍持有这条 run 时才写 —— `taskId` 持有 `sessionId` 的会话认领、这条 run 在跑、且调用方的腿判据 `legHolds`
864
+ * 对锁住那一行的 {@link FencedRun} 答是(认领与 `running` 只认 taskId:续跑腿让同一个 taskId 停驻之后回到 `running`、认领仍在,旧腿迟到的改写不许盖掉续跑的新腿
865
+ * 写下的体 —— 那是 ABA,只有腿判据分得开;今天的腿身份 = 副本 `instanceId`(续跑的 CAS 赢点改写它)∧ 调用方进程里这条 run 的活流仍是接下改写的那一只)。
866
+ * 写在所绑 run 店的认领栅栏事务里
867
+ * (`SqlRunStore.whileHoldingClaim`:先锁 run 行、再锁认领行 —— 与终局 / 收割同序 —— 刷新活性,本口的锁读 + UPDATE 在同一个事务连接上)。
868
+ * 于是「这条 run 终局放掉认领 → 同会话新 run 写下它自己的 ctx → 本口迟到的改写」这一序**结构上不可能**盖掉新 run 的行:终局要等本事务提交才拿得到
869
+ * run 行的锁,拿到之后本口再来就判出不持有、一个字节都不写。`putCtx` 的无条件 upsert 只给持有认领的那几条腿自己的写点(提交 / 续跑 CAS 赢点)用;
870
+ * 不在腿里的写者走这一口。
871
+ * 只改**既有**行(锁读零行 ⇒ `context_absent`,不建行):切档改的是这条 run 提交时写下的那一行,没有那一行就没有要改的存储体。
872
+ * 结局闭集 {@link CtxClaimRewrite}:`written` / `claim_released`(接下改写的那条腿已不持有这条 run —— 认领放了 / 不在跑 / 腿判据答否:零写)/ `context_absent`(持有、无行:零写)。
873
+ * 腿判据在栅栏里同步问一次(锁已持有、写之前);它只读、不许 await。
874
+ * 编码与形闸同 {@link SqlCheckpointStore.putCtx}(写之前判,坏形响亮拒、盘上不动);一行装不下 ⇒ `StoreRowTooLargeError`。
875
+ */
876
+ rewriteCtxWhileClaimed(sessionId: string, taskId: string, ctx: SealedCheckpointCtx, legHolds: (run: FencedRun) => boolean): Promise<CtxClaimRewrite>;
839
877
  /**
840
878
  * 🔴 **一次性迁移的 ctx 行改写店腿**({@link CheckpointCtxRowsRewriter};用它的迁移与各自的行改写见那里,窗与删法见 `plugins/one-time-migrations.ts` 登记表;
841
879
  * 本店不知道改写是什么,只负责扫与回写):按 `session_id` 键集分页扫 `checkpoint_ctx`
@@ -845,6 +883,20 @@ export declare class SqlCheckpointStore implements CheckpointStore {
845
883
  * ⇒ 不计、不重试(新写者是本版写下的、已是新形;是旧版副本就由之后的起服再扫到)。一行装不下(如封签比明文长)⇒ 计 `tooLarge`、那一行留原样,其余照扫。
846
884
  */
847
885
  rewriteCtxRows(rewrite: CtxRowRewrite): Promise<CtxRowsRewrite>;
886
+ /**
887
+ * 起服普查的读口({@link KindlessBatchRowSource};用法、范围与『为什么只数不改』见 `approval-batch-census.ts` 头注)—— 两个 SQL 方言**同一份实现**:
888
+ * 按 `token` 键集分页扫 `checkpoint`(所有状态的行),取两个载体,**各按它的读者判**(判官都是 core `readRuleOffers` 给读出的 batch 打的 `kindlessForm` 记号,
889
+ * {@link countKindlessBatchOffers};一行里任一载体带旧形成员即算一行):
890
+ * · `rule_suggestions` 列(审批候选的落列)—— 读者是本店的回读口,吃的是 {@link boundedReaderInput}(扫描窗 + 成员前缀帽);普查读同一份输入;
891
+ * · blob 里 `pendingAction.ruleOffers`(引擎铸、本店原样存、`put` 不校验)—— 读者是引擎(整只数组,没有本店的窗),普查读整只数组;在场却不是列表 ⇒ 数进 `unreadableCells`。
892
+ * 预筛(只为省传输,**不是判官**):`rule_suggestions` 是原样存的 TEXT(转义写法可以不同于 `JSON.stringify`),所以只问 `IS NOT NULL`,不做字符串匹配;
893
+ * blob 是 JSON 承载列(MySQL 协议 JSON / PG jsonb 入库即规范化),它的 `pendingAction` 子树文本里一个字符串值 `batch` 恒以 `"batch"` 字面出现 ⇒ `LIKE '%"batch"%'` 对它是完备的
894
+ * (空白不同无妨:MySQL 协议 `"kind": "batch"`)。
895
+ * 读不出形的 cell(坏 JSON / 不是列该有的形;读口是 {@link decodeNullableJsonColumn} 同一只,只容忍「体」的问题,读腿漏投影的 `not-text` 原样抛)不计入行,
896
+ * 数进 `unreadableCells`(到不了读者,但不静默:`rule_suggestions` 坏 cell 在队列读面有 `server.approvals.rule-suggestions-cell-unreadable`,普查另出 warn)。
897
+ * 行指纹 = {@link tokenFingerprint}(token 是机密,永不进遥测)。**只读**:不改任何一行;逐页读、**不是原子快照**(页间别的副本的写入可以让一行被漏数或多数一行)。
898
+ */
899
+ scanKindlessBatchRows(): Promise<KindlessBatchScan>;
848
900
  /**
849
901
  * GC ctx rows whose lifecycle is over (bound to the checkpoint, don't leak):
850
902
  * a session with NO pending checkpoint, NO active run, AND not touched since `cutoff`.
@@ -883,16 +935,12 @@ export declare class SqlCheckpointStore implements CheckpointStore {
883
935
  export declare class TiDBCheckpointStore extends SqlCheckpointStore {
884
936
  constructor(pool: MySqlPool, logger?: {
885
937
  info?(msg: string, meta?: unknown): void;
886
- }, opts?: {
887
- readonly retention?: RetentionDeclaration;
888
- });
938
+ }, opts?: SqlCheckpointStoreOptions);
889
939
  }
890
940
  /** PostgreSQL binding — historical class name + ctor shape preserved. */
891
941
  export declare class PgCheckpointStore extends SqlCheckpointStore {
892
942
  constructor(pool: PgPool, logger?: {
893
943
  info?(msg: string, meta?: unknown): void;
894
- }, opts?: {
895
- readonly retention?: RetentionDeclaration;
896
- });
944
+ }, opts?: SqlCheckpointStoreOptions);
897
945
  }
898
946
  //# sourceMappingURL=checkpoint-store-sql.d.ts.map
@@ -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 } 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):
@@ -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) {
@@ -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 = {