@aeondave/pi-persona-mind 0.9.0 → 0.9.2
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 +4 -0
- package/CHANGELOG.md +28 -0
- package/README.md +59 -55
- package/docs/DESIGN.md +25 -3
- package/package.json +3 -3
- package/src/core/auto-optimize.ts +4 -4
- package/src/core/capture.ts +10 -2
- package/src/core/memory-inspector.ts +149 -149
- package/src/core/memory-read.ts +3 -3
- package/src/core/memory.ts +6 -0
- package/src/core/optimize-history.ts +3 -3
- package/src/core/optimize-service.ts +4 -4
- package/src/core/optimize.ts +3 -9
- package/src/core/service.ts +8 -6
- package/src/core/store.ts +3 -1
- package/src/extension/inspector-data.ts +69 -69
- package/src/index.ts +11 -4
- package/src/ui/inspector-frame.ts +44 -0
- package/src/ui/memory-inspector.ts +91 -61
|
@@ -1,149 +1,149 @@
|
|
|
1
|
-
import type { MemoryEntry } from "./memory.ts";
|
|
2
|
-
import { replaySessionNotes, SESSION_NOTE_ENTRY_TYPE } from "./session-memory.ts";
|
|
3
|
-
|
|
4
|
-
export const MAX_INSPECTOR_BRANCH_ENTRIES = 2_000;
|
|
5
|
-
export const INSPECTOR_PAGE_SIZE = 40;
|
|
6
|
-
export const MAX_INSPECTOR_MESSAGE_CHARS = 32_000;
|
|
7
|
-
|
|
8
|
-
export interface InspectorTimelineItem { id: string; title: string; body: string; timestamp: string; source?: { title: string; body: string } }
|
|
9
|
-
export interface InspectorTimelinePage { items: InspectorTimelineItem[]; total: number; offset: number; nextOffset?: number; omittedOlder: number; notice: string }
|
|
10
|
-
export interface InspectorTimelineOptions { query: string; offset: number }
|
|
11
|
-
|
|
12
|
-
function record(value: unknown): Record<string, unknown> | undefined {
|
|
13
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
14
|
-
}
|
|
15
|
-
function clipped(text: string, max = MAX_INSPECTOR_MESSAGE_CHARS): string {
|
|
16
|
-
const marker = "… [clipped at 32000 chars]";
|
|
17
|
-
if (text.length <= max) return text;
|
|
18
|
-
const cap = Math.max(0, max - marker.length);
|
|
19
|
-
return `${text.slice(0, cap)}${marker}`;
|
|
20
|
-
}
|
|
21
|
-
function visibleText(content: unknown, max = MAX_INSPECTOR_MESSAGE_CHARS): string {
|
|
22
|
-
if (typeof content === "string") return clipped(content, max);
|
|
23
|
-
if (!Array.isArray(content)) return "";
|
|
24
|
-
const parts = content.flatMap((part) => {
|
|
25
|
-
const item = record(part);
|
|
26
|
-
return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
|
|
27
|
-
});
|
|
28
|
-
return clipped(parts.join("\n"), max);
|
|
29
|
-
}
|
|
30
|
-
function callParams(call: unknown): Record<string, unknown> | undefined {
|
|
31
|
-
const item = record(call);
|
|
32
|
-
if (!item) return undefined;
|
|
33
|
-
const args = item.arguments ?? item.params;
|
|
34
|
-
return record(args);
|
|
35
|
-
}
|
|
36
|
-
function normalizedTags(value: unknown): string[] | undefined {
|
|
37
|
-
if (value === undefined) return [];
|
|
38
|
-
if (!Array.isArray(value) || !value.every((tag) => typeof tag === "string")) return undefined;
|
|
39
|
-
return [...new Set(value.map((tag) => tag.trim().toLowerCase()).filter(Boolean))].sort();
|
|
40
|
-
}
|
|
41
|
-
export interface InspectorRecordingOwner { persona: string; projectRoot: string }
|
|
42
|
-
export function findMemoryRecordingSource(memory: MemoryEntry, branch: readonly unknown[], target: "project" | "project-long" | "persona" | "shared", owner: InspectorRecordingOwner): InspectorTimelineItem["source"] {
|
|
43
|
-
for (let index = 0; index < branch.length; index++) {
|
|
44
|
-
const raw = record(branch[index]);
|
|
45
|
-
const message = record(raw?.message);
|
|
46
|
-
if (raw?.type !== "message" || message?.role !== "assistant") continue;
|
|
47
|
-
const calls = Array.isArray(message.toolCalls) ? message.toolCalls : Array.isArray(message.content) ? message.content.filter((part) => record(part)?.type === "toolCall") : [];
|
|
48
|
-
for (const rawCall of calls) {
|
|
49
|
-
const call = record(rawCall);
|
|
50
|
-
const params = callParams(rawCall);
|
|
51
|
-
if (!call || call.name !== "memory" || typeof call.id !== "string" || !params || params.action !== "remember" || params.term === "session") continue;
|
|
52
|
-
const expectedTerm = target === "project" ? "short" : "long";
|
|
53
|
-
const scope = target === "project-long" ? "project" : target;
|
|
54
|
-
if (params.term !== expectedTerm || params.scope !== undefined && params.scope !== scope || (expectedTerm === "long" && params.scope !== scope) || params.kind !== memory.kind || typeof params.text !== "string" || params.text.trim() !== memory.text || JSON.stringify(normalizedTags(params.tags)) !== JSON.stringify(memory.tags)) continue;
|
|
55
|
-
for (let resultIndex = index + 1; resultIndex < branch.length; resultIndex++) {
|
|
56
|
-
const resultRaw = record(branch[resultIndex]);
|
|
57
|
-
const result = record(resultRaw?.message);
|
|
58
|
-
if (result?.role !== "toolResult" || result.toolCallId !== call.id || result.toolName !== "memory") continue;
|
|
59
|
-
if (result.isError !== false) break;
|
|
60
|
-
const output = visibleText(result.content);
|
|
61
|
-
const resultDetails = record(result.details);
|
|
62
|
-
const recording = record(resultDetails?.recording);
|
|
63
|
-
const exactRecording = resultDetails?.ok === true && recording?.version === 1 && recording.target === target && recording.persona === owner.persona && (target === "project" || target === "project-long" ? recording.projectRoot === owner.projectRoot : true);
|
|
64
|
-
const expectedReceipt = `Remembered ${memory.id} — ${expectedTerm}-term ${memory.kind} in ${scope} scope.`;
|
|
65
|
-
if (exactRecording && output.trim().startsWith(expectedReceipt)) {
|
|
66
|
-
const callText = JSON.stringify({ tool: "memory", toolCallId: call.id, action: params.action, term: params.term, scope, kind: params.kind, text: params.text, tags: params.tags ?? [] });
|
|
67
|
-
const recordingText = JSON.stringify(recording);
|
|
68
|
-
return { title: "Recording context (not truth evidence)", body: `Active branch assistant entry ${String(raw.id)}; matching memory toolCall ${call.id}; successful toolResult entry ${String(resultRaw?.id)}. Recording call summary (selected fields): ${clipped(callText)}. Matched native result recording metadata: ${clipped(recordingText)}. Exact successful result text: ${clipped(output)} This is recording context, not proof of factual truth.` };
|
|
69
|
-
}
|
|
70
|
-
break;
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return undefined;
|
|
75
|
-
}
|
|
76
|
-
export function findSessionNoteRecordingSource(note: { id: string; kind: string; text: string; recordedAt: string; originSessionId: string; source?: string }, branch: readonly unknown[], noteHistory: readonly unknown[]): InspectorTimelineItem["source"] {
|
|
77
|
-
const examined = branch.slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
|
|
78
|
-
const events = examined.flatMap((raw) => {
|
|
79
|
-
const entry = record(raw);
|
|
80
|
-
return entry?.type === "custom" && entry.customType === SESSION_NOTE_ENTRY_TYPE ? [entry.data] : [];
|
|
81
|
-
});
|
|
82
|
-
const replay = replaySessionNotes(events, noteHistory);
|
|
83
|
-
if (replay.error || !replay.notes.some((current) => current.id === note.id && current.kind === note.kind && current.text === note.text && current.recordedAt === note.recordedAt && current.originSessionId === note.originSessionId && current.source === note.source)) return undefined;
|
|
84
|
-
for (let index = examined.length - 1; index >= 0; index--) {
|
|
85
|
-
const entry = record(examined[index]);
|
|
86
|
-
if (entry?.type !== "custom" || entry.customType !== SESSION_NOTE_ENTRY_TYPE) continue;
|
|
87
|
-
const event = record(entry.data);
|
|
88
|
-
const saved = record(event?.note);
|
|
89
|
-
if (event?.version === 1 && event.op === "save" && saved?.id === note.id && saved.kind === note.kind && saved.text === note.text && saved.recordedAt === note.recordedAt && saved.originSessionId === note.originSessionId && saved.source === note.source) {
|
|
90
|
-
return { title: "Validated active-branch save event", body: `Native custom entry ${String(entry.id)} (${SESSION_NOTE_ENTRY_TYPE}), event save, note id ${note.id}. Exact validated saved text: ${clipped(note.text)}${note.source === undefined ? "" : `; literal source metadata: ${clipped(note.source)}`}. Recording context only, not proof of factual truth.` };
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return undefined;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
export function buildInspectorTimeline(branchInput: readonly unknown[], noteHistory: readonly unknown[], options: InspectorTimelineOptions): InspectorTimelinePage {
|
|
97
|
-
const examined = branchInput.slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
|
|
98
|
-
const omittedOlder = Math.max(0, branchInput.length - examined.length);
|
|
99
|
-
const noteData: unknown[] = [];
|
|
100
|
-
for (const raw of examined) {
|
|
101
|
-
const entry = record(raw);
|
|
102
|
-
if (entry?.type === "custom" && entry.customType === SESSION_NOTE_ENTRY_TYPE) noteData.push(entry.data);
|
|
103
|
-
}
|
|
104
|
-
const replay = replaySessionNotes(noteData, noteHistory);
|
|
105
|
-
const items: InspectorTimelineItem[] = [];
|
|
106
|
-
const itemOrders = new Map<InspectorTimelineItem, number>();
|
|
107
|
-
const addItem = (item: InspectorTimelineItem, order: number): void => { items.push(item); itemOrders.set(item, order); };
|
|
108
|
-
for (let index = 0; index < examined.length; index++) {
|
|
109
|
-
const raw = record(examined[index]);
|
|
110
|
-
if (!raw || typeof raw.id !== "string" || typeof raw.timestamp !== "string") continue;
|
|
111
|
-
if (raw.type === "message") {
|
|
112
|
-
const message = record(raw.message);
|
|
113
|
-
if (!message || (message.role !== "user" && message.role !== "assistant")) continue;
|
|
114
|
-
const body = visibleText(message.content);
|
|
115
|
-
if (!body || !Number.isFinite(Date.parse(raw.timestamp))) continue;
|
|
116
|
-
const role = message.role === "user" ? "User" : "Assistant";
|
|
117
|
-
const preview = body.replace(/\s+/g, " ").trim();
|
|
118
|
-
const shortPreview = preview.length > 120 ? `${preview.slice(0, 119)}…` : preview;
|
|
119
|
-
const metadata = `timestamp: ${raw.timestamp}\nrole: ${role.toLowerCase()}\nentry id: ${raw.id}`;
|
|
120
|
-
const detail = visibleText(message.content, Math.max(0, MAX_INSPECTOR_MESSAGE_CHARS - metadata.length - 2));
|
|
121
|
-
addItem({ id: raw.id, title: `${raw.timestamp} · ${role} · ${shortPreview}`, body: `${metadata}\n\n${detail}`, timestamp: raw.timestamp }, index);
|
|
122
|
-
} else if (raw.type === "custom" && raw.customType === SESSION_NOTE_ENTRY_TYPE && !replay.error) {
|
|
123
|
-
const data = record(raw.data);
|
|
124
|
-
if (!data || data.version !== 1) continue;
|
|
125
|
-
if (data.op === "save") {
|
|
126
|
-
const note = record(data.note);
|
|
127
|
-
if (!note || typeof note.id !== "string" || typeof note.text !== "string") continue;
|
|
128
|
-
const validated = replay.notes.find((active) => active.id === note.id &&
|
|
129
|
-
active.kind === note.kind && active.text === note.text && active.recordedAt === note.recordedAt &&
|
|
130
|
-
active.originSessionId === note.originSessionId && active.source === note.source);
|
|
131
|
-
const source = validated ? findSessionNoteRecordingSource(validated, examined, noteHistory) : undefined;
|
|
132
|
-
if (!Number.isFinite(Date.parse(raw.timestamp))) continue;
|
|
133
|
-
const noteBody = [`timestamp: ${raw.timestamp}`, "role: session note", `entry id: ${raw.id}`, `note id: ${note.id}`, `kind: ${String(note.kind)}`, `recorded: ${String(note.recordedAt)}`, `origin session id: ${String(note.originSessionId)}`, `text: ${clipped(note.text)}`].join("\n");
|
|
134
|
-
const preview = note.text.replace(/\s+/g, " ").trim();
|
|
135
|
-
const shortPreview = preview.length > 120 ? `${preview.slice(0, 119)}…` : preview;
|
|
136
|
-
addItem({ id: raw.id, title: `${raw.timestamp} · Session note saved · ${shortPreview}`, body: `${noteBody}${source ? "" : "\nNo resolvable recording in this active-branch window."}`, timestamp: raw.timestamp, ...(source ? { source } : {}) }, index);
|
|
137
|
-
} else if (data.op === "forget" && typeof data.id === "string") {
|
|
138
|
-
if (!Number.isFinite(Date.parse(raw.timestamp))) continue;
|
|
139
|
-
addItem({ id: raw.id, title: `${raw.timestamp} · Session note forgotten · ${data.id}`, body: `timestamp: ${raw.timestamp}\nrole: session note tombstone\nentry id: ${raw.id}\nnote id: ${data.id}\nEarlier transcript bytes remain.`, timestamp: raw.timestamp }, index);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
const sorted = items.sort((a, b) => itemOrders.get(b)! - itemOrders.get(a)!);
|
|
144
|
-
const query = options.query.trim().toLowerCase();
|
|
145
|
-
const matched = sorted.filter((item) => !query || `${item.title} ${item.body} ${item.source?.title ?? ""} ${item.source?.body ?? ""}`.toLowerCase().includes(query));
|
|
146
|
-
const offset = Number.isSafeInteger(options.offset) && options.offset >= 0 ? options.offset : 0;
|
|
147
|
-
const page = matched.slice(offset, offset + INSPECTOR_PAGE_SIZE);
|
|
148
|
-
return { items: page, total: matched.length, offset, ...(offset + page.length < matched.length ? { nextOffset: offset + page.length } : {}), omittedOlder, notice: `Timeline and recording-source lookup cover at most the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} native active-branch entries; ${omittedOlder} older native entries omitted. Counts and search matches apply only to this bounded window and searchable text excerpts are clipped to ${MAX_INSPECTOR_MESSAGE_CHARS} characters per message. Native branch order is used; timestamps are display-only. Source links are recording context, not proof of truth.` };
|
|
149
|
-
}
|
|
1
|
+
import type { MemoryEntry } from "./memory.ts";
|
|
2
|
+
import { replaySessionNotes, SESSION_NOTE_ENTRY_TYPE } from "./session-memory.ts";
|
|
3
|
+
|
|
4
|
+
export const MAX_INSPECTOR_BRANCH_ENTRIES = 2_000;
|
|
5
|
+
export const INSPECTOR_PAGE_SIZE = 40;
|
|
6
|
+
export const MAX_INSPECTOR_MESSAGE_CHARS = 32_000;
|
|
7
|
+
|
|
8
|
+
export interface InspectorTimelineItem { id: string; title: string; body: string; timestamp: string; source?: { title: string; body: string } }
|
|
9
|
+
export interface InspectorTimelinePage { items: InspectorTimelineItem[]; total: number; offset: number; nextOffset?: number; omittedOlder: number; notice: string }
|
|
10
|
+
export interface InspectorTimelineOptions { query: string; offset: number }
|
|
11
|
+
|
|
12
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
13
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
14
|
+
}
|
|
15
|
+
function clipped(text: string, max = MAX_INSPECTOR_MESSAGE_CHARS): string {
|
|
16
|
+
const marker = "… [clipped at 32000 chars]";
|
|
17
|
+
if (text.length <= max) return text;
|
|
18
|
+
const cap = Math.max(0, max - marker.length);
|
|
19
|
+
return `${text.slice(0, cap)}${marker}`;
|
|
20
|
+
}
|
|
21
|
+
function visibleText(content: unknown, max = MAX_INSPECTOR_MESSAGE_CHARS): string {
|
|
22
|
+
if (typeof content === "string") return clipped(content, max);
|
|
23
|
+
if (!Array.isArray(content)) return "";
|
|
24
|
+
const parts = content.flatMap((part) => {
|
|
25
|
+
const item = record(part);
|
|
26
|
+
return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
|
|
27
|
+
});
|
|
28
|
+
return clipped(parts.join("\n"), max);
|
|
29
|
+
}
|
|
30
|
+
function callParams(call: unknown): Record<string, unknown> | undefined {
|
|
31
|
+
const item = record(call);
|
|
32
|
+
if (!item) return undefined;
|
|
33
|
+
const args = item.arguments ?? item.params;
|
|
34
|
+
return record(args);
|
|
35
|
+
}
|
|
36
|
+
function normalizedTags(value: unknown): string[] | undefined {
|
|
37
|
+
if (value === undefined) return [];
|
|
38
|
+
if (!Array.isArray(value) || !value.every((tag) => typeof tag === "string")) return undefined;
|
|
39
|
+
return [...new Set(value.map((tag) => tag.trim().toLowerCase()).filter(Boolean))].sort();
|
|
40
|
+
}
|
|
41
|
+
export interface InspectorRecordingOwner { persona: string; projectRoot: string }
|
|
42
|
+
export function findMemoryRecordingSource(memory: MemoryEntry, branch: readonly unknown[], target: "project" | "project-long" | "persona" | "shared", owner: InspectorRecordingOwner): InspectorTimelineItem["source"] {
|
|
43
|
+
for (let index = 0; index < branch.length; index++) {
|
|
44
|
+
const raw = record(branch[index]);
|
|
45
|
+
const message = record(raw?.message);
|
|
46
|
+
if (raw?.type !== "message" || message?.role !== "assistant") continue;
|
|
47
|
+
const calls = Array.isArray(message.toolCalls) ? message.toolCalls : Array.isArray(message.content) ? message.content.filter((part) => record(part)?.type === "toolCall") : [];
|
|
48
|
+
for (const rawCall of calls) {
|
|
49
|
+
const call = record(rawCall);
|
|
50
|
+
const params = callParams(rawCall);
|
|
51
|
+
if (!call || call.name !== "memory" || typeof call.id !== "string" || !params || params.action !== "remember" || params.term === "session") continue;
|
|
52
|
+
const expectedTerm = target === "project" ? "short" : "long";
|
|
53
|
+
const scope = target === "project-long" ? "project" : target;
|
|
54
|
+
if (params.term !== expectedTerm || params.scope !== undefined && params.scope !== scope || (expectedTerm === "long" && params.scope !== scope) || params.kind !== memory.kind || typeof params.text !== "string" || params.text.trim() !== memory.text || JSON.stringify(normalizedTags(params.tags)) !== JSON.stringify(memory.tags)) continue;
|
|
55
|
+
for (let resultIndex = index + 1; resultIndex < branch.length; resultIndex++) {
|
|
56
|
+
const resultRaw = record(branch[resultIndex]);
|
|
57
|
+
const result = record(resultRaw?.message);
|
|
58
|
+
if (result?.role !== "toolResult" || result.toolCallId !== call.id || result.toolName !== "memory") continue;
|
|
59
|
+
if (result.isError !== false) break;
|
|
60
|
+
const output = visibleText(result.content);
|
|
61
|
+
const resultDetails = record(result.details);
|
|
62
|
+
const recording = record(resultDetails?.recording);
|
|
63
|
+
const exactRecording = resultDetails?.ok === true && recording?.version === 1 && recording.target === target && recording.persona === owner.persona && (target === "project" || target === "project-long" ? recording.projectRoot === owner.projectRoot : true);
|
|
64
|
+
const expectedReceipt = `Remembered ${memory.id} — ${expectedTerm}-term ${memory.kind} in ${scope} scope.`;
|
|
65
|
+
if (exactRecording && output.trim().startsWith(expectedReceipt)) {
|
|
66
|
+
const callText = JSON.stringify({ tool: "memory", toolCallId: call.id, action: params.action, term: params.term, scope, kind: params.kind, text: params.text, tags: params.tags ?? [] });
|
|
67
|
+
const recordingText = JSON.stringify(recording);
|
|
68
|
+
return { title: "Recording context (not truth evidence)", body: `Active branch assistant entry ${String(raw.id)}; matching memory toolCall ${call.id}; successful toolResult entry ${String(resultRaw?.id)}. Recording call summary (selected fields): ${clipped(callText)}. Matched native result recording metadata: ${clipped(recordingText)}. Exact successful result text: ${clipped(output)} This is recording context, not proof of factual truth.` };
|
|
69
|
+
}
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
export function findSessionNoteRecordingSource(note: { id: string; kind: string; text: string; recordedAt: string; originSessionId: string; source?: string }, branch: readonly unknown[], noteHistory: readonly unknown[]): InspectorTimelineItem["source"] {
|
|
77
|
+
const examined = branch.slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
|
|
78
|
+
const events = examined.flatMap((raw) => {
|
|
79
|
+
const entry = record(raw);
|
|
80
|
+
return entry?.type === "custom" && entry.customType === SESSION_NOTE_ENTRY_TYPE ? [entry.data] : [];
|
|
81
|
+
});
|
|
82
|
+
const replay = replaySessionNotes(events, noteHistory);
|
|
83
|
+
if (replay.error || !replay.notes.some((current) => current.id === note.id && current.kind === note.kind && current.text === note.text && current.recordedAt === note.recordedAt && current.originSessionId === note.originSessionId && current.source === note.source)) return undefined;
|
|
84
|
+
for (let index = examined.length - 1; index >= 0; index--) {
|
|
85
|
+
const entry = record(examined[index]);
|
|
86
|
+
if (entry?.type !== "custom" || entry.customType !== SESSION_NOTE_ENTRY_TYPE) continue;
|
|
87
|
+
const event = record(entry.data);
|
|
88
|
+
const saved = record(event?.note);
|
|
89
|
+
if (event?.version === 1 && event.op === "save" && saved?.id === note.id && saved.kind === note.kind && saved.text === note.text && saved.recordedAt === note.recordedAt && saved.originSessionId === note.originSessionId && saved.source === note.source) {
|
|
90
|
+
return { title: "Validated active-branch save event", body: `Native custom entry ${String(entry.id)} (${SESSION_NOTE_ENTRY_TYPE}), event save, note id ${note.id}. Exact validated saved text: ${clipped(note.text)}${note.source === undefined ? "" : `; literal source metadata: ${clipped(note.source)}`}. Recording context only, not proof of factual truth.` };
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function buildInspectorTimeline(branchInput: readonly unknown[], noteHistory: readonly unknown[], options: InspectorTimelineOptions): InspectorTimelinePage {
|
|
97
|
+
const examined = branchInput.slice(-MAX_INSPECTOR_BRANCH_ENTRIES);
|
|
98
|
+
const omittedOlder = Math.max(0, branchInput.length - examined.length);
|
|
99
|
+
const noteData: unknown[] = [];
|
|
100
|
+
for (const raw of examined) {
|
|
101
|
+
const entry = record(raw);
|
|
102
|
+
if (entry?.type === "custom" && entry.customType === SESSION_NOTE_ENTRY_TYPE) noteData.push(entry.data);
|
|
103
|
+
}
|
|
104
|
+
const replay = replaySessionNotes(noteData, noteHistory);
|
|
105
|
+
const items: InspectorTimelineItem[] = [];
|
|
106
|
+
const itemOrders = new Map<InspectorTimelineItem, number>();
|
|
107
|
+
const addItem = (item: InspectorTimelineItem, order: number): void => { items.push(item); itemOrders.set(item, order); };
|
|
108
|
+
for (let index = 0; index < examined.length; index++) {
|
|
109
|
+
const raw = record(examined[index]);
|
|
110
|
+
if (!raw || typeof raw.id !== "string" || typeof raw.timestamp !== "string") continue;
|
|
111
|
+
if (raw.type === "message") {
|
|
112
|
+
const message = record(raw.message);
|
|
113
|
+
if (!message || (message.role !== "user" && message.role !== "assistant")) continue;
|
|
114
|
+
const body = visibleText(message.content);
|
|
115
|
+
if (!body || !Number.isFinite(Date.parse(raw.timestamp))) continue;
|
|
116
|
+
const role = message.role === "user" ? "User" : "Assistant";
|
|
117
|
+
const preview = body.replace(/\s+/g, " ").trim();
|
|
118
|
+
const shortPreview = preview.length > 120 ? `${preview.slice(0, 119)}…` : preview;
|
|
119
|
+
const metadata = `timestamp: ${raw.timestamp}\nrole: ${role.toLowerCase()}\nentry id: ${raw.id}`;
|
|
120
|
+
const detail = visibleText(message.content, Math.max(0, MAX_INSPECTOR_MESSAGE_CHARS - metadata.length - 2));
|
|
121
|
+
addItem({ id: raw.id, title: `${raw.timestamp} · ${role} · ${shortPreview}`, body: `${metadata}\n\n${detail}`, timestamp: raw.timestamp }, index);
|
|
122
|
+
} else if (raw.type === "custom" && raw.customType === SESSION_NOTE_ENTRY_TYPE && !replay.error) {
|
|
123
|
+
const data = record(raw.data);
|
|
124
|
+
if (!data || data.version !== 1) continue;
|
|
125
|
+
if (data.op === "save") {
|
|
126
|
+
const note = record(data.note);
|
|
127
|
+
if (!note || typeof note.id !== "string" || typeof note.text !== "string") continue;
|
|
128
|
+
const validated = replay.notes.find((active) => active.id === note.id &&
|
|
129
|
+
active.kind === note.kind && active.text === note.text && active.recordedAt === note.recordedAt &&
|
|
130
|
+
active.originSessionId === note.originSessionId && active.source === note.source);
|
|
131
|
+
const source = validated ? findSessionNoteRecordingSource(validated, examined, noteHistory) : undefined;
|
|
132
|
+
if (!Number.isFinite(Date.parse(raw.timestamp))) continue;
|
|
133
|
+
const noteBody = [`timestamp: ${raw.timestamp}`, "role: session note", `entry id: ${raw.id}`, `note id: ${note.id}`, `kind: ${String(note.kind)}`, `recorded: ${String(note.recordedAt)}`, `origin session id: ${String(note.originSessionId)}`, `text: ${clipped(note.text)}`].join("\n");
|
|
134
|
+
const preview = note.text.replace(/\s+/g, " ").trim();
|
|
135
|
+
const shortPreview = preview.length > 120 ? `${preview.slice(0, 119)}…` : preview;
|
|
136
|
+
addItem({ id: raw.id, title: `${raw.timestamp} · Session note saved · ${shortPreview}`, body: `${noteBody}${source ? "" : "\nNo resolvable recording in this active-branch window."}`, timestamp: raw.timestamp, ...(source ? { source } : {}) }, index);
|
|
137
|
+
} else if (data.op === "forget" && typeof data.id === "string") {
|
|
138
|
+
if (!Number.isFinite(Date.parse(raw.timestamp))) continue;
|
|
139
|
+
addItem({ id: raw.id, title: `${raw.timestamp} · Session note forgotten · ${data.id}`, body: `timestamp: ${raw.timestamp}\nrole: session note tombstone\nentry id: ${raw.id}\nnote id: ${data.id}\nEarlier transcript bytes remain.`, timestamp: raw.timestamp }, index);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const sorted = items.sort((a, b) => itemOrders.get(b)! - itemOrders.get(a)!);
|
|
144
|
+
const query = options.query.trim().toLowerCase();
|
|
145
|
+
const matched = sorted.filter((item) => !query || `${item.title} ${item.body} ${item.source?.title ?? ""} ${item.source?.body ?? ""}`.toLowerCase().includes(query));
|
|
146
|
+
const offset = Number.isSafeInteger(options.offset) && options.offset >= 0 ? options.offset : 0;
|
|
147
|
+
const page = matched.slice(offset, offset + INSPECTOR_PAGE_SIZE);
|
|
148
|
+
return { items: page, total: matched.length, offset, ...(offset + page.length < matched.length ? { nextOffset: offset + page.length } : {}), omittedOlder, notice: `Timeline and recording-source lookup cover at most the newest ${MAX_INSPECTOR_BRANCH_ENTRIES} native active-branch entries; ${omittedOlder} older native entries omitted. Counts and search matches apply only to this bounded window and searchable text excerpts are clipped to ${MAX_INSPECTOR_MESSAGE_CHARS} characters per message. Native branch order is used; timestamps are display-only. Source links are recording context, not proof of truth.` };
|
|
149
|
+
}
|
package/src/core/memory-read.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Explicit full-fact retrieval, separate from clipped, budgeted discovery and injection. */
|
|
2
|
-
import { isExpired, isMemoryId, memoryContentKey, memoryIdMatches, type MemoryEntry } from "./memory.ts";
|
|
3
|
-
import {
|
|
2
|
+
import { isExpired, isMemoryId, isSafeMemoryContent, memoryContentKey, memoryIdMatches, type MemoryEntry } from "./memory.ts";
|
|
3
|
+
import type { OptimizeFailure, OptimizeTarget } from "./optimize.ts";
|
|
4
4
|
import type { JsonStore } from "./store.ts";
|
|
5
5
|
|
|
6
6
|
export type MemoryReadScope = "long" | "short" | "both" | "project" | "persona" | "shared";
|
|
@@ -26,7 +26,7 @@ export async function readMemory(stores: Record<OptimizeTarget, JsonStore<Memory
|
|
|
26
26
|
const matches = snapshots.flatMap(({ target, snapshot }) => snapshot.store.entries.filter((entry) => !isExpired(entry, now) && memoryIdMatches(entry, id)).map((entry) => ({ entry, target })));
|
|
27
27
|
if (matches.length === 0) return { ok: false, reason: "memory not found in the requested active scope" };
|
|
28
28
|
if (new Set(matches.map(({ entry }) => memoryContentKey(entry))).size > 1) return { ok: false, reason: "ambiguous memory ID addresses multiple distinct facts; no fact selected" };
|
|
29
|
-
if (matches.some(({ entry }) => !
|
|
29
|
+
if (matches.some(({ entry }) => !isSafeMemoryContent(entry))) return { ok: false, reason: "memory contains unsafe stored content and was withheld" };
|
|
30
30
|
return { ok: true, entries: matches.slice(0, 8), total: matches.length, withheld: Math.max(0, matches.length - 8) };
|
|
31
31
|
} catch (error) {
|
|
32
32
|
return { ok: false, reason: error instanceof Error ? error.message : "memory read storage failure" };
|
package/src/core/memory.ts
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
import { compatibleContentIds, contentId } from "./ids.ts";
|
|
13
13
|
import { rankMemoryEntries } from "./retrieval.ts";
|
|
14
|
+
import { scanContent } from "./scanner.ts";
|
|
14
15
|
|
|
15
16
|
export const MEMORY_KINDS = ["objective", "invariant", "preference", "convention", "gotcha", "rationale", "note"] as const;
|
|
16
17
|
export type MemoryKind = (typeof MEMORY_KINDS)[number];
|
|
@@ -74,6 +75,11 @@ export interface MemoryEntry {
|
|
|
74
75
|
derivedFrom?: string[];
|
|
75
76
|
}
|
|
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
|
+
|
|
77
83
|
export interface MemoryInput {
|
|
78
84
|
term: MemoryTerm;
|
|
79
85
|
kind: MemoryKind;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
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,
|
|
2
|
+
import { isExpired, isSafeMemoryContent, memoryContentKey, validateMemory, type MemoryEntry } from "./memory.ts";
|
|
3
|
+
import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS, MAX_OPTIMIZE_SOURCES, samePersistedMemory, type OptimizeChange, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
|
|
4
4
|
import { JsonStore, withFileLock } from "./store.ts";
|
|
5
5
|
|
|
6
6
|
export const MAX_OPTIMIZE_HISTORY = 32;
|
|
@@ -84,7 +84,7 @@ export function restoreReceipt(entries: readonly MemoryEntry[], receipt: Optimiz
|
|
|
84
84
|
if (receipt.state === "undone" || receipt.state === "rejected") return { ok: false, reason: "receipt was already undone or its replacement was rejected" };
|
|
85
85
|
const before = receipt.changes.flatMap((change) => change.before);
|
|
86
86
|
const after = receipt.changes.map((change) => change.after);
|
|
87
|
-
if ([...before, ...after].some((entry) => !
|
|
87
|
+
if ([...before, ...after].some((entry) => !isSafeMemoryContent(entry))) return { ok: false, reason: "receipt contains unsafe memory content" };
|
|
88
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
89
|
if ([...before, ...after].some((entry) => isExpired(entry, now))) return { ok: false, reason: "receipt contains expired sources; undo cannot revive expired memory" };
|
|
90
90
|
const selected = new Set<MemoryEntry>();
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/** Session-local staged plans over strict one-file memory snapshots. No model calls or hidden jobs. */
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { isExpired, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
|
|
3
|
+
import { isExpired, isSafeMemoryContent, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
|
|
4
4
|
import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeUndone } from "./optimize-history.ts";
|
|
5
5
|
import {
|
|
6
6
|
isOptimizeTarget, MAX_OPTIMIZE_ENTRIES, MAX_OPTIMIZE_PLANS, OPTIMIZE_PLAN_TTL_MS,
|
|
7
|
-
optimizeCandidates, planConsolidation,
|
|
7
|
+
optimizeCandidates, planConsolidation,
|
|
8
8
|
type OptimizeApplied, type OptimizeFailure, type OptimizeInspection, type OptimizeInspectOptions,
|
|
9
9
|
type OptimizePlan, type OptimizePreviewInput, type OptimizeTarget,
|
|
10
10
|
} from "./optimize.ts";
|
|
@@ -48,7 +48,7 @@ export class MemoryOptimizer {
|
|
|
48
48
|
const snapshot = await this.options.stores[target].inspectStrict();
|
|
49
49
|
const active = snapshot.store.entries.filter((entry) => !isExpired(entry, this.now()));
|
|
50
50
|
const query = options.query?.trim().toLowerCase();
|
|
51
|
-
const eligible = active.filter((entry) =>
|
|
51
|
+
const eligible = active.filter((entry) => isSafeMemoryContent(entry) && (!query || `${entry.text} ${entry.tags.join(" ")}`.toLowerCase().includes(query)));
|
|
52
52
|
const max = options.max === undefined || !Number.isFinite(options.max) ? 20 : Math.max(1, Math.min(MAX_OPTIMIZE_ENTRIES, Math.floor(options.max)));
|
|
53
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
54
|
const nextOffset = offset + entries.length;
|
|
@@ -133,7 +133,7 @@ export class MemoryOptimizer {
|
|
|
133
133
|
try {
|
|
134
134
|
const storePath = this.options.stores[target].filePath;
|
|
135
135
|
const all = (await this.historyStore(target).read()).filter((receipt) => receipt.target === target && receipt.storePath === storePath && receipt.persona === this.options.persona);
|
|
136
|
-
const safe = all.filter((receipt) => receipt.changes.every((change) => [...change.before, change.after].every(
|
|
136
|
+
const safe = all.filter((receipt) => receipt.changes.every((change) => [...change.before, change.after].every(isSafeMemoryContent)));
|
|
137
137
|
const receipts = safe.slice().reverse().slice(0, Math.min(MAX_OPTIMIZE_HISTORY, Math.floor(max)));
|
|
138
138
|
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 };
|
|
139
139
|
} catch (error) { return failure(error); }
|
package/src/core/optimize.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
/** Explicit memory consolidation rules. Similarity discovers candidates; it never authorizes edits. */
|
|
2
2
|
import {
|
|
3
|
-
isExpired, isMemoryId, makeMemory, memoryContentKey, MEMORY_KINDS,
|
|
3
|
+
isExpired, isMemoryId, isSafeMemoryContent, makeMemory, memoryContentKey, MEMORY_KINDS,
|
|
4
4
|
MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_SOURCE_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS, MAX_MEMORY_TEXT_CHARS,
|
|
5
5
|
validateMemory, type MemoryEntry, type MemoryKind,
|
|
6
6
|
} from "./memory.ts";
|
|
7
|
-
import { scanContent } from "./scanner.ts";
|
|
8
7
|
|
|
9
8
|
export type OptimizeTarget = "project" | "project-long" | "persona" | "shared";
|
|
10
9
|
export interface OptimizeOperation { sourceIds: string[]; kind: MemoryKind; text: string; tags?: string[]; source?: string }
|
|
@@ -35,11 +34,6 @@ export function isOptimizeTarget(value: unknown): value is OptimizeTarget {
|
|
|
35
34
|
return value === "project" || value === "project-long" || value === "persona" || value === "shared";
|
|
36
35
|
}
|
|
37
36
|
|
|
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
37
|
function terms(text: string): Set<string> {
|
|
44
38
|
return new Set(text.toLowerCase().match(/[\p{L}\p{N}\p{M}]+/gu) ?? []);
|
|
45
39
|
}
|
|
@@ -90,7 +84,7 @@ export function planConsolidation(entries: readonly MemoryEntry[], operations: r
|
|
|
90
84
|
if (selected.has(entry)) return { ok: false, reason: "source IDs overlap within or between operations" };
|
|
91
85
|
if (isExpired(entry, now)) return { ok: false, reason: `source ${id} expired; inspect again` };
|
|
92
86
|
if ((target === "project" || target === "project-long") && entry.persona !== persona) return { ok: false, reason: `source ${id} belongs to a different or unowned persona` };
|
|
93
|
-
if (!
|
|
87
|
+
if (!isSafeMemoryContent(entry)) return { ok: false, reason: `source ${id} contains unsafe stored content` };
|
|
94
88
|
selected.add(entry); before.push(entry);
|
|
95
89
|
}
|
|
96
90
|
if (before.some((entry) => entry.persona !== before[0]!.persona)) return { ok: false, reason: "consolidation cannot mix persona ownership markers" };
|
|
@@ -118,7 +112,7 @@ export function planConsolidation(entries: readonly MemoryEntry[], operations: r
|
|
|
118
112
|
if ((after.source?.length ?? 0) > MAX_MEMORY_SOURCE_CHARS) return { ok: false, reason: "combined source provenance exceeds memory bounds; split the operation" };
|
|
119
113
|
const normalizedAfter = validateMemory(after);
|
|
120
114
|
if (!normalizedAfter) return { ok: false, reason: "replacement metadata exceeds memory schema bounds" };
|
|
121
|
-
if (!
|
|
115
|
+
if (!isSafeMemoryContent(normalizedAfter)) return { ok: false, reason: "replacement content, tags or source rejected by content scanner" };
|
|
122
116
|
changes.push({ before, after: normalizedAfter });
|
|
123
117
|
}
|
|
124
118
|
const effectiveChanges = changes.filter((change) => change.before.length !== 1 || !samePersistedMemory(change.before[0]!, change.after));
|
package/src/core/service.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { readMemory, memoryTargets, type MemoryReadResult, type MemoryReadScope
|
|
|
18
18
|
import { MemoryOptimizer } from "./optimize-service.ts";
|
|
19
19
|
import { samePersistedMemory } from "./optimize.ts";
|
|
20
20
|
import type { MemoryEntry, MemoryInput, MemoryKind } from "./memory.ts";
|
|
21
|
-
import { clampRecallMax, isExpired, isMemoryId, makeMemory, memoryContentKey, memoryIdMatches, promoteToLong, pruneExpired, recall, sameMemoryContent, supersedeTargets, upsertMemory, validateLongMemory, validateShortMemory, MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_ID_CHARS, MAX_MEMORY_SOURCE_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS, MAX_MEMORY_TEXT_CHARS } from "./memory.ts";
|
|
21
|
+
import { clampRecallMax, isExpired, isMemoryId, isSafeMemoryContent, makeMemory, memoryContentKey, memoryIdMatches, promoteToLong, pruneExpired, recall, sameMemoryContent, supersedeTargets, upsertMemory, validateLongMemory, validateShortMemory, MAX_MEMORY_DERIVED_IDS, MAX_MEMORY_ID_CHARS, MAX_MEMORY_SOURCE_CHARS, MAX_MEMORY_TAGS, MAX_MEMORY_TAG_CHARS, MAX_MEMORY_TEXT_CHARS } from "./memory.ts";
|
|
22
22
|
import { scanContent } from "./scanner.ts";
|
|
23
23
|
import { memoryMutationLockPath, type Scope } from "./scope.ts";
|
|
24
24
|
import { JsonStore, type JsonStoreOptions, withFileLock } from "./store.ts";
|
|
@@ -290,7 +290,7 @@ export class MindService {
|
|
|
290
290
|
// Same contract as `forget`: a handle that addresses more than one fact retires none of
|
|
291
291
|
// them, and the caller is told so rather than silently getting a partial write. Read under
|
|
292
292
|
// the mutation lock every writer holds, so the answer cannot go stale before the update.
|
|
293
|
-
// The pool is the one `forget` resolves against —
|
|
293
|
+
// The pool is the one `forget` resolves against — all durable/working stores, not just the one
|
|
294
294
|
// being written: a v1 comma-joined id can name a durable fact in `shared` and another in
|
|
295
295
|
// `ltm`, and a per-store check would still let the write destroy whichever copy sits in the
|
|
296
296
|
// target tier while the delete path refuses the identical handle.
|
|
@@ -323,6 +323,7 @@ export class MindService {
|
|
|
323
323
|
if (matches.length !== 1) return { ok: false, reason: "source missing or ambiguous" } as const;
|
|
324
324
|
const found = matches[0]!;
|
|
325
325
|
if (isExpired(found, this.now()) || found.persona !== this.scope.persona) return { ok: false, reason: "source expired or belongs to another persona" } as const;
|
|
326
|
+
if (!isSafeMemoryContent(found)) return { ok: false, reason: "source contains unsafe memory content; promotion refused" } as const;
|
|
326
327
|
const promoted = promoteToLong(found, this.now());
|
|
327
328
|
if (target === "project") promoted.persona = this.scope.persona;
|
|
328
329
|
const destination = target === "project" ? this.projectLtm : target === "shared" ? this.shared : this.ltm;
|
|
@@ -562,15 +563,16 @@ export class MindService {
|
|
|
562
563
|
return { stmRemoved, backlogRemoved };
|
|
563
564
|
}
|
|
564
565
|
|
|
565
|
-
/**
|
|
566
|
-
async acknowledgeDue(
|
|
567
|
-
|
|
566
|
+
/** Acknowledge only the shown deadline; a concurrent renewal must keep its new alarm. */
|
|
567
|
+
async acknowledgeDue(shown: readonly { id: string; dueAtEpochMs: number }[]): Promise<number> {
|
|
568
|
+
if (shown.length === 0) return 0;
|
|
569
|
+
const wanted = new Map(shown.map((item) => [item.id, item.dueAtEpochMs]));
|
|
568
570
|
let cleared = 0;
|
|
569
571
|
try {
|
|
570
572
|
await this.backlog.update((es) =>
|
|
571
573
|
es.map((e) => {
|
|
572
574
|
if (e.dueAtEpochMs === undefined) return e;
|
|
573
|
-
if (wanted
|
|
575
|
+
if (wanted.get(e.id) !== e.dueAtEpochMs) return e;
|
|
574
576
|
if (e.state !== "open" && e.state !== "taken") return e;
|
|
575
577
|
cleared++;
|
|
576
578
|
const next = { ...e };
|
package/src/core/store.ts
CHANGED
|
@@ -788,7 +788,9 @@ export class JsonStore<E> {
|
|
|
788
788
|
if (lockToken === undefined) {
|
|
789
789
|
const peek = await this.tryBak();
|
|
790
790
|
if (!peek) return null;
|
|
791
|
-
|
|
791
|
+
// Missing was only an optimistic observation: a writer may repair and commit
|
|
792
|
+
// while this reader waits. Re-read live state under its lock before restoring.
|
|
793
|
+
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
792
794
|
}
|
|
793
795
|
const bak = await this.tryBak();
|
|
794
796
|
if (!bak) return null;
|