@operad-io/bot 0.2.0 → 0.3.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/src/schedule.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { messageOf } from "@operad-io/engine";
14
- import { CHAT_TYPE } from "@operad-io/chat";
14
+ import { CHAT_TYPE, chatData, sendMessage } from "@operad-io/chat";
15
15
  import { ChatWatches } from "./chat-watch.ts";
16
16
  import {
17
17
  cronMatches,
@@ -35,7 +35,9 @@ import {
35
35
  } from "@operad-io/engine";
36
36
  import { runLine } from "@operad-io/engine/platform";
37
37
  import { BOT_TYPE, BotError } from "./bot.ts";
38
+ import { followUps, removeFollowUp, withBotLock, type FollowUp } from "./follow-up.ts";
38
39
  import { SETUP_DEV_INSTRUCTION } from "./setup-dev.ts";
40
+ import { SETUP_GIT_INSTRUCTION } from "./setup-git.ts";
39
41
  import { SETUP_INSTRUCTION } from "./setup.ts";
40
42
 
41
43
  /** The source's name for a scheduled message; a message from it is a background run. */
@@ -57,14 +59,38 @@ export interface ScheduledLast {
57
59
  readonly firedAt?: number | undefined;
58
60
  /** The schedule this planned time belongs to. */
59
61
  readonly schedule: string;
62
+ /** True when the firing caught up after earlier planned minutes were skipped. */
63
+ readonly skippedEarlier?: boolean | undefined;
60
64
  /** The chat the firing opened. */
61
65
  readonly chatId?: string | undefined;
62
66
  /** A short summary of the reply, or why it could not start. */
63
67
  readonly result?: string | undefined;
64
68
  /** True once the notify command was run for `result`. */
65
69
  readonly notified?: boolean | undefined;
70
+ /** True when a person ran the entry now: `firedAt` is then the run's time, and `plannedAt` is untouched. */
71
+ readonly manual?: boolean | undefined;
66
72
  }
67
73
 
74
+ /** One finished firing kept for the next prompt. */
75
+ export interface ScheduledRecent {
76
+ /** The planned minute of the firing, in epoch milliseconds. */
77
+ readonly plannedAt: number;
78
+ readonly result: string;
79
+ }
80
+
81
+ /** How many finished results an entry keeps and its next prompt carries. */
82
+ export const SCHEDULE_RECENT_COUNT = 3;
83
+ /** The longest a kept result is in the next prompt. */
84
+ export const SCHEDULE_RECENT_MAX = 120;
85
+
86
+ /** The reply that means a firing has nothing to report. */
87
+ export const SCHEDULE_QUIET_MARKER = "NOTHING_TO_REPORT";
88
+ /** What a quiet firing records as its result. */
89
+ export const SCHEDULE_QUIET_RESULT = "Nothing to report.";
90
+
91
+ /** The line every scheduled prompt ends with: how to end quietly. */
92
+ export const SCHEDULE_PREAMBLE = `If there is nothing new to report, reply with exactly ${SCHEDULE_QUIET_MARKER} and nothing else; the person is then not notified. Otherwise reply as usual.`;
93
+
68
94
  /** One scheduled prompt of a bot. */
69
95
  export interface ScheduledPrompt {
70
96
  readonly name: string;
@@ -75,6 +101,10 @@ export interface ScheduledPrompt {
75
101
  readonly effort?: string | undefined;
76
102
  readonly paused: boolean;
77
103
  readonly last?: ScheduledLast | undefined;
104
+ /** The last few finished results, oldest first. */
105
+ readonly recent?: readonly ScheduledRecent[] | undefined;
106
+ /** When a person asked to run it now, until the source starts that run. */
107
+ readonly runNow?: number | undefined;
78
108
  }
79
109
 
80
110
  /** The longest summary an entry keeps and a notification carries. */
@@ -94,9 +124,11 @@ function lastOf(value: unknown): ScheduledLast | undefined {
94
124
  ? { firedAt: value.firedAt }
95
125
  : {}),
96
126
  schedule: value.schedule,
127
+ ...(value.skippedEarlier === true ? { skippedEarlier: true } : {}),
97
128
  ...(text(value.chatId) === undefined ? {} : { chatId: value.chatId as string }),
98
129
  ...(text(value.result) === undefined ? {} : { result: value.result as string }),
99
130
  ...(value.notified === true ? { notified: true } : {}),
131
+ ...(value.manual === true ? { manual: true } : {}),
100
132
  };
101
133
  }
