@phren/cli 0.1.42 → 0.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/capabilities/cli.js +1 -1
  2. package/dist/capabilities/mcp.js +1 -1
  3. package/dist/capabilities/vscode.js +3 -3
  4. package/dist/capabilities/web-ui.js +29 -29
  5. package/dist/cli/hooks-output.js +15 -6
  6. package/dist/cli/hooks.js +2 -2
  7. package/dist/governance/scores.d.ts +9 -1
  8. package/dist/governance/scores.js +12 -1
  9. package/dist/init/init-uninstall.js +12 -2
  10. package/dist/profile-store.d.ts +2 -0
  11. package/dist/profile-store.js +13 -17
  12. package/dist/shared/fragment-graph.js +7 -2
  13. package/dist/shared/retrieval.d.ts +10 -0
  14. package/dist/shared/retrieval.js +17 -4
  15. package/dist/shell/entry.d.ts +8 -0
  16. package/dist/shell/entry.js +114 -58
  17. package/dist/shell/input.d.ts +1 -1
  18. package/dist/shell/input.js +4 -1
  19. package/dist/shell/keys.d.ts +36 -0
  20. package/dist/shell/keys.js +107 -0
  21. package/dist/shell/render.d.ts +33 -0
  22. package/dist/shell/render.js +216 -46
  23. package/dist/shell/shell.js +16 -3
  24. package/dist/shell/view.js +2 -1
  25. package/dist/store-registry.d.ts +13 -0
  26. package/dist/store-registry.js +106 -34
  27. package/dist/tools/memory.js +12 -5
  28. package/dist/tools/ops.js +1 -1
  29. package/package.json +31 -4
  30. package/starter/global/skills/phren-consolidate/SKILL.md +152 -0
  31. package/starter/global/skills/phren-discover/SKILL.md +175 -0
  32. package/starter/global/skills/phren-init/SKILL.md +216 -0
  33. package/starter/global/skills/phren-profiles/SKILL.md +121 -0
  34. package/starter/global/skills/phren-sync/SKILL.md +261 -0
  35. package/dist/init-uninstall.d.ts +0 -3
  36. package/dist/init-uninstall.js +0 -514
  37. package/dist/init-walkthrough.d.ts +0 -55
  38. package/dist/init-walkthrough.js +0 -524
