@code-yeongyu/senpi-agent-core 2026.11.3-2 → 2026.11.4-2

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 (118) hide show
  1. package/dist/agent-loop.js +7 -47
  2. package/dist/conformance/index.d.ts +37 -0
  3. package/dist/conformance/index.js +25 -0
  4. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  5. package/dist/conformance/loop-core-manifest.js +1 -0
  6. package/dist/conformance/registry.js +31 -1
  7. package/dist/execution/canonical-json.d.ts +3 -0
  8. package/dist/execution/canonical-json.js +12 -0
  9. package/dist/execution/coordinator-codec.d.ts +5 -0
  10. package/dist/execution/coordinator-codec.js +104 -0
  11. package/dist/execution/coordinator-consent.d.ts +29 -0
  12. package/dist/execution/coordinator-consent.js +63 -0
  13. package/dist/execution/coordinator-plan.d.ts +33 -0
  14. package/dist/execution/coordinator-plan.js +106 -0
  15. package/dist/execution/coordinator-sequential.d.ts +15 -0
  16. package/dist/execution/coordinator-sequential.js +34 -0
  17. package/dist/execution/coordinator-types.d.ts +161 -0
  18. package/dist/execution/coordinator-types.js +2 -0
  19. package/dist/execution/coordinator.d.ts +27 -0
  20. package/dist/execution/coordinator.js +164 -0
  21. package/dist/execution/device-files-node.d.ts +8 -0
  22. package/dist/execution/device-files-node.js +112 -0
  23. package/dist/execution/device-files.d.ts +80 -0
  24. package/dist/execution/device-files.js +87 -0
  25. package/dist/execution/grant-verify.d.ts +70 -0
  26. package/dist/execution/grant-verify.js +87 -0
  27. package/dist/execution/ledger.d.ts +2 -0
  28. package/dist/execution/ledger.js +1 -0
  29. package/dist/execution/nested-codec.d.ts +5 -0
  30. package/dist/execution/nested-codec.js +41 -0
  31. package/dist/execution/nested-types.d.ts +92 -0
  32. package/dist/execution/nested-types.js +3 -0
  33. package/dist/execution/nested.d.ts +48 -0
  34. package/dist/execution/nested.js +206 -0
  35. package/dist/execution/plane-model.d.ts +33 -0
  36. package/dist/execution/plane-model.js +80 -0
  37. package/dist/execution/plane.d.ts +72 -0
  38. package/dist/execution/plane.js +172 -0
  39. package/dist/execution/remote-device-files.d.ts +12 -0
  40. package/dist/execution/remote-device-files.js +84 -0
  41. package/dist/execution/remote-executor.d.ts +74 -0
  42. package/dist/execution/remote-executor.js +193 -0
  43. package/dist/execution/remote-file-call.d.ts +14 -0
  44. package/dist/execution/remote-file-call.js +30 -0
  45. package/dist/execution/remote-hand-ledger.d.ts +40 -0
  46. package/dist/execution/remote-hand-ledger.js +137 -0
  47. package/dist/execution/remote-link.d.ts +36 -0
  48. package/dist/execution/remote-link.js +117 -0
  49. package/dist/execution/remote-protocol.d.ts +104 -0
  50. package/dist/execution/remote-protocol.js +104 -0
  51. package/dist/execution/remote-tool-host.d.ts +37 -0
  52. package/dist/execution/remote-tool-host.js +114 -0
  53. package/dist/execution/scope-lifecycle.d.ts +81 -0
  54. package/dist/execution/scope-lifecycle.js +173 -0
  55. package/dist/execution/testing/batch-cases.d.ts +6 -0
  56. package/dist/execution/testing/batch-cases.js +210 -0
  57. package/dist/execution/testing/batch-executor.d.ts +34 -0
  58. package/dist/execution/testing/batch-executor.js +170 -0
  59. package/dist/execution/testing/batch-harness.d.ts +58 -0
  60. package/dist/execution/testing/batch-harness.js +286 -0
  61. package/dist/execution/testing/batch-registry.d.ts +3 -0
  62. package/dist/execution/testing/batch-registry.js +30 -0
  63. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  64. package/dist/execution/testing/cancel-cases.js +64 -0
  65. package/dist/execution/testing/consent-cases.d.ts +14 -0
  66. package/dist/execution/testing/consent-cases.js +66 -0
  67. package/dist/execution/testing/fault-hand-cases.d.ts +6 -0
  68. package/dist/execution/testing/fault-hand-cases.js +70 -0
  69. package/dist/execution/testing/hand-harness.d.ts +48 -0
  70. package/dist/execution/testing/hand-harness.js +136 -0
  71. package/dist/execution/testing/kill-batch.d.ts +12 -0
  72. package/dist/execution/testing/kill-batch.js +70 -0
  73. package/dist/execution/testing/kill-hand.d.ts +16 -0
  74. package/dist/execution/testing/kill-hand.js +75 -0
  75. package/dist/execution/testing/kill-nest.d.ts +6 -0
  76. package/dist/execution/testing/kill-nest.js +55 -0
  77. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  78. package/dist/execution/testing/kill-wakex.js +81 -0
  79. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  80. package/dist/execution/testing/lifecycle-cases.js +60 -0
  81. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  82. package/dist/execution/testing/lifecycle-registry.js +19 -0
  83. package/dist/execution/testing/multi-hand-cases.d.ts +6 -0
  84. package/dist/execution/testing/multi-hand-cases.js +44 -0
  85. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  86. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  87. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  88. package/dist/execution/testing/multi-seq-cases.js +46 -0
  89. package/dist/execution/testing/nest-cases.d.ts +39 -0
  90. package/dist/execution/testing/nest-cases.js +181 -0
  91. package/dist/execution/testing/nest-registry.d.ts +3 -0
  92. package/dist/execution/testing/nest-registry.js +27 -0
  93. package/dist/execution/testing/scope-cases.d.ts +6 -0
  94. package/dist/execution/testing/scope-cases.js +49 -0
  95. package/dist/execution/testing/seq-cases.d.ts +6 -0
  96. package/dist/execution/testing/seq-cases.js +71 -0
  97. package/dist/execution/testing/seq-registry.d.ts +3 -0
  98. package/dist/execution/testing/seq-registry.js +32 -0
  99. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  100. package/dist/execution/testing/wake-exec-cases.js +147 -0
  101. package/dist/execution/testing/wake-registry.d.ts +3 -0
  102. package/dist/execution/testing/wake-registry.js +26 -0
  103. package/dist/execution/tool-host.d.ts +10 -2
  104. package/dist/execution/tool-outcome-events.d.ts +11 -0
  105. package/dist/execution/tool-outcome-events.js +47 -0
  106. package/dist/execution/wake-inbox.d.ts +25 -0
  107. package/dist/execution/wake-inbox.js +85 -0
  108. package/dist/execution/wake-outbox.d.ts +30 -0
  109. package/dist/execution/wake-outbox.js +87 -0
  110. package/dist/execution/wake-types.d.ts +45 -0
  111. package/dist/execution/wake-types.js +3 -0
  112. package/dist/harness/env/nodejs.js +4 -0
  113. package/dist/index.d.ts +21 -1
  114. package/dist/index.js +19 -1
  115. package/dist/node.d.ts +1 -0
  116. package/dist/node.js +1 -0
  117. package/dist/transport/testing/multi-cases.js +8 -8
  118. package/package.json +3 -3
