@aeondave/pi-persona-mind 0.9.7 → 0.9.8

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.
Files changed (54) hide show
  1. package/AGENTS.md +137 -137
  2. package/CHANGELOG.md +287 -282
  3. package/LICENSE +24 -24
  4. package/README.md +1 -1
  5. package/docs/DESIGN.md +605 -605
  6. package/docs/MEMORY-RESEARCH.md +163 -163
  7. package/package.json +11 -2
  8. package/src/core/auto-optimize.ts +323 -323
  9. package/src/core/backlog.ts +228 -228
  10. package/src/core/blocked.ts +38 -38
  11. package/src/core/capture.ts +155 -155
  12. package/src/core/context-budget.ts +74 -74
  13. package/src/core/handoff-store.ts +111 -111
  14. package/src/core/handoff.ts +70 -70
  15. package/src/core/host-compat.ts +16 -16
  16. package/src/core/ids.ts +59 -59
  17. package/src/core/inject.ts +247 -247
  18. package/src/core/knowledge-review.ts +107 -107
  19. package/src/core/memory-read.ts +34 -34
  20. package/src/core/memory.ts +321 -321
  21. package/src/core/migrate.ts +713 -713
  22. package/src/core/mind-settings.ts +54 -54
  23. package/src/core/optimize-history.ts +163 -163
  24. package/src/core/optimize-service.ts +189 -189
  25. package/src/core/optimize.ts +127 -127
  26. package/src/core/retrieval.ts +164 -164
  27. package/src/core/scanner.ts +146 -146
  28. package/src/core/scope.ts +201 -201
  29. package/src/core/service.ts +720 -720
  30. package/src/core/session-memory.ts +71 -71
  31. package/src/core/store.ts +1002 -1002
  32. package/src/extension/activity.ts +79 -79
  33. package/src/extension/auto-optimize-session.ts +143 -143
  34. package/src/extension/auto-optimize.ts +565 -565
  35. package/src/extension/handoff.ts +23 -23
  36. package/src/extension/knowledge-review.ts +229 -229
  37. package/src/extension/memory-inspector.ts +82 -82
  38. package/src/extension/mind-actions.ts +38 -38
  39. package/src/extension/mind-worker.ts +32 -32
  40. package/src/extension/persona-dependency.ts +76 -76
  41. package/src/extension/reference-anchor.ts +48 -48
  42. package/src/extension/review-evidence.ts +222 -222
  43. package/src/extension/worker-memory-anchor.ts +28 -28
  44. package/src/session-memory.ts +127 -127
  45. package/src/tools/backlog.ts +126 -126
  46. package/src/tools/memory-handoff.ts +30 -30
  47. package/src/tools/memory-history.ts +46 -46
  48. package/src/tools/memory.ts +6 -4
  49. package/src/ui/card-frame.ts +161 -161
  50. package/src/ui/inspector-frame.ts +44 -44
  51. package/src/ui/memory-inspector.ts +464 -464
  52. package/src/ui/mind-result-card.ts +48 -48
  53. package/src/ui/presentation.ts +87 -87
  54. package/src/ui/session-note-card.ts +58 -58
