@phren/cli 0.1.40 → 0.1.42

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 (119) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +12 -16
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +244 -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/namespaces-utils.js +1 -1
  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 +141 -33
  16. package/dist/cli/session-tool-hook.js +17 -5
  17. package/dist/cli-registry.d.ts +1 -1
  18. package/dist/cli-registry.js +1 -0
  19. package/dist/content/archive.js +3 -2
  20. package/dist/content/dedup.d.ts +1 -4
  21. package/dist/content/dedup.js +11 -66
  22. package/dist/content/learning.d.ts +20 -2
  23. package/dist/content/learning.js +26 -7
  24. package/dist/content/quality.d.ts +23 -0
  25. package/dist/content/quality.js +123 -0
  26. package/dist/content/secrets.d.ts +52 -0
  27. package/dist/content/secrets.js +196 -0
  28. package/dist/data/access.d.ts +56 -2
  29. package/dist/data/access.js +255 -32
  30. package/dist/data/tasks.js +46 -6
  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 +18 -5
  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 +213 -17
  39. package/dist/governance/rbac.d.ts +8 -0
  40. package/dist/governance/rbac.js +26 -0
  41. package/dist/hooks.d.ts +20 -0
  42. package/dist/hooks.js +113 -3
  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.js +6 -6
  47. package/dist/init/init.js +10 -6
  48. package/dist/init/setup.d.ts +4 -3
  49. package/dist/init/setup.js +120 -16
  50. package/dist/init/store-gitignore.d.ts +29 -0
  51. package/dist/init/store-gitignore.js +48 -0
  52. package/dist/link/doctor.js +86 -20
  53. package/dist/phren-core.d.ts +35 -8
  54. package/dist/phren-core.js +35 -8
  55. package/dist/phren-paths.d.ts +90 -1
  56. package/dist/phren-paths.js +150 -5
  57. package/dist/proactivity.js +1 -1
  58. package/dist/project-config.js +3 -2
  59. package/dist/project-topics.js +13 -12
  60. package/dist/shared/data-utils.js +13 -3
  61. package/dist/shared/embedding-cache.d.ts +16 -0
  62. package/dist/shared/embedding-cache.js +24 -0
  63. package/dist/shared/fragment-graph.js +10 -0
  64. package/dist/shared/index.d.ts +6 -0
  65. package/dist/shared/index.js +523 -138
  66. package/dist/shared/ollama.d.ts +14 -2
  67. package/dist/shared/ollama.js +84 -5
  68. package/dist/shared/retrieval.d.ts +22 -1
  69. package/dist/shared/retrieval.js +30 -1
  70. package/dist/shared/search-fallback.js +15 -3
  71. package/dist/shared/vector-index.d.ts +20 -1
  72. package/dist/shared/vector-index.js +18 -4
  73. package/dist/shared.d.ts +1 -1
  74. package/dist/shared.js +1 -1
  75. package/dist/status.js +18 -1
  76. package/dist/store-registry.d.ts +22 -0
  77. package/dist/store-registry.js +36 -3
  78. package/dist/store-routing.d.ts +8 -0
  79. package/dist/store-routing.js +23 -1
  80. package/dist/task/lifecycle.js +31 -0
  81. package/dist/tools/config.js +19 -9
  82. package/dist/tools/data.js +1 -1
  83. package/dist/tools/extract-facts.js +3 -2
  84. package/dist/tools/extract.js +2 -2
  85. package/dist/tools/finding.js +20 -8
  86. package/dist/tools/graph.js +9 -1
  87. package/dist/tools/memory.js +1 -1
  88. package/dist/tools/notes.js +3 -3
  89. package/dist/tools/ops.js +19 -18
  90. package/dist/tools/search.js +2 -2
  91. package/dist/tools/session.js +2 -2
  92. package/dist/tools/tasks.js +2 -2
  93. package/dist/tools/types.d.ts +32 -2
  94. package/dist/tools/types.js +41 -8
  95. package/dist/ui/scripts.js +2 -2
  96. package/dist/ui/server.js +7 -6
  97. package/dist/utils-fts.js +3 -2
  98. package/dist/utils-paths.d.ts +1 -0
  99. package/dist/utils-paths.js +1 -1
  100. package/dist/utils.d.ts +1 -1
  101. package/dist/utils.js +1 -1
  102. package/package.json +1 -1
  103. package/dist/cli-hooks-git.d.ts +0 -50
  104. package/dist/cli-hooks-git.js +0 -288
  105. package/starter/my-api/.claude/skills/README.md +0 -7
  106. package/starter/my-api/CLAUDE.md +0 -33
  107. package/starter/my-api/FINDINGS.md +0 -9
  108. package/starter/my-api/summary.md +0 -7
  109. package/starter/my-api/tasks.md +0 -7
  110. package/starter/my-first-project/.claude/skills/README.md +0 -7
  111. package/starter/my-first-project/CLAUDE.md +0 -49
  112. package/starter/my-first-project/FINDINGS.md +0 -24
  113. package/starter/my-first-project/summary.md +0 -11
  114. package/starter/my-first-project/tasks.md +0 -25
  115. package/starter/my-frontend/.claude/skills/README.md +0 -7
  116. package/starter/my-frontend/CLAUDE.md +0 -33
  117. package/starter/my-frontend/FINDINGS.md +0 -9
  118. package/starter/my-frontend/summary.md +0 -7
  119. package/starter/my-frontend/tasks.md +0 -7
