@aeondave/pi-persona-mind 0.8.7 → 0.9.1

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.
@@ -0,0 +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,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 { safeOptimizeMemory, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
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 }) => !safeOptimizeMemory(entry))) return { ok: false, reason: "memory contains unsafe stored content and was withheld" };
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" };
@@ -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, safeOptimizeMemory, type OptimizeChange, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
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) => !safeOptimizeMemory(entry))) return { ok: false, reason: "receipt contains unsafe memory content" };
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, safeOptimizeMemory,
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) => safeOptimizeMemory(entry) && (!query || `${entry.text} ${entry.tags.join(" ")}`.toLowerCase().includes(query)));
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;
@@ -58,10 +58,12 @@ export class MemoryOptimizer {
58
58
  }
59
59
 
60
60
  async preview(input: OptimizePreviewInput): Promise<OptimizePlan | OptimizeFailure> {
61
+ const generation = this.generation;
61
62
  const target = input.target ?? "project";
62
63
  if (!isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
63
64
  try {
64
65
  const snapshot = await this.options.stores[target].inspectStrict();
66
+ if (this.generation !== generation) return { ok: false, reason: "memory owner changed; preview invalidated before staging" };
65
67
  if (snapshot.fingerprint !== input.fingerprint) return { ok: false, reason: "memory store changed since inspection; inspect again" };
66
68
  const now = this.now();
67
69
  const result = planConsolidation(snapshot.store.entries, input.operations, target, this.options.persona, now);
@@ -80,7 +82,8 @@ export class MemoryOptimizer {
80
82
  return stored ? structuredClone(stored.plan) : { ok: false, reason: "plan not found or expired; inspect and stage again" };
81
83
  }
82
84
 
83
- async apply(planId: string): Promise<OptimizeApplied | OptimizeFailure> {
85
+ /** Parent-only synchronous evidence checks run again under the store's CAS lock. */
86
+ async apply(planId: string, assertEvidenceFresh?: () => void): Promise<OptimizeApplied | OptimizeFailure> {
84
87
  this.expirePlans();
85
88
  const staged = this.plans.get(planId);
86
89
  if (!staged) return { ok: false, reason: "plan not found or expired; inspect and stage again" };
@@ -93,6 +96,7 @@ export class MemoryOptimizer {
93
96
  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
97
  };
95
98
  assertCurrent();
99
+ assertEvidenceFresh?.();
96
100
  const store = this.options.stores[staged.plan.target];
97
101
  if ((await store.inspectStrict()).fingerprint !== staged.plan.fingerprint) throw new StoreConflictError();
98
102
  const history = this.historyStore(staged.plan.target);
@@ -104,7 +108,7 @@ export class MemoryOptimizer {
104
108
  let callbackRejected = false;
105
109
  try {
106
110
  await store.compareAndUpdate(staged.plan.fingerprint, () => {
107
- try { assertCurrent(); return structuredClone(staged.next); }
111
+ try { assertCurrent(); assertEvidenceFresh?.(); return structuredClone(staged.next); }
108
112
  catch (error) { callbackRejected = true; throw error; }
109
113
  });
110
114
  } catch (error) {
@@ -129,7 +133,7 @@ export class MemoryOptimizer {
129
133
  try {
130
134
  const storePath = this.options.stores[target].filePath;
131
135
  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)));
136
+ const safe = all.filter((receipt) => receipt.changes.every((change) => [...change.before, change.after].every(isSafeMemoryContent)));
133
137
  const receipts = safe.slice().reverse().slice(0, Math.min(MAX_OPTIMIZE_HISTORY, Math.floor(max)));
134
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 };
135
139
  } catch (error) { return failure(error); }
@@ -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,12 +84,12 @@ 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 (!safeOptimizeMemory(entry)) return { ok: false, reason: `source ${id} contains unsafe stored content` };
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" };
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)" };
91
+ if (!(MEMORY_KINDS as readonly unknown[]).includes(operation.kind)) {
92
+ return { ok: false, reason: "invalid memory kind for the selected tier" };
99
93
  }
100
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` };
101
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" };
@@ -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 (!safeOptimizeMemory(normalizedAfter)) return { ok: false, reason: "replacement content, tags or source rejected by content scanner" };
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));
@@ -64,13 +64,12 @@ function entryPathMatches(entry: RetrievalSource, paths: readonly string[]): str
64
64
  return paths.filter((path) => content.includes(path));
65
65
  }
66
66
 
67
- function rankItem<T extends RetrievalSource>(entry: T, query: string): RetrievalRank<T> {
68
- const terms = queryTerms(query);
67
+ function rankItem<T extends RetrievalSource>(entry: T, terms: readonly string[], paths: readonly string[]): RetrievalRank<T> {
69
68
  const textWords = new Set(words(entry.text));
70
69
  const tagWords = new Set((entry.tags ?? []).flatMap(words));
71
70
  const textTerms = terms.filter((term) => textWords.has(term));
72
71
  const tagTerms = terms.filter((term) => !textWords.has(term) && tagWords.has(term));
73
- const pathMatches = entryPathMatches(entry, queryPaths(query));
72
+ const pathMatches = entryPathMatches(entry, paths);
74
73
  const textScore = textTerms.reduce((sum, term) => sum + (NEGATION_AND_EXCEPTION.has(term) ? 4 : 3), 0);
75
74
  const tagScore = tagTerms.reduce((sum, term) => sum + (NEGATION_AND_EXCEPTION.has(term) ? 3 : 2), 0);
76
75
  const score = textScore + tagScore + pathMatches.length * 12;
@@ -83,7 +82,9 @@ export function rankRetrievalEntries<T extends RetrievalSource>(
83
82
  query: string,
84
83
  tieBreak?: (a: T, b: T) => number,
85
84
  ): RetrievalRank<T>[] {
86
- return entries.map((entry) => rankItem(entry, query)).sort((a, b) => {
85
+ const terms = queryTerms(query);
86
+ const paths = queryPaths(query);
87
+ return entries.map((entry) => rankItem(entry, terms, paths)).sort((a, b) => {
87
88
  if (a.score !== b.score) return b.score - a.score;
88
89
  const tie = tieBreak?.(a.entry, b.entry) ?? 0;
89
90
  if (tie !== 0) return tie;
@@ -17,8 +17,8 @@ import { renderMind } from "./inject.ts";
17
17
  import { readMemory, memoryTargets, type MemoryReadResult, type MemoryReadScope } from "./memory-read.ts";
18
18
  import { MemoryOptimizer } from "./optimize-service.ts";
19
19
  import { samePersistedMemory } from "./optimize.ts";
20
- import type { MemoryEntry, MemoryInput, MemoryKind, MemoryTerm } 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";
20
+ import type { MemoryEntry, MemoryInput, MemoryKind } 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";
@@ -34,19 +34,21 @@ export interface MindServiceOptions {
34
34
  budget?: MindBudget;
35
35
  }
36
36
 
37
- export interface RememberInput {
38
- term: MemoryTerm;
37
+ interface RememberInputBase {
39
38
  kind: MemoryKind;
40
39
  text: string;
41
40
  tags?: string[];
42
41
  ttlHours?: number;
43
42
  supersedes?: string;
44
- /** Durable repository knowledge stays in this project; persona is the default for long facts. */
45
- scope?: "project" | "persona" | "shared";
46
43
  source?: string;
47
44
  derivedFrom?: string[];
48
45
  }
49
46
 
47
+ /** Long writes name their destination; short working memory is project-scoped by default. */
48
+ export type RememberInput =
49
+ | (RememberInputBase & { term: "long"; scope: "project" | "persona" | "shared" })
50
+ | (RememberInputBase & { term: "short"; scope?: "project" });
51
+
50
52
  export interface BacklogAddInput {
51
53
  text: string;
52
54
  tags?: string[];
@@ -225,6 +227,11 @@ export class MindService {
225
227
  return new MemoryOptimizer({ stores: this.memoryStores(), persona: this.scope.persona, now: this.now, mutationLock: this.memoryMutationLock });
226
228
  }
227
229
 
230
+ /** Read-only identity snapshot for inspection and native recording receipts; no store paths or IO. */
231
+ inspectionScope(): Pick<Scope, "persona" | "projectRoot" | "homeWorkspace"> {
232
+ return { persona: this.scope.persona, projectRoot: this.scope.projectRoot, ...(this.scope.homeWorkspace ? { homeWorkspace: true as const } : {}) };
233
+ }
234
+
228
235
  /** Explicit full retrieval; reads never refresh age/expiry or repair malformed stores. */
229
236
  readMemory(id: string, scope: MemoryReadScope = "both"): Promise<MemoryReadResult> {
230
237
  return readMemory(this.memoryStores(), id, scope, this.now());
@@ -232,7 +239,9 @@ export class MindService {
232
239
 
233
240
  /** Store a memory (long or short term). Scanned + non-empty-checked before it is persisted. */
234
241
  async remember(input: RememberInput): Promise<RememberResult> {
242
+ if (input.term !== "long" && input.term !== "short") return { ok: false, reason: "unknown memory term" };
235
243
  if (input.scope !== undefined && !["project", "persona", "shared"].includes(input.scope)) return { ok: false, reason: "unknown memory scope" };
244
+ if (input.term === "long" && input.scope === undefined) return { ok: false, reason: "long-term memory requires an explicit scope: project, persona, or shared" };
236
245
  if (input.term === "short" && input.scope !== undefined && input.scope !== "project") return { ok: false, reason: "short-term memory belongs to the project" };
237
246
  const now = this.now();
238
247
  const text = input.text.trim();
@@ -261,8 +270,8 @@ export class MindService {
261
270
  const scan = scanContent(text);
262
271
  if (!scan.ok) return { ok: false, reason: scan.reason ?? "rejected by content scanner" };
263
272
 
264
- // An objective is the persona's durable north-star — always long-term, never a decaying note.
265
- const term: MemoryTerm = input.kind === "objective" ? "long" : input.term;
273
+ // Kind describes content; only the caller-selected term controls lifetime.
274
+ const term = input.term;
266
275
  const makeInput: MemoryInput = { term, kind: input.kind, text };
267
276
  if (input.tags) makeInput.tags = input.tags;
268
277
  if (input.ttlHours !== undefined) makeInput.ttlHours = input.ttlHours;
@@ -281,7 +290,7 @@ export class MindService {
281
290
  // Same contract as `forget`: a handle that addresses more than one fact retires none of
282
291
  // them, and the caller is told so rather than silently getting a partial write. Read under
283
292
  // the mutation lock every writer holds, so the answer cannot go stale before the update.
284
- // The pool is the one `forget` resolves against — ALL THREE memory tiers, not just the one
293
+ // The pool is the one `forget` resolves against — all durable/working stores, not just the one
285
294
  // being written: a v1 comma-joined id can name a durable fact in `shared` and another in
286
295
  // `ltm`, and a per-store check would still let the write destroy whichever copy sits in the
287
296
  // target tier while the delete path refuses the identical handle.
@@ -314,6 +323,7 @@ export class MindService {
314
323
  if (matches.length !== 1) return { ok: false, reason: "source missing or ambiguous" } as const;
315
324
  const found = matches[0]!;
316
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;
317
327
  const promoted = promoteToLong(found, this.now());
318
328
  if (target === "project") promoted.persona = this.scope.persona;
319
329
  const destination = target === "project" ? this.projectLtm : target === "shared" ? this.shared : this.ltm;
@@ -553,15 +563,16 @@ export class MindService {
553
563
  return { stmRemoved, backlogRemoved };
554
564
  }
555
565
 
556
- /** Clear dueAt on still-open items after a wake was shown, so the alarm does not re-nag. */
557
- async acknowledgeDue(ids?: readonly string[]): Promise<number> {
558
- const wanted = ids && ids.length > 0 ? new Set(ids) : undefined;
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]));
559
570
  let cleared = 0;
560
571
  try {
561
572
  await this.backlog.update((es) =>
562
573
  es.map((e) => {
563
574
  if (e.dueAtEpochMs === undefined) return e;
564
- if (wanted && !wanted.has(e.id)) return e;
575
+ if (wanted.get(e.id) !== e.dueAtEpochMs) return e;
565
576
  if (e.state !== "open" && e.state !== "taken") return e;
566
577
  cleared++;
567
578
  const next = { ...e };
package/src/core/store.ts CHANGED
@@ -474,7 +474,11 @@ async function recoverDeadLocalLock(
474
474
  try {
475
475
  await mkdir(gate);
476
476
  } catch (err) {
477
- if ((err as NodeJS.ErrnoException).code === "EEXIST") return false;
477
+ const code = (err as NodeJS.ErrnoException).code;
478
+ // Windows may report EPERM while a contender's removed gate is still pending
479
+ // deletion. We acquired nothing: retry through the caller's bounded contention
480
+ // wait, without removing the gate or inspecting/replacing the canonical token.
481
+ if (code === "EEXIST" || (process.platform === "win32" && code === "EPERM")) return false;
478
482
  throw err;
479
483
  }
480
484
  try {
@@ -784,7 +788,9 @@ export class JsonStore<E> {
784
788
  if (lockToken === undefined) {
785
789
  const peek = await this.tryBak();
786
790
  if (!peek) return null;
787
- return withFileLock(`${this.filePath}.lock`, async (token) => this.recoverFromBak(reason, token));
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));
788
794
  }
789
795
  const bak = await this.tryBak();
790
796
  if (!bak) return null;
@@ -3,7 +3,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
3
3
  import type { MindService } from "../core/service.ts";
4
4
  import type { Scope } from "../core/scope.ts";
5
5
  import type { AutoOptimizeTarget } from "../core/auto-optimize.ts";
6
- import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, type AutoAttempt } from "./auto-optimize.ts";
6
+ import { AUTO_ATTEMPT_ENTRY, AutoOptimizeScheduler, type AutoAttempt, type AutoOptimizeReportContext, type ReviewReservation } from "./auto-optimize.ts";
7
7
  import { launchMindWorker } from "./mind-worker.ts";
8
8
  import { MIND_RESULT_ENTRY_TYPE } from "../ui/mind-result-card.ts";
9
9
 
@@ -24,7 +24,7 @@ export function autoOptimizeTarget(input: unknown): AutoOptimizeTarget | undefin
24
24
  if (scope !== undefined && scope !== "project" && scope !== "persona" && scope !== "shared") return undefined;
25
25
  if (value.action === "remember") {
26
26
  if (value.term === "short") return scope === undefined || scope === "project" ? "project" : undefined;
27
- if (value.term !== "long" || scope === "shared") return undefined;
27
+ if (value.term !== "long" || scope === undefined || scope === "shared") return undefined;
28
28
  return scope === "project" ? "project-long" : "persona";
29
29
  }
30
30
  if (value.action === "promote") {
@@ -42,6 +42,7 @@ export interface AutoOptimizeSession {
42
42
  setEnabled(enabled: boolean): void;
43
43
  targets(): readonly AutoOptimizeTarget[];
44
44
  startExplicit(target?: AutoOptimizeTarget): boolean;
45
+ reserveReview(target: AutoOptimizeTarget): ReviewReservation | undefined;
45
46
  }
46
47
 
47
48
  export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoOptimizeSession {
@@ -69,7 +70,7 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
69
70
  const data = entry.data as Record<string, unknown>;
70
71
  if (data.version === 1 && data.owner === key && typeof data.digest === "string" && /^[a-f0-9]{64}$/.test(data.digest) && typeof data.at === "number" && Number.isFinite(data.at) && data.at >= 0 && data.at <= Date.now() && (data.state === "started" || data.state === "settled")) {
71
72
  const target = data.target === "project" || data.target === "project-long" || data.target === "persona" ? data.target : undefined;
72
- attempts.push({ digest: data.digest, at: data.at, state: data.state, ...(target ? { target } : {}) });
73
+ attempts.push({ digest: data.digest, at: data.at, state: data.state, ...(target ? { target } : {}), ...(data.explicit === true ? { explicit: true } : {}) });
73
74
  if (attempts.length > 64) attempts.shift();
74
75
  }
75
76
  }
@@ -80,10 +81,26 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
80
81
  optimizer: () => deps.mind(ctx).createOptimizer(),
81
82
  launch: (task: string) => launchMindWorker(pi, ctx.sessionManager.getSessionId(), deps.persona(ctx), task),
82
83
  recordAttempt: (attempt: AutoAttempt) => { if (!current()) throw new Error("automatic memory owner changed"); pi.appendEntry(AUTO_ATTEMPT_ENTRY, { version: 1, owner: key, ...attempt }); },
83
- report: (title: string, body: string) => {
84
+ report: (title: string, body: string, reportContext?: AutoOptimizeReportContext) => {
84
85
  if (!current()) throw new Error("automatic memory owner changed");
85
- pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body });
86
- if (title !== "Mind automatic proposal") ctx.ui.notify(`Mind · ${body.split("\n", 1)[0]!.slice(0, 160)}`, "info");
86
+ if (reportContext?.automatic && reportContext.phase === "proposal") {
87
+ pi.appendEntry("pi-persona-mind-auto-proposal", { title, content: body });
88
+ return;
89
+ }
90
+ if (reportContext?.automatic && !reportContext.attention) {
91
+ ctx.ui.notify(`mind · ${reportContext.target} · ${reportContext.summary}`, "info");
92
+ return;
93
+ }
94
+ pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body, ...(reportContext?.automatic ? { reportContext } : {}) });
95
+ if (reportContext?.automatic) {
96
+ if (reportContext.attention) ctx.ui.notify(`mind · ${reportContext.target} review needs attention`, "warning");
97
+ return;
98
+ }
99
+ if (title !== "Mind automatic proposal") {
100
+ const target = / — (project(?:-long)?|persona)$/.exec(title)?.[1];
101
+ const kind = title.includes("proposal") ? "proposal" : "review";
102
+ ctx.ui.notify(`mind · ${target ? `${target} ` : ""}${kind} update`, "info");
103
+ }
87
104
  }, attempts,
88
105
  };
89
106
  if (resetPreference) scheduler.activate(owner, process.env.PI_PERSONA_MIND_OPTIMIZE !== "off");
@@ -97,6 +114,8 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
97
114
  pi.on("input", () => { scheduler.interrupt(); });
98
115
  pi.on("agent_start", () => { scheduler.interrupt(); });
99
116
  pi.on("model_select", () => { scheduler.interrupt(); });
117
+ // Native /tree preserves the session manager/id/file but revokes work accepted on its old branch.
118
+ pi.on("session_tree", () => { scheduler.interrupt(); });
100
119
  pi.on("ui_prompt_start", () => { scheduler.interrupt(); });
101
120
  pi.on("turn_end", (event, ctx) => {
102
121
  if (!safeAvailable(ctx) || event.message.role !== "assistant" || tokenEvents.has(event.messageEntryId)) return;
@@ -118,5 +137,6 @@ export function installAutoOptimize(pi: ExtensionAPI, deps: Dependencies): AutoO
118
137
  setEnabled: (enabled) => scheduler.setEnabled(enabled),
119
138
  targets: () => scheduler.targets(),
120
139
  startExplicit: (target) => scheduler.startExplicit(target),
140
+ reserveReview: (target) => scheduler.reserveReview(target),
121
141
  };
122
142
  }