UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

858 lines (857 loc) • 28 kB
import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import { b as uniqueStrings, f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { E as resolveMemoryRemDreamingConfig, T as resolveMemoryLightDreamingConfig, _ as formatMemoryDreamingDay } from "./dreaming-C72ZWZJr.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./error-runtime-BM740gJj.mjs"; import { c as readWorkspaceText, i as listWorkspaceDirectory, r as inspectWorkspaceFile } from "./memory-workspace-files-Ekb7DRdf.mjs"; import { n as listMemoryArtifactProvenance } from "./memory-artifact-provenance-5S6kb8QC.mjs"; import "./memory-core-host-engine-foundation-CvV28XoZ.mjs"; import { n as listSessionTranscriptCorpusEntriesForAgent } from "./memory-core-host-engine-sessions-DAG-vYby.mjs"; import "./memory-core-host-status-B88S-xY5.mjs"; import "./memory-core-host-runtime-core-vt7Kf2j2.mjs"; import "./dreaming-shared-BXVwrm4P.mjs"; import { t as appendFailedDreamingEvent } from "./dreaming-events-j1JNkKH0.mjs"; import { N as isGenericDailyHeading, O as compareStoreTimestampDesc, X as normalizeConceptToken, o as readRecentDreamDiaryEntries, tt as withMemoryWorkspaceLock } from "./dreaming-dreams-file-Cbm7FmRe.mjs"; import { c as filterFreshLightDreamingEntries, d as recordDreamingPhaseSignals, f as recordRemConsideredPhaseSignals, p as isPromotionOriginBlocked, u as readLightStagedKeys } from "./short-term-promotion-B9mXaw_L.mjs"; import { S as writeSessionIngestionState, _ as normalizeMemoryDay, b as readSessionIngestionState, c as resolveSessionAgentsForWorkspace, d as sessionExclusionReasons, f as sessionIngestionSourceFromCorpus, g as compareDailyMemoryFilesByNewestDay, h as DAILY_MEMORY_FILENAME_RE, l as resolveSessionIngestionFileCap, m as trimTrackedSessionScopes, o as mergeTrackedMessageHashes, p as sessionIngestionStateKeyFromCorpus, r as appendSessionCorpusLines, s as resolveAdmissionPolicy, u as scanSessionIngestionSource, v as parseDailyMemoryFileName, x as writeDailyIngestionState, y as readDailyIngestionState } from "./session-ingestion-BF9O-2hL.mjs"; import { n as writeDailyDreamingPhaseBlock } from "./dreaming-markdown-Dm0h3ndB.mjs"; import { n as preparedTextSimilarity, t as prepareSimilarityText } from "./tokenize-Cj8uCWRq.mjs"; import { t as findForgottenMemorySessionIds } from "./memory-entry-origins-DE0zsEvo.mjs"; import { n as readShortTermRecallEntries, r as recordShortTermRecalls, t as filterLiveShortTermRecallEntries } from "./short-term-promotion-record-CRlApliA.mjs"; import path from "node:path"; import { createHash } from "node:crypto"; //#region extensions/memory-core/src/dreaming-snippet-dedupe.ts const LIGHT_DIARY_SNIPPET_SIMILARITY_THRESHOLD = .35; function dedupeEntries(e, t) { const n = []; const r = /* @__PURE__ */ new Map(); for (const i of e) { const e = r.get(i.path); const a = prepareSimilarityText(i.snippet); const o = e?.find((e) => preparedTextSimilarity(e.prepared, a) >= t)?.candidate; if (o) { o.sourceEntryKeys.push(i.key); if (i.recallCount > o.recallCount) o.recallCount = i.recallCount; o.totalScore = Math.max(o.totalScore, i.totalScore); o.recallDays = [.../* @__PURE__ */ new Set([...o.recallDays, ...i.recallDays])].toSorted(); o.conceptTags = uniqueStrings([...o.conceptTags, ...i.conceptTags]); o.lastRecalledAt = compareStoreTimestampDesc(i.lastRecalledAt, o.lastRecalledAt) < 0 ? i.lastRecalledAt : o.lastRecalledAt; continue; } const s = { ...i, sourceEntryKeys: [i.key] }; n.push(s); if (e) e.push({ candidate: s, prepared: a }); else r.set(i.path, [{ candidate: s, prepared: a }]); } return n; } function normalizeDiaryCoverageText(e) { return e.toLowerCase().replace(/\s+/g, " ").trim(); } function isEntryCoveredByRecentDiary(e, t) { const n = normalizeDiaryCoverageText(e.snippet); if (!n) return false; const r = prepareSimilarityText(e.snippet); return t.some((e) => e.normalized.includes(n) || preparedTextSimilarity(r, e.prepared) >= LIGHT_DIARY_SNIPPET_SIMILARITY_THRESHOLD); } function prioritizeLightEntriesByDiaryCoverage(e, t) { if (t.length === 0) return e; const n = t.map((e) => ({ normalized: normalizeDiaryCoverageText(e), prepared: prepareSimilarityText(e) })); const r = []; const i = []; for (const t of e) if (isEntryCoveredByRecentDiary(t, n)) i.push(t); else r.push(t); return [...r, ...i]; } //#endregion //#region extensions/memory-core/src/dreaming-phases.ts const DAILY_INGESTION_SCORE = .62; const DAILY_INGESTION_MAX_SNIPPET_CHARS = 280; const DAILY_INGESTION_MIN_SNIPPET_CHARS = 8; const DAILY_INGESTION_MAX_CHUNK_LINES = 4; const LIGHT_DIARY_HISTORY_LIMIT = 4; const MANAGED_DAILY_DREAMING_BLOCKS = [{ heading: "## Light Sleep", startMarker: "<!-- openclaw:dreaming:light:start -->", endMarker: "<!-- openclaw:dreaming:light:end -->" }, { heading: "## REM Sleep", startMarker: "<!-- openclaw:dreaming:rem:start -->", endMarker: "<!-- openclaw:dreaming:rem:end -->" }]; function calculateLookbackCutoffMs(e, t) { return e - Math.max(0, t) * 24 * 60 * 60 * 1e3; } function isDayWithinLookback(e, t) { const n = Date.parse(`${e}T23:59:59.999Z`); return Number.isFinite(n) && n >= t; } function normalizeDailyListMarker(e) { return e.replace(/^\d+\.\s+/, "").replace(/^[-*+]\s+/, "").trim(); } function normalizeDailyHeading(e) { const t = e.trim().match(/^#{1,6}\s+(.+)$/); if (!t) return null; const n = t[1] ? normalizeDailyListMarker(t[1]) : ""; if (!n || DAILY_MEMORY_FILENAME_RE.test(n) || isGenericDailyHeading(n)) return null; return truncateUtf16Safe(n, DAILY_INGESTION_MAX_SNIPPET_CHARS).replace(/\s+/g, " "); } function normalizeDailySnippet(e) { const t = e.trim(); if (!t || t.startsWith("#") || t.startsWith("<!--")) return null; const n = normalizeDailyListMarker(t); if (n.length < DAILY_INGESTION_MIN_SNIPPET_CHARS) return null; return truncateUtf16Safe(n, DAILY_INGESTION_MAX_SNIPPET_CHARS).replace(/\s+/g, " "); } function buildDailyChunkSnippet(e, t) { const n = t.join(" ").trim(); const r = e ? `${e}: ${n}` : n; return truncateUtf16Safe(r, DAILY_INGESTION_MAX_SNIPPET_CHARS).replace(/\s+/g, " ").trim(); } function buildDailyListSnippet(e, t, n) { return buildDailyChunkSnippet(e, [[...t, n].join(" > ").replaceAll(": > ", ": ")]); } function buildDailySnippetChunks(e, t) { const n = []; let r = null; let i = []; let a = 0; let o = []; const flushChunk = () => { if (i.length === 0) return; const e = buildDailyChunkSnippet(r, i); if (e.length >= DAILY_INGESTION_MIN_SNIPPET_CHARS) n.push({ startLine: a, endLine: a + i.length - 1, snippet: e }); i = []; }; for (let s = 0; s < e.length; s += 1) { const c = e[s]; const l = normalizeDailyHeading(c); if (l) { flushChunk(); r = l; o = []; continue; } const u = c.trim(); if (!u || u.startsWith("<!--")) { flushChunk(); o = []; continue; } const d = c.match(/^(\s*)(?:[-*+]|\d+\.)\s+(.+)$/); if (d) { flushChunk(); const i = d[1]?.length ?? 0; const a = truncateUtf16Safe(normalizeDailyListMarker(u), DAILY_INGESTION_MAX_SNIPPET_CHARS).replace(/\s+/g, " "); if (!a) { o = []; continue; } while ((o.at(-1)?.indent ?? -1) >= i) o.pop(); const c = []; let l = s; let f = false; let p; for (let t = s + 1; t < e.length; t += 1) { const n = e[t]; const r = n.trim(); if (!r) { let n = t + 1; while (n < e.length && !e[n]?.trim()) n += 1; const r = e[n]?.match(/^(\s*)(?:[-*+]|\d+\.)\s+(.+)$/); if (r && (r[1]?.length ?? 0) > i) { f = true; p = n; } break; } if (r.startsWith("#") || r.startsWith("<!--")) break; const a = n.match(/^(\s*)(?:[-*+]|\d+\.)\s+(.+)$/); if (a) { f = (a[1]?.length ?? 0) > i; break; } c.push(r.replace(/\s+/g, " ")); l = t; } const m = [a, ...c].join(" "); const h = buildDailyListSnippet(r, o.map((e) => e.text), m); if (!(f && c.length === 0 && a.endsWith(":")) && h.length >= DAILY_INGESTION_MIN_SNIPPET_CHARS) n.push({ startLine: s + 1, endLine: l + 1, snippet: h, identitySnippet: h }); o.push({ indent: i, text: m }); s = p === void 0 ? l : p - 1; if (n.length >= t) break; continue; } o = []; const f = normalizeDailySnippet(c); if (!f) { flushChunk(); continue; } if (i.length >= DAILY_INGESTION_MAX_CHUNK_LINES) flushChunk(); if (i.length === 0) a = s + 1; i.push(f); if (n.length >= t) break; } flushChunk(); return n.slice(0, t); } function resolveDailyFileProvenance(e) { if (e.recorded?.originClass === "untrusted") return { originClass: "untrusted", observedAt: e.recorded.observedAt }; if (e.recorded?.fileHash === e.currentHash) return { originClass: e.recorded.originClass, observedAt: e.recorded.observedAt }; return { originClass: "agent", observedAt: e.defaultObservedAt }; } async function readDailyFileProvenance(e) { return new Map((await listMemoryArtifactProvenance({ workspaceDir: e })).map((e) => [e.relativePath, e.provenance])); } function findManagedDailyDreamingHeadingIndex(e, t, n) { for (let r = t - 1; r >= 0; r -= 1) { const t = e[r]?.trim() ?? ""; if (!t) continue; return t === n ? r : null; } return null; } function isManagedDailyDreamingBoundary(e, t, n) { const r = e.trim(); const i = /^#{1,6}(?=\s)/.exec(r); return i !== null && i[0].length <= t || n.has(r); } function stripManagedDailyDreamingLines(e) { const t = new Map(MANAGED_DAILY_DREAMING_BLOCKS.map((e) => [e.startMarker, e])); const n = [...e]; for (let r = 0; r < n.length; r += 1) { const i = t.get(n[r]?.trim() ?? ""); if (!i) continue; let a = -1; for (let e = r + 1; e < n.length; e += 1) { const r = n[e]; if ((r?.trim() ?? "") === i.endMarker) { a = e; break; } if (r && isManagedDailyDreamingBoundary(r, i.heading.indexOf(" "), t)) { a = e - 1; break; } } if (a < r) continue; const o = findManagedDailyDreamingHeadingIndex(e, r, i.heading) ?? r; for (let e = o; e <= a; e += 1) n[e] = ""; r = a; } return n; } function buildDailyIngestionResults(e) { const t = resolveDailyFileProvenance({ currentHash: createHash("sha256").update(e.raw).digest("hex"), defaultObservedAt: e.defaultObservedAt, ...e.recorded ? { recorded: e.recorded } : {} }); return buildDailySnippetChunks(stripManagedDailyDreamingLines(e.raw.split(/\r?\n/)), e.limit).map((n) => Object.assign({ path: e.path, startLine: n.startLine, endLine: n.endLine, score: DAILY_INGESTION_SCORE, snippet: n.snippet, source: "memory", provenance: { ...t, sessionKind: "unknown" } }, n.identitySnippet ? { identitySnippet: n.identitySnippet } : {})); } function entryWithinLookback(e, t) { if ((e.recallDays ?? []).some((e) => isDayWithinLookback(e, t))) return true; if (Math.max(0, Math.floor(e.dailyCount ?? 0)) > 0 && Math.max(0, Math.floor(e.recallCount ?? 0)) === 0 && Math.max(0, Math.floor(e.groundedCount ?? 0)) === 0) return false; const n = Date.parse(e.lastRecalledAt); return Number.isFinite(n) && n >= t; } function filterRecallEntriesWithinLookback(e) { const t = calculateLookbackCutoffMs(e.nowMs, e.lookbackDays); return e.entries.filter((e) => entryWithinLookback(e, t)); } function resolveWorkspaceMemoryRelativePath(e, t) { const n = path.relative(e, t).replace(/\\/g, "/"); if (n && n !== ".." && !n.startsWith("../")) return n; return `memory/${path.basename(t)}`; } async function collectSessionIngestionBatches(e) { if (!e.cfg) { const t = { version: 3, files: {}, seenMessages: {} }; return { batches: [], nextState: t, changed: JSON.stringify(t) !== JSON.stringify(e.state) }; } const t = resolveSessionAgentsForWorkspace({ cfg: e.cfg, workspaceDir: e.workspaceDir }); const n = calculateLookbackCutoffMs(e.nowMs, e.lookbackDays); const r = /* @__PURE__ */ new Map(); const i = { ...e.state.files }; const a = { ...e.state.seenMessages }; const o = []; for (const n of t) { const t = /* @__PURE__ */ new Set(); const r = await listSessionTranscriptCorpusEntriesForAgent(n, { config: e.cfg, includeRetainedSqlite: true, includeContentRevision: false }); const a = await findForgottenMemorySessionIds({ agentId: n, sessionIds: r.map((e) => e.sessionId) }); const s = []; for (const e of r) { t.add(sessionIngestionStateKeyFromCorpus(e)); const n = sessionIngestionSourceFromCorpus(e, "dreaming"); if (n) s.push(n); } const c = await sessionExclusionReasons(s, e.admissionPolicy, a); for (const e of s) { const t = c.get(e); if (t) { i[e.stateKey] = { mtimeMs: e.buildOptions.updatedAtMs ?? 0, size: 0, contentHash: "", lineCount: 0, lastContentLine: 0, excludedReason: t }; continue; } o.push(e); } for (const e of Object.keys(i)) if (e.startsWith(`${n}:`) && !t.has(e)) delete i[e]; } const s = o.toSorted((e, t) => { if (e.agentId !== t.agentId) return e.agentId.localeCompare(t.agentId); return e.sessionPath.localeCompare(t.sessionPath); }); let c = 240; const l = resolveSessionIngestionFileCap(s.length); for (const t of s) { if (c <= 0) break; const o = Math.max(1, Math.min(l, c)); const s = await scanSessionIngestionSource({ source: t, previous: e.state.files[t.stateKey], seenMessages: a, timezone: e.timezone, maxCandidates: o, classifyDay: (e) => isDayWithinLookback(e, n) ? "include" : "skip" }); if (s.status === "absent") { delete i[t.stateKey]; continue; } if (s.fileState) i[t.stateKey] = s.fileState; if (s.status !== "scanned") continue; for (const e of s.candidates) { const t = r.get(e.day) ?? []; t.push(e); r.set(e.day, t); } if (s.candidates.length > 0) { const e = a[t.scope] ?? []; a[t.scope] = mergeTrackedMessageHashes(e, s.candidates.map((e) => e.hash)); c -= s.candidates.length; } } const u = trimTrackedSessionScopes(a); const d = []; for (const t of [...r.keys()].toSorted()) { const n = r.get(t) ?? []; if (n.length === 0) continue; const i = await appendSessionCorpusLines({ workspaceDir: e.workspaceDir, day: t, lines: n }); if (i.length > 0) d.push({ day: t, results: i }); } const f = { version: 3, files: i, seenMessages: u }; return { batches: d, nextState: f, changed: JSON.stringify(f) !== JSON.stringify(e.state) }; } const DEFAULT_DAILY_INGESTION_LOOKBACK_DAYS = 14; function dailyIngestionLookbackDays(e) { return Math.max(DEFAULT_DAILY_INGESTION_LOOKBACK_DAYS, e); } async function collectDailyIngestionBatches(e) { const t = await readDailyFileProvenance(e.workspaceDir); const n = path.join(e.workspaceDir, "memory"); const r = calculateLookbackCutoffMs(e.nowMs, e.lookbackDays); const i = (await listWorkspaceDirectory(e.workspaceDir, n).catch((e) => { if (extractErrorCode(e) === "ENOENT") return []; throw e; })).flatMap((e) => { const t = e.isFile() ? parseDailyMemoryFileName(e.name) : null; return t && isDayWithinLookback(t.day, r) ? [t] : []; }).toSorted(compareDailyMemoryFilesByNewestDay); const a = []; const o = new Set(i.map((e) => `memory/${e.fileName}`)); const s = Object.fromEntries(Object.entries(e.state.files).filter(([e]) => o.has(e))); let c = false; const l = Math.max(20, e.limit * 4); const u = Math.max(6, Math.ceil(l / Math.max(1, i.length))); let d = 0; for (const r of i) { const i = `memory/${r.fileName}`; const o = path.join(n, r.fileName); const f = await inspectWorkspaceFile(e.workspaceDir, o).catch((e) => { if (extractErrorCode(e) === "ENOENT") return null; throw e; }); if (!f) { delete s[i]; continue; } const p = { mtimeMs: Math.floor(Math.max(0, f.mtimeMs)), size: Math.floor(Math.max(0, f.size)) }; s[i] = p; const m = e.state.files[i]; const h = m !== void 0 && m.mtimeMs === p.mtimeMs && m.size === p.size; const g = normalizeMemoryDay(m?.lastDreamingDayIngested); if (h && g === e.ingestionDreamingDay) { p.lastDreamingDayIngested = g; continue; } c = true; const _ = await readWorkspaceText(e.workspaceDir, o).catch((e) => { if (extractErrorCode(e) === "ENOENT") return ""; throw e; }); if (!_) continue; const v = t.get(i); const y = buildDailyIngestionResults({ raw: _, path: i, limit: Math.min(u, l - d), defaultObservedAt: p.mtimeMs, ...v ? { recorded: v } : {} }); if (y.length === 0) continue; a.push({ day: r.day, results: y }); d += y.length; p.lastDreamingDayIngested = e.ingestionDreamingDay; if (d >= l) break; } if (!c) { const t = Object.keys(e.state.files); const n = Object.keys(s); if (t.length !== n.length || t.some((e) => !Object.hasOwn(s, e))) c = true; } return { batches: a, nextState: { version: 1, files: s }, changed: c }; } async function seedHistoricalDailyMemorySignals(e) { const t = uniqueStrings(normalizeStringEntries(e.filePaths)); if (t.length === 0) return { importedFileCount: 0, importedSignalCount: 0, skippedPaths: [] }; return await withMemoryWorkspaceLock(e.workspaceDir, async () => { const n = await readDailyFileProvenance(e.workspaceDir); const r = t.map((e) => ({ filePath: e, file: parseDailyMemoryFileName(path.basename(e)) })).toSorted((e, t) => { if (e.file && t.file) return compareDailyMemoryFilesByNewestDay(e.file, t.file); if (e.file) return -1; if (t.file) return 1; return e.filePath.localeCompare(t.filePath); }); const i = r.flatMap((e) => e.file ? [{ filePath: e.filePath, file: e.file }] : []); const a = r.filter((e) => !e.file).map((e) => e.filePath); const o = Math.max(20, e.limit * 4); const s = Math.max(6, Math.ceil(o / Math.max(1, i.length))); let c = 0; let l = 0; for (const t of i) { if (c >= o) break; const r = await readWorkspaceText(e.workspaceDir, t.filePath).catch((e) => { if (extractErrorCode(e) === "ENOENT") { a.push(t.filePath); return ""; } throw e; }); if (!r) continue; const i = resolveWorkspaceMemoryRelativePath(e.workspaceDir, t.filePath); const u = n.get(i); const d = buildDailyIngestionResults({ raw: r, path: i, limit: Math.min(s, o - c), defaultObservedAt: e.nowMs, ...u ? { recorded: u } : {} }); if (d.length === 0) continue; await recordShortTermRecalls({ workspaceDir: e.workspaceDir, query: `__dreaming_daily__:${t.file.day}`, results: d, signalType: "daily", dedupeByQueryPerDay: true, dayBucket: formatMemoryDreamingDay(e.nowMs, e.timezone), nowMs: e.nowMs, timezone: e.timezone }); c += d.length; l += 1; } return { importedFileCount: l, importedSignalCount: c, skippedPaths: a }; }); } function entryAverageScore(e) { const t = Math.max(0, Math.floor(e.recallCount ?? 0) + Math.floor(e.dailyCount ?? 0) + Math.floor(e.groundedCount ?? 0)); return t > 0 ? Math.max(0, Math.min(1, e.totalScore / t)) : 0; } function buildLightDreamingBody(e) { if (e.length === 0) return ["- No notable updates."]; return e.flatMap((e) => [ `- Candidate: ${e.snippet || "(no snippet captured)"}`, ` - confidence: ${entryAverageScore(e).toFixed(2)}`, ` - evidence: ${e.path}:${e.startLine}-${e.endLine}`, ` - recalls: ${e.recallCount}`, ` - status: staged` ]); } function calculateCandidateTruthConfidence(e) { const t = Math.min(1, Math.log1p(e.recallCount) / Math.log1p(6)); const n = entryAverageScore(e); const r = Math.min(1, (e.recallDays?.length ?? 0) / 3); const i = Math.min(1, (e.conceptTags?.length ?? 0) / 6); return Math.max(0, Math.min(1, n * .45 + t * .25 + r * .2 + i * .1)); } function selectRemCandidateTruths(e, t) { if (t <= 0) return []; return dedupeEntries(e.filter((e) => !e.promotedAt), .88).map((e) => ({ key: e.key, snippet: e.snippet || "(no snippet captured)", confidence: calculateCandidateTruthConfidence(e), evidence: `${e.path}:${e.startLine}-${e.endLine}` })).filter((e) => e.confidence >= .45).toSorted((e, t) => t.confidence - e.confidence || e.snippet.localeCompare(t.snippet)).slice(0, t); } function buildRemReflections(e, t, n) { const r = /* @__PURE__ */ new Map(); for (const t of e) for (const e of new Set(t.conceptTags.map(normalizeConceptToken))) { if (!e) continue; const n = r.get(e) ?? { count: 0, evidence: /* @__PURE__ */ new Set() }; n.count += 1; n.evidence.add(`${t.path}:${t.startLine}-${t.endLine}`); r.set(e, n); } const i = [...r.entries()].map(([t, n]) => { return { tag: t, strength: Math.min(1, n.count / Math.max(1, e.length) * 2), stat: n }; }).filter((e) => e.strength >= n).toSorted((e, t) => t.strength - e.strength || t.stat.count - e.stat.count || e.tag.localeCompare(t.tag)).slice(0, t); if (i.length === 0) return ["- No strong patterns surfaced."]; return i.flatMap((e) => [ `- Theme: \`${e.tag}\` kept surfacing across ${e.stat.count} memories.`, ` - confidence: ${e.strength.toFixed(2)}`, ` - evidence: ${[...e.stat.evidence].slice(0, 3).join(", ")}`, ` - note: reflection` ]); } function previewRemDreaming(e) { const t = buildRemReflections(e.entries, e.limit, e.minPatternStrength); const n = selectRemCandidateTruths(e.entries, Math.max(1, Math.min(3, e.limit))); const r = n.map((e) => ({ snippet: e.snippet, confidence: e.confidence, evidence: e.evidence })); const i = uniqueStrings(n.map((e) => e.key)); const a = [ "### Reflections", ...t, "", "### Possible Lasting Truths", ...r.length > 0 ? r.map((e) => `- ${e.snippet} [confidence=${e.confidence.toFixed(2)} evidence=${e.evidence}]`) : ["- No strong candidate truths surfaced."] ]; return { sourceEntryCount: e.entries.length, reflections: t, candidateTruths: r, candidateKeys: i, bodyLines: a }; } async function ingestDreamingPhaseSignals(e) { const { workspaceDir: t, nowMs: n } = e; const r = { workspaceDir: t, nowMs: n, timezone: e.config.timezone }; const recordBatches = async (e, t, n) => { for (const i of e) await recordShortTermRecalls({ ...r, query: `__dreaming_${t}__:${i.day}`, results: i.results, signalType: "daily", dedupeByQueryPerDay: t === "sessions", dayBucket: n ?? i.day }); }; await withMemoryWorkspaceLock(t, async () => { const i = await readDailyIngestionState(t); const a = formatMemoryDreamingDay(n, r.timezone); const o = await collectDailyIngestionBatches({ ...r, lookbackDays: dailyIngestionLookbackDays(e.config.lookbackDays), limit: e.config.limit, ingestionDreamingDay: a, state: i }); await recordBatches(o.batches, "daily"); if (o.changed) await writeDailyIngestionState(t, o.nextState); }); await withMemoryWorkspaceLock(t, async () => { const i = await readSessionIngestionState(t); const a = await collectSessionIngestionBatches({ ...r, cfg: e.cfg, lookbackDays: e.config.lookbackDays, admissionPolicy: e.admissionPolicy, state: i }); const o = formatMemoryDreamingDay(n, r.timezone); await recordBatches(a.batches, "sessions", o); if (a.changed) await writeSessionIngestionState(t, a.nextState); }); } async function readDreamingPhaseEntries(e, t) { const { workspaceDir: n, nowMs: r } = e; let i = filterRecallEntriesWithinLookback({ entries: await readShortTermRecallEntries({ workspaceDir: n, nowMs: r }), nowMs: r, lookbackDays: e.config.lookbackDays }); if (t === "light") i = await filterFreshLightDreamingEntries({ workspaceDir: n, nowMs: r, entries: i }); return (await filterLiveShortTermRecallEntries({ workspaceDir: n, entries: i })).filter((e) => !isPromotionOriginBlocked(e)); } async function prepareLightDreaming(e) { const { nowMs: t } = e; const n = await readDreamingPhaseEntries(e, "light"); const r = dedupeEntries(n.toSorted((e, t) => { const n = compareStoreTimestampDesc(e.lastRecalledAt, t.lastRecalledAt); if (n !== 0) return n; return t.recallCount - e.recallCount; }), e.config.dedupeSimilarity); const i = await readRecentDreamDiaryEntries({ workspaceDir: e.workspaceDir, limit: LIGHT_DIARY_HISTORY_LIMIT }); const a = prioritizeLightEntriesByDiaryCoverage(r, i); const o = a.slice(0, e.config.limit); let s; if (o.length > 0) { const n = uniqueStrings(o.flatMap((e) => e.conceptTags).filter(Boolean)); s = { phase: "light", snippets: o.map((e) => e.snippet).filter(Boolean), sourceEntryKeys: o.flatMap((e) => e.sourceEntryKeys), currentDate: formatMemoryDreamingDay(t, e.config.timezone), ...n.length > 0 ? { themes: n } : {}, ...i.length > 0 ? { recentDiaryEntries: i } : {} }; } return { bodyLines: buildLightDreamingBody(o), keys: o.map((e) => e.key), logMessage: `memory-core: light dreaming staged ${Math.min(a.length, e.config.limit)} candidate(s) [workspace=${e.workspaceDir}].`, data: s }; } async function prepareRemDreaming(e) { const { nowMs: t } = e; const n = await readDreamingPhaseEntries(e, "rem"); const r = await readLightStagedKeys({ workspaceDir: e.workspaceDir, nowMs: t }); const i = r.size > 0 ? n.filter((e) => r.has(e.key)) : []; const a = i.length > 0 ? i : n; const o = previewRemDreaming({ entries: a, limit: e.config.limit, minPatternStrength: e.config.minPatternStrength }); let s; if (a.length > 0) { const e = o.candidateTruths.map((e) => e.snippet).filter(Boolean); const t = o.reflections.filter((e) => !e.startsWith("- No strong") && !e.startsWith(" -")); s = { phase: "rem", sourceEntryKeys: a.map((e) => e.key), snippets: e.length > 0 ? e : a.slice(0, 8).map((e) => e.snippet).filter(Boolean), ...t.length > 0 ? { themes: t } : {} }; } return { bodyLines: o.bodyLines, keys: o.candidateKeys, consideredKeys: i.map((e) => e.key), logMessage: `memory-core: REM dreaming wrote reflections from ${a.length} recent memory trace(s) [workspace=${e.workspaceDir}].`, data: s }; } async function runDreamingSweepPhases(e) { const t = typeof e.nowMs === "number" && Number.isFinite(e.nowMs) ? e.nowMs : Date.now(); const n = resolveAdmissionPolicy(e.pluginConfig); const r = []; let i = false; async function runPhase(a, o, s) { if (!o.enabled || o.limit <= 0) return; try { const i = { ...e, config: o, nowMs: t, admissionPolicy: n }; await ingestDreamingPhaseSignals(i); const c = await withMemoryWorkspaceLock(e.workspaceDir, async () => { const n = await s(i); const r = { workspaceDir: e.workspaceDir, phase: a, nowMs: t }; await writeDailyDreamingPhaseBlock({ ...r, bodyLines: n.bodyLines, hasContent: n.data !== void 0, timezone: o.timezone, storage: o.storage }); if (n.consideredKeys?.length) await recordRemConsideredPhaseSignals({ ...r, keys: n.consideredKeys }); await recordDreamingPhaseSignals({ ...r, keys: n.keys }); if (n.data && o.storage.mode !== "separate") e.logger.info(n.logMessage); return n.data; }); if (c) r.push({ data: c, timezone: o.timezone, model: o.execution?.model }); } catch (n) { await appendFailedDreamingEvent({ workspaceDir: e.workspaceDir, phase: a, error: formatErrorMessage(n), storageMode: o.storage.mode, nowMs: t, logger: e.logger }); e.logger.error(`memory-core: ${a} dreaming failed: ${formatErrorMessage(n)}`); i = true; } } await runPhase("light", resolveMemoryLightDreamingConfig(e), prepareLightDreaming); if (!i) await runPhase("rem", resolveMemoryRemDreamingConfig(e), prepareRemDreaming); return { narratives: r, failed: i }; } //#endregion export { seedHistoricalDailyMemorySignals as i, previewRemDreaming as n, runDreamingSweepPhases as r, filterRecallEntriesWithinLookback as t };