102
134
 
@@ -108,6 +140,15 @@ export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
108
140
  const prompt = text(value.prompt);
109
141
  if (name === undefined || schedule === undefined || prompt === undefined) return undefined;
110
142
  const last = lastOf(value.last);
143
+ const recent: ScheduledRecent[] = [];
144
+ if (Array.isArray(value.recent)) {
145
+ for (const item of value.recent) {
146
+ if (!isRecord(item)) continue;
147
+ if (typeof item.plannedAt !== "number" || !Number.isFinite(item.plannedAt)) continue;
148
+ if (text(item.result) === undefined) continue;
149
+ recent.push({ plannedAt: item.plannedAt, result: item.result as string });
150
+ }
151
+ }
111
152
  return {
112
153
  name,
113
154
  schedule,
@@ -116,6 +157,8 @@ export function scheduledPromptOf(value: unknown): ScheduledPrompt | undefined {
116
157
  ...(text(value.effort) === undefined ? {} : { effort: value.effort as string }),
117
158
  paused: value.paused === true,
118
159
  ...(last === undefined ? {} : { last }),
160
+ ...(recent.length === 0 ? {} : { recent: recent.slice(-SCHEDULE_RECENT_COUNT) }),
161
+ ...(typeof value.runNow === "number" && Number.isFinite(value.runNow) ? { runNow: value.runNow } : {}),
119
162
  };
120
163
  }
121
164
 
@@ -168,6 +211,10 @@ function stored(entry: ScheduledPrompt): Record<string, JsonValue> {
168
211
  ...(entry.effort === undefined ? {} : { effort: entry.effort }),
169
212
  paused: entry.paused,
170
213
  ...(entry.last === undefined ? {} : { last: entry.last as unknown as JsonValue }),
214
+ ...(entry.recent === undefined || entry.recent.length === 0
215
+ ? {}
216
+ : { recent: entry.recent as unknown as JsonValue }),
217
+ ...(entry.runNow === undefined ? {} : { runNow: entry.runNow }),
171
218
  };
172
219
  }
173
220
 
@@ -215,13 +262,68 @@ export function latenessLine(scheduledAt: number, lateSecs: number): string {
215
262
  return `Scheduled for ${localStamp(scheduledAt)}; this run is ${lateText(lateSecs)} late.`;
216
263
  }
217
264
 
