@phren/cli 0.1.52 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,8 @@
1
1
  import { getPhrenPath, readRootManifest } from "../shared.js";
2
2
  import { listMachines as listMachinesStore, listProfiles as listProfilesStore } from "../data/access.js";
3
3
  import { setTelemetryEnabled, getTelemetrySummary, resetTelemetry } from "../telemetry.js";
4
+ import { readInstallPreferences, updateInstallPreferences } from "../init/preferences.js";
5
+ import { resolveMcpProfile } from "../mcp/profile.js";
4
6
  import * as path from "path";
5
7
  import { buildConfigView } from "../config/resolve.js";
6
8
  import { CONFIG_DOMAINS } from "../config/schema.js";
@@ -115,6 +117,8 @@ export async function handleConfig(args) {
115
117
  return handleConfigProfiles();
116
118
  case "telemetry":
117
119
  return handleConfigTelemetry(rest);
120
+ case "mcp-profile":
121
+ return handleConfigMcpProfile(rest);
118
122
  case "proactivity":
119
123
  case "proactivity.findings":
120
124
  case "proactivity.tasks":
@@ -201,6 +205,30 @@ function handleConfigProfiles() {
201
205
  console.log(" (no projects)");
202
206
  }
203
207
  }
208
+ function handleConfigMcpProfile(args) {
209
+ const phrenPath = getPhrenPath();
210
+ const want = args[0]?.trim().toLowerCase();
211
+ if (want === "core" || want === "full") {
212
+ updateInstallPreferences(phrenPath, () => ({ mcpProfile: want }));
213
+ console.log(`MCP profile set to ${want}. Restart your MCP clients (Claude Code, Cursor, …) to pick it up.`);
214
+ if (want === "core")
215
+ console.log("Agents see 10 tools; everything else is reachable through phren_admin.");
216
+ else
217
+ console.log("Agents see every tool by name, plus the revise_finding / manage_task / session composites.");
218
+ return;
219
+ }
220
+ if (want) {
221
+ console.error(`Unknown profile "${args[0]}". Use core or full.`);
222
+ process.exitCode = 1;
223
+ return;
224
+ }
225
+ const current = resolveMcpProfile(phrenPath);
226
+ const source = process.env.PHREN_MCP_PROFILE ? "PHREN_MCP_PROFILE" : (readInstallPreferences(phrenPath).mcpProfile ? "install preferences" : "default");
227
+ console.log(`MCP profile: ${current} (${source})`);
228
+ console.log(current === "core"
229
+ ? "10 tools: search_knowledge, get_memory_detail, get_project_summary, add_finding, revise_finding, get_tasks, add_task, manage_task, session, phren_admin."
230
+ : "Every tool by name. `phren config mcp-profile core` for the compact surface.");
231
+ }
204
232
  function handleConfigTelemetry(args) {
205
233
  const action = args[0];
206
234
  switch (action) {
package/dist/cli/hooks.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // cli-hooks-output.ts — hook output formatting
6
6
  // cli-hooks-globs.ts — project glob matching
7
7
  import { debugLog, sessionMarker, sessionsDir, getPhrenPath, } from "../shared.js";
8
- import { mergeConfig, } from "../shared/governance.js";
8
+ import { mergeConfig, recordLookupEvents } from "../shared/governance.js";
9
9
  import { loadIndexForHook, detectProject, } from "../shared/index.js";
10
10
  import { isProjectHookEnabled } from "../project-config.js";
11
11
  import { checkConsolidationNeeded, } from "../shared/content.js";
@@ -37,6 +37,7 @@ import { getGitContext, trackSessionMetrics, } from "./hooks-session.js";
37
37
  import { approximateTokens, SNIPPET_OVERHEAD_TOKENS } from "../shared/retrieval.js";
38
38
  import { resolveRuntimeProfile } from "../runtime-profile.js";
39
39
  import { handleTaskPromptLifecycle } from "../task/lifecycle.js";
40
+ import { bestFindingNodeId } from "../finding-graph-id.js";
40
41
  // Auto-learn from prompts was removed — it learned conversational noise ("bro", "idk", typos)
41
42
  // as synonyms for high-frequency terms. Manual `phren config synonyms add` still works.
42
43
  // Future: finding-based co-occurrence mining (phren maintain command, not live hook).
@@ -227,6 +228,35 @@ export async function handleHookPrompt() {
227
228
  budgetUsedTokens = runningTokens;
228
229
  debugLog(`injection-budget: trimmed ${selected.length} -> ${kept.length} snippets to fit ${maxInjectTokens} token budget`);
229
230
  }
231
+ // Live activity: what a prompt pulled in is a recall as much as a search
232
+ // hit is, and it is by far the most common kind. Recording it here is what
233
+ // lets the terminal graph's watch mode, and anything else tailing the log,
234
+ // light up while an agent works. Best-effort: logging must never break
235
+ // the hook.
236
+ try {
237
+ const at = new Date().toISOString();
238
+ // The prompt, not the expanded keyword string: the feed shows this to a
239
+ // person, and "retry retry backoff backoff jitter" is not what they asked.
240
+ const asked = prompt.replace(/\s+/g, " ").trim().slice(0, 160);
241
+ recordLookupEvents(getPhrenPath(), budgetSelected.map((s) => {
242
+ const nodeId = s.doc.type === "findings" ? bestFindingNodeId(s.doc.project, s.doc.content, keywords) : null;
243
+ return {
244
+ at,
245
+ query: asked,
246
+ project: s.doc.project,
247
+ filename: s.doc.filename,
248
+ type: s.doc.type,
249
+ path: s.doc.path,
250
+ snippet: s.snippet,
251
+ source: "hook",
252
+ ...(nodeId ? { nodeId } : {}),
253
+ ...(sessionId ? { session: sessionId } : {}),
254
+ };
255
+ }));
256
+ }
257
+ catch (err) {
258
+ debugLog(`hook-prompt lookup-events: ${errorMessage(err)}`);
259
+ }
230
260
  const parts = buildHookOutput(budgetSelected, budgetUsedTokens, intent, gitCtx, detectedProject, stage, safeTokenBudget, getPhrenPath(), sessionId);
231
261
  const taskLevel = resolvedConfig.proactivity.tasks
232
262
  ?? resolvedConfig.proactivity.base
@@ -94,6 +94,7 @@ const CONFIG_SUBCOMMANDS = [
94
94
  { name: "machines", usage: "phren config machines", summary: "Registered machines" },
95
95
  { name: "profiles", usage: "phren config profiles", summary: "Profiles and projects" },
96
96
  { name: "telemetry", usage: "phren config telemetry [on|off]", summary: "Opt-in usage telemetry" },
97
+ { name: "mcp-profile", usage: "phren config mcp-profile [core|full]", summary: "MCP tool surface: 10 core tools or all of them" },
97
98
  ];
98
99
  const MAINTAIN_SUBCOMMANDS = [
99
100
  { name: "govern", usage: "phren maintain govern [project]", summary: "Queue stale memories for review" },
@@ -101,8 +101,12 @@ export const DEFAULT_WORKFLOW_POLICY = {
101
101
  /** Default index policy. Exported so {@link config/schema} can render one source of truth. */
102
102
  export const DEFAULT_INDEX_POLICY = {
103
103
  schemaVersion: GOVERNANCE_SCHEMA_VERSION,
104
- includeGlobs: ["**/*.md", "**/skills/**/*.md", ".claude/skills/**/*.md"],
105
- excludeGlobs: ["**/.git/**", "**/node_modules/**", "**/dist/**", "**/build/**"],
104
+ // Skills are instructions you invoke by name, not knowledge to retrieve:
105
+ // indexed, they crowd the findings out of a prompt's context budget (nine of
106
+ // twelve injections in one session were skill files). They stay reachable
107
+ // through list_skills and the global CLAUDE.md.
108
+ includeGlobs: ["**/*.md"],
109
+ excludeGlobs: ["**/.git/**", "**/node_modules/**", "**/dist/**", "**/build/**", "**/skills/**", "**/.claude/skills/**"],
106
110
  includeHidden: false,
107
111
  };
108
112
  const DEFAULT_RUNTIME_HEALTH = {
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";
@@ -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
  }