@phren/cli 0.1.39 → 0.1.41

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 (124) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +11 -3
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +243 -9
  6. package/dist/cli/govern.js +6 -87
  7. package/dist/cli/hooks-context.d.ts +1 -1
  8. package/dist/cli/hooks-context.js +1 -1
  9. package/dist/cli/namespaces-review.js +14 -1
  10. package/dist/cli/session-background.js +4 -0
  11. package/dist/cli/session-git.d.ts +18 -0
  12. package/dist/cli/session-git.js +47 -0
  13. package/dist/cli/session-start.js +2 -2
  14. package/dist/cli/session-stop.d.ts +11 -0
  15. package/dist/cli/session-stop.js +157 -33
  16. package/dist/cli/session-tool-hook.js +17 -5
  17. package/dist/cli-handlers.d.ts +2 -0
  18. package/dist/cli-handlers.js +40 -0
  19. package/dist/cli-registry.d.ts +1 -1
  20. package/dist/cli-registry.js +16 -1
  21. package/dist/content/dedup.d.ts +1 -4
  22. package/dist/content/dedup.js +7 -63
  23. package/dist/content/learning.d.ts +20 -2
  24. package/dist/content/learning.js +21 -3
  25. package/dist/content/quality.d.ts +23 -0
  26. package/dist/content/quality.js +123 -0
  27. package/dist/content/secrets.d.ts +52 -0
  28. package/dist/content/secrets.js +193 -0
  29. package/dist/data/access.d.ts +56 -2
  30. package/dist/data/access.js +246 -24
  31. package/dist/entrypoint.js +5 -1
  32. package/dist/finding/impact.js +170 -43
  33. package/dist/finding/lifecycle.d.ts +19 -2
  34. package/dist/finding/lifecycle.js +15 -3
  35. package/dist/git-worktree.d.ts +19 -0
  36. package/dist/git-worktree.js +117 -0
  37. package/dist/governance/policy.d.ts +84 -4
  38. package/dist/governance/policy.js +209 -14
  39. package/dist/governance/rbac.d.ts +8 -0
  40. package/dist/governance/rbac.js +26 -0
  41. package/dist/hooks.d.ts +26 -0
  42. package/dist/hooks.js +119 -6
  43. package/dist/index.js +5 -1
  44. package/dist/init/guard-globals.d.ts +20 -0
  45. package/dist/init/guard-globals.js +72 -6
  46. package/dist/init/init-configure.d.ts +7 -2
  47. package/dist/init/init-configure.js +42 -16
  48. package/dist/init/init-preset.d.ts +3 -0
  49. package/dist/init/init-preset.js +122 -0
  50. package/dist/init/init-uninstall.js +9 -0
  51. package/dist/init/init-walkthrough.d.ts +2 -0
  52. package/dist/init/init-walkthrough.js +42 -17
  53. package/dist/init/init.d.ts +5 -0
  54. package/dist/init/init.js +71 -19
  55. package/dist/init/management-preset.d.ts +42 -0
  56. package/dist/init/management-preset.js +122 -0
  57. package/dist/init/preferences.d.ts +17 -0
  58. package/dist/init/preferences.js +3 -0
  59. package/dist/init/self-wiring.d.ts +5 -0
  60. package/dist/init/self-wiring.js +52 -0
  61. package/dist/init/setup.d.ts +9 -4
  62. package/dist/init/setup.js +139 -23
  63. package/dist/init/store-gitignore.d.ts +29 -0
  64. package/dist/init/store-gitignore.js +48 -0
  65. package/dist/init/teardown.d.ts +15 -0
  66. package/dist/init/teardown.js +241 -0
  67. package/dist/link/doctor.js +127 -34
  68. package/dist/link/link.js +49 -26
  69. package/dist/phren-core.d.ts +35 -8
  70. package/dist/phren-core.js +35 -8
  71. package/dist/phren-paths.d.ts +90 -1
  72. package/dist/phren-paths.js +150 -5
  73. package/dist/proactivity.js +1 -1
  74. package/dist/shared/embedding-cache.d.ts +16 -0
  75. package/dist/shared/embedding-cache.js +24 -0
  76. package/dist/shared/fragment-graph.js +10 -0
  77. package/dist/shared/index.d.ts +6 -0
  78. package/dist/shared/index.js +523 -138
  79. package/dist/shared/ollama.d.ts +14 -2
  80. package/dist/shared/ollama.js +84 -5
  81. package/dist/shared/retrieval.d.ts +22 -1
  82. package/dist/shared/retrieval.js +30 -1
  83. package/dist/shared/search-fallback.js +15 -3
  84. package/dist/shared/vector-index.d.ts +20 -1
  85. package/dist/shared/vector-index.js +18 -4
  86. package/dist/shared.d.ts +1 -1
  87. package/dist/shared.js +1 -1
  88. package/dist/status.js +31 -2
  89. package/dist/store-registry.d.ts +22 -0
  90. package/dist/store-registry.js +36 -3
  91. package/dist/task/lifecycle.js +31 -0
  92. package/dist/tools/config.js +16 -7
  93. package/dist/tools/data.js +1 -1
  94. package/dist/tools/extract.js +2 -2
  95. package/dist/tools/finding.js +14 -3
  96. package/dist/tools/graph.js +9 -1
  97. package/dist/tools/memory.js +1 -1
  98. package/dist/tools/notes.js +3 -3
  99. package/dist/tools/ops.js +19 -18
  100. package/dist/tools/search.js +2 -2
  101. package/dist/tools/session.js +2 -2
  102. package/dist/tools/tasks.js +2 -2
  103. package/dist/tools/types.d.ts +32 -2
  104. package/dist/tools/types.js +41 -8
  105. package/dist/ui/scripts.js +2 -2
  106. package/dist/ui/server.js +5 -0
  107. package/package.json +1 -1
  108. package/dist/cli-hooks-git.d.ts +0 -50
  109. package/dist/cli-hooks-git.js +0 -288
  110. package/starter/my-api/.claude/skills/README.md +0 -7
  111. package/starter/my-api/CLAUDE.md +0 -33
  112. package/starter/my-api/FINDINGS.md +0 -9
  113. package/starter/my-api/summary.md +0 -7
  114. package/starter/my-api/tasks.md +0 -7
  115. package/starter/my-first-project/.claude/skills/README.md +0 -7
  116. package/starter/my-first-project/CLAUDE.md +0 -49
  117. package/starter/my-first-project/FINDINGS.md +0 -24
  118. package/starter/my-first-project/summary.md +0 -11
  119. package/starter/my-first-project/tasks.md +0 -25
  120. package/starter/my-frontend/.claude/skills/README.md +0 -7
  121. package/starter/my-frontend/CLAUDE.md +0 -33
  122. package/starter/my-frontend/FINDINGS.md +0 -9
  123. package/starter/my-frontend/summary.md +0 -7
  124. package/starter/my-frontend/tasks.md +0 -7
