@phren/cli 0.1.21 → 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.
@@ -22,6 +22,21 @@ export declare function runBestEffortGit(args: string[], cwd: string): Promise<{
22
22
  output?: string;
23
23
  error?: string;
24
24
  }>;
25
+ /**
26
+ * Files phren is allowed to auto-stage in a team store. Anything not in this
27
+ * list (notably `.runtime/`, secrets, build output) is skipped on session-stop
28
+ * and `push_changes`.
29
+ */
30
+ export declare const TEAM_STORE_PATHSPECS: readonly ["*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**", ".phren-team.yaml"];
31
+ /**
32
+ * Stage each team pathspec individually so a single no-match (e.g. a store
33
+ * with no `truths.md` anywhere) doesn't abort the entire `git add` and strand
34
+ * every other change. Errors are swallowed by `runBestEffortGit` already.
35
+ *
36
+ * Returns the number of pathspecs that staged successfully — useful for
37
+ * telemetry, not gating.
38
+ */
39
+ export declare function addTeamPathspecs(cwd: string): Promise<number>;
25
40
  export declare function countUnsyncedCommits(cwd: string): Promise<number>;
26
41
  export declare function isMergeableMarkdown(relPath: string): boolean;
27
42
  export declare function snapshotLocalMergeableFiles(cwd: string): Promise<Map<string, string>>;
@@ -121,6 +121,43 @@ export async function runBestEffortGit(args, cwd) {
121
121
  }
122
122
  return { ok: false, error: "git command failed" };
123
123
  }
124
+ /**
125
+ * Files phren is allowed to auto-stage in a team store. Anything not in this
126
+ * list (notably `.runtime/`, secrets, build output) is skipped on session-stop
127
+ * and `push_changes`.
128
+ */
129
+ export const TEAM_STORE_PATHSPECS = [
130
+ "*/journal/*",
131
+ "*/tasks.md",
132
+ "*/truths.md",
133
+ "*/FINDINGS.md",
134
+ "*/FINDINGS.md.bak",
135
+ "*/summary.md",
136
+ "*/review.md",
137
+ "*/CLAUDE.md",
138
+ "*/topic-config.json",
139
+ "*/phren.project.yaml",
140
+ "*/reference/**",
141
+ "*/skills/**",
142
+ ".phren-team.yaml",
143
+ ];
144
+ /**
145
+ * Stage each team pathspec individually so a single no-match (e.g. a store
146
+ * with no `truths.md` anywhere) doesn't abort the entire `git add` and strand
147
+ * every other change. Errors are swallowed by `runBestEffortGit` already.
148
+ *
149
+ * Returns the number of pathspecs that staged successfully — useful for
150
+ * telemetry, not gating.
151
+ */
152
+ export async function addTeamPathspecs(cwd) {
153
+ let staged = 0;
154
+ for (const spec of TEAM_STORE_PATHSPECS) {
155
+ const result = await runBestEffortGit(["add", "--sparse", "--", spec], cwd);
156
+ if (result.ok)
157
+ staged++;
158
+ }
159
+ return staged;
160
+ }
124
161
  export async function countUnsyncedCommits(cwd) {
125
162
  const upstream = await runBestEffortGit(["rev-parse", "--abbrev-ref", "@{upstream}"], cwd);
126
163
  if (!upstream.ok || !upstream.output) {
@@ -7,7 +7,7 @@ import * as fs from "fs";
7
7
  import * as path from "path";
8
8
  import * as os from "os";
9
9
  import { spawnDetachedChild } from "./shared/process.js";
10
- import { resolveSubprocessArgs as _resolveSubprocessArgs, runBestEffortGit, countUnsyncedCommits, recoverPushConflict, } from "./cli-hooks-git.js";
10
+ import { resolveSubprocessArgs as _resolveSubprocessArgs, runBestEffortGit, countUnsyncedCommits, recoverPushConflict, addTeamPathspecs, } from "./cli-hooks-git.js";
11
11
  import { logger } from "./logger.js";
12
12
  const SYNC_LOCK_STALE_MS = 10 * 60 * 1000; // 10 minutes
13
13
  /** Read JSON from stdin if it's not a TTY. Returns null if stdin is a TTY or parsing fails. */
@@ -485,8 +485,9 @@ export async function handleHookStop() {
485
485
  try {
486
486
  const storeStatus = await runBestEffortGit(["status", "--porcelain"], store.path);
487
487
  if (storeStatus.ok && storeStatus.output) {
488
- // Only stage journal/, tasks.md, truths.md, FINDINGS.md, summary.md — NOT .runtime/
489
- await runBestEffortGit(["add", "--sparse", "--", "*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**", ".phren-team.yaml"], store.path);
488
+ // Stage each team-safe pathspec individually — a single no-match
489
+ // (e.g. no */truths.md in this store) used to abort the whole add.
490
+ await addTeamPathspecs(store.path);
490
491
  const actor = process.env.PHREN_ACTOR || process.env.USER || "unknown";
491
492
  const teamCommit = await runBestEffortGit(["commit", "-m", `phren: ${actor} team sync`], store.path);
492
493
  if (teamCommit.ok) {
@@ -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.
@@ -16,6 +16,7 @@ import { appendChildFinding, editFinding as editFindingCore, readFindings, FINDI
16
16
  import { getActiveTaskForSession } from "../task/lifecycle.js";
17
17
  import { isInactiveFindingLine, supersedeFinding, retractFinding as retractFindingLifecycle, resolveFindingContradiction, } from "../finding/lifecycle.js";
18
18
  import { permissionDeniedError } from "../governance/rbac.js";
19
+ import { TEAM_STORE_PATHSPECS } from "../cli-hooks-git.js";
19
20
  const JACCARD_MAYBE_LOW = 0.25;
20
21
  const JACCARD_MAYBE_HIGH = 0.40; // above this isDuplicateFinding already catches it
21
22
  function findJaccardCandidates(phrenPath, project, finding) {
@@ -569,8 +570,14 @@ async function handlePushChanges(ctx, { message }) {
569
570
  teamResults.push({ store: store.name, pushed: false });
570
571
  continue;
571
572
  }
572
- // Only stage team-safe files: journal/, tasks.md, truths.md, FINDINGS.md, summary.md
573
- runStoreGit(["add", "--sparse", "--", "*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**"]);
573
+ // Stage each team-safe pathspec individually — a single no-match
574
+ // (e.g. no */truths.md in this store) used to abort the whole add.
575
+ for (const spec of TEAM_STORE_PATHSPECS) {
576
+ try {
577
+ runStoreGit(["add", "--sparse", "--", spec]);
578
+ }
579
+ catch { /* best-effort */ }
580
+ }
574
581
  const actor = process.env.PHREN_ACTOR || process.env.USER || "unknown";
575
582
  runStoreGit(["commit", "-m", `phren: ${actor} team sync`]);
576
583
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.1.21",
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": {