@niwa-labs/commitments 0.0.0-stage → 0.0.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 +21 -0
- package/README.md +27 -2
- package/package.json +32 -4
- package/src/cockpit/actions.ts +37 -0
- package/src/cockpit/cards.ts +45 -0
- package/src/cockpit/index.tsx +19 -0
- package/src/cockpit/page.tsx +68 -0
- package/src/index.ts +478 -0
- package/src/records.ts +232 -0
- package/test/cockpit-actions.test.ts +37 -0
- package/test/cockpit-cards.test.ts +41 -0
- package/test/commitments.test.ts +443 -0
- package/test/queries.test.ts +41 -0
- package/test/replay.test.ts +83 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
// Commitments on a real host: a promise is made, comes due at its deadline into an agent's inbox,
|
|
2
|
+
// and is done, missed or cancelled. A promise for the owner stands only on his own word.
|
|
3
|
+
|
|
4
|
+
import { afterEach, expect, test } from "bun:test";
|
|
5
|
+
|
|
6
|
+
import { action, actionRef, grant, principalOf, record } from "@niwa-labs/core";
|
|
7
|
+
import type { Address, Caller, StoredRecord } from "@niwa-labs/core";
|
|
8
|
+
import type { Plugin } from "@niwa-labs/plugin";
|
|
9
|
+
import { plugin } from "@niwa-labs/plugin";
|
|
10
|
+
import { agentNotify } from "@niwa-labs/agent/records";
|
|
11
|
+
import { requestAnswer, requestAsk, requestResolve } from "@niwa-labs/requests/records";
|
|
12
|
+
import { baseStack, connect, connectAsOwner, createNiwa, eventually, tempHome, testClock } from "@niwa-labs/testing";
|
|
13
|
+
import type { NiwaApi, TestClock } from "@niwa-labs/testing";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
|
|
16
|
+
import { commitments } from "../src/index.ts";
|
|
17
|
+
import {
|
|
18
|
+
commitmentBriefing,
|
|
19
|
+
commitmentCancel,
|
|
20
|
+
commitmentDone,
|
|
21
|
+
commitmentGet,
|
|
22
|
+
commitmentList,
|
|
23
|
+
commitmentMake,
|
|
24
|
+
} from "../src/records.ts";
|
|
25
|
+
|
|
26
|
+
const START = 1_700_000_000_000;
|
|
27
|
+
const HOUR = 3_600_000;
|
|
28
|
+
const GRACE = 2 * HOUR;
|
|
29
|
+
|
|
30
|
+
/** What the stub of the agents plugin was told: the agent and the text of each fact. */
|
|
31
|
+
type Told = { agent: string; text: string };
|
|
32
|
+
|
|
33
|
+
/** The agents plugin, as far as commitments use it: a fact told to an agent lands in its inbox. */
|
|
34
|
+
function agentsStub(told: Told[]) {
|
|
35
|
+
return plugin("agents", (api) => {
|
|
36
|
+
api.action(
|
|
37
|
+
action(agentNotify, {
|
|
38
|
+
recovery: "repeat",
|
|
39
|
+
effect: "record",
|
|
40
|
+
world: "niwa",
|
|
41
|
+
run: async (input) => {
|
|
42
|
+
if (input.agent === "ghost") throw new Error("no agent is called ghost");
|
|
43
|
+
told.push({ agent: input.agent, text: input.text });
|
|
44
|
+
return { turn: `fact-${(told.length + 0xa00000).toString(16)}` };
|
|
45
|
+
},
|
|
46
|
+
}),
|
|
47
|
+
);
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A record the owner writes himself: a sentence of his, as a message would be. */
|
|
52
|
+
const Said = record("test.said", z.object({ text: z.string() }));
|
|
53
|
+
const say = actionRef("test.say", { description: "Write a sentence.", input: z.object({ text: z.string() }), output: z.object({ record: z.string() }) });
|
|
54
|
+
/** A turn some plugin says the owner wrote, as the agents plugin does for his messages. */
|
|
55
|
+
const Turn = record("test.turn", z.object({ author: z.object({ kind: z.string() }).loose(), text: z.string() }));
|
|
56
|
+
/** A record of the owner's that says nothing in words. */
|
|
57
|
+
const Nod = record("test.nod", z.object({}));
|
|
58
|
+
const nod = actionRef("test.nod", { description: "Nod.", input: z.object({}), output: z.object({ record: z.string() }) });
|
|
59
|
+
const words = plugin("words", (api) => {
|
|
60
|
+
api.declare(Said, Turn, Nod);
|
|
61
|
+
api.action(action(nod, { recovery: "repeat", effect: "record", world: "niwa", run: async (_input, ctx) => ({ record: String((await ctx.emit(Nod, {})).id) }) }));
|
|
62
|
+
api.action(
|
|
63
|
+
action(say, {
|
|
64
|
+
recovery: "repeat",
|
|
65
|
+
effect: "record",
|
|
66
|
+
world: "niwa",
|
|
67
|
+
run: async (input, ctx) => ({ record: String((await ctx.emit(Said, input)).id) }),
|
|
68
|
+
}),
|
|
69
|
+
);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/** The messages module's own actions, as far as a test sends a message through them. */
|
|
73
|
+
const Place = z.object({ kind: z.string(), id: z.string().optional() }).loose();
|
|
74
|
+
const letter = { to: Place, from: Place.optional(), body: z.object({ type: z.literal("update"), text: z.string() }) };
|
|
75
|
+
const messageSendRef = actionRef("message.send", { description: "Send a message.", input: z.object(letter), output: z.object({}).loose() });
|
|
76
|
+
const messageReceiveRef = actionRef("message.receive", { description: "Receive a message.", input: z.object(letter), output: z.object({}).loose() });
|
|
77
|
+
|
|
78
|
+
/** The owner is the owner; a session `rin` speaks as the agent `rin`. */
|
|
79
|
+
function bind(caller: Caller): Address | undefined {
|
|
80
|
+
if (caller.kind !== "client") return undefined;
|
|
81
|
+
if (caller.principal?.kind === "owner") return { kind: "owner" };
|
|
82
|
+
// Built id first: an address is the same address whatever order its keys come in.
|
|
83
|
+
if (caller.principal?.kind === "session") return { id: String(caller.principal.id), kind: "agent" };
|
|
84
|
+
return { kind: "client", id: caller.id };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface World {
|
|
88
|
+
readonly host: ReturnType<typeof createNiwa>;
|
|
89
|
+
readonly clock: TestClock;
|
|
90
|
+
readonly told: Told[];
|
|
91
|
+
readonly owner: NiwaApi;
|
|
92
|
+
readonly rin: NiwaApi;
|
|
93
|
+
readonly records: (type: string) => Promise<StoredRecord[]>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const cleanups: Array<() => Promise<void>> = [];
|
|
97
|
+
afterEach(async () => {
|
|
98
|
+
for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
async function world(extra: readonly Plugin[] = []): Promise<World> {
|
|
102
|
+
const home = await tempHome();
|
|
103
|
+
const clock = testClock(START);
|
|
104
|
+
const host = createNiwa({ home: home.path, clock });
|
|
105
|
+
const told: Told[] = [];
|
|
106
|
+
cleanups.push(() => home.cleanup());
|
|
107
|
+
cleanups.push(() => host.close());
|
|
108
|
+
host.use(...baseStack().plugins, ...extra, agentsStub(told), words, commitments({ messages: { bind }, graceMs: GRACE }));
|
|
109
|
+
await host.serve();
|
|
110
|
+
const owner = await connectAsOwner(home.path);
|
|
111
|
+
cleanups.push(() => owner.close());
|
|
112
|
+
const token = host.issueToken(principalOf("session", "rin"), { grant: grant(["commitment.*", "test.say", "emit:test.turn", "message.send"]) });
|
|
113
|
+
const rin = await connect({ home: home.path, id: "session:rin", token });
|
|
114
|
+
cleanups.push(() => rin.close());
|
|
115
|
+
const records = async (type: string) => (await host.records.read()).filter((row) => row.type === type);
|
|
116
|
+
return { host, clock, told, owner, rin, records };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
test("an agent's own promise comes due into its inbox, and is missed when not done after the grace", async () => {
|
|
120
|
+
const w = await world();
|
|
121
|
+
const made = await w.rin.call(commitmentMake, { text: "Check the nightly build", to: "rin", due: START + HOUR });
|
|
122
|
+
expect(made.status).toBe("open");
|
|
123
|
+
const card = await w.owner.call(commitmentGet, { id: made.id });
|
|
124
|
+
expect(card).toMatchObject({ status: "open", party: "self", by: { kind: "agent", id: "rin" }, basis: { kind: "own" } });
|
|
125
|
+
|
|
126
|
+
await w.clock.advance(HOUR);
|
|
127
|
+
await eventually(async () => (await w.records("commitment.delivered")).length === 1);
|
|
128
|
+
expect(w.told).toEqual([{ agent: "rin", text: expect.stringContaining("Check the nightly build") }]);
|
|
129
|
+
expect((await w.owner.call(commitmentGet, { id: made.id })).status).toBe("due");
|
|
130
|
+
|
|
131
|
+
await w.clock.advance(GRACE);
|
|
132
|
+
await eventually(async () => (await w.records("commitment.missed")).length === 1);
|
|
133
|
+
expect((await w.owner.call(commitmentGet, { id: made.id })).status).toBe("missed");
|
|
134
|
+
expect(w.told).toHaveLength(2);
|
|
135
|
+
expect(w.told[1]?.text).toContain("missed");
|
|
136
|
+
expect(await w.rin.call(commitmentDone, { id: made.id })).toMatchObject({ status: "kept-late" });
|
|
137
|
+
expect(await w.owner.call(commitmentGet, { id: made.id })).toMatchObject({ status: "kept-late" });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("a promise done before its deadline is not delivered", async () => {
|
|
141
|
+
const w = await world();
|
|
142
|
+
const made = await w.rin.call(commitmentMake, { text: "Send the summary", to: "rin", due: START + HOUR });
|
|
143
|
+
expect(await w.rin.call(commitmentDone, { id: made.id, note: "sent" })).toEqual({ id: made.id, status: "kept" });
|
|
144
|
+
await w.clock.advance(HOUR + GRACE);
|
|
145
|
+
await eventually(async () => (await w.host.records.read()).filter((row) => row.type === "timer.slept").length >= 1);
|
|
146
|
+
// The wake came and found the promise kept: nothing reaches the inbox.
|
|
147
|
+
await Bun.sleep(50);
|
|
148
|
+
expect(await w.records("commitment.delivered")).toHaveLength(0);
|
|
149
|
+
expect(await w.records("commitment.missed")).toHaveLength(0);
|
|
150
|
+
expect(w.told).toEqual([]);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test("an agent's promise for the owner without his word is only proposed, and stands once he confirms", async () => {
|
|
154
|
+
const w = await world();
|
|
155
|
+
const proposed = await w.rin.call(commitmentMake, { text: "Reply to the landlord", to: "rin", party: "owner", due: START + 24 * HOUR });
|
|
156
|
+
expect(proposed.status).toBe("proposed");
|
|
157
|
+
expect(await w.records("commitment.made")).toHaveLength(0);
|
|
158
|
+
|
|
159
|
+
await eventually(async () => (await w.records("request.created")).length === 1);
|
|
160
|
+
const [asked] = await w.records("request.created");
|
|
161
|
+
const request = asked?.data as { id: string; to: Address; question: string; input: { kind: string; title: string } };
|
|
162
|
+
expect(request.to).toEqual({ kind: "owner" });
|
|
163
|
+
expect(request.question).toBe("commitment.confirm");
|
|
164
|
+
expect(request.input.kind).toBe("confirm");
|
|
165
|
+
expect(request.input.title).toContain("Reply to the landlord");
|
|
166
|
+
|
|
167
|
+
await w.owner.call(requestAnswer, { id: request.id, answer: { ids: ["yes"] } });
|
|
168
|
+
await eventually(async () => (await w.records("commitment.made")).length === 1);
|
|
169
|
+
const card = await w.owner.call(commitmentGet, { id: proposed.id });
|
|
170
|
+
expect(card).toMatchObject({ status: "open", party: "owner", basis: { kind: "owner-confirmed", request: request.id } });
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("a proposed promise the owner does not confirm is declined and never comes due", async () => {
|
|
174
|
+
const w = await world();
|
|
175
|
+
const proposed = await w.rin.call(commitmentMake, { text: "Pay the bill", to: "rin", party: "owner", due: START + HOUR });
|
|
176
|
+
await eventually(async () => (await w.records("request.created")).length === 1);
|
|
177
|
+
const id = ((await w.records("request.created"))[0]?.data as { id: string }).id;
|
|
178
|
+
await w.owner.call(requestAnswer, { id, answer: { ids: ["no"] } });
|
|
179
|
+
await eventually(async () => (await w.records("commitment.declined")).length === 1);
|
|
180
|
+
expect((await w.owner.call(commitmentGet, { id: proposed.id })).status).toBe("declined");
|
|
181
|
+
await w.clock.advance(HOUR + GRACE);
|
|
182
|
+
await Bun.sleep(50);
|
|
183
|
+
expect(await w.records("commitment.made")).toHaveLength(0);
|
|
184
|
+
expect(w.told).toEqual([]);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
test("the proposals wait for the owner side by side", async () => {
|
|
188
|
+
const w = await world();
|
|
189
|
+
const first = await w.rin.call(commitmentMake, { text: "Book the flight", to: "rin", party: "owner" });
|
|
190
|
+
const second = await w.rin.call(commitmentMake, { text: "Renew the passport", to: "rin", party: "owner" });
|
|
191
|
+
await eventually(async () => (await w.records("request.created")).length === 2);
|
|
192
|
+
const asked = (await w.records("request.created")).map((row) => row.data as { id: string; input: { title: string } });
|
|
193
|
+
const renew = asked.find((one) => one.input.title.includes("passport"));
|
|
194
|
+
await w.owner.call(requestAnswer, { id: renew?.id ?? "", answer: { ids: ["yes"] } });
|
|
195
|
+
await eventually(async () => (await w.records("commitment.made")).length === 1);
|
|
196
|
+
expect((await w.owner.call(commitmentGet, { id: second.id })).status).toBe("open");
|
|
197
|
+
expect((await w.owner.call(commitmentGet, { id: first.id })).status).toBe("proposed");
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("a promise for the owner stands on a record of his words, and not on someone else's", async () => {
|
|
201
|
+
const w = await world();
|
|
202
|
+
const his = await w.owner.call(say, { text: "Remind me to call mum on Sunday" });
|
|
203
|
+
const made = await w.rin.call(commitmentMake, {
|
|
204
|
+
text: "Call mum",
|
|
205
|
+
to: "rin",
|
|
206
|
+
party: "owner",
|
|
207
|
+
basis: { kind: "owner-words", record: his.record },
|
|
208
|
+
});
|
|
209
|
+
expect(made.status).toBe("open");
|
|
210
|
+
expect(await w.owner.call(commitmentGet, { id: made.id })).toMatchObject({ basis: { kind: "owner-words", record: his.record } });
|
|
211
|
+
|
|
212
|
+
const hers = await w.rin.call(say, { text: "Remind me to sell the car" });
|
|
213
|
+
const forged = w.rin.call(commitmentMake, {
|
|
214
|
+
text: "Sell the car",
|
|
215
|
+
to: "rin",
|
|
216
|
+
party: "owner",
|
|
217
|
+
basis: { kind: "owner-words", record: hers.record },
|
|
218
|
+
});
|
|
219
|
+
await expect(forged).rejects.toThrow(/owner/);
|
|
220
|
+
const missing = w.rin.call(commitmentMake, { text: "Sell the car", to: "rin", party: "owner", basis: { kind: "owner-words", record: "nowhere" } });
|
|
221
|
+
await expect(missing).rejects.toThrow(/owner/);
|
|
222
|
+
expect(await w.records("commitment.made")).toHaveLength(1);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
test("his words stand for the promise as he worded it, not for terms an agent made of them", async () => {
|
|
226
|
+
const w = await world();
|
|
227
|
+
const his = await w.owner.call(say, { text: "I will check the report." });
|
|
228
|
+
const basis = { kind: "owner-words" as const, record: his.record };
|
|
229
|
+
// A deadline cannot be read out of words: the one an agent chose is put to him.
|
|
230
|
+
const dated = await w.rin.call(commitmentMake, { text: "Check the report", to: "rin", party: "owner", due: START + 6 * HOUR, basis });
|
|
231
|
+
expect(dated.status).toBe("proposed");
|
|
232
|
+
// Nor is a promise he did not word: it is put to him as it now reads.
|
|
233
|
+
const reworded = await w.rin.call(commitmentMake, { text: "Finish the report today", to: "rin", party: "owner", basis });
|
|
234
|
+
expect(reworded.status).toBe("proposed");
|
|
235
|
+
expect(await w.records("commitment.made")).toHaveLength(0);
|
|
236
|
+
await eventually(async () => (await w.records("request.created")).length === 2);
|
|
237
|
+
// What he worded, as he worded it, stands at once.
|
|
238
|
+
const quoted = await w.rin.call(commitmentMake, { text: "check the REPORT", to: "rin", party: "owner", basis });
|
|
239
|
+
expect(quoted.status).toBe("open");
|
|
240
|
+
expect(await w.owner.call(commitmentGet, { id: dated.id })).toMatchObject({ status: "proposed" });
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
test("a record counts as the owner's words only when he wrote it, or a plugin says he did, and it has words", async () => {
|
|
244
|
+
const w = await world();
|
|
245
|
+
const relayed = await w.host.emit(Turn, { author: { kind: "owner" }, text: "Remind me to renew the domain" });
|
|
246
|
+
const made = await w.rin.call(commitmentMake, { text: "Renew the domain", to: "rin", party: "owner", basis: { kind: "owner-words", record: String(relayed.id) } });
|
|
247
|
+
expect(made.status).toBe("open");
|
|
248
|
+
|
|
249
|
+
// A client that may write the record itself is its author, whatever the record says.
|
|
250
|
+
const claimed = await w.rin.emit(Turn, { author: { kind: "owner" }, text: "Remind me to buy a boat" });
|
|
251
|
+
const forged = w.rin.call(commitmentMake, { text: "Buy a boat", to: "rin", party: "owner", basis: { kind: "owner-words", record: String(claimed.id) } });
|
|
252
|
+
await expect(forged).rejects.toThrow(/owner/);
|
|
253
|
+
|
|
254
|
+
const nodded = await w.owner.call(nod, {});
|
|
255
|
+
const wordless = w.rin.call(commitmentMake, { text: "Sell the boat", to: "rin", party: "owner", basis: { kind: "owner-words", record: nodded.record } });
|
|
256
|
+
await expect(wordless).rejects.toThrow(/owner/);
|
|
257
|
+
expect(await w.records("commitment.made")).toHaveLength(1);
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test("a delivery that fails holds up no other commitment", async () => {
|
|
261
|
+
const w = await world();
|
|
262
|
+
const lost = await w.rin.call(commitmentMake, { text: "Tell the ghost", to: "ghost", due: START + HOUR });
|
|
263
|
+
const mine = await w.rin.call(commitmentMake, { text: "Check the backups", to: "rin", due: START + 2 * HOUR });
|
|
264
|
+
await w.clock.advance(2 * HOUR);
|
|
265
|
+
await eventually(async () => (await w.owner.call(commitmentGet, { id: mine.id })).status === "due");
|
|
266
|
+
expect(w.told).toEqual([{ agent: "rin", text: expect.stringContaining("Check the backups") }]);
|
|
267
|
+
await w.clock.advance(GRACE);
|
|
268
|
+
await eventually(async () => (await w.owner.call(commitmentGet, { id: mine.id })).status === "missed");
|
|
269
|
+
// The one whose inbox could not be reached was never delivered, and still comes to its end.
|
|
270
|
+
expect((await w.owner.call(commitmentGet, { id: lost.id })).status).toBe("missed");
|
|
271
|
+
expect((await w.records("commitment.delivered")).map((row) => (row.data as { id: string }).id)).toEqual([mine.id]);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
test("the owner's own promise stands at once", async () => {
|
|
275
|
+
const w = await world();
|
|
276
|
+
const made = await w.owner.call(commitmentMake, { text: "File the taxes", to: "rin", party: "owner", due: START + HOUR });
|
|
277
|
+
expect(made.status).toBe("open");
|
|
278
|
+
expect(await w.owner.call(commitmentGet, { id: made.id })).toMatchObject({ by: { kind: "owner" }, basis: { kind: "owner" } });
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
test("a promise is made by an address: a caller that speaks as none is refused", async () => {
|
|
282
|
+
const w = await world();
|
|
283
|
+
await expect(w.host.call(commitmentMake, { text: "Anything", to: "rin" })).rejects.toThrow(/address/);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test("an agent cancels its own promise, not one made for the owner; the owner cancels any", async () => {
|
|
287
|
+
const w = await world();
|
|
288
|
+
const own = await w.rin.call(commitmentMake, { text: "Tidy the notes", to: "rin", due: START + HOUR });
|
|
289
|
+
const his = await w.owner.call(commitmentMake, { text: "Renew the lease", to: "rin", party: "owner", due: START + HOUR });
|
|
290
|
+
|
|
291
|
+
expect(await w.rin.call(commitmentCancel, { id: own.id, reason: "not needed" })).toEqual({ id: own.id, status: "cancelled" });
|
|
292
|
+
await expect(w.rin.call(commitmentCancel, { id: his.id })).rejects.toThrow(/owner/);
|
|
293
|
+
expect(await w.owner.call(commitmentCancel, { id: his.id })).toEqual({ id: his.id, status: "cancelled" });
|
|
294
|
+
await expect(w.owner.call(commitmentCancel, { id: his.id })).rejects.toThrow(/cancelled/);
|
|
295
|
+
await expect(w.rin.call(commitmentDone, { id: his.id })).rejects.toThrow(/cancelled/);
|
|
296
|
+
|
|
297
|
+
await w.clock.advance(HOUR + GRACE);
|
|
298
|
+
await Bun.sleep(50);
|
|
299
|
+
expect(w.told).toEqual([]);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
test("cancelling a proposal withdraws the question put to the owner", async () => {
|
|
303
|
+
const w = await world();
|
|
304
|
+
const proposed = await w.rin.call(commitmentMake, { text: "Call the bank", to: "rin", party: "owner" });
|
|
305
|
+
await eventually(async () => (await w.records("request.created")).length === 1);
|
|
306
|
+
await w.rin.call(commitmentCancel, { id: proposed.id });
|
|
307
|
+
await eventually(async () => (await w.records("request.cancelled")).length === 1);
|
|
308
|
+
const id = ((await w.records("request.created"))[0]?.data as { id: string }).id;
|
|
309
|
+
expect((await w.records("request.cancelled"))[0]?.data).toMatchObject({ id });
|
|
310
|
+
expect((await w.owner.call(commitmentGet, { id: proposed.id })).status).toBe("cancelled");
|
|
311
|
+
// The author took it back: the owner did not refuse it.
|
|
312
|
+
await Bun.sleep(50);
|
|
313
|
+
expect(await w.records("commitment.declined")).toHaveLength(0);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
test("a question asked after its proposal was cancelled is withdrawn at once", async () => {
|
|
317
|
+
// The ask is held until the proposal is cancelled, so the question is created after the cancel.
|
|
318
|
+
let release = () => {};
|
|
319
|
+
const held = new Promise<void>((resolve) => (release = resolve));
|
|
320
|
+
let asking = false;
|
|
321
|
+
const hold = plugin("hold", (api) => {
|
|
322
|
+
api.adjust(requestAsk, async (input) => {
|
|
323
|
+
asking = true;
|
|
324
|
+
await held;
|
|
325
|
+
return input;
|
|
326
|
+
});
|
|
327
|
+
});
|
|
328
|
+
const w = await world([hold]);
|
|
329
|
+
const proposed = await w.rin.call(commitmentMake, { text: "Call the plumber", to: "rin", party: "owner" });
|
|
330
|
+
await eventually(() => asking);
|
|
331
|
+
await w.rin.call(commitmentCancel, { id: proposed.id });
|
|
332
|
+
release();
|
|
333
|
+
await eventually(async () => (await w.records("request.cancelled")).length === 1);
|
|
334
|
+
const id = ((await w.records("request.created"))[0]?.data as { id: string }).id;
|
|
335
|
+
expect((await w.records("request.cancelled"))[0]?.data).toMatchObject({ id });
|
|
336
|
+
expect(await w.records("commitment.made")).toHaveLength(0);
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
test("only the one who made a promise, or the owner, says it is done", async () => {
|
|
340
|
+
const w = await world();
|
|
341
|
+
const his = await w.owner.call(commitmentMake, { text: "Water the plants", to: "rin" });
|
|
342
|
+
await expect(w.rin.call(commitmentDone, { id: his.id })).rejects.toThrow(/owner/);
|
|
343
|
+
expect(await w.owner.call(commitmentDone, { id: his.id })).toEqual({ id: his.id, status: "kept" });
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
test("the list and the briefing show where each promise stands", async () => {
|
|
347
|
+
const w = await world();
|
|
348
|
+
const late = await w.rin.call(commitmentMake, { text: "Write the report", to: "rin", due: START + 3 * HOUR });
|
|
349
|
+
const kept = await w.rin.call(commitmentMake, { text: "Fix the typo", to: "rin" });
|
|
350
|
+
await w.rin.call(commitmentDone, { id: kept.id });
|
|
351
|
+
await w.rin.call(commitmentMake, { text: "Ask the owner about Friday", to: "rin", party: "owner" });
|
|
352
|
+
|
|
353
|
+
const all = await w.owner.call(commitmentList, {});
|
|
354
|
+
expect(all.items[0]).toMatchObject({ by: { kind: "agent", id: "rin" }, canCancel: true });
|
|
355
|
+
expect(all.items[1]).toMatchObject({ canCancel: false });
|
|
356
|
+
expect(all.items.map((item): string[] => [item.description, item.status])).toEqual([
|
|
357
|
+
["Write the report", "open"],
|
|
358
|
+
["Fix the typo", "kept"],
|
|
359
|
+
["Ask the owner about Friday", "proposed"],
|
|
360
|
+
]);
|
|
361
|
+
expect((await w.owner.call(commitmentList, { status: "open" })).items.map((item) => item.id)).toEqual([late.id]);
|
|
362
|
+
|
|
363
|
+
const briefing = await w.owner.call(commitmentBriefing, { agent: "rin" });
|
|
364
|
+
expect(briefing.text).toContain("Write the report");
|
|
365
|
+
expect(briefing.text).toContain("Ask the owner about Friday");
|
|
366
|
+
expect(briefing.text).not.toContain("Fix the typo");
|
|
367
|
+
expect((await w.owner.call(commitmentBriefing, { agent: "someone-else" })).text).toBe("");
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
test("an answer a resolver found for the owner confirms nothing", async () => {
|
|
371
|
+
const w = await world();
|
|
372
|
+
const proposed = await w.rin.call(commitmentMake, { text: "Wire the deposit", to: "rin", party: "owner", due: START + HOUR });
|
|
373
|
+
await eventually(async () => (await w.records("request.created")).length === 1);
|
|
374
|
+
const id = ((await w.records("request.created"))[0]?.data as { id: string }).id;
|
|
375
|
+
expect(await w.host.call(requestResolve, { id, answer: { ids: ["yes"] }, info: { how: "recalled" } })).toEqual({ answered: false });
|
|
376
|
+
expect((await w.owner.call(commitmentGet, { id: proposed.id })).status).toBe("proposed");
|
|
377
|
+
await w.owner.call(requestAnswer, { id, answer: { ids: ["yes"] } });
|
|
378
|
+
await eventually(async () => (await w.records("commitment.made")).length === 1);
|
|
379
|
+
expect((await w.owner.call(commitmentGet, { id: proposed.id })).basis).toMatchObject({ kind: "owner-confirmed", request: id });
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
test("a message he wrote is his words, whether it was sent by him or came in as his", async () => {
|
|
383
|
+
const w = await world();
|
|
384
|
+
const to = { kind: "agent", id: "rin" } as const;
|
|
385
|
+
await w.owner.call(messageSendRef, { to, body: { type: "update", text: "Please renew the lease." } });
|
|
386
|
+
await w.host.call(messageReceiveRef, { from: { kind: "owner" }, to, body: { type: "update", text: "Also ring the plumber" } });
|
|
387
|
+
const [sent] = await w.records("message.sent");
|
|
388
|
+
const [received] = await w.records("message.received");
|
|
389
|
+
expect(sent).toBeDefined();
|
|
390
|
+
expect(received).toBeDefined();
|
|
391
|
+
const lease = await w.rin.call(commitmentMake, { text: "renew the lease", to: "rin", party: "owner", basis: { kind: "owner-words", record: String(sent?.id) } });
|
|
392
|
+
const plumber = await w.rin.call(commitmentMake, { text: "ring the plumber", to: "rin", party: "owner", basis: { kind: "owner-words", record: String(received?.id) } });
|
|
393
|
+
expect([lease.status, plumber.status]).toEqual(["open", "open"]);
|
|
394
|
+
|
|
395
|
+
// A message an agent sent is the agent's word, to whoever it is addressed.
|
|
396
|
+
await w.rin.call(messageSendRef, { to: { kind: "owner" }, body: { type: "update", text: "Remind me to sell the car." } });
|
|
397
|
+
const [, agents] = await w.records("message.sent");
|
|
398
|
+
const forged = w.rin.call(commitmentMake, { text: "sell the car", to: "rin", party: "owner", basis: { kind: "owner-words", record: String(agents?.id) } });
|
|
399
|
+
await expect(forged).rejects.toThrow(/owner/);
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
test("a commitment done while its deadline is being told is not delivered, and not missed", async () => {
|
|
403
|
+
// The inbox is slow: the owner marks the promise done while the wake is still telling the agent.
|
|
404
|
+
let release = () => {};
|
|
405
|
+
const held = new Promise<void>((resolve) => (release = resolve));
|
|
406
|
+
let telling = false;
|
|
407
|
+
const slow = plugin("slow", (api) => {
|
|
408
|
+
api.adjust(agentNotify, async (input) => {
|
|
409
|
+
telling = true;
|
|
410
|
+
await held;
|
|
411
|
+
return input;
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
const w = await world([slow]);
|
|
415
|
+
const made = await w.rin.call(commitmentMake, { text: "Send the invoice", to: "rin", due: START + HOUR });
|
|
416
|
+
await w.clock.advance(HOUR);
|
|
417
|
+
await eventually(() => telling);
|
|
418
|
+
await w.owner.call(commitmentDone, { id: made.id });
|
|
419
|
+
release();
|
|
420
|
+
await w.clock.advance(GRACE);
|
|
421
|
+
await Bun.sleep(100);
|
|
422
|
+
expect(await w.records("commitment.delivered")).toHaveLength(0);
|
|
423
|
+
expect(await w.records("commitment.missed")).toHaveLength(0);
|
|
424
|
+
expect((await w.owner.call(commitmentGet, { id: made.id })).status).toBe("kept");
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
test("a deadline a date cannot hold is refused, and so is a grace that ends before it begins", async () => {
|
|
428
|
+
const w = await world();
|
|
429
|
+
await expect(w.rin.call(commitmentMake, { text: "Never", to: "rin", due: 8_640_000_000_000_001 })).rejects.toThrow();
|
|
430
|
+
// The grace after the deadline is past the last moment too.
|
|
431
|
+
await expect(w.rin.call(commitmentMake, { text: "Nearly never", to: "rin", due: 8_640_000_000_000_000 - HOUR })).rejects.toThrow(/last moment/);
|
|
432
|
+
expect(() => commitments({ graceMs: -1 })).toThrow(/graceMs/);
|
|
433
|
+
expect(() => commitments({ graceMs: Number.NaN })).toThrow(/graceMs/);
|
|
434
|
+
expect(await w.records("commitment.proposed")).toHaveLength(0);
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
test("competing completion and cancellation leave exactly one ending", async () => {
|
|
438
|
+
const w = await world();
|
|
439
|
+
const { id } = await w.rin.call(commitmentMake, { text: "Write the report", to: "rin" });
|
|
440
|
+
const result = await Promise.allSettled([w.rin.call(commitmentDone, { id }), w.owner.call(commitmentCancel, { id })]);
|
|
441
|
+
expect(result.filter(one => one.status === "fulfilled")).toHaveLength(1);
|
|
442
|
+
expect([...(await w.records("commitment.kept")), ...(await w.records("commitment.cancelled"))]).toHaveLength(1);
|
|
443
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// The query builders of the commitment records: what a script waits for when it waits for one promise.
|
|
2
|
+
|
|
3
|
+
import { expect, test } from "bun:test";
|
|
4
|
+
|
|
5
|
+
import { resolveQuery } from "@niwa-labs/core";
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
CommitmentCancelled,
|
|
9
|
+
CommitmentId,
|
|
10
|
+
CommitmentDeclined,
|
|
11
|
+
CommitmentDelivered,
|
|
12
|
+
CommitmentKept,
|
|
13
|
+
CommitmentMade,
|
|
14
|
+
CommitmentMissed,
|
|
15
|
+
CommitmentProposed,
|
|
16
|
+
commitmentCancelled,
|
|
17
|
+
commitmentDeclined,
|
|
18
|
+
commitmentDelivered,
|
|
19
|
+
commitmentKept,
|
|
20
|
+
commitmentMade,
|
|
21
|
+
commitmentMissed,
|
|
22
|
+
commitmentProposed,
|
|
23
|
+
} from "../src/records.ts";
|
|
24
|
+
|
|
25
|
+
const id = CommitmentId.parse("com-3fa9c2");
|
|
26
|
+
|
|
27
|
+
test("each record of a commitment is a query of its type, filtered on the commitment", () => {
|
|
28
|
+
expect(commitmentMade(id)).toEqual({ types: [CommitmentMade], filter: { id } });
|
|
29
|
+
expect(commitmentProposed(id)).toEqual({ types: [CommitmentProposed], filter: { id } });
|
|
30
|
+
expect(commitmentDeclined(id)).toEqual({ types: [CommitmentDeclined], filter: { id } });
|
|
31
|
+
expect(commitmentDelivered(id)).toEqual({ types: [CommitmentDelivered], filter: { id } });
|
|
32
|
+
expect(commitmentKept(id)).toEqual({ types: [CommitmentKept], filter: { id } });
|
|
33
|
+
expect(commitmentMissed(id)).toEqual({ types: [CommitmentMissed], filter: { id } });
|
|
34
|
+
expect(commitmentCancelled(id)).toEqual({ types: [CommitmentCancelled], filter: { id } });
|
|
35
|
+
expect(resolveQuery(commitmentKept(id)).types?.map(String)).toEqual(["commitment.kept"]);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("a text that is not the id of a commitment is refused when the query is made", () => {
|
|
39
|
+
expect(() => commitmentKept("task-3fa9c2")).toThrow();
|
|
40
|
+
expect(() => commitmentMissed("")).toThrow();
|
|
41
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// A done or a cancel made again under its own operation, after the host stopped before it kept the
|
|
2
|
+
// answer, answers what the first call answered; only another operation meets a commitment that ended.
|
|
3
|
+
|
|
4
|
+
import { expect, test } from "bun:test";
|
|
5
|
+
|
|
6
|
+
import { recordId } from "@niwa-labs/core";
|
|
7
|
+
import type { Action, ActionContext, Address, Caller, JournalReader, NewRecord, OperationId, RecordTypeName, StoredRecord } from "@niwa-labs/core";
|
|
8
|
+
import type { PluginApi } from "@niwa-labs/plugin";
|
|
9
|
+
|
|
10
|
+
import { commitments } from "../src/index.ts";
|
|
11
|
+
|
|
12
|
+
/** A journal in memory: records in commit order, written once by id. */
|
|
13
|
+
class MemoryJournal {
|
|
14
|
+
readonly rows: StoredRecord[] = [];
|
|
15
|
+
|
|
16
|
+
append(record: NewRecord): StoredRecord {
|
|
17
|
+
const same = this.rows.find((row) => row.id === record.id);
|
|
18
|
+
if (same !== undefined) return same;
|
|
19
|
+
const stored = { ...record, seq: this.rows.length + 1, at: 1_000_000 } as unknown as StoredRecord;
|
|
20
|
+
this.rows.push(stored);
|
|
21
|
+
return stored;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
reader(): JournalReader {
|
|
25
|
+
return {
|
|
26
|
+
get: (id: string) => this.rows.find((row) => row.id === id),
|
|
27
|
+
since: (from: number, types?: RecordTypeName[]) => this.rows.filter((row) => row.seq > from && (types === undefined || types.includes(row.type as RecordTypeName))),
|
|
28
|
+
} as unknown as JournalReader;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const rin: Caller = { kind: "client", id: "session:rin", principal: { kind: "session", id: "rin" } } as unknown as Caller;
|
|
33
|
+
const bind = (caller: Caller): Address | undefined => (caller.kind === "client" && caller.principal?.kind === "session" ? { kind: "agent", id: String(caller.principal.id) } : undefined);
|
|
34
|
+
|
|
35
|
+
/** The actions of the plugin run by hand over a journal of its own, as the host would run them. */
|
|
36
|
+
function serve() {
|
|
37
|
+
const journal = new MemoryJournal();
|
|
38
|
+
const reader = journal.reader();
|
|
39
|
+
const found = new Map<string, Action<any, any, any>>();
|
|
40
|
+
const api = new Proxy({} as PluginApi, {
|
|
41
|
+
get: (_target, name) => {
|
|
42
|
+
if (name === "action") return (one: Action<any, any, any>) => void found.set(one.name, one);
|
|
43
|
+
if (name === "journal") return () => reader;
|
|
44
|
+
return () => undefined;
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
commitments({ messages: { bind } }).setup(api);
|
|
48
|
+
// The context of one call: a call made again is a new context under the same operation.
|
|
49
|
+
const call = async (name: string, input: unknown, operation: string): Promise<{ id: string; status: string }> => {
|
|
50
|
+
let ordinal = 0;
|
|
51
|
+
const ctx = {
|
|
52
|
+
operationId: operation as OperationId,
|
|
53
|
+
caller: rin,
|
|
54
|
+
emit: async (type: { name: string; version: number }, data: unknown) => {
|
|
55
|
+
ordinal += 1;
|
|
56
|
+
const id = recordId(`${operation}/emit/${ordinal}`);
|
|
57
|
+
return journal.append({ id, stream: `input:${type.name}`, type: type.name, schema: type.version, data, actor: rin, cause: null, root: id } as unknown as NewRecord);
|
|
58
|
+
},
|
|
59
|
+
} as unknown as ActionContext;
|
|
60
|
+
const one = found.get(name);
|
|
61
|
+
if (one === undefined) throw new Error(`no action ${name}`);
|
|
62
|
+
return (await one.run(one.input.parse(input), ctx)) as { id: string; status: string };
|
|
63
|
+
};
|
|
64
|
+
return { call };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
test("a done made again under its operation answers kept, and another operation finds it ended", async () => {
|
|
68
|
+
const world = serve();
|
|
69
|
+
const made = await world.call("commitment.make", { text: "Send the notes", to: "rin" }, "op-make");
|
|
70
|
+
expect(await world.call("commitment.done", { id: made.id }, "op-done")).toEqual({ id: made.id, status: "kept" });
|
|
71
|
+
expect(await world.call("commitment.done", { id: made.id }, "op-done")).toEqual({ id: made.id, status: "kept" });
|
|
72
|
+
await expect(world.call("commitment.done", { id: made.id }, "op-other")).rejects.toThrow(/kept/);
|
|
73
|
+
await expect(world.call("commitment.cancel", { id: made.id }, "op-done")).rejects.toThrow(/kept/);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("a cancel made again under its operation answers cancelled, and another operation finds it ended", async () => {
|
|
77
|
+
const world = serve();
|
|
78
|
+
const made = await world.call("commitment.make", { text: "Send the notes", to: "rin" }, "op-make");
|
|
79
|
+
expect(await world.call("commitment.cancel", { id: made.id }, "op-cancel")).toEqual({ id: made.id, status: "cancelled" });
|
|
80
|
+
expect(await world.call("commitment.cancel", { id: made.id }, "op-cancel")).toEqual({ id: made.id, status: "cancelled" });
|
|
81
|
+
await expect(world.call("commitment.cancel", { id: made.id }, "op-other")).rejects.toThrow(/cancelled/);
|
|
82
|
+
await expect(world.call("commitment.done", { id: made.id }, "op-cancel")).rejects.toThrow(/cancelled/);
|
|
83
|
+
});
|