@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
@@ -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;
@@ -1,4 +1,5 @@
1
1
  import { repairPreexistingInstall } from "./setup.js";
2
+ import { type ManagementCapabilities, type ManagementPreset } from "./management-preset.js";
2
3
  import type { InitOptions } from "./init.js";
3
4
  /**
4
5
  * Configure MCP for all detected AI coding tools (Claude, VS Code, Cursor, Copilot, Codex).
@@ -7,14 +8,18 @@ import type { InitOptions } from "./init.js";
7
8
  export declare function configureMcpTargets(phrenPath: string, opts: {
8
9
  mcpEnabled: boolean;
9
10
  hooksEnabled: boolean;
11
+ caps?: ManagementCapabilities;
10
12
  }, verb?: "Configured" | "Updated"): string;
11
13
  /**
12
14
  * Configure hooks if enabled, or log a disabled message.
13
15
  * @param verb - label used in log messages, e.g. "Updated" or "Configured"
14
16
  */
15
- export declare function configureHooksIfEnabled(phrenPath: string, hooksEnabled: boolean, verb: string): void;
17
+ export declare function configureHooksIfEnabled(phrenPath: string, hooksEnabled: boolean, verb: string, caps?: ManagementCapabilities): void;
16
18
  export declare function applyOnboardingPreferences(phrenPath: string, opts: InitOptions): void;
17
- export declare function writeWalkthroughEnvDefaults(phrenPath: string, opts: InitOptions): string[];
19
+ export declare function writeWalkthroughEnvDefaults(phrenPath: string, opts: InitOptions, presetContext?: {
20
+ preset: ManagementPreset;
21
+ explicit: boolean;
22
+ }): string[];
18
23
  export declare function collectRepairedAssetLabels(repaired: ReturnType<typeof repairPreexistingInstall>): string[];
19
24
  export declare function applyProjectStorageBindings(repoRoot: string, phrenPath: string): string[];
20
25
  export declare function warmSemanticSearch(phrenPath: string, profile?: string): Promise<string>;
@@ -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";
@@ -15,23 +16,29 @@ import { VERSION } from "./shared.js";
15
16
  import { writeInstallPreferences, writeGovernanceInstallPreferences, } from "./preferences.js";
16
17
  import { repairPreexistingInstall, ensureGovernanceFiles, ensureGitignoreEntry, upsertProjectEnvVar, detectProjectDir, bootstrapFromExisting, runPostInitVerify, } from "./setup.js";
17
18
  import { log } from "./shared.js";
19
+ import { resolveManagementCapabilities, getManagementPreset } from "./management-preset.js";
18
20
  /**
19
21
  * Configure MCP for all detected AI coding tools (Claude, VS Code, Cursor, Copilot, Codex).
20
22
  * @param verb - label used in log messages, e.g. "Updated" or "Configured"
21
23
  */
