@aeondave/pi-persona-mind 0.9.7 → 0.9.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +137 -137
- package/CHANGELOG.md +287 -282
- package/LICENSE +24 -24
- package/README.md +1 -1
- package/docs/DESIGN.md +605 -605
- package/docs/MEMORY-RESEARCH.md +163 -163
- package/package.json +11 -2
- package/src/core/auto-optimize.ts +323 -323
- package/src/core/backlog.ts +228 -228
- package/src/core/blocked.ts +38 -38
- package/src/core/capture.ts +155 -155
- package/src/core/context-budget.ts +74 -74
- package/src/core/handoff-store.ts +111 -111
- package/src/core/handoff.ts +70 -70
- package/src/core/host-compat.ts +16 -16
- package/src/core/ids.ts +59 -59
- package/src/core/inject.ts +247 -247
- package/src/core/knowledge-review.ts +107 -107
- package/src/core/memory-read.ts +34 -34
- package/src/core/memory.ts +321 -321
- package/src/core/migrate.ts +713 -713
- package/src/core/mind-settings.ts +54 -54
- package/src/core/optimize-history.ts +163 -163
- package/src/core/optimize-service.ts +189 -189
- package/src/core/optimize.ts +127 -127
- package/src/core/retrieval.ts +164 -164
- package/src/core/scanner.ts +146 -146
- package/src/core/scope.ts +201 -201
- package/src/core/service.ts +720 -720
- package/src/core/session-memory.ts +71 -71
- package/src/core/store.ts +1002 -1002
- package/src/extension/activity.ts +79 -79
- package/src/extension/auto-optimize-session.ts +143 -143
- package/src/extension/auto-optimize.ts +565 -565
- package/src/extension/handoff.ts +23 -23
- package/src/extension/knowledge-review.ts +229 -229
- package/src/extension/memory-inspector.ts +82 -82
- package/src/extension/mind-actions.ts +38 -38
- package/src/extension/mind-worker.ts +32 -32
- package/src/extension/persona-dependency.ts +76 -76
- package/src/extension/reference-anchor.ts +48 -48
- package/src/extension/review-evidence.ts +222 -222
- package/src/extension/worker-memory-anchor.ts +28 -28
- package/src/session-memory.ts +127 -127
- package/src/tools/backlog.ts +126 -126
- package/src/tools/memory-handoff.ts +30 -30
- package/src/tools/memory-history.ts +46 -46
- package/src/tools/memory.ts +6 -4
- package/src/ui/card-frame.ts +161 -161
- package/src/ui/inspector-frame.ts +44 -44
- package/src/ui/memory-inspector.ts +464 -464
- package/src/ui/mind-result-card.ts +48 -48
- package/src/ui/presentation.ts +87 -87
- package/src/ui/session-note-card.ts +58 -58
package/src/core/memory.ts
CHANGED
|
@@ -1,321 +1,321 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The memory faculty — pure domain logic, no I/O.
|
|
3
|
-
*
|
|
4
|
-
* Two temporal tiers share this one entry shape:
|
|
5
|
-
* - LONG-TERM (identity): durable, persona-scoped, never expires. Who a persona is for this user.
|
|
6
|
-
* - SHORT-TERM (working context): project-scoped, carries an `expiresAt`, decays on its own.
|
|
7
|
-
* The tier is not stored on the entry — it is implied by which file the entry lives in (LTM vs STM)
|
|
8
|
-
* and by whether it has an `expiresAt`. This module builds, validates, dedups/supersedes, decays,
|
|
9
|
-
* and ranks entries; rendering lives in inject.ts, persistence in store.ts.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { compatibleContentIds, contentId } from "./ids.ts";
|
|
13
|
-
import { rankMemoryEntries } from "./retrieval.ts";
|
|
14
|
-
import { scanContent } from "./scanner.ts";
|
|
15
|
-
|
|
16
|
-
export const MEMORY_KINDS = ["objective", "invariant", "preference", "convention", "gotcha", "rationale", "note"] as const;
|
|
17
|
-
export type MemoryKind = (typeof MEMORY_KINDS)[number];
|
|
18
|
-
export type MemoryTerm = "long" | "short";
|
|
19
|
-
|
|
20
|
-
/** Default life of a short-term memory before it is deleted from the store. */
|
|
21
|
-
export const DEFAULT_TTL_HOURS = 48;
|
|
22
|
-
export const DEFAULT_RECALL_MAX = 8;
|
|
23
|
-
export const MAX_RECALL_MAX = 50;
|
|
24
|
-
export const MAX_RECALL_QUERY_CHARS = 512;
|
|
25
|
-
export const MAX_MEMORY_TEXT_CHARS = 8_192;
|
|
26
|
-
export const MAX_MEMORY_TAGS = 64;
|
|
27
|
-
export const MAX_MEMORY_TAG_CHARS = 256;
|
|
28
|
-
export const MAX_MEMORY_SOURCE_CHARS = 1_024;
|
|
29
|
-
export const MAX_MEMORY_DERIVED_IDS = 64;
|
|
30
|
-
export const MAX_MEMORY_ID_CHARS = 128;
|
|
31
|
-
const MAX_MEMORY_PERSONA_CHARS = 128;
|
|
32
|
-
const SAFE_MEMORY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
33
|
-
|
|
34
|
-
/** IDs are echoed by tools and may arrive from migrated/out-of-band stores; keep them one safe token. */
|
|
35
|
-
export function isMemoryId(value: unknown): value is string {
|
|
36
|
-
return typeof value === "string" && value.length <= MAX_MEMORY_ID_CHARS && SAFE_MEMORY_ID.test(value);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Clamp a user-facing recall page to a small, finite range. */
|
|
40
|
-
export function clampRecallMax(max: number | undefined): number {
|
|
41
|
-
if (max === undefined || Number.isNaN(max)) return DEFAULT_RECALL_MAX;
|
|
42
|
-
if (max === Number.POSITIVE_INFINITY) return MAX_RECALL_MAX;
|
|
43
|
-
if (max === Number.NEGATIVE_INFINITY) return 1;
|
|
44
|
-
return Math.max(1, Math.min(MAX_RECALL_MAX, Math.floor(max)));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Flatten and fence text before putting a persisted entry in a tool result. */
|
|
48
|
-
export function compactMemoryText(text: string, cap = 240): string {
|
|
49
|
-
const safeCap = Number.isFinite(cap) && cap >= 2 ? Math.floor(cap) : 240;
|
|
50
|
-
const flat = text
|
|
51
|
-
.replace(/<\/?persona-mind\b[^>]*>/gi, "[persona-mind]")
|
|
52
|
-
.replace(/\s+/g, " ")
|
|
53
|
-
.trim();
|
|
54
|
-
return flat.length > safeCap ? `${flat.slice(0, safeCap - 1)}…` : flat;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export interface MemoryEntry {
|
|
58
|
-
/** Content-addressed (kind + text + tags): re-recording the same fact updates in place. */
|
|
59
|
-
id: string;
|
|
60
|
-
kind: MemoryKind;
|
|
61
|
-
text: string;
|
|
62
|
-
tags: string[];
|
|
63
|
-
recordedAt: string;
|
|
64
|
-
/** Bumped when the fact is re-recorded or promoted; reads stay write-free. */
|
|
65
|
-
lastSeenAt: string;
|
|
66
|
-
/** The id this entry retires (kept as lineage; the retired entry is removed from the active set). */
|
|
67
|
-
supersedes?: string;
|
|
68
|
-
/** Who recorded it (owning persona, or a child agent handle). Mainly meaningful for short-term. */
|
|
69
|
-
persona?: string;
|
|
70
|
-
/** Short-term only: recordedAt + ttl. Absent ⇒ long-term / durable. */
|
|
71
|
-
expiresAt?: string;
|
|
72
|
-
/** Optional human-citable origin ("session 3", "child scout"). NOT part of the content id. */
|
|
73
|
-
source?: string;
|
|
74
|
-
/** Optional ids of the entries this fact was distilled from (an intra-store citation graph). */
|
|
75
|
-
derivedFrom?: string[];
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** All persisted model-visible fields are untrusted, including tags and human-citable origins. */
|
|
79
|
-
export function isSafeMemoryContent(entry: MemoryEntry): boolean {
|
|
80
|
-
return [entry.text, ...entry.tags, entry.source ?? "", entry.persona ?? ""].every((text) => scanContent(text).ok);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export interface MemoryInput {
|
|
84
|
-
term: MemoryTerm;
|
|
85
|
-
kind: MemoryKind;
|
|
86
|
-
text: string;
|
|
87
|
-
tags?: string[];
|
|
88
|
-
/** Short-term only; defaults to {@link DEFAULT_TTL_HOURS}. */
|
|
89
|
-
ttlHours?: number;
|
|
90
|
-
supersedes?: string;
|
|
91
|
-
persona?: string;
|
|
92
|
-
source?: string;
|
|
93
|
-
derivedFrom?: string[];
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function normalizeText(text: string): string {
|
|
97
|
-
return text.trim().replace(/\s+/g, " ").toLowerCase();
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function normalizeTags(tags: readonly string[]): string[] {
|
|
101
|
-
return [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/** Semantic equality deliberately ignores historical ID encoding and presentation noise. */
|
|
105
|
-
export function memoryContentKey(entry: Pick<MemoryEntry, "kind" | "text" | "tags">): string {
|
|
106
|
-
return JSON.stringify([entry.kind, normalizeText(entry.text), normalizeTags(entry.tags)]);
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export function sameMemoryContent(a: MemoryEntry, b: MemoryEntry): boolean {
|
|
110
|
-
return memoryContentKey(a) === memoryContentKey(b);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** True when an id can address this entry under either the current or migrated encoding. */
|
|
114
|
-
export function memoryIdMatches(entry: MemoryEntry, id: string): boolean {
|
|
115
|
-
return entry.id === id || compatibleContentIds(entry.kind, entry.text, entry.tags).includes(id);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function iso(now: number): string {
|
|
119
|
-
return new Date(now).toISOString();
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function normTags(tags: readonly string[]): string[] {
|
|
123
|
-
return [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** Build a memory entry. Long term ⇒ durable; short term ⇒ carries an expiry. */
|
|
127
|
-
export function makeMemory(input: MemoryInput, now: number): MemoryEntry {
|
|
128
|
-
const text = input.text.trim();
|
|
129
|
-
const tags = normTags(input.tags ?? []);
|
|
130
|
-
const entry: MemoryEntry = {
|
|
131
|
-
id: contentId(input.kind, text, tags),
|
|
132
|
-
kind: input.kind,
|
|
133
|
-
text,
|
|
134
|
-
tags,
|
|
135
|
-
recordedAt: iso(now),
|
|
136
|
-
lastSeenAt: iso(now),
|
|
137
|
-
};
|
|
138
|
-
if (input.term === "short") {
|
|
139
|
-
const ttl = input.ttlHours ?? DEFAULT_TTL_HOURS;
|
|
140
|
-
entry.expiresAt = iso(now + ttl * 3_600_000);
|
|
141
|
-
}
|
|
142
|
-
if (input.supersedes) entry.supersedes = input.supersedes;
|
|
143
|
-
if (input.persona) entry.persona = input.persona;
|
|
144
|
-
if (input.source) entry.source = input.source;
|
|
145
|
-
if (input.derivedFrom && input.derivedFrom.length > 0) entry.derivedFrom = [...input.derivedFrom];
|
|
146
|
-
return entry;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
/** Graduate a short-term entry into durable long-term: drop expiry + persona tag, keep id/age. */
|
|
150
|
-
export function promoteToLong(entry: MemoryEntry, now: number): MemoryEntry {
|
|
151
|
-
const promoted: MemoryEntry = {
|
|
152
|
-
id: entry.id,
|
|
153
|
-
kind: entry.kind,
|
|
154
|
-
text: entry.text,
|
|
155
|
-
tags: entry.tags,
|
|
156
|
-
recordedAt: entry.recordedAt,
|
|
157
|
-
lastSeenAt: iso(now),
|
|
158
|
-
};
|
|
159
|
-
if (entry.supersedes) promoted.supersedes = entry.supersedes;
|
|
160
|
-
if (entry.source) promoted.source = entry.source;
|
|
161
|
-
if (entry.derivedFrom) promoted.derivedFrom = entry.derivedFrom;
|
|
162
|
-
return promoted;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** True once a short-term entry has passed its expiry. Long-term entries never expire. */
|
|
166
|
-
export function isExpired(entry: MemoryEntry, now: number): boolean {
|
|
167
|
-
return entry.expiresAt !== undefined && now >= Date.parse(entry.expiresAt);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** Drop expired short-term entries; keep everything else. Callers that persist must write this back. */
|
|
171
|
-
export function pruneExpired(entries: readonly MemoryEntry[], now: number): MemoryEntry[] {
|
|
172
|
-
return entries.filter((e) => !isExpired(e, now));
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/** A short-term entry that is still live but within `windowMs` of expiring — flag it "verify". */
|
|
176
|
-
export function nearExpiry(entry: MemoryEntry, now: number, windowMs: number): boolean {
|
|
177
|
-
if (entry.expiresAt === undefined || isExpired(entry, now)) return false;
|
|
178
|
-
return Date.parse(entry.expiresAt) - now <= windowMs;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
export interface SupersedeTargets {
|
|
182
|
-
/** The entries the id may retire — empty when it addresses nothing, or more than one fact. */
|
|
183
|
-
targets: MemoryEntry[];
|
|
184
|
-
/** The id names two or more semantically distinct facts, so it cannot pick between them. */
|
|
185
|
-
ambiguous: boolean;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Which entries a `supersedes` id is allowed to retire. Ids are matched across the v1/v2 encodings
|
|
190
|
-
* (see {@link memoryIdMatches}), so one historical handle can name several distinct facts — the v1
|
|
191
|
-
* comma-join erased the tag boundary. When it does, NOTHING is retired: this is the same refusal the
|
|
192
|
-
* delete path makes (`MindService.forget` → `ambiguous_id`), for the same reason — a shared handle is
|
|
193
|
-
* no evidence about which fact the caller meant, and guessing destroys a durable memory.
|
|
194
|
-
*/
|
|
195
|
-
export function supersedeTargets(entries: readonly MemoryEntry[], id: string): SupersedeTargets {
|
|
196
|
-
const targets = entries.filter((e) => memoryIdMatches(e, id));
|
|
197
|
-
const distinct = new Set(targets.map((e) => memoryContentKey(e)));
|
|
198
|
-
return distinct.size > 1 ? { targets: [], ambiguous: true } : { targets, ambiguous: false };
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* Insert `entry`, deduping by content id (an update-in-place that preserves the original
|
|
203
|
-
* `recordedAt` and bumps `lastSeenAt`) and retiring the entry named by `entry.supersedes` — unless
|
|
204
|
-
* that id is ambiguous, in which case it retires nothing (see {@link supersedeTargets}).
|
|
205
|
-
* A caller that detected cross-store ambiguity can disable retirement while preserving lineage.
|
|
206
|
-
*/
|
|
207
|
-
export function upsertMemory(entries: readonly MemoryEntry[], entry: MemoryEntry, retireSupersedes = true): MemoryEntry[] {
|
|
208
|
-
const key = memoryContentKey(entry);
|
|
209
|
-
const existing = entries.find((e) => memoryContentKey(e) === key);
|
|
210
|
-
const merged: MemoryEntry = existing
|
|
211
|
-
? { ...entry, id: existing.id, recordedAt: existing.recordedAt, lastSeenAt: entry.recordedAt }
|
|
212
|
-
: entry;
|
|
213
|
-
// A repeated observation renews the fact, not its origin. Keep omitted provenance without
|
|
214
|
-
// inheriting lifetime/owner fields, and do not replay its historical supersedes retirement.
|
|
215
|
-
if (existing) {
|
|
216
|
-
if (entry.source === undefined && existing.source !== undefined) merged.source = existing.source;
|
|
217
|
-
if (entry.derivedFrom === undefined && existing.derivedFrom !== undefined) merged.derivedFrom = [...existing.derivedFrom];
|
|
218
|
-
if (entry.supersedes === undefined && existing.supersedes !== undefined) merged.supersedes = existing.supersedes;
|
|
219
|
-
}
|
|
220
|
-
// Retire the previous copy under the SAME semantic key it was found by, never by its id: an id
|
|
221
|
-
// carried over from a migrated store can be shared with an unrelated fact, and dropping every
|
|
222
|
-
// entry holding it would erase that fact too.
|
|
223
|
-
const retired = new Set(retireSupersedes && entry.supersedes ? supersedeTargets(entries, entry.supersedes).targets : []);
|
|
224
|
-
return [...entries.filter((e) => memoryContentKey(e) !== key && !retired.has(e)), merged];
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
export interface RecallOptions {
|
|
228
|
-
max: number;
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* Explainable lexical/path recall, shared with injection. A query only returns positive matches;
|
|
233
|
-
* empty discovery remains recency-ordered. Ranking never changes stored age or expiry.
|
|
234
|
-
*/
|
|
235
|
-
export function recall(entries: readonly MemoryEntry[], query: string, _now: number, opts: RecallOptions): MemoryEntry[] {
|
|
236
|
-
const byRecency = (a: MemoryEntry, b: MemoryEntry): number => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt);
|
|
237
|
-
if (!query.trim()) {
|
|
238
|
-
return [...entries].sort(byRecency).slice(0, opts.max);
|
|
239
|
-
}
|
|
240
|
-
return rankMemoryEntries(entries, query).filter((match) => match.score > 0).slice(0, opts.max).map((match) => match.entry);
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* A COARSE, prompt-cache-stable age label: "today", "2d", "3w", "5mo", "1y".
|
|
245
|
-
*
|
|
246
|
-
* The injected `<persona-mind>` block is folded into the system prompt every turn. A minute/hour
|
|
247
|
-
* granular age ("29m" → "30m" a minute later) would mutate that block every minute and bust provider
|
|
248
|
-
* prompt-caching of the whole system prefix — for zero real signal, since a durable memory is not a
|
|
249
|
-
* log line and never needed sub-day precision. So the entire sub-day range collapses to ONE stable
|
|
250
|
-
* bucket ("today") and the rest steps at day granularity or coarser: the label now flips at most
|
|
251
|
-
* once per day, keeping the block byte-identical across a working session's turns.
|
|
252
|
-
*/
|
|
253
|
-
export function ageLabel(recordedAt: string, now: number): string {
|
|
254
|
-
const days = Math.floor(Math.max(0, now - Date.parse(recordedAt)) / 86_400_000);
|
|
255
|
-
if (!Number.isFinite(days)) return "?"; // corrupt/unparseable timestamp — never render "NaN…"
|
|
256
|
-
if (days < 1) return "today";
|
|
257
|
-
if (days < 14) return `${days}d`; // day granularity where recency is load-bearing
|
|
258
|
-
if (days < 60) return `${Math.floor(days / 7)}w`;
|
|
259
|
-
if (days < 365) return `${Math.floor(days / 30)}mo`;
|
|
260
|
-
return `${Math.floor(days / 365)}y`;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
function isKind(v: unknown): v is MemoryKind {
|
|
264
|
-
return typeof v === "string" && (MEMORY_KINDS as readonly string[]).includes(v);
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
function isStringArray(v: unknown): v is string[] {
|
|
268
|
-
return Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
function isBoundedStringArray(v: unknown, maxItems: number, maxChars: number): v is string[] {
|
|
272
|
-
return isStringArray(v) && v.length <= maxItems && v.every((value) => value.length <= maxChars);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/** A persisted timestamp must be a non-empty string understood by the platform date parser. */
|
|
276
|
-
export function isValidTimestamp(v: unknown): v is string {
|
|
277
|
-
return typeof v === "string" && v.length > 0 && Number.isFinite(Date.parse(v));
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
/** Runtime validation for one persisted entry (used as JsonStore.validateEntry). null ⇒ drop. */
|
|
281
|
-
export function validateMemory(raw: unknown): MemoryEntry | null {
|
|
282
|
-
if (!raw || typeof raw !== "object") return null;
|
|
283
|
-
const o = raw as Record<string, unknown>;
|
|
284
|
-
if (!isMemoryId(o.id) || !isKind(o.kind)) return null;
|
|
285
|
-
if (typeof o.text !== "string" || o.text.length === 0 || o.text.length > MAX_MEMORY_TEXT_CHARS) return null;
|
|
286
|
-
if (!isBoundedStringArray(o.tags, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS) || !isValidTimestamp(o.recordedAt) || !isValidTimestamp(o.lastSeenAt)) return null;
|
|
287
|
-
const entry: MemoryEntry = { id: o.id, kind: o.kind, text: o.text, tags: o.tags, recordedAt: o.recordedAt, lastSeenAt: o.lastSeenAt };
|
|
288
|
-
if (o.supersedes !== undefined) {
|
|
289
|
-
if (!isMemoryId(o.supersedes)) return null;
|
|
290
|
-
entry.supersedes = o.supersedes;
|
|
291
|
-
}
|
|
292
|
-
if (o.persona !== undefined) {
|
|
293
|
-
if (typeof o.persona !== "string" || o.persona.length === 0 || o.persona.length > MAX_MEMORY_PERSONA_CHARS) return null;
|
|
294
|
-
entry.persona = o.persona;
|
|
295
|
-
}
|
|
296
|
-
if (o.expiresAt !== undefined) {
|
|
297
|
-
if (!isValidTimestamp(o.expiresAt)) return null;
|
|
298
|
-
entry.expiresAt = o.expiresAt;
|
|
299
|
-
}
|
|
300
|
-
if (o.source !== undefined) {
|
|
301
|
-
if (typeof o.source !== "string" || o.source.length > MAX_MEMORY_SOURCE_CHARS) return null;
|
|
302
|
-
entry.source = o.source;
|
|
303
|
-
}
|
|
304
|
-
if (o.derivedFrom !== undefined) {
|
|
305
|
-
if (!isBoundedStringArray(o.derivedFrom, MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_ID_CHARS) || o.derivedFrom.some((id) => !isMemoryId(id))) return null;
|
|
306
|
-
entry.derivedFrom = o.derivedFrom;
|
|
307
|
-
}
|
|
308
|
-
return entry;
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
/** Validator for the durable tier: an LTM record must not carry short-term expiry metadata. */
|
|
312
|
-
export function validateLongMemory(raw: unknown): MemoryEntry | null {
|
|
313
|
-
const entry = validateMemory(raw);
|
|
314
|
-
return entry && entry.expiresAt === undefined ? entry : null;
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
/** Validator for the working tier: an STM record must carry a valid expiry timestamp. */
|
|
318
|
-
export function validateShortMemory(raw: unknown): MemoryEntry | null {
|
|
319
|
-
const entry = validateMemory(raw);
|
|
320
|
-
return entry && entry.expiresAt !== undefined ? entry : null;
|
|
321
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* The memory faculty — pure domain logic, no I/O.
|
|
3
|
+
*
|
|
4
|
+
* Two temporal tiers share this one entry shape:
|
|
5
|
+
* - LONG-TERM (identity): durable, persona-scoped, never expires. Who a persona is for this user.
|
|
6
|
+
* - SHORT-TERM (working context): project-scoped, carries an `expiresAt`, decays on its own.
|
|
7
|
+
* The tier is not stored on the entry — it is implied by which file the entry lives in (LTM vs STM)
|
|
8
|
+
* and by whether it has an `expiresAt`. This module builds, validates, dedups/supersedes, decays,
|
|
9
|
+
* and ranks entries; rendering lives in inject.ts, persistence in store.ts.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { compatibleContentIds, contentId } from "./ids.ts";
|
|
13
|
+
import { rankMemoryEntries } from "./retrieval.ts";
|
|
14
|
+
import { scanContent } from "./scanner.ts";
|
|
15
|
+
|
|
16
|
+
export const MEMORY_KINDS = ["objective", "invariant", "preference", "convention", "gotcha", "rationale", "note"] as const;
|
|
17
|
+
export type MemoryKind = (typeof MEMORY_KINDS)[number];
|
|
18
|
+
export type MemoryTerm = "long" | "short";
|
|
19
|
+
|
|
20
|
+
/** Default life of a short-term memory before it is deleted from the store. */
|
|
21
|
+
export const DEFAULT_TTL_HOURS = 48;
|
|
22
|
+
export const DEFAULT_RECALL_MAX = 8;
|
|
23
|
+
export const MAX_RECALL_MAX = 50;
|
|
24
|
+
export const MAX_RECALL_QUERY_CHARS = 512;
|
|
25
|
+
export const MAX_MEMORY_TEXT_CHARS = 8_192;
|
|
26
|
+
export const MAX_MEMORY_TAGS = 64;
|
|
27
|
+
export const MAX_MEMORY_TAG_CHARS = 256;
|
|
28
|
+
export const MAX_MEMORY_SOURCE_CHARS = 1_024;
|
|
29
|
+
export const MAX_MEMORY_DERIVED_IDS = 64;
|
|
30
|
+
export const MAX_MEMORY_ID_CHARS = 128;
|
|
31
|
+
const MAX_MEMORY_PERSONA_CHARS = 128;
|
|
32
|
+
const SAFE_MEMORY_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
|
|
33
|
+
|
|
34
|
+
/** IDs are echoed by tools and may arrive from migrated/out-of-band stores; keep them one safe token. */
|
|
35
|
+
export function isMemoryId(value: unknown): value is string {
|
|
36
|
+
return typeof value === "string" && value.length <= MAX_MEMORY_ID_CHARS && SAFE_MEMORY_ID.test(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Clamp a user-facing recall page to a small, finite range. */
|
|
40
|
+
export function clampRecallMax(max: number | undefined): number {
|
|
41
|
+
if (max === undefined || Number.isNaN(max)) return DEFAULT_RECALL_MAX;
|
|
42
|
+
if (max === Number.POSITIVE_INFINITY) return MAX_RECALL_MAX;
|
|
43
|
+
if (max === Number.NEGATIVE_INFINITY) return 1;
|
|
44
|
+
return Math.max(1, Math.min(MAX_RECALL_MAX, Math.floor(max)));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Flatten and fence text before putting a persisted entry in a tool result. */
|
|
48
|
+
export function compactMemoryText(text: string, cap = 240): string {
|
|
49
|
+
const safeCap = Number.isFinite(cap) && cap >= 2 ? Math.floor(cap) : 240;
|
|
50
|
+
const flat = text
|
|
51
|
+
.replace(/<\/?persona-mind\b[^>]*>/gi, "[persona-mind]")
|
|
52
|
+
.replace(/\s+/g, " ")
|
|
53
|
+
.trim();
|
|
54
|
+
return flat.length > safeCap ? `${flat.slice(0, safeCap - 1)}…` : flat;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface MemoryEntry {
|
|
58
|
+
/** Content-addressed (kind + text + tags): re-recording the same fact updates in place. */
|
|
59
|
+
id: string;
|
|
60
|
+
kind: MemoryKind;
|
|
61
|
+
text: string;
|
|
62
|
+
tags: string[];
|
|
63
|
+
recordedAt: string;
|
|
64
|
+
/** Bumped when the fact is re-recorded or promoted; reads stay write-free. */
|
|
65
|
+
lastSeenAt: string;
|
|
66
|
+
/** The id this entry retires (kept as lineage; the retired entry is removed from the active set). */
|
|
67
|
+
supersedes?: string;
|
|
68
|
+
/** Who recorded it (owning persona, or a child agent handle). Mainly meaningful for short-term. */
|
|
69
|
+
persona?: string;
|
|
70
|
+
/** Short-term only: recordedAt + ttl. Absent ⇒ long-term / durable. */
|
|
71
|
+
expiresAt?: string;
|
|
72
|
+
/** Optional human-citable origin ("session 3", "child scout"). NOT part of the content id. */
|
|
73
|
+
source?: string;
|
|
74
|
+
/** Optional ids of the entries this fact was distilled from (an intra-store citation graph). */
|
|
75
|
+
derivedFrom?: string[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** All persisted model-visible fields are untrusted, including tags and human-citable origins. */
|
|
79
|
+
export function isSafeMemoryContent(entry: MemoryEntry): boolean {
|
|
80
|
+
return [entry.text, ...entry.tags, entry.source ?? "", entry.persona ?? ""].every((text) => scanContent(text).ok);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface MemoryInput {
|
|
84
|
+
term: MemoryTerm;
|
|
85
|
+
kind: MemoryKind;
|
|
86
|
+
text: string;
|
|
87
|
+
tags?: string[];
|
|
88
|
+
/** Short-term only; defaults to {@link DEFAULT_TTL_HOURS}. */
|
|
89
|
+
ttlHours?: number;
|
|
90
|
+
supersedes?: string;
|
|
91
|
+
persona?: string;
|
|
92
|
+
source?: string;
|
|
93
|
+
derivedFrom?: string[];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function normalizeText(text: string): string {
|
|
97
|
+
return text.trim().replace(/\s+/g, " ").toLowerCase();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function normalizeTags(tags: readonly string[]): string[] {
|
|
101
|
+
return [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Semantic equality deliberately ignores historical ID encoding and presentation noise. */
|
|
105
|
+
export function memoryContentKey(entry: Pick<MemoryEntry, "kind" | "text" | "tags">): string {
|
|
106
|
+
return JSON.stringify([entry.kind, normalizeText(entry.text), normalizeTags(entry.tags)]);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function sameMemoryContent(a: MemoryEntry, b: MemoryEntry): boolean {
|
|
110
|
+
return memoryContentKey(a) === memoryContentKey(b);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** True when an id can address this entry under either the current or migrated encoding. */
|
|
114
|
+
export function memoryIdMatches(entry: MemoryEntry, id: string): boolean {
|
|
115
|
+
return entry.id === id || compatibleContentIds(entry.kind, entry.text, entry.tags).includes(id);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function iso(now: number): string {
|
|
119
|
+
return new Date(now).toISOString();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function normTags(tags: readonly string[]): string[] {
|
|
123
|
+
return [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Build a memory entry. Long term ⇒ durable; short term ⇒ carries an expiry. */
|
|
127
|
+
export function makeMemory(input: MemoryInput, now: number): MemoryEntry {
|
|
128
|
+
const text = input.text.trim();
|
|
129
|
+
const tags = normTags(input.tags ?? []);
|
|
130
|
+
const entry: MemoryEntry = {
|
|
131
|
+
id: contentId(input.kind, text, tags),
|
|
132
|
+
kind: input.kind,
|
|
133
|
+
text,
|
|
134
|
+
tags,
|
|
135
|
+
recordedAt: iso(now),
|
|
136
|
+
lastSeenAt: iso(now),
|
|
137
|
+
};
|
|
138
|
+
if (input.term === "short") {
|
|
139
|
+
const ttl = input.ttlHours ?? DEFAULT_TTL_HOURS;
|
|
140
|
+
entry.expiresAt = iso(now + ttl * 3_600_000);
|
|
141
|
+
}
|
|
142
|
+
if (input.supersedes) entry.supersedes = input.supersedes;
|
|
143
|
+
if (input.persona) entry.persona = input.persona;
|
|
144
|
+
if (input.source) entry.source = input.source;
|
|
145
|
+
if (input.derivedFrom && input.derivedFrom.length > 0) entry.derivedFrom = [...input.derivedFrom];
|
|
146
|
+
return entry;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Graduate a short-term entry into durable long-term: drop expiry + persona tag, keep id/age. */
|
|
150
|
+
export function promoteToLong(entry: MemoryEntry, now: number): MemoryEntry {
|
|
151
|
+
const promoted: MemoryEntry = {
|
|
152
|
+
id: entry.id,
|
|
153
|
+
kind: entry.kind,
|
|
154
|
+
text: entry.text,
|
|
155
|
+
tags: entry.tags,
|
|
156
|
+
recordedAt: entry.recordedAt,
|
|
157
|
+
lastSeenAt: iso(now),
|
|
158
|
+
};
|
|
159
|
+
if (entry.supersedes) promoted.supersedes = entry.supersedes;
|
|
160
|
+
if (entry.source) promoted.source = entry.source;
|
|
161
|
+
if (entry.derivedFrom) promoted.derivedFrom = entry.derivedFrom;
|
|
162
|
+
return promoted;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** True once a short-term entry has passed its expiry. Long-term entries never expire. */
|
|
166
|
+
export function isExpired(entry: MemoryEntry, now: number): boolean {
|
|
167
|
+
return entry.expiresAt !== undefined && now >= Date.parse(entry.expiresAt);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Drop expired short-term entries; keep everything else. Callers that persist must write this back. */
|
|
171
|
+
export function pruneExpired(entries: readonly MemoryEntry[], now: number): MemoryEntry[] {
|
|
172
|
+
return entries.filter((e) => !isExpired(e, now));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A short-term entry that is still live but within `windowMs` of expiring — flag it "verify". */
|
|
176
|
+
export function nearExpiry(entry: MemoryEntry, now: number, windowMs: number): boolean {
|
|
177
|
+
if (entry.expiresAt === undefined || isExpired(entry, now)) return false;
|
|
178
|
+
return Date.parse(entry.expiresAt) - now <= windowMs;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export interface SupersedeTargets {
|
|
182
|
+
/** The entries the id may retire — empty when it addresses nothing, or more than one fact. */
|
|
183
|
+
targets: MemoryEntry[];
|
|
184
|
+
/** The id names two or more semantically distinct facts, so it cannot pick between them. */
|
|
185
|
+
ambiguous: boolean;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Which entries a `supersedes` id is allowed to retire. Ids are matched across the v1/v2 encodings
|
|
190
|
+
* (see {@link memoryIdMatches}), so one historical handle can name several distinct facts — the v1
|
|
191
|
+
* comma-join erased the tag boundary. When it does, NOTHING is retired: this is the same refusal the
|
|
192
|
+
* delete path makes (`MindService.forget` → `ambiguous_id`), for the same reason — a shared handle is
|
|
193
|
+
* no evidence about which fact the caller meant, and guessing destroys a durable memory.
|
|
194
|
+
*/
|
|
195
|
+
export function supersedeTargets(entries: readonly MemoryEntry[], id: string): SupersedeTargets {
|
|
196
|
+
const targets = entries.filter((e) => memoryIdMatches(e, id));
|
|
197
|
+
const distinct = new Set(targets.map((e) => memoryContentKey(e)));
|
|
198
|
+
return distinct.size > 1 ? { targets: [], ambiguous: true } : { targets, ambiguous: false };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Insert `entry`, deduping by content id (an update-in-place that preserves the original
|
|
203
|
+
* `recordedAt` and bumps `lastSeenAt`) and retiring the entry named by `entry.supersedes` — unless
|
|
204
|
+
* that id is ambiguous, in which case it retires nothing (see {@link supersedeTargets}).
|
|
205
|
+
* A caller that detected cross-store ambiguity can disable retirement while preserving lineage.
|
|
206
|
+
*/
|
|
207
|
+
export function upsertMemory(entries: readonly MemoryEntry[], entry: MemoryEntry, retireSupersedes = true): MemoryEntry[] {
|
|
208
|
+
const key = memoryContentKey(entry);
|
|
209
|
+
const existing = entries.find((e) => memoryContentKey(e) === key);
|
|
210
|
+
const merged: MemoryEntry = existing
|
|
211
|
+
? { ...entry, id: existing.id, recordedAt: existing.recordedAt, lastSeenAt: entry.recordedAt }
|
|
212
|
+
: entry;
|
|
213
|
+
// A repeated observation renews the fact, not its origin. Keep omitted provenance without
|
|
214
|
+
// inheriting lifetime/owner fields, and do not replay its historical supersedes retirement.
|
|
215
|
+
if (existing) {
|
|
216
|
+
if (entry.source === undefined && existing.source !== undefined) merged.source = existing.source;
|
|
217
|
+
if (entry.derivedFrom === undefined && existing.derivedFrom !== undefined) merged.derivedFrom = [...existing.derivedFrom];
|
|
218
|
+
if (entry.supersedes === undefined && existing.supersedes !== undefined) merged.supersedes = existing.supersedes;
|
|
219
|
+
}
|
|
220
|
+
// Retire the previous copy under the SAME semantic key it was found by, never by its id: an id
|
|
221
|
+
// carried over from a migrated store can be shared with an unrelated fact, and dropping every
|
|
222
|
+
// entry holding it would erase that fact too.
|
|
223
|
+
const retired = new Set(retireSupersedes && entry.supersedes ? supersedeTargets(entries, entry.supersedes).targets : []);
|
|
224
|
+
return [...entries.filter((e) => memoryContentKey(e) !== key && !retired.has(e)), merged];
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export interface RecallOptions {
|
|
228
|
+
max: number;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Explainable lexical/path recall, shared with injection. A query only returns positive matches;
|
|
233
|
+
* empty discovery remains recency-ordered. Ranking never changes stored age or expiry.
|
|
234
|
+
*/
|
|
235
|
+
export function recall(entries: readonly MemoryEntry[], query: string, _now: number, opts: RecallOptions): MemoryEntry[] {
|
|
236
|
+
const byRecency = (a: MemoryEntry, b: MemoryEntry): number => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt);
|
|
237
|
+
if (!query.trim()) {
|
|
238
|
+
return [...entries].sort(byRecency).slice(0, opts.max);
|
|
239
|
+
}
|
|
240
|
+
return rankMemoryEntries(entries, query).filter((match) => match.score > 0).slice(0, opts.max).map((match) => match.entry);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* A COARSE, prompt-cache-stable age label: "today", "2d", "3w", "5mo", "1y".
|
|
245
|
+
*
|
|
246
|
+
* The injected `<persona-mind>` block is folded into the system prompt every turn. A minute/hour
|
|
247
|
+
* granular age ("29m" → "30m" a minute later) would mutate that block every minute and bust provider
|
|
248
|
+
* prompt-caching of the whole system prefix — for zero real signal, since a durable memory is not a
|
|
249
|
+
* log line and never needed sub-day precision. So the entire sub-day range collapses to ONE stable
|
|
250
|
+
* bucket ("today") and the rest steps at day granularity or coarser: the label now flips at most
|
|
251
|
+
* once per day, keeping the block byte-identical across a working session's turns.
|
|
252
|
+
*/
|
|
253
|
+
export function ageLabel(recordedAt: string, now: number): string {
|
|
254
|
+
const days = Math.floor(Math.max(0, now - Date.parse(recordedAt)) / 86_400_000);
|
|
255
|
+
if (!Number.isFinite(days)) return "?"; // corrupt/unparseable timestamp — never render "NaN…"
|
|
256
|
+
if (days < 1) return "today";
|
|
257
|
+
if (days < 14) return `${days}d`; // day granularity where recency is load-bearing
|
|
258
|
+
if (days < 60) return `${Math.floor(days / 7)}w`;
|
|
259
|
+
if (days < 365) return `${Math.floor(days / 30)}mo`;
|
|
260
|
+
return `${Math.floor(days / 365)}y`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function isKind(v: unknown): v is MemoryKind {
|
|
264
|
+
return typeof v === "string" && (MEMORY_KINDS as readonly string[]).includes(v);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function isStringArray(v: unknown): v is string[] {
|
|
268
|
+
return Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function isBoundedStringArray(v: unknown, maxItems: number, maxChars: number): v is string[] {
|
|
272
|
+
return isStringArray(v) && v.length <= maxItems && v.every((value) => value.length <= maxChars);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** A persisted timestamp must be a non-empty string understood by the platform date parser. */
|
|
276
|
+
export function isValidTimestamp(v: unknown): v is string {
|
|
277
|
+
return typeof v === "string" && v.length > 0 && Number.isFinite(Date.parse(v));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Runtime validation for one persisted entry (used as JsonStore.validateEntry). null ⇒ drop. */
|
|
281
|
+
export function validateMemory(raw: unknown): MemoryEntry | null {
|
|
282
|
+
if (!raw || typeof raw !== "object") return null;
|
|
283
|
+
const o = raw as Record<string, unknown>;
|
|
284
|
+
if (!isMemoryId(o.id) || !isKind(o.kind)) return null;
|
|
285
|
+
if (typeof o.text !== "string" || o.text.length === 0 || o.text.length > MAX_MEMORY_TEXT_CHARS) return null;
|
|
286
|
+
if (!isBoundedStringArray(o.tags, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS) || !isValidTimestamp(o.recordedAt) || !isValidTimestamp(o.lastSeenAt)) return null;
|
|
287
|
+
const entry: MemoryEntry = { id: o.id, kind: o.kind, text: o.text, tags: o.tags, recordedAt: o.recordedAt, lastSeenAt: o.lastSeenAt };
|
|
288
|
+
if (o.supersedes !== undefined) {
|
|
289
|
+
if (!isMemoryId(o.supersedes)) return null;
|
|
290
|
+
entry.supersedes = o.supersedes;
|
|
291
|
+
}
|
|
292
|
+
if (o.persona !== undefined) {
|
|
293
|
+
if (typeof o.persona !== "string" || o.persona.length === 0 || o.persona.length > MAX_MEMORY_PERSONA_CHARS) return null;
|
|
294
|
+
entry.persona = o.persona;
|
|
295
|
+
}
|
|
296
|
+
if (o.expiresAt !== undefined) {
|
|
297
|
+
if (!isValidTimestamp(o.expiresAt)) return null;
|
|
298
|
+
entry.expiresAt = o.expiresAt;
|
|
299
|
+
}
|
|
300
|
+
if (o.source !== undefined) {
|
|
301
|
+
if (typeof o.source !== "string" || o.source.length > MAX_MEMORY_SOURCE_CHARS) return null;
|
|
302
|
+
entry.source = o.source;
|
|
303
|
+
}
|
|
304
|
+
if (o.derivedFrom !== undefined) {
|
|
305
|
+
if (!isBoundedStringArray(o.derivedFrom, MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_ID_CHARS) || o.derivedFrom.some((id) => !isMemoryId(id))) return null;
|
|
306
|
+
entry.derivedFrom = o.derivedFrom;
|
|
307
|
+
}
|
|
308
|
+
return entry;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/** Validator for the durable tier: an LTM record must not carry short-term expiry metadata. */
|
|
312
|
+
export function validateLongMemory(raw: unknown): MemoryEntry | null {
|
|
313
|
+
const entry = validateMemory(raw);
|
|
314
|
+
return entry && entry.expiresAt === undefined ? entry : null;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Validator for the working tier: an STM record must carry a valid expiry timestamp. */
|
|
318
|
+
export function validateShortMemory(raw: unknown): MemoryEntry | null {
|
|
319
|
+
const entry = validateMemory(raw);
|
|
320
|
+
return entry && entry.expiresAt !== undefined ? entry : null;
|
|
321
|
+
}
|