@aeondave/pi-persona-mind 0.0.0-stage → 0.8.4
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 +78 -0
- package/CHANGELOG.md +78 -0
- package/LICENSE +24 -0
- package/README.md +244 -2
- package/assets/banner.png +0 -0
- package/docs/DESIGN.md +282 -0
- package/docs/MEMORY-RESEARCH.md +112 -0
- package/package.json +93 -4
- package/src/core/auto-optimize.ts +239 -0
- package/src/core/backlog.ts +228 -0
- package/src/core/blocked.ts +38 -0
- package/src/core/capture.ts +146 -0
- package/src/core/context-budget.ts +74 -0
- package/src/core/host-compat.ts +13 -0
- package/src/core/ids.ts +59 -0
- package/src/core/inject.ts +247 -0
- package/src/core/memory-read.ts +34 -0
- package/src/core/memory.ts +308 -0
- package/src/core/migrate.ts +713 -0
- package/src/core/mind-settings.ts +54 -0
- package/src/core/optimize-history.ts +101 -0
- package/src/core/optimize-service.ts +182 -0
- package/src/core/optimize.ts +133 -0
- package/src/core/retrieval.ts +108 -0
- package/src/core/scanner.ts +146 -0
- package/src/core/scope.ts +205 -0
- package/src/core/service.ts +644 -0
- package/src/core/session-memory.ts +71 -0
- package/src/core/store.ts +948 -0
- package/src/extension/activity.ts +79 -0
- package/src/extension/auto-optimize-session.ts +118 -0
- package/src/extension/auto-optimize.ts +265 -0
- package/src/extension/mind-command.ts +335 -0
- package/src/extension/mind-worker.ts +32 -0
- package/src/extension/persona-dependency.ts +76 -0
- package/src/index.ts +1231 -0
- package/src/session-memory.ts +118 -0
- package/src/tools/backlog.ts +126 -0
- package/src/tools/memory-optimize.ts +133 -0
- package/src/tools/memory.ts +400 -0
- package/src/ui/mind-result-card.ts +15 -0
- package/src/ui/presentation.ts +97 -0
- package/src/ui/session-note-card.ts +50 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Mind's own session preferences. Active persona ownership never comes from this file. */
|
|
2
|
+
import { closeSync, fstatSync, openSync, readSync, statSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { TextDecoder } from "node:util";
|
|
5
|
+
import { captureMode } from "./capture.ts";
|
|
6
|
+
|
|
7
|
+
export interface MindSettings { mindCapture: "auto" | "prompt" | "off"; mindNudge: boolean }
|
|
8
|
+
const snapshots = new Map<string, MindSettings>();
|
|
9
|
+
const MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
function savedPreferences(path: string): Partial<MindSettings> {
|
|
12
|
+
let fd: number | undefined;
|
|
13
|
+
try {
|
|
14
|
+
const listed = statSync(path);
|
|
15
|
+
if (!listed.isFile() || !Number.isSafeInteger(listed.size) || listed.size > MAX_SETTINGS_BYTES) return {};
|
|
16
|
+
fd = openSync(path, "r");
|
|
17
|
+
const opened = fstatSync(fd);
|
|
18
|
+
if (!opened.isFile() || opened.size !== listed.size || opened.size > MAX_SETTINGS_BYTES) return {};
|
|
19
|
+
const bytes = Buffer.allocUnsafe(opened.size);
|
|
20
|
+
let offset = 0;
|
|
21
|
+
while (offset < bytes.length) {
|
|
22
|
+
const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
|
|
23
|
+
if (count === 0) return {};
|
|
24
|
+
offset += count;
|
|
25
|
+
}
|
|
26
|
+
if (fstatSync(fd).size !== opened.size) return {};
|
|
27
|
+
const parsed: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, ""));
|
|
28
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
29
|
+
const row = parsed as Record<string, unknown>;
|
|
30
|
+
if (row.version !== 1 || !row.preferences || typeof row.preferences !== "object" || Array.isArray(row.preferences)) return {};
|
|
31
|
+
const prefs = row.preferences as Record<string, unknown>;
|
|
32
|
+
if (prefs.mindCapture !== undefined && prefs.mindCapture !== "auto" && prefs.mindCapture !== "prompt" && prefs.mindCapture !== "off") return {};
|
|
33
|
+
if (prefs.mindNudge !== undefined && typeof prefs.mindNudge !== "boolean") return {};
|
|
34
|
+
return { ...(prefs.mindCapture === undefined ? {} : { mindCapture: prefs.mindCapture as MindSettings["mindCapture"] }), ...(prefs.mindNudge === undefined ? {} : { mindNudge: prefs.mindNudge as boolean }) };
|
|
35
|
+
} catch { return {}; }
|
|
36
|
+
finally { if (fd !== undefined) closeSync(fd); }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function resolveMindSettings(agentDir: string, env: NodeJS.ProcessEnv, sessionId: string): MindSettings {
|
|
40
|
+
const key = `${sessionId}\0${agentDir}`;
|
|
41
|
+
const cached = snapshots.get(key);
|
|
42
|
+
if (cached) return { ...cached };
|
|
43
|
+
const saved = savedPreferences(join(agentDir, "persona", "settings.json"));
|
|
44
|
+
const settings: MindSettings = {
|
|
45
|
+
mindCapture: env.PI_PERSONA_MIND_CAPTURE !== undefined ? captureMode(env) : saved.mindCapture ?? "auto",
|
|
46
|
+
mindNudge: env.PI_PERSONA_MIND_NUDGE !== undefined ? env.PI_PERSONA_MIND_NUDGE !== "off" : saved.mindNudge ?? true,
|
|
47
|
+
};
|
|
48
|
+
snapshots.set(key, settings);
|
|
49
|
+
return { ...settings };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function resetMindSettings(sessionId: string): void {
|
|
53
|
+
for (const key of snapshots.keys()) if (key.startsWith(`${sessionId}\0`)) snapshots.delete(key);
|
|
54
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Bounded write-ahead before images. Missing/corrupt history is never repaired to empty. */
|
|
2
|
+
import { isExpired, memoryContentKey, validateMemory, type MemoryEntry } from "./memory.ts";
|
|
3
|
+
import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS, MAX_OPTIMIZE_SOURCES, samePersistedMemory, safeOptimizeMemory, type OptimizeChange, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
|
|
4
|
+
import { JsonStore, withFileLock } from "./store.ts";
|
|
5
|
+
|
|
6
|
+
export const MAX_OPTIMIZE_HISTORY = 32;
|
|
7
|
+
export const MAX_OPTIMIZE_HISTORY_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
export interface OptimizeReceipt {
|
|
9
|
+
receiptId: string;
|
|
10
|
+
planId: string;
|
|
11
|
+
target: OptimizeTarget;
|
|
12
|
+
persona: string;
|
|
13
|
+
createdAt: string;
|
|
14
|
+
/** Prepared may mean interrupted before OR after memory commit; exact facts decide undo. */
|
|
15
|
+
state: "prepared" | "applied" | "undone" | "rejected";
|
|
16
|
+
storePath: string;
|
|
17
|
+
changes: OptimizeChange[];
|
|
18
|
+
}
|
|
19
|
+
export interface OptimizeHistory {
|
|
20
|
+
ok: true; target: OptimizeTarget; receipts: OptimizeReceipt[]; retained: number; omitted: number;
|
|
21
|
+
limit: number; maxBytes: number; withheldUnsafe: number;
|
|
22
|
+
}
|
|
23
|
+
export interface OptimizeUndone { ok: true; receiptId: string; target: OptimizeTarget; restored: number; warning?: string }
|
|
24
|
+
|
|
25
|
+
function validateReceipt(raw: unknown): OptimizeReceipt | null {
|
|
26
|
+
if (!raw || typeof raw !== "object") return null;
|
|
27
|
+
const value = raw as Partial<OptimizeReceipt>;
|
|
28
|
+
if (![value.receiptId, value.planId].every((id) => typeof id === "string" && /^[\da-f-]{36}$/i.test(id))) return null;
|
|
29
|
+
if (!isOptimizeTarget(value.target) || typeof value.persona !== "string" || !value.persona || value.persona.length > 128) return null;
|
|
30
|
+
if (typeof value.createdAt !== "string" || !Number.isFinite(Date.parse(value.createdAt))) return null;
|
|
31
|
+
if (!["prepared", "applied", "undone", "rejected"].includes(value.state ?? "")) return null;
|
|
32
|
+
if (typeof value.storePath !== "string" || value.storePath.length > 32_768 || !value.storePath) return null;
|
|
33
|
+
if (!Array.isArray(value.changes) || !value.changes.length || value.changes.length > MAX_OPTIMIZE_OPERATIONS) return null;
|
|
34
|
+
const changes: OptimizeChange[] = [];
|
|
35
|
+
const sourceIds = new Set<string>(); const replacementIds = new Set<string>();
|
|
36
|
+
for (const change of value.changes) {
|
|
37
|
+
if (!change || !Array.isArray(change.before) || !change.before.length || change.before.length > MAX_OPTIMIZE_SOURCES) return null;
|
|
38
|
+
const before: MemoryEntry[] = [];
|
|
39
|
+
for (const source of change.before) {
|
|
40
|
+
const entry = validateMemory(source);
|
|
41
|
+
if (!entry || sourceIds.has(entry.id)) return null;
|
|
42
|
+
sourceIds.add(entry.id); before.push(entry);
|
|
43
|
+
}
|
|
44
|
+
const after = validateMemory(change.after);
|
|
45
|
+
if (!after || replacementIds.has(after.id)) return null;
|
|
46
|
+
replacementIds.add(after.id); changes.push({ before, after });
|
|
47
|
+
}
|
|
48
|
+
return { receiptId: value.receiptId!, planId: value.planId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
|
|
49
|
+
state: value.state!, storePath: value.storePath, changes };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Strict CAS avoids JsonStore.update's recovery semantics, which are unsuitable for recovery logs. */
|
|
53
|
+
export class OptimizeHistoryStore {
|
|
54
|
+
private readonly store: JsonStore<OptimizeReceipt>;
|
|
55
|
+
readonly path: string;
|
|
56
|
+
constructor(path: string, now: () => number) {
|
|
57
|
+
this.path = path;
|
|
58
|
+
this.store = new JsonStore(path, { version: 1, validateEntry: validateReceipt, maxBytes: MAX_OPTIMIZE_HISTORY_BYTES, maxEntries: MAX_OPTIMIZE_HISTORY, now });
|
|
59
|
+
}
|
|
60
|
+
async exclusive<T>(run: () => Promise<T>): Promise<T> { return withFileLock(`${this.path}.transaction.lock`, run); }
|
|
61
|
+
async read(): Promise<OptimizeReceipt[]> { return (await this.store.inspectStrict()).store.entries; }
|
|
62
|
+
async prepare(receipt: OptimizeReceipt): Promise<void> {
|
|
63
|
+
const snapshot = await this.store.inspectStrict();
|
|
64
|
+
const entries = [...snapshot.store.entries, receipt];
|
|
65
|
+
// Only settled history can be evicted. An unresolved crash intent may own the only before image.
|
|
66
|
+
const bytes = () => Buffer.byteLength(`${JSON.stringify({ ...snapshot.store, sequence: snapshot.store.sequence + 1, entries }, null, 2)}\n`, "utf8");
|
|
67
|
+
while (entries.length > MAX_OPTIMIZE_HISTORY || bytes() > MAX_OPTIMIZE_HISTORY_BYTES) {
|
|
68
|
+
const index = entries.findIndex((entry) => entry.receiptId !== receipt.receiptId && entry.state !== "prepared");
|
|
69
|
+
if (index < 0) throw new Error("optimizer history capacity exhausted by recovery receipts; replacement refused");
|
|
70
|
+
entries.splice(index, 1);
|
|
71
|
+
}
|
|
72
|
+
await this.store.compareAndUpdate(snapshot.fingerprint, () => entries);
|
|
73
|
+
}
|
|
74
|
+
async settle(receiptId: string, state: OptimizeReceipt["state"]): Promise<void> {
|
|
75
|
+
const snapshot = await this.store.inspectStrict();
|
|
76
|
+
if (!snapshot.store.entries.some((receipt) => receipt.receiptId === receiptId)) throw new Error("optimizer recovery receipt disappeared; history requires repair");
|
|
77
|
+
await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => entries.map((receipt) => receipt.receiptId === receiptId ? { ...receipt, state } : receipt));
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Revert only exact affected rows, never a whole historical snapshot. */
|
|
82
|
+
export function restoreReceipt(entries: readonly MemoryEntry[], receipt: OptimizeReceipt, persona: string, now: number): { ok: true; entries: MemoryEntry[]; restored: number } | OptimizeFailure {
|
|
83
|
+
if (receipt.persona !== persona) return { ok: false, reason: "receipt belongs to a different persona owner" };
|
|
84
|
+
if (receipt.state === "undone" || receipt.state === "rejected") return { ok: false, reason: "receipt was already undone or its replacement was rejected" };
|
|
85
|
+
const before = receipt.changes.flatMap((change) => change.before);
|
|
86
|
+
const after = receipt.changes.map((change) => change.after);
|
|
87
|
+
if ([...before, ...after].some((entry) => !safeOptimizeMemory(entry))) return { ok: false, reason: "receipt contains unsafe memory content" };
|
|
88
|
+
if ((receipt.target === "project" || receipt.target === "project-long") && [...before, ...after].some((entry) => entry.persona !== persona)) return { ok: false, reason: "receipt contains foreign or unowned project facts" };
|
|
89
|
+
if ([...before, ...after].some((entry) => isExpired(entry, now))) return { ok: false, reason: "receipt contains expired sources; undo cannot revive expired memory" };
|
|
90
|
+
const selected = new Set<MemoryEntry>();
|
|
91
|
+
for (const replacement of after) {
|
|
92
|
+
const matches = entries.filter((entry) => entry.id === replacement.id);
|
|
93
|
+
if (matches.length !== 1 || !samePersistedMemory(matches[0]!, replacement)) return { ok: false, reason: "affected replacement changed or is missing; undo refused" };
|
|
94
|
+
selected.add(matches[0]!);
|
|
95
|
+
}
|
|
96
|
+
const untouched = entries.filter((entry) => !selected.has(entry));
|
|
97
|
+
for (const source of before) {
|
|
98
|
+
if (untouched.some((entry) => entry.id === source.id || memoryContentKey(entry) === memoryContentKey(source))) return { ok: false, reason: "restored source collides with a current fact; undo refused" };
|
|
99
|
+
}
|
|
100
|
+
return { ok: true, entries: [...untouched, ...structuredClone(before)], restored: before.length };
|
|
101
|
+
}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/** Session-local staged plans over strict one-file memory snapshots. No model calls or hidden jobs. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { isExpired, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
|
|
4
|
+
import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeUndone } from "./optimize-history.ts";
|
|
5
|
+
import {
|
|
6
|
+
isOptimizeTarget, MAX_OPTIMIZE_ENTRIES, MAX_OPTIMIZE_PLANS, OPTIMIZE_PLAN_TTL_MS,
|
|
7
|
+
optimizeCandidates, planConsolidation, safeOptimizeMemory,
|
|
8
|
+
type OptimizeApplied, type OptimizeFailure, type OptimizeInspection, type OptimizeInspectOptions,
|
|
9
|
+
type OptimizePlan, type OptimizePreviewInput, type OptimizeTarget,
|
|
10
|
+
} from "./optimize.ts";
|
|
11
|
+
import { DEFAULT_STORE_MAX_ENTRIES, type JsonStore, StoreConflictError, withFileLock } from "./store.ts";
|
|
12
|
+
|
|
13
|
+
export interface MemoryOptimizerOptions {
|
|
14
|
+
stores: Record<OptimizeTarget, JsonStore<MemoryEntry>>;
|
|
15
|
+
persona: string;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
/** Shares MindService's mutation ordering with promote/forget/reset. */
|
|
18
|
+
mutationLock?: string;
|
|
19
|
+
/** Defaults to a scope-bound sidecar beside each target store. */
|
|
20
|
+
historyPaths?: Partial<Record<OptimizeTarget, string>>;
|
|
21
|
+
}
|
|
22
|
+
interface StagedPlan { plan: OptimizePlan; next: MemoryEntry[] }
|
|
23
|
+
|
|
24
|
+
function failure(error: unknown): OptimizeFailure {
|
|
25
|
+
return { ok: false, reason: error instanceof Error ? error.message : "memory optimizer storage failure" };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export class MemoryOptimizer {
|
|
29
|
+
private readonly options: MemoryOptimizerOptions;
|
|
30
|
+
private readonly now: () => number;
|
|
31
|
+
private readonly plans = new Map<string, StagedPlan>();
|
|
32
|
+
private readonly histories = new Map<OptimizeTarget, OptimizeHistoryStore>();
|
|
33
|
+
private generation = 0;
|
|
34
|
+
constructor(options: MemoryOptimizerOptions) {
|
|
35
|
+
this.options = { ...options, stores: { ...options.stores } };
|
|
36
|
+
this.now = options.now ?? Date.now;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Ownership/lifecycle adapters discard this instance or explicitly invalidate its plans. */
|
|
40
|
+
invalidate(): void { this.plans.clear(); this.generation++; }
|
|
41
|
+
|
|
42
|
+
async inspect(target: OptimizeTarget = "project", options: OptimizeInspectOptions = {}): Promise<OptimizeInspection | OptimizeFailure> {
|
|
43
|
+
if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
|
|
44
|
+
if (options.query !== undefined && (typeof options.query !== "string" || options.query.length > MAX_RECALL_QUERY_CHARS)) return { ok: false, reason: `query exceeds ${MAX_RECALL_QUERY_CHARS} characters` };
|
|
45
|
+
const offset = options.offset ?? 0;
|
|
46
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || offset > DEFAULT_STORE_MAX_ENTRIES) return { ok: false, reason: `offset must be an integer from 0 to ${DEFAULT_STORE_MAX_ENTRIES}` };
|
|
47
|
+
try {
|
|
48
|
+
const snapshot = await this.options.stores[target].inspectStrict();
|
|
49
|
+
const active = snapshot.store.entries.filter((entry) => !isExpired(entry, this.now()));
|
|
50
|
+
const query = options.query?.trim().toLowerCase();
|
|
51
|
+
const eligible = active.filter((entry) => safeOptimizeMemory(entry) && (!query || `${entry.text} ${entry.tags.join(" ")}`.toLowerCase().includes(query)));
|
|
52
|
+
const max = options.max === undefined || !Number.isFinite(options.max) ? 20 : Math.max(1, Math.min(MAX_OPTIMIZE_ENTRIES, Math.floor(options.max)));
|
|
53
|
+
const entries = eligible.slice().sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt) || a.id.localeCompare(b.id)).slice(offset, offset + max);
|
|
54
|
+
const nextOffset = offset + entries.length;
|
|
55
|
+
return { ok: true, target, fingerprint: snapshot.fingerprint, entries, total: active.length, withheld: active.length - entries.length, candidates: optimizeCandidates(entries), offset, matched: eligible.length,
|
|
56
|
+
...(nextOffset < eligible.length ? { nextOffset } : {}) };
|
|
57
|
+
} catch (error) { return failure(error); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async preview(input: OptimizePreviewInput): Promise<OptimizePlan | OptimizeFailure> {
|
|
61
|
+
const target = input.target ?? "project";
|
|
62
|
+
if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
|
|
63
|
+
try {
|
|
64
|
+
const snapshot = await this.options.stores[target].inspectStrict();
|
|
65
|
+
if (snapshot.fingerprint !== input.fingerprint) return { ok: false, reason: "memory store changed since inspection; inspect again" };
|
|
66
|
+
const now = this.now();
|
|
67
|
+
const result = planConsolidation(snapshot.store.entries, input.operations, target, this.options.persona, now);
|
|
68
|
+
if (!result.ok) return result;
|
|
69
|
+
const plan: OptimizePlan = { ok: true, planId: randomUUID(), target, fingerprint: snapshot.fingerprint, expiresAt: new Date(now + OPTIMIZE_PLAN_TTL_MS).toISOString(), changes: result.changes, beforeCount: snapshot.store.entries.length, afterCount: result.entries.length };
|
|
70
|
+
this.expirePlans();
|
|
71
|
+
while (this.plans.size >= MAX_OPTIMIZE_PLANS) this.plans.delete(this.plans.keys().next().value!);
|
|
72
|
+
this.plans.set(plan.planId, structuredClone({ plan, next: result.entries }));
|
|
73
|
+
return structuredClone(plan);
|
|
74
|
+
} catch (error) { return failure(error); }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
getPlan(planId: string): OptimizePlan | OptimizeFailure {
|
|
78
|
+
this.expirePlans();
|
|
79
|
+
const stored = this.plans.get(planId);
|
|
80
|
+
return stored ? structuredClone(stored.plan) : { ok: false, reason: "plan not found or expired; inspect and stage again" };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async apply(planId: string): Promise<OptimizeApplied | OptimizeFailure> {
|
|
84
|
+
this.expirePlans();
|
|
85
|
+
const staged = this.plans.get(planId);
|
|
86
|
+
if (!staged) return { ok: false, reason: "plan not found or expired; inspect and stage again" };
|
|
87
|
+
try {
|
|
88
|
+
let receiptId: string | undefined;
|
|
89
|
+
let warning: string | undefined;
|
|
90
|
+
const commit = async () => this.historyStore(staged.plan.target).exclusive(async () => {
|
|
91
|
+
const assertCurrent = () => {
|
|
92
|
+
if (this.plans.get(planId) !== staged || this.now() >= Date.parse(staged.plan.expiresAt)) throw new Error("plan expired or invalidated; inspect and stage again");
|
|
93
|
+
if (staged.plan.changes.some((change) => change.before.some((entry) => isExpired(entry, this.now())))) throw new Error("a source expired since preview; inspect and stage again");
|
|
94
|
+
};
|
|
95
|
+
assertCurrent();
|
|
96
|
+
const store = this.options.stores[staged.plan.target];
|
|
97
|
+
if ((await store.inspectStrict()).fingerprint !== staged.plan.fingerprint) throw new StoreConflictError();
|
|
98
|
+
const history = this.historyStore(staged.plan.target);
|
|
99
|
+
if (staged.plan.changes.length) {
|
|
100
|
+
receiptId = randomUUID();
|
|
101
|
+
const receipt: OptimizeReceipt = { receiptId, planId, target: staged.plan.target, persona: this.options.persona, createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: structuredClone(staged.plan.changes) };
|
|
102
|
+
await history.prepare(receipt);
|
|
103
|
+
}
|
|
104
|
+
let callbackRejected = false;
|
|
105
|
+
try {
|
|
106
|
+
await store.compareAndUpdate(staged.plan.fingerprint, () => {
|
|
107
|
+
try { assertCurrent(); return structuredClone(staged.next); }
|
|
108
|
+
catch (error) { callbackRejected = true; throw error; }
|
|
109
|
+
});
|
|
110
|
+
} catch (error) {
|
|
111
|
+
// A generic IO failure may occur after rename. Preserve its prepared before images.
|
|
112
|
+
if (receiptId && (callbackRejected || error instanceof StoreConflictError)) await history.settle(receiptId, "rejected").catch(() => {});
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
this.plans.delete(planId);
|
|
116
|
+
if (receiptId) {
|
|
117
|
+
try { await history.settle(receiptId, "applied"); }
|
|
118
|
+
catch { warning = "replacement committed; durable receipt remains prepared because history finalization failed"; }
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
if (this.options.mutationLock) await withFileLock(this.options.mutationLock, commit); else await commit();
|
|
122
|
+
return { ok: true, planId, target: staged.plan.target, changed: staged.plan.changes.length, beforeCount: staged.plan.beforeCount, afterCount: staged.plan.afterCount, ...(receiptId ? { receiptId } : {}), ...(warning ? { warning } : {}) };
|
|
123
|
+
} catch (error) { return failure(error); }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async history(target: OptimizeTarget = "project", max = 20): Promise<OptimizeHistory | OptimizeFailure> {
|
|
127
|
+
if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
|
|
128
|
+
if (!Number.isFinite(max) || max < 1) return { ok: false, reason: "history max must be a positive finite number" };
|
|
129
|
+
try {
|
|
130
|
+
const storePath = this.options.stores[target].filePath;
|
|
131
|
+
const all = (await this.historyStore(target).read()).filter((receipt) => receipt.target === target && receipt.storePath === storePath && receipt.persona === this.options.persona);
|
|
132
|
+
const safe = all.filter((receipt) => receipt.changes.every((change) => [...change.before, change.after].every(safeOptimizeMemory)));
|
|
133
|
+
const receipts = safe.slice().reverse().slice(0, Math.min(MAX_OPTIMIZE_HISTORY, Math.floor(max)));
|
|
134
|
+
return { ok: true, target, receipts, retained: all.length, omitted: safe.length - receipts.length, withheldUnsafe: all.length - safe.length, limit: MAX_OPTIMIZE_HISTORY, maxBytes: MAX_OPTIMIZE_HISTORY_BYTES };
|
|
135
|
+
} catch (error) { return failure(error); }
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async undo(receiptId: string, target?: OptimizeTarget): Promise<OptimizeUndone | OptimizeFailure> {
|
|
139
|
+
const generation = this.generation;
|
|
140
|
+
if (target !== undefined && !isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
|
|
141
|
+
try {
|
|
142
|
+
const candidates: OptimizeTarget[] = target ? [target] : ["project", "project-long", "persona", "shared"];
|
|
143
|
+
for (const candidate of candidates) {
|
|
144
|
+
const history = this.historyStore(candidate);
|
|
145
|
+
const found = (await history.read()).some((receipt) => receipt.receiptId === receiptId && receipt.target === candidate && receipt.storePath === this.options.stores[candidate].filePath);
|
|
146
|
+
if (!found) continue;
|
|
147
|
+
const commit = async () => history.exclusive(async (): Promise<OptimizeUndone | OptimizeFailure> => {
|
|
148
|
+
const receipt = (await history.read()).find((entry) => entry.receiptId === receiptId && entry.target === candidate && entry.storePath === this.options.stores[candidate].filePath);
|
|
149
|
+
if (!receipt) return { ok: false, reason: "optimizer receipt is no longer retained" };
|
|
150
|
+
const store = this.options.stores[candidate];
|
|
151
|
+
const snapshot = await store.inspectStrict();
|
|
152
|
+
let restored = 0;
|
|
153
|
+
await store.compareAndUpdate(snapshot.fingerprint, (entries) => {
|
|
154
|
+
if (this.generation !== generation) throw new Error("memory owner changed; undo invalidated before commit");
|
|
155
|
+
const result = restoreReceipt(entries, receipt, this.options.persona, this.now());
|
|
156
|
+
if (!result.ok) throw new Error(result.reason);
|
|
157
|
+
restored = result.restored;
|
|
158
|
+
return result.entries;
|
|
159
|
+
});
|
|
160
|
+
try { await history.settle(receiptId, "undone"); }
|
|
161
|
+
catch { return { ok: true, receiptId, target: candidate, restored, warning: "undo committed; history finalization failed, affected-fact checks prevent duplicate undo" }; }
|
|
162
|
+
return { ok: true, receiptId, target: candidate, restored };
|
|
163
|
+
});
|
|
164
|
+
return this.options.mutationLock ? await withFileLock(this.options.mutationLock, commit) : await commit();
|
|
165
|
+
}
|
|
166
|
+
return { ok: false, reason: "optimizer receipt not found in this scope or no longer retained" };
|
|
167
|
+
} catch (error) { return failure(error); }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private historyStore(target: OptimizeTarget): OptimizeHistoryStore {
|
|
171
|
+
let history = this.histories.get(target);
|
|
172
|
+
if (!history) {
|
|
173
|
+
history = new OptimizeHistoryStore(this.options.historyPaths?.[target] ?? `${this.options.stores[target].filePath}.optimize-history.json`, this.now);
|
|
174
|
+
this.histories.set(target, history);
|
|
175
|
+
}
|
|
176
|
+
return history;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private expirePlans(): void {
|
|
180
|
+
for (const [id, staged] of this.plans) if (this.now() >= Date.parse(staged.plan.expiresAt)) this.plans.delete(id);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/** Explicit memory consolidation rules. Similarity discovers candidates; it never authorizes edits. */
|
|
2
|
+
import {
|
|
3
|
+
isExpired, isMemoryId, makeMemory, memoryContentKey, MEMORY_KINDS,
|
|
4
|
+
MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_SOURCE_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS, MAX_MEMORY_TEXT_CHARS,
|
|
5
|
+
validateMemory, type MemoryEntry, type MemoryKind,
|
|
6
|
+
} from "./memory.ts";
|
|
7
|
+
import { scanContent } from "./scanner.ts";
|
|
8
|
+
|
|
9
|
+
export type OptimizeTarget = "project" | "project-long" | "persona" | "shared";
|
|
10
|
+
export interface OptimizeOperation { sourceIds: string[]; kind: MemoryKind; text: string; tags?: string[]; source?: string }
|
|
11
|
+
export interface OptimizeFailure { ok: false; reason: string }
|
|
12
|
+
export interface OptimizeCandidate { leftId: string; rightId: string; similarity: number; exact: boolean }
|
|
13
|
+
export interface OptimizeInspection {
|
|
14
|
+
ok: true; target: OptimizeTarget; fingerprint: string; entries: MemoryEntry[];
|
|
15
|
+
total: number; withheld: number; candidates: OptimizeCandidate[];
|
|
16
|
+
offset: number; matched: number; nextOffset?: number;
|
|
17
|
+
}
|
|
18
|
+
export interface OptimizeChange { before: MemoryEntry[]; after: MemoryEntry }
|
|
19
|
+
export interface OptimizePlan {
|
|
20
|
+
ok: true; planId: string; target: OptimizeTarget; fingerprint: string; expiresAt: string;
|
|
21
|
+
changes: OptimizeChange[]; beforeCount: number; afterCount: number;
|
|
22
|
+
}
|
|
23
|
+
export interface OptimizeApplied { ok: true; planId: string; target: OptimizeTarget; changed: number; beforeCount: number; afterCount: number; receiptId?: string; warning?: string }
|
|
24
|
+
export interface OptimizePreviewInput { target?: OptimizeTarget; fingerprint: string; operations: OptimizeOperation[] }
|
|
25
|
+
export interface OptimizeInspectOptions { query?: string; max?: number; offset?: number }
|
|
26
|
+
|
|
27
|
+
export const MAX_OPTIMIZE_ENTRIES = 100;
|
|
28
|
+
export const MAX_OPTIMIZE_CANDIDATES = 12;
|
|
29
|
+
export const MAX_OPTIMIZE_OPERATIONS = 8;
|
|
30
|
+
export const MAX_OPTIMIZE_SOURCES = 16;
|
|
31
|
+
export const MAX_OPTIMIZE_PLANS = 4;
|
|
32
|
+
export const OPTIMIZE_PLAN_TTL_MS = 10 * 60_000;
|
|
33
|
+
|
|
34
|
+
export function isOptimizeTarget(value: unknown): value is OptimizeTarget {
|
|
35
|
+
return value === "project" || value === "project-long" || value === "persona" || value === "shared";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** All persisted model-visible fields are untrusted, including tags and human-citable origins. */
|
|
39
|
+
export function safeOptimizeMemory(entry: MemoryEntry): boolean {
|
|
40
|
+
return [entry.text, ...entry.tags, entry.source ?? "", entry.persona ?? ""].every((text) => scanContent(text).ok);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function terms(text: string): Set<string> {
|
|
44
|
+
return new Set(text.toLowerCase().match(/[\p{L}\p{N}\p{M}]+/gu) ?? []);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function samePersistedMemory(a: MemoryEntry, b: MemoryEntry): boolean {
|
|
48
|
+
const left = validateMemory(a);
|
|
49
|
+
const right = validateMemory(b);
|
|
50
|
+
return left !== null && right !== null && JSON.stringify(left) === JSON.stringify(right);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Bounded lexical advisory only: opposite claims can have almost identical words. */
|
|
54
|
+
export function optimizeCandidates(entries: readonly MemoryEntry[]): OptimizeCandidate[] {
|
|
55
|
+
const bounded = entries.slice(0, MAX_OPTIMIZE_ENTRIES);
|
|
56
|
+
const words = bounded.map((entry) => terms(`${entry.text} ${entry.tags.join(" ")}`));
|
|
57
|
+
const candidates: OptimizeCandidate[] = [];
|
|
58
|
+
for (let i = 0; i < bounded.length; i++) {
|
|
59
|
+
const left = bounded[i]!;
|
|
60
|
+
for (let j = i + 1; j < bounded.length; j++) {
|
|
61
|
+
const right = bounded[j]!;
|
|
62
|
+
if (left.kind !== right.kind || left.persona !== right.persona) continue;
|
|
63
|
+
const a = words[i]!; const b = words[j]!;
|
|
64
|
+
const common = [...a].filter((word) => b.has(word)).length;
|
|
65
|
+
const union = a.size + b.size - common;
|
|
66
|
+
const exact = memoryContentKey(left) === memoryContentKey(right);
|
|
67
|
+
const similarity = exact ? 1 : union === 0 ? 0 : common / union;
|
|
68
|
+
if (exact || similarity >= 0.45) candidates.push({ leftId: left.id, rightId: right.id, similarity, exact });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return candidates.sort((a, b) => b.similarity - a.similarity || a.leftId.localeCompare(b.leftId) || a.rightId.localeCompare(b.rightId)).slice(0, MAX_OPTIMIZE_CANDIDATES);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Build a reviewed replacement set without mutation. Unselected entries are never upsert targets. */
|
|
75
|
+
export function planConsolidation(entries: readonly MemoryEntry[], operations: readonly OptimizeOperation[], target: OptimizeTarget, persona: string, now: number): { ok: true; changes: OptimizeChange[]; entries: MemoryEntry[] } | OptimizeFailure {
|
|
76
|
+
if (!Array.isArray(operations) || operations.length < 1 || operations.length > MAX_OPTIMIZE_OPERATIONS) {
|
|
77
|
+
return { ok: false, reason: `provide 1..${MAX_OPTIMIZE_OPERATIONS} explicit consolidation operations` };
|
|
78
|
+
}
|
|
79
|
+
const selected = new Set<MemoryEntry>();
|
|
80
|
+
const changes: OptimizeChange[] = [];
|
|
81
|
+
for (const operation of operations) {
|
|
82
|
+
if (!operation || !Array.isArray(operation.sourceIds) || operation.sourceIds.length < 1 || operation.sourceIds.length > MAX_OPTIMIZE_SOURCES || operation.sourceIds.some((id: unknown) => !isMemoryId(id))) {
|
|
83
|
+
return { ok: false, reason: `each operation needs 1..${MAX_OPTIMIZE_SOURCES} exact safe source IDs` };
|
|
84
|
+
}
|
|
85
|
+
const before: MemoryEntry[] = [];
|
|
86
|
+
for (const id of operation.sourceIds) {
|
|
87
|
+
const matches = entries.filter((entry) => entry.id === id);
|
|
88
|
+
if (matches.length !== 1) return { ok: false, reason: `source ${id} is missing or ambiguous; no entries changed` };
|
|
89
|
+
const entry = matches[0]!;
|
|
90
|
+
if (selected.has(entry)) return { ok: false, reason: "source IDs overlap within or between operations" };
|
|
91
|
+
if (isExpired(entry, now)) return { ok: false, reason: `source ${id} expired; inspect again` };
|
|
92
|
+
if ((target === "project" || target === "project-long") && entry.persona !== persona) return { ok: false, reason: `source ${id} belongs to a different or unowned persona` };
|
|
93
|
+
if (!safeOptimizeMemory(entry)) return { ok: false, reason: `source ${id} contains unsafe stored content` };
|
|
94
|
+
selected.add(entry); before.push(entry);
|
|
95
|
+
}
|
|
96
|
+
if (before.some((entry) => entry.persona !== before[0]!.persona)) return { ok: false, reason: "consolidation cannot mix persona ownership markers" };
|
|
97
|
+
if (!(MEMORY_KINDS as readonly unknown[]).includes(operation.kind) || (target === "project" && operation.kind === "objective")) {
|
|
98
|
+
return { ok: false, reason: "invalid memory kind for the selected tier (objectives are durable)" };
|
|
99
|
+
}
|
|
100
|
+
if (typeof operation.text !== "string" || !operation.text.trim() || operation.text.length > MAX_MEMORY_TEXT_CHARS) return { ok: false, reason: `replacement text must contain 1..${MAX_MEMORY_TEXT_CHARS} characters` };
|
|
101
|
+
if (operation.tags !== undefined && (!Array.isArray(operation.tags) || operation.tags.length > MAX_MEMORY_TAGS || operation.tags.some((tag: unknown) => typeof tag !== "string" || tag.length > MAX_MEMORY_TAG_CHARS))) return { ok: false, reason: "replacement tags exceed memory bounds" };
|
|
102
|
+
if (operation.source !== undefined && (typeof operation.source !== "string" || operation.source.length > MAX_MEMORY_SOURCE_CHARS)) return { ok: false, reason: "replacement source exceeds memory bounds" };
|
|
103
|
+
const tags = operation.tags ?? before.flatMap((entry) => entry.tags);
|
|
104
|
+
const after = makeMemory({ term: target === "project" ? "short" : "long", kind: operation.kind, text: operation.text, tags }, now);
|
|
105
|
+
if (after.tags.length > MAX_MEMORY_TAGS || after.tags.some((tag) => tag.length > MAX_MEMORY_TAG_CHARS)) return { ok: false, reason: "combined replacement tags exceed memory bounds; provide explicit tags or split the operation" };
|
|
106
|
+
const marker = before[0]!.persona;
|
|
107
|
+
if (marker !== undefined) after.persona = marker;
|
|
108
|
+
after.recordedAt = before.reduce((earliest, entry) => Date.parse(entry.recordedAt) < Date.parse(earliest) ? entry.recordedAt : earliest, before[0]!.recordedAt);
|
|
109
|
+
if (target === "project") {
|
|
110
|
+
if (before.some((entry) => entry.expiresAt === undefined)) return { ok: false, reason: "project source lacks expiry" };
|
|
111
|
+
after.expiresAt = before.reduce((earliest, entry) => Date.parse(entry.expiresAt!) < Date.parse(earliest) ? entry.expiresAt! : earliest, before[0]!.expiresAt!);
|
|
112
|
+
}
|
|
113
|
+
const lineage = [...new Set(before.flatMap((entry) => [entry.id, ...(entry.derivedFrom ?? []), ...(entry.supersedes ? [entry.supersedes] : [])]))].filter((id) => id !== after.id);
|
|
114
|
+
if (lineage.length > MAX_MEMORY_DERIVED_IDS) return { ok: false, reason: `consolidation provenance exceeds ${MAX_MEMORY_DERIVED_IDS} IDs; split the operation` };
|
|
115
|
+
if (lineage.length > 0) after.derivedFrom = lineage;
|
|
116
|
+
const origins = [...new Set([...before.flatMap((entry) => entry.source ? [entry.source] : []), ...(operation.source ? [operation.source] : [])])];
|
|
117
|
+
if (origins.length > 0) after.source = origins.join("; ");
|
|
118
|
+
if ((after.source?.length ?? 0) > MAX_MEMORY_SOURCE_CHARS) return { ok: false, reason: "combined source provenance exceeds memory bounds; split the operation" };
|
|
119
|
+
const normalizedAfter = validateMemory(after);
|
|
120
|
+
if (!normalizedAfter) return { ok: false, reason: "replacement metadata exceeds memory schema bounds" };
|
|
121
|
+
if (!safeOptimizeMemory(normalizedAfter)) return { ok: false, reason: "replacement content, tags or source rejected by content scanner" };
|
|
122
|
+
changes.push({ before, after: normalizedAfter });
|
|
123
|
+
}
|
|
124
|
+
const effectiveChanges = changes.filter((change) => change.before.length !== 1 || !samePersistedMemory(change.before[0]!, change.after));
|
|
125
|
+
const effectivelySelected = new Set(effectiveChanges.flatMap((change) => change.before));
|
|
126
|
+
const untouched = entries.filter((entry) => !effectivelySelected.has(entry));
|
|
127
|
+
const replacements = effectiveChanges.map((change) => change.after);
|
|
128
|
+
for (let i = 0; i < replacements.length; i++) {
|
|
129
|
+
const replacement = replacements[i]!;
|
|
130
|
+
if ([...untouched, ...replacements.slice(0, i)].some((entry) => entry.id === replacement.id || memoryContentKey(entry) === memoryContentKey(replacement))) return { ok: false, reason: "replacement collides with another fact; include its exact source or revise the proposal" };
|
|
131
|
+
}
|
|
132
|
+
return { ok: true, changes: effectiveChanges, entries: [...untouched, ...replacements] };
|
|
133
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Deterministic lexical and repository-path ranking; tags are the only explicit semantic bridge. */
|
|
2
|
+
|
|
3
|
+
import type { MemoryEntry, MemoryKind } from "./memory.ts";
|
|
4
|
+
|
|
5
|
+
const QUERY_MAX_CHARS = 512;
|
|
6
|
+
const STOP_WORDS = new Set([
|
|
7
|
+
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how", "in", "into", "is", "it", "of", "on", "or", "the", "this", "to", "use", "what", "when", "where", "which", "with",
|
|
8
|
+
]);
|
|
9
|
+
const NEGATION_AND_EXCEPTION = new Set(["except", "never", "no", "not", "only", "unless", "without"]);
|
|
10
|
+
const KIND_PRIORITY: Record<MemoryKind, number> = { objective: -1, invariant: 0, preference: 1, convention: 2, rationale: 3, gotcha: 4, note: 5 };
|
|
11
|
+
|
|
12
|
+
export interface RetrievalSource {
|
|
13
|
+
text: string;
|
|
14
|
+
tags?: readonly string[];
|
|
15
|
+
id?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RetrievalRank<T> {
|
|
19
|
+
entry: T;
|
|
20
|
+
score: number;
|
|
21
|
+
textTerms: string[];
|
|
22
|
+
tagTerms: string[];
|
|
23
|
+
pathMatches: string[];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function compareStrings(a: string, b: string): number {
|
|
27
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const TOKEN_SEGMENTS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{N}]+/gu;
|
|
31
|
+
const EAST_ASIAN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
32
|
+
|
|
33
|
+
function words(value: string): string[] {
|
|
34
|
+
const segments = value.toLowerCase().match(TOKEN_SEGMENTS) ?? [];
|
|
35
|
+
return segments.flatMap((segment) => {
|
|
36
|
+
const chars = [...segment];
|
|
37
|
+
if (chars.length < 2 || !EAST_ASIAN.test(chars[0] ?? "")) return [segment];
|
|
38
|
+
const bigrams: string[] = [];
|
|
39
|
+
for (let index = 0; index < chars.length - 1; index++) bigrams.push(`${chars[index]}${chars[index + 1]}`);
|
|
40
|
+
return bigrams;
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function queryTerms(query: string): string[] {
|
|
45
|
+
const seen = new Set<string>();
|
|
46
|
+
const result: string[] = [];
|
|
47
|
+
for (const term of words(query.slice(0, QUERY_MAX_CHARS))) {
|
|
48
|
+
if (STOP_WORDS.has(term) && !NEGATION_AND_EXCEPTION.has(term)) continue;
|
|
49
|
+
if (seen.has(term)) continue;
|
|
50
|
+
seen.add(term);
|
|
51
|
+
result.push(term);
|
|
52
|
+
}
|
|
53
|
+
return result;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function queryPaths(query: string): string[] {
|
|
57
|
+
const matches = query.slice(0, QUERY_MAX_CHARS).match(/[A-Za-z0-9_.-]+(?:[\\/][A-Za-z0-9_.-]+)+/g) ?? [];
|
|
58
|
+
return [...new Set(matches.map((path) => path.replace(/\\/g, "/").toLowerCase()))];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function entryPathMatches(entry: RetrievalSource, paths: readonly string[]): string[] {
|
|
62
|
+
if (paths.length === 0) return [];
|
|
63
|
+
const content = `${entry.text} ${(entry.tags ?? []).join(" ")}`.replace(/\\/g, "/").toLowerCase();
|
|
64
|
+
return paths.filter((path) => content.includes(path));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function rankItem<T extends RetrievalSource>(entry: T, query: string): RetrievalRank<T> {
|
|
68
|
+
const terms = queryTerms(query);
|
|
69
|
+
const textWords = new Set(words(entry.text));
|
|
70
|
+
const tagWords = new Set((entry.tags ?? []).flatMap(words));
|
|
71
|
+
const textTerms = terms.filter((term) => textWords.has(term));
|
|
72
|
+
const tagTerms = terms.filter((term) => !textWords.has(term) && tagWords.has(term));
|
|
73
|
+
const pathMatches = entryPathMatches(entry, queryPaths(query));
|
|
74
|
+
const textScore = textTerms.reduce((sum, term) => sum + (NEGATION_AND_EXCEPTION.has(term) ? 4 : 3), 0);
|
|
75
|
+
const tagScore = tagTerms.reduce((sum, term) => sum + (NEGATION_AND_EXCEPTION.has(term) ? 3 : 2), 0);
|
|
76
|
+
const score = textScore + tagScore + pathMatches.length * 12;
|
|
77
|
+
return { entry, score, textTerms, tagTerms, pathMatches };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Rank generic text/tag entries; optional ties are resolved by the supplied domain comparator. */
|
|
81
|
+
export function rankRetrievalEntries<T extends RetrievalSource>(
|
|
82
|
+
entries: readonly T[],
|
|
83
|
+
query: string,
|
|
84
|
+
tieBreak?: (a: T, b: T) => number,
|
|
85
|
+
): RetrievalRank<T>[] {
|
|
86
|
+
return entries.map((entry) => rankItem(entry, query)).sort((a, b) => {
|
|
87
|
+
if (a.score !== b.score) return b.score - a.score;
|
|
88
|
+
const tie = tieBreak?.(a.entry, b.entry) ?? 0;
|
|
89
|
+
if (tie !== 0) return tie;
|
|
90
|
+
return compareStrings(a.entry.id ?? "", b.entry.id ?? "");
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function dateTie(a: Pick<MemoryEntry, "lastSeenAt">, b: Pick<MemoryEntry, "lastSeenAt">): number {
|
|
95
|
+
const aTime = Date.parse(a.lastSeenAt);
|
|
96
|
+
const bTime = Date.parse(b.lastSeenAt);
|
|
97
|
+
const aValid = Number.isFinite(aTime) ? aTime : Number.NEGATIVE_INFINITY;
|
|
98
|
+
const bValid = Number.isFinite(bTime) ? bTime : Number.NEGATIVE_INFINITY;
|
|
99
|
+
return bValid - aValid;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Rank durable/working facts for a task or explicit recall. There is no stemming, synonym table,
|
|
104
|
+
* embedding, or learned score: lexical matches and hand-authored tags explain every positive rank.
|
|
105
|
+
*/
|
|
106
|
+
export function rankMemoryEntries(entries: readonly MemoryEntry[], query: string): RetrievalRank<MemoryEntry>[] {
|
|
107
|
+
return rankRetrievalEntries(entries, query, (a, b) => KIND_PRIORITY[a.kind] - KIND_PRIORITY[b.kind] || dateTie(a, b));
|
|
108
|
+
}
|