@phren/cli 0.1.42 → 0.1.45

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 (97) 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/actions.d.ts +1 -1
  6. package/dist/cli/actions.js +7 -2
  7. package/dist/cli/config-proactivity.d.ts +6 -6
  8. package/dist/cli/hooks-output.js +15 -6
  9. package/dist/cli/hooks.d.ts +1 -1
  10. package/dist/cli/hooks.js +16 -5
  11. package/dist/cli/session-stop.d.ts +1 -1
  12. package/dist/cli/session-tool-hook.d.ts +1 -1
  13. package/dist/cli-registry.js +1 -1
  14. package/dist/data/access.js +2 -1
  15. package/dist/generated/memory-ui-graph.browser.js +481 -318
  16. package/dist/governance/locks.js +6 -0
  17. package/dist/governance/scores.d.ts +9 -1
  18. package/dist/governance/scores.js +12 -1
  19. package/dist/graph-core/index.d.ts +2 -0
  20. package/dist/graph-core/index.js +2 -0
  21. package/dist/graph-core/model.d.ts +84 -0
  22. package/dist/graph-core/model.js +355 -0
  23. package/dist/graph-core/types.d.ts +110 -0
  24. package/dist/graph-core/types.js +43 -0
  25. package/dist/index.js +4 -1
  26. package/dist/init/init-uninstall.d.ts +1 -0
  27. package/dist/init/init-uninstall.js +13 -3
  28. package/dist/init/setup.js +11 -4
  29. package/dist/link/context.js +2 -1
  30. package/dist/link/link.js +3 -2
  31. package/dist/link/skills.js +2 -1
  32. package/dist/memory-ui-graph.runtime.js +481 -318
  33. package/dist/phren-core.d.ts +16 -0
  34. package/dist/phren-core.js +21 -0
  35. package/dist/phren-paths.js +8 -4
  36. package/dist/profile-store.d.ts +2 -0
  37. package/dist/profile-store.js +16 -19
  38. package/dist/project-config.js +2 -1
  39. package/dist/shared/fragment-graph.js +7 -2
  40. package/dist/shared/index.js +1 -1
  41. package/dist/shared/retrieval.d.ts +38 -0
  42. package/dist/shared/retrieval.js +62 -4
  43. package/dist/shell/entry.d.ts +10 -2
  44. package/dist/shell/entry.js +128 -97
  45. package/dist/shell/graph/canvas.d.ts +64 -0
  46. package/dist/shell/graph/canvas.js +256 -0
  47. package/dist/shell/graph/controller.d.ts +164 -0
  48. package/dist/shell/graph/controller.js +645 -0
  49. package/dist/shell/graph/glyphs.d.ts +12 -0
  50. package/dist/shell/graph/glyphs.js +31 -0
  51. package/dist/shell/graph/graph-view.d.ts +12 -0
  52. package/dist/shell/graph/graph-view.js +408 -0
  53. package/dist/shell/graph/layout.d.ts +68 -0
  54. package/dist/shell/graph/layout.js +267 -0
  55. package/dist/shell/input.d.ts +4 -1
  56. package/dist/shell/input.js +28 -5
  57. package/dist/shell/intro.d.ts +37 -0
  58. package/dist/shell/intro.js +82 -0
  59. package/dist/shell/keys.d.ts +36 -0
  60. package/dist/shell/keys.js +107 -0
  61. package/dist/shell/logo-fx.d.ts +35 -0
  62. package/dist/shell/logo-fx.js +128 -0
  63. package/dist/shell/render.d.ts +34 -1
  64. package/dist/shell/render.js +220 -66
  65. package/dist/shell/shell.d.ts +13 -1
  66. package/dist/shell/shell.js +61 -10
  67. package/dist/shell/startup.d.ts +37 -0
  68. package/dist/shell/startup.js +105 -0
  69. package/dist/shell/state-store.d.ts +1 -1
  70. package/dist/shell/state-store.js +1 -1
  71. package/dist/shell/types.js +1 -0
  72. package/dist/shell/view.d.ts +3 -0
  73. package/dist/shell/view.js +26 -4
  74. package/dist/store-registry.d.ts +13 -0
  75. package/dist/store-registry.js +109 -37
  76. package/dist/test-global-setup.d.ts +1 -0
  77. package/dist/test-global-setup.js +22 -0
  78. package/dist/tool-registry.js +1 -0
  79. package/dist/tools/memory.js +12 -5
  80. package/dist/tools/ops.js +1 -1
  81. package/dist/ui/data.d.ts +15 -7
  82. package/dist/ui/data.js +102 -3
  83. package/dist/utils-fts.js +2 -1
  84. package/dist/utils-helpers.d.ts +1 -0
  85. package/dist/utils-helpers.js +6 -0
  86. package/dist/utils.d.ts +1 -1
  87. package/dist/utils.js +1 -1
  88. package/package.json +38 -7
  89. package/starter/global/skills/phren-consolidate/SKILL.md +152 -0
  90. package/starter/global/skills/phren-discover/SKILL.md +175 -0
  91. package/starter/global/skills/phren-init/SKILL.md +216 -0
  92. package/starter/global/skills/phren-profiles/SKILL.md +121 -0
  93. package/starter/global/skills/phren-sync/SKILL.md +261 -0
  94. package/dist/init-uninstall.d.ts +0 -3
  95. package/dist/init-uninstall.js +0 -514
  96. package/dist/init-walkthrough.d.ts +0 -55
  97. package/dist/init-walkthrough.js +0 -524