@@ -0,0 +1,286 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { createBatchCoordinator } from "../coordinator.js";
3
+ import { createNestedAdmission } from "../nested.js";
4
+ import { createScopeLifecycle } from "../scope-lifecycle.js";
5
+ import { createWakeInbox } from "../wake-inbox.js";
6
+ import { createWakeOutbox } from "../wake-outbox.js";
7
+ const ADMITTED_AT = 100;
8
+ const NOW = ADMITTED_AT + 1;
9
+ export class BrainKilledError extends Error {
10
+ constructor(label) {
11
+ super(`brain killed around ${label}`);
12
+ this.name = "BrainKilledError";
13
+ }
14
+ }
15
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
16
+ function labelOf(writes) {
17
+ for (const write of writes) {
18
+ if (write.op !== "append" || !write.kind.startsWith("execution."))
19
+ continue;
20
+ const data = write.data;
21
+ if (!isObject(data))
22
+ return undefined;
23
+ return typeof data.executionId === "string" ? `${String(data.step)}:${data.executionId}` : String(data.step);
24
+ }
25
+ return undefined;
26
+ }
27
+ function withCommit(store, commit) {
28
+ return {
29
+ readEpoch: () => store.readEpoch(),
30
+ readHead: () => store.readHead(),
31
+ claim: (expected, next) => store.claim(expected, next),
32
+ commit,
33
+ mintId: () => store.mintId(),
34
+ scanRecords: (query) => store.scanRecords(query),
35
+ getDocument: (key) => store.getDocument(key),
36
+ scanDocuments: (prefix) => store.scanDocuments(prefix),
37
+ exportSnapshot: () => store.exportSnapshot(),
38
+ importSnapshot: (epoch, snapshot) => store.importSnapshot(epoch, snapshot),
39
+ };
40
+ }
41
+ /**
42
+ * The brain's store: `onDurable` sees the label of every durable write; with `kill`, the brain dies before that write
43
+ * (nothing of it durable) or after it is durable, and never writes again.
44
+ */
45
+ function brainStore(store, onDurable, kill) {
46
+ let dead = false;
47
+ return withCommit(store, async (epoch, writes, adopt) => {
48
+ const label = labelOf(writes) ?? "";
49
+ if (dead)
50
+ throw new BrainKilledError(label);
51
+ const hit = kill !== undefined && label === kill.label;
52
+ if (hit && kill.at === "before") {
53
+ dead = true;
54
+ throw new BrainKilledError(label);
55
+ }
56
+ const result = await store.commit(epoch, writes, adopt);
57
+ onDurable(label);
58
+ if (hit) {
59
+ dead = true;
60
+ throw new BrainKilledError(label);
61
+ }
62
+ return result;
63
+ });
64
+ }
65
+ function deadAfter(store, killed) {
66
+ return withCommit(store, (epoch, writes, adopt) => {
67
+ if (killed.aborted)
68
+ return Promise.reject(new Error("a killed executor cannot write"));
69
+ return store.commit(epoch, writes, adopt);
70
+ });
71
+ }
72
+ export function batchPlan(batchId, calls) {
73
+ return {
74
+ batchId,
75
+ scope: "scope",
76
+ workspace: "workspace",
77
+ generation: 1,
78
+ admittedAt: ADMITTED_AT,
79
+ leaseUntil: ADMITTED_AT + 60_000,
80
+ calls: calls.map(([executionId, executor, name = "read", sequential]) => ({
81
+ executionId,
82
+ executor,
83
+ name,
84
+ args: { executionId },
85
+ sequential: sequential === "sequential",
86
+ })),
87
+ };
88
+ }
89
+ export const resultOf = (executionId, name = "read") => ({
90
+ kind: "result",
91
+ value: { executionId, name },
92
+ });
93
+ /** Two executors (`e1`, `e2`) and one brain, each on its own durable medium, with pausable steps and kill controls. */
94
+ export async function batchHarness(adapters) {
95
+ const trace = [];
96
+ const gates = new Map();
97
+ const gate = (key) => {
98
+ let found = gates.get(key);
99
+ if (found === undefined) {
100
+ found = { reached: Promise.withResolvers() };
101
+ gates.set(key, found);
102
+ }
103
+ return found;
104
+ };
105
+ const pause = async (executionId, point) => {
106
+ const found = gate(`${executionId}/${point}`);
107
+ found.reached.resolve();
108
+ if (found.open !== undefined)
109
+ await found.open.promise;
110
+ };
111
+ const claimed = async () => {
112
+ const medium = await adapters.store.createMedium();
113
+ await (await adapters.store.open(medium)).claim(0, 1);
114
+ return medium;
115
+ };
116
+ let clock = NOW;
117
+ const executors = new Map();
118
+ const start = async (id, medium) => {
119
+ const killed = new AbortController();
120
+ const store = deadAfter(await adapters.store.open(medium), killed.signal);
121
+ const endpoint = await adapters.executor.open({
122
+ id,
123
+ store,
124
+ epoch: 1,
125
+ now: () => clock,
126
+ trace,
127
+ pause,
128
+ killed: killed.signal,
129
+ });
130
+ executors.set(id, { medium, killed, endpoint });
131
+ };
132
+ const current = (id) => {
133
+ const found = executors.get(id);
134
+ if (found === undefined)
135
+ throw new Error(`no executor ${id}`);
136
+ return found.endpoint;
137
+ };
138
+ const proxy = (id) => ({
139
+ prepare: (request) => current(id).prepare(request),
140
+ release: (ref) => current(id).release(ref),
141
+ abort: (ref) => current(id).abort(ref),
142
+ consent: (ref, frozenDigest) => {
143
+ const endpoint = current(id);
144
+ if (endpoint.consent === undefined)
145
+ throw new Error(`executor ${id} takes no consent`);
146
+ return endpoint.consent(ref, frozenDigest);
147
+ },
148
+ });
149
+ const kill = (id) => {
150
+ const found = executors.get(id);
151
+ if (found === undefined)
152
+ throw new Error(`no executor ${id}`);
153
+ found.killed.abort();
154
+ return found.medium;
155
+ };
156
+ for (const id of ["e1", "e2"])
157
+ await start(id, await claimed());
158
+ const brainMedium = await claimed();
159
+ const wakeMedia = new Map();
160
+ let scopeMedium;
161
+ const brainWrites = [];
162
+ const writeWaiters = new Map();
163
+ const onDurable = (label) => {
164
+ brainWrites.push(label);
165
+ writeWaiters.get(label)?.resolve([...brainWrites]);
166
+ };
167
+ return {
168
+ trace,
169
+ count: (event) => trace.filter((entry) => entry === event).length,
170
+ /** Resolves with every durable brain write so far, at the moment the brain's `label` write becomes durable. */
171
+ written: (label) => {
172
+ const waiter = Promise.withResolvers();
173
+ writeWaiters.set(label, waiter);
174
+ return waiter.promise;
175
+ },
176
+ /** Hold `executionId` at `point`: `reached` resolves when the step gets there, `open()` lets it continue. */
177
+ hold: (executionId, point) => {
178
+ const found = gate(`${executionId}/${point}`);
179
+ const open = Promise.withResolvers();
180
+ found.open = open;
181
+ return { reached: found.reached.promise, open: () => open.resolve() };
182
+ },
183
+ /**
184
+ * A fresh brain process over the brain's durable medium, optionally dying around one of its writes. Two issuers
185
+ * on one harness are two sessions' brains sharing the executors.
186
+ */
187
+ brain: async (dieAt, issuer = "brain", consent) => {
188
+ const opened = await adapters.store.open(brainMedium);
189
+ return createBatchCoordinator({
190
+ ...(consent === undefined ? {} : { consent }),
191
+ issuer,
192
+ store: brainStore(opened, onDurable, dieAt),
193
+ epoch: 1,
194
+ admission: createAdmissionLine(),
195
+ executor: proxy,
196
+ });
197
+ },
198
+ /** The brain's nested admission over the same durable medium, optionally dying around one of its writes. */
199
+ nested: async (dieAt, issuer = "brain") => {
200
+ const opened = await adapters.store.open(brainMedium);
201
+ return createNestedAdmission({
202
+ issuer,
203
+ store: brainStore(opened, onDurable, dieAt),
204
+ epoch: 1,
205
+ admission: createAdmissionLine(),
206
+ clock: () => clock,
207
+ });
208
+ },
209
+ /** A hand's durable wake outbox on its own medium (one per hand), optionally dying around one of its writes. */
210
+ wakeOutbox: async (hand, dieAt) => {
211
+ let medium = wakeMedia.get(hand);
212
+ if (medium === undefined) {
213
+ medium = await claimed();
214
+ wakeMedia.set(hand, medium);
215
+ }
216
+ return createWakeOutbox({
217
+ hand,
218
+ store: brainStore(await adapters.store.open(medium), () => { }, dieAt),
219
+ epoch: 1,
220
+ admission: createAdmissionLine(),
221
+ clock: () => clock,
222
+ });
223
+ },
224
+ /** The endpoint's scope lifecycle on its own medium, optionally dying around one of its writes. */
225
+ scopes: async (idleTtlMs, dieAt) => {
226
+ if (scopeMedium === undefined)
227
+ scopeMedium = await claimed();
228
+ return createScopeLifecycle({
229
+ store: brainStore(await adapters.store.open(scopeMedium), () => { }, dieAt),
230
+ epoch: 1,
231
+ admission: createAdmissionLine(),
232
+ clock: () => clock,
233
+ idleTtlMs,
234
+ });
235
+ },
236
+ /** The `wake_expired` records a hand's outbox logged, in log order. */
237
+ wakeLog: async (hand) => {
238
+ const medium = wakeMedia.get(hand);
239
+ if (medium === undefined)
240
+ return [];
241
+ const store = await adapters.store.open(medium);
242
+ return (await store.scanRecords({ kind: "execution.wake-expired" })).map((record) => record.data);
243
+ },
244
+ /** The brain's wake inbox over its medium; `owner` binds each scope to its authenticated hand. */
245
+ wakeInbox: async (owner, dieAt) => createWakeInbox({
246
+ issuer: "brain",
247
+ store: brainStore(await adapters.store.open(brainMedium), onDurable, dieAt),
248
+ epoch: 1,
249
+ admission: createAdmissionLine(),
250
+ clock: () => clock,
251
+ owner,
252
+ }),
253
+ /** Moves every executor's clock: a lease that ends before the new time is expired on the next ledger event. */
254
+ advance: (ms) => {
255
+ clock += ms;
256
+ },
257
+ /** The executor proxy for `id`, as the brain reaches it (a late approval goes through it). */
258
+ executor: proxy,
259
+ /** Kill the executor process and start a new one on the same durable medium. */
260
+ restartExecutor: async (id) => start(id, kill(id)),
261
+ /** Kill the executor and start it on a new, empty medium: every execution it held is lost. */
262
+ loseExecutor: async (id) => {
263
+ kill(id);
264
+ await start(id, await claimed());
265
+ },
266
+ ledgerState: async (id, executionId) => {
267
+ const store = await adapters.store.open(executors.get(id)?.medium ?? "");
268
+ const row = await store.getDocument(`execution.ledger:${JSON.stringify(["brain", executionId])}`);
269
+ if (!isObject(row) || !isObject(row.progress))
270
+ return undefined;
271
+ return String(row.progress.state);
272
+ },
273
+ };
274
+ }
275
+ export async function expectRejects(operation, type, what) {
276
+ try {
277
+ await operation;
278
+ }
279
+ catch (error) {
280
+ if (error instanceof type)
281
+ return;
282
+ throw new Error(`${what}: expected ${type.name}, got ${String(error)}`);
283
+ }
284
+ throw new Error(`${what}: expected ${type.name}, but it resolved`);
285
+ }
286
+ //# sourceMappingURL=batch-harness.js.map
@@ -0,0 +1,3 @@
1
+ import type { RegisteredCase } from "../../conformance/registry.ts";
2
+ export declare const BATCH_REGISTRY: readonly RegisteredCase[];
3
+ //# sourceMappingURL=batch-registry.d.ts.map
@@ -0,0 +1,30 @@
1
+ import { KILL_BATCH_DECLARATIONS } from "./kill-batch.js";
2
+ const BATCH_CASES_IMPL = "packages/agent/src/execution/testing/batch-cases.ts";
3
+ const INTRO = "#5416";
4
+ const batchCase = (id, expected) => ({
5
+ id,
6
+ impl: BATCH_CASES_IMPL,
7
+ intro: INTRO,
8
+ adapters: ["store", "executor"],
9
+ expected,
10
+ });
11
+ export const BATCH_REGISTRY = [
12
+ batchCase("BATCH-01", "the brain crashes after the manifest: the same execution ids are re-prepared; nothing had run"),
13
+ batchCase("BATCH-02", "the brain crashes after the prepares: prepare is re-sent, stored replies return, hooks never rerun"),
14
+ batchCase("BATCH-03", "the brain crashes inside a released wave: released calls get a re-sent release, unmarked ready calls are released, the next wave waits"),
15
+ batchCase("BATCH-05", "an executor restart keeps prepared and released calls, and release proceeds"),
16
+ batchCase("BATCH-06", "a lost prepared execution answers unknown_execution and is uncertain; siblings settle"),
17
+ batchCase("BATCH-07", "prepare runs in source order across executors; each release waits for its dependencies' final outcomes"),
18
+ batchCase("BATCH-08", "a batch_abort reply ABORTs the batch: no later prepare, no body, abort re-sent on recovery"),
19
+ batchCase("BATCH-09", "a blocked call is a per-call result; the other calls are released"),
20
+ batchCase("REPLAY-01", "an executor restart during preparation replays like today (X12): placeholder result, never rerun, a reissued call runs once"),
21
+ batchCase("REPLAY-02", "the same beside a prepared sibling: the sibling is aborted unrun, both replay with the placeholder"),
22
+ ...KILL_BATCH_DECLARATIONS.map(({ id, scenario, kill }) => ({
23
+ id,
24
+ impl: "packages/agent/src/execution/testing/kill-batch.ts",
25
+ intro: INTRO,
26
+ adapters: ["store", "executor"],
27
+ expected: `everywhere: kill the brain ${kill.at} its ${kill.label} write (${scenario}); recovery reaches the uncrashed outcomes with stable ids, each step run once`,
28
+ })),
29
+ ];
30
+ //# sourceMappingURL=batch-registry.js.map
@@ -0,0 +1,8 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { NestedCancelTarget } from "../nested-types.ts";
3
+ import type { BatchCaseAdapters } from "./batch-executor.ts";
4
+ type CancelCase = CaseImplementation<BatchCaseAdapters>;
5
+ export declare const cancelTargetOf: (childRequestId: string, executor: string) => NestedCancelTarget;
6
+ export declare const CANCEL_CASES: ReadonlyMap<string, CancelCase>;
7
+ export {};
8
+ //# sourceMappingURL=cancel-cases.d.ts.map
@@ -0,0 +1,64 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { nestedChildId } from "../nested.js";
3
+ import { admitted, nestParent, nestRequest, openedParent, refusedWith } from "./nest-cases.js";
4
+ export const cancelTargetOf = (childRequestId, executor) => ({
5
+ ref: { issuer: "brain", executionId: nestedChildId("p", childRequestId), generation: 1 },
6
+ executor,
7
+ });
8
+ /** CANCEL-01: the parent cancel commits before the child's admission: the child is refused, its activity too. */
9
+ const cancelFirst = async (adapters) => {
10
+ const { nested } = await openedParent(adapters);
11
+ await nested.release("p");
12
+ await nested.registerActivity({
13
+ activityId: "a1",
14
+ parent: "p",
15
+ executor: "e1",
16
+ scope: "scope",
17
+ targets: ["model"],
18
+ budget: 2,
19
+ expiresAt: nestParent.leaseUntil,
20
+ });
21
+ expectEqual(await nested.cancel("p"), [], "no child to cascade to");
22
+ expectEqual(await nested.admit(nestRequest()), refusedWith("parent_terminal"), "a child racing the cancel");
23
+ expectEqual(await nested.admit(nestRequest({ activityId: "a1" })), refusedWith("activity_ended"), "the cancel binding ended the activity");
24
+ expectEqual(await nested.registerActivity({
25
+ activityId: "a2",
26
+ parent: "p",
27
+ executor: "e1",
28
+ scope: "scope",
29
+ targets: ["model"],
30
+ budget: 1,
31
+ expiresAt: nestParent.leaseUntil,
32
+ }), refusedWith("parent_terminal"), "no new activity after the cancel");
33
+ };
34
+ /**
35
+ * CANCEL-02: the child's admission commits before the parent cancel: the child exists and the cancel durably cascades
36
+ * to its executor, delivered once it is taken and re-sent by a restarted brain until then.
37
+ */
38
+ const admittedFirst = async (adapters) => {
39
+ const { h, nested } = await openedParent(adapters);
40
+ await nested.release("p");
41
+ expectEqual(await nested.admit(nestRequest({ target: "e2" })), admitted("c1", "e2", false), "admitted before the cancel");
42
+ expectEqual(await nested.cancel("p"), [cancelTargetOf("c1", "e2")], "the cancel names the child");
43
+ expectEqual((await nested.read("p"))?.cancels, { [nestedChildId("p", "c1")]: "queued" }, "the cascade is durable before delivery");
44
+ const refused = [];
45
+ await nested
46
+ .deliverCancels("p", async (target) => {
47
+ refused.push(target);
48
+ throw new Error("the child's executor is unreachable");
49
+ })
50
+ .catch(() => undefined);
51
+ const restarted = await h.nested();
52
+ const sent = [];
53
+ expectEqual(await restarted.deliverCancels("p", async (target) => {
54
+ sent.push(target);
55
+ }), 1, "a restarted brain re-sends it");
56
+ expectEqual([refused, sent], [[cancelTargetOf("c1", "e2")], [cancelTargetOf("c1", "e2")]], "both sends");
57
+ expectEqual(await restarted.deliverCancels("p", async () => { }), 0, "delivered once taken");
58
+ expectEqual(await restarted.admit(nestRequest({ target: "e2" })), admitted("c1", "e2", true), "the admitted child still exists");
59
+ };
60
+ export const CANCEL_CASES = new Map([
61
+ ["CANCEL-01", cancelFirst],
62
+ ["CANCEL-02", admittedFirst],
63
+ ]);
64
+ //# sourceMappingURL=cancel-cases.js.map
@@ -0,0 +1,14 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { BatchConsent, ConsentAnswer, ConsentRequest } from "../coordinator-types.ts";
3
+ import type { BatchCaseAdapters } from "./batch-executor.ts";
4
+ type ConsentCase = CaseImplementation<BatchCaseAdapters>;
5
+ /** An approver that hands each request to the case and answers when the case says so. */
6
+ export declare function scriptedConsent(needsConsent?: (name: string) => boolean): {
7
+ port: BatchConsent;
8
+ requests: ConsentRequest[];
9
+ asked: Promise<void>;
10
+ answer: (given: ConsentAnswer) => void;
11
+ };
12
+ export declare const CONSENT_CASES: ReadonlyMap<string, ConsentCase>;
13
+ export {};
14
+ //# sourceMappingURL=consent-cases.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { batchHarness, batchPlan } from "./batch-harness.js";
3
+ /** A lease that has ended: the harness admits every call with a 60 s lease. */
4
+ const PAST_LEASE_MS = 120_000;
5
+ /** An approver that hands each request to the case and answers when the case says so. */
6
+ export function scriptedConsent(needsConsent = () => false) {
7
+ const requests = [];
8
+ const waiting = [];
9
+ const asked = Promise.withResolvers();
10
+ const port = {
11
+ needsConsent: ({ name }) => needsConsent(name),
12
+ approve: (request) => {
13
+ requests.push(request);
14
+ const answered = Promise.withResolvers();
15
+ waiting.push({ request, answer: answered.resolve });
16
+ asked.resolve();
17
+ return answered.promise;
18
+ },
19
+ };
20
+ return {
21
+ port,
22
+ requests,
23
+ asked: asked.promise,
24
+ answer: (given) => {
25
+ const next = waiting.shift();
26
+ if (next === undefined)
27
+ throw new Error("no consent request is waiting");
28
+ next.answer(given);
29
+ },
30
+ };
31
+ }
32
+ /** S10's rule: a call settled during preparation ABORTs the rest as an interrupted preparation (replayed as today). */
33
+ const notRun = { kind: "not_run", cause: "interrupted_preparation" };
34
+ async function expiredWhileAwaiting(h, answer, lateApproval) {
35
+ const plan = batchPlan(lateApproval ? "consent-02" : "consent-01", [
36
+ ["a", "e1"],
37
+ ["g", "e1", "gated"],
38
+ ["c", "e2"],
39
+ ]);
40
+ const approver = scriptedConsent();
41
+ const run = (await h.brain(undefined, "brain", approver.port)).run(plan);
42
+ await approver.asked;
43
+ h.advance(PAST_LEASE_MS);
44
+ approver.answer(answer);
45
+ const result = await run;
46
+ const expired = { kind: "interrupted", reason: "lease_expired", uncertain: true };
47
+ expectEqual(result, { decision: "ABORT", outcomes: [notRun, expired, notRun] }, "lease_expired, the rest ABORTed");
48
+ expectEqual(approver.requests.map(({ executionId, gate }) => [executionId, gate]), [["g", "frozen"]], "one approval request, bound to the frozen call");
49
+ expectEqual(h.count("body:a") + h.count("body:g") + h.count("body:c"), 0, "no body ran");
50
+ expectEqual(h.count("shim:g"), 1, "no automatic successor: g was never prepared again");
51
+ const frozenDigest = approver.requests[0]?.digest ?? "";
52
+ const late = await h.executor("e1").consent?.({ issuer: "brain", executionId: "g", generation: 1 }, frozenDigest);
53
+ expectEqual(late?.kind === "settled" ? late.outcome.reason : late?.kind, "lease_expired", "a later approval is rejected with the endpoint's own lease_expired outcome");
54
+ expectEqual(await h.ledgerState("e1", "g"), "settled", "the endpoint is terminal");
55
+ expectEqual(await (await h.brain(undefined, "brain", approver.port)).run(plan), result, "recovery decides the same");
56
+ expectEqual(approver.requests.length, 1, "recovery asks nobody again");
57
+ }
58
+ /** CONSENT-01 (S12, cross-machine): the lease expires while g awaits Gate B consent. */
59
+ const expiryWhileAwaiting = async (adapters) => expiredWhileAwaiting(await batchHarness(adapters), "expired", false);
60
+ /** CONSENT-02 (S12, cross-machine): the approval for g arrives after its lease expired, and is rejected. */
61
+ const lateApproval = async (adapters) => expiredWhileAwaiting(await batchHarness(adapters), "approved", true);
62
+ export const CONSENT_CASES = new Map([
63
+ ["CONSENT-01", expiryWhileAwaiting],
64
+ ["CONSENT-02", lateApproval],
65
+ ]);
66
+ //# sourceMappingURL=consent-cases.js.map
@@ -0,0 +1,6 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import { type HandCaseAdapters } from "./hand-harness.ts";
3
+ type HandCase = CaseImplementation<HandCaseAdapters>;
4
+ export declare const FAULT_HAND_CASES: ReadonlyMap<string, HandCase>;
5
+ export {};
6
+ //# sourceMappingURL=fault-hand-cases.d.ts.map
@@ -0,0 +1,70 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { createCarrierFault, FAULT_PROFILE_NAMES, } from "../../transport/testing/fault-transport.js";
3
+ import { call, openHandRig } from "./hand-harness.js";
4
+ const SCOPES = ["a", "b"];
5
+ const CALLS = 12;
6
+ /** The sends span 360 ms, past the flap profile's second drop (260 ms), so every profile acts while calls are live. */
7
+ const PACE_MS = 30;
8
+ const ids = (scope) => Array.from({ length: CALLS }, (_, index) => `${scope}${index + 1}`);
9
+ const texts = (messages) => messages.map((message) => message.content.map((part) => (part.type === "text" ? part.text : "")).join(""));
10
+ const acted = {
11
+ slow: (stats) => stats.refused > 0,
12
+ lossy: (stats) => stats.lost > 0,
13
+ laggy: (stats) => stats.reordered > 0,
14
+ flap: (stats) => stats.drops >= 2,
15
+ "drop-reattach": (stats) => stats.drops >= 2,
16
+ };
17
+ /**
18
+ * Calls of two scopes sent one by one across the faulted link: every call settles with exactly the result an unfaulted
19
+ * run gives, each body runs once, and each scope's calls start in their lane order.
20
+ */
21
+ const underProfile = (name) => async (adapters) => {
22
+ const stats = { refused: 0, lost: 0, reordered: 0, drops: 0 };
23
+ const rig = await openHandRig(adapters, { placement: "cross-machine", fault: createCarrierFault(name, stats) });
24
+ const what = `FAULT-HAND ${name}`;
25
+ const batches = [];
26
+ for (let index = 0; index < CALLS; index++) {
27
+ for (const scope of SCOPES)
28
+ batches.push(rig.execute(scope, [call(ids(scope)[index] ?? "")], "sequential"));
29
+ await rig.advance(PACE_MS);
30
+ }
31
+ const results = await rig.settle(Promise.all(batches), `${what}: every call settled`);
32
+ expectEqual(results.flatMap(({ messages }) => texts(messages)).sort(), SCOPES.flatMap((scope) => ids(scope).map((id) => `ran:${id}`)).sort(), `${what}: results equal the unfaulted run`);
33
+ for (const scope of SCOPES)
34
+ expectEqual(rig.bodies.filter((body) => body.startsWith(`${scope}:`)), ids(scope).map((id) => `${scope}:${id}`), `${what}: scope ${scope} ran each call once, in lane order`);
35
+ expectEqual(rig.faults, [], `${what}: the hand reported no fault`);
36
+ if (!acted[name](stats))
37
+ throw new Error(`${what}: the profile never acted (${JSON.stringify(stats)})`);
38
+ };
39
+ /**
40
+ * The hand becomes unreachable for far longer than the transport's resume window while several sessions' calls run on
41
+ * it: every dependent call pauses (no outcome is invented and nothing reruns), and after the hand is reachable again each
42
+ * scope's call settles exactly once with its own result.
43
+ */
44
+ const unreachableThenBack = async (adapters) => {
45
+ const rig = await openHandRig(adapters, { placement: "cross-machine" });
46
+ rig.gateBodies();
47
+ const settledScopes = new Set();
48
+ const batches = SCOPES.map((scope) => {
49
+ const batch = rig.execute(scope, [call(`${scope}1`)]);
50
+ void batch.then(() => settledScopes.add(scope));
51
+ return batch;
52
+ });
53
+ await rig.runUntil(() => rig.bodies.length === SCOPES.length, "FAULT-HAND-MULTI-01: every scope's call is running");
54
+ rig.disconnect();
55
+ for (const scope of SCOPES)
56
+ rig.release(`${scope}1`);
57
+ await rig.advance(60_000);
58
+ expectEqual([...settledScopes], [], "FAULT-HAND-MULTI-01: dependent calls pause while the hand is unreachable");
59
+ rig.reconnect();
60
+ const results = await rig.settle(Promise.all(batches), "FAULT-HAND-MULTI-01: every scope resumed after reconnect");
61
+ expectEqual(results.map(({ messages }) => texts(messages)), SCOPES.map((scope) => [`ran:${scope}1`]), "FAULT-HAND-MULTI-01: each scope settled with its own result");
62
+ await rig.advance(5_000);
63
+ expectEqual(rig.bodies, SCOPES.map((scope) => `${scope}:${scope}1`), "FAULT-HAND-MULTI-01: resumed once: no body ran twice");
64
+ expectEqual(rig.faults, [], "FAULT-HAND-MULTI-01: the hand reported no fault");
65
+ };
66
+ export const FAULT_HAND_CASES = new Map([
67
+ ...FAULT_PROFILE_NAMES.map((name, index) => [`FAULT-HAND-0${index + 1}`, underProfile(name)]),
68
+ ["FAULT-HAND-MULTI-01", unreachableThenBack],
69
+ ]);
70
+ //# sourceMappingURL=fault-hand-cases.js.map
@@ -0,0 +1,48 @@
1
+ import type { AgentToolCall, ToolExecutionMode } from "../../types.ts";
2
+ import { type ManualTimers } from "../../durable/testing/manual-timers.ts";
3
+ import type { StoreCaseAdapters } from "../../durable/testing/store-harness.ts";
4
+ import type { CarrierFault, TransportCaseAdapters } from "../../transport/testing/transport-harness.ts";
5
+ import type { ExecutionEntry } from "../ledger-types.ts";
6
+ import { type HandPlacement } from "../remote-tool-host.ts";
7
+ import type { ToolHostResult } from "../tool-host.ts";
8
+ /** What the KILL-HAND, MULTI-HAND and FAULT-HAND cases need from a host: a durable store and a transport. */
9
+ export type HandCaseAdapters = StoreCaseAdapters & TransportCaseAdapters;
10
+ /** Kill the hand at the `commit`-th ledger commit (0-based), before it or once it is durable. */
11
+ export interface KillPoint {
12
+ readonly commit: number;
13
+ readonly at: "before" | "durable";
14
+ }
15
+ export interface HandRig {
16
+ /** Every tool body start, as `<scope>:<toolCallId>`, across all hand processes. */
17
+ readonly bodies: readonly string[];
18
+ /** Faults the hand processes reported (a killed hand reports the kill). */
19
+ readonly faults: readonly unknown[];
20
+ readonly killed: Promise<void>;
21
+ execute(scope: string, calls: readonly AgentToolCall[], mode?: ToolExecutionMode): Promise<ToolHostResult>;
22
+ /** A new hand process on the reopened store and the same link; resolves once it announced itself. */
23
+ restart(): Promise<void>;
24
+ /** Hold every body until `release(toolCallId)`. */
25
+ gateBodies(): void;
26
+ release(toolCallId: string): void;
27
+ /**
28
+ * Lets `ms` of transport time pass in small steps, running the work each due timer starts before the next step, so a
29
+ * check made afterwards sees everything that time could have produced. Cases wait only through this, `settle` and
30
+ * `runUntil`: a bare timer advance fires timers without letting the hand's settle chain run, and an assertion that
31
+ * nothing happened would then pass whether or not the case's precondition held.
32
+ */
33
+ advance(ms: number): Promise<void>;
34
+ /** Advances transport time until `promise` settles; fails past the budget. */
35
+ settle<T>(promise: Promise<T>, what: string, budgetMs?: number): Promise<T>;
36
+ runUntil(done: () => boolean, what: string, budgetMs?: number): Promise<void>;
37
+ /** Drops the carrier between session and hand (the hand becomes unreachable) and attaches it again. */
38
+ disconnect(): void;
39
+ reconnect(): void;
40
+ rows(): Promise<ExecutionEntry[]>;
41
+ }
42
+ export declare function call(id: string): AgentToolCall;
43
+ export declare function openHandRig(adapters: HandCaseAdapters, options: {
44
+ readonly placement: HandPlacement;
45
+ readonly killAt?: KillPoint;
46
+ readonly fault?: (timers: ManualTimers) => CarrierFault;
47
+ }): Promise<HandRig>;
48
+ //# sourceMappingURL=hand-harness.d.ts.map