@phren/cli 0.2.16 → 0.3.0

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 (60) hide show
  1. package/dist/bridge/agent-hooks.d.ts +2 -0
  2. package/dist/bridge/agent-hooks.js +4 -0
  3. package/dist/bridge/code-note.d.ts +2 -1
  4. package/dist/bridge/code-note.js +13 -4
  5. package/dist/bridge/code-routes.d.ts +32 -14
  6. package/dist/bridge/code-routes.js +131 -8
  7. package/dist/bridge/dispatch-returns.d.ts +2 -0
  8. package/dist/bridge/dispatch-returns.js +12 -8
  9. package/dist/bridge/dispatch.d.ts +4 -1
  10. package/dist/bridge/dispatch.js +30 -5
  11. package/dist/bridge/install.d.ts +0 -4
  12. package/dist/bridge/install.js +3 -3
  13. package/dist/bridge/protocol.js +20 -1
  14. package/dist/bridge/schedule-watch.d.ts +2 -0
  15. package/dist/bridge/schedule-watch.js +16 -3
  16. package/dist/bridge/server-pane-routes.d.ts +7 -0
  17. package/dist/bridge/server-pane-routes.js +90 -11
  18. package/dist/bridge/server-routes.d.ts +2 -0
  19. package/dist/bridge/server-routes.js +44 -26
  20. package/dist/bridge/transcript-preview.d.ts +2 -0
  21. package/dist/bridge/transcript-preview.js +15 -0
  22. package/dist/bridge-hook.mjs +8842 -3209
  23. package/dist/cli/config-policy.js +25 -0
  24. package/dist/cli/extract.d.ts +0 -8
  25. package/dist/cli/extract.js +1 -1
  26. package/dist/cli-registry.js +7 -7
  27. package/dist/content/validate.d.ts +14 -3
  28. package/dist/content/validate.js +174 -114
  29. package/dist/data/access.d.ts +9 -0
  30. package/dist/data/access.js +18 -0
  31. package/dist/generated/memory-ui-graph.browser.js +520 -410
  32. package/dist/governance/policy.js +4 -3
  33. package/dist/hooks.d.ts +0 -15
  34. package/dist/hooks.js +1 -1
  35. package/dist/init/init-uninstall.js +13 -3
  36. package/dist/init/setup.js +19 -5
  37. package/dist/init/store-gitignore.d.ts +0 -5
  38. package/dist/init/store-gitignore.js +0 -8
  39. package/dist/link/context-imports.d.ts +15 -0
  40. package/dist/link/context-imports.js +101 -0
  41. package/dist/link/doctor.js +28 -4
  42. package/dist/mcp/profile.d.ts +0 -4
  43. package/dist/mcp/profile.js +0 -13
  44. package/dist/memory-ui-graph.runtime.js +520 -410
  45. package/dist/modules/code-package.js +10 -2
  46. package/dist/modules/registry.js +1 -1
  47. package/dist/profile-store.js +39 -3
  48. package/dist/project-topics.d.ts +1 -0
  49. package/dist/project-topics.js +9 -6
  50. package/dist/shared/retrieval.d.ts +0 -2
  51. package/dist/shared/retrieval.js +1 -1
  52. package/dist/tools/code.js +29 -21
  53. package/dist/tools/config.js +3 -0
  54. package/dist/tools/dispatch.js +1 -1
  55. package/dist/tools/finding.d.ts +11 -0
  56. package/dist/tools/finding.js +154 -99
  57. package/dist/ui/server.js +18 -1
  58. package/dist/update.js +21 -10
  59. package/package.json +7 -7
  60. package/starter/global/skills/conductor/SKILL.md +1 -1
@@ -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;
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;
@@ -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,26 @@ 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
+ }
913
937
  const ok = checks.every((c) => c.ok);
914
938
  return { ok, machine, profile: profile || undefined, checks };
915
939
  }
@@ -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;
@@ -322,16 +322,3 @@ export function buildCompositeTools(catalog) {
322
322
  }
323
323
  return out;
324
324
  }
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
- }