265
+ /** The result of a finished firing, cut to what the next prompt carries. */
266
+ function recentText(result: string): string {
267
+ return result.length <= SCHEDULE_RECENT_MAX
268
+ ? result
269
+ : `${result.slice(0, SCHEDULE_RECENT_MAX - 1)}…`;
270
+ }
271
+
272
+ /** True while the last firing's chat has started and its result is not yet recorded. */
273
+ function isReplying(last: ScheduledLast | undefined): boolean {
274
+ return last?.chatId !== undefined && last.result === undefined;
275
+ }
276
+
277
+ /**
278
+ * What a firing tells the agent beyond the person's own prompt: the earlier
279
+ * results of the same entry so it does not repeat them, the quiet-ending line,
280
+ * and for a catch-up the lateness line. The chat does not show it.
281
+ */
282
+ export function scheduledInstruction(entry: ScheduledPrompt): string {
283
+ // `last` is recorded when the firing starts, so it says what was planned and when it ran.
284
+ const last = entry.last;
285
+ const late =
286
+ last?.firedAt !== undefined &&
287
+ last.manual !== true &&
288
+ (last.plannedAt < minuteStart(last.firedAt) || last.skippedEarlier === true)
289
+ ? { scheduledAt: last.plannedAt, lateSecs: Math.floor((last.firedAt - last.plannedAt) / 1_000) }
290
+ : undefined;
291
+ const parts: string[] = [];
292
+ const recent = (entry.recent ?? []).slice(-SCHEDULE_RECENT_COUNT);
293
+ if (recent.length > 0) {
294
+ const lines = recent.map((item) => `- ${localStamp(item.plannedAt)}: ${recentText(item.result)}`);
295
+ parts.push(
296
+ `Earlier results of this scheduled prompt, oldest first; the person has already seen them, so do not repeat them:\n${lines.join("\n")}`,
297
+ );
298
+ }
299
+ parts.push(SCHEDULE_PREAMBLE);
300
+ if (late !== undefined) parts.push(latenessLine(late.scheduledAt, late.lateSecs));
301
+ return parts.join("\n\n");
302
+ }
303
+
304
+ /** The instruction of the firing of the named entry now recorded on a bot; undefined when it has none. */
305
+ export function scheduledInstructionFor(data: Readonly<Record<string, unknown>>, name: string): string | undefined {
306
+ const entry = scheduledPrompts(data).find((item) => item.name === name);
307
+ return entry === undefined ? undefined : scheduledInstruction(entry);
308
+ }
309
+
310
+ /** True when a reply is exactly the quiet marker. */
311
+ export function isQuietReply(message: string): boolean {
312
+ return message.trim() === SCHEDULE_QUIET_MARKER;
313
+ }
314
+
218
315
  /** What a bot chat's first session starts with: a schedule it writes is a proposal. */
219
316
  export const SCHEDULE_INSTRUCTION =
220
317
  "To schedule something for me, propose it: call the operad `command` tool with plugin `bot`, verb `schedule`, action `add` (or `edit` or `remove`). Give the schedule both as a five-field cron expression and in words. Nothing takes effect until I approve it in Pending.";
221
318
 
319
+ /** The line telling the agent how to set a follow-up for itself in this chat (ADR 0030 D16). */
320
+ export function followUpInstruction(chat: string): string {
321
+ return `To look at something again later in this chat (chat ${chat}), set a follow-up: call the operad \`command\` tool with plugin \`bot\`, verb \`follow-up\`, args [\`${chat}\`, \`--at\`, <a time such as "2026-12-01 09:00" or "+2h">, \`--do\`, <one sentence of what to do>]. It takes effect at once; at most 5 not yet due per chat and at most 30 days ahead. Verb \`follow-ups\` with args [\`${chat}\`] lists them, and with \`--cancel\`, <id> cancels one. When it is due you are sent that sentence here.`;
322
+ }
323
+
222
324
  /** The text and place a bot chat starts with. */
223
- export function scheduledChatContext(): { readonly text: string; readonly where: string } {
224
- const line = `${SCHEDULE_INSTRUCTION} ${SETUP_DEV_INSTRUCTION} ${SETUP_INSTRUCTION}`;
325
+ export function scheduledChatContext(chat: string): { readonly text: string; readonly where: string } {
326
+ const line = `${SCHEDULE_INSTRUCTION} ${followUpInstruction(chat)} ${SETUP_DEV_INSTRUCTION} ${SETUP_GIT_INSTRUCTION} ${SETUP_INSTRUCTION}`;
225
327
  return { text: line, where: line };
226
328
  }
227
329
 
@@ -339,6 +441,7 @@ async function replaceEntry(
339
441
  change: (entry: ScheduledPrompt) => ScheduledPrompt | undefined,
340
442
  cause: string,
341
443
  ): Promise<ScheduledPrompt | undefined> {
444
+ return withBotLock(store, bot, async () => {
342
445
  const object = await botObject(store, bot);
343
446
  const entries = scheduledPrompts(object.data);
344
447
  let changed: ScheduledPrompt | undefined;
@@ -359,10 +462,12 @@ async function replaceEntry(
359
462
  cause,
360
463
  );
361
464
  return changed;
465
+ });
362
466
  }
363
467
 
364
468
  /** Removes one entry from the bot object. */
365
469
  async function removeEntry(store: ObjectStore, bot: string, name: string): Promise<boolean> {
470
+ return withBotLock(store, bot, async () => {
366
471
  const object = await botObject(store, bot);
367
472
  const entries = scheduledPrompts(object.data);
368
473
  const next = entries.filter((entry) => entry.name !== name);
@@ -374,6 +479,7 @@ async function removeEntry(store: ObjectStore, bot: string, name: string): Promi
374
479
  "action:bot/schedule-remove",
375
480
  );
376
481
  return true;
482
+ });
377
483
  }
