Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

feat(memory): extract memories at conversation boundaries, not only after six idle hours

leen.zhoub8d1941cc338
diff --git a/packages/brain/src/conversations/bots/bot-service.ts b/packages/brain/src/conversations/bots/bot-service.ts
index dbf9801..6137a7a 100644
--- a/packages/brain/src/conversations/bots/bot-service.ts
+++ b/packages/brain/src/conversations/bots/bot-service.ts
@@ -1,3 +1,4 @@
+// Owns Bot changes and private topic lifecycle operations.
import { randomInt } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
import type { AgentRuntime } from "@pibot/agent";
@@ -423,19 +424,21 @@ export class BotService {
// every message in a phone's new topic fail at once (v0.0.2 B7).
const { selection } = await this.topicWorkplace.initial({ botId });
this.active(botId);
+ const previous = this.conversations.currentDmIfPresent(botId)?.id;
const topic = transaction(this.deps.db, () => {
const topic = this.conversations.create({ botId, workplace: selection });
this.conversations.switchTopic(botId, topic.id);
return topic;
});
- this.deps.chat.openConversation(topic.id);
+ this.deps.chat.openConversation(topic.id, previous);
this.deps.peer.emit("sidebar.changed", { conversationKey: `dm:${botId}` });
return topic;
}
async switchTopic(botId: string, topicId: string) {
this.active(botId);
+ const previous = this.conversations.currentDmIfPresent(botId)?.id;
const topic = businessResult(() => this.conversations.switchTopic(botId, topicId));
- this.deps.chat.openConversation(topic.id);
+ this.deps.chat.openConversation(topic.id, previous);
return topic;
}
start() {
diff --git a/packages/brain/src/conversations/chat/chat.ts b/packages/brain/src/conversations/chat/chat.ts
index b37cb28..01ecaea 100644
--- a/packages/brain/src/conversations/chat/chat.ts
+++ b/packages/brain/src/conversations/chat/chat.ts
@@ -1,3 +1,4 @@
+// Manages chat admission, conversation selection and durable runs.
import { randomUUID } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
import type { AgentRuntime } from "@pibot/agent";
@@ -450,6 +451,7 @@ export class ChatService {
)
throw new RpcError(-32602, "routine_proposal_unavailable");
}
+ const previousTopic = newTopic ? this.conversations.currentDmIfPresent(botId)?.id : undefined;
const [conversation, user, record] = transaction(this.db, () => {
resolveMessageQuote(
this.db,
@@ -491,7 +493,7 @@ export class ChatService {
return [conversation, user, record] as const;
});
accepted = true;
- this.openConversation(conversation.id);
+ this.openConversation(conversation.id, previousTopic);
this.queue.publish(record, {
userInitiated: true,
bot,
@@ -560,10 +562,12 @@ export class ChatService {
this.queue.retired.delete(botId);
this.local?.background.foreground.restore(botId);
}
- openConversation(conversationId: string) {
+ openConversation(conversationId: string, previousTopic = this.openedConversation) {
if (this.local?.tasks.tasks.isInternalConversation(conversationId))
throw new RpcError(-32602, "Unknown topic");
this.openedConversation = conversationId;
+ if (previousTopic && previousTopic !== conversationId)
+ this.local?.memoryExtraction?.boundary(previousTopic);
}
history(botId: string, topicId?: string, page: { before?: string; limit?: number } = {}) {
if (topicId && this.local?.tasks.tasks.isInternalConversation(topicId))
diff --git a/packages/brain/src/local-service.ts b/packages/brain/src/local-service.ts
index 87cab7b..d242462 100644
--- a/packages/brain/src/local-service.ts
+++ b/packages/brain/src/local-service.ts
@@ -1,3 +1,4 @@
+// Owns the ports and shared runtime services of the local brain.
import { join } from "node:path";
import type { LocalToolCall, LocalToolPorts } from "@pibot/agent";
import {
@@ -215,6 +216,9 @@ export class LocalService {
if (this.memoryProvider === port) this.memoryProvider = undefined;
};
}
+ get memoryExtraction() {
+ return this.memoryProvider?.extraction;
+ }
get memory() {
if (!this.memoryProvider) throw new RpcError(RpcErrorCodes.unsupported, "memory_unavailable");
return this.memoryProvider.personal;
diff --git a/packages/brain/src/runtime/memory/port.ts b/packages/brain/src/runtime/memory/port.ts
index fb3a797..986580e 100644
--- a/packages/brain/src/runtime/memory/port.ts
+++ b/packages/brain/src/runtime/memory/port.ts
@@ -1,3 +1,4 @@
+// Defines the capability ports consumed by the brain without importing memory.
import type { Bot, Memory, MemoryProposal } from "@pibot/protocol-base";
export interface MemoryPromptRequest {
@@ -51,7 +52,17 @@ export interface GroupMemoryPort {
prompt(groupId: string, botId?: string, request?: MemoryPromptRequest): string;
}
+/** In-process producers carry trusted IDs; the capability decides whether a topic is eligible. */
+export interface MemoryExtractionPort {
+ boundary(conversationId: string): void;
+ correction(conversationId: string, sourceMessageId: string): void;
+ pause(): void;
+ saveOnExit(): Promise<void>;
+ resume(): void;
+}
+
export interface MemoryPort {
+ extraction?: MemoryExtractionPort;
personal: PersonalMemoryPort;
group: GroupMemoryPort;
}
diff --git a/packages/brain/src/runtime/startup/create-brain-controller.ts b/packages/brain/src/runtime/startup/create-brain-controller.ts
index b936121..262d3af 100644
--- a/packages/brain/src/runtime/startup/create-brain-controller.ts
+++ b/packages/brain/src/runtime/startup/create-brain-controller.ts
@@ -1,3 +1,4 @@
+// Coordinates brain admission and producer shutdown before releasing durable state.
import type { Logger } from "@pibot/observability";
import {
BrainWakeControlSchema,
@@ -111,8 +112,11 @@ export function createBrainController(ctx: StartupContext): Awaited<ReturnType<t
desktopClient(connected) {
if (!ctx.sleepService.interrupt())
return Promise.reject(new RpcError(RpcErrorCodes.closed, "brain_sleep_committed"));
+ // Initial attachment sync may report offline without a desktop having quit.
+ const leaving = !connected && ctx.interactiveAttached;
// Close admission synchronously; a preflight accepted before this boundary must drain.
if (!connected) {
+ if (leaving) ctx.capabilities.memoryExtraction?.pause();
ctx.ports
?.get<import("../../core/capability.ts").InteractiveClientPort>("interactive-client")
?.setInteractive("quit");
@@ -133,6 +137,7 @@ export function createBrainController(ctx: StartupContext): Awaited<ReturnType<t
]);
// Bounded: an RPC that never settles must not keep admission closed forever.
await settleWithin(ctx.logger, ctx.interactiveRequests, "interactive_requests_timeout");
+ if (leaving && !ctx.stopping) await ctx.capabilities.memoryExtraction?.saveOnExit();
if (drained.some((result) => result.status === "rejected"))
throw new Error("interactive_drain_unconfirmed");
} else {
@@ -143,6 +148,7 @@ export function createBrainController(ctx: StartupContext): Awaited<ReturnType<t
ctx.ports
?.get<import("../../core/capability.ts").InteractiveClientPort>("interactive-client")
?.setInteractive("available");
+ ctx.capabilities.memoryExtraction?.resume();
ctx.chat.admitInteractive(true);
ctx.groups.admitInteractive(true);
}
@@ -195,6 +201,8 @@ export function createBrainController(ctx: StartupContext): Awaited<ReturnType<t
stop() {
stopped ??= (async () => {
ctx.stopping = true;
+ const extraction = ctx.capabilities.memoryExtraction;
+ extraction?.pause();
const sessionRecoveryStopped = ctx.stopSessionRecovery();
await ctx.stopStartupMaintenance();
ctx.sleepService.dispose();
@@ -217,6 +225,7 @@ export function createBrainController(ctx: StartupContext): Awaited<ReturnType<t
await ctx.chat.stop();
await ctx.groups.stop();
await ctx.botBusiness.stop();
+ await extraction?.saveOnExit();
ctx.unsubscribeCheckpoints?.();
await settleWithin(ctx.logger, ctx.requests, "shutdown_requests_timeout");
await ctx.modelPort?.stop();
diff --git a/packages/memory/src/brain/capability.ts b/packages/memory/src/brain/capability.ts
index eda5973..f45d9a2 100644
--- a/packages/memory/src/brain/capability.ts
+++ b/packages/memory/src/brain/capability.ts
@@ -1,3 +1,4 @@
+// Registers memory services and owns the lifetime of the maintenance workers.
import type { BrainCapability } from "@pibot/brain/kit";
import { registerGroupMemoryRpc } from "./group-memory-service.ts";
import { MemoryExtractionQueue } from "./memory-extraction-queue.ts";
@@ -78,6 +79,7 @@ export function memoryCapability(): BrainCapability {
registerGroupMemoryRpc(ctx.rpc.handle, memory);
const releasePort = ctx.memory.provide({
personal: memory,
+ extraction,
group: { prompt: (groupId, botId, request) => memory.groupPrompt(groupId, botId, request) },
});
const releaseTools = (["memory_add", "memory_update", "memory_remove"] as const).map((tool) =>
diff --git a/packages/memory/src/brain/memory-extraction-attempt.ts b/packages/memory/src/brain/memory-extraction-attempt.ts
new file mode 100644
index 0000000..ad70b32
--- /dev/null
+++ b/packages/memory/src/brain/memory-extraction-attempt.ts
@@ -0,0 +1,307 @@
+// Dispatches and settles one leased extraction, including its fixed-code health and audit receipts.
+import type { DatabaseSync } from "node:sqlite";
+import type { MemoryDraftRequest, MemoryDraftUsage } from "@pibot/agent";
+import type { BrainRedactor } from "@pibot/brain/kit";
+import {
+ AuditRepo,
+ BackgroundTaskHealthRepo,
+ BotsRepo,
+ correctionTopic,
+ type MemoryExtraction,
+ type MemoryExtractionsRepo,
+ memoryMaintenanceUsage,
+ SettingsRepo,
+} from "@pibot/storage";
+import {
+ type ExtractionSource,
+ extractionPrompt,
+ extractionSource,
+ groupExtractionInstruction,
+} from "./memory-extraction.ts";
+import { applyExtractionCandidates, extractionErrorCode } from "./memory-extraction-result.ts";
+import type { MemoryService } from "./memory-service.ts";
+
+interface Model {
+ provider: string;
+ id: string;
+}
+export interface MemoryExtractionAttemptDeps {
+ db: DatabaseSync;
+ redactor: BrainRedactor;
+ logger: { warn(message: string): void; info?(message: string): void };
+ memory: MemoryService;
+ healthChanged?(): void;
+ isBotIdle(botId: string): boolean;
+ isPaused(): boolean;
+ draftMemories?: (
+ request: MemoryDraftRequest,
+ ) => Promise<{ draft: unknown; tokens: number; costUsd?: number }>;
+}
+
+export function dayStart(now = new Date()): string {
+ const value = new Date(now);
+ value.setHours(0, 0, 0, 0);
+ return value.toISOString();
+}
+
+export class MemoryExtractionAttempt {
+ private readonly bots: BotsRepo;
+ private readonly settings: SettingsRepo;
+ private readonly health: BackgroundTaskHealthRepo;
+ constructor(
+ private readonly deps: MemoryExtractionAttemptDeps,
+ private readonly repo: MemoryExtractionsRepo,
+ ) {
+ this.bots = new BotsRepo(deps.db);
+ this.settings = new SettingsRepo(deps.db);
+ this.health = new BackgroundTaskHealthRepo(deps.db, deps.healthChanged);
+ }
+ limit() {
+ const settings = this.settings.get();
+ return {
+ costUsd: settings.memoryExtractionDailyCostUsd ?? 0.5,
+ tokens: settings.memoryExtractionDailyTokens ?? 2_000_000,
+ };
+ }
+ /**
+ * The model this Bot actually chats with: its own, else the default it follows. The auxiliary
+ * model setting is tried first inside draftMemories, which falls back to this one. Preferring
+ * the default here made every Bot's extraction fail with no_model once the default became
+ * unusable (maintainers 2026-11-15: default on the official ChatGPT plan OpenAI refuses, while Pi ran
+ * fine on the Codex sign-in), and the inbox filled with failure cards.
+ */
+ private model(botId: string): Model | undefined {
+ const bot = this.bots.get(botId);
+ // An image Bot's own model only draws (e.g. seedream), so it is never among the text models
+ // extraction can run on and every attempt failed with no_model (maintainers 2026-11-18, 小图). It
+ // uses the default model its sibling Bots chat with instead.
+ if (bot?.imageMode) return this.settings.get().defaultModel ?? undefined;
+ return bot?.modelProvider && bot.modelId
+ ? { provider: bot.modelProvider, id: bot.modelId }
+ : (this.settings.get().defaultModel ?? undefined);
+ }
+ private permitted(row: MemoryExtraction): boolean {
+ const bot = this.bots.get(row.botId);
+ // An external agent keeps its own memory; its chats never go to Pi Bot's model.
+ if (!bot || bot.archivedAt || !bot.memoryExtraction || bot.kind === "agent") return false;
+ const topic = this.deps.db
+ .prepare(`SELECT bot_id,group_id FROM conversations WHERE id=?`)
+ .get(row.conversationId);
+ if (!topic || topic.group_id !== row.groupId) return false;
+ return row.groupId
+ ? !!this.deps.db
+ .prepare(
+ `SELECT 1 FROM group_members gm JOIN groups g ON g.id=gm.group_id WHERE gm.group_id=? AND gm.bot_id=? AND gm.left_at IS NULL AND g.coordinator_bot_id=? AND g.archived_at IS NULL`,
+ )
+ .get(row.groupId, row.botId, row.botId)
+ : topic.bot_id === row.botId;
+ }
+ async process(row: MemoryExtraction, signal: AbortSignal) {
+ try {
+ await this.extract(row, signal);
+ } catch (error) {
+ this.failed(row, signal, error);
+ }
+ }
+ private async extract(row: MemoryExtraction, signal: AbortSignal) {
+ const skip = (error: string, coverageMessageId?: string) =>
+ this.repo.finish(row.id, { status: "skipped", error, coverageMessageId });
+ if (!this.permitted(row)) {
+ skip("extraction_disabled_or_scope_changed");
+ return;
+ }
+ const automated = this.repo.automatedReason(row.conversationId);
+ if (automated) {
+ skip(automated, this.repo.watermark(row.conversationId)?.messageId);
+ return;
+ }
+ if (
+ row.reason === "correction" &&
+ (!row.sourceMessageId ||
+ !correctionTopic(this.deps.db, row.conversationId, row.sourceMessageId))
+ ) {
+ skip("correction_source_unavailable");
+ return;
+ }
+ const newest = this.repo.watermark(row.conversationId);
+ if (
+ row.reason !== "correction" &&
+ newest &&
+ this.repo.covered(row.conversationId, newest.messageId)
+ ) {
+ skip("already_covered");
+ return;
+ }
+ const prior = this.deps.db
+ .prepare(
+ `SELECT coverage_message_id AS id FROM memory_extractions WHERE conversation_id=? AND status='done' AND coverage_message_id IS NOT NULL ORDER BY finished_at DESC LIMIT 1`,
+ )
+ .get(row.conversationId);
+ const source = extractionSource(
+ this.deps.db,
+ row.conversationId,
+ prior?.id == null ? null : String(prior.id),
+ 12_000,
+ row.groupId ?? undefined,
+ );
+ if (!source) {
+ skip("no_new_human_content");
+ return;
+ }
+ const model = this.model(row.botId);
+ const draftMemories = this.deps.draftMemories;
+ if (!model || !draftMemories) {
+ // A missing model used to be silent forever; a streak makes the inbox say it.
+ this.health.fail("memory_extraction", row.botId, "no_model");
+ skip("no_model");
+ return;
+ }
+ const result = await this.draft(row, source, model, draftMemories, signal);
+ signal.throwIfAborted();
+ if (!this.deps.isBotIdle(row.botId)) {
+ this.repo.defer(row, "bot_busy");
+ return;
+ }
+ if (!this.permitted(row)) {
+ skip("extraction_disabled_or_scope_changed");
+ return;
+ }
+ if (this.repo.watermark(row.conversationId)?.messageId !== source.watermarkId) {
+ this.repo.defer(row, "source_changed");
+ return;
+ }
+ this.apply(row, source, result);
+ }
+ private draft(
+ row: MemoryExtraction,
+ source: ExtractionSource,
+ model: Model,
+ draftMemories: NonNullable<MemoryExtractionAttemptDeps["draftMemories"]>,
+ signal: AbortSignal,
+ ) {
+ const text = this.deps.redactor.redact(
+ extractionPrompt(
+ this.deps.memory.extractionCatalog(row.botId, row.groupId),
+ source.text,
+ source.truncated,
+ ),
+ );
+ const used = memoryMaintenanceUsage(this.deps.db, dayStart());
+ const limit = this.limit();
+ const draft = (chosen: Model) =>
+ draftMemories({
+ model: chosen,
+ text,
+ ...(row.groupId ? { instruction: groupExtractionInstruction() } : {}),
+ signal,
+ budget: {
+ tokens: Math.max(0, limit.tokens - used.tokens),
+ costUsd: Math.max(0, limit.costUsd - used.costUsd),
+ },
+ onUsage: (usage: MemoryDraftUsage) => this.repo.recordUsage(row.id, usage),
+ });
+ // The Bot's own model may be gone or its key invalid while the main model in Settings still
+ // works; one retry there keeps the job alive (maintainers 2026-11-18). Both fail before any
+ // request is dispatched, so nothing is billed twice.
+ const fallback = this.settings.get().defaultModel ?? undefined;
+ return draft(model).catch((error: unknown) => {
+ const code = extractionErrorCode(error);
+ if (
+ (code !== "no_model" && code !== "auth_failed") ||
+ !fallback ||
+ (fallback.provider === model.provider && fallback.id === model.id) ||
+ signal.aborted
+ )
+ throw error;
+ return draft({ provider: fallback.provider, id: fallback.id });
+ });
+ }
+ private apply(
+ row: MemoryExtraction,
+ source: ExtractionSource,
+ result: { draft: unknown; tokens: number; costUsd?: number },
+ ) {
+ const counts = applyExtractionCandidates(
+ this.deps.memory,
+ row,
+ source.subjectMessageId,
+ result.draft,
+ source.groupSourceIds,
+ source.groupSourceTexts,
+ );
+ this.repo.diagnostics(row.id, counts);
+ const accepted = counts.applied + counts.proposed;
+ this.deps.logger.info?.(
+ JSON.stringify({
+ module: "memory",
+ reasonCode: "extraction_result",
+ botId: row.botId,
+ extractionId: row.id,
+ ...counts,
+ }),
+ );
+ this.audit(row, source.messageCount, accepted);
+ const failed = counts.raw && !accepted && !counts.reasons.candidate_duplicate;
+ this.repo.finish(row.id, {
+ status: failed ? "failed" : "done",
+ coverageMessageId: source.watermarkId,
+ tokens: result.tokens,
+ costUsd: result.costUsd,
+ candidates: accepted,
+ error: !counts.raw
+ ? "no_candidates"
+ : !counts.valid
+ ? "candidates_invalid"
+ : !accepted
+ ? "candidates_not_applied"
+ : null,
+ });
+ // Wanted repeated zero results noticed, but "nothing worth remembering" is the normal
+ // outcome of short task chats (run a command, make a page): as a card it told users to check
+ // their models and keys for a working job (v0.0.2 test, 2026-11-14). It stays in the log line
+ // above; only invalid or unapplied candidates, a real fault, count against health.
+ if (failed)
+ this.health.fail(
+ "memory_extraction",
+ row.botId,
+ !counts.valid ? "candidates_invalid" : "candidates_not_applied",
+ );
+ else this.health.recover("memory_extraction", row.botId);
+ }
+ private failed(row: MemoryExtraction, signal: AbortSignal, error: unknown) {
+ const code = extractionErrorCode(error);
+ if (signal.aborted) {
+ this.repo.defer(row, this.deps.isPaused() ? "worker_stopped" : "bot_preempted");
+ return;
+ }
+ if (code === "budget_exhausted") {
+ this.repo.defer(row, code);
+ return;
+ }
+ if (code === "no_model" || code === "auth_failed") {
+ this.health.fail("memory_extraction", row.botId, code);
+ this.repo.finish(row.id, { status: "skipped", error: code });
+ return;
+ }
+ this.deps.logger.warn(
+ JSON.stringify({ module: "memory", reasonCode: "memory_extraction_failed", error: code }),
+ );
+ this.health.fail("memory_extraction", row.botId, code);
+ this.repo.finish(row.id, { status: "failed", error: code });
+ }
+ private audit(row: MemoryExtraction, messages: number, applied: number) {
+ new AuditRepo(this.deps.db, this.deps.redactor).append({
+ botId: row.botId,
+ kind: "memory.changed",
+ summary: "Memory extracted automatically / 自动提炼记忆",
+ detail: {
+ actor: "automatic",
+ reasonCode: "memory_extracted",
+ conversationId: row.conversationId,
+ messageCount: Math.min(messages, 50),
+ ...(row.groupId ? { groupId: row.groupId } : {}),
+ revision: applied,
+ },
+ });
+ }
+}
diff --git a/packages/memory/src/brain/memory-extraction-queue.ts b/packages/memory/src/brain/memory-extraction-queue.ts
index f7958b9..59f287c 100644
--- a/packages/memory/src/brain/memory-extraction-queue.ts
+++ b/packages/memory/src/brain/memory-extraction-queue.ts
@@ -1,83 +1,124 @@
-import type { DatabaseSync } from "node:sqlite";
-import type { MemoryDraftRequest, MemoryDraftUsage } from "@pibot/agent";
-import type { BrainRedactor } from "@pibot/brain/kit";
+// Owns the durable extraction worker and yields to foreground Bot work.
import {
- AuditRepo,
- BackgroundTaskHealthRepo,
- BotsRepo,
- type MemoryExtraction,
+ boundaryTopics,
+ correctionTopic,
MemoryExtractionsRepo,
memoryMaintenanceUsage,
- SettingsRepo,
} from "@pibot/storage";
import {
- extractionPrompt,
- extractionSource,
- groupExtractionInstruction,
-} from "./memory-extraction.ts";
-import { applyExtractionCandidates, extractionErrorCode } from "./memory-extraction-result.ts";
-import type { MemoryService } from "./memory-service.ts";
+ dayStart,
+ MemoryExtractionAttempt,
+ type MemoryExtractionAttemptDeps,
+} from "./memory-extraction-attempt.ts";
+import { extractionErrorCode } from "./memory-extraction-result.ts";
-interface Model {
- provider: string;
- id: string;
-}
-interface Deps {
- db: DatabaseSync;
- redactor: BrainRedactor;
- logger: { warn(message: string): void; info?(message: string): void };
- memory: MemoryService;
- healthChanged?(): void;
+interface Deps extends Omit<MemoryExtractionAttemptDeps, "isPaused"> {
isIdle(): boolean;
- isBotIdle(botId: string): boolean;
onBotWork(listener: (botId: string) => void): () => void;
- draftMemories?: (
- request: MemoryDraftRequest,
- ) => Promise<{ draft: unknown; tokens: number; costUsd?: number }>;
}
const TOPICS_PER_BOT_DAY = 20;
-const SCAN_MS = 60_000;
-function dayStart(now = new Date()): string {
- const value = new Date(now);
- value.setHours(0, 0, 0, 0);
- return value.toISOString();
-}
+const SCAN_MS = 15_000;
+const FALLBACK_SCAN_MS = 60_000;
/** One durable worker, yielding to its owning Bot and sharing the unchanged organization caps. */
export class MemoryExtractionQueue {
private readonly repo: MemoryExtractionsRepo;
- private readonly bots: BotsRepo;
- private readonly settings: SettingsRepo;
- private readonly health: BackgroundTaskHealthRepo;
+ private readonly attempt: MemoryExtractionAttempt;
private timer: ReturnType<typeof setTimeout> | undefined;
private controller: AbortController | undefined;
private stopped = false;
+ private paused = false;
+ private nextScan = 0;
+ private nextFallback = 0;
private busy = false;
private activeBot: string | undefined;
private releaseWork: (() => void) | undefined;
private running: Promise<void> | undefined;
+ private exitSave: Promise<void> | undefined;
constructor(private readonly deps: Deps) {
this.repo = new MemoryExtractionsRepo(deps.db);
- this.bots = new BotsRepo(deps.db);
- this.settings = new SettingsRepo(deps.db);
- this.health = new BackgroundTaskHealthRepo(deps.db, deps.healthChanged);
+ this.attempt = new MemoryExtractionAttempt(
+ { ...deps, isPaused: () => this.stopped || this.paused },
+ this.repo,
+ );
}
start() {
this.repo.recover();
this.stopped = false;
+ this.paused = false;
+ this.nextScan = 0;
+ this.nextFallback = 0;
this.releaseWork = this.deps.onBotWork((botId) => {
if (botId === this.activeBot) this.controller?.abort();
});
this.schedule(5_000);
}
- async stop() {
- this.stopped = true;
+ pause() {
+ this.paused = true;
if (this.timer) clearTimeout(this.timer);
this.timer = undefined;
+ this.controller?.abort();
+ }
+ saveOnExit() {
+ this.pause();
+ this.exitSave ??= this.persistExitTopics()
+ .catch((error: unknown) => {
+ this.warn("memory_extraction_exit_failed", error);
+ })
+ .finally(() => {
+ this.exitSave = undefined;
+ });
+ return this.exitSave;
+ }
+ private async persistExitTopics() {
+ await this.running;
+ const at = new Date().toISOString();
+ let after = "";
+ for (;;) {
+ const page = boundaryTopics(this.deps.db, { at, before: at, after, exit: true });
+ for (const topic of page) this.repo.enqueue({ ...topic, reason: "boundary" }, at);
+ const last = page.at(-1);
+ if (!last || page.length < 100) break;
+ after = last.conversationId;
+ // Large histories must not monopolize the brain's event loop during shutdown.
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ }
+ }
+ resume() {
+ if (!this.paused || this.stopped) return;
+ this.paused = false;
+ this.nextScan = 0;
+ this.wake();
+ }
+ async stop() {
+ this.stopped = true;
this.releaseWork?.();
this.releaseWork = undefined;
- this.controller?.abort();
+ this.pause();
await this.running;
+ await this.exitSave;
+ }
+ boundary(conversationId: string) {
+ try {
+ if (this.stopped) return;
+ const at = new Date().toISOString();
+ const [topic] = boundaryTopics(this.deps.db, { at, before: at, conversationId });
+ if (topic && this.repo.enqueue({ ...topic, reason: "boundary" }, at)) this.wake();
+ } catch (error) {
+ this.warn("memory_extraction_boundary_failed", error);
+ }
+ }
+ correction(conversationId: string, sourceMessageId: string) {
+ try {
+ if (this.stopped) return;
+ const topic = correctionTopic(this.deps.db, conversationId, sourceMessageId);
+ if (topic && this.repo.enqueue({ ...topic, reason: "correction" })) this.wake();
+ } catch (error) {
+ this.warn("memory_extraction_correction_failed", error);
+ }
+ }
+ private wake() {
+ if (!this.running) this.schedule(0);
}
usage(since: string) {
return memoryMaintenanceUsage(this.deps.db, since);
@@ -86,10 +127,14 @@ export class MemoryExtractionQueue {
return !this.busy;
}
private schedule(delay: number) {
- if (this.stopped) return;
+ if (this.stopped || this.paused) return;
if (this.timer) clearTimeout(this.timer);
this.timer = setTimeout(() => {
- this.running = this.tick();
+ this.timer = undefined;
+ this.running = this.tick().finally(() => {
+ this.running = undefined;
+ this.schedule(SCAN_MS);
+ });
}, delay);
this.timer.unref?.();
}
@@ -99,7 +144,19 @@ export class MemoryExtractionQueue {
} catch (error) {
this.warn("memory_extraction_tick_failed", error);
}
- this.schedule(SCAN_MS);
+ }
+ private scan() {
+ const now = Date.now();
+ if (now >= this.nextFallback) {
+ this.nextFallback = now + FALLBACK_SCAN_MS;
+ this.enqueueDue();
+ }
+ if (now < this.nextScan) return;
+ this.nextScan = now + SCAN_MS;
+ const at = new Date(now).toISOString();
+ const before = new Date(now - 30 * 60_000).toISOString();
+ for (const topic of boundaryTopics(this.deps.db, { at, before }))
+ this.repo.enqueue({ ...topic, reason: "boundary" }, at);
}
enqueueDue() {
const now = new Date();
@@ -115,28 +172,19 @@ export class MemoryExtractionQueue {
return count;
}
private async drain() {
- if (this.busy || this.stopped || !this.deps.isIdle()) return;
+ if (this.busy || this.stopped || this.paused || !this.deps.isIdle()) return;
this.busy = true;
const excluded = new Set<string>();
try {
- this.enqueueDue();
- while (!this.stopped && this.deps.isIdle()) {
+ while (!this.stopped && !this.paused && this.deps.isIdle()) {
+ this.scan();
const used = this.usage(dayStart());
- const limit = this.limit();
+ const limit = this.attempt.limit();
if (used.costUsd >= limit.costUsd || used.tokens >= limit.tokens) break;
for (const [id, n] of this.repo.todayByBot(dayStart()))
if (n >= TOPICS_PER_BOT_DAY) excluded.add(id);
const next = this.repo.claim([...excluded]);
if (!next) break;
- const automated = this.repo.automatedReason(next.conversationId);
- if (automated) {
- this.repo.finish(next.id, {
- status: "skipped",
- error: automated,
- coverageMessageId: this.repo.watermark(next.conversationId)?.messageId,
- });
- continue;
- }
if (!this.deps.isBotIdle(next.botId)) {
this.repo.defer(next, "bot_busy");
excluded.add(next.botId);
@@ -144,7 +192,7 @@ export class MemoryExtractionQueue {
}
this.activeBot = next.botId;
this.controller = new AbortController();
- await this.process(next);
+ await this.attempt.process(next, this.controller.signal);
if (
this.controller.signal.aborted ||
this.deps.db
@@ -166,215 +214,6 @@ export class MemoryExtractionQueue {
this.controller = undefined;
}
}
- private limit() {
- const settings = this.settings.get();
- return {
- costUsd: settings.memoryExtractionDailyCostUsd ?? 0.5,
- tokens: settings.memoryExtractionDailyTokens ?? 2_000_000,
- };
- }
- /**
- * The model this Bot actually chats with: its own, else the default it follows. The auxiliary
- * model setting is tried first inside draftMemories, which falls back to this one. Preferring
- * the default here made every Bot's extraction fail with no_model once the default became
- * unusable (maintainers 2026-11-15: default on the official ChatGPT plan OpenAI refuses, while Pi ran
- * fine on the Codex sign-in), and the inbox filled with failure cards.
- */
- private model(botId: string): Model | undefined {
- const bot = this.bots.get(botId);
- // An image Bot's own model only draws (e.g. seedream), so it is never among the text models
- // extraction can run on and every attempt failed with no_model (maintainers 2026-11-18, 小图). It
- // uses the default model its sibling Bots chat with instead.
- if (bot?.imageMode) return this.settings.get().defaultModel ?? undefined;
- return bot?.modelProvider && bot.modelId
- ? { provider: bot.modelProvider, id: bot.modelId }
- : (this.settings.get().defaultModel ?? undefined);
- }
- private permitted(row: MemoryExtraction): boolean {
- const bot = this.bots.get(row.botId);
- // An external agent keeps its own memory; its chats never go to Pi Bot's model.
- if (!bot || bot.archivedAt || !bot.memoryExtraction || bot.kind === "agent") return false;
- const topic = this.deps.db
- .prepare(`SELECT bot_id,group_id FROM conversations WHERE id=?`)
- .get(row.conversationId);
- if (!topic || topic.group_id !== row.groupId) return false;
- return row.groupId
- ? !!this.deps.db
- .prepare(
- `SELECT 1 FROM group_members gm JOIN groups g ON g.id=gm.group_id WHERE gm.group_id=? AND gm.bot_id=? AND gm.left_at IS NULL AND g.coordinator_bot_id=? AND g.archived_at IS NULL`,
- )
- .get(row.groupId, row.botId, row.botId)
- : topic.bot_id === row.botId;
- }
- private async process(row: MemoryExtraction) {
- const skip = (error: string, coverageMessageId?: string) =>
- this.repo.finish(row.id, { status: "skipped", error, coverageMessageId });
- if (!this.permitted(row)) {
- skip("extraction_disabled_or_scope_changed");
- return;
- }
- const automated = this.repo.automatedReason(row.conversationId);
- if (automated) {
- skip(automated, this.repo.watermark(row.conversationId)?.messageId);
- return;
- }
- const prior = this.deps.db
- .prepare(
- `SELECT coverage_message_id AS id FROM memory_extractions WHERE conversation_id=? AND status='done' AND coverage_message_id IS NOT NULL ORDER BY finished_at DESC LIMIT 1`,
- )
- .get(row.conversationId);
- const source = extractionSource(
- this.deps.db,
- row.conversationId,
- prior?.id == null ? null : String(prior.id),
- 12_000,
- row.groupId ?? undefined,
- );
- if (!source) {
- skip("no_new_human_content");
- return;
- }
- const model = this.model(row.botId);
- const draftMemories = this.deps.draftMemories;
- if (!model || !draftMemories) {
- // A missing model used to be silent forever; a streak makes the inbox say it.
- this.health.fail("memory_extraction", row.botId, "no_model");
- skip("no_model");
- return;
- }
- const controller = this.controller;
- if (!controller) throw new Error("extraction_controller_missing");
- try {
- const text = this.deps.redactor.redact(
- extractionPrompt(
- this.deps.memory.extractionCatalog(row.botId, row.groupId),
- source.text,
- source.truncated,
- ),
- );
- const used = this.usage(dayStart());
- const limit = this.limit();
- const draft = (chosen: Model) =>
- draftMemories({
- model: chosen,
- text,
- ...(row.groupId ? { instruction: groupExtractionInstruction() } : {}),
- signal: controller.signal,
- budget: {
- tokens: Math.max(0, limit.tokens - used.tokens),
- costUsd: Math.max(0, limit.costUsd - used.costUsd),
- },
- onUsage: (usage: MemoryDraftUsage) => this.repo.recordUsage(row.id, usage),
- });
- // The Bot's own model may be gone or its key invalid while the main model in Settings still
- // works; one retry there keeps the job alive (maintainers 2026-11-18). Both fail before any
- // request is dispatched, so nothing is billed twice.
- const fallback = this.settings.get().defaultModel ?? undefined;
- const result = await draft(model).catch((error: unknown) => {
- const code = extractionErrorCode(error);
- if (
- (code !== "no_model" && code !== "auth_failed") ||
- !fallback ||
- (fallback.provider === model.provider && fallback.id === model.id) ||
- controller.signal.aborted
- )
- throw error;
- return draft({ provider: fallback.provider, id: fallback.id });
- });
- controller.signal.throwIfAborted();
- if (!this.deps.isBotIdle(row.botId)) {
- this.repo.defer(row, "bot_busy");
- return;
- }
- if (!this.permitted(row)) {
- skip("extraction_disabled_or_scope_changed");
- return;
- }
- if (this.repo.watermark(row.conversationId)?.messageId !== source.watermarkId) {
- this.repo.defer(row, "source_changed");
- return;
- }
- const counts = applyExtractionCandidates(
- this.deps.memory,
- row,
- source.subjectMessageId,
- result.draft,
- source.groupSourceIds,
- source.groupSourceTexts,
- );
- this.repo.diagnostics(row.id, counts);
- const accepted = counts.applied + counts.proposed;
- this.deps.logger.info?.(
- JSON.stringify({
- module: "memory",
- reasonCode: "extraction_result",
- botId: row.botId,
- extractionId: row.id,
- ...counts,
- }),
- );
- this.audit(row, source.messageCount, accepted);
- const failed = counts.raw && !accepted && !counts.reasons.candidate_duplicate;
- this.repo.finish(row.id, {
- status: failed ? "failed" : "done",
- coverageMessageId: source.watermarkId,
- tokens: result.tokens,
- costUsd: result.costUsd,
- candidates: accepted,
- error: !counts.raw
- ? "no_candidates"
- : !counts.valid
- ? "candidates_invalid"
- : !accepted
- ? "candidates_not_applied"
- : null,
- });
- // Wanted repeated zero results noticed, but "nothing worth remembering" is the normal
- // outcome of short task chats (run a command, make a page): as a card it told users to check
- // their models and keys for a working job (v0.0.2 test, 2026-11-14). It stays in the log line
- // above; only invalid or unapplied candidates, a real fault, count against health.
- if (failed)
- this.health.fail(
- "memory_extraction",
- row.botId,
- !counts.valid ? "candidates_invalid" : "candidates_not_applied",
- );
- else this.health.recover("memory_extraction", row.botId);
- } catch (error) {
- const code = extractionErrorCode(error);
- if (this.controller?.signal.aborted) {
- this.repo.defer(row, this.stopped ? "worker_stopped" : "bot_preempted");
- return;
- }
- if (code === "budget_exhausted") {
- this.repo.defer(row, code);
- return;
- }
- if (code === "no_model" || code === "auth_failed") {
- this.health.fail("memory_extraction", row.botId, code);
- skip(code);
- return;
- }
- this.warn("memory_extraction_failed", error);
- this.health.fail("memory_extraction", row.botId, code);
- this.repo.finish(row.id, { status: "failed", error: code });
- }
- }
- private audit(row: MemoryExtraction, messages: number, applied: number) {
- new AuditRepo(this.deps.db, this.deps.redactor).append({
- botId: row.botId,
- kind: "memory.changed",
- summary: "Memory extracted automatically / 自动提炼记忆",
- detail: {
- actor: "automatic",
- reasonCode: "memory_extracted",
- conversationId: row.conversationId,
- messageCount: Math.min(messages, 50),
- ...(row.groupId ? { groupId: row.groupId } : {}),
- revision: applied,
- },
- });
- }
private warn(reasonCode: string, error: unknown) {
this.deps.logger.warn(
JSON.stringify({ module: "memory", reasonCode, error: extractionErrorCode(error) }),
diff --git a/packages/orchestration/src/conversations/groups/group-topics.ts b/packages/orchestration/src/conversations/groups/group-topics.ts
index a49d093..bb84540 100644
--- a/packages/orchestration/src/conversations/groups/group-topics.ts
+++ b/packages/orchestration/src/conversations/groups/group-topics.ts
@@ -1,3 +1,4 @@
+// Owns committed group topic selection and its workspace bindings.
import {
abortable,
GroupTopicFolderChoices,
@@ -116,6 +117,7 @@ export class GroupTopicsService {
false,
true,
);
+ this.service.deps.local.memoryExtraction?.boundary(previous.conversationId);
return this.service.folders.present(this.required(groupId));
}
async archive(
@@ -243,7 +245,7 @@ export class GroupTopicsService {
const binding = await this.binding(previous, finalFolders, finalPrimary);
this.idle(groupId);
this.assertSource(groupId, previous);
- return (await this.service.mutate(
+ const created = (await this.service.mutate(
groupId,
() =>
transaction(this.service.deps.db, () => {
@@ -264,6 +266,9 @@ export class GroupTopicsService {
false,
true,
)) as Group;
+ if (created.conversationId !== previous.conversationId)
+ this.service.deps.local.memoryExtraction?.boundary(previous.conversationId);
+ return created;
}
/** Only short-lived group picker choices reach ACP; client paths never enter folder tables. */
async acpSelection(
diff --git a/packages/orchestration/src/conversations/groups/group-workflow-progress.ts b/packages/orchestration/src/conversations/groups/group-workflow-progress.ts
index 6ab0f2e..5d1af99 100644
--- a/packages/orchestration/src/conversations/groups/group-workflow-progress.ts
+++ b/packages/orchestration/src/conversations/groups/group-workflow-progress.ts
@@ -1,3 +1,4 @@
+// Stores workflow progress and owns the transition when a plan stops.
import { createHash } from "node:crypto";
import type { ToolRunContext } from "@pibot/brain/orchestration-kit";
import {
@@ -381,6 +382,8 @@ export class GroupWorkflowProgress {
return true;
});
if (!stopped) return;
+ const source = new MessagesRepo(this.service.deps.db).get(record.sourceMessageId);
+ if (source) this.service.deps.local.memoryExtraction?.boundary(source.conversationId);
settlePlanWebConsent(this.service, record);
// Maintainers 2026-11-14: unmerged step workspaces and Pi Bot's folder repository go with the plan.
this.service.workflows.merges.ended(record);
diff --git a/packages/orchestration/src/conversations/groups/group-workflows.ts b/packages/orchestration/src/conversations/groups/group-workflows.ts
index 75d5881..ae59544 100644
--- a/packages/orchestration/src/conversations/groups/group-workflows.ts
+++ b/packages/orchestration/src/conversations/groups/group-workflows.ts
@@ -1,3 +1,4 @@
+// Runs group workflows until their steps and durable terminal state settle.
import {
type GroupExecutionPlan,
type GroupPlanCard,
@@ -505,6 +506,8 @@ export class GroupWorkflowScheduler implements WorkflowEngine {
}
return { todo: undefined, pauses };
});
+ const source = new MessagesRepo(this.service.deps.db).get(record.sourceMessageId);
+ if (source) this.service.deps.local.memoryExtraction?.boundary(source.conversationId);
this.merges.ended(record);
const completedTodo = completed.todo;
if (completedTodo) {
diff --git a/packages/routines/src/brain/execution/execution.ts b/packages/routines/src/brain/execution/execution.ts
index 0d54393..03212d4 100644
--- a/packages/routines/src/brain/execution/execution.ts
+++ b/packages/routines/src/brain/execution/execution.ts
@@ -1,3 +1,4 @@
+// Admits routine runs and reconciles their durable terminal records.
import { createHash, randomUUID } from "node:crypto";
import { join } from "node:path";
import type { DatabaseSync } from "node:sqlite";
@@ -419,6 +420,7 @@ export class RoutineExecution {
// A routine failing the same way (a gone working folder, a missing model) used
// to leave a trace only in the log; this streak is what the inbox card shows.
if (finished) {
+ this.deps.local.memoryExtraction?.boundary(ended.conversationId);
const health = new BackgroundTaskHealthRepo(this.deps.db);
const subject = current.routineId ?? "";
if (status === "failed")
diff --git a/packages/storage/migrations/0174_memory_extraction_boundaries.sql b/packages/storage/migrations/0174_memory_extraction_boundaries.sql
new file mode 100644
index 0000000..7e950f1
--- /dev/null
+++ b/packages/storage/migrations/0174_memory_extraction_boundaries.sql
@@ -0,0 +1,45 @@
+-- Preserve old attempts while allowing one durable successor behind a running extraction.
+CREATE TABLE memory_extractions_next (
+ id TEXT PRIMARY KEY,
+ bot_id TEXT NOT NULL REFERENCES bots(id) ON DELETE CASCADE,
+ conversation_id TEXT NOT NULL,
+ group_id TEXT,
+ status TEXT NOT NULL CHECK(status IN ('queued','running','done','failed','skipped')),
+ reason TEXT NOT NULL CHECK(reason IN ('idle','archive','boundary','correction')),
+ priority INTEGER NOT NULL DEFAULT 0 CHECK(priority BETWEEN 0 AND 2),
+ source_message_id TEXT,
+ coverage_message_id TEXT,
+ model_provider TEXT,
+ model_id TEXT,
+ tokens INTEGER NOT NULL DEFAULT 0,
+ cost_usd REAL NOT NULL DEFAULT 0,
+ candidates INTEGER NOT NULL DEFAULT 0,
+ error TEXT,
+ created_at TEXT NOT NULL,
+ started_at TEXT,
+ finished_at TEXT,
+ raw_candidates INTEGER NOT NULL DEFAULT 0,
+ valid_candidates INTEGER NOT NULL DEFAULT 0,
+ applied_candidates INTEGER NOT NULL DEFAULT 0,
+ proposed_candidates INTEGER NOT NULL DEFAULT 0,
+ reason_counts TEXT NOT NULL DEFAULT '{}'
+);
+INSERT INTO memory_extractions_next (
+ id, bot_id, conversation_id, group_id, status, reason, coverage_message_id, model_provider,
+ model_id, tokens, cost_usd, candidates, error, created_at, started_at, finished_at,
+ raw_candidates, valid_candidates, applied_candidates, proposed_candidates, reason_counts
+)
+SELECT id, bot_id, conversation_id, group_id, status, reason, coverage_message_id, model_provider,
+ model_id, tokens, cost_usd, candidates, error, created_at, started_at, finished_at,
+ raw_candidates, valid_candidates, applied_candidates, proposed_candidates, reason_counts
+FROM memory_extractions ORDER BY rowid;
+DROP TABLE memory_extractions;
+ALTER TABLE memory_extractions_next RENAME TO memory_extractions;
+CREATE UNIQUE INDEX memory_extractions_queued ON memory_extractions(conversation_id) WHERE status='queued';
+CREATE UNIQUE INDEX memory_extractions_running ON memory_extractions(conversation_id) WHERE status='running';
+CREATE INDEX memory_extractions_queue ON memory_extractions(status, priority DESC, created_at, id);
+CREATE INDEX memory_extractions_bot_day ON memory_extractions(bot_id, created_at);
+CREATE INDEX memory_extractions_started ON memory_extractions(started_at, bot_id);
+CREATE INDEX memory_extractions_topic ON memory_extractions(conversation_id, status, finished_at);
+CREATE INDEX memory_extractions_bot_results ON memory_extractions(bot_id, finished_at DESC, id DESC)
+ WHERE status='done';
diff --git a/packages/storage/src/bots/memory-extraction-boundaries.ts b/packages/storage/src/bots/memory-extraction-boundaries.ts
new file mode 100644
index 0000000..3462861
--- /dev/null
+++ b/packages/storage/src/bots/memory-extraction-boundaries.ts
@@ -0,0 +1,164 @@
+// Selects eligible conversation boundaries using stored ownership and message provenance.
+import type { DatabaseSync } from "node:sqlite";
+import { memoryHumanMessageSql } from "./memory-extraction-origin.ts";
+
+const topicOwner = `
+ FROM conversations c
+ LEFT JOIN groups g ON g.id=c.group_id AND g.archived_at IS NULL
+ JOIN bots b ON b.id=COALESCE(c.bot_id,g.coordinator_bot_id)
+ WHERE c.kind IN ('dm','group') AND c.internal_task_id IS NULL
+ AND b.archived_at IS NULL AND b.memory_extraction=1 AND b.kind IS NOT 'agent'
+ AND (c.kind='dm' OR EXISTS (
+ SELECT 1 FROM group_members gm WHERE gm.group_id=g.id AND gm.bot_id=b.id AND gm.left_at IS NULL
+ ))`;
+
+function topic(row: Record<string, unknown>) {
+ return {
+ conversationId: String(row.conversationId),
+ botId: String(row.botId),
+ groupId: row.groupId == null ? null : String(row.groupId),
+ sourceMessageId: String(row.sourceMessageId),
+ };
+}
+
+export function correctionTopic(db: DatabaseSync, conversationId: string, sourceId: string) {
+ const row = db
+ .prepare(
+ `SELECT c.id AS conversationId, b.id AS botId, c.group_id AS groupId, ? AS sourceMessageId
+ ${topicOwner} AND c.id=? AND EXISTS (
+ SELECT 1 FROM messages m WHERE m.id=? AND m.conversation_id=c.id AND (${memoryHumanMessageSql})
+ ) AND NOT EXISTS (
+ SELECT 1 FROM memory_extractions e WHERE e.conversation_id=c.id
+ AND e.reason='correction' AND e.source_message_id=? AND e.status IN ('done','skipped')
+ )`,
+ )
+ .get(sourceId, conversationId, sourceId, sourceId);
+ return row ? topic(row) : undefined;
+}
+
+export const memoryExtractionCadence = (botColumn: string) => `(
+ SELECT COUNT(*) FROM (
+ SELECT error, finished_at FROM memory_extractions observed
+ WHERE observed.bot_id=${botColumn} AND status='done'
+ ORDER BY finished_at DESC, id DESC LIMIT 3
+ ) WHERE error='no_candidates'
+ HAVING MAX(finished_at)>?
+) IS NOT 3`;
+
+export function boundaryTopics(
+ db: DatabaseSync,
+ options: { at: string; before: string; conversationId?: string; after?: string; exit?: boolean },
+) {
+ const now = Date.parse(options.at);
+ const day = new Date(now);
+ day.setHours(0, 0, 0, 0);
+ const explicit = options.conversationId !== undefined;
+ const quiet = !explicit && !options.exit;
+ const quietFloor = new Date(now - 6 * 60 * 60_000).toISOString();
+ const rows = db
+ .prepare(
+ `WITH topics AS (
+ SELECT c.id AS conversationId, b.id AS botId, c.group_id AS groupId,
+ (SELECT id FROM messages WHERE conversation_id=c.id ORDER BY rowid DESC LIMIT 1)
+ AS sourceMessageId
+ ${topicOwner}
+ AND c.id ${explicit ? "=" : ">"} ?
+ ${quiet ? `AND c.id IN (SELECT conversation_id FROM messages WHERE created_at>? AND created_at<=?)` : ""}
+ AND EXISTS (
+ SELECT 1 FROM messages m WHERE m.conversation_id=c.id AND (${memoryHumanMessageSql})
+ )
+ )
+ SELECT t.* FROM topics t JOIN messages last ON last.id=t.sourceMessageId
+ WHERE last.created_at<=? AND NOT EXISTS (
+ SELECT 1 FROM memory_extractions e WHERE e.conversation_id=t.conversationId AND (
+ (e.status='queued' AND e.priority>=1)
+ OR (e.status='running' AND e.source_message_id=t.sourceMessageId)
+ OR (e.status='done' AND e.coverage_message_id=t.sourceMessageId)
+ OR (e.reason='boundary' AND e.created_at>?)
+ OR (e.status IN ('failed','skipped') AND e.error IS NOT 'already_covered' AND e.finished_at>?)
+ )
+ )
+ AND (SELECT COUNT(*) FROM memory_extractions e WHERE e.conversation_id=t.conversationId
+ AND e.status='failed' AND e.started_at>?)<3
+ ${quiet ? "AND last.created_at>?" : ""}
+ ${options.exit ? "" : `AND ${memoryExtractionCadence("t.botId")}`}
+ ORDER BY t.conversationId LIMIT 100`,
+ )
+ .all(
+ options.conversationId ?? options.after ?? "",
+ ...(quiet ? [quietFloor, options.before] : []),
+ options.before,
+ new Date(now - 10 * 60_000).toISOString(),
+ new Date(now - 60 * 60_000).toISOString(),
+ day.toISOString(),
+ ...(quiet ? [quietFloor] : []),
+ ...(options.exit ? [] : [new Date(now - 2 * 60 * 60_000).toISOString()]),
+ );
+ return rows.map(topic);
+}
+
+export interface ExtractionTopic {
+ conversationId: string;
+ botId: string;
+ groupId: string | null;
+ lastMessageId: string;
+ lastUserId: string;
+ lastAt: string;
+}
+
+/**
+ * Topics that are ready for extraction. A topic is due when it was archived or its last message
+ * is older than the idle cutoff; it needs two user messages, an enabled Bot, and no extraction
+ * that already covered its newest message. Failed/skipped attempts wait an hour and stop after
+ * three failures in a day so a broken model cannot loop.
+ */
+export function legacyDueTopics(
+ db: DatabaseSync,
+ idleBefore: string,
+ retryAfter: string,
+ failedSince: string,
+ limit: number,
+) {
+ const rows = db
+ .prepare(
+ `WITH t AS (
+ SELECT c.id AS conversationId,
+ COALESCE(c.bot_id, g.coordinator_bot_id) AS botId,
+ c.group_id AS groupId,
+ c.archived_at AS archivedAt,
+ (SELECT m.id FROM messages m WHERE m.conversation_id=c.id
+ ORDER BY m.rowid DESC LIMIT 1) AS lastMessageId,
+ (SELECT m.created_at FROM messages m WHERE m.conversation_id=c.id
+ ORDER BY m.rowid DESC LIMIT 1) AS lastAt,
+ (SELECT m.id FROM messages m WHERE m.conversation_id=c.id AND m.role='user'
+ AND m.status='done' ORDER BY m.rowid DESC LIMIT 1) AS lastUserId,
+ (SELECT COUNT(*) FROM messages m WHERE m.conversation_id=c.id AND m.role='user'
+ AND m.status='done') AS userCount
+ FROM conversations c LEFT JOIN groups g ON g.id=c.group_id
+ WHERE c.kind IN ('dm','group')
+ )
+ SELECT t.conversationId, t.botId, t.groupId, t.lastMessageId, t.lastUserId, t.lastAt
+ FROM t JOIN bots b ON b.id=t.botId AND b.memory_extraction=1 AND b.archived_at IS NULL
+ WHERE t.userCount>=2 AND t.lastMessageId IS NOT NULL
+ AND (t.archivedAt IS NOT NULL OR t.lastAt<=?)
+ AND NOT EXISTS (
+ SELECT 1 FROM memory_extractions e WHERE e.conversation_id=t.conversationId
+ AND (((e.status='done' OR (e.status='skipped' AND e.error LIKE 'automation_%')) AND e.coverage_message_id=t.lastMessageId)
+ OR e.status IN ('queued','running')
+ OR (e.status IN ('failed','skipped') AND e.error IS NOT 'already_covered' AND e.finished_at>?))
+ )
+ AND (SELECT COUNT(*) FROM memory_extractions e2
+ WHERE e2.conversation_id=t.conversationId AND e2.status='failed'
+ AND e2.started_at>?)<3
+ ORDER BY (t.archivedAt IS NOT NULL) DESC, t.lastAt DESC LIMIT ?`,
+ )
+ .all(idleBefore, retryAfter, failedSince, limit);
+ return rows.map((value) => ({
+ conversationId: String(value.conversationId),
+ botId: String(value.botId),
+ groupId: value.groupId == null ? null : String(value.groupId),
+ lastMessageId: String(value.lastMessageId),
+ lastUserId: String(value.lastUserId),
+ lastAt: String(value.lastAt),
+ })) satisfies ExtractionTopic[];
+}
diff --git a/packages/storage/src/bots/memory-extraction.ts b/packages/storage/src/bots/memory-extraction.ts
index 6d6be0d..5b6edaa 100644
--- a/packages/storage/src/bots/memory-extraction.ts
+++ b/packages/storage/src/bots/memory-extraction.ts
@@ -1,17 +1,20 @@
+// Persists the extraction queue, including interrupted attempts and their usage.
import { randomUUID } from "node:crypto";
import type { DatabaseSync } from "node:sqlite";
+import { transaction } from "../database/database.ts";
+import { legacyDueTopics, memoryExtractionCadence } from "./memory-extraction-boundaries.ts";
import { extractionAutomatedReason } from "./memory-extraction-origin.ts";
-export { memoryHumanMessageSql } from "./memory-extraction-origin.ts";
+export {
+ boundaryTopics,
+ correctionTopic,
+ type ExtractionTopic,
+} from "./memory-extraction-boundaries.ts";
-import { transaction } from "../database/database.ts";
+export { memoryHumanMessageSql } from "./memory-extraction-origin.ts";
-/**
- * The post-hoc extraction queue. Rows are the durable work items; the unique open index in
- * migration 0135 makes enqueueing idempotent and `recover` puts a crash-interrupted run back in the
- * queue instead of losing it.
- */
export type MemoryExtractionStatus = "queued" | "running" | "done" | "failed" | "skipped";
+export type MemoryExtractionReason = "idle" | "archive" | "boundary" | "correction";
export interface MemoryExtraction {
id: string;
@@ -19,7 +22,8 @@ export interface MemoryExtraction {
conversationId: string;
groupId: string | null;
status: MemoryExtractionStatus;
- reason: "idle" | "archive";
+ reason: MemoryExtractionReason;
+ sourceMessageId: string | null;
coverageMessageId: string | null;
modelProvider: string | null;
modelId: string | null;
@@ -32,17 +36,8 @@ export interface MemoryExtraction {
finishedAt: string | null;
}
-export interface ExtractionTopic {
- conversationId: string;
- botId: string;
- groupId: string | null;
- lastMessageId: string;
- lastUserId: string;
- lastAt: string;
-}
-
const columns = `id, bot_id AS botId, conversation_id AS conversationId, group_id AS groupId,
- status, reason, coverage_message_id AS coverageMessageId, model_provider AS modelProvider,
+ status, reason, source_message_id AS sourceMessageId, coverage_message_id AS coverageMessageId, model_provider AS modelProvider,
model_id AS modelId, tokens, cost_usd AS costUsd, candidates, error, created_at AS createdAt,
started_at AS startedAt, finished_at AS finishedAt`;
@@ -53,7 +48,8 @@ function row(value: Record<string, unknown>): MemoryExtraction {
conversationId: String(value.conversationId),
groupId: value.groupId == null ? null : String(value.groupId),
status: value.status as MemoryExtractionStatus,
- reason: value.reason as "idle" | "archive",
+ reason: value.reason as MemoryExtractionReason,
+ sourceMessageId: value.sourceMessageId == null ? null : String(value.sourceMessageId),
coverageMessageId: value.coverageMessageId == null ? null : String(value.coverageMessageId),
modelProvider: value.modelProvider == null ? null : String(value.modelProvider),
modelId: value.modelId == null ? null : String(value.modelId),
@@ -78,20 +74,33 @@ export class MemoryExtractionsRepo {
for (const value of interrupted) this.defer(row(value), "restart_interrupted");
}
- enqueue(input: {
- botId: string;
- conversationId: string;
- groupId?: string | null;
- reason: "idle" | "archive";
- }): boolean {
+ enqueue(
+ input: Pick<MemoryExtraction, "botId" | "conversationId" | "reason"> &
+ Partial<Pick<MemoryExtraction, "groupId" | "sourceMessageId">>,
+ at = new Date().toISOString(),
+ ): boolean {
+ const priority = input.reason === "correction" ? 2 : input.reason === "boundary" ? 1 : 0;
+ const source = input.sourceMessageId ?? null;
const result = this.db
.prepare(
`INSERT INTO memory_extractions
- (id, bot_id, conversation_id, group_id, status, reason, created_at)
- SELECT ?,?,?,?, 'queued', ?, ?
- WHERE NOT EXISTS (
- SELECT 1 FROM memory_extractions WHERE conversation_id=? AND status IN ('queued','running')
- )`,
+ (id, bot_id, conversation_id, group_id, status, reason, priority, source_message_id, created_at)
+ SELECT ?,?,?,?, 'queued', ?,?,?,?
+ WHERE NOT EXISTS (
+ SELECT 1 FROM memory_extractions
+ WHERE conversation_id=? AND status='running'
+ AND (?=0 OR (reason=? AND source_message_id IS ?))
+ )
+ ON CONFLICT(conversation_id) WHERE status='queued' DO UPDATE SET
+ bot_id=excluded.bot_id, group_id=excluded.group_id,
+ reason=excluded.reason, priority=excluded.priority,
+ source_message_id=excluded.source_message_id, created_at=excluded.created_at,
+ error=NULL
+ WHERE excluded.priority>memory_extractions.priority OR (
+ excluded.priority=2 AND (
+ SELECT rowid FROM messages WHERE id=excluded.source_message_id
+ )>(SELECT rowid FROM messages WHERE id=memory_extractions.source_message_id)
+ )`,
)
.run(
randomUUID(),
@@ -99,18 +108,21 @@ export class MemoryExtractionsRepo {
input.conversationId,
input.groupId ?? null,
input.reason,
- new Date().toISOString(),
+ priority,
+ source,
+ at,
input.conversationId,
+ priority,
+ input.reason,
+ source,
);
return result.changes > 0;
}
- /**
- * Oldest queued row not owned by a Bot that already reached today's topic cap. The caps are
- * applied by the caller so rows stay queued (not failed) until the next day.
- */
+ /** Claims urgent rows first, preserving the archive-first order among legacy items. */
claim(excludedBotIds: readonly string[], now = new Date().toISOString()) {
return transaction(this.db, () => {
+ const timestamp = Date.parse(now);
const excluded = excludedBotIds.length
? `AND bot_id NOT IN (${excludedBotIds.map(() => "?").join(",")})`
: "";
@@ -118,13 +130,25 @@ export class MemoryExtractionsRepo {
.prepare(
`SELECT ${columns} FROM memory_extractions
WHERE status='queued' ${excluded}
- ORDER BY CASE WHEN EXISTS (SELECT 1 FROM conversations c
+ AND NOT EXISTS (SELECT 1 FROM memory_extractions active
+ WHERE active.conversation_id=memory_extractions.conversation_id AND active.status='running')
+ AND (reason<>'boundary'
+ OR EXISTS (SELECT 1 FROM conversations c
+ WHERE c.id=memory_extractions.conversation_id AND c.archived_at IS NOT NULL)
+ OR (SELECT m.created_at FROM messages m WHERE m.conversation_id=memory_extractions.conversation_id
+ ORDER BY m.rowid DESC LIMIT 1)<=?
+ OR ${memoryExtractionCadence("memory_extractions.bot_id")})
+ ORDER BY priority DESC, CASE WHEN EXISTS (SELECT 1 FROM conversations c
WHERE c.id=memory_extractions.conversation_id AND c.archived_at IS NOT NULL)
THEN 0 ELSE 1 END,
(SELECT m.created_at FROM messages m WHERE m.conversation_id=memory_extractions.conversation_id
ORDER BY m.rowid DESC LIMIT 1) DESC, created_at, id LIMIT 1`,
)
- .get(...excludedBotIds);
+ .get(
+ ...excludedBotIds,
+ new Date(timestamp - 6 * 60 * 60_000).toISOString(),
+ new Date(timestamp - 2 * 60 * 60_000).toISOString(),
+ );
if (!found) return undefined;
const value = row(found);
const changed = this.db
@@ -183,15 +207,24 @@ export class MemoryExtractionsRepo {
const usage = this.db
.prepare("SELECT tokens FROM memory_extractions WHERE id=?")
.get(value.id);
- if (!Number(usage?.tokens)) {
+ const successor = this.db
+ .prepare("SELECT 1 FROM memory_extractions WHERE conversation_id=? AND status='queued'")
+ .get(value.conversationId);
+ if (!Number(usage?.tokens) && !successor) {
this.db
.prepare(`UPDATE memory_extractions SET status='queued', started_at=NULL,
error=? WHERE id=? AND status='running'`)
.run(reason, value.id);
return;
}
- this.finish(value.id, { status: "failed", error: reason });
- this.enqueue({ ...value, reason: value.reason });
+ if (Number(usage?.tokens)) this.finish(value.id, { status: "failed", error: reason });
+ else this.db.prepare("DELETE FROM memory_extractions WHERE id=?").run(value.id);
+ this.enqueue(value, value.createdAt);
+ this.db
+ .prepare(
+ "UPDATE memory_extractions SET error=? WHERE conversation_id=? AND status='queued' AND error IS NULL",
+ )
+ .run(reason, value.conversationId);
});
}
@@ -232,6 +265,15 @@ export class MemoryExtractionsRepo {
);
}
+ covered(conversationId: string, messageId: string) {
+ return !!this.db
+ .prepare(
+ `SELECT 1 FROM memory_extractions WHERE conversation_id=? AND status='done'
+ AND coverage_message_id=?`,
+ )
+ .get(conversationId, messageId);
+ }
+
/** The newest message the topic has; used as the coverage watermark after a run. */
watermark(conversationId: string) {
const last = this.db
@@ -254,55 +296,8 @@ export class MemoryExtractionsRepo {
: undefined;
}
- /**
- * Topics that are ready for extraction. A topic is due when it was archived or its last message
- * is older than the idle cutoff; it needs two user messages, an enabled Bot, and no extraction
- * that already covered its newest message. Failed/skipped attempts wait an hour and stop after
- * three failures in a day so a broken model cannot loop.
- */
dueTopics(idleBefore: string, retryAfter: string, failedSince: string, limit = 100) {
- const rows = this.db
- .prepare(
- `WITH t AS (
- SELECT c.id AS conversationId,
- COALESCE(c.bot_id, g.coordinator_bot_id) AS botId,
- c.group_id AS groupId,
- c.archived_at AS archivedAt,
- (SELECT m.id FROM messages m WHERE m.conversation_id=c.id
- ORDER BY m.rowid DESC LIMIT 1) AS lastMessageId,
- (SELECT m.created_at FROM messages m WHERE m.conversation_id=c.id
- ORDER BY m.rowid DESC LIMIT 1) AS lastAt,
- (SELECT m.id FROM messages m WHERE m.conversation_id=c.id AND m.role='user'
- AND m.status='done' ORDER BY m.rowid DESC LIMIT 1) AS lastUserId,
- (SELECT COUNT(*) FROM messages m WHERE m.conversation_id=c.id AND m.role='user'
- AND m.status='done') AS userCount
- FROM conversations c LEFT JOIN groups g ON g.id=c.group_id
- WHERE c.kind IN ('dm','group')
- )
- SELECT t.conversationId, t.botId, t.groupId, t.lastMessageId, t.lastUserId, t.lastAt
- FROM t JOIN bots b ON b.id=t.botId AND b.memory_extraction=1 AND b.archived_at IS NULL
- WHERE t.userCount>=2 AND t.lastMessageId IS NOT NULL
- AND (t.archivedAt IS NOT NULL OR t.lastAt<=?)
- AND NOT EXISTS (
- SELECT 1 FROM memory_extractions e WHERE e.conversation_id=t.conversationId
- AND (((e.status='done' OR (e.status='skipped' AND e.error LIKE 'automation_%')) AND e.coverage_message_id=t.lastMessageId)
- OR e.status IN ('queued','running')
- OR (e.status IN ('failed','skipped') AND e.finished_at>?))
- )
- AND (SELECT COUNT(*) FROM memory_extractions e2
- WHERE e2.conversation_id=t.conversationId AND e2.status='failed'
- AND e2.started_at>?)<3
- ORDER BY (t.archivedAt IS NOT NULL) DESC, t.lastAt DESC LIMIT ?`,
- )
- .all(idleBefore, retryAfter, failedSince, limit);
- return rows.map((value) => ({
- conversationId: String(value.conversationId),
- botId: String(value.botId),
- groupId: value.groupId == null ? null : String(value.groupId),
- lastMessageId: String(value.lastMessageId),
- lastUserId: String(value.lastUserId),
- lastAt: String(value.lastAt),
- })) satisfies ExtractionTopic[];
+ return legacyDueTopics(this.db, idleBefore, retryAfter, failedSince, limit);
}
/** Attempts started today, including failures: the cap protects both cost and time. */
@@ -340,7 +335,7 @@ export class MemoryExtractionsRepo {
};
}
- /** Pending work survives a restart; the queue is drained oldest-first on the next start. */
+ /** Pending work survives a restart. */
pending(): number {
const value = this.db
.prepare("SELECT COUNT(*) AS n FROM memory_extractions WHERE status IN ('queued','running')")
diff --git a/packages/storage/test/store.test.ts b/packages/storage/test/store.test.ts
index 9f88b2e..1fc6e3d 100644
--- a/packages/storage/test/store.test.ts
+++ b/packages/storage/test/store.test.ts
@@ -1,3 +1,4 @@
+// Exercises the real SQLite migration and repository contracts in temporary data directories.
import { randomUUID } from "node:crypto";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -262,7 +263,7 @@ describe("database and migrations", () => {
"worktree_allocations",
]);
const versions = db.prepare("SELECT * FROM schema_migrations").all();
- expect(versions).toHaveLength(171);
+ expect(versions).toHaveLength(172);
expect(versions[0]?.version).toBe(1);
expect(String(versions[0]?.applied_at)).toMatch(/Z$/);
const bot = new BotsRepo(db).ensureMainBot();