@aeondave/pi-persona-mind 0.0.0-stage → 0.8.4
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 +78 -0
- package/CHANGELOG.md +78 -0
- package/LICENSE +24 -0
- package/README.md +244 -2
- package/assets/banner.png +0 -0
- package/docs/DESIGN.md +282 -0
- package/docs/MEMORY-RESEARCH.md +112 -0
- package/package.json +93 -4
- package/src/core/auto-optimize.ts +239 -0
- package/src/core/backlog.ts +228 -0
- package/src/core/blocked.ts +38 -0
- package/src/core/capture.ts +146 -0
- package/src/core/context-budget.ts +74 -0
- package/src/core/host-compat.ts +13 -0
- package/src/core/ids.ts +59 -0
- package/src/core/inject.ts +247 -0
- package/src/core/memory-read.ts +34 -0
- package/src/core/memory.ts +308 -0
- package/src/core/migrate.ts +713 -0
- package/src/core/mind-settings.ts +54 -0
- package/src/core/optimize-history.ts +101 -0
- package/src/core/optimize-service.ts +182 -0
- package/src/core/optimize.ts +133 -0
- package/src/core/retrieval.ts +108 -0
- package/src/core/scanner.ts +146 -0
- package/src/core/scope.ts +205 -0
- package/src/core/service.ts +644 -0
- package/src/core/session-memory.ts +71 -0
- package/src/core/store.ts +948 -0
- package/src/extension/activity.ts +79 -0
- package/src/extension/auto-optimize-session.ts +118 -0
- package/src/extension/auto-optimize.ts +265 -0
- package/src/extension/mind-command.ts +335 -0
- package/src/extension/mind-worker.ts +32 -0
- package/src/extension/persona-dependency.ts +76 -0
- package/src/index.ts +1231 -0
- package/src/session-memory.ts +118 -0
- package/src/tools/backlog.ts +126 -0
- package/src/tools/memory-optimize.ts +133 -0
- package/src/tools/memory.ts +400 -0
- package/src/ui/mind-result-card.ts +15 -0
- package/src/ui/presentation.ts +97 -0
- package/src/ui/session-note-card.ts +50 -0
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
import { inspectStoreFile, type StoreDiagnostic } from "../core/migrate.ts";
|
|
6
|
+
import type { Scope } from "../core/scope.ts";
|
|
7
|
+
import type { MindService } from "../core/service.ts";
|
|
8
|
+
import type { SessionMemory } from "../session-memory.ts";
|
|
9
|
+
import type { MemoryOptimizer } from "../core/optimize-service.ts";
|
|
10
|
+
import { formatOptimizeApplied, formatOptimizeFailure, formatOptimizeHistory, formatOptimizeInspection, formatOptimizePlan, formatOptimizeUndone } from "../tools/memory-optimize.ts";
|
|
11
|
+
import { isOptimizeTarget } from "../core/optimize.ts";
|
|
12
|
+
import { runMindActivity } from "./activity.ts";
|
|
13
|
+
import type { MindActivityRunner } from "./activity.ts";
|
|
14
|
+
|
|
15
|
+
export type MindOptimizeTarget = "project" | "project-long" | "persona" | "shared";
|
|
16
|
+
|
|
17
|
+
export type MindCommand =
|
|
18
|
+
| { type: "snapshot" }
|
|
19
|
+
| { type: "help" }
|
|
20
|
+
| { type: "doctor" }
|
|
21
|
+
| { type: "reset" }
|
|
22
|
+
| { type: "migrate-persona" }
|
|
23
|
+
| { type: "session" }
|
|
24
|
+
| { type: "optimize-inspect"; target: MindOptimizeTarget }
|
|
25
|
+
| { type: "optimize-show"; planId: string }
|
|
26
|
+
| { type: "optimize-apply"; planId: string }
|
|
27
|
+
| { type: "optimize-history"; target: MindOptimizeTarget }
|
|
28
|
+
| { type: "optimize-undo"; receiptId: string; target: MindOptimizeTarget }
|
|
29
|
+
| { type: "optimize-auto"; action: "status" | "on" | "off" }
|
|
30
|
+
| { type: "invalid"; message: string };
|
|
31
|
+
|
|
32
|
+
const USAGE =
|
|
33
|
+
"usage: /persona-mind [help|doctor|session|reset [workspace]|migrate-persona|optimize [project|project-long|persona|shared]|optimize show <planId>|optimize apply <planId>|optimize history [target]|optimize undo <receiptId> [target]|optimize auto [status|on|off]]";
|
|
34
|
+
|
|
35
|
+
export interface MindCommandDeps {
|
|
36
|
+
agentDir: string;
|
|
37
|
+
resolveScope(ctx: ExtensionContext): Scope;
|
|
38
|
+
rawPersona(ctx: ExtensionContext): string | null;
|
|
39
|
+
getMind(ctx: ExtensionContext): MindService;
|
|
40
|
+
getSessionMemory(): SessionMemory;
|
|
41
|
+
getOptimizer(ctx: ExtensionContext): MemoryOptimizer;
|
|
42
|
+
activity?(ctx: ExtensionContext): MindActivityRunner | undefined;
|
|
43
|
+
autoOptimize?: { status(): string; setEnabled(enabled: boolean): void };
|
|
44
|
+
isCurrent(ctx: ExtensionContext): boolean;
|
|
45
|
+
ensureLegacyMigrated(ctx: ExtensionContext, includeAmbiguousPersonaAlias?: boolean, awaitCompletion?: boolean): Promise<void>;
|
|
46
|
+
migrationStatus(): string;
|
|
47
|
+
unavailableReason(ctx: ExtensionContext): string | undefined;
|
|
48
|
+
surfaceWarning(ctx: ExtensionContext, message: string): void;
|
|
49
|
+
pendingWarnings(): readonly string[];
|
|
50
|
+
acknowledgeWarnings(ctx: ExtensionContext, warningCount: number): void;
|
|
51
|
+
capturePolicy(): string;
|
|
52
|
+
isDelegatedLeg: boolean;
|
|
53
|
+
sessionActive(): boolean;
|
|
54
|
+
afterWorkspaceReset(ctx: ExtensionContext): Promise<void>;
|
|
55
|
+
appendResult(ctx: ExtensionContext, title: string, body: string): void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function registerMindCommands(pi: ExtensionAPI, deps: MindCommandDeps): void {
|
|
59
|
+
const handler = async (args: string, ctx: ExtensionContext): Promise<void> => {
|
|
60
|
+
const command = parseMindCommand(args);
|
|
61
|
+
if (command.type !== "help") {
|
|
62
|
+
const unavailable = deps.unavailableReason(ctx);
|
|
63
|
+
if (unavailable) {
|
|
64
|
+
ctx.ui.notify(unavailable, "warning");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (command.type === "invalid") {
|
|
69
|
+
ctx.ui.notify(command.message, "warning");
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (command.type === "help") {
|
|
73
|
+
const body = [
|
|
74
|
+
"/persona-mind — persona memory and active-session notes",
|
|
75
|
+
"/persona-mind doctor — inspect store health and migration warnings",
|
|
76
|
+
"/persona-mind session — list notes on this active session branch",
|
|
77
|
+
"/persona-mind reset [workspace] — clear this project's short-term memory and backlog",
|
|
78
|
+
"/persona-mind migrate-persona — explicitly import an ambiguous historical persona alias",
|
|
79
|
+
"/persona-mind optimize [project|project-long|persona|shared] — inspect bounded candidates (read-only); project is expiring working memory, project-long is durable repository knowledge",
|
|
80
|
+
"Ask the agent to compare candidates with current evidence, read full entries, and stage a concise proposal that preserves exceptions and provenance.",
|
|
81
|
+
"/persona-mind optimize show <planId> — inspect exact staged text; /persona-mind optimize apply <planId> commits that plan only",
|
|
82
|
+
"/persona-mind optimize history [target] — inspect bounded durable before/after receipts; /persona-mind optimize undo <receiptId> [target] restores unchanged affected facts (target defaults to project)",
|
|
83
|
+
"/persona-mind optimize auto [status|on|off] — inspect or switch automatic review for this session; off cancels pending work",
|
|
84
|
+
"/mind is an alias. Manual inspection makes no changes; manual apply commits only a staged plan. Automatic review uses the session model at idle and reports its changes.",
|
|
85
|
+
].join("\n");
|
|
86
|
+
publish(ctx, deps, "pi-persona-mind help", body, "Command reference is in the expandable card.");
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
if (command.type === "optimize-auto") {
|
|
90
|
+
if (!captureSessionOwner(deps, ctx)()) {
|
|
91
|
+
ctx.ui.notify("Memory session owner changed; automatic optimization was not changed.", "warning");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (deps.isDelegatedLeg || !deps.autoOptimize) {
|
|
95
|
+
ctx.ui.notify("Automatic memory optimization is unavailable in this session.", "warning");
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (command.action !== "status") deps.autoOptimize.setEnabled(command.action === "on");
|
|
99
|
+
publish(ctx, deps, "Automatic memory optimization", deps.autoOptimize.status(), "Automatic memory optimization status is in the expandable card.");
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (command.type === "migrate-persona") {
|
|
103
|
+
const ownerCurrent = captureSessionOwner(deps, ctx);
|
|
104
|
+
const scopeAtStart = deps.resolveScope(ctx);
|
|
105
|
+
if (!ownerCurrent()) return;
|
|
106
|
+
const rawPersona = deps.rawPersona(ctx);
|
|
107
|
+
await deps.ensureLegacyMigrated(ctx, true, true);
|
|
108
|
+
if (!ownerCurrent() || !sameScope(scopeAtStart, deps.resolveScope(ctx))) return;
|
|
109
|
+
deps.surfaceWarning(ctx, rawPersona === null
|
|
110
|
+
? "AMBIGUOUS persona migration requested, but no active persona is selected; only project aliases were reconciled."
|
|
111
|
+
: `AMBIGUOUS persona migration imported the historical alias for '${rawPersona}'. Review the result; source files were left untouched.`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (command.type === "optimize-history" || command.type === "optimize-undo") {
|
|
116
|
+
const active = captureOptimizer(deps, ctx);
|
|
117
|
+
if (!active || !optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
118
|
+
ctx.ui.notify("Memory owner changed; optimization history is unavailable in the active scope.", "warning");
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
const formatted = command.type === "optimize-history"
|
|
122
|
+
? await runMindActivity(deps.activity?.(ctx), "inspect", command.target, async () => {
|
|
123
|
+
const result = await active.optimizer.history(command.target);
|
|
124
|
+
return result.ok ? formatOptimizeHistory(result) : formatOptimizeFailure(result);
|
|
125
|
+
}, (result) => result.details.ok === true)
|
|
126
|
+
: await runMindActivity(deps.activity?.(ctx), "apply", command.target, async () => {
|
|
127
|
+
const result = await active.optimizer.undo(command.receiptId, command.target);
|
|
128
|
+
return result.ok ? formatOptimizeUndone(result) : formatOptimizeFailure(result);
|
|
129
|
+
}, (result) => result.details.ok === true);
|
|
130
|
+
if (!optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
131
|
+
ctx.ui.notify(command.type === "optimize-undo" ? "Memory owner changed while undo was running. Inspect the target memory before retrying; undo may already have completed." : "Memory owner changed while history was read; no stale result was displayed.", "warning");
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
publish(ctx, deps, command.type === "optimize-history" ? "Memory optimization history" : "Memory consolidation undo", formatted.content[0]?.text ?? "No result.");
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (command.type === "optimize-apply") {
|
|
138
|
+
const active = captureOptimizer(deps, ctx);
|
|
139
|
+
if (!active || !optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
140
|
+
ctx.ui.notify("Memory owner changed; this staged plan is no longer available in the active scope.", "warning");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const plan = active.optimizer.getPlan(command.planId);
|
|
144
|
+
const result = plan.ok
|
|
145
|
+
? await runMindActivity(deps.activity?.(ctx), "apply", plan.target, () => active.optimizer.apply(command.planId), (outcome) => outcome.ok)
|
|
146
|
+
: await active.optimizer.apply(command.planId);
|
|
147
|
+
if (!optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
148
|
+
ctx.ui.notify("The memory owner changed while apply was running. Inspect the target memory before retrying; the staged apply may already have completed.", "warning");
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const formatted = result.ok ? formatOptimizeApplied(result) : formatOptimizeFailure(result);
|
|
152
|
+
publish(ctx, deps, "Memory optimization result", formatted.content[0]?.text ?? "No result.", "Memory optimization result is in the expandable card.");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (command.type === "optimize-show") {
|
|
156
|
+
const active = captureOptimizer(deps, ctx);
|
|
157
|
+
if (!active || !optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
158
|
+
ctx.ui.notify("Memory owner changed; this staged plan is unavailable in the active scope.", "warning");
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const result = active.optimizer.getPlan(command.planId);
|
|
162
|
+
const formatted = result.ok ? formatOptimizePlan(result) : formatOptimizeFailure(result);
|
|
163
|
+
publish(ctx, deps, "Staged memory optimization plan", formatted.content[0]?.text ?? "No result.", "Staged memory plan is in the expandable card.");
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
if (command.type === "optimize-inspect") {
|
|
167
|
+
await deps.ensureLegacyMigrated(ctx);
|
|
168
|
+
const active = captureOptimizer(deps, ctx);
|
|
169
|
+
if (!active || !optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
170
|
+
ctx.ui.notify("Memory owner changed before inspection; no result was displayed.", "warning");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const result = await runMindActivity(deps.activity?.(ctx), "inspect", command.target, () => active.optimizer.inspect(command.target), (outcome) => outcome.ok);
|
|
174
|
+
if (!optimizerIsCurrent(deps, ctx, active.optimizer, active.ownerCurrent)) {
|
|
175
|
+
ctx.ui.notify("Memory scope changed while inspection was running; no stale result was displayed.", "warning");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const formatted = result.ok ? formatOptimizeInspection(result) : formatOptimizeFailure(result);
|
|
179
|
+
publish(ctx, deps, `Memory optimization · ${command.target}`, formatted.content[0]?.text ?? "No result.", `Memory inspection for ${command.target} is in the expandable card.`);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const ownerCurrent = captureSessionOwner(deps, ctx);
|
|
184
|
+
const scopeAtStart = deps.resolveScope(ctx);
|
|
185
|
+
if (!ownerCurrent()) return;
|
|
186
|
+
if (command.type === "doctor") await deps.ensureLegacyMigrated(ctx);
|
|
187
|
+
else await deps.ensureLegacyMigrated(ctx);
|
|
188
|
+
if (!ownerCurrent() || !sameScope(scopeAtStart, deps.resolveScope(ctx))) return;
|
|
189
|
+
const scope = scopeAtStart;
|
|
190
|
+
if (command.type === "doctor") {
|
|
191
|
+
const diagnostics: Array<[string, StoreDiagnostic]> = await Promise.all([
|
|
192
|
+
inspectStoreFile(scope.paths.ltm, "ltm").then((d): [string, StoreDiagnostic] => ["long-term", d]),
|
|
193
|
+
inspectStoreFile(scope.paths.shared, "ltm").then((d): [string, StoreDiagnostic] => ["shared", d]),
|
|
194
|
+
inspectStoreFile(scope.paths.projectLtm, "ltm").then((d): [string, StoreDiagnostic] => ["project durable", d]),
|
|
195
|
+
inspectStoreFile(scope.paths.stm, "stm").then((d): [string, StoreDiagnostic] => ["short-term", d]),
|
|
196
|
+
inspectStoreFile(scope.paths.backlog, "backlog").then((d): [string, StoreDiagnostic] => ["backlog", d]),
|
|
197
|
+
]);
|
|
198
|
+
if (!ownerCurrent() || !sameScope(scope, deps.resolveScope(ctx))) return;
|
|
199
|
+
const pathLine = ([label, diagnostic]: [string, StoreDiagnostic]): string => {
|
|
200
|
+
const suffix = diagnostic.status === "missing" ? "not created" : diagnostic.status === "ok" ? `ok (${diagnostic.validEntries} entries)` : `${diagnostic.status} (${diagnostic.message ?? `${diagnostic.invalidEntries} invalid entries`})`;
|
|
201
|
+
return `${label}: ${diagnostic.path} (${suffix})`;
|
|
202
|
+
};
|
|
203
|
+
const diagnosticWarnings = diagnostics.filter(([, diagnostic]) => diagnostic.status !== "missing" && diagnostic.status !== "ok").map(([label, diagnostic]) => `${label}: ${diagnostic.status} — ${diagnostic.message ?? "invalid store"}`);
|
|
204
|
+
const allWarnings = [...deps.pendingWarnings(), ...diagnosticWarnings];
|
|
205
|
+
const lines = [
|
|
206
|
+
"pi-persona-mind doctor",
|
|
207
|
+
`persona: ${scope.persona}`,
|
|
208
|
+
`cwd: ${ctx.cwd}`,
|
|
209
|
+
`project root: ${scope.projectRoot}${scope.homeWorkspace ? " (home — STM/backlog not injected, wakes off)" : ""}`,
|
|
210
|
+
`project slug: ${scope.slug}`,
|
|
211
|
+
`capture: ${deps.capturePolicy()} (PI_PERSONA_MIND_CAPTURE)`,
|
|
212
|
+
`automatic optimization: ${deps.autoOptimize?.status() ?? "unavailable in this session"}`,
|
|
213
|
+
`migration: ${deps.migrationStatus()}`,
|
|
214
|
+
...diagnostics.map(pathLine),
|
|
215
|
+
`legacy root: ${join(deps.agentDir, "pi-persona-mind")} (${existsSync(join(deps.agentDir, "pi-persona-mind")) ? "detected; imported non-destructively" : "absent"})`,
|
|
216
|
+
`warnings: ${allWarnings.length === 0 ? "none" : allWarnings.join(" | ")}`,
|
|
217
|
+
];
|
|
218
|
+
deps.acknowledgeWarnings(ctx, allWarnings.length);
|
|
219
|
+
publish(ctx, deps, "Memory doctor", lines.join("\n"), allWarnings.length === 0 ? "Memory doctor: healthy; see the expandable card." : `Memory doctor found ${allWarnings.length} warning(s); see the expandable card.`, allWarnings.length === 0 ? "info" : "warning");
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (command.type === "reset") {
|
|
223
|
+
if (deps.isDelegatedLeg) {
|
|
224
|
+
ctx.ui.notify("a delegated worker cannot reset the supervisor's workspace mind", "warning");
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const mind = deps.getMind(ctx);
|
|
228
|
+
const result = await mind.resetWorkspace();
|
|
229
|
+
if (!ownerCurrent() || !sameScope(scope, deps.resolveScope(ctx))) return;
|
|
230
|
+
if (!result.ok) {
|
|
231
|
+
ctx.ui.notify(`mind reset failed: ${result.reason}`, "error");
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (deps.sessionActive()) {
|
|
235
|
+
await deps.afterWorkspaceReset(ctx);
|
|
236
|
+
if (!ownerCurrent() || !sameScope(scope, deps.resolveScope(ctx))) return;
|
|
237
|
+
}
|
|
238
|
+
const receipt = `Cleared this workspace (${scope.projectRoot}): ${result.stmRemoved} short-term · ${result.backlogRemoved} backlog. Long-term identity (${result.ltmKept}) left intact.`;
|
|
239
|
+
publish(ctx, deps, "Workspace memory reset", receipt, receipt);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (command.type === "session") {
|
|
243
|
+
const result = deps.getSessionMemory().snapshot(ctx);
|
|
244
|
+
if (!result.ok) {
|
|
245
|
+
ctx.ui.notify(`Session notes unavailable: ${result.reason ?? "active session owner is missing"}`, "warning");
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const rows = result.notes.slice(-20).reverse().map((note) => `- [${note.id}] (${note.kind}) ${note.text.replace(/\s+/g, " ").slice(0, 160)}${note.text.length > 160 ? "…" : ""}`);
|
|
249
|
+
const omitted = result.notes.length > rows.length ? `\n… ${result.notes.length - rows.length} older note(s) omitted; use memory read with an id for full text.` : "";
|
|
250
|
+
const body = `Active-session notes (${result.notes.length}, storage: ${result.storage})${rows.length ? `\n${rows.join("\n")}` : "\n(none)"}${omitted}`;
|
|
251
|
+
publish(ctx, deps, "Active-session notes", body, `Active-session notes: ${result.notes.length}; details are in the expandable card.`);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const mind = deps.getMind(ctx);
|
|
255
|
+
const [summary, block] = await Promise.all([mind.summary(), mind.buildInjection()]);
|
|
256
|
+
if (!ownerCurrent() || !sameScope(scope, deps.resolveScope(ctx))) return;
|
|
257
|
+
const counts = `${summary.ltm} persona/shared · ${summary.projectLtm} project durable · ${summary.stm} working · ${summary.backlogOpen} open backlog`;
|
|
258
|
+
const header = `pi-persona-mind (${scope.persona}) — ${counts}`;
|
|
259
|
+
publish(ctx, deps, "Persona mind snapshot", block ? `${header}\n\n${block}` : `${header}\n\n(empty)`, counts);
|
|
260
|
+
};
|
|
261
|
+
const description = "Persona memory, active-session notes, diagnostics, and reviewed optimization";
|
|
262
|
+
pi.registerCommand("persona-mind", { description, handler });
|
|
263
|
+
pi.registerCommand("mind", { description: `${description} (alias)`, handler });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function publish(ctx: ExtensionContext, deps: MindCommandDeps, title: string, body: string, notice = `${title} is in the expandable card.`, level: "info" | "warning" = "info"): void {
|
|
267
|
+
try {
|
|
268
|
+
deps.appendResult(ctx, title, body);
|
|
269
|
+
ctx.ui.notify(notice, level);
|
|
270
|
+
} catch {
|
|
271
|
+
ctx.ui.notify(`${title}: ${body.split("\n", 1)[0]?.slice(0, 180) ?? "result unavailable"}`, "warning");
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function captureOptimizer(deps: MindCommandDeps, ctx: ExtensionContext): { optimizer: MemoryOptimizer; ownerCurrent: () => boolean } | undefined {
|
|
276
|
+
try {
|
|
277
|
+
if (!deps.isCurrent(ctx)) return undefined;
|
|
278
|
+
const ownerCurrent = deps.getSessionMemory().captureOwner(ctx);
|
|
279
|
+
if (!ownerCurrent()) return undefined;
|
|
280
|
+
return { optimizer: deps.getOptimizer(ctx), ownerCurrent };
|
|
281
|
+
} catch { return undefined; }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function optimizerIsCurrent(deps: MindCommandDeps, ctx: ExtensionContext, captured: MemoryOptimizer, ownerCurrent: () => boolean): boolean {
|
|
285
|
+
try { return ownerCurrent() && deps.isCurrent(ctx) && deps.getOptimizer(ctx) === captured; }
|
|
286
|
+
catch { return false; }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function captureSessionOwner(deps: MindCommandDeps, ctx: ExtensionContext): () => boolean {
|
|
290
|
+
try {
|
|
291
|
+
const ownerCurrent = deps.getSessionMemory().captureOwner(ctx);
|
|
292
|
+
return () => { try { return ownerCurrent() && deps.isCurrent(ctx); } catch { return false; } };
|
|
293
|
+
} catch { return () => false; }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function sameScope(left: Scope, right: Scope): boolean {
|
|
297
|
+
return left.persona === right.persona && left.projectRoot === right.projectRoot && left.slug === right.slug &&
|
|
298
|
+
left.paths.ltm === right.paths.ltm && left.paths.shared === right.paths.shared && left.paths.projectLtm === right.paths.projectLtm && left.paths.stm === right.paths.stm && left.paths.backlog === right.paths.backlog;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Parse the shared /persona-mind and /mind command grammar without performing any action. */
|
|
302
|
+
export function parseMindCommand(args: string): MindCommand {
|
|
303
|
+
if (typeof args !== "string") return { type: "invalid", message: USAGE };
|
|
304
|
+
const parts = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
305
|
+
if (parts.length === 0) return { type: "snapshot" };
|
|
306
|
+
if (parts.length === 1 && parts[0] === "help") return { type: "help" };
|
|
307
|
+
if (parts.length === 1 && parts[0] === "doctor") return { type: "doctor" };
|
|
308
|
+
if (parts.length === 1 && parts[0] === "session") return { type: "session" };
|
|
309
|
+
if (parts.length === 1 && parts[0] === "reset") return { type: "reset" };
|
|
310
|
+
if (parts.length === 2 && parts[0] === "reset" && parts[1] === "workspace") return { type: "reset" };
|
|
311
|
+
if (parts[0] === "reset") return { type: "invalid", message: "reset only clears THIS PROJECT's short-term memory and backlog. Long-term persona identity is not workspace-scoped — forget individual facts with `memory forget <id>`." };
|
|
312
|
+
if (parts.length === 1 && parts[0] === "migrate-persona") return { type: "migrate-persona" };
|
|
313
|
+
if (parts[0] === "optimize") {
|
|
314
|
+
if (parts[1] === "history" && (parts.length === 2 || parts.length === 3 && isOptimizeTarget(parts[2]))) return { type: "optimize-history", target: parts[2] as MindOptimizeTarget ?? "project" };
|
|
315
|
+
if (parts[1] === "undo" && (parts.length === 3 || parts.length === 4 && isOptimizeTarget(parts[3])) && isPlanId(args.trim().split(/\s+/)[2])) return { type: "optimize-undo", receiptId: args.trim().split(/\s+/)[2]!, target: parts[3] as MindOptimizeTarget ?? "project" };
|
|
316
|
+
if (parts[1] === "auto") {
|
|
317
|
+
if (parts.length === 2) return { type: "optimize-auto", action: "status" };
|
|
318
|
+
if (parts.length === 3 && (parts[2] === "status" || parts[2] === "on" || parts[2] === "off")) return { type: "optimize-auto", action: parts[2] };
|
|
319
|
+
return { type: "invalid", message: USAGE };
|
|
320
|
+
}
|
|
321
|
+
if (parts.length === 1) return { type: "optimize-inspect", target: "project" };
|
|
322
|
+
if (parts.length === 2 && (parts[1] === "project" || parts[1] === "project-long" || parts[1] === "persona" || parts[1] === "shared")) {
|
|
323
|
+
return { type: "optimize-inspect", target: parts[1] };
|
|
324
|
+
}
|
|
325
|
+
if (parts.length === 3 && (parts[1] === "show" || parts[1] === "apply") && isPlanId(args.trim().split(/\s+/)[2])) {
|
|
326
|
+
const planId = args.trim().split(/\s+/)[2]!;
|
|
327
|
+
return parts[1] === "show" ? { type: "optimize-show", planId } : { type: "optimize-apply", planId };
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return { type: "invalid", message: USAGE };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function isPlanId(value: string | undefined): value is string {
|
|
334
|
+
return typeof value === "string" && /^[A-Za-z0-9_-]{1,160}$/.test(value);
|
|
335
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Closed local bridge: Persona owns the real tracked worker and its model/permissions. */
|
|
2
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export type MindWorkerResult = {
|
|
5
|
+
status: "done"; ok: true; output: string; error?: string; resultRef?: string; model?: string; thinking?: string;
|
|
6
|
+
} | {
|
|
7
|
+
status: "failed" | "stopped"; ok: false; output: string; error?: string; resultRef?: string; model?: string; thinking?: string;
|
|
8
|
+
};
|
|
9
|
+
export type MindWorkerAdmission = { ok: false; reason: string } | {
|
|
10
|
+
ok: true; runId: string; model: string; thinking: string;
|
|
11
|
+
completion: Promise<MindWorkerResult>; cancel(): void;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export function launchMindWorker(pi: Pick<ExtensionAPI, "events">, sessionId: string, persona: string | null, task: string): MindWorkerAdmission {
|
|
15
|
+
const replies: unknown[] = [];
|
|
16
|
+
let accepting = true;
|
|
17
|
+
let failed = false;
|
|
18
|
+
try { pi.events.emit("pi-persona:mind-worker:v1", { version: 1, sessionId, persona, task, respond: (value: unknown) => { if (accepting) replies.push(value); else cancelReply(value); } }); }
|
|
19
|
+
catch { failed = true; }
|
|
20
|
+
finally { accepting = false; }
|
|
21
|
+
const reply = replies[0] as Partial<Extract<MindWorkerAdmission, { ok: true }>> | undefined;
|
|
22
|
+
if (!failed && replies.length === 1 && reply?.ok === true && typeof reply.runId === "string" && typeof reply.model === "string" && typeof reply.thinking === "string" && typeof reply.cancel === "function" && reply.completion instanceof Promise) return reply as Extract<MindWorkerAdmission, { ok: true }>;
|
|
23
|
+
// Ambiguous admission cannot leave an unowned worker running.
|
|
24
|
+
for (const value of replies) cancelReply(value);
|
|
25
|
+
if (failed) return { ok: false, reason: "Persona worker admission failed" };
|
|
26
|
+
const refusal = replies[0] as { reason?: unknown } | undefined;
|
|
27
|
+
return { ok: false, reason: typeof refusal?.reason === "string" ? refusal.reason : "Compatible Persona worker service unavailable" };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function cancelReply(value: unknown): void {
|
|
31
|
+
try { const item = value as { cancel?: unknown }; if (typeof item?.cancel === "function") item.cancel(); } catch { /* bounded cleanup */ }
|
|
32
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/** Mind requires the loaded Persona extension's public, synchronous capability protocol. */
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
|
|
4
|
+
export const PERSONA_COMPANION_CHANNEL = "pi-persona:companion:v1";
|
|
5
|
+
export const PERSONA_MEMORY_OWNER_CHANNEL = "pi-persona:memory-owner:v1";
|
|
6
|
+
export const PERSONA_MEMORY_OWNER_CHANGED = "pi-persona:memory-owner-changed:v1";
|
|
7
|
+
export const PERSONA_REQUIRED_REASON = "Mind is inactive: load a compatible pi-persona extension and /reload.";
|
|
8
|
+
export interface PersonaPresence {
|
|
9
|
+
version: 1;
|
|
10
|
+
provider: "pi-persona";
|
|
11
|
+
role: "supervisor" | "leg" | "disabled";
|
|
12
|
+
capabilities: { memory: 1 | false; activity: 1 | false };
|
|
13
|
+
}
|
|
14
|
+
export type PersonaDependency = { ok: true; presence: PersonaPresence } | { ok: false; reason: string };
|
|
15
|
+
export interface PersonaMemoryOwner { version: 1; provider: "pi-persona"; sessionId: string; ready: boolean; persona: string | null }
|
|
16
|
+
export function parsePersonaMemoryOwner(value: unknown, sessionId: string): PersonaMemoryOwner | undefined {
|
|
17
|
+
try {
|
|
18
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
19
|
+
const row = value as Record<string, unknown>;
|
|
20
|
+
if (Reflect.ownKeys(row).some((key) => !["version", "provider", "sessionId", "ready", "persona"].includes(String(key)))) return undefined;
|
|
21
|
+
if (row.version !== 1 || row.provider !== "pi-persona" || row.sessionId !== sessionId || typeof row.ready !== "boolean" || (row.persona !== null && (typeof row.persona !== "string" || !row.persona.trim() || row.persona.length > 1024))) return undefined;
|
|
22
|
+
return { version: 1, provider: "pi-persona", sessionId, ready: row.ready, persona: row.persona as string | null };
|
|
23
|
+
} catch { return undefined; }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function queryPersonaMemoryOwner(pi: Pick<ExtensionAPI, "events">, ctx: ExtensionContext): PersonaMemoryOwner | undefined {
|
|
27
|
+
try {
|
|
28
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
29
|
+
const responses: unknown[] = [];
|
|
30
|
+
let accepting = true;
|
|
31
|
+
try { pi.events.emit(PERSONA_MEMORY_OWNER_CHANNEL, { version: 1, sessionId, respond: (owner: unknown) => { if (accepting) responses.push(owner); } }); }
|
|
32
|
+
finally { accepting = false; }
|
|
33
|
+
return responses.length === 1 ? parsePersonaMemoryOwner(responses[0], sessionId) : undefined;
|
|
34
|
+
} catch { return undefined; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function validPresence(value: unknown): value is PersonaPresence {
|
|
38
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
39
|
+
const row = value as Record<string, unknown>;
|
|
40
|
+
if (Object.keys(row).some((key) => !["version", "provider", "role", "capabilities"].includes(key))) return false;
|
|
41
|
+
if (row.version !== 1 || row.provider !== "pi-persona" || typeof row.role !== "string" || !["supervisor", "leg", "disabled"].includes(row.role)) return false;
|
|
42
|
+
if (!row.capabilities || typeof row.capabilities !== "object" || Array.isArray(row.capabilities)) return false;
|
|
43
|
+
const caps = row.capabilities as Record<string, unknown>;
|
|
44
|
+
if (Object.keys(caps).some((key) => key !== "memory" && key !== "activity")) return false;
|
|
45
|
+
if ((caps.memory !== 1 && caps.memory !== false) || (caps.activity !== 1 && caps.activity !== false)) return false;
|
|
46
|
+
return row.role === "supervisor" ? caps.memory === 1 && caps.activity === 1
|
|
47
|
+
: row.role === "leg" ? caps.memory === 1 && caps.activity === false
|
|
48
|
+
: caps.memory === false && caps.activity === false;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function queryPersonaDependency(pi: Pick<ExtensionAPI, "events">): PersonaDependency {
|
|
52
|
+
const responses: unknown[] = [];
|
|
53
|
+
let accepting = true;
|
|
54
|
+
try { pi.events.emit(PERSONA_COMPANION_CHANNEL, { version: 1, respond: (presence: unknown) => { if (accepting) responses.push(presence); } }); }
|
|
55
|
+
catch { return { ok: false, reason: PERSONA_REQUIRED_REASON }; }
|
|
56
|
+
finally { accepting = false; }
|
|
57
|
+
try {
|
|
58
|
+
if (responses.length !== 1 || !validPresence(responses[0]) || responses[0].capabilities.memory !== 1) return { ok: false, reason: PERSONA_REQUIRED_REASON };
|
|
59
|
+
return { ok: true, presence: structuredClone(responses[0]) };
|
|
60
|
+
} catch { return { ok: false, reason: PERSONA_REQUIRED_REASON }; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Active tool selection is discovery only; this wrapper also guards direct programmatic execution. */
|
|
64
|
+
export function personaGuardedTools(pi: ExtensionAPI, unavailableReason: (ctx: ExtensionContext) => string | undefined): ExtensionAPI {
|
|
65
|
+
const guarded = Object.create(pi) as ExtensionAPI;
|
|
66
|
+
guarded.registerTool = (definition) => pi.registerTool({
|
|
67
|
+
...definition,
|
|
68
|
+
async execute(...args) {
|
|
69
|
+
const reason = unavailableReason(args[4]);
|
|
70
|
+
// Pi converts thrown tool errors to its native error result, also for executeTool().
|
|
71
|
+
if (reason) throw new Error(reason);
|
|
72
|
+
return definition.execute(...args);
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
return guarded;
|
|
76
|
+
}
|