@earendil-works/pi-durable 0.87.1 → 0.99.1

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 (168) hide show
  1. package/README.md +46 -4
  2. package/dist/documents.d.ts +66 -0
  3. package/dist/documents.d.ts.map +1 -0
  4. package/dist/documents.js +98 -0
  5. package/dist/documents.js.map +1 -0
  6. package/dist/entries.d.ts +13 -0
  7. package/dist/entries.d.ts.map +1 -0
  8. package/dist/entries.js +18 -0
  9. package/dist/entries.js.map +1 -0
  10. package/dist/env/index.d.ts +131 -0
  11. package/dist/env/index.d.ts.map +1 -0
  12. package/dist/env/index.js +45 -0
  13. package/dist/env/index.js.map +1 -0
  14. package/dist/env/node.d.ts +45 -0
  15. package/dist/env/node.d.ts.map +1 -0
  16. package/dist/env/node.js +908 -0
  17. package/dist/env/node.js.map +1 -0
  18. package/dist/env/utils/adaptive-publisher.d.ts +24 -0
  19. package/dist/env/utils/adaptive-publisher.d.ts.map +1 -0
  20. package/dist/env/utils/adaptive-publisher.js +79 -0
  21. package/dist/env/utils/adaptive-publisher.js.map +1 -0
  22. package/dist/env/utils/output-capture.d.ts +31 -0
  23. package/dist/env/utils/output-capture.d.ts.map +1 -0
  24. package/dist/env/utils/output-capture.js +238 -0
  25. package/dist/env/utils/output-capture.js.map +1 -0
  26. package/dist/env/utils/truncate.d.ts +71 -0
  27. package/dist/env/utils/truncate.d.ts.map +1 -0
  28. package/dist/env/utils/truncate.js +294 -0
  29. package/dist/env/utils/truncate.js.map +1 -0
  30. package/dist/errors.d.ts +15 -0
  31. package/dist/errors.d.ts.map +1 -0
  32. package/dist/errors.js +24 -0
  33. package/dist/errors.js.map +1 -0
  34. package/dist/harness/config.d.ts +20 -0
  35. package/dist/harness/config.d.ts.map +1 -0
  36. package/dist/harness/config.js +18 -0
  37. package/dist/harness/config.js.map +1 -0
  38. package/dist/harness/context.d.ts +27 -0
  39. package/dist/harness/context.d.ts.map +1 -0
  40. package/dist/harness/context.js +109 -0
  41. package/dist/harness/context.js.map +1 -0
  42. package/dist/harness/generation.d.ts +36 -0
  43. package/dist/harness/generation.d.ts.map +1 -0
  44. package/dist/harness/generation.js +266 -0
  45. package/dist/harness/generation.js.map +1 -0
  46. package/dist/harness/harness.d.ts +10 -0
  47. package/dist/harness/harness.d.ts.map +1 -0
  48. package/dist/harness/harness.js +266 -0
  49. package/dist/harness/harness.js.map +1 -0
  50. package/dist/harness/live.d.ts +40 -0
  51. package/dist/harness/live.d.ts.map +1 -0
  52. package/dist/harness/live.js +41 -0
  53. package/dist/harness/live.js.map +1 -0
  54. package/dist/harness/prompt.d.ts +24 -0
  55. package/dist/harness/prompt.d.ts.map +1 -0
  56. package/dist/harness/prompt.js +88 -0
  57. package/dist/harness/prompt.js.map +1 -0
  58. package/dist/harness/registry.d.ts +7 -0
  59. package/dist/harness/registry.d.ts.map +1 -0
  60. package/dist/harness/registry.js +309 -0
  61. package/dist/harness/registry.js.map +1 -0
  62. package/dist/harness/scheduler.d.ts +63 -0
  63. package/dist/harness/scheduler.d.ts.map +1 -0
  64. package/dist/harness/scheduler.js +605 -0
  65. package/dist/harness/scheduler.js.map +1 -0
  66. package/dist/harness/submissions.d.ts +24 -0
  67. package/dist/harness/submissions.d.ts.map +1 -0
  68. package/dist/harness/submissions.js +133 -0
  69. package/dist/harness/submissions.js.map +1 -0
  70. package/dist/harness/types.d.ts +358 -0
  71. package/dist/harness/types.d.ts.map +1 -0
  72. package/dist/harness/types.js +2 -0
  73. package/dist/harness/types.js.map +1 -0
  74. package/dist/harness/util.d.ts +14 -0
  75. package/dist/harness/util.d.ts.map +1 -0
  76. package/dist/harness/util.js +55 -0
  77. package/dist/harness/util.js.map +1 -0
  78. package/dist/ids.d.ts +6 -0
  79. package/dist/ids.d.ts.map +1 -0
  80. package/dist/ids.js +9 -0
  81. package/dist/ids.js.map +1 -0
  82. package/dist/index.d.ts +12 -1
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +10 -0
  85. package/dist/index.js.map +1 -1
  86. package/dist/session/forks.d.ts +10 -0
  87. package/dist/session/forks.d.ts.map +1 -0
  88. package/dist/session/forks.js +42 -0
  89. package/dist/session/forks.js.map +1 -0
  90. package/dist/session/observation.d.ts +28 -0
  91. package/dist/session/observation.d.ts.map +1 -0
  92. package/dist/session/observation.js +280 -0
  93. package/dist/session/observation.js.map +1 -0
  94. package/dist/session/session.d.ts +59 -0
  95. package/dist/session/session.d.ts.map +1 -0
  96. package/dist/session/session.js +380 -0
  97. package/dist/session/session.js.map +1 -0
  98. package/dist/session/transaction.d.ts +105 -0
  99. package/dist/session/transaction.d.ts.map +1 -0
  100. package/dist/session/transaction.js +718 -0
  101. package/dist/session/transaction.js.map +1 -0
  102. package/dist/storage/jsonl/index.d.ts +2 -0
  103. package/dist/storage/jsonl/index.d.ts.map +1 -0
  104. package/dist/storage/jsonl/index.js +2 -0
  105. package/dist/storage/jsonl/index.js.map +1 -0
  106. package/dist/storage/jsonl/node.d.ts +6 -0
  107. package/dist/storage/jsonl/node.d.ts.map +1 -0
  108. package/dist/storage/jsonl/node.js +8 -0
  109. package/dist/storage/jsonl/node.js.map +1 -0
  110. package/dist/storage/jsonl/storage.d.ts +115 -0
  111. package/dist/storage/jsonl/storage.d.ts.map +1 -0
  112. package/dist/storage/jsonl/storage.js +681 -0
  113. package/dist/storage/jsonl/storage.js.map +1 -0
  114. package/dist/storage/memory.d.ts +31 -14
  115. package/dist/storage/memory.d.ts.map +1 -1
  116. package/dist/storage/memory.js +208 -61
  117. package/dist/storage/memory.js.map +1 -1
  118. package/dist/storage/sqlite/database.d.ts +5 -1
  119. package/dist/storage/sqlite/database.d.ts.map +1 -1
  120. package/dist/storage/sqlite/database.js.map +1 -1
  121. package/dist/storage/sqlite/index.d.ts.map +1 -1
  122. package/dist/storage/sqlite/migrations.d.ts +1 -1
  123. package/dist/storage/sqlite/migrations.d.ts.map +1 -1
  124. package/dist/storage/sqlite/migrations.js +8 -1
  125. package/dist/storage/sqlite/migrations.js.map +1 -1
  126. package/dist/storage/sqlite/node.d.ts.map +1 -1
  127. package/dist/storage/sqlite/node.js +2 -2
  128. package/dist/storage/sqlite/node.js.map +1 -1
  129. package/dist/storage/sqlite/storage.d.ts +20 -14
  130. package/dist/storage/sqlite/storage.d.ts.map +1 -1
  131. package/dist/storage/sqlite/storage.js +159 -55
  132. package/dist/storage/sqlite/storage.js.map +1 -1
  133. package/dist/tasks.d.ts +6 -0
  134. package/dist/tasks.d.ts.map +1 -0
  135. package/dist/tasks.js +5 -0
  136. package/dist/tasks.js.map +1 -0
  137. package/dist/testing/assertions.d.ts +5 -0
  138. package/dist/testing/assertions.d.ts.map +1 -0
  139. package/dist/testing/assertions.js +25 -0
  140. package/dist/testing/assertions.js.map +1 -0
  141. package/dist/testing/index.d.ts +6 -0
  142. package/dist/testing/index.d.ts.map +1 -0
  143. package/dist/testing/index.js +5 -0
  144. package/dist/testing/index.js.map +1 -0
  145. package/dist/testing/runner.d.ts +10 -0
  146. package/dist/testing/runner.d.ts.map +1 -0
  147. package/dist/testing/runner.js +14 -0
  148. package/dist/testing/runner.js.map +1 -0
  149. package/dist/testing/storage-benchmark.d.ts +41 -0
  150. package/dist/testing/storage-benchmark.d.ts.map +1 -0
  151. package/dist/testing/storage-benchmark.js +351 -0
  152. package/dist/testing/storage-benchmark.js.map +1 -0
  153. package/dist/testing/storage-conformance.d.ts +4 -0
  154. package/dist/testing/storage-conformance.d.ts.map +1 -0
  155. package/dist/testing/storage-conformance.js +1122 -0
  156. package/dist/testing/storage-conformance.js.map +1 -0
  157. package/dist/testing/types.d.ts +19 -0
  158. package/dist/testing/types.d.ts.map +1 -0
  159. package/dist/testing/types.js +2 -0
  160. package/dist/testing/types.js.map +1 -0
  161. package/dist/types.d.ts +422 -54
  162. package/dist/types.d.ts.map +1 -1
  163. package/dist/types.js.map +1 -1
  164. package/docs/chord-delta-findings.md +1 -1
  165. package/docs/pico-v5-chord-usage.md +47 -60
  166. package/docs/pico-v5-handoff.md +469 -264
  167. package/docs/pico-v5.md +1523 -639
  168. package/package.json +30 -5
package/docs/pico-v5.md CHANGED
@@ -5,13 +5,18 @@ Pico5 uses existing package types as follows:
5
5
 
6
6
  ```ts
7
7
  import type {
8
+ AttachedReplicatedState,
8
9
  Context,
9
10
  Draft,
11
+ JsonRepresentation,
10
12
  JsonValue,
11
13
  ReplicatedState,
12
14
  } from "@earendil-works/chord";
13
- import { applyImmutable, type Op } from "@earendil-works/chord/delta";
15
+ import type { Op } from "@earendil-works/chord/delta";
14
16
  import type {
17
+ AssistantMessage,
18
+ CacheRetention,
19
+ DeferredHandle,
15
20
  Message,
16
21
  Models,
17
22
  ModelThinkingLevel,
@@ -19,6 +24,7 @@ import type {
19
24
  Tool,
20
25
  ToolReference,
21
26
  ToolResultMessage,
27
+ Transport,
22
28
  UserMessage,
23
29
  } from "@earendil-works/pi-ai";
24
30
 
@@ -47,6 +53,10 @@ The core rule is:
47
53
  - A **definition** is a typed token describing one document or document family.
48
54
  - A **source** exposes committed document changes to Chord without exposing a
49
55
  mutable object.
56
+ - A **turn** is one assistant response and the tool calls it makes. A **run**
57
+ is the sequence of turns from an admitted input to the final answer; turn
58
+ boundaries (section 6) sit between its turns. A conversation is busy while a
59
+ run is active.
50
60
 
51
61
  Required invariants:
52
62
 
@@ -55,10 +65,12 @@ Required invariants:
55
65
  3. All visible progress is durable. There is no volatile publication path.
56
66
  4. External effects do not run inside the Session mutation transaction.
57
67
  5. Entries and IDs are immutable and never reused after a committed write.
58
- 6. Document drafts are revoked when their transaction callback settles. Values
59
- assigned into a draft are copied by value.
68
+ 6. Document drafts are fully revoked when their transaction callback settles:
69
+ the Session synchronously prepares or aborts every open change at that point.
70
+ Values assigned into a draft are copied by value and must be strict JSON.
60
71
  7. The mutation line remains held through storage settlement and committed-state
61
- adoption. Listener callbacks run later, off the line.
72
+ adoption. Commit/close observers run synchronously only to capture immutable
73
+ state; document-state and watch user callbacks run later, off the line.
62
74
  8. An uncertain storage failure is fatal to the open Session. It publishes
63
75
  nothing and must be reopened. Preparation and checkpoint failures occur before
64
76
  storage admission and roll back normally.
@@ -69,20 +81,37 @@ The concrete JSON representations may add bookkeeping fields, but must preserve
69
81
  these contracts.
70
82
 
71
83
  ```ts
72
- type Id = number;
84
+ declare const idBrand: unique symbol;
85
+ type Id<Kind extends string, Type = unknown> = number & {
86
+ readonly [idBrand]: {
87
+ readonly kind: Kind;
88
+ readonly type: Type;
89
+ };
90
+ };
91
+ type ConversationId = Id<"conversation">;
92
+ type EntryId = Id<"entry">;
93
+ type TaskId<Result = unknown> = Id<"task", Result>;
94
+ type SubmissionId = Id<"submission">;
95
+ type DocumentId = Id<"document">;
96
+
97
+ declare const seqBrand: unique symbol;
73
98
  /** Strictly increases between commits; gaps are permitted. */
74
- type Seq = number;
75
- const ROOT_CONVERSATION_ID: Id = 1;
99
+ type Seq = number & { readonly [seqBrand]: "sequence" };
100
+ const ROOT_CONVERSATION_ID = 1 as ConversationId;
101
+
102
+ type ConversationOwnership =
103
+ | { readonly kind: "ownerless" }
104
+ | { readonly kind: "task"; readonly taskId: TaskId };
76
105
 
77
106
  type ConversationRecord = {
78
- readonly id: Id;
107
+ readonly id: ConversationId;
79
108
  readonly parent?: {
80
- readonly conversationId: Id;
81
- readonly at: Id;
109
+ readonly conversationId: ConversationId;
110
+ readonly at: EntryId;
82
111
  };
83
112
  readonly owner?: {
84
- readonly conversationId: Id;
85
- readonly taskId: Id;
113
+ readonly conversationId: ConversationId;
114
+ readonly taskId: TaskId;
86
115
  };
87
116
  };
88
117
  ```
@@ -100,38 +129,41 @@ interface SystemMessage {
100
129
  }
101
130
  ```
102
131
 
103
- `content` is the base prompt on the leading message and additional instruction
104
- text on later messages. `sections` is an ordered named patch: a string adds or
105
- replaces a section, while `null` removes it. `toolsRemoved` is applied before
106
- `toolsAdded` within one message. Replaying every system message in transcript
107
- order yields the effective prompt and tool set.
132
+ In pi-ai, `content` is the base prompt on the leading message and additional
133
+ instruction text on later messages. `sections` is an ordered named patch: a
134
+ string adds or replaces a section, while `null` removes it. `toolsRemoved` is
135
+ applied before `toolsAdded` within one message. Replaying every system message
136
+ in transcript order yields the effective prompt and tool set.
137
+
138
+ Pico always writes `content: ""`. Every prompt part, including the preamble, is
139
+ a named section produced by the registry's system prompt slot (section 7.4).
108
140
 
109
141
  ```ts
110
142
  type ContextEdit = {
111
- readonly target: Id;
143
+ readonly target: EntryId;
112
144
  } & (
113
145
  | { readonly action: "omit"; readonly messages?: never }
114
146
  | { readonly action: "replace"; readonly messages: readonly Message[] }
115
147
  );
116
148
 
117
149
  type EntryRecord = {
118
- readonly id: Id;
119
- readonly conversationId: Id;
150
+ readonly id: EntryId;
151
+ readonly conversationId: ConversationId;
120
152
  readonly kind: string;
121
153
  readonly model?: readonly Message[];
122
154
  readonly data?: JsonValue;
123
- readonly head?: Id;
155
+ readonly head?: EntryId;
124
156
  readonly edits?: readonly ContextEdit[];
125
- readonly byTaskId?: Id;
157
+ readonly byTaskId?: TaskId;
126
158
  };
127
159
 
128
160
  type EntryDraft = Omit<EntryRecord, "id" | "conversationId" | "byTaskId" | "head"> & {
129
- readonly head?: Id | "self";
161
+ readonly head?: EntryId | "self";
130
162
  };
131
163
 
132
164
  type SubmissionRecordBase = {
133
- readonly id: Id;
134
- readonly conversationId: Id;
165
+ readonly id: SubmissionId;
166
+ readonly conversationId: ConversationId;
135
167
  readonly requestId?: string;
136
168
  };
137
169
 
@@ -148,21 +180,21 @@ type SubmissionRecord =
148
180
  }
149
181
  | {
150
182
  readonly status: "placed";
151
- readonly entry: Id;
183
+ readonly entry: EntryId;
152
184
  readonly answer?: never;
153
185
  readonly reason?: never;
154
186
  readonly detail?: never;
155
187
  }
156
188
  | {
157
189
  readonly status: "done";
158
- readonly entry: Id;
159
- readonly answer: Id;
190
+ readonly entry: EntryId;
191
+ readonly answer: EntryId;
160
192
  readonly reason?: never;
161
193
  readonly detail?: never;
162
194
  }
163
195
  | {
164
196
  readonly status: "unanswered";
165
- readonly entry?: Id;
197
+ readonly entry?: EntryId;
166
198
  readonly answer?: never;
167
199
  readonly reason: string;
168
200
  readonly detail?: JsonValue;
@@ -180,7 +212,7 @@ type SubmissionRecord =
180
212
  }
181
213
  | {
182
214
  readonly status: "done";
183
- readonly entry: Id;
215
+ readonly entry: EntryId;
184
216
  readonly answer?: never;
185
217
  readonly reason?: never;
186
218
  readonly detail?: never;
@@ -194,6 +226,10 @@ type SubmissionRecord =
194
226
  }
195
227
  ));
196
228
 
229
+ type SubmissionSettlement =
230
+ | { readonly status: "done"; readonly answer: EntryId }
231
+ | { readonly status: "unanswered"; readonly reason: string; readonly detail?: JsonValue };
232
+
197
233
  type SubmissionCreate = SubmissionRecord extends infer Record
198
234
  ? Record extends SubmissionRecord
199
235
  ? Omit<Record, "id">
@@ -201,10 +237,18 @@ type SubmissionCreate = SubmissionRecord extends infer Record
201
237
  : never;
202
238
  ```
203
239
 
240
+ ID brands are compile-time only. IDs and sequences remain ordinary numbers in
241
+ memory, JSON, JSONL, and SQLite. Code applies a brand only at a trusted creation
242
+ or decoding boundary. The distinct sequence brand prevents an entity ID from
243
+ being used as a document commit point.
244
+
204
245
  Conversation history parenting and task ownership are separate:
205
246
 
206
247
  - `parent` controls inherited entries and historical documents.
207
- - `owner` controls task authorization, subtree abort, and subtree idle waits.
248
+ - `owner` records task attribution and connects scopes for subtree abort and idle traversal. It is not an access-control capability.
249
+ - Creation always supplies `ConversationOwnership` explicitly. The Session
250
+ derives the persisted owner's conversation from the named task; callers never
251
+ construct the persisted owner pair.
208
252
 
209
253
  A conversation's owner remains recorded after the owning task becomes terminal.
210
254
 
@@ -228,9 +272,11 @@ Context derivation:
228
272
  5. If `H` exists, context entries are `H` followed by non-head entries in the
229
273
  range. Otherwise they are the range.
230
274
  6. Keep every positional system message and its tool/section changes.
231
- 7. Order tool results by assistant tool-call order.
232
- 8. Synthesize missing tool results after a fork when required by the provider
233
- message protocol.
275
+ 7. Move each assistant's tool results, found before the next assistant message,
276
+ directly after it in tool-call order, ahead of any intervening user or system
277
+ message. The provider protocol requires results to follow their call.
278
+ 8. Synthesize an error result for every call without one, for example after a
279
+ fork cut or at an interrupted tail. Drop tool results with no preceding call.
234
280
  9. Exclude model-less entries and assistant messages with `aborted`, `error`, or
235
281
  `deferred` stop reasons from future provider requests.
236
282
 
