@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,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";
@@ -14,6 +16,7 @@ import { GOVERNANCE_SCHEMA_VERSION, } from "../shared/governance.js";
14
16
  import { STOP_WORDS, errorMessage } from "../utils.js";
15
17
  import { ROOT, STARTER_DIR, VERSION, resolveEntryScript, commandVersion, versionAtLeast, nearestWritableTarget } from "./shared.js";
16
18
  import { readInstallPreferences } from "./preferences.js";
19
+ import { getManagementPreset, resolveManagementCapabilities, } from "./management-preset.js";
17
20
  import { TASKS_FILENAME } from "../data/tasks.js";
18
21
  import { FINDINGS_FILENAME } from "../data/access.js";
19
22
  import { getProjectOwnershipDefault, parseProjectOwnershipMode, readProjectConfig, writeProjectConfig, } from "../project-config.js";
@@ -190,32 +193,38 @@ function copyDirRecursive(src, dest) {
190
193
  }
191
194
  function ensureRuntimeAssets(phrenPath) {
192
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.
193
200
  const runtimeDir = path.join(phrenPath, ".runtime");
194
- if (!fs.existsSync(runtimeDir)) {
195
- fs.mkdirSync(runtimeDir, { recursive: true });
201
+ const runtimeExisted = fs.existsSync(runtimeDir);
202
+ ensurePrivateDir(runtimeDir);
203
+ if (!runtimeExisted)
196
204
  created.push(".runtime/");
197
- }
198
205
  const sessions = sessionsDir(phrenPath);
199
- if (!fs.existsSync(sessions)) {
200
- fs.mkdirSync(sessions, { recursive: true });
206
+ const sessionsExisted = fs.existsSync(sessions);
207
+ ensurePrivateDir(sessions);
208
+ if (!sessionsExisted)
201
209
  created.push(".sessions/");
202
- }
203
210
  return created;
204
211
  }
