@phren/cli 0.1.40 → 0.1.42

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 (119) hide show
  1. package/dist/auth/profiles.js +59 -5
  2. package/dist/cli/actions.js +12 -16
  3. package/dist/cli/config-access.js +8 -1
  4. package/dist/cli/extract.d.ts +27 -1
  5. package/dist/cli/extract.js +244 -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/namespaces-utils.js +1 -1
  11. package/dist/cli/session-git.d.ts +18 -0
  12. package/dist/cli/session-git.js +47 -0
  13. package/dist/cli/session-start.js +2 -2
  14. package/dist/cli/session-stop.d.ts +11 -0
  15. package/dist/cli/session-stop.js +141 -33
  16. package/dist/cli/session-tool-hook.js +17 -5
  17. package/dist/cli-registry.d.ts +1 -1
  18. package/dist/cli-registry.js +1 -0
  19. package/dist/content/archive.js +3 -2
  20. package/dist/content/dedup.d.ts +1 -4
  21. package/dist/content/dedup.js +11 -66
  22. package/dist/content/learning.d.ts +20 -2
  23. package/dist/content/learning.js +26 -7
  24. package/dist/content/quality.d.ts +23 -0
  25. package/dist/content/quality.js +123 -0
  26. package/dist/content/secrets.d.ts +52 -0
  27. package/dist/content/secrets.js +196 -0
  28. package/dist/data/access.d.ts +56 -2
  29. package/dist/data/access.js +255 -32
  30. package/dist/data/tasks.js +46 -6
  31. package/dist/entrypoint.js +5 -1
  32. package/dist/finding/impact.js +170 -43
  33. package/dist/finding/lifecycle.d.ts +19 -2
  34. package/dist/finding/lifecycle.js +18 -5
  35. package/dist/git-worktree.d.ts +19 -0
  36. package/dist/git-worktree.js +117 -0
  37. package/dist/governance/policy.d.ts +84 -4
  38. package/dist/governance/policy.js +213 -17
  39. package/dist/governance/rbac.d.ts +8 -0
  40. package/dist/governance/rbac.js +26 -0
  41. package/dist/hooks.d.ts +20 -0
  42. package/dist/hooks.js +113 -3
  43. package/dist/index.js +5 -1
  44. package/dist/init/guard-globals.d.ts +20 -0
  45. package/dist/init/guard-globals.js +72 -6
  46. package/dist/init/init-configure.js +6 -6
  47. package/dist/init/init.js +10 -6
  48. package/dist/init/setup.d.ts +4 -3
  49. package/dist/init/setup.js +120 -16
  50. package/dist/init/store-gitignore.d.ts +29 -0
  51. package/dist/init/store-gitignore.js +48 -0
  52. package/dist/link/doctor.js +86 -20
  53. package/dist/phren-core.d.ts +35 -8
  54. package/dist/phren-core.js +35 -8
  55. package/dist/phren-paths.d.ts +90 -1
  56. package/dist/phren-paths.js +150 -5
  57. package/dist/proactivity.js +1 -1
  58. package/dist/project-config.js +3 -2
  59. package/dist/project-topics.js +13 -12
  60. package/dist/shared/data-utils.js +13 -3
  61. package/dist/shared/embedding-cache.d.ts +16 -0
  62. package/dist/shared/embedding-cache.js +24 -0
  63. package/dist/shared/fragment-graph.js +10 -0
  64. package/dist/shared/index.d.ts +6 -0
  65. package/dist/shared/index.js +523 -138
  66. package/dist/shared/ollama.d.ts +14 -2
  67. package/dist/shared/ollama.js +84 -5
  68. package/dist/shared/retrieval.d.ts +22 -1
  69. package/dist/shared/retrieval.js +30 -1
  70. package/dist/shared/search-fallback.js +15 -3
  71. package/dist/shared/vector-index.d.ts +20 -1
  72. package/dist/shared/vector-index.js +18 -4
  73. package/dist/shared.d.ts +1 -1
  74. package/dist/shared.js +1 -1
  75. package/dist/status.js +18 -1
  76. package/dist/store-registry.d.ts +22 -0
  77. package/dist/store-registry.js +36 -3
  78. package/dist/store-routing.d.ts +8 -0
  79. package/dist/store-routing.js +23 -1
  80. package/dist/task/lifecycle.js +31 -0
  81. package/dist/tools/config.js +19 -9
  82. package/dist/tools/data.js +1 -1
  83. package/dist/tools/extract-facts.js +3 -2
  84. package/dist/tools/extract.js +2 -2
  85. package/dist/tools/finding.js +20 -8
  86. package/dist/tools/graph.js +9 -1
  87. package/dist/tools/memory.js +1 -1
  88. package/dist/tools/notes.js +3 -3
  89. package/dist/tools/ops.js +19 -18
  90. package/dist/tools/search.js +2 -2
  91. package/dist/tools/session.js +2 -2
  92. package/dist/tools/tasks.js +2 -2
  93. package/dist/tools/types.d.ts +32 -2
  94. package/dist/tools/types.js +41 -8
  95. package/dist/ui/scripts.js +2 -2
  96. package/dist/ui/server.js +7 -6
  97. package/dist/utils-fts.js +3 -2
  98. package/dist/utils-paths.d.ts +1 -0
  99. package/dist/utils-paths.js +1 -1
  100. package/dist/utils.d.ts +1 -1
  101. package/dist/utils.js +1 -1
  102. package/package.json +1 -1
  103. package/dist/cli-hooks-git.d.ts +0 -50
  104. package/dist/cli-hooks-git.js +0 -288
  105. package/starter/my-api/.claude/skills/README.md +0 -7
  106. package/starter/my-api/CLAUDE.md +0 -33
  107. package/starter/my-api/FINDINGS.md +0 -9
  108. package/starter/my-api/summary.md +0 -7
  109. package/starter/my-api/tasks.md +0 -7
  110. package/starter/my-first-project/.claude/skills/README.md +0 -7
  111. package/starter/my-first-project/CLAUDE.md +0 -49
  112. package/starter/my-first-project/FINDINGS.md +0 -24
  113. package/starter/my-first-project/summary.md +0 -11
  114. package/starter/my-first-project/tasks.md +0 -25
  115. package/starter/my-frontend/.claude/skills/README.md +0 -7
  116. package/starter/my-frontend/CLAUDE.md +0 -33
  117. package/starter/my-frontend/FINDINGS.md +0 -9
  118. package/starter/my-frontend/summary.md +0 -7
  119. package/starter/my-frontend/tasks.md +0 -7
