@phren/cli 0.1.13 → 0.1.15

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 (75) hide show
  1. package/README.md +1 -1
  2. package/dist/capabilities/cli.js +1 -1
  3. package/dist/capabilities/mcp.js +1 -1
  4. package/dist/capabilities/vscode.js +1 -1
  5. package/dist/capabilities/web-ui.js +1 -1
  6. package/dist/cli/extract.js +2 -1
  7. package/dist/cli/govern.js +3 -2
  8. package/dist/cli/hooks-session.d.ts +18 -36
  9. package/dist/cli/hooks-session.js +21 -1482
  10. package/dist/cli/namespaces-findings.d.ts +1 -0
  11. package/dist/cli/namespaces-findings.js +208 -0
  12. package/dist/cli/namespaces-profile.d.ts +1 -0
  13. package/dist/cli/namespaces-profile.js +76 -0
  14. package/dist/cli/namespaces-projects.d.ts +1 -0
  15. package/dist/cli/namespaces-projects.js +371 -0
  16. package/dist/cli/namespaces-review.d.ts +1 -0
  17. package/dist/cli/namespaces-review.js +45 -0
  18. package/dist/cli/namespaces-skills.d.ts +4 -0
  19. package/dist/cli/namespaces-skills.js +550 -0
  20. package/dist/cli/namespaces-store.d.ts +2 -0
  21. package/dist/cli/namespaces-store.js +367 -0
  22. package/dist/cli/namespaces-tasks.d.ts +1 -0
  23. package/dist/cli/namespaces-tasks.js +369 -0
  24. package/dist/cli/namespaces-utils.d.ts +4 -0
  25. package/dist/cli/namespaces-utils.js +47 -0
  26. package/dist/cli/namespaces.d.ts +7 -11
  27. package/dist/cli/namespaces.js +8 -2011
  28. package/dist/cli/ops.js +2 -2
  29. package/dist/cli/session-background.d.ts +3 -0
  30. package/dist/cli/session-background.js +176 -0
  31. package/dist/cli/session-git.d.ts +17 -0
  32. package/dist/cli/session-git.js +181 -0
  33. package/dist/cli/session-metrics.d.ts +2 -0
  34. package/dist/cli/session-metrics.js +67 -0
  35. package/dist/cli/session-start.d.ts +3 -0
  36. package/dist/cli/session-start.js +290 -0
  37. package/dist/cli/session-stop.d.ts +8 -0
  38. package/dist/cli/session-stop.js +468 -0
  39. package/dist/cli/session-tool-hook.d.ts +18 -0
  40. package/dist/cli/session-tool-hook.js +376 -0
  41. package/dist/cli/team.js +7 -5
  42. package/dist/cli-hooks-session-handlers.js +2 -1
  43. package/dist/content/archive.js +2 -1
  44. package/dist/content/dedup.js +6 -5
  45. package/dist/content/learning.js +3 -2
  46. package/dist/content/validate.js +2 -1
  47. package/dist/core/project.js +2 -1
  48. package/dist/data/access.d.ts +1 -0
  49. package/dist/data/access.js +11 -10
  50. package/dist/finding/journal.js +2 -1
  51. package/dist/finding/lifecycle.js +2 -1
  52. package/dist/governance/policy.d.ts +2 -0
  53. package/dist/governance/policy.js +2 -2
  54. package/dist/hooks.js +38 -2
  55. package/dist/init/init-uninstall.js +2 -1
  56. package/dist/init/setup.js +5 -4
  57. package/dist/init-uninstall.js +2 -1
  58. package/dist/link/checksums.js +2 -1
  59. package/dist/link/context.js +2 -1
  60. package/dist/link/doctor.js +4 -3
  61. package/dist/link/link.js +2 -1
  62. package/dist/phren-paths.js +3 -2
  63. package/dist/profile-store.d.ts +1 -0
  64. package/dist/profile-store.js +15 -16
  65. package/dist/project-topics.js +4 -3
  66. package/dist/shell/input.js +3 -3
  67. package/dist/status.js +2 -2
  68. package/dist/tools/data.js +4 -4
  69. package/dist/tools/extract.js +2 -1
  70. package/dist/tools/finding.js +9 -9
  71. package/dist/tools/search.js +4 -4
  72. package/dist/tools/session.js +2 -2
  73. package/dist/ui/data.js +6 -5
  74. package/dist/ui/server.js +3 -3
  75. package/package.json +1 -1
