@code-yeongyu/senpi-agent-core 2026.11.3-3 → 2026.11.5-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 (167) hide show
  1. package/dist/agent-loop.js +20 -186
  2. package/dist/agent.d.ts +4 -0
  3. package/dist/agent.js +4 -0
  4. package/dist/conformance/index.d.ts +30 -0
  5. package/dist/conformance/index.js +21 -0
  6. package/dist/conformance/loop-core-manifest.d.ts +1 -1
  7. package/dist/conformance/loop-core-manifest.js +18 -0
  8. package/dist/conformance/registry.js +20 -18
  9. package/dist/egress/types.d.ts +102 -0
  10. package/dist/egress/types.js +7 -0
  11. package/dist/execution/canonical-digest.d.ts +10 -0
  12. package/dist/execution/canonical-digest.js +20 -0
  13. package/dist/execution/canonical-json.d.ts +3 -0
  14. package/dist/execution/canonical-json.js +12 -0
  15. package/dist/execution/chain-count.d.ts +26 -0
  16. package/dist/execution/chain-count.js +45 -0
  17. package/dist/execution/coordinator-codec.js +13 -2
  18. package/dist/execution/coordinator-consent.d.ts +29 -0
  19. package/dist/execution/coordinator-consent.js +63 -0
  20. package/dist/execution/coordinator-plan.d.ts +1 -2
  21. package/dist/execution/coordinator-plan.js +4 -17
  22. package/dist/execution/coordinator-sequential.d.ts +15 -0
  23. package/dist/execution/coordinator-sequential.js +34 -0
  24. package/dist/execution/coordinator-types.d.ts +45 -0
  25. package/dist/execution/coordinator.d.ts +3 -1
  26. package/dist/execution/coordinator.js +35 -3
  27. package/dist/execution/device-files-node.d.ts +8 -0
  28. package/dist/execution/device-files-node.js +150 -0
  29. package/dist/execution/device-files.d.ts +109 -0
  30. package/dist/execution/device-files.js +124 -0
  31. package/dist/execution/ledger-types.d.ts +3 -1
  32. package/dist/execution/ledger.d.ts +9 -3
  33. package/dist/execution/ledger.js +8 -2
  34. package/dist/execution/loop-hook-host-hand.d.ts +33 -0
  35. package/dist/execution/loop-hook-host-hand.js +71 -0
  36. package/dist/execution/loop-hook-host-protocol.d.ts +46 -0
  37. package/dist/execution/loop-hook-host-protocol.js +47 -0
  38. package/dist/execution/loop-hook-host.d.ts +40 -0
  39. package/dist/execution/loop-hook-host.js +87 -0
  40. package/dist/execution/nested-codec.d.ts +5 -0
  41. package/dist/execution/nested-codec.js +41 -0
  42. package/dist/execution/nested-types.d.ts +92 -0
  43. package/dist/execution/nested-types.js +3 -0
  44. package/dist/execution/nested.d.ts +48 -0
  45. package/dist/execution/nested.js +206 -0
  46. package/dist/execution/plane-model.d.ts +33 -0
  47. package/dist/execution/plane-model.js +80 -0
  48. package/dist/execution/plane-session.d.ts +56 -0
  49. package/dist/execution/plane-session.js +178 -0
  50. package/dist/execution/plane.d.ts +75 -0
  51. package/dist/execution/plane.js +172 -0
  52. package/dist/execution/prepared/executor-body.d.ts +22 -0
  53. package/dist/execution/prepared/executor-body.js +73 -0
  54. package/dist/execution/prepared/executor-freeze.d.ts +17 -0
  55. package/dist/execution/prepared/executor-freeze.js +42 -0
  56. package/dist/execution/prepared/executor-pipeline.d.ts +11 -0
  57. package/dist/execution/prepared/executor-pipeline.js +26 -0
  58. package/dist/execution/prepared/executor-types.d.ts +131 -0
  59. package/dist/execution/prepared/executor-types.js +2 -0
  60. package/dist/execution/prepared/executor.d.ts +8 -0
  61. package/dist/execution/prepared/executor.js +261 -0
  62. package/dist/execution/prepared/memory-batch-store.d.ts +4 -0
  63. package/dist/execution/prepared/memory-batch-store.js +4 -0
  64. package/dist/execution/prepared/pipeline-prepared-batch.d.ts +27 -0
  65. package/dist/execution/prepared/pipeline-prepared-batch.js +175 -0
  66. package/dist/execution/prepared/pipeline-prepared.d.ts +10 -0
  67. package/dist/execution/prepared/pipeline-prepared.js +54 -0
  68. package/dist/execution/remote-device-files.d.ts +12 -0
  69. package/dist/execution/remote-device-files.js +113 -0
  70. package/dist/execution/remote-epoch-gate.d.ts +19 -0
  71. package/dist/execution/remote-epoch-gate.js +46 -0
  72. package/dist/execution/remote-epoch.d.ts +53 -0
  73. package/dist/execution/remote-epoch.js +74 -0
  74. package/dist/execution/remote-executor.d.ts +17 -0
  75. package/dist/execution/remote-executor.js +70 -18
  76. package/dist/execution/remote-file-call.d.ts +14 -0
  77. package/dist/execution/remote-file-call.js +31 -0
  78. package/dist/execution/remote-hand-ledger.d.ts +11 -3
  79. package/dist/execution/remote-hand-ledger.js +31 -15
  80. package/dist/execution/remote-link.d.ts +41 -0
  81. package/dist/execution/remote-link.js +153 -0
  82. package/dist/execution/remote-protocol.d.ts +50 -4
  83. package/dist/execution/remote-protocol.js +48 -2
  84. package/dist/execution/remote-tool-host.d.ts +23 -3
  85. package/dist/execution/remote-tool-host.js +25 -64
  86. package/dist/execution/scope-lifecycle.d.ts +81 -0
  87. package/dist/execution/scope-lifecycle.js +173 -0
  88. package/dist/execution/testing/batch-executor.js +32 -3
  89. package/dist/execution/testing/batch-harness.d.ts +25 -3
  90. package/dist/execution/testing/batch-harness.js +83 -5
  91. package/dist/execution/testing/cancel-cases.d.ts +8 -0
  92. package/dist/execution/testing/cancel-cases.js +64 -0
  93. package/dist/execution/testing/consent-cases.d.ts +14 -0
  94. package/dist/execution/testing/consent-cases.js +66 -0
  95. package/dist/execution/testing/epoch-cases.d.ts +8 -0
  96. package/dist/execution/testing/epoch-cases.js +84 -0
  97. package/dist/execution/testing/epoch-harness.d.ts +47 -0
  98. package/dist/execution/testing/epoch-harness.js +172 -0
  99. package/dist/execution/testing/epoch-registry.d.ts +3 -0
  100. package/dist/execution/testing/epoch-registry.js +17 -0
  101. package/dist/execution/testing/hand-harness.d.ts +3 -0
  102. package/dist/execution/testing/hand-harness.js +27 -22
  103. package/dist/execution/testing/hand-registry.d.ts +3 -0
  104. package/dist/execution/testing/hand-registry.js +20 -0
  105. package/dist/execution/testing/kill-epoch.d.ts +9 -0
  106. package/dist/execution/testing/kill-epoch.js +71 -0
  107. package/dist/execution/testing/kill-hook.d.ts +14 -0
  108. package/dist/execution/testing/kill-hook.js +117 -0
  109. package/dist/execution/testing/kill-nest.d.ts +6 -0
  110. package/dist/execution/testing/kill-nest.js +55 -0
  111. package/dist/execution/testing/kill-wakex.d.ts +6 -0
  112. package/dist/execution/testing/kill-wakex.js +81 -0
  113. package/dist/execution/testing/lifecycle-cases.d.ts +9 -0
  114. package/dist/execution/testing/lifecycle-cases.js +60 -0
  115. package/dist/execution/testing/lifecycle-registry.d.ts +3 -0
  116. package/dist/execution/testing/lifecycle-registry.js +19 -0
  117. package/dist/execution/testing/multi-epoch-cases.d.ts +4 -0
  118. package/dist/execution/testing/multi-epoch-cases.js +29 -0
  119. package/dist/execution/testing/multi-lifecycle-cases.d.ts +4 -0
  120. package/dist/execution/testing/multi-lifecycle-cases.js +34 -0
  121. package/dist/execution/testing/multi-seq-cases.d.ts +4 -0
  122. package/dist/execution/testing/multi-seq-cases.js +46 -0
  123. package/dist/execution/testing/nest-cases.d.ts +39 -0
  124. package/dist/execution/testing/nest-cases.js +181 -0
  125. package/dist/execution/testing/nest-registry.d.ts +3 -0
  126. package/dist/execution/testing/nest-registry.js +27 -0
  127. package/dist/execution/testing/scope-cases.d.ts +6 -0
  128. package/dist/execution/testing/scope-cases.js +49 -0
  129. package/dist/execution/testing/seq-cases.d.ts +6 -0
  130. package/dist/execution/testing/seq-cases.js +71 -0
  131. package/dist/execution/testing/seq-registry.d.ts +3 -0
  132. package/dist/execution/testing/seq-registry.js +32 -0
  133. package/dist/execution/testing/wake-exec-cases.d.ts +20 -0
  134. package/dist/execution/testing/wake-exec-cases.js +147 -0
  135. package/dist/execution/testing/wake-registry.d.ts +3 -0
  136. package/dist/execution/testing/wake-registry.js +26 -0
  137. package/dist/execution/tool-host.d.ts +23 -3
  138. package/dist/execution/tool-host.js +18 -1
  139. package/dist/execution/tool-outcome-events.d.ts +11 -0
  140. package/dist/execution/tool-outcome-events.js +47 -0
  141. package/dist/execution/wake-inbox.d.ts +25 -0
  142. package/dist/execution/wake-inbox.js +85 -0
  143. package/dist/execution/wake-outbox.d.ts +30 -0
  144. package/dist/execution/wake-outbox.js +87 -0
  145. package/dist/execution/wake-types.d.ts +45 -0
  146. package/dist/execution/wake-types.js +3 -0
  147. package/dist/harness/agent-harness.d.ts +6 -0
  148. package/dist/harness/execution/tool-host-call.d.ts +13 -0
  149. package/dist/harness/execution/tool-host-call.js +55 -0
  150. package/dist/harness/execution/tools.d.ts +2 -1
  151. package/dist/harness/execution/tools.js +32 -17
  152. package/dist/harness/runtime/drive/tools.js +1 -1
  153. package/dist/harness/runtime/harness.js +1 -0
  154. package/dist/harness/runtime/types.d.ts +1 -0
  155. package/dist/index.d.ts +27 -2
  156. package/dist/index.js +24 -1
  157. package/dist/node.d.ts +1 -0
  158. package/dist/node.js +1 -0
  159. package/dist/public-entry.d.ts +10 -0
  160. package/dist/public-entry.js +23 -0
  161. package/dist/step-commit.d.ts +24 -0
  162. package/dist/step-commit.js +24 -0
  163. package/dist/tool-name-alias.d.ts +1 -7
  164. package/dist/tool-name-alias.js +0 -17
  165. package/dist/transport/testing/multi-cases.js +8 -8
  166. package/dist/types.d.ts +37 -1
  167. package/package.json +3 -3
