Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): keep nightly learning from skipping or overwriting work

Chrisc88ad4fa1f5d
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearning.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearning.test.ts
index 47d36e814f..1e8b242574 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearning.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearning.test.ts
@@ -2,6 +2,8 @@
* 夜间学习的真实入口(runNightlyLearning / revertNightlyLearningItem):状态文件落在临时目录,
* 数据库、辅助模型、记忆库与技能库用内存替身。依据 2026-10-23 主人裁决:没有新对话不调用模型;
* 只出现一次的做法先观察,再次出现才转正为技能;改动之后被人改过的不能撤销;失败不扣计数。
+ * PR #6940 review:读取位置不能卡在一批全被过滤的回复上,也不能越过仍在生成的回复;
+ * 模型思考期间被改过的记忆和技能不覆盖,合并的保留项没写成功时不删来源。
*/
import fs from 'node:fs/promises';
import os from 'node:os';
@@ -24,7 +26,10 @@ vi.mock('../../appSessionState.js', () => ({
}));
vi.mock('../../localDb/client/current.js', () => {
const db = {
- query: vi.fn(async (sql: string) => (sql.includes('nightly-learning-turns') ? h.rows : [])),
+ // 按真实查询的水位区间与条数上限返回(参数:botId, after, until)。
+ query: vi.fn(async (sql: string, params: unknown[]) => (sql.includes('nightly-learning-turns')
+ ? h.rows.filter((r) => r.createdAt > (params[1] as number) && r.createdAt <= (params[2] as number)).slice(0, 401)
+ : [])),
queryOne: vi.fn(async () => ({ canonicalSessionId: 'main', capabilities: JSON.stringify({ memory: true }) })),
};
return { getDbClient: () => db };
@@ -47,7 +52,7 @@ vi.mock('../../maker-host/index.js', () => ({
getMaker: () => ({
makerMemory: {
getStore: async () => ({
- list: async () => [...h.memories.values()],
+ list: async () => [...h.memories.values()].map((record) => structuredClone(record)),
read: async (filename: string) => {
const record = h.memories.get(filename);
if (!record) throw new MemoryError('not-found', filename);
@@ -76,6 +81,8 @@ const turn = (n: number, text: string, createdAt: number) => ({
sessionId: 'main', id: `reply${n}`, content: 'Done.', meta: JSON.stringify({ turnCompleted: true }), createdAt, role: 'canonical',
inputId: `user${n}`, inputContent: JSON.stringify(text), inputMeta: '{}',
});
+/** 第 n 次调用模型时发给它的对话消息 id。 */
+const sentIds = (call: number) => JSON.parse(h.model.mock.calls[call]![1]).messages.map((m: { id: string }) => m.id);
const reply = (plan: Record<string, unknown>) => h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify(plan) });
const memory = (name: string, title: string, body: string) => {
const filename = `feedback_${name}.md`;
@@ -168,3 +175,47 @@ it('keeps the count when the model fails and leaves conversations that arrive mi
expect(state.pending.turns).toBe(1);
expect(state.runs[0]!.outcome).toBe('nothing');
});
+
+it('moves past a batch of filtered replies and waits for a reply that is still being written', async () => {
+ const t0 = Date.now() - 60_000;
+ await recordNightlyLearningTurn(h.root, 'bot', 'main', t0);
+ // 一批 400 条子代理回复全被过滤:下一次必须越过它们,读到后面的主人对话。
+ const sub = { meta: JSON.stringify({ turnCompleted: true, parentUuid: 'p' }) };
+ h.rows = Array.from({ length: 400 }, (_, i) => ({ ...turn(100 + i, 'sub', t0 + i), ...sub }));
+ h.rows.push(turn(1, 'Please keep answers short.', t0 + 1000));
+ h.rows.push({ ...turn(2, 'And cite sources.', t0 + 2000), meta: JSON.stringify({}) });
+ await runNightlyLearning('bot', { manual: false });
+ expect(h.model).not.toHaveBeenCalled();
+ reply({});
+ await runNightlyLearning('bot', { manual: false });
+ expect(sentIds(0)).toEqual(['user1', 'reply1']);
+
+ // 第二轮回复当时还在生成:完成后下一次读到它,已学过的第一轮不再重复。
+ h.rows[h.rows.length - 1] = turn(2, 'And cite sources.', t0 + 2000);
+ await recordNightlyLearningTurn(h.root, 'bot', 'main', t0 + 2000);
+ reply({});
+ await runNightlyLearning('bot', { manual: false });
+ expect(sentIds(1)).toEqual(['user2', 'reply2']);
+});
+
+it('never overwrites edits made while the model was thinking, and keeps a merge source whose kept memory was skipped', async () => {
+ const kept = memory('progress', 'Report results', 'Report feature results.');
+ const dup = memory('progress_dup', 'Report results too', 'Only report results.');
+ h.skills.set('deploy', { source: 'old steps', enabled: true });
+ h.model.mockImplementationOnce(async () => {
+ h.memories.get(kept).frontmatter.updatedAt = 'edited-by-owner';
+ h.skills.set('deploy', { source: 'owner steps', enabled: true });
+ return { ok: true, text: JSON.stringify({
+ memories: [
+ { op: 'delete', filename: dup, mergedInto: kept, reason: 'duplicate' },
+ { op: 'update', filename: kept, title: 'Report results', description: 'd', body: 'Merged.', reason: 'merge' },
+ ],
+ skills: [{ op: 'update', slug: 'deploy', title: 'Deploy', description: 'd', body: 'model steps', reason: 'r' }],
+ }) };
+ });
+ await runNightlyLearning('bot', { manual: true });
+ expect(h.memories.get(kept).body).toBe('Report feature results.');
+ expect(h.memories.get(dup).body).toBe('Only report results.');
+ expect(h.skills.get('deploy')!.source).toBe('owner steps');
+ expect((await readNightlyLearningState(h.root, 'bot'))!.runs[0]!.items).toEqual([]);
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearningCounter.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearningCounter.test.ts
index eb9cfa337c..7e9c06bb2f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearningCounter.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botNightlyLearningCounter.test.ts
@@ -8,6 +8,7 @@ const h = vi.hoisted(() => ({
row: null as null | { botId: string; role: string; createdAt: number; meta: string; inputMeta: string | null; inputContent?: string },
record: vi.fn(),
}));
+vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } }));
vi.mock('../../appSessionState.js', () => ({
activeOwnerScopeKey: () => 'owner',
isAppSessionBoundaryPending: () => false,
diff --git a/apps/desktop/src/main/maker-ipc/botNightlyLearning.ts b/apps/desktop/src/main/maker-ipc/botNightlyLearning.ts
index 54f618dd9f..652cfaedc5 100644
--- a/apps/desktop/src/main/maker-ipc/botNightlyLearning.ts
+++ b/apps/desktop/src/main/maker-ipc/botNightlyLearning.ts
@@ -49,6 +49,8 @@ const MAX_REPLIES = 400;
const MESSAGE_BUDGET = 60_000;
const USER_TEXT_CHARS = 4_000;
const ASSISTANT_TEXT_CHARS = 3_000;
+/** 这么久以内开始、还没完成的回复会挡住水位,等它完成后再学;更早的视为已中断,不再等。 */
+const IN_FLIGHT_HOLD_MS = 6 * 60 * 60_000;
export class NightlyLearningError extends Error {
constructor(readonly code: 'NOT_FOUND' | 'CHANGED' | 'BUSY' | 'UNAVAILABLE', message: string) {
@@ -91,8 +93,20 @@ const parseMeta = (raw: string | null) => {
try { return JSON.parse(raw || '{}') as Record<string, any>; } catch { return {}; }
};
-/** 读取水位之后主人和伙伴完成的对话轮次;口径与计数器(botNightlyLearningCounter.ts)一致。 */
-async function readTurns(botId: string, after: number, until: number): Promise<{ turns: Turn[]; truncated: boolean }> {
+type TurnScan = {
+ turns: Turn[];
+ /** 读到了 until 之前的全部回复;否则 scannedThrough 是这一批扫到的最后一条回复的时间。 */
+ complete: boolean;
+ scannedThrough: number;
+ /** 最早一条仍在生成的回复的时间;水位不能越过它。 */
+ holdAt: number;
+};
+
+/**
+ * 读取水位之后主人和伙伴完成的对话轮次;口径与计数器(botNightlyLearningCounter.ts)一致。
+ * 已经学过的回复(learned)跳过;被过滤掉的回复同样算扫过,水位照常推进。
+ */
+async function readTurns(botId: string, after: number, until: number, learned: Record<string, number>): Promise<TurnScan> {
const rows = await getDbClient().query<{
sessionId: string; id: string; content: string; meta: string; createdAt: number; role: string;
inputId: string | null; inputContent: string | null; inputMeta: string | null;
@@ -117,9 +131,14 @@ async function readTurns(botId: string, after: number, until: number): Promise<{
[botId, after, until],
);
const turns: Turn[] = [];
+ let holdAt = Infinity;
for (const row of rows.slice(0, MAX_REPLIES)) {
const meta = parseMeta(row.meta);
- if (meta.turnCompleted !== true || meta.parentUuid || meta.botPrivateReply || meta.botGroupLane) continue;
+ if (meta.parentUuid || meta.botPrivateReply || meta.botGroupLane || learned[row.id]) continue;
+ if (meta.turnCompleted !== true) {
+ if (row.createdAt > until - IN_FLIGHT_HOLD_MS) holdAt = Math.min(holdAt, row.createdAt);
+ continue;
+ }
const inputMeta = parseMeta(row.inputMeta);
if (!row.inputId || isAutomaticInputOriginKind(inputMeta.origin?.kind)) continue;
const source = inputMeta.imSource;
@@ -136,7 +155,8 @@ async function readTurns(botId: string, after: number, until: number): Promise<{
],
});
}
- return { turns, truncated: rows.length > MAX_REPLIES };
+ const complete = rows.length <= MAX_REPLIES;
+ return { turns, complete, scannedThrough: complete ? until : rows[MAX_REPLIES - 1]!.createdAt, holdAt };
}
/** 从工具调用记录里数这个伙伴的技能被读了几次:调用技能,或读了它技能目录下的 SKILL.md。 */
@@ -207,17 +227,19 @@ const sameMemory = (a: MemorySnapshot, b: MemorySnapshot) =>
const sameSkill = (a: SkillSnapshot, b: SkillSnapshot) =>
(!a && !b) || (!!a && !!b && a.source === b.source && a.enabled === b.enabled);
-/** 把一条记忆改成目标内容(null = 删除),返回改完后的实际内容。 */
-async function applyMemory(store: MemoryStore, filename: string, target: MemorySnapshot): Promise<MemorySnapshot> {
- const current = await readMemory(store, filename);
+/**
+ * 把一条记忆改成目标内容(null = 删除),返回改完后的实际内容。expected 是调用方刚核对过的版本
+ * (null = 应当不存在),直接交给存储层核对:这之间被改过就由存储层拒绝,不覆盖。
+ */
+async function applyMemory(store: MemoryStore, filename: string, target: MemorySnapshot, expected: string | null): Promise<MemorySnapshot> {
if (!target) {
- if (current) await store.delete(filename, current.frontmatter.updatedAt);
+ if (expected !== null) await store.delete(filename, expected);
return null;
}
- if (!current) {
+ if (expected === null) {
await store.write({ type: target.type, name: target.slug, title: target.title, description: target.description, body: target.body, mode: 'create', preserveBody: true });
} else {
- await store.update(filename, current.frontmatter.updatedAt, { title: target.title, description: target.description, body: target.body });
+ await store.update(filename, expected, { title: target.title, description: target.description, body: target.body });
}
return memorySnapshot(await readMemory(store, filename));
}
@@ -297,11 +319,18 @@ async function runLocked(
const state = (await readNightlyLearningState(root, botId)) ?? null;
const snapshotTurns = state?.pending.turns ?? 0;
const after = state?.throughAt ?? (state?.pending.firstAt ? state.pending.firstAt - 1 : startedAt);
- const { turns, truncated } = await readTurns(botId, after, startedAt);
- const selected = learningSnapshotPrefix(turns, MESSAGE_BUDGET);
+ const scan = await readTurns(botId, after, startedAt, state?.learned ?? {});
+ const selected = learningSnapshotPrefix(scan.turns, MESSAGE_BUDGET);
const messages = selected.flatMap((turn) => turn.messages);
- const readAll = !truncated && selected.length === turns.length;
- const throughAt = readAll ? startedAt : (selected.at(-1)?.createdAt ?? after);
+ const allSelected = selected.length === scan.turns.length;
+ const readAll = scan.complete && allSelected;
+ // 没读完时退到最后读到的那一毫秒之前,同一毫秒里还没读的回复下次仍能读到;读过的记进 learned 跳过。
+ // 仍在生成的回复挡住水位,等它完成后再学。
+ const frontier = !allSelected ? (selected.at(-1)?.createdAt ?? after + 1) - 1
+ : scan.complete ? startedAt : scan.scannedThrough - 1;
+ const throughAt = Math.max(after, Math.min(frontier, scan.holdAt - 1));
+ const learnedNow: Record<string, number> = {};
+ for (const turn of selected) if (turn.createdAt > throughAt) learnedNow[turn.messages[1]!.id] = turn.createdAt;
const perSession = new Map<string, number>();
for (const turn of selected) perSession.set(turn.sessionId, (perSession.get(turn.sessionId) ?? 0) + 1);
const consumedTurns = readAll ? snapshotTurns : selected.length;
@@ -312,9 +341,15 @@ async function runLocked(
if (advance) {
subtractPending(s, perSession, consumedTurns);
s.throughAt = Math.max(s.throughAt ?? 0, throughAt);
+ const learned = Object.fromEntries(Object.entries({ ...s.learned, ...learnedNow }).filter(([, at]) => at > s.throughAt!));
+ if (Object.keys(learned).length) s.learned = learned;
+ else delete s.learned;
}
extra?.(s);
- s.runs.unshift(run);
+ // 整理开始前已先登记了这次运行(逐条记录改动),这里补齐结果。
+ const existing = s.runs.find((r) => r.id === run.id);
+ if (existing) Object.assign(existing, run);
+ else s.runs.unshift(run);
return s;
});
};
@@ -327,6 +362,12 @@ async function runLocked(
const enabledSkills = (await Promise.all(catalog.filter((s) => s.enabled !== false).map((s) => readBotSkillForBot(botId, s.slug))))
.filter((s) => s !== null);
const skillFull = learningSnapshotBudget(enabledSkills.filter((s) => s.body.length <= 12000), 30_000);
+ // 运行前的技能原文与启用状态;写入前核对,模型返回前被改过或停用的技能不覆盖。
+ const skillBefore = new Map<string, SkillSnapshot>();
+ for (const s of catalog.filter((c) => c.enabled !== false)) {
+ const source = await readBotSkillSourceForBot(botId, s.slug);
+ if (source !== null) skillBefore.set(s.slug, { source, enabled: true });
+ }
const usageNow = await countSkillUsage(botId, new Set(catalog.map((s) => s.slug)), after, throughAt);
const usage = { ...(state?.skillUsage ?? {}) };
for (const [slug, value] of usageNow) {
@@ -398,18 +439,34 @@ async function runLocked(
const items: NightlyLearningItem[] = [];
const backup: NightlyLearningBackup = {};
- const add = (item: Omit<NightlyLearningItem, 'id'>, kind: 'memory' | 'skill', b: MemorySnapshot | SkillSnapshot, a: MemorySnapshot | SkillSnapshot) => {
+ // 改动前先登记这次运行,每改一条就把备份和记录落盘:中途退出时已做的改动仍能在记录里撤销。
+ await updateNightlyLearningState(root, botId, (s) => {
+ s.runs.unshift({ id: runId, at: startedAt, ...(manual ? { manual: true } : {}), outcome: 'nothing', turns: selected.length, items: [] });
+ return s;
+ });
+ const add = async (item: Omit<NightlyLearningItem, 'id'>, kind: 'memory' | 'skill', b: MemorySnapshot | SkillSnapshot, a: MemorySnapshot | SkillSnapshot) => {
const id = `i${items.length + 1}`;
items.push({ id, ...item });
backup[id] = { kind, before: b, after: a };
+ await writeNightlyLearningBackup(root, botId, runId, backup);
+ await updateNightlyLearningState(root, botId, (s) => {
+ const run = s.runs.find((r) => r.id === runId);
+ if (!run) return null;
+ run.items = structuredClone(items);
+ run.outcome = 'learned';
+ return s;
+ });
};
const full = new Map(memoryFull.map((m) => [m.filename, m]));
- // 合并时保留的那一条可能同一轮里改了标题:「并入」显示改后的标题。
- const plannedTitles = new Map(plan.memories.flatMap((op) => (op.op === 'update' ? [[op.filename, op.title] as const] : [])));
+ // 合并 = 更新保留的那一条 + 删除来源。保留项的更新没写成功、保留项不存在或这一轮也要删时,不删来源。
+ const plannedUpdates = new Set(plan.memories.flatMap((op) => (op.op === 'update' ? [op.filename] : [])));
+ const plannedDeletes = new Set(plan.memories.flatMap((op) => (op.op === 'delete' ? [op.filename] : [])));
+ const appliedUpdates = new Map<string, string>();
const titleOf = (filename: string) =>
- plannedTitles.get(filename) ?? memories.find((m) => m.filename === filename)?.frontmatter.title ?? filename;
+ appliedUpdates.get(filename) ?? memories.find((m) => m.filename === filename)?.frontmatter.title ?? filename;
+ const memoryOps = [...plan.memories.filter((op) => op.op !== 'delete'), ...plan.memories.filter((op) => op.op === 'delete')];
- for (const op of store ? plan.memories : []) {
+ for (const op of store ? memoryOps : []) {
if (!current()) break;
try {
if (op.op === 'create') {
@@ -417,7 +474,7 @@ async function runLocked(
const filename = `${op.type}_${op.name}.md`;
if (await readMemory(store!, filename)) continue;
const target: MemorySnapshot = { filename, type: op.type, slug: op.name, title: op.title, description: op.description, body: op.body, updatedAt: '' };
- add({ kind: 'memory', action: 'created', target: filename, title: op.title, reason: op.reason }, 'memory', null, await applyMemory(store!, filename, target));
+ await add({ kind: 'memory', action: 'created', target: filename, title: op.title, reason: op.reason }, 'memory', null, await applyMemory(store!, filename, target, null));
continue;
}
const prior = full.get(op.filename);
@@ -427,13 +484,16 @@ async function runLocked(
const beforeSnap = memorySnapshot(live);
if (op.op === 'update') {
if (op.body === live.body && op.title === live.frontmatter.title && op.description === live.frontmatter.description) continue;
- const afterSnap = await applyMemory(store!, op.filename, { ...beforeSnap!, title: op.title, description: op.description, body: op.body });
- add({ kind: 'memory', action: 'updated', target: op.filename, title: op.title, reason: op.reason }, 'memory', beforeSnap, afterSnap);
+ const afterSnap = await applyMemory(store!, op.filename, { ...beforeSnap!, title: op.title, description: op.description, body: op.body }, live.frontmatter.updatedAt);
+ appliedUpdates.set(op.filename, op.title);
+ await add({ kind: 'memory', action: 'updated', target: op.filename, title: op.title, reason: op.reason }, 'memory', beforeSnap, afterSnap);
} else {
- await applyMemory(store!, op.filename, null);
- add({
+ const into = op.mergedInto;
+ if (into && (plannedDeletes.has(into) || (plannedUpdates.has(into) && !appliedUpdates.has(into)) || !(await readMemory(store!, into)))) continue;
+ await applyMemory(store!, op.filename, null, live.frontmatter.updatedAt);
+ await add({
kind: 'memory', action: 'deleted', target: op.filename, title: live.frontmatter.title, reason: op.reason,
- ...(op.mergedInto ? { mergedInto: titleOf(op.mergedInto) } : {}),
+ ...(into ? { mergedInto: titleOf(into) } : {}),
}, 'memory', beforeSnap, null);
}
} catch (error) {
@@ -443,18 +503,23 @@ async function runLocked(
const enabledSlugs = new Set(skillFull.map((s) => s.slug));
const nameOf = (slug: string) => catalog.find((s) => s.slug === slug)?.name ?? slug;
- for (const op of plan.skills) {
+ const plannedSkillUpdates = new Set(plan.skills.flatMap((op) => (op.op === 'update' ? [op.slug] : [])));
+ const appliedSkillUpdates = new Set<string>();
+ const skillOps = [...plan.skills.filter((op) => op.op === 'update'), ...plan.skills.filter((op) => op.op !== 'update')];
+ for (const op of skillOps) {
if (!current()) break;
try {
if (op.op === 'update' && !enabledSlugs.has(op.slug)) continue;
- if (op.op === 'disable' && !catalog.some((s) => s.slug === op.slug && s.enabled !== false)) continue;
+ if (op.op === 'disable' && op.mergedInto && plannedSkillUpdates.has(op.mergedInto) && !appliedSkillUpdates.has(op.mergedInto)) continue;
+ const expected = skillBefore.get(op.slug);
const beforeSnap = await readSkill(botId, op.slug);
- if (!beforeSnap) continue;
+ if (!beforeSnap || !expected || !sameSkill(beforeSnap, expected)) continue;
const target: SkillSnapshot = op.op === 'update'
? { source: renderBotSkillFile({ slug: op.slug, name: op.title, description: op.description, updatedAt: new Date().toISOString(), body: op.body }), enabled: true }
: { source: beforeSnap.source, enabled: false };
const afterSnap = await applySkill(botId, op.slug, target);
- add({
+ if (op.op === 'update') appliedSkillUpdates.add(op.slug);
+ await add({
kind: 'skill', action: op.op === 'update' ? 'updated' : 'disabled', target: op.slug,
title: op.op === 'update' ? op.title : nameOf(op.slug), reason: op.reason,
...(op.op === 'disable' && op.mergedInto ? { mergedInto: nameOf(op.mergedInto) } : {}),
@@ -472,12 +537,14 @@ async function runLocked(
if (!candidate || !hasLearningEvidence(op, messages, true)) continue;
if (catalog.some((s) => s.slug === op.slug)) continue;
try {
+ if (await readSkill(botId, op.slug)) continue;
const target: SkillSnapshot = {
source: renderBotSkillFile({ slug: op.slug, name: op.title, description: op.description, updatedAt: new Date().toISOString(), body: op.body }),
enabled: true,
};
- add({ kind: 'skill', action: 'created', target: op.slug, title: op.title, reason: op.reason }, 'skill', null, await applySkill(botId, op.slug, target));
+ const afterSnap = await applySkill(botId, op.slug, target);
promoted.add(candidate.id);
+ await add({ kind: 'skill', action: 'created', target: op.slug, title: op.title, reason: op.reason }, 'skill', null, afterSnap);
} catch (error) {
log.warn('nightly skill promotion skipped', { botId, error: String(error) });
}
@@ -492,7 +559,6 @@ async function runLocked(
}
const forgotten = new Set(plan.forget);
- if (items.length) await writeNightlyLearningBackup(root, botId, runId, backup);
await recordRun(
{ id: runId, at: startedAt, ...(manual ? { manual: true } : {}), outcome: items.length ? 'learned' : 'nothing', turns: selected.length, items },
(s) => {
@@ -509,10 +575,25 @@ async function runLocked(
return { resultText: items.length ? `Nightly learning made ${items.length} change(s)` : 'Nightly learning found nothing to change' };
}
+/**
+ * 排队等待期间可能换了账号:技能服务按执行时的当前账号取目录,备份目录却是入队前取的。
+ * 每次读写前核对仍是入队时的账号,不是就拒绝,不写进另一个账号。
+ */
+function ownerGuard(): () => void {
+ const owner = activeOwnerScopeKey();
+ const db = getDbClient();
+ return () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== owner || getDbClient() !== db)
+ throw new NightlyLearningError('UNAVAILABLE', 'Account changed');
+ };
+}
+
/** 撤销(redo=false)或恢复(redo=true)一条改动;内容在那之后被改过时拒绝,不覆盖。 */
export async function revertNightlyLearningItem(botId: string, runId: string, itemId: string, redo: boolean): Promise<void> {
const root = ownerScopedUserDataPath();
+ const assertOwner = ownerGuard();
await runSerializedForTeammate(botId, async () => {
+ assertOwner();
const state = await readNightlyLearningState(root, botId);
const item = state?.runs.find((r) => r.id === runId)?.items.find((i) => i.id === itemId);
const backup = await readNightlyLearningBackup(root, botId, runId);
@@ -526,10 +607,12 @@ export async function revertNightlyLearningItem(botId: string, runId: string, it
if (!store) throw new NightlyLearningError('UNAVAILABLE', 'Memory is turned off');
const live = memorySnapshot(await readMemory(store, item.target));
if (!sameMemory(live, expected as MemorySnapshot)) throw new NightlyLearningError('CHANGED', 'Changed since then');
- actual = await applyMemory(store, item.target, target as MemorySnapshot);
+ assertOwner();
+ actual = await applyMemory(store, item.target, target as MemorySnapshot, live?.updatedAt ?? null);
} else {
const live = await readSkill(botId, item.target);
if (!sameSkill(live, expected as SkillSnapshot)) throw new NightlyLearningError('CHANGED', 'Changed since then');
+ assertOwner();
actual = await applySkill(botId, item.target, target as SkillSnapshot);
}
// 记下还原后的实际内容(记忆的更新时间会变),下一次恢复 / 撤销按它核对。
@@ -550,8 +633,10 @@ export async function revertNightlyLearningItem(botId: string, runId: string, it
/** 「现在记成技能」直接用候选的草稿建技能并记一条可撤销记录;「不用学」移出观察且以后不再加回。 */
export async function resolveNightlyLearningCandidate(botId: string, candidateId: string, action: 'promote' | 'decline'): Promise<void> {
const root = ownerScopedUserDataPath();
+ const assertOwner = ownerGuard();
let changed = false;
await runSerializedForTeammate(botId, async () => {
+ assertOwner();
const state = await readNightlyLearningState(root, botId);
const candidate = state?.candidates.find((c) => c.id === candidateId);
if (!candidate) throw new NightlyLearningError('NOT_FOUND', 'Candidate not found');
@@ -567,6 +652,7 @@ export async function resolveNightlyLearningCandidate(botId: string, candidateId
const base = normalizeBotSkillSlug(candidate.draft.name) ?? `skill-${candidateId.replace(/[^a-z0-9]/gi, '').toLowerCase().slice(-8)}`;
let slug = base;
for (let n = 2; existing.has(slug); n += 1) slug = `${base.slice(0, 60)}-${n}`;
+ assertOwner();
const after = await applySkill(botId, slug, {
source: renderBotSkillFile({ slug, name: candidate.draft.name, description: candidate.draft.description, updatedAt: new Date().toISOString(), body: candidate.draft.body }),
enabled: true,
diff --git a/apps/desktop/src/main/maker-ipc/botNightlyLearningCounter.ts b/apps/desktop/src/main/maker-ipc/botNightlyLearningCounter.ts
index 5d101e10ac..9169a0fece 100644
--- a/apps/desktop/src/main/maker-ipc/botNightlyLearningCounter.ts
+++ b/apps/desktop/src/main/maker-ipc/botNightlyLearningCounter.ts
@@ -7,6 +7,7 @@
* 以及宿主合成的隐藏指令(开场问候、续跑等 `[UI_ACTION_TRIGGER]` 行)。
* 同一条回复只计一次(回复上记 nightlyLearningCounted),重启或重放终态不会重复计数。
*/
+import { BrowserWindow } from 'electron';
import { activeOwnerScopeKey, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
import { getDbClient } from '../localDb/client/current.js';
import { patchMessageAgentMetaWithResult } from '../localDb/ipc/messages.js';
@@ -72,4 +73,9 @@ export async function countNightlyLearningTurn(sessionId: string, replyId: strin
});
if (!claimed || !current()) return;
await recordNightlyLearningTurn(ownerScopedUserDataPath(), row.botId, sessionId, row.createdAt);
+ // 打开着的例行任务页与学习记录页随之刷新「待整理」;换账号后不推给新账号的页面。
+ if (!current()) return;
+ for (const window of BrowserWindow.getAllWindows()) {
+ if (!window.isDestroyed()) window.webContents.send('routines:changed');
+ }
}
diff --git a/apps/desktop/src/main/maker-ipc/botNightlyLearningState.ts b/apps/desktop/src/main/maker-ipc/botNightlyLearningState.ts
index 2bdec9d7d1..ec3df15797 100644
--- a/apps/desktop/src/main/maker-ipc/botNightlyLearningState.ts
+++ b/apps/desktop/src/main/maker-ipc/botNightlyLearningState.ts
@@ -35,6 +35,11 @@ export interface NightlyLearningState {
pending: { turns: number; sessions: Record<string, number>; firstAt?: number };
/** 已整理到的回复时间(created_at,毫秒);之后的回复留给下一次。 */
throughAt?: number;
+ /**
+ * 水位之后已经学过的回复(回复 client_id → created_at)。水位为等仍在生成的回复而停在前面,
+ * 或一批没读完时,下一次跳过这些回复,不重复学同一轮;水位越过后随之删除。
+ */
+ learned?: Record<string, number>;
runs: NightlyLearningRun[];
candidates: NightlyLearningCandidateRecord[];
/** 用户点过「不用学」的做法标题,避免下次又加回观察。 */
@@ -76,6 +81,8 @@ export function parseNightlyLearningState(raw: unknown): NightlyLearningState {
const pending = isRecord(raw.pending) ? raw.pending : {};
const sessions: Record<string, number> = {};
if (isRecord(pending.sessions)) for (const [id, n] of Object.entries(pending.sessions)) if (num(n) > 0) sessions[id] = num(n);
+ const learned: Record<string, number> = {};
+ if (isRecord(raw.learned)) for (const [id, at] of Object.entries(raw.learned)) if (num(at) > 0) learned[id] = num(at);
const usage: NightlyLearningState['skillUsage'] = {};
if (isRecord(raw.skillUsage)) for (const [slug, value] of Object.entries(raw.skillUsage))
if (isRecord(value)) usage[slug] = { count: num(value.count), lastUsedAt: num(value.lastUsedAt) };
@@ -85,6 +92,7 @@ export function parseNightlyLearningState(raw: unknown): NightlyLearningState {
...(raw.frequency === 'weekly' ? { frequency: 'weekly' as const } : {}),
pending: { turns: num(pending.turns), sessions, ...(num(pending.firstAt) ? { firstAt: num(pending.firstAt) } : {}) },
...(num(raw.throughAt) ? { throughAt: num(raw.throughAt) } : {}),
+ ...(Object.keys(learned).length ? { learned } : {}),
runs: Array.isArray(raw.runs) ? (raw.runs.filter(isRecord) as unknown as NightlyLearningRun[]).slice(0, MAX_RUNS) : [],
candidates: Array.isArray(raw.candidates)
? (raw.candidates.filter((c) => isRecord(c) && typeof c.id === 'string' && isRecord(c.draft)) as unknown as NightlyLearningCandidateRecord[])
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index dd6b0f4bf6..a84809551d 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -173,8 +173,14 @@ id 为 `builtin-nightly-learning-<伙伴 id>`,过长时同样改用 sha256 前
读不完的留到下一次),模型只提议,宿主逐条校验后落盘:新记忆须引用主人原话;只改快照里读到全文的记忆与技能;
只出现一次的做法放进「在观察的做法」(不加载、不进提示词),同类事再次出现或主人点「现在记成技能」才转正为技能;
停用技能、删除记忆要写理由。记忆关闭时不读也不写记忆。成功才推进水位并按处理过的轮数扣减计数,失败保留计数。
-- **撤销**:每条改动前后内容存在 `learning-history/<runId>.json`,记录页逐条撤销 / 恢复;之后被主人或伙伴改过的
- 内容不覆盖,提示不能撤销。停用技能走已有的 `disabled-skills/`。
+ 水位按扫过的回复推进(被过滤的也算扫过);6 小时内开始、仍在生成的回复挡住水位,完成后再学;为此停在前面时,
+ 已学过的回复记在 `learned` 里跳过,不重复学。
+- **不覆盖并发修改**:记忆按运行前读到的版本交给存储层核对;技能按运行前的原文与启用状态核对;模型思考期间被改过的
+ 一律跳过。合并(更新保留项 + 删除 / 停用来源)只有保留项写成功、仍存在且本轮不删时才处理来源。
+- **撤销**:改动前先登记这次运行,每改一条就把前后内容写入 `learning-history/<runId>.json` 并更新记录,中途退出时
+ 已做的改动仍能撤销。记录页逐条撤销 / 恢复;之后被主人或伙伴改过的内容不覆盖,提示不能撤销;排队期间换了账号的
+ 撤销与转正直接拒绝。停用技能走已有的 `disabled-skills/`。
+- **刷新**:计数成功后通知已打开的例行任务页与学习记录页刷新「待整理」。
- 结果只进伙伴设置「例行任务 → 夜间学习」的记录页,不插入聊天时间线,不发推送。不随云端伙伴同步。
- 回复后复盘已于 2026-10-23 停用(`cindy-bots-runtime.md` §3.2);对话中记忆照常当场保存,
技能只在主人明确要求或纠正已有技能时当场保存,其余交给夜间学习。