@@ -10,11 +10,24 @@
10
10
  * Claude session boots with a SessionStart hook that throws
11
11
  * `NOT_FOUND: phren root not found. Run 'phren init'.`
12
12
  *
13
- * Behavior: before any global file is rewritten, scan the three known
14
- * locations. If any of them already references a *different* path that
15
- * resolves to a valid phren root, refuse to proceed unless `--force` is
16
- * passed. Stale wiring (existing path missing or not a phren root) is not a
17
- * conflict — init is the right tool to repair it.
13
+ * Behavior: before any global file is rewritten, scan the known locations. If
14
+ * any of them already references a *different* path that resolves to a valid
15
+ * phren root, refuse to proceed unless `--force` is passed. Stale wiring
16
+ * (existing path missing or not a phren root) is not a conflict — init is the
17
+ * right tool to repair it.
18
+ *
19
+ * Scope, stated precisely because the module name reads broader than it is:
20
+ * this guards `phren init` only, and only the four locations enumerated in
21
+ * findConflictingGlobalWiring — the CLI wrapper, settings.json mcpServers,
22
+ * settings.json hooks, and (added later) the ~/.claude/CLAUDE.md symlink.
23
+ *
24
+ * It is NOT a guard on every user-level file phren writes. In particular the
25
+ * home skill symlinks under ~/.claude/skills are not covered, and
26
+ * `repairPreexistingInstall()` — which rewrites the same global surfaces and
27
+ * runs on every SessionStart hook, from the web UI, and from `phren doctor` —
28
+ * never calls into this module at all. The CLAUDE.md symlink case is handled
29
+ * at its own write site in init/setup.ts (repairGlobalClaudeSymlink) using the
30
+ * helpers exported here, so it holds on those paths too.
18
31
  */
19
32
  import * as fs from "fs";
20
33
  import * as path from "path";
