@aeondave/pi-persona-mind 0.9.2 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ import { scanContent } from "./scanner.ts";
2
+
3
+ export const MAX_HANDOFF_RECORD_BYTES = 16_384;
4
+ export const MAX_HANDOFF_ENTRIES = 32;
5
+ export const MAX_HANDOFF_STORE_BYTES = 128 * 1024;
6
+ export const MAX_HANDOFF_GOAL_PREVIEW_CHARS = 160;
7
+
8
+ export interface HandoffOrigin { sessionId: string; branchId: string | null; cwd: string }
9
+ export interface HandoffContext extends HandoffOrigin { persona: string; projectRoot: string; isCurrent?: () => boolean }
10
+ export interface HandoffContent { goal: string; completed: string[]; pending: string[]; nextStep: string; references: string[] }
11
+ export interface HandoffEntry extends HandoffContent {
12
+ id: string; revision: number; persona: string; projectRoot: string; origin: HandoffOrigin;
13
+ createdAt: string; updatedAt: string; status: "open" | "completed"; resolution?: string;
14
+ }
15
+ export type HandoffInput =
16
+ | ({ operation: "save" } & HandoffContent)
17
+ | { operation: "list" }
18
+ | { operation: "read"; id: string }
19
+ | { operation: "complete"; id: string; revision: number; resolution: string }
20
+ | { operation: "forget"; id: string; revision: number };
21
+
22
+ function safeString(value: unknown, max = 4096): value is string {
23
+ return typeof value === "string" && value.trim().length > 0 && value.length <= max && scanContent(value).ok;
24
+ }
25
+ function safeArray(value: unknown): value is string[] {
26
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > 32 || Reflect.ownKeys(value).length !== value.length + 1) return false;
27
+ for (let index = 0; index < value.length; index++) {
28
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
29
+ if (!descriptor || !("value" in descriptor) || !safeString(descriptor.value, 2048)) return false;
30
+ }
31
+ return true;
32
+ }
33
+ function dataRecord(value: unknown): value is Record<string, unknown> {
34
+ return value !== null && typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value))
35
+ && Reflect.ownKeys(value).every((key) => typeof key === "string" && "value" in Object.getOwnPropertyDescriptor(value, key)!);
36
+ }
37
+ function exactFields(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): boolean {
38
+ return required.every((key) => Object.hasOwn(value, key)) && Reflect.ownKeys(value).every((key) => typeof key === "string" && (required.includes(key) || optional.includes(key)));
39
+ }
40
+ const CONTENT_FIELDS = ["goal", "completed", "pending", "nextStep", "references"] as const;
41
+ function content(value: HandoffContent): HandoffContent {
42
+ return { goal: value.goal, completed: [...value.completed], pending: [...value.pending], nextStep: value.nextStep, references: [...value.references] };
43
+ }
44
+ export function validHandoffContent(value: unknown): value is HandoffContent {
45
+ return dataRecord(value) && CONTENT_FIELDS.every((key) => Object.hasOwn(value, key))
46
+ && safeString(value.goal) && safeArray(value.completed) && safeArray(value.pending) && safeString(value.nextStep) && safeArray(value.references)
47
+ && Buffer.byteLength(JSON.stringify(content(value as unknown as HandoffContent)), "utf8") <= MAX_HANDOFF_RECORD_BYTES;
48
+ }
49
+ export function validContext(value: HandoffContext): boolean {
50
+ return [value.persona, value.projectRoot, value.sessionId, value.cwd].every((s) => safeString(s, 1024)) && (value.branchId === null || safeString(value.branchId, 1024));
51
+ }
52
+ export function validateHandoff(raw: unknown): HandoffEntry | null {
53
+ if (!dataRecord(raw) || !exactFields(raw, ["id", "revision", "persona", "projectRoot", "origin", "createdAt", "updatedAt", "status", ...CONTENT_FIELDS], ["resolution"])) return null;
54
+ if (!dataRecord(raw.origin) || !exactFields(raw.origin, ["sessionId", "branchId", "cwd"])) return null;
55
+ const origin = raw.origin;
56
+ if (![raw.persona, raw.projectRoot, origin.sessionId, origin.cwd].every((value) => safeString(value, 1024)) || origin.branchId !== null && !safeString(origin.branchId, 1024)) return null;
57
+ if (typeof raw.id !== "string" || !/^[a-f0-9]{32}$/.test(raw.id) || typeof raw.revision !== "number" || !Number.isSafeInteger(raw.revision) || raw.revision < 1 || !validHandoffContent(raw)) return null;
58
+ // Writers use ISO timestamps. Exact strings reject coercible arrays/numbers and ignored suffixes.
59
+ const validDate = (value: unknown): value is string => safeString(value, 24) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
60
+ if (!validDate(raw.createdAt) || !validDate(raw.updatedAt)) return null;
61
+ const status = raw.status;
62
+ if (status !== "open" && status !== "completed") return null;
63
+ if (status === "open" ? Object.hasOwn(raw, "resolution") : !safeString(raw.resolution)) return null;
64
+ const entry: HandoffEntry = { id: raw.id, revision: raw.revision, persona: raw.persona as string, projectRoot: raw.projectRoot as string,
65
+ origin: { sessionId: origin.sessionId as string, branchId: origin.branchId as string | null, cwd: origin.cwd as string },
66
+ createdAt: raw.createdAt, updatedAt: raw.updatedAt, status, ...content(raw),
67
+ ...(status === "completed" ? { resolution: raw.resolution as string } : {}) };
68
+ return Buffer.byteLength(JSON.stringify(entry), "utf8") <= MAX_HANDOFF_RECORD_BYTES ? entry : null;
69
+ }
70
+ export function validResolution(value: unknown): value is string { return safeString(value); }
@@ -1,5 +1,5 @@
1
1
  /** The extension targets current Pi only; this is a floor check, not a compatibility layer. */
