@aeondave/pi-persona-mind 0.9.2 → 0.9.3

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.
@@ -21,34 +21,58 @@ export interface RetrievalRank<T> {
21
21
  textTerms: string[];
22
22
  tagTerms: string[];
23
23
  pathMatches: string[];
24
+ /** Matched query terms that used a weaker identifier/vowel-accent bridge. */
25
+ normalizedTerms: string[];
24
26
  }
25
27
 
26
28
  function compareStrings(a: string, b: string): number {
27
29
  return a < b ? -1 : a > b ? 1 : 0;
28
30
  }
29
31
 
30
- const TOKEN_SEGMENTS = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+|[\p{L}\p{N}]+/gu;
31
- const EAST_ASIAN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
32
+ 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;
32
35
 
33
36
  function words(value: string): string[] {
34
- const segments = value.toLowerCase().match(TOKEN_SEGMENTS) ?? [];
35
- return segments.flatMap((segment) => {
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; }
36
41
  const chars = [...segment];
37
- if (chars.length < 2 || !EAST_ASIAN.test(chars[0] ?? "")) return [segment];
38
- const bigrams: string[] = [];
39
- for (let index = 0; index < chars.length - 1; index++) bigrams.push(`${chars[index]}${chars[index + 1]}`);
40
- return bigrams;
41
- });
42
+ 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()));
42
63
  }
43
64
 
44
- function queryTerms(query: string): string[] {
65
+ interface QueryTerm { original: string; components: readonly string[] }
66
+
67
+ function queryTerms(query: string): QueryTerm[] {
45
68
  const seen = new Set<string>();
46
- const result: string[] = [];
47
- for (const term of words(query.slice(0, QUERY_MAX_CHARS))) {
69
+ const result: QueryTerm[] = [];
70
+ for (const word of words(query.slice(0, QUERY_MAX_CHARS))) {
71
+ const term = word.toLowerCase();
48
72
  if (STOP_WORDS.has(term) && !NEGATION_AND_EXCEPTION.has(term)) continue;
49
73
  if (seen.has(term)) continue;
50
74
  seen.add(term);
51
- result.push(term);
75
+ result.push({ original: term, components: components(word) });
52
76
  }
53
77
  return result;
54
78
  }
@@ -64,16 +88,40 @@ function entryPathMatches(entry: RetrievalSource, paths: readonly string[]): str
64
88
  return paths.filter((path) => content.includes(path));
65
89
  }
66
90
 
67
- function rankItem<T extends RetrievalSource>(entry: T, terms: readonly string[], paths: readonly string[]): RetrievalRank<T> {
68
- const textWords = new Set(words(entry.text));
69
- const tagWords = new Set((entry.tags ?? []).flatMap(words));
70
- const textTerms = terms.filter((term) => textWords.has(term));
71
- const tagTerms = terms.filter((term) => !textWords.has(term) && tagWords.has(term));
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
+ exact.add(word.toLowerCase());
96
+ for (const part of components(word)) normalized.add(part);
97
+ }
98
+ return { exact, normalized };
99
+ }
100
+
101
+ function rankItem<T extends RetrievalSource>(entry: T, terms: readonly QueryTerm[], paths: readonly string[]): RetrievalRank<T> {
102
+ if (terms.length === 0) {
103
+ const pathMatches = entryPathMatches(entry, paths);
104
+ return { entry, score: pathMatches.length * 12, textTerms: [], tagTerms: [], pathMatches, normalizedTerms: [] };
105
+ }
106
+ const textWords = vocabulary(entry.text);
107
+ const tagWords = vocabulary((entry.tags ?? []).join(" "));
108
+ const textTerms: string[] = [];
109
+ const tagTerms: string[] = [];
110
+ const normalizedTerms: string[] = [];
111
+ let lexicalScore = 0;
112
+ for (const { original, components: parts } of terms) {
113
+ const negation = NEGATION_AND_EXCEPTION.has(original);
114
+ if (textWords.exact.has(original)) { textTerms.push(original); lexicalScore += negation ? 4 : 3; }
115
+ else if (tagWords.exact.has(original)) { tagTerms.push(original); lexicalScore += negation ? 3 : 2; }
116
+ else if (parts.every((part) => textWords.normalized.has(part))) {
117
+ textTerms.push(original); normalizedTerms.push(original); lexicalScore += 1;
118
+ } else if (parts.every((part) => tagWords.normalized.has(part))) {
119
+ tagTerms.push(original); normalizedTerms.push(original); lexicalScore += 0.75;
120
+ }
121
+ }
72
122
  const pathMatches = entryPathMatches(entry, paths);
73
- const textScore = textTerms.reduce((sum, term) => sum + (NEGATION_AND_EXCEPTION.has(term) ? 4 : 3), 0);
74
- const tagScore = tagTerms.reduce((sum, term) => sum + (NEGATION_AND_EXCEPTION.has(term) ? 3 : 2), 0);
75
- const score = textScore + tagScore + pathMatches.length * 12;
76
- return { entry, score, textTerms, tagTerms, pathMatches };
123
+ const score = lexicalScore + pathMatches.length * 12;
124
+ return { entry, score, textTerms, tagTerms, pathMatches, normalizedTerms };
77
125
  }
