@aeondave/pi-persona-mind 0.8.7 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +58 -14
- package/CHANGELOG.md +95 -0
- package/README.md +123 -67
- package/docs/DESIGN.md +224 -35
- package/docs/MEMORY-RESEARCH.md +135 -112
- package/package.json +7 -12
- package/src/core/auto-optimize.ts +12 -10
- package/src/core/capture.ts +14 -6
- package/src/core/host-compat.ts +9 -6
- package/src/core/knowledge-review.ts +107 -0
- package/src/core/memory-inspector.ts +149 -0
- package/src/core/memory-read.ts +3 -3
- package/src/core/memory.ts +6 -0
- package/src/core/optimize-history.ts +3 -3
- package/src/core/optimize-service.ts +10 -6
- package/src/core/optimize.ts +5 -11
- package/src/core/retrieval.ts +5 -4
- package/src/core/service.ts +24 -13
- package/src/core/store.ts +8 -2
- package/src/extension/auto-optimize-session.ts +26 -6
- package/src/extension/auto-optimize.ts +134 -25
- package/src/extension/inspector-data.ts +69 -0
- package/src/extension/knowledge-review.ts +215 -0
- package/src/extension/memory-inspector.ts +82 -0
- package/src/extension/mind-actions.ts +38 -0
- package/src/extension/mind-command.ts +42 -1
- package/src/extension/review-evidence.ts +222 -0
- package/src/index.ts +90 -43
- package/src/session-memory.ts +6 -2
- package/src/tools/backlog.ts +2 -2
- package/src/tools/memory.ts +51 -24
- package/src/ui/card-frame.ts +161 -0
- package/src/ui/inspector-frame.ts +44 -0
- package/src/ui/memory-inspector.ts +460 -0
- package/src/ui/mind-result-card.ts +37 -4
- package/src/ui/presentation.ts +13 -23
- package/src/ui/session-note-card.ts +12 -6
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Read-only inspector lifecycle. No persistence, model requests, or replacement retrieval policy. */
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { estimateTokens } from "../core/context-budget.ts";
|
|
4
|
+
import type { InspectorPage, InspectorRequest, InspectorTab } from "./inspector-data.ts";
|
|
5
|
+
import type { InspectorActionRequest } from "./mind-actions.ts";
|
|
6
|
+
|
|
7
|
+
export interface InspectorScreenOptions {
|
|
8
|
+
load(request: InspectorRequest): Promise<InspectorPage>;
|
|
9
|
+
isCurrent(): boolean;
|
|
10
|
+
initialTab: InspectorTab;
|
|
11
|
+
signal: AbortSignal;
|
|
12
|
+
onAction?(request: InspectorActionRequest): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface MemoryInspectorDeps {
|
|
15
|
+
unavailableReason(ctx: ExtensionContext): string | undefined;
|
|
16
|
+
captureOwner(ctx: ExtensionContext): () => boolean;
|
|
17
|
+
load(ctx: ExtensionContext, request: InspectorRequest): Promise<InspectorPage>;
|
|
18
|
+
show(ctx: ExtensionContext, options: InspectorScreenOptions): Promise<void>;
|
|
19
|
+
actions?(ctx: ExtensionContext, request: InspectorActionRequest, isCurrent: () => boolean): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createMemoryInspector(deps: MemoryInspectorDeps) {
|
|
23
|
+
let generation = 0;
|
|
24
|
+
let opening: AbortController | undefined;
|
|
25
|
+
let prepared: { text: string; at: string; current: () => boolean } | undefined;
|
|
26
|
+
const invalidate = (): void => {
|
|
27
|
+
generation++;
|
|
28
|
+
prepared = undefined;
|
|
29
|
+
const old = opening;
|
|
30
|
+
opening = undefined;
|
|
31
|
+
old?.abort();
|
|
32
|
+
};
|
|
33
|
+
const captureContext = (ctx: ExtensionContext): (() => boolean) => {
|
|
34
|
+
const acceptedGeneration = generation;
|
|
35
|
+
const owner = deps.captureOwner(ctx);
|
|
36
|
+
return () => acceptedGeneration === generation && owner();
|
|
37
|
+
};
|
|
38
|
+
return {
|
|
39
|
+
invalidate, captureContext,
|
|
40
|
+
recordContext(ctx: ExtensionContext, text: string, current = captureContext(ctx)): void {
|
|
41
|
+
if (current()) prepared = { text, at: new Date().toISOString(), current };
|
|
42
|
+
},
|
|
43
|
+
async open(ctx: ExtensionContext, initialTab: InspectorTab = "memories"): Promise<void> {
|
|
44
|
+
const unavailable = deps.unavailableReason(ctx);
|
|
45
|
+
if (unavailable) { ctx.ui.notify(unavailable, "warning"); return; }
|
|
46
|
+
if (ctx.mode !== "tui") { ctx.ui.notify("Memory inspector requires the interactive terminal (TUI). Use /mind, /mind session or memory recall/read here.", "info"); return; }
|
|
47
|
+
if (opening) return;
|
|
48
|
+
const owner = deps.captureOwner(ctx);
|
|
49
|
+
if (!owner()) { ctx.ui.notify("Memory session owner is unavailable.", "warning"); return; }
|
|
50
|
+
const acceptedGeneration = generation;
|
|
51
|
+
const controller = new AbortController();
|
|
52
|
+
opening = controller;
|
|
53
|
+
const current = (): boolean => !controller.signal.aborted && acceptedGeneration === generation && owner();
|
|
54
|
+
const requireCurrent = (): void => { if (!current()) throw new Error("Memory inspector session owner changed; reopen it."); };
|
|
55
|
+
try {
|
|
56
|
+
await deps.show(ctx, {
|
|
57
|
+
initialTab, signal: controller.signal, isCurrent: current,
|
|
58
|
+
...(deps.actions ? { onAction: async (request: InspectorActionRequest) => { requireCurrent(); await deps.actions!(ctx, request, current); } } : {}),
|
|
59
|
+
async load(request) {
|
|
60
|
+
requireCurrent();
|
|
61
|
+
if (request.tab === "context") {
|
|
62
|
+
if (!prepared?.current()) return { items: [], total: 0, offset: 0, notice: "No Mind context prepared in this active session/branch yet. Start a turn; reopening does not recompute or persist context." };
|
|
63
|
+
const { text, at } = prepared;
|
|
64
|
+
return {
|
|
65
|
+
items: [{ id: "prepared-context", title: `Last prepared · ${at} · ~${estimateTokens(text)} tokens (estimate)`, body: text || "Mind prepared no additional context for this turn." }],
|
|
66
|
+
total: 1, offset: 0,
|
|
67
|
+
notice: "Exact last block prepared by Mind, not the final provider payload. Later extensions may change it. UTF-8 bytes/3 is a planning estimate, not billing. Omission notices are part of the block; selection uses the existing lexical/tag/path ranker and bounded priority, never a second inspector policy.",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const page = await deps.load(ctx, request);
|
|
71
|
+
requireCurrent();
|
|
72
|
+
return page;
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (current()) ctx.ui.notify(`Memory inspector unavailable: ${error instanceof Error ? error.message : "read failed"}`, "warning");
|
|
77
|
+
} finally {
|
|
78
|
+
if (opening === controller) opening = undefined;
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Explicit human actions after F10 closes. Browsing itself stays read-only. */
|
|
2
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { InspectorRequest } from "./inspector-data.ts";
|
|
4
|
+
import type { ReviewTarget } from "../core/knowledge-review.ts";
|
|
5
|
+
import type { createKnowledgeReview } from "./knowledge-review.ts";
|
|
6
|
+
|
|
7
|
+
export type InspectorActionRequest = InspectorRequest & { selectedId?: string };
|
|
8
|
+
export interface MindActionDeps {
|
|
9
|
+
consolidate(target: ReviewTarget): boolean;
|
|
10
|
+
review: ReturnType<typeof createKnowledgeReview>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function runMindInspectorActions(ctx: ExtensionContext, request: InspectorActionRequest, current: () => boolean, deps: MindActionDeps): Promise<void> {
|
|
14
|
+
if (!current() || ctx.mode !== "tui" || request.tab !== "memories") return;
|
|
15
|
+
const target = request.scope === "project" || request.scope === "project-long" || request.scope === "persona" ? request.scope : undefined;
|
|
16
|
+
const consolidate = "Consolidate this scope (bounded window)";
|
|
17
|
+
const selected = "Review selected fact against evidence";
|
|
18
|
+
const window = "Review this scope against evidence (bounded window)";
|
|
19
|
+
const show = "Show pending knowledge review";
|
|
20
|
+
const apply = "Approve staged knowledge corrections";
|
|
21
|
+
const discard = "Discard/cancel knowledge review";
|
|
22
|
+
const choices = [...(target ? [consolidate, ...(request.selectedId ? [selected] : []), window] : []), show, apply, discard];
|
|
23
|
+
const choice = await ctx.ui.select(`Mind actions · ${request.scope}${target ? "" : " (choose a project/persona scope to review facts)"}`, choices);
|
|
24
|
+
if (!choice || !current()) return;
|
|
25
|
+
if (choice === show) { await deps.review.show(ctx); return; }
|
|
26
|
+
if (choice === apply) { await deps.review.apply(ctx); return; }
|
|
27
|
+
if (choice === discard) { deps.review.discard(ctx); return; }
|
|
28
|
+
if (!target) return;
|
|
29
|
+
if (choice === consolidate) {
|
|
30
|
+
const accepted = await ctx.ui.confirm("Consolidate memory?", `Review one bounded window of ${target} on the current session model. Compatible facts may be merged and applied through the existing validated optimizer; history and guarded undo are retained. This is not a truth audit or a full-store rewrite. Continue?`);
|
|
31
|
+
if (!accepted || !current()) return;
|
|
32
|
+
const started = deps.consolidate(target);
|
|
33
|
+
ctx.ui.notify(started ? `mind · ${target} consolidation requested; bounded inspection and worker admission are preparing.` : "Mind maintenance or the foreground is busy; no consolidation was accepted.", started ? "info" : "warning");
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (choice === selected) await deps.review.start(ctx, target, request.selectedId);
|
|
37
|
+
else if (choice === window) await deps.review.start(ctx, target);
|
|
38
|
+
}
|
|
@@ -11,11 +11,19 @@ import { formatOptimizeApplied, formatOptimizeFailure, formatOptimizeHistory, fo
|
|
|
11
11
|
import { isOptimizeTarget } from "../core/optimize.ts";
|
|
12
12
|
import { runMindActivity } from "./activity.ts";
|
|
13
13
|
import type { MindActivityRunner } from "./activity.ts";
|
|
14
|
+
import type { InspectorTab } from "./inspector-data.ts";
|
|
15
|
+
import type { ReviewTarget } from "../core/knowledge-review.ts";
|
|
16
|
+
import type { createKnowledgeReview } from "./knowledge-review.ts";
|
|
14
17
|
|
|
15
18
|
export type MindOptimizeTarget = "project" | "project-long" | "persona" | "shared";
|
|
16
19
|
|
|
17
20
|
export type MindCommand =
|
|
18
21
|
| { type: "snapshot" }
|
|
22
|
+
| { type: "browse"; tab: InspectorTab }
|
|
23
|
+
| { type: "review"; target?: ReviewTarget }
|
|
24
|
+
| { type: "review-show" }
|
|
25
|
+
| { type: "review-apply" }
|
|
26
|
+
| { type: "review-discard" }
|
|
19
27
|
| { type: "help" }
|
|
20
28
|
| { type: "doctor" }
|
|
21
29
|
| { type: "reset" }
|
|
@@ -32,7 +40,7 @@ export type MindCommand =
|
|
|
32
40
|
| { type: "invalid"; message: string };
|
|
33
41
|
|
|
34
42
|
const USAGE =
|
|
35
|
-
"usage: /persona-mind [help|doctor|session|reset [workspace]|migrate-persona|optimize [all|project|project-long|persona]|optimize inspect [project|project-long|persona|shared]|optimize show <planId>|optimize apply <planId>|optimize history [target]|optimize undo <receiptId> [target]|optimize auto [status|on|off]]";
|
|
43
|
+
"usage: /persona-mind [help|browse [memories|context|timeline]|timeline|review [project|project-long|persona|show|apply|discard]|doctor|session|reset [workspace]|migrate-persona|optimize [all|project|project-long|persona]|optimize inspect [project|project-long|persona|shared]|optimize show <planId>|optimize apply <planId>|optimize history [target]|optimize undo <receiptId> [target]|optimize auto [status|on|off]]";
|
|
36
44
|
|
|
37
45
|
export interface MindCommandDeps {
|
|
38
46
|
agentDir: string;
|
|
@@ -40,6 +48,8 @@ export interface MindCommandDeps {
|
|
|
40
48
|
rawPersona(ctx: ExtensionContext): string | null;
|
|
41
49
|
getMind(ctx: ExtensionContext): MindService;
|
|
42
50
|
getSessionMemory(): SessionMemory;
|
|
51
|
+
openInspector?(ctx: ExtensionContext, tab: InspectorTab): Promise<void>;
|
|
52
|
+
knowledgeReview?: ReturnType<typeof createKnowledgeReview>;
|
|
43
53
|
getOptimizer(ctx: ExtensionContext): MemoryOptimizer;
|
|
44
54
|
activity?(ctx: ExtensionContext): MindActivityRunner | undefined;
|
|
45
55
|
autoOptimize?: { status(): string; setEnabled(enabled: boolean): void; targets?(): readonly Exclude<MindOptimizeTarget, "shared">[]; startExplicit?(target?: Exclude<MindOptimizeTarget, "shared">): boolean };
|
|
@@ -71,9 +81,28 @@ export function registerMindCommands(pi: ExtensionAPI, deps: MindCommandDeps): v
|
|
|
71
81
|
ctx.ui.notify(command.message, "warning");
|
|
72
82
|
return;
|
|
73
83
|
}
|
|
84
|
+
if (command.type === "review" || command.type === "review-show" || command.type === "review-apply" || command.type === "review-discard") {
|
|
85
|
+
if (deps.isDelegatedLeg || !deps.isCurrent(ctx) || !deps.knowledgeReview) { ctx.ui.notify("Knowledge review requires an active supervisor session.", "warning"); return; }
|
|
86
|
+
if (command.type === "review-show") await deps.knowledgeReview.show(ctx);
|
|
87
|
+
else if (command.type === "review-apply") await deps.knowledgeReview.apply(ctx);
|
|
88
|
+
else if (command.type === "review-discard") deps.knowledgeReview.discard(ctx);
|
|
89
|
+
else await deps.knowledgeReview.start(ctx, command.target ?? (deps.resolveScope(ctx).homeWorkspace ? "persona" : "project-long"));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (command.type === "browse") {
|
|
93
|
+
if (deps.isDelegatedLeg || !deps.isCurrent(ctx) || !deps.openInspector) {
|
|
94
|
+
ctx.ui.notify("Memory inspector requires an active supervisor session.", "warning");
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
await deps.openInspector(ctx, command.tab);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
74
100
|
if (command.type === "help") {
|
|
75
101
|
const body = [
|
|
76
102
|
"/persona-mind — persona memory and active-session notes",
|
|
103
|
+
"F10 or /mind browse [memories|context|timeline] — memory inspector; a opens explicit consolidation/review actions; /mind timeline opens active-branch conversation history",
|
|
104
|
+
"/mind review [project|project-long|persona] — evidence-grounded knowledge review on the session model; stages corrections, never auto-applies",
|
|
105
|
+
"/mind review show|apply|discard — inspect the proposal, approve guarded corrections, or cancel/discard; retirement findings are recommendations only",
|
|
77
106
|
"/persona-mind doctor — inspect store health and migration warnings",
|
|
78
107
|
"/persona-mind session — list notes on this active session branch",
|
|
79
108
|
"/persona-mind reset [workspace] — clear this project's short-term memory and backlog",
|
|
@@ -329,6 +358,18 @@ export function parseMindCommand(args: string): MindCommand {
|
|
|
329
358
|
const parts = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
330
359
|
if (parts.length === 0) return { type: "snapshot" };
|
|
331
360
|
if (parts.length === 1 && parts[0] === "help") return { type: "help" };
|
|
361
|
+
if (parts[0] === "review") {
|
|
362
|
+
if (parts.length === 1) return { type: "review" };
|
|
363
|
+
if (parts.length === 2 && (parts[1] === "project" || parts[1] === "project-long" || parts[1] === "persona")) return { type: "review", target: parts[1] };
|
|
364
|
+
if (parts.length === 2 && (parts[1] === "show" || parts[1] === "apply" || parts[1] === "discard")) return { type: `review-${parts[1]}` };
|
|
365
|
+
return { type: "invalid", message: "usage: /mind review [project|project-long|persona|show|apply|discard]. Shared and session notes are not model-review targets." };
|
|
366
|
+
}
|
|
367
|
+
if (parts.length === 1 && parts[0] === "timeline") return { type: "browse", tab: "timeline" };
|
|
368
|
+
if (parts[0] === "browse") {
|
|
369
|
+
if (parts.length === 1) return { type: "browse", tab: "memories" };
|
|
370
|
+
if (parts.length === 2 && (parts[1] === "memories" || parts[1] === "context" || parts[1] === "timeline")) return { type: "browse", tab: parts[1] };
|
|
371
|
+
return { type: "invalid", message: USAGE };
|
|
372
|
+
}
|
|
332
373
|
if (parts.length === 1 && parts[0] === "doctor") return { type: "doctor" };
|
|
333
374
|
if (parts.length === 1 && parts[0] === "session") return { type: "session" };
|
|
334
375
|
if (parts.length === 1 && parts[0] === "reset") return { type: "reset" };
|
|
@@ -0,0 +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
|
+
}
|