@@ -5,12 +5,12 @@ import { debugLog, EXEC_TIMEOUT_QUICK_MS, getProjectDirs, isRecord, homeDir, hom
5
5
  import { migrateInvalidProjectNames, formatMigrationSummary } from "../project-migrate.js";
6
6
  import { ROOT_MANIFEST_FILENAME } from "../phren-paths.js";
7
7
  import { STORES_FILENAME } from "../store-registry.js";
8
- import { commandVersion, versionAtLeast, nearestWritableTarget } from "../init/shared.js";
8
+ import { commandVersion, versionAtLeast, nearestWritableTarget, resolveEntryScript } from "../init/shared.js";
9
9
  import { validateGovernanceJson } from "../shared/governance.js";
10
10
  import { errorMessage } from "../utils.js";
11
11
  import { buildIndex, queryRows } from "../shared/index.js";
12
12
  import { validateTaskFormat, validateFindingsFormat } from "../shared/content.js";
13
- import { detectInstalledTools, isEphemeralNpxPath } from "../hooks.js";
13
+ import { detectInstalledTools, isEphemeralNpxPath, findStaleHookEntrypoints } from "../hooks.js";
14
14
  import { validateSkillFrontmatter, validateSkillsDir } from "./skills.js";
15
15
  import { verifyFileChecksums, updateFileChecksums } from "./checksums.js";
16
16
  import { buildSkillManifest } from "../skill/registry.js";
@@ -18,6 +18,7 @@ import { inspectTaskHygiene } from "../task/hygiene.js";
18
18
  import { resolveTaskFilePath, TASK_FILE_ALIASES } from "../data/tasks.js";
19
19
  import { FINDINGS_FILENAME } from "../data/access.js";
20
20
  import { repairPreexistingInstall } from "../init/setup.js";
21
+ import { getManagementPreset, resolveManagementCapabilities } from "../init/management-preset.js";
21
22
  import { getMachineName, lookupProfile, findProfileFile, getProfileProjects, findProjectDir, } from "./link.js";
22
23
  import { claudeProjectKey } from "./context.js";
23
24
  import { getProjectOwnershipMode, readProjectConfig } from "../project-config.js";
@@ -188,6 +189,8 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
188
189
  detail: nodeVersion || "node not found in PATH",
189
190
  });
190
191
  const prefs = readInstallPreferences(phrenPath);
192
+ const managementPreset = getManagementPreset(phrenPath);
193
+ const caps = resolveManagementCapabilities(phrenPath);
191
194
  const gitRemote = gitRemoteStatus(phrenPath, prefs.syncIntent);
192
195
  checks.push({
193
196
  name: "git-remote",
@@ -290,28 +293,52 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
290
293
  ok: fs.existsSync(memoryFile),
291
294
  detail: fs.existsSync(memoryFile) ? memoryFile : "missing generated MEMORY.md",
292
295
  });
