Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): bound event receipts and defer routines during scheduler startup
Chris1f607d921b38
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 2f7df0a927..a1ef83b405 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -958,7 +958,7 @@ import { pickNativeAtResource } from './nativeAtResourcePicker.js';import {startScheduler,resetScheduler,- getScheduler,+ getSchedulerIfInitialized,getScheduleStorage,getScheduleStorageIfInitialized,getProjectAutomationLoader,@@ -1014,7 +1014,7 @@ async function waitForCurrentAccountProviderModelsReady(): Promise<void> {}// Live getters preserve account/scheduler replacement without loading Main modules at dispatch time.-configureRoutineHost({ getBot: getBotRemoteResourceSource, getScheduler, getScheduleStorage });+configureRoutineHost({ getBot: getBotRemoteResourceSource, getScheduler: getSchedulerIfInitialized, getScheduleStorage });/*** Phase 4: 不再用 `_schedulerStarted` flag —— `startScheduler()` 内部以 `_scheduler`diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 7c262b8b8b..9b66514e7e 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -1477,6 +1477,10 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册返回 {ok:true,accepted,duplicate} 表示事件已持久接收(accepted 是匹配例行任务数),不代表模型已运行或业务已成功。ok:false 时保留投递 ID,按退避重试;不可假报已处理。多条件 OR 命中只入队一次;运行期间的新事件可合并进下一轮。重启不自动重放已经开始、结果未知的执行,以免重复外部副作用。时间与事件共用运行历史。去重针对投递身份,业务对象已完成与否仍由任务指令和工具记录判断。+宿主硬上限:单插件每 60 秒最多 60 次发布,全账号最多 240 次;待处理发布请求分别最多 8 和 32。+去重窗口为 24 小时,回执按 UTF-8 JSON 限制为单插件 256 KiB、账号 2 MiB;超限返回 ok:false,+应保留原 event.id 稍后重试,不要改 ID 或紧密循环重试。容量满时不会驱逐窗口内回执;旧版过量+回执在启动时保留最新的有界部分。事件运行历史不受回执清理影响。意识是 Cindy 的第三方能力包,文件形态是 \`.cindy\`(zip 包)。装入后可给主机叠加:AI 可调用的工具、常驻界面面板、模型代办能力。本手册教你(agent)替用户diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.tsindex 41e3863249..cf23f9ef96 100644--- a/apps/desktop/src/main/routines/__tests__/service.test.ts+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';const mock = vi.hoisted(() => ({scope: 'owner-a',boundaryPending: false,+ schedulerReady: true,load: vi.fn<() => Promise<RoutineState | null>>(async () => null),profiles: [] as Array<{ id: string; status: string }>,save: vi.fn<(state: RoutineState) => Promise<void>>(async () => {}),@@ -51,7 +52,7 @@ vi.mock('../store.js', () => ({import { configureRoutineHost, getRoutineEngine, routineTools, stopRoutines, updateBotRoutineLifecycle } from '../service.js';beforeEach(() => configureRoutineHost({getBot: mock.getBot,- getScheduler: () => mock.scheduler,+ getScheduler: () => mock.schedulerReady ? mock.scheduler : null,getScheduleStorage: () => mock.storage,}));afterEach(async () => {@@ -59,6 +60,7 @@ afterEach(async () => {vi.clearAllMocks();mock.scope = 'owner-a';mock.boundaryPending = false;+ mock.schedulerReady = true;mock.load.mockResolvedValue(null);mock.storage.get.mockResolvedValue(null);mock.profiles = [];@@ -292,3 +294,39 @@ it.each(['explicit', 'timer', 'replacement'] as const)('waits for execution andexpect(mock.load).toHaveBeenCalledTimes(2);expect(mock.scheduler.runNow).toHaveBeenCalledOnce();});++it('retains a restored batch until scheduler startup completes, then executes the same run once', async () => {+ vi.useFakeTimers();+ const engine = await getRoutineEngine();+ const routine = await engine.put('bot', {+ name: 'Restored', prompt: 'Check the PR', enabled: true,+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],+ });+ const saved = structuredClone(mock.save.mock.calls.at(-1)![0]);+ saved.runs = [{ id: 'restored-batch', routineId: routine.id, revision: 1, triggerIds: ['manual'], events: [], status: 'queued', createdAt: 1 }];+ await stopRoutines();+ mock.load.mockResolvedValue(saved);+ mock.profiles = [{ id: 'bot', status: 'active' }];+ mock.schedulerReady = false;+ const restored = await getRoutineEngine();+ await vi.advanceTimersByTimeAsync(0);+ expect(restored.history(routine.id)).toEqual([expect.objectContaining({ id: 'restored-batch', status: 'queued' })]);+ expect(mock.storage.insert).not.toHaveBeenCalled();+ expect(mock.scheduler.runNow).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(29000);+ mock.schedulerReady = true;+ await vi.advanceTimersByTimeAsync(1000);+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();+ expect(restored.history(routine.id)).toEqual([expect.objectContaining({ id: 'restored-batch', status: 'success' })]);+});++it('does not classify an actual backing storage failure as scheduler cold start', async () => {+ const routine = await routineTools.save('bot', {+ name: 'Review', prompt: 'Check', enabled: true,+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],+ });+ mock.storage.get.mockRejectedValueOnce(new Error('storage unavailable'));+ await routineTools.runNow('bot', routine.id);+ await vi.waitFor(async () => expect((await routineTools.history('bot', routine.id))[0]).toMatchObject({ status: 'failed', error: 'storage unavailable' }));+ expect(mock.scheduler.runNow).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.tsindex 74536a7f94..035f749daa 100644--- a/apps/desktop/src/main/routines/service.ts+++ b/apps/desktop/src/main/routines/service.ts@@ -28,7 +28,7 @@ import { botProfiles } from '../localDb/schema.js';/** Bootstrap supplies live getters without a service -> scheduler -> IPC dependency cycle. */export interface RoutineHostDeps {getBot(botId: string): Promise<{ status: string; canonicalSessionId?: string | null }>;- getScheduler(): Pick<Scheduler, 'runNow' | 'pause' | 'delete'>;+ getScheduler(): Pick<Scheduler, 'runNow' | 'pause' | 'delete'> | null;getScheduleStorage(): Pick<ScheduleStorage, 'get' | 'insert' | 'update' | 'listRuns'>;}@@ -63,13 +63,14 @@ function assertScope(scope: string): void {/** Resolve the current canonical task at dispatch time, preserving its actual model and permissions. */async function execute(scope: string, routine: Routine, run: RoutineRun, signal: AbortSignal) {assertScope(scope);+ const scheduler = getRoutineHost().getScheduler();+ if (!scheduler) return { deferred: true };const bot = await getRoutineHost().getBot(routine.botId);assertScope(scope);if (signal.aborted) throw new Error('Routine cancelled');if (bot.status !== 'active' || !bot.canonicalSessionId)throw new Error('The teammate is unavailable');const storage = getRoutineHost().getScheduleStorage();- const scheduler = getRoutineHost().getScheduler();const id = `routine-${routine.id}`;const now = Date.now();const schedule: Schedule = {@@ -255,6 +256,7 @@ async function cleanBackingSchedules(scope: string, ids: string[], remove: booleif (!ids.length) return;assertScope(scope);const scheduler = getRoutineHost().getScheduler();+ if (!scheduler) throw new Error('Routine scheduler is not ready; retry later');const storage = getRoutineHost().getScheduleStorage();for (const id of ids) {const scheduleId = `routine-${id}`;diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.tsindex 0896d6b482..69e52aad15 100644--- a/apps/desktop/src/main/scheduler-host/index.ts+++ b/apps/desktop/src/main/scheduler-host/index.ts@@ -233,6 +233,11 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedulreturn scheduler;}+/** Cold-start probe for callers that own a durable deferred queue. */+export function getSchedulerIfInitialized(): Scheduler | null {+ return _scheduler;+}+export function getScheduler(): Scheduler {if (!_scheduler) {throw new Error('scheduler not started: call startScheduler() first');diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.mdindex 11bf333f63..c5eba9d5fe 100644--- a/docs/product-rules/bot-routines.md+++ b/docs/product-rules/bot-routines.md@@ -19,6 +19,8 @@所有执行复用伙伴 canonical task,继承模型、技能和实际权限,包括冷恢复时的权限。合成触发消息不作为用户聊天消息展示;有成果的输出由已有伙伴消息链呈现,空转复用静默策略。每条例行任务最多一个正在执行的运行;等待中的新事件合并为一批。不同规则共享伙伴时,由既有任务队列串行派发。+启动恢复时若调度器尚未就绪,同样保留原 queued 批次并在 30 秒后重试,不标记为失败。+伙伴忙碌导致的 deferred 保留同一待执行批次,30 秒后重试;宿主通过 runNow 的内部 deferToCaller 选项领取重试责任,底层不设置重试时间,不能由旧 backing schedule 另行重放旧事件。普通手动调度保持原有忙碌失败语义。已开始的执行失败不会自动重做,避免重复外部副作用。暂停或删除取消等待项并中止当前运行;修改规则取消旧版本等待项,下一次事件按新规则匹配。执行已结束但终态落盘失败时,保留执行结果和该规则的运行锁;后续触发只能排队,不能再次执行。每 30 秒只重试保存原结果,成功后才释放队列;若在此期间重启,沿用 interrupted 恢复,不重放已执行项。其它规则不因单条终态保存失败而被停用。@@ -82,6 +84,8 @@ const receipt = await cindy.routines.request({事件 data 只允许平坦字符串、数值、布尔值,单事件 JSON 限制 32000 字符;禁止提交令牌和凭证。筛选支持 equals、contains、not-equals,同一条件内部筛选为 AND。带 `originRoutineId` 的事件不会反向触发同一规则。等待批次达到 100 个事件后返回可重试错误,不静默丢事件。+宿主限制事件发布频率:单来源每 60 秒最多 60 次,全账号最多 240 次;待处理发布请求上限分别为 8 和 32,限速在解析负载和进入持久写入队列之前执行,状态重报不重置额度。去重回执保留 24 小时(过期项在后续接收或启动时清理),按 UTF-8 JSON 字节数限制为单来源 256 KiB、全账号 2 MiB。容量满时拒绝新事件并返回可重试错误,不驱逐窗口内回执;相同 ID 的已确认重投不重新写盘。启动时将旧版过量回执按时间从新到旧裁入上限,不改运行历史。+本协议不要求第三方连接器的固定组合:飞书长连接、Gmail 本地采集和 GitHub 事件适配器都可报告相同形态的事件。本次交付的是宿主接入与执行能力,不会自动给现有飞书/Gmail 插件增加第三方订阅;适配器需按上述协议接入。## 验证与边界diff --git a/packages/maker-scheduler/src/__tests__/routine-event-admission.test.ts b/packages/maker-scheduler/src/__tests__/routine-event-admission.test.tsnew file mode 100644index 0000000000..07797be034--- /dev/null+++ b/packages/maker-scheduler/src/__tests__/routine-event-admission.test.ts@@ -0,0 +1,47 @@+import { Buffer } from 'node:buffer';+import { expect, it } from 'vitest';+import { RoutineEventAdmission, ROUTINE_EVENT_LIMITS as limits, addRoutineReceipt, compactRoutineReceipts } from '../routine-event-admission.js';++it('enforces global frequency and pending limits across distinct authenticated sources', () => {+ const admission = new RoutineEventAdmission();+ const releases = Array.from({ length: limits.pendingGlobal }, (_, i) => admission.acquire(`source-${i}`, 1000));+ expect(() => admission.acquire('another', 1000)).toThrow('busy');+ releases.forEach((release) => release());+ for (let i = releases.length; i < limits.global; i++) admission.acquire(`source-${i}`, 1000)();+ expect(() => admission.acquire('another', 1000)).toThrow('rate limit');+ expect(() => admission.acquire('another', 1000 + limits.windowMs)()).not.toThrow();+});++it('migrates oversized legacy receipts by UTF-8 bytes, including source caps and TTL', () => {+ const now = limits.receiptTtlMs + 10000;+ const legacy: Record<string, number> = {};+ for (let source = 0; source < 12; source++) {+ for (let i = 0; i < 400; i++) legacy[JSON.stringify([`source-${source}`, `${'界'.repeat(250)}${i}`])] = now - i;+ }+ legacy[JSON.stringify(['expired', 'old'])] = now - limits.receiptTtlMs;+ const compact = compactRoutineReceipts(legacy, now);+ expect(Buffer.byteLength(JSON.stringify(compact))).toBeLessThanOrEqual(limits.receiptBytesGlobal);+ expect(compact[JSON.stringify(['expired', 'old'])]).toBeUndefined();+ for (let source = 0; source < 12; source++) {+ const own = Object.fromEntries(Object.entries(compact).filter(([key]) => JSON.parse(key)[0] === `source-${source}`));+ expect(Buffer.byteLength(JSON.stringify(own))).toBeLessThanOrEqual(limits.receiptBytesPerSource);+ }+ expect(Object.keys(compact).length).toBeLessThan(Object.keys(legacy).length);+ expect(compact[JSON.stringify(['source-0', `${'界'.repeat(250)}0`])]).toBe(now);+});++it('rejects new receipts at capacity without evicting live deduplication, then admits after expiry', () => {+ const now = 1000;+ const receipts: Record<string, number> = {};+ let i = 0;+ const key = () => JSON.stringify(['source', `${'界'.repeat(250)}${i++}`]);+ try { while (true) addRoutineReceipt(receipts, 'source', key(), now); } catch (error) {+ expect(String(error)).toContain('storage is full');+ }+ const saved = JSON.stringify(receipts);+ expect(() => addRoutineReceipt(receipts, 'source', key(), now)).toThrow('storage is full');+ expect(JSON.stringify(receipts)).toBe(saved);+ addRoutineReceipt(receipts, 'another', JSON.stringify(['another', 'independent']), now);+ addRoutineReceipt(receipts, 'source', key(), now + limits.receiptTtlMs);+ expect(Object.keys(receipts)).toHaveLength(1);+});diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.tsindex 64c990c5d3..cb214a967c 100644--- a/packages/maker-scheduler/src/__tests__/routines.test.ts+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts@@ -515,3 +515,48 @@ it('does not start execution if stop arrives while its running claim is being saexpect(f.execute).not.toHaveBeenCalled();expect(f.snapshot()?.runs[0].status).toBe('running');});++it('rate-limits unmatched events before writing, without resetting the limit on source status updates', async () => {+ const persist = vi.fn(async () => {});+ const f = await fixture(undefined, null, persist);+ for (let i = 0; i < 60; i++) await f.engine.publish('github', event(`unmatched-${i}`));+ const writes = persist.mock.calls.length;+ f.engine.registerSource({ id: 'github', name: 'GitHub', status: 'listening', events: [{ type: 'pr', name: 'PR', fields: [] }] });+ await expect(f.engine.publish('github', event('overflow'))).rejects.toThrow('rate limit');+ expect(persist).toHaveBeenCalledTimes(writes);+ f.advance(60_000);+ expect(await f.engine.publish('github', event('unmatched-0'))).toMatchObject({ duplicate: true });+ expect(persist).toHaveBeenCalledTimes(writes);+ await f.engine.publish('github', event('overflow'));+ expect(persist).toHaveBeenCalledTimes(writes + 1);+ await f.engine.stop();+});++it('bounds concurrent plugin requests before they enter the slow persistent write queue', async () => {+ let release!: () => void;+ let block = false;+ const f = await fixture(undefined, null, async () => {+ if (block) await new Promise<void>((resolve) => { release = resolve; });+ });+ block = true;+ const pending = Array.from({ length: 8 }, (_, i) => f.engine.publish('github', event(`pending-${i}`)));+ await expect(f.engine.publish('github', event('overflow'))).rejects.toThrow('busy');+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));+ block = false;+ release();+ await Promise.all(pending);+ expect(await f.engine.publish('github', event('overflow'))).toMatchObject({ duplicate: false });+ await f.engine.stop();+});++it('keeps committed deduplication across restart and expires it after the bounded window', async () => {+ const f = await fixture();+ await f.engine.publish('github', event('receipt'));+ await f.engine.stop();+ const restored = await fixture(undefined, f.snapshot());+ expect(await restored.engine.publish('github', event('receipt'))).toMatchObject({ duplicate: true });+ restored.advance(24 * 60 * 60_000);+ expect(await restored.engine.publish('github', event('receipt'))).toMatchObject({ duplicate: false });+ expect(Object.keys(restored.snapshot()!.receipts)).toHaveLength(1);+ await restored.engine.stop();+});diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.tsindex 8158793820..195c3a3af1 100644--- a/packages/maker-scheduler/src/routine-engine.ts+++ b/packages/maker-scheduler/src/routine-engine.ts@@ -1,3 +1,4 @@+import { RoutineEventAdmission, addRoutineReceipt, compactRoutineReceipts, receiptIsLive } from './routine-event-admission.js';import {matchesRoutineEvent,nextRoutineTriggerAt,@@ -67,6 +68,7 @@ export class RoutineEngine {next: {},};private readonly sources = new Map<string, RoutineSource>();+ private readonly eventAdmission = new RoutineEventAdmission();private readonly active = new Map<string, AbortController>();private readonly activeTasks = new Map<string, Promise<void>>();private readonly blockedBots = new Set<string>();@@ -95,6 +97,7 @@ export class RoutineEngine {for (const routine of saved.routines) parseRoutineInput(routine);this.state = saved;}+ this.state.receipts = compactRoutineReceipts(this.state.receipts, this.deps.now());for (const [botId, status] of botStates ?? []) this.applyBotState(this.state, botId, status);for (const botId of this.state.pausedBotIds ?? []) this.blockedBots.add(botId);// Removed rules have no history entry point; do not retain their event payloads.@@ -310,37 +313,39 @@ export class RoutineEngine {raw: unknown,isCurrent: () => boolean = () => true,): Promise<{ accepted: number; duplicate: boolean }> {- const event = parseRoutineEvent(raw);+ if (this.stopped) throw new Error("Routine service is stopped");const source = this.sources.get(sourceId);- if (- !source ||- source.status !== "listening" ||- !source.events.some((item) => item.type === event.type)- ) {- throw new Error(- "Event source is not listening or event type is undeclared",- );- }- const result = await this.change((state) => {+ if (!source || source.status !== "listening") throw new Error("Event source is not listening");+ const release = this.eventAdmission.acquire(sourceId, this.deps.now());+ try {+ const event = parseRoutineEvent(raw);+ if (!source.events.some((item) => item.type === event.type))+ throw new Error("Event type is undeclared");if (!isCurrent()) throw new Error("Event publisher is no longer active");const receipt = JSON.stringify([sourceId, event.id]);- if (Object.hasOwn(state.receipts, receipt))+ // A committed duplicate needs no clone or disk write. The queued check below handles races.+ if (receiptIsLive(this.state.receipts[receipt], this.deps.now()))return { accepted: 0, duplicate: true };- const matches = state.routines- .filter((routine) => !this.blockedBots.has(routine.botId) && !this.removing.has(routine.id))- .map((routine) => ({- routine,- ids: matchesRoutineEvent(routine, sourceId, event),- }))- .filter((match) => match.ids.length > 0);- for (const { routine, ids } of matches)- this.enqueue(state, routine, ids, { sourceId, event });- state.receipts[receipt] = this.deps.now();- return { accepted: matches.length, duplicate: false };- });- source.lastEventAt = this.deps.now();- this.pump();- return result;+ const result = await this.change((state) => {+ if (!isCurrent()) throw new Error("Event publisher is no longer active");+ const now = this.deps.now();+ if (receiptIsLive(state.receipts[receipt], now))+ return { accepted: 0, duplicate: true };+ addRoutineReceipt(state.receipts, sourceId, receipt, now);+ const matches = state.routines+ .filter((routine) => !this.blockedBots.has(routine.botId) && !this.removing.has(routine.id))+ .map((routine) => ({ routine, ids: matchesRoutineEvent(routine, sourceId, event) }))+ .filter((match) => match.ids.length > 0);+ for (const { routine, ids } of matches)+ this.enqueue(state, routine, ids, { sourceId, event });+ return { accepted: matches.length, duplicate: false };+ });+ source.lastEventAt = this.deps.now();+ this.pump();+ return result;+ } finally {+ release();+ }}async runNow(botId: string, id: string): Promise<void> {diff --git a/packages/maker-scheduler/src/routine-event-admission.ts b/packages/maker-scheduler/src/routine-event-admission.tsnew file mode 100644index 0000000000..cde50e6c16--- /dev/null+++ b/packages/maker-scheduler/src/routine-event-admission.ts@@ -0,0 +1,100 @@+import { Buffer } from 'node:buffer';++/** Host policy, not plugin-configurable. Receipts are bounded separately from user history. */+export const ROUTINE_EVENT_LIMITS = {+ windowMs: 60_000,+ perSource: 60,+ global: 240,+ pendingPerSource: 8,+ pendingGlobal: 32,+ receiptTtlMs: 24 * 60 * 60_000,+ receiptBytesPerSource: 256 * 1024,+ receiptBytesGlobal: 2 * 1024 * 1024,+} as const;++/** Reserve before parsing or joining the durable write queue, including duplicate requests. */+export class RoutineEventAdmission {+ private readonly windows = new Map<string, { start: number; count: number }>();+ private global = { start: 0, count: 0 };+ private readonly pending = new Map<string, number>();+ private totalPending = 0;++ acquire(sourceId: string, now: number): () => void {+ const limits = ROUTINE_EVENT_LIMITS;+ for (const [id, window] of this.windows)+ if (now - window.start >= limits.windowMs) this.windows.delete(id);+ if (now - this.global.start >= limits.windowMs) this.global = { start: now, count: 0 };+ const window = this.windows.get(sourceId) ?? { start: now, count: 0 };+ if (window.count >= limits.perSource || this.global.count >= limits.global)+ throw new Error('Routine event rate limit reached; retry after 60 seconds');+ const pending = this.pending.get(sourceId) ?? 0;+ if (pending >= limits.pendingPerSource || this.totalPending >= limits.pendingGlobal)+ throw new Error('Routine event intake is busy; retry later');+ window.count += 1;+ this.global.count += 1;+ this.windows.set(sourceId, window);+ this.pending.set(sourceId, pending + 1);+ this.totalPending += 1;+ return () => {+ const remaining = (this.pending.get(sourceId) ?? 1) - 1;+ if (remaining) this.pending.set(sourceId, remaining);+ else this.pending.delete(sourceId);+ this.totalPending -= 1;+ };+ }+}++function sourceOf(key: string): string | undefined {+ try {+ const parts: unknown = JSON.parse(key);+ if (Array.isArray(parts) && parts.length === 2 && parts.every((part) => typeof part === 'string' && part.length > 0))+ return parts[0] as string;+ } catch { /* Ignore malformed legacy receipt keys. */ }+ return undefined;+}++function entryBytes(key: string, timestamp: number): number {+ // Includes the quoted/escaped key, colon, timestamp and a comma (conservative for the last entry).+ return Buffer.byteLength(JSON.stringify(key), 'utf8') + String(timestamp).length + 2;+}++export function receiptIsLive(timestamp: number, now: number): boolean {+ return Number.isSafeInteger(timestamp) && timestamp >= 0 && now - timestamp < ROUTINE_EVENT_LIMITS.receiptTtlMs;+}++/** Startup migration keeps newest receipts within byte limits, without deleting any run history. */+export function compactRoutineReceipts(receipts: Record<string, number>, now: number): Record<string, number> {+ const result: Record<string, number> = {};+ const perSource = new Map<string, number>();+ let total = 2;+ for (const [key, timestamp] of Object.entries(receipts).sort((a, b) => b[1] - a[1])) {+ const source = sourceOf(key);+ if (!source || !receiptIsLive(timestamp, now)) continue;+ const bytes = entryBytes(key, timestamp);+ const sourceBytes = perSource.get(source) ?? 2;+ if (total + bytes > ROUTINE_EVENT_LIMITS.receiptBytesGlobal || sourceBytes + bytes > ROUTINE_EVENT_LIMITS.receiptBytesPerSource) continue;+ result[key] = timestamp;+ total += bytes;+ perSource.set(source, sourceBytes + bytes);+ }+ return result;+}++/** Reject overflow instead of evicting live receipts and allowing forced duplicate execution. */+export function addRoutineReceipt(receipts: Record<string, number>, sourceId: string, key: string, now: number): void {+ let total = 2;+ let sourceBytes = 2;+ for (const [existing, timestamp] of Object.entries(receipts)) {+ if (!receiptIsLive(timestamp, now)) {+ delete receipts[existing];+ continue;+ }+ const bytes = entryBytes(existing, timestamp);+ total += bytes;+ if (sourceOf(existing) === sourceId) sourceBytes += bytes;+ }+ const bytes = entryBytes(key, now);+ if (total + bytes > ROUTINE_EVENT_LIMITS.receiptBytesGlobal || sourceBytes + bytes > ROUTINE_EVENT_LIMITS.receiptBytesPerSource)+ throw new Error('Routine receipt storage is full; retry after receipts expire (24 hours)');+ receipts[key] = now;+}