@dxos/compute 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/lib/AiMetering.mjs +1 -0
  2. package/dist/lib/Hook.mjs +1 -0
  3. package/dist/lib/Operation.mjs +3 -3
  4. package/dist/lib/Process.mjs +2 -2
  5. package/dist/lib/Trace.mjs +1 -1
  6. package/dist/lib/chunk-AgentIdentity.mjs +1 -1
  7. package/dist/lib/chunk-AgentService.mjs.map +1 -1
  8. package/dist/lib/chunk-AiMetering.mjs +77 -0
  9. package/dist/lib/chunk-AiMetering.mjs.map +1 -0
  10. package/dist/lib/chunk-Cancellation.mjs +1 -1
  11. package/dist/lib/chunk-Hook.mjs +78 -0
  12. package/dist/lib/chunk-Hook.mjs.map +1 -0
  13. package/dist/lib/chunk-Instructions.mjs +1 -1
  14. package/dist/lib/chunk-Operation.mjs +169 -5
  15. package/dist/lib/chunk-Operation.mjs.map +1 -1
  16. package/dist/lib/chunk-OperationHandlerSet.mjs +1 -1
  17. package/dist/lib/chunk-OperationRegistry.mjs +1 -1
  18. package/dist/lib/chunk-OperationRegistry.mjs.map +1 -1
  19. package/dist/lib/chunk-Process.mjs +18 -10
  20. package/dist/lib/chunk-Process.mjs.map +1 -1
  21. package/dist/lib/chunk-Project.mjs +52 -24
  22. package/dist/lib/chunk-Project.mjs.map +1 -1
  23. package/dist/lib/chunk-Reducer.mjs +827 -0
  24. package/dist/lib/chunk-Reducer.mjs.map +1 -0
  25. package/dist/lib/chunk-Routine.mjs +1 -1
  26. package/dist/lib/chunk-Runnable.mjs +1 -1
  27. package/dist/lib/chunk-ServiceResolver.mjs +1 -1
  28. package/dist/lib/chunk-Skill.mjs +10 -47
  29. package/dist/lib/chunk-Skill.mjs.map +1 -1
  30. package/dist/lib/chunk-Spec.mjs +49 -0
  31. package/dist/lib/chunk-Spec.mjs.map +1 -0
  32. package/dist/lib/chunk-SpecReview.mjs +98 -0
  33. package/dist/lib/chunk-SpecReview.mjs.map +1 -0
  34. package/dist/lib/chunk-SqlService.mjs.map +1 -1
  35. package/dist/lib/chunk-StorageService.mjs +1 -1
  36. package/dist/lib/chunk-Template.mjs +2 -2
  37. package/dist/lib/chunk-Trace.mjs +97 -13
  38. package/dist/lib/chunk-Trace.mjs.map +1 -1
  39. package/dist/lib/chunk-Trajectory.mjs +326 -0
  40. package/dist/lib/chunk-Trajectory.mjs.map +1 -0
  41. package/dist/lib/chunk-Transcript.mjs +84 -0
  42. package/dist/lib/chunk-Transcript.mjs.map +1 -0
  43. package/dist/lib/chunk-definitions.mjs +1 -1
  44. package/dist/lib/errors.mjs +3 -1
  45. package/dist/lib/errors.mjs.map +1 -1
  46. package/dist/lib/index.mjs +14 -8
  47. package/dist/lib/testing.mjs +2 -2
  48. package/dist/lib/trajectory/Reducer.mjs +1 -0
  49. package/dist/lib/trajectory/Trajectory.mjs +1 -0
  50. package/dist/lib/trajectory/Transcript.mjs +1 -0
  51. package/dist/lib/types/Project.mjs +1 -1
  52. package/dist/lib/types/Skill.mjs +1 -1
  53. package/dist/lib/types/Spec.mjs +1 -0
  54. package/dist/lib/types/SpecReview.mjs +1 -0
  55. package/dist/types/src/AgentService.d.ts +9 -0
  56. package/dist/types/src/AgentService.d.ts.map +1 -1
  57. package/dist/types/src/AiMetering.d.ts +23 -0
  58. package/dist/types/src/AiMetering.d.ts.map +1 -0
  59. package/dist/types/src/AiMetering.test.d.ts +2 -0
  60. package/dist/types/src/AiMetering.test.d.ts.map +1 -0
  61. package/dist/types/src/Hook.d.ts +84 -0
  62. package/dist/types/src/Hook.d.ts.map +1 -0
  63. package/dist/types/src/Hook.test.d.ts +2 -0
  64. package/dist/types/src/Hook.test.d.ts.map +1 -0
  65. package/dist/types/src/Operation.d.ts +276 -2
  66. package/dist/types/src/Operation.d.ts.map +1 -1
  67. package/dist/types/src/Process.d.ts +26 -4
  68. package/dist/types/src/Process.d.ts.map +1 -1
  69. package/dist/types/src/Script.test.d.ts +2 -0
  70. package/dist/types/src/Script.test.d.ts.map +1 -0
  71. package/dist/types/src/Trace.d.ts +103 -1
  72. package/dist/types/src/Trace.d.ts.map +1 -1
  73. package/dist/types/src/errors.d.ts +30 -0
  74. package/dist/types/src/errors.d.ts.map +1 -1
  75. package/dist/types/src/index.d.ts +3 -1
  76. package/dist/types/src/index.d.ts.map +1 -1
  77. package/dist/types/src/trajectory/Reducer.d.ts +191 -0
  78. package/dist/types/src/trajectory/Reducer.d.ts.map +1 -0
  79. package/dist/types/src/trajectory/Reducer.test.d.ts +2 -0
  80. package/dist/types/src/trajectory/Reducer.test.d.ts.map +1 -0
  81. package/dist/types/src/trajectory/Trajectory.d.ts +3211 -0
  82. package/dist/types/src/trajectory/Trajectory.d.ts.map +1 -0
  83. package/dist/types/src/trajectory/Trajectory.test.d.ts +2 -0
  84. package/dist/types/src/trajectory/Trajectory.test.d.ts.map +1 -0
  85. package/dist/types/src/trajectory/Transcript.d.ts +40 -0
  86. package/dist/types/src/trajectory/Transcript.d.ts.map +1 -0
  87. package/dist/types/src/trajectory/index.d.ts +4 -0
  88. package/dist/types/src/trajectory/index.d.ts.map +1 -0
  89. package/dist/types/src/trajectory/light-threads.test.d.ts +2 -0
  90. package/dist/types/src/trajectory/light-threads.test.d.ts.map +1 -0
  91. package/dist/types/src/trajectory/samples.test.d.ts +2 -0
  92. package/dist/types/src/trajectory/samples.test.d.ts.map +1 -0
  93. package/dist/types/src/types/Project.d.ts +11 -12
  94. package/dist/types/src/types/Project.d.ts.map +1 -1
  95. package/dist/types/src/types/Skill.d.ts +6 -51
  96. package/dist/types/src/types/Skill.d.ts.map +1 -1
  97. package/dist/types/src/types/Spec.d.ts +26 -0
  98. package/dist/types/src/types/Spec.d.ts.map +1 -0
  99. package/dist/types/src/types/SpecReview.d.ts +76 -0
  100. package/dist/types/src/types/SpecReview.d.ts.map +1 -0
  101. package/dist/types/src/types/index.d.ts +2 -0
  102. package/dist/types/src/types/index.d.ts.map +1 -1
  103. package/dist/types/tsconfig.tsbuildinfo +1 -1
  104. package/package.json +59 -26
  105. package/src/AgentService.ts +9 -0
  106. package/src/AiMetering.test.ts +89 -0
  107. package/src/AiMetering.ts +93 -0
  108. package/src/Hook.test.ts +75 -0
  109. package/src/Hook.ts +154 -0
  110. package/src/Operation.test.ts +23 -0
  111. package/src/Operation.ts +334 -0
  112. package/src/Process.ts +33 -6
  113. package/src/Script.test.ts +74 -0
  114. package/src/Trace.ts +97 -4
  115. package/src/errors.ts +3 -0
  116. package/src/index.ts +3 -1
  117. package/src/trajectory/Reducer.test.ts +575 -0
  118. package/src/trajectory/Reducer.ts +1026 -0
  119. package/src/trajectory/Trajectory.test.ts +114 -0
  120. package/src/trajectory/Trajectory.ts +440 -0
  121. package/src/trajectory/Transcript.ts +113 -0
  122. package/src/trajectory/index.ts +7 -0
  123. package/src/trajectory/light-threads.test.ts +310 -0
  124. package/src/trajectory/samples.test.ts +285 -0
  125. package/src/types/Project.test.ts +2 -1
  126. package/src/types/Project.ts +43 -27
  127. package/src/types/Skill.ts +6 -61
  128. package/src/types/Spec.ts +68 -0
  129. package/src/types/SpecReview.ts +98 -0
  130. package/src/types/index.ts +2 -0
  131. package/dist/lib/McpServer.mjs +0 -1
  132. package/dist/lib/chunk-McpServer.mjs +0 -124
  133. package/dist/lib/chunk-McpServer.mjs.map +0 -1
  134. package/dist/types/src/McpServer.d.ts +0 -113
  135. package/dist/types/src/McpServer.d.ts.map +0 -1
  136. package/src/McpServer.ts +0 -142