@@ -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,8 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import type { ToolHostResult } from "../tool-host.ts";
3
+ import { type HandCaseAdapters } from "./hand-harness.ts";
4
+ type EpochCase = CaseImplementation<HandCaseAdapters>;
5
+ export declare const texts: ({ messages }: ToolHostResult) => string[];
6
+ export declare const EPOCH_CASES: ReadonlyMap<string, EpochCase>;
7
+ export {};
8
+ //# sourceMappingURL=epoch-cases.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { expectEqual } from "../../durable/testing/store-harness.js";
2
+ import { floorCommit, openEpochRig, stepCommit } from "./epoch-harness.js";
3
+ import { call } from "./hand-harness.js";
4
+ export const texts = ({ messages }) => messages.map((message) => message.content.map((part) => (part.type === "text" ? part.text : "")).join(""));
5
+ const OLD = { name: "brain-old", epoch: 1 };
6
+ const NEW = { name: "brain-new", epoch: 2 };
7
+ /** SC-MOVE step 1: while the hand's floor ACK is held, the new owner's call has no effect, then runs once. */
8
+ const floorAckBarrier = async (adapters) => {
9
+ const rig = await openEpochRig(adapters, { brains: [OLD, NEW] });
10
+ rig.setOwner("s", OLD.name);
11
+ const before = await rig.settle(rig.execute(OLD.name, "s", [call("c0")]), "EPOCH-01: the first owner's call");
12
+ expectEqual(texts(before), ["ran:c0"], "EPOCH-01: the first owner runs on its floor");
13
+ rig.setOwner("s", NEW.name);
14
+ const barrier = rig.hold(floorCommit("s", NEW.epoch));
15
+ const moved = rig.execute(NEW.name, "s", [call("c1")]);
16
+ await rig.settle(barrier.reached, "EPOCH-01: the new owner's floor reached the hand's store");
17
+ await rig.advance(2_000);
18
+ expectEqual(rig.bodies, ["s:c0"], "EPOCH-01: nothing of the new owner's call ran while its floor ACK was held");
19
+ expectEqual((await rig.rows()).length, 1, "EPOCH-01: the new owner's call was not even recorded");
20
+ barrier.release();
21
+ expectEqual(texts(await rig.settle(moved, "EPOCH-01: the new owner's call")), ["ran:c1"], "EPOCH-01: result");
22
+ expectEqual(rig.bodies, ["s:c0", "s:c1"], "EPOCH-01: the new owner's call ran exactly once after the ACK");
23
+ };
24
+ /** SC-MOVE step 2: two brains claim the session at once; exactly one wins, and only the winner's calls run. */
25
+ const concurrentClaims = async (adapters) => {
26
+ const first = { name: "brain-first", epoch: 1 };
27
+ const rivals = [
28
+ { name: "brain-a", epoch: 2 },
29
+ { name: "brain-b", epoch: 2 },
30
+ ];
31
+ const rig = await openEpochRig(adapters, { brains: [first, ...rivals] });
32
+ rig.setOwner("s", first.name);
33
+ await rig.settle(rig.execute(first.name, "s", [call("c0")]), "EPOCH-02: the first owner's call");
34
+ const session = await adapters.store.createMedium();
35
+ const opened = await Promise.all([0, 1, 2].map(() => adapters.store.open(session)));
36
+ const [owner, ...claimants] = opened;
37
+ await owner?.claim(0, 1);
38
+ const claims = await Promise.allSettled(claimants.map((store) => store.claim(1, 2)));
39
+ const won = rivals.filter((_, index) => claims[index]?.status === "fulfilled");
40
+ expectEqual(won.length, 1, "EPOCH-02: exactly one of two concurrent CAS claims wins");
41
+ const winner = won[0] ?? rivals[0];
42
+ const loser = rivals.find((rival) => rival !== winner) ?? rivals[1];
43
+ if (winner === undefined || loser === undefined)
44
+ throw new Error("EPOCH-02: no rivals");
45
+ rig.setOwner("s", winner.name);
46
+ const [ran, refused] = await rig.settle(Promise.all([rig.execute(winner.name, "s", [call("cw")]), rig.execute(loser.name, "s", [call("cl")])]), "EPOCH-02: both claimants' calls");
47
+ expectEqual(texts(ran), ["ran:cw"], "EPOCH-02: the winner's call runs");
48
+ expectEqual([texts(refused), refused.messages[0]?.isError], [["The hand refused this session's epoch: peer_unauthorized"], true], "EPOCH-02: the loser's floor is refused and its call is never sent");
49
+ expectEqual(rig.bodies, ["s:c0", "s:cw"], "EPOCH-02: only the winner's call ran");
50
+ };
51
+ /** SC-MOVE step 3: an old owner's delayed walk (prepare, release) and a delayed invoke after the move are refused. */
52
+ const delayedOldOwner = async (adapters) => {
53
+ const rig = await openEpochRig(adapters, { brains: [OLD, NEW] });
54
+ rig.setOwner("s", OLD.name);
55
+ await rig.settle(rig.execute(OLD.name, "s", [call("c0")]), "EPOCH-03: the old owner's first call");
56
+ const prepare = rig.hold(stepCommit(OLD.name, "prepare"));
57
+ const delayed = rig.execute(OLD.name, "s", [call("c2")]);
58
+ await rig.settle(prepare.reached, "EPOCH-03: the old owner's delayed call is mid-walk");
59
+ rig.setOwner("s", NEW.name);
60
+ const moved = rig.execute(NEW.name, "s", [call("c1")]);
61
+ await rig.advance(2_000);
62
+ prepare.release();
63
+ expectEqual(texts(await rig.settle(moved, "EPOCH-03: the new owner's call")), ["ran:c1"], "EPOCH-03: new owner");
64
+ expectEqual(texts(await rig.settle(delayed, "EPOCH-03: the old owner's mid-walk call")), ["The hand refused this tool call: epoch_fenced"], "EPOCH-03: the old owner's walk is refused at its next step");
65
+ const late = await rig.settle(rig.execute(OLD.name, "s", [call("c3")]), "EPOCH-03: a delayed old-owner invoke");
66
+ expectEqual(texts(late), ["The hand refused this tool call: epoch_fenced"], "EPOCH-03: a delayed invoke is fenced");
67
+ await rig.advance(200);
68
+ const rows = await rig.rows();
69
+ expectEqual(rig.bodies, ["s:c0", "s:c1"], "EPOCH-03: no old-owner call ran after the move");
70
+ expectEqual(rows.map(({ commandId, progress }) => [
71
+ commandId,
72
+ progress.state === "settled" ? progress.outcome.reason : progress.state,
73
+ ]), [
74
+ ["brain-new-1", "acked"],
75
+ ["brain-old-1", "acked"],
76
+ ["brain-old-3", "cancelled"],
77
+ ], "EPOCH-03: the fenced walk's record is cancelled, never dispatched; the delayed invoke left no record");
78
+ };
79
+ export const EPOCH_CASES = new Map([
80
+ ["EPOCH-01", floorAckBarrier],
81
+ ["EPOCH-02", concurrentClaims],
82
+ ["EPOCH-03", delayedOldOwner],
83
+ ]);
84
+ //# sourceMappingURL=epoch-cases.js.map
@@ -0,0 +1,47 @@
1
+ import type { AgentToolCall } from "../../types.ts";
2
+ import type { StoreValue, StoreWrite } from "../../durable/store.ts";
3
+ import type { ExecutionEntry } from "../ledger-types.ts";
4
+ import { type HandPlacement } from "../remote-tool-host.ts";
5
+ import type { ToolHostResult } from "../tool-host.ts";
6
+ import { type HandCaseAdapters, type TransportPump } from "./hand-harness.ts";
7
+ export type CommitMatch = (writes: readonly StoreWrite[]) => boolean;
8
+ export interface EpochBrainSpec {
9
+ /** The brain principal: its link's authenticated peer and the name `ownerOf` answers. */
10
+ readonly name: string;
11
+ readonly epoch: number;
12
+ }
13
+ export interface EpochRig extends TransportPump {
14
+ /** Every tool body start, as `<scope>:<toolCallId>`, across all hand processes. */
15
+ readonly bodies: readonly string[];
16
+ readonly faults: readonly unknown[];
17
+ readonly killed: Promise<void>;
18
+ execute(brain: string, scope: string, calls: readonly AgentToolCall[]): Promise<ToolHostResult>;
19
+ /** Moves `scope` to `brain` in the hand's placement record (what `ownerOf` answers). */
20
+ setOwner(scope: string, brain: string): void;
21
+ /** Holds the next commit `match` picks until `release()`; `reached` settles when it arrives. */
22
+ hold(match: CommitMatch): {
23
+ readonly reached: Promise<void>;
24
+ release(): void;
25
+ };
26
+ /** A new hand process on the reopened store; every link's executor announces itself. */
27
+ restart(): Promise<void>;
28
+ rows(): Promise<ExecutionEntry[]>;
29
+ /** The floor persisted for `scope` (read from a fresh store instance), or `undefined`. */
30
+ floor(scope: string): Promise<StoreValue | undefined>;
31
+ }
32
+ export declare const floorCommit: (scope: string, epoch: number) => CommitMatch;
33
+ /** The ledger commit of `event` for a call `brain` sent (execution IDs are minted as `<brain>-<n>`). */
34
+ export declare const stepCommit: (brain: string, event: string) => CommitMatch;
35
+ /**
36
+ * One hand process reached by several brains, each over its own link with its own executor (a peer link per brain),
37
+ * sharing the hand's store, ledger and epoch fence: what a session sees when it moves from one brain to another.
38
+ */
39
+ export declare function openEpochRig(adapters: HandCaseAdapters, options: {
40
+ readonly brains: readonly EpochBrainSpec[];
41
+ readonly placement?: HandPlacement;
42
+ readonly kill?: {
43
+ readonly match: CommitMatch;
44
+ readonly at: "before" | "durable";
45
+ };
46
+ }): Promise<EpochRig>;
47
+ //# sourceMappingURL=epoch-harness.d.ts.map
@@ -0,0 +1,172 @@
1
+ import { createAdmissionLine } from "../../durable/store-admission.js";
2
+ import { createManualTimers } from "../../durable/testing/manual-timers.js";
3
+ import { claimedStore } from "../../durable/testing/store-cases.js";
4
+ import { createInProcessNetwork } from "../../transport/in-process-carrier.js";
5
+ import { localEndpoint } from "../../transport/local-endpoint.js";
6
+ import { createGrantVerifier } from "../grant-verify.js";
7
+ import { createExecutionLedger } from "../ledger.js";
8
+ import { createHandEpochFence, EPOCH_FLOOR_PREFIX } from "../remote-epoch.js";
9
+ import { createRemoteExecutor } from "../remote-executor.js";
10
+ import { createHandLedger } from "../remote-hand-ledger.js";
11
+ import { createRemoteToolHost } from "../remote-tool-host.js";
12
+ import { transportPump } from "./hand-harness.js";
13
+ const LEASE_MS = 3_600_000;
14
+ const HAND = "hand";
15
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
16
+ const field = (write, name) => {
17
+ const data = write.op === "delete" ? undefined : write.data;
18
+ return isRecord(data) ? data[name] : undefined;
19
+ };
20
+ export const floorCommit = (scope, epoch) => (writes) => writes.some((write) => write.op === "put" && write.key === `${EPOCH_FLOOR_PREFIX}${scope}` && field(write, "epoch") === epoch);
21
+ /** The ledger commit of `event` for a call `brain` sent (execution IDs are minted as `<brain>-<n>`). */
22
+ export const stepCommit = (brain, event) => (writes) => writes.some((write) => write.op === "append" &&
23
+ field(write, "event") === event &&
24
+ String(field(write, "commandId")).startsWith(`${brain}-`));
25
+ /** A hand process's store: holds and kills act on whole commits; after a kill every call fails, as in a dead process. */
26
+ function processStore(inner, holds, kill) {
27
+ let dead = false;
28
+ const alive = () => {
29
+ if (dead)
30
+ throw new Error("the hand was killed");
31
+ };
32
+ const die = (at) => {
33
+ dead = true;
34
+ kill?.die();
35
+ throw new Error(`hand killed ${at} the matched commit`);
36
+ };
37
+ let killArmed = kill !== undefined;
38
+ const live = (read) => async (...args) => {
39
+ alive();
40
+ return read(...args);
41
+ };
42
+ return {
43
+ readEpoch: live(() => inner.readEpoch()),
44
+ readHead: live(() => inner.readHead()),
45
+ claim: live((expected, next) => inner.claim(expected, next)),
46
+ mintId: () => inner.mintId(),
47
+ scanRecords: live((query) => inner.scanRecords(query)),
48
+ getDocument: live((key) => inner.getDocument(key)),
49
+ scanDocuments: live((prefix) => inner.scanDocuments(prefix)),
50
+ exportSnapshot: live(() => inner.exportSnapshot()),
51
+ importSnapshot: live((epoch, snapshot) => inner.importSnapshot(epoch, snapshot)),
52
+ async commit(epoch, writes, adopt) {
53
+ alive();
54
+ const index = holds.findIndex((hold) => hold.match(writes));
55
+ const hold = index < 0 ? undefined : holds.splice(index, 1)[0];
56
+ if (hold !== undefined) {
57
+ hold.reached.resolve();
58
+ await hold.gate.promise;
59
+ alive();
60
+ }
61
+ const killing = killArmed && kill !== undefined && kill.match(writes);
62
+ if (!killing)
63
+ return inner.commit(epoch, writes, adopt);
64
+ killArmed = false;
65
+ if (kill.at === "before")
66
+ return die("before");
67
+ await inner.commit(epoch, writes, () => { });
68
+ return die("once durable");
69
+ },
70
+ };
71
+ }
72
+ /**
73
+ * One hand process reached by several brains, each over its own link with its own executor (a peer link per brain),
74
+ * sharing the hand's store, ledger and epoch fence: what a session sees when it moves from one brain to another.
75
+ */
76
+ export async function openEpochRig(adapters, options) {
77
+ const timers = createManualTimers(1_000);
78
+ const pump = transportPump(timers);
79
+ const network = createInProcessNetwork({ schedule: (deliver) => void timers.setTimer(deliver, 0) });
80
+ const verifier = createGrantVerifier({ self: HAND, workspaces: [{ root: "/work" }], canonicalize: (path) => path });
81
+ verifier.install({
82
+ rv: 1,
83
+ expiresAt: Number.MAX_SAFE_INTEGER,
84
+ grants: options.brains.map(({ name }) => ({
85
+ holder: name,
86
+ target: HAND,
87
+ workspace: "omo",
88
+ capability: "execute",
89
+ })),
90
+ });
91
+ const handSides = new Map();
92
+ const hosts = new Map();
93
+ for (const { name, epoch } of options.brains) {
94
+ const sessionSide = adapters.transport.createSide(timers);
95
+ const handSide = adapters.transport.createSide(timers);
96
+ const endpoint = localEndpoint(adapters.platform, `epoch-${name}`, "/run/senpi-conformance");
97
+ network.listen(endpoint, handSide);
98
+ network.dial(endpoint, sessionSide).connect();
99
+ handSides.set(name, handSide);
100
+ let minted = 0;
101
+ const placement = options.placement ?? "cross-machine";
102
+ hosts.set(name, createRemoteToolHost({ transport: sessionSide, placement, epoch, mintId: () => `${name}-${minted++}` }));
103
+ }
104
+ const { medium } = await claimedStore(adapters.store);
105
+ const owners = new Map();
106
+ const bodies = [];
107
+ const faults = [];
108
+ const holds = [];
109
+ const killed = Promise.withResolvers();
110
+ const startHand = async (store) => {
111
+ const admission = createAdmissionLine();
112
+ const ledger = createExecutionLedger({ store, epoch: 1, admission });
113
+ const hand = createHandLedger({
114
+ ledger,
115
+ executor: HAND,
116
+ issuer: "session",
117
+ workspace: "workspace",
118
+ now: timers.now,
119
+ leaseMs: LEASE_MS,
120
+ });
121
+ const fence = createHandEpochFence({
122
+ ownerOf: (scope) => owners.get(scope),
123
+ durable: { store, epoch: 1, admission },
124
+ });
125
+ const executors = options.brains.map(({ name }) => {
126
+ const transport = handSides.get(name);
127
+ if (transport === undefined)
128
+ throw new Error(`no link for ${name}`);
129
+ return createRemoteExecutor({
130
+ authority: { kind: "peer", peer: name, verifier },
131
+ transport,
132
+ ledger: hand,
133
+ fence,
134
+ openScope: async (scope) => ({
135
+ run: async (handCall) => {
136
+ bodies.push(`${scope.id}:${handCall.toolCallId}`);
137
+ return { content: [{ type: "text", text: `ran:${handCall.toolCallId}` }], details: {} };
138
+ },
139
+ isSequential: () => false,
140
+ dispose: async () => { },
141
+ }),
142
+ onFault: (error) => faults.push(error),
143
+ });
144
+ });
145
+ await pump.settle(Promise.all(executors.map(({ ready }) => ready)), "every link's executor is ready");
146
+ };
147
+ const kill = options.kill === undefined ? undefined : { ...options.kill, die: () => killed.resolve() };
148
+ await startHand(processStore(await adapters.store.open(medium), holds, kill));
149
+ const reader = async () => adapters.store.open(medium);
150
+ return {
151
+ ...pump,
152
+ bodies,
153
+ faults,
154
+ killed: killed.promise,
155
+ execute(brain, scope, calls) {
156
+ const host = hosts.get(brain);
157
+ if (host === undefined)
158
+ throw new Error(`no brain ${brain}`);
159
+ return host.execute({ scope: { id: scope, root: `/work/${scope}` }, calls, mode: "parallel" }, { emit: () => { } });
160
+ },
161
+ setOwner: (scope, brain) => void owners.set(scope, brain),
162
+ hold(match) {
163
+ const hold = { match, reached: Promise.withResolvers(), gate: Promise.withResolvers() };
164
+ holds.push(hold);
165
+ return { reached: hold.reached.promise, release: () => hold.gate.resolve() };
166
+ },
167
+ restart: async () => startHand(processStore(await reader(), holds, undefined)),
168
+ rows: async () => createExecutionLedger({ store: await reader(), epoch: 1, admission: createAdmissionLine() }).scan(),
169
+ floor: async (scope) => (await reader()).getDocument(`${EPOCH_FLOOR_PREFIX}${scope}`),
170
+ };
171
+ }
172
+ //# sourceMappingURL=epoch-harness.js.map
@@ -0,0 +1,3 @@
1
+ import type { RegisteredCase } from "../../conformance/registry.ts";
2
+ export declare const EPOCH_REGISTRY: readonly RegisteredCase[];
3
+ //# sourceMappingURL=epoch-registry.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { KILL_EPOCH_DECLARATIONS } from "./kill-epoch.js";
2
+ const epochCase = (id, impl, expected) => ({
3
+ id,
4
+ impl,
5
+ intro: "#5729",
6
+ adapters: ["store", "transport", "executor"],
7
+ expected,
8
+ });
9
+ const EPOCH_IMPL = "packages/agent/src/execution/testing/epoch-cases.ts";
10
+ export const EPOCH_REGISTRY = [
11
+ epochCase("EPOCH-01", EPOCH_IMPL, "a barrier holding the floor ACK while the new owner dispatches: 0 effects, then once"),
12
+ epochCase("EPOCH-02", EPOCH_IMPL, "two concurrent CAS claims: exactly one owner; only its calls run"),
13
+ epochCase("EPOCH-03", EPOCH_IMPL, "an old owner's delayed prepare, release or invoke after the new owner's first call is refused"),
14
+ epochCase("MULTI-EPOCH-01", "packages/agent/src/execution/testing/multi-epoch-cases.ts", "one session's epoch bump leaves the other sessions' scopes on the hand untouched"),
15
+ ...KILL_EPOCH_DECLARATIONS.map(({ id, expected }) => epochCase(id, "packages/agent/src/execution/testing/kill-epoch.ts", expected)),
16
+ ];
17
+ //# sourceMappingURL=epoch-registry.js.map
@@ -40,6 +40,9 @@ export interface HandRig {
40
40
  rows(): Promise<ExecutionEntry[]>;
41
41
  }