@@ -0,0 +1,376 @@
1
+ /**
2
+ * PostToolUse hook handler and context hook handler.
3
+ * Extracted from hooks-session.ts for modularity.
4
+ */
5
+ import * as fs from "fs";
6
+ import * as path from "path";
7
+ import { buildHookContext, debugLog, appendAuditLog, runtimeFile, sessionMarker, getPhrenPath, getWorkflowPolicy, appendReviewQueue, getProactivityLevelForFindings, FINDING_SENSITIVITY_CONFIG, isProjectHookEnabled, errorMessage, detectProject, } from "./hooks-context.js";
8
+ import { logger } from "../logger.js";
9
+ import { buildIndex, queryRows, } from "../shared/index.js";
10
+ import { filterTaskByPriority } from "../shared/retrieval.js";
11
+ // ── PostToolUse hook ─────────────────────────────────────────────────────────
12
+ const INTERESTING_TOOLS = new Set(["Read", "Write", "Edit", "Bash", "Glob", "Grep"]);
13
+ const COOLDOWN_MS = parseInt(process.env.PHREN_AUTOCAPTURE_COOLDOWN_MS ?? "30000", 10);
14
+ function getSessionCap() {
15
+ if (process.env.PHREN_AUTOCAPTURE_SESSION_CAP) {
16
+ return parseInt(process.env.PHREN_AUTOCAPTURE_SESSION_CAP, 10);
17
+ }
18
+ try {
19
+ const policy = getWorkflowPolicy(getPhrenPath());
20
+ const sensitivity = policy.findingSensitivity ?? "balanced";
21
+ return FINDING_SENSITIVITY_CONFIG[sensitivity]?.sessionCap ?? 10;
22
+ }
23
+ catch {
24
+ return 10;
25
+ }
26
+ }
27
+ function flattenToolResponseText(value, maxChars = 4000) {
28
+ if (typeof value === "string")
29
+ return value;
30
+ const queue = [value];
31
+ const parts = [];
32
+ let length = 0;
33
+ while (queue.length > 0 && length < maxChars) {
34
+ const current = queue.shift();
35
+ if (typeof current === "string") {
36
+ const trimmed = current.trim();
37
+ if (!trimmed)
38
+ continue;
39
+ parts.push(trimmed);
40
+ length += trimmed.length + 1;
41
+ continue;
42
+ }
43
+ if (Array.isArray(current)) {
44
+ queue.unshift(...current);
45
+ continue;
46
+ }
47
+ if (current && typeof current === "object") {
48
+ queue.unshift(...Object.values(current));
49
+ }
50
+ }
51
+ if (parts.length > 0)
52
+ return parts.join("\n").slice(0, maxChars);
53
+ return JSON.stringify(value ?? "").slice(0, maxChars);
54
+ }
55
+ export async function handleHookTool() {
56
+ const ctx = buildHookContext();
57
+ if (!ctx.hooksEnabled) {
58
+ process.exit(0);
59
+ }
60
+ try {
61
+ const start = Date.now();
62
+ let raw = "";
63
+ if (!process.stdin.isTTY) {
64
+ try {
65
+ raw = fs.readFileSync(0, "utf-8");
66
+ }
67
+ catch (err) {
68
+ logger.debug("hooks-session", `hookTool stdinRead: ${errorMessage(err)}`);
69
+ process.exit(0);
70
+ }
71
+ }
72
+ let data;
73
+ try {
74
+ data = JSON.parse(raw);
75
+ }
76
+ catch (err) {
77
+ logger.debug("hooks-session", `hookTool stdinParse: ${errorMessage(err)}`);
78
+ process.exit(0);
79
+ }
80
+ const toolName = String(data.tool_name ?? data.tool ?? "");
81
+ if (!INTERESTING_TOOLS.has(toolName)) {
82
+ process.exit(0);
83
+ }
84
+ const sessionId = data.session_id;
85
+ const input = (data.tool_input ?? {});
86
+ const entry = {
87
+ at: new Date().toISOString(),
88
+ session_id: sessionId,
89
+ tool: toolName,
90
+ };
91
+ if (toolName === "Read" || toolName === "Write" || toolName === "Edit") {
92
+ const filePath = input.file_path ?? input.path ?? undefined;
93
+ if (filePath)
94
+ entry.file = String(filePath);
95
+ }
96
+ else if (toolName === "Bash") {
97
+ const cmd = input.command ?? undefined;
98
+ if (cmd)
99
+ entry.command = String(cmd).slice(0, 200);
100
+ }
101
+ else if (toolName === "Glob") {
102
+ const pattern = input.pattern ?? undefined;
103
+ if (pattern)
104
+ entry.file = String(pattern);
105
+ }
106
+ else if (toolName === "Grep") {
107
+ const pattern = input.pattern ?? undefined;
108
+ const searchPath = input.path ?? undefined;
109
+ if (pattern)
110
+ entry.command = `grep ${pattern}${searchPath ? ` in ${searchPath}` : ""}`.slice(0, 200);
111
+ }
112
+ const responseStr = flattenToolResponseText(data.tool_response ?? "");
113
+ if (/(error|exception|failed|no such file|ENOENT)/i.test(responseStr)) {
114
+ entry.error = responseStr.slice(0, 300);
115
+ }
116
+ const cwd = (data.cwd ?? input.cwd ?? undefined);
117
+ let activeProject = cwd ? detectProject(ctx.phrenPath, cwd, ctx.profile) : null;
118
+ if (!isProjectHookEnabled(ctx.phrenPath, activeProject, "PostToolUse")) {
119
+ appendAuditLog(ctx.phrenPath, "hook_tool", `status=project_disabled project=${activeProject}`);
120
+ process.exit(0);
121
+ }
122
+ try {
123
+ const logFile = runtimeFile(ctx.phrenPath, "tool-log.jsonl");
124
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
125
+ fs.appendFileSync(logFile, JSON.stringify(entry) + "\n");
126
+ }
127
+ catch (err) {
128
+ logger.debug("hooks-session", `hookTool toolLog: ${errorMessage(err)}`);
129
+ }
130
+ const cooldownFile = runtimeFile(ctx.phrenPath, "hook-tool-cooldown");
131
+ try {
132
+ if (fs.existsSync(cooldownFile)) {
133
+ const age = Date.now() - fs.statSync(cooldownFile).mtimeMs;
134
+ if (age < COOLDOWN_MS) {
135
+ debugLog(`hook-tool: cooldown active (${Math.round(age / 1000)}s < ${Math.round(COOLDOWN_MS / 1000)}s), skipping extraction`);
136
+ activeProject = null;
137
+ }
138
+ }
139
+ }
140
+ catch (err) {
141
+ logger.debug("hooks-session", `hookTool cooldownStat: ${errorMessage(err)}`);
142
+ }
143
+ if (activeProject && sessionId) {
144
+ try {
145
+ const capFile = sessionMarker(ctx.phrenPath, `tool-findings-${sessionId}`);
146
+ let count = 0;
147
+ if (fs.existsSync(capFile)) {
148
+ count = Number.parseInt(fs.readFileSync(capFile, "utf8").trim(), 10) || 0;
149
+ }
150
+ const sessionCap = getSessionCap();
151
+ if (count >= sessionCap) {
152
+ debugLog(`hook-tool: session cap reached (${count}/${sessionCap}), skipping extraction`);
153
+ activeProject = null;
154
+ }
155
+ }
156
+ catch (err) {
157
+ logger.debug("hooks-session", `hookTool sessionCapCheck: ${errorMessage(err)}`);
158
+ }
159
+ }
160
+ const findingsLevelForTool = getProactivityLevelForFindings(ctx.phrenPath);
161
+ if (activeProject && findingsLevelForTool !== "low") {
162
+ try {
163
+ const candidates = filterToolFindingsForProactivity(extractToolFindings(toolName, input, responseStr), findingsLevelForTool);
164
+ for (const { text, confidence } of candidates) {
165
+ appendReviewQueue(ctx.phrenPath, activeProject, "Review", [text]);
166
+ debugLog(`hook-tool: queued candidate for review (conf=${confidence}): ${text.slice(0, 60)}`);
167
+ }
168
+ if (candidates.length > 0) {
169
+ try {
170
+ fs.writeFileSync(cooldownFile, Date.now().toString());
171
+ }
172
+ catch (err) {
173
+ logger.debug("hooks-session", `hookTool cooldownWrite: ${errorMessage(err)}`);
174
+ }
175
+ if (sessionId) {
176
+ try {
177
+ const capFile = sessionMarker(ctx.phrenPath, `tool-findings-${sessionId}`);
178
+ let count = 0;
179
+ try {
180
+ count = Number.parseInt(fs.readFileSync(capFile, "utf8").trim(), 10) || 0;
181
+ }
182
+ catch (err) {
183
+ logger.debug("hooks-session", `hookTool capFileRead: ${errorMessage(err)}`);
184
+ }
185
+ count += candidates.length;
186
+ fs.writeFileSync(capFile, count.toString());
187
+ }
188
+ catch (err) {
189
+ logger.debug("hooks-session", `hookTool capFileWrite: ${errorMessage(err)}`);
190
+ }
191
+ }
192
+ }
193
+ }
194
+ catch (err) {
195
+ debugLog(`hook-tool: finding extraction failed: ${errorMessage(err)}`);
196
+ }
197
+ }
198
+ else if (activeProject) {
199
+ debugLog("hook-tool: skipped because findings proactivity is low");
200
+ }
201
+ const elapsed = Date.now() - start;
202
+ debugLog(`hook-tool: ${toolName} logged in ${elapsed}ms`);
203
+ process.exit(0);
204
+ }
205
+ catch (err) {
206
+ debugLog(`hook-tool: unhandled error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
207
+ process.exit(0);
208
+ }
209
+ }
210
+ const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\]\s*(.+)/i;
211
+ export function filterToolFindingsForProactivity(candidates, level = getProactivityLevelForFindings(getPhrenPath())) {
212
+ if (level === "high")
213
+ return candidates;
214
+ if (level === "low")
215
+ return [];
216
+ return candidates.filter((candidate) => candidate.explicit === true);
217
+ }
218
+ export function extractToolFindings(toolName, input, responseStr) {
219
+ const candidates = [];
220
+ const changedContent = (toolName === "Edit" || toolName === "Write")
221
+ ? String(input.new_string ?? input.content ?? "")
222
+ : "";
223
+ const explicitSource = changedContent || responseStr;
224
+ const tagMatches = explicitSource.matchAll(new RegExp(EXPLICIT_TAG_PATTERN.source, "gi"));
225
+ for (const m of tagMatches) {
226
+ const tag = m[1].toLowerCase();
227
+ const content = m[2].replace(/\s+/g, " ").trim().slice(0, 200);
228
+ if (content) {
229
+ candidates.push({ text: `[${tag}] ${content}`, confidence: 0.85, explicit: true });
230
+ }
231
+ }
232
+ if (toolName === "Edit" || toolName === "Write") {
233
+ const filePath = String(input.file_path ?? input.path ?? "unknown");
234
+ const filename = path.basename(filePath);
235
+ if (/\b(TODO|FIXME)\b/.test(changedContent)) {
236
+ const firstLine = changedContent.split("\n").find((l) => /\b(TODO|FIXME)\b/.test(l));
237
+ if (firstLine) {
238
+ candidates.push({
239
+ text: `[pitfall] ${filename}: ${firstLine.trim().slice(0, 150)}`,
240
+ confidence: 0.45,
241
+ explicit: false,
242
+ });
243
+ }
244
+ }
245
+ if (/\btry\s*\{[\s\S]*?\bcatch\b/.test(changedContent)) {
246
+ const meaningfulLine = changedContent.split("\n").find((l) => l.trim().length > 10 && !/^\s*(try|catch|\{|\})/.test(l));
247
+ if (meaningfulLine) {
248
+ candidates.push({
249
+ text: `[pitfall] ${filename}: error handling added near "${meaningfulLine.trim().slice(0, 100)}"`,
250
+ confidence: 0.45,
251
+ explicit: false,
252
+ });
253
+ }
254
+ }
255
+ }
256
+ if (toolName === "Bash") {
257
+ const cmd = String(input.command ?? "").slice(0, 30);
258
+ const hasError = /(error|exception|failed|ENOENT|command not found|permission denied)/i.test(responseStr);
259
+ if (hasError && cmd) {
260
+ const firstErrorLine = responseStr.split("\n").find((l) => /(error|exception|failed|ENOENT|command not found|permission denied)/i.test(l));
261
+ if (firstErrorLine) {
262
+ candidates.push({
263
+ text: `[bug] command '${cmd}' failed: ${firstErrorLine.trim().slice(0, 150)}`,
264
+ confidence: 0.55,
265
+ explicit: false,
266
+ });
267
+ }
268
+ }
269
+ }
270
+ return candidates;
271
+ }
272
+ // ── Context hook handler ────────────────────────────────────────────────────
273
+ function readStdinJson() {
274
+ if (process.stdin.isTTY)
275
+ return null;
276
+ try {
277
+ return JSON.parse(fs.readFileSync(0, "utf-8"));
278
+ }
279
+ catch (err) {
280
+ logger.debug("hooks-session", `readStdinJson: ${errorMessage(err)}`);
281
+ return null;
282
+ }
283
+ }
284
+ export async function handleHookContext() {
285
+ const ctx = buildHookContext();
286
+ if (!ctx.hooksEnabled) {
287
+ process.exit(0);
288
+ }
289
+ let cwd = ctx.cwd;
290
+ const ctxStdin = readStdinJson();
291
+ if (ctxStdin?.cwd)
292
+ cwd = ctxStdin.cwd;
293
+ const project = cwd !== ctx.cwd ? detectProject(ctx.phrenPath, cwd, ctx.profile) : ctx.activeProject;
294
+ if (!isProjectHookEnabled(ctx.phrenPath, project, "UserPromptSubmit")) {
295
+ process.exit(0);
296
+ }
297
+ const db = await buildIndex(ctx.phrenPath, ctx.profile);
298
+ const contextLabel = project ? `\u25c6 phren \u00b7 ${project} \u00b7 context` : `\u25c6 phren \u00b7 context`;
299
+ const parts = [contextLabel, "<phren-context>"];
300
+ if (project) {
301
+ const summaryRow = queryRows(db, "SELECT content FROM docs WHERE project = ? AND type = 'summary'", [project]);
302
+ if (summaryRow) {
303
+ parts.push(`# ${project}`);
304
+ parts.push(summaryRow[0][0]);
305
+ parts.push("");
306
+ }
307
+ const findingsRow = queryRows(db, "SELECT content FROM docs WHERE project = ? AND type = 'findings'", [project]);
308
+ if (findingsRow) {
309
+ const content = findingsRow[0][0];
310
+ const bullets = content.split("\n").filter(l => l.startsWith("- ")).slice(0, 10);
311
+ if (bullets.length > 0) {
312
+ parts.push("## Recent findings");
313
+ parts.push(bullets.join("\n"));
314
+ parts.push("");
315
+ }
316
+ }
317
+ // Collect pinned tasks across ALL projects (excluding Done)
318
+ const allTaskRows = queryRows(db, "SELECT project, content FROM docs WHERE type = 'task'", []);
319
+ const pinnedFromOtherProjects = [];
320
+ if (allTaskRows) {
321
+ for (const row of allTaskRows) {
322
+ const taskProject = row[0];
323
+ if (taskProject === project)
324
+ continue;
325
+ const content = row[1];
326
+ const pinned = content.split("\n")
327
+ .filter(l => l.startsWith("- [ ] ") && /\[pinned\]/i.test(l))
328
+ .map(l => `[${taskProject}] ${l}`);
329
+ pinnedFromOtherProjects.push(...pinned);
330
+ }
331
+ }
332
+ // Active project tasks — pinned float to top, exclude Done
333
+ const taskRow = queryRows(db, "SELECT content FROM docs WHERE project = ? AND type = 'task'", [project]);
334
+ const pinnedItems = [];
335
+ const otherItems = [];
336
+ if (taskRow) {
337
+ const content = taskRow[0][0];
338
+ const allItems = content.split("\n").filter(l => l.startsWith("- [ ] "));
339
+ for (const item of allItems) {
340
+ if (/\[pinned\]/i.test(item)) {
341
+ pinnedItems.push(item);
342
+ }
343
+ else {
344
+ otherItems.push(item);
345
+ }
346
+ }
347
+ }
348
+ const filteredOther = filterTaskByPriority(otherItems);
349
+ const allPinned = [...pinnedItems, ...pinnedFromOtherProjects].slice(0, 10);
350
+ const remaining = Math.max(0, 5 - allPinned.length);
351
+ const trimmedOther = filteredOther.slice(0, remaining);
352
+ if (allPinned.length > 0 || trimmedOther.length > 0) {
353
+ if (allPinned.length > 0) {
354
+ parts.push("## Pinned tasks");
355
+ parts.push(allPinned.join("\n"));
356
+ }
357
+ if (trimmedOther.length > 0) {
358
+ parts.push("## Active tasks");
359
+ parts.push(trimmedOther.join("\n"));
360
+ }
361
+ parts.push("");
362
+ }
363
+ }
364
+ else {
365
+ const projectRows = queryRows(db, "SELECT DISTINCT project FROM docs ORDER BY project", []);
366
+ if (projectRows) {
367
+ parts.push("# Phren projects");
368
+ parts.push(projectRows.map(r => `- ${r[0]}`).join("\n"));
369
+ parts.push("");
370
+ }
371
+ }
372
+ parts.push("<phren-context>");
373
+ if (parts.length > 2) {
374
+ console.log(parts.join("\n"));
375
+ }
376
+ }
package/dist/cli/team.js CHANGED
@@ -6,6 +6,8 @@ import * as fs from "fs";
6
6
  import * as path from "path";
