@phren/cli 0.1.40 → 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 (105) 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-git.d.ts +18 -0
  11. package/dist/cli/session-git.js +47 -0
  12. package/dist/cli/session-start.js +2 -2
  13. package/dist/cli/session-stop.d.ts +11 -0
  14. package/dist/cli/session-stop.js +141 -33
  15. package/dist/cli/session-tool-hook.js +17 -5
  16. package/dist/cli-registry.d.ts +1 -1
  17. package/dist/cli-registry.js +1 -0
  18. package/dist/content/dedup.d.ts +1 -4
  19. package/dist/content/dedup.js +7 -63
  20. package/dist/content/learning.d.ts +20 -2
  21. package/dist/content/learning.js +21 -3
  22. package/dist/content/quality.d.ts +23 -0
  23. package/dist/content/quality.js +123 -0
  24. package/dist/content/secrets.d.ts +52 -0
  25. package/dist/content/secrets.js +193 -0
  26. package/dist/data/access.d.ts +56 -2
  27. package/dist/data/access.js +246 -24
  28. package/dist/entrypoint.js +5 -1
  29. package/dist/finding/impact.js +170 -43
  30. package/dist/finding/lifecycle.d.ts +19 -2
  31. package/dist/finding/lifecycle.js +15 -3
  32. package/dist/git-worktree.d.ts +19 -0
  33. package/dist/git-worktree.js +117 -0
  34. package/dist/governance/policy.d.ts +84 -4
  35. package/dist/governance/policy.js +209 -14
  36. package/dist/governance/rbac.d.ts +8 -0
  37. package/dist/governance/rbac.js +26 -0
  38. package/dist/hooks.d.ts +20 -0
  39. package/dist/hooks.js +113 -3
  40. package/dist/index.js +5 -1
  41. package/dist/init/guard-globals.d.ts +20 -0
  42. package/dist/init/guard-globals.js +72 -6
  43. package/dist/init/init-configure.js +6 -6
  44. package/dist/init/init.js +10 -6
  45. package/dist/init/setup.d.ts +4 -3
  46. package/dist/init/setup.js +120 -16
  47. package/dist/init/store-gitignore.d.ts +29 -0
  48. package/dist/init/store-gitignore.js +48 -0
  49. package/dist/link/doctor.js +86 -20
  50. package/dist/phren-core.d.ts +35 -8
  51. package/dist/phren-core.js +35 -8
  52. package/dist/phren-paths.d.ts +90 -1
  53. package/dist/phren-paths.js +150 -5
  54. package/dist/proactivity.js +1 -1
  55. package/dist/shared/embedding-cache.d.ts +16 -0
  56. package/dist/shared/embedding-cache.js +24 -0
  57. package/dist/shared/fragment-graph.js +10 -0
  58. package/dist/shared/index.d.ts +6 -0
  59. package/dist/shared/index.js +523 -138
  60. package/dist/shared/ollama.d.ts +14 -2
  61. package/dist/shared/ollama.js +84 -5
  62. package/dist/shared/retrieval.d.ts +22 -1
  63. package/dist/shared/retrieval.js +30 -1
  64. package/dist/shared/search-fallback.js +15 -3
  65. package/dist/shared/vector-index.d.ts +20 -1
  66. package/dist/shared/vector-index.js +18 -4
  67. package/dist/shared.d.ts +1 -1
  68. package/dist/shared.js +1 -1
  69. package/dist/status.js +18 -1
  70. package/dist/store-registry.d.ts +22 -0
  71. package/dist/store-registry.js +36 -3
  72. package/dist/task/lifecycle.js +31 -0
  73. package/dist/tools/config.js +16 -7
  74. package/dist/tools/data.js +1 -1
  75. package/dist/tools/extract.js +2 -2
  76. package/dist/tools/finding.js +14 -3
  77. package/dist/tools/graph.js +9 -1
  78. package/dist/tools/memory.js +1 -1
  79. package/dist/tools/notes.js +3 -3
  80. package/dist/tools/ops.js +19 -18
  81. package/dist/tools/search.js +2 -2
  82. package/dist/tools/session.js +2 -2
  83. package/dist/tools/tasks.js +2 -2
  84. package/dist/tools/types.d.ts +32 -2
  85. package/dist/tools/types.js +41 -8
  86. package/dist/ui/scripts.js +2 -2
  87. package/dist/ui/server.js +5 -0
  88. package/package.json +1 -1
  89. package/dist/cli-hooks-git.d.ts +0 -50
  90. package/dist/cli-hooks-git.js +0 -288
  91. package/starter/my-api/.claude/skills/README.md +0 -7
  92. package/starter/my-api/CLAUDE.md +0 -33
  93. package/starter/my-api/FINDINGS.md +0 -9
  94. package/starter/my-api/summary.md +0 -7
  95. package/starter/my-api/tasks.md +0 -7
  96. package/starter/my-first-project/.claude/skills/README.md +0 -7
  97. package/starter/my-first-project/CLAUDE.md +0 -49
  98. package/starter/my-first-project/FINDINGS.md +0 -24
  99. package/starter/my-first-project/summary.md +0 -11
  100. package/starter/my-first-project/tasks.md +0 -25
  101. package/starter/my-frontend/.claude/skills/README.md +0 -7
  102. package/starter/my-frontend/CLAUDE.md +0 -33
  103. package/starter/my-frontend/FINDINGS.md +0 -9
  104. package/starter/my-frontend/summary.md +0 -7
  105. package/starter/my-frontend/tasks.md +0 -7