@@ -4,7 +4,7 @@ import * as path from "path";
4
4
  import * as yaml from "js-yaml";
5
5
  import { expandHomePath, atomicWriteText } from "./phren-paths.js";
6
6
  import { withFileLock } from "./governance/locks.js";
7
- import { isRecord, PhrenError } from "./phren-core.js";
7
+ import { isRecord, loadYamlDocument, PhrenError } from "./phren-core.js";
8
8
  import { getProjectDirs } from "./shared.js";
9
9
  // ── Constants ────────────────────────────────────────────────────────────────
10
10
  export const STORES_FILENAME = "stores.yaml";
@@ -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
- parsed = yaml.load(raw, { schema: yaml.CORE_SCHEMA });
42
+ parsed = loadYamlDocument(raw, (text) => yaml.load(text, { 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);
@@ -159,7 +183,7 @@ export function readTeamBootstrap(storePath) {
159
183
  return null;
160
184
  try {
161
185
  const raw = fs.readFileSync(filePath, "utf8");
162
- const parsed = yaml.load(raw, { schema: yaml.CORE_SCHEMA });
186
+ const parsed = loadYamlDocument(raw, (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
163
187
  if (!isRecord(parsed) || typeof parsed.name !== "string")
164
188
  return null;
165
189
  return {
@@ -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) {
@@ -11,4 +11,5 @@
11
11
  * - Watch mode re-runs where pretest does not re-fire
12
12
  * - CI environments that skip npm lifecycle scripts
13
13
  */
14
+ export declare function teardown(): Promise<void>;
14
15
  export declare function setup(): Promise<void>;
@@ -13,13 +13,35 @@
13
13
  */
14
14
  import { execFileSync } from "child_process";
15
15
  import * as fs from "fs";
16
+ import * as os from "os";
16
17
  import * as path from "path";
17
18
  import { fileURLToPath } from "url";
18
19
  const __filename = fileURLToPath(import.meta.url);
19
20
  const __dirname = path.dirname(__filename);
20
21
  const REPO_ROOT = path.resolve(__dirname, "../../..");
21
22
  const CLI_PATH = path.join(REPO_ROOT, "packages", "cli", "dist", "index.js");
23
+ let sandboxHome = null;
24
+ /**
25
+ * Point HOME (and USERPROFILE) at a throwaway directory for the whole run.
26
+ *
27
+ * `pool: "forks"` workers inherit this process's env, and on Linux/macOS
28
+ * `os.homedir()` reads $HOME too, so this covers every route the CLI uses to
29
+ * find the user's home. Without it, isolation depends on each test
30
+ * remembering to override HOME — and the ones that forgot (e.g. the web-ui
31
+ * readiness test) re-pointed the developer's real ~/.claude/CLAUDE.md and
32
+ * ~/.claude/skills/phren-* at temp dirs that were deleted seconds later.
33
+ */
34
+ function sandboxHomeDir() {
35
+ sandboxHome = fs.mkdtempSync(path.join(os.tmpdir(), "phren-test-home-"));
36
+ process.env.HOME = sandboxHome;
37
+ process.env.USERPROFILE = sandboxHome;
38
+ }
39
+ export async function teardown() {
40
+ if (sandboxHome)
41
+ fs.rmSync(sandboxHome, { recursive: true, force: true });
42
+ }
22
43
  export async function setup() {
44
+ sandboxHomeDir();
23
45
  if (fs.existsSync(CLI_PATH)) {
24
46
  // Dist already present — skip build. This is the common path when
25
47
  // `npm test` is used (pretest already built it) or during watch mode
@@ -5,6 +5,7 @@ const CATEGORY_BY_MODULE = {
5
5
  "search": "Search and browse",
6
6
  "tasks": "Task management",
7
7
  "finding": "Finding capture",
8
+ "notes": "Notes",
8
9
  "memory": "Memory quality",
9
10
  "data": "Data management",
10
11
  "graph": "Fragments and graph",
@@ -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)."),
package/dist/ui/data.d.ts CHANGED
@@ -1,13 +1,13 @@
1
1
  import type { SqlJsDatabase } from "../shared/index.js";
2
2
  import { type LookupEvent } from "../governance/activity.js";
3
- interface EntryScore {
3
+ export interface EntryScore {
4
4
  impressions: number;
5
5
  helpful: number;
6
6
  repromptPenalty: number;
7
7
  regressionPenalty: number;
8
8
  lastUsedAt: string;
9
9
  }
10
- interface GraphNode {
10
+ export interface GraphNode {
11
11
  id: string;
12
12
  label: string;
13
13
  fullLabel: string;
@@ -30,18 +30,26 @@ interface GraphNode {
30
30
  findingCount?: number;
31
31
  taskCount?: number;
32
32
  }
33
- interface GraphDocRef {
33
+ export interface GraphDocRef {
34
34
  doc: string;
35
35
  project: string;
36
36
  scoreKey?: string;
37
37
  }
38
- interface GraphTopicMeta {
38
+ export interface GraphTopicMeta {
39
39
  slug: string;
40
40
  label: string;
41
41
  }
42
- interface GraphLink {
42
+ export interface GraphLink {
43
43
  source: string;
44
44
  target: string;
45
+ /** Absent for the default project→leaf spoke; set for the opt-in enrichment edges. */
46
+ kind?: "fragment" | "supersedes" | "contradicts";
47
+ }
48
+ export interface BuildGraphOptions {
49
+ /** Fragment↔fragment edges for fragments co-mentioned in the same documents. */
50
+ includeFragmentEdges?: boolean;
51
+ /** Finding→finding edges from `supersedes` / `contradicts` lifecycle annotations. */
52
+ includeLifecycleEdges?: boolean;
45
53
  }
46
54
  interface ProjectInfo {
47
55
  name: string;
@@ -92,7 +100,7 @@ export declare function collectSkillsForUI(phrenPath: string, profile?: string):
92
100
  export declare function getHooksData(phrenPath: string, profile?: string): {
93
101
  globalEnabled: boolean;
94
102
  tools: {
95
- tool: "claude" | "copilot" | "cursor" | "codex";
103
+ tool: "claude" | "codex" | "copilot" | "cursor";
96
104
  enabled: boolean;
97
105
  configPath: string;
98
106
  exists: boolean;
@@ -108,7 +116,7 @@ export declare function getHooksData(phrenPath: string, profile?: string): {
108
116
  }>;
109
117
  }[];
110
118
  };
111
- export declare function buildGraph(phrenPath: string, profile?: string, focusProject?: string, existingDb?: SqlJsDatabase | null): Promise<{
119
+ export declare function buildGraph(phrenPath: string, profile?: string, focusProject?: string, existingDb?: SqlJsDatabase | null, opts?: BuildGraphOptions): Promise<{
112
120
  nodes: GraphNode[];
113
121
  links: GraphLink[];
114
122
  total: number;
package/dist/ui/data.js CHANGED
@@ -10,13 +10,32 @@ import { hookConfigPaths, hookConfigRoots } from "../provider-adapters.js";
10
10
  import { readProjectConfig, isProjectHookEnabled, PROJECT_HOOK_EVENTS } from "../project-config.js";
11
11
  import { getAllSkills } from "../skill/registry.js";
12
12
  import { resolveTaskFilePath, readTasks, TASKS_FILENAME } from "../data/tasks.js";
13
- import { FINDINGS_FILENAME } from "../data/access.js";
13
+ import { FINDINGS_FILENAME, readFindings } from "../data/access.js";
14
14
  import { buildIndex, queryDocBySourceKey, queryRows } from "../shared/index.js";
15
15
  import { readProjectTopics, classifyTopicForText } from "../project-topics.js";
16
16
  import { entryScoreKey } from "../governance/scores.js";
17
17
  import { findingStableId } from "../finding-graph-id.js";
18
18
  import { readRecentLookups } from "../governance/activity.js";
19
19
  import { logger } from "../logger.js";
20
+ /** `[tag] text` → `text`, lower-cased, for matching lifecycle snippets against node labels. */
21
+ function lifecycleKey(text) {
22
+ return text.replace(/^\[[a-z_-]+\]\s+/i, "").trim().toLowerCase();
23
+ }
24
+ /**
25
+ * Resolve a 60-char lifecycle snippet to a finding node of the same project.
26
+ * Either side may be the prefix of the other: the snippet is truncated, and
27
+ * the node label may itself be shorter than 60 chars.
28
+ */
29
+ function resolveLifecycleRef(snippet, candidates) {
30
+ const key = lifecycleKey(snippet);
31
+ if (!key)
32
+ return undefined;
33
+ for (const candidate of candidates) {
34
+ if (candidate.key.startsWith(key) || key.startsWith(candidate.key))
35
+ return candidate.nodeId;
36
+ }
37
+ return undefined;
38
+ }
20
39
  function extractGithubUrl(content) {
21
40
  const match = content.match(/https?:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/);
22
41
  return match ? match[0] : undefined;
@@ -160,7 +179,7 @@ export function getHooksData(phrenPath, profile) {
160
179
  }
161
180
  return { globalEnabled, tools, customHooks: readCustomHooks(phrenPath), projectOverrides };
162
181
  }
163
- export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
182
+ export async function buildGraph(phrenPath, profile, focusProject, existingDb, opts = {}) {
164
183
  // Collect projects from primary store and all readable non-primary stores
165
184
  const storeProjects = [];
166
185
  const primaryProjects = getProjectDirs(phrenPath, profile)
@@ -205,6 +224,15 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
205
224
  usedFindingIds.set(id, seen + 1);
206
225
  return seen === 0 ? id : `${id}-${seen + 1}`;
207
226
  };
227
+ // Finding text → node id per project, for resolving lifecycle snippets.
228
+ const findingKeysByProject = new Map();
229
+ const rememberFinding = (project, text, nodeId) => {
230
+ if (!opts.includeLifecycleEdges)
231
+ return;
232
+ const list = findingKeysByProject.get(project) ?? [];
233
+ list.push({ key: lifecycleKey(text), nodeId });
234
+ findingKeysByProject.set(project, list);
235
+ };
208
236
  for (const { storePath, project } of storeProjects) {
209
237
  // Load dynamic topics for this project
210
238
  const { topics: projectTopics } = readProjectTopics(storePath, project);
@@ -318,6 +346,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
318
346
  date: currentDate,
319
347
  });
320
348
  links.push({ source: project, target: nodeId });
349
+ rememberFinding(project, text, nodeId);
321
350
  for (const other of exactProjectMentions(text, projectSet, project)) {
322
351
  links.push({ source: project, target: other });
323
352
  }
@@ -354,6 +383,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
354
383
  date: currentDate,
355
384
  });
356
385
  links.push({ source: project, target: nodeId });
386
+ rememberFinding(project, text, nodeId);
357
387
  for (const other of exactProjectMentions(text, projectSet, project)) {
358
388
  links.push({ source: project, target: other });
359
389
  }
@@ -390,12 +420,43 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
390
420
  date: currentDate,
391
421
  });
392
422
  links.push({ source: project, target: nodeId });
423
+ rememberFinding(project, text, nodeId);
393
424
  }
394
425
  const projectNode = projectNodeByName.get(project);
395
426
  if (projectNode) {
396
427
  projectNode.findingCount = (projectNode.findingCount || 0) + taggedCount + untaggedAdded;
397
428
  }
398
429
  }
430
+ // ── Lifecycle edges (opt-in) ─────────────────────────────────────────
431
+ if (opts.includeLifecycleEdges) {
432
+ for (const { storePath, project } of storeProjects) {
433
+ const candidates = findingKeysByProject.get(project);
434
+ if (!candidates?.length)
435
+ continue;
436
+ const result = readFindings(storePath, project);
437
+ if (!result.ok)
438
+ continue;
439
+ for (const item of result.data) {
440
+ if (!item.supersedes && !item.supersededBy && !item.contradicts?.length)
441
+ continue;
442
+ const self = resolveLifecycleRef(item.text, candidates);
443
+ if (!self)
444
+ continue;
445
+ const edge = (snippet, kind, newerFirst) => {
446
+ const other = resolveLifecycleRef(snippet, candidates);
447
+ if (!other || other === self)
448
+ return;
449
+ links.push(newerFirst ? { source: self, target: other, kind } : { source: other, target: self, kind });
450
+ };
451
+ if (item.supersedes)
452
+ edge(item.supersedes, "supersedes", true);
453
+ if (item.supersededBy)
454
+ edge(item.supersededBy, "supersedes", false);
455
+ for (const snippet of item.contradicts ?? [])
456
+ edge(snippet, "contradicts", true);
457
+ }
458
+ }
459
+ }
399
460
  // ── Tasks ──────────────────────────────────────────────────────────
400
461
  try {
401
462
  for (const { storePath, project } of storeProjects) {
@@ -479,6 +540,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
479
540
  refsByEntity.set(entityId, refs);
480
541
  }
481
542
  }
543
+ const entityNodeIds = new Map();
482
544
  if (rows) {
483
545
  for (const row of rows) {
484
546
  const entityId = typeof row[0] === "number" ? row[0] : -1;
@@ -517,7 +579,44 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
517
579
  for (const proj of linkedProjects) {
518
580
  links.push({ source: nodeId, target: proj });
519
581
  }
582
+ entityNodeIds.set(entityId, nodeId);
583
+ }
584
+ }
585
+ // ── Fragment co-occurrence edges (opt-in) ──────────────────────────
586
+ // Two fragments mentioned by the same document are related; the more
587
+ // documents they share, the stronger the tie. Derived from refsByEntity,
588
+ // so no extra SQL.
589
+ if (opts.includeFragmentEdges && entityNodeIds.size > 1) {
590
+ const MAX_ENTITIES_PER_DOC = 40;
591
+ const MAX_FRAGMENT_EDGES = 400;
592
+ const entitiesByDoc = new Map();
593
+ for (const [entityId, nodeId] of entityNodeIds) {
594
+ for (const ref of refsByEntity.get(entityId) ?? []) {
595
+ const list = entitiesByDoc.get(ref.doc) ?? [];
596
+ if (list.length < MAX_ENTITIES_PER_DOC && !list.includes(nodeId))
597
+ list.push(nodeId);
598
+ entitiesByDoc.set(ref.doc, list);
599
+ }
600
+ }
601
+ const pairCounts = new Map();
602
+ for (const members of entitiesByDoc.values()) {
603
+ const sorted = members.slice().sort();
604
+ for (let i = 0; i < sorted.length; i++) {
605
+ for (let j = i + 1; j < sorted.length; j++) {
606
+ const key = `${sorted[i]}||${sorted[j]}`;
607
+ const entry = pairCounts.get(key) ?? { a: sorted[i], b: sorted[j], count: 0 };
608
+ entry.count++;
609
+ pairCounts.set(key, entry);
610
+ }
611
+ }
520
612
  }
613
+ const ranked = Array.from(pairCounts.values()).sort((x, y) => y.count - x.count || x.a.localeCompare(y.a) || x.b.localeCompare(y.b));
614
+ // Prefer pairs that co-occur in several docs; on a small store fall back
615
+ // to single co-mentions so the fragment layer still has structure.
616
+ const strong = ranked.filter((pair) => pair.count >= 2);
617
+ const chosen = (strong.length >= 20 ? strong : ranked).slice(0, MAX_FRAGMENT_EDGES);
618
+ for (const pair of chosen)
619
+ links.push({ source: pair.a, target: pair.b, kind: "fragment" });
521
620
  }
522
621
  }
523
622
  catch {
@@ -582,7 +681,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
582
681
  }
583
682
  const seen = new Set();
584
683
  const dedupedLinks = links.filter((link) => {
585
- const key = [link.source, link.target].sort().join("||");
684
+ const key = `${[link.source, link.target].sort().join("||")}::${link.kind ?? ""}`;
586
685
  if (seen.has(key))
587
686
  return false;
588
687
  seen.add(key);
package/dist/utils-fts.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
3
  import * as yaml from "js-yaml";
4
+ import { loadYamlDocument } from "./phren-core.js";
4
5
  import { fileURLToPath } from "url";
5
6
  import { findPhrenPath } from "./phren-paths.js";
6
7
  import { isValidProjectName } from "./utils-paths.js";
@@ -122,7 +123,7 @@ function parseSynonymsYaml(filePath) {
122
123
  if (!fs.existsSync(filePath))
123
124
  return {};
124
125
  try {
125
- const parsed = yaml.load(fs.readFileSync(filePath, "utf8"), { schema: yaml.CORE_SCHEMA });
126
+ const parsed = loadYamlDocument(fs.readFileSync(filePath, "utf8"), (text) => yaml.load(text, { schema: yaml.CORE_SCHEMA }));
126
127
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
127
128
  return {};
128
129
  const loaded = {};
@@ -9,6 +9,7 @@ export declare function resolveExecCommand(cmd: string): ResolvedExecCommand;
9
9
  export declare function errorMessage(err: unknown): string;
10
10
  export declare function isFeatureEnabled(envName: string, defaultValue?: boolean): boolean;
11
11
  export declare function clampInt(raw: string | undefined, fallback: number, min: number, max: number): number;
12
+ export declare function clampFloat(raw: string | undefined, fallback: number, min: number, max: number): number;
12
13
  export declare function getOptionValue(args: string[], name: string): string | undefined;
13
14
  export declare function getPositionalArgs(args: string[], optionNamesWithValues: string[]): string[];
14
15
  export {};
@@ -78,6 +78,12 @@ export function clampInt(raw, fallback, min, max) {
78
78
  return fallback;
79
79
  return Math.min(max, Math.max(min, parsed));
80
80
  }
81
+ export function clampFloat(raw, fallback, min, max) {
82
+ const parsed = Number.parseFloat(raw || "");
83
+ if (Number.isNaN(parsed))
84
+ return fallback;
85
+ return Math.min(max, Math.max(min, parsed));
86
+ }
81
87
  // ── Argv parsing helpers ────────────────────────────────────────────────────
82
88
  export function getOptionValue(args, name) {
83
89
  const exactIdx = args.indexOf(name);
package/dist/utils.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { runGitOrThrow, runGit, normalizeExecCommand, resolveExecCommand, errorMessage, isFeatureEnabled, clampInt, getOptionValue, getPositionalArgs, } from "./utils-helpers.js";
1
+ export { runGitOrThrow, runGit, normalizeExecCommand, resolveExecCommand, errorMessage, isFeatureEnabled, clampInt, clampFloat, getOptionValue, getPositionalArgs, } from "./utils-helpers.js";
2
2
  export { isValidProjectName, safeProjectPath, queueFilePath, QUEUE_FILENAME, } from "./utils-paths.js";
3
3
  export { STOP_WORDS, extractKeywordEntries, extractKeywords, learnedSynonymsPath, loadLearnedSynonyms, loadSynonymMap, learnSynonym, removeLearnedSynonym, sanitizeFts5Query, buildRobustFtsQuery, buildRelaxedFtsQuery, buildFtsQueryVariants, } from "./utils-fts.js";
package/dist/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Barrel re-export. Implementations split across utils-helpers.ts (general
2
2
  // helpers, argv parsing, exec helpers), utils-paths.ts (path validation),
3
3
  // utils-fts.ts (FTS5 query building, synonym/keyword extraction).
4
- export { runGitOrThrow, runGit, normalizeExecCommand, resolveExecCommand, errorMessage, isFeatureEnabled, clampInt, getOptionValue, getPositionalArgs, } from "./utils-helpers.js";
4
+ export { runGitOrThrow, runGit, normalizeExecCommand, resolveExecCommand, errorMessage, isFeatureEnabled, clampInt, clampFloat, getOptionValue, getPositionalArgs, } from "./utils-helpers.js";
5
5
  export { isValidProjectName, safeProjectPath, queueFilePath, QUEUE_FILENAME, } from "./utils-paths.js";
6
6
  export { STOP_WORDS, extractKeywordEntries, extractKeywords, learnedSynonymsPath, loadLearnedSynonyms, loadSynonymMap, learnSynonym, removeLearnedSynonym, sanitizeFts5Query, buildRobustFtsQuery, buildRelaxedFtsQuery, buildFtsQueryVariants, } from "./utils-fts.js";