@@ -37,22 +37,103 @@ export function separator(width = 50) {
37
37
  export function stripAnsi(s) {
38
38
  return s.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
39
39
  }
40
+ // ── Display width ────────────────────────────────────────────────────────────
41
+ // String length counts UTF-16 code units, which is not what a terminal draws:
42
+ // combining marks occupy no cell, and East Asian Wide / emoji-presentation
43
+ // characters occupy two. Measuring with .length under-counts those, so a line
44
+ // built to "fit" overflows, the terminal autowraps it, and every row below
45
+ // shifts — which corrupts the whole in-place redraw. Ambiguous-width characters
46
+ // are counted as one cell, matching the default in Windows Terminal and most
47
+ // Unix terminals.
48
+ const ZERO_WIDTH = /^\p{M}$/u;
49
+ // East Asian Wide/Fullwidth blocks plus the BMP characters with
50
+ // Emoji_Presentation=Yes (which terminals draw double-wide).
51
+ const WIDE_RANGES = [
52
+ [0x1100, 0x115f], [0x231a, 0x231b], [0x23e9, 0x23ec], [0x23f0, 0x23f0],
53
+ [0x23f3, 0x23f3], [0x25fd, 0x25fe], [0x2614, 0x2615], [0x2648, 0x2653],
54
+ [0x267f, 0x267f], [0x2693, 0x2693], [0x26a1, 0x26a1], [0x26aa, 0x26ab],
55
+ [0x26bd, 0x26be], [0x26c4, 0x26c5], [0x26ce, 0x26ce], [0x26d4, 0x26d4],
56
+ [0x26ea, 0x26ea], [0x26f2, 0x26f3], [0x26f5, 0x26f5], [0x26fa, 0x26fa],
57
+ [0x26fd, 0x26fd], [0x2705, 0x2705], [0x270a, 0x270b], [0x2728, 0x2728],
58
+ [0x274c, 0x274c], [0x274e, 0x274e], [0x2753, 0x2755], [0x2757, 0x2757],
59
+ [0x2795, 0x2797], [0x27b0, 0x27b0], [0x27bf, 0x27bf], [0x2b1b, 0x2b1c],
60
+ [0x2b50, 0x2b50], [0x2b55, 0x2b55], [0x2e80, 0x303e], [0x3041, 0x33ff],
61
+ [0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xa960, 0xa97f],
62
+ [0xac00, 0xd7a3], [0xf900, 0xfaff], [0xfe10, 0xfe19], [0xfe30, 0xfe6f],
63
+ [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f004, 0x1f004], [0x1f0cf, 0x1f0cf],
64
+ [0x1f18e, 0x1f18e], [0x1f191, 0x1f19a], [0x1f300, 0x1f64f],
65
+ [0x1f680, 0x1f6ff], [0x1f7e0, 0x1f7eb], [0x1f900, 0x1f9ff],
66
+ [0x1fa70, 0x1faff], [0x20000, 0x3fffd],
67
+ ];
68
+ function isWideCodePoint(cp) {
69
+ let lo = 0, hi = WIDE_RANGES.length - 1;
70
+ while (lo <= hi) {
71
+ const mid = (lo + hi) >> 1;
72
+ const range = WIDE_RANGES[mid];
73
+ if (cp < range[0])
74
+ hi = mid - 1;
75
+ else if (cp > range[1])
76
+ lo = mid + 1;
77
+ else
78
+ return true;
79
+ }
80
+ return false;
81
+ }
82
+ /** Terminal cells occupied by `s`, ignoring any ANSI escape codes it contains. */
83
+ export function displayWidth(s) {
84
+ const plain = stripAnsi(s);
85
+ let width = 0;
86
+ for (let i = 0; i < plain.length;) {
87
+ const cp = plain.codePointAt(i);
88
+ const size = cp > 0xffff ? 2 : 1;
89
+ i += size;
90
+ // Zero-width joiner, bidi/format controls and byte-order mark draw nothing.
91
+ if (cp === 0x200d || (cp >= 0x200b && cp <= 0x200f) || cp === 0xfeff)
92
+ continue;
93
+ // Variation selectors: VS16 promotes the previous character to emoji width.
94
+ if (cp >= 0xfe00 && cp <= 0xfe0f) {
95
+ if (cp === 0xfe0f)
96
+ width += 1;
97
+ continue;
98
+ }
99
+ if (cp >= 0xe0100 && cp <= 0xe01ef)
100
+ continue;
101
+ if (ZERO_WIDTH.test(String.fromCodePoint(cp)))
102
+ continue;
103
+ width += isWideCodePoint(cp) ? 2 : 1;
104
+ }
105
+ return width;
106
+ }
40
107
  function visibleWidth(s) {
41
- return stripAnsi(s).length;
108
+ return displayWidth(s);
109
+ }
110
+ /** Longest prefix of `plain` (unstyled) that fits in `cols` cells. */
111
+ function sliceToWidth(plain, cols) {
112
+ let width = 0;
113
+ for (let i = 0; i < plain.length;) {
114
+ const cp = plain.codePointAt(i);
115
+ const size = cp > 0xffff ? 2 : 1;
116
+ const next = displayWidth(String.fromCodePoint(cp));
117
+ if (width + next > cols)
118
+ return plain.slice(0, i);
119
+ width += next;
120
+ i += size;
121
+ }
122
+ return plain;
42
123
  }
43
124
  export function padToWidth(s, width) {
44
125
  if (width <= 0)
45
126
  return "";
46
127
  if (width === 1)
47
128
  return truncateLine(s, width);
48
- const visible = stripAnsi(s);
49
- if (visible.length > width)
50
- return visible.slice(0, width - 1) + "…";
51
- return s + " ".repeat(width - visible.length);
129
+ const visible = displayWidth(s);
130
+ if (visible > width)
131
+ return sliceToWidth(stripAnsi(s), width - 1) + "…";
132
+ return s + " ".repeat(width - visible);
52
133
  }
53
134
  // ANSI handling: `s` may contain ANSI escape codes (styled text from the style.*
54
- // helpers). We measure visible width via stripAnsi, then if truncation is needed we
55
- // slice the *plain* text (discarding ANSI codes) to avoid cutting mid-escape. A
135
+ // helpers). We measure visible width via displayWidth, then if truncation is needed
136
+ // we slice the *plain* text (discarding ANSI codes) to avoid cutting mid-escape. A
56
137
  // trailing reset is appended to guard against any residual SGR state from earlier
57
138
  // output on the same terminal line.
58
139
  export function truncateLine(s, cols) {
@@ -60,10 +141,9 @@ export function truncateLine(s, cols) {
60
141
  return "";
61
142
  if (cols === 1)
62
143
  return "…" + "\x1b[0m";
63
- const visible = stripAnsi(s);
64
- if (visible.length <= cols)
144
+ if (displayWidth(s) <= cols)
65
145
  return s;
66
- return visible.slice(0, cols - 1) + "…" + "\x1b[0m";
146
+ return sliceToWidth(stripAnsi(s), cols - 1) + "…" + "\x1b[0m";
67
147
  }
68
148
  // Reserve one column to avoid terminal autowrap when a line exactly fills the width.
69
149
  // Many terminals wrap on the last visible column, which corrupts full-screen redraws.
@@ -219,50 +299,140 @@ export function clearToEnd() {
219
299
  process.stdout.write("\x1b[J");
220
300
  }
221
301
  }
222
- export function shellStartupFrames(version) {
223
- const cols = process.stdout.columns || 80;
302
+ // Begin/End Synchronized Update (DEC private mode 2026). Terminals that support
303
+ // it buffer everything between the two and present the frame in one go, so a
304
+ // multi-kilobyte repaint never shows half-drawn. Terminals that don't support it
305
+ // ignore unknown private modes, so this is safe to send unconditionally.
306
+ const SYNC_BEGIN = "\x1b[?2026h";
307
+ const SYNC_END = "\x1b[?2026l";
308
+ const HIDE_CURSOR = "\x1b[?25l";
309
+ const SHOW_CURSOR = "\x1b[?25h";
310
+ // Autowrap off. The views already truncate to renderWidth(), but a single
311
+ // mismeasured line would otherwise wrap, push every row below it down, and
312
+ // scroll the frame out from under the cursor-home redraw — corrupting every
313
+ // subsequent frame. With autowrap off an over-long line is merely clipped.
314
+ const WRAP_OFF = "\x1b[?7l";
315
+ const WRAP_ON = "\x1b[?7h";
316
+ const ALT_SCREEN_ON = "\x1b[?1049h";
317
+ const ALT_SCREEN_OFF = "\x1b[?1049l";
318
+ /** Switch to the alternate screen buffer and put the terminal in TUI mode. */
319
+ export function enterFullscreen() {
320
+ if (!process.stdout.isTTY)
321
+ return;
322
+ process.stdout.write(ALT_SCREEN_ON);
323
+ process.stdout.write(HIDE_CURSOR);
324
+ process.stdout.write(WRAP_OFF);
325
+ }
326
+ /** Undo enterFullscreen(). Safe to call more than once. */
327
+ export function exitFullscreen() {
328
+ if (!process.stdout.isTTY)
329
+ return;
330
+ process.stdout.write(WRAP_ON);
331
+ process.stdout.write(SHOW_CURSOR);
332
+ process.stdout.write(ALT_SCREEN_OFF);
333
+ }
334
+ /**
335
+ * Write one frame as a single synchronized write.
336
+ *
337
+ * The old path issued three separate writes (home, body, erase-to-end) with the
338
+ * cursor visible, which let a concurrent repaint interleave between them and
339
+ * dragged the caret across the screen on every keystroke.
340
+ */
341
+ export function paintFrame(frame) {
342
+ // A frame with more lines than the terminal has rows scrolls the alternate
343
+ // buffer, and once it scrolls every later cursor-home repaint lands on
344
+ // shifted rows and the frames stack on top of each other. Clip the overflow
345
+ // (including a trailing newline on the last row) rather than scroll.
346
+ const rows = Math.max(1, process.stdout.rows || 24);
347
+ const lines = frame.split("\n");
348
+ const body = lines.length > rows ? lines.slice(0, rows).join("\n") : frame;
349
+ process.stdout.write(SYNC_BEGIN + "\x1b[H" + body + "\x1b[J" + SYNC_END);
350
+ }
351
+ // The character art is a fixed-size pixel grid; the gap keeps the logo off it.
352
+ const ART_WIDTH = 24;
353
+ const ART_GAP = 2;
354
+ const LOGO_WIDTH = Math.max(...PHREN_LOGO.map(displayWidth));
355
+ /**
356
+ * The wordmark line, split onto two rows when the terminal is too narrow to
357
+ * carry the tagline alongside the version badge.
358
+ */
359
+ function startupInfoLines(version, available) {
224
360
  const tagline = style.dim("local memory for working agents");
225
- const versionBadge = badge(`v${version}`, style.boldBlue);
226
- if (cols >= 72) {
227
- // Side-by-side: phren character on left, logo text on right
228
- const phrenLines = PHREN_STARTUP_ART;
229
- const logoLines = PHREN_LOGO.map(line => gradient(line));
230
- const infoLine = `${gradient("◆")} ${style.bold("phren")} ${versionBadge} ${tagline}`;
231
- // Logo is 6 lines, pad to align vertically with character center
232
- const rightSide = [
233
- "", "", ...logoLines, "", infoLine,
234
- ];
235
- // Merge side by side: character left (26 cols), logo right
236
- const charWidth = 26;
237
- const maxLines = Math.max(phrenLines.length, rightSide.length);
238
- const merged = [""];
239
- for (let i = 0; i < maxLines; i++) {
240
- const left = (i < phrenLines.length ? phrenLines[i] : "").padEnd(charWidth);
241
- const right = i < rightSide.length ? rightSide[i] : "";
242
- merged.push(left + right);
361
+ const head = `${gradient("◆")} ${style.bold("phren")} ${badge(`v${version}`, style.boldBlue)}`;
362
+ const single = `${head} ${tagline}`;
363
+ return displayWidth(single) <= available ? [single] : [head, tagline];
364
+ }
365
+ /**
366
+ * Lay out one splash frame from the character art the caller supplies (a live
367
+ * animation frame, or the static art).
368
+ *
369
+ * Every branch is chosen so the result fits the terminal it is about to be
370
+ * painted into: the wide layout needs room for art + gap + logo, the stacked
371
+ * one drops the logo rather than clipping it, and a terminal too short for the
372
+ * character drops the character rather than pushing the tagline off the bottom.
373
+ * A frame taller than the screen would scroll the alternate buffer, and once it
374
+ * scrolls every later cursor-home repaint lands on shifted rows, stacking the
375
+ * frames on top of each other.
376
+ */
377
+ export function composeStartupFrame(artLines, version, hint) {
378
+ const cols = renderWidth();
379
+ const rows = process.stdout.rows || 24;
380
+ const logoLines = PHREN_LOGO.map(line => gradient(line));
381
+ const hintLines = hint ? ["", ` ${hint}`] : [];
382
+ // One blank line above, one below, plus the hint block.
383
+ const budget = rows - 2 - hintLines.length;
384
+ const stackedInfo = startupInfoLines(version, cols - 2).map(line => ` ${line}`);
385
+ const sideBySide = () => {
386
+ // Logo is 6 lines; the leading blanks centre it against the character.
387
+ const rightSide = ["", "", ...logoLines, "", ...startupInfoLines(version, cols - ART_WIDTH - ART_GAP)];
388
+ const lines = [];
389
+ for (let i = 0; i < Math.max(artLines.length, rightSide.length); i++) {
390
+ // padToWidth measures display cells; String.padEnd counts the art's ANSI
391
+ // bytes as width and pads nothing at all.
392
+ const left = padToWidth(i < artLines.length ? artLines[i] : "", ART_WIDTH + ART_GAP);
393
+ lines.push(left + (i < rightSide.length ? rightSide[i] : ""));
243
394
  }
244
- merged.push("");
245
- return [
246
- // Frame 1: Logo with character side by side immediately
247
- merged.join("\n"),
248
- ];
249
- }
250
- if (cols >= 56) {
251
- // Medium terminal: stacked but compact
252
- const logo = PHREN_LOGO.map(line => " " + gradient(line));
253
- const sep = gradient("━".repeat(Math.min(52, cols)));
254
- return [
255
- ["", ...logo, ` ${sep}`, ` ${gradient("◆")} ${style.bold("phren")} ${versionBadge} ${tagline}`, ""].join("\n"),
256
- ];
395
+ return lines;
396
+ };
397
+ // Widest layout the terminal can carry, then progressively less of it: art
398
+ // beside the logo, art alone, logo alone, and finally just the wordmark.
399
+ const candidates = [];
400
+ if (cols >= ART_WIDTH + ART_GAP + LOGO_WIDTH)
401
+ candidates.push(sideBySide());
402
+ candidates.push([...artLines, "", ...stackedInfo]);
403
+ if (cols >= LOGO_WIDTH + 2)
404
+ candidates.push([...logoLines.map(line => ` ${line}`), "", ...stackedInfo]);
405
+ candidates.push(stackedInfo);
406
+ const body = candidates.find(lines => lines.length <= budget) ?? stackedInfo;
407
+ return ["", ...body, ...hintLines, ""];
408
+ }
409
+ /**
410
+ * Clamp a frame to the terminal before painting: truncate each line to the
411
+ * render width, erase whatever the previous frame left to the right of it, and
412
+ * drop rows past the bottom so the frame can never scroll the screen.
413
+ */
414
+ export function fitFrame(lines) {
415
+ const cols = renderWidth();
416
+ const rows = Math.max(1, process.stdout.rows || 24);
417
+ return lines
418
+ .slice(0, rows)
419
+ .map(line => truncateLine(line, cols) + "\x1b[K")
420
+ .join("\n");
421
+ }
422
+ export function shellStartupFrames(version) {
423
+ const cols = process.stdout.columns || 80;
424
+ if (cols >= 44) {
425
+ return [fitFrame(composeStartupFrame(PHREN_STARTUP_ART, version))];
257
426
  }
258
427
  // Narrow terminal: progressive text reveal with gradient
259
428
  const stages = ["p", "phr", "phren"];
260
429
  const spinners = ["◜", "◠", "◝"];
261
- return stages.map((stage, i) => [
430
+ const infoLines = startupInfoLines(version, renderWidth() - 2).map(line => ` ${line}`);
431
+ return stages.map((stage, i) => fitFrame([
262
432
  "",
263
433
  ` ${gradient(stage)} ${style.dim(spinners[i])}`,
264
434
  "",
265
- ` ${versionBadge} ${tagline}`,
435
+ ...infoLines,
266
436
  "",
267
- ].join("\n"));
437
+ ]));
268
438
  }
@@ -9,6 +9,16 @@ import { runDoctor } from "../link/link.js";
9
9
  import { renderShell, } from "./view.js";
10
10
  import { executePalette, completeInput as completeInputFn, getListItems, handleNavigateKey, applyViewShortcut, } from "./input.js";
11
11
  import { errorMessage } from "../utils.js";
12
+ /** Remove the final character, keeping surrogate pairs and combining marks intact. */
13
+ function dropLastCharacter(s) {
14
+ if (!s)
15
+ return s;
16
+ const chars = [...s];
17
+ chars.pop();
18
+ while (chars.length && /\p{M}/u.test(chars[chars.length - 1]))
19
+ chars.pop();
20
+ return chars.join("");
21
+ }
12
22
  // ── Shell class ──────────────────────────────────────────────────────────────
13
23
  export class PhrenShell {
14
24
  phrenPath;
@@ -198,12 +208,15 @@ export class PhrenShell {
198
208
  return true;
199
209
  }
200
210
  if (key === "\x7f" || key === "\x08") {
201
- this.inputBuf = this.inputBuf.slice(0, -1);
211
+ this.inputBuf = dropLastCharacter(this.inputBuf);
202
212
  return true;
203
213
  }
204
- if (key.startsWith("\x1b["))
214
+ if (key.startsWith("\x1b"))
205
215
  return true;
206
- if (key.length === 1 && key.charCodeAt(0) >= 32) {
216
+ // Accept any printable key. Astral characters (emoji, and anything else the
217
+ // user pastes) span two UTF-16 units, so this cannot test key.length === 1.
218
+ const cp = key.codePointAt(0);
219
+ if (cp !== undefined && cp >= 32 && cp !== 0x7f) {
207
220
  this.inputBuf += key;
208
221
  return true;
209
222
  }
@@ -193,7 +193,8 @@ function renderProjectsView(ctx, cursor, height) {
193
193
  const bullet = isActive ? style.green("●") : style.dim("○");
194
194
  const nameStr = isActive ? style.boldGreen(card.name) : style.bold(card.name);
195
195
  const docsStr = style.dim(`[A${card.activeCount} · Q${card.queueCount} · F${card.findingCount} · R${card.reviewCount}]`);
196
- let nameRow = ` ${cursorChar} ${bullet} ${nameStr} ${docsStr}`;
196
+ const storeStr = card.store ? ` ${style.dim("·")} ${style.cyan(card.store)}` : "";
197
+ let nameRow = ` ${cursorChar} ${bullet} ${nameStr} ${docsStr}${storeStr}`;
197
198
  let summaryRow = ` ${style.dim(card.summary || "No summary yet.")}`;
198
199
  if (isSelected) {
199
200
  nameRow = formatSelectableLine(nameRow, cols, true);
@@ -35,6 +35,19 @@ export interface TeamBootstrap {
35
35
  export declare const STORES_FILENAME = "stores.yaml";
36
36
  export declare function storesFilePath(phrenPath: string): string;
37
37
  export declare function generateStoreId(): string;
38
+ /**
39
+ * What a registry read actually found. `registry` is what could be honored;
40
+ * `problems` says what couldn't; `lossy` means stores.yaml EXISTS but the
41
+ * result does not fully represent it (unreadable, unparsable, entries
42
+ * skipped, or validation failed). Mutators must refuse to write while a read
43
+ * is lossy — writing back would silently destroy the entries we skipped.
44
+ */
45
+ export interface RegistryReadResult {
46
+ registry: StoreRegistry | null;
47
+ problems: string[];
48
+ lossy: boolean;
49
+ }
50
+ export declare function readStoreRegistryDetailed(phrenPath: string): RegistryReadResult;
38
51
  export declare function readStoreRegistry(phrenPath: string): StoreRegistry | null;
39
52
  export declare function writeStoreRegistry(phrenPath: string, registry: StoreRegistry): void;
40
53
  /** True when a store's directory exists on this machine. */
@@ -26,33 +26,57 @@ export function generateStoreId() {
26
26
  function deterministicIdFromPath(storePath) {
27
27
  return crypto.createHash("sha256").update(storePath).digest("hex").slice(0, 8);
28
28
  }
29
- // ── Read / Write ─────────────────────────────────────────────────────────────
30
- export function readStoreRegistry(phrenPath) {
29
+ export function readStoreRegistryDetailed(phrenPath) {
31
30
  const filePath = storesFilePath(phrenPath);
32
31
  if (!fs.existsSync(filePath))
33
- return null;
32
+ return { registry: null, problems: [], lossy: false };
34
33
  let raw;
35
34
  try {
36
35
  raw = fs.readFileSync(filePath, "utf8");
37
36
  }
38
- catch {
39
- return null;
37
+ catch (err) {
38
+ return { registry: null, problems: [`${STORES_FILENAME} is unreadable: ${String(err)}`], lossy: true };
40
39
  }
41
40
  let parsed;
42
41
  try {
43
42
  parsed = yaml.load(raw, { schema: yaml.CORE_SCHEMA });
44
43
  }
45
- catch {
46
- return null;
44
+ catch (err) {
45
+ return { registry: null, problems: [`${STORES_FILENAME} is not valid YAML: ${String(err)}`], lossy: true };
46
+ }
47
+ const problems = [];
48
+ const { registry, skippedEntries } = normalizeRegistry(parsed, problems);
49
+ if (!registry) {
50
+ return { registry: null, problems, lossy: true };
47
51
  }
48
- const registry = normalizeRegistry(parsed);
49
- if (!registry)
50
- return null;
51
52
  // Validate on read too — reject malformed registries before they reach hooks/sync
52
53
  const err = validateRegistry(registry);
53
- if (err)
54
- return null;
55
- return registry;
54
+ if (err) {
55
+ problems.push(`${STORES_FILENAME} failed validation: ${err}`);
56
+ return { registry: null, problems, lossy: true };
57
+ }
58
+ return { registry, problems, lossy: skippedEntries > 0 };
59
+ }
60
+ /** Registry read problems already warned about, keyed by path + content. */
61
+ const warnedRegistryProblems = new Set();
62
+ export function readStoreRegistry(phrenPath) {
63
+ const result = readStoreRegistryDetailed(phrenPath);
64
+ if (result.problems.length > 0) {
65
+ // Loud exactly once per process per distinct problem set: a malformed
66
+ // stores.yaml used to be swallowed as "no registry", which silently
67
+ // dropped every team store and re-routed their writes into the primary.
68
+ const signature = `${phrenPath}\n${result.problems.join("\n")}`;
69
+ if (!warnedRegistryProblems.has(signature)) {
70
+ warnedRegistryProblems.add(signature);
71
+ for (const problem of result.problems) {
72
+ console.warn(`phren: ${problem}`);
73
+ }
74
+ if (!result.registry) {
75
+ console.warn(`phren: ignoring ${storesFilePath(phrenPath)} and falling back to the primary store only — fix the file to restore multi-store routing.`);
76
+ }
77
+ }
78
+ }
79
+ return result.registry;
56
80
  }
57
81
  export function writeStoreRegistry(phrenPath, registry) {
58
82
  const err = validateRegistry(registry);
@@ -175,10 +199,27 @@ export function readTeamBootstrap(storePath) {
175
199
  }
176
200
  }
177
201
  // ── Registry mutation helpers ────────────────────────────────────────────────
202
+ /**
203
+ * A registry read that mutators are allowed to write back. A lossy read
204
+ * (stores.yaml exists but was unreadable, unparsable, or had entries skipped)
205
+ * must never round-trip through a writer: `addStoreToRegistry` used to treat
206
+ * that null as "first install" and OVERWRITE the user's malformed-but-real
207
+ * stores.yaml with a fresh single-store registry — one typo'd role plus one
208
+ * `phren store add` silently destroyed every other store entry.
209
+ */
210
+ function readRegistryForMutation(phrenPath) {
211
+ const result = readStoreRegistryDetailed(phrenPath);
212
+ if (result.lossy) {
213
+ throw new Error(`${PhrenError.VALIDATION_ERROR}: ${storesFilePath(phrenPath)} exists but could not be fully read — ` +
214
+ `refusing to rewrite it (that would drop the entries phren cannot parse). ` +
215
+ `Fix the file by hand first. Problems: ${result.problems.join(" | ")}`);
216
+ }
217
+ return result.registry;
218
+ }
178
219
  /** Add a store entry to the registry. Creates stores.yaml if needed. Uses file locking. */
179
220
  export function addStoreToRegistry(phrenPath, entry) {
180
221
  withFileLock(storesFilePath(phrenPath), () => {
181
- let registry = readStoreRegistry(phrenPath);
222
+ let registry = readRegistryForMutation(phrenPath);
182
223
  if (!registry) {
183
224
  // First time — also add the implicit primary store
184
225
  registry = { version: 1, stores: [implicitPrimaryStore(phrenPath)] };
@@ -193,7 +234,7 @@ export function addStoreToRegistry(phrenPath, entry) {
193
234
  /** Remove a store entry by name. Refuses to remove primary. Uses file locking. */
194
235
  export function removeStoreFromRegistry(phrenPath, name) {
195
236
  return withFileLock(storesFilePath(phrenPath), () => {
196
- const registry = readStoreRegistry(phrenPath);
237
+ const registry = readRegistryForMutation(phrenPath);
197
238
  if (!registry)
198
239
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
199
240
  const idx = registry.stores.findIndex((s) => s.name === name);
@@ -210,7 +251,7 @@ export function removeStoreFromRegistry(phrenPath, name) {
210
251
  /** Update the projects[] claim list for a store. Uses file locking. */
211
252
  export function updateStoreProjects(phrenPath, storeName, projects) {
212
253
  withFileLock(storesFilePath(phrenPath), () => {
213
- const registry = readStoreRegistry(phrenPath);
254
+ const registry = readRegistryForMutation(phrenPath);
214
255
  if (!registry)
215
256
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
216
257
  const store = registry.stores.find((s) => s.name === storeName);
@@ -223,7 +264,7 @@ export function updateStoreProjects(phrenPath, storeName, projects) {
223
264
  /** Add projects to a store's subscription list. Deduplicates. Uses file locking. */
224
265
  export function subscribeStoreProjects(phrenPath, storeName, projects) {
225
266
  withFileLock(storesFilePath(phrenPath), () => {
226
- const registry = readStoreRegistry(phrenPath);
267
+ const registry = readRegistryForMutation(phrenPath);
227
268
  if (!registry)
228
269
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
229
270
  const store = registry.stores.find((s) => s.name === storeName);
@@ -240,7 +281,7 @@ export function subscribeStoreProjects(phrenPath, storeName, projects) {
240
281
  /** Remove projects from a store's subscription list. Uses file locking. */
241
282
  export function unsubscribeStoreProjects(phrenPath, storeName, projects) {
242
283
  withFileLock(storesFilePath(phrenPath), () => {
243
- const registry = readStoreRegistry(phrenPath);
284
+ const registry = readRegistryForMutation(phrenPath);
244
285
  if (!registry)
245
286
  throw new Error(`${PhrenError.FILE_NOT_FOUND}: No stores.yaml found`);
246
287
  const store = registry.stores.find((s) => s.name === storeName);
@@ -284,28 +325,57 @@ function validateRegistry(registry) {
284
325
  return null;
285
326
  }
286
327
  // ── Normalization ────────────────────────────────────────────────────────────
287
- function normalizeRegistry(parsed) {
288
- if (!isRecord(parsed))
289
- return null;
290
- if (parsed.version !== 1)
291
- return null;
292
- if (!Array.isArray(parsed.stores))
293
- return null;
328
+ /** Aliases accepted on read for role values other tools/humans plausibly write. */
329
+ const ROLE_ALIASES = { secondary: "team" };
330
+ /**
331
+ * One bad entry used to discard the ENTIRE registry (`return null` mid-loop),
332
+ * with nothing logged — a single typo'd role silently dropped every team
333
+ * store. Now each invalid entry is skipped with a reason pushed to
334
+ * `problems`, and the valid remainder is kept. Callers see `skippedEntries`
335
+ * so mutators can refuse to persist a lossy read.
336
+ */
337
+ function normalizeRegistry(parsed, problems) {
338
+ if (!isRecord(parsed) || parsed.version !== 1 || !Array.isArray(parsed.stores)) {
339
+ problems.push(`${STORES_FILENAME} has an unrecognized shape (expected \`version: 1\` and a \`stores:\` list).`);
340
+ return { registry: null, skippedEntries: 0 };
341
+ }
294
342
  const stores = [];
295
- for (const raw of parsed.stores) {
296
- if (!isRecord(raw))
297
- return null;
343
+ let skippedEntries = 0;
344
+ for (const [index, raw] of parsed.stores.entries()) {
345
+ const skip = (label, reason) => {
346
+ skippedEntries += 1;
347
+ problems.push(`${STORES_FILENAME}: store ${label} ${reason} — entry skipped.`);
348
+ };
349
+ if (!isRecord(raw)) {
350
+ skip(`#${index + 1}`, "is not a mapping");
351
+ continue;
352
+ }
298
353
  const id = typeof raw.id === "string" ? raw.id : "";
299
354
  const name = typeof raw.name === "string" ? raw.name : "";
355
+ const label = name ? `"${name}"` : `#${index + 1}`;
300
356
  const rawPath = typeof raw.path === "string" ? raw.path : "";
301
- const role = typeof raw.role === "string" && isStoreRole(raw.role) ? raw.role : null;
357
+ const rawRole = typeof raw.role === "string" ? raw.role : "";
358
+ const aliasedRole = ROLE_ALIASES[rawRole];
359
+ if (aliasedRole) {
360
+ problems.push(`${STORES_FILENAME}: store ${label} has role "${rawRole}" — reading it as "${aliasedRole}" (valid roles: primary|team|readonly).`);
361
+ }
362
+ const roleValue = aliasedRole ?? rawRole;
363
+ const role = isStoreRole(roleValue) ? roleValue : null;
302
364
  const sync = typeof raw.sync === "string" && isStoreSyncMode(raw.sync) ? raw.sync : "managed-git";
303
365
  const remote = typeof raw.remote === "string" ? raw.remote : undefined;
304
366
  const projects = Array.isArray(raw.projects)
305
367
  ? raw.projects.filter((p) => typeof p === "string")
306
368
  : undefined;
307
- if (!id || !name || !rawPath || !role)
308
- return null;
369
+ if (!id || !name || !rawPath || !role) {
370
+ const missing = [
371
+ !id && "id",
372
+ !name && "name",
373
+ !rawPath && "path",
374
+ !role && `a valid role (got "${rawRole || "(none)"}")`,
375
+ ].filter(Boolean);
376
+ skip(label, `is missing ${missing.join(", ")}`);
377
+ continue;
378
+ }
309
379
  stores.push({
310
380
  id,
311
381
  name,
@@ -316,9 +386,11 @@ function normalizeRegistry(parsed) {
316
386
  projects: projects && projects.length > 0 ? projects : undefined,
317
387
  });
318
388
  }
319
- if (stores.length === 0)
320
- return null;
321
- return { version: 1, stores };
389
+ if (stores.length === 0) {
390
+ problems.push(`${STORES_FILENAME} contains no usable store entries.`);
391
+ return { registry: null, skippedEntries };
392
+ }
393
+ return { registry: { version: 1, stores }, skippedEntries };
322
394
  }
323
395
  // ── Internal helpers ─────────────────────────────────────────────────────────
324
396
  function implicitPrimaryStore(phrenPath) {
@@ -6,6 +6,12 @@ import { runtimeDir } from "../shared.js";
6
6
  import { recordFeedback, flushEntryScores, } from "../shared/governance.js";
7
7
  import { upsertCanonical } from "../shared/content.js";
8
8
  import { isValidProjectName } from "../utils.js";
9
+ import { storeAwareProjectPath } from "../store-routing.js";
10
+ /** truths.md path via the same store-aware routing upsertCanonical writes with. */
11
+ function truthsFilePath(phrenPath, project) {
12
+ return storeAwareProjectPath(phrenPath, project, "truths.md")
13
+ ?? path.join(phrenPath, project, "truths.md");
14
+ }
9
15
  export function register(server, ctx) {
10
16
  const { withWriteQueue, updateFileInIndex } = ctx;
11
17
  server.registerTool("pin_memory", {
@@ -32,8 +38,7 @@ export function register(server, ctx) {
32
38
  const result = upsertCanonical(phrenPath, project, memory);
33
39
  if (!result.ok)
34
40
  return mcpResponse({ ok: false, error: result.error });
35
- const canonicalPath = path.join(phrenPath, project, "truths.md");
36
- updateFileInIndex(canonicalPath);
41
+ updateFileInIndex(truthsFilePath(phrenPath, project));
37
42
  return mcpResponse({ ok: true, message: result.data, data: { project, memory } });
38
43
  });
39
44
  });
@@ -56,7 +61,7 @@ export function register(server, ctx) {
56
61
  }
57
62
  if (!isValidProjectName(project))
58
63
  return mcpResponse({ ok: false, error: `Invalid project name: "${project}"` });
59
- const truthsPath = path.join(phrenPath, project, "truths.md");
64
+ const truthsPath = truthsFilePath(phrenPath, project);
60
65
  if (!fs.existsSync(truthsPath)) {
61
66
  return mcpResponse({ ok: true, message: `No truths pinned for "${project}" yet.`, data: { project, truths: [], count: 0 } });
62
67
  }
@@ -74,9 +79,11 @@ export function register(server, ctx) {
74
79
  });
75
80
  server.registerTool("memory_feedback", {
76
81
  title: "◆ phren · feedback",
77
- description: "Record feedback on whether an injected memory was helpful or noisy/regressive.",
82
+ description: "Record feedback on whether an injected memory was helpful or noisy/regressive. " +
83
+ "The key is printed in <phren-context> snippet headers as `fb:<project>/<file>:<digest>` — pass that token (with or without the `fb:` prefix). " +
84
+ "Feedback adjusts that memory's ranking weight in future injections.",
78
85
  inputSchema: z.object({
79
- key: z.string().describe("Memory key to score."),
86
+ key: z.string().describe("Feedback key from an injected snippet header, e.g. `fb:myproj/FINDINGS.md:a1b2c3d4e5f6` or `myproj/FINDINGS.md:a1b2c3d4e5f6`."),
80
87
  feedback: z.enum(["helpful", "reprompt", "regression"]).describe("Feedback type."),
81
88
  }),
82
89
  }, async ({ key, feedback }) => {
package/dist/tools/ops.js CHANGED
@@ -494,7 +494,7 @@ export function register(server, ctx) {
494
494
  }, (params) => handleGetReviewQueue(ctx, params));
495
495
  server.registerTool("manage_review_item", {
496
496
  title: "◆ phren · manage review item",
497
- description: "Manage a review queue item: approve (removes from queue, finding stays), reject (removes from queue AND FINDINGS.md), or edit (updates text in both).",
497
+ description: "Manage a review queue item: approve (PROMOTES the queued line into FINDINGS.md — if the finding is already present or archived it just dequeues), reject (removes from queue AND FINDINGS.md), or edit (updates text in both).",
498
498
  inputSchema: z.object({
499
499
  project: z.string().describe("Project name."),
500
500
  line: z.string().max(10000).describe("The raw queue line text (as returned by get_review_queue)."),