78
126
 
79
127
  /** Rank generic text/tag entries; optional ties are resolved by the supplied domain comparator. */
@@ -9,6 +9,7 @@
9
9
  * (same default life; a later wake extends it).
10
10
  */
11
11
 
12
+ import { randomUUID } from "node:crypto";
12
13
  import type { BacklogEntry, BacklogState, TransitionResult } from "./backlog.ts";
13
14
  import { clampBacklogMax, compactTerminal, makeBacklog, openItems, orderBacklog, pruneExpired as pruneExpiredBacklog, transition, validateBacklog, viewFor, MAX_BACKLOG_NOTE_CHARS, MAX_BACKLOG_TAGS, MAX_BACKLOG_TAG_CHARS, MAX_BACKLOG_TEXT_CHARS } from "./backlog.ts";
14
15
  import { contentId } from "./ids.ts";
@@ -16,7 +17,8 @@ import type { MindBudget } from "./inject.ts";
16
17
  import { renderMind } from "./inject.ts";
17
18
  import { readMemory, memoryTargets, type MemoryReadResult, type MemoryReadScope } from "./memory-read.ts";
18
19
  import { MemoryOptimizer } from "./optimize-service.ts";
19
- import { samePersistedMemory } from "./optimize.ts";
20
+ import { OptimizeHistoryStore, type OptimizeReceipt } from "./optimize-history.ts";
21
+ import { samePersistedMemory, type OptimizeTarget } from "./optimize.ts";
20
22
  import type { MemoryEntry, MemoryInput, MemoryKind } from "./memory.ts";
21
23
  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
24
  import { scanContent } from "./scanner.ts";
@@ -32,6 +34,8 @@ export interface MindServiceOptions {
32
34
  now?: () => number;
33
35
  onWarn?: (message: string) => void;
34
36
  budget?: MindBudget;
37
+ /** Runtime owner snapshot for remember admission/commit; omitted by standalone store callers. */
38
+ isCurrent?: () => boolean;
35
39
  }
36
40
 
