@phren/cli 0.1.22 → 0.1.23

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.
@@ -394,22 +394,29 @@ export async function runTopLevelCommand(argv, opts = {}) {
394
394
  return finish(1);
395
395
  }
396
396
  const cloneUrl = getOptionValue(initArgs, "--clone-url");
397
- await runInit({
398
- mode: modeArg,
399
- machine: machineIdx !== -1 ? initArgs[machineIdx + 1] : undefined,
400
- profile: profileIdx !== -1 ? initArgs[profileIdx + 1] : undefined,
401
- mcp: mcpMode,
402
- projectOwnershipDefault: ownershipMode,
403
- taskMode,
404
- findingsProactivity,
405
- taskProactivity,
406
- template: templateIdx !== -1 ? initArgs[templateIdx + 1] : undefined,
407
- applyStarterUpdate: initArgs.includes("--apply-starter-update"),
408
- dryRun: initArgs.includes("--dry-run"),
409
- yes: initArgs.includes("--yes") || initArgs.includes("-y"),
410
- express: initArgs.includes("--express"),
411
- _walkthroughCloneUrl: cloneUrl,
412
- });
397
+ try {
398
+ await runInit({
399
+ mode: modeArg,
400
+ machine: machineIdx !== -1 ? initArgs[machineIdx + 1] : undefined,
401
+ profile: profileIdx !== -1 ? initArgs[profileIdx + 1] : undefined,
402
+ mcp: mcpMode,
403
+ projectOwnershipDefault: ownershipMode,
404
+ taskMode,
405
+ findingsProactivity,
406
+ taskProactivity,
407
+ template: templateIdx !== -1 ? initArgs[templateIdx + 1] : undefined,
408
+ applyStarterUpdate: initArgs.includes("--apply-starter-update"),
409
+ dryRun: initArgs.includes("--dry-run"),
410
+ yes: initArgs.includes("--yes") || initArgs.includes("-y"),
411
+ express: initArgs.includes("--express"),
412
+ force: initArgs.includes("--force"),
413
+ _walkthroughCloneUrl: cloneUrl,
414
+ });
415
+ }
416
+ catch (err) {
417
+ console.error(errorMessage(err));
418
+ return finish(1);
419
+ }
413
420
  return finish();
414
421
  }
