@sema-agent/core 7.57.0 → 7.58.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 (198) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/dist/agents/subagent-steps.js +2 -4
  3. package/dist/brain/route-adjudicator.js +2 -1
  4. package/dist/core/a2a.d.ts +2 -1
  5. package/dist/core/a2a.js +23 -10
  6. package/dist/core/allow-entry.d.ts +2 -1
  7. package/dist/core/allow-entry.js +2 -1
  8. package/dist/core/ask-origin.d.ts +21 -2
  9. package/dist/core/ask-origin.js +5 -1
  10. package/dist/core/auto-compaction.d.ts +4 -0
  11. package/dist/core/auto-compaction.js +1 -1
  12. package/dist/core/auto-mode-directive.d.ts +29 -5
  13. package/dist/core/auto-mode-directive.js +38 -8
  14. package/dist/core/checkpoint-requirements.d.ts +7 -1
  15. package/dist/core/checkpoint-requirements.js +2 -0
  16. package/dist/core/checkpoint-store.d.ts +27 -11
  17. package/dist/core/checkpoint-store.js +13 -3
  18. package/dist/core/engine-notice.d.ts +1 -1
  19. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  20. package/dist/core/fs-write-gate-policy.js +7 -3
  21. package/dist/core/gate-fold.js +6 -3
  22. package/dist/core/gate-lanes.js +11 -2
  23. package/dist/core/git-worktree-env.d.ts +53 -11
  24. package/dist/core/git-worktree-env.js +96 -12
  25. package/dist/core/hooks.d.ts +4 -1
  26. package/dist/core/hooks.js +12 -5
  27. package/dist/core/human-input-projection.d.ts +1 -0
  28. package/dist/core/human-input-projection.js +3 -0
  29. package/dist/core/locked-config.d.ts +15 -1
  30. package/dist/core/locked-config.js +38 -2
  31. package/dist/core/mcp-call-meta.d.ts +66 -0
  32. package/dist/core/mcp-call-meta.js +103 -0
  33. package/dist/core/mcp-connection-pool.d.ts +3 -1
  34. package/dist/core/mcp-connection-pool.js +3 -1
  35. package/dist/core/mcp-failure.d.ts +7 -1
  36. package/dist/core/mcp-failure.js +10 -0
  37. package/dist/core/mcp-probe.d.ts +4 -0
  38. package/dist/core/mcp-probe.js +1 -1
  39. package/dist/core/mcp-server-link.d.ts +5 -2
  40. package/dist/core/mcp-server-spec.d.ts +46 -18
  41. package/dist/core/mcp-server-spec.js +1 -18
  42. package/dist/core/mcp.d.ts +6 -14
  43. package/dist/core/mcp.js +77 -37
  44. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  45. package/dist/core/memory-engine/scope-contract.js +80 -11
  46. package/dist/core/mode-policy.d.ts +8 -5
  47. package/dist/core/mode-policy.js +5 -4
  48. package/dist/core/mods/host.js +1 -1
  49. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  50. package/dist/core/mods/kernel/dispatch.js +10 -8
  51. package/dist/core/mods/kernel/events.d.ts +5 -1
  52. package/dist/core/mods/kernel/events.js +1 -1
  53. package/dist/core/mods/kernel/registration.d.ts +5 -1
  54. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  55. package/dist/core/mods/kernel/site-rules.js +10 -0
  56. package/dist/core/mods/package.d.ts +23 -0
  57. package/dist/core/mods/package.js +118 -0
  58. package/dist/core/mods/stations.d.ts +2 -2
  59. package/dist/core/mods/stations.js +1 -1
  60. package/dist/core/mods/tool-call.d.ts +5 -1
  61. package/dist/core/mods/tool-call.js +12 -3
  62. package/dist/core/path-guard-rows.d.ts +20 -0
  63. package/dist/core/path-guard-rows.js +11 -0
  64. package/dist/core/peer-seat.d.ts +186 -0
  65. package/dist/core/peer-seat.js +307 -0
  66. package/dist/core/present-plan-tool.d.ts +10 -1
  67. package/dist/core/present-plan-tool.js +46 -2
  68. package/dist/core/protocol-http-auth.d.ts +40 -29
  69. package/dist/core/protocol-http-auth.js +30 -32
  70. package/dist/core/redaction-marks.d.ts +16 -0
  71. package/dist/core/redaction-marks.js +16 -0
  72. package/dist/core/redaction-passes.js +8 -9
  73. package/dist/core/retention.d.ts +41 -15
  74. package/dist/core/retention.js +59 -12
  75. package/dist/core/rewrite-rejudge.d.ts +37 -0
  76. package/dist/core/rewrite-rejudge.js +40 -0
  77. package/dist/core/run-origin.d.ts +40 -0
  78. package/dist/core/run-origin.js +37 -0
  79. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  80. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  81. package/dist/core/runner/compaction-restate.d.ts +15 -6
  82. package/dist/core/runner/compaction-restate.js +28 -2
  83. package/dist/core/runner/contracts.d.ts +13 -5
  84. package/dist/core/runner/gate-exit.d.ts +18 -4
  85. package/dist/core/runner/gate-exit.js +5 -1
  86. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  87. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  88. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  89. package/dist/core/runner/prepare-config-doors.js +12 -10
  90. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  91. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  92. package/dist/core/runner/prepare-gate-stations.js +1 -1
  93. package/dist/core/runner/prepare-hands-readface.d.ts +7 -3
  94. package/dist/core/runner/prepare-hands-readface.js +4 -1
  95. package/dist/core/runner/prepare-memory.d.ts +3 -0
  96. package/dist/core/runner/prepare-memory.js +19 -23
  97. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  98. package/dist/core/runner/prepare-policy-chain.js +2 -2
  99. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  100. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  101. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  102. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  103. package/dist/core/runner/prepare-task.js +25 -12
  104. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  105. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  106. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  107. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  108. package/dist/core/runner/resume-admission.js +1 -1
  109. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  110. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  111. package/dist/core/runner/run-harness-handlers.js +1 -8
  112. package/dist/core/runner/run-identity-wiring.js +1 -0
  113. package/dist/core/runner/run-leg.js +5 -1
  114. package/dist/core/runner/run-notification-lane.js +3 -0
  115. package/dist/core/runner/terminal-account.js +3 -3
  116. package/dist/core/runner/tool-end-body.js +1 -0
  117. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  118. package/dist/core/runner/tool-occurrence.js +2 -1
  119. package/dist/core/runner/write-protection-station.d.ts +8 -2
  120. package/dist/core/runner/write-protection-station.js +2 -0
  121. package/dist/core/runner-deps.d.ts +2 -2
  122. package/dist/core/sensitive-path-policy.js +6 -7
  123. package/dist/core/session-log-transfer.d.ts +24 -0
  124. package/dist/core/session-log-transfer.js +166 -0
  125. package/dist/core/session-store.d.ts +84 -19
  126. package/dist/core/session-store.js +162 -24
  127. package/dist/core/session.d.ts +92 -1
  128. package/dist/core/shell-read-silence.js +1 -0
  129. package/dist/core/steer-replay.d.ts +4 -2
  130. package/dist/core/steer-replay.js +2 -1
  131. package/dist/core/store-contracts/checkpoint-store-contract.js +17 -0
  132. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  133. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  134. package/dist/core/store-contracts/session-store-contract.js +236 -2
  135. package/dist/core/task-event.d.ts +68 -8
  136. package/dist/core/task-registry-shared.d.ts +2 -1
  137. package/dist/core/task-spec.d.ts +37 -0
  138. package/dist/core/task-stream.d.ts +2 -1
  139. package/dist/core/terminal-cause.d.ts +1 -1
  140. package/dist/core/tool-catalog-entries.js +1 -0
  141. package/dist/core/tool-result-store.d.ts +17 -10
  142. package/dist/core/tool-result-store.js +3 -1
  143. package/dist/core/types.d.ts +1 -1
  144. package/dist/core/untrusted-egress.d.ts +0 -2
  145. package/dist/core/untrusted-egress.js +10 -14
  146. package/dist/core/wiring-manifest.d.ts +12 -3
  147. package/dist/core/wiring-manifest.js +4 -3
  148. package/dist/core/workspace-snapshot.d.ts +44 -0
  149. package/dist/core/workspace-snapshot.js +34 -0
  150. package/dist/core/write-protect.d.ts +43 -3
  151. package/dist/core/write-protect.js +43 -16
  152. package/dist/engine/execution-env/node-execution-env.js +15 -11
  153. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  154. package/dist/engine/harness/agent-harness.d.ts +5 -0
  155. package/dist/engine/harness/agent-harness.js +2 -0
  156. package/dist/engine/harness/types.d.ts +48 -7
  157. package/dist/engine/harness/types.js +5 -1
  158. package/dist/engine/llm/types.d.ts +12 -3
  159. package/dist/engine/llm/types.js +1 -1
  160. package/dist/engine/session/import-validate.js +3 -0
  161. package/dist/engine/session/memory-repo.d.ts +17 -9
  162. package/dist/engine/session/memory-repo.js +44 -34
  163. package/dist/engine/session/repo-utils.d.ts +22 -4
  164. package/dist/engine/session/repo-utils.js +49 -1
  165. package/dist/engine/session/storage-base.d.ts +10 -1
  166. package/dist/engine/session/storage-base.js +7 -1
  167. package/dist/index.d.ts +13 -6
  168. package/dist/index.js +10 -4
  169. package/dist/internal/harness-types.d.ts +1 -1
  170. package/dist/internal/harness.d.ts +2 -2
  171. package/dist/internal/harness.js +2 -2
  172. package/dist/stores/file/index.d.ts +4 -1
  173. package/dist/stores/file/index.js +4 -1
  174. package/dist/stores/file/session-store.d.ts +15 -8
  175. package/dist/stores/file/session-store.js +28 -13
  176. package/dist/tools/fs/fs-write.d.ts +6 -3
  177. package/dist/tools/fs/fs-write.js +8 -7
  178. package/dist/tools/fs/index.d.ts +3 -0
  179. package/dist/tools/fs/index.js +1 -1
  180. package/dist/tools/fs/safety.js +40 -8
  181. package/dist/tools/fs/search.js +6 -24
  182. package/dist/tools/fs/shell-read-check.d.ts +8 -1
  183. package/dist/tools/fs/shell-read-check.js +59 -15
  184. package/dist/tools/fs/shell-read-establish.js +2 -1
  185. package/dist/tools/fs/shell-read-identity.js +1 -1
  186. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  187. package/dist/tools/worktree.d.ts +42 -15
  188. package/dist/tools/worktree.js +60 -32
  189. package/package.json +4 -2
  190. package/test/export-surface.snapshot.json +63 -1
  191. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  192. package/wire-changes/core@7.58.0.json +2188 -0
  193. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  194. package/wire-changes/primitives@7.58.0.json +29 -0
  195. package/dist/primitives/credential-ref.d.ts +0 -89
  196. package/dist/primitives/credential-ref.js +0 -125
  197. package/dist/primitives/index.d.ts +0 -2
  198. package/dist/primitives/index.js +0 -1
@@ -344,8 +344,8 @@ export interface ExecutionEnvExecOptions {
344
344
  /**
345
345
  * Filesystem capability used by the harness.
346
346
  *
347
- * Paths passed to methods may be absolute or relative to {@link cwd}. Paths returned by file operations are addressed paths
348
- * in the filesystem namespace, but are not canonicalized through symlinks unless returned by {@link canonicalPath}.
347
+ * Paths passed to methods may be absolute or relative to {@link cwd}: an absolute path as written, a relative one ANCHORED at `cwd`; a `..` segment
348
+ * is the filesystem's to resolve (`bridge/../next`, `bridge` a symlink, is beside what it leads to), never folded lexically. Returned paths are addressed, not canonicalized unless from {@link canonicalPath}.
349
349
  *
350
350
  * Operation methods must never throw or reject. All filesystem failures, including unexpected backend failures, must be
351
351
  * encoded in the returned {@link Result}. Implementations must preserve this invariant.
@@ -353,9 +353,9 @@ export interface ExecutionEnvExecOptions {
353
353
  export interface FileSystem {
354
354
  /** Current working directory for relative paths. */
355
355
  cwd: string;
356
- /** Return an absolute addressed path without requiring it to exist and without resolving symlinks. */
356
+ /** An absolute addressed path, existence not required: ANCHOR ONLY (absolute as written, relative joined under {@link cwd}), no `..` folding, no symlink resolution; an environment with no working directory of its own answers an error. */
357
357
  absolutePath(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
358
- /** Join path segments in the filesystem namespace without requiring the result to exist. */
358
+ /** Join path segments in the filesystem namespace without requiring the result to exist, and without folding a `..`. */
359
359
  joinPath(parts: string[], abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
360
360
  /** Read a UTF-8 text file. */
361
361
  readTextFile(path: string, abortSignal?: AbortSignal): Promise<Result<string, FileError>>;
@@ -710,6 +710,10 @@ export interface ActiveWorktreeSession {
710
710
  originalCwd: string;
711
711
  baseSha: string;
712
712
  entered?: boolean;
713
+ /** The managed name (`.sema/worktrees/<name>`) the tree was CREATED under; absent for a tree entered by `path` or an older record. */
714
+ name?: string;
715
+ /** The branch the tree was CREATED on (`sema/<name>`), not refreshed when a shell switches branches; absent as `name` is (ExitWorktree then leaves every branch alone). */
716
+ branch?: string;
713
717
  }
714
718
  /**
715
719
  * REF-D3/D4 merge target: the session's WORKSPACE STATE container (nests {@link ActiveWorktreeSession}) —
@@ -942,6 +946,30 @@ export interface SessionHead {
942
946
  readonly incarnation: string | undefined;
943
947
  readonly leafId: string | null;
944
948
  }
949
+ /** Where a log stood when read: its entry count and last entry id (`null` = empty). Every append adds an id the log never held, so an
950
+ * appended log never shows the same mark again; a log replaced whole does only with as many entries ending on the same id. */
951
+ export interface SessionLogMark {
952
+ readonly length: number;
953
+ readonly lastEntryId: string | null;
954
+ }
955
+ /** What a conditional write of a session row expects of the row, judged by the repo INSIDE the write's own step (`sessionRowMatches`); a
956
+ * miss is refused `SessionError("conflict")` with nothing written, as the leaf CAS refuses a stale append. It is the row as a read of it
957
+ * answered: `row` = that read's owner and occupant cell (a {@link SessionHead} serves; `null` = no row), `log` (when the log binds) = the
958
+ * log's mark as read — a replacement judged against the log binds it, a deletion owed to the occupant does not. */
959
+ export interface SessionRowExpectation {
960
+ readonly row: {
961
+ readonly owner: string | null;
962
+ readonly incarnation: string | undefined;
963
+ } | null;
964
+ readonly log?: SessionLogMark;
965
+ }
966
+ /** One read of a row ({@link SessionRepo.readRow}): its metadata (placement included), its head and its whole log oldest-first, all of
967
+ * one row generation — the head is the one a write expecting this row names. */
968
+ export interface SessionRowRead<TMetadata extends SessionMetadata = SessionMetadata> {
969
+ readonly metadata: TMetadata;
970
+ readonly head: SessionHead;
971
+ readonly entries: SessionTreeEntry[];
972
+ }
945
973
  export interface JsonlSessionMetadata extends SessionMetadata {
946
974
  cwd: string;
947
975
  path: string;
@@ -1104,7 +1132,10 @@ export interface SessionRepo<TMetadata extends SessionMetadata = SessionMetadata
1104
1132
  /** Record activity on the row now: the time {@link list} answers as the row's `lastActiveAt` moves to now. A missing row is a no-op; a
1105
1133
  * fault rejects. Optional: a repo without it records only what its writes record. */
1106
1134
  touch?(sessionId: string): Promise<void>;
1107
- delete(metadata: TMetadata): Promise<void>;
1135
+ /** Remove the row and its whole log; an id with no row is a no-op. With `expect`, conditional: the repo judges the row against it in the
1136
+ * removal's own step and on a miss — no row, another generation, or (when the log binds) another log — removes nothing and refuses
1137
+ * `SessionError("conflict")` ({@link readRow}: which repos judge it). */
1138
+ delete(metadata: TMetadata, expect?: SessionRowExpectation): Promise<void>;
1108
1139
  /** A fork is a NEW row: `options.id` equal to the source's id is refused (`invalid_fork_target`) — onto its source it would mint a new occupant over the source's own transcript. */
1109
1140
  fork(source: TMetadata, options: SessionForkOptions & TCreateOptions): Promise<Session<TMetadata>>;
1110
1141
  /**
@@ -1116,10 +1147,19 @@ export interface SessionRepo<TMetadata extends SessionMetadata = SessionMetadata
1116
1147
  exportEntries?(sessionId: string): Promise<SessionTreeEntry[]>;
1117
1148
  /** The row's {@link SessionHead} in one read (`undefined` = no row); `TtlSessionStore` has a head read and an ownership pair only over a repo that has this. */
1118
1149
  headOf?(sessionId: string): Promise<SessionHead | undefined>;
1150
+ /** The row in one read — metadata, head and whole log (no compaction floor) of one generation; `undefined` = no row. A repo with this
1151
+ * judges every expectation its writes are handed; `TtlSessionStore` passes them, and has `delete` / `logTransfer`, only over such a repo. */
1152
+ readRow?(sessionId: string): Promise<SessionRowRead<TMetadata> | undefined>;
1119
1153
  /**
1120
1154
  * 2c session-sync: write a verbatim entry log (produced by {@link exportEntries} on another backend) into `sessionId` (the log is
1121
- * replaced, never the row: an existing row keeps its metadata whole; an absent id is a new row recording `owner`, `undefined` ⇒ `null` — the caller's principal, never the bundle's). The log MUST be passed through `validateEntriesForImport` first (the single fail-closed
1155
+ * replaced, never the row: an absent id is a new row recording `owner`, `undefined` ⇒ `null` — the caller's principal, never the bundle's;
1156
+ * an existing row keeps its metadata whole and takes the log only when it is already `owner`'s — compared null-safe — else the import is
1157
+ * refused `conflict`, and a placed row `placement_refused`, with nothing written; the owner check and the replacement are one step,
1158
+ * so a row another writer created after the caller looked is refused, never taken). The log MUST be passed through `validateEntriesForImport` first (the single fail-closed
1122
1159
  * invariant gate); a durable backend persists THAT function's output, it does not re-implement the checks.
1160
+ * With `options.expect`, the replacement is conditional on the row as the caller read it ({@link sessionRowMatches}, judged in the same
1161
+ * step as the owner check and the write): a miss writes nothing and is refused `SessionError("conflict")`. Answers the head of the row
1162
+ * the write committed (its owner and occupant, and the leaf the new log leaves it on), from that same step — never a later read.
1123
1163
  * Optional.
1124
1164
  *
1125
1165
  * design/171 §6.4 — `options.preserveActorAssertions` is the OPERATOR-level trusted-import
@@ -1131,7 +1171,8 @@ export interface SessionRepo<TMetadata extends SessionMetadata = SessionMetadata
1131
1171
  */
1132
1172
  importEntries?(sessionId: string, owner: string | undefined, entries: SessionTreeEntry[], options?: {
1133
1173
  preserveActorAssertions?: boolean;
1134
- }): Promise<void>;
1174
+ expect?: SessionRowExpectation;
1175
+ }): Promise<SessionHead>;
1135
1176
  }
1136
1177
  export interface JsonlSessionCreateOptions extends SessionCreateOptions {
1137
1178
  cwd: string;
@@ -128,7 +128,11 @@ export function normalizeWorkspaceState(value) {
128
128
  return undefined;
129
129
  if (w.entered !== undefined && typeof w.entered !== "boolean")
130
130
  return undefined;
131
- out.activeWorktree = { worktreeDir: w.worktreeDir, originalCwd: w.originalCwd, baseSha: w.baseSha, ...(w.entered === true ? { entered: true } : {}) };
131
+ if (w.name !== undefined && (typeof w.name !== "string" || !/^[A-Za-z0-9._/-]{1,64}$/.test(w.name)))
132
+ return undefined;
133
+ if (w.branch !== undefined && (typeof w.branch !== "string" || !/^sema\/[A-Za-z0-9._+-]{1,64}$/.test(w.branch)))
134
+ return undefined;
135
+ out.activeWorktree = { worktreeDir: w.worktreeDir, originalCwd: w.originalCwd, baseSha: w.baseSha, ...(w.entered === true ? { entered: true } : {}), ...(w.name !== undefined ? { name: w.name } : {}), ...(w.branch !== undefined ? { branch: w.branch } : {}) };
132
136
  }
133
137
  return out;
134
138
  }
@@ -387,6 +387,15 @@ export interface UserMessage {
387
387
  * old-session-verbatim posture as the engine-provenance fields above.
388
388
  */
389
389
  actor?: ActorAssertion;
390
+ /**
391
+ * What brought the ONE input this message carries, when its host said so (`"scheduled"`: the deployment's scheduler handed
392
+ * it) — the objective's `TaskSpec.runOrigin`. A message that carries several inputs (a resumed leg's continuation: parked
393
+ * steers, a wake's message, an approver's words) carries none, exactly like {@link UserMessage.actor}; each input's word rides its
394
+ * `human_input` frame. Attribution metadata only: never sent to a provider ({@link stripEngineMetadata} strips it), never a
395
+ * decision input. The session-import gate keeps a member of the closed set and drops anything else. Absent = the host said
396
+ * nothing.
397
+ */
398
+ runOrigin?: import("../../core/run-origin.js").RunOrigin;
390
399
  /**
391
400
  * The DELIVERY RECORD of a user-attachment frame: this message is the engine-minted frame carrying one attachment
392
401
  * the user declared on the human message it follows, or one file a landed compaction re-read
@@ -667,10 +676,10 @@ export interface ToolResultMessage<TDetails = unknown> {
667
676
  export type Message = UserMessage | AssistantMessage | ToolResultMessage;
668
677
  /**
669
678
  * RB-3 (stage S4 carry): strip the engine-provenance metadata fields from user messages before
670
- * serializing a Context to an external wire. The seven fields (`enginePrefixChars`/`engineSegments`/
671
- * `engineMinted`/`provenance`/`actor`/`engineNoteKey`/`attachment`) are INTERNAL coordination between the engine's
679
+ * serializing a Context to an external wire. The eight fields (`enginePrefixChars`/`engineSegments`/
680
+ * `engineMinted`/`provenance`/`actor`/`engineNoteKey`/`attachment`/`runOrigin`) are INTERNAL coordination between the engine's
672
681
  * minting side and its consumers (permission classifier, compaction summarizer, prompt suggestions,
673
- * multiplayer attribution, attachment delivery) — they must never reach a provider payload. The built-in brains construct
682
+ * multiplayer attribution, attachment delivery, run attribution) — they must never reach a provider payload. The built-in brains construct
674
683
  * their own wire shapes and are immune; a CUSTOM Brain that whole-object-serializes messages
675
684
  * (`JSON.stringify(context.messages)`) would leak them — run the array through this projection first.
676
685
  */
@@ -52,7 +52,7 @@ export function stripEngineMetadata(messages) {
52
52
  return messages.map((m) => {
53
53
  if (m.role !== "user")
54
54
  return m;
55
- const { enginePrefixChars: _a, engineSegments: _b, engineMinted: _c, provenance: _d, actor: _e, engineNoteKey: _f, attachment: _g, ...rest } = m;
55
+ const { enginePrefixChars: _a, engineSegments: _b, engineMinted: _c, provenance: _d, actor: _e, engineNoteKey: _f, attachment: _g, runOrigin: _h, ...rest } = m;
56
56
  return rest;
57
57
  });
58
58
  }
@@ -2,6 +2,7 @@ import { SessionError, normalizeAnnouncedListing, normalizeReminderMark, normali
2
2
  import { leafIdAfterEntry } from "./storage-base.js";
3
3
  import { parseSessionTimestampMs } from "./timestamps.js";
4
4
  import { flattenableUserText, normalizeEngineSegments } from "../../core/untrusted-text.js";
5
+ import { isRunOrigin } from "../../core/run-origin.js";
5
6
  import { readStoredPromptEpoch } from "../../prompt-assembly/epoch.js";
6
7
  import { MAX_MINTED_TOOL_RESULT_REF_CHARS } from "../../core/tool-result-store.js";
7
8
  import { PERSISTED_OUTPUT_REFS_MAX_ENTRIES, SKILL_RETENTION_PER_SKILL_MAX_CHARS, SKILL_RETENTION_TOTAL_MAX_CHARS, } from "../compaction/utils.js";
@@ -284,6 +285,8 @@ function normalizeEngineProvenanceStamp(message, preserveActorAssertions = false
284
285
  }
285
286
  if (m.attachment !== undefined)
286
287
  delete m.attachment;
288
+ if (m.runOrigin !== undefined && !isRunOrigin(m.runOrigin))
289
+ delete m.runOrigin;
287
290
  if (m.engineMinted !== undefined && m.engineMinted !== true)
288
291
  delete m.engineMinted;
289
292
  if (m.provenance !== undefined && m.provenance !== "engine-note")
@@ -1,29 +1,37 @@
1
- import { type Session, type SessionCreateOptions, type SessionForkOptions, type SessionHead, type SessionMetadata, type SessionRepo, type SessionRow, type SessionTreeEntry } from "../harness/types.js";
1
+ import { type Session, type SessionCreateOptions, type SessionForkOptions, type SessionHead, type SessionMetadata, type SessionRepo, type SessionRow, type SessionRowExpectation, type SessionRowRead, type SessionTreeEntry } from "../harness/types.js";
2
2
  export declare class InMemorySessionRepo implements SessionRepo<SessionMetadata, SessionCreateOptions> {
3
- private sessions;
3
+ private rows;
4
4
  /** Each row's last touch (epoch ms). */
5
5
  private touched;
6
6
  create(options?: SessionCreateOptions): Promise<Session>;
7
7
  open(metadata: SessionMetadata): Promise<Session>;
8
- /** The row's head off the one session object that IS the row: every cell comes from that object, so a delete and re-create of the
9
- * id while this reads cannot mix two generations. */
8
+ /** The row's head off the one row that IS it: every cell comes from that row, so a delete and re-create of the id while this reads
9
+ * cannot mix two generations. */
10
10
  headOf(sessionId: string): Promise<SessionHead | undefined>;
11
+ /** The row in one synchronous read: its metadata, its head and a copy of its log, from the one row that is it. */
12
+ readRow(sessionId: string): Promise<SessionRowRead | undefined>;
11
13
  /** Every row, with its last {@link touch} as its activity time where it has one. This repo hands its sessions' storages out and never
12
14
  * sees their writes (an entry's own `timestamp` is the writer's data, not the time of the write), so a row never touched carries none
13
15
  * and a reader takes its `createdAt`. */
14
16
  list(): Promise<SessionRow[]>;
15
17
  /** Record activity on the row now (a missing row: nothing to record). The time lives and dies with the row: `delete` drops it. */
16
18
  touch(sessionId: string): Promise<void>;
17
- delete(metadata: SessionMetadata): Promise<void>;
19
+ /** Remove the row; with `expect`, only the row the expectation names, judged and removed in one synchronous step. */
20
+ delete(metadata: SessionMetadata, expect?: SessionRowExpectation): Promise<void>;
18
21
  fork(sourceMetadata: SessionMetadata, options: SessionForkOptions & SessionCreateOptions): Promise<Session>;
19
- /** 2c session-sync: the FULL log for export. InMemory holds everything (no F3 floor), so
20
- * `getEntries()` IS the full oldest-first log with `id`/`parentId` verbatim. */
22
+ /** 2c session-sync: the FULL log for export — {@link readRow}'s log (InMemory holds everything, no F3 floor: the full oldest-first log
23
+ * with `id`/`parentId` verbatim). A missing row is `not_found`. */
21
24
  exportEntries(sessionId: string): Promise<SessionTreeEntry[]>;
22
25
  /** 2c session-sync: import a verbatim log into `sessionId`. The single invariant gate runs first
23
- * ({@link validateEntriesForImport}, fail-closed); a new row records `owner`, an existing row keeps its metadata whole.
26
+ * ({@link validateEntriesForImport}, fail-closed); then, in one synchronous step, the row standing now is judged — the expectation
27
+ * (`options.expect`, {@link sessionRowMatches}) and the write law (`importRowCells`: a new row records `owner`, an existing row keeps its
28
+ * metadata whole and must already be `owner`'s) — and the log replaced; the head answered is the new row's.
24
29
  * design/171: the operator's trusted-import flag is forwarded to the gate that persists — see
25
30
  * SessionRepo.importEntries. */
26
31
  importEntries(sessionId: string, owner: string | undefined, entries: SessionTreeEntry[], options?: {
27
32
  preserveActorAssertions?: boolean;
28
- }): Promise<void>;
33
+ expect?: SessionRowExpectation;
34
+ }): Promise<SessionHead>;
35
+ /** Lay a row down under its id: one storage, one session over it, the metadata it was built with. */
36
+ private lay;
29
37
  }
@@ -1,15 +1,16 @@
1
1
  import { SessionError } from "../harness/types.js";
2
2
  import { validateEntriesForImport } from "./import-validate.js";
3
3
  import { InMemorySessionStorage } from "./memory-storage.js";
4
- import { assertForkTarget, createSessionId, createTimestamp, forkRowCells, frozenRow, getEntriesToFork, headOfSession, importRowCells, incarnationCell, ownerCell, toSession } from "./repo-utils.js";
4
+ import { resolveLeafId } from "./storage-base.js";
5
+ import { assertForkTarget, createSessionId, createTimestamp, forkRowCells, frozenRow, getEntriesToFork, headOfSession, importRowCells, incarnationCell, ownerCell, rowExpectationMissed, sessionRowMatches, toSession } from "./repo-utils.js";
5
6
  export class InMemorySessionRepo {
6
- sessions = new Map();
7
+ rows = new Map();
7
8
  touched = new Map();
8
9
  async create(options = {}) {
9
10
  if (options.id !== undefined) {
10
- const existing = this.sessions.get(options.id);
11
+ const existing = this.rows.get(options.id);
11
12
  if (existing)
12
- return existing;
13
+ return existing.session;
13
14
  }
14
15
  const metadata = frozenRow({
15
16
  id: options.id ?? createSessionId(),
@@ -17,35 +18,41 @@ export class InMemorySessionRepo {
17
18
  ...incarnationCell(undefined),
18
19
  ...ownerCell(options.owner),
19
20
  });
20
- const storage = new InMemorySessionStorage({ metadata });
21
- const session = toSession(storage);
22
- this.sessions.set(metadata.id, session);
23
- return session;
21
+ return this.lay(metadata, []).session;
24
22
  }
25
23
  async open(metadata) {
26
- const session = this.sessions.get(metadata.id);
27
- if (!session) {
24
+ const row = this.rows.get(metadata.id);
25
+ if (!row) {
28
26
  throw new SessionError("not_found", `Session not found: ${metadata.id}`);
29
27
  }
30
- return session;
28
+ return row.session;
31
29
  }
32
30
  async headOf(sessionId) {
33
- const row = this.sessions.get(sessionId);
34
- return row === undefined ? undefined : headOfSession(row);
31
+ const row = this.rows.get(sessionId);
32
+ return row === undefined ? undefined : headOfSession(row.session);
33
+ }
34
+ async readRow(sessionId) {
35
+ const row = this.rows.get(sessionId);
36
+ if (row === undefined)
37
+ return undefined;
38
+ const entries = await row.storage.getEntries();
39
+ return { metadata: row.metadata, head: { owner: row.metadata.owner ?? null, incarnation: row.metadata.incarnation, leafId: resolveLeafId(entries) }, entries };
35
40
  }
36
41
  async list() {
37
- return Promise.all([...this.sessions.entries()].map(async ([id, session]) => {
38
- const meta = await session.getMetadata();
42
+ return [...this.rows.entries()].map(([id, row]) => {
39
43
  const touched = this.touched.get(id);
40
- return touched !== undefined ? { ...meta, lastActiveAt: touched } : meta;
41
- }));
44
+ return touched !== undefined ? { ...row.metadata, lastActiveAt: touched } : row.metadata;
45
+ });
42
46
  }
43
47
  async touch(sessionId) {
44
- if (this.sessions.has(sessionId))
48
+ if (this.rows.has(sessionId))
45
49
  this.touched.set(sessionId, Date.now());
46
50
  }
47
- async delete(metadata) {
48
- this.sessions.delete(metadata.id);
51
+ async delete(metadata, expect) {
52
+ const row = this.rows.get(metadata.id);
53
+ if (!sessionRowMatches(expect, row?.metadata, () => row.storage.logMarkNow()))
54
+ throw rowExpectationMissed(metadata.id, "delete");
55
+ this.rows.delete(metadata.id);
49
56
  this.touched.delete(metadata.id);
50
57
  }
51
58
  async fork(sourceMetadata, options) {
@@ -57,25 +64,28 @@ export class InMemorySessionRepo {
57
64
  createdAt: createTimestamp(),
58
65
  ...forkRowCells(await source.getMetadata(), options.owner),
59
66
  });
60
- const storage = new InMemorySessionStorage({ metadata, entries: forkedEntries });
61
- const session = toSession(storage);
62
- this.sessions.set(metadata.id, session);
63
- return session;
67
+ return this.lay(metadata, forkedEntries).session;
64
68
  }
65
69
  async exportEntries(sessionId) {
66
- const session = await this.open({ id: sessionId, createdAt: "" });
67
- return session.getStorage().getEntries();
70
+ const row = await this.readRow(sessionId);
71
+ if (row === undefined)
72
+ throw new SessionError("not_found", `Session not found: ${sessionId}`);
73
+ return row.entries;
68
74
  }
69
75
  async importEntries(sessionId, owner, entries, options) {
70
76
  ownerCell(owner);
71
77
  const validated = validateEntriesForImport(entries, options);
72
- let prior = this.sessions.get(sessionId);
73
- let header = prior !== undefined ? await prior.getMetadata() : undefined;
74
- while (this.sessions.get(sessionId) !== prior) {
75
- prior = this.sessions.get(sessionId);
76
- header = prior !== undefined ? await prior.getMetadata() : undefined;
77
- }
78
- const metadata = frozenRow(importRowCells(sessionId, owner, header, createTimestamp()));
79
- this.sessions.set(sessionId, toSession(new InMemorySessionStorage({ metadata, entries: validated })));
78
+ const prior = this.rows.get(sessionId);
79
+ if (!sessionRowMatches(options?.expect, prior?.metadata, () => prior.storage.logMarkNow()))
80
+ throw rowExpectationMissed(sessionId, "import");
81
+ const metadata = frozenRow(importRowCells(sessionId, owner, prior?.metadata, createTimestamp()));
82
+ this.lay(metadata, validated);
83
+ return { owner: metadata.owner ?? null, incarnation: metadata.incarnation, leafId: resolveLeafId(validated) };
84
+ }
85
+ lay(metadata, entries) {
86
+ const storage = new InMemorySessionStorage({ metadata, entries });
87
+ const row = { session: toSession(storage), storage, metadata };
88
+ this.rows.set(metadata.id, row);
89
+ return row;
80
90
  }
81
91
  }
@@ -1,4 +1,4 @@
1
- import { type SessionHead, type SessionMetadata, type SessionStorage, type SessionTreeEntry } from "../harness/types.js";
1
+ import { SessionError, type SessionHead, type SessionLogMark, type SessionMetadata, type SessionRowExpectation, type SessionStorage, type SessionTreeEntry } from "../harness/types.js";
2
2
  import type { Session } from "../harness/types.js";
3
3
  export declare function createSessionId(): string;
4
4
  /** The {@link SessionMetadata.incarnation} cell for a write laying a row's metadata down — the bundled repos' ONE mint point.
@@ -20,15 +20,33 @@ export declare function compareOccupants(before: {
20
20
  } | undefined, after: {
21
21
  readonly incarnation?: SessionHead["incarnation"];
22
22
  } | undefined): "same" | "different" | "unknown";
23
+ /**
24
+ * THE judge of a conditional row write ({@link SessionRowExpectation}), called by the repo inside the write's own atomic step with the
25
+ * row as it stands there — its owner and occupant cell (`undefined` = no row) and a reading of its log's mark, asked for only when the
26
+ * log binds: no expectation ⇒ no precondition; `row: null` ⇒ the row must be absent; otherwise the row must be there with the same owner
27
+ * and the same occupant cell and — when `log` is given — a log of the same mark ({@link sessionLogMarkOf}). The occupant cell is compared
28
+ * as written, an absent token equal to an absent one: this asks whether any write changed the row since the read the expectation came
29
+ * from, not whether two parties name one occupant ({@link compareOccupants}, where unknown is never the same) — and since every write
30
+ * that creates a row mints a token, a row without one cannot be created again, so an absent cell is one generation. An expectation that
31
+ * is not of this shape is refused (a `TypeError` naming the member), never read as no precondition.
32
+ */
33
+ export declare function sessionRowMatches(expect: SessionRowExpectation | undefined, row: {
34
+ readonly owner?: string | null;
35
+ readonly incarnation?: string | undefined;
36
+ } | undefined, logNow: () => SessionLogMark): boolean;
37
+ /** The refusal of a conditional row write whose expectation the row does not meet: nothing was written. */
38
+ export declare function rowExpectationMissed(sessionId: string, what: string): SessionError;
23
39
  /** The {@link SessionHead} a session object shows: its metadata's owner and occupant and its storage's leaf, off that one object. */
24
40
  export declare function headOfSession(session: Session): Promise<SessionHead>;
25
41
  /** The {@link SessionMetadata.owner} cell the write creating a row records: `owner` (a principal name, or `null`; `undefined` = none
26
42
  * named = `null`). An `owner` that is neither is refused before the write, so no row ever holds an owner cell that reads as neither
27
43
  * — a blank string included: it names nobody, so it is no owner and not anonymous either. */
28
44
  export declare function ownerCell(owner: unknown): Pick<SessionMetadata, "owner">;
29
- /** The metadata an import lays down. An import replaces the log, never the row: an existing row keeps its metadata whole (its creation
30
- * time, lineage, placement, occupant and owner were recorded by the write that created it); an absent id is a new row recording `owner`
31
- * and a fresh occupant. `owner` is judged either way. */
45
+ /** The metadata an import lays down, and the import's refusals — one reading for every repo that replaces a log. An import replaces
46
+ * the log, never the row: an absent id is a new row recording `owner` and a fresh occupant; an existing row keeps its metadata whole
47
+ * (its creation time, lineage, placement, occupant and owner were recorded by the write that created it), and only a row that is
48
+ * already the importer's takes the log — owners compared null-safe, `undefined` naming `null` — so another owner's row is refused
49
+ * `conflict` and a placed row `placement_refused`, before anything is written. `owner` is judged either way. */
32
50
  export declare function importRowCells(sessionId: string, owner: unknown, existing: SessionMetadata | undefined, createdAt: string): SessionMetadata;
33
51
  /** The one decoding of a stored owner cell: a principal name is the owner; absence (`undefined`, `null`) is anonymous. A cell that is
34
52
  * there but is neither (a blank string included) cannot be read as anyone's, and reading it as anonymous would admit every
@@ -32,6 +32,48 @@ export function compareOccupants(before, after) {
32
32
  return "unknown";
33
33
  return a === b ? "same" : "different";
34
34
  }
35
+ export function sessionRowMatches(expect, row, logNow) {
36
+ if (expect === undefined)
37
+ return true;
38
+ const want = readRowExpectation(expect);
39
+ if (want.row === null)
40
+ return row === undefined;
41
+ if (row === undefined || (row.owner ?? null) !== want.row.owner || row.incarnation !== want.row.incarnation)
42
+ return false;
43
+ if (want.log === undefined)
44
+ return true;
45
+ const now = logNow();
46
+ return now.length === want.log.length && now.lastEntryId === want.log.lastEntryId;
47
+ }
48
+ function readRowExpectation(expect) {
49
+ if (typeof expect !== "object" || expect === null)
50
+ throw new TypeError(`a session row expectation must be an object { row, log? }, got ${expect === null ? "null" : typeof expect}`);
51
+ const { row, log } = expect;
52
+ const mark = log === undefined ? undefined : readLogMark(log);
53
+ if (row === null)
54
+ return { row: null, ...(mark !== undefined ? { log: mark } : {}) };
55
+ if (typeof row !== "object" || row === undefined)
56
+ throw new TypeError(`a session row expectation's row must be the row's owner and occupant, or null (no row), got ${typeof row}`);
57
+ const { owner, incarnation } = row;
58
+ if (owner !== null && typeof owner !== "string")
59
+ throw new TypeError(`a session row expectation's row.owner must be a principal name or null, got ${typeof owner}`);
60
+ if (incarnation !== undefined && typeof incarnation !== "string")
61
+ throw new TypeError(`a session row expectation's row.incarnation must be a string or absent, got ${typeof incarnation}`);
62
+ return { row: { owner, incarnation }, ...(mark !== undefined ? { log: mark } : {}) };
63
+ }
64
+ function readLogMark(log) {
65
+ if (typeof log !== "object" || log === null)
66
+ throw new TypeError(`a session row expectation's log must be a log mark { length, lastEntryId }, got ${log === null ? "null" : typeof log}`);
67
+ const { length, lastEntryId } = log;
68
+ if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0)
69
+ throw new TypeError(`a session row expectation's log.length must be an integer ≥ 0`);
70
+ if (lastEntryId !== null && typeof lastEntryId !== "string")
71
+ throw new TypeError(`a session row expectation's log.lastEntryId must be an entry id or null, got ${typeof lastEntryId}`);
72
+ return { length, lastEntryId };
73
+ }
74
+ export function rowExpectationMissed(sessionId, what) {
75
+ return new SessionError("conflict", `session ${sessionId} is not the row the ${what} expected (it was deleted, created again, or written since it was read) — nothing was written; read the row again`);
76
+ }
35
77
  export async function headOfSession(session) {
36
78
  const meta = await session.getMetadata();
37
79
  return { owner: meta.owner ?? null, incarnation: meta.incarnation, leafId: await session.getStorage().getLeafId() };
@@ -49,7 +91,13 @@ export function ownerCell(owner) {
49
91
  }
50
92
  export function importRowCells(sessionId, owner, existing, createdAt) {
51
93
  const named = ownerCell(owner);
52
- return existing ?? { id: sessionId, createdAt, ...incarnationCell(undefined), ...named };
94
+ if (existing === undefined)
95
+ return { id: sessionId, createdAt, ...incarnationCell(undefined), ...named };
96
+ if (existing.placement !== undefined)
97
+ throw new SessionError("placement_refused", `session ${sessionId} belongs to the ${existing.placement.kind} placement partition — an import cannot replace its log`);
98
+ if ((existing.owner ?? null) !== named.owner)
99
+ throw new SessionError("conflict", `session ${sessionId} is not the importer's row — an import replaces only a log whose row the importer owns (or an anonymous row, by an anonymous import); nothing was written`);
100
+ return existing;
53
101
  }
54
102
  export function readOwnerCell(raw, sessionId) {
55
103
  if (raw === undefined || raw === null)
@@ -1,6 +1,12 @@
1
- import { type LeafEntry, type SessionMetadata, type SessionStorage, type SessionTreeEntry, type SessionWriteOptions } from "../harness/types.js";
1
+ import { type LeafEntry, type SessionLogMark, type SessionMetadata, type SessionStorage, type SessionTreeEntry, type SessionWriteOptions } from "../harness/types.js";
2
2
  /** Return the effective branch leaf after applying a session tree entry. */
3
3
  export declare function leafIdAfterEntry(entry: SessionTreeEntry): string | null;
4
+ /** A log's {@link SessionLogMark}: its length and its last entry's id — the one reading of the mark, for the reader that marks a log it
5
+ * read and for the repo that judges the log it is about to write over. */
6
+ export declare function sessionLogMarkOf(entries: readonly SessionTreeEntry[]): SessionLogMark;
7
+ /** The leaf a log leaves its session on: the leaf after its last entry (`null` for an empty log) — what a storage replaying the log
8
+ * answers, and so what a repo answers as the head of a row whose log it has just written or read whole. */
9
+ export declare function resolveLeafId(entries: readonly SessionTreeEntry[]): string | null;
4
10
  export declare abstract class BaseSessionStorage<TMetadata extends SessionMetadata = SessionMetadata> implements SessionStorage<TMetadata> {
5
11
  private readonly metadata;
6
12
  private readonly entries;
@@ -15,6 +21,9 @@ export declare abstract class BaseSessionStorage<TMetadata extends SessionMetada
15
21
  getFloorId(): string | null;
16
22
  getMetadata(): Promise<TMetadata>;
17
23
  getLeafId(): Promise<string | null>;
24
+ /** The log's mark ({@link sessionLogMarkOf}) as it stands at this instant, read synchronously: for a repo judging a row and writing it in
25
+ * one step with no await between them (an await would let a write through this storage land between the judgement and the write). */
26
+ logMarkNow(): SessionLogMark;
18
27
  protected createLeafEntry(leafId: string | null): LeafEntry;
19
28
  createEntryId(): Promise<string>;
20
29
  /**
@@ -32,7 +32,10 @@ function generateEntryId(byId) {
32
32
  export function leafIdAfterEntry(entry) {
33
33
  return entry.type === "leaf" ? entry.targetId : entry.id;
34
34
  }
35
- function resolveLeafId(entries) {
35
+ export function sessionLogMarkOf(entries) {
36
+ return { length: entries.length, lastEntryId: entries.length === 0 ? null : entries[entries.length - 1].id };
37
+ }
38
+ export function resolveLeafId(entries) {
36
39
  let leafId = null;
37
40
  for (const entry of entries) {
38
41
  leafId = leafIdAfterEntry(entry);
@@ -72,6 +75,9 @@ export class BaseSessionStorage {
72
75
  }
73
76
  return this.leafId;
74
77
  }
78
+ logMarkNow() {
79
+ return sessionLogMarkOf(this.entries);
80
+ }
75
81
  createLeafEntry(leafId) {
76
82
  if (leafId !== null && !this.byId.has(leafId)) {
77
83
  throw new SessionError("not_found", `Entry ${leafId} not found`);