@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,222 +1,222 @@
1
- import { createHash } from "node:crypto";
2
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, type BigIntStats } from "node:fs";
3
- import { realpath } from "node:fs/promises";
4
- import { extname, isAbsolute, relative, resolve, sep } from "node:path";
5
- import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
6
- import { scanContent } from "../core/scanner.ts";
7
- import type { ReviewEvidence } from "../core/knowledge-review.ts";
8
-
9
- export interface ReviewEvidenceSnapshot { evidence: ReviewEvidence[]; coverage: string[]; assertFresh(): void; }
10
- const MAX_FILES = 6;
11
- const MAX_FILE_BYTES = 32 * 1024;
12
- const MAX_TOTAL_BYTES = 64 * 1024;
13
- const MAX_EXCERPT_CHARS = 8_000;
14
- const MAX_BRANCH_ENTRIES = 2_000;
15
- const MAX_USER_MESSAGES = 12;
16
- const MAX_USER_EACH = 2_000;
17
- const MAX_USER_TOTAL = 6_000;
18
- const MAX_EVIDENCE_SERIALIZED = 24_000;
19
- const MAX_REPOSITORY_SERIALIZED = 18_000;
20
- const ALLOWED = new Set([".md", ".mdx", ".txt", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".html", ".css", ".scss", ".sql", ".sh", ".ps1", ".py", ".go", ".rs", ".java", ".kt", ".c", ".h", ".cpp", ".hpp", ".xml", ".properties", ".gitignore", ".editorconfig"]);
21
- const digest = (bytes: Uint8Array | string): string => createHash("sha256").update(bytes).digest("hex");
22
- const samePath = (a: string, b: string): boolean => relative(a, b) === "";
23
- const sameIdentity = (a: BigIntStats, b: BigIntStats): boolean => a.dev === b.dev && a.ino === b.ino && a.mode === b.mode;
24
- const sameFile = (a: BigIntStats, b: BigIntStats): boolean => sameIdentity(a, b) && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
25
- const hiddenPath = (path: string): boolean => path.split("/").some((part) => [".git", "node_modules", "credentials", "private"].includes(part.toLowerCase()) || /^\.env/i.test(part) || /(?:private[-_.]?key|credentials?)/i.test(part));
26
- function checkedPath(path: string): string {
27
- if (typeof path !== "string" || !path.trim() || path.length > 400 || isAbsolute(path) || /^[\\/]/.test(path) || /[:\u0000-\u001f\u007f-\u009f]/.test(path) || path.split(/[\\/]/).includes("..")) throw new Error("Repository evidence path must be relative and traversal-free, without colons or controls");
28
- const parts = path.split(/[\\/]/).filter((part) => part !== "" && part !== ".");
29
- // Reject Win32 aliases (trailing dots/spaces and device names) on every platform.
30
- if (!parts.length || parts.some((part) => /[. ]$/.test(part) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw new Error("Repository evidence path has an unsupported segment");
31
- const normalized = parts.join("/");
32
- if (!scanContent(normalized).ok || hiddenPath(normalized) || !ALLOWED.has(extname(normalized).toLowerCase()) && ![".gitignore", ".editorconfig"].includes(parts.at(-1)!.toLowerCase())) throw new Error("Repository evidence path is excluded or unsupported");
33
- return normalized;
34
- }
35
- function textContent(message: unknown): string | null {
36
- if (!message || typeof message !== "object") return null;
37
- const item = message as { role?: unknown; content?: unknown };
38
- if (item.role !== "user") return null;
39
- if (typeof item.content === "string") return item.content;
40
- if (!Array.isArray(item.content)) return null;
41
- const texts: string[] = [];
42
- for (const block of item.content) {
43
- if (!block || typeof block !== "object" || (block as { type?: unknown }).type !== "text" || typeof (block as { text?: unknown }).text !== "string") return null;
44
- texts.push((block as { text: string }).text);
45
- }
46
- return texts.join("\n");
47
- }
48
- function branchDigest(branch: readonly SessionEntry[]): string {
49
- // Bind the bounded active-branch membership/order and full native user text, not tool/assistant payloads.
50
- return digest(JSON.stringify([branch.length, branch.slice(-MAX_BRANCH_ENTRIES).map((entry) => [entry.id, entry.parentId, entry.type, entry.type === "message" ? digest(textContent(entry.message) ?? "") : null])]));
51
- }
52
-
53
- // Keep all descriptor IO in this bounded synchronous reader, also used at the synchronous apply boundary.
54
- // O_NOFOLLOW protects the final component on POSIX; Node does not provide that guarantee on Windows.
55
- // Pre/post component identities, canonical paths and descriptor stats detect observed swaps, not a
56
- // transaction against external writers (including an ancestor swapped out and back between checks).
57
- function readRepositoryFile(root: string, path: string, remaining: number, check: () => void): { bytes: Uint8Array } | { omitted: string } {
58
- const fullPath = resolve(root, path);
59
- const rel = relative(root, fullPath);
60
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error("Repository evidence path escapes project root");
61
- const inspect = (): BigIntStats[] => {
62
- const stats: BigIntStats[] = [];
63
- let cursor = root;
64
- const parts = path.split("/");
65
- for (let i = 0; i <= parts.length; i++) {
66
- if (i > 0) cursor = resolve(cursor, parts[i - 1]!);
67
- check();
68
- const stat = lstatSync(cursor, { bigint: true });
69
- if (stat.isSymbolicLink()) throw new Error("Repository evidence symlink components are not allowed");
70
- if (i < parts.length ? !stat.isDirectory() : !stat.isFile()) throw new Error("Repository evidence path is not a regular file or directory");
71
- stats.push(stat);
72
- }
73
- check();
74
- if (!samePath(realpathSync.native(fullPath), fullPath)) throw new Error("Repository evidence canonical path changed");
75
- return stats;
76
- };
77
- const before = inspect();
78
- const initial = before.at(-1)!;
79
- if (initial.size > BigInt(MAX_FILE_BYTES)) return { omitted: "file exceeds 32 KiB limit" };
80
- if (initial.size > BigInt(remaining)) return { omitted: "64 KiB total raw-byte limit reached" };
81
- const verifyPath = (): void => {
82
- const after = inspect();
83
- if (!after.every((stat, i) => sameIdentity(stat, before[i]!)) || !sameFile(initial, after.at(-1)!)) throw new Error("Repository evidence path or file changed during read");
84
- };
85
- const posixFlags = process.platform === "win32" ? 0 : (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
86
- check();
87
- const fd = openSync(fullPath, constants.O_RDONLY | posixFlags);
88
- try {
89
- check();
90
- const opened = fstatSync(fd, { bigint: true });
91
- if (!opened.isFile() || !sameFile(initial, opened)) throw new Error("Repository evidence descriptor changed before read");
92
- verifyPath();
93
- const buffer = new Uint8Array(Number(initial.size) + 1);
94
- let count = 0;
95
- while (count < buffer.length) {
96
- check();
97
- const read = readSync(fd, buffer, count, buffer.length - count, count);
98
- if (read === 0) break;
99
- count += read;
100
- }
101
- check();
102
- if (count !== Number(initial.size) || !sameFile(opened, fstatSync(fd, { bigint: true }))) throw new Error("Repository evidence file changed during read");
103
- verifyPath();
104
- check();
105
- return { bytes: buffer.slice(0, count) };
106
- } finally { closeSync(fd); }
107
- }
108
-
109
- export async function collectReviewEvidence(ctx: ExtensionContext, paths: readonly string[], isCurrent: () => boolean): Promise<ReviewEvidenceSnapshot> {
110
- if (!Array.isArray(paths) || paths.length > MAX_FILES) throw new Error("Select at most six explicit repository files");
111
- const repositoryRequested = paths.length > 0;
112
- const check = (): void => {
113
- if (!isCurrent()) throw new Error("Review evidence owner or lifecycle changed; evidence revoked");
114
- if (repositoryRequested && !ctx.isProjectTrusted()) throw new Error("Repository evidence requires project trust; evidence revoked");
115
- if (!isCurrent()) throw new Error("Review evidence owner or lifecycle changed; evidence revoked");
116
- };
117
- check();
118
- const selected = paths.map(checkedPath);
119
- const seen = new Set(selected.map((path) => process.platform === "win32" ? path.toLowerCase() : path));
120
- if (seen.size !== selected.length) throw new Error("Duplicate repository evidence path");
121
- check();
122
- // fs/promises realpath uses native canonicalization; use its synchronous native
123
- // counterpart below too (legacy realpathSync can retain Windows short-name aliases).
124
- const root = await realpath(ctx.cwd);
125
- check(); // No subsequent IO if ownership/trust was revoked across the async boundary.
126
- const rootStat = lstatSync(root, { bigint: true });
127
- if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error("Review project root changed; evidence revoked");
128
- const checkRoot = (): void => {
129
- check();
130
- if (!samePath(realpathSync.native(ctx.cwd), root)) throw new Error("Review project root changed; evidence revoked");
131
- check();
132
- if (!sameIdentity(rootStat, lstatSync(root, { bigint: true }))) throw new Error("Review project root changed; evidence revoked");
133
- };
134
- const coverage: string[] = [];
135
- const evidence: ReviewEvidence[] = [];
136
- const repoRefs: { path: string; digest: string }[] = [];
137
- let totalBytes = 0;
138
- for (const path of selected) {
139
- checkRoot();
140
- const result = readRepositoryFile(root, path, MAX_TOTAL_BYTES - totalBytes, check);
141
- if ("omitted" in result) { coverage.push(`${path}: omitted (${result.omitted})`); continue; }
142
- const { bytes } = result;
143
- totalBytes += bytes.length;
144
- if (bytes.includes(0) || [...bytes.slice(0, Math.min(bytes.length, 4096))].filter((byte) => byte < 9 || byte > 13 && byte < 32).length > 2) {
145
- coverage.push(`${path}: withheld (unsupported binary or unreadable content)`); continue;
146
- }
147
- let raw: string;
148
- try { raw = new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
149
- catch { coverage.push(`${path}: withheld (invalid UTF-8 text)`); continue; }
150
- const fullDigest = digest(bytes);
151
- if (!scanContent(raw).ok) { coverage.push(`${path}: withheld (unsafe content detected)`); continue; }
152
- // A final newline terminates a line; it does not create a fictitious extra source line.
153
- const lines = raw === "" ? [] : raw.replace(/\r?\n$/, "").split(/\r?\n/);
154
- const id = `repo-${repoRefs.length + 1}`;
155
- let fitted: ReviewEvidence | undefined;
156
- for (let i = 0; i < lines.length; i++) {
157
- const text = `${fitted ? fitted.text + "\n" : ""}${i + 1}: ${lines[i]}`;
158
- const item: ReviewEvidence = { id, kind: "repository", label: `${path}:1-${i + 1}`, text, digest: fullDigest };
159
- if (text.length > MAX_EXCERPT_CHARS || JSON.stringify([...evidence, item]).length > MAX_REPOSITORY_SERIALIZED) break;
160
- fitted = item;
161
- }
162
- if (!fitted) { coverage.push(`${path}: omitted (admitted 0/${lines.length} lines; no whole source line fits the excerpt/evidence budget)`); continue; }
163
- if (!scanContent(fitted.text).ok) { coverage.push(`${path}: withheld (unsafe excerpt detected)`); continue; }
164
- const lineCount = fitted.text.split("\n").length;
165
- evidence.push(fitted);
166
- repoRefs.push({ path, digest: fullDigest });
167
- coverage.push(`${path}: admitted ${lineCount}/${lines.length} lines (1-${lineCount}); full-file SHA-256 recorded${lineCount < lines.length ? "; clipped (whole-line excerpt/evidence budget)" : "; complete file"}.`);
168
- }
169
-
170
- check();
171
- const branch = ctx.sessionManager.getBranch();
172
- check();
173
- const nativeDigest = branchDigest(branch);
174
- const branchLength = branch.length;
175
- const branchAnchor = branch.at(-1)?.id;
176
- const recent = branch.slice(-MAX_BRANCH_ENTRIES);
177
- if (branch.length > recent.length) coverage.push(`Native branch limited to newest ${MAX_BRANCH_ENTRIES} entries; earlier history not checked.`);
178
- let userTotal = 0;
179
- let userCount = 0;
180
- const omitted = { long: 0, aggregate: 0, count: 0, serialized: 0, unsafe: 0 };
181
- for (let i = recent.length - 1; i >= 0; i--) {
182
- const entry = recent[i]!;
183
- if (entry.type !== "message") continue;
184
- const text = textContent(entry.message);
185
- if (text === null || !text.trim()) continue;
186
- if (text.length > MAX_USER_EACH) { omitted.long++; continue; }
187
- if (userCount >= MAX_USER_MESSAGES) { omitted.count++; continue; }
188
- if (text.length + userTotal > MAX_USER_TOTAL) { omitted.aggregate++; continue; }
189
- if (!scanContent(text).ok) { omitted.unsafe++; continue; }
190
- // Native IDs are labels only, never authority or paths; omit unsafe/oversized labels too.
191
- if (entry.id.length > 200 || !scanContent(entry.id).ok) { omitted.unsafe++; continue; }
192
- const item: ReviewEvidence = { id: `user-${userCount + 1}`, kind: "user-message", label: `active native branch user-role entry ${entry.id} (whole message; authorship unverified)`, text, digest: digest(text) };
193
- if (JSON.stringify([...evidence, item]).length > MAX_EVIDENCE_SERIALIZED) { omitted.serialized++; continue; }
194
- evidence.push(item);
195
- userTotal += text.length; userCount++;
196
- }
197
- if (omitted.long) coverage.push(`${omitted.long} whole native user message(s) omitted (exceeds 2000 characters each); no partial intent supplied.`);
198
- if (omitted.aggregate) coverage.push(`${omitted.aggregate} whole native user message(s) omitted (6000-character aggregate limit); no partial intent supplied.`);
199
- if (omitted.count) coverage.push(`${omitted.count} whole native user message(s) omitted (12-message limit).`);
200
- if (omitted.serialized) coverage.push(`${omitted.serialized} whole native user message(s) omitted (serialized review evidence budget).`);
201
- if (omitted.unsafe) coverage.push("Unsafe native user-role text or labels withheld (content safety filter); actual text omitted.");
202
- coverage.push(`Native evidence: newest qualifying whole user-role messages only; authorship unverified; scope is active branch; ${userCount} messages / ${userTotal} characters admitted. Assistant, tool, custom, image, and reasoning content excluded.`);
203
- const assertFresh = (): void => {
204
- checkRoot();
205
- for (const ref of repoRefs) {
206
- checkRoot();
207
- try {
208
- const result = readRepositoryFile(root, ref.path, MAX_FILE_BYTES, check);
209
- if (!("bytes" in result) || digest(result.bytes) !== ref.digest) throw new Error();
210
- } catch { throw new Error(`Review evidence changed, revoked or unreadable: ${ref.path}`); }
211
- }
212
- check();
213
- const current = ctx.sessionManager.getBranch();
214
- check();
215
- // Review reports/previews legitimately append native entries. Bind the captured prefix and
216
- // anchor, not the current leaf. isCurrent separately fences host branch-navigation events.
217
- if (current.length < branchLength || current[branchLength - 1]?.id !== branchAnchor || branchDigest(current.slice(0, branchLength)) !== nativeDigest) throw new Error("Review native evidence or active branch changed or was revoked");
218
- checkRoot();
219
- };
220
- checkRoot();
221
- return { evidence, coverage, assertFresh };
222
- }
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, type BigIntStats } from "node:fs";
3
+ import { realpath } from "node:fs/promises";
4
+ import { extname, isAbsolute, relative, resolve, sep } from "node:path";
5
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
6
+ import { scanContent } from "../core/scanner.ts";
7
+ import type { ReviewEvidence } from "../core/knowledge-review.ts";
8
+
9
+ export interface ReviewEvidenceSnapshot { evidence: ReviewEvidence[]; coverage: string[]; assertFresh(): void; }
10
+ const MAX_FILES = 6;
11
+ const MAX_FILE_BYTES = 32 * 1024;
12
+ const MAX_TOTAL_BYTES = 64 * 1024;
13
+ const MAX_EXCERPT_CHARS = 8_000;
14
+ const MAX_BRANCH_ENTRIES = 2_000;
15
+ const MAX_USER_MESSAGES = 12;
16
+ const MAX_USER_EACH = 2_000;
17
+ const MAX_USER_TOTAL = 6_000;
18
+ const MAX_EVIDENCE_SERIALIZED = 24_000;
19
+ const MAX_REPOSITORY_SERIALIZED = 18_000;
20
+ const ALLOWED = new Set([".md", ".mdx", ".txt", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".json", ".jsonc", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".html", ".css", ".scss", ".sql", ".sh", ".ps1", ".py", ".go", ".rs", ".java", ".kt", ".c", ".h", ".cpp", ".hpp", ".xml", ".properties", ".gitignore", ".editorconfig"]);
21
+ const digest = (bytes: Uint8Array | string): string => createHash("sha256").update(bytes).digest("hex");
22
+ const samePath = (a: string, b: string): boolean => relative(a, b) === "";
23
+ const sameIdentity = (a: BigIntStats, b: BigIntStats): boolean => a.dev === b.dev && a.ino === b.ino && a.mode === b.mode;
24
+ const sameFile = (a: BigIntStats, b: BigIntStats): boolean => sameIdentity(a, b) && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
25
+ const hiddenPath = (path: string): boolean => path.split("/").some((part) => [".git", "node_modules", "credentials", "private"].includes(part.toLowerCase()) || /^\.env/i.test(part) || /(?:private[-_.]?key|credentials?)/i.test(part));
26
+ function checkedPath(path: string): string {
27
+ if (typeof path !== "string" || !path.trim() || path.length > 400 || isAbsolute(path) || /^[\\/]/.test(path) || /[:\u0000-\u001f\u007f-\u009f]/.test(path) || path.split(/[\\/]/).includes("..")) throw new Error("Repository evidence path must be relative and traversal-free, without colons or controls");
28
+ const parts = path.split(/[\\/]/).filter((part) => part !== "" && part !== ".");
29
+ // Reject Win32 aliases (trailing dots/spaces and device names) on every platform.
30
+ if (!parts.length || parts.some((part) => /[. ]$/.test(part) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw new Error("Repository evidence path has an unsupported segment");
31
+ const normalized = parts.join("/");
32
+ if (!scanContent(normalized).ok || hiddenPath(normalized) || !ALLOWED.has(extname(normalized).toLowerCase()) && ![".gitignore", ".editorconfig"].includes(parts.at(-1)!.toLowerCase())) throw new Error("Repository evidence path is excluded or unsupported");
33
+ return normalized;
34
+ }
35
+ function textContent(message: unknown): string | null {
36
+ if (!message || typeof message !== "object") return null;
37
+ const item = message as { role?: unknown; content?: unknown };
38
+ if (item.role !== "user") return null;
39
+ if (typeof item.content === "string") return item.content;
40
+ if (!Array.isArray(item.content)) return null;
41
+ const texts: string[] = [];
42
+ for (const block of item.content) {
43
+ if (!block || typeof block !== "object" || (block as { type?: unknown }).type !== "text" || typeof (block as { text?: unknown }).text !== "string") return null;
44
+ texts.push((block as { text: string }).text);
45
+ }
46
+ return texts.join("\n");
47
+ }
48
+ function branchDigest(branch: readonly SessionEntry[]): string {
49
+ // Bind the bounded active-branch membership/order and full native user text, not tool/assistant payloads.
50
+ return digest(JSON.stringify([branch.length, branch.slice(-MAX_BRANCH_ENTRIES).map((entry) => [entry.id, entry.parentId, entry.type, entry.type === "message" ? digest(textContent(entry.message) ?? "") : null])]));
51
+ }
52
+
53
+ // Keep all descriptor IO in this bounded synchronous reader, also used at the synchronous apply boundary.
54
+ // O_NOFOLLOW protects the final component on POSIX; Node does not provide that guarantee on Windows.
55
+ // Pre/post component identities, canonical paths and descriptor stats detect observed swaps, not a
56
+ // transaction against external writers (including an ancestor swapped out and back between checks).
57
+ function readRepositoryFile(root: string, path: string, remaining: number, check: () => void): { bytes: Uint8Array } | { omitted: string } {
58
+ const fullPath = resolve(root, path);
59
+ const rel = relative(root, fullPath);
60
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error("Repository evidence path escapes project root");
61
+ const inspect = (): BigIntStats[] => {
62
+ const stats: BigIntStats[] = [];
63
+ let cursor = root;
64
+ const parts = path.split("/");
65
+ for (let i = 0; i <= parts.length; i++) {
66
+ if (i > 0) cursor = resolve(cursor, parts[i - 1]!);
67
+ check();
68
+ const stat = lstatSync(cursor, { bigint: true });
69
+ if (stat.isSymbolicLink()) throw new Error("Repository evidence symlink components are not allowed");
70
+ if (i < parts.length ? !stat.isDirectory() : !stat.isFile()) throw new Error("Repository evidence path is not a regular file or directory");
71
+ stats.push(stat);
72
+ }
73
+ check();
74
+ if (!samePath(realpathSync.native(fullPath), fullPath)) throw new Error("Repository evidence canonical path changed");
75
+ return stats;
76
+ };
77
+ const before = inspect();
78
+ const initial = before.at(-1)!;
79
+ if (initial.size > BigInt(MAX_FILE_BYTES)) return { omitted: "file exceeds 32 KiB limit" };
80
+ if (initial.size > BigInt(remaining)) return { omitted: "64 KiB total raw-byte limit reached" };
81
+ const verifyPath = (): void => {
82
+ const after = inspect();
83
+ if (!after.every((stat, i) => sameIdentity(stat, before[i]!)) || !sameFile(initial, after.at(-1)!)) throw new Error("Repository evidence path or file changed during read");
84
+ };
85
+ const posixFlags = process.platform === "win32" ? 0 : (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
86
+ check();
87
+ const fd = openSync(fullPath, constants.O_RDONLY | posixFlags);
88
+ try {
89
+ check();
90
+ const opened = fstatSync(fd, { bigint: true });
91
+ if (!opened.isFile() || !sameFile(initial, opened)) throw new Error("Repository evidence descriptor changed before read");
92
+ verifyPath();
93
+ const buffer = new Uint8Array(Number(initial.size) + 1);
94
+ let count = 0;
95
+ while (count < buffer.length) {
96
+ check();
97
+ const read = readSync(fd, buffer, count, buffer.length - count, count);
98
+ if (read === 0) break;
99
+ count += read;
100
+ }
101
+ check();
102
+ if (count !== Number(initial.size) || !sameFile(opened, fstatSync(fd, { bigint: true }))) throw new Error("Repository evidence file changed during read");
103
+ verifyPath();
104
+ check();
105
+ return { bytes: buffer.slice(0, count) };
106
+ } finally { closeSync(fd); }
107
+ }
108
+
109
+ export async function collectReviewEvidence(ctx: ExtensionContext, paths: readonly string[], isCurrent: () => boolean): Promise<ReviewEvidenceSnapshot> {
110
+ if (!Array.isArray(paths) || paths.length > MAX_FILES) throw new Error("Select at most six explicit repository files");
111
+ const repositoryRequested = paths.length > 0;
112
+ const check = (): void => {
113
+ if (!isCurrent()) throw new Error("Review evidence owner or lifecycle changed; evidence revoked");
114
+ if (repositoryRequested && !ctx.isProjectTrusted()) throw new Error("Repository evidence requires project trust; evidence revoked");
115
+ if (!isCurrent()) throw new Error("Review evidence owner or lifecycle changed; evidence revoked");
116
+ };
117
+ check();
118
+ const selected = paths.map(checkedPath);
119
+ const seen = new Set(selected.map((path) => process.platform === "win32" ? path.toLowerCase() : path));
120
+ if (seen.size !== selected.length) throw new Error("Duplicate repository evidence path");
121
+ check();
122
+ // fs/promises realpath uses native canonicalization; use its synchronous native
123
+ // counterpart below too (legacy realpathSync can retain Windows short-name aliases).
124
+ const root = await realpath(ctx.cwd);
125
+ check(); // No subsequent IO if ownership/trust was revoked across the async boundary.
126
+ const rootStat = lstatSync(root, { bigint: true });
127
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new Error("Review project root changed; evidence revoked");
128
+ const checkRoot = (): void => {
129
+ check();
130
+ if (!samePath(realpathSync.native(ctx.cwd), root)) throw new Error("Review project root changed; evidence revoked");
131
+ check();
132
+ if (!sameIdentity(rootStat, lstatSync(root, { bigint: true }))) throw new Error("Review project root changed; evidence revoked");
133
+ };
134
+ const coverage: string[] = [];
135
+ const evidence: ReviewEvidence[] = [];
136
+ const repoRefs: { path: string; digest: string }[] = [];
137
+ let totalBytes = 0;
138
+ for (const path of selected) {
139
+ checkRoot();
140
+ const result = readRepositoryFile(root, path, MAX_TOTAL_BYTES - totalBytes, check);
141
+ if ("omitted" in result) { coverage.push(`${path}: omitted (${result.omitted})`); continue; }
142
+ const { bytes } = result;
143
+ totalBytes += bytes.length;
144
+ if (bytes.includes(0) || [...bytes.slice(0, Math.min(bytes.length, 4096))].filter((byte) => byte < 9 || byte > 13 && byte < 32).length > 2) {
145
+ coverage.push(`${path}: withheld (unsupported binary or unreadable content)`); continue;
146
+ }
147
+ let raw: string;
148
+ try { raw = new TextDecoder("utf-8", { fatal: true }).decode(bytes); }
149
+ catch { coverage.push(`${path}: withheld (invalid UTF-8 text)`); continue; }
150
+ const fullDigest = digest(bytes);
151
+ if (!scanContent(raw).ok) { coverage.push(`${path}: withheld (unsafe content detected)`); continue; }
152
+ // A final newline terminates a line; it does not create a fictitious extra source line.
153
+ const lines = raw === "" ? [] : raw.replace(/\r?\n$/, "").split(/\r?\n/);
154
+ const id = `repo-${repoRefs.length + 1}`;
155
+ let fitted: ReviewEvidence | undefined;
156
+ for (let i = 0; i < lines.length; i++) {
157
+ const text = `${fitted ? fitted.text + "\n" : ""}${i + 1}: ${lines[i]}`;
158
+ const item: ReviewEvidence = { id, kind: "repository", label: `${path}:1-${i + 1}`, text, digest: fullDigest };
159
+ if (text.length > MAX_EXCERPT_CHARS || JSON.stringify([...evidence, item]).length > MAX_REPOSITORY_SERIALIZED) break;
160
+ fitted = item;
161
+ }
162
+ if (!fitted) { coverage.push(`${path}: omitted (admitted 0/${lines.length} lines; no whole source line fits the excerpt/evidence budget)`); continue; }
163
+ if (!scanContent(fitted.text).ok) { coverage.push(`${path}: withheld (unsafe excerpt detected)`); continue; }
164
+ const lineCount = fitted.text.split("\n").length;
165
+ evidence.push(fitted);
166
+ repoRefs.push({ path, digest: fullDigest });
167
+ coverage.push(`${path}: admitted ${lineCount}/${lines.length} lines (1-${lineCount}); full-file SHA-256 recorded${lineCount < lines.length ? "; clipped (whole-line excerpt/evidence budget)" : "; complete file"}.`);
168
+ }
169
+
170
+ check();
171
+ const branch = ctx.sessionManager.getBranch();
172
+ check();
173
+ const nativeDigest = branchDigest(branch);
174
+ const branchLength = branch.length;
175
+ const branchAnchor = branch.at(-1)?.id;
176
+ const recent = branch.slice(-MAX_BRANCH_ENTRIES);
177
+ if (branch.length > recent.length) coverage.push(`Native branch limited to newest ${MAX_BRANCH_ENTRIES} entries; earlier history not checked.`);
178
+ let userTotal = 0;
179
+ let userCount = 0;
180
+ const omitted = { long: 0, aggregate: 0, count: 0, serialized: 0, unsafe: 0 };
181
+ for (let i = recent.length - 1; i >= 0; i--) {
182
+ const entry = recent[i]!;
183
+ if (entry.type !== "message") continue;
184
+ const text = textContent(entry.message);
185
+ if (text === null || !text.trim()) continue;
186
+ if (text.length > MAX_USER_EACH) { omitted.long++; continue; }
187
+ if (userCount >= MAX_USER_MESSAGES) { omitted.count++; continue; }
188
+ if (text.length + userTotal > MAX_USER_TOTAL) { omitted.aggregate++; continue; }
189
+ if (!scanContent(text).ok) { omitted.unsafe++; continue; }
190
+ // Native IDs are labels only, never authority or paths; omit unsafe/oversized labels too.
191
+ if (entry.id.length > 200 || !scanContent(entry.id).ok) { omitted.unsafe++; continue; }
192
+ const item: ReviewEvidence = { id: `user-${userCount + 1}`, kind: "user-message", label: `active native branch user-role entry ${entry.id} (whole message; authorship unverified)`, text, digest: digest(text) };
193
+ if (JSON.stringify([...evidence, item]).length > MAX_EVIDENCE_SERIALIZED) { omitted.serialized++; continue; }
194
+ evidence.push(item);
195
+ userTotal += text.length; userCount++;
196
+ }
197
+ if (omitted.long) coverage.push(`${omitted.long} whole native user message(s) omitted (exceeds 2000 characters each); no partial intent supplied.`);
198
+ if (omitted.aggregate) coverage.push(`${omitted.aggregate} whole native user message(s) omitted (6000-character aggregate limit); no partial intent supplied.`);
199
+ if (omitted.count) coverage.push(`${omitted.count} whole native user message(s) omitted (12-message limit).`);
200
+ if (omitted.serialized) coverage.push(`${omitted.serialized} whole native user message(s) omitted (serialized review evidence budget).`);
201
+ if (omitted.unsafe) coverage.push("Unsafe native user-role text or labels withheld (content safety filter); actual text omitted.");
202
+ coverage.push(`Native evidence: newest qualifying whole user-role messages only; authorship unverified; scope is active branch; ${userCount} messages / ${userTotal} characters admitted. Assistant, tool, custom, image, and reasoning content excluded.`);
203
+ const assertFresh = (): void => {
204
+ checkRoot();
205
+ for (const ref of repoRefs) {
206
+ checkRoot();
207
+ try {
208
+ const result = readRepositoryFile(root, ref.path, MAX_FILE_BYTES, check);
209
+ if (!("bytes" in result) || digest(result.bytes) !== ref.digest) throw new Error();
210
+ } catch { throw new Error(`Review evidence changed, revoked or unreadable: ${ref.path}`); }
211
+ }
212
+ check();
213
+ const current = ctx.sessionManager.getBranch();
214
+ check();
215
+ // Review reports/previews legitimately append native entries. Bind the captured prefix and
216
+ // anchor, not the current leaf. isCurrent separately fences host branch-navigation events.
217
+ if (current.length < branchLength || current[branchLength - 1]?.id !== branchAnchor || branchDigest(current.slice(0, branchLength)) !== nativeDigest) throw new Error("Review native evidence or active branch changed or was revoked");
218
+ checkRoot();
219
+ };
220
+ checkRoot();
221
+ return { evidence, coverage, assertFresh };
222
+ }
@@ -1,28 +1,28 @@
1
- import { contentText } from "@earendil-works/pi-ai";
2
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
-
4
- const WORKER_CONTRACT_ENTRY = "pi-persona-worker-contract";
5
-
6
- /** The launch task and time of a Persona v1 continuation, from the current native branch. */
7
- export function workerMemoryAnchor(manager: ExtensionContext["sessionManager"]): { query: string; timestamp: number } | undefined {
8
- try {
9
- if (!manager.getSessionFile()) return undefined;
10
- const branch = manager.getBranch();
11
- const contracts = branch.filter((entry) => entry.type === "custom" && entry.customType === WORKER_CONTRACT_ENTRY);
12
- const contract = contracts[0];
13
- if (contracts.length !== 1 || contract?.type !== "custom") return undefined;
14
- const data: unknown = contract.data;
15
- if (!data || typeof data !== "object" || !("version" in data) || data.version !== 1
16
- || !("sha256" in data) || typeof data.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(data.sha256)) return undefined;
17
-
18
- for (const entry of branch.slice(branch.indexOf(contract) + 1)) {
19
- if (entry.type === "message" && entry.message.role === "user") {
20
- const { content, timestamp } = entry.message;
21
- if (!Number.isSafeInteger(timestamp) || timestamp <= 0 || timestamp > Date.now()) return undefined;
22
- const query = contentText(content);
23
- return query.trim() ? { query, timestamp } : undefined;
24
- }
25
- }
26
- } catch { /* Ordinary per-turn ranking still applies when the branch is unreadable. */ }
27
- return undefined;
28
- }
1
+ import { contentText } from "@earendil-works/pi-ai";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+
4
+ const WORKER_CONTRACT_ENTRY = "pi-persona-worker-contract";
5
+
6
+ /** The launch task and time of a Persona v1 continuation, from the current native branch. */
7
+ export function workerMemoryAnchor(manager: ExtensionContext["sessionManager"]): { query: string; timestamp: number } | undefined {
8
+ try {
9
+ if (!manager.getSessionFile()) return undefined;
10
+ const branch = manager.getBranch();
11
+ const contracts = branch.filter((entry) => entry.type === "custom" && entry.customType === WORKER_CONTRACT_ENTRY);
12
+ const contract = contracts[0];
13
+ if (contracts.length !== 1 || contract?.type !== "custom") return undefined;
14
+ const data: unknown = contract.data;
15
+ if (!data || typeof data !== "object" || !("version" in data) || data.version !== 1
16
+ || !("sha256" in data) || typeof data.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(data.sha256)) return undefined;
17
+
18
+ for (const entry of branch.slice(branch.indexOf(contract) + 1)) {
19
+ if (entry.type === "message" && entry.message.role === "user") {
20
+ const { content, timestamp } = entry.message;
21
+ if (!Number.isSafeInteger(timestamp) || timestamp <= 0 || timestamp > Date.now()) return undefined;
22
+ const query = contentText(content);
23
+ return query.trim() ? { query, timestamp } : undefined;
24
+ }
25
+ }
26
+ } catch { /* Ordinary per-turn ranking still applies when the branch is unreadable. */ }
27
+ return undefined;
28
+ }