@@ -271,15 +317,12 @@ type SubmissionDraft = {
271
317
 
272
318
  type InputSubmissionDraft = Extract<SubmissionDraft, { readonly type: "input" }>;
273
319
 
274
- type SectionSeed =
275
- | { readonly key: string; readonly value: JsonValue }
276
- | { readonly key: string; readonly remove: true };
320
+ /** Runs inside the creating commit, after the conversation and its configuration exist. */
321
+ type ConversationInit = (tx: Tx, conversationId: ConversationId) => void | Promise<void>;
277
322
 
278
- type ConversationSpec = {
279
- readonly parent?: { readonly conversationId: Id; readonly at: Id };
280
- readonly model?: ModelRef;
281
- readonly sections?: readonly SectionSeed[];
282
- readonly activeTools?: readonly string[];
323
+ type ConversationCreateOptions = {
324
+ readonly ownership: ConversationOwnership;
325
+ readonly init?: ConversationInit;
283
326
  };
284
327
 
285
328
  type AnyTask = {
@@ -294,22 +337,58 @@ type AnyTask = {
294
337
  };
295
338
  };
296
339
 
297
- type HarnessOptions = {
340
+ type HarnessOptions<Tool extends ToolRegistration = ToolRegistration> = {
298
341
  readonly models: Models; // the pi-ai Models interface
299
- readonly tools?: readonly ToolRegistration[];
300
- readonly taskKinds?: readonly AnyTask[];
301
- readonly sections?: readonly SystemSection<JsonValue>[];
342
+ readonly registry: RegistryReader<Tool>; // section 7.1
302
343
  readonly now?: () => number;
303
- readonly root?: Omit<ConversationSpec, "parent">;
304
344
  readonly onReport?: (error: unknown) => void;
305
345
  };
306
346
 
307
- interface Entry<E extends EntryRecord = EntryRecord> {
347
+ /** Curated pi-ai request options; absent fields use pi-ai defaults. */
348
+ type ConversationStreamOptions = {
349
+ transport?: Transport;
350
+ timeoutMs?: number;
351
+ /** Provider/SDK retries inside one request attempt. */
352
+ maxRetries?: number;
353
+ maxRetryDelayMs?: number;
354
+ headers?: Record<string, string>;
355
+ metadata?: JsonObject;
356
+ cacheRetention?: CacheRetention;
357
+ deferred?: boolean | { window?: "15m" | "1h" | "24h" };
358
+ };
359
+
360
+ /** Durable generation attempt retries; the JSON shape of pi-ai `RetryPolicy`. */
361
+ type ConversationRetryPolicy = {
362
+ enabled: boolean;
363
+ maxRetries: number;
364
+ baseDelayMs: number;
365
+ maxAgentDelayMs?: number;
366
+ };
367
+
368
+ type ConversationConfigState = {
369
+ model?: ModelRef;
370
+ thinkingLevel: ModelThinkingLevel;
371
+ activeTools: string[];
372
+ streamOptions?: ConversationStreamOptions;
373
+ retry?: ConversationRetryPolicy;
374
+ };
375
+
376
+ /** Built-in rewindable configuration document; see below. */
377
+ declare const ConversationConfig: RewindableConversationDocToken<ConversationConfigState>;
378
+
379
+ /** Entry whose `data` has type `D`; `never` means the kind carries no data. */
380
+ type TypedEntry<D extends JsonValue> = Omit<EntryRecord, "data"> &
381
+ ([D] extends [never] ? { readonly data?: never } : { readonly data: D });
382
+
383
+ type TypedEntryDraft<D extends JsonValue> = Omit<EntryDraft, "kind" | "data"> &
384
+ ([D] extends [never] ? { readonly data?: never } : { readonly data: D });
385
+
386
+ interface Entry<D extends JsonValue = never> {
308
387
  readonly kind: string;
309
- is(entry: EntryRecord | undefined): entry is E;
388
+ is(entry: EntryRecord | undefined): entry is TypedEntry<D>;
310
389
  }
311
390
 
312
- function defineEntry<E extends EntryRecord>(kind: string): Entry<E>;
391
+ function defineEntry<D extends JsonValue = never>(kind: string): Entry<D>;
313
392
 
314
393
  type ContextView = {
315
394
  readonly head: EntryRecord | undefined;
@@ -322,7 +401,7 @@ type SettledSubmissionRecord = SubmissionRecord & {
322
401
  };
323
402
 
324
403
  interface Submission {
325
- readonly id: Id;
404
+ readonly id: SubmissionId;
326
405
  status(context: Context): Promise<SubmissionRecord>;
327
406
  wait(context: Context): Promise<SettledSubmissionRecord>;
328
407
  abort(context: Context): Promise<"aborted" | "already_placed" | "settled">;
@@ -332,6 +411,27 @@ type SettledTask<R> = TaskRecord<JsonValue, JsonValue, R> & {
332
411
  readonly state: Extract<TaskState<JsonValue, R>, { status: "terminal" }>;
333
412
  };
334
413
 
414
+ type TaskInspection = {
415
+ readonly record: TaskRecord<JsonValue, JsonValue, JsonValue>;
416
+ readonly state:
417
+ | { readonly kind: "running" }
418
+ | { readonly kind: "ready"; readonly migrates: boolean }
419
+ | { readonly kind: "waiting"; readonly on: readonly TaskId[] }
420
+ | {
421
+ readonly kind: "blocked";
422
+ readonly reason: "missing_task" | "task_too_old" | "migration_failed";
423
+ readonly error?: unknown;
424
+ };
425
+ };
426
+
427
+ type HarnessInspection = {
428
+ readonly scheduling: "paused" | "running" | "closing";
429
+ readonly tasks: readonly TaskInspection[];
430
+ /** Queued and placed submissions in ID order. */
431
+ readonly submissions: readonly SubmissionRecord[];
432
+ readonly registry: readonly RegistryFailure[];
433
+ };
434
+
335
435
  type ConversationWatch = WatchHandle<ConversationView>;
336
436
 
337
437
  type HooksOf<K> = K extends Task<infer _I, infer _S, infer _R, infer H>
@@ -339,7 +439,7 @@ type HooksOf<K> = K extends Task<infer _I, infer _S, infer _R, infer H>
339
439
  : never;
340
440
 
341
441
  interface Conversation {
342
- readonly id: Id;
442
+ readonly id: ConversationId;
343
443
  submit(submission: SubmissionDraft, context: Context): Promise<Submission>;
344
444
 
345
445
  getModel(context: Context): Promise<ModelRef | undefined>;
@@ -348,15 +448,10 @@ interface Conversation {
348
448
  setThinkingLevel(level: ModelThinkingLevel, context: Context): Promise<void>;
349
449
  getActiveTools(context: Context): Promise<readonly string[]>;
350
450
  setActiveTools(names: readonly string[], context: Context): Promise<void>;
351
- getSection<T extends JsonValue>(
352
- section: SystemSection<T>,
353
- context: Context,
354
- ): Promise<T | undefined>;
355
- setSection<T extends JsonValue>(
356
- section: SystemSection<T>,
357
- value: T | undefined,
358
- context: Context,
359
- ): Promise<void>;
451
+ getStreamOptions(context: Context): Promise<ConversationStreamOptions>;
452
+ setStreamOptions(options: ConversationStreamOptions, context: Context): Promise<void>;
453
+ getRetryPolicy(context: Context): Promise<ConversationRetryPolicy>;
454
+ setRetryPolicy(policy: ConversationRetryPolicy | undefined, context: Context): Promise<void>;
360
455
 
361
456
  commit<T>(
362
457
  change: (tx: Tx) => T | Promise<T>,
@@ -365,68 +460,50 @@ interface Conversation {
365
460
  context(context: Context): Promise<ContextView>;
366
461
  entries(
367
462
  query: Omit<EntryQuery, "conversationId">,
368
- cursor: Cursor | undefined,
369
463
  limit: number,
464
+ cursor: Cursor | undefined,
370
465
  context: Context,
371
466
  ): Promise<Page<EntryRecord, Cursor>>;
372
467
  fork(
373
- at: Id,
374
- spec: Omit<ConversationSpec, "parent">,
468
+ at: EntryId,
469
+ options: ConversationCreateOptions,
375
470
  context: Context,
376
471
  ): Promise<Conversation>;
377
- collapse(instructions: string | undefined, context: Context): Promise<Id>;
472
+ collapse(instructions: string | undefined, context: Context): Promise<TaskId>;
378
473
  reset(handoff: string | undefined, context: Context): Promise<void>;
379
474
  abort(context: Context): Promise<void>;
380
475
  waitForIdle(context: Context): Promise<void>;
381
- hooks<K extends AnyTask>(
382
- owner: string,
383
- task: K,
384
- handlers: Partial<HooksOf<K>>,
385
- options?: { readonly subtree?: boolean },
386
- ): () => void;
476
+ viewState(context: Context): Promise<AttachedReplicatedState<ConversationView>>;
387
477
  watch(context: Context): Promise<ConversationWatch>;
388
478
  }
389
479
 
390
480
  interface Harness extends Session {
391
481
  resume(): void;
392
- suspend(context: Context): Promise<void>;
393
- quiescent(): boolean;
394
- hold(): () => void;
395
-
396
- registerTaskKind(task: AnyTask): () => void;
397
- registerTool(tool: ToolRegistration): () => void;
398
- registerSection(section: SystemSection<JsonValue>): () => void;
399
- hooks<K extends AnyTask>(
400
- owner: string,
401
- task: K,
402
- handlers: Partial<HooksOf<K>>,
403
- ): () => void;
404
-
405
- root(context: Context): Promise<Conversation>;
406
- onConversation(listener: (conversation: Conversation) => void): () => void;
407
- conversation(id: Id, context: Context): Promise<Conversation | undefined>;
408
- createConversation(
409
- spec: ConversationSpec & { readonly input?: UserInput },
482
+
483
+ root(
410
484
  context: Context,
485
+ options?: { readonly init?: ConversationInit },
411
486
  ): Promise<Conversation>;
487
+ conversation(id: ConversationId, context: Context): Promise<Conversation | undefined>;
488
+ createConversation(options: ConversationCreateOptions, context: Context): Promise<Conversation>;
412
489
 
413
- getTask(id: Id, context: Context): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
414
- submission(id: Id, context: Context): Promise<Submission | undefined>;
490
+ getTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;
491
+ inspect(context: Context): Promise<HarnessInspection>;
492
+ submission(id: SubmissionId, context: Context): Promise<Submission | undefined>;
415
493
  abortSubmission(
416
- id: Id,
494
+ id: SubmissionId,
417
495
  context: Context,
418
- conversationId?: Id,
496
+ conversationId?: ConversationId,
419
497
  ): Promise<"aborted" | "already_placed" | "settled" | "not_found">;
420
- abortTask(id: Id, context: Context): Promise<"marked" | "terminal">;
421
- markTask(id: Id, context: Context): Promise<"marked" | "terminal">;
422
- waitForTask<R>(ref: TaskRef<R>, context: Context): Promise<SettledTask<R>>;
498
+ abortTask(id: TaskId, context: Context): Promise<"marked" | "terminal">;
499
+ waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;
423
500
  waitForIdle(context: Context): Promise<void>;
424
501
  }
425
502
 
426
503
  declare const Harness: {
427
- open(
504
+ open<Tool extends ToolRegistration>(
428
505
  storage: Storage,
429
- options: HarnessOptions,
506
+ options: HarnessOptions<Tool>,
430
507
  context: Context,
431
508
  ): Promise<Harness>;
432
509
  };
@@ -439,76 +516,122 @@ conversation watch replace those surfaces. `submit()` durably admits either a
439
516
  user input or passive entry write and returns one `Submission` that tracks its
440
517
  settlement.
441
518
 
442
- `Harness.open()` installs built-in task, tool, and section definitions followed
443
- by supplied task kinds, tools, and sections. It changes
444
- surviving `running` tasks to `pending`, migrates task records, and settles unknown
445
- or unmigratable live task kinds as `orphaned` before resolving. Any built-in
446
- document touched by that recovery migrates through its ordinary typed access
447
- path. Open does not scan or migrate other documents. IDs and names in registries must be unique. No
448
- handler dispatches during open. Dynamic registration is available after open and
449
- does not resurrect a task already settled by that pass.
450
-
451
- The root conversation always has reserved ID `ROOT_CONVERSATION_ID` (`1`). Empty
452
- storage creates that conversation from `options.root`; reopen looks it up by the
453
- reserved ID. `options.root` never overwrites existing state. `root()` returns
454
- that handle. A conversation with no configured model produces a durable
455
- `no_model` generation failure.
519
+ `Harness.open()` binds the Session to one application-owned registry (section
520
+ 7.1). `createRegistry()` pre-registers the built-in task definitions (section 8);
521
+ they cannot be disposed or replaced, and open rejects a registry whose snapshot
522
+ lacks any of them or the built-in `pi` conversation setup.
523
+ Open changes surviving `running` tasks to `pending` and does nothing else to
524
+ task records: it never migrates or terminalizes a task because its definition
525
+ is missing or unmigratable. Such a task stays `pending` and is **blocked**: the
526
+ scheduler skips it and reconsiders it whenever the registry changes (section
527
+ 5.4). Any built-in document touched by recovery migrates through its ordinary
528
+ typed access path. Open does not scan or migrate other documents. No handler
529
+ dispatches during open. Applications should register tasks before open so
530
+ recovered work can resume immediately; registration after open also unblocks it.
531
+
532
+ The root conversation always has reserved ID `ROOT_CONVERSATION_ID` (`1`).
533
+ `root(context, { init })` creates it lazily: when the root is absent, one commit
534
+ on the Session line creates the ownerless root, its default configuration, and
535
+ runs `init(tx, rootId)`. When the root already exists, `init` is ignored and no
536
+ write occurs. Reopen finds the same root by its reserved ID. A conversation with
537
+ no configured model produces a durable `no_model` generation failure.
456
538
 
457
539
  `resume()` is idempotent while running and only enables scheduling. It does not
458
- repeat open-time reconciliation. `suspend()` is terminal for that Harness
459
- instance and follows the close semantics below; `resume()` after suspend/close
460
- rejects. `quiescent()` means no task invocation is currently executing; eligible
461
- or delayed durable tasks may still exist. `hold()` is available only while
462
- quiescent and pauses reservation until its idempotent release function runs.
463
-
464
- Runtime registration rejects duplicate IDs/names and returns an idempotent
465
- function that unregisters only that exact token. It supports declaration
466
- movement during normal operation, not replacement of executing extension code;
467
- section 7.4 governs code reload.
468
-
469
- Conversation creation atomically commits the conversation, built-in
470
- configuration and section/tool seeds, and an optional input submission. For a fork,
471
- omitted model, section, and active-tool values follow their document definition's
472
- fork policy; provided values override those forked built-in values in the same
473
- commit. Other documents follow their own definitions without special handling.
474
-
475
- The built-in conversation configuration document contains the selected model,
476
- thinking level, an ordered array of section key/value records, and active tool
477
- names. Its initial thinking level
478
- is `"off"`. It is rewindable with `fork: "asOf"`, so a child starts from the
479
- configuration visible at its selected entry unless explicit creation seeds
480
- override it. Conversation creation eagerly
481
- creates it, so `getModel()`, `getThinkingLevel()`, `getActiveTools()`, and
482
- `getSection()` return detached committed snapshots without a get-or-create
483
- write. Each setter performs one ordinary Session commit against that document;
484
- `setSection(section, undefined)` removes the value. A setter does not start
540
+ repeat open-time reconciliation, and it throws after close. Work that must happen
541
+ before any task runs, such as registration or seeding, happens before
542
+ `resume()`. Calls that ask for progress also enable scheduling, so they never
543
+ wait on a paused Harness: `Conversation.submit()`, `Submission.wait()`,
544
+ `Harness.waitForTask()`, `Harness.waitForIdle()`, and
545
+ `Conversation.waitForIdle()`. Recovered work starts with them. A viewer that only
546
+ reads never enables scheduling.
547
+
548
+ `createConversation({ ownership, init })` and
549
+ `fork(at, { ownership, init })` commit atomically: the conversation, its
550
+ explicitly selected ownership, its configuration, and every write made by `init`.
551
+ A first input is an ordinary `submit()` afterward. A request ID makes a retried
552
+ `submit()` to the same conversation exactly-once; a host that must survive a
553
+ crash between the two calls first finds its conversation again, for example
554
+ through a key written by `init`. Host callers must choose ownerless or task
555
+ ownership; neither the Harness nor a conversation handle infers ownership from
556
+ call context. A new independent conversation receives the default configuration
557
+ before `init` runs. A fork receives the configuration visible at `at` through
558
+ the ordinary `asOf` fork policy; `init` may then override it with
559
+ `tx.doc(ConversationConfig, id)`. Other documents follow their own definitions
560
+ without special handling.
561
+
562
+ Every Harness commit that creates or forks a conversation runs the registry's
563
+ conversation setups (section 7.1) in the same commit, whether through the
564
+ conveniences or through raw `tx.createConversation()` and `tx.forkConversation()`,
565
+ for example inside a tool commit. The built-in `pi` setup runs first: an
566
+ independent conversation gets the default configuration and a fork keeps its
567
+ `asOf` copy, and both get an empty `pi.live`. Applications register setups for
568
+ their own documents the same way. The conveniences add only `init` and its checks,
569
+ which run after every setup. A conversation created by a plain Session has no
570
+ built-in documents; its configuration reads as
571
+ `ConversationConfig.definition.initial()` until something writes it.
572
+
573
+ The built-in conversation configuration document is final at version 1:
574
+
575
+ | field | value |
576
+ |---|---|
577
+ | kind | `pi.conversation.config` |
578
+ | version | `1` (no migration) |
579
+ | scope/history/fork | conversation, `rewindable`, `asOf` |
580
+ | schema | `ConversationConfigState` |
581
+ | `initial()` | `{ thinkingLevel: "off", activeTools: [] }` |
582
+ | checkpoint | complete base on every change |
583
+ | view mount | `docs["pi.conversation.config"]` |
584
+
585
+ It has no prompt sections: prompt text is produced per request by the registry
586
+ (section 7.4). Any code may edit it with
587
+ `tx.doc(ConversationConfig, id)`, including in the same commit as a create or
588
+ fork. The getters return immutable committed values, falling back to
589
+ `initial()` when the document is absent; they never write. `getStreamOptions()`
590
+ returns `{}` and `getRetryPolicy()` returns the default policy
591
+ `{ enabled: true, maxRetries: 3, baseDelayMs: 2000, maxAgentDelayMs: 60000 }`
592
+ when the field is absent; `setRetryPolicy(undefined)` removes the field.
593
+ `streamOptions` are forwarded to every generation request of the conversation;
594
+ `streamOptions.maxRetries` are provider retries inside one request, while `retry`
595
+ governs durable generation attempts (section 8). Each setter performs
596
+ one ordinary Session commit against the document. A setter does not start
485
597
  generation or append a system entry. Request preparation later compares the
486
- desired committed configuration with transcript history and appends the required
598
+ desired configuration with transcript history and appends the required
487
599
  positional system baseline or delta.
488
600
 
489
- Tool declarations and executable functions are process-local Harness registry
490
- entries, supplied through `HarnessOptions.tools` or `registerTool()`. The durable
491
- configuration document stores only active tool names. A new independent
492
- conversation defaults to every tool registered when its creation is admitted;
493
- `ConversationSpec.activeTools` overrides that default. A fork with no explicit
494
- `activeTools` uses the configuration document's `asOf` value.
495
-
496
- `registerTool()` changes only the runtime registry. It does not activate the tool
497
- in existing conversations or write a document. `setActiveTools()` is the only
498
- host operation that replaces one existing conversation's durable active set.
499
- Explicit `ConversationSpec.activeTools` and `setActiveTools()` values must contain
500
- unique names that are registered when their commit is admitted; otherwise the
501
- whole operation rejects without a write. Inherited historical names are not
502
- revalidated during a fork and may later be unavailable after registry movement.
503
- Unregistering a tool does not rewrite any conversation.
504
-
505
- If request preparation finds unavailable active names, it performs no provider
506
- request. It atomically terminalizes the generation task as `failed` with
507
- `detail: { code: "missing_active_tool", names }`, makes its placed input submissions
508
- `unanswered` with reason `missing_active_tool`, clears matching turn control, and
509
- appends a visible model-less diagnostic entry. It does not silently change the
510
- durable loadout. Historical system entries remain replayable because they store
511
- the exact declarations actually offered to prior requests.
601
+ Default active tools for a root or independent conversation, including one
602
+ created through `tx.createConversation()` in a Harness commit, are the names of
603
+ every tool registered when its creation commit runs, in registry order.
604
+ `setActiveTools()` rejects the whole operation without a write when a name is
605
+ duplicated or when a name that was not already active in that conversation is
606
+ not registered. The create/fork conveniences check only one thing about `init`
607
+ writes: names that `init` newly activates must be registered. Names that were
608
+ already active are never revalidated, so stale unregistered names survive every
609
+ edit. All other raw document writes are trusted and unchecked, so other writers,
610
+ such as post-tools `addTools`, never fault because of registry movement. Readers tolerate what raw
611
+ writes can produce: request preparation offers the first occurrence of a
612
+ duplicated name, and post-tools `addTools` appends only names not already
613
+ active.
614
+
615
+ `init` runs after the conversation creation, which is a table write, so table
616
+ reads inside it throw `ReadAfterWrite` (section 4). Document access remains
617
+ available.
618
+
619
+ The configuration document records the desired loadout; the registry records
620
+ what this process can execute now. An active name may therefore be unregistered,
621
+ for example during extension reload, after restart before registration, or in a
622
+ fork opened by a process that lacks an extension. The document is never
623
+ rewritten because of registry movement, so a re-registered tool becomes available
624
+ again without host action. Hosts derive current availability as active names
625
+ that are currently registered.
626
+
627
+ A missing tool implementation never fails a request. Request preparation offers
628
+ only active names that are currently registered. If the replayed tool state still
629
+ offers an unregistered name, the appended system delta lists it in
630
+ `toolsRemoved`; when the name is registered again, a later delta adds its current
631
+ declaration. When the model calls a tool that is not offered or whose
632
+ implementation is unavailable at execution time, the tool task appends an error
633
+ tool result with `details: { code: "tool_unavailable" }` stating that the tool is
634
+ not available, and the run continues so the model can react.
512
635
 
513
636
  A `Conversation.commit()` is a Session commit bound to that conversation.
514
637
  `tx.createTask()` defaults `TaskOptions.conversationId` to the bound conversation.
@@ -517,29 +640,30 @@ fork-aware stored history; callers cannot substitute another conversation ID.
517
640
  Generic Session-wide document operations remain available directly on `Harness`
518
641
  because `Harness extends Session`.
519
642
 
520
- `fork()` requires a concrete visible parent entry and applies section 3.7.
643
+ `fork()` requires a concrete visible parent entry and explicit ownership, then
644
+ applies section 3.7.
521
645
  `collapse()` returns the newly admitted background collapse task ID, not its
522
646
  future summary entry. `reset()` durably admits a passive self-head reset or
523
647
  handoff write and then resolves; while busy, placement follows section 6 and may
524
648
  occur later. Observe its placement through the conversation watch. An idle wait
525
649
  does not guarantee placement of queued passive writes.
526
650
 
527
- `markTask()` only commits `abortRequested`; it neither signals nor joins an
528
- active invocation. The scheduler notices the mark on its next drain.
529
- `abortTask()` also signals and joins an active run before starting the abort
530
- invocation. `Conversation.abort()` withdraws queued input submissions, marks
531
- non-background tasks in the conversation and owned subtree, signals them, and
532
- resolves only after that subtree is ordinarily idle. Passive writes and
533
- background tasks survive. Conversation idle means no non-background live task
534
- in that conversation or its ownership subtree; Harness idle applies the same
535
- rule Session-wide. Pending dependency- or deadline-blocked work is still live
536
- and therefore not idle. Cancelling an idle wait aborts only that waiter.
537
-
538
- `onConversation()` synchronously visits the currently loaded committed
539
- conversations in ascending ID order, then reports each later creation after its
540
- commit. Listener failures go to `onReport` and do not stop other listeners. Its
541
- idempotent disposer removes the listener; Harness close removes all remaining
542
- listeners.
651
+ `abortTask()` commits `abortRequested` and the durable foreground-subtree
652
+ cascade, then signals and joins the active run; the scheduler then starts the
653
+ abort invocation. Marking without signalling is internal: the cascade marks
654
+ owned tasks in the same commit. `Conversation.abort()` withdraws queued
655
+ input submissions, marks non-background tasks selected by ordinary ownership
656
+ traversal, signals them, and resolves only after that scope is ordinarily idle.
657
+ Passive writes and background subtrees survive. Conversation idle means no live
658
+ non-background task selected from that conversation. Harness idle applies the
659
+ same traversal from every ownerless conversation root. Pending dependency- or
660
+ deadline-blocked work is still live and therefore not idle. Cancelling an idle
661
+ wait aborts only that waiter.
662
+
663
+ Conversation handles are stateless; compare them by `id`. Hosts discover
664
+ conversations through lookups and scans. An activity view that lists active
665
+ conversations and reports conversations becoming active or idle is specified
666
+ with run control (Package 17); there is no creation listener.
543
667
 
544
668
  `submit()` returns after durable admission, not settlement. An input submission
545
669
  creates a user message with the admission timestamp; `whenBusy` defaults to
@@ -553,23 +677,37 @@ reopen; records remain queryable after settlement.
553
677
 
554
678
  `abortTask()` durably requests cancellation and returns `marked` after the mark
555
679
  is committed, any active run invocation has joined, and an abort invocation has
556
- been scheduled; it does not await terminal settlement. `waitForTask()` observes
680
+ been scheduled, or a blocked task has been settled as `orphaned` (section 5.4);
681
+ it does not await terminal settlement. `waitForTask()` observes
557
682
  the terminal receipt. Aborting an already terminal task returns `terminal`; an
558
683
  unknown ID rejects. Explicit task abort includes a background task. Cancelling a
559
684
  task or idle wait does not abort work.
560
685
 
561
- `Conversation.watch()` atomically captures an immutable structural view and
562
- registers for later complete Session commits. Its `WatchHandle` uses the same
563
- serialized asynchronous update and reset-compaction contract as `watchDoc()` in
564
- section 9.2. It carries no semantic events and owns no second tracker.
565
-
566
- `close()` is equivalent to `suspend()` for v1. It seals mutation admission and
567
- task reservation, signals invocations, and stops watches. Outside the Session
568
- line it lets already-admitted storage commits settle, joins task/tool/hook
569
- invocations and in-flight watch callbacks, then closes sources and storage. It
570
- writes no task outcome. Handles belong to that open Harness and must be
571
- reacquired after reopen. A non-cooperative watch callback can delay graceful
572
- close just like a non-cooperative task invocation.
686
+ `inspect()` returns live work at one point on the Session line, for recovery
687
+ decisions after open, viewers, and diagnostics. It writes nothing, does not
688
+ enable scheduling, and runs no task code. Each pending or running task carries
689
+ its state under the current registry: `running` with an active invocation;
690
+ `ready` when the next scheduling pass would reserve it, with `migrates` when its
691
+ definition is newer and has `migrate`; `waiting` on unfinished dependencies; or
692
+ `blocked` (section 5.4). A migration shows as failed only after the scheduler
693
+ tried it, or when the newer definition has no `migrate`; inspection never runs
694
+ one to find out. Blocked reasons are derived, never stored. Queued and placed
695
+ submissions and the registry's wrapper failures complete the view. Finished
696
+ tasks, settled submissions, transcripts, and documents use their own APIs.
697
+
698
+ `Conversation.viewState()` returns its current structural mount as a disposable
699
+ read-only Chord state. `Conversation.watch()` atomically captures that immutable
700
+ revision and registers for later exact complete-commit frames. Its `WatchHandle`
701
+ uses the same serialized asynchronous, bounded-buffer contract as `watchDoc()`
702
+ in section 9.2. Neither carries semantic events or owns a second persistence
703
+ authority.
704
+
705
+ `close()` seals mutation admission and
706
+ task reservation, signals invocations, and stops future watch deliveries. Outside
707
+ the Session line it lets already-admitted storage commits settle, joins
708
+ task/tool/hook invocations, then closes states and storage. Already-running watch
709
+ callbacks remain caller-owned and may finish independently. Close writes no task
710
+ outcome. Handles belong to that open Harness and must be reacquired after reopen.
573
711
 
574
712
  ## 3. Documents
575
713
 
@@ -597,12 +735,17 @@ type DocumentSemantics =
597
735
  | RewindableConversationSemantics
598
736
  | { readonly scope: "task" };
599
737
 
738
+ type CheckpointInfo = {
739
+ /** Deltas already stored after the newest base, excluding this change. */
740
+ readonly deltasSinceBase: number;
741
+ };
742
+
600
743
  type CommonDocDefinition<T extends JsonObject> = {
601
744
  readonly kind: string;
602
745
  readonly version: number;
603
746
  initial(): T;
604
747
  migrate?(value: JsonObject, fromVersion: number): T;
605
- checkpointWhen?(value: Readonly<T>, ops: readonly Op[]): boolean;
748
+ checkpointWhen?(value: Readonly<T>, ops: readonly Op[], info: CheckpointInfo): boolean;
606
749
  };
607
750
 
608
751
  type DocDefinition<T extends JsonObject> =
@@ -734,21 +877,21 @@ A persisted document instance has one `DocumentRecord`:
734
877
 
735
878
  ```ts
736
879
  type DocumentRecord = {
737
- readonly id: Id; // unique incarnation
880
+ readonly id: DocumentId; // unique incarnation
738
881
  readonly kind: string; // stable definition kind
739
882
  readonly key?: string; // families only
740
883
  readonly createdAt: Seq; // stamped by the committing storage
741
884
  readonly retiredAt?: Seq;
742
885
  } & (
743
886
  | { readonly scope: { readonly kind: "session" } }
744
- | ({ readonly scope: { readonly kind: "conversation"; readonly conversationId: Id } } & (
887
+ | ({ readonly scope: { readonly kind: "conversation"; readonly conversationId: ConversationId } } & (
745
888
  | { readonly history: "latest"; readonly fork: "current" | "initial" }
746
889
  | {
747
890
  readonly history: "rewindable";
748
891
  readonly fork: "asOf" | "current" | "initial";
749
892
  }
750
893
  ))
751
- | { readonly scope: { readonly kind: "task"; readonly taskId: Id } }
894
+ | { readonly scope: { readonly kind: "task"; readonly taskId: TaskId } }
752
895
  );
753
896
 
754
897
  type DocumentCreate = DocumentRecord extends infer Record
@@ -779,56 +922,83 @@ There is no mutable `session.document()` API.
779
922
  interface Session extends DocumentObserver {
780
923
  commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;
781
924
  close(context: Context): Promise<void>;
925
+ subscribeCommits(listener: (publication: CommitPublication, context: Context) => void): () => void;
926
+ subscribeClose(listener: () => void): () => void;
782
927
 
783
928
  snapshot<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<Readonly<T> | undefined>;
784
- snapshot<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: Id, context: Context): Promise<Readonly<T> | undefined>;
785
- snapshot<T extends JsonObject>(token: TaskDocToken<T>, taskId: Id, context: Context): Promise<Readonly<T> | undefined>;
929
+ snapshot<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context): Promise<Readonly<T> | undefined>;
930
+ snapshot<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context): Promise<Readonly<T> | undefined>;
786
931
  snapshot<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<Readonly<T> | undefined>;
787
- snapshot<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: Id, key: string, context: Context): Promise<Readonly<T> | undefined>;
788
- snapshot<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: Id, key: string, context: Context): Promise<Readonly<T> | undefined>;
789
-
790
- snapshotAsOf<T extends JsonObject>(token: RewindableConversationDocToken<T>, conversationId: Id, at: Id, context: Context): Promise<Readonly<T> | undefined>;
791
- snapshotAsOf<T extends JsonObject, I extends JsonValue>(token: RewindableConversationDocFamilyToken<T, I>, conversationId: Id, key: string, at: Id, context: Context): Promise<Readonly<T> | undefined>;
792
-
793
- documentSource<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentSource<T> | undefined>;
794
- documentSource<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: Id, context: Context): Promise<DocumentSource<T> | undefined>;
795
- documentSource<T extends JsonObject>(token: TaskDocToken<T>, taskId: Id, context: Context): Promise<DocumentSource<T> | undefined>;
796
- documentSource<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<DocumentSource<T> | undefined>;
797
- documentSource<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: Id, key: string, context: Context): Promise<DocumentSource<T> | undefined>;
798
- documentSource<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: Id, key: string, context: Context): Promise<DocumentSource<T> | undefined>;
932
+ snapshot<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context): Promise<Readonly<T> | undefined>;
933
+ snapshot<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context): Promise<Readonly<T> | undefined>;
934
+
935
+ snapshotAsOf<T extends JsonObject>(token: RewindableConversationDocToken<T>, conversationId: ConversationId, at: EntryId, context: Context): Promise<Readonly<T> | undefined>;
936
+ snapshotAsOf<T extends JsonObject, I extends JsonValue>(token: RewindableConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, at: EntryId, context: Context): Promise<Readonly<T> | undefined>;
937
+
938
+ documentState<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentState<T> | undefined>;
939
+ documentState<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context): Promise<DocumentState<T> | undefined>;
940
+ documentState<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context): Promise<DocumentState<T> | undefined>;
941
+ documentState<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<DocumentState<T> | undefined>;
942
+ documentState<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context): Promise<DocumentState<T> | undefined>;
943
+ documentState<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context): Promise<DocumentState<T> | undefined>;
799
944
  }
800
945
 
801
946
  interface Tx {
802
- conversation(id: Id): Promise<ConversationRecord | undefined>;
803
- entry(id: Id): Promise<EntryRecord | undefined>;
804
- task(id: Id): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
805
- scanEntries(query: EntryQuery): Promise<readonly EntryRecord[]>;
806
- scanTasks(query: TaskQuery): Promise<readonly TaskRecord<JsonValue, JsonValue, JsonValue>[]>;
807
-
808
- createConversation(value: Omit<ConversationRecord, "id">): Promise<ConversationRecord>;
809
- appendEntry(conversationId: Id, value: EntryDraft): Promise<EntryRecord>;
947
+ conversation(id: ConversationId): Promise<ConversationRecord | undefined>;
948
+ entry(id: EntryId): Promise<EntryRecord | undefined>;
949
+ /** Undefined when the entry is absent or has another kind. */
950
+ entry<D extends JsonValue>(token: Entry<D>, id: EntryId): Promise<TypedEntry<D> | undefined>;
951
+ task(id: TaskId): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
952
+ scanConversations(query: ConversationQuery, limit: number, cursor?: Cursor): Promise<Page<ConversationRecord, Cursor>>;
953
+ scanEntries(query: EntryQuery, limit: number, cursor?: Cursor): Promise<Page<EntryRecord, Cursor>>;
954
+ scanTasks(query: TaskQuery, limit: number, cursor?: Cursor): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;
955
+
956
+ createConversation(options: { readonly ownership: ConversationOwnership }): Promise<ConversationRecord>;
957
+ forkConversation(
958
+ parentConversationId: ConversationId,
959
+ at: EntryId,
960
+ options: { readonly ownership: ConversationOwnership },
961
+ ): Promise<ConversationRecord>;
962
+ appendEntry(conversationId: ConversationId, value: EntryDraft): Promise<EntryRecord>;
963
+ /** The token supplies `kind` and types `data`. */
964
+ appendEntry<D extends JsonValue>(
965
+ token: Entry<D>, conversationId: ConversationId, value: TypedEntryDraft<D>,
966
+ ): Promise<TypedEntry<D>>;
810
967
  createTask<I, S extends { phase: string }, R, H extends object>(
811
968
  task: Task<I, S, R, H>, input: I, options?: TaskOptions,
812
- ): Promise<TaskRef<R>>;
813
- setTask(value: TaskRecord<JsonValue, JsonValue, JsonValue>): void;
969
+ ): Promise<TaskId<R>>;
970
+ /** Settle a queued or placed submission; only a placed input can be answered. A settled one stays unchanged. */
971
+ settleSubmission(id: SubmissionId, settlement: SubmissionSettlement): void;
814
972
 
815
973
  doc<T extends JsonObject>(token: SessionDocToken<T>): Promise<Draft<T>>;
816
- doc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: Id): Promise<Draft<T>>;
817
- doc<T extends JsonObject>(token: TaskDocToken<T>, taskId: Id): Promise<Draft<T>>;
974
+ doc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<Draft<T>>;
975
+ doc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<Draft<T>>;
818
976
  doc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, seed: I): Promise<Draft<T>>;
819
- doc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: Id, key: string, seed: I): Promise<Draft<T>>;
820
- doc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: Id, key: string, seed: I): Promise<Draft<T>>;
977
+ doc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, seed: I): Promise<Draft<T>>;
978
+ doc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, seed: I): Promise<Draft<T>>;
821
979
 
822
980
  retireDoc<T extends JsonObject>(token: SessionDocToken<T>): Promise<void>;
823
- retireDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: Id): Promise<void>;
824
- retireDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: Id): Promise<void>;
981
+ retireDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId): Promise<void>;
982
+ retireDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId): Promise<void>;
825
983
  retireDoc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string): Promise<void>;
826
- retireDoc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: Id, key: string): Promise<void>;
827
- retireDoc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: Id, key: string): Promise<void>;
984
+ retireDoc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string): Promise<void>;
985
+ retireDoc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string): Promise<void>;
828
986
  }
829
987
  ```
830
988
 
831
- ID-creating transaction methods are asynchronous because remote storage may allocate globally unique IDs durably. Only public typed `tx.doc()` is get-or-create. Internal fork copying may create
989
+ ID-creating transaction methods are asynchronous because remote storage may
990
+ allocate globally unique numeric IDs durably. Conversation creation always
991
+ requires explicit ownership; no transaction wrapper injects the executing task.
992
+ For task ownership, the caller supplies only a typed task ID. The Session derives
993
+ the persisted owner conversation from the task's final candidate record.
994
+
995
+ An owner task may be committed or staged earlier in the same transaction. Before
996
+ Storage admission, the Session rejects a missing, terminal, or abort-marked owner,
997
+ including one made terminal or abort-marked later in that transaction. Existing
998
+ owner edges remain valid when their owners terminalize afterward. Conversation
999
+ creation returns an inert record, never an operational handle.
1000
+ `forkConversation()` additionally validates one visible entry and applies section
1001
+ 3.7. Only public typed `tx.doc()` is get-or-create. Internal fork copying may create
832
1002
  new incarnations directly from stored values without a definition. `tx.doc()`
833
1003
  receives the definition token that supplies
834
1004
  its static type, initializer, migration, and checkpoint policy. Scope-preserving
@@ -844,7 +1014,7 @@ registered and ordinary documents are not scanned at open.
844
1014
  - The first acquisition of one logical address is memoized before awaiting. Later
845
1015
  acquisitions in that transaction return the same draft; for a missing family,
846
1016
  the first call's detached seed wins and later seeds are ignored.
847
- - `snapshot()`, `snapshotAsOf()`, `documentSource()`, and `watchDoc()` never create
1017
+ - `snapshot()`, `snapshotAsOf()`, `documentState()`, and `watchDoc()` never create
848
1018
  or persist migration. They return `undefined` when the requested incarnation is
849
1019
  absent and migrate a reconstructed value only in memory.
850
1020
  - Task-scoped `tx.doc()` validates against the transaction's latest candidate task
@@ -858,9 +1028,11 @@ registered and ordinary documents are not scanned at open.
858
1028
  - A terminal candidate rejects later task-document access. Terminal settlement
859
1029
  retires both existing task documents and task documents created earlier in the
860
1030
  same transaction.
861
- - `snapshot()` returns a detached JSON copy.
862
- - `documentSource()` returns an opaque source bound to one committed incarnation.
863
- - `tx.doc()` returns one revocable copy-on-write `Draft<T>` for the transaction.
1031
+ - `snapshot()` returns the current shareable immutable revision. Mutation of it
1032
+ or any retained descendant is unsupported; callers that need mutable ownership
1033
+ must copy it first.
1034
+ - `documentState()` returns a disposable read-only Chord state bound to one committed incarnation.
1035
+ - `tx.doc()` returns one revocable Astra overlay `Draft<T>` for the transaction.
864
1036
  - Historical reads never create documents in the past.
865
1037
 
866
1038
  `snapshotAsOf()` is available only for rewindable conversation documents. It
@@ -877,13 +1049,15 @@ alive at the target commit.
877
1049
 
878
1050
  ### 3.4 Mutation ownership
879
1051
 
880
- Pico uses Chord Delta's transaction shape directly:
1052
+ Pico uses Chord Delta's Astra-immutable transaction shape directly:
881
1053
 
882
1054
  ```ts
883
1055
  interface Prepared<T extends object> {
884
1056
  readonly base: T;
885
1057
  readonly value: T;
886
1058
  readonly ops: readonly Op[];
1059
+ readonly baseRevision: number;
1060
+ abort(): void;
887
1061
  }
888
1062
  interface Change<T extends object> {
889
1063
  readonly state: Draft<T>;
@@ -892,64 +1066,91 @@ interface Change<T extends object> {
892
1066
  }
893
1067
  interface Tracker<T extends object> {
894
1068
  readonly value: T;
1069
+ readonly revision: number;
895
1070
  beginChange(): Change<T>;
896
1071
  prepareReplace(value: T): Prepared<T>;
897
1072
  adopt(prepared: Prepared<T>): void;
898
1073
  }
899
1074
  ```
900
1075
 
901
- One tracker has at most one open change. `prepare()` revokes the draft and returns
902
- an inert branded result without changing `tracker.value`; `abort()` is
903
- idempotent. `adopt()` accepts only a result from that tracker whose `base` is
904
- still current. `ops.length === 0` implies `value === base`. Pico's Session line
905
- ensures no tracker becomes stale between preparation, Storage settlement, and
906
- adoption.
907
-
908
- Each loaded document owns one tracker. The first `tx.doc()` acquisition calls
909
- `tracker.beginChange()` and memoizes that change's draft for the rest of the
910
- possibly async Session callback.
1076
+ Each loaded document owns one tracker whose `value` is its current immutable
1077
+ revision. Immutability is a trusted ownership contract, not runtime freezing:
1078
+ a revision and its descendants must never be mutated after transfer to the
1079
+ tracker. `prepare()` revokes the draft, emits detached self-contained
1080
+ operations, and computes `value` with the optimized immutable applier before
1081
+ Storage admission. Unchanged subtrees are structurally shared with `base`.
1082
+ Operation placement payloads may also be shared with `value`; mutating either a
1083
+ prepared operation or an immutable revision is unsupported. Astra preserves an
1084
+ empty operation batch for changes it proves are no-ops, but Pico performs no
1085
+ additional whole-value equality pass for nonempty structural batches.
1086
+
1087
+ `abort()` is idempotent. `adopt()` accepts only a prepared result from that
1088
+ tracker at its current revision, then performs only a synchronous pointer swap
1089
+ to the already-computed immutable `value`. It performs no diffing, application,
1090
+ allocation, or callback. The Session line permits at most one open change per
1091
+ tracker and ensures no result becomes stale between preparation, Storage
1092
+ settlement, and adoption.
1093
+
1094
+ The first `tx.doc()` acquisition calls `tracker.beginChange()` and memoizes that
1095
+ change's draft for the rest of the possibly async Session callback.
911
1096
 
912
1097
  Transaction behavior:
913
1098
 
914
1099
  ```text
915
1100
  begin transaction
916
1101
  acquire and memoize document changes by logical address
917
- mutate revocable copy-on-write drafts
1102
+ mutate revocable Astra overlay drafts
918
1103
  callback settles
919
- seal Tx and synchronously reject further draft/Tx use
1104
+ seal Tx; synchronously prepare or abort every open change, revoking every draft
920
1105
  if any acquisition is pending: abort open changes, reject, then drain and abort it
921
1106
  callback fails with no pending acquisition
922
1107
  abort every open change; persist and publish nothing
923
1108
  callback succeeds with no pending acquisition
924
- prepare every open change -> immutable candidate + frozen Chord Op[]
925
- normalize deep no-ops to the previous value + []
1109
+ prepare every open change -> immutable next revision + self-contained Chord Op[]
926
1110
  Session evaluates each required/ordinary document write exactly once
1111
+ prepare every affected loaded conversation mount revision
927
1112
  Storage.commit persists the atomic batch while the Session line remains held
928
1113
  storage succeeds
929
- adopt every prepared change and enqueue candidate/ops publication
1114
+ adopt every prepared change by pointer swap and enqueue immutable revision/ops publication
930
1115
  release the line; invoke listeners later
931
1116
  storage fails
932
- poison Session and publish nothing
1117
+ abort every prepared change, poison Session, and publish nothing
933
1118
  ```
934
1119
 
935
1120
  A pending acquisition that resolves after sealing never exposes a draft; its
936
1121
  change is aborted and its promise rejects. The Session observes every such
937
- settlement before releasing the line.
938
-
939
- `prepare()` performs all JSON, ownership, diff, and freezing work. Preparation or
940
- checkpoint failure occurs before Storage admission and rolls back normally.
941
- Adoption performs no diffing, allocation, or callback. The prepared candidate
942
- itself becomes the immutable published value; Pico does not replay its operations
943
- to construct another copy. An unchanged existing current-version document writes
944
- and publishes nothing. Creation and required version transitions still write a
945
- base when their prepared operation batch is empty; an equal-value version base
946
- does not emit a watch update.
947
-
948
- Values assigned into a draft are copied immediately by value. Repeated placements
949
- are independent. Chord may structurally share unchanged immutable subtrees across
950
- revisions. Operation tuples, paths, splice payload arrays, permutations, and the
951
- outer batch are frozen before checkpoint code, Storage, or listeners can observe
952
- them.
1122
+ settlement before releasing the line. Initializer, migration, and replacement
1123
+ roots come from caller code: the Session copies each one into exclusive kernel
1124
+ ownership, rejecting any value that is not strict JSON, before it becomes an
1125
+ immutable tracker revision. Loaded and fork-copy roots are already detached
1126
+ strict JSON from Storage and enter the tracker without another copy. Chord's
1127
+ `track()` and `prepareReplace()` take ownership in O(1) without traversal, so
1128
+ every root they receive must come from one of these sources. Migration callbacks
1129
+ never receive a live tracker revision.
1130
+
1131
+ Preparation, validation, checkpoint, or mounted-view preparation failure occurs
1132
+ before Storage admission and rolls back normally. The Session performs no
1133
+ strict-JSON walk of prepared operations or selected bases: roots are checked on
1134
+ entry and Chord checks every draft placement, so every revision, operation
1135
+ payload, and base is strict JSON by construction. Tracker branding and `baseRevision` enforce ownership and staleness; the
1136
+ Session never substitutes caller-created prepared values. The prepared immutable
1137
+ candidate itself becomes the adopted and published value. Storage receives that complete value only when the
1138
+ Session selects a base; otherwise it receives only the prepared operation batch.
1139
+ An existing current-version document with an empty batch writes and publishes
1140
+ nothing. A nonempty structural batch whose final value is deeply equal to its
1141
+ base remains a valid durable change and publication. Creation and required
1142
+ version transitions still write a base when their prepared batch is empty; an
1143
+ equal-value version base does not emit a watch update.
1144
+
1145
+ Values assigned into a draft are copied immediately by value. Repeated
1146
+ placements are independent. Chord checks each placement while copying it and
1147
+ throws at the offending assignment, before the draft changes, when the value is
1148
+ not strict JSON: `undefined` array elements or nested object values, non-finite
1149
+ numbers, functions, symbols, bigints, accessors, symbol keys, sparse arrays, or
1150
+ objects whose prototype is neither `Object.prototype` nor `null`. Assigning
1151
+ `undefined` directly to an object property deletes that property. Draft reads, draft writes, and all `Tx` operations
1152
+ reject after the callback settles. The prepared immutable value remains readable
1153
+ by Session-owned checkpoint and Storage preparation.
953
1154
 
954
1155
  ```ts
955
1156
  let escaped: Draft<LiveState>;
@@ -960,8 +1161,7 @@ escaped.message = message; // throws: the draft was revoked
960
1161
  ```
961
1162
 
962
1163
  Fire-and-forget work that mutates a draft before the owner callback settles may
963
- silently enter that transaction and is unsupported. After settlement, draft and
964
- `Tx` operations reject.
1164
+ silently enter that transaction and is unsupported.
965
1165
 
966
1166
  ### 3.5 Bases and checkpoints
967
1167
 
@@ -971,10 +1171,14 @@ For an ordinary later mutation, the definition alone decides whether the
971
1171
  storage record is a base:
972
1172
 
973
1173
  ```ts
974
- const useBase = definition.checkpointWhen?.(candidateValue, ops) ?? false;
1174
+ const useBase = definition.checkpointWhen?.(candidateValue, ops, { deltasSinceBase }) ?? false;
975
1175
  ```
976
1176
 
977
1177
  The Session evaluates this predicate exactly once after tracker preparation.
1178
+ `deltasSinceBase` counts the deltas already stored after the incarnation's newest
1179
+ base, excluding the change being evaluated. Storage reports it when it
1180
+ materializes the current value; the Session advances it after each adopted write
1181
+ and resets it after every base, so evaluation performs no Storage read.
978
1182
  Creation and version transitions require bases and do not call it. The Session
979
1183
  then gives Storage only the selected representation:
980
1184
 
@@ -997,6 +1201,12 @@ code and never receives an unused complete candidate with a selected delta.
997
1201
  - Storage does not count encoded bytes, compare against `initial()`, or invent
998
1202
  checkpoints.
999
1203
 
1204
+ A definition can bound replay directly:
1205
+
1206
+ ```ts
1207
+ checkpointWhen: (_value, _ops, info) => info.deltasSinceBase >= 31
1208
+ ```
1209
+
1000
1210
  A high-churn live document can checkpoint when it becomes empty:
1001
1211
 
1002
1212
  ```ts
@@ -1017,11 +1227,17 @@ no migrate -> reject older stored version
1017
1227
  ```
1018
1228
 
1019
1229
  `migrate()` is pure and returns a complete current-version value. Migration is
1020
- access-driven: `tx.doc()`, `snapshot()`, `snapshotAsOf()`, `documentSource()`, and
1230
+ access-driven: `tx.doc()`, `snapshot()`, `snapshotAsOf()`, `documentState()`, and
1021
1231
  `watchDoc()` reconstruct and migrate through the token supplied to that call.
1022
1232
  Harness open does not sweep ordinary documents.
1023
1233
 
1024
- - Read-only access migrates only its returned in-memory value and never writes.
1234
+ - Read-only access migrates only in memory and never writes. It may cache a
1235
+ tracker over that migrated immutable revision together with the older stored
1236
+ version marker; the next successful `tx.doc()` access still writes the required
1237
+ current-version base. A cached tracker serves only tokens of the version its value was
1238
+ materialized for. Access with any other version, such as a token from reloaded
1239
+ extension code, drops it and reloads the stored value, so each token migrates
1240
+ from the stored version or rejects a newer one. Migration always starts from a detached stored value.
1025
1241
  `tx.doc()` stages migration in its enclosing transaction; callback failure
1026
1242
  persists nothing, and later draft edits coalesce into one final required base.
1027
1243
  - Rewindable history is not rewritten. Current and historical reconstructed
@@ -1048,7 +1264,7 @@ Each conversation document follows the history/fork policy persisted in its
1048
1264
  | conversation setting | child value |
1049
1265
  |---|---|
1050
1266
  | `fork: "asOf"` | parent value at `E`'s commit |
1051
- | `fork: "current"` | parent value when the fork commit runs |
1267
+ | `fork: "current"` | committed parent value selected when the fork commit runs |
1052
1268
  | `fork: "initial"` | no copied instance; initializer on first child access |
1053
1269
 
1054
1270
  `current` and `asOf` copy logically present conversation singleton and family
@@ -1058,21 +1274,54 @@ values become independent child instances with new IDs and initial bases.
1058
1274
  supplied definition. Task documents and tasks are never copied. Session documents
1059
1275
  remain shared and are not rewindable.
1060
1276
 
1277
+ Fork copying reads committed stored values rather than typed tracker caches. A
1278
+ transaction that creates a fork therefore rejects if it also writes one of the
1279
+ parent's `fork: "current"` documents; commit the parent change first so the fork
1280
+ has one unambiguous stored source revision.
1281
+
1282
+ Forks stage backend-side `document.copy` commands carrying the child create
1283
+ record and an exact source incarnation/point. Storage materializes each source
1284
+ and persists its stored value/version as the child's independent initial base;
1285
+ remote Storage performs this server-side. Every copy reads committed pre-batch
1286
+ source state independent of write-array order. A selected source may not be
1287
+ created, changed, or retired in the same batch. Copying remains atomic with the
1288
+ conversation, overrides, registry writes, and other mutations.
1289
+
1290
+ An unaccessed copy retains only its descriptor in Session memory. Typed access
1291
+ inside the creating transaction lazily reads the detached source, migrates when
1292
+ required, and replaces the copy with one ordinary child create containing the
1293
+ final prepared value. Definition-free copies publish explicit `document.copy`
1294
+ metadata rather than a value. That metadata announces Storage-backed initial
1295
+ state and is never interpreted as a document value. Document states, watches,
1296
+ and mounted views hydrate by capturing their baseline and subscription
1297
+ atomically on the Session line: a later commit already present becomes the
1298
+ baseline, while one committed after registration is delivered. Publications
1299
+ and watches are convergence mechanisms, not audit streams. A mounted aggregate
1300
+ must acquire all of its document baselines and commit subscription in one
1301
+ Session-line operation so it never exposes a mixture from one commit.
1302
+
1061
1303
  ## 4. Transactions and storage ownership
1062
1304
 
1063
1305
  A Session commit callback may be asynchronous. It owns the Session mutation
1064
1306
  line through callback execution, preparation, storage settlement, committed
1065
- baseline adoption, and publication enqueue. Listener callbacks run later.
1307
+ baseline adoption, and publication enqueue. Commit observers run on the
1308
+ line; document-state and watch user callbacks run later.
1066
1309
  External model, process, tool, network, and human effects run outside it.
1310
+ `subscribeCommits()` observes complete immutable publications synchronously on
1311
+ the line after adoption. `subscribeClose()` observes close synchronously when it
1312
+ begins, after admission is sealed; the Harness stops watches and signals task
1313
+ invocations there. Both return idempotent disposers; their listeners must not
1314
+ throw, block, or call Session APIs. Document-state subscribers and watch
1315
+ listeners still run later, off the line.
1067
1316
 
1068
1317
  ```ts
1069
1318
  await session.commit(async tx => {
1070
- const task = await tx.task(taskId); // table read
1319
+ const conversation = await tx.conversation(conversationId); // table read
1071
1320
  const live = await tx.doc(LiveDoc, conversationId);
1072
1321
 
1073
1322
  await tx.appendEntry(conversationId, message); // first table write
1074
1323
  delete live.message; // document mutation remains valid
1075
- tx.setTask(nextTask(task));
1324
+ await tx.createTask(Follow, { after: message.id }); // further table writes are fine
1076
1325
  }, context);
1077
1326
  ```
1078
1327
 
@@ -1116,12 +1365,12 @@ type TaskState<S, R> =
1116
1365
  | { readonly status: "terminal"; readonly outcome: TaskOutcome<R> };
1117
1366
 
1118
1367
  type TaskRecord<I, S, R> = {
1119
- readonly id: Id;
1120
- readonly conversationId: Id;
1368
+ readonly id: TaskId<R>;
1369
+ readonly conversationId: ConversationId;
1121
1370
  readonly kind: string;
1122
1371
  readonly version: number;
1123
1372
  readonly input: I;
1124
- readonly after: readonly Id[];
1373
+ readonly after: readonly TaskId[];
1125
1374
  readonly background: boolean;
1126
1375
  readonly abortRequested: boolean;
1127
1376
  } & (
@@ -1139,6 +1388,9 @@ type RunningTask<I, S, R> = TaskRecord<I, S, R> & {
1139
1388
  readonly state: Extract<TaskState<S, R>, { status: "running" }>;
1140
1389
  };
1141
1390
 
1391
+ /** State a task commits for itself: a replacement checkpoint or its terminal outcome. */
1392
+ type NextTaskState<S, R> = Extract<TaskState<S, R>, { status: "running" | "terminal" }>;
1393
+
1142
1394
  interface HookRunner<H extends object> {
1143
1395
  each<K extends keyof H>(name: K, invoke: (handler: H[K]) => void | Promise<void>): Promise<void>;
1144
1396
  }
@@ -1149,19 +1401,32 @@ type PhaseHandler<I, P, S, R, H extends object> = (
1149
1401
  context: Context,
1150
1402
  ) => Promise<void>;
1151
1403
 
1152
- interface TaskRuntime<I, S, R, H extends object> extends DocumentObserver {
1153
- readonly taskId: Id;
1154
- readonly conversationId: Id;
1404
+ interface TaskRuntime<I, S, R, H extends object> extends DocumentObserver, DocumentReader {
1405
+ readonly taskId: TaskId<R>;
1406
+ readonly conversationId: ConversationId;
1155
1407
  readonly signal: AbortSignal;
1408
+ /** Registry snapshot of the current phase; refreshed at every phase boundary. */
1409
+ readonly registry: RegistrySnapshot<ToolRegistration>;
1410
+ readonly models: Models;
1156
1411
  readonly hooks: HookRunner<H>;
1157
1412
 
1158
1413
  commit(
1159
- change: (tx: Tx, current: RunningTask<I, S, R>) => void | Promise<void>,
1414
+ change: (
1415
+ tx: Tx,
1416
+ current: RunningTask<I, S, R>,
1417
+ ) => NextTaskState<S, R> | undefined | Promise<NextTaskState<S, R> | undefined>,
1160
1418
  context: Context,
1161
1419
  ): Promise<void>;
1162
1420
 
1163
1421
  memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
1164
1422
  memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
1423
+ conversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;
1424
+ /** Committed raw active transcript and model context, optionally cut off at `at`. */
1425
+ context(conversationId: ConversationId, context: Context, at?: EntryId): Promise<ContextView>;
1426
+ /** The Harness clock. */
1427
+ now(): number;
1428
+ /** Forward a non-fatal failure to `HarnessOptions.onReport`. */
1429
+ report(error: unknown): void;
1165
1430
  sleep(until: number, context: Context): Promise<void>;
1166
1431
  }
1167
1432
 
@@ -1172,7 +1437,7 @@ type TaskDefinition<I, S extends { phase: string }, R, H extends object> = {
1172
1437
  readonly phases: {
1173
1438
  [P in S["phase"]]: PhaseHandler<I, Extract<S, { phase: P }>, S, R, H>;
1174
1439
  };
1175
- abort(task: TaskRecord<I, S, R>, runtime: TaskRuntime<I, S, R, H>, context: Context): Promise<void>;
1440
+ abort(task: RunningTask<I, S, R>, runtime: TaskRuntime<I, S, R, H>, context: Context): Promise<void>;
1176
1441
  migrate?(input: JsonValue, checkpoint: JsonValue, fromVersion: number): {
1177
1442
  input: I;
1178
1443
  checkpoint: S;
@@ -1184,11 +1449,9 @@ interface Task<I, S extends { phase: string }, R, H extends object> {
1184
1449
  readonly definition: TaskDefinition<I, S, R, H>;
1185
1450
  }
1186
1451
 
1187
- declare const taskResultType: unique symbol;
1188
- type TaskRef<R> = { readonly id: Id; readonly [taskResultType]?: R };
1189
1452
  type TaskOptions = {
1190
- readonly conversationId?: Id;
1191
- readonly after?: readonly Id[];
1453
+ readonly conversationId?: ConversationId;
1454
+ readonly after?: readonly TaskId[];
1192
1455
  readonly background?: boolean;
1193
1456
  };
1194
1457
 
@@ -1197,34 +1460,98 @@ function defineTask<I, S extends { phase: string }, R, H extends object = {}>(
1197
1460
  ): Task<I, S, R, H>;
1198
1461
  ```
1199
1462
 
1463
+ `TaskId<R>` is the numeric task ID itself with an erased result-type brand. It
1464
+ replaces a separate task-reference wrapper: `createTask()` returns `TaskId<R>`,
1465
+ typed waits infer `R` from that ID, and result-agnostic operations accept
1466
+ `TaskId<unknown>`. A task's `conversationId` is immutable after creation; a
1467
+ replacement that moves an existing task to another conversation rejects before
1468
+ Storage admission so persisted conversation-owner edges cannot become stale.
1469
+
1200
1470
  The phase map is exhaustive and phase-narrowed. A handler may perform several
1201
1471
  commits around one effect, but each durable checkpoint is a full replacement.
1202
1472
  `TaskRuntime.commit()` rereads and gates the current durable task on the Session
1203
- line before invoking its callback. Transaction methods replace its checkpoint
1204
- or write its terminal outcome.
1473
+ line before invoking its callback. It rejects when the invocation has ended, the
1474
+ Harness is closing, the task is terminal, or a run invocation's task carries an
1475
+ abort mark. Its `tx.createTask()` defaults to the task's conversation, and every
1476
+ entry it appends records the task as `byTaskId`. When the
1477
+ callback returns a state, the runtime replaces the task's state in the same
1478
+ commit, so the checkpoint or outcome is atomic with the callback's entries,
1479
+ documents, and child tasks and is type-checked against the task's checkpoint and
1480
+ result types. Returning nothing leaves the state unchanged. A terminal state
1481
+ drops the memos. `pending` is never returned; only reconciliation and handover
1482
+ write it.
1483
+
1484
+ `Tx` has no task replacement operation. A task changes only its own state,
1485
+ through its runtime. The scheduler owns reservation, reconciliation, handover,
1486
+ faults, and orphaning; `abortTask()` owns abort marks. Other code
1487
+ stops a task with `abortTask()` and reads its result with `waitForTask()`.
1488
+
1489
+ ```ts
1490
+ // Intent, effect, outcome.
1491
+ prepare: async (task, runtime, context) => {
1492
+ await runtime.commit(() => ({ status: "running", checkpoint: { phase: "charge", key: newKey() } }), context);
1493
+ },
1494
+ charge: async (task, runtime, context) => {
1495
+ const receipt = await payments.charge(task.state.checkpoint.key); // idempotent by key
1496
+ await runtime.commit(async (tx, current) => {
1497
+ const entry = await tx.appendEntry(current.conversationId, receiptEntry(receipt));
1498
+ return { status: "terminal", outcome: { status: "completed", result: { entryId: entry.id } } };
1499
+ }, context);
1500
+ },
1501
+ // The abort handler decides the outcome; returning without one faults the task.
1502
+ abort: async (task, runtime, context) => {
1503
+ await payments.cancel(task.state.checkpoint);
1504
+ await runtime.commit(() => ({ status: "terminal", outcome: { status: "aborted", reason: "user" } }), context);
1505
+ },
1506
+ ```
1507
+ `memo(name, candidate)` is one gated commit; `memo(name)` reads the committed
1508
+ record. `sleep(until)` compares against the Harness `now` clock and rejects when
1509
+ the invocation is signalled or its context is cancelled. Watches acquired through
1510
+ the runtime stop when the invocation ends. `snapshot()`/`snapshotAsOf()` read
1511
+ committed documents, for example to supply `PromptInput.read` (section 7.4).
1512
+ `context()` captures its bounds on the Session line and derives the view from
1513
+ immutable entries off the line, like `Conversation.context()`. Like every runtime
1514
+ operation, these reject after the invocation ends.
1205
1515
 
1206
1516
  Reservation durably changes `pending` to `running`. One invocation runs phase
1207
- handlers in sequence; checkpoint commits retain `running`. After a handler
1208
- settles, the scheduler rereads the task and applies the first matching rule:
1517
+ handlers in sequence; checkpoint commits retain `running`. Before every phase,
1518
+ including the first, the scheduler runs one step callback on the Session line.
1519
+ It reads the committed task and synchronously applies the first matching rule
1520
+ below to the phase that just returned. It writes any fault or handover in the
1521
+ same commit, together with the Harness cleanup for a scheduler-written outcome
1522
+ (section 5.4), which may await document access inside that callback. It ends
1523
+ the invocation there when a rule stops it. A runtime commit the
1524
+ invocation queued earlier therefore either lands before the step and counts, or
1525
+ reaches the line after it and rejects. Before the first phase only rules 1–3
1526
+ apply:
1209
1527
 
1210
1528
  1. Terminal: stop.
1211
1529
  2. Session closing: stop; preserve the checkpoint and any abort mark for reopen.
1212
1530
  3. Run mode with a durable abort mark: end and join the run invocation, then
1213
1531
  dispatch a fresh abort invocation.
1214
1532
  4. Uncaught error: write terminal `faulted`.
1215
- 5. Checkpoint changed, including progress within the same phase: invoke its
1216
- phase handler in the same task invocation.
1533
+ 5. Checkpoint changed, including progress within the same phase: refresh the
1534
+ registry snapshot and either hand over (section 5.4) or invoke the phase
1535
+ handler in the same task invocation.
1217
1536
  6. Checkpoint unchanged: write terminal `faulted` because no durable progress
1218
1537
  was made.
1219
1538
 
1539
+ An abort invocation runs its abort handler once. After it settles, a step
1540
+ applies rules 1, 2, and 4; a handler that returns without a terminal outcome
1541
+ faults the task. When Storage rejects a step's fault or handover write, the
1542
+ invocation still ends; the task stays `running` and the next reservation runs it
1543
+ again.
1544
+
1220
1545
  On open, running-task reconciliation changes surviving `running` tasks back to
1221
- `pending`, preserving their checkpoint and abort mark. Task migration then runs
1222
- before dispatch. One callback handles every supported older version; newer or
1223
- unmigratable live tasks become orphaned.
1546
+ `pending`, preserving their checkpoint and abort mark. Task migration runs at
1547
+ reservation, atomically with `pending -> running`. One callback handles every
1548
+ supported older version. A task whose definition is missing, older than the
1549
+ stored version, or fails migration stays `pending` and blocked until a fitting
1550
+ definition is registered or the task is aborted (section 5.4).
1224
1551
  `close()` marks the runtime closing, seals admission and reservation, signals
1225
1552
  invocations, and stops watches. Outside the Session line it settles admitted
1226
- commits and joins invocations plus in-flight watch callbacks before closing
1227
- storage. Later runtime commits reject, and close writes no task outcome. Closing
1553
+ commits and joins invocations before closing storage. Already-running watch callbacks remain
1554
+ caller-owned. Later runtime commits reject, and close writes no task outcome. Closing
1228
1555
  starts no fresh phase or abort invocation. It does not set abort marks,
1229
1556
  terminalize tasks, retire task documents, or publish document retirement. The
1230
1557
  hosting layer withdraws services and
@@ -1268,7 +1595,8 @@ A terminal transition atomically:
1268
1595
  The execution checkpoint and memos disappear from the terminal representation.
1269
1596
  Terminal records remain queryable for dependencies, waiters, inspection, and
1270
1597
  reopen. A normal run becomes eligible when every `after` task is terminal. An abort
1271
- mark bypasses dependencies so pending work can always reach its abort handler.
1598
+ mark bypasses dependencies so pending work can always reach its abort handler,
1599
+ or its `orphaned` settlement when its definition is unavailable.
1272
1600
 
1273
1601
  ### 5.4 Scheduler, abort, and ownership
1274
1602
 
@@ -1293,50 +1621,132 @@ the durable mark on reopen. Cancelling one caller's `Context` only cancels
1293
1621
  that call or wait; it does not durably abort shared work unless the invoked API
1294
1622
  commits an abort mark.
1295
1623
 
1296
- A task may create owned conversations. Abort and idle operations traverse the
1297
- conversation ownership tree. History parents are irrelevant to this traversal.
1298
- Background tasks do not block ordinary idle waits and survive ordinary
1299
- conversation abort unless explicitly included.
1300
-
1301
- Initial task definitions are registered before open performs live-task migration
1302
- and orphan reconciliation. Dynamic registration begins only after that pass.
1303
- Document migration remains access-driven. Unknown or unmigratable live task kinds
1304
- become terminal `orphaned`;
1305
- affected input submissions become unanswered, any matching active turn control is cleared,
1306
- task-scoped documents retire, and a visible notice entry is appended in one
1307
- commit. Faulting a turn task performs the same control/submission cleanup with a
1624
+ A task may create owned conversations. Conversations are durable scopes; tasks
1625
+ are the units of live work counted by idle and marked by abort. History parents
1626
+ are irrelevant to ownership traversal.
1627
+
1628
+ Ordinary traversal starts at an explicitly addressed conversation, visits its
1629
+ tasks, and follows conversations owned by each non-background task. It follows
1630
+ owner edges after the owner becomes terminal, but a background owner is a
1631
+ boundary: ordinary traversal skips that task and its complete owned subtree.
1632
+ Direct conversation operations start inside that conversation regardless of its
1633
+ owner. Directly aborting a live background task includes that task and follows
1634
+ its ordinary owned subtree; nested background owners remain boundaries. Full
1635
+ teardown crosses every boundary, marks every live task, and must seal new
1636
+ admission while it gathers the complete indexed ownership subtree.
1637
+
1638
+ `Conversation.abort()` withdraws queued inputs and marks live non-background
1639
+ tasks selected by ordinary traversal. `Conversation.waitForIdle()` waits until
1640
+ that traversal contains no live non-background task. Harness idle performs the
1641
+ same traversal from every ownerless conversation root rather than globally
1642
+ counting tasks, so ordinary work below a background owner does not block it.
1643
+ Explicit `waitForTask()` waits for its referenced task regardless of the task's
1644
+ background flag.
1645
+
1646
+ An abort mark atomically and idempotently cascades to foreground-owned work,
1647
+ including conversations, tasks, and submissions staged in the same transaction.
1648
+ Terminal outcomes `failed`, `faulted`, `orphaned`, and `aborted` record the same
1649
+ durable cancellation intent; `completed` does not. Conversation records and
1650
+ owner edges are never retired with the task. Active invocations are signalled
1651
+ after commit, and a terminal receipt guarantees durable cancellation intent,
1652
+ not descendant quiescence.
1653
+
1654
+ Every run invocation start resolves the task's definition by `TaskRecord.kind`
1655
+ from the scheduler's current registry snapshot:
1656
+
1657
+ ```text
1658
+ definition missing -> stay pending, blocked: missing_task
1659
+ stored version newer than it -> stay pending, blocked: task_too_old
1660
+ stored version older than it -> migrate(input, checkpoint, storedVersion)
1661
+ failure -> stay pending, blocked: migration_failed
1662
+ success -> commit migrated record + running atomically
1663
+ equal version -> commit running
1664
+ ```
1665
+
1666
+ An abort invocation resolves the definition the same way. When the definition
1667
+ can take the task, its abort handler runs; otherwise the task is orphaned as
1668
+ described below.
1669
+
1670
+ A failed migration is reported once through `onReport` and retried only after
1671
+ the registry resolves a different definition object for the task's kind.
1672
+
1673
+ The Harness never terminalizes a task merely because registry code is missing or
1674
+ incompatible, neither at open nor later. A blocked task without an abort mark
1675
+ keeps its durable record unchanged, remains live, still blocks ordinary idle
1676
+ waits, and is reconsidered whenever the registry changes. The blocked reason is derived
1677
+ runtime state, not a persisted task status. Document migration remains
1678
+ access-driven.
1679
+
1680
+ Aborting a blocked task cannot run its abort handler, because that code is
1681
+ missing or cannot take the task. The Harness therefore settles it as terminal
1682
+ `orphaned` instead of `aborted`: `aborted` means the task's own abort handler
1683
+ ran and decided the outcome, while `orphaned` means no task code ran, so external
1684
+ effects the task started may remain uncleaned. The orphaned `reason` is the
1685
+ blocked reason (`missing_task`, `task_too_old`, or `migration_failed`). When
1686
+ `abortTask()` finds no active invocation and the current snapshot
1687
+ cannot take the task, the marking commit settles it directly; otherwise the
1688
+ scheduler settles it when it would reserve the abort invocation. Only an abort (direct, by
1689
+ conversation, or by cascade) orphans a task; a missing definition alone never
1690
+ does. The orphaning commit performs the cleanup the task's code cannot: affected
1691
+ input submissions become unanswered with the reason, any matching active run
1692
+ control is cleared, and task-scoped documents retire. No transcript entry is
1693
+ written; the terminal task record and unanswered submissions carry the reason.
1694
+ Faulting a run task performs the same control/submission cleanup with a
1308
1695
  `faulted` outcome.
1309
1696
 
1697
+ The scheduler knows nothing about runs or task kinds. The Harness, which owns
1698
+ submissions, run control, and the built-in tasks, gives it one hook that the
1699
+ scheduler calls in the same commit for every terminal outcome it writes itself
1700
+ (`faulted` and `orphaned`). The hook ignores tasks whose kind is not a built-in
1701
+ run kind, so it never creates `pi.live` elsewhere. It settles the run when
1702
+ `pi.live.run` names the task (section 8): its inputs become `unanswered` with reason `faulted`
1703
+ (detail: the error message) or the blocked reason, and `run` and `generation`
1704
+ are removed. Outcomes a task commits for itself do their own settlement.
1705
+
1706
+ At every normal phase boundary (section 5.1, rule 5), the step refreshes the
1707
+ invocation's registry snapshot. If the task definition resolved by name is a different object
1708
+ than the one the invocation started with and the new definition can reserve the
1709
+ task (same version, or a higher version with `migrate`), the invocation hands
1710
+ over: the step commits the task back to `pending` with its checkpoint, memos,
1711
+ and abort mark and ends the invocation, and the next reservation starts a fresh invocation under the new
1712
+ definition, applying the reservation rules above. When the definition is missing
1713
+ or cannot reserve the task, the invocation keeps running under its old
1714
+ definition, reports once through `onReport` per resolved definition, and
1715
+ reconsiders at its next boundary. A handler that
1716
+ never settles never hands over.
1717
+
1310
1718
  ## 6. Submissions and inbox
1311
1719
 
1312
- Submission records back awaitable host objects. Their record transitions use
1313
- Session-private transaction operations, not the public `Tx` interface. The inbox
1720
+ Submission records back awaitable host objects. Admission is Harness-internal;
1721
+ run tasks settle the inputs they answer with `tx.settleSubmission()`. The inbox
1314
1722
  itself is an ordered conversation document containing tagged items:
1315
1723
 
1316
1724
  ```ts
1317
1725
  type InboxItem =
1318
- | { readonly id: Id; readonly mode: "steer" | "followUp"; readonly message: Message }
1319
- | { readonly id: Id; readonly mode: "write"; readonly entry: EntryDraft };
1726
+ | { readonly id: SubmissionId; readonly mode: "steer" | "followUp"; readonly message: Message }
1727
+ | { readonly id: SubmissionId; readonly mode: "write"; readonly entry: EntryDraft };
1320
1728
  ```
1321
1729
 
1322
- A built-in turn-control document has an optional `active` value naming the task
1323
- currently responsible for the turn and its placed input-submission IDs. `active !==
1324
- undefined` defines `busy`; get-or-create of the idle document does not. The
1325
- value remains active while generation, tools, and post-tools hand work to one
1326
- another.
1730
+ Run control lives in the built-in live document `pi.live` (section 8). Its
1731
+ optional `run` value names the task currently responsible for the run and its
1732
+ placed input-submission IDs. `run !== undefined` defines `busy`; get-or-create
1733
+ of the idle document does not. The value remains while generation, tools, and
1734
+ post-tools hand work to one another. The ID list is mutable state because a
1735
+ boundary adds placed steering inputs to an active run; every terminal path
1736
+ settles exactly the listed inputs.
1327
1737
 
1328
1738
  Admission and terminal transitions:
1329
1739
 
1330
1740
  | action | submission state | other writes |
1331
1741
  |---|---|---|
1332
- | idle input submission | `placed`, with user entry | create turn controller/generation |
1742
+ | idle input submission | `placed`, with user entry | create run controller/generation |
1333
1743
  | busy input submission | `queued` | append steer/follow-up inbox item |
1334
- | idle write submission | `done`, with entry | append entry; no turn |
1744
+ | idle write submission | `done`, with entry | append entry; no run |
1335
1745
  | busy write submission | `queued` | append write inbox item |
1336
- | boundary places user item | `placed`, with entry | add ID to current/successor turn |
1746
+ | boundary places user item | `placed`, with entry | add ID to current/successor run |
1337
1747
  | boundary places write | `done`, with entry | append entry |
1338
- | turn answers | input `done`, with required answer entry | clear/hand off turn controller |
1339
- | turn fails or aborts | input `unanswered`, with reason | clear/hand off turn controller |
1748
+ | run answers | input `done`, with required answer entry | clear/hand off run controller |
1749
+ | run fails or aborts | input `unanswered`, with reason | clear/hand off run controller |
1340
1750
  | withdraw queued item | `unanswered`, reason `aborted` | remove inbox item |
1341
1751
  | stale item | `unanswered`, reason `stale` | remove inbox item |
1342
1752
 
@@ -1357,33 +1767,233 @@ Boundary selection is deterministic by item ID:
1357
1767
  | `final` | all | first/all by mode | first/all by mode |
1358
1768
 
1359
1769
  A queued self-head write cuts older pending user items: those submissions become
1360
- stale, the write is placed, and the current turn terminates. Other head writes
1770
+ stale, the write is placed, and the current run terminates. Other head writes
1361
1771
  whose target predates the caller's newest known head are stale.
1362
1772
 
1363
1773
  At ordinary `postTools`, generation continues even with no queued trigger;
1364
1774
  selected steer IDs join that continuation. A terminating/handoff post-tools
1365
- boundary uses final behavior instead. At `final`, the current turn's placed
1775
+ boundary uses final behavior instead. At `final`, the current run's placed
1366
1776
  input submissions settle first; selected user IDs start one successor generation. Writes
1367
1777
  never trigger generation by themselves. A final boundary without continuation
1368
1778
  or user triggers leaves the conversation idle.
1369
1779
 
1370
1780
  Selected and stale items are removed positionally while retained item order is
1371
- preserved. Chord's revision differ must express scattered removals without
1372
- carrying retained values; IDs are not substituted for positional inbox
1781
+ preserved. Chord's Astra operation generator must express scattered removals
1782
+ without carrying retained values; IDs are not substituted for positional inbox
1373
1783
  semantics.
1374
1784
 
1375
- ## 7. Hooks, tools, and system sections
1785
+ ## 7. Registry, hooks, tools, and system prompt
1786
+
1787
+ ### 7.1 Registry
1788
+
1789
+ Extension code reaches the Harness through one application-owned registry. The
1790
+ registry is process-local, may outlive a Harness, and is the only place tools,
1791
+ tool wrappers, hooks, tasks, and the system prompt are registered. Nothing
1792
+ in it is persisted; durable state stays in conversations, entries, tasks, and
1793
+ documents.
1794
+
1795
+ ```ts
1796
+ type DocumentReader = Pick<Session, "snapshot" | "snapshotAsOf">;
1797
+
1798
+ interface Registration {
1799
+ /** Idempotent; removes exactly the registrations this token covers. */
1800
+ dispose(): void;
1801
+ }
1802
+
1803
+ type ToolWrapper<Tool extends ToolRegistration> = (tool: Tool) => Tool;
1804
+
1805
+ type HookScope = {
1806
+ readonly conversationId: ConversationId;
1807
+ /** Also match conversations owned, transitively, by tasks of this conversation. */
1808
+ readonly subtree?: boolean;
1809
+ };
1810
+
1811
+ type PromptInput<Tool extends ToolRegistration> = {
1812
+ readonly conversationId: ConversationId;
1813
+ /** Active and registered tools in configured order, as offered in this request. */
1814
+ readonly tools: readonly Tool[];
1815
+ /** Sections already in effect after replaying the active transcript. */
1816
+ readonly shown: Readonly<Record<string, string>>;
1817
+ readonly model?: ModelRef;
1818
+ readonly thinkingLevel: ModelThinkingLevel;
1819
+ /** Committed document reads. */
1820
+ readonly read: DocumentReader;
1821
+ };
1822
+
1823
+ type PromptSection<Tool extends ToolRegistration> = {
1824
+ readonly key: string;
1825
+ render(
1826
+ input: PromptInput<Tool>,
1827
+ context: Context,
1828
+ ): string | undefined | Promise<string | undefined>;
1829
+ /** Default true: wrap the text as `<key>\n...\n</key>`. */
1830
+ readonly tag?: boolean;
1831
+ };
1376
1832
 
1377
- ### 7.1 Hooks
1833
+ type PromptSectionWrapper<Tool extends ToolRegistration> = (
1834
+ section: PromptSection<Tool>,
1835
+ ) => PromptSection<Tool>;
1836
+
1837
+ /**
1838
+ * Stages the documents every new conversation gets, inside the creating commit, after fork copies and before host
1839
+ * `init`. Table reads throw; a fork (`conversation.parent`) already holds its copied documents. A throw fails the
1840
+ * creation.
1841
+ */
1842
+ type ConversationSetup = (
1843
+ tx: Tx,
1844
+ conversation: ConversationRecord,
1845
+ registry: RegistrySnapshot<ToolRegistration>,
1846
+ ) => void | Promise<void>;
1847
+
1848
+ type RegistryFailure = {
1849
+ readonly kind: "tool" | "section";
1850
+ /** Tool name or section key. */
1851
+ readonly name: string;
1852
+ readonly error: unknown;
1853
+ };
1854
+
1855
+ interface RegistryReader<Tool extends ToolRegistration = ToolRegistration> {
1856
+ /** Immutable view of the whole current registry. */
1857
+ snapshot(): RegistrySnapshot<Tool>;
1858
+ /** Called synchronously after every publication; wakes the scheduler to reconsider blocked tasks. */
1859
+ subscribe(listener: () => void): () => void;
1860
+ }
1861
+
1862
+ interface RegistrySnapshot<Tool extends ToolRegistration> {
1863
+ /** Composed tools in registry order; a tool whose wrapper failed is absent. */
1864
+ tools(): readonly Tool[];
1865
+ tool(name: string): Tool | undefined;
1866
+ /** Base tool names in registry order, including tools whose wrappers fail. */
1867
+ toolNames(): readonly string[];
1868
+ task(name: string): AnyTask | undefined;
1869
+ /** Hooks registered for tasks with `task`'s name, in registry order. */
1870
+ hooks<K extends AnyTask>(task: K): readonly {
1871
+ readonly handlers: Partial<HooksOf<K>>;
1872
+ readonly scope?: HookScope;
1873
+ }[];
1874
+ /** Composed sections in registry order; a section whose wrapper failed is absent. */
1875
+ sections(): readonly PromptSection<Tool>[];
1876
+ /** Wrapper failures of this state; the Harness reports them where it uses them. */
1877
+ failures(): readonly RegistryFailure[];
1878
+ /** Conversation setups in registry order, the built-in `pi` setup first. */
1879
+ conversationSetups(): readonly { readonly key: string; readonly setup: ConversationSetup }[];
1880
+ }
1881
+
1882
+ interface Registry<Tool extends ToolRegistration = ToolRegistration> extends RegistryReader<Tool> {
1883
+ readonly tools: {
1884
+ add(tool: Tool): Registration;
1885
+ wrap(name: string, key: string, wrapper: ToolWrapper<Tool>): Registration;
1886
+ list(): readonly Tool[];
1887
+ };
1888
+ readonly hooks: {
1889
+ add<K extends AnyTask>(
1890
+ task: K,
1891
+ handlers: Partial<HooksOf<K>>,
1892
+ options?: { readonly scope?: HookScope; readonly key?: string },
1893
+ ): Registration;
1894
+ };
1895
+ readonly tasks: {
1896
+ add(task: AnyTask): Registration;
1897
+ list(): readonly AnyTask[];
1898
+ };
1899
+ readonly conversations: {
1900
+ setup(key: string, setup: ConversationSetup): Registration;
1901
+ };
1902
+ readonly systemPrompt: {
1903
+ section(
1904
+ key: string,
1905
+ render: PromptSection<Tool>["render"],
1906
+ options?: { readonly tag?: boolean },
1907
+ ): Registration;
1908
+ wrap(key: string, wrapperKey: string, wrapper: PromptSectionWrapper<Tool>): Registration;
1909
+ sections(): readonly PromptSection<Tool>[];
1910
+ };
1911
+ batch(register: () => void): Registration;
1912
+ }
1913
+
1914
+ function createRegistry<Tool extends ToolRegistration = ToolRegistration>(): Registry<Tool>;
1915
+ ```
1916
+
1917
+ The `Tool` parameter lets applications attach metadata such as prompt snippets to
1918
+ their tools; the Harness only relies on `ToolRegistration`. Pi-ai declarations
1919
+ derived from a registered tool keep only pi-ai `Tool` fields (`toToolDeclaration`),
1920
+ so application metadata never enters the transcript.
1921
+
1922
+ Registration rules:
1923
+
1924
+ - `createRegistry()` starts with the built-in task definitions of section 8 and
1925
+ the built-in `pi` conversation setup registered first. They have no
1926
+ `Registration`, so they cannot be disposed, and the duplicate rule rejects
1927
+ another task with a built-in name or another `pi` setup. `tasks.list()`
1928
+ includes them. Hooks register against built-in tasks like any other task.
1929
+ Setup keys are unique and ordered like section keys.
1930
+ - Tool names, section keys, and task names are unique among published
1931
+ registrations. Tool wrapper keys are unique per tool name, section wrapper
1932
+ keys per section key, and hook keys per task name. Duplicates reject.
1933
+ Section keys match `^[a-z][a-z0-9_-]*$`.
1934
+ - Keyed slots are ordered by the position at which their key was first
1935
+ registered. The registry remembers that position forever, so re-registering an
1936
+ existing key, as a reload does, keeps its position; a new key appends. Hooks
1937
+ without a key append.
1938
+ - Registered objects are immutable and wrappers are pure: a wrapper returns a
1939
+ new object and never mutates its input.
1940
+ - Every call outside `batch()` publishes immediately. Publication is synchronous,
1941
+ invokes no extension callback, and notifies subscribers.
1942
+
1943
+ `batch(register)` stages every registration and disposal made while `register`
1944
+ runs and publishes once when it returns. It validates only the final staged
1945
+ state, so order inside the block does not matter: disposing an old tool and
1946
+ adding its replacement is a gapless reload. If `register` throws, returns a
1947
+ thenable, or the final state is invalid, nothing is published, staged disposals
1948
+ are rolled back, and `batch()` throws. Only registrations made synchronously
1949
+ inside `register` belong to the batch; a registration made later by a detached
1950
+ continuation is an ordinary immediate registration. Calling `batch()` inside a
1951
+ batch is a programming error and throws. The returned `Registration` covers every
1952
+ registration added in the batch that was not disposed inside it.
1953
+
1954
+ A snapshot is a plain immutable value; nothing is released. The scheduler takes
1955
+ one per phase-handler invocation and passes it through the runtime; handlers and
1956
+ hooks read that snapshot and never take their own. At every normal phase boundary
1957
+ the scheduler takes a fresh one (section 5.4). A tool task keeps the composed tool
1958
+ it pinned until execution settles. Different phases may observe different
1959
+ registry states; nothing requires one run to see a single registry state across
1960
+ its generation, tool, and post-tools tasks. Host operations, such as the create
1961
+ conveniences, take one snapshot inside their commit.
1962
+
1963
+ ```ts
1964
+ // ToolTask is the built-in tool task's token; its hooks are listed in section 7.2.
1965
+ const registration = registry.batch(() => {
1966
+ registry.tools.add(grep);
1967
+ registry.hooks.add(ToolTask, { beforeTool: audit }, { key: "audit" });
1968
+ });
1969
+ // later, reload: publish the replacement at once
1970
+ registry.batch(() => {
1971
+ registration.dispose();
1972
+ registry.tools.add(grepV2);
1973
+ registry.hooks.add(ToolTask, { beforeTool: audit2 }, { key: "audit" });
1974
+ });
1975
+ ```
1976
+
1977
+ The registry does not track which running work still uses a disposed
1978
+ registration. Work that already started keeps using the code it took, so an
1979
+ extension that frees resources right after `dispose()` can make a still-running
1980
+ call fail with an ordinary error result. Extensions that need graceful disposal
1981
+ manage their resources' lifetime themselves, for example by reference counting.
1982
+
1983
+ ### 7.2 Hooks
1378
1984
 
1379
1985
  A hook is a typed question asked by a task before it commits a decision. Hooks
1380
- are declared by task kind and registered in registration order Session-wide or
1381
- for a conversation and its owned subtree. They run off the line; a crash before
1382
- the consuming commit may rerun them. Abort errors always propagate.
1986
+ are declared by task definition and registered through `registry.hooks.add()`
1987
+ Session-wide or, with `scope`, for one conversation and optionally its owned
1988
+ subtree. Subtree matching follows conversation ownership, not history parents.
1989
+ Registration is typed by the task token, but dispatch matches the task's name,
1990
+ so hooks survive a reload of their task; keeping hook signatures compatible
1991
+ across task versions is the task author's responsibility. Hooks run in registry
1992
+ order off the line; a crash before the consuming commit may rerun them. Abort
1993
+ errors always propagate.
1383
1994
 
1384
1995
  | hook | composition | ordinary throw |
1385
1996
  |---|---|---|
1386
- | system instructions | all; draft changes compose; last tool override wins | roll back that handler, report, continue |
1387
1997
  | `beforeRequest` | replacement chain | report, continue |
1388
1998
  | `afterResponse` | all observers | report, continue |
1389
1999
  | `onYield` | first continuation wins | report, continue |
@@ -1395,7 +2005,7 @@ the consuming commit may rerun them. Abort errors always propagate.
1395
2005
  Hooks use task memos for durable first-writer-wins decisions. There is no public
1396
2006
  semantic event channel; current UI status is document state.
1397
2007
 
1398
- ### 7.2 Tools
2008
+ ### 7.3 Tools
1399
2009
 
1400
2010
  ```ts
1401
2011
  type ToolControl = {
@@ -1411,20 +2021,20 @@ type ToolExecutionResult = {
1411
2021
  readonly control?: ToolControl;
1412
2022
  };
1413
2023
 
1414
- interface OwnedConversation {
1415
- readonly id: Id;
2024
+ interface ConversationHandle {
2025
+ readonly id: ConversationId;
1416
2026
  submit(submission: InputSubmissionDraft, context: Context): Promise<Submission>;
1417
2027
  abort(context: Context): Promise<void>;
1418
2028
  waitForIdle(context: Context): Promise<void>;
1419
2029
  }
1420
2030
 
1421
- interface ToolExecutionApi extends DocumentObserver {
1422
- readonly taskId: Id;
1423
- readonly conversationId: Id;
2031
+ interface ToolExecutionApi extends DocumentObserver, DocumentReader {
2032
+ readonly taskId: TaskId;
2033
+ readonly conversationId: ConversationId;
1424
2034
  readonly callId: string;
1425
- stream(chunk: string | Uint8Array): void;
2035
+ output(chunk: string | Uint8Array): void;
2036
+ details(value: JsonValue, context: Context): Promise<void>;
1426
2037
  commit<T>(change: (tx: Tx) => T | Promise<T>, context: Context): Promise<T>;
1427
- progress(value: JsonObject, context: Context): Promise<void>;
1428
2038
  memo<T extends JsonValue>(name: string, context: Context): Promise<T | undefined>;
1429
2039
  memo<T extends JsonValue>(name: string, candidate: T, context: Context): Promise<T>;
1430
2040
  createTask<I, S extends { phase: string }, R, H extends object>(
@@ -1432,18 +2042,15 @@ interface ToolExecutionApi extends DocumentObserver {
1432
2042
  input: I,
1433
2043
  options: Omit<TaskOptions, "conversationId">,
1434
2044
  context: Context,
1435
- ): Promise<TaskRef<R>>;
1436
- getTask<R>(ref: TaskRef<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;
1437
- waitForTask<R>(ref: TaskRef<R>, context: Context): Promise<SettledTask<R>>;
1438
- createConversation(
1439
- spec: Omit<ConversationSpec, "parent"> & { readonly inherit?: boolean },
1440
- context: Context,
1441
- ): Promise<OwnedConversation>;
2045
+ ): Promise<TaskId<R>>;
2046
+ getTask<R>(id: TaskId<R>, context: Context): Promise<TaskRecord<JsonValue, JsonValue, R> | undefined>;
2047
+ waitForTask<R>(id: TaskId<R>, context: Context): Promise<SettledTask<R>>;
2048
+ conversation(id: ConversationId, context: Context): Promise<ConversationHandle | undefined>;
1442
2049
  }
1443
2050
 
1444
2051
  type ToolRegistration = Tool & {
1445
2052
  readonly replay?: "safe" | "unsafe";
1446
- readonly output?: {
2053
+ readonly outputLimits?: {
1447
2054
  readonly maxBytes?: number;
1448
2055
  readonly maxLines?: number;
1449
2056
  readonly retain?: "head" | "tail";
@@ -1456,60 +2063,138 @@ type ToolRegistration = Tool & {
1456
2063
  };
1457
2064
  ```
1458
2065
 
1459
- Omitted `replay` is `unsafe`. Omitted output bounds are 64 KiB, 200 lines, and
1460
- `retain: "head"`. `stream()` synchronously accepts UTF-8 output into that
1461
- invocation-owned bounded buffer and throws after invocation end. Throttled
1462
- commits publish the retained output and dropped byte/line counts in the tool
1463
- presentation document. If `execute()` omits `content`, the final retained stream
1464
- becomes one text content item; no stream becomes an empty content list. Explicit
2066
+ Omitted `replay` is `unsafe`. Omitted `outputLimits` are 50 KiB, 2,000 lines,
2067
+ and `retain: "head"`.
2068
+
2069
+ A running tool reports two things to the UI, mirroring the two halves of its
2070
+ final result:
2071
+
2072
+ - `output(chunk)` appends running text output, like stdout. If `execute()` omits
2073
+ `content`, the final retained output becomes one text content item; no output
2074
+ becomes an empty content list.
2075
+ - `details(value)` replaces the running details with a complete JSON value; it
2076
+ does not merge keys. If `execute()` omits `details`, the last value becomes the
2077
+ final `details`, so a renderer handles one details shape from the first
2078
+ update through the final result.
2079
+
2080
+ Neither is sent to the model while the tool runs. `output()` synchronously
2081
+ accepts UTF-8 output into that invocation-owned bounded buffer and throws after
2082
+ invocation end. Throttled commits publish the retained output, dropped
2083
+ byte/line counts, and the current details in the tool presentation document. Explicit
1465
2084
  text in explicit result content is bounded by the same limits before transcript
1466
2085
  persistence; non-text content is retained as declared by its pi-ai type.
1467
2086
 
1468
- `progress(value)` replaces the invocation's complete JSON `progress` payload; it
1469
- does not merge keys. Its promise resolves after the corresponding or coalesced
1470
- document commit. During normal settlement, accepted output updates drain before
2087
+ `output()` never spills complete output to a file because spilling requires a
2088
+ filesystem, which may be remote or unavailable. A tool that must preserve
2089
+ complete output spills through the `ExecutionEnv` or `FileSystem` it was given,
2090
+ such as shell execution with spill capture, and reports the resulting path in its
2091
+ details.
2092
+
2093
+ The `details()` promise resolves after the corresponding or coalesced document
2094
+ commit. During normal settlement, accepted output updates drain before
1471
2095
  the tool-result entry and terminal task record commit. Abort and close obey
1472
2096
  invocation and Session admission gates: uncommitted buffered updates may be
1473
2097
  discarded, while admitted commits settle. Cancellation, callback, tracker
1474
2098
  preparation, and checkpoint failures occur before Storage admission and do not
1475
2099
  poison the Session. An uncertain Storage failure follows the fatal Session rule.
1476
2100
 
1477
- Tools are dynamically registered declarations with name, description, JSON
1478
- schema, replay policy, and execute function. A tool call is accepted only if it
1479
- was offered in the request's effective system/tool history. Arguments are
1480
- validated before and after `beforeTool` hooks.
2101
+ Tools are registry entries (section 7.1) with name, description, JSON schema,
2102
+ replay policy, and execute function. `registry.tools.wrap(name, key, wrapper)`
2103
+ decorates a tool without replacing it. Each snapshot composes the current base
2104
+ tool with its wrappers in registry order; a wrapper never captures a base, so
2105
+ reloading the base keeps its wrappers. A wrapper that throws or returns a tool
2106
+ with a different name makes that tool absent from the snapshot (fail closed:
2107
+ not offered, and calls produce `tool_unavailable`) and is reported. A wrapper
2108
+ without a base contributes nothing. The composite supplies the declaration,
2109
+ argument validation, replay policy, and execution.
2110
+
2111
+ A tool call is accepted only if it was offered in the request's effective
2112
+ system/tool history. A call to a tool that is not offered or has no registered
2113
+ implementation produces the `tool_unavailable` error result described in section
2114
+ 2.2 instead of failing the run. The tool task resolves the composed tool once
2115
+ from its snapshot before argument validation and pins it until execution
2116
+ settles, even across later snapshot refreshes. Arguments must satisfy both the offered
2117
+ declaration and the pinned implementation's schema; they are validated before
2118
+ and after `beforeTool` hooks.
1481
2119
 
1482
2120
  After hooks and validation, the tool task durably records the final call and
1483
2121
  resolved replay policy before execution. Recovery does not rerun `beforeTool`
1484
- and does not let a changed registry declaration alter that stored policy.
2122
+ and passes the same stored arguments to `execute()`. A replay-safe tool may
2123
+ reconstruct a submission from those arguments when that transformation is pure.
2124
+ Random values, timestamps, mutable document/configuration reads, or other derived
2125
+ inputs that must remain stable are first captured in a durable memo, checkpoint,
2126
+ or task input. A background supervisor receives the final submission draft in
2127
+ its own durable input so it can finish independently. Recovery does not let a
2128
+ changed registry declaration alter the stored replay policy.
1485
2129
 
1486
- An owned conversation accepts only input submissions; tools use ordinary
1487
- transaction writes for passive entries.
2130
+ A tool-acquired conversation handle accepts only input submissions; tools use
2131
+ ordinary transaction writes for passive entries.
1488
2132
 
1489
2133
  A tool executes in a durable task. It may:
1490
2134
 
1491
- - write bounded progress/output to a presentation or task-scoped document;
2135
+ - publish bounded running output and details to its presentation document;
1492
2136
  - commit memos;
1493
2137
  - create and wait for tasks;
1494
- - create owned conversations;
2138
+ - atomically create or fork explicitly owned conversations through `commit()`;
1495
2139
  - observe documents for which it has a token/reference;
1496
2140
  - mutate authorized documents through `commit()`;
1497
2141
  - return bounded model content and separate diagnostic details.
1498
2142
 
1499
- Tool operations use the invoking task's admission and
1500
- invocation-lifetime gates. Task creation defaults to that task's conversation.
1501
- Trusted document access follows sections 3.3 and 9.2; there is no additional
1502
- document subtree authorization layer. `createConversation()` records the
1503
- invoking task as owner and returns an invocation-bound handle. `inherit` defaults
1504
- to `false`. When true, creation atomically selects the invoking conversation's
1505
- newest committed visible entry as `parent.at`; if no entry exists, it creates no
1506
- history parent. Conversation documents then apply section 3.7 at that entry, and
1507
- explicit model/section seeds override their inherited built-in values. With no
1508
- parent, documents initialize normally. That handle's
1509
- operations reject after the invocation ends. A `Submission` returned by its
1510
- `submit()` is invocation-bound in the same way; the admitted submission remains
1511
- durable after those methods reject. Invocation-owned document watches stop when
1512
- the invocation ends.
2143
+ Tool operations use the invoking task's admission and invocation-lifetime gates.
2144
+ Task creation defaults to that task's conversation. Trusted document and
2145
+ conversation access follows sections 3.3 and 9.2; there is no additional subtree
2146
+ authorization layer. Possession of a Session-global typed ID is sufficient in
2147
+ trusted code.
2148
+
2149
+ Tools have no conversation-creation convenience method. They create or fork a
2150
+ conversation inside `commit()`, state its ownership explicitly, atomically stage
2151
+ any related document/task writes, and receive only the inert record. After that
2152
+ commit settles, `conversation(id)` acquires an invocation-bound operational
2153
+ handle for submission, explicit abort, and idle waits without changing
2154
+ ownership. A commit callback must not call `conversation()` or use a previously
2155
+ acquired handle: nested Session operations and external effects are forbidden
2156
+ while the mutation line is held. A handle's operations reject after the
2157
+ invocation ends. A `Submission` returned by its `submit()` is invocation-bound in
2158
+ the same way; the admitted submission remains durable after those methods reject.
2159
+ Invocation-owned document watches stop when the invocation ends.
2160
+
2161
+ A foreground subagent conversation is explicitly owned by its tool task. One
2162
+ transaction creates or forks the child and records its durable registry mapping;
2163
+ after settlement the tool reacquires the child, submits with the registered
2164
+ request ID, and waits for that submission's result. Aborting or abnormally
2165
+ terminalizing the tool task cascades through the owned scope.
2166
+
2167
+ A background subagent is provisioned in one transaction. After deduplicating by
2168
+ its durable registry key, the tool stages a background supervisor task `B`, a
2169
+ child conversation `C` explicitly owned by `B`, and the registry mapping from the
2170
+ semantic name to `C` plus its stable request ID. `B` may be staged earlier in the
2171
+ same transaction and used immediately as `C`'s owner. Its durable input contains
2172
+ the exact submission draft and the registry location/key; it need not contain
2173
+ `C`'s not-yet-created ID. Once scheduled, `B` resolves `C` from the mapping,
2174
+ verifies the immutable owner edge, and performs normal `Conversation.submit()`.
2175
+ A crash before admission makes `B` retry; a crash after admission returns the
2176
+ existing request-ID-deduplicated `Submission`. The initiating tool may race the
2177
+ same submit for lower latency and wait only for the durable admission receipt.
2178
+ The supervisor may complete after setup: its terminal record retains
2179
+ `background`, so ancestor ordinary abort and idle traversal continue to stop at
2180
+ its owned scope.
2181
+
2182
+ Applications may maintain a conversation document mapping semantic subagent
2183
+ names to durable conversation IDs and application-minted submission request IDs.
2184
+ Such a live registry uses `fork: "initial"` so children do not inherit the
2185
+ parent's agent list and its update is not a selected fork source. Conversation
2186
+ creation/forking, supervisor creation when applicable, and the registry mapping
2187
+ commit atomically. The supervisor input, tool's durable final arguments, or a
2188
+ durable checkpoint must retain enough information to reconstruct the exact
2189
+ submission draft; the registry itself need not duplicate that payload. Initial
2190
+ or later input then uses the registered stable request ID with the full
2191
+ `Conversation.submit()` state machine. A crash before admission leaves a durable
2192
+ request to submit; a crash after admission retries the same request and receives
2193
+ the existing `Submission`. A read-only lookup by conversation/request ID can
2194
+ report absence or return the durable queued/placed/done/unanswered receipt.
2195
+ Submission admission therefore needs no private transaction shortcut and does
2196
+ not move onto `Tx`. Kernel ownership indexes independently drive abort and idle
2197
+ traversal.
1513
2198
 
1514
2199
  A tool result may request `addTools`, `terminate`, or `handoff`. Post-tools
1515
2200
  applies added tool names to configured loadout, uses a final boundary for
@@ -1517,27 +2202,19 @@ terminate/handoff, and writes a headed handoff entry when requested.
1517
2202
 
1518
2203
  On reopen, a tool reruns only when both its stored intent policy and the current
1519
2204
  registered declaration say `safe`. A current `unsafe` declaration may veto a
1520
- stored-safe replay; a current-safe declaration never upgrades stored unsafe.
1521
- Every other orphaned effect produces an interrupted result containing the
2205
+ stored-safe replay; a current-safe declaration never upgrades stored unsafe. A
2206
+ tool with no current registration is treated as `unsafe`. Every other orphaned
2207
+ effect produces an interrupted result containing the
1522
2208
  durable partial output. Completed, failed, and aborted
1523
2209
  tool terminal outcomes retain their tool-result entry ID for post-tools.
1524
2210
 
1525
- ### 7.3 System sections and dynamic tools
1526
-
1527
- ```ts
1528
- interface SystemSection<T extends JsonValue = JsonValue> {
1529
- readonly key: string;
1530
- render(value: T): string;
1531
- }
1532
-
1533
- function defineSystemSection<T extends JsonValue>(definition: {
1534
- readonly key: string;
1535
- render(value: T): string;
1536
- }): SystemSection<T>;
1537
- ```
2211
+ ### 7.4 System prompt and dynamic tools
1538
2212
 
1539
- Pico stores prompt and tool changes directly as PR #9548 `SystemMessage` values
1540
- at their transcript positions:
2213
+ Pico has no durable prompt sections. The registry's system prompt slot produces
2214
+ the desired sections for each request; the transcript's `pi.system` entries are
2215
+ the only durable record of what the model saw. Pico stores prompt and tool
2216
+ changes directly as PR #9548 `SystemMessage` values at their transcript
2217
+ positions, always with empty `content`:
1541
2218
 
1542
2219
  ```ts
1543
2220
  type SystemEntry = EntryRecord & {
@@ -1547,8 +2224,8 @@ type SystemEntry = EntryRecord & {
1547
2224
 
1548
2225
  const baseline: SystemMessage = {
1549
2226
  role: "system",
1550
- content: basePrompt,
1551
- sections: { persona: renderedPersona, cwd: renderedCwd },
2227
+ content: "",
2228
+ sections: { preamble: renderedPreamble, cwd: renderedCwd },
1552
2229
  toolsAdded: allEffectiveTools,
1553
2230
  timestamp: now,
1554
2231
  };
@@ -1563,10 +2240,51 @@ const delta: SystemMessage = {
1563
2240
  };
1564
2241
  ```
1565
2242
 
1566
- System sections are registered by stable, non-integer-like key. Generation
1567
- prepares the desired rendered section values and effective tool roster, compares
1568
- them with the state obtained by replaying the active transcript, and appends a
1569
- positional `pi.system` baseline or delta.
2243
+ Generation preparation takes these steps against its phase snapshot:
2244
+
2245
+ 1. Read the committed configuration and replay the active transcript's system
2246
+ messages into the shown sections and offered tools.
2247
+ 2. Compute the desired tools: active names that the snapshot resolves, in
2248
+ configured order, as composed by their wrappers.
2249
+ 3. Render every registered section, in registry order, with `PromptInput`: the
2250
+ conversation, those tools, the shown sections, the configured model and
2251
+ thinking level, and a `DocumentReader` for committed documents (the task
2252
+ runtime). The results are the desired sections.
2253
+ 4. Compare desired sections and tool declarations with the replayed state and
2254
+ append one positional `pi.system` entry when they differ.
2255
+
2256
+ Preparation does not recheck the transcript before appending: only the Harness
2257
+ writes to a busy conversation, through submissions, run tasks, and boundaries,
2258
+ so the transcript it read is still current (section 12).
2259
+
2260
+ Model and thinking level are request options, not prompt state.
2261
+
2262
+ Registered sections are the only source of prompt text; there is no separate
2263
+ builder. `systemPrompt.section(key, render, { tag })` adds a section, and
2264
+ `systemPrompt.wrap(key, wrapperKey, wrapper)` decorates one, composed per
2265
+ snapshot like tool wrappers. Sections render in registry order: the position at
2266
+ which each key was first registered. A section whose `render` returns
2267
+ `undefined` is omitted, which is how a section varies by conversation. With
2268
+ `tag` omitted or true, text is wrapped as `<key>\n...\n</key>`. A section that
2269
+ throws keeps its shown text, if any, and is reported; the request is still sent.
2270
+ Errors thrown after the generation invocation is cancelled propagate; an abort
2271
+ error of the section's own, such as its fetch timing out, is an ordinary failure. With no registered sections, the desired section set is
2272
+ empty.
2273
+
2274
+ A minimal prompt is one untagged section:
2275
+
2276
+ ```ts
2277
+ registry.systemPrompt.section("preamble", () => "You are a helpful assistant.", { tag: false });
2278
+ ```
2279
+
2280
+ Sections read per-conversation data through `input.read`. For example, a
2281
+ coding agent keeps its own conversation document with the agent kind, preamble,
2282
+ and working directory; its preamble and cwd sections render from that document,
2283
+ and its AGENTS.md and skills sections return `undefined` for subagent
2284
+ conversations.
2285
+ Renderers must be deterministic for equal inputs: any change in rendered text,
2286
+ such as an embedded timestamp, appends a system delta and invalidates provider
2287
+ prompt caches.
1570
2288
 
1571
2289
  Replay applies messages in transcript order. Non-empty `content` appends
1572
2290
  instructions. A section string adds or replaces that name without moving an
@@ -1574,74 +2292,64 @@ existing section; `null` removes it, and a later re-addition appends it to the
1574
2292
  ordered section map. Within one message, tool removals happen before additions,
1575
2293
  so a same-name replacement gets the new declaration and position.
1576
2294
 
1577
- The built-in configuration document stores sections as an ordered array, never
1578
- as an object whose key order must be inferred by Delta. `setSection(section,
1579
- undefined)` removes the record; setting it later appends it at the end. Preparation compares both values and order. If values can be patched
1580
- without changing order, it emits the minimal patch. If effective and desired
1581
- section order differ, one commit appends two `pi.system` entries: the first
1582
- removes every effective section with `null`, and the second re-adds every desired
1583
- section in desired order. This makes order-only changes and deletion/re-addition
1584
- between requests replay exactly; merely restating equal values is insufficient.
2295
+ Preparation compares both values and order. If values can be patched without
2296
+ changing order, it emits the minimal patch. If shown and desired section order
2297
+ differ, one commit appends two `pi.system` entries: the first removes every
2298
+ shown section with `null`, and the second re-adds every desired section in
2299
+ desired order. This makes order-only changes and deletion/re-addition between
2300
+ requests replay exactly; merely restating equal values is insufficient.
1585
2301
 
1586
2302
  A PR #9548 `SystemMessage` is always a patch, not a reset: it cannot remove
1587
2303
  previous `content` or restore section order merely by restating current values.
1588
- Therefore, when a head removes the previous request-visible baseline, the new
2304
+ Therefore, when a head removes the previous request-visible baseline, which is
2305
+ the case when the active context has a head marker and no `pi.system` entry
2306
+ follows that marker, the new
1589
2307
  `pi.system` entry adds `ContextEdit` omissions for every earlier `pi.system`
1590
2308
  entry still retained after the cut. Its own message is then a complete baseline
1591
- containing the base `content`, every desired section in order, and every effective
1592
- tool declaration. Model-context replay sees the new baseline instead of the
1593
- omitted retained deltas. Head rebaselining takes precedence over ordinary
1594
- order/value patching. Without a head cut, an order mismatch uses the two-entry
1595
- remove/re-add sequence above; only when order already matches does preparation
1596
- emit the minimal changed values, `null` removals, and tool additions/removals.
1597
- Same-name tool replacements remove before adding. Registry or document changes
1598
- while preparation hooks run cause preparation to retry against a new snapshot.
1599
-
1600
- Conversation creation may seed section values or explicit removals. Preparation
1601
- uses a mutable section draft with get/set/delete/wrap; each throwing hook loses
1602
- only its own draft changes. The rendered strings stored in historical
1603
- `SystemMessage.sections` remain authoritative even if the current renderer
1604
- changes. Pi-ai decides whether to send the messages positionally to a capable
1605
- provider or fold them into one leading system message; Pico does not rewrite its
1606
- stored transcript for provider compatibility.
1607
-
1608
- ### 7.4 Host extension reload
1609
-
1610
- A host extension generation is the Session-side code implementing its task kinds,
1611
- hooks, tools, sections, and document definitions. Registry APIs may
1612
- change registered declarations during normal product operation, but they do not
1613
- make replacement of that implementation code safe while its callbacks are
1614
- running. Document definitions are passed explicitly to typed access rather than
1615
- registered.
1616
-
1617
- In v1, changing host extension code is a Harness generation boundary:
1618
-
1619
- 1. Stop new admission and task reservation.
1620
- 2. Close the Harness, signalling and joining its active task, tool, and hook
1621
- invocations plus in-flight watch callbacks without writing abort marks or
1622
- terminal outcomes.
1623
- 3. Dispose the old facets and registrations.
1624
- 4. Construct a new Harness over the same storage and new document tokens.
1625
- 5. Register the complete task definition set before open performs live-task
1626
- migration and orphan reconciliation. Ordinary documents migrate on later
1627
- typed access.
1628
- 6. Resume scheduling from the durable checkpoints.
1629
-
1630
- A durable task does not need to become terminal before this restart; only its
1631
- current invocation must settle. A task definition must increase its version when
1632
- the meaning of persisted input or checkpoint state changes and migrate supported
1633
- older state. Uncommitted hook work may rerun under the new generation; committed
1634
- memos remain part of the live task.
1635
-
1636
- If old extension code ignores cancellation and never settles, graceful in-process
1637
- reload cannot complete. The host must terminate that isolated worker/process
1638
- before opening the Session under the new generation. Old and new generations
1639
- must never own the same Session concurrently.
1640
-
1641
- Generation-pinned registries that drain old callbacks while routing new work to
1642
- new code, plus explicit compatible task takeover, are possible future work. Safe
1643
- forced takeover of arbitrary non-cooperative JavaScript requires worker/process
1644
- isolation and is not a v1 promise.
2309
+ containing every desired section in order and every effective tool declaration.
2310
+ Model-context replay sees the new baseline instead of the omitted retained
2311
+ deltas. Preparation writes this baseline even when it restates the replayed
2312
+ values, so every later preparation finds a `pi.system` entry after the marker.
2313
+ Head rebaselining takes precedence over ordinary order/value patching.
2314
+ Without a head cut, an order mismatch uses the two-entry remove/re-add sequence
2315
+ above; only when order already matches does preparation emit the minimal changed
2316
+ values, `null` removals, and tool additions/removals. A changed tool declaration
2317
+ is removed and re-added in the same message. When the offered tool order differs
2318
+ from the desired order, the message removes every offered tool and re-adds the
2319
+ desired tools in order.
2320
+
2321
+ The rendered strings stored in historical `SystemMessage.sections` remain
2322
+ authoritative even if the current renderer changes. Pi-ai decides whether to
2323
+ send the messages positionally to a capable provider or fold them into one
2324
+ leading system message; Pico does not rewrite its stored transcript for provider
2325
+ compatibility.
2326
+
2327
+ ### 7.5 Extension reload
2328
+
2329
+ Extension code is reloaded in process through the registry. The host publishes
2330
+ the new registrations and disposes the old ones in one `batch()`. The Harness
2331
+ keeps running; no close or reopen is required.
2332
+
2333
+ - New phase invocations and tool tasks use the new registrations immediately;
2334
+ running invocations see them at their next phase boundary.
2335
+ - Work already running keeps its snapshot until its phase handler settles, and a
2336
+ pinned tool keeps its implementation until its execution settles. Replacement
2337
+ never signals or interrupts it. Resources the old code uses are the
2338
+ extension's responsibility (section 7.1).
2339
+ - A task definition replaced by name hands over at its next normal phase boundary
2340
+ (section 5.4). A task definition must increase its version when the meaning
2341
+ of persisted input or checkpoint state changes and migrate supported older
2342
+ state; a failed migration blocks the task rather than terminalizing it.
2343
+ - Keyed registrations re-registered under the same key keep their position, so a
2344
+ reload does not reorder hooks, tools, or sections.
2345
+ - Document definitions are passed explicitly to typed access and need no
2346
+ registration; changed tokens take effect on their next access.
2347
+
2348
+ If old extension code ignores cancellation and never settles, new work already
2349
+ uses the replacement. Harness close still joins every invocation. Safe forced termination of arbitrary
2350
+ non-cooperative JavaScript requires worker/process isolation; that host
2351
+ terminates the process and reopens the Session from durable state. Old and new
2352
+ Harness instances must never own the same Session concurrently.
1645
2353
 
1646
2354
  ## 8. Built-in tasks
1647
2355
 
@@ -1649,10 +2357,10 @@ The initial implementation provides:
1649
2357
 
1650
2358
  | kind | responsibility |
1651
2359
  |---|---|
1652
- | generation | prepare system/loadout, request or poll model, retry, classify response |
1653
- | tool | validate, hook, execute, persist progress, append result |
1654
- | post-tools | wait for tools, apply controls, run boundary, continue generation |
1655
- | collapse | select a transcript range, summarize, append a headed summary |
2360
+ | `pi.generation` | prepare system/loadout, request or poll model, retry, classify response |
2361
+ | `pi.tool` | validate, hook, execute, persist output and details, append result |
2362
+ | `pi.post-tools` | wait for tools, apply controls, run boundary, continue generation |
2363
+ | `pi.collapse` | select a transcript range, summarize, append a headed summary |
1656
2364
 
1657
2365
  Generation uses `HarnessOptions.models` without a Pico-specific model adapter. It
1658
2366
  resolves `models.getModel(ref.provider, ref.modelId)`, builds a pi-ai `Context`
@@ -1673,12 +2381,136 @@ Bounded output records whether content was truncated and any retained file path.
1673
2381
  Compaction changes model context by appending a summary entry with a head. It
1674
2382
  does not delete transcript history.
1675
2383
 
2384
+ ### 8.1 Built-in entries
2385
+
2386
+ Built-in entry kinds carry no `data`; each is exported as an `Entry` token.
2387
+
2388
+ | kind | `model` | written by |
2389
+ |---|---|---|
2390
+ | `pi.user` | `[UserMessage]`, timestamp from the Harness clock at admission or placement | submissions |
2391
+ | `pi.assistant` | `[AssistantMessage]` with any stop reason | generation |
2392
+ | `pi.system` | `[SystemMessage]` with `content: ""` (section 7.4) | generation preparation |
2393
+ | `pi.tool-result` | `[ToolResultMessage]` | tool tasks |
2394
+
2395
+ Every provider result becomes a `pi.assistant` entry: answers, failed attempts
2396
+ with their error text and usage, and converted partials with stop reason
2397
+ `aborted`. Context derivation (section 2.1, rule 9) keeps failed and aborted
2398
+ messages out of later requests, so no separate usage or notice kind exists.
2399
+
2400
+ ### 8.2 Live document
2401
+
2402
+ ```ts
2403
+ type LiveState = {
2404
+ /** Run control (section 6); present exactly while the conversation is busy. */
2405
+ run?: { taskId: TaskId; inputs: SubmissionId[] };
2406
+ /** Presentation of the current generation attempt. */
2407
+ generation?: {
2408
+ attempt: number;
2409
+ /** Committed throttled partial of the in-flight response. */
2410
+ message?: JsonRepresentation<AssistantMessage>;
2411
+ /** Durable backoff before the next attempt. */
2412
+ retry?: { at: number; error: string };
2413
+ /** Provider-side deferred response being polled. */
2414
+ deferred?: { pollAt: number };
2415
+ };
2416
+ };
2417
+ ```
2418
+
2419
+ | field | value |
2420
+ |---|---|
2421
+ | kind | `pi.live` |
2422
+ | version | `1` |
2423
+ | scope/history/fork | conversation, `latest`, `initial` |
2424
+ | `initial()` | `{}` |
2425
+ | checkpoint | complete base whenever `generation` is absent |
2426
+ | view mount | `docs["pi.live"]` |
2427
+ | created | with every Harness conversation (section 2.2) |
2428
+
2429
+ Nothing is in flight at every turn boundary and while idle, so the stored delta
2430
+ chain spans at most one generation, including its retries and deferred polls, or
2431
+ one tool round, and each base is small. Tool progress adds its own condition with the tool task.
2432
+
2433
+ Tool progress and compaction status join this document with the tool and
2434
+ collapse tasks. Partials are normalized to strict JSON before assignment. Every
2435
+ terminal path of a run task removes `run` and `generation` in the commit that
2436
+ settles the run's inputs. `tx.settleSubmission()` stages each input's new status
2437
+ and resolves the transaction's latest candidate submission record, falling back
2438
+ to committed state, during assembly, like task-document validation (section 3.3),
2439
+ so it is not a caller table read and works after the commit's first table write.
2440
+
2441
+ ### 8.3 Generation
2442
+
2443
+ ```ts
2444
+ type GenerationInput = {};
2445
+ type GenerationCheckpoint =
2446
+ | { phase: "prepare"; attempt: number }
2447
+ | {
2448
+ phase: "request";
2449
+ attempt: number;
2450
+ model: ModelRef;
2451
+ thinkingLevel: ModelThinkingLevel;
2452
+ streamOptions: ConversationStreamOptions;
2453
+ /** Newest entry included in the request. */
2454
+ cutoff: EntryId;
2455
+ }
2456
+ | { phase: "retry"; attempt: number; until: number }
2457
+ | { phase: "poll"; attempt: number; model: ModelRef; handle: DeferredHandle; pollAt: number };
2458
+ type GenerationResult = { entryId: EntryId };
2459
+ ```
2460
+
2461
+ `pi.generation` is version 1 and starts at `{ phase: "prepare", attempt: 1 }`.
2462
+ The run's inputs live in `pi.live.run`, not in the task input.
2463
+
2464
+ - `prepare` runs section 7.4 against the committed configuration. When no model
2465
+ is configured or `models.getModel()` does not know it, the task fails with
2466
+ `no_model`. Otherwise one commit appends the planned `pi.system` entries and
2467
+ moves to `request` with the new tail as `cutoff` and the configuration's model,
2468
+ thinking level, and stream options.
2469
+ - `request` and `poll` resolve the checkpoint's model through
2470
+ `models.getModel()`; an unknown model fails the task with `no_model`, like
2471
+ `prepare`. `request` converts a leftover partial (below) before it resolves
2472
+ the model.
2473
+ - `request` first converts a committed partial left in `pi.live` by an
2474
+ interrupted attempt into an aborted `pi.assistant` entry. It then streams the
2475
+ model context through `cutoff` with the invocation signal, the thinking level
2476
+ as `reasoning` (omitted for `off`), and the pinned `streamOptions`,
2477
+ committing throttled partials. Recovery resends the same messages with the
2478
+ same pinned model, thinking level, and stream options.
2479
+ - Before classifying, the handler stops the partial throttle and awaits any
2480
+ partial commit in flight, so no stale partial lands after the outcome. The
2481
+ terminal message is classified in one commit that also clears the partial:
2482
+ - `stop`/`length`: append the answer, settle the run's inputs `done`, remove
2483
+ `run` and `generation`, and complete with `{ entryId }`. The same commit
2484
+ applies the final boundary (section 6).
2485
+ - `toolUse`: append the assistant entry and continue through the tool chain.
2486
+ - `error` that `isRetryableAssistantError()` accepts while the conversation's
2487
+ retry policy allows another attempt (`enabled` and `attempt <= maxRetries`,
2488
+ so `maxRetries` counts retries after the first attempt): append the error entry and move to
2489
+ `retry` with `until = now + retryDelayMs(policy, attempt)`.
2490
+ - any other `error`, or `aborted` without an abort mark: append the error
2491
+ entry, settle the inputs `unanswered` with `model_error`, remove `run` and
2492
+ `generation`, and fail.
2493
+ - `deferred`: move to `poll` with `pollAt = now + (handle.pollAfterMs ?? 5000)`.
2494
+ - `retry` sleeps until `until`, then returns to `prepare` with the next attempt,
2495
+ so configuration changes made during the backoff apply.
2496
+ - `poll` sleeps until `pollAt` and calls `models.fetchDeferred()`. A still
2497
+ deferred result moves `pollAt` strictly later; any other result is classified
2498
+ as above.
2499
+ - The abort handler calls `models.cancelDeferred()` in `poll` when the model is
2500
+ known (a failure is reported), converts a committed partial, settles the inputs `unanswered` with
2501
+ `aborted`, removes `run` and `generation`, and ends `aborted`.
2502
+
2503
+ Input submissions settle `unanswered` with one of these reasons: `no_model`,
2504
+ `model_error` (detail: provider error text), `aborted`, `faulted` (detail: error
2505
+ message), or an orphaning blocked reason (section 5.4). Fault and orphan
2506
+ settlement discard a committed partial without writing a transcript entry.
2507
+
1676
2508
 
1677
2509
  ## 9. Document observation and Chord
1678
2510
 
1679
- ### 9.1 Document source
2511
+ ### 9.1 Document state
1680
2512
 
1681
- Chord exposes this source-adoption contract from its replicated-state layer:
2513
+ Chord's existing replicated-state layer exposes this source-adoption contract:
1682
2514
 
1683
2515
  ```ts
1684
2516
  interface ReplicatedStateSourceFrame<T> {
@@ -1715,24 +2547,21 @@ function replicatedState<T>(
1715
2547
  options?: ReplicatedStateSourceOptions,
1716
2548
  ): AttachedReplicatedState<T>;
1717
2549
 
1718
- declare const documentSourceType: unique symbol;
1719
- interface DocumentSource<T extends JsonObject>
1720
- extends ReplicatedStateSource<Readonly<T> | null> {
1721
- readonly [documentSourceType]: T;
1722
- }
2550
+ type DocumentState<T extends JsonObject> =
2551
+ AttachedReplicatedState<Readonly<T> | null>;
1723
2552
 
1724
2553
  type WatchEnd =
1725
2554
  | { readonly reason: "stopped" | "cancelled" | "session_closed" | "retired" }
1726
2555
  | { readonly reason: "listener_error"; readonly error: Error };
1727
2556
 
1728
2557
  interface WatchHandle<T> {
1729
- /** Immutable acquisition snapshot. This reference never changes. */
2558
+ /** Acquisition revision before start; latest delivered immutable revision afterward. */
1730
2559
  readonly value: T;
1731
2560
  /** Installs the sole serialized asynchronous listener. */
1732
- start(listener: (ops: readonly Op[], context: Context) => Promise<void>): void;
1733
- /** Prevents another callback from starting and signals an in-flight callback. */
1734
- stop(): void;
1735
- /** Settles after termination and any in-flight callback. */
2561
+ start(listener: (value: T, ops: readonly Op[], context: Context) => Promise<void>): void;
2562
+ /** Idempotently stops future callbacks and returns this watch's terminal result. */
2563
+ stop(): Promise<WatchEnd>;
2564
+ /** Settles when the watch terminates; an already-running callback remains caller-owned. */
1736
2565
  readonly closed: Promise<WatchEnd>;
1737
2566
  }
1738
2567
 
@@ -1740,35 +2569,35 @@ type DocumentWatch<T extends JsonObject> = WatchHandle<Readonly<T> | null>;
1740
2569
 
1741
2570
  interface DocumentObserver {
1742
2571
  watchDoc<T extends JsonObject>(token: SessionDocToken<T>, context: Context): Promise<DocumentWatch<T> | undefined>;
1743
- watchDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: Id, context: Context): Promise<DocumentWatch<T> | undefined>;
1744
- watchDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: Id, context: Context): Promise<DocumentWatch<T> | undefined>;
2572
+ watchDoc<T extends JsonObject>(token: ConversationDocToken<T>, conversationId: ConversationId, context: Context): Promise<DocumentWatch<T> | undefined>;
2573
+ watchDoc<T extends JsonObject>(token: TaskDocToken<T>, taskId: TaskId, context: Context): Promise<DocumentWatch<T> | undefined>;
1745
2574
  watchDoc<T extends JsonObject, I extends JsonValue>(token: SessionDocFamilyToken<T, I>, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
1746
- watchDoc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: Id, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
1747
- watchDoc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: Id, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
2575
+ watchDoc<T extends JsonObject, I extends JsonValue>(token: ConversationDocFamilyToken<T, I>, conversationId: ConversationId, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
2576
+ watchDoc<T extends JsonObject, I extends JsonValue>(token: TaskDocFamilyToken<T, I>, taskId: TaskId, key: string, context: Context): Promise<DocumentWatch<T> | undefined>;
1748
2577
  }
1749
2578
  ```
1750
2579
 
1751
- `DocumentSource` is an opaque Chord-recognized `ReplicatedStateSource`. A Chord
1752
- replicated state adopts it directly and forwards its committed immutable value
1753
- and operations without another tracker or re-diff. `attach()` is one synchronous
1754
- boundary: `snapshot.value` includes every commit through `snapshot.cursor`, and
1755
- the attachment buffers only later frames. `activate()` installs the sole listener
1756
- and synchronously drains those frames in contiguous cursor order before returning.
1757
- An operation already covered by the snapshot is never redelivered. Source-backed
1758
- state is publication-only and Pico remains its sole mutator.
2580
+ `documentState()` attaches Pico's committed document stream to Chord before
2581
+ returning. The returned state is already hydrated with the exact shareable
2582
+ immutable revision, has no mutation methods, and publishes every later exact
2583
+ committed revision and operation batch without another tracker, value copy, or
2584
+ re-diff. Disposing it unregisters only that observation; Pico remains the sole
2585
+ document mutator.
1759
2586
 
1760
- Source and watch acquisition never create; absent lookup returns `undefined`.
2587
+ State and watch acquisition never create; absent lookup returns `undefined`.
1761
2588
  Successful acquisition binds one concrete incarnation. Retirement publishes a
1762
- JSON `null` replacement and ends that incarnation's stream. The service may then
1763
- withdraw itself; if it remains exposed, consumers see `null`, never stale state.
1764
- If the incarnation retires before attachment, attachment hydrates terminal
1765
- `null`; it never binds a replacement incarnation. A later recreation requires
1766
- acquiring a new source/watch.
2589
+ JSON `null` root replacement and ends that incarnation's stream. If the state
2590
+ remains exposed, consumers see `null`, never stale state. A later recreation
2591
+ requires acquiring a new state or watch.
1767
2592
 
1768
- Each adopted replicated state assigns its own in-memory contiguous delivery
1769
- sequence; Pico does not persist or expose that sequence through `WatchHandle`.
1770
- A live source or watch pins its incarnation's loaded tracker; eviction begins only
1771
- after every attachment ends. Reopen creates a new source lifetime and hydration.
2593
+ Each document state assigns its own in-memory contiguous Chord delivery sequence.
2594
+ Pico does not persist or expose that sequence through `WatchHandle`. States and watches retain immutable revisions independently of the loaded tracker
2595
+ cache. Reopen creates a new state lifetime and hydration.
2596
+
2597
+ Internally, state attachment uses Chord's synchronous atomic snapshot-and-register
2598
+ boundary: the snapshot includes every commit before attachment, and every later
2599
+ exact frame is buffered until activation. This prevents a snapshot from being
2600
+ paired with operations based on a newer unseen revision.
1772
2601
 
1773
2602
  ### 9.2 `watchDoc`
1774
2603
 
@@ -1776,83 +2605,60 @@ Tasks, hooks, and tools may observe any existing document for which their code
1776
2605
  has a token and owner/key. There is no additional subtree permission system inside trusted
1777
2606
  Session code.
1778
2607
 
1779
- `watchDoc()` is available on task, hook, and tool APIs. On the Session line,
1780
- acquisition resolves one existing concrete incarnation, captures its immutable
1781
- committed value, and registers the handle for every later committed operation
1782
- batch. It returns `undefined` when absent. `watch.value` is that fixed acquisition snapshot and
1783
- never changes.
2608
+ On the Session line, `watchDoc()` resolves one existing concrete incarnation,
2609
+ captures its current immutable tracker revision in O(1), and registers for every
2610
+ later exact committed revision and operation batch. It returns `undefined` when
2611
+ absent. Before `start()`, `watch.value` remains the acquisition revision while
2612
+ later frames buffer.
1784
2613
 
1785
2614
  ```ts
1786
2615
  const watch = await api.watchDoc(JobOutputDoc, producerTaskId, context);
1787
2616
  if (watch === undefined) return;
1788
- let value = watch.value;
1789
2617
  try {
1790
- await initializeConsumer(value, context);
1791
- watch.start(async (ops, deliveryContext) => {
1792
- value = applyImmutable(value, ops);
1793
- await consume(value, deliveryContext);
2618
+ await initializeConsumer(watch.value, context);
2619
+ watch.start(async (value, ops, deliveryContext) => {
2620
+ await consume(value, ops, deliveryContext);
1794
2621
  });
1795
2622
  } catch (error) {
1796
- watch.stop();
1797
- await watch.closed;
2623
+ await watch.stop();
1798
2624
  throw error;
1799
2625
  }
1800
2626
  ```
1801
2627
 
1802
- The caller initializes from `value` before `start()`. `start()` synchronously
1803
- installs the sole listener, changes the prepared handle to active, and schedules
1804
- delivery; it never invokes the listener inline. A second `start()`, or `start()`
1805
- after stop, throws.
1806
-
1807
- One per-watch delivery line awaits each callback before starting the next, so
1808
- callbacks never overlap. Commits never wait for callback settlement: while one
1809
- batch is in flight, later batches append to the pending queue. Empty operation
1810
- batches are discarded before enqueueing and cannot consume queue bookkeeping. An
1811
- update accepted between acquisition and return, or between return and `start()`,
1812
- is therefore not lost. The listener's promise covers all work the watch
1813
- serializes; fire-and-forget work started by the listener is outside that
1814
- guarantee.
1815
-
1816
- The pending queue is bounded only by the total number of operations in its
1817
- undelivered batches. It never estimates serialized size or calls
1818
- `JSON.stringify()` to make a compaction decision. When the operation-count limit
1819
- is exceeded, the handle leaves the in-flight batch untouched and replaces the
1820
- entire pending suffix with one newly allocated root replacement batch:
1821
-
1822
- ```ts
1823
- [["r", latestImmutablePublishedValue]]
1824
- ```
2628
+ `start()` installs the sole listener and schedules delivery; it never invokes
2629
+ user code inline. Each callback receives the exact immutable committed value and
2630
+ the exact operation batch that produced it. Immediately before invocation,
2631
+ `watch.value` advances to that value. The watch awaits the listener before
2632
+ starting its next callback, but Session commits never wait for callback
2633
+ settlement.
1825
2634
 
1826
- The reset counts as one pending operation regardless of the document's in-memory
1827
- size. Later deltas append behind it. If the operation-count limit is exceeded
1828
- again, the whole pending suffix is replaced with a newer reset rather than
1829
- accumulating an unbounded operation list. This bounds delta bookkeeping, not the
1830
- document value itself. This watch observes convergent committed state, not every
1831
- intermediate transition.
1832
-
1833
- The replacement value is the prepared immutable candidate corresponding exactly
1834
- to the last batch compacted into it. Pico adopts and publishes that candidate
1835
- after storage succeeds; it never exposes a draft or borrowed storage value.
1836
- Watches may share the immutable candidate and frozen operation payloads. A
1837
- mutable consumer must detach them before using mutable `apply()` or `track()`.
1838
-
1839
- A watch remains bound to its original incarnation. Retirement replaces the
1840
- pending suffix with `[["r", null]]`. Before start, `value` remains the original
1841
- snapshot and the terminal reset becomes the first delivered batch. While active,
1842
- the reset follows any in-flight callback. Successful terminal delivery closes as
1843
- `retired`; recreation requires another watch.
1844
-
1845
- `stop()` is idempotent, unregisters the handle, discards pending batches,
1846
- prevents another callback from starting, and signals the watch delivery context.
1847
- An in-flight callback is allowed to settle; `closed` resolves only afterward.
1848
- The acquisition `Context` governs the watch lifetime. Cancellation during
1849
- acquisition cleans up any registration before rejecting. Cancellation immediately
1850
- after successful acquisition may return an already-stopped handle,
1851
- whose `start()` throws and whose `closed` reports `cancelled`. Invocation
1852
- termination and Session close stop owned watches similarly. Listener rejection
1853
- is reported, discards pending work, and closes only that watch as
1854
- `listener_error`. The first termination reason wins, and every late rejection is
1855
- observed.
2635
+ A watch retains at most 100 pending committed frames, excluding the frame already
2636
+ being delivered. Adding frame 101 replaces the complete undelivered suffix with
2637
+ one self-contained root replacement `[["r", newestValue]]`, using the newest
2638
+ exact immutable revision and that commit's Context. Later exact frames follow
2639
+ that replacement normally. Another overflow replaces the pending suffix again.
2640
+ No serialized-byte measurement, value copy, operation replay, or re-diff occurs.
2641
+ This is convergent observation, not an audit stream; consumers requiring every
2642
+ transition must persist those facts separately.
2643
+
2644
+ `watch.value` and every previously returned revision remain stable forever under
2645
+ the trusted immutability contract. Consumers must not mutate them or retained
2646
+ descendants. The selected commit Context's values are preserved without inheriting the
2647
+ producer's cancellation. A callback owns its own asynchronous work.
2648
+
2649
+ A watch remains bound to its original incarnation. Retirement queues the exact
2650
+ terminal `[["r", null]]` frame, or folds it into an overflow replacement with
2651
+ value `null`. After that callback settles, the watch closes as `retired` and never
2652
+ follows a replacement incarnation.
2653
+
2654
+ `stop()` is idempotent. It synchronously unregisters, discards pending frames,
2655
+ prevents another callback from starting, and returns the common terminal promise.
2656
+ An already-running callback is not aborted or joined and remains caller-owned.
2657
+ The acquisition `Context` governs watch lifetime. Cancellation during acquisition
2658
+ cleans up before rejecting; later cancellation and Session close stop future
2659
+ delivery similarly. Listener failure discards pending work and closes only that
2660
+ watch as `listener_error`. The first termination reason wins, and every late
2661
+ rejection is observed.
1856
2662
 
1857
2663
  ### 9.3 Conversation view
1858
2664
 
@@ -1873,31 +2679,34 @@ through their own Chord services, not automatically mounted.
1873
2679
  The mount consumes one complete Session commit and publishes one Chord batch:
1874
2680
 
1875
2681
  ```text
1876
- document op ["s", ["message"], value]
1877
- -> view op ["s", ["docs", "pi.live", "message"], value]
2682
+ document op ["s", ["generation", "message"], value]
2683
+ -> view op ["s", ["docs", "pi.live", "generation", "message"], value]
1878
2684
  ```
1879
2685
 
1880
2686
  Entry appends/head changes and every changed mounted document are included in
1881
- the same publication. The mount owns no document revision producer and performs no semantic
1882
- projection. It materializes one immutable published view per batch with
1883
- `applyImmutable(previousView, mountedOps)` so every conversation watch can share
1884
- that value for reset compaction. A Chord adapter assigns a contiguous in-memory
1885
- delivery sequence per view source lifetime.
1886
-
1887
- `Conversation.watch()` exposes that mount through the same immutable acquisition
1888
- snapshot, serialized asynchronous listener, and reset-compacted pending queue as
1889
- `watchDoc()`. Each non-empty operation batch represents one complete Session
1890
- commit; a commit that does not change the mounted view emits no watch batch. Chord
1891
- Session facets may forward the captured value and committed operations through
1892
- services, but that product wiring is not part of the Harness facade and must not
1893
- add another tracker or semantic event envelope.
2687
+ the same publication. Before Storage admission, the Session derives the mounted
2688
+ operation batch and prepares each affected loaded mount's next immutable revision
2689
+ with the optimized immutable applier. Failure rolls back normally. After Storage
2690
+ success, finalization only installs the prepared mount pointers/cursors and
2691
+ enqueues publication. Mounted document revisions may be structurally shared
2692
+ because they obey the same trusted immutability contract. The mount performs no
2693
+ semantic projection and owns no second persistence authority. A Chord adapter
2694
+ assigns a contiguous in-memory delivery sequence per view source lifetime.
2695
+
2696
+ `Conversation.viewState()` exposes the mount directly as a disposable read-only
2697
+ Chord state for facets and UI services. `Conversation.watch()` exposes the same
2698
+ mount through Package 12's serialized exact-frame watch with bounded pending
2699
+ frames and full-value overflow replacements. An empty mounted operation batch
2700
+ creates no revision; a redundant nonempty batch remains a real publication.
2701
+ Neither API adds another tracker, persistence authority, or semantic event
2702
+ envelope.
1894
2703
 
1895
2704
  ### 9.4 Agent-mode notifications
1896
2705
 
1897
2706
  The Session kernel and Chord structural sources do not maintain a semantic event
1898
2707
  journal. Coding-agent JSON/RPC compatibility uses a thin agent-mode adapter
1899
- derived from each uncoalesced committed publication before per-watch queue
1900
- compaction. It owns no tracker or persistence and emits notifications only after
2708
+ derived from each uncoalesced committed publication before any per-watch
2709
+ overflow replacement. It owns no tracker or persistence and emits notifications only after
1901
2710
  the commit that makes them true.
1902
2711
 
1903
2712
  The adapter protocol covers run start/settlement, committed assistant progress,
@@ -1920,7 +2729,7 @@ these rules:
1920
2729
  adapter.
1921
2730
 
1922
2731
  This adapter is allowed even though a public Session-kernel semantic stream is a
1923
- non-goal. It must not derive notifications from a lossy, reset-compacted watch
2732
+ non-goal. It must not derive notifications from a lossy, overflow-reset watch
1924
2733
  when complete subscribed lifecycle delivery is promised.
1925
2734
 
1926
2735
  ## 10. Storage contract
@@ -1935,20 +2744,30 @@ type Page<T, C> = {
1935
2744
 
1936
2745
  type Cursor = Readonly<Record<string, JsonValue>>;
1937
2746
 
2747
+ type ConversationQuery = {
2748
+ readonly ownerConversationId?: ConversationId;
2749
+ readonly ownerTaskId?: TaskId;
2750
+ };
2751
+
1938
2752
  type EntryQuery = {
1939
- readonly conversationId: Id;
1940
- readonly minEntryId?: Id; // inclusive
1941
- readonly maxEntryId?: Id; // inclusive
2753
+ readonly conversationId: ConversationId;
2754
+ readonly minEntryId?: EntryId; // inclusive
2755
+ readonly maxEntryId?: EntryId; // inclusive
1942
2756
  };
1943
2757
 
1944
2758
  type TaskQuery = {
1945
- readonly conversationId?: Id;
2759
+ readonly conversationId?: ConversationId;
1946
2760
  readonly kind?: string;
1947
2761
  readonly status?: "pending" | "running" | "terminal";
1948
2762
  readonly abortRequested?: boolean;
1949
2763
  readonly background?: boolean;
1950
2764
  };
1951
2765
 
2766
+ type SubmissionQuery = {
2767
+ readonly conversationId?: ConversationId;
2768
+ readonly status?: SubmissionRecord["status"];
2769
+ };
2770
+
1952
2771
  type DocumentPoint = Seq | "current";
1953
2772
 
1954
2773
  type DocumentAddress = {
@@ -1971,6 +2790,8 @@ type StoredDocument = {
1971
2790
  readonly record: DocumentRecord;
1972
2791
  readonly version: number;
1973
2792
  readonly value: JsonObject;
2793
+ /** Deltas replayed after the selected base to materialize `value`. */
2794
+ readonly deltasSinceBase: number;
1974
2795
  };
1975
2796
 
1976
2797
  type StorageWrite =
@@ -1983,12 +2804,17 @@ type StorageWrite =
1983
2804
  readonly record: DocumentCreate;
1984
2805
  readonly content: Extract<DocumentContent, { kind: "base" }>;
1985
2806
  }
2807
+ | {
2808
+ readonly type: "document.copy";
2809
+ readonly record: DocumentCreate;
2810
+ readonly source: { readonly id: DocumentId; readonly at: DocumentPoint };
2811
+ }
1986
2812
  | {
1987
2813
  readonly type: "document.change";
1988
- readonly id: Id;
2814
+ readonly id: DocumentId;
1989
2815
  readonly content: DocumentContent;
1990
2816
  }
1991
- | { readonly type: "document.retire"; readonly id: Id };
2817
+ | { readonly type: "document.retire"; readonly id: DocumentId };
1992
2818
 
1993
2819
  /**
1994
2820
  * Trusts the owning Session to supply semantically valid records, references,
@@ -1999,29 +2825,45 @@ type StorageWrite =
1999
2825
  */
2000
2826
  interface Storage {
2001
2827
  commit(writes: readonly StorageWrite[], context: Context): Promise<Seq>;
2002
- mintId(): Promise<Id>;
2828
+ /** Allocate from the one global numeric namespace; the generic brand is compile-time only. */
2829
+ mintId<I extends Id<string>>(): Promise<I>;
2003
2830
 
2004
- conversation(id: Id, context: Context): Promise<ConversationRecord | undefined>;
2005
- scanConversations(cursor: Cursor | undefined, limit: number, context: Context): Promise<Page<ConversationRecord, Cursor>>;
2831
+ conversation(id: ConversationId, context: Context): Promise<ConversationRecord | undefined>;
2832
+ scanConversations(query: ConversationQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<ConversationRecord, Cursor>>;
2006
2833
 
2007
- entry(id: Id, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;
2008
- findLatestHeadMarker(conversationId: Id, atOrBeforeEntryId: Id | undefined, context: Context): Promise<(EntryRecord & { readonly head: Id }) | undefined>;
2009
- scanEntries(query: EntryQuery, cursor: Cursor | undefined, limit: number, context: Context): Promise<Page<EntryRecord, Cursor>>;
2834
+ entry(id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;
2835
+ entry(conversationId: ConversationId, id: EntryId, context: Context): Promise<{ readonly entry: EntryRecord; readonly commitSeq: Seq } | undefined>;
2836
+ findLatestHeadMarker(conversationId: ConversationId, atOrBeforeEntryId: EntryId | undefined, context: Context): Promise<(EntryRecord & { readonly head: EntryId }) | undefined>;
2837
+ scanEntries(query: EntryQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<EntryRecord, Cursor>>;
2010
2838
 
2011
- task(id: Id, context: Context): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
2012
- scanTasks(query: TaskQuery, cursor: Cursor | undefined, limit: number, context: Context): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;
2839
+ task(id: TaskId, context: Context): Promise<TaskRecord<JsonValue, JsonValue, JsonValue> | undefined>;
2840
+ scanTasks(query: TaskQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<TaskRecord<JsonValue, JsonValue, JsonValue>, Cursor>>;
2013
2841
 
2014
- submission(id: Id, context: Context): Promise<SubmissionRecord | undefined>;
2015
- submissionByRequest(conversationId: Id, requestId: string, context: Context): Promise<SubmissionRecord | undefined>;
2842
+ submission(id: SubmissionId, context: Context): Promise<SubmissionRecord | undefined>;
2843
+ scanSubmissions(query: SubmissionQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<SubmissionRecord, Cursor>>;
2844
+ submissionByRequest(conversationId: ConversationId, requestId: string, context: Context): Promise<SubmissionRecord | undefined>;
2016
2845
 
2017
2846
  findDocument(address: DocumentAddress, at: DocumentPoint, context: Context): Promise<DocumentRecord | undefined>;
2018
- document(id: Id, at: DocumentPoint, context: Context): Promise<StoredDocument | undefined>;
2019
- scanDocuments(query: DocumentQuery, cursor: Cursor | undefined, limit: number, context: Context): Promise<Page<DocumentRecord, Cursor>>;
2847
+ document(id: DocumentId, at: DocumentPoint, context: Context): Promise<StoredDocument | undefined>;
2848
+ scanDocuments(query: DocumentQuery, limit: number, cursor: Cursor | undefined, context: Context): Promise<Page<DocumentRecord, Cursor>>;
2020
2849
 
2021
2850
  close(context: Context): Promise<void>;
2022
2851
  }
2023
2852
  ```
2024
2853
 
2854
+ `StorageRejected` means a batch was rejected before any durable effect and is
2855
+ guaranteed not to have committed. Session rolls such a batch back normally;
2856
+ unknown failures after Storage admission remain fatal because their commit state
2857
+ is uncertain. Backends use `StorageRejected` for deterministic `document.copy`
2858
+ source, replay, and consistency failures only when rollback is guaranteed.
2859
+
2860
+ A `document.copy` reads committed pre-batch source state independent of command
2861
+ order. The source must be an alive conversation document at the selected point,
2862
+ and kind/key/history/fork must match the child create record. Storage persists
2863
+ one independent complete child base at the source's stored version. A batch may
2864
+ not create, change, or retire a selected source. Later source changes,
2865
+ reclamation, retirement, or backend reopen cannot affect the child.
2866
+
2025
2867
  Cursors are backend-owned JSON objects. Callers only round-trip them to the same
2026
2868
  scan on the same storage; cross-storage or cross-query use is unsupported. The
2027
2869
  Session owns the mutation line, so storage implementations do not add a second
@@ -2034,8 +2876,14 @@ inclusive ID range in newest-first order while applying every conversation
2034
2876
  ancestry cap. With no bounds it pages complete visible history. To read context
2035
2877
  through entry `E`, find the marker at or before `E`, then scan from
2036
2878
  `marker?.head` through `E`. For current context the upper bound is omitted.
2037
- `entry()` combines exact global lookup with the commit sequence required by
2038
- historical document reads. `limit` is always the maximum page size.
2879
+ Conversation owner filters are indexed and conjunctive. They support ownership
2880
+ traversal without an all-conversation scan; application-maintained registries
2881
+ are not a substitute for these kernel indexes.
2882
+
2883
+ `entry(id)` combines exact global lookup with the commit sequence required by
2884
+ historical document reads. `entry(conversationId, id)` returns that pair only
2885
+ when the entry is visible through the requested conversation's ancestry. `limit`
2886
+ is always the maximum page size.
2039
2887
  `findDocument()` resolves one exact logical kind/scope/key address at current or
2040
2888
  historical membership. A missing key means the singleton, not every family
2041
2889
  member. `scanDocuments()` enumerates only the incarnations alive in one exact
@@ -2047,8 +2895,8 @@ background status.
2047
2895
  `document(id, at)` materializes one specific incarnation and never follows a
2048
2896
  replacement at the same logical address. Callers resolve an address with
2049
2897
  `findDocument()` when they do not already hold an incarnation ID. It selects the
2050
- newest applicable base, applies its ordered Chord delta tail, and returns the detached materialized value plus stored
2051
- definition version. Base/delta records are backend-private. The lookup never
2898
+ newest applicable base, applies its ordered Chord delta tail, and returns the detached materialized value, stored
2899
+ definition version, and number of replayed deltas after that base. Base/delta records are backend-private. The lookup never
2052
2900
  scans unrelated documents. An unknown ID returns `undefined`. At `"current"`, a
2053
2901
  retired incarnation returns `undefined`. A numeric lookup of a rewindable
2054
2902
  conversation incarnation returns `undefined` outside its half-open lifetime and
@@ -2096,11 +2944,12 @@ benchmarks.
2096
2944
 
2097
2945
  ### 11.3 JSONL
2098
2946
 
2099
- JSONL uses reclaimable sidecars without exposing them to the harness. Persistence
2100
- alone does not provide the ownership boundary: any decoded indexes, materialized
2101
- values, or caches retained in memory must be detached from commit arguments and
2102
- must not be exposed directly by reads. A JSONL backend cannot simply add file
2103
- appends around aliasing memory tables.
2947
+ JSONL depends on the portable `FileSystem` capability, not the broader
2948
+ `ExecutionEnv`. It uses reclaimable sidecars without exposing them to the
2949
+ harness. Persistence alone does not provide the ownership boundary: any decoded
2950
+ indexes, materialized values, or caches retained in memory must be detached from
2951
+ commit arguments and must not be exposed directly by reads. A JSONL backend
2952
+ cannot simply add file appends around aliasing memory tables.
2104
2953
 
2105
2954
  ```text
2106
2955
  main.jsonl table writes, document records, and one marker per commit
@@ -2115,9 +2964,18 @@ Publication protocol:
2115
2964
  3. Publish in memory only after the marker write succeeds.
2116
2965
 
2117
2966
  Every commit uses this protocol; there is no standalone-sidecar fast path.
2118
- Without `fsync`, it guarantees ordinary process-crash consistency, not survival
2119
- of power, host, kernel, or filesystem failure. Durable mode flushes sidecars
2120
- before the marker.
2967
+ JSONL creation accepts an `fsync` option that defaults to `false`. Without
2968
+ `fsync`, it guarantees ordinary process-crash consistency, not survival of
2969
+ power, host, kernel, or filesystem failure. With `fsync: true`, the backend
2970
+ appends all affected sidecar records, flushes each affected sidecar, and only
2971
+ then appends the main marker. Ordinary publication does not explicitly flush
2972
+ `main.jsonl`; an acknowledged tail commit may therefore still disappear, but a
2973
+ marker that survives should not overtake its sidecar data. A main-only commit has
2974
+ no sidecars to flush. Before destructive reclamation with `fsync: true`, the
2975
+ backend flushes `main.jsonl` once so the authorizing marker cannot disappear
2976
+ while its replacement or removal survives. If that flush fails, the committed
2977
+ state remains published and reclamation is deferred. A non-empty temporary
2978
+ replacement is also flushed before rename.
2121
2979
 
2122
2980
  Recovery:
2123
2981
 
@@ -2129,25 +2987,32 @@ Recovery:
2129
2987
  record unnecessary.
2130
2988
  - Any uncertain append failure poisons the open backend.
2131
2989
 
2132
- Reclamation starts only after the authorizing base/retirement commits. It writes
2133
- a temporary replacement, renames it, and invalidates cached file descriptors so
2134
- future appends cannot target an unlinked inode. `main.jsonl` is not compacted in
2135
- the initial implementation.
2990
+ Reclamation starts only after the authorizing base/retirement commits. When no
2991
+ sidecar records remain, it removes the sidecar directly. Otherwise, it writes a
2992
+ temporary replacement, renames it, and invalidates cached file descriptors so
2993
+ future appends cannot target an unlinked inode. Flushing `main.jsonl` to
2994
+ authorize reclamation does not compact it. `main.jsonl` is not compacted in the
2995
+ initial implementation.
2136
2996
 
2137
2997
  ## 12. API footguns
2138
2998
 
2139
2999
  These are contracts, not invitations to add defensive machinery:
2140
3000
 
2141
- - **Detached draft work:** drafts and bound array methods are revoked after the
2142
- Session callback settles. Fire-and-forget work that runs before settlement can
2143
- still mutate the active transaction and is unsupported.
3001
+ - **Detached draft work:** draft reads, draft writes, and all `Tx` operations
3002
+ reject after the Session callback settles. Fire-and-forget work that runs
3003
+ before callback settlement can still mutate the active transaction and is
3004
+ unsupported.
2144
3005
  - **Read after write:** read every required table row before the first table
2145
3006
  write. Document drafts remain usable afterward; table reads do not.
3007
+ - **Writing to a busy conversation:** only the Harness appends to a conversation
3008
+ with an active run. Raw entries appended by `Harness.commit()` or a custom
3009
+ task while a generation prepares its request can misplace its system prompt entries;
3010
+ use a write submission.
2146
3011
  - **Long transactions:** an async commit callback holds the Session mutation
2147
3012
  line. Never await models, tools, processes, network calls, humans, a nested
2148
3013
  Session commit, or a Session waiter inside it. Use methods on the current `Tx`.
2149
3014
  - **Explicit creation:** only typed `tx.doc()` creates an absent document. Snapshot,
2150
- source, and watch lookup return `undefined` instead.
3015
+ state, and watch lookup return `undefined` instead.
2151
3016
  - **Family initialization:** the first acquisition of an absent family address
2152
3017
  selects its seed. Existing instances and later calls ignore seeds; a seed is
2153
3018
  neither identity nor an update.
@@ -2161,15 +3026,20 @@ These are contracts, not invitations to add defensive machinery:
2161
3026
  change requires explicit copy and retirement. Passing incompatible definition
2162
3027
  tokens that claim the same kind is unsupported caller misuse; Session does not
2163
3028
  maintain a document-definition registry to detect it.
2164
- - **Watch activation:** `watch.value` is the immutable acquisition snapshot.
2165
- Initialize the consumer from it before `start()`; queued operations are based
2166
- on exactly that value.
2167
- - **Coalesced watches:** slow or unstarted watches may replace an undelivered
2168
- suffix with a complete reset, omitting intermediate committed states. A facet
2169
- that must audit every transition must persist each fact as an immutable entry
2170
- or in its own journal and scan that history explicitly.
2171
- - **Watch self-join:** a listener may call `stop()`, but must not await its own
2172
- `closed` promise or a Session close that joins that listener.
3029
+ - **Trusted immutable revisions:** `snapshot()`, state values, watch values, and
3030
+ their descendants may share tracker-owned containers. Never mutate them; copy
3031
+ first when mutable ownership is required. Runtime freezing is not provided.
3032
+ - **Watch activation:** before `start()`, `watch.value` remains the immutable
3033
+ acquisition revision. Initialize the consumer from it first. After start, the
3034
+ property advances to each delivered immutable revision before its callback;
3035
+ every earlier reference remains stable.
3036
+ - **Buffered watches:** slow or unstarted watches retain up to 100 exact committed
3037
+ frames. Overflow replaces the undelivered suffix with one full-value root
3038
+ replacement, so intermediate committed states may be omitted. A consumer that
3039
+ must audit every transition must persist each fact in an immutable entry or
3040
+ journal and scan that history explicitly.
3041
+ - **Watch stop:** a listener may call and await `stop()`; it prevents future
3042
+ callbacks but neither aborts nor joins the callback already running.
2173
3043
  - **Durable progress cadence:** clients see only committed progress. A crash may
2174
3044
  lose the current uncommitted throttle window.
2175
3045
  - **Large terminal results:** terminal task records remain queryable. Put large
@@ -2177,6 +3047,20 @@ These are contracts, not invitations to add defensive machinery:
2177
3047
  outcome. Never reference a task-scoped document retired by that same outcome.
2178
3048
  - **Raw transcript:** view entries are not model context. Rendering edits,
2179
3049
  display-only entries, and model filtering require the appropriate reducer.
3050
+ - **Reserved `pi.` names:** task names, document kinds, and entry kinds starting
3051
+ with `pi.` belong to built-ins by convention. Nothing enforces it; reusing one
3052
+ collides with Harness behavior, such as `pi.system` entries being replayed as
3053
+ system messages.
3054
+ - **Early resource disposal:** disposing a `Registration` only stops new use.
3055
+ Freeing resources immediately can fail calls that are still running.
3056
+ - **Async batches:** `batch()` callbacks are synchronous. A callback that returns
3057
+ a promise publishes nothing and throws.
3058
+ - **Unstable prompt text:** a section renderer whose output changes without a
3059
+ real content change, for example by embedding the time, appends system deltas
3060
+ and defeats provider prompt caching.
3061
+ - **Durable stream options:** `streamOptions.headers` and `metadata` are stored
3062
+ in the conversation configuration history and copied into forks. Never put
3063
+ credentials there; `Models` resolves auth.
2180
3064
  - **Fatal storage errors:** after an uncertain storage failure the Session is
2181
3065
  poisoned. Do not catch the error and continue using it.
2182
3066
  - **JSONL durability:** default JSONL ordering handles ordinary process crashes;
@@ -2197,4 +3081,4 @@ Pico5 initially has no:
2197
3081
  - SQL translation of arbitrary Chord operations;
2198
3082
  - JSONL global compaction or automatic corruption repair;
2199
3083
  - compatibility layer for removed Pico prototypes;
2200
- - in-process hot replacement of Session-side extension implementations.
3084
+ - forced termination of non-cooperative extension code inside one process.