@aeondave/pi-persona-mind 0.9.3 → 0.9.5
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 +259 -220
- package/README.md +170 -169
- package/docs/DESIGN.md +554 -520
- package/docs/MEMORY-RESEARCH.md +9 -5
- package/package.json +94 -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 +31 -8
- 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/extension/worker-memory-anchor.ts +28 -0
- package/src/index.ts +13 -2
- 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,94 @@
|
|
|
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-
|
|
63
|
-
"@earendil-works/pi-
|
|
64
|
-
"
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
"@
|
|
86
|
-
"
|
|
87
|
-
"
|
|
88
|
-
"
|
|
89
|
-
|
|
90
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@aeondave/pi-persona-mind",
|
|
3
|
+
"version": "0.9.5",
|
|
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.5/assets/banner.png",
|
|
56
|
+
"extensions": [
|
|
57
|
+
"./src/index.ts"
|
|
58
|
+
]
|
|
59
|
+
},
|
|
60
|
+
"peerDependencies": {
|
|
61
|
+
"@aeondave/pi-persona": ">=1.18.1",
|
|
62
|
+
"@earendil-works/pi-ai": "*",
|
|
63
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
64
|
+
"@earendil-works/pi-tui": "*",
|
|
65
|
+
"typebox": "*"
|
|
66
|
+
},
|
|
67
|
+
"peerDependenciesMeta": {
|
|
68
|
+
"@aeondave/pi-persona": {
|
|
69
|
+
"optional": true
|
|
70
|
+
},
|
|
71
|
+
"@earendil-works/pi-ai": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"@earendil-works/pi-coding-agent": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"@earendil-works/pi-tui": {
|
|
78
|
+
"optional": true
|
|
79
|
+
},
|
|
80
|
+
"typebox": {
|
|
81
|
+
"optional": true
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
"devDependencies": {
|
|
85
|
+
"@earendil-works/pi-agent-core": "1.6.0",
|
|
86
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
87
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
88
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
89
|
+
"@types/node": "^22.0.0",
|
|
90
|
+
"tsx": "^4.19.0",
|
|
91
|
+
"typebox": "*",
|
|
92
|
+
"typescript": "^7.0.2"
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -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" };
|
|
@@ -668,7 +691,7 @@ export class MindService {
|
|
|
668
691
|
* persona, so it inherits who the persona IS but not the supervisor's project state or deferred
|
|
669
692
|
* intent. (The caller also withholds the write tools + wakes from a leg — see index.ts.)
|
|
670
693
|
*/
|
|
671
|
-
async buildInjection(opts: { lean?: boolean; query?: string; fixedBlocks?: readonly string[]; cleanup?: boolean } = {}): Promise<string> {
|
|
694
|
+
async buildInjection(opts: { lean?: boolean; query?: string; fixedBlocks?: readonly string[]; cleanup?: boolean; leanReferenceTime?: number } = {}): Promise<string> {
|
|
672
695
|
// Workers inherit a read-only lean block; they must not mutate the supervisor's stores.
|
|
673
696
|
// A background import may own the profile lock while awaiting another store writer. Reads
|
|
674
697
|
// already filter expiry; defer disk hygiene until a later turn rather than joining that import.
|
|
@@ -678,7 +701,7 @@ export class MindService {
|
|
|
678
701
|
if (opts.lean || this.scope.homeWorkspace) {
|
|
679
702
|
const ltm = this.safeMemories(await this.longMemories(), "long-term");
|
|
680
703
|
if (opts.lean) {
|
|
681
|
-
return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now, lean: true, ...context, ...(this.budget ? { budget: this.budget } : {}) });
|
|
704
|
+
return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now: opts.leanReferenceTime ?? now, lean: true, ...context, ...(this.budget ? { budget: this.budget } : {}) });
|
|
682
705
|
}
|
|
683
706
|
return renderMind({ persona: this.scope.persona, ltm, stm: [], backlog: [], now, ...context, ...(this.budget ? { budget: this.budget } : {}) });
|
|
684
707
|
}
|