@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,713 +1,713 @@
1
- /**
2
- * One-way importer for the superseded `pi-`prefixed storage root.
3
- *
4
- * The old root is only read. Memory merges join the profile transaction lock before JsonStore's
5
- * per-file lock, coordinating background import with foreground edits across projects. Two copies of one fact
6
- * are reconciled by which copy is LATER, not by which root it sits in; distinct
7
- * same-id content is preserved. Filenames and legacy bytes are not rewritten or removed.
8
- */
9
-
10
- import { lstat, opendir } from "node:fs/promises";
11
- import { createHash } from "node:crypto";
12
- import { basename, join, resolve, win32 } from "node:path";
13
-
14
- import type { BacklogEntry, BacklogState } from "./backlog.ts";
15
- import { validateBacklog } from "./backlog.ts";
16
- import type { MemoryEntry } from "./memory.ts";
17
- import { validateLongMemory, validateShortMemory } from "./memory.ts";
18
- import { contentId } from "./ids.ts";
19
- import { DEFAULT_PERSONA, memoryMutationLockPath, projectSlug, sanitizePersona, SHARED_SCOPE, type ProjectSlugOptions } from "./scope.ts";
20
- import { DEFAULT_STORE_MAX_ENTRIES, JsonStore, readTextFileBounded, StoreCapacityError, withFileLock, type JsonStoreOptions } from "./store.ts";
21
-
22
- const STORE_VERSION = 1;
23
- const WIN_RESERVED_DEVICE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
24
- const DEFAULT_MAX_FILES = 256;
25
- const DEFAULT_MAX_FILE_BYTES = 4 * 1024 * 1024;
26
- const LEGACY_MANIFEST_FILE = ".legacy-import-v1.json";
27
-
28
- export type ImportKind = "ltm" | "stm" | "backlog";
29
-
30
- interface ImportDirectory {
31
- relative: string;
32
- kind: ImportKind;
33
- }
34
-
35
- const IMPORT_DIRECTORIES: readonly ImportDirectory[] = [
36
- { relative: join("memory", "ltm"), kind: "ltm" },
37
- { relative: join("memory", "stm"), kind: "stm" },
38
- { relative: "backlog", kind: "backlog" },
39
- ];
40
-
41
- /** Counts and diagnostics returned by {@link migrateLegacyRoot}. */
42
- export interface MigrationReport {
43
- /** Recognized JSON files whose contents were read under the three supported legacy directories. */
44
- filesScanned: number;
45
- /** Unchanged legacy files skipped from content read/parse by the durable source manifest. */
46
- filesSkipped: number;
47
- /** Files a commit touched: a recognized source that yielded at least one imported entry, or a
48
- * current destination whose stored records were reconciled in place (see `entriesAdded`). */
49
- filesMigrated: number;
50
- /** Valid, source-semantic-unique legacy entries considered. */
51
- entriesSeen: number;
52
- /** Entries newly appended to, or reconciled in place in, the current destination. */
53
- entriesAdded: number;
54
- /** Valid entries the destination already held under the same semantic identity (kept or reconciled). */
55
- conflicts: number;
56
- /** Entries rejected by the current schema validator. */
57
- invalidEntries: number;
58
- warnings: string[];
59
- }
60
-
61
- export interface LegacyMigrationOptions {
62
- /** Override the old root; defaults to `<agentDir>/pi-persona-mind`. */
63
- legacyRoot?: string;
64
- /** Override the current root; defaults to `<agentDir>/persona-mind`. */
65
- destinationRoot?: string;
66
- /** Injectable clock forwarded to JsonStore. */
67
- now?: () => number;
68
- /** Maximum recognized files imported in one pass. */
69
- maxFiles?: number;
70
- /** Maximum bytes read from one source file. */
71
- maxFileBytes?: number;
72
- }
73
-
74
- /** Options for the bounded migration of aliases created by the v0.5.2 scope rules. */
75
- export interface ScopeAliasMigrationOptions {
76
- /** Override the old root; defaults to `<agentDir>/pi-persona-mind`. */
77
- legacyRoot?: string;
78
- /** Override the current root; defaults to `<agentDir>/persona-mind`. */
79
- currentRoot?: string;
80
- /** Injectable project canonicalization seam, forwarded to {@link projectSlug}. */
81
- project?: ProjectSlugOptions;
82
- /** Platform seam for the persona filename rule. Defaults to the project platform when supplied. */
83
- personaPlatform?: NodeJS.Platform | string;
84
- /** Injectable clock forwarded to JsonStore. */
85
- now?: () => number;
86
- /** Import a lossy/reserved persona alias only when an explicit user command opts in. */
87
- includeAmbiguousPersonaAlias?: boolean;
88
- /** Maximum bytes read from one source file. */
89
- maxFileBytes?: number;
90
- }
91
-
92
- function emptyReport(): MigrationReport {
93
- return {
94
- filesScanned: 0,
95
- filesSkipped: 0,
96
- filesMigrated: 0,
97
- entriesSeen: 0,
98
- entriesAdded: 0,
99
- conflicts: 0,
100
- invalidEntries: 0,
101
- warnings: [],
102
- };
103
- }
104
-
105
- interface LegacySourceStamp {
106
- id: string;
107
- source: string;
108
- destination: string;
109
- kind: ImportKind;
110
- size: string;
111
- mtimeNs: string;
112
- ctimeNs: string;
113
- dev: string;
114
- ino: string;
115
- }
116
-
117
- const DECIMAL = /^\d+$/;
118
-
119
- function validateLegacySourceStamp(raw: unknown): LegacySourceStamp | null {
120
- if (!isRecord(raw)) return null;
121
- if (typeof raw.id !== "string" || !/^[a-f0-9]{24}$/.test(raw.id)) return null;
122
- if (typeof raw.source !== "string" || !raw.source || raw.source.length > 8_192) return null;
123
- if (typeof raw.destination !== "string" || !raw.destination || raw.destination.length > 8_192) return null;
124
- if (raw.kind !== "ltm" && raw.kind !== "stm" && raw.kind !== "backlog") return null;
125
- for (const field of [raw.size, raw.mtimeNs, raw.ctimeNs, raw.dev, raw.ino]) {
126
- if (typeof field !== "string" || !DECIMAL.test(field)) return null;
127
- }
128
- return raw as unknown as LegacySourceStamp;
129
- }
130
-
131
- async function sourceStamp(source: string, destination: string, kind: ImportKind): Promise<LegacySourceStamp | null> {
132
- try {
133
- const stats = await lstat(source, { bigint: true });
134
- if (!stats.isFile()) return null;
135
- return {
136
- id: createHash("sha256").update(`${resolve(source)}\0${resolve(destination)}`).digest("hex").slice(0, 24),
137
- source: resolve(source),
138
- destination: resolve(destination),
139
- kind,
140
- size: stats.size.toString(),
141
- mtimeNs: stats.mtimeNs.toString(),
142
- ctimeNs: stats.ctimeNs.toString(),
143
- dev: stats.dev.toString(),
144
- ino: stats.ino.toString(),
145
- };
146
- } catch {
147
- return null;
148
- }
149
- }
150
-
151
- function sameStamp(a: LegacySourceStamp, b: LegacySourceStamp): boolean {
152
- return a.source === b.source && a.destination === b.destination && a.kind === b.kind && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs && a.dev === b.dev && a.ino === b.ino;
153
- }
154
-
155
- async function regularFileExists(path: string): Promise<boolean> {
156
- try {
157
- return (await lstat(path)).isFile();
158
- } catch {
159
- return false;
160
- }
161
- }
162
-
163
- function oldPersonaSegment(name: string, _platform: NodeJS.Platform | string = process.platform): string {
164
- const segment = name
165
- .replace(/[^a-zA-Z0-9._-]+/g, "-")
166
- .replace(/^[-.]+|[-.]+$/g, "")
167
- .slice(0, 64);
168
- if (!segment) return `persona-${createHash("sha256").update(name).digest("hex").slice(0, 12)}`;
169
- const reserved = segment.toLowerCase() === "_shared" || segment.toLowerCase() === "_default" || WIN_RESERVED_DEVICE.test(segment);
170
- return reserved ? `persona-${segment}` : segment;
171
- }
172
-
173
- function oldProjectSlug(projectRoot: string, platform: NodeJS.Platform | string = process.platform): string {
174
- const canonical = platform === "win32" ? win32.resolve(projectRoot) : resolve(projectRoot);
175
- const hash = createHash("sha256").update(canonical).digest("hex").slice(0, 24);
176
- const baseName = platform === "win32" ? win32.basename(canonical) : basename(canonical);
177
- const base =
178
- (baseName || "project")
179
- .replace(/[^a-zA-Z0-9._-]+/g, "-")
180
- .replace(/^-+|-+$/g, "")
181
- .slice(0, 48) || "project";
182
- return `${base}-${hash}`;
183
- }
184
-
185
- function isRecord(value: unknown): value is Record<string, unknown> {
186
- return typeof value === "object" && value !== null;
187
- }
188
-
189
- async function readBounded(path: string, maxBytes: number, report: MigrationReport, label: string): Promise<string | null> {
190
- try {
191
- return await readTextFileBounded(path, maxBytes);
192
- } catch (err) {
193
- if ((err as NodeJS.ErrnoException).code !== "ENOENT") warning(report, `${label}: could not read ${path}: ${String(err)}`);
194
- return null;
195
- }
196
- }
197
-
198
- export type StoreDiagnosticStatus = "missing" | "ok" | "invalid" | "corrupt";
199
-
200
- export interface StoreDiagnostic {
201
- path: string;
202
- status: StoreDiagnosticStatus;
203
- validEntries: number;
204
- invalidEntries: number;
205
- message?: string;
206
- }
207
-
208
- /** Read-only store validation for `/mind doctor`; unlike JsonStore.load this never quarantines. */
209
- export async function inspectStoreFile(
210
- path: string,
211
- kind: ImportKind,
212
- maxFileBytes = DEFAULT_MAX_FILE_BYTES,
213
- maxEntries = DEFAULT_STORE_MAX_ENTRIES,
214
- ): Promise<StoreDiagnostic> {
215
- let raw: string;
216
- try {
217
- raw = await readTextFileBounded(path, maxFileBytes);
218
- } catch (err) {
219
- if ((err as NodeJS.ErrnoException).code === "ENOENT") return { path, status: "missing", validEntries: 0, invalidEntries: 0 };
220
- return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: String(err) };
221
- }
222
- let parsed: unknown;
223
- try {
224
- parsed = JSON.parse(raw);
225
- } catch {
226
- return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: "invalid JSON" };
227
- }
228
- // Name a version skew explicitly: an operator reading `/mind doctor` must be able to tell "another
229
- // build wrote this" (nothing to repair here) from "these bytes are damaged". The predicate must
230
- // match JsonStore.parseStore EXACTLY — it refuses only a positive safe-integer version on an
231
- // otherwise well-formed envelope, and QUARANTINES everything else. Promising "left untouched" for
232
- // a shape load() moves aside to `*.corrupt-N` would send the operator away from a live data loss.
233
- if (isRecord(parsed) && Array.isArray(parsed.entries) && typeof parsed.version === "number" && Number.isSafeInteger(parsed.version) && parsed.version > 0 && parsed.version !== STORE_VERSION) {
234
- return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: `store version ${parsed.version} was written by a different pi-persona-mind build (this one reads version ${STORE_VERSION}); it is left untouched` };
235
- }
236
- if (!isRecord(parsed) || parsed.version !== STORE_VERSION || typeof parsed.updatedAt !== "string" || !Number.isFinite(Date.parse(parsed.updatedAt)) || typeof parsed.sequence !== "number" || !Number.isSafeInteger(parsed.sequence) || parsed.sequence < 0 || !Array.isArray(parsed.entries)) {
237
- return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: "invalid store envelope" };
238
- }
239
- if (parsed.entries.length > maxEntries) {
240
- return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: `exceeds ${maxEntries}-entry limit` };
241
- }
242
- const validate = kind === "ltm" ? validateLongMemory : kind === "stm" ? validateShortMemory : validateBacklog;
243
- let validEntries = 0;
244
- let invalidEntries = 0;
245
- for (const entry of parsed.entries) {
246
- if (validate(entry) === null) invalidEntries++;
247
- else validEntries++;
248
- }
249
- return { path, status: invalidEntries > 0 ? "invalid" : "ok", validEntries, invalidEntries, ...(invalidEntries > 0 ? { message: `${invalidEntries} invalid entr${invalidEntries === 1 ? "y" : "ies"}` } : {}) };
250
- }
251
-
252
- function warning(report: MigrationReport, message: string): void {
253
- report.warnings.push(message);
254
- }
255
-
256
- function canonicalizeEntry<E>(entry: E): E {
257
- if (!isRecord(entry) || typeof entry.text !== "string" || !Array.isArray(entry.tags)) return entry;
258
- const tags = entry.tags.filter((tag): tag is string => typeof tag === "string");
259
- const kind = typeof entry.kind === "string" ? entry.kind : "backlog";
260
- const id = contentId(kind, entry.text, tags);
261
- return typeof entry.id === "string" && entry.id !== id ? ({ ...entry, id } as E) : entry;
262
- }
263
-
264
- function entryIdentity(entry: unknown): string {
265
- if (!isRecord(entry)) return JSON.stringify(entry);
266
- const tags = Array.isArray(entry.tags) ? entry.tags.filter((tag): tag is string => typeof tag === "string").map((tag) => tag.trim().toLowerCase()).filter(Boolean).sort() : [];
267
- // Content identity is semantic, not the serialized id: v1 comma-joined tags and the
268
- // collision-safe v2 encoding can address the same fact with different hashes. Conversely,
269
- // distinct facts that once collided still differ by their normalized tag arrays/text here.
270
- if (typeof entry.kind === "string" && typeof entry.text === "string") return JSON.stringify([entry.kind, entry.text.trim().replace(/\s+/g, " ").toLowerCase(), tags]);
271
- if (typeof entry.state === "string" && typeof entry.text === "string") return JSON.stringify(["backlog", entry.text.trim().replace(/\s+/g, " ").toLowerCase(), tags]);
272
- return JSON.stringify(entry);
273
- }
274
-
275
- interface ParsedLegacy<E> {
276
- entries: E[];
277
- invalidEntries: number;
278
- }
279
-
280
- /** Why one source could not be read as a store. The caller reports it — it may first retry a `.bak`. */
281
- interface LegacyParseFailure {
282
- failure: string;
283
- }
284
-
285
- function isParseFailure<E>(result: ParsedLegacy<E> | LegacyParseFailure): result is LegacyParseFailure {
286
- return "failure" in result;
287
- }
288
-
289
- function parseLegacy<E>(raw: string, validate: (value: unknown) => E | null, path: string, report: MigrationReport): ParsedLegacy<E> | LegacyParseFailure {
290
- let parsed: unknown;
291
- try {
292
- parsed = JSON.parse(raw);
293
- } catch {
294
- return { failure: `legacy mind: could not parse ${path}` };
295
- }
296
- if (!isRecord(parsed) || !Array.isArray(parsed.entries)) {
297
- return { failure: `legacy mind: ${path} has no entries array` };
298
- }
299
-
300
- const entries: E[] = [];
301
- let invalidEntries = 0;
302
- const identities = new Set<string>();
303
- for (const rawEntry of parsed.entries) {
304
- const entry = validate(canonicalizeEntry(rawEntry));
305
- if (entry === null) {
306
- invalidEntries++;
307
- continue;
308
- }
309
- const identity = entryIdentity(entry);
310
- if (identities.has(identity)) continue;
311
- identities.add(identity);
312
- entries.push(entry);
313
- }
314
- if (invalidEntries > 0) warning(report, `legacy mind: ${path} contained ${invalidEntries} invalid entr${invalidEntries === 1 ? "y" : "ies"}`);
315
- return { entries, invalidEntries };
316
- }
317
-
318
- /**
319
- * Read one legacy store, falling back to the `<file>.bak` sidecar JsonStore maintains beside every
320
- * store (store.ts) when the live bytes are torn. This import is the only pass that will ever carry
321
- * those entries across — the release note invites the user to delete the legacy root afterwards — so
322
- * a recoverable last-known-good copy must not be abandoned. null ⇒ nothing was read: the caller must
323
- * NOT stamp the source, or the next start's skip test would bury the damage forever.
324
- */
325
- async function readLegacyStore<E>(
326
- legacyPath: string,
327
- validate: (value: unknown) => E | null,
328
- report: MigrationReport,
329
- maxFileBytes: number,
330
- ): Promise<ParsedLegacy<E> | null> {
331
- const raw = await readBounded(legacyPath, maxFileBytes, report, "legacy mind");
332
- if (raw === null) return null;
333
- const parsed = parseLegacy<E>(raw, validate, legacyPath, report);
334
- if (!isParseFailure(parsed)) return parsed;
335
- // Only a source we could READ but not PARSE is torn. A source that vanished mid-scan is gone, and
336
- // importing a leftover sidecar for it would resurrect data the user deleted.
337
- const backupPath = `${legacyPath}.bak`;
338
- const backupRaw = await readBounded(backupPath, maxFileBytes, report, "legacy mind");
339
- const backup = backupRaw === null ? null : parseLegacy<E>(backupRaw, validate, backupPath, report);
340
- // A sidecar that parses to NOTHING is not a recovery: accepting it would let the caller stamp the
341
- // torn source as imported, and the skip test would then bury it on every later start — the exact
342
- // burial this fallback exists to prevent.
343
- if (backup !== null && !isParseFailure(backup) && backup.entries.length > 0) {
344
- warning(report, `${parsed.failure}; recovered its last-known-good ${backupPath}`);
345
- return backup;
346
- }
347
- warning(report, `${parsed.failure}; no usable ${backupPath} either — nothing was imported from it`);
348
- return null;
349
- }
350
-
351
- async function importFile(
352
- legacyPath: string,
353
- destinationPath: string,
354
- kind: ImportKind,
355
- report: MigrationReport,
356
- now: (() => number) | undefined,
357
- maxFileBytes: number,
358
- memoryLock: string,
359
- ): Promise<boolean> {
360
- if (kind === "ltm" || kind === "stm") {
361
- const validate = kind === "ltm" ? validateLongMemory : validateShortMemory;
362
- const parsed = await readLegacyStore<MemoryEntry>(legacyPath, validate, report, maxFileBytes);
363
- if (parsed === null) return false;
364
- report.entriesSeen += parsed.entries.length;
365
- report.invalidEntries += parsed.invalidEntries;
366
- if (parsed.entries.length === 0) return true;
367
- const store = new JsonStore<MemoryEntry>(destinationPath, makeStoreOptions(validate, now, report));
368
- // Source IO remains outside the lock; only destination selection/merge shares foreground ordering.
369
- return withFileLock(memoryLock, () => mergeImport(store, parsed.entries, report, legacyPath, "legacy mind", reconcileMemory));
370
- } else {
371
- const parsed = await readLegacyStore<BacklogEntry>(legacyPath, validateBacklog, report, maxFileBytes);
372
- if (parsed === null) return false;
373
- report.entriesSeen += parsed.entries.length;
374
- report.invalidEntries += parsed.invalidEntries;
375
- if (parsed.entries.length === 0) return true;
376
- const store = new JsonStore<BacklogEntry>(destinationPath, makeStoreOptions(validateBacklog, now, report));
377
- return mergeImport(store, parsed.entries, report, legacyPath, "legacy mind", reconcileBacklog);
378
- }
379
- }
380
-
381
- function makeStoreOptions<E>(validateEntry: (raw: unknown) => E | null, now: (() => number) | undefined, report: MigrationReport): JsonStoreOptions<E> {
382
- const options: JsonStoreOptions<E> = {
383
- version: STORE_VERSION,
384
- validateEntry,
385
- onWarn: (message) => warning(report, message),
386
- };
387
- if (now !== undefined) options.now = now;
388
- return options;
389
- }
390
-
391
- /**
392
- * How one semantic-identity collision is settled. Returns the destination record ITSELF when the
393
- * incoming copy carries nothing later — identity comparison is what keeps an unchanged import a
394
- * genuine no-op that does not bump the store sequence.
395
- */
396
- type Reconcile<E> = (destination: E, incoming: E) => E;
397
-
398
- /**
399
- * Settle two copies of one fact by FRESHNESS, not by which root they came from.
400
- *
401
- * The destination is no longer the newer root: 0.7.0 promotes the pre-0.6 snapshot that the 0.6.x
402
- * importer drained and deliberately left populated to DESTINATION, so keeping its record on every
403
- * match would resurrect a superseded copy — a dead `expiresAt` re-expiring a live short-term memory.
404
- * This is `upsertMemory`'s own live rule rather than a second reconciliation: identity (`id`) and
405
- * first-recorded (`recordedAt`) stay the destination's, and everything the user last touched comes
406
- * from whichever copy was seen last. Both sides are validated, so `lastSeenAt` parses on both.
407
- */
408
- function reconcileMemory(destination: MemoryEntry, incoming: MemoryEntry): MemoryEntry {
409
- if (Date.parse(incoming.lastSeenAt) <= Date.parse(destination.lastSeenAt)) return destination;
410
- return { ...incoming, id: destination.id, recordedAt: destination.recordedAt };
411
- }
412
-
413
- /** open → taken → done/dropped; the state machine (backlog.ts) only ever moves forward. */
414
- const BACKLOG_PROGRESS: Readonly<Record<BacklogState, number>> = { open: 0, taken: 1, done: 2, dropped: 2 };
415
-
416
- /**
417
- * Settle two copies of one lead by LIFECYCLE PROGRESS, so a terminal state and its note survive a
418
- * merge in either direction and finished work never reverts to `open`.
419
- *
420
- * `state` deliberately stays out of the identity: `contentId("backlog", text, tags)` ignores it, so
421
- * adding it here would leave an open row and a done row sharing one content id — which the ambiguity
422
- * guards then refuse to act on, and which `backlog list` shows twice. Because the state machine only
423
- * moves forward, the further-along record is the later one; taking it whole also carries over the
424
- * `dueAtEpochMs` that `acknowledgeDue` already cleared, so a delivered wake is not re-armed.
425
- */
426
- function reconcileBacklog(destination: BacklogEntry, incoming: BacklogEntry): BacklogEntry {
427
- if (BACKLOG_PROGRESS[incoming.state] <= BACKLOG_PROGRESS[destination.state]) return destination;
428
- // Carry only what the LIFECYCLE owns: the state, the note that explains it, and the due date, which
429
- // finishing a lead CLEARS — keeping the superseded copy's would re-arm a wake the user already
430
- // acknowledged. Identity and retention stay with the destination: taking the further-along copy
431
- // wholesale would drag its `expiresAt` across against the destination's own `createdAt`, and a
432
- // superseded lifetime can predate it, leaving a row that expires before it exists.
433
- const merged: BacklogEntry = { ...destination, state: incoming.state };
434
- if (incoming.note === undefined) delete merged.note;
435
- else merged.note = incoming.note;
436
- if (incoming.dueAtEpochMs === undefined) delete merged.dueAtEpochMs;
437
- else merged.dueAtEpochMs = incoming.dueAtEpochMs;
438
- return merged;
439
- }
440
-
441
- /** First occurrence wins, so the pre-read check and the locked mutator agree on the destination copy. */
442
- function byIdentity<E>(entries: readonly E[]): Map<string, { at: number; entry: E }> {
443
- const index = new Map<string, { at: number; entry: E }>();
444
- for (const [at, entry] of entries.entries()) {
445
- const identity = entryIdentity(entry);
446
- if (!index.has(identity)) index.set(identity, { at, entry });
447
- }
448
- return index;
449
- }
450
-
451
- async function merge<E extends { id: string }>(store: JsonStore<E>, incoming: readonly E[], report: MigrationReport, reconcile: Reconcile<E>): Promise<void> {
452
- // A read avoids an unnecessary sequence bump on a repeat import. The update
453
- // callback still re-checks identities while holding JsonStore's per-file lock.
454
- const current = byIdentity((await store.load()).entries);
455
- // Count conflicts the way the merge actually dedups — by semantic identity. Counting serialized
456
- // ids instead let the v2 twin of a record written under the v1 comma-joined id be dropped by the
457
- // dedup below without the report ever saying so.
458
- let pending = false;
459
- for (const entry of incoming) {
460
- const held = current.get(entryIdentity(entry));
461
- if (held === undefined) {
462
- pending = true;
463
- continue;
464
- }
465
- report.conflicts++;
466
- if (reconcile(held.entry, entry) !== held.entry) pending = true;
467
- }
468
- if (!pending) return;
469
-
470
- let addedHere = 0;
471
- await store.update((entries) => {
472
- // JsonStore may replay the mutator after lock-ownership recovery; diagnostics must describe
473
- // the committed attempt, not accumulate counts from abandoned attempts.
474
- addedHere = 0;
475
- const next = [...entries];
476
- const held = byIdentity(next);
477
- for (const entry of incoming) {
478
- const identity = entryIdentity(entry);
479
- const existing = held.get(identity);
480
- if (existing === undefined) {
481
- held.set(identity, { at: next.length, entry });
482
- next.push(entry);
483
- addedHere++;
484
- continue;
485
- }
486
- const reconciled = reconcile(existing.entry, entry);
487
- if (reconciled === existing.entry) continue;
488
- next[existing.at] = reconciled;
489
- held.set(identity, { at: existing.at, entry: reconciled });
490
- addedHere++;
491
- }
492
- return next;
493
- });
494
- if (addedHere > 0) {
495
- report.entriesAdded += addedHere;
496
- report.filesMigrated++;
497
- }
498
- }
499
-
500
- /** A full destination is a source-local migration failure, not a reason to stop scanning. */
501
- async function mergeImport<E extends { id: string }>(
502
- store: JsonStore<E>,
503
- incoming: readonly E[],
504
- report: MigrationReport,
505
- sourcePath: string,
506
- label: string,
507
- reconcile: Reconcile<E>,
508
- ): Promise<boolean> {
509
- try {
510
- await merge(store, incoming, report, reconcile);
511
- return true;
512
- } catch (err) {
513
- if (!(err instanceof StoreCapacityError)) throw err;
514
- warning(report, `${label}: skipped ${sourcePath} — ${err.message}`);
515
- return false;
516
- }
517
- }
518
-
519
- async function importAliasFile(
520
- sourcePath: string,
521
- destinationPath: string,
522
- kind: ImportKind,
523
- report: MigrationReport,
524
- now: (() => number) | undefined,
525
- maxFileBytes: number,
526
- memoryLock: string,
527
- ): Promise<void> {
528
- if (!(await regularFileExists(sourcePath))) return;
529
- report.filesScanned++;
530
-
531
- if (kind === "ltm" || kind === "stm") {
532
- const validate = kind === "ltm" ? validateLongMemory : validateShortMemory;
533
- // Same `.bak` recovery as the legacy-root pass: nothing else ever opens the OLD alias filename
534
- // (`mindPaths` only returns the new names), so this is the one pass that can rescue a torn one.
535
- const parsed = await readLegacyStore<MemoryEntry>(sourcePath, validate, report, maxFileBytes);
536
- if (parsed === null) return;
537
- report.entriesSeen += parsed.entries.length;
538
- report.invalidEntries += parsed.invalidEntries;
539
- if (parsed.entries.length === 0) return;
540
- await withFileLock(memoryLock, () => mergeImport(new JsonStore<MemoryEntry>(destinationPath, makeStoreOptions(validate, now, report)), parsed.entries, report, sourcePath, "scope alias", reconcileMemory));
541
- return;
542
- }
543
-
544
- const parsed = await readLegacyStore<BacklogEntry>(sourcePath, validateBacklog, report, maxFileBytes);
545
- if (parsed === null) return;
546
- report.entriesSeen += parsed.entries.length;
547
- report.invalidEntries += parsed.invalidEntries;
548
- if (parsed.entries.length === 0) return;
549
- await mergeImport(new JsonStore<BacklogEntry>(destinationPath, makeStoreOptions(validateBacklog, now, report)), parsed.entries, report, sourcePath, "scope alias", reconcileBacklog);
550
- }
551
-
552
- /**
553
- * A backlog record carries the persona segment that was current when it was written, and the segment
554
- * rule changed in 0.5.2 — so a record written by an older version no longer matches the live scope
555
- * and the persona view silently returns nothing (while the injected block still shows the items).
556
- * Rewrite only THIS persona's own historical segment; another persona's records are left alone, and
557
- * the no-persona scope is never touched (its records were always written as the `_default` segment).
558
- */
559
- async function reconcileBacklogPersona(
560
- path: string,
561
- from: string,
562
- to: string,
563
- report: MigrationReport,
564
- now: (() => number) | undefined,
565
- ): Promise<void> {
566
- const store = new JsonStore<BacklogEntry>(path, makeStoreOptions(validateBacklog, now, report));
567
- let reconciled = 0;
568
- try {
569
- // Read first so an already-current store is a genuine no-op and does not bump its sequence.
570
- if (!(await store.load()).entries.some((entry) => entry.persona === from)) return;
571
- await store.update((entries) => {
572
- // JsonStore may replay the mutator after lock recovery; count the committed attempt only.
573
- reconciled = 0;
574
- return entries.map((entry) => {
575
- if (entry.persona !== from) return entry;
576
- reconciled++;
577
- return { ...entry, persona: to };
578
- });
579
- });
580
- } catch (err) {
581
- warning(report, `scope alias: could not reconcile the stored persona of ${path}: ${String(err)}`);
582
- return;
583
- }
584
- if (reconciled > 0) {
585
- report.entriesAdded += reconciled;
586
- report.filesMigrated++;
587
- }
588
- }
589
-
590
- /**
591
- * Reconciles at most three old filenames for one already-visited scope, then the persona segment
592
- * stored inside the current backlog. It does not scan either root: callers choose when a scope is
593
- * active, keeping startup bounded. Sources are read-only; destination updates use JsonStore locking.
594
- */
595
- export async function migrateCurrentScopeAliases(
596
- agentDir: string,
597
- rawPersona: string | null,
598
- projectRoot: string,
599
- options: ScopeAliasMigrationOptions = {},
600
- ): Promise<MigrationReport> {
601
- const report = emptyReport();
602
- const platform = options.personaPlatform ?? options.project?.platform;
603
- const persona = rawPersona === null ? DEFAULT_PERSONA : sanitizePersona(rawPersona, platform);
604
- const project = projectSlug(projectRoot, options.project);
605
- const oldPersona = oldPersonaSegment(rawPersona ?? DEFAULT_PERSONA, platform);
606
- const oldProject = oldProjectSlug(projectRoot, options.project?.platform);
607
- const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
608
- const legacyRoot = options.legacyRoot ?? join(agentDir, "pi-persona-mind");
609
- const currentRoot = options.currentRoot ?? join(agentDir, "persona-mind");
610
- const memoryLock = memoryMutationLockPath({ shared: join(currentRoot, "memory", "ltm", `${SHARED_SCOPE}.json`) });
611
- const currentBase = currentRoot;
612
- const roots = [currentRoot, legacyRoot];
613
- const aliases: readonly { kind: ImportKind; oldRelative: string; newRelative: string }[] = [
614
- ...(options.includeAmbiguousPersonaAlias ? [{ kind: "ltm" as const, oldRelative: join("memory", "ltm", `${oldPersona}.json`), newRelative: join("memory", "ltm", `${persona}.json`) }] : []),
615
- { kind: "stm", oldRelative: join("memory", "stm", `${oldProject}.json`), newRelative: join("memory", "stm", `${project}.json`) },
616
- { kind: "backlog", oldRelative: join("backlog", `${oldProject}.json`), newRelative: join("backlog", `${project}.json`) },
617
- ];
618
- const visited = new Set<string>();
619
- for (const alias of aliases) {
620
- // A stable ordinary name has no alias to reconcile. This also guarantees
621
- // the common path is a genuine no-op and does not bump store sequence.
622
- if (alias.oldRelative === alias.newRelative) continue;
623
- const destination = join(currentBase, alias.newRelative);
624
- for (const root of roots) {
625
- const sourcePath = join(root, alias.oldRelative);
626
- if (sourcePath === destination || visited.has(sourcePath)) continue;
627
- visited.add(sourcePath);
628
- await importAliasFile(sourcePath, destination, alias.kind, report, options.now, maxFileBytes, memoryLock);
629
- }
630
- }
631
- // After the filenames are reconciled, repair the persona segment embedded in the backlog records
632
- // themselves — nothing else rewrites it, so the view would stay empty for the rest of time.
633
- if (rawPersona !== null && oldPersona !== persona) {
634
- await reconcileBacklogPersona(join(currentBase, "backlog", `${project}.json`), oldPersona, persona, report, options.now);
635
- }
636
- return report;
637
- }
638
-
639
- /**
640
- * Import supported files from `<agentDir>/pi-persona-mind` into the current
641
- * `<agentDir>/persona-mind` root. It is safe to call repeatedly and from
642
- * concurrent processes. The legacy root is never written.
643
- */
644
- export async function migrateLegacyRoot(agentDir: string, options: LegacyMigrationOptions = {}): Promise<MigrationReport> {
645
- const report = emptyReport();
646
- const legacyRoot = options.legacyRoot ?? join(agentDir, "pi-persona-mind");
647
- const destinationRoot = options.destinationRoot ?? join(agentDir, "persona-mind");
648
- const memoryLock = memoryMutationLockPath({ shared: join(destinationRoot, "memory", "ltm", `${SHARED_SCOPE}.json`) });
649
- const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
650
- const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
651
- const manifest = new JsonStore<LegacySourceStamp>(
652
- join(destinationRoot, LEGACY_MANIFEST_FILE),
653
- makeStoreOptions(validateLegacySourceStamp, options.now, report),
654
- );
655
- const known = new Map((await manifest.load()).entries.map((entry) => [entry.id, entry]));
656
- const processed: LegacySourceStamp[] = [];
657
- let recognized = 0;
658
-
659
- directories:
660
- for (const directory of IMPORT_DIRECTORIES) {
661
- const sourceDirectory = join(legacyRoot, directory.relative);
662
- let handle: Awaited<ReturnType<typeof opendir>> | undefined;
663
- try {
664
- handle = await opendir(sourceDirectory);
665
- for await (const file of handle) {
666
- if (!file.isFile() || !file.name.toLowerCase().endsWith(".json")) continue;
667
- if (recognized >= maxFiles) {
668
- warning(report, `legacy mind: stopped after the ${maxFiles}-file migration limit`);
669
- break directories;
670
- }
671
- recognized++;
672
- const relativeFile = join(directory.relative, file.name);
673
- const source = join(legacyRoot, relativeFile);
674
- const destination = join(destinationRoot, relativeFile);
675
- try {
676
- const stamp = await sourceStamp(source, destination, directory.kind);
677
- const previous = stamp ? known.get(stamp.id) : undefined;
678
- if (stamp && previous && sameStamp(stamp, previous) && (await regularFileExists(destination))) {
679
- report.filesSkipped++;
680
- continue;
681
- }
682
- report.filesScanned++;
683
- if (await importFile(source, destination, directory.kind, report, options.now, maxFileBytes, memoryLock)) {
684
- const committedStamp = stamp ?? (await sourceStamp(source, destination, directory.kind));
685
- if (committedStamp) processed.push(committedStamp);
686
- }
687
- } catch (err) {
688
- // One destination's failure (a version skew, a lock timeout under two concurrent Pi
689
- // starts, an EPERM on the Windows rename) belongs to THIS source. Letting it reach the
690
- // directory catch aborts the iteration, and readdir order is stable — every later file
691
- // would be stranded, unnamed, on every subsequent start.
692
- warning(report, `legacy mind: could not import ${source}: ${String(err)}`);
693
- }
694
- }
695
- } catch (err) {
696
- if ((err as NodeJS.ErrnoException).code !== "ENOENT") warning(report, `legacy mind: could not scan ${sourceDirectory}: ${String(err)}`);
697
- } finally {
698
- await handle?.close().catch(() => {});
699
- }
700
- }
701
- if (processed.length > 0) {
702
- try {
703
- await manifest.update((entries) => {
704
- const next = new Map(entries.map((entry) => [entry.id, entry]));
705
- for (const entry of processed) next.set(entry.id, entry);
706
- return [...next.values()].sort((a, b) => a.source.localeCompare(b.source));
707
- });
708
- } catch (err) {
709
- warning(report, `legacy mind: imported data but could not update the source manifest: ${String(err)}`);
710
- }
711
- }
712
- return report;
713
- }
1
+ /**
2
+ * One-way importer for the superseded `pi-`prefixed storage root.
3
+ *
4
+ * The old root is only read. Memory merges join the profile transaction lock before JsonStore's
5
+ * per-file lock, coordinating background import with foreground edits across projects. Two copies of one fact
6
+ * are reconciled by which copy is LATER, not by which root it sits in; distinct
7
+ * same-id content is preserved. Filenames and legacy bytes are not rewritten or removed.
8
+ */
9
+
10
+ import { lstat, opendir } from "node:fs/promises";
11
+ import { createHash } from "node:crypto";
12
+ import { basename, join, resolve, win32 } from "node:path";
13
+
14
+ import type { BacklogEntry, BacklogState } from "./backlog.ts";
15
+ import { validateBacklog } from "./backlog.ts";
16
+ import type { MemoryEntry } from "./memory.ts";
17
+ import { validateLongMemory, validateShortMemory } from "./memory.ts";
18
+ import { contentId } from "./ids.ts";
19
+ import { DEFAULT_PERSONA, memoryMutationLockPath, projectSlug, sanitizePersona, SHARED_SCOPE, type ProjectSlugOptions } from "./scope.ts";
20
+ import { DEFAULT_STORE_MAX_ENTRIES, JsonStore, readTextFileBounded, StoreCapacityError, withFileLock, type JsonStoreOptions } from "./store.ts";
21
+
22
+ const STORE_VERSION = 1;
23
+ const WIN_RESERVED_DEVICE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
24
+ const DEFAULT_MAX_FILES = 256;
25
+ const DEFAULT_MAX_FILE_BYTES = 4 * 1024 * 1024;
26
+ const LEGACY_MANIFEST_FILE = ".legacy-import-v1.json";
27
+
28
+ export type ImportKind = "ltm" | "stm" | "backlog";
29
+
30
+ interface ImportDirectory {
31
+ relative: string;
32
+ kind: ImportKind;
33
+ }
34
+
35
+ const IMPORT_DIRECTORIES: readonly ImportDirectory[] = [
36
+ { relative: join("memory", "ltm"), kind: "ltm" },
37
+ { relative: join("memory", "stm"), kind: "stm" },
38
+ { relative: "backlog", kind: "backlog" },
39
+ ];
40
+
41
+ /** Counts and diagnostics returned by {@link migrateLegacyRoot}. */
42
+ export interface MigrationReport {
43
+ /** Recognized JSON files whose contents were read under the three supported legacy directories. */
44
+ filesScanned: number;
45
+ /** Unchanged legacy files skipped from content read/parse by the durable source manifest. */
46
+ filesSkipped: number;
47
+ /** Files a commit touched: a recognized source that yielded at least one imported entry, or a
48
+ * current destination whose stored records were reconciled in place (see `entriesAdded`). */
49
+ filesMigrated: number;
50
+ /** Valid, source-semantic-unique legacy entries considered. */
51
+ entriesSeen: number;
52
+ /** Entries newly appended to, or reconciled in place in, the current destination. */
53
+ entriesAdded: number;
54
+ /** Valid entries the destination already held under the same semantic identity (kept or reconciled). */
55
+ conflicts: number;
56
+ /** Entries rejected by the current schema validator. */
57
+ invalidEntries: number;
58
+ warnings: string[];
59
+ }
60
+
61
+ export interface LegacyMigrationOptions {
62
+ /** Override the old root; defaults to `<agentDir>/pi-persona-mind`. */
63
+ legacyRoot?: string;
64
+ /** Override the current root; defaults to `<agentDir>/persona-mind`. */
65
+ destinationRoot?: string;
66
+ /** Injectable clock forwarded to JsonStore. */
67
+ now?: () => number;
68
+ /** Maximum recognized files imported in one pass. */
69
+ maxFiles?: number;
70
+ /** Maximum bytes read from one source file. */
71
+ maxFileBytes?: number;
72
+ }
73
+
74
+ /** Options for the bounded migration of aliases created by the v0.5.2 scope rules. */
75
+ export interface ScopeAliasMigrationOptions {
76
+ /** Override the old root; defaults to `<agentDir>/pi-persona-mind`. */
77
+ legacyRoot?: string;
78
+ /** Override the current root; defaults to `<agentDir>/persona-mind`. */
79
+ currentRoot?: string;
80
+ /** Injectable project canonicalization seam, forwarded to {@link projectSlug}. */
81
+ project?: ProjectSlugOptions;
82
+ /** Platform seam for the persona filename rule. Defaults to the project platform when supplied. */
83
+ personaPlatform?: NodeJS.Platform | string;
84
+ /** Injectable clock forwarded to JsonStore. */
85
+ now?: () => number;
86
+ /** Import a lossy/reserved persona alias only when an explicit user command opts in. */
87
+ includeAmbiguousPersonaAlias?: boolean;
88
+ /** Maximum bytes read from one source file. */
89
+ maxFileBytes?: number;
90
+ }
91
+
92
+ function emptyReport(): MigrationReport {
93
+ return {
94
+ filesScanned: 0,
95
+ filesSkipped: 0,
96
+ filesMigrated: 0,
97
+ entriesSeen: 0,
98
+ entriesAdded: 0,
99
+ conflicts: 0,
100
+ invalidEntries: 0,
101
+ warnings: [],
102
+ };
103
+ }
104
+
105
+ interface LegacySourceStamp {
106
+ id: string;
107
+ source: string;
108
+ destination: string;
109
+ kind: ImportKind;
110
+ size: string;
111
+ mtimeNs: string;
112
+ ctimeNs: string;
113
+ dev: string;
114
+ ino: string;
115
+ }
116
+
117
+ const DECIMAL = /^\d+$/;
118
+
119
+ function validateLegacySourceStamp(raw: unknown): LegacySourceStamp | null {
120
+ if (!isRecord(raw)) return null;
121
+ if (typeof raw.id !== "string" || !/^[a-f0-9]{24}$/.test(raw.id)) return null;
122
+ if (typeof raw.source !== "string" || !raw.source || raw.source.length > 8_192) return null;
123
+ if (typeof raw.destination !== "string" || !raw.destination || raw.destination.length > 8_192) return null;
124
+ if (raw.kind !== "ltm" && raw.kind !== "stm" && raw.kind !== "backlog") return null;
125
+ for (const field of [raw.size, raw.mtimeNs, raw.ctimeNs, raw.dev, raw.ino]) {
126
+ if (typeof field !== "string" || !DECIMAL.test(field)) return null;
127
+ }
128
+ return raw as unknown as LegacySourceStamp;
129
+ }
130
+
131
+ async function sourceStamp(source: string, destination: string, kind: ImportKind): Promise<LegacySourceStamp | null> {
132
+ try {
133
+ const stats = await lstat(source, { bigint: true });
134
+ if (!stats.isFile()) return null;
135
+ return {
136
+ id: createHash("sha256").update(`${resolve(source)}\0${resolve(destination)}`).digest("hex").slice(0, 24),
137
+ source: resolve(source),
138
+ destination: resolve(destination),
139
+ kind,
140
+ size: stats.size.toString(),
141
+ mtimeNs: stats.mtimeNs.toString(),
142
+ ctimeNs: stats.ctimeNs.toString(),
143
+ dev: stats.dev.toString(),
144
+ ino: stats.ino.toString(),
145
+ };
146
+ } catch {
147
+ return null;
148
+ }
149
+ }
150
+
151
+ function sameStamp(a: LegacySourceStamp, b: LegacySourceStamp): boolean {
152
+ return a.source === b.source && a.destination === b.destination && a.kind === b.kind && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs && a.dev === b.dev && a.ino === b.ino;
153
+ }
154
+
155
+ async function regularFileExists(path: string): Promise<boolean> {
156
+ try {
157
+ return (await lstat(path)).isFile();
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+
163
+ function oldPersonaSegment(name: string, _platform: NodeJS.Platform | string = process.platform): string {
164
+ const segment = name
165
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
166
+ .replace(/^[-.]+|[-.]+$/g, "")
167
+ .slice(0, 64);
168
+ if (!segment) return `persona-${createHash("sha256").update(name).digest("hex").slice(0, 12)}`;
169
+ const reserved = segment.toLowerCase() === "_shared" || segment.toLowerCase() === "_default" || WIN_RESERVED_DEVICE.test(segment);
170
+ return reserved ? `persona-${segment}` : segment;
171
+ }
172
+
173
+ function oldProjectSlug(projectRoot: string, platform: NodeJS.Platform | string = process.platform): string {
174
+ const canonical = platform === "win32" ? win32.resolve(projectRoot) : resolve(projectRoot);
175
+ const hash = createHash("sha256").update(canonical).digest("hex").slice(0, 24);
176
+ const baseName = platform === "win32" ? win32.basename(canonical) : basename(canonical);
177
+ const base =
178
+ (baseName || "project")
179
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
180
+ .replace(/^-+|-+$/g, "")
181
+ .slice(0, 48) || "project";
182
+ return `${base}-${hash}`;
183
+ }
184
+
185
+ function isRecord(value: unknown): value is Record<string, unknown> {
186
+ return typeof value === "object" && value !== null;
187
+ }
188
+
189
+ async function readBounded(path: string, maxBytes: number, report: MigrationReport, label: string): Promise<string | null> {
190
+ try {
191
+ return await readTextFileBounded(path, maxBytes);
192
+ } catch (err) {
193
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") warning(report, `${label}: could not read ${path}: ${String(err)}`);
194
+ return null;
195
+ }
196
+ }
197
+
198
+ export type StoreDiagnosticStatus = "missing" | "ok" | "invalid" | "corrupt";
199
+
200
+ export interface StoreDiagnostic {
201
+ path: string;
202
+ status: StoreDiagnosticStatus;
203
+ validEntries: number;
204
+ invalidEntries: number;
205
+ message?: string;
206
+ }
207
+
208
+ /** Read-only store validation for `/mind doctor`; unlike JsonStore.load this never quarantines. */
209
+ export async function inspectStoreFile(
210
+ path: string,
211
+ kind: ImportKind,
212
+ maxFileBytes = DEFAULT_MAX_FILE_BYTES,
213
+ maxEntries = DEFAULT_STORE_MAX_ENTRIES,
214
+ ): Promise<StoreDiagnostic> {
215
+ let raw: string;
216
+ try {
217
+ raw = await readTextFileBounded(path, maxFileBytes);
218
+ } catch (err) {
219
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return { path, status: "missing", validEntries: 0, invalidEntries: 0 };
220
+ return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: String(err) };
221
+ }
222
+ let parsed: unknown;
223
+ try {
224
+ parsed = JSON.parse(raw);
225
+ } catch {
226
+ return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: "invalid JSON" };
227
+ }
228
+ // Name a version skew explicitly: an operator reading `/mind doctor` must be able to tell "another
229
+ // build wrote this" (nothing to repair here) from "these bytes are damaged". The predicate must
230
+ // match JsonStore.parseStore EXACTLY — it refuses only a positive safe-integer version on an
231
+ // otherwise well-formed envelope, and QUARANTINES everything else. Promising "left untouched" for
232
+ // a shape load() moves aside to `*.corrupt-N` would send the operator away from a live data loss.
233
+ if (isRecord(parsed) && Array.isArray(parsed.entries) && typeof parsed.version === "number" && Number.isSafeInteger(parsed.version) && parsed.version > 0 && parsed.version !== STORE_VERSION) {
234
+ return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: `store version ${parsed.version} was written by a different pi-persona-mind build (this one reads version ${STORE_VERSION}); it is left untouched` };
235
+ }
236
+ if (!isRecord(parsed) || parsed.version !== STORE_VERSION || typeof parsed.updatedAt !== "string" || !Number.isFinite(Date.parse(parsed.updatedAt)) || typeof parsed.sequence !== "number" || !Number.isSafeInteger(parsed.sequence) || parsed.sequence < 0 || !Array.isArray(parsed.entries)) {
237
+ return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: "invalid store envelope" };
238
+ }
239
+ if (parsed.entries.length > maxEntries) {
240
+ return { path, status: "corrupt", validEntries: 0, invalidEntries: 0, message: `exceeds ${maxEntries}-entry limit` };
241
+ }
242
+ const validate = kind === "ltm" ? validateLongMemory : kind === "stm" ? validateShortMemory : validateBacklog;
243
+ let validEntries = 0;
244
+ let invalidEntries = 0;
245
+ for (const entry of parsed.entries) {
246
+ if (validate(entry) === null) invalidEntries++;
247
+ else validEntries++;
248
+ }
249
+ return { path, status: invalidEntries > 0 ? "invalid" : "ok", validEntries, invalidEntries, ...(invalidEntries > 0 ? { message: `${invalidEntries} invalid entr${invalidEntries === 1 ? "y" : "ies"}` } : {}) };
250
+ }
251
+
252
+ function warning(report: MigrationReport, message: string): void {
253
+ report.warnings.push(message);
254
+ }
255
+
256
+ function canonicalizeEntry<E>(entry: E): E {
257
+ if (!isRecord(entry) || typeof entry.text !== "string" || !Array.isArray(entry.tags)) return entry;
258
+ const tags = entry.tags.filter((tag): tag is string => typeof tag === "string");
259
+ const kind = typeof entry.kind === "string" ? entry.kind : "backlog";
260
+ const id = contentId(kind, entry.text, tags);
261
+ return typeof entry.id === "string" && entry.id !== id ? ({ ...entry, id } as E) : entry;
262
+ }
263
+
264
+ function entryIdentity(entry: unknown): string {
265
+ if (!isRecord(entry)) return JSON.stringify(entry);
266
+ const tags = Array.isArray(entry.tags) ? entry.tags.filter((tag): tag is string => typeof tag === "string").map((tag) => tag.trim().toLowerCase()).filter(Boolean).sort() : [];
267
+ // Content identity is semantic, not the serialized id: v1 comma-joined tags and the
268
+ // collision-safe v2 encoding can address the same fact with different hashes. Conversely,
269
+ // distinct facts that once collided still differ by their normalized tag arrays/text here.
270
+ if (typeof entry.kind === "string" && typeof entry.text === "string") return JSON.stringify([entry.kind, entry.text.trim().replace(/\s+/g, " ").toLowerCase(), tags]);
271
+ if (typeof entry.state === "string" && typeof entry.text === "string") return JSON.stringify(["backlog", entry.text.trim().replace(/\s+/g, " ").toLowerCase(), tags]);
272
+ return JSON.stringify(entry);
273
+ }
274
+
275
+ interface ParsedLegacy<E> {
276
+ entries: E[];
277
+ invalidEntries: number;
278
+ }
279
+
280
+ /** Why one source could not be read as a store. The caller reports it — it may first retry a `.bak`. */
281
+ interface LegacyParseFailure {
282
+ failure: string;
283
+ }
284
+
285
+ function isParseFailure<E>(result: ParsedLegacy<E> | LegacyParseFailure): result is LegacyParseFailure {
286
+ return "failure" in result;
287
+ }
288
+
289
+ function parseLegacy<E>(raw: string, validate: (value: unknown) => E | null, path: string, report: MigrationReport): ParsedLegacy<E> | LegacyParseFailure {
290
+ let parsed: unknown;
291
+ try {
292
+ parsed = JSON.parse(raw);
293
+ } catch {
294
+ return { failure: `legacy mind: could not parse ${path}` };
295
+ }
296
+ if (!isRecord(parsed) || !Array.isArray(parsed.entries)) {
297
+ return { failure: `legacy mind: ${path} has no entries array` };
298
+ }
299
+
300
+ const entries: E[] = [];
301
+ let invalidEntries = 0;
302
+ const identities = new Set<string>();
303
+ for (const rawEntry of parsed.entries) {
304
+ const entry = validate(canonicalizeEntry(rawEntry));
305
+ if (entry === null) {
306
+ invalidEntries++;
307
+ continue;
308
+ }
309
+ const identity = entryIdentity(entry);
310
+ if (identities.has(identity)) continue;
311
+ identities.add(identity);
312
+ entries.push(entry);
313
+ }
314
+ if (invalidEntries > 0) warning(report, `legacy mind: ${path} contained ${invalidEntries} invalid entr${invalidEntries === 1 ? "y" : "ies"}`);
315
+ return { entries, invalidEntries };
316
+ }
317
+
318
+ /**
319
+ * Read one legacy store, falling back to the `<file>.bak` sidecar JsonStore maintains beside every
320
+ * store (store.ts) when the live bytes are torn. This import is the only pass that will ever carry
321
+ * those entries across — the release note invites the user to delete the legacy root afterwards — so
322
+ * a recoverable last-known-good copy must not be abandoned. null ⇒ nothing was read: the caller must
323
+ * NOT stamp the source, or the next start's skip test would bury the damage forever.
324
+ */
325
+ async function readLegacyStore<E>(
326
+ legacyPath: string,
327
+ validate: (value: unknown) => E | null,
328
+ report: MigrationReport,
329
+ maxFileBytes: number,
330
+ ): Promise<ParsedLegacy<E> | null> {
331
+ const raw = await readBounded(legacyPath, maxFileBytes, report, "legacy mind");
332
+ if (raw === null) return null;
333
+ const parsed = parseLegacy<E>(raw, validate, legacyPath, report);
334
+ if (!isParseFailure(parsed)) return parsed;
335
+ // Only a source we could READ but not PARSE is torn. A source that vanished mid-scan is gone, and
336
+ // importing a leftover sidecar for it would resurrect data the user deleted.
337
+ const backupPath = `${legacyPath}.bak`;
338
+ const backupRaw = await readBounded(backupPath, maxFileBytes, report, "legacy mind");
339
+ const backup = backupRaw === null ? null : parseLegacy<E>(backupRaw, validate, backupPath, report);
340
+ // A sidecar that parses to NOTHING is not a recovery: accepting it would let the caller stamp the
341
+ // torn source as imported, and the skip test would then bury it on every later start — the exact
342
+ // burial this fallback exists to prevent.
343
+ if (backup !== null && !isParseFailure(backup) && backup.entries.length > 0) {
344
+ warning(report, `${parsed.failure}; recovered its last-known-good ${backupPath}`);
345
+ return backup;
346
+ }
347
+ warning(report, `${parsed.failure}; no usable ${backupPath} either — nothing was imported from it`);
348
+ return null;
349
+ }
350
+
351
+ async function importFile(
352
+ legacyPath: string,
353
+ destinationPath: string,
354
+ kind: ImportKind,
355
+ report: MigrationReport,
356
+ now: (() => number) | undefined,
357
+ maxFileBytes: number,
358
+ memoryLock: string,
359
+ ): Promise<boolean> {
360
+ if (kind === "ltm" || kind === "stm") {
361
+ const validate = kind === "ltm" ? validateLongMemory : validateShortMemory;
362
+ const parsed = await readLegacyStore<MemoryEntry>(legacyPath, validate, report, maxFileBytes);
363
+ if (parsed === null) return false;
364
+ report.entriesSeen += parsed.entries.length;
365
+ report.invalidEntries += parsed.invalidEntries;
366
+ if (parsed.entries.length === 0) return true;
367
+ const store = new JsonStore<MemoryEntry>(destinationPath, makeStoreOptions(validate, now, report));
368
+ // Source IO remains outside the lock; only destination selection/merge shares foreground ordering.
369
+ return withFileLock(memoryLock, () => mergeImport(store, parsed.entries, report, legacyPath, "legacy mind", reconcileMemory));
370
+ } else {
371
+ const parsed = await readLegacyStore<BacklogEntry>(legacyPath, validateBacklog, report, maxFileBytes);
372
+ if (parsed === null) return false;
373
+ report.entriesSeen += parsed.entries.length;
374
+ report.invalidEntries += parsed.invalidEntries;
375
+ if (parsed.entries.length === 0) return true;
376
+ const store = new JsonStore<BacklogEntry>(destinationPath, makeStoreOptions(validateBacklog, now, report));
377
+ return mergeImport(store, parsed.entries, report, legacyPath, "legacy mind", reconcileBacklog);
378
+ }
379
+ }
380
+
381
+ function makeStoreOptions<E>(validateEntry: (raw: unknown) => E | null, now: (() => number) | undefined, report: MigrationReport): JsonStoreOptions<E> {
382
+ const options: JsonStoreOptions<E> = {
383
+ version: STORE_VERSION,
384
+ validateEntry,
385
+ onWarn: (message) => warning(report, message),
386
+ };
387
+ if (now !== undefined) options.now = now;
388
+ return options;
389
+ }
390
+
391
+ /**
392
+ * How one semantic-identity collision is settled. Returns the destination record ITSELF when the
393
+ * incoming copy carries nothing later — identity comparison is what keeps an unchanged import a
394
+ * genuine no-op that does not bump the store sequence.
395
+ */
396
+ type Reconcile<E> = (destination: E, incoming: E) => E;
397
+
398
+ /**
399
+ * Settle two copies of one fact by FRESHNESS, not by which root they came from.
400
+ *
401
+ * The destination is no longer the newer root: 0.7.0 promotes the pre-0.6 snapshot that the 0.6.x
402
+ * importer drained and deliberately left populated to DESTINATION, so keeping its record on every
403
+ * match would resurrect a superseded copy — a dead `expiresAt` re-expiring a live short-term memory.
404
+ * This is `upsertMemory`'s own live rule rather than a second reconciliation: identity (`id`) and
405
+ * first-recorded (`recordedAt`) stay the destination's, and everything the user last touched comes
406
+ * from whichever copy was seen last. Both sides are validated, so `lastSeenAt` parses on both.
407
+ */
408
+ function reconcileMemory(destination: MemoryEntry, incoming: MemoryEntry): MemoryEntry {
409
+ if (Date.parse(incoming.lastSeenAt) <= Date.parse(destination.lastSeenAt)) return destination;
410
+ return { ...incoming, id: destination.id, recordedAt: destination.recordedAt };
411
+ }
412
+
413
+ /** open → taken → done/dropped; the state machine (backlog.ts) only ever moves forward. */
414
+ const BACKLOG_PROGRESS: Readonly<Record<BacklogState, number>> = { open: 0, taken: 1, done: 2, dropped: 2 };
415
+
416
+ /**
417
+ * Settle two copies of one lead by LIFECYCLE PROGRESS, so a terminal state and its note survive a
418
+ * merge in either direction and finished work never reverts to `open`.
419
+ *
420
+ * `state` deliberately stays out of the identity: `contentId("backlog", text, tags)` ignores it, so
421
+ * adding it here would leave an open row and a done row sharing one content id — which the ambiguity
422
+ * guards then refuse to act on, and which `backlog list` shows twice. Because the state machine only
423
+ * moves forward, the further-along record is the later one; taking it whole also carries over the
424
+ * `dueAtEpochMs` that `acknowledgeDue` already cleared, so a delivered wake is not re-armed.
425
+ */
426
+ function reconcileBacklog(destination: BacklogEntry, incoming: BacklogEntry): BacklogEntry {
427
+ if (BACKLOG_PROGRESS[incoming.state] <= BACKLOG_PROGRESS[destination.state]) return destination;
428
+ // Carry only what the LIFECYCLE owns: the state, the note that explains it, and the due date, which
429
+ // finishing a lead CLEARS — keeping the superseded copy's would re-arm a wake the user already
430
+ // acknowledged. Identity and retention stay with the destination: taking the further-along copy
431
+ // wholesale would drag its `expiresAt` across against the destination's own `createdAt`, and a
432
+ // superseded lifetime can predate it, leaving a row that expires before it exists.
433
+ const merged: BacklogEntry = { ...destination, state: incoming.state };
434
+ if (incoming.note === undefined) delete merged.note;
435
+ else merged.note = incoming.note;
436
+ if (incoming.dueAtEpochMs === undefined) delete merged.dueAtEpochMs;
437
+ else merged.dueAtEpochMs = incoming.dueAtEpochMs;
438
+ return merged;
439
+ }
440
+
441
+ /** First occurrence wins, so the pre-read check and the locked mutator agree on the destination copy. */
442
+ function byIdentity<E>(entries: readonly E[]): Map<string, { at: number; entry: E }> {
443
+ const index = new Map<string, { at: number; entry: E }>();
444
+ for (const [at, entry] of entries.entries()) {
445
+ const identity = entryIdentity(entry);
446
+ if (!index.has(identity)) index.set(identity, { at, entry });
447
+ }
448
+ return index;
449
+ }
450
+
451
+ async function merge<E extends { id: string }>(store: JsonStore<E>, incoming: readonly E[], report: MigrationReport, reconcile: Reconcile<E>): Promise<void> {
452
+ // A read avoids an unnecessary sequence bump on a repeat import. The update
453
+ // callback still re-checks identities while holding JsonStore's per-file lock.
454
+ const current = byIdentity((await store.load()).entries);
455
+ // Count conflicts the way the merge actually dedups — by semantic identity. Counting serialized
456
+ // ids instead let the v2 twin of a record written under the v1 comma-joined id be dropped by the
457
+ // dedup below without the report ever saying so.
458
+ let pending = false;
459
+ for (const entry of incoming) {
460
+ const held = current.get(entryIdentity(entry));
461
+ if (held === undefined) {
462
+ pending = true;
463
+ continue;
464
+ }
465
+ report.conflicts++;
466
+ if (reconcile(held.entry, entry) !== held.entry) pending = true;
467
+ }
468
+ if (!pending) return;
469
+
470
+ let addedHere = 0;
471
+ await store.update((entries) => {
472
+ // JsonStore may replay the mutator after lock-ownership recovery; diagnostics must describe
473
+ // the committed attempt, not accumulate counts from abandoned attempts.
474
+ addedHere = 0;
475
+ const next = [...entries];
476
+ const held = byIdentity(next);
477
+ for (const entry of incoming) {
478
+ const identity = entryIdentity(entry);
479
+ const existing = held.get(identity);
480
+ if (existing === undefined) {
481
+ held.set(identity, { at: next.length, entry });
482
+ next.push(entry);
483
+ addedHere++;
484
+ continue;
485
+ }
486
+ const reconciled = reconcile(existing.entry, entry);
487
+ if (reconciled === existing.entry) continue;
488
+ next[existing.at] = reconciled;
489
+ held.set(identity, { at: existing.at, entry: reconciled });
490
+ addedHere++;
491
+ }
492
+ return next;
493
+ });
494
+ if (addedHere > 0) {
495
+ report.entriesAdded += addedHere;
496
+ report.filesMigrated++;
497
+ }
498
+ }
499
+
500
+ /** A full destination is a source-local migration failure, not a reason to stop scanning. */
501
+ async function mergeImport<E extends { id: string }>(
502
+ store: JsonStore<E>,
503
+ incoming: readonly E[],
504
+ report: MigrationReport,
505
+ sourcePath: string,
506
+ label: string,
507
+ reconcile: Reconcile<E>,
508
+ ): Promise<boolean> {
509
+ try {
510
+ await merge(store, incoming, report, reconcile);
511
+ return true;
512
+ } catch (err) {
513
+ if (!(err instanceof StoreCapacityError)) throw err;
514
+ warning(report, `${label}: skipped ${sourcePath} — ${err.message}`);
515
+ return false;
516
+ }
517
+ }
518
+
519
+ async function importAliasFile(
520
+ sourcePath: string,
521
+ destinationPath: string,
522
+ kind: ImportKind,
523
+ report: MigrationReport,
524
+ now: (() => number) | undefined,
525
+ maxFileBytes: number,
526
+ memoryLock: string,
527
+ ): Promise<void> {
528
+ if (!(await regularFileExists(sourcePath))) return;
529
+ report.filesScanned++;
530
+
531
+ if (kind === "ltm" || kind === "stm") {
532
+ const validate = kind === "ltm" ? validateLongMemory : validateShortMemory;
533
+ // Same `.bak` recovery as the legacy-root pass: nothing else ever opens the OLD alias filename
534
+ // (`mindPaths` only returns the new names), so this is the one pass that can rescue a torn one.
535
+ const parsed = await readLegacyStore<MemoryEntry>(sourcePath, validate, report, maxFileBytes);
536
+ if (parsed === null) return;
537
+ report.entriesSeen += parsed.entries.length;
538
+ report.invalidEntries += parsed.invalidEntries;
539
+ if (parsed.entries.length === 0) return;
540
+ await withFileLock(memoryLock, () => mergeImport(new JsonStore<MemoryEntry>(destinationPath, makeStoreOptions(validate, now, report)), parsed.entries, report, sourcePath, "scope alias", reconcileMemory));
541
+ return;
542
+ }
543
+
544
+ const parsed = await readLegacyStore<BacklogEntry>(sourcePath, validateBacklog, report, maxFileBytes);
545
+ if (parsed === null) return;
546
+ report.entriesSeen += parsed.entries.length;
547
+ report.invalidEntries += parsed.invalidEntries;
548
+ if (parsed.entries.length === 0) return;
549
+ await mergeImport(new JsonStore<BacklogEntry>(destinationPath, makeStoreOptions(validateBacklog, now, report)), parsed.entries, report, sourcePath, "scope alias", reconcileBacklog);
550
+ }
551
+
552
+ /**
553
+ * A backlog record carries the persona segment that was current when it was written, and the segment
554
+ * rule changed in 0.5.2 — so a record written by an older version no longer matches the live scope
555
+ * and the persona view silently returns nothing (while the injected block still shows the items).
556
+ * Rewrite only THIS persona's own historical segment; another persona's records are left alone, and
557
+ * the no-persona scope is never touched (its records were always written as the `_default` segment).
558
+ */
559
+ async function reconcileBacklogPersona(
560
+ path: string,
561
+ from: string,
562
+ to: string,
563
+ report: MigrationReport,
564
+ now: (() => number) | undefined,
565
+ ): Promise<void> {
566
+ const store = new JsonStore<BacklogEntry>(path, makeStoreOptions(validateBacklog, now, report));
567
+ let reconciled = 0;
568
+ try {
569
+ // Read first so an already-current store is a genuine no-op and does not bump its sequence.
570
+ if (!(await store.load()).entries.some((entry) => entry.persona === from)) return;
571
+ await store.update((entries) => {
572
+ // JsonStore may replay the mutator after lock recovery; count the committed attempt only.
573
+ reconciled = 0;
574
+ return entries.map((entry) => {
575
+ if (entry.persona !== from) return entry;
576
+ reconciled++;
577
+ return { ...entry, persona: to };
578
+ });
579
+ });
580
+ } catch (err) {
581
+ warning(report, `scope alias: could not reconcile the stored persona of ${path}: ${String(err)}`);
582
+ return;
583
+ }
584
+ if (reconciled > 0) {
585
+ report.entriesAdded += reconciled;
586
+ report.filesMigrated++;
587
+ }
588
+ }
589
+
590
+ /**
591
+ * Reconciles at most three old filenames for one already-visited scope, then the persona segment
592
+ * stored inside the current backlog. It does not scan either root: callers choose when a scope is
593
+ * active, keeping startup bounded. Sources are read-only; destination updates use JsonStore locking.
594
+ */
595
+ export async function migrateCurrentScopeAliases(
596
+ agentDir: string,
597
+ rawPersona: string | null,
598
+ projectRoot: string,
599
+ options: ScopeAliasMigrationOptions = {},
600
+ ): Promise<MigrationReport> {
601
+ const report = emptyReport();
602
+ const platform = options.personaPlatform ?? options.project?.platform;
603
+ const persona = rawPersona === null ? DEFAULT_PERSONA : sanitizePersona(rawPersona, platform);
604
+ const project = projectSlug(projectRoot, options.project);
605
+ const oldPersona = oldPersonaSegment(rawPersona ?? DEFAULT_PERSONA, platform);
606
+ const oldProject = oldProjectSlug(projectRoot, options.project?.platform);
607
+ const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
608
+ const legacyRoot = options.legacyRoot ?? join(agentDir, "pi-persona-mind");
609
+ const currentRoot = options.currentRoot ?? join(agentDir, "persona-mind");
610
+ const memoryLock = memoryMutationLockPath({ shared: join(currentRoot, "memory", "ltm", `${SHARED_SCOPE}.json`) });
611
+ const currentBase = currentRoot;
612
+ const roots = [currentRoot, legacyRoot];
613
+ const aliases: readonly { kind: ImportKind; oldRelative: string; newRelative: string }[] = [
614
+ ...(options.includeAmbiguousPersonaAlias ? [{ kind: "ltm" as const, oldRelative: join("memory", "ltm", `${oldPersona}.json`), newRelative: join("memory", "ltm", `${persona}.json`) }] : []),
615
+ { kind: "stm", oldRelative: join("memory", "stm", `${oldProject}.json`), newRelative: join("memory", "stm", `${project}.json`) },
616
+ { kind: "backlog", oldRelative: join("backlog", `${oldProject}.json`), newRelative: join("backlog", `${project}.json`) },
617
+ ];
618
+ const visited = new Set<string>();
619
+ for (const alias of aliases) {
620
+ // A stable ordinary name has no alias to reconcile. This also guarantees
621
+ // the common path is a genuine no-op and does not bump store sequence.
622
+ if (alias.oldRelative === alias.newRelative) continue;
623
+ const destination = join(currentBase, alias.newRelative);
624
+ for (const root of roots) {
625
+ const sourcePath = join(root, alias.oldRelative);
626
+ if (sourcePath === destination || visited.has(sourcePath)) continue;
627
+ visited.add(sourcePath);
628
+ await importAliasFile(sourcePath, destination, alias.kind, report, options.now, maxFileBytes, memoryLock);
629
+ }
630
+ }
631
+ // After the filenames are reconciled, repair the persona segment embedded in the backlog records
632
+ // themselves — nothing else rewrites it, so the view would stay empty for the rest of time.
633
+ if (rawPersona !== null && oldPersona !== persona) {
634
+ await reconcileBacklogPersona(join(currentBase, "backlog", `${project}.json`), oldPersona, persona, report, options.now);
635
+ }
636
+ return report;
637
+ }
638
+
639
+ /**
640
+ * Import supported files from `<agentDir>/pi-persona-mind` into the current
641
+ * `<agentDir>/persona-mind` root. It is safe to call repeatedly and from
642
+ * concurrent processes. The legacy root is never written.
643
+ */
644
+ export async function migrateLegacyRoot(agentDir: string, options: LegacyMigrationOptions = {}): Promise<MigrationReport> {
645
+ const report = emptyReport();
646
+ const legacyRoot = options.legacyRoot ?? join(agentDir, "pi-persona-mind");
647
+ const destinationRoot = options.destinationRoot ?? join(agentDir, "persona-mind");
648
+ const memoryLock = memoryMutationLockPath({ shared: join(destinationRoot, "memory", "ltm", `${SHARED_SCOPE}.json`) });
649
+ const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
650
+ const maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES;
651
+ const manifest = new JsonStore<LegacySourceStamp>(
652
+ join(destinationRoot, LEGACY_MANIFEST_FILE),
653
+ makeStoreOptions(validateLegacySourceStamp, options.now, report),
654
+ );
655
+ const known = new Map((await manifest.load()).entries.map((entry) => [entry.id, entry]));
656
+ const processed: LegacySourceStamp[] = [];
657
+ let recognized = 0;
658
+
659
+ directories:
660
+ for (const directory of IMPORT_DIRECTORIES) {
661
+ const sourceDirectory = join(legacyRoot, directory.relative);
662
+ let handle: Awaited<ReturnType<typeof opendir>> | undefined;
663
+ try {
664
+ handle = await opendir(sourceDirectory);
665
+ for await (const file of handle) {
666
+ if (!file.isFile() || !file.name.toLowerCase().endsWith(".json")) continue;
667
+ if (recognized >= maxFiles) {
668
+ warning(report, `legacy mind: stopped after the ${maxFiles}-file migration limit`);
669
+ break directories;
670
+ }
671
+ recognized++;
672
+ const relativeFile = join(directory.relative, file.name);
673
+ const source = join(legacyRoot, relativeFile);
674
+ const destination = join(destinationRoot, relativeFile);
675
+ try {
676
+ const stamp = await sourceStamp(source, destination, directory.kind);
677
+ const previous = stamp ? known.get(stamp.id) : undefined;
678
+ if (stamp && previous && sameStamp(stamp, previous) && (await regularFileExists(destination))) {
679
+ report.filesSkipped++;
680
+ continue;
681
+ }
682
+ report.filesScanned++;
683
+ if (await importFile(source, destination, directory.kind, report, options.now, maxFileBytes, memoryLock)) {
684
+ const committedStamp = stamp ?? (await sourceStamp(source, destination, directory.kind));
685
+ if (committedStamp) processed.push(committedStamp);
686
+ }
687
+ } catch (err) {
688
+ // One destination's failure (a version skew, a lock timeout under two concurrent Pi
689
+ // starts, an EPERM on the Windows rename) belongs to THIS source. Letting it reach the
690
+ // directory catch aborts the iteration, and readdir order is stable — every later file
691
+ // would be stranded, unnamed, on every subsequent start.
692
+ warning(report, `legacy mind: could not import ${source}: ${String(err)}`);
693
+ }
694
+ }
695
+ } catch (err) {
696
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") warning(report, `legacy mind: could not scan ${sourceDirectory}: ${String(err)}`);
697
+ } finally {
698
+ await handle?.close().catch(() => {});
699
+ }
700
+ }
701
+ if (processed.length > 0) {
702
+ try {
703
+ await manifest.update((entries) => {
704
+ const next = new Map(entries.map((entry) => [entry.id, entry]));
705
+ for (const entry of processed) next.set(entry.id, entry);
706
+ return [...next.values()].sort((a, b) => a.source.localeCompare(b.source));
707
+ });
708
+ } catch (err) {
709
+ warning(report, `legacy mind: imported data but could not update the source manifest: ${String(err)}`);
710
+ }
711
+ }
712
+ return report;
713
+ }