@aeondave/pi-persona-mind 0.9.6 → 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 -135
- package/CHANGELOG.md +287 -270
- package/LICENSE +24 -24
- package/README.md +84 -171
- package/docs/DESIGN.md +605 -573
- package/docs/MEMORY-RESEARCH.md +163 -163
- package/package.json +15 -6
- package/src/core/auto-optimize.ts +323 -249
- package/src/core/backlog.ts +228 -228
- package/src/core/blocked.ts +38 -38
- package/src/core/capture.ts +155 -154
- 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 -180
- 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 -205
- 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 -569
- 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 -0
- package/src/extension/review-evidence.ts +222 -222
- package/src/extension/worker-memory-anchor.ts +28 -28
- package/src/index.ts +1357 -1310
- package/src/session-memory.ts +127 -122
- 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 -56
package/src/core/optimize.ts
CHANGED
|
@@ -1,127 +1,127 @@
|
|
|
1
|
-
/** Explicit memory consolidation rules. Similarity discovers candidates; it never authorizes edits. */
|
|
2
|
-
import {
|
|
3
|
-
isExpired, isMemoryId, isSafeMemoryContent, 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
|
-
|
|
8
|
-
export type OptimizeTarget = "project" | "project-long" | "persona" | "shared";
|
|
9
|
-
export interface OptimizeOperation { sourceIds: string[]; kind: MemoryKind; text: string; tags?: string[]; source?: string }
|
|
10
|
-
export interface OptimizeFailure { ok: false; reason: string }
|
|
11
|
-
export interface OptimizeCandidate { leftId: string; rightId: string; similarity: number; exact: boolean }
|
|
12
|
-
export interface OptimizeInspection {
|
|
13
|
-
ok: true; target: OptimizeTarget; fingerprint: string; entries: MemoryEntry[];
|
|
14
|
-
total: number; withheld: number; candidates: OptimizeCandidate[];
|
|
15
|
-
offset: number; matched: number; nextOffset?: number;
|
|
16
|
-
}
|
|
17
|
-
export interface OptimizeChange { before: MemoryEntry[]; after: MemoryEntry }
|
|
18
|
-
export interface OptimizePlan {
|
|
19
|
-
ok: true; planId: string; target: OptimizeTarget; fingerprint: string; expiresAt: string;
|
|
20
|
-
changes: OptimizeChange[]; beforeCount: number; afterCount: number;
|
|
21
|
-
}
|
|
22
|
-
export interface OptimizeApplied { ok: true; planId: string; target: OptimizeTarget; changed: number; beforeCount: number; afterCount: number; receiptId?: string; warning?: string }
|
|
23
|
-
export interface OptimizePreviewInput { target?: OptimizeTarget; fingerprint: string; operations: OptimizeOperation[] }
|
|
24
|
-
export interface OptimizeInspectOptions { query?: string; max?: number; offset?: number }
|
|
25
|
-
|
|
26
|
-
export const MAX_OPTIMIZE_ENTRIES = 100;
|
|
27
|
-
export const MAX_OPTIMIZE_CANDIDATES = 12;
|
|
28
|
-
export const MAX_OPTIMIZE_OPERATIONS = 8;
|
|
29
|
-
export const MAX_OPTIMIZE_SOURCES = 16;
|
|
30
|
-
export const MAX_OPTIMIZE_PLANS = 4;
|
|
31
|
-
export const OPTIMIZE_PLAN_TTL_MS = 10 * 60_000;
|
|
32
|
-
|
|
33
|
-
export function isOptimizeTarget(value: unknown): value is OptimizeTarget {
|
|
34
|
-
return value === "project" || value === "project-long" || value === "persona" || value === "shared";
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function terms(text: string): Set<string> {
|
|
38
|
-
return new Set(text.toLowerCase().match(/[\p{L}\p{N}\p{M}]+/gu) ?? []);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export function samePersistedMemory(a: MemoryEntry, b: MemoryEntry): boolean {
|
|
42
|
-
const left = validateMemory(a);
|
|
43
|
-
const right = validateMemory(b);
|
|
44
|
-
return left !== null && right !== null && JSON.stringify(left) === JSON.stringify(right);
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Bounded lexical advisory only: opposite claims can have almost identical words. */
|
|
48
|
-
export function optimizeCandidates(entries: readonly MemoryEntry[]): OptimizeCandidate[] {
|
|
49
|
-
const bounded = entries.slice(0, MAX_OPTIMIZE_ENTRIES);
|
|
50
|
-
const words = bounded.map((entry) => terms(`${entry.text} ${entry.tags.join(" ")}`));
|
|
51
|
-
const candidates: OptimizeCandidate[] = [];
|
|
52
|
-
for (let i = 0; i < bounded.length; i++) {
|
|
53
|
-
const left = bounded[i]!;
|
|
54
|
-
for (let j = i + 1; j < bounded.length; j++) {
|
|
55
|
-
const right = bounded[j]!;
|
|
56
|
-
if (left.kind !== right.kind || left.persona !== right.persona) continue;
|
|
57
|
-
const a = words[i]!; const b = words[j]!;
|
|
58
|
-
const common = [...a].filter((word) => b.has(word)).length;
|
|
59
|
-
const union = a.size + b.size - common;
|
|
60
|
-
const exact = memoryContentKey(left) === memoryContentKey(right);
|
|
61
|
-
const similarity = exact ? 1 : union === 0 ? 0 : common / union;
|
|
62
|
-
if (exact || similarity >= 0.45) candidates.push({ leftId: left.id, rightId: right.id, similarity, exact });
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return candidates.sort((a, b) => b.similarity - a.similarity || a.leftId.localeCompare(b.leftId) || a.rightId.localeCompare(b.rightId)).slice(0, MAX_OPTIMIZE_CANDIDATES);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** Build a reviewed replacement set without mutation. Unselected entries are never upsert targets. */
|
|
69
|
-
export function planConsolidation(entries: readonly MemoryEntry[], operations: readonly OptimizeOperation[], target: OptimizeTarget, persona: string, now: number): { ok: true; changes: OptimizeChange[]; entries: MemoryEntry[] } | OptimizeFailure {
|
|
70
|
-
if (!Array.isArray(operations) || operations.length < 1 || operations.length > MAX_OPTIMIZE_OPERATIONS) {
|
|
71
|
-
return { ok: false, reason: `provide 1..${MAX_OPTIMIZE_OPERATIONS} explicit consolidation operations` };
|
|
72
|
-
}
|
|
73
|
-
const selected = new Set<MemoryEntry>();
|
|
74
|
-
const changes: OptimizeChange[] = [];
|
|
75
|
-
for (const operation of operations) {
|
|
76
|
-
if (!operation || !Array.isArray(operation.sourceIds) || operation.sourceIds.length < 1 || operation.sourceIds.length > MAX_OPTIMIZE_SOURCES || operation.sourceIds.some((id: unknown) => !isMemoryId(id))) {
|
|
77
|
-
return { ok: false, reason: `each operation needs 1..${MAX_OPTIMIZE_SOURCES} exact safe source IDs` };
|
|
78
|
-
}
|
|
79
|
-
const before: MemoryEntry[] = [];
|
|
80
|
-
for (const id of operation.sourceIds) {
|
|
81
|
-
const matches = entries.filter((entry) => entry.id === id);
|
|
82
|
-
if (matches.length !== 1) return { ok: false, reason: `source ${id} is missing or ambiguous; no entries changed` };
|
|
83
|
-
const entry = matches[0]!;
|
|
84
|
-
if (selected.has(entry)) return { ok: false, reason: "source IDs overlap within or between operations" };
|
|
85
|
-
if (isExpired(entry, now)) return { ok: false, reason: `source ${id} expired; inspect again` };
|
|
86
|
-
if ((target === "project" || target === "project-long") && entry.persona !== persona) return { ok: false, reason: `source ${id} belongs to a different or unowned persona` };
|
|
87
|
-
if (!isSafeMemoryContent(entry)) return { ok: false, reason: `source ${id} contains unsafe stored content` };
|
|
88
|
-
selected.add(entry); before.push(entry);
|
|
89
|
-
}
|
|
90
|
-
if (before.some((entry) => entry.persona !== before[0]!.persona)) return { ok: false, reason: "consolidation cannot mix persona ownership markers" };
|
|
91
|
-
if (!(MEMORY_KINDS as readonly unknown[]).includes(operation.kind)) {
|
|
92
|
-
return { ok: false, reason: "invalid memory kind for the selected tier" };
|
|
93
|
-
}
|
|
94
|
-
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` };
|
|
95
|
-
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" };
|
|
96
|
-
if (operation.source !== undefined && (typeof operation.source !== "string" || operation.source.length > MAX_MEMORY_SOURCE_CHARS)) return { ok: false, reason: "replacement source exceeds memory bounds" };
|
|
97
|
-
const tags = operation.tags ?? before.flatMap((entry) => entry.tags);
|
|
98
|
-
const after = makeMemory({ term: target === "project" ? "short" : "long", kind: operation.kind, text: operation.text, tags }, now);
|
|
99
|
-
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" };
|
|
100
|
-
const marker = before[0]!.persona;
|
|
101
|
-
if (marker !== undefined) after.persona = marker;
|
|
102
|
-
after.recordedAt = before.reduce((earliest, entry) => Date.parse(entry.recordedAt) < Date.parse(earliest) ? entry.recordedAt : earliest, before[0]!.recordedAt);
|
|
103
|
-
if (target === "project") {
|
|
104
|
-
if (before.some((entry) => entry.expiresAt === undefined)) return { ok: false, reason: "project source lacks expiry" };
|
|
105
|
-
after.expiresAt = before.reduce((earliest, entry) => Date.parse(entry.expiresAt!) < Date.parse(earliest) ? entry.expiresAt! : earliest, before[0]!.expiresAt!);
|
|
106
|
-
}
|
|
107
|
-
const lineage = [...new Set(before.flatMap((entry) => [entry.id, ...(entry.derivedFrom ?? []), ...(entry.supersedes ? [entry.supersedes] : [])]))].filter((id) => id !== after.id);
|
|
108
|
-
if (lineage.length > MAX_MEMORY_DERIVED_IDS) return { ok: false, reason: `consolidation provenance exceeds ${MAX_MEMORY_DERIVED_IDS} IDs; split the operation` };
|
|
109
|
-
if (lineage.length > 0) after.derivedFrom = lineage;
|
|
110
|
-
const origins = [...new Set([...before.flatMap((entry) => entry.source ? [entry.source] : []), ...(operation.source ? [operation.source] : [])])];
|
|
111
|
-
if (origins.length > 0) after.source = origins.join("; ");
|
|
112
|
-
if ((after.source?.length ?? 0) > MAX_MEMORY_SOURCE_CHARS) return { ok: false, reason: "combined source provenance exceeds memory bounds; split the operation" };
|
|
113
|
-
const normalizedAfter = validateMemory(after);
|
|
114
|
-
if (!normalizedAfter) return { ok: false, reason: "replacement metadata exceeds memory schema bounds" };
|
|
115
|
-
if (!isSafeMemoryContent(normalizedAfter)) return { ok: false, reason: "replacement content, tags or source rejected by content scanner" };
|
|
116
|
-
changes.push({ before, after: normalizedAfter });
|
|
117
|
-
}
|
|
118
|
-
const effectiveChanges = changes.filter((change) => change.before.length !== 1 || !samePersistedMemory(change.before[0]!, change.after));
|
|
119
|
-
const effectivelySelected = new Set(effectiveChanges.flatMap((change) => change.before));
|
|
120
|
-
const untouched = entries.filter((entry) => !effectivelySelected.has(entry));
|
|
121
|
-
const replacements = effectiveChanges.map((change) => change.after);
|
|
122
|
-
for (let i = 0; i < replacements.length; i++) {
|
|
123
|
-
const replacement = replacements[i]!;
|
|
124
|
-
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" };
|
|
125
|
-
}
|
|
126
|
-
return { ok: true, changes: effectiveChanges, entries: [...untouched, ...replacements] };
|
|
127
|
-
}
|
|
1
|
+
/** Explicit memory consolidation rules. Similarity discovers candidates; it never authorizes edits. */
|
|
2
|
+
import {
|
|
3
|
+
isExpired, isMemoryId, isSafeMemoryContent, 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
|
+
|
|
8
|
+
export type OptimizeTarget = "project" | "project-long" | "persona" | "shared";
|
|
9
|
+
export interface OptimizeOperation { sourceIds: string[]; kind: MemoryKind; text: string; tags?: string[]; source?: string }
|
|
10
|
+
export interface OptimizeFailure { ok: false; reason: string }
|
|
11
|
+
export interface OptimizeCandidate { leftId: string; rightId: string; similarity: number; exact: boolean }
|
|
12
|
+
export interface OptimizeInspection {
|
|
13
|
+
ok: true; target: OptimizeTarget; fingerprint: string; entries: MemoryEntry[];
|
|
14
|
+
total: number; withheld: number; candidates: OptimizeCandidate[];
|
|
15
|
+
offset: number; matched: number; nextOffset?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface OptimizeChange { before: MemoryEntry[]; after: MemoryEntry }
|
|
18
|
+
export interface OptimizePlan {
|
|
19
|
+
ok: true; planId: string; target: OptimizeTarget; fingerprint: string; expiresAt: string;
|
|
20
|
+
changes: OptimizeChange[]; beforeCount: number; afterCount: number;
|
|
21
|
+
}
|
|
22
|
+
export interface OptimizeApplied { ok: true; planId: string; target: OptimizeTarget; changed: number; beforeCount: number; afterCount: number; receiptId?: string; warning?: string }
|
|
23
|
+
export interface OptimizePreviewInput { target?: OptimizeTarget; fingerprint: string; operations: OptimizeOperation[] }
|
|
24
|
+
export interface OptimizeInspectOptions { query?: string; max?: number; offset?: number }
|
|
25
|
+
|
|
26
|
+
export const MAX_OPTIMIZE_ENTRIES = 100;
|
|
27
|
+
export const MAX_OPTIMIZE_CANDIDATES = 12;
|
|
28
|
+
export const MAX_OPTIMIZE_OPERATIONS = 8;
|
|
29
|
+
export const MAX_OPTIMIZE_SOURCES = 16;
|
|
30
|
+
export const MAX_OPTIMIZE_PLANS = 4;
|
|
31
|
+
export const OPTIMIZE_PLAN_TTL_MS = 10 * 60_000;
|
|
32
|
+
|
|
33
|
+
export function isOptimizeTarget(value: unknown): value is OptimizeTarget {
|
|
34
|
+
return value === "project" || value === "project-long" || value === "persona" || value === "shared";
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function terms(text: string): Set<string> {
|
|
38
|
+
return new Set(text.toLowerCase().match(/[\p{L}\p{N}\p{M}]+/gu) ?? []);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function samePersistedMemory(a: MemoryEntry, b: MemoryEntry): boolean {
|
|
42
|
+
const left = validateMemory(a);
|
|
43
|
+
const right = validateMemory(b);
|
|
44
|
+
return left !== null && right !== null && JSON.stringify(left) === JSON.stringify(right);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Bounded lexical advisory only: opposite claims can have almost identical words. */
|
|
48
|
+
export function optimizeCandidates(entries: readonly MemoryEntry[]): OptimizeCandidate[] {
|
|
49
|
+
const bounded = entries.slice(0, MAX_OPTIMIZE_ENTRIES);
|
|
50
|
+
const words = bounded.map((entry) => terms(`${entry.text} ${entry.tags.join(" ")}`));
|
|
51
|
+
const candidates: OptimizeCandidate[] = [];
|
|
52
|
+
for (let i = 0; i < bounded.length; i++) {
|
|
53
|
+
const left = bounded[i]!;
|
|
54
|
+
for (let j = i + 1; j < bounded.length; j++) {
|
|
55
|
+
const right = bounded[j]!;
|
|
56
|
+
if (left.kind !== right.kind || left.persona !== right.persona) continue;
|
|
57
|
+
const a = words[i]!; const b = words[j]!;
|
|
58
|
+
const common = [...a].filter((word) => b.has(word)).length;
|
|
59
|
+
const union = a.size + b.size - common;
|
|
60
|
+
const exact = memoryContentKey(left) === memoryContentKey(right);
|
|
61
|
+
const similarity = exact ? 1 : union === 0 ? 0 : common / union;
|
|
62
|
+
if (exact || similarity >= 0.45) candidates.push({ leftId: left.id, rightId: right.id, similarity, exact });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return candidates.sort((a, b) => b.similarity - a.similarity || a.leftId.localeCompare(b.leftId) || a.rightId.localeCompare(b.rightId)).slice(0, MAX_OPTIMIZE_CANDIDATES);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Build a reviewed replacement set without mutation. Unselected entries are never upsert targets. */
|
|
69
|
+
export function planConsolidation(entries: readonly MemoryEntry[], operations: readonly OptimizeOperation[], target: OptimizeTarget, persona: string, now: number): { ok: true; changes: OptimizeChange[]; entries: MemoryEntry[] } | OptimizeFailure {
|
|
70
|
+
if (!Array.isArray(operations) || operations.length < 1 || operations.length > MAX_OPTIMIZE_OPERATIONS) {
|
|
71
|
+
return { ok: false, reason: `provide 1..${MAX_OPTIMIZE_OPERATIONS} explicit consolidation operations` };
|
|
72
|
+
}
|
|
73
|
+
const selected = new Set<MemoryEntry>();
|
|
74
|
+
const changes: OptimizeChange[] = [];
|
|
75
|
+
for (const operation of operations) {
|
|
76
|
+
if (!operation || !Array.isArray(operation.sourceIds) || operation.sourceIds.length < 1 || operation.sourceIds.length > MAX_OPTIMIZE_SOURCES || operation.sourceIds.some((id: unknown) => !isMemoryId(id))) {
|
|
77
|
+
return { ok: false, reason: `each operation needs 1..${MAX_OPTIMIZE_SOURCES} exact safe source IDs` };
|
|
78
|
+
}
|
|
79
|
+
const before: MemoryEntry[] = [];
|
|
80
|
+
for (const id of operation.sourceIds) {
|
|
81
|
+
const matches = entries.filter((entry) => entry.id === id);
|
|
82
|
+
if (matches.length !== 1) return { ok: false, reason: `source ${id} is missing or ambiguous; no entries changed` };
|
|
83
|
+
const entry = matches[0]!;
|
|
84
|
+
if (selected.has(entry)) return { ok: false, reason: "source IDs overlap within or between operations" };
|
|
85
|
+
if (isExpired(entry, now)) return { ok: false, reason: `source ${id} expired; inspect again` };
|
|
86
|
+
if ((target === "project" || target === "project-long") && entry.persona !== persona) return { ok: false, reason: `source ${id} belongs to a different or unowned persona` };
|
|
87
|
+
if (!isSafeMemoryContent(entry)) return { ok: false, reason: `source ${id} contains unsafe stored content` };
|
|
88
|
+
selected.add(entry); before.push(entry);
|
|
89
|
+
}
|
|
90
|
+
if (before.some((entry) => entry.persona !== before[0]!.persona)) return { ok: false, reason: "consolidation cannot mix persona ownership markers" };
|
|
91
|
+
if (!(MEMORY_KINDS as readonly unknown[]).includes(operation.kind)) {
|
|
92
|
+
return { ok: false, reason: "invalid memory kind for the selected tier" };
|
|
93
|
+
}
|
|
94
|
+
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` };
|
|
95
|
+
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" };
|
|
96
|
+
if (operation.source !== undefined && (typeof operation.source !== "string" || operation.source.length > MAX_MEMORY_SOURCE_CHARS)) return { ok: false, reason: "replacement source exceeds memory bounds" };
|
|
97
|
+
const tags = operation.tags ?? before.flatMap((entry) => entry.tags);
|
|
98
|
+
const after = makeMemory({ term: target === "project" ? "short" : "long", kind: operation.kind, text: operation.text, tags }, now);
|
|
99
|
+
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" };
|
|
100
|
+
const marker = before[0]!.persona;
|
|
101
|
+
if (marker !== undefined) after.persona = marker;
|
|
102
|
+
after.recordedAt = before.reduce((earliest, entry) => Date.parse(entry.recordedAt) < Date.parse(earliest) ? entry.recordedAt : earliest, before[0]!.recordedAt);
|
|
103
|
+
if (target === "project") {
|
|
104
|
+
if (before.some((entry) => entry.expiresAt === undefined)) return { ok: false, reason: "project source lacks expiry" };
|
|
105
|
+
after.expiresAt = before.reduce((earliest, entry) => Date.parse(entry.expiresAt!) < Date.parse(earliest) ? entry.expiresAt! : earliest, before[0]!.expiresAt!);
|
|
106
|
+
}
|
|
107
|
+
const lineage = [...new Set(before.flatMap((entry) => [entry.id, ...(entry.derivedFrom ?? []), ...(entry.supersedes ? [entry.supersedes] : [])]))].filter((id) => id !== after.id);
|
|
108
|
+
if (lineage.length > MAX_MEMORY_DERIVED_IDS) return { ok: false, reason: `consolidation provenance exceeds ${MAX_MEMORY_DERIVED_IDS} IDs; split the operation` };
|
|
109
|
+
if (lineage.length > 0) after.derivedFrom = lineage;
|
|
110
|
+
const origins = [...new Set([...before.flatMap((entry) => entry.source ? [entry.source] : []), ...(operation.source ? [operation.source] : [])])];
|
|
111
|
+
if (origins.length > 0) after.source = origins.join("; ");
|
|
112
|
+
if ((after.source?.length ?? 0) > MAX_MEMORY_SOURCE_CHARS) return { ok: false, reason: "combined source provenance exceeds memory bounds; split the operation" };
|
|
113
|
+
const normalizedAfter = validateMemory(after);
|
|
114
|
+
if (!normalizedAfter) return { ok: false, reason: "replacement metadata exceeds memory schema bounds" };
|
|
115
|
+
if (!isSafeMemoryContent(normalizedAfter)) return { ok: false, reason: "replacement content, tags or source rejected by content scanner" };
|
|
116
|
+
changes.push({ before, after: normalizedAfter });
|
|
117
|
+
}
|
|
118
|
+
const effectiveChanges = changes.filter((change) => change.before.length !== 1 || !samePersistedMemory(change.before[0]!, change.after));
|
|
119
|
+
const effectivelySelected = new Set(effectiveChanges.flatMap((change) => change.before));
|
|
120
|
+
const untouched = entries.filter((entry) => !effectivelySelected.has(entry));
|
|
121
|
+
const replacements = effectiveChanges.map((change) => change.after);
|
|
122
|
+
for (let i = 0; i < replacements.length; i++) {
|
|
123
|
+
const replacement = replacements[i]!;
|
|
124
|
+
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" };
|
|
125
|
+
}
|
|
126
|
+
return { ok: true, changes: effectiveChanges, entries: [...untouched, ...replacements] };
|
|
127
|
+
}
|
package/src/core/retrieval.ts
CHANGED
|
@@ -1,164 +1,164 @@
|
|
|
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
|
-
/** Matched query terms that used a weaker identifier/vowel-accent bridge. */
|
|
25
|
-
normalizedTerms: string[];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function compareStrings(a: string, b: string): number {
|
|
29
|
-
return a < b ? -1 : a > b ? 1 : 0;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
const TOKEN_SEGMENTS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[vV]?\d+(?:\.\d+)+(?:-[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*)?(?:\+[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*)?|[\p{L}\p{N}]+/gu;
|
|
33
|
-
const EAST_ASIAN_START = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
34
|
-
const LATIN = /^\p{Script=Latin}+$/u;
|
|
35
|
-
|
|
36
|
-
function words(value: string): string[] {
|
|
37
|
-
const segments = value.normalize("NFC").match(TOKEN_SEGMENTS) ?? [];
|
|
38
|
-
const result: string[] = [];
|
|
39
|
-
for (const segment of segments) {
|
|
40
|
-
if (!EAST_ASIAN_START.test(segment)) { result.push(segment); continue; }
|
|
41
|
-
const chars = [...segment];
|
|
42
|
-
if (chars.length < 2) { result.push(segment); continue; }
|
|
43
|
-
for (let index = 0; index < chars.length - 1; index++) result.push(`${chars[index]}${chars[index + 1]}`);
|
|
44
|
-
}
|
|
45
|
-
return result;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** Fold vowel diacritics only: consonants such as ñ stay distinct (año must not match ano). */
|
|
49
|
-
function foldVowels(value: string): string {
|
|
50
|
-
if (/^[\x00-\x7f]*$/.test(value)) return value;
|
|
51
|
-
return value.normalize("NFD").replace(/([aeiouy])[\u0300-\u036f]+/g, "$1").normalize("NFC");
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function components(word: string): string[] {
|
|
55
|
-
// Numeric identifiers/hashes/versions are exact atoms, never word-expansion sources.
|
|
56
|
-
if (/\p{N}/u.test(word) || /^[a-f\d]{8,}$/i.test(word)) return [word.toLowerCase()];
|
|
57
|
-
if (/^[\x00-\x7f]*$/.test(word)) {
|
|
58
|
-
return word.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").toLowerCase().split(" ");
|
|
59
|
-
}
|
|
60
|
-
return word.replace(/(\p{Ll})(\p{Lu})/gu, (match, a: string, b: string) => LATIN.test(match) ? `${a} ${b}` : match)
|
|
61
|
-
.replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu, (match, a: string, b: string) => LATIN.test(match) ? `${a} ${b}` : match)
|
|
62
|
-
.split(" ").map((part) => foldVowels(part.toLowerCase()));
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
interface QueryTerm { original: string; components: readonly string[] }
|
|
66
|
-
|
|
67
|
-
function queryTerms(query: string): QueryTerm[] {
|
|
68
|
-
const seen = new Set<string>();
|
|
69
|
-
const result: QueryTerm[] = [];
|
|
70
|
-
for (const word of words(query.slice(0, QUERY_MAX_CHARS))) {
|
|
71
|
-
const term = word.toLowerCase();
|
|
72
|
-
if (STOP_WORDS.has(term) && !NEGATION_AND_EXCEPTION.has(term)) continue;
|
|
73
|
-
if (seen.has(term)) continue;
|
|
74
|
-
seen.add(term);
|
|
75
|
-
result.push({ original: term, components: components(word) });
|
|
76
|
-
}
|
|
77
|
-
return result;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function queryPaths(query: string): string[] {
|
|
81
|
-
const matches = query.slice(0, QUERY_MAX_CHARS).match(/[A-Za-z0-9_.-]+(?:[\\/][A-Za-z0-9_.-]+)+/g) ?? [];
|
|
82
|
-
return [...new Set(matches.map((path) => path.replace(/\\/g, "/").toLowerCase()))];
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function entryPathMatches(entry: RetrievalSource, paths: readonly string[]): string[] {
|
|
86
|
-
if (paths.length === 0) return [];
|
|
87
|
-
const content = `${entry.text} ${(entry.tags ?? []).join(" ")}`.replace(/\\/g, "/").toLowerCase();
|
|
88
|
-
return paths.filter((path) => content.includes(path));
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function vocabulary(value: string): { exact: ReadonlySet<string>; normalized: ReadonlySet<string> } {
|
|
92
|
-
const exact = new Set<string>();
|
|
93
|
-
const normalized = new Set<string>();
|
|
94
|
-
for (const word of new Set(words(value))) {
|
|
95
|
-
// Expand only stored tail words: expanding queries would make partial versions match.
|
|
96
|
-
const tail = word.match(/^[vV]?\d+(?:\.\d+)+[-+](.*)$/u)?.[1];
|
|
97
|
-
// Tail qualifiers do not express negation; ordinary occurrences remain searchable.
|
|
98
|
-
const tailWords = tail?.split(/[-+.]/).filter((part) => /^\p{L}+$/u.test(part))
|
|
99
|
-
.flatMap(words).filter((part) => !NEGATION_AND_EXCEPTION.has(part.toLowerCase())) ?? [];
|
|
100
|
-
for (const token of [word, ...tailWords]) {
|
|
101
|
-
exact.add(token.toLowerCase());
|
|
102
|
-
for (const part of components(token)) normalized.add(part);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
return { exact, normalized };
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function rankItem<T extends RetrievalSource>(entry: T, terms: readonly QueryTerm[], paths: readonly string[]): RetrievalRank<T> {
|
|
109
|
-
if (terms.length === 0) {
|
|
110
|
-
const pathMatches = entryPathMatches(entry, paths);
|
|
111
|
-
return { entry, score: pathMatches.length * 12, textTerms: [], tagTerms: [], pathMatches, normalizedTerms: [] };
|
|
112
|
-
}
|
|
113
|
-
const textWords = vocabulary(entry.text);
|
|
114
|
-
const tagWords = vocabulary((entry.tags ?? []).join(" "));
|
|
115
|
-
const textTerms: string[] = [];
|
|
116
|
-
const tagTerms: string[] = [];
|
|
117
|
-
const normalizedTerms: string[] = [];
|
|
118
|
-
let lexicalScore = 0;
|
|
119
|
-
for (const { original, components: parts } of terms) {
|
|
120
|
-
const negation = NEGATION_AND_EXCEPTION.has(original);
|
|
121
|
-
if (textWords.exact.has(original)) { textTerms.push(original); lexicalScore += negation ? 4 : 3; }
|
|
122
|
-
else if (tagWords.exact.has(original)) { tagTerms.push(original); lexicalScore += negation ? 3 : 2; }
|
|
123
|
-
else if (parts.every((part) => textWords.normalized.has(part))) {
|
|
124
|
-
textTerms.push(original); normalizedTerms.push(original); lexicalScore += 1;
|
|
125
|
-
} else if (parts.every((part) => tagWords.normalized.has(part))) {
|
|
126
|
-
tagTerms.push(original); normalizedTerms.push(original); lexicalScore += 0.75;
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
const pathMatches = entryPathMatches(entry, paths);
|
|
130
|
-
const score = lexicalScore + pathMatches.length * 12;
|
|
131
|
-
return { entry, score, textTerms, tagTerms, pathMatches, normalizedTerms };
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** Rank generic text/tag entries; optional ties are resolved by the supplied domain comparator. */
|
|
135
|
-
export function rankRetrievalEntries<T extends RetrievalSource>(
|
|
136
|
-
entries: readonly T[],
|
|
137
|
-
query: string,
|
|
138
|
-
tieBreak?: (a: T, b: T) => number,
|
|
139
|
-
): RetrievalRank<T>[] {
|
|
140
|
-
const terms = queryTerms(query);
|
|
141
|
-
const paths = queryPaths(query);
|
|
142
|
-
return entries.map((entry) => rankItem(entry, terms, paths)).sort((a, b) => {
|
|
143
|
-
if (a.score !== b.score) return b.score - a.score;
|
|
144
|
-
const tie = tieBreak?.(a.entry, b.entry) ?? 0;
|
|
145
|
-
if (tie !== 0) return tie;
|
|
146
|
-
return compareStrings(a.entry.id ?? "", b.entry.id ?? "");
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function dateTie(a: Pick<MemoryEntry, "lastSeenAt">, b: Pick<MemoryEntry, "lastSeenAt">): number {
|
|
151
|
-
const aTime = Date.parse(a.lastSeenAt);
|
|
152
|
-
const bTime = Date.parse(b.lastSeenAt);
|
|
153
|
-
const aValid = Number.isFinite(aTime) ? aTime : Number.NEGATIVE_INFINITY;
|
|
154
|
-
const bValid = Number.isFinite(bTime) ? bTime : Number.NEGATIVE_INFINITY;
|
|
155
|
-
return bValid - aValid;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Rank durable/working facts for a task or explicit recall. There is no stemming, synonym table,
|
|
160
|
-
* embedding, or learned score: lexical matches and hand-authored tags explain every positive rank.
|
|
161
|
-
*/
|
|
162
|
-
export function rankMemoryEntries(entries: readonly MemoryEntry[], query: string): RetrievalRank<MemoryEntry>[] {
|
|
163
|
-
return rankRetrievalEntries(entries, query, (a, b) => KIND_PRIORITY[a.kind] - KIND_PRIORITY[b.kind] || dateTie(a, b));
|
|
164
|
-
}
|
|
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
|
+
/** Matched query terms that used a weaker identifier/vowel-accent bridge. */
|
|
25
|
+
normalizedTerms: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function compareStrings(a: string, b: string): number {
|
|
29
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const TOKEN_SEGMENTS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[vV]?\d+(?:\.\d+)+(?:-[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*)?(?:\+[\p{L}\p{N}-]+(?:\.[\p{L}\p{N}-]+)*)?|[\p{L}\p{N}]+/gu;
|
|
33
|
+
const EAST_ASIAN_START = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
34
|
+
const LATIN = /^\p{Script=Latin}+$/u;
|
|
35
|
+
|
|
36
|
+
function words(value: string): string[] {
|
|
37
|
+
const segments = value.normalize("NFC").match(TOKEN_SEGMENTS) ?? [];
|
|
38
|
+
const result: string[] = [];
|
|
39
|
+
for (const segment of segments) {
|
|
40
|
+
if (!EAST_ASIAN_START.test(segment)) { result.push(segment); continue; }
|
|
41
|
+
const chars = [...segment];
|
|
42
|
+
if (chars.length < 2) { result.push(segment); continue; }
|
|
43
|
+
for (let index = 0; index < chars.length - 1; index++) result.push(`${chars[index]}${chars[index + 1]}`);
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Fold vowel diacritics only: consonants such as ñ stay distinct (año must not match ano). */
|
|
49
|
+
function foldVowels(value: string): string {
|
|
50
|
+
if (/^[\x00-\x7f]*$/.test(value)) return value;
|
|
51
|
+
return value.normalize("NFD").replace(/([aeiouy])[\u0300-\u036f]+/g, "$1").normalize("NFC");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function components(word: string): string[] {
|
|
55
|
+
// Numeric identifiers/hashes/versions are exact atoms, never word-expansion sources.
|
|
56
|
+
if (/\p{N}/u.test(word) || /^[a-f\d]{8,}$/i.test(word)) return [word.toLowerCase()];
|
|
57
|
+
if (/^[\x00-\x7f]*$/.test(word)) {
|
|
58
|
+
return word.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").toLowerCase().split(" ");
|
|
59
|
+
}
|
|
60
|
+
return word.replace(/(\p{Ll})(\p{Lu})/gu, (match, a: string, b: string) => LATIN.test(match) ? `${a} ${b}` : match)
|
|
61
|
+
.replace(/(\p{Lu})(\p{Lu}\p{Ll})/gu, (match, a: string, b: string) => LATIN.test(match) ? `${a} ${b}` : match)
|
|
62
|
+
.split(" ").map((part) => foldVowels(part.toLowerCase()));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface QueryTerm { original: string; components: readonly string[] }
|
|
66
|
+
|
|
67
|
+
function queryTerms(query: string): QueryTerm[] {
|
|
68
|
+
const seen = new Set<string>();
|
|
69
|
+
const result: QueryTerm[] = [];
|
|
70
|
+
for (const word of words(query.slice(0, QUERY_MAX_CHARS))) {
|
|
71
|
+
const term = word.toLowerCase();
|
|
72
|
+
if (STOP_WORDS.has(term) && !NEGATION_AND_EXCEPTION.has(term)) continue;
|
|
73
|
+
if (seen.has(term)) continue;
|
|
74
|
+
seen.add(term);
|
|
75
|
+
result.push({ original: term, components: components(word) });
|
|
76
|
+
}
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function queryPaths(query: string): string[] {
|
|
81
|
+
const matches = query.slice(0, QUERY_MAX_CHARS).match(/[A-Za-z0-9_.-]+(?:[\\/][A-Za-z0-9_.-]+)+/g) ?? [];
|
|
82
|
+
return [...new Set(matches.map((path) => path.replace(/\\/g, "/").toLowerCase()))];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function entryPathMatches(entry: RetrievalSource, paths: readonly string[]): string[] {
|
|
86
|
+
if (paths.length === 0) return [];
|
|
87
|
+
const content = `${entry.text} ${(entry.tags ?? []).join(" ")}`.replace(/\\/g, "/").toLowerCase();
|
|
88
|
+
return paths.filter((path) => content.includes(path));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function vocabulary(value: string): { exact: ReadonlySet<string>; normalized: ReadonlySet<string> } {
|
|
92
|
+
const exact = new Set<string>();
|
|
93
|
+
const normalized = new Set<string>();
|
|
94
|
+
for (const word of new Set(words(value))) {
|
|
95
|
+
// Expand only stored tail words: expanding queries would make partial versions match.
|
|
96
|
+
const tail = word.match(/^[vV]?\d+(?:\.\d+)+[-+](.*)$/u)?.[1];
|
|
97
|
+
// Tail qualifiers do not express negation; ordinary occurrences remain searchable.
|
|
98
|
+
const tailWords = tail?.split(/[-+.]/).filter((part) => /^\p{L}+$/u.test(part))
|
|
99
|
+
.flatMap(words).filter((part) => !NEGATION_AND_EXCEPTION.has(part.toLowerCase())) ?? [];
|
|
100
|
+
for (const token of [word, ...tailWords]) {
|
|
101
|
+
exact.add(token.toLowerCase());
|
|
102
|
+
for (const part of components(token)) normalized.add(part);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { exact, normalized };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function rankItem<T extends RetrievalSource>(entry: T, terms: readonly QueryTerm[], paths: readonly string[]): RetrievalRank<T> {
|
|
109
|
+
if (terms.length === 0) {
|
|
110
|
+
const pathMatches = entryPathMatches(entry, paths);
|
|
111
|
+
return { entry, score: pathMatches.length * 12, textTerms: [], tagTerms: [], pathMatches, normalizedTerms: [] };
|
|
112
|
+
}
|
|
113
|
+
const textWords = vocabulary(entry.text);
|
|
114
|
+
const tagWords = vocabulary((entry.tags ?? []).join(" "));
|
|
115
|
+
const textTerms: string[] = [];
|
|
116
|
+
const tagTerms: string[] = [];
|
|
117
|
+
const normalizedTerms: string[] = [];
|
|
118
|
+
let lexicalScore = 0;
|
|
119
|
+
for (const { original, components: parts } of terms) {
|
|
120
|
+
const negation = NEGATION_AND_EXCEPTION.has(original);
|
|
121
|
+
if (textWords.exact.has(original)) { textTerms.push(original); lexicalScore += negation ? 4 : 3; }
|
|
122
|
+
else if (tagWords.exact.has(original)) { tagTerms.push(original); lexicalScore += negation ? 3 : 2; }
|
|
123
|
+
else if (parts.every((part) => textWords.normalized.has(part))) {
|
|
124
|
+
textTerms.push(original); normalizedTerms.push(original); lexicalScore += 1;
|
|
125
|
+
} else if (parts.every((part) => tagWords.normalized.has(part))) {
|
|
126
|
+
tagTerms.push(original); normalizedTerms.push(original); lexicalScore += 0.75;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const pathMatches = entryPathMatches(entry, paths);
|
|
130
|
+
const score = lexicalScore + pathMatches.length * 12;
|
|
131
|
+
return { entry, score, textTerms, tagTerms, pathMatches, normalizedTerms };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Rank generic text/tag entries; optional ties are resolved by the supplied domain comparator. */
|
|
135
|
+
export function rankRetrievalEntries<T extends RetrievalSource>(
|
|
136
|
+
entries: readonly T[],
|
|
137
|
+
query: string,
|
|
138
|
+
tieBreak?: (a: T, b: T) => number,
|
|
139
|
+
): RetrievalRank<T>[] {
|
|
140
|
+
const terms = queryTerms(query);
|
|
141
|
+
const paths = queryPaths(query);
|
|
142
|
+
return entries.map((entry) => rankItem(entry, terms, paths)).sort((a, b) => {
|
|
143
|
+
if (a.score !== b.score) return b.score - a.score;
|
|
144
|
+
const tie = tieBreak?.(a.entry, b.entry) ?? 0;
|
|
145
|
+
if (tie !== 0) return tie;
|
|
146
|
+
return compareStrings(a.entry.id ?? "", b.entry.id ?? "");
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function dateTie(a: Pick<MemoryEntry, "lastSeenAt">, b: Pick<MemoryEntry, "lastSeenAt">): number {
|
|
151
|
+
const aTime = Date.parse(a.lastSeenAt);
|
|
152
|
+
const bTime = Date.parse(b.lastSeenAt);
|
|
153
|
+
const aValid = Number.isFinite(aTime) ? aTime : Number.NEGATIVE_INFINITY;
|
|
154
|
+
const bValid = Number.isFinite(bTime) ? bTime : Number.NEGATIVE_INFINITY;
|
|
155
|
+
return bValid - aValid;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Rank durable/working facts for a task or explicit recall. There is no stemming, synonym table,
|
|
160
|
+
* embedding, or learned score: lexical matches and hand-authored tags explain every positive rank.
|
|
161
|
+
*/
|
|
162
|
+
export function rankMemoryEntries(entries: readonly MemoryEntry[], query: string): RetrievalRank<MemoryEntry>[] {
|
|
163
|
+
return rankRetrievalEntries(entries, query, (a, b) => KIND_PRIORITY[a.kind] - KIND_PRIORITY[b.kind] || dateTie(a, b));
|
|
164
|
+
}
|