@phren/cli 0.1.53 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -164,38 +164,21 @@ async function main() {
164
164
  });
165
165
  // Track MCP tool calls for telemetry (opt-in only, best-effort)
166
166
  const { trackToolCall } = await import("./telemetry.js");
167
+ const { createToolGate, resolveMcpProfile } = await import("./mcp/profile.js");
167
168
  const origRegisterTool = server.registerTool.bind(server);
168
- // Tools Claude reaches for during normal work. Marked with anthropic/alwaysLoad
169
- // so Claude Code keeps their schemas resident instead of deferring them behind
170
- // ToolSearch — otherwise the first call in a fresh session fails with
171
- // InputValidationError until the schema is fetched.
172
- const ALWAYS_LOAD_TOOLS = new Set([
173
- "add_finding",
174
- "add_note",
175
- "add_task",
176
- "complete_task",
177
- "search_knowledge",
178
- "session_start",
179
- "session_end",
180
- "get_findings",
181
- "get_tasks",
182
- ]);
183
- const registeredToolNames = new Set();
184
- server.registerTool = function (name, config, handler) {
185
- const registeredName = name;
186
- // Registration runs before server.connect, so throwing here fails fast at
187
- // startup instead of letting a later module silently shadow an earlier tool.
188
- if (registeredToolNames.has(registeredName)) {
189
- throw new Error(`Duplicate MCP tool registration: "${String(registeredName)}"`);
190
- }
191
- registeredToolNames.add(registeredName);
192
- let finalConfig = config;
193
- if (ALWAYS_LOAD_TOOLS.has(registeredName)) {
194
- const cfgObj = config;
195
- const existingMeta = cfgObj?._meta ?? {};
196
- finalConfig = { ...cfgObj, _meta: { ...existingMeta, "anthropic/alwaysLoad": true } };
197
- }
198
- const wrapped = async (...args) => {
169
+ // Tools Claude reaches for during normal work in the full profile. Marked
170
+ // anthropic/alwaysLoad so Claude Code keeps their schemas resident instead of
171
+ // deferring them behind ToolSearch. The core profile marks all of its tools.
172
+ const ALWAYS_LOAD_TOOLS = ["add_note", "complete_task", "session_start", "session_end", "get_findings"];
173
+ // Every module registers its tools as before; the gate decides what the
174
+ // client sees. `core` (the default) exposes ten tools and folds the rest
175
+ // behind phren_admin; `full` is the whole surface. See mcp/profile.ts.
176
+ const mcpProfile = resolveMcpProfile(phrenPath);
177
+ const gate = createToolGate({
178
+ profile: mcpProfile,
179
+ alwaysLoad: ALWAYS_LOAD_TOOLS,
180
+ register: (name, config, handler) => origRegisterTool(name, config, handler),
181
+ wrap: (registeredName, handler) => async (...args) => {
199
182
  if (shuttingDown) {
200
183
  return {
201
184
  content: [{
@@ -225,9 +208,9 @@ async function main() {
225
208
  logger.warn("trackToolCall", errorMessage(err));
226
209
  }
227
210
  return handler(...args);
228
- };
229
- return origRegisterTool(registeredName, finalConfig, wrapped);
230
- };
211
+ },
212
+ });
213
+ server.registerTool = gate.registerTool;
231
214
  // Register all tool handlers from domain modules
232
215
  const ctx = {
233
216
  phrenPath,
@@ -264,9 +247,10 @@ async function main() {
264
247
  ]);
265
248
  for (const mod of toolModules)
266
249
  mod.register(server, ctx);
250
+ gate.finish();
267
251
  const transport = new StdioServerTransport();
268
252
  await server.connect(transport);
269
- console.error(`phren-mcp running (${phrenPath})`);
253
+ console.error(`phren-mcp running (${phrenPath}) · profile ${mcpProfile} · ${gate.exposed.size} tools`);
270
254
  // Graceful shutdown: drain write queue and close DB before exit
271
255
  async function shutdown(signal) {
272
256
  shuttingDown = true;
@@ -1,6 +1,12 @@
1
1
  import type { CustomHookEntry } from "../hooks.js";
2
2
  export interface InstallPreferences {
3
3
  mcpEnabled?: boolean;
4
+ /**
5
+ * Which MCP tool surface clients get. "core" (default) is ten tools with
6
+ * everything else behind phren_admin; "full" is every tool by name.
7
+ * PHREN_MCP_PROFILE overrides it. See mcp/profile.ts.
8
+ */
9
+ mcpProfile?: "core" | "full";
4
10
  hooksEnabled?: boolean;
5
11
  skillsScope?: "global" | "project";
6
12
  projectOwnershipDefault?: "phren-managed" | "detached" | "repo-managed";
@@ -24,6 +24,8 @@ import { claudeProjectKey } from "./context.js";
24
24
  import { getProjectOwnershipMode, readProjectConfig } from "../project-config.js";
25
25
  import { readInstallPreferences } from "../init/preferences.js";
26
26
  import { logger } from "../logger.js";
27
+ import { CONTEXT_COST_LIMITS, medianHookInjectionTokens, storeWeight } from "../store-weight.js";
28
+ import { resolveMcpProfile } from "../mcp/profile.js";
27
29
  // ── Doctor ──────────────────────────────────────────────────────────────────
28
30
  function isWrapperActive(tool) {
29
31
  const isWindows = process.platform === "win32";
@@ -542,6 +544,30 @@ export async function runDoctor(phrenPath, fix = false, checkData = false) {
542
544
  runtime = null;
543
545
  }
544
546
  }
547
+ // What an agent pays before it says a word, and per prompt after. None of
548
+ // the tidying stays done unless this is visible.
549
+ try {
550
+ const weight = storeWeight(phrenPath);
551
+ const profile = resolveMcpProfile(phrenPath);
552
+ const injection = medianHookInjectionTokens(phrenPath);
553
+ const problems = [];
554
+ if (weight.globalClaude > CONTEXT_COST_LIMITS.globalClaudeWords)
555
+ problems.push(`global CLAUDE.md is ${weight.globalClaude} words (aim under ${CONTEXT_COST_LIMITS.globalClaudeWords})`);
556
+ if (profile === "full")
557
+ problems.push("MCP profile is full (59 tools, ~53k chars of schema per session); `phren config mcp-profile core` is ~17k");
558
+ if (injection.medianTokens > CONTEXT_COST_LIMITS.medianInjectionTokens)
559
+ problems.push(`median hook injection is ${injection.medianTokens} tokens over the last ${injection.prompts} prompts`);
560
+ checks.push({
561
+ name: "context-cost",
562
+ ok: problems.length === 0,
563
+ detail: problems.length
564
+ ? problems.join("; ")
565
+ : `global CLAUDE.md ${weight.globalClaude} words · MCP profile ${profile} (${profile === "core" ? "10 tools, ~17k chars" : "59 tools, ~53k chars"})${injection.prompts ? ` · median injection ${injection.medianTokens} tokens over ${injection.prompts} prompts` : ""} · store: findings ${weight.findings.toLocaleString("en-US")} words, archive ${weight.reference.toLocaleString("en-US")}, tasks ${weight.tasks.toLocaleString("en-US")}, skills ${weight.skills.toLocaleString("en-US")}`,
566
+ });
567
+ }
568
+ catch (err) {
569
+ logger.debug("doctor", `context-cost: ${errorMessage(err)}`);
570
+ }
545
571
  checks.push({
546
572
  name: "runtime-health-file",
547
573
  ok: Boolean(runtime),
@@ -0,0 +1,80 @@
1
+ /**
2
+ * MCP tool profiles.
3
+ *
4
+ * The server used to hand every client 59 tools, about 11k tokens of schema
5
+ * before a word was said, and 59 similar verbs to choose the wrong one from.
6
+ * The `core` profile (the default) exposes the handful an agent reaches for
7
+ * during normal work plus one `phren_admin` tool that reaches everything
8
+ * else by name. `full` is the old surface for anyone who scripted against
9
+ * it, and it also gains the composites.
10
+ *
11
+ * Nothing here knows how a tool works. Modules register tools exactly as
12
+ * before; the server's registerTool wrapper records each one in a catalog and
13
+ * only exposes the core ones, and the composites built here dispatch into
14
+ * that catalog, validating against the target tool's own schema first.
15
+ */
16
+ export type McpProfile = "core" | "full";
17
+ export declare const MCP_PROFILES: readonly McpProfile[];
18
+ /** What an agent gets in the core profile. Order is the order clients list them. */
19
+ export declare const CORE_TOOLS: readonly string[];
20
+ /** Env wins, then the install preference, then core. */
21
+ export declare function resolveMcpProfile(phrenPath: string, env?: NodeJS.ProcessEnv): McpProfile;
22
+ export interface ToolConfig {
23
+ title?: string;
24
+ description?: string;
25
+ inputSchema?: unknown;
26
+ [key: string]: unknown;
27
+ }
28
+ export type ToolHandler = (args: Record<string, unknown>) => unknown;
29
+ export interface CatalogEntry {
30
+ name: string;
31
+ config: ToolConfig;
32
+ handler: ToolHandler;
33
+ }
34
+ export type Catalog = Map<string, CatalogEntry>;
35
+ /**
36
+ * Notes fold into add_finding: `kind: "note"` saves a lightweight daily note
37
+ * instead of a durable finding. The note tool keeps its own schema and
38
+ * handler; this only adds the switch and routes through the catalog, so the
39
+ * note module can register before or after the finding module.
40
+ */
41
+ export declare function decorateAddFinding(entry: CatalogEntry, catalog: Catalog): CatalogEntry;
42
+ export interface ToolGate {
43
+ /** Drop-in for McpServer.registerTool: records every tool, exposes only what the profile allows. */
44
+ registerTool: (name: string, config: ToolConfig, handler: ToolHandler) => void;
45
+ /** Call once every module has registered: adds the composites. */
46
+ finish: () => void;
47
+ readonly catalog: Catalog;
48
+ readonly exposed: Set<string>;
49
+ readonly profile: McpProfile;
50
+ }
51
+ /**
52
+ * Sits between the tool modules and the real server. Modules keep calling
53
+ * registerTool exactly as before; the gate keeps the catalog, exposes core
54
+ * tools (or everything, in `full`), marks core tools always-loaded for Claude
55
+ * Code, and registers the composites when `finish` is called.
56
+ */
57
+ export declare function createToolGate(opts: {
58
+ profile: McpProfile;
59
+ register: (name: string, config: ToolConfig, handler: ToolHandler) => unknown;
60
+ /** Wraps every handler (guards, telemetry) before it is stored or exposed. */
61
+ wrap?: (name: string, handler: ToolHandler) => ToolHandler;
62
+ /** Extra tools to mark always-loaded for Claude Code, on top of the core set. */
63
+ alwaysLoad?: Iterable<string>;
64
+ }): ToolGate;
65
+ /** Run a catalog tool by name after validating the arguments against its own schema. */
66
+ export declare function dispatch(catalog: Catalog, target: string, args: Record<string, unknown>): Promise<unknown>;
67
+ export interface BuiltTool {
68
+ name: string;
69
+ config: ToolConfig;
70
+ handler: ToolHandler;
71
+ }
72
+ /**
73
+ * The composite tools for a catalog. An action that has no registered target
74
+ * (a module not loaded, say) is left out rather than advertised.
75
+ */
76
+ export declare function buildCompositeTools(catalog: Catalog): BuiltTool[];
77
+ /** Rough size of what a client downloads for a set of tools, for tests and doctor. */
78
+ export declare function schemaWeight(entries: Iterable<{
79
+ config: ToolConfig;
80
+ }>): number;
@@ -0,0 +1,282 @@
1
+ /**
2
+ * MCP tool profiles.
3
+ *
4
+ * The server used to hand every client 59 tools, about 11k tokens of schema
5
+ * before a word was said, and 59 similar verbs to choose the wrong one from.
6
+ * The `core` profile (the default) exposes the handful an agent reaches for
7
+ * during normal work plus one `phren_admin` tool that reaches everything
8
+ * else by name. `full` is the old surface for anyone who scripted against
9
+ * it, and it also gains the composites.
10
+ *
11
+ * Nothing here knows how a tool works. Modules register tools exactly as
12
+ * before; the server's registerTool wrapper records each one in a catalog and
13
+ * only exposes the core ones, and the composites built here dispatch into
14
+ * that catalog, validating against the target tool's own schema first.
15
+ */
16
+ import { z } from "zod";
17
+ import { readInstallPreferences } from "../init/preferences.js";
18
+ export const MCP_PROFILES = ["core", "full"];
19
+ /** What an agent gets in the core profile. Order is the order clients list them. */
20
+ export const CORE_TOOLS = [
21
+ "search_knowledge",
22
+ "get_memory_detail",
23
+ "get_project_summary",
24
+ "add_finding",
25
+ "revise_finding",
26
+ "get_tasks",
27
+ "add_task",
28
+ "manage_task",
29
+ "session",
30
+ "phren_admin",
31
+ ];
32
+ /** Env wins, then the install preference, then core. */
33
+ export function resolveMcpProfile(phrenPath, env = process.env) {
34
+ const fromEnv = env.PHREN_MCP_PROFILE?.trim().toLowerCase();
35
+ if (fromEnv === "core" || fromEnv === "full")
36
+ return fromEnv;
37
+ try {
38
+ const prefs = readInstallPreferences(phrenPath);
39
+ if (prefs.mcpProfile === "core" || prefs.mcpProfile === "full")
40
+ return prefs.mcpProfile;
41
+ }
42
+ catch {
43
+ // No preferences yet: the default applies.
44
+ }
45
+ return "core";
46
+ }
47
+ const COMPOSITES = {
48
+ revise_finding: {
49
+ title: "◆ phren · revise finding",
50
+ summary: "Change an existing finding: supersede, retract, edit, remove, link, resolve a contradiction, pin, or give feedback on it. Pass `action` plus that action's own parameters.",
51
+ actions: {
52
+ supersede: "supersede_finding",
53
+ retract: "retract_finding",
54
+ edit: "edit_finding",
55
+ remove: "remove_finding",
56
+ link: "link_findings",
57
+ resolve_contradiction: "resolve_contradiction",
58
+ pin: "pin_memory",
59
+ feedback: "memory_feedback",
60
+ },
61
+ },
62
+ manage_task: {
63
+ title: "◆ phren · manage task",
64
+ summary: "Change an existing task: complete, update, remove, pin, or tidy the done list. Pass `action` plus that action's own parameters.",
65
+ actions: {
66
+ complete: "complete_task",
67
+ update: "update_task",
68
+ remove: "remove_task",
69
+ pin: "pin_task",
70
+ tidy: "tidy_done_tasks",
71
+ },
72
+ },
73
+ session: {
74
+ title: "◆ phren · session",
75
+ summary: "Session lifecycle: start, end, current context, or history. Pass `action` plus that action's own parameters.",
76
+ actions: {
77
+ start: "session_start",
78
+ end: "session_end",
79
+ context: "session_context",
80
+ history: "session_history",
81
+ },
82
+ },
83
+ };
84
+ /** The tools a composite stands for, so the admin tool does not list them twice. */
85
+ function foldedNames() {
86
+ const out = new Set(["add_note"]); // reachable as add_finding with kind: "note"
87
+ for (const c of Object.values(COMPOSITES))
88
+ for (const target of Object.values(c.actions))
89
+ out.add(target);
90
+ return out;
91
+ }
92
+ /**
93
+ * Notes fold into add_finding: `kind: "note"` saves a lightweight daily note
94
+ * instead of a durable finding. The note tool keeps its own schema and
95
+ * handler; this only adds the switch and routes through the catalog, so the
96
+ * note module can register before or after the finding module.
97
+ */
98
+ export function decorateAddFinding(entry, catalog) {
99
+ const schema = schemaOf(entry);
100
+ if (!schema)
101
+ return entry;
102
+ const config = {
103
+ ...entry.config,
104
+ description: `${entry.config.description ?? ""} Pass kind: "note" to save a lightweight daily note instead (goes to the project's notes, not FINDINGS.md).`,
105
+ inputSchema: schema.extend({
106
+ kind: z.enum(["finding", "note"]).optional().describe("'finding' (default) is durable, curated knowledge; 'note' is a lightweight daily note."),
107
+ date: z.string().optional().describe("Notes only: YYYY-MM-DD, defaults to today."),
108
+ }),
109
+ };
110
+ const handler = (args) => {
111
+ const { kind, date, ...rest } = args;
112
+ if (kind === "note") {
113
+ const finding = rest.finding;
114
+ const text = Array.isArray(finding) ? finding.map(String).join("\n\n") : String(finding ?? "");
115
+ return dispatch(catalog, "add_note", { project: rest.project, text, ...(date ? { date } : {}) });
116
+ }
117
+ return entry.handler(rest);
118
+ };
119
+ return { name: entry.name, config, handler };
120
+ }
121
+ /**
122
+ * Sits between the tool modules and the real server. Modules keep calling
123
+ * registerTool exactly as before; the gate keeps the catalog, exposes core
124
+ * tools (or everything, in `full`), marks core tools always-loaded for Claude
125
+ * Code, and registers the composites when `finish` is called.
126
+ */
127
+ export function createToolGate(opts) {
128
+ const alwaysLoad = new Set([...CORE_TOOLS, ...(opts.alwaysLoad ?? [])]);
129
+ const catalog = new Map();
130
+ const exposed = new Set();
131
+ const expose = (name, config, handler) => {
132
+ let finalConfig = config;
133
+ if (alwaysLoad.has(name)) {
134
+ const meta = config._meta ?? {};
135
+ finalConfig = { ...config, _meta: { ...meta, "anthropic/alwaysLoad": true } };
136
+ }
137
+ opts.register(name, finalConfig, handler);
138
+ exposed.add(name);
139
+ };
140
+ const registerTool = (name, config, handler) => {
141
+ if (catalog.has(name))
142
+ throw new Error(`Duplicate MCP tool registration: "${name}"`);
143
+ const wrapped = opts.wrap ? opts.wrap(name, handler) : handler;
144
+ let entry = { name, config, handler: wrapped };
145
+ if (name === "add_finding")
146
+ entry = decorateAddFinding(entry, catalog);
147
+ catalog.set(name, entry);
148
+ if (opts.profile === "core" && !CORE_TOOLS.includes(name))
149
+ return;
150
+ expose(name, entry.config, entry.handler);
151
+ };
152
+ const finish = () => {
153
+ for (const tool of buildCompositeTools(catalog)) {
154
+ if (catalog.has(tool.name))
155
+ continue;
156
+ catalog.set(tool.name, { name: tool.name, config: tool.config, handler: tool.handler });
157
+ expose(tool.name, tool.config, tool.handler);
158
+ }
159
+ };
160
+ return { registerTool, finish, catalog, exposed, profile: opts.profile };
161
+ }
162
+ function schemaOf(entry) {
163
+ const raw = entry.config.inputSchema;
164
+ if (!raw)
165
+ return null;
166
+ if (raw instanceof z.ZodObject)
167
+ return raw;
168
+ if (typeof raw === "object")
169
+ return z.object(raw);
170
+ return null;
171
+ }
172
+ function paramDocs(entry) {
173
+ const schema = schemaOf(entry);
174
+ if (!schema)
175
+ return [];
176
+ return Object.entries(schema.shape).map(([name, type]) => {
177
+ const t = type;
178
+ return { name, required: !t.isOptional(), description: t.description ?? "" };
179
+ });
180
+ }
181
+ function firstSentence(text) {
182
+ const flat = (text ?? "").replace(/\s+/g, " ").trim();
183
+ const end = flat.search(/\.\s|\.$/);
184
+ const s = end === -1 ? flat : flat.slice(0, end + 1);
185
+ return s.length > 140 ? `${s.slice(0, 139)}…` : s;
186
+ }
187
+ function actionLine(action, entry) {
188
+ const required = paramDocs(entry).filter((p) => p.required).map((p) => p.name);
189
+ const req = required.length ? ` (required: ${required.join(", ")})` : "";
190
+ return `${action} — ${firstSentence(entry.config.description)}${req}`;
191
+ }
192
+ function errorResponse(error, extra = {}) {
193
+ return { content: [{ type: "text", text: JSON.stringify({ ok: false, error, ...extra }, null, 2) }] };
194
+ }
195
+ /** Run a catalog tool by name after validating the arguments against its own schema. */
196
+ export async function dispatch(catalog, target, args) {
197
+ const entry = catalog.get(target);
198
+ if (!entry)
199
+ return errorResponse(`Unknown tool "${target}"`);
200
+ const schema = schemaOf(entry);
201
+ if (schema) {
202
+ const parsed = schema.safeParse(args);
203
+ if (!parsed.success) {
204
+ return errorResponse(`Invalid arguments for ${target}`, {
205
+ issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })),
206
+ params: paramDocs(entry),
207
+ });
208
+ }
209
+ return entry.handler(parsed.data);
210
+ }
211
+ return entry.handler(args);
212
+ }
213
+ /**
214
+ * The composite tools for a catalog. An action that has no registered target
215
+ * (a module not loaded, say) is left out rather than advertised.
216
+ */
217
+ export function buildCompositeTools(catalog) {
218
+ const out = [];
219
+ for (const [name, composite] of Object.entries(COMPOSITES)) {
220
+ const actions = Object.entries(composite.actions).filter(([, target]) => catalog.has(target));
221
+ if (!actions.length)
222
+ continue;
223
+ const lines = actions.map(([action, target]) => actionLine(action, catalog.get(target)));
224
+ const actionNames = actions.map(([action]) => action);
225
+ const map = Object.fromEntries(actions);
226
+ out.push({
227
+ name,
228
+ config: {
229
+ title: composite.title,
230
+ description: `${composite.summary}\nActions:\n${lines.map((l) => `- ${l}`).join("\n")}`,
231
+ inputSchema: z.object({ action: z.enum(actionNames).describe("Which change to make.") }).passthrough(),
232
+ },
233
+ handler: (args) => {
234
+ const { action, ...rest } = args;
235
+ return dispatch(catalog, map[action], rest);
236
+ },
237
+ });
238
+ }
239
+ const folded = foldedNames();
240
+ const adminTargets = [...catalog.keys()]
241
+ .filter((n) => !CORE_TOOLS.includes(n) && !folded.has(n) && !(n in COMPOSITES))
242
+ .sort();
243
+ if (adminTargets.length) {
244
+ const lines = adminTargets.map((n) => actionLine(n, catalog.get(n)));
245
+ const actionNames = ["list_actions", ...adminTargets];
246
+ out.push({
247
+ name: "phren_admin",
248
+ config: {
249
+ title: "◆ phren · admin",
250
+ description: "Everything else phren can do — skills, hooks, config, notes, review queue, export/import, doctor, the fragment graph — behind one tool. " +
251
+ "Pass `action` plus that action's parameters; `list_actions` returns every action with its full parameter list.\nActions:\n" +
252
+ lines.map((l) => `- ${l}`).join("\n"),
253
+ inputSchema: z.object({ action: z.enum(actionNames).describe("Which admin action to run, or list_actions.") }).passthrough(),
254
+ },
255
+ handler: (args) => {
256
+ const { action, ...rest } = args;
257
+ if (action === "list_actions") {
258
+ const actions = adminTargets.map((n) => {
259
+ const entry = catalog.get(n);
260
+ return { name: n, description: entry.config.description ?? "", params: paramDocs(entry) };
261
+ });
262
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, actions }, null, 2) }] };
263
+ }
264
+ return dispatch(catalog, action, rest);
265
+ },
266
+ });
267
+ }
268
+ return out;
269
+ }
270
+ /** Rough size of what a client downloads for a set of tools, for tests and doctor. */
271
+ export function schemaWeight(entries) {
272
+ let chars = 0;
273
+ for (const { config } of entries) {
274
+ chars += (config.title ?? "").length + (config.description ?? "").length;
275
+ const raw = config.inputSchema;
276
+ const schema = raw instanceof z.ZodObject ? raw : raw && typeof raw === "object" ? z.object(raw) : null;
277
+ if (schema)
278
+ for (const [k, t] of Object.entries(schema.shape))
279
+ chars += k.length + (t.description ?? "").length + 24;
280
+ }
281
+ return chars;
282
+ }
@@ -150,6 +150,8 @@ export declare function findProjectNameCaseInsensitive(phrenPath: string, name:
150
150
  export declare function findProjectNamesByCanonicalKey(phrenPath: string, name: string): string[];
151
151
  export declare function findArchivedProjectNameCaseInsensitive(phrenPath: string, name: string): string | null;
152
152
  export declare function getProjectDirs(phrenPath: string, profile?: string): string[];
153
+ /** Claude's own memory directory is indexed only when asked: by default phren indexes phren. */
154
+ export declare function nativeMemoryEnabled(env?: NodeJS.ProcessEnv): boolean;
153
155
  export declare function collectNativeMemoryFiles(): Array<{
154
156
  project: string;
155
157
  file: string;
@@ -621,6 +621,11 @@ export function getProjectDirs(phrenPath, profile) {
621
621
  return [];
622
622
  }
623
623
  }
624
+ /** Claude's own memory directory is indexed only when asked: by default phren indexes phren. */
625
+ export function nativeMemoryEnabled(env = process.env) {
626
+ const raw = env.PHREN_FEATURE_NATIVE_MEMORY?.trim().toLowerCase();
627
+ return raw === "1" || raw === "true" || raw === "on";
628
+ }
624
629
  // Collect MEMORY*.md files from native agent memory locations (~/.claude/projects/*/memory/)
625
630
  export function collectNativeMemoryFiles() {
626
631
  const claudeProjectsDir = homePath(".claude", "projects");
@@ -3,7 +3,7 @@ import * as path from "path";
3
3
  import * as os from "os";
4
4
  import * as crypto from "crypto";
5
5
  import { globSync } from "glob";
6
- import { debugLog, appendIndexEvent, getProjectDirs, collectNativeMemoryFiles, runtimeFile, homeDir, readRootManifest, } from "../shared.js";
6
+ import { debugLog, appendIndexEvent, getProjectDirs, collectNativeMemoryFiles, nativeMemoryEnabled, runtimeFile, homeDir, readRootManifest, } from "../shared.js";
7
7
  /**
8
8
  * Cached store project dirs to avoid repeated dynamic imports in sync code paths.
9
9
  * Populated by `refreshStoreProjectDirs()`, consumed by `getAllStoreProjectDirs()`.
@@ -333,7 +333,7 @@ function computePhrenHash(phrenPath, profile, preGlobbed) {
333
333
  }
334
334
  }
335
335
  }
336
- for (const mem of collectNativeMemoryFiles()) {
336
+ for (const mem of nativeMemoryEnabled() ? collectNativeMemoryFiles() : []) {
337
337
  try {
338
338
  const stat = fs.statSync(mem.fullPath);
339
339
  hash.update(`native:${mem.fullPath}:${stat.mtimeMs}:${stat.size}`);
@@ -583,7 +583,7 @@ function globAllFiles(phrenPath, profile) {
583
583
  allAbsolutePaths.push(fullPath);
584
584
  }
585
585
  }
586
- for (const mem of collectNativeMemoryFiles()) {
586
+ for (const mem of nativeMemoryEnabled() ? collectNativeMemoryFiles() : []) {
587
587
  entries.push({ fullPath: mem.fullPath, project: mem.project, filename: mem.file, type: "findings" });
588
588
  allAbsolutePaths.push(mem.fullPath);
589
589
  }
@@ -900,18 +900,21 @@ function collectContentDirs(phrenPath, projectDirs) {
900
900
  walk(dir);
901
901
  }
902
902
  walk(path.join(phrenPath, "global", "skills"));
903
- // Native agent memory (~/.claude/projects/*/memory) is indexed too, but the
904
- // surrounding project dirs are huge — watch only the two levels that matter.
905
- const nativeRoot = path.join(homeDir(), ".claude", "projects");
906
- out.add(nativeRoot);
907
- try {
908
- for (const entry of fs.readdirSync(nativeRoot, { withFileTypes: true })) {
909
- if (entry.isDirectory())
910
- out.add(path.join(nativeRoot, entry.name, "memory"));
903
+ // Native agent memory (~/.claude/projects/*/memory) is indexed only when
904
+ // PHREN_FEATURE_NATIVE_MEMORY is on; then the surrounding project dirs are
905
+ // huge, so watch only the two levels that matter.
906
+ if (nativeMemoryEnabled()) {
907
+ const nativeRoot = path.join(homeDir(), ".claude", "projects");
908
+ out.add(nativeRoot);
909
+ try {
910
+ for (const entry of fs.readdirSync(nativeRoot, { withFileTypes: true })) {
911
+ if (entry.isDirectory())
912
+ out.add(path.join(nativeRoot, entry.name, "memory"));
913
+ }
914
+ }
915
+ catch {
916
+ // no native memory dirs — the nativeRoot entry above still catches creation
911
917
  }
912
- }
913
- catch {
914
- // no native memory dirs — the nativeRoot entry above still catches creation
915
918
  }
916
919
  return [...out];
917
920
  }
@@ -19,6 +19,12 @@ export declare const SNIPPET_OVERHEAD_TOKENS = 24;
19
19
  * recall. Cross-project docs face a higher bar. Tunable via
20
20
  * PHREN_MIN_QUERY_RELEVANCE (0 disables the floor). */
21
21
  declare const DEFAULT_MIN_QUERY_RELEVANCE = 0.12;
22
+ /**
23
+ * Tasks are a backlog, not memory: a to-do list injected into a debugging
24
+ * question is noise that costs findings their budget. They go in only when the
25
+ * prompt is about building or asks about the work itself.
26
+ */
27
+ export declare function wantsTasks(prompt: string, intent: ReturnType<typeof detectTaskIntent>): boolean;
22
28
  export declare function detectTaskIntent(prompt: string): "debug" | "review" | "build" | "docs" | "skill" | "general";
23
29
  export declare function fileRelevanceBoost(filePath: string, changedFiles: Set<string>): number;
24
30
  export declare function branchMatchBoost(content: string, branch: string | undefined): number;
@@ -59,6 +59,15 @@ const INTENT_DEBUG_RE = /(bug|error|fix|broken|regression|fail|stack trace)/;
59
59
  const INTENT_REVIEW_RE = /(review|audit|pr|pull request|nit|refactor)/;
60
60
  const INTENT_BUILD_RE = /(build|deploy|release|ci|workflow|pipeline|test)/;
61
61
  const INTENT_DOCS_RE = /\b(doc|docs|readme|explain|guide|instructions?)\b/;
62
+ const WANTS_TASKS_RE = /\b(tasks?|todos?|backlog|queue|what'?s (left|next|remaining)|what is (left|next|remaining)|next up|remaining work|priorit(y|ies))\b/i;
63
+ /**
64
+ * Tasks are a backlog, not memory: a to-do list injected into a debugging
65
+ * question is noise that costs findings their budget. They go in only when the
66
+ * prompt is about building or asks about the work itself.
67
+ */
68
+ export function wantsTasks(prompt, intent) {
69
+ return intent === "build" || WANTS_TASKS_RE.test(prompt);
70
+ }
62
71
  export function detectTaskIntent(prompt) {
63
72
  const p = prompt.toLowerCase();
64
73
  if (INTENT_SKILL_CMD_RE.test(p) || INTENT_SKILL_KW_RE.test(p))
package/dist/shared.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export type { HookToolName } from "./provider-adapters.js";
2
2
  export { HOOK_TOOL_NAMES, hookConfigPath } from "./provider-adapters.js";
3
3
  export { EXEC_TIMEOUT_MS, EXEC_TIMEOUT_QUICK_MS, PhrenError, type PhrenErrorCode, type PhrenResult, phrenOk, phrenErr, forwardErr, parsePhrenErrorCode, isRecord, withDefaults, FINDING_TYPES, type FindingType, FINDING_TAGS, type FindingTag, KNOWN_OBSERVATION_TAGS, DOC_TYPES, type DocType, capCache, RESERVED_PROJECT_DIR_NAMES, } from "./phren-core.js";
4
- export { ROOT_MANIFEST_FILENAME, type InstallMode, type SyncMode, type PhrenRootManifest, type InstallContext, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, lookupEventsLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, projectSlugFromPath, canonicalProjectKey, findProjectNameCaseInsensitive, findProjectNamesByCanonicalKey, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, ensurePrivateDir, ftsCacheRoot, ensureFtsCacheRootPrivate, } from "./phren-paths.js";
4
+ export { ROOT_MANIFEST_FILENAME, type InstallMode, type SyncMode, type PhrenRootManifest, type InstallContext, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, lookupEventsLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, projectSlugFromPath, canonicalProjectKey, findProjectNameCaseInsensitive, findProjectNamesByCanonicalKey, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, nativeMemoryEnabled, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, ensurePrivateDir, ftsCacheRoot, ensureFtsCacheRootPrivate, } from "./phren-paths.js";
5
5
  export { PROACTIVITY_LEVELS, type ProactivityLevel, parseProactivityLevel, getProactivityLevel, getProactivityLevelForFindings, getProactivityLevelForTask, hasExplicitFindingSignal, hasExplicitTaskSignal, hasExecutionIntent, hasDiscoveryIntent, shouldAutoCaptureFindingsForLevel, shouldAutoCaptureTaskForLevel, } from "./proactivity.js";
6
6
  export declare function normalizeMemoryScope(scope?: string | null): string | undefined;
7
7
  export declare function isMemoryScopeVisible(itemScope: string | undefined, activeScope?: string): boolean;
package/dist/shared.js CHANGED
@@ -6,7 +6,7 @@ import { withFileLock } from "./governance/locks.js";
6
6
  const MAX_LOG_LINES = 1000;
7
7
  export { HOOK_TOOL_NAMES, hookConfigPath } from "./provider-adapters.js";
8
8
  export { EXEC_TIMEOUT_MS, EXEC_TIMEOUT_QUICK_MS, PhrenError, phrenOk, phrenErr, forwardErr, parsePhrenErrorCode, isRecord, withDefaults, FINDING_TYPES, FINDING_TAGS, KNOWN_OBSERVATION_TAGS, DOC_TYPES, capCache, RESERVED_PROJECT_DIR_NAMES, } from "./phren-core.js";
9
- export { ROOT_MANIFEST_FILENAME, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, lookupEventsLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, projectSlugFromPath, canonicalProjectKey, findProjectNameCaseInsensitive, findProjectNamesByCanonicalKey, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, ensurePrivateDir, ftsCacheRoot, ensureFtsCacheRootPrivate, } from "./phren-paths.js";
9
+ export { ROOT_MANIFEST_FILENAME, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, lookupEventsLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, projectSlugFromPath, canonicalProjectKey, findProjectNameCaseInsensitive, findProjectNamesByCanonicalKey, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, nativeMemoryEnabled, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, ensurePrivateDir, ftsCacheRoot, ensureFtsCacheRootPrivate, } from "./phren-paths.js";
10
10
  export { PROACTIVITY_LEVELS, parseProactivityLevel, getProactivityLevel, getProactivityLevelForFindings, getProactivityLevelForTask, hasExplicitFindingSignal, hasExplicitTaskSignal, hasExecutionIntent, hasDiscoveryIntent, shouldAutoCaptureFindingsForLevel, shouldAutoCaptureTaskForLevel, } from "./proactivity.js";
11
11
  const MEMORY_SCOPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
12
12
  export function normalizeMemoryScope(scope) {