Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(backup): export and restore limit_reset and cron routines

Ooi Pin Jun24a632800fd9
diff --git a/server/routine-request-schemas.ts b/server/routine-request-schemas.ts
index 318c34eecb..b1f7de2282 100644
--- a/server/routine-request-schemas.ts
+++ b/server/routine-request-schemas.ts
@@ -1,19 +1,14 @@
// The shapes a routine request takes: the tool input a bot sends, and the normalized operation a card stores.
import { z } from "zod";
-import { normalizeCronSchedule } from "../shared/routine-schedule.ts";
+import {
+ ENGINE_ID, MAX_DATE_MS, TIME, intervalWindowMinutes, refineStoredInterval, storedCronScheduleSchema,
+ storedIntervalWindowSchema, storedLimitResetDefinition, storedWeekdaysSchema,
+} from "../shared/routine-schedule-schema.ts";
import type { JsonValue } from "./schema.ts";
-export const TIME = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
+export { ENGINE_ID, MAX_DATE_MS, TIME, intervalWindowMinutes, storedCronScheduleSchema, storedIntervalWindowSchema, storedWeekdaysSchema };
export const ROUTINE_ID = /^[A-Za-z0-9_-]{1,128}$/;
-export const MAX_DATE_MS = 8_640_000_000_000_000;
-export const ENGINE_ID = /^[\w.:-]{1,128}$/;
-
-export function intervalWindowMinutes(window: { start: string; end: string }): number {
- const [startHour, startMinute] = window.start.split(":").map(Number);
- const [endHour, endMinute] = window.end.split(":").map(Number);
- return endHour * 60 + endMinute - (startHour * 60 + startMinute);
-}
export const jsonObjectSchema = z.record(z.string(), z.custom<JsonValue>());
export const toolIntervalWindowSchema = z.object({
@@ -77,29 +72,9 @@ export const routineProposalSchema = z.discriminatedUnion("action", [
z.object({ action: z.literal("delete"), routineId: z.string().max(128), forBot: targetBotSchema.optional() }).strict(),
]);
-export const storedWeekdaysSchema = z.array(z.number().int().min(0).max(6)).min(1).max(7).refine(
- (weekdays) => new Set(weekdays).size === weekdays.length,
- "Stored routine weekdays must be unique",
-);
-export const storedIntervalWindowSchema = z.object({
- start: z.string().regex(TIME),
- end: z.string().regex(TIME),
-}).strict().refine(
- ({ start, end }) => start < end,
- "Stored interval window must end later on the same day",
-);
-export const storedCronScheduleSchema = z.object({
- type: z.literal("cron"), expression: z.string().max(256), timeZone: z.string().max(128),
-}).strict().superRefine((schedule, context) => {
- try {
- normalizeCronSchedule(schedule);
- } catch (error) {
- context.addIssue({ code: "custom", message: error instanceof Error ? error.message : "Invalid stored cron schedule" });
- }
-});
export const storedScheduleSchema = z.discriminatedUnion("type", [
storedCronScheduleSchema,
- z.object({ type: z.literal("limit_reset"), engine: z.string().regex(ENGINE_ID), repeat: z.enum(["once", "every_reset"]) }).strict(),
+ z.object({ type: z.literal("limit_reset"), ...storedLimitResetDefinition }).strict(),
z.object({ type: z.literal("once"), at: z.number().int().nonnegative() }).strict(),
z.object({
type: z.literal("daily"),
@@ -114,26 +89,10 @@ export const storedScheduleSchema = z.discriminatedUnion("type", [
window: storedIntervalWindowSchema.optional(),
endsAt: z.number().int().nonnegative().max(MAX_DATE_MS).optional(),
}).strict(),
-]).superRefine((schedule, context) => {
- if (schedule.type !== "interval") return;
- if (schedule.window && intervalWindowMinutes(schedule.window) < schedule.everyMinutes) {
- context.addIssue({
- code: "custom",
- message: "Stored interval window must be at least as long as the cadence",
- path: ["window"],
- });
- }
- if (schedule.endsAt !== undefined && schedule.anchorAt !== undefined && schedule.endsAt < schedule.anchorAt) {
- context.addIssue({
- code: "custom",
- message: "Stored interval end must not be before its anchor",
- path: ["endsAt"],
- });
- }
-});
+]).superRefine((schedule, context) => refineStoredInterval(schedule, context));
export const storedScheduleChangesSchema = z.discriminatedUnion("type", [
storedCronScheduleSchema,
- z.object({ type: z.literal("limit_reset"), engine: z.string().regex(ENGINE_ID), repeat: z.enum(["once", "every_reset"]) }).strict(),
+ z.object({ type: z.literal("limit_reset"), ...storedLimitResetDefinition }).strict(),
z.object({ type: z.literal("once"), at: z.number().int().nonnegative() }).strict(),
z.object({
type: z.literal("daily"),
@@ -148,28 +107,7 @@ export const storedScheduleChangesSchema = z.discriminatedUnion("type", [
window: storedIntervalWindowSchema.nullable().optional(),
endsAt: z.number().int().nonnegative().max(MAX_DATE_MS).nullable().optional(),
}).strict(),
-]).superRefine((schedule, context) => {
- if (schedule.type !== "interval") return;
- if (schedule.window && intervalWindowMinutes(schedule.window) < schedule.everyMinutes) {
- context.addIssue({
- code: "custom",
- message: "Stored interval window must be at least as long as the cadence",
- path: ["window"],
- });
- }
- if (
- schedule.endsAt !== undefined &&
- schedule.endsAt !== null &&
- schedule.anchorAt !== undefined &&
- schedule.endsAt < schedule.anchorAt
- ) {
- context.addIssue({
- code: "custom",
- message: "Stored interval end must not be before its anchor",
- path: ["endsAt"],
- });
- }
-});
+]).superRefine((schedule, context) => refineStoredInterval(schedule, context));
export const storedDefinitionSchema = z.object({
name: z.string().trim().min(1).max(80),
instructions: z.string().trim().min(1).max(20_000),
diff --git a/server/team-backup.test.ts b/server/team-backup.test.ts
index ad145c3c88..039aee5f61 100644
--- a/server/team-backup.test.ts
+++ b/server/team-backup.test.ts
@@ -7,21 +7,30 @@ import { Store, UNTITLED_TASK } from "./store.ts";
import { RoutineManager } from "./routines.ts";
import { createTeamBackup, importTeamBackup } from "./team-backup.ts";
import { parseTeamBackup } from "../shared/team-backup.ts";
+import { AFTER_RESET_MS } from "../shared/limit-reset.ts";
import { approvalModeFor } from "../shared/approval-mode.ts";
import { WIDGET_SAMPLES } from "../shared/widget-samples.ts";
import { soulFile, soulHash } from "./bot-folder.ts";
import { appendMemoryLog, readMemoryFile, readMemoryLog, readMemoryTopic, searchMemoryFiles, updateMemory, workspaceDir, writeMemoryTopic } from "./workspace.ts";
const selection = () => ({ instanceId: "fixture", model: "fixture-model" });
+const KNOWN_RESET_AT = Date.parse("2026-11-26T12:00:00.000Z");
+const knownLimitResetAt = (engine: string) => engine === "claude" ? KNOWN_RESET_AT : null;
-function fixture() {
- const store = new Store(selection);
- const routines = new RoutineManager({
+function openRoutines(store: Store, options: { limitResetAt?: (engine: string) => number | null; file?: string } = {}) {
+ return new RoutineManager({
+ ...(options.file ? { file: options.file } : {}),
+ ...(options.limitResetAt ? { limitResetAt: options.limitResetAt } : {}),
botState: (id) => store.bot(id) ? "ready" : "missing",
goalState: (id, botId) => store.group(id ?? "")?.memberIds.includes(botId) ? "ready" : "missing",
createTask: (id, title) => store.createTask(id, title),
startTurn: async () => { throw new Error("Import must never run a bot"); },
});
+}
+
+function fixture(options: { limitResetAt?: (engine: string) => number | null } = {}) {
+ const store = new Store(selection);
+ const routines = openRoutines(store, options);
const chief = store.createBot({ name: "Mira", section: "Engineering", description: "Full instructions\n".repeat(400) }, { seedMessages: false });
store.setSoul(chief.id, " Cite sources.\nRespect the user's current request. 🐭\n");
const scout = store.createBot({ name: "Scout", section: "Engineering", mascotBody: "circle", mascotFaceColor: "black", mascotBodyColor: "#12ab9f", mascotMaterial: "fluffy" }, { seedMessages: false });
@@ -57,6 +66,17 @@ function fixture() {
return { store, routines, chief, scout, otherChief, archived, group };
}
+function portableBackup(store: Store, routines: RoutineManager, name: string) {
+ return JSON.parse(JSON.stringify(createTeamBackup(store, routines.listRoutines(), name))) as ReturnType<typeof createTeamBackup>;
+}
+
+function restoredRoutine(store: Store, routines: RoutineManager, backup: ReturnType<typeof portableBackup>, name: string) {
+ const imported = importTeamBackup(store, routines, backup, selection());
+ const owner = imported.bots.find((bot) => bot.name === "Mira 2")!;
+ const routine = imported.routines.find((item) => item.name === name)!;
+ return { owner, routine };
+}
+
describe("additive portable team backups", () => {
beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
@@ -180,6 +200,111 @@ describe("additive portable team backups", () => {
expect(readMemoryFile(noMemory.id).text).toBe("");
});
+ it("exports a disabled limit-reset routine and restores it paused on its new owner", () => {
+ const { store, routines, chief } = fixture();
+ const created = routines.create({
+ name: "After Claude resets", prompt: "Finish the report.", botId: chief.id, enabled: false,
+ schedule: { type: "limit_reset", engine: "claude", repeat: "once" },
+ });
+ const backup = portableBackup(store, routines, "Limit reset once");
+ const saved = backup.routines.find((routine) => routine.name === "After Claude resets")!;
+ expect(saved.schedule).toEqual(created.schedule);
+ const { owner, routine } = restoredRoutine(store, routines, backup, "After Claude resets");
+ expect(routine.schedule).toEqual(created.schedule);
+ expect(routine.botId).toBe(owner.id);
+ expect(routine.enabled).toBe(false);
+ expect(routine.nextRunAt).toBeNull();
+ });
+
+ it("exports a disabled limit-reset routine that repeats every reset", () => {
+ const { store, routines, chief } = fixture();
+ const created = routines.create({
+ name: "Every Claude reset", prompt: "Pick up the next report.", botId: chief.id, enabled: false,
+ schedule: { type: "limit_reset", engine: "claude", repeat: "every_reset" },
+ });
+ const backup = portableBackup(store, routines, "Limit reset repeat");
+ const saved = backup.routines.find((routine) => routine.name === "Every Claude reset")!;
+ expect(saved.schedule).toEqual(created.schedule);
+ const { owner, routine } = restoredRoutine(store, routines, backup, "Every Claude reset");
+ expect(routine.schedule).toEqual(created.schedule);
+ expect(routine.botId).toBe(owner.id);
+ expect(routine.enabled).toBe(false);
+ expect(routine.nextRunAt).toBeNull();
+ });
+
+ it("preserves a known limit-reset time through backup and import with the same provider", () => {
+ const { store, routines, chief } = fixture({ limitResetAt: knownLimitResetAt });
+ const created = routines.create({
+ name: "Known Claude reset", prompt: "Continue after the known reset.", botId: chief.id, enabled: false,
+ schedule: { type: "limit_reset", engine: "claude", repeat: "once" },
+ });
+ expect(created.schedule).toEqual({ type: "limit_reset", engine: "claude", repeat: "once", at: KNOWN_RESET_AT + AFTER_RESET_MS });
+ const backup = portableBackup(store, routines, "Known limit reset");
+ const saved = backup.routines.find((routine) => routine.name === "Known Claude reset")!;
+ expect(saved.schedule).toEqual(created.schedule);
+ const { owner, routine } = restoredRoutine(store, routines, backup, "Known Claude reset");
+ expect(routine.schedule).toEqual(created.schedule);
+ expect(routine.botId).toBe(owner.id);
+ expect(routine.enabled).toBe(false);
+ expect(routine.nextRunAt).toBeNull();
+ });
+
+ it("keeps a limit-reset snapshot in the file and pauses the import when the destination has no reset time", () => {
+ const { store, routines, chief } = fixture({ limitResetAt: knownLimitResetAt });
+ const created = routines.create({
+ name: "Snapshot Claude reset", prompt: "Keep the snapshot.", botId: chief.id, enabled: false,
+ schedule: { type: "limit_reset", engine: "claude", repeat: "once" },
+ });
+ const backup = portableBackup(store, routines, "Limit reset snapshot");
+ const saved = backup.routines.find((routine) => routine.name === "Snapshot Claude reset")!;
+ expect(saved.schedule).toEqual(created.schedule);
+ expect(saved.schedule).toEqual({ type: "limit_reset", engine: "claude", repeat: "once", at: KNOWN_RESET_AT + AFTER_RESET_MS });
+ const destination = openRoutines(store, { file: join(DATA_DIR, "routines-no-reset.json") });
+ const { owner, routine } = restoredRoutine(store, destination, backup, "Snapshot Claude reset");
+ expect(routine.schedule).toEqual({ type: "limit_reset", engine: "claude", repeat: "once", at: null });
+ expect(routine.botId).toBe(owner.id);
+ expect(routine.enabled).toBe(false);
+ expect(routine.nextRunAt).toBeNull();
+ });
+
+ it("exports an enabled cron routine and restores it paused", () => {
+ const { store, routines, chief } = fixture();
+ const created = routines.create({
+ name: "Weekday cron", prompt: "Send the weekday brief.", botId: chief.id, enabled: true,
+ schedule: { type: "cron", expression: "15 9 * * 1-5", timeZone: "Asia/Kuala_Lumpur" },
+ });
+ expect(created.enabled).toBe(true);
+ const backup = portableBackup(store, routines, "Cron");
+ const saved = backup.routines.find((routine) => routine.name === "Weekday cron")!;
+ expect(saved.schedule).toEqual(created.schedule);
+ const { owner, routine } = restoredRoutine(store, routines, backup, "Weekday cron");
+ expect(routine.schedule).toEqual(created.schedule);
+ expect(routine.botId).toBe(owner.id);
+ expect(routine.enabled).toBe(false);
+ expect(routine.nextRunAt).toBeNull();
+ });
+
+ it("round-trips an interval's weekdays, window and end", () => {
+ const { store, routines, chief } = fixture();
+ const anchorAt = Date.UTC(2026, 7, 17, 8, 5);
+ const endsAt = Date.UTC(2099, 0, 1);
+ const created = routines.create({
+ name: "Support hours", prompt: "Check during support hours.", botId: chief.id, enabled: true,
+ schedule: {
+ type: "interval", everyMinutes: 30, anchorAt,
+ weekdays: [1, 3, 5], window: { start: "09:00", end: "17:00" }, endsAt,
+ },
+ });
+ const backup = portableBackup(store, routines, "Constrained interval");
+ const saved = backup.routines.find((routine) => routine.name === "Support hours")!;
+ expect(saved.schedule).toEqual(created.schedule);
+ const { owner, routine } = restoredRoutine(store, routines, backup, "Support hours");
+ expect(routine.schedule).toEqual(created.schedule);
+ expect(routine.botId).toBe(owner.id);
+ expect(routine.enabled).toBe(false);
+ expect(routine.nextRunAt).toBeNull();
+ });
+
it("round-trips all bots, sections, Chiefs, rooms, tasks and branches without changing originals", () => {
const { store, routines, chief, scout, otherChief, archived, group } = fixture();
const backup = createTeamBackup(store, routines.listRoutines(), "My team");
diff --git a/shared/routine-schedule-schema.ts b/shared/routine-schedule-schema.ts
new file mode 100644
index 0000000000..97d0debe7c
--- /dev/null
+++ b/shared/routine-schedule-schema.ts
@@ -0,0 +1,71 @@
+import { z } from "zod";
+
+import { normalizeCronSchedule } from "./routine-schedule.ts";
+
+export const TIME = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
+export const MAX_DATE_MS = 8_640_000_000_000_000;
+export const ENGINE_ID = /^[\w.:-]{1,128}$/;
+
+export function intervalWindowMinutes(window: { start: string; end: string }): number {
+ const [startHour, startMinute] = window.start.split(":").map(Number);
+ const [endHour, endMinute] = window.end.split(":").map(Number);
+ return endHour * 60 + endMinute - (startHour * 60 + startMinute);
+}
+
+export const storedWeekdaysSchema = z.array(z.number().int().min(0).max(6)).min(1).max(7).refine(
+ (weekdays) => new Set(weekdays).size === weekdays.length,
+ "Stored routine weekdays must be unique",
+);
+export const storedIntervalWindowSchema = z.object({
+ start: z.string().regex(TIME),
+ end: z.string().regex(TIME),
+}).strict().refine(
+ ({ start, end }) => start < end,
+ "Stored interval window must end later on the same day",
+);
+export const storedCronScheduleSchema = z.object({
+ type: z.literal("cron"), expression: z.string().max(256), timeZone: z.string().max(128),
+}).strict().superRefine((schedule, context) => {
+ try {
+ normalizeCronSchedule(schedule);
+ } catch (error) {
+ context.addIssue({ code: "custom", message: error instanceof Error ? error.message : "Invalid stored cron schedule" });
+ }
+});
+export const storedLimitResetDefinition = {
+ engine: z.string().regex(ENGINE_ID),
+ repeat: z.enum(["once", "every_reset"]),
+};
+export const storedLimitResetAtSchema = z.number().int().positive().max(MAX_DATE_MS).nullable();
+
+export function refineStoredInterval(
+ schedule: {
+ type: string;
+ everyMinutes?: number;
+ window?: { start: string; end: string } | null;
+ endsAt?: number | null;
+ anchorAt?: number;
+ },
+ context: { addIssue(issue: { code: "custom"; message: string; path: string[] }): void },
+): void {
+ if (schedule.type !== "interval") return;
+ if (schedule.window && schedule.everyMinutes !== undefined && intervalWindowMinutes(schedule.window) < schedule.everyMinutes) {
+ context.addIssue({
+ code: "custom",
+ message: "Stored interval window must be at least as long as the cadence",
+ path: ["window"],
+ });
+ }
+ if (
+ schedule.endsAt !== undefined &&
+ schedule.endsAt !== null &&
+ schedule.anchorAt !== undefined &&
+ schedule.endsAt < schedule.anchorAt
+ ) {
+ context.addIssue({
+ code: "custom",
+ message: "Stored interval end must not be before its anchor",
+ path: ["endsAt"],
+ });
+ }
+}
diff --git a/shared/team-backup.ts b/shared/team-backup.ts
index ddb1ceac1b..46a5a5ee38 100644
--- a/shared/team-backup.ts
+++ b/shared/team-backup.ts
@@ -2,6 +2,10 @@ import { z } from "zod";
import { mascotBodyColorSchema, mascotFaceColorSchema, mascotMaterialSchema } from "./bot-avatar.ts";
import { CONNECTOR_SLUG_PATTERN, CONNECTOR_TOOL_NAME_PATTERN, MAUS_COLOR_NAMES } from "./wire.ts";
+import {
+ MAX_DATE_MS, refineStoredInterval, storedCronScheduleSchema, storedIntervalWindowSchema, storedLimitResetAtSchema,
+ storedLimitResetDefinition, storedWeekdaysSchema,
+} from "./routine-schedule-schema.ts";
import { parseToolScope, type ToolScope } from "./tool-scope.ts";
export const MAX_TEAM_BACKUP_BYTES = 50 * 1024 * 1024;
@@ -67,9 +71,18 @@ const playbook = z.object({
instructions: z.string().max(200_000),
});
const schedule = z.discriminatedUnion("type", [
- z.object({ type: z.literal("once"), at: timestamp }),
+ storedCronScheduleSchema,
+ z.object({ type: z.literal("limit_reset"), ...storedLimitResetDefinition, at: storedLimitResetAtSchema }).strict(),
+ z.object({ type: z.literal("once"), at: z.number().finite().min(-MAX_DATE_MS).max(MAX_DATE_MS) }),
z.object({ type: z.literal("daily"), time: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/), weekdays: z.array(z.number().int().min(0).max(6)).min(1).max(7) }),
- z.object({ type: z.literal("interval"), everyMinutes: z.number().int().min(5).max(1440), anchorAt: z.number().int().min(0).max(8_640_000_000_000_000) }),
+ z.object({
+ type: z.literal("interval"),
+ everyMinutes: z.number().int().min(5).max(1_440),
+ anchorAt: z.number().int().nonnegative().max(MAX_DATE_MS),
+ weekdays: storedWeekdaysSchema.optional(),
+ window: storedIntervalWindowSchema.optional(),
+ endsAt: z.number().int().nonnegative().max(MAX_DATE_MS).optional(),
+ }).strict().superRefine((value, context) => refineStoredInterval(value, context)),
]);
// A bot's memory travels with it, in the same plain markdown it lives in:
// the person's accumulated corrections are part of who the bot is. The