@agentropy/testkit 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ https://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,34 @@
1
- # Temporary Holding Version
1
+ # @agentropy/testkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Offline fakes and conformance suites for Agentropy.** Part of [Agentropy](https://github.com/bassemZohdy/agentropy), a TypeScript framework for durable, capability-driven multi-agent work. Version 0.x: the API can still change between minor versions.
4
+
5
+ Everything needed to test agents and providers without a network: a fake clock, fake model, fake policy, audit and credential fakes, a fault injector, a network guard, a fake workflow engine, and reusable conformance suites (store, communication, workflow engine) for the authors of adapters.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @agentropy/testkit
11
+ ```
12
+
13
+ Node 24 or newer.
14
+
15
+ ## Use
16
+
17
+ ```ts
18
+ import { FakeClock, FakePolicy } from '@agentropy/testkit';
19
+
20
+ const clock = new FakeClock('2026-01-01T00:00:00.000Z');
21
+ const pdp = new FakePolicy(); // allows everything unless you add to pdp.denied
22
+ ```
23
+
24
+ Use it as a dev dependency next to `@agentropy/runtime`.
25
+
26
+ ## Learn more
27
+
28
+ - [Conformance kit](https://github.com/bassemZohdy/agentropy/blob/main/docs/conformance-kit.md)
29
+ - [Building agents](https://github.com/bassemZohdy/agentropy/blob/main/skills/agentropy-build-agent/SKILL.md)
30
+ - [Every export](https://github.com/bassemZohdy/agentropy/blob/main/docs/api.md)
31
+
32
+ ## License
33
+
34
+ Apache-2.0. See the [repository](https://github.com/bassemZohdy/agentropy) for the source, issues and contributing guide.
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Reusable AgentCommunicationProvider conformance suite (R-31, AC-18). Plain functions: pass your test
3
+ * runner's describe/it/expect so provider authors can run it in their own repositories.
4
+ */
5
+ import { type AgentCommunicationProvider, type AgentEvent, type AgentMessage, type AgentRef, type CommunicationRouter, type DelegationRequest, type TaskSnapshot, type TrustedPrincipal } from '@agentropy/core';
6
+ export interface TestApi {
7
+ describe: (name: string, fn: () => void) => void;
8
+ it: (name: string, fn: () => Promise<void> | void) => void;
9
+ expect: (value: unknown) => {
10
+ toBe(v: unknown): void;
11
+ toEqual(v: unknown): void;
12
+ };
13
+ }
14
+ /** Minimal in-memory target honoring idempotency keys and tenant scoping; stands in for a TaskService. */
15
+ export declare class FakeDirectTarget {
16
+ readonly tasks: Map<string, {
17
+ snapshot: TaskSnapshot;
18
+ tenantId: string;
19
+ callerId: string;
20
+ }>;
21
+ readonly byKey: Map<string, {
22
+ taskId: string;
23
+ fingerprint: string;
24
+ }>;
25
+ readonly received: AgentMessage[];
26
+ private seq;
27
+ delegate<I>(request: DelegationRequest<I>, caller: TrustedPrincipal): Promise<{
28
+ taskId: string;
29
+ }>;
30
+ private visible;
31
+ getTask(taskId: string, caller: TrustedPrincipal): Promise<TaskSnapshot>;
32
+ cancel(taskId: string, caller: TrustedPrincipal): Promise<TaskSnapshot>;
33
+ subscribe(taskId: string, caller: TrustedPrincipal): AsyncIterable<AgentEvent>;
34
+ receive(message: AgentMessage): Promise<{
35
+ accepted: boolean;
36
+ }>;
37
+ }
38
+ export interface CommunicationConformanceSetup {
39
+ router: CommunicationRouter;
40
+ provider: AgentCommunicationProvider;
41
+ target: AgentRef;
42
+ caller: TrustedPrincipal;
43
+ /** Messages the target observed, for the forged-actor check. */
44
+ received: () => AgentMessage[];
45
+ }
46
+ export declare function defineCommunicationConformance(t: TestApi, name: string, setup: () => CommunicationConformanceSetup): void;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Reusable AgentCommunicationProvider conformance suite (R-31, AC-18). Plain functions: pass your test
3
+ * runner's describe/it/expect so provider authors can run it in their own repositories.
4
+ */
5
+ import { AgentropyError, isAgentropyError, } from '@agentropy/core';
6
+ /** Minimal in-memory target honoring idempotency keys and tenant scoping; stands in for a TaskService. */
7
+ export class FakeDirectTarget {
8
+ tasks = new Map();
9
+ byKey = new Map();
10
+ received = [];
11
+ seq = 0;
12
+ async delegate(request, caller) {
13
+ const key = `${caller.tenantId}|${caller.id}|${request.idempotencyKey}`;
14
+ const fingerprint = JSON.stringify([request.target, request.input]);
15
+ const prior = this.byKey.get(key);
16
+ if (prior) {
17
+ if (prior.fingerprint !== fingerprint)
18
+ throw new AgentropyError('IdempotencyConflict', 'Idempotency key reused with a different request');
19
+ return { taskId: prior.taskId };
20
+ }
21
+ const taskId = `task-${++this.seq}`;
22
+ this.tasks.set(taskId, {
23
+ snapshot: { taskId, status: 'created', revision: 1, authority: 'local' },
24
+ tenantId: caller.tenantId,
25
+ callerId: caller.id,
26
+ });
27
+ this.byKey.set(key, { taskId, fingerprint });
28
+ return { taskId };
29
+ }
30
+ visible(taskId, caller) {
31
+ const t = this.tasks.get(taskId);
32
+ if (!t || t.tenantId !== caller.tenantId)
33
+ throw new AgentropyError('NotFound', 'Task not found');
34
+ return t;
35
+ }
36
+ async getTask(taskId, caller) {
37
+ return structuredClone(this.visible(taskId, caller).snapshot);
38
+ }
39
+ async cancel(taskId, caller) {
40
+ const t = this.visible(taskId, caller);
41
+ if (['completed', 'failed', 'cancelled'].includes(t.snapshot.status))
42
+ throw new AgentropyError('InvalidState', 'Task is terminal');
43
+ t.snapshot = {
44
+ ...t.snapshot,
45
+ status: 'cancelled',
46
+ revision: t.snapshot.revision + 1,
47
+ };
48
+ return structuredClone(t.snapshot);
49
+ }
50
+ async *subscribe(taskId, caller) {
51
+ const t = this.visible(taskId, caller);
52
+ yield {
53
+ eventId: `${taskId}:${t.snapshot.revision}`,
54
+ taskId,
55
+ type: 'taskStatusChanged',
56
+ revision: t.snapshot.revision,
57
+ payload: { status: t.snapshot.status },
58
+ };
59
+ }
60
+ async receive(message) {
61
+ this.received.push(message);
62
+ return { accepted: true };
63
+ }
64
+ }
65
+ async function errorCode(p) {
66
+ try {
67
+ await p;
68
+ return 'no-error';
69
+ }
70
+ catch (err) {
71
+ return isAgentropyError(err) ? err.code : 'non-agentropy';
72
+ }
73
+ }
74
+ export function defineCommunicationConformance(t, name, setup) {
75
+ const ctx = (caller) => ({
76
+ caller,
77
+ correlationId: 'corr-1',
78
+ });
79
+ const request = (key, input = { x: 1 }) => ({
80
+ target: {},
81
+ input,
82
+ idempotencyKey: key,
83
+ correlationId: 'corr-1',
84
+ });
85
+ t.describe(`communication provider conformance: ${name} (AC-18)`, () => {
86
+ t.it('delegate → getTask → cancel through a pinned route', async () => {
87
+ const s = setup();
88
+ const route = await s.router.selectRoute(s.target, 'delegate', ctx(s.caller));
89
+ t.expect(route.providerId).toBe(s.provider.id);
90
+ const p = s.router.provider(route);
91
+ const ref = await p.delegate(route, request('k1'), ctx(s.caller));
92
+ t.expect((await p.getTask(ref, ctx(s.caller))).normalized).toBe('created');
93
+ t.expect((await p.cancel(ref, ctx(s.caller))).normalized).toBe('cancelled');
94
+ t.expect(await errorCode(p.cancel(ref, ctx(s.caller)))).toBe('InvalidState');
95
+ });
96
+ t.it('duplicate delegation with the same key returns the original task; a different payload conflicts', async () => {
97
+ const s = setup();
98
+ const route = await s.router.selectRoute(s.target, 'delegate', ctx(s.caller));
99
+ const p = s.router.provider(route);
100
+ const a = await p.delegate(route, request('dup'), ctx(s.caller));
101
+ const b = await p.delegate(route, request('dup'), ctx(s.caller));
102
+ t.expect(b.remoteTaskId).toBe(a.remoteTaskId);
103
+ t.expect(await errorCode(p.delegate(route, request('dup', { x: 2 }), ctx(s.caller)))).toBe('IdempotencyConflict');
104
+ });
105
+ t.it('subscribe yields revisioned task events', async () => {
106
+ const s = setup();
107
+ const route = await s.router.selectRoute(s.target, 'subscribe', ctx(s.caller));
108
+ const p = s.router.provider(route);
109
+ const ref = await p.delegate(route, request('sub'), ctx(s.caller));
110
+ const events = [];
111
+ for await (const e of p.subscribe(ref, ctx(s.caller)))
112
+ events.push(e);
113
+ t.expect(events.length > 0 &&
114
+ events.every((e) => e.taskId === ref.remoteTaskId && typeof e.revision === 'number')).toBe(true);
115
+ });
116
+ t.it('cross-tenant targets are refused before route selection', async () => {
117
+ const s = setup();
118
+ t.expect(await errorCode(s.router.selectRoute({ ...s.target, tenantId: 'other-tenant' }, 'delegate', ctx(s.caller)))).toBe('TenantMismatch');
119
+ });
120
+ t.it('a forged envelope actor is replaced by the verified caller', async () => {
121
+ const s = setup();
122
+ const route = await s.router.selectRoute(s.target, 'send', ctx(s.caller));
123
+ const forged = {
124
+ schemaVersion: 1,
125
+ kind: 'command',
126
+ name: 'ping',
127
+ messageId: 'm-1',
128
+ correlationId: 'corr-1',
129
+ idempotencyKey: 'm-1',
130
+ tenantId: 'other-tenant',
131
+ actor: { principalId: 'root', principalType: 'service' },
132
+ createdAt: '2026-11-05T00:00:00.000Z',
133
+ payload: {},
134
+ };
135
+ await s.router.provider(route).send(route, forged, ctx(s.caller));
136
+ const got = s.received().at(-1);
137
+ t.expect(got.actor.principalId).toBe(s.caller.id);
138
+ t.expect(got.tenantId).toBe(s.caller.tenantId);
139
+ });
140
+ t.it('undeclared requirements fail explicitly, never by silent downgrade', async () => {
141
+ const s = setup();
142
+ t.expect(await errorCode(s.router.selectRoute(s.target, 'delegate', ctx(s.caller), {
143
+ durability: 'durable-execution',
144
+ }))).toBe(s.provider.features.durability === 'durable-execution'
145
+ ? 'no-error'
146
+ : 'GuaranteeUnavailable');
147
+ t.expect(await errorCode(s.router.selectRoute(s.target, 'delegate', ctx(s.caller), {
148
+ extensions: ['urn:x:streaming-messages'],
149
+ }))).toBe('UnsupportedOperation');
150
+ });
151
+ t.it('a pinned route whose provider is gone fails NoCompatibleRoute', async () => {
152
+ const s = setup();
153
+ const route = await s.router.selectRoute(s.target, 'delegate', ctx(s.caller));
154
+ t.expect(await errorCode(Promise.resolve().then(() => s.router.provider({ ...route, providerId: 'vanished' })))).toBe('NoCompatibleRoute');
155
+ });
156
+ });
157
+ }
@@ -0,0 +1,20 @@
1
+ export interface ScheduledCall {
2
+ readonly id: number;
3
+ readonly dueAt: number;
4
+ readonly callback: () => void;
5
+ }
6
+ /** Deterministic, synchronous fake clock for tests; no real timers or wall clock. */
7
+ export declare class FakeClock {
8
+ private timestamp;
9
+ private nextId;
10
+ private scheduled;
11
+ /** Accepts epoch milliseconds or an ISO-8601 instant. */
12
+ constructor(initial?: number | string);
13
+ now(): number;
14
+ /** Current time as ISO-8601; bound, so it can be passed as a `now: () => string` dependency. */
15
+ readonly iso: () => string;
16
+ scheduleAt(dueAt: number, callback: () => void): number;
17
+ cancel(id: number): boolean;
18
+ advanceTo(epochMs: number): void;
19
+ advanceBy(milliseconds: number): void;
20
+ }
@@ -0,0 +1,58 @@
1
+ /** Deterministic, synchronous fake clock for tests; no real timers or wall clock. */
2
+ export class FakeClock {
3
+ timestamp;
4
+ nextId = 0;
5
+ scheduled = [];
6
+ /** Accepts epoch milliseconds or an ISO-8601 instant. */
7
+ constructor(initial = 0) {
8
+ const initialEpochMs = typeof initial === 'string' ? Date.parse(initial) : initial;
9
+ if (!Number.isSafeInteger(initialEpochMs)) {
10
+ throw new RangeError('Invalid initial time');
11
+ }
12
+ this.timestamp = initialEpochMs;
13
+ }
14
+ now() {
15
+ return this.timestamp;
16
+ }
17
+ /** Current time as ISO-8601; bound, so it can be passed as a `now: () => string` dependency. */
18
+ iso = () => new Date(this.timestamp).toISOString();
19
+ scheduleAt(dueAt, callback) {
20
+ if (!Number.isSafeInteger(dueAt) || dueAt < this.timestamp) {
21
+ throw new RangeError('Invalid scheduled time');
22
+ }
23
+ const id = ++this.nextId;
24
+ this.scheduled.push({ id, dueAt, callback });
25
+ return id;
26
+ }
27
+ cancel(id) {
28
+ const previous = this.scheduled.length;
29
+ this.scheduled = this.scheduled.filter((item) => item.id !== id);
30
+ return this.scheduled.length < previous;
31
+ }
32
+ advanceTo(epochMs) {
33
+ if (!Number.isSafeInteger(epochMs) || epochMs < this.timestamp) {
34
+ throw new RangeError('Clock cannot move backwards or use an unsafe time');
35
+ }
36
+ let count = 0;
37
+ while (true) {
38
+ this.scheduled.sort((a, b) => a.dueAt - b.dueAt || a.id - b.id);
39
+ const next = this.scheduled[0];
40
+ if (!next || next.dueAt > epochMs)
41
+ break;
42
+ if (++count > 10000)
43
+ throw new RangeError('Too many callbacks in one advance');
44
+ this.scheduled.shift();
45
+ this.timestamp = next.dueAt;
46
+ next.callback();
47
+ }
48
+ this.timestamp = epochMs;
49
+ }
50
+ advanceBy(milliseconds) {
51
+ const validDelta = Number.isSafeInteger(milliseconds) && milliseconds >= 0;
52
+ const nextTime = this.timestamp + milliseconds;
53
+ if (!validDelta || !Number.isSafeInteger(nextTime)) {
54
+ throw new RangeError('Invalid time delta');
55
+ }
56
+ this.advanceTo(nextTime);
57
+ }
58
+ }
@@ -0,0 +1,11 @@
1
+ /** Deterministic fake text completion for offline integration tests. */
2
+ export declare class FakeModel {
3
+ private readonly responses;
4
+ private readonly prompts;
5
+ private fallback;
6
+ setResponse(prompt: string, response: string): void;
7
+ setFallback(response: string): void;
8
+ complete(prompt: string): Promise<string>;
9
+ history(): readonly string[];
10
+ reset(): void;
11
+ }
@@ -0,0 +1,28 @@
1
+ /** Deterministic fake text completion for offline integration tests. */
2
+ export class FakeModel {
3
+ responses = new Map();
4
+ prompts = [];
5
+ fallback;
6
+ setResponse(prompt, response) {
7
+ this.responses.set(prompt, response);
8
+ }
9
+ setFallback(response) {
10
+ this.fallback = response;
11
+ }
12
+ async complete(prompt) {
13
+ this.prompts.push(prompt);
14
+ const result = this.responses.get(prompt) ?? this.fallback;
15
+ if (result === undefined) {
16
+ throw new Error('No fake response configured for prompt');
17
+ }
18
+ return result;
19
+ }
20
+ history() {
21
+ return [...this.prompts];
22
+ }
23
+ reset() {
24
+ this.responses.clear();
25
+ this.prompts.length = 0;
26
+ this.fallback = undefined;
27
+ }
28
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Offline WorkflowEngine for tests and examples: runs registered async functions as "workflows", idempotent per
3
+ * key, completing when `finish` is called (or immediately with `autoFinish`). Not a workflow engine — real engines
4
+ * (Temporal, Quarkus Flow, …) plug in through the same SPI.
5
+ */
6
+ import type { WorkflowEngine, WorkflowRun } from '@agentropy/core';
7
+ export declare class FakeWorkflowEngine implements WorkflowEngine {
8
+ private readonly workflows;
9
+ readonly id = "fake-workflow";
10
+ readonly runs: Map<string, WorkflowRun & {
11
+ tenantId: string;
12
+ workflow: string;
13
+ input: unknown;
14
+ }>;
15
+ private readonly byKey;
16
+ private readonly listeners;
17
+ starts: number;
18
+ constructor(workflows?: Record<string, (input: unknown) => unknown | Promise<unknown>>);
19
+ start(workflow: string, input: unknown, ctx: {
20
+ tenantId: string;
21
+ taskId: string;
22
+ idempotencyKey: string;
23
+ }): Promise<WorkflowRun>;
24
+ status(runId: string, ctx: {
25
+ tenantId: string;
26
+ }): Promise<WorkflowRun>;
27
+ onFinished(listener: (run: WorkflowRun & {
28
+ tenantId: string;
29
+ }) => void): void;
30
+ /** Execute a running workflow's function and report completion (or failure). */
31
+ finish(runId: string): Promise<void>;
32
+ private view;
33
+ }
@@ -0,0 +1,64 @@
1
+ export class FakeWorkflowEngine {
2
+ workflows;
3
+ id = 'fake-workflow';
4
+ runs = new Map();
5
+ byKey = new Map();
6
+ listeners = [];
7
+ starts = 0;
8
+ constructor(workflows = {}) {
9
+ this.workflows = workflows;
10
+ }
11
+ async start(workflow, input, ctx) {
12
+ const existing = this.byKey.get(ctx.idempotencyKey);
13
+ if (existing)
14
+ return this.view(existing);
15
+ this.starts++;
16
+ const runId = `run-${this.runs.size + 1}`;
17
+ this.byKey.set(ctx.idempotencyKey, runId);
18
+ this.runs.set(runId, {
19
+ runId,
20
+ state: 'running',
21
+ tenantId: ctx.tenantId,
22
+ workflow,
23
+ input,
24
+ });
25
+ return this.view(runId);
26
+ }
27
+ async status(runId, ctx) {
28
+ const r = this.runs.get(runId);
29
+ if (!r || r.tenantId !== ctx.tenantId)
30
+ return { runId, state: 'failed', code: 'NotFound' };
31
+ return this.view(runId);
32
+ }
33
+ onFinished(listener) {
34
+ this.listeners.push(listener);
35
+ }
36
+ /** Execute a running workflow's function and report completion (or failure). */
37
+ async finish(runId) {
38
+ const r = this.runs.get(runId);
39
+ if (!r || r.state !== 'running')
40
+ return;
41
+ const fn = this.workflows[r.workflow];
42
+ try {
43
+ if (!fn)
44
+ throw new Error(`unknown workflow ${r.workflow}`);
45
+ r.output = await fn(r.input);
46
+ r.state = 'completed';
47
+ }
48
+ catch {
49
+ r.state = 'failed';
50
+ r.code = 'TaskFailed';
51
+ }
52
+ for (const l of this.listeners)
53
+ l({ ...this.view(runId), tenantId: r.tenantId });
54
+ }
55
+ view(runId) {
56
+ const r = this.runs.get(runId);
57
+ return {
58
+ runId,
59
+ state: r.state,
60
+ ...(r.output !== undefined ? { output: r.output } : {}),
61
+ ...(r.code ? { code: r.code } : {}),
62
+ };
63
+ }
64
+ }
@@ -0,0 +1,18 @@
1
+ /** Deterministic offline fakes (M1-10): policy decision point, audit writer, grant verifier. The clock is in fake-clock.ts. */
2
+ import type { AuditEvent, AuditIntentWriter, PolicyDecision, PolicyDecisionPoint, PolicyRequest } from '@agentropy/core';
3
+ export declare class FakePolicy implements PolicyDecisionPoint {
4
+ readonly denied: Set<string>;
5
+ readonly requests: PolicyRequest[];
6
+ down: boolean;
7
+ /** Deny by action, or by `${action}@${resourceId}`. */
8
+ decide(request: PolicyRequest): Promise<PolicyDecision>;
9
+ }
10
+ export declare class FakeAudit implements AuditIntentWriter {
11
+ readonly events: AuditEvent[];
12
+ failing: boolean;
13
+ record(event: AuditEvent): Promise<void>;
14
+ }
15
+ export declare class FakeGrants {
16
+ readonly status: Map<string, "valid" | "expired" | "revoked">;
17
+ check(ref: string): Promise<'valid' | 'expired' | 'revoked'>;
18
+ }
package/dist/fakes.js ADDED
@@ -0,0 +1,30 @@
1
+ export class FakePolicy {
2
+ denied = new Set();
3
+ requests = [];
4
+ down = false;
5
+ /** Deny by action, or by `${action}@${resourceId}`. */
6
+ async decide(request) {
7
+ this.requests.push(request);
8
+ if (this.down)
9
+ throw new Error('policy decision point unavailable');
10
+ return this.denied.has(request.action) ||
11
+ this.denied.has(`${request.action}@${request.resource.id}`)
12
+ ? { effect: 'deny' }
13
+ : { effect: 'allow' };
14
+ }
15
+ }
16
+ export class FakeAudit {
17
+ events = [];
18
+ failing = false;
19
+ async record(event) {
20
+ if (this.failing)
21
+ throw new Error('audit store unavailable');
22
+ this.events.push(structuredClone(event));
23
+ }
24
+ }
25
+ export class FakeGrants {
26
+ status = new Map();
27
+ async check(ref) {
28
+ return this.status.get(ref) ?? 'valid';
29
+ }
30
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Deterministic, in-memory fault injection for provider/runtime contract tests.
3
+ * A named operation can be configured to fail its next N invocations.
4
+ */
5
+ export declare class FaultInjector {
6
+ private readonly failures;
7
+ private readonly calls;
8
+ failNext(operation: string, times?: number, message?: string): void;
9
+ checkpoint(operation: string): void;
10
+ callCount(operation: string): number;
11
+ pendingFailures(operation: string): number;
12
+ reset(): void;
13
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Deterministic, in-memory fault injection for provider/runtime contract tests.
3
+ * A named operation can be configured to fail its next N invocations.
4
+ */
5
+ export class FaultInjector {
6
+ failures = new Map();
7
+ calls = new Map();
8
+ failNext(operation, times = 1, message = 'Injected failure') {
9
+ if (!operation.trim())
10
+ throw new RangeError('Operation must be nonempty');
11
+ if (!Number.isSafeInteger(times) || times < 1) {
12
+ throw new RangeError('Failure count must be a positive safe integer');
13
+ }
14
+ this.failures.set(operation, { remaining: times, message });
15
+ }
16
+ checkpoint(operation) {
17
+ if (!operation.trim())
18
+ throw new RangeError('Operation must be nonempty');
19
+ this.calls.set(operation, this.callCount(operation) + 1);
20
+ const failure = this.failures.get(operation);
21
+ if (!failure)
22
+ return;
23
+ failure.remaining--;
24
+ if (failure.remaining === 0)
25
+ this.failures.delete(operation);
26
+ throw new Error(failure.message);
27
+ }
28
+ callCount(operation) {
29
+ return this.calls.get(operation) ?? 0;
30
+ }
31
+ pendingFailures(operation) {
32
+ return this.failures.get(operation)?.remaining ?? 0;
33
+ }
34
+ reset() {
35
+ this.failures.clear();
36
+ this.calls.clear();
37
+ }
38
+ }
@@ -0,0 +1,11 @@
1
+ /** @agentropy/testkit — offline fakes and reusable conformance suites. */
2
+ export declare const packageName: "@agentropy/testkit";
3
+ export * from './communication.js';
4
+ export * from './fake-clock.js';
5
+ export * from './fake-model.js';
6
+ export * from './fakes.js';
7
+ export * from './fault-injector.js';
8
+ export * from './store.js';
9
+ export * from './network-guard.js';
10
+ export * from './fake-workflow.js';
11
+ export * from './workflow-conformance.js';
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ /** @agentropy/testkit — offline fakes and reusable conformance suites. */
2
+ export const packageName = '@agentropy/testkit';
3
+ export * from './communication.js';
4
+ export * from './fake-clock.js';
5
+ export * from './fake-model.js';
6
+ export * from './fakes.js';
7
+ export * from './fault-injector.js';
8
+ export * from './store.js';
9
+ export * from './network-guard.js';
10
+ export * from './fake-workflow.js';
11
+ export * from './workflow-conformance.js';
@@ -0,0 +1,13 @@
1
+ /** Thrown by every blocked network call; the same class across module instances. */
2
+ export declare const NetworkDisabledError: new (what: string) => Error;
3
+ export type NetworkDisabledError = Error;
4
+ /** Installs the guard once per process; returns a function that removes it. */
5
+ export declare function blockNetwork(): () => void;
6
+ /**
7
+ * Lets TCP connects (and DNS lookups of the host) through to exactly these `host:port` endpoints while the guard
8
+ * stays installed. `fetch` stays blocked. Returns a function that withdraws the permission.
9
+ */
10
+ export declare function allowNetwork(endpoints: string[]): () => void;
11
+ /** `host:port` of a database or service URL, for `allowNetwork`. */
12
+ export declare function endpointOf(url: string, defaultPort: number): string;
13
+ export declare const isNetworkBlocked: () => boolean;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Offline guard for test suites (AC-14 "whole suite runs with network disabled"): outbound TCP connects, DNS
3
+ * lookups and `fetch` throw. Local IPC (Unix sockets / named pipes, used by test runners) stays available.
4
+ *
5
+ * The guard is process-global (TASK-033.3): its state lives on `globalThis`, so every module instance — the
6
+ * package entry (`dist`) and the sources a setup file imports — sees the same guard. A suite that needs a live
7
+ * endpoint names it with `allowNetwork(['127.0.0.1:5432'])`; everything else stays blocked.
8
+ */
9
+ import dns from 'node:dns';
10
+ import net from 'node:net';
11
+ const KEY = Symbol.for('agentropy.testkit.networkGuard');
12
+ const state = (globalThis[KEY] ??= {
13
+ allowed: new Set(),
14
+ NetworkDisabledError: class NetworkDisabledError extends Error {
15
+ constructor(what) {
16
+ super(`Network access is disabled in tests (${what})`);
17
+ this.name = 'NetworkDisabledError';
18
+ }
19
+ },
20
+ });
21
+ /** Thrown by every blocked network call; the same class across module instances. */
22
+ export const NetworkDisabledError = state.NetworkDisabledError;
23
+ /** `host:port` of a `Socket#connect` call, or undefined for IPC (a path). */
24
+ function endpoint(args) {
25
+ const first = args[0];
26
+ if (Array.isArray(first))
27
+ return endpoint(first);
28
+ if (typeof first === 'string' && Number.isNaN(Number(first)))
29
+ return undefined;
30
+ if (typeof first === 'object' && first !== null) {
31
+ const o = first;
32
+ if (typeof o.path === 'string')
33
+ return undefined;
34
+ return `${typeof o.host === 'string' ? o.host : 'localhost'}:${String(o.port)}`;
35
+ }
36
+ return `${typeof args[1] === 'string' ? args[1] : 'localhost'}:${String(first)}`;
37
+ }
38
+ /** IP literals resolve without any network traffic; named hosts only when an allowed endpoint names them. */
39
+ const hostAllowed = (host) => net.isIP(host) !== 0 ||
40
+ [...state.allowed].some((e) => e.slice(0, e.lastIndexOf(':')) === host);
41
+ /** Installs the guard once per process; returns a function that removes it. */
42
+ export function blockNetwork() {
43
+ if (state.remove)
44
+ return state.remove;
45
+ const connect = net.Socket.prototype.connect;
46
+ const lookup = dns.lookup;
47
+ const promisesLookup = dns.promises.lookup;
48
+ const fetchFn = globalThis.fetch;
49
+ net.Socket.prototype.connect = function (...args) {
50
+ const at = endpoint(args);
51
+ if (at !== undefined && !state.allowed.has(at))
52
+ throw new NetworkDisabledError(`tcp connect ${at}`);
53
+ return connect.apply(this, args);
54
+ };
55
+ dns.lookup = ((host, ...rest) => {
56
+ if (!hostAllowed(host))
57
+ throw new NetworkDisabledError('dns lookup');
58
+ return lookup(host, ...rest);
59
+ });
60
+ dns.promises.lookup = ((host, ...rest) => hostAllowed(host)
61
+ ? promisesLookup(host, ...rest)
62
+ : Promise.reject(new NetworkDisabledError('dns lookup')));
63
+ globalThis.fetch = (() => Promise.reject(new NetworkDisabledError('fetch')));
64
+ state.remove = () => {
65
+ net.Socket.prototype.connect = connect;
66
+ dns.lookup = lookup;
67
+ dns.promises.lookup = promisesLookup;
68
+ globalThis.fetch = fetchFn;
69
+ state.remove = undefined;
70
+ };
71
+ return state.remove;
72
+ }
73
+ /**
74
+ * Lets TCP connects (and DNS lookups of the host) through to exactly these `host:port` endpoints while the guard
75
+ * stays installed. `fetch` stays blocked. Returns a function that withdraws the permission.
76
+ */
77
+ export function allowNetwork(endpoints) {
78
+ for (const e of endpoints)
79
+ if (!/^[^\s:]+:\d+$/.test(e))
80
+ throw new Error(`allowNetwork expects host:port, got ${e}`);
81
+ const added = endpoints.filter((e) => !state.allowed.has(e));
82
+ for (const e of added)
83
+ state.allowed.add(e);
84
+ return () => {
85
+ for (const e of added)
86
+ state.allowed.delete(e);
87
+ };
88
+ }
89
+ /** `host:port` of a database or service URL, for `allowNetwork`. */
90
+ export function endpointOf(url, defaultPort) {
91
+ const u = new URL(url);
92
+ return `${u.hostname}:${u.port || defaultPort}`;
93
+ }
94
+ export const isNetworkBlocked = () => state.remove !== undefined;
@@ -0,0 +1,9 @@
1
+ /** Reusable Store conformance suite (ADR-0017): every adapter (memory, SQLite, later PostgreSQL) must pass it. */
2
+ import { type Store } from '@agentropy/core';
3
+ import type { TestApi } from './communication.js';
4
+ export interface StoreConformanceOptions {
5
+ create: () => Promise<Store>;
6
+ /** For durable adapters: close and reopen the same underlying storage. */
7
+ reopen?: (store: Store) => Promise<Store>;
8
+ }
9
+ export declare function defineStoreConformance(t: TestApi, name: string, o: StoreConformanceOptions): void;
package/dist/store.js ADDED
@@ -0,0 +1,184 @@
1
+ /** Reusable Store conformance suite (ADR-0017): every adapter (memory, SQLite, later PostgreSQL) must pass it. */
2
+ import { isAgentropyError } from '@agentropy/core';
3
+ async function code(p) {
4
+ try {
5
+ await p;
6
+ return 'no-error';
7
+ }
8
+ catch (err) {
9
+ return isAgentropyError(err) ? err.code : 'non-agentropy';
10
+ }
11
+ }
12
+ export function defineStoreConformance(t, name, o) {
13
+ t.describe(`store conformance: ${name}`, () => {
14
+ t.it('insert/get and duplicate IDs fail StaleRevision', async () => {
15
+ const s = await o.create();
16
+ const doc = await s.transaction((tx) => tx.insert('tasks', 't1', { tenantId: 'a', status: 'created' }));
17
+ t.expect([doc.revision, doc.value]).toEqual([
18
+ 1,
19
+ { tenantId: 'a', status: 'created' },
20
+ ]);
21
+ t.expect(await code(s.transaction((tx) => tx.insert('tasks', 't1', { tenantId: 'a' })))).toBe('StaleRevision');
22
+ t.expect((await s.transaction((tx) => tx.get('tasks', 't1')))?.value).toEqual({ tenantId: 'a', status: 'created' });
23
+ t.expect(await s.transaction((tx) => tx.get('tasks', 'nope'))).toBe(undefined);
24
+ await s.close();
25
+ });
26
+ t.it('update and remove are compare-and-swap on revision; seq is stable', async () => {
27
+ const s = await o.create();
28
+ const a = await s.transaction((tx) => tx.insert('tasks', 't1', { status: 'created' }));
29
+ const b = await s.transaction((tx) => tx.update('tasks', 't1', 1, { status: 'assigned' }));
30
+ t.expect([b.revision, b.seq]).toEqual([2, a.seq]);
31
+ t.expect(await code(s.transaction((tx) => tx.update('tasks', 't1', 1, { status: 'running' })))).toBe('StaleRevision');
32
+ t.expect(await code(s.transaction((tx) => tx.update('tasks', 'missing', 1, {})))).toBe('StaleRevision');
33
+ t.expect(await code(s.transaction((tx) => tx.remove('tasks', 't1', 1)))).toBe('StaleRevision');
34
+ await s.transaction((tx) => tx.remove('tasks', 't1', 2));
35
+ t.expect(await s.transaction((tx) => tx.get('tasks', 't1'))).toBe(undefined);
36
+ await s.close();
37
+ });
38
+ t.it('find filters by indexed equality and range, orders by seq or field, pages by seq', async () => {
39
+ const s = await o.create();
40
+ await s.transaction(async (tx) => {
41
+ await tx.insert('wakeups', 'w3', {
42
+ taskId: 'x',
43
+ status: 'armed',
44
+ dueAt: '2026-11-05T03:00:00Z',
45
+ });
46
+ await tx.insert('wakeups', 'w1', {
47
+ taskId: 'x',
48
+ status: 'armed',
49
+ dueAt: '2026-11-05T01:00:00Z',
50
+ });
51
+ await tx.insert('wakeups', 'w2', {
52
+ taskId: 'y',
53
+ status: 'fired',
54
+ dueAt: '2026-11-05T02:00:00Z',
55
+ });
56
+ await tx.insert('wakeups', 'w4', { taskId: 'y', status: 'armed' });
57
+ });
58
+ const ids = async (p) => (await p).map((d) => d.id);
59
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', { where: { status: 'armed' } })))).toEqual(['w3', 'w1', 'w4']);
60
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', {
61
+ where: { status: 'armed' },
62
+ range: { field: 'dueAt', lte: '2026-11-05T02:30:00Z' },
63
+ })))).toEqual(['w1']);
64
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', {
65
+ where: { status: 'armed' },
66
+ orderBy: 'dueAt',
67
+ limit: 2,
68
+ })))).toEqual(['w4', 'w1']);
69
+ const first = (await s.transaction((tx) => tx.find('wakeups', {})))[0];
70
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', { afterSeq: first.seq, limit: 1 })))).toEqual(['w1']);
71
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', { where: { dueAt: null } })))).toEqual(['w4']);
72
+ await s.close();
73
+ });
74
+ t.it('limit 0 returns nothing; strings order by code unit, nulls first; ranges combine with equality', async () => {
75
+ const s = await o.create();
76
+ await s.transaction(async (tx) => {
77
+ for (const [id, dueAt] of [
78
+ ['w-e', 'é'],
79
+ ['w-z', 'Z'],
80
+ ['w-a', 'a'],
81
+ ['w-b', 'b'],
82
+ ])
83
+ await tx.insert('wakeups', id, {
84
+ taskId: 'x',
85
+ status: 'armed',
86
+ dueAt,
87
+ });
88
+ await tx.insert('wakeups', 'w-fired', {
89
+ taskId: 'x',
90
+ status: 'fired',
91
+ dueAt: 'a',
92
+ });
93
+ await tx.insert('wakeups', 'w-null', {
94
+ taskId: 'x',
95
+ status: 'armed',
96
+ });
97
+ });
98
+ const ids = async (p) => (await p).map((d) => d.id);
99
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', { limit: 0 })))).toEqual([]);
100
+ // Code-unit order (uppercase before lowercase, accented after ASCII), nulls first.
101
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', {
102
+ where: { status: 'armed' },
103
+ orderBy: 'dueAt',
104
+ })))).toEqual(['w-null', 'w-z', 'w-a', 'w-b', 'w-e']);
105
+ // Descending is the exact reverse, with and without a limit.
106
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', {
107
+ where: { status: 'armed' },
108
+ orderBy: 'dueAt',
109
+ descending: true,
110
+ })))).toEqual(['w-e', 'w-b', 'w-a', 'w-z', 'w-null']);
111
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', { descending: true, limit: 2 })))).toEqual(['w-null', 'w-fired']);
112
+ // `beforeSeq` continues a descending page: the rows committed before the last one seen (FIX-062).
113
+ const newest = (await s.transaction((tx) => tx.find('wakeups', { descending: true, limit: 2 }))).at(-1);
114
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', {
115
+ descending: true,
116
+ beforeSeq: newest.seq,
117
+ limit: 2,
118
+ })))).toEqual(['w-b', 'w-a']);
119
+ t.expect(await ids(s.transaction((tx) => tx.find('wakeups', {
120
+ where: { status: 'armed' },
121
+ range: { field: 'dueAt', gte: 'a', lte: 'b' },
122
+ orderBy: 'dueAt',
123
+ })))).toEqual(['w-a', 'w-b']);
124
+ await s.close();
125
+ });
126
+ t.it('a failed transaction rolls back every write across collections', async () => {
127
+ const s = await o.create();
128
+ await s.transaction((tx) => tx.insert('tasks', 't1', { status: 'running' }));
129
+ const result = await code(s.transaction(async (tx) => {
130
+ await tx.update('tasks', 't1', 1, { status: 'waiting' });
131
+ await tx.insert('checkpoints', 'c1', { taskId: 't1', data: 1 });
132
+ await tx.insert('wakeups', 'w1', { taskId: 't1', status: 'armed' });
133
+ await tx.insert('tasks', 't1', {}); // duplicate → StaleRevision → rollback
134
+ }));
135
+ t.expect(result).toBe('StaleRevision');
136
+ const after = await s.transaction(async (tx) => [
137
+ await tx.get('tasks', 't1'),
138
+ await tx.get('checkpoints', 'c1'),
139
+ await tx.get('wakeups', 'w1'),
140
+ ]);
141
+ t.expect([
142
+ after[0]?.revision,
143
+ after[0]?.value,
144
+ after[1],
145
+ after[2],
146
+ ]).toEqual([1, { status: 'running' }, undefined, undefined]);
147
+ await s.close();
148
+ });
149
+ t.it('transactions are serialized: concurrent read-modify-write loses no update', async () => {
150
+ const s = await o.create();
151
+ await s.transaction((tx) => tx.insert('sessions', 'counter', { n: 0 }));
152
+ await Promise.all(Array.from({ length: 20 }, () => s.transaction(async (tx) => {
153
+ const cur = (await tx.get('sessions', 'counter'));
154
+ await new Promise((r) => setTimeout(r, 1));
155
+ await tx.update('sessions', 'counter', cur.revision, {
156
+ n: cur.value.n + 1,
157
+ });
158
+ })));
159
+ t.expect((await s.transaction((tx) => tx.get('sessions', 'counter')))?.value.n).toBe(20);
160
+ await s.close();
161
+ });
162
+ t.it('non-scalar indexed fields are rejected', async () => {
163
+ const s = await o.create();
164
+ t.expect(await code(s.transaction((tx) => tx.insert('tasks', 'bad', { status: { nested: true } })))).toBe('Internal');
165
+ await s.close();
166
+ });
167
+ if (o.reopen) {
168
+ const reopen = o.reopen;
169
+ t.it('committed data survives close/reopen; uncommitted data does not; seq keeps increasing', async () => {
170
+ const s = await o.create();
171
+ const a = await s.transaction((tx) => tx.insert('outbox', 'e1', { published: 0, aggregateId: 't1' }));
172
+ await code(s.transaction(async (tx) => {
173
+ await tx.insert('outbox', 'e2', { published: 0 });
174
+ throw new Error('crash before commit');
175
+ }));
176
+ const s2 = await reopen(s);
177
+ t.expect((await s2.transaction((tx) => tx.find('outbox', {}))).map((d) => d.id)).toEqual(['e1']);
178
+ const b = await s2.transaction((tx) => tx.insert('outbox', 'e3', { published: 0 }));
179
+ t.expect(b.seq > a.seq).toBe(true);
180
+ await s2.close();
181
+ });
182
+ }
183
+ });
184
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Reusable WorkflowEngine conformance suite (FEAT-028.6, C-05, X-10). Any engine adapter must pass it offline:
3
+ * idempotent start per key, tenant-scoped status without disclosure, terminal-state mapping, and exactly one
4
+ * completion report per terminal run with the owning tenant. The harness drives runs to an end through
5
+ * `finish`, because only the engine (or its fake) knows how a run completes.
6
+ */
7
+ import type { WorkflowEngine } from '@agentropy/core';
8
+ import type { TestApi } from './communication.js';
9
+ export interface WorkflowConformanceHarness {
10
+ engine: WorkflowEngine;
11
+ /** Drive a running run to an end, then let the adapter report it (webhook, poll, …). */
12
+ finish(runId: string, outcome: {
13
+ output: unknown;
14
+ } | {
15
+ failed: true;
16
+ }): Promise<void>;
17
+ /** Name of a workflow the engine knows. */
18
+ workflow: string;
19
+ }
20
+ export declare function defineWorkflowEngineConformance(t: TestApi, name: string, setup: () => Promise<WorkflowConformanceHarness> | WorkflowConformanceHarness): void;
@@ -0,0 +1,55 @@
1
+ export function defineWorkflowEngineConformance(t, name, setup) {
2
+ const ctx = (tenantId, key) => ({
3
+ tenantId,
4
+ taskId: `task-${key}`,
5
+ idempotencyKey: key,
6
+ });
7
+ t.describe(`workflow engine conformance: ${name}`, () => {
8
+ t.it('start is idempotent per key and returns a running run', async () => {
9
+ const h = await setup();
10
+ const a = await h.engine.start(h.workflow, { n: 1 }, ctx('t-1', 'k1'));
11
+ const again = await h.engine.start(h.workflow, { n: 1 }, ctx('t-1', 'k1'));
12
+ const other = await h.engine.start(h.workflow, { n: 2 }, ctx('t-1', 'k2'));
13
+ t.expect(a.state).toBe('running');
14
+ t.expect(again.runId).toBe(a.runId);
15
+ t.expect(other.runId === a.runId).toBe(false);
16
+ });
17
+ t.it('status is tenant-scoped: another tenant or an unknown run is NotFound', async () => {
18
+ const h = await setup();
19
+ const run = await h.engine.start(h.workflow, {}, ctx('t-1', 'k'));
20
+ t.expect((await h.engine.status(run.runId, { tenantId: 't-1' })).state).toBe('running');
21
+ t.expect(await h.engine.status(run.runId, { tenantId: 't-2' })).toEqual({
22
+ runId: run.runId,
23
+ state: 'failed',
24
+ code: 'NotFound',
25
+ });
26
+ t.expect((await h.engine.status('no-such-run', { tenantId: 't-1' })).code).toBe('NotFound');
27
+ });
28
+ t.it('completion carries the output; failure carries an error code', async () => {
29
+ const h = await setup();
30
+ const ok = await h.engine.start(h.workflow, {}, ctx('t-1', 'ok'));
31
+ const bad = await h.engine.start(h.workflow, {}, ctx('t-1', 'bad'));
32
+ await h.finish(ok.runId, { output: { total: 42 } });
33
+ await h.finish(bad.runId, { failed: true });
34
+ const done = await h.engine.status(ok.runId, { tenantId: 't-1' });
35
+ t.expect([done.state, done.output]).toEqual([
36
+ 'completed',
37
+ { total: 42 },
38
+ ]);
39
+ const failed = await h.engine.status(bad.runId, { tenantId: 't-1' });
40
+ t.expect(failed.state).toBe('failed');
41
+ t.expect(typeof failed.code === 'string' && failed.code !== 'NotFound').toBe(true);
42
+ });
43
+ t.it('reports each terminal run once, with its tenant', async () => {
44
+ const h = await setup();
45
+ const seen = [];
46
+ h.engine.onFinished((r) => seen.push(r));
47
+ const run = await h.engine.start(h.workflow, {}, ctx('t-9', 'once'));
48
+ await h.finish(run.runId, { output: 'x' });
49
+ await h.finish(run.runId, { output: 'x' });
50
+ t.expect(seen.map((r) => [r.runId, r.state, r.tenantId])).toEqual([
51
+ [run.runId, 'completed', 't-9'],
52
+ ]);
53
+ });
54
+ });
55
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@agentropy/testkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Agentropy testkit: offline fakes and reusable conformance suites for provider authors.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/bassemZohdy/agentropy.git",
9
+ "directory": "packages/testkit"
10
+ },
11
+ "homepage": "https://github.com/bassemZohdy/agentropy/tree/main/packages/testkit#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/bassemZohdy/agentropy/issues"
14
+ },
15
+ "keywords": [
16
+ "agents",
17
+ "testing",
18
+ "fakes",
19
+ "conformance",
20
+ "agentropy"
21
+ ],
22
+ "engines": {
23
+ "node": ">=24"
24
+ },
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "LICENSE"
35
+ ],
36
+ "dependencies": {
37
+ "@agentropy/core": "0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@a2a-js/sdk": "1.3.0",
41
+ "@electric-sql/pglite": "0.5.16",
42
+ "@opentelemetry/api": "1.10.0",
43
+ "@opentelemetry/sdk-metrics": "3.1.1",
44
+ "@opentelemetry/sdk-trace": "3.1.1",
45
+ "@types/pg": "^8.23.1",
46
+ "pg": "^8.23.1"
47
+ },
48
+ "scripts": {
49
+ "build": "tsc -b",
50
+ "typecheck": "tsc --noEmit"
51
+ }
6
52
  }