415
422
  if (argvCommand === "uninstall") {
@@ -0,0 +1,6 @@
1
+ export interface WiringConflict {
2
+ location: string;
3
+ existingPath: string;
4
+ }
5
+ export declare function findConflictingGlobalWiring(newPhrenPath: string): WiringConflict[];
6
+ export declare function assertNoGlobalWiringConflict(newPhrenPath: string, force: boolean): void;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Guards against `phren init` silently repointing the user's global wiring
3
+ * (CLI wrapper at ~/.local/bin/phren and Claude settings.json hooks/MCP) at a
4
+ * different phren root than the one currently in use.
5
+ *
6
+ * Why: `phren init` is also exercised by tests/smoke scripts that invoke it
7
+ * with `PHREN_PATH=/tmp/...`. Without an isolated $HOME the install logic
8
+ * cheerfully rewrites the user's real wrapper and Claude hooks to point at
9
+ * the throwaway path, which then disappears with `rm -rf /tmp/foo`. The next
10
+ * Claude session boots with a SessionStart hook that throws
11
+ * `NOT_FOUND: phren root not found. Run 'phren init'.`
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.
18
+ */
19
+ import * as fs from "fs";
20
+ import * as path from "path";
21
+ import { homePath, isRecord } from "../shared.js";
22
+ import { hookConfigPath } from "../provider-adapters.js";
23
+ const WRAPPER_POSIX_RE = /PHREN_PATH="\$\{PHREN_PATH:-([^}]+)\}"/;
24
+ const WRAPPER_WIN_RE = /set "PHREN_PATH=([^"]+)"/;
25
+ const HOOK_PHREN_PATH_RE = /PHREN_PATH=(?:'([^']+)'|"([^"]+)"|(\S+))/;
26
+ function samePath(a, b) {
27
+ return path.resolve(a) === path.resolve(b);
28
+ }
29
+ /**
30
+ * A path counts as a "valid phren root" only if it currently looks like one
31
+ * — root manifest, machines.yaml, or the global skills tree. We deliberately
32
+ * tolerate partial roots so a clean `phren init` repair still works.
33
+ */
34
+ function looksLikePhrenRoot(candidate) {
35
+ if (!fs.existsSync(candidate))
36
+ return false;
37
+ if (fs.existsSync(path.join(candidate, "phren.root.yaml")))
38
+ return true;
39
+ if (fs.existsSync(path.join(candidate, "machines.yaml")))
40
+ return true;
41
+ if (fs.existsSync(path.join(candidate, "global")))
42
+ return true;
43
+ return false;
44
+ }
45
+ function readWrapperPath() {
46
+ const wrapperName = process.platform === "win32" ? "phren.cmd" : "phren";
47
+ const wrapperFile = path.join(homePath(".local", "bin"), wrapperName);
48
+ if (!fs.existsSync(wrapperFile))
49
+ return null;
50
+ let content;
51
+ try {
52
+ content = fs.readFileSync(wrapperFile, "utf8");
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ if (!content.includes("PHREN_CLI_WRAPPER"))
58
+ return null;
59
+ const re = process.platform === "win32" ? WRAPPER_WIN_RE : WRAPPER_POSIX_RE;
60
+ const m = content.match(re);
61
+ return m?.[1] ?? null;
62
+ }
63
+ function extractHookPhrenPath(command) {
64
+ const m = command.match(HOOK_PHREN_PATH_RE);
65
+ if (!m)
66
+ return null;
67
+ return m[1] ?? m[2] ?? m[3] ?? null;
68
+ }
69
+ function readClaudeSettings() {
70
+ const settingsPath = hookConfigPath("claude");
71
+ if (!fs.existsSync(settingsPath))
72
+ return null;
73
+ try {
74
+ return JSON.parse(fs.readFileSync(settingsPath, "utf8"));
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ export function findConflictingGlobalWiring(newPhrenPath) {
81
+ const conflicts = [];
82
+ const seen = new Set();
83
+ const record = (location, existingPath) => {
84
+ if (samePath(existingPath, newPhrenPath))
85
+ return;
86
+ if (!looksLikePhrenRoot(existingPath))
87
+ return;
88
+ const key = `${location}:${path.resolve(existingPath)}`;
89
+ if (seen.has(key))
90
+ return;
91
+ seen.add(key);
92
+ conflicts.push({ location, existingPath });
93
+ };
94
+ const wrapperPath = readWrapperPath();
95
+ if (wrapperPath) {
96
+ record(`~/.local/bin/${process.platform === "win32" ? "phren.cmd" : "phren"} wrapper`, wrapperPath);
97
+ }
98
+ const settings = readClaudeSettings();
99
+ if (isRecord(settings)) {
100
+ const mcpServers = settings.mcpServers;
101
+ if (isRecord(mcpServers)) {
102
+ const phrenServer = mcpServers.phren;
103
+ if (isRecord(phrenServer) && Array.isArray(phrenServer.args) && phrenServer.args.length > 0) {
104
+ const last = phrenServer.args[phrenServer.args.length - 1];
105
+ if (typeof last === "string") {
106
+ record("~/.claude/settings.json mcpServers.phren", last);
107
+ }
108
+ }
109
+ }
110
+ const hooks = settings.hooks;
111
+ if (isRecord(hooks)) {
112
+ for (const eventName of ["UserPromptSubmit", "Stop", "SessionStart", "PostToolUse"]) {
113
+ const eventHooks = hooks[eventName];
114
+ if (!Array.isArray(eventHooks))
115
+ continue;
116
+ for (const entry of eventHooks) {
117
+ if (!isRecord(entry))
118
+ continue;
119
+ const inner = entry.hooks;
120
+ if (!Array.isArray(inner))
121
+ continue;
122
+ for (const h of inner) {
123
+ if (!isRecord(h))
124
+ continue;
125
+ const command = typeof h.command === "string" ? h.command : "";
126
+ if (!command)
127
+ continue;
128
+ const extracted = extractHookPhrenPath(command);
129
+ if (extracted) {
130
+ record(`~/.claude/settings.json hooks.${eventName}`, extracted);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+ return conflicts;
138
+ }
139
+ export function assertNoGlobalWiringConflict(newPhrenPath, force) {
140
+ if (force)
141
+ return;
142
+ const conflicts = findConflictingGlobalWiring(newPhrenPath);
143
+ if (conflicts.length === 0)
144
+ return;
145
+ const lines = [
146
+ `phren init: refusing to repoint global wiring at ${newPhrenPath}.`,
147
+ "",
148
+ "Existing files reference a different phren root that still looks valid:",
149
+ ];
150
+ for (const c of conflicts) {
151
+ lines.push(` - ${c.location} → ${c.existingPath}`);
152
+ }
153
+ lines.push("");
154
+ lines.push("If you intend to switch the global wiring to the new path, re-run with --force.");
155
+ lines.push("If you're running a smoke test, set HOME (and XDG_*) to a sandbox before invoking init.");
156
+ throw new Error(lines.join("\n"));
157
+ }
@@ -44,6 +44,14 @@ export interface InitOptions {
44
44
  yes?: boolean;
45
45
  /** Skip walkthrough entirely with recommended defaults (express mode) */
46
46
  express?: boolean;
47
+ /**
48
+ * Allow init to repoint global wiring (~/.local/bin/phren wrapper and
49
+ * Claude settings.json hooks/mcpServers.phren) at a different phren root
50
+ * than the one currently in use. Without this, init refuses when an
51
+ * existing global file references a different valid phren root — protects
52
+ * against tests/smoke runs that forget to sandbox $HOME.
53
+ */
54
+ force?: boolean;
47
55
  template?: "python-project" | "monorepo" | "library" | "frontend" | string;
48
56
  /** Set by walkthrough to pass project name to init logic */
49
57
  _walkthroughProject?: string;
package/dist/init/init.js CHANGED
@@ -23,6 +23,7 @@ export { runUninstall } from "./init-uninstall.js";
23
23
  // Internal imports from extracted modules (used by runInit)
24
24
  import { configureMcpTargets, configureHooksIfEnabled, applyOnboardingPreferences, writeWalkthroughEnvDefaults, collectRepairedAssetLabels, applyProjectStorageBindings, warmSemanticSearch, runProjectLocalInit, } from "./init-configure.js";
25
25
  import { runWalkthrough, createWalkthroughPrompts, createWalkthroughStyle } from "./init-walkthrough.js";
26
+ import { assertNoGlobalWiringConflict } from "./guard-globals.js";
26
27
  import { getMcpEnabledPreference, getHooksEnabledPreference, writeInstallPreferences, readInstallPreferences, } from "./preferences.js";
27
28
  import { ensureGovernanceFiles, repairPreexistingInstall, runPostInitVerify, applyStarterTemplateUpdates, listTemplates, applyTemplate, ensureProjectScaffold, ensureLocalGitRepo, bootstrapFromExisting, updateMachinesYaml, detectProjectDir, isProjectTracked, } from "./setup.js";
28
29
  import { DEFAULT_PHREN_PATH, STARTER_DIR, VERSION, log } from "./shared.js";
@@ -101,6 +102,9 @@ export async function runInit(opts = {}) {
101
102
  }
102
103
  let phrenPath = resolveInitPhrenPath(opts);
103
104
  const dryRun = Boolean(opts.dryRun);
105
+ if (!dryRun) {
106
+ assertNoGlobalWiringConflict(phrenPath, Boolean(opts.force));
107
+ }
104
108
  // Migrate the legacy hidden store directory into ~/.phren when upgrading
105
109
  // from the previous product name. Only runs when the resolved phrenPath
106
110
  // doesn't exist yet but the legacy directory does.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.1.22",
3
+ "version": "0.1.23",
4
4
  "description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {