@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,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content scanner — gates every write into the mind, and re-runs on load before injection.
|
|
3
|
+
*
|
|
4
|
+
* A memory is injected back into the supervisor's system prompt, and a sub-agent (or another
|
|
5
|
+
* process) may be the one writing it, so stored text is an untrusted escalation surface. The
|
|
6
|
+
* scanner rejects, in tiers, the classes that are genuinely dangerous as PERSISTED, RE-INJECTED
|
|
7
|
+
* facts:
|
|
8
|
+
*
|
|
9
|
+
* - "all" (fires in every scope): the attacks on the supervisor itself — prompt-injection /
|
|
10
|
+
* role-hijack, deception directives ("don't tell the user"), and invisible unicode
|
|
11
|
+
* used to smuggle them. These are never a legitimate fact to store.
|
|
12
|
+
* - "context" (the default): adds credential/secret leakage — blocking a raw key from being
|
|
13
|
+
* persisted into a shared, re-injected store.
|
|
14
|
+
* - "strict" (opt-in): adds high-false-positive offensive-security vocabulary. OFF by default so
|
|
15
|
+
* a custom security persona can retain legitimate findings like any other persona.
|
|
16
|
+
*
|
|
17
|
+
* Pattern-based, no LLM: cheap, deterministic, cross-OS. Injection patterns are filler-tolerant so
|
|
18
|
+
* padding between the verb and its target cannot bypass them, and are matched against a
|
|
19
|
+
* whitespace-collapsed copy too so a newline placed inside a phrase (which the render path rejoins)
|
|
20
|
+
* cannot slip past the scan.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
export type ScanScope = "all" | "context" | "strict";
|
|
24
|
+
const SCOPE_RANK: Record<ScanScope, number> = { all: 0, context: 1, strict: 2 };
|
|
25
|
+
|
|
26
|
+
export interface ScanResult {
|
|
27
|
+
ok: boolean;
|
|
28
|
+
reason?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface Rule {
|
|
32
|
+
re: RegExp;
|
|
33
|
+
reason: string;
|
|
34
|
+
minScope: ScanScope;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Invisible / format-control characters: zero-width spaces & joiners (U+200B-200D), bidi marks and
|
|
38
|
+
// overrides (U+200E-200F, U+202A-202E), word joiner & invisible math ops (U+2060-2064), bidi
|
|
39
|
+
// isolates (U+2066-2069), BOM/ZWNBSP (U+FEFF), supplementary variation selectors
|
|
40
|
+
// (U+E0100-E01EF), and the Unicode Tags block (U+E0000-E007F) — the "Trojan Source" hiding set.
|
|
41
|
+
// Basic VS15/VS16 are intentionally not blanket-banned: ordinary emoji such as ⚠️ use them.
|
|
42
|
+
const INVISIBLE = /[----\u{e0000}-\u{e007f}\u{e0100}-\u{e01ef}]/u;
|
|
43
|
+
/** A basic variation selector attached to ASCII is not normal typography and is a common byte-
|
|
44
|
+
* smuggling shape; the same selector after an emoji/symbol remains legitimate presentation data. */
|
|
45
|
+
const ASCII_VARIATION_SELECTOR = /[\u0000-\u007f][\ufe00-\ufe0f]/u;
|
|
46
|
+
|
|
47
|
+
// NUL and the remaining non-whitespace C0/C1 controls can terminate strings or alter terminal /
|
|
48
|
+
// transport framing. Tabs and line breaks are ordinary prose formatting and stay allowed.
|
|
49
|
+
const UNSAFE_CONTROL = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/u;
|
|
50
|
+
|
|
51
|
+
// Override/system-prompt phrases are matched as word sequences below instead of as a regex with a
|
|
52
|
+
// greedy filler gap. That makes the scan linear even when an untrusted document contains megabytes
|
|
53
|
+
// of near-matching filler, and avoids the old fixed 120-character bypass.
|
|
54
|
+
const OVERRIDE_START = new Set(["ignore", "disregard", "forget", "override", "ignora", "ignorare", "dimentica", "dimenticare", "sovrascrivi", "sovrascrivere"]);
|
|
55
|
+
const OVERRIDE_TARGET = new Set([
|
|
56
|
+
"previous", "prior", "above", "earlier", "all", "the", "these", "those", "your",
|
|
57
|
+
"precedente", "precedenti", "sopra", "anteriore", "anteriori", "tutto", "tutti", "tutta", "tutte", "il", "lo", "la", "i", "gli", "le", "questo", "questa", "questi", "queste", "tuo", "tua", "tuoi", "tue",
|
|
58
|
+
]);
|
|
59
|
+
const OVERRIDE_OBJECT = new Set([
|
|
60
|
+
"instruction", "instructions", "directive", "directives", "prompt", "prompts", "message", "messages", "rule", "rules",
|
|
61
|
+
"istruzione", "istruzioni", "direttiva", "direttive", "messaggio", "messaggi", "regola", "regole",
|
|
62
|
+
]);
|
|
63
|
+
const SYSTEM_TARGET = new Set(["disregard", "ignore", "override", "ignora", "ignorare", "sovrascrivi", "sovrascrivere"]);
|
|
64
|
+
const SYSTEM_WORD = new Set(["system", "sistema"]);
|
|
65
|
+
const PROMPT_WORD = new Set(["prompt"]);
|
|
66
|
+
const DECEPTION_START = new Set(["never", "dont", "mai"]);
|
|
67
|
+
const DECEPTION_VERB = new Set([
|
|
68
|
+
"tell", "inform", "mention", "reveal", "show", "disclose", "notify",
|
|
69
|
+
"dire", "informa", "informare", "menziona", "menzionare", "rivela", "rivelare", "mostra", "mostrare", "notifica", "notificare",
|
|
70
|
+
]);
|
|
71
|
+
const USER_TARGET = new Set(["user", "utente", "allutente"]);
|
|
72
|
+
|
|
73
|
+
function hasWordSequence(text: string, groups: readonly ReadonlySet<string>[]): boolean {
|
|
74
|
+
// Splitting at a full stop/newline preserves the old rule's sentence boundary. The caller passes a
|
|
75
|
+
// whitespace-collapsed copy, so a newline inserted inside a phrase is still detected.
|
|
76
|
+
for (const sentence of text.split(/[.\n]/)) {
|
|
77
|
+
const words = sentence.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [];
|
|
78
|
+
let group = 0;
|
|
79
|
+
for (const word of words) {
|
|
80
|
+
if (!groups[group]?.has(word)) continue;
|
|
81
|
+
group++;
|
|
82
|
+
if (group === groups.length) return true;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const RULES: Rule[] = [
|
|
89
|
+
// ── attacks on the supervisor itself — always flagged ───────────────────────
|
|
90
|
+
{ re: /\byou\s+are\s+now\s+(?:a\b|an\b|the\b|no\s+longer\b)/i, reason: "possible role-hijack: identity reassignment", minScope: "all" },
|
|
91
|
+
{ re: /^\s*(?:please\s+)?act\s+as\s+(?:the\s+)?system\b/i, reason: "possible role-hijack: system impersonation", minScope: "all" },
|
|
92
|
+
{ re: /\b(?:new|updated)\s+(?:system\s+)?(?:instructions?|directives?)\s*:/i, reason: "possible prompt-injection: injected directives", minScope: "all" },
|
|
93
|
+
// ── credential / secret leakage — blocked by default (context) ──────────────
|
|
94
|
+
{ re: /\bsk-ant-[A-Za-z0-9_-]{16,}/, reason: "possible secret: Anthropic API key", minScope: "context" },
|
|
95
|
+
{ re: /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}/, reason: "possible secret: OpenAI API key", minScope: "context" },
|
|
96
|
+
{ re: /\bAKIA[0-9A-Z]{16}\b/, reason: "possible secret: AWS access key id", minScope: "context" },
|
|
97
|
+
{ re: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/, reason: "possible secret: GitHub token", minScope: "context" },
|
|
98
|
+
{ re: /\bxox[baprs]-[A-Za-z0-9-]{10,}/, reason: "possible secret: Slack token", minScope: "context" },
|
|
99
|
+
{ re: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/, reason: "possible secret: private key block", minScope: "context" },
|
|
100
|
+
{ re: /\bBearer\s+[A-Za-z0-9._-]{16,}/, reason: "possible secret: bearer token / credential", minScope: "context" },
|
|
101
|
+
{ re: /\b(?:password|passwd|pwd|secret|api[_-]?key|token|access[_-]?token)\s*[=:]\s*\S{8,}/i, reason: "possible secret: inline credential assignment", minScope: "context" },
|
|
102
|
+
// ── offensive-security vocabulary — opt-in only, independent of persona name ──
|
|
103
|
+
{ re: /\b(?:cobalt\s+strike|sliver|havoc|mythic|meterpreter)\b[^.\n]{0,30}\b(?:beacon|implant|payload|c2)\b/i, reason: "offensive-security tooling (strict scope)", minScope: "strict" },
|
|
104
|
+
{ re: /\bauthorized_keys\b[^.\n]{0,40}\b(?:append|echo|>>|backdoor|persist)/i, reason: "SSH-key persistence (strict scope)", minScope: "strict" },
|
|
105
|
+
];
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Scan a candidate memory/backlog text at the given scope (default "context"). Returns
|
|
109
|
+
* `{ ok: true }` when safe to store/inject, or `{ ok: false, reason }` naming the first problem
|
|
110
|
+
* found. Empty/whitespace is treated as OK here — non-emptiness is the caller's concern.
|
|
111
|
+
*/
|
|
112
|
+
export function scanContent(text: string, scope: ScanScope = "context"): ScanResult {
|
|
113
|
+
if (INVISIBLE.test(text)) return { ok: false, reason: "invisible unicode / hidden characters detected" };
|
|
114
|
+
if (ASCII_VARIATION_SELECTOR.test(text)) return { ok: false, reason: "suspicious variation selector attached to ASCII" };
|
|
115
|
+
if (UNSAFE_CONTROL.test(text)) return { ok: false, reason: "unsafe control character detected" };
|
|
116
|
+
// Fold compatibility-width glyphs before matching: a model reads full-width Latin as the same
|
|
117
|
+
// instruction, so the trust boundary must as well. The render path also collapses whitespace;
|
|
118
|
+
// scan that form so a newline-split phrase cannot re-join into an unchecked instruction.
|
|
119
|
+
const normalized = text.normalize("NFKC");
|
|
120
|
+
const collapsed = normalized.replace(/\s+/g, " ");
|
|
121
|
+
if (hasWordSequence(collapsed, [OVERRIDE_START, OVERRIDE_TARGET, OVERRIDE_OBJECT])) {
|
|
122
|
+
return { ok: false, reason: "possible prompt-injection: override instruction" };
|
|
123
|
+
}
|
|
124
|
+
if (
|
|
125
|
+
hasWordSequence(collapsed, [SYSTEM_TARGET, SYSTEM_WORD, PROMPT_WORD]) ||
|
|
126
|
+
hasWordSequence(collapsed, [SYSTEM_TARGET, PROMPT_WORD, SYSTEM_WORD])
|
|
127
|
+
) {
|
|
128
|
+
return { ok: false, reason: "possible prompt-injection: target the system prompt" };
|
|
129
|
+
}
|
|
130
|
+
// Keep this filler-unbounded like the override checks. Apostrophes are removed before tokenizing
|
|
131
|
+
// so `don't` and `don’t` both become the single sentinel `dont`.
|
|
132
|
+
const deceptionText = collapsed.replace(/['’]/g, "");
|
|
133
|
+
if (
|
|
134
|
+
hasWordSequence(deceptionText, [DECEPTION_START, DECEPTION_VERB, USER_TARGET]) ||
|
|
135
|
+
hasWordSequence(deceptionText, [new Set(["do"]), new Set(["not"]), DECEPTION_VERB, USER_TARGET]) ||
|
|
136
|
+
hasWordSequence(deceptionText, [new Set(["non"]), DECEPTION_VERB, USER_TARGET])
|
|
137
|
+
) {
|
|
138
|
+
return { ok: false, reason: "possible deception: directive to hide/conceal from the user" };
|
|
139
|
+
}
|
|
140
|
+
const limit = SCOPE_RANK[scope];
|
|
141
|
+
for (const rule of RULES) {
|
|
142
|
+
if (SCOPE_RANK[rule.minScope] > limit) continue;
|
|
143
|
+
if (rule.re.test(normalized) || (collapsed !== normalized && rule.re.test(collapsed))) return { ok: false, reason: rule.reason };
|
|
144
|
+
}
|
|
145
|
+
return { ok: true };
|
|
146
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scope resolution — where a mind's stores live, and which persona owns the view.
|
|
3
|
+
*
|
|
4
|
+
* Active ownership is supplied by the live companion protocol.
|
|
5
|
+
*
|
|
6
|
+
* Layout under `<agentDir>/persona-mind/`:
|
|
7
|
+
* memory/ltm/<persona>.json long-term, per persona (identity)
|
|
8
|
+
* memory/ltm/_shared.json long-term, shared across personas
|
|
9
|
+
* memory/project/<project>.json durable repository knowledge
|
|
10
|
+
* memory/stm/<project>.json short-term, per project (decays)
|
|
11
|
+
* backlog/<project>.json backlog, per project
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { basename, dirname, join, resolve, win32 } from "node:path";
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_PERSONA = "_default";
|
|
20
|
+
export const SHARED_SCOPE = "_shared";
|
|
21
|
+
|
|
22
|
+
export interface ScopePaths {
|
|
23
|
+
/** Long-term memory for the active persona. */
|
|
24
|
+
ltm: string;
|
|
25
|
+
/** Long-term memory shared across personas. */
|
|
26
|
+
shared: string;
|
|
27
|
+
/** Durable repository knowledge, attributed to its recording persona. */
|
|
28
|
+
projectLtm: string;
|
|
29
|
+
/** Short-term memory for the current project. */
|
|
30
|
+
stm: string;
|
|
31
|
+
/** Backlog for the current project. */
|
|
32
|
+
backlog: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Persona/shared facts span projects, so every memory writer uses one profile transaction lock. */
|
|
36
|
+
export function memoryMutationLockPath(paths: Pick<ScopePaths, "shared">): string {
|
|
37
|
+
return `${paths.shared}.memory-transaction.lock`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface Scope {
|
|
41
|
+
persona: string;
|
|
42
|
+
projectRoot: string;
|
|
43
|
+
slug: string;
|
|
44
|
+
paths: ScopePaths;
|
|
45
|
+
/** True when the resolved project is the user's home directory (no real git workspace). */
|
|
46
|
+
homeWorkspace?: true;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The internal scope names a real persona must never be allowed to occupy (they back the shared
|
|
50
|
+
* tier and the no-persona fallback; a collision would bleed private↔shared memory or merge scopes).
|
|
51
|
+
* Compared case-insensitively — a case-insensitive filesystem aliases `_SHARED.json` to `_shared.json`. */
|
|
52
|
+
const RESERVED_SCOPES: ReadonlySet<string> = new Set([DEFAULT_PERSONA, SHARED_SCOPE]);
|
|
53
|
+
|
|
54
|
+
/** Windows reserved device base names: `NUL.json`/`CON.json`/… resolve to the device (a silent
|
|
55
|
+
* write-to-void) in legacy Win32 path resolution, so a persona named after one must not be a filename. */
|
|
56
|
+
const WIN_RESERVED = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
|
|
57
|
+
const MAX_CANONICAL_CACHE_ENTRIES = 256;
|
|
58
|
+
const canonicalProjectCache = new Map<string, string>();
|
|
59
|
+
|
|
60
|
+
function isReservedSegment(s: string): boolean {
|
|
61
|
+
const deviceBase = s.split(".", 1)[0] ?? s;
|
|
62
|
+
return RESERVED_SCOPES.has(s.toLowerCase()) || WIN_RESERVED.test(deviceBase);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A stable 12-hex content id for a persona name, used when it has no filesystem-safe characters. */
|
|
66
|
+
function personaHash(name: string): string {
|
|
67
|
+
return createHash("sha256").update(name).digest("hex").slice(0, 12);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** A filesystem-safe single path segment for a persona name (no separators, no traversal). Two hazards
|
|
71
|
+
* are guarded: a name with no safe characters (CJK/Cyrillic/emoji) would collapse to one sentinel and
|
|
72
|
+
* merge every such persona (and the no-persona scope) — it gets a stable content-derived segment; and a
|
|
73
|
+
* name that lands on an internal sentinel or a Windows device name is prefixed so it can never hijack
|
|
74
|
+
* that reserved store. */
|
|
75
|
+
export function sanitizePersona(name: string, platform: NodeJS.Platform | string = process.platform): string {
|
|
76
|
+
const s = name
|
|
77
|
+
.replace(/[^a-zA-Z0-9._-]+/g, "-")
|
|
78
|
+
.replace(/^[-.]+|[-.]+$/g, "")
|
|
79
|
+
.slice(0, 64);
|
|
80
|
+
if (!s) return `persona-${personaHash(name)}`;
|
|
81
|
+
const lossy = s !== name || (platform === "win32" && s !== s.toLowerCase());
|
|
82
|
+
if (isReservedSegment(s)) return `persona-${s}-${personaHash(name)}`;
|
|
83
|
+
return lossy ? `${s}-${personaHash(name)}` : s;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The agent dir the mind should use, mirroring pi-persona's own `PI_AGENT_DIR || getAgentDir()`
|
|
88
|
+
* precedence so both extensions co-locate their data: an explicit override (tests) wins, else
|
|
89
|
+
* `PI_AGENT_DIR`, else `undefined` — signalling the caller to fall back to Pi's `getAgentDir()`
|
|
90
|
+
* (kept lazy so tests that inject a dir never invoke the SDK). Env is injectable for tests.
|
|
91
|
+
*/
|
|
92
|
+
export function preferredAgentDir(explicit: string | undefined, env: NodeJS.ProcessEnv = process.env): string | undefined {
|
|
93
|
+
if (explicit !== undefined) return explicit;
|
|
94
|
+
// Raw value with a truthiness check, exactly as pi-persona does (`PI_AGENT_DIR || getAgentDir()`);
|
|
95
|
+
// trimming here would make the two extensions resolve different dirs for a padded value.
|
|
96
|
+
const override = env.PI_AGENT_DIR;
|
|
97
|
+
return override ? override : undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface ProjectSlugOptions {
|
|
101
|
+
/** Injectable for tests and alternate filesystem providers; defaults to realpathSync.native. */
|
|
102
|
+
realpath?: (path: string) => string;
|
|
103
|
+
/** Injectable platform seam; defaults to the current Node platform. */
|
|
104
|
+
platform?: NodeJS.Platform | string;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Canonical project identity: resolved, realpathed, and case-folded on Windows. */
|
|
108
|
+
export function canonicalProjectIdentity(projectRoot: string, opts: ProjectSlugOptions = {}): string {
|
|
109
|
+
const platform = opts.platform ?? process.platform;
|
|
110
|
+
const resolved = platform === "win32" ? win32.resolve(projectRoot) : resolve(projectRoot);
|
|
111
|
+
// The default realpath provider is stable for a live project root and is the only path we cache.
|
|
112
|
+
// Injectable providers stay uncached so tests and alternate filesystems observe every call.
|
|
113
|
+
const cacheKey = opts.realpath === undefined ? `${platform}\0${platform === "win32" ? resolved.toLowerCase() : resolved}` : undefined;
|
|
114
|
+
if (cacheKey !== undefined) {
|
|
115
|
+
const cached = canonicalProjectCache.get(cacheKey);
|
|
116
|
+
if (cached !== undefined) return cached;
|
|
117
|
+
}
|
|
118
|
+
let canonical: string;
|
|
119
|
+
let cacheable = false;
|
|
120
|
+
try {
|
|
121
|
+
canonical = (opts.realpath ?? ((path: string) => realpathSync.native(path)))(resolved);
|
|
122
|
+
cacheable = true;
|
|
123
|
+
} catch {
|
|
124
|
+
canonical = resolved;
|
|
125
|
+
}
|
|
126
|
+
if (platform === "win32") canonical = canonical.toLowerCase();
|
|
127
|
+
if (cacheKey !== undefined && cacheable) {
|
|
128
|
+
if (canonicalProjectCache.size >= MAX_CANONICAL_CACHE_ENTRIES) {
|
|
129
|
+
const oldest = canonicalProjectCache.keys().next().value;
|
|
130
|
+
if (oldest !== undefined) canonicalProjectCache.delete(oldest);
|
|
131
|
+
}
|
|
132
|
+
canonicalProjectCache.set(cacheKey, canonical);
|
|
133
|
+
}
|
|
134
|
+
return canonical;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A stable per-project store name: sanitized basename + a 24-hex hash of the canonical path. */
|
|
138
|
+
export function projectSlug(projectRoot: string, opts: ProjectSlugOptions = {}): string {
|
|
139
|
+
const canonical = canonicalProjectIdentity(projectRoot, opts);
|
|
140
|
+
const hash = createHash("sha256").update(canonical).digest("hex").slice(0, 24);
|
|
141
|
+
const baseName = (opts.platform ?? process.platform) === "win32" ? win32.basename(canonical) : basename(canonical);
|
|
142
|
+
const base =
|
|
143
|
+
(baseName || "project")
|
|
144
|
+
.replace(/[^a-zA-Z0-9._-]+/g, "-")
|
|
145
|
+
.replace(/^-+|-+$/g, "")
|
|
146
|
+
.slice(0, 48) || "project";
|
|
147
|
+
return `${base}-${hash}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface ProjectRootOptions {
|
|
151
|
+
/** Never treat this directory as a git project root (typically the user's home). */
|
|
152
|
+
homedir?: string;
|
|
153
|
+
/** Equality used to compare walked directories against `homedir`. Defaults to string equality. */
|
|
154
|
+
samePath?: (a: string, b: string) => boolean;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Walk up from `startDir` to the nearest directory that satisfies `hasGit`; else return `startDir`.
|
|
158
|
+
* A git-initialized home directory is skipped so every folder under `~` does not share one backlog. */
|
|
159
|
+
export function findProjectRoot(startDir: string, hasGit: (dir: string) => boolean, opts: ProjectRootOptions = {}): string {
|
|
160
|
+
const home = opts.homedir;
|
|
161
|
+
const same = opts.samePath ?? ((a, b) => a === b);
|
|
162
|
+
let cur = startDir;
|
|
163
|
+
for (;;) {
|
|
164
|
+
if (hasGit(cur) && !(home !== undefined && same(cur, home))) return cur;
|
|
165
|
+
const parent = dirname(cur);
|
|
166
|
+
if (parent === cur) return startDir;
|
|
167
|
+
cur = parent;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Build store paths for a (persona, project-slug) pair. Inputs must be pre-sanitized. */
|
|
172
|
+
export function mindPaths(agentDir: string, persona: string, slug: string): ScopePaths {
|
|
173
|
+
const base = join(agentDir, "persona-mind");
|
|
174
|
+
return {
|
|
175
|
+
ltm: join(base, "memory", "ltm", `${persona}.json`),
|
|
176
|
+
shared: join(base, "memory", "ltm", `${SHARED_SCOPE}.json`),
|
|
177
|
+
projectLtm: join(base, "memory", "project", `${slug}.json`),
|
|
178
|
+
stm: join(base, "memory", "stm", `${slug}.json`),
|
|
179
|
+
backlog: join(base, "backlog", `${slug}.json`),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
export interface ScopeResolutionOptions {
|
|
185
|
+
/** Authoritative owner from the loaded companion; null explicitly means Persona is off. */
|
|
186
|
+
persona: string | null;
|
|
187
|
+
homedir?: string;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Resolve paths from an explicit live owner; never infer ownership from global settings. */
|
|
191
|
+
export function resolveScope(agentDir: string, cwd: string, opts: ScopeResolutionOptions): Scope {
|
|
192
|
+
if (!opts || (opts.persona !== null && (typeof opts.persona !== "string" || !opts.persona.trim()))) throw new Error("live persona owner is unavailable");
|
|
193
|
+
const rawPersona = opts.persona;
|
|
194
|
+
const persona = rawPersona ? sanitizePersona(rawPersona) : DEFAULT_PERSONA;
|
|
195
|
+
const home = opts.homedir ?? homedir();
|
|
196
|
+
const start = resolve(cwd);
|
|
197
|
+
const projectRoot = findProjectRoot(start, (d) => existsSync(join(d, ".git")), {
|
|
198
|
+
homedir: home,
|
|
199
|
+
samePath: (a, b) => canonicalProjectIdentity(a) === canonicalProjectIdentity(b),
|
|
200
|
+
});
|
|
201
|
+
const slug = projectSlug(projectRoot);
|
|
202
|
+
const paths = mindPaths(agentDir, persona, slug);
|
|
203
|
+
const homeWorkspace = canonicalProjectIdentity(projectRoot) === canonicalProjectIdentity(home);
|
|
204
|
+
return homeWorkspace ? { persona, projectRoot, slug, paths, homeWorkspace: true } : { persona, projectRoot, slug, paths };
|
|
205
|
+
}
|