package/dist/hooks.d.ts CHANGED
@@ -14,6 +14,26 @@ export declare function detectInstalledTools(): Set<string>;
14
14
  * re-resolves on every run) or the ~/.local/bin/phren wrapper instead.
15
15
  */
16
16
  export declare function isEphemeralNpxPath(p: string): boolean;
17
+ /**
18
+ * The local file a hook command depends on — the `~/.local/bin/phren` wrapper,
19
+ * or the script passed to `node`.
20
+ *
21
+ * Returns `null` for commands that re-resolve themselves on every run
22
+ * (`npx -y @phren/cli …`), which cannot go stale, and for commands with no
23
+ * recognisable path.
24
+ *
25
+ * Why this matters: `npm install -g @phren/cli` can move the package entry
26
+ * between versions (0.1.40 moved it from `mcp/dist/index.js` to
27
+ * `dist/index.js`). Hook commands in settings.json keep the old absolute path
28
+ * and every hook then dies with MODULE_NOT_FOUND on every prompt and every
29
+ * Stop — silently, because hook failures are not surfaced.
30
+ */
31
+ export declare function extractHookScriptPath(command: string): string | null;
32
+ /**
33
+ * Hook commands whose entrypoint no longer exists on disk. Deduplicated, so an
34
+ * upgrade that breaks all four lifecycle hooks reports one path, not four.
35
+ */
36
+ export declare function findStaleHookEntrypoints(commands: readonly string[]): string[];
17
37
  /** Shell-escape a value by wrapping in single quotes with proper escaping of embedded single quotes. */
18
38
  export declare function shellEscape(s: string): string;
