@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
package/src/index.ts
ADDED
|
@@ -0,0 +1,1231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-persona-mind — a durable, persona-aware mind for Pi supervisors.
|
|
3
|
+
*
|
|
4
|
+
* Wires the two agent-facing tools (memory, backlog), injects the deterministic <persona-mind>
|
|
5
|
+
* block into the system prompt every turn (so memory survives compaction + restart), re-arms
|
|
6
|
+
* durable backlog wake timers on session start AND surfaces any that came due while offline as a
|
|
7
|
+
* collapsed, display-only transcript card (never a follow-up that starts a turn), and
|
|
8
|
+
* offers `/persona-mind` (`/mind` alias) for snapshots, session notes, diagnostics, and reviewed
|
|
9
|
+
* optimization. All heavy lifting lives in the pure core.
|
|
10
|
+
* A compatible loaded pi-persona supplies the live memory owner; no selected persona uses `_default`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { closeSync, existsSync, fstatSync, lstatSync, openSync, readSync, unlinkSync, writeSync } from "node:fs";
|
|
14
|
+
import { hostname } from "node:os";
|
|
15
|
+
import { join } from "node:path";
|
|
16
|
+
|
|
17
|
+
import { getAgentDir, VERSION } from "@earendil-works/pi-coding-agent";
|
|
18
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
19
|
+
|
|
20
|
+
import { detectBlockedLeg } from "./core/blocked.ts";
|
|
21
|
+
import { detectCaptureCues, type CaptureCue } from "./core/capture.ts";
|
|
22
|
+
import { EMPTY_HINT_PREFIX } from "./core/inject.ts";
|
|
23
|
+
import { isSupportedPiVersion, MIN_PI_VERSION } from "./core/host-compat.ts";
|
|
24
|
+
import { compactMemoryText } from "./core/memory.ts";
|
|
25
|
+
import { migrateCurrentScopeAliases, migrateLegacyRoot, type MigrationReport } from "./core/migrate.ts";
|
|
26
|
+
import { preferredAgentDir, resolveScope } from "./core/scope.ts";
|
|
27
|
+
import { resetMindSettings, resolveMindSettings } from "./core/mind-settings.ts";
|
|
28
|
+
import { MindService } from "./core/service.ts";
|
|
29
|
+
import { registerBacklogTool } from "./tools/backlog.ts";
|
|
30
|
+
import { registerMemoryTool } from "./tools/memory.ts";
|
|
31
|
+
import { renderExpandableCard } from "./ui/presentation.ts";
|
|
32
|
+
import { createSessionMemory } from "./session-memory.ts";
|
|
33
|
+
import { registerSessionNoteRenderer } from "./ui/session-note-card.ts";
|
|
34
|
+
import type { MemoryOptimizer } from "./core/optimize-service.ts";
|
|
35
|
+
import { registerMindCommands } from "./extension/mind-command.ts";
|
|
36
|
+
import { MIND_RESULT_ENTRY_TYPE, registerMindResultRenderer } from "./ui/mind-result-card.ts";
|
|
37
|
+
import { parsePersonaMemoryOwner, PERSONA_MEMORY_OWNER_CHANGED, personaGuardedTools, queryPersonaDependency, queryPersonaMemoryOwner } from "./extension/persona-dependency.ts";
|
|
38
|
+
import { createMindActivityRunner } from "./extension/activity.ts";
|
|
39
|
+
import { installAutoOptimize } from "./extension/auto-optimize-session.ts";
|
|
40
|
+
|
|
41
|
+
const STATUS_KEY = "pi-persona-mind";
|
|
42
|
+
/** Display-only transcript card for a due backlog wake. Never sent to the model; never starts a turn. */
|
|
43
|
+
const WAKE_ENTRY_TYPE = "pi-persona-mind-wake";
|
|
44
|
+
/** A stalled read must never freeze a turn: injection degrades to nothing past this deadline. */
|
|
45
|
+
const INJECT_DEADLINE_MS = 750;
|
|
46
|
+
const MIGRATION_AWAIT_MS = 100;
|
|
47
|
+
const MAX_TIMER_DELAY_MS = 2_147_000_000;
|
|
48
|
+
const MAX_WAKE_REMINDERS = 20;
|
|
49
|
+
const MAX_WAKE_TEXT_CHARS = 200;
|
|
50
|
+
const MAX_WAKE_OWNER_BYTES = 1024;
|
|
51
|
+
type WakeState = Awaited<ReturnType<MindService["backlogList"]>>;
|
|
52
|
+
// Unique per extension instance (not just per process): two instances in one process must not both
|
|
53
|
+
// believe they own the wake lock. Date/random are fine in the real runtime (unlike workflow scripts).
|
|
54
|
+
let ownerInstanceSeq = 0;
|
|
55
|
+
|
|
56
|
+
export { isSupportedPiVersion } from "./core/host-compat.ts";
|
|
57
|
+
|
|
58
|
+
export interface ExtensionOptions {
|
|
59
|
+
/** Override the agent dir (tests). Defaults to Pi's getAgentDir(). */
|
|
60
|
+
agentDir?: string;
|
|
61
|
+
/** Maximum time lifecycle hooks wait for migration; the migration continues in the background. */
|
|
62
|
+
migrationAwaitMs?: number;
|
|
63
|
+
/** Injectable timer ceiling for testing long wake delays. */
|
|
64
|
+
wakeTimerMaxDelayMs?: number;
|
|
65
|
+
/** Narrow lifecycle seam for deterministic wake read/race tests. */
|
|
66
|
+
wakeStateReader?: (mind: MindService) => Promise<WakeState>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isAlive(pid: number): boolean {
|
|
70
|
+
try {
|
|
71
|
+
process.kill(pid, 0);
|
|
72
|
+
return true;
|
|
73
|
+
} catch (err) {
|
|
74
|
+
return (err as NodeJS.ErrnoException).code !== "ESRCH";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type WakeOwnerRead =
|
|
79
|
+
| { status: "ok"; token: string }
|
|
80
|
+
| { status: "missing" | "unreadable" | "nonregular" | "oversized" };
|
|
81
|
+
|
|
82
|
+
/** Read only a tiny, regular wake-owner file; owner locks are coordination metadata, not a data file. */
|
|
83
|
+
function readWakeOwner(path: string): WakeOwnerRead {
|
|
84
|
+
let fd: number | undefined;
|
|
85
|
+
try {
|
|
86
|
+
const linkStat = lstatSync(path);
|
|
87
|
+
if (linkStat.isSymbolicLink() || !linkStat.isFile()) return { status: "nonregular" };
|
|
88
|
+
fd = openSync(path, "r");
|
|
89
|
+
if (!fstatSync(fd).isFile()) return { status: "nonregular" };
|
|
90
|
+
const bytes = Buffer.allocUnsafe(MAX_WAKE_OWNER_BYTES + 1);
|
|
91
|
+
const length = readSync(fd, bytes, 0, bytes.length, 0);
|
|
92
|
+
if (length > MAX_WAKE_OWNER_BYTES) return { status: "oversized" };
|
|
93
|
+
return { status: "ok", token: bytes.subarray(0, length).toString("utf8") };
|
|
94
|
+
} catch (err) {
|
|
95
|
+
return { status: (err as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable" };
|
|
96
|
+
} finally {
|
|
97
|
+
if (fd !== undefined) {
|
|
98
|
+
try {
|
|
99
|
+
closeSync(fd);
|
|
100
|
+
} catch {
|
|
101
|
+
/* raced close */
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function ownerIsStale(path: string, token: string): boolean {
|
|
108
|
+
const owner = readWakeOwner(path);
|
|
109
|
+
if (owner.status === "missing") return true;
|
|
110
|
+
if (owner.status !== "ok") return false;
|
|
111
|
+
try {
|
|
112
|
+
const content = owner.token;
|
|
113
|
+
if (content === token) return false; // ours
|
|
114
|
+
const colon = content.indexOf(":");
|
|
115
|
+
const host = colon < 0 ? "" : content.slice(0, colon);
|
|
116
|
+
const pid = colon < 0 ? NaN : Number.parseInt(content.slice(colon + 1), 10);
|
|
117
|
+
if (host === hostname() && Number.isInteger(pid) && pid > 0) {
|
|
118
|
+
// A LOCAL owner: stale iff its process is gone. Never time-steal a LIVE local owner — that is
|
|
119
|
+
// the >120s double-fire (a second session opened later in the same project would steal the
|
|
120
|
+
// still-alive owner's lock and both would then fire the same backlog wakes).
|
|
121
|
+
return !isAlive(pid);
|
|
122
|
+
}
|
|
123
|
+
// Foreign host / unparseable token cannot be proven dead. Fail closed: time-stealing a live
|
|
124
|
+
// foreign owner can make two sessions deliver the same wake. Manual cleanup is safer.
|
|
125
|
+
return false;
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Non-blocking claim of the per-project wake-firer lock. Only the owner arms/fires wakes. */
|
|
132
|
+
function claimWakeOwner(path: string, token: string): boolean {
|
|
133
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
134
|
+
let fd: number | undefined;
|
|
135
|
+
let created = false;
|
|
136
|
+
let createError: unknown;
|
|
137
|
+
try {
|
|
138
|
+
fd = openSync(path, "wx");
|
|
139
|
+
created = true;
|
|
140
|
+
writeSync(fd, token);
|
|
141
|
+
} catch (err) {
|
|
142
|
+
createError = err;
|
|
143
|
+
} finally {
|
|
144
|
+
if (fd !== undefined) {
|
|
145
|
+
try {
|
|
146
|
+
closeSync(fd);
|
|
147
|
+
} catch {
|
|
148
|
+
/* best effort; the create error remains authoritative */
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (created && createError !== undefined) {
|
|
153
|
+
// A failed write can strand an empty file. Remove it only while it is still empty; a
|
|
154
|
+
// non-empty replacement may belong to a racing claimant and must be left untouched.
|
|
155
|
+
const current = readWakeOwner(path);
|
|
156
|
+
if (current.status === "ok" && current.token === "") {
|
|
157
|
+
try {
|
|
158
|
+
unlinkSync(path);
|
|
159
|
+
} catch {
|
|
160
|
+
/* raced */
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
if (created) {
|
|
166
|
+
// Confirm our token actually stuck: a racing stealer's unlink+recreate could have replaced
|
|
167
|
+
// it between our create and now. If the lock isn't ours, we do NOT own the wakes — retry.
|
|
168
|
+
const current = readWakeOwner(path);
|
|
169
|
+
if (current.status === "ok" && current.token === token) return true;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if ((createError as NodeJS.ErrnoException | undefined)?.code !== "EEXIST") return false;
|
|
173
|
+
const current = readWakeOwner(path);
|
|
174
|
+
if (current.status === "ok" && current.token === token) return true; // re-claim ours
|
|
175
|
+
if (!ownerIsStale(path, token)) return false; // a live holder owns it
|
|
176
|
+
try {
|
|
177
|
+
unlinkSync(path);
|
|
178
|
+
} catch {
|
|
179
|
+
/* raced */
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Explain an owner lock that cannot be safely claimed; live local owners remain quiet by design. */
|
|
186
|
+
function wakeOwnerWarning(path: string, token: string): string | undefined {
|
|
187
|
+
const owner = readWakeOwner(path);
|
|
188
|
+
if (owner.status === "missing") return undefined;
|
|
189
|
+
if (owner.status === "oversized") return "wake owner lock is oversized; wakes are suppressed until it is removed (see /mind doctor)";
|
|
190
|
+
if (owner.status !== "ok") return "wake owner lock is unreadable or non-regular; wakes are suppressed until it is removed (see /mind doctor)";
|
|
191
|
+
const content = owner.token;
|
|
192
|
+
if (!content) {
|
|
193
|
+
return "wake owner lock is malformed; wakes are suppressed until it is removed (see /mind doctor)";
|
|
194
|
+
}
|
|
195
|
+
if (content === token) return undefined;
|
|
196
|
+
const fields = content.split(":");
|
|
197
|
+
const pid = fields.length === 3 ? Number.parseInt(fields[1] ?? "", 10) : NaN;
|
|
198
|
+
if (fields.length !== 3 || !fields[0] || !Number.isInteger(pid) || pid <= 0 || !fields[2]) {
|
|
199
|
+
return "wake owner lock is malformed; wakes are suppressed until it is removed (see /mind doctor)";
|
|
200
|
+
}
|
|
201
|
+
if (fields[0] !== hostname()) {
|
|
202
|
+
const safeHost = fields[0].replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64) || "unknown";
|
|
203
|
+
return `wake owner lock belongs to foreign host '${safeHost}'; wakes are suppressed until it is removed (see /mind doctor)`;
|
|
204
|
+
}
|
|
205
|
+
return undefined;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function withDeadline<T>(p: Promise<T>, ms: number, fallback: T, onTimeout?: () => void): Promise<T> {
|
|
209
|
+
return new Promise<T>((resolve, reject) => {
|
|
210
|
+
let settled = false;
|
|
211
|
+
const timer = setTimeout(() => {
|
|
212
|
+
if (settled) return;
|
|
213
|
+
settled = true;
|
|
214
|
+
onTimeout?.();
|
|
215
|
+
resolve(fallback);
|
|
216
|
+
}, ms);
|
|
217
|
+
timer.unref?.();
|
|
218
|
+
void p.then(
|
|
219
|
+
(value) => {
|
|
220
|
+
if (settled) return;
|
|
221
|
+
settled = true;
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
resolve(value);
|
|
224
|
+
},
|
|
225
|
+
(err: unknown) => {
|
|
226
|
+
if (settled) return;
|
|
227
|
+
settled = true;
|
|
228
|
+
clearTimeout(timer);
|
|
229
|
+
reject(err);
|
|
230
|
+
},
|
|
231
|
+
);
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Build the extension. Exported (separately from the default factory) so tests can inject agentDir. */
|
|
236
|
+
export function createExtension(pi: ExtensionAPI, opts: ExtensionOptions = {}): void {
|
|
237
|
+
// Do not touch the host API when loaded by a Pi release below the supported contract floor.
|
|
238
|
+
if (!isSupportedPiVersion(VERSION)) throw new Error(`pi-persona-mind requires Pi ${MIN_PI_VERSION}+ (found ${VERSION}).`);
|
|
239
|
+
// Mirror pi-persona's own PI_AGENT_DIR precedence so both extensions co-locate their data (and the
|
|
240
|
+
// Mind reads canonical preferences from the same root). getAgentDir() stays lazy — only
|
|
241
|
+
// called when neither an explicit override (tests) nor PI_AGENT_DIR is set.
|
|
242
|
+
const agentDir = preferredAgentDir(opts.agentDir) ?? getAgentDir();
|
|
243
|
+
let capturePolicy: "auto" | "prompt" | "off" = "auto";
|
|
244
|
+
let nudgeEnabled = true;
|
|
245
|
+
let currentSessionContext: ExtensionContext | undefined;
|
|
246
|
+
const suspendedMindTools = new Set<string>();
|
|
247
|
+
let personaUnavailable = false;
|
|
248
|
+
let onPersonaUnavailable = (_ctx?: ExtensionContext): void => {};
|
|
249
|
+
const unavailableReason = (ctx = currentSessionContext): string | undefined => {
|
|
250
|
+
const dependency = queryPersonaDependency(pi);
|
|
251
|
+
if (!dependency.ok) onPersonaUnavailable(ctx);
|
|
252
|
+
if (!dependency.ok) return dependency.reason;
|
|
253
|
+
const owner = ctx ? queryPersonaMemoryOwner(pi, ctx) : undefined;
|
|
254
|
+
if (!owner?.ready) {
|
|
255
|
+
onPersonaUnavailable(ctx);
|
|
256
|
+
return owner ? "Mind is waiting for Persona's session memory owner." : "Mind is inactive: compatible pi-persona memory owner is unavailable; /reload.";
|
|
257
|
+
}
|
|
258
|
+
personaUnavailable = false;
|
|
259
|
+
return undefined;
|
|
260
|
+
};
|
|
261
|
+
const available = (ctx = currentSessionContext): boolean => unavailableReason(ctx) === undefined;
|
|
262
|
+
let settingsCollectUnsubscribe: (() => void) | undefined;
|
|
263
|
+
const sessionIdOf = (ctx: ExtensionContext): string => ctx.sessionManager.getSessionId();
|
|
264
|
+
const rawMindPersona = (ctx: ExtensionContext): string | null => {
|
|
265
|
+
const owner = queryPersonaMemoryOwner(pi, ctx);
|
|
266
|
+
if (!owner?.ready) throw new Error("Persona's session memory owner is unavailable");
|
|
267
|
+
return owner.persona;
|
|
268
|
+
};
|
|
269
|
+
const resolveMindScope = (ctx: ExtensionContext) => resolveScope(agentDir, ctx.cwd, { persona: rawMindPersona(ctx) });
|
|
270
|
+
const captureMemoryOwner = (ctx: ExtensionContext): (() => boolean) => {
|
|
271
|
+
const generation = sessionLifecycleGeneration;
|
|
272
|
+
const manager = ctx.sessionManager;
|
|
273
|
+
const id = manager.getSessionId();
|
|
274
|
+
const file = manager.getSessionFile();
|
|
275
|
+
const scope = JSON.stringify(resolveMindScope(ctx));
|
|
276
|
+
return () => {
|
|
277
|
+
try { return generation === sessionLifecycleGeneration && ctx.sessionManager === manager && manager.getSessionId() === id && manager.getSessionFile() === file && available(ctx) && scope === JSON.stringify(resolveMindScope(ctx)); }
|
|
278
|
+
catch { return false; }
|
|
279
|
+
};
|
|
280
|
+
};
|
|
281
|
+
const migrationWaitMs = Math.max(0, opts.migrationAwaitMs ?? MIGRATION_AWAIT_MS);
|
|
282
|
+
const wakeTimerMaxDelayMs = Math.min(MAX_TIMER_DELAY_MS, Math.max(1, opts.wakeTimerMaxDelayMs ?? MAX_TIMER_DELAY_MS));
|
|
283
|
+
const ownerToken = `${hostname()}:${process.pid}:${++ownerInstanceSeq}`;
|
|
284
|
+
const warnings = new Set<string>();
|
|
285
|
+
let warningStatusActive = false;
|
|
286
|
+
const setStatus = (ctx: ExtensionContext, value: string, color: "warning" | "dim" | "accent" = "dim"): void => {
|
|
287
|
+
try {
|
|
288
|
+
ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg(color, value) : value);
|
|
289
|
+
} catch {
|
|
290
|
+
/* cosmetic */
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const surfaceWarning = (ctx: ExtensionContext, message: string): void => {
|
|
294
|
+
if (warnings.has(message)) return;
|
|
295
|
+
warnings.add(message);
|
|
296
|
+
warningStatusActive = true;
|
|
297
|
+
try {
|
|
298
|
+
ctx.ui.notify(`[pi-persona-mind] ${message}`, "warning");
|
|
299
|
+
} catch {
|
|
300
|
+
/* a diagnostic must not break the host */
|
|
301
|
+
}
|
|
302
|
+
setStatus(ctx, "mind warning · /mind doctor", "warning");
|
|
303
|
+
};
|
|
304
|
+
const getMind = (ctx: ExtensionContext): MindService => {
|
|
305
|
+
const reason = unavailableReason(ctx);
|
|
306
|
+
if (reason) throw new Error(reason);
|
|
307
|
+
return new MindService(resolveMindScope(ctx), { onWarn: (message) => surfaceWarning(ctx, message) });
|
|
308
|
+
};
|
|
309
|
+
const sessionMemory = createSessionMemory(pi);
|
|
310
|
+
registerSessionNoteRenderer(pi);
|
|
311
|
+
registerMindResultRenderer(pi);
|
|
312
|
+
let optimizerCache: { manager: ExtensionContext["sessionManager"]; key: string; optimizer: MemoryOptimizer } | undefined;
|
|
313
|
+
const discardOptimizer = (): void => {
|
|
314
|
+
optimizerCache?.optimizer.invalidate();
|
|
315
|
+
optimizerCache = undefined;
|
|
316
|
+
};
|
|
317
|
+
const getOptimizer = (ctx: ExtensionContext): MemoryOptimizer => {
|
|
318
|
+
if (!sessionMemory.isCurrent(ctx)) throw new Error("memory optimizer session owner is unavailable");
|
|
319
|
+
const mind = getMind(ctx);
|
|
320
|
+
const scope = resolveMindScope(ctx);
|
|
321
|
+
const key = JSON.stringify([ctx.sessionManager.getSessionId(), ctx.sessionManager.getSessionFile(), scope.persona, scope.paths]);
|
|
322
|
+
if (optimizerCache?.manager === ctx.sessionManager && optimizerCache.key === key) return optimizerCache.optimizer;
|
|
323
|
+
discardOptimizer();
|
|
324
|
+
const optimizer = mind.createOptimizer();
|
|
325
|
+
optimizerCache = { manager: ctx.sessionManager, key, optimizer };
|
|
326
|
+
return optimizer;
|
|
327
|
+
};
|
|
328
|
+
const getActivity = (ctx: ExtensionContext) => {
|
|
329
|
+
const ownerCurrent = sessionMemory.captureOwner(ctx);
|
|
330
|
+
const scopeKey = JSON.stringify(resolveMindScope(ctx));
|
|
331
|
+
return createMindActivityRunner({
|
|
332
|
+
sessionId: ctx.sessionManager.getSessionId(),
|
|
333
|
+
isCurrent: () => ownerCurrent() && scopeKey === JSON.stringify(resolveMindScope(ctx)),
|
|
334
|
+
enabled: () => { const dependency = queryPersonaDependency(pi); return dependency.ok && dependency.presence.capabilities.activity === 1; },
|
|
335
|
+
emit: (channel, event) => pi.events.emit(channel, event),
|
|
336
|
+
});
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
pi.registerEntryRenderer<{ content: string }>(WAKE_ENTRY_TYPE, (entry, { expanded }, theme) => {
|
|
340
|
+
const body = typeof entry.data?.content === "string" ? entry.data.content : "";
|
|
341
|
+
return renderExpandableCard("pi-persona-mind", body, expanded, theme);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
/** Human-visible due reminder: toast + collapsed card. Must never sendUserMessage / triggerTurn. */
|
|
345
|
+
const deliverWake = (ctx: ExtensionContext, body: string): void => {
|
|
346
|
+
const first = body.split("\n", 1)[0] ?? body;
|
|
347
|
+
const toast = first.length > 160 ? `${first.slice(0, 159)}…` : first;
|
|
348
|
+
try {
|
|
349
|
+
ctx.ui.notify(`[pi-persona-mind] ${toast}`, "info");
|
|
350
|
+
} catch {
|
|
351
|
+
/* headless / no UI */
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
pi.appendEntry(WAKE_ENTRY_TYPE, { content: body });
|
|
355
|
+
} catch {
|
|
356
|
+
/* host without transcript entries */
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
let rootMigration: Promise<MigrationReport> | undefined;
|
|
360
|
+
let backgroundMigration: Promise<MigrationReport> | undefined;
|
|
361
|
+
let backgroundMigrationKey: string | undefined;
|
|
362
|
+
let backgroundMigrationPending = false;
|
|
363
|
+
let backgroundMigrationWarnings = 0;
|
|
364
|
+
let backgroundMigrationFailure: string | undefined;
|
|
365
|
+
let observedMigration: Promise<MigrationReport> | undefined;
|
|
366
|
+
let observedMigrationGeneration = -1;
|
|
367
|
+
const migrationProgressNotices = new WeakSet<Promise<MigrationReport>>();
|
|
368
|
+
const aliasMigrations = new Map<string, Promise<MigrationReport>>();
|
|
369
|
+
let migrationNoticeShown = false;
|
|
370
|
+
let migrationGeneration = 0;
|
|
371
|
+
let sessionActive = false;
|
|
372
|
+
let sessionStarting = false;
|
|
373
|
+
let lastArmedMigrationGeneration = 0;
|
|
374
|
+
|
|
375
|
+
const mergeReports = (a: MigrationReport, b: MigrationReport): MigrationReport => ({
|
|
376
|
+
filesScanned: a.filesScanned + b.filesScanned,
|
|
377
|
+
filesSkipped: a.filesSkipped + b.filesSkipped,
|
|
378
|
+
filesMigrated: a.filesMigrated + b.filesMigrated,
|
|
379
|
+
entriesSeen: a.entriesSeen + b.entriesSeen,
|
|
380
|
+
entriesAdded: a.entriesAdded + b.entriesAdded,
|
|
381
|
+
conflicts: a.conflicts + b.conflicts,
|
|
382
|
+
invalidEntries: a.invalidEntries + b.invalidEntries,
|
|
383
|
+
warnings: [...a.warnings, ...b.warnings],
|
|
384
|
+
});
|
|
385
|
+
const reportMigration = (ctx: ExtensionContext, report: MigrationReport): void => {
|
|
386
|
+
if (report.warnings.length === 1) surfaceWarning(ctx, report.warnings[0] ?? "legacy memory migration reported a warning");
|
|
387
|
+
else if (report.warnings.length > 1) {
|
|
388
|
+
const shown = report.warnings.slice(0, 4).join(" | ");
|
|
389
|
+
surfaceWarning(ctx, `legacy memory migration reported ${report.warnings.length} warnings: ${shown}${report.warnings.length > 4 ? ` | +${report.warnings.length - 4} more` : ""}`);
|
|
390
|
+
}
|
|
391
|
+
if (report.entriesAdded > 0 && !migrationNoticeShown) {
|
|
392
|
+
migrationNoticeShown = true;
|
|
393
|
+
try {
|
|
394
|
+
ctx.ui.notify(
|
|
395
|
+
`[pi-persona-mind] Imported/reconciled ${report.entriesAdded} stored entr${report.entriesAdded === 1 ? "y" : "ies"} from legacy scope paths; source files were left untouched.`,
|
|
396
|
+
"info",
|
|
397
|
+
);
|
|
398
|
+
} catch {
|
|
399
|
+
/* headless/no UI */
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const runMigration = async (ctx: ExtensionContext, includeAmbiguousPersonaAlias: boolean): Promise<MigrationReport> => {
|
|
404
|
+
const scope = resolveMindScope(ctx);
|
|
405
|
+
const rawPersona = rawMindPersona(ctx);
|
|
406
|
+
// Scope belongs to the operation that started the import, even if a root import blocks.
|
|
407
|
+
const rootReport = await (rootMigration ??= migrateLegacyRoot(agentDir));
|
|
408
|
+
const aliasKey = JSON.stringify([rawPersona, scope.projectRoot, includeAmbiguousPersonaAlias]);
|
|
409
|
+
let aliasPromise = aliasMigrations.get(aliasKey);
|
|
410
|
+
if (!aliasPromise) {
|
|
411
|
+
aliasPromise = migrateCurrentScopeAliases(agentDir, rawPersona, scope.projectRoot, { includeAmbiguousPersonaAlias });
|
|
412
|
+
aliasMigrations.set(aliasKey, aliasPromise);
|
|
413
|
+
}
|
|
414
|
+
return mergeReports(rootReport, await aliasPromise);
|
|
415
|
+
};
|
|
416
|
+
const rearmAfterMigration = (ctx: ExtensionContext): void => {
|
|
417
|
+
if (!sessionActive || sessionStarting || migrationGeneration <= lastArmedMigrationGeneration) return;
|
|
418
|
+
const scope = resolveMindScope(ctx);
|
|
419
|
+
if (activeScopeKey !== JSON.stringify([scope.persona, scope.projectRoot])) return;
|
|
420
|
+
void (async () => {
|
|
421
|
+
try {
|
|
422
|
+
await armWakes(ctx);
|
|
423
|
+
lastArmedMigrationGeneration = migrationGeneration;
|
|
424
|
+
await refreshStatus(ctx);
|
|
425
|
+
} catch (err) {
|
|
426
|
+
surfaceWarning(ctx, `could not refresh after memory migration: ${err instanceof Error ? err.message : String(err)}`);
|
|
427
|
+
}
|
|
428
|
+
})();
|
|
429
|
+
};
|
|
430
|
+
const migrationKey = (ctx: ExtensionContext): string => JSON.stringify([rawMindPersona(ctx), resolveMindScope(ctx).projectRoot]);
|
|
431
|
+
const migrationStatus = (): string => backgroundMigrationPending
|
|
432
|
+
? "running in background; existing stores remain available, older imported entries may appear later"
|
|
433
|
+
: backgroundMigrationFailure ? `failed: ${backgroundMigrationFailure}; /reload retries the legacy import`
|
|
434
|
+
: backgroundMigrationWarnings > 0 ? `completed with ${backgroundMigrationWarnings} warning(s); source files kept, see warnings below; /reload rechecks legacy sources`
|
|
435
|
+
: backgroundMigration ? "complete; legacy source files kept" : "not started";
|
|
436
|
+
const observeMigration = (ctx: ExtensionContext, task: Promise<MigrationReport>, key: string): void => {
|
|
437
|
+
const generation = sessionLifecycleGeneration;
|
|
438
|
+
if (observedMigration === task && observedMigrationGeneration === generation) return;
|
|
439
|
+
observedMigration = task;
|
|
440
|
+
observedMigrationGeneration = generation;
|
|
441
|
+
const current = (): boolean => generation === sessionLifecycleGeneration && available(ctx) && migrationKey(ctx) === key;
|
|
442
|
+
void task.then((report) => {
|
|
443
|
+
if (!current()) return;
|
|
444
|
+
reportMigration(ctx, report);
|
|
445
|
+
rearmAfterMigration(ctx);
|
|
446
|
+
}, (err: unknown) => {
|
|
447
|
+
if (current()) surfaceWarning(ctx, `legacy memory import failed; /reload retries it: ${err instanceof Error ? err.message : String(err)}`);
|
|
448
|
+
}).catch((err: unknown) => {
|
|
449
|
+
if (current()) surfaceWarning(ctx, `legacy memory import finished but its status could not refresh: ${err instanceof Error ? err.message : String(err)}`);
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
const startBackgroundMigration = (ctx: ExtensionContext): Promise<MigrationReport> => {
|
|
453
|
+
const key = migrationKey(ctx);
|
|
454
|
+
if (backgroundMigration && backgroundMigrationKey === key) {
|
|
455
|
+
observeMigration(ctx, backgroundMigration, key);
|
|
456
|
+
return backgroundMigration;
|
|
457
|
+
}
|
|
458
|
+
const task = runMigration(ctx, false);
|
|
459
|
+
backgroundMigration = task;
|
|
460
|
+
backgroundMigrationKey = key;
|
|
461
|
+
backgroundMigrationPending = true;
|
|
462
|
+
backgroundMigrationWarnings = 0;
|
|
463
|
+
backgroundMigrationFailure = undefined;
|
|
464
|
+
void task.then(
|
|
465
|
+
(report) => {
|
|
466
|
+
if (backgroundMigration !== task) return;
|
|
467
|
+
backgroundMigrationPending = false;
|
|
468
|
+
backgroundMigrationWarnings = report.warnings.length;
|
|
469
|
+
migrationGeneration++;
|
|
470
|
+
},
|
|
471
|
+
(err: unknown) => {
|
|
472
|
+
if (backgroundMigration !== task) return;
|
|
473
|
+
backgroundMigrationPending = false;
|
|
474
|
+
backgroundMigrationFailure = err instanceof Error ? err.message : String(err);
|
|
475
|
+
backgroundMigration = undefined;
|
|
476
|
+
backgroundMigrationKey = undefined;
|
|
477
|
+
rootMigration = undefined;
|
|
478
|
+
aliasMigrations.clear();
|
|
479
|
+
},
|
|
480
|
+
);
|
|
481
|
+
observeMigration(ctx, task, key);
|
|
482
|
+
return task;
|
|
483
|
+
};
|
|
484
|
+
const ensureLegacyMigrated = async (ctx: ExtensionContext, includeAmbiguousPersonaAlias = false, awaitCompletion = false): Promise<void> => {
|
|
485
|
+
if (isDelegatedLeg || !available(ctx)) return;
|
|
486
|
+
const generation = sessionLifecycleGeneration;
|
|
487
|
+
const key = migrationKey(ctx);
|
|
488
|
+
const current = (): boolean => generation === sessionLifecycleGeneration && available(ctx) && migrationKey(ctx) === key;
|
|
489
|
+
const task = includeAmbiguousPersonaAlias ? runMigration(ctx, true) : startBackgroundMigration(ctx);
|
|
490
|
+
try {
|
|
491
|
+
if (includeAmbiguousPersonaAlias || awaitCompletion) {
|
|
492
|
+
const report = await task;
|
|
493
|
+
if (current()) reportMigration(ctx, report);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
await withDeadline(task, migrationWaitMs, undefined, () => {
|
|
497
|
+
if (!current() || !backgroundMigrationPending) return;
|
|
498
|
+
if (!migrationProgressNotices.has(task)) {
|
|
499
|
+
migrationProgressNotices.add(task);
|
|
500
|
+
try { ctx.ui.notify("[pi-persona-mind] Legacy memory import continues in the background. This turn can proceed; older entries may appear after import finishes. /persona-mind doctor shows its status.", "info"); }
|
|
501
|
+
catch { /* Progress cannot interrupt the turn. */ }
|
|
502
|
+
}
|
|
503
|
+
if (!warningStatusActive) setStatus(ctx, "mind importing older memory · /persona-mind doctor");
|
|
504
|
+
});
|
|
505
|
+
} catch (err) {
|
|
506
|
+
if (!includeAmbiguousPersonaAlias && backgroundMigration === task) {
|
|
507
|
+
backgroundMigration = undefined;
|
|
508
|
+
backgroundMigrationKey = undefined;
|
|
509
|
+
}
|
|
510
|
+
if (includeAmbiguousPersonaAlias) { rootMigration = undefined; aliasMigrations.clear(); }
|
|
511
|
+
if (current()) surfaceWarning(ctx, `legacy memory import failed; /reload retries it: ${err instanceof Error ? err.message : String(err)}`);
|
|
512
|
+
}
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
// Persona marks actual delegated worker legs with a dedicated marker,
|
|
516
|
+
// PI_PERSONA_LEG=1 — the in-process fork-bomb guard sets it transiently around session creation, and
|
|
517
|
+
// the child engine puts it in the spawn env (a child process also carries PI_PERSONA_CHILD=1). We key
|
|
518
|
+
// on those, NOT on PI_PERSONA_DISABLE: a disabled supervisor is not a delegated leg. The loaded
|
|
519
|
+
// Persona's companion response separately denies its memory capability. Sampled HERE at factory time
|
|
520
|
+
// (the in-process marker is popped
|
|
521
|
+
// before the turn runs). A worker is not the persona: it inherits only the lean mind (north-star +
|
|
522
|
+
// identity — see buildInjection) and must NOT manage the supervisor's memory or fire its wakes. Absent
|
|
523
|
+
// the markers, only a compatible, enabled supervisor may use the full mind.
|
|
524
|
+
const isDelegatedLeg = process.env.PI_PERSONA_LEG === "1" || process.env.PI_PERSONA_CHILD === "1";
|
|
525
|
+
const autoOptimize = installAutoOptimize(pi, { isDelegatedLeg, available, captureOwner: captureMemoryOwner, scope: resolveMindScope, persona: rawMindPersona, mind: getMind });
|
|
526
|
+
|
|
527
|
+
// Withhold the write tools from a worker: a leg reading/writing the supervisor persona's LTM/STM/
|
|
528
|
+
// backlog is exactly the bleed we prevent. It still INHERITS the lean block below (read-only, curated).
|
|
529
|
+
if (!isDelegatedLeg) {
|
|
530
|
+
const guardedTools = personaGuardedTools(pi, unavailableReason);
|
|
531
|
+
registerMemoryTool(guardedTools, getMind, sessionMemory, getOptimizer, getActivity);
|
|
532
|
+
registerBacklogTool(guardedTools, getMind);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// Backlog wake timers — only the elected owner session arms/fires them, so concurrent sessions
|
|
536
|
+
// never double-deliver. In-memory, unref'd, re-armed from disk on session start; cleared on shutdown.
|
|
537
|
+
const timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
538
|
+
// Undelivered alarms outlive their timeout handles: a concurrent re-arm or slow store read
|
|
539
|
+
// must not turn a deadline that just passed into an ignored, apparently old overdue item.
|
|
540
|
+
const pendingWakeIds = new Set<string>();
|
|
541
|
+
// Keep the exact displayed deadline until a fresh snapshot observes its acknowledgement.
|
|
542
|
+
// An in-flight-only guard would miss a pre-ack snapshot that returns after the write settles.
|
|
543
|
+
const displayedWakeDeadlines = new Map<string, number>();
|
|
544
|
+
let ownerPath: string | undefined;
|
|
545
|
+
let wakeGeneration = 0;
|
|
546
|
+
const readWakeState = opts.wakeStateReader ?? ((mind: MindService): Promise<WakeState> => mind.backlogList({ all: true }));
|
|
547
|
+
const clearTimers = (preservePending = false): void => {
|
|
548
|
+
for (const t of timers.values()) clearTimeout(t);
|
|
549
|
+
timers.clear();
|
|
550
|
+
if (!preservePending) {
|
|
551
|
+
pendingWakeIds.clear();
|
|
552
|
+
displayedWakeDeadlines.clear();
|
|
553
|
+
}
|
|
554
|
+
};
|
|
555
|
+
const releaseWakeOwner = (): void => {
|
|
556
|
+
if (!ownerPath) return;
|
|
557
|
+
try {
|
|
558
|
+
const owner = readWakeOwner(ownerPath);
|
|
559
|
+
if (owner.status === "ok" && owner.token === ownerToken) unlinkSync(ownerPath);
|
|
560
|
+
} catch {
|
|
561
|
+
/* already released */
|
|
562
|
+
}
|
|
563
|
+
ownerPath = undefined;
|
|
564
|
+
};
|
|
565
|
+
onPersonaUnavailable = (ctx): void => {
|
|
566
|
+
// A stale context can be refused without revoking a different currently active native owner.
|
|
567
|
+
if (ctx && currentSessionContext && ctx.sessionManager !== currentSessionContext.sessionManager) return;
|
|
568
|
+
if (personaUnavailable) return;
|
|
569
|
+
personaUnavailable = true;
|
|
570
|
+
autoOptimize.revoke();
|
|
571
|
+
discardOptimizer();
|
|
572
|
+
sessionMemory.deactivate();
|
|
573
|
+
sessionActive = false;
|
|
574
|
+
sessionStarting = false;
|
|
575
|
+
wakeGeneration++;
|
|
576
|
+
clearTimers();
|
|
577
|
+
releaseWakeOwner();
|
|
578
|
+
settingsCollectUnsubscribe?.();
|
|
579
|
+
settingsCollectUnsubscribe = undefined;
|
|
580
|
+
const active = pi.getActiveTools();
|
|
581
|
+
for (const name of active) if (name === "memory" || name === "backlog") suspendedMindTools.add(name);
|
|
582
|
+
pi.setActiveTools(active.filter((name) => name !== "memory" && name !== "backlog"));
|
|
583
|
+
};
|
|
584
|
+
const wakeCurrent = (generation: number, path: string): boolean => available() && sessionActive && wakeGeneration === generation && ownerPath === path;
|
|
585
|
+
const armWakes = async (ctx: ExtensionContext, deliverPastDue = true, newlyQueuedId?: string): Promise<void> => {
|
|
586
|
+
if (!available(ctx)) return;
|
|
587
|
+
const generation = ++wakeGeneration;
|
|
588
|
+
if (newlyQueuedId) pendingWakeIds.add(newlyQueuedId);
|
|
589
|
+
clearTimers(true);
|
|
590
|
+
const scope = resolveMindScope(ctx);
|
|
591
|
+
if (scope.homeWorkspace) {
|
|
592
|
+
pendingWakeIds.clear();
|
|
593
|
+
displayedWakeDeadlines.clear();
|
|
594
|
+
releaseWakeOwner();
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
const nextOwnerPath = `${scope.paths.backlog}.wakeowner`;
|
|
598
|
+
ownerPath = nextOwnerPath;
|
|
599
|
+
if (!claimWakeOwner(nextOwnerPath, ownerToken)) {
|
|
600
|
+
const warning = wakeOwnerWarning(nextOwnerPath, ownerToken);
|
|
601
|
+
if (warning) surfaceWarning(ctx, warning);
|
|
602
|
+
if (wakeGeneration === generation && ownerPath === nextOwnerPath) ownerPath = undefined; // another live session owns the wakes; we still inject, just don't fire
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
const mind = getMind(ctx);
|
|
606
|
+
let all: Awaited<ReturnType<MindService["backlogList"]>>;
|
|
607
|
+
try {
|
|
608
|
+
all = await readWakeState(mind);
|
|
609
|
+
} catch (err) {
|
|
610
|
+
if (wakeCurrent(generation, nextOwnerPath)) {
|
|
611
|
+
surfaceWarning(ctx, `could not load backlog wake state: ${err instanceof Error ? err.message : String(err)}`);
|
|
612
|
+
}
|
|
613
|
+
if (wakeGeneration === generation && ownerPath === nextOwnerPath) releaseWakeOwner();
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const now = Date.now();
|
|
617
|
+
if (!wakeCurrent(generation, nextOwnerPath)) {
|
|
618
|
+
if (wakeGeneration === generation && ownerPath === nextOwnerPath) releaseWakeOwner();
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
// Deliver items that came due while offline as ONE combined reminder, instead of dropping them.
|
|
622
|
+
// Display-only: the mind is already injected on the next user turn; a follow-up would start the
|
|
623
|
+
// agent unprompted (it used to treat "Use backlog take" as an order to resume work).
|
|
624
|
+
const activeWakeDeadlines = new Map<string, number>();
|
|
625
|
+
for (const item of all) if (item.dueAtEpochMs !== undefined) activeWakeDeadlines.set(item.id, item.dueAtEpochMs);
|
|
626
|
+
for (const id of pendingWakeIds) if (!activeWakeDeadlines.has(id)) pendingWakeIds.delete(id);
|
|
627
|
+
for (const [id, deadline] of displayedWakeDeadlines) if (activeWakeDeadlines.get(id) !== deadline) displayedWakeDeadlines.delete(id);
|
|
628
|
+
const due = all.filter((item) => item.dueAtEpochMs !== undefined && item.dueAtEpochMs <= now && displayedWakeDeadlines.get(item.id) !== item.dueAtEpochMs && (deliverPastDue || pendingWakeIds.has(item.id)));
|
|
629
|
+
if (due.length > 0) {
|
|
630
|
+
try {
|
|
631
|
+
const shown = due.slice(0, MAX_WAKE_REMINDERS);
|
|
632
|
+
const list = shown.map((e) => `• ${compactMemoryText(e.text, MAX_WAKE_TEXT_CHARS)} (id ${e.id})`).join("\n");
|
|
633
|
+
const omitted = due.length - shown.length;
|
|
634
|
+
const more = omitted > 0 ? `\n… +${omitted} more due item(s); use \`backlog list\` to review them.` : "";
|
|
635
|
+
if (!wakeCurrent(generation, nextOwnerPath)) return;
|
|
636
|
+
for (const item of due) {
|
|
637
|
+
pendingWakeIds.delete(item.id);
|
|
638
|
+
if (item.dueAtEpochMs !== undefined) displayedWakeDeadlines.set(item.id, item.dueAtEpochMs);
|
|
639
|
+
}
|
|
640
|
+
const headline = deliverPastDue ? `${due.length} backlog item(s) came due while you were away:` : `backlog due — ${due.length} item(s):`;
|
|
641
|
+
deliverWake(
|
|
642
|
+
ctx,
|
|
643
|
+
`${headline}\n${list}${more}\nReview when ready — stale leads auto-remove after ~48h; keep durable facts in long-term memory.`,
|
|
644
|
+
);
|
|
645
|
+
await mind.acknowledgeDue(due.map((item) => item.id));
|
|
646
|
+
} catch {
|
|
647
|
+
/* raced shutdown */
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
// Schedule the future ones.
|
|
651
|
+
const scheduleWake = (item: (typeof all)[number], remainingMs: number): void => {
|
|
652
|
+
if (!wakeCurrent(generation, nextOwnerPath)) return;
|
|
653
|
+
pendingWakeIds.add(item.id);
|
|
654
|
+
const delay = Math.min(Math.max(1, remainingMs), wakeTimerMaxDelayMs);
|
|
655
|
+
const t = setTimeout(() => {
|
|
656
|
+
if (!wakeCurrent(generation, nextOwnerPath)) return;
|
|
657
|
+
timers.delete(item.id);
|
|
658
|
+
// Re-check at every chunk. This avoids Node's ~24.8-day timer overflow and also notices
|
|
659
|
+
// a completed/dropped item before re-arming the next chunk.
|
|
660
|
+
void (async () => {
|
|
661
|
+
try {
|
|
662
|
+
if (!wakeCurrent(generation, nextOwnerPath)) return;
|
|
663
|
+
const live = (await mind.backlogList({ all: true })).find((entry) => entry.id === item.id);
|
|
664
|
+
if (!wakeCurrent(generation, nextOwnerPath)) return;
|
|
665
|
+
if (!live || (live.state !== "open" && live.state !== "taken") || live.dueAtEpochMs === undefined) {
|
|
666
|
+
pendingWakeIds.delete(item.id);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
if (displayedWakeDeadlines.get(live.id) === live.dueAtEpochMs) {
|
|
670
|
+
pendingWakeIds.delete(live.id);
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
const left = live.dueAtEpochMs - Date.now();
|
|
674
|
+
if (left > 0) {
|
|
675
|
+
scheduleWake(live, left);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (!wakeCurrent(generation, nextOwnerPath)) return;
|
|
679
|
+
pendingWakeIds.delete(item.id);
|
|
680
|
+
displayedWakeDeadlines.set(live.id, live.dueAtEpochMs);
|
|
681
|
+
deliverWake(
|
|
682
|
+
ctx,
|
|
683
|
+
`backlog due — ${compactMemoryText(live.text, MAX_WAKE_TEXT_CHARS)} (id ${live.id}). Review when ready.`,
|
|
684
|
+
);
|
|
685
|
+
await mind.acknowledgeDue([live.id]);
|
|
686
|
+
} catch (err) {
|
|
687
|
+
if (wakeCurrent(generation, nextOwnerPath)) surfaceWarning(ctx, `could not re-check due backlog item ${item.id}: ${err instanceof Error ? err.message : String(err)}`);
|
|
688
|
+
}
|
|
689
|
+
})();
|
|
690
|
+
}, delay);
|
|
691
|
+
t.unref?.();
|
|
692
|
+
timers.set(item.id, t);
|
|
693
|
+
};
|
|
694
|
+
for (const item of all) {
|
|
695
|
+
if ((item.state !== "open" && item.state !== "taken") || item.dueAtEpochMs === undefined) continue;
|
|
696
|
+
const delay = item.dueAtEpochMs - now;
|
|
697
|
+
if (delay <= 0 || timers.has(item.id)) continue;
|
|
698
|
+
scheduleWake(item, delay);
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
let activeScopeKey: string | undefined;
|
|
702
|
+
let sessionLifecycleGeneration = 0;
|
|
703
|
+
const reconcileScope = async (ctx: ExtensionContext, lifecycleGeneration = sessionLifecycleGeneration): Promise<void> => {
|
|
704
|
+
if (lifecycleGeneration !== sessionLifecycleGeneration) return;
|
|
705
|
+
const scope = resolveMindScope(ctx);
|
|
706
|
+
const nextKey = JSON.stringify([scope.persona, scope.projectRoot]);
|
|
707
|
+
if (activeScopeKey === undefined) {
|
|
708
|
+
activeScopeKey = nextKey;
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (activeScopeKey === nextKey) return;
|
|
712
|
+
discardOptimizer();
|
|
713
|
+
clearTimers();
|
|
714
|
+
releaseWakeOwner();
|
|
715
|
+
activeScopeKey = nextKey;
|
|
716
|
+
if (sessionActive && !isDelegatedLeg) {
|
|
717
|
+
await armWakes(ctx);
|
|
718
|
+
if (lifecycleGeneration !== sessionLifecycleGeneration) return;
|
|
719
|
+
lastArmedMigrationGeneration = migrationGeneration;
|
|
720
|
+
await refreshStatus(ctx);
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
|
|
724
|
+
const refreshStatus = async (ctx: ExtensionContext): Promise<void> => {
|
|
725
|
+
try {
|
|
726
|
+
const s = await getMind(ctx).summary();
|
|
727
|
+
if (warningStatusActive) {
|
|
728
|
+
setStatus(ctx, "mind warning · /mind doctor", "warning");
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
if (backgroundMigrationPending) { setStatus(ctx, "mind importing older memory · /persona-mind doctor"); return; }
|
|
732
|
+
const label = `mind ${s.ltm}L·${s.projectLtm}P·${s.stm}S · backlog ${s.backlogOpen}`;
|
|
733
|
+
setStatus(ctx, label);
|
|
734
|
+
} catch (err) {
|
|
735
|
+
surfaceWarning(ctx, `could not refresh memory status: ${err instanceof Error ? err.message : String(err)}`);
|
|
736
|
+
}
|
|
737
|
+
};
|
|
738
|
+
|
|
739
|
+
// A delegated leg came back BLOCKED — surface it as a backlog candidate (deterministic, nudge-only,
|
|
740
|
+
// never auto-writes). Reached on BOTH delivery paths: the sync delegate/council tool_result, and the
|
|
741
|
+
// background completion path where the report arrives as an attributed custom message.
|
|
742
|
+
const nudgeBlocked = (ctx: ExtensionContext, snippet: string): void => {
|
|
743
|
+
try {
|
|
744
|
+
const hint = `⚠️ a delegated leg reported ${snippet} — \`backlog add\` so the thread isn't lost`;
|
|
745
|
+
ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg("accent", hint) : hint);
|
|
746
|
+
} catch {
|
|
747
|
+
/* cosmetic */
|
|
748
|
+
}
|
|
749
|
+
};
|
|
750
|
+
const isDelegatedReport = (prompt: string): boolean => /^(?:\[pi-persona\]\s+)?\d+\s+async runs? settled\b/i.test(prompt.trim());
|
|
751
|
+
const customMessagesHandledBeforeStart = new WeakSet<object>();
|
|
752
|
+
const customReportsNudged = new WeakSet<object>();
|
|
753
|
+
const deferredInputsProcessed = new WeakSet<object>();
|
|
754
|
+
const nudgeCustomDelegatedReport = (message: object, text: string, ctx: ExtensionContext) => {
|
|
755
|
+
if (!nudgeEnabled || !isDelegatedReport(text)) return undefined;
|
|
756
|
+
const blocked = detectBlockedLeg(text);
|
|
757
|
+
if (blocked && !customReportsNudged.has(message)) {
|
|
758
|
+
customReportsNudged.add(message);
|
|
759
|
+
nudgeBlocked(ctx, blocked.snippet);
|
|
760
|
+
}
|
|
761
|
+
return blocked;
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
interface CaptureNotice {
|
|
765
|
+
hint: string;
|
|
766
|
+
}
|
|
767
|
+
let pendingCaptureNotice: CaptureNotice | undefined;
|
|
768
|
+
let pendingInputProvenance: { source: "interactive" | "rpc" | "extension" } | undefined;
|
|
769
|
+
let latestDirectInputPrompt: string | undefined;
|
|
770
|
+
let captureInputGeneration = 0;
|
|
771
|
+
const directInputPrompts = new Set<string>();
|
|
772
|
+
const rememberDirectInputPrompt = (prompt: string): void => {
|
|
773
|
+
directInputPrompts.delete(prompt);
|
|
774
|
+
directInputPrompts.add(prompt);
|
|
775
|
+
while (directInputPrompts.size > 128) {
|
|
776
|
+
const oldest = directInputPrompts.values().next().value as string | undefined;
|
|
777
|
+
if (oldest === undefined) break;
|
|
778
|
+
directInputPrompts.delete(oldest);
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
// Cue snippets already surfaced in the prompt this session: at most once per direct statement.
|
|
782
|
+
const cueHinted = new Set<string>();
|
|
783
|
+
const nestedBlockedRelays = new Set<string>();
|
|
784
|
+
const rememberCueHint = (snippet: string): void => {
|
|
785
|
+
cueHinted.delete(snippet);
|
|
786
|
+
cueHinted.add(snippet);
|
|
787
|
+
while (cueHinted.size > 128) {
|
|
788
|
+
const oldest = cueHinted.values().next().value as string | undefined;
|
|
789
|
+
if (oldest === undefined) break;
|
|
790
|
+
cueHinted.delete(oldest);
|
|
791
|
+
}
|
|
792
|
+
};
|
|
793
|
+
// The empty-mind discoverability line is an ANNOUNCEMENT — shown once per session, not a banner that
|
|
794
|
+
// persists every turn while the mind stays empty (that would be the nag we avoid).
|
|
795
|
+
let emptyAnnounced = false;
|
|
796
|
+
const resetSessionTransientState = (): number => {
|
|
797
|
+
sessionLifecycleGeneration++;
|
|
798
|
+
captureInputGeneration++;
|
|
799
|
+
pendingCaptureNotice = undefined;
|
|
800
|
+
pendingInputProvenance = undefined;
|
|
801
|
+
latestDirectInputPrompt = undefined;
|
|
802
|
+
directInputPrompts.clear();
|
|
803
|
+
cueHinted.clear();
|
|
804
|
+
nestedBlockedRelays.clear();
|
|
805
|
+
emptyAnnounced = false;
|
|
806
|
+
return sessionLifecycleGeneration;
|
|
807
|
+
};
|
|
808
|
+
const rememberNestedBlockedRelay = (toolCallId: string): void => {
|
|
809
|
+
nestedBlockedRelays.delete(toolCallId);
|
|
810
|
+
nestedBlockedRelays.add(toolCallId);
|
|
811
|
+
while (nestedBlockedRelays.size > 256) {
|
|
812
|
+
const oldest = nestedBlockedRelays.values().next().value as string | undefined;
|
|
813
|
+
if (oldest === undefined) break;
|
|
814
|
+
nestedBlockedRelays.delete(oldest);
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
const captureDirectCues = async (
|
|
818
|
+
text: string,
|
|
819
|
+
ctx: ExtensionContext,
|
|
820
|
+
lifecycleGeneration: number,
|
|
821
|
+
inputGeneration: number,
|
|
822
|
+
): Promise<CaptureNotice | undefined> => {
|
|
823
|
+
const cues = detectCaptureCues(text);
|
|
824
|
+
if (cues.length === 0) return undefined;
|
|
825
|
+
const explicit = capturePolicy === "auto" ? cues.filter((cue) => cue.strong) : [];
|
|
826
|
+
const mind = explicit.length > 0 ? getMind(ctx) : undefined;
|
|
827
|
+
const ownerCurrent = captureMemoryOwner(ctx);
|
|
828
|
+
const isCurrent = (): boolean => lifecycleGeneration === sessionLifecycleGeneration && inputGeneration === captureInputGeneration && ownerCurrent();
|
|
829
|
+
if (explicit.length > 0) {
|
|
830
|
+
await ensureLegacyMigrated(ctx);
|
|
831
|
+
if (isCurrent()) await reconcileScope(ctx, lifecycleGeneration);
|
|
832
|
+
}
|
|
833
|
+
const stored: string[] = [];
|
|
834
|
+
const failures: string[] = [];
|
|
835
|
+
if (mind) {
|
|
836
|
+
for (const cue of explicit) {
|
|
837
|
+
const label = cue.kind === "preference" ? "User preference" : cue.kind === "rationale" ? "Durable user decision" : "User explicitly asked to retain";
|
|
838
|
+
const result = await mind.remember({
|
|
839
|
+
term: cue.term,
|
|
840
|
+
kind: cue.kind,
|
|
841
|
+
text: `${label}: ${cue.candidate}`,
|
|
842
|
+
tags: ["auto-captured"],
|
|
843
|
+
source: "direct user persistence cue",
|
|
844
|
+
});
|
|
845
|
+
if (result.ok) {
|
|
846
|
+
stored.push(result.entry.id);
|
|
847
|
+
if (isCurrent()) autoOptimize.memoryAdded(ctx, cue.term === "long" ? "persona" : "project");
|
|
848
|
+
}
|
|
849
|
+
else failures.push(result.reason);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
// Durable writes from the accepted user input are preserved across a session change, but its
|
|
853
|
+
// acknowledgement and prompt/UI state belong only to the session/input that accepted it.
|
|
854
|
+
if (!isCurrent()) return undefined;
|
|
855
|
+
for (const cue of explicit) rememberCueHint(cue.snippet);
|
|
856
|
+
|
|
857
|
+
let hint = "";
|
|
858
|
+
if (stored.length > 0) {
|
|
859
|
+
hint = `⟢ pi-persona-mind — already captured ${stored.length} explicit user memor${stored.length === 1 ? "y" : "ies"} (${stored.join(", ")}); do not duplicate ${stored.length === 1 ? "it" : "them"}.`;
|
|
860
|
+
try {
|
|
861
|
+
ctx.ui.notify(`[pi-persona-mind] Captured ${stored.length} explicit memor${stored.length === 1 ? "y" : "ies"}.`, "info");
|
|
862
|
+
} catch {
|
|
863
|
+
/* headless/no UI */
|
|
864
|
+
}
|
|
865
|
+
await refreshStatus(ctx);
|
|
866
|
+
}
|
|
867
|
+
if (failures.length > 0) {
|
|
868
|
+
const reason = failures[0] ?? "unknown storage failure";
|
|
869
|
+
const retryHint = `⚠ pi-persona-mind could not auto-capture one explicit user memory: ${reason}. Before final, retry once with a safe declarative \`memory remember\` entry.`;
|
|
870
|
+
hint = [hint, retryHint].filter(Boolean).join("\n\n");
|
|
871
|
+
surfaceWarning(ctx, `automatic capture failed: ${reason}`);
|
|
872
|
+
}
|
|
873
|
+
if (!hint && nudgeEnabled) {
|
|
874
|
+
const cue = cues[0];
|
|
875
|
+
if (cue) {
|
|
876
|
+
rememberCueHint(cue.snippet);
|
|
877
|
+
hint = `⟢ pi-persona-mind — possible durable ${cue.kind} detected in direct user input. Save one safe declarative memory only if it should outlive this task.`;
|
|
878
|
+
try {
|
|
879
|
+
ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg("accent", `💡 worth remembering? memory remember (${cue.kind})`) : `💡 worth remembering? (${cue.kind})`);
|
|
880
|
+
} catch {
|
|
881
|
+
/* cosmetic */
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return hint ? { hint } : undefined;
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
// Capture only INPUT owned by the user. Extension-authored follow-ups and delegated reports are
|
|
889
|
+
// foreign data; before_agent_start cannot distinguish them, but the input event can. Direct,
|
|
890
|
+
// explicit persist-intent is safe to commit deterministically before the model runs. Everything
|
|
891
|
+
// softer remains a model-visible candidate governed by the standing tool guideline.
|
|
892
|
+
pi.on("input", async (event, ctx) => {
|
|
893
|
+
if (!available(ctx)) return;
|
|
894
|
+
const lifecycleGeneration = sessionLifecycleGeneration;
|
|
895
|
+
const inputGeneration = ++captureInputGeneration;
|
|
896
|
+
pendingInputProvenance = { source: event.source };
|
|
897
|
+
pendingCaptureNotice = undefined;
|
|
898
|
+
if (event.source === "extension") {
|
|
899
|
+
return;
|
|
900
|
+
}
|
|
901
|
+
if (isDelegatedLeg || capturePolicy === "off") {
|
|
902
|
+
return;
|
|
903
|
+
}
|
|
904
|
+
latestDirectInputPrompt = event.text;
|
|
905
|
+
rememberDirectInputPrompt(event.text);
|
|
906
|
+
const notice = await captureDirectCues(event.text, ctx, lifecycleGeneration, inputGeneration);
|
|
907
|
+
if (lifecycleGeneration === sessionLifecycleGeneration && inputGeneration === captureInputGeneration && latestDirectInputPrompt === event.text) {
|
|
908
|
+
pendingCaptureNotice = notice;
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
|
|
912
|
+
const customMessageText = (content: unknown): string => {
|
|
913
|
+
if (typeof content === "string") return content;
|
|
914
|
+
if (!Array.isArray(content)) return "";
|
|
915
|
+
return content
|
|
916
|
+
.map((part) => (part && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : ""))
|
|
917
|
+
.filter(Boolean)
|
|
918
|
+
.join("\n");
|
|
919
|
+
};
|
|
920
|
+
|
|
921
|
+
// Custom messages bypass `input`. Idle custom-triggered starts are handled in before_agent_start;
|
|
922
|
+
// messages appended inside an existing run still arrive only here. A deferred input is replayed
|
|
923
|
+
// user text and may be auto-captured; async child/exocom reports remain foreign.
|
|
924
|
+
pi.on("message_start", async (event, ctx) => {
|
|
925
|
+
if (!available(ctx)) return;
|
|
926
|
+
const message = event.message;
|
|
927
|
+
if (message.role !== "custom") return;
|
|
928
|
+
if (customMessagesHandledBeforeStart.has(message)) {
|
|
929
|
+
customMessagesHandledBeforeStart.delete(message);
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
const lifecycleGeneration = sessionLifecycleGeneration;
|
|
933
|
+
const inputGeneration = ++captureInputGeneration;
|
|
934
|
+
pendingInputProvenance = { source: "extension" };
|
|
935
|
+
pendingCaptureNotice = undefined;
|
|
936
|
+
const text = customMessageText(message.content);
|
|
937
|
+
if (!text) return;
|
|
938
|
+
if (message.customType === "pi-persona") {
|
|
939
|
+
nudgeCustomDelegatedReport(message, text, ctx);
|
|
940
|
+
return;
|
|
941
|
+
}
|
|
942
|
+
if (message.customType === "pi-persona-deferred-input") {
|
|
943
|
+
if (isDelegatedLeg || capturePolicy === "off") return;
|
|
944
|
+
if (deferredInputsProcessed.has(message)) return;
|
|
945
|
+
deferredInputsProcessed.add(message);
|
|
946
|
+
pendingInputProvenance = { source: "interactive" };
|
|
947
|
+
latestDirectInputPrompt = text;
|
|
948
|
+
rememberDirectInputPrompt(text);
|
|
949
|
+
const notice = await captureDirectCues(text, ctx, lifecycleGeneration, inputGeneration);
|
|
950
|
+
if (lifecycleGeneration === sessionLifecycleGeneration && inputGeneration === captureInputGeneration && latestDirectInputPrompt === text) {
|
|
951
|
+
pendingCaptureNotice = notice;
|
|
952
|
+
}
|
|
953
|
+
return;
|
|
954
|
+
}
|
|
955
|
+
pendingInputProvenance = { source: "extension" };
|
|
956
|
+
pendingCaptureNotice = undefined;
|
|
957
|
+
});
|
|
958
|
+
|
|
959
|
+
// Inject the mind into every turn. before_agent_start re-fires after compaction, so this is also
|
|
960
|
+
// how memory survives compaction: it re-injects from disk. Fail-open: a stalled read (slow disk,
|
|
961
|
+
// lock contention) degrades to no injection rather than hanging the turn.
|
|
962
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
963
|
+
if (!available(ctx)) return;
|
|
964
|
+
const lifecycleGeneration = sessionLifecycleGeneration;
|
|
965
|
+
const ownerCurrent = captureMemoryOwner(ctx);
|
|
966
|
+
await ensureLegacyMigrated(ctx);
|
|
967
|
+
if (!ownerCurrent()) return;
|
|
968
|
+
await reconcileScope(ctx, lifecycleGeneration);
|
|
969
|
+
if (!ownerCurrent()) return;
|
|
970
|
+
let provenance = pendingInputProvenance?.source;
|
|
971
|
+
pendingInputProvenance = undefined;
|
|
972
|
+
const customMessage = event.messageType === "custom" ? event.message : undefined;
|
|
973
|
+
if (customMessage) {
|
|
974
|
+
customMessagesHandledBeforeStart.add(customMessage);
|
|
975
|
+
provenance = customMessage.customType === "pi-persona-deferred-input" ? "interactive" : "extension";
|
|
976
|
+
const deferredWasAlreadyProcessed = customMessage.customType === "pi-persona-deferred-input" && deferredInputsProcessed.has(customMessage);
|
|
977
|
+
if (!deferredWasAlreadyProcessed) pendingCaptureNotice = undefined;
|
|
978
|
+
}
|
|
979
|
+
const userPrompt = event.messageType === "user" ? event.prompt : undefined;
|
|
980
|
+
// Only the attributed deferred-input convention represents direct user text in a custom event.
|
|
981
|
+
// Other custom messages remain extension-authored, even if their bodies resemble user intent.
|
|
982
|
+
const directInputPrompt = customMessage
|
|
983
|
+
? customMessage.customType === "pi-persona-deferred-input" ? customMessageText(customMessage.content) : undefined
|
|
984
|
+
: userPrompt;
|
|
985
|
+
const delegatedReport = customMessage
|
|
986
|
+
? customMessage.customType === "pi-persona" ? customMessageText(customMessage.content) : undefined
|
|
987
|
+
: userPrompt;
|
|
988
|
+
if (customMessage?.customType === "pi-persona-deferred-input") {
|
|
989
|
+
provenance = "interactive";
|
|
990
|
+
if (typeof directInputPrompt === "string" && !deferredInputsProcessed.has(customMessage)) {
|
|
991
|
+
deferredInputsProcessed.add(customMessage);
|
|
992
|
+
const inputGeneration = ++captureInputGeneration;
|
|
993
|
+
latestDirectInputPrompt = directInputPrompt;
|
|
994
|
+
rememberDirectInputPrompt(directInputPrompt);
|
|
995
|
+
const notice = isDelegatedLeg || capturePolicy === "off"
|
|
996
|
+
? undefined
|
|
997
|
+
: await captureDirectCues(directInputPrompt, ctx, lifecycleGeneration, inputGeneration);
|
|
998
|
+
if (lifecycleGeneration === sessionLifecycleGeneration && inputGeneration === captureInputGeneration && latestDirectInputPrompt === directInputPrompt) {
|
|
999
|
+
pendingCaptureNotice = notice;
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
let cueHint = "";
|
|
1004
|
+
if (!isDelegatedLeg) {
|
|
1005
|
+
// A delegated leg that came back BLOCKED arrives HERE on the async/background
|
|
1006
|
+
// path: pi-persona delivers the completion report as a follow-up user message; an
|
|
1007
|
+
// idle `sendMessage(..., { triggerTurn: true })` instead arrives in the custom-message variant.
|
|
1008
|
+
// In both cases, provenance and the host's event discriminator keep foreign reports out of capture.
|
|
1009
|
+
const blocked = customMessage?.customType === "pi-persona"
|
|
1010
|
+
? nudgeCustomDelegatedReport(customMessage, delegatedReport ?? "", ctx)
|
|
1011
|
+
: nudgeEnabled && provenance === "extension" && delegatedReport !== undefined && isDelegatedReport(delegatedReport)
|
|
1012
|
+
? detectBlockedLeg(delegatedReport)
|
|
1013
|
+
: undefined;
|
|
1014
|
+
if (blocked) {
|
|
1015
|
+
if (customMessage?.customType !== "pi-persona") nudgeBlocked(ctx, blocked.snippet);
|
|
1016
|
+
} else if (capturePolicy !== "off") {
|
|
1017
|
+
const notice = pendingCaptureNotice;
|
|
1018
|
+
pendingCaptureNotice = undefined;
|
|
1019
|
+
const promptBelongsToAnOlderDirectInput = directInputPrompt !== undefined && directInputPrompts.has(directInputPrompt) && directInputPrompt !== latestDirectInputPrompt;
|
|
1020
|
+
if (notice && directInputPrompt !== undefined && (provenance === "interactive" || provenance === "rpc") && !promptBelongsToAnOlderDirectInput) {
|
|
1021
|
+
cueHint = notice.hint;
|
|
1022
|
+
} else if (nudgeEnabled && provenance !== "extension") {
|
|
1023
|
+
// A current programmatic path may lack direct-input provenance: nudge only. Never auto-write
|
|
1024
|
+
// here because an extension-authored follow-up is indistinguishable from direct user input.
|
|
1025
|
+
const cue: CaptureCue | undefined = directInputPrompt === undefined ? undefined : detectCaptureCues(directInputPrompt)[0];
|
|
1026
|
+
if (cue && !cueHinted.has(cue.snippet)) {
|
|
1027
|
+
rememberCueHint(cue.snippet);
|
|
1028
|
+
try {
|
|
1029
|
+
ctx.ui.setStatus(STATUS_KEY, ctx.ui.theme ? ctx.ui.theme.fg("accent", `💡 worth remembering? memory remember (${cue.kind})`) : `💡 worth remembering? (${cue.kind})`);
|
|
1030
|
+
} catch {
|
|
1031
|
+
/* cosmetic */
|
|
1032
|
+
}
|
|
1033
|
+
if (cue.strong) {
|
|
1034
|
+
cueHint = "⟢ pi-persona-mind — an explicit persistence cue was detected, but its input provenance was unavailable. Save one safe declarative `memory remember` entry before final only if it came directly from the user.";
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
let block = "";
|
|
1041
|
+
const query = directInputPrompt ?? latestDirectInputPrompt ?? "";
|
|
1042
|
+
const sessionBlock = isDelegatedLeg ? "" : sessionMemory.injection(ctx, { query, maxTokens: 600 });
|
|
1043
|
+
try {
|
|
1044
|
+
// A worker inherits the LEAN mind (north-star + identity only); the supervisor gets it all.
|
|
1045
|
+
block = await withDeadline(getMind(ctx).buildInjection({ lean: isDelegatedLeg, cleanup: !backgroundMigrationPending, query, fixedBlocks: [sessionBlock, cueHint].filter(Boolean).map((text) => `${text}\n\n`) }), INJECT_DEADLINE_MS, "", () => {
|
|
1046
|
+
if (ownerCurrent()) surfaceWarning(ctx, `memory injection exceeded ${INJECT_DEADLINE_MS}ms and was skipped for this turn`);
|
|
1047
|
+
});
|
|
1048
|
+
} catch (err) {
|
|
1049
|
+
if (ownerCurrent()) surfaceWarning(ctx, `memory injection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1050
|
+
}
|
|
1051
|
+
if (!ownerCurrent()) return;
|
|
1052
|
+
// The empty-mind hint announces the faculty ONCE per session, then goes quiet even if the mind
|
|
1053
|
+
// stays empty — a state indicator, not a per-turn nag. Matched by PREFIX: a content block starts
|
|
1054
|
+
// with `<persona-mind …` and a memory's text sits inside the fence, so this only ever recognises
|
|
1055
|
+
// the announcement itself — never a real memory that happens to quote the phrase.
|
|
1056
|
+
if (block.startsWith(EMPTY_HINT_PREFIX)) {
|
|
1057
|
+
if (emptyAnnounced) block = "";
|
|
1058
|
+
else emptyAnnounced = true;
|
|
1059
|
+
}
|
|
1060
|
+
const injected = [block, sessionBlock, cueHint].filter(Boolean).join("\n\n");
|
|
1061
|
+
if (injected) return { systemPrompt: `${event.systemPrompt}\n\n${injected}` };
|
|
1062
|
+
return;
|
|
1063
|
+
});
|
|
1064
|
+
|
|
1065
|
+
// The SYNC delegation path: a `delegate`/`council` tool_result whose report carries a BLOCKED/UNKNOWN
|
|
1066
|
+
// marker (the async/background default lands in before_agent_start above). No result mutation — just a
|
|
1067
|
+
// status-line nudge — so it composes cleanly alongside pi-persona's own tool_result hook.
|
|
1068
|
+
const REPORT_TOOLS = new Set(["delegate", "council", "flow"]);
|
|
1069
|
+
pi.on("tool_result", async (event, ctx) => {
|
|
1070
|
+
if (!available(ctx)) return;
|
|
1071
|
+
const toolCallId = typeof event.toolCallId === "string" ? event.toolCallId : "";
|
|
1072
|
+
const relaysNestedBlocked = toolCallId ? nestedBlockedRelays.delete(toolCallId) : false;
|
|
1073
|
+
if (isDelegatedLeg) return undefined;
|
|
1074
|
+
if (event.toolName === "memory" || event.toolName === "backlog") {
|
|
1075
|
+
const details = event.details && typeof event.details === "object" ? (event.details as Record<string, unknown>) : undefined;
|
|
1076
|
+
if (details?.ok === false) return { isError: true };
|
|
1077
|
+
if (details?.ok === true) {
|
|
1078
|
+
await refreshStatus(ctx);
|
|
1079
|
+
// A due item added during a running session must be armed now, not only after the next
|
|
1080
|
+
// restart. Re-arm on every successful backlog mutation so take/done/drop also cancel
|
|
1081
|
+
// stale timers. Existing overdue items are not re-announced by this maintenance pass.
|
|
1082
|
+
if (event.toolName === "backlog" && sessionActive) {
|
|
1083
|
+
const newlyQueuedId = event.input?.action === "add" && typeof details.id === "string" ? details.id : undefined;
|
|
1084
|
+
await armWakes(ctx, false, newlyQueuedId);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
return undefined;
|
|
1088
|
+
}
|
|
1089
|
+
if (!nudgeEnabled) return undefined;
|
|
1090
|
+
const text = event.content.reduce((s, c) => (c.type === "text" ? s + c.text : s), "");
|
|
1091
|
+
const blocked = detectBlockedLeg(text);
|
|
1092
|
+
const parentToolCallId = typeof event.parentToolCallId === "string" && event.parentToolCallId.length > 0 ? event.parentToolCallId : undefined;
|
|
1093
|
+
if (parentToolCallId) {
|
|
1094
|
+
if (blocked && (REPORT_TOOLS.has(event.toolName) || relaysNestedBlocked)) rememberNestedBlockedRelay(parentToolCallId);
|
|
1095
|
+
return undefined;
|
|
1096
|
+
}
|
|
1097
|
+
if (blocked && (REPORT_TOOLS.has(event.toolName) || relaysNestedBlocked)) nudgeBlocked(ctx, blocked.snippet);
|
|
1098
|
+
return undefined;
|
|
1099
|
+
});
|
|
1100
|
+
|
|
1101
|
+
const startSession = async (_event: unknown, ctx: ExtensionContext): Promise<void> => {
|
|
1102
|
+
autoOptimize.revoke();
|
|
1103
|
+
currentSessionContext = ctx;
|
|
1104
|
+
discardOptimizer();
|
|
1105
|
+
sessionMemory.deactivate();
|
|
1106
|
+
const reason = unavailableReason(ctx);
|
|
1107
|
+
if (!isDelegatedLeg && !reason) sessionMemory.activate(ctx);
|
|
1108
|
+
const lifecycleGeneration = resetSessionTransientState();
|
|
1109
|
+
const sessionId = sessionIdOf(ctx);
|
|
1110
|
+
settingsCollectUnsubscribe?.();
|
|
1111
|
+
settingsCollectUnsubscribe = undefined;
|
|
1112
|
+
if (reason) {
|
|
1113
|
+
sessionActive = false;
|
|
1114
|
+
sessionStarting = false;
|
|
1115
|
+
wakeGeneration++;
|
|
1116
|
+
clearTimers();
|
|
1117
|
+
releaseWakeOwner();
|
|
1118
|
+
pi.setActiveTools(pi.getActiveTools().filter((name) => name !== "memory" && name !== "backlog"));
|
|
1119
|
+
setStatus(ctx, "Mind inactive · requires pi-persona");
|
|
1120
|
+
const pendingOwner = queryPersonaMemoryOwner(pi, ctx);
|
|
1121
|
+
if (pendingOwner && !pendingOwner.ready) { setStatus(ctx, "Mind waiting for Persona session"); return; }
|
|
1122
|
+
try { ctx.ui.notify(reason, "info"); } catch { /* Availability is also enforced at every tool call. */ }
|
|
1123
|
+
return;
|
|
1124
|
+
}
|
|
1125
|
+
if (suspendedMindTools.size > 0) {
|
|
1126
|
+
pi.setActiveTools([...new Set([...pi.getActiveTools(), ...suspendedMindTools])]);
|
|
1127
|
+
suspendedMindTools.clear();
|
|
1128
|
+
}
|
|
1129
|
+
// Mind preferences are session snapshots, independent from Persona's live owner.
|
|
1130
|
+
resetMindSettings(sessionId);
|
|
1131
|
+
const mindSettings = resolveMindSettings(agentDir, process.env, sessionId);
|
|
1132
|
+
capturePolicy = mindSettings.mindCapture;
|
|
1133
|
+
nudgeEnabled = mindSettings.mindNudge;
|
|
1134
|
+
autoOptimize.activate(ctx, true);
|
|
1135
|
+
// A worker never arms/fires the supervisor's backlog wakes (nor shows a status line).
|
|
1136
|
+
if (isDelegatedLeg) return;
|
|
1137
|
+
settingsCollectUnsubscribe = pi.events.on("pi-persona:settings:collect:v1", (payload) => {
|
|
1138
|
+
if (!payload || typeof payload !== "object") return;
|
|
1139
|
+
const add = (payload as { add?: unknown }).add;
|
|
1140
|
+
if (typeof add !== "function") return;
|
|
1141
|
+
try {
|
|
1142
|
+
add("mind", { mindCapture: capturePolicy, mindNudge: nudgeEnabled });
|
|
1143
|
+
} catch {
|
|
1144
|
+
/* an optional settings consumer must not interrupt a Pi lifecycle event */
|
|
1145
|
+
}
|
|
1146
|
+
});
|
|
1147
|
+
sessionActive = true;
|
|
1148
|
+
sessionStarting = true;
|
|
1149
|
+
try {
|
|
1150
|
+
await ensureLegacyMigrated(ctx);
|
|
1151
|
+
if (lifecycleGeneration !== sessionLifecycleGeneration) return;
|
|
1152
|
+
await reconcileScope(ctx, lifecycleGeneration);
|
|
1153
|
+
if (lifecycleGeneration !== sessionLifecycleGeneration) return;
|
|
1154
|
+
await armWakes(ctx);
|
|
1155
|
+
if (lifecycleGeneration !== sessionLifecycleGeneration) return;
|
|
1156
|
+
lastArmedMigrationGeneration = migrationGeneration;
|
|
1157
|
+
try {
|
|
1158
|
+
// Import selection/commit shares the profile mutex with expiry cleanup. Its bounded
|
|
1159
|
+
// startup wait must not be rejoined through hygiene while the import is still pending.
|
|
1160
|
+
if (!backgroundMigrationPending) await getMind(ctx).sweepExpired();
|
|
1161
|
+
} catch {
|
|
1162
|
+
/* expired STM/backlog must not block session start */
|
|
1163
|
+
}
|
|
1164
|
+
if (lifecycleGeneration !== sessionLifecycleGeneration) return;
|
|
1165
|
+
await refreshStatus(ctx);
|
|
1166
|
+
} finally {
|
|
1167
|
+
if (lifecycleGeneration === sessionLifecycleGeneration) {
|
|
1168
|
+
sessionStarting = false;
|
|
1169
|
+
rearmAfterMigration(ctx);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
pi.on("session_start", startSession);
|
|
1174
|
+
pi.events.on(PERSONA_MEMORY_OWNER_CHANGED, (value: unknown) => {
|
|
1175
|
+
const ctx = currentSessionContext;
|
|
1176
|
+
if (!ctx) return;
|
|
1177
|
+
const changed = parsePersonaMemoryOwner(value, sessionIdOf(ctx));
|
|
1178
|
+
if (!changed) return;
|
|
1179
|
+
if (!changed.ready) { onPersonaUnavailable(); return; }
|
|
1180
|
+
if (!available(ctx)) return;
|
|
1181
|
+
autoOptimize.activate(ctx);
|
|
1182
|
+
const generation = sessionLifecycleGeneration;
|
|
1183
|
+
void (async () => {
|
|
1184
|
+
if (!sessionActive && !sessionStarting) { await startSession({}, ctx); return; }
|
|
1185
|
+
await reconcileScope(ctx, generation);
|
|
1186
|
+
if (generation !== sessionLifecycleGeneration || !available(ctx)) return;
|
|
1187
|
+
await ensureLegacyMigrated(ctx);
|
|
1188
|
+
if (generation === sessionLifecycleGeneration && available(ctx)) await refreshStatus(ctx);
|
|
1189
|
+
})().catch((error: unknown) => { if (generation === sessionLifecycleGeneration && available(ctx)) surfaceWarning(ctx, `could not activate Persona memory owner: ${error instanceof Error ? error.message : String(error)}`); });
|
|
1190
|
+
});
|
|
1191
|
+
|
|
1192
|
+
pi.on("session_shutdown", (_event, ctx) => {
|
|
1193
|
+
currentSessionContext = undefined;
|
|
1194
|
+
discardOptimizer();
|
|
1195
|
+
sessionMemory.deactivate();
|
|
1196
|
+
resetSessionTransientState();
|
|
1197
|
+
sessionActive = false;
|
|
1198
|
+
sessionStarting = false;
|
|
1199
|
+
settingsCollectUnsubscribe?.();
|
|
1200
|
+
settingsCollectUnsubscribe = undefined;
|
|
1201
|
+
resetMindSettings(sessionIdOf(ctx));
|
|
1202
|
+
wakeGeneration++;
|
|
1203
|
+
clearTimers();
|
|
1204
|
+
releaseWakeOwner();
|
|
1205
|
+
});
|
|
1206
|
+
|
|
1207
|
+
registerMindCommands(pi, {
|
|
1208
|
+
agentDir, resolveScope: resolveMindScope, rawPersona: rawMindPersona, getMind,
|
|
1209
|
+
getSessionMemory: () => sessionMemory, getOptimizer, ensureLegacyMigrated, surfaceWarning,
|
|
1210
|
+
migrationStatus,
|
|
1211
|
+
unavailableReason,
|
|
1212
|
+
activity: getActivity,
|
|
1213
|
+
autoOptimize,
|
|
1214
|
+
pendingWarnings: () => [...warnings],
|
|
1215
|
+
acknowledgeWarnings: (ctx, count) => {
|
|
1216
|
+
warnings.clear(); warningStatusActive = false;
|
|
1217
|
+
setStatus(ctx, count === 0 ? "mind doctor · healthy" : `mind doctor · ${count} warning(s) acknowledged`, count === 0 ? "dim" : "warning");
|
|
1218
|
+
},
|
|
1219
|
+
capturePolicy: () => capturePolicy, isDelegatedLeg, sessionActive: () => sessionActive,
|
|
1220
|
+
isCurrent: (ctx) => sessionMemory.isCurrent(ctx),
|
|
1221
|
+
afterWorkspaceReset: async (ctx) => { discardOptimizer(); await armWakes(ctx, false); await refreshStatus(ctx); },
|
|
1222
|
+
appendResult: (ctx, title, body) => {
|
|
1223
|
+
if (!sessionMemory.isCurrent(ctx)) throw new Error("mind result owner is unavailable");
|
|
1224
|
+
pi.appendEntry(MIND_RESULT_ENTRY_TYPE, { title, content: body });
|
|
1225
|
+
},
|
|
1226
|
+
});
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
export default function piPersonaMind(pi: ExtensionAPI): void {
|
|
1230
|
+
createExtension(pi);
|
|
1231
|
+
}
|