22
24
  export function configureMcpTargets(phrenPath, opts, verb = "Configured") {
25
+ const caps = opts.caps ?? resolveManagementCapabilities(phrenPath);
23
26
  // Install the stable ~/.local/bin/phren wrapper BEFORE writing any hook
24
27
  // commands. buildLifecycleCommands prefers that wrapper (it carries an npx
25
28
  // fallback, so it survives nvm switches and npx cache clears); if it doesn't
26
29
  // yet exist, hook commands fall through to the ephemeral npx-cache entry path
27
30
  // and break the next time npx prunes its cache. configureHooksIfEnabled runs
28
31
  // later and re-installs the wrapper idempotently, emitting the user-facing
29
- // "CLI wrapper" line — this early install is intentionally silent.
30
- try {
31
- installPhrenCliWrapper(phrenPath);
32
- }
33
- catch (err) {
34
- debugLog(`configureMcpTargets: early wrapper install failed: ${errorMessage(err)}`);
32
+ // "CLI wrapper" line — this early install is intentionally silent. Presets
33
+ // that opt out of wrappers (assisted/manual) skip it; hooks then use the
34
+ // node/npx invocation form.
35
+ if (caps.installWrappers) {
36
+ try {
37
+ installPhrenCliWrapper(phrenPath);
38
+ }
39
+ catch (err) {
40
+ debugLog(`configureMcpTargets: early wrapper install failed: ${errorMessage(err)}`);
41
+ }
35
42
  }
36
43
  let claudeStatus = "no_settings";
37
44
  try {
@@ -90,10 +97,11 @@ export function configureMcpTargets(phrenPath, opts, verb = "Configured") {
90
97
  * Configure hooks if enabled, or log a disabled message.
91
98
  * @param verb - label used in log messages, e.g. "Updated" or "Configured"
92
99
  */
93
- export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb) {
100
+ export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb, caps) {
101
+ const resolvedCaps = caps ?? resolveManagementCapabilities(phrenPath);
94
102
  if (hooksEnabled) {
95
103
  try {
96
- const hooked = configureAllHooks(phrenPath, { allTools: true });
104
+ const hooked = configureAllHooks(phrenPath, { allTools: true, installWrappers: resolvedCaps.installWrappers });
97
105
  if (hooked.length)
98
106
  log(` ${verb} hooks: ${hooked.join(", ")}`);
99
107
  }
@@ -104,6 +112,12 @@ export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb) {
104
112
  else {
105
113
  log(` Hooks are disabled by preference (run: phren hooks-mode on)`);
106
114
  }
115
+ // Presets that opt out of wrappers (assisted/manual) leave the user's PATH and
116
+ // ~/.local/bin untouched; hooks fall back to the node/npx invocation form.
117
+ if (!resolvedCaps.installWrappers) {
118
+ log(` CLI wrapper: skipped (${getManagementPreset(phrenPath)} preset) — use 'npx @phren/cli <command>' or a global install`);
119
+ return;
120
+ }
107
121
  // Install phren CLI wrapper at ~/.local/bin/phren so the bare command works
108
122
  const wrapperInstalled = installPhrenCliWrapper(phrenPath);
109
123
  if (wrapperInstalled) {
@@ -158,13 +172,26 @@ export function applyOnboardingPreferences(phrenPath, opts) {
158
172
  updateWorkflowPolicy(phrenPath, workflowPatch);
159
173
  }
160
174
  }
161
- export function writeWalkthroughEnvDefaults(phrenPath, opts) {
175
+ export function writeWalkthroughEnvDefaults(phrenPath, opts, presetContext) {
162
176
  const envFile = path.join(phrenPath, ".env");
163
177
  let envContent = fs.existsSync(envFile) ? fs.readFileSync(envFile, "utf8") : "# phren feature flags — generated by init\n";
164
178
  const envFlags = [];
179
+ const manualPreset = presetContext?.preset === "manual";
180
+ const presetExplicit = presetContext?.explicit === true;
165
181
  const autoCaptureChoice = opts._walkthroughAutoCapture;
166
182
  const hasAutoCaptureFlag = /^\s*PHREN_FEATURE_AUTO_CAPTURE=.*$/m.test(envContent);
167
- if (typeof autoCaptureChoice === "boolean") {
183
+ if (manualPreset) {
184
+ // Manual preset turns off the prompt-time/background automations. Force the
185
+ // flags to 0 only when the preset was explicitly chosen this run; on a plain
186
+ // re-init we respect any lines the user already set.
187
+ for (const key of ["PHREN_FEATURE_AUTO_CAPTURE", "PHREN_FEATURE_AUTO_EXTRACT", "PHREN_FEATURE_DAILY_MAINTENANCE"]) {
188
+ const present = new RegExp(`^\\s*${key}=.*$`, "m").test(envContent);
189
+ if (presetExplicit || !present) {
190
+ envFlags.push({ flag: `${key}=0`, label: `${key.replace("PHREN_FEATURE_", "").toLowerCase().replace(/_/g, " ")} disabled (manual preset)` });
191
+ }
192
+ }
193
+ }
194
+ else if (typeof autoCaptureChoice === "boolean") {
168
195
  envFlags.push({
169
196
  flag: `PHREN_FEATURE_AUTO_CAPTURE=${autoCaptureChoice ? "1" : "0"}`,
170
197
  label: `Auto-capture ${autoCaptureChoice ? "enabled" : "disabled"}`,
@@ -296,7 +323,7 @@ export async function runProjectLocalInit(opts = {}) {
296
323
  opts.projectOwnershipDefault = ownershipDefault;
297
324
  }
298
325
  const mcpEnabled = opts.mcp ? opts.mcp === "on" : true;
299
- const projectName = path.basename(workspaceRoot).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
326
+ const projectName = projectSlugFromPath(workspaceRoot);
300
327
  if (opts.dryRun) {
301
328
  log("\nInit dry run. No files will be written.\n");
302
329
  log(`Mode: project-local`);
@@ -319,12 +346,11 @@ export async function runProjectLocalInit(opts = {}) {
319
346
  ensureGovernanceFiles(phrenPath);
320
347
  repairPreexistingInstall(phrenPath);
321
348
  fs.mkdirSync(path.join(phrenPath, "global", "skills"), { recursive: true });
322
- fs.mkdirSync(path.join(phrenPath, ".runtime"), { recursive: true });
323
- fs.mkdirSync(path.join(phrenPath, ".sessions"), { recursive: true });
349
+ ensurePrivateDir(path.join(phrenPath, ".runtime"));
350
+ ensurePrivateDir(path.join(phrenPath, ".sessions"));
324
351
  if (!fs.existsSync(path.join(phrenPath, ".gitignore"))) {
325
352
  atomicWriteText(path.join(phrenPath, ".gitignore"), [
326
- ".runtime/",
327
- ".sessions/",
353
+ ...STORE_SECRET_GITIGNORE_LINES,
328
354
  "*.lock",
329
355
  "*.tmp-*",
330
356
  "",
@@ -0,0 +1,3 @@
1
+ export declare function runPreset(arg?: string, opts?: {
2
+ yes?: boolean;
3
+ }): Promise<void>;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * `phren preset [status|managed|assisted|manual]` — switch the management preset.
3
+ *
4
+ * Switching re-wires MCP/hooks for the new preset and, on a downgrade, tears down
5
+ * the phren-owned symlinks/wrappers/repo-mirrors the previous preset installed;
6
+ * on an upgrade it re-creates them. MCP registration stays on across all presets.
7
+ */
8
+ import { debugLog, findPhrenPath, readRootManifest } from "../shared.js";
9
+ import { errorMessage } from "../utils.js";
10
+ import { configureClaude } from "./config.js";
11
+ import { configureMcpTargets, configureHooksIfEnabled } from "./init-configure.js";
12
+ import { repairPreexistingInstall } from "./setup.js";
13
+ import { getMcpEnabledPreference, getHooksEnabledPreference, setHooksEnabledPreference, setManagementPresetPreference, } from "./preferences.js";
14
+ import { MANAGEMENT_PRESETS, getManagementPreset, parseManagementPreset, presetSummaryLines, resolveManagementCapabilities, } from "./management-preset.js";
15
+ import { removePhrenHomeSymlinks, removePhrenWrappers, sweepAgentSkillSymlinks, sweepProjectMirrors } from "./teardown.js";
16
+ import { printSelfWiringSnippet } from "./self-wiring.js";
17
+ import { DEFAULT_PHREN_PATH, log, confirmPrompt } from "./shared.js";
18
+ function printCapabilityTable(caps) {
19
+ const row = (label, on) => log(` ${on ? "on " : "off"} ${label}`);
20
+ row("MCP server registration", true);
21
+ row("Lifecycle hooks", caps.hooksDefault);
22
+ row("~/.claude/CLAUDE.md symlink", caps.linkGlobalClaudeMd);
23
+ row("~/.claude/skills symlinks", caps.installSkillLinks);
24
+ row("~/.local/bin wrappers", caps.installWrappers);
25
+ row("SessionStart self-heal", caps.selfHeal);
26
+ row("Repo mirroring", caps.repoMirroring);
27
+ row("Lifecycle automations (maintenance, auto-commit)", caps.lifecycleAutomations);
28
+ }
29
+ export async function runPreset(arg, opts = {}) {
30
+ const phrenPath = findPhrenPath() || process.env.PHREN_PATH || DEFAULT_PHREN_PATH;
31
+ const manifest = readRootManifest(phrenPath);
32
+ const normalized = arg?.trim().toLowerCase();
33
+ if (!normalized || normalized === "status") {
34
+ const current = getManagementPreset(phrenPath);
35
+ log(`Management preset: ${current} — ${presetSummaryLines(current)}`);
36
+ printCapabilityTable(resolveManagementCapabilities(phrenPath));
37
+ log(`Change: phren preset <${MANAGEMENT_PRESETS.join("|")}>`);
38
+ return;
39
+ }
40
+ const preset = parseManagementPreset(normalized);
41
+ if (!preset) {
42
+ throw new Error(`Invalid preset "${arg}". Use one of: ${MANAGEMENT_PRESETS.join(", ")}`);
43
+ }
44
+ if (manifest?.installMode === "project-local") {
45
+ throw new Error("preset switching is unsupported in project-local mode");
46
+ }
47
+ const previous = getManagementPreset(phrenPath);
48
+ const prevCaps = resolveManagementCapabilities(phrenPath);
49
+ if (preset === previous) {
50
+ log(`Already on the ${preset} preset.`);
51
+ printCapabilityTable(prevCaps);
52
+ return;
53
+ }
54
+ // Persist first so caps resolution (incl. the self-heal path) sees the new preset.
55
+ setManagementPresetPreference(phrenPath, preset);
56
+ const caps = resolveManagementCapabilities(phrenPath);
57
+ const teardownNeeded = (prevCaps.linkGlobalClaudeMd && !caps.linkGlobalClaudeMd) ||
58
+ (prevCaps.installSkillLinks && !caps.installSkillLinks) ||
59
+ (prevCaps.installWrappers && !caps.installWrappers) ||
60
+ (prevCaps.repoMirroring && !caps.repoMirroring);
61
+ if (teardownNeeded && !opts.yes) {
62
+ const ok = await confirmPrompt(`Switching ${previous} → ${preset} will remove phren-owned symlinks/wrappers from your machine and repos. Continue?`);
63
+ if (!ok) {
64
+ // Revert the preference — the user declined the teardown.
65
+ setManagementPresetPreference(phrenPath, previous);
66
+ log("Aborted. Preset unchanged.");
67
+ return;
68
+ }
69
+ }
70
+ log(`Switching management preset: ${previous} → ${preset}\n`);
71
+ // Hooks follow the preset default (manual disables them).
72
+ const mcpEnabled = getMcpEnabledPreference(phrenPath);
73
+ const hooksEnabled = caps.hooksDefault && (previous === "manual" ? true : getHooksEnabledPreference(phrenPath));
74
+ setHooksEnabledPreference(phrenPath, hooksEnabled);
75
+ try {
76
+ configureClaude(phrenPath, { mcpEnabled, hooksEnabled });
77
+ }
78
+ catch (err) {
79
+ debugLog(`preset: configureClaude failed: ${errorMessage(err)}`);
80
+ }
81
+ try {
82
+ configureMcpTargets(phrenPath, { mcpEnabled, hooksEnabled, caps }, "Updated");
83
+ }
84
+ catch (err) {
85
+ debugLog(`preset: configureMcpTargets failed: ${errorMessage(err)}`);
86
+ }
87
+ configureHooksIfEnabled(phrenPath, hooksEnabled, "Updated", caps);
88
+ // Teardown of artifacts the previous preset installed but the new one doesn't.
89
+ if (prevCaps.linkGlobalClaudeMd && !caps.linkGlobalClaudeMd)
90
+ removePhrenHomeSymlinks();
91
+ if (prevCaps.installSkillLinks && !caps.installSkillLinks)
92
+ sweepAgentSkillSymlinks(phrenPath);
93
+ if (prevCaps.installWrappers && !caps.installWrappers)
94
+ removePhrenWrappers();
95
+ if (prevCaps.repoMirroring && !caps.repoMirroring)
96
+ sweepProjectMirrors(phrenPath);
97
+ // Setup of artifacts the new preset adds but the previous one lacked.
98
+ const setupNeeded = (!prevCaps.linkGlobalClaudeMd && caps.linkGlobalClaudeMd) ||
99
+ (!prevCaps.installSkillLinks && caps.installSkillLinks) ||
100
+ (!prevCaps.repoMirroring && caps.repoMirroring);
101
+ if (setupNeeded) {
102
+ try {
103
+ repairPreexistingInstall(phrenPath, { caps, preset });
104
+ }
105
+ catch (err) {
106
+ debugLog(`preset: repair failed: ${errorMessage(err)}`);
107
+ }
108
+ try {
109
+ const { runLink } = await import("../link/link.js");
110
+ await runLink(phrenPath, {});
111
+ }
112
+ catch (err) {
113
+ debugLog(`preset: runLink failed: ${errorMessage(err)}`);
114
+ }
115
+ }
116
+ log(`\nManagement preset set to ${preset}.`);
117
+ printCapabilityTable(caps);
118
+ if (preset !== "managed") {
119
+ printSelfWiringSnippet(phrenPath, preset);
120
+ }
121
+ log(`\nRestart your agent to apply changes.`);
122
+ }
@@ -10,6 +10,7 @@ import { FINDINGS_FILENAME } from "../data/access.js";
10
10
  import { codexJsonCandidates, copilotMcpCandidates, cursorMcpCandidates, vscodeMcpCandidates, } from "../provider-adapters.js";
11
11
  import { removeMcpServerAtPath, removeTomlMcpServer, isPhrenCommand, patchJsonFile, } from "./config.js";
12
12
  import { DEFAULT_PHREN_PATH, log } from "./shared.js";
13
+ import { sweepProjectMirrors } from "./teardown.js";
13
14
  const PHREN_NPM_PACKAGE_NAME = "@phren/cli";
14
15
  function getNpmCommand() {
15
16
  return process.platform === "win32" ? "npm.cmd" : "npm";
@@ -448,6 +449,14 @@ export async function runUninstall(opts = {}) {
448
449
  catch (err) {
449
450
  debugLog(`uninstall: skill symlink sweep failed: ${errorMessage(err)}`);
450
451
  }
452
+ // Remove per-project repo mirror symlinks + phren-managed .git/info/exclude
453
+ // lines BEFORE deleting the store (this reads project config from the store).
454
+ try {
455
+ sweepProjectMirrors(phrenPath);
456
+ }
457
+ catch (err) {
458
+ debugLog(`uninstall: project mirror sweep failed: ${errorMessage(err)}`);
459
+ }
451
460
  }
452
461
  if (phrenPath && fs.existsSync(phrenPath)) {
453
462
  try {
@@ -1,4 +1,5 @@
1
1
  import type { ProjectOwnershipMode } from "../project-config.js";
2
+ import { type ManagementPreset } from "./management-preset.js";
2
3
  import type { ProactivityLevel } from "../proactivity.js";
3
4
  import { type InitProjectDomain, type InferredInitScaffold } from "./setup.js";
4
5
  import type { McpMode } from "./shared.js";
@@ -35,6 +36,7 @@ export interface WalkthroughResult {
35
36
  mcp: McpMode;
36
37
  hooks: McpMode;
37
38
  projectOwnershipDefault: ProjectOwnershipMode;
39
+ managementPreset: ManagementPreset;
38
40
  findingsProactivity: ProactivityLevel;
39
41
  taskProactivity: ProactivityLevel;
40
42
  lowConfidenceThreshold: number;
@@ -3,6 +3,7 @@
3
3
  * Prompts the user through storage, identity, MCP, hooks, and feature configuration.
4
4
  */
5
5
  import * as path from "path";
6
+ import { MANAGEMENT_PRESETS, presetSummaryLines } from "./management-preset.js";
6
7
  import { PROJECT_OWNERSHIP_MODES } from "../project-config.js";
7
8
  import { getMachineName } from "../machine-identity.js";
8
9
  import { expandHomePath, homePath } from "../shared.js";
@@ -149,6 +150,7 @@ export async function runWalkthrough(phrenPath, options) {
149
150
  mcp: "on",
150
151
  hooks: "on",
151
152
  projectOwnershipDefault: "phren-managed",
153
+ managementPreset: "managed",
152
154
  findingsProactivity: "high",
153
155
  taskProactivity: "high",
154
156
  lowConfidenceThreshold: 0.7,
@@ -217,6 +219,7 @@ export async function runWalkthrough(phrenPath, options) {
217
219
  mcp: "on",
218
220
  hooks: "on",
219
221
  projectOwnershipDefault: "phren-managed",
222
+ managementPreset: "managed",
220
223
  findingsProactivity: "high",
221
224
  taskProactivity: "high",
222
225
  lowConfidenceThreshold: 0.7,
@@ -275,17 +278,30 @@ export async function runWalkthrough(phrenPath, options) {
275
278
  else {
276
279
  log(`Domain: ${inferredDomain} (inferred from project content)`);
277
280
  }
281
+ printSection("Management Level");
282
+ log("How much of your machine should phren wire up?");
283
+ for (const p of MANAGEMENT_PRESETS)
284
+ log(` ${p}: ${presetSummaryLines(p)}`);
285
+ log(" Change later: phren preset <managed|assisted|manual>");
286
+ const managementPreset = await prompts.select("Management level", MANAGEMENT_PRESETS.map((p) => ({ value: p, name: p === "managed" ? "managed (recommended)" : p })), "managed");
278
287
  printSection("Project Ownership");
279
- log("Choose who owns repo-facing instruction files for projects you add.");
280
- log(" phren-managed: Phren may mirror CLAUDE.md / AGENTS.md into the repo");
281
- log(" detached: Phren keeps its own docs but does not write into the repo");
282
- log(" repo-managed: keep the repo's existing CLAUDE/AGENTS files as canonical");
283
- log(" Change later: phren config project-ownership <mode>");
284
- const projectOwnershipDefault = await prompts.select("Default project ownership", [
285
- { value: "detached", name: "detached (default)" },
286
- { value: "phren-managed", name: "phren-managed" },
287
- { value: "repo-managed", name: "repo-managed" },
288
- ], "detached");
288
+ let projectOwnershipDefault;
289
+ if (managementPreset !== "managed") {
290
+ projectOwnershipDefault = "detached";
291
+ log(`Using detached ownership — the ${managementPreset} preset never writes into your repos.`);
292
+ }
293
+ else {
294
+ log("Choose who owns repo-facing instruction files for projects you add.");
295
+ log(" phren-managed: Phren may mirror CLAUDE.md / AGENTS.md into the repo");
296
+ log(" detached: Phren keeps its own docs but does not write into the repo");
297
+ log(" repo-managed: keep the repo's existing CLAUDE/AGENTS files as canonical");
298
+ log(" Change later: phren config project-ownership <mode>");
299
+ projectOwnershipDefault = await prompts.select("Default project ownership", [
300
+ { value: "detached", name: "detached (default)" },
301
+ { value: "phren-managed", name: "phren-managed" },
302
+ { value: "repo-managed", name: "repo-managed" },
303
+ ], "detached");
304
+ }
289
305
  printSection("MCP");
290
306
  log("MCP mode registers phren as a tool server so your AI agent can call it");
291
307
  log("directly: search memory, manage tasks, save findings, etc.");
@@ -294,13 +310,21 @@ export async function runWalkthrough(phrenPath, options) {
294
310
  log(" Change later: phren mcp-mode on|off");
295
311
  const mcp = (await prompts.confirm("Enable MCP?", true)) ? "on" : "off";
296
312
  printSection("Hooks");
297
- log("Hooks run shell commands at session start, prompt submit, and session end.");
298
- log(" - SessionStart: git pull (keeps memory in sync across machines)");
299
- log(" - UserPromptSubmit: searches phren and injects relevant context");
300
- log(" - Stop: commits and pushes any new findings after each response");
301
- log(" What they touch: ~/.claude/settings.json (hooks section only)");
302
- log(" Change later: phren hooks-mode on|off");
303
- const hooks = (await prompts.confirm("Enable hooks?", true)) ? "on" : "off";
313
+ let hooks;
314
+ if (managementPreset === "manual") {
315
+ hooks = "off";
316
+ log("Skipped — the manual preset runs phren as an MCP server only (no hooks).");
317
+ log(" Enable later: phren preset assisted (or phren hooks-mode on)");
318
+ }
319
+ else {
320
+ log("Hooks run shell commands at session start, prompt submit, and session end.");
321
+ log(" - SessionStart: git pull (keeps memory in sync across machines)");
322
+ log(" - UserPromptSubmit: searches phren and injects relevant context");
323
+ log(" - Stop: commits and pushes any new findings after each response");
324
+ log(" What they touch: ~/.claude/settings.json (hooks section only)");
325
+ log(" Change later: phren hooks-mode on|off");
326
+ hooks = (await prompts.confirm("Enable hooks?", true)) ? "on" : "off";
327
+ }
304
328
  printSection("Semantic Search (Optional)");
305
329
  log("Phren can use a local embedding model for semantic (fuzzy) search via Ollama.");
306
330
  log(" Best fit: paraphrase-heavy or weak-lexical queries.");
@@ -511,6 +535,7 @@ export async function runWalkthrough(phrenPath, options) {
511
535
  mcp,
512
536
  hooks,
513
537
  projectOwnershipDefault,
538
+ managementPreset,
514
539
  findingsProactivity,
515
540
  taskProactivity,
516
541
  lowConfidenceThreshold,
@@ -10,11 +10,14 @@ export { ensureGovernanceFiles, repairPreexistingInstall, runPostInitVerify, get
10
10
  export { configureMcpTargets, warmSemanticSearch, runProjectLocalInit } from "./init-configure.js";
11
11
  export { runMcpMode } from "./init-mcp-mode.js";
12
12
  export { runHooksMode } from "./init-hooks-mode.js";
13
+ export { runPreset } from "./init-preset.js";
14
+ export { printSelfWiringSnippet } from "./self-wiring.js";
13
15
  export { runUninstall } from "./init-uninstall.js";
14
16
  import { type InitProjectDomain, type InferredInitScaffold } from "./setup.js";
15
17
  import { type McpMode } from "./shared.js";
16
18
  import { type ProjectOwnershipMode } from "../project-config.js";
17
19
  import { type ProactivityLevel } from "../proactivity.js";
20
+ import { type ManagementPreset } from "./management-preset.js";
18
21
  export { type McpMode, parseMcpMode } from "./shared.js";
19
22
  type StorageLocationChoice = "global" | "project" | "custom";
20
23
  type SkillsScope = "global" | "project";
@@ -32,6 +35,8 @@ export interface InitOptions {
32
35
  mcp?: McpMode;
33
36
  hooks?: McpMode;
34
37
  projectOwnershipDefault?: ProjectOwnershipMode;
38
+ /** Management preset controlling phren's machine footprint (managed | assisted | manual). */
39
+ managementPreset?: ManagementPreset;
35
40
  findingsProactivity?: ProactivityLevel;
36
41
  taskProactivity?: ProactivityLevel;
37
42
  lowConfidenceThreshold?: number;