293
- const globalClaudeSrc = path.join(phrenPath, "global", "CLAUDE.md");
294
- const globalClaudeDest = homePath(".claude", "CLAUDE.md");
295
- let globalLinkOk = false;
296
- try {
297
- globalLinkOk = fs.existsSync(globalClaudeDest) && fs.realpathSync(globalClaudeDest) === fs.realpathSync(globalClaudeSrc);
296
+ // Under presets that don't symlink into ~/.claude, the "missing" links are
297
+ // expected — report them as ok with a preset note instead of failures.
298
+ if (caps.linkGlobalClaudeMd) {
299
+ const globalClaudeSrc = path.join(phrenPath, "global", "CLAUDE.md");
300
+ const globalClaudeDest = homePath(".claude", "CLAUDE.md");
301
+ let globalLinkOk = false;
302
+ try {
303
+ globalLinkOk = fs.existsSync(globalClaudeDest) && fs.realpathSync(globalClaudeDest) === fs.realpathSync(globalClaudeSrc);
304
+ }
305
+ catch (err) {
306
+ debugLog(`doctor: global CLAUDE.md symlink check failed: ${errorMessage(err)}`);
307
+ globalLinkOk = false;
308
+ }
309
+ checks.push({
310
+ name: "global-link",
311
+ ok: globalLinkOk,
312
+ detail: globalLinkOk ? "global CLAUDE.md symlink ok" : "global CLAUDE.md link drifted/missing",
313
+ });
298
314
  }
299
- catch (err) {
300
- debugLog(`doctor: global CLAUDE.md symlink check failed: ${errorMessage(err)}`);
301
- globalLinkOk = false;
315
+ else {
316
+ checks.push({
317
+ name: "global-link",
318
+ ok: true,
319
+ detail: `not managed under ${managementPreset} preset (phren does not write ~/.claude/CLAUDE.md)`,
320
+ });
321
+ }
322
+ if (caps.installSkillLinks) {
323
+ pushSkillMirrorChecks(checks, "global", buildSkillManifest(phrenPath, profile || "", "global", homePath(".claude", "skills")), homePath(".claude", "skills"));
324
+ }
325
+ else {
326
+ checks.push({ name: "skills-mirror:global", ok: true, detail: `skills not mirrored under ${managementPreset} preset` });
302
327
  }
303
- checks.push({
304
- name: "global-link",
305
- ok: globalLinkOk,
306
- detail: globalLinkOk ? "global CLAUDE.md symlink ok" : "global CLAUDE.md link drifted/missing",
307
- });
308
- pushSkillMirrorChecks(checks, "global", buildSkillManifest(phrenPath, profile || "", "global", homePath(".claude", "skills")), homePath(".claude", "skills"));
309
328
  for (const project of projects) {
310
329
  if (project === "global")
311
330
  continue;
312
331
  const config = readProjectConfig(phrenPath, project);
313
332
  const ownership = getProjectOwnershipMode(phrenPath, project, config);
314
333
  const target = findProjectDir(project);
334
+ if (!caps.repoMirroring) {
335
+ checks.push({
336
+ name: `ownership:${project}`,
337
+ ok: true,
338
+ detail: `repo mirrors disabled (${managementPreset} preset)`,
339
+ });
340
+ continue;
341
+ }
315
342
  if (ownership !== "phren-managed") {
316
343
  checks.push({
317
344
  name: `ownership:${project}`,
@@ -347,7 +374,7 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
347
374
  }
348
375
  // Store registry health
349
376
  try {
350
- const { resolveAllStores, storesFilePath } = await import("../store-registry.js");
377
+ const { resolveAllStores, storesFilePath, describeUnavailableStore } = await import("../store-registry.js");
351
378
  const storesFile = storesFilePath(phrenPath);
352
379
  if (fs.existsSync(storesFile)) {
353
380
  const stores = resolveAllStores(phrenPath);
@@ -358,14 +385,26 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
358
385
  ? `${stores.length} stores configured`
359
386
  : "stores.yaml exists but no stores parsed",
360
387
  });
388
+ // Projects claimed by a store that is not attached here cannot be written
389
+ // at all — phren refuses rather than diverting them to the primary store.
390
+ const orphanedClaims = stores
391
+ .filter((store) => store.available === false && store.projects?.length)
392
+ .map((store) => `${store.name} → ${store.projects.join(", ")}`);
393
+ checks.push({
394
+ name: "store-claims-attached",
395
+ ok: orphanedClaims.length === 0,
396
+ detail: orphanedClaims.length === 0
397
+ ? "every claimed project resolves to an attached store"
398
+ : `projects claimed by unattached stores (writes to them will fail): ${orphanedClaims.join("; ")}`,
399
+ });
361
400
  for (const store of stores) {
362
- const pathExists = fs.existsSync(store.path);
401
+ const pathExists = store.available !== false;
363
402
  const gitExists = pathExists && fs.existsSync(path.join(store.path, ".git"));
364
403
  if (!pathExists) {
365
404
  checks.push({
366
405
  name: `store:${store.name}`,
367
406
  ok: false,
368
- detail: `store '${store.name}' path missing: ${store.path}`,
407
+ detail: describeUnavailableStore(store),
369
408
  });
370
409
  }
371
410
  else if (!gitExists) {
@@ -398,27 +437,75 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
398
437
  let hookOk = false;
399
438
  let lifecycleOk = false;
400
439
  let hooksEphemeral = false;
401
- try {
440
+ let staleEntrypoints = [];
441
+ /** Every `command` string under a Claude settings.json hook event. */
442
+ const phrenHookCommands = (hooks) => {
443
+ const commands = [];
444
+ for (const event of ["UserPromptSubmit", "Stop", "SessionStart", "PostToolUse"]) {
445
+ const entries = hooks[event];
446
+ if (!Array.isArray(entries))
447
+ continue;
448
+ for (const entry of entries) {
449
+ if (!isRecord(entry) || !Array.isArray(entry.hooks))
450
+ continue;
451
+ for (const hook of entry.hooks) {
452
+ if (isRecord(hook) && typeof hook.command === "string")
453
+ commands.push(hook.command);
454
+ }
455
+ }
456
+ }
457
+ return commands.filter((command) => /hook-(prompt|stop|session-start|tool)\b/.test(command));
458
+ };
459
+ const readHookState = () => {
402
460
  const cfg = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
403
- const hooks = cfg?.hooks || {};
461
+ const hooks = isRecord(cfg?.hooks) ? cfg.hooks : {};
404
462
  const promptHooks = JSON.stringify(hooks.UserPromptSubmit || []);
405
463
  const stopHooks = JSON.stringify(hooks.Stop || []);
406
464
  const startHooks = JSON.stringify(hooks.SessionStart || []);
407
- hookOk = promptHooks.includes("hook-prompt");
408
- const stopHookOk = stopHooks.includes("hook-stop");
409
- const startHookOk = startHooks.includes("hook-session-start");
410
- lifecycleOk = stopHookOk && startHookOk;
411
- // A hook command that points into the npx cache (~/.npm/_npx/<hash>/…)
412
- // works until npx prunes that cache, then breaks silently. Flag it so a
413
- // re-init (which now resolves to the stable ~/.local/bin/phren wrapper)
414
- // can repair it before the user notices context has stopped flowing.
415
- hooksEphemeral = [promptHooks, stopHooks, startHooks].some(isEphemeralNpxPath);
465
+ const commands = phrenHookCommands(hooks);
466
+ return {
467
+ hookOk: promptHooks.includes("hook-prompt"),
468
+ lifecycleOk: stopHooks.includes("hook-stop") && startHooks.includes("hook-session-start"),
469
+ // A hook command that points into the npx cache (~/.npm/_npx/<hash>/…)
470
+ // works until npx prunes that cache, then breaks silently.
471
+ ephemeral: [promptHooks, stopHooks, startHooks].some(isEphemeralNpxPath),
472
+ // A command whose entrypoint no longer exists is worse: it fails on every
473
+ // single turn with MODULE_NOT_FOUND. `npm i -g @phren/cli` moved the
474
+ // package entry in 0.1.40, so every upgraded install hit exactly this and
475
+ // doctor still reported the path as fine.
476
+ stale: findStaleHookEntrypoints(commands),
477
+ };
478
+ };
479
+ try {
480
+ const state = readHookState();
481
+ hookOk = state.hookOk;
482
+ lifecycleOk = state.lifecycleOk;
483
+ hooksEphemeral = state.ephemeral;
484
+ staleEntrypoints = state.stale;
416
485
  }
417
486
  catch (err) {
418
487
  debugLog(`doctor: failed to read Claude settings for hook check: ${errorMessage(err)}`);
419
488
  hookOk = false;
420
489
  lifecycleOk = false;
421
490
  }
491
+ // Repair stale/ephemeral hook commands before reporting, so `--fix` actually
492
+ // fixes the thing rather than reporting it as OK and doing nothing.
493
+ let hookPathRepaired = false;
494
+ if (fix && (staleEntrypoints.length > 0 || hooksEphemeral)) {
495
+ try {
496
+ const { configureClaude } = await import("../init/config.js");
497
+ configureClaude(phrenPath);
498
+ const state = readHookState();
499
+ hookOk = state.hookOk;
500
+ lifecycleOk = state.lifecycleOk;
501
+ hooksEphemeral = state.ephemeral;
502
+ hookPathRepaired = state.stale.length === 0 && !state.ephemeral;
503
+ staleEntrypoints = state.stale;
504
+ }
505
+ catch (err) {
506
+ debugLog(`doctor: hook path repair failed: ${errorMessage(err)}`);
507
+ }
508
+ }
422
509
  checks.push({
423
510
  name: "claude-hooks",
424
511
  ok: hookOk,
@@ -433,10 +520,16 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
433
520
  });
434
521
  checks.push({
435
522
  name: "hook-path-stable",
436
- ok: !hooksEphemeral,
437
- detail: hooksEphemeral
438
- ? "hook commands point into the ephemeral npx cache (~/.npm/_npx/…); re-run `npx @phren/cli init` to repoint at the stable ~/.local/bin/phren wrapper"
439
- : "hook commands use a stable entrypoint",
523
+ ok: !hooksEphemeral && staleEntrypoints.length === 0,
524
+ detail: staleEntrypoints.length > 0
525
+ ? `hook commands point at ${staleEntrypoints.length} entrypoint(s) that no longer exist: ${staleEntrypoints.join(", ")}. `
526
+ + `Every hook fails with MODULE_NOT_FOUND — usually after \`npm install -g @phren/cli\` moved the package entry. `
527
+ + `Run \`phren doctor --fix\` to repoint them at ${resolveEntryScript()}`
528
+ : hooksEphemeral
529
+ ? "hook commands point into the ephemeral npx cache (~/.npm/_npx/…); re-run `npx @phren/cli init` to repoint at the stable ~/.local/bin/phren wrapper"
530
+ : hookPathRepaired
531
+ ? "hook commands repaired to the current entrypoint"
532
+ : "hook commands resolve to an entrypoint that exists",
440
533
  });
441
534
  const runtimeHealthPath = runtimeHealthFile(phrenPath);
442
535
  let runtime = null;
package/dist/link/link.js CHANGED
@@ -15,6 +15,7 @@ import { STORES_FILENAME } from "../store-registry.js";
15
15
  import { log } from "../init/shared.js";
16
16
  import { listMachines as listMachinesShared, listProfiles as listProfilesShared, setMachineProfile, } from "../profile-store.js";
17
17
  import { writeSkillMd, isManagedSymlink } from "./skills.js";
18
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
18
19
  import { syncScopeSkillsToDir } from "../skill/files.js";
19
20
  import { renderSkillInstructionsSection } from "../skill/registry.js";
20
21
  import { findProjectDir } from "../project-locator.js";
@@ -271,39 +272,60 @@ function writeManagedAgentsFile(src, dest, content, managedRoot) {
271
272
  return true;
272
273
  }
273
274
  // ── Linking operations ──────────────────────────────────────────────────────
274
- function linkGlobal(phrenPath, tools) {
275
- log(" global skills -> ~/.claude/skills/");
276
- const skillsDir = homePath(".claude", "skills");
277
- syncScopeSkillsToDir(phrenPath, "global", skillsDir);
278
- if (tools.has("copilot")) {
279
- const copilotSkillsDir = homePath(".copilot", "skills");
280
- log(" global skills -> ~/.copilot/skills/");
281
- try {
282
- syncScopeSkillsToDir(phrenPath, "global", copilotSkillsDir);
283
- }
284
- catch (err) {
285
- logger.debug("link", `linkGlobal copilotSkills: ${errorMessage(err)}`);
286
- }
287
- }
288
- const globalClaude = path.join(phrenPath, "global", "CLAUDE.md");
289
- if (fs.existsSync(globalClaude)) {
290
- symlinkFile(globalClaude, homePath(".claude", "CLAUDE.md"), phrenPath);
275
+ function linkGlobal(phrenPath, tools, caps) {
276
+ if (caps.installSkillLinks) {
277
+ log(" global skills -> ~/.claude/skills/");
278
+ const skillsDir = homePath(".claude", "skills");
279
+ syncScopeSkillsToDir(phrenPath, "global", skillsDir);
291
280
  if (tools.has("copilot")) {
281
+ const copilotSkillsDir = homePath(".copilot", "skills");
282
+ log(" global skills -> ~/.copilot/skills/");
292
283
  try {
293
- const copilotInstrDir = homePath(".github");
294
- fs.mkdirSync(copilotInstrDir, { recursive: true });
295
- symlinkFile(globalClaude, path.join(copilotInstrDir, "copilot-instructions.md"), phrenPath);
284
+ syncScopeSkillsToDir(phrenPath, "global", copilotSkillsDir);
296
285
  }
297
286
  catch (err) {
298
- logger.debug("link", `linkGlobal copilotInstructions: ${errorMessage(err)}`);
287
+ logger.debug("link", `linkGlobal copilotSkills: ${errorMessage(err)}`);
288
+ }
289
+ }
290
+ }
291
+ if (caps.linkGlobalClaudeMd) {
292
+ const globalClaude = path.join(phrenPath, "global", "CLAUDE.md");
293
+ if (fs.existsSync(globalClaude)) {
294
+ symlinkFile(globalClaude, homePath(".claude", "CLAUDE.md"), phrenPath);
295
+ if (tools.has("copilot")) {
296
+ try {
297
+ const copilotInstrDir = homePath(".github");
298
+ fs.mkdirSync(copilotInstrDir, { recursive: true });
299
+ symlinkFile(globalClaude, path.join(copilotInstrDir, "copilot-instructions.md"), phrenPath);
300
+ }
301
+ catch (err) {
302
+ logger.debug("link", `linkGlobal copilotInstructions: ${errorMessage(err)}`);
303
+ }
299
304
  }
300
305
  }
301
306
  }
307
+ if (!caps.installSkillLinks && !caps.linkGlobalClaudeMd) {
308
+ log(" global symlinks skipped (management preset does not write into ~/.claude)");
309
+ }
302
310
  }
303
- function linkProject(phrenPath, project, tools) {
311
+ function linkProject(phrenPath, project, tools, caps) {
304
312
  const config = readProjectConfig(phrenPath, project);
305
313
  const ownership = getProjectOwnershipMode(phrenPath, project, config);
306
314
  const target = findProjectDir(project);
315
+ // Presets that opt out of repo mirroring still register per-project MCP
316
+ // servers, but never write into the repo itself.
317
+ if (!caps.repoMirroring) {
318
+ if (target) {
319
+ log(` ${project} -> ${target} (repo mirrors disabled by preset)`);
320
+ }
321
+ else {
322
+ log(` ${project} (repo mirrors disabled by preset)`);
323
+ }
324
+ if (isRecord(config.mcpServers)) {
325
+ linkProjectMcpServers(project, config.mcpServers);
326
+ }
327
+ return;
328
+ }
307
329
  if (!target && ownership === "phren-managed") {
308
330
  log(` skip ${project} (not found on disk)`);
309
331
  if (isRecord(config.mcpServers)) {
@@ -496,12 +518,13 @@ export async function runLink(phrenPath, opts = {}) {
496
518
  const detectedTools = opts.allTools
497
519
  ? new Set(["copilot", "cursor", "codex"])
498
520
  : detectInstalledTools();
521
+ const caps = resolveManagementCapabilities(phrenPath);
499
522
  // Step 5: Symlink
500
523
  log("Linking...");
501
- linkGlobal(phrenPath, detectedTools);
524
+ linkGlobal(phrenPath, detectedTools, caps);
502
525
  for (const p of projects) {
503
526
  if (p !== "global")
504
- linkProject(phrenPath, p, detectedTools);
527
+ linkProject(phrenPath, p, detectedTools, caps);
505
528
  }
506
529
  // Remove stale phren__<project>__* MCP entries for removed projects
507
530
  pruneStaleProjectMcpServers(projects.filter(p => p !== "global"));
@@ -514,10 +537,10 @@ export async function runLink(phrenPath, opts = {}) {
514
537
  log(` MCP mode: ${mcpEnabled ? "ON (recommended)" : "OFF (hooks-only fallback)"}`);
515
538
  log(` Hooks mode: ${hooksEnabled ? "ON (active)" : "OFF (disabled)"}`);
516
539
  maybeOfferStarterTemplateUpdate(phrenPath);
517
- const mcpStatusForContext = configureMcpTargets(phrenPath, { mcpEnabled, hooksEnabled });
540
+ const mcpStatusForContext = configureMcpTargets(phrenPath, { mcpEnabled, hooksEnabled, caps });
518
541
  // Register hooks for Copilot CLI, Cursor, Codex
519
542
  if (hooksEnabled) {
520
- const hookedTools = configureAllHooks(phrenPath, { tools: detectedTools });
543
+ const hookedTools = configureAllHooks(phrenPath, { tools: detectedTools, installWrappers: caps.installWrappers });
521
544
  if (hookedTools.length)
522
545
  log(` Hooks registered: ${hookedTools.join(", ")}`);
523
546
  }
@@ -11,7 +11,7 @@ export declare const UNIVERSAL_TECH_TERMS_RE: RegExp;
11
11
  * Additional fragment patterns beyond CamelCase and acronyms.
12
12
  * Each pattern has a named group so callers can identify the fragment type.
13
13
  */
14
- export declare const EXTRA_ENTITY_PATTERNS: Array<{
14
+ export declare const EXTRA_FRAGMENT_PATTERNS: Array<{
15
15
  re: RegExp;
16
16
  label: string;
17
17
  }>;
@@ -50,15 +50,42 @@ export declare function parsePhrenErrorCode(msg: string): PhrenErrorCode | undef
50
50
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
51
51
  /** Shallow-merge data onto defaults so missing keys get filled in. */
52
52
  export declare function withDefaults<T extends object>(data: Partial<T>, defaults: T): T;
53
- /** All valid finding type tags — used for writes, search filters, and hook extraction */
54
- export declare const FINDING_TYPES: readonly ["decision", "pitfall", "pattern", "tradeoff", "architecture", "bug"];
53
+ /**
54
+ * Finding types offered as an explicit choice: add_finding's findingType
55
+ * param, promote_note --type, and the web/iOS type pickers. Deliberately the
56
+ * intersection of what used to be three disjoint lists (this enum, the decay
57
+ * table, and the auto-detector) — "tradeoff" and "architecture" were offered
58
+ * here but had no decay rule and no max-age, so they never actually worked.
59
+ * Legacy stores may still contain those two tags; reading/searching them as
60
+ * plain text still works, they just aren't offered or decay-tracked anymore.
61
+ */
62
+ export declare const FINDING_TYPES: readonly ["decision", "pitfall", "pattern", "bug"];
55
63
  export type FindingType = (typeof FINDING_TYPES)[number];
56
- /** Searchable finding tags (same set as FINDING_TYPES) */
57
- export declare const FINDING_TAGS: readonly ["decision", "pitfall", "pattern", "tradeoff", "architecture", "bug"];
58
- export type FindingTag = FindingType;
59
- /** Canonical set of known observation tags — derived from FINDING_TYPES */
64
+ /**
65
+ * Every finding tag phren can actually produce or needs to search for: the
66
+ * offered FINDING_TYPES above, plus tags autoDetectFindingType
67
+ * (content/learning.ts) writes on its own initiative — "workaround" and
68
+ * "context" — which aren't offered as an explicit pick but still need a
69
+ * decay rule (finding/lifecycle.ts's FINDING_TYPE_DECAY is typed against
70
+ * this exact set) and need to stay filterable via search_knowledge's `tag`
71
+ * param.
72
+ */
73
+ export declare const FINDING_TAGS: readonly ["decision", "pitfall", "pattern", "bug", "workaround", "context"];
74
+ export type FindingTag = (typeof FINDING_TAGS)[number];
75
+ /** Canonical set of known finding tags for the "unknown tag" write-time warning — derived from FINDING_TAGS (not just FINDING_TYPES) so phren never flags its own auto-written workaround/context tags as unknown. */
60
76
  export declare const KNOWN_OBSERVATION_TAGS: Set<string>;
61
- /** Document types in the FTS index */
77
+ /**
78
+ * Document types in the FTS index.
79
+ *
80
+ * "canonical" is `truths.md`'s type (see FILE_TYPE_MAP in shared/index.ts):
81
+ * the file was renamed from `canonical_memories.md` to `truths.md` in the
82
+ * 0.0.5 rename, but the type string was not renamed with it, so it still
83
+ * leaks as the literal `--type canonical` / `type: "canonical"` value across
84
+ * the CLI and API (docs/api-reference.md documents it as-is because that is
85
+ * what the index actually produces). Renaming it requires touching
86
+ * shared/index.ts and shared/retrieval.ts together with this file, since all
87
+ * three must agree on the type string.
88
+ */
62
89
  export declare const DOC_TYPES: readonly ["claude", "findings", "notes", "reference", "skills", "summary", "task", "changelog", "canonical", "review-queue", "skill", "other"];
63
90
  export type DocType = (typeof DOC_TYPES)[number];
64
91
  export declare function capCache<K, V>(cache: Map<K, V>): void;
@@ -12,7 +12,7 @@ export const UNIVERSAL_TECH_TERMS_RE = /\b(Python|Rust|Go|Java|TypeScript|JavaSc
12
12
  * Additional fragment patterns beyond CamelCase and acronyms.
13
13
  * Each pattern has a named group so callers can identify the fragment type.
14
14
  */
15
- export const EXTRA_ENTITY_PATTERNS = [
15
+ export const EXTRA_FRAGMENT_PATTERNS = [
16
16
  // Semantic version numbers: v1.2.3, 2.0.0-beta.1
17
17
  { re: /\bv?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?\b/g, label: "version" },
18
18
  // Environment variable keys: PHREN_*, NODE_ENV, etc. (2+ uppercase segments separated by _)
@@ -86,13 +86,40 @@ export function withDefaults(data, defaults) {
86
86
  }
87
87
  return merged;
88
88
  }
89
- /** All valid finding type tags — used for writes, search filters, and hook extraction */
90
- export const FINDING_TYPES = ["decision", "pitfall", "pattern", "tradeoff", "architecture", "bug"];
91
- /** Searchable finding tags (same set as FINDING_TYPES) */
92
- export const FINDING_TAGS = FINDING_TYPES;
93
- /** Canonical set of known observation tags — derived from FINDING_TYPES */
94
- export const KNOWN_OBSERVATION_TAGS = new Set(FINDING_TYPES);
95
- /** Document types in the FTS index */
89
+ /**
90
+ * Finding types offered as an explicit choice: add_finding's findingType
91
+ * param, promote_note --type, and the web/iOS type pickers. Deliberately the
92
+ * intersection of what used to be three disjoint lists (this enum, the decay
93
+ * table, and the auto-detector) — "tradeoff" and "architecture" were offered
94
+ * here but had no decay rule and no max-age, so they never actually worked.
95
+ * Legacy stores may still contain those two tags; reading/searching them as
96
+ * plain text still works, they just aren't offered or decay-tracked anymore.
97
+ */
98
+ export const FINDING_TYPES = ["decision", "pitfall", "pattern", "bug"];
99
+ /**
100
+ * Every finding tag phren can actually produce or needs to search for: the
101
+ * offered FINDING_TYPES above, plus tags autoDetectFindingType
102
+ * (content/learning.ts) writes on its own initiative — "workaround" and
103
+ * "context" — which aren't offered as an explicit pick but still need a
104
+ * decay rule (finding/lifecycle.ts's FINDING_TYPE_DECAY is typed against
105
+ * this exact set) and need to stay filterable via search_knowledge's `tag`
106
+ * param.
107
+ */
108
+ export const FINDING_TAGS = [...FINDING_TYPES, "workaround", "context"];
109
+ /** Canonical set of known finding tags for the "unknown tag" write-time warning — derived from FINDING_TAGS (not just FINDING_TYPES) so phren never flags its own auto-written workaround/context tags as unknown. */
110
+ export const KNOWN_OBSERVATION_TAGS = new Set(FINDING_TAGS);
111
+ /**
112
+ * Document types in the FTS index.
113
+ *
114
+ * "canonical" is `truths.md`'s type (see FILE_TYPE_MAP in shared/index.ts):
115
+ * the file was renamed from `canonical_memories.md` to `truths.md` in the
116
+ * 0.0.5 rename, but the type string was not renamed with it, so it still
117
+ * leaks as the literal `--type canonical` / `type: "canonical"` value across
118
+ * the CLI and API (docs/api-reference.md documents it as-is because that is
119
+ * what the index actually produces). Renaming it requires touching
120
+ * shared/index.ts and shared/retrieval.ts together with this file, since all
121
+ * three must agree on the type string.
122
+ */
96
123
  export const DOC_TYPES = ["claude", "findings", "notes", "reference", "skills", "summary", "task", "changelog", "canonical", "review-queue", "skill", "other"];
97
124
  // ── Cache eviction helper ────────────────────────────────────────────────────
98
125
  const CACHE_MAX = 1000;
@@ -16,7 +16,35 @@ export declare function homePath(...parts: string[]): string;
16
16
  export declare function expandHomePath(input: string): string;
17
17
  export declare function defaultPhrenPath(): string;
18
18
  export declare function rootManifestPath(phrenPath: string): string;
19
- export declare function atomicWriteText(filePath: string, content: string): void;
19
+ export interface AtomicWriteOptions {
20
+ /**
21
+ * POSIX mode for the written file, applied to the temp file *before* the
22
+ * rename. Callers writing secrets must pass this rather than chmod-ing after
23
+ * the fact: a post-rename chmod leaves the file readable at the default
24
+ * umask-derived mode (0644 on a stock install) for the whole write window,
25
+ * which is exactly long enough for another local user to read it.
26
+ */
27
+ mode?: number;
28
+ }
29
+ export declare function atomicWriteText(filePath: string, content: string, opts?: AtomicWriteOptions): void;
30
+ /**
31
+ * Create (or tighten) a directory that holds per-user private data — runtime
32
+ * logs, session transcripts, credential stores.
33
+ *
34
+ * Plain `fs.mkdirSync(dir, { recursive: true })` yields 0755 under the stock
35
+ * 0022 umask, which makes every file inside world-listable and world-readable
36
+ * on a shared machine. Passing `mode` to mkdirSync is not enough on its own:
37
+ * mkdirSync's mode applies only to directories it actually *creates*, so a
38
+ * directory that some earlier code path already made at 0755 keeps that mode
39
+ * forever. That is not hypothetical — `runtimeFile()` created `~/.phren/.runtime`
40
+ * with no mode long before `auth/profiles.ts` ever asked for 0700, so the
41
+ * credential directory shipped world-readable in practice.
42
+ *
43
+ * Only ever narrows: if the directory is already 0700 or tighter it is left
44
+ * alone. Best-effort — a chmod failure (foreign filesystem, Windows) must not
45
+ * break the caller, since the directory itself is usable either way.
46
+ */
47
+ export declare function ensurePrivateDir(dir: string): string;
20
48
  export declare function isInstallMode(value: unknown): value is InstallMode;
21
49
  export declare function readRootManifest(phrenPath: string): PhrenRootManifest | null;
22
50
  export declare function writeRootManifest(phrenPath: string, manifest: PhrenRootManifest): void;
@@ -31,6 +59,44 @@ export declare function runtimeDir(phrenPath: string): string;
31
59
  export declare function tryUnlink(filePath: string): void;
32
60
  export declare function sessionsDir(phrenPath: string): string;
33
61
  export declare function runtimeFile(phrenPath: string, name: string): string;
62
+ /**
63
+ * Per-user root for the FTS snapshot cache: `os.tmpdir()/phren-fts-<uid>`.
64
+ *
65
+ * Canonical definition of the path lives here, with every other phren path
66
+ * helper. `shared/index.ts` currently has its own private copy — see
67
+ * ensureFtsCacheRootPrivate() for why that matters and what still needs to
68
+ * change there.
69
+ */
70
+ export declare function ftsCacheRoot(): string;
71
+ /**
72
+ * Make the FTS snapshot cache root private, creating it if needed.
73
+ *
74
+ * The snapshot is a SQLite export of the *entire* indexed store — the full
75
+ * text of every finding, note, task and reference doc. It was being written
76
+ * as an 0644 file inside an 0755 directory:
77
+ *
78
+ * drwxr-xr-x $TMPDIR/phren-fts-501
79
+ * -rw-r--r-- $TMPDIR/phren-fts-501/<storeKey>/<hash>.db
80
+ *
81
+ * On macOS `os.tmpdir()` is a per-user `/var/folders/…/T` at 0700, which is
82
+ * the only reason this is not already a leak there. On Linux and WSL
83
+ * `os.tmpdir()` is `/tmp` — mode 1777, world-readable — so any local account
84
+ * can read another user's whole knowledge base. phren ships cross-platform on
85
+ * npm, so that is a live exposure, not a theoretical one.
86
+ *
87
+ * A 0700 root closes it completely: POSIX denies traversal into the directory,
88
+ * so the modes of the per-store subdirectory and the .db files inside it stop
89
+ * being reachable at all. Called once per process from the CLI and MCP-server
90
+ * entrypoints, which both creates it correctly on a clean machine and repairs
91
+ * the 0755 root on machines that already have one.
92
+ *
93
+ * Still worth doing for defence in depth, in the file that actually writes
94
+ * them: `shared/index.ts` should pass `{ recursive: true, mode: 0o700 }` to
95
+ * the `fs.mkdirSync(cacheDir, …)` calls and `{ mode: 0o600 }` to the
96
+ * `fs.writeFileSync(cacheFile, db.export())` calls. That file is owned by
97
+ * another change in flight, so it is reported rather than edited here.
98
+ */
99
+ export declare function ensureFtsCacheRootPrivate(): string;
34
100
  export declare function installPreferencesFile(phrenPath: string): string;
35
101
  export declare function runtimeHealthFile(phrenPath: string): string;
36
102
  export declare function shellStateFile(phrenPath: string): string;
@@ -58,7 +124,30 @@ export declare function appendIndexEvent(phrenPath: string, event: Record<string
58
124
  export declare function resolveFindingsPath(projectDir: string): string | undefined;
59
125
  export declare function listInvalidProjectDirs(phrenPath: string): string[];
60
126
  export declare function normalizeProjectNameForCreate(name: string): string;
127
+ /**
128
+ * The single source of truth for turning a source directory into a project
129
+ * slug. Previously copy-pasted at five call sites, which is how the same repo
130
+ * could end up registered twice under near-identical names.
131
+ *
132
+ * Runs of non-slug characters collapse to one hyphen and leading/trailing
133
+ * hyphens are trimmed, so `My.App`, `My..App` and `My App` all yield `my-app`
134
+ * instead of the old `my-app` / `my--app` / `my-app` split.
135
+ */
136
+ export declare function projectSlugFromPath(sourcePath: string): string;
137
+ /**
138
+ * Collapse a project name to the key used for duplicate detection: lowercase
139
+ * with every separator removed. `Max4LivePlugins`, `max4liveplugins` and
140
+ * `max4live-plugins` all map to `max4liveplugins`, so the second spelling of a
141
+ * repo can be recognized as the project that already exists.
142
+ */
143
+ export declare function canonicalProjectKey(name: string): string;
61
144
  export declare function findProjectNameCaseInsensitive(phrenPath: string, name: string): string | null;
145
+ /**
146
+ * Existing project directories whose name canonicalizes to the same key as
147
+ * `name` (see {@link canonicalProjectKey}). Exact matches are returned first so
148
+ * callers can prefer them.
149
+ */
150
+ export declare function findProjectNamesByCanonicalKey(phrenPath: string, name: string): string[];
62
151
  export declare function findArchivedProjectNameCaseInsensitive(phrenPath: string, name: string): string | null;
63
152
  export declare function getProjectDirs(phrenPath: string, profile?: string): string[];
64
153
  export declare function collectNativeMemoryFiles(): Array<{