2
- export const MIN_PI_VERSION = "1.5.2";
2
+ export const MIN_PI_VERSION = "1.6.0";
3
3
 
4
4
  export function isSupportedPiVersion(version: string): boolean {
5
5
  const parsed = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version);
@@ -7,7 +7,7 @@ export function isSupportedPiVersion(version: string): boolean {
7
7
  const parts = parsed.slice(1, 4).map(Number);
8
8
  if (parts.some((part) => !Number.isSafeInteger(part))) return false;
9
9
  const current = parts as [number, number, number];
10
- const minimum = [1, 5, 2] as const;
10
+ const minimum = [1, 6, 0] as const;
11
11
  for (let i = 0; i < minimum.length; i++) {
12
12
  if (current[i]! > minimum[i]!) return true;
13
13
  if (current[i]! < minimum[i]!) return false;
@@ -210,6 +210,13 @@ export function upsertMemory(entries: readonly MemoryEntry[], entry: MemoryEntry
210
210
  const merged: MemoryEntry = existing
211
211
  ? { ...entry, id: existing.id, recordedAt: existing.recordedAt, lastSeenAt: entry.recordedAt }
212
212
  : entry;
213
+ // A repeated observation renews the fact, not its origin. Keep omitted provenance without
214
+ // inheriting lifetime/owner fields, and do not replay its historical supersedes retirement.
215
+ if (existing) {
216
+ if (entry.source === undefined && existing.source !== undefined) merged.source = existing.source;
217
+ if (entry.derivedFrom === undefined && existing.derivedFrom !== undefined) merged.derivedFrom = [...existing.derivedFrom];
218
+ if (entry.supersedes === undefined && existing.supersedes !== undefined) merged.supersedes = existing.supersedes;
219
+ }
213
220
  // Retire the previous copy under the SAME semantic key it was found by, never by its id: an id
214
221
  // carried over from a migrated store can be shared with an unrelated fact, and dropping every
215
222
  // entry holding it would erase that fact too.
@@ -1,35 +1,48 @@
1
1
  /** Bounded write-ahead before images. Missing/corrupt history is never repaired to empty. */
2
2
  import { isExpired, isSafeMemoryContent, memoryContentKey, validateMemory, type MemoryEntry } from "./memory.ts";
3
3
  import { isOptimizeTarget, MAX_OPTIMIZE_OPERATIONS, MAX_OPTIMIZE_SOURCES, samePersistedMemory, type OptimizeChange, type OptimizeFailure, type OptimizeTarget } from "./optimize.ts";
4
- import { JsonStore, withFileLock } from "./store.ts";
4
+ import { JsonStore, StoreCapacityError, StoreConflictError, withFileLock } from "./store.ts";
5
5
 
6
6
  export const MAX_OPTIMIZE_HISTORY = 32;
7
7
  export const MAX_OPTIMIZE_HISTORY_BYTES = 2 * 1024 * 1024;
8
- export interface OptimizeReceipt {
8
+ interface ReceiptBase {
9
9
  receiptId: string;
10
- planId: string;
11
10
  target: OptimizeTarget;
12
11
  persona: string;
13
12
  createdAt: string;
14
13
  /** Prepared may mean interrupted before OR after memory commit; exact facts decide undo. */
15
14
  state: "prepared" | "applied" | "undone" | "rejected";
16
15
  storePath: string;
16
+ /** Memory-store fingerprint the receipt was prepared against. Bytes still equal to it mean the replacement is not in effect (never landed, or rolled back by backup recovery), so there is nothing to undo. */
17
+ fingerprint?: string;
17
18
  changes: OptimizeChange[];
18
19
  }
20
+ /** Missing origin is the existing persisted optimizer contract, never an ordinary replacement. */
21
+ export type OptimizeReceipt = ReceiptBase & (
22
+ | { origin?: "optimization"; planId: string }
23
+ | { origin: "replacement"; planId?: never }
24
+ );
19
25
  export interface OptimizeHistory {
20
26
  ok: true; target: OptimizeTarget; receipts: OptimizeReceipt[]; retained: number; omitted: number;
21
27
  limit: number; maxBytes: number; withheldUnsafe: number;
22
28
  }
23
29
  export interface OptimizeUndone { ok: true; receiptId: string; target: OptimizeTarget; restored: number; warning?: string }
30
+ export interface OptimizeReceiptDetail { ok: true; target: OptimizeTarget; receipt: OptimizeReceipt }
24
31
 
25
32
  function validateReceipt(raw: unknown): OptimizeReceipt | null {
26
33
  if (!raw || typeof raw !== "object") return null;
27
34
  const value = raw as Partial<OptimizeReceipt>;
28
- if (![value.receiptId, value.planId].every((id) => typeof id === "string" && /^[\da-f-]{36}$/i.test(id))) return null;
35
+ const validId = (id: unknown) => typeof id === "string" && /^[\da-f-]{36}$/i.test(id);
36
+ if (!validId(value.receiptId)) return null;
37
+ if (value.origin === "replacement" ? value.planId !== undefined : !validId(value.planId) || value.origin !== undefined && value.origin !== "optimization") return null;
29
38
  if (!isOptimizeTarget(value.target) || typeof value.persona !== "string" || !value.persona || value.persona.length > 128) return null;
30
- if (typeof value.createdAt !== "string" || !Number.isFinite(Date.parse(value.createdAt))) return null;
39
+ // Writers use Date.toISOString(). Bound before parsing so metadata cannot expand discovery output.
40
+ if (typeof value.createdAt !== "string" || value.createdAt.length > 27) return null;
41
+ const createdAt = Date.parse(value.createdAt);
42
+ if (!Number.isFinite(createdAt) || new Date(createdAt).toISOString() !== value.createdAt) return null;
31
43
  if (!["prepared", "applied", "undone", "rejected"].includes(value.state ?? "")) return null;
32
44
  if (typeof value.storePath !== "string" || value.storePath.length > 32_768 || !value.storePath) return null;
45
+ if (value.fingerprint !== undefined && (typeof value.fingerprint !== "string" || !/^[\da-f]{64}$/.test(value.fingerprint))) return null;
33
46
  if (!Array.isArray(value.changes) || !value.changes.length || value.changes.length > MAX_OPTIMIZE_OPERATIONS) return null;
34
47
  const changes: OptimizeChange[] = [];
35
48
  const sourceIds = new Set<string>(); const replacementIds = new Set<string>();
@@ -45,8 +58,9 @@ function validateReceipt(raw: unknown): OptimizeReceipt | null {
45
58
  if (!after || replacementIds.has(after.id)) return null;
46
59
  replacementIds.add(after.id); changes.push({ before, after });
47
60
  }
48
- return { receiptId: value.receiptId!, planId: value.planId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
49
- state: value.state!, storePath: value.storePath, changes };
61
+ const receipt: ReceiptBase = { receiptId: value.receiptId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
62
+ state: value.state!, storePath: value.storePath, ...(value.fingerprint === undefined ? {} : { fingerprint: value.fingerprint }), changes };
63
+ return value.origin === "replacement" ? { ...receipt, origin: "replacement" } : { ...receipt, origin: "optimization", planId: value.planId! };
50
64
  }
51
65
 
52
66
  /** Strict CAS avoids JsonStore.update's recovery semantics, which are unsuitable for recovery logs. */
@@ -59,13 +73,25 @@ export class OptimizeHistoryStore {
59
73
  }
60
74
  async exclusive<T>(run: () => Promise<T>): Promise<T> { return withFileLock(`${this.path}.transaction.lock`, run); }
61
75
  async read(): Promise<OptimizeReceipt[]> { return (await this.store.inspectStrict()).store.entries; }
62
- async prepare(receipt: OptimizeReceipt): Promise<void> {
76
+ /** `currentFingerprint` is the memory store's verified current fingerprint, used only to resolve this writer's own intents that are not in effect. */
77
+ async prepare(receipt: OptimizeReceipt, currentFingerprint?: string): Promise<void> {
63
78
  const snapshot = await this.store.inspectStrict();
64
- const entries = [...snapshot.store.entries, receipt];
79
+ let entries = [...snapshot.store.entries, receipt];
65
80
  // Only settled history can be evicted. An unresolved crash intent may own the only before image.
66
81
  const bytes = () => Buffer.byteLength(`${JSON.stringify({ ...snapshot.store, sequence: snapshot.store.sequence + 1, entries }, null, 2)}\n`, "utf8");
82
+ let resolved = false;
67
83
  while (entries.length > MAX_OPTIMIZE_HISTORY || bytes() > MAX_OPTIMIZE_HISTORY_BYTES) {
68
84
  const index = entries.findIndex((entry) => entry.receiptId !== receipt.receiptId && entry.state !== "prepared");
85
+ if (index < 0 && !resolved && currentFingerprint !== undefined) {
86
+ // Byte-identical memory since preparation means that intent is not in effect, whether it never
87
+ // committed or backup recovery rolled it back, so no before image is needed. Only receipts of
88
+ // this store and owner qualify: the history file is shared across personas, and another owner's
89
+ // intent is theirs to settle. A receipt without a fingerprint, or prepared against other bytes, stays protected.
90
+ resolved = true;
91
+ const mine = (entry: OptimizeReceipt) => entry.storePath === receipt.storePath && entry.persona === receipt.persona && entry.target === receipt.target;
92
+ entries = entries.map((entry): OptimizeReceipt => entry.receiptId !== receipt.receiptId && entry.state === "prepared" && entry.fingerprint === currentFingerprint && mine(entry) ? { ...entry, state: "rejected" } : entry);
93
+ continue;
94
+ }
69
95
  if (index < 0) throw new Error("optimizer history capacity exhausted by recovery receipts; replacement refused");
70
96
  entries.splice(index, 1);
71
97
  }
@@ -76,11 +102,47 @@ export class OptimizeHistoryStore {
76
102
  if (!snapshot.store.entries.some((receipt) => receipt.receiptId === receiptId)) throw new Error("optimizer recovery receipt disappeared; history requires repair");
77
103
  await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => entries.map((receipt) => receipt.receiptId === receiptId ? { ...receipt, state } : receipt));
78
104
  }
105
+
106
+ /** Caller owns the memory transaction lock. Both writers share this write-ahead/CAS protocol. */
107
+ async commit(store: JsonStore<MemoryEntry>, fingerprint: string, receipt: OptimizeReceipt | undefined,
108
+ mutate: (entries: MemoryEntry[]) => MemoryEntry[], assertCurrent: () => void = () => {}): Promise<{ entries: MemoryEntry[]; warning?: string }> {
109
+ return this.exclusive(async () => {
110
+ assertCurrent();
111
+ if ((await store.inspectStrict()).fingerprint !== fingerprint) throw new StoreConflictError();
112
+ if (receipt) await this.prepare({ ...receipt, fingerprint }, fingerprint);
113
+ let callbackRejected = false;
114
+ let entries: MemoryEntry[];
115
+ try {
116
+ entries = (await store.compareAndUpdate(fingerprint, (current) => {
117
+ try { assertCurrent(); return mutate(current); }
118
+ catch (error) { callbackRejected = true; throw error; }
119
+ })).entries;
120
+ } catch (error) {
121
+ if (receipt) {
122
+ // Capacity is checked during serialization, before any write. Any other error may follow
123
+ // the rename, so only memory bytes still identical to the prepared fingerprint show that the
124
+ // replacement is not in effect (it never landed, or backup recovery rolled it back); a changed
125
+ // or unreadable store keeps the only before image prepared.
126
+ const unwritten = callbackRejected || error instanceof StoreConflictError || error instanceof StoreCapacityError
127
+ || await store.inspectStrict().then((current) => current.fingerprint === fingerprint, () => false);
128
+ if (unwritten) await this.settle(receipt.receiptId, "rejected").catch(() => {});
129
+ else throw new Error(`memory replacement outcome uncertain; durable receipt ${receipt.receiptId} remains prepared: ${error instanceof Error ? error.message : "storage failure"}`);
130
+ }
131
+ throw error;
132
+ }
133
+ if (receipt) {
134
+ try { await this.settle(receipt.receiptId, "applied"); }
135
+ catch { return { entries, warning: "replacement committed; durable receipt remains prepared because history finalization failed" }; }
136
+ }
137
+ return { entries };
138
+ });
139
+ }
79
140
  }
80
141
 
81
142
  /** Revert only exact affected rows, never a whole historical snapshot. */
82
143
  export function restoreReceipt(entries: readonly MemoryEntry[], receipt: OptimizeReceipt, persona: string, now: number): { ok: true; entries: MemoryEntry[]; restored: number } | OptimizeFailure {
83
144
  if (receipt.persona !== persona) return { ok: false, reason: "receipt belongs to a different persona owner" };
145
+ if (receipt.origin === "replacement") return { ok: false, reason: "ordinary replacement history is read-only; optimizer undo is unavailable for this receipt" };
84
146
  if (receipt.state === "undone" || receipt.state === "rejected") return { ok: false, reason: "receipt was already undone or its replacement was rejected" };
85
147
  const before = receipt.changes.flatMap((change) => change.before);
86
148
  const after = receipt.changes.map((change) => change.after);
@@ -1,14 +1,14 @@
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
3
  import { isExpired, isSafeMemoryContent, MAX_RECALL_QUERY_CHARS, type MemoryEntry } from "./memory.ts";
4
- import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeUndone } from "./optimize-history.ts";
4
+ import { MAX_OPTIMIZE_HISTORY, MAX_OPTIMIZE_HISTORY_BYTES, OptimizeHistoryStore, restoreReceipt, type OptimizeHistory, type OptimizeReceipt, type OptimizeReceiptDetail, type OptimizeUndone } from "./optimize-history.ts";
5
5
  import {
6
6
  isOptimizeTarget, MAX_OPTIMIZE_ENTRIES, MAX_OPTIMIZE_PLANS, OPTIMIZE_PLAN_TTL_MS,
7
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";
11
- import { DEFAULT_STORE_MAX_ENTRIES, type JsonStore, StoreConflictError, withFileLock } from "./store.ts";
11
+ import { DEFAULT_STORE_MAX_ENTRIES, type JsonStore, withFileLock } from "./store.ts";
12
12
 
13
13
  export interface MemoryOptimizerOptions {
14
14
  stores: Record<OptimizeTarget, JsonStore<MemoryEntry>>;
@@ -90,38 +90,23 @@ export class MemoryOptimizer {
90
90
  try {
91
91
  let receiptId: string | undefined;
92
92
  let warning: string | undefined;
93
- const commit = async () => this.historyStore(staged.plan.target).exclusive(async () => {
93
+ const commit = async () => {
94
94
  const assertCurrent = () => {
95
95
  if (this.plans.get(planId) !== staged || this.now() >= Date.parse(staged.plan.expiresAt)) throw new Error("plan expired or invalidated; inspect and stage again");
96
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");
97
+ assertEvidenceFresh?.();
97
98
  };
98
- assertCurrent();
99
- assertEvidenceFresh?.();
100
99
  const store = this.options.stores[staged.plan.target];
101
- if ((await store.inspectStrict()).fingerprint !== staged.plan.fingerprint) throw new StoreConflictError();
102
100
  const history = this.historyStore(staged.plan.target);
101
+ let receipt: OptimizeReceipt | undefined;
103
102
  if (staged.plan.changes.length) {
104
103
  receiptId = randomUUID();
105
- const receipt: OptimizeReceipt = { receiptId, planId, target: staged.plan.target, persona: this.options.persona, createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: structuredClone(staged.plan.changes) };
106
- await history.prepare(receipt);
107
- }
108
- let callbackRejected = false;
109
- try {
110
- await store.compareAndUpdate(staged.plan.fingerprint, () => {
111
- try { assertCurrent(); assertEvidenceFresh?.(); return structuredClone(staged.next); }
112
- catch (error) { callbackRejected = true; throw error; }
113
- });
114
- } catch (error) {
115
- // A generic IO failure may occur after rename. Preserve its prepared before images.
116
- if (receiptId && (callbackRejected || error instanceof StoreConflictError)) await history.settle(receiptId, "rejected").catch(() => {});
117
- throw error;
104
+ receipt = { receiptId, planId, origin: "optimization", target: staged.plan.target, persona: this.options.persona, createdAt: new Date(this.now()).toISOString(), state: "prepared", storePath: store.filePath, changes: structuredClone(staged.plan.changes) };
118
105
  }
106
+ const result = await history.commit(store, staged.plan.fingerprint, receipt, () => structuredClone(staged.next), assertCurrent);
119
107
  this.plans.delete(planId);
120
- if (receiptId) {
121
- try { await history.settle(receiptId, "applied"); }
122
- catch { warning = "replacement committed; durable receipt remains prepared because history finalization failed"; }
123
- }
124
- });
108
+ warning = result.warning;
109
+ };
125
110
  if (this.options.mutationLock) await withFileLock(this.options.mutationLock, commit); else await commit();
126
111
  return { ok: true, planId, target: staged.plan.target, changed: staged.plan.changes.length, beforeCount: staged.plan.beforeCount, afterCount: staged.plan.afterCount, ...(receiptId ? { receiptId } : {}), ...(warning ? { warning } : {}) };
127
112
  } catch (error) { return failure(error); }
@@ -139,6 +124,15 @@ export class MemoryOptimizer {
139
124
  } catch (error) { return failure(error); }
140
125
  }
141
126
 
127
+ /** Exact, bounded read through the same owner/content filters as history; no active-store IO. */
128
+ async getReceipt(receiptId: string, target: OptimizeTarget): Promise<OptimizeReceiptDetail | OptimizeFailure> {
129
+ if (typeof receiptId !== "string" || !/^[\da-f-]{36}$/i.test(receiptId)) return { ok: false, reason: "invalid memory receipt id" };
130
+ const history = await this.history(target, MAX_OPTIMIZE_HISTORY);
131
+ if (!history.ok) return history;
132
+ const receipt = history.receipts.find((entry) => entry.receiptId === receiptId);
133
+ return receipt ? { ok: true, target, receipt } : { ok: false, reason: "memory receipt not found in this scope, unsafe, or no longer retained" };
134
+ }
135
+
142
136
  async undo(receiptId: string, target?: OptimizeTarget): Promise<OptimizeUndone | OptimizeFailure> {
143
137
  const generation = this.generation;
144
138
  if (target !== undefined && !isOptimizeTarget(target)) return { ok: false, reason: "unknown memory optimizer target" };
@@ -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,47 @@ 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
+ // Expand only stored tail words: expanding queries would make partial versions match.
96
+ const tail = word.match(/^[vV]?\d+(?:\.\d+)+[-+](.*)$/u)?.[1];
97
+ // Tail qualifiers do not express negation; ordinary occurrences remain searchable.
98
+ const tailWords = tail?.split(/[-+.]/).filter((part) => /^\p{L}+$/u.test(part))
99
+ .flatMap(words).filter((part) => !NEGATION_AND_EXCEPTION.has(part.toLowerCase())) ?? [];
100
+ for (const token of [word, ...tailWords]) {
101
+ exact.add(token.toLowerCase());
102
+ for (const part of components(token)) normalized.add(part);
103
+ }
104
+ }
105
+ return { exact, normalized };
106
+ }
107
+
108
+ function rankItem<T extends RetrievalSource>(entry: T, terms: readonly QueryTerm[], paths: readonly string[]): RetrievalRank<T> {
109
+ if (terms.length === 0) {
110
+ const pathMatches = entryPathMatches(entry, paths);
111
+ return { entry, score: pathMatches.length * 12, textTerms: [], tagTerms: [], pathMatches, normalizedTerms: [] };
112
+ }
113
+ const textWords = vocabulary(entry.text);
114
+ const tagWords = vocabulary((entry.tags ?? []).join(" "));
115
+ const textTerms: string[] = [];
116
+ const tagTerms: string[] = [];
117
+ const normalizedTerms: string[] = [];
118
+ let lexicalScore = 0;
119
+ for (const { original, components: parts } of terms) {
120
+ const negation = NEGATION_AND_EXCEPTION.has(original);
121
+ if (textWords.exact.has(original)) { textTerms.push(original); lexicalScore += negation ? 4 : 3; }
122
+ else if (tagWords.exact.has(original)) { tagTerms.push(original); lexicalScore += negation ? 3 : 2; }
123
+ else if (parts.every((part) => textWords.normalized.has(part))) {
124
+ textTerms.push(original); normalizedTerms.push(original); lexicalScore += 1;
125
+ } else if (parts.every((part) => tagWords.normalized.has(part))) {
126
+ tagTerms.push(original); normalizedTerms.push(original); lexicalScore += 0.75;
127
+ }
128
+ }
72
129
  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 };
130
+ const score = lexicalScore + pathMatches.length * 12;
131
+ return { entry, score, textTerms, tagTerms, pathMatches, normalizedTerms };
77
132
  }
78
133
 
79
134
  /** Rank generic text/tag entries; optional ties are resolved by the supplied domain comparator. */