378
484
 
379
485
  /** The current entry with the fields the proposal changed, from `before` to `after`, applied. */
@@ -440,6 +546,7 @@ async function addEntry(
440
546
  bot: string,
441
547
  entry: ScheduledPrompt,
442
548
  ): Promise<ScheduledPrompt> {
549
+ return withBotLock(store, bot, async () => {
443
550
  const object = await botObject(store, bot);
444
551
  const entries = scheduledPrompts(object.data);
445
552
  if (entries.some((item) => item.name === entry.name)) {
@@ -452,6 +559,7 @@ async function addEntry(
452
559
  "action:bot/schedule-add",
453
560
  );
454
561
  return entry;
562
+ });
455
563
  }
456
564
 
457
565
  function entryArgs(required: boolean): ActionTypeDefinition["args"] {
@@ -625,6 +733,32 @@ export const scheduleActions: readonly ActionTypeDefinition[] = [
625
733
  return `resumed scheduled prompt "${name}" for bot ${ctx.object.id}`;
626
734
  },
627
735
  },
736
+ {
737
+ name: "schedule-run-now",
738
+ on: BOT_TYPE,
739
+ args: nameArg(),
740
+ when: (state) => state.removed !== true,
741
+ why: (object) =>
742
+ object.data.removed === true ? `bot ${object.id} is no longer in the settings` : undefined,
743
+ async run(ctx, args) {
744
+ const name = checkPromptName((args as { readonly name: string }).name);
745
+ const current = scheduledPrompts(ctx.object.data).find((entry) => entry.name === name);
746
+ if (current !== undefined && isReplying(current.last)) {
747
+ throw new BotError(
748
+ `scheduled prompt "${name}" of bot ${ctx.object.id} is still replying to its previous firing (chat ${current.last?.chatId ?? ""}); run it now after that reply ends`,
749
+ );
750
+ }
751
+ const changed = await replaceEntry(
752
+ ctx.store,
753
+ ctx.object.id,
754
+ name,
755
+ (entry) => ({ ...entry, runNow: entry.runNow ?? Date.now() }),
756
+ "action:bot/schedule-run-now",
757
+ );
758
+ if (changed === undefined) throw new BotError(`bot ${ctx.object.id} has no scheduled prompt "${name}"`);
759
+ return `running scheduled prompt "${name}" of bot ${ctx.object.id} now; its next timed run is unchanged`;
760
+ },
761
+ },
628
762
  {
629
763
  name: "schedule-remove",
630
764
  on: BOT_TYPE,
@@ -642,6 +776,19 @@ export const scheduleActions: readonly ActionTypeDefinition[] = [
642
776
  },
643
777
  ];
644
778
 
779
+ /** A value shown literally in Markdown: a code span that survives a backtick inside it. */
780
+ export function markdownCode(value: string): string {
781
+ const longest = Math.max(0, ...[...value.matchAll(/`+/g)].map((run) => run[0].length));
782
+ const fence = "`".repeat(longest + 1);
783
+ const pad = value.startsWith("`") || value.endsWith("`") ? " " : "";
784
+ return `${fence}${pad}${value}${pad}${fence}`;
785
+ }
786
+
787
+ /** A user's text shown as text in Markdown: the characters that format are escaped. */
788
+ export function markdownText(value: string): string {
789
+ return value.replace(/([\\`*_{}\[\]<>#|~!])/g, "\\$1").replace(/\r?\n/g, " ");
790
+ }
791
+
645
792
  /** The lines a bot page shows for its scheduled prompts. */
646
793
  export function scheduledMarkdown(entries: readonly ScheduledPrompt[], now: number): string[] {
647
794
  if (entries.length === 0) return ["Scheduled: none."];
@@ -653,8 +800,8 @@ export function scheduledMarkdown(entries: readonly ScheduledPrompt[], now: numb
653
800
  const ended =
654
801
  last?.result === undefined
655
802
  ? ""
656
- : `; last ${last.chatId === undefined ? "" : `chat ${last.chatId}: `}${last.result}`;
657
- lines.push(`- ${entry.name} (${entry.schedule}${state})${ended}`);
803
+ : `; last ${last.chatId === undefined ? "" : `chat ${last.chatId}: `}${markdownText(last.result)}`;
804
+ lines.push(`- ${markdownText(entry.name)} (${markdownCode(entry.schedule)}${state})${ended}`);
658
805
  }
659
806
  return lines;
660
807
  }
@@ -667,6 +814,9 @@ interface ScheduledSource {
667
814
  readonly logger: PluginBaseContext["logger"];
668
815
  readonly client: SourceContext["client"];
669
816
  readonly runs?: RunControl | undefined;
817
+ /** What a follow-up needs to put its message in the chat; without them none is sent. */
818
+ readonly facts?: SourceContext["facts"] | undefined;
819
+ readonly emit?: SourceContext["emit"] | undefined;
670
820
  }
671
821
 
672
822
  /** The bot's own source for scheduled prompts. */
@@ -707,14 +857,50 @@ export class BotScheduleSource {
707
857
  if (object.data.removed === true) continue;
708
858
  const bot = object.id;
709
859
  for (const entry of scheduledPrompts(object.data)) {
860
+ if (entry.runNow !== undefined) {
861
+ // The entry read here is stale after this; the next check handles its timed run.
862
+ await this.runNow(bot, entry, now);
863
+ continue;
864
+ }
710
865
  await this.one(bot, entry, now, catchUp);
711
866
  }
867
+ for (const followUp of followUps(object.data)) {
868
+ if (followUp.at <= now) await this.followUp(bot, followUp, now);
869
+ }
712
870
  }
713
871
  } finally {
714
872
  this.busy = false;
715
873
  }
716
874
  }
717
875
 
876
+ /**
877
+ * Sends a due follow-up into its chat (ADR 0030 D16). The entry is removed
878
+ * first, so a crash loses it rather than sends it twice. A late one, such as
879
+ * after `serve` was down, says when it was set for and how late it is.
880
+ */
881
+ private async followUp(bot: string, entry: FollowUp, now: number): Promise<void> {
882
+ const { facts, emit } = this.ctx;
883
+ if (facts === undefined || emit === undefined) return;
884
+ if (!(await removeFollowUp(this.ctx.store, bot, entry.id, "source:bot/follow-up"))) return;
885
+ const chat = await this.ctx.store.get(CHAT_TYPE, entry.chat);
886
+ if (chat === undefined || chatData(chat.data).closed) {
887
+ await this.chatWatches.log(`follow-up ${entry.id} of bot ${bot}: chat ${entry.chat} is closed or gone; dropped`);
888
+ return;
889
+ }
890
+ const lateMs = now - entry.at;
891
+ const parts = [`Follow-up you set for yourself: ${entry.text}`];
892
+ if (lateMs >= WAKE_GAP_MS) parts.push(latenessLine(entry.at, Math.floor(lateMs / 1_000)));
893
+ try {
894
+ await sendMessage(
895
+ { facts, emit: (event) => emit({ source: event.source, type: event.type, key: event.key, object: event.object ?? `${CHAT_TYPE}:${entry.chat}` }), store: this.ctx.store, home: this.ctx.home, actor: { via: SCHEDULE_SOURCE, id: "follow-up" }, source: SCHEDULE_SOURCE },
896
+ entry.chat,
897
+ parts.join("\n\n"),
898
+ );
899
+ } catch (error) {
900
+ await this.chatWatches.log(`follow-up ${entry.id} of bot ${bot}: ${messageOf(error)}`);
901
+ }
902
+ }
903
+
718
904
  private async bots(): Promise<readonly StoredObject[]> {
719
905
  const found: StoredObject[] = [];
720
906
  let cursor: string | undefined;
@@ -776,8 +962,34 @@ export class BotScheduleSource {
776
962
  minute = latest !== null && latest > last.plannedAt ? latest : null;
777
963
  }
778
964
  if (minute === null) return;
779
- const late = minute < minuteStart(now) || skipped.length > 0;
780
- await this.fire(bot, entry, minute, now, late, skipped);
965
+ await this.fire(bot, entry, minute, now, skipped);
966
+ }
967
+
968
+ /**
969
+ * Fires an entry once because a person asked. The request is cleared first, so
970
+ * a crash loses it rather than runs it twice. The planned time and schedule of
971
+ * `last` stay what the timed runs expect, so the next timed run is unchanged.
972
+ */
973
+ private async runNow(bot: string, entry: ScheduledPrompt, now: number): Promise<void> {
974
+ const cleared = await replaceEntry(
975
+ this.ctx.store,
976
+ bot,
977
+ entry.name,
978
+ (current) => (current.runNow === undefined ? undefined : { ...current, runNow: undefined }),
979
+ "source:bot/run-now",
980
+ );
981
+ if (cleared === undefined) return;
982
+ // A firing started since the request was made still owns `last`: drop the request.
983
+ if (isReplying(cleared.last)) {
984
+ await this.chatWatches.log(
985
+ `scheduled prompt "${entry.name}" of bot ${bot}: run now dropped, the previous firing is still replying`,
986
+ );
987
+ return;
988
+ }
989
+ const last = entry.last !== undefined && entry.last.schedule === entry.schedule ? entry.last : undefined;
990
+ const latest = latestCronMinute(parseCron(entry.schedule), now, CATCH_UP_DAYS);
991
+ const planned = last?.plannedAt ?? latest ?? minuteStart(now);
992
+ await this.fire(bot, entry, planned, now, [], true);
781
993
  }
782
994
 
783
995
  private async fire(
@@ -785,25 +997,25 @@ export class BotScheduleSource {
785
997
  entry: ScheduledPrompt,
786
998
  minute: number,
787
999
  now: number,
788
- late: boolean,
789
1000
  skipped: readonly number[],
1001
+ manual = false,
790
1002
  ): Promise<void> {
791
- const lateSecs = Math.floor((now - minute) / 1_000);
792
- await this.setLast(bot, entry.name, {
1003
+ const recorded = {
793
1004
  plannedAt: minute,
794
1005
  firedAt: now,
795
1006
  schedule: entry.schedule,
796
- });
797
- const prompt = late
798
- ? `${entry.prompt}\n\n${latenessLine(minute, lateSecs)}`
799
- : entry.prompt;
800
- const title = `${entry.name} (${localDate(minute)})`.slice(0, 120);
1007
+ ...(skipped.length > 0 ? { skippedEarlier: true } : {}),
1008
+ ...(manual ? { manual: true } : {}),
1009
+ };
1010
+ await this.setLast(bot, entry.name, recorded);
1011
+ const title = `${entry.name} (${localDate(manual ? now : minute)})`.slice(0, 120);
801
1012
  let chatId: string | undefined;
802
1013
  try {
803
1014
  const run = await this.ctx.client.act("bot:chat", `${BOT_TYPE}:${bot}`, {
804
1015
  args: {
805
1016
  title,
806
- message: prompt,
1017
+ // The person's own prompt; the bot:chat action adds what only the agent needs.
1018
+ message: entry.prompt,
807
1019
  ...(entry.model === undefined ? {} : { model: entry.model }),
808
1020
  ...(entry.effort === undefined ? {} : { effort: entry.effort }),
809
1021
  },
@@ -816,9 +1028,7 @@ export class BotScheduleSource {
816
1028
  } catch (error) {
817
1029
  const message = messageOf(error);
818
1030
  await this.setLast(bot, entry.name, {
819
- plannedAt: minute,
820
- firedAt: now,
821
- schedule: entry.schedule,
1031
+ ...recorded,
822
1032
  result: replySummary(`Could not start: ${message}`),
823
1033
  });
824
1034
  return;
@@ -838,7 +1048,7 @@ export class BotScheduleSource {
838
1048
  "step:bot/scheduled",
839
1049
  );
840
1050
  if (changed === undefined) return;
841
- await this.watch(bot, entry.name, minute, chatId);
1051
+ await this.watch(bot, entry.name, manual ? now : minute, chatId);
842
1052
  if (skipped.length > 0) {
843
1053
  await this.chatWatches.log(
844
1054
  `scheduled prompt "${entry.name}" of bot ${bot}: skipped ${skipped
@@ -868,27 +1078,42 @@ export class BotScheduleSource {
868
1078
  if (chat === undefined) return undefined;
869
1079
  const reply = [...read.messages].reverse().find((message) => message.role === "assistant");
870
1080
  const failure = [...read.entries].reverse().find((item) => item.kind === "failure");
871
- const result =
872
- reply === undefined
1081
+ // A failure after the reply means the run did not end quietly.
1082
+ const failedAfter = reply !== undefined && failure !== undefined && failure.sequence > reply.sequence;
1083
+ const quiet = reply !== undefined && !failedAfter && isQuietReply(reply.text);
1084
+ const result = quiet
1085
+ ? SCHEDULE_QUIET_RESULT
1086
+ : reply === undefined
873
1087
  ? failure === undefined
874
1088
  ? undefined
875
1089
  : replySummary(failure.text ?? "The reply failed.")
876
- : replySummary(reply.text);
1090
+ : failedAfter
1091
+ ? replySummary(failure.text ?? "The reply failed.")
1092
+ : replySummary(reply.text);
877
1093
  if (result === undefined) return undefined;
878
1094
  const title = typeof chat.data.title === "string" ? chat.data.title : chatId;
879
- return { result, title };
1095
+ return { result, title, quiet };
880
1096
  },
881
- async ({ result, title }) => {
1097
+ async ({ result, title, quiet }) => {
882
1098
  await replaceEntry(
883
1099
  this.ctx.store,
884
1100
  bot,
885
1101
  name,
886
1102
  (entry) =>
887
1103
  entry.last?.chatId === chatId
888
- ? { ...entry, last: { ...entry.last, result, notified: false } }
1104
+ ? {
1105
+ ...entry,
1106
+ last: { ...entry.last, result, notified: quiet },
1107
+ recent: [
1108
+ ...(entry.recent ?? []).filter((item) => item.plannedAt !== plannedAt),
1109
+ { plannedAt, result },
1110
+ ].slice(-SCHEDULE_RECENT_COUNT),
1111
+ }
889
1112
  : undefined,
890
1113
  "step:bot/scheduled",
891
1114
  );
1115
+ // A quiet ending records its result and runs no notify command.
1116
+ if (quiet) return;
892
1117
  try {
893
1118
  await this.notify({ chatId, title, summary: result });
894
1119
  } catch (error) {
@@ -917,7 +1142,7 @@ export class BotScheduleSource {
917
1142
  for (const entry of scheduledPrompts(object.data)) {
918
1143
  const last = entry.last;
919
1144
  if (last?.chatId === undefined || last.notified === true) continue;
920
- await this.watch(object.id, entry.name, last.plannedAt, last.chatId);
1145
+ await this.watch(object.id, entry.name, last.manual === true && last.firedAt !== undefined ? last.firedAt : last.plannedAt, last.chatId);
921
1146
  }
922
1147
  }
923
1148
  }
package/src/setup-dev.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * writes the file and asks `dev` to register the repository.
7
7
  */
8
8
 
9
- import { execFileSync } from "node:child_process";
9
+ import { execFileSync, spawnSync } from "node:child_process";
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
12
12
  import { isAbsolute, join, resolve } from "node:path";
@@ -19,7 +19,7 @@ import {
19
19
  type CommandContext,
20
20
  type ObjectStore,
21
21
  } from "@operad-io/engine";
22
- import { writeFileAtomic } from "@operad-io/engine/platform";
22
+ import { findGit, writeFileAtomic } from "@operad-io/engine/platform";
23
23
  import { BotError, readBots } from "./bot.ts";
24
24
  import { setupDevPrompt } from "./setup.ts";
25
25
 
@@ -52,8 +52,10 @@ export const SETUP_DEV_INSTRUCTION =
52
52
  "To set up dev for a repository (Setup Dev), call the operad `command` tool with plugin `bot`, verb `setup-dev`, my bot and the repository's directory and no input: it answers with the steps. Nothing is turned on until I approve the proposal in Pending.";
53
53
 
54
54
  function git(directory: string, args: readonly string[]): string | undefined {
55
+ const program = findGit();
56
+ if (program === undefined) return undefined;
55
57
  try {
56
- return execFileSync("git", ["-C", directory, ...args], {
58
+ return execFileSync(program, ["-C", directory, ...args], {
57
59
  encoding: "utf8",
58
60
  stdio: ["ignore", "pipe", "ignore"],
59
61
  }).trim();
@@ -62,17 +64,36 @@ function git(directory: string, args: readonly string[]): string | undefined {
62
64
  }
63
65
  }
64
66
 
67
+ // The top of the work tree `directory` is in; undefined when there is no git
68
+ // program or git says, in English, that the folder is in no work tree. Any other
69
+ // refusal (dubious ownership, an unreadable .git, nothing printed) is an error
70
+ // carrying git's message: the folder may be a repository.
71
+ function toplevelOf(directory: string): string | undefined {
72
+ const program = findGit();
73
+ if (program === undefined) return undefined;
74
+ const result = spawnSync(program, ["-C", directory, "rev-parse", "--show-toplevel"], {
75
+ encoding: "utf8",
76
+ env: { ...process.env, LC_ALL: "C", LANGUAGE: "" },
77
+ });
78
+ const top = (result.stdout ?? "").trim();
79
+ if (result.status === 0 && top.length > 0) return top;
80
+ const reason = (result.stderr ?? "").trim();
81
+ if (result.status !== 0 && /not a git repository|this operation must be run in a work tree/i.test(reason)) {
82
+ return undefined;
83
+ }
84
+ throw new BotError(`setup-dev: git cannot tell what "${directory}" is: ${reason.length > 0 ? reason : "it printed nothing"}`);
85
+ }
86
+
65
87
  function rootOf(path: string): string {
66
88
  if (!existsSync(path) || !statSync(path).isDirectory()) {
67
89
  throw new BotError(`setup-dev: there is no directory "${path}"`);
68
90
  }
69
91
  const real = realpathSync(path);
70
- const top = git(real, ["rev-parse", "--show-toplevel"]);
71
- if (top === undefined || top.length === 0 || realpathSync(top) !== real) {
72
- throw new BotError(`setup-dev: "${path}" is not the root of a git work tree`);
73
- }
74
- if ((git(real, ["remote"]) ?? "").length === 0) {
75
- throw new BotError(`setup-dev: "${path}" has no git remote; add one first`);
92
+ // A folder needs git only to create a task: without the program, or in no
93
+ // repository, it is set up as it is. A subfolder of a repository is refused.
94
+ const top = toplevelOf(real);
95
+ if (top !== undefined && realpathSync(top) !== real) {
96
+ throw new BotError(`setup-dev: "${path}" is inside the git repository at "${top}"; use "${top}" instead`);
76
97
  }
77
98
  return real;
78
99
  }
@@ -121,6 +142,13 @@ export async function proposeDev(
121
142
  throw new BotError(`setup-dev: the dev.json text is not JSON: ${messageOf(error)}`);
122
143
  }
123
144
  if (!isRecord(parsed)) throw new BotError("setup-dev: the dev.json text must be a JSON object");
145
+ // A repository with no remote works on its local main branch: the file names none.
146
+ if ((git(repo, ["remote"]) ?? "").length === 0) delete parsed.remote;
147
+ // Without a repository the work is done in the folder itself, whatever the text says.
148
+ if (toplevelOf(repo) === undefined) {
149
+ parsed.workIn = "branch";
150
+ delete parsed.concurrency;
151
+ }
124
152
  if ((await registeredPaths(store)).some((path) => resolve(path) === repo)) {
125
153
  throw new BotError(`setup-dev: "${repo}" is already registered`);
126
154
  }