37
41
  interface RememberInputBase {
@@ -82,7 +86,7 @@ export interface AmbiguousMemory {
82
86
  resolves: boolean;
83
87
  }
84
88
 
85
- export type RememberResult = { ok: true; entry: MemoryEntry } | { ok: false; reason: string };
89
+ export type RememberResult = { ok: true; entry: MemoryEntry; receiptId?: string; warning?: string } | { ok: false; reason: string };
86
90
  export type BacklogAddResult = { ok: true; entry: BacklogEntry } | { ok: false; reason: string };
87
91
  export type BacklogSetResult = { ok: true; entry: BacklogEntry } | { ok: false; reason?: string };
88
92
  export type ForgetResult = { removed: number; reason?: "ambiguous_id"; candidates?: AmbiguousMemory[] };
@@ -160,6 +164,7 @@ export class MindService {
160
164
  private readonly backlog: JsonStore<BacklogEntry>;
161
165
  private readonly memoryMutationLock: string;
162
166
  private readonly warn: (message: string) => void;
167
+ private readonly isCurrent: () => boolean;
163
168
 
164
169
  constructor(
165
170
  scope: Scope,
@@ -169,6 +174,7 @@ export class MindService {
169
174
  this.now = opts.now ?? Date.now;
170
175
  this.budget = opts.budget;
171
176
  this.warn = opts.onWarn ?? (() => {});
177
+ this.isCurrent = opts.isCurrent ?? (() => true);
172
178
  const longOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateLongMemory, now: this.now };
173
179
  const shortOpts: JsonStoreOptions<MemoryEntry> = { version: STORE_VERSION, validateEntry: validateShortMemory, now: this.now };
174
180
  const backlogOpts: JsonStoreOptions<BacklogEntry> = { version: STORE_VERSION, validateEntry: validateBacklog, now: this.now };
@@ -239,6 +245,7 @@ export class MindService {
239
245
 
240
246
  /** Store a memory (long or short term). Scanned + non-empty-checked before it is persisted. */
241
247
  async remember(input: RememberInput): Promise<RememberResult> {
248
+ if (!this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner is unavailable; no memory was stored" };
242
249
  if (input.term !== "long" && input.term !== "short") return { ok: false, reason: "unknown memory term" };
243
250
  if (input.scope !== undefined && !["project", "persona", "shared"].includes(input.scope)) return { ok: false, reason: "unknown memory scope" };
244
251
  if (input.term === "long" && input.scope === undefined) return { ok: false, reason: "long-term memory requires an explicit scope: project, persona, or shared" };
@@ -281,38 +288,73 @@ export class MindService {
281
288
  if (term === "short" || input.scope === "project") makeInput.persona = this.scope.persona;
282
289
 
283
290
  const entry = makeMemory(makeInput, now);
284
- const store = term === "short" ? this.stm : input.scope === "project" ? this.projectLtm : input.scope === "shared" ? this.shared : this.ltm;
291
+ const target: OptimizeTarget = term === "short" ? "project" : input.scope === "project" ? "project-long" : input.scope === "shared" ? "shared" : "persona";
292
+ const store = this.memoryStores()[target];
285
293
  try {
286
- let committed: MemoryEntry | undefined;
287
- let ambiguous: { id: string; candidates: AmbiguousMemory[] } | undefined;
288
- await withFileLock(this.memoryMutationLock, async () => {
289
- if (entry.supersedes !== undefined) {
290
- // Same contract as `forget`: a handle that addresses more than one fact retires none of
291
- // them, and the caller is told so rather than silently getting a partial write. Read under
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 — all durable/working stores, not just the one
294
- // being written: a v1 comma-joined id can name a durable fact in `shared` and another in
295
- // `ltm`, and a per-store check would still let the write destroy whichever copy sits in the
296
- // target tier while the delete path refuses the identical handle.
297
- const loaded = await Promise.all(Object.values(this.memoryStores()).map((memoryStore) => memoryStore.load()));
298
- const visible = loaded.flatMap((snapshot) => pruneExpired(snapshot.entries, this.now()));
299
- if (supersedeTargets(visible, entry.supersedes).ambiguous) {
300
- ambiguous = { id: entry.supersedes, candidates: ambiguityCandidates(visible, entry.supersedes) };
301
- return;
302
- }
303
- }
304
- const updated = await store.update((es) => upsertMemory(term === "short" ? pruneExpired(es, this.now()) : es, entry));
305
- committed = updated.entries.find((candidate) => sameMemoryContent(candidate, entry));
294
+ const result = await withFileLock(this.memoryMutationLock, async (): Promise<RememberResult> => {
295
+ this.assertRememberOwner();
296
+ if (entry.supersedes !== undefined) return this.rememberSuperseding(entry, target);
297
+ const updated = await store.update((es) => {
298
+ this.assertRememberOwner();
299
+ return upsertMemory(term === "short" ? pruneExpired(es, this.now()) : es, entry);
300
+ });
301
+ return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry)) ?? entry };
306
302
  });
307
- if (ambiguous) {
308
- return { ok: false, reason: ambiguousSupersedesReason(ambiguous.id, ambiguous.candidates) };
309
- }
310
- return { ok: true, entry: committed ?? entry };
303
+ if (result.ok && !this.rememberOwnerCurrent()) return { ok: false, reason: "memory owner changed while remember was running; the write may have committed in its original scope; inspect that scope before retrying" };
304
+ return result;
311
305
  } catch (err) {
312
306
  return { ok: false, reason: storageFailure(err) };
313
307
  }
314
308
  }
315
309
 
310
+ private rememberOwnerCurrent(): boolean {
311
+ try { return this.isCurrent(); } catch { return false; }
312
+ }
313
+
314
+ private assertRememberOwner(): void {
315
+ if (!this.rememberOwnerCurrent()) throw new Error("memory owner changed; remember refused before commit");
316
+ }
317
+
318
+ /** Under the memory transaction lock: resolve across tiers, but retire only in the destination. */
319
+ private async rememberSuperseding(entry: MemoryEntry, target: OptimizeTarget): Promise<RememberResult> {
320
+ const stores = Object.values(this.memoryStores());
321
+ const store = this.memoryStores()[target];
322
+ // Unlike recovery reads, strict snapshots cannot silently erase evidence before replacement.
323
+ const loaded = await Promise.all(stores.map((memoryStore) => memoryStore.inspectStrict()));
324
+ const visible = loaded.flatMap((snapshot) => pruneExpired(snapshot.store.entries, this.now()));
325
+ const resolved = supersedeTargets(visible, entry.supersedes!);
326
+ if (resolved.ambiguous) return { ok: false, reason: ambiguousSupersedesReason(entry.supersedes!, ambiguityCandidates(visible, entry.supersedes!)) };
327
+ const snapshot = loaded[stores.indexOf(store)]!;
328
+ const active = pruneExpired(snapshot.store.entries, this.now());
329
+ if (resolved.targets.length > 0 && !active.some((candidate) => memoryIdMatches(candidate, entry.supersedes!))) {
330
+ return { ok: false, reason: "memory supersedes id exists only outside the destination tier; use the source's scope and lifetime to replace it" };
331
+ }
332
+ const retired = supersedeTargets(active, entry.supersedes!).targets.filter((candidate) => !sameMemoryContent(candidate, entry));
333
+ const mutate = (entries: MemoryEntry[]) => {
334
+ this.assertRememberOwner();
335
+ if (isExpired(entry, this.now())) throw new Error("the replacement expired before commit; record the current fact again");
336
+ return upsertMemory(target === "project" ? pruneExpired(entries, this.now()) : entries, entry);
337
+ };
338
+ if (!retired.length) {
339
+ const updated = await store.compareAndUpdate(snapshot.fingerprint, mutate);
340
+ return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry)) ?? entry };
341
+ }
342
+ const next = mutate(snapshot.store.entries);
343
+ const after = next.find((candidate) => sameMemoryContent(candidate, entry))!;
344
+ // If the new fact already exists, upsert also updates that row's metadata: retain it too.
345
+ const before = active.filter((candidate) => retired.includes(candidate) || sameMemoryContent(candidate, entry));
346
+ const receipt: OptimizeReceipt = { receiptId: randomUUID(), origin: "replacement", target, persona: this.scope.persona,
347
+ createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: [{ before, after }] };
348
+ const history = new OptimizeHistoryStore(`${store.filePath}.optimize-history.json`, this.now);
349
+ const updated = await history.commit(store, snapshot.fingerprint, receipt, () => structuredClone(next), () => {
350
+ this.assertRememberOwner();
351
+ if (before.some((source) => isExpired(source, this.now()))) throw new Error("a superseded source expired before commit; record the current fact again");
352
+ if (isExpired(after, this.now())) throw new Error("the replacement expired before commit; record the current fact again");
353
+ });
354
+ return { ok: true, entry: updated.entries.find((candidate) => sameMemoryContent(candidate, entry))!, receiptId: receipt.receiptId,
355
+ ...(updated.warning ? { warning: updated.warning } : {}) };
356
+ }
357
+
316
358
  /** Preserve repository scope unless the caller explicitly selects a broader durable tier. */
317
359
  async promote(id: string, target: "project" | "persona" | "shared" = "project"): Promise<{ ok: true; entry: MemoryEntry; ambiguousSupersedes?: string } | { ok: false; reason?: string }> {
318
360
  if (!["project", "persona", "shared"].includes(target)) return { ok: false, reason: "unknown promotion scope" };
@@ -0,0 +1,23 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { Scope } from "../core/scope.ts";
3
+ import type { HandoffInput } from "../core/handoff.ts";
4
+ import { HandoffStore, type HandoffResult } from "../core/handoff-store.ts";
5
+
6
+ /** Captures provenance; the supplied owner guard invalidates navigation, but allows ordinary appends. */
7
+ export async function runHandoff(ctx: ExtensionContext, scope: Scope, ownerCurrent: () => boolean, input: HandoffInput): Promise<HandoffResult> {
8
+ try {
9
+ const manager = ctx.sessionManager;
10
+ const branchId = manager.getLeafId();
11
+ const sessionId = manager.getSessionId();
12
+ const isCurrent = () => { try { return ownerCurrent() && ctx.sessionManager === manager && manager.getSessionId() === sessionId; } catch { return false; } };
13
+ if (!isCurrent()) return { ok: false, reason: "handoff session owner unavailable" };
14
+ const result = await new HandoffStore(scope).execute({ persona: scope.persona, projectRoot: scope.projectRoot, sessionId, branchId, cwd: ctx.cwd, isCurrent }, input);
15
+ if (!isCurrent()) {
16
+ if (!result.ok) return result;
17
+ return { ok: false, reason: result.operation === "read" || result.operation === "list"
18
+ ? "handoff owner changed; historical snapshot withheld"
19
+ : `handoff ${result.operation} committed in the original scope before the owner changed; inspect it before retrying` };
20
+ }
21
+ return result;
22
+ } catch { return { ok: false, reason: "handoff session owner unavailable" }; }
23
+ }