@phren/cli 0.1.39 → 0.1.40

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.
@@ -8,6 +8,7 @@ import { fileURLToPath } from "url";
8
8
  import { debugLog, errorMessage, runtimeFile, isFeatureEnabled, } from "./hooks-context.js";
9
9
  import { qualityMarkers } from "../shared.js";
10
10
  import { spawnDetachedChild } from "../shared/process.js";
11
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
11
12
  import { logger } from "../logger.js";
12
13
  const SYNC_LOCK_STALE_MS = 10 * 60 * 1000; // 10 minutes
13
14
  const MAINTENANCE_LOCK_STALE_MS = 2 * 60 * 60 * 1000; // 2 hours
@@ -64,6 +65,9 @@ export function scheduleBackgroundSync(phrenPathLocal) {
64
65
  export function scheduleBackgroundMaintenance(phrenPathLocal, project) {
65
66
  if (!isFeatureEnabled("PHREN_FEATURE_DAILY_MAINTENANCE", true))
66
67
  return false;
68
+ // Lifecycle automations (daily maintenance) are off under the manual preset.
69
+ if (!resolveManagementCapabilities(phrenPathLocal).lifecycleAutomations)
70
+ return false;
67
71
  const markers = qualityMarkers(phrenPathLocal);
68
72
  if (fs.existsSync(markers.done))
69
73
  return false;
@@ -10,6 +10,7 @@ import { logger } from "../logger.js";
10
10
  import { runBestEffortGit, countUnsyncedCommits, recoverPushConflict, } from "./session-git.js";
11
11
  import { resolveSubprocessArgs, scheduleBackgroundSync, } from "./session-background.js";
12
12
  import { spawnDetachedChild } from "../shared/process.js";
13
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
13
14
  // ── Utility ─────────────────────────────────────────────────────────────────
14
15
  /** Read JSON from stdin if it's not a TTY. Returns null if stdin is a TTY or parsing fails. */
15
16
  function readStdinJson() {
@@ -225,6 +226,21 @@ export async function handleHookStop() {
225
226
  appendAuditLog(phrenPath, "hook_stop", "status=skipped-local");
226
227
  return;
227
228
  }
229
+ // Under the manual preset lifecycle automations are off: never auto commit or
230
+ // push the store, even if a stale Stop hook fires. Files on disk are the record.
231
+ if (!resolveManagementCapabilities(phrenPath).lifecycleAutomations) {
232
+ updateRuntimeHealth(phrenPath, {
233
+ lastStopAt: now,
234
+ lastAutoSave: { at: now, status: "saved-local", detail: "manual preset: auto-commit disabled" },
235
+ lastSync: {
236
+ lastPushAt: now,
237
+ lastPushStatus: "saved-local",
238
+ lastPushDetail: "manual preset does not auto-commit or push",
239
+ },
240
+ });
241
+ appendAuditLog(phrenPath, "hook_stop", "status=skipped-manual-preset");
242
+ return;
243
+ }
228
244
  const gitRepo = ensureLocalGitRepo(phrenPath);
229
245
  if (!gitRepo.ok) {
230
246
  finalizeTaskSession({
@@ -14,4 +14,6 @@ export declare function runStatusCommand(_args: string[]): Promise<number>;
14
14
  export declare function runVerifyCommand(_args: string[]): Promise<number>;
15
15
  export declare function runMcpModeCommand(args: string[]): Promise<number>;
16
16
  export declare function runHooksModeCommand(args: string[]): Promise<number>;
17
+ export declare function runPresetCommand(args: string[]): Promise<number>;
18
+ export declare function runSnippetCommand(_args: string[]): Promise<number>;
17
19
  export declare function runLinkRemovedNotice(_args: string[]): Promise<number>;
@@ -79,6 +79,7 @@ export async function runAddCommand(args) {
79
79
  }
80
80
  export async function runInitCommand(args) {
81
81
  const { parseMcpMode, runInit } = await import("./init/init.js");
82
+ const { parseManagementPreset, MANAGEMENT_PRESETS } = await import("./init/management-preset.js");
82
83
  const machineIdx = args.indexOf("--machine");
83
84
  const profileIdx = args.indexOf("--profile");
84
85
  const mcpIdx = args.indexOf("--mcp");
@@ -118,6 +119,18 @@ export async function runInitCommand(args) {
118
119
  console.error(`Invalid --task-proactivity value "${taskArg}". Use one of: high, medium, low.`);
119
120
  return 1;
120
121
  }
122
+ const presetArg = getOptionValue(args, "--preset") ?? getOptionValue(args, "--management");
123
+ const managementPreset = parseManagementPreset(presetArg);
124
+ if (presetArg && !managementPreset) {
125
+ console.error(`Invalid --preset value "${presetArg}". Use one of: ${MANAGEMENT_PRESETS.join(", ")}`);
126
+ return 1;
127
+ }
128
+ const hooksMode = parseMcpMode(getOptionValue(args, "--hooks") ?? "");
129
+ const hooksArg = getOptionValue(args, "--hooks");
130
+ if (hooksArg && !hooksMode) {
131
+ console.error(`Invalid --hooks value "${hooksArg}". Use "on" or "off".`);
132
+ return 1;
133
+ }
121
134
  const cloneUrl = getOptionValue(args, "--clone-url");
122
135
  try {
123
136
  await runInit({
@@ -125,7 +138,9 @@ export async function runInitCommand(args) {
125
138
  machine: machineIdx !== -1 ? args[machineIdx + 1] : undefined,
126
139
  profile: profileIdx !== -1 ? args[profileIdx + 1] : undefined,
127
140
  mcp: mcpMode,
141
+ hooks: hooksMode,
128
142
  projectOwnershipDefault: ownershipMode,
143
+ managementPreset,
129
144
  taskMode,
130
145
  findingsProactivity,
131
146
  taskProactivity,
@@ -198,6 +213,31 @@ export async function runHooksModeCommand(args) {
198
213
  return 1;
199
214
  }
200
215
  }
216
+ export async function runPresetCommand(args) {
217
+ const { runPreset } = await import("./init/init.js");
218
+ const positional = args.filter((a) => !a.startsWith("-"));
219
+ const yes = args.includes("--yes") || args.includes("-y");
220
+ try {
221
+ await runPreset(positional[0], { yes });
222
+ return 0;
223
+ }
224
+ catch (err) {
225
+ console.error(errorMessage(err));
226
+ return 1;
227
+ }
228
+ }
229
+ export async function runSnippetCommand(_args) {
230
+ const { printSelfWiringSnippet } = await import("./init/init.js");
231
+ const phrenPath = findPhrenPath() || defaultPhrenPath();
232
+ try {
233
+ printSelfWiringSnippet(phrenPath);
234
+ return 0;
235
+ }
236
+ catch (err) {
237
+ console.error(errorMessage(err));
238
+ return 1;
239
+ }
240
+ }
201
241
  export async function runLinkRemovedNotice(_args) {
202
242
  console.error("`phren link` has been removed. Use `phren init` instead.");
203
243
  return 1;
@@ -117,7 +117,7 @@ export const REGISTRY = [
117
117
  {
118
118
  name: "init",
119
119
  topic: "setup",
120
- usage: "phren init [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]",
120
+ usage: "phren init [--preset managed|assisted|manual] [--mode shared|project-local] [--machine <n>] [--profile <n>] [--dry-run] [-y]",
121
121
  cheatUsage: "phren init",
122
122
  summary: "Set up phren",
123
123
  featured: true,
@@ -456,6 +456,20 @@ export const REGISTRY = [
456
456
  summary: "Toggle hook execution",
457
457
  run: native("runHooksModeCommand"),
458
458
  },
459
+ {
460
+ name: "preset",
461
+ topic: "setup",
462
+ usage: "phren preset [status|managed|assisted|manual] [-y]",
463
+ summary: "Set the management preset (how much phren wires up)",
464
+ run: native("runPresetCommand"),
465
+ },
466
+ {
467
+ name: "snippet",
468
+ topic: "setup",
469
+ usage: "phren snippet",
470
+ summary: "Print the self-wiring snippet for assisted/manual presets",
471
+ run: native("runSnippetCommand"),
472
+ },
459
473
  {
460
474
  name: "verify",
461
475
  topic: "setup",
package/dist/hooks.d.ts CHANGED
@@ -115,5 +115,11 @@ export declare function runPrePromptHooks(phrenPath: string, stdinJson: string,
115
115
  export interface HookConfigOptions {
116
116
  tools?: Set<string>;
117
117
  allTools?: boolean;
118
+ /**
119
+ * Whether to install ~/.local/bin session wrappers. Defaults to the current
120
+ * management preset's `installWrappers` capability. Assisted/manual presets
121
+ * skip wrappers (hooks fall back to node/npx invocation).
122
+ */
123
+ installWrappers?: boolean;
118
124
  }
119
125
  export declare function configureAllHooks(phrenPath: string, options?: HookConfigOptions): string[];
package/dist/hooks.js CHANGED
@@ -11,6 +11,7 @@ import { hookConfigPath } from "./provider-adapters.js";
11
11
  import { PACKAGE_SPEC } from "./package-metadata.js";
12
12
  import { logger } from "./logger.js";
13
13
  import { withFileLock } from "./shared/governance.js";
14
+ import { resolveManagementCapabilities } from "./init/management-preset.js";
14
15
  export function commandExists(cmd) {
15
16
  try {
16
17
  const whichCmd = process.platform === "win32" ? "where.exe" : "which";
@@ -898,6 +899,8 @@ export function configureAllHooks(phrenPath, options = {}) {
898
899
  : options.allTools
899
900
  ? new Set(["copilot", "cursor", "codex"])
900
901
  : detectInstalledTools();
902
+ const installWrappers = options.installWrappers
903
+ ?? resolveManagementCapabilities(phrenPath).installWrappers;
901
904
  const lifecycle = buildLifecycleCommands(phrenPath);
902
905
  // ── GitHub Copilot CLI (user-level: ~/.github/hooks/phren.json) ──────────
903
906
  if (detected.has("copilot")) {
@@ -927,7 +930,7 @@ export function configureAllHooks(phrenPath, options = {}) {
927
930
  catch (err) {
928
931
  console.warn(`configureAllHooks: copilot hook config failed: ${errorMessage(err)}`);
929
932
  }
930
- if (isToolHookEnabled(phrenPath, "copilot"))
933
+ if (installWrappers && isToolHookEnabled(phrenPath, "copilot"))
931
934
  installSessionWrapper("copilot", phrenPath);
932
935
  }
933
936
  // ── Cursor (user-level: ~/.cursor/hooks.json) ────────────────────────────
@@ -959,7 +962,7 @@ export function configureAllHooks(phrenPath, options = {}) {
959
962
  catch (err) {
960
963
  console.warn(`configureAllHooks: cursor hook config failed: ${errorMessage(err)}`);
961
964
  }
962
- if (isToolHookEnabled(phrenPath, "cursor"))
965
+ if (installWrappers && isToolHookEnabled(phrenPath, "cursor"))
963
966
  installSessionWrapper("cursor", phrenPath);
964
967
  }
965
968
  // ── Codex (codex.json in phren path) ─────────────────────────────────────
@@ -990,7 +993,7 @@ export function configureAllHooks(phrenPath, options = {}) {
990
993
  catch (err) {
991
994
  console.warn(`configureAllHooks: codex hook config failed: ${errorMessage(err)}`);
992
995
  }
993
- if (isToolHookEnabled(phrenPath, "codex"))
996
+ if (installWrappers && isToolHookEnabled(phrenPath, "codex"))
994
997
  installSessionWrapper("codex", phrenPath);
995
998
  }
996
999
  return configured;
@@ -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>;
@@ -15,23 +15,29 @@ import { VERSION } from "./shared.js";
15
15
  import { writeInstallPreferences, writeGovernanceInstallPreferences, } from "./preferences.js";
16
16
  import { repairPreexistingInstall, ensureGovernanceFiles, ensureGitignoreEntry, upsertProjectEnvVar, detectProjectDir, bootstrapFromExisting, runPostInitVerify, } from "./setup.js";
17
17
  import { log } from "./shared.js";
18
+ import { resolveManagementCapabilities, getManagementPreset } from "./management-preset.js";
18
19
  /**
19
20
  * Configure MCP for all detected AI coding tools (Claude, VS Code, Cursor, Copilot, Codex).
20
21
  * @param verb - label used in log messages, e.g. "Updated" or "Configured"
21
22
  */
22
23
  export function configureMcpTargets(phrenPath, opts, verb = "Configured") {
24
+ const caps = opts.caps ?? resolveManagementCapabilities(phrenPath);
23
25
  // Install the stable ~/.local/bin/phren wrapper BEFORE writing any hook
24
26
  // commands. buildLifecycleCommands prefers that wrapper (it carries an npx
25
27
  // fallback, so it survives nvm switches and npx cache clears); if it doesn't
26
28
  // yet exist, hook commands fall through to the ephemeral npx-cache entry path
27
29
  // and break the next time npx prunes its cache. configureHooksIfEnabled runs
28
30
  // 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)}`);
31
+ // "CLI wrapper" line — this early install is intentionally silent. Presets
32
+ // that opt out of wrappers (assisted/manual) skip it; hooks then use the
33
+ // node/npx invocation form.
34
+ if (caps.installWrappers) {
35
+ try {
36
+ installPhrenCliWrapper(phrenPath);
37
+ }
38
+ catch (err) {
39
+ debugLog(`configureMcpTargets: early wrapper install failed: ${errorMessage(err)}`);
40
+ }
35
41
  }
36
42
  let claudeStatus = "no_settings";
37
43
  try {
@@ -90,10 +96,11 @@ export function configureMcpTargets(phrenPath, opts, verb = "Configured") {
90
96
  * Configure hooks if enabled, or log a disabled message.
91
97
  * @param verb - label used in log messages, e.g. "Updated" or "Configured"
92
98
  */
93
- export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb) {
99
+ export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb, caps) {
100
+ const resolvedCaps = caps ?? resolveManagementCapabilities(phrenPath);
94
101
  if (hooksEnabled) {
95
102
  try {
96
- const hooked = configureAllHooks(phrenPath, { allTools: true });
103
+ const hooked = configureAllHooks(phrenPath, { allTools: true, installWrappers: resolvedCaps.installWrappers });
97
104
  if (hooked.length)
98
105
  log(` ${verb} hooks: ${hooked.join(", ")}`);
99
106
  }
@@ -104,6 +111,12 @@ export function configureHooksIfEnabled(phrenPath, hooksEnabled, verb) {
104
111
  else {
105
112
  log(` Hooks are disabled by preference (run: phren hooks-mode on)`);
106
113
  }
114
+ // Presets that opt out of wrappers (assisted/manual) leave the user's PATH and
115
+ // ~/.local/bin untouched; hooks fall back to the node/npx invocation form.
116
+ if (!resolvedCaps.installWrappers) {
117
+ log(` CLI wrapper: skipped (${getManagementPreset(phrenPath)} preset) — use 'npx @phren/cli <command>' or a global install`);
118
+ return;
119
+ }
107
120
  // Install phren CLI wrapper at ~/.local/bin/phren so the bare command works
108
121
  const wrapperInstalled = installPhrenCliWrapper(phrenPath);
109
122
  if (wrapperInstalled) {
@@ -158,13 +171,26 @@ export function applyOnboardingPreferences(phrenPath, opts) {
158
171
  updateWorkflowPolicy(phrenPath, workflowPatch);
159
172
  }
160
173
  }
161
- export function writeWalkthroughEnvDefaults(phrenPath, opts) {
174
+ export function writeWalkthroughEnvDefaults(phrenPath, opts, presetContext) {
162
175
  const envFile = path.join(phrenPath, ".env");
163
176
  let envContent = fs.existsSync(envFile) ? fs.readFileSync(envFile, "utf8") : "# phren feature flags — generated by init\n";
164
177
  const envFlags = [];
178
+ const manualPreset = presetContext?.preset === "manual";
179
+ const presetExplicit = presetContext?.explicit === true;
165
180
  const autoCaptureChoice = opts._walkthroughAutoCapture;
166
181
  const hasAutoCaptureFlag = /^\s*PHREN_FEATURE_AUTO_CAPTURE=.*$/m.test(envContent);
167
- if (typeof autoCaptureChoice === "boolean") {
182
+ if (manualPreset) {
183
+ // Manual preset turns off the prompt-time/background automations. Force the
184
+ // flags to 0 only when the preset was explicitly chosen this run; on a plain
185
+ // re-init we respect any lines the user already set.
186
+ for (const key of ["PHREN_FEATURE_AUTO_CAPTURE", "PHREN_FEATURE_AUTO_EXTRACT", "PHREN_FEATURE_DAILY_MAINTENANCE"]) {
187
+ const present = new RegExp(`^\\s*${key}=.*$`, "m").test(envContent);
188
+ if (presetExplicit || !present) {
189
+ envFlags.push({ flag: `${key}=0`, label: `${key.replace("PHREN_FEATURE_", "").toLowerCase().replace(/_/g, " ")} disabled (manual preset)` });
190
+ }
191
+ }
192
+ }
193
+ else if (typeof autoCaptureChoice === "boolean") {
168
194
  envFlags.push({
169
195
  flag: `PHREN_FEATURE_AUTO_CAPTURE=${autoCaptureChoice ? "1" : "0"}`,
170
196
  label: `Auto-capture ${autoCaptureChoice ? "enabled" : "disabled"}`,
@@ -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;