@phren/cli 0.1.40 → 0.1.41

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 (105) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +11 -3
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +243 -9
  6. package/dist/cli/govern.js +6 -87
  7. package/dist/cli/hooks-context.d.ts +1 -1
  8. package/dist/cli/hooks-context.js +1 -1
  9. package/dist/cli/namespaces-review.js +14 -1
  10. package/dist/cli/session-git.d.ts +18 -0
  11. package/dist/cli/session-git.js +47 -0
  12. package/dist/cli/session-start.js +2 -2
  13. package/dist/cli/session-stop.d.ts +11 -0
  14. package/dist/cli/session-stop.js +141 -33
  15. package/dist/cli/session-tool-hook.js +17 -5
  16. package/dist/cli-registry.d.ts +1 -1
  17. package/dist/cli-registry.js +1 -0
  18. package/dist/content/dedup.d.ts +1 -4
  19. package/dist/content/dedup.js +7 -63
  20. package/dist/content/learning.d.ts +20 -2
  21. package/dist/content/learning.js +21 -3
  22. package/dist/content/quality.d.ts +23 -0
  23. package/dist/content/quality.js +123 -0
  24. package/dist/content/secrets.d.ts +52 -0
  25. package/dist/content/secrets.js +193 -0
  26. package/dist/data/access.d.ts +56 -2
  27. package/dist/data/access.js +246 -24
  28. package/dist/entrypoint.js +5 -1
  29. package/dist/finding/impact.js +170 -43
  30. package/dist/finding/lifecycle.d.ts +19 -2
  31. package/dist/finding/lifecycle.js +15 -3
  32. package/dist/git-worktree.d.ts +19 -0
  33. package/dist/git-worktree.js +117 -0
  34. package/dist/governance/policy.d.ts +84 -4
  35. package/dist/governance/policy.js +209 -14
  36. package/dist/governance/rbac.d.ts +8 -0
  37. package/dist/governance/rbac.js +26 -0
  38. package/dist/hooks.d.ts +20 -0
  39. package/dist/hooks.js +113 -3
  40. package/dist/index.js +5 -1
  41. package/dist/init/guard-globals.d.ts +20 -0
  42. package/dist/init/guard-globals.js +72 -6
  43. package/dist/init/init-configure.js +6 -6
  44. package/dist/init/init.js +10 -6
  45. package/dist/init/setup.d.ts +4 -3
  46. package/dist/init/setup.js +120 -16
  47. package/dist/init/store-gitignore.d.ts +29 -0
  48. package/dist/init/store-gitignore.js +48 -0
  49. package/dist/link/doctor.js +86 -20
  50. package/dist/phren-core.d.ts +35 -8
  51. package/dist/phren-core.js +35 -8
  52. package/dist/phren-paths.d.ts +90 -1
  53. package/dist/phren-paths.js +150 -5
  54. package/dist/proactivity.js +1 -1
  55. package/dist/shared/embedding-cache.d.ts +16 -0
  56. package/dist/shared/embedding-cache.js +24 -0
  57. package/dist/shared/fragment-graph.js +10 -0
  58. package/dist/shared/index.d.ts +6 -0
  59. package/dist/shared/index.js +523 -138
  60. package/dist/shared/ollama.d.ts +14 -2
  61. package/dist/shared/ollama.js +84 -5
  62. package/dist/shared/retrieval.d.ts +22 -1
  63. package/dist/shared/retrieval.js +30 -1
  64. package/dist/shared/search-fallback.js +15 -3
  65. package/dist/shared/vector-index.d.ts +20 -1
  66. package/dist/shared/vector-index.js +18 -4
  67. package/dist/shared.d.ts +1 -1
  68. package/dist/shared.js +1 -1
  69. package/dist/status.js +18 -1
  70. package/dist/store-registry.d.ts +22 -0
  71. package/dist/store-registry.js +36 -3
  72. package/dist/task/lifecycle.js +31 -0
  73. package/dist/tools/config.js +16 -7
  74. package/dist/tools/data.js +1 -1
  75. package/dist/tools/extract.js +2 -2
  76. package/dist/tools/finding.js +14 -3
  77. package/dist/tools/graph.js +9 -1
  78. package/dist/tools/memory.js +1 -1
  79. package/dist/tools/notes.js +3 -3
  80. package/dist/tools/ops.js +19 -18
  81. package/dist/tools/search.js +2 -2
  82. package/dist/tools/session.js +2 -2
  83. package/dist/tools/tasks.js +2 -2
  84. package/dist/tools/types.d.ts +32 -2
  85. package/dist/tools/types.js +41 -8
  86. package/dist/ui/scripts.js +2 -2
  87. package/dist/ui/server.js +5 -0
  88. package/package.json +1 -1
  89. package/dist/cli-hooks-git.d.ts +0 -50
  90. package/dist/cli-hooks-git.js +0 -288
  91. package/starter/my-api/.claude/skills/README.md +0 -7
  92. package/starter/my-api/CLAUDE.md +0 -33
  93. package/starter/my-api/FINDINGS.md +0 -9
  94. package/starter/my-api/summary.md +0 -7
  95. package/starter/my-api/tasks.md +0 -7
  96. package/starter/my-first-project/.claude/skills/README.md +0 -7
  97. package/starter/my-first-project/CLAUDE.md +0 -49
  98. package/starter/my-first-project/FINDINGS.md +0 -24
  99. package/starter/my-first-project/summary.md +0 -11
  100. package/starter/my-first-project/tasks.md +0 -25
  101. package/starter/my-frontend/.claude/skills/README.md +0 -7
  102. package/starter/my-frontend/CLAUDE.md +0 -33
  103. package/starter/my-frontend/FINDINGS.md +0 -9
  104. package/starter/my-frontend/summary.md +0 -7
  105. package/starter/my-frontend/tasks.md +0 -7
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The gitignore entries every phren store must have, whichever install mode
3
+ * created it.
4
+ *
5
+ * A store is a git repo that phren itself pushes: `push_changes` and the
6
+ * session-stop hook both run `git add -A` against it, and a synced store has a
7
+ * remote. Anything secret-bearing that is not ignored therefore ends up in a
8
+ * commit — this is exactly how `.config/auth-profiles.json` leaked before
9
+ * credentials moved to `.runtime/`.
10
+ *
11
+ * Both `git add -A` paths already carry an unstage guard for the same set
12
+ * (`tools/finding.ts` push_changes, `cli/session-stop.ts`). That guard is the
13
+ * second line of defence, and only the second: it can unstage a change, but it
14
+ * cannot un-commit a file that some other path — a user's own `git add .`, an
15
+ * editor's git integration — already tracked. .gitignore is the line that
16
+ * stops the file from ever becoming tracked, so the two lists must agree.
17
+ *
18
+ * Kept as a shared const because there were two templates that had already
19
+ * drifted: `packages/cli/starter/.gitignore` (shared mode) and the inline list
20
+ * in `init-configure.ts` (project-local mode). Neither covered `.env`, which
21
+ * `phren init` writes into the store itself and which the docs tell users to
22
+ * put `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `PHREN_LLM_KEY` in.
23
+ */
24
+ export const STORE_SECRET_GITIGNORE_LINES = [
25
+ // Credential store (API keys, OpenAI Codex OAuth access + refresh tokens),
26
+ // debug/hook-error logs, and cached memory content.
27
+ ".runtime/",
28
+ // Session transcripts and per-session message artifacts.
29
+ ".sessions/",
30
+ // Feature flags *and* API keys — see docs/environment.md. Written by
31
+ // `phren init` (ensureDefaultFeatureFlags), so it always exists.
32
+ ".env",
33
+ // Key material a user may have dropped in the store directory.
34
+ "*.pem",
35
+ "*.key",
36
+ // Legacy credential location, pre-`.runtime/` migration. Stays forever so a
37
+ // store created before the move, or one where the migration has not run yet,
38
+ // never has its credentials committed.
39
+ ".config/auth-profiles.json",
40
+ ];
41
+ /**
42
+ * Whether a .gitignore body already covers every secret-bearing entry.
43
+ * Compares whole trimmed lines, so a commented-out entry does not count.
44
+ */
45
+ export function missingSecretGitignoreLines(content) {
46
+ const present = new Set(content.split("\n").map((line) => line.trim()));
47
+ return STORE_SECRET_GITIGNORE_LINES.filter((entry) => !present.has(entry));
48
+ }
@@ -5,12 +5,12 @@ import { debugLog, EXEC_TIMEOUT_QUICK_MS, getProjectDirs, isRecord, homeDir, hom
5
5
  import { migrateInvalidProjectNames, formatMigrationSummary } from "../project-migrate.js";
6
6
  import { ROOT_MANIFEST_FILENAME } from "../phren-paths.js";
7
7
  import { STORES_FILENAME } from "../store-registry.js";
8
- import { commandVersion, versionAtLeast, nearestWritableTarget } from "../init/shared.js";
8
+ import { commandVersion, versionAtLeast, nearestWritableTarget, resolveEntryScript } from "../init/shared.js";
9
9
  import { validateGovernanceJson } from "../shared/governance.js";
10
10
  import { errorMessage } from "../utils.js";
11
11
  import { buildIndex, queryRows } from "../shared/index.js";
12
12
  import { validateTaskFormat, validateFindingsFormat } from "../shared/content.js";
13
- import { detectInstalledTools, isEphemeralNpxPath } from "../hooks.js";
13
+ import { detectInstalledTools, isEphemeralNpxPath, findStaleHookEntrypoints } from "../hooks.js";
14
14
  import { validateSkillFrontmatter, validateSkillsDir } from "./skills.js";
15
15
  import { verifyFileChecksums, updateFileChecksums } from "./checksums.js";
16
16
  import { buildSkillManifest } from "../skill/registry.js";
@@ -374,7 +374,7 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
374
374
  }
375
375
  // Store registry health
376
376
  try {
377
- const { resolveAllStores, storesFilePath } = await import("../store-registry.js");
377
+ const { resolveAllStores, storesFilePath, describeUnavailableStore } = await import("../store-registry.js");
378
378
  const storesFile = storesFilePath(phrenPath);
379
379
  if (fs.existsSync(storesFile)) {
380
380
  const stores = resolveAllStores(phrenPath);
@@ -385,14 +385,26 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
385
385
  ? `${stores.length} stores configured`
386
386
  : "stores.yaml exists but no stores parsed",
387
387
  });
388
+ // Projects claimed by a store that is not attached here cannot be written
389
+ // at all — phren refuses rather than diverting them to the primary store.
390
+ const orphanedClaims = stores
391
+ .filter((store) => store.available === false && store.projects?.length)
392
+ .map((store) => `${store.name} → ${store.projects.join(", ")}`);
393
+ checks.push({
394
+ name: "store-claims-attached",
395
+ ok: orphanedClaims.length === 0,
396
+ detail: orphanedClaims.length === 0
397
+ ? "every claimed project resolves to an attached store"
398
+ : `projects claimed by unattached stores (writes to them will fail): ${orphanedClaims.join("; ")}`,
399
+ });
388
400
  for (const store of stores) {
389
- const pathExists = fs.existsSync(store.path);
401
+ const pathExists = store.available !== false;
390
402
  const gitExists = pathExists && fs.existsSync(path.join(store.path, ".git"));
391
403
  if (!pathExists) {
392
404
  checks.push({
393
405
  name: `store:${store.name}`,
394
406
  ok: false,
395
- detail: `store '${store.name}' path missing: ${store.path}`,
407
+ detail: describeUnavailableStore(store),
396
408
  });
397
409
  }
398
410
  else if (!gitExists) {
@@ -425,27 +437,75 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
425
437
  let hookOk = false;
426
438
  let lifecycleOk = false;
427
439
  let hooksEphemeral = false;
428
- try {
440
+ let staleEntrypoints = [];
441
+ /** Every `command` string under a Claude settings.json hook event. */
442
+ const phrenHookCommands = (hooks) => {
443
+ const commands = [];
444
+ for (const event of ["UserPromptSubmit", "Stop", "SessionStart", "PostToolUse"]) {
445
+ const entries = hooks[event];
446
+ if (!Array.isArray(entries))
447
+ continue;
448
+ for (const entry of entries) {
449
+ if (!isRecord(entry) || !Array.isArray(entry.hooks))
450
+ continue;
451
+ for (const hook of entry.hooks) {
452
+ if (isRecord(hook) && typeof hook.command === "string")
453
+ commands.push(hook.command);
454
+ }
455
+ }
456
+ }
457
+ return commands.filter((command) => /hook-(prompt|stop|session-start|tool)\b/.test(command));
458
+ };
459
+ const readHookState = () => {
429
460
  const cfg = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
430
- const hooks = cfg?.hooks || {};
461
+ const hooks = isRecord(cfg?.hooks) ? cfg.hooks : {};
431
462
  const promptHooks = JSON.stringify(hooks.UserPromptSubmit || []);
432
463
  const stopHooks = JSON.stringify(hooks.Stop || []);
433
464
  const startHooks = JSON.stringify(hooks.SessionStart || []);
434
- hookOk = promptHooks.includes("hook-prompt");
435
- const stopHookOk = stopHooks.includes("hook-stop");
436
- const startHookOk = startHooks.includes("hook-session-start");
437
- lifecycleOk = stopHookOk && startHookOk;
438
- // A hook command that points into the npx cache (~/.npm/_npx/<hash>/…)
439
- // works until npx prunes that cache, then breaks silently. Flag it so a
440
- // re-init (which now resolves to the stable ~/.local/bin/phren wrapper)
441
- // can repair it before the user notices context has stopped flowing.
442
- hooksEphemeral = [promptHooks, stopHooks, startHooks].some(isEphemeralNpxPath);
465
+ const commands = phrenHookCommands(hooks);
466
+ return {
467
+ hookOk: promptHooks.includes("hook-prompt"),
468
+ lifecycleOk: stopHooks.includes("hook-stop") && startHooks.includes("hook-session-start"),
469
+ // A hook command that points into the npx cache (~/.npm/_npx/<hash>/…)
470
+ // works until npx prunes that cache, then breaks silently.
471
+ ephemeral: [promptHooks, stopHooks, startHooks].some(isEphemeralNpxPath),
472
+ // A command whose entrypoint no longer exists is worse: it fails on every
473
+ // single turn with MODULE_NOT_FOUND. `npm i -g @phren/cli` moved the
474
+ // package entry in 0.1.40, so every upgraded install hit exactly this and
475
+ // doctor still reported the path as fine.
476
+ stale: findStaleHookEntrypoints(commands),
477
+ };
478
+ };
479
+ try {
480
+ const state = readHookState();
481
+ hookOk = state.hookOk;
482
+ lifecycleOk = state.lifecycleOk;
483
+ hooksEphemeral = state.ephemeral;
484
+ staleEntrypoints = state.stale;
443
485
  }
444
486
  catch (err) {
445
487
  debugLog(`doctor: failed to read Claude settings for hook check: ${errorMessage(err)}`);
446
488
  hookOk = false;
447
489
  lifecycleOk = false;
448
490
  }
491
+ // Repair stale/ephemeral hook commands before reporting, so `--fix` actually
492
+ // fixes the thing rather than reporting it as OK and doing nothing.
493
+ let hookPathRepaired = false;
494
+ if (fix && (staleEntrypoints.length > 0 || hooksEphemeral)) {
495
+ try {
496
+ const { configureClaude } = await import("../init/config.js");
497
+ configureClaude(phrenPath);
498
+ const state = readHookState();
499
+ hookOk = state.hookOk;
500
+ lifecycleOk = state.lifecycleOk;
501
+ hooksEphemeral = state.ephemeral;
502
+ hookPathRepaired = state.stale.length === 0 && !state.ephemeral;
503
+ staleEntrypoints = state.stale;
504
+ }
505
+ catch (err) {
506
+ debugLog(`doctor: hook path repair failed: ${errorMessage(err)}`);
507
+ }
508
+ }
449
509
  checks.push({
450
510
  name: "claude-hooks",
451
511
  ok: hookOk,
@@ -460,10 +520,16 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
460
520
  });
461
521
  checks.push({
462
522
  name: "hook-path-stable",
463
- ok: !hooksEphemeral,
464
- detail: hooksEphemeral
465
- ? "hook commands point into the ephemeral npx cache (~/.npm/_npx/…); re-run `npx @phren/cli init` to repoint at the stable ~/.local/bin/phren wrapper"
466
- : "hook commands use a stable entrypoint",
523
+ ok: !hooksEphemeral && staleEntrypoints.length === 0,
524
+ detail: staleEntrypoints.length > 0
525
+ ? `hook commands point at ${staleEntrypoints.length} entrypoint(s) that no longer exist: ${staleEntrypoints.join(", ")}. `
526
+ + `Every hook fails with MODULE_NOT_FOUND — usually after \`npm install -g @phren/cli\` moved the package entry. `
527
+ + `Run \`phren doctor --fix\` to repoint them at ${resolveEntryScript()}`
528
+ : hooksEphemeral
529
+ ? "hook commands point into the ephemeral npx cache (~/.npm/_npx/…); re-run `npx @phren/cli init` to repoint at the stable ~/.local/bin/phren wrapper"
530
+ : hookPathRepaired
531
+ ? "hook commands repaired to the current entrypoint"
532
+ : "hook commands resolve to an entrypoint that exists",
467
533
  });
