@phren/cli 0.2.16 → 0.3.1

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 (102) hide show
  1. package/dist/bridge/agent-hooks.d.ts +17 -6
  2. package/dist/bridge/agent-hooks.js +59 -24
  3. package/dist/bridge/claude-question-dialog.d.ts +65 -0
  4. package/dist/bridge/claude-question-dialog.js +210 -0
  5. package/dist/bridge/code-note.d.ts +2 -1
  6. package/dist/bridge/code-note.js +13 -4
  7. package/dist/bridge/code-routes.d.ts +32 -14
  8. package/dist/bridge/code-routes.js +131 -8
  9. package/dist/bridge/command.js +92 -2
  10. package/dist/bridge/computers.d.ts +5 -0
  11. package/dist/bridge/computers.js +10 -4
  12. package/dist/bridge/conductor-group.d.ts +23 -0
  13. package/dist/bridge/conductor-group.js +25 -0
  14. package/dist/bridge/dispatch-returns.d.ts +2 -0
  15. package/dist/bridge/dispatch-returns.js +12 -8
  16. package/dist/bridge/dispatch.d.ts +4 -1
  17. package/dist/bridge/dispatch.js +30 -5
  18. package/dist/bridge/hand-off.js +5 -1
  19. package/dist/bridge/herdr.d.ts +7 -0
  20. package/dist/bridge/herdr.js +53 -2
  21. package/dist/bridge/install.d.ts +0 -4
  22. package/dist/bridge/install.js +3 -3
  23. package/dist/bridge/link.d.ts +48 -0
  24. package/dist/bridge/link.js +136 -0
  25. package/dist/bridge/memory-store.d.ts +23 -0
  26. package/dist/bridge/memory-store.js +152 -0
  27. package/dist/bridge/pair.d.ts +46 -0
  28. package/dist/bridge/pair.js +240 -0
  29. package/dist/bridge/peers.d.ts +9 -0
  30. package/dist/bridge/peers.js +25 -2
  31. package/dist/bridge/protocol.js +20 -1
  32. package/dist/bridge/schedule-watch.d.ts +2 -0
  33. package/dist/bridge/schedule-watch.js +16 -3
  34. package/dist/bridge/server-launch.d.ts +9 -0
  35. package/dist/bridge/server-launch.js +34 -11
  36. package/dist/bridge/server-pane-routes.d.ts +7 -0
  37. package/dist/bridge/server-pane-routes.js +128 -18
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +55 -29
  40. package/dist/bridge/server-stream.js +4 -1
  41. package/dist/bridge/speech-key.d.ts +33 -0
  42. package/dist/bridge/speech-key.js +106 -0
  43. package/dist/bridge/speech-transcribe.js +1 -1
  44. package/dist/bridge/speech.d.ts +1 -3
  45. package/dist/bridge/speech.js +2 -16
  46. package/dist/bridge/transcript-preview.d.ts +2 -0
  47. package/dist/bridge/transcript-preview.js +15 -0
  48. package/dist/bridge-hook.mjs +9940 -3601
  49. package/dist/cli/config-policy.js +25 -0
  50. package/dist/cli/extract.d.ts +0 -8
  51. package/dist/cli/extract.js +1 -1
  52. package/dist/cli-handlers.js +6 -0
  53. package/dist/cli-registry.js +21 -9
  54. package/dist/content/learning.js +1 -1
  55. package/dist/content/validate.d.ts +14 -3
  56. package/dist/content/validate.js +174 -114
  57. package/dist/data/access.d.ts +9 -0
  58. package/dist/data/access.js +18 -0
  59. package/dist/data/tasks.d.ts +26 -0
  60. package/dist/data/tasks.js +72 -1
  61. package/dist/entrypoint.js +7 -0
  62. package/dist/generated/memory-ui-graph.browser.js +520 -410
  63. package/dist/governance/policy.js +4 -3
  64. package/dist/governance/rbac.d.ts +1 -1
  65. package/dist/governance/rbac.js +1 -0
  66. package/dist/hooks.d.ts +0 -15
  67. package/dist/hooks.js +1 -1
  68. package/dist/init/init-uninstall.js +13 -3
  69. package/dist/init/init-walkthrough.d.ts +10 -0
  70. package/dist/init/init-walkthrough.js +24 -1
  71. package/dist/init/init.d.ts +5 -0
  72. package/dist/init/init.js +54 -32
  73. package/dist/init/setup.js +19 -5
  74. package/dist/init/store-gitignore.d.ts +0 -5
  75. package/dist/init/store-gitignore.js +0 -8
  76. package/dist/link/context-imports.d.ts +15 -0
  77. package/dist/link/context-imports.js +101 -0
  78. package/dist/link/doctor.js +38 -4
  79. package/dist/mcp/profile.d.ts +0 -4
  80. package/dist/mcp/profile.js +2 -14
  81. package/dist/memory-ui-graph.runtime.js +520 -410
  82. package/dist/modules/code-package.js +10 -2
  83. package/dist/modules/config.d.ts +7 -0
  84. package/dist/modules/config.js +17 -0
  85. package/dist/modules/registry.js +6 -5
  86. package/dist/profile-store.js +39 -3
  87. package/dist/project-topics.d.ts +1 -0
  88. package/dist/project-topics.js +9 -6
  89. package/dist/shared/retrieval.d.ts +0 -2
  90. package/dist/shared/retrieval.js +1 -1
  91. package/dist/sync/task-claim.d.ts +22 -0
  92. package/dist/sync/task-claim.js +45 -0
  93. package/dist/tools/code.js +29 -21
  94. package/dist/tools/config.js +3 -0
  95. package/dist/tools/dispatch.js +3 -3
  96. package/dist/tools/finding.d.ts +11 -0
  97. package/dist/tools/finding.js +154 -99
  98. package/dist/tools/tasks.js +40 -1
  99. package/dist/ui/server.js +18 -1
  100. package/dist/update.js +21 -10
  101. package/package.json +8 -7
  102. package/starter/global/skills/conductor/SKILL.md +42 -10
