@aeondave/pi-persona-mind 0.9.3 → 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.
- package/AGENTS.md +135 -131
- package/CHANGELOG.md +253 -220
- package/README.md +170 -169
- package/docs/DESIGN.md +550 -520
- package/docs/MEMORY-RESEARCH.md +9 -5
- package/package.json +90 -90
- package/src/core/handoff-store.ts +45 -4
- package/src/core/optimize-history.ts +27 -7
- package/src/core/retrieval.ts +9 -2
- package/src/core/service.ts +29 -6
- package/src/core/store.ts +87 -39
- package/src/extension/auto-optimize-session.ts +3 -2
- package/src/extension/auto-optimize.ts +107 -35
- package/src/extension/knowledge-review.ts +20 -6
- package/src/index.ts +4 -1
- package/src/tools/memory-history.ts +1 -1
package/docs/MEMORY-RESEARCH.md
CHANGED
|
@@ -34,16 +34,20 @@ injection. This is explainable and avoids an additional indexing service, but di
|
|
|
34
34
|
queries may miss relevant facts. No general semantic-recall guarantee follows from a passing test.
|
|
35
35
|
|
|
36
36
|
Identifier components and vowel-accent folding are lower-weight fallback matches, behind exact
|
|
37
|
-
words and paths. Numeric versions stay
|
|
37
|
+
words and paths. Numeric versions stay exact atoms; alphabetic tail words are also indexed at ordinary
|
|
38
|
+
word weight, while numeric or digit-bearing tail parts stay inside the atom. Negation remains searchable, and Unicode/CJK
|
|
38
39
|
segmentation is preserved. A fallback can still add irrelevant rows: fewer missed identifiers does
|
|
39
40
|
not imply perfect precision. Tags already normalized when saved cannot recover lost camel casing.
|
|
40
41
|
|
|
41
42
|
`npm run eval:memory` compares the previous ranker and injection renderer with the current ones on
|
|
42
43
|
the same corpus, scope and budget. In the 12-case development fixture, positive top-one hits improve
|
|
43
|
-
from 2/7 to 7/7; in
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
from 2/7 to 7/7; in the separate nine-case held-out set, they improve from 6/7 to 7/7.
|
|
45
|
+
The held-out set was written alongside the implementation, not withheld from it.
|
|
46
|
+
Negative queries with results fall from one to zero in each set. Strict false positives among the top
|
|
47
|
+
three, ignoring `acceptableIds`, remain 1 to 1 in development and 5 to 5 in the held-out set.
|
|
48
|
+
With acceptable labels, the counts are 1 to 1 and 5 to 3 respectively; that held-out reduction depends
|
|
49
|
+
on the labels excusing weaker accent matches. A weak `memory`/`memoryOwnership` match remains.
|
|
50
|
+
The preceding 30-case fixture's metrics and
|
|
47
51
|
seven sentinel outcomes are unchanged. These small synthetic sets and their labels are inspectable
|
|
48
52
|
regression evidence, not an external benchmark or a general semantic-quality claim.
|
|
49
53
|
|
package/package.json
CHANGED
|
@@ -1,90 +1,90 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@aeondave/pi-persona-mind",
|
|
3
|
-
"version": "0.9.
|
|
4
|
-
"private": false,
|
|
5
|
-
"type": "module",
|
|
6
|
-
"description": "Local memory for Pi with pi-persona
|
|
7
|
-
"keywords": [
|
|
8
|
-
"pi-package",
|
|
9
|
-
"pi-extension",
|
|
10
|
-
"pi-coding-agent",
|
|
11
|
-
"pi",
|
|
12
|
-
"memory",
|
|
13
|
-
"agent-memory",
|
|
14
|
-
"persistent-memory",
|
|
15
|
-
"persona",
|
|
16
|
-
"long-term-memory",
|
|
17
|
-
"short-term-memory",
|
|
18
|
-
"backlog",
|
|
19
|
-
"pi-persona"
|
|
20
|
-
],
|
|
21
|
-
"author": "AeonDave",
|
|
22
|
-
"license": "MIT",
|
|
23
|
-
"repository": {
|
|
24
|
-
"type": "git",
|
|
25
|
-
"url": "git+https://github.com/AeonDave/pi-persona-mind.git"
|
|
26
|
-
},
|
|
27
|
-
"homepage": "https://github.com/AeonDave/pi-persona-mind#readme",
|
|
28
|
-
"bugs": {
|
|
29
|
-
"url": "https://github.com/AeonDave/pi-persona-mind/issues"
|
|
30
|
-
},
|
|
31
|
-
"publishConfig": {
|
|
32
|
-
"access": "public"
|
|
33
|
-
},
|
|
34
|
-
"files": [
|
|
35
|
-
"src",
|
|
36
|
-
"docs/DESIGN.md",
|
|
37
|
-
"docs/MEMORY-RESEARCH.md",
|
|
38
|
-
"assets/banner.png",
|
|
39
|
-
"README.md",
|
|
40
|
-
"CHANGELOG.md",
|
|
41
|
-
"AGENTS.md",
|
|
42
|
-
"LICENSE"
|
|
43
|
-
],
|
|
44
|
-
"main": "src/index.ts",
|
|
45
|
-
"engines": {
|
|
46
|
-
"node": ">=22.19.0"
|
|
47
|
-
},
|
|
48
|
-
"scripts": {
|
|
49
|
-
"typecheck": "tsc --noEmit",
|
|
50
|
-
"test": "node --import tsx --import ./test/setup/hermetic-env.ts --test test/*.test.ts",
|
|
51
|
-
"eval:memory": "node --import tsx scripts/evaluate-memory.ts",
|
|
52
|
-
"verify": "npm run typecheck && npm test"
|
|
53
|
-
},
|
|
54
|
-
"pi": {
|
|
55
|
-
"image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.
|
|
56
|
-
"extensions": [
|
|
57
|
-
"./src/index.ts"
|
|
58
|
-
]
|
|
59
|
-
},
|
|
60
|
-
"peerDependencies": {
|
|
61
|
-
"@aeondave/pi-persona": ">=1.18.1",
|
|
62
|
-
"@earendil-works/pi-coding-agent": "*",
|
|
63
|
-
"@earendil-works/pi-tui": "*",
|
|
64
|
-
"typebox": "*"
|
|
65
|
-
},
|
|
66
|
-
"peerDependenciesMeta": {
|
|
67
|
-
"@aeondave/pi-persona": {
|
|
68
|
-
"optional": true
|
|
69
|
-
},
|
|
70
|
-
"@earendil-works/pi-coding-agent": {
|
|
71
|
-
"optional": true
|
|
72
|
-
},
|
|
73
|
-
"@earendil-works/pi-tui": {
|
|
74
|
-
"optional": true
|
|
75
|
-
},
|
|
76
|
-
"typebox": {
|
|
77
|
-
"optional": true
|
|
78
|
-
}
|
|
79
|
-
},
|
|
80
|
-
"devDependencies": {
|
|
81
|
-
"@earendil-works/pi-agent-core": "1.6.0",
|
|
82
|
-
"@earendil-works/pi-ai": "1.6.0",
|
|
83
|
-
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
84
|
-
"@earendil-works/pi-tui": "1.6.0",
|
|
85
|
-
"@types/node": "^22.0.0",
|
|
86
|
-
"tsx": "^4.19.0",
|
|
87
|
-
"typebox": "*",
|
|
88
|
-
"typescript": "^7.0.2"
|
|
89
|
-
}
|
|
90
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@aeondave/pi-persona-mind",
|
|
3
|
+
"version": "0.9.4",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "Local memory for Pi with pi-persona — durable project and persona facts, session notes, bounded retrieval, and supervised automatic consolidation.",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi-extension",
|
|
10
|
+
"pi-coding-agent",
|
|
11
|
+
"pi",
|
|
12
|
+
"memory",
|
|
13
|
+
"agent-memory",
|
|
14
|
+
"persistent-memory",
|
|
15
|
+
"persona",
|
|
16
|
+
"long-term-memory",
|
|
17
|
+
"short-term-memory",
|
|
18
|
+
"backlog",
|
|
19
|
+
"pi-persona"
|
|
20
|
+
],
|
|
21
|
+
"author": "AeonDave",
|
|
22
|
+
"license": "MIT",
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/AeonDave/pi-persona-mind.git"
|
|
26
|
+
},
|
|
27
|
+
"homepage": "https://github.com/AeonDave/pi-persona-mind#readme",
|
|
28
|
+
"bugs": {
|
|
29
|
+
"url": "https://github.com/AeonDave/pi-persona-mind/issues"
|
|
30
|
+
},
|
|
31
|
+
"publishConfig": {
|
|
32
|
+
"access": "public"
|
|
33
|
+
},
|
|
34
|
+
"files": [
|
|
35
|
+
"src",
|
|
36
|
+
"docs/DESIGN.md",
|
|
37
|
+
"docs/MEMORY-RESEARCH.md",
|
|
38
|
+
"assets/banner.png",
|
|
39
|
+
"README.md",
|
|
40
|
+
"CHANGELOG.md",
|
|
41
|
+
"AGENTS.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"main": "src/index.ts",
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=22.19.0"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"typecheck": "tsc --noEmit",
|
|
50
|
+
"test": "node --import tsx --import ./test/setup/hermetic-env.ts --test test/*.test.ts",
|
|
51
|
+
"eval:memory": "node --import tsx scripts/evaluate-memory.ts",
|
|
52
|
+
"verify": "npm run typecheck && npm test"
|
|
53
|
+
},
|
|
54
|
+
"pi": {
|
|
55
|
+
"image": "https://raw.githubusercontent.com/AeonDave/pi-persona-mind/v0.9.4/assets/banner.png",
|
|
56
|
+
"extensions": [
|
|
57
|
+
"./src/index.ts"
|
|
58
|
+
]
|
|
59
|
+
},
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"@aeondave/pi-persona": ">=1.18.1",
|
|
62
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
63
|
+
"@earendil-works/pi-tui": "*",
|
|
64
|
+
"typebox": "*"
|
|
65
|
+
},
|
|
66
|
+
"peerDependenciesMeta": {
|
|
67
|
+
"@aeondave/pi-persona": {
|
|
68
|
+
"optional": true
|
|
69
|
+
},
|
|
70
|
+
"@earendil-works/pi-coding-agent": {
|
|
71
|
+
"optional": true
|
|
72
|
+
},
|
|
73
|
+
"@earendil-works/pi-tui": {
|
|
74
|
+
"optional": true
|
|
75
|
+
},
|
|
76
|
+
"typebox": {
|
|
77
|
+
"optional": true
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
"devDependencies": {
|
|
81
|
+
"@earendil-works/pi-agent-core": "1.6.0",
|
|
82
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
83
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
84
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
85
|
+
"@types/node": "^22.0.0",
|
|
86
|
+
"tsx": "^4.19.0",
|
|
87
|
+
"typebox": "*",
|
|
88
|
+
"typescript": "^7.0.2"
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { isAbsolute, relative } from "node:path";
|
|
3
3
|
import { canonicalProjectIdentity, type Scope } from "./scope.ts";
|
|
4
|
-
import { JsonStore, StoreConflictError } from "./store.ts";
|
|
4
|
+
import { BoundedReadFailure, JsonStore, StoreCapacityError, StoreConflictError, StoreVersionError } from "./store.ts";
|
|
5
5
|
import { MAX_HANDOFF_ENTRIES, MAX_HANDOFF_GOAL_PREVIEW_CHARS, MAX_HANDOFF_RECORD_BYTES, MAX_HANDOFF_STORE_BYTES, validContext, validHandoffContent, validateHandoff, validResolution, type HandoffContext, type HandoffEntry, type HandoffInput } from "./handoff.ts";
|
|
6
6
|
|
|
7
7
|
export type HandoffResult =
|
|
@@ -14,7 +14,8 @@ export class HandoffStore {
|
|
|
14
14
|
private readonly store: JsonStore<HandoffEntry>;
|
|
15
15
|
constructor(privateScope: Scope) {
|
|
16
16
|
this.scope = privateScope;
|
|
17
|
-
|
|
17
|
+
// The byte cap bounds the shared file; entry quotas belong to each owner.
|
|
18
|
+
this.store = new JsonStore(`${privateScope.paths.stm}.handoffs.json`, { version: 1, validateEntry: validateHandoff, maxEntries: Number.MAX_SAFE_INTEGER, maxBytes: MAX_HANDOFF_STORE_BYTES });
|
|
18
19
|
}
|
|
19
20
|
private readonly scope: Scope;
|
|
20
21
|
|
|
@@ -41,6 +42,8 @@ export class HandoffStore {
|
|
|
41
42
|
}
|
|
42
43
|
let entry: HandoffEntry;
|
|
43
44
|
if (input.operation === "save") {
|
|
45
|
+
// CAS rechecks this snapshot under the lock, so concurrent saves cannot exceed the quota.
|
|
46
|
+
if (owned.length >= MAX_HANDOFF_ENTRIES) return { ok: false, reason: `handoff quota of ${MAX_HANDOFF_ENTRIES} entries reached for this persona in this project; use forget to free space` };
|
|
44
47
|
const now = new Date().toISOString();
|
|
45
48
|
entry = { id: randomBytes(16).toString("hex"), revision: 1, persona: context.persona, projectRoot: canonicalProjectIdentity(context.projectRoot), origin: { sessionId: context.sessionId, branchId: context.branchId, cwd: context.cwd }, createdAt: now, updatedAt: now, status: "open", goal: input.goal, completed: [...input.completed], pending: [...input.pending], nextStep: input.nextStep, references: [...input.references] };
|
|
46
49
|
} else {
|
|
@@ -62,9 +65,47 @@ export class HandoffStore {
|
|
|
62
65
|
if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed after commit; inspect the original scope" };
|
|
63
66
|
if (input.operation === "forget") return { ok: true, operation: "forget" };
|
|
64
67
|
return { ok: true, operation: input.operation, entry };
|
|
65
|
-
} catch (error) {
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error instanceof StoreConflictError) continue;
|
|
70
|
+
if (error instanceof StoreCapacityError && error.kind === "bytes") {
|
|
71
|
+
const otherEntries = snapshot.store.entries.filter((e) => e.persona !== context.persona);
|
|
72
|
+
// Match JsonStore's envelope, indentation and newline: could this operation fit
|
|
73
|
+
// if the caller freed every existing entry they own?
|
|
74
|
+
const afterForgetting = { ...snapshot.store, sequence: snapshot.store.sequence + 1, updatedAt: new Date().toISOString(),
|
|
75
|
+
entries: input.operation === "forget" ? otherEntries : [...otherEntries, entry] };
|
|
76
|
+
const othersBlock = Buffer.byteLength(`${JSON.stringify(afterForgetting, null, 2)}\n`, "utf8") > error.limit;
|
|
77
|
+
const counts = `your entries: ${owned.length}; other personas: ${otherEntries.length} entries`;
|
|
78
|
+
const remedy = owned.length > 0 ? "; use forget to free space" : "";
|
|
79
|
+
return { ok: false, reason: othersBlock
|
|
80
|
+
? `other personas' handoffs fill this project's handoff file ${this.store.filePath} (${counts}); ${error.limit}-byte limit exceeded${remedy}`
|
|
81
|
+
: `handoff file ${this.store.filePath} exceeds ${error.limit} bytes (${counts})${remedy}` };
|
|
82
|
+
}
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
66
85
|
}
|
|
67
86
|
return { ok: false, reason: "handoff store busy; retry" };
|
|
68
|
-
} catch (error) {
|
|
87
|
+
} catch (error) {
|
|
88
|
+
const file = `handoff file ${this.store.filePath}`;
|
|
89
|
+
if (error instanceof BoundedReadFailure) {
|
|
90
|
+
return { ok: false, reason: error.kind === "path"
|
|
91
|
+
? `${file} has an unsafe or changing path; repair it as a regular file and retry`
|
|
92
|
+
: `${file} exceeds safe read limits or changed size while being read; repair it within the ${MAX_HANDOFF_STORE_BYTES}-byte limit and retry` };
|
|
93
|
+
}
|
|
94
|
+
if (error instanceof StoreVersionError) {
|
|
95
|
+
return { ok: false, reason: `${file} uses version ${error.found}, but this build reads version ${error.expected}; use a compatible build; the file is left untouched` };
|
|
96
|
+
}
|
|
97
|
+
// JsonStore's two untyped strict-read refusals are covered by real-file regression
|
|
98
|
+
// cases, so a change to either upstream message cannot silently lose this mapping.
|
|
99
|
+
if (error instanceof Error && error.message === "memory store is missing with a recoverable backup; repair before optimizing") {
|
|
100
|
+
return { ok: false, reason: `${file} is missing while ${this.store.filePath}.bak exists; inspect the backup and repair the handoff file by hand` };
|
|
101
|
+
}
|
|
102
|
+
if (error instanceof Error && error.message === "memory store is corrupt or contains invalid entries; repair before optimizing") {
|
|
103
|
+
return { ok: false, reason: `${file} is corrupt or contains invalid entries; repair or remove the invalid entry by hand` };
|
|
104
|
+
}
|
|
105
|
+
if (error instanceof Error && "code" in error && typeof error.code === "string") {
|
|
106
|
+
return { ok: false, reason: `${file} cannot be accessed (${error.code}); check the path and permissions, repair access and retry` };
|
|
107
|
+
}
|
|
108
|
+
return { ok: false, reason: error instanceof Error ? error.message : "handoff storage failure" };
|
|
109
|
+
}
|
|
69
110
|
}
|
|
70
111
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
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, StoreConflictError, 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;
|
|
@@ -13,6 +13,8 @@ interface ReceiptBase {
|
|
|
13
13
|
/** Prepared may mean interrupted before OR after memory commit; exact facts decide undo. */
|
|
14
14
|
state: "prepared" | "applied" | "undone" | "rejected";
|
|
15
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;
|
|
16
18
|
changes: OptimizeChange[];
|
|
17
19
|
}
|
|
18
20
|
/** Missing origin is the existing persisted optimizer contract, never an ordinary replacement. */
|
|
@@ -40,6 +42,7 @@ function validateReceipt(raw: unknown): OptimizeReceipt | null {
|
|
|
40
42
|
if (!Number.isFinite(createdAt) || new Date(createdAt).toISOString() !== value.createdAt) return null;
|
|
41
43
|
if (!["prepared", "applied", "undone", "rejected"].includes(value.state ?? "")) return null;
|
|
42
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;
|
|
43
46
|
if (!Array.isArray(value.changes) || !value.changes.length || value.changes.length > MAX_OPTIMIZE_OPERATIONS) return null;
|
|
44
47
|
const changes: OptimizeChange[] = [];
|
|
45
48
|
const sourceIds = new Set<string>(); const replacementIds = new Set<string>();
|
|
@@ -56,7 +59,7 @@ function validateReceipt(raw: unknown): OptimizeReceipt | null {
|
|
|
56
59
|
replacementIds.add(after.id); changes.push({ before, after });
|
|
57
60
|
}
|
|
58
61
|
const receipt: ReceiptBase = { receiptId: value.receiptId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
|
|
59
|
-
state: value.state!, storePath: value.storePath, changes };
|
|
62
|
+
state: value.state!, storePath: value.storePath, ...(value.fingerprint === undefined ? {} : { fingerprint: value.fingerprint }), changes };
|
|
60
63
|
return value.origin === "replacement" ? { ...receipt, origin: "replacement" } : { ...receipt, origin: "optimization", planId: value.planId! };
|
|
61
64
|
}
|
|
62
65
|
|
|
@@ -70,13 +73,25 @@ export class OptimizeHistoryStore {
|
|
|
70
73
|
}
|
|
71
74
|
async exclusive<T>(run: () => Promise<T>): Promise<T> { return withFileLock(`${this.path}.transaction.lock`, run); }
|
|
72
75
|
async read(): Promise<OptimizeReceipt[]> { return (await this.store.inspectStrict()).store.entries; }
|
|
73
|
-
|
|
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> {
|
|
74
78
|
const snapshot = await this.store.inspectStrict();
|
|
75
|
-
|
|
79
|
+
let entries = [...snapshot.store.entries, receipt];
|
|
76
80
|
// Only settled history can be evicted. An unresolved crash intent may own the only before image.
|
|
77
81
|
const bytes = () => Buffer.byteLength(`${JSON.stringify({ ...snapshot.store, sequence: snapshot.store.sequence + 1, entries }, null, 2)}\n`, "utf8");
|
|
82
|
+
let resolved = false;
|
|
78
83
|
while (entries.length > MAX_OPTIMIZE_HISTORY || bytes() > MAX_OPTIMIZE_HISTORY_BYTES) {
|
|
79
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
|
+
}
|
|
80
95
|
if (index < 0) throw new Error("optimizer history capacity exhausted by recovery receipts; replacement refused");
|
|
81
96
|
entries.splice(index, 1);
|
|
82
97
|
}
|
|
@@ -94,7 +109,7 @@ export class OptimizeHistoryStore {
|
|
|
94
109
|
return this.exclusive(async () => {
|
|
95
110
|
assertCurrent();
|
|
96
111
|
if ((await store.inspectStrict()).fingerprint !== fingerprint) throw new StoreConflictError();
|
|
97
|
-
if (receipt) await this.prepare(receipt);
|
|
112
|
+
if (receipt) await this.prepare({ ...receipt, fingerprint }, fingerprint);
|
|
98
113
|
let callbackRejected = false;
|
|
99
114
|
let entries: MemoryEntry[];
|
|
100
115
|
try {
|
|
@@ -103,9 +118,14 @@ export class OptimizeHistoryStore {
|
|
|
103
118
|
catch (error) { callbackRejected = true; throw error; }
|
|
104
119
|
})).entries;
|
|
105
120
|
} catch (error) {
|
|
106
|
-
// Generic IO errors can follow rename: never discard the only before image.
|
|
107
121
|
if (receipt) {
|
|
108
|
-
|
|
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(() => {});
|
|
109
129
|
else throw new Error(`memory replacement outcome uncertain; durable receipt ${receipt.receiptId} remains prepared: ${error instanceof Error ? error.message : "storage failure"}`);
|
|
110
130
|
}
|
|
111
131
|
throw error;
|
package/src/core/retrieval.ts
CHANGED
|
@@ -92,8 +92,15 @@ function vocabulary(value: string): { exact: ReadonlySet<string>; normalized: Re
|
|
|
92
92
|
const exact = new Set<string>();
|
|
93
93
|
const normalized = new Set<string>();
|
|
94
94
|
for (const word of new Set(words(value))) {
|
|
95
|
-
|
|
96
|
-
|
|
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
|
+
}
|
|
97
104
|
}
|
|
98
105
|
return { exact, normalized };
|
|
99
106
|
}
|
package/src/core/service.ts
CHANGED
|
@@ -23,7 +23,7 @@ import type { MemoryEntry, MemoryInput, MemoryKind } from "./memory.ts";
|
|
|
23
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";
|
|
24
24
|
import { scanContent } from "./scanner.ts";
|
|
25
25
|
import { memoryMutationLockPath, type Scope } from "./scope.ts";
|
|
26
|
-
import { JsonStore, type JsonStoreOptions, withFileLock } from "./store.ts";
|
|
26
|
+
import { JsonStore, type JsonStoreOptions, type StoreFile, withFileLock } from "./store.ts";
|
|
27
27
|
|
|
28
28
|
const STORE_VERSION = 1;
|
|
29
29
|
|
|
@@ -315,16 +315,39 @@ export class MindService {
|
|
|
315
315
|
if (!this.rememberOwnerCurrent()) throw new Error("memory owner changed; remember refused before commit");
|
|
316
316
|
}
|
|
317
317
|
|
|
318
|
+
/**
|
|
319
|
+
* Tolerant read that must have seen every row: a clean read, an absent tier, or a full restore from a valid
|
|
320
|
+
* backup. Rows that were preserved but hidden, a quarantine that started the tier empty, or a backup that
|
|
321
|
+
* exists but could not be used could hold the very id being superseded, so they refuse instead of passing as
|
|
322
|
+
* an empty tier.
|
|
323
|
+
*/
|
|
324
|
+
private async loadCompletely(store: JsonStore<MemoryEntry>): Promise<StoreFile<MemoryEntry>> {
|
|
325
|
+
const refuse = (detail: string): Error => new Error(`memory store ${store.filePath} was not read completely, so it cannot be checked for an ambiguous supersedes id: ${detail}`);
|
|
326
|
+
let read;
|
|
327
|
+
try {
|
|
328
|
+
read = await store.loadChecked();
|
|
329
|
+
} catch (err) {
|
|
330
|
+
throw refuse(err instanceof Error ? err.message : String(err));
|
|
331
|
+
}
|
|
332
|
+
if (!read.complete) throw refuse(read.reasons.join("; "));
|
|
333
|
+
return read.file;
|
|
334
|
+
}
|
|
335
|
+
|
|
318
336
|
/** Under the memory transaction lock: resolve across tiers, but retire only in the destination. */
|
|
319
337
|
private async rememberSuperseding(entry: MemoryEntry, target: OptimizeTarget): Promise<RememberResult> {
|
|
320
|
-
const stores = Object.values(this.memoryStores());
|
|
321
338
|
const store = this.memoryStores()[target];
|
|
322
|
-
//
|
|
323
|
-
|
|
324
|
-
|
|
339
|
+
// The destination is compare-and-swapped, so only its strict snapshot may anchor the write. The other
|
|
340
|
+
// tiers merely feed the ambiguity check, so they are read without blocking on repairable damage: a clean
|
|
341
|
+
// read or a full restore from the backup counts. Any tier whose identities were not all checked (hidden
|
|
342
|
+
// rows, quarantine, foreign version, I/O error) could hide the id being superseded, so it refuses, naming the store.
|
|
343
|
+
const snapshot = await store.inspectStrict().catch((err: unknown) => {
|
|
344
|
+
throw new Error(`destination memory store ${store.filePath}: ${(err instanceof Error ? err.message : String(err)).replace("; repair before optimizing", "; repair it before replacing a memory")}`);
|
|
345
|
+
});
|
|
346
|
+
const others = await Promise.all(Object.values(this.memoryStores()).filter((memoryStore) => memoryStore !== store).map((memoryStore) =>
|
|
347
|
+
this.loadCompletely(memoryStore)));
|
|
348
|
+
const visible = [snapshot.store, ...others].flatMap((file) => pruneExpired(file.entries, this.now()));
|
|
325
349
|
const resolved = supersedeTargets(visible, entry.supersedes!);
|
|
326
350
|
if (resolved.ambiguous) return { ok: false, reason: ambiguousSupersedesReason(entry.supersedes!, ambiguityCandidates(visible, entry.supersedes!)) };
|
|
327
|
-
const snapshot = loaded[stores.indexOf(store)]!;
|
|
328
351
|
const active = pruneExpired(snapshot.store.entries, this.now());
|
|
329
352
|
if (resolved.targets.length > 0 && !active.some((candidate) => memoryIdMatches(candidate, entry.supersedes!))) {
|
|
330
353
|
return { ok: false, reason: "memory supersedes id exists only outside the destination tier; use the source's scope and lifetime to replace it" };
|
package/src/core/store.ts
CHANGED
|
@@ -34,6 +34,17 @@ export interface StoreFile<E> {
|
|
|
34
34
|
entries: E[];
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/**
|
|
38
|
+
* A tolerant read together with whether it saw every row. `complete` is false when the result may be
|
|
39
|
+
* missing rows that exist on disk: rows hidden as invalid, a file quarantined to start empty, or an
|
|
40
|
+
* existing backup that could not be used while the live file is absent. `reasons` says why.
|
|
41
|
+
*/
|
|
42
|
+
export interface StoreRead<E> {
|
|
43
|
+
file: StoreFile<E>;
|
|
44
|
+
complete: boolean;
|
|
45
|
+
reasons: string[];
|
|
46
|
+
}
|
|
47
|
+
|
|
37
48
|
export interface StoreSnapshot<E> {
|
|
38
49
|
store: StoreFile<E>;
|
|
39
50
|
/** Binds the exact live bytes and store path, including same-sequence replacements. */
|
|
@@ -56,7 +67,13 @@ let lockSeq = 0;
|
|
|
56
67
|
// JsonStore.load(), but the next atomic rewrite can put them back verbatim instead of silently
|
|
57
68
|
// erasing data that the current validator does not understand yet.
|
|
58
69
|
const PRESERVED_INVALID_ENTRIES: unique symbol = Symbol("preservedInvalidEntries");
|
|
59
|
-
|
|
70
|
+
// Set on an empty store that stands in for data which exists but could not be read, so loadChecked()
|
|
71
|
+
// can tell it from a store that is genuinely empty. Never persisted.
|
|
72
|
+
const UNREAD_REASON: unique symbol = Symbol("unreadReason");
|
|
73
|
+
type InternalStoreFile<E> = StoreFile<E> & { [PRESERVED_INVALID_ENTRIES]?: unknown[]; [UNREAD_REASON]?: string };
|
|
74
|
+
|
|
75
|
+
/** What the `.bak` sidecar offers: nothing, a valid store, or a file that exists but cannot be used. */
|
|
76
|
+
type BackupRead<E> = { kind: "absent" } | { kind: "usable"; store: InternalStoreFile<E> } | { kind: "unusable"; reason: string };
|
|
60
77
|
|
|
61
78
|
export interface AtomicWriteOptions {
|
|
62
79
|
/** Refresh the `.bak` sidecar from the current live file only when this returns true for its
|
|
@@ -784,41 +801,49 @@ export class JsonStore<E> {
|
|
|
784
801
|
});
|
|
785
802
|
}
|
|
786
803
|
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
804
|
+
/** A missing backup is normal; one that exists but cannot be used is not, and is never repaired or moved. */
|
|
805
|
+
private async readBak(): Promise<BackupRead<E>> {
|
|
806
|
+
try {
|
|
807
|
+
const store = this.parseStore(await readTextFileBounded(`${this.filePath}.bak`, this.maxBytes));
|
|
808
|
+
return store ? { kind: "usable", store } : { kind: "unusable", reason: "unparseable or unexpected shape" };
|
|
809
|
+
} catch (err) {
|
|
810
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return { kind: "absent" };
|
|
811
|
+
return { kind: "unusable", reason: err instanceof Error ? err.message : String(err) };
|
|
794
812
|
}
|
|
795
|
-
|
|
796
|
-
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** Restore the last-known-good `.bak` over the live path. Only an unusable backup warns; an absent one is silent. */
|
|
816
|
+
private async recoverFromBak(reason: string): Promise<BackupRead<E>> {
|
|
817
|
+
const bak = await this.readBak();
|
|
818
|
+
if (bak.kind === "unusable") this.onWarn(`mind store: ${this.filePath}.bak rejected — ${bak.reason}`);
|
|
819
|
+
if (bak.kind !== "usable") return bak;
|
|
797
820
|
this.onWarn(`mind store: ${this.filePath} ${reason}; recovered from ${this.filePath}.bak`);
|
|
798
|
-
this.warnInvalidEntries(bak);
|
|
799
|
-
await this.restoreLive(bak);
|
|
821
|
+
this.warnInvalidEntries(bak.store);
|
|
822
|
+
await this.restoreLive(bak.store);
|
|
800
823
|
return bak;
|
|
801
824
|
}
|
|
802
825
|
|
|
803
|
-
/**
|
|
804
|
-
private
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
if (err instanceof BoundedReadFailure) {
|
|
809
|
-
this.onWarn(`mind store: ${this.filePath}.bak rejected — ${err.message}`);
|
|
810
|
-
}
|
|
811
|
-
return null;
|
|
812
|
-
}
|
|
826
|
+
/** Empty stand-in for data that exists but was not read, flagged so loadChecked() reports it incomplete. */
|
|
827
|
+
private unreadEmpty(reason: string): InternalStoreFile<E> {
|
|
828
|
+
const store: InternalStoreFile<E> = this.empty();
|
|
829
|
+
store[UNREAD_REASON] = reason;
|
|
830
|
+
return store;
|
|
813
831
|
}
|
|
814
832
|
|
|
815
|
-
|
|
833
|
+
/** An unreadable live file was set aside: announce it and start empty, flagged incomplete. */
|
|
834
|
+
private startEmpty(reason: string): InternalStoreFile<E> {
|
|
835
|
+
this.onWarn(`mind store: ${this.filePath} ${reason}`);
|
|
836
|
+
return this.unreadEmpty(reason);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
private invalidEntriesNote(store: InternalStoreFile<E>): string | null {
|
|
816
840
|
const count = store[PRESERVED_INVALID_ENTRIES]?.length ?? 0;
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
);
|
|
841
|
+
return count === 0 ? null : `contained ${count} invalid entr${count === 1 ? "y" : "ies"}; preserved raw and hidden from consumers`;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
private warnInvalidEntries(store: InternalStoreFile<E>): void {
|
|
845
|
+
const note = this.invalidEntriesNote(store);
|
|
846
|
+
if (note !== null) this.onWarn(`mind store: ${this.filePath} ${note}`);
|
|
822
847
|
}
|
|
823
848
|
|
|
824
849
|
private async recoverBoundedFailure(failure: BoundedReadFailure, lockToken?: string): Promise<InternalStoreFile<E>> {
|
|
@@ -827,13 +852,12 @@ export class JsonStore<E> {
|
|
|
827
852
|
// store lock before quarantine so a writer that repaired the path wins the race safely.
|
|
828
853
|
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
829
854
|
}
|
|
830
|
-
const bak = await this.recoverFromBak(`rejected — ${failure.message}
|
|
831
|
-
if (bak) return bak;
|
|
855
|
+
const bak = await this.recoverFromBak(`rejected — ${failure.message}`);
|
|
856
|
+
if (bak.kind === "usable") return bak.store;
|
|
832
857
|
const quarantineOptions: QuarantineOptions = {};
|
|
833
858
|
if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
|
|
834
859
|
const dest = await quarantineCorrupt(this.filePath, failure.message, quarantineOptions);
|
|
835
|
-
this.
|
|
836
|
-
return this.empty();
|
|
860
|
+
return this.startEmpty(`rejected — ${failure.message}; no usable backup, quarantined to ${dest ?? "(nowhere)"}, starting empty`);
|
|
837
861
|
}
|
|
838
862
|
|
|
839
863
|
private async loadInternal(lockToken?: string): Promise<InternalStoreFile<E>> {
|
|
@@ -842,8 +866,18 @@ export class JsonStore<E> {
|
|
|
842
866
|
raw = await readTextFileBounded(this.filePath, this.maxBytes);
|
|
843
867
|
} catch (err) {
|
|
844
868
|
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
845
|
-
|
|
846
|
-
|
|
869
|
+
if (lockToken === undefined) {
|
|
870
|
+
// Missing was only an optimistic observation: a writer may repair and commit while this reader
|
|
871
|
+
// waits. Unless there is no backup at all, re-read live state under its lock before restoring.
|
|
872
|
+
if ((await this.readBak()).kind === "absent") return this.empty();
|
|
873
|
+
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
874
|
+
}
|
|
875
|
+
const bak = await this.recoverFromBak("missing");
|
|
876
|
+
if (bak.kind === "usable") return bak.store;
|
|
877
|
+
// Only an absent backup makes this tier genuinely empty. One that exists but cannot be used leaves
|
|
878
|
+
// the tier unread: the rows it holds may be exactly the ones a caller needs to see. The backup
|
|
879
|
+
// warning has already been given by recoverFromBak.
|
|
880
|
+
return bak.kind === "unusable" ? this.unreadEmpty(`has no live file and its backup ${this.filePath}.bak could not be used (${bak.reason}); the tier was not read`) : this.empty();
|
|
847
881
|
}
|
|
848
882
|
if (err instanceof BoundedReadFailure) return this.recoverBoundedFailure(err, lockToken);
|
|
849
883
|
throw err;
|
|
@@ -865,18 +899,32 @@ export class JsonStore<E> {
|
|
|
865
899
|
return withFileLock(`${this.filePath}.lock`, async (token) => this.loadInternal(token));
|
|
866
900
|
}
|
|
867
901
|
// Live file is torn/invalid — roll back to the last-known-good backup before giving up.
|
|
868
|
-
const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost"
|
|
869
|
-
if (bak) return bak;
|
|
902
|
+
const bak = await this.recoverFromBak("was corrupt — the last committed write may be lost");
|
|
903
|
+
if (bak.kind === "usable") return bak.store;
|
|
870
904
|
const quarantineOptions: QuarantineOptions = {};
|
|
871
905
|
if (lockToken !== undefined) quarantineOptions.lockToken = lockToken;
|
|
872
906
|
const dest = await quarantineCorrupt(this.filePath, "unparseable / unexpected shape", quarantineOptions);
|
|
873
|
-
this.
|
|
874
|
-
|
|
907
|
+
return this.startEmpty(`was corrupt and had no usable backup — quarantined to ${dest ?? "(nowhere)"}, starting empty`);
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
private plain(store: InternalStoreFile<E>): StoreFile<E> {
|
|
911
|
+
return { version: store.version, updatedAt: store.updatedAt, sequence: store.sequence, entries: [...store.entries] };
|
|
875
912
|
}
|
|
876
913
|
|
|
877
914
|
async load(): Promise<StoreFile<E>> {
|
|
915
|
+
return this.plain(await this.loadInternal());
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/**
|
|
919
|
+
* The same tolerant read as {@link load}, plus whether it saw every row. A missing file with no backup is
|
|
920
|
+
* complete, and so is a restore from a valid backup. Rows hidden as invalid, a quarantine that started the
|
|
921
|
+
* store empty, or a backup that exists but could not be used while the live file is absent are not. A foreign
|
|
922
|
+
* version or an I/O error on the live file still throws, exactly as it does for `load`.
|
|
923
|
+
*/
|
|
924
|
+
async loadChecked(): Promise<StoreRead<E>> {
|
|
878
925
|
const store = await this.loadInternal();
|
|
879
|
-
|
|
926
|
+
const reasons = [store[UNREAD_REASON], this.invalidEntriesNote(store)].filter((reason): reason is string => typeof reason === "string");
|
|
927
|
+
return { file: this.plain(store), complete: reasons.length === 0, reasons };
|
|
880
928
|
}
|
|
881
929
|
|
|
882
930
|
/** Read without recovery, quarantine, warnings or writes; invalid rows make editing unsafe. */
|