468
534
  const runtimeHealthPath = runtimeHealthFile(phrenPath);
469
535
  let runtime = null;
@@ -11,7 +11,7 @@ export declare const UNIVERSAL_TECH_TERMS_RE: RegExp;
11
11
  * Additional fragment patterns beyond CamelCase and acronyms.
12
12
  * Each pattern has a named group so callers can identify the fragment type.
13
13
  */
14
- export declare const EXTRA_ENTITY_PATTERNS: Array<{
14
+ export declare const EXTRA_FRAGMENT_PATTERNS: Array<{
15
15
  re: RegExp;
16
16
  label: string;
17
17
  }>;
@@ -50,15 +50,42 @@ export declare function parsePhrenErrorCode(msg: string): PhrenErrorCode | undef
50
50
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
51
51
  /** Shallow-merge data onto defaults so missing keys get filled in. */
52
52
  export declare function withDefaults<T extends object>(data: Partial<T>, defaults: T): T;
53
- /** All valid finding type tags — used for writes, search filters, and hook extraction */
54
- export declare const FINDING_TYPES: readonly ["decision", "pitfall", "pattern", "tradeoff", "architecture", "bug"];
53
+ /**
54
+ * Finding types offered as an explicit choice: add_finding's findingType
55
+ * param, promote_note --type, and the web/iOS type pickers. Deliberately the
56
+ * intersection of what used to be three disjoint lists (this enum, the decay
57
+ * table, and the auto-detector) — "tradeoff" and "architecture" were offered
58
+ * here but had no decay rule and no max-age, so they never actually worked.
59
+ * Legacy stores may still contain those two tags; reading/searching them as
60
+ * plain text still works, they just aren't offered or decay-tracked anymore.
61
+ */
62
+ export declare const FINDING_TYPES: readonly ["decision", "pitfall", "pattern", "bug"];
55
63
  export type FindingType = (typeof FINDING_TYPES)[number];
56
- /** Searchable finding tags (same set as FINDING_TYPES) */
57
- export declare const FINDING_TAGS: readonly ["decision", "pitfall", "pattern", "tradeoff", "architecture", "bug"];
58
- export type FindingTag = FindingType;
59
- /** Canonical set of known observation tags — derived from FINDING_TYPES */
64
+ /**
65
+ * Every finding tag phren can actually produce or needs to search for: the
66
+ * offered FINDING_TYPES above, plus tags autoDetectFindingType
67
+ * (content/learning.ts) writes on its own initiative — "workaround" and
68
+ * "context" — which aren't offered as an explicit pick but still need a
69
+ * decay rule (finding/lifecycle.ts's FINDING_TYPE_DECAY is typed against
70
+ * this exact set) and need to stay filterable via search_knowledge's `tag`
71
+ * param.
72
+ */
73
+ export declare const FINDING_TAGS: readonly ["decision", "pitfall", "pattern", "bug", "workaround", "context"];
74
+ export type FindingTag = (typeof FINDING_TAGS)[number];
75
+ /** Canonical set of known finding tags for the "unknown tag" write-time warning — derived from FINDING_TAGS (not just FINDING_TYPES) so phren never flags its own auto-written workaround/context tags as unknown. */
60
76
  export declare const KNOWN_OBSERVATION_TAGS: Set<string>;
61
- /** Document types in the FTS index */
77
+ /**
78
+ * Document types in the FTS index.
79
+ *
80
+ * "canonical" is `truths.md`'s type (see FILE_TYPE_MAP in shared/index.ts):
81
+ * the file was renamed from `canonical_memories.md` to `truths.md` in the
82
+ * 0.0.5 rename, but the type string was not renamed with it, so it still
83
+ * leaks as the literal `--type canonical` / `type: "canonical"` value across
84
+ * the CLI and API (docs/api-reference.md documents it as-is because that is
85
+ * what the index actually produces). Renaming it requires touching
86
+ * shared/index.ts and shared/retrieval.ts together with this file, since all
87
+ * three must agree on the type string.
88
+ */
62
89
  export declare const DOC_TYPES: readonly ["claude", "findings", "notes", "reference", "skills", "summary", "task", "changelog", "canonical", "review-queue", "skill", "other"];
63
90
  export type DocType = (typeof DOC_TYPES)[number];
64
91
  export declare function capCache<K, V>(cache: Map<K, V>): void;
@@ -12,7 +12,7 @@ export const UNIVERSAL_TECH_TERMS_RE = /\b(Python|Rust|Go|Java|TypeScript|JavaSc
12
12
  * Additional fragment patterns beyond CamelCase and acronyms.
13
13
  * Each pattern has a named group so callers can identify the fragment type.
14
14
  */
15
- export const EXTRA_ENTITY_PATTERNS = [
15
+ export const EXTRA_FRAGMENT_PATTERNS = [
16
16
  // Semantic version numbers: v1.2.3, 2.0.0-beta.1
17
17
  { re: /\bv?\d+\.\d+\.\d+(?:-[a-zA-Z0-9.]+)?\b/g, label: "version" },
18
18
  // Environment variable keys: PHREN_*, NODE_ENV, etc. (2+ uppercase segments separated by _)
@@ -86,13 +86,40 @@ export function withDefaults(data, defaults) {
86
86
  }
87
87
  return merged;
88
88
  }
89
- /** All valid finding type tags — used for writes, search filters, and hook extraction */
90
- export const FINDING_TYPES = ["decision", "pitfall", "pattern", "tradeoff", "architecture", "bug"];
91
- /** Searchable finding tags (same set as FINDING_TYPES) */
92
- export const FINDING_TAGS = FINDING_TYPES;
93
- /** Canonical set of known observation tags — derived from FINDING_TYPES */
94
- export const KNOWN_OBSERVATION_TAGS = new Set(FINDING_TYPES);
95
- /** Document types in the FTS index */
89
+ /**
90
+ * Finding types offered as an explicit choice: add_finding's findingType
91
+ * param, promote_note --type, and the web/iOS type pickers. Deliberately the
92
+ * intersection of what used to be three disjoint lists (this enum, the decay
93
+ * table, and the auto-detector) — "tradeoff" and "architecture" were offered
94
+ * here but had no decay rule and no max-age, so they never actually worked.
95
+ * Legacy stores may still contain those two tags; reading/searching them as
96
+ * plain text still works, they just aren't offered or decay-tracked anymore.
97
+ */
98
+ export const FINDING_TYPES = ["decision", "pitfall", "pattern", "bug"];
99
+ /**
100
+ * Every finding tag phren can actually produce or needs to search for: the
101
+ * offered FINDING_TYPES above, plus tags autoDetectFindingType
102
+ * (content/learning.ts) writes on its own initiative — "workaround" and
103
+ * "context" — which aren't offered as an explicit pick but still need a
104
+ * decay rule (finding/lifecycle.ts's FINDING_TYPE_DECAY is typed against
105
+ * this exact set) and need to stay filterable via search_knowledge's `tag`
106
+ * param.
107
+ */
108
+ export const FINDING_TAGS = [...FINDING_TYPES, "workaround", "context"];
109
+ /** Canonical set of known finding tags for the "unknown tag" write-time warning — derived from FINDING_TAGS (not just FINDING_TYPES) so phren never flags its own auto-written workaround/context tags as unknown. */
110
+ export const KNOWN_OBSERVATION_TAGS = new Set(FINDING_TAGS);
111
+ /**
112
+ * Document types in the FTS index.
113
+ *
114
+ * "canonical" is `truths.md`'s type (see FILE_TYPE_MAP in shared/index.ts):
115
+ * the file was renamed from `canonical_memories.md` to `truths.md` in the
116
+ * 0.0.5 rename, but the type string was not renamed with it, so it still
117
+ * leaks as the literal `--type canonical` / `type: "canonical"` value across
118
+ * the CLI and API (docs/api-reference.md documents it as-is because that is
119
+ * what the index actually produces). Renaming it requires touching
120
+ * shared/index.ts and shared/retrieval.ts together with this file, since all
121
+ * three must agree on the type string.
122
+ */
96
123
  export const DOC_TYPES = ["claude", "findings", "notes", "reference", "skills", "summary", "task", "changelog", "canonical", "review-queue", "skill", "other"];
97
124
  // ── Cache eviction helper ────────────────────────────────────────────────────
98
125
  const CACHE_MAX = 1000;
@@ -16,7 +16,35 @@ export declare function homePath(...parts: string[]): string;
16
16
  export declare function expandHomePath(input: string): string;
17
17
  export declare function defaultPhrenPath(): string;
18
18
  export declare function rootManifestPath(phrenPath: string): string;
19
- export declare function atomicWriteText(filePath: string, content: string): void;
19
+ export interface AtomicWriteOptions {
20
+ /**
21
+ * POSIX mode for the written file, applied to the temp file *before* the
22
+ * rename. Callers writing secrets must pass this rather than chmod-ing after
23
+ * the fact: a post-rename chmod leaves the file readable at the default
24
+ * umask-derived mode (0644 on a stock install) for the whole write window,
25
+ * which is exactly long enough for another local user to read it.
26
+ */
27
+ mode?: number;
28
+ }
29
+ export declare function atomicWriteText(filePath: string, content: string, opts?: AtomicWriteOptions): void;
30
+ /**
31
+ * Create (or tighten) a directory that holds per-user private data — runtime
32
+ * logs, session transcripts, credential stores.
33
+ *
34
+ * Plain `fs.mkdirSync(dir, { recursive: true })` yields 0755 under the stock
35
+ * 0022 umask, which makes every file inside world-listable and world-readable
36
+ * on a shared machine. Passing `mode` to mkdirSync is not enough on its own:
37
+ * mkdirSync's mode applies only to directories it actually *creates*, so a
38
+ * directory that some earlier code path already made at 0755 keeps that mode
39
+ * forever. That is not hypothetical — `runtimeFile()` created `~/.phren/.runtime`
40
+ * with no mode long before `auth/profiles.ts` ever asked for 0700, so the
41
+ * credential directory shipped world-readable in practice.
42
+ *
43
+ * Only ever narrows: if the directory is already 0700 or tighter it is left
44
+ * alone. Best-effort — a chmod failure (foreign filesystem, Windows) must not
45
+ * break the caller, since the directory itself is usable either way.
46
+ */
47
+ export declare function ensurePrivateDir(dir: string): string;
20
48
  export declare function isInstallMode(value: unknown): value is InstallMode;
21
49
  export declare function readRootManifest(phrenPath: string): PhrenRootManifest | null;
22
50
  export declare function writeRootManifest(phrenPath: string, manifest: PhrenRootManifest): void;
@@ -31,6 +59,44 @@ export declare function runtimeDir(phrenPath: string): string;
31
59
  export declare function tryUnlink(filePath: string): void;
32
60
  export declare function sessionsDir(phrenPath: string): string;
33
61
  export declare function runtimeFile(phrenPath: string, name: string): string;
62
+ /**
63
+ * Per-user root for the FTS snapshot cache: `os.tmpdir()/phren-fts-<uid>`.
64
+ *
65
+ * Canonical definition of the path lives here, with every other phren path
66
+ * helper. `shared/index.ts` currently has its own private copy — see
67
+ * ensureFtsCacheRootPrivate() for why that matters and what still needs to
68
+ * change there.
69
+ */
70
+ export declare function ftsCacheRoot(): string;
71
+ /**
72
+ * Make the FTS snapshot cache root private, creating it if needed.
73
+ *
74
+ * The snapshot is a SQLite export of the *entire* indexed store — the full
75
+ * text of every finding, note, task and reference doc. It was being written
76
+ * as an 0644 file inside an 0755 directory:
77
+ *
78
+ * drwxr-xr-x $TMPDIR/phren-fts-501
79
+ * -rw-r--r-- $TMPDIR/phren-fts-501/<storeKey>/<hash>.db
80
+ *
81
+ * On macOS `os.tmpdir()` is a per-user `/var/folders/…/T` at 0700, which is
82
+ * the only reason this is not already a leak there. On Linux and WSL
83
+ * `os.tmpdir()` is `/tmp` — mode 1777, world-readable — so any local account
84
+ * can read another user's whole knowledge base. phren ships cross-platform on
85
+ * npm, so that is a live exposure, not a theoretical one.
86
+ *
87
+ * A 0700 root closes it completely: POSIX denies traversal into the directory,
88
+ * so the modes of the per-store subdirectory and the .db files inside it stop
89
+ * being reachable at all. Called once per process from the CLI and MCP-server
90
+ * entrypoints, which both creates it correctly on a clean machine and repairs
91
+ * the 0755 root on machines that already have one.
92
+ *
93
+ * Still worth doing for defence in depth, in the file that actually writes
94
+ * them: `shared/index.ts` should pass `{ recursive: true, mode: 0o700 }` to
95
+ * the `fs.mkdirSync(cacheDir, …)` calls and `{ mode: 0o600 }` to the
96
+ * `fs.writeFileSync(cacheFile, db.export())` calls. That file is owned by
97
+ * another change in flight, so it is reported rather than edited here.
98
+ */
99
+ export declare function ensureFtsCacheRootPrivate(): string;
34
100
  export declare function installPreferencesFile(phrenPath: string): string;
35
101
  export declare function runtimeHealthFile(phrenPath: string): string;
36
102
  export declare function shellStateFile(phrenPath: string): string;
@@ -58,7 +124,30 @@ export declare function appendIndexEvent(phrenPath: string, event: Record<string
58
124
  export declare function resolveFindingsPath(projectDir: string): string | undefined;
59
125
  export declare function listInvalidProjectDirs(phrenPath: string): string[];
60
126
  export declare function normalizeProjectNameForCreate(name: string): string;
127
+ /**
128
+ * The single source of truth for turning a source directory into a project
129
+ * slug. Previously copy-pasted at five call sites, which is how the same repo
130
+ * could end up registered twice under near-identical names.
131
+ *
132
+ * Runs of non-slug characters collapse to one hyphen and leading/trailing
133
+ * hyphens are trimmed, so `My.App`, `My..App` and `My App` all yield `my-app`
134
+ * instead of the old `my-app` / `my--app` / `my-app` split.
135
+ */
136
+ export declare function projectSlugFromPath(sourcePath: string): string;
137
+ /**
138
+ * Collapse a project name to the key used for duplicate detection: lowercase
139
+ * with every separator removed. `Max4LivePlugins`, `max4liveplugins` and
140
+ * `max4live-plugins` all map to `max4liveplugins`, so the second spelling of a
141
+ * repo can be recognized as the project that already exists.
142
+ */
143
+ export declare function canonicalProjectKey(name: string): string;
61
144
  export declare function findProjectNameCaseInsensitive(phrenPath: string, name: string): string | null;
145
+ /**
146
+ * Existing project directories whose name canonicalizes to the same key as
147
+ * `name` (see {@link canonicalProjectKey}). Exact matches are returned first so
148
+ * callers can prefer them.
149
+ */
150
+ export declare function findProjectNamesByCanonicalKey(phrenPath: string, name: string): string[];
62
151
  export declare function findArchivedProjectNameCaseInsensitive(phrenPath: string, name: string): string | null;
63
152
  export declare function getProjectDirs(phrenPath: string, profile?: string): string[];
64
153
  export declare function collectNativeMemoryFiles(): Array<{
@@ -32,11 +32,16 @@ export function defaultPhrenPath() {
32
32
  export function rootManifestPath(phrenPath) {
33
33
  return path.join(phrenPath, ROOT_MANIFEST_FILENAME);
34
34
  }
35
- export function atomicWriteText(filePath, content) {
35
+ export function atomicWriteText(filePath, content, opts = {}) {
36
36
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
37
37
  const tmpPath = `${filePath}.tmp-${crypto.randomUUID()}`;
38
- fs.writeFileSync(tmpPath, content);
38
+ fs.writeFileSync(tmpPath, content, opts.mode !== undefined ? { mode: opts.mode } : undefined);
39
39
  try {
40
+ // writeFileSync's mode is masked by umask, so re-assert it explicitly. The
41
+ // temp name is unguessable and freshly created, so this happens before any
42
+ // other process can have the file open under its final name.
43
+ if (opts.mode !== undefined && process.platform !== "win32")
44
+ fs.chmodSync(tmpPath, opts.mode);
40
45
  fs.renameSync(tmpPath, filePath);
41
46
  }
42
47
  catch (err) {
@@ -47,6 +52,37 @@ export function atomicWriteText(filePath, content) {
47
52
  throw err;
48
53
  }
49
54
  }
55
+ /**
56
+ * Create (or tighten) a directory that holds per-user private data — runtime
57
+ * logs, session transcripts, credential stores.
58
+ *
59
+ * Plain `fs.mkdirSync(dir, { recursive: true })` yields 0755 under the stock
60
+ * 0022 umask, which makes every file inside world-listable and world-readable
61
+ * on a shared machine. Passing `mode` to mkdirSync is not enough on its own:
62
+ * mkdirSync's mode applies only to directories it actually *creates*, so a
63
+ * directory that some earlier code path already made at 0755 keeps that mode
64
+ * forever. That is not hypothetical — `runtimeFile()` created `~/.phren/.runtime`
65
+ * with no mode long before `auth/profiles.ts` ever asked for 0700, so the
66
+ * credential directory shipped world-readable in practice.
67
+ *
68
+ * Only ever narrows: if the directory is already 0700 or tighter it is left
69
+ * alone. Best-effort — a chmod failure (foreign filesystem, Windows) must not
70
+ * break the caller, since the directory itself is usable either way.
71
+ */
72
+ export function ensurePrivateDir(dir) {
73
+ fs.mkdirSync(dir, { recursive: true });
74
+ if (process.platform === "win32")
75
+ return dir;
76
+ try {
77
+ const current = fs.statSync(dir).mode & 0o777;
78
+ if ((current & 0o077) !== 0)
79
+ fs.chmodSync(dir, 0o700);
80
+ }
81
+ catch {
82
+ // best-effort hardening; the directory is still usable
83
+ }
84
+ return dir;
85
+ }
50
86
  export function isInstallMode(value) {
51
87
  return value === "shared" || value === "project-local";
52
88
  }
@@ -238,15 +274,75 @@ export function tryUnlink(filePath) {
238
274
  export function sessionsDir(phrenPath) {
239
275
  return path.join(phrenPath, ".sessions");
240
276
  }
277
+ // `.runtime` holds debug.log, hook-errors.log, memory-usage.log,
278
+ // lookup-events.jsonl and the auth profile store — i.e. verbatim knowledge-base
279
+ // content plus plaintext API keys. It is per-user runtime state, never shared,
280
+ // so it gets 0700. Because ensurePrivateDir also tightens a directory that
281
+ // already exists, this repairs the 0755 `.runtime` that shipped installs have.
241
282
  const runtimeDirsMade = new Set();
242
283
  export function runtimeFile(phrenPath, name) {
243
284
  const dir = runtimeDir(phrenPath);
244
285
  if (!runtimeDirsMade.has(dir)) {
245
- fs.mkdirSync(dir, { recursive: true });
286
+ ensurePrivateDir(dir);
246
287
  runtimeDirsMade.add(dir);
247
288
  }
248
289
  return path.join(dir, name);
249
290
  }
291
+ /**
292
+ * Per-user root for the FTS snapshot cache: `os.tmpdir()/phren-fts-<uid>`.
293
+ *
294
+ * Canonical definition of the path lives here, with every other phren path
295
+ * helper. `shared/index.ts` currently has its own private copy — see
296
+ * ensureFtsCacheRootPrivate() for why that matters and what still needs to
297
+ * change there.
298
+ */
299
+ export function ftsCacheRoot() {
300
+ let userSuffix;
301
+ try {
302
+ userSuffix = String(os.userInfo().uid);
303
+ }
304
+ catch {
305
+ userSuffix = crypto.createHash("sha1").update(homeDir()).digest("hex").slice(0, 12);
306
+ }
307
+ return path.join(os.tmpdir(), `phren-fts-${userSuffix}`);
308
+ }
309
+ /**
310
+ * Make the FTS snapshot cache root private, creating it if needed.
311
+ *
312
+ * The snapshot is a SQLite export of the *entire* indexed store — the full
313
+ * text of every finding, note, task and reference doc. It was being written
314
+ * as an 0644 file inside an 0755 directory:
315
+ *
316
+ * drwxr-xr-x $TMPDIR/phren-fts-501
317
+ * -rw-r--r-- $TMPDIR/phren-fts-501/<storeKey>/<hash>.db
318
+ *
319
+ * On macOS `os.tmpdir()` is a per-user `/var/folders/…/T` at 0700, which is
320
+ * the only reason this is not already a leak there. On Linux and WSL
321
+ * `os.tmpdir()` is `/tmp` — mode 1777, world-readable — so any local account
322
+ * can read another user's whole knowledge base. phren ships cross-platform on
323
+ * npm, so that is a live exposure, not a theoretical one.
324
+ *
325
+ * A 0700 root closes it completely: POSIX denies traversal into the directory,
326
+ * so the modes of the per-store subdirectory and the .db files inside it stop
327
+ * being reachable at all. Called once per process from the CLI and MCP-server
328
+ * entrypoints, which both creates it correctly on a clean machine and repairs
329
+ * the 0755 root on machines that already have one.
330
+ *
331
+ * Still worth doing for defence in depth, in the file that actually writes
332
+ * them: `shared/index.ts` should pass `{ recursive: true, mode: 0o700 }` to
333
+ * the `fs.mkdirSync(cacheDir, …)` calls and `{ mode: 0o600 }` to the
334
+ * `fs.writeFileSync(cacheFile, db.export())` calls. That file is owned by
335
+ * another change in flight, so it is reported rather than edited here.
336
+ */
337
+ export function ensureFtsCacheRootPrivate() {
338
+ try {
339
+ return ensurePrivateDir(ftsCacheRoot());
340
+ }
341
+ catch {
342
+ // Never let cache hardening break startup; the cache itself is optional.
343
+ return ftsCacheRoot();
344
+ }
345
+ }
250
346
  export function installPreferencesFile(phrenPath) {
251
347
  return path.join(runtimeDir(phrenPath), "install-preferences.json");
252
348
  }
@@ -273,9 +369,10 @@ export function memoryUsageLogFile(phrenPath) {
273
369
  export function lookupEventsLogFile(phrenPath) {
274
370
  return path.join(runtimeDir(phrenPath), "lookup-events.jsonl");
275
371
  }
372
+ // `.sessions` holds session transcripts and per-session message artifacts —
373
+ // raw conversation content. Same treatment as `.runtime`.
276
374
  export function sessionMarker(phrenPath, name) {
277
- const dir = sessionsDir(phrenPath);
278
- fs.mkdirSync(dir, { recursive: true });
375
+ const dir = ensurePrivateDir(sessionsDir(phrenPath));
279
376
  return path.join(dir, name);
280
377
  }
281
378
  // Debug logging is best-effort and only writes when a phren root already exists.
@@ -371,6 +468,30 @@ export function listInvalidProjectDirs(phrenPath) {
371
468
  export function normalizeProjectNameForCreate(name) {
372
469
  return name.trim().toLowerCase();
373
470
  }
471
+ /**
472
+ * The single source of truth for turning a source directory into a project
473
+ * slug. Previously copy-pasted at five call sites, which is how the same repo
474
+ * could end up registered twice under near-identical names.
475
+ *
476
+ * Runs of non-slug characters collapse to one hyphen and leading/trailing
477
+ * hyphens are trimmed, so `My.App`, `My..App` and `My App` all yield `my-app`
478
+ * instead of the old `my-app` / `my--app` / `my-app` split.
479
+ */
480
+ export function projectSlugFromPath(sourcePath) {
481
+ return path.basename(path.resolve(sourcePath))
482
+ .toLowerCase()
483
+ .replace(/[^a-z0-9_-]+/g, "-")
484
+ .replace(/^-+|-+$/g, "");
485
+ }
486
+ /**
487
+ * Collapse a project name to the key used for duplicate detection: lowercase
488
+ * with every separator removed. `Max4LivePlugins`, `max4liveplugins` and
489
+ * `max4live-plugins` all map to `max4liveplugins`, so the second spelling of a
490
+ * repo can be recognized as the project that already exists.
491
+ */
492
+ export function canonicalProjectKey(name) {
493
+ return name.trim().toLowerCase().replace(/[\s_-]+/g, "");
494
+ }
374
495
  export function findProjectNameCaseInsensitive(phrenPath, name) {
375
496
  const needle = name.toLowerCase();
376
497
  try {
@@ -387,6 +508,30 @@ export function findProjectNameCaseInsensitive(phrenPath, name) {
387
508
  }
388
509
  return null;
389
510
  }
511
+ /**
512
+ * Existing project directories whose name canonicalizes to the same key as
513
+ * `name` (see {@link canonicalProjectKey}). Exact matches are returned first so
514
+ * callers can prefer them.
515
+ */
516
+ export function findProjectNamesByCanonicalKey(phrenPath, name) {
517
+ const needle = canonicalProjectKey(name);
518
+ if (!needle)
519
+ return [];
520
+ const matches = [];
521
+ try {
522
+ for (const entry of fs.readdirSync(phrenPath, { withFileTypes: true })) {
523
+ if (!isProjectDirEntry(entry))
524
+ continue;
525
+ if (canonicalProjectKey(entry.name) === needle)
526
+ matches.push(entry.name);
527
+ }
528
+ }
529
+ catch (err) {
530
+ if ((process.env.PHREN_DEBUG))
531
+ stderrLog(`findProjectNamesByCanonicalKey: ${errorMessage(err)}`);
532
+ }
533
+ return matches.sort((a, b) => (a === name ? -1 : b === name ? 1 : a.localeCompare(b)));
534
+ }
390
535
  export function findArchivedProjectNameCaseInsensitive(phrenPath, name) {
391
536
  const needle = name.toLowerCase();
392
537
  try {