@aeondave/pi-persona-mind 0.9.1 → 0.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +131 -123
- package/CHANGELOG.md +224 -198
- package/README.md +169 -145
- package/docs/DESIGN.md +533 -475
- package/docs/MEMORY-RESEARCH.md +25 -1
- package/package.json +90 -90
- package/src/core/handoff-store.ts +70 -0
- package/src/core/handoff.ts +70 -0
- package/src/core/host-compat.ts +2 -2
- package/src/core/memory.ts +7 -0
- package/src/core/optimize-history.ts +48 -6
- package/src/core/optimize-service.ts +18 -24
- package/src/core/retrieval.ts +70 -22
- package/src/core/service.ts +69 -27
- package/src/extension/handoff.ts +23 -0
- package/src/extension/mind-command.ts +449 -404
- package/src/index.ts +14 -3
- package/src/tools/memory-handoff.ts +30 -0
- package/src/tools/memory-history.ts +46 -0
- package/src/tools/memory-optimize.ts +121 -133
- package/src/tools/memory.ts +466 -427
- package/src/ui/memory-inspector.ts +449 -445
package/docs/MEMORY-RESEARCH.md
CHANGED
|
@@ -33,6 +33,20 @@ Mind uses deterministic lexical, tag and path ranking, with explicit full reads
|
|
|
33
33
|
injection. This is explainable and avoids an additional indexing service, but differently worded
|
|
34
34
|
queries may miss relevant facts. No general semantic-recall guarantee follows from a passing test.
|
|
35
35
|
|
|
36
|
+
Identifier components and vowel-accent folding are lower-weight fallback matches, behind exact
|
|
37
|
+
words and paths. Numeric versions stay intact, negation terms remain searchable, and Unicode/CJK
|
|
38
|
+
segmentation is preserved. A fallback can still add irrelevant rows: fewer missed identifiers does
|
|
39
|
+
not imply perfect precision. Tags already normalized when saved cannot recover lost camel casing.
|
|
40
|
+
|
|
41
|
+
`npm run eval:memory` compares the previous ranker and injection renderer with the current ones on
|
|
42
|
+
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 a separate nine-case supervisor-labelled holdout withheld during initial
|
|
44
|
+
implementation, they improve from 6/7 to 7/7. Negative queries with results fall from one to zero in
|
|
45
|
+
each set. False positives among the top three remain 1 in development and fall from 5 to 3 in the
|
|
46
|
+
holdout; a weak `memory`/`memoryOwnership` match remains. The preceding 30-case fixture's metrics and
|
|
47
|
+
seven sentinel outcomes are unchanged. These small synthetic sets and their labels are inspectable
|
|
48
|
+
regression evidence, not an external benchmark or a general semantic-quality claim.
|
|
49
|
+
|
|
36
50
|
Injection is a planning budget, not a billing measurement. Preserve wrappers, omission counts and
|
|
37
51
|
whole admitted excerpts within the documented limits. The runtime estimate operates on UTF-8 bytes;
|
|
38
52
|
it must not select a correction factor by detecting a language. A comparison against a named reference
|
|
@@ -56,6 +70,16 @@ encoding remains a comparison to that encoding, not a count for every possible s
|
|
|
56
70
|
Successful validation establishes structural permission and freshness, not semantic truth. A worker
|
|
57
71
|
can still propose a bad summary. Keep proposals inspectable and state that limitation explicitly.
|
|
58
72
|
|
|
73
|
+
Ordinary explicit supersession now uses that same receipt protocol. This preserves a changed
|
|
74
|
+
decision's original evidence without making historical facts compete with current facts in recall.
|
|
75
|
+
An ordinary receipt is read-only; consolidation undo retains its existing conflict checks. No second
|
|
76
|
+
archive, embeddings service or automatically generated summary is introduced.
|
|
77
|
+
|
|
78
|
+
Cross-session handoffs address a separate need: a deliberately saved work snapshot with a next step,
|
|
79
|
+
origin and explicit completion resolution. They remain owner-scoped and manually discoverable, never
|
|
80
|
+
automatic instructions or a claim that a worker session was restored. Quota refusal and explicit
|
|
81
|
+
forgetting preserve unfinished work instead of silently deleting it on a timer.
|
|
82
|
+
|
|
59
83
|
## What verification can establish
|
|
60
84
|
|
|
61
85
|
The local suite exercises store concurrency, atomic replacement, stale-plan refusal, provenance,
|
|
@@ -83,7 +107,7 @@ reference counts or automatically tune the production budget from a small fixtur
|
|
|
83
107
|
## Inspector architecture decision
|
|
84
108
|
|
|
85
109
|
The memory inspector adds a read-only view over existing stores and the native active branch, rather
|
|
86
|
-
than introducing
|
|
110
|
+
than introducing a permanent transcript and summary tree. This preserves Mind's role as
|
|
87
111
|
selective scoped memory and avoids a second retention policy, summarizer budget and source of truth.
|
|
88
112
|
A separate archive could eventually make older cross-session episodes navigable, but would require an
|
|
89
113
|
explicit access, deletion and retention design; an opaque source string is not that authorization.
|
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.
|
|
82
|
-
"@earendil-works/pi-ai": "1.
|
|
83
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
84
|
-
"@earendil-works/pi-tui": "1.
|
|
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.3",
|
|
4
|
+
"private": false,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "Local memory for Pi with pi-persona \u2014 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.3/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
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { isAbsolute, relative } from "node:path";
|
|
3
|
+
import { canonicalProjectIdentity, type Scope } from "./scope.ts";
|
|
4
|
+
import { JsonStore, StoreConflictError } from "./store.ts";
|
|
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
|
+
|
|
7
|
+
export type HandoffResult =
|
|
8
|
+
| { ok: false; reason: string }
|
|
9
|
+
| { ok: true; operation: "save" | "read" | "complete"; entry: HandoffEntry }
|
|
10
|
+
| { ok: true; operation: "list"; total: number; entries: (Pick<HandoffEntry, "id" | "revision" | "goal" | "status" | "createdAt" | "updatedAt"> & { goalTruncated: boolean })[] }
|
|
11
|
+
| { ok: true; operation: "forget" };
|
|
12
|
+
|
|
13
|
+
export class HandoffStore {
|
|
14
|
+
private readonly store: JsonStore<HandoffEntry>;
|
|
15
|
+
constructor(privateScope: Scope) {
|
|
16
|
+
this.scope = privateScope;
|
|
17
|
+
this.store = new JsonStore(`${privateScope.paths.stm}.handoffs.json`, { version: 1, validateEntry: validateHandoff, maxEntries: MAX_HANDOFF_ENTRIES, maxBytes: MAX_HANDOFF_STORE_BYTES });
|
|
18
|
+
}
|
|
19
|
+
private readonly scope: Scope;
|
|
20
|
+
|
|
21
|
+
async execute(context: HandoffContext, input: HandoffInput): Promise<HandoffResult> {
|
|
22
|
+
try {
|
|
23
|
+
if (this.scope.homeWorkspace || !validContext(context) || context.isCurrent?.() === false || context.persona !== this.scope.persona || canonicalProjectIdentity(context.projectRoot) !== canonicalProjectIdentity(this.scope.projectRoot)) return { ok: false, reason: "handoff owner or project unavailable" };
|
|
24
|
+
const cwdRelative = relative(canonicalProjectIdentity(context.projectRoot), canonicalProjectIdentity(context.cwd));
|
|
25
|
+
if (cwdRelative === ".." || cwdRelative.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(cwdRelative)) return { ok: false, reason: "handoff cwd outside project" };
|
|
26
|
+
if (input.operation === "save" && !validHandoffContent(input)) return { ok: false, reason: "invalid or unsafe handoff content" };
|
|
27
|
+
if (input.operation === "complete" && !validResolution(input.resolution)) return { ok: false, reason: "resolution must be nonempty and safe" };
|
|
28
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
29
|
+
const snapshot = await this.store.inspectStrict();
|
|
30
|
+
if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed" };
|
|
31
|
+
if (new Set(snapshot.store.entries.map((e) => e.id)).size !== snapshot.store.entries.length) return { ok: false, reason: "handoff store contains duplicate IDs" };
|
|
32
|
+
const owned = snapshot.store.entries.filter((e) => e.persona === context.persona && canonicalProjectIdentity(e.projectRoot) === canonicalProjectIdentity(context.projectRoot));
|
|
33
|
+
if (input.operation === "list") return { ok: true, operation: "list", total: owned.length, entries: owned.map(({ id, revision, goal, status, createdAt, updatedAt }) => {
|
|
34
|
+
const goalTruncated = goal.length > MAX_HANDOFF_GOAL_PREVIEW_CHARS;
|
|
35
|
+
const preview = goalTruncated ? `${goal.slice(0, MAX_HANDOFF_GOAL_PREVIEW_CHARS - 1).replace(/[\uD800-\uDBFF]$/, "")}…` : goal;
|
|
36
|
+
return { id, revision, goal: preview, goalTruncated, status, createdAt, updatedAt };
|
|
37
|
+
}) };
|
|
38
|
+
if (input.operation === "read") {
|
|
39
|
+
const entry = owned.find((e) => e.id === input.id);
|
|
40
|
+
return entry ? { ok: true, operation: "read", entry } : { ok: false, reason: "handoff not found" };
|
|
41
|
+
}
|
|
42
|
+
let entry: HandoffEntry;
|
|
43
|
+
if (input.operation === "save") {
|
|
44
|
+
const now = new Date().toISOString();
|
|
45
|
+
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
|
+
} else {
|
|
47
|
+
const found = owned.find((e) => e.id === input.id);
|
|
48
|
+
if (!found) return { ok: false, reason: "handoff not found" };
|
|
49
|
+
if (found.revision !== input.revision) return { ok: false, reason: "handoff changed; read it again" };
|
|
50
|
+
if (input.operation === "complete" && found.status !== "open") return { ok: false, reason: "handoff already completed" };
|
|
51
|
+
entry = input.operation === "complete" ? { ...found, status: "completed", revision: found.revision + 1, updatedAt: new Date().toISOString(), resolution: input.resolution } : found;
|
|
52
|
+
}
|
|
53
|
+
if (Buffer.byteLength(JSON.stringify(entry), "utf8") > MAX_HANDOFF_RECORD_BYTES) return { ok: false, reason: `handoff snapshot including metadata exceeds ${MAX_HANDOFF_RECORD_BYTES} bytes; shorten the content or resolution` };
|
|
54
|
+
const normalized = validateHandoff(entry);
|
|
55
|
+
if (!normalized) return { ok: false, reason: "handoff snapshot metadata is invalid" };
|
|
56
|
+
entry = normalized;
|
|
57
|
+
try {
|
|
58
|
+
await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => {
|
|
59
|
+
if (context.isCurrent?.() === false) throw new Error("handoff owner changed");
|
|
60
|
+
return input.operation === "save" ? [...entries, entry] : input.operation === "forget" ? entries.filter((e) => e.id !== entry.id) : entries.map((e) => e.id === entry.id ? entry : e);
|
|
61
|
+
});
|
|
62
|
+
if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed after commit; inspect the original scope" };
|
|
63
|
+
if (input.operation === "forget") return { ok: true, operation: "forget" };
|
|
64
|
+
return { ok: true, operation: input.operation, entry };
|
|
65
|
+
} catch (error) { if (error instanceof StoreConflictError) continue; throw error; }
|
|
66
|
+
}
|
|
67
|
+
return { ok: false, reason: "handoff store busy; retry" };
|
|
68
|
+
} catch (error) { return { ok: false, reason: error instanceof Error ? error.message : "handoff storage failure" }; }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -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); }
|
package/src/core/host-compat.ts
CHANGED
|
@@ -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.
|
|
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,
|
|
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;
|
package/src/core/memory.ts
CHANGED
|
@@ -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,13 +1,12 @@
|
|
|
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, 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
|
-
|
|
8
|
+
interface ReceiptBase {
|
|
9
9
|
receiptId: string;
|
|
10
|
-
planId: string;
|
|
11
10
|
target: OptimizeTarget;
|
|
12
11
|
persona: string;
|
|
13
12
|
createdAt: string;
|
|
@@ -16,18 +15,29 @@ export interface OptimizeReceipt {
|
|
|
16
15
|
storePath: string;
|
|
17
16
|
changes: OptimizeChange[];
|
|
18
17
|
}
|
|
18
|
+
/** Missing origin is the existing persisted optimizer contract, never an ordinary replacement. */
|
|
19
|
+
export type OptimizeReceipt = ReceiptBase & (
|
|
20
|
+
| { origin?: "optimization"; planId: string }
|
|
21
|
+
| { origin: "replacement"; planId?: never }
|
|
22
|
+
);
|
|
19
23
|
export interface OptimizeHistory {
|
|
20
24
|
ok: true; target: OptimizeTarget; receipts: OptimizeReceipt[]; retained: number; omitted: number;
|
|
21
25
|
limit: number; maxBytes: number; withheldUnsafe: number;
|
|
22
26
|
}
|
|
23
27
|
export interface OptimizeUndone { ok: true; receiptId: string; target: OptimizeTarget; restored: number; warning?: string }
|
|
28
|
+
export interface OptimizeReceiptDetail { ok: true; target: OptimizeTarget; receipt: OptimizeReceipt }
|
|
24
29
|
|
|
25
30
|
function validateReceipt(raw: unknown): OptimizeReceipt | null {
|
|
26
31
|
if (!raw || typeof raw !== "object") return null;
|
|
27
32
|
const value = raw as Partial<OptimizeReceipt>;
|
|
28
|
-
|
|
33
|
+
const validId = (id: unknown) => typeof id === "string" && /^[\da-f-]{36}$/i.test(id);
|
|
34
|
+
if (!validId(value.receiptId)) return null;
|
|
35
|
+
if (value.origin === "replacement" ? value.planId !== undefined : !validId(value.planId) || value.origin !== undefined && value.origin !== "optimization") return null;
|
|
29
36
|
if (!isOptimizeTarget(value.target) || typeof value.persona !== "string" || !value.persona || value.persona.length > 128) return null;
|
|
30
|
-
|
|
37
|
+
// Writers use Date.toISOString(). Bound before parsing so metadata cannot expand discovery output.
|
|
38
|
+
if (typeof value.createdAt !== "string" || value.createdAt.length > 27) return null;
|
|
39
|
+
const createdAt = Date.parse(value.createdAt);
|
|
40
|
+
if (!Number.isFinite(createdAt) || new Date(createdAt).toISOString() !== value.createdAt) return null;
|
|
31
41
|
if (!["prepared", "applied", "undone", "rejected"].includes(value.state ?? "")) return null;
|
|
32
42
|
if (typeof value.storePath !== "string" || value.storePath.length > 32_768 || !value.storePath) return null;
|
|
33
43
|
if (!Array.isArray(value.changes) || !value.changes.length || value.changes.length > MAX_OPTIMIZE_OPERATIONS) return null;
|
|
@@ -45,8 +55,9 @@ function validateReceipt(raw: unknown): OptimizeReceipt | null {
|
|
|
45
55
|
if (!after || replacementIds.has(after.id)) return null;
|
|
46
56
|
replacementIds.add(after.id); changes.push({ before, after });
|
|
47
57
|
}
|
|
48
|
-
|
|
58
|
+
const receipt: ReceiptBase = { receiptId: value.receiptId!, target: value.target, persona: value.persona, createdAt: value.createdAt,
|
|
49
59
|
state: value.state!, storePath: value.storePath, changes };
|
|
60
|
+
return value.origin === "replacement" ? { ...receipt, origin: "replacement" } : { ...receipt, origin: "optimization", planId: value.planId! };
|
|
50
61
|
}
|
|
51
62
|
|
|
52
63
|
/** Strict CAS avoids JsonStore.update's recovery semantics, which are unsuitable for recovery logs. */
|
|
@@ -76,11 +87,42 @@ export class OptimizeHistoryStore {
|
|
|
76
87
|
if (!snapshot.store.entries.some((receipt) => receipt.receiptId === receiptId)) throw new Error("optimizer recovery receipt disappeared; history requires repair");
|
|
77
88
|
await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => entries.map((receipt) => receipt.receiptId === receiptId ? { ...receipt, state } : receipt));
|
|
78
89
|
}
|
|
90
|
+
|
|
91
|
+
/** Caller owns the memory transaction lock. Both writers share this write-ahead/CAS protocol. */
|
|
92
|
+
async commit(store: JsonStore<MemoryEntry>, fingerprint: string, receipt: OptimizeReceipt | undefined,
|
|
93
|
+
mutate: (entries: MemoryEntry[]) => MemoryEntry[], assertCurrent: () => void = () => {}): Promise<{ entries: MemoryEntry[]; warning?: string }> {
|
|
94
|
+
return this.exclusive(async () => {
|
|
95
|
+
assertCurrent();
|
|
96
|
+
if ((await store.inspectStrict()).fingerprint !== fingerprint) throw new StoreConflictError();
|
|
97
|
+
if (receipt) await this.prepare(receipt);
|
|
98
|
+
let callbackRejected = false;
|
|
99
|
+
let entries: MemoryEntry[];
|
|
100
|
+
try {
|
|
101
|
+
entries = (await store.compareAndUpdate(fingerprint, (current) => {
|
|
102
|
+
try { assertCurrent(); return mutate(current); }
|
|
103
|
+
catch (error) { callbackRejected = true; throw error; }
|
|
104
|
+
})).entries;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
// Generic IO errors can follow rename: never discard the only before image.
|
|
107
|
+
if (receipt) {
|
|
108
|
+
if (callbackRejected || error instanceof StoreConflictError) await this.settle(receipt.receiptId, "rejected").catch(() => {});
|
|
109
|
+
else throw new Error(`memory replacement outcome uncertain; durable receipt ${receipt.receiptId} remains prepared: ${error instanceof Error ? error.message : "storage failure"}`);
|
|
110
|
+
}
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
if (receipt) {
|
|
114
|
+
try { await this.settle(receipt.receiptId, "applied"); }
|
|
115
|
+
catch { return { entries, warning: "replacement committed; durable receipt remains prepared because history finalization failed" }; }
|
|
116
|
+
}
|
|
117
|
+
return { entries };
|
|
118
|
+
});
|
|
119
|
+
}
|
|
79
120
|
}
|
|
80
121
|
|
|
81
122
|
/** Revert only exact affected rows, never a whole historical snapshot. */
|
|
82
123
|
export function restoreReceipt(entries: readonly MemoryEntry[], receipt: OptimizeReceipt, persona: string, now: number): { ok: true; entries: MemoryEntry[]; restored: number } | OptimizeFailure {
|
|
83
124
|
if (receipt.persona !== persona) return { ok: false, reason: "receipt belongs to a different persona owner" };
|
|
125
|
+
if (receipt.origin === "replacement") return { ok: false, reason: "ordinary replacement history is read-only; optimizer undo is unavailable for this receipt" };
|
|
84
126
|
if (receipt.state === "undone" || receipt.state === "rejected") return { ok: false, reason: "receipt was already undone or its replacement was rejected" };
|
|
85
127
|
const before = receipt.changes.flatMap((change) => change.before);
|
|
86
128
|
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,
|
|
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 () =>
|
|
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
|
-
|
|
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
|
-
|
|
121
|
-
|
|
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" };
|