19
39
  export interface LifecycleCommands {
package/dist/hooks.js CHANGED
@@ -12,6 +12,9 @@ import { PACKAGE_SPEC } from "./package-metadata.js";
12
12
  import { logger } from "./logger.js";
13
13
  import { withFileLock } from "./shared/governance.js";
14
14
  import { resolveManagementCapabilities } from "./init/management-preset.js";
15
+ // Dependency-free leaf module — hooks.ts runs in a per-PostToolUse subprocess
16
+ // and must not pull in content/dedup.ts's import graph.
17
+ import { redactSecretsForLog } from "./content/secrets.js";
15
18
  export function commandExists(cmd) {
16
19
  try {
17
20
  const whichCmd = process.platform === "win32" ? "where.exe" : "which";
@@ -77,6 +80,98 @@ function resolveCliEntryScript() {
77
80
  export function isEphemeralNpxPath(p) {
78
81
  return /(^|[/\\])_npx[/\\]/.test(p);
79
82
  }
83
+ /** Split a hook command into tokens, honouring single and double quotes. */
84
+ function tokenizeCommand(command) {
85
+ const tokens = [];
86
+ let current = "";
87
+ let quote = null;
88
+ let started = false;
89
+ for (const ch of command) {
90
+ if (quote) {
91
+ if (ch === quote)
92
+ quote = null;
93
+ else
94
+ current += ch;
95
+ continue;
96
+ }
97
+ if (ch === '"' || ch === "'") {
98
+ quote = ch;
99
+ started = true;
100
+ continue;
101
+ }
102
+ if (/\s/.test(ch)) {
103
+ if (started || current)
104
+ tokens.push(current);
105
+ current = "";
106
+ started = false;
107
+ continue;
108
+ }
109
+ current += ch;
110
+ started = true;
111
+ }
112
+ if (started || current)
113
+ tokens.push(current);
114
+ return tokens;
115
+ }
116
+ function isPathLike(token) {
117
+ return token.startsWith("/")
118
+ || token.startsWith("~/")
119
+ || token.startsWith("\\\\")
120
+ || /^[A-Za-z]:[\\/]/.test(token);
121
+ }
122
+ /**
123
+ * The local file a hook command depends on — the `~/.local/bin/phren` wrapper,
124
+ * or the script passed to `node`.
125
+ *
126
+ * Returns `null` for commands that re-resolve themselves on every run
127
+ * (`npx -y @phren/cli …`), which cannot go stale, and for commands with no
128
+ * recognisable path.
129
+ *
130
+ * Why this matters: `npm install -g @phren/cli` can move the package entry
131
+ * between versions (0.1.40 moved it from `mcp/dist/index.js` to
132
+ * `dist/index.js`). Hook commands in settings.json keep the old absolute path
133
+ * and every hook then dies with MODULE_NOT_FOUND on every prompt and every
134
+ * Stop — silently, because hook failures are not surfaced.
135
+ */
136
+ export function extractHookScriptPath(command) {
137
+ if (!command)
138
+ return null;
139
+ // `npx` re-resolves the package each run, so it is never stale.
140
+ if (/(^|\s)npx(\.cmd)?(\s|$)/.test(command))
141
+ return null;
142
+ const tokens = tokenizeCommand(command);
143
+ for (let i = 0; i < tokens.length; i++) {
144
+ const token = tokens[i];
145
+ if (!token)
146
+ continue;
147
+ // Skip shell scaffolding: `set`, `&&`, and `VAR=value` assignments.
148
+ if (token === "&&" || token === "set" || /^[A-Za-z_][A-Za-z0-9_]*=/.test(token))
149
+ continue;
150
+ if (/^node(\.exe)?$/i.test(token)) {
151
+ const next = tokens[i + 1];
152
+ return next && isPathLike(next) ? next : null;
153
+ }
154
+ if (isPathLike(token))
155
+ return token;
156
+ }
157
+ return null;
158
+ }
159
+ /**
160
+ * Hook commands whose entrypoint no longer exists on disk. Deduplicated, so an
161
+ * upgrade that breaks all four lifecycle hooks reports one path, not four.
162
+ */
163
+ export function findStaleHookEntrypoints(commands) {
164
+ const stale = new Set();
165
+ for (const command of commands) {
166
+ const scriptPath = extractHookScriptPath(command);
167
+ if (!scriptPath)
168
+ continue;
169
+ const expanded = scriptPath.startsWith("~/") ? homePath(scriptPath.slice(2)) : scriptPath;
170
+ if (!fs.existsSync(expanded))
171
+ stale.add(scriptPath);
172
+ }
173
+ return [...stale];
174
+ }
80
175
  function phrenPackageSpec() {
81
176
  return PACKAGE_SPEC;
82
177
  }
@@ -670,9 +765,24 @@ export function readCustomHooks(phrenPath) {
670
765
  return [];
671
766
  }
672
767
  }
768
+ /**
769
+ * Every path that reports a custom-hook failure funnels through here and
770
+ * through buildHookErrorMessage below, so redaction happens in one place.
771
+ *
772
+ * The composed message is the hook's own command plus the child's stderr.
773
+ * Hook commands legitimately carry inline credentials — `curl -H
774
+ * "Authorization: Bearer …"` contains none of the shell metacharacters
775
+ * validateCustomHookCommand rejects — and a failing child prints whatever it
776
+ * wants to stderr, which execFileSync appends to the thrown error's message.
777
+ * That string was going verbatim into .runtime/hook-errors.log *and* back to
778
+ * the MCP caller, i.e. into the agent's context and transcript.
779
+ */
780
+ function buildHookErrorMessage(event, command, detail) {
781
+ return redactSecretsForLog(`${event}: ${command}: ${detail}`);
782
+ }
673
783
  function appendHookErrorLog(phrenPath, event, message) {
674
784
  const logPath = runtimeFile(phrenPath, "hook-errors.log");
675
- const line = `[${new Date().toISOString()}] [${event}] ${message}\n`;
785
+ const line = `[${new Date().toISOString()}] [${event}] ${redactSecretsForLog(message)}\n`;
676
786
  try {
677
787
  withFileLock(logPath, () => {
678
788
  fs.appendFileSync(logPath, line);
@@ -771,7 +881,7 @@ export function runCustomHooks(phrenPath, event, env = {}) {
771
881
  });
772
882
  }
773
883
  catch (err) {
774
- const message = `${event}: ${hook.command}: ${errorMessage(err)}`;
884
+ const message = buildHookErrorMessage(event, hook.command, errorMessage(err));
775
885
  debugLog(`runCustomHooks: ${message}`);
776
886
  errors.push({ code: PhrenError.VALIDATION_ERROR, message });
777
887
  try {
@@ -880,7 +990,7 @@ export function runPrePromptHooks(phrenPath, stdinJson, siblingCommandsOverride)
880
990
  outputs.push(trimmed);
881
991
  }
882
992
  catch (err) {
883
- const message = `pre-prompt: ${hook.command}: ${errorMessage(err)}`;
993
+ const message = buildHookErrorMessage("pre-prompt", hook.command, errorMessage(err));
884
994
  debugLog(`runPrePromptHooks: ${message}`);
885
995
  try {
886
996
  appendHookErrorLog(phrenPath, "pre-prompt", errorMessage(err));
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
- import { findPhrenPathWithArg, debugLog, runtimeDir, } from "./shared.js";
4
+ import { findPhrenPathWithArg, debugLog, ensureFtsCacheRootPrivate, runtimeDir, } from "./shared.js";
5
5
  import { log as structuredLog, logger } from "./logger.js";
6
6
  import { errorMessage } from "./utils.js";
7
7
  import { printIntegratedHelp, printIntegratedVersion, resolveTopLevelInvocation, runTopLevelCommand, } from "./entrypoint.js";
@@ -70,6 +70,10 @@ async function main() {
70
70
  ]);
71
71
  const profile = resolveRuntimeProfile(phrenPath);
72
72
  cleanStaleLocks(phrenPath);
73
+ // Before buildIndex() writes the first snapshot: the FTS cache is a full
74
+ // SQLite export of the store, and on Linux it lands in a world-readable
75
+ // /tmp. A 0700 root makes it unreachable to other local accounts.
76
+ ensureFtsCacheRootPrivate();
73
77
  let db = null;
74
78
  let indexReady = false;
75
79
  let shuttingDown = false;
@@ -2,5 +2,25 @@ export interface WiringConflict {
2
2
  location: string;
3
3
  existingPath: string;
4
4
  }
5
+ /**
6
+ * A path counts as a "valid phren root" only if it currently looks like one
7
+ * — root manifest, machines.yaml, or the global skills tree. We deliberately
8
+ * tolerate partial roots so a clean `phren init` repair still works.
9
+ */
10
+ export declare function looksLikePhrenRoot(candidate: string): boolean;
11
+ /**
12
+ * True when `candidate` is a *different* phren root than the one being
13
+ * installed and still looks live. That combination is the one case where
14
+ * rewriting a global file destroys wiring someone is actually using; a stale
15
+ * root (deleted, or never a root) is exactly what init exists to repair.
16
+ */
17
+ export declare function isLiveForeignPhrenRoot(candidate: string, newPhrenPath: string): boolean;
18
+ /**
19
+ * Recover the phren root that owns a `~/.claude/CLAUDE.md` symlink, from the
20
+ * link target's shape (`<root>/global/CLAUDE.md`). Returns null when the
21
+ * target is not structured like a phren global file, i.e. it belongs to
22
+ * something that is not phren and must not be touched.
23
+ */
24
+ export declare function phrenRootFromGlobalClaudeLink(target: string): string | null;
5
25
  export declare function findConflictingGlobalWiring(newPhrenPath: string): WiringConflict[];
6
26
  export declare function assertNoGlobalWiringConflict(newPhrenPath: string, force: boolean): void;
@@ -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[];