@@ -1,111 +1,111 @@
1
- import { randomBytes } from "node:crypto";
2
- import { isAbsolute, relative } from "node:path";
3
- import { canonicalProjectIdentity, type Scope } from "./scope.ts";
4
- import { BoundedReadFailure, JsonStore, StoreCapacityError, StoreConflictError, StoreVersionError } 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
- // 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 });
19
- }
20
- private readonly scope: Scope;
21
-
22
- async execute(context: HandoffContext, input: HandoffInput): Promise<HandoffResult> {
23
- try {
24
- 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" };
25
- const cwdRelative = relative(canonicalProjectIdentity(context.projectRoot), canonicalProjectIdentity(context.cwd));
26
- if (cwdRelative === ".." || cwdRelative.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(cwdRelative)) return { ok: false, reason: "handoff cwd outside project" };
27
- if (input.operation === "save" && !validHandoffContent(input)) return { ok: false, reason: "invalid or unsafe handoff content" };
28
- if (input.operation === "complete" && !validResolution(input.resolution)) return { ok: false, reason: "resolution must be nonempty and safe" };
29
- for (let attempt = 0; attempt < 10; attempt++) {
30
- const snapshot = await this.store.inspectStrict();
31
- if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed" };
32
- if (new Set(snapshot.store.entries.map((e) => e.id)).size !== snapshot.store.entries.length) return { ok: false, reason: "handoff store contains duplicate IDs" };
33
- const owned = snapshot.store.entries.filter((e) => e.persona === context.persona && canonicalProjectIdentity(e.projectRoot) === canonicalProjectIdentity(context.projectRoot));
34
- if (input.operation === "list") return { ok: true, operation: "list", total: owned.length, entries: owned.map(({ id, revision, goal, status, createdAt, updatedAt }) => {
35
- const goalTruncated = goal.length > MAX_HANDOFF_GOAL_PREVIEW_CHARS;
36
- const preview = goalTruncated ? `${goal.slice(0, MAX_HANDOFF_GOAL_PREVIEW_CHARS - 1).replace(/[\uD800-\uDBFF]$/, "")}…` : goal;
37
- return { id, revision, goal: preview, goalTruncated, status, createdAt, updatedAt };
38
- }) };
39
- if (input.operation === "read") {
40
- const entry = owned.find((e) => e.id === input.id);
41
- return entry ? { ok: true, operation: "read", entry } : { ok: false, reason: "handoff not found" };
42
- }
43
- let entry: HandoffEntry;
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` };
47
- const now = new Date().toISOString();
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] };
49
- } else {
50
- const found = owned.find((e) => e.id === input.id);
51
- if (!found) return { ok: false, reason: "handoff not found" };
52
- if (found.revision !== input.revision) return { ok: false, reason: "handoff changed; read it again" };
53
- if (input.operation === "complete" && found.status !== "open") return { ok: false, reason: "handoff already completed" };
54
- entry = input.operation === "complete" ? { ...found, status: "completed", revision: found.revision + 1, updatedAt: new Date().toISOString(), resolution: input.resolution } : found;
55
- }
56
- 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` };
57
- const normalized = validateHandoff(entry);
58
- if (!normalized) return { ok: false, reason: "handoff snapshot metadata is invalid" };
59
- entry = normalized;
60
- try {
61
- await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => {
62
- if (context.isCurrent?.() === false) throw new Error("handoff owner changed");
63
- 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);
64
- });
65
- if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed after commit; inspect the original scope" };
66
- if (input.operation === "forget") return { ok: true, operation: "forget" };
67
- return { ok: true, operation: input.operation, entry };
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
- }
85
- }
86
- return { ok: false, reason: "handoff store busy; retry" };
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
- }
110
- }
111
- }
1
+ import { randomBytes } from "node:crypto";
2
+ import { isAbsolute, relative } from "node:path";
3
+ import { canonicalProjectIdentity, type Scope } from "./scope.ts";
4
+ import { BoundedReadFailure, JsonStore, StoreCapacityError, StoreConflictError, StoreVersionError } 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
+ // 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 });
19
+ }
20
+ private readonly scope: Scope;
21
+
22
+ async execute(context: HandoffContext, input: HandoffInput): Promise<HandoffResult> {
23
+ try {
24
+ 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" };
25
+ const cwdRelative = relative(canonicalProjectIdentity(context.projectRoot), canonicalProjectIdentity(context.cwd));
26
+ if (cwdRelative === ".." || cwdRelative.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || isAbsolute(cwdRelative)) return { ok: false, reason: "handoff cwd outside project" };
27
+ if (input.operation === "save" && !validHandoffContent(input)) return { ok: false, reason: "invalid or unsafe handoff content" };
28
+ if (input.operation === "complete" && !validResolution(input.resolution)) return { ok: false, reason: "resolution must be nonempty and safe" };
29
+ for (let attempt = 0; attempt < 10; attempt++) {
30
+ const snapshot = await this.store.inspectStrict();
31
+ if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed" };
32
+ if (new Set(snapshot.store.entries.map((e) => e.id)).size !== snapshot.store.entries.length) return { ok: false, reason: "handoff store contains duplicate IDs" };
33
+ const owned = snapshot.store.entries.filter((e) => e.persona === context.persona && canonicalProjectIdentity(e.projectRoot) === canonicalProjectIdentity(context.projectRoot));
34
+ if (input.operation === "list") return { ok: true, operation: "list", total: owned.length, entries: owned.map(({ id, revision, goal, status, createdAt, updatedAt }) => {
35
+ const goalTruncated = goal.length > MAX_HANDOFF_GOAL_PREVIEW_CHARS;
36
+ const preview = goalTruncated ? `${goal.slice(0, MAX_HANDOFF_GOAL_PREVIEW_CHARS - 1).replace(/[\uD800-\uDBFF]$/, "")}…` : goal;
37
+ return { id, revision, goal: preview, goalTruncated, status, createdAt, updatedAt };
38
+ }) };
39
+ if (input.operation === "read") {
40
+ const entry = owned.find((e) => e.id === input.id);
41
+ return entry ? { ok: true, operation: "read", entry } : { ok: false, reason: "handoff not found" };
42
+ }
43
+ let entry: HandoffEntry;
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` };
47
+ const now = new Date().toISOString();
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] };
49
+ } else {
50
+ const found = owned.find((e) => e.id === input.id);
51
+ if (!found) return { ok: false, reason: "handoff not found" };
52
+ if (found.revision !== input.revision) return { ok: false, reason: "handoff changed; read it again" };
53
+ if (input.operation === "complete" && found.status !== "open") return { ok: false, reason: "handoff already completed" };
54
+ entry = input.operation === "complete" ? { ...found, status: "completed", revision: found.revision + 1, updatedAt: new Date().toISOString(), resolution: input.resolution } : found;
55
+ }
56
+ 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` };
57
+ const normalized = validateHandoff(entry);
58
+ if (!normalized) return { ok: false, reason: "handoff snapshot metadata is invalid" };
59
+ entry = normalized;
60
+ try {
61
+ await this.store.compareAndUpdate(snapshot.fingerprint, (entries) => {
62
+ if (context.isCurrent?.() === false) throw new Error("handoff owner changed");
63
+ 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);
64
+ });
65
+ if (context.isCurrent?.() === false) return { ok: false, reason: "handoff owner changed after commit; inspect the original scope" };
66
+ if (input.operation === "forget") return { ok: true, operation: "forget" };
67
+ return { ok: true, operation: input.operation, entry };
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
+ }
85
+ }
86
+ return { ok: false, reason: "handoff store busy; retry" };
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
+ }
110
+ }
111
+ }
@@ -1,70 +1,70 @@
1
- import { scanContent } from "./scanner.ts";
2
-
3
- export const MAX_HANDOFF_RECORD_BYTES = 16_384;
4
- export const MAX_HANDOFF_ENTRIES = 32;
5
- export const MAX_HANDOFF_STORE_BYTES = 128 * 1024;
6
- export const MAX_HANDOFF_GOAL_PREVIEW_CHARS = 160;
7
-
8
- export interface HandoffOrigin { sessionId: string; branchId: string | null; cwd: string }
9
- export interface HandoffContext extends HandoffOrigin { persona: string; projectRoot: string; isCurrent?: () => boolean }
10
- export interface HandoffContent { goal: string; completed: string[]; pending: string[]; nextStep: string; references: string[] }
11
- export interface HandoffEntry extends HandoffContent {
12
- id: string; revision: number; persona: string; projectRoot: string; origin: HandoffOrigin;
13
- createdAt: string; updatedAt: string; status: "open" | "completed"; resolution?: string;
14
- }
15
- export type HandoffInput =
16
- | ({ operation: "save" } & HandoffContent)
17
- | { operation: "list" }
18
- | { operation: "read"; id: string }
19
- | { operation: "complete"; id: string; revision: number; resolution: string }
20
- | { operation: "forget"; id: string; revision: number };
21
-
22
- function safeString(value: unknown, max = 4096): value is string {
23
- return typeof value === "string" && value.trim().length > 0 && value.length <= max && scanContent(value).ok;
24
- }
25
- function safeArray(value: unknown): value is string[] {
26
- if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > 32 || Reflect.ownKeys(value).length !== value.length + 1) return false;
27
- for (let index = 0; index < value.length; index++) {
28
- const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
29
- if (!descriptor || !("value" in descriptor) || !safeString(descriptor.value, 2048)) return false;
30
- }
31
- return true;
32
- }
33
- function dataRecord(value: unknown): value is Record<string, unknown> {
34
- return value !== null && typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value))
35
- && Reflect.ownKeys(value).every((key) => typeof key === "string" && "value" in Object.getOwnPropertyDescriptor(value, key)!);
36
- }
37
- function exactFields(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): boolean {
38
- return required.every((key) => Object.hasOwn(value, key)) && Reflect.ownKeys(value).every((key) => typeof key === "string" && (required.includes(key) || optional.includes(key)));
39
- }
40
- const CONTENT_FIELDS = ["goal", "completed", "pending", "nextStep", "references"] as const;
41
- function content(value: HandoffContent): HandoffContent {
42
- return { goal: value.goal, completed: [...value.completed], pending: [...value.pending], nextStep: value.nextStep, references: [...value.references] };
43
- }
44
- export function validHandoffContent(value: unknown): value is HandoffContent {
45
- return dataRecord(value) && CONTENT_FIELDS.every((key) => Object.hasOwn(value, key))
46
- && safeString(value.goal) && safeArray(value.completed) && safeArray(value.pending) && safeString(value.nextStep) && safeArray(value.references)
47
- && Buffer.byteLength(JSON.stringify(content(value as unknown as HandoffContent)), "utf8") <= MAX_HANDOFF_RECORD_BYTES;
48
- }
49
- export function validContext(value: HandoffContext): boolean {
50
- return [value.persona, value.projectRoot, value.sessionId, value.cwd].every((s) => safeString(s, 1024)) && (value.branchId === null || safeString(value.branchId, 1024));
51
- }
52
- export function validateHandoff(raw: unknown): HandoffEntry | null {
53
- if (!dataRecord(raw) || !exactFields(raw, ["id", "revision", "persona", "projectRoot", "origin", "createdAt", "updatedAt", "status", ...CONTENT_FIELDS], ["resolution"])) return null;
54
- if (!dataRecord(raw.origin) || !exactFields(raw.origin, ["sessionId", "branchId", "cwd"])) return null;
55
- const origin = raw.origin;
56
- if (![raw.persona, raw.projectRoot, origin.sessionId, origin.cwd].every((value) => safeString(value, 1024)) || origin.branchId !== null && !safeString(origin.branchId, 1024)) return null;
57
- if (typeof raw.id !== "string" || !/^[a-f0-9]{32}$/.test(raw.id) || typeof raw.revision !== "number" || !Number.isSafeInteger(raw.revision) || raw.revision < 1 || !validHandoffContent(raw)) return null;
58
- // Writers use ISO timestamps. Exact strings reject coercible arrays/numbers and ignored suffixes.
59
- const validDate = (value: unknown): value is string => safeString(value, 24) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
60
- if (!validDate(raw.createdAt) || !validDate(raw.updatedAt)) return null;
61
- const status = raw.status;
62
- if (status !== "open" && status !== "completed") return null;
63
- if (status === "open" ? Object.hasOwn(raw, "resolution") : !safeString(raw.resolution)) return null;
64
- const entry: HandoffEntry = { id: raw.id, revision: raw.revision, persona: raw.persona as string, projectRoot: raw.projectRoot as string,
65
- origin: { sessionId: origin.sessionId as string, branchId: origin.branchId as string | null, cwd: origin.cwd as string },
66
- createdAt: raw.createdAt, updatedAt: raw.updatedAt, status, ...content(raw),
67
- ...(status === "completed" ? { resolution: raw.resolution as string } : {}) };
68
- return Buffer.byteLength(JSON.stringify(entry), "utf8") <= MAX_HANDOFF_RECORD_BYTES ? entry : null;
69
- }
70
- export function validResolution(value: unknown): value is string { return safeString(value); }
1
+ import { scanContent } from "./scanner.ts";
2
+
3
+ export const MAX_HANDOFF_RECORD_BYTES = 16_384;
4
+ export const MAX_HANDOFF_ENTRIES = 32;
5
+ export const MAX_HANDOFF_STORE_BYTES = 128 * 1024;
6
+ export const MAX_HANDOFF_GOAL_PREVIEW_CHARS = 160;
7
+
8
+ export interface HandoffOrigin { sessionId: string; branchId: string | null; cwd: string }
9
+ export interface HandoffContext extends HandoffOrigin { persona: string; projectRoot: string; isCurrent?: () => boolean }
10
+ export interface HandoffContent { goal: string; completed: string[]; pending: string[]; nextStep: string; references: string[] }
11
+ export interface HandoffEntry extends HandoffContent {
12
+ id: string; revision: number; persona: string; projectRoot: string; origin: HandoffOrigin;
13
+ createdAt: string; updatedAt: string; status: "open" | "completed"; resolution?: string;
14
+ }
15
+ export type HandoffInput =
16
+ | ({ operation: "save" } & HandoffContent)
17
+ | { operation: "list" }
18
+ | { operation: "read"; id: string }
19
+ | { operation: "complete"; id: string; revision: number; resolution: string }
20
+ | { operation: "forget"; id: string; revision: number };
21
+
22
+ function safeString(value: unknown, max = 4096): value is string {
23
+ return typeof value === "string" && value.trim().length > 0 && value.length <= max && scanContent(value).ok;
24
+ }
25
+ function safeArray(value: unknown): value is string[] {
26
+ if (!Array.isArray(value) || Object.getPrototypeOf(value) !== Array.prototype || value.length > 32 || Reflect.ownKeys(value).length !== value.length + 1) return false;
27
+ for (let index = 0; index < value.length; index++) {
28
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
29
+ if (!descriptor || !("value" in descriptor) || !safeString(descriptor.value, 2048)) return false;
30
+ }
31
+ return true;
32
+ }
33
+ function dataRecord(value: unknown): value is Record<string, unknown> {
34
+ return value !== null && typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value))
35
+ && Reflect.ownKeys(value).every((key) => typeof key === "string" && "value" in Object.getOwnPropertyDescriptor(value, key)!);
36
+ }
37
+ function exactFields(value: Record<string, unknown>, required: readonly string[], optional: readonly string[] = []): boolean {
38
+ return required.every((key) => Object.hasOwn(value, key)) && Reflect.ownKeys(value).every((key) => typeof key === "string" && (required.includes(key) || optional.includes(key)));
39
+ }
40
+ const CONTENT_FIELDS = ["goal", "completed", "pending", "nextStep", "references"] as const;
41
+ function content(value: HandoffContent): HandoffContent {
42
+ return { goal: value.goal, completed: [...value.completed], pending: [...value.pending], nextStep: value.nextStep, references: [...value.references] };
43
+ }
44
+ export function validHandoffContent(value: unknown): value is HandoffContent {
45
+ return dataRecord(value) && CONTENT_FIELDS.every((key) => Object.hasOwn(value, key))
46
+ && safeString(value.goal) && safeArray(value.completed) && safeArray(value.pending) && safeString(value.nextStep) && safeArray(value.references)
47
+ && Buffer.byteLength(JSON.stringify(content(value as unknown as HandoffContent)), "utf8") <= MAX_HANDOFF_RECORD_BYTES;
48
+ }
49
+ export function validContext(value: HandoffContext): boolean {
50
+ return [value.persona, value.projectRoot, value.sessionId, value.cwd].every((s) => safeString(s, 1024)) && (value.branchId === null || safeString(value.branchId, 1024));
51
+ }
52
+ export function validateHandoff(raw: unknown): HandoffEntry | null {
53
+ if (!dataRecord(raw) || !exactFields(raw, ["id", "revision", "persona", "projectRoot", "origin", "createdAt", "updatedAt", "status", ...CONTENT_FIELDS], ["resolution"])) return null;
54
+ if (!dataRecord(raw.origin) || !exactFields(raw.origin, ["sessionId", "branchId", "cwd"])) return null;
55
+ const origin = raw.origin;
56
+ if (![raw.persona, raw.projectRoot, origin.sessionId, origin.cwd].every((value) => safeString(value, 1024)) || origin.branchId !== null && !safeString(origin.branchId, 1024)) return null;
57
+ if (typeof raw.id !== "string" || !/^[a-f0-9]{32}$/.test(raw.id) || typeof raw.revision !== "number" || !Number.isSafeInteger(raw.revision) || raw.revision < 1 || !validHandoffContent(raw)) return null;
58
+ // Writers use ISO timestamps. Exact strings reject coercible arrays/numbers and ignored suffixes.
59
+ const validDate = (value: unknown): value is string => safeString(value, 24) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
60
+ if (!validDate(raw.createdAt) || !validDate(raw.updatedAt)) return null;
61
+ const status = raw.status;
62
+ if (status !== "open" && status !== "completed") return null;
63
+ if (status === "open" ? Object.hasOwn(raw, "resolution") : !safeString(raw.resolution)) return null;
64
+ const entry: HandoffEntry = { id: raw.id, revision: raw.revision, persona: raw.persona as string, projectRoot: raw.projectRoot as string,
65
+ origin: { sessionId: origin.sessionId as string, branchId: origin.branchId as string | null, cwd: origin.cwd as string },
66
+ createdAt: raw.createdAt, updatedAt: raw.updatedAt, status, ...content(raw),
67
+ ...(status === "completed" ? { resolution: raw.resolution as string } : {}) };
68
+ return Buffer.byteLength(JSON.stringify(entry), "utf8") <= MAX_HANDOFF_RECORD_BYTES ? entry : null;
69
+ }
70
+ export function validResolution(value: unknown): value is string { return safeString(value); }
@@ -1,16 +1,16 @@
1
- /** The extension targets current Pi only; this is a floor check, not a compatibility layer. */
2
- export const MIN_PI_VERSION = "1.7.0";
3
- const minimum = MIN_PI_VERSION.split(".").map(Number);
4
-
5
- export function isSupportedPiVersion(version: string): boolean {
6
- 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
- if (!parsed) return false;
8
- const parts = parsed.slice(1, 4).map(Number);
9
- if (parts.some((part) => !Number.isSafeInteger(part))) return false;
10
- const current = parts as [number, number, number];
11
- for (let i = 0; i < minimum.length; i++) {
12
- if (current[i]! > minimum[i]!) return true;
13
- if (current[i]! < minimum[i]!) return false;
14
- }
15
- return parsed[4] === undefined;
16
- }
1
+ /** The extension targets current Pi only; this is a floor check, not a compatibility layer. */
2
+ export const MIN_PI_VERSION = "1.7.0";
3
+ const minimum = MIN_PI_VERSION.split(".").map(Number);
4
+
5
+ export function isSupportedPiVersion(version: string): boolean {
6
+ 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
+ if (!parsed) return false;
8
+ const parts = parsed.slice(1, 4).map(Number);
9
+ if (parts.some((part) => !Number.isSafeInteger(part))) return false;
10
+ const current = parts as [number, number, number];
11
+ for (let i = 0; i < minimum.length; i++) {
12
+ if (current[i]! > minimum[i]!) return true;
13
+ if (current[i]! < minimum[i]!) return false;
14
+ }
15
+ return parsed[4] === undefined;
16
+ }
package/src/core/ids.ts CHANGED
@@ -1,59 +1,59 @@
1
- /**
2
- * Content-addressed identity for mind entries.
3
- *
4
- * An entry's id is derived from its meaning (kind + normalized text + tag set), not from a
5
- * random uuid or a counter. Two consequences follow for free: re-recording the same fact
6
- * produces the same id (so a `remember` becomes an idempotent update-in-place, never a
7
- * duplicate), and the id is a stable, citable handle for `recall`/`forget`.
8
- */
9
-
10
- import { createHash } from "node:crypto";
11
-
12
- /** Collapse trivial variation so the "same fact" hashes to the same id: trim, single-space, lowercase. */
13
- function normalizeText(text: string): string {
14
- return text.trim().replace(/\s+/g, " ").toLowerCase();
15
- }
16
-
17
- /** Normalize a tag set: trim, lowercase, drop empties, dedup, sort — order-independent. */
18
- function normalizeTags(tags: readonly string[]): string[] {
19
- return [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
20
- }
21
-
22
- /**
23
- * Keep the historical tag serialization for ordinary inputs so existing ids remain stable. Once a
24
- * tag contains a delimiter that the legacy comma-join cannot represent unambiguously, switch the
25
- * whole material to a versioned JSON encoding. The leading control marker is excluded from the
26
- * legacy branch, so the two encodings cannot collide.
27
- */
28
- function materialFor(kind: string, text: string, tags: readonly string[]): string {
29
- const legacySafe = ![kind, text, ...tags].some((value) => value.includes("\0") || value.includes("\u0001")) && !tags.some((tag) => tag.includes(","));
30
- if (legacySafe) return `${kind}\0${text}\0${tags.join(",")}`;
31
- return `\u0001v2\0${JSON.stringify([kind, text, tags])}`;
32
- }
33
-
34
- function digest(material: string): string {
35
- return createHash("sha256").update(material).digest("hex").slice(0, 12);
36
- }
37
-
38
- /** The original v1 digest, retained for reading and addressing migrated records. */
39
- export function legacyContentId(kind: string, text: string, tags: readonly string[]): string {
40
- const normalizedText = normalizeText(text);
41
- const normalizedTags = normalizeTags(tags);
42
- return digest(`${kind}\0${normalizedText}\0${normalizedTags.join(",")}`);
43
- }
44
-
45
- /** A 12-char lowercase-hex content id over (kind, normalized text, normalized tag set). */
46
- export function contentId(kind: string, text: string, tags: readonly string[]): string {
47
- const material = materialFor(kind, normalizeText(text), normalizeTags(tags));
48
- return digest(material);
49
- }
50
-
51
- /**
52
- * IDs that may refer to this semantic content across the v1/v2 encoding boundary. The set has one
53
- * member for ordinary inputs (v1 and v2 are identical there), and two for delimiter-bearing inputs.
54
- */
55
- export function compatibleContentIds(kind: string, text: string, tags: readonly string[]): string[] {
56
- const current = contentId(kind, text, tags);
57
- const legacy = legacyContentId(kind, text, tags);
58
- return current === legacy ? [current] : [current, legacy];
59
- }
1
+ /**
2
+ * Content-addressed identity for mind entries.
3
+ *
4
+ * An entry's id is derived from its meaning (kind + normalized text + tag set), not from a
5
+ * random uuid or a counter. Two consequences follow for free: re-recording the same fact
6
+ * produces the same id (so a `remember` becomes an idempotent update-in-place, never a
7
+ * duplicate), and the id is a stable, citable handle for `recall`/`forget`.
8
+ */
9
+
10
+ import { createHash } from "node:crypto";
11
+
12
+ /** Collapse trivial variation so the "same fact" hashes to the same id: trim, single-space, lowercase. */
13
+ function normalizeText(text: string): string {
14
+ return text.trim().replace(/\s+/g, " ").toLowerCase();
15
+ }
16
+
17
+ /** Normalize a tag set: trim, lowercase, drop empties, dedup, sort — order-independent. */
18
+ function normalizeTags(tags: readonly string[]): string[] {
19
+ return [...new Set(tags.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
20
+ }
21
+
22
+ /**
23
+ * Keep the historical tag serialization for ordinary inputs so existing ids remain stable. Once a
24
+ * tag contains a delimiter that the legacy comma-join cannot represent unambiguously, switch the
25
+ * whole material to a versioned JSON encoding. The leading control marker is excluded from the
26
+ * legacy branch, so the two encodings cannot collide.
27
+ */
28
+ function materialFor(kind: string, text: string, tags: readonly string[]): string {
29
+ const legacySafe = ![kind, text, ...tags].some((value) => value.includes("\0") || value.includes("\u0001")) && !tags.some((tag) => tag.includes(","));
30
+ if (legacySafe) return `${kind}\0${text}\0${tags.join(",")}`;
31
+ return `\u0001v2\0${JSON.stringify([kind, text, tags])}`;
32
+ }
33
+
34
+ function digest(material: string): string {
35
+ return createHash("sha256").update(material).digest("hex").slice(0, 12);
36
+ }
37
+
38
+ /** The original v1 digest, retained for reading and addressing migrated records. */
39
+ export function legacyContentId(kind: string, text: string, tags: readonly string[]): string {
40
+ const normalizedText = normalizeText(text);
41
+ const normalizedTags = normalizeTags(tags);
42
+ return digest(`${kind}\0${normalizedText}\0${normalizedTags.join(",")}`);
43
+ }
44
+
45
+ /** A 12-char lowercase-hex content id over (kind, normalized text, normalized tag set). */
46
+ export function contentId(kind: string, text: string, tags: readonly string[]): string {
47
+ const material = materialFor(kind, normalizeText(text), normalizeTags(tags));
48
+ return digest(material);
49
+ }
50
+
51
+ /**
52
+ * IDs that may refer to this semantic content across the v1/v2 encoding boundary. The set has one
53
+ * member for ordinary inputs (v1 and v2 are identical there), and two for delimiter-bearing inputs.
54
+ */
55
+ export function compatibleContentIds(kind: string, text: string, tags: readonly string[]): string[] {
56
+ const current = contentId(kind, text, tags);
57
+ const legacy = legacyContentId(kind, text, tags);
58
+ return current === legacy ? [current] : [current, legacy];
59
+ }