@@ -817,7 +817,6 @@ function collectTtlExpiredEntries(file, project, ttlDays, lastRetrieval) {
817
817
  * filled up.
818
818
  */
819
819
  export function pruneDeadMemories(phrenPath, project, dryRun) {
820
- const policy = getRetentionPolicy(phrenPath);
821
820
  if (project && !isValidProjectName(project))
822
821
  return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
823
822
  const dirs = project
@@ -827,12 +826,14 @@ export function pruneDeadMemories(phrenPath, project, dryRun) {
827
826
  })()
828
827
  : getProjectDirs(phrenPath).filter((dir) => path.basename(dir) !== "global");
829
828
  let pruned = 0;
830
- const cutoffDays = policy.retentionDays;
831
829
  const dryRunDetails = [];
832
830
  for (const dir of dirs) {
833
831
  const file = resolveFindingsPath(dir);
834
832
  if (!file)
835
833
  continue;
834
+ // Resolve per project: a project's own retentionDays override must win over
835
+ // the global window, as it already does on the injection path.
836
+ const cutoffDays = getRetentionPolicy(phrenPath, path.basename(dir)).retentionDays;
836
837
  // Q23: see docs/decisions/Q23-per-file-lock-concurrent-writers.md
837
838
  withFileLock(file, () => {
838
839
  const lines = fs.readFileSync(file, "utf8").split("\n");
@@ -894,7 +895,7 @@ export function pruneDeadMemories(phrenPath, project, dryRun) {
894
895
  if (!file)
895
896
  continue;
896
897
  const projectName = path.basename(dir);
897
- const expiredEntries = collectTtlExpiredEntries(file, projectName, policy.ttlDays, lastRetrieval);
898
+ const expiredEntries = collectTtlExpiredEntries(file, projectName, getRetentionPolicy(phrenPath, projectName).ttlDays, lastRetrieval);
898
899
  if (!expiredEntries.length)
899
900
  continue;
900
901
  ttlExpired += expiredEntries.length;
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * The actor is read from the PHREN_ACTOR env var (falls back to open if unset).
18
18
  */
19
- type RbacAction = "add_finding" | "remove_finding" | "edit_finding" | "complete_task" | "add_task" | "remove_task" | "update_task" | "pin_task" | "add_note" | "edit_note" | "remove_note" | "promote_note" | "manage_config";
19
+ type RbacAction = "add_finding" | "remove_finding" | "edit_finding" | "complete_task" | "add_task" | "remove_task" | "update_task" | "pin_task" | "claim_task" | "add_note" | "edit_note" | "remove_note" | "promote_note" | "manage_config";
20
20
  /**
21
21
  * Appended to every ACL-write denial. The natural way to lock yourself out is
22
22
  * to run the very first `phren config access set --admins=someone-else`: that
@@ -145,6 +145,7 @@ const CONTRIBUTOR_ACTIONS = new Set([
145
145
  "remove_task",
146
146
  "update_task",
147
147
  "pin_task",
148
+ "claim_task",
148
149
  "add_note",
149
150
  "edit_note",
150
151
  "remove_note",
package/dist/hooks.d.ts CHANGED
@@ -14,21 +14,6 @@ export declare function detectInstalledTools(): Set<string>;
14
14
  * re-resolves on every run) or the ~/.local/bin/phren wrapper instead.
15
15
  */
16
16
  export declare function isEphemeralNpxPath(p: string): boolean;
17
- /**
18
- * The local file a hook command depends on — the `~/.local/bin/phren` wrapper,
19
- * or the script passed to `node`.
20
- *
21
- * Returns `null` for commands that re-resolve themselves on every run
22
- * (`npx -y @phren/cli …`), which cannot go stale, and for commands with no
23
- * recognisable path.
24
- *
25
- * Why this matters: `npm install -g @phren/cli` can move the package entry
26
- * between versions (0.1.40 moved it from `mcp/dist/index.js` to
27
- * `dist/index.js`). Hook commands in settings.json keep the old absolute path
28
- * and every hook then dies with MODULE_NOT_FOUND on every prompt and every
29
- * Stop — silently, because hook failures are not surfaced.
30
- */
31
- export declare function extractHookScriptPath(command: string): string | null;
32
17
  /**
33
18
  * Hook commands whose entrypoint no longer exists on disk. Deduplicated, so an
34
19
  * upgrade that breaks all four lifecycle hooks reports one path, not four.
package/dist/hooks.js CHANGED
@@ -133,7 +133,7 @@ function isPathLike(token) {
133
133
  * and every hook then dies with MODULE_NOT_FOUND on every prompt and every
134
134
  * Stop — silently, because hook failures are not surfaced.
135
135
  */
136
- export function extractHookScriptPath(command) {
136
+ function extractHookScriptPath(command) {
137
137
  if (!command)
138
138
  return null;
139
139
  // `npx` re-resolves the package each run, so it is never stale.
@@ -175,8 +175,14 @@ function filterAgentHooks(filePath, commandField) {
175
175
  }
176
176
  }
177
177
  async function promptUninstallConfirm(phrenPath) {
178
- if (!process.stdin.isTTY || !process.stdout.isTTY)
179
- return true;
178
+ // No TTY is not consent: agent shells, CI steps and pipes all lack one, and
179
+ // they are exactly where an accidental `phren uninstall` must not delete the
180
+ // store. --yes is the explicit opt-in.
181
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
182
+ log(`\n Refusing to delete ${phrenPath} without confirmation.`);
183
+ log(" This session is non-interactive; re-run with --yes to confirm.");
184
+ return false;
185
+ }
180
186
  // Show summary of what will be deleted
181
187
  try {
182
188
  const projectDirs = getProjectDirs(phrenPath);
@@ -242,7 +248,11 @@ export async function runUninstall(opts = {}) {
242
248
  });
243
249
  });
244
250
  })()
245
- : true);
251
+ : (() => {
252
+ log("\n Refusing to remove phren config without confirmation.");
253
+ log(" This session is non-interactive; re-run with --yes to confirm.");
254
+ return false;
255
+ })());
246
256
  if (!confirmed) {
247
257
  log("Uninstall cancelled.");
248
258
  return;
@@ -53,6 +53,10 @@ export interface WalkthroughResult {
53
53
  findingSensitivity: "minimal" | "conservative" | "balanced" | "aggressive";
54
54
  githubUsername?: string;
55
55
  githubRepo?: string;
56
+ /** Create the private repo with gh and push, instead of printing the steps. */
57
+ githubCreate?: boolean;
58
+ /** Install Phren Hook and show the pairing QR code once setup finishes. */
59
+ connectPhone?: boolean;
56
60
  cloneUrl?: string;
57
61
  domain: InitProjectDomain;
58
62
  inferredScaffold?: InferredInitScaffold;
@@ -60,6 +64,12 @@ export interface WalkthroughResult {
60
64
  export interface WalkthroughOptions {
61
65
  /** When true, skip the express prompt and use recommended defaults immediately */
62
66
  express?: boolean;
67
+ /** When true, skip the express prompt and ask about every setting */
68
+ advanced?: boolean;
69
+ /** The signed-in GitHub login from gh, for the sync offer; injectable for tests */
70
+ githubLogin?: () => Promise<string | undefined>;
63
71
  }
72
+ /** The login gh is signed in as, or undefined when gh is missing or signed out. */
73
+ export declare function ghLogin(): Promise<string | undefined>;
64
74
  export declare function runWalkthrough(phrenPath: string, options?: WalkthroughOptions): Promise<WalkthroughResult>;
65
75
  export {};
@@ -125,6 +125,16 @@ async function readlineWalkthroughPrompts() {
125
125
  function detectRepoRootForStorage(phrenPath) {
126
126
  return detectProjectDir(process.cwd(), phrenPath);
127
127
  }
128
+ /** The login gh is signed in as, or undefined when gh is missing or signed out. */
129
+ export async function ghLogin() {
130
+ const { execFile } = await import("child_process");
131
+ return new Promise(resolve => {
132
+ execFile("gh", ["api", "user", "--jq", ".login"], { timeout: 8000 }, (error, stdout) => {
133
+ const login = String(stdout ?? "").trim();
134
+ resolve(!error && /^[A-Za-z0-9-]{1,39}$/.test(login) ? login : undefined);
135
+ });
136
+ });
137
+ }
128
138
  // Interactive walkthrough for first-time init
129
139
  export async function runWalkthrough(phrenPath, options) {
130
140
  const prompts = await createWalkthroughPrompts();
@@ -151,7 +161,7 @@ export async function runWalkthrough(phrenPath, options) {
151
161
  log("Every option can be changed later.\n");
152
162
  // Express mode: skip the entire walkthrough with recommended defaults
153
163
  const useExpress = options?.express === true
154
- || (options?.express !== false && await prompts.confirm("Use recommended settings? (global storage, MCP on, hooks on, auto tasks)", true));
164
+ || (options?.express !== false && options?.advanced !== true && await prompts.confirm("Use recommended settings? (global storage, MCP on, hooks on, auto tasks)", true));
155
165
  if (useExpress) {
156
166
  const expressResult = {
157
167
  storageChoice: "global",
@@ -184,6 +194,19 @@ export async function runWalkthrough(phrenPath, options) {
184
194
  "Task mode: auto",
185
195
  "Domain: software",
186
196
  ]);
197
+ // Only a live terminal gets the follow-up offers; --express stays silent.
198
+ if (options?.express !== true) {
199
+ const login = await (options?.githubLogin ?? ghLogin)();
200
+ if (login && await prompts.confirm(`Sync memory to a private GitHub repo (${login}/my-phren)?`, true)) {
201
+ expressResult.githubUsername = login;
202
+ expressResult.githubRepo = "my-phren";
203
+ expressResult.githubCreate = true;
204
+ }
205
+ if (["darwin", "linux"].includes(process.platform)
206
+ && await prompts.confirm("Connect your phone now? (shows a QR code to scan in the Phren app)", false)) {
207
+ expressResult.connectPhone = true;
208
+ }
209
+ }
187
210
  return expressResult;
188
211
  }
189
212
  printSection("Storage Location");
@@ -49,6 +49,8 @@ export interface InitOptions {
49
49
  yes?: boolean;
50
50
  /** Skip walkthrough entirely with recommended defaults (express mode) */
51
51
  express?: boolean;
52
+ /** Ask about every setting instead of offering recommended defaults */
53
+ advanced?: boolean;
52
54
  /**
53
55
  * Allow init to repoint global wiring (~/.local/bin/phren wrapper and
54
56
  * Claude settings.json hooks/mcpServers.phren) at a different phren root
@@ -64,7 +66,10 @@ export interface InitOptions {
64
66
  _walkthroughGithub?: {
65
67
  username?: string;
66
68
  repo: string;
69
+ create?: boolean;
67
70
  };
71
+ /** Set by walkthrough when the user wants the phone connected right away */
72
+ _walkthroughPair?: boolean;
68
73
  /** Set by walkthrough to seed project docs/topics by domain */
69
74
  _walkthroughDomain?: InitProjectDomain;
70
75
  /** Set by walkthrough to seed adaptive project scaffold from current repo content */
package/dist/init/init.js CHANGED
@@ -74,6 +74,35 @@ export function isVersionNewer(current, previous) {
74
74
  return true;
75
75
  return c.pre > p.pre;
76
76
  }
77
+ function hasGitRemote(phrenPath) {
78
+ try {
79
+ return execFileSync("git", ["-C", phrenPath, "remote"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env: nonInteractiveGitEnv() }).trim() !== "";
80
+ }
81
+ catch {
82
+ return false;
83
+ }
84
+ }
85
+ /** Commit the new store and publish it as a private repo with gh. Returns whether it is now synced. */
86
+ async function createGithubStore(phrenPath, username, repo) {
87
+ const git = (args) => execFileSync("git", ["-C", phrenPath, ...args], { stdio: ["ignore", "pipe", "pipe"], env: nonInteractiveGitEnv() });
88
+ try {
89
+ git(["add", "-A"]);
90
+ try {
91
+ git(["commit", "-q", "-m", "Initial phren setup"]);
92
+ }
93
+ catch { /* nothing new to commit */ }
94
+ log(`\nCreating private repo ${username}/${repo} and pushing your memory…`);
95
+ execFileSync("gh", ["repo", "create", `${username}/${repo}`, "--private", `--source=${phrenPath}`, "--remote=origin", "--push"], { stdio: ["ignore", "pipe", "pipe"], timeout: 120_000 });
96
+ writeInstallPreferences(phrenPath, { syncIntent: "sync" });
97
+ log(` Synced: https://github.com/${username}/${repo} (private). Hooks pull and push it after each session.`);
98
+ return true;
99
+ }
100
+ catch (err) {
101
+ const stderr = String(err.stderr ?? "").trim().split("\n")[0];
102
+ log(` Couldn't create the GitHub repo${stderr ? `: ${stderr}` : ""}. Your memory is safe locally.`);
103
+ return false;
104
+ }
105
+ }
77
106
  function normalizedBootstrapProjectName(projectPath) {
78
107
  return projectSlugFromPath(projectPath);
79
108
  }
@@ -165,7 +194,7 @@ export async function runInit(opts = {}) {
165
194
  // --express bypasses the TTY check since it skips all interactive prompts
166
195
  const isTTY = process.stdin.isTTY && process.stdout.isTTY;
167
196
  if (!hasExistingInstall && !dryRun && !opts.yes && (isTTY || opts.express)) {
168
- const answers = await runWalkthrough(phrenPath, { express: opts.express });
197
+ const answers = await runWalkthrough(phrenPath, { express: opts.express, advanced: opts.advanced });
169
198
  opts._walkthroughStorageChoice = answers.storageChoice;
170
199
  opts._walkthroughStoragePath = answers.storagePath;
171
200
  opts._walkthroughStorageRepoRoot = answers.storageRepoRoot;
@@ -188,8 +217,9 @@ export async function runInit(opts = {}) {
188
217
  opts._walkthroughCloneUrl = answers.cloneUrl;
189
218
  }
190
219
  if (answers.githubRepo) {
191
- opts._walkthroughGithub = { username: answers.githubUsername, repo: answers.githubRepo };
220
+ opts._walkthroughGithub = { username: answers.githubUsername, repo: answers.githubRepo, create: answers.githubCreate };
192
221
  }
222
+ opts._walkthroughPair = answers.connectPhone;
193
223
  opts._walkthroughDomain = answers.domain;
194
224
  if (answers.inferredScaffold) {
195
225
  opts._walkthroughInferredScaffold = answers.inferredScaffold;
@@ -654,41 +684,33 @@ export async function runInit(opts = {}) {
654
684
  }
655
685
  }
656
686
  log(`\n\x1b[95m◆\x1b[0m phren initialized`);
657
- log(`\nNext steps:`);
658
- let step = 1;
659
- log(` ${step++}. Start a new Claude session in your project directory — phren injects context automatically`);
660
- log(` ${step++}. Run \`phren doctor\` to verify everything is wired correctly`);
661
- log(` ${step++}. Change defaults anytime: \`phren config project-ownership\`, \`phren config workflow\`, \`phren config proactivity.findings\`, \`phren config proactivity.tasks\``);
662
687
  const gh = opts._walkthroughGithub;
663
- if (gh) {
664
- const remote = gh.username
665
- ? `git@github.com:${gh.username}/${gh.repo}.git`
666
- : `git@github.com:YOUR_USERNAME/${gh.repo}.git`;
667
- log(` ${step++}. Push your phren to GitHub (private repo recommended):`);
668
- log(` cd ${phrenPath}`);
669
- log(` git add . && git commit -m "Initial phren setup"`);
670
- if (gh.username) {
671
- log(` gh repo create ${gh.username}/${gh.repo} --private --source=. --push`);
672
- log(` # or manually: git remote add origin ${remote} && git push -u origin main`);
688
+ let synced = hasGitRemote(phrenPath);
689
+ if (!synced && gh?.create && gh.username)
690
+ synced = await createGithubStore(phrenPath, gh.username, gh.repo);
691
+ let paired = false;
692
+ if (opts._walkthroughPair) {
693
+ const { enableHookForPhone } = await import("../modules/config.js");
694
+ const { runPair } = await import("../bridge/pair.js");
695
+ enableHookForPhone(phrenPath);
696
+ try {
697
+ paired = await runPair([], VERSION) === 0;
673
698
  }
674
- else {
675
- log(` git remote add origin ${remote}`);
676
- log(` git push -u origin main`);
699
+ catch (err) {
700
+ log(` Phone pairing didn't finish: ${errorMessage(err)}`);
677
701
  }
678
702
  }
679
- else {
680
- log(` ${step++}. Push to GitHub for cross-machine sync (private repo recommended):`);
681
- log(` cd ${phrenPath}`);
682
- log(` git add . && git commit -m "Initial phren setup"`);
683
- log(` git remote add origin git@github.com:YOUR_USERNAME/my-phren.git`);
684
- log(` git push -u origin main`);
703
+ log(`\nNext:`);
704
+ let step = 1;
705
+ log(` ${step++}. Start a new agent session (Claude, Codex, Copilot…) in a project. Phren loads its memory automatically.`);
706
+ if (!paired)
707
+ log(` ${step++}. Connect your phone any time: phren pair`);
708
+ if (!synced) {
709
+ const repo = gh ? `${gh.username ? `${gh.username}/` : ""}${gh.repo}` : "my-phren";
710
+ log(` ${step++}. Sync across computers: cd ${phrenPath} && gh repo create ${repo} --private --source=. --push`);
685
711
  }
686
- log(` ${step++}. Add more projects: cd ~/your-project && phren add`);
687
- if (!mcpEnabled) {
712
+ if (!mcpEnabled)
688
713
  log(` ${step++}. Turn MCP on: phren mcp-mode on`);
689
- }
690
- log(` ${step++}. After your first week, run phren-discover to surface gaps in your project knowledge`);
691
- log(` ${step++}. After working across projects, run phren-consolidate to find cross-project patterns`);
692
- log(`\n Read ${phrenPath}/README.md for a guided tour of each file.`);
714
+ log(` Settings: phren config · Health check: phren doctor`);
693
715
  log(``);
694
716
  }
@@ -35,8 +35,16 @@ function normalizeProjects(raw) {
35
35
  return [];
36
36
  return raw.map((entry) => String(entry));
37
37
  }
38
- function profileLooksRealProject(project) {
39
- return project === "global" || !LEGACY_SAMPLE_PROJECTS.has(project);
38
+ /**
39
+ * The sample names are also ordinary repo names, so the name alone is not
40
+ * evidence. phren stopped shipping the sample directories: an entry with no
41
+ * project directory in the store is the leftover sample, one with a directory
42
+ * is a real project.
43
+ */
44
+ function profileLooksRealProject(phrenPath, project) {
45
+ if (project === "global" || !LEGACY_SAMPLE_PROJECTS.has(project))
46
+ return true;
47
+ return fs.existsSync(path.join(phrenPath, project));
40
48
  }
41
49
  function pruneLegacySampleProjectsFromProfiles(phrenPath) {
42
50
  const profilesDir = path.join(phrenPath, "profiles");
@@ -53,7 +61,7 @@ function pruneLegacySampleProjectsFromProfiles(phrenPath) {
53
61
  if (!isRecord(parsed))
54
62
  continue;
55
63
  const originalProjects = normalizeProjects(parsed.projects);
56
- const nextProjects = originalProjects.filter(profileLooksRealProject);
64
+ const nextProjects = originalProjects.filter((project) => profileLooksRealProject(phrenPath, project));
57
65
  if (nextProjects.length === originalProjects.length)
58
66
  continue;
59
67
  removed += originalProjects.length - nextProjects.length;
@@ -345,8 +353,10 @@ export function repairPreexistingInstall(phrenPath, opts) {
345
353
  return {
346
354
  profileFilesUpdated: profileRepair.filesUpdated,
347
355
  removedLegacyProjects: profileRepair.removed,
348
- createdContextFile: ensureGeneratedContextFile(preferredHome),
349
- createdRootMemory: ensureGeneratedRootMemory(preferredHome),
356
+ // Both live in the user's home, so they are self-heal surfaces: `assisted`
357
+ // and `manual` do not re-create them.
358
+ createdContextFile: caps.selfHeal ? ensureGeneratedContextFile(preferredHome) : false,
359
+ createdRootMemory: caps.selfHeal ? ensureGeneratedRootMemory(preferredHome) : false,
350
360
  createdGlobalAssets,
351
361
  createdRuntimeAssets,
352
362
  createdFeatureDefaults,
@@ -741,7 +751,11 @@ export function updateMachinesYaml(phrenPath, machine, profile) {
741
751
  }
742
752
  }
743
753
  catch (err) {
754
+ // Not "no existing mapping": setMachineProfile refuses to rewrite the file,
755
+ // and the user needs to hear why the mapping did not change.
744
756
  logger.debug("setup", `updateMachinesYaml parse: ${errorMessage(err)}`);
757
+ console.warn(` ${machinesFile} could not be parsed; machine mappings left unchanged. Fix it by hand (check for git conflict markers), then run 'phren init' again.`);
758
+ return;
745
759
  }
746
760
  // Passive init/link refreshes should keep an existing mapping; explicit overrides can remap.
747
761
  if (hasExistingMapping && !machine && !profile)
@@ -22,8 +22,3 @@
22
22
  * put `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `PHREN_LLM_KEY` in.
23
23
  */
24
24
  export declare const STORE_SECRET_GITIGNORE_LINES: readonly [".runtime/", ".sessions/", ".env", "*.pem", "*.key", ".config/auth-profiles.json", ".config/modules.yaml.migration-backup"];
25
- /**
26
- * Whether a .gitignore body already covers every secret-bearing entry.
27
- * Compares whole trimmed lines, so a commented-out entry does not count.
28
- */
29
- export declare function missingSecretGitignoreLines(content: string): string[];
@@ -40,11 +40,3 @@ export const STORE_SECRET_GITIGNORE_LINES = [
40
40
  // Legacy module migration backups were once written into the working tree.
41
41
  ".config/modules.yaml.migration-backup",
42
42
  ];
43
- /**
44
- * Whether a .gitignore body already covers every secret-bearing entry.
45
- * Compares whole trimmed lines, so a commented-out entry does not count.
46
- */
47
- export function missingSecretGitignoreLines(content) {
48
- const present = new Set(content.split("\n").map((line) => line.trim()));
49
- return STORE_SECRET_GITIGNORE_LINES.filter((entry) => !present.has(entry));
50
- }
@@ -0,0 +1,15 @@
1
+ export interface ContextImportHit {
2
+ scope: string;
3
+ file: string;
4
+ line: number;
5
+ target: string;
6
+ }
7
+ export declare function findContextImportLines(content: string): Array<{
8
+ line: number;
9
+ target: string;
10
+ }>;
11
+ /** Turn each run of `@path` lines into one plain reference list. */
12
+ export declare function rewriteContextImports(content: string): string;
13
+ export declare function scanContextImports(phrenPath: string): ContextImportHit[];
14
+ /** Rewrite every flagged file in place; returns the files changed. */
15
+ export declare function fixContextImports(phrenPath: string, hits: ContextImportHit[]): string[];
@@ -0,0 +1,101 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { AGENT_INSTRUCTIONS_FILENAME, LEGACY_AGENT_INSTRUCTIONS_FILENAME } from "../agent-instructions.js";
4
+ import { atomicWriteText, debugLog, getProjectDirs } from "../shared.js";
5
+ import { errorMessage } from "../utils.js";
6
+ // Claude Code expands `@path` lines in CLAUDE.md as file imports, resolved
7
+ // against the real location of the file. A repo's CLAUDE.md is a symlink into
8
+ // the store, so every such import lands in ~/.phren/<project>/... — outside
9
+ // the repo — and Claude Code (2.1.278+) blocks on an "Allow external CLAUDE.md
10
+ // file imports?" dialog per project, or silently drops the import headless.
11
+ // The archive is retrieved by the hook on demand anyway, so the fix is a plain
12
+ // mention instead of an import.
13
+ const IMPORT_LINE_RE = /^@(?![a-z0-9-]+\/[a-z0-9-]+$)(\S+)\s*$/i;
14
+ export function findContextImportLines(content) {
15
+ const hits = [];
16
+ let inFence = false;
17
+ content.split("\n").forEach((raw, i) => {
18
+ const line = raw.trimEnd();
19
+ if (/^\s*(```|~~~)/.test(line)) {
20
+ inFence = !inFence;
21
+ return;
22
+ }
23
+ if (inFence)
24
+ return;
25
+ const m = IMPORT_LINE_RE.exec(line);
26
+ if (m)
27
+ hits.push({ line: i + 1, target: m[1] });
28
+ });
29
+ return hits;
30
+ }
31
+ /** Turn each run of `@path` lines into one plain reference list. */
32
+ export function rewriteContextImports(content) {
33
+ const lines = content.split("\n");
34
+ const flagged = new Set(findContextImportLines(content).map((h) => h.line - 1));
35
+ const out = [];
36
+ for (let i = 0; i < lines.length; i++) {
37
+ if (!flagged.has(i)) {
38
+ out.push(lines[i]);
39
+ continue;
40
+ }
41
+ const run = [];
42
+ while (i < lines.length && (flagged.has(i) || (run.length && lines[i].trim() === "" && flagged.has(i + 1)))) {
43
+ if (flagged.has(i))
44
+ run.push(lines[i].trim().slice(1));
45
+ i++;
46
+ }
47
+ i--;
48
+ out.push("Reference docs (the phren hook injects relevant parts on demand; not imported):");
49
+ for (const target of run)
50
+ out.push(`- \`${target}\``);
51
+ }
52
+ return out.join("\n");
53
+ }
54
+ function contextFilesIn(dir) {
55
+ return [AGENT_INSTRUCTIONS_FILENAME, LEGACY_AGENT_INSTRUCTIONS_FILENAME]
56
+ .map((name) => path.join(dir, name))
57
+ .filter((file) => {
58
+ try {
59
+ return fs.lstatSync(file).isFile();
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ });
65
+ }
66
+ export function scanContextImports(phrenPath) {
67
+ const hits = [];
68
+ const scopeDirs = [path.join(phrenPath, "global"), ...getProjectDirs(phrenPath)];
69
+ for (const dir of scopeDirs) {
70
+ for (const file of contextFilesIn(dir)) {
71
+ let content;
72
+ try {
73
+ content = fs.readFileSync(file, "utf8");
74
+ }
75
+ catch {
76
+ continue;
77
+ }
78
+ for (const hit of findContextImportLines(content))
79
+ hits.push({ scope: path.basename(dir), file, ...hit });
80
+ }
81
+ }
82
+ return hits;
83
+ }
84
+ /** Rewrite every flagged file in place; returns the files changed. */
85
+ export function fixContextImports(phrenPath, hits) {
86
+ const fixed = [];
87
+ for (const file of [...new Set(hits.map((h) => h.file))]) {
88
+ try {
89
+ const content = fs.readFileSync(file, "utf8");
90
+ const next = rewriteContextImports(content);
91
+ if (next !== content) {
92
+ atomicWriteText(file, next);
93
+ fixed.push(file);
94
+ }
95
+ }
96
+ catch (err) {
97
+ debugLog(`context-imports: could not rewrite ${file}: ${errorMessage(err)}`);
98
+ }
99
+ }
100
+ return fixed;
101
+ }
@@ -22,6 +22,7 @@ import { repairPreexistingInstall } from "../init/setup.js";
22
22
  import { getManagementPreset, resolveManagementCapabilities } from "../init/management-preset.js";
23
23
  import { getMachineName, lookupProfile, findProfileFile, getProfileProjects, findProjectDir, } from "./link.js";
24
24
  import { claudeProjectKey } from "./context.js";
25
+ import { scanContextImports, fixContextImports } from "./context-imports.js";
25
26
  import { getProjectOwnershipMode, readProjectConfig } from "../project-config.js";
26
27
  import { readInstallPreferences } from "../init/preferences.js";
27
28
  import { logger } from "../logger.js";
@@ -330,17 +331,20 @@ export async function runDoctor(phrenPath, fix = false, checkData = false, confi
330
331
  ? "could not benchmark filesystem, check ~/.phren permissions"
331
332
  : `write+read+delete in ${fsMs}ms${fsSlow ? " (slow, check if ~/.phren is on a network mount)" : ""}`,
332
333
  });
334
+ // Both generated home files are self-heal surfaces; under a preset without
335
+ // selfHeal a missing one is expected, not a failure.
336
+ const notSelfHealed = `not re-created under ${managementPreset} preset`;
333
337
  const contextFile = homePath(".phren-context.md");
334
338
  checks.push({
335
339
  name: "context-file",
336
- ok: fs.existsSync(contextFile),
337
- detail: fs.existsSync(contextFile) ? contextFile : "missing ~/.phren-context.md",
340
+ ok: fs.existsSync(contextFile) || !caps.selfHeal,
341
+ detail: fs.existsSync(contextFile) ? contextFile : caps.selfHeal ? "missing ~/.phren-context.md" : notSelfHealed,
338
342
  });
339
343
  const memoryFile = path.join(homeDir(), ".claude", "projects", claudeProjectKey(), "memory", "MEMORY.md");
340
344
  checks.push({
341
345
  name: "root-memory",
342
- ok: fs.existsSync(memoryFile),
343
- detail: fs.existsSync(memoryFile) ? memoryFile : "missing generated MEMORY.md",
346
+ ok: fs.existsSync(memoryFile) || !caps.selfHeal,
347
+ detail: fs.existsSync(memoryFile) ? memoryFile : caps.selfHeal ? "missing generated MEMORY.md" : notSelfHealed,
344
348
  });
345
349
  // Under presets that don't symlink into ~/.claude, the "missing" links are
346
350
  // expected — report them as ok with a preset note instead of failures.
@@ -910,6 +914,36 @@ export async function runDoctor(phrenPath, fix = false, checkData = false, confi
910
914
  catch (err) {
911
915
  debugLog(`doctor: zombie task scan failed: ${errorMessage(err)}`);
912
916
  }
917
+ // `@path` import lines in store-managed AGENTS.md/CLAUDE.md resolve outside
918
+ // the repo (the repo file is a symlink into the store), so Claude Code blocks
919
+ // on its external-imports dialog. With --fix, rewrite them as plain mentions.
920
+ try {
921
+ const importHits = scanContextImports(phrenPath);
922
+ const fixedFiles = importHits.length && fix ? fixContextImports(phrenPath, importHits) : [];
923
+ const scopes = [...new Set(importHits.map((h) => h.scope))];
924
+ checks.push({
925
+ name: "context-imports",
926
+ ok: importHits.length === 0 || fixedFiles.length > 0,
927
+ detail: importHits.length === 0
928
+ ? "no @imports in managed AGENTS.md/CLAUDE.md"
929
+ : fixedFiles.length
930
+ ? `rewrote ${importHits.length} @import line(s) as plain references in ${fixedFiles.length} file(s) (${scopes.join(", ")})`
931
+ : `${importHits.length} @import line(s) in ${scopes.join(", ")} resolve outside the repo and trigger Claude Code's "Allow external CLAUDE.md file imports?" dialog. Run \`phren doctor --fix\` to rewrite them as plain references.`,
932
+ });
933
+ }
934
+ catch (err) {
935
+ debugLog(`doctor: context-imports scan failed: ${errorMessage(err)}`);
936
+ }
937
+ // Spoken replies are optional, so only a stored key other users can read,
938
+ // or a broken file, fails the check. The key itself is never shown.
939
+ try {
940
+ const { speechKeyStatus } = await import("../bridge/speech-key.js");
941
+ const speech = await speechKeyStatus();
942
+ checks.push({ name: "speech-key", ok: !speech.problem, detail: `${speech.configured ? "configured" : "not configured"}: ${speech.detail}` });
943
+ }
944
+ catch (err) {
945
+ debugLog(`doctor: speech-key check failed: ${errorMessage(err)}`);
946
+ }
913
947
  const ok = checks.every((c) => c.ok);
914
948
  return { ok, machine, profile: profile || undefined, checks };
915
949
  }
@@ -61,7 +61,3 @@ export interface BuiltTool {
61
61
  * (a module not loaded, say) is left out rather than advertised.
62
62
  */
63
63
  export declare function buildCompositeTools(catalog: Catalog): BuiltTool[];
64
- /** Rough size of what a client downloads for a set of tools, for tests and doctor. */
65
- export declare function schemaWeight(entries: Iterable<{
66
- config: ToolConfig;
67
- }>): number;
@@ -62,9 +62,10 @@ const COMPOSITES = {
62
62
  },
63
63
  manage_task: {
64
64
  title: "◆ phren · manage task",
65
- summary: "Change an existing task: complete, update, remove, pin, or tidy the done list. Pass `action` plus that action's own parameters.",
65
+ summary: "Change an existing task: complete, update, remove, pin, claim for this computer, or tidy the done list. Pass `action` plus that action's own parameters.",
66
66
  actions: {
67
67
  complete: "complete_task",
68
+ claim: "claim_task",
68
69
  update: "update_task",
69
70
  remove: "remove_task",
70
71
  pin: "pin_task",
@@ -322,16 +323,3 @@ export function buildCompositeTools(catalog) {
322
323
  }
323
324
  return out;
324
325
  }
325
- /** Rough size of what a client downloads for a set of tools, for tests and doctor. */
326
- export function schemaWeight(entries) {
327
- let chars = 0;
328
- for (const { config } of entries) {
329
- chars += (config.title ?? "").length + (config.description ?? "").length;
330
- const raw = config.inputSchema;
331
- const schema = raw instanceof z.ZodObject ? raw : raw && typeof raw === "object" ? z.object(raw) : null;
332
- if (schema)
333
- for (const [k, t] of Object.entries(schema.shape))
334
- chars += k.length + (t.description ?? "").length + 24;
335
- }
336
- return chars;
337
- }