@@ -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 {
@@ -7,7 +7,7 @@ import { getWorkflowPolicy } from "./governance/policy.js";
7
7
  export const PROACTIVITY_LEVELS = ["high", "medium", "low"];
8
8
  const DEFAULT_PROACTIVITY_LEVEL = "high";
9
9
  const EXPLICIT_FINDING_SIGNAL_PATTERN = /\b(add finding|worth remembering)\b/i;
10
- const EXPLICIT_FINDING_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\]/i;
10
+ const EXPLICIT_FINDING_TAG_PATTERN = /\[(pitfall|decision|pattern|bug|workaround|context)\]/i;
11
11
  const EXPLICIT_TASK_SIGNAL_PATTERN = /\b(?:add(?:\s+(?:this|that|it))?\s+(?:to\s+(?:the\s+)?)?(?:task|todo(?:\s+list)?|task(?:\s+list)?)|add\s+(?:a\s+)?task|put(?:\s+(?:this|that|it))?\s+(?:in|on)\s+(?:the\s+)?(?:task|todo(?:\s+list)?|task(?:\s+list)?))\b/i;
12
12
  export function parseProactivityLevel(raw) {
13
13
  if (!raw)
@@ -4,7 +4,8 @@ import * as path from "path";
4
4
  import * as yaml from "js-yaml";
5
5
  import { readInstallPreferences } from "./init/preferences.js";
6
6
  import { debugLog } from "./shared.js";
7
- import { errorMessage, safeProjectPath } from "./utils.js";
7
+ import { errorMessage } from "./utils.js";
8
+ import { storeAwareProjectPath } from "./store-routing.js";
8
9
  import { withFileLock } from "./shared/governance.js";
9
10
  export const PROJECT_OWNERSHIP_MODES = ["phren-managed", "detached", "repo-managed"];
10
11
  export const PROJECT_HOOK_EVENTS = ["UserPromptSubmit", "Stop", "SessionStart", "PostToolUse"];
@@ -25,7 +26,7 @@ export function projectConfigPath(phrenPath, project) {
25
26
  return path.join(phrenPath, project, "phren.project.yaml");
26
27
  }
27
28
  function resolveProjectConfigPath(phrenPath, project) {
28
- return safeProjectPath(phrenPath, project, "phren.project.yaml");
29
+ return storeAwareProjectPath(phrenPath, project, "phren.project.yaml");
29
30
  }
30
31
  function writeProjectConfigFile(configPath, next) {
31
32
  fs.mkdirSync(path.dirname(configPath), { recursive: true });
@@ -3,7 +3,8 @@ import * as fs from "fs";
3
3
  import * as path from "path";
4
4
  import { debugLog } from "./shared.js";
5
5
  import { withFileLock } from "./shared/governance.js";
6
- import { STOP_WORDS, errorMessage, extractKeywords, isValidProjectName, safeProjectPath } from "./utils.js";
6
+ import { STOP_WORDS, errorMessage, extractKeywords, isValidProjectName } from "./utils.js";
7
+ import { storeAwareProjectPath } from "./store-routing.js";
7
8
  import { walkDirectory } from "./shared/data-utils.js";
8
9
  import { FINDINGS_FILENAME } from "./data/access.js";
9
10
  const TOPIC_CONFIG_FILENAME = "topic-config.json";
@@ -381,16 +382,16 @@ function ensureGeneralTopic(topics) {
381
382
  return [...topics, { ...GENERAL_TOPIC, keywords: [...GENERAL_TOPIC.keywords] }];
382
383
  }
383
384
  function topicConfigPath(phrenPath, project) {
384
- return safeProjectPath(phrenPath, project, TOPIC_CONFIG_FILENAME);
385
+ return storeAwareProjectPath(phrenPath, project, TOPIC_CONFIG_FILENAME);
385
386
  }
386
387
  function projectDirPath(phrenPath, project) {
387
- return safeProjectPath(phrenPath, project);
388
+ return storeAwareProjectPath(phrenPath, project);
388
389
  }
389
390
  function topicReferenceRelativePath(slug) {
390
391
  return path.posix.join("reference", "topics", `${slug}.md`);
391
392
  }
392
393
  export function topicReferencePath(phrenPath, project, slug) {
393
- return safeProjectPath(phrenPath, project, "reference", "topics", `${normalizeTopicSlug(slug)}.md`);
394
+ return storeAwareProjectPath(phrenPath, project, "reference", "topics", `${normalizeTopicSlug(slug)}.md`);
394
395
  }
395
396
  function readJsonFile(filePath) {
396
397
  try {
@@ -412,14 +413,14 @@ function countByTerm(terms) {
412
413
  function readTopicInputContent(phrenPath, project) {
413
414
  const parts = [];
414
415
  for (const file of ["CLAUDE.md", FINDINGS_FILENAME]) {
415
- const filePath = safeProjectPath(phrenPath, project, file);
416
+ const filePath = storeAwareProjectPath(phrenPath, project, file);
416
417
  if (!filePath || !fs.existsSync(filePath))
417
418
  continue;
418
419
  const content = fs.readFileSync(filePath, "utf8").trim();
419
420
  if (content)
420
421
  parts.push(content);
421
422
  }
422
- const referenceDir = safeProjectPath(phrenPath, project, "reference");
423
+ const referenceDir = storeAwareProjectPath(phrenPath, project, "reference");
423
424
  if (referenceDir && fs.existsSync(referenceDir)) {
424
425
  for (const filePath of readReferenceMarkdownFiles(referenceDir)) {
425
426
  try {
@@ -834,7 +835,7 @@ export function listProjectReferenceDocs(phrenPath, project, topics) {
834
835
  if (!projectDir)
835
836
  return { topicDocs: [], otherDocs: [] };
836
837
  const topicDocs = listProjectTopicDocs(phrenPath, project, topics);
837
- const referenceDir = safeProjectPath(phrenPath, project, "reference");
838
+ const referenceDir = storeAwareProjectPath(phrenPath, project, "reference");
838
839
  if (!referenceDir || !fs.existsSync(referenceDir))
839
840
  return { topicDocs, otherDocs: [] };
840
841
  const otherDocs = [];
@@ -857,7 +858,7 @@ export function listProjectReferenceDocs(phrenPath, project, topics) {
857
858
  }
858
859
  function listLegacyTopicDocs(phrenPath, project) {
859
860
  const projectDir = projectDirPath(phrenPath, project);
860
- const referenceDir = safeProjectPath(phrenPath, project, "reference");
861
+ const referenceDir = storeAwareProjectPath(phrenPath, project, "reference");
861
862
  if (!projectDir || !referenceDir || !fs.existsSync(referenceDir))
862
863
  return [];
863
864
  const files = fs.readdirSync(referenceDir, { withFileTypes: true })
@@ -898,7 +899,7 @@ function tokenizeSuggestionTerms(text) {
898
899
  function collectSuggestionCorpus(phrenPath, project) {
899
900
  const parts = [];
900
901
  for (const file of ["CLAUDE.md", "summary.md", FINDINGS_FILENAME]) {
901
- const filePath = safeProjectPath(phrenPath, project, file);
902
+ const filePath = storeAwareProjectPath(phrenPath, project, file);
902
903
  if (!filePath || !fs.existsSync(filePath))
903
904
  continue;
904
905
  const content = fs.readFileSync(filePath, "utf8");
@@ -1030,10 +1031,10 @@ function resolveReferenceContentPath(phrenPath, project, file) {
1030
1031
  return null;
1031
1032
  if (!file.endsWith(".md"))
1032
1033
  return null;
1033
- const filePath = safeProjectPath(phrenPath, project, file);
1034
+ const filePath = storeAwareProjectPath(phrenPath, project, file);
1034
1035
  if (!filePath)
1035
1036
  return null;
1036
- const referenceRoot = safeProjectPath(phrenPath, project, "reference");
1037
+ const referenceRoot = storeAwareProjectPath(phrenPath, project, "reference");
1037
1038
  if (!referenceRoot)
1038
1039
  return null;
1039
1040
  const normalizedRoot = referenceRoot + path.sep;
@@ -1051,7 +1052,7 @@ export function readReferenceContent(phrenPath, project, file) {
1051
1052
  }
1052
1053
  export function reclassifyLegacyTopicDocs(phrenPath, project) {
1053
1054
  const { topics } = readProjectTopics(phrenPath, project);
1054
- const referenceDir = safeProjectPath(phrenPath, project, "reference");
1055
+ const referenceDir = storeAwareProjectPath(phrenPath, project, "reference");
1055
1056
  if (!referenceDir || !fs.existsSync(referenceDir))
1056
1057
  return { movedFiles: 0, movedEntries: 0, skipped: [] };
1057
1058
  const skipped = [];
@@ -1,8 +1,9 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
- import { phrenErr, PhrenError, phrenOk, } from "../shared.js";
3
+ import { phrenErr, PhrenError, phrenOk, parsePhrenErrorCode, } from "../shared.js";
4
4
  import { withFileLock as withFileLockRaw } from "./governance.js";
5
5
  import { isValidProjectName, safeProjectPath, errorMessage } from "../utils.js";
6
+ import { resolveProject } from "../store-routing.js";
6
7
  export function withSafeLock(filePath, fn) {
7
8
  try {
8
9
  return withFileLockRaw(filePath, fn);
@@ -46,8 +47,17 @@ export function ensureProject(phrenPath, project) {
46
47
  const dir = safeProjectPath(phrenPath, project);
47
48
  if (!dir)
48
49
  return phrenErr(`Project name "${project}" is not valid. Use lowercase letters, numbers, and hyphens (e.g. "my-project").`, PhrenError.INVALID_PROJECT_NAME);
49
- if (!fs.existsSync(dir)) {
50
+ if (fs.existsSync(dir))
51
+ return phrenOk(dir);
52
+ // Not in the primary store — the project may live in a registered secondary store.
53
+ try {
54
+ return phrenOk(resolveProject(phrenPath, project).projectDir);
55
+ }
56
+ catch (err) {
57
+ const msg = errorMessage(err);
58
+ if (parsePhrenErrorCode(msg) === PhrenError.VALIDATION_ERROR) {
59
+ return phrenErr(msg.replace(/^[A-Z_]+:\s*/, ""), PhrenError.VALIDATION_ERROR);
60
+ }
50
61
  return phrenErr(`No project "${project}" found. Add it with 'cd ~/your-project && phren add'.`, PhrenError.PROJECT_NOT_FOUND);
51
62
  }
52
- return phrenOk(dir);
53
63
  }
@@ -6,14 +6,30 @@ export interface EmbeddingCoverage {
6
6
  missingPct: number;
7
7
  state: "empty" | "cold" | "warming" | "warm";
8
8
  }
9
+ /**
10
+ * `[mtimeMs, size]` of the embeddings.json the in-memory map was last built
11
+ * from. Derived caches (the LSH vector index) stamp *this*, not a fresh stat of
12
+ * the file, so an index can never claim to describe bytes it never saw.
13
+ */
14
+ export interface EmbeddingSourceMarker {
15
+ mtimeMs: number;
16
+ size: number;
17
+ }
9
18
  export declare class EmbeddingCache {
10
19
  private phrenPath;
11
20
  private cache;
12
21
  private dirty;
13
22
  private dirtyUpserts;
14
23
  private dirtyDeletes;
24
+ private source;
15
25
  constructor(phrenPath: string);
16
26
  load(): Promise<void>;
27
+ /**
28
+ * Marker for the embeddings.json revision this in-memory map reflects, or
29
+ * null when it was never loaded from a file. Pass it to anything that
30
+ * persists a derived view of `getAllEntries()`.
31
+ */
32
+ sourceMarker(): EmbeddingSourceMarker | null;
17
33
  get(docPath: string, model: string): number[] | null;
18
34
  set(docPath: string, model: string, vec: number[]): void;
19
35
  delete(docPath: string): void;