@@ -0,0 +1,575 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { describe, test } from 'vitest';
6
+
7
+ import { DXN, Feed, Obj, Ref } from '@dxos/echo';
8
+
9
+ import * as Reducer from './Reducer.ts';
10
+ import * as Trajectory from './Trajectory.ts';
11
+
12
+ const user: Trajectory.Sender = { role: 'user', name: 'alice' };
13
+ const assistant: Trajectory.Sender = { role: 'assistant' };
14
+ const system: Trajectory.Sender = { role: 'event', name: 'alarm' };
15
+ const model = DXN.make('com.anthropic.model.claude-sonnet-5.default');
16
+
17
+ const text = (value: string) => [{ _tag: 'text' as const, text: value }];
18
+
19
+ /**
20
+ * An event written in `thread` (absent: main). An opener starts a thread of its own, as `Feed.fork` makes it the base
21
+ * of a new branch; the branch takes the opener's id so a test can name the thread by its opener.
22
+ */
23
+ const event = (
24
+ payload: Trajectory.Payload,
25
+ sender: Trajectory.Sender = assistant,
26
+ thread?: string,
27
+ ): Trajectory.Event => {
28
+ if (payload._tag === 'turnBegin' || payload._tag === 'threadOpen') {
29
+ const id = Obj.ID.random();
30
+ return Trajectory.make({ id, payload, sender, thread: Trajectory.ThreadId.make(id) });
31
+ }
32
+ return Trajectory.make({
33
+ payload,
34
+ sender,
35
+ thread: thread === undefined ? undefined : Trajectory.ThreadId.make(thread),
36
+ });
37
+ };
38
+
39
+ /** The thread an opener started: its branch, which takes the opener's id here. */
40
+ const threadId = (opener: Trajectory.Event): Trajectory.ThreadId => Trajectory.ThreadId.make(opener.id);
41
+
42
+ const message = (value: string, sender: Trajectory.Sender = assistant, thread?: string) =>
43
+ event({ _tag: 'message', blocks: text(value) }, sender, thread);
44
+
45
+ const texts = (entries: readonly Reducer.PromptEntry[]) =>
46
+ entries.flatMap((entry) => entry.blocks.map((block) => (block._tag === 'text' ? block.text : block._tag)));
47
+
48
+ describe('Reducer', () => {
49
+ describe('session', () => {
50
+ test('queue holds user messages until consumed or cancelled', ({ expect }) => {
51
+ const first = message('one', user);
52
+ const second = message('two', user);
53
+ const reply = message('reply');
54
+ const { state } = Reducer.run(Reducer.session, [
55
+ first,
56
+ second,
57
+ reply,
58
+ event({ _tag: 'promptConsume', message: first.id }),
59
+ ]);
60
+ expect(state.queue).to.deep.eq([second.id]);
61
+
62
+ const cancelled = Reducer.run(Reducer.session, [event({ _tag: 'promptCancel', message: second.id })], {
63
+ state,
64
+ count: 4,
65
+ });
66
+ expect(cancelled.state.queue).to.deep.eq([]);
67
+ });
68
+
69
+ test('alarms, bindings, background tools, threads, turn and model', ({ expect }) => {
70
+ const set = event({ _tag: 'alarmSet', wakeAt: 10, message: 'ping' });
71
+ const fired = event({ _tag: 'alarmSet', wakeAt: 20 });
72
+ const feed = Ref.make(Feed.make());
73
+ const open = event({ _tag: 'threadOpen', mode: 'fresh' });
74
+ const turn = event({ _tag: 'turnBegin', model });
75
+ const { state } = Reducer.run(Reducer.session, [
76
+ set,
77
+ fired,
78
+ event({ _tag: 'alarmFire', alarm: fired.id }),
79
+ event({ _tag: 'contextBind', skills: [], objects: [feed, feed] }),
80
+ event({ _tag: 'toolBackground', toolCallId: 't1', pid: 'p1' }),
81
+ event({ _tag: 'toolBackground', toolCallId: 't2' }),
82
+ event({
83
+ _tag: 'toolDeliver',
84
+ toolCallId: 't1',
85
+ result: { _tag: 'toolResult', toolCallId: 't1', name: 'x', providerExecuted: false },
86
+ }),
87
+ open,
88
+ event({ _tag: 'threadClose', status: 'completed' }, assistant, open.id),
89
+ turn,
90
+ ]);
91
+ expect(state.alarms).to.deep.eq([{ id: set.id, wakeAt: 10, message: 'ping' }]);
92
+ expect(state.objects).to.have.length(1);
93
+ expect(state.background).to.deep.eq([{ toolCallId: 't2', pid: undefined }]);
94
+ expect(state.threads).to.deep.eq([{ id: open.id, mode: 'fresh', status: 'completed' }]);
95
+ expect(state.turns).to.deep.eq([turn.id]);
96
+ expect(state.model).to.eq(model);
97
+
98
+ const ended = Reducer.run(
99
+ Reducer.session,
100
+ [
101
+ event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, turn.id),
102
+ event({ _tag: 'contextUnbind', skills: [], objects: [feed] }),
103
+ ],
104
+ { state, count: 10 },
105
+ );
106
+ expect(ended.state.turns).to.deep.eq([]);
107
+ expect(ended.state.objects).to.have.length(0);
108
+ });
109
+
110
+ test('the first consume in feed order claims a message; later ones are rejected', ({ expect }) => {
111
+ const question = message('question', user);
112
+ const first = event({ _tag: 'turnBegin', model, from: { event: question.id } });
113
+ const second = event({ _tag: 'turnBegin', model, from: { event: question.id } });
114
+ const won = event({ _tag: 'promptConsume', message: question.id }, assistant, first.id);
115
+ const lost = event({ _tag: 'promptConsume', message: question.id }, assistant, second.id);
116
+ const events = [question, first, second, won, lost];
117
+
118
+ const session = Reducer.run(Reducer.session, events).state;
119
+ expect(session.queue).to.deep.eq([]);
120
+ expect(session.rejected).to.deep.eq([lost.id]);
121
+
122
+ const thread = Reducer.run(Reducer.thread, events).state;
123
+ expect(thread.items.map((item) => item.thread)).to.deep.eq([first.id]);
124
+
125
+ const prompt = Reducer.run(Reducer.prompt, events).state;
126
+ expect(texts(Reducer.promptFor(prompt, threadId(first)))).to.deep.eq(['question']);
127
+ expect(texts(Reducer.promptFor(prompt, threadId(second)))).to.deep.eq([]);
128
+ });
129
+ });
130
+
131
+ describe('thread', () => {
132
+ test('renders every message with its queue status', ({ expect }) => {
133
+ const first = message('one', user);
134
+ const second = message('two', user);
135
+ const { state } = Reducer.run(Reducer.thread, [
136
+ first,
137
+ second,
138
+ event({ _tag: 'promptConsume', message: first.id }),
139
+ event({ _tag: 'promptCancel', message: second.id }),
140
+ message('reply'),
141
+ event({ _tag: 'alarmSet', wakeAt: 1 }),
142
+ ]);
143
+ expect(state.items.map((item) => item.status)).to.deep.eq(['cancelled', 'consumed', 'sent']);
144
+ });
145
+
146
+ test('a consumed message moves to where the model sees it and joins the turn', ({ expect }) => {
147
+ const typed = message('typed mid-turn', user);
148
+ const turn = event({ _tag: 'turnBegin', model });
149
+ const { state } = Reducer.run(Reducer.thread, [
150
+ message('call'),
151
+ typed,
152
+ message('result'),
153
+ turn,
154
+ event({ _tag: 'promptConsume', message: typed.id }, assistant, turn.id),
155
+ ]);
156
+ expect(state.items.at(-1)?.thread).to.eq(turn.id);
157
+ expect(
158
+ state.items.map(
159
+ (item) =>
160
+ `${item.status}:${item.blocks.map((block) => (block._tag === 'text' ? block.text : block._tag)).join(' ')}`,
161
+ ),
162
+ ).to.deep.eq(['sent:call', 'sent:result', 'consumed:typed mid-turn']);
163
+ });
164
+ test('a resolution settles the request block it names, leaving the message itself as written', ({ expect }) => {
165
+ const ask = event({
166
+ _tag: 'message',
167
+ blocks: [{ _tag: 'request', requestId: 'r1', title: 'Write note.txt', options: [] }],
168
+ });
169
+ const { state } = Reducer.run(Reducer.thread, [
170
+ ask,
171
+ event({ _tag: 'requestResolve', message: ask.id, requestId: 'r1', resolution: { outcome: 'cancelled' } }),
172
+ ]);
173
+ const [block] = state.items[0].blocks;
174
+ expect(block._tag === 'request' && block.resolution).to.deep.eq({ outcome: 'cancelled' });
175
+ expect(ask.payload._tag === 'message' && ask.payload.blocks[0]).to.not.have.property('resolution');
176
+ });
177
+ });
178
+
179
+ describe('prompt', () => {
180
+ test('a user message enters the prompt where it is consumed', ({ expect }) => {
181
+ const prompt = message('question', user);
182
+ const { state } = Reducer.run(Reducer.prompt, [
183
+ message('earlier'),
184
+ prompt,
185
+ message('wake up', system),
186
+ event({ _tag: 'promptConsume', message: prompt.id }),
187
+ ]);
188
+ expect(texts(state.entries)).to.deep.eq(['earlier', 'wake up', 'question']);
189
+ expect(state.held).to.deep.eq({});
190
+ });
191
+
192
+ test('a raw merge splices the thread, a summary merge appends its summary', ({ expect }) => {
193
+ const turn = event({ _tag: 'threadOpen', mode: 'fork' });
194
+ const subagent = event({ _tag: 'threadOpen', mode: 'fresh' });
195
+ const { state } = Reducer.run(Reducer.prompt, [
196
+ turn,
197
+ subagent,
198
+ message('turn reply', assistant, turn.id),
199
+ message('subagent work', assistant, subagent.id),
200
+ message('meanwhile', system),
201
+ event({ _tag: 'threadMerge', mode: 'raw' }, assistant, turn.id),
202
+ event({ _tag: 'threadMerge', mode: 'summary', summary: text('subagent summary') }, assistant, subagent.id),
203
+ ]);
204
+ expect(texts(state.entries)).to.deep.eq(['meanwhile', 'turn reply', 'subagent summary']);
205
+ expect(state.threads).to.deep.eq({});
206
+ });
207
+
208
+ test('a turn reaches the main prompt as one block at its turnEnd', ({ expect }) => {
209
+ const question = message('question', user);
210
+ const first = event({ _tag: 'turnBegin', model, from: { event: question.id } });
211
+ const second = event({ _tag: 'turnBegin', model, from: { event: question.id } });
212
+ const steps = [
213
+ question,
214
+ first,
215
+ second,
216
+ event({ _tag: 'promptConsume', message: question.id }, assistant, first.id),
217
+ message('first: call', assistant, first.id),
218
+ message('second: call', assistant, second.id),
219
+ message('first: answer', assistant, first.id),
220
+ ];
221
+ const during = Reducer.run(Reducer.prompt, steps);
222
+ expect(texts(during.state.entries)).to.deep.eq([]);
223
+ expect(texts(Reducer.promptFor(during.state, threadId(first)))).to.deep.eq([
224
+ 'question',
225
+ 'first: call',
226
+ 'first: answer',
227
+ ]);
228
+ expect(texts(Reducer.promptFor(during.state, threadId(second)))).to.deep.eq(['second: call']);
229
+
230
+ const { state } = Reducer.run(
231
+ Reducer.prompt,
232
+ [
233
+ event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, first.id),
234
+ event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, second.id),
235
+ ],
236
+ during,
237
+ );
238
+ expect(texts(state.entries)).to.deep.eq(['question', 'first: call', 'first: answer', 'second: call']);
239
+ expect(state.threads).to.deep.eq({});
240
+ // The second turn merged after a block it never saw.
241
+ expect(Object.keys(state.stale)).to.deep.eq([second.id]);
242
+ expect(state.stale[threadId(second)]).to.include.members([question.id, steps[4].id, steps[6].id]);
243
+ });
244
+
245
+ test('a turn sees only what was in the feed at its from.event, however late the rest syncs', ({ expect }) => {
246
+ const question = message('question', user);
247
+ const consume = event({ _tag: 'promptConsume', message: question.id });
248
+ // Another writer's message, confirmed between what the turn saw and its turnBegin.
249
+ const concurrent = message('concurrent', system);
250
+ const turn = event({ _tag: 'turnBegin', model, from: { event: consume.id } });
251
+ const during = Reducer.run(Reducer.prompt, [
252
+ question,
253
+ consume,
254
+ concurrent,
255
+ turn,
256
+ message('answer', assistant, turn.id),
257
+ ]);
258
+ expect(texts(during.state.entries)).to.deep.eq(['question', 'concurrent']);
259
+ expect(texts(Reducer.promptFor(during.state, threadId(turn)))).to.deep.eq(['question', 'answer']);
260
+
261
+ const { state } = Reducer.run(
262
+ Reducer.prompt,
263
+ [event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, turn.id)],
264
+ during,
265
+ );
266
+ expect(texts(state.entries)).to.deep.eq(['question', 'concurrent', 'answer']);
267
+ expect(state.stale).to.deep.eq({ [turn.id]: [concurrent.id] });
268
+ });
269
+
270
+ test('a turn that saw everything merges clean', ({ expect }) => {
271
+ const question = message('question', user);
272
+ const consume = event({ _tag: 'promptConsume', message: question.id });
273
+ const turn = event({ _tag: 'turnBegin', model, from: { event: consume.id } });
274
+ const { state } = Reducer.run(Reducer.prompt, [
275
+ question,
276
+ consume,
277
+ turn,
278
+ message('answer', assistant, turn.id),
279
+ event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, turn.id),
280
+ ]);
281
+ expect(texts(state.entries)).to.deep.eq(['question', 'answer']);
282
+ expect(state.stale).to.deep.eq({});
283
+ });
284
+
285
+ test('a fork does not see what its parent gains after it opens', ({ expect }) => {
286
+ const before = message('before');
287
+ const fork = event({ _tag: 'threadOpen', mode: 'fork', from: { event: before.id } });
288
+ const { state } = Reducer.run(Reducer.prompt, [
289
+ before,
290
+ fork,
291
+ message('after'),
292
+ message('forked', assistant, fork.id),
293
+ ]);
294
+ expect(texts(Reducer.promptFor(state, threadId(fork)))).to.deep.eq(['before', 'forked']);
295
+ });
296
+
297
+ test('a thread merged while a turn inside it runs stays frozen until the turn ends', ({ expect }) => {
298
+ const fork = event({ _tag: 'threadOpen', mode: 'fork' });
299
+ const brief = message('brief', system, fork.id);
300
+ const turn = event(
301
+ { _tag: 'turnBegin', model, from: { thread: Trajectory.ThreadId.make(fork.id), event: brief.id } },
302
+ assistant,
303
+ fork.id,
304
+ );
305
+ const during = Reducer.run(Reducer.prompt, [
306
+ message('main'),
307
+ fork,
308
+ brief,
309
+ turn,
310
+ event({ _tag: 'threadMerge', mode: 'summary', summary: text('fork summary') }, assistant, fork.id),
311
+ ]);
312
+ expect(texts(Reducer.promptFor(during.state, threadId(turn)))).to.deep.eq(['main', 'brief']);
313
+ expect(during.state.threads[threadId(fork)]?.closed).to.eq(true);
314
+
315
+ const { state } = Reducer.run(
316
+ Reducer.prompt,
317
+ [message('work', assistant, turn.id), event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, turn.id)],
318
+ during,
319
+ );
320
+ // The turn's parent had already ended, so its block lands in main; the frozen parent goes with it.
321
+ expect(texts(state.entries)).to.deep.eq(['main', 'fork summary', 'work']);
322
+ expect(state.threads).to.deep.eq({});
323
+ });
324
+
325
+ test('a turn inside a thread merges into that thread, not main', ({ expect }) => {
326
+ const subagent = event({ _tag: 'threadOpen', mode: 'fresh' });
327
+ const brief = message('brief', system, subagent.id);
328
+ const turn = event(
329
+ { _tag: 'turnBegin', model, from: { thread: Trajectory.ThreadId.make(subagent.id), event: brief.id } },
330
+ assistant,
331
+ subagent.id,
332
+ );
333
+ const { state } = Reducer.run(Reducer.prompt, [
334
+ message('main'),
335
+ subagent,
336
+ brief,
337
+ turn,
338
+ message('work', assistant, turn.id),
339
+ event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, turn.id),
340
+ ]);
341
+ expect(texts(state.entries)).to.deep.eq(['main']);
342
+ expect(texts(Reducer.promptFor(state, threadId(subagent)))).to.deep.eq(['brief', 'work']);
343
+ });
344
+
345
+ test('rewind drops the main prompt and thread from its event on, and a fork records its origin', ({ expect }) => {
346
+ const kept = message('kept');
347
+ const dropped = message('dropped');
348
+ const origin = { feed: Ref.make(Feed.make()), event: kept.id };
349
+ const events = [
350
+ event({ _tag: 'fork', from: origin }),
351
+ kept,
352
+ dropped,
353
+ message('also dropped'),
354
+ event({ _tag: 'rewind', from: dropped.id }),
355
+ message('after'),
356
+ ];
357
+ const prompt = Reducer.run(Reducer.prompt, events).state;
358
+ expect(texts(prompt.entries)).to.deep.eq(['kept', 'after']);
359
+ expect(prompt.origin?.event).to.eq(kept.id);
360
+
361
+ const thread = Reducer.run(Reducer.thread, events).state;
362
+ expect(
363
+ thread.items
364
+ .filter((item) => item.status !== 'rewound')
365
+ .flatMap((item) => item.blocks.map((block) => (block._tag === 'text' ? block.text : ''))),
366
+ ).to.deep.eq(['kept', 'after']);
367
+ expect(thread.items.filter((item) => item.status === 'rewound')).to.have.length(2);
368
+ });
369
+
370
+ test('compact replaces its range with the summary', ({ expect }) => {
371
+ const first = message('one');
372
+ const second = message('two');
373
+ const { state } = Reducer.run(Reducer.prompt, [
374
+ first,
375
+ second,
376
+ message('three'),
377
+ event({ _tag: 'compact', from: first.id, to: second.id, summary: text('one and two') }),
378
+ ]);
379
+ expect(texts(state.entries)).to.deep.eq(['one and two', 'three']);
380
+ });
381
+
382
+ test('a compact starting at a queued message leaves the prompt unchanged', ({ expect }) => {
383
+ const queued = message('queued', user);
384
+ const reply = message('reply');
385
+ const { state } = Reducer.run(Reducer.prompt, [
386
+ message('earlier'),
387
+ queued,
388
+ reply,
389
+ event({ _tag: 'compact', from: queued.id, to: reply.id, summary: text('summary') }),
390
+ ]);
391
+ expect(texts(state.entries)).to.deep.eq(['earlier', 'reply']);
392
+ });
393
+
394
+ test('a compact starting inside an earlier summary starts at that summary', ({ expect }) => {
395
+ const first = message('one');
396
+ const second = message('two');
397
+ const third = message('three');
398
+ const { state } = Reducer.run(Reducer.prompt, [
399
+ message('zero'),
400
+ first,
401
+ second,
402
+ third,
403
+ message('four'),
404
+ event({ _tag: 'compact', from: first.id, to: second.id, summary: text('one and two') }),
405
+ event({ _tag: 'compact', from: second.id, to: third.id, summary: text('one to three') }),
406
+ ]);
407
+ expect(texts(state.entries)).to.deep.eq(['zero', 'one to three', 'four']);
408
+ });
409
+
410
+ test('a compact naming an event outside the prompt leaves it unchanged', ({ expect }) => {
411
+ const alarm = event({ _tag: 'alarmSet', wakeAt: 1 });
412
+ const later = message('later');
413
+ const { state } = Reducer.run(Reducer.prompt, [
414
+ message('earlier'),
415
+ alarm,
416
+ later,
417
+ event({ _tag: 'compact', from: alarm.id, to: later.id, summary: text('summary') }),
418
+ ]);
419
+ expect(texts(state.entries)).to.deep.eq(['earlier', 'later']);
420
+ });
421
+
422
+ test('a reversed compact range leaves the prompt unchanged', ({ expect }) => {
423
+ const first = message('one');
424
+ const second = message('two');
425
+ const third = message('three');
426
+ const { state } = Reducer.run(Reducer.prompt, [
427
+ first,
428
+ second,
429
+ third,
430
+ event({ _tag: 'compact', from: third.id, to: first.id, summary: text('reversed') }),
431
+ ]);
432
+ expect(texts(state.entries)).to.deep.eq(['one', 'two', 'three']);
433
+ });
434
+ });
435
+
436
+ describe('properties', () => {
437
+ // Deterministic PRNG so a failing sequence reproduces.
438
+ const random = (seed: number) => () => {
439
+ seed = (seed * 1_103_515_245 + 12_345) % 2 ** 31;
440
+ return seed / 2 ** 31;
441
+ };
442
+
443
+ const sequence = (seed: number, length: number): Trajectory.Event[] => {
444
+ const next = random(seed);
445
+ const pick = <T>(items: readonly T[]): T | undefined => items[Math.floor(next() * items.length)];
446
+ const events: Trajectory.Event[] = [];
447
+ const users: Trajectory.EventId[] = [];
448
+ const threads: Trajectory.EventId[] = [];
449
+ const turns: Trajectory.EventId[] = [];
450
+ for (let index = 0; index < length; index++) {
451
+ const roll = next();
452
+ const thread = next() < 0.3 ? pick(threads) : undefined;
453
+ const queued = pick(users);
454
+ const merged = pick(threads);
455
+ const ending = pick(turns);
456
+ const compactFrom = pick(events.slice(0, 2));
457
+ const compactTo = pick(events);
458
+ let created: Trajectory.Event;
459
+ if (roll < 0.25) {
460
+ created = message(`user ${index}`, user, thread);
461
+ users.push(created.id);
462
+ } else if (roll < 0.45) {
463
+ created = message(`assistant ${index}`, assistant, thread);
464
+ } else if (roll < 0.55) {
465
+ created = message(`event ${index}`, system);
466
+ } else if (roll < 0.65 && queued) {
467
+ created = event({ _tag: 'promptConsume', message: queued }, assistant, thread);
468
+ } else if (roll < 0.7 && queued) {
469
+ created = event({ _tag: 'promptCancel', message: queued }, user);
470
+ } else if (roll < 0.8) {
471
+ created = event({ _tag: 'threadOpen', mode: next() < 0.5 ? 'fork' : 'fresh' });
472
+ threads.push(created.id);
473
+ } else if (roll < 0.9 && merged) {
474
+ const mode = next() < 0.5 ? 'raw' : 'summary';
475
+ created = event({ _tag: 'threadMerge', mode, summary: text(`summary ${index}`) }, assistant, merged);
476
+ } else if (roll < 0.95 && compactFrom && compactTo) {
477
+ created = event({
478
+ _tag: 'compact',
479
+ from: compactFrom.id,
480
+ to: compactTo.id,
481
+ summary: text(`compact ${index}`),
482
+ });
483
+ } else if (roll < 0.97) {
484
+ const head = events.at(-1);
485
+ created = event(
486
+ {
487
+ _tag: 'turnBegin',
488
+ model,
489
+ from: head
490
+ ? { ...(thread !== undefined ? { thread: Trajectory.ThreadId.make(thread) } : {}), event: head.id }
491
+ : undefined,
492
+ },
493
+ assistant,
494
+ thread,
495
+ );
496
+ threads.push(created.id);
497
+ turns.push(created.id);
498
+ } else if (ending) {
499
+ created = event({ _tag: 'turnEnd', finishReason: 'stop' }, assistant, ending);
500
+ } else {
501
+ created = event({ _tag: 'alarmSet', wakeAt: index });
502
+ }
503
+
504
+ events.push(created);
505
+ }
506
+
507
+ return events;
508
+ };
509
+
510
+ test('the prompt only grows, except at compact', ({ expect }) => {
511
+ for (let seed = 1; seed <= 50; seed++) {
512
+ let state = Reducer.prompt.initial;
513
+ for (const next of sequence(seed, 60)) {
514
+ const after = Reducer.prompt.step(state, next);
515
+ if (next.payload._tag !== 'compact' && next.payload._tag !== 'rewind') {
516
+ expect(after.entries.slice(0, state.entries.length), `seed ${seed}`).to.deep.eq(state.entries);
517
+ }
518
+ state = after;
519
+ }
520
+ }
521
+ });
522
+
523
+ test('an open turn or fork sends a prompt that only grows, whatever other writers append', ({ expect }) => {
524
+ for (let seed = 1; seed <= 50; seed++) {
525
+ let state = Reducer.prompt.initial;
526
+ for (const next of sequence(seed, 60)) {
527
+ const after = Reducer.prompt.step(state, next);
528
+ if (next.payload._tag !== 'compact') {
529
+ for (const id of Object.keys(state.threads).map((key) => Trajectory.ThreadId.make(key))) {
530
+ if (after.threads[id]) {
531
+ const sent = Reducer.promptFor(state, id);
532
+ expect(Reducer.promptFor(after, id).slice(0, sent.length), `seed ${seed}`).to.deep.eq(sent);
533
+ }
534
+ }
535
+ }
536
+ state = after;
537
+ }
538
+ }
539
+ });
540
+
541
+ test('folding a batch matches stepping each event, and leaves the state it started from as it was', ({
542
+ expect,
543
+ }) => {
544
+ const check = <S>(reducer: Reducer.Reducer<S>, events: readonly Trajectory.Event[], seed: number) => {
545
+ const stepped = events.reduce(reducer.step, reducer.initial);
546
+ const middle = Reducer.run(reducer, events.slice(0, 30));
547
+ expect(Reducer.run(reducer, events.slice(30), middle).state, `seed ${seed}`).to.deep.eq(stepped);
548
+ expect(Reducer.run(reducer, events.slice(30), middle).state, `seed ${seed}`).to.deep.eq(stepped);
549
+ expect(middle.state, `seed ${seed}`).to.deep.eq(Reducer.run(reducer, events.slice(0, 30)).state);
550
+ };
551
+
552
+ for (let seed = 1; seed <= 20; seed++) {
553
+ const events = sequence(seed, 60);
554
+ check(Reducer.session, events, seed);
555
+ check(Reducer.thread, events, seed);
556
+ check(Reducer.prompt, events, seed);
557
+ }
558
+ });
559
+
560
+ test('resuming from a checkpoint matches a full replay', ({ expect }) => {
561
+ const check = <S>(reducer: Reducer.Reducer<S>, events: readonly Trajectory.Event[], seed: number) => {
562
+ const full = Reducer.run(reducer, events);
563
+ const resumed = Reducer.run(reducer, events.slice(25), Reducer.run(reducer, events.slice(0, 25)));
564
+ expect(resumed, `seed ${seed}`).to.deep.eq(full);
565
+ };
566
+
567
+ for (let seed = 1; seed <= 20; seed++) {
568
+ const events = sequence(seed, 60);
569
+ check(Reducer.session, events, seed);
570
+ check(Reducer.thread, events, seed);
571
+ check(Reducer.prompt, events, seed);
572
+ }
573
+ });
574
+ });
575
+ });