42
42
  export declare function call(id: string): AgentToolCall;
43
+ export type TransportPump = Pick<HandRig, "advance" | "settle" | "runUntil">;
44
+ /** Steps transport time on `timers` the way every hand rig waits (see {@link HandRig.advance}). */
45
+ export declare function transportPump(timers: ManualTimers): TransportPump;
43
46
  export declare function openHandRig(adapters: HandCaseAdapters, options: {
44
47
  readonly placement: HandPlacement;
45
48
  readonly killAt?: KillPoint;
@@ -16,6 +16,31 @@ const drain = async () => {
16
16
  export function call(id) {
17
17
  return { type: "toolCall", id, name: "probe", arguments: { id } };
18
18
  }
19
+ /** Steps transport time on `timers` the way every hand rig waits (see {@link HandRig.advance}). */
20
+ export function transportPump(timers) {
21
+ const pump = async (stop, ms) => {
22
+ const end = timers.now() + ms;
23
+ await drain();
24
+ while (!stop() && timers.now() < end) {
25
+ await timers.advanceTo(Math.min(end, timers.now() + TICK_MS));
26
+ await drain();
27
+ }
28
+ };
29
+ const runUntil = async (done, what, budgetMs = 600_000) => {
30
+ await pump(done, budgetMs);
31
+ if (!done())
32
+ throw new Error(`${what}: not reached within ${budgetMs} ms of transport time`);
33
+ };
34
+ const settle = async (promise, what, budgetMs = 600_000) => {
35
+ let outcome;
36
+ promise.then((value) => void (outcome = { value }), (error) => void (outcome = { error }));
37
+ await runUntil(() => outcome !== undefined, what, budgetMs);
38
+ if (outcome === undefined || "error" in outcome)
39
+ throw outcome?.error;
40
+ return outcome.value;
41
+ };
42
+ return { advance: (ms) => pump(() => false, ms), settle, runUntil };
43
+ }
19
44
  export async function openHandRig(adapters, options) {
20
45
  const timers = createManualTimers(1_000);
21
46
  const network = createInProcessNetwork({ schedule: (deliver) => void timers.setTimer(deliver, 0) });
@@ -83,29 +108,9 @@ export async function openHandRig(adapters, options) {
83
108
  let current = await adapters.store.open(medium, { onWritePoint: killing });
84
109
  await startHand(current).ready;
85
110
  const host = createRemoteToolHost({ transport: sessionSide, placement: options.placement });
86
- const pump = async (stop, ms) => {
87
- const end = timers.now() + ms;
88
- await drain();
89
- while (!stop() && timers.now() < end) {
90
- await timers.advanceTo(Math.min(end, timers.now() + TICK_MS));
91
- await drain();
92
- }
93
- };
94
- const runUntil = async (done, what, budgetMs = 600_000) => {
95
- await pump(done, budgetMs);
96
- if (!done())
97
- throw new Error(`${what}: not reached within ${budgetMs} ms of transport time`);
98
- };
99
- const settle = async (promise, what, budgetMs = 600_000) => {
100
- let outcome;
101
- promise.then((value) => void (outcome = { value }), (error) => void (outcome = { error }));
102
- await runUntil(() => outcome !== undefined, what, budgetMs);
103
- if (outcome === undefined || "error" in outcome)
104
- throw outcome?.error;
105
- return outcome.value;
106
- };
111
+ const { advance, settle, runUntil } = transportPump(timers);
107
112
  return {
108
- advance: (ms) => pump(() => false, ms),
113
+ advance,
109
114
  bodies,
110
115
  faults,
111
116
  killed: killed.promise,
@@ -0,0 +1,3 @@
1
+ import type { RegisteredCase } from "../../conformance/registry.ts";
2
+ export declare const HAND_REGISTRY: readonly RegisteredCase[];
3
+ //# sourceMappingURL=hand-registry.d.ts.map
@@ -0,0 +1,20 @@
1
+ import { KILL_HAND_DECLARATIONS } from "./kill-hand.js";
2
+ const HAND_INTRO = "#5482";
3
+ const handCase = (id, impl, expected) => ({
4
+ id,
5
+ impl,
6
+ intro: HAND_INTRO,
7
+ adapters: ["store", "transport", "executor"],
8
+ expected,
9
+ });
10
+ const KILL_HAND_IMPL = "packages/agent/src/execution/testing/kill-hand.ts";
11
+ const MULTI_HAND_IMPL = "packages/agent/src/execution/testing/multi-hand-cases.ts";
12
+ const FAULT_HAND_IMPL = "packages/agent/src/execution/testing/fault-hand-cases.ts";
13
+ export const HAND_REGISTRY = [
14
+ ...KILL_HAND_DECLARATIONS.map(({ id, expected }) => handCase(id, KILL_HAND_IMPL, expected)),
15
+ handCase("MULTI-HAND-01", MULTI_HAND_IMPL, "N scopes batch at once on one hand; each scope's calls start in lane order"),
16
+ handCase("MULTI-KILL-01", MULTI_HAND_IMPL, "cross-machine: a hand killed with several scopes in flight; each ends hand_restarted, uncertain, never rerun"),
17
+ ...["slow", "lossy", "laggy", "flap", "drop-reattach"].map((profile, index) => handCase(`FAULT-HAND-0${index + 1}`, FAULT_HAND_IMPL, `${profile} profile: every call settles with its unfaulted result, runs once, per-scope order kept`)),
18
+ handCase("FAULT-HAND-MULTI-01", FAULT_HAND_IMPL, "hand unreachable past the resume window: dependent calls pause, then each scope resumes exactly once"),
19
+ ];
20
+ //# sourceMappingURL=hand-registry.js.map
@@ -0,0 +1,9 @@
1
+ import type { CaseImplementation } from "../../conformance/runner.ts";
2
+ import { type HandCaseAdapters } from "./hand-harness.ts";
3
+ export interface KillEpochDeclaration {
4
+ readonly id: string;
5
+ readonly expected: string;
6
+ }
7
+ export declare const KILL_EPOCH_DECLARATIONS: readonly KillEpochDeclaration[];
8
+ export declare const KILL_EPOCH_CASES: ReadonlyMap<string, CaseImplementation<HandCaseAdapters>>;
9
+ //# sourceMappingURL=kill-epoch.d.ts.map