@niwa-labs/rin 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.
@@ -0,0 +1,988 @@
1
+ // Rin on a real host. The test stands in for her model: it reads the facts she is told and decides as she would,
2
+ // through her own actions; the host carries the decisions out.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+ import { Database } from "bun:sqlite";
6
+ import { cp } from "node:fs/promises";
7
+ import { z } from "zod";
8
+
9
+ import { CORE_TYPES, JOURNAL_FILE, NotSent, OptionIdSchema, action, actionRef, grant, principalOf } from "@niwa-labs/core";
10
+ import type { Address, Caller, StoredRecord } from "@niwa-labs/core";
11
+ import { AGENT, plugin, pluginName } from "@niwa-labs/plugin";
12
+ import type { AgentOffer, Plugin } from "@niwa-labs/plugin";
13
+ import { AGENT_BRIEFING, AGENT_PROMPT_SECTION, AGENT_TYPES, agentNotify, agentReply, agentTell } from "@niwa-labs/agent/records";
14
+ import { NoteCorrected, NoteErased, NoteRetracted, NoteWritten, memoryConsolidate } from "@niwa-labs/memory/records";
15
+ import { messageSendRef } from "@niwa-labs/messages/records";
16
+ import { ResolverRegistry, requests } from "@niwa-labs/requests";
17
+ import { RequestCreated, requestAnswer, requestAsk, requestCancel, requestOpen } from "@niwa-labs/requests/records";
18
+ import { RunFinished, RunRequested, RunStarted, workflowStart } from "@niwa-labs/workflow/records";
19
+ import { connect, connectAsOwner, createNiwa, eventually, messages, tempHome, testClock, timers, workflow } from "@niwa-labs/testing";
20
+ import type { NiwaApi, TestClock } from "@niwa-labs/testing";
21
+
22
+ import { rinPlugin } from "../src/plugin.ts";
23
+ import type { RinOptions } from "../src/plugin.ts";
24
+ import {
25
+ rinAttend,
26
+ rinAttention,
27
+ rinBriefing,
28
+ rinCharter,
29
+ rinCharterPropose,
30
+ rinCharterRetire,
31
+ rinPromptCharter,
32
+ rinContext,
33
+ rinConversation,
34
+ rinCorrect,
35
+ rinDismiss,
36
+ rinInbox,
37
+ rinNotice,
38
+ rinSelfHistory,
39
+ rinSelfInstall,
40
+ } from "../src/records.ts";
41
+
42
+ const HOUR = 3_600_000;
43
+ /** Noon of a day, local time: away from the quiet hours. */
44
+ const NOON = new Date(2026, 10, 20, 12, 0).getTime();
45
+
46
+ /** The owner is the owner; a session `rin` speaks as the agent `rin`, a session `lead` as the agent `lead`. */
47
+ function bind(caller: Caller): Address | undefined {
48
+ if (caller.kind !== "client") return undefined;
49
+ if (caller.principal?.kind === "owner") return { kind: "owner" };
50
+ if (caller.principal?.kind === "session") return { id: String(caller.principal.id), kind: "agent" };
51
+ return { kind: "client", id: caller.id };
52
+ }
53
+
54
+ /** The action of a stub that writes a record of a type it declares, as the test says. */
55
+ const writeRef = (name: string) =>
56
+ actionRef(`${name}.write`, {
57
+ description: "Write a record of a declared type.",
58
+ input: z.object({ type: z.string(), data: z.unknown() }),
59
+ output: z.object({ id: z.string() }),
60
+ });
61
+
62
+ function writer(name: string, types: readonly { name: string }[], extra: (api: Parameters<Parameters<typeof plugin>[1]>[0]) => void = () => {}): Plugin {
63
+ return plugin(name, (api) => {
64
+ api.declare(...(types as never[]));
65
+ api.action(
66
+ action(writeRef(name), {
67
+ recovery: "repeat",
68
+ effect: "record",
69
+ world: "niwa",
70
+ run: async (input, ctx) => {
71
+ const type = types.find((one) => one.name === input.type);
72
+ if (type === undefined) throw new Error(`no type ${input.type}`);
73
+ return { id: String((await ctx.emit(type as never, input.data as never)).id) };
74
+ },
75
+ }),
76
+ );
77
+ extra(api);
78
+ });
79
+ }
80
+
81
+ interface World {
82
+ readonly home: string;
83
+ readonly host: ReturnType<typeof createNiwa>;
84
+ readonly clock: TestClock;
85
+ /** What Rin was told, in order: the facts of her inbox. */
86
+ readonly told: string[];
87
+ /** What reached the owner now. */
88
+ readonly sent: string[];
89
+ readonly offered: { agents: AgentOffer[]; briefing: string[]; prompt: Array<{ id: string; agent?: string; action: string }> };
90
+ readonly owner: NiwaApi;
91
+ readonly rin: NiwaApi;
92
+ readonly lead: NiwaApi;
93
+ readonly records: (type: string) => Promise<StoredRecord[]>;
94
+ /** Write a record of the agents' or the workflow module's, as they would. */
95
+ readonly agents: (type: string, data: unknown) => Promise<string>;
96
+ readonly runs: (type: string, data: unknown, as?: NiwaApi) => Promise<string>;
97
+ /** Write a record of the memory module, as it would. */
98
+ readonly memory: (type: string, data: unknown) => Promise<string>;
99
+ /** The fact Rin was last told that names an occasion, and the occasion. */
100
+ readonly lastOccasion: () => string;
101
+ /** `on`: the send fails; `unsure`: it fails in a way that may have sent it, not as `NotSent`. */
102
+ readonly failSay: { on: boolean; unsure: boolean };
103
+ /** How many of the next facts told to her fail: the handler that tells her pauses, as after a crash. */
104
+ readonly failTell: { times: number };
105
+ readonly consolidated: string[];
106
+ /** Let a paused invocation go on: the step that failed is made again. */
107
+ readonly retryPaused: () => Promise<void>;
108
+ }
109
+
110
+ const cleanups: Array<() => Promise<void>> = [];
111
+ afterEach(async () => {
112
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
113
+ });
114
+
115
+ async function world(options: Partial<RinOptions> = {}, start = NOON, resolvers?: ResolverRegistry, realWorkflow = false, withTelegram = true, fixture: {
116
+ prepareHome?: (path: string) => Promise<void>;
117
+ surface?: Plugin & { bind(fallback: typeof bind): typeof bind };
118
+ } = {}): Promise<World> {
119
+ const home = await tempHome();
120
+ await fixture.prepareHome?.(home.path);
121
+ const clock = testClock(start);
122
+ const host = createNiwa({ home: home.path, clock });
123
+ cleanups.push(() => home.cleanup());
124
+ cleanups.push(() => host.close());
125
+ const told: string[] = [];
126
+ const sent: string[] = [];
127
+ const consolidated: string[] = [];
128
+ const failSay = { on: false, unsure: false };
129
+ const failTell = { times: 0 };
130
+ const offered = { agents: [] as AgentOffer[], briefing: [] as string[], prompt: [] as Array<{ id: string; agent?: string; action: string }> };
131
+ const agentsStub = writer("agents", AGENT_TYPES, (api) => {
132
+ api.action(action(agentTell, { recovery: "repeat", effect: "record", world: "niwa", run: async () => { throw new Error("agent.tell is not stubbed"); } }));
133
+ api.action(action(agentReply, { recovery: "repeat", effect: "record", world: "niwa", run: async () => { throw new Error("agent.reply is not stubbed"); } }));
134
+ api.action(
135
+ action(agentNotify, {
136
+ recovery: "repeat",
137
+ effect: "record",
138
+ world: "niwa",
139
+ run: async (input) => {
140
+ if (failTell.times > 0) {
141
+ failTell.times -= 1;
142
+ throw new Error("the inbox is gone");
143
+ }
144
+ if (input.agent === "rin") told.push(input.text);
145
+ return { turn: `fact-${(told.length + 0xa00000).toString(16)}` };
146
+ },
147
+ }),
148
+ );
149
+ api.service(() => {
150
+ offered.agents.push(...api.offers(AGENT).map((one) => one.value));
151
+ offered.briefing.push(...api.offers(AGENT_BRIEFING).map((one) => one.value.action));
152
+ offered.prompt.push(...api.offers(AGENT_PROMPT_SECTION).map((one) => one.value));
153
+ return () => {};
154
+ });
155
+ });
156
+ const workflowStub = realWorkflow ? workflow() : writer("workflow", [RunRequested, RunStarted, RunFinished]);
157
+ const memoryStub = writer("memory", [NoteWritten, NoteCorrected, NoteRetracted, NoteErased], (api) => {
158
+ api.action(action(memoryConsolidate, {
159
+ recovery: "repeat", effect: "record", world: "niwa",
160
+ run: async ({ memory = "stub" }) => {
161
+ consolidated.push(memory);
162
+ return { memory, merged: [], lifted: [], dropped: [], retired: [] };
163
+ },
164
+ }));
165
+ });
166
+ const telegram = plugin("telegram", (api) => {
167
+ api.action(
168
+ action("telegram.send", {
169
+ description: "Send a text to the owner's chat.",
170
+ input: z.object({ text: z.string() }),
171
+ output: z.object({ messageId: z.number() }),
172
+ recovery: "do-not-repeat",
173
+ effect: "write",
174
+ world: "local",
175
+ run: async (input) => {
176
+ if (failSay.on) throw failSay.unsure ? new Error("the connection was cut") : new NotSent("telegram is down");
177
+ sent.push(input.text);
178
+ return { messageId: sent.length };
179
+ },
180
+ }),
181
+ );
182
+ });
183
+ host.use(
184
+ messages({ bind }),
185
+ requests({ bind: fixture.surface?.bind(bind) ?? bind, ...(resolvers === undefined ? {} : { resolvers }) }),
186
+ timers([]),
187
+ agentsStub,
188
+ workflowStub,
189
+ memoryStub,
190
+ ...(withTelegram ? [fixture.surface ?? telegram] : []),
191
+ rinPlugin({ bind, harness: "claude", telegram: withTelegram, quietHours: { from: "23:00", to: "08:00" }, ...options }),
192
+ );
193
+ await host.serve();
194
+ const owner = await connectAsOwner(home.path);
195
+ cleanups.push(() => owner.close());
196
+ const session = async (name: string) => {
197
+ const token = host.issueToken(principalOf("session", name), { grant: grant(["rin.*", "request.ask", "message.send", "workflow.*"]) });
198
+ const client = await connect({ home: home.path, id: `session:${name}`, token });
199
+ cleanups.push(() => client.close());
200
+ return client;
201
+ };
202
+ const rin = await session("rin");
203
+ const lead = await session("lead");
204
+ const records = async (type: string) => (await host.records.read()).filter((row) => row.type === type);
205
+ return {
206
+ home: home.path,
207
+ host,
208
+ clock,
209
+ told,
210
+ sent,
211
+ offered,
212
+ owner,
213
+ rin,
214
+ lead,
215
+ records,
216
+ agents: async (type, data) => (await owner.call(writeRef("agents"), { type, data })).id,
217
+ memory: async (type, data) => (await owner.call(writeRef("memory"), { type, data })).id,
218
+ runs: async (type, data, as = owner) => (await as.call(writeRef("workflow"), { type, data })).id,
219
+ lastOccasion: () => {
220
+ const fact = [...told].reverse().find((text) => text.includes("(occasion occ-"));
221
+ return /occasion (occ-[0-9a-f]{10})/.exec(fact ?? "")?.[1] ?? "";
222
+ },
223
+ failSay,
224
+ failTell,
225
+ consolidated,
226
+ retryPaused: async () => {
227
+ let paused: string | undefined;
228
+ await eventually(async () => {
229
+ const open = await owner.call(requestOpen, {});
230
+ paused = open.requests.find((one): one is Extract<typeof one, { kind: "paused" }> => "kind" in one && one.kind === "paused")?.invocation;
231
+ return paused !== undefined;
232
+ }, 5000, "an invocation to pause");
233
+ await owner.call("niwa.invocation.resolve" as never, { invocation: paused, choice: "retry" } as never);
234
+ },
235
+ };
236
+ }
237
+
238
+ /** Wait until Rin was told `n` facts. */
239
+ async function toldCount(w: World, n: number): Promise<void> {
240
+ await eventually(() => w.told.length >= n, 5000, `Rin to be told ${n} facts, got ${w.told.length}`);
241
+ }
242
+
243
+ test("Rin is offered to the agents module with a briefing section of her own", async () => {
244
+ const w = await world();
245
+ expect(w.offered.agents.map((one) => one.name)).toEqual(["rin"]);
246
+ expect(w.offered.briefing).toEqual(["rin.briefing"]);
247
+ expect(w.offered.prompt).toEqual([{ id: "charter", agent: "rin", action: "rin.prompt.charter" }]);
248
+ });
249
+
250
+ test("an occasion reaches her once while it holds, with what she weighs", async () => {
251
+ const w = await world();
252
+ const opened = await w.lead.call(rinNotice, { key: "ci:pr-101", kind: "ci", text: "CI is red on PR 101" });
253
+ expect(opened.status).toBe("opened");
254
+ await toldCount(w, 1);
255
+ expect(w.told[0]).toContain("CI is red on PR 101");
256
+ expect(w.told[0]).toContain("The owner is not working in an attached session now.");
257
+ expect(w.told[0]).toContain("Your charter has no rules yet.");
258
+
259
+ // Three red builds over the night are one occasion.
260
+ expect((await w.lead.call(rinNotice, { key: "ci:pr-101", kind: "ci", text: "CI is red on PR 101 again" })).status).toBe("repeated");
261
+ expect((await w.lead.call(rinNotice, { key: "ci:pr-101", kind: "ci", text: "CI is red on PR 101 again" })).status).toBe("repeated");
262
+ await Bun.sleep(50);
263
+ expect(w.told).toHaveLength(1);
264
+ const { occasions } = await w.owner.call(rinAttention, {});
265
+ expect(occasions).toMatchObject([{ key: "ci:pr-101", count: 3 }]);
266
+ });
267
+
268
+ test("concurrent notices share an occasion claim and retry with the claimed text", async () => {
269
+ const w = await world();
270
+ w.failTell.times = 1;
271
+ const input = { key: "ci:same", kind: "ci", text: "The build is red" };
272
+ const notices = await Promise.all([w.lead.call(rinNotice, input), w.owner.call(rinNotice, input), w.lead.call(rinNotice, input)]);
273
+ expect(new Set(notices.map(({ occasion }) => occasion)).size).toBe(1);
274
+ expect(notices.map(({ status }) => status).sort()).toEqual(["opened", "repeated", "repeated"]);
275
+ await eventually(async () => (await w.records("rin.occasion.claimed")).length === 1);
276
+ const claim = (await w.records("rin.occasion.claimed"))[0]?.data as { occasion: string; text: string };
277
+ const [opened] = notices;
278
+ if (opened?.occasion === undefined) throw new Error("the notice must name an occasion");
279
+ expect(claim.occasion).toBe(opened.occasion);
280
+ await w.owner.call(rinCharterPropose, { about: "tone", text: "Stay brief" });
281
+ await w.retryPaused();
282
+ await toldCount(w, 1);
283
+ await eventually(async () => (await w.records("rin.occasion.notified")).length === 1);
284
+ expect(w.told[0]).toBe(claim.text);
285
+ });
286
+
287
+ test("the stub model's decisions: silence keeps, the next contact waits for his message, now goes out", async () => {
288
+ const w = await world();
289
+ const decide = async (key: string, kind: string, decision: "silent" | "next-contact" | "now", text: string) => {
290
+ const before = w.told.length;
291
+ await w.lead.call(rinNotice, { key, kind, text });
292
+ await toldCount(w, before + 1);
293
+ return w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision, text });
294
+ };
295
+ expect((await decide("ci:pr-7", "ci", "silent", "CI on a draft")).outcome).toBe("kept");
296
+ expect((await decide("task:t-1", "task", "next-contact", "The review is done: two comments"))).toMatchObject({ outcome: "held", why: "next-contact" });
297
+ expect((await decide("agent:lead", "agent", "now", "The lead has been stuck for an hour"))).toMatchObject({ outcome: "sending" });
298
+ await eventually(() => w.sent.length === 1);
299
+ expect(w.sent).toEqual(["The lead has been stuck for an hour"]);
300
+
301
+ // He writes to her: what waited is brought up, and she is told what it was.
302
+ const before = w.told.length;
303
+ await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "morning" } });
304
+ await toldCount(w, before + 1);
305
+ expect(w.told.at(-1)).toContain("- The review is done: two comments");
306
+ const { items } = await w.owner.call(rinAttention, {});
307
+ expect(items.map((one) => [one.text, one.status])).toEqual([
308
+ ["The lead has been stuck for an hour", "said"],
309
+ ["The review is done: two comments", "brought"],
310
+ ]);
311
+ });
312
+
313
+ test("a fact of her inbox, a task's outcome, can be decided about by the id her inbox read gives", async () => {
314
+ const w = await world();
315
+ await w.agents("agent.turn.queued", { agent: "rin", turn: "fact-0a0a0a", kind: "fact", author: { kind: "niwa", by: "tasks" }, text: "Task task-1 is done: two comments\nmore" });
316
+ await w.agents("agent.turn.queued", { agent: "lead", turn: "fact-0b0b0b", kind: "fact", author: { kind: "niwa", by: "tasks" }, text: "not hers" });
317
+ const before = await w.rin.call(rinInbox, {});
318
+ expect(before.turns).toEqual([{ turn: "fact-0a0a0a", kind: "fact", from: { kind: "niwa", by: "tasks" }, text: "Task task-1 is done: two comments", decided: false }]);
319
+ const held = await w.rin.call(rinAttend, { subject: { kind: "turn", turn: before.turns[0]!.turn }, decision: "next-contact", text: "The review task is done: two comments" });
320
+ expect(held.outcome).toBe("held");
321
+ expect((await w.rin.call(rinInbox, {})).turns).toEqual([]);
322
+ expect((await w.rin.call(rinInbox, { decided: true })).turns).toMatchObject([{ turn: "fact-0a0a0a", decided: true }]);
323
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("- The review task is done: two comments");
324
+ });
325
+
326
+ test("the conversation shows what he wrote with where it stands, and what she wrote to him", async () => {
327
+ const w = await world();
328
+ const replyTo = { channel: "cockpit", conversation: "rin" } as const;
329
+ const first = await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, replyTo, body: { type: "update", text: "Review the migration" } });
330
+ const second = await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, replyTo, body: { type: "update", text: "And the docs" } });
331
+ const third = await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, replyTo, body: { type: "update", text: "And the tests" } });
332
+ await w.lead.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "not his" } });
333
+ expect((await w.owner.call(rinConversation, {})).messages.map((one) => [one.text, one.from, one.delivery])).toEqual([
334
+ ["Review the migration", "owner", "waiting"],
335
+ ["And the docs", "owner", "waiting"],
336
+ ["And the tests", "owner", "waiting"],
337
+ ]);
338
+ await w.agents("agent.turn.delivered", { agent: "rin", turn: first.id, session: "claude s1", receipt: { status: "started" } });
339
+ await w.agents("agent.turn.failed", { agent: "rin", turn: second.id, status: "unsent", reason: "the harness is gone" });
340
+ await w.rin.call(messageSendRef, { to: { kind: "owner" }, body: { type: "update", text: "Unrouted outbound message" } });
341
+ await w.agents("agent.turn.replied", { agent: "rin", turn: first.id, replyTo, text: "Done: two comments" });
342
+ const { messages } = await w.owner.call(rinConversation, {});
343
+ expect(messages.map((one) => [one.id === third.id ? "third" : one.text, one.from, one.delivery])).toEqual([
344
+ ["Review the migration", "owner", "delivered"],
345
+ ["And the docs", "owner", "unsent"],
346
+ ["third", "owner", "waiting"],
347
+ ["Done: two comments", "rin", undefined],
348
+ ]);
349
+ expect(messages.at(-1)?.turn).toBe(first.id);
350
+ expect((await w.owner.call(rinConversation, { conversation: "different" })).messages).toEqual([]);
351
+ await expect(w.lead.call(rinConversation, {})).rejects.toThrow("Only the owner");
352
+ expect((await w.owner.call(rinConversation, { limit: 2 })).messages.map((one) => one.from)).toEqual(["owner", "rin"]);
353
+ });
354
+
355
+ test("only Rin decides, and something already said is raised again only by a rule of her charter", async () => {
356
+ const w = await world();
357
+ await w.lead.call(rinNotice, { key: "pr:9", kind: "pr", text: "PR 9 waits for his review" });
358
+ await toldCount(w, 1);
359
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
360
+ await expect(w.lead.call(rinAttend, { subject, decision: "now", text: "x" })).rejects.toThrow("only Rin");
361
+ await expect(w.rin.call(rinAttend, { subject, decision: "now" })).rejects.toThrow("needs the text");
362
+ await w.rin.call(rinAttend, { subject, decision: "now", text: "PR 9 waits for you" });
363
+ await expect(w.rin.call(rinAttend, { subject, decision: "now", text: "PR 9 still waits" })).rejects.toThrow("insist");
364
+ await expect(w.rin.call(rinAttend, { subject, decision: "insist", text: "PR 9 still waits" })).rejects.toThrow("rule");
365
+
366
+ const { rule } = await w.owner.call(rinCharterPropose, { about: "attention.pr", text: "A PR that waits on me a day is raised again" });
367
+ const insisted = await w.rin.call(rinAttend, { subject, decision: "insist", text: "PR 9 still waits, a day now", rule });
368
+ expect(insisted.outcome).toBe("sending");
369
+ await eventually(() => w.sent.length === 2);
370
+ expect(w.sent[1]).toBe("PR 9 still waits, a day now");
371
+ });
372
+
373
+ test("what she says now in his quiet hours goes out when they end", async () => {
374
+ const night = new Date(2026, 10, 20, 23, 30).getTime();
375
+ const w = await world({}, night);
376
+ await w.lead.call(rinNotice, { key: "deploy:1", kind: "deploy", text: "The deploy failed" });
377
+ await toldCount(w, 1);
378
+ expect(w.told[0]).toContain("These are his quiet hours, until 08:00");
379
+ const held = await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision: "now", text: "The deploy failed at 23:30" });
380
+ expect(held).toMatchObject({ outcome: "held", why: "quiet-hours", until: new Date(2026, 10, 21, 8, 0).getTime() });
381
+ await w.clock.advance(4 * HOUR);
382
+ await Bun.sleep(50);
383
+ expect(w.sent).toEqual([]);
384
+ await w.clock.advance(5 * HOUR);
385
+ await eventually(() => w.sent.length === 1);
386
+ expect(w.sent).toEqual(["The deploy failed at 23:30"]);
387
+ });
388
+
389
+ test("Rin consolidates her memory once when the night's quiet period ends", async () => {
390
+ const midnight = new Date(2026, 10, 21, 0, 0).getTime();
391
+ const w = await world({}, midnight);
392
+ expect(w.consolidated).toEqual([]);
393
+ await w.clock.advance(8 * HOUR);
394
+ await eventually(() => w.consolidated.length === 1);
395
+ expect(w.consolidated).toEqual(["rin"]);
396
+ await w.clock.advance(HOUR);
397
+ expect(w.consolidated).toEqual(["rin"]);
398
+ });
399
+
400
+ test("past the safety ceiling, what she says now waits for his next contact", async () => {
401
+ const w = await world({ ceiling: { count: 1, windowMs: 24 * HOUR } });
402
+ for (const key of ["a:1", "a:2"]) await w.lead.call(rinNotice, { key, kind: "agent", text: `Agent ${key} is stuck` });
403
+ await toldCount(w, 2);
404
+ const [first, second] = w.told.map((text) => /occasion (occ-[0-9a-f]{10})/.exec(text)?.[1] ?? "");
405
+ expect((await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: first! }, decision: "now", text: "one" })).outcome).toBe("sending");
406
+ expect(await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: second! }, decision: "now", text: "two" })).toMatchObject({ outcome: "held", why: "ceiling" });
407
+ await eventually(() => w.sent.length === 1);
408
+ expect((await w.rin.call(rinContext, {})).ceiling.left).toBe(0);
409
+ });
410
+
411
+ test("what cannot reach him now waits for his next contact, and she is told", async () => {
412
+ const w = await world();
413
+ w.failSay.on = true;
414
+ await w.lead.call(rinNotice, { key: "x:1", kind: "ci", text: "red" });
415
+ await toldCount(w, 1);
416
+ await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision: "now", text: "Main is red" });
417
+ await toldCount(w, 2);
418
+ expect(w.told[1]).toContain("did not reach him");
419
+ expect((await w.owner.call(rinAttention, { status: "held" })).items).toMatchObject([{ text: "Main is red", why: "undelivered" }]);
420
+ });
421
+
422
+ test("a decision to tell him now is refused while the host serves no action that does, and holding it is not", async () => {
423
+ const w = await world({}, NOON, undefined, false, false);
424
+ await w.lead.call(rinNotice, { key: "ci:x", kind: "ci", text: "red" });
425
+ await toldCount(w, 1);
426
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
427
+ await expect(w.rin.call(rinAttend, { subject, decision: "now", text: "Main is red" })).rejects.toThrow("No channel is configured");
428
+ expect((await w.owner.call(rinAttention, {})).items).toEqual([]);
429
+ expect((await w.rin.call(rinAttend, { subject, decision: "next-contact", text: "Main is red" })).outcome).toBe("held");
430
+ });
431
+
432
+ test("a custom delivery action must be served at startup", async () => {
433
+ await expect(world({ say: "slack.post" }, NOON, undefined, false, false)).rejects.toThrow('needs the action "slack.post"');
434
+ });
435
+
436
+ test("what may have reached him is not sent again and does not wait for his next contact", async () => {
437
+ const w = await world();
438
+ w.failSay.on = true;
439
+ w.failSay.unsure = true;
440
+ await w.lead.call(rinNotice, { key: "x:1", kind: "ci", text: "red" });
441
+ await toldCount(w, 1);
442
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
443
+ await w.rin.call(rinAttend, { subject, decision: "now", text: "Main is red" });
444
+ await toldCount(w, 2);
445
+ expect(w.told[1]).toContain("may or may not have reached him");
446
+ expect((await w.owner.call(rinAttention, {})).items).toMatchObject([{ text: "Main is red", status: "unsure" }]);
447
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("");
448
+ // It counts as told: saying it again is insisting.
449
+ await expect(w.rin.call(rinAttend, { subject, decision: "now", text: "Main is red" })).rejects.toThrow("insist");
450
+ });
451
+
452
+ test("what did not reach him because its occasion ended meanwhile is dropped, not held for his next contact", async () => {
453
+ const w = await world();
454
+ w.failSay.on = true;
455
+ await w.lead.call(rinNotice, { key: "x:2", kind: "ci", text: "red" });
456
+ await toldCount(w, 1);
457
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
458
+ // The send fails slowly: the occasion ends before the failure is settled.
459
+ await w.rin.call(rinAttend, { subject, decision: "now", text: "Main is red" });
460
+ await w.lead.call(rinNotice, { key: "x:2", kind: "ci", text: "green", ends: true });
461
+ await Bun.sleep(100);
462
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("");
463
+ const items = (await w.owner.call(rinAttention, {})).items;
464
+ expect(items.map((one) => one.status)).not.toContain("held");
465
+ });
466
+
467
+ test("a decision about an occasion that ended is refused", async () => {
468
+ const w = await world();
469
+ await w.lead.call(rinNotice, { key: "ci:late", kind: "ci", text: "Main is red" });
470
+ await toldCount(w, 1);
471
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
472
+ await w.lead.call(rinNotice, { key: "ci:late", kind: "ci", text: "Main is green", ends: true });
473
+ await expect(w.rin.call(rinAttend, { subject, decision: "next-contact", text: "Main was red" })).rejects.toThrow("no such occasion");
474
+ });
475
+
476
+ test("two decisions to tell him one thing are one message, and a thing already told is raised again only by insisting", async () => {
477
+ const night = new Date(2026, 10, 20, 23, 30).getTime();
478
+ const w = await world({}, night);
479
+ await w.lead.call(rinNotice, { key: "deploy:2", kind: "deploy", text: "The deploy failed" });
480
+ await toldCount(w, 1);
481
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
482
+ const first = await w.rin.call(rinAttend, { subject, decision: "now", text: "The deploy failed" });
483
+ const second = await w.rin.call(rinAttend, { subject, decision: "now", text: "The deploy failed at 23:30, twice" });
484
+ expect(second.item).toBe(first.item);
485
+ expect((await w.owner.call(rinAttention, {})).items).toMatchObject([{ text: "The deploy failed at 23:30, twice", status: "held" }]);
486
+ await w.clock.advance(9 * HOUR);
487
+ await eventually(() => w.sent.length >= 1);
488
+ await Bun.sleep(50);
489
+ expect(w.sent).toEqual(["The deploy failed at 23:30, twice"]);
490
+
491
+ // A held thing is not told yet, so there is nothing to insist on; a told one cannot be said again or held again.
492
+ await w.lead.call(rinNotice, { key: "deploy:3", kind: "deploy", text: "Another deploy failed" });
493
+ await toldCount(w, 2);
494
+ const other = { kind: "occasion" as const, occasion: w.lastOccasion() };
495
+ await w.rin.call(rinAttend, { subject: other, decision: "next-contact", text: "Another deploy failed" });
496
+ const rule = (await w.owner.call(rinCharterPropose, { about: "attention.deploy", text: "Raise a failed deploy again after a day" })).rule;
497
+ await expect(w.rin.call(rinAttend, { subject: other, decision: "insist", text: "again", rule })).rejects.toThrow("not told");
498
+ await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "morning" } });
499
+ await eventually(async () => (await w.records("rin.attention.brought")).length === 1);
500
+ await expect(w.rin.call(rinAttend, { subject: other, decision: "now", text: "again" })).rejects.toThrow("insist");
501
+ await expect(w.rin.call(rinAttend, { subject: other, decision: "next-contact", text: "again" })).rejects.toThrow("insist");
502
+ });
503
+
504
+ test("an occasion that ends drops what waited about it", async () => {
505
+ const w = await world();
506
+ await w.lead.call(rinNotice, { key: "ci:main", kind: "ci", text: "Main is red" });
507
+ await toldCount(w, 1);
508
+ await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision: "next-contact", text: "Main was red overnight" });
509
+ expect((await w.lead.call(rinNotice, { key: "ci:main", kind: "ci", text: "Main is green", ends: true })).status).toBe("ended");
510
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("");
511
+ expect((await w.owner.call(rinAttention, {})).items).toMatchObject([{ status: "dropped" }]);
512
+ });
513
+
514
+ test("what was brought up reaches her from the record that says so, also when telling her paused", async () => {
515
+ const w = await world();
516
+ await w.lead.call(rinNotice, { key: "task:t-9", kind: "task", text: "The review task is done" });
517
+ await toldCount(w, 1);
518
+ await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision: "next-contact", text: "The review is done" });
519
+ w.failTell.times = 1;
520
+ await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "morning" } });
521
+ await eventually(async () => (await w.records("rin.attention.brought")).length === 1);
522
+ await w.retryPaused();
523
+ await toldCount(w, 2);
524
+ expect(w.told[1]).toContain("- The review is done");
525
+ });
526
+
527
+ test("her briefing shows what waits, also to the attach that brought it up", async () => {
528
+ const w = await world();
529
+ await w.lead.call(rinNotice, { key: "task:t-2", kind: "task", text: "The migration task is done" });
530
+ await toldCount(w, 1);
531
+ await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision: "next-contact", text: "The migration is done" });
532
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("- The migration is done");
533
+ expect((await w.owner.call(rinBriefing, { agent: "lead" })).text).toBe("");
534
+
535
+ await w.agents("agent.attached", { agent: "rin", session: "claude s1", cwd: "/work/a" });
536
+ await eventually(async () => (await w.records("rin.attention.brought")).length === 1);
537
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("- The migration is done");
538
+ expect((await w.rin.call(rinContext, {})).working).toEqual([{ session: "claude s1", cwd: "/work/a", agent: "rin" }]);
539
+
540
+ await w.agents("agent.attached", { agent: "rin", session: "claude s2", cwd: "/work/a" });
541
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("");
542
+ });
543
+
544
+ test("a stuck agent is an occasion until a turn reaches it again", async () => {
545
+ const w = await world();
546
+ await w.agents("agent.turn.failed", { agent: "lead", turn: "msg-abcdef", status: "unsent", reason: "the harness is gone" });
547
+ await toldCount(w, 1);
548
+ expect(w.told[0]).toContain("A turn did not reach agent lead");
549
+ await w.agents("agent.turn.failed", { agent: "lead", turn: "msg-abcde0", status: "unsent", reason: "the harness is gone" });
550
+ await eventually(async () => (await w.records("rin.occasion.repeated")).length === 1);
551
+ await w.agents("agent.turn.delivered", { agent: "lead", turn: "msg-abcde1", session: "claude s9", receipt: { status: "started" } });
552
+ await eventually(async () => (await w.records("rin.occasion.ended")).length === 1);
553
+ expect(w.told).toHaveLength(1);
554
+ expect((await w.owner.call(rinAttention, {})).occasions).toEqual([]);
555
+ });
556
+
557
+ test("she learns how a workflow run she started ended, and not runs of others", async () => {
558
+ const w = await world();
559
+ // The run is asked for by its caller, and the workflow module writes its start.
560
+ await w.runs("workflow.run.requested", { run: "run-00a001", file: "/s/a.ts", args: {}, label: "nightly" }, w.rin);
561
+ await w.runs("workflow.run.requested", { run: "run-00a002", file: "/s/b.ts", args: {} }, w.lead);
562
+ await w.runs("workflow.run.started", { run: "run-00a001", file: "/s/a.ts", args: {}, label: "nightly" });
563
+ await w.runs("workflow.run.started", { run: "run-00a002", file: "/s/b.ts", args: {} });
564
+ await w.runs("workflow.run.finished", { run: "run-00a002", outcome: { status: "done", result: 1 } });
565
+ await w.runs("workflow.run.finished", { run: "run-00a001", outcome: { status: "done", result: 1 } });
566
+ await toldCount(w, 1);
567
+ expect(w.told[0]).toContain("The workflow run run-00a001 (nightly) you started ended: done.");
568
+ await Bun.sleep(50);
569
+ expect(w.told).toHaveLength(1);
570
+ });
571
+
572
+ test("on a real workflow module she learns of the run she started with workflow.start, and not of another caller's", async () => {
573
+ const w = await world({}, NOON, undefined, true);
574
+ const script = `${w.home}/quick.ts`;
575
+ await Bun.write(script, 'export default workflow({ description: "A run that ends at once", output: z.json() }, async () => ({ ok: true }));\n');
576
+ const hers = await w.rin.call(workflowStart, { file: script });
577
+ const his = await w.lead.call(workflowStart, { file: script });
578
+ await eventually(async () => (await w.records("workflow.run.finished")).length === 2, 20_000, "both runs to finish");
579
+ await toldCount(w, 1);
580
+ expect(w.told[0]).toContain(`The workflow run ${hers.run}`);
581
+ await Bun.sleep(100);
582
+ expect(w.told).toHaveLength(1);
583
+ expect(w.told.join("\n")).not.toContain(his.run);
584
+ }, 60_000);
585
+
586
+ test("a correction is the owner's: Rin writes one only from his own words", async () => {
587
+ const w = await world();
588
+ await expect(w.lead.call(rinCorrect, { about: "tone", what: "Be shorter" })).rejects.toThrow("owner");
589
+ await expect(w.rin.call(rinCorrect, { about: "tone", what: "Be shorter" })).rejects.toThrow("own words");
590
+ const said = await w.lead.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "be shorter" } });
591
+ await expect(w.rin.call(rinCorrect, { about: "tone", what: "Be shorter", source: said.id })).rejects.toThrow("own words");
592
+ const his = await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "too long, keep it to three lines" } });
593
+ const written = await w.rin.call(rinCorrect, { about: "tone", what: "Keep Telegram replies to three lines", source: his.id });
594
+ const { corrections } = await w.owner.call(rinCharter, {});
595
+ expect(corrections).toMatchObject([{ correction: written.correction, about: "tone", by: { kind: "agent", id: "rin" } }]);
596
+ });
597
+
598
+ test("her source may be the id of the journal record that holds his words, and nothing that merely carries his name", async () => {
599
+ const w = await world();
600
+ const his = await w.owner.call(messageSendRef, { to: { kind: "agent", id: "rin" }, body: { type: "update", text: "too long, keep it to three lines" } });
601
+ // The id of the record an action emitted holds slashes: it is a record id like any other.
602
+ const record = (await w.records("message.sent")).find((row) => (row.data as { id?: string }).id === his.id)!;
603
+ expect(String(record.id)).toContain("/emit/");
604
+ const viaRecord = await w.rin.call(rinCorrect, { about: "tone", what: "Keep replies to three lines", source: String(record.id) });
605
+ expect(viaRecord.correction).toMatch(/^cor-/);
606
+
607
+ // A turn of his that holds a message counts; one whose author is another agent does not, whoever wrote the record.
608
+ const turn = await w.agents("agent.turn.queued", { agent: "rin", turn: "msg-aaaaaa", kind: "message", author: { kind: "owner" }, text: "no jokes before ten" });
609
+ expect((await w.rin.call(rinCorrect, { about: "tone", what: "No jokes before ten", source: turn })).correction).toMatch(/^cor-/);
610
+ const alien = await w.agents("agent.turn.queued", { agent: "rin", turn: "msg-bbbbbb", kind: "message", author: { kind: "agent", id: "lead" }, text: "he said no jokes" });
611
+ await expect(w.rin.call(rinCorrect, { about: "tone", what: "No jokes", source: alien })).rejects.toThrow("own words");
612
+
613
+ // A record his client wrote that holds no words of his: his own correction, or the answer to a request.
614
+ const written = await w.owner.call(rinCorrect, { about: "memory", what: "Stop noting what I eat" });
615
+ const correction = (await w.records("rin.corrected")).find((row) => (row.data as { correction?: string }).correction === written.correction)!;
616
+ await expect(w.rin.call(rinCorrect, { about: "memory", what: "Stop noting food", source: String(correction.id) })).rejects.toThrow("own words");
617
+ await expect(w.rin.call(rinCorrect, { about: "memory", what: "Stop noting food", source: "no-such-record/emit/1" })).rejects.toThrow("own words");
618
+ });
619
+
620
+ test("repeated corrections ask her for a rule, and the owner's yes puts it in her charter", async () => {
621
+ const w = await world();
622
+ const first = await w.owner.call(rinCorrect, { about: "attention.ci", what: "Do not tell me about CI on drafts" });
623
+ await Bun.sleep(30);
624
+ expect(w.told).toHaveLength(0);
625
+ const second = await w.owner.call(rinCorrect, { about: "attention.ci", what: "Draft PRs can be red, leave them" });
626
+ await toldCount(w, 1);
627
+ expect(w.told[0]).toContain("corrections about attention.ci repeat");
628
+ expect(w.told[0]).toContain(first.correction);
629
+ expect(w.told[0]).toContain(second.correction);
630
+
631
+ // The stub model words the rule.
632
+ const proposed = await w.rin.call(rinCharterPropose, {
633
+ about: "attention.ci",
634
+ text: "Red CI on a draft PR is not worth telling",
635
+ corrections: [first.correction, second.correction],
636
+ });
637
+ expect(proposed.status).toBe("proposed");
638
+ await expect(w.rin.call(rinCharterPropose, { about: "attention.ci", text: "again" })).rejects.toThrow("already waits");
639
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toContain("Red CI on a draft PR is not worth telling");
640
+
641
+ await eventually(async () => (await w.records("request.created")).length === 1);
642
+ const asked = (await w.records("request.created"))[0]?.data as { id: string; input: { title: string } };
643
+ expect(asked.input.title).toContain("Red CI on a draft PR is not worth telling");
644
+ await w.owner.call(requestAnswer, { id: asked.id, answer: { ids: ["confirm"] } });
645
+ await eventually(async () => (await w.records("rin.charter.ruled")).length === 1);
646
+ await toldCount(w, 2);
647
+ expect(w.told[1]).toContain("The owner confirmed a rule of your charter");
648
+
649
+ // The rule is in the section of her prompt, read live, and only hers.
650
+ expect((await w.owner.call(rinPromptCharter, { agent: "rin" })).text).toContain(`${proposed.rule} (attention.ci): Red CI on a draft PR is not worth telling`);
651
+ expect((await w.owner.call(rinPromptCharter, { agent: "lead" })).text).toBe("");
652
+
653
+ // The rule goes with every occasion she is told about.
654
+ await w.lead.call(rinNotice, { key: "ci:pr-3", kind: "ci", text: "CI is red on draft PR 3" });
655
+ await toldCount(w, 3);
656
+ expect(w.told[2]).toContain(`${proposed.rule} (attention.ci): Red CI on a draft PR is not worth telling`);
657
+ });
658
+
659
+ test("the ask for a rule reaches her from the record that says one is due, also when telling her paused", async () => {
660
+ const w = await world();
661
+ await w.owner.call(rinCorrect, { about: "attention.ci", what: "Do not tell me about CI on drafts" });
662
+ w.failTell.times = 1;
663
+ await w.owner.call(rinCorrect, { about: "attention.ci", what: "Draft PRs can be red, leave them" });
664
+ await eventually(async () => (await w.records("rin.charter.due")).length === 1);
665
+ await w.retryPaused();
666
+ await toldCount(w, 1);
667
+ expect(w.told[0]).toContain("corrections about attention.ci repeat");
668
+ });
669
+
670
+ test("her prompt section says her charter has no rules before the owner confirms one", async () => {
671
+ const w = await world();
672
+ expect((await w.owner.call(rinPromptCharter, { agent: "rin" })).text).toBe("Your charter has no rules yet.");
673
+ });
674
+
675
+ test("a rule the owner declines stays out of the charter", async () => {
676
+ const w = await world();
677
+ const proposed = await w.rin.call(rinCharterPropose, { about: "tone", text: "No jokes before ten" });
678
+ await eventually(async () => (await w.records("request.created")).length === 1);
679
+ const asked = (await w.records("request.created"))[0]?.data as { id: string };
680
+ await w.owner.call(requestAnswer, { id: asked.id, answer: { ids: ["decline"] } });
681
+ await eventually(async () => (await w.records("rin.charter.declined")).length === 1);
682
+ const { rules } = await w.owner.call(rinCharter, {});
683
+ expect(rules).toMatchObject([{ rule: proposed.rule, status: "declined" }]);
684
+ });
685
+
686
+ test("what the owner answers to a question of hers comes back to her as a fact, and a resolver's answer is told as not his", async () => {
687
+ const w = await world();
688
+ const choice = { kind: "choice", title: "Shall I archive the old branches?", options: [{ id: "yes", label: "yes", flavor: "plain" }, { id: "no", label: "no", flavor: "plain" }] } as never;
689
+ const first = (await w.rin.call(requestAsk, { to: { kind: "owner" }, question: "rin.archive" as never, input: choice })) as { id: string };
690
+ await w.owner.call(requestAnswer, { id: first.id as never, answer: { ids: ["no"] } as never });
691
+ await toldCount(w, 1);
692
+ expect(w.told[0]).toContain(first.id);
693
+ expect(w.told[0]).toContain("Shall I archive the old branches?");
694
+ expect(w.told[0]).toContain("The owner chose no");
695
+
696
+ const second = await world({}, NOON, resolving("yes"));
697
+ const asked = (await second.rin.call(requestAsk, { to: { kind: "owner" }, question: "rin.archive" as never, input: choice })) as { id: string };
698
+ await toldCount(second, 1);
699
+ expect(second.told[0]).toContain(asked.id);
700
+ expect(second.told[0]).toContain("Not the owner but a resolver");
701
+ });
702
+
703
+ test("what the owner acts out is a correction: a question of hers turned down, something she told him waved away", async () => {
704
+ const w = await world();
705
+ const ask = await w.rin.call(requestAsk, { to: { kind: "owner" }, question: "rin.check" as never, input: { kind: "choice", title: "Shall I archive the old branches?", options: [{ id: "yes", label: "yes", flavor: "plain" }] } as never });
706
+ const id = (ask as { id: string }).id;
707
+ await w.owner.call(requestCancel, { id: id as never, reason: "not now" });
708
+ await eventually(async () => (await w.records("rin.corrected")).length === 1);
709
+ const turnedDown = (await w.records("rin.corrected"))[0]?.data as { about: string; what: string };
710
+ expect(turnedDown).toMatchObject({ about: "questions" });
711
+ expect(turnedDown.what).toContain("Shall I archive the old branches?");
712
+
713
+ await w.lead.call(rinNotice, { key: "news:1", kind: "news", text: "A new release of Bun" });
714
+ await toldCount(w, 1);
715
+ const said = await w.rin.call(rinAttend, { subject: { kind: "occasion", occasion: w.lastOccasion() }, decision: "next-contact", text: "Bun has a new release" });
716
+ await expect(w.lead.call(rinDismiss, { item: said.item! })).rejects.toThrow("only the owner");
717
+ await w.owner.call(rinDismiss, { item: said.item!, reason: "I do not care about releases" });
718
+ const corrections = (await w.owner.call(rinCharter, {})).corrections;
719
+ expect(corrections.map((one) => one.about)).toEqual(["questions", "attention.news"]);
720
+ expect((await w.owner.call(rinBriefing, { agent: "rin" })).text).toBe("");
721
+ });
722
+
723
+ const HER = { kind: "agent" as const, id: "rin" };
724
+ const noteWritten = (note: string, text: string) => ({ memory: "rin", note, text, about: "owner", source: { kind: "inferred" }, by: HER });
725
+
726
+ test("what the owner did to a note of hers is a correction that reads the note from memory, and shows nothing of an erased one", async () => {
727
+ const w = await world();
728
+ await w.memory("memory.note.written", noteWritten("note-aaaaaaaa", "The owner eats late"));
729
+ await w.memory("memory.note.corrected", { memory: "rin", note: "note-aaaaaaaa", text: "The owner eats at nine", by: { kind: "owner" } });
730
+ await w.memory("memory.note.written", noteWritten("note-bbbbbbbb", "The owner dislikes mornings"));
731
+ await w.memory("memory.note.retracted", { memory: "rin", note: "note-bbbbbbbb", reason: "He likes them", by: { kind: "owner" } });
732
+ await eventually(async () => (await w.records("rin.corrected")).length === 2);
733
+ const read = async () => (await w.owner.call(rinCharter, {})).corrections.map((one) => one.what);
734
+ expect(await read()).toEqual([
735
+ 'The owner changed a note of yours: "The owner eats late" became "The owner eats at nine"',
736
+ 'The owner took back a note of yours: "The owner dislikes mornings", saying: He likes them',
737
+ ]);
738
+
739
+ // Erased: what the correction says no longer holds the note's words, though nothing was rewritten.
740
+ await w.memory("memory.note.erased", { memory: "rin", note: "note-aaaaaaaa", by: { kind: "owner" } });
741
+ await eventually(async () => (await w.records("rin.corrected")).length === 3);
742
+ const after = await read();
743
+ expect(after.join("\n")).not.toContain("eats");
744
+ expect(after[0]).toBe("The owner changed a note of yours");
745
+ expect(after[1]).toContain("dislikes mornings");
746
+ // The records of her own hold no words of the note either.
747
+ expect(JSON.stringify((await w.records("rin.corrected")).map((row) => row.data))).not.toContain("eats");
748
+ });
749
+
750
+ test("the ask for a rule holds none of a note's words, which stay in memory and in what rin.charter reads", async () => {
751
+ const w = await world();
752
+ await w.memory("memory.note.written", noteWritten("note-aaaaaaaa", "The owner eats late"));
753
+ await w.memory("memory.note.corrected", { memory: "rin", note: "note-aaaaaaaa", text: "The owner eats at nine", by: { kind: "owner" } });
754
+ await eventually(async () => (await w.records("rin.corrected")).length === 1);
755
+ await w.memory("memory.note.corrected", { memory: "rin", note: "note-aaaaaaaa", text: "The owner eats at ten", by: { kind: "owner" } });
756
+ await eventually(async () => (await w.records("rin.corrected")).length === 2);
757
+ await toldCount(w, 1);
758
+ expect(w.told[0]).toContain("corrections about memory repeat");
759
+ expect(w.told[0]).toContain("rin.charter");
760
+ expect(w.told[0]).not.toContain("eats");
761
+ // Her inbox is journaled: the words of a note erased after the ask are not in it.
762
+ expect(JSON.stringify((await w.records("agent.turn.queued")).map((row) => row.data))).not.toContain("eats");
763
+ expect((await w.owner.call(rinCharter, {})).corrections.map((one) => one.what).join("\n")).toContain("eats at nine");
764
+ });
765
+
766
+ test("a long reason for taking a note back does not make the charter unreadable", async () => {
767
+ const w = await world();
768
+ await w.memory("memory.note.written", noteWritten("note-cccccccc", "The owner likes jazz"));
769
+ await w.memory("memory.note.retracted", { memory: "rin", note: "note-cccccccc", reason: "x".repeat(2100), by: { kind: "owner" } });
770
+ await eventually(async () => (await w.records("rin.corrected")).length === 1);
771
+ const { corrections } = await w.owner.call(rinCharter, {});
772
+ expect(corrections).toHaveLength(1);
773
+ expect(corrections[0]!.what.length).toBeLessThanOrEqual(2000);
774
+ expect(corrections[0]!.what).toContain("The owner likes jazz");
775
+ });
776
+
777
+ test("notices and decisions that arrive at once are taken one after the other", async () => {
778
+ const w = await world();
779
+ const notices = await Promise.all([1, 2, 3].map((n) => w.lead.call(rinNotice, { key: "ci:pr-5", kind: "ci", text: `red ${n}` })));
780
+ expect(notices.map((one) => one.status).sort()).toEqual(["opened", "repeated", "repeated"]);
781
+ await toldCount(w, 1);
782
+ const subject = { kind: "occasion" as const, occasion: w.lastOccasion() };
783
+ const decided = await Promise.allSettled([1, 2].map((n) => w.rin.call(rinAttend, { subject, decision: "now", text: `PR 5 is red (${n})` })));
784
+ expect(decided.map((one) => one.status).sort()).toEqual(["fulfilled", "rejected"]);
785
+ });
786
+
787
+ // ---- the owner's word -------------------------------------------------------------------------------------------
788
+
789
+ /** A resolver that answers every question with the choice, as a judge of an area would. */
790
+ function resolving(choice: string): ResolverRegistry {
791
+ const resolvers = new ResolverRegistry();
792
+ resolvers.register("*", () => ({ answered: true, answer: { ids: [OptionIdSchema.parse(choice)] }, info: { how: "recalled" } }));
793
+ return resolvers;
794
+ }
795
+
796
+ test("only the owner's answer can settle a proposed rule", async () => {
797
+ const w = await world({}, NOON, resolving("confirm"));
798
+ const proposed = await w.rin.call(rinCharterPropose, { about: "tone", text: "No jokes before ten" });
799
+ const request = await asked(w, 1);
800
+ expect(await w.records("request.answered")).toEqual([]);
801
+ expect((await w.owner.call(rinCharter, {})).rules).toMatchObject([{ rule: proposed.rule, status: "proposed" }]);
802
+ await w.owner.call(requestAnswer, { id: request.id, answer: { ids: ["confirm"] } });
803
+ await eventually(async () => (await w.records("rin.charter.ruled")).length === 1);
804
+ expect((await w.owner.call(rinCharter, {})).rules).toMatchObject([{ rule: proposed.rule, status: "ruled" }]);
805
+ });
806
+
807
+ /** A module that exports a plugin of Rin's group, written to a file of the host's home. */
808
+ async function moduleOf(w: World, name: string, version: string): Promise<string> {
809
+ const path = `${w.home}/${name.replace("/", "-")}.ts`;
810
+ await Bun.write(
811
+ path,
812
+ [`import { plugin } from ${JSON.stringify(import.meta.resolve("@niwa-labs/plugin"))};`, `export default plugin(${JSON.stringify(name)}, () => {}, { version: ${JSON.stringify(version)} });`, ""].join("\n"),
813
+ );
814
+ return path;
815
+ }
816
+
817
+ /** The request Rin's last proposal to the owner opened. */
818
+ async function asked(w: World, count: number): Promise<{ id: string; input: { title: string } }> {
819
+ await eventually(async () => (await w.records("request.created")).length === count);
820
+ return (await w.records("request.created"))[count - 1]!.data as { id: string; input: { title: string } };
821
+ }
822
+
823
+ test("she installs a plugin of her own group only after the owner said yes to that file", async () => {
824
+ const w = await world({ selfEdit: "ask" });
825
+ const module = await moduleOf(w, "rin/extra", "v1");
826
+ const proposed = await w.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "to keep a diary" });
827
+ const request = await asked(w, 1);
828
+ expect(request.input.title).toContain("rin/extra");
829
+ expect(request.input.title).toContain(proposed.hash);
830
+ expect(request.input.title).toContain("to keep a diary");
831
+ // Nothing is installed while the owner has not answered.
832
+ expect(w.host.installed(pluginName("rin/extra"))).toBeUndefined();
833
+
834
+ await w.owner.call(requestAnswer, { id: request.id, answer: { ids: ["confirm"] } });
835
+ await eventually(async () => (await w.records("rin.self-edit.settled")).length === 1);
836
+ expect((await w.records("rin.self-edit.settled"))[0]?.data).toMatchObject({ edit: proposed.edit, outcome: "installed" });
837
+ expect(String(w.host.installed(pluginName("rin/extra"))?.version)).toBe("v1");
838
+ await toldCount(w, 1);
839
+ expect(w.told[0]).toContain("rin/extra");
840
+ });
841
+
842
+ test("a plugin the owner declines is not installed, and a file changed after he looked is refused", async () => {
843
+ const w = await world({ selfEdit: "ask" });
844
+ const module = await moduleOf(w, "rin/extra", "v1");
845
+ await w.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "diary" });
846
+ await w.owner.call(requestAnswer, { id: (await asked(w, 1)).id, answer: { ids: ["decline"] } });
847
+ await eventually(async () => (await w.records("rin.self-edit.settled")).length === 1);
848
+ expect((await w.records("rin.self-edit.settled"))[0]?.data).toMatchObject({ outcome: "declined" });
849
+ expect(w.host.installed(pluginName("rin/extra"))).toBeUndefined();
850
+
851
+ // He says yes to the file he was shown; it changes before it is installed.
852
+ await w.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "diary again" });
853
+ const second = await asked(w, 2);
854
+ await moduleOf(w, "rin/extra", "v2");
855
+ await w.owner.call(requestAnswer, { id: second.id, answer: { ids: ["confirm"] } });
856
+ await eventually(async () => (await w.records("rin.self-edit.settled")).length === 2);
857
+ expect((await w.records("rin.self-edit.settled"))[1]?.data).toMatchObject({ outcome: "failed" });
858
+ expect(w.host.installed(pluginName("rin/extra"))).toBeUndefined();
859
+ });
860
+
861
+ test("self-edit questions wait for the owner even if a resolver would approve", async () => {
862
+ const w = await world({ selfEdit: "ask" }, NOON, resolving("confirm"));
863
+ const module = await moduleOf(w, "rin/extra", "v1");
864
+ await w.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "diary" });
865
+ const request = await asked(w, 1);
866
+ expect((await w.owner.call(requestOpen, {})).requests.some((one) => "id" in one && one.id === request.id)).toBe(true);
867
+ expect(await w.records("request.answered")).toEqual([]);
868
+ expect(w.host.installed(pluginName("rin/extra"))).toBeUndefined();
869
+ await w.owner.call(requestAnswer, { id: request.id, answer: { ids: ["confirm"] } });
870
+ await eventually(async () => w.host.installed(pluginName("rin/extra")) !== undefined);
871
+ });
872
+
873
+ test("free mode records the claim and outcome without a request, and the owner can uninstall", async () => {
874
+ const w = await world({ selfEdit: "free" });
875
+ const module = await moduleOf(w, "rin/extra", "v1");
876
+ const proposed = await w.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "diary" });
877
+ await eventually(async () => (await w.records("rin.self-edit.settled")).length === 1);
878
+ expect(await w.records("request.created")).toEqual([]);
879
+ expect((await w.records("rin.self-edit.claimed")).map((row) => row.data)).toEqual([{ ...proposed, plugin: "rin/extra" }]);
880
+ expect(await w.owner.call(rinSelfHistory, {})).toMatchObject({
881
+ mode: "free",
882
+ edits: [{ ...proposed, plugin: "rin/extra", status: "installed" }],
883
+ installed: [{ plugin: "rin/extra", version: "v1", hash: proposed.hash }],
884
+ });
885
+ await w.owner.call(actionRef("plugin.uninstall", {
886
+ description: "Uninstall selected module.",
887
+ input: z.object({ plugin: z.string(), hash: z.string() }),
888
+ output: z.object({ plugin: z.string(), hash: z.string() }),
889
+ }), { plugin: "rin/extra", hash: proposed.hash });
890
+ expect((await w.owner.call(rinSelfHistory, {})).installed).toEqual([]);
891
+ });
892
+
893
+ test("charter and install accept the owner confirmed by the requests surface binding", async () => {
894
+ const surface = plugin("owner-buttons", (api) => {
895
+ api.on(RequestCreated, { id: "confirm" }, async (request, step) => {
896
+ if (request.to.kind === "owner" && request.answerPolicy === "owner-only") {
897
+ await step(requestAnswer, { id: request.id, answer: { ids: ["confirm"] } });
898
+ }
899
+ });
900
+ });
901
+ const buttonBinding = (fallback: typeof bind): typeof bind => (caller) =>
902
+ caller.kind === "handler" && caller.handler === "owner-buttons/confirm" ? { kind: "owner" } : fallback(caller);
903
+ const w = await world({ selfEdit: "ask", telegram: false }, NOON, undefined, false, true, {
904
+ surface: { ...surface, bind: buttonBinding },
905
+ });
906
+ const { rule } = await w.rin.call(rinCharterPropose, { about: "tone", text: "Keep it short" });
907
+ await eventually(async () => (await w.records("rin.charter.ruled")).length === 1);
908
+ expect((await w.records("rin.charter.ruled"))[0]?.data).toMatchObject({ rule });
909
+ const module = await moduleOf(w, "rin/extra", "v1");
910
+ const proposed = await w.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "diary" });
911
+ await eventually(async () => (await w.records("rin.self-edit.settled")).length === 1);
912
+ expect((await w.records(CORE_TYPES.pluginInstalled)).map((row) => row.data)).toMatchObject([{ hash: proposed.hash }]);
913
+ expect((await w.records("request.answered")).map((row) => row.actor)).toMatchObject([
914
+ { kind: "handler", handler: "owner-buttons/confirm" }, { kind: "handler", handler: "owner-buttons/confirm" },
915
+ ]);
916
+ });
917
+
918
+ // Restart from a prefix of a real, successful installation's journal. All retained rows,
919
+ // including invocation and handler identity, were written by the host.
920
+ for (const [boundary, mode, expected] of [
921
+ ["claim", "off", "cancelled"],
922
+ ["claim", "ask", "installed"],
923
+ ["intent", "off", "unknown"],
924
+ ["receipt", "off", "installed"],
925
+ ] as const) {
926
+ test(`recover a free self-edit at the ${boundary} under ${mode}`, async () => {
927
+ const first = await world({ selfEdit: "free" });
928
+ const module = await moduleOf(first, "rin/extra", "v1");
929
+ const proposed = await first.rin.call(rinSelfInstall, { plugin: "rin/extra", module, why: "diary" });
930
+ await eventually(async () => (await first.records("rin.self-edit.settled")).length === 1);
931
+ const type = boundary === "claim" ? "rin.self-edit.claimed" : boundary === "receipt" ? CORE_TYPES.pluginInstalled : CORE_TYPES.stepIntent;
932
+ const checkpoint = (await first.records(type)).find((row) => boundary !== "intent" || (row.data as { action?: string }).action === "plugin.install");
933
+ if (!checkpoint) throw new Error(`Missing ${boundary} checkpoint`);
934
+ await first.host.close();
935
+ const restarted = await world({ selfEdit: mode }, NOON, undefined, false, true, { prepareHome: async (path) => {
936
+ await cp(first.home, path, { recursive: true });
937
+ const db = new Database(`${path}/${JOURNAL_FILE}`);
938
+ try {
939
+ db.run("DELETE FROM links WHERE from_id IN (SELECT id FROM records WHERE seq > ?)", [checkpoint.seq]);
940
+ db.run("DELETE FROM records WHERE seq > ?", [checkpoint.seq]);
941
+ } finally {
942
+ db.close();
943
+ }
944
+ } });
945
+ if (mode === "ask") {
946
+ const request = await asked(restarted, 1);
947
+ expect(request.input.title).toContain(proposed.hash);
948
+ expect(await restarted.records(CORE_TYPES.pluginInstalled)).toHaveLength(0);
949
+ await restarted.owner.call(requestAnswer, { id: request.id, answer: { ids: ["confirm"] } });
950
+ }
951
+ await eventually(async () => (await restarted.records("rin.self-edit.settled")).length === 1);
952
+ expect((await restarted.records("rin.self-edit.settled"))[0]?.data).toMatchObject({ edit: proposed.edit, outcome: expected });
953
+ expect(await restarted.records("rin.self-edit.claimed")).toHaveLength(1);
954
+ expect(await restarted.records("request.created")).toHaveLength(mode === "ask" ? 1 : 0);
955
+ expect(await restarted.records(CORE_TYPES.pluginInstalled)).toHaveLength(expected === "installed" ? 1 : 0);
956
+ const attempts = (await restarted.records(CORE_TYPES.stepIntent)).filter((row) => (row.data as { action: string }).action === "plugin.install");
957
+ expect(attempts).toHaveLength(boundary === "claim" && mode === "off" ? 0 : 1);
958
+ });
959
+ }
960
+
961
+ test("simultaneous charter proposals admit one rule, and a late approval cannot revive a retired rule", async () => {
962
+ const w = await world();
963
+ const outcomes = await Promise.allSettled([
964
+ w.rin.call(rinCharterPropose, { about: "tone", text: "Shorter replies" }),
965
+ w.rin.call(rinCharterPropose, { about: "tone", text: "More detail" }),
966
+ ]);
967
+ expect(outcomes.filter((result) => result.status === "fulfilled")).toHaveLength(1);
968
+ const winner = outcomes.find((result) => result.status === "fulfilled");
969
+ if (winner === undefined) throw new Error("a proposal must win");
970
+ const request = await asked(w, 1);
971
+ await w.owner.call(rinCharterRetire, { rule: winner.value.rule });
972
+ await w.owner.call(requestAnswer, { id: request.id, answer: { ids: ["confirm"] } });
973
+ await eventually(async () => (await w.records("niwa.record.refused")).some(({ data }) => (data as { code?: unknown })?.code === "rule-closed"));
974
+ expect((await w.owner.call(rinCharter, {})).rules).toMatchObject([{ rule: winner.value.rule, status: "retired" }]);
975
+ });
976
+
977
+ test("only Rin proposes to change herself, only when the owner turned it on, and only a plugin of her group", async () => {
978
+ const on = await world({ selfEdit: "ask" });
979
+ const module = await moduleOf(on, "rin/extra", "v1");
980
+ await expect(on.lead.call(rinSelfInstall, { plugin: "rin/extra", module, why: "x" })).rejects.toThrow("only Rin");
981
+ await expect(on.owner.call(rinSelfInstall, { plugin: "rin/extra", module, why: "x" })).rejects.toThrow("only Rin");
982
+ await expect(on.rin.call(rinSelfInstall, { plugin: "other/extra", module, why: "x" })).rejects.toThrow("begins with rin/");
983
+ await expect(on.rin.call(rinSelfInstall, { plugin: "rin/extra", module: `${on.home}/missing.ts`, why: "x" })).rejects.toThrow("cannot read");
984
+ expect((await on.records("request.created")).length).toBe(0);
985
+
986
+ const off = await world();
987
+ await expect(off.rin.call(rinSelfInstall, { plugin: "rin/extra", module: await moduleOf(off, "rin/extra", "v1"), why: "x" })).rejects.toThrow("turned off");
988
+ });