@operad-io/bot 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tidy.ts CHANGED
@@ -5,13 +5,16 @@
5
5
  * when the botanist wakes and what a person sees.
6
6
  */
7
7
 
8
- import { messageOf } from "@operad-io/engine";
8
+ import { messageOf, type PluginFact, type SourceContext } from "@operad-io/engine";
9
9
  import { join, resolve } from "node:path";
10
10
  import {
11
11
  CHAT_TYPE,
12
12
  allEntries,
13
13
  allMessages,
14
14
  chatData,
15
+ lastReplyOutcome,
16
+ readChat,
17
+ stoppedRunAfter,
15
18
  chatFacts,
16
19
  costText,
17
20
  writingReplyNow,
@@ -37,11 +40,13 @@ import {
37
40
  ensureMemoryLayout,
38
41
  ensureRepository,
39
42
  linkReport,
43
+ lockInstructions,
40
44
  memoryEnabled,
41
45
  memoryTidyState,
42
46
  openMemorySearch,
43
47
  tidyCommitForChat,
44
48
  tidyCommitSummary,
49
+ unlockInstructions,
45
50
  wikiDirectoryOfHome,
46
51
  type LinkReport,
47
52
  } from "@operad-io/memory";
@@ -55,12 +60,19 @@ import {
55
60
  } from "./bot.ts";
56
61
  import { ChatWatches } from "./chat-watch.ts";
57
62
  import {
63
+ ROUTINE_TYPE,
58
64
  SCHEDULE_SOURCE,
59
65
  localDate,
60
- notifyScheduledReply,
66
+ mainChatDelivery,
61
67
  replySummary,
68
+ scheduledPromptOf,
69
+ withRun,
70
+ droppedRuns,
71
+ forgetRuns,
72
+ type RoutineRun,
62
73
  type ScheduleNotice,
63
74
  } from "./schedule.ts";
75
+ import { DREAMING_BUILTIN, DREAMING_NAME, dreamingId } from "./routine.ts";
64
76
 
65
77
  /** The internal object type of one bot's tidy state and card. */
66
78
  export const TIDY_TYPE = "bot-tidy";
@@ -120,6 +132,8 @@ export interface TidyData {
120
132
  export interface TidyNote {
121
133
  readonly path: string;
122
134
  readonly content: string;
135
+ /** The local date the note was last changed, `YYYY-MM-DD`. */
136
+ readonly date: string;
123
137
  }
124
138
 
125
139
  /** One chat in the period the tidy checks. */
@@ -147,6 +161,8 @@ export interface TidyWork {
147
161
  readonly indexOver: boolean;
148
162
  readonly indexBytes: number;
149
163
  readonly baseline: string | undefined;
164
+ /** The local date of this tidy, `YYYY-MM-DD`. */
165
+ readonly today: string;
150
166
  }
151
167
 
152
168
  function integer(value: unknown, fallback = 0): number {
@@ -265,7 +281,8 @@ async function chatsToCheck(
265
281
  if (chat.parent !== `${BOT_TYPE}:${bot}`) continue;
266
282
  if (chat.scheduled?.entry === TIDY_ORIGIN) continue;
267
283
  const messages = allMessages(store, object.id)
268
- .filter((message) => since === undefined || message.at >= since)
284
+ // A message of a stretch that is not remembered never reaches Dreaming.
285
+ .filter((message) => message.private !== true && (since === undefined || message.at >= since))
269
286
  .map((message) => ({
270
287
  role: message.role,
271
288
  text: cut(message.text, 1_500),
@@ -310,17 +327,22 @@ export async function tidyWork(
310
327
  store: ObjectStore,
311
328
  bot: string,
312
329
  cwd: string,
313
- options: { readonly home?: string | undefined } = {},
330
+ options: { readonly home?: string | undefined; readonly now?: number | undefined } = {},
314
331
  ): Promise<TidyWork> {
332
+ const now = options.now ?? Date.now();
315
333
  const memoryDir = join(cwd, "memory");
316
334
  ensureMemoryLayout(memoryDir);
317
335
  const memory = memoryTidyState(memoryDir, bot);
318
336
  const notes: TidyNote[] = [];
319
337
  for (const path of memory.notes) {
320
338
  try {
339
+ const file = Bun.file(join(memoryDir, ...path.split("/")));
321
340
  notes.push({
322
341
  path,
323
- content: cut(await Bun.file(join(memoryDir, ...path.split("/"))).text(), 8_000),
342
+ content: cut(await file.text(), 8_000),
343
+ // A checkout or restore can reset a file's time, so the date stays
344
+ // inside the period the tidy checks: not before the last tidy, not after now.
345
+ date: localDate(Math.min(now, Math.max(file.lastModified, memory.since ?? 0))),
324
346
  });
325
347
  } catch {
326
348
  // A note that vanished between the check and this read is not work.
@@ -333,6 +355,7 @@ export async function tidyWork(
333
355
  indexOver: memory.indexOver,
334
356
  indexBytes: memory.indexBytes,
335
357
  baseline: memory.baseline,
358
+ today: localDate(now),
336
359
  };
337
360
  }
338
361
 
@@ -405,13 +428,16 @@ export function tidyPrompt(bot: string, work: TidyWork): string {
405
428
  "This is the nightly memory tidy. Work only from the notes and chat records below.",
406
429
  "Fix notes that are wrong or out of date: the newer fact replaces the older one, and the old note stays where it is, marked as replaced; do not delete it.",
407
430
  `Keep memory/index.md under 8,000 characters by moving detail into topic notes. It is ${work.indexBytes} bytes now.`,
431
+ `Today is ${work.today}. Each note below has the date it was last changed; read a time word in a note ("next week", "tomorrow", "this month") from that date, not from today.`,
432
+ 'Rewrite a sentence that is relative to a time that has passed as a plain dated fact, using the note\'s date: "Going to Singapore next week" in a note dated 2026-07-03 becomes "Went to Singapore in July 2026". Leave a sentence whose time has not passed. Never guess a date the note does not give.',
433
+ 'A fact that holds only for a while carries the date it stops holding, as "until YYYY-MM-DD"; once that date is before today, say it no longer holds. A newer fact supersedes an older one: keep the older text, marked as replaced with the date, and write the newer fact beside it; never delete it.',
408
434
  "Check only the period since the last tidy. Do not change instructions.md. End with a short summary of what changed.",
409
435
  "",
410
436
  `## Notes added or changed since the last tidy (${work.notes.length})`,
411
437
  ];
412
438
  if (work.notes.length === 0) out.push("None.");
413
439
  for (const note of work.notes) {
414
- out.push("", `### ${note.path}`, "```markdown", note.content, "```");
440
+ out.push("", `### ${note.path} (changed ${note.date})`, "```markdown", note.content, "```");
415
441
  }
416
442
  out.push("", `## Chats in the period (${work.chats.length})`);
417
443
  if (work.chats.length === 0) out.push("None.");
@@ -446,22 +472,22 @@ export function tidyOutcomeLine(bot: string, outcome: TidyOutcome): string {
446
472
  export function tidyCardPrompt(data: TidyData): string {
447
473
  if (data.state === "pending" || data.state === "requested") {
448
474
  const lines = [
449
- `Memory tidy for bot ${data.bot}: ${data.counts.notes} new or changed note${data.counts.notes === 1 ? "" : "s"}, ${data.counts.chats} chat${data.counts.chats === 1 ? "" : "s"} to check.`,
475
+ `Dreaming for bot ${data.bot}: ${data.counts.notes} new or changed note${data.counts.notes === 1 ? "" : "s"}, ${data.counts.chats} chat${data.counts.chats === 1 ? "" : "s"} to check.`,
450
476
  data.counts.indexOver ? "The memory index is over its limit." : "The memory index is within its limit.",
451
477
  ];
452
478
  if (data.state === "requested") lines.push("It runs as soon as no chat of this bot is replying.");
453
479
  return lines.join(" ");
454
480
  }
455
481
  if (data.state === "running") {
456
- return `Memory tidy for bot ${data.bot} is running in chat ${data.chatId ?? "…"}.`;
482
+ return `Dreaming for bot ${data.bot} is running.`;
457
483
  }
458
484
  const outcome = data.outcome ?? data.lastOutcome;
459
485
  if (data.state === "failed") {
460
486
  const reason = outcome === undefined ? "no reason was recorded" : outcome.summary;
461
- return `Memory tidy for bot ${data.bot} failed: ${reason.replace(/\.$/, "")}.`;
487
+ return `Dreaming for bot ${data.bot} failed: ${reason.replace(/\.$/, "")}.`;
462
488
  }
463
- if (outcome === undefined) return `Memory tidy for bot ${data.bot}: nothing to show.`;
464
- return `Memory tidy for bot ${data.bot} finished. ${tidyOutcomeLine(data.bot, outcome)}.${outcome.reply.length === 0 ? "" : ` Reply: ${outcome.reply}`}`;
489
+ if (outcome === undefined) return `Dreaming for bot ${data.bot}: nothing to show.`;
490
+ return `Dreaming for bot ${data.bot} finished. ${tidyOutcomeLine(data.bot, outcome)}.${outcome.reply.length === 0 ? "" : ` Reply: ${outcome.reply}`}`;
465
491
  }
466
492
 
467
493
  /** The actions a tidy card offers: Run and Skip. */
@@ -473,13 +499,10 @@ export const tidyActions: readonly ActionTypeDefinition[] = [
473
499
  async run(ctx) {
474
500
  const data = tidyDataOf(ctx.object.data);
475
501
  if (data === undefined) throw new BotError("this tidy card has no usable state");
476
- await ctx.store.put(
477
- TIDY_TYPE,
478
- data.bot,
479
- { ...data, state: "requested", requestedAt: Date.now(), outcome: undefined } as unknown as Record<string, JsonValue>,
480
- "action:bot/run",
481
- );
482
- return `memory tidy for bot ${data.bot} will run when no chat of the bot is replying`;
502
+ const next = { ...data, state: "requested", requestedAt: Date.now(), outcome: undefined } as TidyData;
503
+ await ctx.store.put(TIDY_TYPE, data.bot, next as unknown as Record<string, JsonValue>, "action:bot/run");
504
+ await syncDreaming(ctx.store, next, Date.now());
505
+ return `Dreaming for bot ${data.bot} will run when no chat of the bot is replying`;
483
506
  },
484
507
  },
485
508
  {
@@ -489,17 +512,52 @@ export const tidyActions: readonly ActionTypeDefinition[] = [
489
512
  async run(ctx) {
490
513
  const data = tidyDataOf(ctx.object.data);
491
514
  if (data === undefined) throw new BotError("this tidy card has no usable state");
492
- await ctx.store.put(
493
- TIDY_TYPE,
494
- data.bot,
495
- { ...data, state: "skipped", requestedAt: undefined } as unknown as Record<string, JsonValue>,
496
- "action:bot/skip",
497
- );
498
- return `skipped the memory tidy of bot ${data.bot} until the next check finds work`;
515
+ const next = { ...data, state: "skipped", requestedAt: undefined } as TidyData;
516
+ await ctx.store.put(TIDY_TYPE, data.bot, next as unknown as Record<string, JsonValue>, "action:bot/skip");
517
+ await syncDreaming(ctx.store, next, Date.now());
518
+ return `skipped Dreaming for bot ${data.bot} until the next check finds work`;
499
519
  },
500
520
  },
501
521
  ];
502
522
 
523
+ /**
524
+ * Keeps the Dreaming routine of a bot in step with its tidy state: the routine
525
+ * object is what the list of routines shows. A run is added or updated by id;
526
+ * the history keeps 30 days.
527
+ */
528
+ export async function syncDreaming(
529
+ store: ObjectStore,
530
+ tidy: TidyData,
531
+ now: number,
532
+ options: { readonly schedule?: string | undefined; readonly run?: RoutineRun | undefined } = {},
533
+ ): Promise<void> {
534
+ const id = dreamingId(tidy.bot);
535
+ const current = await store.get(ROUTINE_TYPE, id);
536
+ const entry = scheduledPromptOf(current?.data);
537
+ const schedule = options.schedule ?? entry?.schedule ?? "30 3 * * *";
538
+ const started = options.run === undefined ? undefined : entry?.runs?.find((item) => item.id === options.run?.id)?.at;
539
+ const run = options.run === undefined ? undefined : { ...options.run, at: started ?? options.run.at };
540
+ const runs = run === undefined ? entry?.runs : withRun(entry?.runs, run, now);
541
+ const outcome = tidy.outcome ?? tidy.lastOutcome;
542
+ const data: Record<string, JsonValue> = {
543
+ bot: tidy.bot,
544
+ name: DREAMING_NAME,
545
+ builtin: DREAMING_BUILTIN,
546
+ schedule,
547
+ prompt: "Tidy this bot's memory.",
548
+ paused: false,
549
+ state: tidy.state,
550
+ ...(outcome === undefined
551
+ ? {}
552
+ : { last: { plannedAt: tidy.plannedAt, schedule, result: outcomeSummary(outcome), ...(tidy.state === "failed" ? { failed: true } : {}) } as unknown as JsonValue }),
553
+ ...(runs === undefined || runs.length === 0 ? {} : { runs: runs as unknown as JsonValue }),
554
+ };
555
+ if (current === undefined || JSON.stringify(current.data) !== JSON.stringify(data)) {
556
+ await store.put(ROUTINE_TYPE, id, data, "source:bot/tidy");
557
+ }
558
+ if (run !== undefined) await forgetRuns(store, droppedRuns(entry?.runs, run, now));
559
+ }
560
+
503
561
  /** The pending items the tidy cards make. */
504
562
  export async function tidyItems(
505
563
  store: ObjectStore,
@@ -529,11 +587,11 @@ export async function tidyItems(
529
587
  function tidyRow(object: StoredObject): ObjectRow {
530
588
  const data = tidyDataOf(object.data);
531
589
  if (data === undefined) {
532
- return { id: object.id, title: "Memory tidy", state: "broken", parent: `${BOT_TYPE}:${object.id}` };
590
+ return { id: object.id, title: DREAMING_NAME, state: "broken", parent: `${BOT_TYPE}:${object.id}` };
533
591
  }
534
592
  return {
535
593
  id: object.id,
536
- title: `Memory tidy for ${data.bot}`,
594
+ title: `${DREAMING_NAME} for ${data.bot}`,
537
595
  state: data.state,
538
596
  parent: `${BOT_TYPE}:${data.bot}`,
539
597
  ...(data.state === "pending" || data.state === "failed"
@@ -548,7 +606,7 @@ function tidyRow(object: StoredObject): ObjectRow {
548
606
  /** How a tidy card shows when it is read as an object. */
549
607
  export const tidyViews: ObjectViews = {
550
608
  row: tidyRow,
551
- sections: () => [{ id: "tidy", title: "Memory tidy" }],
609
+ sections: () => [{ id: "tidy", title: DREAMING_NAME }],
552
610
  load: (_ctx, object): SectionContent => {
553
611
  const data = tidyDataOf(object.data);
554
612
  return {
@@ -566,6 +624,8 @@ export interface TidySourceContext {
566
624
  readonly clock: () => number;
567
625
  readonly logger: { write(text: string): Promise<string> };
568
626
  readonly client: ClientApi;
627
+ /** What a delivery to the main chat needs to write; without it a result stays in the history. */
628
+ readonly facts?: SourceContext["facts"] | undefined;
569
629
  readonly harnesses?: readonly string[] | undefined;
570
630
  readonly harnessCapabilities?: ((harness: string) => HarnessCapabilities | undefined) | undefined;
571
631
  /** How the check reads its work; a test replaces it to see whether it ran. */
@@ -606,7 +666,7 @@ export class BotTidySource {
606
666
  options: { readonly notify?: ((notice: ScheduleNotice) => Promise<void>) | undefined } = {},
607
667
  ) {
608
668
  this.ctx = ctx;
609
- this.notify = options.notify ?? ((notice) => notifyScheduledReply(ctx.home, notice));
669
+ this.notify = options.notify ?? mainChatDelivery(ctx);
610
670
  this.chatWatches = new ChatWatches(ctx.logger, ctx.store, ctx.runs);
611
671
  }
612
672
 
@@ -615,8 +675,19 @@ export class BotTidySource {
615
675
  await this.chatWatches.settled();
616
676
  }
617
677
 
618
- private async put(bot: string, data: TidyData, cause: string): Promise<void> {
678
+ private async put(bot: string, data: TidyData, cause: string, run?: RoutineRun): Promise<void> {
619
679
  await this.ctx.store.put(TIDY_TYPE, bot, data as unknown as Record<string, JsonValue>, cause);
680
+ let schedule: string | undefined;
681
+ try {
682
+ const settings = readBots(this.ctx.home, this.ctx.settings)[bot];
683
+ if (settings !== undefined) {
684
+ const { hour, minute } = tidyClock(settings);
685
+ schedule = `${minute} ${hour} * * *`;
686
+ }
687
+ } catch {
688
+ // Without usable settings the routine keeps the schedule it has.
689
+ }
690
+ await syncDreaming(this.ctx.store, data, this.ctx.clock(), { ...(schedule === undefined ? {} : { schedule }), ...(run === undefined ? {} : { run }) });
620
691
  }
621
692
 
622
693
  private async bots(): Promise<readonly StoredObject[]> {
@@ -649,7 +720,7 @@ export class BotTidySource {
649
720
  try {
650
721
  settings = readBots(this.ctx.home, this.ctx.settings)[bot];
651
722
  } catch (error) {
652
- await this.chatWatches.log(`memory tidy: ${messageOf(error)}`);
723
+ await this.chatWatches.log(`dreaming: ${messageOf(error)}`);
653
724
  return;
654
725
  }
655
726
  if (settings === undefined || !memoryEnabled(this.ctx.home)) return;
@@ -658,7 +729,7 @@ export class BotTidySource {
658
729
  cwd = workingDirectory(this.ctx.home, bot, settings);
659
730
  ensureBotMemory(cwd, this.ctx.home);
660
731
  } catch (error) {
661
- await this.chatWatches.log(`memory tidy ${bot}: ${messageOf(error)}`);
732
+ await this.chatWatches.log(`dreaming ${bot}: ${messageOf(error)}`);
662
733
  return;
663
734
  }
664
735
  const stored = await this.ctx.store.get(TIDY_TYPE, bot);
@@ -745,7 +816,7 @@ export class BotTidySource {
745
816
 
746
817
  private workFor(bot: string, cwd: string): Promise<TidyWork> {
747
818
  if (this.ctx.work !== undefined) return this.ctx.work(this.ctx.store, bot, cwd);
748
- return tidyWork(this.ctx.store, bot, cwd, { home: this.ctx.home });
819
+ return tidyWork(this.ctx.store, bot, cwd, { home: this.ctx.home, now: this.ctx.clock() });
749
820
  }
750
821
 
751
822
  /** A run that started but can no longer be watched is reported, not left running. */
@@ -769,17 +840,22 @@ export class BotTidySource {
769
840
  ...(auto ? { outcome: undefined, lastOutcome: outcome } : { outcome }),
770
841
  },
771
842
  "source:bot/tidy",
843
+ { id: data.chatId ?? `failed-${now}`, at: now, status: "failed", result: outcome.summary },
772
844
  );
773
845
  if (auto) {
774
846
  try {
775
847
  await this.notify({
776
- chatId: outcome.chatId,
777
- title: "Memory tidy",
848
+ routineId: dreamingId(bot),
849
+ runId: outcome.chatId,
850
+ title: DREAMING_NAME,
778
851
  summary: tidyOutcomeLine(bot, outcome),
852
+ text: tidyOutcomeLine(bot, outcome),
853
+ failed: true,
854
+ bot,
779
855
  });
780
856
  } catch (error) {
781
857
  await this.chatWatches.log(
782
- `memory tidy of bot ${bot}: notify: ${messageOf(error)}`,
858
+ `dreaming of bot ${bot}: notify: ${messageOf(error)}`,
783
859
  );
784
860
  }
785
861
  }
@@ -810,10 +886,12 @@ export class BotTidySource {
810
886
  await this.put(bot, running, "source:bot/tidy");
811
887
  const model = backgroundModel(settings, this.ctx);
812
888
  let chatId: string | undefined;
889
+ // The tidy never changes the person's instructions: read-only until the run's commit.
890
+ lockInstructions(join(cwd, "memory"));
813
891
  try {
814
892
  const run = await this.ctx.client.act("bot:chat", `${BOT_TYPE}:${bot}`, {
815
893
  args: {
816
- title: `Memory tidy (${localDate(now)})`.slice(0, 120),
894
+ title: `${DREAMING_NAME} (${localDate(now)})`.slice(0, 120),
817
895
  message: tidyPrompt(bot, work),
818
896
  ...(model === undefined ? {} : { model }),
819
897
  },
@@ -823,32 +901,63 @@ export class BotTidySource {
823
901
  ? run.opens.slice(CHAT_TYPE.length + 1)
824
902
  : undefined;
825
903
  } catch (error) {
904
+ unlockInstructions(join(cwd, "memory"));
826
905
  const message = messageOf(error);
827
906
  await this.failStart(bot, running, `Could not start: ${message}`);
828
- await this.chatWatches.log(`memory tidy of bot ${bot} could not start: ${message}`);
907
+ await this.chatWatches.log(`dreaming of bot ${bot} could not start: ${message}`);
829
908
  return;
830
909
  }
831
910
  if (chatId === undefined) {
832
- await this.failStart(bot, running, "Could not start: it opened no chat");
833
- await this.chatWatches.log(`memory tidy of bot ${bot} opened no chat`);
911
+ unlockInstructions(join(cwd, "memory"));
912
+ await this.failStart(bot, running, "Could not start: it started no run");
913
+ await this.chatWatches.log(`dreaming of bot ${bot} started no run`);
834
914
  return;
835
915
  }
836
- await this.put(bot, { ...running, chatId }, "source:bot/tidy");
837
- await this.watch(bot, chatId, auto);
916
+ await this.put(bot, { ...running, chatId }, "source:bot/tidy", { id: chatId, at: now, status: "running" });
917
+ await this.watch(bot, chatId, auto, join(cwd, "memory"));
838
918
  }
839
919
 
840
- private async watch(bot: string, chatId: string, auto: boolean): Promise<void> {
920
+ private async watch(bot: string, chatId: string, auto: boolean, memoryDir: string | undefined): Promise<void> {
841
921
  this.chatWatches.watchChatReply(
842
922
  chatId,
843
923
  chatId,
844
924
  async (read) => {
845
- const committed = read.facts.some(
846
- (fact) =>
847
- fact.type === TIDY_COMMIT_FACT &&
848
- isRecord(fact.data) &&
849
- fact.data["chat"] === chatId,
850
- );
851
- if (!committed) return undefined;
925
+ const committedIn = (facts: readonly PluginFact[]): boolean =>
926
+ facts.some(
927
+ (fact) =>
928
+ fact.type === TIDY_COMMIT_FACT &&
929
+ isRecord(fact.data) &&
930
+ fact.data["chat"] === chatId,
931
+ );
932
+ if (!committedIn(read.facts)) {
933
+ // The commit is a step after the reply (memory/commit), so a plain
934
+ // reply is not yet an ending: only a cancelled or failed run, or a run
935
+ // that has wholly ended, is one without its commit.
936
+ const outcome = lastReplyOutcome(read.messages, read.entries);
937
+ const cancelled = stoppedRunAfter(read.facts, -1) !== undefined || outcome.kind === "stopped";
938
+ if (!cancelled && outcome.kind === "none") return undefined;
939
+ if (!cancelled && outcome.kind === "normal") {
940
+ if (this.ctx.runs === undefined || outcome.runId === undefined) return undefined;
941
+ if ((await this.ctx.runs.active(outcome.runId)) !== false) return undefined;
942
+ // The commit may have landed as the run ended: read again before ending without it.
943
+ if (committedIn(readChat(this.ctx.store, chatId).facts)) return undefined;
944
+ }
945
+ // The run ended without its commit: the instructions are given back.
946
+ if (memoryDir !== undefined) unlockInstructions(memoryDir);
947
+ const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
948
+ if (stored === undefined) return undefined;
949
+ const failure = [...read.entries].reverse().find((item) => item.kind === "failure");
950
+ const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
951
+ return {
952
+ stored,
953
+ replyText: reply?.text,
954
+ // A plain reply that ended with no commit is a quiet end, not a failure.
955
+ failureText:
956
+ outcome.kind === "normal" && !cancelled
957
+ ? undefined
958
+ : failure?.text ?? "The run was cancelled before it changed the memory.",
959
+ };
960
+ }
852
961
  const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
853
962
  if (stored === undefined) return undefined;
854
963
  const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
@@ -896,6 +1005,12 @@ export class BotTidySource {
896
1005
  : replySummary(failureText),
897
1006
  reply: replyText === undefined ? "" : replySummary(replyText),
898
1007
  };
1008
+ const run: RoutineRun = {
1009
+ id: chatId,
1010
+ at: now,
1011
+ status: failureText !== undefined ? "failed" : outcome.changed ? "done" : "quiet",
1012
+ result: outcomeSummary(outcome),
1013
+ };
899
1014
  const data = tidyDataOf((await this.ctx.store.get(TIDY_TYPE, bot))?.data ?? {});
900
1015
  if (auto) {
901
1016
  await this.put(
@@ -913,17 +1028,22 @@ export class BotTidySource {
913
1028
  lastOutcome: outcome,
914
1029
  },
915
1030
  "source:bot/tidy",
1031
+ run,
916
1032
  );
917
1033
  if (outcome.changed || failureText !== undefined) {
918
1034
  try {
919
1035
  await this.notify({
920
- chatId,
921
- title: typeof stored.data.title === "string" ? stored.data.title : "Memory tidy",
1036
+ routineId: dreamingId(bot),
1037
+ runId: chatId,
1038
+ title: DREAMING_NAME,
922
1039
  summary: tidyOutcomeLine(bot, { ...outcome, summary: outcomeSummary(outcome) }),
1040
+ text: tidyOutcomeLine(bot, { ...outcome, summary: outcomeSummary(outcome) }),
1041
+ failed: failureText !== undefined,
1042
+ bot,
923
1043
  });
924
1044
  } catch (error) {
925
1045
  await this.chatWatches.log(
926
- `memory tidy of bot ${bot}: notify: ${messageOf(error)}`,
1046
+ `dreaming of bot ${bot}: notify: ${messageOf(error)}`,
927
1047
  );
928
1048
  }
929
1049
  }
@@ -944,6 +1064,7 @@ export class BotTidySource {
944
1064
  outcome,
945
1065
  },
946
1066
  "source:bot/tidy",
1067
+ run,
947
1068
  );
948
1069
  return;
949
1070
  }
@@ -961,16 +1082,21 @@ export class BotTidySource {
961
1082
  outcome,
962
1083
  },
963
1084
  "source:bot/tidy",
1085
+ run,
964
1086
  );
965
1087
  try {
966
1088
  await this.notify({
967
- chatId,
968
- title: typeof stored.data.title === "string" ? stored.data.title : "Memory tidy",
1089
+ routineId: dreamingId(bot),
1090
+ runId: chatId,
1091
+ title: DREAMING_NAME,
969
1092
  summary: tidyOutcomeLine(bot, { ...outcome, summary: outcomeSummary(outcome) }),
1093
+ text: tidyOutcomeLine(bot, { ...outcome, summary: outcomeSummary(outcome) }),
1094
+ failed: false,
1095
+ bot,
970
1096
  });
971
1097
  } catch (error) {
972
1098
  await this.chatWatches.log(
973
- `memory tidy of bot ${bot}: notify: ${messageOf(error)}`,
1099
+ `dreaming of bot ${bot}: notify: ${messageOf(error)}`,
974
1100
  );
975
1101
  }
976
1102
  }
@@ -978,19 +1104,38 @@ export class BotTidySource {
978
1104
  private async resume(): Promise<void> {
979
1105
  for (const object of await this.tidyObjects()) {
980
1106
  const data = tidyDataOf(object.data);
981
- if (data?.state !== "running") continue;
1107
+ if (data === undefined) continue;
1108
+ const memoryDir = this.memoryDirOf(data.bot);
1109
+ if (data.state !== "running") {
1110
+ // No run is going: nothing may keep the instructions read-only.
1111
+ if (memoryDir !== undefined) unlockInstructions(memoryDir);
1112
+ continue;
1113
+ }
1114
+ if (memoryDir !== undefined && data.chatId === undefined) unlockInstructions(memoryDir);
982
1115
  if (data.chatId === undefined) {
983
1116
  // The process died after marking the run but before recording its chat.
984
- await this.failStart(data.bot, data, "Could not start: the tidy chat was not recorded");
1117
+ await this.failStart(data.bot, data, "Could not start: the run was not recorded");
985
1118
  continue;
986
1119
  }
987
- await this.watch(data.bot, data.chatId, data.auto === true);
1120
+ await this.watch(data.bot, data.chatId, data.auto === true, memoryDir);
1121
+ }
1122
+ }
1123
+
1124
+ /** The bot's memory directory, or undefined when its settings cannot be read. */
1125
+ private memoryDirOf(bot: string): string | undefined {
1126
+ try {
1127
+ const settings = readBots(this.ctx.home, this.ctx.settings)[bot];
1128
+ if (settings === undefined) return undefined;
1129
+ return join(workingDirectory(this.ctx.home, bot, settings), "memory");
1130
+ } catch {
1131
+ return undefined;
988
1132
  }
989
1133
  }
990
1134
 
991
1135
  start(): { stop: () => void } {
992
1136
  this.timer = setInterval(() => {
993
1137
  this.chatWatches.track(this.poll());
1138
+ this.chatWatches.recheckAll();
994
1139
  }, 1_000);
995
1140
  if (typeof this.timer === "object" && "unref" in this.timer) {
996
1141
  this.timer.unref();