205
- function ensureDefaultFeatureFlags(phrenPath) {
212
+ function ensureDefaultFeatureFlags(phrenPath, preset) {
206
213
  const created = [];
207
214
  const envPath = path.join(phrenPath, ".env");
208
215
  const header = "# phren feature flags — generated by init\n";
209
216
  let content = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf8") : header;
210
217
  let changed = !fs.existsSync(envPath);
211
218
  const lines = content.split("\n");
219
+ // Manual preset opts out of prompt-time auto-capture by default.
220
+ const autoCaptureDefault = preset === "manual" ? "0" : "1";
212
221
  const hasAutoCaptureFlag = lines.some((line) => line.trimStart().startsWith("PHREN_FEATURE_AUTO_CAPTURE="));
213
222
  if (!hasAutoCaptureFlag) {
214
223
  if (!content.endsWith("\n"))
215
224
  content += "\n";
216
- content += "PHREN_FEATURE_AUTO_CAPTURE=1\n";
225
+ content += `PHREN_FEATURE_AUTO_CAPTURE=${autoCaptureDefault}\n`;
217
226
  changed = true;
218
- created.push(".env:PHREN_FEATURE_AUTO_CAPTURE=1");
227
+ created.push(`.env:PHREN_FEATURE_AUTO_CAPTURE=${autoCaptureDefault}`);
219
228
  }
220
229
  if (changed) {
221
230
  atomicWriteText(envPath, content);
@@ -301,15 +310,24 @@ export function upsertProjectEnvVar(repoRoot, key, value) {
301
310
  atomicWriteText(envPath, content);
302
311
  return true;
303
312
  }
304
- export function repairPreexistingInstall(phrenPath) {
313
+ export function repairPreexistingInstall(phrenPath, opts) {
314
+ // Resolve the effective management capabilities. Callers that are applying a
315
+ // not-yet-persisted preset (e.g. init) pass caps explicitly; the every-session
316
+ // self-heal path resolves from stored preferences.
317
+ const caps = opts?.caps ?? resolveManagementCapabilities(phrenPath);
318
+ const preset = opts?.preset ?? getManagementPreset(phrenPath);
305
319
  const createdGovernanceAssets = ensureGovernanceFiles(phrenPath);
306
320
  const createdGlobalAssets = ensureGlobalStarterAssets(phrenPath);
307
321
  const createdRuntimeAssets = [...createdGovernanceAssets, ...ensureRuntimeAssets(phrenPath)];
308
- const createdFeatureDefaults = ensureDefaultFeatureFlags(phrenPath);
322
+ const createdFeatureDefaults = ensureDefaultFeatureFlags(phrenPath, preset);
309
323
  const profileRepair = pruneLegacySampleProjectsFromProfiles(phrenPath);
310
324
  const preferredHome = resolvePreferredHomeDir(phrenPath);
311
- const createdSkillArtifacts = ensureGeneratedSkillArtifacts(phrenPath, preferredHome);
312
- const repairedGlobalSymlink = repairGlobalClaudeSymlink(phrenPath);
325
+ // Structural surfaces (home skills symlinks + ~/.claude/CLAUDE.md) are only
326
+ // created/self-healed under presets that opt into them.
327
+ const createdSkillArtifacts = caps.installSkillLinks
328
+ ? ensureGeneratedSkillArtifacts(phrenPath, preferredHome)
329
+ : [];
330
+ const repairedGlobalSymlink = caps.linkGlobalClaudeMd ? repairGlobalClaudeSymlink(phrenPath) : false;
313
331
  return {
314
332
  profileFilesUpdated: profileRepair.filesUpdated,
315
333
  removedLegacyProjects: profileRepair.removed,
@@ -322,7 +340,27 @@ export function repairPreexistingInstall(phrenPath) {
322
340
  repairedGlobalSymlink,
323
341
  };
324
342
  }
325
- /** 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
+ */
326
364
  function repairGlobalClaudeSymlink(phrenPath) {
327
365
  const src = path.join(phrenPath, "global", "CLAUDE.md");
328
366
  if (!fs.existsSync(src))
@@ -334,9 +372,14 @@ function repairGlobalClaudeSymlink(phrenPath) {
334
372
  const target = path.resolve(path.dirname(dest), fs.readlinkSync(dest));
335
373
  if (target === path.resolve(src))
336
374
  return false; // already correct
337
- // Stale symlink pointing elsewhere — managed by phren, safe to replace.
338
- // Match .phren dirs and phren-created links (test runs use /tmp/phren-*/global/CLAUDE.md)
339
- 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"))
340
383
  fs.unlinkSync(dest);
341
384
  else
342
385
  return false; // not ours, don't touch
@@ -1034,6 +1077,55 @@ export function ensureLocalGitRepo(phrenPath) {
1034
1077
  /** Bootstrap a phren project from an existing project directory with CLAUDE.md.
1035
1078
  * @param profile - if provided, only this profile YAML is updated (avoids leaking project to unrelated profiles).
1036
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
+ }
1037
1129
  export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
1038
1130
  const profile = typeof opts === "string" ? opts : opts.profile;
1039
1131
  const profilePhrenPath = typeof opts === "string" ? phrenPath : (opts.profilePhrenPath ?? phrenPath);
@@ -1043,7 +1135,18 @@ export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
1043
1135
  }
1044
1136
  const manifest = readRootManifest(phrenPath);
1045
1137
  const isProjectLocal = manifest?.installMode === "project-local";
1046
- 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);
1047
1150
  if (isProjectLocal) {
1048
1151
  const matchesWorkspace = resolvedPath === sourceRoot || resolvedPath.startsWith(sourceRoot + path.sep);
1049
1152
  if (!matchesWorkspace) {
@@ -1062,9 +1165,15 @@ export function bootstrapFromExisting(phrenPath, projectPath, opts = {}) {
1062
1165
  }
1063
1166
  }
1064
1167
  const claudeContent = claudeMdPath ? fs.readFileSync(claudeMdPath, "utf8") : null;
1065
- const projectName = isProjectLocal
1168
+ const derivedName = isProjectLocal
1066
1169
  ? String(manifest?.primaryProject)
1067
- : 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
+ }
1068
1177
  const existingProject = findProjectNameCaseInsensitive(phrenPath, projectName);
1069
1178
  if (existingProject && existingProject !== projectName) {
1070
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.`);
@@ -1179,12 +1288,19 @@ export function updateMachinesYaml(phrenPath, machine, profile) {
1179
1288
  * A directory qualifies if it:
1180
1289
  * - Is not the home directory or phren directory
1181
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.
1182
1295
  */
1183
1296
  export function detectProjectDir(dir, phrenPath) {
1184
1297
  const home = os.homedir();
1185
1298
  const tmpRoot = path.resolve(os.tmpdir());
1186
1299
  const resolvedPhrenPath = path.resolve(phrenPath);
1187
- 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);
1188
1304
  while (true) {
1189
1305
  // Never treat the shared OS temp root itself as a project. Tools may drop
1190
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
+ }
@@ -0,0 +1,15 @@
1
+ /** Remove the phren-owned ~/.claude/CLAUDE.md and copilot-instructions.md symlinks. */
2
+ export declare function removePhrenHomeSymlinks(): string[];
3
+ /** Remove ~/.local/bin/{copilot,cursor,codex,phren} wrappers that carry the phren marker. */
4
+ export declare function removePhrenWrappers(): string[];
5
+ /** Remove skill symlinks in agent skill dirs that resolve into the phren store, plus manifests. */
6
+ export declare function sweepAgentSkillSymlinks(phrenPath: string): void;
7
+ /** Remove the given exclude entries (and the phren-managed marker) from a repo's .git/info/exclude. */
8
+ export declare function removeGitExcludes(projectDir: string, entries: string[]): void;
9
+ /**
10
+ * Remove per-project repo mirror symlinks (CLAUDE.md, REFERENCE.md, findings,
11
+ * AGENTS.md, CLAUDE-*.md, .github/copilot-instructions.md, .claude/skills/*) that
12
+ * phren created in phren-managed repos, and strip the matching exclude lines.
13
+ * Only removes symlinks that resolve back into the phren store.
14
+ */
15
+ export declare function sweepProjectMirrors(phrenPath: string): void;
@@ -0,0 +1,241 @@
1
+ /**
2
+ * Teardown helpers: remove phren-owned symlinks, wrappers, and repo mirrors.
3
+ *
4
+ * Shared by `phren uninstall` and `phren preset` downgrades. Everything here
5
+ * only ever removes artifacts phren itself created — symlinks that resolve into
6
+ * the store, wrappers carrying the phren marker, and `.git/info/exclude` lines
7
+ * under the phren-managed marker. User-owned files are never touched.
8
+ */
9
+ import * as fs from "fs";
10
+ import * as path from "path";
11
+ import { homeDir, homePath, getProjectDirs } from "../phren-paths.js";
12
+ import { debugLog } from "../shared.js";
13
+ import { errorMessage } from "../utils.js";
14
+ import { log } from "./shared.js";
15
+ import { FINDINGS_FILENAME } from "../data/access.js";
16
+ import { getProjectOwnershipMode, readProjectConfig } from "../project-config.js";
17
+ import { findProjectDir } from "../project-locator.js";
18
+ function agentSkillDirs() {
19
+ const home = homeDir();
20
+ return [
21
+ homePath(".claude", "skills"),
22
+ path.join(home, ".cursor", "skills"),
23
+ path.join(home, ".copilot", "skills"),
24
+ path.join(home, ".codex", "skills"),
25
+ ];
26
+ }
27
+ /** Remove the phren-owned ~/.claude/CLAUDE.md and copilot-instructions.md symlinks. */
28
+ export function removePhrenHomeSymlinks() {
29
+ const removed = [];
30
+ for (const link of [homePath(".claude", "CLAUDE.md"), homePath(".github", "copilot-instructions.md")]) {
31
+ try {
32
+ if (fs.lstatSync(link).isSymbolicLink()) {
33
+ fs.unlinkSync(link);
34
+ log(` Removed symlink: ${link}`);
35
+ removed.push(link);
36
+ }
37
+ }
38
+ catch {
39
+ // Missing or a regular file (user-owned) — leave it alone.
40
+ }
41
+ }
42
+ return removed;
43
+ }
44
+ /** Remove ~/.local/bin/{copilot,cursor,codex,phren} wrappers that carry the phren marker. */
45
+ export function removePhrenWrappers() {
46
+ const removed = [];
47
+ const localBinDir = path.join(homeDir(), ".local", "bin");
48
+ for (const tool of ["copilot", "cursor", "codex", "phren"]) {
49
+ const wrapperPath = path.join(localBinDir, tool);
50
+ try {
51
+ if (fs.existsSync(wrapperPath)) {
52
+ const content = fs.readFileSync(wrapperPath, "utf8");
53
+ if (content.includes("PHREN_PATH") && content.includes("phren")) {
54
+ fs.unlinkSync(wrapperPath);
55
+ log(` Removed ${tool} wrapper (${wrapperPath})`);
56
+ removed.push(wrapperPath);
57
+ }
58
+ }
59
+ }
60
+ catch (err) {
61
+ debugLog(`removePhrenWrappers: cleanup failed for ${wrapperPath}: ${errorMessage(err)}`);
62
+ }
63
+ }
64
+ return removed;
65
+ }
66
+ /** Remove skill symlinks in agent skill dirs that resolve into the phren store, plus manifests. */
67
+ export function sweepAgentSkillSymlinks(phrenPath) {
68
+ const resolvedPhren = path.resolve(phrenPath);
69
+ for (const dir of agentSkillDirs()) {
70
+ if (!fs.existsSync(dir))
71
+ continue;
72
+ let entries;
73
+ try {
74
+ entries = fs.readdirSync(dir, { withFileTypes: true });
75
+ }
76
+ catch (err) {
77
+ debugLog(`sweepAgentSkillSymlinks: readdirSync failed for ${dir}: ${errorMessage(err)}`);
78
+ continue;
79
+ }
80
+ for (const entry of entries) {
81
+ if (!entry.isSymbolicLink())
82
+ continue;
83
+ const fullPath = path.join(dir, entry.name);
84
+ try {
85
+ const target = fs.realpathSync(fullPath);
86
+ if (target.startsWith(resolvedPhren + path.sep) || target === resolvedPhren) {
87
+ fs.unlinkSync(fullPath);
88
+ log(` Removed skill symlink: ${fullPath}`);
89
+ }
90
+ }
91
+ catch {
92
+ // Broken symlink — only remove it if it clearly pointed into the store.
93
+ try {
94
+ const raw = fs.readlinkSync(fullPath);
95
+ const resolved = path.resolve(dir, raw);
96
+ if (resolved.startsWith(resolvedPhren + path.sep) || resolved === resolvedPhren) {
97
+ fs.unlinkSync(fullPath);
98
+ log(` Removed broken skill symlink: ${fullPath}`);
99
+ }
100
+ }
101
+ catch (err2) {
102
+ debugLog(`sweepAgentSkillSymlinks: could not inspect ${fullPath}: ${errorMessage(err2)}`);
103
+ }
104
+ }
105
+ }
106
+ const parentDir = path.dirname(dir);
107
+ for (const manifestFile of ["skill-manifest.json", "skill-commands.json"]) {
108
+ const manifestPath = path.join(parentDir, manifestFile);
109
+ try {
110
+ if (fs.existsSync(manifestPath)) {
111
+ fs.unlinkSync(manifestPath);
112
+ log(` Removed ${manifestFile} (${manifestPath})`);
113
+ }
114
+ }
115
+ catch (err) {
116
+ debugLog(`sweepAgentSkillSymlinks: could not remove ${manifestPath}: ${errorMessage(err)}`);
117
+ }
118
+ }
119
+ }
120
+ }
121
+ /** Remove the given exclude entries (and the phren-managed marker) from a repo's .git/info/exclude. */
122
+ export function removeGitExcludes(projectDir, entries) {
123
+ const excludePath = path.join(projectDir, ".git", "info", "exclude");
124
+ if (!fs.existsSync(excludePath))
125
+ return;
126
+ try {
127
+ const removeSet = new Set(entries);
128
+ const lines = fs.readFileSync(excludePath, "utf8").split("\n");
129
+ const kept = lines.filter((line) => {
130
+ const trimmed = line.trim();
131
+ if (trimmed === "# phren-managed")
132
+ return false;
133
+ return !removeSet.has(trimmed);
134
+ });
135
+ // Collapse any trailing blank lines we may have introduced.
136
+ while (kept.length > 1 && kept[kept.length - 1].trim() === "" && kept[kept.length - 2].trim() === "") {
137
+ kept.pop();
138
+ }
139
+ const next = kept.join("\n");
140
+ if (next !== lines.join("\n")) {
141
+ fs.writeFileSync(excludePath, next.endsWith("\n") || next === "" ? next : next + "\n");
142
+ log(` Cleaned phren entries from ${excludePath}`);
143
+ }
144
+ }
145
+ catch (err) {
146
+ debugLog(`removeGitExcludes: failed for ${projectDir}: ${errorMessage(err)}`);
147
+ }
148
+ }
149
+ /**
150
+ * Remove per-project repo mirror symlinks (CLAUDE.md, REFERENCE.md, findings,
151
+ * AGENTS.md, CLAUDE-*.md, .github/copilot-instructions.md, .claude/skills/*) that
152
+ * phren created in phren-managed repos, and strip the matching exclude lines.
153
+ * Only removes symlinks that resolve back into the phren store.
154
+ */
155
+ export function sweepProjectMirrors(phrenPath) {
156
+ const resolvedPhren = path.resolve(phrenPath);
157
+ const resolvesIntoStore = (p) => {
158
+ try {
159
+ const target = fs.realpathSync(p);
160
+ return target.startsWith(resolvedPhren + path.sep) || target === resolvedPhren;
161
+ }
162
+ catch {
163
+ // Broken symlink — check its raw (unresolved) target.
164
+ try {
165
+ const raw = fs.readlinkSync(p);
166
+ const resolved = path.resolve(path.dirname(p), raw);
167
+ return resolved.startsWith(resolvedPhren + path.sep) || resolved === resolvedPhren;
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ }
173
+ };
174
+ for (const projectDir of getProjectDirs(phrenPath)) {
175
+ const project = path.basename(projectDir);
176
+ if (project === "global")
177
+ continue;
178
+ let ownership;
179
+ try {
180
+ const config = readProjectConfig(phrenPath, project);
181
+ ownership = getProjectOwnershipMode(phrenPath, project, config);
182
+ }
183
+ catch (err) {
184
+ debugLog(`sweepProjectMirrors: config read failed for ${project}: ${errorMessage(err)}`);
185
+ continue;
186
+ }
187
+ if (ownership !== "phren-managed")
188
+ continue;
189
+ const repo = findProjectDir(project);
190
+ if (!repo || !fs.existsSync(repo))
191
+ continue;
192
+ const removedEntries = [];
193
+ const removeMirror = (relPath) => {
194
+ const full = path.join(repo, relPath);
195
+ let stat;
196
+ try {
197
+ stat = fs.lstatSync(full);
198
+ }
199
+ catch {
200
+ return;
201
+ }
202
+ if (!stat.isSymbolicLink())
203
+ return;
204
+ if (!resolvesIntoStore(full))
205
+ return;
206
+ try {
207
+ fs.unlinkSync(full);
208
+ log(` Removed repo mirror: ${full}`);
209
+ removedEntries.push(relPath);
210
+ }
211
+ catch (err) {
212
+ debugLog(`sweepProjectMirrors: could not remove ${full}: ${errorMessage(err)}`);
213
+ }
214
+ };
215
+ // Fixed mirror files.
216
+ for (const f of ["CLAUDE.md", "REFERENCE.md", FINDINGS_FILENAME, "AGENTS.md", path.join(".github", "copilot-instructions.md")]) {
217
+ removeMirror(f);
218
+ }
219
+ // CLAUDE-*.md split files.
220
+ try {
221
+ for (const f of fs.readdirSync(repo)) {
222
+ if (/^CLAUDE-.+\.md$/.test(f))
223
+ removeMirror(f);
224
+ }
225
+ }
226
+ catch { /* repo unreadable — skip */ }
227
+ // Project skill symlinks under .claude/skills.
228
+ const skillsDir = path.join(repo, ".claude", "skills");
229
+ if (fs.existsSync(skillsDir)) {
230
+ try {
231
+ for (const entry of fs.readdirSync(skillsDir, { withFileTypes: true })) {
232
+ if (entry.isSymbolicLink())
233
+ removeMirror(path.join(".claude", "skills", entry.name));
234
+ }
235
+ }
236
+ catch { /* skills dir unreadable — skip */ }
237
+ }
238
+ if (removedEntries.length > 0)
239
+ removeGitExcludes(repo, removedEntries);
240
+ }
241
+ }