7
7
  import { execFileSync } from "child_process";
8
8
  import { getPhrenPath } from "../shared.js";
9
+ import { FINDINGS_FILENAME } from "../data/access.js";
10
+ import { TASKS_FILENAME } from "../data/tasks.js";
9
11
  import { isValidProjectName } from "../utils.js";
10
12
  import { addProjectToProfile, resolveActiveProfile } from "../profile-store.js";
11
13
  import { addStoreToRegistry, findStoreByName, generateStoreId, readTeamBootstrap, updateStoreProjects, } from "../store-registry.js";
@@ -81,7 +83,7 @@ async function handleTeamInit(args) {
81
83
  const globalDir = path.join(storePath, "global");
82
84
  fs.mkdirSync(globalDir, { recursive: true });
83
85
  atomicWriteText(path.join(globalDir, "CLAUDE.md"), `# ${name} Team Store\n\nShared knowledge for the ${name} team.\n`);
84
- atomicWriteText(path.join(globalDir, "FINDINGS.md"), `# global findings\n`);
86
+ atomicWriteText(path.join(globalDir, FINDINGS_FILENAME), `# global findings\n`);
85
87
  // Initialize git repo
86
88
  execFileSync("git", ["init"], {
87
89
  cwd: storePath,
@@ -230,11 +232,11 @@ async function handleTeamAddProject(args) {
230
232
  const journalDir = path.join(projectDir, "journal");
231
233
  fs.mkdirSync(journalDir, { recursive: true });
232
234
  // Scaffold project files
233
- if (!fs.existsSync(path.join(projectDir, "FINDINGS.md"))) {
234
- atomicWriteText(path.join(projectDir, "FINDINGS.md"), `# ${projectName} findings\n`);
235
+ if (!fs.existsSync(path.join(projectDir, FINDINGS_FILENAME))) {
236
+ atomicWriteText(path.join(projectDir, FINDINGS_FILENAME), `# ${projectName} findings\n`);
235
237
  }
236
- if (!fs.existsSync(path.join(projectDir, "tasks.md"))) {
237
- atomicWriteText(path.join(projectDir, "tasks.md"), `# ${projectName} tasks\n\n## Active\n\n## Queue\n\n## Done\n`);
238
+ if (!fs.existsSync(path.join(projectDir, TASKS_FILENAME))) {
239
+ atomicWriteText(path.join(projectDir, TASKS_FILENAME), `# ${projectName} tasks\n\n## Active\n\n## Queue\n\n## Done\n`);
238
240
  }
239
241
  if (!fs.existsSync(path.join(projectDir, "summary.md"))) {
240
242
  atomicWriteText(path.join(projectDir, "summary.md"), `# ${projectName}\n**What:** \n`);
@@ -10,12 +10,13 @@ import * as fs from "fs";
10
10
  import * as path from "path";
11
11
  import { spawnDetachedChild } from "./shared/process.js";
12
12
  import { TASKS_FILENAME } from "./data/tasks.js";
13
+ import { FINDINGS_FILENAME } from "./data/access.js";
13
14
  import { resolveSubprocessArgs as _resolveSubprocessArgs, runBestEffortGit, countUnsyncedCommits, } from "./cli-hooks-git.js";
14
15
  const SESSION_START_ONBOARDING_MARKER = "session-start-onboarding-v1";
15
16
  const SYNC_WARN_MARKER = "sync-broken-warned-v1";
16
17
  function projectHasBootstrapSignals(phrenPath, project) {
17
18
  const projectDir = path.join(phrenPath, project);
18
- const findingsPath = path.join(projectDir, "FINDINGS.md");
19
+ const findingsPath = path.join(projectDir, FINDINGS_FILENAME);
19
20
  if (fs.existsSync(findingsPath)) {
20
21
  const findings = fs.readFileSync(findingsPath, "utf8");
21
22
  if (/^-\s+/m.test(findings))
@@ -8,6 +8,7 @@ import { walkDirectory } from "../shared/data-utils.js";
8
8
  import { appendArchivedEntriesToTopicDoc, classifyTopicForText, readProjectTopics, topicReferencePath } from "../project-topics.js";
9
9
  import { isCitationLine, isArchiveStart, isArchiveEnd, stripComments } from "./metadata.js";
10
10
  import { logger } from "../logger.js";
11
+ import { FINDINGS_FILENAME } from "../data/access.js";
11
12
  /**
12
13
  * Count active (non-archived) finding entries in FINDINGS.md content.
13
14
  * Entries inside archive blocks are considered archived.
@@ -116,7 +117,7 @@ export function autoArchiveToReference(phrenPath, project, keepCount) {
116
117
  const resolvedDir = safeProjectPath(phrenPath, project);
117
118
  if (!resolvedDir || !fs.existsSync(resolvedDir))
118
119
  return phrenErr(`Project "${project}" not found in phren.`, PhrenError.PROJECT_NOT_FOUND);
119
- const learningsPath = path.join(resolvedDir, "FINDINGS.md");
120
+ const learningsPath = path.join(resolvedDir, FINDINGS_FILENAME);
120
121
  if (!fs.existsSync(learningsPath))
121
122
  return phrenOk(0);
122
123
  // Consolidation lock to prevent concurrent runs for the same project (atomic create via wx flag).
@@ -6,6 +6,7 @@ import { isFeatureEnabled, safeProjectPath, errorMessage } from "../utils.js";
6
6
  import { UNIVERSAL_TECH_TERMS_RE, EXTRA_ENTITY_PATTERNS } from "../phren-core.js";
7
7
  import { isInactiveFindingLine } from "../finding/lifecycle.js";
8
8
  import { logger } from "../logger.js";
9
+ import { FINDINGS_FILENAME } from "../data/access.js";
9
10
  // ── LLM provider abstraction ────────────────────────────────────────────────
10
11
  const MAX_CACHE_ENTRIES = 500;
11
12
  function loadCache(cachePath) {
@@ -200,7 +201,7 @@ const DYNAMIC_ENTITY_RE = /\b(?:[A-Z][a-z]+(?:[A-Z][a-z]*)+|[A-Z]{2,8}|[A-Z][a-z
200
201
  */
201
202
  export function extractDynamicEntities(phrenPath, project) {
202
203
  try {
203
- const findingsPath = path.join(phrenPath, project, "FINDINGS.md");
204
+ const findingsPath = path.join(phrenPath, project, FINDINGS_FILENAME);
204
205
  if (!fs.existsSync(findingsPath))
205
206
  return new Set();
206
207
  const findingsStat = fs.statSync(findingsPath);
@@ -479,7 +480,7 @@ export async function checkSemanticDedup(phrenPath, project, newLearning, signal
479
480
  const resolvedDir = safeProjectPath(phrenPath, project);
480
481
  if (!resolvedDir)
481
482
  return false;
482
- const findingsPath = path.join(resolvedDir, "FINDINGS.md");
483
+ const findingsPath = path.join(resolvedDir, FINDINGS_FILENAME);
483
484
  if (!fs.existsSync(findingsPath))
484
485
  return false;
485
486
  const existingContent = fs.readFileSync(findingsPath, "utf8");
@@ -537,13 +538,13 @@ export async function checkSemanticConflicts(phrenPath, project, newFinding, sig
537
538
  // Collect bullet sources: { bullets, sourceProject } pairs
538
539
  const sources = [];
539
540
  // Current project
540
- const findingsPath = path.join(resolvedDir, "FINDINGS.md");
541
+ const findingsPath = path.join(resolvedDir, FINDINGS_FILENAME);
541
542
  if (fs.existsSync(findingsPath)) {
542
543
  const content = fs.readFileSync(findingsPath, "utf8");
543
544
  sources.push({ bullets: content.split("\n").filter((l) => l.startsWith("- ")), sourceProject: null });
544
545
  }
545
546
  // Global project findings
546
- const globalFindingsPath = path.join(phrenPath, "global", "FINDINGS.md");
547
+ const globalFindingsPath = path.join(phrenPath, "global", FINDINGS_FILENAME);
547
548
  if (fs.existsSync(globalFindingsPath)) {
548
549
  const content = fs.readFileSync(globalFindingsPath, "utf8");
549
550
  const bullets = content.split("\n").filter((l) => l.startsWith("- "));
@@ -557,7 +558,7 @@ export async function checkSemanticConflicts(phrenPath, project, newFinding, sig
557
558
  const otherProjects = entries
558
559
  .filter((e) => e.isDirectory() && e.name !== project && e.name !== "global" && !e.name.startsWith("."))
559
560
  .map((e) => {
560
- const fp = path.join(phrenPath, e.name, "FINDINGS.md");
561
+ const fp = path.join(phrenPath, e.name, FINDINGS_FILENAME);
561
562
  if (!fs.existsSync(fp))
562
563
  return null;
563
564
  try {
@@ -13,6 +13,7 @@ import { countActiveFindings, autoArchiveToReference } from "./archive.js";
13
13
  import { resolveAutoFindingTaskItem, resolveFindingTaskReference, resolveFindingSessionId, } from "../finding/context.js";
14
14
  import { buildLifecycleComments, extractFindingType, parseFindingLifecycle, stripLifecycleComments, } from "../finding/lifecycle.js";
15
15
  import { METADATA_REGEX, } from "./metadata.js";
16
+ import { FINDINGS_FILENAME } from "../data/access.js";
16
17
  /** Default cap for active findings before auto-archiving is triggered. */
17
18
  const DEFAULT_FINDINGS_CAP = 20;
18
19
  const LIFECYCLE_ANNOTATION_RE = METADATA_REGEX.lifecycleAnnotation;
@@ -265,7 +266,7 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
265
266
  const resolvedDir = safeProjectPath(phrenPath, project);
266
267
  if (!resolvedDir)
267
268
  return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
268
- const learningsPath = path.join(resolvedDir, "FINDINGS.md");
269
+ const learningsPath = path.join(resolvedDir, FINDINGS_FILENAME);
269
270
  // Secret/PII scan — reject before anything else (before existence check, before lock)
270
271
  const nowIso = new Date().toISOString();
271
272
  const today = nowIso.slice(0, 10);
@@ -416,7 +417,7 @@ export function addFindingsToFile(phrenPath, project, learnings, opts) {
416
417
  const resolvedDir = safeProjectPath(phrenPath, project);
417
418
  if (!resolvedDir)
418
419
  return phrenErr(`Invalid project name: "${project}".`, PhrenError.INVALID_PROJECT_NAME);
419
- const learningsPath = path.join(resolvedDir, "FINDINGS.md");
420
+ const learningsPath = path.join(resolvedDir, FINDINGS_FILENAME);
420
421
  const nowIso = new Date().toISOString();
421
422
  const today = nowIso.slice(0, 10);
422
423
  const resolvedCitationInputResult = resolveFindingCitationInput(phrenPath, project);
@@ -8,6 +8,7 @@ import { countActiveFindings } from "./archive.js";
8
8
  import { isTaskFileName } from "../data/tasks.js";
9
9
  import { METADATA_REGEX } from "./metadata.js";
10
10
  import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
11
+ import { FINDINGS_FILENAME } from "../data/access.js";
11
12
  /** Maximum allowed length for a single finding entry (token budget protection). */
12
13
  export const MAX_FINDING_LENGTH = 2000;
13
14
  function safeParseDate(s) {
@@ -34,7 +35,7 @@ export function validateFinding(text) {
34
35
  * Returns null if the project has no FINDINGS.md.
35
36
  */
36
37
  export function getProjectConsolidationStatus(dir) {
37
- const learningsPath = path.join(dir, "FINDINGS.md");
38
+ const learningsPath = path.join(dir, FINDINGS_FILENAME);
38
39
  if (!fs.existsSync(learningsPath))
39
40
  return null;
40
41
  const content = fs.readFileSync(learningsPath, "utf8");
@@ -3,6 +3,7 @@ import { phrenErr, phrenOk, readRootManifest } from "../shared.js";
3
3
  import { bootstrapFromExisting } from "../init/setup.js";
4
4
  import { resolveActiveProfile } from "../profile-store.js";
5
5
  import { TASKS_FILENAME } from "../data/tasks.js";
6
+ import { FINDINGS_FILENAME } from "../data/access.js";
6
7
  export function addProjectFromPath(phrenPath, targetPath, requestedProfile, ownership) {
7
8
  if (!targetPath) {
8
9
  return phrenErr("Path is required. Pass the current project directory explicitly to avoid adding the wrong working directory.");
@@ -29,7 +30,7 @@ export function addProjectFromPath(phrenPath, targetPath, requestedProfile, owne
29
30
  files: {
30
31
  claude: added.claudePath,
31
32
  summary: path.join(phrenPath, added.project, "summary.md"),
32
- findings: path.join(phrenPath, added.project, "FINDINGS.md"),
33
+ findings: path.join(phrenPath, added.project, FINDINGS_FILENAME),
33
34
  task: path.join(phrenPath, added.project, TASKS_FILENAME),
34
35
  },
35
36
  });
@@ -7,6 +7,7 @@ export { readTasks, readTasksAcrossProjects, resolveTaskItem, addTask, addTasks,
7
7
  export { addProjectToProfile, listMachines, listProfiles, listProjectCards, removeProjectFromProfile, setMachineProfile, type ProfileInfo, type ProjectCard, } from "../profile-store.js";
8
8
  export { loadShellState, resetShellState, saveShellState, type ShellState, } from "../shell/state-store.js";
9
9
  export { getRuntimeHealth as readRuntimeHealth } from "../shared/governance.js";
10
+ export declare const FINDINGS_FILENAME = "FINDINGS.md";
10
11
  export interface FindingItem {
11
12
  id: string;
12
13
  /** Stable 8-char hex ID embedded as `<!-- fid:XXXXXXXX -->`. Survives reordering and consolidation. */
@@ -17,6 +17,7 @@ export { readTasks, readTasksAcrossProjects, resolveTaskItem, addTask, addTasks,
17
17
  export { addProjectToProfile, listMachines, listProfiles, listProjectCards, removeProjectFromProfile, setMachineProfile, } from "../profile-store.js";
18
18
  export { loadShellState, resetShellState, saveShellState, } from "../shell/state-store.js";
19
19
  export { getRuntimeHealth as readRuntimeHealth } from "../shared/governance.js";
20
+ export const FINDINGS_FILENAME = "FINDINGS.md";
20
21
  function extractDateHeading(line) {
21
22
  const heading = line.match(/^##\s+(.+)$/);
22
23
  if (!heading)
@@ -105,7 +106,7 @@ export function readFindings(phrenPath, project, opts = {}) {
105
106
  const ensured = ensureProject(phrenPath, project);
106
107
  if (!ensured.ok)
107
108
  return forwardErr(ensured);
108
- const findingsPath = path.join(ensured.data, 'FINDINGS.md');
109
+ const findingsPath = path.join(ensured.data, FINDINGS_FILENAME);
109
110
  const file = findingsPath;
110
111
  if (!fs.existsSync(file))
111
112
  return phrenOk([]);
@@ -283,13 +284,13 @@ export function removeFinding(phrenPath, project, match) {
283
284
  const ensured = ensureProject(phrenPath, project);
284
285
  if (!ensured.ok)
285
286
  return forwardErr(ensured);
286
- const findingsPath = path.resolve(path.join(ensured.data, 'FINDINGS.md'));
287
+ const findingsPath = path.resolve(path.join(ensured.data, FINDINGS_FILENAME));
287
288
  if (!findingsPath.startsWith(phrenPath + path.sep) && findingsPath !== phrenPath) {
288
- return phrenErr(`FINDINGS.md path escapes phren store`, PhrenError.VALIDATION_ERROR);
289
+ return phrenErr(`${FINDINGS_FILENAME} path escapes phren store`, PhrenError.VALIDATION_ERROR);
289
290
  }
290
291
  const filePath = findingsPath;
291
292
  if (!fs.existsSync(filePath))
292
- return phrenErr(`No FINDINGS.md file found for "${project}". Add a finding first with add_finding or :find add.`, PhrenError.FILE_NOT_FOUND);
293
+ return phrenErr(`No ${FINDINGS_FILENAME} file found for "${project}". Add a finding first with add_finding or :find add.`, PhrenError.FILE_NOT_FOUND);
293
294
  return withSafeLock(filePath, () => {
294
295
  const lines = fs.readFileSync(filePath, "utf8").split("\n");
295
296
  const needle = normalizeFindingText(match);
@@ -320,12 +321,12 @@ export function removeFindings(phrenPath, project, matches) {
320
321
  const ensured = ensureProject(phrenPath, project);
321
322
  if (!ensured.ok)
322
323
  return forwardErr(ensured);
323
- const findingsPath = path.resolve(path.join(ensured.data, 'FINDINGS.md'));
324
+ const findingsPath = path.resolve(path.join(ensured.data, FINDINGS_FILENAME));
324
325
  if (!findingsPath.startsWith(phrenPath + path.sep) && findingsPath !== phrenPath) {
325
- return phrenErr(`FINDINGS.md path escapes phren store`, PhrenError.VALIDATION_ERROR);
326
+ return phrenErr(`${FINDINGS_FILENAME} path escapes phren store`, PhrenError.VALIDATION_ERROR);
326
327
  }
327
328
  if (!fs.existsSync(findingsPath))
328
- return phrenErr(`No FINDINGS.md file found for "${project}". Add a finding first with add_finding or :find add.`, PhrenError.FILE_NOT_FOUND);
329
+ return phrenErr(`No ${FINDINGS_FILENAME} file found for "${project}". Add a finding first with add_finding or :find add.`, PhrenError.FILE_NOT_FOUND);
329
330
  return withSafeLock(findingsPath, () => {
330
331
  const lines = fs.readFileSync(findingsPath, "utf8").split("\n");
331
332
  const removed = [];
@@ -374,12 +375,12 @@ export function editFinding(phrenPath, project, oldText, newText) {
374
375
  const newTextTrimmed = newText.trim();
375
376
  if (!newTextTrimmed)
376
377
  return phrenErr("New finding text cannot be empty.", PhrenError.EMPTY_INPUT);
377
- const findingsPath = path.resolve(path.join(ensured.data, "FINDINGS.md"));
378
+ const findingsPath = path.resolve(path.join(ensured.data, FINDINGS_FILENAME));
378
379
  if (!findingsPath.startsWith(phrenPath + path.sep) && findingsPath !== phrenPath) {
379
- return phrenErr(`FINDINGS.md path escapes phren store`, PhrenError.VALIDATION_ERROR);
380
+ return phrenErr(`${FINDINGS_FILENAME} path escapes phren store`, PhrenError.VALIDATION_ERROR);
380
381
  }
381
382
  if (!fs.existsSync(findingsPath))
382
- return phrenErr(`No FINDINGS.md file found for "${project}".`, PhrenError.FILE_NOT_FOUND);
383
+ return phrenErr(`No ${FINDINGS_FILENAME} file found for "${project}".`, PhrenError.FILE_NOT_FOUND);
383
384
  return withSafeLock(findingsPath, () => {
384
385
  const lines = fs.readFileSync(findingsPath, "utf8").split("\n");
385
386
  const needle = normalizeFindingText(oldText);
@@ -5,6 +5,7 @@ import { runtimeDir, phrenOk, phrenErr, PhrenError, atomicWriteText } from "../s
5
5
  import { withFileLock } from "../shared/governance.js";
6
6
  import { addFindingToFile } from "../shared/content.js";
7
7
  import { isValidProjectName, errorMessage } from "../utils.js";
8
+ import { FINDINGS_FILENAME } from "../data/access.js";
8
9
  function journalRoot(phrenPath) {
9
10
  const dir = path.join(runtimeDir(phrenPath), "finding-journal");
10
11
  fs.mkdirSync(dir, { recursive: true });
@@ -198,7 +199,7 @@ export function materializeTeamFindings(storePath, project) {
198
199
  }
199
200
  lines.push("");
200
201
  }
201
- const findingsPath = path.join(storePath, project, "FINDINGS.md");
202
+ const findingsPath = path.join(storePath, project, FINDINGS_FILENAME);
202
203
  try {
203
204
  atomicWriteText(findingsPath, lines.join("\n"));
204
205
  return phrenOk({ entryCount: count });