@@ -31,7 +44,7 @@ function samePath(a, b) {
31
44
  * — root manifest, machines.yaml, or the global skills tree. We deliberately
32
45
  * tolerate partial roots so a clean `phren init` repair still works.
33
46
  */
34
- function looksLikePhrenRoot(candidate) {
47
+ export function looksLikePhrenRoot(candidate) {
35
48
  if (!fs.existsSync(candidate))
36
49
  return false;
37
50
  if (fs.existsSync(path.join(candidate, "phren.root.yaml")))
@@ -42,6 +55,51 @@ function looksLikePhrenRoot(candidate) {
42
55
  return true;
43
56
  return false;
44
57
  }
58
+ /**
59
+ * True when `candidate` is a *different* phren root than the one being
60
+ * installed and still looks live. That combination is the one case where
61
+ * rewriting a global file destroys wiring someone is actually using; a stale
62
+ * root (deleted, or never a root) is exactly what init exists to repair.
63
+ */
64
+ export function isLiveForeignPhrenRoot(candidate, newPhrenPath) {
65
+ if (samePath(candidate, newPhrenPath))
66
+ return false;
67
+ return looksLikePhrenRoot(candidate);
68
+ }
69
+ /**
70
+ * Recover the phren root that owns a `~/.claude/CLAUDE.md` symlink, from the
71
+ * link target's shape (`<root>/global/CLAUDE.md`). Returns null when the
72
+ * target is not structured like a phren global file, i.e. it belongs to
73
+ * something that is not phren and must not be touched.
74
+ */
75
+ export function phrenRootFromGlobalClaudeLink(target) {
76
+ const resolved = path.resolve(target);
77
+ if (path.basename(resolved) !== "CLAUDE.md")
78
+ return null;
79
+ const globalDir = path.dirname(resolved);
80
+ if (path.basename(globalDir) !== "global")
81
+ return null;
82
+ const root = path.dirname(globalDir);
83
+ return root && root !== globalDir ? root : null;
84
+ }
85
+ /**
86
+ * The phren root that `~/.claude/CLAUDE.md` currently points at, or null when
87
+ * the file is absent, a regular file, or a symlink into something that isn't
88
+ * a phren store.
89
+ */
90
+ function readGlobalClaudeMdRoot() {
91
+ const dest = homePath(".claude", "CLAUDE.md");
92
+ let target;
93
+ try {
94
+ if (!fs.lstatSync(dest).isSymbolicLink())
95
+ return null;
96
+ target = path.resolve(path.dirname(dest), fs.readlinkSync(dest));
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ return phrenRootFromGlobalClaudeLink(target);
102
+ }
45
103
  function readWrapperPath() {
46
104
  const wrapperName = process.platform === "win32" ? "phren.cmd" : "phren";
47
105
  const wrapperFile = path.join(homePath(".local", "bin"), wrapperName);
@@ -95,6 +153,14 @@ export function findConflictingGlobalWiring(newPhrenPath) {
95
153
  if (wrapperPath) {
96
154
  record(`~/.local/bin/${process.platform === "win32" ? "phren.cmd" : "phren"} wrapper`, wrapperPath);
97
155
  }
156
+ // ~/.claude/CLAUDE.md is a symlink into <root>/global/CLAUDE.md, i.e. it is
157
+ // global wiring exactly like the wrapper is — but it was not scanned, so
158
+ // `phren init` with a throwaway PHREN_PATH would repoint the user's real one
159
+ // and the guard would report no conflict.
160
+ const claudeMdRoot = readGlobalClaudeMdRoot();
161
+ if (claudeMdRoot) {
162
+ record("~/.claude/CLAUDE.md symlink", claudeMdRoot);
163
+ }
98
164
  const settings = readClaudeSettings();
99
165
  if (isRecord(settings)) {
100
166
  const mcpServers = settings.mcpServers;
@@ -6,7 +6,8 @@ import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import * as crypto from "crypto";
8
8
  import { getProjectOwnershipDefault } from "../project-config.js";
9
- import { atomicWriteText, debugLog, readRootManifest, writeRootManifest, } from "../shared.js";
9
+ import { atomicWriteText, debugLog, ensurePrivateDir, projectSlugFromPath, readRootManifest, writeRootManifest, } from "../shared.js";
10
+ import { STORE_SECRET_GITIGNORE_LINES } from "./store-gitignore.js";
10
11
  import { errorMessage } from "../utils.js";
11
12
  import { configureAllHooks, installPhrenCliWrapper, ensureLocalBinOnWindowsPath } from "../hooks.js";
12
13
  import { updateWorkflowPolicy } from "../shared/governance.js";
@@ -322,7 +323,7 @@ export async function runProjectLocalInit(opts = {}) {
322
323
  opts.projectOwnershipDefault = ownershipDefault;
323
324
  }
324
325
  const mcpEnabled = opts.mcp ? opts.mcp === "on" : true;
325
- const projectName = path.basename(workspaceRoot).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
326
+ const projectName = projectSlugFromPath(workspaceRoot);
326
327
  if (opts.dryRun) {
327
328
  log("\nInit dry run. No files will be written.\n");
328
329
  log(`Mode: project-local`);
@@ -345,12 +346,11 @@ export async function runProjectLocalInit(opts = {}) {
345
346
  ensureGovernanceFiles(phrenPath);
346
347
  repairPreexistingInstall(phrenPath);
347
348
  fs.mkdirSync(path.join(phrenPath, "global", "skills"), { recursive: true });
348
- fs.mkdirSync(path.join(phrenPath, ".runtime"), { recursive: true });
349
- fs.mkdirSync(path.join(phrenPath, ".sessions"), { recursive: true });
349
+ ensurePrivateDir(path.join(phrenPath, ".runtime"));
350
+ ensurePrivateDir(path.join(phrenPath, ".sessions"));
350
351
  if (!fs.existsSync(path.join(phrenPath, ".gitignore"))) {
351
352
  atomicWriteText(path.join(phrenPath, ".gitignore"), [
352
- ".runtime/",
353
- ".sessions/",
353
+ ...STORE_SECRET_GITIGNORE_LINES,
354
354
  "*.lock",
355
355
  "*.tmp-*",
356
356
  "",
package/dist/init/init.js CHANGED
@@ -7,7 +7,7 @@ import * as fs from "fs";
7
7
  import * as path from "path";
8
8
  import { execFileSync } from "child_process";
9
9
  import { getMachineName, persistMachineName } from "../machine-identity.js";
10
- import { atomicWriteText, debugLog, expandHomePath, homePath, writeRootManifest, } from "../shared.js";
10
+ import { atomicWriteText, debugLog, expandHomePath, homePath, projectSlugFromPath, writeRootManifest, } from "../shared.js";
11
11
  import { isValidProjectName, errorMessage } from "../utils.js";
12
12
  import { logger } from "../logger.js";
13
13
  export { configureClaude, configureVSCode, configureCursorMcp, configureCopilotMcp, configureCodexMcp, logMcpTargetStatus, resetVSCodeProbeCache, patchJsonFile, } from "./config.js";
@@ -70,7 +70,7 @@ export function isVersionNewer(current, previous) {
70
70
  return c.pre > p.pre;
71
71
  }
72
72
  function normalizedBootstrapProjectName(projectPath) {
73
- return path.basename(projectPath).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
73
+ return projectSlugFromPath(projectPath);
74
74
  }
75
75
  export function getPendingBootstrapTarget(phrenPath, _opts) {
76
76
  const cwdProject = detectProjectDir(process.cwd(), phrenPath);
@@ -468,13 +468,17 @@ export async function runInit(opts = {}) {
468
468
  const useTemplateProject = Boolean(walkthroughProject) || Boolean(opts.template);
469
469
  const firstProjectName = walkthroughProject || "my-first-project";
470
470
  const firstProjectDomain = opts._walkthroughDomain ?? "software";
471
- // Copy bundled starter to ~/.phren
471
+ // Copy bundled starter to ~/.phren.
472
+ //
473
+ // Note: packages/cli/starter/ no longer ships my-api/my-frontend/
474
+ // my-first-project sample-project directories — they were bundled but
475
+ // never copied (this loop used to skip them by name) and ensureProjectScaffold()
476
+ // below generates the real first-project content instead. Those three names
477
+ // still appear in LEGACY_SAMPLE_PROJECTS (init/setup.ts) purely to prune them
478
+ // out of profiles left behind by installs that predate this cleanup.
472
479
  function copyDir(src, dest) {
473
480
  fs.mkdirSync(dest, { recursive: true });
474
481
  for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
475
- if (src === STARTER_DIR && entry.isDirectory() && ["my-api", "my-frontend", "my-first-project"].includes(entry.name)) {
476
- continue;
477
- }
478
482
  const srcPath = path.join(src, entry.name);
479
483
  const destPath = path.join(dest, entry.name);
480
484
  if (entry.isDirectory()) {
@@ -67,9 +67,6 @@ export interface InferredInitScaffold {
67
67
  export declare function inferInitScaffoldFromRepo(repoRoot: string, fallbackDomain?: InitProjectDomain): InferredInitScaffold | null;
68
68
  export declare function ensureProjectScaffold(projectDir: string, projectName: string, domain?: InitProjectDomain, inference?: InferredInitScaffold | null): void;
69
69
  export declare function ensureLocalGitRepo(phrenPath: string): LocalGitRepoStatus;
70
- /** Bootstrap a phren project from an existing project directory with CLAUDE.md.
71
- * @param profile - if provided, only this profile YAML is updated (avoids leaking project to unrelated profiles).
72
- */
73
70
  export declare function bootstrapFromExisting(phrenPath: string, projectPath: string, opts?: string | BootstrapProjectOptions): BootstrapProjectResult;
74
71
  export declare function updateMachinesYaml(phrenPath: string, machine?: string, profile?: string): void;
75
72
  /**
@@ -78,6 +75,10 @@ export declare function updateMachinesYaml(phrenPath: string, machine?: string,
78
75
  * A directory qualifies if it:
79
76
  * - Is not the home directory or phren directory
80
77
  * - Has a CLAUDE.md, AGENTS.md, .claude/CLAUDE.md, or .git directory
78
+ *
79
+ * A git worktree resolves to the repository it belongs to. Without this a
80
+ * throwaway agent worktree under `.claude/worktrees/<codename>` looks like its
81
+ * own repo (it has a `.git` entry) and gets offered as a new project.
81
82
  */
82
83
  export declare function detectProjectDir(dir: string, phrenPath: string): string | null;
83
84
  /**
@@ -5,8 +5,10 @@ import * as fs from "fs";
5
5
  import * as path from "path";
6
6
  import * as os from "os";
7
7
  import * as yaml from "js-yaml";
8
- import { atomicWriteText, debugLog, findProjectNameCaseInsensitive, hookConfigPath, EXEC_TIMEOUT_QUICK_MS, readRootManifest, sessionsDir, runtimeHealthFile, isRecord, } from "../shared.js";
9
- import { homePath } from "../phren-paths.js";
8
+ import { atomicWriteText, debugLog, findProjectNameCaseInsensitive, findProjectNamesByCanonicalKey, projectSlugFromPath, hookConfigPath, EXEC_TIMEOUT_QUICK_MS, readRootManifest, sessionsDir, runtimeHealthFile, isRecord, } from "../shared.js";
9
+ import { ensurePrivateDir, homePath } from "../phren-paths.js";
10
+ import { isLiveForeignPhrenRoot, phrenRootFromGlobalClaudeLink } from "./guard-globals.js";
11
+ import { resolveWorktreeParent } from "../git-worktree.js";
10
12
  import { addProjectToProfile, listProfiles, resolveActiveProfile, setMachineProfile } from "../profile-store.js";
11
13
  import { getMachineName } from "../machine-identity.js";
12
14
  import { execFileSync } from "child_process";
@@ -191,16 +193,20 @@ function copyDirRecursive(src, dest) {
191
193
  }
192
194
  function ensureRuntimeAssets(phrenPath) {
193
195
  const created = [];
196
+ // Both directories hold per-user private data (credential store, debug and
197
+ // hook-error logs, session transcripts) and are gitignored by the store
198
+ // template. ensurePrivateDir creates them 0700 and tightens an existing
199
+ // 0755 one left behind by an older install.
194
200
  const runtimeDir = path.join(phrenPath, ".runtime");
195
- if (!fs.existsSync(runtimeDir)) {
196
- fs.mkdirSync(runtimeDir, { recursive: true });
201
+ const runtimeExisted = fs.existsSync(runtimeDir);
202
+ ensurePrivateDir(runtimeDir);
203
+ if (!runtimeExisted)
197
204
  created.push(".runtime/");
198
- }
199
205
  const sessions = sessionsDir(phrenPath);
200
- if (!fs.existsSync(sessions)) {
201
- fs.mkdirSync(sessions, { recursive: true });
206
+ const sessionsExisted = fs.existsSync(sessions);
207
+ ensurePrivateDir(sessions);
208
+ if (!sessionsExisted)
202
209
  created.push(".sessions/");
203
- }
204
210
  return created;
205
211
  }
206
212
  function ensureDefaultFeatureFlags(phrenPath, preset) {
@@ -334,7 +340,27 @@ export function repairPreexistingInstall(phrenPath, opts) {
334
340
  repairedGlobalSymlink,
335
341
  };
336
342
  }
337
- /** Re-create ~/.claude/CLAUDE.md symlink if the source exists but the link is missing/broken. */
343
+ /**
344
+ * Re-create the ~/.claude/CLAUDE.md symlink if the source exists but the link
345
+ * is missing or broken.
346
+ *
347
+ * The ownership test used to be `target.includes(".phren") ||
348
+ * target.endsWith("global/CLAUDE.md")`, which treats *any* live phren root's
349
+ * global file as fair game to unlink. That is how a run with
350
+ * `PHREN_PATH=/tmp/…` — a smoke test, or phren's own web UI — leaves the
351
+ * user's real `~/.claude/CLAUDE.md` pointing into a temp directory that then
352
+ * disappears, and every later Claude session starts with no global context.
353
+ *
354
+ * assertNoGlobalWiringConflict does not save us here: it guards `phren init`,
355
+ * and this function is reached from repairPreexistingInstall(), which runs on
356
+ * every SessionStart hook (cli/session-start.ts), from the web UI
357
+ * (ui/server.ts) and from `phren doctor` (link/doctor.ts) — none of which
358
+ * consult the guard. So the check has to live at the write site.
359
+ *
360
+ * New rule: a symlink into a *different* root that still looks live is left
361
+ * alone. Stale wiring (the root is gone, or was never a root) is still
362
+ * repaired, which is the case this function exists for.
363
+ */
338
364
  function repairGlobalClaudeSymlink(phrenPath) {
339
365
  const src = path.join(phrenPath, "global", "CLAUDE.md");
340
366
  if (!fs.existsSync(src))
@@ -346,9 +372,14 @@ function repairGlobalClaudeSymlink(phrenPath) {
346
372
  const target = path.resolve(path.dirname(dest), fs.readlinkSync(dest));
347
373
  if (target === path.resolve(src))
348
374
  return false; // already correct
349
- // Stale symlink pointing elsewhere — managed by phren, safe to replace.
350
- // Match .phren dirs and phren-created links (test runs use /tmp/phren-*/global/CLAUDE.md)
351
- if (target.includes(".phren") || target.endsWith("global/CLAUDE.md"))
375
+ const owningRoot = phrenRootFromGlobalClaudeLink(target);
376
+ if (owningRoot && isLiveForeignPhrenRoot(owningRoot, phrenPath)) {
377
+ debugLog(`refusing to repoint ~/.claude/CLAUDE.md: still owned by live phren root ${owningRoot}`);
378
+ return false;
379
+ }
380
+ // Stale phren wiring — safe to replace. `.includes(".phren")` stays for
381
+ // links that are not shaped like <root>/global/CLAUDE.md.
382
+ if (owningRoot || target.includes(".phren"))
352
383
  fs.unlinkSync(dest);
353
384
  else
354
385
  return false; // not ours, don't touch
@@ -1046,6 +1077,55 @@ export function ensureLocalGitRepo(phrenPath) {
1046
1077
  /** Bootstrap a phren project from an existing project directory with CLAUDE.md.
1047
1078
  * @param profile - if provided, only this profile YAML is updated (avoids leaking project to unrelated profiles).
1048
1079
  */
1080
+ /**
1081
+ * Find an already-registered project that `sourceRoot` should reuse rather than
1082
+ * getting a near-duplicate directory of its own. Two signals, strongest first:
1083
+ *
1084
+ * 1. **Same source path.** Another project already points at this exact
1085
+ * directory — unambiguous, reuse it whatever it is called.
1086
+ * 2. **Same canonical slug.** `max4liveplugins` vs `max4live-plugins`: the same
1087
+ * repo spelled two ways. Only reused when the existing project has no source
1088
+ * path recorded, or records this one — if it points somewhere else it is a
1089
+ * genuinely different project that merely slugs alike, and both are kept.
1090
+ *
1091
+ * Returns `null` when nothing matches, i.e. create the project normally.
1092
+ */
1093
+ function findExistingProjectForSource(phrenPath, sourceRoot, derivedName) {
1094
+ let candidates;
1095
+ try {
1096
+ candidates = fs.readdirSync(phrenPath, { withFileTypes: true })
1097
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
1098
+ .map((entry) => entry.name);
1099
+ }
1100
+ catch (err) {
1101
+ debugLog(`findExistingProjectForSource readdir: ${errorMessage(err)}`);
1102
+ return null;
1103
+ }
1104
+ const sourceOf = (project) => {
1105
+ try {
1106
+ return readProjectConfig(phrenPath, project).sourcePath
1107
+ ? path.resolve(String(readProjectConfig(phrenPath, project).sourcePath))
1108
+ : null;
1109
+ }
1110
+ catch (err) {
1111
+ debugLog(`findExistingProjectForSource config ${project}: ${errorMessage(err)}`);
1112
+ return null;
1113
+ }
1114
+ };
1115
+ const resolvedSource = path.resolve(sourceRoot);
1116
+ for (const project of candidates) {
1117
+ if (sourceOf(project) === resolvedSource)
1118
+ return project;
1119
+ }
1120
+ for (const project of findProjectNamesByCanonicalKey(phrenPath, derivedName)) {
1121
+ if (project === derivedName)
1122
+ return project; // exact match; nothing to reconcile
1123
+ const existingSource = sourceOf(project);
1124
+ if (existingSource === null || existingSource === resolvedSource)
1125
+ return project;
1126
+ }
1127
+ return null;
1128
+ }
1049
1129
  export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
1050
1130
  const profile = typeof opts === "string" ? opts : opts.profile;
1051
1131
  const profilePhrenPath = typeof opts === "string" ? phrenPath : (opts.profilePhrenPath ?? phrenPath);
@@ -1055,7 +1135,18 @@ export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
1055
1135
  }
1056
1136
  const manifest = readRootManifest(phrenPath);
1057
1137
  const isProjectLocal = manifest?.installMode === "project-local";
1058
- const sourceRoot = isProjectLocal ? path.resolve(manifest.workspaceRoot || resolvedPath) : resolvedPath;
1138
+ // A git worktree — notably the agent-managed ones under `.claude/worktrees/`
1139
+ // — is a checkout of a repository we may already track. Attribute it to that
1140
+ // repository instead of registering the worktree's throwaway codename as a
1141
+ // brand-new top-level project.
1142
+ const worktree = isProjectLocal ? null : resolveWorktreeParent(resolvedPath);
1143
+ const worktreeRepoRoot = worktree && fs.existsSync(worktree.repoRoot) ? worktree.repoRoot : null;
1144
+ if (worktreeRepoRoot) {
1145
+ debugLog(`bootstrapFromExisting: ${resolvedPath} is a ${worktree.reason}; attributing to ${worktreeRepoRoot}`);
1146
+ }
1147
+ const sourceRoot = isProjectLocal
1148
+ ? path.resolve(manifest.workspaceRoot || resolvedPath)
1149
+ : (worktreeRepoRoot ?? resolvedPath);
1059
1150
  if (isProjectLocal) {
1060
1151
  const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path.sep);
1061
1152
  if (!matchesWorkspace) {
@@ -1074,9 +1165,15 @@ export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
1074
1165
  }
1075
1166
  }
1076
1167
  const claudeContent = claudeMdPath ? fs.readFileSync(claudeMdPath, "utf8") : null;
1077
- const projectName = isProjectLocal
1168
+ const derivedName = isProjectLocal
1078
1169
  ? String(manifest?.primaryProject)
1079
- : path.basename(sourceRoot).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
1170
+ : projectSlugFromPath(sourceRoot);
1171
+ const projectName = isProjectLocal
1172
+ ? derivedName
1173
+ : (findExistingProjectForSource(phrenPath, sourceRoot, derivedName) ?? derivedName);
1174
+ if (projectName !== derivedName) {
1175
+ debugLog(`bootstrapFromExisting: reusing existing project "${projectName}" for ${sourceRoot} (derived "${derivedName}")`);
1176
+ }
1080
1177
  const existingProject = findProjectNameCaseInsensitive(phrenPath, projectName);
1081
1178
  if (existingProject && existingProject !== projectName) {
1082
1179
  throw new Error(`Project "${existingProject}" already exists with different casing. Refusing to bootstrap "${projectName}" because it would split the same project on case-sensitive filesystems.`);
@@ -1191,12 +1288,19 @@ export function updateMachinesYaml(phrenPath, machine, profile) {
1191
1288
  * A directory qualifies if it:
1192
1289
  * - Is not the home directory or phren directory
1193
1290
  * - Has a CLAUDE.md, AGENTS.md, .claude/CLAUDE.md, or .git directory
1291
+ *
1292
+ * A git worktree resolves to the repository it belongs to. Without this a
1293
+ * throwaway agent worktree under `.claude/worktrees/<codename>` looks like its
1294
+ * own repo (it has a `.git` entry) and gets offered as a new project.
1194
1295
  */
1195
1296
  export function detectProjectDir(dir, phrenPath) {
1196
1297
  const home = os.homedir();
1197
1298
  const tmpRoot = path.resolve(os.tmpdir());
1198
1299
  const resolvedPhrenPath = path.resolve(phrenPath);
1199
- let current = path.resolve(dir);
1300
+ const worktree = resolveWorktreeParent(dir);
1301
+ let current = worktree && fs.existsSync(worktree.repoRoot)
1302
+ ? worktree.repoRoot
1303
+ : path.resolve(dir);
1200
1304
  while (true) {
1201
1305
  // Never treat the shared OS temp root itself as a project. Tools may drop
1202
1306
  // global instruction files there, which would otherwise hijack detection
@@ -0,0 +1,29 @@
1
+ /**
2
+ * The gitignore entries every phren store must have, whichever install mode
3
+ * created it.
4
+ *
5
+ * A store is a git repo that phren itself pushes: `push_changes` and the
6
+ * session-stop hook both run `git add -A` against it, and a synced store has a
7
+ * remote. Anything secret-bearing that is not ignored therefore ends up in a
8
+ * commit — this is exactly how `.config/auth-profiles.json` leaked before
9
+ * credentials moved to `.runtime/`.
10
+ *
11
+ * Both `git add -A` paths already carry an unstage guard for the same set
12
+ * (`tools/finding.ts` push_changes, `cli/session-stop.ts`). That guard is the
13
+ * second line of defence, and only the second: it can unstage a change, but it
14
+ * cannot un-commit a file that some other path — a user's own `git add .`, an
15
+ * editor's git integration — already tracked. .gitignore is the line that
16
+ * stops the file from ever becoming tracked, so the two lists must agree.
17
+ *
18
+ * Kept as a shared const because there were two templates that had already
19
+ * drifted: `packages/cli/starter/.gitignore` (shared mode) and the inline list
20
+ * in `init-configure.ts` (project-local mode). Neither covered `.env`, which
21
+ * `phren init` writes into the store itself and which the docs tell users to
22
+ * put `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `PHREN_LLM_KEY` in.
23
+ */
24
+ export declare const STORE_SECRET_GITIGNORE_LINES: readonly [".runtime/", ".sessions/", ".env", "*.pem", "*.key", ".config/auth-profiles.json"];
25
+ /**
26
+ * Whether a .gitignore body already covers every secret-bearing entry.
27
+ * Compares whole trimmed lines, so a commented-out entry does not count.
28
+ */
29
+ export declare function missingSecretGitignoreLines(content: string): string[];
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The gitignore entries every phren store must have, whichever install mode
3
+ * created it.
4
+ *
5
+ * A store is a git repo that phren itself pushes: `push_changes` and the
6
+ * session-stop hook both run `git add -A` against it, and a synced store has a
7
+ * remote. Anything secret-bearing that is not ignored therefore ends up in a
8
+ * commit — this is exactly how `.config/auth-profiles.json` leaked before
9
+ * credentials moved to `.runtime/`.
10
+ *
11
+ * Both `git add -A` paths already carry an unstage guard for the same set
12
+ * (`tools/finding.ts` push_changes, `cli/session-stop.ts`). That guard is the
13
+ * second line of defence, and only the second: it can unstage a change, but it
14
+ * cannot un-commit a file that some other path — a user's own `git add .`, an
15
+ * editor's git integration — already tracked. .gitignore is the line that
16
+ * stops the file from ever becoming tracked, so the two lists must agree.
17
+ *
18
+ * Kept as a shared const because there were two templates that had already
19
+ * drifted: `packages/cli/starter/.gitignore` (shared mode) and the inline list
20
+ * in `init-configure.ts` (project-local mode). Neither covered `.env`, which
21
+ * `phren init` writes into the store itself and which the docs tell users to
22
+ * put `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `PHREN_LLM_KEY` in.
23
+ */
24
+ export const STORE_SECRET_GITIGNORE_LINES = [
25
+ // Credential store (API keys, OpenAI Codex OAuth access + refresh tokens),
26
+ // debug/hook-error logs, and cached memory content.
27
+ ".runtime/",
28
+ // Session transcripts and per-session message artifacts.
29
+ ".sessions/",
30
+ // Feature flags *and* API keys — see docs/environment.md. Written by
31
+ // `phren init` (ensureDefaultFeatureFlags), so it always exists.
32
+ ".env",
33
+ // Key material a user may have dropped in the store directory.
34
+ "*.pem",
35
+ "*.key",
36
+ // Legacy credential location, pre-`.runtime/` migration. Stays forever so a
37
+ // store created before the move, or one where the migration has not run yet,
38
+ // never has its credentials committed.
39
+ ".config/auth-profiles.json",
40
+ ];
41
+ /**
42
+ * Whether a .gitignore body already covers every secret-bearing entry.
43
+ * Compares whole trimmed lines, so a commented-out entry does not count.
44
+ */
45
+ export function missingSecretGitignoreLines(content) {
46
+ const present = new Set(content.split("\n").map((line) => line.trim()));
47
+ return STORE_SECRET_GITIGNORE_LINES.filter((entry) => !present.has(entry));
48
+ }
@@ -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";
@@ -374,7 +374,7 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
374
374
  }
375
375
  // Store registry health
376
376
  try {
377
- const { resolveAllStores, storesFilePath } = await import("../store-registry.js");
377
+ const { resolveAllStores, storesFilePath, describeUnavailableStore } = await import("../store-registry.js");
378
378
  const storesFile = storesFilePath(phrenPath);
379
379
  if (fs.existsSync(storesFile)) {
380
380
  const stores = resolveAllStores(phrenPath);
@@ -385,14 +385,26 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
385
385
  ? `${stores.length} stores configured`
386
386
  : "stores.yaml exists but no stores parsed",
387
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
+ });
388
400
  for (const store of stores) {
389
- const pathExists = fs.existsSync(store.path);
401
+ const pathExists = store.available !== false;
390
402
  const gitExists = pathExists && fs.existsSync(path.join(store.path, ".git"));
391
403
  if (!pathExists) {
392
404
  checks.push({
393
405
  name: `store:${store.name}`,
394
406
  ok: false,
395
- detail: `store '${store.name}' path missing: ${store.path}`,
407
+ detail: describeUnavailableStore(store),
396
408
  });
397
409
  }
398
410
  else if (!gitExists) {
@@ -425,27 +437,75 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
425
437
  let hookOk = false;
426
438
  let lifecycleOk = false;
427
439
  let hooksEphemeral = false;
428
- 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 = () => {
429
460
  const cfg = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
430
- const hooks = cfg?.hooks || {};
461
+ const hooks = isRecord(cfg?.hooks) ? cfg.hooks : {};
431
462
  const promptHooks = JSON.stringify(hooks.UserPromptSubmit || []);
432
463
  const stopHooks = JSON.stringify(hooks.Stop || []);
433
464
  const startHooks = JSON.stringify(hooks.SessionStart || []);
434
- hookOk = promptHooks.includes("hook-prompt");
435
- const stopHookOk = stopHooks.includes("hook-stop");
436
- const startHookOk = startHooks.includes("hook-session-start");
437
- lifecycleOk = stopHookOk && startHookOk;
438
- // A hook command that points into the npx cache (~/.npm/_npx/<hash>/…)
439
- // works until npx prunes that cache, then breaks silently. Flag it so a
440
- // re-init (which now resolves to the stable ~/.local/bin/phren wrapper)
441
- // can repair it before the user notices context has stopped flowing.
442
- 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;
443
485
  }
444
486
  catch (err) {
445
487
  debugLog(`doctor: failed to read Claude settings for hook check: ${errorMessage(err)}`);
446
488
  hookOk = false;
447
489
  lifecycleOk = false;
448
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
+ }
449
509
  checks.push({
450
510
  name: "claude-hooks",
451
511
  ok: hookOk,
@@ -460,10 +520,16 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
460
520
  });
461
521
  checks.push({
462
522
  name: "hook-path-stable",
463
- ok: !hooksEphemeral,
464
- detail: hooksEphemeral
465
- ? "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"
466
- : "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",
467
533
  });
468
534
  const runtimeHealthPath = runtimeHealthFile(phrenPath);
469
535
  let runtime = null;